diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index fa662e01..c31eda1f 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -20,7 +20,7 @@ from flask import Blueprint, Response, current_app, g, request, send_file from app import db from app.core.auth.jwt import get_current_user -from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError +from app.core.errors import AppError, ConflictError, NotFoundError, UnauthorizedError, ValidationError from app.core.response import ok from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask from app.services.shipping_notice.chat_actions import build_chat_actions_payload @@ -2198,6 +2198,88 @@ def workspace_confirm_shipping_order_review_customer(case_no: str): )) +@workspace_shipping_notice_bp.route( + '/shipping-notice/order-review-cases//customer/rebind', + methods=['POST'], +) +def workspace_rebind_shipping_order_review_customer(case_no: str): + """ + 确认客户改绑:直接修改已确认的客户识别结果并刷新订单快照客户。 + + Body: customer_id, expected_order_data_version, reason? + 仅当订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无活动 Gate Attempt, + 即发货通知/Excel 未产生)时允许;版本乐观锁与状态守卫在服务层 fail-closed。 + """ + user = _require_user() + data = request.get_json(silent=True) or {} + try: + customer_id = int(data.get('customer_id')) + except (TypeError, ValueError) as exc: + raise ValidationError( + 'Customer id is required', + code='SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED', + details={'field': 'customer_id'}, + ) from exc + try: + expected_order_data_version = int(data.get('expected_order_data_version')) + except (TypeError, ValueError) as exc: + raise ValidationError( + 'Expected order data version is required', + code='SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED', + details={'field': 'expected_order_data_version'}, + ) from exc + + from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer + from app.services.shipping_notice.order_review_customer_service import ( + project_review_case_customer_resolution, + ) + from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit + from app.services.shipping_notice.order_review_projection import serialize_review_case + from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot + + case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or '')) + if case is None: + raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND') + formal = resolve_formal_ot(case) + if not formal.get('has_formal_ot') or formal.get('task') is None: + raise ConflictError( + 'A formal order task is required before rebinding customer', + code='SHIPPING.FORMAL_OT_REQUIRED', + details={'task_missing': bool(formal.get('task_missing'))}, + ) + + result = rebind_confirmed_customer( + task=formal['task'], + new_customer_id=customer_id, + actor_id=int(user.id), + expected_order_data_version=expected_order_data_version, + reason=str(data.get('reason') or '').strip() or None, + ) + db.session.commit() + + resolution = result['resolution'] + rebind_record = next( + ( + item.get('rebind') for item in (resolution.evidence_json or []) + if isinstance(item, dict) and item.get('rebind') + ), + None, + ) or {} + refreshed_case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or '')) + return _ok({ + 'case': serialize_review_case(refreshed_case) if refreshed_case is not None else None, + 'customer_resolution': ( + project_review_case_customer_resolution(refreshed_case) + if refreshed_case is not None else None + ), + 'rebind': { + 'previous_customer_id': rebind_record.get('previous_customer_id'), + 'customer_id': int(resolution.confirmed_customer_id), + 'snapshot_id': int(result['snapshot'].id), + }, + }) + + @workspace_shipping_notice_bp.route( '/shipping-notice/order-review-cases//reservation/revalidate', methods=['POST'], diff --git a/backend/app/services/shipping_notice/customer_resolution_service.py b/backend/app/services/shipping_notice/customer_resolution_service.py index 93ab18fa..d5cefe88 100644 --- a/backend/app/services/shipping_notice/customer_resolution_service.py +++ b/backend/app/services/shipping_notice/customer_resolution_service.py @@ -1,10 +1,13 @@ """ services/shipping_notice/customer_resolution_service.py -用途:提供订单任务的唯一客户识别结果读取与确认入口。 -依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer。 +用途:提供订单任务的唯一客户识别结果读取、确认与确认后改绑入口。 +依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer、 + ShippingNotice、ShippingOrderSnapshot、order_edit_window_service、order_freeze_service、audit_service。 逻辑:客户身份来自已发布规则生成的证据快照;订单字段(包括 bill_to)只能作为证据, - 不能承担客户角色或流程门禁真相。 + 不能承担客户角色或流程门禁真相。确认后改绑(rebind_confirmed_customer)仅在订单 + 编辑窗 header 可编辑(无 Export Artifact 且无活动 Gate Attempt)时允许直接修改 + 确认结果,并原地刷新冻结快照客户(快照表 uq task_id 唯一约束决定不可另建新行)。 """ from __future__ import annotations @@ -14,7 +17,14 @@ from typing import Any from app import db from app.core.errors import ConflictError, NotFoundError, ValidationError -from app.models import ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderTask +from app.models import ( + ShippingCustomer, + ShippingCustomerShadowResolution, + ShippingNotice, + ShippingOrderCandidate, + ShippingOrderSnapshot, + ShippingOrderTask, +) def resolution_for_task(task: Any) -> ShippingCustomerShadowResolution | None: @@ -74,3 +84,265 @@ def confirm_customer_resolution( resolution.status = 'confirmed' db.session.flush() return resolution + + +# 改绑后 audit 事件类型:已纳入 progress_audit_contract.REVIEW_WORKBENCH_AUDIT_EVENT_TYPES +# 冻结字典(review_* snake_case 命名;review_customer_confirmed 专指首次确认,改绑独立成码)。 +REBIND_AUDIT_EVENT_TYPE = 'review_customer_rebound' + + +def _order_notice_for_task(task: Any) -> ShippingNotice | None: + """回读该正式订单的任一通知作为编辑窗谓词入口;editable_scope 会按 order_task_id 聚合全部通知。""" + return ( + ShippingNotice.query + .filter(ShippingNotice.order_task_id == int(task.id)) + .order_by(ShippingNotice.id.asc()) + .first() + ) if getattr(task, 'id', None) is not None else None + + +def _review_case_no_for_task(task: Any) -> str | None: + """ + 经建单确认修订反查正式任务所属复核 Case 编号(order_edit_window_service 同款反查模式)。 + + 核心逻辑:ShippingOrderReviewConfirmedRevision.case_id → ShippingOrderReviewCase.case_no, + 取最新一条修订;无修订(历史数据)时返回 None,审计事件照常落库。 + """ + from app.models import ShippingOrderReviewCase, ShippingOrderReviewConfirmedRevision + + if getattr(task, 'id', None) is None: + return None + row = ( + db.session.query(ShippingOrderReviewCase.case_no) + .join( + ShippingOrderReviewConfirmedRevision, + ShippingOrderReviewConfirmedRevision.case_id == ShippingOrderReviewCase.id, + ) + .filter(ShippingOrderReviewConfirmedRevision.task_id == int(task.id)) + .order_by(ShippingOrderReviewConfirmedRevision.id.desc()) + .first() + ) + return str(row[0]).strip() or None if row is not None else None + + +def _assert_rebind_window_open(task: Any) -> None: + """ + 改绑编辑窗守卫(fail-closed):header 不可编辑即拒绝,不区分原因放行。 + + 核心逻辑:editable_scope(order_task)['header'] = 全部通知无 Export Artifact 且无活动 + Gate Attempt;尚无通知的未发货订单视为可编辑。details 区分 excel_exists / active_attempt + 供前端定位(“已产生发货通知/Excel,请先走撤销流程” vs 系统处理中)。 + """ + from app.services.shipping_notice import order_edit_window_service as order_edit_window + + notice = _order_notice_for_task(task) + if notice is None: + return + scope = order_edit_window.editable_scope(notice) + if bool(scope.get('header')): + return + excel_exists = any( + order_edit_window._notice_has_export_artifact(item) + for item in order_edit_window._order_notices(notice) + ) + active_attempt = order_edit_window.order_has_active_attempt(notice) + raise ConflictError( + 'Customer rebind is blocked after shipping notice or Excel generation', + code='SHIPPING.CUSTOMER_REBIND_BLOCKED', + details={'excel_exists': excel_exists, 'active_attempt': active_attempt}, + ) + + +def rebind_allowed_for_task(task: Any) -> bool: + """ + 判定正式任务当前是否允许改绑确认客户(工作台「修改客户」按钮谓词,只读 fail-closed)。 + + 核心逻辑:识别结果已确认,且编辑窗 header 可编辑(全部通知无 Export Artifact 且 + 无活动 Gate Attempt)。与 rebind_confirmed_customer 守卫①②同源;并发语义由 API 层 + expected_order_data_version 承担,此处为只读投影不下发并发状态。 + + Args: + task: 正式任务(ShippingOrderTask/ShippingNotice,按 resolution_for_task 语义解析)。 + + Returns: + True 表示当前可改绑;False 表示未确认、Excel 已产生或存在活动 Attempt。 + """ + row = resolution_for_task(task) + if row is None or row.status != 'confirmed' or not row.confirmed_customer_id: + return False + notice = _order_notice_for_task(task) + if notice is None: + return True + from app.services.shipping_notice import order_edit_window_service as order_edit_window + + return bool(order_edit_window.editable_scope(notice).get('header')) + + +def _append_rebind_audit( + *, + task: Any, + previous_customer_id: int, + new_customer: ShippingCustomer, + actor_id: int, + reason: str | None, +) -> None: + """写改绑审计事件:before/after 携带原/新确认客户(键须命中审计快照白名单),并挂 review_case_no 供 Case 时间线查询。""" + from app.services.shipping_notice.audit_service import append_shipping_audit_event + + task_no = str(getattr(task, 'task_no', '') or '') + version = int(getattr(task, 'order_data_version', 0) or 1) + append_shipping_audit_event( + event_type=REBIND_AUDIT_EVENT_TYPE, + aggregate_type='shipping_task', + aggregate_id=task_no, + task_no=task_no, + review_case_no=_review_case_no_for_task(task), + actor_type='user', + actor_id=int(actor_id), + action='rebind_confirmed_customer', + result='success', + reason=str(reason or '').strip() or None, + before={'previous_value': previous_customer_id, 'task_no': task_no, 'order_data_version': version}, + after={'new_value': int(new_customer.id), 'task_no': task_no, 'order_data_version': version}, + metadata={ + 'previous_customer_id': int(previous_customer_id), + 'confirmed_customer_id': int(new_customer.id), + }, + ) + + +def _refresh_frozen_snapshot_customer(task: Any, customer: ShippingCustomer) -> ShippingOrderSnapshot | None: + """ + 原地刷新冻结快照的订购客户事实(customer_id / 客户简称)。 + + 核心逻辑:快照表对 task_id 有唯一约束(uq_shipping_order_snapshots_task),且快照行身份 + 被 Notice 行 / 波次行 / 库存匹配以 snapshot_line_id 引用,因此改绑不能删行重建,只能按 + 新客户刷新客户身份字段;单头模板文本(customer_code/customer_name 等单据原文事实)不动。 + """ + snapshot_id = getattr(task, 'order_snapshot_id', None) + if not snapshot_id: + return None + snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) + if snapshot is None: + return None + snapshot.customer_id = int(customer.id) + snapshot.customer_short_code_snapshot = str(getattr(customer, 'short_code', None) or '') + db.session.flush() + return snapshot + + +def rebind_confirmed_customer( + task: Any, + *, + new_customer_id: int, + actor_id: int, + expected_order_data_version: int, + reason: str | None = None, +) -> dict[str, Any]: + """ + 确认客户改绑:直接修改已确认的客户识别结果并刷新冻结快照客户。 + + 核心逻辑:守卫顺序固定 fail-closed——⓪客户端乐观锁版本比较(expected_order_data_version + 必填,与任务当前 order_data_version 不一致即 409,写任何数据之前执行,保证冲突零副作用; + freeze 对已冻结任务幂等早退、不重复做版本校验,故版本比较只在此处);①识别结果已确认 + (未确认走既有确认流程);②订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无 + 活动 Gate Attempt,即发货通知/Excel 未产生);③新客户存在、启用且 ≠ 当前确认客户。 + 通过后更新确认结果(追加 rebind 证据记录,保持 evidence_json 与 identity_rule_set_checksum + 非空冻结契约)、写审计、原地刷新快照客户,最后按 freeze 契约复核并返回快照。 + + Args: + task: 正式订单任务 ShippingOrderTask(经 candidate_id 反查唯一识别结果)。 + new_customer_id: 目标标准客户 id;必须存在且启用。 + actor_id: 执行改绑的用户 id(必填,审计与 manual 冻结要求)。 + expected_order_data_version: 客户端读到的订单数据版本;与任务当前版本不一致时拒绝, + 防止并发编辑被静默覆盖(对齐 wave 路由 expected_draft_version 模式)。 + reason: 可选改绑原因;进入证据记录、审计与确认原因链。 + + Returns: + dict: {'resolution': 更新后的识别结果行, 'snapshot': 客户已刷新的冻结快照}。 + + Raises: + ValidationError: 缺少执行人(SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED,内部调用契约)。 + ConflictError: 订单数据版本不一致(SHIPPING.ORDER_DATA_VERSION_MISMATCH)、识别结果 + 未确认(SHIPPING.CUSTOMER_RESOLUTION_REQUIRED)、编辑窗关闭 + (SHIPPING.CUSTOMER_REBIND_BLOCKED,details 含 excel_exists/active_attempt)、 + 新客户停用(SHIPPING.CUSTOMER_INACTIVE)或与当前客户相同 + (SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER)。 + NotFoundError: 目标客户不存在(SHIPPING.CUSTOMER_NOT_FOUND)。 + """ + if not actor_id: + # 内部调用契约缺失(非编辑窗状态),与 SHIPPING.CUSTOMER_REBIND_BLOCKED 的 A 管控语义区分。 + raise ValidationError('Customer rebind requires an operator', code='SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED') + + # [STEP 1] 守卫⓪:客户端版本比较在写任何数据之前执行;freeze 幂等早退不重复校验。 + actual_version = int(getattr(task, 'order_data_version', 0) or 1) + if actual_version != int(expected_order_data_version): + raise ConflictError( + 'Order data version has changed', + code='SHIPPING.ORDER_DATA_VERSION_MISMATCH', + details={'expected': int(expected_order_data_version), 'actual': actual_version}, + ) + + # [STEP 2] 守卫①:识别结果已确认(未确认走既有识别候选确认流程,不在此补确认)。 + resolution = resolution_for_task(task) + if ( + resolution is None or str(resolution.status or '') != 'confirmed' + or resolution.confirmed_customer_id is None + ): + raise ConflictError( + 'Confirmed customer resolution is required before rebind', + code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED', + ) + + # [STEP 3] 守卫②:编辑窗 header 谓词(发货通知/Excel 已产生或系统处理中即拒绝)。 + _assert_rebind_window_open(task) + + # [STEP 4] 守卫③:新客户存在、启用且 ≠ 当前确认客户。 + customer = db.session.get(ShippingCustomer, int(new_customer_id)) + if customer is None: + raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND') + if str(customer.status or '') != 'active': + raise ConflictError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE') + previous_customer_id = int(resolution.confirmed_customer_id) + if int(customer.id) == previous_customer_id: + raise ConflictError( + 'Rebind target equals the current confirmed customer', + code='SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER', + ) + + # [STEP 5] 更新确认结果:追加 rebind 证据记录(保留原识别证据;checksum 契约不动)。 + resolution.confirmed_customer_id = int(customer.id) + resolution.evidence_json = [ + *(list(resolution.evidence_json or [])), + { + 'source': 'manual_rebind', + 'rebind': { + 'previous_customer_id': previous_customer_id, + 'new_customer_id': int(customer.id), + 'actor_id': int(actor_id), + 'reason': str(reason or '').strip() or None, + 'rebound_at': datetime.utcnow().isoformat(), + }, + }, + ] + db.session.flush() + + # [STEP 6] 审计:before/after 携带原/新确认客户(与业务写入同事务,挂 review_case_no)。 + _append_rebind_audit( + task=task, previous_customer_id=previous_customer_id, + new_customer=customer, actor_id=int(actor_id), reason=reason, + ) + + # [STEP 7] 快照客户刷新 + freeze 契约复核:manual 冻结校验 actor_id;已冻结任务走幂等 + # 早退返回当前快照(不重复版本校验——版本一致性已由守卫⓪保证)。 + snapshot = _refresh_frozen_snapshot_customer(task, customer) + from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot + + snapshot = freeze_order_snapshot( + task, + actor_id=int(actor_id), + expected_order_data_version=int(expected_order_data_version), + freeze_mode='manual', + ) + db.session.flush() + return {'resolution': resolution, 'snapshot': snapshot} diff --git a/backend/app/services/shipping_notice/inventory_routing_engine.py b/backend/app/services/shipping_notice/inventory_routing_engine.py index b87c182a..657512a9 100644 --- a/backend/app/services/shipping_notice/inventory_routing_engine.py +++ b/backend/app/services/shipping_notice/inventory_routing_engine.py @@ -2,8 +2,10 @@ services/shipping_notice/inventory_routing_engine.py 用途:执行已发布的通用库存源路由规则并生成可解释的 Source 候选。 -依赖:库存路由模型、冻结订单 Snapshot、routing_operators。 -逻辑:只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。 +依赖:库存路由模型、冻结订单 Snapshot、routing_operators、inventory_source_repository。 +逻辑:行级评估先做「库存源线索直连」(冻结行 inventory_source_hint 经精确/唯一后缀解析启用源, + 命中即 resolved,跳过全部规则层——含预约单号兜底规则;未命中 fail-open 落回规则层); + 随后只评估最高优先级命中的规则层;规则仅输出候选或人工复核,不执行 RPA 或 Warehouse 判定。 多候选为建单前正常结果(can_build=True);零候选或 require_manual_review 才阻断建单。 输出附带规则版本与命中规则摘要,供建单前重路由审计与前端展示;可用性过滤由资格服务完成。 """ @@ -15,6 +17,7 @@ from datetime import datetime from typing import Any from app.models import ShippingInventoryRoutingRule, ShippingOrderSnapshot +from app.services.shipping_notice.inventory_source_repository import list_database_inventory_sources from app.services.shipping_notice.routing_operators import matches_operator @@ -88,6 +91,55 @@ def _matched_rule_summaries(rules: list[ShippingInventoryRoutingRule]) -> tuple[ ) +def _resolve_source_from_hint(line_source_hint: str) -> str | None: + """ + 库存源线索 → 启用源解析:精确 source_code 相等优先,否则启用源中唯一后缀命中。 + + 无命中或多命中(后缀撞源)返回 None——调用方 fail-open 落回规则层,不以线索阻断流程。 + """ + code = str(line_source_hint or '').strip().upper() + if not code: + return None + enabled_codes = [ + normalized + for normalized in ( + str(item.get('source_code') or '').strip().upper() + for item in list_database_inventory_sources(enabled_only=True) + ) + if normalized + ] + if code in enabled_codes: + return code + suffix_hits = [item for item in enabled_codes if item.endswith(code)] + return suffix_hits[0] if len(suffix_hits) == 1 else None + + +def _hint_routing_result(source_code: str) -> InventoryRoutingResult: + """线索直连结果:resolved 单源,evidence 标明来源供审计追溯。""" + return InventoryRoutingResult( + 'resolved', + (source_code,), + (), + {'reason': 'inventory_source_hint', 'raw_source_codes': [source_code]}, + matched_rules=(), + ) + + +def _resolve_snapshot_line_source_hint(*, task: Any, line: dict[str, Any]) -> str | None: + """从冻结 Snapshot 行的强类型线索列读取并解析线索;行缺失或不可解析返回 None。""" + snapshot_id = getattr(task, 'order_snapshot_id', None) + if not snapshot_id: + return None + snapshot = ShippingOrderSnapshot.query.get(int(snapshot_id)) + if snapshot is None: + return None + position = int(line.get('_position', 0)) + target = next((item for item in snapshot.lines if item.position == position), None) + if target is None: + return None + return _resolve_source_from_hint(str(getattr(target, 'inventory_source_hint', '') or '')) + + def _condition_value(condition: Any, *, task: Any, line: dict[str, Any] | None) -> Any: """只读取冻结 Snapshot;履约路由不得回读动态 FieldValue。""" if condition.source_kind != 'order_field': @@ -232,14 +284,22 @@ def evaluate_inventory_source_rules( """ 评估已发布规则并返回最高优先级的 Source 候选集合(冻结 Snapshot 路径)。 + 核心逻辑:行级评估先做库存源线索直连(冻结行 inventory_source_hint 列 → 精确/唯一后缀 + 解析启用源,命中即 resolved,优先于包括预约单号兜底在内的全部规则层);未命中 fail-open + 落回规则层。任务级评估无线索语义,维持原行为。 + Args: task: 已解析的货代任务(须有 order_snapshot_id)。 - line: 行级规则的订单行;任务级规则传 None。 + line: 行级规则的订单行;任务级规则传 None。须含 `_position`(`_task_routing_lines` 产物)。 now: 测试可注入的评估时间,默认当前 UTC 时间。 Returns: InventoryRoutingResult: 含 status / source_codes / matched_rules / can_build。 """ + if line is not None: + hint_code = _resolve_snapshot_line_source_hint(task=task, line=line) + if hint_code: + return _hint_routing_result(hint_code) scope = 'line' if line is not None else 'task' return _evaluate_with_reader( scope=scope, @@ -254,11 +314,15 @@ def evaluate_inventory_source_rules_for_field_values( line_field_values: dict[str, Any] | None = None, scope: str | None = None, now: datetime | None = None, + line_source_hint: str | None = None, ) -> InventoryRoutingResult: """ - 基于 field_id→值映射评估路由(建单前 Draft / 资格服务)。 + 基于 field_id→值 映射评估路由(建单前 Draft / 资格评估)。 - 核心逻辑:未传 scope 时,有 line_field_values 则评 line,否则评 task; + 核心逻辑:行级评估先做库存源线索直连(调用方从 Draft 行取 `inventory_source_hint` 值 + 传入;精确/唯一后缀解析启用源,命中即 resolved,优先于全部规则层);未命中 fail-open + 落回规则层。任务级评估(line_field_values=None)忽略线索,维持原行为。 + 未传 scope 时,有 line_field_values 则评 line,否则评 task; 不依赖 ShippingNotice / Snapshot,便于复核草稿阶段投影候选。 Args: @@ -266,6 +330,7 @@ def evaluate_inventory_source_rules_for_field_values( line_field_values: Line 字段值;行级规则必填。 scope: 显式规则作用域 ``line`` / ``task``;缺省按是否有行值推断。 now: 可选评估时间。 + line_source_hint: Draft 行的库存源线索原始值;任务级评估或不传时忽略。 Returns: InventoryRoutingResult。 @@ -274,6 +339,10 @@ def evaluate_inventory_source_rules_for_field_values( resolved_scope = scope or ('line' if line_field_values is not None else 'task') if resolved_scope not in {'line', 'task'}: raise ValueError('inventory routing scope must be line or task') + if resolved_scope == 'line': + hint_code = _resolve_source_from_hint(line_source_hint or '') + if hint_code: + return _hint_routing_result(hint_code) line_values = dict(line_field_values or {}) if resolved_scope == 'line' else None return _evaluate_with_reader( scope=resolved_scope, diff --git a/backend/app/services/shipping_notice/order_build_eligibility_service.py b/backend/app/services/shipping_notice/order_build_eligibility_service.py index 52cdb840..7754ad4c 100644 --- a/backend/app/services/shipping_notice/order_build_eligibility_service.py +++ b/backend/app/services/shipping_notice/order_build_eligibility_service.py @@ -290,6 +290,8 @@ def project_line_inventory_candidates( header_field_values=header_ids, line_field_values=line_ids, scope='line', + # [线索直连] Draft 行的库存源线索经引擎精确/唯一后缀解析启用源,命中即优先于全部规则层。 + line_source_hint=str(line_by_code.get('inventory_source_hint') or '').strip() or None, ) task_result = evaluate_inventory_source_rules_for_field_values( header_field_values=header_ids, diff --git a/backend/app/services/shipping_notice/order_edit_window_service.py b/backend/app/services/shipping_notice/order_edit_window_service.py index 36268b77..1fbbb271 100644 --- a/backend/app/services/shipping_notice/order_edit_window_service.py +++ b/backend/app/services/shipping_notice/order_edit_window_service.py @@ -118,7 +118,25 @@ def _order_snapshot_line_ids(notice: ShippingNotice) -> list[str]: return sorted(set(keys), key=lambda value: int(value)) -def editable_scope(order_task: ShippingNotice) -> dict[str, Any]: +def _resolve_scope_notice(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | None: + """编辑窗身份归一:主通知原样返回;传入 OT 时按 order_task_id 反查任一同单通知。 + + 产物(Export Artifact)与 Attempt 都挂在通知上——OT 身份直接参与谓词会因 + 查不到产物而恒判可编辑(用户报告:Excel 已产生仍显示出单工具条)。 + """ + task_id = getattr(task, 'id', None) + if isinstance(task, ShippingNotice) or task_id is None: + # 主通知原样返回;未落库的 OT 不可能有通知,视同"Excel 从未生成"。 + return task if isinstance(task, ShippingNotice) else None + return ( + ShippingNotice.query + .filter(ShippingNotice.order_task_id == int(task_id)) + .order_by(ShippingNotice.id.asc()) + .first() + ) + + +def editable_scope(order_task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]: """ 计算确认后订单的编辑窗矩阵(D10 / §3.1)。 @@ -127,20 +145,24 @@ def editable_scope(order_task: ShippingNotice) -> dict[str, Any]: 行未入波次 → 无活动 Attempt(不受首单 Excel 限制)。 Args: - order_task: 正式订单的主 ShippingNotice(含 order_task_id 可回读同订单全部通知)。 + order_task: 主 ShippingNotice 或正式 OT(OT 自动按 order_task_id 归一到主通知)。 Returns: dict: {'header': bool, 'lines': {snapshot_line_id: bool}},同构供 ui_state.edit_window 下发。 """ - notices = _order_notices(order_task) + notice = _resolve_scope_notice(order_task) + if notice is None: + # 尚未产生任何通知(Excel 从未生成):无产物、无活动 Attempt,视为可编辑。 + return {'header': True, 'lines': {}} + notices = _order_notices(notice) order_busy = any(_notice_has_active_attempt(n) for n in notices) header_has_excel = any(_notice_has_export_artifact(n) for n in notices) header = (not header_has_excel) and (not order_busy) - wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(order_task)) + wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(notice)) lines: dict[str, bool] = {} - for snapshot_line_id in _order_snapshot_line_ids(order_task): + for snapshot_line_id in _order_snapshot_line_ids(notice): wave_task_id = wave_notice_map.get(snapshot_line_id) if wave_task_id is None: # 未入波次行:不受首单 Excel 限制,仅受活动 Attempt 影响。 diff --git a/backend/app/services/shipping_notice/order_review_customer_service.py b/backend/app/services/shipping_notice/order_review_customer_service.py index 94dec08c..ee101a8a 100644 --- a/backend/app/services/shipping_notice/order_review_customer_service.py +++ b/backend/app/services/shipping_notice/order_review_customer_service.py @@ -15,15 +15,21 @@ from typing import Any from app import db from app.core.errors import ConflictError, NotFoundError from app.models import ( + ShippingCustomer, ShippingOrderCandidate, ShippingCustomerShadowResolution, ShippingOrderExtraction, ShippingOrderReviewCase, + ShippingOrderTask, ) from app.services.shipping_notice.candidate_qualification_service import ( resolve_review_case_customer_resolved, ) -from app.services.shipping_notice.customer_resolution_service import confirm_customer_resolution +from app.services.shipping_notice.customer_resolution_service import ( + confirm_customer_resolution, + rebind_allowed_for_task, + resolution_for_task, +) from app.services.shipping_notice.workflow_ledger_service import ( assert_case_is_current_workflow_version, ) @@ -160,19 +166,45 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di ) ) ] + # [STEP 2] 已确认(含改绑)后以确认结果与客户主数据为权威展示:识别候选显示在改绑后会 stale。 + confirmed_task = ( + db.session.get(ShippingOrderTask, int(case.confirmed_task_id)) + if getattr(case, 'confirmed_task_id', None) else None + ) + resolution_row = resolution_for_task(confirmed_task) if confirmed_task is not None else None + confirmed_customer_id = ( + getattr(resolution_row, 'confirmed_customer_id', None) + if resolution_row is not None and resolution_row.status == 'confirmed' + else (getattr(shadow, 'confirmed_customer_id', None) if shadow is not None else None) + ) + confirmed_customer = ( + db.session.get(ShippingCustomer, int(confirmed_customer_id)) + if confirmed_customer_id else None + ) + return { 'resolved': bool(resolved), 'status': status, 'role': 'customer', 'extraction_id': int(extraction.id) if extraction is not None else None, 'raw_name': None, - 'customer_id': getattr(shadow, 'confirmed_customer_id', None) or display_match.get('customer_id'), - 'standard_name': display_match.get('standard_name'), - 'short_code': display_match.get('short_code'), + 'customer_id': confirmed_customer_id or display_match.get('customer_id'), + 'standard_name': ( + confirmed_customer.standard_name if confirmed_customer is not None + else display_match.get('standard_name') + ), + 'short_code': ( + confirmed_customer.short_code if confirmed_customer is not None + else display_match.get('short_code') + ), 'candidates': list(display_match.get('candidates') or []), 'input_values': input_values, 'evidence': evidence, 'match': display_match, + # 「修改客户」按钮谓词:仅已确认且无 Export Artifact/活动 Attempt 时可改绑(A 管控)。 + 'rebind_allowed': ( + rebind_allowed_for_task(confirmed_task) if confirmed_task is not None else False + ), } diff --git a/backend/app/services/shipping_notice/progress_audit_contract.py b/backend/app/services/shipping_notice/progress_audit_contract.py index 1da6d453..c2c6a03b 100644 --- a/backend/app/services/shipping_notice/progress_audit_contract.py +++ b/backend/app/services/shipping_notice/progress_audit_contract.py @@ -120,6 +120,7 @@ REVIEW_WORKBENCH_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({ 'review_field_changed', 'review_field_updated', 'review_customer_confirmed', + 'review_customer_rebound', 'review_duplicate_resolved', 'review_conflict_resolved', 'review_qualification_evaluated', diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index e15d5c49..76d4bceb 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -1162,6 +1162,13 @@ def _build_stage_context( } +def _build_edit_window(task: ShippingNotice) -> dict[str, Any]: + """二期编辑窗(D10)谓词:header/lines 可编辑矩阵,工作台以此隐藏/禁用出单入口。""" + from app.services.shipping_notice import order_edit_window_service as order_edit_window + + return order_edit_window.editable_scope(task) + + def build_task_ui_state( task: ShippingNotice, *, @@ -1269,6 +1276,10 @@ def build_task_ui_state( ) if include_stage_context else None ) + edit_window = ( + _build_edit_window(task) + if include_stage_context else None + ) reason = None if isinstance(process_gate, dict) and process_gate.get("blocking_reason_code"): reason = { @@ -1290,6 +1301,9 @@ def build_task_ui_state( "actions": actions, # 仅正式详情按需返回的工作面只读事实;不产生状态、权限或动作。 **({'stage_context': stage_context} if stage_context is not None else {}), + # 二期编辑窗门控矩阵(无 Export Artifact 且无活动 Attempt 才可编辑); + # 波次出单工具条与字段编辑守卫的数据源,禁止再次静默丢失。 + **({'edit_window': edit_window} if edit_window is not None else {}), "reason": reason, # OT 与 Notice 字段不完全同构:禁止硬读 Notice 专属列。 "lifecycle_status": getattr(task, "lifecycle_status", None) or getattr(task, "status", None), diff --git a/backend/tests/test_customer_resolution_rebind.py b/backend/tests/test_customer_resolution_rebind.py new file mode 100644 index 00000000..d435bf3c --- /dev/null +++ b/backend/tests/test_customer_resolution_rebind.py @@ -0,0 +1,517 @@ +""" +tests/test_customer_resolution_rebind.py + +用途:确认客户改绑(customer_resolution_service.rebind_confirmed_customer)契约测试。 +依赖:内存数据库、客户识别结果服务、order_freeze_service(真实冻结链)、 + order_edit_window_service(编辑窗 header 谓词)、ShippingExportArtifact。 +逻辑:已确认订单在产生发货通知/Excel 之前允许直接修改确认客户;改绑同步刷新冻结快照客户, + 并保持 evidence_json / identity_rule_set_checksum 非空冻结契约;Excel 已产生 / 活动 + Gate Attempt / 同客户 / 未知或停用客户 / 未确认识别结果均 fail-closed 且零副作用。 +""" + +from __future__ import annotations + +from decimal import Decimal + +import pytest + +from app import db +from app.core.errors import ConflictError, NotFoundError, ValidationError +from app.models import ( + ShippingAuditEvent, + ShippingCustomer, + ShippingCustomerShadowResolution, + ShippingExportArtifact, + ShippingInventoryParsingProfile, + ShippingNotice, + ShippingOrderCandidate, + ShippingOrderExtraction, + ShippingOrderField, + ShippingOrderIntake, + ShippingOrderLine, + ShippingOrderSchema, + ShippingOrderSchemaVersion, + ShippingOrderTask, + User, +) +from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer +from app.services.shipping_notice.order_review_customer_service import project_review_case_customer_resolution +from app.services.shipping_notice.order_freeze_service import ( + HEADER_FIELD_PROJECTIONS, + LINE_FIELD_PROJECTIONS, + freeze_order_snapshot, +) +from tests.conftest import parse_api_error + + +def _build_confirmed_frozen_order(*, suffix: str) -> dict: + """构造已确认客户 + 已冻结快照 + 未产生 Excel 的正式订单(编辑窗 header 可编辑)。""" + user = User(username=f'rebind-user-{suffix}', email=f'rebind-user-{suffix}@example.test', password_hash='x') + old_customer = ShippingCustomer(standard_name='原确认客户', short_code='OLD', status='active') + new_customer = ShippingCustomer(standard_name='新确认客户', short_code='NEWC', status='active') + inactive_customer = ShippingCustomer(standard_name='停用客户', short_code='OFF', status='inactive') + task = ShippingOrderTask(task_no=f'OT-REBIND-{suffix}', source_type='direct_pdf', user_id=1, order_data_version=7) + schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Rebind frozen order') + db.session.add_all([user, old_customer, new_customer, inactive_customer, task, schema]) + db.session.flush() + from app.services.shipping_notice import field_asset_service + field_asset_service.ensure_standard_assets_seeded() + definitions = [] + fields: dict[str, ShippingOrderField] = {} + for code in [*HEADER_FIELD_PROJECTIONS, *LINE_FIELD_PROJECTIONS]: + scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line' + field = ShippingOrderField.query.filter_by(field_code=code, scope=scope).one() + fields[code] = field + definitions.append({'field_id': field.id, 'field_code': code, 'scope': scope, 'value_type': field.value_type, 'enabled': True}) + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', definition_json={'fields': definitions}, checksum='rebind-test', + ) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction( + task_id=task.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted', + ) + db.session.add(extraction) + db.session.flush() + line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1) + db.session.add(line) + db.session.flush() + values = { + 'customer_po_number': 'PO-REBIND', 'customer_code': 'C-001', 'customer_name': 'Customer', + 'part_number': '000123', 'reservation_id': '0012345678', 'qty': Decimal('12.50'), + 'unit_price': Decimal('2.30'), 'line_amount_with_tax': Decimal('28.75'), 'uom': 'PCS', + } + for code, field in fields.items(): + value = values.get(code) + decision = _make_decision(extraction, line, field, code, value) + db.session.add(decision) + db.session.flush() + if value is not None: + db.session.add(_make_field_value(extraction, line, field, decision, value)) + task.current_order_extraction_id = extraction.id + intake = ShippingOrderIntake( + intake_no=f'INT-REBIND-{suffix}', asset_id=1, user_id=user.id, parser_version='test', + ) + db.session.add(intake) + db.session.flush() + candidate = ShippingOrderCandidate( + candidate_no=f'CAND-REBIND-{suffix}', intake_id=intake.id, primary_document_id=1, + candidate_key=f'rebind-{suffix}', order_extraction_id=extraction.id, candidate_status='accepted', + ) + db.session.add(candidate) + db.session.flush() + task.candidate_id = candidate.id + task.user_id = int(user.id) + resolution = ShippingCustomerShadowResolution( + candidate_id=candidate.id, intake_id=intake.id, resolution_version='test.v1', status='confirmed', + evidence_json=[{'definition_code': 'test_customer', 'normalized_value': old_customer.short_code}], + candidate_matches_json=[ + {'customer_id': old_customer.id, 'score': 100}, + {'customer_id': new_customer.id, 'score': 90}, + ], + resolution_context_json={'rule_set': {'checksum': 'f' * 64}}, + identity_rule_set_checksum='f' * 64, top_customer_id=old_customer.id, top_score=100, + confirmed_customer_id=old_customer.id, confirmation_method='manual', confirmed_by_id=user.id, + ) + notice = ShippingNotice(task_no=f'SN-REBIND-{suffix}', order_task_id=task.id) + db.session.add_all([resolution, notice]) + db.session.flush() + snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7) + db.session.commit() + return { + 'user': user, 'task': task, 'notice': notice, 'resolution': resolution, + 'old_customer': old_customer, 'new_customer': new_customer, 'inactive_customer': inactive_customer, + 'snapshot': snapshot, 'schema_version_id': int(version.id), + } + + +def _make_decision(extraction, line, field, code, value): + """构造单头/行字段裁决行(与既有快照测试同构)。""" + from app.models import ShippingOrderFieldDecision + return ShippingOrderFieldDecision( + extraction_id=extraction.id, line_id=None if code in HEADER_FIELD_PROJECTIONS else line.id, + field_id=field.id, decision_status='accepted', + resolved_value_json=str(value) if isinstance(value, Decimal) else value, + supporting_observation_ids_json=[], + ) + + +def _make_field_value(extraction, line, field, decision, value): + """构造字段值投影行(Decimal 保留精度,料号/预约号保留前导零)。""" + from app.models import ShippingOrderFieldValue + return ShippingOrderFieldValue( + extraction_id=extraction.id, line_id=None if field.scope == 'header' else line.id, + field_id=field.id, decision_id=decision.id, + value_json=str(value) if isinstance(value, Decimal) else value, + value_text=str(value) if isinstance(value, str) else None, + value_decimal=value if isinstance(value, Decimal) else None, + ) + + +def _attach_ready_export_artifact(notice: ShippingNotice) -> None: + """给通知挂一个 ready 导出产物(Excel 已产生,header 编辑窗关闭)。""" + from app.models import ShippingOrderSchema as Schema + from app.models import ShippingOrderSchemaVersion, ShippingOrderExtraction + + template = _template_row() + profile = ShippingInventoryParsingProfile( + profile_code='REBIND_PROFILE', display_name='Rebind profile', version=1, status='published', + file_format='xlsx', definition_json={}, + ) + schema = Schema(schema_code='REBIND_SCHEMA', display_name='Rebind schema') + db.session.add_all([template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion( + schema_id=schema.id, version=1, status='published', definition_json={}, checksum='b' * 64, + ) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted') + db.session.add(extraction) + db.session.flush() + db.session.add(ShippingExportArtifact( + task_id=int(notice.id), artifact_no=f'ART-REBIND-{notice.task_no}', template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum='d' * 64, + file_path='rebind.xlsx', file_name='rebind.xlsx', file_checksum='e' * 64, + file_size=1, status='ready', + )) + db.session.flush() + + +_TEMPLATE_CACHE: dict = {} + + +def _template_row(): + """复用同进程内已建模板,避免不同用例重复建模板造成噪音。 + + 缓存需自愈:每测试独立 create_all/drop_all,缓存 id 在新 DB 中可能不存在 + (该脆弱组合即 Task 1 评审预警项),取不到时重建并刷新缓存。 + """ + from app.models import ShippingExcelTemplate + cached_id = _TEMPLATE_CACHE.get('id') + if cached_id is not None: + template = db.session.get(ShippingExcelTemplate, int(cached_id)) + if template is not None: + return template + _TEMPLATE_CACHE.pop('id', None) + template = ShippingExcelTemplate( + template_code='REBIND_TPL', display_name='Rebind template', version=1, status='published', + storage_bucket='test', storage_key='rebind-tpl.xlsx', original_filename='rebind-tpl.xlsx', + file_checksum='a' * 64, definition_json={}, + ) + db.session.add(template) + db.session.flush() + _TEMPLATE_CACHE['id'] = int(template.id) + return template + + +def _resolution_of(task: ShippingOrderTask) -> ShippingCustomerShadowResolution: + """按 OT 的候选反查唯一识别结果行。""" + return ShippingCustomerShadowResolution.query.filter_by(candidate_id=int(task.candidate_id)).one() + + +def _attach_confirmed_revision(fx: dict, *, suffix: str): + """构造建单确认修订,把冻结任务挂到真实复核 Case 上(审计 review_case_no 反查依赖)。""" + from app.models import ShippingOrderReviewConfirmedRevision + + _user, case = _seed_review_case(suffix=suffix) + db.session.add(ShippingOrderReviewConfirmedRevision( + case_id=int(case.id), task_id=int(fx['task'].id), draft_version=1, + schema_version_id=int(fx['schema_version_id']), + idempotency_key=f'IDEM-REBIND-{suffix}', + confirmed_by_id=int(fx['user'].id), + )) + # 生产确认路径会把任务挂上 Case;改绑投影经 confirmed_task_id 反查确认结果。 + case.confirmed_task_id = int(fx['task'].id) + db.session.flush() + return case + + +def test_rebind_updates_confirmed_customer_and_refreezes_snapshot(app): + """改绑必须更新确认结果并按新客户重冻结快照(客户 ODM 白名单随新客户生效)。""" + with app.app_context(): + fx = _build_confirmed_frozen_order(suffix='happy') + # Case 反查夹具的 suffix 必须大写(intake_no 查找统一 upper 归一)。 + case = _attach_confirmed_revision(fx, suffix='HAPPY-CASE') + + result = rebind_confirmed_customer( + task=fx['task'], new_customer_id=int(fx['new_customer'].id), + actor_id=int(fx['user'].id), expected_order_data_version=7, reason='选错客户', + ) + db.session.commit() + + resolution = result['resolution'] + snapshot = result['snapshot'] + # 断言意图:确认结果与快照客户同步改绑;审计与 evidence_json 记录原客户(可追溯)。 + assert resolution.confirmed_customer_id == int(fx['new_customer'].id) + assert snapshot.customer_id == int(fx['new_customer'].id) + assert snapshot.customer_short_code_snapshot == str(fx['new_customer'].short_code) + rebind_record = next( + item for item in (resolution.evidence_json or []) + if isinstance(item, dict) and item.get('rebind') + ) + assert rebind_record['rebind']['previous_customer_id'] == int(fx['old_customer'].id) + assert rebind_record['rebind']['new_customer_id'] == int(fx['new_customer'].id) + assert rebind_record['rebind']['actor_id'] == int(fx['user'].id) + assert rebind_record['rebind']['reason'] == '选错客户' + assert resolution.identity_rule_set_checksum == 'f' * 64 # 冻结契约:保持非空 + # 原始识别证据保留(rebind 记录是追加,不是覆盖)。 + assert resolution.evidence_json[0]['definition_code'] == 'test_customer' + # 快照唯一约束(uq task_id):一个任务一份快照,改绑是原地刷新而非新行。 + assert int(snapshot.id) == int(fx['snapshot'].id) + assert fx['task'].order_snapshot_id == snapshot.id + # 审计事件:before/after 携带原/新确认客户与原因;挂 review_case_no 供 Case 时间线查询。 + event = ShippingAuditEvent.query.filter_by( + event_type='review_customer_rebound', aggregate_id=str(fx['task'].task_no), + ).one() + assert event.before_snapshot_json['previous_value'] == int(fx['old_customer'].id) + assert event.after_snapshot_json['new_value'] == int(fx['new_customer'].id) + assert event.reason == '选错客户' + assert event.actor_type == 'user' + assert event.review_case_no == str(case.case_no) + # 改绑后投影以确认结果+客户主数据为权威展示:名字/简称/改绑谓词直供工作台。 + projection = project_review_case_customer_resolution(case=case) + assert projection['standard_name'] == str(fx['new_customer'].standard_name) + assert projection['short_code'] == str(fx['new_customer'].short_code) + assert projection['customer_id'] == int(fx['new_customer'].id) + assert projection['rebind_allowed'] is True + + +def test_task_ui_state_emits_edit_window_gate_for_workbench(app): + """工作台 payload 必须下发 edit_window(D10 门控数据源,防合并再次丢失)。 + + 回归背景:前端波次出单工具条的显示条件读 ui_state.edit_window.header, + 后端曾把该字段丢失,导致 Excel 已产生仍显示「生成发货通知和 Excel」工具条。 + """ + fx = _build_confirmed_frozen_order(suffix='ew') + from app.services.shipping_notice.ui_state import build_task_ui_state + + ui = build_task_ui_state(fx['notice'], include_stage_context=True) + # 断言意图:Excel 未产生时 header=True(出单工具条显示)。 + assert ui['edit_window']['header'] is True + + _attach_ready_export_artifact(fx['notice']) + ui_after = build_task_ui_state(fx['notice'], include_stage_context=True) + # 断言意图:Excel 已产生时 header=False(出单工具条隐藏——用户报告的缺陷)。 + assert ui_after['edit_window']['header'] is False + # OT 身份构建必须与通知身份同判(editable_scope 身份归一):用户场景即按 OT 加载详情。 + ui_by_ot = build_task_ui_state(fx['task'], include_stage_context=True) + assert ui_by_ot['edit_window']['header'] is False + + +def test_rebind_rejects_when_export_artifact_exists(app): + """已产生 Excel(header 不可编辑)时改绑必须 409,且确认结果不被改动。""" + with app.app_context(): + fx = _build_confirmed_frozen_order(suffix='excel') + _attach_ready_export_artifact(fx['notice']) + case = _attach_confirmed_revision(fx, suffix='EXCEL-CASE') + # 断言意图:Excel 已产生时投影谓词 fail-closed(前端「修改客户」按钮禁用的数据源)。 + assert project_review_case_customer_resolution(case=case)['rebind_allowed'] is False + + with pytest.raises(ConflictError) as exc: + rebind_confirmed_customer( + task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id), + expected_order_data_version=7, + ) + + # 断言意图:A 管控 fail-closed;错误码可前端定位(details 区分 Excel / 活动 Attempt)。 + assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED' + assert exc.value.details['excel_exists'] is True + assert exc.value.details['active_attempt'] is False + db.session.rollback() + assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) + + +def test_rebind_rejects_when_active_gate_attempt_exists(app, monkeypatch): + """存在活动 Gate Attempt(库存 RPA / 匹配处理中)时改绑必须 409。""" + monkeypatch.setattr( + 'app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt', + lambda n: True, + ) + with app.app_context(): + fx = _build_confirmed_frozen_order(suffix='busy') + + with pytest.raises(ConflictError) as exc: + rebind_confirmed_customer( + task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id), + expected_order_data_version=7, + ) + + assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED' + assert exc.value.details['excel_exists'] is False + assert exc.value.details['active_attempt'] is True + db.session.rollback() + assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) + + +def test_rebind_rejects_same_customer_and_unknown_customer(app): + """同客户重复改绑与不存在/停用客户都必须 409/404,不产生副作用。""" + with app.app_context(): + fx = _build_confirmed_frozen_order(suffix='guards') + + with pytest.raises(ConflictError) as same: + rebind_confirmed_customer( + task=fx['task'], new_customer_id=int(fx['old_customer'].id), actor_id=int(fx['user'].id), + expected_order_data_version=7, + ) + assert same.value.code == 'SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER' + + with pytest.raises(NotFoundError) as unknown: + rebind_confirmed_customer( + task=fx['task'], new_customer_id=999999, actor_id=int(fx['user'].id), + expected_order_data_version=7, + ) + assert unknown.value.code == 'SHIPPING.CUSTOMER_NOT_FOUND' + + with pytest.raises(ConflictError) as inactive: + rebind_confirmed_customer( + task=fx['task'], new_customer_id=int(fx['inactive_customer'].id), actor_id=int(fx['user'].id), + expected_order_data_version=7, + ) + assert inactive.value.code == 'SHIPPING.CUSTOMER_INACTIVE' + + # 断言意图:拒绝路径零副作用(确认结果与快照均不被触碰)。 + db.session.rollback() + assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) + assert fx['task'].order_snapshot_id == fx['snapshot'].id + + +def test_rebind_requires_confirmed_resolution(app): + """识别结果未确认(或缺失)时改绑必须 409,提示走既有识别确认流程。""" + with app.app_context(): + fx = _build_confirmed_frozen_order(suffix='unconfirmed') + resolution = _resolution_of(fx['task']) + resolution.status = 'unique_candidate' + db.session.commit() + + with pytest.raises(ConflictError) as exc: + rebind_confirmed_customer( + task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id), + expected_order_data_version=7, + ) + + assert exc.value.code == 'SHIPPING.CUSTOMER_RESOLUTION_REQUIRED' + db.session.rollback() + assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) + + +def test_rebind_rejects_stale_version_without_side_effects(app): + """[断言] 客户端版本比较在守卫阶段执行:版本不一致必须 409 且零副作用(不写确认结果/审计/快照)。""" + with app.app_context(): + fx = _build_confirmed_frozen_order(suffix='stale') + + with pytest.raises(ConflictError) as exc: + rebind_confirmed_customer( + task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id), + expected_order_data_version=6, + ) + + # 断言意图:乐观锁在写前拒绝;details 呈现 expected/actual 供前端提示刷新。 + assert exc.value.code == 'SHIPPING.ORDER_DATA_VERSION_MISMATCH' + assert exc.value.details == {'expected': 6, 'actual': 7} + db.session.rollback() + assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) + assert fx['task'].order_snapshot_id == fx['snapshot'].id + assert ShippingAuditEvent.query.filter_by(event_type='review_customer_rebound').count() == 0 + + +def test_rebind_requires_operator_for_internal_call(app): + """[断言] 缺少执行人的内部调用按参数错误拒绝(独立于编辑窗 A 管控语义)。""" + with app.app_context(): + fx = _build_confirmed_frozen_order(suffix='no-actor') + + with pytest.raises(ValidationError) as exc: + rebind_confirmed_customer( + task=fx['task'], new_customer_id=int(fx['new_customer'].id), + actor_id=None, expected_order_data_version=7, + ) + + assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED' + db.session.rollback() + assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id) + + +# --------------------------------------------------------------------------- +# API 路由层(POST /api/workspace/shipping-notice/order-review-cases//customer/rebind) +# --------------------------------------------------------------------------- + +def _seed_review_case(*, suffix: str): + """构造属主用户与其复核 Case(未建正式 OT,够验证路由守卫)。""" + from tests.test_shipping_order_extraction_runs import _seed_run_input + from tests.test_shipping_order_review_service import _materialized_run + + user, agent, session, intake, _document = _seed_run_input(suffix=suffix) + run = _materialized_run(user=user, agent=agent, session=session, intake=intake) + from app.services.shipping_notice.order_review_service import ensure_run_review_cases + case = ensure_run_review_cases(run=run)[0] + db.session.commit() + return user, case + + +def _auth_headers(user) -> dict: + from app.core.auth.jwt import issue_local_access_token + return {'Authorization': f'Bearer {issue_local_access_token(user)}'} + + +def test_rebind_api_requires_customer_id(app): + """[断言] 缺少 customer_id 的请求体被 400 拦截,错误码可前端定位。""" + with app.app_context(): + user, case = _seed_review_case(suffix='API-BODY') + client = app.test_client() + response = client.post( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind', + headers=_auth_headers(user), json={}, + ) + error = parse_api_error(response.get_json()) + assert response.status_code == 400 + assert error['code'] == 'SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED' + + +def test_rebind_api_requires_expected_version(app): + """[断言] 缺少 expected_order_data_version 的请求体被 400 拦截(乐观锁必填)。""" + with app.app_context(): + user, case = _seed_review_case(suffix='API-VER') + client = app.test_client() + response = client.post( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind', + headers=_auth_headers(user), json={'customer_id': 1}, + ) + error = parse_api_error(response.get_json()) + assert response.status_code == 400 + assert error['code'] == 'SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED' + assert error['details']['field'] == 'expected_order_data_version' + + +def test_rebind_api_rejects_case_outside_ownership(app): + """[断言] 非属主访问他人 Case 必须按不存在拒绝(404),不泄露存在性。""" + with app.app_context(): + owner, case = _seed_review_case(suffix='API-OWNER') + # agent_code 全局唯一,非属主用户须使用独立 agent_code。 + from tests.test_shipping_order_extraction_runs import _seed_run_input + outsider, _a, _s, _i, _d = _seed_run_input(suffix='API-OUTSIDER', agent_code='shipping_notice_rebind') + client = app.test_client() + response = client.post( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind', + headers=_auth_headers(outsider), + json={'customer_id': 1, 'expected_order_data_version': 1}, + ) + error = parse_api_error(response.get_json()) + assert response.status_code == 404 + assert error['code'] == 'SHIPPING.REVIEW_CASE_NOT_FOUND' + assert owner is not None + + +def test_rebind_api_requires_formal_order_task(app): + """[断言] Case 尚未确认建单(无正式 OT)时改绑必须 409。""" + with app.app_context(): + user, case = _seed_review_case(suffix='API-NOOT') + client = app.test_client() + response = client.post( + f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind', + headers=_auth_headers(user), + json={'customer_id': 1, 'expected_order_data_version': 1}, + ) + error = parse_api_error(response.get_json()) + assert response.status_code == 409 + assert error['code'] == 'SHIPPING.FORMAL_OT_REQUIRED' diff --git a/backend/tests/test_shipping_inventory_routing_engine.py b/backend/tests/test_shipping_inventory_routing_engine.py index 02cffc87..5f96799f 100644 --- a/backend/tests/test_shipping_inventory_routing_engine.py +++ b/backend/tests/test_shipping_inventory_routing_engine.py @@ -14,7 +14,10 @@ from app.models import ( ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, ) -from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules +from app.services.shipping_notice.inventory_routing_engine import ( + evaluate_inventory_source_rules, + evaluate_inventory_source_rules_for_field_values, +) from app.services.shipping_notice.order_schema import service as order_schema_service @@ -212,3 +215,111 @@ def test_five_digit_reservation_rule_can_route_to_crane(app): result = evaluate_inventory_source_rules(task=task, line=line) assert result.status == 'resolved' assert result.source_codes == ('CRANE',) + + +# ---------- 库存源线索直连(引擎内建,优先于全部规则层) ---------- + +def _hint_sources(monkeypatch, codes): + """隔离线索解析的启用源清单(引擎自 list_database_inventory_sources 读取)。""" + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_routing_engine.list_database_inventory_sources', + lambda enabled_only=True: [{'source_code': code} for code in codes], + ) + + +def _set_snapshot_line_hint(task, hint: str) -> None: + """在冻结快照行的强类型线索列写入线索值(模拟订单明细「库存源线索」)。""" + snapshot_line = ShippingOrderSnapshotLine.query.filter_by( + snapshot_id=task.order_snapshot_id, position=0, + ).one() + snapshot_line.inventory_source_hint = hint + db.session.commit() + + +def test_hint_direct_connect_suffix_wins_over_reservation_fallback(app, monkeypatch): + """[断言] 核心需求:线索非空且可唯一后缀解析时直接 resolved,预约单号兜底规则不得参与。""" + _hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01', 'DSV360_AWSCV']) + fields = _published_line_fields() + task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) + db.session.add(_rule( + code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'], + conditions=[(fields['reservation_id'], 'prefix', '1')], + )) + _set_snapshot_line_hint(task, 'BYAWSPRD01') + db.session.commit() + result = evaluate_inventory_source_rules(task=task, line=line) + assert result.status == 'resolved' + assert result.source_codes == ('DSV360_AWSBI_BYAWSPRD01',) + assert result.evidence.get('reason') == 'inventory_source_hint' + assert result.matched_rule_ids == () + + +def test_hint_direct_connect_exact_code_match(app, monkeypatch): + """[断言] 线索即完整源编码时精确命中。""" + _hint_sources(monkeypatch, ['DSV360_AWSCV', 'DSV360_AWSDU']) + fields = _published_line_fields() + task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) + _set_snapshot_line_hint(task, 'DSV360_AWSCV') + db.session.commit() + result = evaluate_inventory_source_rules(task=task, line=line) + assert result.status == 'resolved' + assert result.source_codes == ('DSV360_AWSCV',) + + +def test_hint_unresolvable_falls_back_to_reservation_rule(app, monkeypatch): + """[断言] fail-open:线索无命中(拼错/停用)时落回规则层,预约兜底照常,不阻断流程。""" + _hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01']) + fields = _published_line_fields() + task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) + db.session.add(_rule( + code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB', 'DBS_RTM'], + conditions=[(fields['reservation_id'], 'prefix', '1')], + )) + _set_snapshot_line_hint(task, 'NOPE_WAREHOUSE') + db.session.commit() + result = evaluate_inventory_source_rules(task=task, line=line) + assert result.status == 'ambiguous' + assert result.source_codes == ('DBS_DUB', 'DBS_RTM') + + +def test_hint_ambiguous_suffix_falls_back_to_rules(app, monkeypatch): + """[断言] 后缀撞多个启用源(多命中)时不采用线索,落回规则层裁决。""" + _hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01', 'DSV360_CRANE_BYAWSPRD01']) + fields = _published_line_fields() + task, line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) + db.session.add(_rule( + code='RSV_PREFIX_1', priority=100, sources=['DBS_DUB'], + conditions=[(fields['reservation_id'], 'prefix', '1')], + )) + _set_snapshot_line_hint(task, 'BYAWSPRD01') + db.session.commit() + result = evaluate_inventory_source_rules(task=task, line=line) + assert result.status == 'resolved' + assert result.source_codes == ('DBS_DUB',) + + +def test_hint_direct_connect_ignored_for_task_scope(app, monkeypatch): + """[断言] 线索是行级信号:任务级评估(line=None)维持原行为。""" + _hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01']) + fields = _published_line_fields() + task, _line = _task_with_line_values(fields, {fields['reservation_id']: ('1000123456', 'reservation_id')}) + _set_snapshot_line_hint(task, 'BYAWSPRD01') + db.session.commit() + result = evaluate_inventory_source_rules(task=task, line=None) + assert result.status == 'unresolved' + + +def test_draft_entry_hint_direct_connect_and_fallback(app, monkeypatch): + """[断言] Draft 入口:线索命中直接 resolved(无规则也生效);未传线索时维持 unresolved。""" + _hint_sources(monkeypatch, ['DSV360_AWSBI_BYAWSPRD01']) + result = evaluate_inventory_source_rules_for_field_values( + header_field_values={}, line_field_values={}, scope='line', + line_source_hint='BYAWSPRD01', + ) + assert result.status == 'resolved' + assert result.source_codes == ('DSV360_AWSBI_BYAWSPRD01',) + assert result.evidence.get('reason') == 'inventory_source_hint' + fallback = evaluate_inventory_source_rules_for_field_values( + header_field_values={}, line_field_values={}, scope='line', + ) + assert fallback.status == 'unresolved' diff --git a/docs/demand.md b/docs/demand.md index 1a86b9d3..3bd6a402 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -297,6 +297,7 @@ - **生命周期治理**:创建、编辑、启停、简码变更和识别证据创建/审核/停用/自动匹配授权必须记录客户快照、操作者、原因与前后差异;简码、状态和自动匹配授权变更必须填写原因,管理员可在客户主数据页面查询时间线和门禁状态。 - **客户角色分离**:订单解析必须分别保存 Bill-to 账款客户和 Ship-to 送货对象的原文及证据;Bill-to 决定业务归属客户,Ship-to 指向客户主数据下的送货站点。客户简称只能由已确认 Bill-to 主数据派生,禁止由 LLM 提取或人工在订单模板中重复维护。 - **确定性优先匹配**:存在来源系统和外部编码时必须优先精确匹配;否则回退标准名称和已审核别名。未命中、多候选或站点归属不合法时进入人工复核。 +- **确认客户改绑(2026-10-13)**:客户确认后发现识别/选择错误时,支持在订单复核工作台直接改绑已确认客户(守卫:尚未产生发货通知 Excel 且无活动处理、目标客户有效且不同于当前客户、乐观锁版本一致),改绑更新确认结果、追加证据并全链路审计,同步原地刷新冻结快照客户;改后回通知准备重新生成 Excel,已产生 Excel 时须先走撤销流程。 ### 3.x 货代发货通知建单防重复(第一阶段) diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 0ccd237d..f0ef8f83 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -3999,3 +3999,69 @@ inventory_preparation Gate **审计**:产生新版本时写任务事件 `inventory_candidates_refreshed` (scope=task:previous_set_id/new_set_id/source_codes;scope=line:line_no/previous_codes/new_codes/new_set_id)。 + +## 2026-10-13 库存源线索直连(路由引擎内建,优先于全部规则层) + +**背景**:`inventory_source_hint`(订单行「库存源线索」,如 BYAWSPRD01)自设计起定位为 +可选路由线索(见上文「冻结 Snapshot 路由裁决」),但引擎此前不消费该列,线索只能靠 +管理员逐值维护高优先级规则生效;漏配新仓线索时预约单号兜底规则照常参与,产生错误候选。 + +**实现(fail-open 直连)**:`inventory_routing_engine.py` 行级评估最前置一步—— +- 快照路径:`evaluate_inventory_source_rules` 对行级评估自读冻结行强类型列 + `ShippingOrderSnapshotLine.inventory_source_hint`(按 `_position` 对齐,同 `_condition_value`); +- Draft 路径:`evaluate_inventory_source_rules_for_field_values` 新增可选入参 + `line_source_hint`(`order_build_eligibility_service.project_line_inventory_candidates` + 从 `line_by_code['inventory_source_hint']` 传入); +- 解析规则(`_resolve_source_from_hint`):线索归一大写后,启用源中**精确 source_code 相等** + 优先,否则**唯一后缀命中**(BYAWSPRD01 → DSV360_AWSBI_BYAWSPRD01);无命中或多命中 + 返回 None——**fail-open 落回规则层**(含预约单号兜底与逐值线索规则),不以线索阻断流程; +- 命中即返回 `resolved` 单源,evidence `reason='inventory_source_hint'`、`matched_rule_ids` + 为空(预约兜底等低层规则不参与);任务级评估(line=None)无线索语义,维持原行为。 + +**继承链(零额外改动)**:运行时裁决 `adjudicate_inventory_source`、冻结行级候选收集 +`_collect_order_line_candidates`、行级候选刷新 `refresh_line_candidates_from_current_routing` +均经行级规则评估自动生效——多行线索不同则按既有语义合并为 ambiguous 并按行钉候选; +订单行后补线索可经「重新获取库存(RPA)」的候选集刷新即时生效。 + +**边界**:波次行路由(D8 `freeze_wave_notice_routing`)暂未接入(波次行无线索强类型列, +需 field_id 反查,留待后续);线索解析失败不告警不门禁;放行证据的「料号兜底」与此无关。 + +## 确认客户改绑(2026-10-13) + +> 背景:订单复核阶段客户选错后,客户识别面板在 `customer_resolution.resolved` 后整体消失,确认后没有任何改客户入口;任务推进到通知准备后 Excel 生成失败(关联案例 SORC-336EB5E5D6D84CBE:库存行 ODM ID 不在新客户维护范围)。本节记录已实现并过评审的「确认客户改绑」:不重走识别候选打分确认,直接修改已确认的客户识别结果,改完回通知准备重新生成 Excel。 + +### 交互:客户识别面板两态化(`ReviewCustomerResolutionPanel`) + +- **未识别态**(`resolved=false`):行为不变,仍走识别候选确认流程。 +- **已识别态**(`resolved=true`):面板默认**折叠为一行摘要条**(状态徽标「已确认」+ 确认客户名 + 展开 chevron + 「修改客户」按钮);展开显示既有识别详情(命中输入/识别依据等历史信息,不展示 ODM 范围)。 +- 「修改客户」按钮可用性 = 编辑窗头级谓词(`editable_scope(order_task)['header']`);不满足则禁用 + tooltip 说明("已产生发货通知/Excel,请先走撤销流程")。点击后复用既有客户搜索(`searchCustomers`)选定目标客户 → 二次确认弹窗(明示「将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成」)→ 提交 → 成功 toast → `refreshed` 事件走既有刷新链。 + +### 守卫:fail-closed 四层(`rebind_confirmed_customer`,顺序固定) + +`backend/app/services/shipping_notice/customer_resolution_service.py` 的 `rebind_confirmed_customer`: + +1. **版本守卫**:`expected_order_data_version` 必填,与任务当前 `order_data_version` 不一致即 409 `SHIPPING.ORDER_DATA_VERSION_MISMATCH`——守卫期比较,写任何数据之前执行,冲突零副作用(freeze 幂等早退不重复做版本校验,版本比较只在此处)。 +2. **已确认**:resolution 行存在且 `status='confirmed'` 且已有确认客户,否则 409 `SHIPPING.CUSTOMER_RESOLUTION_REQUIRED`(未确认走既有确认流程,不在此补确认)。 +3. **编辑窗 header 谓词**:`editable_scope(order_task)['header']` 为 True,即该订单任一通知**无 Export Artifact 且无活动 Gate Attempt**;否则 409 `SHIPPING.CUSTOMER_REBIND_BLOCKED`(details 区分 `excel_exists` / `active_attempt`)。 +4. **新客户有效**:目标客户存在(`SHIPPING.CUSTOMER_NOT_FOUND`)、启用(`SHIPPING.CUSTOMER_INACTIVE`)且 ≠ 当前确认客户(`SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER`)。 + +### 写入链(同事务) + +1. **更新确认结果**:`confirmed_customer_id` 换新;`evidence_json` 追加 rebind 条目(原/新客户、操作人、原因、时间,保留原识别证据,维持非空契约);`identity_rule_set_checksum` 保留不动(冻结要求非空)。 +2. **审计**:同事务写 `review_customer_rebound`(before/after 确认客户 + reason,携带 `review_case_no`;事件已入 `REVIEW_WORKBENCH_AUDIT_EVENT_TYPES`,见 `progress_audit_contract.py`)。 +3. **原地刷新快照 + freeze 幂等路径**:`_refresh_frozen_snapshot_customer` 原地刷新快照 `customer_id`/客户简称,随后 `freeze_order_snapshot(mode='manual', actor_id, expected_order_data_version)` 按冻结契约复核——已冻结任务幂等早退返回当前快照。 + +### API + +`POST /api/workspace/shipping-notice/order-review-cases//customer/rebind`,body `{ customer_id, expected_order_data_version, reason? }`,返回刷新后的识别结果与快照投影。 + +### 零改动项与边界备忘 + +- **匹配与门禁零触碰**:匹配键=预约单号+料号,与客户无关,不失效匹配、不改门禁状态;守卫保证仅 Excel 未产生时可改绑,改后回通知准备重新生成 Excel;ODM 白名单导出时实时读新客户 `odm_ids`,无需任何配置动作。 +- **已放行缺口行的补录证据不随改绑重算**:放行决定仍有效,导出按快照 `release_field_values` 全量字典取值。 +- **Excel 表头客户名文字来自单据原文,不随改绑变化**(产品确认项)。 +- 预约号是货代侧事实,与客户无关,不重跑预约校验;不做「Excel 已产生后改绑作废重出」模型(守卫直接拒绝)。 + +### 设计与实施记录 + +- 设计 spec:[2026-10-13 确认客户改绑设计](../../superpowers/specs/2026-10-13-customer-rebind-design.md);实施计划:[2026-10-13 确认客户改绑计划](../../superpowers/plans/2026-10-13-customer-rebind.md)。 diff --git a/docs/funclist.md b/docs/funclist.md index 87c3cb1d..0ef369b4 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -230,6 +230,8 @@ | **编辑窗前端渲染(二期 T13)** | 已实现 | `ShippingTaskUiState.edit_window` 类型 + `formalHeaderEditable()`/`formalLineEditable(lineKey)`;头字段编辑块按 `edit_window.header` 门控、歧义行源下拉确认按行锁定;四语言 `errors.json` 补 `SHIPPING.EDIT_WINDOW_FIELD_LOCKED/SYSTEM_BUSY`;`npm run build` 通过。 | | 库存匹配料号兜底自动放行与料号维度可用数量展示(2026-10-09) | 已实现 | 匹配器按料号键二次汇总下发 `part_available_qty`(行允许源内、忽略预约号与单位,跨源不合并;迁移 `0a575f3afc32` 新列,存量行重匹配后回填),投影/ui_state prep 行透出;前端匹配表原「可用数量」改「预约数量」并新增「可用数量」列(四语言);匹配落库后 `auto_release_part_fallback_shortages` 对「缺口+料号总量≥需求+证据字段全部自动取值」行由系统创建 `release_inventory_shortage` 决定(`decision_source='system'`,快照 `auto_release`/`release_evidence_scope`),证据不可解析/字段分歧/总量不足降级人工,不自动撤销;证据带出优先级:预约号+料号 → 料号键重筛 → 人工补录,`release_field_values` 为导出 Excel 证据覆盖唯一来源;Excel/波次出单条件不变(出单仍需人工勾选波次)。见 [features/shipping-notice/technical.md](features/shipping-notice/technical.md)「料号兜底自动放行与数量列」。 | | 库存候选源刷新(人工重取前置,2026-10-13) | 已实现 | 「重新获取库存(RPA)」人工重取前按当前主数据幂等重判候选集(任务级整单重路由、行级仅重评目标行;仅未定源,人工钉源/已定源/Excel 已生成/轮询路径均不刷新),新版候选集 supersede 时内置失效旧库存事实,随后按新候选重取重算;前端歧义行库存源下拉改为候选置顶 + 全部已启用源兜底 | +| 库存源线索直连(2026-10-13) | 已实现 | 订单行「库存源线索」(inventory_source_hint)在行级路由评估最前置直连:精确 source_code 相等或启用源唯一后缀命中即 resolved(优先于预约单号兜底等全部规则层,evidence 标 reason),无命中/后缀多命中 fail-open 落回规则层;快照路径引擎自读强类型列、Draft 路径由资格投影传值;波次行路由暂未接入 | +| 确认客户改绑(2026-10-13) | 已实现 | 订单复核工作台客户识别面板两态化(已识别态默认折叠摘要条 + 「修改客户」按钮,可用性=编辑窗 header 谓词);后端 `rebind_confirmed_customer` 四层守卫:乐观锁 `expected_order_data_version` 写前比较 → 识别结果已确认 → 编辑窗 header(任一通知无 Export Artifact 且无活动 Attempt)→ 新客户有效且 ≠ 当前;链路:`evidence_json` 追加 rebind 条目 → 审计 `review_customer_rebound`(携带 review_case_no)→ 原地刷新快照客户/简称 + freeze 幂等;匹配与门禁零改动,改后回通知准备重新生成 Excel。设计:[2026-10-13 确认客户改绑设计](superpowers/specs/2026-10-13-customer-rebind-design.md) | ### 排程平台任务契约中心(schedule) diff --git a/docs/superpowers/plans/2026-10-13-customer-rebind.md b/docs/superpowers/plans/2026-10-13-customer-rebind.md new file mode 100644 index 00000000..f72b3434 --- /dev/null +++ b/docs/superpowers/plans/2026-10-13-customer-rebind.md @@ -0,0 +1,181 @@ +# 确认客户改绑(Customer Rebind)实施计划 + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** 已确认订单在产生发货通知/Excel 之前,允许用户在订单复核工作台的客户识别面板上直接修改确认客户(改绑),改后重新冻结快照并重新生成 Excel。 + +**Architecture:** 客户识别面板两态化(未识别=现状流程;已识别=默认折叠摘要条+「修改客户」),前端管控复用编辑窗头级谓词;后端新增 `rebind_confirmed_customer` 一条链(守卫→更新 resolution 行→审计→手动重冻结),匹配/门禁零触碰——守卫保证仅在无 Excel 产物时可改,无失效连锁。 + +**Tech Stack:** Flask + SQLAlchemy 2.0(后端);Vue 3 + TypeScript + Vue I18n 四语言(前端)。 + +**Spec:** `docs/superpowers/specs/2026-10-13-customer-rebind-design.md` + +## Global Constraints + +- 🚫 禁止自动 commit;任务以 `git add <具体文件>` 收尾(工作区有他人并行 WIP)。 +- 🌍 前端新增文案四语言(zh-CN/zh-TW/en/th)同步;chat.json 用精确子串编辑,禁 PowerShell 改写。 +- 🧷 冻结契约:`evidence_json` 与 `identity_rule_set_checksum` 必须保持非空(`order_freeze_service._confirmed_ordering_customer` 校验,:274-287);`freeze_order_snapshot(mode='manual')` 必须传 `actor_id`。 +- ⚠️ 匹配/门禁状态零改动:本能力不触碰 `export.py`、`post_ot_fulfillment_wave_service.py`、门禁 gate 行。 +- 📝 新函数含 Args/Returns docstring;测试有断言意图注释(§5.4)。 +- 后端测试:`cd backend && ./.venv/Scripts/python.exe -m pytest -q`;前端 vitest 可用 + `npm run build`。 + +--- + +### Task 1: 后端改绑服务 + API + +**Files:** +- Modify: `backend/app/services/shipping_notice/customer_resolution_service.py`(新增 `rebind_confirmed_customer`) +- Modify: `backend/app/api/workspace/shipping_notice.py`(新增 rebind 端点,模式对齐同文件 `order-review-cases//line-fulfillment/decide` 路由 :2163-2194) +- Test: `backend/tests/test_customer_resolution_rebind.py`(新建;夹具对齐既有客户确认相关测试的构造,执行者按文件内/相邻测试文件现状取用) + +**Interfaces:** +- Consumes: `resolution_for_task(task)`(本服务既有);`editable_scope(order_task)['header']`(`order_edit_window_service.py:121`);`freeze_order_snapshot(task, actor_id, expected_order_data_version, freeze_mode='manual')`(`order_freeze_service.py`)。 +- Produces: `rebind_confirmed_customer(*, task, new_customer_id, actor_id, reason=None) -> dict`(返回 {'resolution': 行, 'snapshot': 重冻结快照});API `POST .../order-review-cases//customer/rebind`。 + +- [ ] **Step 1: 写失败测试** + +```python +def test_rebind_updates_confirmed_customer_and_refreezes_snapshot(): + """改绑必须更新确认结果并按新客户重冻结快照(客户 ODM 白名单随新客户生效)。""" + # 夹具:已确认 resolution(status='confirmed', confirmed_customer_id=旧客户, evidence_json 非空) + # + 已冻结快照 + 无 Export Artifact/无活动 Attempt(editable_scope.header=True)。 + result = rebind_confirmed_customer( + task=task, new_customer_id=int(new_customer.id), actor_id=int(user.id), reason='选错客户', + ) + # 断言意图:确认结果与快照客户同步改绑;审计与 evidence_json 记录原客户(可追溯)。 + assert result['resolution'].confirmed_customer_id == int(new_customer.id) + assert result['snapshot'].customer_id == int(new_customer.id) + assert result['resolution'].evidence_json['rebind']['previous_customer_id'] == int(old_customer.id) + assert result['resolution'].identity_rule_set_checksum # 冻结契约:保持非空 + + +def test_rebind_rejects_when_export_artifact_exists(): + """已产生 Excel(header 不可编辑)时改绑必须 409,且确认结果不被改动。""" + # 夹具:同上,但给任一通知造 Export Artifact(对齐既有 artifact 测试构造)。 + with pytest.raises(ConflictError) as exc: + rebind_confirmed_customer(task=task, new_customer_id=int(new_customer.id), actor_id=int(user.id)) + # 断言意图:A 管控 fail-closed;错误码可前端定位。 + assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED' + assert resolution_row.confirmed_customer_id == int(old_customer.id) + + +def test_rebind_rejects_same_customer_and_unknown_customer(): + """同客户重复改绑与不存在/停用客户都必须 409/404,不产生副作用。""" +``` + +(夹具构造对齐仓库内既有客户确认测试;断言语义以三段注释为准。) + +- [ ] **Step 2: 确认失败** + +Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_customer_resolution_rebind.py -q` +Expected: FAIL(函数不存在) + +- [ ] **Step 3: 实现** + +`rebind_confirmed_customer` 顺序: +1. `resolution = resolution_for_task(task)`;`status != 'confirmed'` → ConflictError(提示走识别确认流程)。 +2. `editable_scope(task)['header']` 非 True → ConflictError `SHIPPING.CUSTOMER_REBIND_BLOCKED`(details 标注 excel_exists / active_attempt)。 +3. 新客户存在且启用(ShippingCustomer 查询)且 ≠ `resolution.confirmed_customer_id`,否则 404/409。 +4. `previous = resolution.confirmed_customer_id`;更新 id;`evidence_json = {**evidence_json, 'rebind': {...previous, new, actor_id, reason, utcnow}}`;flush。 +5. 审计(事件类型对齐 `progress_audit_contract` 既有集合,执行者核对后选用;before/after 客户 + reason)。 +6. `freeze_order_snapshot(task, actor_id=actor_id, expected_order_data_version=int(task.order_data_version or 1), freeze_mode='manual')`;返回 resolution + 新快照。 + +API 端点:校验登录与 case 归属(对齐 decide 端点的守卫风格),`actor_id` 取当前用户,调用服务,返回刷新 case 投影(复用既有序列化 helper)。 + +- [ ] **Step 4: 确认通过 + 回归** + +```bash +cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_customer_resolution_rebind.py tests/test_shipping_notice_ui_state.py -q +``` +(ui_state 已知基线失败 2 个不算。)另跑一个冻结相关套件确认零回归:`pytest tests/test_shipping_order_edit_window.py -q`。 + +- [ ] **Step 5: Stage** + +```bash +git add backend/app/services/shipping_notice/customer_resolution_service.py backend/app/api/workspace/shipping_notice.py backend/tests/test_customer_resolution_rebind.py +``` + +--- + +### Task 2: 前端面板两态化 + 修改客户弹窗 + +**Files:** +- Modify: `frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue`(两态化:resolved → 折叠摘要条;新增修改客户流程,复用既有 `searchCustomers` 与客户选择组件) +- Modify: `frontend/src/features/chat/views/ShippingOrderReviewView.vue`(面板 props:传入 `:rebind-allowed`(`formalEditWindow?.header === true`,:466 formalEditWindow)与禁用原因;渲染条件 `v-if="!activeCase.customer_resolution?.resolved"` 改为始终渲染并交由面板内部分态) +- Modify: `frontend/src/features/chat/api/shipping.api.ts`(新增 `rebindWorkspaceShippingOrderReviewCustomer(caseNo, { customer_id, reason })`) +- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json`(新键,见 Task 3) +- Test: `frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts`(新建/扩展,对齐既有面板 spec 写法) + +**Interfaces:** +- Consumes: Task 1 API;`formalEditWindow`(view :466);面板既有 `searchCustomers`(:111)与 `refreshed` emit。 +- Produces: 面板 props `rebindAllowed: boolean`;emit `refreshed`(复用)。 + +- [ ] **Step 1: spec 断言先行** + +```typescript +// 断言意图:已识别态默认折叠为摘要条(状态徽标+客户名),不默认展开详情; +// 「修改客户」按钮在 rebindAllowed=false 时禁用。 +it('renders collapsed summary with customer name when resolved', ...) +it('disables rebind button when rebindAllowed is false and shows reason', ...) +it('submits rebind with selected customer and emits refreshed', ...) +``` + +(按该文件/相邻面板 spec 的 mount 与查询写法落地;先跑确认失败。) + +- [ ] **Step 2: 实现面板两态** + +- `resolved=true`:渲染折叠条——`已确认` 徽标 + `resolution` 中的标准客户名(现有字段)+ chevron(展开显示既有识别详情,**无 ODM 范围**)+ 「修改客户」按钮(`:disabled="!rebindAllowed"` + tooltip 用禁用原因 i18n 键)。 +- 修改客户流程:打开复用的客户搜索选择(`searchCustomers`)→ 选定 → 影响确认弹窗(i18n 文案见 Task 3)→ `rebindWorkspaceShippingOrderReviewCustomer` → 成功 toast("客户已更新,可回通知准备重新生成 Excel")→ `emit('refreshed')`。 +- `resolved=false`:原样。 + +- [ ] **Step 3: 视图接线** + +`ShippingOrderReviewView.vue:6008` 的 `v-if` 改为始终渲染该面板(resolved 与否由面板分态);补 props `:rebind-allowed="formalEditWindow?.header === true"`;`@refreshed="handleReviewGateDataRefreshed"` 既有。 + +- [ ] **Step 4: 验收** + +```bash +cd frontend && npx vitest run src/features/chat/components/shipping-review/ && npm run build +``` + +- [ ] **Step 5: Stage** + +```bash +git add frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts frontend/src/features/chat/views/ShippingOrderReviewView.vue frontend/src/features/chat/api/shipping.api.ts frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json +``` + +--- + +### Task 3: i18n 四语言 + +**Files:** +- Modify: 四语言 `chat.json` 的 `shippingOrderReview` 域内(建议 `customerResolution` 邻近块) + +**Interfaces:** Produces 键:`rebindButton`(修改客户)、`rebindDisabledExcelExists`(禁用原因)、`rebindConfirmTitle`、`rebindConfirmImpact`、`rebindSuccessToast`(文案含"可回通知准备重新生成 Excel")、`rebindFailedToast`。 + +- [ ] 四语言值: + +| 键 | zh-CN | zh-TW | en | th | +| --- | --- | --- | --- | --- | +| rebindButton | 修改客户 | 修改客戶 | Change customer | เปลี่ยนลูกค้า | +| rebindDisabledExcelExists | 已产生发货通知/Excel,请先走撤销流程 | 已產生發貨通知/Excel,請先走撤銷流程 | Notice/Excel already generated — undo it first | มีการแจ้งเตือน/Excel แล้ว โปรดยกเลิกก่อน | +| rebindConfirmTitle | 确认修改客户 | 確認修改客戶 | Confirm customer change | ยืนยันการเปลี่ยนลูกค้า | +| rebindConfirmImpact | 将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成 | 將更新訂單客戶並重新凍結訂單快照;已產生的發貨通知/Excel 需重新生成 | The order customer will be updated and the snapshot re-frozen; generated notice/Excel must be regenerated | ลูกค้าจะถูกอัปเดตและ snapshot จะถูก freeze ใหม่ | +| rebindSuccessToast | 客户已更新,可回通知准备重新生成 Excel | 客戶已更新,可回通知準備重新產生 Excel | Customer updated — regenerate the Excel in notice preparation | อัปเดตลูกค้าแล้ว สร้าง Excel ใหม่ได้ | +| rebindFailedToast | 客户修改失败 | 客戶修改失敗 | Failed to change customer | เปลี่ยนลูกค้าไม่สำเร็จ | + +- [ ] JSON 合法性校验(node 解析四文件);`git add` 四文件。 + +--- + +### Task 4: 文档 + 回归 + +- [ ] `docs/features/shipping-notice/technical.md` 文末追加「确认客户改绑(2026-10-13)」(守卫/链路/边界备忘——已放行证据不重算);`docs/funclist.md` 加 1 行。 +- [ ] 回归:后端 `pytest tests/test_customer_resolution_rebind.py tests/test_shipping_order_edit_window.py tests/test_shipping_notice_ui_state.py -q`(ui_state 2 个基线失败除外);前端 vitest 面板 spec + `npm run build`。 +- [ ] 人工冒烟:本地复现单(SORC-336EB5E5D6D84CBE)——折叠条显示;客户 15 补 ODM 或改绑到维护了 581 的客户;回通知准备重新生成 Excel 成功。 + +## Self-Review + +- 规格覆盖:两态化/折叠/无 ODM 展示 → Task 2;管控 A → Task 1 守卫 + Task 2 按钮禁用;改绑链 → Task 1;审计/追溯 → Step 3.5;边界 → spec §4 + Task 4 文档。 +- 占位符:夹具构造与事件类型对齐项已给出现有锚点(文件:行)与断言语义,属执行者对齐指引。 +- 类型一致:`rebind_confirmed_customer` 签名、API 路径、`rebindAllowed` prop、i18n 键名前后一致。 diff --git a/docs/superpowers/specs/2026-10-13-customer-rebind-design.md b/docs/superpowers/specs/2026-10-13-customer-rebind-design.md new file mode 100644 index 00000000..885a5fbf --- /dev/null +++ b/docs/superpowers/specs/2026-10-13-customer-rebind-design.md @@ -0,0 +1,51 @@ +# 确认客户改绑(Customer Rebind)设计 + +日期:2026-10-13 | 状态:待评审 | 关联案例:SORC-336EB5E5D6D84CBE(客户选错 → Excel 生成 ODM 白名单失败) + +## 1. 背景与目标 + +订单复核阶段客户选错,任务推进到通知准备后 Excel 生成失败(`artifact_generation`:库存行 ODM ID 不在客户维护范围内)。当前**确认后没有任何入口可以改客户**:客户识别面板在 `customer_resolution.resolved` 后整体消失(`ShippingOrderReviewView.vue:6008`)。 + +目标:在订单复核工作台的客户识别面板上,允许用户**直接修改客户识别的确认结果**(不重走识别候选确认),改完回通知准备重新生成 Excel。 + +## 2. 交互设计 + +### 2.1 面板两态化(`ReviewCustomerResolutionPanel`) + +- **未识别**(`resolved=false`):保持现状(识别候选确认流程)。 +- **已识别**(`resolved=true`):面板默认**折叠为一行摘要条**(不再整体消失): + - 摘要条:状态徽标「已确认」+ 标准客户名(截断)+ 展开 chevron + 「修改客户」按钮; + - 展开:显示既有识别详情(命中输入/识别依据等历史信息);**不展示 ODM 范围**; + - 「修改客户」按钮的可用性 = 编辑窗头级谓词(`editable_scope(order_task)['header']`,即:该订单任一通知无 Export Artifact 且无活动 Gate Attempt)。不满足 → 按钮禁用 + tooltip 说明("已产生发货通知/Excel,请先走撤销流程")。 + +### 2.2 修改客户流程 + +点「修改客户」→ 复用既有客户搜索组件(`searchCustomers`)直接选定目标客户(**不重走识别候选打分确认**)→ 二次确认弹窗(明示影响:「将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成」)→ 提交 → 成功 toast("客户已更新,可回通知准备重新生成 Excel")→ `refreshed` 事件走既有刷新链。 + +## 3. 后端设计 + +`customer_resolution_service.rebind_confirmed_customer(task, new_customer_id, actor_id, reason=None)`: + +1. **守卫(fail-closed,顺序固定)**: + - resolution 行存在且 `status='confirmed'`(未确认走既有确认流程,409); + - `editable_scope(order_task)['header']` 为 True,否则 409 `SHIPPING.CUSTOMER_REBIND_BLOCKED`(details 区分:Excel 已产生 / 存在活动 Attempt); + - 新客户存在且启用,且 ≠ 当前确认客户。 +2. **更新**:`confirmed_customer_id = new_customer_id`;`evidence_json` 追加 rebind 记录(时间/操作人/原因/原客户,保持非空契约);`identity_rule_set_checksum` 保留不动(冻结要求非空)。 +3. **审计**:`append_shipping_audit_event`(before/after confirmed_customer_id + reason,事件类型对齐仓库审计契约)。 +4. **重冻结**:`freeze_order_snapshot(mode='manual', actor_id, expected_order_data_version)`——快照 `customer_id`/客户简称/模板头字段全部按新客户刷新;乐观锁冲突透传 409。 +5. **不动的部分**:不失效匹配(匹配键=预约+料号,与客户无关);不改门禁状态(Excel 未产生时无可失效产物——守卫已保证;Excel 已产生时守卫直接拒绝)。 +6. **API**:`POST /api/workspace/shipping-notice/order-review-cases//customer/rebind`,body `{customer_id, reason?}` → 返回刷新后的 case 投影。 + +## 4. 边界与不做的事 + +- 已放行缺口行的补录证据不随改绑重算(决定仍有效,导出按快照 `release_field_values` 全量字典取值)——文档备忘。 +- 预约号是货代侧事实,与客户无关,不重跑预约校验。 +- Excel 已产生时改绑被守卫拒绝(A 管控),不做"改后作废重出"模型。 +- ODM 白名单在导出时实时读新客户的 `odm_ids`,改绑后无需任何 ODM 配置动作即可被「重新生成 Excel」消费。 + +## 5. 验收标准 + +1. 已识别面板默认折叠,展示确认客户摘要;未识别态行为不变。 +2. Excel 未产生时「修改客户」可用,走搜索→确认→提交后:快照客户更新、审计落库、工作台自动刷新。 +3. Excel 已产生/有活动 Attempt 时按钮禁用并说明原因;直接调 API 返回 409。 +4. 改绑后重新生成 Excel 使用新客户 ODM 白名单(本案例:白名单含 581 后成功出单)。 diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index a234bc40..c860f7e9 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -673,6 +673,30 @@ export const confirmWorkspaceShippingOrderReviewCustomer = ( }, ); +/** + * 确认客户改绑:直接修改已确认客户并按新客户重冻结订单快照。 + * 核心逻辑:携带 expected_order_data_version 乐观锁;Excel 已产生/存在活动 Gate Attempt 时后端 409 + * (SHIPPING.CUSTOMER_REBIND_BLOCKED),版本漂移返回 SHIPPING.ORDER_DATA_VERSION_MISMATCH, + * 均由调用方以 BusinessError localized message 展示。 + * @param caseNo - 复核 Case 编号 + * @param payload - 新客户 ID、expected_order_data_version(case 投影 order_data_version)与可选原因 + */ +export const rebindWorkspaceShippingOrderReviewCustomer = ( + caseNo: string, + payload: { customer_id: number; expected_order_data_version: number; reason?: string }, +) => requestJson<{ + case: ShippingOrderReviewCase | null; + customer_resolution: ShippingOrderReviewCustomerResolution | null; + rebind: { previous_customer_id?: number | null; customer_id: number; snapshot_id: number }; +}>( + `/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/customer/rebind`, + { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }, +); + /** * 重新检测建单前重复订单。 */ diff --git a/frontend/src/features/chat/components/ShippingCustomerConfirmDialog.vue b/frontend/src/features/chat/components/ShippingCustomerConfirmDialog.vue index 301d19a8..6368fce4 100644 --- a/frontend/src/features/chat/components/ShippingCustomerConfirmDialog.vue +++ b/frontend/src/features/chat/components/ShippingCustomerConfirmDialog.vue @@ -25,17 +25,20 @@ watch(() => props.open, (open) => { diff --git a/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts index c47c3bd1..7463e981 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts @@ -1,21 +1,52 @@ /** * features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts - * 用途:锁定唯一标准客户候选的工作台提示,避免将可自动确认状态误报为未识别。 - * 依赖:vitest、@vue/test-utils、vue-i18n、ReviewCustomerResolutionPanel。 - * 逻辑:unique_candidate 显示自动确认说明和明确按钮;其他未确认状态维持人工选择入口。 + * 用途:锁定客户识别面板两态行为——未确认态保留候选确认流程;已确认态折叠为摘要条并提供「修改客户」改绑入口。 + * 依赖:vitest、@vue/test-utils、vue-i18n、ReviewCustomerResolutionPanel、shipping.api(mock)。 + * 逻辑:已确认摘要条默认折叠(已确认徽标 + 标准客户名 + chevron),展开仅显示既有识别详情; + * rebindAllowed=false 时改绑按钮禁用并展示原因;选定新客户经影响确认弹窗提交改绑 API 并 emit refreshed。 + * 改绑 i18n 键由 Task 3 落 chat.json,这里在 vue-i18n mock 中前置补齐同路径键。 */ -import { describe, expect, it } from 'vitest'; -import { mount } from '@vue/test-utils'; +import { flushPromises, mount } from '@vue/test-utils'; import { createI18n } from 'vue-i18n'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import ReviewCustomerResolutionPanel from './ReviewCustomerResolutionPanel.vue'; +import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCustomerConfirmDialog.vue'; +import { + listWorkspaceShippingCustomerOptions, + rebindWorkspaceShippingOrderReviewCustomer, +} from '@/features/chat/api/shipping.api'; +import { useMessage } from '@/shared/composables/useMessage'; + +const messageSpies = vi.hoisted(() => ({ + success: vi.fn(), + warning: vi.fn(), + error: vi.fn(), + info: vi.fn(), +})); + +vi.mock('@/features/chat/api/shipping.api', () => ({ + confirmWorkspaceShippingOrderReviewCustomer: vi.fn(), + listWorkspaceShippingCustomerOptions: vi.fn(), + retryWorkspaceShippingOrderReviewCustomerResolution: vi.fn(), + rebindWorkspaceShippingOrderReviewCustomer: vi.fn(), +})); + +vi.mock('@/shared/composables/useMessage', () => ({ + useMessage: () => messageSpies, +})); const i18n = createI18n({ legacy: false, locale: 'zh-CN', messages: { 'zh-CN': { + common: { cancel: '取消' }, chat: { - shippingCustomer: { loadFailed: '加载失败', confirmFailed: '确认失败' }, + shippingCustomer: { + loadFailed: '加载失败', + confirmFailed: '确认失败', + confirm: '确认', + }, shippingOrderReview: { customerResolution: { title: '客户确认', subtitle: '请选择标准客户', uniqueCandidateHint: '已找到唯一标准客户候选;保存校验时系统会自动确认,也可手动确认。', @@ -24,6 +55,13 @@ const i18n = createI18n({ standardCustomer: '标准客户', customerCode: '客户编码', matchedInputs: '匹配输入', candidates: '候选客户', pdfReparseHint: '请重新识别 PDF', inputLabels: { customerCode: '客户编码', customerName: '客户名称', address: '地址', email: '邮箱', domain: '域名', other: '其他' }, status: { unique_candidate: '唯一候选', unmatched: '未匹配', confirmed: '已确认' }, + // 改绑键:与 Task 3 将落入 locales/*/chat.json 的键路径保持一致 + rebindButton: '修改客户', + rebindDisabledExcelExists: '已产生发货通知/Excel,请先走撤销流程', + rebindConfirmTitle: '确认修改客户', + rebindConfirmImpact: '将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成', + rebindSuccessToast: '客户已更新,可回通知准备重新生成 Excel', + rebindFailedToast: '修改客户失败,请稍后重试', }, resume: { autoCreated: '已自动建单', waitingManualConfirm: '等待人工确认' }, }, @@ -32,32 +70,110 @@ const i18n = createI18n({ }, }); -function mountPanel(status: string) { +const resolvedResolution = { + resolved: true, + status: 'confirmed', + rebind_allowed: true, + customer_id: 11, + raw_name: 'acme', + standard_name: 'ACME 标准客户', + short_code: 'ACME', + input_values: [ + { definition_code: 'customer_code', definition_label: null, raw_value: 'ACME', normalized_value: 'ACME' }, + ], +}; + +function mountPanel(resolution: Record, extraProps: Record = {}) { return mount(ReviewCustomerResolutionPanel, { props: { caseNo: 'CASE-CUSTOMER-1', editable: true, - resolution: { resolved: false, status, raw_name: 'ACME' }, + orderDataVersion: 4, + resolution, + ...extraProps, }, global: { plugins: [i18n], - stubs: { ShippingCustomerConfirmDialog: true }, + // teleport 就地渲染:改绑影响确认弹窗 Teleport 到 body,stub 后断言仍在 wrapper 内可达。 + stubs: { ShippingCustomerConfirmDialog: true, teleport: true }, }, }); } describe('ReviewCustomerResolutionPanel', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(listWorkspaceShippingCustomerOptions).mockResolvedValue([]); + }); + it('唯一候选展示自动确认说明和明确确认入口', () => { - const wrapper = mountPanel('unique_candidate'); + const wrapper = mountPanel({ resolved: false, status: 'unique_candidate', raw_name: 'ACME' }); expect(wrapper.text()).toContain('保存校验时系统会自动确认'); expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('确认唯一候选'); }); it('非唯一未确认状态维持人工选择客户入口', () => { - const wrapper = mountPanel('unmatched'); + const wrapper = mountPanel({ resolved: false, status: 'unmatched', raw_name: 'ACME' }); expect(wrapper.text()).not.toContain('保存校验时系统会自动确认'); expect(wrapper.get('[data-testid="review-select-customer"]').text()).toContain('选择标准客户'); }); + + it('已确认态默认折叠为摘要条,展开仅显示既有识别详情', async () => { + const wrapper = mountPanel(resolvedResolution); + + // 断言意图:摘要条可见(已确认徽标 + 标准客户名),识别详情默认不展开 + expect(wrapper.get('[data-testid="review-customer-resolution-badge"]').text()).toContain('已确认'); + expect(wrapper.text()).toContain('ACME 标准客户'); + expect(wrapper.find('[data-testid="review-customer-resolution-details"]').exists()).toBe(false); + // 断言意图:改绑入口在摘要条上存在 + expect(wrapper.get('[data-testid="review-rebind-customer"]').exists()).toBe(true); + + // 断言意图:chevron 展开后显示既有识别详情(命中输入),不再是整块识别面板 + await wrapper.get('[data-testid="review-customer-resolution-toggle"]').trigger('click'); + expect(wrapper.get('[data-testid="review-customer-resolution-details"]').exists()).toBe(true); + expect(wrapper.text()).toContain('匹配输入'); + }); + + it('rebindAllowed=false 时改绑按钮禁用并以 tooltip 说明原因', () => { + const wrapper = mountPanel({ ...resolvedResolution, rebind_allowed: false }); + + const rebindButton = wrapper.get('[data-testid="review-rebind-customer"]'); + // 断言意图:edit_window.header=false(Excel 已产生/活动 Attempt)时按钮禁用 + expect(rebindButton.attributes('disabled')).toBeDefined(); + // 断言意图:禁用原因经 tooltip 透出,而非静默置灰 + expect(rebindButton.attributes('title')).toContain('撤销'); + }); + + it('选定新客户并确认影响后提交改绑 API 且 emit refreshed', async () => { + vi.mocked(rebindWorkspaceShippingOrderReviewCustomer).mockResolvedValue({ + case: null, + customer_resolution: null, + rebind: { previous_customer_id: 11, customer_id: 42, snapshot_id: 9 }, + }); + const wrapper = mountPanel(resolvedResolution); + + // [STEP 1] 打开复用的客户搜索选择弹窗并选定目标客户 + await wrapper.get('[data-testid="review-rebind-customer"]').trigger('click'); + await flushPromises(); + const selectDialog = wrapper.findComponent(ShippingCustomerConfirmDialog); + expect(selectDialog.exists()).toBe(true); + selectDialog.vm.$emit('confirm', 42); + await flushPromises(); + + // [STEP 2] 影响确认弹窗出现后提交 + await wrapper.get('[data-testid="review-rebind-confirm-submit"]').trigger('click'); + await flushPromises(); + + // 断言意图:携带乐观锁版本调用改绑 API + expect(rebindWorkspaceShippingOrderReviewCustomer).toHaveBeenCalledTimes(1); + expect(rebindWorkspaceShippingOrderReviewCustomer).toHaveBeenCalledWith( + 'CASE-CUSTOMER-1', + { customer_id: 42, expected_order_data_version: 4 }, + ); + // 断言意图:成功 toast + 复用 refreshed 事件走既有刷新链 + expect(messageSpies.success).toHaveBeenCalled(); + expect(wrapper.emitted('refreshed')).toHaveLength(1); + }); }); diff --git a/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue b/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue index f731a4b7..e28662cb 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue @@ -1,9 +1,11 @@