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

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

No files matched your search

+57
View File
@@ -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表单结构,其余需补充适配。若只验证一个流程,可明确缩小适用流程范围。
未入批次的任务可由管理员填写依据后重新核对,应用当前规则并清除旧归档准备结果。已发送或已固定批次不会被规则修改覆盖。
## 标题生成邮件正文
标题按每个“订单号:”拆成独立段落,只保留订单号、机芯号、产品型号、客户简称、总数量、订单类别,去除客户等级、毛利、订单类型和业务模式。中文冒号、换行和`<br>`可识别;第二段`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检查和测试发信,不启动定时收信服务。
@@ -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.
@@ -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.