feat: add category order rules and read-only sent mail history

This commit is contained in:
abaishu0730 committed 2026-10-19 10:36:32 +08:00
1 parent 388805a8a6
commit efa982a8a1
41 files changed
+1828 -28

No files matched your search

+37
View File
@@ -0,0 +1,37 @@
'use strict';
const {fail}=require('./validation.cjs');
async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,reply}){
if(route!=='/api/order-rules'&&!route.startsWith('/api/order-rules/'))return false;
if(!orderRules)fail('分类通知规则服务未启动。',503);
if(route==='/api/order-rules'&&method==='GET'){reply(200,orderRules.snapshot());return true;}
if(method!=='POST')fail('没有找到此规则操作。',404);
if(user.role==='viewer')fail('只读成员不能编辑规则或提交样本。',403);
const actor=user.username;
if(route==='/api/order-rules/preview'||route==='/api/order-rules/events'){
if(!body||Object.keys(body).some(k=>k!=='sample')||!body.sample||typeof body.sample!=='object'||Array.isArray(body.sample))fail('请提供 BPM 样本对象。');
const preview=route.endsWith('/preview');reply(preview?200:201,preview?orderRules.preview(body.sample):orderRules.ingest(body.sample,actor));
if(!preview)workspace?.record(user,'识别分类通知订单','来源任务 '+String(body.sample.taskId));return true;
}
if(user.role!=='admin')fail('仅管理员可维护规则、批次与发送设置。',403);
let result;
if(route==='/api/order-rules/rules')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)$/.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=>k!=='version'))fail('请提供当前草稿版本。');result=orderRules[rule[2]](rule[1],body,actor);}
else if(batch){if(!body||Object.keys(body).some(k=>!['resolution','note'].includes(k)))fail('核验内容无效。');result=orderRules.resolve(batch[1],body,actor);}
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};
+69
View File
@@ -0,0 +1,69 @@
'use strict';
const path=require('node:path');
const fail=message=>{throw Object.assign(new Error(message),{status:409});};
const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[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 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('/');
}
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}={}){
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('类别必须包含待发订单。');
const to=recipients(rule.to,'收件人'),cc=recipients(rule.cc||[],'抄送人').filter(a=>!to.includes(a));
if(!to.length)fail('收件人名单不能为空。');
const orderIds=[],orderNos=[],attachments=[],plain=[],html=[];
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('同一类别包含不同规则版本,请核实后处理。');
if(order.status&&order.status!=='pending')fail('此类别包含未准备完成的订单。');
const received=Date.parse(order.event?.receivedAt);
if(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(rule.attachPdf&&!order.archive.files.some(file=>file.kind==='pdf'&&/\.pdf$/i.test(file.name)))fail(`订单 ${number} 缺少必需 PDF,本类别已阻塞。`);
orderIds.push(order.id);orderNos.push(number);
const files=order.archive.files;
attachments.push(...files.filter(file=>file.kind!=='pdf'||rule.attachPdf).map(file=>({...file})));
plain.push(`${number}\n${String(order.event.brief??'')}\n${files.map(file=>file.path).join('\n')}`);
html.push(`<li><strong>${escape(number)}</strong><br><span style="color:#0000ff">${lines(order.event.brief)}</span><br>${files.map(file=>`<a style="color:#0000ff" href="${escape(fileLink(file.path))}">${escape(file.path)}</a>`).join('<br>')}</li>`);
}
const prefix=String(rule.subjectPrefix||rule.name||'订单通知');
if(/[\r\n\x00-\x1f]/.test(prefix))fail('邮件标题无效。');
const snapshot={categoryId:rule.categoryId,subject:`${prefix} ${orderNos.join('、')}`,text:[rule.intro||'',...plain,rule.signature||''].filter(Boolean).join('\n\n'),html:`<div>${lines(rule.intro)}</div><ul>${html.join('')}</ul><div>${lines(rule.signature)}</div>`,to,cc,orderIds,orderNos,attachments,cutoff:new Date(limit).toISOString()};
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};
+83
View File
@@ -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-') ? ['订单专员(订单通知书)-海外', '订单专员(订单通知书)']
: id === 'overseas-change' ? ['订单专员(订单通知书)', '订单更改通知书']
: ['订单专员(订单通知书)'],
adapterIds: ['bs-change', 'overseas-change'].includes(id) ? [id] : [],
archiveDirectory: '', filenameDate: '', subjectPrefix: `【${name}】`,
intro: `大家好:\n以下为${name},请查收!`, signature: '', to: [], cc: [],
attachPdf: id.endsWith('-change'), sourceRow: index + 2,
}));
}
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', quantity: '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 };
+112
View File
@@ -0,0 +1,112 @@
'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');
function sameWindow(batch,cutoff,window){
return batch.status==='prepared'&&Date.parse(batch.cutoff)===Date.parse(cutoff)&&batch.window?.start===window.start&&batch.window?.end===window.end&&batch.window?.startInclusive===true&&batch.window?.endInclusive===false;
}
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}){
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;
}
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){
if(!this.ready())return;
const config=freeze(structuredClone(this.store.settings()));
const 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){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;}
if(!this.schedule.next||Date.parse(this.schedule.next)>now.getTime())return;
const cutoff=this.schedule.next;
if(now.getTime()-Date.parse(cutoff)>60000){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;}
if(!this.ready())return;
try{
await this.mail.exclusive(config.channelId,async()=>{
if(!this.ready())return;
// A busy mailbox cannot consume the slot or reserve any orders. Recovery
// applies only to this exact business window, never to earlier history.
const window=windowForCutoff(cutoff,schedule,calendar);
const existing=(this.store.snapshot().batches||[]).filter(batch=>sameWindow(batch,cutoff,window));
const fresh=this.store.prepare(cutoff,'系统调度',window).filter(batch=>sameWindow(batch,cutoff,window));
const batches=[...new Map([...existing,...fresh].map(batch=>[batch.id,freeze(structuredClone(batch))])).values()];
let interrupted=false;
for(const batch of batches){
if(!this.ready()){interrupted=true;break;}
if(batch.status!=='prepared')continue;
await this.dispatch(batch,config);
}
if(!interrupted)this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};
});
}catch(error){if(error.status!==409)throw error;}
}
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('归档文件超过邮件大小限制。');
const stat=await fs.stat(file.path);
if(!stat.isFile()||stat.size!==file.size)throw Error('归档文件大小发生变化。');
const content=await fs.readFile(file.path);
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){
let transport,sending=false;
try{
if(batch.channelId&&batch.channelId!==config.channelId){
this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return;
}
const attachments=await this.attachments(batch,config);
if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
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();
if(!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。');
if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
this.mail.store.guard(channel.id,channel.version);
this.store.beginSending(batch.id);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){
this.store.finishSending(batch.id,sending?'unknown':'failed',sending?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`);
}finally{
try{transport?.close?.();}finally{if(transport)this.mail.clients?.delete(transport);}
}
}
start(){
if(this.timer||this.stopped)return;
this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.();
}
async stop(){
this.stopped=true;clearInterval(this.timer);this.timer=null;
if(this.running)await this.running.catch(()=>{});
}
}
module.exports={OrderRuleDispatcher};
+92
View File
@@ -0,0 +1,92 @@
'use strict';
const {extractTitle}=require('./title.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) {
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', 'source 必须为 todo(待办)');
check('事件修订', scalar(sample.revision) && present(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 =>
Array.isArray(rule.processNames) && rule.processNames.includes(sample.processName)
&& Array.isArray(rule.nodeNames) && rule.nodeNames.includes(sample.nodeName));
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.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', '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 ?? {};
const titleSource=Object.hasOwn(sample,'title')?'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), 'brief'])) {
const path = key === 'brief' ? extracted?`${titleSource} → 订单段落`:'brief' : mappings[key] || '';
const value = key === 'brief' ? extracted?extracted.brief:sample.brief : path && Object.hasOwn(raw, path) ? raw[path] : null;
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]) ? '已取得' : '缺失或不是文本'}`);
}
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}:流程“${(rule.processNames || []).join('、')}”到达节点“${(rule.nodeNames || []).join('、')}”时归入本类别。本时段内同类别订单合并一封,通知与更改分别汇总,更早历史不补发。正常工作日首封只取当天零点到首个时点,第二封取两个时点之间;周一首封从上个工作日最后时点起算。${rule.attachPdf ? '附电子流 PDF;' : ''}文件以订单号、${date}、流水编号命名。BPM 节点由人工办理。`;
}
module.exports = { previewMatch, describeRule };
+29
View File
@@ -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'},
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};
+193
View File
@@ -0,0 +1,193 @@
'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,adapters}=require('./catalog.cjs');const {previewMatch,describeRule}=require('./matching.cjs');
const {buildBatch}=require('./batch.cjs');const {transition}=require('./state.cjs');
const {fail,validateRule,publicationIssues}=require('./validation.cjs');
const {windowForCutoff,upcomingWindow,inWindow}=require('./window.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=()=>[]}={}){
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});
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.status==='sending'){
batch.status='unknown';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();}
transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(error){this.db.exec('ROLLBACK');throw error;}}
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;}
saveSettings(input,actor){return this.transaction(()=>{
const old=this.settings();
if(!input||Object.keys(input).some(k=>!['version','enabled','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('邮箱或邮件大小限制无效。');
if(input.enabled&&(!Object.values(this.capabilities).every(Boolean)||!input.channelId))fail('待办接入、PDF 导出与自动归档尚未全部联调,暂不能启用自动发送。',409);
this.put('settings',{...input,id:'main',version:old.version+1});this.audit(actor,'保存分类通知设置',input.enabled?'已启用':'已暂停');return this.settings();
});}
snapshot(){
const rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,adapters)}));
return {rules,adapters:copy(adapters),orders:this.all('orders').reverse(),batches:this.all('batches').reverse(),settings:this.settings(),audit: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;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),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(()=>{
const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
const issues=publicationIssues(record.draft,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'&&r.published.processNames.some(p=>record.draft.processNames.includes(p))&&r.published.nodeNames.some(n=>record.draft.nodeNames.includes(n)));
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()};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(record.published)record.published.status='paused';this.put('rules',record);this.audit(actor,'暂停规则',id);return this.snapshot().rules.find(r=>r.id===id);
});}
matchingPublications(sample){
const rules=this.all('rules').filter(r=>r.published).map(r=>r.published);
const enabled=rules.filter(r=>r.status==='enabled');
const hasEnabledMatch=enabled.some(r=>r.processNames.includes(sample.processName)&&r.nodeNames.includes(sample.nodeName));
return hasEnabledMatch?enabled:rules;
}
ingest(sample,actor){return this.transaction(()=>{
if(sample?.demo)fail('演示样本仅用于试运行,不能创建正式任务。');
if(!sample||['connectionId','source','instanceId','taskId','revision'].some(k=>!['string','number'].includes(typeof sample[k])||!String(sample[k]).trim()||String(sample[k]).length>250))fail('缺少来源、流程实例、任务及业务修订标识。');
sample=copy(sample);for(const key of ['connectionId','source','instanceId','taskId','revision'])sample[key]=String(sample[key]).trim();
const id=digest(['BPM',sample.connectionId,sample.source,sample.instanceId,sample.taskId,sample.revision]);
const sourceHash=digest(sample),old=this.get('orders',id);
if(old){if(old.sourceHash!==sourceHash)fail('相同任务和业务修订的内容已变化,请核实来源版本。',409);return old;}
const active=this.matchingPublications(sample);
const result=previewMatch(active,adapters,sample),rule=active.find(r=>r.id===result.ruleId);
const ready=Object.values(this.capabilities).every(Boolean),enabled=rule?.status==='enabled';
const order={id,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};
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
if(window&&validDate(sample.receivedAt)&&Date.parse(sample.receivedAt)<Date.parse(window.start)){order.status='ignored';order.error='早于当前处理时段的历史订单,不归档、不补发。';}
this.put('orders',order);this.audit(actor,'识别订单任务',id);return order;
});}
recordArchive(id,evidence,actor){return this.transaction(()=>{
if(!this.capabilities.automaticArchive)fail('自动归档接入待联调。',409);
const order=this.get('orders',id);if(!order)fail('订单任务不存在。',404);
if(!['identified','preparing'].includes(order.status))fail('当前状态不允许记录归档结果。',409);
const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
if(window&&Date.parse(order.event.receivedAt)<Date.parse(window.start))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(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')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;
});}
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.batchId||!['blocked','identified','preparing','archived','pending'].includes(order.status))fail('仅未进入批次的待处理订单可以重新识别。',409);
const published=this.matchingPublications(order.sample);
const result=previewMatch(published,adapters,order.sample),rule=published.find(r=>r.id===result.ruleId);
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;
order.archive=null;order.status=Object.values(this.capabilities).every(Boolean)?'identified':'blocked';
order.error=order.status==='blocked'?'待办接入、PDF 导出和自动归档待联调。':null;order.updatedAt=this.now();
this.put('orders',order);this.audit(actor,'应用当前规则重新识别',id+':'+input.note.trim());return order;
});}
prepare(cutoff,actor,requestedWindow){return this.transaction(()=>{
if(!validDate(cutoff))fail('请选择包含时区的有效发送截止时间。');
const window=windowForCutoff(cutoff,this.schedule(),this.calendar());
if(requestedWindow&&(requestedWindow.start!==window.start||requestedWindow.end!==window.end))fail('发送时段与业务日历不一致。',409);
for(const batch of this.all('batches'))if(batch.status==='prepared'&&Date.parse(batch.cutoff)<Date.parse(cutoff)){
batch.status=transition('batch',batch.status,'cancel');batch.error='已错过原发送时段,历史订单不补发。';this.put('batches',batch);this.updateBatchOrders(batch,'ignored',batch.error);
}
const grouped=new Map(),batches=[];
for(const order of this.all('orders')){
if(!['identified','preparing','archived','pending','blocked'].includes(order.status)||!order.categoryId)continue;
const at=order.event.receivedAt||order.sample.receivedAt;
if(validDate(at)&&Date.parse(at)<Date.parse(window.start)){order.status='ignored';order.error='早于本时段的历史订单,不补发。';this.put('orders',order);continue;}
if(!inWindow(at,window))continue;
if(!grouped.has(order.categoryId))grouped.set(order.categoryId,[]);grouped.get(order.categoryId).push(order);
}
for(const orders of grouped.values()){
const rule=orders[0].ruleSnapshot;if(!rule)continue;
if(this.all('batches').some(b=>b.categoryId===rule.categoryId&&Date.parse(b.cutoff)===Date.parse(cutoff)&&!['failed','cancelled'].includes(b.status)))continue;
const published=this.get('rules',rule.id)?.published;
let error=!published||published.status!=='enabled'?'该类别规则已暂停。':null;
if(!error&&orders.some(o=>o.status!=='pending'))error='本类别存在字段、文件或归档尚未准备完成的订单。';
let snapshot;
if(!error)try{snapshot=buildBatch(rule,orders,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window});}catch(cause){error=cause.message;}
if(error){for(const order of orders){order.error=error;this.put('orders',order);}continue;}
const batch={...snapshot,id:crypto.randomUUID(),status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null};
this.put('batches',batch);
for(const order of orders){order.status=transition('order',order.status,'batch');order.batchId=batch.id;order.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);if(order?.batchId===batch.id){order.status=status;order.error=error;order.updatedAt=this.now();this.put('orders',order);}}}
beginSending(id){return this.transaction(()=>{
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
if(this.get('rules',batch.ruleSnapshot.id)?.published?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409);
const orders=batch.orderIds.map(oid=>this.get('orders',oid));
if(orders.some(o=>!o||o.batchId!==id||o.status!=='batched'))fail('批次订单预留已变化。',409);
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.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')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===batch.id){order.batchId=null;this.put('orders',order);}}
this.audit('系统发送','更新批次结果',id+' '+status);return batch;
});}
resolve(id,input,actor){return this.transaction(()=>{
const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
if(!input||!['sent','retry'].includes(input.resolution)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请选择核验结果并填写至少5字依据。');
batch.status=transition('batch',batch.status,input.resolution==='sent'?'resolve_sent':'retry');batch.resolution={...input,actor,at:this.now()};this.put('batches',batch);
this.updateBatchOrders(batch,input.resolution==='sent'?'sent':'pending',null);
if(input.resolution==='retry')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===id){order.batchId=null;this.put('orders',order);}}
this.audit(actor,'核验分类邮件结果',id+':'+input.note.trim());return batch;
});}
close(){this.db.close();this.vault.destroy();}
}
module.exports={RuleStore};
+22
View File
@@ -0,0 +1,22 @@
'use strict';
// Fixed field boundaries keep extraction deterministic; raw title stays on the event.
const retained=new Set(['订单号','机芯号','产品型号','客户简称','总数量','订单类别']);
function extractTitle(title){
const raw=typeof title==='string'?title:'';
const text=raw.replace(/<br\s*\/?\s*>/gi,'\n').replace(/&nbsp;|&#160;|&#x20;/gi,' ');
const matches=[...text.matchAll(/(客户等级|毛利|订单号|机芯号|产品型号|客户简称|总数量|订单类别|订单类型|业务模式)\s*[::]/gu)];
const orders=[],factoryHints=[],issues=[];let current=null;
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==='订单号'){
current={orderNo:value,text:''};orders.push(current);
if(!value)issues.push('标题中的订单号为空,不能遗漏该订单段落');
}
if(current&&retained.has(label))current.text+=`${label}:${value}`;
}
if(!orders.length)issues.push('标题中没有可识别的“订单号:”段落');
return {rawTitle:raw,orders,brief:orders.map(order=>order.text).join('\n'),factoryHints,issues};
}
module.exports={extractTitle};
+42
View File
@@ -0,0 +1,42 @@
'use strict';
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'];
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]]));
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.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.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};
+40
View File
@@ -0,0 +1,40 @@
'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){
const prior=dayOf(new Date(+date-DAY));
const monday=new Date(day+'T00:00:00Z').getUTCDay()===1;
if(monday||!dayPolicy(prior,schedule,overrides).send){
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};