From 041bb73b9a79db21d1412d9f82a6a84a5b799f90 Mon Sep 17 00:00:00 2001 From: sophie Date: Wed, 14 Oct 2026 13:44:56 +0800 Subject: [PATCH 01/11] fix: update docs --- docs/platform/README.md | 1 + docs/platform/permission-model.md | 140 +++++++++++++++++++++ docs/platform/role-permission-prototype.md | 47 ------- docs/tec.md | 2 +- 4 files changed, 142 insertions(+), 48 deletions(-) create mode 100644 docs/platform/permission-model.md delete mode 100644 docs/platform/role-permission-prototype.md diff --git a/docs/platform/README.md b/docs/platform/README.md index 8fa630f4..0f385f99 100644 --- a/docs/platform/README.md +++ b/docs/platform/README.md @@ -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+ 未实施) | diff --git a/docs/platform/permission-model.md b/docs/platform/permission-model.md new file mode 100644 index 00000000..38cff601 --- /dev/null +++ b/docs/platform/permission-model.md @@ -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` 保护 | diff --git a/docs/platform/role-permission-prototype.md b/docs/platform/role-permission-prototype.md deleted file mode 100644 index 400f9289..00000000 --- a/docs/platform/role-permission-prototype.md +++ /dev/null @@ -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. **取消勾选后确认** = 回到默认普通用户。编辑「普通用户」时取消勾选忽略。 - ---- - -## 一期不做 - -- 一人多角色、按人额外加应用、在核对矩阵上打勾。 -- 部门自动映射角色(部门是组织,角色是权限包;入职/调岗由管理员选或改角色)。 -- 员工自助「申请某个应用」(若保留申请,应改为申请换角色)。 diff --git a/docs/tec.md b/docs/tec.md index 4032c315..4d19004d 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -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) From d7d4819a427fcef4a9d6003f609b8d98332e9ab4 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Wed, 14 Oct 2026 19:31:39 +0800 Subject: [PATCH 02/11] =?UTF-8?q?feat(shipping-notice):=20=E6=97=A0?= =?UTF-8?q?=E8=A1=A8=E5=A4=B4=E6=96=87=E6=A1=A3=E6=8A=BD=E5=8F=96=E5=A2=9E?= =?UTF-8?q?=E5=BC=BA=E4=B8=8E=E5=A4=8D=E6=A0=B8=E6=B7=B1=E9=93=BE=E8=BA=AB?= =?UTF-8?q?=E4=BB=BD=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增表头 OCR 救援:模板匹配落 layout_drift/no_match 时按表头带证据补洞重评候选身份,主抽取流程接入并落 identity_rescue 事实字段 - 预约号裸数字兜底:正文无表头且常规证据缺失时扫描 5/10 位纯数字候选,持久化预置、合并末段唯一/多候选裁决 - 修复复核深链仅带 run_no 时队列项显示未命名:Case 身份优先按当前工作面 displayCase 匹配队列项 - 同步抽取 Job/运行服务/候选持久化配套与 OCR 救援、预约号启发式、表头身份测试 --- .../handlers/shipping_order_extraction.py | 53 +++ .../document_candidate_persist.py | 10 + .../document_layout/order_profile_matcher.py | 42 +- .../order_profile_ocr_rescue.py | 395 ++++++++++++++++++ .../order_extraction_run_service.py | 9 + .../order_extraction_workflow.py | 13 + .../shipping_notice/order_supplement_merge.py | 200 ++++++++- .../shipping_notice/reservation_id.py | 147 ++++++- .../test_order_profile_header_identity.py | 58 ++- .../tests/test_order_profile_ocr_rescue.py | 333 +++++++++++++++ .../test_shipping_reservation_heuristic.py | 330 +++++++++++++++ .../useShippingOrderReview.spec.ts | 50 +++ .../shipping-review/useShippingOrderReview.ts | 4 + .../views/ShippingOrderReviewView.spec.ts | 17 + .../chat/views/ShippingOrderReviewView.vue | 5 +- 15 files changed, 1660 insertions(+), 6 deletions(-) create mode 100644 backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py create mode 100644 backend/tests/test_order_profile_ocr_rescue.py create mode 100644 backend/tests/test_shipping_reservation_heuristic.py diff --git a/backend/app/jobs/handlers/shipping_order_extraction.py b/backend/app/jobs/handlers/shipping_order_extraction.py index 91d0612f..8e837a71 100644 --- a/backend/app/jobs/handlers/shipping_order_extraction.py +++ b/backend/app/jobs/handlers/shipping_order_extraction.py @@ -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', diff --git a/backend/app/services/shipping_notice/document_candidate_persist.py b/backend/app/services/shipping_notice/document_candidate_persist.py index ec9a04c3..8a1141be 100644 --- a/backend/app/services/shipping_notice/document_candidate_persist.py +++ b/backend/app/services/shipping_notice/document_candidate_persist.py @@ -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,14 @@ def persist_documents_and_candidates( schema_definition=definition, ) supplement['document_id'] = int(body_doc.id) + # [裸数字兜底] 无表头数据行解析不出补充行时,预置正文裸 5/10 位数字候选; + # 是否采纳由 merge_email_supplements 在合并末段结合已提取字段值裁决。 + supplement['reservation_candidates'] = find_bare_numeric_reservation_candidates( + body_text=body_text, + 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 +689,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) diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py index afeffd64..7dfaca94 100644 --- a/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py +++ b/backend/app/services/shipping_notice/document_layout/order_profile_matcher.py @@ -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:: 原子(短语内单词不再残留);未命中的剩余单词沿用词级 原子的既有过滤(长度 >= _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::` 列表项(短语内单词不残留);未命中词按 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] = [] diff --git a/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py b/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py new file mode 100644 index 00000000..4479dbae --- /dev/null +++ b/backend/app/services/shipping_notice/document_layout/order_profile_ocr_rescue.py @@ -0,0 +1,395 @@ +""" +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 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, +) + +# 与 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 _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) + # [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 read_asset_fn is None: + from app.services.file_assets.service import read_asset_bytes + read_asset_fn = read_asset_bytes + 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 (ValueError, TypeError, KeyError, OSError): + 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 + if read_asset_fn is None: + from app.services.file_assets.service import read_asset_bytes + read_asset_fn = read_asset_bytes + _, _, 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 (ValueError, TypeError, KeyError, OSError): + # 补救属锦上添花:任何数据/环境异常都回退原判,不阻断主链。 + return match diff --git a/backend/app/services/shipping_notice/order_extraction_run_service.py b/backend/app/services/shipping_notice/order_extraction_run_service.py index 546bec50..767ffc4d 100644 --- a/backend/app/services/shipping_notice/order_extraction_run_service.py +++ b/backend/app/services/shipping_notice/order_extraction_run_service.py @@ -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,14 @@ def _build_snapshot( ) if isinstance(email_supplement, dict): email_supplement['document_id'] = int(document.id) + # [裸数字兜底] 快照冻结前按当前正文重扫裸 5/10 位数字候选; + # 合并末段结合订单已提取字段值裁决,快照重建保证与 Schema 同源。 + email_supplement['reservation_candidates'] = find_bare_numeric_reservation_candidates( + body_text=str(document.extracted_text or ''), + 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, diff --git a/backend/app/services/shipping_notice/order_extraction_workflow.py b/backend/app/services/shipping_notice/order_extraction_workflow.py index f1bb7815..5ed74fd5 100644 --- a/backend/app/services/shipping_notice/order_extraction_workflow.py +++ b/backend/app/services/shipping_notice/order_extraction_workflow.py @@ -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( diff --git a/backend/app/services/shipping_notice/order_supplement_merge.py b/backend/app/services/shipping_notice/order_supplement_merge.py index fd75403b..54fff4d1 100644 --- a/backend/app/services/shipping_notice/order_supplement_merge.py +++ b/backend/app/services/shipping_notice/order_supplement_merge.py @@ -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,182 @@ def _supplement_multi_value_conflict( } +def _iter_order_observation_values(order: dict[str, Any]) -> list[Any]: + """收集订单头 + 全部行的原始字段 Observation 值,供兜底排除集使用。""" + values: list[Any] = [] + field_groups: list[Any] = [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], +) -> set[str]: + """构造裸数字候选的排除集:订单已提取值 + 邮件补充行值 + 邮件主题标签值。 + + 核心逻辑:客户 PO 号本身就是 10 位纯数字,是启发式最大的误判源;因此除了 + 订单 Observation 原值外,还纳入 Reservation/PO 两种归一变体(千分位、x.0、 + 前导零),并排除主题里「PO xxx」等带标签数字(Q10 双保险)。 + """ + excluded: set[str] = set() + raw_values = _iter_order_observation_values(order) + 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 _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 + if _order_has_reservation_value(order, ids): + return + excluded = _heuristic_excluded_values(order, supplement) | claimed + surviving, status = filter_reservation_heuristic_candidates(candidates, excluded_values=excluded) + if status == 'none': + return + 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 +671,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 diff --git a/backend/app/services/shipping_notice/reservation_id.py b/backend/app/services/shipping_notice/reservation_id.py index 5a837afb..8fdc7d3b 100644 --- a/backend/app/services/shipping_notice/reservation_id.py +++ b/backend/app/services/shipping_notice/reservation_id.py @@ -2,9 +2,11 @@ services/shipping_notice/reservation_id.py 用途:提取、标准化并校验发货通知与库存中的 Reservation ID。 -依赖:正则表达式与标准 `typing` 工具。 +依赖:正则表达式与标准 `typing` 工具;裸数字兜底扫描惰性依赖版面 HTML 网格解析。 逻辑:由 notice_lines、inventory_snapshot、match、extract、EML 补充解析等多个模块复用; 归一结果恒为 5/10 位纯数字(可剥括号备注、@ 前缀、短数字行序后缀如 35354-1)。 + 另提供「裸数字兜底」:正文无表头且常规证据缺失时,扫描排除后的 5/10 位 + 纯数字候选(供 order_supplement_merge 在合并末段做唯一/多候选裁决)。 """ from __future__ import annotations @@ -30,6 +32,17 @@ PR_NUMBER_LINE_RE = re.compile( r"PR\s*Number\s*[::]?\s*([^\n\r]+)", re.IGNORECASE, ) +# [裸数字兜底] 独立的 5/10 位纯数字 token;前后不能紧贴数字,防止从更长数字串截取。 +BARE_NUMERIC_RESERVATION_RE = re.compile(r"(? str: @@ -151,3 +164,135 @@ 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 _heuristic_context_snippet(text: str, match: re.Match[str]) -> str: + """截取 token 所在行命中国的前后片段,供复核面板展示证据上下文。""" + start = max(match.start() - 40, 0) + end = min(match.end() + 40, len(text)) + return text[start:end].strip() + + +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 find_bare_numeric_reservation_candidates( + *, + body_text: str = "", + html_tables: list[str] | None = None, + content_hash: str = "", +) -> list[dict[str, Any]]: + """扫描正文中的裸 5/10 位纯数字预约单号候选(排除带业务标签的数字)。 + + AI 触发时机:EML 正文数据行没有表头、常规表头契约解析不出预约单号时, + 在补充事实里预置候选列表;真正「是否采纳」由 order_supplement_merge 在 + 合并末段结合已提取字段值裁决,本函数绝不直接写入订单。 + + 核心逻辑:先扫 HTML 表格单元格(保留 DOM cell_id 证据),再扫纯文本行 + (保留行号与上下文片段);紧跟 PO/订单/发票/数量标签的数字串不作为候选; + 同值只保留首个证据;总数截断到 MAX_HEURISTIC_RESERVATION_CANDIDATES。 + + Args: + body_text: EML 正文纯文本(含展平的数据行)。 + html_tables: 正文顶层 HTML 表格片段列表;可为空。 + content_hash: 正文 Document 内容哈希,用于稳定 cell_id。 + + Returns: + list[dict]: ``[{value, evidence}]``;evidence 含 table_index/row_index/ + column_index/cell_id/raw_value,纯文本候选另含 context。扫描不到返回空列表。 + """ + candidates: list[dict[str, Any]] = [] + seen: set[str] = set() + + def _collect(text: str, base_evidence: dict[str, Any]) -> None: + excluded_spans = [item.span() for item in LABELED_NON_RESERVATION_RE.finditer(text)] + for match in BARE_NUMERIC_RESERVATION_RE.finditer(text): + if any(start <= match.start() and match.end() <= end for start, end in excluded_spans): + continue + value = match.group() + if value in seen or len(candidates) >= MAX_HEURISTIC_RESERVATION_CANDIDATES: + continue + seen.add(value) + evidence = {**base_evidence, 'raw_value': value} + if 'cell_id' not in evidence: + evidence['cell_id'] = f"reservation-heuristic:{content_hash}:line{evidence.get('row_index')}" + evidence['context'] = _heuristic_context_snippet(text, match) + candidates.append({'value': value, 'evidence': evidence}) + + for cell_text, base_evidence in _iter_heuristic_cell_texts(html_tables, content_hash): + _collect(cell_text, dict(base_evidence)) + for line_index, line in enumerate(str(body_text or '').splitlines()): + if line.strip(): + _collect(line, {'table_index': None, 'row_index': line_index + 1, 'column_index': None}) + 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' diff --git a/backend/tests/test_order_profile_header_identity.py b/backend/tests/test_order_profile_header_identity.py index b9ffaa49..eb2d0da5 100644 --- a/backend/tests/test_order_profile_header_identity.py +++ b/backend/tests/test_order_profile_header_identity.py @@ -11,7 +11,8 @@ tests/test_order_profile_header_identity.py 逻辑:pure_unit;别名命中产出 field:: 标记原子(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'] diff --git a/backend/tests/test_order_profile_ocr_rescue.py b/backend/tests/test_order_profile_ocr_rescue.py new file mode 100644 index 00000000..e00377cd --- /dev/null +++ b/backend/tests/test_order_profile_ocr_rescue.py @@ -0,0 +1,333 @@ +""" +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_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 diff --git a/backend/tests/test_shipping_reservation_heuristic.py b/backend/tests/test_shipping_reservation_heuristic.py new file mode 100644 index 00000000..277de2dc --- /dev/null +++ b/backend/tests/test_shipping_reservation_heuristic.py @@ -0,0 +1,330 @@ +"""验证 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_row(): + """截图 1:无表头数据行只识别 4000122230;仓库/料号/日期/供应商号不误报。""" + row = 'DBS SLC 4000122230 6233 504-006075-001 D4-AR1200163A1 Welltrust 10/13/2026' + candidates = find_bare_numeric_reservation_candidates(body_text=row, content_hash='h') + # 断言:仅 10 位纯数字 4000122230 入选;4 位站点号、带连字符料号、日期均被长度/边界挡住。 + assert [item['value'] for item in candidates] == ['4000122230'] + assert candidates[0]['evidence']['row_index'] == 1 + assert candidates[0]['evidence']['cell_id'].startswith('reservation-heuristic:h:line') + + +def test_scan_finds_five_digit_reservation(): + """截图 3:5 位候选 39739 同样可识别。""" + row = 'DBS PHX01 39739 6233 504-006055-001 D4-A08AR12000002 WEL 10/12/2026' + candidates = find_bare_numeric_reservation_candidates(body_text=row, content_hash='h') + assert [item['value'] for item in candidates] == ['39739'] + + +def test_scan_rejects_labeled_context_and_wrong_lengths(): + """标签上下文(PO/Invoice/Qty/紧凑 PO12345)排除;4/6/11/13 位数字不入选。""" + text = ( + 'PO# 1000053337\n' + 'Purchase Order : 1000053286\n' + 'Invoice 1234567890\n' + 'Qty 10000\n' + 'PO39739\n' + 'ref 1234 123456 12345678901 1234567890123\n' + 'valid 4000122230' + ) + candidates = find_bare_numeric_reservation_candidates(body_text=text, content_hash='h') + # 断言:只有裸露的 10 位 4000122230 幸存;带标签数字与错误长度全部排除。 + assert [item['value'] for item in candidates] == ['4000122230'] + + +def test_scan_accepts_short_numeric_suffix_form(): + """35354-1 短行序后缀形态:本体 35354 作为候选(归一由合并端处理)。""" + candidates = find_bare_numeric_reservation_candidates(body_text='IR# 35354-1', content_hash='h') + # 断言:35354 后跟 "-"(非数字)满足边界;IR# 标签不在排除标签清单内。 + assert [item['value'] for item in candidates] == ['35354'] + + +def test_scan_dedupes_and_caps_candidates(): + """同值只留首个证据;候选总数截断到上限,防止引用链刷爆快照。""" + text = '\n'.join(['4000122230'] + [f'{30000 + index}' for index in range(30)]) + candidates = find_bare_numeric_reservation_candidates(body_text=text, content_hash='h') + values = [item['value'] for item in candidates] + # 断言:30 个不同 5 位数字 + 1 个 10 位数字共 31 个 token,但只保留前 20 个。 + assert len(values) == 20 + assert values.count('4000122230') == 1 + + +def test_scan_uses_dom_cell_evidence_for_html_tables(): + """HTML 表格单元格候选携带 DOM 级 cell_id,供复核证据回溯。""" + html = '
10000533374000122230
' + candidates = find_bare_numeric_reservation_candidates( + body_text='', html_tables=[html], content_hash='dom123', + ) + assert [item['value'] for item in candidates] == ['1000053337', '4000122230'] + # 断言:表格路径证据含 table_index/column_index/cell_id(DOM 定位),无 context 片段。 + evidence = candidates[1]['evidence'] + assert evidence['table_index'] == 0 + assert evidence['column_index'] == 1 + assert evidence['cell_id'].startswith('reservation-heuristic:dom123:0') + + +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] diff --git a/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts b/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts index 78704e4f..c1caf135 100644 --- a/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts +++ b/frontend/src/features/chat/shipping-review/useShippingOrderReview.spec.ts @@ -408,6 +408,56 @@ describe('useShippingOrderReview build eligibility writes', () => { }); + it('records the auto-selected Case when a deep link carries only run_no (formal downstream)', async () => { + + // 用户场景:历史记录等入口以 run_no 直链进入(URL 无 case_no/task_no),且唯一 + // 文件已确认建单、处于正式下游阶段(选法 2 不拉 Case 快照)。 + // 关键断言:自动选中的 CASE-1 必须落入 requestedCaseNo,否则 displayCase/ + // activeReviewNavItem 无身份 → 任务详情不加载 → 五阶段页签全锁死 + 标题「未命名」。 + + api.getRun.mockResolvedValue({ + + run_no: 'RUN-1', + + items: [{ + + case_no: 'CASE-1', document_id: 1, file_name: 'po.pdf', status: 'confirmed', + + has_formal_ot: true, lifecycle_stage: 'freight_upload', confirmed_task_no: 'OT-1', + + }], + + }); + + api.getQueue.mockResolvedValue({ + + summary: { total: 1, needs_action: 0, processing: 0, completed: 1 }, + + items: [{ + + case_no: 'CASE-1', source_run_no: 'RUN-1', document_id: 1, file_name: 'po.pdf', + + status: 'confirmed', has_formal_ot: true, lifecycle_stage: 'freight_upload', + + confirmed_task_no: 'OT-1', issue_count: 0, available_actions: [], + + }], + + }); + + const review = useShippingOrderReview(); + + await review.load('RUN-1'); + + expect(review.requestedCaseNo.value).toBe('CASE-1'); + + // 选法 2:正式下游仍不得拉取 Case 快照。 + + expect(api.getCase).not.toHaveBeenCalled(); + + }); + + it('does not prefetch PDF preview on load or selectCase; ensurePreviewLoaded fetches on demand', async () => { // 关键断言:进入工作台/切换文档不触发 preview 审计与下载。 const review = useShippingOrderReview(); diff --git a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts index a879ed9a..51fe3b31 100644 --- a/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts +++ b/frontend/src/features/chat/shipping-review/useShippingOrderReview.ts @@ -1156,6 +1156,10 @@ export function useShippingOrderReview(options: { if (generation !== caseLoadGeneration) return; // [STREAM] Run 替代不等于其内全部 PDF 替代;当前文件只由队列 Stream 裁决。 const caseNo = preferredCaseNo || queue.items[0]?.case_no || run.items[0]?.case_no; + // [深链自愈] 历史记录切换等入口可能只带 run_no 进入(URL 无 case_no/task_no); + // 自动选中的 Case 必须回写 requestedCaseNo,否则正式下游(选法 2 不拉 Case)下 + // displayCase/activeReviewNavItem 无身份,任务详情不加载、五阶段页签全锁死。 + if (!preferredCaseNo) requestedCaseNo.value = caseNo || null; // [选法 2] 正式任务下游阶段(通知准备/货代上传/通知完成)本阶段不拉复核编辑器 // (Case 快照 + Evidence),改由任务详情 + 统一投影驱动;进入「订单复核」才补拉。 const navItem = (queue.items || run.items).find( diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts b/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts index f4c70d99..b21de571 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.spec.ts @@ -945,6 +945,23 @@ describe('ShippingOrderReviewView layout phase 1', () => { expect((wrapper.vm as any).$route.query.case_no).toBe('CASE-NEW'); }); + it('falls back to the requested Case identity for the header order summary on run_no-only deep links', async () => { + // 用户场景:历史记录切换生成的深链只带 mode+run_no(无 case_no/task_no)。 + // 关键断言:标题订单摘要按 displayCase 身份(requestedCaseNo)匹配队列项, + // 展示文件名与 Case 号;不得因 URL 缺 case 参数而退化为「未命名」。 + const previousRequestedCaseNo = requestedCaseNo.value; + requestedCaseNo.value = 'CASE-1'; + try { + const wrapper = await mountView(); + const summary = wrapper.find('[data-testid="review-selected-order-summary"]'); + expect(summary.exists()).toBe(true); + expect(summary.text()).toContain('po.pdf'); + expect(summary.text()).toContain('CASE-1'); + } finally { + requestedCaseNo.value = previousRequestedCaseNo; + } + }); + it('opens the replacement Case at its backend current stage after reparse completes', async () => { const originalQueue = reviewQueue.value; try { diff --git a/frontend/src/features/chat/views/ShippingOrderReviewView.vue b/frontend/src/features/chat/views/ShippingOrderReviewView.vue index da9f1948..52739b99 100644 --- a/frontend/src/features/chat/views/ShippingOrderReviewView.vue +++ b/frontend/src/features/chat/views/ShippingOrderReviewView.vue @@ -2301,8 +2301,11 @@ const processDetailPoNumber = computed(() => { * 改源到任务级」计划(E)一并收敛。 */ const selectedOrderSummary = computed(() => { + // 深链可能只带 run_no(历史记录切换等入口);此时 Case 身份在 requestedCaseNo → + // displayCase 上,必须优先按当前工作面身份匹配队列项,不能因 URL 缺 case 而显示「未命名」。 const activeNo = String( - route.query.case || route.query.case_no + displayCase.value?.case_no + || route.query.case || route.query.case_no || '', ).trim(); const item = reviewQueue.value?.items?.find((candidate) => candidate.case_no === activeNo) From 5f6fbcd76fd813d57b7a7a862210124e89473ceb Mon Sep 17 00:00:00 2001 From: sophie Date: Wed, 14 Oct 2026 20:25:35 +0800 Subject: [PATCH 03/11] =?UTF-8?q?feat:=20element=20plus=20UI=E7=BB=84?= =?UTF-8?q?=E4=BB=B6=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- .gitee/PULL_REQUEST_TEMPLATE.md | 23 + Jenkinsfile | 16 + docs/README.md | 1 + docs/ui/ELEMENT_MIGRATION.md | 248 +++ docs/ui/UI_CODING_GUIDELINES.md | 1 + .../eslint-rules/no-legacy-admin-controls.js | 76 + frontend/eslint.config.js | 43 + frontend/package-lock.json | 1465 ++++++++++++++++- frontend/package.json | 7 + .../admin/composables/useElementProvider.ts | 35 + .../admin/modules/agents/AgentsPage.vue | 288 ++-- .../agents/components/AgentFormModal.vue | 64 +- .../components/AgentPermissionModal.vue | 128 +- .../agents/components/AgentTestModal.vue | 125 +- .../agents/composables/useAgentsAdmin.ts | 61 +- .../admin/modules/users/UsersPage.vue | 510 +++--- .../users/components/BatchEditUserModal.vue | 110 +- .../users/components/BatchPermissionModal.vue | 100 +- .../users/components/UserFormModal.vue | 287 ++-- .../users/composables/useUsersAdmin.ts | 111 +- .../features/admin/styles/element-trial.css | 110 ++ .../kb/components/DifyHealthDialog.vue | 140 +- .../kb/components/DifySettingsDialog.vue | 344 +++- .../features/kb/components/KbAdminPanel.vue | 411 +++-- .../features/kb/components/KbGroupDrawer.vue | 132 +- frontend/src/locales/en/kb.json | 23 +- frontend/src/locales/th/kb.json | 23 +- frontend/src/locales/zh-CN/kb.json | 23 +- frontend/src/locales/zh-TW/kb.json | 23 +- scripts/ci_frontend_lint.sh | 20 + 30 files changed, 3621 insertions(+), 1327 deletions(-) create mode 100644 .gitee/PULL_REQUEST_TEMPLATE.md create mode 100644 docs/ui/ELEMENT_MIGRATION.md create mode 100644 frontend/eslint-rules/no-legacy-admin-controls.js create mode 100644 frontend/eslint.config.js create mode 100644 frontend/src/features/admin/composables/useElementProvider.ts create mode 100644 frontend/src/features/admin/styles/element-trial.css create mode 100644 scripts/ci_frontend_lint.sh diff --git a/.gitee/PULL_REQUEST_TEMPLATE.md b/.gitee/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..b7096080 --- /dev/null +++ b/.gitee/PULL_REQUEST_TEMPLATE.md @@ -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` 通过。 + +## 测试 + + diff --git a/Jenkinsfile b/Jenkinsfile index 71f4561a..e0402622 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -353,6 +353,22 @@ pipeline { } } + stage('Frontend Lint') { + when { + expression { env.FRONTEND_CHANGED == 'true' } + } + steps { + echo '[Frontend Lint] FRONTEND_CHANGED=true,执行 npm run lint(Element 规则当前为 off)' + sh ''' + set -e + docker run --rm \ + -v "${WORKSPACE}:/repo" \ + -w /repo \ + node:22-alpine sh -c "chmod +x scripts/ci_frontend_lint.sh && ./scripts/ci_frontend_lint.sh" + ''' + } + } + // stage('Frontend Build (CI)') { // when { // expression { env.FRONTEND_CHANGED == 'true' } diff --git a/docs/README.md b/docs/README.md index 652851e6..de17406a 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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 集成说明 | diff --git a/docs/ui/ELEMENT_MIGRATION.md b/docs/ui/ELEMENT_MIGRATION.md new file mode 100644 index 00000000..71a28932 --- /dev/null +++ b/docs/ui/ELEMENT_MIGRATION.md @@ -0,0 +1,248 @@ +# Element Plus 迁移规范 + +> **用途**:管理端页面从手写 Tailwind 控件换成 Element Plus 时的唯一操作说明。后续每换一页,按本文做,不要再单页发明一套间距、字号或按钮写法。 +> **适用**:管理控制台里已经或即将换成 Element 的列表、筛选、表格、表单弹窗。 +> **不适用**:对话、文档画布、冻结列宽表(订单交期回复、发货审核等)。这些仍走 [UI_CODING_GUIDELINES.md](./UI_CODING_GUIDELINES.md),不要在同一块界面里混用两套按钮和输入框。 +> **试点**:用户管理、应用配置、知识库分组。列表和短弹窗已按本文收过。应用配置的创建/编辑表单内部还没换完,见 §8。新页面以本文为准。 + +旧页面在换完之前,继续遵守 [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` 时,在 ` diff --git a/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue b/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue index edae52d5..ff4cb499 100644 --- a/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue +++ b/frontend/src/features/admin/modules/agents/components/AgentFormModal.vue @@ -2,14 +2,15 @@ * features/admin/modules/agents/components/AgentFormModal.vue * * 用途:应用管理新增/编辑弹窗,集中承载 Agent 基础信息(含启用状态)、Dify/Iframe 配置和常见问题表单。 - * 依赖:agent.types AgentFormState、schedule.types ScheduleTask、AgentToolRunProgressConfig、vue-i18n。 - * 逻辑:父组件控制 visible/isEditing/isSaving 与保存;本组件直接编辑传入的 form(含 is_active),并通过事件通知关闭、保存、增删常见问题。 + * 依赖:element-plus 对话框、agent.types AgentFormState、schedule.types ScheduleTask、AgentToolRunProgressConfig、vue-i18n。 + * 逻辑:父组件控制 visible/isEditing/isSaving 与保存;外壳是 680px 对话框。表单内部字段仍沿用原有输入控件。 */ + + diff --git a/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue b/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue index 2b5d3685..de2ce1a2 100644 --- a/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue +++ b/frontend/src/features/admin/modules/agents/components/AgentPermissionModal.vue @@ -1,11 +1,12 @@ /** * features/admin/modules/agents/components/AgentPermissionModal.vue - * - * 为指定 Agent 批量勾选可访问用户的权限弹窗。 + * 用途:为指定应用勾选可访问用户。 + * 依赖:element-plus、admin.types、agent.types。 + * 逻辑:AgentsPage 传入用户和已选 id;勾选变化交给父组件 togglePermissionUser。 */ - + + diff --git a/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue b/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue index 7ef7d6f4..3affcf1d 100644 --- a/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue +++ b/frontend/src/features/admin/modules/agents/components/AgentTestModal.vue @@ -1,11 +1,12 @@ /** * features/admin/modules/agents/components/AgentTestModal.vue - * - * Agent 连通性测试弹窗:展示请求 URL、输出信息与分析结果。 + * 用途:应用连通性测试弹窗,展示请求地址、输出和分析结果。 + * 依赖:element-plus、agent.types。 + * 逻辑:AgentsPage 传入当前应用和测试结果;重新测试由父组件发起。 */ - + + diff --git a/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts b/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts index 0eb5e7a2..ac7bf631 100644 --- a/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts +++ b/frontend/src/features/admin/modules/agents/composables/useAgentsAdmin.ts @@ -4,10 +4,12 @@ * Agent 管理模块的业务逻辑:列表 CRUD、连通性测试、权限分配。 * 从原 AdminView.vue 的 agents 相关 script 抽取,供 AgentsPage 使用。 * 权限组启用后拒绝打开按人授权弹窗,提示改到应用权限页的角色包。 + * 删除确认使用 Element MessageBox。 */ import { ref, computed } from 'vue'; import { useI18n } from 'vue-i18n'; +import { ElMessageBox } from 'element-plus'; import { createAdminAgent, deleteAdminAgent, @@ -238,6 +240,7 @@ export function useAgentsAdmin() { const contentProfileOptions = ref([]); const users = ref([]); const rolesConfigured = ref(false); + const rolesChecked = ref(false); const scheduleTasks = ref([]); const trainingExamPdfGuides = ref([]); const isLoading = ref(true); @@ -256,9 +259,6 @@ export function useAgentsAdmin() { const permissionAgent = ref(null); const permissionUserIds = ref([]); - const showDeleteConfirmDialog = ref(false); - const deleteConfirmMessage = ref(''); - let deleteConfirmAction: (() => Promise | void) | null = null; const activeUsers = () => users.value.filter((u) => u.status !== 'pending'); @@ -336,6 +336,8 @@ export function useAgentsAdmin() { } catch (e) { console.error('Error loading permission roles:', e); rolesConfigured.value = false; + } finally { + rolesChecked.value = true; } }; @@ -364,18 +366,25 @@ export function useAgentsAdmin() { } }; + /** + * 进入页面时先拉应用列表,再在后台补齐编辑弹窗要用的目录、用户和排程。 + * 核心逻辑:加载遮罩只等应用列表。权限组、用户、排程和目录在后台拉取,未返回时不盖住表格。 + */ const loadAll = async (): Promise => { isLoading.value = true; - await Promise.all([ + try { + await loadAgents(); + } finally { + isLoading.value = false; + } + void Promise.all([ loadRegistrySchema(), loadIntentRouteOptions(), loadContentProfileOptions(), - loadAgents(), loadUsers(), loadRolesConfigured(), loadScheduleTasks(), ]); - isLoading.value = false; }; const resetForm = (): void => { @@ -405,27 +414,26 @@ export function useAgentsAdmin() { void loadTrainingExamPdfGuides(agent.id); }; - const openDeleteConfirm = ( + /** + * 用 Element 确认框询问后再执行删除。 + * 核心逻辑:取消时 MessageBox 会 reject,这里吞掉,不调用 action。 + * @param message - 确认文案 + * @param action - 用户点确定后执行的删除 + */ + const openDeleteConfirm = async ( message: string, action: () => Promise | void, - ): void => { - deleteConfirmMessage.value = message; - deleteConfirmAction = action; - showDeleteConfirmDialog.value = true; - }; - - const closeDeleteConfirm = (): void => { - showDeleteConfirmDialog.value = false; - deleteConfirmAction = null; - }; - - const confirmDelete = async (): Promise => { - if (!deleteConfirmAction) return; + ): Promise => { try { - await deleteConfirmAction(); - } finally { - closeDeleteConfirm(); + await ElMessageBox.confirm(message, t('common.deleteDialog.defaultTitle'), { + type: 'warning', + confirmButtonText: t('common.deleteDialog.confirm'), + cancelButtonText: t('common.deleteDialog.cancel'), + }); + } catch { + return; } + await action(); }; /** @@ -613,7 +621,7 @@ export function useAgentsAdmin() { }; const deleteAgent = async (id: number): Promise => { - openDeleteConfirm(t('admin.agent.confirmDelete'), async () => { + await openDeleteConfirm(t('admin.agent.confirmDelete'), async () => { try { await deleteAdminAgent(id); await loadAgents(); @@ -723,6 +731,7 @@ export function useAgentsAdmin() { contentProfileOptions, users, rolesConfigured, + rolesChecked, scheduleTasks, trainingExamPdfGuides, activeUsers, @@ -739,8 +748,6 @@ export function useAgentsAdmin() { showPermissionModal, permissionAgent, permissionUserIds, - showDeleteConfirmDialog, - deleteConfirmMessage, loadAll, resetForm, selectAgent, @@ -758,7 +765,5 @@ export function useAgentsAdmin() { openPermissionModal, togglePermissionUser, savePermissions, - closeDeleteConfirm, - confirmDelete, }; } diff --git a/frontend/src/features/admin/modules/users/UsersPage.vue b/frontend/src/features/admin/modules/users/UsersPage.vue index 18e152cf..4e3c403b 100644 --- a/frontend/src/features/admin/modules/users/UsersPage.vue +++ b/frontend/src/features/admin/modules/users/UsersPage.vue @@ -1,24 +1,43 @@ /** * features/admin/modules/users/UsersPage.vue * 用途:用户管理独立页面(服务端筛选分页、用户/部门列排序、批量操作)。 - * 依赖:useUsersAdmin、SortableTableHeader、PaginationBar、用户相关 Modal、adminRoleLabel、getUserAvatarLabel。 - * 逻辑:路由 /admin/users;列表经 listAdminUsersPage 按页拉取;权限组启用后只选角色、关闭按人授权。 + * 依赖:useUsersAdmin、useElementProvider、element-plus、用户相关 Modal、adminRoleLabel、getUserAvatarLabel。 + * 逻辑:路由 /admin/users;本页是 Element Plus 试点,筛选、表格、分页、工具栏和三个业务弹窗走组件库。 + * 删除和改角色用 Element 确认框。列表经 listAdminUsersPage 按页拉取。 */ + + diff --git a/frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue b/frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue index 65ad5bb9..1dd94abe 100644 --- a/frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue +++ b/frontend/src/features/admin/modules/users/components/BatchEditUserModal.vue @@ -1,17 +1,19 @@ /** * features/admin/modules/users/components/BatchEditUserModal.vue * 用途:批量编辑用户部门/角色/状态弹窗。权限组启用后角色下拉读权限组列表。 - * 依赖:admin.types、permissionRole.types、user.types、roleLabel.LEGACY_ROLE_OPTIONS。 - * 逻辑:UsersPage 传入角色列表;未选字段表示保持不变。 + * 依赖:element-plus、admin.types、permissionRole.types、user.types、roleLabel.LEGACY_ROLE_OPTIONS。 + * 逻辑:UsersPage 传入角色列表;未选字段表示保持不变。本弹窗属于用户管理 Element Plus 试点。 */ diff --git a/frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue b/frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue index 79901833..06f9f658 100644 --- a/frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue +++ b/frontend/src/features/admin/modules/users/components/BatchPermissionModal.vue @@ -1,9 +1,21 @@ /** * features/admin/modules/users/components/BatchPermissionModal.vue - * 批量分配/移除用户 Agent 权限弹窗。 + * 用途:批量分配、移除或覆盖用户 Agent 权限。 + * 依赖:element-plus、admin.types、user.types。 + * 逻辑:UsersPage 传入已选人数与 Agent 列表;动作为 add / remove / set。本弹窗属于用户管理 Element Plus 试点。 */ diff --git a/frontend/src/features/admin/modules/users/components/UserFormModal.vue b/frontend/src/features/admin/modules/users/components/UserFormModal.vue index 525b7ab8..62117c80 100644 --- a/frontend/src/features/admin/modules/users/components/UserFormModal.vue +++ b/frontend/src/features/admin/modules/users/components/UserFormModal.vue @@ -1,17 +1,30 @@ /** * features/admin/modules/users/components/UserFormModal.vue * 用途:创建/编辑用户弹窗。权限组启用后只选角色,不再按人勾应用或功能权限。 - * 依赖:admin.types、user.types、permissionRole.types、roleLabel.LEGACY_ROLE_OPTIONS。 - * 逻辑:UsersPage 传入角色列表;未种子权限组时保留历史 Agent / 培训 HR 勾选,角色下拉用旧枚举。 + * 依赖:element-plus、admin.types、user.types、permissionRole.types、roleLabel.LEGACY_ROLE_OPTIONS。 + * 逻辑:UsersPage 传入角色列表;未种子权限组时保留历史 Agent / 功能权限勾选,角色下拉用旧枚举。 + * 本弹窗属于用户管理 Element Plus 试点。 */ + + diff --git a/frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts b/frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts index ef412f38..bceab23b 100644 --- a/frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts +++ b/frontend/src/features/admin/modules/users/composables/useUsersAdmin.ts @@ -3,10 +3,12 @@ * 用途:用户管理模块业务逻辑(CRUD、服务端筛选分页、用户/部门列排序、批量操作)。 * 依赖:admin.api、useMessage、useTableSort、permissionRole.types。 * 逻辑:UsersPage 调用本 composable;列表经 listAdminUsersPage 按页拉取,排序参数随请求下发。 - * 权限组启用后创建用户预填默认角色,改角色须确认;批量按人授权入口关闭。 + * 权限组启用后创建用户预填默认角色;删除和改角色用 Element 确认框。批量按人授权入口关闭。 + * Element Plus 表格通过 applyServerSort 写入列排序。 */ import { computed, ref, watch } from 'vue'; import { useI18n } from 'vue-i18n'; +import { ElMessageBox } from 'element-plus'; import { batchDeleteAdminUsers, batchUpdateAdminPermissions, @@ -68,10 +70,6 @@ export function useUsersAdmin() { const showUserModal = ref(false); const editingUser = ref(createEmptyUserForm()); const originalUserRole = ref('user'); - const showRoleConfirm = ref(false); - const roleConfirmMessage = ref(''); - let pendingUserSave: (() => Promise) | null = null; - let pendingBatchSave: (() => Promise) | null = null; const showBatchEditModal = ref(false); const batchEditForm = ref({ department: '', role: '', status: '' }); @@ -79,9 +77,6 @@ export function useUsersAdmin() { const showBatchPermissionModal = ref(false); const batchPermissionForm = ref({ agent_ids: [], action: 'add' }); - const showDeleteConfirmDialog = ref(false); - const deleteConfirmMessage = ref(''); - let deleteConfirmAction: (() => Promise | void) | null = null; /** 当前页是否已全部选中 */ const allPaginatedUsersSelected = computed( @@ -194,25 +189,41 @@ export function useUsersAdmin() { }, 300); }, { deep: true }); - const openDeleteConfirm = (message: string, action: () => Promise | void): void => { - deleteConfirmMessage.value = message; - deleteConfirmAction = action; - showDeleteConfirmDialog.value = true; - }; - - const closeDeleteConfirm = (): void => { - showDeleteConfirmDialog.value = false; - deleteConfirmAction = null; + /** + * 用 Element 确认框询问后再执行删除。 + * 核心逻辑:取消时 MessageBox 会 reject,这里吞掉,不调用 action。 + * @param message - 确认文案 + * @param action - 用户点确定后执行的删除 + */ + const openDeleteConfirm = async (message: string, action: () => Promise | void): Promise => { + try { + await ElMessageBox.confirm(message, t('common.deleteDialog.defaultTitle'), { + type: 'warning', + confirmButtonText: t('common.deleteDialog.confirm'), + cancelButtonText: t('common.deleteDialog.cancel'), + }); + } catch { + return; + } + await action(); }; /** - * 执行待确认的删除操作。 - * 核心逻辑:先快照 action 并立即关闭弹窗,再 await 删除与刷新,避免异步完成前弹窗无法关闭。 + * 用 Element 确认框询问改角色,确定后执行保存。 + * 核心逻辑:与删除确认同一组件,避免一页两种确认框。取消则不保存。 + * @param message - 角色变更说明 + * @param action - 用户点确定后提交 */ - const confirmDelete = async (): Promise => { - const action = deleteConfirmAction; - closeDeleteConfirm(); - if (!action) return; + const confirmRoleThen = async (message: string, action: () => Promise): Promise => { + try { + await ElMessageBox.confirm(message, t('admin.permRoles.userRoleConfirmTitle'), { + type: 'warning', + confirmButtonText: t('admin.save'), + cancelButtonText: t('admin.cancel'), + }); + } catch { + return; + } await action(); }; @@ -296,11 +307,10 @@ export function useUsersAdmin() { : nextRole !== originalUserRole.value; const touchesAdmin = isAdminRoleCode(nextRole) || isAdminRoleCode(originalUserRole.value); if (roleChanged) { - roleConfirmMessage.value = touchesAdmin + const message = touchesAdmin ? t('admin.permRoles.userAdminConfirm') : t('admin.permRoles.userRoleConfirm', { role: nextRole }); - pendingUserSave = persistUser; - showRoleConfirm.value = true; + await confirmRoleThen(message, persistUser); return; } await persistUser(); @@ -348,28 +358,6 @@ export function useUsersAdmin() { } }; - /** - * 确认改角色(含管理员)后再提交。 - */ - const confirmRoleChange = async (): Promise => { - const userSave = pendingUserSave; - const batchSave = pendingBatchSave; - pendingUserSave = null; - pendingBatchSave = null; - showRoleConfirm.value = false; - if (userSave) { - await userSave(); - return; - } - if (batchSave) await batchSave(); - }; - - const closeRoleConfirm = (): void => { - pendingUserSave = null; - pendingBatchSave = null; - showRoleConfirm.value = false; - }; - const cleanRejectedUsers = async (): Promise => { openDeleteConfirm(t('admin.user.confirmClean'), async () => { try { @@ -446,11 +434,10 @@ export function useUsersAdmin() { return; } if (data.role) { - roleConfirmMessage.value = isAdminRoleCode(data.role) + const message = isAdminRoleCode(data.role) ? t('admin.permRoles.userAdminConfirm') : t('admin.permRoles.batchRoleConfirm'); - pendingBatchSave = () => persistBatchEdit(data); - showRoleConfirm.value = true; + await confirmRoleThen(message, () => persistBatchEdit(data)); return; } await persistBatchEdit(data); @@ -504,6 +491,19 @@ export function useUsersAdmin() { scheduleLoadUsers(true); }; + /** + * 按指定列和方向重新查询第一页。 + * 核心逻辑:方向未变时不请求;变更后回到第一页再拉取。 + * @param key - username 或 department,与后端 sort_by 白名单一致 + * @param dir - asc 或 desc + */ + const applyServerSort = (key: UserSortKey, dir: 'asc' | 'desc'): void => { + if (sortKey.value === key && sortDir.value === dir) return; + sortKey.value = key; + sortDir.value = dir; + scheduleLoadUsers(true); + }; + return { users, agents, @@ -530,12 +530,9 @@ export function useUsersAdmin() { batchEditForm, showBatchPermissionModal, batchPermissionForm, - showDeleteConfirmDialog, - deleteConfirmMessage, - showRoleConfirm, - roleConfirmMessage, loadAll, toggleSort, + applyServerSort, openCreateUserModal, openEditUserModal, saveUser, @@ -547,9 +544,5 @@ export function useUsersAdmin() { openBatchPermissionModal, submitBatchEdit, submitBatchPermission, - closeDeleteConfirm, - confirmDelete, - confirmRoleChange, - closeRoleConfirm, }; } diff --git a/frontend/src/features/admin/styles/element-trial.css b/frontend/src/features/admin/styles/element-trial.css new file mode 100644 index 00000000..bf659079 --- /dev/null +++ b/frontend/src/features/admin/styles/element-trial.css @@ -0,0 +1,110 @@ +/** + * features/admin/styles/element-trial.css + * 用途:管理端 Element Plus 的字体、字号、颜色、圆角、控件高度,以及和 Tailwind 共存的修正。 + * 依赖:tokens.css 的 --text-* / --bg-* / --border-*,element-plus 暗色变量,Tailwind preflight。 + * 逻辑:由 UsersPage、AgentsPage、KbAdminPanel 在暗色 CSS 之后引入,所以 html.dark 能盖过 Element 默认暗色。 + * 字号和颜色以本文变量为准。页面不要再用 text-sm / text-muted 改表格和按钮。 + */ + +:root, +html.dark { + --el-color-primary: #0284c7; + --el-color-primary-light-3: #4da3d6; + --el-color-primary-light-5: #81c2e3; + --el-color-primary-light-7: #b4daf0; + --el-color-primary-light-8: #cde6f4; + --el-color-primary-light-9: #e6f3fa; + --el-color-primary-dark-2: #0269a0; + --el-font-family: "PingFang SC", "Microsoft YaHei", "Segoe UI", system-ui, sans-serif; + --el-font-size-extra-large: 20px; + --el-font-size-large: 18px; + --el-font-size-medium: 16px; + --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-text-color-disabled: var(--text-muted); + --el-border-color: var(--border-default); + --el-border-color-light: var(--border-subtle); + --el-border-color-lighter: var(--border-subtle); + --el-bg-color: var(--bg-surface); + --el-bg-color-overlay: var(--bg-surface); + --el-fill-color-blank: var(--bg-surface); + --el-fill-color-light: var(--bg-surface-soft); + --el-border-radius-base: 8px; + --el-component-size: 32px; +} + +.el-button { + display: inline-flex; + align-items: center; + justify-content: center; +} + +.el-button .el-icon, +.el-button svg { + display: inline-flex; + flex: none; +} + +/* Tailwind forms 会给单行输入框内部的 input 加边框。聚焦时左右两边会多出两条蓝线。 + 多行输入框的边框就画在 .el-textarea__inner 上,不能一起清掉。 */ +.el-input__inner, +.el-select__input, +.el-range-input, +.el-input__inner:hover, +.el-select__input:hover, +.el-range-input:hover, +.el-input__inner:focus, +.el-select__input:focus, +.el-range-input:focus { + border: 0; + outline: none; + background-color: transparent; + box-shadow: none; + --tw-ring-shadow: 0 0 #0000; + --tw-ring-offset-shadow: 0 0 #0000; +} + +.el-textarea__inner { + background-color: var(--el-input-bg-color, var(--el-fill-color-blank)); + box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset; +} + +.el-textarea__inner:hover { + box-shadow: 0 0 0 1px var(--el-input-hover-border-color, var(--el-border-color-hover)) inset; +} + +.el-textarea__inner:focus { + outline: none; + box-shadow: 0 0 0 1px var(--el-input-focus-border-color, var(--el-color-primary)) inset; + --tw-ring-shadow: 0 0 #0000; + --tw-ring-offset-shadow: 0 0 #0000; +} + +/* 列表首尾列与页头 32px 对齐;分页贴在表格下方 */ +.hx-admin-table .el-table__cell:first-child .cell { + padding-left: 32px; +} + +.hx-admin-table .el-table__cell:last-child .cell { + padding-right: 32px; +} + +.hx-admin-pager { + display: flex; + justify-content: flex-end; + padding: 12px 32px; + border-top: 1px solid var(--el-border-color-lighter); +} + +/* 表单里的补充说明,字号和颜色走 Element 变量 */ +.hx-element-hint { + margin-top: 4px; + font-size: var(--el-font-size-extra-small); + line-height: 1.4; + color: var(--el-text-color-secondary); +} diff --git a/frontend/src/features/kb/components/DifyHealthDialog.vue b/frontend/src/features/kb/components/DifyHealthDialog.vue index 07db0375..7c66faf5 100644 --- a/frontend/src/features/kb/components/DifyHealthDialog.vue +++ b/frontend/src/features/kb/components/DifyHealthDialog.vue @@ -1,16 +1,20 @@  + + diff --git a/frontend/src/features/kb/components/DifySettingsDialog.vue b/frontend/src/features/kb/components/DifySettingsDialog.vue index d5f5d604..d642a5a6 100644 --- a/frontend/src/features/kb/components/DifySettingsDialog.vue +++ b/frontend/src/features/kb/components/DifySettingsDialog.vue @@ -2,17 +2,34 @@ /** * features/kb/components/DifySettingsDialog.vue * 用途:提供知识库 Dify 连接及默认同步参数的查看、编辑和保存界面。 - * 依赖:Vue 响应式 API、Vue I18n、kb.api 的 Dify 设置读写接口。 - * 逻辑:KbAdminPanel 控制弹窗开关;本组件加载或保存设置后通过事件把结果反馈给父组件。 + * 依赖:Vue 响应式 API、Element Plus、Vue I18n、kb.api 的 Dify 设置读写接口。 + * 逻辑:KbAdminPanel 控制弹窗开关;本组件加载或保存设置后通过事件把结果反馈给父组件。表单按连接、检索、分段三块排,密钥默认遮挡;开关行按左标题、开关、右标题、数字四列对齐。 */ -import { reactive, ref, watch } from 'vue'; +import { reactive, ref, useId, watch } from 'vue'; import { useI18n } from 'vue-i18n'; +import { + ElButton, + ElDialog, + ElForm, + ElFormItem, + ElInput, + ElInputNumber, + ElLoading, + ElOption, + ElSelect, + ElSwitch, +} from 'element-plus'; import { getKbDifySettings, updateKbDifySettings } from '../api/kb.api'; const props = defineProps<{ open: boolean }>(); const emit = defineEmits<{ close: []; saved: [message: string]; error: [message: string] }>(); const { t } = useI18n(); +const vLoading = ElLoading.directive; +const rerankLabelId = useId(); +const topKLabelId = useId(); +const scoreSwitchLabelId = useId(); +const scoreValueLabelId = useId(); const loading = ref(false); const saving = ref(false); @@ -108,94 +125,243 @@ watch(() => props.open, (open) => { + + diff --git a/frontend/src/features/kb/components/KbAdminPanel.vue b/frontend/src/features/kb/components/KbAdminPanel.vue index 4ee393e1..1cefd037 100644 --- a/frontend/src/features/kb/components/KbAdminPanel.vue +++ b/frontend/src/features/kb/components/KbAdminPanel.vue @@ -2,28 +2,33 @@ /** * features/kb/components/KbAdminPanel.vue * 知识库配置面板(治理面:分组、Dify)。 - * 依赖:kb.api、DifySettingsDialog、DifyHealthDialog、DeleteConfirmDialog、Vue I18n。 - * 逻辑:管理控制台加载知识库分组;分组列表在主表格过滤排序,新增/编辑通过右侧抽屉提交。 + * 依赖:kb.api、Element Plus、DifySettingsDialog、DifyHealthDialog、Vue I18n。 + * 逻辑:管理控制台加载知识库分组;列表、表头排序、文档数筛选、分页和删除确认用 Element。排序和筛选都作用在全量数据上,再分页。新增/编辑走 KbGroupDrawer。 */ import { computed, onMounted, ref, watch } from 'vue'; import { useRouter } from 'vue-router'; import { useI18n } from 'vue-i18n'; +import { CircleCheck, Plus, Search, Setting, Tools } from '@element-plus/icons-vue'; import { - Activity, - Pencil, - Plus, - RefreshCw, - Search, - Settings, - Trash2, - Wrench, -} from 'lucide-vue-next'; + ElAlert, + ElButton, + ElConfigProvider, + ElInput, + ElLoading, + ElMessageBox, + ElPagination, + ElSpace, + ElTable, + ElTableColumn, +} 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 KbGroupDrawer, { type KbGroupFormValue } from './KbGroupDrawer.vue'; import DifyHealthDialog from './DifyHealthDialog.vue'; import DifySettingsDialog from './DifySettingsDialog.vue'; -import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue'; -import PaginationBar from '@/shared/components/PaginationBar.vue'; import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes'; import { createKbGroup, @@ -35,35 +40,42 @@ import { import { formatDateTime } from '../utils/kb-display.utils'; type GroupFilterMode = 'all' | 'withDocs' | 'empty'; -type GroupSortMode = 'updatedDesc' | 'updatedAsc' | 'docsDesc' | 'docsAsc' | 'nameAsc'; +type GroupSortKey = 'name' | 'document_count' | 'updated_at'; const router = useRouter(); const { t } = useI18n(); +const { elementLocale } = useElementProvider(); +const vLoading = ElLoading.directive; const groups = ref([]); const isSubmitting = ref(false); const isDeleting = ref(false); -const isRefreshing = ref(false); +const isRefreshing = ref(true); const editingGroupId = ref(null); const form = ref({ name: '', description: '' }); const feedback = ref(''); const feedbackType = ref<'success' | 'error' | ''>(''); const settingsDialogOpen = ref(false); const healthDialogOpen = ref(false); -const deleteDialogOpen = ref(false); const drawerOpen = ref(false); -const deletingGroup = ref(null); const searchKeyword = ref(''); const filterMode = ref('all'); -const sortMode = ref('updatedDesc'); +const sortKey = ref('updated_at'); +const sortDir = ref<'asc' | 'desc' | ''>('desc'); const currentPage = ref(1); const pageSize = ref(20); -const filterOptions: GroupFilterMode[] = ['all', 'withDocs', 'empty']; -const sortOptions: GroupSortMode[] = ['updatedDesc', 'updatedAsc', 'docsDesc', 'docsAsc', 'nameAsc']; const pageSizeOptions = [10, 20, 50, 100]; -const totalDocuments = computed(() => groups.value.reduce((total, group) => total + (group.document_count ?? 0), 0)); +/** + * 文档数表头筛选项。 + * 核心逻辑:不放「全部」;Element 筛选面板的重置会清空条件,等同于全部。 + */ +const documentFilters = computed(() => [ + { text: t('kbAdmin.filters.withDocs'), value: 'withDocs' }, + { text: t('kbAdmin.filters.empty'), value: 'empty' }, +]); + const filteredGroups = computed(() => { const keyword = searchKeyword.value.trim().toLowerCase(); const matched = groups.value.filter((group) => { @@ -77,16 +89,17 @@ const filteredGroups = computed(() => { return matchesKeyword && matchesFilter; }); + if (!sortKey.value || !sortDir.value) return matched; return [...matched].sort((a, b) => { - const docsA = a.document_count ?? 0; - const docsB = b.document_count ?? 0; - const updatedA = Date.parse(a.updated_at || '') || 0; - const updatedB = Date.parse(b.updated_at || '') || 0; - if (sortMode.value === 'updatedAsc') return updatedA - updatedB; - if (sortMode.value === 'docsDesc') return docsB - docsA; - if (sortMode.value === 'docsAsc') return docsA - docsB; - if (sortMode.value === 'nameAsc') return a.name.localeCompare(b.name, undefined, { numeric: true }); - return updatedB - updatedA; + let result = 0; + if (sortKey.value === 'name') { + result = a.name.localeCompare(b.name, undefined, { numeric: true }); + } else if (sortKey.value === 'document_count') { + result = (a.document_count ?? 0) - (b.document_count ?? 0); + } else { + result = (Date.parse(a.updated_at || '') || 0) - (Date.parse(b.updated_at || '') || 0); + } + return sortDir.value === 'asc' ? result : -result; }); }); const pagedGroups = computed(() => { @@ -94,19 +107,33 @@ const pagedGroups = computed(() => { return filteredGroups.value.slice(start, start + pageSize.value); }); +/** + * 表格空状态文案。 + * 核心逻辑:一个分组都没有时提示去创建;有分组但筛选后为空时提示调整条件。 + */ +const tableEmptyText = computed(() => ( + groups.value.length === 0 ? t('kbAdmin.groupsEmpty') : t('kbAdmin.filters.emptyResult') +)); + /** 格式化分组更新时间,避免管理台表格直接暴露后端 ISO 时间字符串。 */ const formatGroupUpdatedAt = (value?: string | null) => formatDateTime(value); -/** 加载知识库治理页的分组数据,供页面初始渲染和操作后刷新复用。 */ +/** + * 加载知识库治理页的分组数据,供页面初始渲染和操作后刷新复用。 + * 核心逻辑:只等分组列表;失败写入页面提示,并用 finally 关掉表格加载态。 + */ const loadData = async () => { isRefreshing.value = true; - const groupsResult = await getKbGroupsSafe(); - if (groupsResult.ok) groups.value = groupsResult.data; - else { - feedback.value = groupsResult.error || t('kbAdmin.msg.loadGroupsFailed'); - feedbackType.value = 'error'; + try { + const groupsResult = await getKbGroupsSafe(); + if (groupsResult.ok) groups.value = groupsResult.data; + else { + feedback.value = groupsResult.error || t('kbAdmin.msg.loadGroupsFailed'); + feedbackType.value = 'error'; + } + } finally { + isRefreshing.value = false; } - isRefreshing.value = false; }; /** 重置分组表单到新建状态,关闭抽屉或切换新建时清空当前编辑对象。 */ @@ -162,17 +189,27 @@ const handleSubmitGroup = async () => { await loadData(); }; -/** 打开分组删除确认弹窗,确认前不直接调用删除接口。 */ -const handleDeleteGroup = (group: KbGroup) => { - deletingGroup.value = group; - deleteDialogOpen.value = true; -}; - -/** 确认删除当前选中的分组,并在成功后同步刷新列表与编辑表单状态。 */ -const handleDeleteGroupConfirm = async () => { - if (!deletingGroup.value) return; +/** + * 确认后删除分组,并刷新列表。 + * 核心逻辑:Element 确认框取消会 reject,这里直接返回,不调用删除接口。 + * @param group - 待删除的分组 + */ +const handleDeleteGroup = async (group: KbGroup) => { + try { + await ElMessageBox.confirm( + t('kbAdmin.deleteDialog.message', { name: group.name }), + t('kbAdmin.deleteDialog.title'), + { + type: 'warning', + confirmButtonText: t('common.deleteDialog.confirm'), + cancelButtonText: t('common.deleteDialog.cancel'), + }, + ); + } catch { + return; + } isDeleting.value = true; - const result = await deleteKbGroup(deletingGroup.value.id); + const result = await deleteKbGroup(group.id); isDeleting.value = false; if (!result.ok) { feedback.value = result.error || t('kbAdmin.msg.deleteFailed'); @@ -180,15 +217,46 @@ const handleDeleteGroupConfirm = async () => { return; } - if (editingGroupId.value === deletingGroup.value.id) closeDrawer(); + if (editingGroupId.value === group.id) closeDrawer(); feedback.value = t('kbAdmin.msg.deleted'); feedbackType.value = 'success'; - deleteDialogOpen.value = false; - deletingGroup.value = null; await loadData(); }; -watch([searchKeyword, filterMode, sortMode, pageSize], () => { +/** + * 按文档数表头筛选全部分组,并回到第一页。 + * 核心逻辑:筛选发生在分页之前。未选或重置时显示全部;单选时只留有文档或空分组。 + * @param filters - Element 按 column-key 给出的已选值 + */ +function onFilterChange(filters: Record): void { + const selected = filters.document_count ?? []; + if (selected.length === 1 && (selected[0] === 'withDocs' || selected[0] === 'empty')) { + filterMode.value = selected[0]; + } else { + filterMode.value = 'all'; + } + currentPage.value = 1; +} + +/** + * 按表头把筛选后的全部分组重排,并回到第一页。 + * 核心逻辑:排序发生在分页之前,所以翻页后顺序不变。第三次点击表头时 Element 清空排序,列表回到接口原顺序。 + * @param payload.prop - 列字段 + * @param payload.order - ascending、descending 或空 + */ +function onSortChange(payload: { prop: string | null; order: string | null }): void { + const field = payload.prop; + if ((field === 'name' || field === 'document_count' || field === 'updated_at') && payload.order) { + sortKey.value = field; + sortDir.value = payload.order === 'ascending' ? 'asc' : 'desc'; + } else { + sortKey.value = ''; + sortDir.value = ''; + } + currentPage.value = 1; +} + +watch([searchKeyword, pageSize], () => { currentPage.value = 1; }); @@ -200,142 +268,98 @@ defineExpose({ loadData }); + + diff --git a/frontend/src/features/kb/components/KbGroupDrawer.vue b/frontend/src/features/kb/components/KbGroupDrawer.vue index 5c50922d..d665a9ed 100644 --- a/frontend/src/features/kb/components/KbGroupDrawer.vue +++ b/frontend/src/features/kb/components/KbGroupDrawer.vue @@ -1,14 +1,16 @@