Compare commits

..
27 Commits
Author SHA1 Message Date
super 668d0c4a67 Merge branch 'dev' into super 2026-10-22 19:52:51 +08:00
sophie b69c725992 !25 Merge branch 'dev' into chat-format
Merge pull request !25 from 王瑞雪/chat-format
2026-10-22 02:59:02 +00:00
HTEWJ\26070045 331a983476 Merge branch 'dev' into chat-format 2026-10-22 10:48:09 +08:00
sophie 55e56e4dc9 fix: 在AGENTS.md约束增加element plus 2026-10-21 20:12:25 +08:00
sophie cdc8610ec1 fix(admin): 管理控制台界面使用element plus 2026-10-20 17:01:24 +08:00
HTEWJ\26070045 9236f2949c style(chat-format): 修改回复样式为序号缩进等 2026-10-16 15:15:48 +08:00
sophie 6c47d0639c build: 修改frontend lint报错 2026-10-15 15:13:10 +08:00
hugo 22bee49346 fix(shipping-notice): 工作台五阶段定位只进不退并保留最近投影
提交订单后的刷新窗口内,extractionLifecycleProgress 会被 Run 级
lifecycle_progress(两段模型,恒为 intake_parse)短暂覆盖,五阶段页签
闪回「接收解析」后再跳「通知准备」。

- lifecycleProgressForView 保持最近一次非空投影兜底,不再回落 Run 级旧值;
- 新增 lifecycleStageFloor 只进不退下限:自动定位永不回跳已越过的更早
  阶段;显式 route 请求(用户手动点击阶段入口)不受限,可回看前置阶段。
2026-10-15 09:45:14 +08:00
hugo c27379d933 fix(shipping-notice): 预约单号兜底分作用域并镜像补写明细缺失行
订单级早退导致表头已有预约单号时明细行补写永不执行(回归
SNER-20261014-0AB6D98A doc 915 明细预约号空)。

- 兜底早退改分作用域:scope=header 表头有值才跳过;scope=line
  行级全有值才跳过,存在缺失行仍执行补写;
- 镜像语义:排除集移除表头已采纳的预约号值——它正是要写入缺失
  行级的值;其余订单观测值(尤其 PO)保持排除防误判;
- PO 行定位收敛不变:本单 PO 所在行的预约号唯一命中后写入。

真数据验证:9/9 PO 各自唯一写入本行预约号
(4510042199→1000161448 … 4510042208→1000131033),与表头一致。
2026-10-15 08:43:05 +08:00
hugo f7734c8ccb fix(shipping-notice): 识别收口自动解决已采纳字段的补充冲突
重识别 Run 收口时对本 Run 可复核 Case 原子激活文件 Stream
(batch_reparse_succeeded,含 Run 谱系证明与可选来源声明),
使工作台队列不再因 Stream 断链而丢失单据。

- persist 收口对本 Run 候选批量调用 resolve_satisfied_supplement_conflicts:
  supplement_field_conflict 的字段级裁决已 accepted(PO 行收敛唯一写入
  或正式值源)即标记 resolved,不再阻断提交订单;
- 投影过滤 resolved 冲突不下发待裁决面板;
- 同一 field_code 表头/行级双字段(如预约单号)任一位置 accepted 即满足;
- 新增测试环境失败 Run 重排队运维脚本(仅测试库硬校验、dry-run 默认)。
2026-10-15 02:27:16 +08:00
hugo dde2093e06 fix(shipping-notice): 收口激活按 run_id 取 Run 修变量作用域 2026-10-15 01:39:37 +08:00
hugo e78f750db0 fix(shipping-notice): 重识别 Run 终态激活 Case 并收紧裸数字兜底口径
- 修复重解析延迟激活钩子未接线:Run 终态原子激活可复核 Case 为文件 Stream 当前版本,工作台队列不再空白
- 新增 run_is_reparse_successor_of_case 判定 Case 与重解析 Run 的后继关系
- 裸数字兜底口径收紧:仅扫「整格恰好 5/10 位纯数字」的正文 HTML 表格单元格,自由文本与带前后字符的值一律不取,防误绑签名与邮编
- 新增客户 PO 匹配变体集合(原值/归一/去前导零)纳入排除集,补充合并末段裁决更准
- 同步预约号启发式测试,business/technical 文档记录收紧决策
2026-10-15 01:26:23 +08:00
hugo 1efb165fd5 fix(shipping-notice): 调整XFA 身份指纹漂移降级软门禁并放行 datasets 取值
供应商换代重导 XFA 表单必变 template 包指纹,原硬拦截使视觉已唯一
命中的单据永远停在无数据人工复核。

- 身份校验改为状态判定写入 decision.xfa_identity_state
  (matched/incomplete/mismatch),漂移仅记 fallback 码不拦截;
- 放行后按模板既有 bindings 对新包 datasets 取值,仍强制
  validate_xfa_extraction 业务交叉校验兜底;
- 取值/业务校验失败时身份码前置转 Review,复核者可见漂移根因。
2026-10-15 00:31:43 +08:00
hugo 47ee68ed25 fix(shipping-notice): 批次投影收敛需人工未物化识别 Run 并下发重解析
收口 completed 且最新 Run review_required、但未物化 Case/OT 的附件
(如 XFA 身份门禁在唯一命中后拒绝、候选从未创建)原先落入兜底
running,批次进度中心误显示「处理中」且无任何动作入口。

- 文档级裁决新增 review_required 无 Task/Case 分支:waiting_human
  + candidate_creating(回归 SNER-20261014-E27D657F)
- 重解析入口与 failed 分支同源:无 OT/无 Case 且最新 Run 失败或
  需人工,均下发 reparse 动作
2026-10-14 23:23:26 +08:00
hugo 97059b336b fix(shipping-notice): 抽取收口纠正失败文档状态并修复 OCR 救援资产读取
- 抽取收口读取 Run 内 Unit 级失败事实:全部 Unit 失败的附件不再按零 pending 误写 completed
- EML 父项跟随 Run 结果收敛:终态 Run 禁止停留「处理中」,运行中仅区分解析失败与处理中
- OCR 救援资产读取修复:read_asset_bytes 接收 id 时按 FileAsset 加载字节,传参口径纠正
- 同步抽取/投影测试并新增工作台投影测试
2026-10-14 22:43:30 +08:00
sophie a92df4c38d Merge branch 'dev' of https://gitee.com/justop/hxops into dev 2026-10-14 20:25:53 +08:00
sophieandCursor 5f6fbcd76f feat: element plus UI组件库
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-14 20:25:35 +08:00
hugo d7d4819a42 feat(shipping-notice): 无表头文档抽取增强与复核深链身份修复
- 新增表头 OCR 救援:模板匹配落 layout_drift/no_match 时按表头带证据补洞重评候选身份,主抽取流程接入并落 identity_rescue 事实字段
- 预约号裸数字兜底:正文无表头且常规证据缺失时扫描 5/10 位纯数字候选,持久化预置、合并末段唯一/多候选裁决
- 修复复核深链仅带 run_no 时队列项显示未命名:Case 身份优先按当前工作面 displayCase 匹配队列项
- 同步抽取 Job/运行服务/候选持久化配套与 OCR 救援、预约号启发式、表头身份测试
2026-10-14 19:55:37 +08:00
sophie 041bb73b9a fix: update docs 2026-10-14 13:44:56 +08:00
hugo af2658e244 Merge branch 'hugo-auto-transfer' into dev 2026-10-13 21:18:25 +08:00
hugo 6ac2effac3 feat(shipping-notice): 支持已确认订单改绑客户并重冻结快照
- 客户识别面板两态化:已识别折叠为摘要条 +「修改客户」入口,前端管控复用编辑窗头级谓词
- 新增 rebind_confirmed_customer 链路:守卫→更新 resolution 行→审计→手动重冻结,改后重新生成 Excel
- 守卫保证仅在无发货通知/Excel 产物时可改,匹配与门禁零触碰、无失效连锁
- 路由引擎/建单资格/编辑窗服务同步适配,errors 补充改绑错误码四语言
- 同步客户面板测试、确认对话框与四语言文案,落设计与实施计划文档
2026-10-13 21:13:58 +08:00
sophie c305d0544b !24 Merge branch 'dev' into change
Merge pull request !24 from 王瑞雪/change
2026-10-13 08:19:18 +00:00
sophie 5879871ade Merge branch 'dev' of https://gitee.com/justop/hxops into dev 2026-10-13 15:52:38 +08:00
sophie b8cc0cbe77 fix: 设备验收预警优化 2026-10-13 15:52:09 +08:00
hugo 4a726fe8b2 Merge branch 'hugo-auto-transfer' into dev 2026-10-13 15:10:45 +08:00
hugo ea94fb28db feat(shipping-notice): 人工重取库存前置候选刷新并放开行级库存源下拉
- 人工重试库存准备前置幂等重判:任务级整单重路由、行级定向重评目标行,复用裁决与冻结链路,零新动作码零契约变更
- 新版候选集 supersede 时内置失效旧库存事实,导出归档与查询服务同步适配
- 行级「库存源」下拉抽纯函数合并选项:歧义行候选置顶 + 全部已启用源去重兜底,任一已启用源可人工指定
- 库存源门禁归一 Notice→OT 身份解析;任务中心抽屉与表格接入行级重取入口
- 同步四语言文案、技术文档与实施计划
2026-10-13 15:04:40 +08:00
super 8d14b8a100 Merge branch 'dev' into super 2026-09-21 17:07:47 +08:00
179 changed files with 18709 additions and 6359 deletions

No files matched your search

-70
View File
@@ -1,70 +0,0 @@
---
description: 文件层与函数层注释强制规范(撰写与调整代码时均适用)
alwaysApply: true
---
# 代码注释(强制)
撰写或**修改**代码时,必须补齐或更新两层注释。完整说明见 `AGENTS.md` §5。
## 文件层(文件顶部)
块注释须包含:**用途**、**主要 import/依赖**、**与上下游文件的逻辑关系**。
```typescript
/**
* features/kb/composables/useKbWorkspace.ts
* 用途:知识库作业面编排入口,组合 state / computed / data 等子模块。
* 依赖:kb-workspace/* composables、kb.api、kb-display.utils。
* 逻辑:KbWorkspaceView 调用本 composable;本文件再分发至 useKbWorkspaceData 等子模块。
*/
```
```python
"""
services/kb_sync.py
用途:知识库文档与 Dify 之间的同步编排。
依赖:dify_service、models.KbDocument、minio_service。
逻辑:由 api/knowledge_base 路由调用;内部委托 chunking 与 job 状态机。
"""
```
## 函数层(每个函数定义上方)
须说明:**用途**、**核心逻辑与实现方式**、**参数**与**返回值**(及异常)。
```typescript
/**
* 加载当前分组下的文档列表,并在静默刷新时合并 stable 项避免闪烁。
* 核心逻辑:调用 getKbGroupFilesSafe,按 mergeStableItems 策略合并新旧列表。
* @param options.silent - 为 true 时不切换 loading,用于轮询刷新
* @returns 是否成功拉取到数据
*/
async function loadDocuments(options?: LoadListOptions): Promise<boolean> { ... }
```
```python
def sync_document_to_dify(document_id: int, *, force: bool = False) -> SyncResult:
"""
将指定文档切片同步至 Dify 知识库。
核心逻辑:读 MinIO 原文 → 切块 → 调 Dify API upsert;失败写入 KbJob 供重试。
Args:
document_id: 本地 KbDocument 主键。
force: 为 True 时忽略已完成状态强制重同步。
Returns:
SyncResult: 含 dify_document_id 与分段数。
Raises:
KbNotFoundError: 文档不存在或无权限。
"""
```
## 修改既有文件时
- 改函数逻辑/签名 → 同步改该函数注释。
- 改 import 或模块协作关系 → 同步改文件头注释。
- Vue SFC:`<script setup>` 内每个函数同样要求函数层注释。
+21
View File
@@ -0,0 +1,21 @@
---
description: 未启用。管理端改用 Element Plus 的写法。启用前不要自动套用。
alwaysApply: false
---
# 管理端 Element Plus(未启用)
本规则现在不自动生效:`alwaysApply` 为 false,且没有 `globs`。打开管理端文件时不会套用。
启用:在本文件顶部 frontmatter 加上下面的 `globs` 后保存。不要改 `alwaysApply`。
```yaml
globs: frontend/src/features/admin/**/*.vue,frontend/src/features/kb/components/KbAdminPanel.vue,frontend/src/features/kb/components/KbGroupDrawer.vue
```
启用之后,改这些 Vue 时遵守 `docs/ui/ELEMENT_MIGRATION.md` §4:
- 按钮、输入、下拉、表格、弹窗、分页用 Element Plus,不要新写 `<button>`、`<input>`、`<select>`、`<textarea>`。
- 不要新写 `btn-primary`、`btn-secondary`、`btn-ghost`、`btn-danger`、`input-field`、`select-field`。
- 图标用 `@element-plus/icons-vue`,不要新加 `lucide-vue-next`。
- 字号和颜色用 `element-trial.css` 里的 Element 变量,不要在单元格上写 `text-sm`、`text-xs`、`text-muted`。
+23
View File
@@ -0,0 +1,23 @@
## 改动说明
<!-- 这次改了什么、为什么改。 -->
## 管理端界面
这次改动如果碰到管理控制台、知识库配置,或已经换成 Element Plus 的页面,按 `docs/ui/ELEMENT_MIGRATION.md` §6 核对。没改界面就删掉下面的清单。
- [ ] 只在该页入口引入 Element 样式和 `element-trial.css`,并用 `ElConfigProvider` 包住。
- [ ] 列表骨架符合规范 §3,左右 32px 对齐,只有一层卡片。
- [ ] 按钮符合规范 §4.1,没有 `size="small"` 和默认按钮混在一行。
- [ ] 表格状态是 `ElTag`,单元格没有 `text-xs` / `text-sm` / `text-muted`。
- [ ] 筛选框没有被拉成整行,空选项不是「请选择」。
- [ ] 弹窗宽度只有 480px 或 680px,短表单不是整屏抽屉。
- [ ] 加载遮罩只等列表请求,数据出来后遮罩消失。
- [ ] 删除确认与本页其他确认框是同一种。
- [ ] 四种语言下按钮、表头、空状态、分页都能读通。
- [ ] `html.dark` 下边框、表头、弹窗底色跟着变量变。
- [ ] `frontend` 下 `npx vue-tsc -b --pretty false` 通过。
## 测试
<!-- 怎么验证。 -->
+3
View File
@@ -59,6 +59,9 @@ frontend/package-lock.json
!.vscode/extensions.json
.trae/*
.cursor/*
!.cursor/rules/
!.cursor/rules/*.mdc
.cursor/rules/* copy.mdc
.idea/
*.swp
*.swo
+2
View File
@@ -150,6 +150,7 @@ docker compose logs -f hxops-backend
- 🧬 **修改数据库表结构必须配套迁移**:任何对 `models.py` / 数据表结构的新增、删除、字段或约束变更,都必须生成并提交对应的 Alembic 迁移脚本(`flask db migrate -m "..."` → `flask db upgrade`),禁止只改模型不出迁移。
- 🌐 **环境变量分层**:`.env.shared` + `.env.<env>`(dev/test/prod),不要在代码里写死环境值。规则见 **[docs/convention/env_loading_priority.md](docs/convention/env_loading_priority.md)** 与 **[docs/convention/环境变量规则.md](docs/convention/环境变量规则.md)**。
- 🌍 **i18n 四语言**:前端新增文案必须同时补齐 `zh-CN / zh-TW / en / th`,禁止硬编码中文。Agent 流程见项目 Skill `add-i18n-keys` 与 [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md)。
- 🎨 **前端界面统一 Element Plus**:`frontend/src` 的页面、弹窗、筛选、表格、按钮和输入使用 Element Plus,写法以 [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) 为准。新改的界面禁止再加 `btn-*`、`input-field`、`select-field`,以及手写 `<button>` / `<input>` / `<select>` / `<textarea>`。尚未替换的旧页面保持原样,轮到该页再整页替换,同一页不要混用两套控件。管理端列表骨架用 `AdminListPage`,页签用 `AdminListTabs`。
- 📡 **SSE 流式约束**:对话链路依赖 Gevent 异步 worker + Nginx `proxy_buffering off`;对话接口(`chat.py`)使用原生 Fetch/SSE 而非 Axios,改动需保持流式不被破坏。
- 🔌 **外部集成依赖**:Oracle Instant Client 19.30 / `pyodbc` / `zeep`(OA、PLM、HR)等本地未必可运行,涉及这些 service 时谨慎并说明。
- ➕ **新增依赖需克制**:不擅自引入未经评审的第三方依赖;如需新增,在提交说明中给出理由。
@@ -207,6 +208,7 @@ docker compose logs -f hxops-backend
| FAQ 缓存 / 热点发现运维 | [docs/faq_cache_ops_manual.md](docs/faq_cache_ops_manual.md) |
| 测试计划 | [docs/test_plan_matrix.md](docs/test_plan_matrix.md) |
| 前端架构规范 | [docs/refactor/frontend_architecture_refactor.md](docs/refactor/frontend_architecture_refactor.md) |
| 前端 Element Plus | [docs/ui/ELEMENT_MIGRATION.md](docs/ui/ELEMENT_MIGRATION.md) |
| 错误处理规范 | [docs/convention/error_handling.md](docs/convention/error_handling.md) |
| Cursor Skills 索引 | [docs/skills/README.md](docs/skills/README.md) |
| 前端四语言 i18n Skill | [docs/skills/add-i18n-keys-skill.md](docs/skills/add-i18n-keys-skill.md) |
Vendored
+23
View File
@@ -353,6 +353,29 @@ pipeline {
}
}
stage('Frontend Lint') {
when {
expression { env.FRONTEND_CHANGED == 'true' }
}
steps {
echo '[Frontend Lint] FRONTEND_CHANGED=true,执行 npm run lint(Element 规则当前为 off)'
sh '''
set -eu
test -f "${WORKSPACE}/scripts/ci_frontend_lint.sh"
test -f "${WORKSPACE}/frontend/package.json"
# 不用 -v 挂载工作区:Jenkins 在容器里时,宿主机 Docker 看不到 /var/jenkins_home。
# 把前端源码和脚本打进容器再检查。node_modules 由容器内 npm ci 安装。
tar -C "${WORKSPACE}" \
--exclude=frontend/node_modules \
--exclude=frontend/dist \
-cf - \
frontend scripts/ci_frontend_lint.sh \
| docker run --rm -i node:22-alpine \
sh -c 'mkdir -p /repo && tar -xf - -C /repo && sh /repo/scripts/ci_frontend_lint.sh'
'''
}
}
// stage('Frontend Build (CI)') {
// when {
// expression { env.FRONTEND_CHANGED == 'true' }
@@ -3,12 +3,14 @@ backend/app/api/equipment_acceptance/__init__.py
用途:设备验收预警的 Chat 作业面接口。
依赖:JWT 当前用户、Agent 授权、sync_service、统一成功响应。
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录和配置;同步、扫描、发送和保存配置仅平台管理员。
逻辑:持有 equipment_acceptance Agent 的用户可看停留列表、发送记录、已归档 Excel 和配置;同步、扫描、发送和保存配置仅平台管理员。
"""
from __future__ import annotations
from flask import Blueprint, g, request
from io import BytesIO
from flask import Blueprint, g, request, send_file
from app.core.auth.jwt import get_current_user
from app.core.errors import ForbiddenError, UnauthorizedError
@@ -19,7 +21,7 @@ from app.services.equipment_acceptance.config_service import (
save_acceptance_config,
)
from app.services.equipment_acceptance.alert_service import generate_alerts, send_pending_alerts
from app.services.equipment_acceptance.send_record_service import list_send_records
from app.services.equipment_acceptance.send_record_service import get_send_file, list_send_files, list_send_records
from app.services.equipment_acceptance.sync_service import (
get_acceptance_order,
list_acceptance_orders,
@@ -157,6 +159,26 @@ def send_equipment_acceptance_alerts():
return ok(send_pending_alerts(), request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/send-files", methods=["GET"])
def list_equipment_acceptance_send_files():
"""列出最近按收件人归档的 Excel。不含文件字节。"""
_require_equipment_acceptance_access()
return ok({"items": list_send_files()}, request_id=getattr(g, "request_id", None))
@equipment_acceptance_bp.route("/send-files/<int:file_id>/excel", methods=["GET"])
def download_equipment_acceptance_send_file(file_id: int):
"""下载一份当时发给收件人的设备验收预警 Excel。"""
_require_equipment_acceptance_access()
row = get_send_file(file_id)
return send_file(
BytesIO(row.excel_file_data),
as_attachment=True,
download_name=row.excel_file_name or f"equipment-acceptance-alert-{file_id}.xlsx",
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
@equipment_acceptance_bp.route("/sends", methods=["GET"])
def list_equipment_acceptance_sends():
"""分页查看发送记录。扫描写入后这里才有行。"""
+189 -12
View File
@@ -20,7 +20,7 @@ from flask import Blueprint, Response, current_app, g, request, send_file
from app import db
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
from app.core.errors import AppError, ConflictError, NotFoundError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
@@ -186,6 +186,7 @@ def workspace_shipping_tasks():
lifecycle_status=lifecycle_status,
page=page,
page_size=page_size,
is_admin=bool(user.is_platform_admin()),
))
@@ -394,14 +395,38 @@ def workspace_batch_restore_shipping_tasks():
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
def workspace_shipping_export_archive():
"""按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
"""按显式任务号下载当前用户可下载(创建者或管理员)的 ready 发货 Excel ZIP。"""
user = _require_user()
data = request.get_json(silent=True) or {}
task_nos = data.get('task_nos')
if task_nos is not None and not isinstance(task_nos, list):
raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
from app.services.shipping_notice.export_archive import build_export_archive
stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or [])
from app.services.shipping_notice.fulfillment_audit import record_access_audit
stream, filename, manifest = build_export_archive(
user_id=user.id,
task_nos=task_nos or [],
is_admin=bool(user.is_platform_admin()),
)
# 与 business_no 批量导出同一审计口径:按票落 record_access_audit(自行提交)。
for entry in manifest.get('entries') or []:
aggregate_no = str(entry.get('business_no') or '').strip()
task_no = str(entry.get('task_no') or '').strip()
if not aggregate_no and not task_no:
continue
record_access_audit(
action='download_task_excel',
aggregate_type='shipping_task',
aggregate_id=task_no or aggregate_no,
actor_id=user.id,
task_no=task_no or None,
reason_code='excel_downloaded',
metadata={
'export': 'batch_zip',
'batch_status': str(entry.get('status') or ''),
},
)
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
response.call_on_close(stream.close)
return response
@@ -455,7 +480,11 @@ def workspace_confirm_shipping_customer(task_no: str):
details={'field': 'customer_id'},
) from exc
updated = confirm_task_customer(task, customer_id=customer_id, actor_id=user.id)
return _ok(serialize_task_detail(updated))
return _ok(serialize_task_detail(
updated,
viewer_user_id=user.id,
is_admin=bool(user.is_platform_admin()),
))
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
@@ -499,7 +528,7 @@ def workspace_create_shipping_task_from_notice():
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id)
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
return _ok({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task, viewer_user_id=user.id) if task else {'task_no': task_id}, 'notice_upload': intake.to_notice_upload_meta(), 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}})
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/replace-notice', methods=['POST'])
def workspace_replace_shipping_task_notice(task_no: str):
@@ -657,7 +686,12 @@ def workspace_shipping_task_ui_state(task_no: str):
task = get_task_for_user(task_no, user.id)
if not task:
raise NotFoundError('Not found')
return _ok(build_task_ui_state(task, include_stage_context=True))
return _ok(build_task_ui_state(
task,
include_stage_context=True,
viewer_user_id=user.id,
viewer_is_admin=bool(user.is_platform_admin()),
))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/chat-actions', methods=['GET'])
def workspace_shipping_task_chat_actions(task_no: str):
@@ -1032,6 +1066,38 @@ def _load_business_notice_for_user(*, business_no: str, user_id: int) -> Shippin
return task
def _load_business_notice_readable_for_user(
*,
business_no: str,
user_id: int,
is_admin: bool,
) -> ShippingNotice:
"""
按精确发货通知单号加载当前用户可下载的 Notice(创建者或管理员)。
核心逻辑:下载是只读动作,授权走 can_download_task_export 统一谓词口径
(可下载=可见),不经过写路径的履约归属断言;管理员可下载其可见的正式
Notice,且每次下载均由端点写入 record_access_audit。
Args:
business_no: 对外发货通知单号。
user_id: 当前服务端会话用户主键。
is_admin: 是否平台管理员。
Returns:
可下载的 ShippingNotice。
Raises:
NotFoundError: 编号不存在、非正式 Notice 或用户不可见。
"""
normalized = str(business_no or '').strip().upper()
from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(normalized, user_id, is_admin=is_admin)
if not isinstance(task, ShippingNotice) or str(task.business_no or '').strip().upper() != normalized:
raise NotFoundError('Shipping notice not found')
return task
def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
"""按 business_no 发起单张通知的货代 RPA 上传或重试。"""
task = _load_business_notice_for_user(business_no=business_no, user_id=user_id)
@@ -1138,9 +1204,13 @@ def workspace_batch_start_shipping_notice_rpa_upload():
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET'])
def workspace_shipping_notice_export(business_no: str):
"""按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。"""
"""按发货通知单号下载该通知唯一的正式 Excel(创建者或管理员),并保留下载审计。"""
user = _require_user()
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
task = _load_business_notice_readable_for_user(
business_no=business_no,
user_id=int(user.id),
is_admin=bool(user.is_platform_admin()),
)
err_msg = task_export_error_message(task)
if err_msg:
raise NotFoundError(err_msg)
@@ -1162,7 +1232,7 @@ def workspace_shipping_notice_export(business_no: str):
@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST'])
def workspace_shipping_notice_export_archive():
"""按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。"""
"""按多个 business_no 下载各自唯一 Excel 的 ZIP(创建者或管理员);任一越权或缺文件均整体拒绝。"""
user = _require_user()
data = request.get_json(silent=True) or {}
raw_values = data.get('business_nos')
@@ -1174,8 +1244,32 @@ def workspace_shipping_notice_export_archive():
if not business_nos or len(business_nos) > 100:
raise ValidationError('business_nos must contain 1 to 100 business numbers')
from app.services.shipping_notice.export_archive import build_export_archive
from app.services.shipping_notice.fulfillment_audit import record_access_audit
stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos)
stream, filename, manifest = build_export_archive(
user_id=int(user.id),
business_nos=business_nos,
is_admin=bool(user.is_platform_admin()),
)
# 批量导出与单票下载同一审计口径:按票落 record_access_audit(自行提交),
# manifest.business_no 是 aggregate 事实源;missing/checksum 票据也留痕。
for entry in manifest.get('entries') or []:
aggregate_no = str(entry.get('business_no') or '').strip()
task_no = str(entry.get('task_no') or '').strip()
if not aggregate_no and not task_no:
continue
record_access_audit(
action='download_notice_excel',
aggregate_type='shipping_notice',
aggregate_id=aggregate_no or task_no,
actor_id=user.id,
task_no=task_no or None,
reason_code='excel_downloaded',
metadata={
'export': 'batch_zip',
'batch_status': str(entry.get('status') or ''),
},
)
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
response.call_on_close(stream.close)
return response
@@ -1183,9 +1277,10 @@ def workspace_shipping_notice_export_archive():
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
"""下载当前用户可下载任务的出货 Excel(创建者或管理员);写入统一访问审计。"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
from app.services.shipping_notice.query_service import get_task_visible_to_user
task = get_task_visible_to_user(task_no, user.id, is_admin=bool(user.is_platform_admin()))
task = _require_formal_notice(task)
err_msg = task_export_error_message(task)
if err_msg:
@@ -2103,6 +2198,88 @@ def workspace_confirm_shipping_order_review_customer(case_no: str):
))
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/customer/rebind',
methods=['POST'],
)
def workspace_rebind_shipping_order_review_customer(case_no: str):
"""
确认客户改绑:直接修改已确认的客户识别结果并刷新订单快照客户。
Body: customer_id, expected_order_data_version, reason?
仅当订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无活动 Gate Attempt,
即发货通知/Excel 未产生)时允许;版本乐观锁与状态守卫在服务层 fail-closed。
"""
user = _require_user()
data = request.get_json(silent=True) or {}
try:
customer_id = int(data.get('customer_id'))
except (TypeError, ValueError) as exc:
raise ValidationError(
'Customer id is required',
code='SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED',
details={'field': 'customer_id'},
) from exc
try:
expected_order_data_version = int(data.get('expected_order_data_version'))
except (TypeError, ValueError) as exc:
raise ValidationError(
'Expected order data version is required',
code='SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED',
details={'field': 'expected_order_data_version'},
) from exc
from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer
from app.services.shipping_notice.order_review_customer_service import (
project_review_case_customer_resolution,
)
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
from app.services.shipping_notice.order_review_projection import serialize_review_case
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
formal = resolve_formal_ot(case)
if not formal.get('has_formal_ot') or formal.get('task') is None:
raise ConflictError(
'A formal order task is required before rebinding customer',
code='SHIPPING.FORMAL_OT_REQUIRED',
details={'task_missing': bool(formal.get('task_missing'))},
)
result = rebind_confirmed_customer(
task=formal['task'],
new_customer_id=customer_id,
actor_id=int(user.id),
expected_order_data_version=expected_order_data_version,
reason=str(data.get('reason') or '').strip() or None,
)
db.session.commit()
resolution = result['resolution']
rebind_record = next(
(
item.get('rebind') for item in (resolution.evidence_json or [])
if isinstance(item, dict) and item.get('rebind')
),
None,
) or {}
refreshed_case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
return _ok({
'case': serialize_review_case(refreshed_case) if refreshed_case is not None else None,
'customer_resolution': (
project_review_case_customer_resolution(refreshed_case)
if refreshed_case is not None else None
),
'rebind': {
'previous_customer_id': rebind_record.get('previous_customer_id'),
'customer_id': int(resolution.confirmed_customer_id),
'snapshot_id': int(result['snapshot'].id),
},
})
@workspace_shipping_notice_bp.route(
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
methods=['POST'],
@@ -724,6 +724,58 @@ def _handoff_continue_order_extraction(
return True
def _emit_reservation_heuristic_audit(
*,
run: Any,
merged_by_unit_id: dict[int, list[dict[str, Any]]],
) -> None:
"""
合并末段「裸数字预约单号兜底」落地后补审计事件,供上线后观察误判率。
【AI 触发时机】:EML 补充合并(merge_email_supplements)完成后调用。
只读订单上的 _hxops_reservation_heuristic 标记,不修改订单;命中与多候选
各发一条事件,metadata 携带 unit/候选值/正文文档定位,便于按 Case 回溯证据。
Args:
run: 当前订单抽取 Run(审计聚合根)。
merged_by_unit_id: 本趟合并产物 {unit_id: [order]}。
"""
applied_entries: list[dict[str, Any]] = []
ambiguous_entries: list[dict[str, Any]] = []
for unit_id, orders in (merged_by_unit_id or {}).items():
for order in orders or []:
marker = order.get('_hxops_reservation_heuristic') if isinstance(order, dict) else None
if not isinstance(marker, dict):
continue
entry = {
'unit_id': int(unit_id),
'values': marker.get('values') or [],
'document_id': marker.get('document_id'),
}
if marker.get('status') == 'applied':
applied_entries.append({**entry, 'value': marker.get('value')})
else:
ambiguous_entries.append(entry)
for event_type, entries in (
('reservation_heuristic_applied', applied_entries),
('reservation_heuristic_ambiguous', ambiguous_entries),
):
if not entries:
continue
append_shipping_audit_event(
event_type=event_type,
aggregate_type='order_extraction_run',
aggregate_id=str(run.id),
run_no=run.run_no,
actor_type='system',
source='shipping_order_extraction',
metadata={
'entries': entries,
'decision_rule_version': 'bare-numeric-reservation-v1',
},
)
def _is_transient_lock_error(exc: BaseException) -> bool:
"""
判断异常是否为瞬时锁冲突(PostgreSQL 死锁 40P01 / 锁等待超时 55P03)。
@@ -1139,6 +1191,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
},
)
_merge_group_orders(eml_units, apply_email_supplements=True)
_emit_reservation_heuristic_audit(run=run, merged_by_unit_id=merged_by_unit_id)
append_shipping_audit_event(
event_type='ORDER_EMAIL_ADJUDICATION_COMPLETED',
aggregate_type='order_extraction_run',
+2
View File
@@ -242,6 +242,7 @@ from app.models.equipment_acceptance import (
EquipmentAcceptanceNode,
EquipmentAcceptanceOperator,
EquipmentAcceptanceOrder,
EquipmentAcceptanceSendFile,
EquipmentAcceptanceSendRecord,
EquipmentAcceptanceSetting,
)
@@ -445,6 +446,7 @@ __all__ = [
'EquipmentAcceptanceNode',
'EquipmentAcceptanceOperator',
'EquipmentAcceptanceSetting',
'EquipmentAcceptanceSendFile',
'EquipmentAcceptanceSendRecord',
'TransferRun',
'TransferSourceJob',
+27 -2
View File
@@ -4,8 +4,9 @@ backend/app/models/equipment_acceptance.py
用途:设备验收预警的本地同步快照和可改配置。
依赖:models.base.Base、users。
逻辑:同步服务按流程实例 request_id upsert 主表,并整批替换当前节点和操作人子表。
配置表只存四档天数和三个固定岗位的系统用户。发送时刻不在这张表。
配置表存四档天数、第 4 轮是否启用,以及三个固定岗位的系统用户。发送时刻不在这张表。
发送记录按验收单和档位留一行。已发送和已取消的姓名不回写;待发送每次扫描重算。
发给每位收件人的 Excel 另存一行,并用 send_record_ids 挂回发送记录,供表格列下载。
不保存流程编号、第二合同编号、验收日期和 isremark。
"""
@@ -14,7 +15,7 @@ from __future__ import annotations
from datetime import datetime
from typing import Optional
from sqlalchemy import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, String, Text, UniqueConstraint
from sqlalchemy import JSON, BigInteger, Boolean, DateTime, ForeignKey, Index, LargeBinary, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column
from app.models.base import Base
@@ -116,6 +117,7 @@ class EquipmentAcceptanceSetting(Base):
day_2: Mapped[int] = mapped_column(nullable=False, default=37)
day_3: Mapped[int] = mapped_column(nullable=False, default=44)
day_4: Mapped[int] = mapped_column(nullable=False, default=51)
round_4_enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
buyer_manager_user_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
@@ -154,3 +156,26 @@ class EquipmentAcceptanceSendRecord(Base):
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
class EquipmentAcceptanceSendFile(Base):
"""一位收件人一次发送留下的 Excel。字节与当时发给企业微信的文件相同。"""
__tablename__ = "equipment_acceptance_send_files"
__table_args__ = (
Index("ix_equipment_acceptance_send_files_created", "created_at"),
)
id: Mapped[int] = mapped_column(primary_key=True)
recipient_user_id: Mapped[Optional[int]] = mapped_column(
ForeignKey("users.id", ondelete="SET NULL"), nullable=True
)
recipient_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
excel_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
excel_file_data: Mapped[Optional[bytes]] = mapped_column(LargeBinary, nullable=True)
excel_file_size: Mapped[Optional[int]] = mapped_column(nullable=True)
send_record_ids: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
status: Mapped[str] = mapped_column(String(32), nullable=False, default="sent")
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
sent_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False)
@@ -0,0 +1,90 @@
"""
backend/app/services/equipment_acceptance/alert_notice.py
用途:把一名收件人的待发送记录收成企微汇总文案和 Excel 明细。
依赖:openpyxl。
逻辑:发送服务按企业微信账号调用。卡片只写张数,逐张明细进工作簿。不写主送、抄送。
"""
from __future__ import annotations
from io import BytesIO
from typing import Any
from openpyxl import Workbook
from openpyxl.styles import Font
NOTICE_HEADERS = (
"验收单号",
"采购单号",
"申请人",
"轮次",
"停留天数",
"当前节点",
"当前处理人",
"通知身份",
)
NOTICE_FILE_NAME = "设备验收停留提醒.xlsx"
def summary_message(lines: list[dict[str, Any]]) -> str:
"""
拼一名收件人的文字卡片。第一行写已逾期的验收单张数,不列单号。
核心逻辑:一张发送记录算一张。同一轮次的张数写在一起,顺序跟传入的明细一致。
Args:
lines: 已按发送记录去重的明细。每项含 threshold_days。
Returns:
卡片正文。没有明细时仍返回可发送的空汇总。
"""
counts: dict[int, int] = {}
order: list[int] = []
for line in lines:
day = int(line.get("threshold_days") or 0)
if day not in counts:
order.append(day)
counts[day] = 0
counts[day] += 1
detail = ",".join(f"超过 {day} 天 {counts[day]} 张" for day in order) or "无"
return f"共 {len(lines)} 张验收单已逾期。\n{detail}。\n明细见下一条文件。"
def build_notice_workbook(lines: list[dict[str, Any]]) -> bytes:
"""
生成这名收件人的验收停留明细。
核心逻辑:一行对应一张发送记录。通知身份写他为什么收到,不写主送或抄送。
Args:
lines: 验收单号、采购单号、申请人、轮次天数、停留天数、当前节点、当前处理人和通知身份。
Returns:
xlsx 字节。
"""
workbook = Workbook()
sheet = workbook.active
sheet.title = "停留提醒"
sheet.append(list(NOTICE_HEADERS))
for cell in sheet[1]:
cell.font = Font(bold=True)
for line in lines:
dwell = line.get("dwell_days")
sheet.append([
_cell(line.get("acceptance_no")),
_cell(line.get("purchase_order_no")),
_cell(line.get("applicant")),
f"超过 {int(line.get('threshold_days') or 0)} 天",
"—" if dwell is None or dwell == "" else dwell,
_cell(line.get("node_name")),
_cell(line.get("handlers")),
_cell(line.get("identity")),
])
sheet.freeze_panes = "A2"
sheet.auto_filter.ref = sheet.dimensions
output = BytesIO()
workbook.save(output)
return output.getvalue()
def _cell(value: Any) -> str:
"""空值写成横线,避免 Excel 里出现空白列。"""
text = str(value or "").strip()
return text or "—"
@@ -11,20 +11,31 @@ from __future__ import annotations
from typing import Any
def due_tiers(dwell_days: int | None, thresholds: tuple[int, int, int, int]) -> list[int]:
def due_tiers(
dwell_days: int | None,
thresholds: tuple[int, int, int, int],
*,
max_tier: int = 4,
) -> list[int]:
"""
按累计天数给出已经跨过的档位。
核心逻辑:需求是「超过 N 天」。停留刚好等于阈值时还不发。四档各自独立,一次可以跨多档。
第 4 轮关闭时最高只到第 3 档,超过第 4 档天数也不产生总经理那一轮。
Args:
dwell_days: 签核自然日。没有计时起点时为空。
thresholds: 四个天数,对应第 1 到第 4 档。
max_tier: 允许的最高档,1 到 4。第 4 轮未启用时传 3。
Returns:
档位号 1 到 4 的列表。没有跨档时为空。
档位号列表。没有跨档时为空。
"""
if dwell_days is None:
return []
return [index + 1 for index, day in enumerate(thresholds) if dwell_days > day]
return [
index + 1
for index, day in enumerate(thresholds)
if dwell_days > day and index + 1 <= max_tier
]
def make_person(
@@ -2,8 +2,9 @@
backend/app/services/equipment_acceptance/alert_service.py
用途:每日扫描生成设备验收待发送记录,并在周五按收件人发送企业微信。
依赖:同步服务、OA 人员目录、alert_plan、发送记录模型、企微通知。
逻辑:扫描先同步 E10,再按停留天数跨档。停表取消未发送记录。已发送的不重发、不改收件人。
依赖:同步服务、OA 人员目录、alert_plan、alert_notice、发送记录模型、企微通知。
逻辑:扫描先同步 E10,再按停留天数跨档。第 4 轮关闭时不生成、也不发送总经理那一轮。
周五按收件人发一条汇总卡片,紧跟着一份 Excel。卡片和文件都成功才算已发送。停表取消未发送记录。已发送的不重发、不改收件人。
"""
from __future__ import annotations
@@ -11,15 +12,23 @@ from __future__ import annotations
import logging
from datetime import datetime
from typing import Any
from zoneinfo import ZoneInfo
from app.extensions import db
from app.models.equipment_acceptance import (
EquipmentAcceptanceNode,
EquipmentAcceptanceOperator,
EquipmentAcceptanceOrder,
EquipmentAcceptanceSendFile,
EquipmentAcceptanceSendRecord,
EquipmentAcceptanceSetting,
)
from app.models.user import User
from app.services.equipment_acceptance.alert_notice import (
NOTICE_FILE_NAME,
build_notice_workbook,
summary_message,
)
from app.services.equipment_acceptance.alert_plan import (
assemble_tier,
due_tiers,
@@ -27,7 +36,7 @@ from app.services.equipment_acceptance.alert_plan import (
resolve_account,
resolve_configured_user,
)
from app.services.equipment_acceptance.config_service import reminder_days
from app.services.equipment_acceptance.config_service import is_round_4_enabled, reminder_days
from app.services.equipment_acceptance.snapshot_rules import WATCHING
_LOGGER = logging.getLogger(__name__)
@@ -61,7 +70,7 @@ def refresh_pending_alerts(
"""
按本地快照刷新待发送记录。
核心逻辑:计时中的单据跨过哪一档就保留哪一档。已发送和已取消不改。
核心逻辑:计时中的单据跨过哪一档就保留哪一档。第 4 轮关闭时最高只到第 3 档。已发送和已取消不改。
未计时或已停表的单据,把还没发出的记录改成已取消。
Args:
directory: 测试注入的人员目录和经副理。空则查询 E10。
@@ -74,6 +83,7 @@ def refresh_pending_alerts(
users_by_job = _users_by_job(_job_numbers(orders, operators, people, deputies))
roles = _configured_users()
thresholds = reminder_days()
max_tier = 4 if is_round_4_enabled() else 3
existing = {
(row.order_id, row.tier): row
for row in db.session.query(EquipmentAcceptanceSendRecord).all()
@@ -86,7 +96,16 @@ def refresh_pending_alerts(
if order.monitor_status != WATCHING:
cancelled += cancel_unsent(order.id)
continue
for draft in _drafts(order, operators.get(order.id, []), people, deputies, users_by_job, roles, thresholds):
for draft in _drafts(
order,
operators.get(order.id, []),
people,
deputies,
users_by_job,
roles,
thresholds,
max_tier=max_tier,
):
current = existing.get((order.id, draft["tier"]))
if current is not None and current.status in ("sent", "cancelled"):
continue
@@ -136,24 +155,37 @@ def send_pending_alerts() -> dict[str, Any]:
"""
把待发送记录按收件人合并成一条企业微信。
核心逻辑:同一个人本轮只收一条。解析失败的人不改发给别人。已取消和已发送不参与。
核心逻辑:同一个人本轮只收一条汇总卡片和一份 Excel。卡片只写张数,明细在文件里。
解析失败的人不改发给别人。已取消和已发送不参与。
第 4 轮关闭时,已生成的待发送第 4 轮也不发出,避免通知总经理。
卡片或附件任一失败都记失败原因,并打一条 warning 日志。
每位收件人的 Excel 都写入 equipment_acceptance_send_files,发送失败也保留。
Returns:
成功人数、失败人数,以及对应的记录条数。
"""
from app.models import Agent
from app.services.integrations.wecom.notify import send_wecom_event_message
from app.services.integrations.wecom.notify import (
send_wecom_event_message,
send_wecom_file_message,
upload_wecom_temp_media,
)
rows = (
db.session.query(EquipmentAcceptanceSendRecord)
.filter(EquipmentAcceptanceSendRecord.status == "pending")
.all()
)
if not is_round_4_enabled():
rows = [row for row in rows if row.tier != 4]
orders = {
order.id: order
for order in db.session.query(EquipmentAcceptanceOrder)
.filter(EquipmentAcceptanceOrder.id.in_([row.order_id for row in rows if row.order_id]))
.all()
} if rows else {}
order_ids = [row.order_id for row in rows if row.order_id]
nodes = _nodes_by_order(order_ids)
operators = _operators_by_order(order_ids)
users = _users_by_id(_recipient_user_ids(rows))
buckets: dict[str, list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]]] = {}
for row in rows:
@@ -166,24 +198,58 @@ def send_pending_alerts() -> dict[str, Any]:
jump_path = f"/chat/{agent.id}" if agent is not None else "/workspace"
jump_params = {"view": "sends"} if agent is not None else None
sent_ids: set[str] = set()
failed_ids: set[str] = set()
failed_reasons: dict[str, str] = {}
for wecom_id, entries in buckets.items():
user = _audit_user(entries, users)
lines = _notice_lines(entries, orders, nodes, operators)
workbook = build_notice_workbook(lines)
archived = _archive_send_file(user, entries, workbook)
failure = ""
try:
result = send_wecom_event_message(
event_type=_EVENT,
user=user,
title="设备验收停留提醒",
content=_message(entries, orders),
content=summary_message(lines),
jump_path=jump_path,
jump_params=jump_params,
wecom_userid=wecom_id,
)
ok = bool(result.get("ok"))
except Exception:
_LOGGER.warning("equipment acceptance wecom send failed")
ok = False
(sent_ids if ok else failed_ids).add(wecom_id)
_LOGGER.exception("equipment acceptance wecom send failed")
failure = "企业微信发送异常"
result = {}
if not failure and not result.get("ok"):
failure = _wecom_failure_text(result)
_LOGGER.warning(
"equipment acceptance wecom send failed reason=%s trace_id=%s detail=%s",
result.get("reason"),
result.get("trace_id"),
failure,
)
if not failure:
try:
media_id = upload_wecom_temp_media(workbook, archived.excel_file_name or NOTICE_FILE_NAME)
file_result = send_wecom_file_message(wecom_id, media_id)
except Exception:
_LOGGER.exception("equipment acceptance wecom file upload failed")
failure = "企业微信附件上传失败"
file_result = {}
if not failure and file_result.get("errcode") != 0:
failure = _file_failure_text(file_result)
_LOGGER.warning(
"equipment acceptance wecom file failed errcode=%s errmsg=%s",
file_result.get("errcode"),
failure,
)
if failure:
failed_reasons[wecom_id] = failure
archived.status = "failed"
archived.error_message = failure
else:
sent_ids.add(wecom_id)
archived.status = "sent"
archived.sent_at = datetime.utcnow()
records_sent = 0
records_failed = 0
now = datetime.utcnow()
@@ -196,9 +262,10 @@ def send_pending_alerts() -> dict[str, Any]:
ready.discard("")
if not ready:
continue
if ready & failed_ids:
hit = [failed_reasons[item] for item in ready if item in failed_reasons]
if hit:
row.status = "failed"
row.error_message = _join_error(row.error_message, "企业微信发送失败")
row.error_message = _join_error(row.error_message, ";".join(dict.fromkeys(hit)))
records_failed += 1
elif ready <= sent_ids:
row.status = "sent"
@@ -207,7 +274,7 @@ def send_pending_alerts() -> dict[str, Any]:
db.session.commit()
return {
"sent": len(sent_ids),
"failed": len(failed_ids),
"failed": len(failed_reasons),
"records_sent": records_sent,
"records_failed": records_failed,
}
@@ -221,9 +288,11 @@ def _drafts(
users_by_job: dict[str, User],
roles: dict[str, User | None],
thresholds: tuple[int, int, int, int],
*,
max_tier: int = 4,
) -> list[dict[str, Any]]:
"""按当前处理人展开四档里已经跨过的档。"""
due = due_tiers(order.dwell_days, thresholds)
"""按当前处理人展开已经跨过、且配置允许的档。第 4 轮关闭时最高到第 3 档。"""
due = due_tiers(order.dwell_days, thresholds, max_tier=max_tier)
if not due:
return []
handlers: list[dict[str, Any]] = []
@@ -410,6 +479,21 @@ def _users_by_id(user_ids: list[int]) -> dict[int, User]:
return {row.id: row for row in rows}
def _nodes_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceNode]]:
"""取出这些验收单的当前节点名称。"""
if not order_ids:
return {}
grouped: dict[int, list[EquipmentAcceptanceNode]] = {}
rows = (
db.session.query(EquipmentAcceptanceNode)
.filter(EquipmentAcceptanceNode.order_id.in_(order_ids))
.all()
)
for row in rows:
grouped.setdefault(row.order_id, []).append(row)
return grouped
def _operators_by_order(order_ids: list[int]) -> dict[int, list[EquipmentAcceptanceOperator]]:
"""取出这些验收单的当前处理人。"""
if not order_ids:
@@ -447,28 +531,145 @@ def _audit_user(
return None
def _message(
def _archive_send_file(
user: User | None,
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
workbook: bytes,
) -> EquipmentAcceptanceSendFile:
"""
把这次准备发给一名收件人的 Excel 先落库。
核心逻辑:发送成功或失败都保留同一份字节,并记下里面的发送记录,供表格列下载。不保存企微 userid。
Args:
user: 系统用户。对不上账号时只留姓名。
entries: 这名收件人的发送记录和席位,用来取展示名。
workbook: xlsx 字节。
Returns:
已加入当前事务、尚未提交的文件行。
"""
now = datetime.utcnow()
name = _recipient_display_name(user, entries)
row = EquipmentAcceptanceSendFile(
recipient_user_id=None if user is None else user.id,
recipient_name=name or None,
excel_file_name=_archive_file_name(name, now),
excel_file_data=workbook,
excel_file_size=len(workbook),
send_record_ids=[row.id for row, _person in entries if row.id],
status="pending",
created_at=now,
)
db.session.add(row)
return row
def _recipient_display_name(
user: User | None,
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
) -> str:
"""优先用系统姓名,没有账号时用收件人席位上的名字。"""
if user is not None:
named = str(user.real_name or user.username or "").strip()
if named:
return named
for _row, person in entries:
named = str(person.get("name") or "").strip()
if named:
return named
return ""
def _archive_file_name(recipient_name: str, moment: datetime) -> str:
"""文件名带上海日期和收件人,避免多次发送都叫同一个名字。"""
local = moment.replace(tzinfo=ZoneInfo("UTC")).astimezone(ZoneInfo("Asia/Shanghai"))
safe = "".join(char for char in recipient_name if char not in '\\/:*?"<>|').strip() or "收件人"
return f"设备验收停留提醒-{local:%Y%m%d}-{safe}.xlsx"[:255]
def _notice_lines(
entries: list[tuple[EquipmentAcceptanceSendRecord, dict[str, Any]]],
orders: dict[int, EquipmentAcceptanceOrder],
) -> str:
"""拼一名收件人本轮要看的验收单。过长时截断。"""
lines: list[str] = []
seen: set[int] = set()
nodes: dict[int, list[EquipmentAcceptanceNode]],
operators: dict[int, list[EquipmentAcceptanceOperator]],
) -> list[dict[str, Any]]:
"""
把一名收件人的发送记录收成 Excel 行。
核心逻辑:同一条发送记录只占一行。通知身份用角色名,例如当前处理人、直接主管,不写主送或抄送。
Args:
entries: 这名收件人挂到的发送记录和对应席位。
orders: 验收单主键到快照。
nodes: 验收单主键到当前节点。
operators: 验收单主键到当前处理人。
Returns:
传给汇总文案和 Excel 的明细行。
"""
grouped: dict[int, dict[str, Any]] = {}
order_keys: list[int] = []
for row, person in entries:
if row.id in seen:
continue
seen.add(row.id)
label = str(person.get("label") or "").strip()
bucket = grouped.get(row.id)
if bucket is None:
bucket = {"row": row, "labels": []}
grouped[row.id] = bucket
order_keys.append(row.id)
if label and label not in bucket["labels"]:
bucket["labels"].append(label)
lines: list[dict[str, Any]] = []
for key in order_keys:
row = grouped[key]["row"]
order = orders.get(row.order_id or 0)
days = "—" if order is None or order.dwell_days is None else str(order.dwell_days)
role = "主送" if person.get("slot") == "to" else "抄送"
lines.append(
f"{role} {row.acceptance_no or '—'},采购单 {row.purchase_order_no or '—'},"
f"停留 {days} 天,超过 {row.threshold_days} 天"
)
text = "\n".join(lines[:12])
if len(lines) > 12:
text = f"{text}\n另有 {len(lines) - 12} 条"
return text[:500]
node_names = _unique_text(node.node_name for node in nodes.get(row.order_id or 0, []))
handler_names = _unique_text(operator.handler_name for operator in operators.get(row.order_id or 0, []))
lines.append({
"acceptance_no": row.acceptance_no,
"purchase_order_no": row.purchase_order_no,
"applicant": None if order is None else order.applicant_name,
"threshold_days": row.threshold_days,
"dwell_days": None if order is None else order.dwell_days,
"node_name": "、".join(node_names),
"handlers": "、".join(handler_names),
"identity": "、".join(grouped[key]["labels"]),
})
return lines
def _unique_text(values) -> list[str]:
"""按出现顺序去掉空白和重复名称。"""
found: list[str] = []
for value in values:
text = str(value or "").strip()
if text and text not in found:
found.append(text)
return found
def _file_failure_text(result: dict[str, Any]) -> str:
"""把企微文件消息的返回收成失败原因。不写入 userid。"""
code = result.get("errcode")
message = str(result.get("errmsg") or "").strip()
text = f"企业微信附件发送失败 {code} {message}".strip()
return text[:255]
def _wecom_failure_text(result: dict[str, Any]) -> str:
"""把企微发送结果收成页面和日志都能看的失败原因。不写入 userid。"""
reason = str(result.get("reason") or "")
if reason == "notify_disabled":
return "企业微信通知总开关已关闭"
if reason == "event_disabled":
return "未开启设备验收预警的企业微信事件"
if reason == "user_unbound":
return "收件人未绑定企业微信"
raw = result.get("raw") if isinstance(result.get("raw"), dict) else {}
if reason == "send_failed":
code = raw.get("errcode")
message = str(raw.get("errmsg") or "").strip()
text = f"企业微信返回 {code} {message}".strip()
return text[:255]
if reason == "exception":
return "企业微信发送异常"
return "企业微信发送失败"
def _join_error(current: str | None, extra: str) -> str:
@@ -1,10 +1,10 @@
"""
backend/app/services/equipment_acceptance/config_service.py
用途:读写设备验收预警配置:四档天数和三个固定岗位。
用途:读写设备验收预警配置:四档天数、第 4 轮开关和三个固定岗位。
依赖:extensions.db、EquipmentAcceptanceSetting、User、统一错误。
逻辑:配置页和停留列表调用。岗位只存系统用户主键。发送时刻不在这里,由排程 Cron 决定。
没有配置行时按冻结默认值 30/37/44/51 返回,不把姓名写进代码。
没有配置行时按冻结默认值 30/37/44/51 返回,第 4 轮默认关闭,不把姓名写进代码。
"""
from __future__ import annotations
@@ -29,6 +29,44 @@ _ROLE_FIELDS = (
_MAX_DAY = 3650
def is_round_4_enabled() -> bool:
"""
读取第 4 轮是否启用。
核心逻辑:没有配置行或字段为假时关闭。关闭后扫描不生成、发送不推出总经理那一轮。
Returns:
启用为 True。
"""
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
if row is None:
return False
return bool(row.round_4_enabled)
def parse_round_4_enabled(raw: Any) -> bool:
"""
校验第 4 轮开关。
核心逻辑:缺省按关闭处理,避免旧请求误打开总经理提醒。传入值必须是布尔。
Args:
raw: 接口里的 round_4_enabled。缺省为 None。
Returns:
是否启用第 4 轮。
Raises:
ValidationError: 传入了布尔以外的值。
"""
if raw is None:
return False
if not isinstance(raw, bool):
raise ValidationError(
"第 4 轮开关必须是是否启用",
code="EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID",
details={"field": "round_4_enabled"},
)
return raw
def reminder_days() -> tuple[int, int, int, int]:
"""
读取四档天数。
@@ -65,12 +103,13 @@ def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]:
Args:
include_candidates: 为 True 时附带在职用户,供选人弹窗使用。
Returns:
days、三个岗位用户主键、已选用户、候选人和更新时间。
days、第 4 轮开关、三个岗位用户主键、已选用户、候选人和更新时间。
"""
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
selected_ids = _selected_ids(row)
return {
"days": list(_days_of(row)),
"round_4_enabled": False if row is None else bool(row.round_4_enabled),
"buyer_manager_user_id": None if row is None else row.buyer_manager_user_id,
"coo_user_id": None if row is None else row.coo_user_id,
"executive_user_id": None if row is None else row.executive_user_id,
@@ -82,12 +121,12 @@ def get_acceptance_config(*, include_candidates: bool) -> dict[str, Any]:
def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[str, Any]:
"""
保存四档天数和三个岗位用户。
保存四档天数、第 4 轮开关和三个岗位用户。
核心逻辑:天数必须逐档增大。岗位为空表示未选;有值时必须是已存在的系统用户。
保存后只影响以后的预警,这里不改历史发送记录。
核心逻辑:天数必须逐档增大。第 4 轮缺省为关闭。岗位为空表示未选;有值时必须是已存在的系统用户。
保存后只影响以后的预警,这里不改历史发送记录。已有的待发送第 4 轮在发送时会被跳过。
Args:
payload: days 为四个整数;三个岗位字段为用户主键或空。
payload: days 为四个整数;round_4_enabled 为布尔;三个岗位字段为用户主键或空。
updated_by: 操作人的系统用户主键。
Returns:
与读取接口相同的配置,并带候选人。
@@ -96,12 +135,14 @@ def save_acceptance_config(payload: dict[str, Any], *, updated_by: int) -> dict[
ValidationError: 天数不合法,或岗位用户不存在。
"""
days = validate_reminder_days(payload.get("days"))
round_4_enabled = parse_round_4_enabled(payload.get("round_4_enabled"))
role_ids = {field: _require_user_id(payload.get(field), field) for field in _ROLE_FIELDS}
row = db.session.get(EquipmentAcceptanceSetting, _SETTING_ID)
if row is None:
row = EquipmentAcceptanceSetting(id=_SETTING_ID)
db.session.add(row)
row.day_1, row.day_2, row.day_3, row.day_4 = days
row.round_4_enabled = round_4_enabled
row.buyer_manager_user_id = role_ids["buyer_manager_user_id"]
row.coo_user_id = role_ids["coo_user_id"]
row.executive_user_id = role_ids["executive_user_id"]
@@ -2,17 +2,20 @@
backend/app/services/equipment_acceptance/send_record_service.py
用途:分页读取设备验收预警的发送记录。
依赖:extensions.db、EquipmentAcceptanceSendRecord、utc_iso。
逻辑:由 GET /api/equipment-acceptance/sends 调用。待发送由扫描写入,本模块只读取。
依赖:extensions.db、EquipmentAcceptanceSendRecord、EquipmentAcceptanceSendFile、utc_iso。
逻辑:由发送记录列表和 Excel 下载接口调用。列表按 send_record_ids 把 Excel 挂到对应行,不读文件字节。
"""
from __future__ import annotations
from typing import Any
from sqlalchemy.orm import defer
from app.core.errors import NotFoundError
from app.core.response import utc_iso
from app.extensions import db
from app.models.equipment_acceptance import EquipmentAcceptanceSendRecord
from app.models.equipment_acceptance import EquipmentAcceptanceSendFile, EquipmentAcceptanceSendRecord
def list_send_records(*, page: int, page_size: int) -> dict[str, Any]:
@@ -36,21 +39,122 @@ def list_send_records(*, page: int, page_size: int) -> dict[str, Any]:
.limit(page_size)
.all()
)
file_rows = _file_rows_for([row.id for row in rows])
return {
"items": [send_record_payload(row) for row in rows],
"items": [
send_record_payload(row, _files_for_record(row.id, file_rows))
for row in rows
],
"total": total,
"page": page,
"page_size": page_size,
}
def send_record_payload(row: EquipmentAcceptanceSendRecord) -> dict[str, Any]:
def list_send_files(*, limit: int = 20) -> list[dict[str, Any]]:
"""
列出最近留下的收件人 Excel,不含文件字节。
核心逻辑:按创建时间倒序。发送失败的文件也返回,方便对照当时准备发出的明细。
Args:
limit: 最多返回条数,上限 50。
Returns:
文件名、收件人、状态和发送时间。
"""
limit = min(50, max(1, limit))
rows = (
db.session.query(EquipmentAcceptanceSendFile)
.order_by(EquipmentAcceptanceSendFile.created_at.desc(), EquipmentAcceptanceSendFile.id.desc())
.limit(limit)
.all()
)
return [send_file_payload(row) for row in rows]
def get_send_file(file_id: int) -> EquipmentAcceptanceSendFile:
"""
取出一份已归档的 Excel。
Args:
file_id: 文件行主键。
Returns:
含字节的文件行。
Raises:
NotFoundError: 记录不存在或没有文件内容。
"""
row = db.session.get(EquipmentAcceptanceSendFile, file_id)
if row is None or not row.excel_file_data:
raise NotFoundError("设备验收预警附件不存在")
return row
def send_file_payload(row: EquipmentAcceptanceSendFile) -> dict[str, Any]:
"""列表用的文件摘要。不返回 Excel 字节。"""
return {
"id": row.id,
"recipient_name": row.recipient_name,
"excel_file_name": row.excel_file_name,
"excel_file_size": row.excel_file_size,
"status": row.status,
"sent_at": utc_iso(row.sent_at),
"created_at": utc_iso(row.created_at),
}
def _file_rows_for(record_ids: list[int]) -> list[EquipmentAcceptanceSendFile]:
"""
取出可能挂在这些发送记录上的 Excel 摘要。
核心逻辑:延迟加载文件字节,只留下文件名和记录编号,避免列表把整份 xlsx 读进内存。
Args:
record_ids: 当前页发送记录主键。为空时不查。
Returns:
归档文件行,不含 excel_file_data。
"""
if not record_ids:
return []
return (
db.session.query(EquipmentAcceptanceSendFile)
.options(defer(EquipmentAcceptanceSendFile.excel_file_data))
.order_by(EquipmentAcceptanceSendFile.id.asc())
.all()
)
def _files_for_record(record_id: int, file_rows: list[EquipmentAcceptanceSendFile]) -> list[dict[str, Any]]:
"""
挑出包含这条发送记录的 Excel。
核心逻辑:send_record_ids 里有这条记录才挂上。没有文件名的不展示。
Args:
record_id: 发送记录主键。
file_rows: 已去掉文件字节的归档行。
Returns:
下载按钮需要的 id 和文件名。
"""
found: list[dict[str, Any]] = []
for row in file_rows:
ids = {int(item) for item in list(row.send_record_ids or []) if item}
if record_id in ids and row.excel_file_name:
found.append({
"id": row.id,
"excel_file_name": row.excel_file_name,
})
return found
def send_record_payload(
row: EquipmentAcceptanceSendRecord,
files: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""
把一条发送记录收成接口数据。
核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。
核心逻辑:单号和主送、抄送用写入时的快照,不回读当前岗位。Excel 只带文件名和主键。
Args:
row: 本地发送记录。
files: 这份记录出现过的归档 Excel。
Returns:
页签表格用的字段。
"""
@@ -68,4 +172,5 @@ def send_record_payload(row: EquipmentAcceptanceSendRecord) -> dict[str, Any]:
"sent_at": utc_iso(row.sent_at),
"error_message": row.error_message,
"created_at": utc_iso(row.created_at),
"files": files or [],
}
@@ -73,6 +73,87 @@ _NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'})
_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'})
def resolve_satisfied_supplement_conflicts(candidate: Any) -> int:
"""
裸数字启发式冲突的字段若已有正式采纳裁决,自动标记已解决。
AI 触发时机:Run 收口持久化完成后调用(或修复脚本对存量 Candidate 执行);
投影与资格门禁共用 current_open_candidate_conflicts,标记 resolved 后
「字段冲突已解决」即达成,不再阻断提交订单。
核心逻辑:supplement_field_conflict 的定位证据来自邮件补充的裸数字候选;
当该字段的字段级裁决已为 accepted(PO 行收敛唯一路径或正式值源写入均算),
「多候选待人工选择」的前提消失——采纳即裁决。仅标记 resolution_status,
不删除审计记录,也不改动任何已写入的字段值。同一 field_code 可能在表头与
行级各配置一个字段:任一位置的裁决 accepted 即视为已满足。
Returns:
int: 实际标记为已解决的冲突条数。
"""
from sqlalchemy.orm.attributes import flag_modified
from app.models import (
ShippingOrderFieldDecision,
ShippingOrderSchemaVersion,
)
conflicts = candidate.conflicts_json if isinstance(candidate.conflicts_json, list) else []
if not conflicts:
return 0
extraction_id = (
getattr(candidate, 'order_extraction_id', None)
or getattr(candidate, 'extraction_id', None)
)
if extraction_id is None:
return 0
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id))
version = (
db.session.get(ShippingOrderSchemaVersion, int(extraction.schema_version_id))
if extraction is not None and extraction.schema_version_id is not None else None
)
definition = (version.definition_json or {}) if version is not None else {}
# 同一 field_code 可能在表头与行级各配置一个字段(如预约单号):任一位置
# 的裁决 accepted 即视为该字段冲突已满足。
field_id_candidates: dict[str, set[str]] = {}
for item in definition.get('fields') or []:
if not isinstance(item, dict):
continue
code = str(item.get('field_code') or '').strip()
fid = str(item.get('field_id') or '').strip()
if code and fid:
field_id_candidates.setdefault(code, set()).add(fid)
changed = 0
for item in conflicts:
if not isinstance(item, dict):
continue
if str(item.get('reason') or '') != 'supplement_field_conflict':
continue
if str(item.get('resolution_status') or 'unresolved').strip() == 'resolved':
continue
field_code = str(item.get('field') or '').strip()
field_id_set = field_id_candidates.get(field_code) or set()
line_index = item.get('line_index')
line_id = int(line_index) if line_index is not None and int(line_index) >= 0 else None
decision = None
for field_id in sorted(field_id_set):
decision = ShippingOrderFieldDecision.query.filter_by(
extraction_id=int(extraction_id), field_id=field_id, line_id=line_id,
).first()
if decision is not None and decision.decision_status == 'accepted':
break
decision = None
if decision is None or decision.decision_status != 'accepted':
continue
item['resolution_status'] = 'resolved'
item['resolution'] = 'auto_scoped_value_accepted'
changed += 1
if changed:
from sqlalchemy.orm.attributes import flag_modified as _fm
_fm(candidate, 'conflicts_json')
return changed
def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) -> bool:
"""按冻结字段配置判断证据缺失是否只是可选字段诊断。
@@ -169,7 +169,7 @@ class ShippingQueryShortageDetailsAction:
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
task = _require_task(ctx)
yield TurnEvent(event="step.started", data={"step_id": "query_shortage_details", "label": "查询缺口明细..."})
detail = serialize_task_detail(task)
detail = serialize_task_detail(task, viewer_user_id=int(ctx.user_id))
content = format_shortage_details_message(detail if isinstance(detail, dict) else {})
yield from stream_text_events(content, payload={"task_no": task.task_no})
yield TurnEvent(event="step.completed", data={"step_id": "query_shortage_details"})
@@ -1,10 +1,13 @@
"""
services/shipping_notice/customer_resolution_service.py
用途:提供订单任务的唯一客户识别结果读取与确认入口。
依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer。
用途:提供订单任务的唯一客户识别结果读取、确认与确认后改绑入口。
依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer、
ShippingNotice、ShippingOrderSnapshot、order_edit_window_service、order_freeze_service、audit_service。
逻辑:客户身份来自已发布规则生成的证据快照;订单字段(包括 bill_to)只能作为证据,
不能承担客户角色或流程门禁真相。
不能承担客户角色或流程门禁真相。确认后改绑(rebind_confirmed_customer)仅在订单
编辑窗 header 可编辑(无 Export Artifact 且无活动 Gate Attempt)时允许直接修改
确认结果,并原地刷新冻结快照客户(快照表 uq task_id 唯一约束决定不可另建新行)。
"""
from __future__ import annotations
@@ -14,7 +17,14 @@ from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderTask
from app.models import (
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingNotice,
ShippingOrderCandidate,
ShippingOrderSnapshot,
ShippingOrderTask,
)
def resolution_for_task(task: Any) -> ShippingCustomerShadowResolution | None:
@@ -74,3 +84,265 @@ def confirm_customer_resolution(
resolution.status = 'confirmed'
db.session.flush()
return resolution
# 改绑后 audit 事件类型:已纳入 progress_audit_contract.REVIEW_WORKBENCH_AUDIT_EVENT_TYPES
# 冻结字典(review_* snake_case 命名;review_customer_confirmed 专指首次确认,改绑独立成码)。
REBIND_AUDIT_EVENT_TYPE = 'review_customer_rebound'
def _order_notice_for_task(task: Any) -> ShippingNotice | None:
"""回读该正式订单的任一通知作为编辑窗谓词入口;editable_scope 会按 order_task_id 聚合全部通知。"""
return (
ShippingNotice.query
.filter(ShippingNotice.order_task_id == int(task.id))
.order_by(ShippingNotice.id.asc())
.first()
) if getattr(task, 'id', None) is not None else None
def _review_case_no_for_task(task: Any) -> str | None:
"""
经建单确认修订反查正式任务所属复核 Case 编号(order_edit_window_service 同款反查模式)。
核心逻辑:ShippingOrderReviewConfirmedRevision.case_id → ShippingOrderReviewCase.case_no,
取最新一条修订;无修订(历史数据)时返回 None,审计事件照常落库。
"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewConfirmedRevision
if getattr(task, 'id', None) is None:
return None
row = (
db.session.query(ShippingOrderReviewCase.case_no)
.join(
ShippingOrderReviewConfirmedRevision,
ShippingOrderReviewConfirmedRevision.case_id == ShippingOrderReviewCase.id,
)
.filter(ShippingOrderReviewConfirmedRevision.task_id == int(task.id))
.order_by(ShippingOrderReviewConfirmedRevision.id.desc())
.first()
)
return str(row[0]).strip() or None if row is not None else None
def _assert_rebind_window_open(task: Any) -> None:
"""
改绑编辑窗守卫(fail-closed):header 不可编辑即拒绝,不区分原因放行。
核心逻辑:editable_scope(order_task)['header'] = 全部通知无 Export Artifact 且无活动
Gate Attempt;尚无通知的未发货订单视为可编辑。details 区分 excel_exists / active_attempt
供前端定位(“已产生发货通知/Excel,请先走撤销流程” vs 系统处理中)。
"""
from app.services.shipping_notice import order_edit_window_service as order_edit_window
notice = _order_notice_for_task(task)
if notice is None:
return
scope = order_edit_window.editable_scope(notice)
if bool(scope.get('header')):
return
excel_exists = any(
order_edit_window._notice_has_export_artifact(item)
for item in order_edit_window._order_notices(notice)
)
active_attempt = order_edit_window.order_has_active_attempt(notice)
raise ConflictError(
'Customer rebind is blocked after shipping notice or Excel generation',
code='SHIPPING.CUSTOMER_REBIND_BLOCKED',
details={'excel_exists': excel_exists, 'active_attempt': active_attempt},
)
def rebind_allowed_for_task(task: Any) -> bool:
"""
判定正式任务当前是否允许改绑确认客户(工作台「修改客户」按钮谓词,只读 fail-closed)。
核心逻辑:识别结果已确认,且编辑窗 header 可编辑(全部通知无 Export Artifact 且
无活动 Gate Attempt)。与 rebind_confirmed_customer 守卫①②同源;并发语义由 API 层
expected_order_data_version 承担,此处为只读投影不下发并发状态。
Args:
task: 正式任务(ShippingOrderTask/ShippingNotice,按 resolution_for_task 语义解析)。
Returns:
True 表示当前可改绑;False 表示未确认、Excel 已产生或存在活动 Attempt。
"""
row = resolution_for_task(task)
if row is None or row.status != 'confirmed' or not row.confirmed_customer_id:
return False
notice = _order_notice_for_task(task)
if notice is None:
return True
from app.services.shipping_notice import order_edit_window_service as order_edit_window
return bool(order_edit_window.editable_scope(notice).get('header'))
def _append_rebind_audit(
*,
task: Any,
previous_customer_id: int,
new_customer: ShippingCustomer,
actor_id: int,
reason: str | None,
) -> None:
"""写改绑审计事件:before/after 携带原/新确认客户(键须命中审计快照白名单),并挂 review_case_no 供 Case 时间线查询。"""
from app.services.shipping_notice.audit_service import append_shipping_audit_event
task_no = str(getattr(task, 'task_no', '') or '')
version = int(getattr(task, 'order_data_version', 0) or 1)
append_shipping_audit_event(
event_type=REBIND_AUDIT_EVENT_TYPE,
aggregate_type='shipping_task',
aggregate_id=task_no,
task_no=task_no,
review_case_no=_review_case_no_for_task(task),
actor_type='user',
actor_id=int(actor_id),
action='rebind_confirmed_customer',
result='success',
reason=str(reason or '').strip() or None,
before={'previous_value': previous_customer_id, 'task_no': task_no, 'order_data_version': version},
after={'new_value': int(new_customer.id), 'task_no': task_no, 'order_data_version': version},
metadata={
'previous_customer_id': int(previous_customer_id),
'confirmed_customer_id': int(new_customer.id),
},
)
def _refresh_frozen_snapshot_customer(task: Any, customer: ShippingCustomer) -> ShippingOrderSnapshot | None:
"""
原地刷新冻结快照的订购客户事实(customer_id / 客户简称)。
核心逻辑:快照表对 task_id 有唯一约束(uq_shipping_order_snapshots_task),且快照行身份
被 Notice 行 / 波次行 / 库存匹配以 snapshot_line_id 引用,因此改绑不能删行重建,只能按
新客户刷新客户身份字段;单头模板文本(customer_code/customer_name 等单据原文事实)不动。
"""
snapshot_id = getattr(task, 'order_snapshot_id', None)
if not snapshot_id:
return None
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id))
if snapshot is None:
return None
snapshot.customer_id = int(customer.id)
snapshot.customer_short_code_snapshot = str(getattr(customer, 'short_code', None) or '')
db.session.flush()
return snapshot
def rebind_confirmed_customer(
task: Any,
*,
new_customer_id: int,
actor_id: int,
expected_order_data_version: int,
reason: str | None = None,
) -> dict[str, Any]:
"""
确认客户改绑:直接修改已确认的客户识别结果并刷新冻结快照客户。
核心逻辑:守卫顺序固定 fail-closed——⓪客户端乐观锁版本比较(expected_order_data_version
必填,与任务当前 order_data_version 不一致即 409,写任何数据之前执行,保证冲突零副作用;
freeze 对已冻结任务幂等早退、不重复做版本校验,故版本比较只在此处);①识别结果已确认
(未确认走既有确认流程);②订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无
活动 Gate Attempt,即发货通知/Excel 未产生);③新客户存在、启用且 ≠ 当前确认客户。
通过后更新确认结果(追加 rebind 证据记录,保持 evidence_json 与 identity_rule_set_checksum
非空冻结契约)、写审计、原地刷新快照客户,最后按 freeze 契约复核并返回快照。
Args:
task: 正式订单任务 ShippingOrderTask(经 candidate_id 反查唯一识别结果)。
new_customer_id: 目标标准客户 id;必须存在且启用。
actor_id: 执行改绑的用户 id(必填,审计与 manual 冻结要求)。
expected_order_data_version: 客户端读到的订单数据版本;与任务当前版本不一致时拒绝,
防止并发编辑被静默覆盖(对齐 wave 路由 expected_draft_version 模式)。
reason: 可选改绑原因;进入证据记录、审计与确认原因链。
Returns:
dict: {'resolution': 更新后的识别结果行, 'snapshot': 客户已刷新的冻结快照}。
Raises:
ValidationError: 缺少执行人(SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED,内部调用契约)。
ConflictError: 订单数据版本不一致(SHIPPING.ORDER_DATA_VERSION_MISMATCH)、识别结果
未确认(SHIPPING.CUSTOMER_RESOLUTION_REQUIRED)、编辑窗关闭
(SHIPPING.CUSTOMER_REBIND_BLOCKED,details 含 excel_exists/active_attempt)、
新客户停用(SHIPPING.CUSTOMER_INACTIVE)或与当前客户相同
(SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER)。
NotFoundError: 目标客户不存在(SHIPPING.CUSTOMER_NOT_FOUND)。
"""
if not actor_id:
# 内部调用契约缺失(非编辑窗状态),与 SHIPPING.CUSTOMER_REBIND_BLOCKED 的 A 管控语义区分。
raise ValidationError('Customer rebind requires an operator', code='SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED')
# [STEP 1] 守卫⓪:客户端版本比较在写任何数据之前执行;freeze 幂等早退不重复校验。
actual_version = int(getattr(task, 'order_data_version', 0) or 1)
if actual_version != int(expected_order_data_version):
raise ConflictError(
'Order data version has changed',
code='SHIPPING.ORDER_DATA_VERSION_MISMATCH',
details={'expected': int(expected_order_data_version), 'actual': actual_version},
)
# [STEP 2] 守卫①:识别结果已确认(未确认走既有识别候选确认流程,不在此补确认)。
resolution = resolution_for_task(task)
if (
resolution is None or str(resolution.status or '') != 'confirmed'
or resolution.confirmed_customer_id is None
):
raise ConflictError(
'Confirmed customer resolution is required before rebind',
code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED',
)
# [STEP 3] 守卫②:编辑窗 header 谓词(发货通知/Excel 已产生或系统处理中即拒绝)。
_assert_rebind_window_open(task)
# [STEP 4] 守卫③:新客户存在、启用且 ≠ 当前确认客户。
customer = db.session.get(ShippingCustomer, int(new_customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if str(customer.status or '') != 'active':
raise ConflictError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
previous_customer_id = int(resolution.confirmed_customer_id)
if int(customer.id) == previous_customer_id:
raise ConflictError(
'Rebind target equals the current confirmed customer',
code='SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER',
)
# [STEP 5] 更新确认结果:追加 rebind 证据记录(保留原识别证据;checksum 契约不动)。
resolution.confirmed_customer_id = int(customer.id)
resolution.evidence_json = [
*(list(resolution.evidence_json or [])),
{
'source': 'manual_rebind',
'rebind': {
'previous_customer_id': previous_customer_id,
'new_customer_id': int(customer.id),
'actor_id': int(actor_id),
'reason': str(reason or '').strip() or None,
'rebound_at': datetime.utcnow().isoformat(),
},
},
]
db.session.flush()
# [STEP 6] 审计:before/after 携带原/新确认客户(与业务写入同事务,挂 review_case_no)。
_append_rebind_audit(
task=task, previous_customer_id=previous_customer_id,
new_customer=customer, actor_id=int(actor_id), reason=reason,
)
# [STEP 7] 快照客户刷新 + freeze 契约复核:manual 冻结校验 actor_id;已冻结任务走幂等
# 早退返回当前快照(不重复版本校验——版本一致性已由守卫⓪保证)。
snapshot = _refresh_frozen_snapshot_customer(task, customer)
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
snapshot = freeze_order_snapshot(
task,
actor_id=int(actor_id),
expected_order_data_version=int(expected_order_data_version),
freeze_mode='manual',
)
db.session.flush()
return {'resolution': resolution, 'snapshot': snapshot}
@@ -47,6 +47,7 @@ from app.services.shipping_notice.order_candidate_builder import (
build_email_order_index,
merge_attachment_candidate,
)
from app.services.shipping_notice.reservation_id import find_bare_numeric_reservation_candidates
BODY_ATTACHMENT_KEY = 'body'
@@ -665,6 +666,13 @@ def persist_documents_and_candidates(
schema_definition=definition,
)
supplement['document_id'] = int(body_doc.id)
# [裸数字兜底] 无表头数据表解析不出补充行时,预置「整格纯数字」表格候选;
# 是否采纳由 merge_email_supplements 在合并末段结合已提取字段值裁决。
supplement['reservation_candidates'] = find_bare_numeric_reservation_candidates(
html_tables=canonical_html_tables,
content_hash=str(body_doc.content_hash or ''),
)
supplement['email_subject'] = str(email_meta.get('subject') or '')
body_doc.order_extraction_result_json = _json_safe_value({
'email_supplement': supplement,
})
@@ -680,6 +688,7 @@ def persist_documents_and_candidates(
'row_count': len(supplement.get('rows') or []),
'issue_codes': list(supplement.get('issues') or []),
'parser_version': supplement.get('version'),
'reservation_candidate_count': len(supplement.get('reservation_candidates') or []),
},
)
active_keys.add(BODY_ATTACHMENT_KEY)
@@ -95,6 +95,10 @@ class ProfileMatchCandidate(BaseModel):
dimension_states: dict[str, MatchDimensionState] = Field(default_factory=dict)
margin_to_next: float | None = Field(default=None, ge=0, le=1)
coordinate_transform: dict[str, Any] | None = None
identity_rescue_assisted: bool = Field(
default=False,
description='该候选的表头身份由表头带证据补洞达成(order_profile_ocr_rescue)。',
)
class ProfileMatchResult(BaseModel):
@@ -124,6 +128,10 @@ class ProfileMatchResult(BaseModel):
margin: float | None = Field(default=None, ge=0, le=1)
scoring_policy_version: str = MATCHER_POLICY_ID
parse_validation: dict[str, Any] | None = None
identity_rescue_source: str | None = Field(
default=None,
description='本次唯一命中的表头带证据补洞来源(acroform_widget / ocr_coordinate);None=未补洞。',
)
def match_frozen_coordinate_profiles(
@@ -1088,7 +1096,10 @@ def _header_normalized_words(text: str) -> list[str]:
核心逻辑:词级原子化与 Schema 别名短语匹配共用同一切词口径,保证两条路径
产出的身份原子完全同源;返回非空小写词序列(中文等非 [a-z0-9] 文本切词为空,
调用方按各自的跳过策略处理)。
调用方按各自的跳过策略处理)。有意不拆驼峰:真实表头大小写不可靠
('UnitCost'/'unitcost'/'UNITCOST' 皆可能出现),仅按大小写边界拆分对全小写
渲染不生效,反而制造两侧不对称;camelCase 别名的对齐由
schema_canonical_header_atoms/_tokens 的连写短语键承担。
"""
normalized = _HEADER_PAREN_GLOSS.sub(' ', str(text).casefold())
normalized = re.sub(r"['’]", '', normalized)
@@ -1180,10 +1191,12 @@ def schema_canonical_header_atoms(
具体措辞。未配置别名时零行为变化,完全退化为词级原子。
核心逻辑:
- header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零风险);
- header_to_field 为 None/空 dict 时直接返回词级原子(兼容旧签名,零行为变化);
- 先把每个别名 key 经与 token 完全相同的词管线(剥括号注记 → casefold →
去撇号 → 按非字母数字切词)转为词元组;同一词元组 casefold 后指向多个
field_code 时整体弃用该短语——身份归属不允许歧义;
- 多词别名额外注册去空格连写短语键([STEP 1.1],如 'Unit Cost' ↔
'unitcost'),使 camelCase 无分隔符表头与空格措辞收敛到同一 field 原子;
- 逐 token 用同一词管线切词后做贪心最长短语匹配:命中即消费整段并产出
field::<field_code> 原子(短语内单词不再残留);未命中的剩余单词沿用词级
原子的既有过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS);
@@ -1218,6 +1231,19 @@ def schema_canonical_header_atoms(
if len(codes) == 1
}
# [STEP 1.1] 连写短语键:camelCase 别名经 normalize_table_header 拆成
# 'Unit Cost' 类带空格键,但真实表头 token 常以无分隔符形式出现且大小写
# 不可靠('UnitCost'/'unitcost'),按大小写边界拆词对全小写渲染不生效。
# 为多词短语额外注册去空格连写键,使连写/空格/混合大小写拼写收敛到同一
# field 原子;只新增、不覆盖既有键,连写键跨字段歧义时整体弃用(同 [STEP 1])。
joined_candidates: dict[tuple[str, ...], set[str]] = {}
for words, code in phrase_to_field.items():
if len(words) > 1:
joined_candidates.setdefault((''.join(words),), set()).add(code)
for joined, codes in joined_candidates.items():
if len(codes) == 1 and joined not in phrase_to_field:
phrase_to_field[joined] = next(iter(codes))
# [STEP 2] 逐 token 贪心最长短语匹配;未命中单词走既有词级原子过滤。
atoms: set[str] = set()
for token in tokens:
@@ -1269,6 +1295,7 @@ def schema_canonical_header_tokens(
- header_to_field 为 None/空 dict 时原样返回输入列表(零归一、零行为变化);
- 短语字典构建与 atoms [STEP 1] 完全同源:别名 key 经同一词管线转词元组,
同一词元组 casefold 后指向多个 field_code 时整体弃用(身份不允许歧义);
多词别名同样注册连写短语键([STEP 1.1],与 atoms 同一口径);
- 逐 token 贪心最长短语匹配:命中片段消费整段并在原位置产出**单个**
`field::<field_code>` 列表项(短语内单词不残留);未命中词按 atoms 同一
过滤(长度 >= _HEADER_ATOM_MIN_LEN 且不在 _HEADER_ATOM_STOPWORDS)原词保留;
@@ -1301,6 +1328,17 @@ def schema_canonical_header_tokens(
if len(codes) == 1
}
# [STEP 1.1] 连写短语键:与 schema_canonical_header_atoms 的 [STEP 1.1] 同一
# 口径——为 camelCase 多词别名注册去空格连写键('Unit Cost' ↔ 'UnitCost'/
# 'unitcost'),只新增、不覆盖既有键,歧义整体弃用。
joined_candidates: dict[tuple[str, ...], set[str]] = {}
for words, code in phrase_to_field.items():
if len(words) > 1:
joined_candidates.setdefault((''.join(words),), set()).add(code)
for joined, codes in joined_candidates.items():
if len(codes) == 1 and joined not in phrase_to_field:
phrase_to_field[joined] = next(iter(codes))
# [STEP 2] 逐 token 贪心最长短语匹配;序列语义:命中产出单个标记列表项,
# 未命中单词原样保留(沿用 atoms 过滤),整体保序、允许重复。
canonical: list[str] = []
@@ -0,0 +1,418 @@
"""
backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py
用途:模板路由失败时的「表头带证据补洞」定向补救(Route B)。
依赖:order_profile_matcher(匹配器与观测管线)、xfa_acroform(AcroForm 控件定位)、
native_pdf(pdfium 渲染)、ocr_pdf(RapidOCR)、file_assets 服务、tool_common 配置。
逻辑:常规匹配 layout_drift/no_match 且存在「仅表头判别冲突 + 观测原子为期望原子
真子集」的可补救候选集合时,按优先级补齐页 1 主表表头带证据:
① AcroForm/XFA 控件展示值(确定性、精确坐标,覆盖供应商把表头文字放进
表单控件/矢量层的世代);② RapidOCR 表头带(纯扫描/图像兜底)。
补洞字形带 source 标记并入页 1 表头带后重跑完整匹配器;仅当结果恰好唯一
命中集合内某个候选时采纳并打 identity_rescue_source 标记,否则维持原判
(fail-closed 由构造保证:补洞引入外来原子会破坏候选自身集合全等,同时
满足多个候选则转 ambiguous,均被拒绝)。补洞字形只在本次匹配内存中生效,
禁止回写布局版本。
"""
from __future__ import annotations
import logging
import unicodedata
from typing import Any, Callable
from app.services.shipping_notice.document_layout.order_profile_matcher import (
ProfileMatchCandidate,
ProfileMatchResult,
_extract_matching_signature,
_header_token_atoms,
_observe_layout_features,
_profile_exclusion_regions,
_profile_termination_rules,
_resolve_coordinate_transform,
_signature_identity_header_tokens,
_translate_signature,
match_frozen_coordinate_profiles,
schema_canonical_header_atoms,
)
from app.services.shipping_notice.document_layout.order_profile import (
OrderCoordinateProfile,
)
logger = logging.getLogger(__name__)
# 与 ocr_pdf.OCR_CONFIDENCE_FLOOR 对齐;低于该置信度的 OCR 行不参与补洞。
OCR_RESCUE_CONFIDENCE_FLOOR = 0.8
# 表头带高度占主表高度的比例,与 _observe_header_candidates 的保守带一致。
_HEADER_BAND_RATIO = 0.30
_BAND_EPSILON = 0.005
def _fold_diacritics(text: str) -> str:
"""NFKD 折叠并剥离音变符号(Komárom→Komarom),与历史签名的无音变口径对齐。"""
decomposed = unicodedata.normalize('NFKD', str(text or ''))
return ''.join(ch for ch in decomposed if unicodedata.category(ch) != 'Mn')
def _candidate_header_atoms(
*,
raw_profile: dict[str, Any],
layout: dict[str, Any],
header_to_field: dict[str, str] | None,
) -> tuple[frozenset[str], frozenset[str], dict[str, Any]]:
"""按匹配器同一观测口径计算候选的期望/观测表头原子与观测特征。"""
signature_body, _meta = _extract_matching_signature(raw_profile)
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
profile = OrderCoordinateProfile(
profile_code=str(raw_profile.get('profile_code') or ''),
version=int(raw_profile.get('version') or 0),
document_match=definition.get('document_match'),
table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
coordinate_model=definition.get('coordinate_model') or {},
reference_page_frames=definition.get('reference_page_frames') or {},
)
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
transform, _reasons = _resolve_coordinate_transform(
profile=profile, pages=pages, page_glyphs=page_glyphs,
)
observed = _observe_layout_features(
layout=layout,
tables=[item for item in layout.get('tables') or [] if isinstance(item, dict)],
pages=pages,
glyph_tables=glyph_tables,
page_glyphs=page_glyphs,
signature=_translate_signature(signature=signature_body, coordinate_transform=transform),
termination_rules=_profile_termination_rules(profile),
exclusion_regions=_profile_exclusion_regions(profile),
)
expected_tokens = _signature_identity_header_tokens(signature_body)
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
if header_to_field:
expected_atoms = schema_canonical_header_atoms(expected_tokens, header_to_field)
observed_atoms = schema_canonical_header_atoms(observed_tokens, header_to_field)
else:
expected_atoms = _header_token_atoms(expected_tokens)
observed_atoms = _header_token_atoms(observed_tokens)
return expected_atoms, observed_atoms, observed
def _eligible_rescue_candidates(
*,
match: ProfileMatchResult,
profiles: list[dict[str, Any]],
layout: dict[str, Any],
header_to_field: dict[str, str] | None,
) -> dict[tuple[str, int], tuple[ProfileMatchCandidate, dict[str, Any]]]:
"""
甄别可补救候选集合:冲突仅表头判别、观测原子为期望原子真子集。
核心逻辑:近亲模板常各自缺不同的尾部列,多个候选可同时可补救——竞争裁决
交给补洞后的完整重跑(接受条件要求补洞后恰好唯一命中集合内候选);
观测侧存在期望之外的外来原子时该候选不可补救(不是单纯缺字)。
"""
profile_by_key = {
(str(item.get('profile_code') or ''), int(item.get('version') or 0)): item
for item in profiles if isinstance(item, dict)
}
eligible: dict[tuple[str, int], tuple[ProfileMatchCandidate, dict[str, Any]]] = {}
for candidate in match.candidates:
if sorted(candidate.reason_codes) != ['profile_header_discriminator_conflict']:
continue
key = (candidate.profile_code, candidate.version)
raw = profile_by_key.get(key)
if raw is None:
continue
expected_atoms, observed_atoms, _observed = _candidate_header_atoms(
raw_profile=raw, layout=layout, header_to_field=header_to_field,
)
if not (expected_atoms - observed_atoms) or (observed_atoms - expected_atoms):
continue
eligible[key] = (candidate, raw)
return eligible
def _glyphs_in_header_band(
*,
glyphs: list[dict[str, Any]],
page_width: float,
page_height: float,
primary_table_bbox: list[float] | None,
source: str,
) -> list[dict[str, Any]]:
"""把补洞字形过滤到主表表头带内(归一化坐标,含少量容差)并打来源标记。"""
if not primary_table_bbox or len(primary_table_bbox) != 4:
return []
if page_width <= 0 or page_height <= 0:
return []
x0, y0, x1, y1 = primary_table_bbox
band_height = max(0.001, y1 - y0) * _HEADER_BAND_RATIO
kept: list[dict[str, Any]] = []
for glyph in glyphs:
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
if not bbox:
continue
center_x = (float(bbox.get('x0') or 0) + float(bbox.get('x1') or 0)) / 2 / page_width
center_y = (float(bbox.get('y0') or 0) + float(bbox.get('y1') or 0)) / 2 / page_height
if (
x0 - _BAND_EPSILON <= center_x <= x1 + _BAND_EPSILON
and y0 - _BAND_EPSILON <= center_y <= y0 + band_height + _BAND_EPSILON
):
marked = dict(glyph)
marked['source'] = source
kept.append(marked)
return kept
def _text_to_char_glyphs(text: str, bbox: dict[str, float]) -> list[dict[str, Any]]:
"""
把控件展示值按词分配展开为字形(与 OCR 字形同构,供视觉行重组)。
核心逻辑:词内字符连续;词间与控件尾部预留 > 0.75×字符宽的几何空隙,
保证 positioned_token_spans 的显著间隔分词能恢复出与签名一致的 token
切分(否则相邻控件字形会被并词,如 'ETD'+'ETA' → 'etdeta')。
"""
folded = _fold_diacritics(text)
words = [word for word in folded.split() if word.strip()]
if not words:
return []
bbox_width = max(0.01, float(bbox['x1']) - float(bbox['x0']))
usable_ratio = 0.7
word_gap_ratio = 1.2
total_chars = sum(len(word) for word in words)
char_width = bbox_width * usable_ratio / max(1, total_chars)
out: list[dict[str, Any]] = []
x = float(bbox['x0'])
y0, y1 = float(bbox['y0']), float(bbox['y1'])
for word in words:
for character in word:
out.append({'text': character, 'bbox': {
'x0': x, 'y0': y0, 'x1': x + char_width, 'y1': y1,
}})
x += char_width
x += char_width * word_gap_ratio
return out
def _default_read_asset_bytes(asset_id: int) -> bytes:
"""按 id 加载 FileAsset 后读取字节;read_asset_bytes 接收 ORM 对象而非 id。"""
from app.extensions import db
from app.models import FileAsset
from app.services.file_assets.service import read_asset_bytes
asset = db.session.get(FileAsset, int(asset_id))
if asset is None:
raise LookupError(f'file asset not found: {asset_id}')
return read_asset_bytes(asset)
def _collect_rescue_glyphs(
*,
document: Any,
page: dict[str, Any],
primary_table_bbox: list[float] | None,
page_images_fn: Callable[[bytes], list[Any]] | None,
ocr_lines_fn: Callable[..., list[Any]] | None,
read_asset_fn: Callable[[int], bytes],
) -> tuple[list[dict[str, Any]], str] | None:
"""
按优先级收集表头带补洞字形。
① AcroForm/XFA 控件展示值(确定性);② 整带 RapidOCR(图像兜底)。
Returns:
(字形列表, 来源标记) 或 None(无可用证据)。
"""
page_width = float(page.get('width') or 0)
page_height = float(page.get('height') or 0)
asset_id = int(getattr(document, 'asset_id', 0) or 0)
if read_asset_fn is None:
read_asset_fn = _default_read_asset_bytes
# [STEP 1] AcroForm/XFA 控件文本:确定性坐标与文本,优先于 OCR。
if asset_id > 0:
try:
from app.services.shipping_notice.document_layout.xfa_acroform import (
read_acroform_widgets,
)
content = read_asset_fn(asset_id)
widgets = [
widget for widget in read_acroform_widgets(content)
if int(widget.page_no) == 1 and str(widget.value or '').strip()
]
widget_glyphs: list[dict[str, Any]] = []
for widget in widgets:
nb = widget.normalized_bbox or {}
if not all(key in nb for key in ('x0', 'y0', 'x1', 'y1')):
continue
widget_glyphs.extend(_text_to_char_glyphs(str(widget.value), {
'x0': float(nb['x0']) * page_width,
'y0': float(nb['y0']) * page_height,
'x1': float(nb['x1']) * page_width,
'y1': float(nb['y1']) * page_height,
}))
band = _glyphs_in_header_band(
glyphs=widget_glyphs, page_width=page_width, page_height=page_height,
primary_table_bbox=primary_table_bbox, source='acroform_widget',
)
if band:
return band, 'acroform_widget'
except Exception: # noqa: BLE001 - 控件读取失败时回退 OCR 来源,补救不阻断主链
pass
# [STEP 2] 表头带 RapidOCR:渲染页 1 后 OCR(纯扫描/图像世代兜底)。
if asset_id <= 0:
return None
try:
if page_images_fn is None:
from app.services.shipping_notice.document_layout.native_pdf import (
extract_native_pdf_pages,
)
def page_images_fn(content: bytes) -> list[Any]:
return extract_native_pdf_pages(content, render_images=True)
if ocr_lines_fn is None:
from app.services.shipping_notice.document_layout.ocr_pdf import (
OCR_CONFIDENCE_FLOOR,
extract_ocr_lines,
)
def ocr_lines_fn(*args: Any, **kwargs: Any) -> list[Any]:
kwargs.setdefault('minimum_confidence', OCR_CONFIDENCE_FLOOR)
return extract_ocr_lines(*args, **kwargs)
pdf_pages = page_images_fn(read_asset_fn(asset_id))
first_page = next((item for item in pdf_pages if int(item.page_no) == 1), None)
if first_page is None or first_page.image is None:
return None
ocr_lines = ocr_lines_fn(
first_page.image,
page_width=first_page.width,
page_height=first_page.height,
minimum_confidence=OCR_RESCUE_CONFIDENCE_FLOOR,
)
if not ocr_lines:
return None
from app.services.shipping_notice.order_document_profile_service import (
_ocr_lines_to_page_characters,
)
ocr_glyphs = [
{**glyph, 'text': _fold_diacritics(str(glyph.get('text') or ''))}
for glyph in _ocr_lines_to_page_characters(lines=ocr_lines)
if str(glyph.get('text') or '').strip()
]
band = _glyphs_in_header_band(
glyphs=ocr_glyphs, page_width=page_width, page_height=page_height,
primary_table_bbox=primary_table_bbox, source='ocr_coordinate',
)
if band:
return band, 'ocr_coordinate'
return None
except Exception as exc: # noqa: BLE001 - 兜底来源失败时交回上层维持原判
# [PARAM_TUNING] 2026-10-14 test 事故(SNER-20261014-8EBAB7A1):AttributeError
# 炸穿本层令整个 Unit 技术失败。收口语义保持「静默回退」,但必须留观测痕
# 迹,否则只能靠 Unit error_message 反推。
logger.warning(
'order profile rescue glyphs failed document_id=%s error_type=%s',
int(getattr(document, 'id', 0) or 0),
type(exc).__name__,
)
return None
def rescue_match_with_header_ocr(
*,
match: ProfileMatchResult,
profiles: list[dict[str, Any]],
layout: dict[str, Any],
header_to_field: dict[str, str] | None,
document: Any,
match_fn: Callable[..., ProfileMatchResult] | None = None,
page_images_fn: Callable[[bytes], list[Any]] | None = None,
ocr_lines_fn: Callable[..., list[Any]] | None = None,
read_asset_fn: Callable[[int], bytes] | None = None,
) -> ProfileMatchResult:
"""
对路由失败结果尝试表头带证据补洞;任何不满足都原样返回(fail-closed)。
Args:
match: 常规匹配结果,须为 layout_drift / no_match 才尝试。
profiles: 冻结模板快照列表(与常规匹配同一份)。
layout: 已含原生坐标证据的运行期 Layout;禁止修改原对象。
header_to_field: Schema 表头别名契约(与常规匹配同源)。
document: ShippingOrderDocument;用于定位原始 PDF 资产。
match_fn / page_images_fn / ocr_lines_fn / read_asset_fn: 测试注入点,
默认分别使用真实匹配器、pdfium 渲染、RapidOCR 与资产读取。
Returns:
ProfileMatchResult:补洞成功返回带 identity_rescue_source 标记的唯一命中;
否则原样返回入参 match。
"""
if match.status not in {'layout_drift', 'no_match'} or not match.candidates:
return match
eligible = _eligible_rescue_candidates(
match=match, profiles=profiles, layout=layout, header_to_field=header_to_field,
)
if not eligible:
return match
try:
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page = pages.get('1') or pages.get(1)
if not isinstance(page, dict):
return match
_, _, probe_observed = _candidate_header_atoms(
raw_profile=next(iter(eligible.values()))[1],
layout=layout,
header_to_field=header_to_field,
)
rescued_glyphs = _collect_rescue_glyphs(
document=document, page=page,
primary_table_bbox=probe_observed.get('primary_table_bbox'),
page_images_fn=page_images_fn, ocr_lines_fn=ocr_lines_fn,
read_asset_fn=read_asset_fn,
)
if not rescued_glyphs:
return match
band_glyphs, rescue_source = rescued_glyphs
page_key = '1'
page_glyphs = dict(evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {})
page_glyphs[page_key] = list(page_glyphs.get(page_key) or []) + band_glyphs
augmented = dict(layout)
augmented_evidence = {**evidence, 'page_glyphs': page_glyphs}
merged_sources = dict(augmented_evidence.get('sources') or {})
merged_page_sources = dict(merged_sources.get('pages') or {})
merged_page_sources[page_key] = f"pdf_coordinate+{rescue_source}"
merged_sources['pages'] = merged_page_sources
augmented_evidence['sources'] = merged_sources
augmented['coordinate_evidence'] = augmented_evidence
re_match_fn = match_fn if match_fn is not None else match_frozen_coordinate_profiles
rescued = re_match_fn(
profiles=profiles, layout=augmented, header_to_field=header_to_field,
)
if rescued.status not in {'unique_match', 'selected_by_score'}:
return match
winner_key = (str(rescued.profile_code or ''), int(rescued.version or 0))
if winner_key not in eligible:
# 补洞改变了竞争格局(唤醒了集合外候选)——维持原判。
return match
marked_candidates = [
item.model_copy(update={'identity_rescue_assisted': (
str(item.profile_code or ''), int(item.version or 0)) == winner_key
})
for item in rescued.candidates
]
return rescued.model_copy(update={
'identity_rescue_source': rescue_source,
'candidates': marked_candidates,
})
except Exception as exc: # noqa: BLE001 - 补救属锦上添花:任何异常(含 AttributeError 等未预期类型错误)都回退原判,不得阻断抽取主链。
logger.warning(
'order profile rescue aborted document_id=%s error_type=%s',
int(getattr(document, 'id', 0) or 0),
type(exc).__name__,
)
return match
@@ -18,7 +18,10 @@ from zipfile import ZIP_DEFLATED, ZipFile
from app.core.errors import NotFoundError, ValidationError
from app.models import ShippingExportArtifact, ShippingNotice
from app.services.shipping_notice.query_service import get_task_for_user, resolve_task_export_download
from app.services.shipping_notice.query_service import (
get_task_visible_to_user,
resolve_task_export_download,
)
MAX_ARCHIVE_TASKS = 100
@@ -28,15 +31,17 @@ def _select_tasks(
user_id: int,
task_refs: list[str] | None,
selection_name: str,
is_admin: bool = False,
require_business_no: bool = False,
) -> tuple[list[ShippingNotice], str]:
"""按显式 task_no 或 business_no 选择当前用户通知,禁止部分越权成功。"""
"""按显式 task_no 或 business_no 选择当前用户可下载通知,禁止部分越权成功。"""
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_refs or []) if str(item or '').strip()))
if not normalized_tasks:
raise ValidationError(f'{selection_name} is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
tasks = []
for task_no in normalized_tasks:
task = get_task_for_user(task_no, user_id)
# 下载授权与单票导出同一谓词:创建者或管理员(可下载=可见)。
task = get_task_visible_to_user(task_no, user_id, is_admin=is_admin)
# 导出归档是正式 Notice 边界;OT 尚未生成正式单据时不可进入 Artifact 查询。
if not isinstance(task, ShippingNotice) or (
require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper()
@@ -90,10 +95,17 @@ def build_export_archive(
user_id: int,
task_nos: list[str] | None = None,
business_nos: list[str] | None = None,
is_admin: bool = False,
) -> tuple[BinaryIO, str, dict]:
"""
生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。
Args:
user_id: 当前下载用户;与 ``is_admin`` 共同构成下载授权谓词口径。
task_nos: 按 SN 技术号选择(与 business_nos 二选一)。
business_nos: 按发货通知单号选择(与 task_nos 二选一)。
is_admin: 是否平台管理员;管理员可打包其可见的正式 Notice。
Returns:
(定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。
"""
@@ -105,6 +117,7 @@ def build_export_archive(
user_id=user_id,
task_refs=selection_values,
selection_name=selection_name,
is_admin=is_admin,
require_business_no=business_nos is not None,
)
artifacts = _ready_artifacts(tasks)
@@ -115,11 +128,16 @@ def build_export_archive(
included = 0
with ZipFile(stream, mode='w', compression=ZIP_DEFLATED) as archive:
for task in tasks:
# business_no 供端点按票写入访问审计(与单票下载同一 aggregate 口径)。
entry_base = {
'task_no': task.task_no,
'business_no': str(getattr(task, 'business_no', '') or ''),
}
task_artifacts = artifacts.get(int(task.id), []) if task.id is not None else []
if not task_artifacts:
entries.append({'task_no': task.task_no, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None})
entries.append({**entry_base, 'status': 'missing_artifact', 'artifact_no': None, 'file_name': None})
for artifact in task_artifacts:
entry = {'task_no': task.task_no, 'status': 'missing_file', 'artifact_no': artifact.artifact_no, 'file_name': None}
entry = {**entry_base, 'status': 'missing_file', 'artifact_no': artifact.artifact_no, 'file_name': None}
entry['artifact_no'] = artifact.artifact_no
path = Path(artifact.file_path)
if not path.is_file():
@@ -716,6 +716,255 @@ def freeze_manual_line_source_selection(
return result, all(bool(item['candidate_inventory_source_codes']) for item in line_projections)
def active_candidate_set_is_manually_pinned(
task: ShippingNotice,
*,
session: Session | None = None,
) -> bool:
"""
判断活动候选集是否含人工选源(「人工指定即定论」的统一判定入口)。
Args:
task: 当前 ShippingOrderTask。
session: 可选 Session。
Returns:
bool: True 表示人工已裁决候选源,自动重路由必须跳过。
"""
sess = session or db.session
active_set = (
sess.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
if getattr(task, 'active_inventory_candidate_set_id', None) is not None
else None
)
if active_set is None:
return False
if getattr(active_set, 'frozen_by_id', None) is not None:
return True
return any(
str(getattr(source, 'candidate_origin', '') or '').strip().lower() == 'manual_override'
for source in (active_set.sources or [])
)
def refresh_candidates_from_current_routing(
task: ShippingNotice,
*,
execution_id: int | None = None,
session: Session | None = None,
) -> bool:
"""
任务级:按当前库存源主数据与路由规则重跑裁决并重冻结候选集;返回是否产生新版本候选集。
【AI 触发时机】:仅「重新获取库存(RPA)」的任务级人工重取路径作为前置步骤调用;
禁止在轮询(poll)、自动首投路径调用——刷新是显式人工动作的伴随效果,不是隐式自动行为。
核心逻辑:
[守卫 1] 仅多候选未定源可刷新(task_frozen_inventory_source_codes > 1);源已定单
不得自动改源,换源走 override_line_inventory_source 行级覆写。
[守卫 2] 活动候选集含人工选源(frozen_by_id / candidate_origin='manual_override')
时跳过:人工指定即定论,禁止重路由洗掉人工裁决。
[STEP 1] 记录当前活动 set_id。
[STEP 2] adjudicate_and_apply_inventory_source(execution_id=...) 重裁决 + 幂等冻结
(freeze 服务 input_fingerprint 未变则复用旧集,零副作用;重裁决为 unresolved 时
apply 不落任何事实,活动集保持不变,同样视为无变化)。
[STEP 3] 活动集变化时冻结服务已内置旧版本下游失效(_invalidate_task_candidate_outputs:
匹配事实/准备 Attempt/RPA Attempt 等),此处仅补写任务事件供审计追溯。
Args:
task: 当前 ShippingOrderTask(须已冻结候选集)。
execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。
session: 可选 Session。
Returns:
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
"""
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.inventory_source_gate import adjudicate_and_apply_inventory_source
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
sess = session or db.session
if len(task_frozen_inventory_source_codes(task)) <= 1:
return False
if active_candidate_set_is_manually_pinned(task, session=sess):
return False
before = get_active_candidate_set(task)
before_set_id = int(before.id) if before is not None else None
adjudicate_and_apply_inventory_source(task, execution_id=execution_id)
sess.flush()
after = get_active_candidate_set(task)
after_set_id = int(after.id) if after is not None else None
if before_set_id == after_set_id:
return False
from app.services.shipping_notice.tool_common import log_task_event
log_task_event(
task,
'inventory_candidates_refreshed',
{
'scope': 'task',
'previous_set_id': before_set_id,
'new_set_id': after_set_id,
'source_codes': task_frozen_inventory_source_codes(task),
},
source='system',
)
return True
def refresh_line_candidates_from_current_routing(
task: ShippingNotice,
*,
line_no: int,
execution_id: int | None = None,
session: Session | None = None,
) -> bool:
"""
行级:按当前库存源主数据与路由规则重评单个订单行的候选源并重冻结候选集;返回是否产生新版本。
【AI 触发时机】:仅「重新获取库存(RPA)」的行级重抓(retry_inventory_preparation 携带
line_scope)作为前置步骤调用;禁止在轮询/自动首投路径调用。
核心逻辑:
[守卫 1] 目标行当前候选 >1(未定源)才重评;单源行已定,改源走行级覆写。
[守卫 2] 活动候选集含人工选源时跳过(与任务级刷新同一条红线:人工指定即定论)。
[STEP 1] 行级规则重评:_task_routing_lines(task) 按 line_no-1 取目标行(越界返回 False),
evaluate_inventory_source_rules(task=task, line=...) 得到规则原始候选,经
get_database_inventory_source 过滤停用源(对齐 _result_to_adjudication 语义);
仅接受 resolved/ambiguous 结论,unresolved 保持旧行为不刷新。
[STEP 2] 以活动集全量行为骨架构建 line_projections:目标行替换为新候选,其余行原样继承
(保留既有行候选,不做整单重路由)。
[STEP 3] freeze_candidates_for_task(candidates_frozen 裁决)幂等冻结;created_new 即新版
候选集(supersede 旧集时内置下游失效),写行级刷新任务事件并返回 True。
Args:
task: 当前 ShippingOrderTask(须已冻结候选集)。
line_no: 目标订单项次(1 基,对应冻结快照 line_no)。
execution_id: 当前 ProcessExecution id;透传冻结服务,避免重冻结撤销活动执行链。
session: 可选 Session。
Returns:
bool: True=产生新版本候选集(调用方随后沿用既有失效与重取链);False=无变化或不适用。
"""
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
from app.services.shipping_notice.inventory_source_rules import (
_task_routing_lines,
compute_routing_fingerprint,
evaluate_inventory_source_rules,
extract_routing_context,
)
sess = session or db.session
active_set = get_active_candidate_set(task)
if active_set is None:
return False
if active_candidate_set_is_manually_pinned(task, session=sess):
return False
existing_lines = {
int(row.line_no): row
for row in (active_set.lines or [])
if getattr(row, 'line_no', None) is not None
}
target = existing_lines.get(int(line_no))
if target is None:
return False
current_codes = [
str(code).strip().upper()
for code in (target.source_codes_json or [])
if str(code or '').strip()
]
if len(current_codes) <= 1:
return False
routing_lines = _task_routing_lines(task)
position = int(line_no) - 1
if position < 0 or position >= len(routing_lines):
return False
line_result = evaluate_inventory_source_rules(task=task, line=routing_lines[position])
line_status = str(getattr(line_result, 'status', '') or '').strip().lower()
if line_status not in {'resolved', 'ambiguous'}:
return False
new_codes: list[str] = []
for raw in (getattr(line_result, 'source_codes', None) or []):
code = str(raw or '').strip().upper()
if code and code not in new_codes and get_database_inventory_source(code) is not None:
new_codes.append(code)
if not new_codes:
return False
line_projections: list[dict[str, Any]] = []
union_codes: list[str] = []
for row_line_no in sorted(existing_lines):
row = existing_lines[row_line_no]
codes = (
new_codes
if row_line_no == int(line_no)
else [
str(code).strip().upper()
for code in (row.source_codes_json or [])
if str(code or '').strip()
]
)
for code in codes:
if code not in union_codes:
union_codes.append(code)
line_projections.append({
'line_no': row_line_no,
'source_line_no': str(getattr(row, 'source_line_no', '') or '') or None,
'part_number': getattr(row, 'part_number', None),
'reservation_id': getattr(row, 'reservation_id', None),
'candidate_inventory_source_codes': codes,
})
if not union_codes:
return False
context = extract_routing_context(task)
adjudication = InventorySourceAdjudication(
status='candidates_frozen',
method='line_refresh_reroute',
source_code=None,
connector_type=None,
warehouse_id=None,
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[{'source_code': code} for code in union_codes],
evidence=[{
'line_candidates_refresh': {
'line_no': int(line_no),
'previous_codes': current_codes,
'new_codes': new_codes,
},
}],
reason='line_refresh_reroute',
)
freeze_result = freeze_candidates_for_task(
task,
adjudication=adjudication,
line_projections=line_projections,
execution_id=execution_id,
session=sess,
)
if not freeze_result.created_new:
return False
from app.services.shipping_notice.tool_common import log_task_event
log_task_event(
task,
'inventory_candidates_refreshed',
{
'scope': 'line',
'line_no': int(line_no),
'previous_codes': current_codes,
'new_codes': new_codes,
'new_set_id': int(freeze_result.candidate_set_id),
},
source='system',
)
return True
def freeze_wave_notice_routing(
notice: ShippingNotice,
*,
@@ -21,6 +21,7 @@ from app.models import (
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingInventoryFile,
ShippingNotice,
ShippingOrderTask,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
@@ -82,8 +83,35 @@ def _candidate_set_filter(
return list(rows)
def resolve_inventory_fact_task(task: Any) -> Any:
"""
将库存事实读取对象归一为正式 OT。
核心逻辑:候选集/库存 Link 全部挂在 OT 上,而货代上传等入口按 business_no
加载 ShippingNotice——Notice 没有 active_inventory_candidate_set_id 字段,
直接查询会 fail-closed 成「库存源尚未确定」(历史缺陷:RPA 上传被恒拦截,
自动推进的 freight_upload_rpa 门禁也因此秒切人工)。OT 原样返回;Notice 沿
order_task_id 解析,缺绑定或 OT 不存在时原样返回,由上层无候选集语义继续
fail-closed。
Args:
task: ShippingOrderTask 或 ShippingNotice。
Returns:
归一后的 OT(或无法解析时的原对象)。
"""
if isinstance(task, ShippingNotice):
order_task_id = getattr(task, 'order_task_id', None)
if order_task_id is None:
return task
order_task = _session().get(ShippingOrderTask, int(order_task_id))
if order_task is not None:
return order_task
return task
def get_active_candidate_set(
task: ShippingOrderTask,
task: ShippingOrderTask | ShippingNotice,
*,
session: Session | None = None,
) -> ShippingInventoryCandidateSet | None:
@@ -92,7 +120,9 @@ def get_active_candidate_set(
核心逻辑:严格依赖 ShippingOrderTask.active_inventory_candidate_set_id;
指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。
传入 ShippingNotice 时先归一为其 order_task(见 resolve_inventory_fact_task)。
"""
task = resolve_inventory_fact_task(task)
candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None)
if candidate_set_id is None:
return None
@@ -2,8 +2,10 @@
services/shipping_notice/inventory_routing_engine.py
用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。
依赖:库存路由模型、冻结订单 Snapshot、routing_operators。
逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
依赖:库存路由模型、冻结订单 Snapshot、routing_operators、inventory_source_repository。
逻辑:行级评估先做「库存源线索直连」(冻结行 inventory_source_hint 经精确/唯一后缀解析启用源,
命中即 resolved,跳过全部规则层——含预约单号兜底规则;未命中 fail-open 落回规则层);
随后只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。
多候选为建单前正常结果(can_build=True);零候选或 require_manual_review 才阻断建单。
输出附带规则版本与命中规则摘要,供建单前重路由审计与前端展示;可用性过滤由资格服务完成。
"""
@@ -15,6 +17,7 @@ from datetime import datetime
from typing import Any
from app.models import ShippingInventoryRoutingRule, ShippingOrderSnapshot
from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources
from app.services.shipping_notice.routing_operators import matches_operator
@@ -88,6 +91,55 @@ def _matched_rule_summaries(rules: list[ShippingInventoryRoutingRule]) -> tuple[
)
def _resolve_source_from_hint(line_source_hint: str) -> str | None:
"""
库存源线索 → 启用源解析:精确 source_code 相等优先,否则启用源中唯一后缀命中。
无命中或多命中(后缀撞源)返回 None——调用方 fail-open 落回规则层,不以线索阻断流程。
"""
code = str(line_source_hint or '').strip().upper()
if not code:
return None
enabled_codes = [
normalized
for normalized in (
str(item.get('source_code') or '').strip().upper()
for item in list_database_inventory_sources(enabled_only=True)
)
if normalized
]
if code in enabled_codes:
return code
suffix_hits = [item for item in enabled_codes if item.endswith(code)]
return suffix_hits[0] if len(suffix_hits) == 1 else None
def _hint_routing_result(source_code: str) -> InventoryRoutingResult:
"""线索直连结果:resolved 单源,evidence 标明来源供审计追溯。"""
return InventoryRoutingResult(
'resolved',
(source_code,),
(),
{'reason': 'inventory_source_hint', 'raw_source_codes': [source_code]},
matched_rules=(),
)
def _resolve_snapshot_line_source_hint(*, task: Any, line: dict[str, Any]) -> str | None:
"""从冻结 Snapshot 行的强类型线索列读取并解析线索;行缺失或不可解析返回 None。"""
snapshot_id = getattr(task, 'order_snapshot_id', None)
if not snapshot_id:
return None
snapshot = ShippingOrderSnapshot.query.get(int(snapshot_id))
if snapshot is None:
return None
position = int(line.get('_position', 0))
target = next((item for item in snapshot.lines if item.position == position), None)
if target is None:
return None
return _resolve_source_from_hint(str(getattr(target, 'inventory_source_hint', '') or ''))
def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None) -> Any:
"""只读取冻结 Snapshot;履约路由不得回读动态 FieldValue。"""
if condition.source_kind != 'order_field':
@@ -232,14 +284,22 @@ def evaluate_inventory_source_rules(
"""
评估已发布规则并返回最高优先级的 Source 候选集合(冻结 Snapshot 路径)。
核心逻辑:行级评估先做库存源线索直连(冻结行 inventory_source_hint 列 → 精确/唯一后缀
解析启用源,命中即 resolved,优先于包括预约单号兜底在内的全部规则层);未命中 fail-open
落回规则层。任务级评估无线索语义,维持原行为。
Args:
task: 已解析的货代任务(须有 order_snapshot_id)。
line: 行级规则的订单行;任务级规则传 None。
line: 行级规则的订单行;任务级规则传 None。须含 `_position`(`_task_routing_lines` 产物)。
now: 测试可注入的评估时间,默认当前 UTC 时间。
Returns:
InventoryRoutingResult: 含 status / source_codes / matched_rules / can_build。
"""
if line is not None:
hint_code = _resolve_snapshot_line_source_hint(task=task, line=line)
if hint_code:
return _hint_routing_result(hint_code)
scope = 'line' if line is not None else 'task'
return _evaluate_with_reader(
scope=scope,
@@ -254,11 +314,15 @@ def evaluate_inventory_source_rules_for_field_values(
line_field_values: dict[str, Any] | None = None,
scope: str | None = None,
now: datetime | None = None,
line_source_hint: str | None = None,
) -> InventoryRoutingResult:
"""
基于 field_id→值映射评估路由(建单前 Draft / 资格服务)。
基于 field_id→值 映射评估路由(建单前 Draft / 资格评估)。
核心逻辑:未传 scope 时,有 line_field_values 则评 line,否则评 task;
核心逻辑:行级评估先做库存源线索直连(调用方从 Draft 行取 `inventory_source_hint` 值
传入;精确/唯一后缀解析启用源,命中即 resolved,优先于全部规则层);未命中 fail-open
落回规则层。任务级评估(line_field_values=None)忽略线索,维持原行为。
未传 scope 时,有 line_field_values 则评 line,否则评 task;
不依赖 ShippingNotice / Snapshot,便于复核草稿阶段投影候选。
Args:
@@ -266,6 +330,7 @@ def evaluate_inventory_source_rules_for_field_values(
line_field_values: Line 字段值;行级规则必填。
scope: 显式规则作用域 ``line`` / ``task``;缺省按是否有行值推断。
now: 可选评估时间。
line_source_hint: Draft 行的库存源线索原始值;任务级评估或不传时忽略。
Returns:
InventoryRoutingResult。
@@ -274,6 +339,10 @@ def evaluate_inventory_source_rules_for_field_values(
resolved_scope = scope or ('line' if line_field_values is not None else 'task')
if resolved_scope not in {'line', 'task'}:
raise ValueError('inventory routing scope must be line or task')
if resolved_scope == 'line':
hint_code = _resolve_source_from_hint(line_source_hint or '')
if hint_code:
return _hint_routing_result(hint_code)
line_values = dict(line_field_values or {}) if resolved_scope == 'line' else None
return _evaluate_with_reader(
scope=resolved_scope,
@@ -277,9 +277,14 @@ def assert_inventory_source_gate(
def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]:
"""返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。"""
"""返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。
传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。
"""
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
task = resolve_inventory_fact_task(task)
source_codes = task_frozen_inventory_source_codes(task)
source_code = source_codes[0] if len(source_codes) == 1 else None
source = get_database_inventory_source(source_code) if source_code else None
@@ -294,13 +299,19 @@ def resolve_inventory_source_warehouse_id(
*,
source: dict[str, Any] | None,
) -> str | None:
"""解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。"""
"""解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。
传入 ShippingNotice 时先归一为其 order_task(库存 Link 挂在 OT 上)。
"""
if not source:
return None
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
if mode == 'fixed':
return str(source.get('fixed_warehouse_id') or '').strip().upper() or None
from app.services.shipping_notice.inventory_candidate_projection import resolve_inventory_fact_task
task = resolve_inventory_fact_task(task)
task_id = getattr(task, 'id', None)
source_code = str(source.get('source_code') or '').strip().upper()
if not task_id or not source_code:
@@ -5,6 +5,9 @@ services/shipping_notice/line_inventory_match_persistence.py
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
新快照新增行并切换 is_current;不覆盖历史快照事实。
行级 inventory_snapshot_id 按匹配结果自带的 inventory_file_no 归因到「命中文件」;
仅行结果未回填文件号(如 not_found)时才回退任务级锚点快照——多源池下锚点文件
≠命中文件,混用会导致 Excel 仓库列写成锚点仓(历史缺陷:AWSCV 单写成 CMH01)。
匹配器下发的料号兜底总量 part_available_qty(Task 1)随行事实字符串化落列,
供后续投影层与自动放行服务读取。
"""
@@ -111,12 +114,14 @@ def persist_line_inventory_match_facts(
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
snap_id = active_inventory_runtime_facts(task).get('inventory_file_id')
# 匹配器结果可能未回填 inventory_file_no,但当前快照本身已是行匹配的
# 正式文件身份。持久化必须补齐,避免“有快照却无行级下载证据”。
# 任务级锚点快照仅作行结果缺文件号时的回退身份;命中文件归因在行循环内逐行解析。
snapshot_file_no = None
if snap_id is not None:
snapshot = ShippingInventoryFile.query.get(int(snap_id))
snapshot_file_no = str(getattr(snapshot, 'inventory_file_no', '') or '').strip() or None
# 命中文件号 → 文件 ID 缓存;文件号查不到文件时缓存 None,本行回退锚点快照
# (命中证据仍以 matched_file_no 为准,不把锚点伪装成命中文件)。
file_id_by_no: dict[str, int | None] = {}
line_results = [
item for item in list(match_payload.get('line_results') or []) if isinstance(item, dict)
@@ -156,6 +161,23 @@ def persist_line_inventory_match_facts(
continue
snapshot_line_id = int(snapshot_line.id)
# [STEP] 行级文件归因:匹配结果自带 inventory_file_no 时解析命中文件 ID;
# 未回填(如 not_found)或文件号无法解析时回退任务级锚点快照。
# 禁止把锚点文件身份盖到命中了其他源文件的行上(历史缺陷根因)。
line_file_no = str(result.get('inventory_file_no') or '').strip() or None
line_snap_id = snap_id
if line_file_no is not None:
if line_file_no not in file_id_by_no:
hit_file = (
ShippingInventoryFile.query
.filter_by(inventory_file_no=line_file_no)
.first()
)
file_id_by_no[line_file_no] = int(hit_file.id) if hit_file is not None else None
resolved_file_id = file_id_by_no[line_file_no]
if resolved_file_id is not None:
line_snap_id = resolved_file_id
match_result, inventory_status = map_disposition_to_match_codes(
disposition=str(result.get('disposition') or res.get('disposition') or ''),
part_number=result.get('part_number') or res.get('part_number'),
@@ -172,8 +194,8 @@ def persist_line_inventory_match_facts(
else []
)
# [STEP] BE-5:无库存快照时禁止 ready/not_found(不得规范为 0)
if snap_id is None and (
# [STEP] BE-5:本行无任何库存文件身份时禁止 ready/not_found(不得规范为 0)
if line_snap_id is None and (
inventory_status == 'ready'
or match_result in {'matched', 'not_found'}
):
@@ -195,20 +217,20 @@ def persist_line_inventory_match_facts(
)
unit_value = str(unit_raw or '').strip()[:32] or None
# [STEP] 同 OT+行+快照:更新;否则新建并撤销旧 current
# [STEP] 同 OT+行+命中文件:更新;否则新建并撤销旧 current
existing = None
if snap_id is not None:
if line_snap_id is not None:
existing = (
ShippingNoticeLineInventoryMatch.query
.filter_by(
task_id=int(task.id),
snapshot_line_id=snapshot_line_id,
line_no=line_no,
inventory_snapshot_id=int(snap_id),
inventory_snapshot_id=int(line_snap_id),
)
.first()
)
if existing is None and snap_id is None:
if existing is None and line_snap_id is None:
existing = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True)
@@ -253,7 +275,7 @@ def persist_line_inventory_match_facts(
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': file_no,
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
'snapshot_missing': line_snap_id is None,
'evidence_ref_plain': evidence_plain if evidence_ref else None,
}
row = ShippingNoticeLineInventoryMatch(
@@ -273,7 +295,7 @@ def persist_line_inventory_match_facts(
else None
),
candidate_line_id=int(candidate_line.id) if candidate_line is not None else None,
inventory_snapshot_id=int(snap_id) if snap_id is not None else None,
inventory_snapshot_id=int(line_snap_id) if line_snap_id is not None else None,
match_result=match_result,
inventory_status=inventory_status,
required_qty=str(required) if required is not None else None,
@@ -304,7 +326,7 @@ def persist_line_inventory_match_facts(
'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None,
'allowed_source_codes_snapshot': list(allowed_source_codes),
'inventory_file_no': file_no,
'inventory_snapshot_id': int(snap_id) if snap_id is not None else None,
'inventory_snapshot_id': int(line_snap_id) if line_snap_id is not None else None,
'inventory_row_ref': result.get('inventory_row_ref'),
'match_result': match_result,
}).encode('utf-8')
@@ -342,7 +364,7 @@ def persist_line_inventory_match_facts(
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': file_no,
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
'snapshot_missing': line_snap_id is None,
'evidence_ref_plain': evidence_plain if evidence_ref else None,
}
existing.match_result = match_result
@@ -385,7 +407,7 @@ def persist_line_inventory_match_facts(
'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None,
'allowed_source_codes_snapshot': list(allowed_source_codes),
'inventory_file_no': file_no,
'inventory_snapshot_id': int(snap_id) if snap_id is not None else None,
'inventory_snapshot_id': int(line_snap_id) if line_snap_id is not None else None,
'inventory_row_ref': result.get('inventory_row_ref'),
'match_result': match_result,
}).encode('utf-8')
@@ -290,6 +290,8 @@ def project_line_inventory_candidates(
header_field_values=header_ids,
line_field_values=line_ids,
scope='line',
# [线索直连] Draft 行的库存源线索经引擎精确/唯一后缀解析启用源,命中即优先于全部规则层。
line_source_hint=str(line_by_code.get('inventory_source_hint') or '').strip() or None,
)
task_result = evaluate_inventory_source_rules_for_field_values(
header_field_values=header_ids,
@@ -118,7 +118,25 @@ def _order_snapshot_line_ids(notice: ShippingNotice) -> list[str]:
return sorted(set(keys), key=lambda value: int(value))
def editable_scope(order_task: ShippingNotice) -> dict[str, Any]:
def _resolve_scope_notice(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | None:
"""编辑窗身份归一:主通知原样返回;传入 OT 时按 order_task_id 反查任一同单通知。
产物(Export Artifact)与 Attempt 都挂在通知上——OT 身份直接参与谓词会因
查不到产物而恒判可编辑(用户报告:Excel 已产生仍显示出单工具条)。
"""
task_id = getattr(task, 'id', None)
if isinstance(task, ShippingNotice) or task_id is None:
# 主通知原样返回;未落库的 OT 不可能有通知,视同"Excel 从未生成"。
return task if isinstance(task, ShippingNotice) else None
return (
ShippingNotice.query
.filter(ShippingNotice.order_task_id == int(task_id))
.order_by(ShippingNotice.id.asc())
.first()
)
def editable_scope(order_task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
"""
计算确认后订单的编辑窗矩阵(D10 / §3.1)。
@@ -127,20 +145,24 @@ def editable_scope(order_task: ShippingNotice) -> dict[str, Any]:
行未入波次 → 无活动 Attempt(不受首单 Excel 限制)。
Args:
order_task: 正式订单的主 ShippingNotice(含 order_task_id 可回读同订单全部通知)。
order_task: 主 ShippingNotice 或正式 OT(OT 自动按 order_task_id 归一到主通知)。
Returns:
dict: {'header': bool, 'lines': {snapshot_line_id: bool}},同构供 ui_state.edit_window 下发。
"""
notices = _order_notices(order_task)
notice = _resolve_scope_notice(order_task)
if notice is None:
# 尚未产生任何通知(Excel 从未生成):无产物、无活动 Attempt,视为可编辑。
return {'header': True, 'lines': {}}
notices = _order_notices(notice)
order_busy = any(_notice_has_active_attempt(n) for n in notices)
header_has_excel = any(_notice_has_export_artifact(n) for n in notices)
header = (not header_has_excel) and (not order_busy)
wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(order_task))
wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(notice))
lines: dict[str, bool] = {}
for snapshot_line_id in _order_snapshot_line_ids(order_task):
for snapshot_line_id in _order_snapshot_line_ids(notice):
wave_task_id = wave_notice_map.get(snapshot_line_id)
if wave_task_id is None:
# 未入波次行:不受首单 Excel 限制,仅受活动 Attempt 影响。
@@ -311,6 +311,51 @@ def _resolve_automatic_acceptance(raw_order: dict[str, Any]) -> dict[str, str] |
return dict(_AUTOMATIC_ACCEPTANCE_BY_MARKER[marker]) if marker in _AUTOMATIC_ACCEPTANCE_BY_MARKER else None
def _failed_unit_errors_by_document(run_id: int | None) -> dict[int, dict[str, str | None]]:
"""
读取 Run 内 Unit 级失败事实(document_id → 错误码/消息),供收口裁决纠正文档级状态。
核心逻辑:persist 的候选裁决只知道「有没有 pending」,不知道 Unit 是否技术失败;
Unit 全失败的附件没有任何产出裁决,禁止按零 pending 误写 completed
(回归 SNER-20261014-8EBAB7A1:9 Unit 全失败仍整批 completed,批次中心误报通知完成)。
Args:
run_id: ShippingOrderProcessingRun 主键;为空时返回空表(领域单测路径)。
Returns:
document_id → {'error_code', 'error_message'} 映射。
"""
if run_id is None:
return {}
from app.models import ShippingOrderProcessingPlan, ShippingOrderProcessingUnit
rows = (
db.session.query(
ShippingOrderProcessingUnit.document_id,
ShippingOrderProcessingUnit.error_code,
ShippingOrderProcessingUnit.error_message,
)
.join(
ShippingOrderProcessingPlan,
ShippingOrderProcessingPlan.id == ShippingOrderProcessingUnit.plan_id,
)
.filter(
ShippingOrderProcessingPlan.run_id == int(run_id),
ShippingOrderProcessingUnit.status == 'failed',
ShippingOrderProcessingUnit.document_id.isnot(None),
)
.all()
)
return {
int(document_id): {
'error_code': str(error_code or '').strip() or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED',
'error_message': str(error_message or '').strip() or 'Order extraction unit failed',
}
for document_id, error_code, error_message in rows
if document_id is not None
}
def persist_order_extraction_result(
*,
session: ChatSession,
@@ -794,21 +839,82 @@ def persist_order_extraction_result(
# [STEP 2] 聚合 Document 结果;无法归属到 Intake 的异常项会使本轮全部 Document 保持部分完成。
has_unassigned_pending = any(not item.get('source_intake_no') for item in pending)
# Unit 失败事实优先:Unit 失败且无候选/待处理裁决的附件,识别并未完成,
# 必须落 failed(携带 Unit 错误码),禁止按「零 pending」误写 completed——
# 否则随后的 Run 失败收口会因「已是终态」跳过回填,批次中心误报已完成。
failed_unit_error_by_document = _failed_unit_errors_by_document(run_id)
for document in documents:
keys = document_candidate_keys[int(document.id)]
document.order_extraction_status = (
'partially_completed'
if document_has_pending[int(document.id)] or has_unassigned_pending
else 'completed'
)
unit_failure = failed_unit_error_by_document.get(int(document.id))
if unit_failure and not keys and not document_has_pending[int(document.id)]:
document.order_extraction_status = 'failed'
document.order_extraction_error_code = unit_failure['error_code']
document.order_extraction_error_message = unit_failure['error_message']
else:
document.order_extraction_status = (
'partially_completed'
if document_has_pending[int(document.id)] or has_unassigned_pending
else 'completed'
)
document.order_extraction_error_code = None
document.order_extraction_error_message = None
document.order_extraction_source = extraction_source
document.order_extraction_result_json = {
'request_id': request_id,
'candidate_keys': keys,
'non_shipping_order_indexes': document_non_shipping_indexes[int(document.id)],
}
document.order_extraction_error_code = None
document.order_extraction_error_message = None
# [STEP 2.5] 重识别 Run 终态收口:本 Run 已落库的可复核 Case 必须在此原子激活为
# 文件 Stream 当前版本——Case 创建时按 reparse 延迟激活、约定等 Run 终态切换,但
# 该钩子此前从未接线,导致工作台队列(按 Stream.current_case_id 平铺)看不到任何
# Case,单据永远不可见(回归 SNER-20261014-35E35017 → BB05A18B:9 Case 全部
# stream_id=NULL,工作台空白且停接收解析)。
if run_id is not None:
from app.models import ShippingOrderProcessingRun, ShippingOrderReviewCase
from app.services.shipping_notice.candidate_service import (
is_current_reviewable_candidate,
)
from app.services.shipping_notice.review_stream_service import (
activate_review_case,
ensure_review_stream_for_case,
run_is_reparse_successor_of_case,
)
persisted_run = db.session.get(ShippingOrderProcessingRun, int(run_id))
if persisted_run is not None and persisted_run.reparse_of_run_id is not None:
reparse_cases = ShippingOrderReviewCase.query.filter(
ShippingOrderReviewCase.run_id == int(persisted_run.id),
ShippingOrderReviewCase.status != 'superseded',
ShippingOrderReviewCase.candidate_id.isnot(None),
).all()
for review_case in reparse_cases:
try:
candidate = db.session.get(
ShippingOrderCandidate, int(review_case.candidate_id),
)
if not is_current_reviewable_candidate(candidate):
continue
stream = ensure_review_stream_for_case(case=review_case)
declared_source = None
if stream.current_case_id is not None:
current_case = db.session.get(
ShippingOrderReviewCase, int(stream.current_case_id),
)
if (
current_case is not None
and run_is_reparse_successor_of_case(
run=persisted_run, current_case=current_case,
)
):
declared_source = int(current_case.id)
activate_review_case(
case=review_case, trigger='batch_reparse_succeeded',
declared_source_case_id=declared_source,
)
except ConflictError:
# 已确认/履约中的当前版本不得被草稿覆盖:保留现状态供人工处理。
continue
# [STEP 3] 只对本次 documents 作用域内消失的 Candidate 做版本失效。
# Unit 增量提交仅带当前 PDF,禁止把同 Intake/Run 的兄弟 PDF Candidate
@@ -836,13 +942,32 @@ def persist_order_extraction_result(
duplicate_results_by_intake.get(int(intake.id), []),
)
apply_duplicate_result_to_intake(intake, aggregate)
intake.order_extraction_status = (
'partially_completed'
if pending_by_intake[int(intake.id)] or has_unassigned_pending
else 'completed'
# Intake 聚合文档级终态:全部业务附件 failed → failed;部分失败 → partially_completed;
# 二者都不得被后续「零 pending 即 completed」的收口覆盖。
intake_documents = documents_by_intake.get(int(intake.id)) or []
failed_intake_documents = [
document
for document in intake_documents
if str(document.order_extraction_status or '').strip().lower() == 'failed'
]
business_document_count = sum(
1
for document in intake_documents
if str(document.document_type or '').strip().lower() != 'email_body'
)
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
if failed_intake_documents and business_document_count > 0 \
and len(failed_intake_documents) >= business_document_count:
intake.order_extraction_status = 'failed'
intake.order_extraction_error_code = failed_intake_documents[0].order_extraction_error_code
intake.order_extraction_error_message = failed_intake_documents[0].order_extraction_error_message
elif failed_intake_documents or pending_by_intake[int(intake.id)] or has_unassigned_pending:
intake.order_extraction_status = 'partially_completed'
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
else:
intake.order_extraction_status = 'completed'
intake.order_extraction_error_code = None
intake.order_extraction_error_message = None
intake.updated_at = datetime.utcnow()
db.session.flush()
@@ -864,6 +989,15 @@ def persist_order_extraction_result(
.all()
)
if run is not None and current_candidates:
# [STEP] 裸数字启发式冲突的自动解决:字段级裁决已 accepted 的
# supplement_field_conflict 不再阻断建单资格(PO 行收敛/正式值源写入
# 即为裁决)。必须在 OT 创建前执行,否则资格门禁误报字段冲突。
from app.services.shipping_notice.candidate_qualification_service import (
resolve_satisfied_supplement_conflicts,
)
for candidate in current_candidates:
resolve_satisfied_supplement_conflicts(candidate)
# PDF 级复核重识别:Run.user_task_no 已是 Case 对应 OT(可能是兄弟号),
# 禁止再按 index=0 当根号、给其他 Candidate 派生 -C{id}。
marker = (getattr(run, 'input_snapshot_json', None) or {}).get('review_reparse')
@@ -1001,7 +1135,13 @@ def persist_order_extraction_result(
for intake in intakes:
intake.parse_status = 'consumed'
intake.consumed_at = now
intake.order_extraction_status = 'completed'
# consumed 仅代表「邮件解析结果已被抽取收口消费」;文档/Intake 级
# order_extraction_status 若已按 Unit 失败裁决为 failed/partially_completed,
# 不得在此覆盖回 completed——否则 Run 失败收口会因「已是终态」跳过回填。
if str(intake.order_extraction_status or '').strip().lower() not in {
'failed', 'partially_completed',
}:
intake.order_extraction_status = 'completed'
intake.updated_at = now
db.session.commit()
@@ -866,6 +866,7 @@ def _build_snapshot(
)
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.generic_parse_plan import compile_generic_parse_plan
from app.services.shipping_notice.reservation_id import find_bare_numeric_reservation_candidates
table_contract = compile_table_header_contract(dict(schema_version.definition_json or {}))
generic_config = (
@@ -932,6 +933,13 @@ def _build_snapshot(
)
if isinstance(email_supplement, dict):
email_supplement['document_id'] = int(document.id)
# [裸数字兜底] 快照冻结前按当前正文重扫「整格纯数字」表格候选;
# 合并末段结合订单已提取字段值裁决,快照重建保证与 Schema 同源。
email_supplement['reservation_candidates'] = find_bare_numeric_reservation_candidates(
html_tables=html_tables,
content_hash=str(document.content_hash or ''),
)
email_supplement['email_subject'] = str(email.get('subject') or '')
document_snapshot = {
'document_id': document.id,
'document_type': document.document_type,
@@ -49,6 +49,9 @@ from app.services.shipping_notice.document_layout.order_profile_matcher import (
ProfileMatchResult,
match_frozen_coordinate_profiles,
)
from app.services.shipping_notice.document_layout.order_profile_ocr_rescue import (
rescue_match_with_header_ocr,
)
from app.services.shipping_notice.document_layout.order_profile_parse_validation import (
validate_profile_parse_candidate,
)
@@ -1078,6 +1081,16 @@ def _profile_table_candidates(
profiles=coordinate_profiles, layout=layout,
header_to_field=contract.header_to_field,
)
if (
match.status in {'layout_drift', 'no_match'}
and document_model is not None
):
# 表头带证据补洞:仅当存在「仅表头判别冲突 + 观测原子纯缺失」候选时
# 尝试;重跑完整匹配器且恰好唯一命中可补救候选才采纳,否则维持原判。
match = rescue_match_with_header_ocr(
match=match, profiles=coordinate_profiles, layout=layout,
header_to_field=contract.header_to_field, document=document_model,
)
affinity_applied = False
if not match_only:
match = _apply_parse_validation_gate(
@@ -498,7 +498,21 @@ def _email_parent_rows(
if document_id <= 0 or document_id in existing_document_ids:
continue
parse_status = parse_statuses.get(intake_id, '')
parent_status = 'failed' if parse_status == 'parse_failed' else 'processing'
run_status = str(run.status or '').strip().lower()
if run_status in {'queued', 'processing'}:
# 运行中的 Run:EML 父项只区分解析失败与处理中。
parent_status = 'failed' if parse_status == 'parse_failed' else 'processing'
else:
# [STEP] 终态 Run 的 EML 父项必须跟随 Run 结果收敛,禁止停留在「处理中」
# (历史缺陷:全部 Unit 失败后父项仍显示处理中,误导用户批次仍在进行)。
# partially_completed 的用户语义与 review_required 一致(需人工处理)。
parent_status = {
'failed': 'failed',
'cancelled': 'cancelled',
'completed': 'completed',
'review_required': 'review_required',
'partially_completed': 'review_required',
}.get(run_status, 'failed')
rows.append({
'unit_id': -document_id,
'document_id': document_id,
@@ -1901,10 +1901,24 @@ def extract(
live_fingerprint = live_fingerprint or signature.get('dataset_structure_fingerprint')
source = selected.get('definition', {}).get('source_contract') if isinstance(selected.get('definition'), dict) else {}
source = source if isinstance(source, dict) else {}
identity_state = 'matched'
if not source.get('template_packet_checksum') or not source.get('dataset_structure_fingerprint'):
return review('xfa_profile_identity_incomplete')
if source.get('template_packet_checksum') != live_template or source.get('dataset_structure_fingerprint') != live_fingerprint:
return review('xfa_profile_identity_mismatch')
identity_state = 'incomplete'
elif (
source.get('template_packet_checksum') != live_template
or source.get('dataset_structure_fingerprint') != live_fingerprint
):
identity_state = 'mismatch'
# [SOFT GATE] XFA 身份指纹漂移不再硬拦截(回归 SNER-20261014-35E35017:供应商
# 换代必变指纹,硬拦截使 XFA 单据永远空转人工)。视觉 Route 已唯一命中,datasets
# 取值后仍有 validate_xfa_extraction 业务交叉校验兜底;漂移降级为决策留痕
# (xfa_identity_state)+ fallback 码,仅当取值/校验失败时与业务原因码一起转 Review。
decision['xfa_identity_state'] = identity_state
if identity_state != 'matched':
decision['fallback_reason_codes'] = [
*(decision.get('fallback_reason_codes') or []),
f'xfa_profile_identity_{identity_state}',
]
table_id = workflow._profile_visual_main_table_id(selected, document.get('layout_snapshot') or {})
if not table_id:
return review('xfa_visual_main_table_missing')
@@ -1947,7 +1961,11 @@ def extract(
# 审计故障不能篡改已冻结的取值/Review 裁决。
pass
if extraction.status != 'parsed' or extraction.reason_codes:
return review(*(list(extraction.reason_codes or []) or ['xfa_required_field_missing']))
codes = list(extraction.reason_codes or []) or ['xfa_required_field_missing']
if identity_state != 'matched':
# 漂移被软门禁放行后取值仍失败:身份码前置,让复核者看到根因。
codes = [f'xfa_profile_identity_{identity_state}', *codes]
return review(*codes)
validation = validate_xfa_extraction(
raw_profile=selected, dataset_analysis=outcome.dataset_analysis, extraction=extraction, pdf_bytes=pdf_bytes,
)
@@ -1960,7 +1978,10 @@ def extract(
'profile_checksum': str(selected.get('checksum') or ''),
}
if not validation.passed:
return review(*(list(validation.reason_codes or []) or ['xfa_business_validation_failed']))
validation_codes = list(validation.reason_codes or []) or ['xfa_business_validation_failed']
if identity_state != 'matched':
validation_codes = [f'xfa_profile_identity_{identity_state}', *validation_codes]
return review(*validation_codes)
table = {
'profile_id': selected.get('profile_id') or selected.get('id'), 'profile_code': str(selected.get('profile_code') or ''),
'profile_version': int(selected.get('version') or 0), 'profile_checksum': str(selected.get('checksum') or ''),
@@ -15,15 +15,21 @@ from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError
from app.models import (
ShippingCustomer,
ShippingOrderCandidate,
ShippingCustomerShadowResolution,
ShippingOrderExtraction,
ShippingOrderReviewCase,
ShippingOrderTask,
)
from app.services.shipping_notice.candidate_qualification_service import (
resolve_review_case_customer_resolved,
)
from app.services.shipping_notice.customer_resolution_service import confirm_customer_resolution
from app.services.shipping_notice.customer_resolution_service import (
confirm_customer_resolution,
rebind_allowed_for_task,
resolution_for_task,
)
from app.services.shipping_notice.workflow_ledger_service import (
assert_case_is_current_workflow_version,
)
@@ -160,19 +166,45 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di
)
)
]
# [STEP 2] 已确认(含改绑)后以确认结果与客户主数据为权威展示:识别候选显示在改绑后会 stale。
confirmed_task = (
db.session.get(ShippingOrderTask, int(case.confirmed_task_id))
if getattr(case, 'confirmed_task_id', None) else None
)
resolution_row = resolution_for_task(confirmed_task) if confirmed_task is not None else None
confirmed_customer_id = (
getattr(resolution_row, 'confirmed_customer_id', None)
if resolution_row is not None and resolution_row.status == 'confirmed'
else (getattr(shadow, 'confirmed_customer_id', None) if shadow is not None else None)
)
confirmed_customer = (
db.session.get(ShippingCustomer, int(confirmed_customer_id))
if confirmed_customer_id else None
)
return {
'resolved': bool(resolved),
'status': status,
'role': 'customer',
'extraction_id': int(extraction.id) if extraction is not None else None,
'raw_name': None,
'customer_id': getattr(shadow, 'confirmed_customer_id', None) or display_match.get('customer_id'),
'standard_name': display_match.get('standard_name'),
'short_code': display_match.get('short_code'),
'customer_id': confirmed_customer_id or display_match.get('customer_id'),
'standard_name': (
confirmed_customer.standard_name if confirmed_customer is not None
else display_match.get('standard_name')
),
'short_code': (
confirmed_customer.short_code if confirmed_customer is not None
else display_match.get('short_code')
),
'candidates': list(display_match.get('candidates') or []),
'input_values': input_values,
'evidence': evidence,
'match': display_match,
# 「修改客户」按钮谓词:仅已确认且无 Export Artifact/活动 Attempt 时可改绑(A 管控)。
'rebind_allowed': (
rebind_allowed_for_task(confirmed_task) if confirmed_task is not None else False
),
}
@@ -304,6 +304,9 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu
is_evidence_gap = reason in _EVIDENCE_GAP_REASONS
if is_evidence_gap and field_evidence_gap_is_non_blocking(candidate, item):
continue
# 已自动解决(正式值源/PO 行收敛写入)的冲突不再进入待裁决面板。
if str(item.get('resolution_status') or '').strip() == 'resolved':
continue
# 只有多个候选值不一致才属于「字段冲突待裁决」。
if len(value_keys) < 2 and not is_evidence_gap and not is_current_open_blocking:
continue
@@ -4,6 +4,9 @@
逻辑:优先 PO+MPN;其次同 PO+合法 reservation_id 对齐;仅唯一签名的 PO 可降级广播;
无同 PO 候选时仅对「PO 缺失」行做唯一料号兜底(mpn_fallback);有 PO 且与 PDF
不一致则禁止补充。歧义只写复核原因。同趟单次合并,不互相重入。
主合并结束后另做「裸数字兜底」:仍无预约单号的订单,从正文裸 5/10 位数字
候选里排除已识别字段值/主题标签值/跨单已占用值,唯一候选以低置信度写入
header 默认值,多候选转为复核冲突,绝不覆盖任何已有值。
"""
from __future__ import annotations
@@ -13,7 +16,12 @@ from typing import Any
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
from app.services.shipping_notice.po_number import normalize_atomic_po_number
from app.services.shipping_notice.reservation_id import validated_reservation_id
from app.services.shipping_notice.reservation_id import (
filter_reservation_heuristic_candidates,
normalize_reservation_id,
reservation_ids_in_labeled_context,
validated_reservation_id,
)
def _values(fields: Any, code: str, codes: dict[str, str]) -> set[str]:
@@ -273,6 +281,269 @@ def _supplement_multi_value_conflict(
}
def _iter_order_observation_values(
order: dict[str, Any], *, include_header_values: bool = True,
) -> list[Any]:
"""收集订单头/行的原始字段 Observation 值;include_header_values=False 时
跳过表头观测(行级补写语义:表头已采纳值允许镜像写入缺失行级)。"""
values: list[Any] = []
field_groups: list[Any] = []
if include_header_values:
field_groups.append(order.get('header_fields'))
for line in order.get('lines') or []:
if isinstance(line, dict):
field_groups.append(line.get('fields'))
for fields in field_groups:
if not isinstance(fields, list):
continue
for field in fields:
if not isinstance(field, dict):
continue
for observation in field.get('observations') or []:
if isinstance(observation, dict) and observation.get('value') not in (None, ''):
values.append(observation.get('value'))
return values
def _heuristic_excluded_values(
order: dict[str, Any],
supplement: dict[str, Any],
*,
include_order_header_values: bool = True,
) -> set[str]:
"""构造裸数字候选的排除集:订单已提取值 + 邮件补充行值 + 邮件主题标签值。
核心逻辑:客户 PO 号本身就是 10 位纯数字,是启发式最大的误判源;因此除了
订单 Observation 原值外,还纳入 Reservation/PO 两种归一变体(千分位、x.0、
前导零),并排除主题里「PO xxx」等带标签数字(Q10 双保险)。
Args:
include_order_header_values: 行级补写语义下传 False——表头已采纳的预约号
正是要镜像写入缺失行级的值,不能出现在排除集里(否则行级永远补不上)。
"""
excluded: set[str] = set()
raw_values = _iter_order_observation_values(
order, include_header_values=include_order_header_values,
)
rows = supplement.get('rows') if isinstance(supplement.get('rows'), list) else []
for row in rows:
if isinstance(row, dict):
raw_values.extend(str(value) for value in row.values() if str(value or '').strip())
for raw in raw_values:
text = str(raw).strip()
if text:
excluded.add(text.upper())
normalized = validated_reservation_id(normalize_reservation_id(raw))
if normalized:
excluded.add(normalized)
excluded.add(normalized.lstrip('0'))
po = normalize_atomic_po_number(raw)
if po:
excluded.add(po.upper())
excluded.add(po.lstrip('0').upper() or po.upper())
excluded.update(
value.upper()
for value in reservation_ids_in_labeled_context(str(supplement.get('email_subject') or ''))
)
return {value for value in excluded if value}
def _inject_reservation_heuristic(
fields: list[dict[str, Any]],
field_id: str,
value: str,
evidence: dict[str, Any],
document_id: int,
) -> None:
"""以裸数字兜底语义写入 reservation Observation:低置信度并携带 basis 标记。
与 _inject 的差异:confidence 固定 0.5(启发式,非权威证据),
email_supplement_evidence 增加 basis='bare_numeric_heuristic' 供复核端标注。
"""
target = next((item for item in fields if isinstance(item, dict) and item.get('field_id') == field_id), None)
observation = {
'value': value, 'document_id': document_id, 'quote': str(evidence.get('raw_value') or value),
'confidence': 0.5, 'email_supplement_evidence': {
'table_index': evidence.get('table_index'), 'row_index': evidence.get('row_index'),
'column_index': evidence.get('column_index'), 'cell_id': evidence.get('cell_id'),
'basis': 'bare_numeric_heuristic',
},
}
if target is None:
fields.append({'field_id': field_id, 'observations': [observation]})
else:
target['observations'] = [observation]
def _order_has_reservation_value(order: dict[str, Any], ids: dict[str, str]) -> bool:
"""判断订单头或任意行已存在预约单号取值(含非法格式原值);存在则兜底绝不写入。
按 Q2 契约「已有值永不覆盖」:即使原值未通过 5/10 位校验(如字母型编号),
也视为已有业务事实,只能走人工纠错,不能被裸数字猜测悄悄替换。
"""
reverse_ids = {v: k for k, v in ids.items()}
if _values(order.get('header_fields'), 'reservation_id', reverse_ids):
return True
for line in order.get('lines') or []:
if isinstance(line, dict) and _values(line.get('fields'), 'reservation_id', reverse_ids):
return True
return False
def _order_po_variants(order: dict[str, Any], ids: dict[str, str]) -> set[str]:
"""本单已提取客户 PO 号的匹配变体集合(原值/归一/去前导零)。"""
reverse_ids = {v: k for k, v in ids.items()}
values = list(_values(order.get('header_fields'), 'customer_po_number', reverse_ids))
for line in order.get('lines') or []:
if isinstance(line, dict):
values.extend(_values(line.get('fields'), 'customer_po_number', reverse_ids))
variants: set[str] = set()
for value in values:
text = str(value).strip()
if not text:
continue
variants.add(text)
po = normalize_atomic_po_number(text)
if po:
variants.update({po, po.lstrip('0')})
variants.add(text.lstrip('0'))
return {variant for variant in variants if variant}
def _apply_reservation_heuristic(
order: dict[str, Any],
supplement: dict[str, Any],
*,
configs: dict[str, dict[str, Any]],
ids: dict[str, str],
schema_version: str,
claimed: set[str],
) -> None:
"""对仍无预约单号的订单执行裸数字兜底裁决(唯一→写入;多候选→冲突)。
核心逻辑:
[STEP 1] Schema 无 reservation_id 字段、候选键缺失或订单已有合法值 → 直接返回;
[STEP 2] 排除集 = 订单已提取值 ∪ 补充行值 ∪ 主题标签值 ∪ 跨单已占用(claimed);
[STEP 3] 唯一候选 → 按 Schema 作用域写入 header 默认值或缺失行,relation 标记
reservation_heuristic 供工作台补充状态展示;
[STEP 4] 多候选 → 复用 supplement_field_conflict 冲突结构(values + 逐候选
email_body 证据源),转现有字段冲突裁决面板,绝不自动挑值。
"""
config = configs.get('reservation_id')
field_id = ids.get('reservation_id')
candidates = supplement.get('reservation_candidates')
if config is None or not field_id or not isinstance(candidates, list) or not candidates:
return
# [分作用域兜底] 「已有值永不覆盖」按字段作用域生效:表头已有预约号→不再重复
# 注入表头;行级缺失→仍执行行级补写(分配邮件一行一个 PO+预约号,明细缺预约
# 号属数据不完整,回归 SNER-20261014-0AB6D98A doc 915 明细预约号空)。
reverse_ids = {v: k for k, v in ids.items()}
header_has_reservation = bool(
_values(order.get('header_fields'), 'reservation_id', reverse_ids),
)
header_reservation_values = set(
_values(order.get('header_fields'), 'reservation_id', reverse_ids),
)
lines_missing_reservation = [
line for line in order.get('lines') or []
if isinstance(line, dict) and isinstance(line.get('fields'), list)
and not _values(line['fields'], 'reservation_id', reverse_ids)
]
scope = str(config.get('scope') or '').strip().lower()
if scope == 'header' and header_has_reservation:
return
if scope != 'header' and not lines_missing_reservation:
return
excluded = _heuristic_excluded_values(order, supplement) | claimed
if lines_missing_reservation and header_has_reservation:
# [镜像语义] 表头已采纳的预约号值从排除集中移除——它正是要写入缺失
# 行级的值;其余订单观测值(尤其 PO)保持排除,防止 PO 误当预约号。
mirror_allow: set[str] = set()
for value in header_reservation_values:
text = str(value).strip().upper()
if text:
mirror_allow.update({text, text.lstrip('0')})
normalized = validated_reservation_id(normalize_reservation_id(text))
if normalized:
mirror_allow.update({normalized, normalized.lstrip('0')})
excluded -= mirror_allow
surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values=excluded)
if status == 'none':
return
# [PO 行定位收敛] 分配邮件整批表格一行一个 PO+预约号:本单 PO 所在行的预约号
# 即本单预约号。裸数字候选携带原始表坐标(table_index/row_index),与补充解析行
# 同源对齐——对齐行内含本单 PO 即认定该候选为本单预约号。命中唯一 → 按唯一路径
# 写入;命中多个或未命中时维持既有冲突裁决(绝不自动猜值)。
order_po_values = _order_po_variants(order, ids)
supplement_rows = supplement.get('rows') if isinstance(supplement.get('rows'), list) else []
parsed_rows_by_pos = {
(str(row.get('table_index') or 0), str(row.get('row_index') or 0)): row
for row in supplement_rows if isinstance(row, dict)
}
scoped: list[dict[str, Any]] = []
if order_po_values and parsed_rows_by_pos:
for item in surviving:
evidence = item.get('evidence') if isinstance(item.get('evidence'), dict) else {}
pos = (str(evidence.get('table_index') or 0), str(evidence.get('row_index') or 0))
row = parsed_rows_by_pos.get(pos)
if row is None:
continue
row_values = {str(value).strip() for value in row.values() if str(value or '').strip()}
if order_po_values & row_values:
scoped.append(item)
if scoped:
surviving = scoped
status = 'unique' if len(surviving) == 1 else 'multiple'
document_id = int(supplement.get('document_id') or 0)
values = [str(item.get('value') or '') for item in surviving]
marker = {'status': status, 'values': values, 'document_id': document_id or None}
if status == 'unique':
value = validated_reservation_id(values[0])
if not value:
return
evidence = dict(surviving[0].get('evidence') or {})
if str(config.get('scope') or '') == 'header':
header_fields = order.get('header_fields')
if isinstance(header_fields, list):
_inject_reservation_heuristic(header_fields, field_id, value, evidence, document_id)
else:
# 行级写入只补真正缺失的行;带任何原值(含非法格式)的行不覆盖。
reverse_ids = {v: k for k, v in ids.items()}
for line in order.get('lines') or []:
if isinstance(line, dict) and isinstance(line.get('fields'), list):
if not _values(line['fields'], 'reservation_id', reverse_ids):
_inject_reservation_heuristic(line['fields'], field_id, value, evidence, document_id)
claimed.add(value)
marker['status'] = 'applied'
marker['value'] = value
if not str(order.get('_hxops_email_supplement_relation') or '').strip():
order['_hxops_email_supplement_relation'] = 'reservation_heuristic'
else:
pseudo_rows = [
{
'reservation_id': item.get('value'),
'table_index': (item.get('evidence') or {}).get('table_index'),
'row_index': (item.get('evidence') or {}).get('row_index'),
'evidence': {'reservation_id': dict(item.get('evidence') or {})},
}
for item in surviving
]
conflict = _supplement_multi_value_conflict(
field_code='reservation_id',
config=config,
values=set(values),
selected_rows=pseudo_rows,
line_index=-1,
email_document_id=document_id,
schema_version=schema_version,
)
if conflict not in order.setdefault('conflicts', []):
order['conflicts'].append(conflict)
if not str(order.get('_hxops_email_supplement_relation') or '').strip():
order['_hxops_email_supplement_relation'] = 'reservation_heuristic'
order['_hxops_reservation_heuristic'] = marker
def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_intake: dict[int, dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
"""
按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。
@@ -487,4 +758,18 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
})
order['_hxops_email_supplement_relation'] = relation
merged.append(order)
# [STEP] 裸数字兜底:主合并完成后仍无预约单号的订单,按排除规则裁决正文候选。
# 跨单 claimed 防止同一候选同时灌入多个订单;旧 Run 补充快照无候选键时整体跳过。
claimed_reservations: set[str] = set()
for order in merged:
supplement = supplements_by_intake.get(int(order.get('_hxops_intake_id') or 0))
if isinstance(supplement, dict) and isinstance(supplement.get('reservation_candidates'), list):
_apply_reservation_heuristic(
order,
supplement,
configs=configs,
ids=ids,
schema_version=schema_version,
claimed=claimed_reservations,
)
return merged
@@ -938,6 +938,42 @@ def _handle_retry_inventory_preparation(
freeze_mode='manual',
)
db.session.flush()
# [STEP 0B] 人工重取前的候选源刷新(幂等):任务级 retry_inventory_preparation 先按当前
# 主数据/路由规则整单重判候选集;行级重抓(line_scope 非空)仅重评目标行候选。
# 两者均无变化零副作用;有变化则新版候选集随 supersede 自带旧事实失效,再走下方
# 既有失效与重取链——补源场景由此闭环:管理端启用新源后点「重新获取库存(RPA)」
# 即可让新源进入取数与匹配范围,无需重建订单。
# 轮询/自动首投(外层条件已排除)与 Excel 已生成(源锁定,D7 边界)不刷新;
# 已定源(任务级整单/行级目标行候选 ≤1)与人工钉源不刷新(helper 内守卫,改源走
# override_line_inventory_source)。
# 行键失效(line_scope_key/snapshot_line_id 解析不到行)时 _resolve_line_inventory_scope
# 返回 None,按既有降级语义走任务级刷新(升级前行为一致)。
if str(payload.get('action_code') or '').strip() == 'retry_inventory_preparation':
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
if latest_export_artifact(task) is None:
from app.services.shipping_notice.inventory_candidate_freeze_service import (
refresh_candidates_from_current_routing,
refresh_line_candidates_from_current_routing,
)
if line_scope is None:
refresh_candidates_from_current_routing(task, execution_id=int(execution.id))
elif refresh_line_candidates_from_current_routing(
task, line_no=int(line_scope['line_no']), execution_id=int(execution.id),
):
# 刷新产生新候选集后旧 scope 已过期:按同参重解析行作用域,让本次失效与
# RPA 取数直接使用新冻结码;重解析为 None(如行键已失效)则保守沿用旧值。
refreshed_scope = _resolve_line_inventory_scope(
task,
line_scope_key=(
payload.get('line_scope_key')
if payload.get('line_scope_key') is not None
else payload.get('snapshot_line_id')
),
)
if refreshed_scope is not None:
line_scope = refreshed_scope
if payload.get('action_code') in {
'retry_inventory_preparation',
'retry_inventory_from_preparation',
@@ -120,6 +120,7 @@ REVIEW_WORKBENCH_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
'review_field_changed',
'review_field_updated',
'review_customer_confirmed',
'review_customer_rebound',
'review_duplicate_resolved',
'review_conflict_resolved',
'review_qualification_evaluated',
@@ -1564,13 +1564,22 @@ def _enrich_task_center_fields(
data["created_by"] = task.user_id
if viewer_user_id is not None:
data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin)
# 下载能力与导出端点同一谓词;SUMMARY/DETAIL 均下发,供抽屉/批量勾选消费。
data["can_download_export"] = can_download_task_export(
task, user_id=int(viewer_user_id), is_admin=is_admin,
)
data["recent_event"] = _latest_task_event_summary(task)
data["artifact_summary"] = _artifact_summary_for_task(task)
data['notice_line_summary'] = _notice_line_summary_for_task(task)
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
from app.services.shipping_notice.ui_state import build_task_ui_state
ui_state = build_task_ui_state(task, include_stage_context=include_stage_context)
ui_state = build_task_ui_state(
task,
include_stage_context=include_stage_context,
viewer_user_id=viewer_user_id,
viewer_is_admin=is_admin,
)
data["ui_state"] = ui_state
# [PERF] 优先复用 ui_state.process_gate(build_task_ui_state 已查 Execution);
# 无 Gate 时回退 position/user_mode,避免再跑一次 resolve_task_ui_state。
@@ -1730,12 +1739,15 @@ def list_tasks_page_for_user(
page: int = 1,
page_size: int = 20,
lifecycle_status: str | None = None,
is_admin: bool = False,
) -> dict[str, Any]:
"""
分页列出当前用户可见的发货任务摘要。
工作台任务量增长后必须由数据库分页,不能先拉取固定上限再在浏览器切页;
`items` 仅表示当前页,`total` 用于计算稳定的页码与空页回退。
``is_admin`` 只影响 SUMMARY 的能力字段(can_handle / can_download_export),
不扩大列表可见范围(仍为本人 + 无主 Notice)。
"""
normalized_page = max(1, int(page))
normalized_page_size = max(1, min(int(page_size), 100))
@@ -1795,7 +1807,7 @@ def list_tasks_page_for_user(
rows = [row for row in rows if row is not None]
return {
"items": [
serialize_task_summary(item, viewer_user_id=user_id)
serialize_task_summary(item, viewer_user_id=user_id, is_admin=is_admin)
for item in rows
],
"page": normalized_page,
@@ -1849,6 +1861,35 @@ def get_task_visible_to_user(
return task
def can_download_task_export(
task: ShippingOrderTask | ShippingNotice | None,
*,
user_id: int,
is_admin: bool = False,
) -> bool:
"""
导出下载的唯一授权谓词:创建者或平台管理员(与导出端点同一口径)。
核心逻辑:单票/批量 Excel 下载端点与 UI 的 download_excel 动作、
can_download_export 字段都必须消费本谓词,禁止各处另行推导归属;
管理员放开下载(可下载=可见)后,每次下载仍须写入 record_access_audit。
无主任务(user_id IS NULL)仅管理员可下载。
Args:
task: 已加载的任务实体(可为 None)。
user_id: 当前查看/下载用户。
is_admin: 是否平台管理员。
Returns:
当前用户是否允许下载该任务的正式 Excel。
"""
if task is None:
return False
if is_admin:
return True
return task.user_id is not None and int(task.user_id) == int(user_id)
def list_freight_notice_groups_for_task(
task: ShippingNotice,
*,
@@ -2,9 +2,12 @@
services/shipping_notice/reservation_id.py
用途:提取、标准化并校验发货通知与库存中的 Reservation ID。
依赖:正则表达式与标准 `typing` 工具。
依赖:正则表达式与标准 `typing` 工具;裸数字兜底扫描惰性依赖版面 HTML 网格解析。
逻辑:由 notice_lines、inventory_snapshot、match、extract、EML 补充解析等多个模块复用;
归一结果恒为 5/10 位纯数字(可剥括号备注、@ 前缀、短数字行序后缀如 35354-1)。
另提供「裸数字兜底」:正文数据表无表头且常规证据缺失时,扫描「整格恰好为
5/10 位纯数字」的 HTML 表格单元格候选(供 order_supplement_merge 在合并
末段做唯一/多候选裁决;自由文本不扫描)。
"""
from __future__ import annotations
@@ -30,6 +33,16 @@ PR_NUMBER_LINE_RE = re.compile(
r"PR\s*Number\s*[::]?\s*([^\n\r]+)",
re.IGNORECASE,
)
# [裸数字兜底] 紧跟业务标签的数字串(PO/订单/发票/数量)不是预约单号;捕获组为数字本体。
# 保留前导词边界防止命中复合词内部;尾部不加边界、由「必须跟数字」门控,
# 使 PO12345 / PO# 12345 / Purchase Order: 12345 等写法都被覆盖,而 podium 等词不受影响。
# 仅用于邮件主题等上下文的标签排除;正文候选已收紧为「整格纯数字」,不再做自由文本扫描。
LABELED_NON_RESERVATION_RE = re.compile(
r"(?i)(?:\bp\.?\s*o\.?|\bpurchase\s+orders?|\borders?|\binvoices?|\binv\.?|\bqty\.?|\bquantity)"
r"(?:\s*(?:number|no\.?|#))?\s*[:#]?\s*(\d{3,})"
)
# 候选数量上限:转发/引用链可能携带大量历史数字,防止 supplement 快照被刷爆。
MAX_HEURISTIC_RESERVATION_CANDIDATES = 20
def normalize_reservation_id(value: Any) -> str:
@@ -151,3 +164,123 @@ def validated_reservation_id(value: Any, *, numeric_only: bool = False) -> str:
"""提取并返回合法 Reservation ID;候选不满足契约时返回空字符串。"""
candidate = extract_reservation_id(value)
return candidate if is_valid_reservation_id(candidate, numeric_only=numeric_only) else ""
def reservation_ids_in_labeled_context(text: str) -> set[str]:
"""返回文本中紧跟业务标签(PO/订单/发票/数量)的数字串,供裸数字候选排除。
AI 触发时机:合并末段判断裸数字候选前,先排除邮件主题等上下文里
「PO xxx」「Invoice xxx」这类带标签的数字,即使它们未被提取为字段。
Args:
text: 任意原文(邮件主题、正文段落等)。
Returns:
set[str]: 标签后紧跟的数字串原文(未归一);无命中返回空集合。
"""
return {
match.group(1)
for match in LABELED_NON_RESERVATION_RE.finditer(str(text or ""))
}
def _iter_heuristic_cell_texts(html_tables: list[str] | None, content_hash: str):
"""惰性产出 HTML 表格单元格文本及其证据定位;解析失败的表安全跳过。
逻辑:版面网格的 cell_id 是 DOM 级可追溯证据,优先于行号猜测;
惰性导入 html_table 避免给本工具模块增加常驻依赖。
"""
if not html_tables:
return
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
for table_index, html in enumerate(html_tables):
try:
grid = parse_html_grid(
str(html or ''), table_id=f'reservation-heuristic:{content_hash}:{table_index}',
)
except Exception:
continue
for row_index, row in enumerate(grid.rows):
for column, slot in enumerate(row):
if slot is None or not str(slot.text or '').strip():
continue
yield str(slot.text), {
'table_index': table_index,
'row_index': row_index,
'column_index': column,
'cell_id': slot.cell_id,
}
def _heuristic_cell_is_bare_number(cell_text: str) -> bool:
"""判断表格单元格是否「整格恰好为 5/10 位纯数字」(2026-10-15 收紧规则)。
前后带任何字符都不取:地址邮编(``Secaucus, NJ 07094``)、带字母前后的
编号(``T00410``)、带备注的值(``39739 (A)``)一律排除,只留独立数值格。
"""
return bool(RESERVATION_ID_NUMERIC_RE.fullmatch(str(cell_text or '').strip()))
def find_bare_numeric_reservation_candidates(
*,
html_tables: list[str] | None = None,
content_hash: str = "",
) -> list[dict[str, Any]]:
"""扫描正文 HTML 表格中「整格恰好为 5/10 位纯数字」的预约单号候选。
AI 触发时机:EML 正文数据表没有表头、常规表头契约解析不出预约单号时,
在补充事实里预置候选列表;真正「是否采纳」由 order_supplement_merge 在
合并末段结合已提取字段值裁决,本函数绝不直接写入订单。
核心逻辑:只认表格(2026-10-15 收紧)——自由文本(签名、地址、引用链)
一律不扫描,杜绝邮编等噪声;单元格整格纯数字才算候选(PO 号同为 10 位
纯数字会入选,由合并端按已提取字段值/主题标签排除);同值只保留首个证据;
总数截断到 MAX_HEURISTIC_RESERVATION_CANDIDATES。
Args:
html_tables: 正文顶层 HTML 表格片段列表;为空时返回空列表(无表格不兜底)。
content_hash: 正文 Document 内容哈希,用于稳定 cell_id。
Returns:
list[dict]: ``[{value, evidence}]``;evidence 含 table_index/row_index/
column_index/cell_id/raw_value(DOM 级可追溯)。
"""
candidates: list[dict[str, Any]] = []
seen: set[str] = set()
for cell_text, base_evidence in _iter_heuristic_cell_texts(html_tables, content_hash):
if not _heuristic_cell_is_bare_number(cell_text):
continue
value = str(cell_text).strip()
if value in seen or len(candidates) >= MAX_HEURISTIC_RESERVATION_CANDIDATES:
continue
seen.add(value)
candidates.append({'value': value, 'evidence': {**base_evidence, 'raw_value': value}})
return candidates
def filter_reservation_heuristic_candidates(
candidates: list[dict[str, Any]],
*,
excluded_values: set[str],
) -> tuple[list[dict[str, Any]], str]:
"""按「已识别字段值/跨单已占用」排除后裁决候选状态。
Args:
candidates: ``find_bare_numeric_reservation_candidates`` 的产物。
excluded_values: 需排除的值集合(比较前统一 strip+大写)。
Returns:
``(surviving, status)``:status 为 ``unique``(恰好一个,可自动采纳)、
``ambiguous``(多个,转人工裁决)或 ``none``(无候选)。
"""
excluded = {str(value).strip().upper() for value in excluded_values if str(value).strip()}
surviving = [
item for item in (candidates or [])
if str(item.get('value') or '').strip().upper() not in excluded
]
if not surviving:
return [], 'none'
if len(surviving) == 1:
return surviving, 'unique'
return surviving, 'ambiguous'
@@ -17,6 +17,7 @@ from app import db
from app.core.errors import ConflictError
from app.models import (
ShippingOrderDocument,
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
ShippingOrderReviewCaseEvent,
ShippingOrderReviewStream,
@@ -30,6 +31,33 @@ ReviewStreamTrigger = Literal[
]
def run_is_reparse_successor_of_case(
*,
run: ShippingOrderProcessingRun,
current_case: ShippingOrderReviewCase,
max_hops: int = 10,
) -> bool:
"""
判定 Run 是否为某文件当前 Case 所属 Run 的重解析后继(沿 reparse_of_run_id 有界上溯)。
核心逻辑:批次重解析(reparse_order_extraction_run)不写 review_reparse 快照
marker,activate_review_case 的替代来源证明需要调用方提供;本函数即该证明——
上溯有界跳数内命中 current_case.run_id 即认定同文件版本替代关系成立。
"""
current_run_id = int(current_case.run_id)
cursor = run
for _ in range(max(1, int(max_hops))):
ancestor_id = getattr(cursor, 'reparse_of_run_id', None)
if ancestor_id is None:
return False
if int(ancestor_id) == current_run_id:
return True
cursor = db.session.get(ShippingOrderProcessingRun, int(ancestor_id))
if cursor is None:
return False
return False
def _document_content_identity(document_id: int) -> str:
"""计算 Stream 的稳定文件身份;当前业务按 Document 严格隔离,哈希仅供审计说明。"""
document = db.session.get(ShippingOrderDocument, int(document_id))
@@ -91,12 +119,19 @@ def activate_review_case(
*,
case: ShippingOrderReviewCase,
trigger: ReviewStreamTrigger,
declared_source_case_id: int | None = None,
) -> ShippingOrderReviewStream:
"""
将一个成功可复核的 Case 原子切换为其文件 Stream 的当前版本。
AI 触发时机:初次 PDF 完成时或重解析成功且新 Case 已完整落库时调用;失败、等待布局和
仅创建后继 Run 时禁止调用。确认/履约中的当前版本不可被草稿覆盖,冲突必须显式暴露。
Args:
declared_source_case_id: 调用方已证明的版本替代来源 Case id(如按 Run 谱系
验证过的前代 Case)。快照 marker 缺失时(批次重解析不写
review_reparse.source_case_no)以它补全替代关系证明;快照 marker
优先,两者皆缺时维持保守冲突语义。
"""
stream = ensure_review_stream_for_case(case=case)
stream = ShippingOrderReviewStream.query.filter_by(id=int(stream.id)).with_for_update().one()
@@ -111,6 +146,9 @@ def activate_review_case(
return stream
if trigger != 'initial_extraction' and current is not None:
declared_source_id = _declared_reparse_source_case_id(incoming)
if declared_source_id is None and declared_source_case_id is not None:
# 调用方已按 Run 谱系证明替代来源(批次重解析不写快照 marker 的口径)。
declared_source_id = int(declared_source_case_id)
if declared_source_id is None or declared_source_id != int(current.id):
# [CONCURRENCY] 晚到分支只能进入冲突,绝不能覆盖已切换的另一文件版本。
stream.state = 'conflict'
@@ -4263,14 +4263,17 @@ def project_conversation_processing_summary(
if case.run_id is not None
)
# 订单抽取失败且尚无 Candidate/Case/OT 时,仍需最新 Run 身份供重解析;
# 仅 load id/run_no,不触碰 Plan/Unit。
# 仅 load id/run_no/status/error_code,不触碰 Plan/Unit。status/error_code
# 供摘要把「抽取收口 completed 但最新 Run 失败」的文档纠正为失败裁决。
latest_run_by_intake_id: dict[int, Any] = {}
if intake_ids:
for intake_id, run_id, run_no in (
for intake_id, run_id, run_no, run_status, run_error_code in (
db.session.query(
ShippingOrderProcessingRunIntake.intake_id,
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.run_no,
ShippingOrderProcessingRun.status,
ShippingOrderProcessingRun.error_code,
)
.join(
ShippingOrderProcessingRun,
@@ -4287,7 +4290,12 @@ def project_conversation_processing_summary(
key = int(intake_id)
if key in latest_run_by_intake_id:
continue
latest_run_by_intake_id[key] = {'id': int(run_id), 'run_no': str(run_no or '').strip()}
latest_run_by_intake_id[key] = {
'id': int(run_id),
'run_no': str(run_no or '').strip(),
'status': str(run_status or '').strip().lower(),
'error_code': str(run_error_code or '').strip() or None,
}
run_ids.add(int(run_id))
runs_by_id = {
int(run.id): run
@@ -4455,7 +4463,31 @@ def project_conversation_processing_summary(
if raw in {'review_required', 'waiting_review', 'pending_review', 'waiting_human'}:
return 'waiting_human', 'waiting_review' if stage == 'candidate_creating' else stage, 'waiting_review'
if raw in {'completed', 'uploaded'}:
return 'completed', 'completed', None
# 文档级 completed 只代表「抽取收口完成」,不是业务终态:通知完成必须
# 以正式 OT/Notice/上传核验为前提,禁止把收口语义译成通知完成
# (回归 SNER-20261014-8EBAB7A1:9 Unit 全失败仍整批 completed,
# 批次中心据此误报 9/9 已完成 + 通知完成)。
if task is not None:
return 'completed', 'completed', None
if case is not None and case_status == 'non_order':
# 非订单处置是唯一无 OT 的合法业务完成出口。
return 'completed', 'completed', None
latest_intake_run = latest_run_by_intake_id.get(int(document.intake_id)) or {}
latest_run_status = str(latest_intake_run.get('status') or '').strip().lower()
if latest_run_status == 'failed':
# 收口 completed 但最新 Run 失败(含历史脏数据):按失败裁决并提供重解析。
return (
'failed',
stage,
str(latest_intake_run.get('error_code') or '') or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED',
)
if latest_run_status == 'review_required' and task is None and case is None:
# 收口 completed 但最新 Run 需人工且未物化 Case/OT(如 XFA 身份门禁
# 在命中后拒绝、候选从未创建):停「需处理」并下发重解析入口,
# 禁止落到处理中(回归 SNER-20261014-E27D657F)。
return ('waiting_human', stage or 'candidate_creating', 'run_review_required')
# 无 OT/无处置的收口完成与全量视图同判词:停接收解析(处理中)。
return 'running', stage, None
if raw in {'cancelled', 'archived'}:
return raw, raw, None
return 'running', stage, None
@@ -4499,9 +4531,23 @@ def project_conversation_processing_summary(
stage = 'candidate_creating'
case_status = str(getattr(case, 'status', None) or '').strip().lower()
terminal_case = case_status in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}
extraction_failed = str(document.order_extraction_status or '').strip().lower() in {
'failed', 'parse_failed', 'technical_retrying',
}
# 抽取需人工事实除文档级状态外,还认「无 OT/无 Case 且最新 Run 失败或需人工」:
# 历史/并发脏数据可能把 Unit 全失败的附件写成 completed(抽取收口语义);
# Run 收口 review_required 但未物化 Case/OT(XFA 门禁拒绝)同理,
# 此时仍必须下发重解析入口,与 _status 的裁决同源。
latest_intake_run_status = str(
(latest_run_by_intake_id.get(int(document.intake_id)) or {}).get('status') or ''
).strip().lower()
extraction_failed = (
str(document.order_extraction_status or '').strip().lower() in {
'failed', 'parse_failed', 'technical_retrying',
}
or (
task is None
and case is None
and latest_intake_run_status in {'failed', 'review_required'}
)
)
task_no = str(task.task_no).strip() if task is not None else None
available_actions: list[str] = []
primary_action: dict[str, Any] | None = None
@@ -61,7 +61,11 @@ from app.services.shipping_notice.lifecycle_projection import (
LIFECYCLE_STAGES,
project_lifecycle,
)
from app.services.shipping_notice.query_service import resolve_task_export_download, serialize_task_summary
from app.services.shipping_notice.query_service import (
can_download_task_export,
resolve_task_export_download,
serialize_task_summary,
)
from app.services.shipping_notice.state_machine import (
UserMode,
)
@@ -1158,10 +1162,19 @@ def _build_stage_context(
}
def _build_edit_window(task: ShippingNotice) -> dict[str, Any]:
"""二期编辑窗(D10)谓词:header/lines 可编辑矩阵,工作台以此隐藏/禁用出单入口。"""
from app.services.shipping_notice import order_edit_window_service as order_edit_window
return order_edit_window.editable_scope(task)
def build_task_ui_state(
task: ShippingNotice,
*,
include_stage_context: bool = False,
viewer_user_id: int | None = None,
viewer_is_admin: bool = False,
) -> dict[str, Any]:
"""
构建单票任务 UI State。
@@ -1170,6 +1183,14 @@ def build_task_ui_state(
禁止 Chat、通知卡与任务中心分别推导状态;
可点击用户动作只由 Gate 与已验证 Artifact 授权产生。
Gate 摘要只查一次,再派生 position/user_mode,禁止再走 resolve_task_ui_state 二次查库。
Args:
task: 源任务实体。
include_stage_context: 是否附带 stage_context(工作面只读事实)。
viewer_user_id: 当前查看者;给定时时 download_excel 动作按导出统一谓词
(can_download_task_export:创建者或管理员)门禁下发;为 None 时维持
聊天链路旧口径(仅按 Artifact 授权,聊天会话与创建者同源)。
viewer_is_admin: 查看者是否平台管理员(配合 viewer_user_id 使用)。
"""
from app.services.shipping_notice.state_machine import (
_review_status_fallback_ui_state,
@@ -1210,7 +1231,12 @@ def build_task_ui_state(
# [AUTHORITY] Gate 负责当前可写恢复动作;Excel 下载是已产出文件的只读动作,
# 两者不能相互覆盖。即使当前 Gate 阻断并清空旧动作,也只在
# Artifact 已通过 resolve_task_export_download 校验时补入下载授权。
if resolve_task_export_download(task) is not None:
# 下载动作与导出端点消费同一谓词:viewer 已知时按创建者/管理员门禁,
# 避免非创建者"看得到点不动";viewer 未知(聊天链路)维持 Artifact 口径。
if resolve_task_export_download(task) is not None and (
viewer_user_id is None
or can_download_task_export(task, user_id=int(viewer_user_id), is_admin=viewer_is_admin)
):
download_action = _unified_action({
'id': 'download_excel',
'label': '下载 Excel',
@@ -1250,6 +1276,10 @@ def build_task_ui_state(
)
if include_stage_context else None
)
edit_window = (
_build_edit_window(task)
if include_stage_context else None
)
reason = None
if isinstance(process_gate, dict) and process_gate.get("blocking_reason_code"):
reason = {
@@ -1271,6 +1301,9 @@ def build_task_ui_state(
"actions": actions,
# 仅正式详情按需返回的工作面只读事实;不产生状态、权限或动作。
**({'stage_context': stage_context} if stage_context is not None else {}),
# 二期编辑窗门控矩阵(无 Export Artifact 且无活动 Attempt 才可编辑);
# 波次出单工具条与字段编辑守卫的数据源,禁止再次静默丢失。
**({'edit_window': edit_window} if edit_window is not None else {}),
"reason": reason,
# OT 与 Notice 字段不完全同构:禁止硬读 Notice 专属列。
"lifecycle_status": getattr(task, "lifecycle_status", None) or getattr(task, "status", None),
@@ -0,0 +1,97 @@
"""补齐设备验收预警的企微事件、第 4 轮开关和 Excel 归档。
Revision ID: eah8c9d0e1f2
Revises: b7a2b2155155
Create Date: 2026-10-13 14:30:00.000000
用途:把尚未提交的三步收成一次升级。已有库如果停在本版本,结构已经齐,不会重跑。
依赖:b7a2b2155155、app_settings、equipment_acceptance_settings、users。
逻辑:企微事件名单末尾补上 equipment_acceptance_warning;第 4 轮默认关闭;按收件人留下发送时的 Excel。
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import text
revision = "eah8c9d0e1f2"
down_revision = "b7a2b2155155"
branch_labels = None
depends_on = None
_KEY = "WECOM_NOTIFY_EVENTS"
_EVENT = "equipment_acceptance_warning"
def _split_events(raw: str | None) -> list[str]:
"""按逗号拆开事件名单,去掉空白项。"""
return [part.strip() for part in str(raw or "").split(",") if part.strip()]
def upgrade():
"""补上企微事件、第 4 轮开关,并建立按收件人归档 Excel 的表。"""
_append_wecom_event()
op.add_column(
"equipment_acceptance_settings",
sa.Column("round_4_enabled", sa.Boolean(), nullable=False, server_default=sa.false()),
)
op.create_table(
"equipment_acceptance_send_files",
sa.Column("id", sa.Integer(), primary_key=True),
sa.Column("recipient_user_id", sa.Integer(), nullable=True),
sa.Column("recipient_name", sa.String(length=200), nullable=True),
sa.Column("excel_file_name", sa.String(length=255), nullable=True),
sa.Column("excel_file_data", sa.LargeBinary(), nullable=True),
sa.Column("excel_file_size", sa.Integer(), nullable=True),
sa.Column("send_record_ids", sa.JSON(), nullable=True),
sa.Column("status", sa.String(length=32), nullable=False),
sa.Column("error_message", sa.Text(), nullable=True),
sa.Column("sent_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["recipient_user_id"], ["users.id"], ondelete="SET NULL"),
)
op.create_index(
"ix_equipment_acceptance_send_files_created",
"equipment_acceptance_send_files",
["created_at"],
)
def downgrade():
"""按相反顺序去掉 Excel 归档、第 4 轮开关和企微事件。"""
op.drop_index("ix_equipment_acceptance_send_files_created", table_name="equipment_acceptance_send_files")
op.drop_table("equipment_acceptance_send_files")
op.drop_column("equipment_acceptance_settings", "round_4_enabled")
_remove_wecom_event()
def _append_wecom_event() -> None:
"""已有事件名单时在末尾补上设备验收预警。没有这一行则不插入。"""
bind = op.get_bind()
if "app_settings" not in sa.inspect(bind).get_table_names():
return
row = bind.execute(text("SELECT value FROM app_settings WHERE key = :key"), {"key": _KEY}).fetchone()
if row is None:
return
events = _split_events(row[0])
if _EVENT in events:
return
events.append(_EVENT)
bind.execute(
text("UPDATE app_settings SET value = :value, updated_at = CURRENT_TIMESTAMP WHERE key = :key"),
{"key": _KEY, "value": ",".join(events)},
)
def _remove_wecom_event() -> None:
"""从已保存的企微事件名单里去掉设备验收预警。没有这一行时不处理。"""
bind = op.get_bind()
if "app_settings" not in sa.inspect(bind).get_table_names():
return
row = bind.execute(text("SELECT value FROM app_settings WHERE key = :key"), {"key": _KEY}).fetchone()
if row is None:
return
events = [part for part in _split_events(row[0]) if part != _EVENT]
bind.execute(
text("UPDATE app_settings SET value = :value, updated_at = CURRENT_TIMESTAMP WHERE key = :key"),
{"key": _KEY, "value": ",".join(events)},
)
@@ -0,0 +1,517 @@
"""
tests/test_customer_resolution_rebind.py
用途:确认客户改绑(customer_resolution_service.rebind_confirmed_customer)契约测试。
依赖:内存数据库、客户识别结果服务、order_freeze_service(真实冻结链)、
order_edit_window_service(编辑窗 header 谓词)、ShippingExportArtifact。
逻辑:已确认订单在产生发货通知/Excel 之前允许直接修改确认客户;改绑同步刷新冻结快照客户,
并保持 evidence_json / identity_rule_set_checksum 非空冻结契约;Excel 已产生 / 活动
Gate Attempt / 同客户 / 未知或停用客户 / 未确认识别结果均 fail-closed 且零副作用。
"""
from __future__ import annotations
from decimal import Decimal
import pytest
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingAuditEvent,
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingExportArtifact,
ShippingInventoryParsingProfile,
ShippingNotice,
ShippingOrderCandidate,
ShippingOrderExtraction,
ShippingOrderField,
ShippingOrderIntake,
ShippingOrderLine,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderTask,
User,
)
from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer
from app.services.shipping_notice.order_review_customer_service import project_review_case_customer_resolution
from app.services.shipping_notice.order_freeze_service import (
HEADER_FIELD_PROJECTIONS,
LINE_FIELD_PROJECTIONS,
freeze_order_snapshot,
)
from tests.conftest import parse_api_error
def _build_confirmed_frozen_order(*, suffix: str) -> dict:
"""构造已确认客户 + 已冻结快照 + 未产生 Excel 的正式订单(编辑窗 header 可编辑)。"""
user = User(username=f'rebind-user-{suffix}', email=f'rebind-user-{suffix}@example.test', password_hash='x')
old_customer = ShippingCustomer(standard_name='原确认客户', short_code='OLD', status='active')
new_customer = ShippingCustomer(standard_name='新确认客户', short_code='NEWC', status='active')
inactive_customer = ShippingCustomer(standard_name='停用客户', short_code='OFF', status='inactive')
task = ShippingOrderTask(task_no=f'OT-REBIND-{suffix}', source_type='direct_pdf', user_id=1, order_data_version=7)
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Rebind frozen order')
db.session.add_all([user, old_customer, new_customer, inactive_customer, task, schema])
db.session.flush()
from app.services.shipping_notice import field_asset_service
field_asset_service.ensure_standard_assets_seeded()
definitions = []
fields: dict[str, ShippingOrderField] = {}
for code in [*HEADER_FIELD_PROJECTIONS, *LINE_FIELD_PROJECTIONS]:
scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line'
field = ShippingOrderField.query.filter_by(field_code=code, scope=scope).one()
fields[code] = field
definitions.append({'field_id': field.id, 'field_code': code, 'scope': scope, 'value_type': field.value_type, 'enabled': True})
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={'fields': definitions}, checksum='rebind-test',
)
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
db.session.add(line)
db.session.flush()
values = {
'customer_po_number': 'PO-REBIND', 'customer_code': 'C-001', 'customer_name': 'Customer',
'part_number': '000123', 'reservation_id': '0012345678', 'qty': Decimal('12.50'),
'unit_price': Decimal('2.30'), 'line_amount_with_tax': Decimal('28.75'), 'uom': 'PCS',
}
for code, field in fields.items():
value = values.get(code)
decision = _make_decision(extraction, line, field, code, value)
db.session.add(decision)
db.session.flush()
if value is not None:
db.session.add(_make_field_value(extraction, line, field, decision, value))
task.current_order_extraction_id = extraction.id
intake = ShippingOrderIntake(
intake_no=f'INT-REBIND-{suffix}', asset_id=1, user_id=user.id, parser_version='test',
)
db.session.add(intake)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no=f'CAND-REBIND-{suffix}', intake_id=intake.id, primary_document_id=1,
candidate_key=f'rebind-{suffix}', order_extraction_id=extraction.id, candidate_status='accepted',
)
db.session.add(candidate)
db.session.flush()
task.candidate_id = candidate.id
task.user_id = int(user.id)
resolution = ShippingCustomerShadowResolution(
candidate_id=candidate.id, intake_id=intake.id, resolution_version='test.v1', status='confirmed',
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': old_customer.short_code}],
candidate_matches_json=[
{'customer_id': old_customer.id, 'score': 100},
{'customer_id': new_customer.id, 'score': 90},
],
resolution_context_json={'rule_set': {'checksum': 'f' * 64}},
identity_rule_set_checksum='f' * 64, top_customer_id=old_customer.id, top_score=100,
confirmed_customer_id=old_customer.id, confirmation_method='manual', confirmed_by_id=user.id,
)
notice = ShippingNotice(task_no=f'SN-REBIND-{suffix}', order_task_id=task.id)
db.session.add_all([resolution, notice])
db.session.flush()
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
db.session.commit()
return {
'user': user, 'task': task, 'notice': notice, 'resolution': resolution,
'old_customer': old_customer, 'new_customer': new_customer, 'inactive_customer': inactive_customer,
'snapshot': snapshot, 'schema_version_id': int(version.id),
}
def _make_decision(extraction, line, field, code, value):
"""构造单头/行字段裁决行(与既有快照测试同构)。"""
from app.models import ShippingOrderFieldDecision
return ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=None if code in HEADER_FIELD_PROJECTIONS else line.id,
field_id=field.id, decision_status='accepted',
resolved_value_json=str(value) if isinstance(value, Decimal) else value,
supporting_observation_ids_json=[],
)
def _make_field_value(extraction, line, field, decision, value):
"""构造字段值投影行(Decimal 保留精度,料号/预约号保留前导零)。"""
from app.models import ShippingOrderFieldValue
return ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=None if field.scope == 'header' else line.id,
field_id=field.id, decision_id=decision.id,
value_json=str(value) if isinstance(value, Decimal) else value,
value_text=str(value) if isinstance(value, str) else None,
value_decimal=value if isinstance(value, Decimal) else None,
)
def _attach_ready_export_artifact(notice: ShippingNotice) -> None:
"""给通知挂一个 ready 导出产物(Excel 已产生,header 编辑窗关闭)。"""
from app.models import ShippingOrderSchema as Schema
from app.models import ShippingOrderSchemaVersion, ShippingOrderExtraction
template = _template_row()
profile = ShippingInventoryParsingProfile(
profile_code='REBIND_PROFILE', display_name='Rebind profile', version=1, status='published',
file_format='xlsx', definition_json={},
)
schema = Schema(schema_code='REBIND_SCHEMA', display_name='Rebind schema')
db.session.add_all([template, profile, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={}, checksum='b' * 64,
)
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted')
db.session.add(extraction)
db.session.flush()
db.session.add(ShippingExportArtifact(
task_id=int(notice.id), artifact_no=f'ART-REBIND-{notice.task_no}', template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='d' * 64,
file_path='rebind.xlsx', file_name='rebind.xlsx', file_checksum='e' * 64,
file_size=1, status='ready',
))
db.session.flush()
_TEMPLATE_CACHE: dict = {}
def _template_row():
"""复用同进程内已建模板,避免不同用例重复建模板造成噪音。
缓存需自愈:每测试独立 create_all/drop_all,缓存 id 在新 DB 中可能不存在
(该脆弱组合即 Task 1 评审预警项),取不到时重建并刷新缓存。
"""
from app.models import ShippingExcelTemplate
cached_id = _TEMPLATE_CACHE.get('id')
if cached_id is not None:
template = db.session.get(ShippingExcelTemplate, int(cached_id))
if template is not None:
return template
_TEMPLATE_CACHE.pop('id', None)
template = ShippingExcelTemplate(
template_code='REBIND_TPL', display_name='Rebind template', version=1, status='published',
storage_bucket='test', storage_key='rebind-tpl.xlsx', original_filename='rebind-tpl.xlsx',
file_checksum='a' * 64, definition_json={},
)
db.session.add(template)
db.session.flush()
_TEMPLATE_CACHE['id'] = int(template.id)
return template
def _resolution_of(task: ShippingOrderTask) -> ShippingCustomerShadowResolution:
"""按 OT 的候选反查唯一识别结果行。"""
return ShippingCustomerShadowResolution.query.filter_by(candidate_id=int(task.candidate_id)).one()
def _attach_confirmed_revision(fx: dict, *, suffix: str):
"""构造建单确认修订,把冻结任务挂到真实复核 Case 上(审计 review_case_no 反查依赖)。"""
from app.models import ShippingOrderReviewConfirmedRevision
_user, case = _seed_review_case(suffix=suffix)
db.session.add(ShippingOrderReviewConfirmedRevision(
case_id=int(case.id), task_id=int(fx['task'].id), draft_version=1,
schema_version_id=int(fx['schema_version_id']),
idempotency_key=f'IDEM-REBIND-{suffix}',
confirmed_by_id=int(fx['user'].id),
))
# 生产确认路径会把任务挂上 Case;改绑投影经 confirmed_task_id 反查确认结果。
case.confirmed_task_id = int(fx['task'].id)
db.session.flush()
return case
def test_rebind_updates_confirmed_customer_and_refreezes_snapshot(app):
"""改绑必须更新确认结果并按新客户重冻结快照(客户 ODM 白名单随新客户生效)。"""
with app.app_context():
fx = _build_confirmed_frozen_order(suffix='happy')
# Case 反查夹具的 suffix 必须大写(intake_no 查找统一 upper 归一)。
case = _attach_confirmed_revision(fx, suffix='HAPPY-CASE')
result = rebind_confirmed_customer(
task=fx['task'], new_customer_id=int(fx['new_customer'].id),
actor_id=int(fx['user'].id), expected_order_data_version=7, reason='选错客户',
)
db.session.commit()
resolution = result['resolution']
snapshot = result['snapshot']
# 断言意图:确认结果与快照客户同步改绑;审计与 evidence_json 记录原客户(可追溯)。
assert resolution.confirmed_customer_id == int(fx['new_customer'].id)
assert snapshot.customer_id == int(fx['new_customer'].id)
assert snapshot.customer_short_code_snapshot == str(fx['new_customer'].short_code)
rebind_record = next(
item for item in (resolution.evidence_json or [])
if isinstance(item, dict) and item.get('rebind')
)
assert rebind_record['rebind']['previous_customer_id'] == int(fx['old_customer'].id)
assert rebind_record['rebind']['new_customer_id'] == int(fx['new_customer'].id)
assert rebind_record['rebind']['actor_id'] == int(fx['user'].id)
assert rebind_record['rebind']['reason'] == '选错客户'
assert resolution.identity_rule_set_checksum == 'f' * 64 # 冻结契约:保持非空
# 原始识别证据保留(rebind 记录是追加,不是覆盖)。
assert resolution.evidence_json[0]['definition_code'] == 'test_customer'
# 快照唯一约束(uq task_id):一个任务一份快照,改绑是原地刷新而非新行。
assert int(snapshot.id) == int(fx['snapshot'].id)
assert fx['task'].order_snapshot_id == snapshot.id
# 审计事件:before/after 携带原/新确认客户与原因;挂 review_case_no 供 Case 时间线查询。
event = ShippingAuditEvent.query.filter_by(
event_type='review_customer_rebound', aggregate_id=str(fx['task'].task_no),
).one()
assert event.before_snapshot_json['previous_value'] == int(fx['old_customer'].id)
assert event.after_snapshot_json['new_value'] == int(fx['new_customer'].id)
assert event.reason == '选错客户'
assert event.actor_type == 'user'
assert event.review_case_no == str(case.case_no)
# 改绑后投影以确认结果+客户主数据为权威展示:名字/简称/改绑谓词直供工作台。
projection = project_review_case_customer_resolution(case=case)
assert projection['standard_name'] == str(fx['new_customer'].standard_name)
assert projection['short_code'] == str(fx['new_customer'].short_code)
assert projection['customer_id'] == int(fx['new_customer'].id)
assert projection['rebind_allowed'] is True
def test_task_ui_state_emits_edit_window_gate_for_workbench(app):
"""工作台 payload 必须下发 edit_window(D10 门控数据源,防合并再次丢失)。
回归背景:前端波次出单工具条的显示条件读 ui_state.edit_window.header,
后端曾把该字段丢失,导致 Excel 已产生仍显示「生成发货通知和 Excel」工具条。
"""
fx = _build_confirmed_frozen_order(suffix='ew')
from app.services.shipping_notice.ui_state import build_task_ui_state
ui = build_task_ui_state(fx['notice'], include_stage_context=True)
# 断言意图:Excel 未产生时 header=True(出单工具条显示)。
assert ui['edit_window']['header'] is True
_attach_ready_export_artifact(fx['notice'])
ui_after = build_task_ui_state(fx['notice'], include_stage_context=True)
# 断言意图:Excel 已产生时 header=False(出单工具条隐藏——用户报告的缺陷)。
assert ui_after['edit_window']['header'] is False
# OT 身份构建必须与通知身份同判(editable_scope 身份归一):用户场景即按 OT 加载详情。
ui_by_ot = build_task_ui_state(fx['task'], include_stage_context=True)
assert ui_by_ot['edit_window']['header'] is False
def test_rebind_rejects_when_export_artifact_exists(app):
"""已产生 Excel(header 不可编辑)时改绑必须 409,且确认结果不被改动。"""
with app.app_context():
fx = _build_confirmed_frozen_order(suffix='excel')
_attach_ready_export_artifact(fx['notice'])
case = _attach_confirmed_revision(fx, suffix='EXCEL-CASE')
# 断言意图:Excel 已产生时投影谓词 fail-closed(前端「修改客户」按钮禁用的数据源)。
assert project_review_case_customer_resolution(case=case)['rebind_allowed'] is False
with pytest.raises(ConflictError) as exc:
rebind_confirmed_customer(
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
expected_order_data_version=7,
)
# 断言意图:A 管控 fail-closed;错误码可前端定位(details 区分 Excel / 活动 Attempt)。
assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED'
assert exc.value.details['excel_exists'] is True
assert exc.value.details['active_attempt'] is False
db.session.rollback()
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
def test_rebind_rejects_when_active_gate_attempt_exists(app, monkeypatch):
"""存在活动 Gate Attempt(库存 RPA / 匹配处理中)时改绑必须 409。"""
monkeypatch.setattr(
'app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt',
lambda n: True,
)
with app.app_context():
fx = _build_confirmed_frozen_order(suffix='busy')
with pytest.raises(ConflictError) as exc:
rebind_confirmed_customer(
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
expected_order_data_version=7,
)
assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED'
assert exc.value.details['excel_exists'] is False
assert exc.value.details['active_attempt'] is True
db.session.rollback()
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
def test_rebind_rejects_same_customer_and_unknown_customer(app):
"""同客户重复改绑与不存在/停用客户都必须 409/404,不产生副作用。"""
with app.app_context():
fx = _build_confirmed_frozen_order(suffix='guards')
with pytest.raises(ConflictError) as same:
rebind_confirmed_customer(
task=fx['task'], new_customer_id=int(fx['old_customer'].id), actor_id=int(fx['user'].id),
expected_order_data_version=7,
)
assert same.value.code == 'SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER'
with pytest.raises(NotFoundError) as unknown:
rebind_confirmed_customer(
task=fx['task'], new_customer_id=999999, actor_id=int(fx['user'].id),
expected_order_data_version=7,
)
assert unknown.value.code == 'SHIPPING.CUSTOMER_NOT_FOUND'
with pytest.raises(ConflictError) as inactive:
rebind_confirmed_customer(
task=fx['task'], new_customer_id=int(fx['inactive_customer'].id), actor_id=int(fx['user'].id),
expected_order_data_version=7,
)
assert inactive.value.code == 'SHIPPING.CUSTOMER_INACTIVE'
# 断言意图:拒绝路径零副作用(确认结果与快照均不被触碰)。
db.session.rollback()
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
assert fx['task'].order_snapshot_id == fx['snapshot'].id
def test_rebind_requires_confirmed_resolution(app):
"""识别结果未确认(或缺失)时改绑必须 409,提示走既有识别确认流程。"""
with app.app_context():
fx = _build_confirmed_frozen_order(suffix='unconfirmed')
resolution = _resolution_of(fx['task'])
resolution.status = 'unique_candidate'
db.session.commit()
with pytest.raises(ConflictError) as exc:
rebind_confirmed_customer(
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
expected_order_data_version=7,
)
assert exc.value.code == 'SHIPPING.CUSTOMER_RESOLUTION_REQUIRED'
db.session.rollback()
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
def test_rebind_rejects_stale_version_without_side_effects(app):
"""[断言] 客户端版本比较在守卫阶段执行:版本不一致必须 409 且零副作用(不写确认结果/审计/快照)。"""
with app.app_context():
fx = _build_confirmed_frozen_order(suffix='stale')
with pytest.raises(ConflictError) as exc:
rebind_confirmed_customer(
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
expected_order_data_version=6,
)
# 断言意图:乐观锁在写前拒绝;details 呈现 expected/actual 供前端提示刷新。
assert exc.value.code == 'SHIPPING.ORDER_DATA_VERSION_MISMATCH'
assert exc.value.details == {'expected': 6, 'actual': 7}
db.session.rollback()
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
assert fx['task'].order_snapshot_id == fx['snapshot'].id
assert ShippingAuditEvent.query.filter_by(event_type='review_customer_rebound').count() == 0
def test_rebind_requires_operator_for_internal_call(app):
"""[断言] 缺少执行人的内部调用按参数错误拒绝(独立于编辑窗 A 管控语义)。"""
with app.app_context():
fx = _build_confirmed_frozen_order(suffix='no-actor')
with pytest.raises(ValidationError) as exc:
rebind_confirmed_customer(
task=fx['task'], new_customer_id=int(fx['new_customer'].id),
actor_id=None, expected_order_data_version=7,
)
assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED'
db.session.rollback()
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
# ---------------------------------------------------------------------------
# API 路由层(POST /api/workspace/shipping-notice/order-review-cases/<case_no>/customer/rebind)
# ---------------------------------------------------------------------------
def _seed_review_case(*, suffix: str):
"""构造属主用户与其复核 Case(未建正式 OT,够验证路由守卫)。"""
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
user, agent, session, intake, _document = _seed_run_input(suffix=suffix)
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
case = ensure_run_review_cases(run=run)[0]
db.session.commit()
return user, case
def _auth_headers(user) -> dict:
from app.core.auth.jwt import issue_local_access_token
return {'Authorization': f'Bearer {issue_local_access_token(user)}'}
def test_rebind_api_requires_customer_id(app):
"""[断言] 缺少 customer_id 的请求体被 400 拦截,错误码可前端定位。"""
with app.app_context():
user, case = _seed_review_case(suffix='API-BODY')
client = app.test_client()
response = client.post(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
headers=_auth_headers(user), json={},
)
error = parse_api_error(response.get_json())
assert response.status_code == 400
assert error['code'] == 'SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED'
def test_rebind_api_requires_expected_version(app):
"""[断言] 缺少 expected_order_data_version 的请求体被 400 拦截(乐观锁必填)。"""
with app.app_context():
user, case = _seed_review_case(suffix='API-VER')
client = app.test_client()
response = client.post(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
headers=_auth_headers(user), json={'customer_id': 1},
)
error = parse_api_error(response.get_json())
assert response.status_code == 400
assert error['code'] == 'SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED'
assert error['details']['field'] == 'expected_order_data_version'
def test_rebind_api_rejects_case_outside_ownership(app):
"""[断言] 非属主访问他人 Case 必须按不存在拒绝(404),不泄露存在性。"""
with app.app_context():
owner, case = _seed_review_case(suffix='API-OWNER')
# agent_code 全局唯一,非属主用户须使用独立 agent_code。
from tests.test_shipping_order_extraction_runs import _seed_run_input
outsider, _a, _s, _i, _d = _seed_run_input(suffix='API-OUTSIDER', agent_code='shipping_notice_rebind')
client = app.test_client()
response = client.post(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
headers=_auth_headers(outsider),
json={'customer_id': 1, 'expected_order_data_version': 1},
)
error = parse_api_error(response.get_json())
assert response.status_code == 404
assert error['code'] == 'SHIPPING.REVIEW_CASE_NOT_FOUND'
assert owner is not None
def test_rebind_api_requires_formal_order_task(app):
"""[断言] Case 尚未确认建单(无正式 OT)时改绑必须 409。"""
with app.app_context():
user, case = _seed_review_case(suffix='API-NOOT')
client = app.test_client()
response = client.post(
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
headers=_auth_headers(user),
json={'customer_id': 1, 'expected_order_data_version': 1},
)
error = parse_api_error(response.get_json())
assert response.status_code == 409
assert error['code'] == 'SHIPPING.FORMAL_OT_REQUIRED'
@@ -0,0 +1,58 @@
"""
tests/test_equipment_acceptance_alert_notice.py
用途:锁定设备验收企微汇总文案和 Excel 列。
依赖:alert_notice、openpyxl。
逻辑:不连数据库,不发企业微信。卡片只写张数。工作簿含申请人,不写主送。
"""
from io import BytesIO
import pytest
from openpyxl import load_workbook
pytestmark = pytest.mark.pure_unit
from app.services.equipment_acceptance.alert_notice import (
NOTICE_HEADERS,
build_notice_workbook,
summary_message,
)
def test_summary_counts_rounds_without_listing_orders():
"""第一行写已逾期张数。正文不出现验收单号,也不写主送。"""
text = summary_message([
{"threshold_days": 30},
{"threshold_days": 30},
{"threshold_days": 37},
])
assert text == "共 3 张验收单已逾期。\n超过 30 天 2 张,超过 37 天 1 张。\n明细见下一条文件。"
assert "主送" not in text
assert "20260210" not in text
def test_workbook_includes_applicant_and_identity():
"""Excel 列与原型一致。通知身份保留角色名,停留天数为空时写横线。"""
data = build_notice_workbook([{
"acceptance_no": "20260210000001",
"purchase_order_no": "1111",
"applicant": "孙浩",
"threshold_days": 30,
"dwell_days": None,
"node_name": "使用部门担当",
"handlers": "吴敏",
"identity": "直接主管",
}])
sheet = load_workbook(BytesIO(data)).active
assert [cell.value for cell in sheet[1]] == list(NOTICE_HEADERS)
assert [cell.value for cell in sheet[2]] == [
"20260210000001",
"1111",
"孙浩",
"超过 30 天",
"—",
"使用部门担当",
"吴敏",
"直接主管",
]
@@ -30,6 +30,7 @@ def test_due_tiers_use_strictly_greater_than_threshold():
assert due_tiers(31, _DAYS) == [1]
assert due_tiers(51, _DAYS) == [1, 2, 3]
assert due_tiers(52, _DAYS) == [1, 2, 3, 4]
assert due_tiers(52, _DAYS, max_tier=3) == [1, 2, 3]
def test_tier_one_keeps_missing_supervisor_as_failure():
@@ -1,15 +1,15 @@
"""
tests/test_equipment_acceptance_config.py
用途:锁定设备验收预警四档天数的保存前校验。
依赖:config_service.validate_reminder_days、ValidationError。
逻辑:不连数据库。默认 30/37/44/51 通过;相等、倒序、非整数和空岗位以外的天数形状被拒绝。
用途:锁定设备验收预警四档天数和第 4 轮开关的保存前校验。
依赖:config_service.validate_reminder_days、parse_round_4_enabled、ValidationError。
逻辑:不连数据库。默认 30/37/44/51 通过;相等、倒序、非整数和空岗位以外的天数形状被拒绝。第 4 轮缺省关闭。
"""
import pytest
from app.core.errors import ValidationError
from app.services.equipment_acceptance.config_service import validate_reminder_days
from app.services.equipment_acceptance.config_service import parse_round_4_enabled, validate_reminder_days
def test_default_reminder_days_pass():
@@ -30,3 +30,13 @@ def test_days_reject_bool_and_wrong_length():
validate_reminder_days([True, 37, 44, 51])
with pytest.raises(ValidationError):
validate_reminder_days([30, 37, 44])
def test_round_4_defaults_off_and_rejects_non_bool():
"""未传开关时按关闭处理。数字 1 不能当成启用,避免误通知总经理。"""
assert parse_round_4_enabled(None) is False
assert parse_round_4_enabled(False) is False
assert parse_round_4_enabled(True) is True
with pytest.raises(ValidationError) as caught:
parse_round_4_enabled(1)
assert caught.value.code == "EQUIPMENT_ACCEPTANCE.SETTINGS_INVALID"
@@ -0,0 +1,121 @@
"""
tests/test_inventory_source_gate_notice_task.py
用途:锁定「库存源稳定门禁 / 库存身份对 ShippingNotice 的归一」契约。
依赖:pytest、inventory_source_gate、inventory_candidate_projection、app 夹具(内存测试库)。
逻辑:货代上传入口按 business_no 加载 Notice,而候选集事实挂在 OT 上;门禁必须沿
order_task_id 归一读取。历史缺陷:Notice 缺 active_inventory_candidate_set_id
字段导致 is_inventory_source_stable(Notice) 恒 False,RPA 上传被
「库存源尚未确定」静默拦截(无事件、无 attempt 记录)。
"""
from __future__ import annotations
def _make_frozen_task_with_notice(task_no: str):
"""构造带冻结候选集(单源 CRANE)的 OT 及其已绑定 Notice。"""
from app import db
from app.models import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingNotice,
ShippingOrderTask,
)
task = ShippingOrderTask(task_no=task_no, source_type='direct_pdf', user_id=1)
db.session.add(task)
db.session.flush()
candidate_set = ShippingInventoryCandidateSet(
task_id=int(task.id),
set_version=1,
lifecycle_status='frozen',
input_fingerprint=f'fp-{task_no}',
routing_rule_version_json={},
)
db.session.add(candidate_set)
db.session.flush()
db.session.add(ShippingInventoryCandidateSource(
candidate_set_id=int(candidate_set.id),
source_code='CRANE',
candidate_order=1,
candidate_origin='rule',
))
db.session.add(ShippingInventoryCandidateLine(
candidate_set_id=int(candidate_set.id),
line_no=1,
part_number='PN-1',
reservation_id='3000092917',
source_codes_json=['CRANE'],
))
task.active_inventory_candidate_set_id = int(candidate_set.id)
db.session.flush()
notice = ShippingNotice(
task_no=f'SN-{task_no}',
order_task_id=int(task.id),
business_no=f'USZ{task_no[-6:]}',
user_id=1,
)
db.session.add(notice)
db.session.flush()
return task, notice
def _patch_source_lookup(monkeypatch):
"""注入启用的 CRANE 源配置(inventory_match 动态仓),免建 RPA Profile。"""
from app.services.shipping_notice import inventory_source_gate as gate_mod
def _source(code):
if str(code).upper() != 'CRANE':
return None
return {
'source_code': 'CRANE',
'display_name': 'Crane FootPrint',
'connector_type': 'crane',
'warehouse_resolution_mode': 'inventory_match',
'fixed_warehouse_id': None,
'enabled': True,
}
monkeypatch.setattr(gate_mod, 'get_database_inventory_source', _source)
def test_inventory_source_stable_resolves_notice_to_order_task(app, monkeypatch):
"""门禁对 Notice 必须沿 order_task_id 读取冻结候选集,判定与 OT 一致。"""
_patch_source_lookup(monkeypatch)
with app.app_context():
from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
task_inventory_identity,
)
task, notice = _make_frozen_task_with_notice('OT-NOTICE-GATE-OK')
# 断言意图:OT 与其 Notice 的稳定性判定一致(历史缺陷:Notice 恒 False)
assert is_inventory_source_stable(task) is True
assert is_inventory_source_stable(notice) is True
# 断言意图:库存身份(RPA 网点/仓库)对两者一致,且能解析到源
identity_ot = task_inventory_identity(task)
identity_notice = task_inventory_identity(notice)
assert identity_ot == identity_notice
assert identity_notice['inventory_source_code'] == 'CRANE'
def test_inventory_source_stable_fail_closed_without_order_task(app, monkeypatch):
"""Notice 缺 OT 绑定时保持 fail-closed(不得误判稳定)。"""
_patch_source_lookup(monkeypatch)
with app.app_context():
from app import db
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
orphan = ShippingNotice(
task_no='SN-ORPHAN-NOTICE',
business_no='USZORPH01',
user_id=1,
)
db.session.add(orphan)
db.session.flush()
# 断言意图:无法归一到 OT 的 Notice 保持 fail-closed
assert is_inventory_source_stable(orphan) is False
@@ -187,3 +187,91 @@ def test_persist_updates_part_available_qty_on_existing_row(app):
assert rows[0].part_available_qty is None
# 断言意图:同快照幂等更新,始终只有一条 current 事实
assert len(rows) == 1
# ---------------------------------------------------------------------------
# 行级文件归因契约(多源池:锚点文件 ≠ 命中文件)
# ---------------------------------------------------------------------------
def _make_inventory_file(app, file_no: str, warehouse_id: str) -> int:
"""构造最小可用库存快照文件,返回主键。"""
from app import db
from app.models import ShippingInventoryFile
file_row = ShippingInventoryFile(
inventory_file_no=file_no,
storage_path=f'/tmp/{file_no}.xlsx',
source_code='DSV360_TEST',
warehouse_id=warehouse_id,
warehouse_code=warehouse_id,
snapshot_status='ready',
line_count=1,
share_mode='warehouse_pool',
)
db.session.add(file_row)
db.session.flush()
return int(file_row.id)
def _ok_result(*, line_index: int = 0, inventory_file_no: str | None = None) -> dict:
"""构造命中库存的行结果桩;inventory_file_no 模拟匹配器回填的命中文件身份。"""
result = {
'line_index': line_index,
'disposition': 'ok',
'part_number': 'PN-1',
'reservation_id': '3000092917',
'required_qty': 8.0,
'available_qty': 8.0,
}
if inventory_file_no is not None:
result['inventory_file_no'] = inventory_file_no
return result
def test_persist_attributes_line_to_hit_file_not_anchor(app):
"""多源池下行命中 B 文件时,inventory_snapshot_id 必须归因 B,而非任务锚点 A。
历史缺陷:持久化把任务级锚点文件 ID 盖到所有行,Excel 仓库列因此写成
锚点仓(AWSCV 单写成 CMH01)。
"""
with app.app_context():
from app import db
from app.models import ShippingInventoryFile
task = _make_snapshot_task('OT-LINE-FILE-ATTR')
anchor_id = _make_inventory_file(app, 'SIF-TEST-ANCHOR', 'BYAWSCMH01')
hit_id = _make_inventory_file(app, 'SIF-TEST-HIT', 'AWSCV')
rows = persist_line_inventory_match_facts(
task=task,
match_payload={
'line_results': [_ok_result(inventory_file_no='SIF-TEST-HIT')],
'resolutions': [],
},
inventory_snapshot_id=anchor_id,
)
# 断言意图:行事实挂到命中文件,而不是任务级锚点文件
assert rows[0].inventory_snapshot_id == hit_id
assert rows[0].matched_file_no == 'SIF-TEST-HIT'
# 断言意图:仓库身份可由命中文件直接推出(Excel 仓库列数据源)
hit_file = db.session.get(ShippingInventoryFile, rows[0].inventory_snapshot_id)
assert hit_file.warehouse_id == 'AWSCV'
def test_persist_falls_back_to_anchor_without_line_file_no(app):
"""行结果未回填文件号(如 not_found)时,保持任务级锚点回退,行为不变。"""
with app.app_context():
task = _make_snapshot_task('OT-LINE-FILE-FALLBACK')
anchor_id = _make_inventory_file(app, 'SIF-TEST-ANCHOR-FB', 'BYAWSCMH01')
rows = persist_line_inventory_match_facts(
task=task,
match_payload={
'line_results': [_not_found_result(part_available_qty=None)],
'resolutions': [],
},
inventory_snapshot_id=anchor_id,
)
# 断言意图:无命中文件身份的行回退锚点快照(历史行为兼容)
assert rows[0].inventory_snapshot_id == anchor_id
@@ -0,0 +1,85 @@
"""
tests/test_order_extraction_workspace_projection.py
用途:锁定工作台投影中 EML 父项状态的收敛契约。
依赖:order_extraction_workspace_projection._email_parent_rows。
逻辑:pure_unit;运行中的 Run(queued/processing)EML 父项维持既有口径
(parse_failed → failed,否则 processing);终态 Run 的 EML 父项必须跟随
Run 结果收敛(failed/cancelled/completed/review_required),禁止停留在
「处理中」——历史缺陷:全部 Unit 失败后父项仍显示处理中。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
from app.services.shipping_notice.order_extraction_workspace_projection import (
_email_parent_rows,
)
pytestmark = pytest.mark.pure_unit
def _run_stub(status: str, parse_status: str | None = 'parsed') -> SimpleNamespace:
return SimpleNamespace(
status=status,
finished_at=None,
input_snapshot_json={'intakes': [{'intake_id': 1, 'parse_status': parse_status}]},
)
def _documents() -> dict[int, dict]:
return {
906: {'document_id': 906, 'intake_id': 1, 'document_type': 'email_body', 'file_name': 'batch.eml'},
}
def test_queued_run_email_parent_stays_processing():
"""运行中(queued)且未解析失败:EML 父项维持「处理中」(既有口径零变化)。"""
rows = _email_parent_rows(
run=_run_stub('queued'),
documents=_documents(),
existing_document_ids=set(),
)
# 关键断言:queued 运行下父项 processing,阶段为邮件解析
assert rows[0]['status'] == 'processing'
assert rows[0]['user_visible_stage'] == 'email_parsing'
def test_failed_run_email_parent_converges_to_failed():
"""终态 failed 的 Run:EML 父项必须收敛为 failed,不得停留「处理中」。"""
rows = _email_parent_rows(
run=_run_stub('failed', parse_status=None),
documents=_documents(),
existing_document_ids=set(),
)
# 关键断言:冻结 parse_status 为 None(消费型 Intake)时,failed Run 的父项
# 曾无条件渲染 processing;现在必须跟随 Run 结果收敛
assert rows[0]['status'] == 'failed'
assert rows[0]['user_visible_stage'] == 'failed'
def test_review_required_run_email_parent_converges_to_review():
"""终态 review_required / partially_completed:父项收敛为需人工复核语义。"""
for status in ('review_required', 'partially_completed'):
rows = _email_parent_rows(
run=_run_stub(status),
documents=_documents(),
existing_document_ids=set(),
)
# 关键断言:两种终态都投影为 review_required(partially_completed 同义)
assert rows[0]['status'] == 'review_required', status
def test_parse_failed_intake_parent_stays_failed_under_active_run():
"""运行中但冻结 parse_status=parse_failed:父项仍为 failed(既有口径零变化)。"""
rows = _email_parent_rows(
run=_run_stub('processing', parse_status='parse_failed'),
documents=_documents(),
existing_document_ids=set(),
)
# 关键断言:解析失败优先于处理中,技术失败原因码保留
assert rows[0]['status'] == 'failed'
assert rows[0]['technical_failure_reason_code'] == 'intake_parse_failed'
@@ -11,7 +11,8 @@ tests/test_order_profile_header_identity.py
逻辑:pure_unit;别名命中产出 field::<field_code> 标记原子(atoms 为集合语义、
tokens 为序列语义且同源——去重即 atoms),未命中词沿用既有词级原子过滤;
None/空 dict 零行为变化;歧义短语整体弃用;PO_6075316 形状仅在含 Ship Date
别名的契约下跨措辞对齐,异义词不归并。
别名的契约下跨措辞对齐,异义词不归并;camelCase 无分隔符表头(UnitCost/
VendorPartNumber)与空格措辞同管线归一,不得再判身份互斥。
"""
from __future__ import annotations
@@ -296,3 +297,58 @@ def test_po6075316_tokens_canonical_sequences_identical_with_ship_date_alias():
assert canonical_expected == canonical_observed
# 关键断言:LN 别名命中产出标记项(词级过滤会丢掉 2 字母 ln,别名先行兜住)
assert canonical_expected[0] == 'field::customer_po_line_no'
# ---------------------------------------------------------------------------
# camelCase 无分隔符表头(真实故障:prod schema 别名 UnitCost/VendorPartNumber
# 经 normalize_table_header 拆成 'Unit Cost'/'Vendor Part Number' 键,而匹配器
# 词管线不拆驼峰,token 'UnitCost' 切成单词 'unitcost',短语匹配静默失效)
# ---------------------------------------------------------------------------
def _contract_mapping(**aliases: str) -> dict[str, str]:
"""按 compile_table_header_contract 真实链路构造别名键(normalize_table_header)。"""
from app.services.shipping_notice.order_schema.table_contract import (
normalize_table_header,
)
return {normalize_table_header(alias): code for alias, code in aliases.items()}
def test_camelcase_token_hits_camelcase_alias():
"""无分隔符驼峰 token 必须命中经 normalize_table_header 拆键的驼峰别名。"""
mapping = _contract_mapping(UnitCost='unit_price')
# 关键断言:契约键为 'Unit Cost'(拆驼峰),token 'UnitCost' 走同一拆分后命中
assert 'Unit Cost' in mapping
assert schema_canonical_header_atoms(['UnitCost'], mapping) == frozenset(
{'field::unit_price'},
)
def test_word_atom_pipeline_stays_case_unsplit():
"""词级原子管线有意不拆驼峰(真实表头大小写不可靠);camel 对齐由连写短语键承担。"""
# 关键断言:无别名契约时 'UnitCost' 与 'Unit Cost' 词级原子不同(零行为变化契约);
# 两者身份对齐只能在别名契约下经由连写短语键达成
assert _header_token_atoms(['UnitCost']) == frozenset({'unitcost'})
assert _header_token_atoms(['Unit Cost']) == frozenset({'unit', 'cost'})
def test_camelcase_wording_difference_not_identity_conflict():
"""模板侧连写、观测侧空格(或反向)在别名契约下不得判原子互斥冲突。"""
mapping = _contract_mapping(UnitCost='unit_price')
signature_tokens = ['Itm', 'UnitCost', 'Extended Cost']
observed_tokens = ['itm', 'Unit Cost', 'extended cost']
# 关键断言:唯一措辞差异是驼峰连写 vs 空格,且该列有别名覆盖 → 非身份冲突
assert _header_discriminator_atoms_conflict(
signature={'table_patterns': [{'header_tokens': signature_tokens}]},
observed={'header_tokens': observed_tokens},
header_to_field=mapping,
) is False
def test_camelcase_tokens_canonical_keeps_order_and_marker():
"""canonical 序列版对驼峰 token 产出单个标记项且保持词序(与 atoms 同源)。"""
canonical = schema_canonical_header_tokens(
['VendorPartNumber', 'UnitCost'],
_contract_mapping(VendorPartNumber='part_number', UnitCost='unit_price'),
)
# 关键断言:每个驼峰 token 各消费为单个 field 标记项,顺序保留、无单词残留
assert canonical == ['field::part_number', 'field::unit_price']
@@ -0,0 +1,406 @@
"""
tests/test_order_profile_ocr_rescue.py
用途:锁定表头带证据补洞(order_profile_ocr_rescue)的门禁契约。
依赖:order_profile_ocr_rescue.rescue_match_with_header_ocr / _eligible_rescue_candidates /
_glyphs_in_header_band、ProfileMatchResult/Candidate。
逻辑:pure_unit;仅「候选集合 = 冲突仅表头判别 + 观测原子纯缺失」可补救;重跑匹配器
必须恰好唯一命中集合内候选才采纳并打 identity_rescue_source 标记;改变竞争格局 /
仍失败 / 无补洞字形 / 带外字形一律原样返回原判;原 layout 禁止突变。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
from app.services.shipping_notice.document_layout.order_profile_ocr_rescue import (
OCR_RESCUE_CONFIDENCE_FLOOR,
_eligible_rescue_candidates,
_glyphs_in_header_band,
rescue_match_with_header_ocr,
)
from app.services.shipping_notice.document_layout.order_profile_matcher import (
ProfileMatchCandidate,
ProfileMatchResult,
)
pytestmark = pytest.mark.pure_unit
V2_CODE = 'ODP-TEST-V2'
OTHER_CODE = 'ODP-TEST-OTHER'
def _candidate(code: str, reasons: list[str]) -> ProfileMatchCandidate:
return ProfileMatchCandidate(
profile_code=code, version=1, score=0.0, hard_match=False,
reason_codes=reasons,
)
def _drift_match(candidates: list[ProfileMatchCandidate]) -> ProfileMatchResult:
return ProfileMatchResult(status='layout_drift', candidates=candidates)
def _layout() -> dict:
return {
'tables': [{'table_id': 't1', 'page_no': 1, 'bbox': [16, 185, 590, 266]}],
'coordinate_evidence': {
'pages': {'1': {'width': 595.0, 'height': 842.0}},
'page_glyphs': {'1': [{'text': 'I', 'bbox': {'x0': 23, 'y0': 190, 'x1': 26, 'y1': 202}}]},
'sources': {'pages': {'1': 'pdf_coordinate'}},
},
}
def _profiles() -> list[dict]:
return [
{'profile_code': V2_CODE, 'version': 1, 'definition': {}},
{'profile_code': OTHER_CODE, 'version': 1, 'definition': {}},
]
def _patch_atoms(monkeypatch, per_code: dict[str, tuple[frozenset, frozenset]]) -> None:
"""按 profile_code 固定期望/观测原子,隔离匹配器观测管线。"""
def fake(*, raw_profile, layout, header_to_field):
expected, observed = per_code[str(raw_profile['profile_code'])]
return frozenset(expected), frozenset(observed), {'primary_table_bbox': [0.027, 0.22, 0.99, 0.32]}
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.order_profile_ocr_rescue._candidate_header_atoms',
fake,
)
def _ocr_line(text: str, x0: float, y0: float, x1: float, y1: float, confidence: float = 0.95):
return SimpleNamespace(
text=text, confidence=confidence,
bbox=SimpleNamespace(x0=x0, y0=y0, x1=x1, y1=y1),
)
def _fake_page() -> SimpleNamespace:
return SimpleNamespace(page_no=1, width=595.0, height=842.0, image=object())
def test_eligibility_collects_all_subset_candidates(monkeypatch):
"""近亲模板各自缺不同尾部列时可同时可补救;竞争由补洞后的重跑裁决。"""
match = _drift_match([
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
_candidate(OTHER_CODE, ['profile_header_discriminator_conflict']),
])
_patch_atoms(monkeypatch, {
V2_CODE: ({'itm', 'qty', 'etd', 'eta'}, {'itm', 'qty'}),
OTHER_CODE: ({'itm', 'qty', 'del'}, {'itm', 'qty'}),
})
eligible = _eligible_rescue_candidates(
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
)
# 关键断言:两个纯缺失候选都进入可补救集合,由重跑匹配器唯一性仲裁
assert {(code, version) for (code, version) in eligible} == {(V2_CODE, 1), (OTHER_CODE, 1)}
def test_eligibility_rejects_foreign_atoms(monkeypatch):
"""观测侧存在期望之外的外来原子 → 不是单纯缺字,不可补救。"""
match = _drift_match([
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
])
_patch_atoms(monkeypatch, {
V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty', 'date'}),
OTHER_CODE: ({'x', 'y', 'z'}, {'x'}),
})
# 关键断言:差集必须「纯缺失」(observed ⊂ expected),有外来词的候选被排除;
# OTHER(含拓扑冲突非纯判别)同样不进集合 → 集合为空
assert _eligible_rescue_candidates(
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
) == {}
def test_rescue_success_marks_unique_same_candidate(monkeypatch):
"""补洞后重跑匹配器须恰好唯一命中集合内候选,成功时打 identity_rescue_source 标记。"""
match = _drift_match([
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
])
_patch_atoms(monkeypatch, {
V2_CODE: ({'itm', 'qty', 'etd', 'eta', 'komarom'}, {'itm', 'qty'}),
OTHER_CODE: ({'a', 'b'}, {'a'}),
})
captured = {}
def fake_match_fn(*, profiles, layout, header_to_field):
captured['layout'] = layout
winner = ProfileMatchCandidate(
profile_code=V2_CODE, version=1, score=0.99, hard_match=True, reason_codes=[],
)
loser = ProfileMatchCandidate(
profile_code=OTHER_CODE, version=1, score=0.0, hard_match=False,
reason_codes=['profile_column_topology_conflict'],
)
return ProfileMatchResult(
status='unique_match', profile_code=V2_CODE, version=1,
candidates=[winner, loser],
)
layout = _layout()
result = rescue_match_with_header_ocr(
match=match, profiles=_profiles(), layout=layout, header_to_field=None,
document=SimpleNamespace(asset_id=7),
match_fn=fake_match_fn,
page_images_fn=lambda content: [_fake_page()],
ocr_lines_fn=lambda *a, **k: [
_ocr_line('ETD', 460, 190, 480, 202),
_ocr_line('ETA Komarom', 500, 190, 560, 202),
],
read_asset_fn=lambda asset_id: b'%PDF-fake',
)
# 关键断言:结果翻转为唯一命中且带补洞来源标记,仅命中候选被打标
assert result.status == 'unique_match'
assert result.identity_rescue_source == 'ocr_coordinate'
marked = {c.profile_code: c.identity_rescue_assisted for c in result.candidates}
assert marked == {V2_CODE: True, OTHER_CODE: False}
# 关键断言:补洞字形只并入增强副本的页 1 表头带,且带来源标记
original_glyphs = _layout()['coordinate_evidence']['page_glyphs']['1']
augmented_glyphs = captured['layout']['coordinate_evidence']['page_glyphs']['1']
assert len(augmented_glyphs) > len(original_glyphs)
assert all(g.get('source') == 'ocr_coordinate' for g in augmented_glyphs[len(original_glyphs):])
assert captured['layout']['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate+ocr_coordinate'
# 关键断言:原 layout 不得被突变
assert layout['coordinate_evidence']['page_glyphs']['1'] == original_glyphs
assert layout['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate'
def test_rescue_aborts_when_rematch_changes_winner(monkeypatch):
"""补洞唤醒集合外候选(改变竞争格局)→ 维持原判。"""
match = _drift_match([
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
])
_patch_atoms(monkeypatch, {
V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}),
OTHER_CODE: ({'a', 'b'}, {'a'}),
})
def fake_match_fn(*, profiles, layout, header_to_field):
return ProfileMatchResult(
status='unique_match', profile_code=OTHER_CODE, version=1,
candidates=[_candidate(OTHER_CODE, [])],
)
result = rescue_match_with_header_ocr(
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
document=SimpleNamespace(asset_id=7),
match_fn=fake_match_fn,
page_images_fn=lambda content: [_fake_page()],
ocr_lines_fn=lambda *a, **k: [_ocr_line('ETD', 460, 190, 480, 202)],
read_asset_fn=lambda asset_id: b'%PDF-fake',
)
# 关键断言:命中者不在可补救集合内 → 原样返回原 layout_drift 判定
assert result is match
def test_rescue_aborts_when_rematch_still_drift(monkeypatch):
"""补洞词未能补齐原子(仍 layout_drift)→ 维持原判。"""
match = _drift_match([
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
])
_patch_atoms(monkeypatch, {
V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}),
OTHER_CODE: ({'a', 'b'}, {'a'}),
})
def fake_match_fn(*, profiles, layout, header_to_field):
return _drift_match([
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
])
result = rescue_match_with_header_ocr(
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
document=SimpleNamespace(asset_id=7),
match_fn=fake_match_fn,
page_images_fn=lambda content: [_fake_page()],
ocr_lines_fn=lambda *a, **k: [_ocr_line('ETD', 460, 190, 480, 202)],
read_asset_fn=lambda asset_id: b'%PDF-fake',
)
assert result is match
def test_rescue_aborts_without_ocr_lines(monkeypatch):
"""OCR 无返回(引擎失败或全部低于置信度)→ 维持原判。"""
match = _drift_match([
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
])
_patch_atoms(monkeypatch, {
V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}),
OTHER_CODE: ({'a', 'b'}, {'a'}),
})
seen = {}
def fake_ocr(*args, **kwargs):
seen['minimum_confidence'] = kwargs.get('minimum_confidence')
return []
result = rescue_match_with_header_ocr(
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
document=SimpleNamespace(asset_id=7),
match_fn=lambda **k: (_ for _ in ()).throw(AssertionError('matcher must not run')),
page_images_fn=lambda content: [_fake_page()],
ocr_lines_fn=fake_ocr,
read_asset_fn=lambda asset_id: b'%PDF-fake',
)
assert result is match
# 关键断言:OCR 置信度门禁与 ocr_pdf.OCR_CONFIDENCE_FLOOR 对齐
assert seen['minimum_confidence'] == OCR_RESCUE_CONFIDENCE_FLOOR
def test_header_band_filter_drops_out_of_band_glyphs():
"""带外补洞字形必须被过滤,只保留主表表头带内的字形并打来源标记。"""
page_width, page_height = 595.0, 842.0
glyphs = [
{'text': 'E', 'bbox': {'x0': 460, 'y0': 190, 'x1': 466, 'y1': 202}},
{'text': 'X', 'bbox': {'x0': 460, 'y0': 400, 'x1': 466, 'y1': 412}},
{'text': 'Y', 'bbox': {'x0': 2, 'y0': 190, 'x1': 8, 'y1': 202}},
]
kept = _glyphs_in_header_band(
glyphs=glyphs, page_width=page_width, page_height=page_height,
primary_table_bbox=[0.027, 0.22, 0.99, 0.32], source='ocr_coordinate',
)
# 关键断言:仅带内字形保留(y≈0.23 ∈ [0.22, 0.22+0.3*0.1];x=0.008 < 0.022 带外),
# 且带 source 标记
assert [g['text'] for g in kept] == ['E']
assert kept[0]['source'] == 'ocr_coordinate'
def test_rescue_prefers_acroform_widgets_over_ocr(monkeypatch):
"""AcroForm 控件文本是首选补洞来源(确定性);命中时不得触发渲染和 OCR。"""
match = _drift_match([
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
])
_patch_atoms(monkeypatch, {
V2_CODE: ({'itm', 'qty', 'etd', 'eta', 'komarom'}, {'itm', 'qty'}),
OTHER_CODE: ({'a', 'b'}, {'a'}),
})
def fake_widget(code: str, value: str):
return SimpleNamespace(
page_no=1, value=value,
normalized_bbox={'x0': 0.77, 'y0': 0.235, 'x1': 0.85, 'y1': 0.25},
qualified_name=code, short_name=code, widget_id=code,
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.xfa_acroform.read_acroform_widgets',
lambda content: [
fake_widget('C_ETD', 'ETD'),
fake_widget('C_ETA', 'ETA Komarom'),
],
)
result = rescue_match_with_header_ocr(
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
document=SimpleNamespace(asset_id=7),
match_fn=lambda **k: ProfileMatchResult(
status='unique_match', profile_code=V2_CODE, version=1,
candidates=[_candidate(V2_CODE, [])],
),
page_images_fn=lambda content: (_ for _ in ()).throw(AssertionError('render must not run')),
ocr_lines_fn=lambda *a, **k: (_ for _ in ()).throw(AssertionError('ocr must not run')),
read_asset_fn=lambda asset_id: b'%PDF-fake',
)
# 关键断言:AcroForm 来源直接命中,OCR/渲染路径完全未被触达
assert result.identity_rescue_source == 'acroform_widget'
assert result.status == 'unique_match'
def test_rescue_never_leaks_asset_read_errors(monkeypatch):
"""资产读取抛 AttributeError(test 环境真实故障:int 传入 read_asset_bytes 访问
.deleted_at)必须被收口为维持原判,不得炸穿抽取 Unit。"""
match = _drift_match([
_candidate(V2_CODE, ['profile_header_discriminator_conflict']),
_candidate(OTHER_CODE, ['profile_column_topology_conflict', 'profile_header_discriminator_conflict']),
])
_patch_atoms(monkeypatch, {
V2_CODE: ({'itm', 'qty', 'etd'}, {'itm', 'qty'}),
OTHER_CODE: ({'a', 'b'}, {'a'}),
})
def broken_read_asset(asset_id):
raise AttributeError("'int' object has no attribute 'deleted_at'")
result = rescue_match_with_header_ocr(
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
document=SimpleNamespace(asset_id=7),
match_fn=lambda **k: (_ for _ in ()).throw(AssertionError('matcher must not run')),
page_images_fn=lambda content: (_ for _ in ()).throw(AssertionError('render must not run')),
ocr_lines_fn=lambda *a, **k: (_ for _ in ()).throw(AssertionError('ocr must not run')),
read_asset_fn=broken_read_asset,
)
# 关键断言:补洞证据读取的任意异常都收口为原判返回
assert result is match
def test_rescue_skipped_for_non_failed_status():
"""常规匹配已成功(如 unique_match)时绝不触发证据补洞。"""
match = ProfileMatchResult(
status='unique_match', profile_code=V2_CODE, version=1,
candidates=[_candidate(V2_CODE, [])],
)
result = rescue_match_with_header_ocr(
match=match, profiles=_profiles(), layout=_layout(), header_to_field=None,
document=SimpleNamespace(asset_id=7),
match_fn=lambda **k: (_ for _ in ()).throw(AssertionError('matcher must not run')),
page_images_fn=lambda content: (_ for _ in ()).throw(AssertionError('render must not run')),
ocr_lines_fn=lambda *a, **k: (_ for _ in ()).throw(AssertionError('ocr must not run')),
read_asset_fn=lambda asset_id: (_ for _ in ()).throw(AssertionError('asset must not run')),
)
assert result is match
def test_default_read_asset_loads_orm_before_read_asset_bytes(monkeypatch):
"""默认资产读取必须先加载 FileAsset ORM 再交给 read_asset_bytes。
回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——默认接线曾把
document.asset_id(int)直接传给 read_asset_bytes,第一行访问
``asset.deleted_at`` 即抛 AttributeError,炸穿补救层令整个抽取 Unit
技术失败。本测试锁定默认接线契约:read_asset_bytes 只接收 ORM 对象。
"""
from types import SimpleNamespace as NS
import app.extensions as extensions
import app.services.file_assets.service as asset_service
from app.services.shipping_notice.document_layout.order_profile_ocr_rescue import (
_default_read_asset_bytes,
)
received_objects: list[object] = []
def fake_read_asset_bytes(asset):
received_objects.append(asset)
return b'%PDF-default-wired'
fake_asset = NS(id=7, deleted_at=None)
class FakeSession:
def get(self, model, asset_id):
assert model is not int and asset_id == 7
return fake_asset
monkeypatch.setattr(asset_service, 'read_asset_bytes', fake_read_asset_bytes)
monkeypatch.setattr(extensions, 'db', NS(session=FakeSession()))
# 关键断言 1:默认接线按 id 取 ORM,read_asset_bytes 收到对象而非 int。
assert _default_read_asset_bytes(7) == b'%PDF-default-wired'
assert received_objects == [fake_asset]
# 关键断言 2:资产不存在时抛 LookupError(可被补救层收口为原判)。
class MissingSession:
def get(self, model, asset_id):
return None
monkeypatch.setattr(extensions, 'db', NS(session=MissingSession()))
with pytest.raises(LookupError):
_default_read_asset_bytes(404)
@@ -14,7 +14,10 @@ from app.models import (
ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingOrderTask,
)
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
from app.services.shipping_notice.inventory_routing_engine import (
evaluate_inventory_source_rules,
evaluate_inventory_source_rules_for_field_values,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
@@ -212,3 +215,111 @@ def test_five_digit_reservation_rule_can_route_to_crane(app):
result = evaluate_inventory_source_rules(task=task, line=line)
assert result.status == 'resolved'
assert result.source_codes == ('CRANE',)
# ---------- 库存源线索直连(引擎内建,优先于全部规则层) ----------
def _hint_sources(monkeypatch, codes):
"""隔离线索解析的启用源清单(引擎自 list_database_inventory_sources 读取)。"""
monkeypatch.setattr(
'app.services.shipping_notice.inventory_routing_engine.list_database_inventory_sources',
lambda enabled_only=True: [{'source_code': code} for code in codes],
)
def _set_snapshot_line_hint(task, hint: str) -> None:
"""在冻结快照行的强类型线索列写入线索值(模拟订单明细「库存源线索」)。"""
snapshot_line = ShippingOrderSnapshotLine.query.filter_by(
snapshot_id=task.order_snapshot_id, position=0,
).one()
snapshot_line.inventory_source_hint = hint
db.session.commit()
def test_hint_direct_connect_suffix_wins_over_reservation_fallback(app, monkeypatch):
"""[断言] 核心需求:线索非空且可唯一后缀解析时直接 resolved,预约单号兜底规则不得参与。"""
_hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01', 'DSV360_AWSCV'])
fields = _published_line_fields()
task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')})
db.session.add(_rule(
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
conditions=[(fields['reservation_id'], 'prefix', '1')],
))
_set_snapshot_line_hint(task, 'BYAWSPRD01')
db.session.commit()
result = evaluate_inventory_source_rules(task=task, line=line)
assert result.status == 'resolved'
assert result.source_codes == ('DSV360_AWSBI_BYAWSPRD01',)
assert result.evidence.get('reason') == 'inventory_source_hint'
assert result.matched_rule_ids == ()
def test_hint_direct_connect_exact_code_match(app, monkeypatch):
"""[断言] 线索即完整源编码时精确命中。"""
_hint_sources(monkeypatch, ['DSV360_AWSCV', 'DSV360_AWSDU'])
fields = _published_line_fields()
task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')})
_set_snapshot_line_hint(task, 'DSV360_AWSCV')
db.session.commit()
result = evaluate_inventory_source_rules(task=task, line=line)
assert result.status == 'resolved'
assert result.source_codes == ('DSV360_AWSCV',)
def test_hint_unresolvable_falls_back_to_reservation_rule(app, monkeypatch):
"""[断言] fail-open:线索无命中(拼错/停用)时落回规则层,预约兜底照常,不阻断流程。"""
_hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01'])
fields = _published_line_fields()
task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')})
db.session.add(_rule(
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'],
conditions=[(fields['reservation_id'], 'prefix', '1')],
))
_set_snapshot_line_hint(task, 'NOPE_WAREHOUSE')
db.session.commit()
result = evaluate_inventory_source_rules(task=task, line=line)
assert result.status == 'ambiguous'
assert result.source_codes == ('DBS_DUB', 'DBS_RTM')
def test_hint_ambiguous_suffix_falls_back_to_rules(app, monkeypatch):
"""[断言] 后缀撞多个启用源(多命中)时不采用线索,落回规则层裁决。"""
_hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01', 'DSV360_CRANE_BYAWSPRD01'])
fields = _published_line_fields()
task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')})
db.session.add(_rule(
code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB'],
conditions=[(fields['reservation_id'], 'prefix', '1')],
))
_set_snapshot_line_hint(task, 'BYAWSPRD01')
db.session.commit()
result = evaluate_inventory_source_rules(task=task, line=line)
assert result.status == 'resolved'
assert result.source_codes == ('DBS_DUB',)
def test_hint_direct_connect_ignored_for_task_scope(app, monkeypatch):
"""[断言] 线索是行级信号:任务级评估(line=None)维持原行为。"""
_hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01'])
fields = _published_line_fields()
task, _line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')})
_set_snapshot_line_hint(task, 'BYAWSPRD01')
db.session.commit()
result = evaluate_inventory_source_rules(task=task, line=None)
assert result.status == 'unresolved'
def test_draft_entry_hint_direct_connect_and_fallback(app, monkeypatch):
"""[断言] Draft 入口:线索命中直接 resolved(无规则也生效);未传线索时维持 unresolved。"""
_hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01'])
result = evaluate_inventory_source_rules_for_field_values(
header_field_values={}, line_field_values={}, scope='line',
line_source_hint='BYAWSPRD01',
)
assert result.status == 'resolved'
assert result.source_codes == ('DSV360_AWSBI_BYAWSPRD01',)
assert result.evidence.get('reason') == 'inventory_source_hint'
fallback = evaluate_inventory_source_rules_for_field_values(
header_field_values={}, line_field_values={}, scope='line',
)
assert fallback.status == 'unresolved'
@@ -31,6 +31,12 @@ def test_inventory_preparation_line_scope_passes_source_codes(monkeypatch):
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
lambda _execution: task,
)
# [回归] 执行器 [STEP 0B] 新增 latest_export_artifact(Excel 源锁定判断,查库)依赖;
# 纯单测无 Flask/DB,打桩为「Excel 已生成」使刷新块短路,保持本用例聚焦行级收窄断言。
monkeypatch.setattr(
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
lambda _task: SimpleNamespace(id=77),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: candidate_set,
@@ -0,0 +1,41 @@
"""
backend/tests/test_shipping_notice_export_archive.py
用途:shipping_notice 批量导出归档(build_export_archive)下载授权单测。
依赖:pytest、ShippingNotice、export_archive.build_export_archive。
逻辑:批量选择与单票导出消费同一谓词口径(创建者或管理员);无 Artifact 时
保留 manifest missing 语义,并按票携带 business_no 供端点写访问审计。
"""
import pytest
from app.core.errors import NotFoundError
from app.models import ShippingNotice
def test_build_export_archive_selects_by_creator_or_admin(app):
"""批量归档与单票下载同一谓词:陌生用户整体拒绝,创建者/管理员放行。"""
with app.app_context():
from app import db
from app.services.shipping_notice.export_archive import build_export_archive
owned = ShippingNotice(
task_no="SN-ARC-OWNED", business_no="QMN-ARC-1", user_id=7, source_type="manual",
)
db.session.add(owned)
db.session.commit()
# 非创建者普通用户:任一越权即整体拒绝(防部分成功)。
with pytest.raises(NotFoundError):
build_export_archive(user_id=8, business_nos=["QMN-ARC-1"])
# 创建者放行;无 Artifact 时保留 missing_artifact 语义并携带 business_no。
_stream, _name, manifest = build_export_archive(user_id=7, business_nos=["QMN-ARC-1"])
assert manifest["entries"][0]["status"] == "missing_artifact"
assert manifest["entries"][0]["business_no"] == "QMN-ARC-1"
# 管理员可下载=可见:他人正式 Notice 放行(端点按票补访问审计)。
_stream, _name, admin_manifest = build_export_archive(
user_id=8, business_nos=["QMN-ARC-1"], is_admin=True,
)
assert admin_manifest["entries"][0]["task_no"] == "SN-ARC-OWNED"
@@ -1697,3 +1697,70 @@ def test_merge_chat_log_payload_requires_exact_turn_ownership(app):
'existing_key': 'kept',
'shipping_order_extraction_state': {'status': 'completed'},
}
def test_persist_close_out_marks_failed_units_failed_not_completed(app):
"""Unit 全失败的空结果收口必须写 failed,禁止把附件误标为识别完成。
回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——persist 在 orders=[]
时按「零 pending」把附件 order_extraction_status 写成 completed;随后的
Run 失败收口因「已是 completed 终态」跳过回填,批次进度中心据此把整批
误报为已完成/通知完成。
"""
with app.app_context():
user, session, intake, document, _runtime_context = _seed_extraction_input()
schema = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
agent = Agent.query.filter_by(agent_code='shipping_notice').one()
run = ShippingOrderProcessingRun(
run_no='SNER-FAILED-UNITS-CLOSE-OUT',
user_id=int(user.id),
owner_agent_id=int(agent.id),
conversation_id=session.session_id,
schema_version_id=int(schema.id),
input_snapshot_hash='failed-units-close-out-snapshot',
input_snapshot_json={},
idempotency_key='failed-units-close-out-run',
status='processing',
)
plan = ShippingOrderProcessingPlan(
run=run,
plan_version='test.v1',
input_snapshot_hash=run.input_snapshot_hash,
unit_count=1,
)
unit = ShippingOrderProcessingUnit(
plan=plan,
intake_id=int(intake.id),
document_id=int(document.id),
position=0,
unit_type='document_extraction',
document_type='attachment',
status='failed',
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED',
error_message="'int' object has no attribute 'deleted_at'",
)
db.session.add_all([run, plan, unit])
db.session.commit()
persist_order_extraction_result(
session=session,
intakes=[intake],
documents=[document],
current_snapshot='failed-units-close-out-snapshot',
request_id='SNER-FAILED-UNITS-CLOSE-OUT',
orders=[],
run_id=int(run.id),
schema_version_id=int(schema.id),
extraction_source='deterministic_order_parser',
auto_create_enabled=False,
)
db.session.commit()
db.session.refresh(document)
db.session.refresh(intake)
# 关键断言 1:Unit 失败且零候选裁决 → 文档必须落 failed 并携带 Unit 错误码。
assert document.order_extraction_status == 'failed'
assert document.order_extraction_error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'
# 关键断言 2:全部附件失败 → Intake 同步 failed;consumed 保留(孤儿重解析依赖)。
assert intake.order_extraction_status == 'failed'
assert intake.parse_status == 'consumed'
@@ -321,6 +321,28 @@ def test_get_task_for_user_rejects_null_owner(app):
assert get_task_visible_to_user("OT-OWNED", 8, is_admin=True) is not None
def test_can_download_task_export_creator_or_admin(app):
"""导出统一谓词:创建者/管理员可下载;非创建者普通用户与无主单一律拒绝。"""
with app.app_context():
from app import db
from app.services.shipping_notice.query_service import can_download_task_export
owned = ShippingNotice(task_no="SN-DL-OWNED", business_no="QMN-DL-1", user_id=7, source_type="manual")
orphan = ShippingNotice(task_no="SN-DL-ORPHAN", business_no="QMN-DL-2", user_id=None, source_type="manual")
db.session.add_all([owned, orphan])
db.session.commit()
# 创建者可下载;同票对非创建者普通用户拒绝。
assert can_download_task_export(owned, user_id=7) is True
assert can_download_task_export(owned, user_id=8) is False
# 管理员可下载=可见:他人票与无主票均放行(下载留痕审计兜底)。
assert can_download_task_export(owned, user_id=8, is_admin=True) is True
assert can_download_task_export(orphan, user_id=7) is False
assert can_download_task_export(orphan, user_id=7, is_admin=True) is True
# 缺实体一律拒绝。
assert can_download_task_export(None, user_id=7, is_admin=True) is False
def test_serialize_task_summary_enriches_todo_and_can_handle(app):
"""SUMMARY enrich 含 todo_category / created_by / can_handle / ui_state。"""
with app.app_context():
@@ -465,6 +465,39 @@ def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypa
assert "download_excel" in button_ids
def test_task_ui_state_gates_download_by_viewer(app, monkeypatch) -> None:
"""下载动作与导出端点同一谓词:创建者/管理员下发,非创建者不下发;viewer 缺省维持聊天旧口径。"""
with app.app_context():
from app import db
task = ShippingNotice(
task_no="SN-UI-VIEWER-EXPORT",
source_type="manual",
user_id=7,
)
db.session.add(task)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.ui_state.resolve_task_export_download',
lambda _task: (object(), 'shipping-export.xlsx'),
)
def button_ids(state):
return [
item.get("code")
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
if item
]
# 创建者与管理员可见下载动作(管理员可下载=可见,消除"看得到点不动")。
assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=7))
assert "download_excel" in button_ids(build_task_ui_state(task, viewer_user_id=8, viewer_is_admin=True))
# 非创建者普通用户不得收到下载动作(端点仍会拒绝,UI 不再误导)。
assert "download_excel" not in button_ids(build_task_ui_state(task, viewer_user_id=8))
# viewer 缺省 = 聊天链路(会话与创建者同源),维持仅 Artifact 授权的旧口径。
assert "download_excel" in button_ids(build_task_ui_state(task))
def test_task_ui_state_keeps_resolved_download_alongside_process_gate(app, monkeypatch) -> None:
"""当前 Gate 的恢复动作不能吞掉已就绪 Excel 的只读下载授权。"""
with app.app_context():
@@ -1651,6 +1651,12 @@ def test_inventory_preparation_mode_maps_by_action_code(monkeypatch):
'app.services.shipping_notice.process_gate_executor._resolve_order_task',
lambda _execution: task,
)
# [回归] 执行器 [STEP 0B] 新增 latest_export_artifact + 候选源刷新前置(查库)依赖;
# 本用例聚焦动作码→mode 映射,打桩为「Excel 已生成」使刷新块短路,隔离刷新链副作用。
monkeypatch.setattr(
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
lambda _task: SimpleNamespace(id=77),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: candidate_set,
@@ -1504,15 +1504,20 @@ def test_summary_includes_the_same_file_status_counts_used_by_batch_overview(app
def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> None:
"""混合状态邮件必须按 PDF 进入各自分组,摘要计数不得沿用 EML 父级状态。"""
"""混合状态邮件必须按 PDF 进入各自分组,摘要计数不得沿用 EML 父级状态。
回归语义(SNER-20261014-8EBAB7A1):无 OT 的文档级 completed 只是抽取收口,
摘要不再译成业务已完成;混合场景改用 failed + processing 两类真实用户分组。
"""
with app.app_context():
from tests.test_shipping_order_extraction_runs import _seed_run_input
user, _agent, session, intake, completed_document = _seed_run_input(
user, _agent, session, intake, failed_document = _seed_run_input(
suffix='SUMMARY-MIXED-EML-LEAF-STATUS',
)
intake.source_type = 'eml'
completed_document.order_extraction_status = 'completed'
failed_document.order_extraction_status = 'failed'
failed_document.order_extraction_error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'
processing_document = ShippingOrderDocument(
intake_id=intake.id,
document_type='attachment',
@@ -1531,17 +1536,17 @@ def test_summary_splits_mixed_eml_leaves_and_counts_each_file_status(app) -> Non
conversation_id=session.session_id,
)['conversation_processing']
# 关键断言:同一 EML 的两个附件以各自状态展示,处理中不能留在已完成容器。
# 关键断言:同一 EML 的两个附件以各自状态展示,处理中不能留在失败容器。
failed_rows = projection['status_groups']['failed']
processing_rows = projection['status_groups']['processing']
completed_rows = projection['status_groups']['completed']
assert [child['source_summary']['document_id'] for child in processing_rows[0]['aggregate_children']] == [
processing_document.id,
]
assert [child['source_summary']['document_id'] for child in completed_rows[0]['aggregate_children']] == [
completed_document.id,
assert [child['source_summary']['document_id'] for child in failed_rows[0]['aggregate_children']] == [
failed_document.id,
]
assert projection['summary']['processing_files'] == 1
assert projection['summary']['completed_files'] == 1
assert projection['summary']['failed_files'] == 1
assert projection['summary']['total_files'] == 2
@@ -3423,3 +3428,58 @@ def test_unrecognized_plan_attachment_is_displayed_but_not_counted_as_recognized
assert ((unrecognized[0].get('source_summary') or {}).get('filename')) == 'F92.pdf'
# 已识别计数只认物化附件;未识别行不计入,从而「已识别 1/2」语义成立。
assert _batch_file_counts(merged)['total_files'] == 1
def test_summary_failed_run_does_not_project_document_completed_as_upload_complete(app) -> None:
"""Run 失败时文档级 completed(抽取收口语义)不得译成业务终态「通知完成」。
回归:test 环境 SNER-20261014-8EBAB7A1(2026-10-14)——9 个 Unit 全部
ORDER_EXTRACTION_UNIT_FAILED,persist 收口零 pending 仍把附件写成
order_extraction_status='completed';首屏摘要 _status() 据此映射
('completed','completed'),批次进度中心误报 9/9 已完成 + 通知完成。
"""
with app.app_context():
from datetime import datetime
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
user, agent, session, intake, document = _seed_run_input(
suffix='SUMMARY-CLOSEOUT-NOT-COMPLETE',
)
intake.source_type = 'eml'
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
for unit in run.extraction_plan.units:
unit.status = 'failed'
unit.error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'
run.status = 'failed'
run.phase = 'failed'
run.error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED'
# 脏数据形态:persist 收口已把文档/Intake 写成 completed(抽取收口 ≠ 业务完成)。
document.order_extraction_status = 'completed'
intake.parse_status = 'consumed'
intake.consumed_at = datetime.utcnow()
intake.order_extraction_status = 'completed'
db.session.commit()
payload = project_conversation_processing_summary(
user_id=user.id,
conversation_id=session.session_id,
)
projection = payload['conversation_processing']
leaf = next(
child
for rows in projection['status_groups'].values()
for row in rows
for child in row.get('aggregate_children', [])
if child['source_summary']['document_id'] == document.id
)
# 关键断言 1:无 OT/Notice 的文件不可能投影为「通知完成」。
assert leaf['ui_state']['lifecycle_stage'] != 'upload_complete'
# 关键断言 2:失败文件不得计入批次已完成统计。
assert projection['summary']['completed'] == 0
# 关键断言 3:与全量视图同判词 —— 失败停接收解析,主动作是重解析。
assert leaf['user_group'] == 'failed'
assert leaf['ui_state']['lifecycle_stage'] == 'intake_parse'
assert leaf['ui_state']['primary_action']['code'] == 'reparse'
@@ -0,0 +1,504 @@
"""
tests/test_shipping_refresh_inventory_candidates.py
用途:人工重取前的候选集刷新守卫与幂等语义——任务级整单重路由、行级单行重评,
未定源才刷新;人工钉源/已定源/无变化场景一律跳过或零副作用。
依赖:inventory_candidate_freeze_service(被测 helper)、inventory_source_gate 与
inventory_source_rules(重裁决/重评入口,测试中 monkeypatch 隔离)、
process_gate_executor(Task 2 的挂载点集成测试)。
逻辑:任务级守卫(多候选、非人工钉源)+ 幂等判定(活动 set_id 变化);行级守卫
(目标行多候选、非人工钉源)+ 行级规则重评 + 定向行替换冻结;执行器仅在
人工 retry(任务级/行级)且非 Excel 锁定时调用对应 helper。
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
def _task(set_id=10):
"""构造最小 OT 形状:仅 helper/执行器读取的字段。"""
return SimpleNamespace(
id=19, task_no='SN-REFRESH',
order_snapshot_id=3,
active_inventory_candidate_set_id=set_id,
step_payload_json={},
)
def _active_set(line_defs):
"""构造最小活动候选集:lines 为 (line_no, codes) 列表。"""
return SimpleNamespace(
id=10, frozen_by_id=None, sources=[],
lines=[
SimpleNamespace(
line_no=line_no, source_codes_json=list(codes),
source_line_no=str(line_no), part_number=f'PN{line_no}', reservation_id=f'R{line_no}',
)
for line_no, codes in line_defs
],
)
def _patch_routing_common(monkeypatch, *, fingerprint='fp-test', config_version='cfg-test'):
"""隔离路由上下文与配置版本(避免测试依赖真实库表与指纹算法)。"""
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.extract_routing_context',
lambda _task: {'customer': 'X'},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.compute_routing_fingerprint',
lambda _ctx: fingerprint,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.inventory_sources_runtime_version',
lambda: config_version,
)
# ---------- 任务级刷新 ----------
def test_refresh_skips_when_single_source_resolved(app, monkeypatch):
"""[断言] 守卫:源已定(冻结候选 ≤1)不重路由——换源只能走行级覆写,禁止自动改源。"""
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
task = _task()
monkeypatch.setattr(
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
lambda _task: ['DSV360_AWSDU'],
)
called = []
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
lambda _task, **_k: called.append(1),
)
assert freeze_service.refresh_candidates_from_current_routing(task) is False
assert not called
def test_refresh_skips_when_manual_selection_exists(app, monkeypatch):
"""[断言] 守卫:人工选源即定论,重取不得洗掉人工裁决。"""
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
task = _task()
monkeypatch.setattr(
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
)
monkeypatch.setattr(
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True,
)
called = []
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
lambda _task, **_k: called.append(1),
)
assert freeze_service.refresh_candidates_from_current_routing(task) is False
assert not called
def test_refresh_returns_true_and_logs_event_when_set_changes(app, monkeypatch):
"""[断言] 重裁决产生新版本:返回 True 并写 inventory_candidates_refreshed 任务事件(scope=task)。"""
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
task = _task(set_id=10)
monkeypatch.setattr(
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
)
monkeypatch.setattr(
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id),
)
def _fake_readjudicate(_task, **_k):
task.active_inventory_candidate_set_id = 11
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
_fake_readjudicate,
)
events = []
monkeypatch.setattr(
'app.services.shipping_notice.tool_common.log_task_event',
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
)
assert freeze_service.refresh_candidates_from_current_routing(task, execution_id=5) is True
assert events and events[0][0] == 'inventory_candidates_refreshed'
assert events[0][1]['scope'] == 'task'
assert events[0][1]['previous_set_id'] == 10
assert events[0][1]['new_set_id'] == 11
def test_refresh_is_noop_when_routing_result_identical(app, monkeypatch):
"""[断言] 幂等:重裁决输入指纹未变(复用旧集,set_id 不变)时返回 False,不写事件。"""
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
task = _task(set_id=10)
monkeypatch.setattr(
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
lambda _task: ['DSV360_AWSDU', 'DSV360_AWSSG'],
)
monkeypatch.setattr(
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: SimpleNamespace(id=task.active_inventory_candidate_set_id),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_gate.adjudicate_and_apply_inventory_source',
lambda _task, **_k: None,
)
events = []
monkeypatch.setattr(
'app.services.shipping_notice.tool_common.log_task_event',
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
)
assert freeze_service.refresh_candidates_from_current_routing(task) is False
assert not events
# ---------- 行级刷新 ----------
def test_line_refresh_skips_when_target_line_single_source(app, monkeypatch):
"""[断言] 守卫:目标行候选 ≤1(已定源)不重评——改源走行级覆写。"""
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
task = _task()
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: _active_set([(1, ['DSV360_AWSDU'])]),
)
called = []
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
lambda **_k: called.append(1),
)
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
assert not called
def test_line_refresh_skips_when_manual_selection_exists(app, monkeypatch):
"""[断言] 守卫:候选集含人工选源即定论,行级重取不得洗掉人工裁决。"""
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
task = _task()
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
)
monkeypatch.setattr(
freeze_service, 'active_candidate_set_is_manually_pinned', lambda *_a, **_k: True,
)
called = []
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
lambda **_k: called.append(1),
)
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
assert not called
def test_line_refresh_skips_when_routing_unresolved(app, monkeypatch):
"""[断言] 行级规则重评为 unresolved(或候选全部停用)时保持旧行为,不冻结不刷新。"""
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
task = _task()
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
lambda _task, **_k: [{'part_number': 'PN1'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
lambda **_k: SimpleNamespace(status='unresolved', source_codes=()),
)
freeze_called = []
monkeypatch.setattr(
freeze_service, 'freeze_candidates_for_task',
lambda *_a, **_k: freeze_called.append(1),
)
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
assert not freeze_called
def test_line_refresh_skips_when_routed_sources_all_disabled(app, monkeypatch):
"""[断言] 规则原始候选未过滤启停(InventoryRoutingResult 契约):候选全部停用时不得入集,保持旧行为。"""
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
task = _task()
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
lambda _task, **_k: [{'part_number': 'PN1'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
lambda **_k: SimpleNamespace(status='resolved', source_codes=('DSV360_AWSDU',)),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
lambda code, **_k: None,
)
freeze_called = []
monkeypatch.setattr(
freeze_service, 'freeze_candidates_for_task',
lambda *_a, **_k: freeze_called.append(1),
)
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
assert not freeze_called
def test_line_refresh_freezes_new_version_when_routing_changes(app, monkeypatch):
"""[断言] 行级重评产生新候选:目标行替换、其余行继承,新版本冻结返回 True 并写行级刷新事件。"""
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
task = _task()
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: _active_set([
(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01']),
(2, ['DSV360_AWSCV']),
]),
)
_patch_routing_common(monkeypatch)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
lambda _task, **_k: [{'part_number': 'PN1'}, {'part_number': 'PN2'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSDU', 'DSV360_AWSCV')),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
lambda code, **_k: {'source_code': code},
)
freeze_kwargs = []
monkeypatch.setattr(
freeze_service, 'freeze_candidates_for_task',
lambda _task, **_k: freeze_kwargs.append(dict(_k)) or SimpleNamespace(created_new=True, candidate_set_id=12),
)
events = []
monkeypatch.setattr(
'app.services.shipping_notice.tool_common.log_task_event',
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
)
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1, execution_id=5) is True
projections = freeze_kwargs[0]['line_projections']
assert projections[0]['line_no'] == 1
assert projections[0]['candidate_inventory_source_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV']
assert projections[1]['line_no'] == 2
assert projections[1]['candidate_inventory_source_codes'] == ['DSV360_AWSCV']
assert events and events[0][0] == 'inventory_candidates_refreshed'
assert events[0][1]['scope'] == 'line'
assert events[0][1]['line_no'] == 1
assert events[0][1]['new_codes'] == ['DSV360_AWSDU', 'DSV360_AWSCV']
def test_line_refresh_is_noop_when_fingerprint_identical(app, monkeypatch):
"""[断言] 幂等:行级重评结论与现状一致(冻结复用旧集 created_new=False)时返回 False,不写事件。"""
from app.services.shipping_notice import inventory_candidate_freeze_service as freeze_service
task = _task()
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: _active_set([(1, ['DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01'])]),
)
_patch_routing_common(monkeypatch)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules._task_routing_lines',
lambda _task, **_k: [{'part_number': 'PN1'}],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_rules.evaluate_inventory_source_rules',
lambda **_k: SimpleNamespace(status='ambiguous', source_codes=('DSV360_AWSCV', 'DSV360_AWSBI_BYAWSCMH01')),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
lambda code, **_k: {'source_code': code},
)
monkeypatch.setattr(
freeze_service, 'freeze_candidates_for_task',
lambda _task, **_k: SimpleNamespace(created_new=False, candidate_set_id=10),
)
events = []
monkeypatch.setattr(
'app.services.shipping_notice.tool_common.log_task_event',
lambda _task, event_type, payload, **_k: events.append((event_type, payload)),
)
assert freeze_service.refresh_line_candidates_from_current_routing(task, line_no=1) is False
assert not events
def _retry_payload(**overrides):
base = {'action_code': 'retry_inventory_preparation', 'actor_user_id': 7}
base.update(overrides)
return base
def _exercise_retry_handler(
monkeypatch, task, payload, *,
refresh_calls, line_scope=None, excel_artifact=None, ensure_calls=None, line_refresh_result=False,
):
"""按既有 override 测试模式直调重取处理器:隔离重路由、失效、准备轮次与 ensure_inventory。
refresh_calls 记录 ('task'|'line', kwargs),用于断言挂载路径与透传参数。
line_scope 传 dict 时每次解析都返回它(缺省行为);传 list 时按调用次序逐个弹出
(用尽后返回 None),用于断言「刷新产生新集后重解析行作用域」。
line_refresh_result 控制行级刷新 helper mock 的返回值(True 表示产生了新候选集)。
ensure_calls 顺序捕获 ensure_inventory 收到的 payload(供断言取数范围)。
另须打桩 inventory_candidate_projection 三个读取函数:执行器 [STEP 0A] 会真实查库校验
活动 CandidateSet,假 Task 不打桩会被提前拦回 inventory_source_routing_required,
永远到不了被测的 [STEP 0B] 刷新块(与 test_shipping_line_scoped_inventory_retry 同模式)。
"""
from app.services.shipping_notice import process_gate_executor as executor
execution = SimpleNamespace(id=5, task_id=int(task.id), candidate_set_id=None)
gate = SimpleNamespace(id=11, gate_code='inventory_preparation', blocking_reason_code='inventory_rpa_timeout')
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: task)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_set',
lambda _task: SimpleNamespace(id=1),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_lines',
lambda _task: [SimpleNamespace(source_codes_json=['DSV360_AWSDU'])],
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_projection.get_active_candidate_sources',
lambda _task: [SimpleNamespace(source_code='DSV360_AWSDU')],
)
if isinstance(line_scope, list):
scope_sequence = list(line_scope)
monkeypatch.setattr(
executor,
'_resolve_line_inventory_scope',
lambda _task, **_k: scope_sequence.pop(0) if scope_sequence else None,
)
else:
monkeypatch.setattr(executor, '_resolve_line_inventory_scope', lambda _task, **_k: line_scope)
monkeypatch.setattr(executor, '_task_payload', lambda _execution, _payload: {'task_id': task.task_no})
monkeypatch.setattr(
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
lambda _task: excel_artifact,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_candidates_from_current_routing',
lambda _task, **_k: refresh_calls.append(('task', dict(_k))) or False,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_candidate_freeze_service.refresh_line_candidates_from_current_routing',
lambda _task, **_k: refresh_calls.append(('line', dict(_k))) or line_refresh_result,
)
monkeypatch.setattr(
'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream',
lambda **_k: {'outcome': 'passed'},
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
lambda **_k: None,
)
if ensure_calls is None:
ensure_calls = []
monkeypatch.setattr(
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
lambda _payload: ensure_calls.append(dict(_payload)) or {'status': 'ok', 'data': {}},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **_k: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
lambda _task: 'inventory_preparation_failed',
)
return executor._handle_retry_inventory_preparation(
execution=execution, gate=gate, payload=payload,
)
def test_retry_refreshes_task_candidates_for_task_level_retry(app, monkeypatch):
"""[断言] 任务级人工重取触发整单刷新前置(透传 execution_id);随后仍走既有失效与重取链。"""
refresh_calls = []
outcome = _exercise_retry_handler(
monkeypatch, _task(), _retry_payload(), refresh_calls=refresh_calls,
)
assert refresh_calls and refresh_calls[0][0] == 'task'
assert refresh_calls[0][1].get('execution_id') == 5
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
def test_retry_refreshes_line_candidates_for_line_scope_retry(app, monkeypatch):
"""[断言] 行级重抓触发目标行刷新前置(透传 line_no 与 execution_id),不做整单重路由。"""
refresh_calls = []
outcome = _exercise_retry_handler(
monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1},
)
assert refresh_calls and refresh_calls[0][0] == 'line'
assert refresh_calls[0][1].get('line_no') == 1
assert refresh_calls[0][1].get('execution_id') == 5
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
def test_retry_skips_refresh_for_poll_and_excel_lock(app, monkeypatch):
"""[断言] 轮询路径与 Excel 已生成(源锁定,任务级+行级)均不刷新候选集。"""
refresh_calls = []
task = _task()
_exercise_retry_handler(
monkeypatch, task, _retry_payload(action_code='poll_inventory_preparation'),
refresh_calls=refresh_calls,
)
_exercise_retry_handler(
monkeypatch, task, _retry_payload(), refresh_calls=refresh_calls,
excel_artifact=SimpleNamespace(id=77),
)
_exercise_retry_handler(
monkeypatch, task, _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
line_scope={'source_codes': ['DSV360_AWSDU'], 'snapshot_line_id': 3, 'line_no': 1},
excel_artifact=SimpleNamespace(id=77),
)
assert not refresh_calls
def test_retry_line_refresh_requeries_with_new_scope(app, monkeypatch):
"""[断言] 行级刷新产生新候选集后须按同参重解析行作用域:同一次点击的失效与 RPA 取数
直接使用新冻结码,而非刷新前解析的旧码;重解析为 None 时才保守沿用旧值。"""
refresh_calls = []
ensure_calls = []
outcome = _exercise_retry_handler(
monkeypatch, _task(), _retry_payload(line_scope_key=3), refresh_calls=refresh_calls,
line_scope=[
{'source_codes': ['DSV360_AWSCV'], 'snapshot_line_id': 3, 'line_no': 1},
{'source_codes': ['DSV360_AWSDU', 'DSV360_AWSCV'], 'snapshot_line_id': 3, 'line_no': 1},
],
line_refresh_result=True,
ensure_calls=ensure_calls,
)
assert refresh_calls and refresh_calls[0][0] == 'line'
assert refresh_calls[0][1].get('line_no') == 1
assert ensure_calls and ensure_calls[-1].get('source_codes') == ['DSV360_AWSDU', 'DSV360_AWSCV']
assert outcome.get('outcome') in {'passed', 'blocked_retryable', 'running', 'needs_human', 'waiting_external'}
def test_retry_from_preparation_does_not_refresh(app, monkeypatch):
"""[断言] retry_inventory_from_preparation 不做候选集刷新前置(仅 retry_inventory_preparation 触发,锁定文档排除项)。"""
refresh_calls = []
_exercise_retry_handler(
monkeypatch, _task(), _retry_payload(action_code='retry_inventory_from_preparation'),
refresh_calls=refresh_calls,
)
assert not refresh_calls
@@ -0,0 +1,322 @@
"""验证 EML 无表头正文「裸 5/10 位数字兜底识别预约单号」的扫描、排除与合并裁决。
依赖:reservation_id 启发式原语与 order_supplement_merge 合并服务。
逻辑:无表头数据行解析不出补充行时,正文裸数字候选在合并末段结合
已提取字段值/主题标签值/跨单占用裁决——唯一候选低置信度写入,
多候选转 supplement_field_conflict 人工裁决,已有值绝不覆盖。
"""
from __future__ import annotations
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
from app.services.shipping_notice.reservation_id import (
filter_reservation_heuristic_candidates,
find_bare_numeric_reservation_candidates,
reservation_ids_in_labeled_context,
)
SCHEMA = {'fields': [
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'aliases': ['PO#', 'PO Number']},
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'aliases': ['MPN', 'Part Number']},
{'field_id': 'qty', 'field_code': 'qty'},
{
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
'aliases': ['Reservation ID', 'External reservation ID'],
},
]}
HEADER_RESERVATION_SCHEMA = {'fields': [
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header'},
{
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'header',
'aliases': ['Reservation ID'],
},
]}
def _order() -> dict:
"""构造 PDF 已解析出 PO/料号/数量、但缺预约单号的订单(截图 1 场景)。"""
return {
'_hxops_intake_id': 1,
'header_fields': [{'field_id': 'po', 'observations': [{'value': '1000053337'}]}],
'lines': [{'fields': [
{'field_id': 'part', 'observations': [{'value': 'D4-AR1200163A1'}]},
{'field_id': 'qty', 'observations': [{'value': 120}]},
]}],
'conflicts': [],
}
def _supplement(candidates: list[str], **extra) -> dict:
"""构造带裸数字候选的正文补充事实(无表头场景 rows 为空)。"""
return {
'rows': [],
'issues': [],
'version': 'email-supplement.v1',
'document_id': 44,
'reservation_candidates': [
{'value': value, 'evidence': {
'table_index': None, 'row_index': index + 1, 'column_index': None,
'cell_id': f'reservation-heuristic:hash:line{index + 1}', 'raw_value': value,
}}
for index, value in enumerate(candidates)
],
**extra,
}
def _reservation_observation(order: dict):
"""读取兜底写入的 reservation Observation;未写入返回 None。"""
for line in order['lines']:
for field in line['fields']:
if field['field_id'] == 'reservation':
return field['observations'][0]
return None
# ---------------------------------------------------------------- 候选扫描
def test_scan_finds_bare_reservation_in_headerless_table_row():
"""截图场景:无表头数据表只识别整格纯数字的 39739;PO 整格入选由合并端排除。"""
html = (
'<table><tr><td>DBS PHX01</td><td>39739</td><td>6233</td>'
'<td>504-006055-001</td><td>D4-A08AR12000002</td><td>WEL</td>'
'<td>10/12/2026</td><td>120</td><td>1000053286</td></tr></table>'
)
candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h')
# 断言:仅两个整格纯数字入选——预约号 39739 与 PO 1000053286(10 位同样合规,
# 由合并端用已提取 PO 字段值/主题标签排除);仓库/料号/日期/数量格一概不取。
assert [item['value'] for item in candidates] == ['39739', '1000053286']
evidence = candidates[0]['evidence']
# 断言:DOM 级证据齐全,可回溯到具体表格/行/列。
assert evidence['table_index'] == 0
assert evidence['row_index'] == 0 and evidence['column_index'] == 1
assert evidence['cell_id'].startswith('reservation-heuristic:h:0')
def test_scan_ignores_cells_with_any_surrounding_content():
"""收紧规则:邮编地址、带字母/备注前后的值一律不取(07094/00410 误报修复)。"""
html = (
'<table><tr>'
'<td>Secaucus, NJ 07094</td>'
'<td>T00410</td>'
'<td>00410-CN</td>'
'<td>39739 (A)</td>'
'<td> 39739 </td>'
'<td>35354-1</td>'
'</tr></table>'
)
candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h')
# 断言:只有去除首尾空白后恰好为纯数字的整格幸存(39739);
# 07094 藏在地址文本里、00410 带字母前后、39739 带备注、35354-1 带后缀,全部排除。
assert [item['value'] for item in candidates] == ['39739']
def test_scan_returns_nothing_without_html_tables():
"""收紧规则:正文无 HTML 表格时不做兜底,纯文本中的数字不再是候选来源。"""
assert find_bare_numeric_reservation_candidates(html_tables=[], content_hash='h') == []
assert find_bare_numeric_reservation_candidates(html_tables=None, content_hash='h') == []
def test_scan_dedupes_and_caps_candidates():
"""同值只留首个证据;候选总数截断到上限,防止大表刷爆快照。"""
cells = '<td>4000122230</td><td>4000122230</td>' + ''.join(
f'<td>{30000 + index}</td>' for index in range(25)
)
html = f'<table><tr>{cells}</tr></table>'
candidates = find_bare_numeric_reservation_candidates(html_tables=[html], content_hash='h')
values = [item['value'] for item in candidates]
# 断言:重复格只保留首个证据;总数截断到 20(1 个 10 位 + 前 19 个 5 位)。
assert len(values) == 20
assert values[0] == '4000122230'
assert values.count('4000122230') == 1
def test_labeled_context_helper_extracts_subject_po():
"""主题「RE_ WELLTRUST ACC PO 1000053337」的 PO 号可被标签助手提取。"""
assert reservation_ids_in_labeled_context('RE_ WELLTRUST ACC PO 1000053337.eml') == {'1000053337'}
# ---------------------------------------------------------------- 过滤裁决
def test_filter_returns_unique_ambiguous_none():
"""过滤器三态:唯一→unique 可自动采纳;多个→ambiguous;全排除→none。"""
candidates = [{'value': value} for value in ['4000122230', '1000053337']]
surviving, status = filter_reservation_heuristic_candidates(
candidates, excluded_values={'1000053337'},
)
assert status == 'unique' and surviving[0]['value'] == '4000122230'
surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values=set())
assert status == 'ambiguous' and len(surviving) == 2
surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values={'1000053337', '4000122230'})
assert status == 'none' and surviving == []
# ---------------------------------------------------------------- 合并裁决
def test_merge_applies_unique_heuristic_candidate_to_lines():
"""唯一候选:低置信度写入缺失行;relation 标记 reservation_heuristic。"""
order = _order()
merged = merge_email_supplements(
orders=[order],
supplements_by_intake={1: _supplement(['4000122230', '1000053337'])},
schema_definition=SCHEMA,
)
observation = _reservation_observation(merged[0])
# 断言:候选中与已提取 PO 相同的 1000053337 被排除,唯一候选自动写入。
assert observation is not None and observation['value'] == '4000122230'
# 断言:启发式语义可辨识——confidence 0.5 + basis 标记,供复核端标注与审计。
assert observation['confidence'] == 0.5
assert observation['email_supplement_evidence']['basis'] == 'bare_numeric_heuristic'
assert merged[0]['_hxops_email_supplement_relation'] == 'reservation_heuristic'
assert merged[0]['_hxops_reservation_heuristic']['status'] == 'applied'
def test_merge_excludes_po_number_missing_from_pdf_via_subject_label():
"""截图 1 修复路径:PDF 侧 PO 也解析失败时,主题标签排除 PO,仍唯一命中。"""
order = _order()
order['header_fields'] = []
merged = merge_email_supplements(
orders=[order],
supplements_by_intake={1: _supplement(
['4000122230', '1000053337'],
email_subject='RE_ WELLTRUST ACC PO 1000053337.eml',
)},
schema_definition=SCHEMA,
)
observation = _reservation_observation(merged[0])
# 断言:主题「PO 1000053337」触发的标签排除让 4000122230 成为唯一候选。
assert observation is not None and observation['value'] == '4000122230'
def test_merge_ambiguous_candidates_become_review_conflict():
"""多候选:不自动挑值,转 supplement_field_conflict 由现有面板裁决。"""
order = _order()
order['header_fields'] = []
merged = merge_email_supplements(
orders=[order],
supplements_by_intake={1: _supplement(['4000122230', '5000122230'])},
schema_definition=SCHEMA,
)
# 断言:未写入任何 reservation,冲突与人工裁决标记就位。
assert _reservation_observation(merged[0]) is None
assert merged[0]['_hxops_reservation_heuristic']['status'] == 'ambiguous'
conflicts = [item for item in merged[0]['conflicts'] if item.get('field') == 'reservation_id']
assert len(conflicts) == 1
conflict = conflicts[0]
# 断言:复用现有冲突结构(reason/阻塞级别/header 作用域),候选值与逐候选证据齐全。
assert conflict['reason'] == 'supplement_field_conflict'
assert conflict['severity'] == 'blocking'
assert conflict['scope'] == 'header'
assert conflict['values'] == ['4000122230', '5000122230']
assert all(source['source_type'] == 'email_body' for source in conflict['sources'])
def test_merge_never_overwrites_existing_reservation():
"""已有合法预约单号(含邮件补充表正常解析出的值)时兜底绝不写入。"""
order = _order()
order['lines'][0]['fields'].append(
{'field_id': 'reservation', 'observations': [{'value': '3000099143'}]},
)
merged = merge_email_supplements(
orders=[order],
supplements_by_intake={1: _supplement(['4000122230'])},
schema_definition=SCHEMA,
)
# 断言:原值保持不变,无启发式标记与 relation 变更。
assert _reservation_observation(merged[0])['value'] == '3000099143'
assert '_hxops_reservation_heuristic' not in merged[0]
assert '_hxops_email_supplement_relation' not in merged[0]
def test_merge_never_overwrites_invalid_format_reservation_raw_value():
"""行上已有非法格式预约单号原值(如字母型编号)时同样不覆盖,交人工纠错。"""
order = _order()
order['lines'][0]['fields'].append(
{'field_id': 'reservation', 'observations': [{'value': 'RSV-88'}]},
)
merged = merge_email_supplements(
orders=[order],
supplements_by_intake={1: _supplement(['4000122230'])},
schema_definition=SCHEMA,
)
# 断言:非法原值虽不通过 5/10 位校验,仍属已有业务事实,兜底跳过。
assert _reservation_observation(merged[0])['value'] == 'RSV-88'
assert '_hxops_reservation_heuristic' not in merged[0]
def test_merge_excludes_qty_and_row_values_from_candidates():
"""数量 39739 与补充行已提取值都参与排除,防止把业务数值误当预约单号。"""
order = _order()
order['lines'][0]['fields'][1]['observations'][0]['value'] = 39739
supplement = _supplement(['39739'])
supplement['rows'] = [{'customer_po_number': '1000053337'}]
order['header_fields'] = []
merged = merge_email_supplements(
orders=[order],
supplements_by_intake={1: supplement},
schema_definition=SCHEMA,
)
# 断言:候选恰为行数量值 → 排除后 none:无注入、无标记。
assert _reservation_observation(merged[0]) is None
assert '_hxops_reservation_heuristic' not in merged[0]
def test_merge_unique_claim_not_reused_across_orders():
"""同 Intake 多订单共享候选:先到先得,第二个订单不得重复占用同一候选。"""
first = _order()
second = _order()
second['lines'][0]['fields'][0]['observations'][0]['value'] = 'D4-A08AR12000002'
merged = merge_email_supplements(
orders=[first, second],
supplements_by_intake={1: _supplement(['4000122230'])},
schema_definition=SCHEMA,
)
# 断言:第一个订单占用后 claimed 生效,第二个订单无候选可用且不产生标记。
assert _reservation_observation(merged[0])['value'] == '4000122230'
assert _reservation_observation(merged[1]) is None
assert '_hxops_reservation_heuristic' not in merged[1]
def test_merge_skips_when_schema_lacks_reservation_field():
"""Schema 未配置 reservation_id 时兜底整体跳过,不误建字段。"""
schema = {'fields': [item for item in SCHEMA['fields'] if item.get('field_code') != 'reservation_id']}
order = _order()
merged = merge_email_supplements(
orders=[order],
supplements_by_intake={1: _supplement(['4000122230'])},
schema_definition=schema,
)
assert _reservation_observation(merged[0]) is None
assert '_hxops_reservation_heuristic' not in merged[0]
def test_merge_writes_header_scope_reservation_when_schema_declares_header():
"""Schema 声明 header 作用域预约单号时,唯一候选写入订单头默认值。"""
order = _order()
merged = merge_email_supplements(
orders=[order],
supplements_by_intake={1: _supplement(['4000122230', '1000053337'])},
schema_definition=HEADER_RESERVATION_SCHEMA,
)
header_field = next(
item for item in merged[0]['header_fields'] if item['field_id'] == 'reservation'
)
# 断言:header 作用域配置下候选写入 header_fields(effective = line ?? header 的头侧默认值)。
assert header_field['observations'][0]['value'] == '4000122230'
assert merged[0]['_hxops_reservation_heuristic']['status'] == 'applied'
def test_merge_without_candidates_key_is_noop():
"""旧 Run 补充快照无 reservation_candidates 键:兜底静默跳过,行为不变。"""
order = _order()
supplement = _supplement([])
supplement.pop('reservation_candidates')
merged = merge_email_supplements(
orders=[order],
supplements_by_intake={1: supplement},
schema_definition=SCHEMA,
)
assert _reservation_observation(merged[0]) is None
assert '_hxops_reservation_heuristic' not in merged[0]
-21
View File
@@ -1,21 +0,0 @@
# 调试记录:访问不可用
- 状态:OPEN
- 会话:access-unavailable
- 日期:2026-09-09
## 症状
用户反馈“无法访问”,尚未明确是前端页面、后端接口、登录链路还是企微消息访问失败。
## 假设
1. 前端开发服务器未启动或端口 8881 不可达。
2. 后端 Flask 服务未启动或端口 5052 不可达。
3. 前端代理、环境地址或跨域配置指向了错误的后端地址。
4. 服务启动后因数据库或外部集成初始化异常退出。
5. 浏览器会话、认证或路由守卫导致访问被拒绝。
## 证据与下一步
待确认访问目标、访问地址、浏览器报错或网络响应后,再收集运行时证据。
-37
View File
@@ -1,37 +0,0 @@
---
session_id: training-video-push-duplicate
status: RESOLVED
---
# 员工培训视频重复推送调试记录
## 症状
测试环境只有 2 个可推送视频,但第 1 期和第 2 期任务向员工展示了相同的 2 个视频。预期是全部视频推送完成后暂停,不再重复推送。
## 假设
1. 推送游标没有跨任务继承,新任务重新从第一个视频开始。
2. 已推送判断只按任务 ID,而不是按视频资源 ID。
3. 推送完成后游标没有持久化或读取错误。
4. 前端资源快照映射错误,后端实际推送资源与页面展示资源不一致。
5. 发布与补推并发读取同一游标,产生重复批次。
## 当前阶段
已定位根因并修复(2026-09-18,用户确认后实施);2026-09-29 生产环境复现变体(每周自动推送路径),已按方案 A 二次修复。
## 结论
- **根因(假设 1 成立)**:HR 在管理端手动新建下一期周任务走 `create_or_update_weekly_task`,新实例 `pushed_video_count=0`,API 层因游标为 0 自动推首批——视频从第 1 个重新推起;视频总数 ≤ 每周推送数量时两期展示完全相同。自动滚动路径(周一排程 `ensure_current_week_task`)本就继承游标,不受影响。
- **修复**:
1. `lean_training_service.create_or_update_weekly_task`:新建任务游标改为继承历史推送进度——取新冻结列表的"最长已推送前缀"长度(`_inherited_pushed_video_count`,以全部已发布任务已推送前缀并集为基线),从上一任务断点续推;
2. `lean_training_push_service.push_lean_training_videos`:分批时跨任务绝对去重(`_already_pushed_resource_ids`),已被其它任务推送过的视频绝不进批次(游标越过);待推区间全部重复时游标推进到末尾、返回 completed 且不发企微。
- **回归保障**:`backend/tests/test_lean_training_push.py` 两条契约测试(继承游标不重推首批 / 断点续推只推新视频且重复区间推完即停)。
## 第二轮(2026-09-29):自动滚动路径的"内容重复"变体
- **现象**:生产环境第 2 期(每周一自动推送)又出现第 1 期已推送视频(如 17、18)。数据库实况:第 2 期 `video_resource_ids=[17,18,25,24,23,22,21,20,19]`、`pushed_video_count=4`、`weekly_count=2`。
- **根因**:与第一轮不同——**企微推送并未重发旧视频**(批次实为 [25,24] 新视频,游标=继承 2 + 本期 2 = 4 属正常绝对游标语义)。重复发生在**任务内容层**:`ensure_current_week_task` 自动滚动时把上一期冻结列表原样复制进新一期(复制 + 尾部追加新视频),而学员端展示(`serialize_weekly_task(learner_view)`)、观看/完成校验(`mark_video_watched` / `save_completion`)、管理看板视频列(`_task_video_rows`)全部按**累积已推送前缀** `video_resource_ids[:pushed_video_count]` 取数——上一期已推送视频出现在第 2 期且要求重看重写感悟,员工感知即"重复推送"。
- **修复(方案 A,2026-09-29)**:新增 `_first_pushed_video_ids_map()` / `_own_pushed_video_ids()`(按周次升序遍历已发布任务,已推送前缀中"此前其它任务未推送过"的视频才归属本任务),并把上述四处口径统一改为"本任务首次推送的部分"。游标与数据结构不动;已产生的脏数据(第 2 期前缀含旧视频)自动恢复正常展示,无需修库。
- **回归保障**:新增契约测试 `test_learner_period_videos_only_own_first_pushed`(复刻生产脏数据:第 2 期学员端只见/只考本期新增视频、第 1 期展示不受影响、看板口径一致、越权观看被拒)。
+1
View File
@@ -5,6 +5,7 @@
| [features/](features/README.md) | **业务域**落地手册(部署、Dify、API、运维;**产品原型随域同目录**) |
| [platform/](platform/README.md) | **平台级**设计与跨域原型(Agent 注册、进度底座、Runtime Context) |
| [convention/](convention/) | 开发规范(提交、错误处理、环境变量、发布流程等) |
| [ui/](ui/ELEMENT_MIGRATION.md) | 界面规范([设计系统](ui/DESIGN_SYSTEM.md)、[编码准则](ui/UI_CODING_GUIDELINES.md)、[Element 迁移](ui/ELEMENT_MIGRATION.md)) |
| [skills/](skills/README.md) | Cursor Agent Skills 团队说明([i18n](skills/add-i18n-keys-skill.md)、[发布说明](skills/release-notes-skill.md)) |
| [openapi/](openapi/) | Dify / 集成 OpenAPI 契约 |
| [dify/](dify/) | Dify 集成说明 |
+6 -1
View File
@@ -1,5 +1,9 @@
# 智能HR请假管理需求
## 年度教育训练计划(2026-10)
独立于入职、安全、精益、出国规章培训。年底按主办单位收集下一年度计划,讲师按月排课;课程库保存可重复使用的课件和试题,签到、录制、考试发布和完成状态记在月度场次上。未完成提醒每周一 09:00 发给当月仍有未完成场次的讲师,文案对齐人事课内部邮件。细则见 [features/training/annual-training-plan-demand.md](features/training/annual-training-plan-demand.md),设计方案见 [features/training/annual-training-plan-design.md](features/training/annual-training-plan-design.md),原型见 [features/training/annual-training-plan-prototype.html](features/training/annual-training-plan-prototype.html)。
## 订单交期回复 Agent(2026-09)
生管在工作台按 ERP 已审核、已核准、未结案的销售订单行回复交期(可拆多批次),保存后经行内或批量企微通知对应业务员并锁定;具备只读权限的业务人员可查看,回执不改状态。系统只读 ERP,不回写。操作权限按用户功能权限划分。每天 07:00(北京时间)全量同步全部合格订单,可手动刷新;正式环境可配置同步起始日期(`ORDER_DELIVERY_SYNC_DATE_FROM`,如上线日 2026-10-10),只同步订单日期 ≥ 起始日的订单行(2026-10-09 增补)。一期不做单别白名单管理,操作页不出单别列。细则见 [features/order-delivery-reply/demand.md](features/order-delivery-reply/demand.md)。
@@ -22,7 +26,7 @@
## 设备验收预警(2026-09)
- 从 OA 资产验收单第一次进入「使用部门担当」起按自然日累计停留;只监控未归档、有效、可以验收的流程。归档、退回、撤回、作废或无法验收立即停表。再进入时计时起点不改,仍按第一次写入的 `sbsyrjssj` 计算,不从 0 重计。`sfzfth` 不考虑从退回改回正常。
- 超过 30/37/44/51 天各发一次企业微信。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人汇总。
- 超过 30/37/44/51 天各发一次企业微信。第 4 轮默认关闭,配置打开后才通知总经理。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理可在界面配置。每日扫描只生成待发送,初始每周五 18:00 按收件人发送汇总卡片和 Excel 明细。
- 规则已冻结。验收单读 E10 `ecology10.dbo.ft_gdzcysdv2`,人员 ID 经 `eteams.dbo.employee` 用工号对上系统用户。流程状态读 `wfc_requestbase.flowstatus`,`7`、`8`、`99`、`-99` 都按撤销停表。当前节点读 `wfc_currentnode` 再关联 `wfp_node`,当前处理人读 `wfc_operate.userid`。直接主管取 `employee.SUPERIOR`,经副理按 `employee.DEPARTMENT` 查 E10 部门矩阵。申请人 `sqr` 是人员 ID。退回为 `sfzfth = 0`。无法验收说明正文是 `ycsm`,只留痕。只读同步、停留列表、发送记录、每日扫描和周五企业微信已实现,入口与合同付款预警相同(内置 Chat Agent `equipment_acceptance`)。不查询、不保存 `isremark`。默认每天 06:00 扫描、每周五 18:00 按收件人发送。停表取消未发送,已发送不撤回。需求见 [设备验收预警需求](features/equipment-acceptance-warning/demand.md),数据设计见 [technical.md](features/equipment-acceptance-warning/technical.md)。
## 合同付款预警 Agent(2026-08)
@@ -297,6 +301,7 @@
- **生命周期治理**:创建、编辑、启停、简码变更和识别证据创建/审核/停用/自动匹配授权必须记录客户快照、操作者、原因与前后差异;简码、状态和自动匹配授权变更必须填写原因,管理员可在客户主数据页面查询时间线和门禁状态。
- **客户角色分离**:订单解析必须分别保存 Bill-to 账款客户和 Ship-to 送货对象的原文及证据;Bill-to 决定业务归属客户,Ship-to 指向客户主数据下的送货站点。客户简称只能由已确认 Bill-to 主数据派生,禁止由 LLM 提取或人工在订单模板中重复维护。
- **确定性优先匹配**:存在来源系统和外部编码时必须优先精确匹配;否则回退标准名称和已审核别名。未命中、多候选或站点归属不合法时进入人工复核。
- **确认客户改绑(2026-10-13)**:客户确认后发现识别/选择错误时,支持在订单复核工作台直接改绑已确认客户(守卫:尚未产生发货通知 Excel 且无活动处理、目标客户有效且不同于当前客户、乐观锁版本一致),改绑更新确认结果、追加证据并全链路审计,同步原地刷新冻结快照客户;改后回通知准备重新生成 Excel,已产生 Excel 时须先走撤销流程。
### 3.x 货代发货通知建单防重复(第一阶段)
+1
View File
@@ -16,6 +16,7 @@
| [contract-payment-plan](contract-payment-plan/) | 合同付款计划 / 预警 Agent | [方案 V3](contract-payment-plan/contract-payment-warning-proposal-v3.md) · [工作台原型](contract-payment-plan/contract-payment-plan-workspace-prototype-v2.html) · [人工复核原型](contract-payment-plan/contract-payment-review-prototype.html) · [Chat Agent 原型](contract-payment-plan/contract-payment-chat-agent-prototype.html) |
| [equipment-maintenance](equipment-maintenance/README.md) | 设备维保助手 | [聊天原型](equipment-maintenance/equipment-maintenance-agent-chat-lofi.html) |
| [equipment-acceptance-warning](equipment-acceptance-warning/README.md) | 设备验收停留预警 | [需求说明](equipment-acceptance-warning/demand.md) · [数据设计](equipment-acceptance-warning/technical.md) |
| [training](training/) | 教育训练:新人培训与年度计划 | [年度教育训练计划需求](training/annual-training-plan-demand.md) · [设计方案](training/annual-training-plan-design.md) · [可点击原型](training/annual-training-plan-prototype.html) · [精益周任务规则](training/精益管理周任务规则手册.md) |
**平台级**设计与跨域原型见 [platform/](../platform/README.md)。
@@ -76,6 +76,9 @@
}
.when { display: flex; flex-direction: column; gap: 8px; }
.when b { font-size: 12px; color: var(--muted); font-weight: 700; }
.switch { display: flex; align-items: center; gap: 6px; font-size: 13px; font-weight: 700; }
.when small { color: var(--muted); font-size: 12px; }
.round.off .people { opacity: 0.45; }
.day {
display: flex;
align-items: center;
@@ -267,10 +270,12 @@
</div>
</article>
<article class="round">
<article class="round off" id="round4">
<div class="when">
<b>第 4 轮</b>
<label class="day">超过 <input value="51" /> 天</label>
<label class="switch"><input id="round4Switch" type="checkbox" /> 启用第 4 轮</label>
<small>默认关闭,不通知总经理</small>
</div>
<div class="people">
<div class="line">
@@ -305,7 +310,12 @@
<button class="save" type="button">保存配置</button>
</div>
</section>
<p class="mark">效果图,尚未接到现有页面。</p>
<p class="mark">效果图。第 4 轮开关已接到现有配置页,默认关闭。</p>
<script>
document.getElementById("round4Switch").addEventListener("change", (event) => {
document.getElementById("round4").classList.toggle("off", !event.target.checked);
});
</script>
</main>
</body>
</html>
@@ -60,6 +60,8 @@
| 超过 44 天 | COO | 采购经副理 |
| 超过 51 天 | 总经理 | COO、采购经副理 |
第 4 轮在配置里单独开关,默认关闭。关闭时不生成、也不发送总经理这一轮。打开后,下一次扫描才按超过第 4 档的天数产生待发送。前 3 轮不受这个开关影响。
人员解析:
- 担当、直接主管、经副理取**当前节点处理人**及其上级,不固定成「使用部门担当」本人。
@@ -70,7 +72,7 @@
## 6. 推送
已确认:扫描与发送分离。发送时刻做成可配置,**初始对齐合同付款预警,为每周五 18:00**(见 [合同付款预警需求](../contract-payment-plan/demand.md))。到点后按收件人合并为一条企业微信汇总。渠道只有企业微信。
已确认:扫描与发送分离。发送时刻做成可配置,**初始对齐合同付款预警,为每周五 18:00**(见 [合同付款预警需求](../contract-payment-plan/demand.md))。到点后按收件人合并为一条企业微信汇总卡片,并紧跟一份只含该收件人明细的 Excel。这份 Excel 按收件人归档,挂在发送记录表的 Excel 附件列上,点文件名再下载。卡片不逐条列出验收单,也不区分主送和抄送。渠道只有企业微信。
## 7. 数据来源
@@ -0,0 +1,279 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>设备验收预警 · 发送效果图</title>
<style>
:root {
--ink: #142033;
--muted: #64748b;
--line: #dce4ef;
--paper: #ffffff;
--page: #f3f6fa;
--brand: #1d4e89;
--chat: #ededed;
--ok: #217346;
}
* { box-sizing: border-box; }
body {
margin: 0;
min-height: 100vh;
background: var(--page);
color: var(--ink);
font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
}
.page { max-width: 1180px; margin: 0 auto; padding: 18px 20px 48px; }
h1 { margin: 0; font-size: 20px; }
.note { margin: 8px 0 0; color: var(--muted); font-size: 13px; }
.grid {
display: grid;
grid-template-columns: 380px minmax(0, 1fr);
gap: 16px;
margin-top: 16px;
align-items: start;
}
.panel {
background: var(--paper);
border: 1px solid var(--line);
border-radius: 16px;
box-shadow: 0 1px 2px rgba(20, 32, 51, 0.04);
}
.panel h2 { margin: 0; font-size: 15px; }
.panel .sub { margin: 4px 0 0; color: var(--muted); font-size: 12px; }
.head { padding: 16px 18px 0; }
.phone {
margin: 14px 18px 18px;
border-radius: 28px;
background: #111;
padding: 10px;
}
.screen {
overflow: hidden;
border-radius: 20px;
background: var(--chat);
min-height: 560px;
}
.bar {
display: flex;
align-items: center;
justify-content: center;
height: 48px;
background: #f7f7f7;
border-bottom: 1px solid #e5e5e5;
font-size: 15px;
font-weight: 700;
}
.thread { padding: 16px 14px 22px; }
.time { margin: 0 0 12px; text-align: center; color: #8a8a8a; font-size: 12px; }
.card {
background: #fff;
border-radius: 6px;
padding: 14px 14px 0;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04);
}
.card h3 { margin: 0 0 10px; font-size: 16px; font-weight: 700; }
.card p { margin: 0; color: #3d3d3d; font-size: 14px; line-height: 1.65; white-space: pre-line; }
.more {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 12px;
padding: 10px 0 12px;
border-top: 1px solid #ececec;
color: #1f1f1f;
font-size: 14px;
}
.file {
display: flex;
align-items: center;
gap: 10px;
width: 250px;
margin-top: 10px;
padding: 10px 12px;
background: #fff;
border-radius: 6px;
}
.xls {
display: grid;
place-items: center;
width: 36px;
height: 40px;
border-radius: 4px;
background: var(--ok);
color: #fff;
font-size: 11px;
font-weight: 800;
}
.file b { display: block; font-size: 13px; font-weight: 650; }
.file span { color: #8a8a8a; font-size: 12px; }
.sheet { padding: 8px 12px 16px; overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th, td { padding: 8px 10px; text-align: left; white-space: nowrap; }
.sheet th { background: #e8f3ec; color: #145c32; font-weight: 700; border-bottom: 1px solid #cfe3d6; }
.sheet td { border-bottom: 1px solid #edf2f7; }
.sheet tr:nth-child(even) td { background: #fbfcfd; }
.foot { padding: 0 18px 16px; color: var(--muted); font-size: 12px; }
.admin { margin-top: 16px; }
.tabs { display: flex; gap: 4px; margin-top: 14px; border-bottom: 1px solid var(--line); }
.tabs span {
margin-bottom: -1px;
padding: 8px 12px 10px;
border-bottom: 2px solid transparent;
color: var(--muted);
font-size: 14px;
font-weight: 700;
}
.tabs .on { border-color: var(--brand); color: var(--brand); }
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 18px 0;
}
.toolbar p { margin: 0; color: var(--muted); font-size: 12px; }
button {
border: 1px solid var(--brand);
background: var(--brand);
color: #fff;
border-radius: 8px;
padding: 7px 12px;
font-size: 12px;
font-weight: 700;
}
.list { padding: 12px 12px 8px; overflow-x: auto; }
.list th { background: #f8fbff; color: var(--muted); font-weight: 700; }
.list td { border-bottom: 1px solid var(--line); }
.sent { color: #142033; }
.wait { color: #9a6700; font-weight: 700; }
.bad { color: #b42318; font-weight: 700; }
@media (max-width: 900px) {
.grid { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<main class="page">
<h1>设备验收预警 · 发送效果图</h1>
<p class="note">效果图,尚未接到现有页面。同一个人只收一条汇总卡片,明细在下一条 Excel。不再区分主送和抄送。</p>
<div class="grid">
<section class="panel">
<div class="head">
<h2>sophie 收到的企业微信</h2>
<p class="sub">她这一轮有 18 张单,卡片里不逐条列出。</p>
</div>
<div class="phone">
<div class="screen">
<div class="bar">设备验收预警</div>
<div class="thread">
<p class="time">19:52</p>
<article class="card">
<h3>设备验收停留提醒</h3>
<p>共 18 张验收单。
超过 30 天 12 张,超过 37 天 4 张,超过 44 天 2 张。
明细见下一条文件。</p>
<div class="more"><span>查看详情</span><span>›</span></div>
</article>
<article class="file">
<div class="xls">XLS</div>
<div>
<b>设备验收停留提醒.xlsx</b>
<span>28.4 KB</span>
</div>
</article>
</div>
</div>
</div>
</section>
<section class="panel">
<div class="head">
<h2>附件里的前 8 行</h2>
<p class="sub">只含 sophie 本人要看的单。通知身份说明她为什么会收到,不再写主送、抄送。</p>
</div>
<div class="sheet">
<table>
<thead>
<tr>
<th>验收单号</th>
<th>采购单号</th>
<th>申请人</th>
<th>轮次</th>
<th>停留天数</th>
<th>当前节点</th>
<th>当前处理人</th>
<th>通知身份</th>
</tr>
</thead>
<tbody>
<tr><td>20260210000001</td><td>1111</td><td>孙浩</td><td>超过 30 天</td><td>31</td><td>使用部门担当</td><td>吴敏</td><td>直接主管</td></tr>
<tr><td>20260211000008</td><td>CG-0881</td><td>李文</td><td>超过 30 天</td><td>33</td><td>品质担当</td><td>林可</td><td>直接主管</td></tr>
<tr><td>20260212000015</td><td>CG-0902</td><td>周洋</td><td>超过 30 天</td><td>36</td><td>公用主管</td><td>sophie</td><td>当前处理人</td></tr>
<tr><td>20260213000022</td><td>CG-0910</td><td>孙浩</td><td>超过 37 天</td><td>40</td><td>设备管理部</td><td>周宁</td><td>采购经副理</td></tr>
<tr><td>20260214000031</td><td>CG-0933</td><td>陈敏</td><td>超过 37 天</td><td>41</td><td>品质经理</td><td>何倩</td><td>采购经副理</td></tr>
<tr><td>20260215000040</td><td>CG-0948</td><td>刘洋</td><td>超过 44 天</td><td>46</td><td>COO</td><td>陈立</td><td>采购经副理</td></tr>
<tr><td>20260216000052</td><td>CG-0961</td><td>王磊</td><td>超过 30 天</td><td>32</td><td>使用部门经理</td><td>赵凯</td><td>直接主管</td></tr>
<tr><td>20260217000060</td><td>CG-0977</td><td>孙浩</td><td>超过 30 天</td><td>35</td><td>固定资产管理人</td><td>孙浩</td><td>采购担当</td></tr>
</tbody>
</table>
</div>
<p class="foot">文件内共 18 行。同一张单若第 1 轮和第 2 轮都还没发过,会各占一行。停留天数是发送当时的天数。</p>
</section>
</div>
<section class="panel admin">
<div class="tabs">
<span>停留情况</span>
<span class="on">发送记录</span>
<span>预警配置</span>
</div>
<div class="toolbar">
<p>每日扫描生成待发送。每周五 18:00 按人汇总,每人一条卡片加一份 Excel。这里仍是一条记录对应一张单的一轮。</p>
<button type="button">导出 Excel</button>
</div>
<div class="list">
<table>
<thead>
<tr>
<th>验收单号</th>
<th>采购单号</th>
<th>轮次</th>
<th>收件人</th>
<th>结果</th>
<th>发送时间</th>
</tr>
</thead>
<tbody>
<tr>
<td>20260210000001</td>
<td>1111</td>
<td>超过 30 天</td>
<td>吴敏、sophie、孙浩</td>
<td class="sent">已发送</td>
<td>2026-10-12 18:55:18</td>
</tr>
<tr>
<td>20260212000015</td>
<td>CG-0902</td>
<td>超过 37 天</td>
<td>孙经理、COO、赵琴</td>
<td class="wait">待发送</td>
<td>—</td>
</tr>
<tr>
<td>20260215000040</td>
<td>CG-0948</td>
<td>超过 44 天</td>
<td>COO、赵琴</td>
<td class="bad">发送失败</td>
<td>—</td>
</tr>
</tbody>
</table>
</div>
<p class="foot">页面上的「导出 Excel」是当前列表里的全部记录。个人在企业微信里收到的文件只含他自己的行。</p>
</section>
</main>
</body>
</html>
@@ -412,7 +412,7 @@ LEFT JOIN eteams.dbo.employee AS handler ON handler.ID = op.userid;
页面入口与合同付款预警相同:迁移写入内置 Chat Agent,`agent_code=equipment_acceptance`,`conversation_mode=task_chat`。对话页按该编码替换消息列表和输入框,页签是停留情况、发送记录和预警配置。普通用户要在用户管理里授予该 Agent 后才看得到。
`equipment_acceptance_settings` 只保留一行。`day_1` 到 `day_4` 默认 30、37、44、51,保存时必须逐档增大。`buyer_manager_user_id`、`coo_user_id`、`executive_user_id` 指向 `users.id`,姓名只在页面上显示。发送时刻不在这张表。`GET/PUT /api/equipment-acceptance/config`:有权限的用户可看,保存只给平台管理员。
`equipment_acceptance_settings` 只保留一行。`day_1` 到 `day_4` 默认 30、37、44、51,保存时必须逐档增大。`round_4_enabled` 默认关闭,关闭时扫描不生成第 4 轮,发送也会跳过已经待发送的第 4 轮。`buyer_manager_user_id`、`coo_user_id`、`executive_user_id` 指向 `users.id`,姓名只在页面上显示。发送时刻不在这张表。`GET/PUT /api/equipment-acceptance/config`:有权限的用户可看,保存只给平台管理员。
## 9. 扫描与发送
@@ -423,11 +423,11 @@ LEFT JOIN eteams.dbo.employee AS handler ON handler.ID = op.userid;
- 超过第 1 档:主送当前处理人,抄送其 `employee.SUPERIOR` 和申请人。
- 超过第 2 档:主送各处理人部门的经副理,抄送配置里的 COO 和采购经副理。
- 超过第 3 档:主送 COO,抄送采购经副理。
- 超过第 4 档:主送总经理,抄送 COO 和采购经副理。
- 超过第 4 档:主送总经理,抄送 COO 和采购经副理。配置里的第 4 轮开关默认关闭,关闭时这一档不产生、也不发送。
人员 ID 先对 `eteams.dbo.employee`,再用 `JOB_NUM` 对 `users.employee_id`,发送用 `users.wecom_userid`。矩阵 `relate_id` 和 E10 人员 ID 都不是企微 userid。没有工号、对不上用户、没绑企微、没有主管或经副理、三个岗位没选,都记在该席位上,不改发给别人。至少有一名可发的人时状态是待发送;一个都没有则整档失败。
每周五 18:00 排程 `equipment-acceptance-alert-weekly` 只发送状态为待发送的记录,不再同步。同一企微账号合并成一条文本卡片,标题「设备验收停留提醒」,事件 `equipment_acceptance_warning`。卡片过长时先留 12 行,其余写成「另有 N 条」。发送成功改为已发送。有人失败则整档改为失败,并附上「企业微信发送失败」;下次扫描会按当前处理人重算并回到待发送。已发出的企业微信不撤回。
每周五 18:00 排程 `equipment-acceptance-alert-weekly` 只发送状态为待发送的记录,不再同步。同一企微账号先收一条文本卡片,标题「设备验收停留提醒」,正文先写共多少张验收单已逾期,再写各轮次数量,事件 `equipment_acceptance_warning`。紧跟着一条文件消息《设备验收停留提醒.xlsx》,列是验收单号、采购单号、申请人、轮次、停留天数、当前节点、当前处理人、通知身份。卡片不写主送、抄送,也不逐条列出验收单。卡片和文件都成功才改为已发送。任一失败则整档改为失败,并写上卡片或附件的原因;下次扫描会按当前处理人重算并回到待发送。每位收件人的 Excel 写入 `equipment_acceptance_send_files`,并记下对应的发送记录。发送失败也保留。发送记录表用 Excel 附件列下载,同一行可有多份。已发出的企业微信不撤回。
停表(归档、退回、撤回、作废、无法验收,以及强制结束)时,待发送和解析失败且还没 `sent_at` 的行改为已取消。
@@ -466,6 +466,7 @@ WYC26071501
- 必须为 **5 位或 10 位纯数字**,例如 `12345` 或 `1000140351`。
- Excel 中的数字型编号可能被存成浮点格式,系统会自动规范为同一字符串再比对,避免「1000140351」与「1000140351.0」对不上。
- 32 位十六进制内部主键和 UUID 会被拒绝,不参与订单关联、指纹或库存匹配。
- **邮件正文表格裸数字兜底(2026-10-14,2026-10-15 收紧)**:邮件正文的数据表没有表头、无法按列名识别预约单号时,系统只扫描**正文表格**中「整格恰好为 5 位或 10 位纯数字」的单元格:若排除其他字段内容(客户 PO 号、数量、日期、供应商编号等)后恰好剩一个候选,作为预约单号的低置信度默认值并在工作台提示「待人工确认」;存在多个候选则不自动填入,转人工在字段冲突面板选择。自由文本(签名、地址邮编如 `Secaucus, NJ 07094`)与前后带任何字符的值(如 `T00410`)一律不取;客户 PO 号本身常为 10 位纯数字,无论它在表格还是主题(如「PO 1000053337」),都会被优先排除。
**不参与匹配的字段:**
+102 -3
View File
@@ -15,7 +15,9 @@
**已完成桶**:默认子视图「通知完成」为跨 OT 平铺的明细行报表(`GET /shipping-tasks/my-todos/done-lines`),行 = 标准 12 字段(客户/客户编号/订单日期/订单项次/料号/数量/约定出货日期/客户PO/已用数量/open qty/订单单号/单价)+ 页面溯源列(`business_no||task_no`);筛选支持 客户 / 料号 / 发货通知日期(Notice created_at)范围,按明细行分页;导出 `GET .../done-lines/export` 严格 12 列中文表头(OT 不落列,openpyxl 直写,不注册模板)。已用数量/open qty 后端暂无数据源,契约留空;约定出货日期取行级 `required_date`(缺失回退快照表头列)、订单单号取表头 `source_order_number`(field_id 键)、单价取行 `unit_price`。「复核驳回 / 已作废」子视图走既有任务表 + 抽屉,`my-todos` 新增 `terminal_kind` 参数(`upload_complete|reject_void`)服务端过滤。
**批量操作**:仅「货代上传」阶段的正式 Notice 行有复选框(`isFreightUploadRow`),勾选 ≥1 后浮出深色操作条(下载 ZIP / 确认已上传 / 发起 RPA / 清除),无常驻工具栏;修复批量按钮 i18n 裸 key(`workspace.shippingNotice.batch.*` 此前误挂 `schedule.batch`,已在四语言归位补齐)。新增页面文案(表格/终态角标/子视图/抽屉/报表列头等)已同步 zh-CN / zh-TW / en / th。
**批量操作**:仅「货代上传」阶段且当前用户可下载(`isBatchDownloadableRow` = `isFreightUploadRow` + 后端谓词字段 `can_download_export`)的正式 Notice 行有复选框,勾选 ≥1 后浮出深色操作条(下载 ZIP / 确认已上传 / 发起 RPA / 清除),无常驻工具栏;修复批量按钮 i18n 裸 key(`workspace.shippingNotice.batch.*` 此前误挂 `schedule.batch`,已在四语言归位补齐)。新增页面文案(表格/终态角标/子视图/抽屉/报表列头等)已同步 zh-CN / zh-TW / en / th。
**Excel 下载权限统一口径(2026-10-13)**:单票(`/shipping-tasks/<no>/export`、`/shipping-notices/<business_no>/export`)与批量(`/shipping-notices/batch/export`、`/shipping-exports/archive`)的下载授权一律消费 `query_service.can_download_task_export` 统一谓词——**创建者或平台管理员(可下载=可见,无主单仅管理员)**;管理员下载消除"看得到点不动",全部下载(含批量按票)写 `record_access_audit`(批量 `metadata.export=batch_zip` 并附 `batch_status`)。UI 与端点同源:SUMMARY/DETAIL enrich 下发 `can_download_export`;`ui_state` 的 `download_excel` 动作按查看者门禁下发(viewer 缺省的聊天链路维持仅 Artifact 授权旧口径);任务中心复选框/全选、抽屉下载链接均消费谓词字段,禁止前端由 `created_by` 自行反推。写路径归属(`get_task_for_user` / 履约归属断言)不变。
## 任务中心 OT 直链工作台:深链补 Case 锚点 + 任务详情兜底(2026-09-17)
@@ -452,6 +454,8 @@ L1 字段级:目标单元格 + 表头 + 相邻单元格
**邮件补充重建规则(2026-07-31)**:邮件表头只能按当前 Run 冻结 Schema 的显式别名映射;行级 `reservation_id` 包含真实业务表头 `External reservation ID`。只要 Intake 保留原始 `body_html_tables`,Run 冻结时必须按自己的 Schema 重新解析完整补充表,不能复用上传阶段缺字段但已有部分行的旧结果;没有 HTML 时才复用已有完整结果或安全回退纵向纯文本解析。**关联收紧(2026-09-15)**:`mpn_fallback` 仅适用于补充行 PO 缺失且料号唯一命中;有 PO 且与 PDF 不一致不得补充。预约号允许短数字行序后缀归一(如 `35354-1` → `35354`)。**无 PO 表头(2026-09-16)**:分配表缺 PO 列但已映射料号或预约号时仍解析补充行(`po_header_missing` 仅作可观测标记);无身份列时仍整表跳过。
**预约单号裸数字兜底(2026-10-14,2026-10-15 收紧)**:EML 正文数据行无表头(如 `DBS SLC 4000122230 6233 504-006075-001 …`)时,表头契约解析不出补充行,`reservation_id` 缺失会阻断库存匹配/Excel/货代上传。补充合并末段(`merge_email_supplements`)因此增加有条件兜底:仅当订单头与全部行均无预约单号取值时触发(已有值含非法格式原值、人工填写一律不覆盖)。候选扫描(`reservation_id.find_bare_numeric_reservation_candidates`,摄取落库与 Run 冻结重建两处执行)**只扫正文 HTML 表格**,且单元格整格去除首尾空白后必须恰好为 5/10 位纯数字(与 Reservation ID 值契约同源)——**2026-10-15 收紧**:不再扫描自由文本(签名、地址邮编 `Secaucus, NJ 07094`、引用链均排除),带任何前后字符的值(如 `T00410`、`39739 (A)`、`35354-1`)一律不取;无 HTML 表格的正文不做兜底。候选数上限 20,DOM cell_id 证据可回溯。排除集 = 订单已提取字段值(全部 Observation 及 PO/预约号归一变体)∪ 邮件补充行值 ∪ 主题「PO/Invoice/Qty」等标签后数字 ∪ 同趟跨单已占用值(PO 号同为 10 位整格纯数字会入选候选,靠本排除集剔除)。排除后**唯一候选** → 以 confidence 0.5、`email_supplement_evidence.basis='bare_numeric_heuristic'` 低置信度写入(Schema 声明 header 作用域写订单头默认值,否则写缺失行),relation 标记 `reservation_heuristic`(前端四语言展示「待人工确认」)并发审计事件 `reservation_heuristic_applied`;**多候选** → 复用 `supplement_field_conflict` 冲突结构转现有字段冲突裁决面板,绝不自动挑值,发审计事件 `reservation_heuristic_ambiguous`;**零候选** → 维持现状(缺失阻断提示不变)。本兜底是「不扫描任意单元格猜 Reservation ID」红线唯一放开的例外,仅限 EML 正文表格;PDF/附件文档仍严格走模板/Schema 契约。一期全局启用、不做按客户配置,误判率经上述审计事件观察后再收敛。
**`llm_extraction` 回退语义(2026-08-01)**:订单字段标记为 `llm_extraction` 表示“确定性解析无法取值时允许 LLM 补充”,不表示必须使用 LLM。通用解析门禁应依据字段是否已有完整、无冲突的确定性证据裁决;已取得必填 Header/Line 值时可直通,缺失时由 `required_field_missing` 转入 LLM/人工复核。
验收标准:四语言文案完整;前端 `npm run build` 通过;业务按钮只消费后端允许动作;对象版本冲突可见;普通用户无法进入模板治理或全局审计;页面不展示虚假百分比或内部 Workflow/Job/Provider 细节。
@@ -766,7 +770,7 @@ export / exportable_snapshot_line_ids)无论库存状态一律剔除结案行
> **历史归档说明(2026-07-28,2026-07-31 纠偏)**:下列阶段 1–5 及 L5-L7 的 Manifest/`orders` 描述记录了 2026-07-21 的旧订单抽取 Workflow 设计,已经失效。订单抽取 Run 不调用该 Workflow;当前 Dify 只在同一 `shipping_notice` Chatflow 的人工字段复核分支接收 `order-review-llm.v1` 最小证据请求。历史段落仅用于审计设计演进,禁止作为画布配置依据。
**阶段 1 历史结论(2026-07-21)**:Run 锁定版本的完整 `definition_json` 已成为确定性订单表格解析的唯一业务配置来源。解析器只使用已启用字段的 `field_code + display_name + aliases` 编译冻结表头契约,不再维护业务别名常量,不读取当前 published 版本,也不在缺少契约时猜测表头。保存草稿和发布版本都会拒绝标准化后跨字段别名碰撞,并拒绝把 Allocation ID、Parent Allocation ID、Commodity Group ID、Supplier Code、UUID、Internal ID 配置为 Reservation ID 表头。同一字段命中多列时不静默选首列,而是记录 `deterministic_table_issues` 并进入复核。后端不再扫描任意单元格猜 Reservation ID,不把文档级 Reservation 广播到所有明细行,也不会为 Schema 未启用的 UOM、币种、金额等字段注入默认值或派生值。冻结的 retired 版本继续按自身别名解析,上传预处理若在任务边界选择当前 published Schema,也只生成提示,不替代正式 Run 的冻结真值。
**阶段 1 历史结论(2026-07-21)**:Run 锁定版本的完整 `definition_json` 已成为确定性订单表格解析的唯一业务配置来源。解析器只使用已启用字段的 `field_code + display_name + aliases` 编译冻结表头契约,不再维护业务别名常量,不读取当前 published 版本,也不在缺少契约时猜测表头。保存草稿和发布版本都会拒绝标准化后跨字段别名碰撞,并拒绝把 Allocation ID、Parent Allocation ID、Commodity Group ID、Supplier Code、UUID、Internal ID 配置为 Reservation ID 表头。同一字段命中多列时不静默选首列,而是记录 `deterministic_table_issues` 并进入复核。后端不再扫描任意单元格猜 Reservation ID(**2026-10-14 修订**:唯一放开的例外是 EML 正文无表头时的「预约单号裸数字兜底」,见下方专段;模板专区之外的 PDF/附件单元格仍禁止猜测),不把文档级 Reservation 广播到所有明细行,也不会为 Schema 未启用的 UOM、币种、金额等字段注入默认值或派生值。冻结的 retired 版本继续按自身别名解析,上传预处理若在任务边界选择当前 published Schema,也只生成提示,不替代正式 Run 的冻结真值。
**Reservation ID 专用证据区域(2026-08-25)**:管理员在同一模板画布圈选唯一的 `reservation_id_region`(区域坐标与页码),不配置 JSON、来源映射、拆分规则或 Header/Line 归属。后端只从该区域内带 `Reservation` 语义的 5/10 位数字提取候选:无行号的值写入 `header.reservation_id`,并由既有有效值规则作为所有未覆盖明细的默认 Reservation;`Line N` / `for line N` / `L#N` 的值按 Customer PO 行号(`customer_po_line_no`,LN 列)定位对应逻辑明细并覆盖默认值(**2026-09-16 修订**:此前按"第 N 个逻辑明细"位置写入,LN 非连续——如部分行已拆到其他 PO——时会错配行归属并把存在的行号误报越界;解析行缺少 LN 取值时才回退位置序以兼容无 LN 字段的旧 Schema)。多个不同整单值、同一行不同值、被引用行号不存在或 Schema 未启用行字段时转 Review;普通数量、客户号等无 Reservation 标签数字一律忽略。区域页可不同于明细页,正式解析、画布预览和盲测共用同一解析/归属契约;XFA 拆分规则仍仅负责 datasets 结构取值,不能代替本能力。**带复核原因的确定性订单必须保留(2026-09-16)**:Reservation 专区/行校验触发 `needs_review` 时以 `deterministic` 携带原因码交 STP 裁决,已解析订单继续落 provisional Candidate 供复核台编辑;不得以 `review_required` 丢弃取值导致复核草稿空白。
@@ -1902,7 +1906,7 @@ GET /api/admin/shipping-order-schema/published-contract
- `GET /api/workspace/shipping-tasks?page=1&page_size=10` 由数据库执行排序、总数统计和切片,返回 `{ items, page, page_size, total }`;业务阶段统一由 `ui_state.stage` 投影,接口不再接受 `process_status`。
- 工作台每页展示 10 条任务,筛选或刷新重置为第一页;任务多选、全选和 ZIP 下载只作用于当前页,切页时清空选择,禁止跨页误操作。
- 工作台提供“下载本批次 ZIP”和任务列表显式多选两种入口;多选可全选当前页结果并显示选择数量。
- 后端按当前用户重新解析批次/任务,任一显式任务越权则整体拒绝;单次最多 100 票。
- 后端按当前用户重新解析批次/任务,任一显式任务越权则整体拒绝;单次最多 100 票。下载授权与单票导出同一谓词(`can_download_task_export`:创建者或管理员),成功后按票写 `record_access_audit`(`metadata.export=batch_zip`,manifest entries 携带 `business_no` 供审计聚合)。
- 每票只选择最新且仍与 Task 当前导出路径一致的 `status=ready` Artifact,并在打包前复算 SHA-256;任务纠错清空引用、文件缺失或校验失败均不进入 ZIP 文件区,但必须进入 `manifest.json`。
- manifest 状态为 `included / missing_artifact / missing_file / checksum_mismatch`;同名文件保留首个,其余追加 `task_no`,禁止覆盖。
- ZIP 使用 `SpooledTemporaryFile`:小文件在内存,超过 16 MiB 自动落临时磁盘,由响应结束后释放。
@@ -3968,3 +3972,98 @@ inventory_preparation Gate
- Excel/波次条件零改动:出单仍需人工勾选波次,放行行可勾选资格规则不变(`export.py` / wave 服务 / 满足性聚合未改动)。
- 同名不同义:订单明细表 / 聊天匹配卡的「可用数量」仍是预约匹配语义;prep 工作台新「可用数量」列是料号兜底总量,两处是否统一待产品定。
- 存量 canonical-only 快照行料号兜底不生效(与基线一致)。
## 2026-10-13 候选库存源刷新(人工重取前置:任务级+行级,幂等)
**背景**:多候选订单建单时冻结候选库存源集合;之后管理端补配/新增库存源,存量单的
取数范围(RPA 逐源 / 行级按行候选收窄)与匹配池(候选域过滤)均不会自动纳入新源,
通知准备阶段出现"下拉只有 3 个候选源、重新匹配无法感知新源"的运营阻断
(prod 实例 SORC-E19FE1B9AB8F4FD2)。
**方案(升级不换按钮)**:「重新获取库存(RPA)」(`retry_inventory_preparation`)人工重取前
新增幂等前置刷新,任务级与行级共用守卫红线:
- 任务级(`refresh_candidates_from_current_routing`):重跑 `adjudicate_and_apply_inventory_source`
整单重判候选集。
- 行级(`refresh_line_candidates_from_current_routing`):仅重评目标行——行级规则重评
(`evaluate_inventory_source_rules(task, line)`,候选经理 `get_database_inventory_source`
启停过滤,仅接受 resolved/ambiguous),以活动集全量行为骨架定向替换目标行候选后
`freeze_candidates_for_task` 重冻结,其余行原样继承。
- 两者均幂等:输入指纹未变复用旧集零副作用;有变化生成新 `set_version`,supersede 旧集时
由 `_invalidate_task_candidate_outputs` 内置失效旧匹配事实/准备与 RPA Attempt,随后既有
`invalidate_inventory_downstream` + `ensure_inventory(mode='retry_rpa')` 按新候选重取并重算匹配。
- 守卫:已定源不刷新(任务级冻结候选 ≤1 / 行级目标行候选 ≤1),换源走
`override_line_inventory_source`;候选集含人工选源(frozen_by_id /
candidate_origin='manual_override')不刷新(人工指定即定论);Excel 已生成(D7)不刷新;
轮询/自动首投/`retry_inventory_from_preparation` 不刷新。
- 前端歧义行(source_ambiguous)库存源下拉由"仅候选"改为"候选置顶 + 全部已启用源
去重兜底"(`features/chat/shipping/inlineSourceOptions.ts` 纯函数),与后端覆写
动作"任一已启用源都允许"的既有语义对齐;人工补选新源提交后自动重冻结该行并重匹配。
**审计**:产生新版本时写任务事件 `inventory_candidates_refreshed`
(scope=task:previous_set_id/new_set_id/source_codes;scope=line:line_no/previous_codes/new_codes/new_set_id)。
## 2026-10-13 库存源线索直连(路由引擎内建,优先于全部规则层)
**背景**:`inventory_source_hint`(订单行「库存源线索」,如 BYAWSPRD01)自设计起定位为
可选路由线索(见上文「冻结 Snapshot 路由裁决」),但引擎此前不消费该列,线索只能靠
管理员逐值维护高优先级规则生效;漏配新仓线索时预约单号兜底规则照常参与,产生错误候选。
**实现(fail-open 直连)**:`inventory_routing_engine.py` 行级评估最前置一步——
- 快照路径:`evaluate_inventory_source_rules` 对行级评估自读冻结行强类型列
`ShippingOrderSnapshotLine.inventory_source_hint`(按 `_position` 对齐,同 `_condition_value`);
- Draft 路径:`evaluate_inventory_source_rules_for_field_values` 新增可选入参
`line_source_hint`(`order_build_eligibility_service.project_line_inventory_candidates`
从 `line_by_code['inventory_source_hint']` 传入);
- 解析规则(`_resolve_source_from_hint`):线索归一大写后,启用源中**精确 source_code 相等**
优先,否则**唯一后缀命中**(BYAWSPRD01 → DSV360_AWSBI_BYAWSPRD01);无命中或多命中
返回 None——**fail-open 落回规则层**(含预约单号兜底与逐值线索规则),不以线索阻断流程;
- 命中即返回 `resolved` 单源,evidence `reason='inventory_source_hint'`、`matched_rule_ids`
为空(预约兜底等低层规则不参与);任务级评估(line=None)无线索语义,维持原行为。
**继承链(零额外改动)**:运行时裁决 `adjudicate_inventory_source`、冻结行级候选收集
`_collect_order_line_candidates`、行级候选刷新 `refresh_line_candidates_from_current_routing`
均经行级规则评估自动生效——多行线索不同则按既有语义合并为 ambiguous 并按行钉候选;
订单行后补线索可经「重新获取库存(RPA)」的候选集刷新即时生效。
**边界**:波次行路由(D8 `freeze_wave_notice_routing`)暂未接入(波次行无线索强类型列,
需 field_id 反查,留待后续);线索解析失败不告警不门禁;放行证据的「料号兜底」与此无关。
## 确认客户改绑(2026-10-13)
> 背景:订单复核阶段客户选错后,客户识别面板在 `customer_resolution.resolved` 后整体消失,确认后没有任何改客户入口;任务推进到通知准备后 Excel 生成失败(关联案例 SORC-336EB5E5D6D84CBE:库存行 ODM ID 不在新客户维护范围)。本节记录已实现并过评审的「确认客户改绑」:不重走识别候选打分确认,直接修改已确认的客户识别结果,改完回通知准备重新生成 Excel。
### 交互:客户识别面板两态化(`ReviewCustomerResolutionPanel`)
- **未识别态**(`resolved=false`):行为不变,仍走识别候选确认流程。
- **已识别态**(`resolved=true`):面板默认**折叠为一行摘要条**(状态徽标「已确认」+ 确认客户名 + 展开 chevron + 「修改客户」按钮);展开显示既有识别详情(命中输入/识别依据等历史信息,不展示 ODM 范围)。
- 「修改客户」按钮可用性 = 编辑窗头级谓词(`editable_scope(order_task)['header']`);不满足则禁用 + tooltip 说明("已产生发货通知/Excel,请先走撤销流程")。点击后复用既有客户搜索(`searchCustomers`)选定目标客户 → 二次确认弹窗(明示「将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成」)→ 提交 → 成功 toast → `refreshed` 事件走既有刷新链。
### 守卫:fail-closed 四层(`rebind_confirmed_customer`,顺序固定)
`backend/app/services/shipping_notice/customer_resolution_service.py` 的 `rebind_confirmed_customer`:
1. **版本守卫**:`expected_order_data_version` 必填,与任务当前 `order_data_version` 不一致即 409 `SHIPPING.ORDER_DATA_VERSION_MISMATCH`——守卫期比较,写任何数据之前执行,冲突零副作用(freeze 幂等早退不重复做版本校验,版本比较只在此处)。
2. **已确认**:resolution 行存在且 `status='confirmed'` 且已有确认客户,否则 409 `SHIPPING.CUSTOMER_RESOLUTION_REQUIRED`(未确认走既有确认流程,不在此补确认)。
3. **编辑窗 header 谓词**:`editable_scope(order_task)['header']` 为 True,即该订单任一通知**无 Export Artifact 且无活动 Gate Attempt**;否则 409 `SHIPPING.CUSTOMER_REBIND_BLOCKED`(details 区分 `excel_exists` / `active_attempt`)。
4. **新客户有效**:目标客户存在(`SHIPPING.CUSTOMER_NOT_FOUND`)、启用(`SHIPPING.CUSTOMER_INACTIVE`)且 ≠ 当前确认客户(`SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER`)。
### 写入链(同事务)
1. **更新确认结果**:`confirmed_customer_id` 换新;`evidence_json` 追加 rebind 条目(原/新客户、操作人、原因、时间,保留原识别证据,维持非空契约);`identity_rule_set_checksum` 保留不动(冻结要求非空)。
2. **审计**:同事务写 `review_customer_rebound`(before/after 确认客户 + reason,携带 `review_case_no`;事件已入 `REVIEW_WORKBENCH_AUDIT_EVENT_TYPES`,见 `progress_audit_contract.py`)。
3. **原地刷新快照 + freeze 幂等路径**:`_refresh_frozen_snapshot_customer` 原地刷新快照 `customer_id`/客户简称,随后 `freeze_order_snapshot(mode='manual', actor_id, expected_order_data_version)` 按冻结契约复核——已冻结任务幂等早退返回当前快照。
### API
`POST /api/workspace/shipping-notice/order-review-cases/<case_no>/customer/rebind`,body `{ customer_id, expected_order_data_version, reason? }`,返回刷新后的识别结果与快照投影。
### 零改动项与边界备忘
- **匹配与门禁零触碰**:匹配键=预约单号+料号,与客户无关,不失效匹配、不改门禁状态;守卫保证仅 Excel 未产生时可改绑,改后回通知准备重新生成 Excel;ODM 白名单导出时实时读新客户 `odm_ids`,无需任何配置动作。
- **已放行缺口行的补录证据不随改绑重算**:放行决定仍有效,导出按快照 `release_field_values` 全量字典取值。
- **Excel 表头客户名文字来自单据原文,不随改绑变化**(产品确认项)。
- 预约号是货代侧事实,与客户无关,不重跑预约校验;不做「Excel 已产生后改绑作废重出」模型(守卫直接拒绝)。
### 设计与实施记录
- 设计 spec:[2026-10-13 确认客户改绑设计](../../superpowers/specs/2026-10-13-customer-rebind-design.md);实施计划:[2026-10-13 确认客户改绑计划](../../superpowers/plans/2026-10-13-customer-rebind.md)。
@@ -0,0 +1,143 @@
# 年度教育训练计划需求说明
> **版本**:V1.1
> **更新日期**:2026-10-20
> **状态**:需求已整理,尚未开发。设计方案见 [annual-training-plan-design.md](annual-training-plan-design.md)。可点击原型见 [annual-training-plan-prototype.html](annual-training-plan-prototype.html)。
> **适用范围**:年底年度计划收集、课程库、月度排课、线下签到、线上学习、学员评价与讲师查看、每周一未完成提醒。
本模块与现有新人培训(入职、安全、精益、出国规章)分开。不读取培训配置,不写入 `training_records`。
## 业务流程
主路径是:先有课程和年度计划,讲师排成一场月度培训,再按线上或线下走完,最后学员自己评价、讲师查看。
```mermaid
flowchart TD
course["HR 维护课程"] --> annual["部门负责人提交年度计划"]
yearRemind["12月1日 09:00 提醒未交的负责人"] -.-> annual
annual --> plan{"讲师排月度计划"}
plan -->|"从年度转入,占用一次"| session["确定一场培训"]
plan -->|年度计划外,不占次数| session
session --> mode{"形式"}
mode -->|线下授课| offline["学员到场签到,讲师可补签"]
mode -->|线上学习| online["学员看课件并完成本场考试"]
offline --> review["学员只提交自己的评价"]
online --> review
review --> instructor["讲师查看每人的评价原文"]
offline --> finish["讲师标记完成"]
online --> finish
weekRemind["每周一 09:00 提醒未完成的讲师"] -.-> finish
instructor --> board["HR 看板与导出"]
finish --> board
```
取消的场次不占年度次数,也不进看板、不发周一提醒。线下的纸质签到表仍交给人事。
## 1. 角色
不新增角色,用功能权限区分:
| 身份 | 能做的事 |
| --- | --- |
| 部门负责人 | 维护本主办单位的年度计划。主办单位取 `users.department`。 |
| 讲师 | 新建月度计划,或把本单位年度计划行转成月度计划。可维护课程资料。同一人可以既是部门负责人又是讲师。 |
| 受训人 | 只看到点到自己名字的培训。线上看课件、完成本场考试,并只提交自己的评价。线下到场签到,没有学习链接,课后只提交自己的评价。看不到别人的评价。 |
| HR / 管理员 | 维护课程库、厂区选项、主办单位选项。查看和导出全部计划。不审批。 |
外训只是年度计划上的「内 / 外」标记,不建外部讲师账号。
## 2. 课程与月度计划
同一门课会反复开,所以课程是主数据。年度计划和月度计划都从课程库选择,不在场次里手填一门新课。选课旁边可以「新建课程」,保存后仍写入课程库,并回到刚才的月度计划。
| 内容 | 放在课程 | 放在月度计划 |
| --- | --- | --- |
| 名称、一级分类、二级分类、分类 | 是 | 选择课程。保存时把分类快照下来,以后改课程库不改写已导出的年度计划 |
| 课件、视频、试题 | 是,下次排课继续用 | 只可另附本场补充资料,不写回课程 |
| 是否关联年度计划 | | 是。不关联记为年度计划外,不占年度次数 |
| 日期、时间、时长、讲师、参加人员、地点 | | 是 |
| 线上 / 线下 | | 是。线下可上传本次录制,并做签到。线上由学员在截止日前看课件、考试并评价,不上传录制;需要同步直播时另填会议链接 |
| 发布考试、考试起止时间 | 题目来自课程试题 | 只对这一场发布,成绩记在这一场 |
| 签到 | | 是,只记这一场的点名名单 |
停用课程后不能再被新计划选中,历史计划仍显示原课程名。
## 3. 年度计划
年底收集下一年度计划。部门负责人直接提交,无审批流。时区 Asia/Shanghai。12 月 1 日 09:00 提醒部门负责人,截止 12 月 31 日。逾期仍可提交,标记为逾期提交。
列与 2026 年苏州和信精密《年度教育训练计划》一致,不含培训费用:编号、厂区、主办单位、课程名称、一级分类、二级分类、次数、参加人员、地点、分类、内/外培训。
- 厂区不在用户表上。HR 维护厂区选项,如 1厂、2厂。
- 主办单位来自现有部门字符串,HR 可以补充。
- 参加人员是点名用户,可以跨部门。表格里的「财会人员」「仓储全员」只是对象说明,不代表全部门。
- 年度行不写具体上课日。上课日在月度场次上。
- 一行有稳定编号,便于转成月度计划。同一行最多转出「次数」场。已取消的月度场次不占次数。
## 4. 月度计划状态
| 状态 | 含义 |
| --- | --- |
| 待开课 | 还没到上课结束时间 |
| 已逾期 | 上课结束时间已过,讲师还没标记完成。由时间推算,不单独保存 |
| 已完成 | 讲师标记完成。完成后不再发未完成提醒 |
| 已取消 | 不占年度次数,不能签到,不再提醒 |
签到和完成是两件事。签到只记录谁来了;完成表示这场培训结束。
## 5. 签到
签到记在月度场次上。名单就是这一场已点名的人,一个人一场只有一条记录。
- 仅线下授课签到。上课开始前 30 分钟到结束前,学员自己签到。必须已登录且在名单内,重复点击只算一次。
- 线下由讲师出示二维码。线上不签到,学员看完规定课件记为已学习。
- 过了签到时间,学员不能再自己签。讲师在这场的签到页补签,补签盖过学员自己的结果,并标成补签。
- 已取消的场次不能签到。
人事课现行要求仍然有效:线下签到表使用纸质版,提交给人事。系统里的签到记录不替代这张纸质表。周一提醒的附件里带空白《培训签到表》。
评价线上和线下都有。学员只提交自己的满意度和收获,讲师在这场查看每人原文,不能代填。
## 6. 提醒
两条提醒分开。都走现有企业微信文本卡片和平台排程,同一收件人同一发送日只发一条。
### 6.1 年底收集
12 月 1 日 09:00 发给各部门负责人,请提交下一年度计划,截止 12 月 31 日。
### 6.2 每周一未完成提醒
对齐人事课 2026-10-19 内部邮件《2026年10月教育训练(第三周提醒)》。
- 发送时间:每周一 09:00(北京时间)。
- 收件人:当月仍有待开课或已逾期场次的讲师。已完成、已取消的场次不算。已经约好上课时间、但还没标记完成的讲师也收。
- 抄送:人事课指定收件人,在配置里维护,不写死姓名。
- 周次:按当月周一计数。10 月 19 日是 2026 年 10 月第三个周一,标题为「第三周提醒」。
- 附件:空白《培训签到表》、当月《教育训练登记》。
- 系统只发送提醒。正文中的「同奖同罚」扣讲师费由薪资处理,本模块不计算、不扣款。
- 邮件原文要求在 N8 上传视频和课件。新模块上线后,上传改在本系统的课程和月度场次里完成。纸质签到表仍交人事。
标题:
`{年}年{月}月教育训练(第{周}周提醒)`
正文:
```text
Hi 各位讲师,
上午好!
{月}月已进入第{周}周,附件为{年}年{月}月份的教育训练,请各位讲师提前与人事约定培训时间,并于{月}月内完成系统课件和考试及评价等,感谢!(已预约的讲师作为提醒)
在当月结束时未完成的讲师根据「同奖同罚」会在薪资中扣除相对应的讲师费,请知悉,感谢!
注:请各位讲师在本系统上进行培训以及相关视频、课件的上传,签到表仍需使用纸质版并提交至人事,谢谢。
```
## 7. 本期不做
- 不把出勤率放进培训看板。看板只统计计划次数、已排场次、分类和讲师时长,已取消场次不计入。
- 不执行讲师费扣薪。
- 不把本模块的成绩或资料写入新人培训记录。
- 学员不查看他人评价,也不进入课程库、年度计划和月度计划表。
@@ -0,0 +1,153 @@
# 年度教育训练计划 — 设计方案
| 项目 | 说明 |
| --- | --- |
| 版本 | V1.0(2026-10-19) |
| 状态 | 方案,尚未开发 |
| 需求基线 | [annual-training-plan-demand.md](annual-training-plan-demand.md) |
| 原型 | [annual-training-plan-prototype.html](annual-training-plan-prototype.html) |
本模块是 HXOPS 里的独立业务。复用现有用户、功能权限、企业微信文本卡片、平台排程和 MinIO。不读 `TrainingConfig`,不写 `training_records`,不进入员工培训聊天工作区。
现有应用是 Flask 单体。本模块继续放在这个进程里,用新的 Blueprint 和表,以便直接调用用户、企微和排程。不另起 FastAPI 服务。
## 1. 页面与权限
入口是独立页面「教育训练计划」,页签与原型一致:培训看板、年度计划、课程管理、收集提醒、月度计划。受训人没有这个入口,只打开签到页。
新增三个功能权限,不新增角色。同一个人可以同时拥有部门负责人和讲师权限。
| 权限 | 默认 | 数据范围 |
| --- | --- | --- |
| `edu_plan_dept_manage` | 无,按人授予 | 年度计划仅本 `users.department` |
| `edu_plan_instruct` | 无,按人授予 | 月度计划仅本部门;可维护课程资料 |
| `edu_plan_hr_manage` | 管理员、HR 默认开启 | 课程库、厂区、主办单位选项、全部查看与导出、提醒抄送人 |
主办单位等于部门字符串。厂区不在用户表上,由 HR 维护选项。外训只是年度行上的标记,不建外部账号。
## 2. 数据
新表使用 `edu_plan_` 前缀,配 Alembic 迁移。文件进 MinIO,库里只存对象键和文件名。
```text
edu_plan_course
课程主数据:名称唯一、一级、二级、分类、启用/停用
edu_plan_course_file
挂在课程上。类型 courseware(课件/视频)或 exam(试题)
edu_plan_annual_line
年度计划行。稳定 id、年度、厂区、主办单位、course_id
保存时写入课程名称和分类快照
次数、地点、内/外、对象说明、提交时间
edu_plan_annual_attendee
年度行点名。user_id,可跨部门
edu_plan_session
月度场次。可空的 annual_line_id(空即计划外)
月份、开始、结束、时长、讲师 user_id、主办单位、厂区
形式 online/offline、地点或会议链接
课程名称和分类快照
本场考试:选用哪份课程试题、起止时间
completed_at、cancelled_at
edu_plan_session_file
只属于这场。类型 supplement(补充资料)、recording(线下录制)、evaluation(评价表)
edu_plan_session_attendee
这场点名。从年度行带出,可增删
edu_plan_attendance
一场一人一条。user_id、来源 self/makeup、signed_at
唯一约束 (session_id, user_id)
edu_plan_option
HR 维护的厂区、额外主办单位
edu_plan_notify_log
提醒幂等。event_key 唯一,记录收件人、发送日、结果
```
分类快照写在年度行和场次上。之后改课程库,不回写这两处,导出年度计划读快照。
停用课程后,新建年度行和计划外场次不能再选它。已有行仍显示快照里的课程名。
一场「已排」次数 = 同一 `annual_line_id` 且 `cancelled_at` 为空的场次数。达到年度行的次数后不能再转入。计划外场次不占次数。
场次对外状态不落库:
| 条件 | 状态 |
| --- | --- |
| `cancelled_at` 有值 | 已取消 |
| `completed_at` 有值 | 已完成 |
| 结束时间早于当前时间 | 已逾期 |
| 其余 | 待开课 |
完成只写 `completed_at`。签到人数不影响完成。
## 3. 主流程
### 3.1 年底收集
部门负责人新增年度行:选厂区、选课程、填次数、地点、内/外、对象说明,并点名参加人员。至少 1 人。
12 月 1 日 09:00 的提醒只发给拥有 `edu_plan_dept_manage`、且下一年度还没有本部门计划行的人。12 月 31 日之后提交的行标记逾期,仍然保存。无审批。
### 3.2 月度排课
两条入口:
1. 从年度行转入。复制厂区、主办单位、课程快照、地点、内/外、点名名单。讲师补月份、上课时间、时长、资料和考试。
2. 讲师直接新建。不填年度行,记为计划外。选已有课程;旁边「新建课程」先写入课程库,再回到这场,已填的时间、人员和形式保留。
线上保存会议链接,不接收录制文件。线下保存地点,可上传本次录制。本场补充资料和评价表不写回课程。
考试只是「对本场发布课程里的某一份试题」,并记录起止时间。一期不做在线答题器。成绩由讲师记在这场上。
### 3.3 签到
签到页地址:`/edu-plan/sessions/{id}/check-in`。企业微信卡片和线下二维码都打开这个地址。二维码只在线下场次的签到抽屉里展示。
学员自己签到须同时满足:已登录、在这场点名名单里、当前时间在开始前 30 分钟到结束时间之间、场次未取消。重复提交不新增记录,来源保持 `self`。
讲师或 HR 补签不受这个时间窗口限制。补签把来源改成 `makeup` 并更新 `signed_at`。已取消场次拒绝签到和补签。
纸质《培训签到表》仍由讲师交给人事。系统记录不替代这张表。周一提醒附上空白模板。
## 4. 提醒
两条排程都注册为平台任务,时区 Asia/Shanghai。发送复用 `send_wecom_event_message`。`edu_plan_notify_log.event_key` 唯一,同一收件人同一发送日只发一条。未绑定企业微信的人记失败原因,不改发给别人。
| 任务 | Cron | 收件人 | event_key |
| --- | --- | --- | --- |
| 年底收集 | `0 9 1 12 *` | 尚未提交下一年度计划的部门负责人 | `edu_plan_annual:{年}:{user_id}` |
| 周一未完成 | `0 9 * * 1` | 当月仍有待开课或已逾期场次的讲师;抄送 HR 配置的人事收件人 | `edu_plan_weekly:{周一日期}:{user_id}` |
周一提醒的周次按当月周一计数。2026-10-19 是 10 月第三个周一,标题为「2026年10月教育训练(第三周提醒)」。正文使用需求说明第 6.2 节的固定文字,只替换年、月、周次。
附件两份:空白培训签到表、当月教育训练登记。登记按当月未取消场次导出。已约好上课时间但未标记完成的讲师同样收到。系统不计算、不扣除讲师费。
## 5. 接口与前端
后端 Blueprint 前缀 `/api/edu-plan`。JSON 使用现有 `{ success, data | error, request_id }`。业务失败抛 `AppError`。前端放在 `frontend/src/features/edu-plan/`,HTTP 走 `requestJson`。文案补齐 zh-CN、zh-TW、en、th。
| 接口 | 谁可以调用 |
| --- | --- |
| 课程、厂区、主办单位选项的维护 | HR |
| 课程资料上传 | HR、讲师 |
| 年度行的增改、导出 | 部门负责人限本部门;HR 全部 |
| 场次的增改、完成、取消、补签 | 讲师限本部门;HR 全部 |
| 学员签到 | 名单内的登录用户 |
| 看板 | 按权限过滤后的场次和年度行 |
看板只统计计划次数、已排场次、分类和讲师时长。已取消场次不计入。不出出勤率。
年度导出列:编号、厂区、主办单位、课程名称、一级分类、二级分类、次数、参加人员、地点、分类、内/外培训。不含培训费用。分类和课程名称用快照。
## 6. 本期不做
- 不把成绩、课件写入员工培训。
- 不做学员工作台,不做在线答题器。
- 不执行同奖同罚扣薪。
- 不把系统签到当成已提交给人事的纸质签到表。
@@ -1,9 +1,9 @@
<!doctype html>
<!--
docs/features/training/annual-training-plan-prototype.html
用途:年度计划、月度计划与培训看板的可点击原型。月度计划可由讲师新建,也可从年度计划行转入。
用途:年度计划、课程库、月度计划与培训看板的可点击原型。学员用「我的培训」自己学习或评价;讲师在月度计划里查看每人提交的评价。
依赖:浏览器原生 HTML/CSS/JavaScript,无需构建。图表用内联 SVG,不引入第三方库。
逻辑:角色切换区分 HR、财务部负责人、仓储课讲师;看板统计计划次数、已排场次、分类和讲师时长。
逻辑:角色切换区分 HR、部门负责人、讲师和学员。线上线下都有评价,学员只填自己的,讲师只读查看。
-->
<html lang="zh-CN">
<head>
@@ -28,14 +28,17 @@
.link { border:0; padding:0; color:#175cd3; background:transparent; font-size:12px; font-weight:800; } .names { color:#334155; } .note { color:var(--muted); } .ops { display:flex; gap:10px; white-space:nowrap; } .chips { display:flex; flex-wrap:wrap; gap:6px; margin-top:6px; } .chip { padding:4px 8px; border-radius:99px; background:#f1f5f9; font-size:12px; }
.mask { position:fixed; inset:0; display:none; background:rgba(15,23,42,.35); } .mask.show { display:block; }
.drawer { position:fixed; top:0; right:0; width:min(460px,100%); height:100%; display:flex; flex-direction:column; background:#fff; box-shadow:-12px 0 40px rgba(15,23,42,.12); transform:translateX(100%); transition:.2s; } .drawer.monthly { width:min(560px,100%); } .mask.show .drawer { transform:none; }
.drawer header,.drawer footer { padding:16px 18px; border-bottom:1px solid var(--line); } .drawer footer { border-bottom:0; border-top:1px solid var(--line); display:flex; justify-content:flex-end; gap:8px; } .drawer h2 { margin:0; font-size:16px; } .drawer .body { padding:16px 18px 24px; overflow:auto; } .field { margin-bottom:12px; } .field input,.field select { width:100%; height:36px; } .field textarea { min-height:64px; resize:vertical; } .readonly { display:flex; align-items:center; min-height:36px; padding:8px 10px; border:1px solid #e7edf5; border-radius:8px; color:#334155; background:#f8fafc; }
.drawer header,.drawer footer { padding:16px 18px; border-bottom:1px solid var(--line); } .drawer footer { border-bottom:0; border-top:1px solid var(--line); display:flex; justify-content:flex-end; gap:8px; } .drawer h2 { margin:0; font-size:16px; } .drawer .body { padding:16px 18px 24px; overflow:auto; } .field { margin-bottom:12px; } .field input,.field select { width:100%; height:36px; } .field textarea { width:100%; min-height:64px; resize:vertical; } .readonly { display:flex; align-items:center; min-height:36px; padding:8px 10px; border:1px solid #e7edf5; border-radius:8px; color:#334155; background:#f8fafc; }
.sheet { display:flex; flex-direction:column; gap:16px; } .block { padding:12px; border:1px solid var(--line); border-radius:12px; background:#fbfcfe; } .block h3 { margin:0 0 10px; font-size:13px; } .sheet .field { margin:0; } .pair { display:grid; grid-template-columns:1fr 1fr; gap:10px 12px; } .pair .full { grid-column:1 / -1; } .triple { display:grid; grid-template-columns:1.2fr .8fr .8fr; gap:10px; }
.file-add { display:grid; grid-template-columns:1fr 72px; gap:8px; margin-top:8px; } .chip .x { margin-left:6px; border:0; padding:0; color:#64748b; background:transparent; font-weight:700; }
.course-pick { display:grid; grid-template-columns:1fr auto; gap:8px; align-items:end; } .course-pick .btns { display:flex; gap:8px; } .switch { display:flex; gap:8px; } .switch label { display:flex; align-items:center; gap:6px; height:36px; margin:0; padding:0 12px; border:1px solid #b8c8dd; border-radius:8px; background:#fff; color:var(--ink); font-size:13px; font-weight:600; } .switch input { width:auto; height:auto; }
.people { max-height:220px; overflow:auto; border:1px solid var(--line); border-radius:8px; } .person { display:flex; gap:8px; align-items:center; padding:8px 10px; border-bottom:1px solid var(--line); } .person:last-child { border-bottom:0; } .person small { margin-left:auto; color:var(--muted); }
.qr { width:120px; height:120px; display:grid; grid-template-columns:repeat(7,1fr); gap:3px; padding:8px; border:1px solid var(--line); border-radius:10px; background:#fff; } .qr i { background:#142033; border-radius:1px; } .qr i.off { background:#e8eef6; } .sign-head { display:flex; justify-content:space-between; gap:12px; align-items:center; }
.hint { margin:0 0 8px; color:var(--muted); font-size:12px; }
.two { display:grid; grid-template-columns:1fr 360px; gap:14px; } .phone { width:100%; padding:16px; border-radius:24px; color:#fff; background:#172033; } .phone small { display:block; color:#aab9cc; text-align:center; } .notice { margin-top:12px; overflow:hidden; border-radius:12px; color:var(--ink); background:#fff; } .notice h3 { margin:0; padding:14px 14px 6px; font-size:15px; } .notice p { margin:0; padding:0 14px 14px; white-space:pre-line; color:#3d4b61; font-size:13px; } .notice button { width:100%; padding:11px; border:0; border-top:1px solid var(--line); color:var(--brand); background:#fff; font-weight:800; }
.two { display:grid; grid-template-columns:1fr 360px; gap:14px; } .phone { width:100%; padding:16px; border-radius:24px; color:#fff; background:#172033; } .phone small { display:block; color:#aab9cc; text-align:center; } .notice { margin-top:12px; overflow:hidden; border-radius:12px; color:var(--ink); background:#fff; } .notice h3 { margin:0; padding:14px 14px 6px; font-size:15px; } .notice p { margin:0; padding:0 14px 14px; white-space:pre-line; color:#3d4b61; font-size:13px; } .notice button { width:100%; padding:11px; border:0; border-top:1px solid var(--line); color:var(--brand); background:#fff; font-weight:800; } .notice button:disabled { color:#94a3b8; cursor:not-allowed; }
.kv { display:grid; grid-template-columns:88px 1fr; gap:8px; padding:8px 0; border-bottom:1px solid var(--line); font-size:13px; } .kv b { color:var(--muted); font-weight:700; }
.toast { position:fixed; right:18px; bottom:18px; z-index:5; padding:10px 12px; border-radius:9px; color:#fff; background:#142036; opacity:0; transition:.2s; } .toast.show { opacity:1; }
.learn-wrap { width:min(760px,100%); margin:0 auto; } .learn-wrap h1 { margin:0; font-size:28px; letter-spacing:-.03em; } .mine { display:grid; gap:12px; margin-top:16px; } .mine-card { display:grid; grid-template-columns:1fr auto; gap:12px; align-items:center; padding:18px 18px 16px; border:0; border-radius:18px; background:#fff; box-shadow:0 8px 24px rgba(20,32,51,.06); text-align:left; } .mine-card b { display:block; margin:6px 0 4px; font-size:18px; } .mine-card p { margin:0; color:var(--muted); font-size:13px; } .back { margin-bottom:14px; border:0; padding:0; color:#175cd3; background:transparent; font-weight:800; } .player { display:grid; grid-template-columns:180px 1fr; gap:18px; padding:22px; border-radius:22px; background:#fff; box-shadow:0 8px 24px rgba(20,32,51,.06); } .steps { display:flex; flex-direction:column; gap:8px; margin:0; padding:0; list-style:none; } .steps button { width:100%; padding:10px 12px; border:0; border-radius:12px; color:#334155; background:#f4f7fb; font-weight:800; text-align:left; } .steps button.on { color:#fff; background:#0f766e; } .stage h2 { margin:0 0 8px; font-size:22px; } .file-row { display:flex; justify-content:space-between; gap:8px; align-items:center; margin-top:8px; padding:12px 14px; border-radius:12px; background:#f4f7fb; } .choices { display:flex; gap:8px; margin:12px 0; } .choices button { flex:1; padding:14px 8px; border:1px solid var(--line); border-radius:14px; background:#fff; font-weight:800; } .choices button.on { border-color:#0f766e; color:#fff; background:#0f766e; } .eval-only { padding:28px 24px; border-radius:22px; background:#fff; box-shadow:0 8px 24px rgba(20,32,51,.06); } .stage textarea,.eval-only textarea { width:100%; min-height:96px; padding:10px; border:1px solid #b8c8dd; border-radius:12px; resize:vertical; } .eval-only h2 { margin:8px 0; font-size:26px; } .facts { display:grid; gap:6px; margin:0 0 16px; color:#334155; } .quotes { display:grid; gap:10px; } .quote { padding:12px 14px; border-radius:12px; background:#f8fafc; } .quote p { margin:6px 0 0; } @media (max-width:700px) { .player { grid-template-columns:1fr; } }
.charts { display:grid; gap:12px; margin-bottom:12px; } .charts.two { grid-template-columns:1fr 1fr; } .charts.three { grid-template-columns:1fr 1fr 1fr; }
.chart-hd { display:flex; justify-content:space-between; gap:8px; align-items:flex-start; padding:12px 14px 0; } .chart-hd h2 { margin:0; font-size:14px; } .chart-hd p { margin:3px 0 0; color:var(--muted); font-size:12px; }
.chart-bd { padding:4px 8px 10px; } .chart-bd svg { display:block; width:100%; height:auto; }
@@ -45,7 +48,7 @@
</head>
<body>
<header class="top">
<div><b>教育训练计划</b><small>原型 · 年度收集与月度排课</small></div>
<div><b>教育训练计划</b><small id="brandSub">原型 · 年度收集与月度排课</small></div>
<nav class="tabs" id="tabs">
<button class="active" data-v="board">培训看板</button>
<button data-v="annual">年度计划</button>
@@ -58,6 +61,7 @@
<option value="hr">HR · 全部主办单位</option>
<option value="dept">部门负责人 · 财务部</option>
<option value="teacher">讲师 · 仓储课</option>
<option value="student">学员 · 吴凯</option>
</select>
</label>
</header>
@@ -112,11 +116,11 @@
<section class="view" id="v-courses">
<div class="hero">
<div><h1>课程管理</h1><p>课程可被多个年度、多个主办单位重复选用。停用后不能进入新计划,已引用的计划仍保留。</p></div>
<div><h1>课程管理</h1><p>课程可重复开课。课件、视频和试题放在课程上,下次排课继续用。</p></div>
<button class="btn primary" id="addCourse">新增课程</button>
</div>
<article class="card"><div class="workbook"><table>
<thead><tr><th>课程名称</th><th>一级分类</th><th>二级分类</th><th>分类</th><th>状态</th><th>被计划引用</th><th></th></tr></thead>
<thead><tr><th>课程名称</th><th>一级分类</th><th>二级分类</th><th>分类</th><th>课件</th><th>试题</th><th>状态</th><th>被计划引用</th><th></th></tr></thead>
<tbody id="courseRows"></tbody>
</table></div></article>
</section>
@@ -131,29 +135,44 @@
逾期仍可补交,将标记为逾期提交。</p><button id="goFill">去填写年度计划</button></div></div>
<article class="card"><div class="hd" style="padding:14px 16px 0"><h2 style="margin:0;font-size:14px">发送规则</h2></div><div style="padding:8px 16px 16px">
<div class="kv"><b>对象</b><span>各主办单位的部门负责人</span></div>
<div class="kv"><b>之后</b><span>部门提交年度计划后,讲师在「月度计划」里排课。开课提醒和出勤不在本原型。</span></div>
<div class="kv"><b>之后</b><span>部门提交年度计划后,讲师在「月度计划」里排课。未完成场次每周一 09:00 提醒讲师。</span></div>
<div class="kv"><b>进度</b><span>HR 在年度计划页看到未提交 / 已提交 / 逾期提交</span></div>
</div></article>
</div>
</section>
<section class="view" id="v-learn">
<div class="learn-wrap" id="learnRoot"></div>
</section>
<section class="view" id="v-monthly">
<div class="hero">
<div>
<h1>月度计划</h1>
<p id="monthlyDesc">讲师创建。从年度计划转入时带出课程、地点和已选人员;直接新建的记为计划外。</p>
<p id="monthlyDesc">选课程库里的课。线上、线下都在这里排;本次录制只用于线下。</p>
</div>
<div>
<button class="btn" id="convertMonthly">从年度计划转入</button>
<button class="btn primary" id="createMonthly">新建月度计划</button>
</div>
</div>
<article class="card" style="margin-bottom:12px">
<div class="two" style="align-items:start;padding:14px 16px">
<div>
<h2 style="margin:0;font-size:14px">本月未完成提醒</h2>
<p class="hint" id="remindHint" style="margin-top:6px"></p>
<div id="remindRules"></div>
<div id="remindList" style="margin-top:8px"></div>
</div>
<div class="phone"><small>企业微信 · 发给讲师</small><div id="remindPhone"></div></div>
</div>
</article>
<article class="card filters">
<label>月份<select id="monthFilter"><option value="">全部</option><option>2026-02</option><option>2026-03</option><option>2026-04</option><option>2026-05</option><option>2026-06</option><option>2026-07</option><option>2026-08</option><option>2026-09</option><option>2026-10</option><option>2026-11</option></select></label>
<label>主办单位<select id="monthUnit"></select></label>
</article>
<article class="card"><div class="workbook"><table>
<thead><tr><th>月份</th><th>来源</th><th>课程</th><th>主办单位</th><th>上课时间</th><th>时长</th><th>讲师</th><th>资料</th><th>参加人员</th><th>状态</th><th></th></tr></thead>
<thead><tr><th>月份</th><th>来源</th><th>课程</th><th>形式</th><th>主办单位</th><th>时间</th><th>讲师</th><th>本场补充</th><th>录制</th><th>考试</th><th>签到 / 学习</th><th>状态</th><th></th></tr></thead>
<tbody id="monthRows"></tbody>
</table></div></article>
</section>
@@ -238,12 +257,60 @@
{ id:12, annualNo:15, month:'2026-11', unit:'仓储课', plant:'1厂', course:'ERP 基本操作', place:'教育训练室', side:'内', start:'2026-11-05T09:00', end:'2026-11-05T11:00', hours:'2', instructor:'郑兰', files:['ERP入门.pdf'], ids:warehouse.slice(), status:'scheduled' }
];
const instructors = ['王敏','赵琳','吴凯','郑兰'];
const courseAssets = {
'叉车安全操作规范': { files: ['叉车操作规范.mp4'], exams: ['叉车安全试题.pdf'] },
'ERP 基本操作': { files: ['ERP入门.pdf'], exams: ['ERP操作试题.pdf'] },
'应收系统账务处理操作': { files: ['应收操作.pptx'], exams: [] },
'化学品操作规范': { files: ['化学品规范.mp4'], exams: ['化学品试题.pdf'] }
};
/**
* 取课程上的课件和试题。没有则建空记录,避免月度计划读到空指针。
* @param {string} name 课程名称
* @returns {{files: string[], exams: string[]}}
*/
function assetsOf(name) {
if (!courseAssets[name]) courseAssets[name] = { files: [], exams: [] };
return courseAssets[name];
}
monthlies.forEach((item) => {
item.mode = 'offline';
item.recording = '';
item.examOn = false;
item.examPaper = '';
item.examFrom = '';
item.examTo = '';
item.files = [];
});
Object.assign(monthlies[0], { recording: '叉车现场录制.mp4', examOn: true, examPaper: '叉车安全试题.pdf', examFrom: '2026-03-12 16:00', examTo: '2026-03-19 18:00' });
Object.assign(monthlies[1], { mode: 'online', place: '', deadline: '2026-03-31', liveOn: false, files: ['本场补充说明.pdf'], examOn: true, examPaper: 'ERP操作试题.pdf', examFrom: '2026-03-01', examTo: '2026-03-31' });
const PROTO_TODAY = '2026-06-18T09:00';
monthlies.forEach((item) => {
if (item.mode !== 'online' && item.end < '2026-06-01') item.status = 'done';
});
const attendance = {
1: { wu: 'self', zheng: 'self', feng: 'makeup' },
3: { wang: 'self', li: 'self', zhao: 'self' },
6: { wang: 'self', li: 'self', zhao: 'self' }
};
const learning = {
1: {
wu: { learned: false, exam: false, review: true, score: '满意', note: '现场演示清楚,急停位置记住了' },
zheng: { learned: false, exam: false, review: true, score: '一般', note: '场地有点吵,后半段听不清' }
},
2: { wu: { learned: true, exam: true, review: true, score: '满意', note: '能自己过一遍入库单了' }, zheng: { learned: true, exam: false, review: false, score: '', note: '' } }
};
const LEARNER_ID = 'wu';
let learnFocus = null;
let role = 'hr';
let drawerMode = '';
let editingNo = 0;
let editingCourse = '';
let editingMonthly = 0;
let attendingId = 0;
let draftFiles = [];
let draftCourseFiles = [];
let draftCourseExams = [];
let monthlyDraft = null;
const courseOf = (name) => courses.find((item) => item[0] === name);
const personName = (id) => (people.find((item) => item.id === id) || {}).name || id;
const toast = (message) => { $('toast').textContent = message; $('toast').classList.add('show'); setTimeout(() => $('toast').classList.remove('show'), 2200); };
@@ -304,8 +371,9 @@
$('tabCourses').style.display = role === 'hr' ? '' : 'none';
$('courseRows').innerHTML = courses.map((item) => {
const used = plans.filter((plan) => plan.course === item[0]).length;
const asset = assetsOf(item[0]);
const status = item[4] === 'enabled' ? '<span class="badge green">启用</span>' : '<span class="badge gray">停用</span>';
return '<tr><td><b>' + item[0] + '</b></td><td>' + item[1] + '</td><td>' + item[2] + '</td><td>' + item[3] + '</td><td>' + status + '</td><td>' + used + '</td><td><button class="link" data-course="' + item[0] + '">编辑</button></td></tr>';
return '<tr><td><b>' + item[0] + '</b></td><td>' + item[1] + '</td><td>' + item[2] + '</td><td>' + item[3] + '</td><td>' + (asset.files.length ? asset.files.length + ' 份' : '—') + '</td><td>' + (asset.exams.length ? asset.exams.length + ' 套' : '—') + '</td><td>' + status + '</td><td>' + used + '</td><td><button class="link" data-course="' + item[0] + '">编辑</button></td></tr>';
}).join('');
}
@@ -410,7 +478,7 @@
$('boardKpis').innerHTML = [
[submittedNames + '/' + unitTotal, '已提交主办单位'],
[periodSessions.length + ' / ' + planTimes, month ? '本月已排 / 全年计划次数' : '已排场次 / 计划次数'],
[String(outside), '计划外场次'],
[String(outside), '年度计划外'],
[String(peopleCount), '计划受训人次']
].map(([value, label]) => '<article class="card metric"><b>' + value + '</b><span>' + label + '</span></article>').join('');
const months = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月'];
@@ -439,7 +507,78 @@
}
/**
* 渲染月度计划。已取消场次仍展示,但不计入年度已排次数。
* 计算月度场次对外展示的状态。已逾期不单独落库,由上课结束时间相对原型日期推出来。
* @param {{status: string, end: string}} item 月度计划
* @returns {'cancelled'|'done'|'overdue'|'scheduled'}
*/
function sessionState(item) {
if (item.status === 'cancelled') return 'cancelled';
if (item.status === 'done') return 'done';
if (item.mode === 'online') {
const due = (item.deadline || '').slice(0, 10);
if (due && due < PROTO_TODAY.slice(0, 10)) return 'overdue';
return 'scheduled';
}
if ((item.end || item.start || '') < PROTO_TODAY) return 'overdue';
return 'scheduled';
}
/**
* 状态对应的标签。待开课和已逾期都会进入本月未完成提醒,已完成和已取消不再提醒。
* @param {string} state sessionState 的返回值
* @returns {string}
*/
function stateBadge(state) {
if (state === 'cancelled') return '<span class="badge gray">已取消</span>';
if (state === 'done') return '<span class="badge blue">已完成</span>';
if (state === 'overdue') return '<span class="badge red">已逾期</span>';
return '<span class="badge green">待开课</span>';
}
/**
* 计算某个日期落在当月的第几个周一。6 月 18 日所在周的周一是 6 月 15 日,对应第三周。
* @param {string} iso 原型当前日期
* @returns {string} 中文周次,如「三」
*/
function monthWeekLabel(iso) {
const date = new Date(iso.slice(0, 10) + 'T00:00:00');
const first = new Date(date.getFullYear(), date.getMonth(), 1);
const firstMonday = 1 + ((8 - (first.getDay() || 7)) % 7);
const monday = date.getDate() - ((date.getDay() + 6) % 7);
const index = Math.max(1, Math.floor((monday - firstMonday) / 7) + 1);
return ['一', '二', '三', '四', '五', '六'][index - 1] || String(index);
}
/**
* 渲染本月未完成提醒。每周一 09:00 发给仍有未完成场次的讲师,文案对齐人事课内部邮件。
* @param {string} unit 主办单位筛选,空字符串表示不限
*/
function renderRemind(unit) {
const month = PROTO_TODAY.slice(0, 7);
const monthNum = String(Number(month.slice(5, 7)));
const year = month.slice(0, 4);
const week = monthWeekLabel(PROTO_TODAY);
const open = monthlies.filter((item) => {
const state = sessionState(item);
return item.month === month && (!unit || item.unit === unit) && (state === 'scheduled' || state === 'overdue');
});
const instructors = [...new Set(open.map((item) => item.instructor))];
$('remindHint').textContent = '原型按 ' + PROTO_TODAY.slice(0, 10) + ' 计算。每周一 09:00 发给本月还未完成的讲师。已约好上课时间的也提醒。';
$('remindRules').innerHTML = '<div class="kv"><b>时间</b><span>每周一 09:00(北京时间)。同一讲师同一个周一只发一条。</span></div><div class="kv"><b>对象</b><span>本月仍有待开课或已逾期场次的讲师。已完成、已取消不发。</span></div><div class="kv"><b>抄送</b><span>人事课指定收件人,在配置里维护,不写死姓名。</span></div><div class="kv"><b>附件</b><span>培训签到表.xls、' + year + '年' + monthNum + '月教育训练登记.xls</span></div><div class="kv"><b>扣薪</b><span>正文告知同奖同罚。系统只发提醒,不计算、不扣除讲师费。</span></div>';
$('remindList').innerHTML = open.length ? open.map((item) => {
const state = sessionState(item);
const kind = state === 'overdue' ? '<span class="badge red">已逾期</span>' : '<span class="badge green">待开课</span>';
return '<div class="kv"><b>' + item.instructor + '</b><span>' + kind + ' ' + item.course + ' · ' + item.start.replace('T', ' ') + '</span></div>';
}).join('') : '<p class="hint">本月没有未完成的讲师。</p>';
const title = year + '年' + monthNum + '月教育训练(第' + week + '周提醒)';
const body = instructors.length
? ('Hi 各位讲师,\n上午好!\n\n' + monthNum + '月已进入第' + week + '周,附件为' + year + '年' + monthNum + '月份的教育训练,请各位讲师提前与人事约定培训时间,并于' + monthNum + '月内完成系统课件和考试及评价等,感谢!(已预约的讲师作为提醒)\n\n在当月结束时未完成的讲师根据「同奖同罚」会在薪资中扣除相对应的讲师费,请知悉,感谢!\n\n注:请各位讲师在本系统上进行培训以及相关视频、课件的上传,签到表仍需使用纸质版并提交至人事,谢谢。\n\n收件人:' + instructors.join('、'))
: '本月没有未完成的讲师。';
$('remindPhone').innerHTML = '<div class="notice"><h3>' + title + '</h3><p>' + body + '</p><button type="button" data-remind-month="' + month + '">查看未完成场次</button></div>';
}
/**
* 渲染月度计划。已取消场次仍展示,但不计入年度已排次数。已完成、已逾期由上课时间相对原型日期区分。
*/
function renderMonthly() {
const locked = scopeUnit();
@@ -449,23 +588,284 @@
unitSelect.disabled = Boolean(locked);
unitSelect.value = locked || current;
if (locked) unitSelect.value = locked;
$('monthlyDesc').textContent = locked
? locked + '讲师可新建月度计划,或从本单位未排满的年度计划转入。'
: '讲师创建。从年度计划转入时带出课程、地点和已选人员;直接新建的记为计划外。';
$('monthlyDesc').textContent = (locked ? locked + '的月度计划。' : '') + '线下点「签到」看名单,线上点「学习」看进度。线上和线下都点「评价」,查看学员自己提交的内容。';
const month = $('monthFilter').value;
const unit = locked || unitSelect.value;
const rows = monthlies.filter((item) => (!month || item.month === month) && (!unit || item.unit === unit));
$('monthRows').innerHTML = rows.map((item) => {
const when = (item.start || '').replace('T', ' ') + (item.end ? ' – ' + item.end.slice(11) : '');
const source = item.annualNo ? '<span class="badge blue">年度 #' + item.annualNo + '</span>' : '<span class="badge amber">计划外</span>';
const state = item.status === 'cancelled' ? '<span class="badge gray">已取消</span>' : '<span class="badge green">待开课</span>';
const cancel = item.status === 'cancelled' ? '' : '<button class="link" data-cancel="' + item.id + '">取消</button>';
return '<tr><td>' + item.month + '</td><td>' + source + '</td><td><b>' + item.course + '</b></td><td>' + item.unit + '</td><td>' + when + '</td><td>' + item.hours + ' 小时</td><td>' + item.instructor + '</td><td>' + (item.files.join('、') || '—') + '</td><td class="names">' + item.ids.map(personName).join('、') + '</td><td>' + state + '</td><td><div class="ops"><button class="link" data-medit="' + item.id + '">编辑</button>' + cancel + '</div></td></tr>';
}).join('') || '<tr><td colspan="11" class="hint">这个范围还没有月度计划。</td></tr>';
const when = item.mode === 'online'
? ('截止 ' + (item.deadline || '—') + (item.liveOn && item.place ? '<br><span class="note">直播</span>' : ''))
: ((item.start || '').replace('T', ' ') + (item.end ? ' – ' + item.end.slice(11) : ''));
const source = item.annualNo ? '<span class="badge blue">年度 #' + item.annualNo + '</span>' : '<span class="badge amber">年度计划外</span>';
const state = sessionState(item);
const stateLabel = stateBadge(state);
const done = (state === 'scheduled' || state === 'overdue') ? '<button class="link" data-done="' + item.id + '">完成</button>' : '';
const cancel = (state === 'scheduled' || state === 'overdue') ? '<button class="link" data-cancel="' + item.id + '">取消</button>' : '';
const modeLabel = item.mode === 'online' ? '<span class="badge blue">线上学习</span>' : '<span class="badge gray">线下授课</span>';
const examLabel = item.examOn ? '<span class="badge green">已发布</span>' : '—';
const attendText = state === 'cancelled' ? '—' : (item.mode === 'online'
? '<button class="link" data-learn="' + item.id + '">学习 ' + finishedCount(item) + '/' + item.ids.length + '</button>'
: '<button class="link" data-attend="' + item.id + '">签到 ' + signedCount(item) + '/' + item.ids.length + '</button>');
const reviewLink = state === 'cancelled' ? '' : '<button class="link" data-reviews="' + item.id + '">评价 ' + reviewCount(item) + '/' + item.ids.length + '</button>';
return '<tr><td>' + item.month + '</td><td>' + source + '</td><td><b>' + item.course + '</b></td><td>' + modeLabel + '</td><td>' + item.unit + '</td><td>' + when + '</td><td>' + item.instructor + '</td><td>' + ((item.files || []).join('、') || '—') + '</td><td>' + (item.mode === 'offline' && item.recording ? item.recording : '—') + '</td><td>' + examLabel + '</td><td>' + attendText + '</td><td>' + stateLabel + '</td><td><div class="ops"><button class="link" data-medit="' + item.id + '">编辑</button>' + reviewLink + done + cancel + '</div></td></tr>';
}).join('') || '<tr><td colspan="13" class="hint">这个范围还没有月度计划。</td></tr>';
renderRemind(unit);
}
function openMask(monthly) { document.querySelector('.drawer').classList.toggle('monthly', Boolean(monthly)); $('mask').classList.add('show'); }
function closeMask() { $('mask').classList.remove('show'); document.querySelector('.drawer').classList.remove('monthly'); drawerMode = ''; }
/**
* 取一场的签到记录。没有则建空对象,键是人员 id,值是 self 或 makeup。
* @param {number} id 月度计划 id
* @returns {Record<string, string>}
*/
function attendOf(id) {
if (!attendance[id]) attendance[id] = {};
return attendance[id];
}
/**
* 统计这场名单里已经签到或被补签的人数。
* @param {{id: number, ids: string[]}} item 月度计划
* @returns {number}
*/
function signedCount(item) {
const book = attendOf(item.id);
return item.ids.filter((id) => book[id]).length;
}
/**
* 取一场线上学习进度。每人有课件、考试、评价三项,缺省都是未完成。
* @param {number} id 月度计划 id
* @returns {Record<string, {learned: boolean, exam: boolean, review: boolean}>}
*/
function learnOf(id) {
if (!learning[id]) learning[id] = {};
return learning[id];
}
/**
* 统计课件、考试、评价都完成的人数。
* @param {{id: number, ids: string[]}} item 月度计划
* @returns {number}
*/
function finishedCount(item) {
const book = learnOf(item.id);
return item.ids.filter((id) => { const row = book[id]; return row && row.learned && row.exam && row.review; }).length;
}
/**
* 统计这场已经提交评价的人数。线上和线下都计。
* @param {{id: number, ids: string[]}} item 月度计划
* @returns {number}
*/
function reviewCount(item) {
const book = learnOf(item.id);
return item.ids.filter((id) => book[id] && book[id].review).length;
}
/**
* 判断学员自己签到的窗口。上课开始前 30 分钟到结束前为 open,更早是 before,结束后是 closed。
* @param {{start: string, end: string}} item 月度计划
* @returns {'before'|'open'|'closed'}
*/
function signWindow(item) {
const now = new Date(PROTO_TODAY).getTime();
const openAt = new Date(item.start).getTime() - 30 * 60 * 1000;
const closeAt = new Date(item.end || item.start).getTime();
if (now < openAt) return 'before';
if (now > closeAt) return 'closed';
return 'open';
}
/**
* 打开这场签到抽屉。名单来自月度计划已点名的人;讲师勾选未签到的人后点补签。
* @param {object} item 月度计划
*/
function openAttendance(item) {
if (item.mode === 'online') { openLearning(item); return; }
if (sessionState(item) === 'cancelled') { toast('已取消的场次不能签到'); return; }
drawerMode = 'attend';
attendingId = item.id;
const windowState = signWindow(item);
const windowText = windowState === 'open' ? '学员现在可以自己签到' : (windowState === 'before' ? '未到签到时间,上课前 30 分钟开放' : '签到已截止,只能由讲师补签');
$('drawerTitle').textContent = '签到 · ' + item.course;
$('drawerHint').textContent = '这是讲师的签到名单。学员评价不在这里,回到列表点「评价」。补签会盖过学员自己的签到。';
const qr = item.mode === 'online' ? '' : '<div class="qr" aria-hidden="true">' + '1100111011010111011010110110101011010111011010110'.split('').map((bit) => '<i class="' + (bit === '1' ? '' : 'off') + '"></i>').join('') + '</div>';
const channel = item.mode === 'online'
? '<p class="hint">线上不出示二维码。学员从企业微信卡片进入同一签到页。</p>'
: '<div class="sign-head"><div><p class="hint" style="margin:0">线下由讲师出示此码。扫码打开的是同一签到页。</p></div>' + qr + '</div>';
$('drawerBody').innerHTML = '<div class="sheet"><section class="block"><h3>学员签到</h3><p class="hint">' + windowText + '。' + item.start.replace('T', ' ') + ' – ' + (item.end || '').slice(11) + '</p>' + channel + '<div class="notice"><h3>请签到</h3><p>' + item.course + '\n' + item.start.replace('T', ' ') + '\n' + item.place + '</p><button type="button" id="sign-self"' + (windowState === 'open' ? '' : ' disabled') + '>模拟一名学员签到</button></div></section><section class="block"><h3>名单</h3><p class="hint" id="sign-sum"></p><div class="people" id="sign-list"></div></section></div>';
const paint = () => {
const book = attendOf(item.id);
const rows = item.ids.map((id) => {
const person = people.find((row) => row.id === id) || { name: id, dept: '' };
const mark = book[id];
const badge = mark === 'makeup' ? '<span class="badge amber">补签</span>' : (mark === 'self' ? '<span class="badge green">已签到</span>' : '<span class="badge gray">未签到</span>');
const box = mark ? '' : '<input type="checkbox" value="' + id + '" />';
return '<label class="person">' + box + '<span>' + person.name + '</span>' + badge + '<small>' + person.dept + '</small></label>';
}).join('');
$('sign-list').innerHTML = rows;
$('sign-sum').textContent = '已签到 ' + signedCount(item) + ' / ' + item.ids.length + '。未签到的人可以勾选后补签。';
};
$('sign-self').addEventListener('click', () => {
if (signWindow(item) !== 'open') { toast('现在不能自己签到'); return; }
const book = attendOf(item.id);
const next = item.ids.find((id) => !book[id]);
if (!next) { toast('名单上的人都已签到'); return; }
book[next] = 'self';
paint();
renderMonthly();
toast(personName(next) + ' 已签到');
});
paint();
openMask(true);
$('drawerSave').textContent = '补签';
}
/**
* 打开线上学习进度。讲师只看每人是否学完、考完、评完,不展示课件和评价原文。
* @param {object} item 月度计划
*/
function openLearning(item) {
if (sessionState(item) === 'cancelled') { toast('已取消的场次不能学习'); return; }
drawerMode = 'learn';
attendingId = item.id;
$('drawerTitle').textContent = '学习进度 · ' + item.course;
$('drawerHint').textContent = '这是讲师看的完成进度,只显示做没做完。评价原文在列表「评价」。';
$('drawerBody').innerHTML = '<div class="sheet"><section class="block"><h3>每人进度</h3><p class="hint">截止 ' + (item.deadline || '—') + (item.examOn ? '。本场已发布考试。' : '。本场未发布考试。') + '学员在「我的培训」里自己完成。</p><p class="hint" id="learn-sum"></p><div class="people" id="learn-list"></div></section></div>';
const book = learnOf(item.id);
$('learn-list').innerHTML = item.ids.map((id) => {
const person = people.find((row) => row.id === id) || { name: id, dept: '' };
const row = book[id] || { learned: false, exam: false, review: false };
const badge = (ok, yes, no) => '<span class="badge ' + (ok ? 'green' : 'gray') + '">' + (ok ? yes : no) + '</span>';
return '<div class="person"><span>' + person.name + '</span>' + badge(row.learned, '已学习', '未学习') + badge(row.exam, '已考试', '未考试') + badge(row.review, '已评价', '未评价') + '<small>' + person.dept + '</small></div>';
}).join('');
$('learn-sum').textContent = '全部完成 ' + finishedCount(item) + ' / ' + item.ids.length + '。';
openMask(true);
$('drawerSave').textContent = '关闭';
}
/**
* 讲师查看这一场的评价原文。线上和线下都有,只读,不能代学员填写。
* @param {object} item 月度计划
*/
function openReviews(item) {
if (sessionState(item) === 'cancelled') { toast('已取消的场次没有评价'); return; }
drawerMode = 'learn';
$('drawerTitle').textContent = '评价 · ' + item.course;
$('drawerHint').textContent = '学员只提交自己的评价。这里给讲师看原文,线上和线下都一样。';
const book = learnOf(item.id);
const rows = item.ids.map((id) => {
const row = book[id];
if (!row || !row.review) return '<div class="quote"><b>' + personName(id) + '</b><p class="note">未评价</p></div>';
return '<div class="quote"><b>' + personName(id) + '</b> <span class="badge green">' + (row.score || '已评价') + '</span><p>' + (row.note || '未填写收获') + '</p></div>';
}).join('');
$('drawerBody').innerHTML = '<div class="sheet"><section class="block"><h3>已提交 ' + reviewCount(item) + ' / ' + item.ids.length + '</h3><div class="quotes">' + rows + '</div></section></div>';
openMask(true);
$('drawerSave').textContent = '关闭';
}
/**
* 学员自己的培训页。线上进入学习(课件、考试,最后自己评价);线下只有评价,没有学习链接。
*/
function renderLearner() {
const mine = monthlies.filter((item) => item.ids.includes(LEARNER_ID) && sessionState(item) !== 'cancelled');
const root = $('learnRoot');
if (!learnFocus) {
root.innerHTML = '<h1>' + personName(LEARNER_ID) + ',你好</h1><p class="hint">只显示点到你名字的培训。线上去学习,线下只评价。评价只有你自己能填,讲师能看到你写的内容。</p><div class="mine">' + mine.map((item) => {
const online = item.mode === 'online';
const row = learnOf(item.id)[LEARNER_ID] || {};
const when = online ? ('请在 ' + (item.deadline || '—') + ' 前完成') : ((item.start || '').replace('T', ' ') + ' · ' + (item.place || ''));
const action = online ? '去学习' : (item.end < PROTO_TODAY ? (row.review ? '查看评价' : '去评价') : '课后开放');
return '<button class="mine-card" type="button" data-open-learn="' + item.id + '"><span><span class="badge ' + (online ? 'blue' : 'gray') + '">' + (online ? '线上学习' : '线下授课') + '</span><b>' + item.course + '</b><p>' + when + (row.review ? ' · 已评价' : '') + '</p></span><strong>' + action + '</strong></button>';
}).join('') + '</div>';
return;
}
const item = monthlies.find((row) => row.id === learnFocus.id);
if (!item) { learnFocus = null; renderLearner(); return; }
const online = item.mode === 'online';
const row = learnOf(item.id)[LEARNER_ID] || { learned: false, exam: false, review: false, score: '', note: '' };
if (!online) {
const locked = item.end >= PROTO_TODAY;
root.innerHTML = '<button class="back" type="button" id="learn-back">返回我的培训</button><article class="eval-only"><span class="badge gray">课后评价</span><h2>' + item.course + '</h2><div class="facts"><span>' + (item.start || '').replace('T', ' ') + (item.end ? ' – ' + item.end.slice(11) : '') + '</span><span>' + (item.place || '') + ' · 讲师 ' + item.instructor + '</span><span>这场没有学习链接,也没有课件和考试。</span></div>' + (locked ? '<p class="hint">下课以后才能评价。</p>' : reviewForm(row)) + '</article>';
bindLearner(item, row);
return;
}
const steps = ['课件', '考试', '评价'];
const step = learnFocus.step || '课件';
const asset = assetsOf(item.course);
let stage = '';
if (step === '课件') {
const files = asset.files.concat(item.files || []);
stage = '<h2>课件</h2><p class="hint">看完后标记。截止 ' + (item.deadline || '—') + '</p>' + (files.length ? files.map((name) => '<div class="file-row"><span>' + name + '</span></div>').join('') : '<p class="note">这门课还没有课件</p>') + '<button class="btn primary" id="mark-learned" type="button" style="margin-top:14px">' + (row.learned ? '已看完' : '我已看完') + '</button>';
} else if (step === '考试') {
stage = item.examOn
? '<h2>考试</h2><p class="hint">' + (item.examPaper || '本场考试') + '</p><button class="btn primary" id="mark-exam" type="button">' + (row.exam ? '已提交' : '提交考试') + '</button>'
: '<h2>考试</h2><p class="hint">这场没有考试,直接去评价。</p>';
} else {
stage = '<h2>我的评价</h2><p class="hint">只提交你自己的。讲师能看到这段文字,其他学员看不到。</p>' + reviewForm(row);
}
root.innerHTML = '<button class="back" type="button" id="learn-back">返回我的培训</button><article class="player"><ol class="steps">' + steps.map((name) => '<li><button type="button" data-step="' + name + '" class="' + (name === step ? 'on' : '') + '">' + name + '</button></li>').join('') + '</ol><div class="stage">' + stage + '</div></article>';
bindLearner(item, row);
}
/**
* 学员评价表。只写自己的满意度和收获。
* @param {{review?: boolean, score?: string, note?: string}} row 当前学员记录
* @returns {string}
*/
function reviewForm(row) {
const score = row.score || '满意';
const choices = ['满意', '一般', '不满意'].map((name) => '<button type="button" data-score="' + name + '" class="' + (score === name ? 'on' : '') + '">' + name + '</button>').join('');
return '<div class="choices" id="score-picks">' + choices + '</div><textarea id="my-note" placeholder="写下这次收获">' + (row.note || '') + '</textarea><button class="btn primary" id="save-review" type="button" style="margin-top:12px">' + (row.review ? '已提交,可修改' : '提交评价') + '</button>';
}
/**
* 绑定学员页上的返回、步骤和学习动作。
* @param {object} item 月度计划
* @param {object} row 当前学员记录
*/
function bindLearner(item, row) {
const book = learnOf(item.id);
const ensure = () => {
if (!book[LEARNER_ID]) book[LEARNER_ID] = { learned: false, exam: false, review: false, score: '满意', note: '' };
return book[LEARNER_ID];
};
$('learn-back').addEventListener('click', () => { learnFocus = null; renderLearner(); });
document.querySelectorAll('[data-step]').forEach((button) => button.addEventListener('click', () => { learnFocus.step = button.dataset.step; renderLearner(); }));
const learned = $('mark-learned');
if (learned) learned.addEventListener('click', () => { ensure().learned = true; renderMonthly(); toast('已看完课件'); renderLearner(); });
const exam = $('mark-exam');
if (exam) exam.addEventListener('click', () => { ensure().exam = true; renderMonthly(); toast('已提交考试'); renderLearner(); });
document.querySelectorAll('[data-score]').forEach((button) => button.addEventListener('click', () => {
document.querySelectorAll('[data-score]').forEach((node) => node.classList.toggle('on', node === button));
}));
const save = $('save-review');
if (save) save.addEventListener('click', () => {
const current = ensure();
const picked = document.querySelector('[data-score].on');
current.review = true;
current.score = picked ? picked.dataset.score : '满意';
current.note = $('my-note').value.trim();
renderMonthly();
toast('评价已提交,讲师可以查看');
renderLearner();
});
}
function openMask(monthly) { $('drawerSave').textContent = '保存'; document.querySelector('.drawer').classList.toggle('monthly', Boolean(monthly)); $('mask').classList.add('show'); }
function closeMask() { $('mask').classList.remove('show'); document.querySelector('.drawer').classList.remove('monthly'); drawerMode = ''; monthlyDraft = null; }
/**
* 关闭抽屉。从月度计划临时去建课程时,取消回到那场,不丢掉已填的时间、人员和形式。
*/
function cancelDrawer() {
if (drawerMode === 'course' && monthlyDraft) {
const draft = monthlyDraft;
monthlyDraft = null;
openMonthly(draft, null);
return;
}
closeMask();
}
/**
* 打开计划行抽屉。分类从课程带出且只读,人员默认不勾选。
@@ -490,16 +890,24 @@
}
/**
* 打开课程抽屉。已有课程改分类不影响已保存计划行的展示快照,原型里用当前课程库直接展示。
* @param {Array<string>|null} course
* 打开课程抽屉。课件和试题记在课程上,供以后的月度计划重复使用。
* 从月度计划点「新建课程」或「编辑课程」进来时,monthlyDraft 里留着未保存的场次,保存或取消后回到那场。
* @param {Array<string>|null} course 为空时是新增
*/
function openCourse(course) {
drawerMode = 'course';
editingCourse = course ? course[0] : '';
const asset = editingCourse ? assetsOf(editingCourse) : { files: [], exams: [] };
draftCourseFiles = editingCourse ? asset.files.slice() : [];
draftCourseExams = editingCourse ? asset.exams.slice() : [];
$('drawerTitle').textContent = course ? '编辑课程' : '新增课程';
$('drawerHint').textContent = '停用后不能被新的年度计划选用。';
$('drawerBody').innerHTML = '<div class="field"><label>课程名称</label><input id="c-name" value="' + (course ? course[0] : '') + '" /></div><div class="field"><label>一级分类</label><input id="c-1" value="' + (course ? course[1] : '') + '" placeholder="专业技能" /></div><div class="field"><label>二级分类</label><input id="c-2" value="' + (course ? course[2] : '') + '" placeholder="职能类" /></div><div class="field"><label>分类</label><input id="c-3" value="' + (course ? course[3] : '知识') + '" /></div><div class="field"><label>状态</label><select id="c-status"><option value="enabled"' + (!course || course[4] === 'enabled' ? ' selected' : '') + '>启用</option><option value="disabled"' + (course && course[4] === 'disabled' ? ' selected' : '') + '>停用</option></select></div>';
openMask();
$('drawerHint').textContent = monthlyDraft ? '保存后回到刚才的月度计划,并选中这门课。' : '课件和试题保存在课程上,下次排课可以继续用。';
const chips = (list, kind) => list.length ? list.map((name, index) => '<span class="chip">' + name + '<button class="x" type="button" data-' + kind + '="' + index + '">×</button></span>').join('') : '<span class="note">还没有</span>';
$('drawerBody').innerHTML = '<div class="sheet"><section class="block"><h3>基本信息</h3><div class="pair"><div class="field full"><label>课程名称</label><input id="c-name" value="' + (course ? course[0] : '') + '" /></div><div class="field"><label>一级分类</label><input id="c-1" value="' + (course ? course[1] : '') + '" placeholder="专业技能" /></div><div class="field"><label>二级分类</label><input id="c-2" value="' + (course ? course[2] : '') + '" placeholder="职能类" /></div><div class="field"><label>分类</label><input id="c-3" value="' + (course ? course[3] : '知识') + '" /></div><div class="field"><label>状态</label><select id="c-status"><option value="enabled"' + (!course || course[4] === 'enabled' ? ' selected' : '') + '>启用</option><option value="disabled"' + (course && course[4] === 'disabled' ? ' selected' : '') + '>停用</option></select></div></div></section><section class="block"><h3>课件 / 视频</h3><div class="chips" id="c-files">' + chips(draftCourseFiles, 'cfile') + '</div><div class="file-add"><input id="c-file" placeholder="如 操作规范.mp4" /><button class="btn" id="c-add-file" type="button">添加</button></div></section><section class="block"><h3>试题</h3><div class="chips" id="c-exams">' + chips(draftCourseExams, 'cexam') + '</div><div class="file-add"><input id="c-exam" placeholder="如 安全试题.pdf" /><button class="btn" id="c-add-exam" type="button">添加</button></div></section></div>';
const paintCourseFiles = () => { $('c-files').innerHTML = chips(draftCourseFiles, 'cfile'); $('c-exams').innerHTML = chips(draftCourseExams, 'cexam'); };
$('c-add-file').addEventListener('click', () => { const name = $('c-file').value.trim(); if (!name) return; draftCourseFiles.push(name); $('c-file').value = ''; paintCourseFiles(); });
$('c-add-exam').addEventListener('click', () => { const name = $('c-exam').value.trim(); if (!name) return; draftCourseExams.push(name); $('c-exam').value = ''; paintCourseFiles(); });
openMask(true);
}
/**
@@ -513,24 +921,58 @@
return;
}
drawerMode = 'monthly';
editingMonthly = record ? record.id : 0;
editingMonthly = record && record.id ? record.id : 0;
const source = annual || (record && record.annualNo ? plans.find((item) => item.no === record.annualNo) : null);
draftFiles = (record ? record.files : []).slice();
$('drawerTitle').textContent = record ? '编辑月度计划' : (source ? '从年度计划转入' : '新建月度计划');
$('drawerHint').textContent = source ? '来自年度计划 #' + source.no + '。上课时间和资料由讲师填写。' : '未关联年度计划,保存后记为计划外。';
draftFiles = (record && record.files ? record.files : []).slice();
$('drawerTitle').textContent = editingMonthly ? '编辑月度计划' : (source ? '从年度计划转入' : '新建月度计划');
$('drawerHint').textContent = source ? '来自年度计划 #' + source.no + '。课程沿用年度计划,不能在这里改成另一门。' : '选「年度计划外」时不占年度次数。课程从课程库选择。';
const selected = new Set(record ? record.ids : (source ? source.ids : []));
const courseName = record ? record.course : (source ? source.course : '');
const courseOptions = courses.filter((item) => item[4] === 'enabled' || item[0] === courseName).map((item) => '<option' + (item[0] === courseName ? ' selected' : '') + '>' + item[0] + '</option>').join('');
const annualOptions = '<option value="0">不关联,记为计划外</option>' + visiblePlans().map((item) => '<option value="' + item.no + '"' + (source && source.no === item.no ? ' selected' : '') + '>#' + item.no + ' ' + item.course + '(已排 ' + scheduledCount(item.no) + '/' + item.times + ')</option>').join('');
const annualOptions = '<option value="0">年度计划外</option>' + visiblePlans().map((item) => '<option value="' + item.no + '"' + (source && source.no === item.no ? ' selected' : '') + '>#' + item.no + ' ' + item.course + '(已排 ' + scheduledCount(item.no) + '/' + item.times + ')</option>').join('');
const unitName = record ? record.unit : (source ? source.unit : (scopeUnit() || '财务部'));
const classDate = record && record.start ? record.start.slice(0, 10) : '';
const startTime = record && record.start ? record.start.slice(11, 16) : '09:00';
const endTime = record && record.end ? record.end.slice(11, 16) : '10:00';
const courseField = source
? '<div class="readonly" id="m-course">' + courseName + '</div>'
: '<select id="m-course">' + courseOptions + '</select>';
$('drawerBody').innerHTML = '<div class="sheet"><section class="block"><h3>课程</h3><div class="pair"><div class="field full"><label>来源</label><select id="m-source"' + (record ? ' disabled' : '') + '>' + annualOptions + '</select></div><div class="field full"><label>课程</label>' + courseField + '</div><div class="field"><label>主办单位</label><div class="readonly" id="m-unit">' + unitName + '</div></div><div class="field"><label>地点</label><input id="m-place" value="' + (record ? record.place : (source ? source.place : '教育训练室')) + '" /></div><div class="field full"><label>讲师</label><select id="m-instructor">' + instructors.map((name) => '<option' + ((record ? record.instructor : instructors[0]) === name ? ' selected' : '') + '>' + name + '</option>').join('') + '</select></div></div></section><section class="block"><h3>上课时间</h3><div class="triple"><div class="field"><label>日期</label><input id="m-date" placeholder="2026-04-09" value="' + classDate + '" /></div><div class="field"><label>开始</label><input id="m-start-time" placeholder="09:00" value="' + startTime + '" /></div><div class="field"><label>结束</label><input id="m-end-time" placeholder="10:00" value="' + endTime + '" /></div></div><div class="field" style="margin-top:10px"><label>时长(小时)</label><input id="m-hours" value="' + (record ? record.hours : '1') + '" /></div><p class="hint" style="margin-top:8px">日期用 2026-04-09,时间用 09:00。填完开始和结束会自动算时长,仍可手改。</p></section><section class="block"><h3>课件 / 视频</h3><div class="chips" id="m-files"></div><div class="file-add"><input id="m-file" placeholder="文件名,如 课件.pdf" /><button class="btn" id="m-add-file" type="button">添加</button></div></section><section class="block"><h3>参加人员</h3><p class="hint">默认带出年度计划已选人员,可按这一场增删。</p><div class="people" id="m-people">' + people.map((item) => '<label class="person"><input type="checkbox" value="' + item.id + '"' + (selected.has(item.id) ? ' checked' : '') + ' /><span>' + item.name + '</span><small>' + item.dept + '</small></label>').join('') + '</div></section></div>';
const courseField = '<select id="m-course"' + (source ? ' disabled' : '') + '>' + courseOptions + '</select>';
const mode = record && record.mode === 'online' ? 'online' : 'offline';
const deadlineValue = record && record.deadline ? record.deadline : '';
const liveOn = Boolean(record && record.liveOn);
const newCourseBtn = '<button class="btn" id="m-new-course" type="button"' + (source ? ' style="display:none"' : '') + '>新建课程</button>';
$('drawerBody').innerHTML = '<div class="sheet"><section class="block"><h3>课程</h3><div class="pair"><div class="field full"><label>来源</label><select id="m-source"' + (editingMonthly ? ' disabled' : '') + '>' + annualOptions + '</select></div><div class="field full"><label>课程</label><div class="course-pick">' + courseField + '<div class="btns">' + newCourseBtn + '<button class="btn" id="m-edit-course" type="button">编辑课程</button></div></div><div class="chips" id="m-course-files"></div></div><div class="field"><label>主办单位</label><div class="readonly" id="m-unit">' + unitName + '</div></div><div class="field" id="m-place-field"><label id="m-place-label">地点</label><input id="m-place" value="' + (record ? record.place : (source ? source.place : '教育训练室')) + '" /></div><div class="field full"><label>讲师</label><select id="m-instructor">' + instructors.map((name) => '<option' + ((record ? record.instructor : instructors[0]) === name ? ' selected' : '') + '>' + name + '</option>').join('') + '</select></div><div class="field full"><label>形式</label><div class="switch"><label><input type="radio" name="m-mode" value="offline"' + (mode === 'offline' ? ' checked' : '') + '>线下授课</label><label><input type="radio" name="m-mode" value="online"' + (mode === 'online' ? ' checked' : '') + '>线上学习</label></div></div></div></section><section class="block" id="m-class-time"><h3>上课时间</h3><div class="triple"><div class="field"><label>日期</label><input id="m-date" placeholder="2026-04-09" value="' + classDate + '" /></div><div class="field"><label>开始</label><input id="m-start-time" placeholder="09:00" value="' + startTime + '" /></div><div class="field"><label>结束</label><input id="m-end-time" placeholder="10:00" value="' + endTime + '" /></div></div><div class="field" style="margin-top:10px"><label>时长(小时)</label><input id="m-hours" value="' + (record ? record.hours : '1') + '" /></div></section><section class="block" id="m-recording-wrap"><h3>本次录制</h3><p class="hint">仅线下授课。这一场的现场录像,不写入课程。</p><input id="m-recording" placeholder="如 叉车现场录制.mp4" value="' + (record && record.recording ? record.recording : '') + '" /></section><section class="block" id="m-sign-block"><h3>到场签到</h3><p class="hint">仅线下授课。上课前 30 分钟到结束,讲师出示二维码,学员扫码签到,讲师可补签。纸质签到表仍交人事。学员没有学习链接,课后只在「我的培训」里评价。讲师在列表「评价」查看。</p></section><section class="block" id="m-online-block"><h3>线上学习</h3><p class="hint">学员在「我的培训」里看课件、考试,并只提交自己的评价。不用二维码,也不交纸质签到表。讲师在列表「学习」看进度,在「评价」看原文。</p><div class="field"><label>学习截止日</label><input id="m-deadline" placeholder="2026-03-31" value="' + deadlineValue + '" /></div><label class="person" style="margin-top:10px"><input type="checkbox" id="m-live"' + (liveOn ? ' checked' : '') + ' />另加一场同步直播</label><div id="m-live-fields" class="field" style="margin-top:10px"><label>会议链接</label><input id="m-meeting" placeholder="腾讯会议链接" value="' + (liveOn && record ? (record.meeting || record.place || '') : '') + '" /></div></section><section class="block"><h3>本场补充资料</h3><p class="hint">只给这一场用,不写回课程。</p><div class="chips" id="m-files"></div><div class="file-add"><input id="m-file" placeholder="文件名,如 补充说明.pdf" /><button class="btn" id="m-add-file" type="button">添加</button></div></section><section class="block"><h3>本场考试</h3><label class="person"><input type="checkbox" id="m-exam-on"' + (record && record.examOn ? ' checked' : '') + ' />对本场受训人发布考试</label><div id="m-exam-fields" class="pair" style="margin-top:10px"><div class="field full"><label>试题</label><select id="m-exam-paper"></select></div><div class="field"><label>开始</label><input id="m-exam-from" placeholder="2026-04-09 16:00" value="' + (record && record.examFrom ? record.examFrom : '') + '" /></div><div class="field"><label>结束</label><input id="m-exam-to" placeholder="2026-04-16 18:00" value="' + (record && record.examTo ? record.examTo : '') + '" /></div></div><p class="hint">题目来自课程里的试题。成绩记在这一场。</p></section><section class="block"><h3>参加人员</h3><p class="hint">默认带出年度计划已选人员,可按这一场增删。</p><div class="people" id="m-people">' + people.map((item) => '<label class="person"><input type="checkbox" value="' + item.id + '"' + (selected.has(item.id) ? ' checked' : '') + ' /><span>' + item.name + '</span><small>' + item.dept + '</small></label>').join('') + '</div></section></div>';
const paintFiles = () => { $('m-files').innerHTML = draftFiles.length ? draftFiles.map((name, index) => '<span class="chip">' + name + '<button class="x" type="button" data-file="' + index + '">×</button></span>').join('') : '<span class="note">还没有资料</span>'; };
const courseNameNow = () => $('m-course').value;
const paintCourseAssets = () => {
const asset = assetsOf(courseNameNow());
$('m-course-files').innerHTML = asset.files.length ? asset.files.map((name) => '<span class="chip">' + name + '</span>').join('') : '<span class="note">这门课还没有课件,可点「编辑课程」上传</span>';
const current = record && record.examPaper ? record.examPaper : '';
$('m-exam-paper').innerHTML = (asset.exams.length ? asset.exams : ['']).map((name) => '<option' + (name === current ? ' selected' : '') + '>' + (name || '课程还没有试题') + '</option>').join('');
};
const syncMode = () => {
const offline = document.querySelector('input[name="m-mode"]:checked').value === 'offline';
const live = !offline && $('m-live').checked;
$('m-class-time').style.display = offline ? '' : 'none';
$('m-recording-wrap').style.display = offline ? '' : 'none';
$('m-sign-block').style.display = offline ? '' : 'none';
$('m-place-field').style.display = offline ? '' : 'none';
$('m-online-block').style.display = offline ? 'none' : '';
$('m-live-fields').style.display = live ? '' : 'none';
$('m-place-label').textContent = '地点';
};
const syncExam = () => { $('m-exam-fields').style.display = $('m-exam-on').checked ? '' : 'none'; };
const leaveForCourse = (course) => {
monthlyDraft = {
id: editingMonthly, annualNo: Number($('m-source').value || 0), course: courseNameNow(),
unit: $('m-unit').textContent, place: $('m-place').value, instructor: $('m-instructor').value,
start: ($('m-date').value && $('m-start-time').value) ? $('m-date').value + 'T' + $('m-start-time').value : '',
end: ($('m-date').value && $('m-end-time').value) ? $('m-date').value + 'T' + $('m-end-time').value : '',
hours: $('m-hours').value, files: draftFiles.slice(), ids: [...document.querySelectorAll('#m-people input:checked')].map((item) => item.value),
mode: document.querySelector('input[name="m-mode"]:checked').value, recording: $('m-recording').value.trim(),
deadline: $('m-deadline').value.trim(), liveOn: $('m-live').checked, meeting: $('m-meeting').value.trim(),
examOn: $('m-exam-on').checked, examPaper: $('m-exam-paper').value, examFrom: $('m-exam-from').value.trim(), examTo: $('m-exam-to').value.trim()
};
openCourse(course);
};
const syncHours = () => {
const start = ($('m-start-time').value || '').split(':');
const end = ($('m-end-time').value || '').split(':');
@@ -538,11 +980,8 @@
const minutes = (Number(end[0]) * 60 + Number(end[1])) - (Number(start[0]) * 60 + Number(start[1]));
if (minutes > 0) $('m-hours').value = String(Math.round(minutes / 6) / 10);
};
const applySource = () => {
const no = Number($('m-source').value);
const plan = plans.find((item) => item.no === no);
if (!plan || $('m-course').tagName !== 'DIV') return;
$('m-course').textContent = plan.course;
const applySource = (plan) => {
$('m-course').value = plan.course;
$('m-unit').textContent = plan.unit;
$('m-place').value = plan.place;
document.querySelectorAll('#m-people input').forEach((input) => { input.checked = plan.ids.includes(input.value); });
@@ -562,24 +1001,37 @@
});
$('m-start-time').addEventListener('change', syncHours);
$('m-end-time').addEventListener('change', syncHours);
if (!record) $('m-source').addEventListener('change', () => {
if (!$('m-source').disabled) $('m-source').addEventListener('change', () => {
const no = Number($('m-source').value);
if (!no) {
$('drawerHint').textContent = '未关联年度计划,保存后记为计划外。';
$('m-course').disabled = false;
$('m-new-course').style.display = '';
$('drawerHint').textContent = '选「年度计划外」时不占年度次数。课程从课程库选择。';
paintCourseAssets();
return;
}
const plan = plans.find((item) => item.no === no);
if (plan && scheduledCount(plan.no) >= plan.times) { toast('这条年度计划次数已排满'); $('m-source').value = '0'; return; }
$('drawerHint').textContent = '来自年度计划 #' + plan.no + '。上课时间和资料由讲师填写。';
if ($('m-course').tagName === 'DIV') applySource();
else {
$('m-unit').textContent = plan.unit;
$('m-place').value = plan.place;
$('m-course').value = plan.course;
document.querySelectorAll('#m-people input').forEach((input) => { input.checked = plan.ids.includes(input.value); });
}
$('m-course').disabled = true;
$('m-new-course').style.display = 'none';
$('drawerHint').textContent = '来自年度计划 #' + plan.no + '。课程沿用年度计划,不能在这里改成另一门。';
applySource(plan);
paintCourseAssets();
});
$('m-course').addEventListener('change', paintCourseAssets);
if ($('m-new-course')) $('m-new-course').addEventListener('click', () => leaveForCourse(null));
$('m-edit-course').addEventListener('click', () => {
const name = courseNameNow();
if (!name) { toast('请先选择课程'); return; }
leaveForCourse(courseOf(name) || [name, '', '', '知识', 'enabled']);
});
document.querySelectorAll('input[name="m-mode"]').forEach((input) => input.addEventListener('change', syncMode));
$('m-live').addEventListener('change', syncMode);
$('m-exam-on').addEventListener('change', syncExam);
paintFiles();
paintCourseAssets();
syncMode();
syncExam();
openMask(true);
}
@@ -587,28 +1039,50 @@
* 保存抽屉。计划行至少点名 1 人;课程名称不能空;月度计划必须填写上课时间。
*/
function saveDrawer() {
if (drawerMode === 'learn') { closeMask(); return; }
if (drawerMode === 'attend') {
const picked = [...document.querySelectorAll('#sign-list input:checked')].map((item) => item.value);
if (!picked.length) { toast('请勾选要补签的人'); return; }
const book = attendOf(attendingId);
picked.forEach((id) => { book[id] = 'makeup'; });
toast('已补签 ' + picked.length + ' 人');
closeMask();
renderMonthly();
return;
}
if (drawerMode === 'monthly') {
const ids = [...document.querySelectorAll('#m-people input:checked')].map((item) => item.value);
if (!ids.length) { toast('请至少选择 1 名参加人员'); return; }
const offline = document.querySelector('input[name="m-mode"]:checked').value === 'offline';
const classDate = $('m-date').value.trim();
const startTime = $('m-start-time').value.trim();
const endTime = $('m-end-time').value.trim();
if (!/^\d{4}-\d{2}-\d{2}$/.test(classDate) || !/^\d{2}:\d{2}$/.test(startTime) || !/^\d{2}:\d{2}$/.test(endTime)) { toast('日期填 2026-04-09,时间填 09:00'); return; }
const deadline = $('m-deadline').value.trim();
const liveOn = !offline && $('m-live').checked;
if (offline && (!/^\d{4}-\d{2}-\d{2}$/.test(classDate) || !/^\d{2}:\d{2}$/.test(startTime) || !/^\d{2}:\d{2}$/.test(endTime))) { toast('线下授课要填上课日期和时间,如 2026-04-09、09:00'); return; }
if (!offline && !/^\d{4}-\d{2}-\d{2}$/.test(deadline)) { toast('线上学习要填截止日,如 2026-03-31'); return; }
if (liveOn && !$('m-meeting').value.trim()) { toast('勾了同步直播就要填会议链接'); return; }
const annualNo = Number($('m-source').value || 0);
const annual = plans.find((item) => item.no === annualNo);
if (annual && scheduledCount(annual.no) >= annual.times && editingMonthly === 0) { toast('次数已排满'); return; }
const courseEl = $('m-course');
const courseName = $('m-course').value;
if ($('m-exam-on').checked && !assetsOf(courseName).exams.length) { toast('这门课还没有试题,请先点「编辑课程」上传'); return; }
const payload = {
annualNo, month: classDate.slice(0, 7), unit:$('m-unit').textContent,
annualNo, month: (offline ? classDate : deadline).slice(0, 7), unit:$('m-unit').textContent,
plant: annual ? annual.plant : '1厂',
course: courseEl.tagName === 'DIV' ? courseEl.textContent : courseEl.value,
place:$('m-place').value.trim() || '教育训练室', side: annual ? annual.side : '内',
start: classDate + 'T' + startTime, end: classDate + 'T' + endTime, hours:$('m-hours').value || '1',
instructor:$('m-instructor').value, files:draftFiles.slice(), ids, status:'scheduled'
course: courseName,
place: offline ? ($('m-place').value.trim() || '教育训练室') : (liveOn ? $('m-meeting').value.trim() : ''), side: annual ? annual.side : '内',
start: offline ? classDate + 'T' + startTime : '', end: offline ? classDate + 'T' + endTime : '', hours: offline ? ($('m-hours').value || '1') : '',
deadline: offline ? '' : deadline, liveOn,
instructor:$('m-instructor').value, files:draftFiles.slice(), ids, status:'scheduled',
mode: offline ? 'offline' : 'online',
recording: offline ? $('m-recording').value.trim() : '',
examOn: $('m-exam-on').checked, examPaper: $('m-exam-on').checked ? $('m-exam-paper').value : '',
examFrom: $('m-exam-on').checked ? $('m-exam-from').value.trim() : '', examTo: $('m-exam-on').checked ? $('m-exam-to').value.trim() : ''
};
if (editingMonthly) Object.assign(monthlies.find((item) => item.id === editingMonthly), payload);
else monthlies.push({ id: monthlies.reduce((max, item) => Math.max(max, item.id), 0) + 1, ...payload });
toast(editingMonthly ? '已更新月度计划' : (annualNo ? '已从年度计划转入' : '已新建计划外月度计划'));
toast(editingMonthly ? '已更新月度计划' : (annualNo ? '已从年度计划转入' : '已新建年度计划外的月度计划'));
closeMask();
renderPlans();
renderMonthly();
@@ -630,10 +1104,26 @@
const next = [name, $('c-1').value.trim() || '未分类', $('c-2').value.trim() || '未分类', $('c-3').value.trim() || '知识', $('c-status').value];
if (editingCourse) {
const index = courses.findIndex((item) => item[0] === editingCourse);
if (editingCourse !== name) {
courseAssets[name] = courseAssets[editingCourse] || { files: [], exams: [] };
delete courseAssets[editingCourse];
}
plans.forEach((item) => { if (item.course === editingCourse) item.course = name; });
monthlies.forEach((item) => { if (item.course === editingCourse) item.course = name; });
courses[index] = next;
} else if (courses.some((item) => item[0] === name)) { toast('课程名称已存在'); return; }
else courses.push(next);
assetsOf(name).files = draftCourseFiles.slice();
assetsOf(name).exams = draftCourseExams.slice();
if (monthlyDraft) {
const draft = monthlyDraft;
monthlyDraft = null;
draft.course = name;
toast('课程已保存,已回到月度计划');
renderCourses();
openMonthly(draft, null);
return;
}
toast(editingCourse ? '已更新课程' : '已新增课程');
renderCourses();
}
@@ -644,12 +1134,39 @@
}
function go(view) {
if (role === 'student' && view !== 'learn') return;
if (view === 'learn' && role !== 'student') return;
if (view === 'courses' && role !== 'hr') { toast('课程库由 HR 维护'); return; }
document.querySelectorAll('.view').forEach((item) => item.classList.toggle('active', item.id === 'v-' + view));
document.querySelectorAll('#tabs button').forEach((item) => item.classList.toggle('active', item.dataset.v === view));
}
$('role').addEventListener('change', () => { role = $('role').value; if (role !== 'hr' && document.getElementById('v-courses').classList.contains('active')) go('annual'); renderUnitFilter(); renderProgress(); renderPlans(); renderCourses(); renderMonthly(); renderBoard(); });
/**
* 切换身份。学员只看到自己的培训页,讲师和 HR 回到管理页。
*/
function applyRole() {
role = $('role').value;
const student = role === 'student';
$('tabs').style.display = student ? 'none' : '';
$('brandSub').textContent = student ? '学员 · 我的培训' : '原型 · 年度收集与月度排课';
if (student) {
learnFocus = null;
renderLearner();
go('learn');
} else if (document.getElementById('v-learn').classList.contains('active')) {
go('monthly');
} else if (role !== 'hr' && document.getElementById('v-courses').classList.contains('active')) {
go('annual');
}
renderUnitFilter();
renderProgress();
renderPlans();
renderCourses();
renderMonthly();
renderBoard();
}
$('role').addEventListener('change', applyRole);
$('tabs').addEventListener('click', (event) => { const button = event.target.closest('[data-v]'); if (button) go(button.dataset.v); });
$('plant').addEventListener('change', renderPlans);
$('unit').addEventListener('change', renderPlans);
@@ -667,7 +1184,22 @@
$('monthRows').addEventListener('click', (event) => {
const edit = event.target.closest('[data-medit]');
const cancel = event.target.closest('[data-cancel]');
const done = event.target.closest('[data-done]');
const attend = event.target.closest('[data-attend]');
const learn = event.target.closest('[data-learn]');
const reviews = event.target.closest('[data-reviews]');
if (edit) openMonthly(monthlies.find((item) => item.id === Number(edit.dataset.medit)), null);
if (attend) openAttendance(monthlies.find((item) => item.id === Number(attend.dataset.attend)));
if (learn) openLearning(monthlies.find((item) => item.id === Number(learn.dataset.learn)));
if (reviews) openReviews(monthlies.find((item) => item.id === Number(reviews.dataset.reviews)));
if (done) {
const item = monthlies.find((row) => row.id === Number(done.dataset.done));
item.status = 'done';
toast('已标记完成,这场不再提醒');
renderPlans();
renderMonthly();
renderBoard();
}
if (cancel) {
const item = monthlies.find((row) => row.id === Number(cancel.dataset.cancel));
item.status = 'cancelled';
@@ -677,6 +1209,20 @@
renderBoard();
}
});
$('remindPhone').addEventListener('click', (event) => {
const button = event.target.closest('[data-remind-month]');
if (!button) return;
$('monthFilter').value = button.dataset.remindMonth;
renderMonthly();
toast('已筛到 ' + button.dataset.remindMonth + ' 的未完成场次');
});
$('learnRoot').addEventListener('click', (event) => {
const card = event.target.closest('[data-open-learn]');
if (!card) return;
const item = monthlies.find((row) => row.id === Number(card.dataset.openLearn));
learnFocus = { id: item.id, step: item.mode === 'online' ? '课件' : '评价' };
renderLearner();
});
$('monthFilter').addEventListener('change', renderMonthly);
$('monthUnit').addEventListener('change', renderMonthly);
$('createMonthly').addEventListener('click', () => openMonthly(null, null));
@@ -686,9 +1232,21 @@
openMonthly(null, candidate);
});
$('courseRows').addEventListener('click', (event) => { const button = event.target.closest('[data-course]'); if (button) openCourse(courseOf(button.dataset.course)); });
$('drawerCancel').addEventListener('click', closeMask);
$('drawerBody').addEventListener('click', (event) => {
if (drawerMode !== 'course') return;
const file = event.target.closest('[data-cfile]');
const exam = event.target.closest('[data-cexam]');
if (file) draftCourseFiles.splice(Number(file.dataset.cfile), 1);
if (exam) draftCourseExams.splice(Number(exam.dataset.cexam), 1);
if (file || exam) {
const chips = (list, kind) => list.length ? list.map((name, index) => '<span class="chip">' + name + '<button class="x" type="button" data-' + kind + '="' + index + '">×</button></span>').join('') : '<span class="note">还没有</span>';
$('c-files').innerHTML = chips(draftCourseFiles, 'cfile');
$('c-exams').innerHTML = chips(draftCourseExams, 'cexam');
}
});
$('drawerCancel').addEventListener('click', cancelDrawer);
$('drawerSave').addEventListener('click', saveDrawer);
$('mask').addEventListener('click', (event) => { if (event.target === $('mask')) closeMask(); });
$('mask').addEventListener('click', (event) => { if (event.target === $('mask')) cancelDrawer(); });
$('goFill').addEventListener('click', () => { $('role').value = 'dept'; $('role').dispatchEvent(new Event('change')); go('annual'); });
['boardYear','boardMonth','boardPlant','boardUnit'].forEach((id) => $(id).addEventListener('change', renderBoard));
renderUnitFilter(); renderProgress(); renderPlans(); renderCourses(); renderMonthly(); renderBoard();
+14 -3
View File
@@ -48,9 +48,9 @@
| 停留预警规则 | 需求已冻结 | 从第一次进入「使用部门担当」起按自然日累计,直到停表。只监控未归档、有效、可以验收的 OA 资产验收单。再进入仍用第一次写入的 `sbsyrjssj`,不从 0 重计。权威:[features/equipment-acceptance-warning/demand.md](features/equipment-acceptance-warning/demand.md)。 |
| 只读同步 | 已实现 | 平台管理员 `POST /api/equipment-acceptance/sync` 拉取 E10 验收单、流程状态、当前节点和操作人。按 `sfkyzcys`、`sfzfth`、`flowstatus` 3/4/5 标停表;`flowstatus` 为 7、8、99、-99 时记为已撤销并不再提醒。不查询、不保存 `isremark`。不保存 `optgroupid`、`batch_number`、`operate_log_id`。 |
| 停留列表 | 已实现 | 入口与合同付款预警相同:内置 Chat Agent `equipment_acceptance` 替换对话区。有权限的用户看列表和详情,同步按钮只给平台管理员。 |
| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,采购经副理、COO、总经理选择系统用户。发送时刻不在此页,以后由排程 Cron 配置,默认每周五 18:00。 |
| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果和发送时间。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 |
| 四档企业微信升级 | 已实现 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人汇总一条企业微信。停表取消未发送。已发送不撤回、不重发。当前处理人就是当前节点上的 `userid`,不使用 `isremark`。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 |
| 预警配置 | 已实现 | 停留情况旁的「预警配置」页。四档天数默认 30/37/44/51,第 4 轮默认关闭,打开后才通知总经理。采购经副理、COO、总经理选择系统用户。发送时刻不在此页,由排程 Cron 配置,默认每周五 18:00。 |
| 发送记录 | 已实现 | Chat 页签「发送记录」。按验收单和档位列出主送、抄送、结果、Excel 附件和发送时间。发给每位收件人的 Excel 归档后挂在对应行上,点文件名下载。`GET /api/equipment-acceptance/sends`。管理员可立即扫描或发送。 |
| 四档企业微信升级 | 已实现 | 超过 30/37/44/51 天各发一次。担当、直接主管、经副理取当前节点处理人及其上级;采购担当取流程申请人。采购经副理、COO、总经理为可配置固定岗位。每天 06:00 同步并生成待发送,每周五 18:00 按收件人发送一条汇总卡片和一份 Excel 明细。停表取消未发送。已发送不撤回、不重发。当前处理人就是当前节点上的 `userid`,不使用 `isremark`。设计:[features/equipment-acceptance-warning/technical.md](features/equipment-acceptance-warning/technical.md)。 |
## 知识库同步状态校验
@@ -95,6 +95,14 @@
| 意见反馈入库 | 已实现 | 用户在 Workspace/Chat 提交意见后写入 `general_feedbacks`,后台报表可查看 |
| 反馈企业微信群通知 | 已实现 | 反馈入库后通过 `WECOM_FEEDBACK_BOT_WEBHOOK` 即时推送到企业微信群;未配置 webhook 时静默跳过,不影响用户提交 |
## 年度教育训练计划
独立于下方「新人培训 Agent」。需求已整理,尚未开发。
| 功能项 | 状态 | 说明 |
| --- | --- | --- |
| 年度收集、课程库、月度排课、签到与周一提醒 | 已文档化 | 不读写现有 `training_records`。每周一 09:00 提醒当月未完成讲师。需求见 [docs/features/training/annual-training-plan-demand.md](features/training/annual-training-plan-demand.md),设计见 [docs/features/training/annual-training-plan-design.md](features/training/annual-training-plan-design.md),原型见 [docs/features/training/annual-training-plan-prototype.html](features/training/annual-training-plan-prototype.html) |
## 新人培训 Agent
| 功能项 | 状态 | 说明 |
@@ -229,6 +237,9 @@
| **Excel 前保存守卫 + 失效分类重跑(二期 T11/T12)** | 已实现 | 正式字段编辑路径(`task_workflow.update_notice_*`)新增活动 Attempt 守卫(`SHIPPING.EDIT_WINDOW_SYSTEM_BUSY`);失效重跑沿用 Schema `change_effect`:路由字段→`rerun_inventory_source_resolution`、行字段→`rerun_inventory_matching`、导出→`regenerate_excel`、需重解析→`require_revision`;审计含 `applied_effects` 失效动作链。设计 §3.2/§3.3。 |
| **编辑窗前端渲染(二期 T13)** | 已实现 | `ShippingTaskUiState.edit_window` 类型 + `formalHeaderEditable()`/`formalLineEditable(lineKey)`;头字段编辑块按 `edit_window.header` 门控、歧义行源下拉确认按行锁定;四语言 `errors.json` 补 `SHIPPING.EDIT_WINDOW_FIELD_LOCKED/SYSTEM_BUSY`;`npm run build` 通过。 |
| 库存匹配料号兜底自动放行与料号维度可用数量展示(2026-10-09) | 已实现 | 匹配器按料号键二次汇总下发 `part_available_qty`(行允许源内、忽略预约号与单位,跨源不合并;迁移 `0a575f3afc32` 新列,存量行重匹配后回填),投影/ui_state prep 行透出;前端匹配表原「可用数量」改「预约数量」并新增「可用数量」列(四语言);匹配落库后 `auto_release_part_fallback_shortages` 对「缺口+料号总量≥需求+证据字段全部自动取值」行由系统创建 `release_inventory_shortage` 决定(`decision_source='system'`,快照 `auto_release`/`release_evidence_scope`),证据不可解析/字段分歧/总量不足降级人工,不自动撤销;证据带出优先级:预约号+料号 → 料号键重筛 → 人工补录,`release_field_values` 为导出 Excel 证据覆盖唯一来源;Excel/波次出单条件不变(出单仍需人工勾选波次)。见 [features/shipping-notice/technical.md](features/shipping-notice/technical.md)「料号兜底自动放行与数量列」。 |
| 库存候选源刷新(人工重取前置,2026-10-13) | 已实现 | 「重新获取库存(RPA)」人工重取前按当前主数据幂等重判候选集(任务级整单重路由、行级仅重评目标行;仅未定源,人工钉源/已定源/Excel 已生成/轮询路径均不刷新),新版候选集 supersede 时内置失效旧库存事实,随后按新候选重取重算;前端歧义行库存源下拉改为候选置顶 + 全部已启用源兜底 |
| 库存源线索直连(2026-10-13) | 已实现 | 订单行「库存源线索」(inventory_source_hint)在行级路由评估最前置直连:精确 source_code 相等或启用源唯一后缀命中即 resolved(优先于预约单号兜底等全部规则层,evidence 标 reason),无命中/后缀多命中 fail-open 落回规则层;快照路径引擎自读强类型列、Draft 路径由资格投影传值;波次行路由暂未接入 |
| 确认客户改绑(2026-10-13) | 已实现 | 订单复核工作台客户识别面板两态化(已识别态默认折叠摘要条 + 「修改客户」按钮,可用性=编辑窗 header 谓词);后端 `rebind_confirmed_customer` 四层守卫:乐观锁 `expected_order_data_version` 写前比较 → 识别结果已确认 → 编辑窗 header(任一通知无 Export Artifact 且无活动 Attempt)→ 新客户有效且 ≠ 当前;链路:`evidence_json` 追加 rebind 条目 → 审计 `review_customer_rebound`(携带 review_case_no)→ 原地刷新快照客户/简称 + freeze 幂等;匹配与门禁零改动,改后回通知准备重新生成 Excel。设计:[2026-10-13 确认客户改绑设计](superpowers/specs/2026-10-13-customer-rebind-design.md) |
### 排程平台任务契约中心(schedule)
+1
View File
@@ -12,5 +12,6 @@
| [progress_contract_platform_prototype.html](progress_contract_platform_prototype.html) | 进度契约平台 HTML 原型 |
| [enterprise-integration-center-prototype.md](enterprise-integration-center-prototype.md) | 企业集成中心蓝图(完整愿景,含 HTML 原型) |
| [integration-connector-framework-design.md](integration-connector-framework-design.md) | Integration Connector Framework 设计(首期最小可行收敛版) |
| [permission-model.md](permission-model.md) | 现网权限说明:角色包、能力键、应用授权、管理后台 |
| [role-permission-prototype.md](role-permission-prototype.md) | 可配置角色权限包(一期约定);[可点击原型](role-permission-prototype.html) |
| [awaiting-callback-reconciler-design.md](awaiting-callback-reconciler-design.md) | 通用「等待外部回调」对账器设计(三域超时兜底统一;设计草案,P2+ 未实施) |
+140
View File
@@ -0,0 +1,140 @@
# 系统权限说明
> **文档路径**:`docs/platform/permission-model.md`
> **用途**:说明现网权限怎么判、有哪些角色包、有哪些能力键,以及哪些业务只认应用授权或平台管理员。
> **依赖**:`permission_roles`、`permission_role_agents`、`users.role`、`user_agent_permissions`、`User.get_feature_permissions`。
> **逻辑**:管理端在 `/admin/permissions` 配角色包;运行时登录态下发 `is_platform_admin` / `role_name` / `feature_permissions`。产品交互约定见 [role-permission-prototype.md](role-permission-prototype.md)。能力目录以 `backend/app/services/permission_roles/catalog.py` 为准。
---
## 怎么判权
一个人只绑一个角色。角色包决定能进哪些应用,以及进了应用之后能做哪些事。平台管理员是特例:应用入口默认全开,也能进管理后台。部门不授权。
登录后后端下发三样东西,前端路由守卫和后端接口用同一份结果:
| 字段 | 含义 |
| --- | --- |
| `is_platform_admin` | 是否平台管理员 |
| `role_name` | 角色显示名 |
| `feature_permissions` | 应用内能力键,值为布尔 |
三层数据:
| 层 | 存在哪 | 运行时怎么用 |
| --- | --- | --- |
| 角色包 | `users.role` 指向 `permission_roles.code` | 每人一个。改角色,或改该角色的勾选,会立刻重写这个人的应用授权 |
| 应用入口 | `permission_role_agents`,同步到 `user_agent_permissions` | 聊天和工作台按「有没有这个 Agent」放行。平台管理员不写授权行,入口隐式全开 |
| 应用内能力 | 角色包上的 `feature_permissions` | 已经进了应用之后,再卡统计、强制新建、台账维护这类动作 |
未种子权限组时,只有 `users.role = admin` 算平台管理员,能力键默认全开。种子之后以权限组上的 `is_platform_admin` 为准,不再用 `hr` 这类角色名暗示能力。种子后禁止按人单独加应用(`POST /users/:id/permissions`、批量权限、按 Agent 授权、权限申请批准加应用)。
主要代码:
- 能力目录与种子角色:`backend/app/services/permission_roles/catalog.py`
- 有效权限计算、按角色重写授权:`backend/app/services/permission_roles/service.py`
- 用户侧合并:`User.get_feature_permissions` / `User.is_platform_admin`(`backend/app/models/user.py`)
- 接口装饰器:`@require_admin`、`@require_agent_permission`(`backend/app/core/decorators.py`)
- 前端守卫:`requiresAdmin`、`requiresFeaturePermission`(`frontend/src/app/router/guards.ts`)
---
## 内置角色包
| 编码 | 名称 | 默认给什么 |
| --- | --- | --- |
| `user` | 普通用户 | 新建用户默认。只勾通用入口。企业知识库在这个聊天里切换,不单独占一列权限 |
| `rd` | 研发应用 | 通用入口,以及名称含「专利」的应用 |
| `hr` | 培训 HR | 通用入口、培训应用,并打开 `training_hr_manage` |
| `shipping` | 货代专员 | 通用入口、货代应用,并打开 `shipping_notice_force_create` |
| `admin` | 管理员 | 平台管理员。应用隐式全开,全部能力键默认打开,可进 `/admin` |
`user`、`hr`、`admin` 是系统角色。`rd`、`shipping` 可以再增删应用。管理员也可以在后台另建角色包。
---
## 应用内能力键
角色编辑里能勾的固定能力。平台管理员默认全开;角色包里可以把某一项关掉。键名与 `KNOWN_FEATURE_KEYS` 对齐。
### 培训
要先勾上内容画像为 `training` 的应用,卡片里才会出现这项。
| 键 | 作用 |
| --- | --- |
| `training_hr_manage` | HR 管理:查看统计、筛选记录、导出 Excel。没有这把钥匙只能当学员使用培训 |
### 货代发货通知
绑定 `agent_code=shipping_notice`。
| 键 | 作用 |
| --- | --- |
| `shipping_notice_force_create` | 跳过重复拦截,强制新建发货通知 |
| `shipping_notice.audit_sensitive_read` | 查看审计里的 before / after / Diff 正文 |
| `shipping_notice.xfa_split_rule_edit` | 维护字段拆分规则 |
| `shipping_notice.xfa_split_rule_preview` | 预览拆分结果 |
| `shipping_notice.xfa_split_rule_publish` | 审核并发布拆分规则 |
后三项主要卡在管理后台的货代模板与审计接口上:先要是平台管理员,再要有对应能力键。
### 设备维保
绑定名称含「维保」或「维修」,或 `agent_code=maintenance` 的应用。
| 键 | 作用 |
| --- | --- |
| `maintenance.ledger_write` | 维护设备台账和维修记录。没有则只能查看 |
### 订单交期回复
绑定 `agent_code=order_delivery_reply`。有 `manage` 就视为同时有 `access`。
| 键 | 作用 |
| --- | --- |
| `order_delivery_reply.access` | 只读已同步订单和回复结果 |
| `order_delivery_reply.manage` | 生管回复交期、发送通知、手动同步 |
读接口要求 `access` 或 `manage`;保存、通知、同步要求 `manage`。部门批量发放只给平台管理员。前端订单交期页用 `requiresFeaturePermission=order_delivery_reply.access` 拦截(持有 `manage` 的人后端视为有 access;守卫读的是登录态里的显式布尔值,角色包须两键一并授予)。
---
## 按应用授权
这些业务不进能力目录。角色包勾上对应 Agent 就能看;改数据、同步、发通知再要求平台管理员。
聊天主链路(会话、补全、附件)统一走 `@require_agent_permission`:请求带 `agent_id`,用户在该 Agent 的授权名单里,或是平台管理员。
| 应用 `agent_code` | 持有该 Agent 能做 | 仅平台管理员 |
| --- | --- | --- |
| `contract_payment` | 查合同付款台账 | 同步 OA、强制覆盖、批量重解析、扫描预警、发送周汇总 |
| `voucher_check` | 查检核任务和发送记录 | 强制重检、通知配置 |
| `equipment_acceptance` | 打开设备验收预警作业面 | 从 E10 同步、修改配置 |
| `in_transit_transfer` | 使用在途调拨接口 | 平台管理员同样放行,没有单独的只读/可写能力键 |
合同付款不再占用功能权限键。无授权返回业务 403,例如 `CONTRACT_PAYMENT.FORBIDDEN`;管理动作返回 `*.ADMIN_REQUIRED`。
---
## 管理后台
`/admin` 整棵树只认平台管理员。前端路由 `requiresAdmin`,后端 `@require_admin`。模块之间不再拆权限,能进后台就能进这些模块:
- 总览、用户、部门、应用、权限组
- 知识库、排程、企业微信、关联服务、平台应用
- 公告、快捷问题、培训配置、采购合同、集成连接器、报表
- 货代管理:字段资产、订单 Schema、订单文档模板、客户识别规则、识别任务、库存与连接配置、运行与审计、门禁诊断
侧栏「管理控制台」只对 `is_platform_admin` 显示。非平台管理员访问 `/admin` 会被送回应用管理。
货代管理页本身是管理员页。读取敏感审计、编辑 / 预览 / 发布拆分规则,还会再查上一节的货代能力键。
---
## 按数据归属,不按角色勾选
| 场景 | 谁可以 |
| --- | --- |
| 收料归档文件下载 | 平台管理员,或该排程任务的通知接收人 |
| 货代门禁恢复 | 读:单据属主、平台管理员,或持有该 Run 所属 Agent 的人。写:单据属主或平台管理员。管理端路由另由 `@require_admin` 保护 |
@@ -1,47 +0,0 @@
# 角色权限配置原型
> **文档路径**:`docs/platform/role-permission-prototype.md`
> **用途**:可配置角色(权限包)一期产品原型说明;交互稿见同目录 HTML。
> **依赖**:管理控制台「应用权限」、`permission_roles`、`users.role`、`user_agent_permissions`。
> **逻辑**:新建用户由管理员选角色(默认普通用户);已有用户可按角色点人数筛选勾选,确定前确认影响。一期已按此实现。可点击稿:[role-permission-prototype.html](role-permission-prototype.html)
---
## 怎么打开
用浏览器直接打开 `docs/platform/role-permission-prototype.html`(无需启动前后端)。左侧切换:
| 屏 | 要看什么 |
| --- | --- |
| **角色配置** | 权限包列表。点「编辑」给该角色勾应用;点蓝色**人数**给该角色加人 |
| **编辑角色** | 列出全部可授权应用;保存前确认会立刻改变该角色下所有人的入口 |
| **用户管理** | **新建用户必须选角色**,默认普通用户;编辑用户改角色也会先确认 |
| **权限核对** | 现行矩阵的只读形态,格子禁用 |
| **现行应用权限** | 对照说明:为什么不再按人打勾 |
建议演示:
1. **用户管理 → 新建用户**:角色预填「普通用户」,可改成培训 HR / 研发应用等,非默认角色会再确认。
2. **新增应用后**:先编辑对应角色勾上该应用 → 再点该角色人数,按部门筛选勾选要进这个角色的人 → **确定后弹出确认**(写清从哪些角色改入)。全选只勾草稿,不要不核对就点确认调整。
---
## 一期约定(已画进原型)
1. **角色 = 权限包**:可用应用 + 应用内能力;管理员单独带「可进 /admin」。
2. **用户只选一个角色**。新建时由管理员指定,默认普通用户;部门不会自动授权。
3. **普通用户**默认只勾 **通用入口**(企业知识库是该聊天里的库切换,不单独占一列)。
4. **研发应用** = 通用入口 + 研发侧应用(如专利);本地尚未接入的应用之后勾进本组即可。编码仍为 `rd`。
5. 角色编辑列出**应用管理中全部启用应用**。有功能权限的应用在卡片内用短标签配置,不另开一排长框。新增应用:勾到需要的角色上,再按需把人改进该角色。
6. **保存角色立即对已绑该角色的用户生效**,弹窗提示人数,须确认。
7. **管理员内置**:应用入口隐式全开;人数不可点;选人列表排除管理员。改到/改出管理员须额外确认。
8. **已有用户批量改角色**:点人数,左部门仅筛选。勾选后确定先出确认框(从来源角色、将失去原权限)。全选不是默认操作。
9. **取消勾选后确认** = 回到默认普通用户。编辑「普通用户」时取消勾选忽略。
---
## 一期不做
- 一人多角色、按人额外加应用、在核对矩阵上打勾。
- 部门自动映射角色(部门是组织,角色是权限包;入职/调岗由管理员选或改角色)。
- 员工自助「申请某个应用」(若保留申请,应改为申请换角色)。
@@ -0,0 +1,181 @@
# 确认客户改绑(Customer Rebind)实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** 已确认订单在产生发货通知/Excel 之前,允许用户在订单复核工作台的客户识别面板上直接修改确认客户(改绑),改后重新冻结快照并重新生成 Excel。
**Architecture:** 客户识别面板两态化(未识别=现状流程;已识别=默认折叠摘要条+「修改客户」),前端管控复用编辑窗头级谓词;后端新增 `rebind_confirmed_customer` 一条链(守卫→更新 resolution 行→审计→手动重冻结),匹配/门禁零触碰——守卫保证仅在无 Excel 产物时可改,无失效连锁。
**Tech Stack:** Flask + SQLAlchemy 2.0(后端);Vue 3 + TypeScript + Vue I18n 四语言(前端)。
**Spec:** `docs/superpowers/specs/2026-10-13-customer-rebind-design.md`
## Global Constraints
- 🚫 禁止自动 commit;任务以 `git add <具体文件>` 收尾(工作区有他人并行 WIP)。
- 🌍 前端新增文案四语言(zh-CN/zh-TW/en/th)同步;chat.json 用精确子串编辑,禁 PowerShell 改写。
- 🧷 冻结契约:`evidence_json` 与 `identity_rule_set_checksum` 必须保持非空(`order_freeze_service._confirmed_ordering_customer` 校验,:274-287);`freeze_order_snapshot(mode='manual')` 必须传 `actor_id`。
- ⚠️ 匹配/门禁状态零改动:本能力不触碰 `export.py`、`post_ot_fulfillment_wave_service.py`、门禁 gate 行。
- 📝 新函数含 Args/Returns docstring;测试有断言意图注释(§5.4)。
- 后端测试:`cd backend && ./.venv/Scripts/python.exe -m pytest <file> -q`;前端 vitest 可用 + `npm run build`。
---
### Task 1: 后端改绑服务 + API
**Files:**
- Modify: `backend/app/services/shipping_notice/customer_resolution_service.py`(新增 `rebind_confirmed_customer`)
- Modify: `backend/app/api/workspace/shipping_notice.py`(新增 rebind 端点,模式对齐同文件 `order-review-cases/<case_no>/line-fulfillment/decide` 路由 :2163-2194)
- Test: `backend/tests/test_customer_resolution_rebind.py`(新建;夹具对齐既有客户确认相关测试的构造,执行者按文件内/相邻测试文件现状取用)
**Interfaces:**
- Consumes: `resolution_for_task(task)`(本服务既有);`editable_scope(order_task)['header']`(`order_edit_window_service.py:121`);`freeze_order_snapshot(task, actor_id, expected_order_data_version, freeze_mode='manual')`(`order_freeze_service.py`)。
- Produces: `rebind_confirmed_customer(*, task, new_customer_id, actor_id, reason=None) -> dict`(返回 {'resolution': 行, 'snapshot': 重冻结快照});API `POST .../order-review-cases/<case_no>/customer/rebind`。
- [ ] **Step 1: 写失败测试**
```python
def test_rebind_updates_confirmed_customer_and_refreezes_snapshot():
"""改绑必须更新确认结果并按新客户重冻结快照(客户 ODM 白名单随新客户生效)。"""
# 夹具:已确认 resolution(status='confirmed', confirmed_customer_id=旧客户, evidence_json 非空)
# + 已冻结快照 + 无 Export Artifact/无活动 Attempt(editable_scope.header=True)。
result = rebind_confirmed_customer(
task=task, new_customer_id=int(new_customer.id), actor_id=int(user.id), reason='选错客户',
)
# 断言意图:确认结果与快照客户同步改绑;审计与 evidence_json 记录原客户(可追溯)。
assert result['resolution'].confirmed_customer_id == int(new_customer.id)
assert result['snapshot'].customer_id == int(new_customer.id)
assert result['resolution'].evidence_json['rebind']['previous_customer_id'] == int(old_customer.id)
assert result['resolution'].identity_rule_set_checksum # 冻结契约:保持非空
def test_rebind_rejects_when_export_artifact_exists():
"""已产生 Excel(header 不可编辑)时改绑必须 409,且确认结果不被改动。"""
# 夹具:同上,但给任一通知造 Export Artifact(对齐既有 artifact 测试构造)。
with pytest.raises(ConflictError) as exc:
rebind_confirmed_customer(task=task, new_customer_id=int(new_customer.id), actor_id=int(user.id))
# 断言意图:A 管控 fail-closed;错误码可前端定位。
assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED'
assert resolution_row.confirmed_customer_id == int(old_customer.id)
def test_rebind_rejects_same_customer_and_unknown_customer():
"""同客户重复改绑与不存在/停用客户都必须 409/404,不产生副作用。"""
```
(夹具构造对齐仓库内既有客户确认测试;断言语义以三段注释为准。)
- [ ] **Step 2: 确认失败**
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_customer_resolution_rebind.py -q`
Expected: FAIL(函数不存在)
- [ ] **Step 3: 实现**
`rebind_confirmed_customer` 顺序:
1. `resolution = resolution_for_task(task)`;`status != 'confirmed'` → ConflictError(提示走识别确认流程)。
2. `editable_scope(task)['header']` 非 True → ConflictError `SHIPPING.CUSTOMER_REBIND_BLOCKED`(details 标注 excel_exists / active_attempt)。
3. 新客户存在且启用(ShippingCustomer 查询)且 ≠ `resolution.confirmed_customer_id`,否则 404/409。
4. `previous = resolution.confirmed_customer_id`;更新 id;`evidence_json = {**evidence_json, 'rebind': {...previous, new, actor_id, reason, utcnow}}`;flush。
5. 审计(事件类型对齐 `progress_audit_contract` 既有集合,执行者核对后选用;before/after 客户 + reason)。
6. `freeze_order_snapshot(task, actor_id=actor_id, expected_order_data_version=int(task.order_data_version or 1), freeze_mode='manual')`;返回 resolution + 新快照。
API 端点:校验登录与 case 归属(对齐 decide 端点的守卫风格),`actor_id` 取当前用户,调用服务,返回刷新 case 投影(复用既有序列化 helper)。
- [ ] **Step 4: 确认通过 + 回归**
```bash
cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_customer_resolution_rebind.py tests/test_shipping_notice_ui_state.py -q
```
(ui_state 已知基线失败 2 个不算。)另跑一个冻结相关套件确认零回归:`pytest tests/test_shipping_order_edit_window.py -q`。
- [ ] **Step 5: Stage**
```bash
git add backend/app/services/shipping_notice/customer_resolution_service.py backend/app/api/workspace/shipping_notice.py backend/tests/test_customer_resolution_rebind.py
```
---
### Task 2: 前端面板两态化 + 修改客户弹窗
**Files:**
- Modify: `frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue`(两态化:resolved → 折叠摘要条;新增修改客户流程,复用既有 `searchCustomers` 与客户选择组件)
- Modify: `frontend/src/features/chat/views/ShippingOrderReviewView.vue`(面板 props:传入 `:rebind-allowed`(`formalEditWindow?.header === true`,:466 formalEditWindow)与禁用原因;渲染条件 `v-if="!activeCase.customer_resolution?.resolved"` 改为始终渲染并交由面板内部分态)
- Modify: `frontend/src/features/chat/api/shipping.api.ts`(新增 `rebindWorkspaceShippingOrderReviewCustomer(caseNo, { customer_id, reason })`)
- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json`(新键,见 Task 3)
- Test: `frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts`(新建/扩展,对齐既有面板 spec 写法)
**Interfaces:**
- Consumes: Task 1 API;`formalEditWindow`(view :466);面板既有 `searchCustomers`(:111)与 `refreshed` emit。
- Produces: 面板 props `rebindAllowed: boolean`;emit `refreshed`(复用)。
- [ ] **Step 1: spec 断言先行**
```typescript
// 断言意图:已识别态默认折叠为摘要条(状态徽标+客户名),不默认展开详情;
// 「修改客户」按钮在 rebindAllowed=false 时禁用。
it('renders collapsed summary with customer name when resolved', ...)
it('disables rebind button when rebindAllowed is false and shows reason', ...)
it('submits rebind with selected customer and emits refreshed', ...)
```
(按该文件/相邻面板 spec 的 mount 与查询写法落地;先跑确认失败。)
- [ ] **Step 2: 实现面板两态**
- `resolved=true`:渲染折叠条——`已确认` 徽标 + `resolution` 中的标准客户名(现有字段)+ chevron(展开显示既有识别详情,**无 ODM 范围**)+ 「修改客户」按钮(`:disabled="!rebindAllowed"` + tooltip 用禁用原因 i18n 键)。
- 修改客户流程:打开复用的客户搜索选择(`searchCustomers`)→ 选定 → 影响确认弹窗(i18n 文案见 Task 3)→ `rebindWorkspaceShippingOrderReviewCustomer` → 成功 toast("客户已更新,可回通知准备重新生成 Excel")→ `emit('refreshed')`。
- `resolved=false`:原样。
- [ ] **Step 3: 视图接线**
`ShippingOrderReviewView.vue:6008` 的 `v-if` 改为始终渲染该面板(resolved 与否由面板分态);补 props `:rebind-allowed="formalEditWindow?.header === true"`;`@refreshed="handleReviewGateDataRefreshed"` 既有。
- [ ] **Step 4: 验收**
```bash
cd frontend && npx vitest run src/features/chat/components/shipping-review/ && npm run build
```
- [ ] **Step 5: Stage**
```bash
git add frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts frontend/src/features/chat/views/ShippingOrderReviewView.vue frontend/src/features/chat/api/shipping.api.ts frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json
```
---
### Task 3: i18n 四语言
**Files:**
- Modify: 四语言 `chat.json` 的 `shippingOrderReview` 域内(建议 `customerResolution` 邻近块)
**Interfaces:** Produces 键:`rebindButton`(修改客户)、`rebindDisabledExcelExists`(禁用原因)、`rebindConfirmTitle`、`rebindConfirmImpact`、`rebindSuccessToast`(文案含"可回通知准备重新生成 Excel")、`rebindFailedToast`。
- [ ] 四语言值:
| 键 | zh-CN | zh-TW | en | th |
| --- | --- | --- | --- | --- |
| rebindButton | 修改客户 | 修改客戶 | Change customer | เปลี่ยนลูกค้า |
| rebindDisabledExcelExists | 已产生发货通知/Excel,请先走撤销流程 | 已產生發貨通知/Excel,請先走撤銷流程 | Notice/Excel already generated — undo it first | มีการแจ้งเตือน/Excel แล้ว โปรดยกเลิกก่อน |
| rebindConfirmTitle | 确认修改客户 | 確認修改客戶 | Confirm customer change | ยืนยันการเปลี่ยนลูกค้า |
| rebindConfirmImpact | 将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成 | 將更新訂單客戶並重新凍結訂單快照;已產生的發貨通知/Excel 需重新生成 | The order customer will be updated and the snapshot re-frozen; generated notice/Excel must be regenerated | ลูกค้าจะถูกอัปเดตและ snapshot จะถูก freeze ใหม่ |
| rebindSuccessToast | 客户已更新,可回通知准备重新生成 Excel | 客戶已更新,可回通知準備重新產生 Excel | Customer updated — regenerate the Excel in notice preparation | อัปเดตลูกค้าแล้ว สร้าง Excel ใหม่ได้ |
| rebindFailedToast | 客户修改失败 | 客戶修改失敗 | Failed to change customer | เปลี่ยนลูกค้าไม่สำเร็จ |
- [ ] JSON 合法性校验(node 解析四文件);`git add` 四文件。
---
### Task 4: 文档 + 回归
- [ ] `docs/features/shipping-notice/technical.md` 文末追加「确认客户改绑(2026-10-13)」(守卫/链路/边界备忘——已放行证据不重算);`docs/funclist.md` 加 1 行。
- [ ] 回归:后端 `pytest tests/test_customer_resolution_rebind.py tests/test_shipping_order_edit_window.py tests/test_shipping_notice_ui_state.py -q`(ui_state 2 个基线失败除外);前端 vitest 面板 spec + `npm run build`。
- [ ] 人工冒烟:本地复现单(SORC-336EB5E5D6D84CBE)——折叠条显示;客户 15 补 ODM 或改绑到维护了 581 的客户;回通知准备重新生成 Excel 成功。
## Self-Review
- 规格覆盖:两态化/折叠/无 ODM 展示 → Task 2;管控 A → Task 1 守卫 + Task 2 按钮禁用;改绑链 → Task 1;审计/追溯 → Step 3.5;边界 → spec §4 + Task 4 文档。
- 占位符:夹具构造与事件类型对齐项已给出现有锚点(文件:行)与断言语义,属执行者对齐指引。
- 类型一致:`rebind_confirmed_customer` 签名、API 路径、`rebindAllowed` prop、i18n 键名前后一致。
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,51 @@
# 确认客户改绑(Customer Rebind)设计
日期:2026-10-13 | 状态:待评审 | 关联案例:SORC-336EB5E5D6D84CBE(客户选错 → Excel 生成 ODM 白名单失败)
## 1. 背景与目标
订单复核阶段客户选错,任务推进到通知准备后 Excel 生成失败(`artifact_generation`:库存行 ODM ID 不在客户维护范围内)。当前**确认后没有任何入口可以改客户**:客户识别面板在 `customer_resolution.resolved` 后整体消失(`ShippingOrderReviewView.vue:6008`)。
目标:在订单复核工作台的客户识别面板上,允许用户**直接修改客户识别的确认结果**(不重走识别候选确认),改完回通知准备重新生成 Excel。
## 2. 交互设计
### 2.1 面板两态化(`ReviewCustomerResolutionPanel`)
- **未识别**(`resolved=false`):保持现状(识别候选确认流程)。
- **已识别**(`resolved=true`):面板默认**折叠为一行摘要条**(不再整体消失):
- 摘要条:状态徽标「已确认」+ 标准客户名(截断)+ 展开 chevron + 「修改客户」按钮;
- 展开:显示既有识别详情(命中输入/识别依据等历史信息);**不展示 ODM 范围**;
- 「修改客户」按钮的可用性 = 编辑窗头级谓词(`editable_scope(order_task)['header']`,即:该订单任一通知无 Export Artifact 且无活动 Gate Attempt)。不满足 → 按钮禁用 + tooltip 说明("已产生发货通知/Excel,请先走撤销流程")。
### 2.2 修改客户流程
点「修改客户」→ 复用既有客户搜索组件(`searchCustomers`)直接选定目标客户(**不重走识别候选打分确认**)→ 二次确认弹窗(明示影响:「将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成」)→ 提交 → 成功 toast("客户已更新,可回通知准备重新生成 Excel")→ `refreshed` 事件走既有刷新链。
## 3. 后端设计
`customer_resolution_service.rebind_confirmed_customer(task, new_customer_id, actor_id, reason=None)`:
1. **守卫(fail-closed,顺序固定)**:
- resolution 行存在且 `status='confirmed'`(未确认走既有确认流程,409);
- `editable_scope(order_task)['header']` 为 True,否则 409 `SHIPPING.CUSTOMER_REBIND_BLOCKED`(details 区分:Excel 已产生 / 存在活动 Attempt);
- 新客户存在且启用,且 ≠ 当前确认客户。
2. **更新**:`confirmed_customer_id = new_customer_id`;`evidence_json` 追加 rebind 记录(时间/操作人/原因/原客户,保持非空契约);`identity_rule_set_checksum` 保留不动(冻结要求非空)。
3. **审计**:`append_shipping_audit_event`(before/after confirmed_customer_id + reason,事件类型对齐仓库审计契约)。
4. **重冻结**:`freeze_order_snapshot(mode='manual', actor_id, expected_order_data_version)`——快照 `customer_id`/客户简称/模板头字段全部按新客户刷新;乐观锁冲突透传 409。
5. **不动的部分**:不失效匹配(匹配键=预约+料号,与客户无关);不改门禁状态(Excel 未产生时无可失效产物——守卫已保证;Excel 已产生时守卫直接拒绝)。
6. **API**:`POST /api/workspace/shipping-notice/order-review-cases/<case_no>/customer/rebind`,body `{customer_id, reason?}` → 返回刷新后的 case 投影。
## 4. 边界与不做的事
- 已放行缺口行的补录证据不随改绑重算(决定仍有效,导出按快照 `release_field_values` 全量字典取值)——文档备忘。
- 预约号是货代侧事实,与客户无关,不重跑预约校验。
- Excel 已产生时改绑被守卫拒绝(A 管控),不做"改后作废重出"模型。
- ODM 白名单在导出时实时读新客户的 `odm_ids`,改绑后无需任何 ODM 配置动作即可被「重新生成 Excel」消费。
## 5. 验收标准
1. 已识别面板默认折叠,展示确认客户摘要;未识别态行为不变。
2. Excel 未产生时「修改客户」可用,走搜索→确认→提交后:快照客户更新、审计落库、工作台自动刷新。
3. Excel 已产生/有活动 Attempt 时按钮禁用并说明原因;直接调 API 返回 409。
4. 改绑后重新生成 Excel 使用新客户 ODM 白名单(本案例:白名单含 581 后成功出单)。
+1 -1
View File
@@ -5,7 +5,7 @@
- 表:`permission_roles`(code/name/feature_permissions/is_default/is_platform_admin)与 `permission_role_agents`。成员仍写在 `users.role`(加宽至 64)。运行时 Chat/工作台继续读 `user_agent_permissions` 与 `require_agent_permission`(`is_platform_admin` 旁路);非管理员的 Agent 行由角色包全量替换。排程种子 owner 与 RPA 心跳告警管理员兜底改为 join `is_platform_admin`(未种子权限组时回退 `users.role=admin`)。登录态下发 `is_platform_admin` / `role_name` / `feature_permissions`;业务门闩认标记与能力键。未种子时默认能力仅平台管理员全开,不再用 `hr` / `maintenance_manager` 角色名暗示权限(培训 FAQ 的 HR/员工身份、会话 guest、聊天 message.role、保留码 `admin` 除外)。
- 种子:`user` 普通用户、`rd` 研发应用、`hr` 培训 HR、`shipping` 货代专员、`admin` 管理员。不再种子设备维保专员。
- 管理 API:`/api/admin/permission-roles*`(列表、目录、CRUD、成员 preview/apply)。种子后禁止 `POST /users/:id/permissions`、`/permissions/batch`、`/agents/:id/permissions` 与权限申请批准加应用。
- 前端:`/admin/permissions` 角色配置 + 只读矩阵;用户表单只选角色。能力键与 `User.get_feature_permissions` 对齐。详细约定见 [platform/role-permission-prototype.md](platform/role-permission-prototype.md)。
- 前端:`/admin/permissions` 角色配置 + 只读矩阵;用户表单只选角色。能力键与 `User.get_feature_permissions` 对齐。权限分层与能力清单见 [platform/permission-model.md](platform/permission-model.md);交互约定见 [platform/role-permission-prototype.md](platform/role-permission-prototype.md)。
- AI 工作台侧栏底部「返回聊天」上方,仅 `is_platform_admin` 渲染「管理控制台」入口(`openAdminPanel` → `/admin`);`/admin` 仍由路由守卫 `requiresAdmin` 拦截非平台管理员。
## 合同付款预警(2026-08)
+259
View File
@@ -0,0 +1,259 @@
# Element Plus 迁移规范
> **用途**:管理端页面从手写 Tailwind 控件换成 Element Plus 时的唯一操作说明。后续每换一页,按本文做,不要再单页发明一套间距、字号或按钮写法。
> **适用**:管理控制台里已经或即将换成 Element 的列表、筛选、表格、表单弹窗。
> **不适用**:对话、文档画布、冻结列宽表(订单交期回复、发货审核等)。这些仍走 [UI_CODING_GUIDELINES.md](./UI_CODING_GUIDELINES.md),不要在同一块界面里混用两套按钮和输入框。
> **试点**:用户管理、应用配置、知识库分组。列表、短弹窗和应用配置的创建/编辑表单已按本文收过。新页面以本文为准。
旧页面在换完之前,继续遵守 [UI_CODING_GUIDELINES.md](./UI_CODING_GUIDELINES.md)。换到 Element 的那一块,以本文为准。
---
## 1. 接入方式
按页面接入,不在 `main.ts` 里 `app.use(ElementPlus)`,也不要全局注册全部组件。
每个改为 Element 的页面(或该页专用弹窗)需要:
1. 按名字导入用到的组件,例如 `ElButton`、`ElTable`、`ElDialog`。
2. 引入样式(页面入口引一次即可,弹窗跟页面走,不必再引):
```ts
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
```
3. 用 `useElementProvider()` 取出 `elementLocale`,页面根上包 `ElConfigProvider`。亮暗靠现有 `html.dark` 加上面的暗色变量文件,不要在组件里再切一套主题算法。
4. 使用 `v-loading` 时,在 `<script setup>` 里写 `const vLoading = ElLoading.directive`。
5. 文案继续用现有 i18n key。新增文案必须同时补齐 zh-CN / zh-TW / en / th。
6. 图标用 `@element-plus/icons-vue`,放进 `ElButton` 的 `icon` 属性。不要再把 `lucide-vue-next` 的图标塞进 Element 按钮。
`element-trial.css` 是管理端 Element 的公共皮肤,只放变量和与 Tailwind 共存的修正。某一页的列宽、筛选框宽度不要写进这个文件。
---
## 2. 先写入变量,再换页面
下面这些变量已经写在 `frontend/src/features/admin/styles/element-trial.css` 的 `:root, html.dark` 里。Element 暗色表在 `html.dark` 上另有一份默认值,所以必须和亮色写在一起,后引入的文件才能盖过它。页面不要再各写一套字号和颜色。
| 变量 | 对齐到 | 用途 |
| --- | --- | --- |
| `--el-font-family` | 已设为 PingFang SC / Microsoft YaHei | 控件字体 |
| `--el-color-primary` | 已设为 `#0284c7` | 主按钮、链接、聚焦边框 |
| `--el-font-size-large` | `18px`(现有 `.section-title`) | 页标题若改用 Element 排版时使用 |
| `--el-font-size-base` | `14px` | 正文、按钮、输入框、表格单元格 |
| `--el-font-size-small` | `13px` | 次要说明、统计 |
| `--el-font-size-extra-small` | `12px` | 标签、辅助提示 |
| `--el-text-color-primary` | `var(--text-primary)` | 标题、强调 |
| `--el-text-color-regular` | `var(--text-secondary)` | 正文 |
| `--el-text-color-secondary` | `var(--text-muted)` | 说明、表头、统计 |
| `--el-text-color-placeholder` | `var(--text-muted)` | 占位符 |
| `--el-border-color` | `var(--border-default)` | 输入框、分割线 |
| `--el-border-color-light` / `--el-border-color-lighter` | `var(--border-subtle)` | 表格线、弱分割 |
| `--el-bg-color` | `var(--bg-surface)` | 弹窗、表格底 |
| `--el-fill-color-light` | `var(--bg-surface-soft)` | 表头底 |
| `--el-border-radius-base` | `8px` | 按钮、输入框、标签 |
| `--el-component-size` | `32px` | 默认按钮、输入框、下拉的高度 |
页面里禁止再用 `text-xs`、`text-sm`、`text-[13px]`、`font-semibold`、`text-primary`、`text-muted` 去改 Element 控件内部或表格单元格的字号和颜色。单元格需要强调时,用 Element 的字重变量或标签,不要回到 Tailwind 字号。
暗色只改上述变量在 `html.dark` 下的取值。不要写 `dark:` 工具类。
---
## 3. 列表页骨架(只有这一套)
```text
section.admin-table-section 一张圆角卡片,页面上只此一层。组件是 features/admin/components/AdminListPage.vue
标题栏 section-title + section-desc + 右侧 ElSpace 按钮
页签 AdminListTabs,没有页签就不占一行
筛选条 一行控件,底部分隔线
ElTable 表头用 Element 灰底,左右内边距与标题栏一致
分页 右对齐,上边一条分隔线
```
约定:
- 标题用 `.section-title`,说明用 `.section-desc`。不要在知识库这种页面单独写 `text-xl font-bold`。
- 左右内边距统一 `32px`(标题、筛选、表格首列/末列、分页同一条边)。
- 筛选和表格之间用一条 `var(--el-border-color-lighter)` 分隔。表头保留 Element 浅灰底,作为第二层分界。不要再在卡片里套一张卡片。
- 统计数字放在筛选行右侧,不要单独占一行贴在表头上。
- 分页用 `ElPagination`,`layout="total, sizes, prev, pager, next"`,`background`。页码和每页条数绑定现有的页码状态,不要另写一套 `PaginationBar`。
---
## 4. 组件怎么用
### 4.1 按钮
| 位置 | 写法 |
| --- | --- |
| 页头主操作(新建、创建) | `ElButton type="primary"`,带 `icon` |
| 页头次操作(刷新、设置、跳转) | 默认 `ElButton`,带 `icon` |
| 行内编辑、查看 | `ElButton link type="primary"` |
| 行内删除 | `ElButton link type="danger"` |
| 弹窗取消 | 默认 `ElButton` |
| 弹窗确定 | `ElButton type="primary"`,提交中加 `:loading` |
同一工具栏里不要出现 `size="small"` 的实心按钮和默认高度按钮混排。行内有文字就用链接按钮,不要再做小图标方钮。没有文字、只能放图标时,必须带 i18n 的 `title`。
危险操作不要用绿色、蓝色按钮。测试、启用这类状态按钮用 `ElTag` 表达状态,操作本身仍按上表。
### 4.2 表格
- 必须设 `row-key`。
- 空数据用 `:empty-text`,文案用已有 i18n key。
- 状态列一律 `ElTag effect="light"`。启用 `success`,停用 `info`,警告 `warning`。不要自绘圆点,不要用 `bg-green-500` 这类 Tailwind 色。
- 表头背景、边框色走 §2 的变量,单页不要再覆盖 `--el-table-header-bg-color`。
- 列用 `min-width`。操作列固定 `width`,`align="right"`。
- 服务端排序用 `sortable="custom"`,在现有的排序函数里改页码并重新请求。不要表格本地排一遍、接口再排一遍。
- 头像不要用默认 `ElAvatar`(会变成灰色)。用户头像继续用现有品牌渐变圆标。
### 4.3 筛选
- `ElInput`、`ElSelect` 默认 `width: 100%`。必须放在限定宽度的容器里,搜索框约 `16rem`,下拉按最长文案定宽(约 `11rem`),靠左排,禁止用 `1fr` 把搜索框拉满整行。
- 「全部 / 所有部门」这类空条件用 `placeholder` 表达。`ElSelect` 的值不要用空字符串,空着时传 `undefined`,清空后写回 `''`。否则会显示 Element 默认的「请选择」。
- 少量互斥筛选(全部 / 有文档 / 空分组)用 `ElRadioGroup` + `ElRadioButton`,选项值用业务枚举,不要用 `label` 当值。
- 窗口变窄时换行,不要每个控件各占一整行。
### 4.4 弹窗和表单
- 用 `ElDialog`,`align-center`,`append-to-body`,`:close-on-click-modal="false"`。
- 短表单(大约 4 个字段以内)宽度 `480px`,一列。字段多或本来就是两列的,宽度 `680px`。不要用整屏高的抽屉装两个字段。
- `ElForm` 使用 `label-position="top"`。
- 标题用 `ElDialog` 的 `title`。说明放在对应 `ElFormItem` 里,字号走 §2,不要写 `text-xs text-muted`。
- 多行文本用 `ElInput type="textarea"`,行数按内容来,一般 4 行。不要把 `.el-textarea__inner` 的边框清掉,那一层就是输入框的边框。
- 提交按钮使用 `:loading`,防止重复提交。提交过程中不允许点遮罩关闭。
- 只有从屏幕侧边滑出、且内容确实很长时才用 `ElDrawer`。创建、编辑这种短表单用对话框。
### 4.5 反馈
- `v-loading` 只盖住表格,并且只等列表自己的请求。目录、用户、排程等弹窗依赖放到列表返回之后再拉,不能让遮罩一直盖住已经画出来的行。
- 删除、不可逆操作统一用 `ElMessageBox.confirm`,按钮文案和提示用现有 i18n。同一页不要同时留着 `DeleteConfirmDialog` 和 `ElMessageBox`。旧确认框在改该页时一起换掉。
- 操作成功或失败用 `useMessage()`。需要留在页面上的结果才用 `ElAlert`。
### 4.6 语言
`useElementProvider` 已映射 zh-CN、zh-TW、en、th。新页面把 `elementLocale` 传给 `ElConfigProvider`,不要在某个弹窗里写死 `zh-cn`。
---
## 5. 不要这样做
- 不要在 `main.ts` 全量注册 Element。
- 不要在同一工具栏里混用 `.btn-primary` 和 `ElButton`。
- 不要用 `!important` 压 Tailwind。Element 是静态 CSS,用更具体的选择器。单行输入框内部的蓝竖线,只重置 `.el-input__inner`,见 `element-trial.css`。
- 不要改全局 `svg { display }`。按钮图标的横向排列只写在 `element-trial.css` 的 `.el-button` 上。
- 不要新增第二套组件库,也不要在已换 Element 的页面里再手写一套输入框样式。
- 不要为了换皮去改接口、分页协议和权限判断。
---
## 6. 单页检查清单
换完一页,逐项核对:
- [ ] 只在该页入口引入 Element 样式和 `element-trial.css`,并用 `ElConfigProvider` 包住。
- [ ] 列表骨架符合 §3,左右 32px 对齐,只有一层卡片。
- [ ] 按钮符合 §4.1,没有 `size="small"` 和默认按钮混在一行。
- [ ] 表格状态是 `ElTag`,单元格没有 `text-xs` / `text-sm` / `text-muted`。
- [ ] 筛选框没有被拉成整行,空选项不是「请选择」。
- [ ] 弹窗宽度只有 480px 或 680px,短表单不是整屏抽屉。
- [ ] 加载遮罩只等列表请求,数据出来后遮罩消失。
- [ ] 删除确认与本页其他确认框是同一种。
- [ ] 四种语言下按钮、表头、空状态、分页都能读通。
- [ ] `html.dark` 下边框、表头、弹窗底色跟着变量变。
- [ ] `frontend` 下 `npx vue-tsc -b --pretty false` 通过。
改管理端界面时,把这份清单写进合并请求描述。模板在 [`.gitee/PULL_REQUEST_TEMPLATE.md`](../../.gitee/PULL_REQUEST_TEMPLATE.md)。ESLint 规则仍是关闭的,间距、弹窗宽度和暗色要靠这份清单看。
---
## 7. 和 Tailwind 共存时已经踩过的问题
| 现象 | 原因 | 处理 |
| --- | --- | --- |
| 按钮里图标和文字分成两行 | Tailwind preflight 把 `svg` 设成 `display: block` | 只在 `.el-button` 上改为横向 flex,已写在 `element-trial.css` |
| 搜索框聚焦时内部多两条蓝竖线 | `@tailwindcss/forms` 给内部 `input` 加了边框 | 只重置 `.el-input__inner` 的边框和阴影 |
| 多行输入框看起来没有边框 | 上一行修正误伤了 `.el-textarea__inner` | 文本域保留 Element 的内阴影边框 |
| 筛选框每个占满一行 | `ElInput` / `ElSelect` 默认 `width: 100%` | 外层限定宽度,靠左排列 |
| 下拉显示「请选择」 | 空字符串不是合法选项值 | 空值用 `undefined`,清空写回 `''`,文案放 `placeholder` |
| 列表已经出来,页面仍一直转圈 | `v-loading` 绑在整页,要等用户、排程等全部返回 | 遮罩只绑列表请求 |
| 头像变成灰色 | `ElAvatar` 默认底色 | 继续用品牌渐变圆标 |
---
## 8. 试点页和本规范的差距
新页面不要复制这些差距。改到对应页时收口。
| 页面 | 状态 |
| --- | --- |
| 用户管理 | 列表、筛选、三个业务弹窗、删除和改角色确认已按 §3、§4 对齐。筛选宽度和两列表单写在页面里。 |
| 知识库分组 | 列表骨架、行内链接按钮、删除确认、创建分组、Dify 设置和健康检查已对齐。 |
| 应用配置 | 列表、状态标签、测试弹窗、授权弹窗、删除确认和 680px 创建/编辑表单内部已对齐。保存仍走原来的 `save` 事件。 |
| 部门管理 | 列表已用 `AdminListPage`。搜索、表头排序、行内链接、480px 表单、员工名单和删除确认已按 §3、§4 对齐。列表仍是本地过滤和排序,没有分页。 |
| 公告管理 | 列表已用 `AdminListPage`。发布/编辑是 680px 对话框,详情是描述列表,删除确认已对齐。 |
| 关联服务 | 列表已用 `AdminListPage`。启用用 `ElSwitch`,表单 480px,删除确认已对齐。 |
| 知识库分组 | 外层不再套第二张卡片,列表骨架改为 `AdminListPage`。 |
| 仪表盘 | 四张统计卡改为 `ElCard` + `ElStatistic`。它不是列表,不用 `AdminListPage`。 |
| 平台应用 | 列表已用 `AdminListPage`。应用筛选、指南表格、680px 表单、上传和删除确认已对齐。 |
| 集成连接器 | 列表已用 `AdminListPage` 和 `AdminListTabs`。六个页签的表格、启停开关、状态标签和行内操作已对齐。创建/编辑抽屉、调用日志和手动调用弹窗仍是原来的控件。 |
| 常用问题 | 列表已用 `AdminListPage` 和 `AdminListTabs`。编辑弹窗、热点发现和删除确认已对齐。 |
| 应用权限 | 列表已用 `AdminListPage` 和 `AdminListTabs`。筛选、分页、权限组表单和删除确认已对齐。选人仍用共享的 `UserPickerDialog`。CSV 导入仍是隐藏文件框。 |
| 采购合同 | 列表已用 `AdminListPage` 和 `AdminListTabs`。模板、规则、审查三个页签,上传和删除确认已对齐。下载和保存参数未改。 |
---
## 9. 检测规则
ESLint 已经装在 `frontend`,配置是 `frontend/eslint.config.js`,规则是 `frontend/eslint-rules/no-legacy-admin-controls.js`。规则名 `hxops/no-legacy-admin-controls`,**当前严重级别是 `off`**。`npm run build` 和提交钩子不跑它。
`frontend/` 有改动时,Jenkins 阶段 `Frontend Lint` 会执行 `scripts/ci_frontend_lint.sh`(`npm ci` 然后 `npm run lint`)。规则仍是 `off`,这一阶段现在应当通过。生产构建阶段仍是注释掉的,lint 不在 `npm run build` 里面。
手动查看时,在 `frontend` 目录执行:
```bash
npm run lint
```
规则关闭时,这条命令应通过,不会因为历史 `<button>` 失败。
### 9.1 查什么
启用之后,检查这些文件的**全文**(不只是本次 diff):
- `frontend/src/features/admin/**/*.vue`
- `frontend/src/features/kb/components/KbAdminPanel.vue`
- `frontend/src/features/kb/components/KbGroupDrawer.vue`
命中下面任一写法就失败:
- `<button>`、`<input>`、`<select>`、`<textarea>`
- 样式类 `btn-primary`、`btn-secondary`、`btn-ghost`、`btn-danger`、`input-field`、`select-field`
- 从 `lucide-vue-next` 引入图标
对话、文档画布、冻结列表格不在上述路径里,不会被这条规则扫到。`DeleteConfirmDialog` 在 `shared/components`,也不在范围内;那个组件按自己的迁移任务换。
### 9.2 后期如何启用
等上述路径里的页面都已按本文换成 Element,再打开规则。提前打开会把尚未迁移的管理页全部判失败。
1. 打开 `frontend/eslint.config.js`,把 `hxops/no-legacy-admin-controls` 从 `'off'` 改为 `'error'`。
2. 在 `frontend` 执行 `npm run lint`,修到通过。
3. 把 `npm run lint` 接到 CI。仍然不要写进 `npm run build`,构建和风格检查分开。
4. 若以后有新的管理端 Vue 不在 §9.1 的路径里,把路径补进 `eslint.config.js` 的 `files`。禁止列表以规则文件为准,不要在文档和脚本里各写一份不同的类名。
5. 同时启用编辑器规则:打开 `.cursor/rules/element-admin-ui.mdc`,按文件里的说明加上 `globs`。现在这份规则没有 `globs`,并且 `alwaysApply` 是 false,不会在打开管理端文件时自动套用。
启用后是整文件检查。已迁移文件里再补原生按钮也会失败,不需要再维护「只查新增行」的名单。
---
## 10. 建议的切换顺序
1. §2 的变量已写入 `element-trial.css`。换下一页之前,在暗色下打开一张已换页面,看按钮、表格和弹窗是否跟着令牌变。
2. 三个试点的列表、短弹窗和应用配置创建/编辑表单内部已按 §6 收过。部门管理也已换成 `AdminListPage`。
3. 之后每个管理端列表按 §6 的清单换,一页一次,骨架用 `AdminListPage`。合并请求用 `.gitee/PULL_REQUEST_TEMPLATE.md` 里的清单。换完再开下一页。
4. §9.1 路径里的页面都换完后,按 §9.2 把 ESLint 规则改成 `error` 并接到 CI。
5. 对话、文档画布、冻结列表格不在本顺序里。
+1
View File
@@ -3,6 +3,7 @@
> **用途**:新功能、改版、修 UI 时必读。给 AI 写需求时,可将本文 **§0 Prompt 片段** 与 **§1 铁律** 一并粘贴进任务说明。
> **架构详解**:见 [DESIGN_SYSTEM.md](./DESIGN_SYSTEM.md)。
> **样式实现**:`frontend/src/styles/tokens.css`、`utilities.css`、`components-ds.css`、`style.css`。
> **管理端换 Element Plus**:正在迁移的列表和弹窗以 [ELEMENT_MIGRATION.md](./ELEMENT_MIGRATION.md) 为准。未迁移的页面仍用本文的按钮和输入框。同一块界面不要混用两套。
---
@@ -0,0 +1,76 @@
/**
* frontend/eslint-rules/no-legacy-admin-controls.js
* 用途:管理端 Vue 里禁止再写原生表单控件、旧按钮样式和 lucide 图标。
* 依赖:vue-eslint-parser 提供的 VElement、VAttribute,以及脚本里的 ImportDeclaration。
* 逻辑:由 eslint.config.js 以 hxops/no-legacy-admin-controls 挂上。当前严重级别为 off。
* 改为 error 的步骤见 docs/ui/ELEMENT_MIGRATION.md §9。
*/
const LEGACY_TAGS = new Set(['button', 'input', 'select', 'textarea']);
const LEGACY_CLASSES = [
'btn-primary',
'btn-secondary',
'btn-ghost',
'btn-danger',
'input-field',
'select-field',
];
/**
* 判断属性是不是 class 或 :class。
* 核心逻辑:静态 class 的 key 是 VIdentifier;绑定 class 的 key 是 VDirectiveKey,参数名才是 class。
* @param key vue-eslint-parser 的属性键节点
* @returns 是 class 绑定则为 true
*/
function isClassAttribute(key) {
if (key?.type === 'VIdentifier') return key.name === 'class';
return key?.type === 'VDirectiveKey' && key.argument?.name === 'class';
}
/** @type {import('eslint').Rule.RuleModule} */
const rule = {
meta: {
type: 'problem',
docs: {
description: '管理端界面使用 Element Plus,不再新增原生控件和旧样式类',
},
schema: [],
messages: {
tag: '管理端请使用 Element Plus,不要新增 <{{name}}>。见 docs/ui/ELEMENT_MIGRATION.md。',
klass: '管理端请使用 Element Plus,不要新增样式类 {{name}}。见 docs/ui/ELEMENT_MIGRATION.md。',
lucide: '管理端按钮图标请使用 @element-plus/icons-vue,不要新增 lucide-vue-next。',
},
},
create(context) {
const templateVisitor = {
VElement(node) {
const name = node.rawName || node.name;
if (!LEGACY_TAGS.has(name)) return;
context.report({ node, messageId: 'tag', data: { name } });
},
VAttribute(node) {
if (!isClassAttribute(node.key)) return;
const raw = context.sourceCode.getText(node);
for (const name of LEGACY_CLASSES) {
if (!raw.includes(name)) continue;
context.report({ node, messageId: 'klass', data: { name } });
}
},
};
const scriptVisitor = {
ImportDeclaration(node) {
if (node.source?.value !== 'lucide-vue-next') return;
context.report({ node, messageId: 'lucide' });
},
};
// 模板节点不会出现在脚本的遍历里,必须交给 vue-eslint-parser 分开访问。
const defineTemplateBodyVisitor = context.sourceCode.parserServices?.defineTemplateBodyVisitor;
if (typeof defineTemplateBodyVisitor === 'function') {
return defineTemplateBodyVisitor(templateVisitor, scriptVisitor);
}
return scriptVisitor;
},
};
export default rule;
+43
View File
@@ -0,0 +1,43 @@
/**
* frontend/eslint.config.js
* 用途:前端 ESLint 配置。目前只挂管理端 Element 迁移规则,且严重级别为 off。
* 依赖:vue-eslint-parser、typescript-eslint、eslint-rules/no-legacy-admin-controls.js。
* 逻辑:npm run lint 会加载本文件,但不会因为历史原生控件失败。
* 启用步骤见 docs/ui/ELEMENT_MIGRATION.md §9。不要把 lint 接进 npm run build。
*/
import vueParser from 'vue-eslint-parser';
import tseslint from 'typescript-eslint';
import noLegacyAdminControls from './eslint-rules/no-legacy-admin-controls.js';
export default [
{
ignores: ['dist/**', 'node_modules/**', 'coverage/**'],
},
{
files: [
'src/features/admin/**/*.vue',
'src/features/kb/components/KbAdminPanel.vue',
'src/features/kb/components/KbGroupDrawer.vue',
],
languageOptions: {
parser: vueParser,
parserOptions: {
parser: tseslint.parser,
extraFileExtensions: ['.vue'],
ecmaVersion: 'latest',
sourceType: 'module',
},
},
plugins: {
hxops: {
rules: {
'no-legacy-admin-controls': noLegacyAdminControls,
},
},
},
rules: {
// 启用时改为 'error'。步骤见 docs/ui/ELEMENT_MIGRATION.md §9。
'hxops/no-legacy-admin-controls': 'off',
},
},
];
+1461 -4
View File
File diff suppressed because it is too large. Load diff
+7
View File
@@ -7,15 +7,18 @@
"dev": "vite",
"build": "vue-tsc -b && vite build",
"preview": "vite preview",
"lint": "eslint .",
"test:unit": "vitest run"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.2",
"@tailwindcss/forms": "^0.5.11",
"@tailwindcss/typography": "^0.5.19",
"@vue-office/docx": "^1.6.3",
"@vue-office/excel": "^1.7.14",
"@vue-office/pdf": "^1.6.5",
"cron-parser": "^5.5.0",
"element-plus": "^2.14.7",
"highlight.js": "^11.11.1",
"html2pdf.js": "^0.14.0",
"lucide-vue-next": "^0.575.0",
@@ -37,12 +40,16 @@
"@vue/test-utils": "^2.4.11",
"@vue/tsconfig": "^0.8.1",
"autoprefixer": "^10.4.24",
"eslint": "^10.12.0",
"eslint-plugin-vue": "^10.11.1",
"jsdom": "^29.1.1",
"postcss": "^8.5.6",
"tailwindcss": "^3.4.17",
"typescript": "~5.9.3",
"typescript-eslint": "^8.71.2",
"vite": "^8.0.0-beta.13",
"vitest": "^4.1.8",
"vue-eslint-parser": "^10.4.1",
"vue-tsc": "^3.1.5"
},
"overrides": {
@@ -0,0 +1,62 @@
/**
* features/admin/components/AdminListPage.vue
* 用途:管理端列表页的唯一卡片骨架。标题、操作、页签、筛选、表格、分页按固定顺序和 32px 内边距排列。
* 依赖:element-plus 的加载指令、components-ds.css 的 admin-table-section / admin-table-header、element-trial.css 的分页条。
* 逻辑:AdminLayout 提供菜单和内容区外边距;各业务页把文案和控件填进插槽。本组件不请求数据。
* 用户管理、部门管理、常用问题等列表调用本组件。页签用 AdminListTabs。页签、筛选、分页没有内容时不占一行。
*/
<script setup lang="ts">
import { ElLoading } from 'element-plus';
import '@/features/admin/styles/element-trial.css';
defineProps<{
/** 首屏整卡加载。为 true 时先盖住卡片,数据回来再画出标题和表格。 */
loading?: boolean;
}>();
const vLoading = ElLoading.directive;
</script>
<template>
<section v-loading="loading" class="admin-table-section admin-list-page min-h-64">
<template v-if="!loading">
<div class="admin-table-header admin-table-header--stacked">
<div class="min-w-0">
<slot name="title" />
</div>
<slot name="actions" />
</div>
<div v-if="$slots.tabs" class="admin-list-page__tabs">
<slot name="tabs" />
</div>
<div v-if="$slots.filters" class="admin-list-page__filters">
<slot name="filters" />
</div>
<slot />
<div v-if="$slots.pagination" class="hx-admin-pager">
<slot name="pagination" />
</div>
</template>
</section>
</template>
<style scoped>
.admin-list-page__tabs {
padding: 0 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.admin-list-page__filters {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px;
padding: 16px 32px;
border-bottom: 1px solid var(--el-border-color-lighter);
}
.admin-list-page__filters :deep(.el-input),
.admin-list-page__filters :deep(.el-select) {
flex: none;
}
</style>
@@ -0,0 +1,89 @@
/**
* features/admin/components/AdminListTabs.vue
* 用途:管理端列表卡片里的页签条。只负责切换,不放表格和筛选。
* 依赖:element-plus 的 ElTabs、ElTabPane、ElTag。
* 逻辑:放进 AdminListPage 的 tabs 插槽。当前页签用 v-model 交给页面,页面再决定筛选和表格。
*/
<script setup lang="ts">
import { ElTabPane, ElTabs, ElTag } from 'element-plus';
/** 一个页签。badge 为 0 或空时不显示数字。 */
export interface AdminListTabItem {
name: string;
label: string;
badge?: number | string;
}
defineProps<{
/** 当前页签名,对应 items 里的 name。 */
modelValue: string;
items: AdminListTabItem[];
}>();
const emit = defineEmits<{
'update:modelValue': [value: string];
}>();
/**
* 把 Element 页签切换写回 v-model。
* @param name - 被点中的页签名
*/
function onTabChange(name: string | number): void {
emit('update:modelValue', String(name));
}
/**
* 数字为 0 或空时不画角标。
* @param badge - 页签上的数量
* @returns 是否显示角标
*/
function showBadge(badge: number | string | undefined): boolean {
return badge != null && badge !== '' && badge !== 0;
}
</script>
<template>
<ElTabs :model-value="modelValue" class="admin-list-tabs" @tab-change="onTabChange">
<ElTabPane v-for="item in items" :key="item.name" :name="item.name">
<template #label>
<span class="admin-list-tabs__label">
{{ item.label }}
<ElTag v-if="showBadge(item.badge)" type="warning" effect="light" size="small">
{{ item.badge }}
</ElTag>
</span>
</template>
</ElTabPane>
</ElTabs>
</template>
<style scoped>
.admin-list-tabs :deep(.el-tabs__header) {
margin-bottom: 0;
}
.admin-list-tabs :deep(.el-tabs__nav-wrap::after) {
display: none;
}
.admin-list-tabs :deep(.el-tabs__content) {
display: none;
}
.admin-list-tabs :deep(.el-tabs__item) {
height: 40px;
padding: 0 16px;
font-size: var(--el-font-size-base);
line-height: 40px;
}
.admin-list-tabs :deep(.el-tabs__active-bar + .el-tabs__item) {
padding-left: 0;
}
.admin-list-tabs__label {
display: inline-flex;
align-items: center;
gap: 6px;
}
</style>
@@ -0,0 +1,35 @@
/**
* features/admin/composables/useElementProvider.ts
* 用途:管理端 Element Plus 试点的界面语言。
* 依赖:element-plus locale、vue-i18n。
* 逻辑:UsersPage、AgentsPage、KbAdminPanel 把 elementLocale 传给 ElConfigProvider;亮暗靠 html.dark 与 Element 暗色变量,不在这里重复切换。
*/
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import zhTw from 'element-plus/es/locale/lang/zh-tw';
import en from 'element-plus/es/locale/lang/en';
import th from 'element-plus/es/locale/lang/th';
const ELEMENT_LOCALES = {
'zh-CN': zhCn,
'zh-TW': zhTw,
en,
th,
} as const;
/**
* 取当前界面语言对应的 Element Plus 语言包。
* 核心逻辑:未知语言回退简体中文。
* @returns elementLocale,随 vue-i18n 语言变化
*/
export function useElementProvider() {
const { locale } = useI18n();
const elementLocale = computed(() => {
const key = locale.value as keyof typeof ELEMENT_LOCALES;
return ELEMENT_LOCALES[key] ?? zhCn;
});
return { elementLocale };
}
@@ -2,22 +2,36 @@
* features/admin/modules/agents/AgentsPage.vue
*
* 用途:管理控制台的应用管理页,提供应用列表、创建/编辑弹窗、测试与授权入口。
* 依赖:useAgentsAdmin 业务编排、AgentFormModal/AgentTestModal/AgentPermissionModal 弹窗。
* 逻辑:页面加载后拉取应用/用户/排程数据;权限组启用后隐藏按人授权按钮。
* 依赖:useAgentsAdmin 业务编排、Element Plus 表格与按钮、AgentFormModal/AgentTestModal/AgentPermissionModal 弹窗。
* 逻辑:页面加载后先展示应用列表;目录、用户和排程在后台补齐。权限组启用后隐藏按人授权按钮。
* 列表使用 Element stripe 斑马纹。选中行浅底画在单元格上,盖过斑马纹。
*/
<script setup lang="ts">
import { computed, ref, onMounted } from 'vue';
import { ref, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Bot, Plus, SquarePen, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { Plus } from '@element-plus/icons-vue';
import {
ElButton,
ElConfigProvider,
ElEmpty,
ElLoading,
ElTable,
ElTableColumn,
ElTag,
} from 'element-plus';
import 'element-plus/dist/index.css';
import 'element-plus/theme-chalk/dark/css-vars.css';
import '@/features/admin/styles/element-trial.css';
import { useElementProvider } from '@/features/admin/composables/useElementProvider';
import AgentFormModal from './components/AgentFormModal.vue';
import AgentPermissionModal from './components/AgentPermissionModal.vue';
import AgentTestModal from './components/AgentTestModal.vue';
import { useAgentsAdmin } from './composables/useAgentsAdmin';
import { useAgentsTableColumnResize } from './composables/useAgentsTableColumnResize';
import type { AgentRow } from '@/features/admin/types/agent.types';
const { t } = useI18n();
const { elementLocale } = useElementProvider();
const vLoading = ElLoading.directive;
const {
agents,
@@ -44,8 +58,7 @@ const {
permissionAgent,
permissionUserIds,
rolesConfigured,
showDeleteConfirmDialog,
deleteConfirmMessage,
rolesChecked,
loadAll,
resetForm,
selectAgent,
@@ -63,23 +76,8 @@ const {
openPermissionModal,
togglePermissionUser,
savePermissions,
closeDeleteConfirm,
confirmDelete,
} = useAgentsAdmin();
const {
columnWidths,
tableMinWidth,
startColumnResize,
resetColumnWidths,
} = useAgentsTableColumnResize();
const tableHeaderColumns = computed(() => [
{ key: 'name', label: t('admin.agent.headers.name'), align: 'left' as const },
{ key: 'status', label: t('admin.agent.headers.status'), align: 'left' as const },
{ key: 'actions', label: t('admin.agent.headers.actions'), align: 'right' as const },
]);
/* 列表仅展示名称、状态和操作;类型/聚合/配置仍由编辑弹窗维护。 */
const formatAgentCode = (agent: AgentRow) => agent.agent_code || 'generic';
@@ -153,6 +151,23 @@ const openEditDialog = (agent: Parameters<typeof selectAgent>[0]): void => {
showFormDialog.value = true;
};
/**
* 点击表格行时打开编辑弹窗。
* 核心逻辑:Element 行对象按 id 找回完整应用,避免把表格行类型直接交给 selectAgent。
*/
const onRowClick = (row: { id?: number }): void => {
const agent = agents.value.find((item) => item.id === row.id);
if (agent) openEditDialog(agent);
};
/**
* 当前选中应用的行样式。
* 核心逻辑:编辑弹窗打开前,用 selectedAgentId 给对应行加上浅底。
*/
const agentRowClass = ({ row }: { row: AgentRow }): string => (
selectedAgentId.value === row.id ? 'agents-row-selected' : ''
);
/**
* 保存应用表单,成功后关闭弹窗。
* 核心逻辑:submitAgent 会处理校验、接口调用和列表刷新;仅在返回 true 时收起弹窗。
@@ -168,134 +183,74 @@ onMounted(() => {
</script>
<template>
<section class="admin-table-section">
<div v-if="isLoading" class="flex items-center justify-center py-20">
<div class="animate-spin rounded-full h-10 w-10 border-b-2 border-brand-600" />
<ElConfigProvider :locale="elementLocale">
<section class="admin-table-section min-h-64">
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.agent.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.agent.subtitle') }}</p>
</div>
<ElButton type="primary" :icon="Plus" @click="openCreateDialog">
{{ t('admin.agent.new') }}
</ElButton>
</div>
<template v-else>
<div class="admin-table-header admin-table-header--stacked">
<div>
<h2 class="section-title">{{ t('admin.agent.title') }}</h2>
<p class="section-desc mt-1">{{ t('admin.agent.subtitle') }}</p>
</div>
<button type="button" class="btn-primary" @click="openCreateDialog">
<Plus class="w-5 h-5" />
<span class="font-medium">{{ t('admin.agent.new') }}</span>
</button>
</div>
<div class="admin-table-wrap">
<div v-if="agents.length === 0" class="admin-table-empty">
<Bot class="w-12 h-12 mx-auto text-muted mb-3" />
<p class="text-lg text-secondary">{{ t('admin.agent.noAgents') }}</p>
</div>
<table
v-else
class="admin-table agent-list-table table-fixed w-full"
:style="{ minWidth: `${tableMinWidth}px` }"
>
<colgroup>
<col
v-for="(width, index) in columnWidths"
:key="`col-${index}`"
:style="{ width: `${width}px` }"
/>
</colgroup>
<thead>
<tr>
<th
v-for="(column, index) in tableHeaderColumns"
:key="column.key"
class="relative px-4 py-3 text-xs"
:class="column.align === 'right' ? 'text-right' : 'text-left'"
>
<span class="truncate pr-2">{{ column.label }}</span>
<button
v-if="index < tableHeaderColumns.length - 1"
type="button"
class="agent-col-resize-handle"
:title="t('admin.agent.resizeColumn')"
@mousedown.prevent="startColumnResize(index, $event)"
@dblclick.prevent="resetColumnWidths"
/>
</th>
</tr>
</thead>
<tbody>
<tr
v-for="agent in agents"
:key="agent.id"
class="group cursor-pointer"
:class="{ 'bg-blue-50/50': selectedAgentId === agent.id }"
@click="openEditDialog(agent)"
<ElEmpty v-if="!isLoading && agents.length === 0" :description="t('admin.agent.noAgents')" />
<ElTable
v-else
v-loading="isLoading"
:data="agents"
row-key="id"
class="agents-element-table hx-admin-table"
stripe
:row-class-name="agentRowClass"
@row-click="onRowClick"
>
<ElTableColumn :label="t('admin.agent.headers.name')" min-width="280">
<template #default="{ row }">
<p class="truncate" :title="(row as AgentRow).name">
{{ (row as AgentRow).name }}
</p>
<p
v-if="(row as AgentRow).description"
class="truncate hx-element-hint"
:title="(row as AgentRow).description"
>
{{ (row as AgentRow).description }}
</p>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.agent.headers.status')" width="140">
<template #default="{ row }">
<ElTag :type="(row as AgentRow).is_active ? 'success' : 'info'" effect="light">
{{ (row as AgentRow).is_active ? t('admin.status.active') : t('admin.status.disabled') }}
</ElTag>
</template>
</ElTableColumn>
<ElTableColumn :label="t('admin.agent.headers.actions')" min-width="280" align="right">
<template #default="{ row }">
<div class="inline-flex items-center justify-end" @click.stop>
<ElButton link type="primary" @click="openEditDialog(row as AgentRow)">
{{ t('admin.edit') }}
</ElButton>
<ElButton
v-if="rolesChecked && !rolesConfigured"
link
type="primary"
@click="openPermissionModal(row as AgentRow)"
>
<td class="px-4 py-4 align-middle">
<div class="agent-list-cell">
<p class="truncate text-sm font-semibold text-primary" :title="agent.name">{{ agent.name }}</p>
<p
v-if="agent.description"
class="truncate text-xs text-muted"
:title="agent.description"
>
{{ agent.description }}
</p>
</div>
</td>
<td class="px-4 py-4 align-middle">
<div class="agent-list-cell">
<span
class="inline-flex w-fit items-center gap-1.5 rounded-full border px-2.5 py-0.5 text-xs font-medium"
:class="agent.is_active ? 'border-green-100 bg-green-50 text-green-700' : 'border-default bg-surface-soft text-secondary'"
>
<span class="h-1.5 w-1.5 shrink-0 rounded-full" :class="agent.is_active ? 'bg-green-500' : 'bg-surface-strong'" />
{{ agent.is_active ? t('admin.status.active') : t('admin.status.disabled') }}
</span>
</div>
</td>
<td class="px-4 py-4 align-middle text-right">
<div class="inline-flex items-center justify-end gap-2">
<button
type="button"
class="inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap rounded-lg bg-blue-50 px-3 py-2 text-sm font-medium text-blue-600 transition-all hover:bg-blue-100"
:title="t('admin.edit')"
@click.stop="openEditDialog(agent)"
>
<SquarePen class="w-4 h-4 shrink-0" />
{{ t('admin.edit') }}
</button>
<button
v-if="!rolesConfigured"
type="button"
class="inline-flex shrink-0 items-center justify-center p-2 text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-lg transition-all"
:title="t('admin.agent.manageAccess')"
@click.stop="openPermissionModal(agent)"
>
<Users class="w-5 h-5 shrink-0" />
</button>
<button
type="button"
class="inline-flex shrink-0 items-center whitespace-nowrap p-2 text-emerald-600 bg-emerald-50 hover:bg-emerald-100 rounded-lg transition-all"
:title="t('admin.agent.test')"
@click.stop="openTestModal(agent)"
>
{{ t('admin.agent.test') }}
</button>
<button
type="button"
class="inline-flex shrink-0 items-center justify-center p-2 text-muted hover:text-red-600 hover:bg-red-50 rounded-lg transition-all"
:title="t('admin.agent.delete')"
@click.stop="deleteAgent(agent.id)"
>
<Trash2 class="w-5 h-5 shrink-0" />
</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
{{ t('admin.agent.manageAccess') }}
</ElButton>
<ElButton link type="primary" @click="openTestModal(row as AgentRow)">
{{ t('admin.agent.test') }}
</ElButton>
<ElButton link type="danger" @click="deleteAgent((row as AgentRow).id)">
{{ t('admin.agent.delete') }}
</ElButton>
</div>
</template>
</ElTableColumn>
</ElTable>
<AgentTestModal
:visible="showTestModal"
@@ -342,45 +297,16 @@ onMounted(() => {
@save="savePermissions"
@toggle-user="togglePermissionUser"
/>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:message="deleteConfirmMessage"
@confirm="confirmDelete"
@cancel="closeDeleteConfirm"
/>
</section>
</ElConfigProvider>
</template>
<style scoped>
.agent-list-table {
table-layout: fixed;
.agents-element-table :deep(.agents-row-selected td.el-table__cell) {
background: color-mix(in srgb, #0284c7 8%, var(--el-bg-color, #fff));
}
.agent-list-cell {
display: flex;
min-height: 2.5rem;
min-width: 0;
flex-direction: column;
justify-content: center;
gap: 0.125rem;
}
.agent-col-resize-handle {
position: absolute;
top: 0;
right: 0;
z-index: 1;
width: 8px;
height: 100%;
cursor: col-resize;
border: none;
background: transparent;
padding: 0;
}
.agent-col-resize-handle:hover,
.agent-col-resize-handle:active {
background-color: color-mix(in srgb, var(--border-default) 65%, transparent);
.agents-element-table :deep(.el-table__row) {
cursor: pointer;
}
</style>
@@ -2,12 +2,13 @@
* features/admin/modules/agents/components/AgentCapabilitiesConfig.vue
*
* 用途:应用管理表单中的 capabilities 能力开关面板。
* 依赖:agent.types AgentFormState、useAgentsAdminRegistry catalog 辅助函数、vue-i18n。
* 逻辑:AgentFormModal 挂载本组件;Catalog forced_capabilities 对应项只读展示。
* 依赖:element-plus 复选框、agent.types AgentFormState、useAgentsAdminRegistry catalog 辅助函数、vue-i18n。
* 逻辑:AgentFormModal 挂载本组件;Catalog forced_capabilities 对应项只读展示。内部字段已换 Element。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { ElCheckbox, ElTag } from 'element-plus';
import type { AgentCapabilities, AgentFormState } from '@/features/admin/types/agent.types';
import {
catalogForcesCapability,
@@ -41,51 +42,92 @@ const capabilityItems = computed(() => (
));
/**
* 切换 task_progress 时同步 tool_run_progress_enabled,供进度配置面板联动。
* 切换能力开关,并在任务进度上同步 tool_run_progress_enabled。
* 核心逻辑:Catalog 强制项由复选框 disabled 拦住;这里只写用户可改的布尔值。
* @param key - capabilities 字段
* @param checked - Element 复选框回传的新值
*/
const handleCapabilityChange = (key: keyof AgentCapabilities, checked: boolean) => {
props.form.capabilities[key] = checked;
const handleCapabilityChange = (key: keyof AgentCapabilities, checked: string | number | boolean) => {
const enabled = checked === true;
props.form.capabilities[key] = enabled;
if (key === 'task_progress') {
props.form.tool_run_progress_enabled = checked;
props.form.tool_run_progress_enabled = enabled;
}
};
</script>
<template>
<div class="col-span-1 md:col-span-2 rounded-2xl border border-default bg-surface-soft/40 p-4">
<div class="mb-4">
<div class="text-xs font-bold uppercase tracking-wider text-muted">
{{ t('admin.agent.capabilities.title') }}
</div>
<p class="mt-1 text-sm leading-6 text-secondary">
{{ t('admin.agent.capabilities.subtitle') }}
</p>
<div class="agent-form-span agent-form-panel">
<div class="agent-panel-head">
<div class="agent-panel-title">{{ t('admin.agent.capabilities.title') }}</div>
<p class="hx-element-hint">{{ t('admin.agent.capabilities.subtitle') }}</p>
</div>
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
<label
<div class="agent-cap-grid">
<ElCheckbox
v-for="item in capabilityItems"
:key="item.key"
class="inline-flex items-start gap-2 rounded-xl border border-default bg-white px-3 py-2 text-sm text-secondary"
:class="{ 'opacity-80': item.forced }"
:model-value="form.capabilities[item.key]"
:disabled="item.forced"
@change="handleCapabilityChange(item.key, $event)"
>
<input
v-model="form.capabilities[item.key]"
type="checkbox"
class="mt-0.5 accent-brand-600"
:disabled="item.forced"
@change="item.key === 'task_progress'
? handleCapabilityChange('task_progress', ($event.target as HTMLInputElement).checked)
: undefined"
/>
<span>
<span class="font-medium text-primary">{{ item.label }}</span>
<span class="mt-1 block text-xs leading-5 text-muted">{{ item.hint }}</span>
<span v-if="item.forced" class="mt-1 block text-xs leading-5 text-amber-600">
{{ t('admin.agent.capabilities.forcedByCatalog') }}
</span>
</span>
</label>
<span>{{ item.label }}</span>
<span class="hx-element-hint">{{ item.hint }}</span>
<ElTag v-if="item.forced" type="warning" effect="light">
{{ t('admin.agent.capabilities.forcedByCatalog') }}
</ElTag>
</ElCheckbox>
</div>
</div>
</template>
<style scoped>
.agent-form-span {
grid-column: 1 / -1;
}
.agent-form-panel {
margin-bottom: 14px;
padding: 16px;
border: 1px solid var(--el-border-color);
border-radius: var(--el-border-radius-base);
background: var(--el-fill-color-light);
}
.agent-panel-head {
margin-bottom: 12px;
}
.agent-panel-title {
color: var(--el-text-color-primary);
font-size: var(--el-font-size-base);
}
.agent-cap-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
.agent-cap-grid :deep(.el-checkbox) {
width: 100%;
height: auto;
align-items: flex-start;
margin-right: 0;
white-space: normal;
}
.agent-cap-grid :deep(.el-checkbox__label) {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
white-space: normal;
}
@media (max-width: 640px) {
.agent-cap-grid {
grid-template-columns: 1fr;
}
}
</style>
File diff suppressed because it is too large. Load diff
@@ -1,11 +1,12 @@
/**
* features/admin/modules/agents/components/AgentPermissionModal.vue
*
* 为指定 Agent 批量勾选可访问用户的权限弹窗。
* 用途:为指定应用勾选可访问用户。
* 依赖:element-plus、admin.types、agent.types。
* 逻辑:AgentsPage 传入用户和已选 id;勾选变化交给父组件 togglePermissionUser。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { ElButton, ElCheckbox, ElDialog } from 'element-plus';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type { AgentRow } from '@/features/admin/types/agent.types';
@@ -24,71 +25,68 @@ const emit = defineEmits<{
}>();
const { t } = useI18n();
/**
* 关闭弹窗。点遮罩或右上角关闭时 Element 会把打开状态写成 false。
* @param open - 对话框是否仍打开
*/
function onVisibleChange(open: boolean): void {
if (!open) emit('close');
}
</script>
<template>
<div v-if="visible && agent" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-2xl max-h-[90vh] animate-fade-in-up">
<div class="px-8 py-6 border-b border-subtle flex justify-between items-center">
<div>
<h3 class="text-lg font-bold text-primary">{{ t('admin.perm.agentModal.title') }}</h3>
<p class="text-sm text-muted">
{{ t('admin.perm.agentModal.agent') }}
<span class="font-medium text-blue-600">{{ agent.name }}</span>
</p>
</div>
<button type="button" class="btn-icon-ds rounded-full" @click="emit('close')">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<div class="flex-1 overflow-y-auto p-8">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div
v-for="user in users"
:key="user.id"
class="flex items-center gap-3 p-3 rounded-xl border transition-all cursor-pointer"
:class="selectedUserIds.includes(user.id) ? 'border-blue-200 bg-blue-50/50' : 'border-default hover-surface-soft'"
@click="emit('toggleUser', user.id)"
>
<div
class="w-5 h-5 rounded border flex items-center justify-center transition-colors"
:class="selectedUserIds.includes(user.id) ? 'bg-blue-600 border-blue-600' : 'bg-surface border-default'"
>
<svg
v-if="selectedUserIds.includes(user.id)"
xmlns="http://www.w3.org/2000/svg"
class="h-3.5 w-3.5 text-white"
viewBox="0 0 20 20"
fill="currentColor"
>
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
</svg>
</div>
<div>
<div class="font-medium text-primary text-sm">{{ user.username }}</div>
<div class="text-xs text-muted">{{ user.real_name || user.email }}</div>
</div>
</div>
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted px-8 py-6">
<button type="button" class="btn-ghost" @click="emit('close')">
{{ t('admin.cancel') }}
</button>
<button
type="button"
:disabled="isSaving"
class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
@click="emit('save')"
<ElDialog
:model-value="visible && !!agent"
:title="t('admin.perm.agentModal.title')"
width="680px"
align-center
append-to-body
:close-on-click-modal="false"
@update:model-value="onVisibleChange"
>
<template v-if="agent">
<p class="section-desc">{{ t('admin.perm.agentModal.agent') }}{{ agent.name }}</p>
<div class="agent-perm-list">
<ElCheckbox
v-for="user in users"
:key="user.id"
:model-value="selectedUserIds.includes(user.id)"
@change="emit('toggleUser', user.id)"
>
<div v-if="isSaving" class="animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent" />
{{ t('admin.perm.agentModal.save') }}
</button>
<span>{{ user.username }}</span>
<span class="hx-element-hint">{{ user.real_name || user.email }}</span>
</ElCheckbox>
</div>
</div>
</div>
</template>
<template #footer>
<ElButton @click="emit('close')">{{ t('admin.cancel') }}</ElButton>
<ElButton type="primary" :loading="isSaving" @click="emit('save')">
{{ t('admin.perm.agentModal.save') }}
</ElButton>
</template>
</ElDialog>
</template>
<style scoped>
.agent-perm-list {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px 16px;
max-height: 65vh;
margin-top: 12px;
overflow-y: auto;
}
.agent-perm-list :deep(.el-checkbox) {
align-items: flex-start;
height: auto;
margin-right: 0;
}
@media (max-width: 640px) {
.agent-perm-list {
grid-template-columns: 1fr;
}
}
</style>
Loaded 100 of 179 files, more files were not shown because too many files have changed in this diff. Show more