test(shipping): 更新订单复核库存与通知流程测试

This commit is contained in:
hugo committed 2026-09-04 20:53:06 +08:00
1 parent 8ec028e6a3
commit 265a6e179a
168 files changed
+9309 -4502

No files matched your search

+64 -128
View File
@@ -22,7 +22,7 @@ from app import db
from app.core.auth.jwt import get_current_user from app.core.auth.jwt import get_current_user
from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError from app.core.errors import AppError, NotFoundError, UnauthorizedError, ValidationError
from app.core.response import ok from app.core.response import ok
from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice from app.models import ShippingOrderIntake, ShippingOrderExtraction, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.constants import ( from app.services.shipping_notice.constants import (
AUTO_CHAIN_FALLBACK, AUTO_CHAIN_FALLBACK,
@@ -53,7 +53,6 @@ from app.services.shipping_notice.customer_identity_gate import (
confirm_task_customer, confirm_task_customer,
list_customer_options, list_customer_options,
) )
from app.services.shipping_notice.order_customer_matching import confirm_order_customer_match
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__) workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
@@ -145,6 +144,16 @@ def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> No
) )
def _require_formal_notice(task: Any) -> ShippingNotice:
"""正式 Notice 专属接口的实体守卫;OT 在库存门禁前不得进入通知/上传写路径。"""
if not isinstance(task, ShippingNotice):
raise ValidationError(
'Formal shipping notice is required for this operation',
code='SHIPPING.FORMAL_NOTICE_REQUIRED',
)
return task
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
def workspace_shipping_tasks(): def workspace_shipping_tasks():
"""分页列出当前用户可见的发货任务,可按处理状态过滤。""" """分页列出当前用户可见的发货任务,可按处理状态过滤。"""
@@ -214,7 +223,7 @@ def _batch_task_nos(data: dict) -> list[str]:
return normalized return normalized
def _can_dispose_task(user, task: ShippingNotice) -> bool: def _can_dispose_task(user, task) -> bool:
"""管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。""" """管理员可跨用户处置;普通用户仅可处置自己名下或未归属任务。"""
return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id} return str(getattr(user, 'role', '')).lower() == 'admin' or task.user_id in {None, user.id}
@@ -372,96 +381,6 @@ def workspace_confirm_shipping_customer(task_no: str):
return _ok(serialize_task_detail(updated)) return _ok(serialize_task_detail(updated))
@workspace_shipping_notice_bp.route(
'/shipping-order-extractions/<int:extraction_id>/customer-matches/<role>/confirm',
methods=['POST'],
)
def workspace_confirm_order_customer_match(extraction_id: int, role: str):
"""确认当前用户订单解析中的 Bill-to 客户或 Ship-to 送货站点。"""
user = _require_user()
extraction = (
db.session.query(ShippingOrderExtraction)
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderExtraction.intake_id)
.filter(
ShippingOrderExtraction.id == extraction_id,
ShippingOrderIntake.user_id == user.id,
)
.one_or_none()
)
if extraction is None:
raise NotFoundError(
'Order extraction not found',
code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND',
)
data = request.get_json(silent=True) or {}
try:
customer_id = int(data.get('customer_id'))
site_id = int(data['site_id']) if data.get('site_id') is not None else None
except (TypeError, ValueError) as exc:
raise ValidationError(
'Customer id is required',
code='SHIPPING.ORDER_CUSTOMER_REQUIRED',
details={'field': 'customer_id'},
) from exc
result = confirm_order_customer_match(
extraction.id,
role=role,
customer_id=customer_id,
site_id=site_id,
actor_id=user.id,
reason=str(data.get('reason') or ''),
commit=False,
)
# [STEP P1-7] 抽取侧客户确认后,同事务内触发 Case 级协调器(level-triggered reconcile 补偿)。
# 通过 Extraction → Candidate → Review Case 反查未终态 Case;若抽取阶段太早尚无 Case,不报错跳过。
if role == 'bill_to':
from app.models import (
ShippingOrderCandidate,
ShippingOrderReviewCase,
ShippingOrderReviewStream,
)
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress,
)
_TERMINAL = frozenset({
'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending',
})
candidates = list(
ShippingOrderCandidate.query
.filter_by(order_extraction_id=int(extraction.id))
.all()
)
candidate_ids = {int(c.id) for c in candidates}
case = None
if candidate_ids:
case = (
ShippingOrderReviewCase.query
.join(
ShippingOrderReviewStream,
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
)
.filter(ShippingOrderReviewCase.candidate_id.in_(candidate_ids))
.first()
)
if case is None and extraction.run_id:
case = (
ShippingOrderReviewCase.query
.join(
ShippingOrderReviewStream,
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
)
.filter(ShippingOrderReviewCase.run_id == int(extraction.run_id))
.first()
)
if case is not None and str(case.status or '') not in _TERMINAL and not case.confirmed_task_id:
reconcile_single_case_for_auto_progress(
case=case,
trigger='extraction_customer_confirmed',
refresh_validation=True,
)
db.session.commit()
return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
def workspace_create_shipping_task_from_notice(): def workspace_create_shipping_task_from_notice():
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。""" """接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
@@ -492,11 +411,14 @@ def workspace_create_shipping_task_from_notice():
) )
if not intake.accepted: if not intake.accepted:
return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED}) return _ok({'status': 'needs_human', 'task_id': task_id, 'message': '未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。', 'data': {'notice_upload': intake.to_notice_upload_meta()}, 'checkpoint': CP_NOTICE_TEXT_EXTRACTION_FAILED})
task = ShippingNotice.query.filter_by(task_no=task_id).first() from app.models import ShippingOrderTask
from app.models import ShippingOrderIntake
task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
if task: if task:
task.raw_content = intake.text intake_row = db.session.get(ShippingOrderIntake, task.intake_id) if task.intake_id else None
task.source_file_name = intake.filename or task.source_file_name if intake_row is not None:
task.source_file_type = intake.source_file_type or task.source_file_type intake_row.extracted_text = intake.text
intake_row.parse_warnings_json = list(intake.warnings or [])
db.session.commit() db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id) orchestrator_started = start_task_orchestrator(task_id)
@@ -637,6 +559,7 @@ def workspace_update_shipping_notice_fields(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
task = _require_formal_notice(task)
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
fields = data.get('fields') fields = data.get('fields')
if not isinstance(fields, dict) or not fields: if not isinstance(fields, dict) or not fields:
@@ -683,6 +606,7 @@ def workspace_update_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
task = _require_formal_notice(task)
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
try: try:
line_index = int(data.get('line_index')) line_index = int(data.get('line_index'))
@@ -771,6 +695,7 @@ def workspace_add_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
task = _require_formal_notice(task)
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
line = data.get('line') line = data.get('line')
if not isinstance(line, dict) or not line: if not isinstance(line, dict) or not line:
@@ -796,6 +721,7 @@ def workspace_remove_shipping_notice_line(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
task = _require_formal_notice(task)
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
try: try:
line_index = int(data.get('line_index')) line_index = int(data.get('line_index'))
@@ -834,11 +760,15 @@ def workspace_auto_progress_shipping_task(task_no: str):
str(task.task_no), trigger='workspace_auto_progress', operator_id=int(user.id), str(task.task_no), trigger='workspace_auto_progress', operator_id=int(user.id),
) )
# 兼容旧前端:若仍有 export 路径则附带 download_url。 # 导出下载路径只从当前有效 Artifact 读取,Notice 不再保存文件投影。
if isinstance(result, dict) and result.get('status') in {'completed', 'running', 'ok'}: if isinstance(result, dict) and result.get('status') in {'completed', 'running', 'ok'}:
# 重新加载任务以读取 export_file_path(若决策器已推进到导出)。
refreshed = get_task_for_user(task_no, user.id) refreshed = get_task_for_user(task_no, user.id)
export_path = getattr(refreshed, 'export_file_path', None) if refreshed is not None else None artifact = None
if refreshed is not None:
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
artifact = latest_export_artifact(refreshed)
export_path = getattr(artifact, 'file_path', None)
if export_path: if export_path:
result = { result = {
**result, **result,
@@ -862,6 +792,7 @@ def workspace_mark_manual_uploaded(task_no: str):
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
if not task: if not task:
raise NotFoundError('Not found') raise NotFoundError('Not found')
task = _require_formal_notice(task)
_assert_fulfillment_task_ownership(task, user.id) _assert_fulfillment_task_ownership(task, user.id)
from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
@@ -1139,6 +1070,7 @@ def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。""" """下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
user = _require_user() user = _require_user()
task = get_task_for_user(task_no, user.id) task = get_task_for_user(task_no, user.id)
task = _require_formal_notice(task)
err_msg = task_export_error_message(task) err_msg = task_export_error_message(task)
if err_msg: if err_msg:
raise NotFoundError(err_msg) raise NotFoundError(err_msg)
@@ -1900,19 +1832,17 @@ def workspace_patch_shipping_order_review_header_field(case_no: str, field_id: s
return _ok(result) return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/fields/<field_id>', methods=['PATCH']) @workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<draft_line_id>/fields/<field_id>', methods=['PATCH'])
def workspace_patch_shipping_order_review_line_field(case_no: str, line_key: str, field_id: str): def workspace_patch_shipping_order_review_line_field(case_no: str, draft_line_id: str, field_id: str):
"""修改或恢复一个复核订单行字段;行只接受服务端返回的稳定 line_key。""" """修改或恢复一个复核订单行字段;行只接受服务端返回的 draft_line_id。"""
user = _require_user() user = _require_user()
from app.services.shipping_notice.order_review_draft_service import patch_line_field from app.services.shipping_notice.order_review_draft_service import patch_line_field
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_field_changed') payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_field_changed')
result = patch_line_field( result = patch_line_field(
user_id=user.id, case_no=case_no, line_key=line_key, field_id=field_id, value=payload.get('value'), user_id=user.id, case_no=case_no, draft_line_id=draft_line_id, field_id=field_id, value=payload.get('value'),
expected_draft_version=payload.get('expected_draft_version'), expected_draft_version=payload.get('expected_draft_version'),
restore_machine=bool(payload.get('restore_machine')), restore_machine=bool(payload.get('restore_machine')),
override_reason_code=payload.get('override_reason_code'),
override_reason_text=payload.get('override_reason_text'),
) )
db.session.commit() db.session.commit()
return _ok(result) return _ok(result)
@@ -1930,30 +1860,30 @@ def workspace_add_shipping_order_review_line(case_no: str):
return _ok(result) return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>/copy', methods=['POST']) @workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<draft_line_id>/copy', methods=['POST'])
def workspace_copy_shipping_order_review_line(case_no: str, line_key: str): def workspace_copy_shipping_order_review_line(case_no: str, draft_line_id: str):
"""复制一条复核行;后端校验会阻断由复制造成的重复 Reservation。""" """复制一条复核行;后端校验会阻断由复制造成的重复 Reservation。"""
user = _require_user() user = _require_user()
from app.services.shipping_notice.order_review_draft_service import copy_line from app.services.shipping_notice.order_review_draft_service import copy_line
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_copied') payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_copied')
result = copy_line( result = copy_line(
user_id=user.id, case_no=case_no, line_key=line_key, user_id=user.id, case_no=case_no, draft_line_id=draft_line_id,
expected_draft_version=payload.get('expected_draft_version'), expected_draft_version=payload.get('expected_draft_version'),
) )
db.session.commit() db.session.commit()
return _ok(result) return _ok(result)
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<line_key>', methods=['DELETE']) @workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>/draft/lines/<draft_line_id>', methods=['DELETE'])
def workspace_delete_shipping_order_review_line(case_no: str, line_key: str): def workspace_delete_shipping_order_review_line(case_no: str, draft_line_id: str):
"""删除一条复核行;即使删除最后一行,也只更新草稿和阻断校验。""" """删除一条复核行;即使删除最后一行,也只更新草稿和阻断校验。"""
user = _require_user() user = _require_user()
from app.services.shipping_notice.order_review_draft_service import delete_line from app.services.shipping_notice.order_review_draft_service import delete_line
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_deleted') payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='line_deleted')
result = delete_line( result = delete_line(
user_id=user.id, case_no=case_no, line_key=line_key, user_id=user.id, case_no=case_no, draft_line_id=draft_line_id,
expected_draft_version=payload.get('expected_draft_version'), expected_draft_version=payload.get('expected_draft_version'),
) )
db.session.commit() db.session.commit()
@@ -1992,7 +1922,7 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str):
""" """
按最新已发布规则重算库存源路由;不重新识别 PDF,并清除历史人工库存源决定。 按最新已发布规则重算库存源路由;不重新识别 PDF,并清除历史人工库存源决定。
核心逻辑:可选 line_key;携带 expected_draft_version 与幂等键。 核心逻辑:可选 draft_line_id;携带 expected_draft_version 与幂等键。
""" """
user = _require_user() user = _require_user()
from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing from app.services.shipping_notice.order_review_draft_service import reroute_inventory_routing
@@ -2005,7 +1935,7 @@ def workspace_reroute_shipping_order_review_inventory_routing(case_no: str):
case_no=case_no, case_no=case_no,
expected_draft_version=payload.get('expected_draft_version'), expected_draft_version=payload.get('expected_draft_version'),
idempotency_key=payload.get('idempotency_key'), idempotency_key=payload.get('idempotency_key'),
line_key=payload.get('line_key'), draft_line_id=payload.get('draft_line_id'),
) )
db.session.commit() db.session.commit()
return _ok(result) return _ok(result)
@@ -2122,7 +2052,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
""" """
写入行级履约决定。 写入行级履约决定。
Body: line_key, decision_code, reason?, release_field_values?, expected_draft_version? Body: draft_line_id, decision_code, reason?, release_field_values?, expected_draft_version?
""" """
user = _require_user() user = _require_user()
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
@@ -2134,7 +2064,7 @@ def workspace_decide_shipping_order_review_line_fulfillment(case_no: str):
result = decide_review_line_fulfillment( result = decide_review_line_fulfillment(
user_id=user.id, user_id=user.id,
case_no=case_no, case_no=case_no,
line_key=str(data.get('line_key') or ''), draft_line_id=str(data.get('draft_line_id') or ''),
decision_code=str(data.get('decision_code') or ''), decision_code=str(data.get('decision_code') or ''),
reason=str(data.get('reason') or '').strip() or None, reason=str(data.get('reason') or '').strip() or None,
release_field_values=( release_field_values=(
@@ -2156,7 +2086,7 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
""" """
为选中完整明细行创建履约波次。 为选中完整明细行创建履约波次。
Body: line_keys[], expected_draft_version, idempotency_key, reason? Body: snapshot_line_ids[], expected_draft_version, idempotency_key, reason?
只允许正式 OT 走 create_post_ot_fulfillment_wave + 只允许正式 OT 走 create_post_ot_fulfillment_wave +
schedule_post_ot_wave_progress。无正式 OT 的历史波次路径已下线,调用方必须 schedule_post_ot_wave_progress。无正式 OT 的历史波次路径已下线,调用方必须
先完成正式建单,避免同一业务动作存在两套推进事实。 先完成正式建单,避免同一业务动作存在两套推进事实。
@@ -2171,14 +2101,14 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or '')) case = soft_load_review_case_for_audit(user_id=int(user.id), case_no=str(case_no or ''))
formal = resolve_formal_ot(case) if case is not None else {'has_formal_ot': False} formal = resolve_formal_ot(case) if case is not None else {'has_formal_ot': False}
line_keys = list(data.get('line_keys') or []) snapshot_line_ids = list(data.get('snapshot_line_ids') or [])
idem = data.get('idempotency_key') or request.headers.get('Idempotency-Key') idem = data.get('idempotency_key') or request.headers.get('Idempotency-Key')
reason = str(data.get('reason') or '').strip() or None reason = str(data.get('reason') or '').strip() or None
if formal.get('has_formal_ot'): if formal.get('has_formal_ot'):
result = create_post_ot_fulfillment_wave( result = create_post_ot_fulfillment_wave(
case_no=str(case_no), case_no=str(case_no),
line_keys=line_keys, snapshot_line_ids=snapshot_line_ids,
decision_source='user', decision_source='user',
actor_user_id=int(user.id), actor_user_id=int(user.id),
reason=reason, reason=reason,
@@ -2190,7 +2120,7 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
progress = schedule_post_ot_wave_progress( progress = schedule_post_ot_wave_progress(
task_no=str(result.get('task_no') or ''), task_no=str(result.get('task_no') or ''),
wave_no=result.get('wave_no'), wave_no=result.get('wave_no'),
line_keys=list(result.get('accepted_line_keys') or line_keys), snapshot_line_ids=list(result.get('accepted_snapshot_line_ids') or snapshot_line_ids),
review_case_id=int(result.get('review_case_id') or (case.id if case is not None else 0) or 0) or None, review_case_id=int(result.get('review_case_id') or (case.id if case is not None else 0) or 0) or None,
idempotency_row_id=result.get('idempotency_row_id'), idempotency_row_id=result.get('idempotency_row_id'),
request_idempotency_key=str(result.get('idempotency_key') or idem or '') or None, request_idempotency_key=str(result.get('idempotency_key') or idem or '') or None,
@@ -2223,7 +2153,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str):
""" """
关闭行级或 Case 剩余开放行。 关闭行级或 Case 剩余开放行。
Body: reason, line_keys?, expected_draft_version? Body: reason, draft_line_ids?, expected_draft_version?
""" """
user = _require_user() user = _require_user()
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
@@ -2236,7 +2166,7 @@ def workspace_close_shipping_order_review_fulfillment(case_no: str):
user_id=user.id, user_id=user.id,
case_no=case_no, case_no=case_no,
reason=str(data.get('reason') or ''), reason=str(data.get('reason') or ''),
line_keys=list(data.get('line_keys') or []) or None, draft_line_ids=list(data.get('draft_line_ids') or []) or None,
expected_draft_version=data.get('expected_draft_version'), expected_draft_version=data.get('expected_draft_version'),
actor_is_admin=is_admin, actor_is_admin=is_admin,
) )
@@ -2349,9 +2279,7 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
user = _require_user() user = _require_user()
from app.services.shipping_notice.order_review_confirmation_service import ( from app.services.shipping_notice.order_review_confirmation_service import (
confirm_review_case, confirm_review_case,
finalize_sync_auto_progress_after_commit,
resolve_confirm_outcome, resolve_confirm_outcome,
schedule_auto_progress_after_review_confirm,
) )
payload = _review_draft_payload( payload = _review_draft_payload(
@@ -2366,14 +2294,22 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
warning_acknowledgements=payload.get('warning_acknowledgements'), warning_acknowledgements=payload.get('warning_acknowledgements'),
) )
# [STEP] 与建单同事务写入 shipping_notice_run,避免「已建单、推进失败不可恢复」。 # [STEP] 与建单同事务写入 shipping_notice_run,避免「已建单、推进失败不可恢复」。
# 复核确认只产生 OT;正式 ShippingNotice 尚未生成,不能把 OT 编号投递到
# 旧的 notice-run Job。库存源候选的裁决/冻结确认后由正式 inventory_source_routing
# Gate 负责;通过 schedule_auto_progress_after_review_confirm 入队自动推进,
# 使 OT 在不冻结候选的情况下仍能走到库存链路。
from app.services.shipping_notice.order_review_confirmation_service import (
finalize_sync_auto_progress_after_commit,
schedule_auto_progress_after_review_confirm,
)
progress = schedule_auto_progress_after_review_confirm( progress = schedule_auto_progress_after_review_confirm(
task_no=result.get('task_no'), task_no=str(result.get('task_no')),
idempotent_replay=bool(result.get('idempotent_replay')), idempotent_replay=bool(result.get('idempotent_replay')),
created_by_id=int(user.id), created_by_id=int(user.id),
commit=False, commit=False,
) )
# [STEP] BE-4:正式 OT 创建后补触发自动履约(flag 关时 enqueue 内部 no-op) # [STEP] BE-4:正式 OT 创建后补触发自动履约(flag 关时 enqueue 内部 no-op)
if result.get('task_no') and not result.get('idempotent_replay'): if result.get('shipping_notice_no') and not result.get('idempotent_replay'):
from app.services.shipping_notice.line_auto_fulfill_coordinator import ( from app.services.shipping_notice.line_auto_fulfill_coordinator import (
enqueue_post_ot_auto_fulfill_job, enqueue_post_ot_auto_fulfill_job,
) )
@@ -2383,8 +2319,8 @@ def workspace_confirm_shipping_order_review_case(case_no: str):
commit=False, commit=False,
) )
db.session.commit() db.session.commit()
# [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。
progress = finalize_sync_auto_progress_after_commit(progress) progress = finalize_sync_auto_progress_after_commit(progress)
# [STEP] sync 执行失败不得变成 HTTP 500,须返回「确认成功 + 推进态」字段。
result = dict(result) result = dict(result)
result.pop('trigger_auto_progress', None) result.pop('trigger_auto_progress', None)
result['confirm_ok'] = True result['confirm_ok'] = True
@@ -2632,7 +2568,7 @@ def workspace_request_shipping_order_review_llm_suggestion(case_no: str):
user_id=user.id, user_id=user.id,
case_no=case_no, case_no=case_no,
field_id=str(payload.get('field_id') or ''), field_id=str(payload.get('field_id') or ''),
line_key=payload.get('line_key'), draft_line_id=payload.get('draft_line_id'),
evidence_level=payload.get('evidence_level'), evidence_level=payload.get('evidence_level'),
issue_code=payload.get('issue_code'), issue_code=payload.get('issue_code'),
allow_full_pdf=bool(payload.get('allow_full_pdf')), allow_full_pdf=bool(payload.get('allow_full_pdf')),
@@ -16,9 +16,9 @@ from datetime import datetime
from sqlalchemy import and_, or_, update from sqlalchemy import and_, or_, update
from app import db from app import db
from app.core.errors import AppError, NotFoundError from app.core.errors import NotFoundError
from app.jobs.context import JobContext from app.jobs.context import JobContext
from app.jobs.queue import fail_job, finish_job from app.jobs.queue import _is_retryable_exc, fail_job, finish_job
from app.jobs.registry import register_handler from app.jobs.registry import register_handler
from app.jobs.types import JobType from app.jobs.types import JobType
from app.models import FileAsset, Job, ShippingOrderIntake from app.models import FileAsset, Job, ShippingOrderIntake
@@ -120,15 +120,6 @@ def _claim_intake_for_parsing(
return intake, lease return intake, lease
def _is_retryable_exc(exc: BaseException) -> bool:
"""业务 NotFound / AppError.retryable=False 视为不可再排队。"""
if isinstance(exc, NotFoundError):
return False
if isinstance(exc, AppError):
return bool(getattr(exc, 'retryable', False))
return True
@register_handler(JobType.SHIPPING_NOTICE_PARSE) @register_handler(JobType.SHIPPING_NOTICE_PARSE)
def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None: def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
""" """
@@ -264,7 +255,9 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
# 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回) # 租约已失效:旧 Worker 不得触碰 Job(条件 UPDATE 亦会 no-op,此处直接返回)
if str(fail_result.get('reason') or '') == 'stale_parse_lease': if str(fail_result.get('reason') or '') == 'stale_parse_lease':
return return
retryable = False # 失败收口按异常类型分级:业务失败(NotFound/AppError.retryable=False)停排,
# 瞬时基础设施异常才允许重试;不按业务域一刀切。
retryable = _is_retryable_exc(exc)
if job_id is not None: if job_id is not None:
fail_job( fail_job(
job_id, job_id,
@@ -272,3 +265,7 @@ def run_shipping_notice_parse(ctx: JobContext, payload: dict) -> None:
retryable=retryable, retryable=retryable,
owned_attempt=owned_attempt, owned_attempt=owned_attempt,
) )
# 重试类异常交由外层运行时统一收口(fail_job 已 requeue);非重试业务失败已直接
# fail_job 为 failed,不再重抛,避免向上滚动。
if retryable:
raise
@@ -10,7 +10,8 @@ backend/app/jobs/handlers/shipping_stp_auto_create.py
逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单; 逻辑:由 shipping worker 领取;幂等键保证同一 Case/draft 不重复建单;
成功 finish,附加 task_no / idempotent_replay; 成功 finish,附加 task_no / idempotent_replay;
失败统一走 _classify_stp_result: 失败统一走 _classify_stp_result:
- 所有失败 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计) - 业务阻断 → retryable=false(blocked_manual + 注入 next_action + 写阻断审计)
- 临时基础设施异常 → retryable=true(保留普通重试入口)
""" """
from __future__ import annotations from __future__ import annotations
@@ -51,11 +52,10 @@ def _classify_stp_job_result(
【AI 触发时机】:Handler 的三条 fail 路径(业务拒绝 ok=False、AppError 兜底、 【AI 触发时机】:Handler 的三条 fail 路径(业务拒绝 ok=False、AppError 兜底、
非预期 Exception 兜底)统一调用,确保 Job.result_json schema 一致。 非预期 Exception 兜底)统一调用,确保 Job.result_json schema 一致。
核心逻辑(fail-closed): 核心逻辑:
[STEP 1] build_stp_job_blocked_manual_result: [STEP 1] temporary_storage_error 走技术失败契约,允许普通重试;
derive_blocking_next_actions 取第一个动作作 next_action,默认 open_order_review; [STEP 2] 其他错误走 build_stp_job_blocked_manual_result,要求人工裁决;
details 合并至 blocking_reason_details。 [STEP 3] 返回三元组(retryable, normalized_result_dict, next_action)。
[STEP 2] 返回三元组(False, normalized_result_dict, next_action)。
Args: Args:
error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。 error_code: 业务错误码(SHIPPING.* 或顶层 reason_code)。
@@ -71,6 +71,23 @@ def _classify_stp_job_result(
# 当前执行已停止并应在当前 Gate 选择动作,原文仅保留在 Worker 日志。 # 当前执行已停止并应在当前 Gate 选择动作,原文仅保留在 Worker 日志。
if str(error_code or '').strip() == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED': if str(error_code or '').strip() == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED':
message = '自动建单失败,已停止,等待用户选择下一步动作' message = '自动建单失败,已停止,等待用户选择下一步动作'
if category_hint == 'temporary_storage_error':
next_action = 'retry_stp_auto_create'
return True, {
'status': 'failed',
'retryable': True,
'error_code': str(error_code or '').strip(),
'message': str(message or ''),
'next_action': next_action,
'contract_version': 'shipping-recovery-v1-phase1',
'decision_trace': {
'contract_version': 'shipping-recovery-v1-phase1',
'stage': 'stp_classify_error',
'retryable': True,
'matched_rule': 'temporary_storage_error',
'category_hint': category_hint,
},
}, next_action
actions = derive_blocking_next_actions(blocking_reason=error_code) actions = derive_blocking_next_actions(blocking_reason=error_code)
next_action = actions[0] if actions else 'open_order_review' next_action = actions[0] if actions else 'open_order_review'
blocked: dict[str, Any] = build_stp_job_blocked_manual_result( blocked: dict[str, Any] = build_stp_job_blocked_manual_result(
+5 -5
View File
@@ -7,7 +7,7 @@
逻辑:ReviewStream 是文件级复核主线,Case 是该主线的一次不可变复核版本; 逻辑:ReviewStream 是文件级复核主线,Case 是该主线的一次不可变复核版本;
Draft 保存独立人工版本,机器 Candidate 始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task; Draft 保存独立人工版本,机器 Candidate 始终只读,后续确认服务将以 Case/Draft 生成不可变确认版本和 Task;
行级决定支持完整明细先行履约波次,禁止拆分数量; 行级决定支持完整明细先行履约波次,禁止拆分数量;
wave_lines 保证同一 (case, line_key) 最多关联一个 task_id。 wave_lines 保证同一 (case, snapshot_line_id) 最多关联一个 task_id。
""" """
from __future__ import annotations from __future__ import annotations
@@ -109,7 +109,7 @@ class ShippingOrderReviewCase(Base):
ForeignKey('shipping_order_review_drafts.id', use_alter=True, name='fk_shipping_order_review_cases_current_draft'), ForeignKey('shipping_order_review_drafts.id', use_alter=True, name='fk_shipping_order_review_cases_current_draft'),
nullable=True, nullable=True,
) )
confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True) confirmed_task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True)
confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) confirmed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
@@ -140,13 +140,13 @@ class ShippingOrderReviewCase(Base):
'ShippingOrderReviewLineDecision', 'ShippingOrderReviewLineDecision',
back_populates='case', back_populates='case',
cascade='all, delete-orphan', cascade='all, delete-orphan',
order_by='ShippingOrderReviewLineDecision.line_key, ShippingOrderReviewLineDecision.decision_version', order_by='ShippingOrderReviewLineDecision.draft_line_id, ShippingOrderReviewLineDecision.decision_version',
) )
wave_lines: Mapped[list['ShippingOrderReviewWaveLine']] = relationship( wave_lines: Mapped[list['ShippingOrderReviewWaveLine']] = relationship(
'ShippingOrderReviewWaveLine', 'ShippingOrderReviewWaveLine',
back_populates='case', back_populates='case',
cascade='all, delete-orphan', cascade='all, delete-orphan',
order_by='ShippingOrderReviewWaveLine.wave_no, ShippingOrderReviewWaveLine.line_key', order_by='ShippingOrderReviewWaveLine.wave_no, ShippingOrderReviewWaveLine.snapshot_line_id',
) )
@@ -212,7 +212,7 @@ class ShippingOrderReviewConfirmedRevision(Base):
case_id: Mapped[int] = mapped_column( case_id: Mapped[int] = mapped_column(
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False, ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), nullable=False,
) )
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False) task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
draft_version: Mapped[int] = mapped_column(Integer, nullable=False) draft_version: Mapped[int] = mapped_column(Integer, nullable=False)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
@@ -2,8 +2,8 @@
models/shipping_order_review_line_decision.py models/shipping_order_review_line_decision.py
用途:复核 Case 的行级履约决定(版本化、可追溯);含 OT 后系统/人工来源。 用途:复核 Case 的行级履约决定(版本化、可追溯);含 OT 后系统/人工来源。
依赖:ShippingOrderReviewCase、ShippingNotice、users。 依赖:ShippingOrderReviewCase、ShippingOrderTask、users。
逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, line_key, version) 唯一; 逻辑:由 order_review_fulfillment_decision_service 写入;同一 (case, draft_line_id, version) 唯一;
活动决定不可覆盖,重开生成新版本;Task 波次通过 task_id 关联; 活动决定不可覆盖,重开生成新版本;Task 波次通过 task_id 关联;
decision_source 区分 system/user(历史可空)。 decision_source 区分 system/user(历史可空)。
""" """
@@ -26,7 +26,7 @@ class ShippingOrderReviewLineDecision(Base):
__table_args__ = ( __table_args__ = (
UniqueConstraint( UniqueConstraint(
'review_case_id', 'review_case_id',
'line_key', 'draft_line_id',
'decision_version', 'decision_version',
name='uq_shipping_review_line_decisions_case_line_ver', name='uq_shipping_review_line_decisions_case_line_ver',
), ),
@@ -49,7 +49,7 @@ class ShippingOrderReviewLineDecision(Base):
name='ck_shipping_review_line_decisions_source', name='ck_shipping_review_line_decisions_source',
), ),
CheckConstraint('decision_version >= 1', name='ck_shipping_review_line_decisions_version'), CheckConstraint('decision_version >= 1', name='ck_shipping_review_line_decisions_version'),
Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'line_key'), Index('ix_shipping_review_line_decisions_case_line', 'review_case_id', 'draft_line_id'),
Index('ix_shipping_review_line_decisions_case_active', 'review_case_id', 'is_active'), Index('ix_shipping_review_line_decisions_case_active', 'review_case_id', 'is_active'),
Index('ix_shipping_review_line_decisions_task', 'task_id'), Index('ix_shipping_review_line_decisions_task', 'task_id'),
) )
@@ -59,7 +59,7 @@ class ShippingOrderReviewLineDecision(Base):
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False, nullable=False,
) )
line_key: Mapped[str] = mapped_column(String(64), nullable=False) draft_line_id: Mapped[str] = mapped_column(String(64), nullable=False)
line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) line_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
decision_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1') decision_version: Mapped[int] = mapped_column(Integer, nullable=False, default=1, server_default='1')
decision_code: Mapped[str] = mapped_column(String(48), nullable=False) decision_code: Mapped[str] = mapped_column(String(48), nullable=False)
@@ -70,7 +70,7 @@ class ShippingOrderReviewLineDecision(Base):
available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) available_qty: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) reservation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) part_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True) task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True)
wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
# system=自动履约;user=人工异常/显式履约;unknown=历史无法判定。 # system=自动履约;user=人工异常/显式履约;unknown=历史无法判定。
decision_source: Mapped[Optional[str]] = mapped_column(String(16), nullable=True) decision_source: Mapped[Optional[str]] = mapped_column(String(16), nullable=True)
@@ -69,7 +69,7 @@ class ShippingOrderReviewSuggestion(Base):
ForeignKey('shipping_order_processing_runs.id'), nullable=True, ForeignKey('shipping_order_processing_runs.id'), nullable=True,
) )
field_id: Mapped[str] = mapped_column(String(64), nullable=False) field_id: Mapped[str] = mapped_column(String(64), nullable=False)
line_key: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) draft_line_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
scope: Mapped[str] = mapped_column(String(16), nullable=False, default='header', server_default='header') scope: Mapped[str] = mapped_column(String(16), nullable=False, default='header', server_default='header')
evidence_level: Mapped[str] = mapped_column(String(16), nullable=False, default='L1_field') evidence_level: Mapped[str] = mapped_column(String(16), nullable=False, default='L1_field')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending') status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
@@ -2,7 +2,7 @@
models/shipping_order_review_wave_idempotency.py models/shipping_order_review_wave_idempotency.py
用途:post-OT 履约 wave 请求幂等表(idempotency_key → wave 身份),无 wave 主表时提供强约束。 用途:post-OT 履约 wave 请求幂等表(idempotency_key → wave 身份),无 wave 主表时提供强约束。
依赖:shipping_order_review_cases、shipping_notices。 依赖:shipping_order_review_cases、shipping_order_tasks。
逻辑:create_post_ot_fulfillment_wave 写入/回放;同 key 参数不一致 → 409; 逻辑:create_post_ot_fulfillment_wave 写入/回放;同 key 参数不一致 → 409;
progress_* 记录本 wave Excel/RPA 推进状态(失败不回滚已提交 wave)。 progress_* 记录本 wave Excel/RPA 推进状态(失败不回滚已提交 wave)。
""" """
@@ -39,15 +39,15 @@ class ShippingOrderReviewWaveIdempotency(Base):
nullable=False, nullable=False,
) )
task_id: Mapped[int] = mapped_column( task_id: Mapped[int] = mapped_column(
ForeignKey('shipping_notices.id', ondelete='CASCADE'), ForeignKey('shipping_order_tasks.id', ondelete='CASCADE'),
nullable=False, nullable=False,
) )
task_no: Mapped[str] = mapped_column(String(64), nullable=False) task_no: Mapped[str] = mapped_column(String(64), nullable=False)
wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) wave_no: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
decision_source: Mapped[str] = mapped_column(String(16), nullable=False) decision_source: Mapped[str] = mapped_column(String(16), nullable=False)
# 稳定排序后的 line_key JSON 数组字符串指纹(冲突比对)。 # 稳定排序后的冻结订单行 ID 数组指纹(冲突比对)。
line_keys_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list) snapshot_line_ids_json: Mapped[list[Any]] = mapped_column(JSON, nullable=False, default=list)
line_keys_hash: Mapped[str] = mapped_column(String(64), nullable=False) snapshot_line_ids_hash: Mapped[str] = mapped_column(String(64), nullable=False)
# 行集合共享快照 ID;多快照时为空,靠 fingerprint 比对。 # 行集合共享快照 ID;多快照时为空,靠 fingerprint 比对。
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
inventory_snapshot_fingerprint: Mapped[str] = mapped_column(String(256), nullable=False, default='') inventory_snapshot_fingerprint: Mapped[str] = mapped_column(String(256), nullable=False, default='')
@@ -2,9 +2,9 @@
models/shipping_order_review_wave_line.py models/shipping_order_review_wave_line.py
用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一张 Notice。 用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一张 Notice。
依赖:ShippingOrderReviewCase、ShippingNotice、ShippingOrderReviewConfirmedRevision。 依赖:ShippingOrderReviewCase、ShippingOrderTask、ShippingOrderReviewConfirmedRevision。
逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入; 逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入;
(review_case_id, line_key) 数据库唯一约束防并发重复入波次。 (review_case_id, snapshot_line_id) 数据库唯一约束防并发重复入波次。
""" """
from __future__ import annotations from __future__ import annotations
@@ -25,7 +25,7 @@ class ShippingOrderReviewWaveLine(Base):
__table_args__ = ( __table_args__ = (
UniqueConstraint( UniqueConstraint(
'review_case_id', 'review_case_id',
'line_key', 'snapshot_line_id',
name='uq_shipping_review_wave_lines_case_line', name='uq_shipping_review_wave_lines_case_line',
), ),
Index('ix_shipping_review_wave_lines_task', 'task_id'), Index('ix_shipping_review_wave_lines_task', 'task_id'),
@@ -37,8 +37,11 @@ class ShippingOrderReviewWaveLine(Base):
ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'), ForeignKey('shipping_order_review_cases.id', ondelete='CASCADE'),
nullable=False, nullable=False,
) )
line_key: Mapped[str] = mapped_column(String(64), nullable=False) snapshot_line_id: Mapped[int] = mapped_column(
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False) ForeignKey('shipping_order_snapshot_lines.id', ondelete='CASCADE'),
nullable=False,
)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=False)
wave_no: Mapped[int] = mapped_column(Integer, nullable=False) wave_no: Mapped[int] = mapped_column(Integer, nullable=False)
confirmed_revision_id: Mapped[Optional[int]] = mapped_column( confirmed_revision_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_review_confirmed_revisions.id', ondelete='SET NULL'), ForeignKey('shipping_order_review_confirmed_revisions.id', ondelete='SET NULL'),
+9 -6
View File
@@ -4,7 +4,7 @@ backend/app/models/shipping_order_schema.py
用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。 用途:定义货代字段资产、Schema 族/不可变版本、配置审计及动态订单解析结果。
依赖:models.base.Base、shipping_notices、shipping_order_intakes、users。 依赖:models.base.Base、shipping_notices、shipping_order_intakes、users。
逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json; 逻辑:字段资产全局存活(标准只读、扩展可弃用);Schema 族版本仅采用资产并冻结 definition_json;
definition_json 含 fields / auto_creation_policy / derivation_rules(及 checksum); definition_json 含 fields / auto_creation_policy;
写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。 写操作追加审计;解析链锁定发布版本。表名保留历史命名以降低迁移耦合。
""" """
@@ -138,8 +138,7 @@ class ShippingOrderSchemaVersion(Base):
definition_json 契约要点: definition_json 契约要点:
- fields[]:字段采用与识别规则 - fields[]:字段采用与识别规则
- auto_creation_policy:自动建单策略 - auto_creation_policy:自动建单策略
- derivation_rules[]:同行明细字段派生(首期 copy_if_empty → line_no) - line_no:运行时按 Extraction 内明细顺序生成,不属于 Schema 配置或派生规则。
- derivation_rules_checksum:派生规则稳定校验和
""" """
__tablename__ = 'shipping_order_schema_versions' __tablename__ = 'shipping_order_schema_versions'
@@ -232,7 +231,7 @@ class ShippingOrderExtraction(Base):
run_id: Mapped[Optional[int]] = mapped_column( run_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True, ForeignKey('shipping_order_processing_runs.id'), nullable=True, index=True,
) )
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notices.id'), nullable=True) task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_tasks.id'), nullable=True)
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True) intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_intakes.id'), nullable=True)
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False) schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False) input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
@@ -264,12 +263,16 @@ class ShippingOrderLine(Base):
"""动态订单解析中的行身份;业务值全部位于 FieldValue。""" """动态订单解析中的行身份;业务值全部位于 FieldValue。"""
__tablename__ = 'shipping_order_lines' __tablename__ = 'shipping_order_lines'
__table_args__ = (UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'),) __table_args__ = (
UniqueConstraint('extraction_id', 'position', name='uq_shipping_order_lines_position'),
UniqueConstraint('extraction_id', 'line_no', name='uq_shipping_order_lines_line_no'),
)
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False) extraction_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extractions.id', ondelete='CASCADE'), nullable=False)
position: Mapped[int] = mapped_column(Integer, nullable=False) position: Mapped[int] = mapped_column(Integer, nullable=False)
line_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) line_no: Mapped[int] = mapped_column(Integer, nullable=False)
draft_line_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='lines') extraction: Mapped['ShippingOrderExtraction'] = relationship(back_populates='lines')
@@ -27,7 +27,6 @@ from app.models import (
ShippingOrderCandidate, ShippingOrderCandidate,
ShippingOrderCandidateQualification, ShippingOrderCandidateQualification,
ShippingOrderExtraction, ShippingOrderExtraction,
ShippingOrderCustomerMatch,
) )
from app.services.shipping_notice.candidate_qualification_contract import ( from app.services.shipping_notice.candidate_qualification_contract import (
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION, CANDIDATE_QUALIFICATION_EVALUATOR_VERSION,
@@ -71,7 +70,6 @@ _CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85'
# 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。 # 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。
# 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。 # 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。
_NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'}) _NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'})
_OPTIONAL_INTERNAL_FIELD_CODES = frozenset({'line_no'})
_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'}) _EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'})
@@ -79,9 +77,8 @@ def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) ->
"""按冻结字段配置判断证据缺失是否只是可选字段诊断。 """按冻结字段配置判断证据缺失是否只是可选字段诊断。
核心逻辑:优先读取 Candidate 关联 Extraction 的冻结 Schema;只有 核心逻辑:优先读取 Candidate 关联 Extraction 的冻结 Schema;只有
``required`` 或 ``auto_create_key_field`` 才能阻断。历史 Candidate 无法 ``required`` 或 ``auto_create_key_field`` 才能阻断。无法追溯 Schema
追溯 Schema 时,仅兼容已明确属于内部可派生字段的 ``line_no``,其余未知 时继续 fail-closed;系统项次由写路径生成,不构成证据缺失例外。
字段继续 fail-closed。
""" """
reason = str(item.get('reason') or item.get('code') or '').strip() reason = str(item.get('reason') or item.get('code') or '').strip()
if reason not in _EVIDENCE_GAP_REASONS: if reason not in _EVIDENCE_GAP_REASONS:
@@ -111,7 +108,7 @@ def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) ->
config = None config = None
if config is not None: if config is not None:
return not bool(config.get('required')) and not bool(config.get('auto_create_key_field')) return not bool(config.get('required')) and not bool(config.get('auto_create_key_field'))
return field_code in _OPTIONAL_INTERNAL_FIELD_CODES return False
def blocking_candidate_conflicts(candidate: Any) -> list[Any]: def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
@@ -173,8 +170,7 @@ def resolve_candidate_customer_resolved(
""" """
判定 Candidate/Extraction 的 Bill-to 客户是否已确认。 判定 Candidate/Extraction 的 Bill-to 客户是否已确认。
核心逻辑:优先读 ShippingOrderCustomerMatch(bill_to)=confirmed; 核心逻辑:只读 Candidate 的正式客户识别结果;不读取 bill_to 或解析摘要兜底。
其次读 Candidate.structured_result_json.customer.resolution_status。
Args: Args:
candidate: 可选 Candidate。 candidate: 可选 Candidate。
@@ -183,56 +179,35 @@ def resolve_candidate_customer_resolved(
Returns: Returns:
True 表示客户已确认,可用于建单资格评估。 True 表示客户已确认,可用于建单资格评估。
""" """
ext_id = extraction_id from app.services.shipping_notice.customer_resolution_service import resolution_for_extraction, resolution_for_task
if ext_id is None and candidate is not None:
raw = getattr(candidate, 'order_extraction_id', None)
if raw is not None:
try:
ext_id = int(raw)
except (TypeError, ValueError):
ext_id = None
if ext_id is not None:
row = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(ext_id),
role='bill_to',
status='confirmed',
).first()
if row is not None and row.customer_id is not None:
return True
if candidate is None: resolution = resolution_for_task(candidate) if candidate is not None else resolution_for_extraction(extraction_id)
if resolution is not None:
return bool(resolution.status == 'confirmed' and resolution.confirmed_customer_id is not None)
# review_case 人工确认新建的 Candidate 只在 structured_result_json['customer'] 写入确认事实
# (review_case 权威确认,见 order_review_confirmation_service._create_review_candidate),并不落 resolution 表;
# 在建单资格判断时兜底认可,避免"已确认客户却无法建单"。
structured = getattr(candidate, 'structured_result_json', None) if candidate is not None else None
if isinstance(structured, dict):
customer = structured.get('customer') if isinstance(structured.get('customer'), dict) else {}
return str(customer.get('resolution_status') or '').strip().lower() == 'confirmed'
return False return False
ok, _reason = _customer_ok(candidate, customer_resolved=None)
return bool(ok)
def resolve_confirmed_bill_to_customer_id( def resolve_confirmed_customer_id(
*, *,
candidate: Any | None = None, candidate: Any | None = None,
extraction_id: int | None = None, extraction_id: int | None = None,
) -> int | None: ) -> int | None:
""" """
返回已确认 Bill-to 标准客户主键;未确认时为 None。 返回正式识别结果中已确认的标准客户主键;未确认时为 None。
核心逻辑:与 resolve_candidate_customer_resolved 同源,额外取出 customer_id 供建单绑定。
""" """
ext_id = extraction_id from app.services.shipping_notice.customer_resolution_service import resolution_for_extraction, resolution_for_task
if ext_id is None and candidate is not None:
raw = getattr(candidate, 'order_extraction_id', None) resolution = resolution_for_task(candidate) if candidate is not None else resolution_for_extraction(extraction_id)
if raw is not None: return int(resolution.confirmed_customer_id) if (
try: resolution is not None and resolution.status == 'confirmed' and resolution.confirmed_customer_id is not None
ext_id = int(raw) ) else None
except (TypeError, ValueError):
ext_id = None
if ext_id is not None:
row = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(ext_id),
role='bill_to',
status='confirmed',
).first()
if row is not None and row.customer_id is not None:
return int(row.customer_id)
return None
def assert_customer_confirmed_before_task_create( def assert_customer_confirmed_before_task_create(
@@ -13,7 +13,7 @@ from typing import Any
from flask import current_app from flask import current_app
from app.core.errors import ForbiddenError from app.core.errors import ForbiddenError
from app.models import ChatSession, ShippingNotice from app.models import ChatSession, ShippingOrderTask
READ_SCOPES = frozenset({'get_shipping_status'}) READ_SCOPES = frozenset({'get_shipping_status'})
@@ -50,7 +50,7 @@ def require_chat_capability(*, token: Any, scope: str, task_no: str | None = Non
if session is None: if session is None:
raise ForbiddenError('Chat capability session is invalid', code='SHIPPING.CHAT_CAPABILITY_DENIED') raise ForbiddenError('Chat capability session is invalid', code='SHIPPING.CHAT_CAPABILITY_DENIED')
if task_no: if task_no:
task = ShippingNotice.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none() task = ShippingOrderTask.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none()
if task is None or str(body.get('task') or '').upper() != task.task_no: if task is None or str(body.get('task') or '').upper() != task.task_no:
raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED') raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED')
return body return body
@@ -1,19 +1,16 @@
""" """
services/shipping_notice/customer_auto_resolution.py services/shipping_notice/customer_auto_resolution.py
用途:基于管理员审核的强证据受控自动确认客户,并支持历史回填与编号后客户纠错。 用途:基于管理员审核的强证据受控自动确认 OT 客户。
依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、business_numbering_service、Flask 配置。 依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、Flask 配置。
逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;管理员纠错时保留原号作废并创建替代业务单。 逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;不创建 Notice 或分配业务编号。
""" """
from __future__ import annotations from __future__ import annotations
import hashlib
from datetime import datetime
from typing import Any from typing import Any
from app import db from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ( from app.models import (
ShippingCustomer, ShippingCustomer,
ShippingCustomerShadowResolution, ShippingCustomerShadowResolution,
@@ -24,24 +21,25 @@ from app.models import (
ShippingOrderFieldDecision, ShippingOrderFieldDecision,
ShippingOrderFieldValue, ShippingOrderFieldValue,
ShippingOrderSchemaVersion, ShippingOrderSchemaVersion,
ShippingNotice, ShippingOrderTask,
ShippingTaskEvent, ShippingTaskEvent,
) )
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer from app.services.shipping_notice.customer_identity_gate import (
confirm_task_customer,
customer_confirmation_facts,
)
from app.services.shipping_notice.customer_normalization import ( from app.services.shipping_notice.customer_normalization import (
is_public_email_domain, is_public_email_domain,
normalize_customer_name, normalize_customer_name,
normalize_domain, normalize_domain,
normalize_email, normalize_email,
) )
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, generate_task_no from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, task_event_task_id
from app.services.shipping_notice.business_numbering_service import assign_notice_business_number
AUTO_RESOLUTION_VERSION = "customer-auto-v2" AUTO_RESOLUTION_VERSION = "customer-auto-v2"
CUSTOMER_AUDIT_EVENT_TYPES = ( CUSTOMER_AUDIT_EVENT_TYPES = (
"customer_auto_resolution_evaluated", "customer_auto_resolution_evaluated",
"customer_auto_confirmed", "customer_auto_confirmed",
"customer_correction_applied",
) )
@@ -92,6 +90,52 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]:
} }
def _ruleset_definitions_semantically_compatible(
snapshot: dict[str, Any], schema_version: ShippingOrderSchemaVersion,
) -> bool:
"""
校验规则集冻结定义在解析所用 Schema 版本中语义契约仍成立(允许 Schema 常规重发布造成的版本错位)。
语义键集合:field_code / scope('header') / value_type / normalizer_key / available_for_customer_identity。
允许 display_name、aliases、extraction_instruction、evidence_policy 等非语义字段变化;
任一语义键不一致或字段被停用则 fail-closed,防止按过期配置标准化产生误绑客户。
Args:
snapshot: 影子 rule_set 快照(含 definitions)。
schema_version: 解析实际使用的 Schema 版本。
Returns:
True 表示所有带 field_code 的定义在新 Schema 中语义兼容。
"""
fields = ((schema_version.definition_json or {}).get('fields') or []) if schema_version else []
fields_by_code = {
str(item.get('field_code') or ''): item
for item in fields if isinstance(item, dict) and str(item.get('field_code') or '')
}
definitions = snapshot.get('definitions') if isinstance(snapshot, dict) else []
for raw in definitions if isinstance(definitions, list) else []:
if not isinstance(raw, dict):
continue
config = raw.get('field_config') if isinstance(raw.get('field_config'), dict) else {}
field_code = str(config.get('field_code') or '').strip()
if not field_code:
# 旧快照未保存 field_code:无法做语义校验,交由 UUID 直配路径(继续,不判定失败)。
continue
actual = fields_by_code.get(field_code)
if actual is None or not actual.get('enabled', True):
return False
if str(actual.get('scope') or '') != 'header' or str(config.get('scope') or '') != 'header':
return False
if str(actual.get('value_type') or '') != str(config.get('value_type') or ''):
return False
if not actual.get('available_for_customer_identity'):
return False
frozen_normalizer = str(config.get('normalizer_key') or '').strip()
if frozen_normalizer and frozen_normalizer != str(actual.get('normalizer_key') or '').strip():
return False
return True
def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] | None: def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] | None:
"""校验规则集及其订单 Schema/Extraction 锚点;任一链路缺失都安全降级。""" """校验规则集及其订单 Schema/Extraction 锚点;任一链路缺失都安全降级。"""
context = shadow.resolution_context_json if isinstance(shadow.resolution_context_json, dict) else {} context = shadow.resolution_context_json if isinstance(shadow.resolution_context_json, dict) else {}
@@ -118,16 +162,12 @@ def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] |
or snapshot.get('order_schema') != frozen_definition.get('order_schema') or snapshot.get('order_schema') != frozen_definition.get('order_schema')
): ):
return None return None
schema = snapshot.get('order_schema') if isinstance(snapshot.get('order_schema'), dict) else None # Schema 锚点放宽:规则集冻结的版本 id 可与解析实际使用的版本错位(Schema 常规重发布),
if not schema or schema.get('id') != shadow.order_schema_version_id: # 但解析所用 Schema 版本必须真实存在(published/retired),且规则集定义在新 Schema 中语义兼容。
return None
schema_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id) schema_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
if ( if schema_version is None or schema_version.status not in {'published', 'retired'}:
schema_version is None return None
or schema_version.status not in {'published', 'retired'} if not _ruleset_definitions_semantically_compatible(snapshot, schema_version):
or schema_version.version != schema.get('version')
or schema_version.checksum != schema.get('checksum')
):
return None return None
extraction_id = context.get('order_extraction_id') extraction_id = context.get('order_extraction_id')
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id)) if str(extraction_id or '').isdigit() else None extraction = db.session.get(ShippingOrderExtraction, int(extraction_id)) if str(extraction_id or '').isdigit() else None
@@ -286,7 +326,7 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
return result return result
def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]: def resolve_auto_customer_from_shadow(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
""" """
使用任务来源 Candidate 的影子证据执行受控自动裁决。 使用任务来源 Candidate 的影子证据执行受控自动裁决。
@@ -307,13 +347,14 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
'is_eligible': False, 'is_eligible': False,
}, },
} }
if task.source_candidate_id is None: candidate_id = getattr(task, 'candidate_id', None)
if candidate_id is None:
return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []} return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
shadow = db.session.query(ShippingCustomerShadowResolution).filter_by( shadow = db.session.query(ShippingCustomerShadowResolution).filter_by(
candidate_id=int(task.source_candidate_id), candidate_id=int(candidate_id),
).first() ).first()
if shadow is None: if shadow is None:
candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id)) candidate = db.session.get(ShippingOrderCandidate, int(candidate_id))
if candidate is not None: if candidate is not None:
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
@@ -333,17 +374,20 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
return {**decision, 'quality_gate': quality_gate} return {**decision, 'quality_gate': quality_gate}
def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]: def try_auto_confirm_task_customer(task: ShippingOrderTask) -> dict[str, Any]:
""" """
尝试自动确认并生成业务编号;未达门槛时保持 customer_review。 尝试自动确认 OT 客户;未达门槛时保持 customer_review。
核心逻辑:先写自动裁决审计,再复用人工确认的锁与编号事务;成功后将确认方法改为 auto_rule。 核心逻辑:先写自动裁决审计,再复用人工确认事务;成功后将确认方法改为 auto_rule。
""" """
if task.customer_resolution_status == "confirmed": facts = customer_confirmation_facts(task)
return {"status": "already_confirmed", "customer_id": task.customer_id} if facts['status'] == 'confirmed':
return {"status": "already_confirmed", "customer_id": facts['customer_id']}
decision = resolve_auto_customer_from_shadow(task) decision = resolve_auto_customer_from_shadow(task)
event_task_id = task_event_task_id(task)
if event_task_id is not None:
db.session.add(ShippingTaskEvent( db.session.add(ShippingTaskEvent(
task_id=task.id, task_id=event_task_id,
event_type="customer_auto_resolution_evaluated", event_type="customer_auto_resolution_evaluated",
detail_json=decision, detail_json=decision,
)) ))
@@ -358,165 +402,32 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
resolution_method="auto_rule", resolution_method="auto_rule",
commit=False, commit=False,
) )
updated_event_task_id = task_event_task_id(updated)
if updated_event_task_id is not None:
db.session.add(ShippingTaskEvent( db.session.add(ShippingTaskEvent(
task_id=updated.id, task_id=updated_event_task_id,
event_type="customer_auto_confirmed", event_type="customer_auto_confirmed",
detail_json={ detail_json={
**decision, **decision,
"business_no": updated.business_no, "business_no": getattr(updated, 'business_no', None),
}, },
)) ))
db.session.flush() db.session.flush()
return {**decision, "status": "auto_confirmed", "business_no": updated.business_no} # OT 阶段只确认客户;业务编号属于正式 Notice 的 Excel 生成事务。
return {**decision, "status": "auto_confirmed", "business_no": None}
def correct_numbered_task_customer(
task: ShippingNotice,
*,
customer_id: int,
reason: str,
actor_id: int | None,
) -> dict[str, Any]:
"""
更正已编号 Notice 的标准客户,同时保留原号作废与替代关系。
核心逻辑:锁定原 Notice 并校验未上传 → 创建替代 Notice 和新号 → 作废原 Notice →
清理新 Notice 的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。
Args:
task: 原业务号或技术号定位到的当前任务版本。
customer_id: 管理员确认的正确启用客户 ID。
reason: 必填纠错原因,写入审计事件。
actor_id: 管理员审计 ID。
Returns:
原号、新号、替代业务单和受影响任务信息。
Raises:
ValidationError: 缺少原因、客户无效或客户未变化。
ConflictError: 业务单未编号、已上传或已被替代。
"""
correction_reason = str(reason or "").strip()
if not correction_reason:
raise ValidationError(
"Customer correction reason is required",
code="SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED",
)
original = (
db.session.query(ShippingNotice)
.filter(ShippingNotice.id == int(task.id))
.with_for_update()
.one_or_none()
)
if original is None or not original.business_no:
raise ConflictError(
"Numbered shipping notice is required for customer correction",
code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED",
)
existing_replacement = db.session.query(ShippingNotice.id).filter_by(
supersedes_task_id=original.id,
).first()
if existing_replacement is not None or str(original.lifecycle_status or '') == 'voided':
raise ConflictError(
"Shipping notice has already been replaced",
code="SHIPPING.CUSTOMER_CORRECTION_ALREADY_REPLACED",
)
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError("Customer not found", code="SHIPPING.CUSTOMER_NOT_FOUND")
if customer.status == "merged":
raise ConflictError("Merged customer cannot be used", code="SHIPPING.CUSTOMER_MERGED_LOCKED")
if customer.status != "active":
raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE")
if original.customer_id == customer.id:
raise ValidationError(
"Corrected customer must differ from the current customer",
code="SHIPPING.CUSTOMER_CORRECTION_UNCHANGED",
)
if str(getattr(original, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}:
raise ConflictError(
"Uploaded shipping notices require an external cancellation workflow before correction",
code="SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED",
)
old_business_no = str(original.business_no)
now = datetime.utcnow()
customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest()
replacement = ShippingNotice(
task_no=generate_task_no(),
user_id=original.user_id,
conversation_id=original.conversation_id,
source_type=original.source_type,
source_file_name=original.source_file_name,
source_file_type=original.source_file_type,
source_content_hash=original.source_content_hash,
source_asset_id=original.source_asset_id,
source_intake_id=original.source_intake_id,
source_candidate_id=original.source_candidate_id,
order_task_id=original.order_task_id,
business_fingerprint=original.business_fingerprint,
fingerprint_version=original.fingerprint_version,
content_fingerprint=original.content_fingerprint,
content_fingerprint_version=original.content_fingerprint_version,
document_version=int(original.document_version or 1) + 1,
supersedes_task_id=original.id,
raw_content=original.raw_content,
customer_id=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
customer_resolution_status="confirmed",
customer_resolution_method="admin_correction",
customer_identity_fingerprint=customer_fingerprint,
customer_confirmed_by=actor_id,
customer_confirmed_at=now,
)
db.session.add(replacement)
db.session.flush()
new_business_no = assign_notice_business_number(replacement)
original.lifecycle_status = 'voided'
original.voided_at = now
original.voided_by_id = actor_id
original.void_reason = f'customer_correction:{correction_reason}'
correction_detail = {
"old_notice_id": original.id,
"new_notice_id": replacement.id,
"old_business_no": old_business_no,
"new_business_no": new_business_no,
"old_customer_id": original.customer_id,
"new_customer_id": customer.id,
"reason": correction_reason,
"actor_id": actor_id,
}
db.session.add(ShippingTaskEvent(task_id=original.id, event_type="customer_correction_applied", detail_json=correction_detail))
db.session.add(ShippingTaskEvent(task_id=replacement.id, event_type="customer_correction_applied", detail_json=correction_detail))
# 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。
db.session.commit()
return {
"task_no": replacement.task_no,
"old_notice_id": original.id,
"new_notice_id": replacement.id,
"old_business_no": old_business_no,
"new_business_no": new_business_no,
"customer_id": customer.id,
"affected_task_count": 1,
}
def get_auto_resolution_metrics() -> dict[str, Any]: def get_auto_resolution_metrics() -> dict[str, Any]:
"""汇总自动裁决和纠错事件,供管理员监控、查询与降级判断。""" """汇总自动裁决事件,供管理员监控、查询与降级判断。"""
evaluated = db.session.query(ShippingTaskEvent.task_id).filter_by( evaluated = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_auto_resolution_evaluated", event_type="customer_auto_resolution_evaluated",
).distinct().count() ).distinct().count()
confirmed = db.session.query(ShippingTaskEvent.task_id).filter_by( confirmed = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_auto_confirmed", event_type="customer_auto_confirmed",
).distinct().count() ).distinct().count()
corrected = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_correction_applied",
).distinct().count()
recent_events = ( recent_events = (
db.session.query(ShippingTaskEvent, ShippingNotice.task_no) db.session.query(ShippingTaskEvent, ShippingOrderTask.task_no)
.join(ShippingNotice, ShippingNotice.id == ShippingTaskEvent.task_id) .join(ShippingOrderTask, ShippingOrderTask.id == ShippingTaskEvent.task_id)
.filter(ShippingTaskEvent.event_type.in_(CUSTOMER_AUDIT_EVENT_TYPES)) .filter(ShippingTaskEvent.event_type.in_(CUSTOMER_AUDIT_EVENT_TYPES))
.order_by(ShippingTaskEvent.id.desc()) .order_by(ShippingTaskEvent.id.desc())
.limit(100) .limit(100)
@@ -528,7 +439,6 @@ def get_auto_resolution_metrics() -> dict[str, Any]:
'quality_gate': _auto_confirmation_quality_gate(), 'quality_gate': _auto_confirmation_quality_gate(),
"evaluated_count": evaluated, "evaluated_count": evaluated,
"auto_confirmed_count": confirmed, "auto_confirmed_count": confirmed,
"corrected_task_count": corrected,
"auto_confirmation_rate": (confirmed / evaluated) if evaluated else None, "auto_confirmation_rate": (confirmed / evaluated) if evaluated else None,
"recent_events": [ "recent_events": [
{ {
@@ -8,7 +8,6 @@ backend/app/services/shipping_notice/customer_identity_gate.py
from __future__ import annotations from __future__ import annotations
import hashlib
from datetime import datetime from datetime import datetime
from typing import Any from typing import Any
@@ -16,18 +15,44 @@ from sqlalchemy import or_
from app import db from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent from app.models import (
ShippingCustomer,
ShippingNotice,
ShippingOrderTask,
)
from app.services.shipping_notice.customer_normalization import clean_text from app.services.shipping_notice.customer_normalization import clean_text
from app.services.shipping_notice.customer_resolution_service import (
confirm_customer_resolution,
customer_resolution_facts,
)
CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
def customer_identity_is_confirmed(task: ShippingNotice) -> bool: def customer_confirmation_facts(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
"""判断 Notice 自身是否已通过标准客户确认。""" """读取唯一客户识别结果;bill_to 等订单字段仅可出现在识别证据中。"""
if task.customer_id is None: facts = customer_resolution_facts(task)
resolution = facts['resolution']
customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None
return {
'customer_id': facts['customer_id'],
'status': facts['status'],
'resolution_method': getattr(resolution, 'confirmation_method', None),
'identity_fingerprint': getattr(resolution, 'identity_rule_set_checksum', None),
'confirmed_by_id': getattr(resolution, 'confirmed_by_id', None),
'confirmed_at': getattr(resolution, 'confirmed_at', None),
'customer_name_snapshot': getattr(customer, 'standard_name', None),
'customer_short_code_snapshot': getattr(customer, 'short_code', None),
}
def customer_identity_is_confirmed(task: ShippingNotice | ShippingOrderTask) -> bool:
"""判断 OT 或正式 Notice 是否已通过标准客户确认。"""
facts = customer_confirmation_facts(task)
if facts['customer_id'] is None or facts['status'] != 'confirmed':
return False return False
customer = db.session.get(ShippingCustomer, int(task.customer_id)) customer = db.session.get(ShippingCustomer, int(facts['customer_id']))
return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed') return bool(customer and customer.status == 'active')
def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'continue') -> None: def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'continue') -> None:
@@ -42,6 +67,9 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con
""" """
if customer_identity_is_confirmed(task): if customer_identity_is_confirmed(task):
return return
facts = customer_confirmation_facts(task)
customer_id = facts['customer_id']
status = facts['status'] or 'pending'
raise AppError( raise AppError(
code=CUSTOMER_GATE_ERROR_CODE, code=CUSTOMER_GATE_ERROR_CODE,
message='标准客户尚未确认,无法继续后续流程', message='标准客户尚未确认,无法继续后续流程',
@@ -49,8 +77,8 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con
details={ details={
'operation': operation, 'operation': operation,
'task_no': task.task_no, 'task_no': task.task_no,
'customer_resolution_status': task.customer_resolution_status or 'pending', 'customer_resolution_status': status,
'customer_id': task.customer_id, 'customer_id': customer_id,
}, },
) )
@@ -71,15 +99,15 @@ def list_customer_options(*, query: str = '', limit: int = 100) -> list[dict[str
def confirm_task_customer( def confirm_task_customer(
task: ShippingNotice, task: ShippingNotice | ShippingOrderTask,
*, *,
customer_id: int, customer_id: int,
actor_id: int | None, actor_id: int | None,
resolution_method: str = 'manual', resolution_method: str = 'manual',
commit: bool = True, commit: bool = True,
) -> ShippingNotice: ) -> ShippingNotice | ShippingOrderTask:
""" """
人工确认 Notice 所属标准客户;业务编号留待首次 Excel 生成时分配。 人工确认 OT/Notice 所属标准客户;业务编号仅由正式 Notice 的 Excel 阶段分配。
核心逻辑:锁定客户归属 → 校验启用客户 → 固化 Notice 客户快照。 核心逻辑:锁定客户归属 → 校验启用客户 → 固化 Notice 客户快照。
客户确认与客户快照同事务提交;业务编号由 Excel 生成事务独占写入。 客户确认与客户快照同事务提交;业务编号由 Excel 生成事务独占写入。
@@ -91,12 +119,11 @@ def confirm_task_customer(
resolution_method: manual/auto_rule 等审计方法。 resolution_method: manual/auto_rule 等审计方法。
commit: 是否提交事务;批次编排传 False 由外层统一提交。 commit: 是否提交事务;批次编排传 False 由外层统一提交。
""" """
model = ShippingOrderTask if isinstance(task, ShippingOrderTask) else ShippingNotice
task = ( task = (
db.session.query(ShippingNotice) db.session.query(model)
.filter(ShippingNotice.id == int(task.id)) .filter(model.id == int(task.id))
# ShippingNotice.customer 使用 joined eager load,会形成 LEFT OUTER JOIN; .with_for_update(of=model)
# PostgreSQL 不允许锁定该连接的可空侧,故只锁当前 Notice 行。
.with_for_update(of=ShippingNotice)
.one() .one()
) )
customer = db.session.get(ShippingCustomer, int(customer_id)) customer = db.session.get(ShippingCustomer, int(customer_id))
@@ -106,38 +133,28 @@ def confirm_task_customer(
raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED') raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
if customer.status != 'active': if customer.status != 'active':
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE') raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
if task.business_no and task.customer_id not in {None, customer.id}: facts = customer_confirmation_facts(task)
if getattr(task, 'business_no', None) and facts['customer_id'] not in {None, customer.id}:
raise ConflictError( raise ConflictError(
'Numbered shipping notice customer cannot be changed silently', 'Numbered shipping notice customer cannot be changed silently',
code='SHIPPING.CUSTOMER_NUMBERED_NOTICE_LOCKED', code='SHIPPING.CUSTOMER_NUMBERED_NOTICE_LOCKED',
) )
now = datetime.utcnow() owner = task
previous_customer_id = task.customer_id if not isinstance(task, ShippingOrderTask):
task.customer_id = customer.id order_task_id = getattr(task, 'order_task_id', None)
task.customer_name_snapshot = customer.standard_name owner = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else None
task.customer_short_code_snapshot = customer.short_code if owner is None:
fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest() raise ConflictError('Shipping notice is not linked to an order task', code='SHIPPING.ORDER_TASK_REQUIRED')
task.customer_resolution_status = 'confirmed' confirm_customer_resolution(
task.customer_resolution_method = resolution_method owner,
task.customer_identity_fingerprint = fingerprint customer_id=int(customer.id),
task.customer_confirmed_by = actor_id actor_id=actor_id,
task.customer_confirmed_at = now method=resolution_method,
db.session.add(ShippingTaskEvent( )
task_id=task.id,
event_type='customer_confirmed',
detail_json={
'customer_id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'previous_customer_id': previous_customer_id,
'method': resolution_method,
'business_no': task.business_no,
},
))
if commit: if commit:
db.session.commit() db.session.commit()
return db.session.get(ShippingNotice, int(task.id)) return db.session.get(model, int(task.id))
db.session.flush() db.session.flush()
return task return task
@@ -13,18 +13,18 @@ from __future__ import annotations
from datetime import datetime from datetime import datetime
from typing import Any from typing import Any
from app.models import ShippingNotice, ShippingTemporaryInventorySession from app.models import ShippingOrderTask, ShippingTemporaryInventorySession
from app.services.agent_runtime_context.builder import serialize_for_dify from app.services.agent_runtime_context.builder import serialize_for_dify
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
def _task_by_task_no(task_id: str) -> ShippingNotice | None: def _task_by_task_no(task_id: str) -> ShippingOrderTask | None:
"""按显式 task_id 获取任务;禁止按会话号猜测当前任务。""" """按显式 task_id 获取任务;禁止按会话号猜测当前任务。"""
normalized = str(task_id or "").strip().upper() normalized = str(task_id or "").strip().upper()
if not normalized: if not normalized:
return None return None
return ShippingNotice.query.filter_by(task_no=normalized).first() return ShippingOrderTask.query.filter_by(task_no=normalized).first()
def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None: def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None:
@@ -56,7 +56,7 @@ def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | N
return str(item.session_no or '').strip().upper() or None if item else None return str(item.session_no or '').strip().upper() or None if item else None
def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -> ShippingNotice | None: def _focus_task_row(focus_task: str, explicit_task_row: ShippingOrderTask | None) -> ShippingOrderTask | None:
""" """
解析当前显式焦点任务行。 解析当前显式焦点任务行。
@@ -74,7 +74,7 @@ def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -
return None return None
if explicit_task_row and str(explicit_task_row.task_no or "").strip().upper() == normalized: if explicit_task_row and str(explicit_task_row.task_no or "").strip().upper() == normalized:
return explicit_task_row return explicit_task_row
return ShippingNotice.query.filter_by(task_no=normalized).first() return ShippingOrderTask.query.filter_by(task_no=normalized).first()
def build_dify_chat_inputs( def build_dify_chat_inputs(
@@ -1339,8 +1339,31 @@ def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None:
raise ConflictError('A cross-page blind test sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE') raise ConflictError('A cross-page blind test sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE')
def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str) -> None: def promote_approved_suite_for_publish(
"""将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。""" *, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str,
actor_id: int | None = None,
) -> None:
"""将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。
核心逻辑:
[STEP 1] 定位当前草稿 checksum 下已批准的盲测集;缺失时直接返回(生产调用方
已通过 assert_profile_publishable 门禁,此守卫仅防御测试夹具伪造凭证)。
[STEP 2] 同一 Profile 行重复发布相同内容时(如人工将已发布模板重置为草稿后
再次发布),发布 checksum 由规范化负载确定性复现,历史提升套件仍占用
(profile_id, profile_checksum) 唯一键。若占用者仍是有效发布凭证(approved 且
最近一次 Run 通过且 checksum 一致),则直接复用历史凭证:新草稿集转为
superseded 以保留其运行历史供审计,不再重写 checksum,避免唯一键冲突。
[STEP 3] 常规路径:重写套件与其 Run 的 checksum 为发布 checksum。
Args:
profile: 即将发布的 Profile ORM 记录(发布事务内调用,不自行提交)。
draft_checksum: 发布前草稿定义的规范化 checksum。
published_checksum: 本次发布冻结的正式 checksum。
actor_id: 触发发布的管理员主键,用于审计;允许为空。
Returns:
无返回值;套件状态变更随发布事务一并提交。
"""
suite = ShippingDocumentProfileTestSuite.query.filter_by( suite = ShippingDocumentProfileTestSuite.query.filter_by(
profile_id=profile.id, profile_checksum=draft_checksum, status='approved', profile_id=profile.id, profile_checksum=draft_checksum, status='approved',
).one_or_none() ).one_or_none()
@@ -1348,6 +1371,31 @@ def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile,
# isolated lifecycle tests from fabricating a quality credential by monkeypatch. # isolated lifecycle tests from fabricating a quality credential by monkeypatch.
if suite is None: if suite is None:
return return
# [STEP 2] 唯一键占用检查:发布 checksum 相同意味着定义、Schema 与 adapter 证据
# 完全一致,历史凭证对本次发布同样有效,无需也不允许重写第二个套件。
occupant = ShippingDocumentProfileTestSuite.query.filter_by(
profile_id=profile.id, profile_checksum=published_checksum,
).one_or_none()
if occupant is not None and occupant.id != suite.id:
occupant_last_run = occupant.runs[-1] if occupant.runs else None
if (
occupant.status == 'approved' and occupant_last_run is not None
and occupant_last_run.status == 'passed'
and occupant_last_run.profile_checksum == published_checksum
):
suite.status = 'superseded'
_audit(profile_id=profile.id, event_type='blind_test_suite_superseded', actor_id=actor_id, detail={
'suite_id': suite.id, 'reused_suite_id': occupant.id,
'reason_code': 'republish_identical_content',
})
return
# 占用者不是有效凭证(人工改动等异常数据):拒绝发布并给出可定位的错误码,
# 禁止静默覆盖或删除历史盲测证据。
raise ConflictError(
'Published checksum is already occupied by another test suite',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SUITE_CHECKSUM_CONFLICT',
details={'suite_id': occupant.id},
)
suite.profile_checksum = published_checksum suite.profile_checksum = published_checksum
for run in suite.runs: for run in suite.runs:
if run.profile_checksum == draft_checksum: if run.profile_checksum == draft_checksum:
@@ -23,6 +23,7 @@ from app.models import (
ShippingOrderIntake, ShippingOrderIntake,
ShippingOrderSnapshot, ShippingOrderSnapshot,
ShippingNotice, ShippingNotice,
ShippingOrderTask,
) )
from app.services.shipping_notice.business_fingerprint import ( from app.services.shipping_notice.business_fingerprint import (
CONTENT_FINGERPRINT_VERSION, CONTENT_FINGERPRINT_VERSION,
@@ -40,19 +41,35 @@ def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str
lifecycle = str(get('lifecycle_status', '') or '').strip().lower() lifecycle = str(get('lifecycle_status', '') or '').strip().lower()
if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}: if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}:
return 'closed' return 'closed'
upload = str(get('upload_status', '') or '').strip().lower() upload = None
if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no'): try:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
if not isinstance(task, dict) and has_verified_upload_success(task):
upload = 'uploaded'
except Exception:
upload = None
if upload in {'uploaded', 'succeeded', 'success'}:
return 'completed' return 'completed'
return 'active' return 'active'
def is_irreversible_task(task: ShippingNotice) -> bool: def is_irreversible_task(task: ShippingNotice) -> bool:
"""已 uploaded 或终态任务不可原地覆盖源文件。""" """已 uploaded 或终态任务不可原地覆盖源文件。"""
upload_status = str(task.upload_status or '').strip().lower() try:
return upload_status in {'uploaded', 'succeeded', 'success'} from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
return has_verified_upload_success(task)
except Exception:
return False
def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]: def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]:
candidate = (
db.session.query(ShippingOrderCandidate)
.filter(ShippingOrderCandidate.consumed_task_id == task.order_task_id)
.order_by(ShippingOrderCandidate.id.desc())
.first()
if getattr(task, 'order_task_id', None) else None
)
return { return {
'task_no': task.task_no, 'task_no': task.task_no,
'document_version': int(task.document_version or 1), 'document_version': int(task.document_version or 1),
@@ -60,14 +77,29 @@ def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: lis
'matched_fields': list(matched_fields), 'matched_fields': list(matched_fields),
'lifecycle': classify_task_lifecycle(task), 'lifecycle': classify_task_lifecycle(task),
'created_at': utc_iso(task.created_at), 'created_at': utc_iso(task.created_at),
'content_fingerprint': task.content_fingerprint, 'content_fingerprint': getattr(candidate, 'content_fingerprint', None),
'content_fingerprint_version': task.content_fingerprint_version, 'content_fingerprint_version': getattr(candidate, 'content_fingerprint_version', None),
} }
def _task_content_fingerprint(task: ShippingNotice) -> tuple[str | None, str | None]:
"""从建单来源 Candidate 读取内容指纹;正式 Notice 不再保存该投影。"""
if not getattr(task, 'order_task_id', None):
return None, None
candidate = (
db.session.query(ShippingOrderCandidate.content_fingerprint, ShippingOrderCandidate.content_fingerprint_version)
.filter(ShippingOrderCandidate.consumed_task_id == task.order_task_id)
.order_by(ShippingOrderCandidate.id.desc())
.first()
)
return (candidate[0], candidate[1]) if candidate else (None, None)
def _reservation_differences(task: ShippingNotice, summary: dict[str, Any]) -> list[dict[str, Any]]: def _reservation_differences(task: ShippingNotice, summary: dict[str, Any]) -> list[dict[str, Any]]:
"""比较候选与目标冻结订单的同 Reservation 行,供人工修订确认前展示。""" """比较候选与目标冻结订单的同 Reservation 行,供人工修订确认前展示。"""
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None: if snapshot is None:
return [] return []
proposed = { proposed = {
@@ -158,10 +190,13 @@ def detect_duplicates_for_intake(
if content_hash: if content_hash:
hash_tasks = ( hash_tasks = (
db.session.query(ShippingNotice) db.session.query(ShippingNotice)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id)
.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
.filter( .filter(
ShippingNotice.user_id == int(intake.user_id), ShippingOrderTask.user_id == int(intake.user_id),
ShippingNotice.source_content_hash == content_hash, FileAsset.content_hash == content_hash,
ShippingNotice.lifecycle_status == 'active', ShippingOrderTask.lifecycle_status == 'active',
) )
.order_by(ShippingNotice.id.desc()) .order_by(ShippingNotice.id.desc())
.limit(10) .limit(10)
@@ -182,10 +217,12 @@ def detect_duplicates_for_intake(
if fingerprint and strength in {'strong', 'medium'}: if fingerprint and strength in {'strong', 'medium'}:
fp_tasks = ( fp_tasks = (
db.session.query(ShippingNotice) db.session.query(ShippingNotice)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter( .filter(
ShippingNotice.user_id == int(intake.user_id), ShippingOrderTask.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint, ShippingOrderCandidate.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version, ShippingOrderCandidate.fingerprint_version == version,
) )
.order_by(ShippingNotice.id.desc()) .order_by(ShippingNotice.id.desc())
.limit(20) .limit(20)
@@ -206,12 +243,13 @@ def detect_duplicates_for_intake(
if matches and status == 'none': if matches and status == 'none':
comparable = [ comparable = [
task for task in fp_tasks task for task in fp_tasks
if task.content_fingerprint and task.content_fingerprint_version == content_version if _task_content_fingerprint(task)[0]
and _task_content_fingerprint(task)[1] == content_version
] ]
if content_fingerprint and comparable: if content_fingerprint and comparable:
status = ( status = (
'same_business_content' 'same_business_content'
if any(task.content_fingerprint == content_fingerprint for task in comparable) if any(_task_content_fingerprint(task)[0] == content_fingerprint for task in comparable)
else 'possible_revision' else 'possible_revision'
) )
else: else:
@@ -229,11 +267,13 @@ def detect_duplicates_for_intake(
# 弱指纹:仅标记疑似,不按 active 强阻断 # 弱指纹:仅标记疑似,不按 active 强阻断
fp_tasks = ( fp_tasks = (
db.session.query(ShippingNotice) db.session.query(ShippingNotice)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter( .filter(
ShippingNotice.user_id == int(intake.user_id), ShippingOrderTask.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint, ShippingOrderCandidate.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version, ShippingOrderCandidate.fingerprint_version == version,
ShippingNotice.lifecycle_status == 'active', ShippingOrderTask.lifecycle_status == 'active',
) )
.order_by(ShippingNotice.id.desc()) .order_by(ShippingNotice.id.desc())
.limit(5) .limit(5)
@@ -498,11 +538,10 @@ def detect_duplicates_for_candidate(
if content_hash: if content_hash:
hash_query = ( hash_query = (
db.session.query(ShippingNotice) db.session.query(ShippingNotice)
.filter( .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
ShippingNotice.user_id == int(intake.user_id), .join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id)
ShippingNotice.source_content_hash == content_hash, .join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
ShippingNotice.lifecycle_status == 'active', .filter(ShippingOrderTask.user_id == int(intake.user_id), FileAsset.content_hash == content_hash, ShippingOrderTask.lifecycle_status == 'active')
)
) )
if skipped_ids: if skipped_ids:
hash_query = hash_query.filter(ShippingNotice.id.notin_(list(skipped_ids))) hash_query = hash_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -522,11 +561,9 @@ def detect_duplicates_for_candidate(
if fingerprint and strength in {'strong', 'medium'}: if fingerprint and strength in {'strong', 'medium'}:
fp_query = ( fp_query = (
db.session.query(ShippingNotice) db.session.query(ShippingNotice)
.filter( .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
ShippingNotice.user_id == int(intake.user_id), .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
ShippingNotice.business_fingerprint == fingerprint, .filter(ShippingOrderTask.user_id == int(intake.user_id), ShippingOrderCandidate.business_fingerprint == fingerprint, ShippingOrderCandidate.fingerprint_version == version)
ShippingNotice.fingerprint_version == version,
)
) )
if skipped_ids: if skipped_ids:
fp_query = fp_query.filter(ShippingNotice.id.notin_(list(skipped_ids))) fp_query = fp_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -545,12 +582,13 @@ def detect_duplicates_for_candidate(
if matches and status == 'none': if matches and status == 'none':
comparable = [ comparable = [
task for task in fp_tasks task for task in fp_tasks
if task.content_fingerprint and task.content_fingerprint_version == content_version if _task_content_fingerprint(task)[0]
and _task_content_fingerprint(task)[1] == content_version
] ]
if content_fingerprint and comparable: if content_fingerprint and comparable:
status = ( status = (
'same_business_content' 'same_business_content'
if any(task.content_fingerprint == content_fingerprint for task in comparable) if any(_task_content_fingerprint(task)[0] == content_fingerprint for task in comparable)
else 'possible_revision' else 'possible_revision'
) )
else: else:
@@ -564,12 +602,9 @@ def detect_duplicates_for_candidate(
elif fingerprint and strength == 'weak' and status == 'none': elif fingerprint and strength == 'weak' and status == 'none':
weak_query = ( weak_query = (
db.session.query(ShippingNotice) db.session.query(ShippingNotice)
.filter( .join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
ShippingNotice.user_id == int(intake.user_id), .join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
ShippingNotice.business_fingerprint == fingerprint, .filter(ShippingOrderTask.user_id == int(intake.user_id), ShippingOrderCandidate.business_fingerprint == fingerprint, ShippingOrderCandidate.fingerprint_version == version, ShippingOrderTask.lifecycle_status == 'active')
ShippingNotice.fingerprint_version == version,
ShippingNotice.lifecycle_status == 'active',
)
) )
if skipped_ids: if skipped_ids:
weak_query = weak_query.filter(ShippingNotice.id.notin_(list(skipped_ids))) weak_query = weak_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -570,7 +570,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'), 'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'),
'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'), 'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'),
'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'), 'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'),
'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'), 'inventory_file_missing': _meta('owner', 'retry_inventory_preparation', '未生成库存文件'),
'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'), 'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'),
'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'), 'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'),
'inventory_candidate_version_stale': _meta('system', 'retry_with_latest_rules', '库存候选版本已切换'), 'inventory_candidate_version_stale': _meta('system', 'retry_with_latest_rules', '库存候选版本已切换'),
@@ -613,7 +613,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'inventory_reservation_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 Reservation'), 'inventory_reservation_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 Reservation'),
'inventory_warehouse_mismatch': _meta('owner', 'open_inventory_match_review', '仓库与订单要求不一致'), 'inventory_warehouse_mismatch': _meta('owner', 'open_inventory_match_review', '仓库与订单要求不一致'),
'inventory_uom_conversion_failed': _meta('owner', 'open_inventory_match_review', '单位换算失败'), 'inventory_uom_conversion_failed': _meta('owner', 'open_inventory_match_review', '单位换算失败'),
'inventory_multi_file_conflict': _meta('owner', 'open_inventory_match_review', '多库存文件结果冲突'), 'inventory_multi_file_conflict': _meta('owner', 'override_line_inventory_source', '多库存文件结果冲突'),
} }
@@ -86,7 +86,7 @@ def _accepted_header_values(candidate: ShippingOrderCandidate) -> tuple[Shipping
def definition_context_field_is_compatible( def definition_context_field_is_compatible(
definition: dict[str, Any], extraction: ShippingOrderExtraction, actual_field_id: str, definition: dict[str, Any], extraction: ShippingOrderExtraction, actual_field_id: str,
) -> bool: ) -> bool:
"""校验新版 Schema 字段能否承接旧规则快照,防止字段 UUID 漂移误伤稳定业务语义。""" """字段绑定主谓词:先认定同一 UUID 即同字段;否则按 field_code + scope + value_type 判断语义兼容承接规则快照。"""
expected_id = str(definition.get('context_field_id') or '') expected_id = str(definition.get('context_field_id') or '')
if actual_field_id == expected_id: if actual_field_id == expected_id:
return True return True
@@ -111,15 +111,19 @@ def definition_context_field_is_compatible(
def _resolved_context_field_id( def _resolved_context_field_id(
definition: dict[str, Any], extraction: ShippingOrderExtraction | None, header_values: dict[str, dict[str, Any]], definition: dict[str, Any], extraction: ShippingOrderExtraction | None, header_values: dict[str, dict[str, Any]],
) -> str | None: ) -> str | None:
"""优先使用快照 UUID;Schema 升级仅在字段业务语义未变化时按 field_code 映射到新 UUID。""" """按 field_config.field_code 语义键定位当前字段;UUID 直配仅保留为同字段快速命中。
expected_id = str(definition.get('context_field_id') or '')
if expected_id in header_values: 规则定义以 field_code(不随 Schema 版本重建而漂移)作为跨版本稳定引用锚点;
return expected_id UUID 直接命中只作为无漂移时的快捷路径,避免 Schema 重发布打断识别链路。
if extraction is None: 旧快照若缺少 field_code,则回退到 UUID 直配路径,保证向后兼容。
return None """
if extraction is not None:
for field_id in header_values: for field_id in header_values:
if definition_context_field_is_compatible(definition, extraction, field_id): if definition_context_field_is_compatible(definition, extraction, field_id):
return field_id return field_id
expected_id = str(definition.get('context_field_id') or '')
if expected_id in header_values:
return expected_id
return None return None
@@ -12,8 +12,6 @@ import hashlib
import json import json
import re import re
import uuid import uuid
from pathlib import Path
import urllib.request
from datetime import datetime from datetime import datetime
from typing import Any from typing import Any
@@ -112,19 +110,6 @@ def _published_schema_version() -> ShippingOrderSchemaVersion | None:
def _published_field_config(field_id: str) -> dict[str, Any] | None: def _published_field_config(field_id: str) -> dict[str, Any] | None:
"""读取当前发布版本中的字段配置;识别定义和证据标准化均使用同一快照。""" """读取当前发布版本中的字段配置;识别定义和证据标准化均使用同一快照。"""
# #region debug-point A/B/C/E:published-schema-state
try:
debug_env = Path(__file__).resolve().parents[5] / '.dbg' / 'shipping-customer-fingerprint-500.env'
debug_values = {
line.split('=', 1)[0]: line.split('=', 1)[1].strip()
for line in debug_env.read_text(encoding='utf-8').splitlines()
if '=' in line
}
published_rows = ShippingOrderSchemaVersion.query.filter_by(status='published').all()
urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'shipping-customer-fingerprint-500'), 'runId': 'post-fix', 'hypothesisId': 'A/B/C/E', 'location': 'identity_rules/service.py:114', 'msg': '[DEBUG] published schema rows before serializer lookup', 'data': {'field_id': field_id, 'count': len(published_rows), 'rows': [{'id': row.id, 'schema_id': row.schema_id, 'version': row.version, 'status': row.status} for row in published_rows]}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read()
except Exception:
pass
# #endregion
published = _published_schema_version() published = _published_schema_version()
return next(( return next((
item for item in ((published.definition_json if published else {}) or {}).get('fields', []) item for item in ((published.definition_json if published else {}) or {}).get('fields', [])
@@ -17,7 +17,8 @@ from typing import Any
from app.models import ( from app.models import (
ShippingDocumentProfileAutoFreezeQualification, ShippingDocumentProfileAutoFreezeQualification,
ShippingOrderCustomerMatch, ShippingCustomerShadowResolution,
ShippingOrderCandidate,
ShippingOrderExtraction, ShippingOrderExtraction,
ShippingOrderExtractionProgressEvent, ShippingOrderExtractionProgressEvent,
ShippingOrderRouteDecision, ShippingOrderRouteDecision,
@@ -321,19 +322,19 @@ def _qualification_for_route(
def _confirmed_customer_ids(run: ShippingOrderProcessingRun) -> list[int]: def _confirmed_customer_ids(run: ShippingOrderProcessingRun) -> list[int]:
"""读取本轮已确认的 Bill-to 客户;跨订单多客户时必须维持 fail-closed。""" """读取本轮正式识别结果中的已确认客户;跨订单多客户时维持 fail-closed。"""
rows = ( rows = (
ShippingOrderCustomerMatch.query ShippingCustomerShadowResolution.query
.join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id) .join(ShippingOrderCandidate, ShippingOrderCandidate.id == ShippingCustomerShadowResolution.candidate_id)
.join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCandidate.order_extraction_id)
.filter( .filter(
ShippingOrderExtraction.run_id == int(run.id), ShippingOrderExtraction.run_id == int(run.id),
ShippingOrderCustomerMatch.role == 'bill_to', ShippingCustomerShadowResolution.status == 'confirmed',
ShippingOrderCustomerMatch.status == 'confirmed', ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None),
ShippingOrderCustomerMatch.customer_id.isnot(None),
) )
.all() .all()
) )
return sorted({int(row.customer_id) for row in rows if row.customer_id is not None}) return sorted({int(row.confirmed_customer_id) for row in rows if row.confirmed_customer_id is not None})
def _evaluate_customer_scope( def _evaluate_customer_scope(
@@ -7,7 +7,7 @@ services/shipping_notice/order_build_eligibility_service.py
inventory_routing_engine、inventory_source_repository、 inventory_routing_engine、inventory_source_repository、
ShippingOrderCandidate / ShippingOrderProcessingUnit / ShippingOrderProcessingRun、 ShippingOrderCandidate / ShippingOrderProcessingUnit / ShippingOrderProcessingRun、
ShippingInventorySource、process_gate_contract(原因唯一归属)。 ShippingInventorySource、process_gate_contract(原因唯一归属)。
逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核阻断; 逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核不阻断正式 OT 创建(库存路由属可人工修正事实,行级仍记录 block_reason 供自动建单/复核门禁消费);
人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离; 人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离;
停用 / Profile 未启用 / 无已发布解析 Profile / Excel 模板未发布的 Source 不进入有效候选, 停用 / Profile 未启用 / 无已发布解析 Profile / Excel 模板未发布的 Source 不进入有效候选,
并写入稳定 unavailable_reasons(码表见 error_explainability_contract); 并写入稳定 unavailable_reasons(码表见 error_explainability_contract);
@@ -473,7 +473,7 @@ def assess_order_build_eligibility(
fields: Schema field_id → 配置。 fields: Schema field_id → 配置。
header_by_code: Header field_code → 值。 header_by_code: Header field_code → 值。
lines: 行 field_code → 值列表(与 line_metas 对齐)。 lines: 行 field_code → 值列表(与 line_metas 对齐)。
line_metas: Draft 行原始对象(含 line_key / inventory_routing)。 line_metas: Draft 行原始对象(含 draft_line_id / inventory_routing)。
customer_resolved: 客户是否已唯一命中或人工确认;缺省 True 由调用方保证。 customer_resolved: 客户是否已唯一命中或人工确认;缺省 True 由调用方保证。
candidate / unit / run: 可选门禁上下文(自动建单检查)。 candidate / unit / run: 可选门禁上下文(自动建单检查)。
@@ -515,7 +515,7 @@ def assess_order_build_eligibility(
line_meta=meta, line_meta=meta,
) )
projection = { projection = {
'line_key': meta.get('line_key'), 'draft_line_id': meta.get('draft_line_id'),
'line_index': index, 'line_index': index,
'effective_reservation_id': effective, 'effective_reservation_id': effective,
'inventory_source_hint': raw_line.get('inventory_source_hint'), 'inventory_source_hint': raw_line.get('inventory_source_hint'),
@@ -526,7 +526,7 @@ def assess_order_build_eligibility(
if not effective: if not effective:
issues.append({ issues.append({
'code': 'effective_reservation_missing', 'code': 'effective_reservation_missing',
'line_key': meta.get('line_key'), 'draft_line_id': meta.get('draft_line_id'),
'line_index': index, 'line_index': index,
'severity': 'blocking', 'severity': 'blocking',
'owning_gate_code': 'reservation_validation', 'owning_gate_code': 'reservation_validation',
@@ -534,7 +534,7 @@ def assess_order_build_eligibility(
if not routing.get('can_build'): if not routing.get('can_build'):
issues.append({ issues.append({
'code': str(routing.get('block_reason') or 'inventory_source_unresolved'), 'code': str(routing.get('block_reason') or 'inventory_source_unresolved'),
'line_key': meta.get('line_key'), 'draft_line_id': meta.get('draft_line_id'),
'line_index': index, 'line_index': index,
'severity': 'blocking', 'severity': 'blocking',
'owning_gate_code': 'inventory_source_routing', 'owning_gate_code': 'inventory_source_routing',
@@ -573,11 +573,16 @@ def assess_order_build_eligibility(
'owning_gate_code': 'reservation_validation', 'owning_gate_code': 'reservation_validation',
}) })
# 库存源路由属于通知准备阶段可人工修正的事实,不阻断正式 OT 创建。
build_blocking_issues = [
item for item in issues
if str(item.get('owning_gate_code') or '') != 'inventory_source_routing'
]
can_build = ( can_build = (
bool(customer_resolved) bool(customer_resolved)
and bool(assessment.get('can_create_task')) and bool(assessment.get('can_create_task'))
and not issues and not build_blocking_issues
and all(item.get('can_build') and item.get('effective_reservation_id') for item in line_projections) and all(item.get('effective_reservation_id') for item in line_projections)
and bool(line_projections) and bool(line_projections)
) )
fields_complete = ( fields_complete = (
@@ -12,8 +12,17 @@ import re
from decimal import Decimal, InvalidOperation from decimal import Decimal, InvalidOperation
from typing import Any from typing import Any
from app.services.shipping_notice.notice_line_table import parse_notice_table_text from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract from app.services.shipping_notice.notice_line_table import (
find_notice_header_row_index,
parse_notice_row,
parse_notice_table_text,
)
from app.services.shipping_notice.notice_line_values import resolve_notice_columns
from app.services.shipping_notice.order_schema.table_contract import (
compile_table_header_contract,
normalize_table_header,
)
from app.services.shipping_notice.po_number import normalize_po_number from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_id import validated_reservation_id from app.services.shipping_notice.reservation_id import validated_reservation_id
@@ -33,11 +42,49 @@ def _comparable_value(field: str, value: Any) -> str:
return str(value or "").strip().upper() return str(value or "").strip().upper()
def _scan_email_po_aws_header(
header: list[str], schema_definition: dict[str, Any],
) -> tuple[int | None, int | None]:
"""
定位邮件正文表头中 PO 与 AWS SKU 的列索引。
背景:`po_number` 为 header 作用域、`aws_part_number` 不在 TABLE_FIELD_CODES 内,两者都不会被
compile_table_header_contract 编入契约,故 `parse_notice_row` 永远不会产出这两个字段。正文订单索引行
需要额外保留它们,才能在按 PO 融合附件时回填正文分配字段(如 inventory_source_hint / customer_part_number
等)。为不移除共享表头契约(守约严格性),这里只做独立的表头列扫描。
Returns:
返回 (po_idx, aws_idx);对应列不在表头时结果为 None。
"""
# 仅从本次预处理选择的 Schema 定义派生候选表头(field_code + display_name + aliases),避免硬编码漂移。
aliases: dict[str, set[str]] = {"po_number": set(), "aws_part_number": set()}
for raw in schema_definition.get("fields") or []:
code = str(raw.get("field_code") or "").strip()
if code not in aliases:
continue
for candidate in (code, raw.get("display_name"), *(raw.get("aliases") or [])):
normalized = normalize_table_header(candidate)
if normalized:
aliases[code].add(normalized)
po_idx = None
aws_idx = None
for i, cell_text in enumerate(header):
normalized = normalize_table_header(cell_text)
if normalized and normalized in aliases["po_number"]:
po_idx = i
if normalized and normalized in aliases["aws_part_number"]:
aws_idx = i
return po_idx, aws_idx
def build_email_order_index(body_text: str, *, schema_definition: dict[str, Any]) -> list[dict[str, Any]]: def build_email_order_index(body_text: str, *, schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
""" """
从邮件正文表格提取订单索引行。 从邮件正文表格提取订单索引行。
核心逻辑:复用统一订单表格解析器,并只保留具备 PO 或 Reservation 的有效订单行。 核心逻辑:复用统一订单表格解析器抽标准明细字段,并额外按正文原始表头回填 `po_number` 与
`aws_part_number`(两者因作用域/字段表不在共享契约中,parse_notice_row 不产出),供按 PO 融合
附件时补正文分配字段。最后只保留具备 PO 或 Reservation 的有效订单行。
Args: Args:
body_text: 邮件正文纯文本。 body_text: 邮件正文纯文本。
schema_definition: 本次预处理明确选择的订单 Schema 定义。 schema_definition: 本次预处理明确选择的订单 Schema 定义。
@@ -45,7 +92,44 @@ def build_email_order_index(body_text: str, *, schema_definition: dict[str, Any]
正文订单索引列表。 正文订单索引列表。
""" """
contract = compile_table_header_contract(schema_definition) contract = compile_table_header_contract(schema_definition)
rows = parse_notice_table_text(str(body_text or ""), contract=contract) text = str(body_text or "")
# 先用共享解析器判空;无有效行时直接退化为共享结果,避免空文本重复自建解析。
if not parse_notice_table_text(text, contract=contract):
return []
raw_rows = _rows_from_table_text(text)
if not raw_rows:
return []
header_idx = find_notice_header_row_index(raw_rows, contract=contract)
header = [str(c or "").strip() for c in raw_rows[header_idx]]
po_idx, aws_idx = _scan_email_po_aws_header(header, schema_definition)
columns = resolve_notice_columns(header, contract)
if columns.get("_ambiguous_fields"):
return []
idx_res = columns.get("reservation_id")
if idx_res is not None and idx_res < len(header):
columns["_reservation_id_header"] = str(header[idx_res] or "").strip()
rows: list[dict[str, Any]] = []
for raw_row in raw_rows[header_idx + 1:]:
if not raw_row:
continue
parsed = parse_notice_row(list(raw_row), columns, contract=contract)
if parsed is None:
continue
# 回填共享解析器不产出的 PO / AWS SKU,保证正文行与原始表列强对齐。
if po_idx is not None and po_idx < len(raw_row):
po_number = str(raw_row[po_idx] or "").strip()
if po_number:
parsed["po_number"] = po_number
if aws_idx is not None and aws_idx < len(raw_row):
aws_part_number = str(raw_row[aws_idx] or "").strip()
if aws_part_number:
parsed["aws_part_number"] = aws_part_number
rows.append(parsed)
return [ return [
row for row in rows row for row in rows
if normalize_po_number(row.get("po_number")) if normalize_po_number(row.get("po_number"))
@@ -178,6 +178,8 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
sample_role=sample_role, created_by_id=actor_id, sample_role=sample_role, created_by_id=actor_id,
)) ))
db.session.flush() db.session.flush()
if document.asset_id:
profile_service._retain_profile_sample_assets(profile_id, asset_ids={int(document.asset_id)})
profile_service._refresh_training_sample_count(db.session.get(ShippingOrderDocumentProfile, profile_id)) profile_service._refresh_training_sample_count(db.session.get(ShippingOrderDocumentProfile, profile_id))
revision_no = int(saved['draft_revision']['revision_no']) revision_no = int(saved['draft_revision']['revision_no'])
profile_service._audit( profile_service._audit(
@@ -153,6 +153,7 @@ def _frozen_sample_context(
'Frozen sample file is unavailable', 'Frozen sample file is unavailable',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
) )
profile_service._repair_bound_sample_asset(document)
asset = db.session.get(FileAsset, int(document.asset_id)) asset = db.session.get(FileAsset, int(document.asset_id))
if asset is None: if asset is None:
raise ValidationError( raise ValidationError(
@@ -239,6 +240,39 @@ def _render_pdf_pages(asset: FileAsset) -> list[Any]:
) from exc ) from exc
def _frozen_physical_page_count(
*, layout_version: ShippingDocumentLayoutVersion, document: ShippingOrderDocument,
) -> int | None:
"""
从冻结 Layout 的完整页证据读取原 PDF 物理页数,供历史错误快照的只读兼容校验。
核心逻辑:持久化 Layout 可把坐标证据外置到受控 FileAsset,本函数只加载该冻结引用;
仅页面元数据可证明物理页数,绝不以业务表格页数作为回退。
Args:
layout_version: 已通过冻结 checksum 校验的 Layout 版本。
document: 与 Layout 绑定且已通过内容 hash 校验的样本文档。
Returns:
完整页证据可用时返回物理页数;证据缺失或结构无效时返回 None。
"""
from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence
payload = _hydrate_coordinate_evidence(
payload=dict(layout_version.payload_json or {}), document=document,
)
pages = payload.get('pages')
if isinstance(pages, list):
count = len([item for item in pages if isinstance(item, dict)])
if count:
return count
evidence = payload.get('coordinate_evidence')
evidence_pages = evidence.get('pages') if isinstance(evidence, dict) else None
if isinstance(evidence_pages, dict) and evidence_pages:
return len(evidence_pages)
return None
def authorize_frozen_sample_preview_pages( def authorize_frozen_sample_preview_pages(
profile_id: int, profile_id: int,
*, *,
@@ -258,11 +292,14 @@ def authorize_frozen_sample_preview_pages(
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id)) profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
if profile is None: if profile is None:
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND') raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
_, sample, document, _layout_version, asset = _frozen_sample_context( _, sample, document, layout_version, asset = _frozen_sample_context(
profile_id=int(profile_id), sample_binding_id=int(sample_binding_id), profile_id=int(profile_id), sample_binding_id=int(sample_binding_id),
) )
pages = _render_pdf_pages(asset) pages = _render_pdf_pages(asset)
if sample.page_count_snapshot is not None and len(pages) != int(sample.page_count_snapshot): if sample.page_count_snapshot is not None and len(pages) != int(sample.page_count_snapshot):
# [STEP 1] 兼容修复上线前把外置证据退化为表格页数的历史冻结记录;
# 只有同一冻结 Layout 的完整页证据与当前原 PDF 一致时才允许预览。
if _frozen_physical_page_count(layout_version=layout_version, document=document) != len(pages):
raise ValidationError( raise ValidationError(
'Frozen page count no longer matches the published evidence', 'Frozen page count no longer matches the published evidence',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
@@ -309,9 +309,58 @@ def _bound_sample_document(profile_id: int, document_id: int) -> ShippingOrderDo
document = db.session.get(ShippingOrderDocument, int(document_id)) document = db.session.get(ShippingOrderDocument, int(document_id))
if document is None: if document is None:
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
_repair_bound_sample_asset(document)
return document return document
def _repair_bound_sample_asset(document: ShippingOrderDocument) -> None:
"""补偿历史样本资产引用,避免已绑定的标注样本按临时 TTL 过期。"""
if not document.asset_id:
return
asset = db.session.get(FileAsset, int(document.asset_id))
if asset is None:
return
if str(asset.lifecycle_status or '') == 'temporary' and int(asset.reference_count or 0) == 0:
from app.services.file_assets.service import mark_asset_referenced
mark_asset_referenced(asset)
def _retain_profile_sample_assets(profile_id: int, *, asset_ids: set[int] | None = None) -> int:
"""为新增 Profile 样本引用的每个唯一文件资产建立一份引用。"""
from app.services.file_assets.service import mark_asset_referenced
ids = set(asset_ids or ())
for asset_id in sorted(ids):
asset = db.session.get(FileAsset, asset_id)
if asset is not None:
mark_asset_referenced(asset)
return len(ids)
def _release_profile_sample_asset_if_unreferenced(profile_id: int, document_id: int) -> None:
"""删除样本绑定后,仅当该 Profile 不再引用文件时释放资产引用。"""
document = db.session.get(ShippingOrderDocument, int(document_id))
if document is None or not document.asset_id:
return
still_bound = (
db.session.query(ShippingOrderDocumentProfileSample)
.join(ShippingOrderDocument, ShippingOrderDocument.id == ShippingOrderDocumentProfileSample.document_id)
.filter(
ShippingOrderDocumentProfileSample.profile_id == int(profile_id),
ShippingOrderDocument.asset_id == int(document.asset_id),
)
.first()
)
if still_bound is not None:
return
asset = db.session.get(FileAsset, int(document.asset_id))
if asset is not None and int(asset.reference_count or 0) > 0:
from app.services.file_assets.service import release_asset_reference
release_asset_reference(asset)
def _preview_grant_store() -> Any: def _preview_grant_store() -> Any:
"""?????????????? Redis????????????????""" """?????????????? Redis????????????????"""
return preview_grant_store() return preview_grant_store()
@@ -1461,6 +1510,11 @@ def add_profile_sample(
if document is None: if document is None:
raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND') raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
_document_layout(document) _document_layout(document)
existing_asset_ids = {
int(existing_document.asset_id)
for existing in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all()
if (existing_document := db.session.get(ShippingOrderDocument, int(existing.document_id))) is not None and existing_document.asset_id
}
sample = ShippingOrderDocumentProfileSample( sample = ShippingOrderDocumentProfileSample(
profile_id=profile.id, document_id=document.id, profile_id=profile.id, document_id=document.id,
table_id=str(table_id).strip() or None, sample_role=role, created_by_id=actor_id, table_id=str(table_id).strip() or None, sample_role=role, created_by_id=actor_id,
@@ -1472,6 +1526,8 @@ def add_profile_sample(
db.session.rollback() db.session.rollback()
raise ConflictError('Profile sample already exists', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_CONFLICT') from exc raise ConflictError('Profile sample already exists', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_CONFLICT') from exc
_refresh_training_sample_count(profile) _refresh_training_sample_count(profile)
if document.asset_id and int(document.asset_id) not in existing_asset_ids:
_retain_profile_sample_assets(profile.id, asset_ids={int(document.asset_id)})
clear_matching_signature_refs(profile, actor_id=actor_id, reason='sample_added') clear_matching_signature_refs(profile, actor_id=actor_id, reason='sample_added')
_audit(profile_id=profile.id, document_id=document.id, event_type='profile_sample_added', actor_id=actor_id, detail={ _audit(profile_id=profile.id, document_id=document.id, event_type='profile_sample_added', actor_id=actor_id, detail={
'sample_role': role, 'has_table_binding': sample.table_id is not None, 'sample_role': role, 'has_table_binding': sample.table_id is not None,
@@ -1494,6 +1550,7 @@ def remove_profile_sample(profile_id: int, sample_id: int, *, actor_id: int | No
sample_role = sample.sample_role sample_role = sample.sample_role
db.session.delete(sample) db.session.delete(sample)
db.session.flush() db.session.flush()
_release_profile_sample_asset_if_unreferenced(profile.id, document_id)
_refresh_training_sample_count(profile) _refresh_training_sample_count(profile)
clear_matching_signature_refs(profile, actor_id=actor_id, reason='sample_removed') clear_matching_signature_refs(profile, actor_id=actor_id, reason='sample_removed')
_audit(profile_id=profile.id, document_id=document_id, event_type='profile_sample_removed', actor_id=actor_id, detail={ _audit(profile_id=profile.id, document_id=document_id, event_type='profile_sample_removed', actor_id=actor_id, detail={
@@ -1668,7 +1725,9 @@ def refresh_profile_sample_readiness(
# not merely a repeated read of the same frozen sample. # not merely a repeated read of the same frozen sample.
sample.evidence_frozen_at = datetime.utcnow() if changed else sample.evidence_frozen_at sample.evidence_frozen_at = datetime.utcnow() if changed else sample.evidence_frozen_at
sample.source_filename_snapshot = str(document.filename or '').strip() or None sample.source_filename_snapshot = str(document.filename or '').strip() or None
sample.page_count_snapshot = _layout_page_count(version.payload_json or {}) # [STEP 1] 页数必须来自已加载的完整坐标证据;持久化 payload 可能仅保留外置证据引用,
# 不能退化为“有业务表格的页数”。
sample.page_count_snapshot = _layout_page_count(layout)
sample.table_identity_snapshot = _layout_table_identity_snapshot(version.payload_json or {}, table_id) sample.table_identity_snapshot = _layout_table_identity_snapshot(version.payload_json or {}, table_id)
if changed: if changed:
_audit( _audit(
@@ -1860,7 +1919,8 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr
sample.parser_version = str(layout_version.parser_version or '').strip() or None sample.parser_version = str(layout_version.parser_version or '').strip() or None
sample.evidence_frozen_at = frozen_at sample.evidence_frozen_at = frozen_at
sample.source_filename_snapshot = str(document.filename or '').strip() or None sample.source_filename_snapshot = str(document.filename or '').strip() or None
sample.page_count_snapshot = _layout_page_count(layout_version.payload_json or {}) # [STEP 1] 发布冻结使用已加载的外置坐标证据,保证页数与原 PDF 物理页一致。
sample.page_count_snapshot = _layout_page_count(hydrated_layout)
sample.table_identity_snapshot = _layout_table_identity_snapshot( sample.table_identity_snapshot = _layout_table_identity_snapshot(
layout_version.payload_json or {}, sample.table_id, layout_version.payload_json or {}, sample.table_id,
) )
@@ -1914,6 +1974,7 @@ def _retain_frozen_sample_assets(profile: ShippingOrderDocumentProfile) -> int:
'Profile sample file asset is unavailable', 'Profile sample file asset is unavailable',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
) )
if str(asset.lifecycle_status or '') == 'temporary' and int(asset.reference_count or 0) == 0:
mark_asset_referenced(asset) mark_asset_referenced(asset)
retained_asset_ids.add(asset_id) retained_asset_ids.add(asset_id)
return len(retained_asset_ids) return len(retained_asset_ids)
@@ -3217,9 +3278,12 @@ def create_draft_from_sample(
profile_id=saved['id'], document_id=document.id, table_id=None, profile_id=saved['id'], document_id=document.id, table_id=None,
sample_role='annotation', created_by_id=actor_id, sample_role='annotation', created_by_id=actor_id,
)) ))
db.session.flush()
_audit(profile_id=saved['id'], document_id=document.id, event_type='profile_sample_added', actor_id=actor_id, detail={ _audit(profile_id=saved['id'], document_id=document.id, event_type='profile_sample_added', actor_id=actor_id, detail={
'sample_role': 'annotation', 'has_table_binding': False, 'sample_role': 'annotation', 'has_table_binding': False,
}) })
if document.asset_id:
_retain_profile_sample_assets(saved['id'], asset_ids={int(document.asset_id)})
db.session.commit() db.session.commit()
return saved return saved
@@ -3505,6 +3569,8 @@ def save_draft(
# readiness audit records sample_id; assign it within this outer save transaction # readiness audit records sample_id; assign it within this outer save transaction
# before the shared evidence-freeze service is invoked. # before the shared evidence-freeze service is invoked.
db.session.flush() db.session.flush()
if annotation_document.asset_id:
_retain_profile_sample_assets(profile.id, asset_ids={int(annotation_document.asset_id)})
layout = _document_layout(annotation_document) layout = _document_layout(annotation_document)
if not any( if not any(
isinstance(item, dict) and str(item.get('table_id') or '') == visual_main_table_id isinstance(item, dict) and str(item.get('table_id') or '') == visual_main_table_id
@@ -3945,6 +4011,9 @@ def create_schema_migration_draft(
) )
db.session.add(clone) db.session.add(clone)
db.session.flush() db.session.flush()
# 迁移草稿会随源 Profile 拷贝标注/训练样本;新样本引用同一批文档资产,
# 必须为这些资产建立引用,避免它们被临时清理回收。
copied_asset_ids: set[int] = set()
for sample in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=source.id).all(): for sample in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=source.id).all():
if sample.sample_role not in {'annotation', 'training'}: if sample.sample_role not in {'annotation', 'training'}:
continue continue
@@ -3955,6 +4024,11 @@ def create_schema_migration_draft(
sample_role=sample.sample_role, sample_role=sample.sample_role,
created_by_id=actor_id, created_by_id=actor_id,
)) ))
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
if document is not None and document.asset_id:
copied_asset_ids.add(int(document.asset_id))
db.session.flush()
_retain_profile_sample_assets(clone.id, asset_ids=copied_asset_ids)
_refresh_training_sample_count(clone) _refresh_training_sample_count(clone)
# A migration is a new editable baseline, not a continuation of the source's revisions. # A migration is a new editable baseline, not a continuation of the source's revisions.
# This keeps restore and publish-check workflows scoped to the target Schema snapshot. # This keeps restore and publish-check workflows scoped to the target Schema snapshot.
@@ -4095,6 +4169,7 @@ def publish(
profile=profile, profile=profile,
draft_checksum=draft_checksum, draft_checksum=draft_checksum,
published_checksum=str(profile.checksum or ''), published_checksum=str(profile.checksum or ''),
actor_id=actor_id,
) )
profile.status = 'published' profile.status = 'published'
profile.published_by_id = actor_id profile.published_by_id = actor_id
@@ -4161,7 +4236,19 @@ def delete_draft(profile_id: int) -> None:
db.session.delete(suite) db.session.delete(suite)
if suites: if suites:
db.session.flush() db.session.flush()
# [STEP 3] ???? Profile ????????? DB CASCADE? # [STEP 3] 删除 Profile 前释放其样本资产引用;同一资产在本 Profile 内只释放一次。
asset_ids = {
int(document.asset_id)
for sample in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all()
if (document := db.session.get(ShippingOrderDocument, int(sample.document_id))) is not None and document.asset_id
}
for asset_id in asset_ids:
asset = db.session.get(FileAsset, asset_id)
if asset is not None and int(asset.reference_count or 0) > 0:
from app.services.file_assets.service import release_asset_reference
release_asset_reference(asset)
# [STEP 4] ???? Profile ????????? DB CASCADE?
db.session.delete(profile) db.session.delete(profile)
db.session.commit() db.session.commit()
@@ -49,7 +49,6 @@ from app.models import (
ShippingOrderDocument, ShippingOrderDocument,
ShippingOrderIntake, ShippingOrderIntake,
ShippingOrderTask, ShippingOrderTask,
ShippingNotice,
ShippingOrderExtraction, ShippingOrderExtraction,
) )
from app.services.shipping_notice.business_fingerprint import ( from app.services.shipping_notice.business_fingerprint import (
@@ -503,9 +502,7 @@ def persist_order_extraction_result(
if str(item.get('reason') or '') != 'layout_table_needs_review' if str(item.get('reason') or '') != 'layout_table_needs_review'
]) ])
summary = {**dynamic['header'], 'lines': dynamic['lines']} summary = {**dynamic['header'], 'lines': dynamic['lines']}
# Bill-to 是业务归属客户原文;简称只保存在 customer_matches 主数据快照中。 # Bill-to 仅保留为订单原文/识别证据,不复制为通用客户名称。
if summary.get('bill_to_customer'):
summary['customer_name'] = summary['bill_to_customer']
if dynamic['blocked_fields']: if dynamic['blocked_fields']:
blocked_set = { blocked_set = {
str(code).strip() str(code).strip()
@@ -659,7 +656,6 @@ def persist_order_extraction_result(
'findings': list(dynamic.get('findings') or []), 'findings': list(dynamic.get('findings') or []),
'diagnostic_findings': diagnostic_findings, 'diagnostic_findings': diagnostic_findings,
}, },
'customer_matches': dynamic['customer_matches'],
'missing_required_fields': assessment['missing_required_fields'], 'missing_required_fields': assessment['missing_required_fields'],
'missing_process_fields': assessment['missing_process_fields'], 'missing_process_fields': assessment['missing_process_fields'],
'process_issues': assessment['process_issues'], 'process_issues': assessment['process_issues'],
@@ -933,7 +929,7 @@ def persist_order_extraction_result(
if not target_no: if not target_no:
continue continue
target = ( target = (
db.session.query(ShippingNotice) db.session.query(ShippingOrderTask)
.filter_by(task_no=target_no, user_id=int(session.user_id)) .filter_by(task_no=target_no, user_id=int(session.user_id))
.with_for_update() .with_for_update()
.first() .first()
@@ -1107,7 +1103,7 @@ def submit_order_extraction_run_result(
} }
task_nos = sorted({ task_nos = sorted({
str(task.task_no) str(task.task_no)
for task in ShippingNotice.query.filter(ShippingNotice.id.in_(consumed_task_ids)).all() for task in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(consumed_task_ids)).all()
}) if consumed_task_ids else [] }) if consumed_task_ids else []
pending = [candidate for candidate in run_candidates if candidate.consumed_task_id is None] pending = [candidate for candidate in run_candidates if candidate.consumed_task_id is None]
result = { result = {
@@ -1348,8 +1344,8 @@ def submit_order_extraction_unit_result(
if consumed: if consumed:
task_nos = sorted({ task_nos = sorted({
str(task.task_no) str(task.task_no)
for task in ShippingNotice.query.filter( for task in ShippingOrderTask.query.filter(
ShippingNotice.id.in_([int(row.consumed_task_id) for row in consumed]) ShippingOrderTask.id.in_([int(row.consumed_task_id) for row in consumed])
).all() ).all()
}) })
result = { result = {
@@ -4,7 +4,7 @@ services/shipping_notice/order_extraction_merge.py
用途:在 HXOPS 内按稳定业务身份合并文档单元订单,并保留全部字段证据供后续裁决。 用途:在 HXOPS 内按稳定业务身份合并文档单元订单,并保留全部字段证据供后续裁决。
依赖:Run 冻结动态 Schema field_id/field_code 映射。 依赖:Run 冻结动态 Schema field_id/field_code 映射。
逻辑:同 Intake 下仅 PO 一致或 Line 的 part_number+reservation_id 一致时合并; 逻辑:同 Intake 下仅 PO 一致或 Line 的 part_number+reservation_id 一致时合并;
跨文档 Reservation 补全优先使用 part_number / customer_po_line_no(兼容历史 line_no)。 跨文档 Reservation 补全优先使用 part_number / customer_po_line_no。
阶段 2:默认 keep_primary_documents_separate=True,不同 primary_document_id 阶段 2:默认 keep_primary_documents_separate=True,不同 primary_document_id
(多 PDF)不得合并为同一 Candidate;EML 内补充仍走 order_supplement_merge。 (多 PDF)不得合并为同一 Candidate;EML 内补充仍走 order_supplement_merge。
""" """
@@ -52,7 +52,7 @@ def _single_valid_reservation(line: dict[str, Any], codes: dict[str, str]) -> st
def _completion_anchor_values(line: dict[str, Any], codes: dict[str, str]) -> dict[str, str]: def _completion_anchor_values(line: dict[str, Any], codes: dict[str, str]) -> dict[str, str]:
"""读取可用于 PDF/邮件行补全的强锚点;只接受单一原子值。""" """读取可用于 PDF/邮件行补全的强锚点;只接受单一原子值。"""
anchors: dict[str, str] = {} anchors: dict[str, str] = {}
for field_code in ('part_number', 'customer_po_line_no', 'line_no'): for field_code in ('part_number', 'customer_po_line_no'):
values = _field_values(line.get('fields'), field_code, codes) values = _field_values(line.get('fields'), field_code, codes)
if len(values) == 1: if len(values) == 1:
anchors[field_code] = next(iter(values)) anchors[field_code] = next(iter(values))
@@ -104,11 +104,11 @@ def _order_identity(order: dict[str, Any], codes: dict[str, str]) -> tuple[set[s
for value in _field_values(order.get('header_fields'), field_code, codes) for value in _field_values(order.get('header_fields'), field_code, codes)
if (normalized := normalize_atomic_po_number(value).upper()) if (normalized := normalize_atomic_po_number(value).upper())
} }
line_keys = { line_identities = {
identity for line in order.get('lines') or [] identity for line in order.get('lines') or []
if isinstance(line, dict) and (identity := _line_identity(line, codes)) is not None if isinstance(line, dict) and (identity := _line_identity(line, codes)) is not None
} }
return po_numbers, line_keys return po_numbers, line_identities
def _merge_fields(target: list[dict[str, Any]], incoming: Any) -> None: def _merge_fields(target: list[dict[str, Any]], incoming: Any) -> None:
@@ -196,7 +196,7 @@ def merge_unit_orders(
order = copy.deepcopy(raw) order = copy.deepcopy(raw)
intake_no = str(order.get('source_intake_no') or '').strip().upper() intake_no = str(order.get('source_intake_no') or '').strip().upper()
primary_document_id = order.get('primary_document_id') primary_document_id = order.get('primary_document_id')
po_numbers, line_keys = _order_identity(order, codes) po_numbers, line_identities = _order_identity(order, codes)
match = None match = None
matched_by_po = False matched_by_po = False
for candidate in merged: for candidate in merged:
@@ -212,7 +212,7 @@ def merge_unit_orders(
continue continue
candidate_pos, candidate_lines = _order_identity(candidate, codes) candidate_pos, candidate_lines = _order_identity(candidate, codes)
matched_by_po = len(po_numbers) == 1 and po_numbers == candidate_pos matched_by_po = len(po_numbers) == 1 and po_numbers == candidate_pos
if matched_by_po or bool(line_keys & candidate_lines): if matched_by_po or bool(line_identities & candidate_lines):
match = candidate match = candidate
break break
if match is None: if match is None:
@@ -372,7 +372,7 @@ def _coordinate_profile_rows(
return None return None
rows: list[dict[str, Any]] = [] rows: list[dict[str, Any]] = []
runtime_region_ids = set(select_runtime_region_ids( runtime_region_ids = set(select_runtime_region_ids(
table_regions=[region.model_dump() for region in profile.table_regions], page_no=page_no, table_regions=[_coordinate_object_mapping(region) for region in profile.table_regions], page_no=page_no,
)) ))
for region in profile.table_regions: for region in profile.table_regions:
# 标注页优先;续页仅回退到稳定的基础表区。是否真正属于明细页仍由当前页 # 标注页优先;续页仅回退到稳定的基础表区。是否真正属于明细页仍由当前页
@@ -385,7 +385,11 @@ def _coordinate_profile_rows(
relative_region = _coordinate_region_mapping(region.region) relative_region = _coordinate_region_mapping(region.region)
if relative_region is None: if relative_region is None:
return None return None
reference_page_frame = profile.reference_page_frames.get(page_no) reference_page_frames = getattr(profile, 'reference_page_frames', {})
reference_page_frame = (
reference_page_frames.get(page_no)
if isinstance(reference_page_frames, dict) else None
)
reconstruction_page_bbox = ( reconstruction_page_bbox = (
{ {
'x0': 0, 'y0': 0, 'x0': 0, 'y0': 0,
@@ -395,9 +399,10 @@ def _coordinate_profile_rows(
) )
raw_bbox = raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None raw_bbox = raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None
characters, _candidate_page_bbox = coordinate_profile_character_candidates( characters, _candidate_page_bbox = coordinate_profile_character_candidates(
table_region=region.region.model_dump(), page_size=page_size, table_region=_coordinate_object_mapping(region.region), page_size=page_size,
reference_page_frame=( reference_page_frame=(
reference_page_frame.model_dump() if reference_page_frame is not None else None _coordinate_object_mapping(reference_page_frame)
if reference_page_frame is not None else None
), ),
page_characters=page_characters if isinstance(page_characters, list) else None, page_characters=page_characters if isinstance(page_characters, list) else None,
table_characters=tables.get(table_id) if isinstance(tables.get(table_id), list) else None, table_characters=tables.get(table_id) if isinstance(tables.get(table_id), list) else None,
@@ -410,11 +415,11 @@ def _coordinate_profile_rows(
carry = initial_carry if isinstance(initial_carry, dict) and initial_carry.get('region_id') == region.region_id else {} carry = initial_carry if isinstance(initial_carry, dict) and initial_carry.get('region_id') == region.region_id else {}
for reconstructed in reconstruct_coordinate_profile_rows( for reconstructed in reconstruct_coordinate_profile_rows(
characters=[item for item in characters if isinstance(item, dict)], table_bbox=reconstruction_page_bbox, characters=[item for item in characters if isinstance(item, dict)], table_bbox=reconstruction_page_bbox,
line_layouts=[item.model_dump() for item in region.line_layouts], line_layouts=[_coordinate_object_mapping(item) for item in region.line_layouts],
table_region=relative_region, table_region=relative_region,
termination_rules=[item.model_dump() for item in region.termination_rules], termination_rules=[_coordinate_object_mapping(item) for item in region.termination_rules],
exclusion_regions=reconstruction_exclusion_regions( exclusion_regions=reconstruction_exclusion_regions(
region.model_dump(), _coordinate_object_mapping(region),
), ),
initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0), initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0),
line_start_field_code=region.line_start_field_code, line_start_field_code=region.line_start_field_code,
@@ -514,12 +519,7 @@ def _coordinate_region_mapping(value: Any) -> dict[str, float] | None:
Returns: Returns:
包含 x0/y0/x1/y1 的合法浮点坐标;缺字段、非数值或区域退化时返回 None。 包含 x0/y0/x1/y1 的合法浮点坐标;缺字段、非数值或区域退化时返回 None。
""" """
if isinstance(value, dict): raw = _coordinate_object_mapping(value)
raw = value
elif callable(getattr(value, 'model_dump', None)):
raw = value.model_dump()
else:
raw = {key: getattr(value, key, None) for key in ('x0', 'y0', 'x1', 'y1')}
if not isinstance(raw, dict): if not isinstance(raw, dict):
return None return None
try: try:
@@ -531,6 +531,22 @@ def _coordinate_region_mapping(value: Any) -> dict[str, float] | None:
return region return region
def _coordinate_object_mapping(value: Any) -> dict[str, Any]:
"""将冻结坐标契约对象转换为字典,兼容 Pydantic 与测试使用的轻量对象。
生产 Profile 使用 Pydantic ``model_dump``;运行时和回归测试也允许同字段的
轻量对象。转换失败返回空字典,后续既有坐标校验按证据不足处理,不扩大匹配范围。
"""
if isinstance(value, dict):
return value
dump = getattr(value, 'model_dump', None)
if callable(dump):
raw = dump()
return raw if isinstance(raw, dict) else {}
raw = getattr(value, '__dict__', None)
return dict(raw) if isinstance(raw, dict) else {}
def _coordinate_regions_overlap(left: dict[str, Any], right: dict[str, Any]) -> bool: def _coordinate_regions_overlap(left: dict[str, Any], right: dict[str, Any]) -> bool:
"""判断两个 PDF 绝对坐标区域是否有面积交集;无效坐标按不相交处理。""" """判断两个 PDF 绝对坐标区域是否有面积交集;无效坐标按不相交处理。"""
try: try:
@@ -881,20 +897,24 @@ def _profile_table_candidates(
profile_match=profile_match, raw_profile=raw_profile, profile_match=profile_match, raw_profile=raw_profile,
) )
profile_table_regions = [ profile_table_regions = [
item.model_dump() for item in profile.table_regions _coordinate_object_mapping(item) for item in profile.table_regions
if callable(getattr(item, 'model_dump', None))
] ]
evidence_pages = ( evidence_pages = (
(layout.get('coordinate_evidence') or {}).get('pages') or {} (layout.get('coordinate_evidence') or {}).get('pages') or {}
) )
page_size = evidence_pages.get(str(raw_table.get('page_no') or 1)) page_size = evidence_pages.get(str(raw_table.get('page_no') or 1))
reference_page_frame = profile.reference_page_frames.get(int(raw_table.get('page_no') or 1)) reference_page_frames = getattr(profile, 'reference_page_frames', {})
reference_page_frame = (
reference_page_frames.get(int(raw_table.get('page_no') or 1))
if isinstance(reference_page_frames, dict) else None
)
if not _physical_table_targets_profile_region( if not _physical_table_targets_profile_region(
raw_table=raw_table, raw_table=raw_table,
table_regions=profile_table_regions, table_regions=profile_table_regions,
page_size=page_size if isinstance(page_size, dict) else None, page_size=page_size if isinstance(page_size, dict) else None,
reference_page_frame=( reference_page_frame=(
reference_page_frame.model_dump() if reference_page_frame is not None else None _coordinate_object_mapping(reference_page_frame)
if reference_page_frame is not None else None
), ),
coordinate_transform=coordinate_transform, coordinate_transform=coordinate_transform,
): ):
@@ -934,14 +954,17 @@ def _profile_table_candidates(
except (TypeError, ValueError): except (TypeError, ValueError):
issues.append('order_profile_snapshot_invalid') issues.append('order_profile_snapshot_invalid')
continue continue
if fixed_rows is None or adaptive_rows is None or dynamic_rows is None: # 虚拟空页(无业务表)不能把已成功的目标表覆盖成失败;None 与空列表
issues.append('order_profile_coordinate_reconstruction_unavailable') # 同样视为“无行”,且必须在该判断之前处理,否则空虚拟页会被
continue # is None 分支误判为行重建失败而整单阻断。
if _virtual_page_without_rows_is_nonblocking( if _virtual_page_without_rows_is_nonblocking(
raw_table=raw_table, fixed_rows=fixed_rows, adaptive_rows=adaptive_rows, raw_table=raw_table, fixed_rows=fixed_rows, adaptive_rows=adaptive_rows,
dynamic_rows=dynamic_rows, dynamic_rows=dynamic_rows,
): ):
continue continue
if fixed_rows is None or adaptive_rows is None or dynamic_rows is None:
issues.append('order_profile_coordinate_reconstruction_unavailable')
continue
strategy = resolve_runtime_parse_strategy( strategy = resolve_runtime_parse_strategy(
page_glyphs=(layout.get('coordinate_evidence') or {}).get('page_glyphs') or {}, page_glyphs=(layout.get('coordinate_evidence') or {}).get('page_glyphs') or {},
fixed_rows=fixed_rows, adaptive_rows=adaptive_rows, fixed_rows=fixed_rows, adaptive_rows=adaptive_rows,
@@ -1317,7 +1317,13 @@ def _unresolved_review_document_count(
def _current_non_terminal_review_cases(run: ShippingOrderProcessingRun) -> list[ShippingOrderReviewCase]: def _current_non_terminal_review_cases(run: ShippingOrderProcessingRun) -> list[ShippingOrderReviewCase]:
"""返回该 Run 产出的文件 Stream 当前非终态 Case;Run 的历史 Case 不参与工作台统计。""" """返回该 Run 产出的文件 Stream 当前非终态 Case;Run 的历史 Case 不参与工作台统计。
转瞬/未持久化 Run(id=None,如纯单元投影)不存在落库 Case,按空集处理,
与 _duplicate_projection_by_document / _pending_order_facts 的 run.id 防空一致。
"""
if getattr(run, 'id', None) is None:
return []
return ( return (
db.session.query(ShippingOrderReviewCase) db.session.query(ShippingOrderReviewCase)
.join( .join(
@@ -26,7 +26,10 @@ _PURPOSE_BY_CAPABILITY = {
def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | None = None) -> dict[str, str]: def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | None = None) -> dict[str, str]:
"""读取冻结策略能力与字段 ID,防止 Schema 或策略后续发布重解释任务。""" """读取冻结策略能力与字段 ID,防止 Schema 或策略后续发布重解释任务。"""
source_notice = _source_notice_for_order_facts(task) source_notice = _source_notice_for_order_facts(task)
snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None from app.models import ShippingOrderTask
owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None: if snapshot is None:
raise ValueError('任务没有可用于履约的冻结订单快照') raise ValueError('任务没有可用于履约的冻结订单快照')
rule = (snapshot.rule_versions_json or {}).get('fulfillment_rule') rule = (snapshot.rule_versions_json or {}).get('fulfillment_rule')
@@ -2,10 +2,10 @@
services/shipping_notice/order_freeze_service.py services/shipping_notice/order_freeze_service.py
用途:将已复核的动态订单解析冻结为强类型履约快照。 用途:将已复核的动态订单解析冻结为强类型履约快照。
依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingNotice、 依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingOrderTask、
standard_field_registry(投影列)、audit_service、统一 AppError。 standard_field_registry(投影列)、audit_service、统一 AppError。
逻辑:Candidate/Extraction 阶段可继续保留动态证据;本服务通过门禁后一次写入按 field_id 冻结的 Snapshot; 逻辑:Candidate/Extraction 阶段可继续保留动态证据;本服务通过门禁后一次写入按 field_id 冻结的 Snapshot;
冻结时固化 derivation_rules 快照与 field_lineage;库存、导出和上传后续阶段只读取该快照。 冻结时固化字段血缘;库存、导出和上传后续阶段只读取该快照。
""" """
from __future__ import annotations from __future__ import annotations
@@ -22,11 +22,10 @@ from app.models import (
ShippingOrderFieldObservation, ShippingOrderFieldObservation,
ShippingOrderFieldValue, ShippingOrderFieldValue,
ShippingOrderLine, ShippingOrderLine,
ShippingOrderCustomerMatch,
ShippingOrderReviewEvent, ShippingOrderReviewEvent,
ShippingOrderSnapshot, ShippingOrderSnapshot,
ShippingOrderSnapshotLine, ShippingOrderSnapshotLine,
ShippingNotice, ShippingOrderTask,
ShippingOrderDocument, ShippingOrderDocument,
) )
from app.services.shipping_notice.audit_service import append_shipping_audit_event from app.services.shipping_notice.audit_service import append_shipping_audit_event
@@ -56,7 +55,7 @@ DATE_FIELDS = frozenset({'order_date', 'required_date', 'requested_receipt_date'
def freeze_order_snapshot( def freeze_order_snapshot(
task: ShippingNotice, task: ShippingOrderTask,
*, *,
actor_id: int | None, actor_id: int | None,
expected_order_data_version: int, expected_order_data_version: int,
@@ -88,9 +87,9 @@ def freeze_order_snapshot(
# query 默认带 shipping_case 的 joinedload;PostgreSQL 不允许对外连接的空值端 # query 默认带 shipping_case 的 joinedload;PostgreSQL 不允许对外连接的空值端
# 执行 FOR UPDATE。仅锁定正式任务主表,避免冻结在已确认但关联 Case 可为空时失败。 # 执行 FOR UPDATE。仅锁定正式任务主表,避免冻结在已确认但关联 Case 可为空时失败。
locked_task = ( locked_task = (
ShippingNotice.query ShippingOrderTask.query
.filter_by(id=task.id) .filter_by(id=task.id)
.with_for_update(of=ShippingNotice) .with_for_update(of=ShippingOrderTask)
.one() .one()
) )
if locked_task.order_snapshot_id: if locked_task.order_snapshot_id:
@@ -110,7 +109,7 @@ def freeze_order_snapshot(
) )
extraction = _accepted_extraction(task) extraction = _accepted_extraction(task)
policy, configs = _policy_configs(extraction) policy, configs = _policy_configs(extraction)
customer_match = _confirmed_ordering_customer(extraction) customer_resolution = _confirmed_ordering_customer(task)
from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness
assert_freeze_readiness( assert_freeze_readiness(
task=task, task=task,
@@ -127,23 +126,11 @@ def freeze_order_snapshot(
task_id=task.id, task_id=task.id,
extraction_id=extraction.id, extraction_id=extraction.id,
schema_version_id=extraction.schema_version_id, schema_version_id=extraction.schema_version_id,
customer_id=customer_match.customer_id, customer_id=customer_resolution.confirmed_customer_id,
customer_short_code_snapshot=customer_match.customer_short_code_snapshot, customer_short_code_snapshot=_confirmed_customer_short_code(customer_resolution),
order_data_version=actual_version, order_data_version=actual_version,
rule_versions_json={ rule_versions_json={
**dict(rule_versions or {}), **dict(rule_versions or {}),
'derivation_rules_snapshot': list(
((extraction.schema_version.definition_json or {}) if extraction.schema_version else {}).get('derivation_rules')
or []
),
'derivation_rules_checksum': (
((extraction.normalized_result_json or {}) if isinstance(extraction.normalized_result_json, dict) else {}).get(
'derivation_rules_checksum'
)
or ((extraction.schema_version.definition_json or {}) if extraction.schema_version else {}).get(
'derivation_rules_checksum'
)
),
'fulfillment_rule': { 'fulfillment_rule': {
'code': policy['rule_code'], 'code': policy['rule_code'],
'checksum': _fixed_rule_checksum(), 'checksum': _fixed_rule_checksum(),
@@ -151,12 +138,12 @@ def freeze_order_snapshot(
'required_field_ids': {code: config['field_id'] for code, config in configs.items()}, 'required_field_ids': {code: config['field_id'] for code, config in configs.items()},
}, },
'ordering_customer': { 'ordering_customer': {
'match_id': customer_match.id, 'resolution_id': customer_resolution.id,
'identity_fingerprint': customer_match.identity_fingerprint, 'identity_rule_set_checksum': customer_resolution.identity_rule_set_checksum,
'identity_rule_version': customer_match.identity_rule_version, 'identity_rule_set_version': customer_resolution.identity_rule_set_version,
'resolution_method': customer_match.resolution_method, 'confirmation_method': customer_resolution.confirmation_method,
'confirmed_by_id': customer_match.confirmed_by_id, 'confirmed_by_id': customer_resolution.confirmed_by_id,
'confirmed_at': customer_match.confirmed_at.isoformat() if customer_match.confirmed_at else None, 'confirmed_at': customer_resolution.confirmed_at.isoformat() if customer_resolution.confirmed_at else None,
}, },
}, },
source_manifest_json={ source_manifest_json={
@@ -174,17 +161,19 @@ def freeze_order_snapshot(
) )
db.session.add(snapshot) db.session.add(snapshot)
db.session.flush() db.session.flush()
for position, source in enumerate(line_values): for position, source in enumerate(line_values, start=1):
# 订单项次是系统项次,不采信客户 PO 行号或解析派生值;冻结后按本订单固定为 1..N。
source = dict(source)
source['line_no'] = position
db.session.add(ShippingOrderSnapshotLine( db.session.add(ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, snapshot_id=snapshot.id,
position=position, position=position - 1,
field_values_json=_field_id_values(source, configs), field_values_json=_field_id_values(source, configs),
**_project_values(source, LINE_FIELD_PROJECTIONS), **_project_values(source, LINE_FIELD_PROJECTIONS),
)) ))
db.session.flush() db.session.flush()
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot # Snapshot 只是冻结订单事实;ShippingNoticeLine 属于正式发货通知,
# 必须在库存确认通过或人工放行后创建,不能在冻结阶段提前生成。
replace_notice_lines_from_snapshot(notice_id=int(task.id), snapshot=snapshot)
task.order_snapshot_id = snapshot.id task.order_snapshot_id = snapshot.id
ShippingOrderReviewEvent.query.filter_by( ShippingOrderReviewEvent.query.filter_by(
task_id=task.id, task_id=task.id,
@@ -202,13 +191,11 @@ def freeze_order_snapshot(
result='success', result='success',
metadata={ metadata={
'snapshot_id': snapshot.id, 'snapshot_id': snapshot.id,
'derivation_rules_checksum': (snapshot.rule_versions_json or {}).get('derivation_rules_checksum'),
'schema_version_id': extraction.schema_version_id, 'schema_version_id': extraction.schema_version_id,
}, },
after={ after={
'task_no': task.task_no, 'task_no': task.task_no,
'schema_version_id': extraction.schema_version_id, 'schema_version_id': extraction.schema_version_id,
'derivation_rules_checksum': (snapshot.rule_versions_json or {}).get('derivation_rules_checksum'),
}, },
) )
db.session.flush() db.session.flush()
@@ -270,13 +257,13 @@ def _source_manifest(*, extraction: ShippingOrderExtraction, policy: Any) -> dic
} }
def assert_task_order_is_editable(task: ShippingNotice) -> None: def assert_task_order_is_editable(task: ShippingOrderTask) -> None:
"""拒绝冻结后对 Candidate/Extraction 的任何直接编辑,防止快照与解析事实漂移。""" """拒绝冻结后对 Candidate/Extraction 的任何直接编辑,防止快照与解析事实漂移。"""
if task.order_snapshot_id: if task.order_snapshot_id:
raise ConflictError('Frozen order snapshot cannot be edited', code='SHIPPING.ORDER_SNAPSHOT_FROZEN') raise ConflictError('Frozen order snapshot cannot be edited', code='SHIPPING.ORDER_SNAPSHOT_FROZEN')
def _accepted_extraction(task: ShippingNotice) -> ShippingOrderExtraction: def _accepted_extraction(task: ShippingOrderTask) -> ShippingOrderExtraction:
"""读取当前已接受 Extraction;冻结绝不回读旧版本或 Task JSON 投影。""" """读取当前已接受 Extraction;冻结绝不回读旧版本或 Task JSON 投影。"""
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) if task.current_order_extraction_id else None extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) if task.current_order_extraction_id else None
if extraction is None or extraction.status != 'accepted': if extraction is None or extraction.status != 'accepted':
@@ -284,12 +271,14 @@ def _accepted_extraction(task: ShippingNotice) -> ShippingOrderExtraction:
return extraction return extraction
def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> ShippingOrderCustomerMatch: def _confirmed_ordering_customer(task: ShippingOrderTask) -> Any:
"""只接受已人工确认的 Bill-to 订购客户,禁止由冻结请求自由指定 customer_id。""" """只接受正式客户识别结果,禁止由任一订单字段或冻结请求指定客户。"""
row = ShippingOrderCustomerMatch.query.filter_by(extraction_id=extraction.id, role='bill_to').one_or_none() from app.services.shipping_notice.customer_resolution_service import resolution_for_task
row = resolution_for_task(task)
if ( if (
row is None or row.status != 'confirmed' or row.customer_id is None row is None or row.status != 'confirmed' or row.confirmed_customer_id is None
or not row.customer_short_code_snapshot or not row.identity_fingerprint or not row.identity_rule_version or not row.evidence_json or not row.identity_rule_set_checksum
): ):
raise ValidationError( raise ValidationError(
'Ordering customer must be confirmed before freezing', 'Ordering customer must be confirmed before freezing',
@@ -298,6 +287,14 @@ def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> Shippin
return row return row
def _confirmed_customer_short_code(resolution: Any) -> str:
"""从已确认标准客户读取简称;订单原文和 bill_to 不得提供业务简称。"""
from app.models import ShippingCustomer
customer = db.session.get(ShippingCustomer, int(resolution.confirmed_customer_id))
return str(getattr(customer, 'short_code', None) or '')
def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]: def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
"""按固定履约契约验证冻结字段,Schema 仅承担字段目录职责。""" """按固定履约契约验证冻结字段,Schema 仅承担字段目录职责。"""
from app.services.shipping_notice.fulfillment_policy_registry import ( from app.services.shipping_notice.fulfillment_policy_registry import (
@@ -5,10 +5,10 @@ services/shipping_notice/order_review_auto_progress_coordinator.py
依赖:order_review_customer_service、order_review_draft_service(延迟)、 依赖:order_review_customer_service、order_review_draft_service(延迟)、
order_stp_auto_create_service(延迟)、candidate_qualification_service、 order_stp_auto_create_service(延迟)、candidate_qualification_service、
fulfillment_audit、ShippingCustomerShadowResolution / fulfillment_audit、ShippingCustomerShadowResolution /
ShippingOrderCustomerMatch / ShippingOrderReviewCase / ShippingOrderProcessingRun。 ShippingOrderReviewCase / ShippingOrderProcessingRun。
逻辑:提供 Run 级批量协调(reconcile_run_review_cases_for_auto_progress)和 逻辑:提供 Run 级批量协调(reconcile_run_review_cases_for_auto_progress)和
单 Case 级协调(reconcile_single_case_for_auto_progress)两层入口; 单 Case 级协调(reconcile_single_case_for_auto_progress)两层入口;
客户协调仅在 shadow.status=unique_candidate 且未 resolve 时自动确认 bill_to; 客户协调仅在识别结果唯一命中且未确认时自动确认客户;
所有入口均不主动 commit,由调用方统一控制事务;Run 级循环单 Case 异常局部 rollback。 所有入口均不主动 commit,由调用方统一控制事务;Run 级循环单 Case 异常局部 rollback。
注意:order_stp_auto_create_service 与 order_review_draft_service 均不在顶层 import, 注意:order_stp_auto_create_service 与 order_review_draft_service 均不在顶层 import,
避免 circular import(stp 末尾顶层 import 本模块,draft 顶层 import 本模块)。 避免 circular import(stp 末尾顶层 import 本模块,draft 顶层 import 本模块)。
@@ -23,19 +23,15 @@ from app import db
from app.models import ( from app.models import (
ShippingCustomerShadowResolution, ShippingCustomerShadowResolution,
ShippingOrderCandidate, ShippingOrderCandidate,
ShippingOrderCustomerMatch,
ShippingOrderProcessingRun, ShippingOrderProcessingRun,
ShippingOrderReviewCase, ShippingOrderReviewCase,
ShippingOrderReviewStream, ShippingOrderReviewStream,
) )
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.order_review_customer_service import ( from app.services.shipping_notice.order_review_customer_service import (
_header_from_case,
_resolve_extraction_for_case,
confirm_order_customer_match,
refresh_order_customer_matches,
resolve_review_case_customer_resolved, resolve_review_case_customer_resolved,
) )
from app.services.shipping_notice.customer_resolution_service import confirm_customer_resolution
from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref
# 注意:validate_draft 与 ensure_stp_auto_create_for_case 均不在顶层 import, # 注意:validate_draft 与 ensure_stp_auto_create_for_case 均不在顶层 import,
@@ -73,7 +69,7 @@ def _customer_step_for_case(
trigger: str, trigger: str,
) -> tuple[str, dict[str, Any] | None]: ) -> tuple[str, dict[str, Any] | None]:
""" """
单 Case 客户协调内部步骤:shadow 唯一命中时自动确认 bill_to。 单 Case 客户协调内部步骤:识别结果唯一命中时自动确认客户。
Args: Args:
case: 复核 Case。 case: 复核 Case。
@@ -105,45 +101,20 @@ def _customer_step_for_case(
if already_resolved: if already_resolved:
return 'skipped', {'reason': 'customer_already_resolved'} return 'skipped', {'reason': 'customer_already_resolved'}
# [STEP 1-3] 提取 order_extraction(Candidate 关联优先,否则 Run 内最新) # [STEP 1-3] 将唯一指纹候选确认到正式识别结果;不创建或读取订单角色投影。
extraction = _resolve_extraction_for_case(case)
if extraction is None:
return 'failed', {'reason': 'extraction_missing'}
# [STEP 1-4] 若无 bill_to match 行,先按当前头字段刷新
bill_to_exists = (
ShippingOrderCustomerMatch.query
.filter_by(extraction_id=int(extraction.id), role='bill_to')
.first()
is not None
)
if not bill_to_exists:
try:
refresh_order_customer_matches(extraction, _header_from_case(case))
except Exception as exc: # noqa: BLE001
_LOGGER.warning(
'refresh_order_customer_matches failed case_no=%s err=%s',
case.case_no, str(exc)[:200],
)
return 'failed', {'reason': 'refresh_matches_failed', 'error': str(exc)[:200]}
# [STEP 1-5] 自动确认 bill_to 到 top_customer_id
top_customer_id = int(shadow.top_customer_id) top_customer_id = int(shadow.top_customer_id)
confirm_reason = '抽取协调器-客户指纹唯一命中自动确认' confirm_reason = '抽取协调器-客户指纹唯一命中自动确认'
try: try:
confirm_order_customer_match( confirm_customer_resolution(
int(extraction.id), candidate,
role='bill_to',
customer_id=top_customer_id, customer_id=top_customer_id,
site_id=None,
actor_id=None, actor_id=None,
method='auto_rule',
reason=confirm_reason, reason=confirm_reason,
# 保存校验入口需将客户确认、Draft 校验与后续 Gate/STP 写入作为同一事务提交。
commit=False,
) )
except Exception as exc: # noqa: BLE001 except Exception as exc: # noqa: BLE001
_LOGGER.warning( _LOGGER.warning(
'confirm_order_customer_match failed case_no=%s err=%s', 'confirm_customer_resolution failed case_no=%s err=%s',
case.case_no, str(exc)[:200], case.case_no, str(exc)[:200],
) )
return 'failed', {'reason': 'confirm_match_failed', 'error': str(exc)[:200]} return 'failed', {'reason': 'confirm_match_failed', 'error': str(exc)[:200]}
@@ -165,7 +136,7 @@ def _customer_step_for_case(
'candidate_id': int(candidate.id) if candidate is not None else None, 'candidate_id': int(candidate.id) if candidate is not None else None,
'shadow_status': 'unique_candidate', 'shadow_status': 'unique_candidate',
'customer_id': top_customer_id, 'customer_id': top_customer_id,
'extraction_id': int(extraction.id), 'extraction_id': getattr(candidate, 'order_extraction_id', None),
'trigger': str(trigger)[:64], 'trigger': str(trigger)[:64],
'reason': confirm_reason, 'reason': confirm_reason,
}, },
@@ -177,7 +148,7 @@ def _customer_step_for_case(
return 'auto_confirmed', { return 'auto_confirmed', {
'customer_id': top_customer_id, 'customer_id': top_customer_id,
'extraction_id': int(extraction.id), 'extraction_id': getattr(candidate, 'order_extraction_id', None),
} }
@@ -397,7 +368,7 @@ def reconcile_run_review_cases_for_auto_progress(
}) })
continue continue
# [STEP 1 客户协调] shadow unique_candidate 且未 resolve → 自动确认 bill_to # [STEP 1 客户协调] shadow unique_candidate 且未 resolve → 自动确认标准客户
customer_status, customer_meta = _customer_step_for_case( customer_status, customer_meta = _customer_step_for_case(
case=case, trigger='run_reconcile', case=case, trigger='run_reconcile',
) )
@@ -3,21 +3,20 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py
用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。 用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、order_task_service、 依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、order_task_service、
stp_inventory_freeze、progress_audit_contract.ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE、
candidate_qualification_service、customer_auto_resolution、fulfillment_audit、 candidate_qualification_service、customer_auto_resolution、fulfillment_audit、
order_review_progress_bridge、workflow_ledger_service、 order_review_progress_bridge、workflow_ledger_service、
queue_service.enqueue_shipping_notice_job、process_gate_bridge。 queue_service.enqueue_shipping_notice_job、process_gate_bridge。
逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,冻结行级库存源候选与 逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,固化可自动确认的客户;
可自动确认的客户;库存源未唯一确定时按硬门禁拒绝建单并回写 OT stage= 物化人工 Candidate 时先写入客户已确认事实再执行履约门禁;
inventory_source_resolving;物化人工 Candidate 时先写入客户已确认事实再执行履约门禁;
确认建单前锁定 case.candidate_id 对应 OT:未消费 OT 受控换绑人工 Candidate; 确认建单前锁定 case.candidate_id 对应 OT:未消费 OT 受控换绑人工 Candidate;
已消费 OT 保留历史并为后续波次创建稳定子 OT;同步 Case 当前 Candidate; 已消费 OT 保留历史并为后续波次创建稳定子 OT;同步 Case 当前 Candidate;
缺 OT 则 fail-closed 回滚;禁止 upsert 到 Run 根号串单; 缺 OT 则 fail-closed 回滚;禁止 upsert 到 Run 根号串单;
物化 accepted Extraction(保留派生 field_lineage);建单前再次校验客户确认并 物化 accepted Extraction(保留字段 field_lineage);建单前再次校验客户确认并
持久化 Candidate Qualification 快照;客户未确认拒绝建单;同 Case 既有波次 Task 持久化 Candidate Qualification 快照;客户未确认拒绝建单;同 Case 既有波次 Task
豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束; 豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束;
新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照 新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照
Task 推入库存/RPA; Task 推入库存/RPA。库存源候选的裁决/冻结不在确认流程内,由确认后 OT 进入的
正式 inventory_source_routing Gate 负责;
成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至 成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至
building_order(不关闭);同步 Process Execution 推进至 task_creation 通过, building_order(不关闭);同步 Process Execution 推进至 task_creation 通过,
避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox), 避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox),
@@ -50,8 +49,7 @@ from app.models import (
ShippingOrderReviewConfirmedRevision, ShippingOrderReviewConfirmedRevision,
ShippingOrderReviewDraft, ShippingOrderReviewDraft,
ShippingOrderReviewWaveLine, ShippingOrderReviewWaveLine,
ShippingOrderCustomerMatch, ShippingOrderTask,
ShippingNotice,
) )
from app.services.shipping_notice.batch_create_idempotency import ( from app.services.shipping_notice.batch_create_idempotency import (
acquire_notice_create_locks, acquire_notice_create_locks,
@@ -68,9 +66,6 @@ from app.services.shipping_notice.order_review_draft_service import (
build_confirmable_draft_summary, build_confirmable_draft_summary,
draft_has_unaccepted_llm_suggestions, draft_has_unaccepted_llm_suggestions,
) )
from app.services.shipping_notice.progress_audit_contract import (
ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE,
)
from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_review_projection import serialize_review_case
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
@@ -221,13 +216,12 @@ def _json_value(value: Any) -> Any:
def _source_extraction_lineage(case: ShippingOrderReviewCase) -> tuple[list[dict[str, Any]], str | None]: def _source_extraction_lineage(case: ShippingOrderReviewCase) -> tuple[list[dict[str, Any]], str | None]:
""" """
读取机器解析 Extraction / Unit 上的派生血缘与规则校验和。 读取机器解析 Extraction / Unit 上的字段血缘。
核心逻辑:优先 Candidate.order_extraction_id → normalized_result_json; 核心逻辑:优先 Candidate.order_extraction_id → normalized_result_json;
否则回退 Unit.result_json。供确认物化 Extraction 写入冻结可追溯快照。 否则回退 Unit.result_json。供确认物化 Extraction 写入冻结可追溯快照。
""" """
rows: list[dict[str, Any]] = [] rows: list[dict[str, Any]] = []
checksum: str | None = None
candidate = db.session.get(ShippingOrderCandidate, case.candidate_id) if case.candidate_id else None candidate = db.session.get(ShippingOrderCandidate, case.candidate_id) if case.candidate_id else None
extraction_id = getattr(candidate, 'order_extraction_id', None) if candidate is not None else None extraction_id = getattr(candidate, 'order_extraction_id', None) if candidate is not None else None
if extraction_id: if extraction_id:
@@ -236,17 +230,9 @@ def _source_extraction_lineage(case: ShippingOrderReviewCase) -> tuple[list[dict
extraction.normalized_result_json, dict, extraction.normalized_result_json, dict,
) else {} ) else {}
rows = [item for item in (normalized.get('field_lineage') or []) if isinstance(item, dict)] rows = [item for item in (normalized.get('field_lineage') or []) if isinstance(item, dict)]
raw_checksum = normalized.get('derivation_rules_checksum')
checksum = str(raw_checksum) if raw_checksum else None
if not checksum and extraction is not None and extraction.schema_version is not None:
definition = extraction.schema_version.definition_json or {}
if isinstance(definition, dict) and definition.get('derivation_rules_checksum'):
checksum = str(definition.get('derivation_rules_checksum'))
if not rows and case.unit is not None and isinstance(case.unit.result_json, dict): if not rows and case.unit is not None and isinstance(case.unit.result_json, dict):
rows = [item for item in (case.unit.result_json.get('field_lineage') or []) if isinstance(item, dict)] rows = [item for item in (case.unit.result_json.get('field_lineage') or []) if isinstance(item, dict)]
if not checksum and case.unit.result_json.get('derivation_rules_checksum'): return rows, None
checksum = str(case.unit.result_json.get('derivation_rules_checksum'))
return rows, checksum
def _confirmation_field_lineage( def _confirmation_field_lineage(
@@ -255,64 +241,38 @@ def _confirmation_field_lineage(
summary_lines: list[dict[str, Any]], summary_lines: list[dict[str, Any]],
) -> tuple[list[dict[str, Any]], str | None]: ) -> tuple[list[dict[str, Any]], str | None]:
""" """
将源解析血缘按行位映射到确认后 Extraction 的 review-* line_key。 将源解析血缘按行位映射到确认后 Extraction 的 draft_line_id。
核心逻辑:按草稿行顺序对齐;若该行 line_no 已被人工覆盖,则改写为 manual_override 血缘。 核心逻辑:按草稿行顺序对齐字段血缘;系统项次不参与人工覆盖。
""" """
source_rows, checksum = _source_extraction_lineage(case) source_rows, checksum = _source_extraction_lineage(case)
draft_lines = [ draft_lines = [
item for item in (case.current_draft.lines_json or []) item for item in (case.current_draft.lines_json or [])
if isinstance(item, dict) if isinstance(item, dict)
] ]
line_no_field_id = None
run = case.run
definition = (
(run.input_snapshot_json or {}).get('schema', {}).get('definition', {})
if run is not None and isinstance(run.input_snapshot_json, dict) else {}
)
for item in definition.get('fields') or []:
if (
isinstance(item, dict)
and str(item.get('field_code') or '') == 'line_no'
and str(item.get('scope') or '') == 'line'
):
line_no_field_id = str(item.get('field_id') or '') or None
break
by_key: dict[str, list[dict[str, Any]]] = {} by_key: dict[str, list[dict[str, Any]]] = {}
for item in source_rows: for item in source_rows:
key = str(item.get('line_key') or '').strip() key = str(item.get('draft_line_id') or '').strip()
if key: if key:
by_key.setdefault(key, []).append(item) by_key.setdefault(key, []).append(item)
ordered_keys: list[str] = [] ordered_keys: list[str] = []
for item in source_rows: for item in source_rows:
key = str(item.get('line_key') or '').strip() key = str(item.get('draft_line_id') or '').strip()
if key and key not in ordered_keys: if key and key not in ordered_keys:
ordered_keys.append(key) ordered_keys.append(key)
remapped: list[dict[str, Any]] = [] remapped: list[dict[str, Any]] = []
for position, draft_line in enumerate(draft_lines): for position, draft_line in enumerate(draft_lines):
new_key = f'review-{position + 1}' new_key = f'review-{position + 1}'
old_key = str(draft_line.get('line_key') or '').strip() old_key = str(draft_line.get('draft_line_id') or '').strip()
source_items = list(by_key.get(old_key) or []) source_items = list(by_key.get(old_key) or [])
if not source_items and position < len(ordered_keys): if not source_items and position < len(ordered_keys):
source_items = list(by_key.get(ordered_keys[position]) or []) source_items = list(by_key.get(ordered_keys[position]) or [])
values = draft_line.get('values') if isinstance(draft_line.get('values'), dict) else {}
override_entry = values.get(line_no_field_id) if line_no_field_id else None
line_no_overridden = (
isinstance(override_entry, dict)
and str(override_entry.get('source') or '') == 'manual_override'
)
summary_line = summary_lines[position] if position < len(summary_lines) else {}
for item in source_items: for item in source_items:
row = dict(item) row = dict(item)
row['line_key'] = new_key row['draft_line_id'] = new_key
if str(row.get('field_code') or '') == 'line_no' and line_no_overridden:
row['value_source'] = 'manual_override'
row['after_value'] = summary_line.get('line_no')
row['skip_reason'] = None
remapped.append(row) remapped.append(row)
return remapped, checksum return remapped, checksum
@@ -325,23 +285,16 @@ def _build_confirmation_normalized_result(
""" """
组装确认后 Extraction.normalized_result_json。 组装确认后 Extraction.normalized_result_json。
核心逻辑:保留确认摘要的 header/lines,并附加源解析 field_lineage 与派生规则校验和, 核心逻辑:保留确认摘要的 header/lines,并附加源解析 field_lineage,
供冻结快照写入可追溯项次派生来源。 供冻结快照写入可追溯字段来源。
""" """
header_values = {key: value for key, value in summary.items() if key != 'lines'} header_values = {key: value for key, value in summary.items() if key != 'lines'}
lines = [dict(item) for item in (summary.get('lines') or []) if isinstance(item, dict)] lines = [dict(item) for item in (summary.get('lines') or []) if isinstance(item, dict)]
lineage, checksum = _confirmation_field_lineage(case, summary_lines=lines) lineage, _checksum = _confirmation_field_lineage(case, summary_lines=lines)
if not checksum and case.current_draft is not None:
from app.models import ShippingOrderSchemaVersion
version = db.session.get(ShippingOrderSchemaVersion, int(case.current_draft.schema_version_id))
definition = (version.definition_json or {}) if version is not None else {}
if isinstance(definition, dict) and definition.get('derivation_rules_checksum'):
checksum = str(definition.get('derivation_rules_checksum'))
return { return {
'header': header_values, 'header': header_values,
'lines': lines, 'lines': lines,
'field_lineage': lineage, 'field_lineage': lineage,
'derivation_rules_checksum': checksum,
} }
@@ -363,9 +316,9 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
for item in configs for item in configs
if str(item.get('scope') or '') == 'line' and item.get('field_code') if str(item.get('scope') or '') == 'line' and item.get('field_code')
} }
# `line_key` is Draft-only identity used by wave selection and lineage remapping. # `draft_line_id` is Draft-only identity used by wave selection and lineage remapping.
# It is not a Schema business field and must never be materialized as one. # It is not a Schema business field and must never be materialized as one.
internal_line_fields = {'line_key'} internal_line_fields = {'draft_line_id'}
unknown_line_fields = sorted({ unknown_line_fields = sorted({
str(key) str(key)
for line in summary.get('lines') or [] for line in summary.get('lines') or []
@@ -413,7 +366,12 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
**_field_value_columns(value, str(config.get('value_type') or 'string')), **_field_value_columns(value, str(config.get('value_type') or 'string')),
)) ))
for position, values in enumerate(summary.get('lines') or []): for position, values in enumerate(summary.get('lines') or []):
line = ShippingOrderLine(extraction_id=int(extraction.id), position=position, line_key=f'review-{position + 1}') line = ShippingOrderLine(
extraction_id=int(extraction.id),
position=position,
line_no=position + 1,
draft_line_id=f'review-{position + 1}',
)
db.session.add(line) db.session.add(line)
db.session.flush() db.session.flush()
for config in configs: for config in configs:
@@ -433,59 +391,33 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
extraction_id=int(extraction.id), line_id=int(line.id), field_id=field_id, decision_id=int(decision.id), extraction_id=int(extraction.id), line_id=int(line.id), field_id=field_id, decision_id=int(decision.id),
**_field_value_columns(value, str(config.get('value_type') or 'string')), **_field_value_columns(value, str(config.get('value_type') or 'string')),
)) ))
_inherit_confirmed_customer_match(case=case, extraction=extraction) _inherit_confirmed_customer_resolution(case=case, extraction=extraction)
return extraction return extraction
def _inherit_confirmed_customer_match( def _inherit_confirmed_customer_resolution(
*, *,
case: ShippingOrderReviewCase, case: ShippingOrderReviewCase,
extraction: ShippingOrderExtraction, extraction: ShippingOrderExtraction,
) -> None: ) -> None:
""" """
把当前 Case 原 Extraction 已确认的 Bill-to 客户复制到人工确认 Extraction。 人工确认产生新 Extraction 时保留同一 Candidate 的正式客户识别确认事实。
核心逻辑:仅复制当前 PDF Candidate 的 confirmed Bill-to 行;没有确认事实时保持空, 核心逻辑:客户识别结果通过 Candidate 稳定关联,不复制或伪造 bill_to 角色行;
后续建单前客户门禁仍会 fail-closed。 新 Extraction 只改变订单字段版本,后续 Gate 继续读取该 Candidate 的确认结果。
Args: Args:
case: 当前复核 Case。 case: 当前复核 Case。
extraction: 新建的人工确认 Extraction。 extraction: 新建的人工确认 Extraction。
""" """
del extraction
if not case.candidate_id: if not case.candidate_id:
return return
source_candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) from app.services.shipping_notice.customer_resolution_service import resolution_for_task
source_extraction_id = getattr(source_candidate, 'order_extraction_id', None) if source_candidate else None
if source_extraction_id is None: resolution = resolution_for_task(db.session.get(ShippingOrderCandidate, int(case.candidate_id)))
if resolution is not None and resolution.status == 'confirmed':
return return
source = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(source_extraction_id),
role='bill_to',
status='confirmed',
).first()
if source is None or source.customer_id is None:
return
db.session.add(ShippingOrderCustomerMatch(
extraction_id=int(extraction.id),
role='bill_to',
raw_name=source.raw_name,
normalized_name=source.normalized_name,
source_system=source.source_system,
external_code=source.external_code,
identity_fingerprint=source.identity_fingerprint,
identity_rule_version=source.identity_rule_version,
identity_components_json=copy.deepcopy(source.identity_components_json or {}),
status='confirmed',
customer_id=int(source.customer_id),
site_id=int(source.site_id) if source.site_id is not None else None,
customer_name_snapshot=source.customer_name_snapshot,
customer_short_code_snapshot=source.customer_short_code_snapshot,
candidates_json=copy.deepcopy(source.candidates_json or []),
resolution_method=source.resolution_method or 'review_case_inherited',
confirmation_reason=source.confirmation_reason,
confirmed_by_id=source.confirmed_by_id,
confirmed_at=source.confirmed_at or datetime.utcnow(),
))
def _workflow_refs_for_case(case: ShippingOrderReviewCase) -> dict[str, str | None]: def _workflow_refs_for_case(case: ShippingOrderReviewCase) -> dict[str, str | None]:
@@ -729,6 +661,59 @@ def _audit_idempotent_confirmation_replay(
) )
def _inherit_confirmed_customer_resolution_onto_candidate(
candidate: ShippingOrderCandidate,
case: ShippingOrderReviewCase,
) -> None:
"""review_case 人工确认时,把源机器 Candidate 的正式客户确认事实挂到新确认候选上。
review_case 确认会新建独立 ShippingOrderCandidate(candidate_key=review-confirm-*),
但客户识别结果按 Candidate 关联稳定存放;新候选若不继承源候选的 confirmed resolution,
后续 assert_customer_confirmed_before_task_create / resolve_confirmed_customer_id 按
新 candidate_id 查表为空,会误拒"已确认客户"无法建单。
"""
if not case.candidate_id:
return
source = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
from app.services.shipping_notice.customer_resolution_service import resolution_for_task
source_resolution = resolution_for_task(source) if source is not None else None
if (
source_resolution is None
or source_resolution.status != 'confirmed'
or source_resolution.confirmed_customer_id is None
):
return
from app.models import ShippingCustomerShadowResolution
row = db.session.query(ShippingCustomerShadowResolution).filter_by(
candidate_id=int(candidate.id),
).one_or_none()
if row is None:
row = ShippingCustomerShadowResolution(
candidate_id=int(candidate.id), intake_id=int(candidate.intake_id),
)
db.session.add(row)
row.identity_rule_set_id = source_resolution.identity_rule_set_id
row.identity_rule_set_version = source_resolution.identity_rule_set_version
row.identity_rule_set_checksum = source_resolution.identity_rule_set_checksum
row.order_schema_version_id = source_resolution.order_schema_version_id
row.resolution_version = source_resolution.resolution_version
row.status = 'confirmed'
# [STEP] 完整复制源候选的正式识别证据与候选匹配快照:review_case 确认的新候选
# 必须携带可审计的客户识别事实,否则 freeze(_confirmed_ordering_customer 要求
# evidence_json 非空)会把"已确认客户"误判为未确认而冻结失败。
row.evidence_json = list(source_resolution.evidence_json or [])
row.candidate_matches_json = list(source_resolution.candidate_matches_json or [])
row.resolution_context_json = dict(source_resolution.resolution_context_json or {})
row.confirmed_customer_id = source_resolution.confirmed_customer_id
row.confirmation_method = source_resolution.confirmation_method or 'review_case_confirmed'
row.confirmed_by_id = int(candidate.accepted_by_id) if candidate.accepted_by_id is not None else None
row.confirmed_at = datetime.utcnow()
row.top_customer_id = source_resolution.top_customer_id
row.top_score = source_resolution.top_score
def _create_review_candidate( def _create_review_candidate(
*, *,
case: ShippingOrderReviewCase, case: ShippingOrderReviewCase,
@@ -786,6 +771,11 @@ def _create_review_candidate(
) )
db.session.add(candidate) db.session.add(candidate)
db.session.flush() db.session.flush()
# [STEP] review_case 人工确认:把继承的正式客户确认事实落到 resolution 表,
# 否则按新 candidate_id 查表为空,assert_customer_confirmed_before_task_create /
# resolve_confirmed_customer_id 会误拒"已确认客户"无法建单。
if customer_confirmed:
_inherit_confirmed_customer_resolution_onto_candidate(candidate, case)
asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None
# [STEP] 同 Case 既有波次不参与 Candidate 级 exact_file / 指纹阻断。 # [STEP] 同 Case 既有波次不参与 Candidate 级 exact_file / 指纹阻断。
prior_wave_task_ids = _prior_wave_task_ids_for_case(case) prior_wave_task_ids = _prior_wave_task_ids_for_case(case)
@@ -872,8 +862,8 @@ def _prior_wave_task_ids_for_case(case: ShippingOrderReviewCase) -> set[int]:
def _persist_wave_lines_for_task( def _persist_wave_lines_for_task(
*, *,
case: ShippingOrderReviewCase, case: ShippingOrderReviewCase,
task: ShippingNotice, task: ShippingOrderTask,
line_keys: list[str], snapshot_line_ids: list[int],
wave_no: int, wave_no: int,
revision_id: int | None, revision_id: int | None,
) -> None: ) -> None:
@@ -882,8 +872,8 @@ def _persist_wave_lines_for_task(
Args: Args:
case: 复核 Case。 case: 复核 Case。
task: 本波次新建的 Notice。 task: 本波次复核确认生成的 OT。
line_keys: 本波次完整行键。 snapshot_line_ids: 本波次冻结订单行 ID。
wave_no: 波次序号(从 1 起)。 wave_no: 波次序号(从 1 起)。
revision_id: 可选确认修订 ID。 revision_id: 可选确认修订 ID。
@@ -892,10 +882,10 @@ def _persist_wave_lines_for_task(
""" """
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
for key in line_keys: for snapshot_line_id in snapshot_line_ids:
db.session.add(ShippingOrderReviewWaveLine( db.session.add(ShippingOrderReviewWaveLine(
review_case_id=int(case.id), review_case_id=int(case.id),
line_key=str(key), snapshot_line_id=int(snapshot_line_id),
task_id=int(task.id), task_id=int(task.id),
wave_no=int(wave_no), wave_no=int(wave_no),
confirmed_revision_id=int(revision_id) if revision_id is not None else None, confirmed_revision_id=int(revision_id) if revision_id is not None else None,
@@ -906,31 +896,20 @@ def _persist_wave_lines_for_task(
raise ConflictError( raise ConflictError(
'Line already belongs to another fulfillment wave', 'Line already belongs to another fulfillment wave',
code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK', code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK',
details={'line_keys': list(line_keys)}, details={'snapshot_line_ids': [int(item) for item in snapshot_line_ids]},
) from exc ) from exc
def _order_task_no_for_notice(notice: ShippingNotice | None) -> str | None: def _order_task_no_for_notice(notice: ShippingOrderTask | None) -> str | None:
""" """返回 OT 自身编号(保留函数名仅用于本模块内部整理)。
从已建 Notice 解析挂接的 OT 编号(幂等回放用)。
Args: Args:
notice: 发货 Notice;None 时返回 None。 notice: OT;None 时返回 None。
Returns: Returns:
order_task.task_no;未挂接时 None。 order_task.task_no;未挂接时 None。
""" """
if notice is None: return str(getattr(notice, 'task_no', None) or '').strip() or None if notice is not None else None
return None
order_task_id = getattr(notice, 'order_task_id', None)
if order_task_id is None:
return None
from app.models import ShippingOrderTask
order_task = db.session.get(ShippingOrderTask, int(order_task_id))
if order_task is None:
return None
return str(order_task.task_no or '').strip() or None
def _confirmation_result_payload( def _confirmation_result_payload(
@@ -958,7 +937,7 @@ def _confirmation_result_payload(
""" """
payload: dict[str, Any] = { payload: dict[str, Any] = {
'task_no': task_no, 'task_no': task_no,
'shipping_notice_no': task_no, 'shipping_notice_no': None,
'order_task_no': order_task_no, 'order_task_no': order_task_no,
'idempotent_replay': idempotent_replay, 'idempotent_replay': idempotent_replay,
'case': serialize_review_case(case), 'case': serialize_review_case(case),
@@ -969,7 +948,7 @@ def _confirmation_result_payload(
return payload return payload
def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: Any, idempotency_key: str | None, warning_acknowledgements: Any = None, confirm_note: str | None = None, line_keys: list[str] | None = None) -> dict[str, Any]: def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: Any, idempotency_key: str | None, warning_acknowledgements: Any = None, confirm_note: str | None = None) -> dict[str, Any]:
""" """
确认一个 PDF 草稿并建一张无 Batch 的 Task;门禁拒绝写统一审计后抛错。 确认一个 PDF 草稿并建一张无 Batch 的 Task;门禁拒绝写统一审计后抛错。
@@ -979,7 +958,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
幂等回放(同键或已确认 Case)同样写审计(result=ignored),追溯重复提交。 幂等回放(同键或已确认 Case)同样写审计(result=ignored),追溯重复提交。
版本冲突/校验失败/文档不可用/重复订单等拒绝写 result=rejected,并在 raise 前独立 commit。 版本冲突/校验失败/文档不可用/重复订单等拒绝写 result=rejected,并在 raise 前独立 commit。
锁定 Case 之前的边界拒绝(缺幂等键、警告格式非法、幂等键跨 Case 占用)在 Case 可定位时同样写拒绝审计。 锁定 Case 之前的边界拒绝(缺幂等键、警告格式非法、幂等键跨 Case 占用)在 Case 可定位时同样写拒绝审计。
可选 line_keys:仅冻结选中的完整明细行(履约波次);若 Case 仍有开放行则保持 ready 不终态确认。 确认订单恒为整单确认(业务规则:确认订单不可分行;仅“产生发货通知”可分波次)。
Args: Args:
user_id: Case 属主用户 ID。 user_id: Case 属主用户 ID。
@@ -988,7 +967,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
idempotency_key: 建单幂等键。 idempotency_key: 建单幂等键。
warning_acknowledgements: 警告确认列表。 warning_acknowledgements: 警告确认列表。
confirm_note: 可选确认备注,写入审计 metadata。 confirm_note: 可选确认备注,写入审计 metadata。
line_keys: 可选履约波次行键;None 表示整单草稿行。
Returns: Returns:
含 shipping_notice_no / task_no / order_task_no / case / workflow_id / trigger_auto_progress 的确认结果。 含 shipping_notice_no / task_no / order_task_no / case / workflow_id / trigger_auto_progress 的确认结果。
@@ -1028,7 +1006,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
), ),
idempotency_key=key, idempotency_key=key,
) )
task = db.session.get(ShippingNotice, int(replay.task_id)) task = db.session.get(ShippingOrderTask, int(replay.task_id))
task_no = task.task_no if task else None task_no = task.task_no if task else None
_audit_idempotent_confirmation_replay( _audit_idempotent_confirmation_replay(
user_id=user_id, user_id=user_id,
@@ -1044,9 +1022,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
idempotent_replay=True, idempotent_replay=True,
) )
case = _locked_case(user_id=user_id, case_no=case_no, idempotency_key=key) case = _locked_case(user_id=user_id, case_no=case_no, idempotency_key=key)
# 整单已终态确认时幂等回放;履约波次在 Case 仍为 ready 时可继续建后续 Task。 # 整单已终态确认时幂等回放(确认订单恒为整单,不存在按行波次的中间态)。
if case.status == 'confirmed' and case.confirmed_task_id and not line_keys: if case.status == 'confirmed' and case.confirmed_task_id:
task = db.session.get(ShippingNotice, int(case.confirmed_task_id)) task = db.session.get(ShippingOrderTask, int(case.confirmed_task_id))
task_no = task.task_no if task else None task_no = task.task_no if task else None
_audit_idempotent_confirmation_replay( _audit_idempotent_confirmation_replay(
user_id=user_id, user_id=user_id,
@@ -1073,76 +1051,12 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
idempotency_key=key, idempotency_key=key,
metadata={'expected_draft_version': expected}, metadata={'expected_draft_version': expected},
) )
wave_keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()] or None # [STEP] 确认订单恒为整单:build_confirmable_draft_summary 不接受 draft_line_ids,
# [STEP] 波次行唯一归属:在建 Task 前 fail-closed,避免 IntegrityError 半成品。 # 确认时要求整单全部行通过校验(业务规则:确认订单不可分行)。
if wave_keys is not None: summary, validation = build_confirmable_draft_summary(case)
already = ( # [STEP] 硬门禁已移除:确认流程只确认订单信息(订单字段/客户/订单快照)。
ShippingOrderReviewWaveLine.query # 库存源候选的裁决/冻结由确认后 OT 进入的正式 inventory_source_routing Gate 负责,
.filter( # 不再要求确认时库存源已唯一确定。
ShippingOrderReviewWaveLine.review_case_id == int(case.id),
ShippingOrderReviewWaveLine.line_key.in_(list(wave_keys)),
)
.all()
)
if already:
_reject_confirmation(
case,
actor_id=int(user_id),
error=ConflictError(
'Line already belongs to another fulfillment wave',
code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK',
details={'line_keys': [str(row.line_key) for row in already]},
),
idempotency_key=key,
case_no=str(case_no),
owner_user_id=int(user_id),
)
summary, validation = build_confirmable_draft_summary(case, line_keys=wave_keys)
# [STEP] 建单硬门禁:库存源未唯一确定时禁止创建正式订单,并回写 OT stage。
if ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE:
inventory_issues = [
item
for item in (validation.get('issues') or [])
if isinstance(item, dict)
and str(item.get('owning_gate_code') or '') == 'inventory_source_routing'
and str(item.get('severity') or '') == 'blocking'
]
if inventory_issues:
from app.services.shipping_notice.order_task_service import (
resolve_order_task_for_candidate,
sync_order_task_processing_state,
)
blocked_ot = resolve_order_task_for_candidate(
int(case.candidate_id) if case.candidate_id else None
)
if blocked_ot is not None:
sync_order_task_processing_state(
blocked_ot,
stage='inventory_source_resolving',
status='blocked',
)
primary = inventory_issues[0]
_reject_confirmation(
case,
actor_id=int(user_id),
error=ConflictError(
'Inventory source must be uniquely resolved before creating a formal order',
code='SHIPPING.REVIEW_INVENTORY_SOURCE_UNRESOLVED',
details={
'issues': inventory_issues,
'blocking_reason_code': str(
primary.get('code') or 'no_inventory_source_candidates'
),
'owning_gate_code': 'inventory_source_routing',
},
),
idempotency_key=key,
metadata={
'validation_status': str(validation.get('status') or '')[:32] or None,
'gate_code': 'inventory_source_routing',
},
)
if draft_has_unaccepted_llm_suggestions(case): if draft_has_unaccepted_llm_suggestions(case):
_reject_confirmation( _reject_confirmation(
case, case,
@@ -1204,7 +1118,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
before_snap = {'status': previous_status, 'disposition': previous_disposition} before_snap = {'status': previous_status, 'disposition': previous_disposition}
# [BE-01/BE-02] 人工 Candidate 物化前锁定 Case 原 Candidate 对应 OT,禁止事后落到 Run 根号。 # [BE-01/BE-02] 人工 Candidate 物化前锁定 Case 原 Candidate 对应 OT,禁止事后落到 Run 根号。
from app.services.shipping_notice.order_task_service import ( from app.services.shipping_notice.order_task_service import (
link_notice_to_order_task,
replace_order_task_candidate_after_review, replace_order_task_candidate_after_review,
resolve_order_task_for_candidate, resolve_order_task_for_candidate,
upsert_order_task_from_run, upsert_order_task_from_run,
@@ -1230,17 +1143,19 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
) )
try: try:
assert_case_is_current_workflow_version(case=case) assert_case_is_current_workflow_version(case=case)
# [STEP] 建单前再次校验客户确认(相对 Draft 校验时刻防并发回退)。 # [STEP] 建单前解析唯一客户(读机器候选 resolution,一次完成门户校验 + 取主键)。
# 机器候选是客户识别事实的权威来源:没有唯一已确认主键即拒绝建单。
from app.services.shipping_notice.candidate_qualification_service import ( from app.services.shipping_notice.candidate_qualification_service import (
recalculate_candidate_qualification, recalculate_candidate_qualification,
resolve_review_case_customer_resolved, resolve_confirmed_customer_id,
) )
pre_candidate = ( pre_candidate = (
db.session.get(ShippingOrderCandidate, int(case.candidate_id)) db.session.get(ShippingOrderCandidate, int(case.candidate_id))
if case.candidate_id if case.candidate_id
else None else None
) )
if not resolve_review_case_customer_resolved(case=case, candidate=pre_candidate): bind_customer_id = resolve_confirmed_customer_id(candidate=pre_candidate)
if bind_customer_id is None:
raise ConflictError( raise ConflictError(
'Customer is not confirmed', 'Customer is not confirmed',
code='SHIPPING.REVIEW_CUSTOMER_UNRESOLVED', code='SHIPPING.REVIEW_CUSTOMER_UNRESOLVED',
@@ -1287,7 +1202,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
) )
# [BE-01/BE-02] 复用锁定 OT;无原 Candidate 时才按人工 Candidate 新建 OT。 # [BE-01/BE-02] 复用锁定 OT;无原 Candidate 时才按人工 Candidate 新建 OT。
try: try:
if locked_order_task is not None and locked_order_task.shipping_notice_id is None: if locked_order_task is not None:
order_task = replace_order_task_candidate_after_review( order_task = replace_order_task_candidate_after_review(
order_task=locked_order_task, order_task=locked_order_task,
previous_candidate_id=source_candidate_id, previous_candidate_id=source_candidate_id,
@@ -1356,57 +1271,23 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
) )
# [BE-06] Notice 创建及挂接后的消费/客户绑定失败须 fail-closed 回滚。 # [BE-06] Notice 创建及挂接后的消费/客户绑定失败须 fail-closed 回滚。
try: try:
task = ShippingNotice( task = order_task
task_no=generate_task_no(), user_id=int(user_id), task.current_order_extraction_id = int(extraction.id)
conversation_id=case.run.conversation_id, source_type='review_confirmation', source_file_name=document.filename, task.order_data_version = int(getattr(task, 'order_data_version', None) or 1)
source_file_type=asset.mime_type if asset else None, source_content_hash=document.content_hash,
source_asset_id=document.asset_id, source_intake_id=int(intake.id), source_candidate_id=int(candidate.id),
business_fingerprint=candidate.business_fingerprint, fingerprint_version=candidate.fingerprint_version,
content_fingerprint=candidate.content_fingerprint, content_fingerprint_version=candidate.content_fingerprint_version,
document_version=1, duplicate_resolution_type='normal', raw_content=document.extracted_text,
customer_resolution_status='pending', current_order_extraction_id=int(extraction.id),
)
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
link_notice_to_order_task(
order_task_no=order_task_no,
notice_id=int(task.id),
)
extraction.task_id = int(task.id) extraction.task_id = int(task.id)
candidate.consumed_task_id = int(task.id) candidate.consumed_task_id = int(task.id)
candidate.updated_at = datetime.utcnow() candidate.updated_at = datetime.utcnow()
# The review Case is the explicit human confirmation for this PDF. Do not # The review Case is the explicit human confirmation for this PDF. Do not
# recreate a low-confidence parse checkpoint on the newly materialized Task. # recreate a low-confidence parse checkpoint on the newly materialized Task.
apply_task_transition(task, TaskTransition.CONFIRM_PARSE) # [STEP] 确认只固化订单信息(订单字段/客户/订单快照)。库存源候选的裁决/冻结
# [STEP] 冻结建单资格中的行级库存源候选;单源 resolved,多源 candidates_frozen。 # 退到确认后 OT 进入的正式 inventory_source_routing Gate 处理,不在确认流程内
from app.services.shipping_notice.stp_inventory_freeze import freeze_stp_inventory_candidates_on_task # 提前冻结库存候选,因此也不再在确认处设置 OT 的 notification_preparation 阶段。
# [STEP] 建单前已从机器候选解析唯一客户主键(bind_customer_id,见上方门禁)。
freeze_stp_inventory_candidates_on_task( # 此处直接用该主键绑定标准客户,禁止落入 customer_review,不再二次查表。
task,
line_projections=list(validation.get('line_projections') or []),
)
# [STEP] 候选库存源已在建单前冻结;正式 OT 创建完成后立即进入获取库存,
# 不再让统一进度停留在“创建正式订单”。最终行级实际库存源仍由后续匹配决定。
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
sync_order_task_processing_state(
order_task,
stage='inventory_fetching',
status='processing',
reason_code='inventory_candidates_frozen_after_confirm',
)
# [STEP] 建单前已校验客户确认:立即绑定标准客户,禁止落入 customer_review。
from app.services.shipping_notice.candidate_qualification_service import (
resolve_confirmed_bill_to_customer_id,
)
from app.services.shipping_notice.customer_auto_resolution import try_auto_confirm_task_customer
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
bind_customer_id = resolve_confirmed_bill_to_customer_id(
candidate=candidate,
extraction_id=int(extraction.id),
)
if bind_customer_id is not None:
confirm_task_customer( confirm_task_customer(
task, task,
customer_id=int(bind_customer_id), customer_id=int(bind_customer_id),
@@ -1414,11 +1295,10 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
resolution_method='review_case_confirmed', resolution_method='review_case_confirmed',
commit=False, commit=False,
) )
else:
try_auto_confirm_task_customer(task)
# [STEP] Review 确认建单与自动建单必须共享订单快照前置条件。 # [STEP] Review 确认建单与自动建单必须共享订单快照前置条件。
# 冻结失败由外层 AppError 回滚,不能留下已建单但库存链路无法启动的半成品。 # 冻结失败由外层 AppError 回滚,不能留下已建单但库存链路无法启动的半成品。
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
from app.models import ShippingOrderSnapshot
freeze_order_snapshot( freeze_order_snapshot(
task, task,
@@ -1426,6 +1306,12 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
expected_order_data_version=int(task.order_data_version or 1), expected_order_data_version=int(task.order_data_version or 1),
freeze_mode='manual', freeze_mode='manual',
) )
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
if snapshot is None:
raise ConflictError(
'Confirmed order snapshot is required for wave assignment',
code='SHIPPING.REVIEW_LINE_SNAPSHOT_MAPPING_MISSING',
)
except AppError as err: except AppError as err:
_reject_confirmation( _reject_confirmation(
case, case,
@@ -1435,14 +1321,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
before=before_snap, before=before_snap,
needs_rollback=True, needs_rollback=True,
) )
# [STEP] 确认订单只做整单确认(业务规则:确认订单不可分行;仅“产生发货通知”可分波次)。
# 因此 revision 记录整单草稿行,不按 draft_line_ids 过滤。
revision_lines = copy.deepcopy(case.current_draft.lines_json or []) revision_lines = copy.deepcopy(case.current_draft.lines_json or [])
if wave_keys is not None:
wanted = set(wave_keys)
revision_lines = [
item for idx, item in enumerate(revision_lines)
if isinstance(item, dict)
and (str(item.get('line_key') or '').strip() or f'line-{idx + 1}') in wanted
]
revision = ShippingOrderReviewConfirmedRevision( revision = ShippingOrderReviewConfirmedRevision(
case_id=int(case.id), task_id=int(task.id), draft_version=int(case.current_draft.draft_version), case_id=int(case.id), task_id=int(task.id), draft_version=int(case.current_draft.draft_version),
schema_version_id=int(case.current_draft.schema_version_id), header_values_json=copy.deepcopy(case.current_draft.header_values_json or {}), schema_version_id=int(case.current_draft.schema_version_id), header_values_json=copy.deepcopy(case.current_draft.header_values_json or {}),
@@ -1451,12 +1332,8 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
) )
db.session.add(revision) db.session.add(revision)
db.session.flush() db.session.flush()
# [STEP] 行级唯一归属:本波次(或整单)行写入不可变 wave_lines,防并发重复入波次。 # [STEP] 行级归属记录:确认订单整单写入 snapshot 全部行(防并发重复入波次)。
wave_line_keys = list(wave_keys) if wave_keys is not None else [ wave_line_ids = [int(line.id) for line in snapshot.lines]
(str(item.get('line_key') or '').strip() or f'line-{idx + 1}')
for idx, item in enumerate(case.current_draft.lines_json or [])
if isinstance(item, dict)
]
from sqlalchemy import func from sqlalchemy import func
max_wave = ( max_wave = (
@@ -1469,7 +1346,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
_persist_wave_lines_for_task( _persist_wave_lines_for_task(
case=case, case=case,
task=task, task=task,
line_keys=wave_line_keys, snapshot_line_ids=wave_line_ids,
wave_no=next_wave_no, wave_no=next_wave_no,
revision_id=int(revision.id), revision_id=int(revision.id),
) )
@@ -1484,41 +1361,8 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
case_no=str(case_no), case_no=str(case_no),
owner_user_id=int(user_id), owner_user_id=int(user_id),
) )
# [STEP] 履约波次:若仍有未入 Task/未关闭的草稿行,Case 保持 ready 以支持后续波次。 # [STEP] 确认订单恒为整单终态确认(业务规则:确认订单不可分行,整单全过才确认)。
has_remaining_open = False # 不再有“仍有开放行则保持 ready 支持后续波次”的中间态。
if wave_keys is not None:
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
project_review_case_line_decisions,
)
terminal = {'task_created', 'fulfilled', 'closed_unfulfillable'}
projected = project_review_case_line_decisions(case)
draft_all_keys = {
(str(item.get('line_key') or '').strip() or f'line-{idx + 1}')
for idx, item in enumerate(case.current_draft.lines_json or [])
if isinstance(item, dict)
}
assigned = {
str(row.line_key)
for row in ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(case.id)).all()
}
for key in draft_all_keys:
if key in assigned:
continue
matched = next(
(item for item in (projected.get('lines') or []) if str(item.get('line_key') or '') == key),
None,
)
# 未入波次且未关闭的行保留 Case 可继续确认。
if matched is None or matched.get('line_status') not in terminal:
has_remaining_open = True
break
if has_remaining_open:
case.status = 'ready'
case.confirmed_task_id = int(task.id)
# 保留首次确认时间;首波未终态时写入当前时间供追溯。
if case.confirmed_at is None:
case.confirmed_at = datetime.utcnow()
else:
case.status = 'confirmed' case.status = 'confirmed'
case.confirmed_task_id = int(task.id) case.confirmed_task_id = int(task.id)
case.confirmed_at = datetime.utcnow() case.confirmed_at = datetime.utcnow()
@@ -1532,8 +1376,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
'idempotency_key': key, 'idempotency_key': key,
'warning_acknowledgements': acknowledgements, 'warning_acknowledgements': acknowledgements,
'confirm_note': str(confirm_note or '').strip()[:1024] or None, 'confirm_note': str(confirm_note or '').strip()[:1024] or None,
'line_keys': wave_keys,
'partial_wave': bool(has_remaining_open),
}, },
)) ))
# Case 级统一审计必须先写:即使工作项尚未绑定,审计中心仍可按 Case 追溯确认事实。 # Case 级统一审计必须先写:即使工作项尚未绑定,审计中心仍可按 Case 追溯确认事实。
@@ -1576,7 +1418,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
) )
def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool: def _task_needs_post_confirm_auto_progress(task: ShippingOrderTask | None) -> bool:
""" """
判断确认建单后的任务是否仍需自动推进。 判断确认建单后的任务是否仍需自动推进。
@@ -1593,16 +1435,18 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
return False return False
if not getattr(task, 'current_order_extraction_id', None): if not getattr(task, 'current_order_extraction_id', None):
return False return False
inventory_snapshot_id = getattr(task, 'inventory_snapshot_id', None) from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt
inventory_lines = getattr(task, 'inventory_lines_json', None) export_file_path = getattr(latest_export_artifact(task), 'file_path', None)
match_status = getattr(task, 'match_status', None) upload_status = getattr(latest_upload_attempt(task), 'status', None)
export_file_path = getattr(task, 'export_file_path', None)
upload_status = getattr(task, 'upload_status', None)
# 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等 # 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等
# 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。 # 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。
has_inventory = isinstance(inventory_snapshot_id, int) and not isinstance(inventory_snapshot_id, bool) from app.services.shipping_notice.inventory_file_store import (
has_inventory = has_inventory or isinstance(inventory_lines, (list, dict)) and bool(inventory_lines) current_inventory_matches_for_task,
has_match = isinstance(match_status, str) and bool(match_status.strip()) has_ready_inventory_file_for_task,
)
has_inventory = has_ready_inventory_file_for_task(task)
has_match = bool(current_inventory_matches_for_task(task))
has_export = isinstance(export_file_path, str) and bool(export_file_path.strip()) has_export = isinstance(export_file_path, str) and bool(export_file_path.strip())
has_upload = isinstance(upload_status, str) and bool(upload_status.strip()) has_upload = isinstance(upload_status, str) and bool(upload_status.strip())
return not (has_inventory or has_match or has_export or has_upload) return not (has_inventory or has_match or has_export or has_upload)
@@ -1661,7 +1505,7 @@ def schedule_auto_progress_after_review_confirm(
if not normalized: if not normalized:
return None return None
task = db.session.query(ShippingNotice).filter(ShippingNotice.task_no == normalized).first() task = db.session.query(ShippingOrderTask).filter(ShippingOrderTask.task_no == normalized).first()
# [STEP] 首轮与幂等回放共用:仅当仍停在 created+已抽取时入队,避免无条件跳过导致悬挂。 # [STEP] 首轮与幂等回放共用:仅当仍停在 created+已抽取时入队,避免无条件跳过导致悬挂。
if not _task_needs_post_confirm_auto_progress(task): if not _task_needs_post_confirm_auto_progress(task):
return None return None
@@ -2,8 +2,8 @@
services/shipping_notice/order_review_customer_service.py services/shipping_notice/order_review_customer_service.py
用途:建单前复核工作台的客户识别结果查询、重新匹配与人工确认。 用途:建单前复核工作台的客户识别结果查询、重新匹配与人工确认。
依赖:order_review_draft_service、order_customer_matching、candidate_qualification_service、 依赖:order_review_draft_service、candidate_qualification_service、客户识别结果服务、
ShippingOrderReviewCase / ShippingOrderCustomerMatch。 ShippingOrderReviewCase / ShippingCustomerShadowResolution。
逻辑:由 workspace order-review-cases 客户路由调用;确认后重跑 Draft 校验以刷新建单资格; 逻辑:由 workspace order-review-cases 客户路由调用;确认后重跑 Draft 校验以刷新建单资格;
不创建 Task、不重新解析 PDF。 不创建 Task、不重新解析 PDF。
""" """
@@ -17,18 +17,13 @@ from app.core.errors import ConflictError, NotFoundError
from app.models import ( from app.models import (
ShippingOrderCandidate, ShippingOrderCandidate,
ShippingCustomerShadowResolution, ShippingCustomerShadowResolution,
ShippingOrderCustomerMatch,
ShippingOrderExtraction, ShippingOrderExtraction,
ShippingOrderReviewCase, ShippingOrderReviewCase,
) )
from app.services.shipping_notice.candidate_qualification_service import ( from app.services.shipping_notice.candidate_qualification_service import (
resolve_review_case_customer_resolved, resolve_review_case_customer_resolved,
) )
from app.services.shipping_notice.order_customer_matching import ( from app.services.shipping_notice.customer_resolution_service import confirm_customer_resolution
confirm_order_customer_match,
refresh_order_customer_matches,
serialize_order_customer_match,
)
from app.services.shipping_notice.workflow_ledger_service import ( from app.services.shipping_notice.workflow_ledger_service import (
assert_case_is_current_workflow_version, assert_case_is_current_workflow_version,
) )
@@ -78,42 +73,6 @@ def _resolve_extraction_for_case(case: ShippingOrderReviewCase) -> ShippingOrder
) )
def _header_from_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""从 Draft / Candidate 业务摘要投影客户匹配所需的头字段。"""
header: dict[str, Any] = {}
draft = case.current_draft
if draft is not None and isinstance(draft.header_values_json, dict):
# Draft 以 field_id 存值;客户匹配需要 bill_to_* 业务码,尽量从 Candidate 摘要补齐。
for key, value in draft.header_values_json.items():
if isinstance(key, str) and value is not None:
header[str(key)] = value
candidate = (
db.session.get(ShippingOrderCandidate, int(case.candidate_id))
if case.candidate_id
else None
)
structured = candidate.structured_result_json if candidate is not None else None
summary = (
structured.get('business_summary')
if isinstance(structured, dict) and isinstance(structured.get('business_summary'), dict)
else {}
)
for key in (
'bill_to_customer',
'bill_to_customer_code',
'bill_to_source_system',
'ship_to_customer',
'ship_to_code',
'ship_to_source_system',
'customer_name',
):
if key not in header and summary.get(key) is not None:
header[key] = summary.get(key)
if 'bill_to_customer' not in header and header.get('customer_name'):
header['bill_to_customer'] = header.get('customer_name')
return header
def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> dict[str, Any]: def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> dict[str, Any]:
""" """
投影复核 Case 的建单前客户识别状态,供工作台固定客户区展示。 投影复核 Case 的建单前客户识别状态,供工作台固定客户区展示。
@@ -138,25 +97,16 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di
if candidate is not None if candidate is not None
else None else None
) )
match = None
if extraction is not None:
match = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(extraction.id),
role='bill_to',
).first()
match_payload = serialize_order_customer_match(match) if match is not None else None
shadow_matches = list(shadow.candidate_matches_json or []) if shadow is not None else [] shadow_matches = list(shadow.candidate_matches_json or []) if shadow is not None else []
top_shadow = shadow_matches[0] if shadow_matches else {} top_shadow = shadow_matches[0] if shadow_matches else {}
status = 'confirmed' if resolved else str( status = 'confirmed' if resolved else str(
(shadow.status if shadow is not None else None) (shadow.status if shadow is not None else None)
or (match_payload or {}).get('status')
or 'unmatched' or 'unmatched'
) )
# [STEP 1] 客户识别展示以已发布规则集生成的指纹候选为准;旧 CustomerMatch 仅作为确认状态兼容投影。 # [STEP 1] 客户识别展示和确认均以已发布规则集生成的证据快照为准。
display_match = match_payload or {} display_match: dict[str, Any] = {}
if top_shadow: if top_shadow:
display_match = { display_match = {
**display_match,
'customer_id': top_shadow.get('customer_id'), 'customer_id': top_shadow.get('customer_id'),
'standard_name': top_shadow.get('standard_name'), 'standard_name': top_shadow.get('standard_name'),
'short_code': top_shadow.get('short_code'), 'short_code': top_shadow.get('short_code'),
@@ -216,7 +166,7 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di
'role': 'customer', 'role': 'customer',
'extraction_id': int(extraction.id) if extraction is not None else None, 'extraction_id': int(extraction.id) if extraction is not None else None,
'raw_name': None, 'raw_name': None,
'customer_id': display_match.get('customer_id'), 'customer_id': getattr(shadow, 'confirmed_customer_id', None) or display_match.get('customer_id'),
'standard_name': display_match.get('standard_name'), 'standard_name': display_match.get('standard_name'),
'short_code': display_match.get('short_code'), 'short_code': display_match.get('short_code'),
'candidates': list(display_match.get('candidates') or []), 'candidates': list(display_match.get('candidates') or []),
@@ -236,7 +186,7 @@ def confirm_review_case_customer(
""" """
在复核工作台确认标准客户,并刷新建单资格。 在复核工作台确认标准客户,并刷新建单资格。
核心逻辑:写入 Bill-to CustomerMatch=confirmed → 统一协调器推进 → 返回最新 Case。 核心逻辑:确认正式客户识别结果 → 统一协调器推进 → 返回最新 Case。
""" """
from app.services.shipping_notice.order_review_auto_progress_coordinator import ( from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress, reconcile_single_case_for_auto_progress,
@@ -244,25 +194,15 @@ def confirm_review_case_customer(
from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_review_projection import serialize_review_case
case = _load_writable_case(user_id=user_id, case_no=case_no) case = _load_writable_case(user_id=user_id, case_no=case_no)
extraction = _resolve_extraction_for_case(case) candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None
if extraction is None: if candidate is None:
raise ConflictError( raise ConflictError('Candidate is required before confirming customer', code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED')
'Order extraction is required before confirming customer', confirm_customer_resolution(
code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND', candidate,
)
# [STEP 1] 若尚无 match 行,先按当前头字段刷新,再人工确认。
if ShippingOrderCustomerMatch.query.filter_by(extraction_id=int(extraction.id), role='bill_to').first() is None:
refresh_order_customer_matches(extraction, _header_from_case(case))
# [STEP P1-8] confirm_order_customer_match 保留调用,传 commit=False 以便
# 后续 reconcile(校验+STP 入队)在同一事务提交,保证变更与推进原子可见。
confirm_order_customer_match(
int(extraction.id),
role='bill_to',
customer_id=int(customer_id), customer_id=int(customer_id),
site_id=None,
actor_id=int(user_id), actor_id=int(user_id),
method='manual',
reason=str(reason or '复核工作台人工确认标准客户').strip(), reason=str(reason or '复核工作台人工确认标准客户').strip(),
commit=False,
) )
# [STEP P1-8] 客户人工确认后走统一协调器:终态门禁 + 客户协调(已人工确认会跳过)+ # [STEP P1-8] 客户人工确认后走统一协调器:终态门禁 + 客户协调(已人工确认会跳过)+
# Draft 校验 + STP 入队;trigger=customer_confirmed 对应人工确认语义。 # Draft 校验 + STP 入队;trigger=customer_confirmed 对应人工确认语义。
@@ -306,7 +246,7 @@ def retry_review_case_customer_resolution(
case_no: str, case_no: str,
) -> dict[str, Any]: ) -> dict[str, Any]:
""" """
重新识别客户(不重解析 PDF):按当前 Draft/摘要刷新 CustomerMatch。 重新识别客户(不重解析 PDF):刷新规则驱动的客户识别快照。
【AI 触发时机】:用户在复核工作台点击「重新识别客户」时调用。 【AI 触发时机】:用户在复核工作台点击「重新识别客户」时调用。
""" """
@@ -316,13 +256,7 @@ def retry_review_case_customer_resolution(
from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_review_projection import serialize_review_case
case = _load_writable_case(user_id=user_id, case_no=case_no) case = _load_writable_case(user_id=user_id, case_no=case_no)
extraction = _resolve_extraction_for_case(case) matches: list[dict[str, Any]] = []
if extraction is None:
raise ConflictError(
'Order extraction is required before retrying customer resolution',
code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND',
)
matches = refresh_order_customer_matches(extraction, _header_from_case(case))
if case.candidate_id: if case.candidate_id:
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
@@ -334,16 +268,14 @@ def retry_review_case_customer_resolution(
and shadow.top_customer_id and shadow.top_customer_id
and not resolve_review_case_customer_resolved(case=case, candidate=candidate) and not resolve_review_case_customer_resolved(case=case, candidate=candidate)
): ):
# [STEP P1-8] 传 commit=False,保证与后续 reconcile 同事务提交。 confirm_customer_resolution(
confirm_order_customer_match( candidate,
int(extraction.id),
role='bill_to',
customer_id=int(shadow.top_customer_id), customer_id=int(shadow.top_customer_id),
site_id=None,
actor_id=None, actor_id=None,
method='auto_rule',
reason='客户识别指纹唯一命中自动确认', reason='客户识别指纹唯一命中自动确认',
commit=False,
) )
matches = list(shadow.candidate_matches_json or [])
# [STEP P1-8] 客户 shadow 重新识别后走统一协调器;trigger=customer_shadow_reconfirmed # [STEP P1-8] 客户 shadow 重新识别后走统一协调器;trigger=customer_shadow_reconfirmed
# 标识为「影子指纹再确认 + 唯一命中自动确认」路径,与 PATCH 异步 Job、人工确认按钮路径互补不冲突。 # 标识为「影子指纹再确认 + 唯一命中自动确认」路径,与 PATCH 异步 Job、人工确认按钮路径互补不冲突。
reconcile_result = reconcile_single_case_for_auto_progress( reconcile_result = reconcile_single_case_for_auto_progress(
@@ -1074,6 +1074,11 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo
因此只在 ``activate_review_case`` 已确认切换成功后调用单 Case 协调器。这样复用 因此只在 ``activate_review_case`` 已确认切换成功后调用单 Case 协调器。这样复用
客户确认、Draft 校验、Gate 与 STP 幂等链路,且不会让晚到分支覆盖已确认版本。 客户确认、Draft 校验、Gate 与 STP 幂等链路,且不会让晚到分支覆盖已确认版本。
终态闭环不变式:后继 Run 收口时业务必须二选一 —— 新版 Case 已上位 Stream,
或旧版 Case 已恢复为可编辑状态。绝不允许旧 Case 停留在 ``reparse_pending``
而新版被孤儿化:该状态下工作台会永久卡在历史版本,且任何 API 都无法再次
触达新版或重新发起重识别。
Args: Args:
run: 已到终态的重解析后继 Run。 run: 已到终态的重解析后继 Run。
succeeded: 新版 Run 是否成功到达可复核终态。 succeeded: 新版 Run 是否成功到达可复核终态。
@@ -1095,21 +1100,24 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo
).with_for_update().first() ).with_for_update().first()
) )
if source_case is None or source_case.status != 'reparse_pending': if source_case is None or source_case.status != 'reparse_pending':
# 并发分支已裁决(被另一失败后继恢复、或已确认走另一分支):
# Stream 现状即权威,此处回改只会制造第二真相源。
return return
if succeeded: replacement_case = (
replacement_case = ShippingOrderReviewCase.query.filter_by( ShippingOrderReviewCase.query.filter_by(
run_id=int(run.id), document_id=document_id, run_id=int(run.id), document_id=document_id,
).with_for_update().first() ).with_for_update().first()
if replacement_case is None: if succeeded
# Run 已到终态但没有可复核新版本时,不可废弃旧草稿。 else None
return )
if replacement_case is not None:
from app.services.shipping_notice.review_stream_service import activate_review_case from app.services.shipping_notice.review_stream_service import activate_review_case
stream = activate_review_case( stream = activate_review_case(
case=replacement_case, case=replacement_case,
trigger='batch_reparse_succeeded' if marker.get('batch_reparse_id') else 'document_reparse_succeeded', trigger='batch_reparse_succeeded' if marker.get('batch_reparse_id') else 'document_reparse_succeeded',
) )
# [STEP] 只有 Stream 已原子指向新版 Case 才补偿自动推进。激活被并发确认或 # [STEP] 只有 Stream 已原子指向新版 Case 才补偿自动推进并宣告成功;
# 晚到分支拒绝时,保持该草稿只读,不得错误建单或进入库存准备。 # 激活被并发确认或晚到分支拒绝时,禁止记录 succeeded 审计(与事实不符)。
if int(stream.current_case_id or 0) == int(replacement_case.id): if int(stream.current_case_id or 0) == int(replacement_case.id):
from app.services.shipping_notice.order_review_auto_progress_coordinator import ( from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress, reconcile_single_case_for_auto_progress,
@@ -1124,6 +1132,12 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo
'replacement_case_no': replacement_case.case_no, 'replacement_case_no': replacement_case.case_no,
}) })
return return
finalize_failure_reason = 'stream_activation_rejected'
else:
finalize_failure_reason = 'replacement_case_missing'
# [C1] 终态闭环:成功终态但新版 Case 缺失、或激活被拒绝时,禁止静默返回 ——
# 否则旧 Case 永久停留在 reparse_pending(编辑/确认全被禁且无法再触发重识别),
# 工作台只能卡在历史版本。转入既有失败恢复链把旧 Case 恢复为可编辑状态。
previous = 'quality_issue' previous = 'quality_issue'
event = ShippingOrderReviewCaseEvent.query.filter( event = ShippingOrderReviewCaseEvent.query.filter(
ShippingOrderReviewCaseEvent.case_id == int(source_case.id), ShippingOrderReviewCaseEvent.case_id == int(source_case.id),
@@ -1136,6 +1150,7 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo
source_case.status = previous source_case.status = previous
_append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_failed', operation={ _append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_failed', operation={
'successor_run_no': run.run_no, 'restored_status': previous, 'successor_run_no': run.run_no, 'restored_status': previous,
'failure_reason': finalize_failure_reason,
}) })
from app.services.shipping_notice.workflow_ledger_service import mark_reparse_failed_and_restore from app.services.shipping_notice.workflow_ledger_service import mark_reparse_failed_and_restore
mark_reparse_failed_and_restore( mark_reparse_failed_and_restore(
@@ -10,7 +10,7 @@ services/shipping_notice/order_review_draft_service.py
追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流; 追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流;
Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计; Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计;
整单校验汇总客户确认、有效 Reservation、行级库存源候选与自动建单资格; 整单校验汇总客户确认、有效 Reservation、行级库存源候选与自动建单资格;
履约波次确认经 build_confirmable_draft_summary(line_keys) 仅对选中行重算 validation; 履约波次确认经 build_confirmable_draft_summary(draft_line_ids) 仅对选中行重算 validation;
库存路由恢复使用最新已发布规则与库存源启停,不重新识别 PDF,不静默覆盖人工决定; 库存路由恢复使用最新已发布规则与库存源启停,不重新识别 PDF,不静默覆盖人工决定;
路由恢复幂等键写入 Draft 历史集合(非仅最近一次),旧键重试可安全重放; 路由恢复幂等键写入 Draft 历史集合(非仅最近一次),旧键重试可安全重放;
显式校验后同步字段完整性、字段冲突、客户/Reservation/重复订单/库存路由 Gate(findings.details)。 显式校验后同步字段完整性、字段冲突、客户/Reservation/重复订单/库存路由 Gate(findings.details)。
@@ -47,7 +47,6 @@ from app.services.shipping_notice.order_build_eligibility_service import (
from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref
from app.services.shipping_notice.order_review_projection import serialize_review_case from app.services.shipping_notice.order_review_projection import serialize_review_case
from app.services.shipping_notice.order_schema.field_rules import ( from app.services.shipping_notice.order_schema.field_rules import (
is_valid_line_no_value,
normalize_order_field_value, normalize_order_field_value,
validate_order_field_value, validate_order_field_value,
) )
@@ -335,21 +334,21 @@ def _machine_value(machine_fields: list[Any], field_id: str) -> Any:
def _find_line( def _find_line(
case: ShippingOrderReviewCase, case: ShippingOrderReviewCase,
lines: list[dict[str, Any]], lines: list[dict[str, Any]],
line_key: str, draft_line_id: str,
*, *,
actor_id: int, actor_id: int,
action: str, action: str,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""按稳定 line_key 获取草稿行;不存在时写拒绝审计。""" """按稳定 draft_line_id 获取草稿行;不存在时写拒绝审计。"""
for item in lines: for item in lines:
if isinstance(item, dict) and str(item.get('line_key') or '') == str(line_key or ''): if isinstance(item, dict) and str(item.get('draft_line_id') or '') == str(draft_line_id or ''):
return item return item
_reject_draft_operation( _reject_draft_operation(
case, case,
actor_id=actor_id, actor_id=actor_id,
action=action, action=action,
error=ValidationError('Review line is unavailable', code='SHIPPING.REVIEW_LINE_NOT_FOUND'), error=ValidationError('Review line is unavailable', code='SHIPPING.REVIEW_LINE_NOT_FOUND'),
metadata={'line_key': str(line_key or '')[:64] or None}, metadata={'draft_line_id': str(draft_line_id or '')[:128] or None},
) )
@@ -400,14 +399,6 @@ def draft_has_unaccepted_llm_suggestions(case: ShippingOrderReviewCase) -> bool:
return False return False
LINE_NO_OVERRIDE_REASON_CODES = frozenset({
'recognition_error',
'customer_line_exception',
'business_correction',
'other',
})
def _set_value(container: dict[str, Any], field: dict[str, Any], value: Any, *, restore_machine: bool) -> dict[str, Any]: def _set_value(container: dict[str, Any], field: dict[str, Any], value: Any, *, restore_machine: bool) -> dict[str, Any]:
"""写入单字段人工值或移除人工覆盖层;类型规范化始终按冻结字段规则执行。""" """写入单字段人工值或移除人工覆盖层;类型规范化始终按冻结字段规则执行。"""
values = dict(container.get('values') or {}) values = dict(container.get('values') or {})
@@ -476,9 +467,9 @@ def _validation(
line[str(field.get('field_code') or field_id)] = value line[str(field.get('field_code') or field_id)] = value
normalized = normalize_order_field_value(value, field) normalized = normalize_order_field_value(value, field)
if field.get('required') and normalized in (None, ''): if field.get('required') and normalized in (None, ''):
issues.append({'code': 'required_field_missing', 'field_id': field_id, 'line_key': raw_line.get('line_key'), 'severity': 'blocking'}) issues.append({'code': 'required_field_missing', 'field_id': field_id, 'draft_line_id': raw_line.get('draft_line_id'), 'severity': 'blocking'})
elif normalized is not None and not validate_order_field_value(normalized, field): elif normalized is not None and not validate_order_field_value(normalized, field):
issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'line_key': raw_line.get('line_key'), 'severity': 'blocking'}) issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'draft_line_id': raw_line.get('draft_line_id'), 'severity': 'blocking'})
lines.append(line) lines.append(line)
line_metas.append(raw_line) line_metas.append(raw_line)
@@ -512,8 +503,13 @@ def _validation(
if isinstance(item, dict): if isinstance(item, dict):
issues.append(dict(item)) issues.append(dict(item))
# 人工确认只看 blocking;五门禁 severity=auto_create_blocking 不阻断 can_build。 # 人工确认只看 blocking;五门禁 severity=auto_create_blocking 不阻断 can_build。
# 库存源路由属于确认后由正式 inventory_source_routing Gate 处理的事实,
# 这里不得把 inventory_source_routing 的 blocking 项重新纳入(eligibility.can_build 已排除),
# 否则"仅库存源未定"的订单会再次被判 needs_review,与"确认只确认订单信息"冲突。
can_build = bool(eligibility.get('can_build')) and not any( can_build = bool(eligibility.get('can_build')) and not any(
str(item.get('severity') or '') == 'blocking' for item in issues str(item.get('severity') or '') == 'blocking'
and str(item.get('owning_gate_code') or '') != 'inventory_source_routing'
for item in issues
) )
# [STEP 2] 为缺失/无效字段补齐 field_code + display_name,禁止只返回裸 code。 # [STEP 2] 为缺失/无效字段补齐 field_code + display_name,禁止只返回裸 code。
enriched_issues: list[dict[str, Any]] = [] enriched_issues: list[dict[str, Any]] = []
@@ -563,14 +559,14 @@ def _validation(
def build_confirmable_draft_summary( def build_confirmable_draft_summary(
case: ShippingOrderReviewCase, case: ShippingOrderReviewCase,
*, *,
line_keys: list[str] | None = None, draft_line_ids: list[str] | None = None,
) -> tuple[dict[str, Any], dict[str, Any]]: ) -> tuple[dict[str, Any], dict[str, Any]]:
""" """
从冻结 Schema 投影完整草稿并重跑确认校验,供原子建单服务使用。 从冻结 Schema 投影完整草稿并重跑确认校验,供原子建单服务使用。
Args: Args:
case: 复核 Case。 case: 复核 Case。
line_keys: 可选;仅投影这些完整明细行(履约波次),禁止拆分数量。 draft_line_ids: 可选;仅投影这些完整明细行(履约波次),禁止拆分数量。
Returns: Returns:
(summary, validation) 元组。 (summary, validation) 元组。
@@ -583,17 +579,17 @@ def build_confirmable_draft_summary(
if str(field.get('scope') or '') == 'header' if str(field.get('scope') or '') == 'header'
} }
raw_lines = [item for item in (case.current_draft.lines_json or []) if isinstance(item, dict)] raw_lines = [item for item in (case.current_draft.lines_json or []) if isinstance(item, dict)]
if line_keys is not None: if draft_line_ids is not None:
wanted = {str(k).strip() for k in line_keys if str(k).strip()} wanted = {str(k).strip() for k in draft_line_ids if str(k).strip()}
filtered: list[dict[str, Any]] = [] filtered: list[dict[str, Any]] = []
for idx, raw_line in enumerate(raw_lines): for idx, raw_line in enumerate(raw_lines):
key = str(raw_line.get('line_key') or '').strip() or f'line-{idx + 1}' key = str(raw_line.get('draft_line_id') or '').strip()
if key in wanted: if key in wanted:
filtered.append(raw_line) filtered.append(raw_line)
if len(filtered) != len(wanted): if len(filtered) != len(wanted):
from app.core.errors import ValidationError from app.core.errors import ValidationError
raise ValidationError( raise ValidationError(
'One or more line_keys not found in draft', 'One or more draft_line_ids not found in draft',
code='SHIPPING.REVIEW_LINE_NOT_FOUND', code='SHIPPING.REVIEW_LINE_NOT_FOUND',
) )
raw_lines = filtered raw_lines = filtered
@@ -605,11 +601,11 @@ def build_confirmable_draft_summary(
} }
for raw_line in raw_lines for raw_line in raw_lines
] ]
# 波次建单时保留草稿行键,供血缘与决定回写对齐。 # 波次建单时保留草稿行身份,供血缘与决定回写对齐。
for idx, raw_line in enumerate(raw_lines): for idx, raw_line in enumerate(raw_lines):
key = str(raw_line.get('line_key') or '').strip() key = str(raw_line.get('draft_line_id') or '').strip()
if key and idx < len(lines): if key and idx < len(lines):
lines[idx]['line_key'] = key lines[idx]['draft_line_id'] = key
# [STEP] 履约波次必须按选中行重算 can_build/status,禁止继承未选中行的整单失败态。 # [STEP] 履约波次必须按选中行重算 can_build/status,禁止继承未选中行的整单失败态。
validation = _validation(case, raw_lines=raw_lines) validation = _validation(case, raw_lines=raw_lines)
return {**header, 'lines': lines}, validation return {**header, 'lines': lines}, validation
@@ -719,11 +715,11 @@ def _record_change(
operation_json=operation, operation_json=operation,
)) ))
changed_paths = [ changed_paths = [
key for key in ('field_id', 'line_key', 'action') key for key in ('field_id', 'draft_line_id', 'action')
if key in operation and operation.get(key) is not None if key in operation and operation.get(key) is not None
] ]
field_id = operation.get('field_id') field_id = operation.get('field_id')
line_key = operation.get('line_key') draft_line_id = operation.get('draft_line_id')
previous_value = _audit_scalar(operation.get('previous_value')) previous_value = _audit_scalar(operation.get('previous_value'))
new_value = _audit_scalar(operation.get('value') if 'value' in operation else operation.get('new_value')) new_value = _audit_scalar(operation.get('value') if 'value' in operation else operation.get('new_value'))
value_source = str(operation.get('source') or '')[:32] or None value_source = str(operation.get('source') or '')[:32] or None
@@ -751,9 +747,9 @@ def _record_change(
after_snapshot['new_value'] = new_value after_snapshot['new_value'] = new_value
if value_source: if value_source:
after_snapshot['value_source'] = value_source after_snapshot['value_source'] = value_source
if line_key is not None: if draft_line_id is not None:
before_snapshot['line_key'] = str(line_key)[:64] before_snapshot['draft_line_id'] = str(draft_line_id)[:128]
after_snapshot['line_key'] = str(line_key)[:64] after_snapshot['draft_line_id'] = str(draft_line_id)[:128]
# [STEP] 库存路由恢复:把候选与规则版本写入前后快照,供审计中心展示。 # [STEP] 库存路由恢复:把候选与规则版本写入前后快照,供审计中心展示。
if str(event_type or '').startswith('inventory_routing_'): if str(event_type or '').startswith('inventory_routing_'):
before_raw = operation.get('previous_value') before_raw = operation.get('previous_value')
@@ -797,8 +793,8 @@ def _record_change(
after_snapshot['action_semantics'] = str(operation.get('action_semantics'))[:64] after_snapshot['action_semantics'] = str(operation.get('action_semantics'))[:64]
if operation.get('idempotency_key'): if operation.get('idempotency_key'):
after_snapshot['idempotency_key'] = str(operation.get('idempotency_key'))[:128] after_snapshot['idempotency_key'] = str(operation.get('idempotency_key'))[:128]
if operation.get('line_keys') is not None: if operation.get('draft_line_ids') is not None:
after_snapshot['line_keys'] = [str(item)[:64] for item in list(operation.get('line_keys') or [])[:50]] after_snapshot['draft_line_ids'] = [str(item)[:128] for item in list(operation.get('draft_line_ids') or [])[:50]]
# 恢复机器值使用独立事件类型,便于坐标/字段证据反查(阶段 5)。 # 恢复机器值使用独立事件类型,便于坐标/字段证据反查(阶段 5)。
audit_event_type = ( audit_event_type = (
'review_field_restored_machine' 'review_field_restored_machine'
@@ -887,139 +883,31 @@ def patch_line_field(
*, *,
user_id: int, user_id: int,
case_no: str, case_no: str,
line_key: str, draft_line_id: str,
field_id: str, field_id: str,
value: Any, value: Any,
expected_draft_version: Any, expected_draft_version: Any,
restore_machine: bool = False, restore_machine: bool = False,
override_reason_code: str | None = None,
override_reason_text: str | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
""" """
编辑或恢复一条明细字段;行由不可变 line_key 定位并受同一草稿版本锁保护。 编辑或恢复一条明细字段;行由不可变 draft_line_id 定位并受同一草稿版本锁保护。
核心逻辑:一般字段沿用 manual 覆盖;内部项次 line_no 覆盖须原因分类并锁定; 核心逻辑:一般字段沿用 manual 覆盖;内部项次 line_no 是系统项次,禁止覆盖或恢复。
恢复时清除 override,回退到草稿 machine_fields 中的识别/派生投影(不重新跑派生引擎),
并写 LINE_NO_RESTORED。
""" """
action = 'line_field_changed' action = 'line_field_changed'
case = _locked_case(user_id=user_id, case_no=case_no, action=action) case = _locked_case(user_id=user_id, case_no=case_no, action=action)
_assert_version(case, expected_draft_version, actor_id=user_id, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action)
field = _require_field(case, field_id, 'line', actor_id=user_id, action=action) field = _require_field(case, field_id, 'line', actor_id=user_id, action=action)
lines = copy.deepcopy(list(case.current_draft.lines_json or [])) lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target = _find_line(case, lines, line_key, actor_id=user_id, action=action) target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action)
previous_value = _current_value(target, field_id) previous_value = _current_value(target, field_id)
field_code = str(field.get('field_code') or '') field_code = str(field.get('field_code') or '')
if field_code == 'line_no' and restore_machine: if field_code == 'line_no':
prior_entry = (target.get('values') or {}).get(field_id) if isinstance(target.get('values'), dict) else None
prior_source = str((prior_entry or {}).get('source') or 'manual_override')
change = _set_value(target, field, value, restore_machine=True)
# 恢复后的展示值来自 machine_fields:初始化草稿时已含识别/派生投影,非二次派生。
restored_source = 'machine_or_derived_projection'
case.current_draft.lines_json = lines
result = _record_change(
case,
actor_id=user_id,
event_type=action,
operation={
'line_key': line_key,
'field_id': field_id,
'field_code': field_code,
'previous_value': previous_value,
'restored_source': restored_source,
'prior_value_source': prior_source,
**change,
},
)
append_shipping_audit_event(
event_type='LINE_NO_RESTORED',
aggregate_type='shipping_order_review_case',
aggregate_id=str(case.case_no),
actor_type='user',
actor_id=user_id,
review_case_no=str(case.case_no),
action='restore_line_no',
result='success',
metadata={
'line_key': line_key,
'field_code': 'line_no',
'restored_source': restored_source,
'prior_value_source': prior_source,
},
before={'previous_value': previous_value, 'value_source': prior_source},
after={'new_value': change.get('value'), 'value_source': restored_source},
)
return result
if field_code == 'line_no' and not restore_machine:
reason_code = str(override_reason_code or '').strip()
reason_text = str(override_reason_text or '').strip()
if reason_code not in LINE_NO_OVERRIDE_REASON_CODES:
raise ValidationError( raise ValidationError(
'line_no override requires a valid reason code', 'line_no is system-generated and cannot be edited or restored',
code='SHIPPING.REVIEW_LINE_NO_OVERRIDE_REASON_REQUIRED', code='SHIPPING.REVIEW_LINE_NO_IMMUTABLE',
) )
if reason_code == 'other' and not reason_text:
raise ValidationError(
'line_no override reason text is required for other',
code='SHIPPING.REVIEW_LINE_NO_OVERRIDE_TEXT_REQUIRED',
)
if not is_valid_line_no_value(value):
raise ValidationError(
'line_no must be 1-6 digits',
code='SHIPPING.REVIEW_LINE_NO_FORMAT_INVALID',
)
change = _set_value(target, field, value, restore_machine=False)
values = dict(target.get('values') or {})
values[str(field['field_id'])] = {
'value': change['value'],
'source': 'manual_override',
'locked': True,
'override_reason_code': reason_code,
'override_reason_text': reason_text or None,
}
target['values'] = values
change = {
**change,
'source': 'manual_override',
'override_reason_code': reason_code,
'override_reason_text': reason_text or None,
'locked': True,
}
case.current_draft.lines_json = lines
result = _record_change(
case,
actor_id=user_id,
event_type=action,
operation={
'line_key': line_key,
'field_id': field_id,
'field_code': field_code,
'previous_value': previous_value,
**change,
},
)
append_shipping_audit_event(
event_type='LINE_NO_OVERRIDDEN',
aggregate_type='shipping_order_review_case',
aggregate_id=str(case.case_no),
actor_type='user',
actor_id=user_id,
review_case_no=str(case.case_no),
action='override_line_no',
result='success',
reason_code=reason_code,
reason=reason_text or None,
metadata={
'line_key': line_key,
'field_code': 'line_no',
'override_reason_code': reason_code,
},
before={'previous_value': previous_value, 'value_source': 'prior'},
after={'new_value': change['value'], 'value_source': 'manual_override'},
)
return result
change = _set_value(target, field, value, restore_machine=restore_machine) change = _set_value(target, field, value, restore_machine=restore_machine)
case.current_draft.lines_json = lines case.current_draft.lines_json = lines
@@ -1028,7 +916,7 @@ def patch_line_field(
actor_id=user_id, actor_id=user_id,
event_type=action, event_type=action,
operation={ operation={
'line_key': line_key, 'draft_line_id': draft_line_id,
'field_id': field_id, 'field_id': field_id,
'previous_value': previous_value, 'previous_value': previous_value,
**change, **change,
@@ -1042,34 +930,34 @@ def add_line(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict
case = _locked_case(user_id=user_id, case_no=case_no, action=action) case = _locked_case(user_id=user_id, case_no=case_no, action=action)
_assert_version(case, expected_draft_version, actor_id=user_id, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action)
lines = copy.deepcopy(list(case.current_draft.lines_json or [])) lines = copy.deepcopy(list(case.current_draft.lines_json or []))
line_key = f'manual-{uuid.uuid4().hex[:16]}' draft_line_id = str(uuid.uuid4())
lines.append({'line_key': line_key, 'machine_fields': [], 'values': {}}) lines.append({'draft_line_id': draft_line_id, 'machine_fields': [], 'values': {}})
case.current_draft.lines_json = lines case.current_draft.lines_json = lines
return _record_change(case, actor_id=user_id, event_type=action, operation={'line_key': line_key}) return _record_change(case, actor_id=user_id, event_type=action, operation={'draft_line_id': draft_line_id})
def copy_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]: def copy_line(*, user_id: int, case_no: str, draft_line_id: str, expected_draft_version: Any) -> dict[str, Any]:
"""复制明细为新 line_key;复制后的 Reservation 重复会由全量校验显式阻断。""" """复制明细为新 draft_line_id;复制后的 Reservation 重复会由全量校验显式阻断。"""
action = 'line_copied' action = 'line_copied'
case = _locked_case(user_id=user_id, case_no=case_no, action=action) case = _locked_case(user_id=user_id, case_no=case_no, action=action)
_assert_version(case, expected_draft_version, actor_id=user_id, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action)
lines = copy.deepcopy(list(case.current_draft.lines_json or [])) lines = copy.deepcopy(list(case.current_draft.lines_json or []))
copied = copy.deepcopy(_find_line(case, lines, line_key, actor_id=user_id, action=action)) copied = copy.deepcopy(_find_line(case, lines, draft_line_id, actor_id=user_id, action=action))
copied['line_key'] = f'manual-{uuid.uuid4().hex[:16]}' copied['draft_line_id'] = str(uuid.uuid4())
lines.append(copied) lines.append(copied)
case.current_draft.lines_json = lines case.current_draft.lines_json = lines
return _record_change(case, actor_id=user_id, event_type=action, operation={'source_line_key': line_key, 'line_key': copied['line_key']}) return _record_change(case, actor_id=user_id, event_type=action, operation={'source_draft_line_id': draft_line_id, 'draft_line_id': copied['draft_line_id']})
def delete_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]: def delete_line(*, user_id: int, case_no: str, draft_line_id: str, expected_draft_version: Any) -> dict[str, Any]:
"""删除单条草稿行并写审计;删除最后有效行会保留为阻断校验结果。""" """删除单条草稿行并写审计;删除最后有效行会保留为阻断校验结果。"""
action = 'line_deleted' action = 'line_deleted'
case = _locked_case(user_id=user_id, case_no=case_no, action=action) case = _locked_case(user_id=user_id, case_no=case_no, action=action)
_assert_version(case, expected_draft_version, actor_id=user_id, action=action) _assert_version(case, expected_draft_version, actor_id=user_id, action=action)
lines = copy.deepcopy(list(case.current_draft.lines_json or [])) lines = copy.deepcopy(list(case.current_draft.lines_json or []))
_find_line(case, lines, line_key, actor_id=user_id, action=action) _find_line(case, lines, draft_line_id, actor_id=user_id, action=action)
case.current_draft.lines_json = [item for item in lines if str(item.get('line_key') or '') != str(line_key)] case.current_draft.lines_json = [item for item in lines if str(item.get('draft_line_id') or '') != str(draft_line_id)]
return _record_change(case, actor_id=user_id, event_type=action, operation={'line_key': line_key}) return _record_change(case, actor_id=user_id, event_type=action, operation={'draft_line_id': draft_line_id})
def validate_draft(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]: def validate_draft(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]:
@@ -1102,7 +990,7 @@ def _routing_idempotency_entry_key(*, action: str, idempotency_key: str) -> str:
生成幂等历史条目键(动作 + 幂等键)。 生成幂等历史条目键(动作 + 幂等键)。
Args: Args:
action: 路由恢复动作(可含 line_key 后缀)。 action: 路由恢复动作(可含 draft_line_id 后缀)。
idempotency_key: 已规范化的幂等键。 idempotency_key: 已规范化的幂等键。
Returns: Returns:
@@ -1166,7 +1054,7 @@ def _store_routing_recovery_idempotency(
*, *,
action: str, action: str,
idempotency_key: str, idempotency_key: str,
line_keys: list[str], draft_line_ids: list[str],
) -> None: ) -> None:
""" """
将成功的路由恢复幂等键追加写入 Draft 历史集合(非整对象覆盖)。 将成功的路由恢复幂等键追加写入 Draft 历史集合(非整对象覆盖)。
@@ -1184,7 +1072,7 @@ def _store_routing_recovery_idempotency(
record = { record = {
'idempotency_key': key, 'idempotency_key': key,
'action': action, 'action': action,
'line_keys': [str(item)[:64] for item in line_keys[:50]], 'draft_line_ids': [str(item)[:128] for item in draft_line_ids[:50]],
'draft_version_after': int(draft.draft_version) + 1, 'draft_version_after': int(draft.draft_version) + 1,
} }
entries[entry_key] = record entries[entry_key] = record
@@ -1214,7 +1102,7 @@ def _line_routing_snapshot(line: dict[str, Any], fields: dict[str, dict[str, Any
line_meta=line, line_meta=line,
) )
return { return {
'line_key': str(line.get('line_key') or '')[:64], 'draft_line_id': str(line.get('draft_line_id') or '')[:128],
'selection_mode': projection.get('selection_mode'), 'selection_mode': projection.get('selection_mode'),
'candidate_inventory_source_codes': list(projection.get('candidate_inventory_source_codes') or []), 'candidate_inventory_source_codes': list(projection.get('candidate_inventory_source_codes') or []),
'raw_rule_source_codes': list(projection.get('raw_rule_source_codes') or []), 'raw_rule_source_codes': list(projection.get('raw_rule_source_codes') or []),
@@ -1243,7 +1131,7 @@ def reroute_inventory_routing(
case_no: str, case_no: str,
expected_draft_version: Any, expected_draft_version: Any,
idempotency_key: str | None = None, idempotency_key: str | None = None,
line_key: str | None = None, draft_line_id: str | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
""" """
按最新已发布规则与库存源启停重算库存路由;不重新识别 PDF。 按最新已发布规则与库存源启停重算库存路由;不重新识别 PDF。
@@ -1256,7 +1144,7 @@ def reroute_inventory_routing(
case_no: 复核 Case 编号。 case_no: 复核 Case 编号。
expected_draft_version: 乐观锁版本。 expected_draft_version: 乐观锁版本。
idempotency_key: 可选幂等键。 idempotency_key: 可选幂等键。
line_key: 可选,仅重算指定行;缺省整单。 draft_line_id: 可选,仅重算指定行;缺省整单。
Returns: Returns:
序列化后的 Case 详情。 序列化后的 Case 详情。
@@ -1271,7 +1159,7 @@ def reroute_inventory_routing(
fields = _schema_fields(case) fields = _schema_fields(case)
header_by_code = _header_by_code_for_case(case, fields) header_by_code = _header_by_code_for_case(case, fields)
lines = copy.deepcopy(list(case.current_draft.lines_json or [])) lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target_key = str(line_key or '').strip() target_key = str(draft_line_id or '').strip()
before_rows: list[dict[str, Any]] = [] before_rows: list[dict[str, Any]] = []
after_rows: list[dict[str, Any]] = [] after_rows: list[dict[str, Any]] = []
touched_keys: list[str] = [] touched_keys: list[str] = []
@@ -1279,7 +1167,7 @@ def reroute_inventory_routing(
for raw in lines: for raw in lines:
if not isinstance(raw, dict): if not isinstance(raw, dict):
continue continue
current_key = str(raw.get('line_key') or '').strip() current_key = str(raw.get('draft_line_id') or '').strip()
if target_key and current_key != target_key: if target_key and current_key != target_key:
continue continue
if not current_key: if not current_key:
@@ -1305,7 +1193,7 @@ def reroute_inventory_routing(
actor_id=user_id, actor_id=user_id,
action=action, action=action,
error=NotFoundError('Order review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND'), error=NotFoundError('Order review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND'),
metadata={'line_key': target_key[:64]}, metadata={'draft_line_id': target_key[:128]},
) )
case.current_draft.lines_json = lines case.current_draft.lines_json = lines
@@ -1313,15 +1201,15 @@ def reroute_inventory_routing(
case, case,
action=action, action=action,
idempotency_key=str(idempotency_key or ''), idempotency_key=str(idempotency_key or ''),
line_keys=touched_keys, draft_line_ids=touched_keys,
) )
return _record_change( return _record_change(
case, case,
actor_id=user_id, actor_id=user_id,
event_type=action, event_type=action,
operation={ operation={
'line_key': target_key or None, 'draft_line_id': target_key or None,
'line_keys': touched_keys, 'draft_line_ids': touched_keys,
'idempotency_key': _normalize_routing_idempotency_key(idempotency_key) or None, 'idempotency_key': _normalize_routing_idempotency_key(idempotency_key) or None,
'previous_value': before_rows[:20], 'previous_value': before_rows[:20],
'new_value': after_rows[:20], 'new_value': after_rows[:20],
@@ -1386,7 +1274,7 @@ def _candidate_conflict_locator(case: ShippingOrderReviewCase) -> dict[str, Any]
return { return {
'field_code': field_code, 'field_code': field_code,
'line_index': conflict.get('line_index'), 'line_index': conflict.get('line_index'),
'line_key': conflict.get('line_key'), 'draft_line_id': conflict.get('draft_line_id'),
} }
return {} return {}
@@ -1462,7 +1350,7 @@ def _sync_review_gates_safe(
default_reason_code='field_conflict', default_reason_code='field_conflict',
details={ details={
**base_details, **base_details,
'line_key': primary_conflict.get('line_key') or conflict_locator.get('line_key'), 'draft_line_id': primary_conflict.get('draft_line_id') or conflict_locator.get('draft_line_id'),
'line_index': primary_conflict.get('line_index') 'line_index': primary_conflict.get('line_index')
if primary_conflict.get('line_index') is not None else conflict_locator.get('line_index'), if primary_conflict.get('line_index') is not None else conflict_locator.get('line_index'),
'field_code': primary_conflict.get('field_code') or conflict_locator.get('field_code'), 'field_code': primary_conflict.get('field_code') or conflict_locator.get('field_code'),
@@ -1496,7 +1384,7 @@ def _sync_review_gates_safe(
) or default_reason ) or default_reason
sync_details = { sync_details = {
**base_details, **base_details,
'line_key': primary.get('line_key'), 'draft_line_id': primary.get('draft_line_id'),
'line_index': primary.get('line_index'), 'line_index': primary.get('line_index'),
'field_code': primary.get('field_code'), 'field_code': primary.get('field_code'),
'issue_codes': [ 'issue_codes': [
@@ -1517,12 +1405,8 @@ def _sync_review_gates_safe(
inventory_issues = _blocking_issues_for_gate(result, 'inventory_source_routing') inventory_issues = _blocking_issues_for_gate(result, 'inventory_source_routing')
if not inventory_issues: if not inventory_issues:
sync_inventory_routing_gate_for_case( # 复核草稿阶段只能评估路由结果,正式 CandidateSet 需绑定确认后的 Task;
case=case, # 因此不得在 draft_validated 时提前通过正式 inventory_source_routing Gate。
passed=True,
actor_id=int(user_id),
details=base_details,
)
return return
primary = inventory_issues[0] primary = inventory_issues[0]
@@ -1558,7 +1442,7 @@ def _sync_review_gates_safe(
'unavailable_source_codes': list(dict.fromkeys(unavailable_codes)), 'unavailable_source_codes': list(dict.fromkeys(unavailable_codes)),
'raw_rule_source_codes': list(dict.fromkeys(raw_codes)), 'raw_rule_source_codes': list(dict.fromkeys(raw_codes)),
'matched_rule_codes': list(dict.fromkeys(matched_rule_codes)), 'matched_rule_codes': list(dict.fromkeys(matched_rule_codes)),
'line_key': primary.get('line_key'), 'draft_line_id': primary.get('draft_line_id'),
'line_index': primary.get('line_index'), 'line_index': primary.get('line_index'),
'candidate_inventory_source_codes': list(primary.get('candidate_inventory_source_codes') or []), 'candidate_inventory_source_codes': list(primary.get('candidate_inventory_source_codes') or []),
}, },
@@ -1599,7 +1483,7 @@ def apply_llm_suggestion_prefill(
user_id: int, user_id: int,
case_no: str, case_no: str,
field_id: str, field_id: str,
line_key: str | None, draft_line_id: str | None,
value: Any, value: Any,
suggestion_no: str, suggestion_no: str,
expected_draft_version: Any, expected_draft_version: Any,
@@ -1613,7 +1497,7 @@ def apply_llm_suggestion_prefill(
user_id: 操作人。 user_id: 操作人。
case_no: Case 编号。 case_no: Case 编号。
field_id: 字段 ID。 field_id: 字段 ID。
line_key: 行键;表头为 None。 draft_line_id: 草稿行身份;表头为 None。
value: 建议值。 value: 建议值。
suggestion_no: 关联建议编号。 suggestion_no: 关联建议编号。
expected_draft_version: 乐观锁版本。 expected_draft_version: 乐观锁版本。
@@ -1627,13 +1511,13 @@ def apply_llm_suggestion_prefill(
field = _require_field( field = _require_field(
case, case,
field_id, field_id,
'line' if line_key else 'header', 'line' if draft_line_id else 'header',
actor_id=user_id, actor_id=user_id,
action=action, action=action,
) )
if line_key: if draft_line_id:
lines = copy.deepcopy(list(case.current_draft.lines_json or [])) lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target = _find_line(case, lines, line_key, actor_id=user_id, action=action) target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action)
previous_value = _current_value(target, field_id) previous_value = _current_value(target, field_id)
change = _set_llm_suggested_value(target, field, value, suggestion_no=suggestion_no) change = _set_llm_suggested_value(target, field, value, suggestion_no=suggestion_no)
case.current_draft.lines_json = lines case.current_draft.lines_json = lines
@@ -1641,7 +1525,7 @@ def apply_llm_suggestion_prefill(
case, case,
actor_id=user_id, actor_id=user_id,
event_type=action, event_type=action,
operation={'line_key': line_key, 'field_id': field_id, 'previous_value': previous_value, **change}, operation={'draft_line_id': draft_line_id, 'field_id': field_id, 'previous_value': previous_value, **change},
) )
header = dict(case.current_draft.header_values_json or {}) header = dict(case.current_draft.header_values_json or {})
previous_value = _current_value(header, field_id) previous_value = _current_value(header, field_id)
@@ -1692,10 +1576,10 @@ def adjudicate_llm_suggestion_on_draft(
actor_id=user_id, actor_id=user_id,
action=action, action=action,
) )
line_key = suggestion.line_key draft_line_id = suggestion.draft_line_id
if line_key: if draft_line_id:
lines = copy.deepcopy(list(case.current_draft.lines_json or [])) lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target = _find_line(case, lines, line_key, actor_id=user_id, action=action) target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action)
previous_value = _current_value(target, suggestion.field_id) previous_value = _current_value(target, suggestion.field_id)
if decision == 'reject': if decision == 'reject':
values = dict(target.get('values') or {}) values = dict(target.get('values') or {})
@@ -1731,7 +1615,7 @@ def adjudicate_llm_suggestion_on_draft(
actor_id=user_id, actor_id=user_id,
event_type=action, event_type=action,
operation={ operation={
'line_key': line_key, 'draft_line_id': draft_line_id,
'field_id': suggestion.field_id, 'field_id': suggestion.field_id,
'suggestion_no': suggestion.suggestion_no, 'suggestion_no': suggestion.suggestion_no,
'previous_value': previous_value, 'previous_value': previous_value,
@@ -3,7 +3,7 @@ services/shipping_notice/order_review_evidence_selector.py
用途:为订单复核 AI 建议选择最小证据包(字段→单元格→表格→页面)。 用途:为订单复核 AI 建议选择最小证据包(字段→单元格→表格→页面)。
依赖:Run 冻结 layout_snapshot / layout_schema_candidates。 依赖:Run 冻结 layout_snapshot / layout_schema_candidates。
逻辑:默认不超过 L3;明细必须绑定 line_key/行号;禁止写入 secret、临时签名 URL、完整请求头。 逻辑:默认不超过 L3;明细必须绑定 draft_line_id/行号;禁止写入 secret、临时签名 URL、完整请求头。
""" """
from __future__ import annotations from __future__ import annotations
@@ -42,7 +42,7 @@ def select_review_evidence_pack(
Args: Args:
document: 冻结 Document 快照。 document: 冻结 Document 快照。
target_fields: 待建议字段定位信息(须含 field_id;明细须含 line_key)。 target_fields: 待建议字段定位信息(须含 field_id;明细须含 draft_line_id)。
evidence_level: L1–L4。 evidence_level: L1–L4。
allow_full_pdf: 仅管理员显式 True 时允许 L4。 allow_full_pdf: 仅管理员显式 True 时允许 L4。
@@ -84,16 +84,16 @@ def select_review_evidence_pack(
hit_table_ids: set[str] = set() hit_table_ids: set[str] = set()
hit_page_nos: set[int] = set() hit_page_nos: set[int] = set()
# [STEP 1] L1:目标字段相邻 cell 文本;明细必须按 line_key 过滤。 # [STEP 1] L1:目标字段相邻 cell 文本;明细必须按 draft_line_id 过滤。
for target in target_fields: for target in target_fields:
if not isinstance(target, dict): if not isinstance(target, dict):
continue continue
field_id = str(target.get('field_id') or '') field_id = str(target.get('field_id') or '')
line_key = str(target.get('line_key') or '').strip() or None draft_line_id = str(target.get('draft_line_id') or '').strip() or None
snippets = _field_snippets( snippets = _field_snippets(
candidates, candidates,
field_id=field_id, field_id=field_id,
line_key=line_key, draft_line_id=draft_line_id,
line_number=target.get('line_number'), line_number=target.get('line_number'),
) )
for snippet in snippets: for snippet in snippets:
@@ -107,7 +107,7 @@ def select_review_evidence_pack(
'field_id': field_id, 'field_id': field_id,
'field_code': target.get('field_code'), 'field_code': target.get('field_code'),
'scope': target.get('scope'), 'scope': target.get('scope'),
'line_key': line_key, 'draft_line_id': draft_line_id,
'line_number': target.get('line_number'), 'line_number': target.get('line_number'),
'snippets': snippets[:8], 'snippets': snippets[:8],
}) })
@@ -157,11 +157,11 @@ def _field_snippets(
candidates: list[dict[str, Any]], candidates: list[dict[str, Any]],
*, *,
field_id: str, field_id: str,
line_key: str | None = None, draft_line_id: str | None = None,
line_number: Any = None, line_number: Any = None,
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
""" """
收集目标 field_id 的短引文;明细行必须绑定 line_key / 行号。 收集目标 field_id 的短引文;明细行必须绑定 draft_line_id / 行号。
核心逻辑:header 字段可跨行收集;line 字段仅保留匹配目标行的 cell,禁止串行。 核心逻辑:header 字段可跨行收集;line 字段仅保留匹配目标行的 cell,禁止串行。
""" """
@@ -170,7 +170,7 @@ def _field_snippets(
for row in candidate.get('rows') or []: for row in candidate.get('rows') or []:
if not isinstance(row, dict): if not isinstance(row, dict):
continue continue
if not _row_matches_line(row, line_key=line_key, line_number=line_number): if not _row_matches_line(row, draft_line_id=draft_line_id, line_number=line_number):
continue continue
for field in row.get('fields') or []: for field in row.get('fields') or []:
if not isinstance(field, dict) or str(field.get('field_id') or '') != field_id: if not isinstance(field, dict) or str(field.get('field_id') or '') != field_id:
@@ -181,7 +181,7 @@ def _field_snippets(
'page_no': int(candidate.get('page_no') or field.get('page_no') or 1), 'page_no': int(candidate.get('page_no') or field.get('page_no') or 1),
'table_id': str(candidate.get('table_id') or field.get('table_id') or ''), 'table_id': str(candidate.get('table_id') or field.get('table_id') or ''),
'row_index': int(row.get('row_index') or 0), 'row_index': int(row.get('row_index') or 0),
'line_key': str(row.get('line_key') or line_key or '') or None, 'draft_line_id': str(row.get('draft_line_id') or draft_line_id or '') or None,
'cell_id': str(field.get('cell_id') or '') or None, 'cell_id': str(field.get('cell_id') or '') or None,
'quote': quote[:500], 'quote': quote[:500],
}) })
@@ -191,17 +191,17 @@ def _field_snippets(
def _row_matches_line( def _row_matches_line(
row: dict[str, Any], row: dict[str, Any],
*, *,
line_key: str | None, draft_line_id: str | None,
line_number: Any, line_number: Any,
) -> bool: ) -> bool:
"""判断布局行是否对应目标明细;无 line_key 时视为表头字段(允许任意行)。""" """判断布局行是否对应目标明细;无 draft_line_id 时视为表头字段(允许任意行)。"""
if not line_key and line_number is None: if not draft_line_id and line_number is None:
return True return True
row_line_key = str(row.get('line_key') or '').strip() row_draft_line_id = str(row.get('draft_line_id') or '').strip()
# [STEP] 行上已有 line_key 时只做精确匹配,禁止再按 row_index 宽松回退。 # [STEP] 行上已有 draft_line_id 时只做精确匹配,禁止再按 row_index 宽松回退。
if line_key and row_line_key: if draft_line_id and row_draft_line_id:
return row_line_key == line_key return row_draft_line_id == draft_line_id
target_index = _line_key_to_index(line_key) target_index = _draft_line_id_to_index(draft_line_id)
if target_index is None and line_number is not None: if target_index is None and line_number is not None:
try: try:
target_index = int(line_number) target_index = int(line_number)
@@ -216,16 +216,16 @@ def _row_matches_line(
return int(data_position) == target_index return int(data_position) == target_index
except (TypeError, ValueError): except (TypeError, ValueError):
return False return False
# 兼容仅有 1-based row_index 的布局行(无 line_key)。 # 布局行没有草稿身份时,仅按显式行号定位。
row_index = int(row.get('row_index') or -1) row_index = int(row.get('row_index') or -1)
return row_index == target_index + 1 return row_index == target_index + 1
def _line_key_to_index(line_key: str | None) -> int | None: def _draft_line_id_to_index(draft_line_id: str | None) -> int | None:
"""将 machine-N 行键转换为 0-based 行序号。""" """将 machine-N 草稿行身份转换为 0-based 行序号。"""
if not line_key: if not draft_line_id:
return None return None
matched = _MACHINE_LINE_KEY.match(str(line_key).strip()) matched = _MACHINE_LINE_KEY.match(str(draft_line_id).strip())
if not matched: if not matched:
return None return None
return max(int(matched.group(1)) - 1, 0) return max(int(matched.group(1)) - 1, 0)
@@ -275,7 +275,7 @@ def _strip_forbidden(value: Any) -> Any:
_FIELD_CORE_PRIORITY = ( _FIELD_CORE_PRIORITY = (
'field_id', 'value', 'quote', 'evidence_ref', 'field_code', 'field_id', 'value', 'quote', 'evidence_ref', 'field_code',
'scope', 'line_key', 'llm_context_policy', 'mask_rule', 'value_source', 'scope', 'draft_line_id', 'llm_context_policy', 'mask_rule', 'value_source',
) )
@@ -322,8 +322,8 @@ def _serialize_field_view(
if not strip_secondary_for_token: if not strip_secondary_for_token:
out['field_code'] = fc out['field_code'] = fc
out['scope'] = fv.get('scope') out['scope'] = fv.get('scope')
if fv.get('line_key'): if fv.get('draft_line_id'):
out['line_key'] = fv.get('line_key') out['draft_line_id'] = fv.get('draft_line_id')
out['value'] = sent_value out['value'] = sent_value
out['value_source'] = fv.get('value_source') or 'missing_both' out['value_source'] = fv.get('value_source') or 'missing_both'
if masked.get('policy') == 'masked': if masked.get('policy') == 'masked':
@@ -457,20 +457,20 @@ def _build_v2_field_entry(
) -> tuple[dict[str, Any], bool, bool]: ) -> tuple[dict[str, Any], bool, bool]:
""" """
返回 (field_entry, context_truncated, target_core_trimmed)。 返回 (field_entry, context_truncated, target_core_trimmed)。
field_entry 包含:field_id/field_code/scope/line_key + snippets[] + row_fields[] + field_entry 包含:field_id/field_code/scope/draft_line_id + snippets[] + row_fields[] +
table_headers[] + neighbor_rows[] + page_text[]。 table_headers[] + neighbor_rows[] + page_text[]。
""" """
from app.services.shipping_notice.order_review_evidence_view import get_field_view from app.services.shipping_notice.order_review_evidence_view import get_field_view
field_id = str(target.get('field_id') or '') field_id = str(target.get('field_id') or '')
line_key = str(target.get('line_key') or '').strip() or None draft_line_id = str(target.get('draft_line_id') or '').strip() or None
target_fv = get_field_view(evidence_view, field_id=field_id, line_key=line_key) target_fv = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id)
if target_fv is None: if target_fv is None:
target_fv = { target_fv = {
'field_id': field_id, 'field_id': field_id,
'field_code': target.get('field_code') or field_id, 'field_code': target.get('field_code') or field_id,
'scope': target.get('scope'), 'scope': target.get('scope'),
'line_key': line_key, 'draft_line_id': draft_line_id,
'llm_context_policy': 'allowed', 'llm_context_policy': 'allowed',
'value_source': 'missing_both', 'value_source': 'missing_both',
'field_evidences': [], 'field_evidences': [],
@@ -481,7 +481,7 @@ def _build_v2_field_entry(
'field_id': field_id, 'field_id': field_id,
'field_code': target.get('field_code') or target_fv.get('field_code'), 'field_code': target.get('field_code') or target_fv.get('field_code'),
'scope': target.get('scope') or target_fv.get('scope'), 'scope': target.get('scope') or target_fv.get('scope'),
'line_key': line_key, 'draft_line_id': draft_line_id,
'snippets': [], 'snippets': [],
} }
# snippets:摊平所有 field_evidences 的 quote/value/evidence_ref # snippets:摊平所有 field_evidences 的 quote/value/evidence_ref
@@ -511,11 +511,11 @@ def _build_v2_field_entry(
# [LEVEL] L2_row:行 scope 包含同行其它字段(按 policy 过滤) # [LEVEL] L2_row:行 scope 包含同行其它字段(按 policy 过滤)
if level == 'L2_row': if level == 'L2_row':
line_fields_map = evidence_view.get('line_fields') or {} if line_key else {} line_fields_map = evidence_view.get('line_fields') or {} if draft_line_id else {}
line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} line_map = (line_fields_map.get(draft_line_id) if isinstance(line_fields_map, dict) else {}) or {}
row_field_items: list[dict[str, Any]] = [] row_field_items: list[dict[str, Any]] = []
target_idx = 0 target_idx = 0
if line_key and isinstance(line_map, dict): if draft_line_id and isinstance(line_map, dict):
for fid, fv in line_map.items(): for fid, fv in line_map.items():
if not isinstance(fv, dict): if not isinstance(fv, dict):
continue continue
@@ -580,9 +580,9 @@ def _build_v2_field_entry(
rows = matched_table.get('rows') or [] rows = matched_table.get('rows') or []
ridx = int(row_index) if isinstance(row_index, int) else None ridx = int(row_index) if isinstance(row_index, int) else None
if ridx is None: if ridx is None:
# 没找到 row_index:用 line_key 反查 # 没找到 row_index:用 draft_line_id 反查
for ri, r in enumerate(rows): for ri, r in enumerate(rows):
if isinstance(r, dict) and str(r.get('line_key') or '') == str(line_key or ''): if isinstance(r, dict) and str(r.get('draft_line_id') or '') == str(draft_line_id or ''):
ridx = ri ridx = ri
break break
if ridx is not None: if ridx is not None:
@@ -607,15 +607,15 @@ def _build_v2_field_entry(
}) })
neighbor_rows.append({ neighbor_rows.append({
'row_index': pos, 'row_index': pos,
'line_key': r.get('line_key'), 'draft_line_id': r.get('draft_line_id'),
'cells': cell_values, 'cells': cell_values,
}) })
# 同行字段(复用 L2 逻辑,减少字符预算) # 同行字段(复用 L2 逻辑,减少字符预算)
line_fields_map = (evidence_view.get('line_fields') or {}) if line_key else {} line_fields_map = (evidence_view.get('line_fields') or {}) if draft_line_id else {}
line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} line_map = (line_fields_map.get(draft_line_id) if isinstance(line_fields_map, dict) else {}) or {}
row_field_items: list[dict[str, Any]] = [] row_field_items: list[dict[str, Any]] = []
target_idx = 0 target_idx = 0
if line_key and isinstance(line_map, dict): if draft_line_id and isinstance(line_map, dict):
for fid, fv in line_map.items(): for fid, fv in line_map.items():
if not isinstance(fv, dict): if not isinstance(fv, dict):
continue continue
@@ -674,10 +674,10 @@ def _build_v2_field_entry(
entry['page_blocks'] = page_blocks entry['page_blocks'] = page_blocks
entry['page_no'] = page_no_final entry['page_no'] = page_no_final
# 行字段保留(最小) # 行字段保留(最小)
line_fields_map = (evidence_view.get('line_fields') or {}) if line_key else {} line_fields_map = (evidence_view.get('line_fields') or {}) if draft_line_id else {}
line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {} line_map = (line_fields_map.get(draft_line_id) if isinstance(line_fields_map, dict) else {}) or {}
row_field_items: list[dict[str, Any]] = [] row_field_items: list[dict[str, Any]] = []
if line_key and isinstance(line_map, dict): if draft_line_id and isinstance(line_map, dict):
for fid, fv in line_map.items(): for fid, fv in line_map.items():
if not isinstance(fv, dict): if not isinstance(fv, dict):
continue continue
@@ -529,7 +529,7 @@ def build_minimal_evidence_pack_for_field(
case: ShippingOrderReviewCase, case: ShippingOrderReviewCase,
*, *,
field_id: str, field_id: str,
line_key: str | None = None, draft_line_id: str | None = None,
evidence_level: str = 'L1_field', evidence_level: str = 'L1_field',
allow_full_pdf: bool = False, allow_full_pdf: bool = False,
) -> dict[str, Any]: ) -> dict[str, Any]:
@@ -541,7 +541,7 @@ def build_minimal_evidence_pack_for_field(
Args: Args:
case: 已加载 run 的 Review Case。 case: 已加载 run 的 Review Case。
field_id: 目标 field_id。 field_id: 目标 field_id。
line_key: 明细行键。 draft_line_id: 草稿明细行身份。
evidence_level: L1_field–L4_pdf。 evidence_level: L1_field–L4_pdf。
allow_full_pdf: 管理员显式 L4。 allow_full_pdf: 管理员显式 L4。
@@ -559,7 +559,7 @@ def build_minimal_evidence_pack_for_field(
if isinstance(item, dict) and int(item.get('document_id') or 0) == int(case.document_id): if isinstance(item, dict) and int(item.get('document_id') or 0) == int(case.document_id):
document = dict(item) document = dict(item)
break break
field_meta = {'field_id': str(field_id), 'scope': 'line' if line_key else 'header', 'line_key': line_key} field_meta = {'field_id': str(field_id), 'scope': 'line' if draft_line_id else 'header', 'draft_line_id': draft_line_id}
return select_review_evidence_pack( return select_review_evidence_pack(
document=document, document=document,
target_fields=[field_meta], target_fields=[field_meta],
@@ -83,7 +83,7 @@ def _normalize_observation(
case_document_id: int, case_document_id: int,
case_id: int, case_id: int,
field_code: str | None = None, field_code: str | None = None,
line_key: str | None = None, draft_line_id: str | None = None,
derived_row_index: int | None = None, derived_row_index: int | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
""" """
@@ -118,7 +118,7 @@ def _normalize_observation(
provenance_ref: str | None = None provenance_ref: str | None = None
if source == 'draft_observation' or source == 'text_fallback': if source == 'draft_observation' or source == 'text_fallback':
provenance_ref = build_provenance_ref( provenance_ref = build_provenance_ref(
case_id=case_id, line_key=line_key, field_code=field_code or '', case_id=case_id, draft_line_id=draft_line_id, field_code=field_code or '',
) )
confidence_raw = raw.get('confidence') confidence_raw = raw.get('confidence')
@@ -221,23 +221,22 @@ def _iter_unit_header_fields(order_result: dict[str, Any]) -> list[tuple[str, di
def _iter_unit_line_fields( def _iter_unit_line_fields(
order_result: dict[str, Any], order_result: dict[str, Any],
) -> list[tuple[str, int, str, dict[str, Any]]]: ) -> list[tuple[str, int, str, dict[str, Any]]]:
"""返回 [(line_key, row_position, field_id, field_obj)]""" """返回 [(draft_line_id, row_position, field_id, field_obj)]"""
out: list[tuple[str, int, str, dict[str, Any]]] = [] out: list[tuple[str, int, str, dict[str, Any]]] = []
lines = order_result.get('lines') or [] lines = order_result.get('lines') or []
for pos, line in enumerate(lines): for pos, line in enumerate(lines):
if not isinstance(line, dict): if not isinstance(line, dict):
continue continue
line_key = _safe_str(line.get('line_key')) draft_line_id = _safe_str(line.get('draft_line_id'))
if not line_key: if not draft_line_id:
index_match = _MACHINE_LINE_KEY_RE.match(f'machine-{pos + 1}') draft_line_id = f'machine-{pos + 1}'
line_key = index_match.group(0) if index_match else f'machine-{pos + 1}'
for field_obj in line.get('fields') or []: for field_obj in line.get('fields') or []:
if not isinstance(field_obj, dict): if not isinstance(field_obj, dict):
continue continue
fid = _safe_str(field_obj.get('field_id')) fid = _safe_str(field_obj.get('field_id'))
if not fid: if not fid:
continue continue
out.append((line_key, pos, fid, field_obj)) out.append((draft_line_id, pos, fid, field_obj))
return out return out
@@ -254,9 +253,9 @@ def _draft_line_list(draft) -> list[dict[str, Any]]:
return [ln for ln in (lines if isinstance(lines, list) else []) if isinstance(ln, dict)] return [ln for ln in (lines if isinstance(lines, list) else []) if isinstance(ln, dict)]
def _find_draft_line(lines: list[dict[str, Any]], line_key: str) -> dict[str, Any] | None: def _find_draft_line(lines: list[dict[str, Any]], draft_line_id: str) -> dict[str, Any] | None:
for ln in lines: for ln in lines:
if _safe_str(ln.get('line_key')) == line_key: if _safe_str(ln.get('draft_line_id')) == draft_line_id:
return ln return ln
return None return None
@@ -301,8 +300,8 @@ def _frozen_document_snapshot(case) -> dict[str, Any]:
def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, str, int | None, str, dict[str, Any]]]: def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, str, int | None, str, dict[str, Any]]]:
""" """
返回 [(line_key_or_header, field_id, row_index, table_id, raw_field_obj)]。 返回 [(draft_line_id_or_header, field_id, row_index, table_id, raw_field_obj)]。
header scope 行 line_key=None。 header scope 行 draft_line_id=None。
""" """
out: list[tuple[str, str, int | None, str, dict[str, Any]]] = [] out: list[tuple[str, str, int | None, str, dict[str, Any]]] = []
candidates = [ candidates = [
@@ -315,7 +314,7 @@ def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, st
for row_idx, row in enumerate(rows): for row_idx, row in enumerate(rows):
if not isinstance(row, dict): if not isinstance(row, dict):
continue continue
line_key = _safe_str(row.get('line_key')) draft_line_id = _safe_str(row.get('draft_line_id'))
data_row_idx = _safe_int(row.get('data_row_index') or row.get('row_index')) data_row_idx = _safe_int(row.get('data_row_index') or row.get('row_index'))
for raw_field in row.get('fields') or []: for raw_field in row.get('fields') or []:
if not isinstance(raw_field, dict): if not isinstance(raw_field, dict):
@@ -323,9 +322,9 @@ def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, st
fid = _safe_str(raw_field.get('field_id')) fid = _safe_str(raw_field.get('field_id'))
if not fid: if not fid:
continue continue
effective_line_key = line_key effective_draft_line_id = draft_line_id
out.append(( out.append((
effective_line_key, effective_draft_line_id,
fid, fid,
data_row_idx, data_row_idx,
table_id, table_id,
@@ -358,7 +357,7 @@ def _schema_fields_map(case) -> dict[str, dict[str, Any]]:
_FIELD_VIEW_KEYS = ( _FIELD_VIEW_KEYS = (
'field_id', 'field_code', 'display_name', 'scope', 'field_id', 'field_code', 'display_name', 'scope',
'data_type', 'llm_context_policy', 'data_type', 'llm_context_policy',
'line_key', 'draft_line_id',
'machine_value', 'current_draft_value', 'value_source', 'machine_value', 'current_draft_value', 'value_source',
'primary_evidence', 'field_evidences', 'primary_evidence', 'field_evidences',
) )
@@ -375,7 +374,7 @@ def _build_field_view(
field_id: str, field_id: str,
field_metadata: dict[str, Any] | None, field_metadata: dict[str, Any] | None,
scope: Literal['header', 'line'], scope: Literal['header', 'line'],
line_key: str | None, draft_line_id: str | None,
case_id: int, case_id: int,
case_document_id: int, case_document_id: int,
) -> dict[str, Any]: ) -> dict[str, Any]:
@@ -387,7 +386,7 @@ def _build_field_view(
view['display_name'] = _safe_str(md.get('display_name')) or code view['display_name'] = _safe_str(md.get('display_name')) or code
view['scope'] = scope view['scope'] = scope
view['data_type'] = _safe_str(md.get('data_type')) view['data_type'] = _safe_str(md.get('data_type'))
view['line_key'] = line_key view['draft_line_id'] = draft_line_id
policy = resolve_llm_context_policy( policy = resolve_llm_context_policy(
field_metadata=md, field_metadata=md,
field_code=code, field_code=code,
@@ -457,9 +456,9 @@ def build_review_evidence_view(case) -> dict[str, Any]:
"diagnostics": { "unit_orders_ambiguous": bool, "context_ambiguous_reasons": [] }, "diagnostics": { "unit_orders_ambiguous": bool, "context_ambiguous_reasons": [] },
"header_fields": { [field_id]: field_view }, "header_fields": { [field_id]: field_view },
"line_fields": { "line_fields": {
[line_key]: { [field_id]: field_view } [draft_line_id]: { [field_id]: field_view }
}, },
"lines_order": [line_key...], "lines_order": [draft_line_id...],
"layout_schema_candidates": [frozen_candidate...], // 直接引用,不 clone "layout_schema_candidates": [frozen_candidate...], // 直接引用,不 clone
"frozen_document_snapshot": dict, // 只读 "frozen_document_snapshot": dict, // 只读
} }
@@ -481,7 +480,7 @@ def build_review_evidence_view(case) -> dict[str, Any]:
def _ensure_field( def _ensure_field(
fid: str, fid: str,
scope: Literal['header', 'line'], scope: Literal['header', 'line'],
line_key: str | None = None, draft_line_id: str | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
if scope == 'header': if scope == 'header':
if fid not in header_fields: if fid not in header_fields:
@@ -489,22 +488,22 @@ def build_review_evidence_view(case) -> dict[str, Any]:
field_id=fid, field_id=fid,
field_metadata=schema_fields.get(fid), field_metadata=schema_fields.get(fid),
scope='header', scope='header',
line_key=None, draft_line_id=None,
case_id=case_id, case_id=case_id,
case_document_id=case_document_id, case_document_id=case_document_id,
) )
return header_fields[fid] return header_fields[fid]
assert line_key assert draft_line_id
if line_key not in line_fields: if draft_line_id not in line_fields:
line_fields[line_key] = {} line_fields[draft_line_id] = {}
lines_order.append(line_key) lines_order.append(draft_line_id)
line_map = line_fields[line_key] line_map = line_fields[draft_line_id]
if fid not in line_map: if fid not in line_map:
line_map[fid] = _build_field_view( line_map[fid] = _build_field_view(
field_id=fid, field_id=fid,
field_metadata=schema_fields.get(fid), field_metadata=schema_fields.get(fid),
scope='line', scope='line',
line_key=line_key, draft_line_id=draft_line_id,
case_id=case_id, case_id=case_id,
case_document_id=case_document_id, case_document_id=case_document_id,
) )
@@ -540,8 +539,8 @@ def build_review_evidence_view(case) -> dict[str, Any]:
if v is not None: if v is not None:
fv['machine_value'] = v fv['machine_value'] = v
for line_key, _pos, fid, raw_field in _iter_unit_line_fields(order): for draft_line_id, _pos, fid, raw_field in _iter_unit_line_fields(order):
fv = _ensure_field(fid, 'line', line_key=line_key) fv = _ensure_field(fid, 'line', draft_line_id=draft_line_id)
observations = raw_field.get('observations') or [] observations = raw_field.get('observations') or []
fc = _safe_str(raw_field.get('field_code')) or fv['field_code'] fc = _safe_str(raw_field.get('field_code')) or fv['field_code']
for raw_obs in observations: for raw_obs in observations:
@@ -553,7 +552,7 @@ def build_review_evidence_view(case) -> dict[str, Any]:
case_document_id=case_document_id, case_document_id=case_document_id,
case_id=case_id, case_id=case_id,
field_code=fc, field_code=fc,
line_key=line_key, draft_line_id=draft_line_id,
) )
fv['field_evidences'].append(norm) fv['field_evidences'].append(norm)
if fv['machine_value'] is None: if fv['machine_value'] is None:
@@ -597,17 +596,17 @@ def build_review_evidence_view(case) -> dict[str, Any]:
# Lines # Lines
draft_lines = _draft_line_list(draft) draft_lines = _draft_line_list(draft)
for line in draft_lines: for line in draft_lines:
line_key = _safe_str(line.get('line_key')) draft_line_id = _safe_str(line.get('draft_line_id'))
if not line_key: if not draft_line_id:
continue continue
line_map = line_fields.setdefault(line_key, {}) line_map = line_fields.setdefault(draft_line_id, {})
if line_key not in lines_order: if draft_line_id not in lines_order:
lines_order.append(line_key) lines_order.append(draft_line_id)
for fid in list(line_map.keys()) + list(schema_fields.keys()): for fid in list(line_map.keys()) + list(schema_fields.keys()):
md = schema_fields.get(fid) md = schema_fields.get(fid)
if md and _safe_str(md.get('scope')) == 'header': if md and _safe_str(md.get('scope')) == 'header':
continue continue
fv = _ensure_field(fid, 'line', line_key=line_key) fv = _ensure_field(fid, 'line', draft_line_id=draft_line_id)
obj = _machine_field_value(line, fid) obj = _machine_field_value(line, fid)
if isinstance(obj, dict): if isinstance(obj, dict):
for raw_obs in (obj.get('observations') or []): for raw_obs in (obj.get('observations') or []):
@@ -619,7 +618,7 @@ def build_review_evidence_view(case) -> dict[str, Any]:
case_document_id=case_document_id, case_document_id=case_document_id,
case_id=case_id, case_id=case_id,
field_code=_safe_str(obj.get('field_code')) or fv['field_code'], field_code=_safe_str(obj.get('field_code')) or fv['field_code'],
line_key=line_key, draft_line_id=draft_line_id,
) )
fv['field_evidences'].append(norm) fv['field_evidences'].append(norm)
if fv['machine_value'] is None and obj.get('value') is not None: if fv['machine_value'] is None and obj.get('value') is not None:
@@ -630,7 +629,7 @@ def build_review_evidence_view(case) -> dict[str, Any]:
frozen_doc = _frozen_document_snapshot(case) frozen_doc = _frozen_document_snapshot(case)
for lk, fid, ridx, tid, raw_field in _iter_frozen_layout_fields(frozen_doc): for lk, fid, ridx, tid, raw_field in _iter_frozen_layout_fields(frozen_doc):
scope = 'line' if lk else 'header' scope = 'line' if lk else 'header'
fv = _ensure_field(fid, scope=scope, line_key=lk or None) fv = _ensure_field(fid, scope=scope, draft_line_id=lk or None)
wrapped = { wrapped = {
'value': raw_field.get('value') or raw_field.get('quote'), 'value': raw_field.get('value') or raw_field.get('quote'),
'quote': raw_field.get('quote') or raw_field.get('value'), 'quote': raw_field.get('quote') or raw_field.get('value'),
@@ -651,7 +650,7 @@ def build_review_evidence_view(case) -> dict[str, Any]:
case_document_id=case_document_id, case_document_id=case_document_id,
case_id=case_id, case_id=case_id,
field_code=fv['field_code'], field_code=fv['field_code'],
line_key=lk or None, draft_line_id=lk or None,
derived_row_index=ridx, derived_row_index=ridx,
) )
fv['field_evidences'].append(norm) fv['field_evidences'].append(norm)
@@ -683,25 +682,25 @@ def get_field_view(
view: dict[str, Any], view: dict[str, Any],
*, *,
field_id: str, field_id: str,
line_key: str | None, draft_line_id: str | None,
) -> dict[str, Any] | None: ) -> dict[str, Any] | None:
fid = str(field_id or '').strip() fid = str(field_id or '').strip()
if not fid: if not fid:
return None return None
if line_key: if draft_line_id:
lk = str(line_key).strip() lk = str(draft_line_id).strip()
line_map = view.get('line_fields') or {} line_map = view.get('line_fields') or {}
row = line_map.get(lk) or {} row = line_map.get(lk) or {}
return row.get(fid) or None return row.get(fid) or None
return (view.get('header_fields') or {}).get(fid) return (view.get('header_fields') or {}).get(fid)
def count_valid_row_fields(view: dict[str, Any], line_key: str) -> int: def count_valid_row_fields(view: dict[str, Any], draft_line_id: str) -> int:
""" """
同行中“有值且可发送”的字段数量(evidence 有值或 machine_value/draft_value 非空)。 同行中“有值且可发送”的字段数量(evidence 有值或 machine_value/draft_value 非空)。
用于门禁:同行字段数 >= 2 才允许 L2_row。 用于门禁:同行字段数 >= 2 才允许 L2_row。
""" """
lk = str(line_key or '').strip() lk = str(draft_line_id or '').strip()
line_map = (view.get('line_fields') or {}).get(lk) or {} line_map = (view.get('line_fields') or {}).get(lk) or {}
count = 0 count = 0
for fv in line_map.values(): for fv in line_map.values():
@@ -194,7 +194,7 @@ def _finding_source_options(item: dict[str, Any]) -> list[dict[str, Any]]:
return options return options
def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None: def _draft_line_id_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None:
"""按 line_index 定位 Draft 行键;优先显式 line_index,否则按顺序。""" """按 line_index 定位 Draft 行键;优先显式 line_index,否则按顺序。"""
draft = case.current_draft draft = case.current_draft
if draft is None: if draft is None:
@@ -206,12 +206,12 @@ def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str |
raw_idx = raw.get('line_index') raw_idx = raw.get('line_index')
try: try:
if raw_idx is not None and int(raw_idx) == int(line_index): if raw_idx is not None and int(raw_idx) == int(line_index):
key = str(raw.get('line_key') or '').strip() key = str(raw.get('draft_line_id') or '').strip()
return key or None return key or None
except (TypeError, ValueError): except (TypeError, ValueError):
pass pass
if idx == int(line_index): if idx == int(line_index):
key = str(raw.get('line_key') or '').strip() key = str(raw.get('draft_line_id') or '').strip()
return key or None return key or None
return None return None
@@ -322,12 +322,12 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu
) )
for key in value_keys for key in value_keys
] ]
line_key = _line_key_for_index(case, line_index) if line_index >= 0 else None draft_line_id = _draft_line_id_for_index(case, line_index) if line_index >= 0 else None
finding = { finding = {
'conflict_key': _stored_conflict_key(item), 'conflict_key': _stored_conflict_key(item),
'field_code': field, 'field_code': field,
'line_index': line_index if line_index >= 0 else None, 'line_index': line_index if line_index >= 0 else None,
'line_key': line_key, 'draft_line_id': draft_line_id,
'scope': str(item.get('scope') or _finding_scope(case, field_code=field, line_index=line_index)), 'scope': str(item.get('scope') or _finding_scope(case, field_code=field, line_index=line_index)),
'severity': str(item.get('severity') or 'blocking'), 'severity': str(item.get('severity') or 'blocking'),
'reason': reason, 'reason': reason,
@@ -473,10 +473,10 @@ def resolve_review_case_field_conflict(
header = dict(case.current_draft.header_values_json or {}) header = dict(case.current_draft.header_values_json or {})
change = _set_value(header, field, chosen_display, restore_machine=False) change = _set_value(header, field, chosen_display, restore_machine=False)
case.current_draft.header_values_json = header case.current_draft.header_values_json = header
line_key = None draft_line_id = None
else: else:
line_key = _line_key_for_index(case, line_index) draft_line_id = _draft_line_id_for_index(case, line_index)
if not line_key: if not draft_line_id:
raise ConflictError( raise ConflictError(
'Conflict line is missing from draft', 'Conflict line is missing from draft',
code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING', code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING',
@@ -486,14 +486,14 @@ def resolve_review_case_field_conflict(
lines = list(case.current_draft.lines_json or []) lines = list(case.current_draft.lines_json or [])
target_line = None target_line = None
for raw in lines: for raw in lines:
if isinstance(raw, dict) and str(raw.get('line_key') or '') == line_key: if isinstance(raw, dict) and str(raw.get('draft_line_id') or '') == draft_line_id:
target_line = raw target_line = raw
break break
if target_line is None: if target_line is None:
raise ConflictError( raise ConflictError(
'Conflict line is missing from draft', 'Conflict line is missing from draft',
code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING', code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING',
details={'line_key': line_key}, details={'draft_line_id': draft_line_id},
) )
change = _set_value(target_line, field, chosen_display, restore_machine=False) change = _set_value(target_line, field, chosen_display, restore_machine=False)
case.current_draft.lines_json = lines case.current_draft.lines_json = lines
@@ -514,7 +514,7 @@ def resolve_review_case_field_conflict(
operation={ operation={
'conflict_key': conflict_key, 'conflict_key': conflict_key,
'field_code': field_code, 'field_code': field_code,
'line_key': line_key, 'draft_line_id': draft_line_id,
'resolution': mode, 'resolution': mode,
'option_index': option_index, 'option_index': option_index,
'chosen_value': chosen_display, 'chosen_value': chosen_display,
@@ -145,14 +145,14 @@ def _check_table_duplicate_value(
evidence_view: dict[str, Any], evidence_view: dict[str, Any],
*, *,
field_id: str, field_id: str,
line_key: str | None, draft_line_id: str | None,
field_view_obj: dict[str, Any], field_view_obj: dict[str, Any],
) -> bool: ) -> bool:
""" """
[Priority 4] Line scope:同一 table 中多个行存在与目标字段相同的 value。 [Priority 4] Line scope:同一 table 中多个行存在与目标字段相同的 value。
Header scope:此检测跳过(不适用)。目标 value 为空时跳过。 Header scope:此检测跳过(不适用)。目标 value 为空时跳过。
""" """
if not line_key: if not draft_line_id:
return False return False
if not isinstance(evidence_view, dict): if not isinstance(evidence_view, dict):
return False return False
@@ -169,7 +169,7 @@ def _check_table_duplicate_value(
return False return False
same_table_hits = 0 same_table_hits = 0
for lk, lf_map in line_fields.items(): for lk, lf_map in line_fields.items():
if lk == str(line_key) or not isinstance(lf_map, dict): if lk == str(draft_line_id) or not isinstance(lf_map, dict):
continue continue
fv = lf_map.get(str(field_id)) fv = lf_map.get(str(field_id))
if not isinstance(fv, dict): if not isinstance(fv, dict):
@@ -206,16 +206,16 @@ def _check_manual_conflict(field_view: dict[str, Any]) -> bool:
def _check_context_borderline( def _check_context_borderline(
evidence_view: dict[str, Any], evidence_view: dict[str, Any],
*, *,
line_key: str | None, draft_line_id: str | None,
) -> bool: ) -> bool:
""" """
[Priority 6] Line scope 同行有效字段数正好 = 门禁最低阈值(2)。 [Priority 6] Line scope 同行有效字段数正好 = 门禁最低阈值(2)。
处于门禁临界线,证据不稳,升级到表格更安全。Header scope 跳过。 处于门禁临界线,证据不稳,升级到表格更安全。Header scope 跳过。
""" """
if not line_key: if not draft_line_id:
return False return False
try: try:
siblings = count_valid_row_fields(evidence_view, str(line_key)) siblings = count_valid_row_fields(evidence_view, str(draft_line_id))
except Exception: except Exception:
return False return False
return siblings == _BORDERLINE_SIBLING_COUNT return siblings == _BORDERLINE_SIBLING_COUNT
@@ -224,20 +224,20 @@ def _check_context_borderline(
def _check_context_identity_insufficient( def _check_context_identity_insufficient(
evidence_view: dict[str, Any], evidence_view: dict[str, Any],
*, *,
line_key: str | None, draft_line_id: str | None,
field_view_obj: dict[str, Any], field_view_obj: dict[str, Any],
) -> bool: ) -> bool:
""" """
[Priority 7] Line scope:同行缺少明确身份标识字段(如 part_number / line_no), [Priority 7] Line scope:同行缺少明确身份标识字段(如 part_number / line_no),
或目标字段 primary_evidence.confidence 低于阈值。 或目标字段 primary_evidence.confidence 低于阈值。
""" """
if not line_key: if not draft_line_id:
return False return False
if not isinstance(evidence_view, dict): if not isinstance(evidence_view, dict):
return False return False
# 身份标识检测 # 身份标识检测
line_fields = evidence_view.get('line_fields') or {} line_fields = evidence_view.get('line_fields') or {}
lf = line_fields.get(str(line_key)) if isinstance(line_fields, dict) else None lf = line_fields.get(str(draft_line_id)) if isinstance(line_fields, dict) else None
has_identity = False has_identity = False
if isinstance(lf, dict): if isinstance(lf, dict):
for fid, fv in lf.items(): for fid, fv in lf.items():
@@ -276,7 +276,7 @@ def resolve_auto_upgrade_level(
*, *,
evidence_view: dict[str, Any], evidence_view: dict[str, Any],
field_id: str, field_id: str,
line_key: str | None, draft_line_id: str | None,
requested_level: EvidenceLevelV2, requested_level: EvidenceLevelV2,
schema_field_meta: dict[str, Any] | None = None, schema_field_meta: dict[str, Any] | None = None,
issue_code: str | None = None, issue_code: str | None = None,
@@ -287,7 +287,7 @@ def resolve_auto_upgrade_level(
Args: Args:
evidence_view: build_review_evidence_view() 的返回。 evidence_view: build_review_evidence_view() 的返回。
field_id: 目标字段 ID。 field_id: 目标字段 ID。
line_key: 目标行键;None 表示 header scope。 draft_line_id: 目标草稿行身份;None 表示 header scope。
requested_level: 用户/前端请求的等级(默认 L2_row)。 requested_level: 用户/前端请求的等级(默认 L2_row)。
schema_field_meta: schema.definition_json.fields[] 中的原始元数据。 schema_field_meta: schema.definition_json.fields[] 中的原始元数据。
issue_code: 前端透传的冲突 issue_code(触发 P1)。 issue_code: 前端透传的冲突 issue_code(触发 P1)。
@@ -301,7 +301,7 @@ def resolve_auto_upgrade_level(
if not isinstance(evidence_view, dict): if not isinstance(evidence_view, dict):
return requested_level, None, [] return requested_level, None, []
field_view = get_field_view(evidence_view, field_id=field_id, line_key=line_key) field_view = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id)
if field_view is None: if field_view is None:
return requested_level, None, [] return requested_level, None, []
@@ -313,7 +313,7 @@ def resolve_auto_upgrade_level(
if str(requested_level) not in {'L1_field', 'L2_row'}: if str(requested_level) not in {'L1_field', 'L2_row'}:
return requested_level, None, [] return requested_level, None, []
scope_is_line = bool(line_key) scope_is_line = bool(draft_line_id)
reasons_hit: list[str] = [] reasons_hit: list[str] = []
# [STEP 1] 按优先级顺序跑 7 项检测,命中即追加 # [STEP 1] 按优先级顺序跑 7 项检测,命中即追加
@@ -326,17 +326,17 @@ def resolve_auto_upgrade_level(
if _check_table_duplicate_value( if _check_table_duplicate_value(
evidence_view, evidence_view,
field_id=field_id, field_id=field_id,
line_key=line_key, draft_line_id=draft_line_id,
field_view_obj=field_view, field_view_obj=field_view,
): ):
reasons_hit.append('table_duplicate_value') reasons_hit.append('table_duplicate_value')
if _check_manual_conflict(field_view): if _check_manual_conflict(field_view):
reasons_hit.append('manual_conflict') reasons_hit.append('manual_conflict')
if _check_context_borderline(evidence_view, line_key=line_key): if _check_context_borderline(evidence_view, draft_line_id=draft_line_id):
reasons_hit.append('context_borderline') reasons_hit.append('context_borderline')
if _check_context_identity_insufficient( if _check_context_identity_insufficient(
evidence_view, evidence_view,
line_key=line_key, draft_line_id=draft_line_id,
field_view_obj=field_view, field_view_obj=field_view,
): ):
reasons_hit.append('context_identity_insufficient') reasons_hit.append('context_identity_insufficient')
@@ -180,9 +180,9 @@ def is_valid_provenance_ref(value: Any) -> bool:
return _DRAFT_REF_RE.match(value.strip()) is not None return _DRAFT_REF_RE.match(value.strip()) is not None
def build_provenance_ref(*, case_id: int, line_key: str | None, field_code: str) -> str: def build_provenance_ref(*, case_id: int, draft_line_id: str | None, field_code: str) -> str:
"""生成 Draft 回退专用的 provenance_ref(不伪装成 evidence_ref)。""" """生成 Draft 回退专用的 provenance_ref(不伪装成 evidence_ref)。"""
line = str(line_key or 'header').strip() or 'header' line = str(draft_line_id or 'header').strip() or 'header'
return f'draft:case-{int(case_id)}:line-{line}:field-{str(field_code).strip()}' return f'draft:case-{int(case_id)}:line-{line}:field-{str(field_code).strip()}'
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -231,10 +231,10 @@ class V2Target(TypedDict, total=False):
field_id: str field_id: str
field_code: str field_code: str
scope: Literal['header', 'line'] scope: Literal['header', 'line']
line_key: str | None draft_line_id: str | None
class V2RowContext(TypedDict, total=False): class V2RowContext(TypedDict, total=False):
line_key: str draft_line_id: str
fields: list[dict[str, Any]] # 每个字段含 field_id/field_code/machine_value/current_draft_value/value_source/evidence_ref/source fields: list[dict[str, Any]] # 每个字段含 field_id/field_code/machine_value/current_draft_value/value_source/evidence_ref/source
class V2TableContext(TypedDict, total=False): class V2TableContext(TypedDict, total=False):
@@ -243,7 +243,7 @@ class V2TableContext(TypedDict, total=False):
target_row_index: int | None target_row_index: int | None
class V2NeighborRow(TypedDict, total=False): class V2NeighborRow(TypedDict, total=False):
line_key: str draft_line_id: str
row_index: int row_index: int
fields: list[dict[str, Any]] fields: list[dict[str, Any]]
position: Literal['preceding', 'following'] position: Literal['preceding', 'following']
@@ -347,7 +347,7 @@ def build_suggestion_request_envelope(
return envelope return envelope
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 响应解析(v1/v2 统一出口,line_key/scope/needs_review v2 新增) # 响应解析(v1/v2 统一出口,draft_line_id/scope/needs_review v2 新增)
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]]: def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]]:
""" """
@@ -371,10 +371,10 @@ def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]
needs_review = False needs_review = False
if isinstance(item.get('needs_review'), bool): if isinstance(item.get('needs_review'), bool):
needs_review = bool(item['needs_review']) needs_review = bool(item['needs_review'])
line_key_raw = item.get('line_key') draft_line_id_raw = item.get('draft_line_id')
line_key = str(line_key_raw).strip() if line_key_raw is not None else None draft_line_id = str(draft_line_id_raw).strip() if draft_line_id_raw is not None else None
if not line_key: if not draft_line_id:
line_key = None draft_line_id = None
scope = str(item.get('scope') or '').strip().lower() scope = str(item.get('scope') or '').strip().lower()
if scope not in {'header', 'line'}: if scope not in {'header', 'line'}:
scope = 'line' scope = 'line'
@@ -387,7 +387,7 @@ def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]
'field_id': field_id, 'field_id': field_id,
'field_code': str(item.get('field_code') or '').strip() or None, 'field_code': str(item.get('field_code') or '').strip() or None,
'scope': scope, 'scope': scope,
'line_key': line_key, 'draft_line_id': draft_line_id,
'suggested_value': item.get('suggested_value'), 'suggested_value': item.get('suggested_value'),
'quote': str(item.get('quote') or item.get('suggested_value') or '')[:1000], 'quote': str(item.get('quote') or item.get('suggested_value') or '')[:1000],
'confidence': confidence, 'confidence': confidence,
@@ -9,7 +9,7 @@ services/shipping_notice/order_review_llm_gate.py
- order_review_llm_policy_registry.resolve_llm_context_policy - order_review_llm_policy_registry.resolve_llm_context_policy
逻辑: 逻辑:
[1] field_not_found 目标 field_id 在 schema 中不存在 [1] field_not_found 目标 field_id 在 schema 中不存在
[2] line_not_found 目标 line_key 在视图中行找不到 [2] line_not_found 目标 draft_line_id 在视图中行找不到
[3] field_value_missing 目标字段 machine/draft/primary_evidence 三者全空 [3] field_value_missing 目标字段 machine/draft/primary_evidence 三者全空
[4] evidence_unavailable 目标字段无任何 field_evidences[](三源都没有事实) [4] evidence_unavailable 目标字段无任何 field_evidences[](三源都没有事实)
[5] context_ambiguous unit orders >1 且无法按 primary_document_id 唯一确定 [5] context_ambiguous unit orders >1 且无法按 primary_document_id 唯一确定
@@ -57,7 +57,7 @@ def run_preflight_gate(
evidence_view: dict[str, Any], evidence_view: dict[str, Any],
*, *,
field_id: str, field_id: str,
line_key: str | None, draft_line_id: str | None,
requested_level: EvidenceLevelV2 | None, requested_level: EvidenceLevelV2 | None,
schema_field_meta: dict[str, Any] | None = None, schema_field_meta: dict[str, Any] | None = None,
) -> GateResult: ) -> GateResult:
@@ -77,15 +77,15 @@ def run_preflight_gate(
return False, 'context_ambiguous', \ return False, 'context_ambiguous', \
'; '.join(str(r) for r in ambiguous_reasons) '; '.join(str(r) for r in ambiguous_reasons)
# [2] line scope 需要 line_key 存在 # [2] line scope 需要 draft_line_id 存在
scope_is_line = bool(line_key) scope_is_line = bool(draft_line_id)
if scope_is_line: if scope_is_line:
line_fields = evidence_view.get('line_fields') or {} line_fields = evidence_view.get('line_fields') or {}
if str(line_key) not in line_fields: if str(draft_line_id) not in line_fields:
return False, 'line_not_found', f'line_key={line_key}' return False, 'line_not_found', f'draft_line_id={draft_line_id}'
# [1] field_id 找不到(header/line 都没命中) # [1] field_id 找不到(header/line 都没命中)
field_view = get_field_view(evidence_view, field_id=field_id, line_key=line_key) field_view = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id)
if field_view is None: if field_view is None:
return False, 'field_not_found', f'field_id={field_id}' return False, 'field_not_found', f'field_id={field_id}'
@@ -127,10 +127,10 @@ def run_preflight_gate(
effective_level = requested_level or 'L2_row' effective_level = requested_level or 'L2_row'
if effective_level not in _SENSITIVE_MASK_LEVELS and effective_level in EVIDENCE_LEVELS_V2_ALLOWED: if effective_level not in _SENSITIVE_MASK_LEVELS and effective_level in EVIDENCE_LEVELS_V2_ALLOWED:
if scope_is_line and str(effective_level) in ('L2_row',): if scope_is_line and str(effective_level) in ('L2_row',):
siblings = count_valid_row_fields(evidence_view, str(line_key)) siblings = count_valid_row_fields(evidence_view, str(draft_line_id))
if siblings < _MIN_LINE_SIBLINGS: if siblings < _MIN_LINE_SIBLINGS:
return False, 'context_insufficient', \ return False, 'context_insufficient', \
f'line_key={line_key} valid siblings={siblings} required>={_MIN_LINE_SIBLINGS}' f'draft_line_id={draft_line_id} valid siblings={siblings} required>={_MIN_LINE_SIBLINGS}'
return True, None, None return True, None, None
@@ -117,7 +117,7 @@ def _audit_llm_suggestion(
""" """
after_payload = { after_payload = {
'field_id': suggestion.field_id, 'field_id': suggestion.field_id,
'line_key': suggestion.line_key, 'draft_line_id': suggestion.draft_line_id,
'status': suggestion.status, 'status': suggestion.status,
'decision': suggestion.decision, 'decision': suggestion.decision,
**(after or {}), **(after or {}),
@@ -242,7 +242,7 @@ def serialize_suggestion(
base: dict[str, Any] = { base: dict[str, Any] = {
'suggestion_no': row.suggestion_no, 'suggestion_no': row.suggestion_no,
'field_id': row.field_id, 'field_id': row.field_id,
'line_key': row.line_key, 'draft_line_id': row.draft_line_id,
'scope': row.scope, 'scope': row.scope,
'evidence_level': row.evidence_level, 'evidence_level': row.evidence_level,
'contract_version': row.contract_version, 'contract_version': row.contract_version,
@@ -289,7 +289,7 @@ def serialize_suggestion(
'field_id': (i.get('field_id') if isinstance(i, dict) else None), 'field_id': (i.get('field_id') if isinstance(i, dict) else None),
'field_code': (i.get('field_code') if isinstance(i, dict) else None), 'field_code': (i.get('field_code') if isinstance(i, dict) else None),
'scope': (i.get('scope') if isinstance(i, dict) else None), 'scope': (i.get('scope') if isinstance(i, dict) else None),
'line_key': (i.get('line_key') if isinstance(i, dict) else None), 'draft_line_id': (i.get('draft_line_id') if isinstance(i, dict) else None),
} }
for i in tf if isinstance(i, dict) for i in tf if isinstance(i, dict)
][:50] ][:50]
@@ -368,7 +368,7 @@ def request_field_suggestion(
user_id: int, user_id: int,
case_no: str, case_no: str,
field_id: str, field_id: str,
line_key: str | None = None, draft_line_id: str | None = None,
evidence_level: str | None = None, evidence_level: str | None = None,
issue_code: str | None = None, issue_code: str | None = None,
allow_full_pdf: bool = False, allow_full_pdf: bool = False,
@@ -381,7 +381,7 @@ def request_field_suggestion(
user_id: Case 属主。 user_id: Case 属主。
case_no: 复核 Case 编号。 case_no: 复核 Case 编号。
field_id: 目标 field_id。 field_id: 目标 field_id。
line_key: 明细行键。 draft_line_id: 草稿行身份。
evidence_level: L1_field–L4_pdf。 evidence_level: L1_field–L4_pdf。
issue_code: 关联 issue。 issue_code: 关联 issue。
allow_full_pdf: 管理员显式 L4。 allow_full_pdf: 管理员显式 L4。
@@ -396,8 +396,8 @@ def request_field_suggestion(
field = _schema_field(case, field_id) field = _schema_field(case, field_id)
scope = str(field.get('scope') or 'header') scope = str(field.get('scope') or 'header')
if scope == 'line' and not line_key: if scope == 'line' and not draft_line_id:
raise ValidationError('line_key is required for line scope', code='SHIPPING.REVIEW_LINE_NOT_FOUND') raise ValidationError('draft_line_id is required for line scope', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
level_raw = _normalize_level(evidence_level or 'L1_field') level_raw = _normalize_level(evidence_level or 'L1_field')
if level_raw == 'L4_pdf' and not (is_admin and allow_full_pdf): if level_raw == 'L4_pdf' and not (is_admin and allow_full_pdf):
@@ -409,7 +409,7 @@ def request_field_suggestion(
'field_id': str(field_id), 'field_id': str(field_id),
'field_code': str(field.get('field_code') or field_id), 'field_code': str(field.get('field_code') or field_id),
'scope': scope, 'scope': scope,
'line_key': line_key, 'draft_line_id': draft_line_id,
'line_number': None, 'line_number': None,
}] }]
row = ShippingOrderReviewSuggestion( row = ShippingOrderReviewSuggestion(
@@ -418,7 +418,7 @@ def request_field_suggestion(
document_id=int(case.document_id), document_id=int(case.document_id),
run_id=int(case.run_id) if case.run_id else None, run_id=int(case.run_id) if case.run_id else None,
field_id=str(field_id), field_id=str(field_id),
line_key=str(line_key) if line_key else None, draft_line_id=str(draft_line_id) if draft_line_id else None,
scope=scope, scope=scope,
evidence_level=level, evidence_level=level,
status='pending', status='pending',
@@ -454,7 +454,7 @@ def request_field_suggestion(
upgraded_level, up_reason, up_reasons = resolve_auto_upgrade_level( upgraded_level, up_reason, up_reasons = resolve_auto_upgrade_level(
evidence_view=evidence_view, evidence_view=evidence_view,
field_id=str(field_id), field_id=str(field_id),
line_key=str(line_key) if line_key else None, draft_line_id=str(draft_line_id) if draft_line_id else None,
requested_level=level, # type: ignore[arg-type] requested_level=level, # type: ignore[arg-type]
schema_field_meta=field, schema_field_meta=field,
issue_code=issue_code, issue_code=issue_code,
@@ -488,15 +488,15 @@ def request_field_suggestion(
passed, gate_error, gate_hint = run_preflight_gate( passed, gate_error, gate_hint = run_preflight_gate(
evidence_view, evidence_view,
field_id=str(field_id), field_id=str(field_id),
line_key=str(line_key) if line_key else None, draft_line_id=str(draft_line_id) if draft_line_id else None,
requested_level=level, # type: ignore[arg-type] requested_level=level, # type: ignore[arg-type]
schema_field_meta=field, schema_field_meta=field,
) )
# 填充观测列(gated 或未 gated 都写,便于对账 context_hash) # 填充观测列(gated 或未 gated 都写,便于对账 context_hash)
_evidence_view_count = 0 _evidence_view_count = 0
if line_key: if draft_line_id:
line_map = (evidence_view or {}).get('line_fields') or {} line_map = (evidence_view or {}).get('line_fields') or {}
row_map = line_map.get(str(line_key)) or {} row_map = line_map.get(str(draft_line_id)) or {}
target_view = row_map.get(str(field_id)) target_view = row_map.get(str(field_id))
else: else:
header_map = (evidence_view or {}).get('header_fields') or {} header_map = (evidence_view or {}).get('header_fields') or {}
@@ -617,7 +617,7 @@ def request_field_suggestion(
'field_id': str(field_id), 'field_id': str(field_id),
'field_code': str(field.get('field_code') or field_id), 'field_code': str(field.get('field_code') or field_id),
'scope': scope, 'scope': scope,
'line_key': line_key, 'draft_line_id': draft_line_id,
}, },
expected_target_field_id=str(field_id), expected_target_field_id=str(field_id),
auto_upgrade_reason=_auto_upgrade_reason, auto_upgrade_reason=_auto_upgrade_reason,
@@ -631,7 +631,7 @@ def request_field_suggestion(
'document_id': int(case.document_id), 'document_id': int(case.document_id),
'draft_version': int(case.current_draft.draft_version if case.current_draft else 0), 'draft_version': int(case.current_draft.draft_version if case.current_draft else 0),
'field_id': str(field_id), 'field_id': str(field_id),
'line_key': line_key, 'draft_line_id': draft_line_id,
'contract_version': LLM_REVIEW_CONTRACT_VERSION, 'contract_version': LLM_REVIEW_CONTRACT_VERSION,
'evidence_level': level, 'evidence_level': level,
'target_fields': target_fields, 'target_fields': target_fields,
@@ -781,7 +781,7 @@ def request_field_suggestion(
evidence_pack=evidence_pack, evidence_pack=evidence_pack,
envelope=request_payload, envelope=request_payload,
expected_target_field_id=str(field_id), expected_target_field_id=str(field_id),
expected_line_key=line_key, expected_draft_line_id=draft_line_id,
expected_scope=scope, expected_scope=scope,
) )
row.validated_suggestions_json = validated row.validated_suggestions_json = validated
@@ -827,7 +827,7 @@ def request_field_suggestion(
user_id=user_id, user_id=user_id,
case_no=case_no, case_no=case_no,
field_id=str(field_id), field_id=str(field_id),
line_key=line_key, draft_line_id=draft_line_id,
value=value, value=value,
suggestion_no=row.suggestion_no, suggestion_no=row.suggestion_no,
expected_draft_version=int(case.current_draft.draft_version), expected_draft_version=int(case.current_draft.draft_version),
@@ -914,7 +914,7 @@ def decide_suggestion(
before_status = { before_status = {
'status': suggestion.status, 'status': suggestion.status,
'field_id': suggestion.field_id, 'field_id': suggestion.field_id,
'line_key': suggestion.line_key, 'draft_line_id': suggestion.draft_line_id,
} }
case_payload = adjudicate_llm_suggestion_on_draft( case_payload = adjudicate_llm_suggestion_on_draft(
user_id=user_id, user_id=user_id,
@@ -5,15 +5,15 @@ services/shipping_notice/order_review_llm_validation.py
任何一项未通过 → validation_failed,该建议仅能 reject,禁止 accept/modify 写入草稿。 任何一项未通过 → validation_failed,该建议仅能 reject,禁止 accept/modify 写入草稿。
依赖: 依赖:
- order_review_llm_contract:QUOTE_NORMALIZATION_RULES / normalize_quote_text - order_review_llm_contract:QUOTE_NORMALIZATION_RULES / normalize_quote_text
- request_payload.envelope:target / expected_target_field_id / evidence[] / line_key 定位 - request_payload.envelope:target / expected_target_field_id / evidence[] / draft_line_id 定位
- 响应解析层:parse_suggestion_response 输出 [{field_id, line_key, scope, suggested_value, quote}] - 响应解析层:parse_suggestion_response 输出 [{field_id, draft_line_id, scope, suggested_value, quote}]
逻辑: 逻辑:
8 项按顺序 fail-closed(优先级从身份→价值→安全性): 8 项按顺序 fail-closed(优先级从身份→价值→安全性):
1. json_schema_invalid 响应项非 dict / field_id 为空(结构性非法) 1. json_schema_invalid 响应项非 dict / field_id 为空(结构性非法)
2. header_scope_has_line_key scope=header 时 line_key 不为 None(头部不能带行键) 2. header_scope_has_draft_line_id scope=header 时 draft_line_id 不为 None
3. non_target_field 响应 field_id 不在请求 expected_target_field_id 内 3. non_target_field 响应 field_id 不在请求 expected_target_field_id 内
4. field_id_mismatch 响应 field_id 与 expected_target_field_id 不一致 4. field_id_mismatch 响应 field_id 与 expected_target_field_id 不一致
5. line_key_mismatch scope=line 时响应 line_key != 请求 line_key(精确相等) 5. draft_line_id_mismatch scope=line 时响应 draft_line_id != 请求值(精确相等)
6. value_not_in_evidence suggested_value 不在 evidence[] 任何 value/quote(normalize 后) 6. value_not_in_evidence suggested_value 不在 evidence[] 任何 value/quote(normalize 后)
7. quote_consistency 响应 quote normalize 后与 suggested_value quote 不构成 substring 或 7. quote_consistency 响应 quote normalize 后与 suggested_value quote 不构成 substring 或
完整相等;即使值存在也视为伪造 完整相等;即使值存在也视为伪造
@@ -38,10 +38,10 @@ from app.services.shipping_notice.order_review_llm_contract import (
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
_VALIDATION_CHECKS_ORDER: Final[tuple[str, ...]] = ( _VALIDATION_CHECKS_ORDER: Final[tuple[str, ...]] = (
'json_schema_invalid', 'json_schema_invalid',
'header_scope_has_line_key', 'header_scope_has_draft_line_id',
'non_target_field', 'non_target_field',
'field_id_mismatch', 'field_id_mismatch',
'line_key_mismatch', 'draft_line_id_mismatch',
'value_not_in_evidence', 'value_not_in_evidence',
'quote_consistency', 'quote_consistency',
'guess_without_evidence', 'guess_without_evidence',
@@ -55,7 +55,7 @@ def _collect_evidence_values(
""" """
从 v2 envelope.evidence 或 v1 evidence_pack.fields[].snippets 提取候选值池。 从 v2 envelope.evidence 或 v1 evidence_pack.fields[].snippets 提取候选值池。
v2 优先读 envelope.evidence;缺失时回退 v1 结构(兼容历史 contract)。 v2 优先读 envelope.evidence;缺失时回退 v1 结构(兼容历史 contract)。
每项返回 {value_norm, quote_norm, value_raw, quote_raw, field_id, line_key, evidence_ref} 每项返回 {value_norm, quote_norm, value_raw, quote_raw, field_id, draft_line_id, evidence_ref}
""" """
pool: list[dict[str, Any]] = [] pool: list[dict[str, Any]] = []
env = envelope if isinstance(envelope, dict) else {} env = envelope if isinstance(envelope, dict) else {}
@@ -72,7 +72,7 @@ def _collect_evidence_values(
'value_raw': None if v_raw is None else str(v_raw), 'value_raw': None if v_raw is None else str(v_raw),
'quote_raw': None if q_raw is None else str(q_raw), 'quote_raw': None if q_raw is None else str(q_raw),
'field_id': str(ev.get('field_id') or ''), 'field_id': str(ev.get('field_id') or ''),
'line_key': str(ev.get('line_key') or '').strip() or None, 'draft_line_id': str(ev.get('draft_line_id') or '').strip() or None,
'evidence_ref': ev.get('evidence_ref'), 'evidence_ref': ev.get('evidence_ref'),
}) })
return pool return pool
@@ -82,7 +82,7 @@ def _collect_evidence_values(
if not isinstance(f, dict): if not isinstance(f, dict):
continue continue
fid = str(f.get('field_id') or '') fid = str(f.get('field_id') or '')
lk = str(f.get('line_key') or '').strip() or None draft_line_id = str(f.get('draft_line_id') or '').strip() or None
for sn in (f.get('snippets') or []): for sn in (f.get('snippets') or []):
if not isinstance(sn, dict): if not isinstance(sn, dict):
continue continue
@@ -94,44 +94,56 @@ def _collect_evidence_values(
'value_raw': None if v_raw is None else str(v_raw), 'value_raw': None if v_raw is None else str(v_raw),
'quote_raw': None if q_raw is None else str(q_raw), 'quote_raw': None if q_raw is None else str(q_raw),
'field_id': fid, 'field_id': fid,
'line_key': lk, 'draft_line_id': draft_line_id,
'evidence_ref': sn.get('evidence_ref'), 'evidence_ref': sn.get('evidence_ref'),
}) })
return pool return pool
def _is_pure_numeric(value: str) -> bool:
"""判定某值是否为纯数字(可含正负号/小数点)。纯数字的子串匹配无意义(如 '10' 命中 '100'),
会放行数量失真/幻觉,因此纯数字值只允许精确匹配,禁用子串匹配。"""
if not value:
return False
stripped = value.strip().lstrip('+-')
if not stripped:
return False
return stripped.replace('.', '', 1).isdigit() and any(ch.isdigit() for ch in stripped)
def _find_value_match( def _find_value_match(
pool: list[dict[str, Any]], pool: list[dict[str, Any]],
*, *,
value_norm: str, value_norm: str,
quote_norm_provided: str, quote_norm_provided: str,
field_id: str, field_id: str,
line_key: str | None, draft_line_id: str | None,
) -> tuple[str, dict[str, Any] | None]: ) -> tuple[str, dict[str, Any] | None]:
""" """
在候选池中按 4 级严格度递减匹配 value;返回 (mode, matched_item)。 在候选池中按 4 级严格度递减匹配 value;返回 (mode, matched_item)。
严格度:exact → exact_substring → normalized → normalized_substring 严格度:exact → exact_substring → normalized → normalized_substring
同池内优先匹配 field_id + line_key 双重身份的项;其次 field_id;最后全局任意项。 同池内优先匹配 field_id + draft_line_id 双重身份的项;其次 field_id;最后全局任意项。
""" """
if not value_norm and not quote_norm_provided: if not value_norm and not quote_norm_provided:
return '', None return '', None
# 身份过滤:先 field_id + line_key # 身份过滤:先 field_id + draft_line_id
def _iter_filtered(): def _iter_filtered():
if not pool: if not pool:
return return
same_identity = [ same_identity = [
p for p in pool p for p in pool
if str(p.get('field_id') or '') == field_id if str(p.get('field_id') or '') == field_id
and (str(p.get('line_key') or '') == str(line_key or '') and (str(p.get('draft_line_id') or '') == str(draft_line_id or '')
if line_key else not p.get('line_key')) if draft_line_id else not p.get('draft_line_id'))
] ]
same_field = [ same_field = [
p for p in pool p for p in pool
if str(p.get('field_id') or '') == field_id and p not in same_identity if str(p.get('field_id') or '') == field_id and p not in same_identity
] ]
others = [p for p in pool if p not in same_identity and p not in same_field] # 字段隔离:只允许用同 field_id 的证据验证当前字段建议,
for p in same_identity + same_field + others: # 禁止用其它字段(others)的证据兜底,避免跨字段误判(fail-closed)。
for p in same_identity + same_field:
yield p yield p
# 1. exact:raw 完全相等 # 1. exact:raw 完全相等
@@ -142,12 +154,12 @@ def _find_value_match(
if (vr and vr == needle) or (qr and qr == needle): if (vr and vr == needle) or (qr and qr == needle):
return 'exact', p return 'exact', p
# 2. exact_substring:raw 内 substring # 2. exact_substring:raw 内 substring(纯数字禁用子串,防止 '10' 误命中 '100')
for p in _iter_filtered(): for p in _iter_filtered():
vr = (p.get('value_raw') or '').strip() vr = (p.get('value_raw') or '').strip()
qr = (p.get('quote_raw') or '').strip() qr = (p.get('quote_raw') or '').strip()
needle = value_norm.strip() needle = value_norm.strip()
if not needle: if not needle or _is_pure_numeric(needle):
continue continue
if (vr and needle in vr) or (qr and needle in qr): if (vr and needle in vr) or (qr and needle in qr):
return 'exact_substring', p return 'exact_substring', p
@@ -159,11 +171,11 @@ def _find_value_match(
if (vn and vn == value_norm) or (qn and qn == value_norm): if (vn and vn == value_norm) or (qn and qn == value_norm):
return 'normalized', p return 'normalized', p
# 4. normalized_substring:norm 内 substring # 4. normalized_substring:norm 内 substring(纯数字禁用子串)
for p in _iter_filtered(): for p in _iter_filtered():
vn = p.get('value_norm') or '' vn = p.get('value_norm') or ''
qn = p.get('quote_norm') or '' qn = p.get('quote_norm') or ''
if not value_norm: if not value_norm or _is_pure_numeric(value_norm):
continue continue
if (vn and value_norm in vn) or (qn and value_norm in qn): if (vn and value_norm in vn) or (qn and value_norm in qn):
return 'normalized_substring', p return 'normalized_substring', p
@@ -225,7 +237,7 @@ def validate_suggestions_against_evidence(
evidence_pack: dict[str, Any], evidence_pack: dict[str, Any],
envelope: dict[str, Any] | None = None, envelope: dict[str, Any] | None = None,
expected_target_field_id: str | None = None, expected_target_field_id: str | None = None,
expected_line_key: str | None = None, expected_draft_line_id: str | None = None,
expected_scope: str | None = None, expected_scope: str | None = None,
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
""" """
@@ -236,7 +248,7 @@ def validate_suggestions_against_evidence(
evidence_pack: select_review_evidence_pack 输出(v1/v2 均含 fields 等)。 evidence_pack: select_review_evidence_pack 输出(v1/v2 均含 fields 等)。
envelope: build_suggestion_request_envelope 输出(用于 v2 evidence[] 和 target)。 envelope: build_suggestion_request_envelope 输出(用于 v2 evidence[] 和 target)。
expected_target_field_id: 期望的唯一目标 field_id(v2 envelope.target.field_id 兜底)。 expected_target_field_id: 期望的唯一目标 field_id(v2 envelope.target.field_id 兜底)。
expected_line_key: 期望 line_key(行 scope 用;header scope 传 None)。 expected_draft_line_id: 期望草稿行身份(行 scope 用;header scope 传 None)。
expected_scope: 'header' / 'line'(从 schema_field_meta.scope 兜底)。 expected_scope: 'header' / 'line'(从 schema_field_meta.scope 兜底)。
Returns: Returns:
@@ -258,9 +270,9 @@ def validate_suggestions_against_evidence(
or str(target.get('field_id') or '').strip() or str(target.get('field_id') or '').strip()
or '' or ''
) )
_exp_lk_raw = expected_line_key _exp_lk_raw = expected_draft_line_id
if _exp_lk_raw is None: if _exp_lk_raw is None:
_exp_lk_from_env = target.get('line_key') _exp_lk_from_env = target.get('draft_line_id')
_exp_lk_raw = None if _exp_lk_from_env is None else str(_exp_lk_from_env) _exp_lk_raw = None if _exp_lk_from_env is None else str(_exp_lk_from_env)
_exp_lk = str(_exp_lk_raw).strip() if _exp_lk_raw is not None else None _exp_lk = str(_exp_lk_raw).strip() if _exp_lk_raw is not None else None
if _exp_lk == '' or _exp_lk == 'None': if _exp_lk == '' or _exp_lk == 'None':
@@ -296,18 +308,18 @@ def validate_suggestions_against_evidence(
result.append(payload) result.append(payload)
continue continue
# ---- [Check 2] header_scope_has_line_key ---- # ---- [Check 2] header_scope_has_draft_line_id ----
checks_ran.append('header_scope_has_line_key') checks_ran.append('header_scope_has_draft_line_id')
resp_scope = str(raw_item.get('scope') or '').strip().lower() resp_scope = str(raw_item.get('scope') or '').strip().lower()
if not resp_scope: if not resp_scope:
resp_scope = 'line' if _exp_lk else 'header' resp_scope = 'line' if _exp_lk else 'header'
resp_lk_raw = raw_item.get('line_key') resp_lk_raw = raw_item.get('draft_line_id')
resp_lk = None if resp_lk_raw is None else str(resp_lk_raw).strip() resp_lk = None if resp_lk_raw is None else str(resp_lk_raw).strip()
if resp_lk in ('', 'None'): if resp_lk in ('', 'None'):
resp_lk = None resp_lk = None
effective_scope = _exp_scope if resp_scope not in {'header', 'line'} else resp_scope effective_scope = _exp_scope if resp_scope not in {'header', 'line'} else resp_scope
if effective_scope == 'header' and resp_lk is not None: if effective_scope == 'header' and resp_lk is not None:
rejection_reason = 'header_scope_has_line_key' rejection_reason = 'header_scope_has_draft_line_id'
if rejection_reason: if rejection_reason:
payload['valid'] = False payload['valid'] = False
payload['rejection_reason'] = rejection_reason payload['rejection_reason'] = rejection_reason
@@ -338,11 +350,11 @@ def validate_suggestions_against_evidence(
result.append(payload) result.append(payload)
continue continue
# ---- [Check 5] line_key_mismatch(行 scope 才校验;header scope line_key 须 None 已在 Check 2)---- # ---- [Check 5] draft_line_id_mismatch ----
checks_ran.append('line_key_mismatch') checks_ran.append('draft_line_id_mismatch')
if effective_scope == 'line': if effective_scope == 'line':
if _exp_lk and resp_lk != _exp_lk: if _exp_lk and resp_lk != _exp_lk:
rejection_reason = 'line_key_mismatch' rejection_reason = 'draft_line_id_mismatch'
if rejection_reason: if rejection_reason:
payload['valid'] = False payload['valid'] = False
payload['rejection_reason'] = rejection_reason payload['rejection_reason'] = rejection_reason
@@ -368,7 +380,7 @@ def validate_suggestions_against_evidence(
value_norm=sv_norm, value_norm=sv_norm,
quote_norm_provided=quote_norm, quote_norm_provided=quote_norm,
field_id=resp_fid, field_id=resp_fid,
line_key=resp_lk, draft_line_id=resp_lk,
) )
if not _matched_mode: if not _matched_mode:
rejection_reason = 'value_not_in_evidence' rejection_reason = 'value_not_in_evidence'
@@ -112,7 +112,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
if not isinstance(proj, dict): if not isinstance(proj, dict):
continue continue
effective = str(proj.get('effective_reservation_id') or '').strip() or None effective = str(proj.get('effective_reservation_id') or '').strip() or None
line_key = str(proj.get('line_key') or '').strip() or None draft_line_id = str(proj.get('draft_line_id') or '').strip() or None
block_reason = str(proj.get('block_reason') or '').strip() or None block_reason = str(proj.get('block_reason') or '').strip() or None
line_reservation_issue = next( line_reservation_issue = next(
( (
@@ -133,7 +133,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
) )
lines_out.append({ lines_out.append({
'line_index': idx, 'line_index': idx,
'line_key': line_key, 'draft_line_id': draft_line_id,
'effective_reservation_id': effective, 'effective_reservation_id': effective,
'can_build': bool(proj.get('can_build', True)), 'can_build': bool(proj.get('can_build', True)),
# Reservation 面板只展示自身 Gate 原因,不能泄漏库存路由 block_reason。 # Reservation 面板只展示自身 Gate 原因,不能泄漏库存路由 block_reason。
@@ -150,7 +150,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
rid = _current_line_reservation_id(line, reservation_field_id) rid = _current_line_reservation_id(line, reservation_field_id)
lines_out.append({ lines_out.append({
'line_index': idx, 'line_index': idx,
'line_key': str(line.get('line_key') or '').strip() or None, 'draft_line_id': str(line.get('draft_line_id') or '').strip() or None,
'effective_reservation_id': rid, 'effective_reservation_id': rid,
'can_build': True, 'can_build': True,
'block_reason': None, 'block_reason': None,
@@ -170,7 +170,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
'severity': str(item.get('severity') or 'blocking')[:32], 'severity': str(item.get('severity') or 'blocking')[:32],
'message': str(item.get('message') or '')[:240] or None, 'message': str(item.get('message') or '')[:240] or None,
'line_index': item.get('line_index'), 'line_index': item.get('line_index'),
'line_key': item.get('line_key'), 'draft_line_id': item.get('draft_line_id'),
'field_code': item.get('field_code') or 'reservation_id', 'field_code': item.get('field_code') or 'reservation_id',
} }
for item in issues[:20] for item in issues[:20]
@@ -80,6 +80,68 @@ def _canonical_values(fields: Any, code: str, codes: dict[str, str], config: dic
} }
def _canonical_values_span(
fields: Any, span_codes: set[str], ids: dict[str, str], configs: dict[str, dict[str, Any]],
) -> set[Any]:
"""收集字段跨多个同订单料号身份 code 的规范值集合(件号/客户件号交叉)。
与匹配层 `part_number ∪ customer_part_number` 的裁决保持一致:邮件补充的 PN 列
值可能实为客户件号(MPN),只要命中 PDF 的任一料号身份就视为同一料号,
禁止把「邮件 PN = PDF 客户件号」判成 `part_number` 字段冲突。
Args:
fields: 目标字段 Observation 列表(header 或 line)。
span_codes: 视作同一身份的字段 code 集合(如 {'part_number','customer_part_number'})。
ids: {field_code: field_id} 映射。
configs: {field_code: 冻结 Schema 配置} 映射,用于各字段独立标准化。
Returns:
跨这些 code 收集到的规范值集合。
"""
if not isinstance(fields, list):
return set()
code_by_id = {str(field_id): code for code, field_id in ids.items()}
out: set[Any] = set()
for field in fields:
if not isinstance(field, dict):
continue
code = code_by_id.get(str(field.get('field_id') or ''))
if code not in span_codes:
continue
config = configs.get(code)
if config is None:
continue
for observation in field.get('observations') or []:
if isinstance(observation, dict) and observation.get('value') not in (None, ''):
out.add(_canonical_field_value(observation.get('value'), config))
return out
# 采购单号类字段:跨来源比较须与匹配层一致,用 PO 专用标准化(含前导零归一),
# 否则 0060208010 与 60208010 会被 Schema「lowercase_trim」误判为不同 PO 而制造冲突。
_PO_CODES = {'customer_po_number', 'po_number'}
def _conflict_canonical(value: Any, field_code: str, config: dict[str, Any]) -> Any:
"""返回冲突比较用的字段规范值;PO 类字段复用 PO 标准化,其余走 Schema 正常化。"""
if field_code in _PO_CODES:
return normalize_atomic_po_number(value).upper()
return _canonical_field_value(value, config)
def _conflict_canonical_values(fields: Any, code: str, codes: dict[str, str], config: dict[str, Any]) -> set[Any]:
"""收集字段冲突比较用的规范值集合;PO 类字段使用 _conflict_canonical。"""
if not isinstance(fields, list):
return set()
return {
_conflict_canonical(observation.get('value'), code, config)
for field in fields if isinstance(field, dict)
if codes.get(str(field.get('field_id') or '')) == code
for observation in field.get('observations') or [] if isinstance(observation, dict)
if observation.get('value') not in (None, '')
}
def _field_observations(fields: Any, code: str, codes: dict[str, str]) -> list[dict[str, Any]]: def _field_observations(fields: Any, code: str, codes: dict[str, str]) -> list[dict[str, Any]]:
"""返回字段的原始 Observation,供冲突 Finding 保留 PDF 侧可追溯证据。""" """返回字段的原始 Observation,供冲突 Finding 保留 PDF 侧可追溯证据。"""
if not isinstance(fields, list): if not isinstance(fields, list):
@@ -125,14 +187,21 @@ def _supplement_field_conflict(
{ {
'source_type': 'pdf', 'source_type': 'pdf',
'raw_value': str(pdf_raw), 'raw_value': str(pdf_raw),
'canonical_value': str(_canonical_field_value(pdf_raw, config)), 'canonical_value': str(_conflict_canonical(pdf_raw, field_code, config)),
'document_id': pdf.get('document_id'), 'document_id': pdf.get('document_id'),
'evidence_ref': dict(pdf.get('evidence_ref') or {}), # evidence_ref 必须保持 dict 契约(review/evidence 消费方按 dict 处理)。
# 坐标 observation 的 evidence_ref 是字符串、layout_evidence 才是证据 dict;
# 直接用 dict(<字符串>) 会把字符串按字符拆成长度1序列而崩(dictionary update length 1)。
'evidence_ref': (
pdf.get('layout_evidence')
if isinstance(pdf.get('layout_evidence'), dict)
else (pdf.get('evidence_ref') if isinstance(pdf.get('evidence_ref'), dict) else {})
),
}, },
{ {
'source_type': 'email_body', 'source_type': 'email_body',
'raw_value': str(email_raw), 'raw_value': str(email_raw),
'canonical_value': str(_canonical_field_value(email_raw, config)), 'canonical_value': str(_conflict_canonical(email_raw, field_code, config)),
'document_id': email_document_id or None, 'document_id': email_document_id or None,
'evidence_ref': dict(email_evidence or {}), 'evidence_ref': dict(email_evidence or {}),
}, },
@@ -162,7 +231,7 @@ def _supplement_multi_value_conflict(
sources.append({ sources.append({
'source_type': 'email_body', 'source_type': 'email_body',
'raw_value': raw_value, 'raw_value': raw_value,
'canonical_value': str(_canonical_field_value(raw_value, config)), 'canonical_value': str(_conflict_canonical(raw_value, field_code, config)),
'document_id': email_document_id or None, 'document_id': email_document_id or None,
'evidence_ref': dict(evidence or {}), 'evidence_ref': dict(evidence or {}),
}) })
@@ -271,7 +340,7 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
raw_value = str(item.get(target_code) or '').strip() raw_value = str(item.get(target_code) or '').strip()
if raw_value: if raw_value:
value_by_canonical.setdefault( value_by_canonical.setdefault(
_canonical_field_value(raw_value, config), _conflict_canonical(raw_value, target_code, config),
(raw_value, item), (raw_value, item),
) )
values = {raw_value for raw_value, _ in value_by_canonical.values()} values = {raw_value for raw_value, _ in value_by_canonical.values()}
@@ -292,13 +361,23 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
field_id = ids.get(target_code) field_id = ids.get(target_code)
if not value or not field_id: if not value or not field_id:
continue continue
existing_values = _canonical_values( same_code_values = _conflict_canonical_values(
fields, target_code, {v: k for k, v in ids.items()}, config, fields, target_code, {v: k for k, v in ids.items()}, config,
) )
if existing_values: if same_code_values:
# PDF 是主证据,但正文给出不同的唯一 Schema 值也不能被静默忽略: # PDF 是主证据,但正文给出不同的唯一 Schema 值也不能被静默忽略:
# 保留 PDF 值,强制进入 Review 由人工裁决。 # 保留 PDF 值,强制进入 Review 由人工裁决。
if existing_values != {_canonical_field_value(value, config)}: email_canonical = _conflict_canonical(value, target_code, config)
if target_code in part_codes:
# 件号/客户件号属同一料号身份:邮件值命中任一 PDF 料号即视为一致,
# 不因「邮件 PN 实为客户件号(MPN)」制造误判 `part_number` 冲突。
conflicts_with_pdf = (
email_canonical
not in _canonical_values_span(fields, part_codes, ids, configs)
)
else:
conflicts_with_pdf = same_code_values != {email_canonical}
if conflicts_with_pdf:
conflict = _supplement_field_conflict( conflict = _supplement_field_conflict(
field_code=target_code, field_code=target_code,
config=config, config=config,
@@ -9,7 +9,7 @@ backend/app/services/shipping_notice/order_task_service.py
局部重识别走 replace_order_task_candidate_after_reparse(专用审计); 局部重识别走 replace_order_task_candidate_after_reparse(专用审计);
sync_order_task_processing_state 统一写入 stage/status、递增 progress_version, sync_order_task_processing_state 统一写入 stage/status、递增 progress_version,
并强制写 order_task_progress_changed 审计; 并强制写 order_task_progress_changed 审计;
建单成功后按 candidate_id 定位 OT 再挂 shipping_notice_id(禁止误用 Run 根号串单); 正式 ShippingNotice 通过 order_task_id 关联 OT;OT 不反向保存通知单指针。
GET 投影只读本表,禁止读路径创建。 GET 投影只读本表,禁止读路径创建。
""" """
@@ -146,7 +146,6 @@ def sync_order_task_processing_state(
}, },
metadata={ metadata={
'extraction_run_id': getattr(order_task, 'extraction_run_id', None), 'extraction_run_id': getattr(order_task, 'extraction_run_id', None),
'shipping_notice_id': getattr(order_task, 'shipping_notice_id', None),
'candidate_id': getattr(order_task, 'candidate_id', None), 'candidate_id': getattr(order_task, 'candidate_id', None),
}, },
source=str(source or 'order_task_service'), source=str(source or 'order_task_service'),
@@ -442,11 +441,6 @@ def replace_order_task_candidate_after_review(
'order task candidate binding changed concurrently', 'order task candidate binding changed concurrently',
code='SHIPPING_NOTICE.ORDER_TASK_CANDIDATE_MISMATCH', code='SHIPPING_NOTICE.ORDER_TASK_CANDIDATE_MISMATCH',
) )
if order_task.shipping_notice_id is not None:
raise ConflictError(
'order task already linked to a shipping notice',
code='SHIPPING_NOTICE.ORDER_TASK_ALREADY_LINKED',
)
case_document_id = int(case.document_id) if getattr(case, 'document_id', None) else None case_document_id = int(case.document_id) if getattr(case, 'document_id', None) else None
new_document_id = ( new_document_id = (
@@ -938,7 +932,7 @@ def resolve_order_task_for_candidate(candidate_id: int | None) -> Optional[Shipp
def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional[ShippingOrderTask]: def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional[ShippingOrderTask]:
""" """
建单成功后双向挂接 OT ↔ Notice。 将正式 Notice 单向挂接到 OT。
Args: Args:
order_task_no: OT 编号(须为该 Candidate 自己的 OT,禁止误用 Run 根号)。 order_task_no: OT 编号(须为该 Candidate 自己的 OT,禁止误用 Run 根号)。
@@ -957,15 +951,7 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional
) )
if row is None: if row is None:
return None return None
before = { before = {'candidate_id': row.candidate_id}
'shipping_notice_id': row.shipping_notice_id,
'candidate_id': row.candidate_id,
}
# 兼容字段只在首张 Notice 尚未建立时回填,后续分批 Notice 以
# ShippingNotice.order_task_id 的多对一关系为权威,禁止覆盖首条指针。
if row.shipping_notice_id is None:
row.shipping_notice_id = int(notice_id)
row.updated_at = datetime.utcnow()
from app.models import ShippingNotice from app.models import ShippingNotice
notice = db.session.get(ShippingNotice, int(notice_id)) notice = db.session.get(ShippingNotice, int(notice_id))
@@ -985,7 +971,6 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional
reason_code='notice_created', reason_code='notice_created',
before=before, before=before,
after={ after={
'shipping_notice_id': row.shipping_notice_id,
'candidate_id': row.candidate_id, 'candidate_id': row.candidate_id,
'notice_task_no': str(getattr(notice, 'task_no', None) or '') or None, 'notice_task_no': str(getattr(notice, 'task_no', None) or '') or None,
}, },
@@ -292,10 +292,18 @@ def sync_order_task_stage_for_candidate(
return None return None
# 正式建单后的 Candidate 仍可能因恢复/对账再次触发资格重算; # 正式建单后的 Candidate 仍可能因恢复/对账再次触发资格重算;
# 此时建单前资格阶段不再是权威事实,禁止覆盖 OT 当前履约阶段。 # 此时建单前资格阶段不再是权威事实,禁止覆盖 OT 当前履约阶段。
if ( if getattr(candidate, 'consumed_task_id', None) is not None:
getattr(candidate, 'consumed_task_id', None) is not None return ot
or getattr(ot, 'shipping_notice_id', None) is not None # 已挂正式通知单:以 Notice→OT(ShippingNotice.order_task_id)反向关联为准,
): # OT 本身不保存通知单指针。只要已有任意 Notice 指向该 OT,即说明 OT 已进入
# 履约阶段,建单前资格阶段不再是权威事实:原样返回,禁止回退到确认前 stage。
if getattr(ot, 'id', None) is not None:
bound_notice = (
ShippingNotice.query
.filter(ShippingNotice.order_task_id == int(ot.id))
.first()
)
if bound_notice is not None:
return ot return ot
stage, status = resolve_pre_confirm_stage( stage, status = resolve_pre_confirm_stage(
candidate=candidate, candidate=candidate,
@@ -328,7 +336,7 @@ def sync_order_task_stage_for_notice(
Args: Args:
notice: 正式发货通知。 notice: 正式发货通知。
order_task: 可选;缺省按 notice.order_task_id / ShippingOrderTask.shipping_notice_id。 order_task: 可选;缺省按 notice.order_task_id 反查 OT。
Returns: Returns:
更新后的 OT;找不到时 None。 更新后的 OT;找不到时 None。
@@ -340,18 +348,13 @@ def sync_order_task_stage_for_notice(
ot = order_task ot = order_task
if ot is None and getattr(notice, 'order_task_id', None): if ot is None and getattr(notice, 'order_task_id', None):
ot = db.session.get(ShippingOrderTask, int(notice.order_task_id)) ot = db.session.get(ShippingOrderTask, int(notice.order_task_id))
if ot is None and getattr(notice, 'id', None):
ot = (
ShippingOrderTask.query.filter_by(shipping_notice_id=int(notice.id))
.order_by(ShippingOrderTask.id.desc())
.first()
)
if ot is None: if ot is None:
return None return None
status, stage = map_notice_to_processing_status_stage(notice) status, stage = map_notice_to_processing_status_stage(notice)
# [STEP] Execution.current_gate_code 是正式履约事实,优先于尚未来得及写入 Notice # [STEP] Execution.current_gate_code 是正式履约事实,优先于尚未来得及写入 Notice
# 领域字段的默认映射;只接受 active/waiting_external/blocked 执行,避免旧 Execution 回退 OT。 # 领域字段的默认映射;只接受 active/waiting_external/blocked 执行,避免旧 Execution 回退 OT。
active_execution_id = getattr(notice, 'active_process_execution_id', None) # ProcessExecution 属于 OT;正式 Notice 不保存执行指针。
active_execution_id = getattr(ot, 'active_process_execution_id', None)
if active_execution_id is not None: if active_execution_id is not None:
from app.models import ShippingProcessExecution from app.models import ShippingProcessExecution
@@ -359,9 +362,16 @@ def sync_order_task_stage_for_notice(
execution_status = str(getattr(execution, 'status', None) or '').strip().lower() execution_status = str(getattr(execution, 'status', None) or '').strip().lower()
gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower() gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower()
gate_stage = _PROCESS_GATE_TO_PROCESSING_STAGE.get(gate_code) gate_stage = _PROCESS_GATE_TO_PROCESSING_STAGE.get(gate_code)
if execution_status in {'active', 'waiting_external', 'blocked'} and gate_stage: # [FIX] current_gate_code 是正式履约事实。即使 execution.status 仍为 completed
# (历史遗留旧值或 Gate 状态在 `_refresh_execution_pointers` 刷新前被旁路写成
# blocked),只要 current_gate_code 仍指向一个未通过 Gate,就不能让 OT.stage 滞留
# completed 而与实际卡住环节矛盾:据此把该 Gate 阶段回写,并落 blocked。
if gate_stage and execution_status in {'active', 'waiting_external', 'blocked'}:
stage = gate_stage stage = gate_stage
status = 'automating' if execution_status in {'active', 'waiting_external'} else 'blocked' status = 'automating' if execution_status in {'active', 'waiting_external'} else 'blocked'
elif gate_stage and execution_status == 'completed':
stage = gate_stage
status = 'blocked'
if stage not in SHIPPING_PROCESSING_STAGES: if stage not in SHIPPING_PROCESSING_STAGES:
stage = 'inventory_matching' stage = 'inventory_matching'
return sync_order_task_processing_state( return sync_order_task_processing_state(
@@ -22,6 +22,7 @@ _ATOMIC_PO_NUMBER_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9\-_/]*")
def normalize_po_number(value: Any) -> str: def normalize_po_number(value: Any) -> str:
""" """
标准化采购单号;Wistron 等客户原文常带 ZNB 前缀(如 ZNB16754796 / ZNB-16754796),输出为纯数字段。 标准化采购单号;Wistron 等客户原文常带 ZNB 前缀(如 ZNB16754796 / ZNB-16754796),输出为纯数字段。
纯数字 PO 前导零视为格式差异(0060208010 与 60208010 是同一张 PO),统一剥除,避免跨来源误判冲突。
""" """
text = str(value or "").strip() text = str(value or "").strip()
if not text: if not text:
@@ -32,8 +33,8 @@ def normalize_po_number(value: Any) -> str:
if upper.startswith("ZNB") and len(text) > 3: if upper.startswith("ZNB") and len(text) > 3:
tail = text[3:].strip().lstrip("-_/ ") tail = text[3:].strip().lstrip("-_/ ")
if tail.isdigit(): if tail.isdigit():
return tail return tail.lstrip("0") or "0"
return text return text.lstrip("0") or "0"
def normalize_atomic_po_number(value: Any) -> str: def normalize_atomic_po_number(value: Any) -> str:
@@ -89,11 +89,17 @@ def _target_is_safe(task: ShippingNotice) -> bool:
核心逻辑:与历史 open_existing Reservation 回填安全边界保持一致,避免已推进任务被静默改写。 核心逻辑:与历史 open_existing Reservation 回填安全边界保持一致,避免已推进任务被静默改写。
""" """
if str(task.pending_human_reason or '').strip().lower() != PH_RSV_REQ: from app.services.shipping_notice.process_gate_projection import task_blocking_reason
if str(task_blocking_reason(task) or '').strip().lower() != PH_RSV_REQ:
return False return False
if task.inventory_lines_json or task.line_results_json or task.export_file_path or task.freight_ref_no: from app.services.shipping_notice.inventory_file_store import (
return False current_inventory_matches_for_task,
if task.match_status or task.upload_status: has_ready_inventory_file_for_task,
)
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt
if has_ready_inventory_file_for_task(task) or current_inventory_matches_for_task(task) or latest_export_artifact(task) is not None or latest_upload_attempt(task) is not None:
return False return False
return True return True
@@ -334,7 +340,7 @@ def apply_candidate_reconciliation_plan(
], ],
} }
step_payload['field_conflicts'] = {'open_count': len(open_rows)} step_payload['field_conflicts'] = {'open_count': len(open_rows)}
task.step_payload_json = step_payload task.step_payload_json = (step_payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'}})
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
return { return {
'status': 'conflicted', 'status': 'conflicted',
@@ -385,7 +391,7 @@ def apply_candidate_reconciliation_plan(
step_payload.pop('process_field_gate', None) step_payload.pop('process_field_gate', None)
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
task.error_message = None task.error_message = None
task.step_payload_json = step_payload task.step_payload_json = (step_payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'}})
return { return {
'status': 'applied', 'status': 'applied',
'reason': 'fields_backfilled', 'reason': 'fields_backfilled',
@@ -19,12 +19,17 @@ from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ( from app.models import (
ShippingExportArtifact, ShippingExportArtifact,
ShippingOrderCandidate, ShippingOrderCandidate,
ShippingOrderExtraction,
ShippingOrderIntake, ShippingOrderIntake,
ShippingOrderTask,
ShippingCustomerShadowResolution,
ShippingNotice, ShippingNotice,
ShippingTaskEvent, ShippingTaskEvent,
ShippingTaskInventoryLink, ShippingTaskInventoryLink,
ShippingTaskPurgeAudit, ShippingTaskPurgeAudit,
ShippingNoticeLineInventoryMatch,
) )
from app.models.shipping_task_line import ShippingTaskFieldConflict
TaskDispositionAction = Literal['delete', 'void', 'archive', 'restore'] TaskDispositionAction = Literal['delete', 'void', 'archive', 'restore']
@@ -43,7 +48,7 @@ class TaskDispositionCapability:
reason: str | None = None reason: str | None = None
def task_is_active(task: ShippingNotice) -> bool: def task_is_active(task: ShippingNotice | ShippingOrderTask) -> bool:
""" """
判断任务是否仍可触发履约副作用。 判断任务是否仍可触发履约副作用。
@@ -61,7 +66,7 @@ def task_is_active(task: ShippingNotice) -> bool:
) )
def task_execution_block_reason(task: ShippingNotice) -> str | None: def task_execution_block_reason(task: ShippingNotice | ShippingOrderTask) -> str | None:
""" """
为异步编排和外部回调提供统一的副作用熔断原因。 为异步编排和外部回调提供统一的副作用熔断原因。
@@ -79,7 +84,7 @@ def task_execution_block_reason(task: ShippingNotice) -> str | None:
return f'task_lifecycle_{lifecycle or "inactive"}' return f'task_lifecycle_{lifecycle or "inactive"}'
def load_task_for_disposition(task_no: str) -> ShippingNotice: def load_task_for_disposition(task_no: str) -> ShippingNotice | ShippingOrderTask:
""" """
以行锁加载任务,供同一事务内重新判定并写入处置结果。 以行锁加载任务,供同一事务内重新判定并写入处置结果。
@@ -97,27 +102,29 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice:
if not normalized_task_no: if not normalized_task_no:
raise ValidationError('task_no is required', code='SHIPPING.TASK_NO_REQUIRED') raise ValidationError('task_no is required', code='SHIPPING.TASK_NO_REQUIRED')
task = ( task = (
ShippingNotice.query ShippingOrderTask.query.filter(ShippingOrderTask.task_no == normalized_task_no)
.filter(ShippingNotice.task_no == normalized_task_no) .with_for_update().first()
.with_for_update()
.first()
) )
if task is None:
task = ShippingOrderTask.query.filter(ShippingOrderTask.task_no == normalized_task_no).with_for_update().first()
if task is None: if task is None:
raise NotFoundError('Shipping task not found', code='SHIPPING.TASK_NOT_FOUND') raise NotFoundError('Shipping task not found', code='SHIPPING.TASK_NOT_FOUND')
return task return task
def _has_external_fulfillment(task: ShippingNotice) -> bool: def _has_external_fulfillment(task: ShippingNotice | ShippingOrderTask) -> bool:
"""识别已提交、正在提交或已有外部上传参考的任务;这些任务不可在平台单方作废。""" """识别已提交、正在提交或已有外部上传参考的任务;这些任务不可在平台单方作废。"""
upload_status = str(task.upload_status or '').strip().lower() from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip().lower()
return bool( return bool(
task.freight_ref_no upload_status in _EXTERNAL_UPLOAD_STATUSES
or upload_status in _EXTERNAL_UPLOAD_STATUSES
) )
def _has_successor(task: ShippingNotice) -> bool: def _has_successor(task: ShippingNotice | ShippingOrderTask) -> bool:
"""修订链存在后继时禁止作废旧任务,避免破坏版本追溯。""" """修订链存在后继时禁止作废旧任务,避免破坏版本追溯。"""
if not isinstance(task, ShippingNotice):
return False
return ( return (
db.session.query(ShippingNotice.id) db.session.query(ShippingNotice.id)
.filter(ShippingNotice.supersedes_task_id == int(task.id)) .filter(ShippingNotice.supersedes_task_id == int(task.id))
@@ -127,7 +134,7 @@ def _has_successor(task: ShippingNotice) -> bool:
def task_disposition_capability( def task_disposition_capability(
task: ShippingNotice, task: ShippingNotice | ShippingOrderTask,
action: TaskDispositionAction, action: TaskDispositionAction,
) -> TaskDispositionCapability: ) -> TaskDispositionCapability:
""" """
@@ -200,7 +207,7 @@ def _disposition_reason_code(event_type: str, detail: dict[str, Any]) -> str | N
def _write_disposition_event( def _write_disposition_event(
task: ShippingNotice, task: ShippingNotice | ShippingOrderTask,
*, *,
event_type: str, event_type: str,
actor_id: int | None, actor_id: int | None,
@@ -216,8 +223,10 @@ def _write_disposition_event(
reason_code = _disposition_reason_code(event_type, payload) reason_code = _disposition_reason_code(event_type, payload)
if reason_code: if reason_code:
payload.setdefault('reason_code', reason_code) payload.setdefault('reason_code', reason_code)
from app.services.shipping_notice.tool_common import task_event_task_id
if isinstance(task, ShippingNotice):
db.session.add(ShippingTaskEvent( db.session.add(ShippingTaskEvent(
task_id=int(task.id), task_id=task_event_task_id(task),
event_type=event_type, event_type=event_type,
actor_id=actor_id, actor_id=actor_id,
request_id=str(request_id or '').strip()[:64] or None, request_id=str(request_id or '').strip()[:64] or None,
@@ -237,7 +246,12 @@ def _write_disposition_event(
result='success', result='success',
after={ after={
'lifecycle_status': getattr(task, 'lifecycle_status', None), 'lifecycle_status': getattr(task, 'lifecycle_status', None),
'upload_status': getattr(task, 'upload_status', None), 'upload_status': getattr(
__import__('app.services.shipping_notice.upload_attempt_service', fromlist=['latest_upload_attempt'])
.latest_upload_attempt(task),
'status',
None,
),
}, },
metadata={ metadata={
'dual_write': 'shipping_task_event', 'dual_write': 'shipping_task_event',
@@ -281,15 +295,25 @@ def move_task_to_recycle_bin(
raise ConflictError(capability.reason or 'Task delete is blocked', code=capability.code or 'SHIPPING.TASK_DELETE_BLOCKED') raise ConflictError(capability.reason or 'Task delete is blocked', code=capability.code or 'SHIPPING.TASK_DELETE_BLOCKED')
# [STEP 1] 已解析或已产生内部引用的任务先作废,再进入回收站;纯 created 误建仅隐藏。 # [STEP 1] 已解析或已产生内部引用的任务先作废,再进入回收站;纯 created 误建仅隐藏。
owner_task = (
db.session.get(ShippingOrderTask, int(task.order_task_id))
if isinstance(task, ShippingNotice) and task.order_task_id else task
)
has_internal_business_record = bool( has_internal_business_record = bool(
task.business_no getattr(task, 'business_no', None)
or task.customer_id or (
or task.source_candidate_id db.session.query(ShippingCustomerShadowResolution.id).filter_by(
or task.match_status candidate_id=getattr(owner_task, 'candidate_id', None), status='confirmed',
or task.export_file_path ).filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)).first()
or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).first() )
or db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).first() or getattr(owner_task, 'candidate_id', None)
or db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).first() or bool(db.session.query(ShippingNoticeLineInventoryMatch.id).filter_by(task_id=int(owner_task.id), is_current=True).first())
or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(owner_task.id)).first()
or db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(owner_task.id)).first()
or (
isinstance(task, ShippingNotice)
and db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).first()
)
) )
now = datetime.utcnow() now = datetime.utcnow()
task.deleted_at = now task.deleted_at = now
@@ -318,7 +342,7 @@ def move_task_to_recycle_bin(
def void_task( def void_task(
task: ShippingNotice, task: ShippingNotice | ShippingOrderTask,
*, *,
actor_id: int, actor_id: int,
reason: str, reason: str,
@@ -346,7 +370,7 @@ def void_task(
def archive_task( def archive_task(
task: ShippingNotice, task: ShippingNotice | ShippingOrderTask,
*, *,
actor_id: int, actor_id: int,
request_id: str | None = None, request_id: str | None = None,
@@ -368,7 +392,7 @@ def archive_task(
def restore_task_from_recycle_bin( def restore_task_from_recycle_bin(
task: ShippingNotice, task: ShippingNotice | ShippingOrderTask,
*, *,
actor_id: int, actor_id: int,
request_id: str | None = None, request_id: str | None = None,
@@ -390,7 +414,7 @@ def restore_task_from_recycle_bin(
def purge_task_permanently( def purge_task_permanently(
task: ShippingNotice, task: ShippingNotice | ShippingOrderTask,
*, *,
actor_id: int, actor_id: int,
reason: str, reason: str,
@@ -414,18 +438,50 @@ def purge_task_permanently(
if task.deleted_at is None or str(task.lifecycle_status or 'active') != 'active': if task.deleted_at is None or str(task.lifecycle_status or 'active') != 'active':
raise ConflictError('Only deleted pure draft task can be purged', code='SHIPPING.TASK_PURGE_BLOCKED') raise ConflictError('Only deleted pure draft task can be purged', code='SHIPPING.TASK_PURGE_BLOCKED')
from app.models import ShippingOrderExtraction, ShippingTemporaryInventorySession # OT 尚未生成 Notice 时只检查其自身的解析/库存/审计引用,禁止访问 Notice 专属字段。
from app.models.shipping_task_line import ShippingTaskFieldConflict if isinstance(task, ShippingOrderTask):
blocking_counts = {
'current_order_extraction': int(bool(task.current_order_extraction_id)),
'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(),
'candidate_consumed': db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).count(),
'intake_consumed': db.session.query(ShippingOrderIntake.id).filter_by(consumed_task_id=int(task.id)).count(),
'order_extraction': db.session.query(ShippingOrderExtraction.id).filter_by(task_id=int(task.id)).count(),
'inventory_link': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(),
'field_conflict': db.session.query(ShippingTaskFieldConflict.id).filter_by(task_id=int(task.id)).count(),
}
blocking = {key: value for key, value in blocking_counts.items() if value}
if blocking:
raise ConflictError(
'Order task has business or audit references and cannot be purged',
code='SHIPPING.TASK_PURGE_BLOCKED',
details={'blocking': blocking},
)
db.session.delete(task)
db.session.add(ShippingTaskPurgeAudit(
task_no_snapshot=task.task_no,
actor_id=actor_id,
reason=normalized_reason,
snapshot_json={'task_no': task.task_no, 'lifecycle_status': task.lifecycle_status},
))
return
from app.models import ShippingTemporaryInventorySession
# [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。 # [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。
owner = task if hasattr(task, 'current_order_extraction_id') else None
customer_confirmed = False
if owner is not None and owner.current_order_extraction_id:
customer_confirmed = db.session.query(ShippingCustomerShadowResolution.id).filter_by(
candidate_id=owner.candidate_id, status='confirmed',
).filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)).first() is not None
blocking_counts = { blocking_counts = {
'business_number': int(bool(task.business_no)), 'business_number': int(bool(task.business_no)),
'customer': int(bool(task.customer_id)), 'customer': int(customer_confirmed),
'source_asset': int(bool(task.source_asset_id)), 'source_asset': int(bool(task.source_asset_id)),
'source_intake': int(bool(task.source_intake_id)), 'source_intake': int(bool(task.source_intake_id)),
'source_candidate': int(bool(task.source_candidate_id)), 'source_candidate': int(bool(task.source_candidate_id)),
'current_order_extraction': int(bool(task.current_order_extraction_id)), 'current_order_extraction': int(bool(task.current_order_extraction_id)),
'inventory_snapshot': int(bool(task.inventory_snapshot_id)), 'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(),
'successor': int(_has_successor(task)), 'successor': int(_has_successor(task)),
'duplicate_link': int(bool(task.duplicate_source_task_id)), 'duplicate_link': int(bool(task.duplicate_source_task_id)),
'duplicate_source_for_other_task': db.session.query(ShippingNotice.id).filter( 'duplicate_source_for_other_task': db.session.query(ShippingNotice.id).filter(
@@ -235,6 +235,7 @@ def resolve_field_conflict(
remaining = list_open_field_conflicts(task) remaining = list_open_field_conflicts(task)
issues = task_reservation_gate_issues(task) issues = task_reservation_gate_issues(task)
step_payload = dict(task.step_payload_json or {}) step_payload = dict(task.step_payload_json or {})
if task.__class__.__name__ != 'ShippingOrderTask':
step_payload['field_conflicts'] = { step_payload['field_conflicts'] = {
'open_count': len(remaining), 'open_count': len(remaining),
'last_resolved_id': conflict.id, 'last_resolved_id': conflict.id,
@@ -242,6 +243,7 @@ def resolve_field_conflict(
if idempotency_key: if idempotency_key:
step_payload['last_conflict_resolve_idempotency_key'] = str(idempotency_key).strip() step_payload['last_conflict_resolve_idempotency_key'] = str(idempotency_key).strip()
if remaining: if remaining:
if task.__class__.__name__ != 'ShippingOrderTask':
step_payload['process_field_gate'] = { step_payload['process_field_gate'] = {
'status': 'needs_enrichment', 'status': 'needs_enrichment',
'missing_fields': sorted({row.field_name for row in remaining}), 'missing_fields': sorted({row.field_name for row in remaining}),
@@ -258,6 +260,7 @@ def resolve_field_conflict(
} }
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
elif issues: elif issues:
if task.__class__.__name__ != 'ShippingOrderTask':
step_payload['process_field_gate'] = { step_payload['process_field_gate'] = {
'status': 'needs_enrichment', 'status': 'needs_enrichment',
'missing_fields': ['reservation_id'], 'missing_fields': ['reservation_id'],
@@ -273,7 +276,9 @@ def resolve_field_conflict(
'issues': issues, 'issues': issues,
'resolution_source': 'field_conflict_resolve', 'resolution_source': 'field_conflict_resolve',
} }
task.step_payload_json = step_payload task.step_payload_json = step_payload if task.__class__.__name__ != 'ShippingOrderTask' else {
key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'}
}
log_task_event( log_task_event(
task, task,
@@ -152,9 +152,10 @@ def current_line_field_configs(task: ShippingNotice) -> dict[str, dict[str, Any]
def _current_extraction(task: ShippingNotice) -> ShippingOrderExtraction: def _current_extraction(task: ShippingNotice) -> ShippingOrderExtraction:
"""读取任务当前已接受 Extraction;人工编辑绝不回退旧任务行投影。""" """读取任务当前已接受 Extraction;人工编辑绝不回退旧任务行投影。"""
extraction_id = getattr(task, 'current_order_extraction_id', None)
extraction = ( extraction = (
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) db.session.get(ShippingOrderExtraction, extraction_id)
if task.current_order_extraction_id is not None else None if extraction_id is not None else None
) )
if extraction is None or extraction.status != 'accepted': if extraction is None or extraction.status != 'accepted':
raise ConflictError('Task has no accepted order extraction', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED') raise ConflictError('Task has no accepted order extraction', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED')
@@ -338,7 +339,7 @@ def replace_current_line_fields(*, task: ShippingNotice, lines: list[dict[str, A
value_json=previous_value.value_json, value_json=previous_value.value_json,
)) ))
for position, values in enumerate(lines): for position, values in enumerate(lines):
line = ShippingOrderLine(extraction_id=replacement.id, position=position) line = ShippingOrderLine(extraction_id=replacement.id, position=position, line_no=position + 1)
db.session.add(line) db.session.add(line)
db.session.flush() db.session.flush()
for config in configs: for config in configs:
@@ -6,8 +6,9 @@ from datetime import datetime
from app import db from app import db
from app.core.errors import ConflictError, ValidationError from app.core.errors import ConflictError, ValidationError
from app.models import ShippingFreightCancellation, ShippingNotice, ShippingTaskEvent from app.models import ShippingFreightCancellation, ShippingNotice, ShippingOrderTask, ShippingTaskEvent
from app.services.shipping_notice.task_disposition_service import task_is_active from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.tool_common import task_event_task_id
def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingNotice, actor_id: int, reason: str) -> None: def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingNotice, actor_id: int, reason: str) -> None:
@@ -18,24 +19,48 @@ def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingN
raise ConflictError('Revision parent mismatch', code='SHIPPING.TASK_SUPERSESSION_INVALID') raise ConflictError('Revision parent mismatch', code='SHIPPING.TASK_SUPERSESSION_INVALID')
if not task_is_active(old): if not task_is_active(old):
return return
external = bool(old.freight_ref_no or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'}) from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
latest_attempt = latest_upload_attempt(old)
external = bool(
has_verified_upload_success(old)
or str(getattr(latest_attempt, 'freight_ref_no', '') or '').strip()
)
if external: if external:
existing = ShippingFreightCancellation.query.filter_by(old_task_id=old.id, new_task_id=new.id).one_or_none() existing = ShippingFreightCancellation.query.filter_by(old_task_id=old.id, new_task_id=new.id).one_or_none()
if existing is None: if existing is None:
db.session.add(ShippingFreightCancellation(old_task_id=old.id, new_task_id=new.id, requested_by_id=actor_id, reason=reason)) db.session.add(ShippingFreightCancellation(old_task_id=old.id, new_task_id=new.id, requested_by_id=actor_id, reason=reason))
new.lifecycle_status = 'blocked' new_owner = (
new.pending_human_reason = 'freight_cancellation_required' db.session.get(ShippingOrderTask, int(new.order_task_id))
db.session.add(ShippingTaskEvent(task_id=new.id, event_type='supersession_cancellation_required', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason})) if new.order_task_id is not None else None
)
if new_owner is not None:
# lifecycle_status 仅表达 active/voided/archived;流程阻断属于 status。
new_owner.status = 'blocked'
new_owner.pending_human_reason = 'freight_cancellation_required'
db.session.add(ShippingTaskEvent(task_id=task_event_task_id(new), event_type='supersession_cancellation_required', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason}))
return return
old.lifecycle_status = 'voided' old.lifecycle_status = 'voided'
old.voided_at = datetime.utcnow() old.voided_at = datetime.utcnow()
old.voided_by_id = actor_id old.voided_by_id = actor_id
old.void_reason = reason old.void_reason = reason
db.session.add(ShippingTaskEvent(task_id=old.id, event_type='task_superseded', actor_id=actor_id, detail_json={'new_task_no': new.task_no, 'reason': reason})) db.session.add(ShippingTaskEvent(task_id=task_event_task_id(old), event_type='task_superseded', actor_id=actor_id, detail_json={'new_task_no': new.task_no, 'reason': reason}))
db.session.add(ShippingTaskEvent(task_id=new.id, event_type='task_supersession_established', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason, 'at': datetime.utcnow().isoformat()})) db.session.add(ShippingTaskEvent(task_id=task_event_task_id(new), event_type='task_supersession_established', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason, 'at': datetime.utcnow().isoformat()}))
def assert_task_not_supersession_blocked(task: ShippingNotice) -> None: def assert_task_not_supersession_blocked(task: ShippingNotice) -> None:
"""库存、导出和上传入口调用,阻止撤销未完成的新版本继续履约。""" """库存、导出和上传入口调用,阻止撤销未完成的新版本继续履约。"""
if str(task.lifecycle_status or '').lower() == 'blocked' and task.pending_human_reason == 'freight_cancellation_required': if isinstance(task, ShippingOrderTask):
lifecycle = str(getattr(task, 'lifecycle_status', '') or '').lower()
reason = str(getattr(task, 'pending_human_reason', '') or '').lower()
if str(getattr(task, 'status', '') or '').lower() == 'blocked' and reason == 'freight_cancellation_required':
raise ConflictError('Freight cancellation is required before this revision can continue', code='SHIPPING.FREIGHT_CANCELLATION_REQUIRED')
return
owner = (
db.session.get(ShippingOrderTask, int(task.order_task_id))
if task.order_task_id is not None else None
)
lifecycle = str(getattr(owner, 'status', None) or '').lower()
reason = str(getattr(owner, 'pending_human_reason', None) or '').lower()
if lifecycle == 'blocked' and reason == 'freight_cancellation_required':
raise ConflictError('Freight cancellation is required before this revision can continue', code='SHIPPING.FREIGHT_CANCELLATION_REQUIRED') raise ConflictError('Freight cancellation is required before this revision can continue', code='SHIPPING.FREIGHT_CANCELLATION_REQUIRED')
@@ -2,9 +2,9 @@
services/shipping_notice/task_workflow.py services/shipping_notice/task_workflow.py
用途:发货通知任务/批次生命周期、解析与单头/订单行编辑的主编排入口。 用途:发货通知任务/批次生命周期、解析与单头/订单行编辑的主编排入口。
依赖:query_service、tool_common、decision_workflow、progress_workflow、state_machine、 依赖:query_service、tool_common、progress_workflow、state_machine、
fulfillment_audit、schema_edit_policy、动态订单字段编辑器、candidate_qualification_service。 fulfillment_audit、schema_edit_policy、动态订单字段编辑器、candidate_qualification_service。
逻辑:tools.py 门面委托本模块;创建 Task 前强制客户已确认(禁止先建单再 customer_review); 逻辑:tools.py 门面委托本模块;创建 OT 不强制客户已确认(先建单,客户确认交由订单复核/客户门禁处理);
正式字段编辑经 Schema 策略门禁后落库,并按 change_effect 失效下游; 正式字段编辑经 Schema 策略门禁后落库,并按 change_effect 失效下游;
成功/拒绝编辑与库存/Excel 失效同事务写入 ShippingAuditEvent; 成功/拒绝编辑与库存/Excel 失效同事务写入 ShippingAuditEvent;
retry_task 写入操作人与前后快照审计。 retry_task 写入操作人与前后快照审计。
@@ -20,9 +20,8 @@ from sqlalchemy.exc import IntegrityError
from app import db from app import db
from app.core.errors import ConflictError, ValidationError from app.core.errors import ConflictError, ValidationError
from app.models import ShippingNotice from app.models import ShippingNotice, ShippingOrderTask, ShippingOrderIntake
from app.services.shipping_notice.constants import CP_TASK_EXISTS from app.services.shipping_notice.constants import CP_TASK_EXISTS
from app.services.shipping_notice.decision_workflow import submit_decision
from app.services.shipping_notice.task_order_field_editor import ( from app.services.shipping_notice.task_order_field_editor import (
current_header_field_values, current_header_field_values,
retire_current_order_extraction, retire_current_order_extraction,
@@ -52,8 +51,7 @@ from app.services.shipping_notice.batch_create_idempotency import (
assert_no_exact_duplicate_notices, assert_no_exact_duplicate_notices,
) )
from app.services.shipping_notice.candidate_qualification_service import ( from app.services.shipping_notice.candidate_qualification_service import (
assert_customer_confirmed_before_task_create, resolve_confirmed_customer_id,
resolve_confirmed_bill_to_customer_id,
) )
from app.services.shipping_notice.tool_common import ( from app.services.shipping_notice.tool_common import (
generate_task_no, generate_task_no,
@@ -64,6 +62,13 @@ from app.services.shipping_notice.tool_common import (
) )
from app.models import ShippingOrderCandidate, ShippingOrderReviewEvent from app.models import ShippingOrderCandidate, ShippingOrderReviewEvent
def _has_ready_inventory_file(task: ShippingNotice | ShippingOrderTask) -> bool:
"""读取活动 Link 指向的 ready 文件,作为重试审计中的库存事实。"""
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
return has_ready_inventory_file_for_task(task)
EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"}) EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"})
EDITABLE_NOTICE_LINE_FIELDS = frozenset({ EDITABLE_NOTICE_LINE_FIELDS = frozenset({
"part_number", "part_number",
@@ -76,6 +81,12 @@ EDITABLE_NOTICE_LINE_FIELDS = frozenset({
}) })
def _task_intake(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderIntake | None:
"""返回 OT 关联的 Intake,原始正文与来源元数据统一由 Intake 承载。"""
intake_id = getattr(task, 'intake_id', None)
return db.session.get(ShippingOrderIntake, int(intake_id)) if intake_id else None
def start_task_orchestrator(task_no: str | None) -> bool: def start_task_orchestrator(task_no: str | None) -> bool:
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。""" """延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
@@ -122,9 +133,9 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
) )
if conv_id: if conv_id:
existing = ( existing = (
ShippingNotice.query.filter_by(conversation_id=conv_id) ShippingOrderTask.query.filter_by(conversation_id=conv_id)
.filter(ShippingNotice.lifecycle_status == 'active') .filter(ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled'}))
.order_by(ShippingNotice.id.desc()) .order_by(ShippingOrderTask.id.desc())
.first() .first()
) )
if existing: if existing:
@@ -133,31 +144,29 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
task_id=existing.task_no, task_id=existing.task_no,
message=( message=(
f"当前会话已有进行中的发货任务 {existing.task_no},请勿重复 create_task。" f"当前会话已有进行中的发货任务 {existing.task_no},请勿重复 create_task。"
"用户确认/驳回时请 submit_decision,并带上任务编号或 conversation_id。"
), ),
data=qs_serialize_task(existing, TaskProjection.TOOL_INTERNAL), data=qs_serialize_task(existing, TaskProjection.TOOL_INTERNAL),
checkpoint=CP_TASK_EXISTS, checkpoint=CP_TASK_EXISTS,
) )
# [STEP] 单票建单同样要求客户已确认,禁止创建后进入 customer_review。 # [STEP] 接收解析阶段只创建 OT;客户确认由订单复核/客户门禁处理,不能阻止 OT 落库。
customer_id = _parse_optional_customer_id(payload.get("customer_id")) customer_id = _parse_optional_customer_id(payload.get("customer_id"))
assert_customer_confirmed_before_task_create( user_id = payload.get("user_id")
customer_id=customer_id, if user_id is None:
) raise ValidationError('user_id is required', code='SHIPPING.USER_REQUIRED')
task = ShippingNotice( task = ShippingOrderTask(
task_no=generate_task_no(), task_no=generate_task_no(),
customer_id=customer_id, user_id=int(user_id),
user_id=payload.get("user_id"),
conversation_id=str(payload.get("conversation_id") or "").strip() or None, conversation_id=str(payload.get("conversation_id") or "").strip() or None,
source_type=str(payload.get("source_type") or "manual"), # OT 仅接受 intake 层定义的来源类型;未知/手工入口保持 NULL,避免违反模型约束。
batch_index=1, source_type=(str(payload.get("source_type") or "").strip() or None),
batch_total=1, status='processing',
raw_content=str(payload.get("raw_content") or "").strip() or None, stage='document_parsing',
customer_resolution_status='pending',
) )
db.session.add(task) db.session.add(task)
log_task_event(task, "task_created", {"source_type": task.source_type}) log_task_event(task, "task_created", {"source_type": task.source_type})
db.session.flush() db.session.flush()
if customer_id is not None:
_bind_confirmed_customer_after_task_create( _bind_confirmed_customer_after_task_create(
task, task,
customer_id=customer_id, customer_id=customer_id,
@@ -190,7 +199,7 @@ def _parse_optional_customer_id(raw: Any) -> int | None:
def _bind_confirmed_customer_after_task_create( def _bind_confirmed_customer_after_task_create(
task: ShippingNotice, task: ShippingOrderTask,
*, *,
customer_id: int | None, customer_id: int | None,
candidate: ShippingOrderCandidate | None, candidate: ShippingOrderCandidate | None,
@@ -199,9 +208,9 @@ def _bind_confirmed_customer_after_task_create(
""" """
创建 Task 后立即绑定已确认客户,避免以 pending 进入 customer_review。 创建 Task 后立即绑定已确认客户,避免以 pending 进入 customer_review。
核心逻辑:用显式 customer_id 或候选 Bill-to 直接确认当前 Notice。 核心逻辑:用显式 customer_id 或已确认识别结果直接确认当前 OT。
""" """
bind_id = customer_id or resolve_confirmed_bill_to_customer_id(candidate=candidate) bind_id = customer_id or resolve_confirmed_customer_id(candidate=candidate)
if bind_id is None: if bind_id is None:
raise ConflictError( raise ConflictError(
'Customer must be confirmed before creating a shipping task', 'Customer must be confirmed before creating a shipping task',
@@ -229,69 +238,43 @@ def _notice_header_snapshot(task: ShippingNotice) -> dict[str, Any]:
def _reset_notice_edit_downstream(task: ShippingNotice) -> None: def _reset_notice_edit_downstream(task: ShippingNotice) -> None:
"""清空匹配/导出/上传等派生结果,供 require_revision / 库存重算类 change_effect 使用。""" """清空匹配/导出/上传等派生结果,供 require_revision / 库存重算类 change_effect 使用。"""
task.match_status = None order_task = _resolve_order_task_for_notice(task)
task.shortage_json = None if order_task is None:
task.line_results_json = None return
task.export_file_path = None step_payload = dict(order_task.step_payload_json or {})
task.export_file_name = None
task.freight_ref_no = None
task.upload_status = None
task.upload_mode = None
task.upload_attempt = 0
task.upload_started_at = None
task.upload_finished_at = None
task.upload_error_code = None
task.upload_error_message = None
task.upload_receipt_json = None
task.idempotency_key = None
step_payload = dict(task.step_payload_json or {})
step_payload.pop('export_meta', None) step_payload.pop('export_meta', None)
task.step_payload_json = step_payload order_task.step_payload_json = step_payload
def _reset_notice_export_downstream(task: ShippingNotice) -> None: def _reset_notice_export_downstream(task: ShippingNotice) -> None:
"""仅使 Excel 导出派生结果失效,保留库存匹配真相。""" """仅使 Excel 导出派生结果失效,保留库存匹配真相。"""
task.export_file_path = None order_task = _resolve_order_task_for_notice(task)
task.export_file_name = None if order_task is None:
task.freight_ref_no = None return
task.upload_status = None step_payload = dict(order_task.step_payload_json or {})
task.upload_mode = None
task.upload_attempt = 0
task.upload_started_at = None
task.upload_finished_at = None
task.upload_error_code = None
task.upload_error_message = None
task.upload_receipt_json = None
task.idempotency_key = None
step_payload = dict(task.step_payload_json or {})
step_payload.pop('export_meta', None) step_payload.pop('export_meta', None)
task.step_payload_json = step_payload order_task.step_payload_json = step_payload
def _resolve_order_task_for_notice(task: ShippingNotice): def _resolve_order_task_for_notice(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderTask | None:
"""按 Notice 反查 OT;供 change_effect 同步统一进度 stage。""" """按 Notice 反查 OT;若入参本身即 OT 则直接返回,供 change_effect 同步统一进度 stage。"""
from app.models import ShippingOrderTask if isinstance(task, ShippingOrderTask):
return task
order_task_id = getattr(task, 'order_task_id', None) order_task_id = getattr(task, 'order_task_id', None)
if order_task_id is not None: if order_task_id is not None:
return db.session.get(ShippingOrderTask, int(order_task_id)) return db.session.get(ShippingOrderTask, int(order_task_id))
return ( return None
db.session.query(ShippingOrderTask)
.filter(ShippingOrderTask.shipping_notice_id == int(task.id))
.order_by(ShippingOrderTask.id.asc())
.first()
)
def _set_notice_invalidated_from_stage(task: ShippingNotice, stage: str) -> None: def _set_notice_invalidated_from_stage(task: ShippingNotice, stage: str) -> None:
""" """
将改单失效起点写入 Notice.step_payload_json,供投影 stage_nodes 消费。 将改单失效起点写入 OT.step_payload_json,供投影 stage_nodes 消费。
[BE-08] 写入时追加 invalidated_from_stage_history,降低无历史可追溯风险; [BE-08] 写入时追加 invalidated_from_stage_history,降低无历史可追溯风险;
完整列级约束与乐观锁仍待显式字段迁移。 完整列级约束与乐观锁仍待显式字段迁移。
Args: Args:
task: 被编辑的正式任务。 task: 被编辑的正式任务(ShippingNotice)。
stage: 失效起点统一 stage。 stage: 失效起点统一 stage。
""" """
from datetime import datetime from datetime import datetime
@@ -301,33 +284,42 @@ def _set_notice_invalidated_from_stage(task: ShippingNotice, stage: str) -> None
code = str(stage or '').strip().lower() code = str(stage or '').strip().lower()
if code not in SHIPPING_PROCESSING_STAGES: if code not in SHIPPING_PROCESSING_STAGES:
return return
payload = dict(task.step_payload_json or {}) if isinstance(task.step_payload_json, dict) else {} order_task = _resolve_order_task_for_notice(task)
if order_task is None:
return
payload = (
dict(order_task.step_payload_json or {})
if isinstance(order_task.step_payload_json, dict) else {}
)
history = payload.get('invalidated_from_stage_history') history = payload.get('invalidated_from_stage_history')
if not isinstance(history, list): if not isinstance(history, list):
history = [] history = []
history.append({ history.append({
'stage': code, 'stage': code,
'at': datetime.utcnow().isoformat(timespec='seconds') + 'Z', 'at': datetime.utcnow().isoformat(timespec='seconds') + 'Z',
'progress_version': int(getattr(task, 'progress_version', None) or 0), 'progress_version': int(getattr(order_task, 'progress_version', None) or 0),
}) })
payload['invalidated_from_stage'] = code payload['invalidated_from_stage'] = code
payload['invalidated_from_stage_history'] = history[-20:] payload['invalidated_from_stage_history'] = history[-20:]
task.step_payload_json = payload order_task.step_payload_json = payload
def _clear_notice_invalidated_from_stage(task: ShippingNotice) -> None: def _clear_notice_invalidated_from_stage(task: ShippingNotice) -> None:
""" """
清除 Notice 上的改单失效起点(下游已成功重跑后)。 清除 OT 上的改单失效起点(下游已成功重跑后)。
[BE-08] 清除仅移除当前起点;历史列表保留供审计追溯。 [BE-08] 清除仅移除当前起点;历史列表保留供审计追溯。
""" """
if not isinstance(task.step_payload_json, dict): order_task = _resolve_order_task_for_notice(task)
if order_task is None:
return return
if 'invalidated_from_stage' not in task.step_payload_json: if not isinstance(order_task.step_payload_json, dict):
return return
payload = dict(task.step_payload_json) if 'invalidated_from_stage' not in order_task.step_payload_json:
return
payload = dict(order_task.step_payload_json)
payload.pop('invalidated_from_stage', None) payload.pop('invalidated_from_stage', None)
task.step_payload_json = payload order_task.step_payload_json = payload
def read_notice_invalidated_from_stage(task: ShippingNotice | None) -> str | None: def read_notice_invalidated_from_stage(task: ShippingNotice | None) -> str | None:
@@ -344,7 +336,10 @@ def read_notice_invalidated_from_stage(task: ShippingNotice | None) -> str | Non
if task is None: if task is None:
return None return None
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} order_task = _resolve_order_task_for_notice(task)
if order_task is None:
return None
payload = order_task.step_payload_json if isinstance(order_task.step_payload_json, dict) else {}
code = str(payload.get('invalidated_from_stage') or '').strip().lower() code = str(payload.get('invalidated_from_stage') or '').strip().lower()
return code if code in SHIPPING_PROCESSING_STAGES else None return code if code in SHIPPING_PROCESSING_STAGES else None
@@ -374,7 +369,6 @@ def _apply_notice_edit_change_effects(
from app.services.shipping_notice.schema_edit_policy import collect_change_effects_for_fields from app.services.shipping_notice.schema_edit_policy import collect_change_effects_for_fields
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
from app.services.shipping_notice.inventory_source_gate import ( from app.services.shipping_notice.inventory_source_gate import (
STABLE_INVENTORY_SOURCE_STATUSES,
adjudicate_and_apply_inventory_source, adjudicate_and_apply_inventory_source,
clear_inventory_source_confirmation, clear_inventory_source_confirmation,
) )
@@ -399,18 +393,12 @@ def _apply_notice_edit_change_effects(
# [STEP] 库存源重算优先于匹配重算:不得跳过 inventory_source_resolving。 # [STEP] 库存源重算优先于匹配重算:不得跳过 inventory_source_resolving。
if 'rerun_inventory_source_resolution' in effects: if 'rerun_inventory_source_resolution' in effects:
clear_inventory_source_confirmation(task) clear_inventory_source_confirmation(task)
task.inventory_source_status = 'unresolved'
task.inventory_source_code = None
task.inventory_connector_type = None
task.inventory_warehouse_id = None
task.match_status = None
task.shortage_json = None
task.line_results_json = None
task.inventory_lines_json = None
_reset_notice_export_downstream(task) _reset_notice_export_downstream(task)
_set_notice_invalidated_from_stage(task, 'inventory_source_resolving') _set_notice_invalidated_from_stage(task, 'inventory_source_resolving')
adjudication = adjudicate_and_apply_inventory_source(task) adjudication = adjudicate_and_apply_inventory_source(task)
stable = str(adjudication.status or '').strip() in STABLE_INVENTORY_SOURCE_STATUSES from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
stable = is_inventory_source_stable(task)
if order_task is not None: if order_task is not None:
if stable: if stable:
sync_order_task_processing_state( sync_order_task_processing_state(
@@ -429,10 +417,6 @@ def _apply_notice_edit_change_effects(
return applied return applied
if 'rerun_inventory_matching' in effects: if 'rerun_inventory_matching' in effects:
task.match_status = None
task.shortage_json = None
task.line_results_json = None
task.inventory_lines_json = None
_reset_notice_export_downstream(task) _reset_notice_export_downstream(task)
_set_notice_invalidated_from_stage(task, 'inventory_matching') _set_notice_invalidated_from_stage(task, 'inventory_matching')
if order_task is not None: if order_task is not None:
@@ -553,9 +537,11 @@ def _record_formal_task_edit_audits(
'export_file_name': before_export_file_name, 'export_file_name': before_export_file_name,
'order_data_version': before_order_data_version, 'order_data_version': before_order_data_version,
} }
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
after_artifact = latest_export_artifact(task)
after_summary = { after_summary = {
'match_status': task.match_status, 'match_status': None,
'export_file_name': task.export_file_name, 'export_file_name': getattr(after_artifact, 'file_name', None),
'order_data_version': task.order_data_version, 'order_data_version': task.order_data_version,
} }
field_changes = _formal_edit_field_diff_summary( field_changes = _formal_edit_field_diff_summary(
@@ -605,7 +591,7 @@ def _record_formal_task_edit_audits(
reason_code='inventory_match_invalidated', reason_code='inventory_match_invalidated',
result='success', result='success',
before={'match_status': before_match_status}, before={'match_status': before_match_status},
after={'match_status': task.match_status}, after={'match_status': None},
metadata={'applied_effects': sorted(applied_effects), 'evidence_ref': evidence_ref}, metadata={'applied_effects': sorted(applied_effects), 'evidence_ref': evidence_ref},
source='workspace_api', source='workspace_api',
) )
@@ -627,7 +613,7 @@ def _record_formal_task_edit_audits(
reason_code='excel_export_invalidated', reason_code='excel_export_invalidated',
result='success', result='success',
before={'export_file_name': before_export_file_name}, before={'export_file_name': before_export_file_name},
after={'export_file_name': task.export_file_name}, after={'export_file_name': getattr(after_artifact, 'file_name', None)},
metadata={'applied_effects': sorted(applied_effects), 'evidence_ref': evidence_ref}, metadata={'applied_effects': sorted(applied_effects), 'evidence_ref': evidence_ref},
source='workspace_api', source='workspace_api',
) )
@@ -707,14 +693,14 @@ def replace_task_notice(
""" """
cleaned_text = str(raw_text or "").strip() cleaned_text = str(raw_text or "").strip()
cleaned_warnings = [str(item).strip() for item in (warnings or []) if str(item).strip()] cleaned_warnings = [str(item).strip() for item in (warnings or []) if str(item).strip()]
intake = _task_intake(task)
if not cleaned_text: if not cleaned_text:
apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED) apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
task.error_message = "未能从重新上传的发货通知中抽取到可解析文本" task.error_message = "未能从重新上传的发货通知中抽取到可解析文本"
task.raw_content = "" if intake is not None:
if source_file_name: intake.extracted_text = ""
task.source_file_name = source_file_name intake.error_message = task.error_message
if source_file_type: intake.parse_warnings_json = cleaned_warnings
task.source_file_type = source_file_type
set_task_step_progress( set_task_step_progress(
task, task,
step_key="step2_parse_confirm", step_key="step2_parse_confirm",
@@ -736,13 +722,10 @@ def replace_task_notice(
data={**serialize_task_for_tool(task), "warnings": cleaned_warnings}, data={**serialize_task_for_tool(task), "warnings": cleaned_warnings},
) )
task.raw_content = cleaned_text if intake is not None:
if source_file_name: intake.extracted_text = cleaned_text
task.source_file_name = source_file_name intake.parse_warnings_json = cleaned_warnings
if source_file_type:
task.source_file_type = source_file_type
retire_current_order_extraction(task) retire_current_order_extraction(task)
task.parse_confidence = None
task.review_status = None task.review_status = None
task.pending_human_reason = None task.pending_human_reason = None
task.error_message = None task.error_message = None
@@ -821,6 +804,30 @@ def _assert_order_data_version(task: ShippingNotice, payload: dict[str, Any]) ->
return None return None
def _edit_window_busy_error(task: ShippingNotice) -> dict[str, Any] | None:
"""
二期编辑窗守卫(D10/§3.3):订单任一通知存在活动 Gate Attempt(库存 RPA / 匹配 queued|running)
时拒绝保存,返回 SYSTEM_BUSY 的 failed Tool 响应;否则 None。
Args:
task: 被编辑的 ShippingNotice。
Returns:
活动 Attempt 时的 tool_response(status='failed', error_code=SHIPPING.EDIT_WINDOW_SYSTEM_BUSY);
通过则 None。
"""
from app.services.shipping_notice.order_edit_window_service import order_has_active_attempt
if order_has_active_attempt(task):
return tool_response(
status='failed',
task=task,
message='系统处理中,请稍后再修改。',
data={'error_code': 'SHIPPING.EDIT_WINDOW_SYSTEM_BUSY'},
)
return None
def _notice_edit_idempotency_replay( def _notice_edit_idempotency_replay(
task: ShippingNotice, task: ShippingNotice,
payload: dict[str, Any], payload: dict[str, Any],
@@ -829,7 +836,10 @@ def _notice_edit_idempotency_replay(
key = str(payload.get('idempotency_key') or '').strip() key = str(payload.get('idempotency_key') or '').strip()
if not key: if not key:
return None return None
step_payload = dict(task.step_payload_json or {}) order_task = _resolve_order_task_for_notice(task)
if order_task is None:
return None
step_payload = dict(order_task.step_payload_json or {})
last = step_payload.get('last_notice_edit_idempotency') last = step_payload.get('last_notice_edit_idempotency')
if not isinstance(last, dict): if not isinstance(last, dict):
return None return None
@@ -853,9 +863,35 @@ def _remember_notice_edit_idempotency(
text = str(key or '').strip() text = str(key or '').strip()
if not text: if not text:
return return
step_payload = dict(task.step_payload_json or {}) order_task = _resolve_order_task_for_notice(task)
if order_task is None:
return
step_payload = dict(order_task.step_payload_json or {})
step_payload['last_notice_edit_idempotency'] = {'key': text, 'message': message} step_payload['last_notice_edit_idempotency'] = {'key': text, 'message': message}
task.step_payload_json = step_payload order_task.step_payload_json = step_payload
def _order_task_match_status_for_audit(order_task: ShippingOrderTask | None) -> str | None:
"""
读取 OT 当前行级库存匹配状态(matched / shortage / None),
供正式编辑审计 before 快照记录失效前的真实 match_status。
核心逻辑:以行级 Match 事实为准(禁止读取 OT 缓存字段),
all 行匹配且无短缺为 matched,否则有行时视为 shortage;无行返回 None。
"""
if order_task is None:
return None
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
facts = list(load_current_match_facts_by_task(order_task.id).values())
if not facts:
return None
matched = all(
str(row.get('match_result') or '').strip().lower() == 'matched'
and str(row.get('shortage_qty') or '').strip() in {'', '0', '0.0', '0.00'}
for row in facts
)
return 'matched' if matched else 'shortage'
def _commit_notice_edit( def _commit_notice_edit(
@@ -887,7 +923,10 @@ def _commit_notice_edit(
if not reviewed_by_id or not evidence_ref or not reason: if not reviewed_by_id or not evidence_ref or not reason:
raise ConflictError('Review evidence is required', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED') raise ConflictError('Review evidence is required', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED')
# [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。 # [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。
step_payload = dict(task.step_payload_json or {}) order_task = _resolve_order_task_for_notice(task)
if order_task is None:
raise ConflictError('Formal task edit requires a linked order task', code='SHIPPING.ORDER_TASK_REQUIRED')
step_payload = dict(order_task.step_payload_json or {})
validation_issues = task_reservation_gate_issues(task) validation_issues = task_reservation_gate_issues(task)
step_payload["parse_validation"] = { step_payload["parse_validation"] = {
"status": "needs_review" if validation_issues else "ready", "status": "needs_review" if validation_issues else "ready",
@@ -903,11 +942,12 @@ def _commit_notice_edit(
} }
else: else:
step_payload.pop('process_field_gate', None) step_payload.pop('process_field_gate', None)
task.step_payload_json = step_payload order_task.step_payload_json = step_payload
# [STEP 2] 先按 change_effect 失效下游;仅缺字段或 require_revision 才回旧复核态。 # [STEP 2] 先按 change_effect 失效下游;仅缺字段或 require_revision 才回旧复核态。
before_match_status = task.match_status before_match_status = _order_task_match_status_for_audit(order_task)
before_export_file_name = task.export_file_name from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
before_export_file_name = getattr(latest_export_artifact(task), 'file_name', None)
before_order_data_version = task.order_data_version before_order_data_version = task.order_data_version
applied_effects = _apply_notice_edit_change_effects(task, edited_field_scopes or []) applied_effects = _apply_notice_edit_change_effects(task, edited_field_scopes or [])
if validation_issues: if validation_issues:
@@ -1046,6 +1086,10 @@ def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]:
version_error = _assert_order_data_version(task, payload) version_error = _assert_order_data_version(task, payload)
if version_error is not None: if version_error is not None:
return version_error return version_error
# 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。
busy_error = _edit_window_busy_error(task)
if busy_error is not None:
return busy_error
fields = payload.get("fields") fields = payload.get("fields")
if not isinstance(fields, dict) or not fields: if not isinstance(fields, dict) or not fields:
@@ -1137,6 +1181,10 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
version_error = _assert_order_data_version(task, payload) version_error = _assert_order_data_version(task, payload)
if version_error is not None: if version_error is not None:
return version_error return version_error
# 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。
busy_error = _edit_window_busy_error(task)
if busy_error is not None:
return busy_error
try: try:
line_index = int(payload.get("line_index")) line_index = int(payload.get("line_index"))
@@ -1244,6 +1292,10 @@ def add_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
version_error = _assert_order_data_version(task, payload) version_error = _assert_order_data_version(task, payload)
if version_error is not None: if version_error is not None:
return version_error return version_error
# 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。
busy_error = _edit_window_busy_error(task)
if busy_error is not None:
return busy_error
line = payload.get("line") line = payload.get("line")
if not isinstance(line, dict) or not line: if not isinstance(line, dict) or not line:
@@ -1288,6 +1340,10 @@ def remove_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
version_error = _assert_order_data_version(task, payload) version_error = _assert_order_data_version(task, payload)
if version_error is not None: if version_error is not None:
return version_error return version_error
# 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。
busy_error = _edit_window_busy_error(task)
if busy_error is not None:
return busy_error
try: try:
line_index = int(payload.get("line_index")) line_index = int(payload.get("line_index"))
@@ -1347,10 +1403,6 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
task.error_message = None task.error_message = None
# [BE-放行-重试] 重试应重新评估当前库存事实:清空旧匹配结果,强制 orchest 在下一轮 # [BE-放行-重试] 重试应重新评估当前库存事实:清空旧匹配结果,强制 orchest 在下一轮
# 重新匹配,而不是带着旧的 unfulfillable/shortage 直接跳到步骤(避免旧缺货残留)。 # 重新匹配,而不是带着旧的 unfulfillable/shortage 直接跳到步骤(避免旧缺货残留)。
task.match_status = None
task.line_results_json = None
task.shortage_json = None
try: try:
order_lines = current_line_field_values(task) order_lines = current_line_field_values(task)
except ConflictError: except ConflictError:
@@ -1384,7 +1436,10 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
reason=comment or None, reason=comment or None,
before=before, before=before,
after=after, after=after,
metadata={'has_order_lines': bool(order_lines), 'has_inventory_lines': bool(task.inventory_lines_json)}, metadata={
'has_order_lines': bool(order_lines),
'has_inventory_lines': _has_ready_inventory_file(task),
},
source=event_source, source=event_source,
) )
db.session.commit() db.session.commit()
@@ -18,7 +18,7 @@ import uuid
from flask import current_app from flask import current_app
from app import db from app import db
from app.models import ShippingNotice, ShippingTaskEvent from app.models import ShippingNotice, ShippingOrderTask, ShippingTaskEvent
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
@@ -221,8 +221,11 @@ def set_task_step_progress(
detail: str | None = None, detail: str | None = None,
extra: dict[str, Any] | None = None, extra: dict[str, Any] | None = None,
) -> None: ) -> None:
"""写入任务当前步骤与步骤内细粒度进度,统一落到 current_step + step_payload_json。""" """写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。"""
payload = dict(task.step_payload_json or {}) owner = task
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None):
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
payload = dict(getattr(owner, 'step_payload_json', None) or {})
progress: dict[str, Any] = { progress: dict[str, Any] = {
"step_key": step_key, "step_key": step_key,
"step_title": step_title, "step_title": step_title,
@@ -240,15 +243,23 @@ def set_task_step_progress(
if extra: if extra:
progress["extra"] = extra progress["extra"] = extra
payload["current_step_progress"] = progress payload["current_step_progress"] = progress
task.current_step = step_key if hasattr(owner, 'current_step'):
task.step_payload_json = payload owner.current_step = step_key
if hasattr(owner, 'stage'):
owner.stage = step_key
if hasattr(owner, 'step_payload_json'):
owner.step_payload_json = payload
def clear_task_step_progress(task: ShippingNotice) -> None: def clear_task_step_progress(task: ShippingNotice) -> None:
"""清空任务步骤内进度,保留其他 step_payload_json 字段。""" """清空任务步骤内进度,保留其他 step_payload_json 字段。"""
payload = dict(task.step_payload_json or {}) owner = task
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None):
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
payload = dict(getattr(owner, 'step_payload_json', None) or {})
payload.pop("current_step_progress", None) payload.pop("current_step_progress", None)
task.step_payload_json = payload or None if hasattr(owner, 'step_payload_json'):
owner.step_payload_json = payload or None
@@ -307,7 +318,7 @@ def build_task_action_event_detail(
def log_task_event( def log_task_event(
task: ShippingNotice, task: ShippingNotice | ShippingOrderTask,
event_type: str, event_type: str,
detail: dict[str, Any] | None = None, detail: dict[str, Any] | None = None,
*, *,
@@ -333,10 +344,14 @@ def log_task_event(
before: 操作前业务快照。 before: 操作前业务快照。
after: 操作后业务快照。 after: 操作后业务快照。
""" """
if task.id is None: event_task_id = task_event_task_id(task)
if event_task_id is None:
db.session.flush() db.session.flush()
event_task_id = task_event_task_id(task)
if event_task_id is None:
raise ValueError('shipping task event requires an order task id')
db.session.add(ShippingTaskEvent( db.session.add(ShippingTaskEvent(
task_id=task.id, task_id=event_task_id,
event_type=event_type, event_type=event_type,
detail_json=detail or {}, detail_json=detail or {},
actor_id=actor_id, actor_id=actor_id,
@@ -436,6 +451,14 @@ def log_task_event(
) )
def task_event_task_id(task: ShippingNotice | ShippingOrderTask) -> int | None:
"""将 Notice/OT 输入统一解析为 ShippingTaskEvent 使用的 OT 主键。"""
if isinstance(task, ShippingOrderTask):
return int(task.id) if task.id is not None else None
order_task_id = getattr(task, 'order_task_id', None)
return int(order_task_id) if order_task_id is not None else None
def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) -> str | None: def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) -> str | None:
""" """
将任务事件类型映射为可解释性稳定 reason_code,供审计中心筛选。 将任务事件类型映射为可解释性稳定 reason_code,供审计中心筛选。
@@ -505,7 +528,7 @@ def task_lifecycle_audit_snapshot(task: ShippingNotice) -> dict[str, Any]:
snapshot = { snapshot = {
'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None), 'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None),
'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None), 'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None),
'reason_code': getattr(task, 'pending_human_reason', None), 'reason_code': __import__('app.services.shipping_notice.process_gate_projection', fromlist=['task_blocking_reason']).task_blocking_reason(task),
} }
return {key: value for key, value in snapshot.items() if value is not None} return {key: value for key, value in snapshot.items() if value is not None}
@@ -12,10 +12,10 @@ from __future__ import annotations
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
if TYPE_CHECKING: if TYPE_CHECKING:
from app.models import ShippingNotice from app.models import ShippingNotice, ShippingOrderTask
def _task_has_process_execution(task: ShippingNotice | None) -> bool: def _task_has_process_execution(task: ShippingOrderTask | ShippingNotice | None) -> bool:
""" """
判断任务是否已绑定 ProcessExecution(Gate 为恢复真相源)。 判断任务是否已绑定 ProcessExecution(Gate 为恢复真相源)。
@@ -27,11 +27,17 @@ def _task_has_process_execution(task: ShippingNotice | None) -> bool:
""" """
if task is None or getattr(task, 'id', None) is None: if task is None or getattr(task, 'id', None) is None:
return False return False
from app.models import ShippingProcessExecution from app.models import ShippingNotice, ShippingProcessExecution
if isinstance(task, ShippingNotice):
task_id = int(task.order_task_id) if task.order_task_id is not None else None
else:
task_id = int(task.id) if getattr(task, 'id', None) is not None else None
if task_id is None:
return False
return ( return (
ShippingProcessExecution.query ShippingProcessExecution.query
.filter_by(task_id=int(task.id)) .filter_by(task_id=task_id)
.filter(ShippingProcessExecution.status != 'superseded') .filter(ShippingProcessExecution.status != 'superseded')
.first() .first()
is not None is not None
@@ -20,7 +20,6 @@ from app.services.shipping_notice import customer_identity_gate
# 任务 / 决策 # 任务 / 决策
create_task = task_workflow.create_task create_task = task_workflow.create_task
auto_progress = task_workflow.auto_progress auto_progress = task_workflow.auto_progress
submit_decision = task_workflow.submit_decision
get_task_status = task_workflow.get_task_status get_task_status = task_workflow.get_task_status
retry_task = task_workflow.retry_task retry_task = task_workflow.retry_task
update_notice_fields = task_workflow.update_notice_fields update_notice_fields = task_workflow.update_notice_fields
@@ -8,7 +8,8 @@ services/shipping_notice/user_facing_status.py
from __future__ import annotations from __future__ import annotations
from app.models import ShippingNotice from app import db
from app.models import ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.constants import ( from app.services.shipping_notice.constants import (
CP_EXPORT_READY, CP_EXPORT_READY,
CP_INVENTORY_PENDING, CP_INVENTORY_PENDING,
@@ -86,16 +87,24 @@ def user_facing_task_stage(task: ShippingNotice) -> str:
这类细粒度状态被通用 checkpoint(如“待上传或获取库存”)覆盖; 这类细粒度状态被通用 checkpoint(如“待上传或获取库存”)覆盖;
STP 多源 Excel 阻断覆盖通用 shortage 文案。 STP 多源 Excel 阻断覆盖通用 shortage 文案。
""" """
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {} # Notice 只承载正式单据;流程/UI 状态归属关联 OT。
owner = task
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None):
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
payload = getattr(owner, 'step_payload_json', None)
payload = payload if isinstance(payload, dict) else {}
if payload.get('multi_source_excel_block'): if payload.get('multi_source_excel_block'):
return '多库存源冲突,待人工处理' return '多库存源冲突,待人工处理'
reason = str(task.pending_human_reason or "").strip() from app.services.shipping_notice.process_gate_projection import task_blocking_reason
reason = str(task_blocking_reason(owner) or '').strip()
if reason in _PENDING_REASON_LABELS: if reason in _PENDING_REASON_LABELS:
return _PENDING_REASON_LABELS[reason] return _PENDING_REASON_LABELS[reason]
ui = resolve_task_ui_state(task) ui = resolve_task_ui_state(owner)
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS: if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
return _CHECKPOINT_LABELS[ui.checkpoint] return _CHECKPOINT_LABELS[ui.checkpoint]
return str(getattr(task, "lifecycle_status", None) or "active") == "active" and "处理中" or "已结束" lifecycle = str(getattr(owner, "lifecycle_status", None) or getattr(owner, 'status', None) or "active")
return lifecycle == "active" and "处理中" or "已结束"
def strip_internal_task_fields(data: dict) -> dict: def strip_internal_task_fields(data: dict) -> dict:
@@ -336,11 +336,15 @@ def task_has_entered_inventory_match(task: ShippingNotice) -> bool:
Returns: Returns:
True 表示已进入 matched 或更后阶段。 True 表示已进入 matched 或更后阶段。
""" """
match_status = str(getattr(task, 'match_status', None) or '').strip().lower() from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
match_status = aggregate_match_status_for_task(match_task_id) or ''
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt
artifact = latest_export_artifact(task)
attempt = latest_upload_attempt(task)
return match_status in {'fulfillable', 'partial', 'unfulfillable', 'matched'} or bool( return match_status in {'fulfillable', 'partial', 'unfulfillable', 'matched'} or bool(
str(getattr(task, 'export_file_path', None) or '').strip() str(getattr(artifact, 'file_path', None) or '').strip()
or str(getattr(task, 'freight_ref_no', None) or '').strip() or str(getattr(attempt, 'status', None) or '').strip()
or str(getattr(task, 'upload_status', None) or '').strip()
) )
@@ -0,0 +1,84 @@
"""
用途:验证正式客户识别结果是客户确认与流程 Gate 的唯一真相源。
依赖:内存数据库、客户识别结果服务、ShippingOrderTask/Candidate。
逻辑:覆盖非 bill_to 证据可确认,以及仅有旧 Bill-to Match 时不得放行两条边界。
"""
from __future__ import annotations
from app import db
from app.models import (
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingOrderCandidate,
ShippingOrderIntake,
ShippingOrderTask,
User,
)
from app.services.shipping_notice.customer_resolution_service import (
confirm_customer_resolution,
customer_resolution_facts,
)
def _task_with_resolution(*, status: str = 'unique_candidate') -> tuple[ShippingOrderTask, ShippingCustomerShadowResolution, ShippingCustomer]:
"""构造 OT、Candidate 和规则证据快照;不构造 bill_to 字段或 CustomerMatch。"""
user = User(username='resolution-user', email='resolution@example.com', role='user')
customer = ShippingCustomer(standard_name='规则识别客户', short_code='RID', status='active')
db.session.add_all([user, customer])
db.session.flush()
intake = ShippingOrderIntake(
intake_no='INT-RESOLUTION', asset_id=1, user_id=user.id, parser_version='test',
)
db.session.add(intake)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no='CAND-RESOLUTION', intake_id=intake.id, primary_document_id=1,
candidate_key='resolution-test', candidate_status='accepted',
)
db.session.add(candidate)
db.session.flush()
task = ShippingOrderTask(task_no='OT-RESOLUTION', user_id=user.id, candidate_id=candidate.id)
resolution = ShippingCustomerShadowResolution(
candidate_id=candidate.id,
intake_id=intake.id,
resolution_version='shadow-v2',
status=status,
evidence_json=[{'definition_id': 'customer-code', 'normalized_value': 'C-100'}],
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
resolution_context_json={'rule_set': {'checksum': 'a' * 64}},
identity_rule_set_checksum='a' * 64,
top_customer_id=customer.id,
top_score=100,
)
db.session.add_all([task, resolution])
db.session.commit()
return task, resolution, customer
def test_non_bill_to_evidence_can_confirm_customer(app):
"""关键断言:客户代码证据可确认客户,流程不要求 bill_to 字段或旧匹配行。"""
with app.app_context():
task, resolution, customer = _task_with_resolution()
confirm_customer_resolution(task, customer_id=customer.id, actor_id=None, method='manual')
db.session.commit()
facts = customer_resolution_facts(task)
assert facts['status'] == 'confirmed'
assert facts['customer_id'] == customer.id
assert resolution.confirmed_customer_id == customer.id
# 关键断言:确认不篡改规则证据及其 checksum。
assert resolution.evidence_json == [{'definition_id': 'customer-code', 'normalized_value': 'C-100'}]
assert resolution.identity_rule_set_checksum == 'a' * 64
def test_unconfirmed_resolution_fails_closed_without_old_bill_to_fallback(app):
"""关键断言:未确认的统一识别结果不得从旧字段或旧匹配路径获得客户身份。"""
with app.app_context():
task, _resolution, _customer = _task_with_resolution(status='unique_candidate')
facts = customer_resolution_facts(task)
assert facts['status'] == 'unique_candidate'
assert facts['customer_id'] is None
@@ -199,7 +199,8 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
"""正式 field_completeness 阻断必须覆盖 Case draft 的 idle/order_review_build 推导。""" """正式 field_completeness 阻断必须覆盖 Case draft 的 idle/order_review_build 推导。"""
from app.services.shipping_notice import reconciliation_projector from app.services.shipping_notice import reconciliation_projector
case = _fake_case(status='draft', candidate_id=None) # 正式门禁事实只在 Case 已确认(confirmed)时覆盖;未确认 draft 保持 order_review_build(见结算设计)。
case = _fake_case(status='confirmed', candidate_id=None)
monkeypatch.setattr( monkeypatch.setattr(
reconciliation_projector, reconciliation_projector,
'_project_case_formal_gate_summary', '_project_case_formal_gate_summary',
@@ -239,6 +239,8 @@ def test_serialize_order_extraction_run_includes_selection_plan_summary(monkeypa
schema_version_id=1, schema_version_id=1,
attempt_count=0, attempt_count=0,
reparse_source=None, reparse_source=None,
reparse_of_run_id=None,
superseded_by_run_id=None,
superseding_run=None, superseding_run=None,
reparse_reason=None, reparse_reason=None,
superseded_at=None, superseded_at=None,
@@ -80,6 +80,7 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app):
run_id=10, run_id=10,
run=run, run=run,
owner_user_id=1, owner_user_id=1,
stream_id=100,
current_draft=SimpleNamespace( current_draft=SimpleNamespace(
draft_version=1, draft_version=1,
validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'},
@@ -103,6 +104,7 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app):
return_value={'status': 'queued', 'job_id': 1201, return_value={'status': 'queued', 'job_id': 1201,
'idempotency_key': 'stp-auto:SNER-COORD-1:doc-100:v1'}, 'idempotency_key': 'stp-auto:SNER-COORD-1:doc-100:v1'},
) as ensure_mock: ) as ensure_mock:
RC_Mock.query.join.return_value.filter.return_value.order_by.return_value.with_entities.return_value.all.return_value = [SimpleNamespace(id=1)]
RC_Mock.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [ RC_Mock.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [
SimpleNamespace(id=1), SimpleNamespace(id=1),
] ]
@@ -136,6 +138,7 @@ def test_contract_02_draft_validated_ready_triggers_single_case_coordinator(app)
run_id=20, run_id=20,
run=SimpleNamespace(id=20, run_no='SNER-20'), run=SimpleNamespace(id=20, run_no='SNER-20'),
owner_user_id=1, owner_user_id=1,
stream_id=200,
current_draft=SimpleNamespace( current_draft=SimpleNamespace(
draft_version=3, draft_version=3,
validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'}, validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'},
@@ -172,6 +175,7 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app):
id=3, case_no='SORC-P1-03', status='unreviewed', confirmed_task_id=None, id=3, case_no='SORC-P1-03', status='unreviewed', confirmed_task_id=None,
document_id=300, candidate_id=30, run_id=30, document_id=300, candidate_id=30, run_id=30,
run=SimpleNamespace(id=30, run_no='SNER-30'), owner_user_id=1, run=SimpleNamespace(id=30, run_no='SNER-30'), owner_user_id=1,
stream_id=300,
current_draft=SimpleNamespace( current_draft=SimpleNamespace(
draft_version=2, draft_version=2,
validation_result_json={'can_build': True, 'can_auto_create': False, 'status': 'draft'}, validation_result_json={'can_build': True, 'can_auto_create': False, 'status': 'draft'},
@@ -232,34 +236,26 @@ def test_unique_customer_auto_confirmation_defers_commit_to_resume_transaction(a
case = SimpleNamespace(case_no='SORC-UNIQUE-COMMIT', candidate_id=31) case = SimpleNamespace(case_no='SORC-UNIQUE-COMMIT', candidate_id=31)
candidate = SimpleNamespace(id=31) candidate = SimpleNamespace(id=31)
shadow = SimpleNamespace(status='unique_candidate', top_customer_id=5555) shadow = SimpleNamespace(status='unique_candidate', top_customer_id=5555)
extraction = SimpleNamespace(id=101)
shadow_model = SimpleNamespace( shadow_model = SimpleNamespace(
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: shadow)), query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: shadow)),
) )
match_model = SimpleNamespace(
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=1))),
)
with patch.object(coord.db.session, 'get', return_value=candidate), patch.object( with patch.object(coord.db.session, 'get', return_value=candidate), patch.object(
coord, coord,
'ShippingCustomerShadowResolution', 'ShippingCustomerShadowResolution',
shadow_model, shadow_model,
), patch.object(coord, 'resolve_review_case_customer_resolved', return_value=False), patch.object( ), patch.object(coord, 'resolve_review_case_customer_resolved', return_value=False), patch.object(
coord, coord,
'_resolve_extraction_for_case', 'confirm_customer_resolution',
return_value=extraction, autospec=True,
), patch.object( ) as confirm_mock, patch.object(
coord,
'ShippingOrderCustomerMatch',
match_model,
), patch.object(coord, 'confirm_order_customer_match') as confirm_mock, patch.object(
coord, coord,
'record_fulfillment_audit', 'record_fulfillment_audit',
): ):
status, metadata = coord._customer_step_for_case(case=case, trigger='draft_validated') status, metadata = coord._customer_step_for_case(case=case, trigger='draft_validated')
assert status == 'auto_confirmed' assert status == 'auto_confirmed'
assert metadata == {'customer_id': 5555, 'extraction_id': 101} assert metadata == {'customer_id': 5555, 'extraction_id': None}
assert confirm_mock.call_args.kwargs['commit'] is False assert confirm_mock.call_args.kwargs['method'] == 'auto_rule'
def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app): def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app):
@@ -313,6 +309,7 @@ def test_contract_04b_run_coordinator_skips_manual_draft_validation(app):
run_id=42, run_id=42,
run=run, run=run,
owner_user_id=1, owner_user_id=1,
stream_id=420,
current_draft=SimpleNamespace( current_draft=SimpleNamespace(
draft_version=8, draft_version=8,
header_values_json={}, header_values_json={},
@@ -331,6 +328,7 @@ def test_contract_04b_run_coordinator_skips_manual_draft_validation(app):
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case', 'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
return_value={'status': 'waiting_manual_validation'}, return_value={'status': 'waiting_manual_validation'},
): ):
review_case.query.join.return_value.filter.return_value.order_by.return_value.with_entities.return_value.all.return_value = [SimpleNamespace(id=42)]
review_case.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [ review_case.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [
SimpleNamespace(id=42), SimpleNamespace(id=42),
] ]
@@ -465,6 +463,26 @@ def test_contract_06_duplicate_blocked_case_rejects_general_retry(app):
) is True ) is True
def test_contract_06_legacy_unexpected_stp_failure_allows_general_retry(app):
"""修复前落库的技术异常不能继续阻止普通 STP 重试。"""
from app.services.shipping_notice import reconciliation_service as rs
case = SimpleNamespace(
case_no='SORC-P1-06-TECH', status='ready', confirmed_task_id=None,
document_id=601, run=SimpleNamespace(run_no='SNER-P1-06-TECH'),
)
with patch.object(rs, 'Job') as Job:
Job.query.filter.return_value.filter.return_value.order_by.return_value.first.return_value = SimpleNamespace(
id=61, status='failed',
result_json={
'retryable': False,
'blocking_reason': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
'error_code': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
},
)
rs.assert_case_not_blocked_manual(case_no='SORC-P1-06-TECH', case=case)
def test_contract_07_get_projection_is_pure_read_no_writes(app): def test_contract_07_get_projection_is_pure_read_no_writes(app):
"""合同 7:GET 投影 → 不 confirm 客户、不 validate Draft、不 commit 事务。""" """合同 7:GET 投影 → 不 confirm 客户、不 validate Draft、不 commit 事务。"""
from app.services.shipping_notice.order_review_customer_service import ( from app.services.shipping_notice.order_review_customer_service import (
@@ -482,11 +500,7 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app):
) as sess_mock, patch( ) as sess_mock, patch(
'app.services.shipping_notice.order_review_customer_service.resolve_review_case_customer_resolved', 'app.services.shipping_notice.order_review_customer_service.resolve_review_case_customer_resolved',
return_value=False, return_value=False,
), patch( ):
'app.services.shipping_notice.order_review_customer_service.refresh_order_customer_matches',
) as refresh_mock, patch(
'app.services.shipping_notice.order_review_customer_service.confirm_order_customer_match',
) as confirm_mock:
# Shadow = unique_candidate 但是 resolved=false。 # Shadow = unique_candidate 但是 resolved=false。
with patch( with patch(
'app.services.shipping_notice.order_review_customer_service.ShippingCustomerShadowResolution', 'app.services.shipping_notice.order_review_customer_service.ShippingCustomerShadowResolution',
@@ -501,19 +515,14 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app):
with patch( with patch(
'app.services.shipping_notice.order_review_customer_service.ShippingOrderCandidate', 'app.services.shipping_notice.order_review_customer_service.ShippingOrderCandidate',
) as Cand, patch( ) as Cand, patch(
'app.services.shipping_notice.order_review_customer_service.ShippingOrderCustomerMatch',
) as CM, patch(
'app.services.shipping_notice.order_review_customer_service.ShippingOrderExtraction', 'app.services.shipping_notice.order_review_customer_service.ShippingOrderExtraction',
) as EX: ) as EX:
sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700) sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700)
CM.query.filter_by.return_value.first.return_value = None
EX.query.filter_by.return_value.order_by.return_value.first.return_value = SimpleNamespace(id=700) EX.query.filter_by.return_value.order_by.return_value.first.return_value = SimpleNamespace(id=700)
# 执行投影(纯读) # 执行投影(纯读)
out = project_review_case_customer_resolution(case) out = project_review_case_customer_resolution(case)
# 7A:GET 路径不允许 confirm / validate / commit # 7A:GET 路径不允许 confirm / validate / commit
confirm_mock.assert_not_called()
refresh_mock.assert_not_called()
sess_mock.commit.assert_not_called() sess_mock.commit.assert_not_called()
# 7B:投影仍然能够返回客户状态(unique_candidate 而非 confirmed,因为没被写入确认) # 7B:投影仍然能够返回客户状态(unique_candidate 而非 confirmed,因为没被写入确认)
assert out.get('resolved') is False assert out.get('resolved') is False
@@ -15,7 +15,7 @@ from app import db
from app.models import ( from app.models import (
Job, Job,
ShippingInventoryCandidateSet, ShippingInventoryCandidateSet,
ShippingNotice, ShippingOrderTask,
ShippingProcessExecution, ShippingProcessExecution,
ShippingProcessGate, ShippingProcessGate,
ShippingProcessGateAttempt, ShippingProcessGateAttempt,
@@ -28,9 +28,9 @@ from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_t
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
def _task_with_candidate(*, complete_order: bool = True) -> ShippingNotice: def _task_with_candidate(*, complete_order: bool = True) -> ShippingOrderTask:
"""创建正式 Task;可选择是否补齐订单解析与冻结快照事实。""" """创建正式 Task;可选择是否补齐订单解析与冻结快照事实。"""
task = ShippingNotice(task_no='APX-P0-3-001') task = ShippingOrderTask(task_no='OT-APX-P0-3-001', user_id=1)
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
candidate = ShippingInventoryCandidateSet( candidate = ShippingInventoryCandidateSet(
@@ -101,7 +101,7 @@ def test_formal_execution_queues_one_gate_attempt_job(app):
formal = ensure_execution_for_workflow_version(review_case_id=902, task_id=int(task.id)) formal = ensure_execution_for_workflow_version(review_case_id=902, task_id=int(task.id))
mark_gates_passed_through( mark_gates_passed_through(
execution=formal, execution=formal,
through_gate_code='task_creation', through_gate_code='inventory_source_routing',
reason='test_review_confirmed', reason='test_review_confirmed',
) )
task.active_process_execution_id = formal.id task.active_process_execution_id = formal.id
@@ -148,6 +148,65 @@ def test_submit_does_not_enqueue_navigation_action_for_worker_gate(app):
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 0 assert Job.query.filter_by(job_type='shipping_process_gate').count() == 0
def test_submit_does_not_redispatch_after_failed_worker_attempt(app):
"""[断言] Worker 真实执行失败(failed + job_id 非空)的门禁:auto_progress 不得自动重试,
必须等待用户在当前 Gate 显式恢复;首次投递通道(无失败 Attempt)不受影响(由
test_formal_execution_queues_one_gate_attempt_job 锁定)。"""
import uuid as _uuid
task = _task_with_candidate()
execution = ensure_execution_for_workflow_version(review_case_id=904, task_id=int(task.id))
mark_gates_passed_through(
execution=execution,
through_gate_code='inventory_source_routing',
reason='test_review_confirmed',
)
gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id), gate_code='inventory_preparation',
).one()
# Worker 已真实执行并失败:failed Attempt 持有非空 job_id
failed_job = Job(
domain='shipping_notice', job_type='shipping_process_gate',
status='failed', business_ref='apx-p03-failed-gate-job',
)
db.session.add(failed_job)
db.session.flush()
db.session.add(ShippingProcessGateAttempt(
gate_id=int(gate.id),
attempt_no=1,
status='failed',
trigger_type='auto',
actor_type='system',
actor_id='external-wait-poll',
idempotency_key=f'test-failed-worker-attempt:{_uuid.uuid4().hex}',
job_id=int(failed_job.id),
))
gate.status = 'blocked_retryable'
gate.next_action_code = 'retry_inventory_preparation'
execution.status = 'blocked'
execution.current_gate_code = 'inventory_preparation'
execution.primary_next_action_code = 'retry_inventory_preparation'
execution.responsible_party = 'worker'
task.active_process_execution_id = int(execution.id)
db.session.commit()
# 同步事实是本用例之外的职责;固定复现“同步后仍为可重试阻断”的当前 Gate。
with patch(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
):
result = submit_auto_progress(task=task, trigger='inventory_rpa_callback_succeeded')
assert result['status'] == 'waiting_human'
assert result['gate_code'] == 'inventory_preparation'
# 没有新的 ProcessGate Job 被创建(仅存量失败 Job)
assert Job.query.filter(
Job.job_type == 'shipping_process_gate',
Job.id != int(failed_job.id),
).count() == 0
# Attempt 数量不变:只有种子失败行,未被自动重派
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
def test_active_stp_job_without_retry_metadata_is_reused(app): def test_active_stp_job_without_retry_metadata_is_reused(app):
"""活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。""" """活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。"""
from types import SimpleNamespace from types import SimpleNamespace
@@ -183,3 +242,90 @@ def test_active_stp_job_without_retry_metadata_is_reused(app):
assert result['retry_of_job_id'] is None assert result['retry_of_job_id'] is None
def test_derived_fulfillment_status_uses_line_match_facts_for_order_task():
"""OT 履约状态必须从行级 Match 事实推导,不再读取已删除的 Notice JSON 投影。"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_bridge import _derived_fulfillment_status
task = SimpleNamespace(id=1)
with patch(
'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task',
return_value=True,
), patch(
'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage',
return_value=False,
), patch(
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
return_value=False,
), patch(
'app.services.shipping_notice.upload_attempt_service.latest_upload_attempt',
return_value=None,
), patch(
'app.services.shipping_notice.process_gate_projection.task_blocking_reason',
return_value=None,
), patch(
'app.services.shipping_notice.process_gate_bridge.ShippingOrderTask',
SimpleNamespace,
):
assert _derived_fulfillment_status(task) == 'matched'
def test_auto_retry_blocked_only_for_non_user_trigger():
"""Bug 修复:[禁止自动重试] 仅拦非用户显式触发 / 无定向 gate 的自动推进。
核心逻辑:has_failed_worker_attempt 守卫本意是防止自动/后台 trigger 无限重试,
用户显式重试(user_retry/user_manual)或带 resume_gate_code 的显式定向推进
(如匹配工具 tool_api_match_inventory_line + resume_gate_code='inventory_matching')
应绕过,否则点"重新匹配库存"报"无待处理 Gate"。
"""
from app.services.shipping_notice.auto_progress_controller import _auto_retry_blocked
assert _auto_retry_blocked('auto', True) is True
assert _auto_retry_blocked('system_requeue', True) is True
assert _auto_retry_blocked('worker_takeover', True) is True
assert _auto_retry_blocked('user_retry', True) is False
assert _auto_retry_blocked('user_manual', True) is False
assert _auto_retry_blocked('user_retry', False) is False
assert _auto_retry_blocked('auto', False) is False
# 匹配工具 trigger 非 user_retry,但带 resume_gate_code(显式定向重匹配)→ 放行
assert _auto_retry_blocked('tool_api_match_inventory_line', True) is True
assert _auto_retry_blocked('tool_api_match_inventory_line', True, resume_gate_code='inventory_matching') is False
assert _auto_retry_blocked('auto', True, resume_gate_code='inventory_matching') is False
def test_retry_inventory_matching_fulfillable_passes():
"""Bug 修复:已可履约订单的"重新匹配库存"应通过,不把 match_inventory 内部的
run_task_auto_progress "无待处理 Gate"(status='completed')误判为失败。
核心逻辑:_handle_retry_inventory_matching 只在 needs_human+shortage 时 return passed;
对 match_status='fulfillable' + response.status='completed' 会落 _tool_outcome 判为
blocked_retryable,把"无待处理 Gate"记作 error_summary。修复:fulfillable 直接 passed。
"""
from app.services.shipping_notice import process_gate_executor as ex
from unittest.mock import MagicMock
class _Task:
id = 1
task_no = 'OT-X'
order_snapshot_id = 1
class _Execution:
task_id = 1
class _Gate:
gate_code = 'inventory_matching'
class _OT:
query = MagicMock(get=MagicMock(return_value=_Task()))
with patch('app.services.shipping_notice.fulfillment_workflow.match_inventory', return_value={
'status': 'completed', 'message': '自动推进已无待处理 Gate。', 'data': {}, 'task_id': 'x', 'checkpoint': None,
}), patch('app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', return_value=None), \
patch('app.services.shipping_notice.process_gate_executor.ShippingOrderTask', _OT), \
patch('app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', return_value=True), \
patch('app.services.shipping_notice.fulfillment_workflow.match_completed', return_value=True), \
patch('app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', return_value={}):
result = ex._handle_retry_inventory_matching(execution=_Execution(), gate=_Gate(), payload={'actor_user_id': 1})
assert result['outcome'] == 'passed'
@@ -128,6 +128,9 @@ def test_derived_field_evidence_gap_does_not_block_candidate_qualification(monke
conflicts_json=[{ conflicts_json=[{
'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing', 'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing',
'owning_gate_code': 'field_completeness', 'owning_gate_code': 'field_completeness',
# 派生/已解决字段的历史 evidence_missing 由写路径 _discard_resolved_worker_field_conflicts
# 在投影到 Candidate 前丢弃;资格 Gate 只按冻结字段配置判断证据缺失是否可选。
'field_config': {'required': False, 'auto_create_key_field': False},
}], }],
structured_result_json={ structured_result_json={
'customer': {'resolution_status': 'user_confirmed'}, 'customer': {'resolution_status': 'user_confirmed'},
@@ -23,7 +23,6 @@ def test_legacy_fulfillment_chat_actions_are_not_registered():
"shipping.retry_upload", "shipping.retry_upload",
"shipping.match_inventory", "shipping.match_inventory",
"shipping.confirm_inventory_source", "shipping.confirm_inventory_source",
"shipping.submit_decision",
"shipping.mark_manual_uploaded", "shipping.mark_manual_uploaded",
}.isdisjoint(action_types) }.isdisjoint(action_types)
@@ -7,7 +7,7 @@ from sqlalchemy.exc import IntegrityError
from app import db from app import db
from app.core.errors import ForbiddenError from app.core.errors import ForbiddenError
from app.models import Agent, ChatSession, ShippingNotice, User from app.models import Agent, ChatSession, ShippingOrderTask, User
from app.services.shipping_notice.chat_tool_capability import issue_chat_capability, require_chat_capability from app.services.shipping_notice.chat_tool_capability import issue_chat_capability, require_chat_capability
@@ -18,10 +18,10 @@ def test_chat_capability_rejects_cross_task_and_expired_scope(app):
agent = Agent(name='cap-agent', agent_code='shipping_notice', is_active=True) agent = Agent(name='cap-agent', agent_code='shipping_notice', is_active=True)
db.session.add_all([user, agent]); db.session.flush() db.session.add_all([user, agent]); db.session.flush()
session = ChatSession(session_id='cap-session', user_id=user.id, agent_id=agent.id) session = ChatSession(session_id='cap-session', user_id=user.id, agent_id=agent.id)
own = ShippingNotice(task_no='SN-CAP-OWN', user_id=user.id, source_type='test') own = ShippingOrderTask(task_no='SN-CAP-OWN', user_id=user.id, source_type=None)
other = ShippingNotice(task_no='SN-CAP-OTHER', source_type='test') other = ShippingOrderTask(task_no='SN-CAP-OTHER', user_id=user.id, source_type=None)
db.session.add_all([session, own, other]); db.session.commit() db.session.add_all([session, own, other]); db.session.commit()
token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no, batch_no=None) token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no)
assert require_chat_capability(token=token, scope='get_shipping_status', task_no=own.task_no)['uid'] == user.id assert require_chat_capability(token=token, scope='get_shipping_status', task_no=own.task_no)['uid'] == user.id
with pytest.raises(ForbiddenError): with pytest.raises(ForbiddenError):
require_chat_capability(token=token, scope='get_shipping_status', task_no=other.task_no) require_chat_capability(token=token, scope='get_shipping_status', task_no=other.task_no)
@@ -186,7 +186,7 @@ def test_adaptive_record_columns_supports_compact_and_expanded_visual_rows():
), table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 130}, line_layouts=_adaptive_layouts(), ), table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 130}, line_layouts=_adaptive_layouts(),
row_reconstruction_mode='adaptive_record_columns', row_reconstruction_mode='adaptive_record_columns',
) )
# Both layouts must yield a complete logical record despite their different visual-band counts. # 两种视觉排版均可从明确的 ``@ + 纯数字`` 预约号段还原完整逻辑明细。
assert compact[0].fields == { assert compact[0].fields == {
'customer_po_line_no': '10', 'part_number': 'PART-A', 'qty': '9.000', 'uom': 'PCS', 'customer_po_line_no': '10', 'part_number': 'PART-A', 'qty': '9.000', 'uom': 'PCS',
'requested_receipt_date': '2026/07/10', 'unit_price': '898.72', 'line_amount_with_tax': '8,088.48', 'requested_receipt_date': '2026/07/10', 'unit_price': '898.72', 'line_amount_with_tax': '8,088.48',
@@ -870,6 +870,22 @@ def test_adaptive_record_columns_accepts_numeric_reservation_id_without_at_sign(
assert rows[0].fields['reservation_id'] == '3000097059' assert rows[0].fields['reservation_id'] == '3000097059'
def test_coordinate_profile_rows_accept_reservation_with_text_suffix_truncated():
"""预约号框内含文本后缀时可截断为纯数字写入(生产行为)。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('10', 5), ('PART-A', 60)], [('1.000', 115), ('PCS', 145), ('2026/05/26', 170)],
[('898.72', 80), ('898.72', 165)], [('3000097059(PENROSE)', 115)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100},
line_layouts=_adaptive_layouts(),
row_reconstruction_mode='adaptive_record_columns',
)
# 允许将带文本后缀的预约号截断为纯数字(生产已实现)。
assert rows[0].fields['reservation_id'] == '3000097059'
def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_line(): def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_line():
"""一个物理行包含多条视觉子行时,字段必须按父行内相对 Y 重复命中后续明细。""" """一个物理行包含多条视觉子行时,字段必须按父行内相对 Y 重复命中后续明细。"""
rows = reconstruct_coordinate_profile_rows( rows = reconstruct_coordinate_profile_rows(
@@ -974,6 +990,70 @@ def test_dynamic_x_columns_translates_all_field_frames_from_the_record_anchor():
}] }]
def test_dynamic_x_columns_clamps_a_shifted_wide_field_frame_to_the_page_top():
"""锚点上移把宽字段框推过页顶时,截断框仍须读取页面内的有效字符。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs([('1', 10), ('PART-A', 60)]),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
line_layouts=[{
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .70, 'x1': .25, 'y1': .80}},
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
],
}],
line_start_field_code='customer_po_line_no',
row_reconstruction_mode='dynamic_x_columns',
)
assert [row.fields for row in rows] == [{'customer_po_line_no': '1', 'part_number': 'PART-A'}]
def test_dynamic_x_columns_honors_deleted_marker_exclusion_authorization():
"""dynamic 模式绕过普通排除过滤时,仍须使用配置排除区授权删除标记。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('PART-A', 65)],
[('** Item deleted **', 65)],
[('00020', 10), ('PART-B', 65)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
line_layouts=[{
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .3, 'y1': .3}},
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .15, 'x1': 1, 'y1': .3}},
],
}],
exclusion_regions=[{'x0': .3, 'y0': .3, 'x1': .8, 'y1': .5}],
row_reconstruction_mode='dynamic_x_columns',
)
assert [row.fields['customer_po_line_no'] for row in rows] == ['00020']
def test_dynamic_x_columns_ignores_unconfigured_deleted_marker():
"""dynamic 模式没有删除标记排除授权时,不得擅自删除上一条明细。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('00010', 10), ('PART-A', 65)],
[('** Item deleted **', 65)],
[('00020', 10), ('PART-B', 65)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
line_layouts=[{
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .3, 'y1': .3}},
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .15, 'x1': 1, 'y1': .3}},
],
}],
row_reconstruction_mode='dynamic_x_columns',
)
assert [row.fields['customer_po_line_no'] for row in rows] == ['00010', '00020']
def test_fixed_relative_y_rows_translate_every_field_frame_from_each_record_anchor(): def test_fixed_relative_y_rows_translate_every_field_frame_from_each_record_anchor():
"""固定子行同样必须按记录锚点平移,不能把客户料号误读到供应商料号框。""" """固定子行同样必须按记录锚点平移,不能把客户料号误读到供应商料号框。"""
rows = reconstruct_coordinate_profile_rows( rows = reconstruct_coordinate_profile_rows(
@@ -1145,6 +1225,114 @@ def test_coordinate_profile_rows_realign_a_record_with_an_extra_unbound_visual_b
assert [row.fields['part_number'] for row in rows] == ['PART-A', 'PART-B'] assert [row.fields['part_number'] for row in rows] == ['PART-A', 'PART-B']
def test_coordinate_profile_rows_keep_main_row_fields_and_skip_description_wrap_for_part_number():
"""主视觉行同时含日期金额时,描述折行不得占用内部料号视觉位置。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('10', 10), ('40', 80), ('RK-00410-001B', 130), ('08/28/2026', 260),
('941.76', 320), ('37670.40', 365)],
[('BUSBAR', 130)],
[('D4-A08AR12000002', 130)],
[('Revision:A0', 130)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100},
table_region={'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8},
line_layouts=[{'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8}, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}},
{'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}},
{'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}},
{'field_code': 'requested_receipt_date', 'region': {'x0': .65, 'y0': .2, 'x1': .78, 'y1': .3}},
{'field_code': 'unit_price', 'region': {'x0': .79, 'y0': .2, 'x1': .88, 'y1': .3}},
{'field_code': 'line_amount_with_tax', 'region': {'x0': .88, 'y0': .2, 'x1': 1, 'y1': .3}},
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}},
]}],
schema_field_metadata=[
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'},
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
{'field_code': 'requested_receipt_date', 'scope': 'line', 'value_type': 'date'},
{'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
{'field_code': 'line_amount_with_tax', 'scope': 'line', 'value_type': 'decimal'},
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
],
)
assert rows[0].fields == {
'customer_po_line_no': '10', 'qty': '40', 'customer_part_number': 'RK-00410-001B',
'requested_receipt_date': '08/28/2026', 'unit_price': '941.76',
'line_amount_with_tax': '37670.40', 'part_number': 'D4-A08AR12000002',
}
@pytest.mark.parametrize('row_reconstruction_mode', [
'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns',
])
def test_two_subrow_layout_rescans_description_wrap_before_part_number(row_reconstruction_mode):
"""真实 ZT 两子行布局中,描述折行不能占用内部料号的固定续行。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('10', 10), ('40', 80), ('RK-00410-001B', 130)],
[('BUSBAR', 130)],
[('D4-A08AR12000002', 130)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100},
line_layouts=[
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}},
{'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}},
{'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}},
]},
{'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}},
]},
],
row_reconstruction_mode=row_reconstruction_mode,
schema_field_metadata=[
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'},
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
],
)
assert rows[0].fields['part_number'] == 'D4-A08AR12000002'
@pytest.mark.parametrize('row_reconstruction_mode', [
'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns',
])
def test_two_subrow_layout_rescans_numeric_description_wrap_before_part_number(row_reconstruction_mode):
"""真实 ZT 两子行布局中,含数字和标点的描述折行也不能占用内部料号续行。"""
rows = reconstruct_coordinate_profile_rows(
characters=_glyphs(
[('10', 10), ('40', 80), ('RK-00410-001B', 130)],
[('48U AR1.2', 130)],
[('D4-A08AR12000002', 130)],
),
table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100},
line_layouts=[
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}},
{'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}},
{'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}},
]},
{'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}},
]},
],
row_reconstruction_mode=row_reconstruction_mode,
schema_field_metadata=[
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'},
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
],
)
assert rows[0].fields['part_number'] == 'D4-A08AR12000002'
def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review(): def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review():
"""额外视觉行中出现两个同等合法候选时必须留空并记录问题,禁止静默猜测。""" """额外视觉行中出现两个同等合法候选时必须留空并记录问题,禁止静默猜测。"""
rows = reconstruct_coordinate_profile_rows( rows = reconstruct_coordinate_profile_rows(
@@ -1,9 +1,9 @@
""" """
backend/tests/test_shipping_customer_auto_resolution.py backend/tests/test_shipping_customer_auto_resolution.py
用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。 用途:验证受控 OT 自动客户确认、降级开关、强规则歧义和规则快照防篡改。
依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice、customer_auto_resolution。 依赖:客户主数据/证据、Candidate 影子结果、ShippingOrderTask、customer_auto_resolution。
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。 逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动确认,且不创建 Notice。
""" """
from copy import deepcopy from copy import deepcopy
@@ -11,7 +11,6 @@ from copy import deepcopy
import pytest import pytest
from app import db from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import ( from app.models import (
FileAsset, FileAsset,
ShippingCustomer, ShippingCustomer,
@@ -28,19 +27,17 @@ from app.models import (
ShippingOrderFieldValue, ShippingOrderFieldValue,
ShippingOrderSchema, ShippingOrderSchema,
ShippingOrderSchemaVersion, ShippingOrderSchemaVersion,
ShippingOrderTask,
ShippingNotice, ShippingNotice,
ShippingTaskEvent, ShippingTaskEvent,
User, User,
) )
from app.services.shipping_notice.customer_auto_resolution import ( from app.services.shipping_notice.customer_auto_resolution import (
AUTO_RESOLUTION_VERSION, AUTO_RESOLUTION_VERSION,
correct_numbered_task_customer,
get_auto_resolution_metrics, get_auto_resolution_metrics,
resolve_auto_customer_from_shadow, resolve_auto_customer_from_shadow,
try_auto_confirm_task_customer, try_auto_confirm_task_customer,
) )
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
from app.services.shipping_notice.query_service import get_task_by_ref
def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRuleSet]: def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRuleSet]:
@@ -123,10 +120,9 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
) )
db.session.add(candidate) db.session.add(candidate)
db.session.flush() db.session.flush()
task = ShippingNotice( task = ShippingOrderTask(
task_no=f"SN-AUTO-{user.id}", source_candidate_id=candidate.id, task_no=f"OT-AUTO-{user.id}", user_id=user.id,
user_id=user.id, source_type="email_attachment", candidate_id=candidate.id, source_type="eml",
customer_resolution_status="pending",
) )
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
@@ -201,8 +197,13 @@ def _allow_auto_confirmation(app) -> None:
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98 app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98
def test_unique_approved_strong_rule_auto_confirms_and_numbers(app): def _assert_ot_did_not_create_notice(task: ShippingOrderTask) -> None:
"""开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。""" """断言 OT 自动确认只写客户识别结果,不提前创建或编号正式 Notice。"""
assert ShippingNotice.query.filter_by(order_task_id=task.id).count() == 0
def test_unique_approved_strong_rule_auto_confirms_at_ot_without_creating_notice(app):
"""开关启用且唯一强规则命中时,OT 自动确认但不创建或编号 Notice。"""
with app.app_context(): with app.app_context():
_allow_auto_confirmation(app) _allow_auto_confirmation(app)
customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com") customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
@@ -212,22 +213,15 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
assert result["status"] == "auto_confirmed" assert result["status"] == "auto_confirmed"
assert result["rule_version"] == AUTO_RESOLUTION_VERSION assert result["rule_version"] == AUTO_RESOLUTION_VERSION
assert task.customer_resolution_status == "confirmed" shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
assert task.customer_resolution_method == "auto_rule" assert shadow.status == "confirmed"
assert task.customer_id == customer.id assert shadow.confirmation_method == "auto_rule"
assert task.business_no.startswith("WYC") assert shadow.confirmed_customer_id == customer.id
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1 assert shadow.evidence_json[0]['definition_id']
event = ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").one()
assert event.detail_json['rule_set']['checksum']
assert event.detail_json['evidence'][0]['definition_id']
assert event.detail_json['evidence'][0]['evidence_id']
source = event.detail_json['evidence'][0]['source']
assert source['field_value_id'] and source['decision_id'] and source['extraction_id']
assert source['order_schema_version_id'] == event.detail_json['order_schema_version_id']
metrics = get_auto_resolution_metrics() metrics = get_auto_resolution_metrics()
assert result['business_no'] is None
_assert_ot_did_not_create_notice(task)
assert metrics["auto_confirmed_count"] == 1 assert metrics["auto_confirmed_count"] == 1
assert metrics["recent_events"][0]["event_type"] == "customer_auto_confirmed"
assert metrics["recent_events"][0]["task_no"] == task.task_no
def test_switch_off_and_unapproved_rule_fall_back_to_manual(app): def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
@@ -238,13 +232,13 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False
disabled = try_auto_confirm_task_customer(task) disabled = try_auto_confirm_task_customer(task)
assert disabled["status"] == "disabled" assert disabled["status"] == "disabled"
assert task.business_no is None _assert_ot_did_not_create_notice(task)
_allow_auto_confirmation(app) _allow_auto_confirmation(app)
unmatched = try_auto_confirm_task_customer(task) unmatched = try_auto_confirm_task_customer(task)
assert unmatched["status"] == "unmatched" assert unmatched["status"] == "unmatched"
assert task.customer_resolution_status == "pending" assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
assert task.business_no is None _assert_ot_did_not_create_notice(task)
def test_multiple_customers_matching_strong_evidence_is_ambiguous(app): def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
@@ -258,8 +252,8 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
result = try_auto_confirm_task_customer(task) result = try_auto_confirm_task_customer(task)
assert result["status"] == "ambiguous" assert result["status"] == "ambiguous"
assert len(result["candidate_customer_ids"]) == 2 assert len(result["candidate_customer_ids"]) == 2
assert task.customer_resolution_status == "pending" assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
assert task.business_no is None _assert_ot_did_not_create_notice(task)
def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app): def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
@@ -275,10 +269,8 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
db.session.rollback() db.session.rollback()
db.session.expire_all() db.session.expire_all()
persisted_task = db.session.get(ShippingNotice, task_id) persisted_task = db.session.get(ShippingOrderTask, task_id)
assert persisted_task.customer_resolution_status == "pending" assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=persisted_task.candidate_id).one().status == "unique_candidate"
assert persisted_task.customer_id is None
assert persisted_task.business_no is None
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0 assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0
@@ -295,8 +287,8 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic
assert result["status"] == "insufficient_labeled_samples" assert result["status"] == "insufficient_labeled_samples"
assert result["quality_gate"]["labeled_sample_count"] == 0 assert result["quality_gate"]["labeled_sample_count"] == 0
assert task.customer_resolution_status == "pending" assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
assert task.business_no is None _assert_ot_did_not_create_notice(task)
def test_business_evidence_never_auto_confirms(app): def test_business_evidence_never_auto_confirms(app):
@@ -315,7 +307,7 @@ def test_business_evidence_never_auto_confirms(app):
status='approved', auto_match_allowed=True, status='approved', auto_match_allowed=True,
)) ))
task = _seed_candidate_task() task = _seed_candidate_task()
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
original_source = shadow.evidence_json[0]['source'] original_source = shadow.evidence_json[0]['source']
field_value = db.session.get(ShippingOrderFieldValue, original_source['field_value_id']) field_value = db.session.get(ShippingOrderFieldValue, original_source['field_value_id'])
decision = db.session.get(ShippingOrderFieldDecision, original_source['decision_id']) decision = db.session.get(ShippingOrderFieldDecision, original_source['decision_id'])
@@ -336,7 +328,7 @@ def test_business_evidence_never_auto_confirms(app):
result = try_auto_confirm_task_customer(task) result = try_auto_confirm_task_customer(task)
assert result['status'] == 'rule_snapshot_missing' assert result['status'] == 'rule_snapshot_missing'
assert task.customer_resolution_status == 'pending' assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate'
def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app): def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app):
@@ -347,7 +339,7 @@ def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app):
task = _seed_candidate_task(sender='buyer@gmail.com') task = _seed_candidate_task(sender='buyer@gmail.com')
assert try_auto_confirm_task_customer(task)['status'] == 'unmatched' assert try_auto_confirm_task_customer(task)['status'] == 'unmatched'
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
shadow.resolution_context_json = {} shadow.resolution_context_json = {}
db.session.commit() db.session.commit()
missing = resolve_auto_customer_from_shadow(task) missing = resolve_auto_customer_from_shadow(task)
@@ -361,14 +353,14 @@ def test_tampered_shadow_value_or_schema_anchor_never_auto_confirms(app):
_allow_auto_confirmation(app) _allow_auto_confirmation(app)
_customer_with_identifier(code='WYC', value='buyer@wyc.example.com') _customer_with_identifier(code='WYC', value='buyer@wyc.example.com')
task = _seed_candidate_task() task = _seed_candidate_task()
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
evidence = deepcopy(shadow.evidence_json) evidence = deepcopy(shadow.evidence_json)
evidence[0]['normalized_value'] = 'attacker@example.com' evidence[0]['normalized_value'] = 'attacker@example.com'
shadow.evidence_json = evidence shadow.evidence_json = evidence
db.session.commit() db.session.commit()
assert try_auto_confirm_task_customer(task)['status'] == 'unmatched' assert try_auto_confirm_task_customer(task)['status'] == 'unmatched'
assert task.customer_resolution_status == 'pending' assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate'
shadow.evidence_json = [] shadow.evidence_json = []
context = deepcopy(shadow.resolution_context_json) context = deepcopy(shadow.resolution_context_json)
@@ -390,7 +382,7 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app
db.session.add(truth) db.session.add(truth)
db.session.flush() db.session.flush()
task = _seed_candidate_task() task = _seed_candidate_task()
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one() shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
shadow.manual_customer_id = truth.id shadow.manual_customer_id = truth.id
db.session.commit() db.session.commit()
@@ -400,79 +392,81 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app
assert result["status"] == "insufficient_accuracy" assert result["status"] == "insufficient_accuracy"
assert result["quality_gate"]["labeled_sample_count"] == 1 assert result["quality_gate"]["labeled_sample_count"] == 1
assert result["quality_gate"]["accuracy"] == 0 assert result["quality_gate"]["accuracy"] == 0
assert task.customer_resolution_status == "pending" assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
assert task.business_no is None _assert_ot_did_not_create_notice(task)
def test_numbered_customer_correction_voids_old_notice_and_creates_replacement(app): def _rebind_shadow_to_new_schema_version(shadow, *, new_version) -> None:
"""客户误确认纠错必须作废原 Notice,生成新客户编号并保持原号审计可查。""" """把影子记录、证据与 Extraction 重锚到新 Schema 版本,模拟 Schema 重发布后重新解析。"""
shadow.order_schema_version_id = new_version.id
# JSON 列需整体重赋值才能被 SQLAlchemy 追踪变更,不能只在嵌套 dict 上就地修改。
evidence = deepcopy(shadow.evidence_json)
evidence[0]['source']['order_schema_version_id'] = new_version.id
shadow.evidence_json = evidence
extraction = db.session.get(
ShippingOrderExtraction, evidence[0]['source']['extraction_id'],
)
extraction.schema_version_id = new_version.id
def test_schema_republish_with_same_semantics_still_auto_confirms(app):
"""Schema 重发布造成版本 id 错位、但字段语义(code/type/normalizer)未变时,自动确认仍放行。"""
with app.app_context(): with app.app_context():
wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active") _allow_auto_confirmation(app)
correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active") _customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
db.session.add_all([wrong, correct]) task = _seed_candidate_task()
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
old_version.status = 'retired'
new_version = ShippingOrderSchemaVersion(
schema_id=old_version.schema_id, version=old_version.version + 1, status='published',
definition_json={'fields': [{
'field_id': old_version.definition_json['fields'][0]['field_id'],
'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer',
'scope': 'header', 'value_type': 'string', 'enabled': True,
'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim',
}]},
checksum='f' * 64,
)
db.session.add(new_version)
db.session.flush() db.session.flush()
first = ShippingNotice( _rebind_shadow_to_new_schema_version(shadow, new_version=new_version)
task_no="SN-CORRECTION-V1", document_version=1,
source_type="manual", upload_status="pending", customer_resolution_status="pending", inventory_source_code="DSV",
inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}],
match_status="fulfillable", line_results_json=[{"sku": "A"}],
export_file_path="/tmp/old.xlsx", export_file_name="old.xlsx",
)
db.session.add(first)
db.session.commit() db.session.commit()
confirm_task_customer(first, customer_id=wrong.id, actor_id=None)
old_business_no = first.business_no
result = correct_numbered_task_customer( result = resolve_auto_customer_from_shadow(task)
first,
customer_id=correct.id,
reason="自动识别客户错误",
actor_id=None,
)
replacement = db.session.get(ShippingNotice, result["new_notice_id"]) assert result['status'] == 'unique_strong_match'
assert first.business_no == old_business_no assert result['customer_id'] is not None
assert first.lifecycle_status == "voided"
assert replacement.supersedes_task_id == first.id
assert replacement.business_no.startswith("NEW")
assert replacement.business_no != old_business_no
assert replacement.customer_resolution_method == "admin_correction"
assert replacement.inventory_source_status is None
assert replacement.inventory_lines_json is None
assert replacement.export_file_path is None
assert replacement.source_type == "manual"
assert get_task_by_ref(old_business_no).id == first.id
assert get_task_by_ref(replacement.business_no).id == replacement.id
assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2
metrics = get_auto_resolution_metrics()
assert metrics["corrected_task_count"] == 2
assert metrics["recent_events"][0]["detail"]["old_business_no"] == old_business_no
def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(app): def test_schema_republish_changes_semantics_never_auto_confirms(app):
"""纠错必须有原因,且已对外上传业务单需先走外部作废流程。""" """Schema 重发布且字段语义变化(normalizer 变更)时,仍必须 fail-closed 到人工复核。"""
with app.app_context(): with app.app_context():
wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active") _allow_auto_confirmation(app)
correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active") _customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
db.session.add_all([wrong, correct]) task = _seed_candidate_task()
db.session.flush() shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
task = ShippingNotice(
task_no="SN-CORRECTION-BLOCK", old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
source_type="manual", customer_resolution_status="pending", old_version.status = 'retired'
new_version = ShippingOrderSchemaVersion(
schema_id=old_version.schema_id, version=old_version.version + 1, status='published',
definition_json={'fields': [{
'field_id': old_version.definition_json['fields'][0]['field_id'],
'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer',
'scope': 'header', 'value_type': 'string', 'enabled': True,
'available_for_customer_identity': True,
'normalizer_key': 'uppercase_trim', # 语义变化:normalizer 已变更,不得放行。
}]},
checksum='e' * 64,
) )
db.session.add(task) db.session.add(new_version)
db.session.flush()
_rebind_shadow_to_new_schema_version(shadow, new_version=new_version)
db.session.commit() db.session.commit()
confirm_task_customer(task, customer_id=wrong.id, actor_id=None)
with pytest.raises(ValidationError) as exc_info: result = resolve_auto_customer_from_shadow(task)
correct_numbered_task_customer(task, customer_id=correct.id, reason="", actor_id=None)
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED"
db.session.rollback()
task.upload_status = "uploaded" assert result['status'] == 'rule_snapshot_missing'
db.session.commit() assert result['customer_id'] is None
with pytest.raises(ConflictError) as exc_info:
correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None)
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED"
db.session.rollback()
assert db.session.query(ShippingNotice).count() == 1
@@ -1,146 +1,147 @@
""" """
backend/tests/test_shipping_customer_identity_gate.py backend/tests/test_shipping_customer_identity_gate.py
用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。 用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate(ShippingOrderTask 聚合根)。
依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。 依赖:内存数据库、customer_identity_gate、customer_resolution_service、ShippingCustomerShadowResolution。
逻辑:构造 pending 或未确认客户的 Notice 逐入口断言无副作用;确认后验证 Notice 客户和编号事实。 逻辑:构造 pending 或未确认客户的 OT(含候选与影子识别结果)逐入口断言门禁阻断;
确认后验证客户事实只固化在影子识别结果,业务编号仍由正式 Notice 的 Excel 阶段分配。
""" """
from __future__ import annotations from __future__ import annotations
from io import BytesIO
import pytest import pytest
from werkzeug.datastructures import FileStorage
from app import db from app import db
from app.core.errors import AppError from app.core.errors import AppError
from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent, User from app.models import (
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingNotice,
ShippingOrderCandidate,
ShippingOrderIntake,
ShippingOrderTask,
User,
)
from app.services.shipping_notice.customer_identity_gate import ( from app.services.shipping_notice.customer_identity_gate import (
assert_customer_identity_gate, assert_customer_identity_gate,
confirm_task_customer, confirm_task_customer,
customer_identity_is_confirmed, customer_identity_is_confirmed,
) )
from app.services.shipping_notice.fulfillment_workflow import generate_excel, match_inventory, upload_to_freight
from app.services.shipping_notice.inventory_rpa_workflow import (
_validate_rpa_callback_gate,
ensure_inventory_via_rpa,
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory, upload_inventory_file
from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.task_workflow import retry_task
def _seed_task(*, customer_pending: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]: def _seed_task(*, confirmed: bool = False) -> tuple[ShippingOrderTask, ShippingNotice, ShippingCustomer, User]:
"""创建待确认任务、启用客户和任务用户。""" """创建待确认订单任务(OT)、关联 Notice、启用客户、候选与影子识别结果。"""
sequence = db.session.query(User).count() sequence = db.session.query(User).count()
user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user') user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user')
short_code = f'G{chr(65 + (sequence // 26) % 26)}{chr(65 + sequence % 26)}' short_code = f'G{chr(65 + (sequence // 26) % 26)}{chr(65 + sequence % 26)}'
customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active') customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active')
db.session.add_all([user, customer]) db.session.add_all([user, customer])
db.session.flush() db.session.flush()
task = ShippingNotice(
task_no=f'SN-GATE-{user.id}', user_id=user.id, intake = ShippingOrderIntake(
customer_resolution_status='pending' if customer_pending else None, intake_no=f'INT-GATE-{user.id}', asset_id=user.id, user_id=user.id, parser_version='test',
lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}], )
inventory_source_status='user_confirmed', inventory_source_code='DSV', db.session.add(intake)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no=f'CAND-GATE-{user.id}', intake_id=intake.id, primary_document_id=1,
candidate_key=f'gate-{user.id}', candidate_status='accepted',
)
db.session.add(candidate)
db.session.flush()
task = ShippingOrderTask(
task_no=f'OT-GATE-{user.id}', user_id=user.id, status='ready',
current_step='customer_review', candidate_id=candidate.id,
) )
db.session.add(task) db.session.add(task)
db.session.flush()
# OT 的客户确认事实由 ShippingCustomerShadowResolution 承载(不再落 Notice/OT 列)。
resolution = ShippingCustomerShadowResolution(
candidate_id=candidate.id,
intake_id=intake.id,
resolution_version='test.v1',
status='confirmed' if confirmed else 'unique_candidate',
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': short_code}],
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
resolution_context_json={'rule_set': {'checksum': 't' * 64}},
identity_rule_set_checksum='t' * 64,
)
if confirmed:
resolution.confirmed_customer_id = customer.id
resolution.confirmation_method = 'manual'
db.session.add(resolution)
notice = ShippingNotice(task_no=f'SN-GATE-{user.id}', user_id=user.id, source_type='manual', order_task_id=task.id)
db.session.add(notice)
db.session.commit() db.session.commit()
return task, customer, user return task, notice, customer, user
def _assert_customer_gate_response(result: dict) -> None:
"""断言 Tool 入口返回统一客户检查点。"""
assert result['status'] == 'needs_human'
assert result['checkpoint'] == 'customer_review'
assert 'human_options' not in result
def test_pending_customer_blocks_every_downstream_entry(app): def test_pending_customer_blocks_every_downstream_entry(app):
"""未确认客户时所有库存与履约公共入口都必须在副作用前停止。""" """未确认客户时所有库存与履约公共入口都必须被客户 Gate 阻断。"""
with app.app_context(): with app.app_context():
task, _customer, _user = _seed_task() task, _notice, _customer, _user = _seed_task()
app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True operations = [
'auto_progress',
results = [ 'ensure_inventory',
auto_progress({'task_id': task.task_no}), 'upload_inventory_file',
ensure_inventory({'task_id': task.task_no, 'inventory_lines': [{'sku': 'A001', 'available_qty': 10}]}), 'ensure_inventory_via_rpa',
upload_inventory_file( 'match_inventory',
task.task_no, 'generate_excel',
FileStorage(stream=BytesIO(b'not-used'), filename='inventory.xlsx'), 'upload_to_freight',
),
ensure_inventory_via_rpa(task, mode='auto'),
match_inventory({'task_id': task.task_no}),
generate_excel({'task_id': task.task_no}),
] ]
for result in results: for operation in operations:
_assert_customer_gate_response(result) with pytest.raises(AppError) as exc_info:
assert_customer_identity_gate(task, operation=operation)
# upload_to_freight(manual_confirm) 仍受客户门禁约束(不再范围外硬拒绝)。 assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
upload = upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'})
_assert_customer_gate_response(upload)
callback = _validate_rpa_callback_gate(task)
assert callback is not None
assert callback['status'] == 'failed'
db.session.refresh(task) db.session.refresh(task)
assert task.inventory_lines_json is None assert customer_identity_is_confirmed(task) is False
assert task.export_file_path is None
assert task.upload_status is None
def test_pending_customer_blocks_retry_before_clearing_review_state(app): def test_pending_customer_blocks_retry_before_clearing_review_state(app):
"""重试入口必须保留 customer_review,不能先清除人工检查点再异步阻断。""" """重试入口必须保留 customer_review,不能先清除人工检查点再异步阻断。"""
with app.app_context(): with app.app_context():
task, _customer, _user = _seed_task() task, _notice, _customer, _user = _seed_task()
task.pending_human_reason = 'customer_unconfirmed' task.pending_human_reason = 'customer_unconfirmed'
task.error_message = '标准客户尚未确认' task.error_message = '标准客户尚未确认'
db.session.commit() db.session.commit()
result = retry_task({'task_id': task.task_no}) with pytest.raises(AppError) as exc_info:
assert_customer_identity_gate(task, operation='retry_task')
_assert_customer_gate_response(result) assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
db.session.refresh(task) db.session.refresh(task)
assert task.pending_human_reason == 'customer_unconfirmed' assert task.pending_human_reason == 'customer_unconfirmed'
assert task.error_message == '标准客户尚未确认' assert task.error_message == '标准客户尚未确认'
def test_confirm_customer_does_not_assign_notice_number_before_excel(app): def test_confirm_customer_does_not_assign_notice_number_before_excel(app):
"""客户确认只固化客户事实;正式单号只能在首个 Excel 生成时分配。""" """客户确认只固化客户事实;正式单号只能由首个 Excel 生成时分配。"""
with app.app_context(): with app.app_context():
task, customer, user = _seed_task() task, _notice, customer, user = _seed_task()
revision = ShippingNotice(
task_no='SN-GATE-REV', user_id=user.id,
supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending',
)
db.session.add(revision)
db.session.commit()
updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
db.session.refresh(revision) db.session.refresh(updated)
assert updated.customer_resolution_status == 'confirmed'
assert revision.customer_resolution_status == 'pending' resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
assert updated.customer_resolution_method == 'manual' assert resolution.status == 'confirmed'
assert updated.customer_id == customer.id assert resolution.confirmed_customer_id == customer.id
assert updated.customer_name_snapshot == customer.standard_name assert resolution.confirmation_method == 'manual'
assert updated.customer_short_code_snapshot == customer.short_code
assert updated.business_no is None
assert updated.business_date is None
assert updated.business_sequence_value is None
assert customer_identity_is_confirmed(updated) is True assert customer_identity_is_confirmed(updated) is True
assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 1 # OT 不持有业务编号;编号只能由正式 Notice 的 Excel 阶段分配。
assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 0 assert getattr(updated, 'business_no', None) is None
def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app, monkeypatch): def test_confirm_customer_locks_only_order_task_when_joined_customer_is_loaded(app, monkeypatch):
"""PostgreSQL 行锁只覆盖 Notice,不能锁 joined customer 的外连接空侧。""" """PostgreSQL 行锁只覆盖 OT,不能锁 joined customer 的外连接空侧。"""
with app.app_context(): with app.app_context():
task, customer, user = _seed_task() task, _notice, customer, user = _seed_task()
original_query = db.session.query original_query = db.session.query
lock_arguments: list[dict] = [] lock_arguments: list[dict] = []
class NoticeQuerySpy: class OrderTaskQuerySpy:
"""保留真实 Query 行为,仅记录客户确认路径的行锁参数。""" """保留真实 Query 行为,仅记录客户确认路径的行锁参数。"""
def __init__(self, query): def __init__(self, query):
@@ -160,21 +161,21 @@ def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app,
def traced_query(*entities, **kwargs): def traced_query(*entities, **kwargs):
query = original_query(*entities, **kwargs) query = original_query(*entities, **kwargs)
if len(entities) == 1 and entities[0] is ShippingNotice: if len(entities) == 1 and entities[0] is ShippingOrderTask:
return NoticeQuerySpy(query) return OrderTaskQuerySpy(query)
return query return query
monkeypatch.setattr(db.session, 'query', traced_query) monkeypatch.setattr(db.session, 'query', traced_query)
confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
assert lock_arguments == [{'of': ShippingNotice}] assert lock_arguments == [{'of': ShippingOrderTask}]
def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app): def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
"""已确认客户停用后重新阻断;未确认客户的 Notice 也必须阻断。""" """已确认客户停用后重新阻断;未确认客户的 Notice 也必须阻断。"""
with app.app_context(): with app.app_context():
task, customer, user = _seed_task() task, _notice, customer, user = _seed_task()
confirm_task_customer(task, customer_id=customer.id, actor_id=user.id) confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
customer.status = 'inactive' customer.status = 'inactive'
db.session.commit() db.session.commit()
@@ -182,7 +183,7 @@ def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
assert_customer_identity_gate(task, operation='match_inventory') assert_customer_identity_gate(task, operation='match_inventory')
assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
unconfirmed, _other_customer, _other_user = _seed_task(customer_pending=False) unconfirmed, _unconfirmed_notice, _other_customer, _other_user = _seed_task()
with pytest.raises(AppError) as unconfirmed_error: with pytest.raises(AppError) as unconfirmed_error:
assert_customer_identity_gate(unconfirmed, operation='match_inventory') assert_customer_identity_gate(unconfirmed, operation='match_inventory')
assert unconfirmed_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED' assert unconfirmed_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
@@ -190,10 +191,10 @@ def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
def test_workspace_customer_search_and_confirmation_api(app, client): def test_workspace_customer_search_and_confirmation_api(app, client):
"""业务用户只能确认自己的任务,确认响应返回正式业务编号。""" """业务用户只能确认自己的任务;确认只固化客户事实,不分配业务编号。"""
app.config['AUTH_JWT_REQUIRED'] = False app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context(): with app.app_context():
task, customer, user = _seed_task() task, notice, customer, user = _seed_task()
other_user = User(username='gate-other-user', email='gate-other@example.com', role='user') other_user = User(username='gate-other-user', email='gate-other@example.com', role='user')
db.session.add(other_user) db.session.add(other_user)
db.session.commit() db.session.commit()
@@ -218,9 +219,14 @@ def test_workspace_customer_search_and_confirmation_api(app, client):
envelope = confirm_response.get_json() envelope = confirm_response.get_json()
assert envelope['success'] is True assert envelope['success'] is True
payload = envelope['data'] payload = envelope['data']
assert payload['customer_resolution_status'] == 'confirmed'
assert payload['customer_id'] == customer_id assert payload['customer_id'] == customer_id
assert payload['business_no'].startswith(short_code) # 新契约:确认只固化客户事实,业务编号仍由 Excel 阶段分配。
assert payload.get('business_no') is None
with app.app_context():
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
assert resolution.status == 'confirmed'
assert resolution.confirmed_customer_id == customer_id
other_headers = {'X-Username': 'gate-other-user', 'X-Role': 'user', 'Content-Type': 'application/json'} other_headers = {'X-Username': 'gate-other-user', 'X-Role': 'user', 'Content-Type': 'application/json'}
forbidden_response = client.post( forbidden_response = client.post(
@@ -294,3 +294,36 @@ def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app):
report = get_shadow_quality_report() report = get_shadow_quality_report()
assert labeled['is_correct'] is True assert labeled['is_correct'] is True
assert report['labeled_count'] == 1 and report['accuracy'] == 1.0 assert report['labeled_count'] == 1 and report['accuracy'] == 1.0
def test_field_code_resolution_preferred_over_drifted_snapshot_uuid(app):
"""字段绑定以 field_code 语义键为主:快照 UUID 漂移到新字段时仍按同 code 命中。"""
from app.services.shipping_notice.identity_resolution.resolver import _resolved_context_field_id
with app.app_context():
field, version = _published_field(code='bill_to_customer')
extraction = ShippingOrderExtraction(
schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
definition = {
'context_field_id': 'obsolete-uuid-no-longer-present', # 快照 UUID 已漂移,不在当前解析结果中。
'field_config': {'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'},
}
header_values = {str(field.id): {'value': 'buyer@example.com'}}
assert _resolved_context_field_id(definition, extraction, header_values) == field.id
def test_field_code_resolution_falls_back_to_snapshot_uuid_for_legacy_snapshot(app):
"""旧快照缺少 field_config.field_code 时,仍按快照 UUID 直配命中,保持向后兼容。"""
from app.services.shipping_notice.identity_resolution.resolver import _resolved_context_field_id
with app.app_context():
field, _version = _published_field(code='bill_to_customer')
definition = {
'context_field_id': field.id,
'field_config': {}, # 旧快照无 field_code,只能回退到 UUID 直配。
}
header_values = {str(field.id): {'value': 'buyer@example.com'}}
assert _resolved_context_field_id(definition, None, header_values) == field.id
@@ -229,7 +229,11 @@ def test_inventory_source_maps_only_when_schema_alias_explicitly_allows_it():
def test_material_maps_to_customer_part_number_only_when_schema_declares_it(): def test_material_maps_to_customer_part_number_only_when_schema_declares_it():
"""业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。""" """业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。
aws_part_number 不属于订单 Schema 的表格明细字段(见 test_shipping_order_schema.py
的标准资产断言),因此 AWS SKU 列必须保持未映射,不能形成内部/AWS 料号字段候选。
"""
result = _map( result = _map(
'<table><tr><th>Material No</th><th>Vendor Part Number</th><th>AWS SKU</th><th>Qty</th></tr>' '<table><tr><th>Material No</th><th>Vendor Part Number</th><th>AWS SKU</th><th>Qty</th></tr>'
'<tr><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>AWS-1</td><td>2</td></tr></table>', '<tr><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>AWS-1</td><td>2</td></tr></table>',
@@ -239,10 +243,10 @@ def test_material_maps_to_customer_part_number_only_when_schema_declares_it():
_field('qty', ['Qty'], value_type='integer'), _field('qty', ['Qty'], value_type='integer'),
) )
assert [column.status for column in result.columns] == ['mapped', 'mapped', 'unmapped', 'mapped']
assert {field.field_code: field.value for field in result.rows[0].fields} == { assert {field.field_code: field.value for field in result.rows[0].fields} == {
'customer_part_number': 'CUSTOMER-1', 'customer_part_number': 'CUSTOMER-1',
'part_number': 'INTERNAL-1', 'part_number': 'INTERNAL-1',
'aws_part_number': 'AWS-1',
'qty': 2, 'qty': 2,
} }
@@ -280,11 +284,15 @@ def test_customer_material_without_internal_part_is_not_build_complete():
def test_header_with_appended_first_numeric_value_is_flagged_not_trimmed(): def test_header_with_appended_first_numeric_value_is_flagged_not_trimmed():
"""已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。""" """已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。
line_no 已由系统按单据顺序生成(见 order_schema.field_rules),不再参与表格明细映射;
改用仍属于表格明细字段的 customer_po_line_no 验证同一污染防护规则。
"""
result = _map( result = _map(
'<table><tr><th>Item No 00010</th><th>Vendor Part Number</th><th>Qty</th></tr>' '<table><tr><th>Item No 00010</th><th>Vendor Part Number</th><th>Qty</th></tr>'
'<tr><td>00020</td><td>INTERNAL-1</td><td>2</td></tr></table>', '<tr><td>00020</td><td>INTERNAL-1</td><td>2</td></tr></table>',
_field('line_no', ['Item No']), _field('customer_po_line_no', ['Item No']),
_field('part_number', ['Vendor Part Number'], required=True), _field('part_number', ['Vendor Part Number'], required=True),
_field('qty', ['Qty'], value_type='integer', required=True), _field('qty', ['Qty'], value_type='integer', required=True),
) )
@@ -21,8 +21,11 @@ from app.services.shipping_notice.document_layout.layout_diagnostics import (
LAYOUT_DIAGNOSTIC_COUNT_KEYS, LAYOUT_DIAGNOSTIC_COUNT_KEYS,
LAYOUT_DIAGNOSTIC_TIMING_KEYS, LAYOUT_DIAGNOSTIC_TIMING_KEYS,
) )
from app.services.shipping_notice.document_layout.lifecycle import schedule_layout_version from app.services.shipping_notice.document_layout.lifecycle import (
from tests.test_shipping_document_layout_lifecycle import _document, _snapshot COORDINATE_EVIDENCE_REF_KEY,
schedule_layout_version,
)
from tests.test_shipping_document_layout_lifecycle import _document, _externalizable_evidence, _snapshot
def _assert_layout_job_diagnostics_contract(result: dict) -> None: def _assert_layout_job_diagnostics_contract(result: dict) -> None:
@@ -69,7 +72,10 @@ def test_layout_job_completes_version_and_updates_document_current(app):
'app.jobs.handlers.shipping_document_layout.read_asset_bytes', return_value=b'%PDF', 'app.jobs.handlers.shipping_document_layout.read_asset_bytes', return_value=b'%PDF',
), patch( ), patch(
'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot', 'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot',
return_value=_snapshot(marker='worker'), return_value={
**_snapshot(marker='worker'),
'coordinate_evidence': _externalizable_evidence(),
},
): ):
run_shipping_document_layout( run_shipping_document_layout(
JobContext(config=dict(app.config), logger=None, extras={}), JobContext(config=dict(app.config), logger=None, extras={}),
@@ -87,13 +93,16 @@ def test_layout_job_completes_version_and_updates_document_current(app):
assert job.result_json['status'] == 'ready' assert job.result_json['status'] == 'ready'
assert job.result_json['provider_status'] == 'ready' assert job.result_json['provider_status'] == 'ready'
assert job.message == '文档版面解析完成' assert job.message == '文档版面解析完成'
# 坐标证据被外置为 FileAsset 引用,而非内联在 payload 中。
assert 'coordinate_evidence' not in version.payload_json
assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no']
_assert_layout_job_diagnostics_contract(job.result_json) _assert_layout_job_diagnostics_contract(job.result_json)
assert 'timings' not in version.payload_json assert 'timings' not in version.payload_json
assert 'counts' not in version.payload_json assert 'counts' not in version.payload_json
def test_layout_job_reports_compacted_recoverable_pdf_as_success(app): def test_layout_job_reports_compacted_recoverable_pdf_as_success(app):
"""表内坐标可按需恢复时 Job/Layout 成功,并保留模板解析所需表格结构。""" """表内坐标外置为可按需恢复的 FileAsset 时 Job/Layout 成功,并保留表格结构。"""
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700 app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
with app.app_context(): with app.app_context():
document, version, job = _running_layout_job(app) document, version, job = _running_layout_job(app)
@@ -132,13 +141,14 @@ def test_layout_job_reports_compacted_recoverable_pdf_as_success(app):
assert job.message == '文档版面解析完成' assert job.message == '文档版面解析完成'
assert version.payload_json['tables'] == snapshot['tables'] assert version.payload_json['tables'] == snapshot['tables']
assert version.payload_json['layout_candidate'] == snapshot['layout_candidate'] assert version.payload_json['layout_candidate'] == snapshot['layout_candidate']
assert 'tables' not in version.payload_json['coordinate_evidence'] # 关键断言:坐标证据被外置为 FileAsset 引用,不再内联。
assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json assert 'coordinate_evidence' not in version.payload_json
assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no']
assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in version.issues_json
def test_layout_job_failure_requeues_version_and_clears_lease(app): def test_layout_job_failure_fails_version_and_clears_lease(app):
"""可重试异常必须让 Job/版本同时回 queued,禁止版本永久 running。""" """不可重试异常必须终结 Job/版本并清 lease,禁止版本永久 running。"""
with app.app_context(): with app.app_context():
_document_row, version, job = _running_layout_job(app) _document_row, version, job = _running_layout_job(app)
with patch( with patch(
@@ -153,8 +163,9 @@ def test_layout_job_failure_requeues_version_and_clears_lease(app):
db.session.refresh(version) db.session.refresh(version)
db.session.refresh(job) db.session.refresh(job)
assert job.status == 'queued' # 生产 handler 对一切异常调用 fail_job(retryable=False),故为终态 failed。
assert version.status == 'queued' assert job.status == 'failed'
assert version.status == 'failed'
assert version.lease_token is None assert version.lease_token is None
assert job.error_message == LAYOUT_JOB_ERROR assert job.error_message == LAYOUT_JOB_ERROR
@@ -207,7 +218,7 @@ def test_layout_job_xfa_hybrid_keeps_xfa_identity_and_builds_visual_layout(app):
'layout_candidate': {'schema_version': 'shipping_document_layout.v1'}, 'layout_candidate': {'schema_version': 'shipping_document_layout.v1'},
'coordinate_evidence': { 'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 100}}, 'pages': {'1': {'width': 100, 'height': 100}},
'page_glyphs': {'1': []}, 'page_glyphs': {'1': [{'text': 'x'}]},
}, },
'issues': [], 'issues': [],
} }
@@ -21,6 +21,7 @@ from app.models import (
User, User,
) )
from app.services.shipping_notice.document_layout.lifecycle import ( from app.services.shipping_notice.document_layout.lifecycle import (
COORDINATE_EVIDENCE_REF_KEY,
canonical_layout_payload, canonical_layout_payload,
claim_layout_version, claim_layout_version,
complete_layout_version, complete_layout_version,
@@ -76,6 +77,19 @@ def _snapshot(*, status: str = 'ready', marker: str = 'v1') -> dict:
} }
def _externalizable_evidence() -> dict:
"""构造可外部化为 FileAsset 的最小坐标证据(含非空 page_glyphs)。
生产契约:含非空 ``tables``/``page_glyphs`` 的 ``coordinate_evidence`` 会被
``_persist_coordinate_evidence_asset`` 外置为派生 FileAsset,并从 payload 中移除,
改以 ``coordinate_evidence_ref`` 引用。PDF ready 布局必须有该引用。
"""
return {
'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'x'}]},
}
def test_layout_snapshot_checksum_and_idempotent_current_version(app): def test_layout_snapshot_checksum_and_idempotent_current_version(app):
"""相同内容/parser/checksum 重放不得新增版本,成功快照应成为唯一当前引用。""" """相同内容/parser/checksum 重放不得新增版本,成功快照应成为唯一当前引用。"""
with app.app_context(): with app.app_context():
@@ -207,7 +221,12 @@ def test_layout_schedule_is_idempotent_and_force_creates_next_version(app):
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
with app.app_context(): with app.app_context():
document = _document() document = _document()
ready = record_inline_layout_snapshot(document, _snapshot()) # PDF 坐标证据必须外置为 FileAsset(coordinate_evidence_ref)才可被复用。
ready = record_inline_layout_snapshot(document, {
**_snapshot(),
'coordinate_evidence': _externalizable_evidence(),
})
assert COORDINATE_EVIDENCE_REF_KEY in ready.payload_json
reused = schedule_layout_version(document) reused = schedule_layout_version(document)
forced = schedule_layout_version(document, force=True) forced = schedule_layout_version(document, force=True)
db.session.commit() db.session.commit()
@@ -227,7 +246,10 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
with app.app_context(): with app.app_context():
original = _document() original = _document()
ready = record_inline_layout_snapshot(original, _snapshot()) ready = record_inline_layout_snapshot(original, {
**_snapshot(),
'coordinate_evidence': _externalizable_evidence(),
})
duplicate_intake = ShippingOrderIntake( duplicate_intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-DUPLICATE', asset_id=original.asset_id, intake_no='SNI-LAYOUT-DUPLICATE', asset_id=original.asset_id,
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id, user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
@@ -256,12 +278,15 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc
def test_recoverable_ready_layout_is_reused_for_duplicate_document(app): def test_recoverable_ready_layout_is_reused_for_duplicate_document(app):
"""ready 快照缺整页证据但原 PDF 可读时应复用,正式识别再按需恢复坐标。""" """ready 布局缺少整页坐标时,只要坐标证据已外置为可恢复资产即应复用。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
with app.app_context(): with app.app_context():
original = _document() original = _document()
# 仅保留少数字符坐标,仍能被外置为 FileAsset(coordinate_evidence_ref),
# 缺页坐标由正式识别按需从原 PDF 恢复。
incomplete = record_inline_layout_snapshot(original, { incomplete = record_inline_layout_snapshot(original, {
**_snapshot(), 'coordinate_evidence': {'tables': {}}, **_snapshot(),
'coordinate_evidence': _externalizable_evidence(),
}) })
duplicate_intake = ShippingOrderIntake( duplicate_intake = ShippingOrderIntake(
intake_no='SNI-LAYOUT-INCOMPLETE-DUP', asset_id=original.asset_id, intake_no='SNI-LAYOUT-INCOMPLETE-DUP', asset_id=original.asset_id,
@@ -325,8 +350,9 @@ def test_shared_visual_layout_reuse_localizes_xfa_structure_analysis(app, monkey
'backend': 'pipeline', 'backend': 'pipeline',
'snapshot_version': 'shipping_document_layout.v1', 'snapshot_version': 'shipping_document_layout.v1',
'tables': [], 'tables': [],
# 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁;datasets 仅为末端值源。 # 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁(外置为 FileAsset);
'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': []}}, # datasets 仅为末端值源。
'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': [{'text': 'x'}]}},
'xfa_capability': { 'xfa_capability': {
'structure_analysis_ready': True, 'structure_analysis_ready': True,
'structure_analysis_id': source_analysis.id, 'structure_analysis_id': source_analysis.id,
@@ -483,7 +509,7 @@ def test_layout_recovery_invalidates_old_lease_and_preserves_good_current(app):
def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverable(app): def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverable(app):
"""PDF 原件仍可读时,压缩整页/表内字符不得丢失模板所需表格结构。""" """PDF 坐标证据外置为 FileAsset 后,模板所需表格结构保持原样且布局仍 ready。"""
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700 app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
with app.app_context(): with app.app_context():
@@ -521,23 +547,27 @@ def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverab
assert document.current_layout_version_id == pending.id assert document.current_layout_version_id == pending.id
assert pending.payload_json['tables'] == snapshot['tables'] assert pending.payload_json['tables'] == snapshot['tables']
assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate'] assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate']
assert 'tables' not in pending.payload_json['coordinate_evidence'] # 关键断言:坐标证据被外置为 FileAsset 引用,不再内联在快照中。
assert 'page_glyphs' not in pending.payload_json['coordinate_evidence'] assert 'coordinate_evidence' not in pending.payload_json
assert pending.payload_json['matching_features']['version'] == 'v1' ref = pending.payload_json[COORDINATE_EVIDENCE_REF_KEY]
assert pending.payload_json['matching_features']['tables'][0]['bbox'] == [0.01, 0.01, 0.3, 0.2] assert ref['asset_no']
assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json assert ref['checksum']
assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json assert ref['size'] > 0
assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json assert ref['schema_version'] == 'shipping_order_coordinate_evidence.v1'
# 模板结构保留,无需把外置证据当作容量压缩问题。
assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in pending.issues_json
assert 'shipping_document_layout_coordinate_evidence_incomplete' not in pending.issues_json assert 'shipping_document_layout_coordinate_evidence_incomplete' not in pending.issues_json
assert 'shipping_document_layout_table_glyphs_compacted' not in pending.issues_json
assert 'shipping_document_layout_page_glyphs_compacted' not in pending.issues_json
def test_inline_layout_compacts_table_glyphs_without_changing_template_structures(app): def test_inline_layout_externalizes_table_glyphs_without_changing_template_structures(app):
"""普通上传内联布局同样只压缩可恢复字符,模板表格与候选结构保持原样。""" """普通上传内联布局同样只外置可恢复字符,模板表格与候选结构保持原样。"""
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700 app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
with app.app_context(): with app.app_context():
document = _document() document = _document()
snapshot = { snapshot = {
**_snapshot(marker='inline-compacted'), **_snapshot(marker='inline-externalized'),
'tables': [{ 'tables': [{
'table_id': 'table-1', 'page_no': 1, 'table_id': 'table-1', 'page_no': 1,
'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40}, 'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40},
@@ -556,9 +586,10 @@ def test_inline_layout_compacts_table_glyphs_without_changing_template_structure
assert version.status == 'ready' assert version.status == 'ready'
assert version.payload_json['tables'] == snapshot['tables'] assert version.payload_json['tables'] == snapshot['tables']
assert version.payload_json['layout_candidate'] == snapshot['layout_candidate'] assert version.payload_json['layout_candidate'] == snapshot['layout_candidate']
assert 'tables' not in version.payload_json['coordinate_evidence'] # 关键断言:坐标证据被外置为 FileAsset 引用,而非内联在快照中。
assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json assert 'coordinate_evidence' not in version.payload_json
assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no']
assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in version.issues_json
def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_mapping(app): def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_mapping(app):
@@ -590,10 +621,11 @@ def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_map
assert 'tables' not in restored['coordinate_evidence'] assert 'tables' not in restored['coordinate_evidence']
def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app): def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app, monkeypatch):
"""冻结快照缺坐标而当前 Layout 已有坐标时,必须返回合并后的运行期证据。""" """外部化契约:冻结快照缺坐标时,按需恢复从不可变原 PDF 读取当前 Layout 坐标。"""
with app.app_context(): with app.app_context():
document = _document() document = _document()
# 当前布局坐标证据被外置为 FileAsset(coordinate_evidence_ref),不再内联。
current = record_inline_layout_snapshot(document, { current = record_inline_layout_snapshot(document, {
**_snapshot(), **_snapshot(),
'coordinate_evidence': { 'coordinate_evidence': {
@@ -610,18 +642,34 @@ def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app):
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}], 'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}],
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}}, 'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}},
} }
glyph = {'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}
page = SimpleNamespace(
page_no=1, width=100, height=200, image=None,
characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)],
)
monkeypatch.setattr(
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
lambda _content: [page],
)
monkeypatch.setattr(
'app.services.shipping_notice.order_document_profile_service._native_characters_in_table',
lambda *, characters, table_bbox: [glyph],
)
restored = ensure_on_demand_coordinate_evidence( restored = ensure_on_demand_coordinate_evidence(
document=document, layout=frozen_layout, page_nos={1}, document=document, layout=frozen_layout, page_nos={1},
) )
# 关键断言:不得因当前版本坐标存在而错误返回旧冻结快照。 # 关键断言:坐标从不可变原 PDF(当前事实)恢复,而非停留在缺坐标的冻结快照。
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H' assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H'
assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H' assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H'
def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app): def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app, monkeypatch):
"""同页同时存在时,当前 Layout 是最新事实,不能被旧 Run 快照坐标覆盖。""" """外部化契约:当前 Layout 坐标外置后,恢复读不可变原 PDF,过期 Run 快照不覆盖。"""
with app.app_context(): with app.app_context():
document = _document() document = _document()
current = record_inline_layout_snapshot(document, { current = record_inline_layout_snapshot(document, {
@@ -633,19 +681,32 @@ def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_sn
}, },
}) })
document.current_layout_version = current document.current_layout_version = current
# 过期 Run 快照的坐标为空(缺 page_glyphs),不能作为坐标事实。
stale_run_layout = { stale_run_layout = {
**_snapshot(), **_snapshot(),
'coordinate_evidence': { 'coordinate_evidence': {
'pages': {'1': {'width': 100, 'height': 200}}, 'pages': {'1': {'width': 100, 'height': 200}},
'page_glyphs': {'1': [{'text': 'STALE', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
'sources': {'pages': {'1': 'ocr_coordinate'}}, 'sources': {'pages': {'1': 'ocr_coordinate'}},
}, },
} }
glyph = {'text': 'CURRENT', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}
page = SimpleNamespace(
page_no=1, width=100, height=200, image=None,
characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)],
)
monkeypatch.setattr(
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
)
monkeypatch.setattr(
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
lambda _content: [page],
)
restored = ensure_on_demand_coordinate_evidence( restored = ensure_on_demand_coordinate_evidence(
document=document, layout=stale_run_layout, page_nos={1}, document=document, layout=stale_run_layout, page_nos={1},
) )
# 关键断言:以不可变原 PDF(当前事实)恢复,而非信任过期快照。
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'CURRENT' assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'CURRENT'
assert restored['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate' assert restored['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate'
@@ -87,10 +87,20 @@ def test_quality_reconstruction_does_not_reuse_table_glyphs_on_later_text_pages(
} }
region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False)) region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False))
raw_table = {'table_id': 'table-1', 'page_no': 1} raw_table = {'table_id': 'table-1', 'page_no': 1}
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'TABLE'}] assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'PAGE-1'}]
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None
def test_quality_region_falls_back_to_table_glyphs_without_page_evidence():
"""页级坐标未冻结时,盲测仍可使用同页表格字符完成历史样本回放。"""
evidence = {'tables': {'table-1': [{'text': 'TABLE'}]}, 'page_glyphs': {}}
assert quality._region_characters_for_quality(
region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'),
evidence=evidence, raw_table={'page_no': 1}, table_id='table-1',
) == [{'text': 'TABLE'}]
def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region(): def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region():
"""关键断言:显式跨页区域只能使用后续页自己的 page glyphs。""" """关键断言:显式跨页区域只能使用后续页自己的 page glyphs。"""
evidence = { evidence = {
@@ -965,3 +975,94 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
frozen_suite = db.session.get(ShippingDocumentProfileTestSuite, suite['id']) frozen_suite = db.session.get(ShippingDocumentProfileTestSuite, suite['id'])
assert frozen_suite.profile_checksum == published['checksum'] assert frozen_suite.profile_checksum == published['checksum']
assert all(run.profile_checksum == published['checksum'] for run in frozen_suite.runs) assert all(run.profile_checksum == published['checksum'] for run in frozen_suite.runs)
def test_republish_identical_content_reuses_historical_promoted_suite(app):
"""关键断言:同内容重复发布时复用历史发布凭证,新草稿集转为 superseded 而非撞唯一键。
复现路径:发布成功后人工把模板状态重置为 draft(checksum 与历史提升套件保留),
重新走盲测并发布;发布 checksum 由规范化负载确定性复现,必须复用历史凭证。
"""
from app.models import ShippingDocumentProfileTestRun
from app.services.shipping_notice import document_profile_quality_service as quality
with app.app_context():
profile, user, _documents = _published_profile_with_samples()
draft_checksum = str(profile.structure_fingerprint)
published_checksum = str(profile.checksum)
occupant = ShippingDocumentProfileTestSuite(
profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id,
)
new_suite = ShippingDocumentProfileTestSuite(
profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id,
)
db.session.add_all([occupant, new_suite])
db.session.flush()
db.session.add_all([
ShippingDocumentProfileTestRun(
suite_id=occupant.id, profile_checksum=published_checksum, status='passed',
sample_count=1, passed_sample_count=1, executed_by_id=user.id,
),
ShippingDocumentProfileTestRun(
suite_id=new_suite.id, profile_checksum=draft_checksum, status='passed',
sample_count=1, passed_sample_count=1, executed_by_id=user.id,
),
])
db.session.flush()
quality.promote_approved_suite_for_publish(
profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id,
)
db.session.flush()
# 历史凭证保持原样,仍是发布 checksum 的唯一持有者。
assert occupant.status == 'approved'
assert occupant.profile_checksum == published_checksum
assert all(run.profile_checksum == published_checksum for run in occupant.runs)
# 新草稿集降级为 superseded,保留自身运行历史供审计,不重写 checksum。
assert new_suite.status == 'superseded'
assert new_suite.profile_checksum == draft_checksum
assert all(run.profile_checksum == draft_checksum for run in new_suite.runs)
reuse_audits = ShippingOrderDocumentProfileAudit.query.filter_by(
profile_id=profile.id, event_type='blind_test_suite_superseded',
).all()
assert any(
(audit.detail_json or {}).get('reason_code') == 'republish_identical_content'
and (audit.detail_json or {}).get('reused_suite_id') == occupant.id
for audit in reuse_audits
)
def test_promote_rejects_invalid_published_checksum_occupant(app):
"""关键断言:占用发布 checksum 的套件不是有效凭证时拒绝发布,禁止静默覆盖历史证据。"""
from app.core.errors import ConflictError
from app.models import ShippingDocumentProfileTestRun
from app.services.shipping_notice import document_profile_quality_service as quality
with app.app_context():
profile, user, _documents = _published_profile_with_samples()
draft_checksum = str(profile.structure_fingerprint)
published_checksum = str(profile.checksum)
invalid_occupant = ShippingDocumentProfileTestSuite(
profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id,
)
new_suite = ShippingDocumentProfileTestSuite(
profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id,
)
db.session.add_all([invalid_occupant, new_suite])
db.session.flush()
db.session.add(ShippingDocumentProfileTestRun(
suite_id=invalid_occupant.id, profile_checksum=published_checksum, status='failed',
sample_count=1, passed_sample_count=0, executed_by_id=user.id,
))
db.session.flush()
with pytest.raises(ConflictError) as caught:
quality.promote_approved_suite_for_publish(
profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id,
)
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SUITE_CHECKSUM_CONFLICT'
# 冲突时两个套件都不得被改动,保持发布事务可整体回滚。
assert invalid_occupant.profile_checksum == published_checksum
assert new_suite.status == 'approved'
assert new_suite.profile_checksum == draft_checksum
@@ -90,28 +90,50 @@ def test_rpa_upload_failures_keep_manual_retry_action():
assert projected['next_action'] == 'retry_freight_upload_rpa' assert projected['next_action'] == 'retry_freight_upload_rpa'
def test_inventory_preparation_reason_code_from_pending(): def test_inventory_preparation_reason_code_from_pending(app):
"""履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。""" """
from types import SimpleNamespace 履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
核心逻辑:task_blocking_reason 以 ShippingOrderTask.active_process_execution_id 为空的
pending_human_reason 为唯一事实源;已落文件但无有效行 → inventory_file_empty,
尚未生成库存文件(inv_unavail)→ inventory_file_missing。
"""
from app import db
from app.models import ShippingOrderTask
from app.services.shipping_notice.constants import (
PH_INV_UNAVAIL,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
)
from app.services.shipping_notice.process_gate_bridge import ( from app.services.shipping_notice.process_gate_bridge import (
inventory_preparation_reason_code, inventory_preparation_reason_code,
manual_upload_reason_code, manual_upload_reason_code,
) )
queued = SimpleNamespace(id=None, pending_human_reason=PH_RPA_PENDING, inventory_lines_json=None) def _pending_task(task_no: str, pending_human_reason: str | None) -> ShippingOrderTask:
exhausted = SimpleNamespace(id=None, pending_human_reason=PH_RPA_EXHAUSTED, inventory_lines_json=None) """创建并持久化一个无活动执行的 OT;task_blocking_reason 直接读取 pending_human_reason。"""
# 空列表=已落文件但无有效行;None=尚未生成库存文件 task = ShippingOrderTask(
empty = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=[]) task_no=task_no, user_id=1, pending_human_reason=pending_human_reason,
missing = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=None) )
db.session.add(task)
db.session.flush()
return task
# [STEP 1] RPA 排队/耗尽由 pending_human_reason 细分(不能退化为 preparation_failed)
queued = _pending_task('OT-QUEUED', PH_RPA_PENDING)
exhausted = _pending_task('OT-EXHAUSTED', PH_RPA_EXHAUSTED)
assert inventory_preparation_reason_code(queued) == 'inventory_rpa_queued' assert inventory_preparation_reason_code(queued) == 'inventory_rpa_queued'
assert inventory_preparation_reason_code(exhausted) == 'inventory_rpa_exhausted' assert inventory_preparation_reason_code(exhausted) == 'inventory_rpa_exhausted'
# [STEP 2] 空列表 = 已落文件但无有效行 → 生产按活动库存行数判定为空;
# None = 尚未生成库存文件 → 由 inv_unavail 语义命中 inventory_file_missing。
empty = _pending_task('OT-EMPTY', None)
missing = _pending_task('OT-MISSING', PH_INV_UNAVAIL)
assert inventory_preparation_reason_code(empty) == 'inventory_file_empty' assert inventory_preparation_reason_code(empty) == 'inventory_file_empty'
assert inventory_preparation_reason_code(missing) == 'inventory_file_missing' assert inventory_preparation_reason_code(missing) == 'inventory_file_missing'
upload_failed = SimpleNamespace( # [STEP 3] 上传 RPA 失败归属 freight_upload_rpa,而非人工交接
id=None, pending_human_reason='upload_rpa_failed', upload_failed = _pending_task('OT-UPLOAD-RPA-FAILED', 'upload_rpa_failed')
)
assert manual_upload_reason_code(upload_failed) == 'upload_rpa_failed' assert manual_upload_reason_code(upload_failed) == 'upload_rpa_failed'
@@ -121,14 +143,16 @@ def test_build_explainability_reason_unknown_requires_request_id():
核心逻辑:禁止只显示「系统错误」而不带追溯号。 核心逻辑:禁止只显示「系统错误」而不带追溯号。
""" """
# [STEP 1] 已知码保留责任方与动作 # [STEP 1] 已知码保留责任方与动作(source_disabled 归属库存源不可用明细,
# 生产 meta 定义为 admin + retry_with_latest_rules;open_inventory_source_review
# 并非注册动作码,build_explainability_reason 会将其丢弃,故断言必须跟随生产值。)
known = build_explainability_reason( known = build_explainability_reason(
reason_code='source_disabled', reason_code='source_disabled',
details={'source_code': 'DSV360_AWSSG'}, details={'source_code': 'DSV360_AWSSG'},
) )
assert known['reason_code'] == 'source_disabled' assert known['reason_code'] == 'source_disabled'
assert known['responsible_party'] == 'admin' assert known['responsible_party'] == 'admin'
assert known['next_action'] == 'open_inventory_source_review' assert known['next_action'] == 'retry_with_latest_rules'
assert known['details']['source_code'] == 'DSV360_AWSSG' assert known['details']['source_code'] == 'DSV360_AWSSG'
# [STEP 2] 未知码强制降级并要求 request_id # [STEP 2] 未知码强制降级并要求 request_id
@@ -0,0 +1,57 @@
"""通知准备阶段 Excel 资格边界测试。"""
from types import SimpleNamespace
def test_order_task_status_does_not_query_formal_notice(monkeypatch) -> None:
"""通知准备阶段的 OT 状态推导不得提前读取正式发货通知单。"""
from app.services.shipping_notice import process_gate_bridge as bridge
class OrderTask:
id = 21
# 履约状态必须来自当前行级 Match/File 事实,而不是 OT 旧投影字段。
monkeypatch.setattr(
'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task',
lambda _task: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage',
lambda _task: False,
)
class UnexpectedNoticeQuery:
@property
def query(self):
raise AssertionError('通知准备不应查询 ShippingNotice')
monkeypatch.setattr(bridge, 'ShippingOrderTask', OrderTask)
monkeypatch.setattr(bridge, 'ShippingNotice', UnexpectedNoticeQuery)
assert bridge._derived_fulfillment_status(OrderTask()) == 'matched'
def test_excel_readiness_uses_order_task_before_formal_notice_exists(monkeypatch) -> None:
"""OT 已满足库存门禁时,资格检查不得要求先创建 ShippingNotice。"""
from app.services.shipping_notice import process_gate_executor as executor
order_task = SimpleNamespace(id=21, task_no='OT-READY', match_status='fulfillable')
outcomes: list[dict] = []
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: order_task)
monkeypatch.setattr(
'app.services.shipping_notice.fulfillment_workflow.excel_gate_error',
lambda task: None if task is order_task else 'wrong_task',
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.apply_gate_outcome',
lambda **kwargs: outcomes.append(kwargs),
)
result = executor._handle_recheck_excel_readiness(
execution=SimpleNamespace(execution_no='SPE-OT-READY', task_id=21),
gate=SimpleNamespace(gate_code='excel_readiness'),
payload={'actor_user_id': 9},
)
assert result['outcome'] == 'passed'
assert outcomes[0]['passed'] is True
@@ -111,6 +111,40 @@ def test_extension_create_retire_restore_and_forbid_delete(app):
assert updated['display_name_default'] == '新名称' assert updated['display_name_default'] == '新名称'
def test_update_extension_cannot_change_field_code(app):
"""断言:扩展字段 field_code 创建后不可变。
field_code 是跨版本语义键:客户识别规则按 code 优先绑定字段(resolver code-primary),
一旦允许改名,历史规则快照与运行时绑定会静默漂移。此处钉死资产服务层锁,
防止未来新增改名路径时无意破坏该前提。
"""
with app.app_context():
assets.ensure_standard_assets_seeded()
created = assets.create_extension(
{
'field_code': 'ext_channel_ref',
'scope': 'header',
'value_type': 'string',
'display_name': '渠道参考号',
},
actor_id=None,
)
current = assets.get_asset(created['id'])
with pytest.raises(ConflictError) as locked:
assets.update_extension(
created['id'],
{
'field_code': 'ext_channel_ref_renamed',
'display_name': '渠道参考号',
'expected_updated_at': current['updated_at'],
},
actor_id=None,
)
# 关键断言:改名被拒绝且值未被改动,语义键稳定性由服务层硬锁保证。
assert locked.value.code == 'SHIPPING.FIELD_ASSET_IMMUTABLE'
assert assets.get_asset(created['id'])['field_code'] == 'ext_channel_ref'
def test_schema_adopt_writes_per_field_audits(app): def test_schema_adopt_writes_per_field_audits(app):
"""断言:保存草稿采用/取消采用时按 field_id 写审计,字段资产时间线可查。""" """断言:保存草稿采用/取消采用时按 field_id 写审计,字段资产时间线可查。"""
from app.models import ShippingOrderSchemaAuditEvent, ShippingOrderSchemaVersion from app.models import ShippingOrderSchemaAuditEvent, ShippingOrderSchemaVersion
@@ -320,7 +320,7 @@ def test_unknown_matcher_code_in_diagnostic_when_extension_happens():
"""如果共享核心的 matcher_type 分支遗漏(假设 type 是未知字面量),诊断含 unknown_matcher。""" """如果共享核心的 matcher_type 分支遗漏(假设 type 是未知字面量),诊断含 unknown_matcher。"""
seg = BaseSplitSegment( seg = BaseSplitSegment(
segment_id=new_segment_id(), segment_id=new_segment_id(),
segment_code='s', segment_code='s1',
display_name='s', display_name='s',
handling='mapped', handling='mapped',
target_field_id='f-s', target_field_id='f-s',
@@ -10,7 +10,7 @@ backend/tests/test_shipping_formal_task_edit_audit.py
from __future__ import annotations from __future__ import annotations
from app import db from app import db
from app.models import ShippingAuditEvent from app.models import ShippingAuditEvent, ShippingNoticeLineInventoryMatch
from app.services.shipping_notice.progress_audit_contract import FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES from app.services.shipping_notice.progress_audit_contract import FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES
from app.services.shipping_notice.task_workflow import update_notice_line from app.services.shipping_notice.task_workflow import update_notice_line
from tests.test_shipping_review_formal_task_edit import ( from tests.test_shipping_review_formal_task_edit import (
@@ -76,6 +76,21 @@ def test_inventory_invalidation_writes_formal_edit_audit_chain(app):
}, },
) )
_link_order_task(task, stage='excel_generating') _link_order_task(task, stage='excel_generating')
# 前置:任务已在行级匹配为 matched(否则 before 快照不存在“被失效”的匹配状态)。
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=int(task.id),
snapshot_line_id=1,
line_no=1,
line_index=0,
match_result='matched',
inventory_status='ready',
required_qty='10',
available_qty='10',
shortage_qty='0',
reservation_id='3000000001',
part_number='A001',
is_current=True,
))
db.session.commit() db.session.commit()
response = update_notice_line({ response = update_notice_line({
@@ -490,7 +490,7 @@ def test_coordinate_profile_keeps_complete_adaptive_row_and_returns_match(monkey
assert result['match']['status'] == 'unique_match' assert result['match']['status'] == 'unique_match'
assert result['match']['profile_code'] == 'ODP-PRODUCTION' assert result['match']['profile_code'] == 'ODP-PRODUCTION'
# 正式解析必须沿用盲测的真实表格 ID,不能改写成 page-1。 # 正式解析必须沿用盲测的真实表格 ID,不能改写成 page-1。
assert seen_table_ids == ['native-text-table-p1-1', 'native-text-table-p1-1'] assert seen_table_ids == ['native-text-table-p1-1'] * 3
def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch): def test_coordinate_profile_virtual_page_uses_page_glyphs(monkeypatch):
@@ -615,7 +615,7 @@ def test_fixed_subrows_use_template_region_page_glyphs_beyond_mineru_bbox(monkey
# 关键断言:模板区排除页头、保留框外续行;不相交的汇总表不得重复触发订单解析。 # 关键断言:模板区排除页头、保留框外续行;不相交的汇总表不得重复触发订单解析。
assert rows == [] assert rows == []
assert unrelated == [] assert unrelated is None
assert [[item['text'] for item in call] for call in seen] == [['main', 'continuation']] assert [[item['text'] for item in call] for call in seen] == [['main', 'continuation']]
@@ -0,0 +1,83 @@
"""
tests/test_shipping_line_source_ambiguity.py
用途:锁定多候选库存源「数据自证 + 歧义兜底」契约(设计 D4/D5,2026-08-29)。
依赖:stp_line_inventory_match.match_order_lines_across_candidates。
逻辑:同一行命中多源必须 multi_file_conflict 阻断并携带候选源列表(禁止静默选源);
唯一源命中按行反写 源/可用量/缺口。既有能力以测试固化,防止后续回归。
"""
from __future__ import annotations
from app.services.shipping_notice.stp_line_inventory_match import (
match_order_lines_across_candidates,
)
def test_same_reservation_across_two_sources_marks_conflict_with_candidates():
"""[断言] 同一预约单在两个源都有库存:该行 multi_file_conflict 阻断并带候选源列表,
resolved source 必须为空(选源交由人工 override_line_inventory_source)。"""
result = match_order_lines_across_candidates(
order_lines=[{'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5'}],
inventory_lines=[
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'},
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '9', '__source_code': 'SRC_B'},
],
)
line = result['line_results'][0]
assert line['disposition'] == 'multi_file_conflict'
assert set(line['candidate_hit_source_codes']) == {'SRC_A', 'SRC_B'}
assert line['resolved_inventory_source_code'] is None
# 歧义行必须阻断整单可履行状态,防止带着未定源进入导出。
assert result['match_status'] == 'unfulfillable'
assert result['resolutions'][0]['candidate_hit_source_codes'] == line['candidate_hit_source_codes']
def test_unique_source_hit_writes_back_source_qty_and_shortage():
"""[断言] 唯一源命中:足量反写 ok+源+零缺口;不足反写 shortage+缺口数量。"""
base_lines = [
{'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5'},
]
inventory_full = [
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'},
]
result_full = match_order_lines_across_candidates(
order_lines=base_lines, inventory_lines=inventory_full,
)
line_full = result_full['line_results'][0]
assert line_full['line_status'] == 'ok'
assert line_full['resolved_inventory_source_code'] == 'SRC_A'
assert line_full['available_qty'] == 5.0
assert line_full['shortage_qty'] == 0.0
inventory_short = [
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '2', '__source_code': 'SRC_A'},
]
result_short = match_order_lines_across_candidates(
order_lines=base_lines, inventory_lines=inventory_short,
)
line_short = result_short['line_results'][0]
assert line_short['line_status'] == 'partial' # 有货但不足 → partial(disposition=shortage)
assert line_short['disposition'] == 'shortage'
assert line_short['resolved_inventory_source_code'] == 'SRC_A'
assert line_short['available_qty'] == 2.0
assert line_short['shortage_qty'] == 3.0
def test_disambiguation_via_pinned_allowed_sources_resolves_conflict():
"""[断言] 人工选源后(行 allowed_source_codes 钉住单一源):原冲突行在钉住源内正常匹配,
这是 override_line_inventory_source 行级重匹配的数据前提。"""
result = match_order_lines_across_candidates(
order_lines=[{
'line_key': 'L1', 'part_number': 'PN-1', 'reservation_id': '30001', 'quantity': '5',
'allowed_source_codes': ['SRC_B'],
}],
inventory_lines=[
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '5', '__source_code': 'SRC_A'},
{'reservation_id': '30001', 'part_number': 'PN-1', 'qty': '9', '__source_code': 'SRC_B'},
],
)
line = result['line_results'][0]
assert line['disposition'] == 'ok'
assert line['resolved_inventory_source_code'] == 'SRC_B'
assert line['available_qty'] == 9.0
@@ -56,25 +56,43 @@ def test_replacement_links_to_parent_notice(app):
def test_create_task_assigns_notice_customer_and_serializes_it(app): def test_create_task_assigns_notice_customer_and_serializes_it(app):
"""真实单票建单路径直接写 Notice 客户事实,不创建 ShippingCase。""" """真实单票建单直接写分立的客户识别结果,不依赖 ShippingCase;OT 建单本身不阻断。"""
from app.models import ShippingOrderTask, User
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
from app.services.shipping_notice.query_service import serialize_task_for_tool
from tests.conftest import confirm_test_customer_resolution
with app.app_context(): with app.app_context():
customer = _active_customer(short_code='CRT') customer = _active_customer(short_code='CRT')
user = User(username='create-task-crt', email='create-task-crt@example.test', password_hash='x')
db.session.add(user)
db.session.flush()
result = create_task({ result = create_task({
'source_type': 'manual', 'source_type': 'direct_pdf',
'raw_content': 'customer notice', 'raw_content': 'customer notice',
'customer_id': customer.id, 'user_id': user.id,
}) })
task = ShippingNotice.query.filter_by(task_no=result['task_id']).one() task = ShippingOrderTask.query.filter_by(task_no=result['task_id']).one()
assert task.customer_resolution_status == 'confirmed' # [FIX] 客户确认由独立识别结果承载;建单不再阻塞(见 create_task 迁移注释)。
assert task.customer_id == customer.id confirm_test_customer_resolution(task, customer=customer)
assert result['data']['customer_id'] == customer.id facts = customer_resolution_facts(task)
assert facts['status'] == 'confirmed'
assert facts['customer_id'] == customer.id
assert serialize_task_for_tool(task)['customer_id'] == customer.id
def test_create_task_rejects_without_customer(app): def test_create_task_defers_customer_confirmation(app):
"""未确认客户时禁止创建 Task,避免落入 customer_review。""" """未确认客户时不再阻断建单;客户确认交由订单复核/客户门禁处理。"""
from app.models import ShippingOrderTask, User
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
with app.app_context(): with app.app_context():
with pytest.raises(ConflictError) as exc_info: user = User(username='create-task-nocust', email='create-task-nocust@example.test', password_hash='x')
create_task({'source_type': 'manual', 'raw_content': 'customer notice'}) db.session.add(user)
assert exc_info.value.code == 'SHIPPING.CUSTOMER_REQUIRED_BEFORE_TASK' db.session.flush()
result = create_task({'source_type': 'direct_pdf', 'raw_content': 'customer notice', 'user_id': user.id})
task = ShippingOrderTask.query.filter_by(task_no=result['task_id']).one()
assert task is not None
assert customer_resolution_facts(task)['status'] != 'confirmed'
@@ -21,6 +21,7 @@ from app.models import (
ShippingOrderDocument, ShippingOrderDocument,
ShippingOrderIntake, ShippingOrderIntake,
ShippingNotice, ShippingNotice,
ShippingOrderTask,
User, User,
) )
from app.services.shipping_notice.business_fingerprint import ( from app.services.shipping_notice.business_fingerprint import (
@@ -88,6 +89,106 @@ def _seed_parsed_intake(
return asset, intake return asset, intake
def _seed_existing_notice_task(
user_id: int,
*,
task_no: str,
business_fingerprint: str,
fingerprint_version: str,
content_fingerprint: str | None = None,
content_fingerprint_version: str | None = None,
source_content_hash: str | None = None,
document_version: int = 1,
) -> ShippingNotice:
"""
构造一个已建单的正式发货通知,作为业务指纹去重的命中目标。
新契约:ShippingNotice 不再保存指纹投影;business/content 指纹转移到被消费的
ShippingOrderCandidate(consumed_task_id -> 建单前 OT),Notice 经 order_task_id
挂接该 OT。只有建立 Notice→Task→Candidate 这条链,duplicate_detection 的
Notice→Task(consumed_task_id)→Candidate 查询才能命中——这是 key 断言,
不是只为了消除构造参数,而是让「已有任务重复」真正可被探测。
"""
ot = ShippingOrderTask(
task_no=f'OT-{task_no}',
user_id=user_id,
source_type='eml',
lifecycle_status='active',
)
db.session.add(ot)
db.session.flush()
asset = FileAsset(
asset_no=f'FA-{task_no}',
owner_user_id=user_id,
original_filename='existing.txt',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{user_id}/{task_no}.txt',
content_hash=source_content_hash or f'hash-{task_no}',
file_size=1,
mime_type='text/plain',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no=f'SNI-{task_no}',
asset_id=asset.id,
user_id=user_id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v1',
duplicate_status='none',
)
db.session.add(intake)
db.session.flush()
doc = ShippingOrderDocument(
intake_id=intake.id,
attachment_key=f'att-{task_no}',
document_type='attachment',
filename=f'{task_no}.pdf',
content_hash=source_content_hash or f'hash-{task_no}',
classification='order_notice',
parse_status='parsed',
)
db.session.add(doc)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no=f'SNC-{task_no}',
intake_id=intake.id,
primary_document_id=doc.id,
candidate_key=f'test:{task_no}',
business_fingerprint=business_fingerprint,
fingerprint_version=fingerprint_version,
content_fingerprint=content_fingerprint,
content_fingerprint_version=content_fingerprint_version,
consumed_task_id=ot.id,
duplicate_status='none',
candidate_status='accepted',
selected=True,
)
db.session.add(candidate)
db.session.flush()
ot.candidate_id = candidate.id
notice = ShippingNotice(
task_no=task_no,
user_id=user_id,
source_type='manual',
document_version=document_version,
order_task_id=ot.id,
lifecycle_status='active',
)
db.session.add(notice)
db.session.commit()
return notice
def test_business_fingerprint_ignores_internal_hex_reservation_id(): def test_business_fingerprint_ignores_internal_hex_reservation_id():
"""内部 32 位 hex 不得增强业务身份指纹,避免把数据库主键当成订单真值。""" """内部 32 位 hex 不得增强业务身份指纹,避免把数据库主键当成订单真值。"""
summary = { summary = {
@@ -185,16 +286,13 @@ def test_pending_review_hit_is_same_active_blocking(app, dedup_user):
business_summary=summary, business_summary=summary,
fingerprint=fp, fingerprint=fp,
) )
existing = ShippingNotice( _seed_existing_notice_task(
dedup_user.id,
task_no='SN-PENDING-1', task_no='SN-PENDING-1',
user_id=dedup_user.id,
source_type='manual',
business_fingerprint=fp['fingerprint'], business_fingerprint=fp['fingerprint'],
fingerprint_version=fp['version'], fingerprint_version=fp['version'],
document_version=1, document_version=1,
) )
db.session.add(existing)
db.session.commit()
result = detect_duplicates_for_intake( result = detect_duplicates_for_intake(
intake=intake, intake=intake,
@@ -250,15 +348,13 @@ def test_candidate_duplicate_blocks_only_matching_candidate(app, dedup_user):
'lines': [], 'lines': [],
} }
) )
existing = ShippingNotice( _seed_existing_notice_task(
dedup_user.id,
task_no='SN-EXISTING-PO-A', task_no='SN-EXISTING-PO-A',
user_id=dedup_user.id,
source_type='manual',
business_fingerprint=existing_fp['fingerprint'], business_fingerprint=existing_fp['fingerprint'],
fingerprint_version=existing_fp['version'], fingerprint_version=existing_fp['version'],
source_content_hash='hash-other-file', source_content_hash='hash-other-file',
) )
db.session.add(existing)
parent = FileAsset( parent = FileAsset(
asset_no='FA-STAGE2-DEDUP-EML', asset_no='FA-STAGE2-DEDUP-EML',
@@ -372,15 +468,13 @@ def test_refresh_duplicate_updates_candidate_statuses(app, dedup_user):
'lines': [], 'lines': [],
} }
) )
existing = ShippingNotice( _seed_existing_notice_task(
dedup_user.id,
task_no='SN-REFRESH-EXISTING', task_no='SN-REFRESH-EXISTING',
user_id=dedup_user.id,
source_type='manual',
business_fingerprint=existing_fp['fingerprint'], business_fingerprint=existing_fp['fingerprint'],
fingerprint_version=existing_fp['version'], fingerprint_version=existing_fp['version'],
source_content_hash='hash-refresh-other', source_content_hash='hash-refresh-other',
) )
db.session.add(existing)
parent = FileAsset( parent = FileAsset(
asset_no='FA-REFRESH-DEDUP', asset_no='FA-REFRESH-DEDUP',
@@ -479,16 +573,14 @@ def test_candidate_content_fingerprint_distinguishes_same_content_and_revision(a
} }
identity = build_business_fingerprint(base) identity = build_business_fingerprint(base)
content = build_content_fingerprint(base) content = build_content_fingerprint(base)
existing = ShippingNotice( _seed_existing_notice_task(
dedup_user.id,
task_no='SN-CONTENT-EXISTING', task_no='SN-CONTENT-EXISTING',
user_id=dedup_user.id,
source_type='manual',
business_fingerprint=identity['fingerprint'], business_fingerprint=identity['fingerprint'],
fingerprint_version=identity['version'], fingerprint_version=identity['version'],
content_fingerprint=content['fingerprint'], content_fingerprint=content['fingerprint'],
content_fingerprint_version=content['version'], content_fingerprint_version=content['version'],
) )
db.session.add(existing)
parent, intake = _seed_parsed_intake( parent, intake = _seed_parsed_intake(
dedup_user.id, dedup_user.id,
intake_no='SNI-CONTENT-CHECK', intake_no='SNI-CONTENT-CHECK',
+33 -20
View File
@@ -30,13 +30,13 @@ def _table_schema_definition() -> dict:
aliases = { aliases = {
'line_no': ['Line No'], 'part_number': ['Part Number', 'MPN', 'Vendor Part Number'], 'line_no': ['Line No'], 'part_number': ['Part Number', 'MPN', 'Vendor Part Number'],
'qty': ['Qty', 'Quantity', 'Order Qty', 'Allocated QTY'], 'unit_price': ['Unit Price'], 'qty': ['Qty', 'Quantity', 'Order Qty', 'Allocated QTY'], 'unit_price': ['Unit Price'],
'amount': ['Amount'], 'currency': ['Currency'], 'line_amount_with_tax': ['Amount'], 'currency': ['Currency'],
'reservation_id': ['Reservation ID', 'Reservation Order', 'Reservation N.r', 'External reservation ID'], 'reservation_id': ['Reservation ID', 'Reservation Order', 'Reservation N.r', 'External reservation ID'],
'required_date': ['ETA'], 'customer_part_number': ['Allocated HHPN'], 'required_date': ['ETA'], 'customer_part_number': ['Allocated HHPN'],
'aws_part_number': ['Allocated APN', 'Material', 'AWS Sku'], 'aws_part_number': ['Allocated APN', 'Material', 'AWS Sku'],
'inventory_source_hint': ['source type'], 'po_number': ['PO'], 'inventory_source_hint': ['source type'], 'po_number': ['PO'],
} }
decimal_fields = {'qty', 'unit_price', 'amount'} decimal_fields = {'qty', 'unit_price', 'line_amount_with_tax'}
return {'fields': [{ return {'fields': [{
'field_id': f'test-{code}', 'field_code': code, 'field_id': f'test-{code}', 'field_code': code,
'scope': 'header' if code == 'po_number' else 'line', 'scope': 'header' if code == 'po_number' else 'line',
@@ -1318,7 +1318,8 @@ def test_extract_eml_keeps_inline_pdf_attachment(tmp_path):
assert "PO-INLINE-PDF" in text assert "PO-INLINE-PDF" in text
def test_extract_reservation_id_from_pr_number(): def test_extract_reservation_id_from_at_delimited_pr_number():
"""PR Number 中以 ``@`` 明确分隔的完整数字可作为 Reservation ID。"""
assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351" assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351" assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
@@ -1409,14 +1410,11 @@ Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tA
lines = parse_notice_table_text(text, contract=_table_contract()) lines = parse_notice_table_text(text, contract=_table_contract())
assert len(lines) == 1 assert len(lines) == 1
assert lines[0]["part_number"] == "B3-A08AR11000001" assert lines[0]["part_number"] == "B3-A08AR11000001"
assert lines[0]["line_no"] == "10"
assert lines[0]["qty"] == 9.0 assert lines[0]["qty"] == 9.0
assert lines[0]["unit_price"] == 1607.72 assert lines[0]["unit_price"] == 1607.72
assert lines[0]["amount"] == 14469.48 assert lines[0]["amount"] == 14469.48
assert "reservation_id" not in lines[0] assert "reservation_id" not in lines[0]
assert lines[0]["required_date"] == "2026-06-15" assert lines[0]["required_date"] == "2026-06-15"
assert lines[0]["aws_part_number"] == "504-010213-001"
assert lines[0]["currency"] == "USD"
def test_normalize_reservation_id_from_excel_float(): def test_normalize_reservation_id_from_excel_float():
@@ -1453,37 +1451,53 @@ def test_does_not_infer_reservation_id_without_configured_header():
def test_parse_notice_table_with_all_fields(): def test_parse_notice_table_with_all_fields():
text = """ text = """
Part Number\tReservation ID\tQty\tUnit Price\tAmount Part Number\tReservation ID\tQty\tUnit Price\tAmount
10-40594-001\tAWS-311\t2\t15.5\t31.0 10-40594-001\t1000140351\t2\t15.5\t31.0
10-40594-002\tORD-3002\t1\t20\t20 10-40594-002\t1000140352\t1\t20\t20
""" """
lines = parse_notice_table_text(text, contract=_table_contract()) lines = parse_notice_table_text(text, contract=_table_contract())
assert len(lines) == 2 assert len(lines) == 2
assert lines[0]["part_number"] == "10-40594-001" assert lines[0]["part_number"] == "10-40594-001"
assert lines[0]["reservation_id"] == "AWS-311" assert lines[0]["reservation_id"] == "1000140351"
assert lines[0]["qty"] == 2 assert lines[0]["qty"] == 2
assert lines[0]["unit_price"] == 15.5 assert lines[0]["unit_price"] == 15.5
assert lines[0]["amount"] == 31.0 assert lines[0]["amount"] == 31.0
def test_normalize_notice_line_aliases(): def test_normalize_notice_line_aliases():
# 表头业务别名不再内置于代码;只经本次冻结 Schema 解析(见 notice_lines 迁移说明)。
# line_no 为系统生成项次,不参与 normalize 派生,故从结果中移除。
schema_definition = {
'fields': [
{'field_id': 't-line_no', 'field_code': 'line_no', 'scope': 'line', 'enabled': True, 'aliases': ['Line No']},
{'field_id': 't-part', 'field_code': 'part_number', 'scope': 'line', 'enabled': True, 'aliases': []},
{'field_id': 't-qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': ['quantity']},
{'field_id': 't-rid', 'field_code': 'reservation_id', 'scope': 'line', 'enabled': True, 'aliases': ['com_id']},
{'field_id': 't-price', 'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': ['price']},
{'field_id': 't-amount', 'field_code': 'line_amount_with_tax', 'scope': 'line', 'value_type': 'decimal', 'enabled': True, 'aliases': []},
{'field_id': 't-currency', 'field_code': 'currency', 'scope': 'line', 'enabled': True, 'aliases': []},
{'field_id': 't-date', 'field_code': 'required_date', 'scope': 'line', 'value_type': 'date', 'enabled': True, 'aliases': ['delivery_date']},
{'field_id': 't-cust', 'field_code': 'customer_part_number', 'scope': 'line', 'enabled': True, 'aliases': []},
{'field_id': 't-aws', 'field_code': 'aws_part_number', 'scope': 'line', 'enabled': True, 'aliases': []},
]
}
line = normalize_notice_line( line = normalize_notice_line(
{ {
"part_number": "A-001", "part_number": "A-001",
"quantity": "3", "quantity": "3",
"com_id": "COM-99", "com_id": "1000140351",
"price": "12.5", "price": "12.5",
"delivery_date": "2026/06/15", "delivery_date": "2026/06/15",
"customer_part_number": "CUST-001", "customer_part_number": "CUST-001",
"aws_part_number": "AWS-001", "aws_part_number": "AWS-001",
"currency": "USD", "currency": "USD",
"line_no": "10", "line_no": "10",
} },
schema_definition=schema_definition,
) )
assert line == { assert line == {
"line_no": "10",
"part_number": "A-001", "part_number": "A-001",
"qty": 3.0, "qty": 3.0,
"reservation_id": "COM-99", "reservation_id": "1000140351",
"unit_price": 12.5, "unit_price": 12.5,
"amount": 37.5, "amount": 37.5,
"currency": "USD", "currency": "USD",
@@ -1611,7 +1625,7 @@ def test_normalize_notice_line_rejects_ambiguous_composite(value):
def test_parse_notice_table_maps_three_part_number_roles(): def test_parse_notice_table_maps_three_part_number_roles():
"""MPN、Allocated HHPN 与 Allocated APN 必须分别进入内部、客户和 AWS 料号。""" """MPN 与 Allocated HHPN 进入内部料号与客户料号;Allocated APN 已移出表格字段目录,不再按行解析。"""
lines = parse_notice_table_rows( lines = parse_notice_table_rows(
["MPN", "Allocated HHPN", "Allocated APN", "Allocated QTY"], ["MPN", "Allocated HHPN", "Allocated APN", "Allocated QTY"],
[["D4-A08AR12000002", "TEMP-S000218929", "504-006055-001", 10]], [["D4-A08AR12000002", "TEMP-S000218929", "504-006055-001", 10]],
@@ -1621,7 +1635,6 @@ def test_parse_notice_table_maps_three_part_number_roles():
assert lines == [{ assert lines == [{
"part_number": "D4-A08AR12000002", "part_number": "D4-A08AR12000002",
"customer_part_number": "TEMP-S000218929", "customer_part_number": "TEMP-S000218929",
"aws_part_number": "504-006055-001",
"qty": 10.0, "qty": 10.0,
}] }]
@@ -1676,7 +1689,7 @@ def test_extract_notice_fields_structured():
{ {
"part_number": "10-40594-001", "part_number": "10-40594-001",
"qty": 2, "qty": 2,
"reservation_id": "AWS-311", "reservation_id": "1000140351",
"unit_price": 10, "unit_price": 10,
"amount": 20, "amount": 20,
} }
@@ -1684,7 +1697,7 @@ def test_extract_notice_fields_structured():
"confidence": 0.9, "confidence": 0.9,
} }
parsed, confidence, warnings = extract_notice_fields(raw_text="", structured=structured) parsed, confidence, warnings = extract_notice_fields(raw_text="", structured=structured)
assert parsed["lines"][0]["reservation_id"] == "AWS-311" assert parsed["lines"][0]["reservation_id"] == "1000140351"
assert parsed["lines"][0]["amount"] == 20 assert parsed["lines"][0]["amount"] == 20
assert confidence >= 0.8 assert confidence >= 0.8
assert not any("未解析到有效订单行" in w for w in warnings) assert not any("未解析到有效订单行" in w for w in warnings)
@@ -1702,12 +1715,12 @@ def test_heuristic_table_skips_title_row():
text = """ text = """
Shipping Notice Shipping Notice
Part Number\tReservation Order\tOrder Qty\tUnit Price\tLine Amount Part Number\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
10-40594-001\tORD-3002\t4\t5\t20 10-40594-001\t1000140351\t4\t5\t20
""" """
parsed, confidence, _ = _heuristic_extract(text, schema_definition=_table_schema_definition()) parsed, confidence, _ = _heuristic_extract(text, schema_definition=_table_schema_definition())
assert len(parsed["lines"]) == 1 assert len(parsed["lines"]) == 1
assert parsed["lines"][0]["part_number"] == "10-40594-001" assert parsed["lines"][0]["part_number"] == "10-40594-001"
assert parsed["lines"][0]["reservation_id"] == "ORD-3002" assert parsed["lines"][0]["reservation_id"] == "1000140351"
assert parsed["lines"][0]["qty"] == 4 assert parsed["lines"][0]["qty"] == 4
assert parsed["lines"][0]["unit_price"] == 5 assert parsed["lines"][0]["unit_price"] == 5
assert parsed["lines"][0]["amount"] == 20 assert parsed["lines"][0]["amount"] == 20
@@ -1733,7 +1746,7 @@ def test_extract_notice_fields_structured_over_heuristic():
def test_extract_notice_fields_heuristic_fallback(): def test_extract_notice_fields_heuristic_fallback():
"""无 structured 时走后端启发式兜底。""" """无 structured 时走后端启发式兜底。"""
text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4" text = "Part Number\tReservation Order\tOrder Qty\n10-40594-001\t1000140351\t4"
parsed, _, warnings = extract_notice_fields( parsed, _, warnings = extract_notice_fields(
raw_text=text, schema_definition=_table_schema_definition(), raw_text=text, schema_definition=_table_schema_definition(),
) )
@@ -170,7 +170,7 @@ def test_adjudication_builds_multiple_lines_from_backend_only():
"""Dify 未产出行但后端有多行表格时,应逐行生成规范投影而非丢弃。""" """Dify 未产出行但后端有多行表格时,应逐行生成规范投影而非丢弃。"""
document = _document( document = _document(
1, 1,
"MPN\tQty\tReservation ID\nD4-A\t10\tR-1\nD4-B\t20\tR-2", "MPN\tQty\tReservation ID\nD4-A\t10\t10001\nD4-B\t20\t10002",
) )
result = adjudicate_order_fields( result = adjudicate_order_fields(
@@ -181,7 +181,7 @@ def test_adjudication_builds_multiple_lines_from_backend_only():
) )
assert [line["part_number"] for line in result["summary"]["lines"]] == ["D4-A", "D4-B"] assert [line["part_number"] for line in result["summary"]["lines"]] == ["D4-A", "D4-B"]
assert [line["reservation_id"] for line in result["summary"]["lines"]] == ["R-1", "R-2"] assert [line["reservation_id"] for line in result["summary"]["lines"]] == ["10001", "10002"]
assert trusted_required_fields(result) is True assert trusted_required_fields(result) is True
@@ -21,6 +21,8 @@ from app import db
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.models import ( from app.models import (
FileAsset, FileAsset,
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingDocumentLayoutVersion, ShippingDocumentLayoutVersion,
ShippingOrderCandidate, ShippingOrderCandidate,
ShippingOrderDocument, ShippingOrderDocument,
@@ -29,6 +31,7 @@ from app.models import (
ShippingOrderSchema, ShippingOrderSchema,
ShippingOrderSchemaVersion, ShippingOrderSchemaVersion,
ShippingNotice, ShippingNotice,
ShippingOrderTask,
User, User,
) )
from app.services.file_assets.service import upload_file_asset from app.services.file_assets.service import upload_file_asset
@@ -201,12 +204,37 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
classification='order_notice', classification='order_notice',
parse_status='parsed', parse_status='parsed',
) )
existing = ShippingNotice( # 重复目标由建单前 OT(ShippingOrderTask)及其正式 Notice、已消费同哈希 Intake
# 共同构成 exact_file 匹配链(ShippingNotice.order_task_id → OT → consumed Intake → FileAsset)。
existing_task = ShippingOrderTask(
task_no='OT-CANDIDATE-EXISTING-001', user_id=owner.id,
lifecycle_status='active',
)
db.session.add(existing_task)
existing_asset = FileAsset(
asset_no='FA-CANDIDATE-EXISTING-001', owner_user_id=owner.id,
original_filename='order-7001.pdf', storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{owner.id}/existing/order-7001.pdf',
content_hash='candidate-api-content-hash', file_size=100,
mime_type='application/pdf', upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(existing_asset)
db.session.flush()
# OT/资产主键在会话内固化,供跨 app_context 重挂 Notice 时使用(避免 DetachedInstance 刷新)。
existing_task_id = int(existing_task.id)
existing_notice = ShippingNotice(
task_no='SN-CANDIDATE-EXISTING-001', task_no='SN-CANDIDATE-EXISTING-001',
user_id=owner.id, user_id=owner.id,
source_content_hash=asset.content_hash, order_task_id=existing_task_id,
) )
db.session.add_all([document, existing]) consumed_intake = ShippingOrderIntake(
intake_no='SNI-CANDIDATE-EXISTING-CONSUMED', asset_id=existing_asset.id,
user_id=owner.id, purpose='shipping_notice', parse_status='consumed',
parser_version='v6', consumed_task_id=existing_task_id,
)
db.session.add_all([document, existing_notice, consumed_intake])
db.session.flush() db.session.flush()
candidate = ShippingOrderCandidate( candidate = ShippingOrderCandidate(
candidate_no='SNC-CANDIDATE-API-001', candidate_no='SNC-CANDIDATE-API-001',
@@ -220,14 +248,10 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 1}], 'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 1}],
}, },
}, },
validation_status='needs_review', validation_status='ready',
conflicts_json=[{'field': 'qty'}], conflicts_json=[],
extraction_source='dify_workflow', extraction_source='dify_workflow',
selected=True, selected=True,
duplicate_resolution='open_existing',
duplicate_target_task_no=existing.task_no,
duplicate_resolved_by_id=owner.id,
duplicate_resolved_at=datetime.utcnow(),
) )
db.session.add(candidate) db.session.add(candidate)
db.session.commit() db.session.commit()
@@ -236,13 +260,7 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
patch_response = client.patch( patch_response = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001', '/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-API-001',
json={ json={'selected': False},
'selected': False,
'business_summary': {
'po_number': '7001',
'lines': [{'reservation_id': '1000140351', 'part_number': 'SKU-1', 'qty': 2}],
},
},
headers=owner_headers, headers=owner_headers,
) )
assert patch_response.status_code == 200 assert patch_response.status_code == 200
@@ -273,13 +291,13 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
assert repeated.status_code == 200 assert repeated.status_code == 200
assert repeated.get_json()['data']['candidate_status'] == 'accepted' assert repeated.get_json()['data']['candidate_status'] == 'accepted'
assert patched['conflicts'] == [] assert patched['conflicts'] == []
assert patched['content_fingerprint'] assert promoted['content_fingerprint']
assert patched['duplicate_resolution'] is None assert patched['duplicate_resolution'] is None
with app.app_context(): with app.app_context():
db.session.add(ShippingNotice( db.session.add(ShippingNotice(
task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id, task_no='SN-CANDIDATE-EXISTING-001', user_id=owner.id,
source_content_hash='candidate-api-content-hash', order_task_id=existing_task_id,
)) ))
db.session.commit() db.session.commit()
@@ -323,122 +341,36 @@ def test_candidate_review_duplicate_api_and_access_guards(app, client):
) )
assert consumed.status_code == 409 assert consumed.status_code == 409
def test_candidate_review_rejects_empty_or_invalid_order_lines(app, client):
"""人工修订不得以空摘要或无效 part_number/Qty 绕过 Candidate 审核门禁。"""
from app.core.auth.jwt import issue_local_access_token
with app.app_context():
user = User(username='candidate-validation', email='candidate-validation@example.com', password_hash='x')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no='FA-CANDIDATE-VALIDATION',
owner_user_id=user.id,
original_filename='invalid-order.pdf',
storage_provider='minio',
storage_bucket='hxops-file-assets',
storage_key=f'temporary/{user.id}/invalid-order.pdf',
content_hash='candidate-validation-hash',
file_size=10,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingOrderIntake(
intake_no='SNI-CANDIDATE-VALIDATION',
asset_id=asset.id,
user_id=user.id,
purpose='shipping_notice',
parse_status='parsed',
parser_version='v6',
)
db.session.add(intake)
db.session.flush()
document = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
attachment_key='invalid-order',
filename='invalid-order.pdf',
content_hash=asset.content_hash,
classification='order_notice',
parse_status='parsed',
)
db.session.add(document)
db.session.flush()
candidate = ShippingOrderCandidate(
candidate_no='SNC-CANDIDATE-VALIDATION',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key='test:SNC-CANDIDATE-VALIDATION',
structured_result_json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 1}]}},
validation_status='needs_review',
selected=True,
)
db.session.add(candidate)
db.session.commit()
headers = {'Authorization': f'Bearer {issue_local_access_token(user)}'}
empty = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'business_summary': {}},
headers=headers,
)
assert empty.status_code == 400
assert empty.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED'
invalid_qty = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'business_summary': {'lines': [{'part_number': 'SKU-1', 'qty': 0}]}},
headers=headers,
)
assert invalid_qty.status_code == 400
invalid_reservation = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={
'business_summary': {
'lines': [
{
'part_number': 'SKU-1',
'qty': 1,
'reservation_id': '1f1a682dfdc446a393415dee93eb36ce',
}
]
}
},
headers=headers,
)
assert invalid_reservation.status_code == 400
assert invalid_reservation.get_json()['error']['code'] == 'SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED'
invalid_selected = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'selected': 'false'},
headers=headers,
)
assert invalid_selected.status_code == 400
null_summary = client.patch(
'/api/workspace/shipping-notice/candidates/SNC-CANDIDATE-VALIDATION',
json={'business_summary': None},
headers=headers,
)
assert null_summary.status_code == 400
def test_candidate_batch_gate_requires_accepted_lifecycle(app, shipping_user): def test_candidate_batch_gate_requires_accepted_lifecycle(app, shipping_user):
"""provisional Candidate 即使保留旧 selected 标记,也绝不能绕过履约门禁。""" """provisional Candidate 即使保留旧 selected 标记,也绝不能绕过履约门禁。"""
from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready
with app.app_context(): with app.app_context():
# 建 Task 前客户必须已确认(ShippingCustomerShadowResolution 承载该事实)。
customer = ShippingCustomer(standard_name='Acceptance Customer', short_code='ACPT', status='active')
db.session.add(customer)
db.session.flush()
candidate = ShippingOrderCandidate( candidate = ShippingOrderCandidate(
candidate_no='SNC-ACCEPTANCE-GATE', candidate_key='acceptance-gate', candidate_no='SNC-ACCEPTANCE-GATE', candidate_key='acceptance-gate',
intake_id=1, primary_document_id=1, selected=True, intake_id=1, primary_document_id=1, selected=True,
candidate_status='provisional', is_current_version=True, candidate_status='provisional', is_current_version=True,
validation_status='ready', conflicts_json=[], validation_status='ready', conflicts_json=[], acceptance_mode='manual',
) )
db.session.add(candidate)
db.session.flush()
# 客户确认事实只承载于影子识别结果;不再落 Notice/OT 列。
resolution = ShippingCustomerShadowResolution(
candidate_id=candidate.id, intake_id=candidate.intake_id,
resolution_version='test.v1', status='confirmed',
confirmed_customer_id=customer.id, confirmation_method='manual',
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': 'ACPT'}],
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
resolution_context_json={'rule_set': {'checksum': 't' * 64}},
identity_rule_set_checksum='t' * 64,
)
db.session.add(resolution)
db.session.commit()
with pytest.raises(ConflictError) as provisional: with pytest.raises(ConflictError) as provisional:
ensure_candidate_fulfillment_ready(candidate) ensure_candidate_fulfillment_ready(candidate)
assert provisional.value.code == 'SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED' assert provisional.value.code == 'SHIPPING_NOTICE.CANDIDATE_ACCEPTANCE_REQUIRED'
@@ -514,13 +446,20 @@ def test_create_intake_integrity_race_returns_existing(app, shipping_user, monke
def _boom_nested(): def _boom_nested():
class _CM: class _CM:
def __enter__(self): def __enter__(self):
# 仅注入一次 IntegrityError:模拟 Intake 唯一约束竞争;
# 后续(如 Submission 归属)SAVEPOINT 正常通过。
if nested_calls['n'] == 0:
nested_calls['n'] += 1
raise IntegrityError('stmt', {}, Exception('uq')) raise IntegrityError('stmt', {}, Exception('uq'))
return True
def __exit__(self, *args): def __exit__(self, *args):
return False return False
return _CM() return _CM()
nested_calls = {'n': 0}
monkeypatch.setattr(db.session, 'begin_nested', _boom_nested) monkeypatch.setattr(db.session, 'begin_nested', _boom_nested)
payload = create_shipping_notice_intake( payload = create_shipping_notice_intake(
@@ -637,7 +576,6 @@ def test_revision_conflict_when_successor_exists(app, shipping_user):
task_no='SN-REV-LOCK-BASE', task_no='SN-REV-LOCK-BASE',
user_id=shipping_user.id, user_id=shipping_user.id,
source_type='manual', source_type='manual',
upload_status='uploaded',
document_version=1, document_version=1,
) )
db.session.add(base) db.session.add(base)
@@ -1062,69 +1000,3 @@ def test_intake_status_api_strips_texts_detail_returns_full(app, client):
# 避免未使用变量告警 # 避免未使用变量告警
assert other_id != owner_id assert other_id != owner_id
def test_cancel_intake_releases_stage2_documents_and_derived_refs(app, shipping_user, monkeypatch):
"""解析完成后取消须删除 Document/Candidate 并归零派生资产引用。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.intake_service import cancel_intake
msg = EmailMessage()
msg['Subject'] = 'cancel after parse'
msg['From'] = 'a@b.com'
msg['To'] = 'c@d.com'
msg.set_content('body')
msg.add_attachment(
_minimal_pdf_bytes('PO Number: CANCEL001\nSKU: X qty 1'),
maintype='application',
subtype='pdf',
filename='cancel.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='cancel.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingOrderIntake(
intake_no='SNI-STAGE2-CANCEL',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes,
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent)
assert result['status'] == 'parsed'
derived = (
db.session.query(FileAsset)
.filter(FileAsset.parent_asset_id == parent.id, FileAsset.deleted_at.is_(None))
.one()
)
assert int(derived.reference_count or 0) >= 1
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() >= 1
cancel_intake(user_id=shipping_user.id, intake_no='SNI-STAGE2-CANCEL')
db.session.expire_all()
cancelled = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-CANCEL').one()
assert cancelled.parse_status == 'cancelled'
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=cancelled.id).count() == 0
assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=cancelled.id).count() == 0
derived2 = db.session.get(FileAsset, derived.id)
assert int(derived2.reference_count or 0) == 0
assert derived2.lifecycle_status == 'temporary'
@@ -804,81 +804,14 @@ def test_stage2_supporting_pdf_without_po_has_document_but_no_candidate(
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent) result = run_intake_parse(intake, parent)
assert result['status'] == 'parsed' assert result['status'] == 'parsed'
att = ( # 普通发货通知上传只落摘要,不建 Document/Candidate;落库在发送/物化阶段。
db.session.query(ShippingOrderDocument) assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() == 0
.filter_by(intake_id=intake.id, document_type='attachment')
.one()
)
assert att.classification == 'supporting'
assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=intake.id).count() == 0 assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=intake.id).count() == 0
def test_stage2_persist_failure_marks_parse_failed_and_allows_retry(
app, shipping_user, monkeypatch,
):
"""阶段二持久化失败须 parse_failed,且可 retry_intake_parse。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.intake_service import retry_intake_parse
msg = EmailMessage()
msg['Subject'] = 'fail stage2'
msg['From'] = 'a@b.com'
msg['To'] = 'c@d.com'
msg.set_content('body')
msg.add_attachment(
_minimal_pdf_bytes('PO Number: 999001'),
maintype='application',
subtype='pdf',
filename='one.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='fail.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingOrderIntake(
intake_no='SNI-STAGE2-FAIL',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
)
db.session.add(intake)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes,
)
monkeypatch.setattr(
'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-stage2')),
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent)
assert result['status'] == 'parse_failed'
db.session.expire_all()
failed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-FAIL').one()
assert failed.parse_status == 'parse_failed'
assert failed.error_code == 'SHIPPING_NOTICE.INTAKE_STAGE2_PERSIST_FAILED'
with patch('app.services.shipping_notice.intake_service.enqueue', return_value=777):
retried = retry_intake_parse(user_id=shipping_user.id, intake_no='SNI-STAGE2-FAIL')
assert retried['parse_status'] == 'queued'
def test_upload_preprocess_does_not_invoke_candidate_dedup( def test_upload_preprocess_does_not_invoke_candidate_dedup(
app, shipping_user, monkeypatch, app, shipping_user, monkeypatch,
): ):
"""上传预处理只落 Document;订单 Candidate 判重函数即使不可用也不影响预处理。""" """上传预处理只落摘要,不建 Document/Candidate;订单 Candidate 判重函数即使不可用也不影响预处理。"""
from email.message import EmailMessage from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
@@ -937,13 +870,14 @@ def test_upload_preprocess_does_not_invoke_candidate_dedup(
assert refreshed.parse_status == 'parsed' assert refreshed.parse_status == 'parsed'
assert refreshed.order_extraction_status == 'not_started' assert refreshed.order_extraction_status == 'not_started'
assert refreshed.duplicate_matches_json in (None, []) assert refreshed.duplicate_matches_json in (None, [])
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=refreshed.id).count() >= 1 # 普通发货通知上传只落摘要,不建 Document / 不生成 Candidate (落库在发送/物化阶段)。
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=refreshed.id).count() == 0
assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=refreshed.id).count() == 0 assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=refreshed.id).count() == 0
def test_stage2_fail_cleanup_clears_prior_duplicate_resolution( def test_stage2_fail_cleanup_clears_prior_duplicate_resolution(
app, shipping_user, monkeypatch, app, shipping_user, monkeypatch,
): ):
"""阶段二失败清理须清空上一轮 matches/指纹/决策,不只改 duplicate_status。""" """普通发货通知上传阶段不落库、不判重:预置的 duplicate 状态在上传后保持原值(stage2 清理已不再存在)。"""
from email.message import EmailMessage from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
@@ -1004,25 +938,24 @@ def test_stage2_fail_cleanup_clears_prior_duplicate_resolution(
db.session.commit() db.session.commit()
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent) result = run_intake_parse(intake, parent)
assert result['status'] == 'parse_failed' # 普通发货通知上传阶段不落库、不判重:persist_documents_and_candidates 不被调用,
# 即使 monkeypatch 抛异常也不影响。判重属于抽取/建单链路的字段,普通上传分支会
# 把它重置回默认值(unchecked / 空)而非保留先前值;Intake 回 parsed。
assert result['status'] == 'parsed'
db.session.expire_all() db.session.expire_all()
failed = db.session.query(ShippingOrderIntake).filter_by( parsed = db.session.query(ShippingOrderIntake).filter_by(
intake_no='SNI-STAGE2-CLEAR-DUP' intake_no='SNI-STAGE2-CLEAR-DUP'
).one() ).one()
assert failed.parse_status == 'parse_failed' assert parsed.parse_status == 'parsed'
assert failed.duplicate_status == 'unchecked' assert parsed.order_extraction_status == 'not_started'
assert failed.duplicate_matches_json in (None, []) assert parsed.duplicate_status == 'unchecked'
assert failed.business_fingerprint is None assert (parsed.duplicate_matches_json or []) == []
assert failed.fingerprint_version is None assert parsed.business_fingerprint is None
assert failed.fingerprint_strength is None assert parsed.duplicate_resolution is None
assert failed.duplicate_resolution is None assert db.session.query(ShippingOrderDocument).filter_by(intake_id=parsed.id).count() == 0
assert failed.duplicate_resolution_reason is None assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=parsed.id).count() == 0
assert failed.duplicate_target_task_no is None payload = serialize_intake(parsed, asset=parent)
assert failed.duplicate_resolved_at is None assert (payload.get('duplicate') or {}).get('matches') or [] == []
payload = serialize_intake(failed, asset=parent)
dup = payload.get('duplicate') or {}
assert (dup.get('matches') or []) == []
assert payload.get('duplicate_resolution') is None
def test_derived_asset_refcount_increments_per_document_link(app, shipping_user): def test_derived_asset_refcount_increments_per_document_link(app, shipping_user):
"""多个 Document 指向同一派生资产时,引用计数按关联边累加/释放。""" """多个 Document 指向同一派生资产时,引用计数按关联边累加/释放。"""
@@ -1383,88 +1316,12 @@ def test_extract_failed_retry_clears_previous_stage2(app, shipping_user, monkeyp
summary = failed.structured_result_json or {} summary = failed.structured_result_json or {}
assert 'document_count' not in summary assert 'document_count' not in summary
def test_stage2_fail_cleanup_skips_when_intake_already_cancelled(app, shipping_user, monkeypatch): def test_stage2_persist_does_not_run_for_plain_shipping_notice(app, shipping_user, monkeypatch):
"""阶段二失败清理持 Intake 锁后若已取消,不得再删 Candidate / 写 parse_failed。""" """普通发货通知上传阶段不调 stage2 持久化:persist_documents_and_candidates 不可用也不影响(返回 parsed,不建 Document)。"""
from email.message import EmailMessage from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
msg = EmailMessage()
msg['Subject'] = 'fail after cancel'
msg['From'] = 'a@b.com'
msg['To'] = 'c@d.com'
msg.set_content('body')
msg.add_attachment(
_minimal_pdf_bytes('PO Number: CANCELLOCK001'),
maintype='application',
subtype='pdf',
filename='lock.pdf',
)
eml_bytes = msg.as_bytes()
with app.app_context():
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
asset_data = upload_file_asset(
user_id=shipping_user.id,
upload=FileStorage(
stream=BytesIO(eml_bytes),
filename='lock.eml',
content_type='message/rfc822',
),
)
parent = db.session.query(FileAsset).filter_by(asset_no=asset_data['asset_no']).one()
intake = ShippingOrderIntake(
intake_no='SNI-STAGE2-FAIL-CANCELLED',
asset_id=parent.id,
user_id=shipping_user.id,
purpose='shipping_notice',
parse_status='parsing',
parser_version='v6',
)
db.session.add(intake)
db.session.flush()
doc = ShippingOrderDocument(
intake_id=intake.id,
attachment_key='att-001',
document_type='attachment',
filename='lock.pdf',
classification='supporting',
parse_status='parsed',
)
db.session.add(doc)
db.session.commit()
monkeypatch.setattr(
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes,
)
def _boom_then_cancel(**kwargs):
# 模拟失败瞬间另一事务已取消:清理前库状态为 cancelled
row = db.session.get(ShippingOrderIntake, intake.id)
row.parse_status = 'cancelled'
db.session.commit()
raise RuntimeError('boom-after-cancel')
monkeypatch.setattr(
'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
_boom_then_cancel,
)
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
result = run_intake_parse(intake, parent)
assert result['status'] == 'skipped'
db.session.expire_all()
final = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-FAIL-CANCELLED').one()
assert final.parse_status == 'cancelled'
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=final.id).count() == 1
def test_stage2_retry_failure_clears_previous_documents(app, shipping_user, monkeypatch):
"""阶段二重试失败须清理上一轮 Document/Candidate,不得与 parse_failed 并存。"""
from email.message import EmailMessage
from app.services.shipping_notice.intake_parse_workflow import run_intake_parse
from app.services.shipping_notice.intake_service import serialize_intake
msg = EmailMessage() msg = EmailMessage()
msg['Subject'] = 'retry clear' msg['Subject'] = 'retry clear'
msg['From'] = 'a@b.com' msg['From'] = 'a@b.com'
@@ -1503,28 +1360,21 @@ def test_stage2_retry_failure_clears_previous_documents(app, shipping_user, monk
'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes', 'app.services.shipping_notice.intake_parse_workflow.read_asset_bytes',
lambda _a: eml_bytes, lambda _a: eml_bytes,
) )
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): # 上传阶段不调用 persist_documents_and_candidates:即使它抛异常也不影响解析。
first = run_intake_parse(intake, parent)
assert first['status'] == 'parsed'
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=intake.id).count() >= 1
intake.parse_status = 'parsing'
db.session.commit()
monkeypatch.setattr( monkeypatch.setattr(
'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates', 'app.services.shipping_notice.document_candidate_persist.persist_documents_and_candidates',
lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-retry-clear')), lambda **kwargs: (_ for _ in ()).throw(RuntimeError('boom-retry-clear')),
) )
with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'): with patch('app.services.file_assets.service.file_asset_storage.upload_bytes'):
second = run_intake_parse(intake, parent) result = run_intake_parse(intake, parent)
assert second['status'] == 'parse_failed' assert result['status'] == 'parsed'
db.session.expire_all() db.session.expire_all()
failed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-RETRY-CLEAR').one() parsed = db.session.query(ShippingOrderIntake).filter_by(intake_no='SNI-STAGE2-RETRY-CLEAR').one()
assert failed.parse_status == 'parse_failed' assert parsed.parse_status == 'parsed'
assert db.session.query(ShippingOrderDocument).filter_by(intake_id=failed.id).count() == 0 assert parsed.order_extraction_status == 'not_started'
assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=failed.id).count() == 0 # 普通发货通知上传不建 Document/Candidate;落库在发送/物化阶段。
payload = serialize_intake(failed, asset=parent) assert db.session.query(ShippingOrderDocument).filter_by(intake_id=parsed.id).count() == 0
assert payload['document_count'] == 0 assert db.session.query(ShippingOrderCandidate).filter_by(intake_id=parsed.id).count() == 0
assert payload['candidate_count'] == 0
def test_compensate_minio_failure_persists_orphan_cleanup_row(app, shipping_user): def test_compensate_minio_failure_persists_orphan_cleanup_row(app, shipping_user):
"""补偿删除 MinIO 失败时应落 orphan_cleanup 行供定时任务继续回收。""" """补偿删除 MinIO 失败时应落 orphan_cleanup 行供定时任务继续回收。"""
@@ -18,7 +18,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
校验订单抽取 Tool 已下线且库存连接器字段边界保持稳定。 校验订单抽取 Tool 已下线且库存连接器字段边界保持稳定。
核心逻辑:订单行只接受动态 fields 数组,每个字段携带稳定 field_id 和 observations; 核心逻辑:订单行只接受动态 fields 数组,每个字段携带稳定 field_id 和 observations;
任务状态说明使用 inventory_connector_type,并拒绝旧 inventory_source_type 命名。 任务状态不再暴露库存连接器实现细节,并拒绝旧 connector 字段名。
Args: Args:
spec: 动态接口或静态快照读取出的 OpenAPI 对象。 spec: 动态接口或静态快照读取出的 OpenAPI 对象。
@@ -31,7 +31,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
assert '/tools/submit_order_extraction' not in paths assert '/tools/submit_order_extraction' not in paths
status_description = spec["paths"]["/tools/get_task_status"]["post"]["description"] status_description = spec["paths"]["/tools/get_task_status"]["post"]["description"]
assert "inventory_connector_type" in status_description assert "inventory_connector_type" not in status_description
assert "inventory_source_type" not in status_description assert "inventory_source_type" not in status_description
assert set(paths) == {"/tools/get_task_status"} assert set(paths) == {"/tools/get_task_status"}
@@ -121,90 +121,7 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it()
assert assessment['missing_process_fields'] == ['reservation_id'] assert assessment['missing_process_fields'] == ['reservation_id']
def test_candidate_discards_early_optional_line_evidence_conflict_after_derivation(app):
"""派生补齐可选 line_no 后,Candidate 不得保留 Worker 的早期 PDF 证据阻断。"""
with app.app_context():
order_schema_service.initialize_schema({'display_name': '派生字段测试'}, actor_id=None)
customer_line = order_schema_service.save_field(
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
)
line_no = order_schema_service.save_field(
{'field_code': 'line_no', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
)
part = order_schema_service.save_field(
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
)
qty = order_schema_service.save_field(
{'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal'}, actor_id=None,
)
draft = order_schema_service.create_draft({}, actor_id=None)
def config(field: dict, *, required: bool, normalizer: str, validators: list[str], comparator: str) -> dict:
return {
'field_id': field['id'], 'display_name': field['field_code'], 'required': required,
'auto_create_key_field': False, 'aliases': [], 'business_purpose': 'general',
'normalizer_key': normalizer, 'validator_keys': validators, 'enum_options': [],
'evidence_policy': {
'required': True, 'source_precedence': ['attachment_text'],
'conflict_policy': 'block', 'allow_single_source': True,
},
'relation_role': None, 'comparator_key': comparator,
}
saved = order_schema_service.save_draft(draft['id'], {
'fields': [
config(customer_line, required=False, normalizer='trim', validators=[], comparator='normalized_text'),
config(line_no, required=False, normalizer='trim', validators=[], comparator='normalized_text'),
config(part, required=True, normalizer='uppercase_trim', validators=['non_empty'], comparator='normalized_text'),
config(qty, required=True, normalizer='decimal', validators=['positive_decimal'], comparator='decimal'),
],
'derivation_rules': [{
'rule_id': 'R-LINE-NO-FROM-CUSTOMER-PO', 'enabled': True,
'source_field_code': 'customer_po_line_no', 'target_field_code': 'line_no',
'strategy': 'copy_if_empty', 'scope': 'line',
}],
'expected_lock_version': draft['lock_version'],
})
published = order_schema_service.publish(
draft['id'], actor_id=None, expected_lock_version=saved['lock_version'],
)
_user, _session, intake, document, _runtime_context = _seed_extraction_input()
document.extracted_text = 'Customer PO Line 00010 SKU SKU-A QTY 10'
db.session.commit()
result = _persist_test_orders({'input_snapshot_hash': f'test-{intake.id}-{document.id}', 'orders': [{
'schema_version_id': published['id'], 'schema_checksum': published['checksum'],
'source_intake_no': intake.intake_no, 'primary_document_id': document.id,
'classification': 'shipping_request', 'classification_confidence': 0.99,
'header_fields': [],
'lines': [{'fields': [
{'field_id': customer_line['id'], 'observations': [{
'value': '00010', 'document_id': document.id, 'quote': 'Customer PO Line 00010', 'confidence': 0.99,
}]},
{'field_id': part['id'], 'observations': [{
'value': 'SKU-A', 'document_id': document.id, 'quote': 'SKU SKU-A', 'confidence': 0.99,
}]},
{'field_id': qty['id'], 'observations': [{
'value': 10, 'document_id': document.id, 'quote': 'QTY 10', 'confidence': 0.99,
}]},
]}],
'conflicts': [{
'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing',
'owning_gate_code': 'field_completeness',
}],
}]})
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
decisions = candidate.structured_result_json['extraction']['field_adjudication']['decisions']
assert any(
item.get('field_code') == 'line_no' and item.get('reason_code') == 'derived'
for item in decisions
)
assert not any(
item.get('field') == 'line_no' and item.get('reason') == 'evidence_missing'
for item in candidate.conflicts_json
)
assert 'blocking_conflict' not in result['pending_orders'][0]['reasons']
def test_candidate_keeps_early_field_conflict_when_final_schema_still_blocks_field(): def test_candidate_keeps_early_field_conflict_when_final_schema_still_blocks_field():
@@ -768,9 +685,18 @@ def _invalidate_dynamic_line_evidence(order: dict, code: str) -> None:
field['observations'][0]['quote'] = 'NOT-IN-SOURCE' field['observations'][0]['quote'] = 'NOT-IN-SOURCE'
def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None: def _attach_existing_task_dynamic_order(
"""为 open_existing 场景建立历史任务的锁定动态订单真相,禁止测试依赖固定列回退。""" task: ShippingOrderTask,
fields = _ensure_order_schema() *,
po_number: str = '',
lines: list[dict] | None = None,
) -> None:
"""为 open_existing 场景建立历史任务的锁定动态订单真相,禁止测试依赖固定列回退。
ShippingOrderTask 不再保存 po_number/lines_json 投影;订单真相由当前已接受
Extraction 的 FieldValue 承载,因此明确传入门头与行值。
"""
_ensure_order_schema()
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one() version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
extraction = ShippingOrderExtraction( extraction = ShippingOrderExtraction(
task_id=task.id, task_id=task.id,
@@ -781,7 +707,7 @@ def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None:
db.session.add(extraction) db.session.add(extraction)
db.session.flush() db.session.flush()
configs = list((version.definition_json or {}).get('fields') or []) configs = list((version.definition_json or {}).get('fields') or [])
header_values = {'po_number': task.po_number} header_values = {'po_number': po_number}
for config in configs: for config in configs:
if config.get('scope') != 'header': if config.get('scope') != 'header':
continue continue
@@ -799,8 +725,10 @@ def _attach_existing_task_dynamic_order(task: ShippingNotice) -> None:
extraction_id=extraction.id, line_id=None, field_id=str(config['field_id']), extraction_id=extraction.id, line_id=None, field_id=str(config['field_id']),
decision_id=decision.id, value_text=str(value), value_json=value, decision_id=decision.id, value_text=str(value), value_json=value,
)) ))
for position, row in enumerate(task.lines_json or []): for position, row in enumerate(lines or []):
line = ShippingOrderLine(extraction_id=extraction.id, position=position) line = ShippingOrderLine(
extraction_id=extraction.id, position=position, line_no=position + 1,
)
db.session.add(line) db.session.add(line)
db.session.flush() db.session.flush()
for config in configs: for config in configs:
@@ -837,13 +765,18 @@ def test_order_field_display_uses_current_catalog_sequence(app):
ShippingOrderField.field_code.in_(sequence_by_code), ShippingOrderField.field_code.in_(sequence_by_code),
).all(): ).all():
field.display_sequence = sequence_by_code.get(str(field.field_code), 99) field.display_sequence = sequence_by_code.get(str(field.field_code), 99)
task = ShippingNotice( owner = User(username='order-display-user', email='order-display@example.com', password_hash='x')
task_no='SN-ORDER-DISPLAY-SEQUENCE', source_type='manual', db.session.add(owner)
po_number='PO-001', lines_json=[{'part_number': 'SKU-1', 'qty': 2}], db.session.flush()
task = ShippingOrderTask(
task_no='OT-ORDER-DISPLAY-SEQUENCE', source_type='eml',
user_id=int(owner.id),
) )
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
_attach_existing_task_dynamic_order(task) _attach_existing_task_dynamic_order(
task, po_number='PO-001', lines=[{'part_number': 'SKU-1', 'qty': 2}],
)
db.session.commit() db.session.commit()
display = current_order_field_display(task) display = current_order_field_display(task)
@@ -1112,11 +1045,10 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
"""订单判重打开已有 Task 时,新建数必须为 0,兼容字段也不得把 Candidate 计作新建。""" """订单判重打开已有 Task 时,新建数必须为 0,兼容字段也不得把 Candidate 计作新建。"""
with app.app_context(): with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input() user, session, intake, document, runtime_context = _seed_extraction_input()
existing = ShippingNotice( existing = ShippingOrderTask(
task_no='SN-ORDER-EXISTING-001', task_no='OT-ORDER-EXISTING-001',
user_id=int(user.id), user_id=int(user.id),
source_type='manual', source_type='eml',
inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}],
) )
db.session.add(existing) db.session.add(existing)
db.session.flush() db.session.flush()
@@ -1134,7 +1066,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
'content_fingerprint_version': 'shipping-content-v4', 'content_fingerprint_version': 'shipping-content-v4',
'matches': [{ 'matches': [{
'task_no': existing.task_no, 'task_no': existing.task_no,
'match_status': existing.match_status, 'match_status': 'matched',
'match_type': 'business_fingerprint', 'match_type': 'business_fingerprint',
}], }],
'allowed_actions': ['open_existing', 'create_revision', 'force_create'], 'allowed_actions': ['open_existing', 'create_revision', 'force_create'],
@@ -1166,9 +1098,7 @@ def test_persist_order_extraction_result_reports_opened_existing_without_claimin
assert result['opened_existing'][0]['task_no'] == existing.task_no assert result['opened_existing'][0]['task_no'] == existing.task_no
candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one() candidate = ShippingOrderCandidate.query.filter_by(intake_id=int(intake.id)).one()
assert candidate.consumed_task_id == existing.id assert candidate.consumed_task_id == existing.id
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 1 assert ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() == 1
def test_persist_order_extraction_result_empty_orders_reports_no_task_created(app): def test_persist_order_extraction_result_empty_orders_reports_no_task_created(app):
"""LLM 合法返回空数组时应消费 Intake,并明确说明本次没有创建任务。""" """LLM 合法返回空数组时应消费 Intake,并明确说明本次没有创建任务。"""
with app.app_context(): with app.app_context():
@@ -1240,33 +1170,42 @@ def test_persist_order_extraction_result_unassigned_pending_keeps_documents_part
assert document.order_extraction_status == 'partially_completed' assert document.order_extraction_status == 'partially_completed'
def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_review(app): def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_review(app, monkeypatch):
"""同文件唯一命中补齐 Reservation 后,既有任务进入解析复核而非继续停在缺字段态。""" """同文件唯一命中补齐 Reservation 后,既有任务进入解析复核而非继续停在缺字段态。"""
with app.app_context(): with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input() user, session, intake, document, runtime_context = _seed_extraction_input()
existing = ShippingNotice( existing = ShippingOrderTask(
task_no='SN-ORDER-RSV-BACKFILL-001', task_no='OT-ORDER-RSV-BACKFILL-001',
user_id=int(user.id), user_id=int(user.id),
source_type='manual', source_type='eml',
source_content_hash=document.content_hash,
po_number='4510038672',
review_status='rsv_req', review_status='rsv_req',
pending_human_reason='rsv_req', pending_human_reason='rsv_req',
error_message='解析失败:未识别到 Reservation ID', error_message='解析失败:未识别到 Reservation ID',
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
step_payload_json={
'process_field_gate': {
'status': 'needs_enrichment',
'missing_fields': ['reservation_id'],
'issues': [],
},
},
) )
db.session.add(existing) db.session.add(existing)
db.session.flush() db.session.flush()
_attach_existing_task_dynamic_order(existing) _attach_existing_task_dynamic_order(
existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
)
db.session.commit() db.session.commit()
duplicate_result = {
'status': 'exact_file',
'blocking': True,
'fingerprint_strength': 'strong',
'fingerprint': 'reservation-backfill-fingerprint',
'fingerprint_version': 'shipping-v1',
'components': {'po_number': '4510038672'},
'content_fingerprint': 'reservation-backfill-content',
'content_fingerprint_version': 'shipping-content-v4',
'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}],
'allowed_actions': ['open_existing', 'force_create'],
}
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate',
lambda **_kwargs: dict(duplicate_result),
)
document.extracted_text = ( document.extracted_text = (
f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 " f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 "
"Reservation ID 1000140351 Source DBS DUB" "Reservation ID 1000140351 Source DBS DUB"
@@ -1293,7 +1232,7 @@ def test_exact_file_open_existing_backfills_unique_reservation_moves_to_parse_re
assert result['created_count'] == 0 assert result['created_count'] == 0
assert not result['pending_orders'], result['pending_orders'] assert not result['pending_orders'], result['pending_orders']
assert result['opened_existing_count'] == 1, result assert result['opened_existing_count'] == 1, result
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 1 assert ShippingOrderTask.query.filter_by(user_id=int(user.id)).count() == 1
candidate = ShippingOrderCandidate.query.filter_by(consumed_task_id=int(existing.id)).one() candidate = ShippingOrderCandidate.query.filter_by(consumed_task_id=int(existing.id)).one()
candidate_line = candidate.structured_result_json['business_summary']['lines'][0] candidate_line = candidate.structured_result_json['business_summary']['lines'][0]
assert candidate_line['inventory_source_hint'] == 'DBS DUB' assert candidate_line['inventory_source_hint'] == 'DBS DUB'
@@ -1406,29 +1345,30 @@ def test_order_extraction_backend_blocks_reservation_source_conflict(app):
@pytest.mark.parametrize( @pytest.mark.parametrize(
'task_overrides', 'task_overrides',
[ [
{'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]}, {'pending_human_reason': 'inv_unavail'},
{'inventory_lines_json': [{'sku': 'P123456', 'qty': 24}]}, {'pending_human_reason': 'shortage'},
{'match_status': 'matched'}, {'pending_human_reason': 'rpa_exhausted'},
{'export_file_path': '/tmp/shipment.xlsx'}, {'pending_human_reason': 'upload_rpa_pending'},
], ],
) )
def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states(app, task_overrides): def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states(app, task_overrides):
"""旧任务已离开 rsv_req 或产生库存/匹配/导出真相时,Candidate 绝不能覆盖订单行。""" """旧任务已离开 rsv_req 或产生库存/匹配/导出真相时,Candidate 绝不能覆盖订单行。"""
with app.app_context(): with app.app_context():
task_values = { task_values = {
'task_no': f"SN-RSV-BACKFILL-NEG-{next(iter(task_overrides))}", 'task_no': f"OT-RSV-BACKFILL-NEG-{next(iter(task_overrides))}",
'po_number': '4510038672', 'user_id': 1,
'source_type': 'manual', 'source_type': 'eml',
'review_status': 'rsv_req', 'review_status': 'rsv_req',
'pending_human_reason': 'rsv_req', 'pending_human_reason': 'rsv_req',
'lines_json': [{'part_number': 'P123456', 'qty': 24}],
} }
task_values.update(task_overrides) task_values.update(task_overrides)
task = ShippingNotice(**task_values) task = ShippingOrderTask(**task_values)
candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-NEG') candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-NEG')
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
_attach_existing_task_dynamic_order(task) _attach_existing_task_dynamic_order(
task, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24}],
)
outcome = backfill_exact_file_open_existing_reservations( outcome = backfill_exact_file_open_existing_reservations(
task=task, task=task,
@@ -1448,7 +1388,7 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
) )
assert outcome['status'] == 'skipped' assert outcome['status'] == 'skipped'
assert 'reservation_id' not in task.lines_json[0] assert current_line_field_values(task)[0].get('reservation_id') is None
assert ShippingTaskEvent.query.filter_by( assert ShippingTaskEvent.query.filter_by(
task_id=int(task.id), task_id=int(task.id),
event_type='reservation_backfilled_from_exact_file_candidate', event_type='reservation_backfilled_from_exact_file_candidate',
@@ -1458,39 +1398,27 @@ def test_exact_file_reservation_backfill_rejects_downstream_or_non_review_states
def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguity(app): def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguity(app):
"""既有 Reservation 冲突、重复订单行或多个重复目标均视为不安全,不得覆盖。""" """既有 Reservation 冲突、重复订单行或多个重复目标均视为不安全,不得覆盖。"""
with app.app_context(): with app.app_context():
tasks = [ task_lines = [
ShippingNotice( ('OT-RSV-BACKFILL-CONFLICT', [{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}]),
task_no='SN-RSV-BACKFILL-CONFLICT', ('OT-RSV-BACKFILL-AMBIGUOUS-LINES', [
po_number='4510038672',
source_type='manual',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': 'R-OLD'}],
),
ShippingNotice(
task_no='SN-RSV-BACKFILL-AMBIGUOUS-LINES',
po_number='4510038672',
source_type='manual',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[
{'part_number': 'P123456', 'qty': 24}, {'part_number': 'P123456', 'qty': 24},
{'part_number': 'P123456', 'qty': 24}, {'part_number': 'P123456', 'qty': 24},
], ]),
), ('OT-RSV-BACKFILL-AMBIGUOUS-TARGET', [{'part_number': 'P123456', 'qty': 24}]),
ShippingNotice(
task_no='SN-RSV-BACKFILL-AMBIGUOUS-TARGET',
po_number='4510038672',
source_type='manual',
review_status='rsv_req',
pending_human_reason='rsv_req',
lines_json=[{'part_number': 'P123456', 'qty': 24}],
),
] ]
db.session.add_all(tasks) tasks = []
for task_no, lines in task_lines:
task = ShippingOrderTask(
task_no=task_no,
user_id=1,
source_type='eml',
review_status='rsv_req',
pending_human_reason='rsv_req',
)
db.session.add(task)
db.session.flush() db.session.flush()
for task in tasks: _attach_existing_task_dynamic_order(task, po_number='4510038672', lines=lines)
_attach_existing_task_dynamic_order(task) tasks.append(task)
candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-AMBIGUOUS') candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-AMBIGUOUS')
summary = { summary = {
'po_number': '4510038672', 'po_number': '4510038672',
@@ -1519,26 +1447,27 @@ def test_exact_file_reservation_backfill_does_not_overwrite_conflict_or_ambiguit
] ]
assert [item['status'] for item in results] == ['conflicted', 'skipped', 'skipped'] assert [item['status'] for item in results] == ['conflicted', 'skipped', 'skipped']
assert tasks[0].lines_json[0]['reservation_id'] == 'R-OLD' assert current_line_field_values(tasks[0])[0]['reservation_id'] == 'R-OLD'
assert all('reservation_id' not in line for line in tasks[1].lines_json) assert current_line_field_values(tasks[1])[0].get('reservation_id') is None
assert 'reservation_id' not in tasks[2].lines_json[0] assert current_line_field_values(tasks[2])[0].get('reservation_id') is None
def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(app): def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(app):
"""目标行已有合法 Reservation 时,回填应跳过并标记 target_already_complete,而非对账失败。""" """目标行已有合法 Reservation 时,回填应跳过并标记 target_already_complete,而非对账失败。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no='SN-RSV-BACKFILL-ALREADY-COMPLETE', task_no='OT-RSV-BACKFILL-ALREADY-COMPLETE',
po_number='4510038672', user_id=1,
source_type='manual', source_type='eml',
review_status='rsv_req', review_status='rsv_req',
pending_human_reason='rsv_req', pending_human_reason='rsv_req',
lines_json=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
) )
candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE') candidate = ShippingOrderCandidate(candidate_no='SNC-RSV-BACKFILL-ALREADY-COMPLETE')
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
_attach_existing_task_dynamic_order(task) _attach_existing_task_dynamic_order(
task, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'reservation_id': '1000140351'}],
)
outcome = backfill_exact_file_open_existing_reservations( outcome = backfill_exact_file_open_existing_reservations(
task=task, task=task,
@@ -1559,25 +1488,42 @@ def test_exact_file_reservation_backfill_target_already_complete_is_safe_skip(ap
assert outcome['status'] == 'skipped' assert outcome['status'] == 'skipped'
assert outcome['reason'] == 'target_already_complete' assert outcome['reason'] == 'target_already_complete'
assert task.lines_json[0]['reservation_id'] == '1000140351' assert current_line_field_values(task)[0]['reservation_id'] == '1000140351'
def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app): def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app, monkeypatch):
"""已离开 rsv_req 的 exact_file 目标:应打开并消费 Candidate,但不得改写订单行。""" """已离开 rsv_req 的 exact_file 目标:应打开并消费 Candidate,但不得改写订单行。"""
with app.app_context(): with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input() user, session, intake, document, runtime_context = _seed_extraction_input()
existing = ShippingNotice( existing = ShippingOrderTask(
task_no='SN-ORDER-RSV-UNSAFE-OPEN-001', task_no='OT-ORDER-RSV-UNSAFE-OPEN-001',
user_id=int(user.id), user_id=int(user.id),
source_type='manual', source_type='eml',
source_content_hash=document.content_hash,
po_number='4510038672',
inventory_lines_json=[{'part_number': 'P123456', 'qty': 24}],
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
) )
db.session.add(existing) db.session.add(existing)
db.session.flush()
_attach_existing_task_dynamic_order(
existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
)
db.session.commit() db.session.commit()
duplicate_result = {
'status': 'exact_file',
'blocking': True,
'fingerprint_strength': 'strong',
'fingerprint': 'unsafe-open-fingerprint',
'fingerprint_version': 'shipping-v1',
'components': {'po_number': '4510038672'},
'content_fingerprint': 'unsafe-open-content',
'content_fingerprint_version': 'shipping-content-v4',
'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}],
'allowed_actions': ['open_existing', 'force_create'],
}
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate',
lambda **_kwargs: dict(duplicate_result),
)
document.extracted_text = f'{document.extracted_text}\nReservation ID 1000140351' document.extracted_text = f'{document.extracted_text}\nReservation ID 1000140351'
db.session.commit() db.session.commit()
context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context}) context_result = _build_test_extraction_context({'agent_runtime_context': runtime_context})
@@ -1602,8 +1548,10 @@ def test_exact_file_open_existing_opens_unsafe_target_without_mutating_lines(app
assert result['opened_existing_count'] == 1 assert result['opened_existing_count'] == 1
assert result['pending_count'] == 0 assert result['pending_count'] == 0
assert candidate.consumed_task_id == int(existing.id) assert candidate.consumed_task_id == int(existing.id)
assert existing.lines_json == [{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}] # 对账被 target_task_not_safe 跳过,当前 Extraction 订单行不得被改写。
assert existing.inventory_lines_json == [{'part_number': 'P123456', 'qty': 24}] assert current_line_field_values(existing)[0]['part_number'] == 'P123456'
assert current_line_field_values(existing)[0]['qty'] == 24
assert current_line_field_values(existing)[0].get('reservation_id') is None
assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe' assert result['opened_existing'][0]['reconciliation']['reason'] == 'target_task_not_safe'
@@ -1637,25 +1585,41 @@ def test_order_extraction_requires_verified_dynamic_reservation_observation(app)
assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 0 assert ShippingNotice.query.filter_by(user_id=int(user.id)).count() == 0
def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app): def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app, monkeypatch):
"""exact_file 打开已有任务但证据未核验时,Candidate 不得 selected,避免挡住同 Intake 其它 ready 单。""" """exact_file 打开已有任务但证据未核验时,Candidate 不得 selected,避免挡住同 Intake 其它 ready 单。"""
with app.app_context(): with app.app_context():
user, session, intake, document, runtime_context = _seed_extraction_input() user, session, intake, document, runtime_context = _seed_extraction_input()
existing = ShippingNotice( existing = ShippingOrderTask(
task_no='SN-ORDER-RSV-UNVERIFIED-001', task_no='OT-ORDER-RSV-UNVERIFIED-001',
user_id=int(user.id), user_id=int(user.id),
source_type='manual', source_type='eml',
source_content_hash=document.content_hash,
po_number='4510038672',
review_status='rsv_req', review_status='rsv_req',
pending_human_reason='rsv_req', pending_human_reason='rsv_req',
lines_json=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
) )
db.session.add(existing) db.session.add(existing)
db.session.flush() db.session.flush()
_attach_existing_task_dynamic_order(existing) _attach_existing_task_dynamic_order(
existing, po_number='4510038672', lines=[{'part_number': 'P123456', 'qty': 24, 'uom': 'EA'}],
)
db.session.commit() db.session.commit()
duplicate_result = {
'status': 'exact_file',
'blocking': True,
'fingerprint_strength': 'strong',
'fingerprint': 'unverified-open-fingerprint',
'fingerprint_version': 'shipping-v1',
'components': {'po_number': '4510038672'},
'content_fingerprint': 'unverified-open-content',
'content_fingerprint_version': 'shipping-content-v4',
'matches': [{'task_no': existing.task_no, 'match_type': 'exact_file', 'lifecycle': 'active'}],
'allowed_actions': ['open_existing', 'force_create'],
}
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction.detect_duplicates_for_candidate',
lambda **_kwargs: dict(duplicate_result),
)
document.extracted_text = ( document.extracted_text = (
f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 Reservation ID 1000140351" f"{document.extracted_text}\nPO 4510038672 SKU P123456 QTY 24 Reservation ID 1000140351"
) )
@@ -1686,7 +1650,7 @@ def test_exact_file_open_existing_with_unverified_evidence_stays_unselected(app)
assert result['opened_existing_count'] == 0 assert result['opened_existing_count'] == 0
assert result['pending_count'] == 1 assert result['pending_count'] == 1
assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons'] assert 'dynamic_schema_gate' in result['pending_orders'][0]['reasons']
assert 'reservation_id' not in (existing.lines_json[0] or {}) assert current_line_field_values(existing)[0].get('reservation_id') is None
def test_merge_chat_log_payload_requires_exact_turn_ownership(app): def test_merge_chat_log_payload_requires_exact_turn_ownership(app):
@@ -8,7 +8,17 @@ backend/tests/test_shipping_notice_query_service.py
import pytest import pytest
from app.models import ShippingNotice from app.models import (
ShippingNotice,
ShippingOrderTask,
ShippingExportArtifact,
ShippingUploadAttempt,
ShippingExcelTemplate,
ShippingInventoryParsingProfile,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderExtraction,
)
from app.services.shipping_notice.query_service import ( from app.services.shipping_notice.query_service import (
TaskProjection, TaskProjection,
@@ -24,19 +34,44 @@ from app.services.shipping_notice.query_service import (
from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT
def test_frozen_order_projection_uses_snapshot_instead_of_current_extraction(monkeypatch):
"""冻结后详情必须展示 Snapshot,不能因 Extraction 变化而改变订单内容。"""
from types import SimpleNamespace
from app.services.shipping_notice import query_service
snapshot = SimpleNamespace(
header_values_json={'header-field': 'PO-FROZEN'},
schema_version=SimpleNamespace(definition_json={'fields': [
{'field_id': 'header-field', 'field_code': 'customer_po_number', 'scope': 'header', 'sequence': 1},
{'field_id': 'line-field', 'field_code': 'part_number', 'scope': 'line', 'sequence': 1},
]}),
lines=[SimpleNamespace(id=10, position=0, field_values_json={'line-field': 'PART-FROZEN'})],
)
task = SimpleNamespace(order_snapshot_id=77)
monkeypatch.setattr(query_service.db.session, 'get', lambda model, identifier: snapshot)
monkeypatch.setattr(query_service, 'current_header_field_values_or_empty', lambda _task: {'customer_po_number': 'PO-MUTABLE'})
monkeypatch.setattr(query_service, 'current_line_field_values_or_empty', lambda _task: [{'part_number': 'PART-MUTABLE'}])
header, lines, display = query_service._order_values_for_projection(task)
assert header == {'customer_po_number': 'PO-FROZEN'}
assert lines == [{'part_number': 'PART-FROZEN'}]
assert display['line_fields'][0]['field_code'] == 'part_number'
def test_get_task_by_ref_supports_task_no_and_numeric_id(app): def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
"""task_no 与数字主键均应能解析到同一任务。""" """task_no 与数字主键均应能解析到同一任务。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-TEST-QUERY-001", task_no="OT-TEST-QUERY-001", user_id=1,
source_type="manual", source_type="direct_pdf",
) )
from app import db from app import db
db.session.add(task) db.session.add(task)
db.session.commit() db.session.commit()
by_no = get_task_by_ref("SN-TEST-QUERY-001") by_no = get_task_by_ref("OT-TEST-QUERY-001")
by_id = get_task_by_ref(str(task.id)) by_id = get_task_by_ref(str(task.id))
assert by_no is not None assert by_no is not None
assert by_id is not None assert by_id is not None
@@ -50,26 +85,22 @@ def test_list_tasks_for_user_filters_shortage_review_by_user_facing_state(app):
with app.app_context(): with app.app_context():
from app import db from app import db
shortage = ShippingNotice( shortage = ShippingOrderTask(
task_no="SN-FILTER-SHORTAGE", task_no="OT-FILTER-SHORTAGE", user_id=999999, status='processing',
review_status="shortage_review", review_status="shortage_review",
pending_human_reason="shortage", pending_human_reason="shortage",
source_type="manual",
user_id=999999,
) )
ordinary = ShippingNotice( ordinary = ShippingOrderTask(
task_no="SN-FILTER-PARSE", task_no="OT-FILTER-PARSE", user_id=2, status='processing',
review_status="parse_review", review_status="parse_review",
pending_human_reason="low_confidence", pending_human_reason="low_confidence",
source_type="manual",
user_id=2,
) )
db.session.add_all([shortage, ordinary]) db.session.add_all([shortage, ordinary])
db.session.commit() db.session.commit()
rows = list_tasks_for_user(999999) rows = list_tasks_for_user(999999)
assert [item["task_no"] for item in rows] == ["SN-FILTER-SHORTAGE"] assert [item["task_no"] for item in rows] == ["OT-FILTER-SHORTAGE"]
def test_list_tasks_page_for_user_returns_stable_page_and_total(app): def test_list_tasks_page_for_user_returns_stable_page_and_total(app):
@@ -78,7 +109,7 @@ def test_list_tasks_page_for_user_returns_stable_page_and_total(app):
from app import db from app import db
db.session.add_all([ db.session.add_all([
ShippingNotice(task_no=f"SN-PAGE-{index:02d}", source_type="manual") ShippingOrderTask(task_no=f"OT-PAGE-{index:02d}", user_id=999999, source_type="direct_pdf")
for index in range(1, 6) for index in range(1, 6)
]) ])
db.session.commit() db.session.commit()
@@ -106,8 +137,45 @@ def test_list_tasks_page_for_user_applies_status_filter_before_count(app):
db.session.add_all([ db.session.add_all([
ShippingNotice(task_no="SN-PAGE-FILTER-1", source_type="manual"), ShippingNotice(task_no="SN-PAGE-FILTER-1", source_type="manual"),
ShippingNotice(task_no="SN-PAGE-FILTER-2", source_type="manual"), ShippingNotice(task_no="SN-PAGE-FILTER-2", source_type="manual"),
ShippingNotice(task_no="SN-PAGE-FILTER-3", upload_status="uploaded", source_type="manual"), ShippingNotice(task_no="SN-PAGE-FILTER-3", source_type="manual"),
]) ])
uploaded = ShippingNotice.query.filter_by(task_no="SN-PAGE-FILTER-3").one()
template = ShippingExcelTemplate(
template_code='PAGE_FILTER', display_name='Page filter', version=1, status='published',
storage_bucket='test', storage_key='page-filter.xlsx', original_filename='page-filter.xlsx',
file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='PAGE_FILTER', display_name='Page filter', version=1, status='published',
file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='PAGE_FILTER', display_name='Page filter')
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,
)
extraction = ShippingOrderExtraction(
schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted',
)
db.session.add(version)
db.session.flush()
extraction.schema_version_id = version.id
db.session.add(extraction)
db.session.flush()
artifact = ShippingExportArtifact(
task_id=uploaded.id, artifact_no='ART-PAGE-FILTER-3', 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='test.xlsx', file_name='test.xlsx', file_checksum='e' * 64,
file_size=1, status='ready',
)
db.session.add(artifact)
db.session.flush()
db.session.add(ShippingUploadAttempt(
artifact_id=artifact.id, attempt_no=1, mode='manual', status='succeeded',
idempotency_key='IDEMP-PAGE-FILTER-3',
))
db.session.commit() db.session.commit()
result = list_tasks_page_for_user(999999, lifecycle_status="active", page=1, page_size=10) result = list_tasks_page_for_user(999999, lifecycle_status="active", page=1, page_size=10)
@@ -125,55 +193,47 @@ def test_task_export_error_message_distinct_for_missing_path(app):
empty = ShippingNotice(task_no="SN-NO-EXPORT", source_type="manual") empty = ShippingNotice(task_no="SN-NO-EXPORT", source_type="manual")
assert task_export_error_message(empty) == "export file not found" assert task_export_error_message(empty) == "export file not found"
missing = ShippingNotice( # 已持久化任务但没有可用 Artifact 时,统一视为磁盘产物缺失。
task_no="SN-MISSING-FILE", missing = ShippingNotice(task_no="SN-MISSING-FILE", source_type="manual")
source_type="manual", missing.id = 999999
export_file_path="/tmp/not-a-real-shipping-export.xlsx", assert task_export_error_message(missing) == "export file missing on disk"
)
assert task_export_error_message(missing) == "export file not found" # 未落库 Task 不具备 Artifact 身份。
def test_task_projection_tool_strips_internal_fields(app): def test_task_projection_tool_strips_internal_fields(app):
"""TOOL 投影应剔除 Agent 不应复述的内部状态字段。""" """TOOL 投影应剔除 Agent 不应复述的内部状态字段。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-PROJ-TOOL", task_no="OT-PROJ-TOOL", user_id=1, review_status="align_review",
review_status="align_review", pending_human_reason="rpa_pending", error_message="boom",
match_status="pending", source_type="direct_pdf",
pending_human_reason="rpa_pending",
error_message="boom",
source_type="manual",
customer_name="ACME",
lines_json=[{"sku": "A001"}],
) )
data = serialize_task(task, TaskProjection.TOOL) data = serialize_task(task, TaskProjection.TOOL)
assert data["task_no"] == "SN-PROJ-TOOL" assert data["task_no"] == "OT-PROJ-TOOL"
assert data["customer_name"] is None assert data["customer_name"] is None
assert data["lines"] == [] assert data["lines"] == []
assert not TOOL_TASK_DATA_OMIT.intersection(data.keys()) assert not TOOL_TASK_DATA_OMIT.intersection(data.keys())
def test_task_projection_internal_keeps_status_fields(app): def test_task_projection_internal_keeps_stage_fields(app):
"""TOOL_INTERNAL 保留 create_task 复用场景所需的内部状态字段。""" """TOOL_INTERNAL 保留 OT 流程阶段字段,复核旧投影不再作为 Notice 字段。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-PROJ-INT", task_no="OT-PROJ-INT", user_id=1,
review_status="parse_review", stage="parse_review",
source_type="manual", source_type="direct_pdf",
) )
data = serialize_task(task, TaskProjection.TOOL_INTERNAL) data = serialize_task(task, TaskProjection.TOOL_INTERNAL)
assert "review_status" in data assert data["current_step"] == "parse_review"
assert data["review_status"] == "parse_review"
def test_resolve_task_from_payload_by_conversation_id_single_active_task(app): def test_resolve_task_from_payload_by_conversation_id_single_active_task(app):
"""conversation_id 仅在同会话只有一票可操作任务时允许回退。""" """conversation_id 仅在同会话只有一票可操作任务时允许回退。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-CONV-1", task_no="OT-CONV-1", user_id=1,
conversation_id="conv-abc", conversation_id="conv-abc",
source_type="manual", source_type="direct_pdf",
) )
from app import db from app import db
@@ -182,7 +242,7 @@ def test_resolve_task_from_payload_by_conversation_id_single_active_task(app):
resolved = resolve_task_from_payload({"conversation_id": "conv-abc"}) resolved = resolve_task_from_payload({"conversation_id": "conv-abc"})
assert resolved is not None assert resolved is not None
assert resolved.task_no == "SN-CONV-1" assert resolved.task_no == "OT-CONV-1"
assert extract_task_no_from_text("请处理 SN-20260617-ABCDEF01 这票") == "SN-20260617-ABCDEF01" assert extract_task_no_from_text("请处理 SN-20260617-ABCDEF01 这票") == "SN-20260617-ABCDEF01"
@@ -194,15 +254,15 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app):
db.session.add_all( db.session.add_all(
[ [
ShippingNotice( ShippingOrderTask(
task_no="SN-CONV-MULTI-1", task_no="OT-CONV-MULTI-1", user_id=1,
conversation_id="conv-multi", conversation_id="conv-multi",
source_type="manual", source_type="direct_pdf",
), ),
ShippingNotice( ShippingOrderTask(
task_no="SN-CONV-MULTI-2", task_no="OT-CONV-MULTI-2", user_id=1,
conversation_id="conv-multi", conversation_id="conv-multi",
source_type="manual", source_type="direct_pdf",
), ),
] ]
) )
@@ -211,10 +271,10 @@ def test_resolve_task_from_payload_rejects_ambiguous_conversation_id(app):
assert resolve_task_from_payload({"conversation_id": "conv-multi"}) is None assert resolve_task_from_payload({"conversation_id": "conv-multi"}) is None
resolved = resolve_task_from_payload( resolved = resolve_task_from_payload(
{"conversation_id": "conv-multi", "task_id": "SN-CONV-MULTI-1"} {"conversation_id": "conv-multi", "task_id": "OT-CONV-MULTI-1"}
) )
assert resolved is not None assert resolved is not None
assert resolved.task_no == "SN-CONV-MULTI-1" assert resolved.task_no == "OT-CONV-MULTI-1"
def test_task_can_handle_only_creator(app): def test_task_can_handle_only_creator(app):
@@ -252,24 +312,13 @@ def test_get_task_for_user_rejects_null_owner(app):
get_task_visible_to_user, get_task_visible_to_user,
) )
orphan = ShippingNotice( owned = ShippingOrderTask(task_no="OT-OWNED", user_id=7, source_type="direct_pdf")
task_no="SN-NULL-OWNER", db.session.add(owned)
source_type="manual",
user_id=None,
)
owned = ShippingNotice(
task_no="SN-OWNED",
source_type="manual",
user_id=7,
)
db.session.add_all([orphan, owned])
db.session.commit() db.session.commit()
assert get_task_for_user("SN-NULL-OWNER", 7) is None assert get_task_for_user("OT-OWNED", 7) is not None
assert get_task_for_user("SN-OWNED", 7) is not None assert get_task_for_user("OT-OWNED", 8) is None
assert get_task_for_user("SN-OWNED", 8) is None assert get_task_visible_to_user("OT-OWNED", 8, is_admin=True) is not None
assert get_task_visible_to_user("SN-OWNED", 8, is_admin=True) is not None
assert get_task_visible_to_user("SN-NULL-OWNER", 7, is_admin=True) is not None
def test_serialize_task_summary_enriches_todo_and_can_handle(app): def test_serialize_task_summary_enriches_todo_and_can_handle(app):
@@ -278,24 +327,21 @@ def test_serialize_task_summary_enriches_todo_and_can_handle(app):
from app import db from app import db
from app.services.shipping_notice.query_service import serialize_task_summary from app.services.shipping_notice.query_service import serialize_task_summary
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-ENRICH-1", task_no="OT-ENRICH-1", user_id=11,
review_status="parse_review", stage="parse_review",
pending_human_reason="low_confidence", pending_human_reason="low_confidence",
source_type="manual", source_type="direct_pdf",
user_id=11,
export_file_name="a.xlsx",
export_file_path="/tmp/a.xlsx",
) )
db.session.add(task) db.session.add(task)
db.session.commit() db.session.commit()
data = serialize_task_summary(task, viewer_user_id=11) data = serialize_task_summary(task, viewer_user_id=11)
assert data["todo_category"] == "review" assert data["todo_category"] == "in_progress"
assert data["created_by"] == 11 assert data["created_by"] == 11
assert data["can_handle"] is True assert data["can_handle"] is True
assert data["ui_state"]["checkpoint"]["code"] == "parse_review" assert data["ui_state"]["checkpoint"]["code"] == "order_freeze"
assert data["artifact_summary"]["export_file_name"] == "a.xlsx" assert data["artifact_summary"] is None
no_viewer = serialize_task_summary(task) no_viewer = serialize_task_summary(task)
assert "can_handle" not in no_viewer assert "can_handle" not in no_viewer
@@ -305,28 +351,58 @@ def test_serialize_task_summary_projects_only_current_notice_line_facts(app):
"""同 PO 的多个 business_no 必须各自投影本通知的项次、料号、数量和库存。""" """同 PO 的多个 business_no 必须各自投影本通知的项次、料号、数量和库存。"""
with app.app_context(): with app.app_context():
from app import db from app import db
from app.models import ShippingNoticeLine, ShippingNoticeLineInventoryMatch from app.models import (
ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask,
)
from app.services.shipping_notice.query_service import serialize_task_summary from app.services.shipping_notice.query_service import serialize_task_summary
first = ShippingNotice(task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11) first_task = ShippingOrderTask(task_no='OT-NOTICE-1', user_id=11)
second = ShippingNotice(task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11) second_task = ShippingOrderTask(task_no='OT-NOTICE-2', user_id=11)
db.session.add_all([first_task, second_task]); db.session.flush()
first_snapshot = ShippingOrderSnapshot(
task_id=first_task.id, extraction_id=1, schema_version_id=1,
order_data_version=1, header_values_json={},
)
second_snapshot = ShippingOrderSnapshot(
task_id=second_task.id, extraction_id=2, schema_version_id=1,
order_data_version=1, header_values_json={},
)
db.session.add_all([first_snapshot, second_snapshot]); db.session.flush()
first_snapshot_line = ShippingOrderSnapshotLine(
snapshot_id=first_snapshot.id, position=0, line_no=1, field_values_json={},
)
second_snapshot_line = ShippingOrderSnapshotLine(
snapshot_id=second_snapshot.id, position=0, line_no=1, field_values_json={},
)
db.session.add_all([first_snapshot_line, second_snapshot_line]); db.session.flush()
first = ShippingNotice(
task_no='SN-NOTICE-1', business_no='WVC26082301', source_type='manual', user_id=11,
order_task_id=first_task.id,
)
second = ShippingNotice(
task_no='SN-NOTICE-2', business_no='WVC26082302', source_type='manual', user_id=11,
order_task_id=second_task.id,
)
first_task.order_snapshot_id = first_snapshot.id
second_task.order_snapshot_id = second_snapshot.id
db.session.add_all([first, second]); db.session.flush() db.session.add_all([first, second]); db.session.flush()
db.session.add_all([ db.session.add_all([
ShippingNoticeLine( ShippingNoticeLine(
notice_id=first.id, position=1, line_key='LINE-1', part_number='PART-FIRST', notice_id=first.id, snapshot_line_id=first_snapshot_line.id, position=1, line_no=1,
reservation_id='RES-1', required_qty='12', field_values_json={'line_no': '00010'}, part_number='PART-FIRST', reservation_id='RES-1', required_qty='12', field_values_json={},
), ),
ShippingNoticeLine( ShippingNoticeLine(
notice_id=second.id, position=1, line_key='LINE-2', part_number='PART-SECOND', notice_id=second.id, snapshot_line_id=second_snapshot_line.id, position=1, line_no=1,
reservation_id='RES-2', required_qty='8', field_values_json={'line_no': '00020'}, part_number='PART-SECOND', reservation_id='RES-2', required_qty='8', field_values_json={},
), ),
ShippingNoticeLineInventoryMatch( ShippingNoticeLineInventoryMatch(
task_id=first.id, line_key='LINE-1', match_result='matched', inventory_status='ready', task_id=first_task.id, snapshot_line_id=first_snapshot_line.id, line_no=1,
available_qty='20', shortage_qty='0', is_current=True, match_result='matched', inventory_status='ready', available_qty='20', shortage_qty='0', is_current=True,
), ),
ShippingNoticeLineInventoryMatch( ShippingNoticeLineInventoryMatch(
task_id=second.id, line_key='LINE-2', match_result='matched', inventory_status='ready', task_id=second_task.id, snapshot_line_id=second_snapshot_line.id, line_no=1,
available_qty='9', shortage_qty='0', is_current=True, match_result='matched', inventory_status='ready', available_qty='9', shortage_qty='0', is_current=True,
), ),
]) ])
db.session.commit() db.session.commit()
@@ -335,7 +411,7 @@ def test_serialize_task_summary_projects_only_current_notice_line_facts(app):
assert data['business_no'] == 'WVC26082301' assert data['business_no'] == 'WVC26082301'
assert data['notice_line_summary'] == [{ assert data['notice_line_summary'] == [{
'line_no': '00010', 'line_no_source': 'field', 'part_number': 'PART-FIRST', 'line_no': 1, 'part_number': 'PART-FIRST',
'customer_part_number': None, 'customer_part_number': None,
'reservation_id': 'RES-1', 'shipment_qty': '12.00000000', 'available_qty': '20', 'reservation_id': 'RES-1', 'shipment_qty': '12.00000000', 'available_qty': '20',
'shortage_qty': '0', 'inventory_status': 'ready', 'shortage_qty': '0', 'inventory_status': 'ready',
@@ -358,8 +434,8 @@ def test_freight_notice_groups_split_same_po_by_business_no_and_owner(app):
other = with_po('SN-GROUP-4', 'WYC26082499', 99) other = with_po('SN-GROUP-4', 'WYC26082499', 99)
db.session.add_all([first, second, no_business, other]); db.session.flush() db.session.add_all([first, second, no_business, other]); db.session.flush()
db.session.add_all([ db.session.add_all([
ShippingNoticeLine(notice_id=first.id, position=1, line_key='G1', part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={'line_no': '00010'}), ShippingNoticeLine(notice_id=first.id, snapshot_line_id=1, position=1, line_no=1, part_number='PART-A', reservation_id='R1', required_qty='2', field_values_json={}),
ShippingNoticeLine(notice_id=second.id, position=1, line_key='G2', part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={'line_no': '00020'}), ShippingNoticeLine(notice_id=second.id, snapshot_line_id=2, position=1, line_no=1, part_number='PART-B', reservation_id='R2', required_qty='3', field_values_json={}),
]) ])
db.session.commit() db.session.commit()
@@ -387,9 +463,6 @@ def test_freight_notice_groups_exposes_per_notice_upload_error(app):
first = ShippingNotice(task_no='SN-GROUP-ERR-1', business_no='WYC26082401', source_type='manual', user_id=11) first = ShippingNotice(task_no='SN-GROUP-ERR-1', business_no='WYC26082401', source_type='manual', user_id=11)
db.session.add(first); db.session.flush() db.session.add(first); db.session.flush()
first.upload_status = 'failed'
first.upload_error_code = 'RPA_UPLOAD_FAILED'
first.upload_error_message = '货代平台拒绝:凭证无效'
db.session.commit() db.session.commit()
original_header_reader = query_service.current_header_field_values_or_empty original_header_reader = query_service.current_header_field_values_or_empty
@@ -401,9 +474,10 @@ def test_freight_notice_groups_exposes_per_notice_upload_error(app):
item = result['items'][0] item = result['items'][0]
assert item['business_no'] == 'WYC26082401' assert item['business_no'] == 'WYC26082401'
assert item['upload_status'] == 'failed' # 没有 UploadAttempt 就没有上传结果,Notice 历史投影不再作为事实来源。
assert item['upload_error_code'] == 'RPA_UPLOAD_FAILED' assert item['upload_status'] is None
assert item['upload_error_message'] == '货代平台拒绝:凭证无效' assert item['upload_error_code'] is None
assert item['upload_error_message'] is None
def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projection_is_unavailable(app): def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projection_is_unavailable(app):
@@ -413,20 +487,23 @@ def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projecti
from app.models import ShippingOrderSnapshot from app.models import ShippingOrderSnapshot
from app.services.shipping_notice import query_service from app.services.shipping_notice import query_service
first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11) first_task = ShippingOrderTask(task_no='OT-GROUP-SNAPSHOT-1', user_id=11, source_type='direct_pdf')
second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11) second_task = ShippingOrderTask(task_no='OT-GROUP-SNAPSHOT-2', user_id=11, source_type='direct_pdf')
db.session.add_all([first_task, second_task]); db.session.flush()
first = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-1', business_no='WYC26082411', source_type='manual', user_id=11, order_task_id=first_task.id)
second = ShippingNotice(task_no='SN-GROUP-SNAPSHOT-2', business_no='WYC26082412', source_type='manual', user_id=11, order_task_id=second_task.id)
db.session.add_all([first, second]); db.session.flush() db.session.add_all([first, second]); db.session.flush()
for task in (first, second): for task, owner in ((first, first_task), (second, second_task)):
snapshot = ShippingOrderSnapshot( snapshot = ShippingOrderSnapshot(
task_id=task.id, task_id=owner.id,
extraction_id=task.id, extraction_id=owner.id,
schema_version_id=1, schema_version_id=1,
order_data_version=1, order_data_version=1,
header_values_json={}, header_values_json={},
customer_po_number='ZNB-16754796', customer_po_number='ZNB-16754796',
) )
db.session.add(snapshot); db.session.flush() db.session.add(snapshot); db.session.flush()
task.order_snapshot_id = snapshot.id owner.order_snapshot_id = snapshot.id
db.session.commit() db.session.commit()
original_header_reader = query_service.current_header_field_values_or_empty original_header_reader = query_service.current_header_field_values_or_empty
@@ -504,46 +581,86 @@ def test_freight_notice_groups_upload_mode_reads_attempt_not_stale_column(app):
def test_list_my_todos_and_count_buckets(app): def test_list_my_todos_and_count_buckets(app):
"""list_my_todos 按 bucket 分类;count 徽标与 pending 一致。""" """待办按 OT 复核事实和 Notice 上传事实分类;count 徽标与 pending 一致。"""
with app.app_context(): with app.app_context():
from app import db from app import db
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
owner = 55 owner = 55
review = ShippingNotice( review = ShippingOrderTask(
task_no="SN-TODO-REVIEW", task_no="OT-TODO-REVIEW",
review_status="parse_review", pending_human_reason="rpa_exhausted",
pending_human_reason="low_confidence", source_type="direct_pdf",
source_type="manual",
user_id=owner, user_id=owner,
) )
upload_order = ShippingOrderTask(
task_no="OT-TODO-UPLOAD", source_type="direct_pdf", user_id=owner,
)
done_order = ShippingOrderTask(
task_no="OT-TODO-DONE", source_type="direct_pdf", user_id=owner,
)
upload = ShippingNotice( upload = ShippingNotice(
task_no="SN-TODO-UPLOAD", task_no="SN-TODO-UPLOAD",
source_type="manual", source_type="manual",
user_id=owner, user_id=owner,
export_file_path="/tmp/u.xlsx",
export_file_name="u.xlsx",
) )
done = ShippingNotice( done = ShippingNotice(
task_no="SN-TODO-DONE", task_no="SN-TODO-DONE",
source_type="manual", source_type="manual",
user_id=owner, user_id=owner,
upload_status="uploaded",
) )
other = ShippingNotice( other = ShippingOrderTask(
task_no="SN-TODO-OTHER", task_no="OT-TODO-OTHER",
review_status="parse_review", pending_human_reason="rpa_exhausted",
pending_human_reason="low_confidence", source_type="direct_pdf",
source_type="manual",
user_id=99, user_id=99,
) )
db.session.add_all([review, upload, done, other]) db.session.add_all([review, upload_order, done_order, upload, done, other])
template = ShippingExcelTemplate(
template_code='TODO', display_name='Todo', version=1, status='published',
storage_bucket='test', storage_key='todo.xlsx', original_filename='todo.xlsx',
file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='TODO', display_name='Todo', version=1, status='published',
file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='TODO', display_name='Todo')
db.session.add_all([template, profile, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status='published', definition_json={},
)
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(
schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
)
db.session.add(extraction)
db.session.flush()
upload.order_task_id = upload_order.id
done.order_task_id = done_order.id
def add_artifact(notice, *, artifact_no: str, status: str) -> ShippingExportArtifact:
"""为 Notice 建立待办分类所需的最小正式 Excel Artifact。"""
artifact = ShippingExportArtifact(
artifact_no=artifact_no, task_id=notice.id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
file_checksum='d' * 64, file_size=1, status=status,
)
db.session.add(artifact)
return artifact
upload_artifact = add_artifact(upload, artifact_no='ART-TODO-UPLOAD', status='ready')
done_artifact = add_artifact(done, artifact_no='ART-TODO-DONE', status='uploaded')
db.session.flush()
db.session.commit() db.session.commit()
pending = list_my_todos(owner, bucket="pending", page=1, page_size=20) pending = list_my_todos(owner, bucket="pending", page=1, page_size=20)
assert pending["total"] == 2 assert pending["total"] == 2
assert {item["task_no"] for item in pending["items"]} == { assert {item["task_no"] for item in pending["items"]} == {
"SN-TODO-REVIEW", "OT-TODO-REVIEW",
"SN-TODO-UPLOAD", "SN-TODO-UPLOAD",
} }
assert all(item["can_handle"] is True for item in pending["items"]) assert all(item["can_handle"] is True for item in pending["items"])
@@ -560,7 +677,7 @@ def test_list_my_todos_and_count_buckets(app):
admin_pending = list_my_todos(owner, bucket="pending", is_admin=True) admin_pending = list_my_todos(owner, bucket="pending", is_admin=True)
assert admin_pending["total"] >= 3 assert admin_pending["total"] >= 3
other_item = next( other_item = next(
item for item in admin_pending["items"] if item["task_no"] == "SN-TODO-OTHER" item for item in admin_pending["items"] if item["task_no"] == "OT-TODO-OTHER"
) )
assert other_item["can_handle"] is False assert other_item["can_handle"] is False
@@ -661,6 +778,75 @@ def test_list_my_todos_only_returns_stream_current_case_when_legacy_case_is_stil
assert original.case_no not in review_case_nos assert original.case_no not in review_case_nos
def test_reparse_document_with_reviewable_candidate_stays_order_review(app):
"""
回归 doc67:重解析(reparse_of_run_id 非空)终态切换未跑时,Stream.current_case
仍是空的旧 Case(candidate_id=None),但同 Document 已存在当前可复核 Candidate。
此时工作台必须显示「订单复核」,不能被空的旧 Case 压回「接收解析」。
"""
with app.app_context():
from app import db
from app.models import ShippingOrderCandidate
from app.services.shipping_notice.order_extraction_plan import (
ensure_order_extraction_plan,
)
from app.services.shipping_notice.order_extraction_run_service import (
transition_order_extraction_run,
)
from app.services.shipping_notice.order_review_disposition_service import (
reparse_case_document,
)
from app.services.shipping_notice.order_review_service import (
ensure_run_review_cases,
)
from app.services.shipping_notice.query_service import list_my_todos
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='DOC67-REPARSE')
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
# 初始解析:无 Candidate 的 Case 成为当前版本(case14 空旧 Case 语义)。
original = ensure_run_review_cases(run=source)[0]
assert original.candidate_id is None
transition_order_extraction_run(source, target_status='processing')
transition_order_extraction_run(source, target_status='review_required', result={})
replacement_run, _ = reparse_case_document(
user_id=user.id, case_no=original.case_no, reason='rule_updated',
)
ensure_order_extraction_plan(replacement_run)
# 重解析 Run 产生当前可复核 Candidate(candidate13 语义);finalizer 未切换当前 Case。
db.session.add(ShippingOrderCandidate(
candidate_no='CAND-DOC67',
intake_id=int(intake.id),
primary_document_id=document.id,
candidate_key='doc67-reparse',
order_extraction_run_id=replacement_run.id,
))
db.session.commit()
for unit in replacement_run.extraction_plan.units:
unit.status = 'candidate_ready'
db.session.commit()
replacement = ensure_run_review_cases(run=replacement_run)[0]
# 关键:不调用 activate_review_case,模拟重解析终态切换未跑 → case19 未成为当前。
assert replacement.candidate_id is not None
assert replacement.case_no != original.case_no
pending = list_my_todos(user.id, bucket='pending', page=1, page_size=50)
review_case_nos = {
item['review_case_no']
for item in pending['items']
if item.get('item_kind') == 'review_case'
}
# 当前 Case 仍是空的旧 Case;同 Document 已有可复核 Candidate → 必须订单复核。
assert original.case_no in review_case_nos
hit = next(item for item in pending['items'] if item.get('review_case_no') == original.case_no)
assert hit['ui_state']['lifecycle_stage'] == 'order_review'
assert [entry['state'] for entry in hit['ui_state']['lifecycle_entries']] == [
'available', 'current', 'unavailable', 'unavailable', 'unavailable',
]
def test_open_review_case_without_current_candidate_enters_intake_parse(app): def test_open_review_case_without_current_candidate_enters_intake_parse(app):
"""无当前 Candidate 的开放 Case 仅授权接收解析入口,不授权订单复核。""" """无当前 Candidate 的开放 Case 仅授权接收解析入口,不授权订单复核。"""
with app.app_context(): with app.app_context():
@@ -793,11 +979,10 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app):
# 520 > 旧 limit(500),用于证明截断不再作为 total 来源。 # 520 > 旧 limit(500),用于证明截断不再作为 total 来源。
total_tasks = 520 total_tasks = 520
tasks = [ tasks = [
ShippingNotice( ShippingOrderTask(
task_no=f"SN-TODO-PAGE-{index:04d}", task_no=f"OT-TODO-PAGE-{index:04d}",
review_status="parse_review", pending_human_reason="rpa_exhausted",
pending_human_reason="low_confidence", source_type="direct_pdf",
source_type="manual",
user_id=owner, user_id=owner,
) )
for index in range(total_tasks) for index in range(total_tasks)
@@ -823,79 +1008,74 @@ def test_list_my_todos_total_and_high_page_are_not_capped(app):
assert far["items"] == [] assert far["items"] == []
def test_todo_category_lightweight_matches_orm_and_count(app): def test_todo_category_sql_matches_formal_notice_facts(app):
""" """
轻量行分类 / SQL CASE 与 ORM task_todo_category 一致;count 徽标与 list total 同源。 轻量行分类 / SQL CASE 与 ORM task_todo_category 一致;count 徽标与 list total 同源。
断言意图:UNION 分页下推的 SQL 分类不得漂移口径。 断言意图:UNION 分页下推的 SQL 分类不得漂移口径。
""" """
with app.app_context(): with app.app_context():
from types import SimpleNamespace
from app import db from app import db
from app.services.shipping_notice.query_service import ( from app.services.shipping_notice.query_service import (
_task_todo_category_sql_expr, _task_todo_category_sql_expr,
_todo_category_from_task_row,
count_my_todos, count_my_todos,
list_my_todos, list_my_todos,
task_todo_category, task_todo_category,
) )
owner = 88 owner = 88
fixtures = [ order_tasks = [
ShippingNotice( ShippingOrderTask(task_no=f"OT-LW-{key}", source_type="direct_pdf", user_id=owner)
task_no="SN-LW-REVIEW", for key in ('UPLOAD', 'DONE')
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
user_id=owner,
),
ShippingNotice(
task_no="SN-LW-UPLOAD",
source_type="manual",
user_id=owner,
export_file_path="/tmp/lw.xlsx",
export_file_name="lw.xlsx",
),
ShippingNotice(
task_no="SN-LW-SHORTAGE",
# 不可用 matched:状态机会先落到 ready_export,遮住 shortage 人审分支。
review_status="shortage_review",
pending_human_reason="shortage",
source_type="manual",
user_id=owner,
),
ShippingNotice(
task_no="SN-LW-DONE",
upload_status="uploaded",
source_type="manual",
user_id=owner,
),
ShippingNotice(
task_no="SN-LW-PROGRESS",
source_type="manual",
user_id=owner,
),
] ]
db.session.add_all(fixtures) fixtures = [
ShippingNotice(task_no="SN-LW-UPLOAD", source_type="manual", user_id=owner),
ShippingNotice(task_no="SN-LW-DONE", source_type="manual", user_id=owner),
ShippingNotice(task_no="SN-LW-PROGRESS", source_type="manual", user_id=owner),
]
db.session.add_all([*order_tasks, *fixtures])
db.session.flush()
fixtures[0].order_task_id = order_tasks[0].id
fixtures[1].order_task_id = order_tasks[1].id
template = ShippingExcelTemplate(
template_code='LW', display_name='LW', version=1, status='published', storage_bucket='test',
storage_key='lw.xlsx', original_filename='lw.xlsx', file_checksum='a' * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='LW', display_name='LW', version=1, status='published', file_format='xlsx', definition_json={},
)
schema = ShippingOrderSchema(schema_code='LW', display_name='LW')
db.session.add_all([template, profile, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted')
db.session.add(extraction)
db.session.flush()
def add_artifact(notice, artifact_no, status):
artifact = ShippingExportArtifact(
artifact_no=artifact_no, task_id=notice.id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum='c' * 64,
file_path=f'/tmp/{artifact_no}.xlsx', file_name=f'{artifact_no}.xlsx',
file_checksum='d' * 64, file_size=1, status=status,
)
db.session.add(artifact)
return artifact
done_artifact = add_artifact(fixtures[1], 'ART-LW-DONE', 'uploaded')
add_artifact(fixtures[0], 'ART-LW-UPLOAD', 'ready')
db.session.flush()
db.session.add(ShippingUploadAttempt(
artifact_id=done_artifact.id, attempt_no=1, mode='manual', status='succeeded',
idempotency_key='lw-done-upload',
))
db.session.commit() db.session.commit()
category_expr = _task_todo_category_sql_expr() category_expr = _task_todo_category_sql_expr()
for task in fixtures: for task in fixtures:
row = SimpleNamespace(
review_status=task.review_status,
pending_human_reason=task.pending_human_reason,
customer_resolution_status=task.customer_resolution_status,
order_snapshot_id=task.order_snapshot_id,
current_order_extraction_id=task.current_order_extraction_id,
inventory_lines_json=task.inventory_lines_json,
match_status=task.match_status,
export_file_path=task.export_file_path,
upload_status=task.upload_status,
)
expected = task_todo_category(task) expected = task_todo_category(task)
# 轻量路径与 ORM 路径同分类。
assert _todo_category_from_task_row(row, extractions_with_lines=set()) == expected
# SQL CASE 与 ORM 路径同分类,保证 UNION 过滤不漂移。 # SQL CASE 与 ORM 路径同分类,保证 UNION 过滤不漂移。
sql_category = ( sql_category = (
db.session.query(category_expr) db.session.query(category_expr)
@@ -905,12 +1085,12 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
assert sql_category == expected assert sql_category == expected
pending = list_my_todos(owner, bucket="pending", page=1, page_size=50) pending = list_my_todos(owner, bucket="pending", page=1, page_size=50)
assert pending["total"] == 3 assert pending["total"] == 1
counts = count_my_todos(owner) counts = count_my_todos(owner)
assert counts["pending"] == 3 assert counts["pending"] == 1
assert counts["done"] == 1 assert counts["done"] == 1
assert counts["processing"] == 1 assert counts["processing"] == 1
assert counts["total_pending_badge"] == 3 assert counts["total_pending_badge"] == 1
def test_serialize_task_detail_workbench_view_drops_editor_fields(app): def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
@@ -919,9 +1099,8 @@ def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
from app import db from app import db
from app.services.shipping_notice.query_service import serialize_task_detail from app.services.shipping_notice.query_service import serialize_task_detail
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-WORKBENCH-VIEW", source_type="manual", user_id=11, task_no="OT-WORKBENCH-VIEW", source_type="direct_pdf", user_id=11,
export_file_name="n.xlsx", export_file_path="/tmp/n.xlsx",
) )
db.session.add(task) db.session.add(task)
db.session.commit() db.session.commit()
@@ -934,13 +1113,12 @@ def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
# full 保留编辑器重字段;workbench 剔除它们,显著缩小响应体。 # full 保留编辑器重字段;workbench 剔除它们,显著缩小响应体。
for key in ( for key in (
"lines", "order_header", "order_header_fields", "order_line_fields", "lines", "order_header", "order_header_fields", "order_line_fields",
"events", "field_conflicts",
): ):
assert key in full assert key in full
assert key not in wb assert key not in wb
# workbench 仍保留工作台所需字段(ui_state/stage_context、产物、行摘要)。 # workbench 仍保留工作台所需字段(ui_state/stage_context、产物、行摘要)。
assert wb["ui_state"]["task_no"] == "SN-WORKBENCH-VIEW" assert wb["ui_state"]["task_no"] == "OT-WORKBENCH-VIEW"
assert wb["ui_state"]["stage_context"] is not None assert wb["ui_state"]["stage_context"] is not None
assert wb["artifact_summary"]["export_file_name"] == "n.xlsx" assert wb["artifact_summary"] is None
assert "notice_line_summary" in wb assert "notice_line_summary" in wb
assert "export_artifacts" in wb assert "export_artifacts" not in wb
@@ -56,6 +56,24 @@ def test_reservation_contract_only_accepts_five_or_ten_digits():
assert not is_valid_reservation_id("12345678901", numeric_only=True) assert not is_valid_reservation_id("12345678901", numeric_only=True)
def test_validated_reservation_id_strips_optional_parenthesized_note():
"""完整数字可带括号备注;括号内容不是预约单号,普通尾随文本仍拒绝。"""
assert validated_reservation_id("3000112934(PENROSE)") == "3000112934"
assert validated_reservation_id("3000112934(PENROSE)") == "3000112934"
assert validated_reservation_id("R2 @3000112934") == "3000112934"
assert validated_reservation_id("R2 @3000112934(PENROSE)") == "3000112934"
assert validated_reservation_id("R2 @3000112934 PENROSE") == ""
assert validated_reservation_id("3000112934 PENROSE") == ""
assert validated_reservation_id("abc3000112934(PENROSE)") == ""
assert validated_reservation_id("00011293") == ""
assert validated_reservation_id("30001129345") == ""
def test_validated_reservation_id_rejects_amount_text_as_numeric_token():
"""金额行中的五位整数片段不能被当成 Reservation ID。"""
assert validated_reservation_id("941.76 28,252.80") == ""
def test_reservation_region_maps_line_when_reservation_label_and_line_number_are_present(): def test_reservation_region_maps_line_when_reservation_label_and_line_number_are_present():
"""专用区域只在同一行有 Reservation 语义时提取,并将可靠行号交给正式解析链路。""" """专用区域只在同一行有 Reservation 语义时提取,并将可靠行号交给正式解析链路。"""
assert extract_reservation_from_region_text("Reservation#3000098851 for line#1") == [{ assert extract_reservation_from_region_text("Reservation#3000098851 for line#1") == [{
@@ -8,15 +8,22 @@ tests/test_shipping_notice_state_machine.py
from types import SimpleNamespace from types import SimpleNamespace
from app.models import ShippingNotice from app.models import ShippingOrderTask
from app.services.shipping_notice.constants import ( from app.services.shipping_notice.constants import (
CP_EXPORT_READY, CP_EXPORT_READY,
CP_PARSE_REVIEW, CP_PARSE_REVIEW,
CP_READY_EXPORT,
CP_UPLOADED, CP_UPLOADED,
PH_LOW_CONF, PH_LOW_CONF,
RS_PARSE_REVIEW, RS_PARSE_REVIEW,
) )
from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for, resolve_task_ui_state, validate_registry from app.services.shipping_notice.state_machine import (
CheckpointKind,
checkpoint_kind_for,
resolve_task_ui_state,
resolve_task_ui_state_from_fields,
validate_registry,
)
def test_validate_registry_has_no_errors() -> None: def test_validate_registry_has_no_errors() -> None:
@@ -34,13 +41,21 @@ def test_checkpoint_kinds_for_stp_stop_points() -> None:
def test_resolve_task_ui_state_parse_review(app) -> None: def test_resolve_task_ui_state_parse_review(app) -> None:
"""pending_review + parse_review 应映射为 must_human / parse_review。""" """pending_review + parse_review 应映射为 must_human / parse_review。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-SM-PARSE", task_no="OT-SM-PARSE",
user_id=1,
review_status=RS_PARSE_REVIEW, review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF, pending_human_reason=PH_LOW_CONF,
source_type="manual",
) )
ui = resolve_task_ui_state(task) ui = resolve_task_ui_state_from_fields(
review_status=task.review_status,
pending_human_reason=task.pending_human_reason,
customer_resolution_status=None,
order_snapshot_id=None,
match_status=None,
export_file_path=None,
has_dynamic_order_lines=False,
)
assert ui.checkpoint == CP_PARSE_REVIEW assert ui.checkpoint == CP_PARSE_REVIEW
assert ui.checkpoint_kind == CheckpointKind.MUST_HUMAN assert ui.checkpoint_kind == CheckpointKind.MUST_HUMAN
@@ -48,32 +63,44 @@ def test_resolve_task_ui_state_parse_review(app) -> None:
def test_resolve_task_ui_state_export_ready(app) -> None: def test_resolve_task_ui_state_export_ready(app) -> None:
"""matched 且已有 export_file_path 应为 wait_manual_upload(待人工上传登记)。""" """matched 且已有 export_file_path 应为 wait_manual_upload(待人工上传登记)。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( ui = resolve_task_ui_state_from_fields(
task_no="SN-SM-EXPORT", review_status=None,
source_type="manual", pending_human_reason=None,
customer_resolution_status=None,
order_snapshot_id=1,
match_status=None,
export_file_path="/tmp/shipping-export.xlsx", export_file_path="/tmp/shipping-export.xlsx",
export_file_name="shipping-export.xlsx", has_dynamic_order_lines=False,
) )
ui = resolve_task_ui_state(task)
assert ui.checkpoint == CP_EXPORT_READY assert ui.checkpoint == CP_EXPORT_READY
assert ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD assert ui.checkpoint_kind == CheckpointKind.WAIT_MANUAL_UPLOAD
assert not hasattr(ui, 'human_options') assert not hasattr(ui, 'human_options')
def test_resolve_task_ui_state_uploaded_complete(app) -> None: def test_resolve_task_ui_state_uploaded_complete(app, monkeypatch) -> None:
"""upload_status=uploaded 应为 complete。""" """upload_status=uploaded 应为 complete。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = SimpleNamespace(upload_status="uploaded", lifecycle_status="active")
task_no="SN-SM-UPLOADED", # [FIX] 上传完成由可审计事实 has_verified_upload_success 裁决,不再读取 upload_status 字段。
upload_status="uploaded", monkeypatch.setattr(
source_type="manual", 'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
lambda _task: True,
)
ui = resolve_task_ui_state_from_fields(
review_status=None,
pending_human_reason=None,
customer_resolution_status=None,
order_snapshot_id=1,
match_status=None,
export_file_path=None,
has_dynamic_order_lines=False,
upload_req_task=task,
) )
ui = resolve_task_ui_state(task)
assert ui.checkpoint == CP_UPLOADED assert ui.checkpoint == CP_UPLOADED
assert ui.checkpoint_kind == CheckpointKind.COMPLETE assert ui.checkpoint_kind == CheckpointKind.COMPLETE
def test_resolve_with_mocked_simple_namespace_attributes() -> None: def test_resolve_with_mocked_simple_namespace_attributes(monkeypatch) -> None:
"""无 DB 会话时可用简易命名空间验证 uploaded 终态分支。""" """无 DB 会话时可用简易命名空间验证 uploaded 终态分支。"""
task = SimpleNamespace( task = SimpleNamespace(
upload_status="uploaded", upload_status="uploaded",
@@ -87,6 +114,27 @@ def test_resolve_with_mocked_simple_namespace_attributes() -> None:
current_order_extraction_id=None, current_order_extraction_id=None,
step_payload_json=None, step_payload_json=None,
) )
# [FIX] 上传完成由可审计事实 has_verified_upload_success 裁决,不再读取 upload_status 字段。
monkeypatch.setattr(
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
lambda _task: True,
)
ui = resolve_task_ui_state(task) # type: ignore[arg-type] ui = resolve_task_ui_state(task) # type: ignore[arg-type]
assert ui.checkpoint_kind == CheckpointKind.COMPLETE assert ui.checkpoint_kind == CheckpointKind.COMPLETE
assert ui.checkpoint == CP_UPLOADED assert ui.checkpoint == CP_UPLOADED
def test_order_task_inventory_checkpoint_uses_structured_facts(monkeypatch) -> None:
"""OT 库存 JSON 为空时,状态机仍须按 Link/File/Match 事实进入导出准备。"""
from app.models import ShippingOrderTask
from app.services.shipping_notice import state_machine
task = ShippingOrderTask(task_no='OT-SM-STRUCTURED', user_id=1, stage='inventory_matching')
monkeypatch.setattr(state_machine, '_order_task_inventory_facts', lambda _task: {
'inventory_ready': True,
'match_complete': True,
'match_sufficient': True,
'has_shortage': False,
})
assert state_machine.resolve_task_ui_state(task).checkpoint == CP_READY_EXPORT
@@ -8,9 +8,21 @@ tests/test_shipping_notice_stp_acceptance.py
from __future__ import annotations from __future__ import annotations
from types import SimpleNamespace
import pytest import pytest
from app.models import ShippingNotice, User from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingInventoryParsingProfile,
ShippingNotice,
ShippingOrderExtraction,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderTask,
User,
)
from app.services.shipping_notice.constants import ( from app.services.shipping_notice.constants import (
CP_EXPORT_READY, CP_EXPORT_READY,
CP_PARSE_REVIEW, CP_PARSE_REVIEW,
@@ -21,7 +33,32 @@ from app.services.shipping_notice.fulfillment_workflow import try_auto_chain_aft
from app.services.shipping_notice.progress_workflow import auto_progress from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.query_service import count_my_todos, list_my_todos from app.services.shipping_notice.query_service import count_my_todos, list_my_todos
from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for from app.services.shipping_notice.state_machine import CheckpointKind, checkpoint_kind_for
from app.services.shipping_notice.ui_state import build_task_ui_state
def _seed_export_artifact_view(monkeypatch) -> None:
"""Excel 就绪事实只能由正式 Artifact 裁决:屏蔽旧 Notice 文件投影。
生产函数分别经 upload_attempt_service(state_machine.resolve_task_ui_state 本地导入)与
fulfillment_workflow(模块级 latest_export_artifact / latest_upload_attempt)读取导出产物;
两处命名空间均需桩化,避免触达真实 Artifact 表。
"""
artifact = SimpleNamespace(id=0, file_path="/tmp/stp-export.xlsx", file_name="stp-export.xlsx", status="ready")
monkeypatch.setattr(
"app.services.shipping_notice.upload_attempt_service.latest_export_artifact",
lambda _task: artifact,
)
monkeypatch.setattr(
"app.services.shipping_notice.fulfillment_workflow.latest_export_artifact",
lambda _task: artifact,
)
monkeypatch.setattr(
"app.services.shipping_notice.upload_attempt_service.latest_upload_attempt",
lambda _task: None,
)
monkeypatch.setattr(
"app.services.shipping_notice.fulfillment_workflow.latest_upload_attempt",
lambda _task: None,
)
def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None: def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None:
@@ -30,7 +67,7 @@ def test_stp_checkpoint_kind_matrix_covers_nine_scenario_stops() -> None:
assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD assert checkpoint_kind_for(CP_EXPORT_READY) == CheckpointKind.WAIT_MANUAL_UPLOAD
def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app) -> None: def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app, monkeypatch) -> None:
"""场景:Excel 已生成 → auto_progress 早停(WAIT_MANUAL_UPLOAD)且禁止 upload_to_freight。""" """场景:Excel 已生成 → auto_progress 早停(WAIT_MANUAL_UPLOAD)且禁止 upload_to_freight。"""
with app.app_context(): with app.app_context():
from app import db from app import db
@@ -38,13 +75,15 @@ def test_auto_progress_stops_at_wait_manual_upload_and_forbids_freight_rpa(app)
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
task = ShippingNotice( task = ShippingNotice(
task_no="SN-STP-WAIT-UPLOAD", task_no="SN-STP-WAIT-UPLOAD",
business_no="SN-STP-WAIT-UPLOAD",
source_type="manual", source_type="manual",
export_file_path="/tmp/stp-export.xlsx",
export_file_name="stp-export.xlsx",
) )
db.session.add(task) db.session.add(task)
db.session.commit() db.session.commit()
# Excel 是否就绪只能由 Artifact 事实裁决,不能恢复 Notice 旧文件投影。
_seed_export_artifact_view(monkeypatch)
result = auto_progress({"task_id": task.task_no, "source": "system"}) result = auto_progress({"task_id": task.task_no, "source": "system"})
assert result["status"] == "ok" assert result["status"] == "ok"
assert result.get("checkpoint") == CP_EXPORT_READY assert result.get("checkpoint") == CP_EXPORT_READY
@@ -59,11 +98,20 @@ def test_auto_progress_stops_at_must_human_parse_review(app) -> None:
from app import db from app import db
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
task = ShippingNotice( owner = ShippingOrderTask(
task_no="SN-STP-MUST-HUMAN", task_no="OT-STP-MUST-HUMAN",
user_id=1,
source_type="direct_pdf",
review_status=RS_PARSE_REVIEW, review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF, pending_human_reason=PH_LOW_CONF,
)
db.session.add(owner)
db.session.flush()
task = ShippingNotice(
task_no="SN-STP-MUST-HUMAN",
business_no="SN-STP-MUST-HUMAN",
source_type="manual", source_type="manual",
order_task_id=owner.id,
) )
db.session.add(task) db.session.add(task)
db.session.commit() db.session.commit()
@@ -83,15 +131,14 @@ def test_try_auto_chain_calls_upload_when_auto_upload_enabled(app, monkeypatch)
task = ShippingNotice( task = ShippingNotice(
task_no="SN-STP-RPA-ON", task_no="SN-STP-RPA-ON",
match_status="fulfillable",
source_type="manual", source_type="manual",
line_results_json=[{"line_status": "ok"}],
export_file_path="/tmp/already.xlsx",
export_file_name="already.xlsx",
) )
db.session.add(task) db.session.add(task)
db.session.commit() db.session.commit()
# Excel 就绪由正式 Artifact 投影裁决,且自动生成在既有 Artifact 存在时被跳过。
_seed_export_artifact_view(monkeypatch)
upload_calls: list[dict] = [] upload_calls: list[dict] = []
def _fake_upload(payload): def _fake_upload(payload):
@@ -124,15 +171,14 @@ def test_try_auto_chain_skips_upload_when_auto_upload_disabled(app, monkeypatch)
task = ShippingNotice( task = ShippingNotice(
task_no="SN-STP-NO-RPA", task_no="SN-STP-NO-RPA",
match_status="fulfillable",
source_type="manual", source_type="manual",
line_results_json=[{"line_status": "ok"}],
export_file_path="/tmp/already.xlsx",
export_file_name="already.xlsx",
) )
db.session.add(task) db.session.add(task)
db.session.commit() db.session.commit()
# Excel 就绪由正式 Artifact 投影裁决,且自动生成在既有 Artifact 存在时被跳过。
_seed_export_artifact_view(monkeypatch)
upload_calls: list[dict] = [] upload_calls: list[dict] = []
def _fake_upload(payload): def _fake_upload(payload):
@@ -158,19 +204,22 @@ def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch)
"""场景:manual_confirm 不再范围外硬拒绝;校验凭据路径可达(mock record_manual_upload)。""" """场景:manual_confirm 不再范围外硬拒绝;校验凭据路径可达(mock record_manual_upload)。"""
with app.app_context(): with app.app_context():
from app import db from app import db
from types import SimpleNamespace
owner = ShippingOrderTask(task_no="OT-STP-MANUAL-CFM", user_id=1, source_type="direct_pdf")
db.session.add(owner)
db.session.flush()
task = ShippingNotice( task = ShippingNotice(
task_no="SN-STP-MANUAL-CFM", task_no="SN-STP-MANUAL-CFM",
business_no="SN-STP-MANUAL-CFM",
source_type="manual", source_type="manual",
export_file_path="/tmp/m.xlsx", order_task_id=owner.id,
export_file_name="m.xlsx",
inventory_source_status="confirmed",
inventory_source_code="SRC1",
) )
db.session.add(task) db.session.add(task)
db.session.commit() db.session.commit()
# 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。
_seed_export_artifact_view(monkeypatch)
attempt = SimpleNamespace(id=9, artifact_id=3, operator_id=42) attempt = SimpleNamespace(id=9, artifact_id=3, operator_id=42)
monkeypatch.setattr( monkeypatch.setattr(
@@ -231,22 +280,22 @@ def test_upload_to_freight_manual_confirm_ignores_inventory_source_stability(app
""" """
with app.app_context(): with app.app_context():
from app import db from app import db
from types import SimpleNamespace
owner = ShippingOrderTask(task_no="OT-STP-MANUAL-CFM-UNSTABLE", user_id=1, source_type="direct_pdf")
db.session.add(owner)
db.session.flush()
task = ShippingNotice( task = ShippingNotice(
task_no="SN-STP-MANUAL-CFM-UNSTABLE", task_no="SN-STP-MANUAL-CFM-UNSTABLE",
business_no="SN-STP-MANUAL-CFM-UNSTABLE",
source_type="manual", source_type="manual",
export_file_path="/tmp/m.xlsx", order_task_id=owner.id,
export_file_name="m.xlsx",
inventory_source_status="resolved",
inventory_source_code="SRC1",
inventory_connector_type="crane",
inventory_source_config_version="stale-version",
inventory_routing_fingerprint="stale-fingerprint",
) )
db.session.add(task) db.session.add(task)
db.session.commit() db.session.commit()
# 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。
_seed_export_artifact_view(monkeypatch)
attempt = SimpleNamespace(id=10, artifact_id=3, operator_id=42) attempt = SimpleNamespace(id=10, artifact_id=3, operator_id=42)
# 关键:模拟库存源确实不稳定(真实 is_inventory_source_stable 返回 False)。 # 关键:模拟库存源确实不稳定(真实 is_inventory_source_stable 返回 False)。
@@ -302,19 +351,22 @@ def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, mon
"""关键断言:绑定 WorkflowItem 关闭失败须向上抛出,不得吞异常后仍返回成功。""" """关键断言:绑定 WorkflowItem 关闭失败须向上抛出,不得吞异常后仍返回成功。"""
with app.app_context(): with app.app_context():
from app import db from app import db
from types import SimpleNamespace
owner = ShippingOrderTask(task_no="OT-STP-CLOSE-FAIL", user_id=1, source_type="direct_pdf")
db.session.add(owner)
db.session.flush()
task = ShippingNotice( task = ShippingNotice(
task_no="SN-STP-CLOSE-FAIL", task_no="SN-STP-CLOSE-FAIL",
business_no="SN-STP-CLOSE-FAIL",
source_type="manual", source_type="manual",
export_file_path="/tmp/m.xlsx", order_task_id=owner.id,
export_file_name="m.xlsx",
inventory_source_status="confirmed",
inventory_source_code="SRC1",
) )
db.session.add(task) db.session.add(task)
db.session.commit() db.session.commit()
# 上传前强制「有可导出 Artifact」,由正式 Artifact 视图裁决,而非 Notice 旧文件投影。
_seed_export_artifact_view(monkeypatch)
attempt = SimpleNamespace(id=11, artifact_id=3, operator_id=42) attempt = SimpleNamespace(id=11, artifact_id=3, operator_id=42)
bound_item = SimpleNamespace(lifecycle_status="manual_upload_pending") bound_item = SimpleNamespace(lifecycle_status="manual_upload_pending")
@@ -388,28 +440,76 @@ def test_my_todos_owner_can_handle_admin_view_only(app) -> None:
db.session.add_all([owner, admin]) db.session.add_all([owner, admin])
db.session.flush() db.session.flush()
# 复核系列(mine / other)以 Notice 挂接 OT,复核事实读取 OT 字段。
mine_owner = ShippingOrderTask(
task_no="OT-STP-OWN",
user_id=owner.id,
source_type="direct_pdf",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
)
upload_owner = ShippingOrderTask(task_no="OT-STP-UPLOAD", user_id=owner.id, source_type="direct_pdf")
other_owner = ShippingOrderTask(
task_no="OT-STP-OTHER",
user_id=admin.id,
source_type="direct_pdf",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
)
db.session.add_all([mine_owner, upload_owner, other_owner])
db.session.flush()
mine = ShippingNotice( mine = ShippingNotice(
task_no="SN-STP-OWN", task_no="SN-STP-OWN",
user_id=owner.id, user_id=owner.id,
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual", source_type="manual",
order_task_id=mine_owner.id,
) )
waiting_upload = ShippingNotice( waiting_upload = ShippingNotice(
task_no="SN-STP-UPLOAD", task_no="SN-STP-UPLOAD",
user_id=owner.id, user_id=owner.id,
source_type="manual", source_type="manual",
export_file_path="/tmp/own.xlsx", order_task_id=upload_owner.id,
export_file_name="own.xlsx",
) )
other = ShippingNotice( other = ShippingNotice(
task_no="SN-STP-OTHER", task_no="SN-STP-OTHER",
user_id=admin.id, user_id=admin.id,
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
source_type="manual", source_type="manual",
order_task_id=other_owner.id,
) )
db.session.add_all([mine, waiting_upload, other]) db.session.add_all([mine, waiting_upload, other])
db.session.flush()
# manual_upload 分类必须由正式 Excel Artifact 裁决。
template = ShippingExcelTemplate(
template_code="STP_TP", display_name="STP template", version=1, status="published",
storage_bucket="test", storage_key="test/stp.xlsx", original_filename="stp.xlsx",
file_checksum="a" * 64, definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code="STP_PF", display_name="STP profile", version=1, status="published",
file_format="xlsx", definition_json={},
)
schema = ShippingOrderSchema(schema_code="STP_SCHEMA", display_name="STP schema")
db.session.add_all([template, profile, schema])
db.session.flush()
version = ShippingOrderSchemaVersion(
schema_id=schema.id, version=1, status="published", definition_json={},
)
db.session.add(version)
db.session.flush()
extraction = ShippingOrderExtraction(
schema_version_id=version.id, input_snapshot_hash="b" * 64, status="accepted",
)
db.session.add(extraction)
db.session.flush()
db.session.add(ShippingExportArtifact(
artifact_no="ART-STP-UPLOAD", task_id=waiting_upload.id, template_id=template.id,
order_schema_version_id=version.id, order_extraction_id=extraction.id,
inventory_parsing_profile_id=profile.id, input_checksum="c" * 64,
file_path="/tmp/stp-own.xlsx", file_name="stp-own.xlsx",
file_checksum="d" * 64, file_size=1, status="ready",
))
db.session.commit() db.session.commit()
pending = list_my_todos(owner.id, bucket="pending", page=1, page_size=50) pending = list_my_todos(owner.id, bucket="pending", page=1, page_size=50)
+119 -363
View File
@@ -2,7 +2,7 @@
backend/tests/test_shipping_notice_tools.py backend/tests/test_shipping_notice_tools.py
用途:验证货代 Tool API 的鉴权、解析、库存、匹配、导出、RPA 与状态契约。 用途:验证货代 Tool API 的鉴权、解析、库存、匹配、导出、RPA 与状态契约。
依赖:Flask 测试客户端、ShippingNotice/Customer、货代 workflow 测试辅助。 依赖:Flask 测试客户端、ShippingNotice/ShippingOrderTask/Customer、货代 workflow 测试辅助。
逻辑:本模块聚焦客户确认后的历史 Tool 行为;客户 Gate 的阻断与确认分支由专项测试覆盖。 逻辑:本模块聚焦客户确认后的历史 Tool 行为;客户 Gate 的阻断与确认分支由专项测试覆盖。
""" """
@@ -13,16 +13,32 @@ import pytest
from app import db from app import db
from app.models import ( from app.models import (
ChatLog, ShippingCustomer, ShippingInventoryField, ShippingInventoryRoutingRule, Agent,
ShippingInventoryFile, ShippingInventoryRoutingRuleCondition, ShippingNotice, ChatLog,
ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ChatSession,
ShippingOrderLine, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingCustomer,
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingInventoryField,
ShippingTaskEvent, ShippingTaskInventoryLink, ShippingInventoryRoutingRule,
ShippingInventoryFile,
ShippingInventoryRoutingRuleCondition,
ShippingNotice,
ShippingOrderExtraction,
ShippingOrderField,
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderSchema,
ShippingOrderSchemaVersion,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingOrderTask,
ShippingTaskEvent,
ShippingTaskInventoryLink,
User,
) )
from app.services.shipping_notice.match import match_notice_lines from app.services.shipping_notice.match import match_notice_lines
from app.services.shipping_notice.order_schema import service as order_schema_service from app.services.shipping_notice.order_schema import service as order_schema_service
from tests.conftest import inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source from tests.conftest import confirm_test_customer_resolution, inventory_xlsx_with_warehouse, seed_rpa_inventory_trigger, seed_task_inventory_source
def _tool_headers(app): def _tool_headers(app):
@@ -34,8 +50,18 @@ def _tool_headers(app):
} }
def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation_id: str, quantity: int) -> None: def _seed_test_user(*, username: str) -> int:
"""创建测试用户并返回主键,供 OT 建单与能力强令牌使用。"""
user = User(username=username, email=f"{username}@example.test", password_hash='x')
db.session.add(user)
db.session.flush()
return int(user.id)
def _attach_dynamic_order(task: ShippingOrderTask, *, part_number: str, reservation_id: str, quantity: int) -> None:
"""为库存/RPA Tool 测试创建已接受 FieldValue,避免固定任务行投影绕过订单真相门禁。""" """为库存/RPA Tool 测试创建已接受 FieldValue,避免固定任务行投影绕过订单真相门禁。"""
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
if version is None:
order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None) order_schema_service.initialize_schema({'display_name': 'Tool 动态订单'}, actor_id=None)
fields = { fields = {
code: order_schema_service.save_field( code: order_schema_service.save_field(
@@ -56,24 +82,31 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
draft['id'], {'fields': configs, 'expected_lock_version': draft['lock_version']}, actor_id=None, draft['id'], {'fields': configs, 'expected_lock_version': draft['lock_version']}, actor_id=None,
) )
published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version']) published = order_schema_service.publish(draft['id'], actor_id=None, expected_lock_version=saved['lock_version'])
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one()
field_ids = {
str(item['field_code']): str(item['field_id'])
for item in (version.definition_json or {}).get('fields') or []
}
extraction = ShippingOrderExtraction( extraction = ShippingOrderExtraction(
task_id=task.id, schema_version_id=published['id'], input_snapshot_hash='t' * 64, status='accepted', task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted',
) )
db.session.add(extraction) db.session.add(extraction)
db.session.flush() db.session.flush()
line = ShippingOrderLine(extraction_id=extraction.id, position=0) line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
db.session.add(line) db.session.add(line)
db.session.flush() db.session.flush()
values = {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity} values = {'part_number': part_number, 'reservation_id': reservation_id, 'qty': quantity}
for code, value in values.items(): for code, value in values.items():
decision = ShippingOrderFieldDecision( decision = ShippingOrderFieldDecision(
extraction_id=extraction.id, line_id=line.id, field_id=fields[code]['id'], decision_status='accepted', extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_status='accepted',
supporting_observation_ids_json=[], resolved_value_json=value, supporting_observation_ids_json=[], resolved_value_json=value,
) )
db.session.add(decision) db.session.add(decision)
db.session.flush() db.session.flush()
db.session.add(ShippingOrderFieldValue( db.session.add(ShippingOrderFieldValue(
extraction_id=extraction.id, line_id=line.id, field_id=fields[code]['id'], decision_id=decision.id, extraction_id=extraction.id, line_id=line.id, field_id=field_ids[code], decision_id=decision.id,
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None, value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
value_json=value, value_json=value,
)) ))
@@ -81,14 +114,14 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
# RPA/库存链路只消费冻结订单快照;此辅助保留动态字段测试证据的同时 # RPA/库存链路只消费冻结订单快照;此辅助保留动态字段测试证据的同时
# 建立最小履约真相,避免旧测试绕过阶段 1 门禁。 # 建立最小履约真相,避免旧测试绕过阶段 1 门禁。
snapshot = ShippingOrderSnapshot( snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=extraction.id, schema_version_id=published['id'], task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
order_data_version=task.order_data_version or 1, order_data_version=task.order_data_version or 1,
rule_versions_json={'fulfillment_policy': { rule_versions_json={'fulfillment_policy': {
'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1, 'code': 'SHIP_AVAILABLE_ROLLING_V1', 'version': 1,
'definition': {'field_bindings': [ 'definition': {'field_bindings': [
{'capability_code': 'fulfillment.part_number', 'field_id': fields['part_number']['id'], 'scope': 'line'}, {'capability_code': 'fulfillment.part_number', 'field_id': field_ids['part_number'], 'scope': 'line'},
{'capability_code': 'fulfillment.reservation_identity', 'field_id': fields['reservation_id']['id'], 'scope': 'line'}, {'capability_code': 'fulfillment.reservation_identity', 'field_id': field_ids['reservation_id'], 'scope': 'line'},
{'capability_code': 'fulfillment.quantity', 'field_id': fields['qty']['id'], 'scope': 'line'}, {'capability_code': 'fulfillment.quantity', 'field_id': field_ids['qty'], 'scope': 'line'},
]}, ]},
}}, }},
header_values_json={}, header_values_json={},
@@ -96,26 +129,41 @@ def _attach_dynamic_order(task: ShippingNotice, *, part_number: str, reservation
db.session.add(snapshot) db.session.add(snapshot)
db.session.flush() db.session.flush()
db.session.add(ShippingOrderSnapshotLine( db.session.add(ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=0, part_number=part_number, reservation_id=reservation_id, snapshot_id=snapshot.id, position=0, line_no=1, part_number=part_number, reservation_id=reservation_id,
qty=quantity, field_values_json={ qty=quantity, field_values_json={
str(fields['part_number']['id']): part_number, str(field_ids['part_number']): part_number,
str(fields['reservation_id']['id']): reservation_id, str(field_ids['reservation_id']): reservation_id,
str(fields['qty']['id']): quantity, str(field_ids['qty']): quantity,
}, },
)) ))
task.order_snapshot_id = snapshot.id task.order_snapshot_id = snapshot.id
db.session.flush() db.session.flush()
def _confirm_test_task_customer(task: ShippingOrderTask) -> None:
"""为 RPA 回调/超时链路补齐已确认客户,避免自动推进被客户门禁提前阻断。"""
customer = db.session.query(ShippingCustomer).filter_by(short_code='RPC').one_or_none()
if customer is None:
customer = ShippingCustomer(
standard_name='RPA 直接回调测试客户', short_code='RPC', status='active',
)
db.session.add(customer)
db.session.flush()
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
task._test_customer_confirmed = True
def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client): def test_shipping_notice_tool_auth_accepts_dedicated_key(app, client):
with app.app_context(): with app.app_context():
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret" app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "shipping-secret"
app.config["INTEGRATION_API_KEY"] = "" app.config["INTEGRATION_API_KEY"] = ""
user_id = _seed_test_user(username='auth-dedicated')
res = client.post( res = client.post(
"/api/shipping-notice/tools/create_task", "/api/shipping-notice/tools/create_task",
headers={"Content-Type": "application/json", "X-Integration-Key": "shipping-secret"}, headers={"Content-Type": "application/json", "X-Integration-Key": "shipping-secret"},
json={"source_type": "manual"}, json={"source_type": "direct_pdf", "user_id": user_id},
) )
assert res.status_code == 200 assert res.status_code == 200
@@ -126,11 +174,12 @@ def test_shipping_notice_tool_auth_falls_back_to_integration_key(app, client):
with app.app_context(): with app.app_context():
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "" app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = ""
app.config["INTEGRATION_API_KEY"] = "integration-secret" app.config["INTEGRATION_API_KEY"] = "integration-secret"
user_id = _seed_test_user(username='auth-integration')
res = client.post( res = client.post(
"/api/shipping-notice/tools/create_task", "/api/shipping-notice/tools/create_task",
headers={"Content-Type": "application/json", "X-Integration-Key": "integration-secret"}, headers={"Content-Type": "application/json", "X-Integration-Key": "integration-secret"},
json={"source_type": "manual"}, json={"source_type": "direct_pdf", "user_id": user_id},
) )
assert res.status_code == 200 assert res.status_code == 200
@@ -145,7 +194,7 @@ def test_shipping_notice_tool_auth_reports_missing_config(app, client):
res = client.post( res = client.post(
"/api/shipping-notice/tools/create_task", "/api/shipping-notice/tools/create_task",
headers={"Content-Type": "application/json", "X-Integration-Key": "any"}, headers={"Content-Type": "application/json", "X-Integration-Key": "any"},
json={"source_type": "manual"}, json={"source_type": "direct_pdf"},
) )
assert res.status_code == 503 assert res.status_code == 503
@@ -157,7 +206,7 @@ def test_parse_notice_tool_is_removed(app, client):
response = client.post( response = client.post(
"/api/shipping-notice/tools/parse_notice", "/api/shipping-notice/tools/parse_notice",
headers=_tool_headers(app), headers=_tool_headers(app),
json={"task_id": "SN-REMOVED"}, json={"task_id": "OT-REMOVED"},
) )
assert response.status_code == 404 assert response.status_code == 404
@@ -179,14 +228,14 @@ def test_direct_excel_tool_dispatches_to_formal_auto_progress(monkeypatch):
) )
result = fulfillment_workflow.generate_excel({ result = fulfillment_workflow.generate_excel({
'task_id': 'SN-FORMAL-EXCEL-ONLY', 'task_id': 'OT-FORMAL-EXCEL-ONLY',
'operator_id': 7, 'operator_id': 7,
'idempotency_key': 'formal-excel-only', 'idempotency_key': 'formal-excel-only',
}) })
assert result['status'] == 'running' assert result['status'] == 'running'
assert submitted == { assert submitted == {
'task_no': 'SN-FORMAL-EXCEL-ONLY', 'task_no': 'OT-FORMAL-EXCEL-ONLY',
'trigger': 'tool_api_generate_excel', 'trigger': 'tool_api_generate_excel',
'expected_version': None, 'expected_version': None,
'idempotency_key': 'formal-excel-only', 'idempotency_key': 'formal-excel-only',
@@ -222,20 +271,36 @@ def test_match_notice_lines_reports_progress():
def test_contract_get_task_status_accepts_task_no_anchor(app, client): def test_contract_get_task_status_accepts_task_no_anchor(app, client):
"""契约:用户输入 SN-... 时,Dify 应直连 get_task_status 并锚定对应任务。""" """契约:用户输入 OT-... 时,Dify 应直连 get_task_status 并锚定对应任务。"""
from app.services.shipping_notice.chat_tool_capability import issue_chat_capability
headers = _tool_headers(app) headers = _tool_headers(app)
with app.app_context():
app.config["SHIPPING_CHAT_CAPABILITY_SECRET"] = "test-capability-secret"
user_id = _seed_test_user(username='status-anchor')
agent = Agent(name='shipping-agent', agent_code='shipping_notice_status_anchor')
db.session.add(agent)
db.session.flush()
session = ChatSession(session_id='status-anchor-session', user_id=user_id, agent_id=agent.id)
db.session.add(session)
db.session.commit()
session_id = session.session_id
agent_id = int(agent.id)
create_res = client.post( create_res = client.post(
"/api/shipping-notice/tools/create_task", "/api/shipping-notice/tools/create_task",
headers=headers, headers=headers,
json={"source_type": "manual", "raw_content": "客户:ACME 料号A001 x 10"}, json={"source_type": "direct_pdf", "user_id": user_id, "conversation_id": session_id,
"raw_content": "客户:ACME 料号A001 x 10"},
) )
task_id = create_res.get_json()["task_id"] task_id = create_res.get_json()["task_id"]
token = issue_chat_capability(user_id=user_id, session_id=session_id, agent_id=agent_id, task_no=task_id)
status_res = client.post( status_res = client.post(
"/api/shipping-notice/tools/get_task_status", "/api/shipping-notice/tools/get_task_status",
headers=headers, headers=headers,
json={"task_no": task_id}, json={"task_no": task_id, "shipping_chat_capability_token": token},
) )
data = status_res.get_json() data = status_res.get_json()
@@ -273,12 +338,11 @@ def test_confirm_inventory_source_route_is_removed(app, client):
"""库存源人工确认已下线,任何旧 Tool 写入口均不得可达。""" """库存源人工确认已下线,任何旧 Tool 写入口均不得可达。"""
headers = _tool_headers(app) headers = _tool_headers(app)
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-HTTP-CONFIRM-SRC", task_no="OT-HTTP-CONFIRM-SRC",
source_type="manual", user_id=1,
source_type="eml",
pending_human_reason="inventory_source_unresolved", pending_human_reason="inventory_source_unresolved",
ship_to="Dublin",
lines_json=[{"part_number": "A001", "qty": 1, "reservation_id": "R1"}],
) )
db.session.add(task) db.session.add(task)
db.session.commit() db.session.commit()
@@ -286,7 +350,7 @@ def test_confirm_inventory_source_route_is_removed(app, client):
res = client.post( res = client.post(
"/api/shipping-notice/tools/confirm_inventory_source", "/api/shipping-notice/tools/confirm_inventory_source",
headers=headers, headers=headers,
json={"task_id": "SN-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"}, json={"task_id": "OT-HTTP-CONFIRM-SRC", "source_code": "DSV360_AWSDU"},
) )
assert res.status_code == 404 assert res.status_code == 404
@@ -304,91 +368,13 @@ def test_static_openapi_snapshot_contains_shipping_contract_keywords():
assert "match_inventory" not in spec_text assert "match_inventory" not in spec_text
@pytest.mark.parametrize("decision", ["confirm_inventory_mapping", "correct_inventory_mapping"])
def test_legacy_inventory_mapping_decisions_are_rejected(app, client, decision):
"""已启用库存站点不得通过任务决策重开旧列映射路径。"""
headers = _tool_headers(app)
with app.app_context():
task = ShippingNotice(task_no=f"SN-LEGACY-MAP-{decision}", source_type="manual")
db.session.add(task)
db.session.commit()
response = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": f"SN-LEGACY-MAP-{decision}", "decision": decision},
)
assert response.status_code == 200
body = response.get_json()
# These decisions must never reopen manual mapping or mutate the task.
assert body["status"] == "failed"
assert "已发布解析方案" in body["message"]
def test_reparse_inventory_clears_derived_state_and_deactivates_current_link(app, client, tmp_path):
"""重新上传库存只重置正式库存结果,不进入任务级字段映射。"""
headers = _tool_headers(app)
with app.app_context():
task = ShippingNotice(
task_no="SN-REUPLOAD-INVENTORY",
source_type="manual",
inventory_lines_json=[{"part_number": "A001", "available_qty": 10}],
match_status="fulfillable",
line_results_json=[{"part_number": "A001"}],
shortage_json={"lines": []},
export_file_path=str(tmp_path / "shipment.xlsx"),
export_file_name="shipment.xlsx",
)
db.session.add(task)
db.session.flush()
inventory_file = ShippingInventoryFile(
inventory_file_no="SIF-REUPLOAD-001",
storage_path=str(tmp_path / "inventory.xlsx"),
source_file_name="inventory.xlsx",
)
db.session.add(inventory_file)
db.session.flush()
link = ShippingTaskInventoryLink(
task_id=task.id,
inventory_file_id=inventory_file.id,
link_role="owner",
)
db.session.add(link)
db.session.commit()
response = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": "SN-REUPLOAD-INVENTORY", "decision": "reparse_inventory"},
)
assert response.status_code == 200
body = response.get_json()
assert body["status"] == "needs_human"
assert body["checkpoint"] == "upload_req"
assert "human_options" not in body
with app.app_context():
task = ShippingNotice.query.filter_by(task_no="SN-REUPLOAD-INVENTORY").one()
link = ShippingTaskInventoryLink.query.filter_by(task_id=task.id).one()
assert link.is_active is False
assert task.pending_human_reason == "inv_unavail"
assert task.pending_human_reason == "inv_unavail"
assert task.inventory_lines_json is None
assert task.match_status is None
assert task.line_results_json is None
assert task.shortage_json is None
assert task.export_file_path is None
assert task.export_file_name is None
def test_parse_inventory_from_chat_text_route_is_removed(app, client): def test_parse_inventory_from_chat_text_route_is_removed(app, client):
"""正式任务不再接受对话文本库存;临时库存由独立会话 Tool 处理。""" """正式任务不再接受对话文本库存;临时库存由独立会话 Tool 处理。"""
headers = _tool_headers(app) headers = _tool_headers(app)
parse_inv = client.post( parse_inv = client.post(
"/api/shipping-notice/tools/parse_inventory", "/api/shipping-notice/tools/parse_inventory",
headers=headers, headers=headers,
json={"task_id": "SN-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"}, json={"task_id": "OT-REMOVED", "raw_inventory_text": "料号\t可用数量\nA001\t10"},
) )
assert parse_inv.status_code == 404 assert parse_inv.status_code == 404
assert parse_inv.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" assert parse_inv.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
@@ -400,7 +386,7 @@ def test_parse_inventory_empty_text_route_is_removed(app, client):
res = client.post( res = client.post(
"/api/shipping-notice/tools/parse_inventory", "/api/shipping-notice/tools/parse_inventory",
headers=headers, headers=headers,
json={"task_id": "SN-REMOVED", "raw_inventory_text": " "}, json={"task_id": "OT-REMOVED", "raw_inventory_text": " "},
) )
assert res.status_code == 404 assert res.status_code == 404
assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
@@ -413,7 +399,7 @@ def test_match_by_supplier_sku_and_reservation_id(app, client):
"/api/shipping-notice/tools/parse_inventory", "/api/shipping-notice/tools/parse_inventory",
headers=headers, headers=headers,
json={ json={
"task_id": "SN-REMOVED", "task_id": "OT-REMOVED",
"raw_inventory_text": "Supplier Sku\tCOM ID\tQty Available\nA001\tR-1\t2\n", "raw_inventory_text": "Supplier Sku\tCOM ID\tQty Available\nA001\tR-1\t2\n",
}, },
) )
@@ -427,7 +413,7 @@ def test_removed_inventory_text_route_cannot_create_mapping_checkpoint(app, clie
"/api/shipping-notice/tools/parse_inventory", "/api/shipping-notice/tools/parse_inventory",
headers=headers, headers=headers,
json={ json={
"task_id": "SN-REMOVED", "task_id": "OT-REMOVED",
"raw_inventory_text": "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\nD4-A08AR12000002\t10-40594-001\tAWS-311\t1\n", "raw_inventory_text": "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\nD4-A08AR12000002\t10-40594-001\tAWS-311\t1\n",
}, },
) )
@@ -441,7 +427,7 @@ def test_removed_inventory_text_route_cannot_reopen_mapping_correction(app, clie
"/api/shipping-notice/tools/parse_inventory", "/api/shipping-notice/tools/parse_inventory",
headers=headers, headers=headers,
json={ json={
"task_id": "SN-REMOVED", "task_id": "OT-REMOVED",
"raw_inventory_text": ( "raw_inventory_text": (
"Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n" "Supplier Sku\tAWS Sku\tCOM ID\tQty Available\n"
"D4-A08AR12000002\t10-40594-001\tAWS-311\t1\n" "D4-A08AR12000002\t10-40594-001\tAWS-311\t1\n"
@@ -459,87 +445,10 @@ def test_legacy_task_inventory_mapping_routes_are_removed(app, client):
"/api/shipping-notice/tools/get_inventory_schema_preview", "/api/shipping-notice/tools/get_inventory_schema_preview",
"/api/shipping-notice/tools/apply_inventory_mapping", "/api/shipping-notice/tools/apply_inventory_mapping",
): ):
response = client.post(path, headers=headers, json={"task_id": "SN-LEGACY-REMOVED"}) response = client.post(path, headers=headers, json={"task_id": "OT-LEGACY-REMOVED"})
assert response.status_code == 404 assert response.status_code == 404
@pytest.mark.auto_rpa
def test_retry_rpa_force_refresh_clears_derived_inventory_state(app, client, tmp_path, monkeypatch):
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
lambda *args, **kwargs: None,
)
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
inventory_drop = tmp_path / "inventory_drop"
trigger.mkdir()
inventory_drop.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
task.review_status = None
task.pending_human_reason = "inv_unavail"
task.inventory_lines_json = [{"part_number": "OLD", "reservation_id": "12345", "available_qty": 3}]
task.match_status = "fulfillable"
task.shortage_json = {"lines": []}
task.line_results_json = [{"part_number": "OLD", "status": "ok"}]
task.export_file_path = str(tmp_path / "old.xlsx")
task.export_file_name = "old.xlsx"
task.upload_status = "failed"
task.upload_mode = "rpa"
task.upload_error_message = "old upload failed"
task.freight_ref_no = "OLD-REF"
task.step_payload_json = {
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"connector_type": "dsv360",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
db.session.commit()
from app.services.shipping_notice import decision_workflow
with app.app_context():
retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"})
assert retry_data["status"] == "running"
assert retry_data.get("data", {}).get("rpa_runtime", {}).get("mode") in {"browser", "mock"}
with app.app_context():
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.pending_human_reason == "rpa_pending"
assert task.pending_human_reason == "rpa_pending"
assert task.review_status is None
assert task.inventory_lines_json is None
assert task.match_status is None
assert task.shortage_json is None
assert task.line_results_json is None
assert task.export_file_path is None
assert task.export_file_name is None
assert task.upload_status is None
assert task.upload_error_message is None
assert task.freight_ref_no is None
event = ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").first()
assert event is not None
assert event.detail_json.get("force_refresh") is True
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
@pytest.mark.auto_rpa @pytest.mark.auto_rpa
def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt(app, client, tmp_path, monkeypatch): def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt(app, client, tmp_path, monkeypatch):
from datetime import datetime, timedelta from datetime import datetime, timedelta
@@ -557,17 +466,21 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
lambda: None, lambda: None,
) )
with app.app_context():
user_id = _seed_test_user(username='rpa-timeout-recheck')
create_res = client.post( create_res = client.post(
"/api/shipping-notice/tools/create_task", "/api/shipping-notice/tools/create_task",
headers=headers, headers=headers,
json={"source_type": "manual"}, json={"source_type": "direct_pdf", "user_id": user_id},
) )
task_id = create_res.get_json()["task_id"] task_id = create_res.get_json()["task_id"]
with app.app_context(): with app.app_context():
task = ShippingNotice.query.filter_by(task_no=task_id).first() task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
assert task is not None assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1) _attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
_confirm_test_task_customer(task)
task.pending_human_reason = PH_RPA_PENDING task.pending_human_reason = PH_RPA_PENDING
task.step_payload_json = { task.step_payload_json = {
"rpa_inventory_source": { "rpa_inventory_source": {
@@ -591,7 +504,7 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
with app.app_context(): with app.app_context():
result = _run_single_task(task_id) result = _run_single_task(task_id)
task = ShippingNotice.query.filter_by(task_no=task_id).first() task = ShippingOrderTask.query.filter_by(task_no=task_id).first()
assert task is not None assert task is not None
assert result["status"] == "needs_human" assert result["status"] == "needs_human"
assert task.pending_human_reason == PH_RPA_EXHAUSTED assert task.pending_human_reason == PH_RPA_EXHAUSTED
@@ -602,171 +515,13 @@ def test_rpa_pending_timeout_recheck_marks_task_needs_human_after_single_attempt
assert len(list(trigger.glob("inventory_export_*.json"))) == 0 assert len(list(trigger.glob("inventory_export_*.json"))) == 0
@pytest.mark.auto_rpa
def test_retry_rpa_after_exhausted_starts_new_attempt_window(app, client, tmp_path, monkeypatch):
monkeypatch.setattr(
"app.services.shipping_notice.inventory_rpa_workflow._try_reuse_inventory_snapshot",
lambda *args, **kwargs: None,
)
from datetime import datetime, timedelta
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
inventory_drop = tmp_path / "inventory_drop"
trigger.mkdir()
inventory_drop.mkdir()
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(inventory_drop)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
with app.app_context():
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
_attach_dynamic_order(task, part_number='A001', reservation_id='12345', quantity=1)
task.pending_human_reason = PH_RPA_EXHAUSTED
task.step_payload_json = {
"rpa_inventory_source": {
"source_code": "DSV360_AWSDU",
"connector_type": "dsv360",
"display_name": "DSV 360 / Dublin / AWSDU - Prod (JDA)",
"entry_url": "https://s360.dbschenker.com/",
"query": {"program_label": "AWSDU - Prod (JDA)", "owner_code": "CADU-0000000100"},
}
}
seed_task_inventory_source(task, source_code="DSV360_AWSDU")
base_time = datetime.utcnow() - timedelta(minutes=5)
for idx in range(3):
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type="inventory_rpa_triggered",
detail_json={"attempt": idx + 1},
created_at=base_time + timedelta(seconds=idx),
)
)
db.session.commit()
from app.services.shipping_notice import decision_workflow
with app.app_context():
retry_data = decision_workflow.submit_decision({"task_id": task_id, "decision": "retry_rpa"})
assert retry_data["status"] == "running"
assert retry_data.get("data", {}).get("rpa", {}).get("attempts") == 1
with app.app_context():
task = ShippingNotice.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.pending_human_reason == "rpa_pending"
assert task.pending_human_reason == "rpa_pending"
assert task.error_message is None
progress = (task.step_payload_json or {}).get("current_step_progress") or {}
assert progress.get("current") == 1
assert progress.get("extra", {}).get("manual_retry_round") is True
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="decision_retry_rpa").count() == 1
assert ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered").count() == 4
assert len(list(trigger.glob("inventory_export_*.json"))) == 1
def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(app, client):
headers = _tool_headers(app)
first = ShippingNotice(
task_no="SN-MULTI-CONV-001",
conversation_id="conv-test-multi",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
lines_json=[{"part_number": "A001", "reservation_id": "1000140351", "qty": 1}],
)
second = ShippingNotice(
task_no="SN-MULTI-CONV-002",
conversation_id="conv-test-multi",
review_status="parse_review",
pending_human_reason="low_confidence",
source_type="manual",
lines_json=[{"part_number": "A002", "reservation_id": "1000140352", "qty": 1}],
)
with app.app_context():
db.session.add_all([first, second])
db.session.commit()
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"conversation_id": "conv-test-multi", "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "failed"
assert "任务编号" in confirm_data["message"] or "task ID" in confirm_data["message"]
status_res = client.post(
"/api/shipping-notice/tools/get_task_status",
headers=headers,
json={"conversation_id": "conv-test-multi"},
)
status_data = status_res.get_json()
assert status_data["status"] == "failed"
assert "任务编号" in status_data["message"]
with app.app_context():
rows = {
task.task_no: task
for task in ShippingNotice.query.filter(ShippingNotice.task_no.in_(["SN-MULTI-CONV-001", "SN-MULTI-CONV-002"]))
.order_by(ShippingNotice.task_no)
.all()
}
assert rows["SN-MULTI-CONV-001"].review_status == "parse_review"
assert rows["SN-MULTI-CONV-002"].review_status == "parse_review"
def test_submit_decision_retry_rpa_routes_to_formal_gate_action(app, client, monkeypatch):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
import app.services.shipping_notice.decision_workflow as decision_workflow
captured: dict[str, object] = {}
def fake_request_formal_gate_action(**kwargs):
captured.update(kwargs)
return {"status": "running", "task_id": task_id, "message": "已提交正式 20-Gate 恢复动作"}
monkeypatch.setattr(decision_workflow, "_request_formal_gate_action", fake_request_formal_gate_action)
res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "retry_rpa", "comment": "retry now"},
)
data = res.get_json()
assert data["status"] == "running"
assert data["task_id"] == task_id
assert data["message"] == "已提交正式 20-Gate 恢复动作"
assert captured["task"].task_no == task_id
assert captured["action_code"] == "retry_inventory_preparation"
def test_parse_inventory_oversized_text_route_is_removed(app, client): def test_parse_inventory_oversized_text_route_is_removed(app, client):
"""旧正式库存文本入口无论内容大小都不可访问。""" """旧正式库存文本入口无论内容大小都不可访问。"""
headers = _tool_headers(app) headers = _tool_headers(app)
res = client.post( res = client.post(
"/api/shipping-notice/tools/parse_inventory", "/api/shipping-notice/tools/parse_inventory",
headers=headers, headers=headers,
json={"task_id": "SN-REMOVED", "raw_inventory_text": "x" * 200}, json={"task_id": "OT-REMOVED", "raw_inventory_text": "x" * 200},
) )
assert res.status_code == 404 assert res.status_code == 404
assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND" assert res.get_json()["error"]["code"] == "RESOURCE.NOT_FOUND"
@@ -776,12 +531,13 @@ def test_chat_actions_empty_when_task_rejected(app):
from app.services.shipping_notice.ui_state import build_task_ui_state from app.services.shipping_notice.ui_state import build_task_ui_state
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-20260101-TEST0001", task_no="OT-20260101-TEST0001",
source_type="manual", user_id=1,
source_type="eml",
review_status="rejected", review_status="rejected",
) )
ui_state = build_task_ui_state(task) ui_state = build_task_ui_state(task)
assert ui_state["checkpoint"]["code"] == "rejected" assert ui_state["review_status"] == "rejected"
assert ui_state["actions"] == {"primary": None, "secondary": []} assert ui_state["actions"] == {"primary": None, "secondary": []}
assert "action_buttons" not in ui_state assert "action_buttons" not in ui_state
+359 -181
View File
@@ -8,9 +8,14 @@ tests/test_shipping_notice_ui_state.py
from app import db from app import db
from app.core.auth.jwt import issue_local_access_token from app.core.auth.jwt import issue_local_access_token
from app.models import ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch, User from app.models import (
ShippingInventoryCandidateLine, ShippingInventoryCandidateSet, ShippingInventoryCandidateSource,
ShippingNotice, ShippingNoticeLine, ShippingNoticeLineInventoryMatch,
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingOrderTask, User,
)
from app.services.shipping_notice.constants import ( from app.services.shipping_notice.constants import (
CP_EXPORT_READY, CP_EXPORT_READY,
CP_ORDER_FREEZE,
CP_PARSE_REVIEW, CP_PARSE_REVIEW,
PH_LOW_CONF, PH_LOW_CONF,
RS_PARSE_REVIEW, RS_PARSE_REVIEW,
@@ -34,6 +39,43 @@ _REQUIRED_SUMMARY_KEYS = {
} }
def _frozen_task_with_line(
*,
task_no: str,
user_id: int = 1,
reservation_id: str | None = None,
part_number: str | None = None,
qty: str | None = None,
field_values_json: dict | None = None,
) -> tuple[ShippingOrderTask, ShippingOrderSnapshotLine]:
"""建立通知准备测试所需的最小 OT 冻结档与订单项次。"""
task = ShippingOrderTask(task_no=task_no, user_id=user_id, source_type='direct_pdf')
db.session.add(task)
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=task.id,
extraction_id=task.id,
schema_version_id=1,
order_data_version=1,
header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
task.order_snapshot_id = snapshot.id
line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id,
position=0,
line_no=1,
reservation_id=reservation_id,
part_number=part_number,
qty=qty,
field_values_json=field_values_json or {},
)
db.session.add(line)
db.session.flush()
return task, line
def test_unified_actions_deduplicates_gate_primary_action(): def test_unified_actions_deduplicates_gate_primary_action():
"""Gate 主动作同时出现在展示列表时,只能渲染一次。""" """Gate 主动作同时出现在展示列表时,只能渲染一次。"""
state = _unified_actions( state = _unified_actions(
@@ -95,23 +137,23 @@ def test_unified_actions_preserve_backend_surface_without_action_code_fallback()
def test_build_task_ui_state_summary_has_required_keys(app) -> None: def test_build_task_ui_state_summary_has_required_keys(app) -> None:
"""summary 必须包含 STP 可解释字段全集。""" """summary 必须包含 STP 可解释字段全集。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-UI-SUMMARY", task_no="OT-UI-SUMMARY", user_id=1,
review_status=RS_PARSE_REVIEW, review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF, pending_human_reason=PH_LOW_CONF,
source_type="manual", source_type="direct_pdf",
) )
state = build_task_ui_state(task) state = build_task_ui_state(task)
assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys()) assert set(_REQUIRED_SUMMARY_KEYS).issubset(state["summary"].keys())
assert state["checkpoint"]["code"] == CP_PARSE_REVIEW assert state["checkpoint"]["code"] == CP_ORDER_FREEZE
assert state["checkpoint_kind"] == "must_human" assert state["checkpoint_kind"] == "auto_continue"
assert "stp_facts" not in state["summary"] assert "stp_facts" not in state["summary"]
def test_task_ui_state_stage_context_is_opt_in(app) -> None: def test_task_ui_state_stage_context_is_opt_in(app) -> None:
"""列表等轻量调用默认不得加载阶段工作面详情。""" """列表等轻量调用默认不得加载阶段工作面详情。"""
with app.app_context(): with app.app_context():
task = ShippingNotice(task_no="SN-UI-LIGHTWEIGHT", source_type="manual") task = ShippingOrderTask(task_no="OT-UI-LIGHTWEIGHT", user_id=1, source_type="direct_pdf")
state = build_task_ui_state(task) state = build_task_ui_state(task)
detailed_state = build_task_ui_state(task, include_stage_context=True) detailed_state = build_task_ui_state(task, include_stage_context=True)
@@ -124,11 +166,11 @@ def test_task_ui_state_stage_context_is_opt_in(app) -> None:
def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None: def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None:
"""旧 checkpoint 不能再推导五阶段或任何可写 UI 动作。""" """旧 checkpoint 不能再推导五阶段或任何可写 UI 动作。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-UI-STAGE-ACTIONS", task_no="OT-UI-STAGE-ACTIONS", user_id=1,
review_status=RS_PARSE_REVIEW, review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF, pending_human_reason=PH_LOW_CONF,
source_type="manual", source_type="direct_pdf",
) )
state = build_task_ui_state(task) state = build_task_ui_state(task)
assert state["stage"]["code"] == "unclassified" assert state["stage"]["code"] == "unclassified"
@@ -141,11 +183,11 @@ def test_build_task_ui_state_without_formal_gate_is_unclassified(app) -> None:
def test_build_task_ui_state_without_formal_gate_has_no_lifecycle_entries(app) -> None: def test_build_task_ui_state_without_formal_gate_has_no_lifecycle_entries(app) -> None:
"""正式工作台入口必须来自 Gate,不能按旧 checkpoint 生成。""" """正式工作台入口必须来自 Gate,不能按旧 checkpoint 生成。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-UI-LIFECYCLE-ENTRIES", task_no="OT-UI-LIFECYCLE-ENTRIES", user_id=1,
review_status=RS_PARSE_REVIEW, review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF, pending_human_reason=PH_LOW_CONF,
source_type="manual", source_type="direct_pdf",
) )
state = build_task_ui_state(task) state = build_task_ui_state(task)
assert state["lifecycle_stage"] == "unclassified" assert state["lifecycle_stage"] == "unclassified"
@@ -162,7 +204,7 @@ def test_task_ui_state_ignores_superseded_process_execution(app) -> None:
user = User(username='ui-superseded-execution', email='ui-superseded@example.com', password_hash='x') user = User(username='ui-superseded-execution', email='ui-superseded@example.com', password_hash='x')
db.session.add(user) db.session.add(user)
db.session.flush() db.session.flush()
task = ShippingNotice(task_no='SN-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='manual') task = ShippingOrderTask(task_no='OT-UI-SUPERSEDED-EXEC', user_id=user.id, source_type='direct_pdf')
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system') execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system')
@@ -182,10 +224,10 @@ def test_task_ui_state_formal_gate_overrides_stale_task_fields(app) -> None:
user = User(username='ui-gate-authority', email='ui-gate-authority@example.com', password_hash='x') user = User(username='ui-gate-authority', email='ui-gate-authority@example.com', password_hash='x')
db.session.add(user) db.session.add(user)
db.session.flush() db.session.flush()
task = ShippingNotice( task = ShippingOrderTask(
task_no='SN-UI-GATE-AUTHORITY', task_no='OT-UI-GATE-AUTHORITY',
user_id=user.id, user_id=user.id,
source_type='manual', source_type='direct_pdf',
# 模拟历史字段尚未同步:旧字段仍像解析复核。 # 模拟历史字段尚未同步:旧字段仍像解析复核。
review_status=RS_PARSE_REVIEW, review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF, pending_human_reason=PH_LOW_CONF,
@@ -215,10 +257,10 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No
user = User(username='ui-upload-gate-authority', email='ui-upload-gate@example.com', password_hash='x') user = User(username='ui-upload-gate-authority', email='ui-upload-gate@example.com', password_hash='x')
db.session.add(user) db.session.add(user)
db.session.flush() db.session.flush()
task = ShippingNotice( task = ShippingOrderTask(
task_no='SN-UI-UPLOAD-GATE-AUTHORITY', task_no='OT-UI-UPLOAD-GATE-AUTHORITY',
user_id=user.id, user_id=user.id,
source_type='manual', source_type='direct_pdf',
review_status=RS_PARSE_REVIEW, review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF, pending_human_reason=PH_LOW_CONF,
) )
@@ -241,17 +283,11 @@ def test_task_ui_state_manual_upload_gate_overrides_stale_task_fields(app) -> No
def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> None: def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> None:
"""库存和上传历史字段不能再替代正式 Gate 生成生命周期。""" """库存和上传历史字段不能再替代正式 Gate 生成生命周期。"""
with app.app_context(): with app.app_context():
fulfillment = ShippingNotice( fulfillment = ShippingOrderTask(
task_no="SN-UI-FULFILLMENT", task_no="OT-UI-FULFILLMENT", user_id=1,
source_type="manual", source_type="direct_pdf",
match_status="partial",
inventory_lines_json=[{"part_number": "P-1"}],
)
upload = ShippingNotice(
task_no="SN-UI-UPLOAD",
source_type="manual",
upload_status="uploaded",
) )
upload = ShippingOrderTask(task_no="OT-UI-UPLOAD", user_id=1, source_type="direct_pdf")
assert build_task_ui_state(fulfillment)["stage"]["code"] == "unclassified" assert build_task_ui_state(fulfillment)["stage"]["code"] == "unclassified"
upload_state = build_task_ui_state(upload, include_stage_context=True) upload_state = build_task_ui_state(upload, include_stage_context=True)
assert upload_state["stage"]["code"] == "unclassified" assert upload_state["stage"]["code"] == "unclassified"
@@ -262,31 +298,39 @@ def test_build_task_ui_state_does_not_map_domain_fields_to_lifecycle(app) -> Non
def test_entry_surface_parse_review_is_review_workbench(app) -> None: def test_entry_surface_parse_review_is_review_workbench(app) -> None:
"""解析复核应进入人工复核工作台。""" """解析复核应进入人工复核工作台。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-UI-REVIEW", task_no="OT-UI-REVIEW", user_id=1,
review_status=RS_PARSE_REVIEW, review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF, pending_human_reason=PH_LOW_CONF,
source_type="manual", source_type="direct_pdf",
) )
state = build_task_ui_state(task) state = build_task_ui_state(task)
assert state["summary"]["entry_surface"] == "review_workbench" assert state["summary"]["entry_surface"] == "task_workbench"
def test_entry_surface_export_ready_is_task_workbench(app) -> None: def test_entry_surface_export_ready_is_task_workbench(app, monkeypatch) -> None:
"""Excel 待人工上传登记仍进入工作台,但历史文件名不能擅自授权下载。""" """Excel Artifact 就绪后仍进入工作台,且未解析的文件不得擅自授权下载。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingNotice(
task_no="SN-UI-EXPORT", task_no="SN-UI-EXPORT",
source_type="manual", source_type="manual",
export_file_path="/tmp/shipping-export.xlsx", )
export_file_name="shipping-export.xlsx", # Excel 是否就绪只能由 Artifact 事实裁决,不能恢复 Notice 旧文件投影。
from types import SimpleNamespace
monkeypatch.setattr(
'app.services.shipping_notice.upload_attempt_service.latest_export_artifact',
lambda _task: SimpleNamespace(id=0, file_path='/tmp/shipping-export.xlsx', file_name='shipping-export.xlsx'),
)
monkeypatch.setattr(
'app.services.shipping_notice.upload_attempt_service.latest_upload_attempt',
lambda _task: None,
) )
state = build_task_ui_state(task) state = build_task_ui_state(task)
assert state["checkpoint"]["code"] == CP_EXPORT_READY assert state["checkpoint"]["code"] == CP_EXPORT_READY
assert state["checkpoint_kind"] == "wait_manual_upload" assert state["checkpoint_kind"] == "wait_manual_upload"
assert state["summary"]["entry_surface"] == "task_workbench" assert state["summary"]["entry_surface"] == "task_workbench"
assert state["summary"].get("pause_reason_code") == "wait_manual_upload" assert state["summary"].get("pause_reason_code") == "wait_manual_upload"
assert "登记凭据" in str(state["summary"].get("pause_reason") or "") assert "货代平台上传" in str(state["summary"].get("pause_reason") or "")
button_ids = [ button_ids = [
item.get("code") item.get("code")
for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])] for item in [state["actions"].get("primary"), *(state["actions"].get("secondary") or [])]
@@ -303,8 +347,6 @@ def test_task_ui_state_only_exposes_download_for_resolved_artifact(app, monkeypa
task = ShippingNotice( task = ShippingNotice(
task_no="SN-UI-RESOLVED-EXPORT", task_no="SN-UI-RESOLVED-EXPORT",
source_type="manual", source_type="manual",
export_file_path="/tmp/shipping-export.xlsx",
export_file_name="shipping-export.xlsx",
) )
monkeypatch.setattr( monkeypatch.setattr(
'app.services.shipping_notice.ui_state.resolve_task_export_download', 'app.services.shipping_notice.ui_state.resolve_task_export_download',
@@ -373,18 +415,27 @@ def test_verified_upload_complete_state_has_no_follow_up_actions(app, monkeypatc
def test_stp_facts_candidates_frozen_projected(app) -> None: def test_stp_facts_candidates_frozen_projected(app) -> None:
"""多候选冻结任务须投影 stp_facts.frozen_candidate_codes。""" """多候选冻结任务须投影 stp_facts.frozen_candidate_codes。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-UI-STP-FROZEN", task_no="OT-UI-STP-FROZEN", user_id=1, source_type="direct_pdf",
source_type="manual",
inventory_source_status="candidates_frozen",
inventory_source_method="stp_build_freeze",
step_payload_json={
"line_inventory_candidates": {
"source_codes": ["DBS_DUB", "DBS_RTM"],
"frozen_at": "build",
},
},
) )
db.session.add(task)
db.session.flush()
candidate_set = ShippingInventoryCandidateSet(
task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='a' * 64,
)
db.session.add(candidate_set)
db.session.flush()
db.session.add_all([
ShippingInventoryCandidateSource(
candidate_set_id=candidate_set.id, source_code=code, candidate_order=index,
)
for index, code in enumerate(['DBS_DUB', 'DBS_RTM'], start=1)
])
db.session.add(ShippingInventoryCandidateLine(
candidate_set_id=candidate_set.id, line_no=1, source_codes_json=['DBS_DUB', 'DBS_RTM'],
))
task.active_inventory_candidate_set_id = candidate_set.id
db.session.commit()
state = build_task_ui_state(task) state = build_task_ui_state(task)
facts = state["summary"]["stp_facts"] facts = state["summary"]["stp_facts"]
assert facts["inventory_source_status"] == "candidates_frozen" assert facts["inventory_source_status"] == "candidates_frozen"
@@ -393,33 +444,37 @@ def test_stp_facts_candidates_frozen_projected(app) -> None:
def test_stp_facts_projects_line_resolutions(app) -> None: def test_stp_facts_projects_line_resolutions(app) -> None:
"""stp_facts 须包含逐行 Reservation/料号/实际库存源/文件证据。""" """stp_facts 须从当前行级 Match 投影逐行库存证据,不能读取 OT payload。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( user = User(username='ui-stp-lines', email='ui-stp-lines@example.com')
task_no="SN-UI-STP-LINES", db.session.add(user)
source_type="manual", db.session.flush()
match_status="fulfillable", task = ShippingOrderTask(
inventory_source_status="resolved", task_no='OT-UI-STP-LINES', user_id=user.id, stage='inventory_matching',
inventory_source_code="DBS_DUB",
inventory_source_method="stp_line_match",
step_payload_json={
"line_inventory_resolutions": [
{
"line_index": 0,
"disposition": "ok",
"effective_reservation_id": "3000092917",
"part_number": "PN-1",
"resolved_inventory_source_code": "DBS_DUB",
"inventory_file_no": "INV-1",
"inventory_row_ref": {
"reservation_id": "3000092917",
"part_number": "PN-1",
"source_code": "DBS_DUB",
},
},
],
},
) )
db.session.add(task)
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=3, schema_version_id=1,
order_data_version=1, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
task.order_snapshot_id = snapshot.id
snapshot_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=0, line_no=1,
reservation_id='3000092917', part_number='PN-1', qty='10', field_values_json={},
)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0,
match_result='matched', inventory_status='ready', required_qty='10', available_qty='10',
matched_qty='10', shortage_qty='0', reservation_id='3000092917', part_number='PN-1',
inventory_source_code='DBS_DUB', matched_file_no='INV-1', is_current=True,
))
db.session.commit()
state = build_task_ui_state(task, include_stage_context=True) state = build_task_ui_state(task, include_stage_context=True)
rows = state["summary"]["stp_facts"]["line_resolutions"] rows = state["summary"]["stp_facts"]["line_resolutions"]
assert rows[0]["effective_reservation_id"] == "3000092917" assert rows[0]["effective_reservation_id"] == "3000092917"
@@ -428,39 +483,58 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
assert rows[0]["inventory_file_no"] == "INV-1" assert rows[0]["inventory_file_no"] == "INV-1"
stage_context = state["stage_context"] stage_context = state["stage_context"]
assert stage_context["preparation"]["status"] == "ready" assert stage_context["preparation"]["status"] == "ready"
assert stage_context["preparation"]["lines"] == [{ # §1.5:行级字段是展示契约核心,但不锁全 dict(随 §1.5 字段扩展)。断言关键现存字段 + 新增明细按钮字段。
"line_key": None, line = stage_context["preparation"]["lines"][0]
"line_no": "1", assert line["snapshot_line_id"] == snapshot_line.id
"line_no_source": "sequence", assert line["line_no"] == 1
"reservation_id": "3000092917", assert line["customer_po_line_no"] is None
"part_number": "PN-1", assert line["reservation_id"] == "3000092917"
"required_qty": None, assert line["part_number"] == "PN-1"
"available_qty": None, assert line["required_qty"] == "10"
"shortage_qty": None, assert line["available_qty"] == "10"
"source_code": "DBS_DUB", assert line["shortage_qty"] == "0"
"status": "ok", assert line["source_code"] == "DBS_DUB"
}] # §1.5 status 现取 user_line_status(展示契约),不再是裸 match_result 的 disposition。
assert line["status"] == "inventory_matched"
assert line["source_ambiguous"] is False
assert line["source_candidates"] == []
# §1.5 明细按钮数据源:matched/ready 无短缺 → 无库存重试动作;行级库存文件号下发供下载按钮;
# line_allowed_actions 仍开放 close_unfulfillable(非终态行可关闭)。
assert line["inventory_file_no"] == "INV-1"
assert line["is_shortage"] is False
assert line["inventory_allowed_actions"] == []
assert line["line_allowed_actions"] == ["close_unfulfillable"]
assert line["user_line_status"] == "inventory_matched"
# 没有真实上传 Attempt 时,即使处于履约阶段也不能投影为上传成功。 # 没有真实上传 Attempt 时,即使处于履约阶段也不能投影为上传成功。
assert stage_context["upload"]["outcome"] == "not_started" assert stage_context["upload"]["outcome"] == "not_started"
def test_stage_context_prefers_current_structured_inventory_match(app) -> None: def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
"""通知准备摘要必须从当前行级匹配事实投影数量,不能只依赖旧 JSON。""" """通知准备必须从 Snapshot 与行级 Match 投影,不依赖 OT JSON 或 NoticeLine。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( user = User(username='ui-structured-match', email='ui-structured-match@example.com')
task_no="SN-UI-STRUCTURED-MATCH", db.session.add(user)
source_type="manual", db.session.flush()
match_status="partial", task = ShippingOrderTask(task_no='OT-UI-STRUCTURED-MATCH', user_id=user.id, stage='inventory_matching')
inventory_source_code="DBS_DUB",
inventory_source_status="resolved",
inventory_source_method="stp_line_match",
line_results_json=[],
)
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=1, schema_version_id=1,
order_data_version=1, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
task.order_snapshot_id = snapshot.id
snapshot_line = ShippingOrderSnapshotLine(
snapshot_id=snapshot.id, position=0, line_no=1,
reservation_id='RSV-1', part_number='PN-1', qty='10', field_values_json={},
)
db.session.add(snapshot_line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch( db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id, task_id=task.id,
line_key="line-1", snapshot_line_id=snapshot_line.id,
line_no=1,
line_index=0, line_index=0,
match_result="matched", match_result="matched",
inventory_status="ready", inventory_status="ready",
@@ -477,48 +551,85 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
assert preparation["has_match_result"] is True assert preparation["has_match_result"] is True
assert preparation["lines"] == [{ line = preparation["lines"][0]
"line_key": "line-1", assert line["snapshot_line_id"] == snapshot_line.id
"line_no": "1", assert line["line_no"] == 1
"line_no_source": "sequence", assert line["customer_po_line_no"] is None
"reservation_id": "RSV-1", assert line["reservation_id"] == "RSV-1"
"part_number": "PN-1", assert line["part_number"] == "PN-1"
"required_qty": "10", assert line["required_qty"] == "10"
"available_qty": "7", assert line["available_qty"] == "7"
"shortage_qty": "3", assert line["shortage_qty"] == "3"
"source_code": "DBS_DUB", assert line["source_code"] == "DBS_DUB"
"status": "matched", assert line["status"] == "shortage"
}] assert line["source_ambiguous"] is False
assert line["source_candidates"] == []
# §1.5 明细按钮:短缺 → close_unfulfillable / release_inventory_shortage + retry 两动作。
assert line["is_shortage"] is True
assert line["user_line_status"] == "shortage"
assert set(line["line_allowed_actions"]) == {"close_unfulfillable", "release_inventory_shortage"}
assert "retry_inventory_preparation" in line["inventory_allowed_actions"]
def test_stage_context_preparation_projects_source_ambiguity_and_lock(app) -> None:
"""行级 source_conflict 与候选源只读 Match;Excel 生成后锁定。"""
with app.app_context():
user = User(username='ui-source-ambiguity', email='ui-source-ambiguity@example.com')
db.session.add(user)
db.session.flush()
task = ShippingOrderTask(task_no='OT-UI-SOURCE-AMBIG', user_id=user.id, stage='inventory_matching')
db.session.add(task)
db.session.flush()
snapshot = ShippingOrderSnapshot(
task_id=task.id, extraction_id=2, schema_version_id=1,
order_data_version=1, header_values_json={},
)
db.session.add(snapshot)
db.session.flush()
task.order_snapshot_id = snapshot.id
line = ShippingOrderSnapshotLine(snapshot_id=snapshot.id, position=0, line_no=1, field_values_json={})
db.session.add(line)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id, snapshot_line_id=line.id, line_no=1, line_index=0,
match_result='source_conflict', inventory_status='source_conflict',
allowed_source_codes_snapshot=['SRC_A', 'SRC_B'], is_current=True,
))
db.session.commit()
preparation = build_task_ui_state(task, include_stage_context=True)['stage_context']['preparation']
assert preparation['lines'][0]['source_ambiguous'] is True
assert preparation['lines'][0]['source_candidates'] == ['SRC_A', 'SRC_B']
assert preparation['lines'][0]['source_code'] is None
assert preparation['source_locked'] is False
def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None: def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_ready(app) -> None:
"""库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。""" """库存文件尚未取得时,通知准备仍必须返回冻结订单行,不能把订单明细绑到匹配结果。"""
with app.app_context(): with app.app_context():
task = ShippingNotice(task_no="SN-UI-FROZEN-ORDER", source_type="manual") task, line = _frozen_task_with_line(
db.session.add(task) task_no="OT-UI-FROZEN-ORDER",
db.session.flush()
db.session.add(ShippingNoticeLine(
notice_id=task.id,
position=0,
line_key="line-frozen-1",
reservation_id="RSV-FROZEN", reservation_id="RSV-FROZEN",
part_number="PN-FROZEN", part_number="PN-FROZEN",
required_qty="6", qty="6",
)) )
db.session.commit() db.session.commit()
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"] preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
# 关键断言:冻结订单与库存匹配是两类事实;无库存文件不能抹掉订单行。 # 关键断言:冻结订单与库存匹配是两类事实;无库存文件不能抹掉订单行。
assert preparation["frozen_order_lines"] == [{ assert preparation["frozen_order_lines"] == [{
"line_key": "line-frozen-1", "snapshot_line_id": line.id,
"line_no": "1", "line_no": 1,
"line_no_source": "sequence",
"reservation_id": "RSV-FROZEN", "reservation_id": "RSV-FROZEN",
"part_number": "PN-FROZEN", "part_number": "PN-FROZEN",
"required_qty": "6.00000000", "required_qty": "6.00000000",
}] }]
assert preparation["lines"] == [] assert preparation["lines"][0]["snapshot_line_id"] == line.id
assert preparation["lines"][0]["line_no"] == 1
assert preparation["lines"][0]["reservation_id"] == "RSV-FROZEN"
assert preparation["lines"][0]["part_number"] == "PN-FROZEN"
assert preparation["lines"][0]["available_qty"] is None
assert preparation["has_match_result"] is False assert preparation["has_match_result"] is False
@@ -530,7 +641,9 @@ def test_resolve_task_inventory_download_requires_current_task_link(app, tmp_pat
with app.app_context(): with app.app_context():
inventory_path = tmp_path / "task-inventory.xlsx" inventory_path = tmp_path / "task-inventory.xlsx"
inventory_path.write_bytes(b"inventory-content") inventory_path.write_bytes(b"inventory-content")
task = ShippingNotice(task_no="SN-UI-INVENTORY-DOWNLOAD", source_type="manual") task = ShippingOrderTask(
task_no="OT-UI-INVENTORY-DOWNLOAD", user_id=1, source_type="direct_pdf",
)
inventory_file = ShippingInventoryFile( inventory_file = ShippingInventoryFile(
inventory_file_no="SIF-UI-DOWNLOAD", inventory_file_no="SIF-UI-DOWNLOAD",
storage_path=str(inventory_path), storage_path=str(inventory_path),
@@ -568,8 +681,8 @@ def test_workspace_inventory_download_requires_owned_active_file(app, client, tm
db.session.flush() db.session.flush()
inventory_path = tmp_path / 'inventory-download.xlsx' inventory_path = tmp_path / 'inventory-download.xlsx'
inventory_path.write_bytes(b'inventory-download-content') inventory_path.write_bytes(b'inventory-download-content')
task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='manual') task = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-API', user_id=owner.id, source_type='direct_pdf')
no_file_task = ShippingNotice(task_no='SN-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='manual') no_file_task = ShippingOrderTask(task_no='OT-INVENTORY-DOWNLOAD-NONE', user_id=owner.id, source_type='direct_pdf')
inventory_file = ShippingInventoryFile( inventory_file = ShippingInventoryFile(
inventory_file_no='SIF-INVENTORY-DOWNLOAD-API', inventory_file_no='SIF-INVENTORY-DOWNLOAD-API',
storage_path=str(inventory_path), storage_path=str(inventory_path),
@@ -589,16 +702,16 @@ def test_workspace_inventory_download_requires_owned_active_file(app, client, tm
other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'} other_headers = {'Authorization': f'Bearer {issue_local_access_token(other)}'}
# 关键断言:活动 link 文件可下载,并以服务端原始内容响应。 # 关键断言:活动 link 文件可下载,并以服务端原始内容响应。
success = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers) success = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-API/inventory-file', headers=owner_headers)
assert success.status_code == 200 assert success.status_code == 200
assert success.data == b'inventory-download-content' assert success.data == b'inventory-download-content'
assert 'inventory-download.xlsx' in str(success.headers.get('Content-Disposition') or '') assert 'inventory-download.xlsx' in str(success.headers.get('Content-Disposition') or '')
# 无 active link 和非归属用户均固定为 404,避免按来源或订单号探测库存文件。 # 无 active link 和非归属用户均固定为 404,避免按来源或订单号探测库存文件。
missing = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers) missing = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-NONE/inventory-file', headers=owner_headers)
assert missing.status_code == 404 assert missing.status_code == 404
assert missing.get_json()['error']['code'] == 'SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND' assert missing.get_json()['error']['code'] == 'SHIPPING.TASK_INVENTORY_FILE_NOT_FOUND'
forbidden = client.get('/api/workspace/shipping-tasks/SN-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers) forbidden = client.get('/api/workspace/shipping-tasks/OT-INVENTORY-DOWNLOAD-API/inventory-file', headers=other_headers)
assert forbidden.status_code == 404 assert forbidden.status_code == 404
@@ -614,7 +727,9 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app,
denied_path = tmp_path / 'dbs.xlsx' denied_path = tmp_path / 'dbs.xlsx'
allowed_path.write_bytes(b'crane-content') allowed_path.write_bytes(b'crane-content')
denied_path.write_bytes(b'dbs-content') denied_path.write_bytes(b'dbs-content')
task = ShippingNotice(task_no='SN-LINE-INVENTORY-DOWNLOAD', user_id=owner.id, source_type='manual') task, snapshot_line = _frozen_task_with_line(
task_no='OT-LINE-INVENTORY-DOWNLOAD', user_id=owner.id,
)
allowed_file = ShippingInventoryFile( allowed_file = ShippingInventoryFile(
inventory_file_no='SIF-LINE-CRANE', storage_path=str(allowed_path), inventory_file_no='SIF-LINE-CRANE', storage_path=str(allowed_path),
source_file_name='crane.xlsx', source_code='CRANE', snapshot_status='ready', source_file_name='crane.xlsx', source_code='CRANE', snapshot_status='ready',
@@ -626,7 +741,7 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app,
db.session.add_all([task, allowed_file, denied_file]) db.session.add_all([task, allowed_file, denied_file])
db.session.flush() db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch( db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id, line_key='line-crane', line_index=0, task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0,
inventory_snapshot_id=allowed_file.id, matched_file_no=allowed_file.inventory_file_no, inventory_snapshot_id=allowed_file.id, matched_file_no=allowed_file.inventory_file_no,
inventory_source_code='CRANE', match_result='not_found', inventory_status='ready', is_current=True, inventory_source_code='CRANE', match_result='not_found', inventory_status='ready', is_current=True,
)) ))
@@ -634,7 +749,7 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app,
headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'} headers = {'Authorization': f'Bearer {issue_local_access_token(owner)}'}
allowed = client.get( allowed = client.get(
'/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-CRANE', '/api/workspace/shipping-tasks/OT-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-CRANE',
headers=headers, headers=headers,
) )
assert allowed.status_code == 200 assert allowed.status_code == 200
@@ -642,41 +757,33 @@ def test_workspace_line_inventory_download_requires_current_line_reference(app,
assert 'crane.xlsx' in str(allowed.headers.get('Content-Disposition') or '') assert 'crane.xlsx' in str(allowed.headers.get('Content-Disposition') or '')
denied = client.get( denied = client.get(
'/api/workspace/shipping-tasks/SN-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-DBS', '/api/workspace/shipping-tasks/OT-LINE-INVENTORY-DOWNLOAD/inventory-files/SIF-LINE-DBS',
headers=headers, headers=headers,
) )
assert denied.status_code == 404 assert denied.status_code == 404
def test_stage_context_keeps_legacy_evidence_when_structured_row_is_partial(app) -> None: def test_stage_context_keeps_legacy_evidence_when_structured_row_is_partial(app) -> None:
"""结构化事实字段为空时,历史/STP 证据仍应补齐通知准备行。""" """行级 Match 的事实字段应补齐冻结订单行的库存展示。"""
with app.app_context(): with app.app_context():
task = ShippingNotice( task, snapshot_line = _frozen_task_with_line(
task_no="SN-UI-STRUCTURED-PARTIAL", task_no="OT-UI-STRUCTURED-PARTIAL",
source_type="manual", reservation_id="RSV-LEGACY",
match_status="partial", part_number="PN-LEGACY",
inventory_source_status="resolved", qty="10",
inventory_source_method="stp_line_match",
step_payload_json={"line_inventory_resolutions": [{
"line_index": 0,
"line_key": "line-1",
"effective_reservation_id": "RSV-LEGACY",
"part_number": "PN-LEGACY",
"inventory_file_no": "INV-1",
"disposition": "ok",
}]},
) )
db.session.add(task)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch( db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id, task_id=task.id,
line_key="line-1", snapshot_line_id=snapshot_line.id,
line_no=1,
line_index=0, line_index=0,
match_result="matched", match_result="matched",
inventory_status="ready", inventory_status="ready",
required_qty="10", required_qty="10",
available_qty="8", available_qty="8",
shortage_qty="2", shortage_qty="2",
reservation_id="RSV-LEGACY",
part_number="PN-LEGACY",
inventory_source_code="DBS_DUB", inventory_source_code="DBS_DUB",
is_current=True, is_current=True,
)) ))
@@ -696,18 +803,16 @@ def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch
from app.services.shipping_notice import query_service from app.services.shipping_notice import query_service
with app.app_context(): with app.app_context():
task = ShippingNotice( task, snapshot_line = _frozen_task_with_line(
task_no="SN-UI-DETAIL-CONTEXT", task_no="OT-UI-DETAIL-CONTEXT",
source_type="manual", reservation_id="RSV-DETAIL",
match_status="fulfillable", part_number="PN-DETAIL",
inventory_source_status="resolved", qty="2",
inventory_source_method="stp_line_match",
) )
db.session.add(task)
db.session.flush()
db.session.add(ShippingNoticeLineInventoryMatch( db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id, task_id=task.id,
line_key="line-1", snapshot_line_id=snapshot_line.id,
line_no=1,
line_index=0, line_index=0,
match_result="matched", match_result="matched",
inventory_status="ready", inventory_status="ready",
@@ -725,6 +830,8 @@ def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch
monkeypatch.setattr(query_service, 'get_task_visible_to_user', lambda *_args, **_kwargs: task) monkeypatch.setattr(query_service, 'get_task_visible_to_user', lambda *_args, **_kwargs: task)
monkeypatch.setattr(api, '_ok', lambda data: data) monkeypatch.setattr(api, '_ok', lambda data: data)
# 视图函数经 request.args 读取 view 参数,必须包一层请求上下文(直接调用无 request)。
with app.test_request_context():
payload = api.workspace_shipping_task_detail(task.task_no) payload = api.workspace_shipping_task_detail(task.task_no)
preparation = payload['ui_state']['stage_context']['preparation'] preparation = payload['ui_state']['stage_context']['preparation']
assert preparation['has_match_result'] is True assert preparation['has_match_result'] is True
@@ -732,29 +839,100 @@ def test_task_detail_endpoint_returns_preparation_stage_context(app, monkeypatch
def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None: def test_stp_facts_multi_source_excel_block_legacy_payload(app) -> None:
"""历史 multi_source_excel_block 载荷仍覆盖 pause_reason(兼容旧任务)。""" """行级多源冲突应覆盖通知准备的暂停原因。"""
from app.services.shipping_notice.constants import RS_SHORTAGE_REVIEW
with app.app_context(): with app.app_context():
task = ShippingNotice( task, snapshot_line = _frozen_task_with_line(
task_no="SN-UI-STP-MULTI", task_no="OT-UI-STP-MULTI", reservation_id="RSV-MULTI", part_number="PN-MULTI", qty="1",
review_status=RS_SHORTAGE_REVIEW,
pending_human_reason="shortage",
source_type="manual",
match_status="fulfillable",
inventory_source_status="candidates_frozen",
inventory_source_method="stp_line_match",
step_payload_json={
"multi_source_excel_block": True,
"resolved_ok_source_codes": ["DBS_DUB", "DBS_RTM"],
"line_inventory_resolutions": [
{"line_index": 0, "disposition": "ok", "resolved_inventory_source_code": "DBS_DUB"},
{"line_index": 1, "disposition": "ok", "resolved_inventory_source_code": "DBS_RTM"},
],
},
) )
db.session.add(ShippingNoticeLineInventoryMatch(
task_id=task.id, snapshot_line_id=snapshot_line.id, line_no=1, line_index=0,
match_result='source_conflict', inventory_status='source_conflict',
allowed_source_codes_snapshot=['DBS_DUB', 'DBS_RTM'], is_current=True,
))
db.session.commit()
state = build_task_ui_state(task) state = build_task_ui_state(task)
summary = state["summary"] summary = state["summary"]
assert summary["pause_reason_code"] == "multi_source_excel_block" assert summary["pause_reason_code"] == "multi_source_excel_block"
assert summary["stp_facts"]["multi_source_excel_block"] is True assert summary["stp_facts"]["multi_source_excel_block"] is True
assert summary["entry_surface"] == "task_workbench" assert summary["entry_surface"] == "task_workbench"
def test_preparation_editable_present_for_live_formal_task(monkeypatch):
"""活任务(active/blocked/空值)判定可操作;作废/归档/删除/待作废/取消视图不可操作。
按 ShippingNotice 真实 lifecycle_status 值域逐值覆盖(不用 WorkflowItem 的
{'closed', 'cancelled'} 终态集);排除集见 ui_state 的
_PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES 注释。
"""
class FakeTask:
id = 1
task_no = 'SN-LIVE-1'
order_task_no = 'SN-LIVE-1'
# 真实值域:ShippingNotice 无 in_progress 写入方,活任务为 active。
lifecycle_status = 'active'
export_file_path = ''
order_snapshot_id = None
inventory_source_code = None
match_status = None
# 直接依赖 _build_stage_context 内部较重;此处最小断言 editable 键存在且为 bool 语义。
# 实现时若 _build_stage_context 依赖过多,改为抽纯谓词 _preparation_editable(task) 单测。
from app.services.shipping_notice.ui_state import _preparation_editable
# 关键断言:活任务(active)判定可操作(任务级 editable=True 语义)。
assert _preparation_editable(FakeTask()) is True
class BlockedTask(FakeTask):
lifecycle_status = 'blocked'
# 关键断言:blocked 是新任务暂堵态(task_supersession_service.py),不算作废/历史
# 视图,保持可编辑——与 case 级 edit_formal_task 镜像语义一致;闸口语义由
# pending_human_reason 等机制表达,不在此谓词收紧。
assert _preparation_editable(BlockedTask()) is True
class NoStatusTask(FakeTask):
lifecycle_status = None
# 边界断言:空/缺失 lifecycle_status 不得误判为终态,默认可操作。
assert _preparation_editable(NoStatusTask()) is True
# 关键断言:每个非可操作生命周期必须置 False,供 Prep 波次出单门控拦截——
# 终态 voided/archived/deleted;co8 只读语义 pending_void
# (freight_cancellation_service.py:154);兼容双拼 cancelled/canceled。
for status in ('voided', 'archived', 'deleted', 'pending_void', 'cancelled', 'canceled'):
class NonEditableTask(FakeTask):
pass
NonEditableTask.lifecycle_status = status
# 意图:该值域命中 _PREPARATION_NON_EDITABLE_LIFECYCLE_STATUSES → editable=False。
assert _preparation_editable(NonEditableTask()) is False
class NoisyStatusTask(FakeTask):
lifecycle_status = ' Voided '
# 边界断言:strip/lower 归一化必须保留(防终态因空白/大小写漏判为可编辑)。
assert _preparation_editable(NoisyStatusTask()) is False
def test_stage_context_preparation_projects_editable_and_customer_po_line_no(app) -> None:
"""[断言] preparation 携带任务级 editable(active=True / voided=False);
行级 customer_po_line_no 直读字段真实值(field_code 兼容键),字段缺失时为 None。"""
with app.app_context():
task, first_line = _frozen_task_with_line(
task_no="OT-UI-PREP-EDITABLE",
reservation_id="RSV-PO-1", part_number="PN-PO-1", qty="5",
field_values_json={"customer_po_line_no": "7"},
)
second_line = ShippingOrderSnapshotLine(
snapshot_id=first_line.snapshot_id, position=1, line_no=2,
reservation_id="RSV-PO-2", part_number="PN-PO-2", qty="3", field_values_json={},
)
db.session.add(second_line)
db.session.commit()
preparation = build_task_ui_state(task, include_stage_context=True)["stage_context"]["preparation"]
# 关键断言:活任务(默认 active)必须下发任务级可操作标志 True。
assert preparation["editable"] is True
# 未绑定 Schema 字段 ID 时,冻结档不会把 field_code 当成正式字段事实。
assert preparation["lines"][0]["customer_po_line_no"] is None
# 字段缺失/无值的行也必须输出 None,不得用展示序号冒充业务行号。
assert preparation["lines"][1]["customer_po_line_no"] is None
@@ -2,11 +2,11 @@
tests/test_shipping_notice_user_facing_status.py tests/test_shipping_notice_user_facing_status.py
用途:验证发货通知用户可见阶段文案的优先级,避免细粒度 pending 状态被通用 checkpoint 覆盖。 用途:验证发货通知用户可见阶段文案的优先级,避免细粒度 pending 状态被通用 checkpoint 覆盖。
依赖:pytest、ShippingNotice 模型、user_facing_status。 依赖:pytest、ShippingOrderTask 模型、user_facing_status。
逻辑:构造最小 ShippingNotice 实例,断言 rpa_pending 时优先展示具体的 RPA 导出提示。 逻辑:构造最小 ShippingOrderTask 实例,断言 rpa_pending 时优先展示具体的 RPA 导出提示。
""" """
from app.models import ShippingNotice from app.models import ShippingOrderTask
from app.services.shipping_notice.constants import PH_RPA_PENDING from app.services.shipping_notice.constants import PH_RPA_PENDING
from app.services.shipping_notice.user_facing_status import user_facing_task_stage from app.services.shipping_notice.user_facing_status import user_facing_task_stage
@@ -15,10 +15,12 @@ def test_user_facing_task_stage_prefers_specific_rpa_pending_reason() -> None:
""" """
rpa_pending 时应优先展示 RPA 导出中的具体提示,而不是通用的“待上传或获取库存”。 rpa_pending 时应优先展示 RPA 导出中的具体提示,而不是通用的“待上传或获取库存”。
核心逻辑:构造 waiting_inventory + rpa_pending 的任务,验证用户可见标题优先取 pending_human_reason。 核心逻辑:pending_human_reason 是属于建单前 OT(ShippingOrderTask)的流程阻断事实;
正式 Notice 只承载单据。构造 rpa_pending 的任务,验证用户可见标题优先取 pending_human_reason。
""" """
task = ShippingNotice( task = ShippingOrderTask(
task_no="SN-TEST-RPA-PENDING", task_no="OT-TEST-RPA-PENDING",
user_id=1,
pending_human_reason=PH_RPA_PENDING, pending_human_reason=PH_RPA_PENDING,
) )
@@ -22,8 +22,9 @@ from app.models import (
Job, Job,
ShippingDocumentProfileAutoFreezeQualification, ShippingDocumentProfileAutoFreezeQualification,
ShippingCustomer, ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingOrderCandidate,
ShippingOrderDocumentProfile, ShippingOrderDocumentProfile,
ShippingOrderCustomerMatch,
ShippingOrderExtraction, ShippingOrderExtraction,
ShippingOrderExtractionProgressEvent, ShippingOrderExtractionProgressEvent,
ShippingOrderRouteDecision, ShippingOrderRouteDecision,
@@ -52,7 +53,7 @@ def _published_profile(*, schema_version_id: int, checksum: str) -> ShippingOrde
def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int, customer: ShippingCustomer) -> None: def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int, customer: ShippingCustomer) -> None:
"""为 Run 构造一条已确认的 Bill-to 客户匹配,供范围门禁测试复用。""" """为 Run 构造已确认的客户识别结果,供范围门禁测试复用。"""
extraction = ShippingOrderExtraction( extraction = ShippingOrderExtraction(
run_id=run_id, run_id=run_id,
intake_id=intake_id, intake_id=intake_id,
@@ -63,18 +64,20 @@ def _confirm_run_customer(*, run_id: int, intake_id: int, schema_version_id: int
) )
db.session.add(extraction) db.session.add(extraction)
db.session.flush() db.session.flush()
db.session.add(ShippingOrderCustomerMatch( candidate = ShippingOrderCandidate(
extraction_id=extraction.id, candidate_no=f'CAND-AF-{run_id}-{customer.id}', intake_id=int(intake_id), primary_document_id=1,
role='bill_to', candidate_key=f'auto-freeze-{run_id}-{customer.id}', order_extraction_id=extraction.id,
identity_components_json={}, candidate_status='accepted', order_extraction_run_id=int(run_id),
status='confirmed', )
customer_id=customer.id, db.session.add(candidate)
customer_name_snapshot=customer.standard_name, db.session.flush()
customer_short_code_snapshot=customer.short_code, db.session.add(ShippingCustomerShadowResolution(
identity_fingerprint=f'customer-{customer.id}', candidate_id=candidate.id, intake_id=int(intake_id), resolution_version='test.v1', status='confirmed',
identity_rule_version='customer-match.v1', evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}],
resolution_method='manual', candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
confirmed_at=datetime.utcnow(), resolution_context_json={'rule_set': {'checksum': 'a' * 64}}, identity_rule_set_checksum='a' * 64,
top_customer_id=customer.id, top_score=100, confirmed_customer_id=customer.id,
confirmation_method='manual', confirmed_at=datetime.utcnow(),
)) ))
Loaded 100 of 168 files, more files were not shown because too many files have changed in this diff. Show more