feat(shipping-notice): 支持已确认订单改绑客户并重冻结快照
- 客户识别面板两态化:已识别折叠为摘要条 +「修改客户」入口,前端管控复用编辑窗头级谓词 - 新增 rebind_confirmed_customer 链路:守卫→更新 resolution 行→审计→手动重冻结,改后重新生成 Excel - 守卫保证仅在无发货通知/Excel 产物时可改,匹配与门禁零触碰、无失效连锁 - 路由引擎/建单资格/编辑窗服务同步适配,errors 补充改绑错误码四语言 - 同步客户面板测试、确认对话框与四语言文案,落设计与实施计划文档
This commit is contained in:
1 parent
4a726fe8b2
commit
6ac2effac3
30 files changed
+1913
-93
No files matched your search
@@ -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/<case_no>/customer/rebind',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_rebind_shipping_order_review_customer(case_no: str):
|
||||
"""
|
||||
确认客户改绑:直接修改已确认的客户识别结果并刷新订单快照客户。
|
||||
|
||||
Body: customer_id, expected_order_data_version, reason?
|
||||
仅当订单编辑窗 header 可编辑(任一通知无 Export Artifact 且无活动 Gate Attempt,
|
||||
即发货通知/Excel 未产生)时允许;版本乐观锁与状态守卫在服务层 fail-closed。
|
||||
"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
try:
|
||||
customer_id = int(data.get('customer_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Customer id is required',
|
||||
code='SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED',
|
||||
details={'field': 'customer_id'},
|
||||
) from exc
|
||||
try:
|
||||
expected_order_data_version = int(data.get('expected_order_data_version'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Expected order data version is required',
|
||||
code='SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED',
|
||||
details={'field': 'expected_order_data_version'},
|
||||
) from exc
|
||||
|
||||
from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer
|
||||
from app.services.shipping_notice.order_review_customer_service import (
|
||||
project_review_case_customer_resolution,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
|
||||
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||||
if case is None:
|
||||
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
formal = resolve_formal_ot(case)
|
||||
if not formal.get('has_formal_ot') or formal.get('task') is None:
|
||||
raise ConflictError(
|
||||
'A formal order task is required before rebinding customer',
|
||||
code='SHIPPING.FORMAL_OT_REQUIRED',
|
||||
details={'task_missing': bool(formal.get('task_missing'))},
|
||||
)
|
||||
|
||||
result = rebind_confirmed_customer(
|
||||
task=formal['task'],
|
||||
new_customer_id=customer_id,
|
||||
actor_id=int(user.id),
|
||||
expected_order_data_version=expected_order_data_version,
|
||||
reason=str(data.get('reason') or '').strip() or None,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
resolution = result['resolution']
|
||||
rebind_record = next(
|
||||
(
|
||||
item.get('rebind') for item in (resolution.evidence_json or [])
|
||||
if isinstance(item, dict) and item.get('rebind')
|
||||
),
|
||||
None,
|
||||
) or {}
|
||||
refreshed_case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
|
||||
return _ok({
|
||||
'case': serialize_review_case(refreshed_case) if refreshed_case is not None else None,
|
||||
'customer_resolution': (
|
||||
project_review_case_customer_resolution(refreshed_case)
|
||||
if refreshed_case is not None else None
|
||||
),
|
||||
'rebind': {
|
||||
'previous_customer_id': rebind_record.get('previous_customer_id'),
|
||||
'customer_id': int(resolution.confirmed_customer_id),
|
||||
'snapshot_id': int(result['snapshot'].id),
|
||||
},
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-notice/order-review-cases/<case_no>/reservation/revalidate',
|
||||
methods=['POST'],
|
||||
|
||||
@@ -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}
|
||||
@@ -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,
|
||||
|
||||
@@ -290,6 +290,8 @@ def project_line_inventory_candidates(
|
||||
header_field_values=header_ids,
|
||||
line_field_values=line_ids,
|
||||
scope='line',
|
||||
# [线索直连] Draft 行的库存源线索经引擎精确/唯一后缀解析启用源,命中即优先于全部规则层。
|
||||
line_source_hint=str(line_by_code.get('inventory_source_hint') or '').strip() or None,
|
||||
)
|
||||
task_result = evaluate_inventory_source_rules_for_field_values(
|
||||
header_field_values=header_ids,
|
||||
|
||||
@@ -118,7 +118,25 @@ def _order_snapshot_line_ids(notice: ShippingNotice) -> list[str]:
|
||||
return sorted(set(keys), key=lambda value: int(value))
|
||||
|
||||
|
||||
def editable_scope(order_task: ShippingNotice) -> dict[str, Any]:
|
||||
def _resolve_scope_notice(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | None:
|
||||
"""编辑窗身份归一:主通知原样返回;传入 OT 时按 order_task_id 反查任一同单通知。
|
||||
|
||||
产物(Export Artifact)与 Attempt 都挂在通知上——OT 身份直接参与谓词会因
|
||||
查不到产物而恒判可编辑(用户报告:Excel 已产生仍显示出单工具条)。
|
||||
"""
|
||||
task_id = getattr(task, 'id', None)
|
||||
if isinstance(task, ShippingNotice) or task_id is None:
|
||||
# 主通知原样返回;未落库的 OT 不可能有通知,视同"Excel 从未生成"。
|
||||
return task if isinstance(task, ShippingNotice) else None
|
||||
return (
|
||||
ShippingNotice.query
|
||||
.filter(ShippingNotice.order_task_id == int(task_id))
|
||||
.order_by(ShippingNotice.id.asc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def editable_scope(order_task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
|
||||
"""
|
||||
计算确认后订单的编辑窗矩阵(D10 / §3.1)。
|
||||
|
||||
@@ -127,20 +145,24 @@ def editable_scope(order_task: ShippingNotice) -> dict[str, Any]:
|
||||
行未入波次 → 无活动 Attempt(不受首单 Excel 限制)。
|
||||
|
||||
Args:
|
||||
order_task: 正式订单的主 ShippingNotice(含 order_task_id 可回读同订单全部通知)。
|
||||
order_task: 主 ShippingNotice 或正式 OT(OT 自动按 order_task_id 归一到主通知)。
|
||||
|
||||
Returns:
|
||||
dict: {'header': bool, 'lines': {snapshot_line_id: bool}},同构供 ui_state.edit_window 下发。
|
||||
"""
|
||||
notices = _order_notices(order_task)
|
||||
notice = _resolve_scope_notice(order_task)
|
||||
if notice is None:
|
||||
# 尚未产生任何通知(Excel 从未生成):无产物、无活动 Attempt,视为可编辑。
|
||||
return {'header': True, 'lines': {}}
|
||||
notices = _order_notices(notice)
|
||||
order_busy = any(_notice_has_active_attempt(n) for n in notices)
|
||||
header_has_excel = any(_notice_has_export_artifact(n) for n in notices)
|
||||
|
||||
header = (not header_has_excel) and (not order_busy)
|
||||
|
||||
wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(order_task))
|
||||
wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(notice))
|
||||
lines: dict[str, bool] = {}
|
||||
for snapshot_line_id in _order_snapshot_line_ids(order_task):
|
||||
for snapshot_line_id in _order_snapshot_line_ids(notice):
|
||||
wave_task_id = wave_notice_map.get(snapshot_line_id)
|
||||
if wave_task_id is None:
|
||||
# 未入波次行:不受首单 Excel 限制,仅受活动 Attempt 影响。
|
||||
|
||||
@@ -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
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -0,0 +1,517 @@
|
||||
"""
|
||||
tests/test_customer_resolution_rebind.py
|
||||
|
||||
用途:确认客户改绑(customer_resolution_service.rebind_confirmed_customer)契约测试。
|
||||
依赖:内存数据库、客户识别结果服务、order_freeze_service(真实冻结链)、
|
||||
order_edit_window_service(编辑窗 header 谓词)、ShippingExportArtifact。
|
||||
逻辑:已确认订单在产生发货通知/Excel 之前允许直接修改确认客户;改绑同步刷新冻结快照客户,
|
||||
并保持 evidence_json / identity_rule_set_checksum 非空冻结契约;Excel 已产生 / 活动
|
||||
Gate Attempt / 同客户 / 未知或停用客户 / 未确认识别结果均 fail-closed 且零副作用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingAuditEvent,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingExportArtifact,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingNotice,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderField,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_resolution_service import rebind_confirmed_customer
|
||||
from app.services.shipping_notice.order_review_customer_service import project_review_case_customer_resolution
|
||||
from app.services.shipping_notice.order_freeze_service import (
|
||||
HEADER_FIELD_PROJECTIONS,
|
||||
LINE_FIELD_PROJECTIONS,
|
||||
freeze_order_snapshot,
|
||||
)
|
||||
from tests.conftest import parse_api_error
|
||||
|
||||
|
||||
def _build_confirmed_frozen_order(*, suffix: str) -> dict:
|
||||
"""构造已确认客户 + 已冻结快照 + 未产生 Excel 的正式订单(编辑窗 header 可编辑)。"""
|
||||
user = User(username=f'rebind-user-{suffix}', email=f'rebind-user-{suffix}@example.test', password_hash='x')
|
||||
old_customer = ShippingCustomer(standard_name='原确认客户', short_code='OLD', status='active')
|
||||
new_customer = ShippingCustomer(standard_name='新确认客户', short_code='NEWC', status='active')
|
||||
inactive_customer = ShippingCustomer(standard_name='停用客户', short_code='OFF', status='inactive')
|
||||
task = ShippingOrderTask(task_no=f'OT-REBIND-{suffix}', source_type='direct_pdf', user_id=1, order_data_version=7)
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Rebind frozen order')
|
||||
db.session.add_all([user, old_customer, new_customer, inactive_customer, task, schema])
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice import field_asset_service
|
||||
field_asset_service.ensure_standard_assets_seeded()
|
||||
definitions = []
|
||||
fields: dict[str, ShippingOrderField] = {}
|
||||
for code in [*HEADER_FIELD_PROJECTIONS, *LINE_FIELD_PROJECTIONS]:
|
||||
scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line'
|
||||
field = ShippingOrderField.query.filter_by(field_code=code, scope=scope).one()
|
||||
fields[code] = field
|
||||
definitions.append({'field_id': field.id, 'field_code': code, 'scope': scope, 'value_type': field.value_type, 'enabled': True})
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': definitions}, checksum='rebind-test',
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
values = {
|
||||
'customer_po_number': 'PO-REBIND', 'customer_code': 'C-001', 'customer_name': 'Customer',
|
||||
'part_number': '000123', 'reservation_id': '0012345678', 'qty': Decimal('12.50'),
|
||||
'unit_price': Decimal('2.30'), 'line_amount_with_tax': Decimal('28.75'), 'uom': 'PCS',
|
||||
}
|
||||
for code, field in fields.items():
|
||||
value = values.get(code)
|
||||
decision = _make_decision(extraction, line, field, code, value)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
if value is not None:
|
||||
db.session.add(_make_field_value(extraction, line, field, decision, value))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'INT-REBIND-{suffix}', asset_id=1, user_id=user.id, parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-REBIND-{suffix}', intake_id=intake.id, primary_document_id=1,
|
||||
candidate_key=f'rebind-{suffix}', order_extraction_id=extraction.id, candidate_status='accepted',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task.candidate_id = candidate.id
|
||||
task.user_id = int(user.id)
|
||||
resolution = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id, intake_id=intake.id, resolution_version='test.v1', status='confirmed',
|
||||
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': old_customer.short_code}],
|
||||
candidate_matches_json=[
|
||||
{'customer_id': old_customer.id, 'score': 100},
|
||||
{'customer_id': new_customer.id, 'score': 90},
|
||||
],
|
||||
resolution_context_json={'rule_set': {'checksum': 'f' * 64}},
|
||||
identity_rule_set_checksum='f' * 64, top_customer_id=old_customer.id, top_score=100,
|
||||
confirmed_customer_id=old_customer.id, confirmation_method='manual', confirmed_by_id=user.id,
|
||||
)
|
||||
notice = ShippingNotice(task_no=f'SN-REBIND-{suffix}', order_task_id=task.id)
|
||||
db.session.add_all([resolution, notice])
|
||||
db.session.flush()
|
||||
snapshot = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
db.session.commit()
|
||||
return {
|
||||
'user': user, 'task': task, 'notice': notice, 'resolution': resolution,
|
||||
'old_customer': old_customer, 'new_customer': new_customer, 'inactive_customer': inactive_customer,
|
||||
'snapshot': snapshot, 'schema_version_id': int(version.id),
|
||||
}
|
||||
|
||||
|
||||
def _make_decision(extraction, line, field, code, value):
|
||||
"""构造单头/行字段裁决行(与既有快照测试同构)。"""
|
||||
from app.models import ShippingOrderFieldDecision
|
||||
return ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=None if code in HEADER_FIELD_PROJECTIONS else line.id,
|
||||
field_id=field.id, decision_status='accepted',
|
||||
resolved_value_json=str(value) if isinstance(value, Decimal) else value,
|
||||
supporting_observation_ids_json=[],
|
||||
)
|
||||
|
||||
|
||||
def _make_field_value(extraction, line, field, decision, value):
|
||||
"""构造字段值投影行(Decimal 保留精度,料号/预约号保留前导零)。"""
|
||||
from app.models import ShippingOrderFieldValue
|
||||
return ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=None if field.scope == 'header' else line.id,
|
||||
field_id=field.id, decision_id=decision.id,
|
||||
value_json=str(value) if isinstance(value, Decimal) else value,
|
||||
value_text=str(value) if isinstance(value, str) else None,
|
||||
value_decimal=value if isinstance(value, Decimal) else None,
|
||||
)
|
||||
|
||||
|
||||
def _attach_ready_export_artifact(notice: ShippingNotice) -> None:
|
||||
"""给通知挂一个 ready 导出产物(Excel 已产生,header 编辑窗关闭)。"""
|
||||
from app.models import ShippingOrderSchema as Schema
|
||||
from app.models import ShippingOrderSchemaVersion, ShippingOrderExtraction
|
||||
|
||||
template = _template_row()
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
profile_code='REBIND_PROFILE', display_name='Rebind profile', version=1, status='published',
|
||||
file_format='xlsx', definition_json={},
|
||||
)
|
||||
schema = Schema(schema_code='REBIND_SCHEMA', display_name='Rebind schema')
|
||||
db.session.add_all([template, profile, schema])
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={}, checksum='b' * 64,
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted')
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingExportArtifact(
|
||||
task_id=int(notice.id), artifact_no=f'ART-REBIND-{notice.task_no}', template_id=template.id,
|
||||
order_schema_version_id=version.id, order_extraction_id=extraction.id,
|
||||
inventory_parsing_profile_id=profile.id, input_checksum='d' * 64,
|
||||
file_path='rebind.xlsx', file_name='rebind.xlsx', file_checksum='e' * 64,
|
||||
file_size=1, status='ready',
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
_TEMPLATE_CACHE: dict = {}
|
||||
|
||||
|
||||
def _template_row():
|
||||
"""复用同进程内已建模板,避免不同用例重复建模板造成噪音。
|
||||
|
||||
缓存需自愈:每测试独立 create_all/drop_all,缓存 id 在新 DB 中可能不存在
|
||||
(该脆弱组合即 Task 1 评审预警项),取不到时重建并刷新缓存。
|
||||
"""
|
||||
from app.models import ShippingExcelTemplate
|
||||
cached_id = _TEMPLATE_CACHE.get('id')
|
||||
if cached_id is not None:
|
||||
template = db.session.get(ShippingExcelTemplate, int(cached_id))
|
||||
if template is not None:
|
||||
return template
|
||||
_TEMPLATE_CACHE.pop('id', None)
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='REBIND_TPL', display_name='Rebind template', version=1, status='published',
|
||||
storage_bucket='test', storage_key='rebind-tpl.xlsx', original_filename='rebind-tpl.xlsx',
|
||||
file_checksum='a' * 64, definition_json={},
|
||||
)
|
||||
db.session.add(template)
|
||||
db.session.flush()
|
||||
_TEMPLATE_CACHE['id'] = int(template.id)
|
||||
return template
|
||||
|
||||
|
||||
def _resolution_of(task: ShippingOrderTask) -> ShippingCustomerShadowResolution:
|
||||
"""按 OT 的候选反查唯一识别结果行。"""
|
||||
return ShippingCustomerShadowResolution.query.filter_by(candidate_id=int(task.candidate_id)).one()
|
||||
|
||||
|
||||
def _attach_confirmed_revision(fx: dict, *, suffix: str):
|
||||
"""构造建单确认修订,把冻结任务挂到真实复核 Case 上(审计 review_case_no 反查依赖)。"""
|
||||
from app.models import ShippingOrderReviewConfirmedRevision
|
||||
|
||||
_user, case = _seed_review_case(suffix=suffix)
|
||||
db.session.add(ShippingOrderReviewConfirmedRevision(
|
||||
case_id=int(case.id), task_id=int(fx['task'].id), draft_version=1,
|
||||
schema_version_id=int(fx['schema_version_id']),
|
||||
idempotency_key=f'IDEM-REBIND-{suffix}',
|
||||
confirmed_by_id=int(fx['user'].id),
|
||||
))
|
||||
# 生产确认路径会把任务挂上 Case;改绑投影经 confirmed_task_id 反查确认结果。
|
||||
case.confirmed_task_id = int(fx['task'].id)
|
||||
db.session.flush()
|
||||
return case
|
||||
|
||||
|
||||
def test_rebind_updates_confirmed_customer_and_refreezes_snapshot(app):
|
||||
"""改绑必须更新确认结果并按新客户重冻结快照(客户 ODM 白名单随新客户生效)。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='happy')
|
||||
# Case 反查夹具的 suffix 必须大写(intake_no 查找统一 upper 归一)。
|
||||
case = _attach_confirmed_revision(fx, suffix='HAPPY-CASE')
|
||||
|
||||
result = rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id),
|
||||
actor_id=int(fx['user'].id), expected_order_data_version=7, reason='选错客户',
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
resolution = result['resolution']
|
||||
snapshot = result['snapshot']
|
||||
# 断言意图:确认结果与快照客户同步改绑;审计与 evidence_json 记录原客户(可追溯)。
|
||||
assert resolution.confirmed_customer_id == int(fx['new_customer'].id)
|
||||
assert snapshot.customer_id == int(fx['new_customer'].id)
|
||||
assert snapshot.customer_short_code_snapshot == str(fx['new_customer'].short_code)
|
||||
rebind_record = next(
|
||||
item for item in (resolution.evidence_json or [])
|
||||
if isinstance(item, dict) and item.get('rebind')
|
||||
)
|
||||
assert rebind_record['rebind']['previous_customer_id'] == int(fx['old_customer'].id)
|
||||
assert rebind_record['rebind']['new_customer_id'] == int(fx['new_customer'].id)
|
||||
assert rebind_record['rebind']['actor_id'] == int(fx['user'].id)
|
||||
assert rebind_record['rebind']['reason'] == '选错客户'
|
||||
assert resolution.identity_rule_set_checksum == 'f' * 64 # 冻结契约:保持非空
|
||||
# 原始识别证据保留(rebind 记录是追加,不是覆盖)。
|
||||
assert resolution.evidence_json[0]['definition_code'] == 'test_customer'
|
||||
# 快照唯一约束(uq task_id):一个任务一份快照,改绑是原地刷新而非新行。
|
||||
assert int(snapshot.id) == int(fx['snapshot'].id)
|
||||
assert fx['task'].order_snapshot_id == snapshot.id
|
||||
# 审计事件:before/after 携带原/新确认客户与原因;挂 review_case_no 供 Case 时间线查询。
|
||||
event = ShippingAuditEvent.query.filter_by(
|
||||
event_type='review_customer_rebound', aggregate_id=str(fx['task'].task_no),
|
||||
).one()
|
||||
assert event.before_snapshot_json['previous_value'] == int(fx['old_customer'].id)
|
||||
assert event.after_snapshot_json['new_value'] == int(fx['new_customer'].id)
|
||||
assert event.reason == '选错客户'
|
||||
assert event.actor_type == 'user'
|
||||
assert event.review_case_no == str(case.case_no)
|
||||
# 改绑后投影以确认结果+客户主数据为权威展示:名字/简称/改绑谓词直供工作台。
|
||||
projection = project_review_case_customer_resolution(case=case)
|
||||
assert projection['standard_name'] == str(fx['new_customer'].standard_name)
|
||||
assert projection['short_code'] == str(fx['new_customer'].short_code)
|
||||
assert projection['customer_id'] == int(fx['new_customer'].id)
|
||||
assert projection['rebind_allowed'] is True
|
||||
|
||||
|
||||
def test_task_ui_state_emits_edit_window_gate_for_workbench(app):
|
||||
"""工作台 payload 必须下发 edit_window(D10 门控数据源,防合并再次丢失)。
|
||||
|
||||
回归背景:前端波次出单工具条的显示条件读 ui_state.edit_window.header,
|
||||
后端曾把该字段丢失,导致 Excel 已产生仍显示「生成发货通知和 Excel」工具条。
|
||||
"""
|
||||
fx = _build_confirmed_frozen_order(suffix='ew')
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
ui = build_task_ui_state(fx['notice'], include_stage_context=True)
|
||||
# 断言意图:Excel 未产生时 header=True(出单工具条显示)。
|
||||
assert ui['edit_window']['header'] is True
|
||||
|
||||
_attach_ready_export_artifact(fx['notice'])
|
||||
ui_after = build_task_ui_state(fx['notice'], include_stage_context=True)
|
||||
# 断言意图:Excel 已产生时 header=False(出单工具条隐藏——用户报告的缺陷)。
|
||||
assert ui_after['edit_window']['header'] is False
|
||||
# OT 身份构建必须与通知身份同判(editable_scope 身份归一):用户场景即按 OT 加载详情。
|
||||
ui_by_ot = build_task_ui_state(fx['task'], include_stage_context=True)
|
||||
assert ui_by_ot['edit_window']['header'] is False
|
||||
|
||||
|
||||
def test_rebind_rejects_when_export_artifact_exists(app):
|
||||
"""已产生 Excel(header 不可编辑)时改绑必须 409,且确认结果不被改动。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='excel')
|
||||
_attach_ready_export_artifact(fx['notice'])
|
||||
case = _attach_confirmed_revision(fx, suffix='EXCEL-CASE')
|
||||
# 断言意图:Excel 已产生时投影谓词 fail-closed(前端「修改客户」按钮禁用的数据源)。
|
||||
assert project_review_case_customer_resolution(case=case)['rebind_allowed'] is False
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
|
||||
# 断言意图:A 管控 fail-closed;错误码可前端定位(details 区分 Excel / 活动 Attempt)。
|
||||
assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED'
|
||||
assert exc.value.details['excel_exists'] is True
|
||||
assert exc.value.details['active_attempt'] is False
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
|
||||
|
||||
def test_rebind_rejects_when_active_gate_attempt_exists(app, monkeypatch):
|
||||
"""存在活动 Gate Attempt(库存 RPA / 匹配处理中)时改绑必须 409。"""
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_edit_window_service._notice_has_active_attempt',
|
||||
lambda n: True,
|
||||
)
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='busy')
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED'
|
||||
assert exc.value.details['excel_exists'] is False
|
||||
assert exc.value.details['active_attempt'] is True
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
|
||||
|
||||
def test_rebind_rejects_same_customer_and_unknown_customer(app):
|
||||
"""同客户重复改绑与不存在/停用客户都必须 409/404,不产生副作用。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='guards')
|
||||
|
||||
with pytest.raises(ConflictError) as same:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['old_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
assert same.value.code == 'SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER'
|
||||
|
||||
with pytest.raises(NotFoundError) as unknown:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=999999, actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
assert unknown.value.code == 'SHIPPING.CUSTOMER_NOT_FOUND'
|
||||
|
||||
with pytest.raises(ConflictError) as inactive:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['inactive_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
assert inactive.value.code == 'SHIPPING.CUSTOMER_INACTIVE'
|
||||
|
||||
# 断言意图:拒绝路径零副作用(确认结果与快照均不被触碰)。
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
assert fx['task'].order_snapshot_id == fx['snapshot'].id
|
||||
|
||||
|
||||
def test_rebind_requires_confirmed_resolution(app):
|
||||
"""识别结果未确认(或缺失)时改绑必须 409,提示走既有识别确认流程。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='unconfirmed')
|
||||
resolution = _resolution_of(fx['task'])
|
||||
resolution.status = 'unique_candidate'
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=7,
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.CUSTOMER_RESOLUTION_REQUIRED'
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
|
||||
|
||||
def test_rebind_rejects_stale_version_without_side_effects(app):
|
||||
"""[断言] 客户端版本比较在守卫阶段执行:版本不一致必须 409 且零副作用(不写确认结果/审计/快照)。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='stale')
|
||||
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id), actor_id=int(fx['user'].id),
|
||||
expected_order_data_version=6,
|
||||
)
|
||||
|
||||
# 断言意图:乐观锁在写前拒绝;details 呈现 expected/actual 供前端提示刷新。
|
||||
assert exc.value.code == 'SHIPPING.ORDER_DATA_VERSION_MISMATCH'
|
||||
assert exc.value.details == {'expected': 6, 'actual': 7}
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
assert fx['task'].order_snapshot_id == fx['snapshot'].id
|
||||
assert ShippingAuditEvent.query.filter_by(event_type='review_customer_rebound').count() == 0
|
||||
|
||||
|
||||
def test_rebind_requires_operator_for_internal_call(app):
|
||||
"""[断言] 缺少执行人的内部调用按参数错误拒绝(独立于编辑窗 A 管控语义)。"""
|
||||
with app.app_context():
|
||||
fx = _build_confirmed_frozen_order(suffix='no-actor')
|
||||
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
rebind_confirmed_customer(
|
||||
task=fx['task'], new_customer_id=int(fx['new_customer'].id),
|
||||
actor_id=None, expected_order_data_version=7,
|
||||
)
|
||||
|
||||
assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED'
|
||||
db.session.rollback()
|
||||
assert _resolution_of(fx['task']).confirmed_customer_id == int(fx['old_customer'].id)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# API 路由层(POST /api/workspace/shipping-notice/order-review-cases/<case_no>/customer/rebind)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _seed_review_case(*, suffix: str):
|
||||
"""构造属主用户与其复核 Case(未建正式 OT,够验证路由守卫)。"""
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
from tests.test_shipping_order_review_service import _materialized_run
|
||||
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix=suffix)
|
||||
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
|
||||
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
|
||||
case = ensure_run_review_cases(run=run)[0]
|
||||
db.session.commit()
|
||||
return user, case
|
||||
|
||||
|
||||
def _auth_headers(user) -> dict:
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
return {'Authorization': f'Bearer {issue_local_access_token(user)}'}
|
||||
|
||||
|
||||
def test_rebind_api_requires_customer_id(app):
|
||||
"""[断言] 缺少 customer_id 的请求体被 400 拦截,错误码可前端定位。"""
|
||||
with app.app_context():
|
||||
user, case = _seed_review_case(suffix='API-BODY')
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
|
||||
headers=_auth_headers(user), json={},
|
||||
)
|
||||
error = parse_api_error(response.get_json())
|
||||
assert response.status_code == 400
|
||||
assert error['code'] == 'SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED'
|
||||
|
||||
|
||||
def test_rebind_api_requires_expected_version(app):
|
||||
"""[断言] 缺少 expected_order_data_version 的请求体被 400 拦截(乐观锁必填)。"""
|
||||
with app.app_context():
|
||||
user, case = _seed_review_case(suffix='API-VER')
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
|
||||
headers=_auth_headers(user), json={'customer_id': 1},
|
||||
)
|
||||
error = parse_api_error(response.get_json())
|
||||
assert response.status_code == 400
|
||||
assert error['code'] == 'SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED'
|
||||
assert error['details']['field'] == 'expected_order_data_version'
|
||||
|
||||
|
||||
def test_rebind_api_rejects_case_outside_ownership(app):
|
||||
"""[断言] 非属主访问他人 Case 必须按不存在拒绝(404),不泄露存在性。"""
|
||||
with app.app_context():
|
||||
owner, case = _seed_review_case(suffix='API-OWNER')
|
||||
# agent_code 全局唯一,非属主用户须使用独立 agent_code。
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
outsider, _a, _s, _i, _d = _seed_run_input(suffix='API-OUTSIDER', agent_code='shipping_notice_rebind')
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
|
||||
headers=_auth_headers(outsider),
|
||||
json={'customer_id': 1, 'expected_order_data_version': 1},
|
||||
)
|
||||
error = parse_api_error(response.get_json())
|
||||
assert response.status_code == 404
|
||||
assert error['code'] == 'SHIPPING.REVIEW_CASE_NOT_FOUND'
|
||||
assert owner is not None
|
||||
|
||||
|
||||
def test_rebind_api_requires_formal_order_task(app):
|
||||
"""[断言] Case 尚未确认建单(无正式 OT)时改绑必须 409。"""
|
||||
with app.app_context():
|
||||
user, case = _seed_review_case(suffix='API-NOOT')
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/customer/rebind',
|
||||
headers=_auth_headers(user),
|
||||
json={'customer_id': 1, 'expected_order_data_version': 1},
|
||||
)
|
||||
error = parse_api_error(response.get_json())
|
||||
assert response.status_code == 409
|
||||
assert error['code'] == 'SHIPPING.FORMAL_OT_REQUIRED'
|
||||
@@ -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'
|
||||
@@ -297,6 +297,7 @@
|
||||
- **生命周期治理**:创建、编辑、启停、简码变更和识别证据创建/审核/停用/自动匹配授权必须记录客户快照、操作者、原因与前后差异;简码、状态和自动匹配授权变更必须填写原因,管理员可在客户主数据页面查询时间线和门禁状态。
|
||||
- **客户角色分离**:订单解析必须分别保存 Bill-to 账款客户和 Ship-to 送货对象的原文及证据;Bill-to 决定业务归属客户,Ship-to 指向客户主数据下的送货站点。客户简称只能由已确认 Bill-to 主数据派生,禁止由 LLM 提取或人工在订单模板中重复维护。
|
||||
- **确定性优先匹配**:存在来源系统和外部编码时必须优先精确匹配;否则回退标准名称和已审核别名。未命中、多候选或站点归属不合法时进入人工复核。
|
||||
- **确认客户改绑(2026-10-13)**:客户确认后发现识别/选择错误时,支持在订单复核工作台直接改绑已确认客户(守卫:尚未产生发货通知 Excel 且无活动处理、目标客户有效且不同于当前客户、乐观锁版本一致),改绑更新确认结果、追加证据并全链路审计,同步原地刷新冻结快照客户;改后回通知准备重新生成 Excel,已产生 Excel 时须先走撤销流程。
|
||||
|
||||
### 3.x 货代发货通知建单防重复(第一阶段)
|
||||
|
||||
|
||||
@@ -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/<case_no>/customer/rebind`,body `{ customer_id, expected_order_data_version, reason? }`,返回刷新后的识别结果与快照投影。
|
||||
|
||||
### 零改动项与边界备忘
|
||||
|
||||
- **匹配与门禁零触碰**:匹配键=预约单号+料号,与客户无关,不失效匹配、不改门禁状态;守卫保证仅 Excel 未产生时可改绑,改后回通知准备重新生成 Excel;ODM 白名单导出时实时读新客户 `odm_ids`,无需任何配置动作。
|
||||
- **已放行缺口行的补录证据不随改绑重算**:放行决定仍有效,导出按快照 `release_field_values` 全量字典取值。
|
||||
- **Excel 表头客户名文字来自单据原文,不随改绑变化**(产品确认项)。
|
||||
- 预约号是货代侧事实,与客户无关,不重跑预约校验;不做「Excel 已产生后改绑作废重出」模型(守卫直接拒绝)。
|
||||
|
||||
### 设计与实施记录
|
||||
|
||||
- 设计 spec:[2026-10-13 确认客户改绑设计](../../superpowers/specs/2026-10-13-customer-rebind-design.md);实施计划:[2026-10-13 确认客户改绑计划](../../superpowers/plans/2026-10-13-customer-rebind.md)。
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
# 确认客户改绑(Customer Rebind)实施计划
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** 已确认订单在产生发货通知/Excel 之前,允许用户在订单复核工作台的客户识别面板上直接修改确认客户(改绑),改后重新冻结快照并重新生成 Excel。
|
||||
|
||||
**Architecture:** 客户识别面板两态化(未识别=现状流程;已识别=默认折叠摘要条+「修改客户」),前端管控复用编辑窗头级谓词;后端新增 `rebind_confirmed_customer` 一条链(守卫→更新 resolution 行→审计→手动重冻结),匹配/门禁零触碰——守卫保证仅在无 Excel 产物时可改,无失效连锁。
|
||||
|
||||
**Tech Stack:** Flask + SQLAlchemy 2.0(后端);Vue 3 + TypeScript + Vue I18n 四语言(前端)。
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-10-13-customer-rebind-design.md`
|
||||
|
||||
## Global Constraints
|
||||
|
||||
- 🚫 禁止自动 commit;任务以 `git add <具体文件>` 收尾(工作区有他人并行 WIP)。
|
||||
- 🌍 前端新增文案四语言(zh-CN/zh-TW/en/th)同步;chat.json 用精确子串编辑,禁 PowerShell 改写。
|
||||
- 🧷 冻结契约:`evidence_json` 与 `identity_rule_set_checksum` 必须保持非空(`order_freeze_service._confirmed_ordering_customer` 校验,:274-287);`freeze_order_snapshot(mode='manual')` 必须传 `actor_id`。
|
||||
- ⚠️ 匹配/门禁状态零改动:本能力不触碰 `export.py`、`post_ot_fulfillment_wave_service.py`、门禁 gate 行。
|
||||
- 📝 新函数含 Args/Returns docstring;测试有断言意图注释(§5.4)。
|
||||
- 后端测试:`cd backend && ./.venv/Scripts/python.exe -m pytest <file> -q`;前端 vitest 可用 + `npm run build`。
|
||||
|
||||
---
|
||||
|
||||
### Task 1: 后端改绑服务 + API
|
||||
|
||||
**Files:**
|
||||
- Modify: `backend/app/services/shipping_notice/customer_resolution_service.py`(新增 `rebind_confirmed_customer`)
|
||||
- Modify: `backend/app/api/workspace/shipping_notice.py`(新增 rebind 端点,模式对齐同文件 `order-review-cases/<case_no>/line-fulfillment/decide` 路由 :2163-2194)
|
||||
- Test: `backend/tests/test_customer_resolution_rebind.py`(新建;夹具对齐既有客户确认相关测试的构造,执行者按文件内/相邻测试文件现状取用)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: `resolution_for_task(task)`(本服务既有);`editable_scope(order_task)['header']`(`order_edit_window_service.py:121`);`freeze_order_snapshot(task, actor_id, expected_order_data_version, freeze_mode='manual')`(`order_freeze_service.py`)。
|
||||
- Produces: `rebind_confirmed_customer(*, task, new_customer_id, actor_id, reason=None) -> dict`(返回 {'resolution': 行, 'snapshot': 重冻结快照});API `POST .../order-review-cases/<case_no>/customer/rebind`。
|
||||
|
||||
- [ ] **Step 1: 写失败测试**
|
||||
|
||||
```python
|
||||
def test_rebind_updates_confirmed_customer_and_refreezes_snapshot():
|
||||
"""改绑必须更新确认结果并按新客户重冻结快照(客户 ODM 白名单随新客户生效)。"""
|
||||
# 夹具:已确认 resolution(status='confirmed', confirmed_customer_id=旧客户, evidence_json 非空)
|
||||
# + 已冻结快照 + 无 Export Artifact/无活动 Attempt(editable_scope.header=True)。
|
||||
result = rebind_confirmed_customer(
|
||||
task=task, new_customer_id=int(new_customer.id), actor_id=int(user.id), reason='选错客户',
|
||||
)
|
||||
# 断言意图:确认结果与快照客户同步改绑;审计与 evidence_json 记录原客户(可追溯)。
|
||||
assert result['resolution'].confirmed_customer_id == int(new_customer.id)
|
||||
assert result['snapshot'].customer_id == int(new_customer.id)
|
||||
assert result['resolution'].evidence_json['rebind']['previous_customer_id'] == int(old_customer.id)
|
||||
assert result['resolution'].identity_rule_set_checksum # 冻结契约:保持非空
|
||||
|
||||
|
||||
def test_rebind_rejects_when_export_artifact_exists():
|
||||
"""已产生 Excel(header 不可编辑)时改绑必须 409,且确认结果不被改动。"""
|
||||
# 夹具:同上,但给任一通知造 Export Artifact(对齐既有 artifact 测试构造)。
|
||||
with pytest.raises(ConflictError) as exc:
|
||||
rebind_confirmed_customer(task=task, new_customer_id=int(new_customer.id), actor_id=int(user.id))
|
||||
# 断言意图:A 管控 fail-closed;错误码可前端定位。
|
||||
assert exc.value.code == 'SHIPPING.CUSTOMER_REBIND_BLOCKED'
|
||||
assert resolution_row.confirmed_customer_id == int(old_customer.id)
|
||||
|
||||
|
||||
def test_rebind_rejects_same_customer_and_unknown_customer():
|
||||
"""同客户重复改绑与不存在/停用客户都必须 409/404,不产生副作用。"""
|
||||
```
|
||||
|
||||
(夹具构造对齐仓库内既有客户确认测试;断言语义以三段注释为准。)
|
||||
|
||||
- [ ] **Step 2: 确认失败**
|
||||
|
||||
Run: `cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_customer_resolution_rebind.py -q`
|
||||
Expected: FAIL(函数不存在)
|
||||
|
||||
- [ ] **Step 3: 实现**
|
||||
|
||||
`rebind_confirmed_customer` 顺序:
|
||||
1. `resolution = resolution_for_task(task)`;`status != 'confirmed'` → ConflictError(提示走识别确认流程)。
|
||||
2. `editable_scope(task)['header']` 非 True → ConflictError `SHIPPING.CUSTOMER_REBIND_BLOCKED`(details 标注 excel_exists / active_attempt)。
|
||||
3. 新客户存在且启用(ShippingCustomer 查询)且 ≠ `resolution.confirmed_customer_id`,否则 404/409。
|
||||
4. `previous = resolution.confirmed_customer_id`;更新 id;`evidence_json = {**evidence_json, 'rebind': {...previous, new, actor_id, reason, utcnow}}`;flush。
|
||||
5. 审计(事件类型对齐 `progress_audit_contract` 既有集合,执行者核对后选用;before/after 客户 + reason)。
|
||||
6. `freeze_order_snapshot(task, actor_id=actor_id, expected_order_data_version=int(task.order_data_version or 1), freeze_mode='manual')`;返回 resolution + 新快照。
|
||||
|
||||
API 端点:校验登录与 case 归属(对齐 decide 端点的守卫风格),`actor_id` 取当前用户,调用服务,返回刷新 case 投影(复用既有序列化 helper)。
|
||||
|
||||
- [ ] **Step 4: 确认通过 + 回归**
|
||||
|
||||
```bash
|
||||
cd backend && ./.venv/Scripts/python.exe -m pytest tests/test_customer_resolution_rebind.py tests/test_shipping_notice_ui_state.py -q
|
||||
```
|
||||
(ui_state 已知基线失败 2 个不算。)另跑一个冻结相关套件确认零回归:`pytest tests/test_shipping_order_edit_window.py -q`。
|
||||
|
||||
- [ ] **Step 5: Stage**
|
||||
|
||||
```bash
|
||||
git add backend/app/services/shipping_notice/customer_resolution_service.py backend/app/api/workspace/shipping_notice.py backend/tests/test_customer_resolution_rebind.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: 前端面板两态化 + 修改客户弹窗
|
||||
|
||||
**Files:**
|
||||
- Modify: `frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue`(两态化:resolved → 折叠摘要条;新增修改客户流程,复用既有 `searchCustomers` 与客户选择组件)
|
||||
- Modify: `frontend/src/features/chat/views/ShippingOrderReviewView.vue`(面板 props:传入 `:rebind-allowed`(`formalEditWindow?.header === true`,:466 formalEditWindow)与禁用原因;渲染条件 `v-if="!activeCase.customer_resolution?.resolved"` 改为始终渲染并交由面板内部分态)
|
||||
- Modify: `frontend/src/features/chat/api/shipping.api.ts`(新增 `rebindWorkspaceShippingOrderReviewCustomer(caseNo, { customer_id, reason })`)
|
||||
- Modify: `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json`(新键,见 Task 3)
|
||||
- Test: `frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts`(新建/扩展,对齐既有面板 spec 写法)
|
||||
|
||||
**Interfaces:**
|
||||
- Consumes: Task 1 API;`formalEditWindow`(view :466);面板既有 `searchCustomers`(:111)与 `refreshed` emit。
|
||||
- Produces: 面板 props `rebindAllowed: boolean`;emit `refreshed`(复用)。
|
||||
|
||||
- [ ] **Step 1: spec 断言先行**
|
||||
|
||||
```typescript
|
||||
// 断言意图:已识别态默认折叠为摘要条(状态徽标+客户名),不默认展开详情;
|
||||
// 「修改客户」按钮在 rebindAllowed=false 时禁用。
|
||||
it('renders collapsed summary with customer name when resolved', ...)
|
||||
it('disables rebind button when rebindAllowed is false and shows reason', ...)
|
||||
it('submits rebind with selected customer and emits refreshed', ...)
|
||||
```
|
||||
|
||||
(按该文件/相邻面板 spec 的 mount 与查询写法落地;先跑确认失败。)
|
||||
|
||||
- [ ] **Step 2: 实现面板两态**
|
||||
|
||||
- `resolved=true`:渲染折叠条——`已确认` 徽标 + `resolution` 中的标准客户名(现有字段)+ chevron(展开显示既有识别详情,**无 ODM 范围**)+ 「修改客户」按钮(`:disabled="!rebindAllowed"` + tooltip 用禁用原因 i18n 键)。
|
||||
- 修改客户流程:打开复用的客户搜索选择(`searchCustomers`)→ 选定 → 影响确认弹窗(i18n 文案见 Task 3)→ `rebindWorkspaceShippingOrderReviewCustomer` → 成功 toast("客户已更新,可回通知准备重新生成 Excel")→ `emit('refreshed')`。
|
||||
- `resolved=false`:原样。
|
||||
|
||||
- [ ] **Step 3: 视图接线**
|
||||
|
||||
`ShippingOrderReviewView.vue:6008` 的 `v-if` 改为始终渲染该面板(resolved 与否由面板分态);补 props `:rebind-allowed="formalEditWindow?.header === true"`;`@refreshed="handleReviewGateDataRefreshed"` 既有。
|
||||
|
||||
- [ ] **Step 4: 验收**
|
||||
|
||||
```bash
|
||||
cd frontend && npx vitest run src/features/chat/components/shipping-review/ && npm run build
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Stage**
|
||||
|
||||
```bash
|
||||
git add frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue frontend/src/features/chat/components/shipping-review/ReviewCustomerResolutionPanel.spec.ts frontend/src/features/chat/views/ShippingOrderReviewView.vue frontend/src/features/chat/api/shipping.api.ts frontend/src/locales/zh-CN/chat.json frontend/src/locales/zh-TW/chat.json frontend/src/locales/en/chat.json frontend/src/locales/th/chat.json
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: i18n 四语言
|
||||
|
||||
**Files:**
|
||||
- Modify: 四语言 `chat.json` 的 `shippingOrderReview` 域内(建议 `customerResolution` 邻近块)
|
||||
|
||||
**Interfaces:** Produces 键:`rebindButton`(修改客户)、`rebindDisabledExcelExists`(禁用原因)、`rebindConfirmTitle`、`rebindConfirmImpact`、`rebindSuccessToast`(文案含"可回通知准备重新生成 Excel")、`rebindFailedToast`。
|
||||
|
||||
- [ ] 四语言值:
|
||||
|
||||
| 键 | zh-CN | zh-TW | en | th |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| rebindButton | 修改客户 | 修改客戶 | Change customer | เปลี่ยนลูกค้า |
|
||||
| rebindDisabledExcelExists | 已产生发货通知/Excel,请先走撤销流程 | 已產生發貨通知/Excel,請先走撤銷流程 | Notice/Excel already generated — undo it first | มีการแจ้งเตือน/Excel แล้ว โปรดยกเลิกก่อน |
|
||||
| rebindConfirmTitle | 确认修改客户 | 確認修改客戶 | Confirm customer change | ยืนยันการเปลี่ยนลูกค้า |
|
||||
| rebindConfirmImpact | 将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成 | 將更新訂單客戶並重新凍結訂單快照;已產生的發貨通知/Excel 需重新生成 | The order customer will be updated and the snapshot re-frozen; generated notice/Excel must be regenerated | ลูกค้าจะถูกอัปเดตและ snapshot จะถูก freeze ใหม่ |
|
||||
| rebindSuccessToast | 客户已更新,可回通知准备重新生成 Excel | 客戶已更新,可回通知準備重新產生 Excel | Customer updated — regenerate the Excel in notice preparation | อัปเดตลูกค้าแล้ว สร้าง Excel ใหม่ได้ |
|
||||
| rebindFailedToast | 客户修改失败 | 客戶修改失敗 | Failed to change customer | เปลี่ยนลูกค้าไม่สำเร็จ |
|
||||
|
||||
- [ ] JSON 合法性校验(node 解析四文件);`git add` 四文件。
|
||||
|
||||
---
|
||||
|
||||
### Task 4: 文档 + 回归
|
||||
|
||||
- [ ] `docs/features/shipping-notice/technical.md` 文末追加「确认客户改绑(2026-10-13)」(守卫/链路/边界备忘——已放行证据不重算);`docs/funclist.md` 加 1 行。
|
||||
- [ ] 回归:后端 `pytest tests/test_customer_resolution_rebind.py tests/test_shipping_order_edit_window.py tests/test_shipping_notice_ui_state.py -q`(ui_state 2 个基线失败除外);前端 vitest 面板 spec + `npm run build`。
|
||||
- [ ] 人工冒烟:本地复现单(SORC-336EB5E5D6D84CBE)——折叠条显示;客户 15 补 ODM 或改绑到维护了 581 的客户;回通知准备重新生成 Excel 成功。
|
||||
|
||||
## Self-Review
|
||||
|
||||
- 规格覆盖:两态化/折叠/无 ODM 展示 → Task 2;管控 A → Task 1 守卫 + Task 2 按钮禁用;改绑链 → Task 1;审计/追溯 → Step 3.5;边界 → spec §4 + Task 4 文档。
|
||||
- 占位符:夹具构造与事件类型对齐项已给出现有锚点(文件:行)与断言语义,属执行者对齐指引。
|
||||
- 类型一致:`rebind_confirmed_customer` 签名、API 路径、`rebindAllowed` prop、i18n 键名前后一致。
|
||||
@@ -0,0 +1,51 @@
|
||||
# 确认客户改绑(Customer Rebind)设计
|
||||
|
||||
日期:2026-10-13 | 状态:待评审 | 关联案例:SORC-336EB5E5D6D84CBE(客户选错 → Excel 生成 ODM 白名单失败)
|
||||
|
||||
## 1. 背景与目标
|
||||
|
||||
订单复核阶段客户选错,任务推进到通知准备后 Excel 生成失败(`artifact_generation`:库存行 ODM ID 不在客户维护范围内)。当前**确认后没有任何入口可以改客户**:客户识别面板在 `customer_resolution.resolved` 后整体消失(`ShippingOrderReviewView.vue:6008`)。
|
||||
|
||||
目标:在订单复核工作台的客户识别面板上,允许用户**直接修改客户识别的确认结果**(不重走识别候选确认),改完回通知准备重新生成 Excel。
|
||||
|
||||
## 2. 交互设计
|
||||
|
||||
### 2.1 面板两态化(`ReviewCustomerResolutionPanel`)
|
||||
|
||||
- **未识别**(`resolved=false`):保持现状(识别候选确认流程)。
|
||||
- **已识别**(`resolved=true`):面板默认**折叠为一行摘要条**(不再整体消失):
|
||||
- 摘要条:状态徽标「已确认」+ 标准客户名(截断)+ 展开 chevron + 「修改客户」按钮;
|
||||
- 展开:显示既有识别详情(命中输入/识别依据等历史信息);**不展示 ODM 范围**;
|
||||
- 「修改客户」按钮的可用性 = 编辑窗头级谓词(`editable_scope(order_task)['header']`,即:该订单任一通知无 Export Artifact 且无活动 Gate Attempt)。不满足 → 按钮禁用 + tooltip 说明("已产生发货通知/Excel,请先走撤销流程")。
|
||||
|
||||
### 2.2 修改客户流程
|
||||
|
||||
点「修改客户」→ 复用既有客户搜索组件(`searchCustomers`)直接选定目标客户(**不重走识别候选打分确认**)→ 二次确认弹窗(明示影响:「将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成」)→ 提交 → 成功 toast("客户已更新,可回通知准备重新生成 Excel")→ `refreshed` 事件走既有刷新链。
|
||||
|
||||
## 3. 后端设计
|
||||
|
||||
`customer_resolution_service.rebind_confirmed_customer(task, new_customer_id, actor_id, reason=None)`:
|
||||
|
||||
1. **守卫(fail-closed,顺序固定)**:
|
||||
- resolution 行存在且 `status='confirmed'`(未确认走既有确认流程,409);
|
||||
- `editable_scope(order_task)['header']` 为 True,否则 409 `SHIPPING.CUSTOMER_REBIND_BLOCKED`(details 区分:Excel 已产生 / 存在活动 Attempt);
|
||||
- 新客户存在且启用,且 ≠ 当前确认客户。
|
||||
2. **更新**:`confirmed_customer_id = new_customer_id`;`evidence_json` 追加 rebind 记录(时间/操作人/原因/原客户,保持非空契约);`identity_rule_set_checksum` 保留不动(冻结要求非空)。
|
||||
3. **审计**:`append_shipping_audit_event`(before/after confirmed_customer_id + reason,事件类型对齐仓库审计契约)。
|
||||
4. **重冻结**:`freeze_order_snapshot(mode='manual', actor_id, expected_order_data_version)`——快照 `customer_id`/客户简称/模板头字段全部按新客户刷新;乐观锁冲突透传 409。
|
||||
5. **不动的部分**:不失效匹配(匹配键=预约+料号,与客户无关);不改门禁状态(Excel 未产生时无可失效产物——守卫已保证;Excel 已产生时守卫直接拒绝)。
|
||||
6. **API**:`POST /api/workspace/shipping-notice/order-review-cases/<case_no>/customer/rebind`,body `{customer_id, reason?}` → 返回刷新后的 case 投影。
|
||||
|
||||
## 4. 边界与不做的事
|
||||
|
||||
- 已放行缺口行的补录证据不随改绑重算(决定仍有效,导出按快照 `release_field_values` 全量字典取值)——文档备忘。
|
||||
- 预约号是货代侧事实,与客户无关,不重跑预约校验。
|
||||
- Excel 已产生时改绑被守卫拒绝(A 管控),不做"改后作废重出"模型。
|
||||
- ODM 白名单在导出时实时读新客户的 `odm_ids`,改绑后无需任何 ODM 配置动作即可被「重新生成 Excel」消费。
|
||||
|
||||
## 5. 验收标准
|
||||
|
||||
1. 已识别面板默认折叠,展示确认客户摘要;未识别态行为不变。
|
||||
2. Excel 未产生时「修改客户」可用,走搜索→确认→提交后:快照客户更新、审计落库、工作台自动刷新。
|
||||
3. Excel 已产生/有活动 Attempt 时按钮禁用并说明原因;直接调 API 返回 409。
|
||||
4. 改绑后重新生成 Excel 使用新客户 ODM 白名单(本案例:白名单含 581 后成功出单)。
|
||||
@@ -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),
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 重新检测建单前重复订单。
|
||||
*/
|
||||
|
||||
@@ -25,17 +25,20 @@ watch(() => props.open, (open) => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="open" class="admin-modal-overlay animate-fade-in items-center z-[170]">
|
||||
<div class="admin-modal-panel max-w-xl max-h-[90vh] scale-100">
|
||||
<div class="px-6 py-5 border-b border-subtle"><h3 class="section-title">{{ t('chat.shippingCustomer.title') }}</h3><p class="section-desc mt-1">{{ t('chat.shippingCustomer.subtitle') }}</p></div>
|
||||
<div class="px-6 py-5 space-y-4 overflow-y-auto">
|
||||
<div class="flex gap-2"><input v-model="query" class="input-field text-sm" :placeholder="t('chat.shippingCustomer.searchPlaceholder')" @keyup.enter="emit('search', query)" /><button type="button" class="btn-ghost" @click="emit('search', query)">{{ t('chat.shippingCustomer.search') }}</button></div>
|
||||
<div class="space-y-2 max-h-80 overflow-y-auto">
|
||||
<label v-for="customer in options" :key="customer.id" class="flex items-center gap-3 rounded-xl border border-default p-3 cursor-pointer hover:border-brand-300"><input v-model="selectedId" type="radio" :value="customer.id" /><span class="flex-1"><span class="font-medium text-primary">{{ customer.standard_name }}</span><span class="ml-2 font-mono text-xs text-muted">{{ customer.short_code }}</span></span></label>
|
||||
<div v-if="!loading && !options.length" class="text-sm text-muted py-8 text-center">{{ t('chat.shippingCustomer.empty') }}</div>
|
||||
<!-- Teleport 到 body:面板/工作区子树的层叠上下文会让页内 fixed 遮罩被粘性列表穿透。 -->
|
||||
<Teleport to="body">
|
||||
<div v-if="open" class="admin-modal-overlay animate-fade-in items-center z-[170]">
|
||||
<div class="admin-modal-panel max-w-xl max-h-[90vh] scale-100">
|
||||
<div class="px-6 py-5 border-b border-subtle"><h3 class="section-title">{{ t('chat.shippingCustomer.title') }}</h3><p class="section-desc mt-1">{{ t('chat.shippingCustomer.subtitle') }}</p></div>
|
||||
<div class="px-6 py-5 space-y-4 overflow-y-auto">
|
||||
<div class="flex min-w-0 gap-2"><input v-model="query" class="input-field min-w-0 flex-1 text-sm" :placeholder="t('chat.shippingCustomer.searchPlaceholder')" @keyup.enter="emit('search', query)" /><button type="button" class="btn-ghost shrink-0 whitespace-nowrap" @click="emit('search', query)">{{ t('chat.shippingCustomer.search') }}</button></div>
|
||||
<div class="space-y-2 max-h-80 overflow-y-auto">
|
||||
<label v-for="customer in options" :key="customer.id" class="flex cursor-pointer items-center gap-3 rounded-xl border p-3" :class="selectedId === customer.id ? 'border-brand-500 bg-brand-50' : 'border-default hover:border-brand-300'"><input v-model="selectedId" type="radio" :value="customer.id" class="accent-brand-600" /><span class="flex-1"><span class="font-medium text-primary">{{ customer.standard_name }}</span><span class="ml-2 font-mono text-xs text-muted">{{ customer.short_code }}</span></span></label>
|
||||
<div v-if="!loading && !options.length" class="text-sm text-muted py-8 text-center">{{ t('chat.shippingCustomer.empty') }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="admin-modal-footer"><button type="button" class="btn-ghost" @click="emit('close')">{{ t('common.cancel') }}</button><button type="button" class="btn-primary" :disabled="!selectedId || loading" @click="selectedId && emit('confirm', selectedId)">{{ t('chat.shippingCustomer.confirm') }}</button></div>
|
||||
</div>
|
||||
<div class="admin-modal-footer"><button type="button" class="btn-ghost" @click="emit('close')">{{ t('common.cancel') }}</button><button type="button" class="btn-primary" :disabled="!selectedId || loading" @click="selectedId && emit('confirm', selectedId)">{{ t('chat.shippingCustomer.confirm') }}</button></div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
+127
-11
@@ -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<string, unknown>, extraProps: Record<string, unknown> = {}) {
|
||||
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);
|
||||
});
|
||||
});
|
||||
+199
-26
@@ -1,9 +1,11 @@
|
||||
<!--
|
||||
features/chat/components/shipping-review/ReviewCustomerResolutionPanel.vue
|
||||
用途:复核工作台固定「建单前客户确认」区域(与重新识别 PDF 分层)。
|
||||
依赖:vue-i18n、ShippingCustomerConfirmDialog、shipping.api 客户确认/重识别接口。
|
||||
逻辑:未解决时完整展开置顶;已解决且 compact 时缩为一行摘要;
|
||||
选择标准客户 / 重新识别客户;成功后 emit refreshed 刷新建单资格。
|
||||
用途:复核工作台固定「建单前客户确认」区域,两态渲染:未确认走识别候选确认流程;已确认折叠为一行摘要条并提供「修改客户」改绑入口。
|
||||
依赖:vue-i18n、ShippingCustomerConfirmDialog、shipping.api 客户确认/重识别/改绑接口。
|
||||
逻辑:resolved=false 时完整展开置顶(现状不动);resolved=true 时默认折叠摘要条(已确认徽标+标准客户名+chevron+修改客户按钮),
|
||||
chevron 展开既有识别详情(不含 ODM 范围);改绑走「复用客户搜索选定 → 影响确认弹窗 → rebind API → 成功 toast → emit refreshed」。
|
||||
resolution.rebind_allowed=false(Excel 已产生/活动 Attempt,后端投影下发)时按钮禁用并以 tooltip 说明;
|
||||
后端 fail-closed 兜底,409 的 BusinessError localized message 直接经 toast 展示。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
@@ -14,6 +16,7 @@ import ShippingCustomerConfirmDialog from '@/features/chat/components/ShippingCu
|
||||
import {
|
||||
confirmWorkspaceShippingOrderReviewCustomer,
|
||||
listWorkspaceShippingCustomerOptions,
|
||||
rebindWorkspaceShippingOrderReviewCustomer,
|
||||
retryWorkspaceShippingOrderReviewCustomerResolution,
|
||||
} from '@/features/chat/api/shipping.api';
|
||||
import type {
|
||||
@@ -25,7 +28,10 @@ const props = defineProps<{
|
||||
caseNo: string;
|
||||
resolution: ShippingOrderReviewCustomerResolution | null | undefined;
|
||||
editable: boolean;
|
||||
/** 已解决时缩为一行摘要(放入「更多状态」) */
|
||||
/** 已确认改绑入口可用性:edit_window.header 明确 false 时禁用;缺失/undefined 视为可用(后端权威守卫兜底) */
|
||||
/** 改绑乐观锁版本:case 投影的 order_data_version(正式任务当前版本),缺省时后端按版本冲突拒绝 */
|
||||
orderDataVersion?: number | null;
|
||||
/** 已解决时缩为一行摘要(历史兼容属性;已确认态现在恒为折叠摘要条) */
|
||||
compact?: boolean;
|
||||
}>();
|
||||
|
||||
@@ -39,8 +45,15 @@ const busy = ref(false);
|
||||
const dialogOpen = ref(false);
|
||||
const options = ref<ShippingCustomerOption[]>([]);
|
||||
const loadingOptions = ref(false);
|
||||
/** 已确认态识别详情是否展开(默认折叠为一行摘要条) */
|
||||
const confirmedDetailsExpanded = ref(false);
|
||||
/** 改绑影响确认弹窗显隐与待提交的新客户 */
|
||||
const rebindConfirmOpen = ref(false);
|
||||
const pendingRebindCustomerId = ref<number | null>(null);
|
||||
|
||||
const resolved = computed(() => Boolean(props.resolution?.resolved));
|
||||
/** 改绑可用性:prop 缺省视为可用,与 formalHeaderEditable 的 fail-open 语义对齐(后端 409 兜底) */
|
||||
const rebindAllowed = computed(() => props.resolution?.rebind_allowed === true);
|
||||
const hasUniqueCandidate = computed(() => (
|
||||
!resolved.value
|
||||
&& String(props.resolution?.status || '').trim() === 'unique_candidate'
|
||||
@@ -66,6 +79,15 @@ const displayName = computed(() => {
|
||||
const inputValues = computed(() => props.resolution?.input_values || []);
|
||||
const candidateRows = computed(() => props.resolution?.candidates || []);
|
||||
|
||||
/** 改绑影响确认弹窗中展示的待提交客户名;选项已卸载时回落展示 ID。 */
|
||||
const pendingRebindCustomerLabel = computed(() => {
|
||||
const customerId = pendingRebindCustomerId.value;
|
||||
if (customerId == null) return '—';
|
||||
const match = options.value.find((item) => item.id === customerId);
|
||||
if (match) return `${match.standard_name} (${match.short_code})`;
|
||||
return `#${customerId}`;
|
||||
});
|
||||
|
||||
function inputLabel(definitionCode: string | null | undefined): string {
|
||||
const code = String(definitionCode || '').trim().toLowerCase();
|
||||
if (code.includes('customer') && code.includes('code')) return t('chat.shippingOrderReview.customerResolution.inputLabels.customerCode');
|
||||
@@ -84,8 +106,13 @@ function candidateValue(candidate: unknown, key: string): string {
|
||||
return String(row[key] ?? '').trim() || '—';
|
||||
}
|
||||
|
||||
/** 切换已确认摘要条的识别详情展开/折叠。 */
|
||||
function toggleConfirmedDetails() {
|
||||
confirmedDetailsExpanded.value = !confirmedDetailsExpanded.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 打开标准客户选择弹窗并加载选项。
|
||||
* 打开标准客户选择弹窗并加载选项(未确认确认流程入口,also 供父级经 ref 外部触发)。
|
||||
*/
|
||||
async function openSelectDialog() {
|
||||
if (!props.editable || busy.value) return;
|
||||
@@ -106,7 +133,25 @@ defineExpose({
|
||||
});
|
||||
|
||||
/**
|
||||
* 按关键词搜索标准客户。
|
||||
* 打开改绑客户选择弹窗(已确认态「修改客户」入口;复用同一搜索选择弹窗)。
|
||||
* AI 触发时机:用户在已确认摘要条点击「修改客户」时进入;rebindAllowed=false 时按钮已禁用,这里仅兜底防抖。
|
||||
*/
|
||||
async function openRebindDialog() {
|
||||
if (!rebindAllowed.value || busy.value) return;
|
||||
dialogOpen.value = true;
|
||||
loadingOptions.value = true;
|
||||
try {
|
||||
options.value = await listWorkspaceShippingCustomerOptions();
|
||||
} catch (error: unknown) {
|
||||
options.value = [];
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
|
||||
} finally {
|
||||
loadingOptions.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 按关键词搜索标准客户(客户选择弹窗复用入口)。
|
||||
*/
|
||||
async function searchCustomers(query: string) {
|
||||
loadingOptions.value = true;
|
||||
@@ -120,7 +165,20 @@ async function searchCustomers(query: string) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认标准客户并通知父级刷新 Case / 建单资格。
|
||||
* 客户选择弹窗确认分发:已确认态进入改绑影响确认(不重走识别确认);未确认态走既有确认建单链路。
|
||||
*/
|
||||
function onCustomerDialogConfirm(customerId: number) {
|
||||
if (resolved.value) {
|
||||
pendingRebindCustomerId.value = customerId;
|
||||
dialogOpen.value = false;
|
||||
rebindConfirmOpen.value = true;
|
||||
return;
|
||||
}
|
||||
void onConfirm(customerId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认标准客户并通知父级刷新 Case / 建单资格(仅未确认态)。
|
||||
*/
|
||||
async function onConfirm(customerId: number) {
|
||||
if (!props.caseNo || busy.value) return;
|
||||
@@ -152,6 +210,34 @@ async function onConfirm(customerId: number) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 提交改绑:携带 case 投影的 order_data_version 乐观锁调用 rebind API;成功后 toast 并 emit refreshed 走既有刷新链。
|
||||
* 失败:BusinessError(含 409 守卫/版本冲突)展示后端 localized message;其余错误回落 rebindFailedToast。
|
||||
*/
|
||||
async function onRebindConfirmSubmit() {
|
||||
const customerId = pendingRebindCustomerId.value;
|
||||
if (!props.caseNo || customerId == null || busy.value) return;
|
||||
busy.value = true;
|
||||
try {
|
||||
await rebindWorkspaceShippingOrderReviewCustomer(props.caseNo, {
|
||||
customer_id: customerId,
|
||||
expected_order_data_version: Number(props.orderDataVersion ?? 0),
|
||||
});
|
||||
rebindConfirmOpen.value = false;
|
||||
pendingRebindCustomerId.value = null;
|
||||
confirmedDetailsExpanded.value = false;
|
||||
msg.success(t('chat.shippingOrderReview.customerResolution.rebindSuccessToast'));
|
||||
emit('refreshed');
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof BusinessError
|
||||
? resolveLocalizedErrorMessage(error.code, error.message)
|
||||
: t('chat.shippingOrderReview.customerResolution.rebindFailedToast');
|
||||
msg.warning(message);
|
||||
} finally {
|
||||
busy.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重新识别客户(不触发 PDF 重识别)。
|
||||
*/
|
||||
@@ -178,26 +264,74 @@ async function onRetry() {
|
||||
class="rounded-xl border border-default bg-surface p-3 shadow-sm"
|
||||
data-testid="review-customer-resolution-panel"
|
||||
:data-compact="compact && resolved ? 'true' : 'false'"
|
||||
:data-state="resolved ? 'resolved' : 'pending'"
|
||||
>
|
||||
<!-- 已解决摘要:一行展示客户与状态,避免占满侧栏首位 -->
|
||||
<!-- 已确认态:折叠摘要条(已确认徽标 + 标准客户名 + chevron + 修改客户入口),不整体占位 -->
|
||||
<template v-if="resolved">
|
||||
<div
|
||||
v-if="compact && resolved"
|
||||
class="flex flex-wrap items-center justify-between gap-2"
|
||||
data-testid="review-customer-resolution-compact"
|
||||
>
|
||||
<p class="text-xs text-secondary">
|
||||
<span class="font-medium text-primary">{{ t('chat.shippingOrderReview.customerResolution.title') }}</span>
|
||||
<span class="mx-1 text-muted">·</span>
|
||||
<span>{{ displayName }}</span>
|
||||
</p>
|
||||
<span
|
||||
class="rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-medium text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100"
|
||||
data-testid="review-customer-resolution-badge"
|
||||
<button
|
||||
type="button"
|
||||
class="flex min-w-0 flex-1 items-center gap-2 text-left"
|
||||
data-testid="review-customer-resolution-toggle"
|
||||
:aria-expanded="confirmedDetailsExpanded"
|
||||
@click="toggleConfirmedDetails"
|
||||
>
|
||||
{{ statusLabel }}
|
||||
</span>
|
||||
<span
|
||||
class="shrink-0 rounded-full bg-emerald-100 px-2 py-0.5 text-[11px] font-medium text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100"
|
||||
data-testid="review-customer-resolution-badge"
|
||||
>
|
||||
{{ statusLabel }}
|
||||
</span>
|
||||
<span class="truncate text-xs font-medium text-primary">{{ displayName }}</span>
|
||||
<span class="shrink-0 text-[10px] text-muted" aria-hidden="true">{{ confirmedDetailsExpanded ? '▲' : '▼' }}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="shrink-0 rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary hover:bg-surface-soft disabled:opacity-60"
|
||||
data-testid="review-rebind-customer"
|
||||
:disabled="!rebindAllowed || busy"
|
||||
:title="rebindAllowed ? undefined : t('chat.shippingOrderReview.customerResolution.rebindDisabledExcelExists')"
|
||||
@click="openRebindDialog"
|
||||
>
|
||||
{{ t('chat.shippingOrderReview.customerResolution.rebindButton') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- 已确认展开区:既有识别详情(标准客户/编码/命中输入/候选),不含 ODM 范围 -->
|
||||
<dl
|
||||
v-if="confirmedDetailsExpanded"
|
||||
class="mt-2 space-y-1 text-xs text-secondary"
|
||||
data-testid="review-customer-resolution-details"
|
||||
>
|
||||
<div class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.standardCustomer') }}</dt>
|
||||
<dd class="font-medium text-primary">{{ displayName }}</dd>
|
||||
</div>
|
||||
<div v-if="resolution?.short_code" class="flex flex-wrap gap-x-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.customerCode') }}</dt>
|
||||
<dd class="font-mono font-medium text-primary">{{ resolution.short_code }}</dd>
|
||||
</div>
|
||||
<div v-if="inputValues.length" class="mt-2 border-t border-default pt-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.matchedInputs') }}</dt>
|
||||
<dd v-for="item in inputValues" :key="`${item.definition_code}:${item.normalized_value}`" class="mt-1 flex flex-wrap gap-x-2">
|
||||
<span class="text-muted">{{ inputLabel(item.definition_label || item.definition_code) }}</span>
|
||||
<span class="font-mono text-primary">{{ item.raw_value || item.normalized_value || '—' }}</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div v-if="candidateRows.length > 1" class="mt-2 border-t border-default pt-2">
|
||||
<dt class="text-muted">{{ t('chat.shippingOrderReview.customerResolution.candidates') }}</dt>
|
||||
<dd v-for="candidate in candidateRows" :key="String(candidate.customer_id)" class="mt-1 flex flex-wrap gap-x-2">
|
||||
<span class="text-primary">{{ candidateValue(candidate, 'standard_name') }}</span>
|
||||
<span class="font-mono text-muted">{{ candidateValue(candidate, 'short_code') }}</span>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
</template>
|
||||
<!-- 未确认态:既有识别候选确认流程(现状不动) -->
|
||||
<template v-else>
|
||||
<header class="flex flex-wrap items-start justify-between gap-2">
|
||||
<div>
|
||||
@@ -209,10 +343,7 @@ async function onRetry() {
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium"
|
||||
:class="resolved
|
||||
? 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950 dark:text-emerald-100'
|
||||
: 'bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100'"
|
||||
class="rounded-full px-2.5 py-1 text-xs font-medium bg-amber-100 text-amber-900 dark:bg-amber-950 dark:text-amber-100"
|
||||
data-testid="review-customer-resolution-badge"
|
||||
>
|
||||
{{ statusLabel }}
|
||||
@@ -269,15 +400,57 @@ async function onRetry() {
|
||||
<p class="mt-2 text-[11px] text-muted">
|
||||
{{ t('chat.shippingOrderReview.customerResolution.pdfReparseHint') }}
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<!-- 客户搜索选择弹窗:未确认态确认 / 已确认态改绑共用 -->
|
||||
<ShippingCustomerConfirmDialog
|
||||
:open="dialogOpen"
|
||||
:options="options"
|
||||
:loading="loadingOptions || busy"
|
||||
@close="dialogOpen = false"
|
||||
@search="searchCustomers"
|
||||
@confirm="onConfirm"
|
||||
@confirm="onCustomerDialogConfirm"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<!-- 改绑影响确认弹窗:明示快照重冻结与通知/Excel 重生成影响后再提交。Teleport 到 body 避免粘性列穿透。 -->
|
||||
<Teleport to="body">
|
||||
<div
|
||||
v-if="rebindConfirmOpen"
|
||||
class="admin-modal-overlay animate-fade-in items-center z-[180]"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
data-testid="review-rebind-confirm-dialog"
|
||||
>
|
||||
<div class="admin-modal-panel max-w-md scale-100">
|
||||
<div class="px-6 py-5 border-b border-subtle">
|
||||
<h3 class="section-title">{{ t('chat.shippingOrderReview.customerResolution.rebindConfirmTitle') }}</h3>
|
||||
</div>
|
||||
<div class="px-6 py-5 space-y-3 text-sm">
|
||||
<p class="text-secondary">{{ t('chat.shippingOrderReview.customerResolution.rebindConfirmImpact') }}</p>
|
||||
<p class="font-medium text-primary" data-testid="review-rebind-confirm-customer">{{ pendingRebindCustomerLabel }}</p>
|
||||
</div>
|
||||
<div class="admin-modal-footer">
|
||||
<button
|
||||
type="button"
|
||||
class="btn-ghost"
|
||||
data-testid="review-rebind-confirm-cancel"
|
||||
:disabled="busy"
|
||||
@click="rebindConfirmOpen = false"
|
||||
>
|
||||
{{ t('common.cancel') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary"
|
||||
data-testid="review-rebind-confirm-submit"
|
||||
:disabled="busy"
|
||||
@click="onRebindConfirmSubmit"
|
||||
>
|
||||
{{ t('chat.shippingCustomer.confirm') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Teleport>
|
||||
</section>
|
||||
</template>
|
||||
@@ -2556,6 +2556,8 @@ export interface ShippingOrderReviewCustomerResolution {
|
||||
resolved: boolean;
|
||||
status: string;
|
||||
role?: string;
|
||||
/** 「修改客户」按钮谓词(后端按 editable_scope.header 下发);缺省视为不可改绑。 */
|
||||
rebind_allowed?: boolean;
|
||||
extraction_id?: number | null;
|
||||
raw_name?: string | null;
|
||||
customer_id?: number | null;
|
||||
|
||||
@@ -3130,6 +3130,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-READY', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
edit_window: { header: true },
|
||||
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
stage_context: {
|
||||
preparation: {
|
||||
@@ -3201,6 +3202,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-READY', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
edit_window: { header: true },
|
||||
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
stage_context: {
|
||||
preparation: {
|
||||
@@ -3259,6 +3261,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
|
||||
task_no: 'SN-READY', status: 'processing', lines: [], events: [],
|
||||
ui_state: {
|
||||
edit_window: { header: true },
|
||||
lifecycle_stage: 'fulfillment_prep', lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
stage_context: {
|
||||
preparation: {
|
||||
|
||||
@@ -463,12 +463,12 @@ const isReviewContentReadOnly = computed(() => (
|
||||
isReadOnly.value || isCompletedFormalTask.value || isStpAutoCreateInProgress.value
|
||||
));
|
||||
|
||||
/** 二期编辑窗(D10):读正式任务 ui_state.edit_window;前端 fail-closed,锁定字段禁用/提示。 */
|
||||
/** 二期编辑窗(D10):读正式任务 ui_state.edit_window(后端权威下发,见 ui_state._build_edit_window)。 */
|
||||
const formalEditWindow = computed(() => formalTaskDetail.value?.ui_state?.edit_window ?? null);
|
||||
|
||||
/** 头字段可编辑:edit_window.header 缺省视为可编辑(后端为权威守卫)。 */
|
||||
/** 头字段可编辑:仅 edit_window.header 显式为 true(无 Export Artifact 且无活动 Attempt)时显示。 */
|
||||
function formalHeaderEditable(): boolean {
|
||||
return formalEditWindow.value?.header !== false;
|
||||
return formalEditWindow.value?.header === true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -522,8 +522,9 @@ async function retryCurrentIntakeParse(): Promise<void> {
|
||||
* 只切换前端工作面并同步可分享深链;禁止在导航点击中修改任何订单生命周期字段。
|
||||
*/
|
||||
const lifecycleStagePinnedByUserForCase = ref<string | null>(null);
|
||||
/** 仅库存短缺放行可建立一次性自动推进许可,避免通用 Gate 恢复抢占用户导航。 */
|
||||
/** 用户触发的推进类 Gate 动作可建立一次性自动推进许可(动作时阶段→新阶段),避免通用 Gate 恢复抢占用户导航。 */
|
||||
const pendingReleaseAutoAdvanceCaseNo = ref<string | null>(null);
|
||||
const pendingReleaseAutoAdvanceFromStage = ref<ReviewLifecycleStageCode | null>(null);
|
||||
/**
|
||||
* 当前重解析完成前的一次性导航许可。
|
||||
*
|
||||
@@ -561,34 +562,41 @@ function cancelPendingReparseNavigation() {
|
||||
}
|
||||
|
||||
/**
|
||||
* 消费库存短缺放行后的自动推进许可。
|
||||
* 消费用户触发的推进类 Gate 动作(缺口放行、重新生成 Excel 等)建立的一次性推进许可。
|
||||
*
|
||||
* 仅当同一 Case 仍停留在放行前的通知准备路由、用户未在放行后手动选阶段,且后端
|
||||
* 权威投影已推进时替换深链。异步 Job 的首个投影可直接到目标阶段,不能依赖 watch
|
||||
* 是否曾观察到旧阶段。
|
||||
* 仅当同一 Case 仍停留在动作发生时的阶段路由、用户未在动作后手动选阶段,且后端
|
||||
* 权威投影已越过动作时阶段时替换深链。异步 Job 的首个投影可直接到目标阶段,不能
|
||||
* 依赖 watch 是否曾观察到旧阶段。
|
||||
*/
|
||||
async function syncPendingReleaseAutoAdvance(): Promise<boolean> {
|
||||
const caseNo = String(activeCase.value?.case_no || '').trim();
|
||||
if (!caseNo || pendingReleaseAutoAdvanceCaseNo.value !== caseNo) return false;
|
||||
const fromStage = pendingReleaseAutoAdvanceFromStage.value;
|
||||
if (!caseNo || !fromStage || pendingReleaseAutoAdvanceCaseNo.value !== caseNo) return false;
|
||||
const requested = String(route.query.lifecycle_stage || '').trim();
|
||||
if (
|
||||
requested !== 'fulfillment_prep'
|
||||
requested !== fromStage
|
||||
|| lifecycleStagePinnedByUserForCase.value === caseNo
|
||||
) {
|
||||
pendingReleaseAutoAdvanceCaseNo.value = null;
|
||||
pendingReleaseAutoAdvanceFromStage.value = null;
|
||||
return false;
|
||||
}
|
||||
const current = lifecycleCurrentStageCode.value;
|
||||
const currentIndex = current ? LIFECYCLE_STAGE_CODES.indexOf(current) : -1;
|
||||
if (currentIndex <= LIFECYCLE_STAGE_CODES.indexOf('fulfillment_prep')) return false;
|
||||
if (currentIndex <= LIFECYCLE_STAGE_CODES.indexOf(fromStage)) return false;
|
||||
pendingReleaseAutoAdvanceCaseNo.value = null;
|
||||
pendingReleaseAutoAdvanceFromStage.value = null;
|
||||
await selectLifecycleStage(current!, { replace: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
async function selectLifecycleStage(code: ReviewLifecycleStageCode, options: { replace?: boolean } = {}) {
|
||||
async function selectLifecycleStage(
|
||||
code: ReviewLifecycleStageCode,
|
||||
options: { replace?: boolean; followThrough?: boolean } = {},
|
||||
) {
|
||||
const target = lifecycleStageItems.value.find((item) => item.code === code);
|
||||
if (!target || target.state === 'blocked') return;
|
||||
// followThrough:提交订单入队后允许进入尚未点亮的目标阶段(任务去向确定,阶段条随后端刷新点亮)。
|
||||
if (!target || (target.state === 'blocked' && !options.followThrough)) return;
|
||||
// 用户主动回看后端 available 或已完成阶段时,异步投影抵达不得将其强制带回当前阶段。
|
||||
// 自动推进均使用 replace,不会写入该意图。
|
||||
if (!options.replace) {
|
||||
@@ -597,6 +605,7 @@ async function selectLifecycleStage(code: ReviewLifecycleStageCode, options: { r
|
||||
rememberPendingReparseStage(code);
|
||||
if (pendingReleaseAutoAdvanceCaseNo.value === caseNo) {
|
||||
pendingReleaseAutoAdvanceCaseNo.value = null;
|
||||
pendingReleaseAutoAdvanceFromStage.value = null;
|
||||
}
|
||||
}
|
||||
if (code === 'intake_parse' && intakeParseContextAuthorized.value && intakeTargetCaseNo.value) {
|
||||
@@ -658,6 +667,7 @@ watch(
|
||||
if (caseNo !== previousCaseNo) {
|
||||
lifecycleStagePinnedByUserForCase.value = null;
|
||||
pendingReleaseAutoAdvanceCaseNo.value = null;
|
||||
pendingReleaseAutoAdvanceFromStage.value = null;
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -1779,6 +1789,8 @@ function handleGateRecoveryAccepted(options: { releaseAutoAdvance?: boolean } =
|
||||
// 放行前可能是用户手动进入通知准备;该历史意图不能阻止本次放行后的自动推进。
|
||||
lifecycleStagePinnedByUserForCase.value = null;
|
||||
pendingReleaseAutoAdvanceCaseNo.value = caseNo;
|
||||
// 记录动作时阶段:只跟随「越过动作时阶段」的一次推进,且用户主动换页会取消。
|
||||
pendingReleaseAutoAdvanceFromStage.value = lifecycleCurrentStageCode.value;
|
||||
}
|
||||
page.bumpWorkflowRefresh?.();
|
||||
startWorkflowProgressPolling();
|
||||
@@ -1876,7 +1888,7 @@ async function executeFormalTaskAction(
|
||||
if (!formalGate) return;
|
||||
const result = await submitProcessGatePrimaryAction(formalGate, { actionCode: action.code });
|
||||
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
|
||||
handleGateRecoveryAccepted();
|
||||
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1946,7 +1958,7 @@ async function handleCurrentTaskAction(
|
||||
if (serverAuthorizedGateAction) {
|
||||
const result = await submitProcessGatePrimaryAction(processGate, { actionCode: normalizedCode });
|
||||
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
|
||||
handleGateRecoveryAccepted();
|
||||
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -2011,7 +2023,7 @@ async function handleCurrentTaskAction(
|
||||
if (!summary) return;
|
||||
const result = await submitProcessGatePrimaryAction(summary, { actionCode: code });
|
||||
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
|
||||
handleGateRecoveryAccepted();
|
||||
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -2937,7 +2949,7 @@ async function confirmCloseLine() {
|
||||
expected_draft_version: activeCase.value?.draft?.draft_version,
|
||||
});
|
||||
closeLineDialogLine.value = null;
|
||||
handleGateRecoveryAccepted();
|
||||
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
|
||||
} catch (error) {
|
||||
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
|
||||
} finally {
|
||||
@@ -4082,7 +4094,8 @@ const submitFormalGateAction = async (
|
||||
});
|
||||
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
|
||||
progressRetrying.value = false;
|
||||
handleGateRecoveryAccepted();
|
||||
// 用户触发的推进类动作(重新生成 Excel 等)成功后允许自动跳到新阶段一次。
|
||||
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
|
||||
}
|
||||
} catch (error) {
|
||||
msg.error(resolveReviewErrorMessage(error));
|
||||
@@ -4113,7 +4126,7 @@ const retryStpAutoCreate = async () => {
|
||||
} else {
|
||||
await reloadLatestDraft();
|
||||
}
|
||||
handleGateRecoveryAccepted();
|
||||
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
|
||||
msg.success(t('chat.shippingOrderReview.autoProgress.retryStpSuccess'));
|
||||
} catch (error) {
|
||||
msg.error(resolveReviewErrorMessage(error));
|
||||
@@ -4330,7 +4343,7 @@ const onUnifiedProcessingAction = async (item: ActionPresentationItem) => {
|
||||
if (!formalGate) return;
|
||||
const result = await submitProcessGatePrimaryAction(formalGate, { actionCode: authorized.code });
|
||||
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
|
||||
handleGateRecoveryAccepted();
|
||||
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -4353,6 +4366,15 @@ const onValidate = async () => {
|
||||
try {
|
||||
const resume = await validate();
|
||||
showReviewResumeOutcome(resume, msg, t, t('chat.shippingOrderReview.saveOrderAndValidateSuccess'));
|
||||
// 入队即确定去向:正式任务创建后进入通知准备工作面(产品确认 2026-10-13),
|
||||
// 不再回放提交前「接收解析」的初始阶段快照;后续获取库存/货代上传推进继续跟随。
|
||||
const outcome = String(resume?.outcome || '').trim();
|
||||
if (['auto_create_enqueued', 'already_queued', 'already_running'].includes(outcome)) {
|
||||
lifecycleStagePinnedByUserForCase.value = null;
|
||||
pendingReleaseAutoAdvanceCaseNo.value = null;
|
||||
pendingReleaseAutoAdvanceFromStage.value = null;
|
||||
await selectLifecycleStage('fulfillment_prep', { replace: true, followThrough: true });
|
||||
}
|
||||
} catch (error) {
|
||||
msg.error(resolveReviewErrorMessage(error));
|
||||
}
|
||||
@@ -6000,14 +6022,16 @@ watch(
|
||||
@open-details="openEligibilityDetails"
|
||||
@navigate-exception="navigateExceptionField"
|
||||
/>
|
||||
<!-- 订单复核 Gate 统一收敛至右栏;主编辑列只保留字段、明细与证据。 -->
|
||||
<!-- 订单复核 Gate 统一收敛至右栏;主编辑列只保留字段、明细与证据。
|
||||
客户识别面板两态渲染(resolved 与否由面板内部分态):已确认折叠为摘要条并提供改绑入口,
|
||||
不再在 resolved 后整体消失。 -->
|
||||
<template v-if="showOrderReviewEditor && activeCase">
|
||||
<ReviewCustomerResolutionPanel
|
||||
v-if="!activeCase.customer_resolution?.resolved"
|
||||
ref="customerResolutionWideRef"
|
||||
:case-no="activeCase.case_no"
|
||||
:resolution="activeCase.customer_resolution"
|
||||
:editable="editable"
|
||||
:order-data-version="activeCase.order_data_version"
|
||||
@refreshed="handleReviewGateDataRefreshed"
|
||||
/>
|
||||
<ReviewFieldConflictPanel
|
||||
|
||||
@@ -2243,6 +2243,12 @@
|
||||
"retrying": "Identifying…",
|
||||
"retryDone": "Customer re-identified",
|
||||
"retryFailed": "Failed to re-identify customer",
|
||||
"rebindButton": "Change customer",
|
||||
"rebindDisabledExcelExists": "Notice/Excel already generated — undo it first",
|
||||
"rebindConfirmTitle": "Confirm customer change",
|
||||
"rebindConfirmImpact": "The order customer will be updated and the snapshot re-frozen; generated notice/Excel must be regenerated",
|
||||
"rebindSuccessToast": "Customer updated — regenerate the Excel in notice preparation",
|
||||
"rebindFailedToast": "Failed to change customer",
|
||||
"uniqueCandidateHint": "One standard customer candidate was found. Saving and validating will confirm it automatically, or you can confirm it manually.",
|
||||
"confirmUniqueCandidate": "Confirm unique candidate",
|
||||
"confirmed": "Customer confirmed",
|
||||
|
||||
@@ -605,6 +605,13 @@
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "Transfer ticket not found.",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "Legacy single-step fields would truncate this binding's multi-step recipe; submit ordered steps via steps_json instead.",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "Integration call not found.",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "Binding steps invalid: steps_json is required, must be a non-empty array of objects."
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "Binding steps invalid: steps_json is required, must be a non-empty array of objects.",
|
||||
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "Customer cannot be changed after a shipping notice/Excel has been generated — undo it first",
|
||||
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "The selected customer is already the confirmed customer",
|
||||
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "Confirm the customer identification first",
|
||||
"SHIPPING.FORMAL_OT_REQUIRED": "Create the formal task first",
|
||||
"SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED": "Select a target customer",
|
||||
"SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED": "Order version has changed — refresh and retry",
|
||||
"SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED": "Customer rebind requires an operator"
|
||||
}
|
||||
}
|
||||
@@ -2243,6 +2243,12 @@
|
||||
"retrying": "กำลังระบุ…",
|
||||
"retryDone": "ระบุลูกค้าใหม่แล้ว",
|
||||
"retryFailed": "ระบุลูกค้าใหม่ไม่สำเร็จ",
|
||||
"rebindButton": "เปลี่ยนลูกค้า",
|
||||
"rebindDisabledExcelExists": "มีการแจ้งเตือน/Excel แล้ว โปรดยกเลิกก่อน",
|
||||
"rebindConfirmTitle": "ยืนยันการเปลี่ยนลูกค้า",
|
||||
"rebindConfirmImpact": "ลูกค้าจะถูกอัปเดตและ snapshot จะถูก freeze ใหม่",
|
||||
"rebindSuccessToast": "อัปเดตลูกค้าแล้ว สร้าง Excel ใหม่ได้",
|
||||
"rebindFailedToast": "เปลี่ยนลูกค้าไม่สำเร็จ",
|
||||
"uniqueCandidateHint": "พบผู้สมัครลูกค้ามาตรฐานเพียงรายเดียว การบันทึกและตรวจสอบจะยืนยันโดยอัตโนมัติ หรือยืนยันด้วยตนเองได้",
|
||||
"confirmUniqueCandidate": "ยืนยันผู้สมัครรายเดียว",
|
||||
"confirmed": "ยืนยันลูกค้าแล้ว",
|
||||
|
||||
@@ -605,6 +605,13 @@
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "ไม่พบตั๋วโอนย้าย",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "ฟิลด์ขั้นตอนเดียวแบบเดิมจะตัดทอนสูตรหลายขั้นตอนของการผูกนี้ โปรดส่งขั้นตอนตามลำดับด้วย steps_json แทน",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "ไม่พบระเบียนการเรียกใช้งานการผสานรวม",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "การกำหนดค่าขั้นตอนการเชื่อมโยงไม่ถูกต้อง: steps_json จำเป็นต้องมีและเป็นอาร์เรย์ที่ไม่ว่าง โดยแต่ละรายการต้องเป็นออบเจกต์"
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "การกำหนดค่าขั้นตอนการเชื่อมโยงไม่ถูกต้อง: steps_json จำเป็นต้องมีและเป็นอาร์เรย์ที่ไม่ว่าง โดยแต่ละรายการต้องเป็นออบเจกต์",
|
||||
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "มีการแจ้งเตือน/Excel แล้ว ไม่สามารถเปลี่ยนลูกค้าได้ โปรดยกเลิกก่อน",
|
||||
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "ลูกค้าที่เลือกเป็นลูกค้าที่ยืนยันอยู่แล้ว",
|
||||
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "โปรดยืนยันการระบุลูกค้าก่อน",
|
||||
"SHIPPING.FORMAL_OT_REQUIRED": "โปรดสร้างงานอย่างเป็นทางการก่อน",
|
||||
"SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED": "โปรดเลือกลูกค้าเป้าหมาย",
|
||||
"SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED": "เวอร์ชันออเดอร์เปลี่ยนแปลง โปรดรีเฟรชแล้วลองใหม่",
|
||||
"SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED": "การเปลี่ยนลูกค้าต้องระบุผู้ดำเนินการ"
|
||||
}
|
||||
}
|
||||
@@ -2277,6 +2277,12 @@
|
||||
"retrying": "识别中…",
|
||||
"retryDone": "已重新识别客户",
|
||||
"retryFailed": "重新识别客户失败",
|
||||
"rebindButton": "修改客户",
|
||||
"rebindDisabledExcelExists": "已产生发货通知/Excel,请先走撤销流程",
|
||||
"rebindConfirmTitle": "确认修改客户",
|
||||
"rebindConfirmImpact": "将更新订单客户并重新冻结订单快照;已生成的发货通知/Excel 需重新生成",
|
||||
"rebindSuccessToast": "客户已更新,可回通知准备重新生成 Excel",
|
||||
"rebindFailedToast": "客户修改失败",
|
||||
"uniqueCandidateHint": "已找到唯一标准客户候选;保存校验时系统会自动确认,也可手动确认。",
|
||||
"confirmUniqueCandidate": "确认唯一候选",
|
||||
"confirmed": "客户已确认",
|
||||
|
||||
@@ -605,6 +605,13 @@
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "调拨票不存在。",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "旧单步字段会截断该绑定的多步配方,请改用 steps_json 提交有序步骤。",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "集成调用记录不存在。",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "绑定步骤配置不合法:steps_json 必填且为非空数组,每项须为对象。"
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "绑定步骤配置不合法:steps_json 必填且为非空数组,每项须为对象。",
|
||||
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "已产生发货通知/Excel,无法修改客户,请先走撤销流程",
|
||||
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "新客户与当前确认客户相同",
|
||||
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "请先完成客户识别确认",
|
||||
"SHIPPING.FORMAL_OT_REQUIRED": "请先创建正式任务",
|
||||
"SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED": "请选择目标客户",
|
||||
"SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED": "订单版本已变化,请刷新后重试",
|
||||
"SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED": "缺少操作人信息,无法修改客户"
|
||||
}
|
||||
}
|
||||
@@ -2243,6 +2243,12 @@
|
||||
"retrying": "識別中…",
|
||||
"retryDone": "已重新識別客戶",
|
||||
"retryFailed": "重新識別客戶失敗",
|
||||
"rebindButton": "修改客戶",
|
||||
"rebindDisabledExcelExists": "已產生發貨通知/Excel,請先走撤銷流程",
|
||||
"rebindConfirmTitle": "確認修改客戶",
|
||||
"rebindConfirmImpact": "將更新訂單客戶並重新凍結訂單快照;已產生的發貨通知/Excel 需重新生成",
|
||||
"rebindSuccessToast": "客戶已更新,可回通知準備重新產生 Excel",
|
||||
"rebindFailedToast": "客戶修改失敗",
|
||||
"uniqueCandidateHint": "已找到唯一標準客戶候選;儲存校驗時系統會自動確認,也可手動確認。",
|
||||
"confirmUniqueCandidate": "確認唯一候選",
|
||||
"confirmed": "客戶已確認",
|
||||
|
||||
@@ -605,6 +605,13 @@
|
||||
"TRANSFER.DOCUMENT_NOT_FOUND": "調撥票不存在。",
|
||||
"INTEGRATION.BINDING_LEGACY_PUT_REJECTED": "舊單步欄位會截斷該繫結的多步配方,請改用 steps_json 提交有序步驟。",
|
||||
"INTEGRATION.CALL_NOT_FOUND": "整合調用記錄不存在。",
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "綁定步驟配置不合法:steps_json 必填且為非空陣列,每項須為物件。"
|
||||
"INTEGRATION.BINDING_STEPS_INVALID": "綁定步驟配置不合法:steps_json 必填且為非空陣列,每項須為物件。",
|
||||
"SHIPPING.CUSTOMER_REBIND_BLOCKED": "已產生發貨通知/Excel,無法修改客戶,請先走撤銷流程",
|
||||
"SHIPPING.CUSTOMER_REBIND_SAME_CUSTOMER": "新客戶與當前確認客戶相同",
|
||||
"SHIPPING.CUSTOMER_RESOLUTION_REQUIRED": "請先完成客戶識別確認",
|
||||
"SHIPPING.FORMAL_OT_REQUIRED": "請先建立正式任務",
|
||||
"SHIPPING.CUSTOMER_REBIND_CUSTOMER_REQUIRED": "請選擇目標客戶",
|
||||
"SHIPPING.CUSTOMER_REBIND_VERSION_REQUIRED": "訂單版本已變化,請重新整理後重試",
|
||||
"SHIPPING.CUSTOMER_REBIND_ACTOR_REQUIRED": "缺少操作人資訊,無法修改客戶"
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user