feat: integrate native BPM task processing and strict Excel test rules
This commit is contained in:
commit
8cb6a32876
444 files changed
+17045
-3182
No files matched your search
@@ -0,0 +1,24 @@
|
||||
'use strict';
|
||||
function canReadConnection(workspace,user,id){
|
||||
if(!user)return false;if(user.role==='admin')return true;if(!id||!user.username)return false;
|
||||
try{const sources=workspace?.recordSources?.()||workspace?.connectionSources?.();const c=sources?sources.find(c=>c.id===id):workspace?.getConnection?.(id);return !!c?.owner&&c.owner===user.username;}catch{return false;}
|
||||
}
|
||||
const canReadOrder=(workspace,user,order)=>!!order&&canReadConnection(workspace,user,order.sample?.connectionId||order.event?.connectionId||order.connectionId);
|
||||
function canReadBatch(workspace,user,batch,store){if(!user||!batch)return false;if(user.role==='admin')return true;return Array.isArray(batch.orderIds)&&batch.orderIds.length>0&&batch.orderIds.every(id=>canReadOrder(workspace,user,store.get('orders',id)));}
|
||||
function publicOrder(order){if(!order)return null;const value=structuredClone(order);delete value.sample;delete value.trace;if(value.event){delete value.event.fields;delete value.event.raw;}return value;}
|
||||
function canReadIssue(store,workspace,user,issue){
|
||||
if(user?.role==='admin')return true;
|
||||
const orders=issue.orderIds||[],tasks=issue.taskIds||[];
|
||||
if(!orders.length&&!tasks.length)return false;
|
||||
return orders.every(id=>canReadOrder(workspace,user,store.get('orders',id)))
|
||||
&&tasks.every(id=>canReadConnection(workspace,user,store.get('execution-tasks',id)?.connectionId));
|
||||
}
|
||||
function publicSnapshot(store,workspace,user){
|
||||
const value=store.snapshot();
|
||||
value.orders=value.orders.filter(order=>canReadOrder(workspace,user,order)).map(publicOrder);
|
||||
value.batches=value.batches.filter(batch=>canReadBatch(workspace,user,batch,store));
|
||||
value.issues=(store.all?.('business-issues')||[]).filter(issue=>canReadIssue(store,workspace,user,issue));
|
||||
if(user?.role!=='admin')value.audit=[];
|
||||
return value;
|
||||
}
|
||||
module.exports={canReadConnection,canReadOrder,canReadBatch,publicOrder,publicSnapshot};
|
||||
@@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
const {fail,validateRule}=require('./validation.cjs');
|
||||
const {checkTemplates}=require('./template-validation.cjs');
|
||||
async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,reply,response}){
|
||||
if(route!=='/api/order-rules'&&!route.startsWith('/api/order-rules/'))return false;
|
||||
if(!orderRules)fail('分类通知规则服务未启动。',503);
|
||||
if(route==='/api/order-rules'&&method==='GET'){const snapshot=require('./access.cjs').publicSnapshot(orderRules,workspace,user);if(Array.isArray(snapshot.rules))snapshot.rules=snapshot.rules.map(rule=>({huizhouEnabled:false,huizhouTemplateId:'',...rule}));reply(200,snapshot);return true;}
|
||||
if(route==='/api/order-rules/import-template'&&method==='GET'){
|
||||
if(user.role!=='admin')fail('仅管理员可导出规则配置。',403);
|
||||
const bytes=await require('./import-template.cjs').template(orderRules);response.writeHead(200,{'Content-Type':'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet','Content-Disposition':"attachment; filename*=UTF-8''"+encodeURIComponent('分类规则.xlsx')});response.end(bytes);return true;
|
||||
}
|
||||
if(method!=='POST')fail('没有找到此规则操作。',404);
|
||||
if(user.role==='viewer')fail('只读成员不能编辑规则或提交样本。',403);
|
||||
const actor=user.username;
|
||||
const migration=/^\/api\/order-rules\/rules\/([\w-]+)\/migration\/(preview|apply)$/.exec(route);
|
||||
if(migration){if(user.role!=='admin')fail('仅管理员可迁移规则。',403);if(!body||Object.keys(body).some(k=>!['version','idempotencyKey','note'].includes(k)))fail('迁移参数无效。');reply(200,orderRules[migration[2]==='preview'?'previewMigration':'applyMigration'](migration[1],body,actor));return true;}
|
||||
const trial=/^\/api\/order-rules\/rules\/([\w-]+)\/trial$/.exec(route);
|
||||
if(trial){
|
||||
if(body?.draft&&user.role!=='admin')fail('仅管理员可试运行编辑中的规则草稿。',403);
|
||||
if(body&&Object.hasOwn(body,'sampleId')&&(typeof body.sampleId!=='string'||!body.sampleId.trim()||body.sampleId.length>200))fail('真实采集样本标识无效。');
|
||||
if(body?.sampleId){const captured=orderRules.get('capture-samples',body.sampleId);if(!captured)fail('真实采集样本不存在。',404);if(user.role!=='admin'&&workspace?.getConnection(captured.sample.connectionId)?.owner!==user.username)fail('仅连接负责人或管理员可试运行此采集样本。',403);}
|
||||
reply(200,orderRules.trial(trial[1],body));return true;
|
||||
}
|
||||
if(route==='/api/order-rules/preview'||route==='/api/order-rules/events'){
|
||||
if(route.endsWith('/events'))fail('客户端事件写入已退役,请通过授权待办扫描创建任务。',410);
|
||||
if(!body||Object.keys(body).some(k=>!['sample','sampleId'].includes(k)))fail('请提供 BPM 样本或服务端采集标识。');
|
||||
if(body.sampleId){if(typeof body.sampleId!=='string'||body.sample)fail('真实试运行只接受服务端采集标识。');const captured=orderRules.get('capture-samples',body.sampleId);if(!captured)fail('真实采集样本不存在。',404);if(user.role!=='admin'&&workspace?.getConnection(captured.sample.connectionId)?.owner!==user.username)fail('仅连接负责人或管理员可试运行此采集样本。',403);reply(200,orderRules.capturedPreview(body.sampleId));}
|
||||
else {if(!body.sample||typeof body.sample!=='object'||Array.isArray(body.sample))fail('请提供 BPM 样本对象。');reply(200,orderRules.previewUntrusted(body.sample));}return true;
|
||||
}
|
||||
if(user.role!=='admin')fail('仅管理员可维护规则、批次与发送设置。',403);
|
||||
let result;
|
||||
if(route==='/api/order-rules/restricted-test'){
|
||||
if(body?.enabled){const channelId=orderRules.restrictedTest()?.channelId||body.channelId;if(!mail?.store.publicChannel(channelId)?.state.smtp)fail('请先验证测试发件邮箱SMTP。',409);for(const record of orderRules.all('rules'))if(!body.ruleIds||body.ruleIds.includes(record.id))checkTemplates(mail,orderRules.executionRule(record)||record.draft);}
|
||||
result=orderRules.saveRestrictedTest(body,user);
|
||||
}
|
||||
else if(route==='/api/order-rules/import/preview')result=require('./import.cjs').previewImport(orderRules,body,actor);
|
||||
else if(route==='/api/order-rules/import/commit')result=require('./import.cjs').commitImport(orderRules,body,actor,{mail});
|
||||
else if(route==='/api/order-rules/rules'){
|
||||
const old=orderRules.get('rules',body?.id)?.draft;
|
||||
if(old)checkTemplates(mail,validateRule(body,old));
|
||||
result=orderRules.saveRule(body,actor);
|
||||
}
|
||||
else if(route==='/api/order-rules/settings'){
|
||||
if(body?.enabled){if(!mail)fail('发件邮箱服务未启动。',409);const channel=mail.store.publicChannel(body.channelId);if(!channel.state.smtp)fail('请先验证发件邮箱 SMTP。',409);}
|
||||
result=orderRules.saveSettings(body,actor);
|
||||
}else if(route==='/api/order-rules/prepare'){
|
||||
if(!body||Object.keys(body).some(k=>k!=='cutoff'))fail('请提供发送截止时间。');
|
||||
const window=orderRules.snapshot().window;
|
||||
if(!window?.available||Date.parse(body.cutoff)!==Date.parse(window.end))fail('仅能在配置的发送时点整理本时段订单;更早历史不补发。',409);
|
||||
result=orderRules.prepare(body.cutoff,actor,window);
|
||||
}else{
|
||||
const rule=/^\/api\/order-rules\/rules\/([\w-]+)\/(publish|pause|resume)$/.exec(route);
|
||||
const batch=/^\/api\/order-rules\/batches\/([\w-]+)\/resolve$/.exec(route);
|
||||
const recheck=/^\/api\/order-rules\/orders\/([\w-]+)\/recheck$/.exec(route);
|
||||
if(rule){if(!body||Object.keys(body).some(k=>!['version','publishedVersion','activationVersion'].includes(k)))fail('请提供当前规则和启停版本。');const record=orderRules.get('rules',rule[1]);if(rule[2]==='publish'){if(!record?.trialSampleId||!orderRules.get('capture-samples',record.trialSampleId))fail('发布前必须选择服务端真实采集样本完成试运行。',409);}
|
||||
if(rule[2]!=='pause'){const selected=rule[2]==='resume'?record?.published:record?.draft;checkTemplates(mail,selected);}
|
||||
result=orderRules[rule[2]](rule[1],body,actor);}
|
||||
else if(batch){if(!body||Object.keys(body).some(k=>!['version','idempotencyKey','resolution','note'].includes(k)))fail('核验内容无效。');result=orderRules.resolve(batch[1],body,actor,{controlled:true});}
|
||||
else if(recheck){if(!body||Object.keys(body).some(k=>k!=='note'))fail('重新识别内容无效。');result=orderRules.recheck(recheck[1],body,actor);}
|
||||
else fail('没有找到此规则操作。',404);
|
||||
}
|
||||
workspace?.record(user,'维护分类通知规则',route.slice('/api/order-rules'.length));reply(200,result);return true;
|
||||
}
|
||||
module.exports={orderRuleApi};
|
||||
@@ -0,0 +1,70 @@
|
||||
'use strict';
|
||||
const path=require('node:path');
|
||||
const {mailContent}=require('./mail-content.cjs');
|
||||
const fail=message=>{throw Object.assign(new Error(message),{status:409});};
|
||||
const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
||||
const lines=value=>escape(value).replace(/\r?\n/g,'<br>');
|
||||
|
||||
function recipients(values,label){
|
||||
if(!Array.isArray(values))fail(`${label}邮箱名单无效。`);
|
||||
const result=[];
|
||||
for(const value of values){
|
||||
if(typeof value!=='string'||/[\r\n\x00-\x1f\x7f]/.test(value))fail(`${label}邮箱地址无效。`);
|
||||
const address=value.trim().toLowerCase();
|
||||
const parts=address.split('@'),local=parts[0],domain=parts[1];
|
||||
if(parts.length!==2||address.length>254||!local||local.length>64||!domain||!domain.includes('.')||!/^[-a-z0-9!#$%&'*+/=?^_`{|}~.]+$/i.test(local)||local.startsWith('.')||local.endsWith('.')||local.includes('..')||domain.split('.').some(p=>!p||p.length>63||! /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(p)))fail(`${label}邮箱地址无效。`);
|
||||
if(!result.includes(address))result.push(address);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function validFile(file){
|
||||
return file&&typeof file.name==='string'&&file.name.length>0&&!/[\r\n\x00-\x1f]/.test(file.name)&&typeof file.path==='string'&&!/[\r\n\x00-\x1f]/.test(file.path)&&(path.isAbsolute(file.path)||path.win32.isAbsolute(file.path))&&!/^[a-z]+:\/\//i.test(file.path)&&/^[a-f\d]{64}$/i.test(file.sha256)&&Number.isSafeInteger(file.size)&&file.size>=0&&['pdf','notice'].includes(file.kind);
|
||||
}
|
||||
|
||||
function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window,notificationMode='normal',store}={}){
|
||||
const limit=Date.parse(cutoff);
|
||||
if(!Number.isFinite(limit)||!Number.isSafeInteger(maxMessageBytes)||maxMessageBytes<1)fail('截止时间或邮件大小设置无效。');
|
||||
const start=window?Date.parse(window.start):null,end=window?Date.parse(window.end):null;
|
||||
if(window&&(!Number.isFinite(start)||!Number.isFinite(end)||start>=end||end!==limit||window.startInclusive!==true||window.endInclusive!==false))fail('邮件时段窗口无效。');
|
||||
if(!rule?.categoryId||!Array.isArray(orders)||!orders.length)fail('类别必须包含待发订单。');
|
||||
if(rule.attachPdf===true)fail('业务通知禁止附件,请先将类别 attachPdf 设置为 false;PDF 归档仍为前置条件。');
|
||||
const to=recipients(rule.to,'收件人'),cc=recipients(rule.cc||[],'抄送人').filter(a=>!to.includes(a));
|
||||
if(!to.length)fail('收件人名单不能为空。');
|
||||
const orderIds=[],attachments=[];
|
||||
for(const order of orders){
|
||||
if(!order?.id||orderIds.includes(order.id))fail('订单标识无效或重复。');
|
||||
if(order.ruleSnapshot?.categoryId!==rule.categoryId)fail('同一批次不能混合类别。');
|
||||
if(order.ruleSnapshot.id!==rule.id||order.ruleSnapshot.version!==rule.version)fail('同一类别包含不同规则版本,请核实后处理。');
|
||||
const binding=notificationMode==='huizhou'?'huizhouTemplateId':'bodyTemplateId';
|
||||
if(order.ruleSnapshot[binding]!==rule[binding])fail('同一批次不能混合不同模板绑定。');
|
||||
if(order.status&&order.status!=='pending')fail('此类别包含未准备完成的订单。');
|
||||
const received=Date.parse(store?require('./restricted-test.cjs').orderTime(store,order):order.event?.receivedAt);
|
||||
if(window&&(store?!require('./restricted-test.cjs').orderInWindow(store,order,window):!Number.isFinite(received)||received<start||received>=end))fail('订单接收时间不属于本批时段窗口。');
|
||||
if(!Number.isFinite(received)||received>limit)fail('订单接收时间超出本批截止范围。');
|
||||
const number=order.event?.orderNo;
|
||||
if(typeof number!=='string'||!number.trim()||/[\r\n\x00-\x1f]/.test(number))fail('订单号无效。');
|
||||
if(!order.archive||!Number.isFinite(Date.parse(order.archive.archivedAt))||!Array.isArray(order.archive.files)||!order.archive.files.length)fail(`订单 ${number} 缺少归档证据,本类别已阻塞。`);
|
||||
if(order.archive.files.some(file=>!validFile(file)))fail(`订单 ${number} 的归档文件证据无效。`);
|
||||
if(!order.archive.files.some(file=>file.kind==='pdf'&&/\.pdf$/i.test(file.name)))fail(`订单 ${number} 缺少必需 PDF,本类别已阻塞。`);
|
||||
orderIds.push(order.id);
|
||||
}
|
||||
const prefix=String(rule.subjectPrefix||rule.name||'订单通知');
|
||||
if(/[\r\n\x00-\x1f]/.test(prefix))fail('邮件标题无效。');
|
||||
const content=mailContent(orders),orderNos=content.orderNos;
|
||||
const snapshot={categoryId:rule.categoryId,subject:`${prefix} ${orderNos.join('、')}`,to,cc,orderIds,orderNos,attachments,cutoff:new Date(limit).toISOString()};
|
||||
snapshot.notificationMode=notificationMode;
|
||||
{
|
||||
snapshot.text=[rule.intro,content.details,notificationMode==='huizhou'?'':'存放地址:'+content.directories.join('\n'),rule.signature].filter(Boolean).join('\n\n');
|
||||
snapshot.html='<div>'+lines(rule.intro)+'</div>'+content.htmlDetails+(notificationMode==='huizhou'?'':content.htmlDirectories)+'<div>'+lines(rule.signature)+'</div>';
|
||||
}
|
||||
if(window){snapshot.window=structuredClone(window);snapshot.windowStart=new Date(start).toISOString();snapshot.windowEnd=new Date(end).toISOString();}
|
||||
// MIME headers, encoded-word subjects, base64 wrapping, attachment metadata and
|
||||
// boundary overhead are intentionally overestimated rather than truncating.
|
||||
const encodedBytes=size=>Math.ceil(Math.ceil(size/3)*4/76)*78;
|
||||
let bytes=16384+encodedBytes(Buffer.byteLength(snapshot.subject+snapshot.text+snapshot.html,'utf8'))+Buffer.byteLength([...to,...cc].join(','))*4;
|
||||
for(const file of attachments)bytes+=encodedBytes(file.size)+4096+Buffer.byteLength(file.name,'utf8')*4;
|
||||
if(bytes>maxMessageBytes)fail(`本类别邮件大小超过容量限制(估计 ${bytes} 字节)。`);
|
||||
return snapshot;
|
||||
}
|
||||
module.exports={buildBatch};
|
||||
@@ -0,0 +1,83 @@
|
||||
'use strict';
|
||||
|
||||
// Public business classification only. Recipient and archive values belong in
|
||||
// the encrypted local store and are deliberately absent from this catalog.
|
||||
const rows = [
|
||||
['overseas-notice', '海外订单通知书', ['海外运营订单评审', '海外宽带接入产品订单', '海外IPC订单评审', '海外返工订单评审']],
|
||||
['overseas-change', '海外订单更改通知书', ['海外运营订单更改评审', '海外宽带接入产品订单更改评审', '海外IPC订单更改评审', '海外返工订单更改评审']],
|
||||
['new-retail-notice', '新零售订单通知书', ['新零售订单评审']],
|
||||
['new-retail-change', '新零售订单更改通知书', ['新零售订单更改评审']],
|
||||
['domestic-notice', '国内订单通知书', ['国内运营订单评审']],
|
||||
['carrier-notice', '运营商事业部订单通知书', ['宽带事业订单评审']],
|
||||
['hardware-notice', '智能硬件订单通知书', ['智能硬件解决方案订单评审']],
|
||||
['retail-notice', '小湃订单通知书', ['零售国内订单评审']],
|
||||
['domestic-change', '国内、运营商事业部、零售、智能硬件订单更改通知书', ['国内运营订单更改评审', '宽带事业订单更改评审', '智能硬件解决方案订单更改评审', '零售国内订单更改评审', '国内、宽带返工订单更改评审', '零售国内返工订单更改评审']],
|
||||
['domestic-rework', '国内、运营商事业部、零售、智能硬件返工订单通知书', ['国内、宽带返工订单评审', '零售国内返工订单评审']],
|
||||
['processing-notice', '加工订单通知书', ['加工订单评审']],
|
||||
['bs-notice', '备损订单通知书', ['备损订单评审']],
|
||||
['bs-change', '备损订单更改通知书', ['备损订单更改评审']],
|
||||
['trial-notice', '试产订单通知书', ['试产订单评审', '中试样机制作申请', '研发样机制作申请']],
|
||||
['trial-change', '试产订单更改通知书', ['试产订单更改评审']],
|
||||
];
|
||||
|
||||
function seedRules() {
|
||||
return rows.map(([id, name, processNames], index) => ({
|
||||
id, version: 1, status: 'paused', name, categoryId: id,
|
||||
processNames: [...processNames],
|
||||
nodeNames: id === 'processing-notice' ? ['订单专员(激活)']
|
||||
: id.startsWith('trial-') ? ['订单专员(订单通知书)-海外', '订单专员(订单通知书)']
|
||||
: ['订单专员(订单通知书)'],
|
||||
adapterIds: ['bs-change', 'overseas-change'].includes(id) ? [id] : [],
|
||||
archiveDirectory: '', filenameDate: '', subjectPrefix: `【${name}】`,
|
||||
intro: `大家好:\n以下为${name},请查收!`, signature: '', to: [], cc: [],
|
||||
attachPdf: false, sourceRow: index + 2,
|
||||
huizhouEnabled: false, huizhouTemplateId: '',
|
||||
}));
|
||||
}
|
||||
|
||||
const adapters = [
|
||||
{
|
||||
id: 'bs-change', label: '备损订单更改评审 v1.4(字段样本已核对)',
|
||||
processName: '备损订单更改评审', processVersion: '1.4', verified: true,
|
||||
verificationScope: '仅核对表单 DOM 字段结构;实时待办、PDF 与归档接口尚未验证。',
|
||||
fields: {
|
||||
orderNo: 'OFR_BS_Applicant.OrderNum', appDate: 'OFR_BS_Applicant.AppDate',
|
||||
customer: 'OFR_BS_BInfo.CustomerName', productLine: 'OFR_BS_Applicant.ProductLine',
|
||||
changeReason: 'OFR_BS_Applicant.ChangeReason', changeContent: 'OFR_BS_Applicant.OrderChangeContent',
|
||||
},
|
||||
sample: {
|
||||
demo: true, connectionId: 'demo-connection', source: 'todo', instanceId: 'DEMO-BS-INSTANCE',
|
||||
taskId: 'DEMO-BS-TASK', revision: 0, processName: '备损订单更改评审', processVersion: '1.4',
|
||||
nodeName: '订单专员(订单通知书)', receivedAt: '2026-10-19T09:00:00+08:00',
|
||||
serialNum: 'DEMO-SERIAL-001', brief: '演示数据:备损订单更改,非真实业务记录。',
|
||||
fields: {
|
||||
'OFR_BS_Applicant.OrderNum': 'DEMO-BS-001', 'OFR_BS_Applicant.AppDate': '2026-10-19',
|
||||
'OFR_BS_BInfo.CustomerName': '演示客户', 'OFR_BS_Applicant.ProductLine': '演示产品线',
|
||||
'OFR_BS_Applicant.ChangeReason': '演示更改原因', 'OFR_BS_Applicant.OrderChangeContent': '演示更改内容',
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'overseas-change', label: '海外返工订单更改评审 v1.1(字段样本已核对)',
|
||||
processName: '海外返工订单更改评审', processVersion: '1.1', verified: true,
|
||||
verificationScope: '仅核对表单 DOM 字段结构;实时待办、PDF 与归档接口尚未验证。',
|
||||
fields: {
|
||||
orderNo: 'OFR_HWLS_Applicant.OrderNum', appDate: 'OFR_HWLS_Applicant.AppDate',
|
||||
customer: 'OFR_HWLS_BInfo.CustomerName', totalAmount: 'OFR_HWLS_BInfo.TotalAmount',
|
||||
changeReason: 'OFR_HWLS_Applicant.ChangeReason', changeContent: 'OFR_HWLS_Applicant.OrderChangeContent',
|
||||
},
|
||||
sample: {
|
||||
demo: true, connectionId: 'demo-connection', source: 'todo', instanceId: 'DEMO-OVERSEAS-INSTANCE',
|
||||
taskId: 'DEMO-OVERSEAS-TASK', revision: 0, processName: '海外返工订单更改评审', processVersion: '1.1',
|
||||
nodeName: '订单专员(订单通知书)', receivedAt: '2026-10-19T09:01:00+08:00',
|
||||
serialNum: 'DEMO-SERIAL-002', brief: '演示数据:海外返工订单更改,非真实业务记录。',
|
||||
fields: {
|
||||
'OFR_HWLS_Applicant.OrderNum': 'DEMO-OVERSEAS-001', 'OFR_HWLS_Applicant.AppDate': '2026-10-19',
|
||||
'OFR_HWLS_BInfo.CustomerName': '演示客户', 'OFR_HWLS_BInfo.TotalAmount': 0,
|
||||
'OFR_HWLS_Applicant.ChangeReason': '演示更改原因', 'OFR_HWLS_Applicant.OrderChangeContent': '演示更改内容',
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
module.exports = { seedRules, adapters };
|
||||
@@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
function modeOf(batch){return batch?.notificationMode||'normal';}
|
||||
function delivery(order,mode='normal'){
|
||||
if(!order)return null;
|
||||
return mode==='normal'?{status:order.status,batchId:order.batchId||null,error:order.error||null}:order.notifications?.huizhou||null;
|
||||
}
|
||||
function updateDelivery(order,mode,patch){
|
||||
if(mode==='normal')Object.assign(order,patch);
|
||||
else {if(!order.notifications?.huizhou)throw Error('惠州通知没有独立预留记录。');Object.assign(order.notifications.huizhou,patch);}
|
||||
return order;
|
||||
}
|
||||
function notifications(order){
|
||||
if(!order)return undefined;
|
||||
const h=delivery(order,'huizhou');
|
||||
return {normal:delivery(order),huizhou:h?{status:h.status,batchId:h.batchId||null,error:h.error||null,orderNos:[...(h.orderNos||[])],issues:[...(h.issues||[])]}:{status:'not_applicable',batchId:null,error:null,orderNos:[],issues:[]}};
|
||||
}
|
||||
function needsRuntimeCheck(order){return !!order?.archive&&(['pending','batched'].includes(order.status)||['pending','batched','blocked'].includes(delivery(order,'huizhou')?.status));}
|
||||
function reserved(order){return !!order?.batchId||!!delivery(order,'huizhou')?.batchId;}
|
||||
module.exports={modeOf,delivery,updateDelivery,notifications,needsRuntimeCheck,reserved};
|
||||
@@ -0,0 +1,147 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs/promises');
|
||||
const path=require('node:path');
|
||||
const crypto=require('node:crypto');
|
||||
const {nextSlots}=require('../../shared/schedule.cjs');
|
||||
const {windowForCutoff}=require('./window.cjs');
|
||||
const {fail}=require('./validation.cjs');
|
||||
const {modeOf,delivery,updateDelivery}=require('./delivery.cjs');
|
||||
function assertMailPolicy(batch){
|
||||
const blocked=message=>{throw Object.assign(new Error(message),{status:409,code:'MAIL_POLICY_BLOCKED'});};
|
||||
if(!Array.isArray(batch.to)||batch.to.length!==1||batch.to[0]!=='2639266652@qq.com'||!Array.isArray(batch.cc)||batch.cc.length)blocked('当前分类通知只允许固定 QQ 2639266652@qq.com,且不得抄送。');
|
||||
if(!Array.isArray(batch.attachments)||batch.attachments.length)blocked('当前分类通知禁止 PDF 或其他附件;旧冻结批次必须先核验处理。');
|
||||
}
|
||||
|
||||
function freeze(value){
|
||||
if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);}
|
||||
return value;
|
||||
}
|
||||
|
||||
class OrderRuleDispatcher{
|
||||
constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date(),providersReady=()=>false,attachmentReader,templateResolver}){
|
||||
this.store=store;this.mail=mail;this.settings=settings;this.calendar=calendar;this.clock=clock;this.providersReady=providersReady;
|
||||
this.running=null;this.stopped=false;this.schedule=null;this.timer=null;
|
||||
this.attachmentReader=attachmentReader;if(templateResolver)store.templateResolver=templateResolver;
|
||||
}
|
||||
ready(){
|
||||
const config=this.store.settings(),cap=this.store.snapshot().capabilities;
|
||||
return !this.stopped&&config.enabled===true&&this.providersReady()===true&&cap?.liveTodo===true&&cap?.pdfExport===true&&cap?.automaticArchive===true;
|
||||
}
|
||||
tick(now=this.clock()){
|
||||
if(this.stopped||this.running)return this.running||Promise.resolve();
|
||||
const task=this.perform(new Date(now));this.running=task;
|
||||
task.finally(()=>{if(this.running===task)this.running=null;}).catch(()=>{});
|
||||
return task;
|
||||
}
|
||||
async perform(now){
|
||||
for(const batch of this.store.snapshot().batches||[])if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。');
|
||||
if(!this.ready())return;
|
||||
const config=freeze(structuredClone(this.store.settings())),schedule=this.settings()?.schedule,calendar=this.calendar();
|
||||
if(!schedule?.times?.length)return;
|
||||
const signature=JSON.stringify([schedule,calendar]);
|
||||
if(!this.schedule||this.schedule.signature!==signature||now-Date.parse(this.schedule.next)>60000){const current=require('./window.cjs').upcomingWindow(now,schedule,calendar);this.schedule={signature,next:current?.available?current.end:nextSlots(schedule,now,1,calendar)[0]};}
|
||||
const cutoff=this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&now-Date.parse(cutoff)<=60000;
|
||||
const queued=(this.store.snapshot().batches||[]).some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
||||
if(!canPrepare&&!queued)return;
|
||||
try{await this.mail.exclusive(config.channelId,async()=>{
|
||||
if(!this.ready())return;
|
||||
if(canPrepare&&!this.store.discoveryBlockers(cutoff).length){const window=windowForCutoff(cutoff,schedule,calendar);this.store.prepare(cutoff,'系统调度',window);}
|
||||
// A frozen collection is immutable. Queue time is distinct from collection time.
|
||||
const batches=(this.store.snapshot().batches||[]).filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000);
|
||||
for(const batch of batches){if(!this.ready())break;
|
||||
let expected;try{expected=windowForCutoff(batch.cutoff,schedule,calendar);}catch{continue;}
|
||||
const legacyStart=new Date(Date.parse(batch.cutoff)+8*3600000).toISOString().slice(0,10)+'T00:00:00+08:00';
|
||||
if(!batch.window||batch.window.end!==expected.end||![Date.parse(expected.start),Date.parse(legacyStart)].includes(Date.parse(batch.window.start))||batch.window.startInclusive!==true||batch.window.endInclusive!==false)continue;
|
||||
if(batch.createdAt&&(Date.parse(batch.createdAt)>Date.parse(batch.cutoff)+60000||Date.parse(batch.createdAt)<Date.parse(batch.cutoff)))continue;if(await this.dispatch(freeze(structuredClone(batch)),config)===false)continue;}
|
||||
});}catch(error){this.store.recordIssue?.('dispatch:'+String(cutoff),{component:'mail',error:error.message,cutoff});if(error.status!==409)throw error;}
|
||||
// Keep the current slot during its collection allowance so repaired categories retry.
|
||||
if(cutoff&&this.clock()-Date.parse(cutoff)>60000)this.schedule={signature,next:nextSlots(schedule,this.clock(),1,calendar)[0]};
|
||||
}
|
||||
async attachments(batch,config){
|
||||
const result=[];let total=0;
|
||||
for(const file of batch.attachments||[]){
|
||||
if(!file||typeof file.path!=='string'||!(path.isAbsolute(file.path)||path.win32.isAbsolute(file.path))||/^[a-z]+:\/\//i.test(file.path)||!/^[a-f\d]{64}$/i.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0)throw Error('归档文件证据无效。');
|
||||
total+=file.size;
|
||||
if(total>(config.maxMessageBytes||20971520))throw Error('归档文件超过邮件大小限制。');
|
||||
if(!this.attachmentReader){const stat=await fs.stat(file.path);if(!stat.isFile()||stat.size!==file.size)throw Error('归档文件大小发生变化。');}
|
||||
const content=this.attachmentReader?await this.attachmentReader(file):await fs.readFile(file.path);
|
||||
if(!Buffer.isBuffer(content))throw Error('归档读取器未返回文件字节。');
|
||||
if(content.length!==file.size||crypto.createHash('sha256').update(content).digest('hex')!==file.sha256.toLowerCase())throw Error('归档文件校验失败。');
|
||||
result.push({filename:file.name,content,contentType:file.kind==='pdf'?'application/pdf':'application/octet-stream',contentDisposition:'attachment'});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
async dispatch(batch,config,{manual=false}={}){
|
||||
if(batch.status!=='prepared')return false;
|
||||
let transport,sending=false;
|
||||
try{
|
||||
assertMailPolicy(batch);
|
||||
require('./restricted-test.cjs').assertBatch(this.store,batch,config);
|
||||
if(batch.channelId&&batch.channelId!==config.channelId){
|
||||
this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return;
|
||||
}
|
||||
const attachments=await this.attachments(batch,config);
|
||||
if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>1800000)throw Error('冻结发送队列超过30分钟。');
|
||||
const channel=freeze(structuredClone(this.mail.store.channelSecret(config.channelId)));
|
||||
if(channel.readOnly)throw Error('只读邮箱不能用于分类通知发送。');
|
||||
transport=this.mail.smtpFactory(channel.smtp);
|
||||
this.mail.clients?.add(transport);
|
||||
await transport.verify();
|
||||
// Scan readiness may change while SMTP verification is pending. Keep this
|
||||
// unsent reservation recoverable instead of turning a scan barrier into failure.
|
||||
if(!manual&&(this.store.discoveryBlockers(batch.cutoff).length||this.store.batchIncomplete(batch)))return false;
|
||||
if(manual?this.stopped||!this.providersReady()||!this.store.providersReady():!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。');
|
||||
if(!manual&&this.clock().getTime()-Date.parse(batch.cutoff)>1800000)throw Error('冻结发送队列超过30分钟。');
|
||||
this.mail.store.guard(channel.id,channel.version);
|
||||
assertMailPolicy(batch);
|
||||
require('./restricted-test.cjs').assertBatch(this.store,batch,config);
|
||||
this.store.beginSending(batch.id,{manual});sending=true;
|
||||
const result=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((result?.accepted||[]).map(address=>String(address.address||address).toLowerCase()));
|
||||
const partial=result?.rejected?.length||[...batch.to,...batch.cc].some(address=>!accepted.has(address.toLowerCase()));
|
||||
this.store.finishSending(batch.id,partial?'unknown':'sent',partial?'部分收件人未被服务器接受,请核对邮件记录后处理。':'邮件服务器已接受全部收件人;最终送达请以邮件记录为准。');
|
||||
}catch(error){
|
||||
if(!sending&&!manual&&error.code==='DISCOVERY_INCOMPLETE')return false;
|
||||
const rejected=error.code==='EENVELOPE'&&error.command==='RCPT TO'&&Array.isArray(error.rejected)&&error.rejected.length>0&&(!error.accepted||error.accepted.length===0)&&[...batch.to,...batch.cc].every(address=>error.rejected.some(r=>String(r.address||r).toLowerCase()===address.toLowerCase()));
|
||||
this.store.finishSending(batch.id,sending&&!rejected?'unknown':'failed',sending&&!rejected?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='MAIL_POLICY_BLOCKED'?error.message:error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`);
|
||||
}finally{
|
||||
try{transport?.close?.();}finally{if(transport)this.mail.clients?.delete(transport);}
|
||||
}
|
||||
}
|
||||
async resend(id,input,actor){
|
||||
if(actor?.role!=='admin')fail('仅管理员可以人工补发。',403);
|
||||
if(this.stopped)fail('发送器正在关闭。',503);
|
||||
if(typeof input?.idempotencyKey!=='string'||!/^[\w:.-]{1,160}$/.test(input.idempotencyKey)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请填写有效幂等标识与至少5字补发依据。');
|
||||
const requestId=crypto.createHash('sha256').update(JSON.stringify([id,actor.username,input.idempotencyKey])).digest('hex');
|
||||
const inputHash=crypto.createHash('sha256').update(JSON.stringify([input.version,input.note])).digest('hex');
|
||||
const replay=record=>{if(record.inputHash!==inputHash)fail('此幂等标识已用于不同的补发请求。',409);return this.store.get('batches',record.batchId);};
|
||||
const prior=this.store.get('resend-requests',requestId);if(prior)return replay(prior);
|
||||
const original=this.store.get('batches',id);if(!original)fail('批次不存在。',404);
|
||||
require('./restricted-test.cjs').assertBatch(this.store,original,{...this.store.settings(),channelId:original.channelId});
|
||||
if(!original.channelId)fail('原批次未冻结发件邮箱,不能补发。',409);
|
||||
const operation=this.mail.exclusive(original.channelId,async()=>{
|
||||
const previous=this.store.get('resend-requests',requestId);if(previous)return replay(previous);
|
||||
const batch=this.store.transaction(()=>{
|
||||
const source=this.store.get('batches',id);if(input.version!==(source.version||1)||source.status!=='failed')fail('批次版本已变化,或发送结果尚未核验。',409);
|
||||
const root=source.rootBatchId||source.id;
|
||||
if(this.store.all('batches').some(b=>b.id!==source.id&&(b.rootBatchId||b.id)===root&&['sent','sending','unknown','prepared'].includes(b.status)))fail('此批次已发送、结果待核实或已有补发尝试。',409);
|
||||
if(source.orderIds.some(oid=>{const state=delivery(this.store.get('orders',oid),modeOf(source));return !state||['sent','unknown','batched','sending'].includes(state.status);}))fail('原订单关联已发送或结果待核实。',409);
|
||||
const next={...structuredClone(source),id:crypto.randomUUID(),version:1,parentBatchId:source.id,rootBatchId:root,status:'prepared',manual:true,createdAt:this.clock().toISOString(),error:null,resolution:null,finishedAt:null,resend:{actor:actor.username,note:input.note.trim(),at:this.clock().toISOString()}};
|
||||
this.store.put('batches',next);for(const oid of next.orderIds){const o=this.store.get('orders',oid);updateDelivery(o,modeOf(next),{batchId:next.id,status:'batched',error:null});this.store.put('orders',o);}
|
||||
this.store.put('resend-requests',{id:requestId,batchId:next.id,inputHash});this.store.audit(actor.username,'人工补发冻结分类邮件',source.id+':'+input.note.trim());return next;
|
||||
});
|
||||
await this.dispatch(freeze(structuredClone(batch)),{...this.store.settings(),channelId:batch.channelId},{manual:true});return this.store.get('batches',batch.id);
|
||||
});
|
||||
this.manualOperations??=new Set();this.manualOperations.add(operation);try{return await operation;}finally{this.manualOperations.delete(operation);}
|
||||
}
|
||||
start(){
|
||||
if(this.timer||this.stopped)return;
|
||||
this.timer=setInterval(()=>this.tick().catch(error=>this.store.recordIssue?.('dispatcher-background',{component:'mail',error:error.message})),30000);this.timer.unref?.();
|
||||
}
|
||||
async stop(){
|
||||
this.stopped=true;clearInterval(this.timer);this.timer=null;
|
||||
if(this.running)await this.running.catch(()=>{});
|
||||
await Promise.allSettled([...(this.manualOperations||[])]);
|
||||
}
|
||||
}
|
||||
module.exports={OrderRuleDispatcher};
|
||||
@@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
const path=require('node:path');
|
||||
const {publicationIssues}=require('./validation.cjs');
|
||||
const {archiveFilename}=require('../storage/order-filename.cjs');
|
||||
const {buildBatch}=require('./batch.cjs'),{applyBodyTemplate}=require('./template.cjs');
|
||||
const {initialNotification,ordersForMode}=require('./huizhou.cjs');
|
||||
function previewEffects(rule,event,store){
|
||||
const hui=initialNotification(rule,event);
|
||||
const result={simulation:true,archiveVerified:false,filename:null,path:null,mail:null,issues:publicationIssues(rule,store.adapters()),provisionalDate:rule.filenameDate==='archiveDate',notifications:{normal:{status:'blocked',mail:null,issues:[]},huizhou:{status:hui.status,mail:null,orderNos:hui.orderNos,issues:hui.issues}}};
|
||||
try{
|
||||
const at=rule.filenameDate==='appDate'?event.appDate:rule.filenameDate==='receivedAt'?event.receivedAt:store.now();
|
||||
result.filename=archiveFilename(event,rule.filenameDate,at);
|
||||
if(!/^\\\\[^\\]+\\[^\\]+/.test(rule.archiveDirectory))return result;
|
||||
result.path=path.win32.join(rule.archiveDirectory,result.filename);
|
||||
// Planning metadata exists only in this stack frame, never as archive evidence.
|
||||
const file={name:result.filename,path:result.path,size:0,sha256:'0'.repeat(64),kind:'pdf'};
|
||||
const order={id:'simulation',event,ruleSnapshot:rule,status:'pending',archive:{archivedAt:store.now(),files:[file]}};
|
||||
const cutoff=new Date(Math.max(Date.parse(event.receivedAt),Date.parse(store.now()))).toISOString();
|
||||
for(const mode of ['normal','huizhou']){
|
||||
if(mode==='huizhou'&&hui.status!=='pending')continue;
|
||||
try{
|
||||
const orders=ordersForMode([order],mode),snapshot=applyBodyTemplate(buildBatch(rule,orders,cutoff,{maxMessageBytes:store.settings().maxMessageBytes,notificationMode:mode}),store.templateResolver?.(rule.categoryId,rule,mode),orders,store.settings().maxMessageBytes);
|
||||
const mail={subject:snapshot.subject,text:snapshot.text,to:snapshot.to,cc:snapshot.cc,attachments:snapshot.attachments.map(f=>f.name),template:snapshot.template||null};
|
||||
result.notifications[mode]={...result.notifications[mode],status:'ready',mail};if(mode==='normal')result.mail=mail;
|
||||
}catch(error){result.notifications[mode].status='blocked';result.notifications[mode].issues.push(error.message);if(mode==='normal')result.issues.push(error.message);}
|
||||
}
|
||||
}catch(error){result.issues.push(error.message);}
|
||||
return result;
|
||||
}
|
||||
module.exports={previewEffects};
|
||||
@@ -0,0 +1,91 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const {fail}=require('./validation.cjs');
|
||||
const {BUSINESS_FIELDS,METADATA_FIELDS,sourcesFor}=require('./field-sources.cjs');
|
||||
const {previewMatch}=require('./matching.cjs');
|
||||
const {archiveFilename}=require('../storage/order-filename.cjs');
|
||||
const hash=v=>crypto.createHash('sha256').update(JSON.stringify(v)).digest('hex');
|
||||
const mappingId=(name,version)=>'captured-'+hash([name,version]).slice(0,24);
|
||||
const admin=actor=>{if(actor?.role!=='admin'||!actor.username)fail('仅管理员可以维护信息识别配置。',403);};
|
||||
function shape(input,keys){if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!keys.includes(k)))fail('信息识别配置参数无效。');}
|
||||
function evidence(store,id,processName,processVersion){const c=store.get('capture-samples',id);if(!c||c.provenance!=='server-provider'||c.sample?.demo||c.processName!==processName||c.processVersion!==processVersion||!processVersion)fail('请选择流程和版本一致的服务端真实采集样本。',409);return c;}
|
||||
function categories(store,processName){return store.all('rules').filter(r=>r.draft.processNames.includes(processName)||r.published?.processNames.includes(processName));}
|
||||
function contextHash(store,draft){return hash(categories(store,draft.processName).map(r=>({id:r.id,version:r.draft.version,date:r.draft.filenameDate,scopes:r.draft.scopes,processNames:r.draft.processNames,nodeNames:r.draft.nodeNames})));}
|
||||
function operation(store,action,input,actor,work){admin(actor);if(typeof input?.idempotencyKey!=='string'||!/^[\w:.-]{1,160}$/.test(input.idempotencyKey))fail('请提供有效的操作幂等标识。');return store.transaction(()=>{const id=hash([actor.username,action,input.idempotencyKey]),signature=hash(input),old=store.get('field-mapping-requests',id);if(old){if(old.signature!==signature)fail('操作标识已用于不同的输入,请刷新后重新操作。',409);return old.result;}const result=work();store.put('field-mapping-requests',{id,signature,result,at:store.now()});return result;});}
|
||||
function validateSources(input,captured,{requireOrder=true}={}){
|
||||
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!BUSINESS_FIELDS.includes(k)&&!METADATA_FIELDS.includes(k)))fail('字段来源配置无效。');
|
||||
if((requireOrder||input.orderNo)&&input.orderNo?.type!=='form')fail('主订单号必须对应表单中的明确字段。');
|
||||
if(input.brief && input.brief.type!=='title')fail('通知摘要必须从标题提取全部订单段落。');
|
||||
const paths=new Set(captured.snapshot.fields.map(f=>f.path)),result={};
|
||||
for(const [key,source]of Object.entries(input)){
|
||||
if(!source||typeof source!=='object'||Array.isArray(source))fail('字段来源格式无效。');
|
||||
if(METADATA_FIELDS.includes(key)){if(source.type!=='metadata'||source.key!==key||Object.keys(source).some(k=>!['type','key'].includes(k)))fail('流程、节点、时间和流水号只能读取原始待办。');}
|
||||
else if(source.type==='form'){if(Object.keys(source).some(k=>!['type','path'].includes(k))||typeof source.path!=='string'||!paths.has(source.path))fail('请选择真实采集目录内的表单字段。');}
|
||||
else if(source.type==='title'){if(key!=='brief'||Object.keys(source).some(k=>k!=='type'))fail('标题订单提取仅用于通知摘要。');}
|
||||
else fail('请选择有效的字段来源,不支持脚本或表达式。');
|
||||
result[key]=structuredClone(source);
|
||||
}
|
||||
if(requireOrder&&result.orderNo?.type!=='form')fail('主订单号必须对应表单中的明确字段。');
|
||||
if(!result.brief)result.brief={type:'title'};
|
||||
if(result.quantity?.path&&result.quantity.path===result.totalAmount?.path)fail('数量和总金额不能对应同一个表单字段。');
|
||||
const labelFor=key=>captured.snapshot.fields.find(f=>f.path===result[key]?.path)?.label||'';
|
||||
if(/金额|单价|价格/.test(labelFor('quantity'))||/数量/.test(labelFor('totalAmount')))fail('数量和总金额不能混用,请核对真实字段标签。');
|
||||
for(const key of METADATA_FIELDS)result[key]={type:'metadata',key};
|
||||
return result;
|
||||
}
|
||||
function saveMapping(store,input,actor){shape(input,['processName','processVersion','sampleId','sources','version','idempotencyKey']);return operation(store,'save',input,actor,()=>{
|
||||
if(typeof input.processName!=='string'||!input.processName.trim()||input.processName.length>250||typeof input.processVersion!=='string'||!input.processVersion.trim()||input.processVersion.length>100||typeof input.sampleId!=='string')fail('流程、表单版本及真实订单不能为空。');
|
||||
const captured=evidence(store,input.sampleId,input.processName,input.processVersion),id=mappingId(input.processName,input.processVersion),old=store.get('field-mapping-drafts',id);
|
||||
if(input.version!==(old?.version||0))fail('识别配置草稿已变化,请刷新后重试。',409);
|
||||
const draft={id,processName:input.processName,processVersion:input.processVersion,sampleId:captured.id,sources:validateSources(input.sources,captured),version:(old?.version||0)+1,status:'draft',requestKey:input.idempotencyKey,check:null,updatedAt:store.now(),updatedBy:actor.username,activeVersion:store.get('field-adapters',id)?.version||null};
|
||||
store.put('field-mapping-drafts',draft);store.audit(actor.username,'保存信息识别草稿',id+' v'+draft.version);return draft;
|
||||
});}
|
||||
function evaluateMapping(store,draft,captured,{relatedRules}={}){
|
||||
const related=relatedRules||categories(store,draft.processName),needDate=related.some(r=>r.draft.filenameDate==='appDate'),mapping={id:draft.id,processName:draft.processName,processVersion:draft.processVersion,sources:draft.sources,verified:true};
|
||||
const rule={id:'mapping-check',name:'信息识别检查',categoryId:'mapping-check',version:draft.version,processNames:[draft.processName],nodeNames:[captured.sample.nodeName],adapterIds:[draft.id],filenameDate:needDate?'appDate':'receivedAt'};
|
||||
const result=previewMatch([rule],[mapping],captured.sample,{mappingEvidence:true});result.configurationOnly=captured.sample.source==='history';result.warnings=result.configurationOnly?['历史样本只核对字段,未核验通知节点;接收时间文件名示例暂用流程发起时间,实际执行须重新读取通知待办。']:[];result.affectedCategories=related.map(r=>({id:r.id,name:r.draft.name}));result.filenames=[];
|
||||
for(const r of related){const item={categoryId:r.id,categoryName:r.draft.name,filename:null,issues:[]};try{const at=r.draft.filenameDate==='appDate'?result.event.appDate:r.draft.filenameDate==='archiveDate'?store.now():result.event.receivedAt;item.filename=archiveFilename(result.event,r.draft.filenameDate,at);}catch(e){item.issues.push(e.message);}result.filenames.push(item);}
|
||||
return result;
|
||||
}
|
||||
function checkMapping(store,input,actor){shape(input,['id','version','sampleId','idempotencyKey']);return operation(store,'check',input,actor,()=>{
|
||||
const draft=store.get('field-mapping-drafts',input.id);if(!draft||draft.version!==input.version)fail('识别配置草稿已变化,请先保存当前草稿。',409);
|
||||
const captured=evidence(store,input.sampleId,draft.processName,draft.processVersion),result=evaluateMapping(store,draft,captured),check={id:crypto.randomUUID(),requestKey:input.idempotencyKey,version:draft.version,sampleId:captured.id,valid:result.valid,result,at:store.now(),actor:actor.username,draftHash:hash(draft.sources),evidenceHash:captured.evidenceHash,contextHash:contextHash(store,draft)};
|
||||
draft.check=check;store.put('field-mapping-drafts',draft);store.audit(actor.username,'检查信息识别结果',draft.id+' '+(check.valid?'通过':'受阻'));return check;
|
||||
});}
|
||||
function activateMapping(store,input,actor){shape(input,['id','version','checkId','idempotencyKey']);return operation(store,'activate',input,actor,()=>{
|
||||
const draft=store.get('field-mapping-drafts',input.id),check=draft?.check;
|
||||
if(!draft||draft.version!==input.version||!check||check.id!==input.checkId||!check.valid||check.version!==draft.version||check.draftHash!==hash(draft.sources)||check.contextHash!==contextHash(store,draft))fail('请重新检查当前识别草稿及关联分类,再确认使用。',409);
|
||||
const captured=evidence(store,check.sampleId,draft.processName,draft.processVersion);
|
||||
if(captured.evidenceHash!==check.evidenceHash||!evaluateMapping(store,draft,captured).valid)fail('真实样本证据已变化,请重新检查。',409);
|
||||
const old=store.get('field-adapters',draft.id),active={id:draft.id,version:(old?.version||0)+1,draftVersion:draft.version,label:draft.processName+' '+draft.processVersion+'(已核验)',processName:draft.processName,processVersion:draft.processVersion,sources:structuredClone(draft.sources),fields:Object.fromEntries(Object.entries(draft.sources).filter(([,s])=>s.type==='form').map(([k,s])=>[k,s.path])),verified:true,reference:false,sampleId:captured.id,evidenceHash:captured.evidenceHash,verifiedAt:store.now(),verifiedBy:actor.username,checkId:check.id};
|
||||
const previous=[...store.adapters(),...require('./catalog.cjs').adapters.map(a=>({...a,reference:true}))];
|
||||
for(const prior of previous.filter(a=>!a.reference&&a.processName===draft.processName&&a.processVersion===draft.processVersion)){
|
||||
store.put('field-mapping-history',{id:prior.id+':'+(prior.version||0),active:prior,replacedAt:store.now(),replacedBy:actor.username});
|
||||
if(prior.id!==active.id)store.put('field-adapters',{...prior,verified:false,status:'superseded',supersededBy:active.id});
|
||||
}
|
||||
store.put('field-adapters',active);
|
||||
for(const record of categories(store,draft.processName)){
|
||||
const ids=record.draft.adapterIds.filter(id=>!previous.some(a=>a.id===id&&a.processName===draft.processName&&a.processVersion===draft.processVersion));if(record.draft.processNames.includes(draft.processName))ids.push(active.id);
|
||||
if(JSON.stringify(ids)!==JSON.stringify(record.draft.adapterIds)){record.draft.adapterIds=[...new Set(ids)];record.draft.version++;}
|
||||
record.trialVersion=null;record.trialSampleId=null;record.trialDemo=null;record.mappingIssue='信息识别配置已更新,请重新检查并发布分类规则。';
|
||||
if(record.published?.processNames.includes(draft.processName)){record.published.status='paused';record.activationVersion=(record.activationVersion||0)+1;}
|
||||
store.put('rules',record);
|
||||
}
|
||||
draft.lastActivationKey=input.idempotencyKey;draft.activeVersion=active.version;draft.active=active;draft.status='verified';store.put('field-mapping-drafts',draft);store.audit(actor.username,'确认使用信息识别配置',active.id+' v'+active.version);return draft;
|
||||
});}
|
||||
function saveLegacy(store,input,actor){admin(actor);shape(input,['sampleId','processName','processVersion','fields','version','idempotencyKey']);const sources=sourcesFor({fields:input.fields});sources.brief={type:'title'};return saveMapping(store,{sampleId:input.sampleId,processName:input.processName,processVersion:input.processVersion,sources,version:input.version??0,idempotencyKey:input.idempotencyKey||'legacy-'+hash(input)},actor);}
|
||||
function directory(store,registry,samples){
|
||||
const allRules=store.all('rules'),drafts=store.all('field-mapping-drafts'),processNames=new Set(allRules.flatMap(r=>[...r.draft.processNames,...(r.published?.processNames||[])]));for(const s of samples)processNames.add(s.processName);
|
||||
return [...processNames].map(processName=>{
|
||||
const related=allRules.filter(r=>r.draft.processNames.includes(processName)||r.published?.processNames.includes(processName)),items=samples.filter(s=>s.processName===processName),versionNames=new Set([...items.map(s=>s.processVersion),...registry.filter(a=>a.processName===processName).map(a=>a.processVersion),...drafts.filter(d=>d.processName===processName).map(d=>d.processVersion)]);
|
||||
if(!versionNames.size)versionNames.add('');
|
||||
const versions=[...versionNames].map(processVersion=>{const sampleIds=items.filter(s=>s.processVersion===processVersion).map(s=>s.id),draft=drafts.find(d=>d.processName===processName&&d.processVersion===processVersion)||null,available=registry.filter(a=>a.processName===processName&&a.processVersion===processVersion),active=available.find(a=>!a.reference&&a.verified)||null,reference=available.find(a=>a.reference)||null;
|
||||
let status=!sampleIds.length?'未采集':!draft&&!active?'待配置':draft&&draft.version!==active?.draftVersion?'待检查':active?'已核验':'待检查';
|
||||
if(draft?.check&&draft.version!==active?.draftVersion)status=draft.check.valid?'检查通过':'检查未通过';
|
||||
if(sampleIds.length&&!active&®istry.some(a=>a.processName===processName&&!a.reference&&a.processVersion!==processVersion))status='版本变化';
|
||||
const duplicate=available.filter(a=>!a.reference).length>1;if(duplicate)status='待检查';
|
||||
return {processVersion,sampleIds,sampleCount:sampleIds.length,status,draft,active,reference,issues:[...(duplicate?['同一流程版本存在重复映射,请重新检查并确认使用唯一配置']:[]),...(!processVersion?['待办未提供表单版本,不能保存或生效']:[]),...(!sampleIds.length?['请获取真实订单样本']:[])]};
|
||||
});return {processName,categories:related.map(r=>({id:r.id,name:r.draft.name,filenameDate:r.draft.filenameDate})),versions};
|
||||
});
|
||||
}
|
||||
module.exports={evaluateMapping,validateSources,saveMapping,checkMapping,activateMapping,saveLegacy,directory,mappingId};
|
||||
@@ -0,0 +1,16 @@
|
||||
'use strict';
|
||||
const aliases={orderNo:['订单号','订单编号','主订单号','orderno','ordernumber'],customer:['客户','客户名称','客户简称'],quantity:['数量','总数量','订单数量','销售数量'],totalAmount:['总金额','订单总金额'],appDate:['申请日期','申请时间','发起时间'],productLine:['产品线'],changeReason:['更改原因','变更原因'],changeContent:['更改内容','变更内容']};
|
||||
const normalize=value=>String(value??'').replace(/[\s::**]/g,'').toLowerCase();
|
||||
function recommendFields(fields){
|
||||
const sources={brief:{type:'title'}},issues=[],candidates={};
|
||||
const actual=(Array.isArray(fields)?fields:[]).filter(f=>typeof f?.path==='string'&&f.path.trim());
|
||||
for(const [key,names]of Object.entries(aliases)){
|
||||
const matches=actual.filter(f=>names.includes(normalize(f.label))).filter(f=>key!=='quantity'||normalize(f.label)!=='数量'||/^(?:qty|quantity|orderquantity|salesquantity)$/i.test(f.path.split('.').at(-1)));
|
||||
candidates[key]=matches.map(f=>({path:f.path,label:f.label||'',value:f.value??null}));
|
||||
if(matches.length===1)sources[key]={type:'form',path:matches[0].path};
|
||||
else if(matches.length>1)issues.push(key+' 有多个同名字段,请人工选择');
|
||||
}
|
||||
if(!sources.orderNo)issues.push('未找到唯一的表单主订单号,请在字段映射选择');
|
||||
return {sources,issues,candidates};
|
||||
}
|
||||
module.exports={recommendFields};
|
||||
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
const BUSINESS_FIELDS=['orderNo','brief','appDate','customer','productLine','quantity','changeReason','changeContent','totalAmount'];
|
||||
const METADATA_FIELDS=['processName','processVersion','nodeName','receivedAt','serialNum'];
|
||||
function sourcesFor(adapter){return adapter?.sources||Object.fromEntries(Object.entries(adapter?.fields||{}).map(([key,path])=>[key,{type:'form',path}]));}
|
||||
function readSource(source,sample){
|
||||
if(source?.type==='form')return {path:source.path,value:Object.hasOwn(sample.fields||{},source.path)?sample.fields[source.path]:null};
|
||||
if(source?.type==='metadata'&&METADATA_FIELDS.includes(source.key))return {path:'待办 · '+source.key,value:sample[source.key]};
|
||||
return {path:'',value:null};
|
||||
}
|
||||
module.exports={BUSINESS_FIELDS,METADATA_FIELDS,sourcesFor,readSource};
|
||||
@@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
const MODES=new Set(['惠州','惠州数字','惠州模式']);
|
||||
const CUSTOMER='惠州创维数字技术有限公司';
|
||||
const clean=value=>String(value||'').trim().replace(/[|,,;;\s]+$/u,'');
|
||||
function selectHuizhou(event){
|
||||
const orders=[],issues=[];
|
||||
for(const row of event?.titleOrders||[]){
|
||||
const mode=clean(row.businessMode),customer=clean(row.customer||row.customerShort);
|
||||
const modeMatch=MODES.has(mode),customerMatch=customer===CUSTOMER;
|
||||
const conflict=row.businessModeAmbiguous||customerMatch&&mode&&!modeMatch;
|
||||
if(conflict){issues.push('订单 '+row.orderNo+' 的惠州业务模式与客户证据冲突或段落归属不明,需核实。');continue;}
|
||||
if(modeMatch||customerMatch){orders.push(structuredClone(row));continue;}
|
||||
if(/^HA/i.test(row.orderNo||'')||mode.includes('惠州')||customer.includes('惠州'))issues.push('订单 '+row.orderNo+' 仅有惠州线索,缺少明确业务模式或已知客户证据,需核实。');
|
||||
}
|
||||
// Whole-event fields may flag missing segment evidence, but can never select all rows.
|
||||
if(!event?.titleOrders?.length&&(MODES.has(clean(event?.businessMode))||clean(event?.customer)===CUSTOMER||/^HA/i.test(event?.orderNo||'')))issues.push('缺少逐订单标题明细,惠州需求需核实。');
|
||||
return {orders,orderNos:orders.map(row=>row.orderNo),issues};
|
||||
}
|
||||
function initialNotification(rule,event){
|
||||
if(rule?.huizhouEnabled!==true)return {status:'disabled',batchId:null,error:null,orderNos:[],issues:[]};
|
||||
const selection=selectHuizhou(event);
|
||||
return {status:selection.issues.length?'blocked':selection.orders.length?'pending':'empty',batchId:null,error:selection.issues.join(';')||null,orderNos:selection.orderNos,issues:selection.issues};
|
||||
}
|
||||
function ordersForMode(orders,mode='normal'){
|
||||
if(mode==='normal')return orders;
|
||||
return orders.flatMap(order=>{
|
||||
const selected=selectHuizhou(order.event);if(!selected.orders.length)return [];
|
||||
return [{...order,status:'pending',event:{...order.event,orderNo:selected.orderNos.join('、'),brief:selected.orders.map(row=>row.text).join('\n'),titleOrders:selected.orders}}];
|
||||
});
|
||||
}
|
||||
module.exports={selectHuizhou,initialNotification,ordersForMode};
|
||||
@@ -0,0 +1,10 @@
|
||||
'use strict';
|
||||
async function template(store){
|
||||
const Excel=require('exceljs'),book=new Excel.Workbook(),sheet=book.addWorksheet('分类规则');
|
||||
sheet.columns=['类别编号','分类名称','订单评审流程','电子流状态','流程节点配对','服务器存档地址','邮件命名','收件人','抄送人','附带PDF','文件名日期'].map(header=>({header,width:['收件人','流程节点配对'].includes(header)?60:28}));
|
||||
const dates={appDate:'申请日期',receivedAt:'接收日期',archiveDate:'归档日期'};
|
||||
for(const {draft:r}of store.all('rules'))sheet.addRow([r.id,r.name,r.processNames.join('/'),r.nodeNames.join('/'),require('./scopes.cjs').scopesFor(r).map(s=>s.processName+' → '+s.nodeName).join('\n'),r.archiveDirectory,r.subjectPrefix,r.to.join('\n'),r.cc.join('\n'),r.attachPdf?'是':'否',dates[r.filenameDate]||'']);
|
||||
sheet.views=[{state:'frozen',ySplit:1}];sheet.getRow(1).font={bold:true};sheet.eachRow(row=>row.alignment={vertical:'top',wrapText:true});sheet.autoFilter='A1:K1';
|
||||
return Buffer.from(await book.xlsx.writeBuffer());
|
||||
}
|
||||
module.exports={template};
|
||||
@@ -0,0 +1,61 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const {validateRule,addresses,fail}=require('./validation.cjs');
|
||||
const {checkTemplates}=require('./template-validation.cjs');
|
||||
const split=value=>String(value||'').split(/[\n/+]/).map(v=>v.trim().replace(/^[“"「]|[”"」]$/g,'')).filter(Boolean);
|
||||
function recipients(value){
|
||||
const text=String(value||'').trim();if(!text)return [];if(!text.includes('@'))fail('收件人未识别到有效邮箱');
|
||||
const parsed=require('nodemailer/lib/addressparser')(text.replace(/[,;\n]/g,',')),values=[];
|
||||
const collect=items=>{for(const item of items){if(item.group)collect(item.group);else values.push(item.address);}};collect(parsed);
|
||||
if(!values.length)fail('收件人未识别到有效邮箱');return addresses(values);
|
||||
}
|
||||
function previewImport(store,input,actor){
|
||||
if(!input||Object.keys(input).some(k=>k!=='rows')||!Array.isArray(input.rows)||input.rows.length<2||input.rows.length>201||input.rows.some(r=>!Array.isArray(r)||r.length>20||r.some(c=>typeof c!=='string'&&typeof c!=='number'||String(c).length>20000)))fail('请导入不超过 200 行、20 列的分类表格。');
|
||||
const headers=input.rows[0].map(v=>String(v).trim());if(new Set(headers.filter(Boolean)).size!==headers.filter(Boolean).length)fail('Excel 列名重复,请检查表头。');
|
||||
for(const name of ['订单评审流程','电子流状态','邮件命名','收件人'])if(!headers.includes(name))fail('缺少 Excel 列:'+name);
|
||||
const originals=store.all('rules'),rows=[],seen=new Set();
|
||||
input.rows.slice(1).forEach((cells,index)=>{
|
||||
const get=name=>String(cells[headers.indexOf(name)]??'').trim();if(!cells.some(c=>String(c).trim()))return;
|
||||
const row={sourceRow:index+2,name:get('分类名称'),issues:[],warnings:[],changes:[]};rows.push(row);
|
||||
try{
|
||||
const explicit=get('类别编号'),subject=get('邮件命名'),name=row.name||subject.match(/^[【\[](.+?)[】\]]/)?.[1];
|
||||
const matches=explicit?originals.filter(r=>r.id===explicit):originals.filter(r=>r.draft.name===name||r.draft.subjectPrefix===subject.match(/^[【\[].+?[】\]]/)?.[0]);
|
||||
if(matches.length>1)fail('类别名称或主题对应多条规则,请用类别编号明确选择');const record=matches[0];
|
||||
if(!record)fail('未找到对应类别,请使用模板中的类别编号或现有分类名称');
|
||||
if(seen.has(record.id))fail('此类别在 Excel 中重复');seen.add(record.id);row.id=record.id;row.name=record.draft.name;
|
||||
const old=record.draft,processes=split(get('订单评审流程')),nodes=split(get('电子流状态'));if(!processes.length||!nodes.length)fail('流程名和节点名不能为空');
|
||||
const prefix=subject.match(/^[【\[].+?[】\]]/)?.[0]||subject;
|
||||
let scopes=processes.flatMap(processName=>nodes.map(nodeName=>({processName,nodeName})));
|
||||
if(get('流程节点配对'))scopes=get('流程节点配对').split('\n').filter(v=>v.trim()).map(v=>{const pair=v.split('→').map(s=>s.trim());if(pair.length!==2||!pair.every(Boolean))fail('流程节点配对请按“流程名 → 节点名”每行一对填写');return {processName:pair[0],nodeName:pair[1]};});
|
||||
const candidate={...old,name:get('分类名称')||old.name,sourceRow:index+2,subjectPrefix:prefix,to:recipients(get('收件人')),scopes};
|
||||
if(headers.includes('抄送人'))candidate.cc=recipients(get('抄送人'));
|
||||
if(headers.includes('服务器存档地址'))candidate.archiveDirectory=get('服务器存档地址');
|
||||
if(headers.includes('文件名日期')){const dates={'申请日期':'appDate','接收日期':'receivedAt','归档日期':'archiveDate','':'',appDate:'appDate',receivedAt:'receivedAt',archiveDate:'archiveDate'};if(!Object.hasOwn(dates,get('文件名日期')))fail('文件名日期只支持申请日期、接收日期或归档日期');candidate.filenameDate=dates[get('文件名日期')];}
|
||||
if(headers.includes('附带PDF')){const value=get('附带PDF');if(!['是','否','true','false'].includes(value))fail('附带PDF请填写是或否');candidate.attachPdf=['是','true'].includes(value);}
|
||||
else if(headers.includes('邮件正文')){const value=get('邮件正文');if(/附件[::].*PDF/i.test(value))candidate.attachPdf=true;else if(/摘要信息/.test(value))candidate.attachPdf=false;else row.warnings.push('邮件正文描述未自动转换,保留原附件设置');}
|
||||
candidate.adapterIds=[...new Set([...old.adapterIds,...store.adapters().filter(a=>a.verified&&processes.includes(a.processName)).filter(a=>!store.adapters().some(b=>b.id!==a.id&&b.verified&&b.processName===a.processName&&b.processVersion===a.processVersion)).map(a=>a.id)])];
|
||||
Object.assign(candidate,validateRule(candidate,old),{version:old.version});row.candidate=candidate;row.version=old.version;row.recipientCount=candidate.to.length;
|
||||
const labels={name:'分类名称',subjectPrefix:'邮件主题',to:'收件人',cc:'抄送人',archiveDirectory:'归档目录',attachPdf:'PDF附件',filenameDate:'文件名日期',scopes:'流程与节点',adapterIds:'BPM识别配置'};
|
||||
for(const [key,label]of Object.entries(labels))if(JSON.stringify(old[key])!==JSON.stringify(candidate[key]))row.changes.push(label);
|
||||
if(!candidate.archiveDirectory.startsWith('\\\\'))row.warnings.push('表内仅有目录名称,请在第03步选择存储服务器和目录');
|
||||
if(!get('流程节点配对')&&processes.length>1&&nodes.length>1)row.warnings.push('此行多个流程共用多个节点,按所有组合导入,请在第01步检查配对');
|
||||
if(!candidate.filenameDate)row.warnings.push('文件名日期仍待选择');
|
||||
}catch(error){row.issues.push(error.message);}
|
||||
});
|
||||
if(!rows.length)fail('表格没有可导入的分类行');
|
||||
const id=crypto.randomUUID(),canCommit=rows.every(r=>!r.issues.length),plan={id,actor,createdAt:store.now(),canCommit,rows};
|
||||
store.put('rule-imports',plan);return publicPlan(plan);
|
||||
}
|
||||
function publicPlan(plan){return {id:plan.id,canCommit:plan.canCommit,rows:plan.rows.map(({candidate,...row})=>row)};}
|
||||
function commitImport(store,input,actor,{mail}={}){return store.transaction(()=>{
|
||||
if(!input||Object.keys(input).some(k=>k!=='id')||typeof input.id!=='string')fail('请选择已检查的导入预览');
|
||||
const plan=store.get('rule-imports',input.id);if(!plan||plan.actor!==actor)fail('导入预览不存在,请重新选择文件',404);
|
||||
if(plan.result)return plan.result;
|
||||
if(Date.parse(store.now())-Date.parse(plan.createdAt)>30*60000)fail('导入预览已过期,请重新选择文件',409);
|
||||
if(!plan.canCommit)fail('请修复 Excel 中的问题后重新导入',409);
|
||||
const prepared=plan.rows.map(row=>{const record=store.get('rules',row.id);return {record,rule:validateRule(row.candidate,record?.draft)};});
|
||||
for(const {rule}of prepared)checkTemplates(mail,rule);
|
||||
for(const {record,rule}of prepared){store.put('rule-history',{id:record.id+':'+record.draft.version,rule:record.draft,at:store.now(),actor});record.draft=rule;record.trialVersion=null;record.trialDemo=null;record.trialSampleId=null;store.put('rules',record);}
|
||||
plan.result={id:plan.id,count:prepared.length};store.put('rule-imports',plan);store.audit(actor,'Excel 导入分类草稿',String(prepared.length)+' 类');return plan.result;
|
||||
});}
|
||||
module.exports={previewImport,commitImport};
|
||||
@@ -0,0 +1,38 @@
|
||||
'use strict';
|
||||
const path=require('node:path');
|
||||
const {escape}=require('../mail/parser.cjs');
|
||||
const {formatOrderLine}=require('../../order-template-bridge.cjs');
|
||||
const {fail}=require('./validation.cjs');
|
||||
const lines=value=>escape(value).replace(/\r?\n/g,'<br>');
|
||||
function fileLink(filePath){
|
||||
if(filePath.startsWith('\\\\'))return 'file://'+filePath.slice(2).split('\\').map(encodeURIComponent).join('/');
|
||||
if(/^[a-z]:[\\/]/i.test(filePath))return 'file:///'+filePath.replace(/\\/g,'/').split('/').map((p,i)=>i===0?p:encodeURIComponent(p)).join('/');
|
||||
return 'file://'+filePath.split('/').map(encodeURIComponent).join('/');
|
||||
}
|
||||
// Content is derived from the event and its recorded archive, never current configuration.
|
||||
function mailContent(orders){
|
||||
const summaries=orders.flatMap(order=>{
|
||||
const event=order.event,rows=event.titleOrders;
|
||||
if(rows?.length&&rows.every(row=>typeof row.text==='string'&&row.text.trim()))return rows.map(row=>({orderNo:row.orderNo,brief:row.text}));
|
||||
// Older event snapshots may lack per-order text. Recover only the declared
|
||||
// title segments, using the same deterministic title parser as ingestion.
|
||||
const parsed=require('./title.cjs').extractTitle(event.brief||'');
|
||||
if(rows?.length&&parsed.orders.length>1)return rows.map(row=>{
|
||||
const matches=parsed.orders.filter(observed=>observed.orderNo===row.orderNo);
|
||||
if(!row.text?.trim()&&matches.length!==1)fail('已识别订单段落缺少可核对的简要说明原文。',409);
|
||||
return {orderNo:row.orderNo,brief:row.text?.trim()?row.text:matches[0].text};
|
||||
});
|
||||
if(rows?.length>1)fail('已识别订单段落缺少可核对的简要说明原文。',409);
|
||||
if(parsed.orders.length>1)return parsed.orders.map(row=>({orderNo:row.orderNo,brief:row.text}));
|
||||
return [{orderNo:rows?.[0]?.orderNo||event.orderNo,brief:event.brief}];
|
||||
});
|
||||
const details=summaries.map(formatOrderLine).join('\n');
|
||||
const seen=new Set(),directories=[];
|
||||
for(const order of orders)for(const file of order.archive.files){
|
||||
const windows=path.win32.isAbsolute(file.path),directory=(windows?path.win32:path.posix).dirname(file.path),key=windows?directory.toLowerCase():directory;
|
||||
if(!seen.has(key)){seen.add(key);directories.push(directory);}
|
||||
}
|
||||
const htmlDirectoryLinks=directories.map(directory=>'<a style="color:#0000ff" href="'+escape(fileLink(directory))+'">'+escape(directory)+'</a>').join('<br>');
|
||||
return {details,orderNos:summaries.map(row=>row.orderNo),directories,htmlDetails:'<div style="color:#0000ff">'+lines(details)+'</div>',htmlDirectoryLinks,htmlDirectories:'<div>存放地址:<br>'+htmlDirectoryLinks+'</div>'};
|
||||
}
|
||||
module.exports={mailContent,fileLink};
|
||||
@@ -0,0 +1,96 @@
|
||||
'use strict';
|
||||
const {extractTitle}=require('./title.cjs');
|
||||
const {sourcesFor,readSource}=require('./field-sources.cjs');
|
||||
const {matchesScope,scopesFor}=require('./scopes.cjs');
|
||||
|
||||
const labels = {
|
||||
orderNo: '订单号', appDate: '申请日期', customer: '客户', productLine: '产品线',
|
||||
quantity: '数量', brief: '摘要', changeReason: '更改原因', changeContent: '更改内容', totalAmount: '总金额',
|
||||
};
|
||||
const present = value => value !== undefined && value !== null && (typeof value !== 'string' || value.trim() !== '');
|
||||
const scalar = value => typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value));
|
||||
const nonblank = value => typeof value === 'string' && value.trim().length > 0;
|
||||
function validAppDate(value){
|
||||
if(!nonblank(value)||!/^\d{4}-\d{2}-\d{2}(?:$|[ T])/.test(value))return false;
|
||||
const day=value.slice(0,10),date=new Date(day+'T00:00:00Z');
|
||||
if(!Number.isFinite(+date)||date.toISOString().slice(0,10)!==day)return false;
|
||||
return value.length===10||Number.isFinite(Date.parse(value.replace(' ','T')));
|
||||
}
|
||||
|
||||
function previewMatch(rules, adapters, input, {mappingEvidence=false}={}) {
|
||||
const sample = input && typeof input === 'object' ? input : {};
|
||||
const checks = [], issues = [];
|
||||
const check = (label, ok, detail) => {
|
||||
checks.push({ label, ok: !!ok, detail });
|
||||
if (!ok) issues.push(detail);
|
||||
};
|
||||
for (const key of ['connectionId', 'instanceId', 'taskId']) {
|
||||
check('事件身份', scalar(sample[key]) && present(sample[key]), `${key}:${present(sample[key]) ? String(sample[key]) : '缺失'}`);
|
||||
}
|
||||
check('事件来源', sample.source === 'todo'||mappingEvidence&&sample.source==='history'&&sample.configurationOnly===true, 'source 必须为 todo(待办);历史证据仅限字段配置检查');
|
||||
check('事件修订', !present(sample.revision)||scalar(sample.revision), `revision:${present(sample.revision) ? String(sample.revision) : '来源未提供'}`);
|
||||
check('接收时间', nonblank(sample.receivedAt) && /T.*(?:Z|[+-]\d{2}:\d{2})$/.test(sample.receivedAt) && Number.isFinite(Date.parse(sample.receivedAt)), 'receivedAt 必须是带时区的有效时间');
|
||||
for (const key of ['processName', 'processVersion', 'nodeName']) {
|
||||
check('流程信息', nonblank(sample[key]), `${key}:${nonblank(sample[key]) ? sample[key] : '缺失'}`);
|
||||
}
|
||||
const matches = (Array.isArray(rules) ? rules : []).filter(rule => matchesScope(rule,sample));
|
||||
check('分类命中', matches.length === 1, matches.length === 1 ? `唯一命中:${matches[0].name}` : matches.length ? `同时命中 ${matches.length} 条规则,须消除冲突` : '没有流程名称和节点名称均精确匹配的规则');
|
||||
const rule = matches.length === 1 ? matches[0] : null;
|
||||
const available = rule ? (Array.isArray(adapters) ? adapters : []).filter(adapter =>
|
||||
rule.adapterIds?.includes(adapter.id) && adapter.processName === sample.processName
|
||||
&& adapter.processVersion === sample.processVersion && (adapter.reference ? sample.demo === true : adapter.verified === true)) : [];
|
||||
const adapter = available.length === 1 ? available[0] : null;
|
||||
check('字段适配', available.length === 1, adapter ? `字段适配 ${adapter.id}:仅表单结构已核对,不代表实时接口可用` : '没有唯一、已核对且流程版本一致的字段适配器');
|
||||
|
||||
const raw = sample.fields && typeof sample.fields === 'object' && !Array.isArray(sample.fields) ? sample.fields : {};
|
||||
const event = {};
|
||||
for (const key of ['connectionId', 'source', 'portalSource', 'instanceId', 'taskId', 'revision', 'processName', 'processVersion', 'nodeName', 'receivedAt', 'serialNum', 'demo']) {
|
||||
if (Object.hasOwn(sample, key)) event[key] = sample[key];
|
||||
}
|
||||
event.documentNum = sample.serialNum ?? '';
|
||||
event.ruleId = rule?.id ?? null;
|
||||
event.ruleVersion = rule?.version ?? null;
|
||||
event.categoryId = rule?.categoryId ?? null;
|
||||
event.adapterId = adapter?.id ?? null;
|
||||
const fieldTrace = [];
|
||||
const mappings = adapter?.fields ?? {},sources=sourcesFor(adapter);
|
||||
const titleSource=Object.hasOwn(sample,'title')?'title':sources.brief?.type!=='title'&&typeof sample.brief==='string'&&/订单号\s*[::]/u.test(sample.brief)?'brief':null;
|
||||
const extracted=titleSource?extractTitle(sample[titleSource]):null;
|
||||
if(extracted){
|
||||
event.rawTitle=extracted.rawTitle;event.titleOrders=extracted.orders;event.factoryHints=extracted.factoryHints;
|
||||
check('标题提取',extracted.issues.length===0,extracted.issues.join(';')||`从标题提取 ${extracted.orders.length} 个订单段落;惠州通知按每段业务模式与客户证据独立判断`);
|
||||
}
|
||||
for (const key of new Set(['orderNo', 'appDate', 'customer', 'productLine', 'quantity', ...Object.keys(mappings), ...Object.keys(sources), 'brief'])) {
|
||||
if(key==='productLine'&&rule?.productLine!==undefined){event.productLine=rule.productLine;check('产品线',nonblank(rule.productLine),'分类规则必须提供明确产品线');fieldTrace.push({key,label:labels[key],path:'rule.productLine',value:rule.productLine});continue;}
|
||||
const selected=readSource(sources[key],sample);
|
||||
if(sources[key]?.type==='form'&&!(key==='brief'&&extracted))check('字段来源',Object.hasOwn(sample.fields||{},sources[key].path),'所选'+(labels[key]||key)+'来源字段不存在:'+sources[key].path);
|
||||
const path = key === 'brief' ? extracted?`${titleSource} → 订单段落`:selected.path||'brief' : selected.path;
|
||||
const value = key === 'brief' ? extracted?extracted.brief:sources.brief?.type==='title'?null:selected.value??sample.brief : selected.value;
|
||||
event[key] = value ?? null;
|
||||
fieldTrace.push({ key, label: labels[key] || key, path, value: value ?? null });
|
||||
}
|
||||
for (const key of ['orderNo', 'brief']) {
|
||||
check(labels[key], nonblank(event[key]), `${key} ${nonblank(event[key]) ? '已取得' : '缺失或不是文本'}`);
|
||||
}
|
||||
if(extracted&&nonblank(event.orderNo))check('主订单号核对',extracted.orders.some(order=>order.orderNo===event.orderNo.trim()),'表单主订单号不在标题订单号中,请核对真实订单。');
|
||||
check('流水编号',nonblank(sample.serialNum),'流水编号 serialNum 必须有值,用于文件命名和追溯');
|
||||
if(rule?.filenameDate==='appDate')check('申请日期',validAppDate(event.appDate),'文件名使用申请日期,样本必须包含有效的申请日期');
|
||||
if (present(event.quantity)) {
|
||||
const numeric = typeof event.quantity === 'number' ? event.quantity : typeof event.quantity === 'string' && event.quantity.trim() ? Number(event.quantity) : NaN;
|
||||
check('数量', Number.isFinite(numeric) && numeric >= 0, 'quantity 必须为非负数,零数量合法');
|
||||
if (Number.isFinite(numeric)) event.quantity = numeric;
|
||||
} else check('数量', true, 'quantity 未提供;不猜测未核对的数量字段');
|
||||
|
||||
return {
|
||||
valid: issues.length === 0, ruleId: rule?.id ?? null, categoryId: rule?.categoryId ?? null,
|
||||
event, checks, issues, fieldTrace, candidates: matches.map(item => item.id),
|
||||
explanation: rule ? describeRule(rule) : '按照流程名称和通知节点精确分类;未命中或多条命中时阻塞。',
|
||||
};
|
||||
}
|
||||
|
||||
function describeRule(rule) {
|
||||
const date = { appDate: '申请日期', receivedAt: '接收日期', archiveDate: '归档日期' }[rule.filenameDate] || '待选择的日期';
|
||||
return `${rule.name}:满足任一流程节点配对(${scopesFor(rule).map(row=>`“${row.processName}” → “${row.nodeName}”`).join(';')||'待选择'})时归入本类别。本时段内同类别订单合并一封,通知与更改分别汇总,更早历史不补发。每封从前一个有效发送时点连续积累;首封覆盖前一发送日晚间与休息日,第二封取两个时点之间。${rule.attachPdf ? '附电子流 PDF;' : ''}文件以订单号、${date}、流水编号命名。BPM 节点由人工办理。`;
|
||||
}
|
||||
|
||||
module.exports = { previewMatch, describeRule };
|
||||
@@ -0,0 +1,115 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const {fail}=require('./validation.cjs');
|
||||
const {previewMatch}=require('./matching.cjs');
|
||||
const canonical=v=>Array.isArray(v)?v.map(canonical):v&&typeof v==='object'?Object.fromEntries(Object.keys(v).sort().map(k=>[k,canonical(v[k])])):v;
|
||||
const digest=v=>crypto.createHash('sha256').update(JSON.stringify(canonical(v))).digest('hex');
|
||||
|
||||
function frozen(store,order){
|
||||
if(!order)return false;
|
||||
return !!order.batchId||!!order.notifications?.huizhou?.batchId||!!order.blockedByBatchId||!!order.missedWindow
|
||||
||['batched','sending','sent','unknown'].includes(order.status)
|
||||
||store.all('batches').some(batch=>batch.orderIds?.includes(order.id));
|
||||
}
|
||||
function validate(input){
|
||||
if(!input||!Number.isInteger(input.version)||typeof input.idempotencyKey!=='string'
|
||||
||!/^[\w:.-]{1,160}$/.test(input.idempotencyKey)||typeof input.note!=='string'
|
||||
||input.note.trim().length<5||input.note.length>2000){
|
||||
fail('请提供版本、幂等标识和至少5字依据。');
|
||||
}
|
||||
}
|
||||
function outputEvent(event){
|
||||
const value={...event};
|
||||
delete value.ruleVersion;
|
||||
delete value.adapterId;
|
||||
return value;
|
||||
}
|
||||
function projection(store,order,rule){
|
||||
const result=previewMatch([rule],store.adapters(),order.sample);
|
||||
if(!result.valid)fail('订单 '+order.id+' 无法应用当前规则:'+result.issues.join(';'),409);
|
||||
const before=[outputEvent(order.event),order.ruleSnapshot?.archiveDirectory,order.ruleSnapshot?.filenameDate];
|
||||
const after=[outputEvent(result.event),rule.archiveDirectory,rule.filenameDate];
|
||||
return {result,archiveChanged:digest(before)!==digest(after)};
|
||||
}
|
||||
function invalidateArchive(order){
|
||||
const history=order.archiveHistory||[];
|
||||
if(order.archive)history.push({generation:order.archiveGeneration||1,evidence:order.archive});
|
||||
order.archiveHistory=history;
|
||||
order.archiveGeneration=(order.archiveGeneration||1)+1;
|
||||
order.archive=null;
|
||||
}
|
||||
function archiveContext(order,task){
|
||||
return {generation:order.archiveGeneration||1,sourceHash:order.sourceHash,
|
||||
outputFingerprint:digest([order.event,order.ruleSnapshot]),taskId:task.id,taskVersion:task.version};
|
||||
}
|
||||
function archiveContextMatches(store,order,expected){
|
||||
const task=store.get('execution-tasks',expected.taskId);
|
||||
return !!order&&!!task&&task.orderId===order.id&&digest(archiveContext(order,task))===digest(expected);
|
||||
}
|
||||
function synchronizeTasks(store,order){
|
||||
for(const task of store.all('execution-tasks').filter(task=>task.orderId===order.id&&!task.supersededBy&&!task.revisionIgnored)){
|
||||
task.status=order.status;
|
||||
task.step=order.archive?'complete':'identify';
|
||||
task.error=null;
|
||||
task.version=(task.version||0)+1;
|
||||
store.put('execution-tasks',task);
|
||||
}
|
||||
}
|
||||
function preview(store,id,input){
|
||||
if(require('./restricted-test.cjs').state(store))fail('受限测试期间不能向正式规则迁移订单,投产须另行检查。',409);
|
||||
validate(input);
|
||||
const rule=store.get('rules',id)?.published;
|
||||
if(!rule||rule.status!=='enabled'||input.version!==rule.version){
|
||||
fail('已发布规则版本已变化或未启用。',409);
|
||||
}
|
||||
const items=[],excluded=[];
|
||||
const candidates=store.all('orders').filter(order=>order.ruleSnapshot?.id===id||order.categoryId===rule.categoryId);
|
||||
for(const order of candidates){
|
||||
if(frozen(store,order)||!['blocked','identified','preparing','archived','pending'].includes(order.status)){
|
||||
excluded.push({id:order.id,status:order.status,reason:'冻结、逾期或已终结订单不可迁移'});
|
||||
continue;
|
||||
}
|
||||
const proposed=projection(store,order,rule);
|
||||
items.push({id:order.id,archiveChanged:proposed.archiveChanged,fromVersion:order.ruleSnapshot?.version,toVersion:rule.version});
|
||||
}
|
||||
return {ruleId:id,version:rule.version,items,excluded};
|
||||
}
|
||||
function apply(store,id,input,actor){
|
||||
validate(input);
|
||||
return store.transaction(()=>{
|
||||
const requestId=digest([id,actor,input.idempotencyKey]);
|
||||
const inputHash=digest(input);
|
||||
const prior=store.get('migration-requests',requestId);
|
||||
if(prior){
|
||||
if(prior.inputHash!==inputHash)fail('幂等标识已用于不同迁移。',409);
|
||||
return prior.result;
|
||||
}
|
||||
// Validate every candidate before the first mutation; the transaction also
|
||||
// protects replay, archive history, task synchronization and audit as one unit.
|
||||
const result=preview(store,id,input);
|
||||
const rule=store.get('rules',id).published;
|
||||
for(const item of result.items){
|
||||
const order=store.get('orders',item.id);
|
||||
const proposed=projection(store,order,rule);
|
||||
// A pending intent freezes its original rule metadata. Until a receipt has
|
||||
// committed, a publication migration starts a new generation for safe retry.
|
||||
if(proposed.archiveChanged||!order.archive&&order.ruleSnapshot?.version!==rule.version){
|
||||
invalidateArchive(order);
|
||||
order.status='identified';
|
||||
}
|
||||
order.event=proposed.result.event;
|
||||
order.trace=proposed.result;
|
||||
order.ruleSnapshot=structuredClone(rule);
|
||||
if(order.notifications)order.notifications.huizhou=require('./huizhou.cjs').initialNotification(rule,order.event);
|
||||
order.categoryId=rule.categoryId;
|
||||
order.updatedAt=store.now();
|
||||
order.error=null;
|
||||
store.put('orders',order);
|
||||
synchronizeTasks(store,order);
|
||||
}
|
||||
store.put('migration-requests',{id:requestId,inputHash,result,at:store.now()});
|
||||
store.audit(actor,'批量应用已发布规则',id+':'+input.note.trim());
|
||||
return result;
|
||||
});
|
||||
}
|
||||
module.exports={preview,apply,frozen,validate,digest,invalidateArchive,synchronizeTasks,archiveContext,archiveContextMatches};
|
||||
@@ -0,0 +1,22 @@
|
||||
'use strict';
|
||||
const query=require('./query.cjs');
|
||||
const {fail}=require('./validation.cjs');
|
||||
async function orderRuleQueryApi(context){
|
||||
const {route,method,url,reply,response,user}=context;
|
||||
if(method!=='GET')return false;
|
||||
if((route==='/api/order-rules'||route.startsWith('/api/order-rules/'))&&!context.orderRules)fail('分类通知规则服务未启动。',503);
|
||||
const params=url instanceof URL?url.searchParams:new URL(String(url||route),'http://localhost').searchParams;
|
||||
if(route==='/api/order-rules'&¶ms.get('view')==='summary'){reply(200,query.summary(context,user));return true;}
|
||||
const match=/^\/api\/order-rules\/(orders|batches)(?:\/([^/]+)(?:\/files\/(\d+))?)?$/.exec(route);
|
||||
if(!match)return false;
|
||||
const [,kind,encoded,index]=match;let id;
|
||||
try{id=encoded&&decodeURIComponent(encoded);}catch{fail('路径编码无效。');}
|
||||
if(index!==undefined&&kind==='orders'){
|
||||
const file=await query.readOrderFile(context,id,Number(index),user);
|
||||
response.writeHead(200,{'Content-Type':'application/pdf','Content-Length':file.bytes.length,'Content-Disposition':"attachment; filename*=UTF-8''"+encodeURIComponent(file.name),'Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});response.end(file.bytes);return true;
|
||||
}
|
||||
if(index!==undefined)return false;
|
||||
reply(200,id?query[kind==='orders'?'orderDetail':'batchDetail'](context,id,user):query[kind==='orders'?'queryOrders':'queryBatches'](context,Object.fromEntries(params),user));
|
||||
return true;
|
||||
}
|
||||
module.exports={orderRuleQueryApi};
|
||||
@@ -0,0 +1,128 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const {canReadConnection,canReadOrder,canReadBatch}=require('./access.cjs');
|
||||
const {fail}=require('./validation.cjs');
|
||||
const {notifications,modeOf}=require('./delivery.cjs');
|
||||
const cache=new WeakMap();
|
||||
const orderStates=['candidate','identified','preparing','archived','pending','batched','blocked','unknown','sent','failed','capturing','archiving','queued','ignored'];
|
||||
const batchStates=['prepared','sending','unknown','failed','sent','cancelled'];
|
||||
function records(store){
|
||||
const revision=store.queryRevision?.();
|
||||
const saved=cache.get(store);
|
||||
if(revision!==undefined&&saved?.revision===revision)return saved;
|
||||
const value={revision:revision??Date.now(),orders:store.all('orders'),batches:store.all('batches'),tasks:store.all('execution-tasks'),candidates:store.all('execution-candidates')||[],issues:store.all('business-issues')};
|
||||
if(revision!==undefined)cache.set(store,value);
|
||||
return value;
|
||||
}
|
||||
function filters(input={},kind){
|
||||
const allowed=['q','categoryId','status','connectionId','from','to','page','pageSize',...(kind==='batches'?['scope']:[])];
|
||||
if(Object.keys(input).some(k=>!allowed.includes(k)))fail('查询参数无效。');
|
||||
const result={page:1,pageSize:25,q:'',scope:'active',...input};
|
||||
for(const name of ['page','pageSize']){result[name]=Number(result[name]);if(!Number.isSafeInteger(result[name])||result[name]<1)fail('页码或分页大小无效。');}
|
||||
if(![25,50,100].includes(result.pageSize))fail('每页仅支持25、50或100条。');
|
||||
if(result.status&&!(kind==='batches'?batchStates:orderStates).includes(result.status))fail('状态筛选无效。');
|
||||
if(kind==='batches'&&!['active','all'].includes(result.scope))fail('批次范围无效。');
|
||||
for(const key of ['q','categoryId','connectionId'])if(result[key]!==undefined&&(typeof result[key]!=='string'||result[key].length>200))fail('查询内容过长或无效。');
|
||||
for(const key of ['from','to'])if(result[key]&&(!/^\d{4}-\d{2}-\d{2}$/.test(result[key])||!Number.isFinite(Date.parse(result[key]))||new Date(result[key]).toISOString().slice(0,10)!==result[key]))fail('日期筛选无效。');
|
||||
if(result.from&&result.to&&result.from>result.to)fail('开始日期不能晚于结束日期。');
|
||||
return result;
|
||||
}
|
||||
const pick=(row,keys)=>Object.fromEntries(keys.filter(k=>row?.[k]!==undefined).map(k=>[k,structuredClone(row[k])]));
|
||||
const identity=row=>pick(row,['source','connectionId','instanceId','taskId','revision','processName','nodeName','orderNo','serialNum','receivedAt','quantity','brief','model','project','title']);
|
||||
function taskEvidence(task,context,user){
|
||||
if(!task)return null;
|
||||
const value=pick(task,['id','version','connectionId','status','step','error','exceptionId','conflict','missedWindow','recovery','updatedAt','createdAt']);
|
||||
value.row=identity(task.row);
|
||||
if(task.conflictRow){const previous=task.previousTaskId?context.orderRules.get('execution-tasks',task.previousTaskId):task;value.revisionEvidence={previous:identity(previous&&canReadConnection(context.workspace,user,previous.connectionId)?previous.row:undefined),incoming:identity(task.conflictRow)};}
|
||||
return value;
|
||||
}
|
||||
function orderRow(order,task){
|
||||
const event=identity(order?.event||task?.row);
|
||||
return {...event,...pick(order,['id','status','categoryId','error','reason','batchId','createdAt','updatedAt','orderNo','receivedAt']),...(order?{notifications:notifications(order),...(order.ruleSnapshot?.testRunId?{testRunId:order.ruleSnapshot.testRunId}:{})}:{}),
|
||||
id:order?.id||'task:'+task.id,connectionId:order?.sample?.connectionId||event.connectionId||task?.connectionId,
|
||||
error:task?.error||order?.error,executionTaskId:task?.id,executionStatus:task?.status,exceptionId:task?.exceptionId,orderNo:order?.orderNo||event.orderNo||event.serialNum||event.taskId,
|
||||
categoryId:order?.categoryId||task?.categoryIds?.[0]||'',status:task&&['failed','blocked','unknown','capturing','archiving'].includes(task.status)?task.status:order?.status||task?.status};
|
||||
}
|
||||
function currentTasks(context,user){
|
||||
const tasks=new Map();for(const task of records(context.orderRules).tasks){if(task.supersededBy||!task.orderId||!canReadConnection(context.workspace,user,task.connectionId))continue;const old=tasks.get(task.orderId);if(!old||Number(!!task.conflict)>Number(!!old.conflict)||!!task.conflict===!!old.conflict&&String(task.createdAt||'')>=String(old.createdAt||''))tasks.set(task.orderId,task);}return tasks;
|
||||
}
|
||||
function candidateRow(candidate){const row=identity(candidate.row);return {...row,id:'candidate:'+candidate.id,connectionId:candidate.connectionId,orderNo:row.orderNo||row.serialNum||row.taskId,status:'candidate',reason:candidate.reason,createdAt:candidate.createdAt,updatedAt:candidate.updatedAt,categoryId:''};}
|
||||
function visibleOrders(context,user){
|
||||
const data=records(context.orderRules),tasks=currentTasks(context,user);
|
||||
const rows=data.orders.filter(o=>canReadOrder(context.workspace,user,o)).map(o=>orderRow(o,tasks.get(o.id)));
|
||||
for(const task of data.tasks)if(!task.orderId&&!task.supersededBy&&canReadConnection(context.workspace,user,task.connectionId))rows.push(orderRow(null,task));
|
||||
for(const candidate of data.candidates)if(candidate.status==='candidate'&&canReadConnection(context.workspace,user,candidate.connectionId))rows.push(candidateRow(candidate));
|
||||
return rows;
|
||||
}
|
||||
function page(rows,input,revision){
|
||||
const q=input.q.trim().toLocaleLowerCase();
|
||||
const from=input.from?Date.parse(input.from+'T00:00:00+08:00'):null;
|
||||
const until=input.to?Date.parse(input.to+'T00:00:00+08:00')+86400000:null;
|
||||
rows=rows.filter(row=>{
|
||||
const searchable=[row.orderNo,row.subject,row.id,row.executionTaskId,row.taskId,row.processName,row.nodeName].join(' ').toLocaleLowerCase();
|
||||
const at=Date.parse(row.windowEnd||row.cutoff||row.windowStart||row.receivedAt||row.createdAt||'');
|
||||
return (!q||searchable.includes(q))
|
||||
&&(!input.status||row.status===input.status)
|
||||
&&(!input.categoryId||row.categoryId===input.categoryId)
|
||||
&&(!input.connectionId||row.connectionId===input.connectionId||row.connectionIds?.includes(input.connectionId))
|
||||
&&(from===null||at>=from)&&(until===null||at<until);
|
||||
});
|
||||
rows.sort((a,b)=>String(b.receivedAt||b.createdAt||'').localeCompare(String(a.receivedAt||a.createdAt||''))||a.id.localeCompare(b.id));
|
||||
const total=rows.length,totalPages=Math.max(1,Math.ceil(total/input.pageSize));
|
||||
const current=Math.min(input.page,totalPages),offset=(current-1)*input.pageSize;
|
||||
return {items:rows.slice(offset,offset+input.pageSize),total,page:current,pageSize:input.pageSize,totalPages,from:total?offset+1:0,to:Math.min(total,offset+input.pageSize),revision};
|
||||
}
|
||||
|
||||
function publicRevision(context,user){
|
||||
const sources=context.workspace?.recordSources?.()||context.workspace?.connectionSources?.()||[];
|
||||
return crypto.createHash('sha256').update(JSON.stringify([records(context.orderRules).revision,user?.username,user?.role,sources.map(c=>[c.id,c.owner,c.status])])).digest('hex').slice(0,24);
|
||||
}
|
||||
function queryOrders(context,input,user){return page(visibleOrders(context,user),filters(input,'orders'),publicRevision(context,user));}
|
||||
function batchRow(context,batch){
|
||||
return {...pick(batch,['id','version','categoryId','subject','status','error','createdAt','windowStart','windowEnd','cutoff','orderNos','testRunId']),notificationMode:modeOf(batch),windowStart:batch.windowStart||batch.window?.start,windowEnd:batch.windowEnd||batch.window?.end||batch.cutoff,orderCount:batch.orderIds?.length||0,connectionIds:[...new Set((batch.orderIds||[]).map(id=>{const o=context.orderRules.get('orders',id);return o?.sample?.connectionId||o?.event?.connectionId||o?.connectionId;}).filter(Boolean))]};
|
||||
}
|
||||
function queryBatches(context,input,user){
|
||||
const f=filters(input,'batches'),data=records(context.orderRules);
|
||||
const rows=data.batches.filter(b=>canReadBatch(context.workspace,user,b,context.orderRules)&&(f.scope==='all'||!['sent','cancelled'].includes(b.status))).map(b=>batchRow(context,b));
|
||||
return page(rows,f,publicRevision(context,user));
|
||||
}
|
||||
function orderDetail(context,id,user){
|
||||
if(id.startsWith('candidate:')){const candidate=records(context.orderRules).candidates.find(row=>row.id===id.slice(10)&&row.status==='candidate');if(!candidate||!canReadConnection(context.workspace,user,candidate.connectionId))fail('候选记录不存在或无权查看。',404);return {...candidateRow(candidate),event:identity(candidate.row),executionTask:null,files:[],batches:[]};}
|
||||
const data=records(context.orderRules),task=id.startsWith('task:')?data.tasks.find(t=>t.id===id.slice(5)):currentTasks(context,user).get(id);
|
||||
const order=id.startsWith('task:')?null:context.orderRules.get('orders',id);
|
||||
if(order?!canReadOrder(context.workspace,user,order):!task||!canReadConnection(context.workspace,user,task.connectionId))fail('订单不存在或无权查看。',404);
|
||||
const files=(order?.archive?.files||[]).map((file,index)=>({...pick(file,['name','size','sha256','kind']),index,url:'/api/order-rules/orders/'+encodeURIComponent(id)+'/files/'+index}));
|
||||
return {...orderRow(order,task),event:identity(order?.event||task?.row),executionTask:taskEvidence(task,context,user),files,archivedAt:order?.archive?.archivedAt,archiveGeneration:order?.archiveGeneration||1,ruleVersion:order?.ruleSnapshot?.version,batches:data.batches.filter(b=>b.orderIds?.includes(id)&&canReadBatch(context.workspace,user,b,context.orderRules)).map(b=>batchRow(context,b))};
|
||||
}
|
||||
function batchDetail(context,id,user){
|
||||
const batch=context.orderRules.get('batches',id);
|
||||
if(!batch||!canReadBatch(context.workspace,user,batch,context.orderRules))fail('批次不存在或无权查看。',404);
|
||||
return {...batchRow(context,batch),...pick(batch,['to','cc','text','window','sentAt','resolvedAt','resolution','manual','originalBatchId']),orders:(batch.orderIds||[]).map(id=>context.orderRules.get('orders',id)).filter(Boolean).map(o=>orderRow(o)),attachments:(batch.attachments||[]).map(a=>pick(a,['name','filename','size','sha256']))};
|
||||
}
|
||||
async function readOrderFile(context,id,index,user){
|
||||
orderDetail(context,id,user);
|
||||
if(!Number.isSafeInteger(index)||index<0)fail('文件编号无效。');
|
||||
const file=context.orderRules.get('orders',id)?.archive?.files?.[index];
|
||||
if(!file||!Number.isSafeInteger(file.size)||!/^[a-f0-9]{64}$/i.test(file.sha256||''))fail('归档文件证据不完整。',409);
|
||||
if(typeof context.execution?.archive?.read!=='function')fail('归档读取服务暂不可用。',503);
|
||||
const bytes=await context.execution.archive.read(structuredClone(file));
|
||||
// Ownership may change while storage performs an asynchronous read.
|
||||
orderDetail(context,id,user);
|
||||
const current=context.orderRules.get('orders',id)?.archive?.files?.[index];
|
||||
if(!current||current.sha256!==file.sha256||current.path!==file.path||current.size!==file.size)fail('归档证据已变化,请重新读取详情。',409);
|
||||
if(!Buffer.isBuffer(bytes)||bytes.length!==file.size||bytes.subarray(0,5).toString()!=='%PDF-'||crypto.createHash('sha256').update(bytes).digest('hex')!==file.sha256)fail('归档文件读回校验失败。',409);
|
||||
return {bytes,name:file.name||'order.pdf'};
|
||||
}
|
||||
function summary(context,user){
|
||||
const result=context.orderRules.snapshot({includeRecords:false});
|
||||
delete result.orders;delete result.batches;delete result.audit;delete result.fields;
|
||||
const rows=visibleOrders(context,user),data=records(context.orderRules),batches=data.batches.filter(b=>canReadBatch(context.workspace,user,b,context.orderRules));
|
||||
const count=(items,status)=>items.filter(i=>status.includes(i.status)).length;
|
||||
result.scans=context.orderRules.all('execution-scans').filter(s=>canReadConnection(context.workspace,user,s.connectionId||s.id)).map(s=>pick(s,['id','connectionId','status','startedAt','finishedAt','rowCount','targetCount','error']));
|
||||
result.counts={orders:rows.length,blocked:rows.filter(row=>['blocked','failed'].includes(row.status)||row.notifications?.huizhou?.status==='blocked').length,unknown:count(batches,['unknown']),activeBatches:count(batches,['prepared','sending','unknown','failed'])};
|
||||
result.issues=data.issues.filter(issue=>!['resolved','retired'].includes(issue.status)).filter(issue=>user.role==='admin'||((issue.orderIds?.length||issue.taskIds?.length)&& (issue.orderIds||[]).every(id=>canReadOrder(context.workspace,user,context.orderRules.get('orders',id)))&&(issue.taskIds||[]).every(id=>canReadConnection(context.workspace,user,context.orderRules.get('execution-tasks',id)?.connectionId)))).slice(-50).map(i=>{const linked=context.workspace?.businessIssue?.(i.id);return pick(linked?{...i,status:linked.status,owner:linked.owner,exceptionId:linked.id}:i,['id','status','type','message','error','component','notificationMode','owner','owners','exceptionId','createdAt','batchId','orderIds','taskIds']);}).filter(i=>!['resolved','retired'].includes(i.status));
|
||||
result.templateUsage=context.orderRules.all('rules').map(r=>({categoryId:r.published?.categoryId||r.draft?.categoryId,name:r.draft?.name,templateId:r.published?.bodyTemplateId||'',huizhouEnabled:r.published?.huizhouEnabled===true,huizhouTemplateId:r.published?.huizhouTemplateId||'',legacyBinding:!!r.published&&r.published.bodyTemplateId===undefined,publishedVersion:r.published?.version||null,status:r.published?.status||'draft'}));
|
||||
result.revision=crypto.createHash('sha256').update(publicRevision(context,user)+JSON.stringify([result.window,result.issues])).digest('hex').slice(0,24);
|
||||
return result;
|
||||
}
|
||||
module.exports={queryOrders,queryBatches,orderDetail,batchDetail,readOrderFile,summary};
|
||||
@@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
const {fail,validateRule}=require('./validation.cjs');
|
||||
const {recommendFields}=require('./field-recommendation.cjs');
|
||||
const {mappingId,evaluateMapping,validateSources}=require('./field-mappings.cjs');
|
||||
const {sourcesFor,BUSINESS_FIELDS}=require('./field-sources.cjs');
|
||||
const {matchesScope,scopesFor}=require('./scopes.cjs');
|
||||
const {previewEffects}=require('./effects-preview.cjs');
|
||||
const labels={orderNo:'主订单号',brief:'通知摘要',appDate:'申请日期',customer:'客户',productLine:'产品线',quantity:'数量',changeReason:'更改原因',changeContent:'更改内容',totalAmount:'总金额'};
|
||||
function proposeMapping(store,input){
|
||||
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!['sampleId','ruleId','ruleVersion','ruleDraft','sources'].includes(k))||typeof input.sampleId!=='string'||!input.sampleId||input.sampleId.length>200)fail('识别提案参数无效。');
|
||||
const captured=store.get('capture-samples',input.sampleId);if(!captured||captured.provenance!=='server-provider'||captured.sample?.demo)fail('真实采集样本不存在。',404);
|
||||
let record=null,rule=null;const records=store.all('rules');
|
||||
if(Object.hasOwn(input,'ruleId')){if(typeof input.ruleId!=='string'||!Number.isInteger(input.ruleVersion))fail('请提供类别及当前规则版本。');record=store.get('rules',input.ruleId);if(!record)fail('规则不存在。',404);if(record.draft.version!==input.ruleVersion)fail('规则版本已变化,请刷新后核对。',409);rule=structuredClone(record.draft);}
|
||||
else if(Object.hasOwn(input,'ruleVersion')||Object.hasOwn(input,'ruleDraft'))fail('规则预览必须指定匹配的类别与版本。');
|
||||
if(Object.hasOwn(input,'ruleDraft')){rule=validateRule(input.ruleDraft,record.draft);rule.version=record.draft.version;}
|
||||
const {sample}=captured,recommended=recommendFields(captured.snapshot.fields),id=mappingId(captured.processName,captured.processVersion),draft=store.get('field-mapping-drafts',id);
|
||||
const active=store.all('field-adapters').filter(a=>a.status!=='superseded'&&a.verified===true&&a.processName===captured.processName&&a.processVersion===captured.processVersion);
|
||||
const chosen=draft||active.length===1&&active[0]||null,basis=draft?'draft':active.length>1?'conflict':chosen?'active':'recommended';
|
||||
let sources=structuredClone(chosen?sourcesFor(chosen):recommended.sources);
|
||||
if(Object.hasOwn(input,'sources'))sources=validateSources(input.sources,captured,{requireOrder:false});
|
||||
const related=records.filter(r=>r.draft.processNames.includes(captured.processName)||r.published?.processNames.includes(captured.processName)).map(r=>({id:r.id,draft:r.id===record?.id?rule:r.draft}));
|
||||
if(rule&&!related.some(r=>r.id===rule.id))related.push({id:rule.id,draft:rule});
|
||||
const recognition=evaluateMapping(store,{id,processName:captured.processName,processVersion:captured.processVersion,version:draft?.version||0,sources},captured,{relatedRules:related});
|
||||
recognition.publishEvidence=false;
|
||||
const blockedReasons=[...recognition.issues],warnings=[...(recognition.warnings||[])];
|
||||
if(active.length>1)blockedReasons.push('同一流程版本存在多个生效映射,请确认唯一配置。');
|
||||
const history=sample.source==='history',scopeCandidate=sample.source==='todo'&&sample.nodeName&&!/历史查看|未提供办理节点/.test(sample.nodeName)?{processName:captured.processName,nodeName:sample.nodeName}:null;
|
||||
const conflicts=records.filter(r=>r.id!==record?.id&&(matchesScope(r.draft,sample)||r.published&&matchesScope(r.published,sample))).map(r=>({ruleId:r.id,name:r.draft.name,published:!!(r.published&&matchesScope(r.published,sample))}));
|
||||
let status=history?'history':rule?matchesScope(rule,sample)?'matched':'candidate':conflicts.length===1?'matched':'none';
|
||||
if(conflicts.length&&(rule||conflicts.length>1)){status='conflict';blockedReasons.push('流程与节点同时命中其他类别:'+conflicts.map(c=>c.name).join('、'));}
|
||||
if(rule&&scopesFor(rule).some(s=>/历史查看|未提供办理节点/.test(s.nodeName))){status='conflict';blockedReasons.push('分类含历史占位节点,请在调整匹配范围中修正。');}
|
||||
if(!captured.processVersion)blockedReasons.push('流程版本未提供,不能复用或生效配置。');
|
||||
recognition.valid=recognition.valid&&active.length<=1&&!!captured.processVersion;
|
||||
const fields=BUSINESS_FIELDS.map(key=>{const source=sources[key]||null,trace=recognition.fieldTrace.find(f=>f.key===key),candidates=recommended.candidates[key]||[],value=trace?.value??null;
|
||||
let state=!source&&candidates.length>1?'ambiguous':value===null||value===''?'missing':'recognized',reason=null;
|
||||
if(source?.type==='form'&&!captured.snapshot.fields.some(f=>f.path===source.path)){state='invalid';reason='所选来源字段不存在';}
|
||||
if(key==='orderNo'&&recognition.issues.some(s=>/主订单号|orderNo/.test(s))){state=state==='ambiguous'?'ambiguous':value==null?'missing':'invalid';reason='请核对表单主订单及标题订单';}
|
||||
if(key==='appDate'&&recognition.issues.some(s=>/日期/.test(s))||key==='quantity'&&recognition.issues.some(s=>/quantity 必须/.test(s))){state='invalid';reason='当前值不符合用途要求';}
|
||||
return {key,label:labels[key],state,source,value,candidates,reason};
|
||||
});
|
||||
const proposal={sampleId:captured.id,evidenceHash:captured.evidenceHash,processName:captured.processName,processVersion:captured.processVersion||null,metadata:{source:sample.source||null,nodeName:scopeCandidate?.nodeName||null,serialNum:sample.serialNum||null,receivedAt:sample.receivedAt||null,capturedAt:captured.capturedAt||null,timestampType:sample.timestampType||(history?'process-start':'received')},scopeCandidate,mapping:{basis,id:chosen?.id||null,draftVersion:draft?.version||0,activeVersion:active.length===1?active[0].version||null:null,sources},fields,recognition,classification:{status,ruleId:rule?.id||(!history&&conflicts.length===1?conflicts[0].ruleId:null)},effects:status==='matched'&&rule&&recognition.valid?previewEffects(rule,recognition.event,store):null,conflicts,blockedReasons:[...new Set(blockedReasons)],warnings};
|
||||
return JSON.parse(JSON.stringify(proposal));
|
||||
}
|
||||
module.exports={proposeMapping};
|
||||
@@ -0,0 +1,15 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const {adapters}=require('./catalog.cjs');
|
||||
const {fail}=require('./validation.cjs');
|
||||
const hash=value=>crypto.createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const keys=new Set(['orderNo','brief','appDate','customer','productLine','quantity','changeReason','changeContent','totalAmount']);
|
||||
function registry(store){const actual=store.all('field-adapters').filter(a=>a.status!=='superseded').map(a=>({...a,reference:false}));for(const a of actual)if(actual.filter(b=>b.processName===a.processName&&b.processVersion===a.processVersion).length>1){a.verified=false;a.status='conflict';}return [...structuredClone(adapters).filter(a=>!actual.some(b=>b.processName===a.processName&&b.processVersion===a.processVersion)).map(a=>({...a,verified:false,reference:true,status:'reference',label:a.processName+' '+a.processVersion+'(参考配置)'})),...actual];}
|
||||
function fields(store){const samples=store.all('capture-samples').map(({snapshot,...sample})=>({...sample,fields:snapshot.fields})),items=registry(store);return {samples,adapters:items,processes:require('./field-mappings.cjs').directory(store,items,samples)};}
|
||||
function recordCapture(store,{sample,snapshot,taskId}){
|
||||
if(sample?.demo||!snapshot||!Array.isArray(snapshot.fields)||snapshot.processVersion!==sample.processVersion)fail('捕获样本缺少一致的流程版本或实际字段证据。',409);
|
||||
const paths=new Set();for(const f of snapshot.fields){if(!f||typeof f.path!=='string'||!f.path||paths.has(f.path)||!Object.hasOwn(sample.fields||{},f.path)||JSON.stringify(sample.fields[f.path])!==JSON.stringify(f.value))fail('捕获字段冲突或与样本不一致。',409);paths.add(f.path);}
|
||||
const id=hash([taskId,sample,snapshot]);const captured={id,taskId,processName:sample.processName,processVersion:sample.processVersion,sample:structuredClone(sample),snapshot:structuredClone(snapshot),capturedAt:store.now(),provenance:'server-provider',evidenceHash:hash({sample,snapshot})};store.put('capture-samples',captured);return captured;
|
||||
}
|
||||
function saveAdapter(store,input,actor){return require('./field-mappings.cjs').saveLegacy(store,input,actor);}
|
||||
module.exports={registry,fields,recordCapture,saveAdapter};
|
||||
@@ -0,0 +1,140 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto');
|
||||
const {fail,publicationIssues,addresses}=require('./validation.cjs');
|
||||
const {scopesFor}=require('./scopes.cjs');
|
||||
const taskIdentity=require('./task-identity.cjs');
|
||||
const canonical=v=>Array.isArray(v)?v.map(canonical):v&&typeof v==='object'?Object.fromEntries(Object.keys(v).sort().map(k=>[k,canonical(v[k])])):v;
|
||||
const hash=v=>crypto.createHash('sha256').update(JSON.stringify(canonical(v))).digest('hex');
|
||||
const state=store=>typeof store?.get==='function'?store.get('restricted-test','main')?.value||null:null;
|
||||
function localPath(unc){
|
||||
if(typeof unc!=='string'||/[\x00-\x1f/:]/.test(unc)||!/^\\\\localhost\\[a-z]\$\\/i.test(unc)||unc.split('\\').some(p=>p==='.'||p==='..'||/[. ]$/.test(p)))fail('受限测试仅允许当前用户桌面的localhost共享子目录。',409);
|
||||
return unc[12]+':\\'+unc.slice(15);
|
||||
}
|
||||
function inside(root,target){const relative=path.win32.relative(root,target);return !relative.startsWith('..')&&!path.win32.isAbsolute(relative);}
|
||||
function realAncestor(target){let current=target;while(!fs.existsSync(current)){const parent=path.dirname(current);if(parent===current)fail('受限测试目录不可访问。',409);current=parent;}return fs.realpathSync(current);}
|
||||
function assertPath(store,directory,run=state(store)){
|
||||
if(!run)return;
|
||||
const root=localPath(run.archiveRoot),target=localPath(directory);
|
||||
if(!inside(root,target)||!inside(fs.realpathSync(root),realAncestor(target)))fail('受限测试归档超出固定桌面目录。',409);
|
||||
}
|
||||
function evidence(store,adapter){
|
||||
const captured=store.get('capture-samples',adapter.sampleId||'');
|
||||
if(!captured||captured.provenance!=='server-provider'||captured.sample?.demo||captured.evidenceHash!==adapter.evidenceHash||captured.processName!==adapter.processName||captured.processVersion!==adapter.processVersion)return false;
|
||||
const result=require('./field-mappings.cjs').evaluateMapping(store,{...adapter,version:adapter.version},captured,{relatedRules:[]});
|
||||
return result.valid;
|
||||
}
|
||||
function summary(store){const run=state(store);if(!run)return null;return {id:run.id,version:run.version,enabled:run.enabled,recipient:run.recipient,archiveRoot:run.archiveRoot,channelId:run.channelId,since:run.since,ruleCount:run.rules.length,readyCount:run.rules.filter(r=>validRule(store,r,run)).length,uncovered:run.uncovered};}
|
||||
function validRule(store,rule,run){return run.enabled&&hash(rule.adapterIds.map(id=>store.adapters().find(a=>a.id===id)))===run.adapterHashes[rule.id];}
|
||||
function executionRule(store,record){
|
||||
const run=state(store);if(!run)return record?.published||null;
|
||||
const rule=run.rules.find(r=>r.id===record?.id);return rule&&validRule(store,rule,run)?structuredClone(rule):null;
|
||||
}
|
||||
function save(store,input,actor){
|
||||
if(actor?.role!=='admin'||!actor.username)fail('仅管理员可以维护受限测试。',403);
|
||||
return store.transaction(()=>{
|
||||
const old=state(store),keys=['version','enabled','recipient','archiveRoot','channelId','ruleIds'];
|
||||
if(!input||Object.keys(input).some(k=>!keys.includes(k))||typeof input.enabled!=='boolean'||input.version!==(old?.version||0))fail('受限测试配置已变化,请刷新。',409);
|
||||
if(old){
|
||||
for(const key of ['recipient','archiveRoot','channelId'])if(input[key]!==undefined&&input[key]!==old[key])fail('受限测试目的地已固定,不能通过启停修改。',409);
|
||||
if(input.ruleIds&&hash([...input.ruleIds].sort())!==hash(old.rules.map(r=>r.id).sort()))fail('受限测试类别已固定。',409);
|
||||
const next={...old,enabled:input.enabled,version:old.version+1};
|
||||
if(next.enabled){assertPath(store,next.archiveRoot,next);if(next.rules.some(r=>!validRule(store,r,next)))fail('测试字段配置已变化,需要重新核验,不能直接恢复。',409);}
|
||||
store.put('restricted-test',{id:'main',value:next});store.audit(actor.username,next.enabled?'恢复受限测试':'暂停受限测试',next.id);return summary(store);
|
||||
}
|
||||
if(!input.enabled)fail('尚未建立受限测试配置。',409);
|
||||
const [recipient]=addresses([input.recipient]);if(!/^[\w.!#$%&'*+\/=?^`{|}~-]+@qq\.com$/i.test(recipient))fail('受限测试只允许一个QQ收件箱。',409);
|
||||
const local=localPath(input.archiveRoot),desktop=store.desktopRoot;
|
||||
if(!fs.existsSync(local)||!fs.statSync(local).isDirectory()||!inside(desktop,local)||path.win32.relative(desktop,local)===''||!inside(fs.realpathSync(desktop),fs.realpathSync(local)))fail('请选择当前用户桌面内已有的测试子目录。',409);
|
||||
if(typeof input.channelId!=='string'||!input.channelId||input.channelId.length>100)fail('请选择已验证的测试发件通道。',409);
|
||||
if(!Array.isArray(input.ruleIds)||!input.ruleIds.length||new Set(input.ruleIds).size!==input.ruleIds.length)fail('请选择测试类别。',409);
|
||||
const run={id:crypto.randomUUID(),version:1,enabled:true,recipient,archiveRoot:input.archiveRoot,channelId:input.channelId,since:store.now(),rules:[],uncovered:[],adapterHashes:{}};
|
||||
for(const id of input.ruleIds){
|
||||
const record=store.get('rules',id);if(!record)fail('测试类别不存在。',409);
|
||||
const draft=record.draft,adapters=store.adapters().filter(a=>a.verified&&!a.reference&&draft.adapterIds.includes(a.id)&&evidence(store,a));
|
||||
const covered=draft.processNames.filter(p=>adapters.some(a=>a.processName===p));
|
||||
run.uncovered.push(...draft.processNames.filter(p=>!covered.includes(p)).map(processName=>({categoryId:id,processName})));
|
||||
const rule={...structuredClone(draft),processNames:covered,scopes:scopesFor(draft).filter(s=>covered.includes(s.processName)),adapterIds:adapters.map(a=>a.id),status:'enabled',testRunId:run.id,testSince:run.since,testArchiveRoot:run.archiveRoot};
|
||||
if(!covered.length||!rule.scopes.length)fail('类别缺少已验证的真实字段证据:'+draft.name,409);
|
||||
assertRule(store,rule,run);
|
||||
const issues=publicationIssues(rule,adapters);if(issues.length)fail(issues.join(';'),409);
|
||||
if(run.rules.some(r=>require('./scopes.cjs').scopesOverlap(r,rule)))fail('测试类别存在流程节点冲突。',409);
|
||||
run.rules.push(rule);run.adapterHashes[id]=hash(rule.adapterIds.map(id=>store.adapters().find(a=>a.id===id)));
|
||||
}
|
||||
store.put('restricted-test',{id:'main',value:run});store.audit(actor.username,'建立受限测试',run.id+' '+run.rules.length+'类');return summary(store);
|
||||
});
|
||||
}
|
||||
function assertRule(store,rule,run=state(store)){
|
||||
if(!run){if(rule?.testRunId)fail('测试配置不存在,禁止按正式规则继续执行。',409);return;}
|
||||
if(!run.enabled||rule?.testRunId!==run.id||rule.testArchiveRoot!==run.archiveRoot)fail('受限测试已暂停或执行快照不一致。',409);
|
||||
const frozen=run.rules.find(r=>r.id===rule.id);if(frozen&&(!validRule(store,frozen,run)||hash(frozen)!==hash(rule)))fail('受限测试字段或规则快照已变化。',409);
|
||||
if(rule.to?.length!==1||rule.to[0]!==run.recipient||rule.cc?.length)fail('受限测试收件人必须为固定QQ且无抄送。',409);
|
||||
assertPath(store,rule.archiveDirectory,run);
|
||||
}
|
||||
function assertEvent(store,sample){const run=state(store);if(!run)return;
|
||||
const at=eventTime(store,sample);
|
||||
if(!run.enabled||sample?.demo||sample?.source!=='todo'||sample.configurationOnly||!Number.isFinite(Date.parse(sample.receivedAt))||Date.parse(at)<Date.parse(run.since)||Date.parse(sample.receivedAt)>Date.parse(store.now())+60000)fail('受限测试只处理启用基线之后或已明确纳入的当前真实待办通知。',409);
|
||||
}
|
||||
function assertOrder(store,order){assertRule(store,order?.ruleSnapshot);if(state(store)||order?.ruleSnapshot?.testRunId){assertEvent(store,order.sample||order.event);assertCurrentPresence(store,order.sample||order.event);for(const file of order.archive?.files||[])assertPath(store,file.path);}}
|
||||
function assertBatch(store,batch,config){
|
||||
const run=state(store);if(!run&&!batch.ruleSnapshot?.testRunId)return;
|
||||
assertRule(store,batch.ruleSnapshot,run);if(batch.testRunId!==run.id||batch.channelId!==run.channelId||config.channelId!==run.channelId||batch.to?.length!==1||batch.to[0]!==run.recipient||batch.cc?.length)fail('受限测试批次目的地与固定配置不一致。',409);
|
||||
for(const file of batch.attachments||[])assertPath(store,file.path,run);
|
||||
for(const id of batch.orderIds||[]){const order=store.get('orders',id);if(!order)fail('测试批次订单不存在。',409);assertOrder(store,order);}
|
||||
}
|
||||
function admissionSnapshot(value){const row=taskIdentity.normalize(value);return Object.fromEntries(['source','portalSource','taskId','instanceId','revision','processName','nodeName','processVersion','receivedAt'].filter(key=>Object.hasOwn(row,key)).map(key=>[key,row[key]]));}
|
||||
function eventTime(store,row){
|
||||
const run=state(store);if(!run)return row?.receivedAt;
|
||||
const entries=(run.currentBacklog||[]).filter(entry=>taskIdentity.sameTask(entry.snapshot,row));
|
||||
if(!entries.length)return row?.receivedAt;
|
||||
if(entries.length!==1||entries[0].testRunId!==run.id||hash(admissionSnapshot(row))!==entries[0].snapshotHash)fail('当前待办纳入证据已变化,须重新人工核验。',409);
|
||||
return entries[0].admittedAt;
|
||||
}
|
||||
function orderTime(store,order){return eventTime(store,order?.sample||order?.event);}
|
||||
function isAdmitted(store,row){const run=state(store);return !!run&&(run.currentBacklog||[]).some(entry=>taskIdentity.sameTask(entry.snapshot,row))&&(eventTime(store,row)!==undefined);}
|
||||
function eventInWindow(store,row,window){
|
||||
const at=eventTime(store,row);
|
||||
if(isAdmitted(store,row)){
|
||||
const current=require('./window.cjs').upcomingWindow(store.clock(),store.schedule(),store.calendar());
|
||||
return !!current&¤t.end===window.end&&Date.parse(at)<Date.parse(window.end);
|
||||
}
|
||||
return require('./window.cjs').inWindow(at,window);
|
||||
}
|
||||
function orderInWindow(store,order,window){return eventInWindow(store,order?.sample||order?.event,window);}
|
||||
function assertCurrentPresence(store,row){
|
||||
const run=state(store),entry=(run?.currentBacklog||[]).find(item=>taskIdentity.sameTask(item.snapshot,row));if(!entry)return;
|
||||
const scan=store.get('current-task-scans',entry.scanConnectionId),matches=scan?.rows.filter(observed=>taskIdentity.sameTask(observed,row))||[];
|
||||
if(!scan||scan.provenance!=='server-provider'||Date.parse(store.now())-Date.parse(scan.finishedAt)>300000||matches.length!==1||taskIdentity.fingerprint(matches[0])!==entry.scanRowHash)fail('纳入任务已离开原通知节点、扫描已过期或当前内容变化,不能冻结或发送。',409);
|
||||
}
|
||||
// Called only on the server after an actual provider list read. This is not
|
||||
// exposed through HTTP or accepted from the incoming order's metadata.
|
||||
function recordCurrentScan(store,{connectionId,rows,startedAt,finishedAt}){
|
||||
if(typeof connectionId!=='string'||!Array.isArray(rows)||![startedAt,finishedAt].every(at=>Number.isFinite(Date.parse(at)))||Date.parse(startedAt)>Date.parse(finishedAt)||Date.parse(finishedAt)>Date.parse(store.now())+60000)fail('当前待办扫描证据无效。',409);
|
||||
const value={id:connectionId,connectionId,rows:structuredClone(rows),startedAt,finishedAt,provenance:'server-provider'};
|
||||
store.put('current-task-scans',value);return value;
|
||||
}
|
||||
function admitCurrent(store,rows,actor){
|
||||
if(actor?.role!=='admin'||!actor.username)fail('仅管理员可以纳入当前待办。',403);
|
||||
return store.transaction(()=>{
|
||||
const run=state(store);if(!run?.enabled||!Array.isArray(rows)||!rows.length)fail('需要已启用受限测试及真实当前待办。',409);
|
||||
const entries=[],keys=new Set();
|
||||
for(const raw of rows){
|
||||
const row=taskIdentity.normalize(raw),key=taskIdentity.taskIdentity(row),scan=store.get('current-task-scans',row.connectionId);
|
||||
if(row.source!=='todo'||row.demo||row.configurationOnly||!Number.isFinite(Date.parse(row.receivedAt))||Date.parse(row.receivedAt)>Date.parse(store.now())+60000||keys.has(key))fail('只能纳入唯一真实当前通知任务。',409);
|
||||
keys.add(key);
|
||||
const observed=scan?.rows.filter(item=>taskIdentity.sameTask(item,row))||[];
|
||||
if(!scan||scan.provenance!=='server-provider'||Date.parse(store.now())-Date.parse(scan.finishedAt)>300000||observed.length!==1||taskIdentity.fingerprint(observed[0])!==taskIdentity.fingerprint(row))fail('缺少五分钟内完整提供器扫描的相同唯一待办证据。',409);
|
||||
const rules=run.rules.filter(rule=>validRule(store,rule,run)&&require('./scopes.cjs').matchesScope(rule,row));
|
||||
if(rules.length!==1||!store.adapters().some(adapter=>rules[0].adapterIds.includes(adapter.id)&&adapter.processName===row.processName&&adapter.processVersion===row.processVersion))fail('当前任务未命中已冻结的确切流程、节点和版本。',409);
|
||||
taskIdentity.assertUnprocessedReceipt(store,row);
|
||||
const order=taskIdentity.lookup(store,'orders',row),task=taskIdentity.lookup(store,'execution-tasks',row);
|
||||
if(order&&(order.archive||require('./migrations.cjs').frozen(store,order))||task&&(['archiving','sent','sending','unknown'].includes(task.status)||task.conflict||task.missedWindow)||store.all('archive-intents').some(intent=>order&&intent.orderId===order.id||task&&intent.taskId===task.id))fail('已有归档、冻结、冲突或结果不确定的任务不能纳入。',409);
|
||||
const snapshot=admissionSnapshot(row),existing=(run.currentBacklog||[]).find(entry=>taskIdentity.sameTask(entry.snapshot,row));
|
||||
if(existing){if(existing.snapshotHash!==hash(snapshot))fail('纳入清单已固定,不能修改任务证据。',409);entries.push(existing);continue;}
|
||||
if(run.currentBacklog)fail('当前待办纳入清单已固定,不能新增任务。',409);
|
||||
entries.push({id:key,taskKey:key,testRunId:run.id,snapshot,snapshotHash:hash(snapshot),scanRowHash:taskIdentity.fingerprint(row),ruleId:rules[0].id,originalReceivedAt:row.receivedAt,admittedAt:store.now(),scanConnectionId:scan.connectionId,scanStartedAt:scan.startedAt,scanFinishedAt:scan.finishedAt});
|
||||
}
|
||||
if(!run.currentBacklog){run.currentBacklog=entries;run.enrolledAt=store.now();store.put('restricted-test',{id:'main',value:run});store.audit(actor.username,'纳入当前未处理待办',run.id+' '+entries.length+'项');}
|
||||
return structuredClone(entries);
|
||||
});
|
||||
}
|
||||
module.exports={state,summary,save,executionRule,assertPath,assertRule,assertEvent,assertOrder,assertBatch,recordCurrentScan,admitCurrent,eventTime,orderTime,isAdmitted,eventInWindow,orderInWindow};
|
||||
@@ -0,0 +1,20 @@
|
||||
'use strict';
|
||||
// Missing scopes means a legacy rule; preserve its original array semantics.
|
||||
function scopesFor(rule){
|
||||
if(Object.hasOwn(rule,'scopes')&&rule.scopes!==undefined)return Array.isArray(rule.scopes)?rule.scopes:[];
|
||||
return (rule.processNames||[]).flatMap(processName=>(rule.nodeNames||[]).map(nodeName=>({processName,nodeName})));
|
||||
}
|
||||
function normalizeScopes(rows){
|
||||
const fail=()=>{throw Object.assign(Error('流程节点配对范围无效,请逐行选择完整流程和节点(最多100行)。'),{status:400});};
|
||||
if(!Array.isArray(rows)||rows.length>100)fail();
|
||||
const seen=new Set(),result=[];
|
||||
for(const row of rows){
|
||||
if(!row||typeof row!=='object'||Array.isArray(row)||Object.keys(row).some(k=>!['processName','nodeName'].includes(k))||['processName','nodeName'].some(k=>typeof row[k]!=='string'||!row[k].trim()||row[k].length>250||/[\x00-\x1f]/.test(row[k])))fail();
|
||||
const value={processName:row.processName.trim(),nodeName:row.nodeName.trim()},key=JSON.stringify(value);
|
||||
if(!seen.has(key)){seen.add(key);result.push(value);}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
const matchesScope=(rule,event)=>scopesFor(rule).some(row=>row.processName===event.processName&&row.nodeName===event.nodeName);
|
||||
const scopesOverlap=(a,b)=>scopesFor(a).some(row=>matchesScope(b,row));
|
||||
module.exports={scopesFor,normalizeScopes,matchesScope,scopesOverlap};
|
||||
@@ -0,0 +1,35 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs'),crypto=require('node:crypto'),XLSX=require('xlsx');
|
||||
const WORKSHEET='订单通知书邮件信息';
|
||||
const HEADERS=['序号','服务器存档地址','订单评审流程','邮件命名','邮件正文','电子流状态','收件人'];
|
||||
const normalize=value=>String(value??'').normalize('NFKC').trim();
|
||||
function mergedCell(sheet,address){
|
||||
const point=XLSX.utils.decode_cell(address),regions=(sheet['!merges']||[]).filter(m=>point.r>=m.s.r&&point.r<=m.e.r&&point.c>=m.s.c&&point.c<=m.e.c);
|
||||
if(regions.length>1)throw Error('Overlapping source merges: '+address);
|
||||
const region=regions[0],anchor=region?XLSX.utils.encode_cell(region.s):address;
|
||||
return {cell:address,anchor,merge:region?XLSX.utils.encode_range(region):null,value:String(sheet[anchor]?.v??'')};
|
||||
}
|
||||
function splitNames(value){return [...new Set(normalize(value).split(/[\/+\r\n]+/).map(v=>v.trim().replace(/^[“”"'「」]+|[“”"'「」]+$/g,'').trim()).filter(Boolean))];}
|
||||
function parseWorkbook(workbook,{source='',sourceSha256=''}={}){
|
||||
const sheet=workbook.Sheets?.[WORKSHEET];if(!sheet)throw Error('Missing source worksheet: '+WORKSHEET);
|
||||
for(let c=0;c<HEADERS.length;c++)if(normalize(sheet[XLSX.utils.encode_cell({r:0,c})]?.v)!==HEADERS[c])throw Error('Unexpected source header: '+XLSX.utils.encode_cell({r:0,c}));
|
||||
// Notes and screenshots continue below the category table in the original
|
||||
// sheet. Reject another category-shaped row, while retaining those notes.
|
||||
const lastRow=Math.max(16,...Object.keys(sheet).filter(key=>/^[A-Z]+\d+$/.test(key)).map(key=>XLSX.utils.decode_cell(key).r+1));
|
||||
for(let row=17;row<=lastRow;row++){
|
||||
const number=normalize(sheet['A'+row]?.v),process=normalize(sheet['C'+row]?.v),title=normalize(sheet['D'+row]?.v),node=normalize(sheet['F'+row]?.v);
|
||||
if((/^\d+$/.test(number)&&Number(number)>0&&(title||node))||(/【[^】]+】/.test(title)&&process))throw Error('Unexpected extra source category at row '+row);
|
||||
}
|
||||
const rules=[];
|
||||
for(let row=2;row<=16;row++){
|
||||
const process=mergedCell(sheet,'C'+row),node=mergedCell(sheet,'F'+row),nameCell=mergedCell(sheet,'D'+row);
|
||||
const name=/【([^】]+)】/.exec(nameCell.value)?.[1]?.trim(),processNames=splitNames(process.value),nodeNames=splitNames(node.value);
|
||||
if(!name||!processNames.length||!nodeNames.length)throw Error('Incomplete source category: '+(!nodeNames.length?'F'+row:'C/D'+row));
|
||||
if(Number(sheet['A'+row]?.v)!==row-1)throw Error('Unexpected source sequence: A'+row);
|
||||
rules.push({name,sourceRow:row,processNames,nodeNames,scopes:processNames.flatMap(processName=>nodeNames.map(nodeName=>({processName,nodeName}))),provenance:{process,node,name:nameCell}});
|
||||
}
|
||||
if(new Set(rules.map(r=>r.name)).size!==15)throw Error('Source must contain 15 unique categories');
|
||||
return {source,sourceSha256,worksheet:WORKSHEET,rules};
|
||||
}
|
||||
function readSourceWorkbook(file){const bytes=fs.readFileSync(file);return parseWorkbook(XLSX.read(bytes,{type:'buffer'}),{source:file,sourceSha256:crypto.createHash('sha256').update(bytes).digest('hex')});}
|
||||
module.exports={WORKSHEET,HEADERS,normalize,mergedCell,splitNames,parseWorkbook,readSourceWorkbook};
|
||||
@@ -0,0 +1,29 @@
|
||||
'use strict';
|
||||
|
||||
// Actions describe completed, evidence-backed steps; callers must never accept a
|
||||
// target state from an HTTP request as authority to bypass these transitions.
|
||||
const transitions={
|
||||
order:{
|
||||
identified:{prepare:'preparing',block:'blocked'},
|
||||
preparing:{archive:'archived',block:'blocked'},
|
||||
archived:{queue:'pending',block:'blocked'},
|
||||
pending:{batch:'batched',block:'blocked'},
|
||||
batched:{sent:'sent',unknown:'unknown',block:'blocked',retry:'pending'},
|
||||
blocked:{retry:'preparing'},
|
||||
unknown:{resolve_sent:'sent',retry:'pending'},
|
||||
sent:{}
|
||||
},
|
||||
batch:{
|
||||
prepared:{send:'sending',fail:'failed',cancel:'cancelled'},
|
||||
sending:{sent:'sent',unknown:'unknown',fail:'failed'},
|
||||
unknown:{resolve_sent:'sent',retry:'cancelled'},
|
||||
failed:{},sent:{},cancelled:{}
|
||||
}
|
||||
};
|
||||
function transition(kind,from,action){
|
||||
const group=Object.hasOwn(transitions,kind)?transitions[kind]:null;
|
||||
const actions=group&&Object.hasOwn(group,from)?group[from]:null;
|
||||
if(!actions||!Object.hasOwn(actions,action))throw Object.assign(new Error(`不允许的状态操作:${kind}/${from}/${action}`),{status:409,statusCode:409});
|
||||
return actions[action];
|
||||
}
|
||||
module.exports={transition};
|
||||
@@ -0,0 +1,335 @@
|
||||
'use strict';
|
||||
const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');
|
||||
const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');
|
||||
const {seedRules}=require('./catalog.cjs');const registry=require('./registry.cjs');const {previewMatch,describeRule}=require('./matching.cjs');
|
||||
const {buildBatch}=require('./batch.cjs');const {transition}=require('./state.cjs');
|
||||
const {applyBodyTemplate}=require('./template.cjs');
|
||||
const {fail,validateRule,publicationIssues}=require('./validation.cjs');
|
||||
const {windowForCutoff,upcomingWindow,inWindow}=require('./window.cjs');
|
||||
const {matchesScope,scopesOverlap}=require('./scopes.cjs');
|
||||
const {initialNotification,ordersForMode}=require('./huizhou.cjs');
|
||||
const {modeOf,delivery,updateDelivery}=require('./delivery.cjs');
|
||||
const taskIdentity=require('./task-identity.cjs');
|
||||
const eligibility=require('./restricted-test.cjs');
|
||||
const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value;
|
||||
const digest=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
|
||||
const copy=value=>structuredClone(value);
|
||||
const BASE_CAPABILITIES={liveTodo:false,pdfExport:false,automaticArchive:false};
|
||||
function validDate(value){return typeof value==='string'&&/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)&&Number.isFinite(Date.parse(value));}
|
||||
class RuleStore{
|
||||
constructor(dir,{clock=()=>new Date(),capabilities={},seedOverrides=[],schedule=()=>({times:['11:00','17:00'],weekends:false}),calendar=()=>[],desktopRoot=path.join(require('node:os').homedir(),'Desktop')}={}){
|
||||
this.desktopRoot=desktopRoot;
|
||||
this.clock=clock;this.schedule=schedule;this.calendar=calendar;this.capabilities={...BASE_CAPABILITIES,...capabilities};
|
||||
try{
|
||||
fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});
|
||||
this.db=new DatabaseSync(path.join(dir,'rules.sqlite'));
|
||||
this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
|
||||
CREATE TABLE IF NOT EXISTS records(kind TEXT NOT NULL,id TEXT NOT NULL,payload BLOB NOT NULL,PRIMARY KEY(kind,id));`);
|
||||
this.transaction(()=>{
|
||||
if(!this.get('settings','main'))this.put('settings',{id:'main',version:1,enabled:false,channelId:'',maxMessageBytes:20971520});
|
||||
const settings=this.get('settings','main');if(settings.processingEnabled===undefined)this.put('settings',{...settings,processingEnabled:settings.enabled,processingSince:settings.enabled?this.now():null});
|
||||
for(const rule of seedRules())if(!this.get('rules',rule.id)){
|
||||
const override=seedOverrides.find(r=>r.id===rule.id);
|
||||
const draft=override?validateRule({...rule,...override},rule):rule;
|
||||
this.put('rules',{id:rule.id,draft:{...draft,status:'draft'},published:null,trialVersion:null,trialDemo:null});
|
||||
}
|
||||
for(const batch of this.all('batches')){
|
||||
if(batch.manual&&batch.status==='prepared'){
|
||||
batch.status='failed';batch.version=(batch.version||1)+1;batch.error='人工补发在发送前中断,可再次受控补发。';this.put('batches',batch);this.updateBatchOrders(batch,'pending',batch.error);
|
||||
}
|
||||
if(batch.status==='sending'){
|
||||
batch.status='unknown';batch.version=(batch.version||1)+1;batch.error='服务重启,发信结果待人工核实。';this.put('batches',batch);
|
||||
this.updateBatchOrders(batch,'unknown',batch.error);
|
||||
}
|
||||
}
|
||||
});
|
||||
}catch(error){try{this.db?.close();}catch{}this.vault?.destroy();throw error;}
|
||||
}
|
||||
now(){return this.clock().toISOString();}
|
||||
restrictedTest(){return require('./restricted-test.cjs').summary(this);}
|
||||
saveRestrictedTest(input,actor){return require('./restricted-test.cjs').save(this,input,actor);}
|
||||
executionRule(record){return require('./restricted-test.cjs').executionRule(this,record);}
|
||||
providersReady(){return ['liveTodo','pdfExport','automaticArchive'].every(key=>this.capabilities[key]===true);}
|
||||
adapters(){return registry.registry(this);}
|
||||
fields(){return registry.fields(this);}
|
||||
recordCapture(input){return registry.recordCapture(this,input);}
|
||||
saveAdapter(input,actor){return registry.saveAdapter(this,input,actor);}
|
||||
proposeMapping(input){return require('./recognition-proposal.cjs').proposeMapping(this,input);}
|
||||
saveMapping(input,actor){return require('./field-mappings.cjs').saveMapping(this,input,actor);}
|
||||
checkMapping(input,actor){return require('./field-mappings.cjs').checkMapping(this,input,actor);}
|
||||
activateMapping(input,actor){return require('./field-mappings.cjs').activateMapping(this,input,actor);}
|
||||
capturedPreview(sampleId){const captured=this.get('capture-samples',sampleId);if(!captured||captured.provenance!=='server-provider')fail('真实捕获样本不存在。',404);const result=this.preview(captured.sample);if(result.valid){const record=this.get('rules',result.ruleId);record.trialSampleId=sampleId;this.put('rules',record);}return result;}
|
||||
previewUntrusted(sample){return previewMatch(this.all('rules').map(r=>r.draft),this.adapters(),sample);}
|
||||
trial(id,input){return require('./trial.cjs').trial(this,id,input);}
|
||||
|
||||
transaction(work){const depth=this.transactionDepth||0,savepoint='rules_nested_'+depth;this.db.exec(depth?'SAVEPOINT '+savepoint:'BEGIN IMMEDIATE');this.transactionDepth=depth+1;try{const result=work();this.db.exec(depth?'RELEASE SAVEPOINT '+savepoint:'COMMIT');return result;}catch(error){if(depth){this.db.exec('ROLLBACK TO SAVEPOINT '+savepoint);this.db.exec('RELEASE SAVEPOINT '+savepoint);}else this.db.exec('ROLLBACK');throw error;}finally{this.transactionDepth=depth;}}
|
||||
get(kind,id){const row=this.db.prepare('SELECT payload FROM records WHERE kind=? AND id=?').get(kind,id);return row?this.vault.decode(kind+':'+id,row.payload):null;}
|
||||
all(kind){return this.db.prepare('SELECT id,payload FROM records WHERE kind=? ORDER BY rowid').all(kind).map(r=>this.vault.decode(kind+':'+r.id,r.payload));}
|
||||
put(kind,value){this.db.prepare('INSERT INTO records VALUES(?,?,?) ON CONFLICT(kind,id) DO UPDATE SET payload=excluded.payload').run(kind,value.id,this.vault.encode(kind+':'+value.id,value));return value;}
|
||||
audit(actor,action,detail){this.put('audit',{id:crypto.randomUUID(),at:this.now(),actor:String(actor||'系统'),action,detail});}
|
||||
settings(){const {id,...settings}=this.get('settings','main');return {...settings,processingEnabled:settings.processingEnabled??settings.enabled,processingSince:settings.processingSince??null};}
|
||||
saveSettings(input,actor){return this.transaction(()=>{
|
||||
const old=this.settings();
|
||||
const testing=this.restrictedTest();if(testing&&input?.channelId!==testing.channelId)fail('受限测试发件通道已固定。',409);
|
||||
if(!input||Object.keys(input).some(k=>!['version','enabled','processingEnabled','processingSince','channelId','maxMessageBytes'].includes(k))||input.version!==old.version)fail('设置已变化,请刷新。',409);
|
||||
if(typeof input.enabled!=='boolean'||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxMessageBytes)||input.maxMessageBytes<1024||input.maxMessageBytes>100*1024*1024)fail('邮箱或邮件大小限制无效。');
|
||||
const run=this.get('restricted-test','main')?.value;
|
||||
const restrictedIntent=testing?.enabled&&testing.readyCount>0&&testing.readyCount===testing.ruleCount&&testing.recipient==='2639266652@qq.com'&&run.rules.every(rule=>rule.to?.length===1&&rule.to[0]==='2639266652@qq.com'&&rule.cc?.length===0&&rule.attachPdf===false);
|
||||
if(input.enabled&&(!input.channelId||!this.providersReady()&&!restrictedIntent))fail('待办接入、PDF 导出与自动归档尚未全部联调,暂不能启用自动发送。',409);
|
||||
if(input.processingEnabled!==undefined&&typeof input.processingEnabled!=='boolean')fail('自动处理开关无效。');
|
||||
const processingEnabled=input.processingEnabled??old.processingEnabled;const processingSince=processingEnabled&&!old.processingEnabled?this.now():old.processingSince;
|
||||
this.put('settings',{...input,processingEnabled,processingSince,id:'main',version:old.version+1});this.audit(actor,'保存分类通知设置',input.enabled?'已启用':'已暂停');return this.settings();
|
||||
});}
|
||||
queryRevision(){return Number(this.db.prepare('SELECT total_changes() AS revision').get().revision);}
|
||||
snapshot({includeRecords=true}={}){
|
||||
const adapters=this.adapters(),rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',activationVersion:record.activationVersion||0,hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,mappingIssue:record.mappingIssue||null,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,adapters)}));
|
||||
const restrictedTest=typeof this.restrictedTest==='function'?this.restrictedTest():null;for(const rule of rules)if(restrictedTest){const active=typeof this.executionRule==='function'?this.executionRule({id:rule.id}):null;rule.testStatus=active?'enabled':'paused';}
|
||||
return {rules,restrictedTest,adapters,orders:includeRecords?this.all('orders').reverse():[],batches:includeRecords?this.all('batches').reverse():[],settings:this.settings(),audit:includeRecords?this.all('audit').slice(-100).reverse():[],capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())};
|
||||
}
|
||||
saveRule(input,actor){return this.transaction(()=>{
|
||||
const record=this.get('rules',input?.id);if(!record)fail('规则不存在。',404);
|
||||
this.put('rule-history',{id:record.id+':'+record.draft.version,rule:copy(record.draft),at:this.now(),actor});
|
||||
record.draft=validateRule(input,record.draft);record.trialVersion=null;record.trialDemo=null;record.trialSampleId=null;this.put('rules',record);
|
||||
this.audit(actor,'保存规则草稿',record.id+' v'+record.draft.version);return {...record.draft,explanation:describeRule(record.draft)};
|
||||
});}
|
||||
preview(sample){
|
||||
const records=this.all('rules');const result=previewMatch(records.map(r=>r.draft),this.adapters(),sample);
|
||||
if(result.valid&&result.ruleId){const record=records.find(r=>r.id===result.ruleId);if(record){record.trialVersion=record.draft.version;record.trialDemo=sample.demo===true;this.put('rules',record);}}
|
||||
return result;
|
||||
}
|
||||
publish(id,input,actor){return this.transaction(()=>{
|
||||
if(this.restrictedTest()?.enabled)fail('受限测试运行期间不能发布正式分类规则;请先暂停测试并重新检查真实通知。',409);
|
||||
const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
|
||||
if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
|
||||
const issues=publicationIssues(record.draft,this.adapters());
|
||||
if(record.trialVersion!==record.draft.version)issues.push('请先用真实结构样本试运行当前草稿');
|
||||
if(record.trialDemo!==false)issues.push('演示样本仅用于理解字段,发布前请校验真实业务样本');
|
||||
const overlaps=this.all('rules').filter(r=>r.id!==id&&r.published?.status==='enabled'&&scopesOverlap(r.published,record.draft));
|
||||
if(overlaps.length)issues.push('与已启用规则存在流程和节点冲突:'+overlaps.map(r=>r.draft.name).join('、'));
|
||||
if(issues.length)fail(issues.join(';'),409);
|
||||
record.published={...copy(record.draft),status:'enabled',publishedAt:this.now()};record.mappingIssue=null;record.publicationSampleId=record.trialSampleId;record.publicationAdaptersHash=digest(record.published.adapterIds.map(id=>this.adapters().find(a=>a.id===id)));record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);
|
||||
this.put('rule-history',{id:record.id+':'+record.draft.version,rule:copy(record.published),at:this.now(),actor});this.audit(actor,'发布规则',id+' v'+record.draft.version);
|
||||
return this.snapshot().rules.find(r=>r.id===id);
|
||||
});}
|
||||
pause(id,input,actor){return this.transaction(()=>{
|
||||
const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
|
||||
if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
|
||||
if(input.activationVersion!==undefined&&input.activationVersion!==(record.activationVersion||0))fail('启停状态已变化,请刷新。',409);
|
||||
if(record.published)record.published.status='paused';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'暂停规则',id);return this.snapshot().rules.find(r=>r.id===id);
|
||||
});}
|
||||
resume(id,input,actor){return this.transaction(()=>{
|
||||
const record=this.get('rules',id);if(!record?.published)fail('此分类尚未发布,请先保存并检查真实订单,再发布启用。',409);
|
||||
if(input?.version!==record.draft.version||input.publishedVersion!==record.published.version||input.activationVersion!==(record.activationVersion||0))fail('规则或启停状态已变化,请刷新。',409);
|
||||
const sample=this.get('capture-samples',record.publicationSampleId||record.trialSampleId||'');
|
||||
const issues=publicationIssues(record.published,this.adapters());
|
||||
if(record.publicationAdaptersHash!==digest(record.published.adapterIds.map(id=>this.adapters().find(a=>a.id===id))))issues.push('BPM 信息识别配置已变化,请重新检查并发布');
|
||||
if(!sample||sample.provenance!=='server-provider'||!previewMatch([record.published],this.adapters(),sample.sample).valid)issues.push('已发布版本需要重新检查真实订单识别结果');
|
||||
const overlaps=this.all('rules').filter(r=>r.id!==id&&r.published?.status==='enabled'&&scopesOverlap(r.published,record.published));
|
||||
if(overlaps.length)issues.push('与其他启用分类的流程节点冲突');
|
||||
if(issues.length)fail(issues.join(';'),409);
|
||||
record.published.status='enabled';record.activationVersion=(record.activationVersion||0)+1;this.put('rules',record);this.audit(actor,'启用已发布规则',id+' v'+record.published.version);return this.snapshot().rules.find(r=>r.id===id);
|
||||
});}
|
||||
matchingPublications(sample){
|
||||
const rules=this.all('rules').map(r=>this.executionRule(r)).filter(Boolean);
|
||||
const enabled=rules.filter(r=>r.status==='enabled');
|
||||
const hasEnabledMatch=enabled.some(r=>matchesScope(r,sample));
|
||||
return hasEnabledMatch?enabled:rules;
|
||||
}
|
||||
ingest(sample,actor){return this.transaction(()=>{
|
||||
require('./restricted-test.cjs').assertEvent(this,sample);
|
||||
if(sample?.demo)fail('演示样本仅用于试运行,不能创建正式任务。');
|
||||
if(!sample||['connectionId','source','instanceId','taskId'].some(k=>!['string','number'].includes(typeof sample[k])||!String(sample[k]).trim()||String(sample[k]).length>250)||sample.revision!==undefined&&sample.revision!==null&&!['string','number'].includes(typeof sample.revision))fail('缺少来源、流程实例或通知任务标识。');
|
||||
sample=taskIdentity.normalize(sample);taskIdentity.assertUnprocessedReceipt(this,sample);
|
||||
const taskKey=taskIdentity.taskIdentity(sample),old=taskIdentity.lookup(this,'orders',sample);
|
||||
const id=old?.id||taskKey,sourceHash=digest(sample);
|
||||
if(old){if(!taskIdentity.equivalent(old,sample))fail('相同通知任务的内容、节点或业务修订已变化,请人工核实来源证据。',409);return old;}
|
||||
const active=this.matchingPublications(sample);
|
||||
const result=previewMatch(active,this.adapters(),sample),rule=active.find(r=>r.id===result.ruleId);
|
||||
const ready=this.providersReady(),enabled=rule?.status==='enabled';
|
||||
if(rule)require('./restricted-test.cjs').assertRule(this,rule);
|
||||
const order={id,taskKey,sourceHash,event:result.event||copy(sample),sample:copy(sample),ruleSnapshot:rule?copy(rule):null,categoryId:result.categoryId||rule?.categoryId||'',status:result.valid&&ready&&enabled?'identified':'blocked',error:result.valid?(!enabled?'该类别规则已暂停。':ready?null:'待办接入、PDF 导出和自动归档待联调。'):result.issues.join(';'),ingestedAt:this.now(),updatedAt:this.now(),archive:null,batchId:null,trace:result};
|
||||
order.notifications={huizhou:initialNotification(rule,order.event)};
|
||||
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
|
||||
const eligibleAt=eligibility.eventTime(this,sample);
|
||||
if(window&&validDate(eligibleAt)&&Date.parse(eligibleAt)<Date.parse(window.start)&&!eligibility.isAdmitted(this,sample)){order.status='ignored';order.error='早于当前处理时段的历史订单,不归档、不补发。';}
|
||||
const frozen=this.all('batches').find(b=>b.categoryId===order.categoryId&&b.window&&eligibility.eventInWindow(this,sample,b.window));
|
||||
if(frozen){order.status='blocked';order.blockedByBatchId=frozen.id;order.error='本接收时段的类别已冻结,新增订单须负责人核验,不能混入已冻结邮件。';this.put('orders',order);this.recordIssue('late:'+order.id,{component:'rules',error:order.error,batchId:frozen.id,orderIds:[order.id]});}
|
||||
this.put('orders',order);this.audit(actor,'识别订单任务',id);return order;
|
||||
});}
|
||||
recordArchive(id,evidence,actor,expected){return this.transaction(()=>{
|
||||
if(!this.capabilities.automaticArchive)fail('自动归档接入待联调。',409);
|
||||
const order=this.get('orders',id);if(!order)fail('订单任务不存在。',404);
|
||||
require('./restricted-test.cjs').assertOrder(this,{...order,archive:evidence});
|
||||
const stale=expected&&!require('./migrations.cjs').archiveContextMatches(this,order,expected);
|
||||
if(!stale){
|
||||
if(!['identified','preparing'].includes(order.status))fail('当前状态不允许记录归档结果。',409);
|
||||
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
|
||||
if(window&&Date.parse(eligibility.orderTime(this,order))<Date.parse(window.start)&&!eligibility.isAdmitted(this,order.sample||order.event))fail('该订单已超出当前时段,不再自动归档或补发。',409);
|
||||
}
|
||||
if(!evidence||!validDate(evidence.archivedAt)||!Array.isArray(evidence.files)||!evidence.files.length||evidence.files.some(f=>!f||typeof f.name!=='string'||!f.name||/[\\/\x00-\x1f]/.test(f.name)||typeof f.path!=='string'||!path.win32.isAbsolute(f.path)||! /^[a-f0-9]{64}$/i.test(f.sha256)||!Number.isSafeInteger(f.size)||f.size<1||!['pdf','notice'].includes(f.kind)))fail('归档证据不完整。');
|
||||
if(stale){
|
||||
// Keep the old operation's receipt under its original context. It cannot
|
||||
// satisfy a newer generation or change that generation's processing state.
|
||||
order.archiveHistory=[...(order.archiveHistory||[]),{...copy(expected),evidence:copy(evidence),stale:true}];
|
||||
this.put('orders',order);this.audit(actor,'保留过期归档回执',id+' generation '+expected.generation);return null;
|
||||
}
|
||||
if(order.status==='identified')order.status=transition('order',order.status,'prepare');
|
||||
order.status=transition('order',order.status,'archive');order.archive=copy(evidence);
|
||||
if(order.ruleSnapshot.attachPdf&&!evidence.files.some(f=>f.kind==='pdf')){order.status='blocked';order.error='缺少本类别要求的电子流 PDF。';}
|
||||
else {order.status=transition('order',order.status,'queue');order.error=null;}
|
||||
order.updatedAt=this.now();this.put('orders',order);this.audit(actor,'记录执行器归档结果',id);return order;
|
||||
});}
|
||||
retryArchive(id,note,actor){return this.transaction(()=>{
|
||||
if(typeof note!=='string'||note.trim().length<5||note.length>2000)fail('请填写至少5字修复依据。');
|
||||
if(!this.capabilities.automaticArchive)fail('自动归档接入待联调。',409);
|
||||
const order=this.get('orders',id);if(!order||!order.ruleSnapshot||order.status!=='blocked'||order.blockedByBatchId||require('./migrations.cjs').frozen(this,order))fail('当前任务不能重试归档。',409);
|
||||
order.status=transition('order',order.status,'retry');order.error=null;order.updatedAt=this.now();this.put('orders',order);this.audit(actor,'重试归档',id+':'+note.trim());return order;
|
||||
});}
|
||||
previewMigration(id,input){return require('./migrations.cjs').preview(this,id,input);}
|
||||
applyMigration(id,input,actor){return require('./migrations.cjs').apply(this,id,input,actor);}
|
||||
recheck(id,input,actor){return this.transaction(()=>{
|
||||
if(typeof input?.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请填写至少5字的重新识别依据。');
|
||||
const order=this.get('orders',id);
|
||||
if(!order||order.blockedByBatchId||require('./migrations.cjs').frozen(this,order)||!['blocked','identified','preparing','archived','pending'].includes(order.status))fail('仅未进入批次的待处理订单可以重新识别。',409);
|
||||
const published=this.matchingPublications(order.sample);
|
||||
const result=previewMatch(published,this.adapters(),order.sample),rule=published.find(r=>r.id===result.ruleId);
|
||||
require('./restricted-test.cjs').assertEvent(this,order.sample);if(rule)require('./restricted-test.cjs').assertRule(this,rule);
|
||||
if(!result.valid||rule?.status!=='enabled')fail(result.issues.join(';')||'对应规则尚未启用。',409);
|
||||
order.event=result.event;order.ruleSnapshot=copy(rule);order.categoryId=rule.categoryId;order.trace=result;
|
||||
if(order.notifications)order.notifications.huizhou=initialNotification(rule,order.event);
|
||||
require('./migrations.cjs').invalidateArchive(order);order.status=this.providersReady()?'identified':'blocked';
|
||||
order.error=order.status==='blocked'?'待办接入、PDF 导出和自动归档待联调。':null;order.updatedAt=this.now();
|
||||
this.put('orders',order);require('./migrations.cjs').synchronizeTasks(this,order);this.audit(actor,'应用当前规则重新识别',id+':'+input.note.trim());return order;
|
||||
});}
|
||||
discoveryBlockers(cutoff,allowed=()=>true){
|
||||
const blockers=(this.deliveryBlockers?.(allowed)||[]).map(id=>'连接 '+id+' 本地执行线索尚未交付。');
|
||||
if(!this.executionSources)return blockers;
|
||||
const pendingSources=new Set([...this.all('execution-discoveries'),...this.all('execution-discovery-runs')].filter(hint=>hint.status==='pending'&&allowed(hint.connectionId)).map(hint=>hint.connectionId));
|
||||
for(const id of pendingSources)blockers.push('连接 '+id+' 完整对账线索尚未处理。');
|
||||
if(this.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。');
|
||||
const window=cutoff?windowForCutoff(cutoff,this.schedule(),this.calendar()):null;
|
||||
const relevant=this.all('execution-tasks').filter(t=>!window||eligibility.eventInWindow(this,t.row,window));
|
||||
const sources=new Set([...this.executionSources(),...relevant.filter(t=>!['sent','ignored'].includes(t.status)).map(t=>t.connectionId)]);
|
||||
for(const id of sources){
|
||||
if(!allowed(id))continue;
|
||||
const scan=this.get('execution-scans',id);
|
||||
if(scan?.status!=='complete')blockers.push('连接 '+id+' 尚无完整成功扫描'+(scan?.error?':'+scan.error:'。'));
|
||||
else if(cutoff&&Date.parse(scan.startedAt)<Date.parse(cutoff))blockers.push('连接 '+id+' 需要截止时点之后启动的完整扫描。');
|
||||
}
|
||||
return blockers;
|
||||
}
|
||||
categoryIncomplete(categoryId,window){
|
||||
return this.all('execution-tasks').some(task=>task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(eligibility.eventTime(this,task.row)))||eligibility.eventInWindow(this,task.row,window))&&(task.conflict||['identified','blocked','failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'||task.runtimeCheck?.status==='blocked'));
|
||||
}
|
||||
batchIncomplete(batch){
|
||||
return this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&(task.conflict||task.runtimeCheck?.status==='blocked'||['failed','capturing','archiving'].includes(task.status)||task.status==='unknown'&&task.step!=='complete'));
|
||||
}
|
||||
issueOwners(input){
|
||||
const orderIds=input.orderIds||[];
|
||||
const taskIds=input.taskIds||[];
|
||||
const taskOwners=this.all('execution-tasks')
|
||||
.filter(task=>orderIds.includes(task.orderId)||taskIds.includes(task.id))
|
||||
.map(task=>task.owner);
|
||||
const sourceOwners=orderIds.map(id=>this.get('orders',id)).filter(Boolean)
|
||||
.map(order=>this.ownerForConnection?.(order.sample?.connectionId));
|
||||
return [...new Set([...taskOwners,...sourceOwners].filter(Boolean))];
|
||||
}
|
||||
recordIssue(id,input){
|
||||
const old=this.get('business-issues',id);
|
||||
const owners=this.issueOwners(input);
|
||||
const status=['resolved','awaiting_verification'].includes(old?.status)?'open':old?.status||'open';
|
||||
return this.put('business-issues',{
|
||||
...old,...input,id,status,owners,
|
||||
ownerStatus:owners.length?'assigned':'unassigned',
|
||||
verification:'核对订单归档、冻结批次和邮件服务器记录后人工处理。',
|
||||
createdAt:old?.createdAt||this.now(),
|
||||
updatedAt:this.now(),
|
||||
});
|
||||
}
|
||||
prepare(cutoff,actor,requestedWindow){return this.transaction(()=>{
|
||||
if(!validDate(cutoff))fail('请选择包含时区的有效发送截止时间。');
|
||||
const window=windowForCutoff(cutoff,this.schedule(),this.calendar());
|
||||
if(eligibility.state(this)){const current=upcomingWindow(this.clock(),this.schedule(),this.calendar());if(!current?.available||current.end!==window.end)return [];}
|
||||
if(requestedWindow&&(requestedWindow.start!==window.start||requestedWindow.end!==window.end))fail('发送时段与业务日历不一致。',409);
|
||||
const blockers=this.discoveryBlockers(cutoff);
|
||||
const resultId=(category,mode)=>category+':'+cutoff+(mode==='normal'?'':':'+mode);
|
||||
const existingBatch=(category,mode)=>this.all('batches').find(b=>b.categoryId===category&&modeOf(b)===mode&&Date.parse(b.cutoff)===Date.parse(cutoff)&&!(b.status==='cancelled'&&b.resolution?.resolution==='retry'));
|
||||
for(const rule of this.all('rules').map(r=>this.executionRule(r)).filter(r=>r?.status==='enabled'))for(const mode of rule.huizhouEnabled===true?['normal','huizhou']:['normal']){const categoryId=rule.categoryId,existing=existingBatch(categoryId,mode);this.put('window-results',{id:resultId(categoryId,mode),categoryId,notificationMode:mode,cutoff,status:existing?'frozen':blockers.length?'blocked':'empty',batchId:existing?.id||null,error:blockers.join(';')||null,updatedAt:this.now()});}
|
||||
if(blockers.length)return [];
|
||||
const grouped=new Map(),batches=[];
|
||||
for(const order of this.all('orders'))for(const mode of ['normal','huizhou']){
|
||||
const state=delivery(order,mode);
|
||||
if(!state||!['identified','preparing','archived','pending','blocked'].includes(state.status)||!order.categoryId||order.blockedByBatchId||order.missedWindow||order.status==='ignored')continue;
|
||||
if(mode==='huizhou'&&(order.ruleSnapshot?.huizhouEnabled!==true||(!state.orderNos?.length&&!state.issues?.length)))continue;
|
||||
const at=eligibility.orderTime(this,order);
|
||||
if(validDate(at)&&Date.parse(at)<Date.parse(window.start)&&!eligibility.isAdmitted(this,order.sample||order.event)){this.recordIssue('missed:'+order.id+':'+mode,{component:'rules',notificationMode:mode,error:'错过整理时点,等待人工处理。',orderIds:[order.id]});updateDelivery(order,mode,{status:'ignored',error:'早于本时段的历史订单,不补发。'});this.put('orders',order);continue;}
|
||||
if(!eligibility.orderInWindow(this,order,window))continue;
|
||||
const key=order.categoryId+':'+mode;if(!grouped.has(key))grouped.set(key,{mode,orders:[]});grouped.get(key).orders.push(order);
|
||||
}
|
||||
for(const {mode,orders} of grouped.values()){
|
||||
const rule=orders[0].ruleSnapshot;if(!rule)continue;
|
||||
if(existingBatch(rule.categoryId,mode))continue;
|
||||
// Only a normal freeze produced by this dual-delivery flow may gain a late
|
||||
// companion after repairing a Hui-only blocker. Historical freezes stay closed.
|
||||
const normal=mode==='huizhou'&&existingBatch(rule.categoryId,'normal');
|
||||
if(normal&&normal.huizhouPlanned!==true)continue;
|
||||
const published=this.executionRule(this.get('rules',rule.id));
|
||||
let error=!published||published.status!=='enabled'?'该类别规则已暂停。':null;
|
||||
if(!error&&published.version!==rule.version)error='本类别订单规则版本已过期,请应用当前已发布规则后处理。';
|
||||
if(!error&&this.categoryIncomplete(rule.categoryId,window))error='本类别存在未完成的采集、归档或核验任务。';
|
||||
if(!error&&mode==='huizhou'&&orders.some(o=>delivery(o,mode).issues?.length))error=orders.flatMap(o=>delivery(o,mode).issues||[]).join(';');
|
||||
if(!error&&orders.some(o=>mode==='normal'?o.status!=='pending':!o.archive||!['pending','batched','sent','unknown'].includes(o.status)))error='本类别存在字段、文件或归档尚未准备完成的订单。';
|
||||
let snapshot;
|
||||
if(!error)try{for(const order of orders)require('./restricted-test.cjs').assertOrder(this,order);const selected=ordersForMode(orders,mode);snapshot=buildBatch(rule,selected,cutoff,{store:this,maxMessageBytes:this.settings().maxMessageBytes,window,notificationMode:mode});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId,rule,mode),selected,this.settings().maxMessageBytes);}catch(cause){error=cause.message;}
|
||||
const key=resultId(rule.categoryId,mode);
|
||||
if(error){this.put('window-results',{id:key,categoryId:rule.categoryId,notificationMode:mode,cutoff,status:'blocked',error,updatedAt:this.now()});this.recordIssue('build:'+key,{component:'rules',notificationMode:mode,error,cutoff,categoryId:rule.categoryId,orderIds:orders.map(o=>o.id)});for(const original of orders){const order=this.get('orders',original.id);updateDelivery(order,mode,{error,...(mode==='huizhou'?{status:'blocked'}:{})});this.put('orders',order);}continue;}
|
||||
const batch={...snapshot,id:crypto.randomUUID(),version:1,status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null};
|
||||
if(rule.testRunId)batch.testRunId=rule.testRunId;
|
||||
require('./restricted-test.cjs').assertBatch(this,batch,this.settings());
|
||||
if(mode==='normal')batch.huizhouPlanned=rule.huizhouEnabled===true&&orders.some(order=>!!order.notifications?.huizhou);
|
||||
this.put('batches',batch);this.put('window-results',{id:key,categoryId:rule.categoryId,notificationMode:mode,cutoff,status:'frozen',batchId:batch.id,updatedAt:this.now()});
|
||||
const issue=this.get('business-issues','build:'+key);if(issue)this.put('business-issues',{...issue,status:'awaiting_verification',updatedAt:this.now()});
|
||||
for(const original of orders){const order=this.get('orders',original.id);updateDelivery(order,mode,{status:mode==='normal'?transition('order',order.status,'batch'):'batched',batchId:batch.id,error:null});order.updatedAt=this.now();this.put('orders',order);}
|
||||
this.audit(actor,'固定分类邮件批次',batch.id+' '+orders.length+'单');batches.push(batch);
|
||||
}
|
||||
return batches;
|
||||
});}
|
||||
updateBatchOrders(batch,status,error=null){for(const id of batch.orderIds){const order=this.get('orders',id),mode=modeOf(batch);if(delivery(order,mode)?.batchId===batch.id){updateDelivery(order,mode,{status,error});order.updatedAt=this.now();this.put('orders',order);}}}
|
||||
releaseBatchOrders(batch){for(const id of batch.orderIds){const order=this.get('orders',id),mode=modeOf(batch);if(delivery(order,mode)?.batchId===batch.id){updateDelivery(order,mode,{batchId:null});this.put('orders',order);}}}
|
||||
beginSending(id,{manual=false}={}){return this.transaction(()=>{
|
||||
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
|
||||
require('./restricted-test.cjs').assertBatch(this,batch,this.settings());
|
||||
if(!(manual&&batch.manual)&&this.executionRule(this.get('rules',batch.ruleSnapshot.id))?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409);
|
||||
if(this.batchIncomplete(batch)||!(manual&&batch.manual)&&this.discoveryBlockers(batch.cutoff).length)throw Object.assign(Error('待办扫描或类别订单尚不完整,等待完整扫描与恢复。'),{status:409,code:'DISCOVERY_INCOMPLETE'});
|
||||
const orders=batch.orderIds.map(oid=>this.get('orders',oid));
|
||||
if(this.all('execution-tasks').some(task=>batch.orderIds.includes(task.orderId)&&task.runtimeCheck?.status==='blocked'))fail('已归档订单的运行条件复核未通过,批次不能进入发送。',409);
|
||||
if(orders.some(o=>!o||delivery(o,modeOf(batch))?.batchId!==id||delivery(o,modeOf(batch))?.status!=='batched'))fail('批次订单预留已变化。',409);
|
||||
batch.version=(batch.version||1)+1;batch.status=transition('batch',batch.status,'send');this.put('batches',batch);return batch;
|
||||
});}
|
||||
finishSending(id,status,message=null){return this.transaction(()=>{
|
||||
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
|
||||
if(!['sent','unknown','failed'].includes(status))fail('发送结果无效。');
|
||||
batch.version=(batch.version||1)+1;batch.status=transition('batch',batch.status,{sent:'sent',unknown:'unknown',failed:'fail'}[status]);batch.error=message;batch.finishedAt=this.now();this.put('batches',batch);
|
||||
this.updateBatchOrders(batch,status==='failed'?'pending':status,message);
|
||||
if(status==='failed')this.releaseBatchOrders(batch);
|
||||
if(['failed','unknown'].includes(status))this.recordIssue('batch:'+id,{component:'mail',batchId:id,error:message,orderIds:batch.orderIds});
|
||||
this.audit('系统发送','更新批次结果',id+' '+status);return batch;
|
||||
});}
|
||||
resolve(id,input,actor,{controlled=false}={}){return this.transaction(()=>{
|
||||
let requestId,inputHash;
|
||||
if(controlled){
|
||||
if(typeof input?.idempotencyKey!=='string'||!/^[\w:.-]{1,160}$/.test(input.idempotencyKey))fail('请提供有效核验幂等标识。');
|
||||
requestId=digest(['resolve',id,actor,input.idempotencyKey]);inputHash=digest([input.version,input.resolution,input.note]);const previous=this.get('resolve-requests',requestId);
|
||||
if(previous){if(previous.inputHash!==inputHash)fail('此幂等标识已用于不同的核验请求。',409);return this.get('batches',id);}
|
||||
}
|
||||
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
|
||||
if(controlled&&input.version!==(batch.version||1))fail('批次版本已变化,请刷新。',409);
|
||||
if(!input||!['sent','retry'].includes(input.resolution)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请选择核验结果并填写至少5字依据。');
|
||||
batch.version=(batch.version||1)+1;batch.status=transition('batch',batch.status,input.resolution==='sent'?'resolve_sent':'retry');batch.resolution={...input,actor,at:this.now()};if(input.resolution==='retry'){batch.status='failed';batch.error='人工已核验未发送,等待受控人工补发。';}this.put('batches',batch);
|
||||
this.updateBatchOrders(batch,input.resolution==='sent'?'sent':'pending',null);
|
||||
if(input.resolution==='retry')this.releaseBatchOrders(batch);
|
||||
if(controlled)this.put('resolve-requests',{id:requestId,batchId:id,inputHash,at:this.now()});this.audit(actor,'核验分类邮件结果',id+':'+input.note.trim());return batch;
|
||||
});}
|
||||
close(){this.db.close();this.vault.destroy();}
|
||||
}
|
||||
module.exports={RuleStore};
|
||||
@@ -0,0 +1,27 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const {fail}=require('./validation.cjs');
|
||||
const canonical=v=>Array.isArray(v)?v.map(canonical):v&&typeof v==='object'?Object.fromEntries(Object.keys(v).sort().map(k=>[k,canonical(v[k])])):v;
|
||||
const digest=v=>crypto.createHash('sha256').update(JSON.stringify(canonical(v))).digest('hex');
|
||||
const text=v=>v===undefined||v===null?'':String(v).trim();
|
||||
function identity(value){const row=value?.sample||value?.row||value?.event||value||{};return {source:text(row.source),portalSource:text(row.portalSource),taskId:text(row.taskId)};}
|
||||
function taskIdentity(value){const item=identity(value);if(!item.source||!item.taskId)fail('缺少来源和通知任务标识。',409);return digest(['notification-task',item.source,item.portalSource,item.taskId]);}
|
||||
// A legacy row with no native portal source is ambiguous. Treat it as an
|
||||
// overlapping namespace, never guess v4/v8 and create a second notification.
|
||||
function sameTask(a,b){a=identity(a);b=identity(b);return !!a.source&&!!a.taskId&&a.source===b.source&&a.taskId===b.taskId&&(!a.portalSource||!b.portalSource||a.portalSource===b.portalSource);}
|
||||
function records(store,kind,value){return store.all(kind).filter(row=>sameTask(row,value));}
|
||||
function lookup(store,kind,value){const rows=records(store,kind,value);if(rows.length>1)fail('同一通知任务存在多条旧记录,须人工核验,禁止新建或自动合并。',409);return rows[0]||null;}
|
||||
function normalize(value){const row=structuredClone(value);for(const key of ['connectionId','source','portalSource','instanceId','taskId','revision'])if(row[key]!==undefined&&row[key]!==null)row[key]=text(row[key]);if(!text(row.revision))delete row.revision;return row;}
|
||||
function fingerprint(value){const row=normalize(value);delete row.connectionId;return digest(row);}
|
||||
function legacyRevisionMissing(previous,incoming){
|
||||
const old=previous?.sample||previous?.row||previous?.event||previous||{},next=incoming?.sample||incoming?.row||incoming?.event||incoming||{};
|
||||
return !previous?.taskKey&&text(old.revision)==='0'&&!old.revisionSource&&old.reportedRevision===undefined&&!text(next.revision)&&next.reportedRevision===undefined;
|
||||
}
|
||||
function equivalent(previous,incoming){
|
||||
const old=previous?.sample||previous?.row||previous?.event||previous;
|
||||
if(fingerprint(old)===fingerprint(incoming))return true;
|
||||
if(!legacyRevisionMissing(previous,incoming))return false;
|
||||
const without=structuredClone(old);delete without.revision;return fingerprint(without)===fingerprint(incoming);
|
||||
}
|
||||
function assertUnprocessedReceipt(store,value){if(records(store,'processed-task-receipts',value).length)fail('通知任务已有处理或发送回执,禁止重复生成归档和邮件。',409);}
|
||||
module.exports={identity,taskIdentity,sameTask,records,lookup,normalize,fingerprint,digest,assertUnprocessedReceipt,legacyRevisionMissing,equivalent};
|
||||
@@ -0,0 +1,9 @@
|
||||
'use strict';
|
||||
const {fail}=require('./validation.cjs');
|
||||
const {ruleTemplate}=require('../mail/rule-template.cjs');
|
||||
function checkTemplates(mail,rule){
|
||||
if(!mail){if(rule?.bodyTemplateId||rule?.huizhouEnabled===true)fail('邮件模板服务暂不可用。',503);return;}
|
||||
ruleTemplate(mail.store,rule?.categoryId,rule);
|
||||
ruleTemplate(mail.store,rule?.categoryId,rule,'huizhou');
|
||||
}
|
||||
module.exports={checkTemplates};
|
||||
@@ -0,0 +1,55 @@
|
||||
'use strict';
|
||||
const {renderTemplate,escape}=require('../mail/parser.cjs');
|
||||
const {fail}=require('./validation.cjs');
|
||||
const {mailContent,fileLink}=require('./mail-content.cjs');
|
||||
const has=(part,key)=>new RegExp('{{\\s*'+key+'\\s*}}').test(part||'');
|
||||
function businessDates(template,orders){
|
||||
if(!['subject','text','html'].some(part=>has(template[part],'日期')))return '';
|
||||
const formatter=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'});
|
||||
return [...new Set(orders.map(order=>{
|
||||
const receivedAt=order.event?.receivedAt;
|
||||
if(typeof receivedAt!=='string'||!/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(receivedAt)||!Number.isFinite(Date.parse(receivedAt)))fail('模板变量日期缺少有效的确认节点接收时间 event.receivedAt:订单 '+(order.event?.orderNo||order.id||'未知')+'。',409);
|
||||
return formatter.format(new Date(receivedAt));
|
||||
}))].join('、');
|
||||
}
|
||||
function applyBodyTemplate(snapshot,template,orders,maxMessageBytes){
|
||||
if(template?.attachments?.length)fail('业务通知模板禁止 PDF 或其他附件。',409);
|
||||
if(snapshot.notificationMode==='huizhou')return applyHuizhouTemplate(snapshot,template,orders,maxMessageBytes);
|
||||
const boundId=orders[0]?.ruleSnapshot?.bodyTemplateId;
|
||||
if(boundId&&(!template||template.id!==boundId))fail('本分类绑定的邮件模板未正确解析。',409);
|
||||
if(!template)return snapshot;
|
||||
const date=businessDates(template,orders),content=mailContent(orders),category=orders[0]?.ruleSnapshot?.name||'';
|
||||
const values={'产品线':[...new Set(orders.map(order=>order.event.productLine).filter(Boolean))].join('、'),'订单号':snapshot.orderNos.join('、'),'日期':date,'订单列表':content.details,'订单明细':content.details,'存放地址':content.directories.join('\n'),'类别名称':category};
|
||||
const rendered=renderTemplate({...template,attachments:[]},values);
|
||||
const subject=rendered.subject?rendered.subject+(has(template.subject,'订单号')?'':' '+snapshot.orderNos.join('、')):snapshot.subject;
|
||||
let text=rendered.text;
|
||||
if(!['订单列表','订单明细'].some(key=>has(template.text,key)))text+='\n\n'+content.details;
|
||||
if(!has(template.text,'存放地址'))text+='\n\n存放地址:'+content.directories.join('\n');
|
||||
let html='<div>'+escape(text).replace(/\r?\n/g,'<br>')+'</div>';
|
||||
const directoryLinks=new Map(content.directories.map(directory=>[escape(directory),'<a style="color:#0000ff" href="'+escape(fileLink(directory))+'">'+escape(directory)+'</a>']));
|
||||
const directoryPattern=[...directoryLinks.keys()].sort((a,b)=>b.length-a.length).map(directory=>directory.replace(/[.*+?^${}()|[\]\\]/g,'\\$&')).join('|');
|
||||
if(directoryPattern)html=html.replace(new RegExp(directoryPattern,'g'),directory=>directoryLinks.get(directory));
|
||||
if(template.html){
|
||||
const token='ORDER_CONTENT_'+require('node:crypto').randomUUID(),directoryToken='ORDER_ARCHIVE_'+require('node:crypto').randomUUID();
|
||||
html=renderTemplate({...template,attachments:[]},{...values,'订单列表':token,'订单明细':token,'存放地址':directoryToken}).html.replaceAll(token,content.htmlDetails).replaceAll(directoryToken,content.htmlDirectoryLinks);
|
||||
if(!['订单列表','订单明细'].some(key=>has(template.html,key)))html+=content.htmlDetails;
|
||||
if(!has(template.html,'存放地址'))html+=content.htmlDirectories;
|
||||
}
|
||||
const bytes=16384+Buffer.byteLength(text+html+subject)*2;
|
||||
if(bytes>maxMessageBytes)fail('关联模板展开后超过邮件容量限制。');
|
||||
return {...snapshot,subject,text,html,template:{id:template.id,version:template.version,bindingVersion:template.bindingVersion}};
|
||||
}
|
||||
function applyHuizhouTemplate(snapshot,template,orders,maxMessageBytes){
|
||||
const rule=orders[0]?.ruleSnapshot;
|
||||
if(!template||!rule?.huizhouTemplateId||template.id!==rule.huizhouTemplateId||template.notificationMode!=='huizhou'||template.status!=='active')fail('惠州通知必须选择已确认且启用的惠州模板。',409);
|
||||
const date=businessDates(template,orders),content=mailContent(orders),details=content.details;
|
||||
const values={'产品线':[...new Set(orders.map(order=>order.event.productLine).filter(Boolean))].join('、'),'订单号':snapshot.orderNos.join('、'),'日期':date,'订单列表':details,'订单明细':details,'存放地址':content.directories.join('\n'),'类别名称':rule.name||''};
|
||||
const rendered=renderTemplate({...template,attachments:[]},values);
|
||||
const subject=rendered.subject+(has(template.subject,'订单号')?'':' '+snapshot.orderNos.join('、'));
|
||||
const text=rendered.text+(['订单列表','订单明细'].some(key=>has(template.text,key))?'':'\n\n'+details);
|
||||
const html=template.html?rendered.html+(['订单列表','订单明细'].some(key=>has(template.html,key))?'':content.htmlDetails):'<div>'+escape(text).replace(/\r?\n/g,'<br>')+'</div>';
|
||||
const bytes=16384+Buffer.byteLength(text+html+subject)*2+(snapshot.attachments||[]).reduce((sum,file)=>sum+Math.ceil(file.size/3)*4+4096,0);
|
||||
if(bytes>maxMessageBytes)fail('关联模板展开后超过邮件容量限制。');
|
||||
return {...snapshot,subject,text,html,template:{id:template.id,version:template.version,bindingVersion:template.bindingVersion,notificationMode:'huizhou'}};
|
||||
}
|
||||
module.exports={applyBodyTemplate};
|
||||
@@ -0,0 +1,76 @@
|
||||
'use strict';
|
||||
const crypto=require('node:crypto');
|
||||
const {frozen}=require('./migrations.cjs');
|
||||
const RECIPIENT='2639266652@qq.com';
|
||||
const usableTemplate=(t,channelId)=>t?.status==='active'&&t.channelId===channelId&&(!t.notificationMode||t.notificationMode==='normal')&&(t.attachments||[]).length===0;
|
||||
function hasEvidence(store,adapter){const capture=store.get('capture-samples',adapter.sampleId||'');if(!capture||capture.provenance!=='server-provider'||capture.sample?.demo||capture.evidenceHash!==adapter.evidenceHash||capture.processName!==adapter.processName||capture.processVersion!==adapter.processVersion)return false;return require('./field-mappings.cjs').evaluateMapping(store,{...adapter,version:adapter.version},capture,{relatedRules:[]}).valid;}
|
||||
function existingTemplate(mail,rule,channelId){
|
||||
for(const get of [()=>rule.bodyTemplateId?mail.template(rule.bodyTemplateId):null,()=>mail.categoryTemplate(rule.categoryId)]){
|
||||
let t;try{t=get();}catch{continue;}
|
||||
if(usableTemplate(t,channelId))return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function buildPreparationPlan({store,mailStore,source,runId=crypto.randomUUID(),channelId,archiveRoot}){
|
||||
const oldRun=store.get('restricted-test','main')?.value||null;
|
||||
channelId=channelId||oldRun?.channelId||store.settings().channelId;
|
||||
archiveRoot=archiveRoot||oldRun?.archiveRoot;
|
||||
const blockers=[],uncovered=[],records=store.all('rules'),adapters=store.adapters(),rules=[],catalog=require('./catalog.cjs').seedRules();
|
||||
if(source?.rules?.length!==15)blockers.push('Source must contain exactly 15 categories');
|
||||
if(!channelId)blockers.push('Missing existing test channel');if(!archiveRoot)blockers.push('Missing existing Desktop test archive root');
|
||||
for(const row of source.rules||[]){
|
||||
const identity=row.id||catalog.find(r=>r.sourceRow===row.sourceRow&&r.name===row.name)?.id;
|
||||
const matches=records.filter(r=>r.draft.name===row.name||(identity&&r.id===identity));
|
||||
if(matches.length!==1){blockers.push('Native category not uniquely matched: '+row.name);continue;}
|
||||
const record=matches[0],old=record.draft;
|
||||
if(row.id&&row.id!==record.id){blockers.push('Source category identity mismatch: '+row.name);continue;}
|
||||
const selected=adapters.filter(a=>old.adapterIds.includes(a.id)&&a.verified&&!a.reference&&row.processNames.includes(a.processName)&&hasEvidence(store,a));
|
||||
const missing=row.processNames.filter(p=>!selected.some(a=>a.processName===p));uncovered.push(...missing.map(processName=>({categoryId:record.id,processName})));
|
||||
if(!selected.length)blockers.push('Missing verified adapter for category: '+record.id);
|
||||
if(!old.archiveDirectory)blockers.push('Missing existing Desktop directory: '+record.id);
|
||||
if(archiveRoot)try{require('./restricted-test.cjs').assertPath(store,old.archiveDirectory,{archiveRoot});}catch{blockers.push('Existing archive directory is outside the Desktop test root: '+record.id);}
|
||||
const template=existingTemplate(mailStore,old,channelId);
|
||||
const templateIntent=template?{action:'reuse',id:template.id}:{action:'create',scope:('test-'+runId+'-'+record.id).slice(0,80),subject:old.subjectPrefix,text:[old.intro,'{{订单列表}}','存放地址:\n{{存放地址}}',old.signature].filter(Boolean).join('\n\n')};
|
||||
const draft={...structuredClone(old),processNames:[...row.processNames],nodeNames:[...row.nodeNames],scopes:row.processNames.flatMap(processName=>row.nodeNames.map(nodeName=>({processName,nodeName}))),adapterIds:selected.map(a=>a.id),productLine:old.name,to:[RECIPIENT],cc:[],attachPdf:false,huizhouEnabled:false,huizhouTemplateId:'',sourceRow:row.sourceRow};
|
||||
rules.push({id:record.id,previousName:old.name,expectedVersion:old.version,draft,template:templateIntent,source:structuredClone(row.provenance||{})});
|
||||
}
|
||||
if(new Set(rules.map(r=>r.id)).size!==15)blockers.push('All 15 unique native categories are required');
|
||||
return {format:1,runId,source:{file:source.source,sha256:source.sourceSha256,worksheet:source.worksheet},productLineSource:'test-label:rule.name',previousRunId:oldRun?.id||null,previousRunVersion:oldRun?.version||0,channelId,archiveRoot,recipient:RECIPIENT,rules,uncovered,blockers,settings:{enabled:false,processingEnabled:false}};
|
||||
}
|
||||
function prepareNativeTemplate(mailStore,item,plan,actor){
|
||||
if(item.template.action==='reuse'){const t=mailStore.template(item.template.id);if(!usableTemplate(t,plan.channelId))throw Error('Template changed');return t;}
|
||||
const channel=mailStore.row(plan.channelId),cursor=channel.cursor,receipts=mailStore.db.prepare('SELECT * FROM receipts WHERE channel_id=?').all(plan.channelId);
|
||||
// Native ingest normally advances IMAP state. Restore it within this same
|
||||
// mail transaction so a local admin import never skips inbound messages.
|
||||
return mailStore.transaction(()=>{
|
||||
const intent=item.template,raw=Buffer.from(JSON.stringify({run:plan.runId,category:item.id,subject:intent.subject,text:intent.text}));
|
||||
const pending=mailStore.ingest(plan.channelId,'admin-test-'+plan.runId,plan.rules.indexOf(item)+1,{subject:intent.subject,scope:intent.scope,text:intent.text,html:'',sender:'local-admin',sourceSubject:intent.subject,messageId:'admin-test-'+plan.runId+'-'+item.id,attachments:[],notes:['Local test template; no inbound mail or send operation.']},raw,channel.version);
|
||||
const active=mailStore.confirm(pending.id,{version:pending.version,scope:intent.scope,subject:intent.subject,useText:true,text:intent.text,notificationMode:'normal'},actor.username);
|
||||
mailStore.db.prepare('UPDATE channels SET cursor=? WHERE id=?').run(cursor,plan.channelId);
|
||||
mailStore.db.prepare('DELETE FROM receipts WHERE channel_id=?').run(plan.channelId);
|
||||
const insert=mailStore.db.prepare('INSERT INTO receipts(id,channel_id,epoch,uid,status,detail,at) VALUES(?,?,?,?,?,?,?)');for(const r of receipts)insert.run(r.id,r.channel_id,r.epoch,r.uid,r.status,r.detail,r.at);
|
||||
return active;
|
||||
});
|
||||
}
|
||||
function applyPreparationPlan({store,mailStore,plan,actor,prepareTemplate=prepareNativeTemplate,saveRun=(s,input,a)=>s.saveRestrictedTest(input,a)}){
|
||||
if(actor?.role!=='admin'||!actor.username)throw Error('Administrator required');
|
||||
if(plan.blockers.length)throw Error('Preparation blocked: '+plan.blockers.join('; '));
|
||||
return store.transaction(()=>{
|
||||
const old=store.get('restricted-test','main')?.value||null;
|
||||
if((old?.id||null)!==plan.previousRunId||(old?.version||0)!==plan.previousRunVersion)throw Error('Previous test run changed');
|
||||
for(const item of plan.rules)if(store.get('rules',item.id)?.draft.version!==item.expectedVersion)throw Error('Rule draft changed: '+item.id);
|
||||
const settings=store.get('settings','main');store.put('settings',{...settings,version:settings.version+1,channelId:plan.channelId,enabled:false,processingEnabled:false});
|
||||
for(const item of plan.rules){const template=prepareTemplate(mailStore,item,plan,actor);store.saveRule({...item.draft,bodyTemplateId:template.id},actor.username);}
|
||||
if(old){
|
||||
const historyId=old.id+':'+old.version;if(store.get('restricted-test-history',historyId))throw Error('Previous test history already exists');
|
||||
store.put('restricted-test-history',{id:historyId,value:structuredClone(old),archivedAt:store.now(),reason:'Replaced by original Excel scopes',source:plan.source});
|
||||
for(const order of store.all('orders'))if(order.ruleSnapshot?.testRunId===old.id&&!frozen(store,order)&&!['sent','sending','unknown'].includes(order.status))store.put('orders',{...order,status:'blocked',error:'此前测试运行已替换;保留旧归档和规则快照,须人工核验,不自动重排或发送。',updatedAt:store.now(),preparationHold:{previousRunId:old.id,previousStatus:order.status}});
|
||||
store.db.prepare('DELETE FROM records WHERE kind=? AND id=?').run('restricted-test','main');
|
||||
}
|
||||
const run=saveRun(store,{version:0,enabled:true,recipient:RECIPIENT,archiveRoot:plan.archiveRoot,channelId:plan.channelId,ruleIds:plan.rules.map(r=>r.id)},actor);
|
||||
store.put('test-preparation',{id:run.id,source:plan.source,provenance:plan.rules.map(r=>({id:r.id,source:r.source})),productLineSource:plan.productLineSource,preparedAt:store.now(),automaticProcessing:false,automaticSending:false});
|
||||
return {run,settings:store.settings(),templates:plan.rules.length};
|
||||
});
|
||||
}
|
||||
function publicPlan(plan){return {...plan,rules:plan.rules.map(r=>({id:r.id,name:r.draft.name,expectedVersion:r.expectedVersion,processNames:r.draft.processNames,nodeNames:r.draft.nodeNames,scopes:r.draft.scopes,productLine:r.draft.productLine,productLineSource:plan.productLineSource,to:r.draft.to,cc:[],attachPdf:false,archiveDirectory:r.draft.archiveDirectory,adapterIds:r.draft.adapterIds,template:r.template.action==='reuse'?r.template:{action:'create',scope:r.template.scope,variables:['订单列表','存放地址']},source:r.source}))};}
|
||||
module.exports={RECIPIENT,existingTemplate,buildPreparationPlan,prepareNativeTemplate,applyPreparationPlan,publicPlan};
|
||||
@@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
|
||||
// Fixed field boundaries keep extraction deterministic; raw title stays on the event.
|
||||
const summaryKeys={'机芯号':'coreNo','产品型号':'productModel','客户简称':'customerShort','出货方式':'shippingMethod','总数量':'totalQuantity','订单类别':'orderCategory'};
|
||||
const retained=new Set(['订单号',...Object.keys(summaryKeys)]);
|
||||
function extractTitle(title){
|
||||
const raw=typeof title==='string'?title:'';
|
||||
const text=raw.replace(/<br\s*\/?\s*>/gi,'\n').replace(/ | | /gi,' ');
|
||||
const matches=[...text.matchAll(/(客户等级|毛利|订单号|机芯号|产品型号|客户简称|出货方式|总数量|订单类别|订单类型|业务模式)\s*[::]/gu)];
|
||||
const orders=[],factoryHints=[],issues=[];let current=null,pendingMode=null,pendingAmbiguous=false;
|
||||
for(let i=0;i<matches.length;i++){
|
||||
const match=matches[i],label=match[1],value=text.slice(match.index+match[0].length,matches[i+1]?.index??text.length).trim();
|
||||
if(['业务模式','客户简称'].includes(label)&&value.includes('惠州'))factoryHints.push({source:label,value,status:'待核实额外通知'});
|
||||
if(label==='订单号'&&!/(?:原|参考)$/.test(text.slice(0,match.index))){
|
||||
// Unknown labels and pipe-separated titles still delimit the identifier.
|
||||
// Keep their original content in the notification paragraph below.
|
||||
const identifier=/^([A-Za-z0-9][A-Za-z0-9._/-]*)(?=$|\s|[\p{Script=Han}|,,;;])/u.exec(value)?.[1]||value;
|
||||
current={orderNo:identifier,text:''};if(pendingMode){current.businessMode=pendingMode;if(pendingAmbiguous)current.businessModeAmbiguous=true;pendingMode=null;pendingAmbiguous=false;}orders.push(current);
|
||||
if(!value)issues.push('标题中的订单号为空,不能遗漏该订单段落');
|
||||
}
|
||||
if(label==='业务模式'){
|
||||
const nextOrder=matches.findIndex((m,index)=>index>i&&m[1]==='订单号');
|
||||
const between=nextOrder<0?[]:matches.slice(i+1,nextOrder).map(m=>m[1]);
|
||||
// Summary fields after a mode still belong to the current order, irrespective
|
||||
// of line wrapping. Only a header with no intervening summary binds forward.
|
||||
const startsParagraph=/[\n|]\s*$/.test(text.slice(0,match.index));
|
||||
const hasOwnSummary=between.some(label=>Object.hasOwn(summaryKeys,label));
|
||||
const forward=nextOrder>=0&&!hasOwnSummary&&(between.includes('毛利')||startsParagraph);
|
||||
if(current&&nextOrder>=0&&!hasOwnSummary&&!forward){
|
||||
// An unmarked boundary cannot establish which adjacent order owns the mode.
|
||||
current.businessModeAmbiguous=true;pendingMode=value;pendingAmbiguous=true;
|
||||
}
|
||||
else if(!current||forward){
|
||||
if(pendingMode&&pendingMode!==value)pendingAmbiguous=true;
|
||||
pendingMode=value;
|
||||
}
|
||||
else if(current){if(current.businessMode&¤t.businessMode!==value)current.businessModeAmbiguous=true;current.businessMode=value;}
|
||||
}
|
||||
if(current&&retained.has(label)){current.text+=`${label}:${value}`;if(summaryKeys[label])current[summaryKeys[label]]=value;}
|
||||
}
|
||||
if(!orders.length)issues.push('标题中没有可识别的“订单号:”段落');
|
||||
return {rawTitle:raw,orders,brief:orders.map(order=>order.text).join('\n'),factoryHints,issues};
|
||||
}
|
||||
module.exports={extractTitle};
|
||||
@@ -0,0 +1,25 @@
|
||||
'use strict';
|
||||
const {isDeepStrictEqual}=require('node:util');
|
||||
const {validateRule,fail}=require('./validation.cjs');
|
||||
const {previewMatch}=require('./matching.cjs'),{scopesFor}=require('./scopes.cjs');
|
||||
const {previewEffects}=require('./effects-preview.cjs');
|
||||
const comparable=rule=>{const value=validateRule(rule,rule);value.version=rule.version;value.scopes=scopesFor(value);return value;};
|
||||
function trial(store,id,input){return store.transaction(()=>{
|
||||
const record=store.get('rules',id);if(!record)fail('规则不存在。',404);
|
||||
if(!input||typeof input!=='object'||Array.isArray(input)||Object.keys(input).some(k=>!['version','draft','sample','sampleId'].includes(k)))fail('草稿试运行参数无效。');
|
||||
if(Object.hasOwn(input,'sampleId')&&(typeof input.sampleId!=='string'||!input.sampleId.trim()||input.sampleId.length>200))fail('真实采集样本标识无效。');
|
||||
if(input.version!==record.draft.version)fail('规则版本已变化,请刷新后重新试运行。',409);
|
||||
if((!!input.sampleId)===(!!input.sample))fail('请选择一个真实采集样本,或提供一个模拟样本。');
|
||||
const captured=input.sampleId?store.get('capture-samples',input.sampleId):null;
|
||||
if(input.sampleId&&(!captured||captured.provenance!=='server-provider'))fail('真实捕获样本不存在。',404);
|
||||
const sample=captured?.sample||input.sample;
|
||||
if(!sample||typeof sample!=='object'||Array.isArray(sample))fail('样本必须是对象。');
|
||||
const candidate=input.draft?validateRule(input.draft,record.draft):structuredClone(record.draft);candidate.version=record.draft.version;
|
||||
const saved=isDeepStrictEqual(comparable(candidate),comparable(record.draft));
|
||||
const rules=store.all('rules').map(r=>r.id===id?candidate:r.draft),result=previewMatch(rules,store.adapters(),sample);
|
||||
if(result.ruleId!==id){result.valid=false;result.issues.push('样本未唯一命中当前类别,请检查适用范围或其他类别冲突。');}
|
||||
const publishEvidence=!!(result.valid&&saved&&captured&&sample.demo!==true);
|
||||
if(publishEvidence){record.trialVersion=record.draft.version;record.trialDemo=false;record.trialSampleId=captured.id;store.put('rules',record);}
|
||||
return {...result,trial:{saved,version:record.draft.version,publishEvidence,source:captured?'captured':'simulation'},effects:result.ruleId===id?previewEffects(candidate,result.event,store):null};
|
||||
});}
|
||||
module.exports={trial};
|
||||
@@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
const {normalizeScopes}=require('./scopes.cjs');
|
||||
const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
|
||||
const fields=['id','version','name','categoryId','processNames','nodeNames','adapterIds','archiveDirectory','filenameDate','subjectPrefix','intro','signature','to','cc','attachPdf','sourceRow','bodyTemplateId','huizhouEnabled','huizhouTemplateId'];
|
||||
function addresses(values){
|
||||
if(!Array.isArray(values)||values.length>500)fail('收件名单格式无效。');
|
||||
return [...new Set(values.map(v=>{
|
||||
if(typeof v!=='string'||v.length>254||! /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?\.[A-Za-z]{2,63}$/.test(v.trim()))fail('请检查邮箱地址:'+String(v).slice(0,80));
|
||||
return v.trim().toLowerCase();
|
||||
}))];
|
||||
}
|
||||
function validateRule(input,old){
|
||||
if(!input||typeof input!=='object'||Array.isArray(input))fail('规则格式无效。');
|
||||
if(!old||input.id!==old.id||input.categoryId!==old.categoryId)fail('规则类别标识不能修改。');
|
||||
if(input.version!==old.version)fail('规则已被其他人修改,请刷新后重试。',409);
|
||||
const rule=Object.fromEntries(fields.map(k=>[k,input[k]??old[k]]));
|
||||
if(Object.hasOwn(input,'productLine')||Object.hasOwn(old,'productLine')){const value=input.productLine??old.productLine;if(typeof value!=='string'||!value.trim()||value.length>200||/[\x00-\x1f]/.test(value))fail('分类产品线不能为空或包含无效内容。');rule.productLine=value.trim();}
|
||||
for(const [key,fallback] of [['huizhouEnabled',false],['huizhouTemplateId','']])rule[key]=input[key]!==undefined?input[key]:old[key]!==undefined?old[key]:fallback;
|
||||
if(typeof rule.huizhouEnabled!=='boolean')fail('惠州通知开关无效。');
|
||||
if(typeof rule.huizhouTemplateId!=='string'||rule.huizhouTemplateId.length>100||!/^[\w-]*$/.test(rule.huizhouTemplateId))fail('请选择有效的惠州邮件模板。');
|
||||
if(rule.bodyTemplateId!==undefined&&(typeof rule.bodyTemplateId!=='string'||rule.bodyTemplateId.length>100||!/^[\w-]*$/.test(rule.bodyTemplateId)))fail('请选择有效的邮件模板。');
|
||||
if(Object.hasOwn(input,'scopes')&&input.scopes!==undefined){
|
||||
rule.scopes=normalizeScopes(input.scopes);
|
||||
rule.processNames=[...new Set(rule.scopes.map(row=>row.processName))];
|
||||
rule.nodeNames=[...new Set(rule.scopes.map(row=>row.nodeName))];
|
||||
}else if(old.scopes&&input.processNames===undefined&&input.nodeNames===undefined)rule.scopes=normalizeScopes(old.scopes);
|
||||
for(const key of ['name','subjectPrefix','archiveDirectory','intro','signature']){
|
||||
if(typeof rule[key]!=='string'||rule[key].length>(['intro','signature'].includes(key)?4000:1200)||(/[\x00]/.test(rule[key])))fail('规则文本格式无效。');
|
||||
rule[key]=rule[key].trim();
|
||||
}
|
||||
if(!rule.name||/[\r\n]/.test(rule.subjectPrefix)||/[\x00-\x1f]/.test(rule.archiveDirectory))fail('请填写规则名称,主题和目录不能换行。');
|
||||
for(const key of ['processNames','nodeNames','adapterIds']){
|
||||
if(!Array.isArray(rule[key])||rule[key].length>100||rule[key].some(v=>typeof v!=='string'||!v.trim()||v.length>250||/[\x00-\x1f]/.test(v)))fail('流程、节点或字段适配配置无效。');
|
||||
rule[key]=[...new Set(rule[key].map(v=>v.trim()))];
|
||||
}
|
||||
if(!['','appDate','receivedAt','archiveDate'].includes(rule.filenameDate)||typeof rule.attachPdf!=='boolean')fail('请选择有效的日期来源和附件要求。');
|
||||
rule.to=addresses(rule.to);rule.cc=addresses(rule.cc).filter(v=>!rule.to.includes(v));
|
||||
rule.version=old.version+1;rule.status='draft';return rule;
|
||||
}
|
||||
function publicationIssues(rule,adapters){
|
||||
const issues=[];
|
||||
if(rule.huizhouEnabled===true&&!rule.huizhouTemplateId)issues.push('开启惠州通知时请选择惠州邮件模板');
|
||||
if(!rule.processNames.length||!rule.nodeNames.length)issues.push('请选择适用流程和到达节点');
|
||||
if(!rule.subjectPrefix)issues.push('请填写邮件主题前缀');
|
||||
if(!rule.archiveDirectory||!/^\\\\[^\\]+\\[^\\]+/.test(rule.archiveDirectory)||/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(rule.archiveDirectory))issues.push('请选择完整服务器共享归档目录');
|
||||
if(!rule.filenameDate)issues.push('请选择文件名日期来源');
|
||||
if(!rule.to.length)issues.push('请配置收件人');
|
||||
for(const process of rule.processNames){
|
||||
if(!adapters.some(a=>a.verified&&!a.reference&&a.processName===process&&rule.adapterIds.includes(a.id)))issues.push('流程字段适配待核验:'+process);
|
||||
}
|
||||
if(rule.adapterIds.some(id=>!adapters.some(a=>a.id===id)))issues.push('包含不存在的字段适配器');
|
||||
return issues;
|
||||
}
|
||||
module.exports={fail,validateRule,publicationIssues,addresses};
|
||||
@@ -0,0 +1,38 @@
|
||||
'use strict';
|
||||
const {dayPolicy,nextSlots}=require('../../shared/schedule.cjs');
|
||||
const invalid=message=>{throw Object.assign(new Error(message),{status:400});};
|
||||
const DAY=86400000,OFFSET=8*3600000;
|
||||
const dayOf=date=>new Date(+date+OFFSET).toISOString().slice(0,10);
|
||||
const at=(day,time)=>new Date(day+'T'+time+':00+08:00').toISOString();
|
||||
function timesOf(schedule){
|
||||
if(!Array.isArray(schedule?.times)||schedule.times.length!==2||schedule.times.some(t=>typeof t!=='string'||! /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(t))||schedule.times[0]===schedule.times[1])invalid('请配置两个不同的发送时间。');
|
||||
return [...schedule.times].sort();
|
||||
}
|
||||
function windowForCutoff(cutoff,schedule,overrides=[]){
|
||||
if(typeof cutoff!=='string'||!/(?:Z|[+-]\d{2}:\d{2})$/.test(cutoff)||!Number.isFinite(Date.parse(cutoff)))invalid('发送截止时间必须包含时区。');
|
||||
const date=new Date(cutoff),day=dayOf(date),times=timesOf(schedule),end=date.toISOString();
|
||||
if(!dayPolicy(day,schedule,overrides).send)invalid('该日期未安排发送。');
|
||||
const index=times.findIndex(time=>at(day,time)===end);if(index<0)invalid('截止时间必须与已配置的发送时点一致。');
|
||||
let start=index?at(day,times[index-1]):at(day,'00:00');
|
||||
if(index===0){
|
||||
{
|
||||
let found=false;
|
||||
for(let back=1;back<=370;back++){
|
||||
const previous=dayOf(new Date(+date-back*DAY));
|
||||
if(dayPolicy(previous,schedule,overrides).send){start=at(previous,times.at(-1));found=true;break;}
|
||||
}
|
||||
if(!found)invalid('找不到上个工作日的发送截止时间,请检查业务日历。');
|
||||
}
|
||||
}
|
||||
const fmt=value=>new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',hour12:false}).format(new Date(value));
|
||||
return {start,end,label:fmt(start)+' 至 '+fmt(end)+'(北京时间,含起点、不含终点)',startInclusive:true,endInclusive:false};
|
||||
}
|
||||
function upcomingWindow(now,schedule,overrides=[]){
|
||||
const times=timesOf(schedule),day=dayOf(now);
|
||||
const due=times.map(t=>at(day,t)).find(t=>+now-Date.parse(t)>=0&&+now-Date.parse(t)<=60000);
|
||||
const cutoff=due&&dayPolicy(day,schedule,overrides).send?due:nextSlots(schedule,now,1,overrides)[0];
|
||||
if(!cutoff)return null;
|
||||
return {...windowForCutoff(cutoff,schedule,overrides),available:Boolean(due&&cutoff===due)};
|
||||
}
|
||||
function inWindow(receivedAt,window){const value=Date.parse(receivedAt);return Number.isFinite(value)&&value>=Date.parse(window.start)&&value<Date.parse(window.end);}
|
||||
module.exports={windowForCutoff,upcomingWindow,inWindow};
|
||||
Reference in new issue
Block a user