diff --git a/docs/field-mappings-guide.md b/docs/field-mappings-guide.md
index f0e3a12..09c7dc5 100644
--- a/docs/field-mappings-guide.md
+++ b/docs/field-mappings-guide.md
@@ -2,18 +2,20 @@
入口:业务设置 → 字段映射。管理员低频维护,日常人员查看结果即可。
-1. 在左侧选流程和表单版本。关联分类来自分类规则,没有样本的流程也显示。展开采样区,选择已授权连接和范围:当前发送窗口待办、全部待办(配置采样)、已办/历史(配置采样)。后两者只补字段证据,旧订单不加入通知队列。列表15分钟有效,采集前重新核对所选流程、版本及身份。
-2. 选择真实样本,核对节点、流水号、接收时间和完整标题。流程版本等元数据只读。字段下拉显示中文标签和实际值,支持搜索;同名候选仅作提示,管理员仍需选择确认。技术路径折叠显示。
+1. 搜索已采集订单(标题、流水号或已能确定的主订单号),选择后自动定位左侧实际流程/版本。默认已采集待办,可切换历史;左侧仍显示未采集版本。也可展开“从 BPM 选择”,选授权连接后只读采集;默认全部待办配置采样,历史必须主动选择。实时列表只搜索已读取的标题/流水号,不能搜索尚未采集的表单值。列表15分钟有效,采集前重新核对版本、身份及连接。
+2. 选单后自动显示主订单、0数量、客户等实际值,以及全部标题订单。优先复用同流程/版本草稿,其次唯一生效配置,最后采用当前真实字段唯一标签;已有草稿中的空项不会自动补齐。不依赖模型、不借其他版本或参考配置兜底。多个同名候选在业务项下选择;完整字段搜索及技术路径收进“调整字段对应(高级)”,展开才读取全部字段。
3. 主订单号必须对应表单明确字段。客户、数量、日期、更改原因等按实际需要对应;数量与金额分开。摘要固定按标题订单号拆段,HA订单也保留,不需选择表单摘要。
-4. 保存草稿后点击检查,对照原始标题查看主订单、全部标题订单和各分类PDF文件名。草稿保存不会影响当前生效映射。修改样本或字段后,旧检查立即失效。
+4. 选单与预览只读,不产生草稿版本、检查凭据、执行任务或邮件;只有调整来源才标为未保存。显式保存草稿后点击检查,对照原始标题查看主订单、全部标题订单和各分类PDF文件名。草稿保存不会影响当前生效映射。修改样本或字段后,旧检查立即失效;预览通过不能代替服务端检查。
5. 核对受影响分类,勾选确认后点击“确认生效”。服务端再次核对版本、采集证据和关联分类上下文;之后关联已发布分类暂停,需到分类规则第04步重新检查并发布。已有冻结批次保持原内容。
状态包括未采集、待配置、待检查、检查通过、检查未通过、已核验、版本变化。参考配置仅供理解,不代表已核验配置,不允许直接启用真实分类。未知版本须重新采集配置。
-失败会保留输入。若保存成功但刷新失败,页面分别提示两个结果;先刷新核实持久状态。写入超时只查询状态,不自动重试。采集明确失败后可再次读取;结果不明时保留操作标识以核实同次操作。
+失败会保留输入。若保存成功但刷新失败,页面分别提示两个结果。保存/检查/生效响应丢失时,先查询持久状态并核对本次操作标识、版本、样本和来源;无法确认则禁用重复提交,刷新核对。旧检查不能冒充新请求成功。采集明确失败后可再次读取;结果不明时保留操作标识。
新写入接口分为 field-mappings/draft、check、activate,携带当前草稿版本与幂等标识。旧 adapters 写入仅生成待检查草稿,不能直接标为已核验;旧字符串路径可读取为表单来源。
+只读入口为 `GET field-samples/catalog` 和 `POST field-mappings/propose`。目录先按连接授权,再搜索及稳定游标分页;提案每次从服务端重取所选证据,不接受客户端字段值或元数据。页面初次读取 `fields?view=directory` 只取覆盖/操作摘要,不带完整表单或旧检查实际值;高级区沿用完整 fields 接口。操作员和只读成员只能看有权连接的证据,实时采样与配置写入仍仅管理员可用。
+
采集及检查不会发信、归档或办理节点。正式自动通知仍暂停;真实类别、字段、存储、邮箱及预览完成现场核验后再另行启用。
历史样本显示实际流程版本;历史接口未提供办理节点及通知接收时间,页面使用“历史查看(未提供办理节点)”和“流程发起时间”。历史证据可检查字段对应,不能用于分类规则的真实通知节点发布检查。若文件名采用接收时间,历史检查中的日期只是发起时间示例,正式执行仍须验证真实待办接收时间。
diff --git a/docs/order-driven-configuration-verification-2026-10-20.md b/docs/order-driven-configuration-verification-2026-10-20.md
new file mode 100644
index 0000000..bf3dbbc
--- /dev/null
+++ b/docs/order-driven-configuration-verification-2026-10-20.md
@@ -0,0 +1,59 @@
+# 真实订单驱动配置:代码与隔离验收
+
+日期:2026-10-20(北京时间)。开发目录为 `C:/Users/ABS/.codex/worktrees/modular-refactor/Order Notification Automation`,分支 `codex/modular-refactor`;基线 `d4070e0`。本轮交付代码,正式服务更新不在范围内。原 Z 盘源码、正式账号/数据库/加密身份及正式服务均未更新;不发送真实邮件、不办理 BPM 节点、不批量生效正式映射或发布正式分类。
+
+## 交付行为
+
+| 操作 | 实际结果与边界 |
+|---|---|
+| 搜索/选择真实订单 | 分类页和字段页共用授权证据选择器;自动带流程、节点、版本及当前订单实际值。默认已采集待办,实时读取默认配置采样;历史需主动选择。 |
+| 自动识别 | 同版本草稿 → 唯一生效 → 当前字段唯一标签。草稿空项不补齐,参考配置不授权,未知版本不沿用其他版本;同名主订单提供实际候选,0数量合法,泛称零部件数量及金额不误配。 |
+| 历史证据 | 节点显示未提供,时间标为流程发起;只能核字段,无节点候选、分类发布凭据、执行任务或邮件。已有历史占位配对提示修正。 |
+| 确认范围 | 选择本身不改规则;显式加入精确流程节点配对,去重且保留已有范围、收件人、模板、目录及附件要求。其他类别冲突列出修复入口。 |
+| 只读预览 | `propose` 从服务端重取采样证据,不接受客户端字段值/元数据。采用当前未保存的日期、目录、模板及主题;未确认配对仅候选。`publishEvidence` 恒为 false,状态前后深比较无写入。 |
+| 字段配置 | 默认核对中文业务值,歧义可直接选择;高级区按需读取当前样本完整字段。保存、检查、确认生效是三个独立动作;预览不能解锁生效。分类页可就地维护。 |
+| 同步与恢复 | 字段生效后合并服务端规则版本及适配器,保留未保存输入;同字段并发修改列出冲突并拦截保存,逐项保留页面值或采用服务器值。保存与刷新失败分别反馈;响应丢失核对同次操作标识,不把旧 check 冒充新请求。 |
+| 复用与执行 | 只保存来源方法,下一订单读取自身值;映射更新暂停关联发布并废弃旧检查,冻结批次深比较不变。15类分类、窗口、归档和受控发送引擎保持原入口。 |
+
+## 接口与权限
+
+`GET /api/order-rules/field-samples/catalog` 只返摘要,先按连接权限过滤,再搜索、精确流程筛选和分页。排序为采集时间倒序、ID升序,游标使用排他排序键边界;新增样本不扰乱后续页,旧游标不能绕过变化后的权限。默认20、上限50,严格校验查询及游标;标题按文本转义。
+
+`POST /api/order-rules/field-mappings/propose` 供三个角色按连接权限读取,非管理员提交来源/规则草稿覆盖返回403;未知参数400、匿名401、无权/禁用连接403、缺样本404、规则版本变化409。草稿/检查/生效和实时采样仍仅管理员可用。
+
+`GET /api/order-rules/fields?view=directory` 是页面初次加载的摘要视图,去除完整表单、HTML、旧检查实际值和适配器内的样本。高级区沿用原完整 fields 接口;两种视图均在原连接授权之后返回。共享推荐、纯识别检查及效果示例均不进入运行 registry,不写试运行凭据。
+
+ZCode 项目资源更新为1.1.0,页面和准备卡片复用同一提案/推荐服务。模型只收到原有安全摘要与固定卡片;没有安装个人技能或开放原生工具。未配置模型时不声称已完成真实模型对话。
+
+## 验收证据
+
+所有测试使用临时 stateDir、合成订单及假 BPM;邮件链路仅连接 `127.0.0.1` 本地 SMTP。没有使用正式邮箱或真实 BPM 提交接口。
+
+专项命令(日志位于忽略目录):
+
+```powershell
+node --test --test-concurrency=1 tests/assistant/field-skill.test.cjs tests/app/order-execution-integration.test.cjs tests/order-rules/order-driven-mapping-ui.test.cjs tests/order-rules/order-driven-rules-ui.test.cjs tests/order-rules/recognition-proposal.test.cjs tests/order-rules/sample-catalog.test.cjs tests/order-rules/field-samples.test.cjs
+```
+
+本次专项:38通过、0失败、0跳过,退出码0,日志 `output-order-driven-acceptance.log`。后续补充“保存后刷新提案依据/版本”回归,最终统计见下方全量结果。
+
+| 覆盖 | 证据 |
+|---|---|
+| 推荐、实际值复用、15类、主订单/HA/0数量、日期及配置冲突 | recognition-proposal、field-mappings、assistant/field-skill |
+| 三角色授权、禁用连接、分页新增/权限变化、未知字段、游标及越权覆盖 | sample-catalog、field-samples |
+| 搜索/清空/筛选/分页/取消、转义、迟到响应、懒加载字段 | sample-picker-ui;规则取消选择同时清空正式检查选单 |
+| 管理员、操作员、只读成员;桌面/390px、快速换单、真实会话失效、离页保护 | order-driven-mapping-ui、order-driven-rules-ui;旧页面/横栏/前进后退由现有导航及工作台用例回归 |
+| 草稿、检查、生效、分类发布分离;并发三方合并/冲突解决;写入响应丢失/旧检查拒绝 | order-driven-mapping-ui、order-driven-rules-ui、field-mapping-ui |
+| 真实 Chromium PDF、文件大小/SHA256读回、本地 SMTP、新单自身值、任务去重及冻结不变 | app/order-execution-integration;原 window/batches/execution 覆盖两个时段、周一/公司调休及历史忽略 |
+
+已实际修复并保留回归的边界:冲突解决按钮被后续提案刷新覆盖;同次请求核实误读旧 check;取消选择遗留正式检查样本;保存后仍显示旧推荐依据。原 Excel 导入、模板/目录选择、发布开关、旧地址及权限用例继续运行。
+
+截图均为虚构数据:`output/verification/order-driven-mapping-desktop.png`、`order-driven-mapping-mobile.png`、`order-driven-rules-desktop.png`、`order-driven-rules-mobile.png`;已检查实际截图及390px整页无横向溢出。
+
+## 全量结果与正式边界
+
+最终 `npm ci`、新鲜完整 `npm test`、全部 JS/CJS 语法、文档链接及 `git diff --check` 的结果在完成后补入本节;不以旧435项记录代替。
+
+未部署、未推送、未合并;保留开发分支供验收。本轮没有启动/停止/重启正式守护,没有修改正式自动通知开关或登录。正式暂停要求继续保留;本地 SMTP 链路测试的启用状态仅存在于临时测试库,测试结束关闭并清理。
+
+现场仍须确认15类真实通知节点/字段、目录权限与邮箱/批次预览;已有采样缺口及流程名称歧义不能用合成用例或猜别名补齐。惠州额外通知未启用。正式更新须用户另行安排,届时再核实实际源码目录、停服一致性备份、原登录、双端口及暂停状态;本轮没有执行这些部署动作。
diff --git a/docs/order-rules-guide.md b/docs/order-rules-guide.md
index 23362bf..e639e77 100644
--- a/docs/order-rules-guide.md
+++ b/docs/order-rules-guide.md
@@ -22,10 +22,12 @@ Excel 15 类已建立。左侧分类卡片显示流程数、收件人数、待
右侧分四步:
-1. **哪些订单归到这里**:从 BPM 流程和节点成对选择,任一完整配对命中即可。旧版数组规则仍保持原组合含义。
-2. **自动识别 BPM 订单信息**:系统自动关联已有识别配置,展示缺失的流程。未知版本和缺少信息会受阻;程序字段对应仅在“字段映射”维护。
-3. **归类后怎样处理**:选择已确认的邮件模板、已配置存储服务器及服务器内文件夹。支持浏览子目录、返回上级、使用当前文件夹;读取失败保留输入。收件人、抄送、日期和 PDF 附件要求仍按类别维护。旧目录和旧模板关联保留,不猜测服务器或类别。
-4. **检查订单识别结果**:选取服务器已从 BPM 采集的真实订单,展示中文订单信息、标题拆分、归档路径和邮件预览。不提供 JSON 编辑,不创建订单、文件、批次,不连接发信或办理节点。
+1. **选择对应的 BPM 订单**:搜索已采集证据,或从授权 BPM 连接只读读取一单,自动带出真实流程、节点、版本。默认当前类别关联流程,可切换其他流程。新配对必须点击“将此流程与节点加入当前类别”,仅追加且去重;原配对及收件人/目录/模板保留。原逐行维护收进“调整匹配范围”,旧版数组语义不变。
+2. **核对自动识别的信息**:显示实际业务值,歧义项直接给候选;管理员可“在此配置字段识别”,分别保存、检查、确认生效,不必跳页。未知版本、路径消失、标题冲突和多个生效配置会受阻;0数量合法。历史只核字段,不能提供触发节点或发布凭据;已有历史占位配对需人工修正。
+3. **设置通知与归档**:选择已确认的邮件模板、已配置存储服务器及服务器内文件夹。支持浏览子目录、返回上级、使用当前文件夹;读取失败保留输入。收件人、抄送、日期和 PDF 附件要求仍按类别维护。选单不能改变这些设置。
+4. **查看处理结果**:只读提案采用当前页面尚未保存的配对、日期、主题、目录和模板生成示例,明确标记“尚未保存/未执行”。字段可用但尚未加入配对时只显示候选;其他类别冲突列出入口。正式“检查识别结果”仍独立使用已核验映射,只有当前已保存草稿及真实通知待办才能产生发布凭据。
+
+字段生效后同步服务端规则版本与适配器;未保存的收件人等输入保留。若页面和服务器同时修改同一字段,列出冲突并拦截保存,逐项选择保留页面值或采用服务器值。规则和字段草稿分别受离页保护;搜索和只读预览不算修改。快速换单、换类别或离页后,旧响应不覆盖当前页面。
保存只生成草稿,旧发布版本继续服务。只有当前已保存规则结合真实采集订单检查通过、业务配置完整且无启用冲突才能发布。检查单个订单不等于全部流程版本、真实目录与邮箱已完成现场验收。新表单需在字段映射核验后再发布。更新已使用映射会暂停关联分类,须重新检查发布,详见[字段映射说明](field-mappings-guide.md)。
diff --git a/docs/web-action-inventory.md b/docs/web-action-inventory.md
index bc15559..641475d 100644
--- a/docs/web-action-inventory.md
+++ b/docs/web-action-inventory.md
@@ -39,6 +39,12 @@
| R03 字段映射目录、搜索/筛选、版本/样本切换 | 管理员编辑,其他角色仅看授权样本 | 流程版本目录及四步配置;未采集也显示 | 未保存保护、390px、离页失效;field-mapping-ui | 已验证可用 |
| R16 读取待办/历史列表、采集所选表单 | 管理员及已授权连接;范围显式选择 | 窗口待办/全部待办配置采样/历史配置采样;独立加密证据,不归档/发信/办理 | 身份/节点/版本/过期变化拒绝,历史保留来源与发起时间;field-samples/history-client/field-mapping-ui | 已验证可用 |
| R17 保存草稿、检查、确认使用 | 管理员;真实样本、版本与幂等键 | 服务端识别证据及生效版本,关联分类暂停需重新检查 | 旧凭据/并发409、输入保留、保存刷新分别反馈;field-mappings/field-mapping-ui | 已验证可用 |
+| R18 搜索已采集订单、清空、流程/来源筛选、上一页/下一页、重新读取 | 三角色;仅可用连接的授权证据 | 摘要目录;真实来源/节点/版本/时间;游标按采集时间和ID稳定分页 | 搜索不写配置、权限变化后旧游标失效、空结果和失败重试、键盘及390px;sample-catalog/sample-picker-ui | 隔离验收 |
+| R19 选择/取消订单、从BPM读取列表、读取并选择 | 三角色可选授权证据;实时采样仅管理员 | 自动识别当前样本;默认配置采样,历史主动选择;取消不采用结果,不承诺取消服务端采集 | 快速换单、迟到响应、401、15分钟失效、重复读取幂等;order-driven-mapping-ui/field-samples | 隔离验收 |
+| R20 选择歧义候选、展开高级区、搜索真实字段、调整来源 | 仅管理员可改;当前真实样本 | 只改变页面来源、旧检查立即失效;高级区按需取完整字段 | 两同名字段、0数量、金额/数量区分、来源消失、字段加载失败保留来源;recognition-proposal/sample-picker-ui/order-driven-rules-ui | 隔离验收 |
+| R21 确认加入流程节点、调整配对、查看冲突类别、返回 | 管理员改配对;三角色查看 | 仅显式确认追加精确一对,去重且保留原范围;历史无触发节点 | 不从知会状态猜节点、已有历史占位受阻、跨类别列出冲突;order-driven-rules-ui/workbench-ui | 隔离验收 |
+| R22 分类内就地保存/检查/生效字段、同步规则版本、逐项解决并发冲突 | 管理员;三个独立写入动作 | 规则/映射分别记录未保存;合并非冲突输入,同字段冲突拦截保存;不自动发布 | 保留收件人/目录等输入、旧检查失效、旧冻结批次不变;order-driven-rules-ui/field-mappings/order-execution-integration | 隔离验收 |
+| R23 当前草稿纯预览、正式检查、写入结果核实 | 三角色看提案;检查/配置写入沿用原权限 | 纯提案采用尚未保存的日期/模板/目录并标为未执行;只有正式trial写发布凭据 | 响应丢失后核对同次操作标识/版本/样本,不把旧check当新操作成功;recognition-proposal/order-driven-mapping-ui | 隔离验收 |
| R04 发布、暂停规则 | 管理员;当前草稿真实试跑、完整配置、无冲突 | 发布快照与审计 | 演示样本不能发布;store/web | 已验证可用 |
| R05 待办扫描、查看进度与重试 | 管理员/连接负责人;有效会话;重试以服务器canRetry为准 | 持久扫描状态/计数/错误、任务与样本、受阻原因,刷新保留恢复依据 | 版本、幂等、重启恢复、零任务扫描失败、非负责人拒绝;execution/web-closure-review-ui | 已验证可用 |
| R06 导出、归档、读回、入队 | 执行器;已验证规则、存储 | 文件路径/大小/SHA256与订单状态 | 不可写、文件变化、缺PDF阻塞;closure-providers/execution | 已验证可用 |
diff --git a/docs/zcode-field-mapping-skill.md b/docs/zcode-field-mapping-skill.md
index d8e4db9..362a949 100644
--- a/docs/zcode-field-mapping-skill.md
+++ b/docs/zcode-field-mapping-skill.md
@@ -1,8 +1,8 @@
# ZCode 的 BPM 样本与字段映射技能
-技能资源随项目部署:`src/modules/assistant/skills/bpm-field-mapping/SKILL.md`,版本1.0.0。加载器只读该固定资源并返回版本和SHA256,不搜索个人技能目录;没有为 Codex 安装技能。每轮 ZCode 对话在可信提示中注入流程指引,助手首页显示加载版本。
+技能资源随项目部署:`src/modules/assistant/skills/bpm-field-mapping/SKILL.md`,版本1.1.0。加载器只读该固定资源并返回版本和SHA256,不搜索个人技能目录;没有为 Codex 安装技能。每轮 ZCode 对话在可信提示中注入流程指引,助手首页显示加载版本。
-管理员可让助手查看缺少的流程样本、采集待办/历史样本或准备字段对应。操作卡分别为 `collect_field_samples`、`collect_history_samples`、`prepare_field_mapping`,模型只提交目标连接或样本ID。服务端负责读取真实字段、保守推荐、保存草稿与统一引擎检查;已有草稿只检查,不覆盖。歧义字段留空,不把数量与金额混用。
+管理员可让助手查看缺少的流程样本、采集待办/历史样本或准备字段对应。操作卡分别为 `collect_field_samples`、`collect_history_samples`、`prepare_field_mapping`,模型只提交目标连接或样本ID。服务端负责读取真实字段、保守推荐、保存草稿与统一引擎检查;已有草稿只检查,不覆盖。与页面共用真实订单提案与推荐模块;已有草稿优先,其次唯一生效配置,最后才是唯一中文标签。歧义时引导页面核对,不补已有草稿空项,不把数量与金额混用。
采集按流程版本去重,逐项持久化进度,失败可尝试同版本其他记录。重启后中断卡不自动重放,应先查看已保存证据;再次采样跳过已有版本。准备草稿的卡片绑定样本摘要和草稿版本,变更后拒绝旧卡片。
diff --git a/src/modules/assistant/field-skill.cjs b/src/modules/assistant/field-skill.cjs
index 5504b92..b3b6dfc 100644
--- a/src/modules/assistant/field-skill.cjs
+++ b/src/modules/assistant/field-skill.cjs
@@ -24,7 +24,7 @@ async function prepare(deps,id,principal,key,guard){
if(!guard||JSON.stringify(current)!==JSON.stringify(guard))throw fail('样本或映射草稿已变化,请重新生成操作卡。',409);
const sample=deps.orderRules.get('capture-samples',id),{mappingId}=require('../order-rules/field-mappings.cjs');
let draft=deps.orderRules.get('field-mapping-drafts',mappingId(sample.processName,sample.processVersion)),issues=[];
- if(!draft){const r=recommend(sample.snapshot.fields);issues=r.issues;if(!r.sources.orderNo)return {status:'needs-selection',issues,link:'#rule-fields'};
+ if(!draft){const proposal=deps.orderRules.proposeMapping({sampleId:id}),r={sources:proposal.mapping.sources,issues:proposal.blockedReasons};issues=r.issues;if(!r.sources.orderNo||proposal.fields.some(f=>f.state==='ambiguous'))return {status:'needs-selection',issues,link:'#rule-fields'};if(!proposal.processVersion||proposal.mapping.basis==='conflict')return {status:'blocked',issues,link:'#rule-fields'};
draft=deps.orderRules.saveMapping({processName:sample.processName,processVersion:sample.processVersion,sampleId:id,sources:r.sources,version:0,idempotencyKey:key+':draft'},principal.user);
}
const check=deps.orderRules.checkMapping({id:draft.id,version:draft.version,sampleId:id,idempotencyKey:key+':check'},principal.user);
diff --git a/src/modules/assistant/skills.cjs b/src/modules/assistant/skills.cjs
index a640289..b689e8d 100644
--- a/src/modules/assistant/skills.cjs
+++ b/src/modules/assistant/skills.cjs
@@ -3,5 +3,5 @@ const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypt
// Only this source-controlled application resource is trusted. No user-provided
// paths or personal/native skill directories are searched.
const text=fs.readFileSync(path.join(__dirname,'skills/bpm-field-mapping/SKILL.md'),'utf8');
-const skill=Object.freeze({id:'bpm-field-mapping',name:'BPM 样本与字段映射',version:'1.0.0',sha256:crypto.createHash('sha256').update(text).digest('hex')});
+const skill=Object.freeze({id:'bpm-field-mapping',name:'BPM 样本与字段映射',version:'1.1.0',sha256:crypto.createHash('sha256').update(text).digest('hex')});
module.exports={projectSkills:()=>[{...skill}],skillPrompt:()=>text};
diff --git a/src/modules/assistant/skills/bpm-field-mapping/SKILL.md b/src/modules/assistant/skills/bpm-field-mapping/SKILL.md
index 3fc95ec..988cd6c 100644
--- a/src/modules/assistant/skills/bpm-field-mapping/SKILL.md
+++ b/src/modules/assistant/skills/bpm-field-mapping/SKILL.md
@@ -1,6 +1,6 @@
---
name: bpm-field-mapping
-version: 1.0.0
+version: 1.1.0
description: 从授权 BPM 待办采集真实证据,辅助配置、检查订单信息识别。
---
@@ -20,8 +20,9 @@ description: 从授权 BPM 待办采集真实证据,辅助配置、检查订
1. 历史证据必须标为 history,节点标为未提供、时间标为流程发起;不能改成 todo。历史映射检查可通过,但分类发布仍须通知待办核验。主订单号必须来自表单明确字段。流程、节点、流水号、接收时间和版本固定来自待办。
2. 通知摘要从标题订单号开始提取,保留全部订单段落,包括 HA 订单;不能用表单摘要代替。表单主订单号必须存在于标题订单号中。
3. 客户、数量、申请日期、更改原因、内容等仅选真实字段目录。数量与金额分别维护;零数量是有效值。文件名使用申请日期时必须检查日期。
-4. 管理员可建议 prepare_field_mapping 卡,targetId 取 fieldMapping.samples 中的样本 ID。服务端只依据唯一字段标签提供候选,保存草稿并调用统一识别检查;歧义时留下缺项。已有草稿只检查,不覆盖。模型不能传路径、脚本、表达式或自造字段值。
-5. 引导管理员到“业务设置 → 字段映射”核对主订单、全部标题段落、文件名、受影响分类,然后勾选确认生效。ZCode 不自动生效或发布分类。生效后相关分类须重新检查发布,冻结批次不变。
+4. 默认引导“选择真实订单 → 自动候选 → 核对差异”。页面与助手共用同一服务:同版本保存草稿优先,其次唯一生效配置,最后才是当前字段唯一标签;不补齐已有草稿中人为留空的可选项。未知版本、多个生效映射、来源消失及同名候选须明确说明,不能猜流程别名或历史节点。
+5. 管理员可建议 prepare_field_mapping 卡,targetId 取 fieldMapping.samples 中的样本 ID。卡片经确认后才准备草稿并检查,歧义时转到页面选择;已有草稿只检查,不覆盖。模型不能传路径、脚本、表达式或自造字段值。选单提案本身不保存,不生成发布凭据。
+6. 引导管理员在字段映射页或分类规则就地面板核对主订单、全部标题段落、文件名及受影响分类,然后勾选确认生效。ZCode 不自动生效或发布分类。生效后相关分类须重新检查发布,冻结批次不变。
## 失败与权限
diff --git a/src/modules/order-rules/recognition-proposal.cjs b/src/modules/order-rules/recognition-proposal.cjs
index bc9ab3a..f043c43 100644
--- a/src/modules/order-rules/recognition-proposal.cjs
+++ b/src/modules/order-rules/recognition-proposal.cjs
@@ -23,14 +23,14 @@ function proposeMapping(store,input){
const recognition=evaluateMapping(store,{id,processName:captured.processName,processVersion:captured.processVersion,version:draft?.version||0,sources},captured,{relatedRules:related});
recognition.publishEvidence=false;
const blockedReasons=[...recognition.issues],warnings=[...(recognition.warnings||[])];
- if(basis==='conflict')blockedReasons.push('同一流程版本存在多个生效映射,请确认唯一配置。');
+ if(active.length>1)blockedReasons.push('同一流程版本存在多个生效映射,请确认唯一配置。');
const history=sample.source==='history',scopeCandidate=sample.source==='todo'&&sample.nodeName&&!/历史查看|未提供办理节点/.test(sample.nodeName)?{processName:captured.processName,nodeName:sample.nodeName}:null;
const conflicts=records.filter(r=>r.id!==record?.id&&(matchesScope(r.draft,sample)||r.published&&matchesScope(r.published,sample))).map(r=>({ruleId:r.id,name:r.draft.name,published:!!(r.published&&matchesScope(r.published,sample))}));
let status=history?'history':rule?matchesScope(rule,sample)?'matched':'candidate':conflicts.length===1?'matched':'none';
if(conflicts.length&&(rule||conflicts.length>1)){status='conflict';blockedReasons.push('流程与节点同时命中其他类别:'+conflicts.map(c=>c.name).join('、'));}
if(rule&&scopesFor(rule).some(s=>/历史查看|未提供办理节点/.test(s.nodeName))){status='conflict';blockedReasons.push('分类含历史占位节点,请在调整匹配范围中修正。');}
if(!captured.processVersion)blockedReasons.push('流程版本未提供,不能复用或生效配置。');
- recognition.valid=recognition.valid&&basis!=='conflict'&&!!captured.processVersion;
+ recognition.valid=recognition.valid&&active.length<=1&&!!captured.processVersion;
const fields=BUSINESS_FIELDS.map(key=>{const source=sources[key]||null,trace=recognition.fieldTrace.find(f=>f.key===key),candidates=recommended.candidates[key]||[],value=trace?.value??null;
let state=!source&&candidates.length>1?'ambiguous':value===null||value===''?'missing':'recognized',reason=null;
if(source?.type==='form'&&!captured.snapshot.fields.some(f=>f.path===source.path)){state='invalid';reason='所选来源字段不存在';}
diff --git a/tests/app/order-execution-integration.test.cjs b/tests/app/order-execution-integration.test.cjs
index 0ddb0dc..ebf8a34 100644
--- a/tests/app/order-execution-integration.test.cjs
+++ b/tests/app/order-execution-integration.test.cjs
@@ -8,14 +8,14 @@ const {FileArea}=require('../../src/modules/storage/files.cjs'),{OrderArchivePro
const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs'),{OrderRuleDispatcher}=require('../../src/modules/order-rules/dispatcher.cjs'),{createDashboard}=require('../../src/app/dashboard.cjs');
test('HTTP todo, captured field binding, real PDF, verified share and loopback SMTP form one persistent chain',async t=>{
- let now=new Date('2026-10-19T02:00:00Z'),web,bpm,smtp,execution,dispatcher,mail,mutations=0,messages=[];
+ let now=new Date('2026-10-19T02:00:00Z'),web,bpm,smtp,execution,dispatcher,mail,mutations=0,messages=[],orderNo='000123';
const dir=await fs.mkdtemp(path.join(os.tmpdir(),'closure-complete-')),dashboard=new Store(path.join(dir,'dashboard')),workspace=new WorkspaceStore(path.join(dir,'workspace')),rules=new RuleStore(path.join(dir,'rules'),{clock:()=>now,schedule:()=>dashboard.settings().schedule}),mailStore=new MailStore(path.join(dir,'mail'));
t.after(async()=>{await dispatcher?.stop();await execution?.stop();await mail?.stop();for(const server of [web,bpm])if(server?.listening)await new Promise(r=>server.close(r));if(smtp)await new Promise(r=>smtp.close(r));rules.close();workspace.close();mailStore.close();await fs.rm(dir,{recursive:true,force:true});});
bpm=http.createServer((req,res)=>{
if(req.url==='/')return res.end('');
- if(req.url.startsWith('/bpm/worklist')||req.url.startsWith('/skyworth/todo/')){res.setHeader('Content-Type','application/json');const v4=req.url.startsWith('/skyworth/');return res.end(JSON.stringify({total:v4?1:0,children:v4?[{taskId:11,processInstanceId:21,processVersion:'fixture-1',processName:'备损订单更改评审',activityName:'订单专员(订单通知书)',startTime:'2026-10-19T09:00:00',serialNum:'S11',processInstanceSubject:'订单号:000123机芯号:TEST客户简称:隔离客户总数量:5',executionPointerId:'http://127.0.0.1:'+bpm.address().port+'/form.aspx?tid=21&pid=11'}]:[]}));}
- if(req.url==='/YZSoft/BPM/XMLService/DataProvider.ashx'&&req.method==='POST'){res.setHeader('Content-Type','application/json');return res.end(JSON.stringify({success:true,Tables:[{TableName:'Order',FormTable:true,Rows:[{Number:'000123',Summary:'隔离更改摘要'}]}]}));}
- if(req.url.startsWith('/form.aspx'))return res.end('
隔离更改订单 ');
+ if(req.url.startsWith('/bpm/worklist')||req.url.startsWith('/skyworth/todo/')){res.setHeader('Content-Type','application/json');const v4=req.url.startsWith('/skyworth/');return res.end(JSON.stringify({total:v4?1:0,children:v4?[{taskId:11,processInstanceId:21,processVersion:'fixture-1',processName:'备损订单更改评审',activityName:'订单专员(订单通知书)',startTime:'2026-10-19T09:00:00',serialNum:'S11',processInstanceSubject:'订单号:'+orderNo+'机芯号:TEST客户简称:隔离客户总数量:0订单号:HA'+orderNo+'机芯号:SECOND客户简称:隔离客户总数量:5',executionPointerId:'http://127.0.0.1:'+bpm.address().port+'/form.aspx?tid=21&pid=11'}]:[]}));}
+ if(req.url==='/YZSoft/BPM/XMLService/DataProvider.ashx'&&req.method==='POST'){res.setHeader('Content-Type','application/json');return res.end(JSON.stringify({success:true,Tables:[{TableName:'Order',FormTable:true,Rows:[{Number:orderNo,Quantity:0,Summary:'隔离更改摘要'}]}]}));}
+ if(req.url.startsWith('/form.aspx'))return res.end('隔离更改订单 ');
mutations++;res.writeHead(403);res.end();
});await new Promise(r=>bpm.listen(0,'127.0.0.1',r));
const manager={run:(_,fn)=>fn(),authorize(){},sessions:new Map(),vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})})},provider=new BpmOrderProvider({manager,allowLocal:true,client:new BpmTodoClient({baseURL:'http://127.0.0.1:'+bpm.address().port+'/',allowLocal:true})});
@@ -28,11 +28,15 @@ test('HTTP todo, captured field binding, real PDF, verified share and loopback S
web=createDashboard({store:dashboard,workspace,orderRules:rules,orderExecution:execution,orderDispatcher:dispatcher,mail,outputDir:dir});await new Promise(r=>web.listen(0,'127.0.0.1',r));const base='http://127.0.0.1:'+web.address().port;let cookie;
const call=async(route,body)=>{const response=await fetch(base+route,{method:body?'POST':'GET',headers:{...(cookie?{Cookie:cookie}:{}),...(body?{'Content-Type':'application/json',Origin:base}:{})},body:body?JSON.stringify(body):undefined});const data=await response.json();assert.ok(response.ok,route+': '+JSON.stringify(data));return {response,data};};
const setup=await call('/api/bootstrap',{username:'admin',password:'Fixture-password-123'});cookie=setup.response.headers.get('set-cookie').split(';')[0];const admin=dashboard.users()[0],connection=workspace.createConnection({name:'隔离连接',owner:'admin'},admin,[admin]);
- await call('/api/order-execution/scan',{connectionId:connection.id,idempotencyKey:'capture'});let fields=(await call('/api/order-rules/fields')).data;const captured=fields.samples[0];assert.ok(captured);
- const adapter=(await call('/api/order-rules/adapters',{sampleId:captured.id,processName:captured.processName,processVersion:captured.processVersion,fields:{orderNo:'Order.Number',brief:'Order.Summary'}})).data;
+ const listing=(await call('/api/order-rules/field-samples/list',{connectionId:connection.id,scope:'configuration',idempotencyKey:'config-list'})).data;
+ const captured=(await call('/api/order-rules/field-samples/capture',{connectionId:connection.id,listId:listing.id,rowId:listing.rows[0].id,idempotencyKey:'config-capture'})).data;
+ const before=rules.all('rules'),catalog=(await call('/api/order-rules/field-samples/catalog')).data;assert.equal(catalog.items[0].id,captured.id);assert.equal(catalog.items[0].fields,undefined);
+ const proposal=(await call('/api/order-rules/field-mappings/propose',{sampleId:captured.id,ruleId:'bs-change',ruleVersion:1})).data;assert.equal(proposal.recognition.valid,true);assert.equal(proposal.recognition.event.quantity,0);assert.match(proposal.recognition.event.brief,/HA000123/);assert.deepEqual(rules.all('rules'),before);assert.deepEqual(rules.all('orders'),[]);assert.deepEqual(rules.all('execution-tasks'),[]);assert.equal(proposal.recognition.publishEvidence,false);
+ const adapter=(await call('/api/order-rules/field-mappings/draft',{sampleId:captured.id,processName:captured.processName,processVersion:captured.processVersion,sources:proposal.mapping.sources,version:0,idempotencyKey:'config-draft'})).data;
const mappingCheck=(await call('/api/order-rules/field-mappings/check',{id:adapter.id,version:adapter.version,sampleId:captured.id,idempotencyKey:'mapping-check'})).data;assert.equal(mappingCheck.valid,true);await call('/api/order-rules/field-mappings/activate',{id:adapter.id,version:adapter.version,checkId:mappingCheck.id,idempotencyKey:'mapping-confirm'});
const current=(await call('/api/order-rules')).data.rules.find(r=>r.id==='bs-change');const saved=(await call('/api/order-rules/rules',{...current,adapterIds:[adapter.id],to:['recipient@example.test'],archiveDirectory:'\\\\fixture-nas\\orders',filenameDate:'receivedAt'})).data;
- assert.equal((await call('/api/order-rules/preview',{sampleId:captured.id})).data.valid,true);await call('/api/order-rules/rules/bs-change/publish',{version:saved.version});
+ assert.equal((await call('/api/order-rules/rules/bs-change/trial',{version:saved.version,sampleId:captured.id})).data.valid,true);await call('/api/order-rules/rules/bs-change/publish',{version:saved.version});
+ orderNo='000456';
await call('/api/order-execution/scan',{connectionId:connection.id,idempotencyKey:'archive'});await call('/api/order-execution/scan',{connectionId:connection.id,idempotencyKey:'duplicate'});assert.equal((await fs.readdir(share)).length,1);assert.equal(mutations,0);
const order=rules.all('orders')[0],evidence=order.archive.files[0],bytes=await archive.read(evidence);assert.equal(bytes.subarray(0,5).toString(),'%PDF-');assert.equal(bytes.length,evidence.size);assert.equal(crypto.createHash('sha256').update(bytes).digest('hex'),evidence.sha256);
const channel=mailStore.saveChannel({name:'隔离邮箱',email:'sender@example.test',enabled:false,senders:['source@example.test'],smtp:{host:'fixture.test',port:465,security:'tls',user:'fixture',password:'fixture'},imap:{host:'fixture.test',port:993,security:'tls',user:'fixture',password:'fixture'}});mailStore.setState(channel.id,channel.version,{smtp:true});
@@ -41,6 +45,6 @@ test('HTTP todo, captured field binding, real PDF, verified share and loopback S
// The dashboard's configured morning cutoff is 09:00, but this received-at is
// exactly 09:00 and belongs to the later half-open window. It must not leak.
assert.equal(messages.length,0);now=new Date('2026-10-19T16:59:00+08:00');await dispatcher.tick();now=new Date('2026-10-19T17:00:00+08:00');await call('/api/order-execution/scan',{connectionId:connection.id,idempotencyKey:'cutoff-complete'});await dispatcher.tick();
- assert.equal(messages.length,1);const message=await simpleParser(messages[0]);assert.deepEqual(message.to.value.map(v=>v.address),['recipient@example.test']);assert.equal(message.attachments.length,1);assert.equal(crypto.createHash('sha256').update(message.attachments[0].content).digest('hex'),evidence.sha256);assert.match(message.text,/000123/);
- assert.equal((await call('/api/order-execution')).data.tasks[0].status,'sent');assert.equal(rules.all('batches').filter(b=>b.status==='sent').length,1);
+ assert.equal(messages.length,1);const message=await simpleParser(messages[0]);assert.deepEqual(message.to.value.map(v=>v.address),['recipient@example.test']);assert.equal(message.attachments.length,1);assert.equal(crypto.createHash('sha256').update(message.attachments[0].content).digest('hex'),evidence.sha256);assert.match(message.text,/000456/);assert.doesNotMatch(message.text,/(?b.status==='sent').length,1);const frozen=rules.all('batches');const updated=rules.saveMapping({processName:captured.processName,processVersion:captured.processVersion,sampleId:captured.id,sources:proposal.mapping.sources,version:1,idempotencyKey:'updated-mapping'},admin),checked=rules.checkMapping({id:updated.id,version:updated.version,sampleId:captured.id,idempotencyKey:'updated-check'},admin);rules.activateMapping({id:updated.id,version:updated.version,checkId:checked.id,idempotencyKey:'updated-confirm'},admin);assert.equal(rules.get('rules','bs-change').published.status,'paused');assert.equal(rules.get('rules','bs-change').trialVersion,null);assert.deepEqual(rules.all('batches'),frozen);assert.equal(mutations,0);
});
diff --git a/tests/assistant/field-skill.test.cjs b/tests/assistant/field-skill.test.cjs
index bc3c314..2027ddb 100644
--- a/tests/assistant/field-skill.test.cjs
+++ b/tests/assistant/field-skill.test.cjs
@@ -45,3 +45,10 @@ test('historical evidence can check a mapping while real notification matching s
assert.equal(result.valid,true);assert.equal(result.result.configurationOnly,true);assert.ok(result.result.warnings.length);
assert.equal(f.store.capturedPreview(sample.id).valid,false);
});
+
+test('assistant prepares the same active-only selection as page preview and never activates or publishes it',async t=>{
+ const f=fixture(t),skill=require('../../src/modules/assistant/field-skill.cjs');await skill.collect(f.deps,'c1',principal,'collect-consistent',()=>{});const sample=f.store.all('capture-samples')[0];
+ f.store.put('field-adapters',{id:'legacy-selected',processName:sample.processName,processVersion:sample.processVersion,verified:true,version:2,sources:{orderNo:{type:'form',path:'Order.Number'},brief:{type:'title'}}});
+ const proposal=f.store.proposeMapping({sampleId:sample.id}),before=f.store.all('rules');assert.equal(proposal.mapping.basis,'active');assert.equal(proposal.mapping.sources.quantity,undefined);
+ const result=await skill.prepare(f.deps,sample.id,principal,'prepare-consistent',skill.guardMapping(f.deps,sample.id,principal.user));assert.equal(result.status,'checked');const draft=f.store.all('field-mapping-drafts')[0];assert.equal(draft.sources.quantity,undefined);assert.deepEqual(f.store.all('rules'),before);assert.equal(f.store.all('field-adapters').length,1);assert.equal(f.store.settings().enabled,false);
+});
diff --git a/tests/order-rules/order-driven-mapping-ui.test.cjs b/tests/order-rules/order-driven-mapping-ui.test.cjs
index 974fd7c..158c969 100644
--- a/tests/order-rules/order-driven-mapping-ui.test.cjs
+++ b/tests/order-rules/order-driven-mapping-ui.test.cjs
@@ -21,3 +21,5 @@ test('operators and viewers only select their own evidence on both pages and nev
});
test('an old check cannot confirm a different interrupted check request',{timeout:90000},async t=>{const {page,runtime}=await orderDrivenUI(t);await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.locator('#fm-recognition').getByText('148396',{exact:true}).waitFor();await page.locator('#fm-save').click();await page.getByText('字段对应草稿已保存。',{exact:true}).waitFor();await page.locator('#fm-check').click();await page.getByText('识别检查完成,请核对订单与文件名。',{exact:true}).waitFor();const before=runtime.orderRules.all('field-mapping-drafts')[0].check.id;await page.route('**/api/order-rules/field-mappings/check',route=>route.abort('failed'));await page.locator('#fm-check').click();await page.getByText(/结果待核实:未能确认同次操作/).waitFor();assert.equal(runtime.orderRules.all('field-mapping-drafts')[0].check.id,before);assert.equal(await page.locator('#fm-activate').isDisabled(),true);});
+
+test('saving a recommendation refreshes its displayed basis and persisted version',{timeout:90000},async t=>{const {page}=await orderDrivenUI(t);await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.locator('#fm-recognition').getByText(/当前订单自动候选/).waitFor();await page.locator('#fm-save').click();await page.locator('#fm-recognition').getByText(/草稿 v1/).waitFor();assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);});
diff --git a/tests/order-rules/order-driven-rules-ui.test.cjs b/tests/order-rules/order-driven-rules-ui.test.cjs
index 5041600..7c066e5 100644
--- a/tests/order-rules/order-driven-rules-ui.test.cjs
+++ b/tests/order-rules/order-driven-rules-ui.test.cjs
@@ -20,3 +20,5 @@ test('concurrent changes to the same rule field block save until explicitly reso
test('ambiguous fields can be selected directly in the rule and remain an unsaved mapping edit',{timeout:90000},async t=>{
const {page,runtime,capture}=await orderDrivenUI(t,'#order-rules');capture({taskId:'amb',serialNum:'AMB',fields:{one:'148396',two:'HA148396'}},{one:'订单号',two:'订单号'});await page.locator('[data-rule-id="bs-change"]').click();await page.getByRole('button',{name:'选择订单 AMB',exact:true}).click();await page.locator('#rule-order-recognition').getByRole('button',{name:'订单号 · 148396',exact:true}).click();await page.locator('#rule-inline-mapping #fm-orderNo').waitFor({state:'attached'});await page.locator('#rule-inline-mapping #fm-recognition [data-recognition-field="orderNo"]').getByText('148396',{exact:true}).waitFor();assert.deepEqual(runtime.orderRules.all('field-mapping-drafts'),[]);assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),true);
});
+
+test('cancelling an order clears the formal check selection and keeps the rule clean',{timeout:90000},async t=>{const {page}=await orderDrivenUI(t,'#order-rules');await page.locator('[data-rule-id="bs-change"]').click();await page.getByRole('button',{name:'选择订单 S-1',exact:true}).click();await page.locator('#rule-order-recognition').getByText('148396',{exact:true}).waitFor();await page.getByRole('button',{name:'取消选择',exact:true}).click();assert.equal(await page.locator('#order-rule-sample-source').inputValue(),'');assert.equal(await page.locator('#order-rule-preview-result').innerText(),'');assert.equal(await page.evaluate(()=>PageLifecycle.dirty()),false);});
diff --git a/tests/order-rules/recognition-proposal.test.cjs b/tests/order-rules/recognition-proposal.test.cjs
index eeaf609..ac034e8 100644
--- a/tests/order-rules/recognition-proposal.test.cjs
+++ b/tests/order-rules/recognition-proposal.test.cjs
@@ -43,3 +43,15 @@ test('unsaved rule dates, subject and directory affect preview without changing
const bad=f.capture({taskId:'bad-date',fields:{order:'148396',date:'2026-02-30'}});const b=f.store.proposeMapping({sampleId:bad.id,ruleId:rule.id,ruleVersion:rule.version,ruleDraft:draft});assert.equal(b.recognition.valid,false);assert.match(b.blockedReasons.join(' '),/日期/);assert.equal(b.effects,null);
assert.throws(()=>f.store.proposeMapping({sampleId:f.captured.id,ruleId:rule.id,ruleVersion:0}),{status:409});
});
+
+test('duplicate active mappings remain blocked even when a saved draft exists',t=>{const f=fixture(t);f.store.saveMapping({processName:f.sample.processName,processVersion:'1.4',sampleId:f.captured.id,sources:{orderNo:{type:'form',path:'order'}},version:0,idempotencyKey:'duplicate-draft'},admin);for(const id of ['active-one','active-two'])f.store.put('field-adapters',{id,processName:f.sample.processName,processVersion:'1.4',verified:true,version:1,sources:{orderNo:{type:'form',path:'order'}}});const p=f.store.proposeMapping({sampleId:f.captured.id});assert.equal(p.recognition.valid,false);assert.match(p.blockedReasons.join(';'),/多个生效映射/);});
+
+test('all fifteen categories reuse methods and recognize the next order independently, including HA and attachment distinctions',t=>{
+ const f=fixture(t);const ids=['overseas-notice','overseas-change','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'];
+ for(const [index,id]of ids.entries()){const rule=f.store.get('rules',id).draft,name=rule.processNames[0],node=rule.nodeNames[0],no='ORDER'+index,title='订单号:'+no+'机芯号:X总数量:0订单号:HA'+no+'机芯号:Y总数量:5',captured=f.capture({taskId:'all-'+id,processName:name,processVersion:'test-'+id,nodeName:node,title,fields:{order:no,qty:0}}),p=f.store.proposeMapping({sampleId:captured.id,ruleId:id,ruleVersion:rule.version});assert.equal(p.classification.status,'matched',id);assert.equal(p.recognition.valid,true,id);assert.equal(p.recognition.event.orderNo,no);assert.equal(p.recognition.event.quantity,0);assert.equal(p.recognition.event.titleOrders.length,2);assert.match(p.recognition.event.brief,new RegExp('HA'+no));
+ const draft=f.store.saveMapping({processName:name,processVersion:'test-'+id,sampleId:captured.id,sources:p.mapping.sources,version:0,idempotencyKey:'save-'+id},admin),check=f.store.checkMapping({id:draft.id,version:draft.version,sampleId:captured.id,idempotencyKey:'check-'+id},admin);assert.equal(check.valid,true,id);f.store.activateMapping({id:draft.id,version:draft.version,checkId:check.id,idempotencyKey:'activate-'+id},admin);
+ const next=f.capture({taskId:'second-'+id,processName:name,processVersion:'test-'+id,nodeName:node,title:'订单号:NEXT'+index+'机芯号:Z',fields:{order:'NEXT'+index,qty:7}}),result=f.store.proposeMapping({sampleId:next.id});assert.equal(result.recognition.event.orderNo,'NEXT'+index);assert.equal(result.recognition.event.quantity,7);assert.equal(f.store.get('field-mapping-drafts',draft.id).version,1);
+ assert.equal(rule.attachPdf,['overseas-change','new-retail-change','domestic-change','bs-change','trial-change'].includes(id));
+ }
+ assert.equal(f.store.settings().enabled,false);assert.deepEqual(f.store.all('orders'),[]);assert.deepEqual(f.store.all('batches'),[]);
+});
diff --git a/tests/order-rules/sample-picker-ui.test.cjs b/tests/order-rules/sample-picker-ui.test.cjs
index b5651dc..742e8fd 100644
--- a/tests/order-rules/sample-picker-ui.test.cjs
+++ b/tests/order-rules/sample-picker-ui.test.cjs
@@ -7,3 +7,9 @@ test('search and paging select evidence without writes, escape titles, cancel se
});
test('late searches and disposed responses cannot overwrite current list',async t=>{const page=await setup(t);await page.evaluate(()=>{window.held=[];window.picker=FieldSamplePicker.mount(document.querySelector('#picker'),{esc:String,user:{role:'viewer'},api:url=>new Promise(resolve=>held.push({url,resolve})),guardSelection:apply=>apply(),onSelect:()=>{}});});await page.waitForFunction(()=>held.length===1);await page.getByLabel('搜索订单号、流水号或标题').fill('new');await page.waitForFunction(()=>held.length===2);await page.evaluate(()=>held[1].resolve({items:[{id:'new',serialNum:'NEW'}],nextCursor:null}));await page.getByRole('button',{name:'选择订单 NEW',exact:true}).waitFor();await page.evaluate(()=>held[0].resolve({items:[{id:'old',serialNum:'OLD'}]}));assert.equal(await page.getByRole('button',{name:'选择订单 OLD',exact:true}).count(),0);await page.getByLabel('搜索订单号、流水号或标题').fill('last');await page.waitForFunction(()=>held.length===3);await page.evaluate(()=>{picker.dispose();document.querySelector('#picker').textContent='已离开';held[2].resolve({items:[{id:'last',serialNum:'LAST'}]});});assert.equal(await page.locator('#picker').innerText(),'已离开');});
test('recognition shows candidates and loads advanced fields lazily, only changing page sources',async t=>{const page=await setup(t);await page.evaluate(()=>{window.loaded=0;window.changes=[];window.panel=FieldRecognitionPanel.render(document.querySelector('#result'),{sampleId:'s1',mapping:{basis:'recommended',sources:{brief:{type:'title'}}},fields:[{key:'orderNo',label:'主订单号',state:'ambiguous',value:null,candidates:[{path:'a',label:'订单号',value:'123'},{path:'b',label:'订单号',value:'HA123'}]},{key:'quantity',label:'数量',state:'recognized',value:0,candidates:[]}],recognition:{valid:false,event:{brief:'123、HA123'}},blockedReasons:['请选择主订单来源'],warnings:[]},{esc:v=>String(v??'').replaceAll('<','<'),admin:true,loadFields:async()=>{loaded++;return [{path:'a',label:'订单号',value:'123'},{path:'b',label:'订单号',value:'HA123'}];},onChangeSources:s=>changes.push(s)});});assert.equal(await page.evaluate(()=>loaded),0);await page.getByRole('button',{name:'订单号 · HA123',exact:true}).click();assert.equal(await page.evaluate(()=>changes[0].orderNo.path),'b');await page.getByText('调整字段对应(高级)',{exact:true}).click();await page.waitForFunction(()=>loaded===1);await page.locator('[data-recognition-source="orderNo"]').selectOption('a');assert.equal(await page.evaluate(()=>changes.at(-1).orderNo.path),'a');assert.match(await page.locator('#result').innerText(),/0/);});
+
+test('failed paging keeps its boundary and keyboard selection works after retry',async t=>{const page=await setup(t);await page.evaluate(()=>{window.failed=false;window.selectedSamples=[];FieldSamplePicker.mount(document.querySelector('#picker'),{esc:String,user:{role:'viewer'},onSelect:async s=>selectedSamples.push(s),api:async url=>{if(url.includes('cursor=page2')&&!failed){failed=true;throw Error('分页断线');}return {items:[{id:url.includes('cursor=page2')?'two':'one',serialNum:url.includes('cursor=page2')?'TWO':'ONE'}],nextCursor:url.includes('cursor=page2')?null:'page2'};}});});await page.getByRole('button',{name:'选择订单 ONE',exact:true}).waitFor();await page.getByRole('button',{name:'下一页',exact:true}).click();await page.getByText('订单读取失败:分页断线',{exact:true}).waitFor();await page.getByRole('button',{name:'下一页',exact:true}).click();const button=page.getByRole('button',{name:'选择订单 TWO',exact:true});await button.focus();await page.keyboard.press('Enter');assert.deepEqual(await page.evaluate(()=>selectedSamples),[{sampleId:'two'}]);});
+
+test('advanced field failure can retry while disposed reads cannot replace the next panel',async t=>{const page=await setup(t);await page.evaluate(()=>{window.loads=0;window.panel=FieldRecognitionPanel.render(document.querySelector('#result'),{sampleId:'s',mapping:{sources:{orderNo:{type:'form',path:'a'}}},fields:[],recognition:{event:{}},blockedReasons:[]},{esc:String,admin:true,loadFields:async()=>{loads++;if(loads===1)throw Error('字段断线');return new Promise(resolve=>window.releaseFields=resolve);}});});await page.getByText('调整字段对应(高级)',{exact:true}).click();await page.getByText('字段读取失败:字段断线',{exact:false}).waitFor();await page.getByRole('button',{name:'重试读取字段',exact:true}).click();await page.waitForFunction(()=>typeof releaseFields==='function');await page.evaluate(()=>{panel.dispose();document.querySelector('#result').textContent='新的样本';releaseFields([{path:'old',label:'旧字段',value:'OLD'}]);});assert.equal(await page.locator('#result').innerText(),'新的样本');});
+
+test('configuration capture locks duplicate actions and cancel only discards the selected result',async t=>{const page=await setup(t);await page.addScriptTag({content:await fs.readFile('web/modules/navigation/lifecycle.js','utf8')});await page.evaluate(()=>{window.calls=[];window.selectedSamples=[];FieldSamplePicker.mount(document.querySelector('#picker'),{esc:String,user:{role:'admin'},connections:[{id:'c',name:'授权连接'}],onSelect:async s=>selectedSamples.push(s),api:async(url,body)=>{calls.push({url,body});if(url.includes('/catalog'))return {items:[],nextCursor:null};if(url.endsWith('/list'))return {id:'list',rows:[{id:'row',serialNum:'LIVE',source:'todo',processName:'流程',processVersion:'1',nodeName:'主管审核'}]};if(url.endsWith('/capture'))return new Promise(resolve=>window.finishCapture=resolve);throw Error('unexpected');}});});await page.getByText('从 BPM 选择',{exact:true}).click();await page.getByLabel('BPM 连接',{exact:true}).selectOption('c');await page.getByRole('button',{name:'读取待办列表',exact:true}).click();assert.equal(await page.getByLabel('读取范围',{exact:true}).inputValue(),'configuration');await page.getByRole('button',{name:'读取并选择 LIVE',exact:true}).click();await page.waitForFunction(()=>typeof finishCapture==='function');assert.equal(await page.getByRole('button',{name:'读取并选择 LIVE',exact:true}).isDisabled(),true);await page.getByRole('button',{name:'取消选择',exact:true}).click();await page.evaluate(()=>finishCapture({id:'captured'}));await page.waitForFunction(()=>!document.querySelector('[data-picker="list"]').disabled);assert.deepEqual(await page.evaluate(()=>selectedSamples),[{sampleId:null}]);assert.equal(await page.evaluate(()=>calls.filter(c=>c.url.endsWith('/capture')).length),1);});
diff --git a/web/modules/field-mappings/recognition-panel.js b/web/modules/field-mappings/recognition-panel.js
index 6418398..2a9ec96 100644
--- a/web/modules/field-mappings/recognition-panel.js
+++ b/web/modules/field-mappings/recognition-panel.js
@@ -2,7 +2,7 @@
'use strict';const text=v=>v==null?'未取得':typeof v==='object'?JSON.stringify(v):String(v),labels={orderNo:'主订单号',customer:'客户',quantity:'数量',appDate:'申请日期',productLine:'产品线',changeReason:'更改原因',changeContent:'更改内容',totalAmount:'总金额'};
function render(host,proposal,{esc,admin=false,loadFields=async()=>[],onChangeSources=()=>{}}){
let disposed=false,revision=0,sources=structuredClone(proposal.mapping?.sources||{}),fields=null;const basis={draft:'待确认草稿',active:'生效配置',recommended:'当前订单自动候选',conflict:'生效配置冲突'};
- host.dataset.readonlySelection='true';host.innerHTML=`当前订单识别结果 · ${esc(basis[proposal.mapping?.basis]||'待核对')}。只读预览,配置尚未在本次操作中保存或生效。
${(proposal.fields||[]).map(f=>`
${esc(f.label)}
${esc(text(f.value))} ${esc(({recognized:'已识别',ambiguous:'有多个候选,请选择',missing:f.key==='orderNo'?'缺少主订单号':'未对应',invalid:'需要修正'})[f.state]||f.state)}${f.source?.type==='form'?' · 来自表单':''}
${f.reason?'
'+esc(f.reason)+'
':''}${admin&&f.state==='ambiguous'?`
${(f.candidates||[]).map((c,i)=>`${esc(c.label||'字段')} · ${esc(text(c.value))} `).join('')}
`:''}
`).join('')}
标题全部订单
${esc(proposal.recognition?.event?.brief||'未取得')}
${[...(proposal.blockedReasons||[]),...(proposal.warnings||[])].map(v=>'
'+esc(v)+'
').join('')}${admin?'
调整字段对应(高级)
':''}
字段来源与检查详情 ${(proposal.recognition?.fieldTrace||[]).map(f=>`
${esc(f.label)}:${esc(f.path||'未对应')} · ${esc(text(f.value))}
`).join('')}
`;
+ const configState=proposal.mapping?.activeVersion?'生效 v'+proposal.mapping.activeVersion+' · 草稿 '+(proposal.mapping.draftVersion?'v'+proposal.mapping.draftVersion:'尚未保存'):proposal.mapping?.draftVersion?'草稿 v'+proposal.mapping.draftVersion+' · 尚未生效':'尚未保存/生效';host.dataset.readonlySelection='true';host.innerHTML=`当前订单识别结果 · ${esc(basis[proposal.mapping?.basis]||'待核对')} · ${esc(configState)}。只读预览,不作为保存或生效凭据。
${(proposal.fields||[]).map(f=>`
${esc(f.label)}
${esc(text(f.value))} ${esc(({recognized:'已识别',ambiguous:'有多个候选,请选择',missing:f.key==='orderNo'?'缺少主订单号':'未对应(可选)',invalid:'需要修正'})[f.state]||f.state)}${f.source?.type==='form'?' · 来自表单':''}
${f.reason?'
'+esc(f.reason)+'
':''}${admin&&f.state==='ambiguous'?`
${(f.candidates||[]).map((c,i)=>`${esc(c.label||'字段')} · ${esc(text(c.value))} `).join('')}
`:''}
`).join('')}
标题全部订单
${esc(proposal.recognition?.event?.brief||'未取得')}
${[...(proposal.blockedReasons||[]),...(proposal.warnings||[])].map(v=>'
'+esc(v)+'
').join('')}${admin?'
调整字段对应(高级)
':''}
字段来源与检查详情 ${(proposal.recognition?.fieldTrace||[]).map(f=>`
${esc(f.label)}:${esc(f.path||'未对应')} · ${esc(text(f.value))}
`).join('')}
`;
const change=()=>{if(!disposed)onChangeSources(structuredClone(sources));};host.querySelectorAll('[data-recognition-candidate]').forEach(b=>b.onclick=()=>{const f=proposal.fields.find(f=>f.key===b.dataset.recognitionCandidate),c=f.candidates[Number(b.dataset.candidate)];sources[f.key]={type:'form',path:c.path};change();});
function draw(search=''){const catalog=host.querySelector('[data-recognition-catalog]');catalog.innerHTML='搜索字段标签或当前值 '+Object.entries(labels).map(([key,label])=>`${label}${key==='orderNo'?'请选择表单订单号':'未对应(可选)'} ${fields.filter(f=>f.path===sources[key]?.path||[f.label,text(f.value)].join(' ').toLocaleLowerCase().includes(search.toLocaleLowerCase())).map(f=>`${esc(f.label||f.path)} · ${esc(text(f.value))} `).join('')} `).join('')+'
';const searchInput=catalog.querySelector('[data-recognition-search]');searchInput.value=search;searchInput.oninput=()=>{const start=searchInput.selectionStart;draw(searchInput.value);const next=catalog.querySelector('[data-recognition-search]');next.focus();next.setSelectionRange(start,start);};catalog.querySelectorAll('[data-recognition-source]').forEach(select=>select.onchange=()=>{if(select.value)sources[select.dataset.recognitionSource]={type:'form',path:select.value};else delete sources[select.dataset.recognitionSource];change();});}
const advanced=host.querySelector('[data-recognition-advanced]');if(advanced)advanced.ontoggle=async()=>{if(!advanced.open||fields||disposed)return;const owner=++revision,target=host.querySelector('[data-recognition-catalog]');target.textContent='正在读取当前订单字段…';try{const result=await loadFields({sampleId:proposal.sampleId});if(disposed||owner!==revision)return;fields=Array.isArray(result)?result:result.fields||[];draw();}catch(error){if(disposed||owner!==revision)return;target.textContent='字段读取失败:'+error.message;const retry=document.createElement('button');retry.type='button';retry.className='btn btn-sm';retry.textContent='重试读取字段';retry.onclick=()=>{advanced.open=false;advanced.open=true;};target.append(retry);}};
diff --git a/web/modules/field-mappings/view.js b/web/modules/field-mappings/view.js
index 527d764..798837a 100644
--- a/web/modules/field-mappings/view.js
+++ b/web/modules/field-mappings/view.js
@@ -31,7 +31,7 @@
function binding(name){const path=sources[name]?.path,field=catalog().find(item=>item.path===path),suggestions=!path?catalog().filter(item=>item.label===labels[name]):[];return `${labels[name]}${name==='orderNo'?' * ':' 可选 '} 搜索${labels[name]}字段标签或当前值 ${fieldOptions(name)} ${esc(field?text(field.value):'尚未对应')}
${suggestions.length===1?'
同名候选,尚未确认:'+esc(text(suggestions[0].value))+'
':''}
字段路径详情 ${esc(path||'尚未选择字段')} `;}
function drawEditor(){const manualOpen=!!get('fm-manual')?.open;const current=selected();if(!current){get('fm-heading').textContent='暂无流程';get('fm-editor').innerHTML='暂无流程目录。请检查类别规则与采集状态。
';return;}
get('fm-heading').textContent=current.process.processName+' · '+(current.version.processVersion||'版本未提供');const item=sample(),meta=item?.sample||item||{},hasSample=!!item;
- panelController?.dispose();get('fm-editor').innerHTML=`${esc(meta.serialNum||'')} · ${esc(meta.nodeName||'')}
真实采集样本 请选择真实样本 ${samples().map(s=>`${esc(s.sample?.serialNum||s.serialNum||s.id)} · ${esc(s.sample?.nodeName||s.nodeName||'节点未提供')} · ${esc(formatDate(s.capturedAt||s.sample?.receivedAt))} `).join('')}${hasSample?`
流程版本 ${esc(current.version.processVersion)}
通知节点 ${esc(meta.nodeName||'未提供')}
流水编号 ${esc(meta.serialNum||'未提供')}
${meta.source==='history'?'流程发起时间':'接收时间'} ${esc(formatDate(meta.receivedAt))}
任务标识 ${esc(meta.taskId||item.taskId||'未提供')} ${meta.source==='history'?'
历史只读样本,仅用于字段配置;未提供办理节点及通知接收时间,不能直接用于通知执行。
':''}
完整${meta.source==='history'?'历史':'待办'}标题
${esc(meta.title||'样本未包含待办标题,检查时会提示缺失')}
`:'
此版本尚无真实样本,请从 BPM 待办读取列表后采集。
'}${admin?`
从 BPM 待办采集样本 BPM 连接 请选择已授权连接 ${connections.map(c=>`${esc(c.name||c.id)} `).join('')}样本范围 当前发送窗口待办 全部待办(仅配置采样) 已办/历史(仅配置采样) 读取待办列表 只读取列表与采集字段,不办理节点、不导出 PDF、不发送邮件。
`:''}
逐项维护字段(高级) 从实际字段标签与当前值选择。元数据固定来自待办;数量与总金额分别对应。
${binding('orderNo')}
摘要来源
完整待办标题 → 订单段落
保留所有标题订单;主订单单独取表单订单号。
sources[name])?'open':''}>可选业务信息 · ${optional.filter(name=>sources[name]).length} 项已对应 ${optional.map(binding).join('')}
关联分类:${esc((current.process.categories||[]).map(c=>c.name).join('、')||'无')}
${admin?`
保存草稿 检查识别结果
已核对识别结果与所有受影响分类,确认使用此版本 确认生效 `:'
当前账号只读,字段对应由管理员维护。
'}
`;
+ panelController?.dispose();get('fm-editor').innerHTML=`${esc(meta.serialNum||'')} · ${esc(meta.source==='history'?'历史 · 节点未提供':meta.nodeName||'')}
真实采集样本 请选择真实样本 ${samples().map(s=>`${esc(s.sample?.serialNum||s.serialNum||s.id)} · ${esc(s.sample?.nodeName||s.nodeName||'节点未提供')} · ${esc(formatDate(s.capturedAt||s.sample?.receivedAt))} `).join('')}${hasSample?`
流程版本 ${esc(current.version.processVersion)}
${meta.source==='history'?'办理节点':'通知节点'} ${esc(meta.source==='history'?'未提供':meta.nodeName||'未提供')}
流水编号 ${esc(meta.serialNum||'未提供')}
${meta.source==='history'?'流程发起时间':'接收时间'} ${esc(formatDate(meta.receivedAt))}
任务标识 ${esc(meta.taskId||item.taskId||'未提供')} ${meta.source==='history'?'
历史只读样本,仅用于字段配置;未提供办理节点及通知接收时间,不能直接用于通知执行。
':''}
完整${meta.source==='history'?'历史':'待办'}标题
${esc(meta.title||'样本未包含待办标题,检查时会提示缺失')}
`:'
此版本尚无真实样本,请从 BPM 待办读取列表后采集。
'}${admin?`
从 BPM 待办采集样本 BPM 连接 请选择已授权连接 ${connections.map(c=>`${esc(c.name||c.id)} `).join('')}样本范围 当前发送窗口待办 全部待办(仅配置采样) 已办/历史(仅配置采样) 读取待办列表 只读取列表与采集字段,不办理节点、不导出 PDF、不发送邮件。
`:''}
逐项维护字段(高级) 从实际字段标签与当前值选择。元数据固定来自待办;数量与总金额分别对应。
${binding('orderNo')}
摘要来源
完整待办标题 → 订单段落
保留所有标题订单;主订单单独取表单订单号。
sources[name])?'open':''}>可选业务信息 · ${optional.filter(name=>sources[name]).length} 项已对应 ${optional.map(binding).join('')}
关联分类:${esc((current.process.categories||[]).map(c=>c.name).join('、')||'无')}
${admin?`
保存草稿 检查识别结果
已核对识别结果与所有受影响分类,确认使用此版本 确认生效 `:'
当前账号只读,字段对应由管理员维护。
'}
`;
get('fm-sample').onchange=()=>{const next=get('fm-sample').value;get('fm-sample').value=sampleId;return guard(()=>{sampleId=next;++revision;check=null;sourcesEdited=false;baseline=snapshot();drawEditor();requestProposal();});};
host.querySelectorAll('[data-fm-search]').forEach(input=>input.oninput=()=>{const name=input.dataset.fmSearch;get('fm-'+name).innerHTML=fieldOptions(name,input.value);});
host.querySelectorAll('[data-fm-binding]').forEach(select=>select.onchange=()=>{const name=select.dataset.fmBinding;if(select.value)sources[name]={type:'form',path:select.value};else delete sources[name];sourcesEdited=true;onSourcesChanged(structuredClone(sources));++proposalRevision;proposal=null;check=null;get('fm-confirm')&&(get('fm-confirm').checked=false);const field=catalog().find(f=>f.path===select.value);get('fm-value-'+name).textContent=field?text(field.value):'尚未对应';get('fm-path-'+name).textContent=select.value||'尚未选择字段';const suggestion=get('fm-suggestion-'+name);if(suggestion)suggestion.hidden=!!select.value;drawResult();updateActions();requestProposal();});
@@ -61,9 +61,9 @@
if(result){uncertain=false;return result;}uncertain=true;throw Error('结果待核实:未能确认同次操作,保留输入,请刷新核对,暂不重复提交。');}}
async function mutate(work){if(busy||!live())return false;busy=true;updateActions();const owner=revision;const owned=()=>live()&&owner===revision;try{return await work(owned);}catch(error){if(owned())feedback(error.message,'danger');return false;}finally{busy=false;if(owned())updateActions();}}
async function refreshDirectory(){const request=++readRevision,fresh=await api('/order-rules/fields?view=directory');if(!live()||request!==readRevision)return;const current=selected(),identity=current?[current.process.processName,current.version.processVersion]:null,legacy=!Array.isArray(fresh.processes);data=fresh;if(identity){const versions=allVersions(),next=versions.findIndex(row=>row.process.processName===identity[0]&&row.version.processVersion===identity[1]);if(legacy&&next>=0)Object.assign(versions[next].version,{draft:current.version.draft,active:current.version.active,status:current.version.status});selection=next;selectedFallback=next<0?current:null;}drawDirectory();}
- async function save(){if(!admin||!sample()||!sources.orderNo?.path)return false;return mutate(async owned=>{const current=selected(),body={processName:current.process.processName,processVersion:current.version.processVersion,sampleId,sources:structuredClone(sources),version:draftVersion},submitted=snapshot();const saved=await verifiedPost('/order-rules/field-mappings/draft',body);if(!owned())return false;record=saved;current.version.draft=saved;draftVersion=saved.version;check=null;baseline=submitted;get('fm-confirm').checked=false;drawResult();await lifecycle.afterSave(refreshDirectory,'字段对应草稿已保存。',feedback,owned);return true;});}
+ async function save(){if(!admin||!sample()||!sources.orderNo?.path)return false;return mutate(async owned=>{const current=selected(),body={processName:current.process.processName,processVersion:current.version.processVersion,sampleId,sources:structuredClone(sources),version:draftVersion},submitted=snapshot();const saved=await verifiedPost('/order-rules/field-mappings/draft',body);if(!owned())return false;record=saved;current.version.draft=saved;draftVersion=saved.version;check=null;baseline=submitted;get('fm-confirm').checked=false;drawResult();await lifecycle.afterSave(refreshDirectory,'字段对应草稿已保存。',feedback,owned);if(owned())requestProposal();return true;});}
async function runCheck(){if(!admin||dirty()||!draftVersion||!record)return false;return mutate(async owned=>{const route='/order-rules/field-mappings/check',body={id:record.id,version:record.version,sampleId},result=await verifiedPost(route,body);if(!owned())return false;keyCache.delete(route+JSON.stringify(body));check=result;selected().version.draft.check=result;selected().version.status=result.valid?'检查通过':'检查未通过';drawDirectory();drawResult();get('fm-confirm').checked=false;feedback(result.valid?'识别检查完成,请核对订单与文件名。':'识别检查未通过,请核对错误。',result.valid?'success':'warning');return true;});}
- async function activate(){if(!admin||!compatibleCheck()||!check.valid||!get('fm-confirm').checked)return false;return mutate(async owned=>{const saved=await verifiedPost('/order-rules/field-mappings/activate',{id:record.id,version:record.version,checkId:check.id});if(!owned())return false;record=saved;selected().version.draft=saved;selected().version.active=saved.active;selected().version.status='已核验';baseline=snapshot();get('fm-confirm').checked=false;await lifecycle.afterSave(refreshDirectory,'字段对应已确认生效。',feedback,owned);if(owned())await onActivated(saved);return true;});}
+ async function activate(){if(!admin||!compatibleCheck()||!check.valid||!get('fm-confirm').checked)return false;return mutate(async owned=>{const saved=await verifiedPost('/order-rules/field-mappings/activate',{id:record.id,version:record.version,checkId:check.id});if(!owned())return false;record=saved;selected().version.draft=saved;selected().version.active=saved.active;selected().version.status='已核验';baseline=snapshot();get('fm-confirm').checked=false;await lifecycle.afterSave(refreshDirectory,'字段对应已确认生效。',feedback,owned);if(owned()){requestProposal();await onActivated(saved);}return true;});}
async function listSamples(){const connectionId=get('fm-connection').value;if(!connectionId){feedback('请先选择 BPM 连接。','warning');return;}return mutate(async owned=>{const route='/order-rules/field-samples/list',body={connectionId,scope:get('fm-scope').value},result=await samplePost(route,body);if(!owned())return;keyCache.delete(route+JSON.stringify(body));listing={...result,connectionId};drawTodoList();});}
function drawTodoList(){get('fm-todo-list').innerHTML=(listing.rows||[]).map((row,index)=>`${esc(row.serialNum||row.taskId)} ${esc(row.processName)} · ${esc(row.processVersion||'版本未提供')} · ${esc(row.nodeName||'')}
${esc(row.title||'无标题')}
采集此样本 `).join('')||'所选范围没有可采集样本
';get('fm-todo-list').querySelectorAll('[data-fm-capture]').forEach(button=>button.onclick=()=>guard(()=>captureSample(listing.rows[Number(button.dataset.fmCapture)])));}
async function captureSample(row){return mutate(async owned=>{const captured=await samplePost('/order-rules/field-samples/capture',{connectionId:listing.connectionId,listId:listing.id,rowId:row.id});if(!owned())return;await lifecycle.afterSave(refreshDirectory,'真实样本已采集,可选择样本核对字段。',feedback,owned);if(!owned())return;const actual=captured.sample?.id?captured.sample:captured;const next=allVersions().findIndex(v=>v.process.processName===(actual.processName||row.processName)&&v.version.processVersion===(actual.processVersion||row.processVersion));if(next>=0){selection=next;selectedFallback=null;loadSelection();if(samples().some(s=>s.id===actual.id))sampleId=actual.id;baseline=snapshot();drawDirectory();drawEditor();requestProposal();}});}
diff --git a/web/modules/order-rules/view.js b/web/modules/order-rules/view.js
index 30f899b..113da62 100644
--- a/web/modules/order-rules/view.js
+++ b/web/modules/order-rules/view.js
@@ -58,7 +58,7 @@
effects.innerHTML=window.OrderRulePreview.proposal(p,{esc,ruleName:read().name});drawSyncConflicts();
}
async function requestProposal(){if(!owned()||!selectedSampleId)return;const id=selectedSampleId,request=++proposalRevision,version=rule.version;try{const result=await api('/order-rules/field-mappings/propose',{sampleId:id,ruleId:rule.id,ruleVersion:version,...(admin?{ruleDraft:read(),...(proposalSources?{sources:proposalSources}:{})}: {})});if(!owned()||request!==proposalRevision||selectedSampleId!==id||rule.version!==version)return;proposal=result;drawProposal();}catch(error){if(owned()&&request===proposalRevision){panel.querySelector('#rule-order-recognition').textContent='识别读取失败:'+error.message;panel.querySelector('#rule-proposal-effects').textContent='预览不可用,请修正或重试。';}}}
- async function selectSample(id){++proposalRevision;++trialRevision;proposal=null;inlineController?.dispose();inlineController=null;panel.querySelector('#rule-inline-mapping').replaceChildren();panel.querySelector('#rule-inline-mapping').hidden=true;selectedSampleId=id;proposalSources=null;drawProposal();if(!id)return;let captured=data.samples.find(s=>s.id===id);if(!captured){const fields=await api('/order-rules/fields?view=directory');if(!owned()||selectedSampleId!==id)return;data.samples=fields.samples||[];captured=data.samples.find(s=>s.id===id);}if(captured?.sample?.source==='todo'){const key='capture:'+id;if(!sources.some(s=>s.id===key)){sources.push({id:key,sampleId:id,label:captured.sample.serialNum||id,processName:captured.processName,sample:captured.sample});source.add(new Option(captured.sample.serialNum||id,key));}source.value=key;}else source.value='';await requestProposal();}
+ async function selectSample(id){++proposalRevision;++trialRevision;source.value='';panel.querySelector('#order-rule-adapter').textContent='';panel.querySelector('#order-rule-preview-result').replaceChildren();proposal=null;inlineController?.dispose();inlineController=null;panel.querySelector('#rule-inline-mapping').replaceChildren();panel.querySelector('#rule-inline-mapping').hidden=true;selectedSampleId=id;proposalSources=null;drawProposal();if(!id)return;let captured=data.samples.find(s=>s.id===id);if(!captured){const fields=await api('/order-rules/fields?view=directory');if(!owned()||selectedSampleId!==id)return;data.samples=fields.samples||[];captured=data.samples.find(s=>s.id===id);}if(captured?.sample?.source==='todo'){const key='capture:'+id;if(!sources.some(s=>s.id===key)){sources.push({id:key,sampleId:id,label:captured.sample.serialNum||id,processName:captured.processName,sample:captured.sample});source.add(new Option(captured.sample.serialNum||id,key));}source.value=key;}else source.value='';await requestProposal();}
pickerController=window.FieldSamplePicker.mount(panel.querySelector('#rule-order-picker'),{api,esc,formatDate,user,isActive:owned,processNames:rule.processNames,connections:data.connections,guardSelection:apply=>window.PageLifecycle.guard(apply),onSelect:({sampleId})=>selectSample(sampleId),feedback});
const editable=['name','archiveDirectory','subjectPrefix','intro','signature','filenameDate','scopes','to','cc','attachPdf','bodyTemplateId','adapterIds'];
function applyValues(value){for(const k of ['name','archiveDirectory','subjectPrefix','intro','signature','filenameDate'])form.elements.namedItem(k).value=value[k]||'';for(const k of ['to','cc'])form.elements.namedItem(k).value=(value[k]||[]).join('\n');form.elements.namedItem('attachPdf').checked=value.attachPdf;form.elements.namedItem('bodyTemplateId').value=value.bodyTemplateId??(form.querySelector('option[value="__legacy__"]')?'__legacy__':'');scopeController.setScopes(value.scopes||[]);resourceController?.setDirectory?.(value.archiveDirectory||'');}