diff --git a/src/app/application.cjs b/src/app/application.cjs index 426dae5..d89804d 100644 --- a/src/app/application.cjs +++ b/src/app/application.cjs @@ -95,7 +95,7 @@ async function main(options = {}) { orderRules=new RuleStore(path.join(stateDir,'order-rules'),{schedule:()=>store.settings().schedule,calendar:()=>workspace.meta('calendar').overrides}); orderProvider=new BpmOrderProvider({manager:bpmSessions});orderArchive=new OrderArchiveProvider({storage,outputDir,journal:orderRules}); orderExecution=new OrderExecutionCoordinator({store:orderRules,workspace,provider:orderProvider,archive:orderArchive,mail,dashboard:store,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,systemPrincipal:custodian.principal}); - orderDispatcher=new OrderRuleDispatcher({store:orderRules,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,providersReady:()=>{const cap=orderExecution.snapshot().capabilities;return ['liveTodo','pdfExport','automaticArchive'].every(key=>cap?.[key]===true);},templateResolver:(categoryId,rule)=>require('../modules/mail/rule-template.cjs').ruleTemplate(mailStore,categoryId,rule),attachmentReader:file=>orderArchive.read(file)}); + orderDispatcher=new OrderRuleDispatcher({store:orderRules,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides,providersReady:()=>{const cap=orderExecution.snapshot().capabilities;return ['liveTodo','pdfExport','automaticArchive'].every(key=>cap?.[key]===true);},templateResolver:(categoryId,rule,mode='normal')=>require('../modules/mail/rule-template.cjs').ruleTemplate(mailStore,categoryId,rule,mode),attachmentReader:file=>orderArchive.read(file)}); orderRules.deliveryBlockers=allowed=>scanStore.deliveries.pendingSources().filter(allowed); bpmMonitor=new BpmArrivalMonitor({workspace,manager:bpmSessions,scanner,provider:orderProvider,settings:()=>store.settings(),onTodoReconciled:payload=>orderExecution.notifyDiscovery(payload)}); assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage,orderRules,orderExecution}); diff --git a/src/modules/order-execution/coordinator.cjs b/src/modules/order-execution/coordinator.cjs index 38c9487..b32cf46 100644 --- a/src/modules/order-execution/coordinator.cjs +++ b/src/modules/order-execution/coordinator.cjs @@ -1,4 +1,5 @@ 'use strict'; +const {needsRuntimeCheck,reserved}=require('../order-rules/delivery.cjs'); const crypto=require('node:crypto'); const {fail}=require('../order-rules/validation.cjs'); const {dayPolicy,nextSlots}=require('../../shared/schedule.cjs'); @@ -189,9 +190,9 @@ class OrderExecutionCoordinator{ } if(hash(task.row)!==hash(row)&&task.ignoredRevisionHash!==hash(row)){task.conflictRow=clone(row);task.status='blocked';task.error='同一事件修订内容冲突,需核对源版本。';task.conflict=true;this.persist(task);} const order=task.orderId&&this.store.get('orders',task.orderId); - const reserved=order?.batchId||['batched','sending','sent','unknown'].includes(order?.status); + const isReserved=reserved(order)||['batched','sending','sent','unknown'].includes(order?.status); const protectedTask=task.supersededBy||task.revisionIgnored||['unknown','sending','sent'].includes(task.status); - if(historical&&!reserved&&!protectedTask)this.holdMissedTask(task,order,frozen); + if(historical&&!isReserved&&!protectedTask)this.holdMissedTask(task,order,frozen); discovered.push(task); } this.query={...this.query,rowCount:rows.length,targetCount:considered,processedCount:0,discoveredAt:this.now()}; @@ -204,13 +205,13 @@ class OrderExecutionCoordinator{ if(task.missedWindow){await this.exception(task,connection,false);continue;} if(task.conflict){await this.exception(task,connection,false);continue;} this.reconcileArchive(task); - if(task.conflict||task.status==='unknown'||task.step==='archive'&&task.status==='failed')continue; + if(task.conflict||task.status==='unknown'&&task.step!=='complete'||task.step==='archive'&&task.status==='failed')continue; const order=task.orderId&&this.store.get('orders',task.orderId); if(order&&['pending','batched','sent','unknown','ignored'].includes(order.status)){ task.status=order.status; task.error=order.error||null; this.persist(task); - if(['pending','batched'].includes(order.status))await this.checkArchivedRuntime(task,order,connection,principal); + if(needsRuntimeCheck(order))await this.checkArchivedRuntime(task,order,connection,principal); continue; } await this.execute(task,connection,principal,{automatic:input.automatic===true}); @@ -226,9 +227,9 @@ class OrderExecutionCoordinator{ if(task.connectionId!==connection.id||observed.has(task.id)||task.conflict)continue; this.reconcileArchive(task); const order=task.orderId&&this.store.get('orders',task.orderId); - if(!order?.archive||!['pending','batched'].includes(order.status))continue; + if(!needsRuntimeCheck(order))continue; const window=this.store.snapshot().window; - if(window&&!order.batchId&&Date.parse(order.event.receivedAt)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}={}){ +function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window,notificationMode='normal'}={}){ 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; @@ -44,16 +44,17 @@ function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window}={}){ 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); + orderIds.push(order.id);orderNos.push(...(notificationMode==='huizhou'?order.event.titleOrders.map(row=>row.orderNo):[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(`
  • ${escape(number)}
    ${lines(order.event.brief)}
    ${files.map(file=>`${escape(file.path)}`).join('
    ')}
  • `); + plain.push(`${number}\n${String(order.event.brief??'')}`+(notificationMode==='huizhou'?'':`\n${files.map(file=>file.path).join('\n')}`)); + html.push(`
  • ${escape(number)}
    ${lines(order.event.brief)}`+(notificationMode==='huizhou'?'':`
    ${files.map(file=>`${escape(file.path)}`).join('
    ')}`)+'
  • '); } 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:`
    ${lines(rule.intro)}
    ${lines(rule.signature)}
    `,to,cc,orderIds,orderNos,attachments,cutoff:new Date(limit).toISOString()}; - if(rule.categoryId==='overseas-notice'){ + snapshot.notificationMode=notificationMode; + if(notificationMode==='normal'&&rule.categoryId==='overseas-notice'){ const content=mailContent(orders); snapshot.text=[rule.intro,content.details,'存放地址:'+content.directories.join('\n'),rule.signature].filter(Boolean).join('\n\n'); snapshot.html='
    '+lines(rule.intro)+'
    '+content.htmlDetails+content.htmlDirectories+'
    '+lines(rule.signature)+'
    '; diff --git a/src/modules/order-rules/delivery.cjs b/src/modules/order-rules/delivery.cjs new file mode 100644 index 0000000..96db6eb --- /dev/null +++ b/src/modules/order-rules/delivery.cjs @@ -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'].includes(delivery(order,'huizhou')?.status));} +function reserved(order){return !!order?.batchId||!!delivery(order,'huizhou')?.batchId;} +module.exports={modeOf,delivery,updateDelivery,notifications,needsRuntimeCheck,reserved}; diff --git a/src/modules/order-rules/dispatcher.cjs b/src/modules/order-rules/dispatcher.cjs index 8adb7f5..b8ee5ff 100644 --- a/src/modules/order-rules/dispatcher.cjs +++ b/src/modules/order-rules/dispatcher.cjs @@ -5,6 +5,7 @@ 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 freeze(value){ if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);} @@ -90,7 +91,7 @@ class OrderRuleDispatcher{ 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&&error.code==='DISCOVERY_INCOMPLETE')return false; + 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==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`); }finally{ @@ -113,9 +114,9 @@ class OrderRuleDispatcher{ 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 o=this.store.get('orders',oid);return !o||['sent','unknown','batched'].includes(o.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);o.batchId=next.id;o.status='batched';o.error=null;this.store.put('orders',o);} + 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); diff --git a/src/modules/order-rules/effects-preview.cjs b/src/modules/order-rules/effects-preview.cjs index 19840b1..9fc67f5 100644 --- a/src/modules/order-rules/effects-preview.cjs +++ b/src/modules/order-rules/effects-preview.cjs @@ -3,8 +3,10 @@ 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 result={simulation:true,archiveVerified:false,filename:null,path:null,mail:null,issues:publicationIssues(rule,store.adapters()),provisionalDate:rule.filenameDate==='archiveDate'}; + 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); @@ -14,8 +16,14 @@ function previewEffects(rule,event,store){ 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(); - const snapshot=applyBodyTemplate(buildBatch(rule,[order],cutoff,{maxMessageBytes:store.settings().maxMessageBytes}),store.templateResolver?.(rule.categoryId,rule),[order],store.settings().maxMessageBytes); - result.mail={subject:snapshot.subject,text:snapshot.text,to:snapshot.to,cc:snapshot.cc,attachments:snapshot.attachments.map(f=>f.name),template:snapshot.template||null}; + 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; } diff --git a/src/modules/order-rules/huizhou.cjs b/src/modules/order-rules/huizhou.cjs new file mode 100644 index 0000000..e563152 --- /dev/null +++ b/src/modules/order-rules/huizhou.cjs @@ -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}; diff --git a/src/modules/order-rules/matching.cjs b/src/modules/order-rules/matching.cjs index 35de489..4da4ba6 100644 --- a/src/modules/order-rules/matching.cjs +++ b/src/modules/order-rules/matching.cjs @@ -58,7 +58,7 @@ function previewMatch(rules, adapters, input, {mappingEvidence=false}={}) { 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} 个订单段落;惠州线索仅供核实,不触发额外发送`); + 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'])) { const selected=readSource(sources[key],sample); diff --git a/src/modules/order-rules/migrations.cjs b/src/modules/order-rules/migrations.cjs index 87eb6b9..267d314 100644 --- a/src/modules/order-rules/migrations.cjs +++ b/src/modules/order-rules/migrations.cjs @@ -7,7 +7,7 @@ const digest=v=>crypto.createHash('sha256').update(JSON.stringify(canonical(v))) function frozen(store,order){ if(!order)return false; - return !!order.batchId||!!order.blockedByBatchId||!!order.missedWindow + 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)); } @@ -99,6 +99,7 @@ function apply(store,id,input,actor){ 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; diff --git a/src/modules/order-rules/query.cjs b/src/modules/order-rules/query.cjs index 04d56bf..13a3369 100644 --- a/src/modules/order-rules/query.cjs +++ b/src/modules/order-rules/query.cjs @@ -2,6 +2,7 @@ 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=['identified','preparing','archived','pending','batched','blocked','unknown','sent','failed','capturing','archiving','queued','ignored']; const batchStates=['prepared','sending','unknown','failed','sent','cancelled']; @@ -37,7 +38,7 @@ function taskEvidence(task,context,user){ } 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']), + return {...event,...pick(order,['id','status','categoryId','error','reason','batchId','createdAt','updatedAt','orderNo','receivedAt']),...(order?{notifications:notifications(order)}:{}), 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}; @@ -76,7 +77,7 @@ function publicRevision(context,user){ } 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']),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))]}; + return {...pick(batch,['id','version','categoryId','subject','status','error','createdAt','windowStart','windowEnd','cutoff','orderNos']),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); @@ -115,9 +116,9 @@ function summary(context,user){ 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:count(rows,['blocked','failed']),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','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||'',legacyBinding:!!r.published&&r.published.bodyTemplateId===undefined,publishedVersion:r.published?.version||null,status:r.published?.status||'draft'})); + 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; } diff --git a/src/modules/order-rules/store.cjs b/src/modules/order-rules/store.cjs index 1446a9e..d370673 100644 --- a/src/modules/order-rules/store.cjs +++ b/src/modules/order-rules/store.cjs @@ -7,6 +7,8 @@ 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 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); @@ -133,6 +135,7 @@ class RuleStore{ const result=previewMatch(active,this.adapters(),sample),rule=active.find(r=>r.id===result.ruleId); const ready=this.providersReady(),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}; + order.notifications={huizhou:initialNotification(rule,order.event)}; const window=upcomingWindow(this.clock(),this.schedule(),this.calendar()); if(window&&validDate(sample.receivedAt)&&Date.parse(sample.receivedAt)b.categoryId===order.categoryId&&b.window&&inWindow(sample.receivedAt,b.window)); @@ -177,6 +180,7 @@ class RuleStore{ const result=previewMatch(published,this.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; + 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; @@ -199,10 +203,10 @@ class RuleStore{ return blockers; } categoryIncomplete(categoryId,window){ - return this.all('execution-tasks').some(task=>task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(task.row?.receivedAt))||inWindow(task.row?.receivedAt,window))&&(task.conflict||['identified','blocked','failed','unknown','capturing','archiving'].includes(task.status)||task.runtimeCheck?.status==='blocked')); + return this.all('execution-tasks').some(task=>task.categoryIds?.includes(categoryId)&&(!Number.isFinite(Date.parse(task.row?.receivedAt))||inWindow(task.row?.receivedAt,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','unknown','capturing','archiving'].includes(task.status))); + 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||[]; @@ -231,42 +235,55 @@ class RuleStore{ const window=windowForCutoff(cutoff,this.schedule(),this.calendar()); if(requestedWindow&&(requestedWindow.start!==window.start||requestedWindow.end!==window.end))fail('发送时段与业务日历不一致。',409); const blockers=this.discoveryBlockers(cutoff); - for(const record of this.all('rules').filter(r=>r.published?.status==='enabled')){const categoryId=record.published.categoryId,existing=this.all('batches').find(b=>b.categoryId===categoryId&&Date.parse(b.cutoff)===Date.parse(cutoff));this.put('window-results',{id:categoryId+':'+cutoff,categoryId,cutoff,status:existing?'frozen':blockers.length?'blocked':'empty',batchId:existing?.id||null,error:blockers.join(';')||null,updatedAt:this.now()});} + 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 record of this.all('rules').filter(r=>r.published?.status==='enabled'))for(const mode of record.published.huizhouEnabled===true?['normal','huizhou']:['normal']){const categoryId=record.published.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')){ - if(!['identified','preparing','archived','pending','blocked'].includes(order.status)||!order.categoryId||order.blockedByBatchId)continue; + 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=order.event.receivedAt||order.sample.receivedAt; - if(validDate(at)&&Date.parse(at)o.id)});continue;} + for(const {mode,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)&&!(b.status==='cancelled'&&b.resolution?.resolution==='retry')))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.get('rules',rule.id)?.published; let error=!published||published.status!=='enabled'?'该类别规则已暂停。':null; - if(!error&&orders.some(o=>o.status!=='pending'))error='本类别存在字段、文件或归档尚未准备完成的订单。'; + 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{snapshot=buildBatch(rule,orders,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window});snapshot=applyBodyTemplate(snapshot,this.templateResolver?.(rule.categoryId,rule),orders,this.settings().maxMessageBytes);}catch(cause){error=cause.message;} - if(error){this.put('window-results',{id:rule.categoryId+':'+cutoff,categoryId:rule.categoryId,cutoff,status:'blocked',error,updatedAt:this.now()});this.recordIssue('build:'+rule.categoryId+':'+cutoff,{component:'rules',error,cutoff,categoryId:rule.categoryId,orderIds:orders.map(o=>o.id)});for(const order of orders){order.error=error;this.put('orders',order);}continue;} + if(!error)try{const selected=ordersForMode(orders,mode);snapshot=buildBatch(rule,selected,cutoff,{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}; - this.put('batches',batch);this.put('window-results',{id:rule.categoryId+':'+cutoff,categoryId:rule.categoryId,cutoff,status:'frozen',batchId:batch.id,updatedAt:this.now()}); - const issue=this.get('business-issues','build:'+rule.categoryId+':'+cutoff);if(issue)this.put('business-issues',{...issue,status:'awaiting_verification',updatedAt:this.now()}); - 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);} + 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);if(order?.batchId===batch.id){order.status=status;order.error=error;order.updatedAt=this.now();this.put('orders',order);}}} + 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); if(!(manual&&batch.manual)&&this.get('rules',batch.ruleSnapshot.id)?.published?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409); - if(!(manual&&batch.manual)&&(this.discoveryBlockers(batch.cutoff).length||this.batchIncomplete(batch)))throw Object.assign(Error('待办扫描或类别订单尚不完整,等待完整扫描与恢复。'),{status:409,code:'DISCOVERY_INCOMPLETE'}); + 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||o.batchId!==id||o.status!=='batched'))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(()=>{ @@ -274,7 +291,7 @@ class RuleStore{ 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')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===batch.id){order.batchId=null;this.put('orders',order);}} + 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; });} @@ -290,7 +307,7 @@ class RuleStore{ 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')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===id){order.batchId=null;this.put('orders',order);}} + 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();} diff --git a/src/modules/order-rules/template.cjs b/src/modules/order-rules/template.cjs index daa1df7..5df4eb7 100644 --- a/src/modules/order-rules/template.cjs +++ b/src/modules/order-rules/template.cjs @@ -4,6 +4,7 @@ const {fail}=require('./validation.cjs'); const {mailContent,fileLink}=require('./mail-content.cjs'); const has=(part,key)=>new RegExp('{{\\s*'+key+'\\s*}}').test(part||''); function applyBodyTemplate(snapshot,template,orders,maxMessageBytes){ + if(snapshot.notificationMode==='huizhou')return applyHuizhouTemplate(snapshot,template,orders,maxMessageBytes); if(!template)return snapshot; const listing=orders.map(order=>`${order.event.orderNo}\n${String(order.event.brief||'')}\n${order.archive.files.map(file=>file.path).join('\n')}`).join('\n\n'); const content=mailContent(orders),category=orders[0]?.ruleSnapshot?.name||''; @@ -28,4 +29,17 @@ function applyBodyTemplate(snapshot,template,orders,maxMessageBytes){ if(bytes>maxMessageBytes)fail('关联模板展开后超过邮件容量限制。'); return {...snapshot,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 content=mailContent(orders),details=content.details; + const values={'产品线':[...new Set(orders.map(order=>order.event.productLine).filter(Boolean))].join('、'),'订单号':snapshot.orderNos.join('、'),'日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(snapshot.cutoff)),'订单列表':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):'
    '+escape(text).replace(/\r?\n/g,'
    ')+'
    '; + 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}; diff --git a/src/modules/order-rules/title.cjs b/src/modules/order-rules/title.cjs index d22d5b2..82bc305 100644 --- a/src/modules/order-rules/title.cjs +++ b/src/modules/order-rules/title.cjs @@ -7,7 +7,7 @@ function extractTitle(title){ const raw=typeof title==='string'?title:''; const text=raw.replace(//gi,'\n').replace(/ | | /gi,' '); const matches=[...text.matchAll(/(客户等级|毛利|订单号|机芯号|产品型号|客户简称|出货方式|总数量|订单类别|订单类型|业务模式)\s*[::]/gu)]; - const orders=[],factoryHints=[],issues=[];let current=null; + const orders=[],factoryHints=[],issues=[];let current=null,pendingMode=null,pendingAmbiguous=false; for(let i=0;iindex>i&&m[1]==='订单号'); + const between=nextOrder<0?[]:matches.slice(i+1,nextOrder).map(m=>m[1]); + // BPM starts the next paragraph with business mode + margin before its order number. + // Ordinary summary text remains byte-for-byte compatible with the existing extractor. + const startsParagraph=/[\n|]\s*$/.test(text.slice(0,match.index)); + if(!current||nextOrder>=0&&(between.includes('毛利')||startsParagraph)){ + 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('标题中没有可识别的“订单号:”段落'); diff --git a/tests/order-rules/huizhou-notification.test.cjs b/tests/order-rules/huizhou-notification.test.cjs new file mode 100644 index 0000000..f8edce6 --- /dev/null +++ b/tests/order-rules/huizhou-notification.test.cjs @@ -0,0 +1,140 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'),crypto=require('node:crypto'); +const {RuleStore}=require('../../src/modules/order-rules/store.cjs'); +const {extractTitle}=require('../../src/modules/order-rules/title.cjs'); +const {OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs'); +const {activateReferenceMapping}=require('../fixtures/activate-field-mapping.cjs'); +const {orderDetail,batchDetail,summary}=require('../../src/modules/order-rules/query.cjs'); +const {previewEffects}=require('../../src/modules/order-rules/effects-preview.cjs'); +const cutoff='2026-10-19T03:00:00.000Z',admin={username:'admin',role:'admin'}; +const mixed='订单号:O-100机芯号:CORE-O客户简称:普通客户总数量:10订单类别:参考订单订单类型:C业务模式:惠州数字毛利:绿标订单号:H-200机芯号:CORE-H客户简称:惠州创维数字技术有限公司总数量:20'; +function fixture(t,{enabled=true,title=mixed,template={}}={}){ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'huizhou-delivery-')),clock=()=>new Date('2026-10-19T02:00:00Z'); + const options={clock,capabilities:{liveTodo:true,pdfExport:true,automaticArchive:true}};let store=new RuleStore(dir,options); + const huiTemplate={id:'hui-template',version:1,status:'active',notificationMode:'huizhou',subject:'惠州 {{订单号}}',text:'业务访问 https://example.test/business\n{{订单明细}}',html:'

    业务访问 https://example.test/business

    {{订单明细}}
    ',...template}; + const resolver=(category,rule,mode='normal')=>mode==='huizhou'?huiTemplate:null;store.templateResolver=resolver; + t.after(()=>{store.close();fs.rmSync(dir,{recursive:true,force:true});}); + const reference=require('../../src/modules/order-rules/catalog.cjs').adapters.find(a=>a.id==='bs-change'); + const {sample}=activateReferenceMapping(store,'bs-change',{connectionId:'c1',instanceId:'i1',taskId:'t1',revision:'1',receivedAt:'2026-10-19T01:00:00Z',title,fields:{[reference.fields.orderNo]:extractTitle(title).orders[0].orderNo}}); + const rule=store.saveRule({...store.get('rules','bs-change').draft,to:['USER@example.test'],cc:['copy@example.test'],archiveDirectory:'\\\\server\\orders',filenameDate:'receivedAt',huizhouEnabled:enabled,huizhouTemplateId:enabled?'hui-template':''},'admin'); + // Capture the final real-shaped sample through the normal mapping/trial contract. + const capture=store.recordCapture({sample,taskId:'final',snapshot:{processVersion:sample.processVersion,fields:Object.entries(sample.fields).map(([path,value])=>({path,value}))}}); + assert.equal(store.capturedPreview(capture.id).valid,true);store.publish(rule.id,{version:rule.version},'admin'); + store.saveSettings({...store.settings(),enabled:true,channelId:'channel'},'admin'); + const bytes=Buffer.from('%PDF-1.7\nisolated Hui fixture'),sha256=crypto.createHash('sha256').update(bytes).digest('hex'); + function ingest(extra={}){const order=store.ingest({...sample,...extra},'system');store.recordArchive(order.id,{archivedAt:'2026-10-19T01:10:00Z',files:[{name:'O-100.pdf',path:'C:\\archive\\O-100.pdf',kind:'pdf',size:bytes.length,sha256}]},'executor');return store.get('orders',order.id);} + const order=ingest(),sent=[];let verifyFailure=false,sendFailure=false; + const mail={exclusive:async(id,work)=>work(),store:{channelSecret:()=>({id:'channel',version:1,email:'sender@example.test',name:'test',smtp:{host:'unused.invalid'}}),guard:()=>{}},smtpFactory:()=>({verify:async()=>{if(verifyFailure)throw Error('verify unavailable');},sendMail:async message=>{sent.push(message);if(sendFailure)throw Error('lost SMTP result');return {accepted:[...message.to,...message.cc],rejected:[]};},close:()=>{}})}; + return {get store(){return store;},order,sample,rule,bytes,sent,ingest,huiTemplate,mail,clock,failVerify(v){verifyFailure=v;},failSend(v){sendFailure=v;},dispatcher(){return new OrderRuleDispatcher({store,mail,settings:()=>({schedule:{times:['11:00','17:00'],weekends:false}}),clock:()=>new Date(cutoff),providersReady:()=>true,attachmentReader:async()=>bytes});},reopen(){store.close();store=new RuleStore(dir,options);store.templateResolver=resolver;return store;},context(){return {orderRules:store,workspace:{recordSources:()=>[{id:'c1',owner:'admin'}]}};}}; +} +function pair(f){const batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,2);return {normal:batches.find(b=>b.notificationMode==='normal'),hui:batches.find(b=>b.notificationMode==='huizhou')};} + +test('mixed event freezes only Hui title details with identical recipients and one shared archive',t=>{ + const f=fixture(t),{normal,hui}=pair(f); + assert.match(normal.text,/O-100/);assert.match(normal.text,/H-200/); + assert.deepEqual(hui.orderNos,['H-200']);assert.match(hui.subject,/H-200/);assert.doesNotMatch(hui.subject+hui.text+hui.html,/O-100|CORE-O/); + assert.match(hui.text,/CORE-H/);assert.match(hui.text,/https:\/\/example.test\/business/);assert.doesNotMatch(hui.text,/C:\\archive|存放地址/); + assert.deepEqual(hui.to,normal.to);assert.deepEqual(hui.cc,normal.cc);assert.deepEqual(hui.attachments,normal.attachments); + assert.deepEqual(f.store.prepare(cutoff,'admin'),[]);assert.equal(f.store.all('orders').length,1);assert.equal(f.store.all('batches').length,2); +}); +test('business mode before a new segment binds forward, and explicit inline mode binds to its own order',()=>{ + const rows=extractTitle(mixed).orders;assert.equal(rows[0].businessMode,undefined);assert.equal(rows[1].businessMode,'惠州数字'); + assert.equal(extractTitle('业务模式:惠州订单号:H-1客户简称:惠州创维数字技术有限公司').orders[0].businessMode,'惠州'); + assert.equal(extractTitle('订单号:H-1业务模式:惠州模式客户简称:惠州创维数字技术有限公司').orders[0].businessMode,'惠州模式'); +}); +test('a separated next-paragraph business mode cannot leak into the preceding ordinary order',()=>{ + const rows=extractTitle('订单号:O-100客户简称:普通客户\n业务模式:惠州数字订单号:H-200客户简称:终端客户').orders; + assert.equal(rows[0].businessMode,undefined);assert.equal(rows[1].businessMode,'惠州数字'); +}); +test('conflicting business headers for the same segment remain visible Hui uncertainty',()=>{ + const {selectHuizhou}=require('../../src/modules/order-rules/huizhou.cjs'); + const selection=selectHuizhou({titleOrders:extractTitle('业务模式:普通业务模式:惠州订单号:H-200客户简称:惠州创维数字技术有限公司').orders});assert.equal(selection.orders.length,0);assert.equal(selection.issues.length,1); +}); +for(const title of ['订单号:HA200客户简称:未知客户','订单号:H-200业务模式:普通客户简称:惠州创维数字技术有限公司'])test('uncertain evidence remains Hui-only and normal still freezes: '+title,t=>{ + const f=fixture(t,{title}),batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);assert.equal(batches[0].notificationMode,'normal'); + const detail=orderDetail(f.context(),f.order.id,admin);assert.equal(detail.notifications.huizhou.status,'blocked');assert.ok(detail.notifications.huizhou.issues.length); +}); +test('trusted Hui business mode is sufficient with a general end-customer name',t=>{ + const f=fixture(t,{title:'订单号:H-200业务模式:惠州模式客户简称:普通客户名称'}),{hui}=pair(f);assert.deepEqual(hui.orderNos,['H-200']);assert.match(hui.text,/普通客户名称/); +}); +test('old ordinary frozen batch cannot acquire a companion from a later Hui-enabled snapshot',t=>{ + const f=fixture(t),{normal,hui}=pair(f);f.store.db.prepare('DELETE FROM records WHERE kind=? AND id=?').run('batches',hui.id); + const legacy=f.store.get('batches',normal.id);delete legacy.notificationMode;delete legacy.huizhouPlanned;f.store.put('batches',legacy); + const order=f.store.get('orders',f.order.id);order.notifications.huizhou={status:'pending',batchId:null,error:null,orderNos:['H-200'],issues:[]};f.store.put('orders',order); + assert.deepEqual(f.store.prepare(cutoff,'admin'),[]);assert.equal(f.store.all('batches').length,1); +}); +for(const opts of [{enabled:false},{title:'订单号:O-100客户简称:普通客户'},{title:'订单号:O-100客户简称:惠州某其他公司'}])test('disabled or empty recognized Hui set never creates an extra batch '+JSON.stringify(opts),t=>{ + const f=fixture(t,opts),batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);assert.equal(batches[0].notificationMode,'normal');assert.equal(f.store.prepare(cutoff,'admin').length,0); +}); +test('legacy order without delivery eligibility never gains a companion even after enabling rule',t=>{ + const f=fixture(t),old=f.store.get('orders',f.order.id);delete old.notifications;delete old.ruleSnapshot.huizhouEnabled;delete old.ruleSnapshot.huizhouTemplateId;f.store.put('orders',old); + const batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);assert.equal(batches[0].notificationMode,'normal'); + const frozen=f.store.get('batches',batches[0].id);delete frozen.notificationMode;f.store.put('batches',frozen);assert.equal(f.store.prepare(cutoff,'admin').length,0); +}); +test('normal sent and Hui failed permit exactly one Hui resend without replaying normal',async t=>{ + const f=fixture(t),{normal,hui}=pair(f),d=f.dispatcher();t.after(()=>d.stop());await d.dispatch(normal,f.store.settings());f.failVerify(true);await d.dispatch(hui,f.store.settings()); + assert.equal(f.store.get('orders',f.order.id).status,'sent');assert.equal(f.store.get('batches',hui.id).status,'failed');f.failVerify(false); + const input={version:f.store.get('batches',hui.id).version,idempotencyKey:'hui-resend',note:'已确认失败并修复邮件连接'}; + const retry=await d.resend(hui.id,input,admin);assert.equal(retry.status,'sent');assert.equal((await d.resend(hui.id,input,admin)).id,retry.id);assert.equal(f.sent.length,2); + assert.deepEqual(f.sent.map(m=>m.subject),[normal.subject,hui.subject]);assert.equal(orderDetail(f.context(),f.order.id,admin).notifications.huizhou.status,'sent'); +}); +test('normal unknown does not prevent Hui delivery or let Hui recovery alter normal',async t=>{ + const f=fixture(t),{normal,hui}=pair(f),d=f.dispatcher();t.after(()=>d.stop());f.failSend(true);await d.dispatch(normal,f.store.settings());f.failSend(false);await d.dispatch(hui,f.store.settings()); + assert.equal(f.store.get('batches',normal.id).status,'unknown');assert.equal(f.store.get('batches',hui.id).status,'sent');assert.equal(f.store.get('orders',f.order.id).status,'unknown'); + await assert.rejects(()=>d.resend(normal.id,{version:f.store.get('batches',normal.id).version,idempotencyKey:'no-unknown',note:'不能未核验直接补发'},admin)); + f.store.resolve(normal.id,{resolution:'sent',note:'服务器已确认全部接收'},'admin');assert.equal(orderDetail(f.context(),f.order.id,admin).notifications.huizhou.status,'sent'); +}); +test('restart marks only sending Hui unknown and manual resolution reserves only Hui',t=>{ + const f=fixture(t),{normal,hui}=pair(f);f.store.beginSending(normal.id);f.store.finishSending(normal.id,'sent');f.store.beginSending(hui.id);f.reopen(); + assert.equal(f.store.get('orders',f.order.id).status,'sent');assert.equal(f.store.get('batches',hui.id).status,'unknown');assert.equal(orderDetail(f.context(),f.order.id,admin).notifications.huizhou.status,'unknown'); + f.store.resolve(hui.id,{resolution:'retry',note:'已核验服务器未接收惠州通知'},'admin');assert.equal(f.store.get('orders',f.order.id).status,'sent');assert.equal(orderDetail(f.context(),f.order.id,admin).notifications.huizhou.status,'pending'); +}); +test('missing or wrong-mode Hui template blocks Hui without discarding ordinary batch',t=>{ + for(const template of [{notificationMode:'normal'},null]){ + const f=fixture(t,{template:template||{}});if(template===null)f.store.templateResolver=()=>null; + const batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);assert.equal(batches[0].notificationMode,'normal');assert.match(orderDetail(f.context(),f.order.id,admin).notifications.huizhou.error,/模板/); + } +}); +test('authorized previews expose both modes and preserve mandatory Hui details when template omits variables',t=>{ + const f=fixture(t,{template:{text:'访问 https://example.test/business',html:'

    访问 https://example.test/business

    '}}),preview=previewEffects(f.store.get('orders',f.order.id).ruleSnapshot,f.order.event,f.store); + assert.match(preview.mail.text,/O-100/);assert.deepEqual(preview.notifications.huizhou.orderNos,['H-200']);assert.match(preview.notifications.huizhou.mail.text,/CORE-H/);assert.doesNotMatch(preview.notifications.huizhou.mail.text,/O-100|存放地址/); + const {hui}=pair(f);assert.equal(batchDetail(f.context(),hui.id,admin).notificationMode,'huizhou');assert.throws(()=>orderDetail(f.context(),f.order.id,{role:'operator',username:'outsider'}),/无权|不存在/); + assert.equal(JSON.stringify(orderDetail(f.context(),f.order.id,admin)).includes('rawTitle'),false); +}); +test('summary counts Hui-only blockers once after the ordinary notification has been sent',t=>{ + const f=fixture(t);f.store.templateResolver=()=>null;const normal=f.store.prepare(cutoff,'admin')[0];f.store.beginSending(normal.id);f.store.finishSending(normal.id,'sent'); + const result=summary(f.context(),admin);assert.equal(result.counts.blocked,1);assert.equal(result.issues.some(i=>i.notificationMode==='huizhou'),true); +}); +for(const ordinaryStatus of ['sent','unknown'])for(const observed of [true,false])test(`archived runtime checks continue with ordinary ${ordinaryStatus} and Hui reserved; todo observed=${observed}`,async t=>{ + const f=fixture(t),{normal,hui}=pair(f);f.store.beginSending(normal.id);f.store.finishSending(normal.id,ordinaryStatus); + const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs'); + const connection={id:'c1',owner:'admin',status:'connected'},row={...f.sample};delete row.fields;delete row.brief; + const taskId=crypto.createHash('sha256').update(JSON.stringify(['c1','todo',String(row.instanceId),String(row.taskId),String(row.revision)])).digest('hex'); + f.store.put('execution-tasks',{id:taskId,version:1,connectionId:'c1',owner:'admin',orderId:f.order.id,row,categoryIds:['bs-change'],status:ordinaryStatus,step:'complete'}); + let corrupt=false,reads=0; + const provider={scan:async()=>observed?[row]:[],capabilities:()=>({liveTodo:true,pdfExport:true}),capture:async()=>{throw Error('must not capture archived event again');}}; + const archive={capabilities:()=>({automaticArchive:true,pdfExport:true}),probe:async()=>({automaticArchive:true,pdfExport:true}),read:async()=>{reads++;return corrupt?Buffer.from('bad'):f.bytes;},archive:async()=>{throw Error('must not export archived event again');}}; + const execution=new OrderExecutionCoordinator({store:f.store,workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},provider,archive,clock:()=>new Date(cutoff)});t.after(()=>execution.stop()); + await execution.scan({connectionId:'c1',idempotencyKey:'healthy'}, {user:admin,sessionId:'fixture-session'});assert.equal(reads,1);assert.equal(f.store.get('execution-tasks',taskId).runtimeCheck.status,'ready');assert.equal(f.store.beginSending(hui.id).status,'sending'); + corrupt=true;await execution.scan({connectionId:'c1',idempotencyKey:'tampered'}, {user:admin,sessionId:'fixture-session'});assert.equal(reads,2);assert.equal(f.store.get('execution-tasks',taskId).runtimeCheck.status,'blocked'); + assert.throws(()=>f.store.beginSending(hui.id),/完整|复核/);assert.equal(f.store.get('orders',f.order.id).status,ordinaryStatus); +}); +test('normal failure cannot auto-refreeze while Hui remains independent and cutoff groups stay separate',t=>{ + const f=fixture(t),{normal,hui}=pair(f);f.store.finishSending(normal.id,'failed','normal verify failed');f.store.beginSending(hui.id);f.store.finishSending(hui.id,'sent');assert.deepEqual(f.store.prepare(cutoff,'admin'),[]); + const later=f.ingest({taskId:'later',instanceId:'later',receivedAt:'2026-10-19T04:00:00Z'}),batches=f.store.prepare('2026-10-19T09:00:00.000Z','admin');assert.equal(batches.length,2);assert.ok(batches.every(b=>b.orderIds.length===1&&b.orderIds[0]===later.id)); + assert.equal(f.store.get('batches',normal.id).status,'failed');assert.equal(f.store.get('batches',hui.id).status,'sent'); +}); +test('repaired Hui preparation ignores normal SMTP unknown on a completed task but preserves source uncertainty gates',t=>{ + const f=fixture(t);f.store.templateResolver=()=>null;const normal=f.store.prepare(cutoff,'admin')[0];f.store.beginSending(normal.id);f.store.finishSending(normal.id,'unknown'); + const task={id:'complete-task',orderId:f.order.id,categoryIds:['bs-change'],row:{receivedAt:f.order.event.receivedAt},step:'archive',status:'unknown',runtimeCheck:{status:'ready'}};f.store.put('execution-tasks',task); + f.store.templateResolver=(category,rule,mode)=>mode==='huizhou'?f.huiTemplate:null; + assert.deepEqual(f.store.prepare(cutoff,'admin'),[]); + task.step='complete';task.conflict=true;f.store.put('execution-tasks',task);assert.deepEqual(f.store.prepare(cutoff,'admin'),[]); + task.conflict=false;f.store.put('execution-tasks',task);const batches=f.store.prepare(cutoff,'admin');assert.equal(batches.length,1);assert.equal(batches[0].notificationMode,'huizhou');assert.equal(f.store.beginSending(batches[0].id).status,'sending');assert.equal(f.store.get('orders',f.order.id).status,'unknown'); +}); +test('manual Hui resend cannot bypass a new source conflict on the shared archive task',async t=>{ + const f=fixture(t),{normal,hui}=pair(f),d=f.dispatcher();t.after(()=>d.stop());f.store.beginSending(normal.id);f.store.finishSending(normal.id,'sent');f.store.finishSending(hui.id,'failed'); + f.store.put('execution-tasks',{id:'conflict-task',orderId:f.order.id,categoryIds:['bs-change'],row:{receivedAt:f.order.event.receivedAt},step:'complete',status:'sent',conflict:true,runtimeCheck:{status:'ready'}}); + const result=await d.resend(hui.id,{version:f.store.get('batches',hui.id).version,idempotencyKey:'conflict-resend',note:'核验发送失败但来源仍存在冲突'},admin); + assert.equal(result.status,'failed');assert.equal(f.sent.length,0);assert.equal(f.store.get('orders',f.order.id).status,'sent'); +});