Merge branch 'hugo-auto-transfer' into dev

This commit is contained in:
hugo committed 2026-10-13 21:18:25 +08:00
commit af2658e244
30 files changed
+1913 -93

No files matched your search

+83 -1
View File
@@ -20,7 +20,7 @@ from flask import Blueprint, Response, current_app, g, request, send_file
from app import db
from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
from app.core.errors import AppError, ConflictError, NotFoundError, UnauthorizedError, ValidationError
from app.core.response import ok
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
@@ -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'