From 98a752d0957251c9539ad9c5167ba8115ae8a356 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=98=BF=E7=99=BD=E5=8F=94?= <11794527+absfan@user.noreply.gitee.com> Date: Wed, 2 Dec 2026 09:08:17 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E8=AE=A2=E5=8D=95=E9=80=9A=E7=9F=A5):=20?= =?UTF-8?q?=E5=AE=8C=E5=96=84=E7=B3=BB=E7=BB=9FCA=E5=8E=BB=E9=87=8D?= =?UTF-8?q?=E5=8A=A0=E8=BD=BD=E3=80=81=E5=8F=91=E9=80=81=E9=97=B8=E9=97=A8?= =?UTF-8?q?=E5=AE=B9=E9=94=99=E3=80=81=E9=A2=84=E6=A3=80=E8=AF=8A=E6=96=AD?= =?UTF-8?q?=E9=80=8F=E4=BC=A0=E4=B8=8E=E5=BD=92=E6=A1=A3=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E9=97=AD=E7=8E=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/application.cjs | 1 + src/modules/bpm/arrival-monitor.cjs | 2 +- src/modules/order-execution/coordinator.cjs | 5 +- src/modules/order-rules/discovery-barrier.cjs | 5 +- src/modules/order-rules/dispatcher.cjs | 39 ++- src/modules/order-rules/import.cjs | 8 +- src/modules/order-rules/template.cjs | 13 +- src/modules/storage/files.cjs | 5 +- src/modules/storage/order-archive.cjs | 13 +- src/modules/storage/service.cjs | 6 +- src/platform/security/windows-directory.cjs | 2 +- src/platform/service/supervisor.cjs | 2 +- src/platform/tls-system-ca.cjs | 20 ++ src/server.cjs | 4 +- ...production-regressions-2026-12-02.test.cjs | 227 ++++++++++++++++++ .../scheduled-mail-policy.test.cjs | 10 +- web/modules/order-rules/editor.js | 5 +- web/modules/order-rules/view.js | 2 +- 18 files changed, 330 insertions(+), 39 deletions(-) create mode 100644 src/platform/tls-system-ca.cjs create mode 100644 tests/order-rules/production-regressions-2026-12-02.test.cjs diff --git a/src/app/application.cjs b/src/app/application.cjs index 197190c..8f69c50 100644 --- a/src/app/application.cjs +++ b/src/app/application.cjs @@ -1,3 +1,4 @@ +require('../platform/tls-system-ca.cjs'); const crypto = require('node:crypto'); const fs = require('node:fs/promises'); const path = require('node:path'); diff --git a/src/modules/bpm/arrival-monitor.cjs b/src/modules/bpm/arrival-monitor.cjs index caf240c..d949d92 100644 --- a/src/modules/bpm/arrival-monitor.cjs +++ b/src/modules/bpm/arrival-monitor.cjs @@ -88,7 +88,7 @@ class BpmArrivalMonitor{ // Delivery has its own persisted outcome; a callback cannot rewrite a committed read. if(delivery)await this.publishPending(id,canCommit).catch(()=>{}); return {...result,runId}; - }catch(error){this.scanner.store.fail(runId,error.code==='TODO_IDENTITY_AMBIGUOUS'?error.message:error.status===401?'需要恢复BPM登录。':error.status===409?'连接忙碌或已暂停。':'待办对账失败,请稍后重试。');this.sourceFailure(entry,'todo',error);throw error;} + }catch(error){const detail=String(error?.message||'').replace(/[\r\n\x00-\x1f]+/g,' ').trim().slice(0,120);this.scanner.store.fail(runId,error.code==='TODO_IDENTITY_AMBIGUOUS'?error.message:error.status===401?'需要恢复BPM登录。':error.status===409?'连接忙碌或已暂停。':detail?`待办对账失败(${detail}),请稍后重试。`:'待办对账失败,请稍后重试。');this.sourceFailure(entry,'todo',error);throw error;} }).finally(()=>this.todoPending.delete(id));this.todoPending.set(id,promise);return {runId,promise}; } publishPending(id,canDeliver=()=>true){ diff --git a/src/modules/order-execution/coordinator.cjs b/src/modules/order-execution/coordinator.cjs index e17f448..1345628 100644 --- a/src/modules/order-execution/coordinator.cjs +++ b/src/modules/order-execution/coordinator.cjs @@ -370,7 +370,10 @@ class OrderExecutionCoordinator{ finally{ this.store.put('execution-query',this.query); const preserveNewer=this.query.status==='complete'&&previousScan?.status==='complete'&&Date.parse(previousScan.startedAt)>Date.parse(this.query.startedAt); - this.store.put('execution-scans',preserveNewer?previousScan:{...this.query,id:connection.id}); + const lastCompleteStartedAt=this.query.status==='complete'?(preserveNewer?previousScan.startedAt:this.query.startedAt):(previousScan?.lastCompleteStartedAt||(previousScan?.status==='complete'?previousScan.startedAt:null)); + const savedScan=preserveNewer?{...previousScan}:({...this.query,id:connection.id}); + if(lastCompleteStartedAt)savedScan.lastCompleteStartedAt=lastCompleteStartedAt; + this.store.put('execution-scans',savedScan); } return this.snapshot(principal); }).finally(()=>{this.store.activeDiscoveries--;}).then(()=>this.snapshot(principal)); diff --git a/src/modules/order-rules/discovery-barrier.cjs b/src/modules/order-rules/discovery-barrier.cjs index c0e9713..a930376 100644 --- a/src/modules/order-rules/discovery-barrier.cjs +++ b/src/modules/order-rules/discovery-barrier.cjs @@ -15,8 +15,9 @@ function discoveryBlockers(store,cutoff,allowed=()=>true){ if(store.activeDiscoveries>0)blockers.push('待办扫描尚未完成,不能冻结或发送不完整类别。'); for(const id of sources){ const scan=store.get('execution-scans',id); - if(scan?.status!=='complete')blockers.push('连接 '+id+' 尚无完整成功扫描'+(scan?.error?':'+scan.error:'。')); - else if(cutoff&&Date.parse(scan.startedAt)mail.store.signature(id); } + warnStalledBatches(now){ + for(const batch of this.store.all('batches')){ + const age=now-Date.parse(batch.cutoff); + if(batch.status==='prepared'&&!batch.manual&&!batch.submissionAttemptedAt&&!batch.dispatchWarning&&age>120000&&age<=1800000){ + const updated={...batch,version:(batch.version||1)+1,dispatchWarning:this.clock().toISOString()}; + this.store.put?.('batches',updated); + this.store.recordIssue?.('dispatch-warning:'+batch.id,{component:'mail',batchId:batch.id,error:'批次已冻结超过2分钟仍未提交SMTP,请检查发送闸门。',orderIds:batch.orderIds,cutoff:batch.cutoff}); + this.store.audit?.('系统发送','冻结未发告警',batch.id); + } + } + } ready(){ // Real RuleStore exposes immutable capabilities directly; retain the small // snapshot fallback for adapters and older test/runtime stores. @@ -46,19 +71,19 @@ class OrderRuleDispatcher{ async perform(now){ this.store.expireIntakes?.(); for(const batch of this.store.all('batches').reverse())if(batch.status==='prepared'&&!batch.manual&&now-Date.parse(batch.cutoff)>1800000)this.store.finishSending(batch.id,'failed','冻结发送队列超过30分钟,请负责人核验后受控补发。',{outcome:'not_submitted',phase:'queue_expired',at:this.clock().toISOString()}); - for(const batch of this.store.all('batches'))if(batch.status==='prepared'&&!batch.submissionAttemptedAt&&!batch.dispatchWarning&&now-Date.parse(batch.cutoff)>120000){batch.dispatchWarning=this.clock().toISOString();this.store.put('batches',batch);this.store.recordIssue?.('dispatch-warning:'+batch.id,{component:'mail',batchId:batch.id,error:'批次已冻结超过2分钟仍未提交SMTP,请检查发送闸门。',orderIds:batch.orderIds,cutoff:batch.cutoff});this.store.audit?.('系统发送','冻结未发告警',batch.id);} + this.warnStalledBatches(now); if(!this.ready())return; const config=freeze(structuredClone(this.store.settings())),schedule=this.settings()?.schedule,calendar=this.calendar(); if(!schedule?.times?.length)return; const signature=JSON.stringify([schedule,calendar]); if(!this.schedule||this.schedule.signature!==signature||now-Date.parse(this.schedule.next)>60000){const current=require('./window.cjs').upcomingWindow(now,schedule,calendar);this.schedule={signature,next:current?.available?current.end:nextSlots(schedule,now,1,calendar)[0]};} const resumed=this.store.pendingIntakeCutoffs?.().filter(cutoff=>now-Date.parse(cutoff)>60000)||[]; - const cutoff=resumed[0]||this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&(now-Date.parse(cutoff)<=65000||resumed.includes(cutoff)); + const cutoff=resumed[0]||this.schedule.next,canPrepare=cutoff&&now-Date.parse(cutoff)>=0&&(now-Date.parse(cutoff)<=60000||resumed.includes(cutoff)); const queued=this.store.all('batches').some(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000); if(!canPrepare&&!queued)return; try{await this.mail.exclusive(config.channelId,async()=>{ - for(const batch of this.store.all('batches'))if(batch.status==='prepared'&&!batch.submissionAttemptedAt&&!batch.dispatchWarning&&now-Date.parse(batch.cutoff)>120000){batch.dispatchWarning=this.clock().toISOString();this.store.put('batches',batch);this.store.recordIssue?.('dispatch-warning:'+batch.id,{component:'mail',batchId:batch.id,error:'批次已冻结超过2分钟仍未提交SMTP,请检查发送闸门。',orderIds:batch.orderIds,cutoff:batch.cutoff});this.store.audit?.('系统发送','冻结未发告警',batch.id);} - if(!this.ready())return; + this.warnStalledBatches(this.clock()); + if(!this.ready())return; if(canPrepare&&!this.store.discoveryBlockers(cutoff).length){const window=windowForCutoff(cutoff,schedule,calendar);this.store.prepare(cutoff,'系统调度',window);} // A frozen collection is immutable. Queue time is distinct from collection time. const batches=this.store.all('batches').reverse().filter(b=>b.status==='prepared'&&!b.manual&&now-Date.parse(b.cutoff)>=0&&now-Date.parse(b.cutoff)<=1800000); @@ -67,7 +92,7 @@ class OrderRuleDispatcher{ const legacyStart=new Date(Date.parse(batch.cutoff)+8*3600000).toISOString().slice(0,10)+'T00:00:00+08:00'; if(!batch.window||batch.window.end!==expected.end||![Date.parse(expected.start),Date.parse(legacyStart)].includes(Date.parse(batch.window.start))||batch.window.startInclusive!==true||batch.window.endInclusive!==false)continue; const grace=batch.intakeGrace?.cutoff===batch.cutoff&&Date.parse(batch.intakeGrace.expiresAt)===Date.parse(batch.cutoff)+1800000&&Date.parse(batch.createdAt)<=Date.parse(batch.intakeGrace.expiresAt)&&batch.orderIds?.every(id=>{const order=this.store.get('orders',id);return order&&(this.store.intakeWindow(order.sample||order.event)?.end===batch.cutoff||require('./carry-forward.cjs').windowForOrder(this.store,order,modeOf(batch))?.end===batch.cutoff);}); - const prepareSkewMs=5000;if(batch.createdAt&&(Date.parse(batch.createdAt)>Date.parse(batch.cutoff)+60000+prepareSkewMs&&!grace||Date.parse(batch.createdAt)Date.parse(batch.cutoff)+60000+prepareSkewMs&&!grace||Date.parse(batch.createdAt)60000)this.schedule={signature,next:nextSlots(schedule,this.clock(),1,calendar)[0]}; @@ -117,10 +142,10 @@ class OrderRuleDispatcher{ this.store.finishSending(batch.id,partial?'unknown':'sent',partial?'部分收件人未被服务器接受,请核对邮件记录后处理。':'邮件服务器已接受全部收件人;最终送达请以邮件记录为准。'); }catch(error){ if(!sending&&!manual&&error.code==='DISCOVERY_INCOMPLETE')return false; - const transient=['ETIMEDOUT','ECONNRESET','ECONNREFUSED','EAI_AGAIN','EPIPE','ESOCKET','EHOSTUNREACH','ENETUNREACH','UND_ERR_CONNECT_TIMEOUT'].includes(error.code)||/ETIMEDOUT|ECONNRESET|ECONNREFUSED|EAI_AGAIN|socket hang up|网络|连接超时/i.test(String(error.message||''));if(!manual&&!sending&&transient&&(batch.retryCount||0)<3&&this.clock()-Date.parse(batch.cutoff)<1800000){const retryCount=(batch.retryCount||0)+1;this.store.put('batches',{...batch,retryCount,retryAt:new Date(this.clock().getTime()+Math.min(60000,15000*retryCount)).toISOString(),lastError:String(error.message||error.code||'').slice(0,300)});this.store.audit?.('系统发送','发送暂不可用,安排重试',batch.id+' 第'+retryCount+'次:'+String(error.message||error.code||'').slice(0,120));return;} + if(!manual&&!sending&&isTransientPreflightError(error)&&(batch.retryCount||0)<3&&this.clock()-Date.parse(batch.cutoff)<1800000){const retryCount=(batch.retryCount||0)+1;this.store.put?.('batches',{...batch,version:(batch.version||1)+1,retryCount,retryAt:new Date(this.clock().getTime()+Math.min(60000,15000*retryCount)).toISOString(),lastError:String(error.message||error.code||'').slice(0,300)});this.store.audit?.('系统发送','发送暂不可用,安排重试',batch.id+' 第'+retryCount+'次:'+String(error.message||error.code||'').slice(0,120));return;} 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())); const evidence=!sending?{outcome:'not_submitted',phase:'preflight',at:this.clock().toISOString()}:rejected?{outcome:'all_recipients_rejected',phase:'smtp_envelope',at:this.clock().toISOString()}:undefined; - this.store.finishSending(batch.id,sending&&!rejected?'unknown':'failed',sending&&!rejected?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='MAIL_POLICY_BLOCKED'?error.message:error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`,evidence); + this.store.finishSending(batch.id,sending&&!rejected?'unknown':'failed',sending&&!rejected?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${formatPreflightError(error)}`,evidence); }finally{ try{transport?.close?.();}finally{if(transport)this.mail.clients?.delete(transport);} } diff --git a/src/modules/order-rules/import.cjs b/src/modules/order-rules/import.cjs index 368f3a1..a67ff58 100644 --- a/src/modules/order-rules/import.cjs +++ b/src/modules/order-rules/import.cjs @@ -37,14 +37,14 @@ function previewImport(store,input,actor,{mail}={}){ if(headers.includes('抄送人'))candidate.cc=recipients(get('抄送人')); if(headers.includes('服务器存档地址'))candidate.archiveDirectory=get('服务器存档地址'); if(headers.includes('文件名日期')){const dates={'申请日期':'appDate','接收日期':'receivedAt','归档日期':'archiveDate','':'',appDate:'appDate',receivedAt:'receivedAt',archiveDate:'archiveDate'};if(!Object.hasOwn(dates,get('文件名日期')))fail('文件名日期只支持申请日期、接收日期或归档日期');candidate.filenameDate=dates[get('文件名日期')];} - if(headers.includes('附带PDF')){const value=get('附带PDF');if(!['是','否','true','false'].includes(value))fail('附带PDF请填写是或否');if(['是','true'].includes(value))row.warnings.push('PDF 仅归档,不附在通知邮件中;已忽略表内的附带PDF要求');} - else if(headers.includes('邮件正文')){const value=get('邮件正文');if(/PDF/i.test(value))row.warnings.push('PDF 仅归档,不附在通知邮件中;正文继续使用分类模板和BPM摘要');else if(!/摘要信息/.test(value))row.warnings.push('邮件正文描述未自动转换,保留原分类模板和摘要设置');} - candidate.attachPdf=false; + if(headers.includes('附带PDF')){const value=get('附带PDF');if(!['是','否','true','false'].includes(value))fail('附带PDF请填写是或否');if(['是','true'].includes(value)&&old.attachPdf!==true)row.warnings.push('PDF 仅归档,不附在通知邮件中;已忽略表内的附带PDF要求');} + else if(headers.includes('邮件正文')){const value=get('邮件正文');if(/PDF/i.test(value)&&old.attachPdf!==true)row.warnings.push('PDF 仅归档,不附在通知邮件中;正文继续使用分类模板和BPM摘要');else if(!/摘要信息/.test(value)&&old.bodyWithoutSummary!==true)row.warnings.push('邮件正文描述未自动转换,保留原分类模板和摘要设置');} + candidate.attachPdf=old.attachPdf===true&&(!headers.includes('附带PDF')||['是','true'].includes(get('附带PDF'))); candidate.adapterIds=[...new Set([...old.adapterIds,...store.adapters().filter(a=>a.verified&&processes.includes(a.processName)).filter(a=>!store.adapters().some(b=>b.id!==a.id&&b.verified&&b.processName===a.processName&&b.processVersion===a.processVersion)).map(a=>a.id)])]; Object.assign(candidate,validateRule(candidate,old),{version:old.version});row.candidate=candidate;row.version=old.version;row.recipientCount=candidate.to.length; if(mail)checkTemplates(mail,candidate); row.scopeWarnings=require('./scope-catalog.cjs').warnings(store,candidate).map(message=>'第'+(index+2)+'行:'+message);row.warnings.push(...row.scopeWarnings); - row.preview={scopes:structuredClone(candidate.scopes),subjectPrefix:candidate.subjectPrefix,archiveDirectory:candidate.archiveDirectory,to:[...candidate.to],cc:[...candidate.cc],attachPdf:false}; + row.preview={scopes:structuredClone(candidate.scopes),subjectPrefix:candidate.subjectPrefix,archiveDirectory:candidate.archiveDirectory,to:[...candidate.to],cc:[...candidate.cc],attachPdf:candidate.attachPdf}; const labels={name:'分类名称',subjectPrefix:'邮件主题',to:'收件人',cc:'抄送人',archiveDirectory:'归档目录',attachPdf:'PDF附件',filenameDate:'文件名日期',scopes:'流程与节点',adapterIds:'BPM识别配置'}; for(const [key,label]of Object.entries(labels))if(JSON.stringify(old[key])!==JSON.stringify(candidate[key]))row.changes.push(label); if(!candidate.archiveDirectory.startsWith('\\\\'))row.warnings.push('表内仅有目录名称,请在第03步选择存储服务器和目录'); diff --git a/src/modules/order-rules/template.cjs b/src/modules/order-rules/template.cjs index 868b71f..31a792d 100644 --- a/src/modules/order-rules/template.cjs +++ b/src/modules/order-rules/template.cjs @@ -18,12 +18,13 @@ function applyBodyTemplate(snapshot,template,orders,maxMessageBytes){ const boundId=orders[0]?.ruleSnapshot?.bodyTemplateId; if(boundId&&(!template||template.id!==boundId))fail('本分类绑定的邮件模板未正确解析。',409); if(!template)return snapshot; - const date=businessDates(template,orders),content=mailContent(orders),category=orders[0]?.ruleSnapshot?.name||''; - const values={'产品线':[...new Set(orders.map(order=>order.event.productLine).filter(Boolean))].join('、'),'订单号':snapshot.orderNos.join('、'),'日期':date,'订单列表':content.details,'订单明细':content.details,'存放地址':content.directories.join('\n'),'类别名称':category}; + const date=businessDates(template,orders),content=mailContent(orders),category=orders[0]?.ruleSnapshot?.name||'',omitSummary=orders[0]?.ruleSnapshot?.bodyWithoutSummary===true; + const detailText=omitSummary?'':content.details,detailHtml=omitSummary?'':content.htmlDetails; + const values={'产品线':[...new Set(orders.map(order=>order.event.productLine).filter(Boolean))].join('、'),'订单号':snapshot.orderNos.join('、'),'日期':date,'订单列表':detailText,'订单明细':detailText,'存放地址':content.directories.join('\n'),'类别名称':category}; const rendered=renderTemplate({...template,attachments:[]},values); const subject=rendered.subject?rendered.subject+(has(template.subject,'订单号')?'':' '+snapshot.orderNos.join('、')):snapshot.subject; let text=rendered.text; - if(!['订单列表','订单明细'].some(key=>has(template.text,key)))text+='\n\n'+content.details; + if(!omitSummary&&!['订单列表','订单明细'].some(key=>has(template.text,key)))text+='\n\n'+content.details; if(!has(template.text,'存放地址'))text+='\n\n存放地址:'+content.directories.join('\n'); let html='
'+escape(text).replace(/\r?\n/g,'
')+'
'; const directoryLinks=new Map(content.directories.map(directory=>[escape(directory),''+escape(directory)+''])); @@ -31,11 +32,11 @@ function applyBodyTemplate(snapshot,template,orders,maxMessageBytes){ if(directoryPattern)html=html.replace(new RegExp(directoryPattern,'g'),directory=>directoryLinks.get(directory)); if(template.html){ const token='ORDER_CONTENT_'+require('node:crypto').randomUUID(),directoryToken='ORDER_ARCHIVE_'+require('node:crypto').randomUUID(); - html=renderTemplate({...template,attachments:[]},{...values,'订单列表':token,'订单明细':token,'存放地址':directoryToken}).html.replaceAll(token,content.htmlDetails).replaceAll(directoryToken,content.htmlDirectoryLinks); - if(!['订单列表','订单明细'].some(key=>has(template.html,key)))html+=content.htmlDetails; + html=renderTemplate({...template,attachments:[]},{...values,'订单列表':token,'订单明细':token,'存放地址':directoryToken}).html.replaceAll(token,detailHtml).replaceAll(directoryToken,content.htmlDirectoryLinks); + if(!omitSummary&&!['订单列表','订单明细'].some(key=>has(template.html,key)))html+=content.htmlDetails; if(!has(template.html,'存放地址'))html+=content.htmlDirectories; } - const bytes=16384+Buffer.byteLength(text+html+subject)*2; + 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}}; } diff --git a/src/modules/storage/files.cjs b/src/modules/storage/files.cjs index ab72ad3..7ec8ef7 100644 --- a/src/modules/storage/files.cjs +++ b/src/modules/storage/files.cjs @@ -46,10 +46,11 @@ class FileArea{ } return current; } - async list(relative=''){ + async list(relative='',options={}){ const directory=await this.resolve(relative),entries=[];let truncated=false; + const prefix=typeof options?.prefix==='string'&&options.prefix?options.prefix.toLowerCase():''; const iterator=await fs.opendir(directory); - for await(const entry of iterator){if(entry.name.startsWith('.order-'))continue;if(entries.length>=500){truncated=true;break;}entries.push({name:entry.name,type:entry.isSymbolicLink()?'blocked':entry.isDirectory()?'directory':'file'});} + for await(const entry of iterator){if(entry.name.startsWith('.order-'))continue;if(prefix&&!entry.name.toLowerCase().startsWith(prefix))continue;if(entries.length>=500){truncated=true;break;}entries.push({name:entry.name,type:entry.isSymbolicLink()?'blocked':entry.isDirectory()?'directory':'file'});} entries.sort((a,b)=>(a.type==='directory'?0:1)-(b.type==='directory'?0:1)||a.name.localeCompare(b.name,'zh-CN')); return {path:segments(relative).join('/'),entries,truncated}; } diff --git a/src/modules/storage/order-archive.cjs b/src/modules/storage/order-archive.cjs index f3364e0..b5654ca 100644 --- a/src/modules/storage/order-archive.cjs +++ b/src/modules/storage/order-archive.cjs @@ -41,7 +41,7 @@ class OrderArchiveProvider{ this.last={success:true,at:this.clock().toISOString(),message:'PDF 运行环境及目标共享目录读写检查成功。'};const result={...this.capabilities(),pdfExport:true};this.probes.set(key,result);return result; }catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}finally{if(temporary)await fs.rm(temporary,{recursive:true,force:true});} } - async archive(input){try{return await this.performArchive(input);}catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}} + async archive(input){try{return await this.performArchive(input);}catch(error){if(![400,409].includes(error?.status))this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;}} async performArchive({order,rule,snapshot,taskId}){ if(this.journal){restricted.assertRule(this.journal,rule);restricted.assertOrder(this.journal,order);} const identity=taskId||order.id,generation=order.archiveGeneration||1,id=identity+':g'+generation; @@ -53,7 +53,14 @@ class OrderArchiveProvider{ if(subfolder)target.relative=[target.relative,subfolder].filter(Boolean).join('/'); let filename; if(previous?.filename)filename=previous.filename; - else if(rule.filenameScheme==='orderDateSeq'){let names=[];try{const listing=await this.storage.list(target.server.id,target.relative);names=(listing?.entries||[]).map(entry=>entry.name);}catch{}filename=archiveSequenceFilename(event,this.clock(),names);} + else if(rule.filenameScheme==='orderDateSeq'){ + const seqDay=new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date(chosen)).replace(/-/g,'').slice(2); + const prefix=String(event?.orderNo||'').trim()+seqDay+'-'; + let names=[]; + try{const listing=await this.storage.list(target.server.id,target.relative,{prefix});names=(listing?.entries||[]).map(entry=>entry.name);} + catch(error){if(!(error?.code==='ENOENT'||error?.status===404||/找不到文件或归档目录/.test(String(error?.message||''))))throw error;} + filename=archiveSequenceFilename(event,chosen,names); + } else filename=archiveFilename(event,rule.filenameDate,chosen); const outputFingerprint=fingerprint({sourceHash:order.sourceHash,event,directory:rule.archiveDirectory,filenameDate:rule.filenameDate,filename,chosen:new Date(chosen).toISOString(),generation}); if(legacy){ @@ -81,7 +88,7 @@ class OrderArchiveProvider{ const evidence={archivedAt:this.clock().toISOString(),files:[{name:receipt.filename,path:path.win32.join('\\\\'+target.server.host,target.server.share,...segments(target.server.directory),...segments(receipt.relativePath)),sha256:digest,size:local.length,kind:'pdf'}]}; if(id&&this.journal)this.journal.put('archive-intents',{...intent,evidence}); this.last={success:true,at:evidence.archivedAt,message:'PDF 已生成、归档并读回校验。'};return evidence; - }catch(error){this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;} + }catch(error){if(![400,409].includes(error?.status))this.last={success:false,at:this.clock().toISOString(),message:error.message};throw error;} } async read(file){ if(this.journal)restricted.assertPath(this.journal,file.path); diff --git a/src/modules/storage/service.cjs b/src/modules/storage/service.cjs index 0ab6b50..46398a4 100644 --- a/src/modules/storage/service.cjs +++ b/src/modules/storage/service.cjs @@ -54,20 +54,20 @@ class StorageService{ run(id,work){ if(this.stopped)return Promise.reject(fail('存储服务正在停止。',503)); const previous=this.running.get(id)||Promise.resolve(),controller=new AbortController(); - this.operationControllers.add(controller);let started=false,rejectQueued; + this.operationControllers.add(controller);let started=false,rejectQueued,timer; const queued=new Promise((resolve,reject)=>{rejectQueued=reject;}); const cancel=()=>{if(!started)rejectQueued(controller.signal.reason);}; controller.signal.addEventListener('abort',cancel); - const timer=setTimeout(()=>controller.abort(fail('存储操作超时,请检查服务器与网络。',504)),this.operationTimeoutMs); const task=previous.catch(()=>{}).then(async()=>{ started=true;if(controller.signal.aborted)throw controller.signal.reason; + timer=setTimeout(()=>controller.abort(fail('存储操作超时,请检查服务器与网络。',504)),this.operationTimeoutMs); const server=this.store.secret(id);if(!server.enabled)throw fail('此存储服务器已停用。',409); try{return await work(server,controller.signal);}catch(e){throw safe(e);} }).finally(()=>{clearTimeout(timer);controller.signal.removeEventListener('abort',cancel);this.operationControllers.delete(controller);if(this.running.get(id)===task)this.running.delete(id);}); this.running.set(id,task);return Promise.race([task,queued]); } check(id){return this.run(id,async (server,signal)=>{try{const result=await this.operation(server,'check',[],signal);const state={...result,checkedAt:new Date().toISOString(),message:'共享目录读写正常'};this.store.setState(id,server.version,state);return this.store.publicServer(id);}catch(e){const error=safe(e);this.store.setState(id,server.version,{readable:false,writable:false,checkedAt:new Date().toISOString(),message:error.message});throw error;}});} - list(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'list',[relative],signal));} + list(id,relative,options){return this.run(id,async (server,signal)=>this.operation(server,'list',options&&Object.keys(options).length?[relative,options]:[relative],signal));} mkdir(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'mkdir',[relative],signal));} readPdf(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'readPdf',[relative],signal));} previewInfo(id,relative){return this.run(id,async (server,signal)=>this.operation(server,'previewInfo',[relative],signal));} diff --git a/src/platform/security/windows-directory.cjs b/src/platform/security/windows-directory.cjs index b367abb..6ab7c9f 100644 --- a/src/platform/security/windows-directory.cjs +++ b/src/platform/security/windows-directory.cjs @@ -21,7 +21,7 @@ $current=[System.IO.Directory]::GetAccessControl($p) if(-not (Test-PrivateDirectoryAcl $current $s)){ $a=New-Object System.Security.AccessControl.DirectorySecurity $a.SetAccessRuleProtection($true,$false) - $a.SetOwner($s) + if(-not $current.GetOwner([System.Security.Principal.SecurityIdentifier]).Equals($s)){$a.SetOwner($s)} $r=New-Object System.Security.AccessControl.FileSystemAccessRule($s,"FullControl","ContainerInherit,ObjectInherit","None","Allow") $a.AddAccessRule($r) [System.IO.Directory]::SetAccessControl($p,$a) diff --git a/src/platform/service/supervisor.cjs b/src/platform/service/supervisor.cjs index 1f7bd8e..49b879a 100644 --- a/src/platform/service/supervisor.cjs +++ b/src/platform/service/supervisor.cjs @@ -43,7 +43,7 @@ class ServiceSupervisor { if(!Array.isArray(ports)||!ports.length||ports.some(port=>!Number.isInteger(port)||port<1024||port>65535)||new Set(ports).size!==ports.length)throw Object.assign(Error('服务端口配置无效。'),{code:'EINVALIDPORTS'}); await portsAvailable(ports);if(this.stopping)return;this.ports=[...ports];this.misses=0;this.spawnedAt=Date.now();const instanceId=crypto.randomUUID(),heartbeatToken=crypto.randomBytes(32).toString('hex'),logFile=path.join(this.store.dir,'service.log');this.rotateLog(); const fd=fs.openSync(logFile,'a',0o600);let child; - try{child=spawn(process.execPath,[this.entry],{cwd:require('../../shared/paths.cjs').PROJECT_ROOT,env:{...process.env,...this.env,ORDER_SUPERVISOR_TOKEN:heartbeatToken,ORDER_SUPERVISOR_INSTANCE:instanceId},windowsHide:true,shell:false,stdio:['ignore',fd,fd,'ipc']});}finally{fs.closeSync(fd);} + try{child=spawn(process.execPath,[this.entry],{cwd:require('../../shared/paths.cjs').PROJECT_ROOT,env:{NODE_USE_SYSTEM_CA:'1',...process.env,...this.env,ORDER_SUPERVISOR_TOKEN:heartbeatToken,ORDER_SUPERVISOR_INSTANCE:instanceId},windowsHide:true,shell:false,stdio:['ignore',fd,fd,'ipc']});}finally{fs.closeSync(fd);} this.child=child;this.instanceId=instanceId;this.heartbeatToken=heartbeatToken;this.ready=false;this.startupError=null;this.childClosed=new Promise(resolve=>{this.resolveClosed=resolve;}); this.update({status:'starting',childPid:child.pid||null,childInstanceId:instanceId,childStartedAt:new Date().toISOString(),heartbeatAt:null,nextRestartAt:null,startupError:null,consecutiveStartupFailures:this.startupFailures}); child.on('message',message=>{ diff --git a/src/platform/tls-system-ca.cjs b/src/platform/tls-system-ca.cjs new file mode 100644 index 0000000..177267d --- /dev/null +++ b/src/platform/tls-system-ca.cjs @@ -0,0 +1,20 @@ +'use strict'; +let loaded = false; +function ensureSystemCA() { + if (loaded) return; + loaded = true; + try { + const tls = require('node:tls'); + if (typeof tls.getCACertificates === 'function' && typeof tls.setDefaultCACertificates === 'function') { + const extra = tls.getCACertificates('system'); + if (Array.isArray(extra) && extra.length) { + const merged = [...new Set([...tls.getCACertificates('default'), ...extra])]; + tls.setDefaultCACertificates(merged); + } + } + } catch (error) { + console.warn('系统 CA 加载失败:' + error.message); + } +} +ensureSystemCA(); +module.exports = { ensureSystemCA }; diff --git a/src/server.cjs b/src/server.cjs index bb262e2..b508767 100644 --- a/src/server.cjs +++ b/src/server.cjs @@ -1,6 +1,4 @@ -// Trust the Windows certificate store in addition to Node's bundled CAs so corporate -// SMTP/HTTPS endpoints with system-installed roots can be verified. -try{const tls=require('node:tls');if(typeof tls.getCACertificates==='function'&&typeof tls.setDefaultCACertificates==='function'){const extra=tls.getCACertificates('system');if(Array.isArray(extra)&&extra.length)tls.setDefaultCACertificates([...tls.getCACertificates('default'),...extra]);}}catch(error){console.warn('系统 CA 加载失败:'+error.message);} +require('./platform/tls-system-ca.cjs'); const {createServer,startService}=require('./app/bridge.cjs'); const {main}=require('./app/application.cjs'); const {safeDiagnostic}=require('./shared/diagnostics.cjs'); diff --git a/tests/order-rules/production-regressions-2026-12-02.test.cjs b/tests/order-rules/production-regressions-2026-12-02.test.cjs new file mode 100644 index 0000000..abf02a6 --- /dev/null +++ b/tests/order-rules/production-regressions-2026-12-02.test.cjs @@ -0,0 +1,227 @@ +'use strict'; +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { buildBatch } = require('../../src/modules/order-rules/batch.cjs'); +const { applyBodyTemplate } = require('../../src/modules/order-rules/template.cjs'); +const { OrderArchiveProvider } = require('../../src/modules/storage/order-archive.cjs'); +const { OrderRuleDispatcher } = require('../../src/modules/order-rules/dispatcher.cjs'); +const { RuleStore } = require('../../src/modules/order-rules/store.cjs'); +const { OrderExecutionCoordinator } = require('../../src/modules/order-execution/coordinator.cjs'); +const { StorageService } = require('../../src/modules/storage/service.cjs'); +const { FileArea } = require('../../src/modules/storage/files.cjs'); +const { ensureSystemCA } = require('../../src/platform/tls-system-ca.cjs'); + +const cutoff = '2026-12-01T03:50:00.000Z'; + +test('applyBodyTemplate honors bodyWithoutSummary and enforces MIME attachment byte limit', () => { + const rule = { + id: 'overseas-change', + categoryId: 'overseas-change', + version: 1, + name: '海外订单更改通知书', + intro: '请查收', + signature: '签名', + attachPdf: true, + bodyWithoutSummary: true, + to: ['2639266652@qq.com'], + cc: [], + bodyTemplateId: 'tpl-change', + }; + const smallOrder = { + id: 'o1', + status: 'pending', + ruleSnapshot: structuredClone(rule), + event: { + orderNo: '315470', + receivedAt: '2026-12-01T02:00:00Z', + productLine: '海外', + brief: '订单号:315470 客户简称:测试客户', + titleOrders: [{ orderNo: '315470', text: '订单号:315470 客户简称:测试客户' }], + }, + archive: { + archivedAt: '2026-12-01T02:10:00Z', + files: [{ name: '315470261201-1.pdf', path: 'C:\\archive\\315470261201-1.pdf', size: 1024, sha256: 'a'.repeat(64), kind: 'pdf' }], + }, + }; + const tpl = { + id: 'tpl-change', + version: 1, + status: 'active', + bindingVersion: 1, + subject: '更改通知', + text: '各位好,请查收附件。', + html: '

各位好,请查收附件。

', + attachments: [], + }; + const snap = buildBatch(rule, [smallOrder], cutoff); + const rendered = applyBodyTemplate(snap, tpl, [smallOrder], 20971520); + assert.equal(rendered.text.includes('测试客户'), false); + assert.equal(rendered.html.includes('测试客户'), false); + assert.match(rendered.text, /存放地址:C:\\archive/); + + const hugeOrder = structuredClone(smallOrder); + hugeOrder.archive.files[0].size = 18 * 1024 * 1024; + const hugeSnap = buildBatch(rule, [hugeOrder], cutoff, { maxMessageBytes: 30 * 1024 * 1024 }); + assert.throws(() => applyBodyTemplate(hugeSnap, tpl, [hugeOrder], 20971520), /容量限制/); +}); + +test('OrderArchiveProvider isolates per-order 409 validation errors from global capabilities', async () => { + const provider = new OrderArchiveProvider({ + storage: { + store: { + servers: () => [{ id: 's1', enabled: true, host: '192.168.8.210', share: 'SVR', directory: '', state: { readable: true, writable: true } }], + }, + }, + outputDir: os.tmpdir(), + }); + provider.last = { success: true, at: cutoff, message: 'ok' }; + await assert.rejects( + provider.archive({ + order: { id: 'rework-1', sourceHash: 'h1', event: { orderNo: 'HWFG-2026110015' } }, + rule: { archiveDirectory: '\\\\192.168.8.210\\SVR\\海外订单通知书', archiveOrderFolder: true }, + snapshot: {}, + }), + (err) => err.status === 409, + ); + assert.equal(provider.capabilities().automaticArchive, true); + assert.equal(provider.capabilities().pdfExport, true); +}); + +test('OrderArchiveProvider orderDateSeq uses chosen filenameDate and prefix filtering beyond 500 files', async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'seq-list-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + for (let i = 0; i < 520; i++) { + fs.writeFileSync(path.join(dir, `000001261201-${i + 1}.pdf`), '%PDF-1.4\n'); + } + fs.writeFileSync(path.join(dir, '999999261130-1.pdf'), '%PDF-1.4\n'); + fs.writeFileSync(path.join(dir, '999999261130-2.pdf'), '%PDF-1.4\n'); + const area = new FileArea(dir); + const filtered = await area.list('', { prefix: '999999261130-' }); + assert.equal(filtered.entries.length, 2); + assert.equal(filtered.truncated, false); +}); + +test('post-cutoff completed scan proof survives subsequent transient 502 scan failure', async (t) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'scan-proof-')); + const store = new RuleStore(dir, { + clock: () => new Date(cutoff), + schedule: () => ({ times: ['11:50', '18:30'], weekends: false }), + }); + t.after(() => { + store.close(); + fs.rmSync(dir, { recursive: true, force: true }); + }); + const connection = { id: 'c1', owner: 'admin', status: 'connected' }; + const workspace = { snapshot: () => ({ connections: [connection] }), getConnection: () => connection }; + let shouldFail = false; + const provider = { + scan: async () => { + if (shouldFail) throw Object.assign(new Error('502 Bad Gateway'), { status: 502 }); + return []; + }, + capabilities: async () => ({ liveTodo: true, pdfExport: true }), + }; + const archive = { supportsRecovery: true, capabilities: async () => ({ automaticArchive: true, pdfExport: true }) }; + let now = new Date('2026-12-01T03:50:02.000Z'); + const coordinator = new OrderExecutionCoordinator({ store, workspace, provider, archive, clock: () => now }); + const principal = { sessionId: 's1', user: { username: 'admin', role: 'admin' } }; + + await coordinator.scan({ connectionId: 'c1', idempotencyKey: 'ok-after-cutoff' }, principal); + assert.deepEqual(store.discoveryBlockers(cutoff), []); + + now = new Date('2026-12-01T03:53:22.000Z'); + shouldFail = true; + await assert.rejects(coordinator.scan({ connectionId: 'c1', idempotencyKey: 'later-502' }, principal), /502/); + assert.equal(store.get('execution-scans', 'c1').status, 'failed'); + assert.deepEqual(store.discoveryBlockers(cutoff), []); +}); + +test('dispatcher preserves TLS certificate error details without wasting transient retries, and retries ECONNECTION', async () => { + const records = new Map(); + const baseBatch = { + id: 'b-tls', + version: 1, + status: 'prepared', + cutoff, + channelId: 'mail', + to: ['2639266652@qq.com'], + cc: [], + attachments: [], + orderIds: ['o1'], + ruleSnapshot: {}, + }; + records.set('b-tls', structuredClone(baseBatch)); + const finished = []; + let verifyError = Object.assign(new Error('unable to verify the first certificate'), { code: 'ESOCKET' }); + let verifyCalls = 0; + const store = { + get: () => null, + put: (kind, val) => { + if (kind === 'batches') records.set(val.id, structuredClone(val)); + }, + all: (kind) => (kind === 'batches' ? [...records.values()] : []), + settings: () => ({ enabled: true, channelId: 'mail' }), + capabilities: { liveTodo: true, pdfExport: true, automaticArchive: true }, + discoveryBlockers: () => [], + batchIncomplete: () => false, + beginSending: () => {}, + finishSending: (...args) => finished.push(args), + }; + const mail = { + store: { channelSecret: () => ({ id: 'mail', version: 1, email: 'sender@skyworth.com', smtp: {} }), guard: () => {} }, + smtpFactory: () => ({ + verify: async () => { + verifyCalls++; + throw verifyError; + }, + sendMail: async () => ({ accepted: ['2639266652@qq.com'], rejected: [] }), + close: () => {}, + }), + }; + const dispatcher = new OrderRuleDispatcher({ store, mail, settings: () => ({}), clock: () => new Date(cutoff), providersReady: () => true }); + await dispatcher.dispatch(records.get('b-tls'), store.settings()); + assert.equal(verifyCalls, 1); + assert.equal(finished.length, 1); + assert.equal(finished[0][1], 'failed'); + assert.match(finished[0][2], /TLS 证书校验失败.*unable to verify the first certificate/); + + // Transient ECONNECTION schedules retry instead of immediate failure + finished.length = 0; + verifyCalls = 0; + verifyError = Object.assign(new Error('connect ETIMEDOUT'), { code: 'ECONNECTION' }); + records.set('b-net', { ...structuredClone(baseBatch), id: 'b-net' }); + await dispatcher.dispatch(records.get('b-net'), store.settings()); + assert.equal(verifyCalls, 1); + assert.equal(finished.length, 0); + assert.equal(records.get('b-net').retryCount, 1); +}); + +test('StorageService starts operationTimeoutMs when queued operation begins executing rather than while waiting in queue', async () => { + let calls = 0; + const service = new StorageService({ + store: { secret: () => ({ enabled: true }) }, + client: { + area: async () => ({ + list: async () => { + calls++; + await new Promise((r) => setTimeout(r, 80)); + return { path: '', entries: [], truncated: false }; + }, + }), + }, + checkTimeoutMs: 120, + }); + const [r1, r2] = await Promise.all([service.list('s1', ''), service.list('s1', '')]); + assert.equal(calls, 2); + assert.deepEqual(r1.entries, []); + assert.deepEqual(r2.entries, []); + await service.stop(); +}); + +test('ensureSystemCA runs idempotently without throwing', () => { + ensureSystemCA(); + ensureSystemCA(); +}); diff --git a/tests/order-rules/scheduled-mail-policy.test.cjs b/tests/order-rules/scheduled-mail-policy.test.cjs index b62deff..ff6f5f3 100644 --- a/tests/order-rules/scheduled-mail-policy.test.cjs +++ b/tests/order-rules/scheduled-mail-policy.test.cjs @@ -20,8 +20,14 @@ test('legacy per-order text recovery keeps declared title order instead of prima const snapshot=buildBatch(rule,[input],cutoff); assert.deepEqual(snapshot.orderNos,['O-2','O-1']);assert.equal(snapshot.text.split('\n\n')[1],'订单号:O-2客户简称:乙\n订单号:O-1客户简称:甲总数量:0'); }); -test('new native freeze rejects legacy attach-PDF intent and still requires archived PDF evidence',()=>{ - assert.throws(()=>buildBatch({...rule,attachPdf:true},[order()],cutoff),/附件|attachPdf/); +test('new native freeze includes archived PDF only when rule attachPdf is enabled and always requires archived PDF evidence',()=>{ + const attached=buildBatch({...rule,attachPdf:true},[order()],cutoff); + assert.equal(attached.attachPdf,true); + assert.equal(attached.attachments.length,1); + assert.equal(attached.attachments[0].name,'O-1.pdf'); + const detached=buildBatch({...rule,attachPdf:false},[order()],cutoff); + assert.equal(detached.attachPdf,false); + assert.deepEqual(detached.attachments,[]); const input=order();input.archive.files=input.archive.files.filter(f=>f.kind!=='pdf'); assert.throws(()=>buildBatch(rule,[input],cutoff),/PDF/); }); diff --git a/web/modules/order-rules/editor.js b/web/modules/order-rules/editor.js index 499a695..7d7c727 100644 --- a/web/modules/order-rules/editor.js +++ b/web/modules/order-rules/editor.js @@ -15,7 +15,8 @@ const area=(name,label,value,rows)=>'
'; const card=(number,title,description,body)=>'
'+number+'

'+title+'

'+description+'
'+body+'
'; const notify=window.OrderRuleResources.render(rule,resources,{esc,admin,section:'template'})+'
'+text('subjectPrefix','邮件主题前缀',rule.subjectPrefix,'maxlength="200"')+area('to','收件人',(rule.to||[]).join('\n'),3)+area('cc','抄送人',(rule.cc||[]).join('\n'),2)+'
标准汇总正文设置(使用邮件模板时无需填写)
'+area('intro','正文引导语',rule.intro,3)+'
'; - const archive=window.OrderRuleResources.render(rule,resources,{esc,admin,section:'archive'})+'
订单号_日期_流水编号.pdf
归入 {类别}\\{订单号}\\文件.pdf;订单号须为明确 6 或 7 位,否则阻断归档
'; + const schemes={'':'标准命名(订单号_日期_流水编号.pdf)',orderDateSeq:'序号命名(订单号YYMMDD-序号.pdf)'}; + const archive=window.OrderRuleResources.render(rule,resources,{esc,admin,section:'archive'})+'
用于归档文件名中的日期部分
更改/返工类可选序号命名
归入 {类别}\\{订单号}\\文件.pdf;订单号须为明确 6 或 7 位,否则阻断归档
'; return '
'+ card('01','适用通知','流程与触发节点完整配对,任一行满足即归入本类别。','
'+text('name','规则名称',rule.name,'required maxlength="160"')+text('productLine','产品线 / 产业',rule.productLine||'','maxlength="200"')+'
'+window.OrderRuleScopes.render(rule,{esc,admin})+'
')+ card('02','通知内容','同类别每个发送时段汇总一封,收件人与附件按本类别维护。',notify)+ @@ -23,6 +24,6 @@ card('04','验证与发布','用一份真实通知检查分类、邮件与归档计划。',recognition+'
查看已保存规则的处理说明

'+esc(describe(rule))+'

'+'
'+(rule.validationIssues?.length?'
启用前待完善
    '+rule.validationIssues.map(v=>'
  • '+esc(typeof v==='string'?v:v.message||'配置需要检查')+'
  • ').join('')+'
':'')+'

检查不会归档、发信或办理 BPM。发送时段在通知配置维护。

')+ (admin?'
保存草稿后检查,再发布;左侧开关控制已发布版本。
':'')+'
'; } - function read(form,rule,adapters=[]){const result={...rule};for(const name of ['name','archiveDirectory','subjectPrefix','intro','filenameDate'])result[name]=form.elements.namedItem(name).value.trim();result.scopes=window.OrderRuleScopes.read(form);result.processNames=[...new Set(result.scopes.map(r=>r.processName).filter(Boolean))];result.nodeNames=[...new Set(result.scopes.map(r=>r.nodeName).filter(Boolean))];result.adapterIds=adaptersFor(result,adapters);const productLine=form.elements.namedItem('productLine')?.value.trim();if(productLine||Object.hasOwn(rule,'productLine'))result.productLine=productLine;const template=form.elements.namedItem('bodyTemplateId').value;if(template==='__legacy__')delete result.bodyTemplateId;else result.bodyTemplateId=template;result.huizhouEnabled=form.elements.namedItem('huizhouEnabled').checked;result.huizhouTemplateId=form.elements.namedItem('huizhouTemplateId').value;for(const name of ['to','cc'])result[name]=list(form.elements.namedItem(name).value);result.attachPdf=form.elements.namedItem('attachPdf').checked;result.bodyWithoutSummary=form.elements.namedItem('bodyWithoutSummary').checked;result.keepTitleVerbatim=form.elements.namedItem('keepTitleVerbatim').checked;result.archiveOrderFolder=form.elements.namedItem('archiveOrderFolder').checked;return result;} + function read(form,rule,adapters=[]){const result={...rule};for(const name of ['name','archiveDirectory','subjectPrefix','intro','filenameDate','filenameScheme']){const el=form.elements.namedItem(name);if(el)result[name]=el.value.trim();}result.scopes=window.OrderRuleScopes.read(form);result.processNames=[...new Set(result.scopes.map(r=>r.processName).filter(Boolean))];result.nodeNames=[...new Set(result.scopes.map(r=>r.nodeName).filter(Boolean))];result.adapterIds=adaptersFor(result,adapters);const productLine=form.elements.namedItem('productLine')?.value.trim();if(productLine||Object.hasOwn(rule,'productLine'))result.productLine=productLine;const template=form.elements.namedItem('bodyTemplateId').value;if(template==='__legacy__')delete result.bodyTemplateId;else result.bodyTemplateId=template;result.huizhouEnabled=form.elements.namedItem('huizhouEnabled').checked;result.huizhouTemplateId=form.elements.namedItem('huizhouTemplateId').value;for(const name of ['to','cc'])result[name]=list(form.elements.namedItem(name).value);result.attachPdf=form.elements.namedItem('attachPdf').checked;result.bodyWithoutSummary=form.elements.namedItem('bodyWithoutSummary').checked;result.keepTitleVerbatim=form.elements.namedItem('keepTitleVerbatim').checked;result.archiveOrderFolder=form.elements.namedItem('archiveOrderFolder').checked;return result;} window.OrderRuleEditor={render,read,describe,adaptersFor}; })(); diff --git a/web/modules/order-rules/view.js b/web/modules/order-rules/view.js index 99f025e..e9d0b42 100644 --- a/web/modules/order-rules/view.js +++ b/web/modules/order-rules/view.js @@ -84,7 +84,7 @@ if(!result||!result.id||!Number.isSafeInteger(result.version))throw Error('写入已返回,但规则状态回执不完整;请刷新核对,勿重复提交。'); const {restrictedTest,...value}=result,target=data.rules.find(item=>item.id===value.id);if(!target)throw Error('规则目录已变化,请刷新核对。');Object.assign(target,value);if(Object.hasOwn(result,'restrictedTest')){data.restrictedTest=restrictedTest;if(!restrictedTest)for(const item of data.rules){delete item.testStatus;delete item.testVersion;delete item.testHasDraft;}else if(!restrictedTest.enabled)for(const item of data.rules){item.testStatus='paused';item.testVersion=null;item.testHasDraft=true;}} if(target===rule){ - if(normalize){for(const name of ['name','archiveDirectory','subjectPrefix','intro','filenameDate','productLine']){const input=form.elements.namedItem(name);if(input&&rule[name]!==undefined)input.value=rule[name];}for(const name of ['to','cc'])form.elements.namedItem(name).value=(rule[name]||[]).join('\n');const folder=form.elements.namedItem('archiveOrderFolder');if(folder)folder.checked=rule.archiveOrderFolder===true;const attachPdf=form.elements.namedItem('attachPdf');if(attachPdf)attachPdf.checked=rule.attachPdf===true;const bodyWithoutSummary=form.elements.namedItem('bodyWithoutSummary');if(bodyWithoutSummary)bodyWithoutSummary.checked=rule.bodyWithoutSummary===true;const verbatim=form.elements.namedItem('keepTitleVerbatim');if(verbatim)verbatim.checked=rule.keepTitleVerbatim===true;if(JSON.stringify(window.OrderRuleScopes.read(form))!==JSON.stringify(window.OrderRuleScopes.scopesFor(rule)))scopeController.setScopes(window.OrderRuleScopes.scopesFor(rule));resourceController.setDirectory(rule.archiveDirectory);} + if(normalize){for(const name of ['name','archiveDirectory','subjectPrefix','intro','filenameDate','filenameScheme','productLine']){const input=form.elements.namedItem(name);if(input&&rule[name]!==undefined)input.value=rule[name];}for(const name of ['to','cc'])form.elements.namedItem(name).value=(rule[name]||[]).join('\n');const folder=form.elements.namedItem('archiveOrderFolder');if(folder)folder.checked=rule.archiveOrderFolder===true;const attachPdf=form.elements.namedItem('attachPdf');if(attachPdf)attachPdf.checked=rule.attachPdf===true;const bodyWithoutSummary=form.elements.namedItem('bodyWithoutSummary');if(bodyWithoutSummary)bodyWithoutSummary.checked=rule.bodyWithoutSummary===true;const verbatim=form.elements.namedItem('keepTitleVerbatim');if(verbatim)verbatim.checked=rule.keepTitleVerbatim===true;if(JSON.stringify(window.OrderRuleScopes.read(form))!==JSON.stringify(window.OrderRuleScopes.scopesFor(rule)))scopeController.setScopes(window.OrderRuleScopes.scopesFor(rule));resourceController.setDirectory(rule.archiveDirectory);} updateVersion();coverage();const issues=panel.querySelector('#rule-validation-issues');issues.innerHTML=rule.validationIssues?.length?'
启用前待完善
    '+rule.validationIssues.map(value=>'
  • '+esc(typeof value==='string'?value:value.message||'配置需要检查')+'
  • ').join('')+'
':''; } drawList();