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

@@ -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.