diff --git a/docs/order-rules-guide.md b/docs/order-rules-guide.md
new file mode 100644
index 0000000..d506315
--- /dev/null
+++ b/docs/order-rules-guide.md
@@ -0,0 +1,57 @@
+# 分类通知规则首版
+
+入口:侧栏“分类通知规则”。六个页签为工作台、通知规则、待发批次、订单记录、发送记录、设置。
+
+## 收单范围
+
+按节点收到时间(不是流程发起时间)和北京时间计算,包含起点、不包含终点。
+
+| 批次 | 以11:00和17:00为例 |
+| --- | --- |
+| 正常工作日上午 | 当天00:00至11:00 |
+| 正常工作日下午 | 当天11:00至17:00 |
+| 周一上午 | 上个工作日最后截止时点至周一11:00,通常为周五17:00开始 |
+
+业务日历决定实际工作日。更早历史不归档、不补发,过期未发送批次取消。历史发送结果不明保留人工核验,不自动重发。具体发送时间在“发送计划”维护。
+
+每个有效类别在一个时段内汇总为一封邮件,普通通知和更改分开,不按产品线误分类。缺必需PDF或归档证据会阻塞本类别;不会静默漏掉本时段订单。超过邮箱容量限制时阻塞整类并提示。
+
+## 配置和对应关系
+
+Excel15个类别已建立。选择类别后维护适用流程、节点、字段适配器、归档共享路径、文件名日期来源、主题、正文引导语、签名及主送/抄送名单。
+
+Excel只有归档分类目录名,完整服务器共享路径与“日期”具体来源仍需业务确认。不会凭目录名猜服务器地址。
+
+保存产生草稿,原发布版本继续服务已有任务。字段对应面板显示中文业务字段、xdatabind来源及样本值。高级选项可替换真实业务样本;校验展示命中原因、缺失字段和多重规则冲突。预置演示样本仅帮助理解,不能作为发布依据。
+
+发布要求当前草稿经过真实结构样本校验、所有适用流程具备已核验字段适配、业务配置完整且无启用规则冲突。当前只核对了备损更改v1.4和海外返工更改v1.1表单结构,其余需补充适配。若只验证一个流程,可明确缩小适用流程范围。
+
+未入批次的任务可由管理员填写依据后重新核对,应用当前规则并清除旧归档准备结果。已发送或已固定批次不会被规则修改覆盖。
+
+## 标题生成邮件正文
+
+标题按每个“订单号:”拆成独立段落,只保留订单号、机芯号、产品型号、客户简称、总数量、订单类别,去除客户等级、毛利、订单类型和业务模式。中文冒号、换行和`
`可识别;第二段`HA`订单不会遗漏,也不会只凭`HA`前缀推断工厂。原始标题保留在加密事件中以便追溯。
+
+在规则的样本试运行面板粘贴“BPM 原始标题”,可对照原文与正文结果。真实接入使用样本的`title`字段;旧`brief`包含订单号标签时同样执行提取,未提供标题的现有更改摘要继续兼容。显式标题中没有订单段落或有空订单号时校验阻塞,不能静默丢掉订单。
+
+标题的业务模式或客户简称出现“惠州”时只标注额外通知待核实。工厂额外邮件的主送、抄送、附件及触发条件尚需历史已发送邮件佐证,不自动生成第二封。
+
+## 只读核对历史邮件
+
+本机规则预览的“邮箱管理”提供只读历史入口。管理员可添加仅含IMAP配置的邮箱,授权码在本机表单输入并加密保存,不需要SMTP配置。保存不会连接邮箱;点击“连接并列出已发送文件夹”后再按日期和主题查询。
+
+一次最多查询31天,显示最近20封(服务端上限50封);逐封打开正文、主送/抄送和附件名称。读取使用只读文件夹与UID,不标已读、不删除、不移动、不更新模板收信游标。正文以转义文本显示,不加载远程图片;正文截断和10MB容量限制明确提示。文件夹UID有效期变化时必须重新查询。
+
+需要邮箱开通IMAP,且历史邮件已同步至服务器。仅有SMTP授权码或仅保存在Foxmail本地的已发送邮件无法通过此入口读取。真实邮箱尚未配置,当前已验证的是本地接口和模拟服务器流程,不代表已读取真实历史邮件。
+
+## 接入边界
+
+首版已实现本地规则维护、精确匹配、字段追踪、状态和版本存储、按时段类别组批、受控SMTP调度和异常核验。
+
+实时待办、自动PDF导出和归档执行器尚未完成联调,页面明确显示“待联调”,默认暂停且禁止启用生产发送。现有待阅扫描不会冒充待办接入。BPM的提交/结束始终由人工办理。
+
+## 独立预览
+
+在项目目录运行 `node scripts/rules-preview.cjs`,访问本机18786端口并点击“进入演示空间”。该空间与正式数据隔离,不访问BPM、不保存业务文件、不发邮件。
+
+可用 `--seed-file` 指定本机从Excel读取的15类名单JSON,私密名单只写入本地加密库,不进入代码仓库;`--state-dir`和`--port`可指定独立目录和端口。导入只初始化尚不存在的类别,不覆盖已有编辑。此预览的邮箱接口只允许IMAP历史查询,拒绝模板收信、SMTP检查和测试发信,不启动定时收信服务。
diff --git a/docs/superpowers/plans/2026-10-19-order-rules.md b/docs/superpowers/plans/2026-10-19-order-rules.md
new file mode 100644
index 0000000..467bf80
--- /dev/null
+++ b/docs/superpowers/plans/2026-10-19-order-rules.md
@@ -0,0 +1,44 @@
+# Order Rules Implementation Plan
+
+> **For agentic workers:** Use subagent-driven-development for independent domain and Web tasks; integrate and review in this session.
+
+**Goal:** Create a usable first Web version of Excel category rules, explicit field mapping, deterministic preview and stateful order/batch records.
+
+**Architecture:** Isolated order-rules module consumes verified form adapters and reusable mailbox/calendar infrastructure. Local encrypted storage holds business data; capabilities block unverified external execution.
+
+**Tech Stack:** Node >=22.13, CommonJS, node:sqlite, existing BpmVault, Tabler/vanilla JS, node:test.
+
+**Spec:** docs/superpowers/specs/2026-10-19-order-rules-design.md
+
+## Global Constraints
+
+15 Excel categories; one mail per category per slot; manual BPM handling; no private recipient lists committed; no live sends during construction; default paused; unverified production providers explicit; modules separated.
+
+### Task 1: Catalog and field adapters
+- [x] Read Excel locally, preserve raw business intent, import private values only into encrypted local store.
+- [x] Write failing matching tests: target node exactness, zero quantity, no unsupported adapter, multiple matches.
+- [x] Implement catalog.cjs and matching.cjs per spec, then run tests.
+
+### Task 2: State and version persistence
+- [x] Write state tests for duplicate events, conflicting drafts, transition legality, blocked category, cutoff and full aggregation, recovery.
+- [x] Implement store.cjs, state.cjs and batch.cjs with encrypted persistent evidence/snapshots.
+- [x] Add API, application lifecycle integration and HTTP role/origin tests.
+
+### Task 3: Web editor and workbench
+- [x] Implement focused view/editor/preview modules under web/modules/order-rules.
+- [x] Add scripts/assets/nav and isolated preview runtime with first-run catalog.
+- [x] Exercise save/reload, readable execution summary, field trace, paused state and unsupported capability feedback.
+
+### Task 4: Integration and review
+- [x] Integrate scheduled dispatch gate with existing mail service; keep provider limitations explicit and no arbitrary archive attestations.
+- [x] Run targeted domain/state/HTTP checks, complete npm test and browser workflow.
+- [x] Review spec and code for false readiness, privacy leakage, retry/duplicate errors; fix findings and document verified scope.
+
+### Task 5: Confirmed title extraction and read-only historical evidence
+- [x] User example red/green regression: retain both ordinary and HA order paragraphs, remove metadata, preserve raw title; Chinese colons/zero quantity and missing order checks.
+- [x] Expose title input and original/result comparison with Huizhou evidence marked pending, without automatic extra email.
+- [x] Add IMAP-only local configuration and bounded sent-folder history search/detail with admin/origin gates, no SMTP, no seen/flag/cursor changes, no remote content loading.
+- [x] Verify service/API/preview/browser paths with simulated mailbox and no external SMTP/BPM calls.
+- [x] Finish combined full regression and live preview check; document pending real mailbox evidence.
+
+Validation: combined full regression 282 tests, 281 passed, 0 failed, 1 expected skip (official ZCode CLI not configured). Local browser verified exact two-order title extraction and empty IMAP-only configuration form. Real mailbox history and production BPM/PDF/archive providers remain pending integration.
diff --git a/docs/superpowers/specs/2026-10-19-order-rules-design.md b/docs/superpowers/specs/2026-10-19-order-rules-design.md
new file mode 100644
index 0000000..2e41225
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-19-order-rules-design.md
@@ -0,0 +1,44 @@
+# Excel 分类通知规则与执行状态
+
+用户已批准聊天中六部分 Web 设计及状态机、字段对应关系、真实样本试运行、规则版本管理,2026-10-19 指示创建首版。
+
+## 业务约束
+
+- Excel `订单通知书邮件发送信息.xls` 的15类是分类依据,同一业务时段内同类汇总一封;通知与更改不混合,不能按产品线决定类别。
+- BPM 节点由人工办理。程序不得提交、结束或更改流程。
+- 自动发送默认暂停。现有待阅扫描不冒充待办接入,DOM 字段证据不冒充实时 API 验证。首版提供真实样本校验与接入接口,未验证适配器不能启用生产规则。
+- 修改生成草稿;发布须校验字段适配、名单、目录、命名日期和样本。历史任务固定原规则,规则版本变化不产生新事件。
+- 订单状态:identified、preparing、archived、pending、batched、sent;失败为blocked;发送不确定为unknown。批次状态:prepared、sending、sent、failed、unknown、cancelled。状态由动作控制,不能任意置成功。
+- 去重键为connectionId/source/instanceId/taskId/revision;订单号不是唯一键。数量为零合法。多条规则命中阻塞,不模糊匹配。
+- 用户补充并确认:正常工作日首封只取当天00:00到首个发送时点,第二封取首个时点到第二时点;周一首封从上个工作日最后时点起算,例如周五17:00到周一11:00。采用北京时间 [start,end),11点整归下午,边界不重复。业务日历休息/暂停间隔按上个实际工作日计算。
+- 以节点接收时间receivedAt归入时段,ingestedAt记录采集时间。更早历史不归档、不补发,过期未发批次取消,结果不明的历史批次仅保留人工核验。新发现但属于已关闭时段的记录不滚入后续邮件。无50/200条静默截断,邮件大小超限阻塞整类。
+- 手工整理只能在已配置发送时点的60秒执行宽限内操作,页面预览不可提前固定邮件。缺必需文件阻塞本类别,不影响其他类别;错过本时段不在下时段补发。
+- SMTP 已接受不等于最终送达;进入发送后异常或部分接受均为unknown,核实后才重试。重启sending恢复unknown。
+
+## 模块与接口
+
+新增 src/modules/order-rules,独立加密 SQLite,复用现有鉴权、审计、邮件和日历。不替换旧通知数据。web/modules/order-rules 下拆分页面渲染与编辑器。
+
+Domain exports from catalog.cjs: `seedRules()` -> array of rule objects; `adapters` -> array `{id,label,processName,processVersion,verified,fields,sample}`. No embedded private recipient lists in repository; Excel private recipients/archive addresses imported locally to encrypted store via optional local file.
+
+Rule object: `{id,version,status:'draft'|'enabled'|'paused',name,categoryId,processNames:[],nodeNames:[],adapterIds:[],archiveDirectory,filenameDate:'appDate'|'receivedAt'|'archiveDate'|'',subjectPrefix,intro,signature,to:[],cc:[],attachPdf:boolean,sourceRow:number}`. Adapter fields maps standard keys to xdatabind; sample `{connectionId,source:'todo',instanceId,taskId,revision,processName,processVersion,nodeName,receivedAt,serialNum,title?,brief,fields:{[xdatabind]:value}}`.
+
+Domain exports from matching.cjs: `previewMatch(rules,adapters,sample)` -> `{valid,ruleId,categoryId,event,checks:[{label,ok,detail}],issues:[],explanation,fieldTrace:[{key,label,path,value}],candidates:[]}`. Normalized event has identity above plus orderNo/appDate/customer/productLine/quantity/brief, no hidden network calls. `describeRule(rule)` Chinese execution summary. Validation is deterministic, no AI and no eval. Adapter verified means sample field structure verified only; service independently gates production availability.
+
+Store exports RuleStore(dir,{clock?}), methods snapshot()->`{rules,adapters,orders,batches,settings,audit,capabilities}`; saveRule(input,actor), publish(id,{version},actor), pause(id,{version},actor), preview(sample), ingest(sample,actor), recordArchive(id,evidence,actor), retryArchive(id,note,actor), prepare(cutoff,actor), beginSending(id), finishSending(id,status,message), resolve(id,{resolution,note},actor), settings(), saveSettings(input,actor), close(). Rule draft update input uses optimistic version. snapshot rules include publishedVersion and draft dirty flag as applicable. settings `{version,enabled:false,channelId:'',maxMessageBytes:20971520}`. capabilities clearly report liveTodo:false,pdfExport:false,automaticArchive:false initially.
+
+recordArchive requires server-created evidence `{files:[{name,path,sha256,size,kind:'pdf'|'notice'}],archivedAt}` verified by archive executor; HTTP never permits clients to assert archive success. No live archive provider => ingest allowed only as blocked task, not sendable. Preview samples never create orders. prepare freezes exact rule/mail/recipient and per-order evidence snapshots and creates one batch/category; blocked/mixed rule versions prevent that category from sending. View only automatic disabled until providers verified. Batch contains id/categoryId/status/subject/text/html/to/cc/orderIds/orderNos/attachments/cutoff/createdAt/error. No data URLs or remote arbitrary URLs accepted.
+
+API prefix `/api/order-rules`: GET root snapshot, POST `/rules` save draft (admin); POST `/rules/:id/publish`, `/pause` (admin); POST `/preview` `{sample}` (operator/admin); POST `/events` `{sample}` (operator/admin); POST `/settings` (admin); POST `/prepare` `{cutoff}` (admin); POST `/batches/:id/resolve` (admin). Preserve origin/session checks; audit mutations. No external-send endpoint in first UI; scheduled dispatch gated by capabilities/settings.
+
+Web entry `#order-rules`, tab views workbench/rules/pending/orders/history/settings. GET above. UI Chinese, real empty states, no fabricated successful tasks; from sample JSON advanced import -> readable field trace. Rule editor normal business fields not JSON paths. Field panel shows verified sample and limitations. Existing integrations remain available separately. Preview/test runtime uses isolated loopback data and no SMTP/BPM.
+
+## 2026-10-19 标题与历史邮件纠正
+
+新增`title.cjs`确定性提取:按订单号分段,保留订单号、机芯号、产品型号、客户简称、总数量、订单类别。客户等级、毛利、订单类型、业务模式不进入正文。原始标题、逐段订单号和惠州线索保存于加密事件;惠州线索仅待核实,不推断HA前缀,不触发额外发信。显式标题无订单段落或订单号为空时阻塞。旧brief已包含订单号标签时同样提取,现有无标题更改摘要兼容。
+
+新增`mail/history.cjs`与`web/modules/mail/history.js`,复用加密MailStore与MailService连接互斥。只读账号仅保存IMAP,不能发信、收取模板或验证SMTP。历史查询为管理员同源POST `/api/mail/channels/:id/history`,支持folders/search/message,服务器已发送文件夹只读锁、UID有效期、31天范围、50封上限、10MB源邮件限制;只返回纯文本及附件元信息,HTML不执行、图片不加载,不更改游标和邮件标记。隔离规则预览启用historyOnly接口门控且不启动MailService定时器。邮箱未配置时真实历史判断保持未完成,待本机配置后只读核对通知要求。
+
+## Verification
+
+Behavior tests: exact matching and aliases, missing adapter, zero quantity, collisions, >200 aggregate, cutoff/new arrivals, duplicate revision, illegal transitions, missing PDF, rule version race, persist/reopen/recover, role/origin checks, no production side effects in preview. UI browser exercise edit/save/reload/sample trace/pending/records. Run complete npm test before completion.
diff --git a/scripts/preview.cjs b/scripts/preview.cjs
index 4bb9187..acdab91 100644
--- a/scripts/preview.cjs
+++ b/scripts/preview.cjs
@@ -6,8 +6,11 @@ const path=require('node:path');
const {Store}=require('../src/modules/dashboard/store.cjs');
const {WorkspaceStore}=require('../src/modules/workspace/store.cjs');
const {createDashboard}=require('../src/app/dashboard.cjs');
+const {RuleStore}=require('../src/modules/order-rules/store.cjs');
+const {MailStore}=require('../src/modules/mail/store.cjs');
+const {MailService}=require('../src/modules/mail/service.cjs');
-async function startPreview({stateDir=path.join(process.env.LOCALAPPDATA || os.homedir(),'OrderNotificationAutomation','preview'),port=18776}={}) {
+async function startPreview({stateDir=path.join(process.env.LOCALAPPDATA || os.homedir(),'OrderNotificationAutomation','preview'),port=18776,ruleSeedOverrides=[],mailHistory=false}={}) {
fs.mkdirSync(stateDir,{recursive:true});
const store=new Store(path.join(stateDir,'accounts'));
if(!store.users().length) {
@@ -17,7 +20,10 @@ async function startPreview({stateDir=path.join(process.env.LOCALAPPDATA || os.h
const admin=store.users().find(user=>user.role==='admin');
if(!admin)throw Error('演示空间缺少管理员,请检查独立演示数据目录。');
const workspace=new WorkspaceStore(path.join(stateDir,'workspace'));
+ const orderRules=new RuleStore(path.join(stateDir,'order-rules'),{seedOverrides:ruleSeedOverrides,schedule:()=>store.settings().schedule,calendar:()=>workspace.meta('calendar').overrides});
+ let mailStore,mail;
try {
+ if(mailHistory){mailStore=new MailStore(path.join(stateDir,'mail-history'));mail=new MailService({store:mailStore});mail.historyOnly=true;}
const snapshot=workspace.snapshot(store.users());
if(!snapshot.exceptions.length) {
for(const item of [
@@ -27,11 +33,11 @@ async function startPreview({stateDir=path.join(process.env.LOCALAPPDATA || os.h
])workspace.createException(item,admin,store.users());
}
if(!snapshot.connections.length)workspace.createConnection({name:'演示 BPM 连接',owner:admin.username},admin,store.users());
- const server=createDashboard({store,workspace,outputDir:path.join(stateDir,'pdf'),previewUserId:admin.id});
+ const server=createDashboard({store,workspace,orderRules,mail,outputDir:path.join(stateDir,'pdf'),previewUserId:admin.id});
await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,'127.0.0.1',resolve);});
let closed=false;
- return {server,store,workspace,async close(){if(closed)return;closed=true;await new Promise(resolve=>server.close(resolve));workspace.close();}};
- } catch(error) { workspace.close();throw error; }
+ return {server,store,workspace,orderRules,mail,async close(){if(closed)return;closed=true;await mail?.stop();await new Promise(resolve=>server.close(resolve));workspace.close();orderRules.close();mailStore?.close();}};
+ } catch(error) { await mail?.stop();workspace.close();orderRules.close();mailStore?.close();throw error; }
}
if(require.main===module)startPreview().then(runtime=>{
diff --git a/scripts/rules-preview.cjs b/scripts/rules-preview.cjs
new file mode 100644
index 0000000..5679619
--- /dev/null
+++ b/scripts/rules-preview.cjs
@@ -0,0 +1,24 @@
+'use strict';
+// Isolated local rule configuration. Never loads production sessions or SMTP.
+const fs=require('node:fs');const os=require('node:os');const path=require('node:path');
+const {startPreview}=require('./preview.cjs');
+async function main(){
+ const args=process.argv.slice(2),options={};
+ for(let i=0;i65535)throw Error('预览端口无效。');
+ let ruleSeedOverrides=[];
+ if(options['--seed-file']){
+ const filename=path.resolve(options['--seed-file']);if(fs.statSync(filename).size>1024*1024)throw Error('导入文件过大。');
+ const rows=JSON.parse(fs.readFileSync(filename,'utf8'));if(!Array.isArray(rows)||rows.length!==15)throw Error('导入文件必须包含15个类别。');
+ ruleSeedOverrides=rows.map(({id,to,cc,archiveDirectory})=>({id,to,cc,archiveDirectory}));
+ }
+ const stateDir=path.resolve(options['--state-dir']||path.join(process.env.LOCALAPPDATA||os.homedir(),'OrderNotificationAutomation','rules-preview'));
+ const fresh=!fs.existsSync(path.join(stateDir,'accounts','state.sqlite'));
+ const runtime=await startPreview({stateDir,port,ruleSeedOverrides,mailHistory:true});
+ if(fresh){const settings=runtime.store.settings();runtime.store.saveSettings({schedule:{...settings.schedule,times:['11:00','17:00']}},settings.version,'规则预览初始化');}
+ console.log(`分类通知规则:http://127.0.0.1:${port}/#order-rules\n独立配置空间;BPM、自动归档和邮件发送均未连接。`);
+ const stop=()=>runtime.close().then(()=>process.exit(0));process.once('SIGINT',stop);process.once('SIGTERM',stop);
+ return runtime;
+}
+if(require.main===module)main().catch(error=>{console.error('规则预览启动失败:'+error.message);process.exitCode=1;});
+module.exports={main};
diff --git a/src/app/application.cjs b/src/app/application.cjs
index 596a962..3afc333 100644
--- a/src/app/application.cjs
+++ b/src/app/application.cjs
@@ -21,6 +21,8 @@ const { StorageStore } = require('../modules/storage/store.cjs');
const { StorageService } = require('../modules/storage/service.cjs');
const { NotificationStore } = require('../modules/notifications/store.cjs');
const { NotificationService } = require('../modules/notifications/service.cjs');
+const { RuleStore } = require('../modules/order-rules/store.cjs');
+const { OrderRuleDispatcher } = require('../modules/order-rules/dispatcher.cjs');
async function closeServer(server){
if(!server)return;
@@ -51,7 +53,7 @@ async function main(options = {}) {
if(errors.length)throw new AggregateError(errors,'关闭服务时部分资源清理失败。');
})();
let server,dashboard,store,workspace,bpmSessions,custodian;
- let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,assistantStore,assistant,health;
+ let mailStore,mail,scanStore,scanner,storageStore,storage,notificationStore,notifications,orderRules,orderDispatcher,assistantStore,assistant,health;
try {
const tokenPath = path.join(stateDir,'pairing.key');
let token;
@@ -69,9 +71,9 @@ async function main(options = {}) {
workspace=new WorkspaceStore(path.join(stateDir,'workspace'));
// Register conditional closures before constructing later resources; partial startup follows the same path.
cleanup.push(()=>closeServer(server));
- cleanup.push(()=>health?.close(),()=>assistant?.stop(),()=>notifications?.stop(),()=>storage?.stop(),()=>scanner?.stop(),()=>mail?.stop(),()=>custodian?.stop(),()=>bpmSessions?.shutdown());
+ cleanup.push(()=>health?.close(),()=>assistant?.stop(),()=>orderDispatcher?.stop(),()=>notifications?.stop(),()=>storage?.stop(),()=>scanner?.stop(),()=>mail?.stop(),()=>custodian?.stop(),()=>bpmSessions?.shutdown());
cleanup.push(()=>closeServer(dashboard),()=>workspace.close());
- cleanup.push(()=>mailStore?.close(),()=>scanStore?.close(),()=>storageStore?.close(),()=>notificationStore?.close(),()=>assistantStore?.close());
+ cleanup.push(()=>mailStore?.close(),()=>scanStore?.close(),()=>storageStore?.close(),()=>notificationStore?.close(),()=>orderRules?.close(),()=>assistantStore?.close());
bpmSessions=new BpmSessionManager({stateDir:path.join(stateDir,'bpm-sessions')});
custodian=new BpmCustodian({workspace,manager:bpmSessions});
mailStore=new MailStore(path.join(stateDir,'mail'));mail=new MailService({store:mailStore});
@@ -79,21 +81,24 @@ async function main(options = {}) {
scanStore=new BpmScanStore(path.join(stateDir,'bpm-scan'));scanner=new BpmScanner({store:scanStore,workspace,manager:bpmSessions,settings:()=>store.settings()});
storageStore=new StorageStore(path.join(stateDir,'storage'));storage=new StorageService({store:storageStore,jobs:store,outputDir});
notificationStore=new NotificationStore(path.join(stateDir,'notifications'));notificationStore.recover();notifications=new NotificationService({store:notificationStore,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides});
+ orderRules=new RuleStore(path.join(stateDir,'order-rules'),{schedule:()=>store.settings().schedule,calendar:()=>workspace.meta('calendar').overrides});
+ orderDispatcher=new OrderRuleDispatcher({store:orderRules,mail,settings:()=>store.settings(),calendar:()=>workspace.meta('calendar').overrides});
assistantStore=new AssistantStore(path.join(stateDir,'assistant'));assistantStore.recover();assistant=new AssistantService({store:assistantStore,runtime:new ZcodeRuntime({stateDir:path.join(stateDir,'assistant','runtime')}),dashboard:store,workspace,scanner,storage});
health=new RuntimeHealth({stateDir,startedAt,instanceId:watchdog.instanceId,workspace,scanner,storage,mail});
await bpmSessions.migrateAccounts(workspace.snapshot().connections);
workspace.markSessionChecksPending();
server=await startService({token,port,outputDir,scale:config.scale,installedExtension,extensionSourceDir:path.join(root,'extension'),store,storage,watchdog,renderSnapshot:options.renderSnapshot});
- dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true});
+ dashboard=createDashboard({store,workspace,outputDir,bpmSessions,mail,scanner,storage,notifications,orderRules,assistant,health,watchdog,trustedProxy:dashboardConfig.trustedProxy===true});
await new Promise((resolve,reject)=>{dashboard.once('error',reject);dashboard.listen(dashboardPort,dashboardHost,resolve);});store.recoverJobs();mailStore.recoverSends();custodian.start();mail.start();scanner.start();notifications.start();
health.start();
+ orderDispatcher.start();
if(!options.quiet){
console.log('订单通知中心已启动。\nWeb 工作台支持业务日历、异常待办与转交、BPM 连接管理。\n在 Chrome 订单页仍可点击扩展中的“导出当前订单”。');
console.log(`首次使用:Chrome 扩展管理 → 开发者模式 → 加载已解压的扩展程序\n选择目录:${installedExtension}\n输出目录:${outputDir}\n本地服务:http://127.0.0.1:${port}`);
console.log(`Web 看板:http://127.0.0.1:${dashboardPort}\n${store.users().length?'使用已创建的工作台账号登录。':'首次请在部署机创建管理员。'}`);
if(dashboardHost==='0.0.0.0')for(const list of Object.values(os.networkInterfaces()))for(const address of list || [])if(address.family==='IPv4' && !address.internal)console.log(`局域网地址:http://${address.address}:${dashboardPort}`);
}
- return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,assistant,health,stop};
+ return {server,dashboard,workspace,bpmSessions,custodian,mail,scanner,storage,notifications,orderRules,orderDispatcher,assistant,health,stop};
}catch(error){try{await stop();}catch(cleanupError){error.cleanupError=cleanupError;}throw error;}
}
module.exports={main};
diff --git a/src/app/assets.cjs b/src/app/assets.cjs
index f8a6500..30e1de8 100644
--- a/src/app/assets.cjs
+++ b/src/app/assets.cjs
@@ -8,6 +8,7 @@ function createAssets(){
'/workspace.js':{path:path.join(webRoot,'modules/workspace/view.js'),type:'text/javascript'},
'/bpm.js':{path:path.join(webRoot,'modules/bpm/view.js'),type:'text/javascript'},
'/mail.js':{path:path.join(webRoot,'modules/mail/view.js'),type:'text/javascript'},
+ '/mail-history.js':{path:path.join(webRoot,'modules/mail/history.js'),type:'text/javascript'},
'/orders.js':{path:path.join(webRoot,'modules/bpm/arrivals.js'),type:'text/javascript'},
'/storage.js':{path:path.join(webRoot,'modules/storage/view.js'),type:'text/javascript'},
'/storage-preview.html':{path:path.join(webRoot,'modules/storage/preview.html'),type:'text/html',preview:true},
@@ -15,6 +16,9 @@ function createAssets(){
'/storage-preview-office.js':{path:path.join(webRoot,'modules/storage/preview-office.js'),type:'text/javascript',preview:true},
'/storage-preview-host.js':{path:path.join(webRoot,'modules/storage/preview-host.js'),type:'text/javascript'},
'/storage-preview.css':{path:path.join(webRoot,'modules/storage/preview.css'),type:'text/css',preview:true},
+ '/order-rules-editor.js':{path:path.join(webRoot,'modules/order-rules/editor.js'),type:'text/javascript'},
+ '/order-rules-preview.js':{path:path.join(webRoot,'modules/order-rules/preview.js'),type:'text/javascript'},
+ '/order-rules.js':{path:path.join(webRoot,'modules/order-rules/view.js'),type:'text/javascript'},
'/notifications.js':{path:path.join(webRoot,'modules/notifications/view.js'),type:'text/javascript'},
'/assistant.js':{path:path.join(webRoot,'modules/assistant/view.js'),type:'text/javascript'},
'/health.js':{path:path.join(webRoot,'modules/health/view.js'),type:'text/javascript'},
diff --git a/src/app/dashboard.cjs b/src/app/dashboard.cjs
index 7dc5dbb..fcd8d57 100644
--- a/src/app/dashboard.cjs
+++ b/src/app/dashboard.cjs
@@ -6,13 +6,14 @@ const {mailApi}=require('../modules/mail/api.cjs');
const {bpmScanApi}=require('../modules/bpm/scan-api.cjs');
const {storageApi}=require('../modules/storage/api.cjs');
const {notificationApi}=require('../modules/notifications/api.cjs');
+const {orderRuleApi}=require('../modules/order-rules/api.cjs');
const {assistantApi}=require('../modules/assistant/api.cjs');
const {respondToPing}=require('../platform/service/ping.cjs');
const {createAssets,PREVIEW_CSP}=require('./assets.cjs');
const {createAuth}=require('../modules/dashboard/auth.cjs');
const {prepareRequest,readBody}=require('./request.cjs');
-function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,assistant,health,watchdog,trustedProxy=false}) {
+function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,mail,scanner,storage,notifications,orderRules,assistant,health,watchdog,trustedProxy=false}) {
const auth=createAuth({store,previewUserId,bpmSessions});
let assetFor;try{assetFor=createAssets();}catch(error){auth.close();throw error;}
const server=http.createServer(async(request,response)=>{
@@ -37,6 +38,7 @@ function createDashboard({store,outputDir,workspace,previewUserId,bpmSessions,ma
if(await bpmScanApi({scanner,workspace,user,sessionId:token,url,route,method:request.method,body,reply}))return;
if(await storageApi({storage,workspace,user,url,route,method:request.method,body,request,response,reply,trustedProxy}))return;
if(await notificationApi({notifications,workspace,user,route,method:request.method,body,reply}))return;
+ if(await orderRuleApi({orderRules,mail,workspace,user,route,method:request.method,body,reply}))return;
if(await assistantApi({assistant,workspace,user,sessionId:token,route,method:request.method,body,request,reply,trustedProxy}))return;
if(workspaceApi({workspace,store,user,route,method:request.method,body,reply,bpmSessions}))return;
if(await dashboardApi({store,outputDir,workspace,mail,scanner,storage,user,route,request,response,body,reply,fail}))return;
diff --git a/src/modules/mail/api.cjs b/src/modules/mail/api.cjs
index 3e6cfb7..2805468 100644
--- a/src/modules/mail/api.cjs
+++ b/src/modules/mail/api.cjs
@@ -4,13 +4,19 @@ const fail=(message,status)=>{throw Object.assign(new Error(message),{status});}
async function mailApi({mail,workspace,user,route,method,body,request,response,reply,trustedProxy}){
if(!route.startsWith('/api/mail'))return false;if(!mail)fail('邮件服务暂不可用。',503);const store=mail.store;
if(method==='POST'&&user.role!=='admin')fail('仅管理员可以维护邮箱和确认模板。',403);
- if(route==='/api/mail'&&method==='GET'){reply(200,{channels:store.channels(),templates:store.templates(),receipts:store.receipts(),sends:store.sends()});return true;}
+ if(route==='/api/mail'&&method==='GET'){reply(200,{historyOnly:mail.historyOnly===true,channels:store.channels(),templates:store.templates(),receipts:store.receipts(),sends:store.sends()});return true;}
const audit=(action,detail)=>workspace?.record(user,action,detail);
if(route==='/api/mail/channels'&&method==='POST'){
if(!secureBpmTransport(request,trustedProxy))fail('请在部署机本地或 HTTPS 页面维护邮箱账号。',403);
+ if(mail.historyOnly&&body?.readOnly!==true)fail('此空间只允许配置只读 IMAP 邮箱。',409);
if(body?.id&&mail.busy(body.id))fail('此邮箱正在执行操作,请稍后保存。',409);const saved=store.saveChannel(body);audit('mail.channel.save',saved.name);reply(body.id?200:201,saved);return true;
}
- let match=/^\/api\/mail\/channels\/([\w-]+)\/(verify|poll|test)$/.exec(route);
+ let match=/^\/api\/mail\/channels\/([\w-]+)\/history$/.exec(route);
+ if(match&&method==='POST'){
+ const result=await mail.history(match[1],body);audit('mail.history.read',store.publicChannel(match[1]).name+' · '+String(body.action));reply(200,result);return true;
+ }
+ if(mail.historyOnly&&method==='POST')fail('此空间仅允许查询历史邮件,不能发信或收取模板。',409);
+ match=/^\/api\/mail\/channels\/([\w-]+)\/(verify|poll|test)$/.exec(route);
if(match&&method==='POST'){const [,id,action]=match;let result;if(action==='test'){if(typeof body.templateId!=='string')fail('请选择已生效模板。',400);result=await mail.sendTest(id,body.templateId);}else result=await mail[action](id);audit('mail.'+action,store.publicChannel(id).name);reply(200,result);return true;}
match=/^\/api\/mail\/templates\/([\w-]+)(?:\/(confirm|reject|preview|source|attachments\/([0-9]+)))?$/.exec(route);
if(match){const [,id,action,index]=match;const template=store.template(id);
diff --git a/src/modules/mail/history.cjs b/src/modules/mail/history.cjs
new file mode 100644
index 0000000..fad3d98
--- /dev/null
+++ b/src/modules/mail/history.cjs
@@ -0,0 +1,46 @@
+'use strict';
+const {simpleParser}=require('mailparser');
+const {MAX_MAIL}=require('./parser.cjs');
+const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
+const sent=folder=>folder.specialUse==='\\Sent'||/^(?:sent|sent items|sent messages|已发送|已发送邮件)$/iu.test(folder.name||folder.path.split(folder.delimiter||'/').at(-1));
+const addresses=values=>(values||[]).slice(0,100).map(({name,address})=>({name:name||'',address:address||''}));
+function date(value){
+ if(typeof value!=='string'||!/^\d{4}-\d{2}-\d{2}$/.test(value))fail('请选择有效的查询日期。');
+ const result=new Date(value+'T00:00:00Z');if(!Number.isFinite(+result)||result.toISOString().slice(0,10)!==value)fail('查询日期无效。');return result;
+}
+async function readHistory(client,input={}){
+ if(!['folders','search','message'].includes(input.action))fail('请选择只读邮件查询操作。');
+ let query,limit;
+ if(input.action==='search'){
+ const since=date(input.since),before=date(input.before),span=before-since;
+ if(span<=0||span>31*86400000)fail('每次查询最多31天,结束日期不包含当天。');
+ limit=input.limit??20;if(!Number.isInteger(limit)||limit<1||limit>50)fail('每次最多显示50封邮件。');
+ if(input.subject!==undefined&&(typeof input.subject!=='string'||input.subject.length>100||/[\x00-\x1f]/.test(input.subject)))fail('主题关键词无效。');
+ query={sentSince:since,sentBefore:before,...(input.subject?.trim()?{subject:input.subject.trim()}: {})};
+ }
+ const folders=(await client.list()).filter(f=>sent(f)&&!f.flags?.has('\\Noselect')).map(f=>({path:f.path,name:f.name||f.path}));
+ if(input.action==='folders')return {folders};
+ if(!folders.some(f=>f.path===input.folder))fail('请选择服务器上的已发送文件夹。');
+ const lock=await client.getMailboxLock(input.folder,{readOnly:true});
+ try{
+ const uidValidity=String(client.mailbox.uidValidity);
+ if(input.action==='search'){
+ const found=await client.search(query,{uid:true}),uids=(found||[]).filter(Number.isSafeInteger).sort((a,b)=>b-a),messages=[];
+ for(const uid of uids.slice(0,limit)){
+ const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info)continue;
+ messages.push({uid,subject:info.envelope?.subject||'',date:info.envelope?.date?.toISOString()||null,to:addresses(info.envelope?.to),cc:addresses(info.envelope?.cc),size:info.size});
+ }
+ return {folder:input.folder,uidValidity,messages,truncated:uids.length>limit};
+ }
+ if(!Number.isSafeInteger(input.uid)||input.uid<=0)fail('邮件标识无效。');
+ if(input.uidValidity!==uidValidity)fail('邮件文件夹已变化,请重新查询后打开。',409);
+ const info=await client.fetchOne(input.uid,{size:true},{uid:true});if(!info)fail('邮件已移除。',404);
+ if(!Number.isSafeInteger(info.size)||info.size>MAX_MAIL)fail('邮件超过10MB,仅可查看查询列表。',413);
+ const source=await client.fetchOne(input.uid,{source:true},{uid:true});if(!source?.source)fail('邮件已移除。',404);
+ if(source.source.length>MAX_MAIL)fail('邮件超过10MB,仅可查看查询列表。',413);
+ const parsed=await simpleParser(source.source,{skipHtmlToText:false,skipTextToHtml:true,skipImageLinks:true});
+ const text=parsed.text||'';
+ return {folder:input.folder,uid:input.uid,uidValidity,messageId:parsed.messageId||'',subject:parsed.subject||'',date:parsed.date?.toISOString()||null,from:addresses(parsed.from?.value),to:addresses(parsed.to?.value),cc:addresses(parsed.cc?.value),text:text.slice(0,100000),truncated:text.length>100000,attachments:parsed.attachments.map(a=>({filename:a.filename||'',size:a.size,contentType:a.contentType}))};
+ }finally{lock.release();}
+}
+module.exports={readHistory};
diff --git a/src/modules/mail/service.cjs b/src/modules/mail/service.cjs
index f9720dc..09afb4b 100644
--- a/src/modules/mail/service.cjs
+++ b/src/modules/mail/service.cjs
@@ -7,8 +7,13 @@ class MailService{
busy(id){return this.running.has(id);}
async exclusive(id,work){if(this.stopped)fail('邮件服务正在停止。',503);if(this.busy(id))fail('此邮箱正在执行操作,请稍后重试。',409);const promise=Promise.resolve().then(work);this.running.set(id,promise);return promise.finally(()=>this.running.delete(id));}
async withImap(config,work){const client=this.imapFactory(config);client.on?.('error',()=>{});this.clients.add(client);try{await client.connect();return await work(client);}finally{try{await client.logout();}catch{}client.close?.();this.clients.delete(client);}}
- verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);let smtp=false,imap=false,message='SMTP 与 IMAP 连接正常';const transport=this.smtpFactory(c.smtp);this.clients.add(transport);try{try{await transport.verify();smtp=true;}catch(e){message=safeError(e,'SMTP');}try{await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});lock.release();});imap=true;}catch(e){message+=(smtp?'':';')+(smtp?'': ' ');message=smtp?safeError(e,'IMAP'):message+safeError(e,'IMAP');}this.store.setState(id,c.version,{checkedAt:new Date().toISOString(),smtp,imap,message});return this.store.publicChannel(id);}finally{transport.close?.();this.clients.delete(transport);}});}
- poll(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(!c.enabled)fail('请先启用此邮箱的模板收信。',409);let imported=0,rejected=0;try{
+ history(id,input){return this.exclusive(id,async()=>{
+ const config=this.store.channelSecret(id);
+ try{const result=await this.withImap(config.imap,client=>require('./history.cjs').readHistory(client,input));this.store.guard(id,config.version);return result;}
+ catch(error){if([400,404,409,413].includes(error.status))throw error;fail(safeError(error,'IMAP'));}
+ });}
+ verify(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱仅支持查询已发送邮件。',409);let smtp=false,imap=false,message='SMTP 与 IMAP 连接正常';const transport=this.smtpFactory(c.smtp);this.clients.add(transport);try{try{await transport.verify();smtp=true;}catch(e){message=safeError(e,'SMTP');}try{await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});lock.release();});imap=true;}catch(e){message+=(smtp?'':';')+(smtp?'': ' ');message=smtp?safeError(e,'IMAP'):message+safeError(e,'IMAP');}this.store.setState(id,c.version,{checkedAt:new Date().toISOString(),smtp,imap,message});return this.store.publicChannel(id);}finally{transport.close?.();this.clients.delete(transport);}});}
+ poll(id){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能收取模板。',409);if(!c.enabled)fail('请先启用此邮箱的模板收信。',409);let imported=0,rejected=0;try{
await this.withImap(c.imap,async client=>{const lock=await client.getMailboxLock('INBOX',{readOnly:true});try{const epoch=String(client.mailbox.uidValidity),cursor=this.store.cursor(id);const sameEpoch=cursor.epoch===epoch;const last=sameEpoch?(cursor.uid||0):0;const query={since:new Date(sameEpoch&&cursor.since?cursor.since:Date.now()-7*86400000),...(last?{uid:(last+1)+':*'}:{})};const found=await client.search(query,{uid:true});const uids=(found||[]).filter(uid=>uid>last).sort((a,b)=>a-b).slice(0,50);
for(const uid of uids){if(this.stopped)break;this.store.guard(id,c.version);const info=await client.fetchOne(uid,{envelope:true,size:true},{uid:true});if(!info){this.store.skip(id,epoch,uid,'skipped','邮件已移除',c.version);continue;}
if(!/^\[模板\]/.test((info.envelope?.subject||'').trim())){this.store.transaction(()=>{this.store.guard(id,c.version);this.store.advance(id,epoch,uid);});continue;}
@@ -22,7 +27,7 @@ class MailService{
}finally{lock.release();}});
this.store.setState(id,c.version,{imap:true,pollAt:new Date().toISOString(),message:`收信完成:新增 ${imported} 个模板,${rejected} 封未导入`});return {imported,rejected};
}catch(error){if(error.status===409)throw error;const message=safeError(error,'IMAP');try{this.store.setState(id,c.version,{imap:false,pollAt:new Date().toISOString(),message});}catch{}fail(message);}});}
- sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id),t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST'};const rendered=renderTemplate(t,values);const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;try{await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,t.id);const result=await transport.sendMail({from:{address:c.email,name:c.name},to:{address:c.email},subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:t.attachments.map(a=>({filename:a.filename,content:Buffer.from(a.content,'base64'),contentType:a.contentType,...(a.cid?{cid:a.cid}:{}),contentDisposition:a.inline?'inline':'attachment'}))});if(!result.accepted?.length)throw new Error('Recipient rejected');this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:c.email};}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核对,请检查本邮箱后再决定是否重试。':safeError(e,'SMTP'));}finally{transport.close?.();this.clients.delete(transport);}});}
+ sendTest(id,templateId){return this.exclusive(id,async()=>{const c=this.store.channelSecret(id);if(c.readOnly)fail('只读邮箱不能发送邮件。',409);const t=this.store.template(templateId);if(t.channelId!==id||t.status!=='active')fail('请选择此邮箱已确认生效的模板。',409);const values={'产品线':t.scope||'默认','订单号':'TEST','日期':new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Shanghai'}).format(new Date()),'订单列表':'测试订单 TEST'};const rendered=renderTemplate(t,values);const transport=this.smtpFactory(c.smtp);this.clients.add(transport);let sendId;try{await transport.verify();this.store.guard(id,c.version);sendId=this.store.beginSend(id,t.id);const result=await transport.sendMail({from:{address:c.email,name:c.name},to:{address:c.email},subject:'[测试] '+rendered.subject,text:rendered.text,html:rendered.html,messageId:`<${sendId}@${c.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true,attachments:t.attachments.map(a=>({filename:a.filename,content:Buffer.from(a.content,'base64'),contentType:a.contentType,...(a.cid?{cid:a.cid}:{}),contentDisposition:a.inline?'inline':'attachment'}))});if(!result.accepted?.length)throw new Error('Recipient rejected');this.store.finishSend(sendId,'sent');return {id:sendId,status:'sent',to:c.email};}catch(e){if(sendId)this.store.finishSend(sendId,'unknown');if(e.status===409)throw e;fail(sendId?'发信结果待核对,请检查本邮箱后再决定是否重试。':safeError(e,'SMTP'));}finally{transport.close?.();this.clients.delete(transport);}});}
start(){this.stopped=false;const tick=()=>{for(const c of this.store.channels())if(c.enabled&&!this.busy(c.id))this.poll(c.id).catch(()=>{});};this.timer=setInterval(tick,this.interval);this.timer.unref?.();this.startTimer=setTimeout(tick,2000);this.startTimer.unref?.();}
async stop(){this.stopped=true;clearInterval(this.timer);clearTimeout(this.startTimer);for(const client of this.clients)try{client.close?.();}catch{}await Promise.allSettled([...this.running.values()]);}
}
diff --git a/src/modules/mail/store.cjs b/src/modules/mail/store.cjs
index 63fd7d2..1d71500 100644
--- a/src/modules/mail/store.cjs
+++ b/src/modules/mail/store.cjs
@@ -29,14 +29,15 @@ class MailStore{
decode(id,value){try{return this.vault.decode(id,value);}catch{fail('邮件加密存储不可用,请联系管理员。',503);}}
row(id){const row=this.db.prepare('SELECT * FROM channels WHERE id=?').get(id);if(!row)fail('邮箱不存在。',404);return row;}
channelSecret(id){const row=this.row(id);return {...this.decode(id,row.payload),id,version:row.version};}
- publicChannel(id){const c=this.channelSecret(id),state=JSON.parse(this.row(id).state);return {...c,smtp:{...c.smtp,password:undefined,hasPassword:!!c.smtp.password},imap:{...c.imap,password:undefined,hasPassword:!!c.imap.password},state};}
+ publicChannel(id){const c=this.channelSecret(id),state=JSON.parse(this.row(id).state);return {...c,smtp:{...c.smtp,password:undefined,hasPassword:!!c.smtp?.password},imap:{...c.imap,password:undefined,hasPassword:!!c.imap.password},state};}
channels(){return this.db.prepare('SELECT id FROM channels ORDER BY rowid').all().map(r=>this.publicChannel(r.id));}
saveChannel(input){return this.transaction(()=>{
if(!input||typeof input!=='object')fail('邮箱配置无效。');const old=input.id?this.channelSecret(input.id):null;if(old&&old.version!==input.version)fail('邮箱已被修改,请刷新后重试。',409);
const id=old?.id||crypto.randomUUID(),address=email(input.email);const existing=this.db.prepare('SELECT id FROM channels WHERE email=?').get(address);if(existing&&existing.id!==id)fail('此邮箱已托管,请使用已有邮箱。',409);
- if(typeof input.enabled!=='boolean'||!Array.isArray(input.senders)||!input.senders.length||input.senders.length>100)fail('请填写模板发件人名单,并选择是否启用收信。');
- const endpoint=kind=>{const v=input[kind];if(!v||!['tls','starttls'].includes(v.security)||!Number.isInteger(v.port)||v.port<1||v.port>65535)fail(kind.toUpperCase()+' 端口或加密方式无效。');const host=text(v.host,'服务器地址',253);if(!/^[a-zA-Z0-9.:-]+$/.test(host)||host.startsWith('-'))fail('服务器地址只填写主机名或 IP。');const password=v.password===''&&old?old[kind].password:v.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 '+kind.toUpperCase()+' 密码或授权码。');const user=text(v.user,'登录账号',254);if(old&&v.password===''&&(old.email!==address||old[kind].user!==user||old[kind].host!==host))fail('更换邮箱、服务器或登录账号时,请重新填写密码。');return {host,port:v.port,security:v.security,user,password};};
- const saved={name:text(input.name,'邮箱名称',80),email:address,smtp:endpoint('smtp'),imap:endpoint('imap'),senders:[...new Set(input.senders.map(email))],enabled:input.enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
+ const readOnly=input.readOnly===true;
+ if(!readOnly&&(typeof input.enabled!=='boolean'||!Array.isArray(input.senders)||!input.senders.length||input.senders.length>100))fail('请填写模板发件人名单,并选择是否启用收信。');
+ const endpoint=kind=>{const v=input[kind];if(!v||!['tls','starttls'].includes(v.security)||!Number.isInteger(v.port)||v.port<1||v.port>65535)fail(kind.toUpperCase()+' 端口或加密方式无效。');const host=text(v.host,'服务器地址',253);if(!/^[a-zA-Z0-9.:-]+$/.test(host)||host.startsWith('-'))fail('服务器地址只填写主机名或 IP。');const password=v.password===''&&old?old[kind]?.password:v.password;if(typeof password!=='string'||!password||password.length>2048)fail('请输入 '+kind.toUpperCase()+' 密码或授权码。');const user=text(v.user,'登录账号',254);if(old&&v.password===''&&(old.email!==address||old[kind].user!==user||old[kind].host!==host))fail('更换邮箱、服务器或登录账号时,请重新填写密码。');return {host,port:v.port,security:v.security,user,password};};
+ const saved={name:text(input.name,'邮箱名称',80),email:address,readOnly,smtp:readOnly?{}:endpoint('smtp'),imap:endpoint('imap'),senders:readOnly?[]:[...new Set(input.senders.map(email))],enabled:readOnly?false:input.enabled,createdAt:old?.createdAt||at(),updatedAt:at()};
const reset=!old||old.email!==address||JSON.stringify(old.imap)!==JSON.stringify(saved.imap);const oldrow=old?this.row(id):null;
const changed=reset||JSON.stringify(old?.smtp)!==JSON.stringify(saved.smtp);const state=changed?{checkedAt:null,smtp:false,imap:false,pollAt:null,message:'待检查连接'}:JSON.parse(oldrow.state);
this.db.prepare('INSERT INTO channels VALUES(?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET email=excluded.email,version=excluded.version,payload=excluded.payload,state=excluded.state,cursor=excluded.cursor').run(id,address,(old?.version||0)+1,this.encode(id,saved),JSON.stringify(state),reset?'{}':oldrow.cursor);return this.publicChannel(id);
diff --git a/src/modules/notifications/service.cjs b/src/modules/notifications/service.cjs
index 1e048ca..1549c6a 100644
--- a/src/modules/notifications/service.cjs
+++ b/src/modules/notifications/service.cjs
@@ -25,7 +25,7 @@ class NotificationService{
if(this.stopped)break;
const channel=this.mail.store.channelSecret(config.channelId),snapshot={channelId:channel.id,industry:items[0].industry,sourceIds:items.map(i=>i.sourceId),subject:items.length===1?items[0].subject:items[0].industry+'业务通知',text:items.map(i=>i.brief).join('\n\n'),to:[...group.to],cc:[...group.cc],slot:new Date(due).toISOString()};
const batch=this.store.prepare(items,snapshot);let transport,sending=false;
- try{transport=this.mail.smtpFactory(channel.smtp);await transport.verify();this.mail.store.guard(channel.id,channel.version);this.store.beginSending(batch);sending=true;
+ try{if(channel.readOnly)throw Error('只读邮箱不能发送邮件。');transport=this.mail.smtpFactory(channel.smtp);await transport.verify();this.mail.store.guard(channel.id,channel.version);this.store.beginSending(batch);sending=true;
const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:snapshot.to,cc:snapshot.cc,subject:snapshot.subject,text:snapshot.text,attachments:[],messageId:`<${batch}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
const accepted=new Set((result.accepted||[]).map(a=>String(a.address||a).toLowerCase()));if(result.rejected?.length||[...snapshot.to,...snapshot.cc].some(a=>!accepted.has(a.toLowerCase()))){this.store.mark(batch,'unknown','部分收件人未被邮件服务器接受,请核实后处理。');}else this.store.mark(batch,'sent');
}catch{this.store.mark(batch,sending?'unknown':'failed',sending?'发信结果待核实,请查询邮件服务器记录。':'SMTP 连接检查失败,请查看通知队列的重试状态。');}finally{transport?.close?.();}
diff --git a/src/modules/order-rules/api.cjs b/src/modules/order-rules/api.cjs
new file mode 100644
index 0000000..2830b8c
--- /dev/null
+++ b/src/modules/order-rules/api.cjs
@@ -0,0 +1,37 @@
+'use strict';
+const {fail}=require('./validation.cjs');
+async function orderRuleApi({orderRules,mail,workspace,user,route,method,body,reply}){
+ if(route!=='/api/order-rules'&&!route.startsWith('/api/order-rules/'))return false;
+ if(!orderRules)fail('分类通知规则服务未启动。',503);
+ if(route==='/api/order-rules'&&method==='GET'){reply(200,orderRules.snapshot());return true;}
+ if(method!=='POST')fail('没有找到此规则操作。',404);
+ if(user.role==='viewer')fail('只读成员不能编辑规则或提交样本。',403);
+ const actor=user.username;
+ if(route==='/api/order-rules/preview'||route==='/api/order-rules/events'){
+ if(!body||Object.keys(body).some(k=>k!=='sample')||!body.sample||typeof body.sample!=='object'||Array.isArray(body.sample))fail('请提供 BPM 样本对象。');
+ const preview=route.endsWith('/preview');reply(preview?200:201,preview?orderRules.preview(body.sample):orderRules.ingest(body.sample,actor));
+ if(!preview)workspace?.record(user,'识别分类通知订单','来源任务 '+String(body.sample.taskId));return true;
+ }
+ if(user.role!=='admin')fail('仅管理员可维护规则、批次与发送设置。',403);
+ let result;
+ if(route==='/api/order-rules/rules')result=orderRules.saveRule(body,actor);
+ else if(route==='/api/order-rules/settings'){
+ if(body?.enabled){if(!mail)fail('发件邮箱服务未启动。',409);const channel=mail.store.publicChannel(body.channelId);if(!channel.state.smtp)fail('请先验证发件邮箱 SMTP。',409);}
+ result=orderRules.saveSettings(body,actor);
+ }else if(route==='/api/order-rules/prepare'){
+ if(!body||Object.keys(body).some(k=>k!=='cutoff'))fail('请提供发送截止时间。');
+ const window=orderRules.snapshot().window;
+ if(!window?.available||Date.parse(body.cutoff)!==Date.parse(window.end))fail('仅能在配置的发送时点整理本时段订单;更早历史不补发。',409);
+ result=orderRules.prepare(body.cutoff,actor,window);
+ }else{
+ const rule=/^\/api\/order-rules\/rules\/([\w-]+)\/(publish|pause)$/.exec(route);
+ const batch=/^\/api\/order-rules\/batches\/([\w-]+)\/resolve$/.exec(route);
+ const recheck=/^\/api\/order-rules\/orders\/([\w-]+)\/recheck$/.exec(route);
+ if(rule){if(!body||Object.keys(body).some(k=>k!=='version'))fail('请提供当前草稿版本。');result=orderRules[rule[2]](rule[1],body,actor);}
+ else if(batch){if(!body||Object.keys(body).some(k=>!['resolution','note'].includes(k)))fail('核验内容无效。');result=orderRules.resolve(batch[1],body,actor);}
+ else if(recheck){if(!body||Object.keys(body).some(k=>k!=='note'))fail('重新识别内容无效。');result=orderRules.recheck(recheck[1],body,actor);}
+ else fail('没有找到此规则操作。',404);
+ }
+ workspace?.record(user,'维护分类通知规则',route.slice('/api/order-rules'.length));reply(200,result);return true;
+}
+module.exports={orderRuleApi};
diff --git a/src/modules/order-rules/batch.cjs b/src/modules/order-rules/batch.cjs
new file mode 100644
index 0000000..bb99b71
--- /dev/null
+++ b/src/modules/order-rules/batch.cjs
@@ -0,0 +1,69 @@
+'use strict';
+const path=require('node:path');
+const fail=message=>{throw Object.assign(new Error(message),{status:409});};
+const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
+const lines=value=>escape(value).replace(/\r?\n/g,'
');
+
+function recipients(values,label){
+ if(!Array.isArray(values))fail(`${label}邮箱名单无效。`);
+ const result=[];
+ for(const value of values){
+ if(typeof value!=='string'||/[\r\n\x00-\x1f\x7f]/.test(value))fail(`${label}邮箱地址无效。`);
+ const address=value.trim().toLowerCase();
+ const parts=address.split('@'),local=parts[0],domain=parts[1];
+ if(parts.length!==2||address.length>254||!local||local.length>64||!domain||!domain.includes('.')||!/^[-a-z0-9!#$%&'*+/=?^_`{|}~.]+$/i.test(local)||local.startsWith('.')||local.endsWith('.')||local.includes('..')||domain.split('.').some(p=>!p||p.length>63||! /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i.test(p)))fail(`${label}邮箱地址无效。`);
+ if(!result.includes(address))result.push(address);
+ }
+ return result;
+}
+
+function fileLink(filePath){
+ if(filePath.startsWith('\\\\'))return 'file://'+filePath.slice(2).split('\\').map(encodeURIComponent).join('/');
+ if(/^[a-z]:[\\/]/i.test(filePath))return 'file:///'+filePath.replace(/\\/g,'/').split('/').map((p,i)=>i===0?p:encodeURIComponent(p)).join('/');
+ return 'file://'+filePath.split('/').map(encodeURIComponent).join('/');
+}
+function validFile(file){
+ return file&&typeof file.name==='string'&&file.name.length>0&&!/[\r\n\x00-\x1f]/.test(file.name)&&typeof file.path==='string'&&!/[\r\n\x00-\x1f]/.test(file.path)&&(path.isAbsolute(file.path)||path.win32.isAbsolute(file.path))&&!/^[a-z]+:\/\//i.test(file.path)&&/^[a-f\d]{64}$/i.test(file.sha256)&&Number.isSafeInteger(file.size)&&file.size>=0&&['pdf','notice'].includes(file.kind);
+}
+
+function buildBatch(rule,orders,cutoff,{maxMessageBytes=20971520,window}={}){
+ const limit=Date.parse(cutoff);
+ if(!Number.isFinite(limit)||!Number.isSafeInteger(maxMessageBytes)||maxMessageBytes<1)fail('截止时间或邮件大小设置无效。');
+ const start=window?Date.parse(window.start):null,end=window?Date.parse(window.end):null;
+ if(window&&(!Number.isFinite(start)||!Number.isFinite(end)||start>=end||end!==limit||window.startInclusive!==true||window.endInclusive!==false))fail('邮件时段窗口无效。');
+ if(!rule?.categoryId||!Array.isArray(orders)||!orders.length)fail('类别必须包含待发订单。');
+ const to=recipients(rule.to,'收件人'),cc=recipients(rule.cc||[],'抄送人').filter(a=>!to.includes(a));
+ if(!to.length)fail('收件人名单不能为空。');
+ const orderIds=[],orderNos=[],attachments=[],plain=[],html=[];
+ for(const order of orders){
+ if(!order?.id||orderIds.includes(order.id))fail('订单标识无效或重复。');
+ if(order.ruleSnapshot?.categoryId!==rule.categoryId)fail('同一批次不能混合类别。');
+ if(order.ruleSnapshot.id!==rule.id||order.ruleSnapshot.version!==rule.version)fail('同一类别包含不同规则版本,请核实后处理。');
+ if(order.status&&order.status!=='pending')fail('此类别包含未准备完成的订单。');
+ const received=Date.parse(order.event?.receivedAt);
+ if(window&&(!Number.isFinite(received)||received=end))fail('订单接收时间不属于本批时段窗口。');
+ if(!Number.isFinite(received)||received>limit)fail('订单接收时间超出本批截止范围。');
+ const number=order.event?.orderNo;
+ if(typeof number!=='string'||!number.trim()||/[\r\n\x00-\x1f]/.test(number))fail('订单号无效。');
+ if(!order.archive||!Number.isFinite(Date.parse(order.archive.archivedAt))||!Array.isArray(order.archive.files)||!order.archive.files.length)fail(`订单 ${number} 缺少归档证据,本类别已阻塞。`);
+ if(order.archive.files.some(file=>!validFile(file)))fail(`订单 ${number} 的归档文件证据无效。`);
+ if(rule.attachPdf&&!order.archive.files.some(file=>file.kind==='pdf'&&/\.pdf$/i.test(file.name)))fail(`订单 ${number} 缺少必需 PDF,本类别已阻塞。`);
+ orderIds.push(order.id);orderNos.push(number);
+ const files=order.archive.files;
+ attachments.push(...files.filter(file=>file.kind!=='pdf'||rule.attachPdf).map(file=>({...file})));
+ plain.push(`${number}\n${String(order.event.brief??'')}\n${files.map(file=>file.path).join('\n')}`);
+ html.push(`${escape(number)}
${lines(order.event.brief)}
${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(window){snapshot.window=structuredClone(window);snapshot.windowStart=new Date(start).toISOString();snapshot.windowEnd=new Date(end).toISOString();}
+ // MIME headers, encoded-word subjects, base64 wrapping, attachment metadata and
+ // boundary overhead are intentionally overestimated rather than truncating.
+ const encodedBytes=size=>Math.ceil(Math.ceil(size/3)*4/76)*78;
+ let bytes=16384+encodedBytes(Buffer.byteLength(snapshot.subject+snapshot.text+snapshot.html,'utf8'))+Buffer.byteLength([...to,...cc].join(','))*4;
+ for(const file of attachments)bytes+=encodedBytes(file.size)+4096+Buffer.byteLength(file.name,'utf8')*4;
+ if(bytes>maxMessageBytes)fail(`本类别邮件大小超过容量限制(估计 ${bytes} 字节)。`);
+ return snapshot;
+}
+module.exports={buildBatch};
diff --git a/src/modules/order-rules/catalog.cjs b/src/modules/order-rules/catalog.cjs
new file mode 100644
index 0000000..6055293
--- /dev/null
+++ b/src/modules/order-rules/catalog.cjs
@@ -0,0 +1,83 @@
+'use strict';
+
+// Public business classification only. Recipient and archive values belong in
+// the encrypted local store and are deliberately absent from this catalog.
+const rows = [
+ ['overseas-notice', '海外订单通知书', ['海外运营订单评审', '海外宽带接入产品订单', '海外IPC订单评审', '海外返工订单评审']],
+ ['overseas-change', '海外订单更改通知书', ['海外运营订单更改评审', '海外宽带接入产品订单更改评审', '海外IPC订单更改评审', '海外返工订单更改评审']],
+ ['new-retail-notice', '新零售订单通知书', ['新零售订单评审']],
+ ['new-retail-change', '新零售订单更改通知书', ['新零售订单更改评审']],
+ ['domestic-notice', '国内订单通知书', ['国内运营订单评审']],
+ ['carrier-notice', '运营商事业部订单通知书', ['宽带事业订单评审']],
+ ['hardware-notice', '智能硬件订单通知书', ['智能硬件解决方案订单评审']],
+ ['retail-notice', '小湃订单通知书', ['零售国内订单评审']],
+ ['domestic-change', '国内、运营商事业部、零售、智能硬件订单更改通知书', ['国内运营订单更改评审', '宽带事业订单更改评审', '智能硬件解决方案订单更改评审', '零售国内订单更改评审', '国内、宽带返工订单更改评审', '零售国内返工订单更改评审']],
+ ['domestic-rework', '国内、运营商事业部、零售、智能硬件返工订单通知书', ['国内、宽带返工订单评审', '零售国内返工订单评审']],
+ ['processing-notice', '加工订单通知书', ['加工订单评审']],
+ ['bs-notice', '备损订单通知书', ['备损订单评审']],
+ ['bs-change', '备损订单更改通知书', ['备损订单更改评审']],
+ ['trial-notice', '试产订单通知书', ['试产订单评审', '中试样机制作申请', '研发样机制作申请']],
+ ['trial-change', '试产订单更改通知书', ['试产订单更改评审']],
+];
+
+function seedRules() {
+ return rows.map(([id, name, processNames], index) => ({
+ id, version: 1, status: 'paused', name, categoryId: id,
+ processNames: [...processNames],
+ nodeNames: id === 'processing-notice' ? ['订单专员(激活)']
+ : id.startsWith('trial-') ? ['订单专员(订单通知书)-海外', '订单专员(订单通知书)']
+ : id === 'overseas-change' ? ['订单专员(订单通知书)', '订单更改通知书']
+ : ['订单专员(订单通知书)'],
+ adapterIds: ['bs-change', 'overseas-change'].includes(id) ? [id] : [],
+ archiveDirectory: '', filenameDate: '', subjectPrefix: `【${name}】`,
+ intro: `大家好:\n以下为${name},请查收!`, signature: '', to: [], cc: [],
+ attachPdf: id.endsWith('-change'), sourceRow: index + 2,
+ }));
+}
+
+const adapters = [
+ {
+ id: 'bs-change', label: '备损订单更改评审 v1.4(字段样本已核对)',
+ processName: '备损订单更改评审', processVersion: '1.4', verified: true,
+ verificationScope: '仅核对表单 DOM 字段结构;实时待办、PDF 与归档接口尚未验证。',
+ fields: {
+ orderNo: 'OFR_BS_Applicant.OrderNum', appDate: 'OFR_BS_Applicant.AppDate',
+ customer: 'OFR_BS_BInfo.CustomerName', productLine: 'OFR_BS_Applicant.ProductLine',
+ changeReason: 'OFR_BS_Applicant.ChangeReason', changeContent: 'OFR_BS_Applicant.OrderChangeContent',
+ },
+ sample: {
+ demo: true, connectionId: 'demo-connection', source: 'todo', instanceId: 'DEMO-BS-INSTANCE',
+ taskId: 'DEMO-BS-TASK', revision: 0, processName: '备损订单更改评审', processVersion: '1.4',
+ nodeName: '订单专员(订单通知书)', receivedAt: '2026-10-19T09:00:00+08:00',
+ serialNum: 'DEMO-SERIAL-001', brief: '演示数据:备损订单更改,非真实业务记录。',
+ fields: {
+ 'OFR_BS_Applicant.OrderNum': 'DEMO-BS-001', 'OFR_BS_Applicant.AppDate': '2026-10-19',
+ 'OFR_BS_BInfo.CustomerName': '演示客户', 'OFR_BS_Applicant.ProductLine': '演示产品线',
+ 'OFR_BS_Applicant.ChangeReason': '演示更改原因', 'OFR_BS_Applicant.OrderChangeContent': '演示更改内容',
+ },
+ },
+ },
+ {
+ id: 'overseas-change', label: '海外返工订单更改评审 v1.1(字段样本已核对)',
+ processName: '海外返工订单更改评审', processVersion: '1.1', verified: true,
+ verificationScope: '仅核对表单 DOM 字段结构;实时待办、PDF 与归档接口尚未验证。',
+ fields: {
+ orderNo: 'OFR_HWLS_Applicant.OrderNum', appDate: 'OFR_HWLS_Applicant.AppDate',
+ customer: 'OFR_HWLS_BInfo.CustomerName', quantity: 'OFR_HWLS_BInfo.TotalAmount',
+ changeReason: 'OFR_HWLS_Applicant.ChangeReason', changeContent: 'OFR_HWLS_Applicant.OrderChangeContent',
+ },
+ sample: {
+ demo: true, connectionId: 'demo-connection', source: 'todo', instanceId: 'DEMO-OVERSEAS-INSTANCE',
+ taskId: 'DEMO-OVERSEAS-TASK', revision: 0, processName: '海外返工订单更改评审', processVersion: '1.1',
+ nodeName: '订单更改通知书', receivedAt: '2026-10-19T09:01:00+08:00',
+ serialNum: 'DEMO-SERIAL-002', brief: '演示数据:海外返工订单更改,非真实业务记录。',
+ fields: {
+ 'OFR_HWLS_Applicant.OrderNum': 'DEMO-OVERSEAS-001', 'OFR_HWLS_Applicant.AppDate': '2026-10-19',
+ 'OFR_HWLS_BInfo.CustomerName': '演示客户', 'OFR_HWLS_BInfo.TotalAmount': 0,
+ 'OFR_HWLS_Applicant.ChangeReason': '演示更改原因', 'OFR_HWLS_Applicant.OrderChangeContent': '演示更改内容',
+ },
+ },
+ },
+];
+
+module.exports = { seedRules, adapters };
diff --git a/src/modules/order-rules/dispatcher.cjs b/src/modules/order-rules/dispatcher.cjs
new file mode 100644
index 0000000..84de8e8
--- /dev/null
+++ b/src/modules/order-rules/dispatcher.cjs
@@ -0,0 +1,112 @@
+'use strict';
+const fs=require('node:fs/promises');
+const path=require('node:path');
+const crypto=require('node:crypto');
+const {nextSlots}=require('../../shared/schedule.cjs');
+const {windowForCutoff}=require('./window.cjs');
+
+function sameWindow(batch,cutoff,window){
+ return batch.status==='prepared'&&Date.parse(batch.cutoff)===Date.parse(cutoff)&&batch.window?.start===window.start&&batch.window?.end===window.end&&batch.window?.startInclusive===true&&batch.window?.endInclusive===false;
+}
+
+function freeze(value){
+ if(value&&typeof value==='object'){for(const item of Object.values(value))freeze(item);Object.freeze(value);}
+ return value;
+}
+
+class OrderRuleDispatcher{
+ constructor({store,mail,settings,calendar=()=>[],clock=()=>new Date(),providersReady=()=>false}){
+ this.store=store;this.mail=mail;this.settings=settings;this.calendar=calendar;this.clock=clock;this.providersReady=providersReady;
+ this.running=null;this.stopped=false;this.schedule=null;this.timer=null;
+ }
+ ready(){
+ const config=this.store.settings(),cap=this.store.snapshot().capabilities;
+ return !this.stopped&&config.enabled===true&&this.providersReady()===true&&cap?.liveTodo===true&&cap?.pdfExport===true&&cap?.automaticArchive===true;
+ }
+ tick(now=this.clock()){
+ if(this.stopped||this.running)return this.running||Promise.resolve();
+ const task=this.perform(new Date(now));this.running=task;
+ task.finally(()=>{if(this.running===task)this.running=null;}).catch(()=>{});
+ return task;
+ }
+ async perform(now){
+ if(!this.ready())return;
+ const config=freeze(structuredClone(this.store.settings()));
+ const schedule=this.settings()?.schedule,calendar=this.calendar();
+ if(!schedule?.times?.length)return;
+ const signature=JSON.stringify([schedule,calendar]);
+ if(!this.schedule||this.schedule.signature!==signature){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;}
+ if(!this.schedule.next||Date.parse(this.schedule.next)>now.getTime())return;
+ const cutoff=this.schedule.next;
+ if(now.getTime()-Date.parse(cutoff)>60000){this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};return;}
+ if(!this.ready())return;
+ try{
+ await this.mail.exclusive(config.channelId,async()=>{
+ if(!this.ready())return;
+ // A busy mailbox cannot consume the slot or reserve any orders. Recovery
+ // applies only to this exact business window, never to earlier history.
+ const window=windowForCutoff(cutoff,schedule,calendar);
+ const existing=(this.store.snapshot().batches||[]).filter(batch=>sameWindow(batch,cutoff,window));
+ const fresh=this.store.prepare(cutoff,'系统调度',window).filter(batch=>sameWindow(batch,cutoff,window));
+ const batches=[...new Map([...existing,...fresh].map(batch=>[batch.id,freeze(structuredClone(batch))])).values()];
+ let interrupted=false;
+ for(const batch of batches){
+ if(!this.ready()){interrupted=true;break;}
+ if(batch.status!=='prepared')continue;
+ await this.dispatch(batch,config);
+ }
+ if(!interrupted)this.schedule={signature,next:nextSlots(schedule,now,1,calendar)[0]};
+ });
+ }catch(error){if(error.status!==409)throw error;}
+ }
+ async attachments(batch,config){
+ const result=[];let total=0;
+ for(const file of batch.attachments||[]){
+ if(!file||typeof file.path!=='string'||!(path.isAbsolute(file.path)||path.win32.isAbsolute(file.path))||/^[a-z]+:\/\//i.test(file.path)||!/^[a-f\d]{64}$/i.test(file.sha256)||!Number.isSafeInteger(file.size)||file.size<0)throw Error('归档文件证据无效。');
+ total+=file.size;
+ if(total>(config.maxMessageBytes||20971520))throw Error('归档文件超过邮件大小限制。');
+ const stat=await fs.stat(file.path);
+ if(!stat.isFile()||stat.size!==file.size)throw Error('归档文件大小发生变化。');
+ const content=await fs.readFile(file.path);
+ if(content.length!==file.size||crypto.createHash('sha256').update(content).digest('hex')!==file.sha256.toLowerCase())throw Error('归档文件校验失败。');
+ result.push({filename:file.name,content,contentType:file.kind==='pdf'?'application/pdf':'application/octet-stream',contentDisposition:'attachment'});
+ }
+ return result;
+ }
+ async dispatch(batch,config){
+ let transport,sending=false;
+ try{
+ if(batch.channelId&&batch.channelId!==config.channelId){
+ this.store.finishSending(batch.id,'failed','批次固定的发件邮箱与当前渠道不同,请核实邮箱设置后生成新批次。');return;
+ }
+ const attachments=await this.attachments(batch,config);
+ if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
+ const channel=freeze(structuredClone(this.mail.store.channelSecret(config.channelId)));
+ if(channel.readOnly)throw Error('只读邮箱不能用于分类通知发送。');
+ transport=this.mail.smtpFactory(channel.smtp);
+ this.mail.clients?.add(transport);
+ await transport.verify();
+ if(!this.ready()||this.store.settings().channelId!==config.channelId)throw Error('发送已暂停或配置已变更。');
+ if(this.clock().getTime()-Date.parse(batch.cutoff)>60000)throw Error('本时段发送宽限已结束。');
+ this.mail.store.guard(channel.id,channel.version);
+ this.store.beginSending(batch.id);sending=true;
+ const result=await transport.sendMail({from:{address:channel.email,name:channel.name},to:[...batch.to],cc:[...batch.cc],subject:batch.subject,text:batch.text,html:batch.html,attachments,messageId:`<${batch.id}@${channel.email.split('@')[1]}>`,disableFileAccess:true,disableUrlAccess:true});
+ const accepted=new Set((result?.accepted||[]).map(address=>String(address.address||address).toLowerCase()));
+ const partial=result?.rejected?.length||[...batch.to,...batch.cc].some(address=>!accepted.has(address.toLowerCase()));
+ this.store.finishSending(batch.id,partial?'unknown':'sent',partial?'部分收件人未被服务器接受,请核对邮件记录后处理。':'邮件服务器已接受全部收件人;最终送达请以邮件记录为准。');
+ }catch(error){
+ this.store.finishSending(batch.id,sending?'unknown':'failed',sending?'发送结果待核实,请核对邮件服务器记录后决定是否重试。':`发送前验证失败:${error.code==='ENOENT'?'归档文件不存在。':error.message==='归档文件校验失败。'?error.message:'请检查归档证据、SMTP 与启用状态。'}`);
+ }finally{
+ try{transport?.close?.();}finally{if(transport)this.mail.clients?.delete(transport);}
+ }
+ }
+ start(){
+ if(this.timer||this.stopped)return;
+ this.timer=setInterval(()=>this.tick().catch(()=>{}),30000);this.timer.unref?.();
+ }
+ async stop(){
+ this.stopped=true;clearInterval(this.timer);this.timer=null;
+ if(this.running)await this.running.catch(()=>{});
+ }
+}
+module.exports={OrderRuleDispatcher};
diff --git a/src/modules/order-rules/matching.cjs b/src/modules/order-rules/matching.cjs
new file mode 100644
index 0000000..a3f0dae
--- /dev/null
+++ b/src/modules/order-rules/matching.cjs
@@ -0,0 +1,92 @@
+'use strict';
+const {extractTitle}=require('./title.cjs');
+
+const labels = {
+ orderNo: '订单号', appDate: '申请日期', customer: '客户', productLine: '产品线',
+ quantity: '数量', brief: '摘要', changeReason: '更改原因', changeContent: '更改内容', totalAmount: '总金额',
+};
+const present = value => value !== undefined && value !== null && (typeof value !== 'string' || value.trim() !== '');
+const scalar = value => typeof value === 'string' || (typeof value === 'number' && Number.isFinite(value));
+const nonblank = value => typeof value === 'string' && value.trim().length > 0;
+function validAppDate(value){
+ if(!nonblank(value)||!/^\d{4}-\d{2}-\d{2}(?:$|[ T])/.test(value))return false;
+ const day=value.slice(0,10),date=new Date(day+'T00:00:00Z');
+ if(!Number.isFinite(+date)||date.toISOString().slice(0,10)!==day)return false;
+ return value.length===10||Number.isFinite(Date.parse(value.replace(' ','T')));
+}
+
+function previewMatch(rules, adapters, input) {
+ const sample = input && typeof input === 'object' ? input : {};
+ const checks = [], issues = [];
+ const check = (label, ok, detail) => {
+ checks.push({ label, ok: !!ok, detail });
+ if (!ok) issues.push(detail);
+ };
+ for (const key of ['connectionId', 'instanceId', 'taskId']) {
+ check('事件身份', scalar(sample[key]) && present(sample[key]), `${key}:${present(sample[key]) ? String(sample[key]) : '缺失'}`);
+ }
+ check('事件来源', sample.source === 'todo', 'source 必须为 todo(待办)');
+ check('事件修订', scalar(sample.revision) && present(sample.revision), `revision:${present(sample.revision) ? String(sample.revision) : '缺失'}`);
+ check('接收时间', nonblank(sample.receivedAt) && /T.*(?:Z|[+-]\d{2}:\d{2})$/.test(sample.receivedAt) && Number.isFinite(Date.parse(sample.receivedAt)), 'receivedAt 必须是带时区的有效时间');
+ for (const key of ['processName', 'processVersion', 'nodeName']) {
+ check('流程信息', nonblank(sample[key]), `${key}:${nonblank(sample[key]) ? sample[key] : '缺失'}`);
+ }
+ const matches = (Array.isArray(rules) ? rules : []).filter(rule =>
+ Array.isArray(rule.processNames) && rule.processNames.includes(sample.processName)
+ && Array.isArray(rule.nodeNames) && rule.nodeNames.includes(sample.nodeName));
+ check('分类命中', matches.length === 1, matches.length === 1 ? `唯一命中:${matches[0].name}` : matches.length ? `同时命中 ${matches.length} 条规则,须消除冲突` : '没有流程名称和节点名称均精确匹配的规则');
+ const rule = matches.length === 1 ? matches[0] : null;
+ const available = rule ? (Array.isArray(adapters) ? adapters : []).filter(adapter =>
+ rule.adapterIds?.includes(adapter.id) && adapter.processName === sample.processName
+ && adapter.processVersion === sample.processVersion && adapter.verified === true) : [];
+ const adapter = available.length === 1 ? available[0] : null;
+ check('字段适配', available.length === 1, adapter ? `字段适配 ${adapter.id}:仅表单结构已核对,不代表实时接口可用` : '没有唯一、已核对且流程版本一致的字段适配器');
+
+ const raw = sample.fields && typeof sample.fields === 'object' && !Array.isArray(sample.fields) ? sample.fields : {};
+ const event = {};
+ for (const key of ['connectionId', 'source', 'instanceId', 'taskId', 'revision', 'processName', 'processVersion', 'nodeName', 'receivedAt', 'serialNum', 'demo']) {
+ if (Object.hasOwn(sample, key)) event[key] = sample[key];
+ }
+ event.documentNum = sample.serialNum ?? '';
+ event.ruleId = rule?.id ?? null;
+ event.ruleVersion = rule?.version ?? null;
+ event.categoryId = rule?.categoryId ?? null;
+ event.adapterId = adapter?.id ?? null;
+ const fieldTrace = [];
+ const mappings = adapter?.fields ?? {};
+ const titleSource=Object.hasOwn(sample,'title')?'title':typeof sample.brief==='string'&&/订单号\s*[::]/u.test(sample.brief)?'brief':null;
+ const extracted=titleSource?extractTitle(sample[titleSource]):null;
+ if(extracted){
+ event.rawTitle=extracted.rawTitle;event.titleOrders=extracted.orders;event.factoryHints=extracted.factoryHints;
+ check('标题提取',extracted.issues.length===0,extracted.issues.join(';')||`从标题提取 ${extracted.orders.length} 个订单段落;惠州线索仅供核实,不触发额外发送`);
+ }
+ for (const key of new Set(['orderNo', 'appDate', 'customer', 'productLine', 'quantity', ...Object.keys(mappings), 'brief'])) {
+ const path = key === 'brief' ? extracted?`${titleSource} → 订单段落`:'brief' : mappings[key] || '';
+ const value = key === 'brief' ? extracted?extracted.brief:sample.brief : path && Object.hasOwn(raw, path) ? raw[path] : null;
+ event[key] = value ?? null;
+ fieldTrace.push({ key, label: labels[key] || key, path, value: value ?? null });
+ }
+ for (const key of ['orderNo', 'brief']) {
+ check(labels[key], nonblank(event[key]), `${key} ${nonblank(event[key]) ? '已取得' : '缺失或不是文本'}`);
+ }
+ check('流水编号',nonblank(sample.serialNum),'流水编号 serialNum 必须有值,用于文件命名和追溯');
+ if(rule?.filenameDate==='appDate')check('申请日期',validAppDate(event.appDate),'文件名使用申请日期,样本必须包含有效的申请日期');
+ if (present(event.quantity)) {
+ const numeric = typeof event.quantity === 'number' ? event.quantity : typeof event.quantity === 'string' && event.quantity.trim() ? Number(event.quantity) : NaN;
+ check('数量', Number.isFinite(numeric) && numeric >= 0, 'quantity 必须为非负数,零数量合法');
+ if (Number.isFinite(numeric)) event.quantity = numeric;
+ } else check('数量', true, 'quantity 未提供;不猜测未核对的数量字段');
+
+ return {
+ valid: issues.length === 0, ruleId: rule?.id ?? null, categoryId: rule?.categoryId ?? null,
+ event, checks, issues, fieldTrace, candidates: matches.map(item => item.id),
+ explanation: rule ? describeRule(rule) : '按照流程名称和通知节点精确分类;未命中或多条命中时阻塞。',
+ };
+}
+
+function describeRule(rule) {
+ const date = { appDate: '申请日期', receivedAt: '接收日期', archiveDate: '归档日期' }[rule.filenameDate] || '待选择的日期';
+ return `${rule.name}:流程“${(rule.processNames || []).join('、')}”到达节点“${(rule.nodeNames || []).join('、')}”时归入本类别。本时段内同类别订单合并一封,通知与更改分别汇总,更早历史不补发。正常工作日首封只取当天零点到首个时点,第二封取两个时点之间;周一首封从上个工作日最后时点起算。${rule.attachPdf ? '附电子流 PDF;' : ''}文件以订单号、${date}、流水编号命名。BPM 节点由人工办理。`;
+}
+
+module.exports = { previewMatch, describeRule };
diff --git a/src/modules/order-rules/state.cjs b/src/modules/order-rules/state.cjs
new file mode 100644
index 0000000..1aaed5d
--- /dev/null
+++ b/src/modules/order-rules/state.cjs
@@ -0,0 +1,29 @@
+'use strict';
+
+// Actions describe completed, evidence-backed steps; callers must never accept a
+// target state from an HTTP request as authority to bypass these transitions.
+const transitions={
+ order:{
+ identified:{prepare:'preparing',block:'blocked'},
+ preparing:{archive:'archived',block:'blocked'},
+ archived:{queue:'pending',block:'blocked'},
+ pending:{batch:'batched',block:'blocked'},
+ batched:{sent:'sent',unknown:'unknown',block:'blocked',retry:'pending'},
+ blocked:{retry:'preparing'},
+ unknown:{resolve_sent:'sent',retry:'pending'},
+ sent:{}
+ },
+ batch:{
+ prepared:{send:'sending',fail:'failed',cancel:'cancelled'},
+ sending:{sent:'sent',unknown:'unknown'},
+ unknown:{resolve_sent:'sent',retry:'cancelled'},
+ failed:{},sent:{},cancelled:{}
+ }
+};
+function transition(kind,from,action){
+ const group=Object.hasOwn(transitions,kind)?transitions[kind]:null;
+ const actions=group&&Object.hasOwn(group,from)?group[from]:null;
+ if(!actions||!Object.hasOwn(actions,action))throw Object.assign(new Error(`不允许的状态操作:${kind}/${from}/${action}`),{status:409,statusCode:409});
+ return actions[action];
+}
+module.exports={transition};
diff --git a/src/modules/order-rules/store.cjs b/src/modules/order-rules/store.cjs
new file mode 100644
index 0000000..3f49301
--- /dev/null
+++ b/src/modules/order-rules/store.cjs
@@ -0,0 +1,193 @@
+'use strict';
+const fs=require('node:fs');const path=require('node:path');const crypto=require('node:crypto');
+const {DatabaseSync}=require('node:sqlite');const {BpmVault}=require('../../platform/security/vault.cjs');
+const {seedRules,adapters}=require('./catalog.cjs');const {previewMatch,describeRule}=require('./matching.cjs');
+const {buildBatch}=require('./batch.cjs');const {transition}=require('./state.cjs');
+const {fail,validateRule,publicationIssues}=require('./validation.cjs');
+const {windowForCutoff,upcomingWindow,inWindow}=require('./window.cjs');
+const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'?Object.fromEntries(Object.keys(value).sort().map(k=>[k,canonical(value[k])])):value;
+const digest=value=>crypto.createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
+const copy=value=>structuredClone(value);
+const BASE_CAPABILITIES={liveTodo:false,pdfExport:false,automaticArchive:false};
+function validDate(value){return typeof value==='string'&&/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(value)&&Number.isFinite(Date.parse(value));}
+class RuleStore{
+ constructor(dir,{clock=()=>new Date(),capabilities={},seedOverrides=[],schedule=()=>({times:['11:00','17:00'],weekends:false}),calendar=()=>[]}={}){
+ this.clock=clock;this.schedule=schedule;this.calendar=calendar;this.capabilities={...BASE_CAPABILITIES,...capabilities};
+ try{
+ fs.mkdirSync(dir,{recursive:true});this.vault=new BpmVault({stateDir:path.join(dir,'secrets')});
+ this.db=new DatabaseSync(path.join(dir,'rules.sqlite'));
+ this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000; PRAGMA secure_delete=ON;
+ CREATE TABLE IF NOT EXISTS records(kind TEXT NOT NULL,id TEXT NOT NULL,payload BLOB NOT NULL,PRIMARY KEY(kind,id));`);
+ this.transaction(()=>{
+ if(!this.get('settings','main'))this.put('settings',{id:'main',version:1,enabled:false,channelId:'',maxMessageBytes:20971520});
+ for(const rule of seedRules())if(!this.get('rules',rule.id)){
+ const override=seedOverrides.find(r=>r.id===rule.id);
+ const draft=override?validateRule({...rule,...override},rule):rule;
+ this.put('rules',{id:rule.id,draft:{...draft,status:'draft'},published:null,trialVersion:null,trialDemo:null});
+ }
+ for(const batch of this.all('batches')){
+ if(batch.status==='sending'){
+ batch.status='unknown';batch.error='服务重启,发信结果待人工核实。';this.put('batches',batch);
+ this.updateBatchOrders(batch,'unknown',batch.error);
+ }
+ }
+ });
+ }catch(error){try{this.db?.close();}catch{}this.vault?.destroy();throw error;}
+ }
+ now(){return this.clock().toISOString();}
+ transaction(work){this.db.exec('BEGIN IMMEDIATE');try{const result=work();this.db.exec('COMMIT');return result;}catch(error){this.db.exec('ROLLBACK');throw error;}}
+ get(kind,id){const row=this.db.prepare('SELECT payload FROM records WHERE kind=? AND id=?').get(kind,id);return row?this.vault.decode(kind+':'+id,row.payload):null;}
+ all(kind){return this.db.prepare('SELECT id,payload FROM records WHERE kind=? ORDER BY rowid').all(kind).map(r=>this.vault.decode(kind+':'+r.id,r.payload));}
+ put(kind,value){this.db.prepare('INSERT INTO records VALUES(?,?,?) ON CONFLICT(kind,id) DO UPDATE SET payload=excluded.payload').run(kind,value.id,this.vault.encode(kind+':'+value.id,value));return value;}
+ audit(actor,action,detail){this.put('audit',{id:crypto.randomUUID(),at:this.now(),actor:String(actor||'系统'),action,detail});}
+ settings(){const {id,...settings}=this.get('settings','main');return settings;}
+ saveSettings(input,actor){return this.transaction(()=>{
+ const old=this.settings();
+ if(!input||Object.keys(input).some(k=>!['version','enabled','channelId','maxMessageBytes'].includes(k))||input.version!==old.version)fail('设置已变化,请刷新。',409);
+ if(typeof input.enabled!=='boolean'||typeof input.channelId!=='string'||input.channelId.length>100||!Number.isInteger(input.maxMessageBytes)||input.maxMessageBytes<1024||input.maxMessageBytes>100*1024*1024)fail('邮箱或邮件大小限制无效。');
+ if(input.enabled&&(!Object.values(this.capabilities).every(Boolean)||!input.channelId))fail('待办接入、PDF 导出与自动归档尚未全部联调,暂不能启用自动发送。',409);
+ this.put('settings',{...input,id:'main',version:old.version+1});this.audit(actor,'保存分类通知设置',input.enabled?'已启用':'已暂停');return this.settings();
+ });}
+ snapshot(){
+ const rules=this.all('rules').map(record=>({...record.draft,status:record.published?.status||'draft',hasDraft:!record.published||record.draft.version!==record.published.version,publishedVersion:record.published?.version||null,trialVersion:record.trialVersion,explanation:describeRule(record.draft),validationIssues:publicationIssues(record.draft,adapters)}));
+ return {rules,adapters:copy(adapters),orders:this.all('orders').reverse(),batches:this.all('batches').reverse(),settings:this.settings(),audit:this.all('audit').slice(-100).reverse(),capabilities:copy(this.capabilities),window:upcomingWindow(this.clock(),this.schedule(),this.calendar())};
+ }
+ saveRule(input,actor){return this.transaction(()=>{
+ const record=this.get('rules',input?.id);if(!record)fail('规则不存在。',404);
+ this.put('rule-history',{id:record.id+':'+record.draft.version,rule:copy(record.draft),at:this.now(),actor});
+ record.draft=validateRule(input,record.draft);record.trialVersion=null;record.trialDemo=null;this.put('rules',record);
+ this.audit(actor,'保存规则草稿',record.id+' v'+record.draft.version);return {...record.draft,explanation:describeRule(record.draft)};
+ });}
+ preview(sample){
+ const records=this.all('rules');const result=previewMatch(records.map(r=>r.draft),adapters,sample);
+ if(result.valid&&result.ruleId){const record=records.find(r=>r.id===result.ruleId);if(record){record.trialVersion=record.draft.version;record.trialDemo=sample.demo===true;this.put('rules',record);}}
+ return result;
+ }
+ publish(id,input,actor){return this.transaction(()=>{
+ const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
+ if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
+ const issues=publicationIssues(record.draft,adapters);
+ if(record.trialVersion!==record.draft.version)issues.push('请先用真实结构样本试运行当前草稿');
+ if(record.trialDemo!==false)issues.push('演示样本仅用于理解字段,发布前请校验真实业务样本');
+ const overlaps=this.all('rules').filter(r=>r.id!==id&&r.published?.status==='enabled'&&r.published.processNames.some(p=>record.draft.processNames.includes(p))&&r.published.nodeNames.some(n=>record.draft.nodeNames.includes(n)));
+ if(overlaps.length)issues.push('与已启用规则存在流程和节点冲突:'+overlaps.map(r=>r.draft.name).join('、'));
+ if(issues.length)fail(issues.join(';'),409);
+ record.published={...copy(record.draft),status:'enabled',publishedAt:this.now()};this.put('rules',record);
+ this.put('rule-history',{id:record.id+':'+record.draft.version,rule:copy(record.published),at:this.now(),actor});this.audit(actor,'发布规则',id+' v'+record.draft.version);
+ return this.snapshot().rules.find(r=>r.id===id);
+ });}
+ pause(id,input,actor){return this.transaction(()=>{
+ const record=this.get('rules',id);if(!record)fail('规则不存在。',404);
+ if(input?.version!==record.draft.version)fail('规则已变化,请刷新。',409);
+ if(record.published)record.published.status='paused';this.put('rules',record);this.audit(actor,'暂停规则',id);return this.snapshot().rules.find(r=>r.id===id);
+ });}
+ matchingPublications(sample){
+ const rules=this.all('rules').filter(r=>r.published).map(r=>r.published);
+ const enabled=rules.filter(r=>r.status==='enabled');
+ const hasEnabledMatch=enabled.some(r=>r.processNames.includes(sample.processName)&&r.nodeNames.includes(sample.nodeName));
+ return hasEnabledMatch?enabled:rules;
+ }
+ ingest(sample,actor){return this.transaction(()=>{
+ if(sample?.demo)fail('演示样本仅用于试运行,不能创建正式任务。');
+ if(!sample||['connectionId','source','instanceId','taskId','revision'].some(k=>!['string','number'].includes(typeof sample[k])||!String(sample[k]).trim()||String(sample[k]).length>250))fail('缺少来源、流程实例、任务及业务修订标识。');
+ sample=copy(sample);for(const key of ['connectionId','source','instanceId','taskId','revision'])sample[key]=String(sample[key]).trim();
+ const id=digest(['BPM',sample.connectionId,sample.source,sample.instanceId,sample.taskId,sample.revision]);
+ const sourceHash=digest(sample),old=this.get('orders',id);
+ if(old){if(old.sourceHash!==sourceHash)fail('相同任务和业务修订的内容已变化,请核实来源版本。',409);return old;}
+ const active=this.matchingPublications(sample);
+ const result=previewMatch(active,adapters,sample),rule=active.find(r=>r.id===result.ruleId);
+ const ready=Object.values(this.capabilities).every(Boolean),enabled=rule?.status==='enabled';
+ const order={id,sourceHash,event:result.event||copy(sample),sample:copy(sample),ruleSnapshot:rule?copy(rule):null,categoryId:result.categoryId||rule?.categoryId||'',status:result.valid&&ready&&enabled?'identified':'blocked',error:result.valid?(!enabled?'该类别规则已暂停。':ready?null:'待办接入、PDF 导出和自动归档待联调。'):result.issues.join(';'),ingestedAt:this.now(),updatedAt:this.now(),archive:null,batchId:null,trace:result};
+ const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
+ if(window&&validDate(sample.receivedAt)&&Date.parse(sample.receivedAt){
+ if(!this.capabilities.automaticArchive)fail('自动归档接入待联调。',409);
+ const order=this.get('orders',id);if(!order)fail('订单任务不存在。',404);
+ if(!['identified','preparing'].includes(order.status))fail('当前状态不允许记录归档结果。',409);
+ const window=upcomingWindow(this.clock(),this.schedule(),this.calendar());
+ if(window&&Date.parse(order.event.receivedAt)!f||typeof f.name!=='string'||!f.name||/[\\/\x00-\x1f]/.test(f.name)||typeof f.path!=='string'||!path.win32.isAbsolute(f.path)||! /^[a-f0-9]{64}$/i.test(f.sha256)||!Number.isSafeInteger(f.size)||f.size<1||!['pdf','notice'].includes(f.kind)))fail('归档证据不完整。');
+ if(order.status==='identified')order.status=transition('order',order.status,'prepare');
+ order.status=transition('order',order.status,'archive');order.archive=copy(evidence);
+ if(order.ruleSnapshot.attachPdf&&!evidence.files.some(f=>f.kind==='pdf')){order.status='blocked';order.error='缺少本类别要求的电子流 PDF。';}
+ else {order.status=transition('order',order.status,'queue');order.error=null;}
+ order.updatedAt=this.now();this.put('orders',order);this.audit(actor,'记录执行器归档结果',id);return order;
+ });}
+ retryArchive(id,note,actor){return this.transaction(()=>{
+ if(typeof note!=='string'||note.trim().length<5||note.length>2000)fail('请填写至少5字修复依据。');
+ if(!this.capabilities.automaticArchive)fail('自动归档接入待联调。',409);
+ const order=this.get('orders',id);if(!order||!order.ruleSnapshot||order.status!=='blocked')fail('当前任务不能重试归档。',409);
+ order.status=transition('order',order.status,'retry');order.error=null;order.updatedAt=this.now();this.put('orders',order);this.audit(actor,'重试归档',id+':'+note.trim());return order;
+ });}
+ recheck(id,input,actor){return this.transaction(()=>{
+ if(typeof input?.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请填写至少5字的重新识别依据。');
+ const order=this.get('orders',id);
+ if(!order||order.batchId||!['blocked','identified','preparing','archived','pending'].includes(order.status))fail('仅未进入批次的待处理订单可以重新识别。',409);
+ const published=this.matchingPublications(order.sample);
+ const result=previewMatch(published,adapters,order.sample),rule=published.find(r=>r.id===result.ruleId);
+ if(!result.valid||rule?.status!=='enabled')fail(result.issues.join(';')||'对应规则尚未启用。',409);
+ order.event=result.event;order.ruleSnapshot=copy(rule);order.categoryId=rule.categoryId;order.trace=result;
+ order.archive=null;order.status=Object.values(this.capabilities).every(Boolean)?'identified':'blocked';
+ order.error=order.status==='blocked'?'待办接入、PDF 导出和自动归档待联调。':null;order.updatedAt=this.now();
+ this.put('orders',order);this.audit(actor,'应用当前规则重新识别',id+':'+input.note.trim());return order;
+ });}
+ prepare(cutoff,actor,requestedWindow){return this.transaction(()=>{
+ if(!validDate(cutoff))fail('请选择包含时区的有效发送截止时间。');
+ const window=windowForCutoff(cutoff,this.schedule(),this.calendar());
+ if(requestedWindow&&(requestedWindow.start!==window.start||requestedWindow.end!==window.end))fail('发送时段与业务日历不一致。',409);
+ for(const batch of this.all('batches'))if(batch.status==='prepared'&&Date.parse(batch.cutoff)b.categoryId===rule.categoryId&&Date.parse(b.cutoff)===Date.parse(cutoff)&&!['failed','cancelled'].includes(b.status)))continue;
+ const published=this.get('rules',rule.id)?.published;
+ let error=!published||published.status!=='enabled'?'该类别规则已暂停。':null;
+ if(!error&&orders.some(o=>o.status!=='pending'))error='本类别存在字段、文件或归档尚未准备完成的订单。';
+ let snapshot;
+ if(!error)try{snapshot=buildBatch(rule,orders,cutoff,{maxMessageBytes:this.settings().maxMessageBytes,window});}catch(cause){error=cause.message;}
+ if(error){for(const order of orders){order.error=error;this.put('orders',order);}continue;}
+ const batch={...snapshot,id:crypto.randomUUID(),status:'prepared',createdAt:this.now(),ruleSnapshot:copy(rule),channelId:this.settings().channelId,error:null};
+ this.put('batches',batch);
+ for(const order of orders){order.status=transition('order',order.status,'batch');order.batchId=batch.id;order.error=null;order.updatedAt=this.now();this.put('orders',order);}
+ this.audit(actor,'固定分类邮件批次',batch.id+' '+orders.length+'单');batches.push(batch);
+ }
+ return batches;
+ });}
+ updateBatchOrders(batch,status,error=null){for(const id of batch.orderIds){const order=this.get('orders',id);if(order?.batchId===batch.id){order.status=status;order.error=error;order.updatedAt=this.now();this.put('orders',order);}}}
+ beginSending(id){return this.transaction(()=>{
+ const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
+ if(this.get('rules',batch.ruleSnapshot.id)?.published?.status!=='enabled')fail('该类别规则已暂停,批次不能进入发送。',409);
+ const orders=batch.orderIds.map(oid=>this.get('orders',oid));
+ if(orders.some(o=>!o||o.batchId!==id||o.status!=='batched'))fail('批次订单预留已变化。',409);
+ batch.status=transition('batch',batch.status,'send');this.put('batches',batch);return batch;
+ });}
+ finishSending(id,status,message=null){return this.transaction(()=>{
+ const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
+ if(!['sent','unknown','failed'].includes(status))fail('发送结果无效。');
+ batch.status=transition('batch',batch.status,{sent:'sent',unknown:'unknown',failed:'fail'}[status]);batch.error=message;batch.finishedAt=this.now();this.put('batches',batch);
+ this.updateBatchOrders(batch,status==='failed'?'pending':status,message);
+ if(status==='failed')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===batch.id){order.batchId=null;this.put('orders',order);}}
+ this.audit('系统发送','更新批次结果',id+' '+status);return batch;
+ });}
+ resolve(id,input,actor){return this.transaction(()=>{
+ const batch=this.get('batches',id);if(!batch)fail('批次不存在。',404);
+ if(!input||!['sent','retry'].includes(input.resolution)||typeof input.note!=='string'||input.note.trim().length<5||input.note.length>2000)fail('请选择核验结果并填写至少5字依据。');
+ batch.status=transition('batch',batch.status,input.resolution==='sent'?'resolve_sent':'retry');batch.resolution={...input,actor,at:this.now()};this.put('batches',batch);
+ this.updateBatchOrders(batch,input.resolution==='sent'?'sent':'pending',null);
+ if(input.resolution==='retry')for(const oid of batch.orderIds){const order=this.get('orders',oid);if(order?.batchId===id){order.batchId=null;this.put('orders',order);}}
+ this.audit(actor,'核验分类邮件结果',id+':'+input.note.trim());return batch;
+ });}
+ close(){this.db.close();this.vault.destroy();}
+}
+module.exports={RuleStore};
diff --git a/src/modules/order-rules/title.cjs b/src/modules/order-rules/title.cjs
new file mode 100644
index 0000000..775f101
--- /dev/null
+++ b/src/modules/order-rules/title.cjs
@@ -0,0 +1,22 @@
+'use strict';
+
+// Fixed field boundaries keep extraction deterministic; raw title stays on the event.
+const retained=new Set(['订单号','机芯号','产品型号','客户简称','总数量','订单类别']);
+function extractTitle(title){
+ const raw=typeof title==='string'?title:'';
+ const text=raw.replace(/
/gi,'\n').replace(/ | | /gi,' ');
+ const matches=[...text.matchAll(/(客户等级|毛利|订单号|机芯号|产品型号|客户简称|总数量|订单类别|订单类型|业务模式)\s*[::]/gu)];
+ const orders=[],factoryHints=[],issues=[];let current=null;
+ for(let i=0;iorder.text).join('\n'),factoryHints,issues};
+}
+module.exports={extractTitle};
diff --git a/src/modules/order-rules/validation.cjs b/src/modules/order-rules/validation.cjs
new file mode 100644
index 0000000..48fba78
--- /dev/null
+++ b/src/modules/order-rules/validation.cjs
@@ -0,0 +1,42 @@
+'use strict';
+const fail=(message,status=400)=>{throw Object.assign(new Error(message),{status});};
+const fields=['id','version','name','categoryId','processNames','nodeNames','adapterIds','archiveDirectory','filenameDate','subjectPrefix','intro','signature','to','cc','attachPdf','sourceRow'];
+function addresses(values){
+ if(!Array.isArray(values)||values.length>500)fail('收件名单格式无效。');
+ return [...new Set(values.map(v=>{
+ if(typeof v!=='string'||v.length>254||! /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?\.[A-Za-z]{2,63}$/.test(v.trim()))fail('请检查邮箱地址:'+String(v).slice(0,80));
+ return v.trim().toLowerCase();
+ }))];
+}
+function validateRule(input,old){
+ if(!input||typeof input!=='object'||Array.isArray(input))fail('规则格式无效。');
+ if(!old||input.id!==old.id||input.categoryId!==old.categoryId)fail('规则类别标识不能修改。');
+ if(input.version!==old.version)fail('规则已被其他人修改,请刷新后重试。',409);
+ const rule=Object.fromEntries(fields.map(k=>[k,input[k]??old[k]]));
+ for(const key of ['name','subjectPrefix','archiveDirectory','intro','signature']){
+ if(typeof rule[key]!=='string'||rule[key].length>(['intro','signature'].includes(key)?4000:1200)||(/[\x00]/.test(rule[key])))fail('规则文本格式无效。');
+ rule[key]=rule[key].trim();
+ }
+ if(!rule.name||/[\r\n]/.test(rule.subjectPrefix)||/[\x00-\x1f]/.test(rule.archiveDirectory))fail('请填写规则名称,主题和目录不能换行。');
+ for(const key of ['processNames','nodeNames','adapterIds']){
+ if(!Array.isArray(rule[key])||rule[key].length>100||rule[key].some(v=>typeof v!=='string'||!v.trim()||v.length>250||/[\x00-\x1f]/.test(v)))fail('流程、节点或字段适配配置无效。');
+ rule[key]=[...new Set(rule[key].map(v=>v.trim()))];
+ }
+ if(!['','appDate','receivedAt','archiveDate'].includes(rule.filenameDate)||typeof rule.attachPdf!=='boolean')fail('请选择有效的日期来源和附件要求。');
+ rule.to=addresses(rule.to);rule.cc=addresses(rule.cc).filter(v=>!rule.to.includes(v));
+ rule.version=old.version+1;rule.status='draft';return rule;
+}
+function publicationIssues(rule,adapters){
+ const issues=[];
+ if(!rule.processNames.length||!rule.nodeNames.length)issues.push('请选择适用流程和到达节点');
+ if(!rule.subjectPrefix)issues.push('请填写邮件主题前缀');
+ if(!rule.archiveDirectory||!/^\\\\[^\\]+\\[^\\]+/.test(rule.archiveDirectory)||/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(rule.archiveDirectory))issues.push('请选择完整服务器共享归档目录');
+ if(!rule.filenameDate)issues.push('请选择文件名日期来源');
+ if(!rule.to.length)issues.push('请配置收件人');
+ for(const process of rule.processNames){
+ if(!adapters.some(a=>a.verified&&a.processName===process&&rule.adapterIds.includes(a.id)))issues.push('流程字段适配待核验:'+process);
+ }
+ if(rule.adapterIds.some(id=>!adapters.some(a=>a.id===id)))issues.push('包含不存在的字段适配器');
+ return issues;
+}
+module.exports={fail,validateRule,publicationIssues};
diff --git a/src/modules/order-rules/window.cjs b/src/modules/order-rules/window.cjs
new file mode 100644
index 0000000..1a941e0
--- /dev/null
+++ b/src/modules/order-rules/window.cjs
@@ -0,0 +1,40 @@
+'use strict';
+const {dayPolicy,nextSlots}=require('../../shared/schedule.cjs');
+const invalid=message=>{throw Object.assign(new Error(message),{status:400});};
+const DAY=86400000,OFFSET=8*3600000;
+const dayOf=date=>new Date(+date+OFFSET).toISOString().slice(0,10);
+const at=(day,time)=>new Date(day+'T'+time+':00+08:00').toISOString();
+function timesOf(schedule){
+ if(!Array.isArray(schedule?.times)||schedule.times.length!==2||schedule.times.some(t=>typeof t!=='string'||! /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(t))||schedule.times[0]===schedule.times[1])invalid('请配置两个不同的发送时间。');
+ return [...schedule.times].sort();
+}
+function windowForCutoff(cutoff,schedule,overrides=[]){
+ if(typeof cutoff!=='string'||!/(?:Z|[+-]\d{2}:\d{2})$/.test(cutoff)||!Number.isFinite(Date.parse(cutoff)))invalid('发送截止时间必须包含时区。');
+ const date=new Date(cutoff),day=dayOf(date),times=timesOf(schedule),end=date.toISOString();
+ if(!dayPolicy(day,schedule,overrides).send)invalid('该日期未安排发送。');
+ const index=times.findIndex(time=>at(day,time)===end);if(index<0)invalid('截止时间必须与已配置的发送时点一致。');
+ let start=index?at(day,times[index-1]):at(day,'00:00');
+ if(index===0){
+ const prior=dayOf(new Date(+date-DAY));
+ const monday=new Date(day+'T00:00:00Z').getUTCDay()===1;
+ if(monday||!dayPolicy(prior,schedule,overrides).send){
+ let found=false;
+ for(let back=1;back<=370;back++){
+ const previous=dayOf(new Date(+date-back*DAY));
+ if(dayPolicy(previous,schedule,overrides).send){start=at(previous,times.at(-1));found=true;break;}
+ }
+ if(!found)invalid('找不到上个工作日的发送截止时间,请检查业务日历。');
+ }
+ }
+ const fmt=value=>new Intl.DateTimeFormat('zh-CN',{timeZone:'Asia/Shanghai',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',hour12:false}).format(new Date(value));
+ return {start,end,label:fmt(start)+' 至 '+fmt(end)+'(北京时间,含起点、不含终点)',startInclusive:true,endInclusive:false};
+}
+function upcomingWindow(now,schedule,overrides=[]){
+ const times=timesOf(schedule),day=dayOf(now);
+ const due=times.map(t=>at(day,t)).find(t=>+now-Date.parse(t)>=0&&+now-Date.parse(t)<=60000);
+ const cutoff=due&&dayPolicy(day,schedule,overrides).send?due:nextSlots(schedule,now,1,overrides)[0];
+ if(!cutoff)return null;
+ return {...windowForCutoff(cutoff,schedule,overrides),available:Boolean(due&&cutoff===due)};
+}
+function inWindow(receivedAt,window){const value=Date.parse(receivedAt);return Number.isFinite(value)&&value>=Date.parse(window.start)&&valueitem.id),ids);
});
+
+test('rule preview can configure IMAP history without enabling polling or SMTP',async t=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'history-preview-'));
+ const runtime=await startPreview({stateDir:dir,port:0,mailHistory:true});
+ t.after(async()=>{await runtime.close();fs.rmSync(dir,{recursive:true,force:true});});
+ const base='http://127.0.0.1:'+runtime.server.address().port;
+ const login=await fetch(base+'/api/preview-login',{method:'POST',headers:{Origin:base,'Content-Type':'application/json'},body:'{}'});
+ const cookie=login.headers.get('set-cookie').split(';')[0];
+ const result=await fetch(base+'/api/mail',{headers:{Cookie:cookie}});
+ assert.equal(result.status,200);assert.equal((await result.json()).historyOnly,true);
+ assert.equal(runtime.mail.timer,undefined);assert.equal(runtime.mail.startTimer,undefined);
+});
diff --git a/tests/mail/history-ui.test.cjs b/tests/mail/history-ui.test.cjs
new file mode 100644
index 0000000..e755aad
--- /dev/null
+++ b/tests/mail/history-ui.test.cjs
@@ -0,0 +1,21 @@
+'use strict';
+const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path');
+const {startPreview}=require('../../scripts/preview.cjs');const {loadPlaywright,browserOptions}=require('../../src/platform/browser.cjs');
+test('history UI saves IMAP-only credentials locally, explicitly queries sent mail and displays escaped evidence',async t=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'history-ui-'));const runtime=await startPreview({stateDir:dir,port:0,mailHistory:true});let browser;
+ t.after(async()=>{await browser?.close();await runtime.close();fs.rmSync(dir,{recursive:true,force:true});});
+ let connects=0;
+ const raw=Buffer.from('From: sender@example.test\r\nTo: orders@example.test\r\nSubject: Test notice\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n
Huizhou evidence');
+ runtime.mail.imapFactory=()=>({mailbox:{uidValidity:1n},on(){},async connect(){connects++;},async list(){return [{path:'Sent',specialUse:'\\Sent'}];},async getMailboxLock(_path,opts){assert.equal(opts.readOnly,true);return {release(){}};},async search(){return [1];},async fetchOne(uid,q){return q.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Test notice'}};},async logout(){},close(){}});
+ browser=await loadPlaywright().chromium.launch(browserOptions());const page=await browser.newPage();const requests=[];page.on('request',r=>requests.push(r.url()));
+ await page.goto('http://127.0.0.1:'+runtime.server.address().port+'/#mail');await page.getByRole('button',{name:'进入演示空间',exact:true}).click();
+ await page.getByRole('button',{name:'添加只读邮箱',exact:true}).click({timeout:5000});
+ for(const [label,value]of [['邮箱名称','历史核对'],['邮箱地址','orders@example.test'],['IMAP 服务器','imap.example.test'],['IMAP 登录账号','orders@example.test'],['IMAP 授权码','History-123']])await page.getByLabel(label,{exact:true}).fill(value);
+ await page.getByRole('button',{name:'保存只读邮箱',exact:true}).click();await page.getByText('只读邮箱已保存。',{exact:true}).waitFor();assert.equal(connects,0);
+ await page.getByRole('button',{name:'连接并列出已发送文件夹',exact:true}).click();await page.getByLabel('已发送文件夹',{exact:true}).selectOption('Sent');
+ await page.getByRole('button',{name:'查询已发送邮件',exact:true}).click();await page.getByRole('button',{name:'查看邮件',exact:true}).click();
+ await page.getByText('
Huizhou evidence',{exact:true}).waitFor();
+ assert.equal(requests.some(r=>r.startsWith('https://tracker.example.test')),false);assert.equal(await page.getByRole('button',{name:/发送测试/}).count(),0);
+ assert.equal(runtime.mail.store.channels()[0].smtp.hasPassword,false);
+ await page.setViewportSize({width:390,height:844});assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true);
+});
diff --git a/tests/mail/history.test.cjs b/tests/mail/history.test.cjs
new file mode 100644
index 0000000..fad5cbf
--- /dev/null
+++ b/tests/mail/history.test.cjs
@@ -0,0 +1,41 @@
+'use strict';
+const {test}=require('node:test');const assert=require('node:assert/strict');
+const {MailService}=require('../../src/modules/mail/service.cjs');
+const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
+const {MailStore}=require('../../src/modules/mail/store.cjs');
+const raw=Buffer.from('From: sender@example.test\r\nTo: orders@example.test\r\nCc: factory@example.test\r\nSubject: Order notice\r\nDate: Sun, 18 Oct 2026 10:00:00 +0800\r\nMessage-ID: \r\nContent-Type: text/plain; charset=utf-8\r\n\r\nOrder body');
+function fixture(){
+ const calls=[],store={channelSecret:()=>({version:1,imap:{}}),guard(){}};
+ const client={mailbox:{uidValidity:9n},on(){},async connect(){},async logout(){},close(){},async list(){return [{path:'Sent',specialUse:'\\Sent',flags:new Set()},{path:'INBOX',flags:new Set()}];},async getMailboxLock(folder,options){calls.push({folder,...options});return {release(){}};},async search(query,options){calls.push({query,...options});return [1,2,3];},async fetchOne(uid,query,options){calls.push({uid,query,...options});return query.source?{source:raw}:{uid,size:raw.length,envelope:{subject:'Order notice',date:new Date('2026-10-18T02:00:00Z'),to:[{address:'orders@example.test'}]}};}};
+ const service=new MailService({store,imapFactory:()=>client,smtpFactory:()=>{throw Error('SMTP must not be used');}});
+ return {service,calls,client};
+}
+test('an IMAP-only history account stores no SMTP credential and rejects all sending or template polling',async t=>{
+ const dir=fs.mkdtempSync(path.join(os.tmpdir(),'history-account-')),store=new MailStore(dir);
+ const service=new MailService({store,smtpFactory:()=>{throw Error('SMTP should be unreachable');}});
+ t.after(async()=>{await service.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});});
+ const account=store.saveChannel({readOnly:true,name:'历史格式核对',email:'orders@example.test',imap:{host:'imap.example.test',port:993,security:'tls',user:'orders@example.test',password:'History-only-123'}});
+ assert.equal(account.readOnly,true);assert.equal(account.enabled,false);assert.equal(account.smtp.hasPassword,false);
+ assert.doesNotMatch(JSON.stringify(store.channels()),/History-only-123/);
+ for(const work of [()=>service.verify(account.id),()=>service.poll(account.id),()=>service.sendTest(account.id,'any')])await assert.rejects(work(),e=>e.status===409&&e.message.includes('只读'));
+});
+test('sent history is bounded, read-only, does not download bodies during search, and keeps mailbox cursor untouched',async()=>{
+ const {service,calls}=fixture();
+ const result=await service.history('channel',{action:'search',folder:'Sent',since:'2026-10-01',before:'2026-10-20',subject:'订单',limit:2});
+ assert.equal(result.messages.length,2);assert.equal(result.truncated,true);assert.deepEqual(result.messages.map(m=>m.uid),[3,2]);
+ assert.ok(calls.some(c=>c.folder==='Sent'&&c.readOnly===true));
+ assert.ok(calls.some(c=>c.query?.sentSince instanceof Date&&c.query.subject==='订单'));
+ assert.ok(!calls.some(c=>c.query?.source));
+ const detail=await service.history('channel',{action:'message',folder:'Sent',uid:3,uidValidity:result.uidValidity});
+ assert.equal(detail.text,'Order body');assert.equal(detail.to[0].address,'orders@example.test');assert.equal(detail.cc[0].address,'factory@example.test');
+ assert.deepEqual(detail.attachments,[]);
+});
+test('history rejects wrong folder, stale UID epoch, oversized messages and unbounded dates without leaking provider errors',async()=>{
+ const {service,client}=fixture();
+ for(const input of [{action:'search',folder:'INBOX',since:'2026-10-01',before:'2026-10-20'},{action:'search',folder:'Sent',since:'2020-01-01',before:'2026-10-20'},{action:'search',folder:'Sent',since:'2026-02-31',before:'2026-03-05'}])await assert.rejects(service.history('c',input),e=>e.status===400);
+ await assert.rejects(service.history('c',{action:'message',folder:'Sent',uid:3,uidValidity:'8'}),e=>e.status===409);
+ client.fetchOne=async()=>({size:20*1024*1024});
+ await assert.rejects(service.history('c',{action:'message',folder:'Sent',uid:3,uidValidity:'9'}),e=>e.status===413);
+ client.connect=async()=>{throw Error('secret password');};
+ await assert.rejects(service.history('c',{action:'folders'}),e=>!e.message.includes('secret password'));
+});
diff --git a/tests/mail/mail-http.test.cjs b/tests/mail/mail-http.test.cjs
index ce0420f..e65a425 100644
--- a/tests/mail/mail-http.test.cjs
+++ b/tests/mail/mail-http.test.cjs
@@ -13,3 +13,18 @@ test('template preview is isolated, source attachments downloadable and confirma
assert.equal((await call('/api/mail/templates/'+d.id+'/confirm',{version:1,subject:d.subject,scope:'',useText:false},reader)).status,403);assert.equal((await call('/api/mail/templates/'+d.id+'/confirm',{version:1,subject:d.subject,scope:'',useText:false},admin)).status,200);assert.equal(mailStore.active(c.id,'').id,d.id);
assert.equal((await call('/api/mail/templates/'+d.id+'/source',undefined,reader)).status,403);const source=await call('/api/mail/templates/'+d.id+'/source',undefined,admin);assert.equal(await source.text(),raw.toString());
});
+
+test('history access requires administrator and same origin; isolated history mode rejects SMTP and polling routes',async t=>{
+ const {mail,mailStore,call,login}=await setup(t);mail.historyOnly=true;
+ const admin=await login('admin'),reader=await login('reader');
+ const saved=await call('/api/mail/channels',{readOnly:true,name:'历史核对',email:'orders@example.test',imap:config.imap},admin);
+ assert.equal(saved.status,201);const account=await saved.json();
+ const url='/api/mail/channels/'+account.id;
+ assert.equal((await call(url+'/history',{action:'folders'},reader)).status,403);
+ assert.equal((await call(url+'/history',{action:'folders'},admin,'https://evil.test')).status,403);
+ for(const action of ['verify','poll','test'])assert.equal((await call(url+'/'+action,{},admin)).status,409);
+ assert.equal((await call('/api/mail/channels',config,admin)).status,409);
+ assert.equal(mailStore.channels().length,1);
+ mail.imapFactory=()=>({on(){},async connect(){},async list(){return [{path:'Sent',specialUse:'\\Sent'}];},async logout(){},close(){}});
+ const folders=await call(url+'/history',{action:'folders'},admin);assert.equal(folders.status,200);assert.deepEqual((await folders.json()).folders,[{path:'Sent',name:'Sent'}]);
+});
diff --git a/tests/order-rules/batches.test.cjs b/tests/order-rules/batches.test.cjs
new file mode 100644
index 0000000..ba03c1c
--- /dev/null
+++ b/tests/order-rules/batches.test.cjs
@@ -0,0 +1,200 @@
+'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 crypto=require('node:crypto');
+const {transition}=require('../../src/modules/order-rules/state.cjs');
+const {buildBatch}=require('../../src/modules/order-rules/batch.cjs');
+
+const cutoff='2026-10-19T01:00:00.000Z';
+function rule(patch={}){return {id:'r1',version:1,categoryId:'notice',name:'订单通知',subjectPrefix:'订单通知',intro:'请处理以下订单。',signature:'业务部',to:['USER@example.com','user@example.com'],cc:['copy@example.com','USER@example.com'],attachPdf:true,archiveDirectory:'\\\\nas\\orders',...patch};}
+function order(id='1',patch={}){return {id,event:{orderNo:`SO-${id}`,brief:'型号 ',receivedAt:'2026-10-19T00:00:00.000Z'},ruleSnapshot:rule(),archive:{archivedAt:'2026-10-19T00:30:00.000Z',files:[{name:`SO-${id}.pdf`,path:`\\\\nas\\orders\\SO-${id}.pdf`,sha256:'a'.repeat(64),size:100,kind:'pdf'}]},...patch};}
+
+test('state actions enforce archive, pending and batch progression without skipping evidence stages',()=>{
+ assert.equal(transition('order','identified','prepare'),'preparing');
+ assert.equal(transition('order','preparing','archive'),'archived');
+ assert.equal(transition('order','archived','queue'),'pending');
+ assert.equal(transition('order','pending','batch'),'batched');
+ assert.equal(transition('order','batched','sent'),'sent');
+ assert.throws(()=>transition('order','identified','sent'),{status:409});
+ assert.throws(()=>transition('order','blocked','sent'),{status:409});
+ assert.throws(()=>transition('batch','failed','send'),{status:409});
+ assert.throws(()=>transition('batch','unknown','send'),{status:409});
+ assert.equal(transition('batch','prepared','send'),'sending');
+ assert.equal(transition('batch','sending','unknown'),'unknown');
+ assert.equal(transition('batch','unknown','resolve_sent'),'sent');
+ assert.equal(transition('batch','unknown','retry'),'cancelled');
+});
+
+test('batch includes every order above 200 with subject numbers and normalized independent recipients',()=>{
+ const orders=Array.from({length:205},(_,i)=>order(String(i+1)));
+ const batch=buildBatch(rule(),orders,cutoff);
+ assert.equal(batch.orderIds.length,205);
+ assert.equal(batch.attachments.length,205);
+ assert.match(batch.subject,/SO-1/);assert.match(batch.subject,/SO-205/);
+ assert.deepEqual(batch.to,['user@example.com']);assert.deepEqual(batch.cc,['copy@example.com']);
+ assert.equal(batch.cutoff,cutoff);
+ orders[0].archive.files[0].name='mutated';orders[0].event.orderNo='mutated';
+ assert.equal(batch.attachments[0].name,'SO-1.pdf');assert.equal(batch.orderNos[0],'SO-1');
+});
+
+test('mail keeps intro signature and escaped summaries with blue clickable UNC evidence',()=>{
+ const batch=buildBatch(rule({intro:'<团队>',signature:'研发 & 业务'}),[order()],cutoff);
+ assert.match(batch.text,/<团队>/);assert.match(batch.text,/研发 & 业务/);
+ assert.match(batch.html,/<script>/);assert.doesNotMatch(batch.html,/