feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理

清理废弃的ShippingCase相关代码与依赖,统一使用ShippingNotice直接关联客户数据。调整库存网关依赖规则,支持仅对库存满足或已人工放行的订单行生成发货Excel,实现滚动履约逻辑。
This commit is contained in:
hugo committed 2026-08-26 02:47:07 +08:00
1 parent 7cfd5d167e
commit 1e5aedb9ed
235 files changed
+11394 -9613

No files matched your search

+3 -3
View File
@@ -185,9 +185,9 @@ FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈
# 货代客户自动确认默认关闭;仅 approved + auto_match_allowed 强规则唯一命中时可开启。
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=true
# OT 后行级自动履约(默认关):关闭时只上线匹配事实契约/明细库存列;禁止自动决定与 wave。
SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=false
SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=true
# 发货通知专用 Worker 进程数;版面解析为长任务,默认并发处理同批两份文档。
SHIPPING_NOTICE_WORKER_CONCURRENCY=2
SHIPPING_NOTICE_WORKER_CONCURRENCY=10
# Layout Job 内整页 OCR 结果复用(PR-1);共享默认关,dev/test 环境文件覆盖为 true,prod 保持 false 灰度。
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
# PDFium 字符预读复用与按需补图(PR-2);共享默认关,dev/test 开启,prod 灰度。
@@ -212,7 +212,7 @@ SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE=dual
SHIPPING_NOTICE_ORDER_LINES_READ_MODE=shadow
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
# 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。
SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300
# 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。
+24 -17
View File
@@ -127,6 +127,13 @@ def chat_completions():
else:
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
# [STEP 1] SSE 生成器可能在请求 scoped Session 清理后才开始迭代;提前快照会话标量,
# 避免流内事务提交使 ORM 实例过期后触发 DetachedInstanceError。
local_session_id = str(session.session_id)
initial_session_status = str(session.status or 'running')
initial_external_conversation_id = str(external_conversation_id or '').strip() or None
stream_session = SimpleNamespace(session_id=local_session_id)
normalized_files: list[dict] | None = None
if files is not None:
if not isinstance(files, list):
@@ -161,8 +168,8 @@ def chat_completions():
display_query=display_query,
user=user_proxy,
agent=agent_proxy,
session=session,
external_conversation_id=external_conversation_id,
session=stream_session,
external_conversation_id=initial_external_conversation_id,
request_id=request_id,
normalized_files=normalized_files,
adapter_hints=_build_chat_adapter_hints(
@@ -182,8 +189,8 @@ def chat_completions():
agent=agent_proxy,
query=query,
agent_id=agent_id,
session_id=session.session_id,
external_conversation_id=external_conversation_id,
session_id=local_session_id,
external_conversation_id=initial_external_conversation_id,
normalized_files=normalized_files,
kb_type=kb_type,
leave_supported=leave_supported,
@@ -195,13 +202,13 @@ def chat_completions():
query,
user_proxy.id,
agent_proxy,
external_conversation_id,
initial_external_conversation_id,
request_id=request_id,
session_id=session.session_id,
session_id=local_session_id,
files=normalized_files,
inputs=build_chat_dify_inputs(
agent_proxy,
session_id=session.session_id,
session_id=local_session_id,
request_id=request_id,
trigger_source="frontend_chat",
user_role=user_proxy.role,
@@ -222,14 +229,14 @@ def chat_completions():
relay_first_chunk_at: float | None = None
created_event = {
'event': 'session_created',
'conversation_id': session.session_id,
'provider_conversation_id': session.external_conversation_id,
'session_status': session.status,
'conversation_id': local_session_id,
'provider_conversation_id': initial_external_conversation_id,
'session_status': initial_session_status,
}
yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n"
known_provider_conversation_id = session.external_conversation_id
known_status = session.status
known_provider_conversation_id = initial_external_conversation_id
known_status = initial_session_status
emitted_handler_state_keys: set[str] = set()
from app.services.chat.stream_relay import (
@@ -272,7 +279,7 @@ def chat_completions():
updated_session = _update_chat_session(
user_id,
agent_id,
session.session_id,
local_session_id,
status=known_status,
external_conversation_id=known_provider_conversation_id,
touch=True,
@@ -281,7 +288,7 @@ def chat_completions():
known_status = updated_session.status
event_data['provider_conversation_id'] = provider_conversation_id
event_data['conversation_id'] = session.session_id
event_data['conversation_id'] = local_session_id
event_data['session_status'] = known_status
if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'):
relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None
@@ -289,7 +296,7 @@ def chat_completions():
current_app.logger.info(
'[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s',
request_id,
session.session_id,
local_session_id,
relay_first_ms,
relay_total_ms,
event_name,
@@ -307,8 +314,8 @@ def chat_completions():
):
yield terminal_line
except Exception as exc:
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id)
payload = {'event': 'error', 'message': str(exc), 'conversation_id': local_session_id, 'session_status': 'error'}
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
# 返回 SSE 响应,mimetype 设为 text/event-stream
+289 -22
View File
@@ -5,7 +5,7 @@ backend/app/api/workspace/shipping_notice.py
依赖:app.core.auth.jwt、app.core.errors、app.core.response.ok、shipping_notice.query_service /
tools / notice_upload / ui_state、shipping_processing_projection。
逻辑:薄路由层鉴权与参数校验;成功响应统一走 `_ok`/`ok` envelope;写接口保留乐观锁、幂等键与
统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint;
统一 AppError;人工上传仅确认唯一 Excel 已上传,不采集回执或凭据;Chat Turn 履约写路径已废弃,请改走本 Blueprint;
`/shipping-processing/*` 为统一进度读源;历史 `/shipping-batches*` 已删除;
Workflow ledger 路由已整段删除,进度请读 shipping-processing / Run API。
"""
@@ -586,6 +586,22 @@ def workspace_list_shipping_task_audit_timeline(task_no: str):
return _ok(payload)
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/freight-notice-groups', methods=['GET'])
def workspace_shipping_task_freight_notice_groups(task_no: str):
"""读取当前 PO 下按 business_no 聚合的货代上传 Notice;仅供订单工作台展示。"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.query_service import (
get_task_visible_to_user,
list_freight_notice_groups_for_task,
)
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
return _ok(list_freight_notice_groups_for_task(task, user_id=int(user.id), is_admin=is_admin))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
def workspace_shipping_task_ui_state(task_no: str):
"""
@@ -638,7 +654,7 @@ def workspace_update_shipping_notice_fields(task_no: str):
@workspace_shipping_notice_bp.route('/shipping-freight-cancellations/<int:cancellation_id>/complete', methods=['POST'])
def workspace_complete_shipping_freight_cancellation(cancellation_id: int):
"""登记货代撤销回执并解除合法后继版本的履约阻断。"""
"""登记已取得外部撤销确认并解除合法后继版本的履约阻断。"""
user = _require_user()
data = request.get_json(silent=True) or {}
from app.models import ShippingFreightCancellation
@@ -650,9 +666,7 @@ def workspace_complete_shipping_freight_cancellation(cancellation_id: int):
raise NotFoundError('Not found')
from app.services.shipping_notice.freight_cancellation_service import complete_freight_cancellation
row = complete_freight_cancellation(
cancellation_id=cancellation.id, actor_id=int(user.id),
freight_receipt_no=str(data.get('freight_receipt_no') or ''),
receipt_asset_id=data.get('receipt_asset_id'), note=str(data.get('note') or ''),
cancellation_id=cancellation.id, actor_id=int(user.id), note=str(data.get('note') or ''),
)
db.session.commit()
return _ok({'id': row.id, 'status': row.status, 'old_task_id': row.old_task_id, 'new_task_id': row.new_task_id})
@@ -834,9 +848,10 @@ def workspace_auto_progress_shipping_task(task_no: str):
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
def workspace_mark_manual_uploaded(task_no: str):
"""
登记人工货代上传;必须提交当前用户已上传的截图或回执 FileAsset 编号。
兼容旧 task_no 的人工上传确认;不再提交或记录截图/PDF、货代回执号。
核心逻辑:委托 upload_to_freight(mode=manual_confirm);禁止 RPA。
核心逻辑:仅委托 upload_to_freight(mode=manual_confirm),新客户端必须改用
business_no 的 `/shipping-notices/<business_no>/confirm-uploaded`。
"""
user = _require_user()
task = get_task_for_user(task_no, user.id)
@@ -852,21 +867,232 @@ def workspace_mark_manual_uploaded(task_no: str):
'actor_id': user.id,
'_trusted_user_id': user.id,
'event_source': 'workspace_api',
'evidence_asset_no': data.get('evidence_asset_no'),
'freight_ref_no': data.get('freight_ref_no'),
'artifact_id': data.get('artifact_id'),
}
result = shipping_tools.upload_to_freight(payload)
if isinstance(result, dict) and str(result.get('status') or '') == 'ok':
# 回执先由既有服务原子登记;随后仅提交 upload_receipt_recorded Gate,由服务端复核事实后 completed。
# 人工确认已由服务原子登记;随后只推进最终上传 Gate。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
run_task_auto_progress(
str(task.task_no), trigger='manual_upload_receipt_recorded', operator_id=int(user.id),
str(task.task_no), trigger='manual_upload_confirmed', operator_id=int(user.id),
)
return _ok(result)
def _confirm_notice_uploaded(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
"""
按发货通知单号确认唯一 Excel 已上传;内部 task_no 仅用于既有状态机和审计追溯。
Args:
business_no: 对外发货通知单号,禁止调用方以 task_no 代替。
user_id: 当前服务端会话用户。
artifact_id: 可选唯一 Excel Artifact 主键;不传时由服务端解析。
Returns:
包含 business_no 和既有上传结果的字典。
Raises:
NotFoundError: 通知单不存在或当前用户无写权限。
"""
task = get_task_for_user(str(business_no).strip().upper(), user_id)
if task is None or str(task.business_no or '').upper() != str(business_no).strip().upper():
raise NotFoundError('Shipping notice not found')
_assert_fulfillment_task_ownership(task, user_id)
from app.services.shipping_notice import tools as shipping_tools
result = shipping_tools.upload_to_freight({
'task_id': task.task_no,
'mode': 'manual_confirm',
'operator_id': user_id,
'actor_id': user_id,
'_trusted_user_id': user_id,
'event_source': 'workspace_api',
'artifact_id': artifact_id,
})
if isinstance(result, dict) and str(result.get('status') or '') == 'ok':
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
run_task_auto_progress(
str(task.task_no), trigger='manual_upload_confirmed', operator_id=user_id,
)
return {'business_no': str(task.business_no), **dict(result or {})}
def _load_business_notice_for_user(*, business_no: str, user_id: int) -> ShippingNotice:
"""
按精确发货通知单号加载当前用户可操作的 Notice。
核心逻辑:先由既有用户归属查询过滤,再二次比较 Notice.business_no;禁止 task_no、
历史聚合编号或模糊引用进入新的货代操作入口。
Args:
business_no: 对外发货通知单号。
user_id: 当前服务端会话用户主键。
Returns:
当前用户拥有履约写权限的 ShippingNotice。
Raises:
NotFoundError: 编号不存在或用户不可访问。
"""
normalized = str(business_no or '').strip().upper()
task = get_task_for_user(normalized, user_id)
if task is None or str(task.business_no or '').strip().upper() != normalized:
raise NotFoundError('Shipping notice not found')
_assert_fulfillment_task_ownership(task, user_id)
return task
def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
"""按 business_no 发起单张通知的货代 RPA 上传或重试。"""
task = _load_business_notice_for_user(business_no=business_no, user_id=user_id)
from app.services.shipping_notice import tools as shipping_tools
result = shipping_tools.upload_to_freight({
'task_id': task.task_no,
'mode': 'retry_upload',
'operator_id': user_id,
'actor_id': user_id,
'_trusted_user_id': user_id,
'event_source': 'workspace_api',
'artifact_id': artifact_id,
})
return {'business_no': str(task.business_no), **dict(result or {})}
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/confirm-uploaded', methods=['POST'])
def workspace_confirm_shipping_notice_uploaded(business_no: str):
"""确认一张发货通知单的唯一 Excel 已人工上传,不接收回执号或截图/PDF。"""
user = _require_user()
data = request.get_json(silent=True) or {}
raw_artifact_id = data.get('artifact_id')
try:
artifact_id = int(raw_artifact_id) if raw_artifact_id is not None else None
except (TypeError, ValueError) as exc:
raise ValidationError('artifact_id must be an integer') from exc
return _ok(_confirm_notice_uploaded(
business_no=business_no, user_id=int(user.id), artifact_id=artifact_id,
))
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/rpa-upload', methods=['POST'])
def workspace_start_shipping_notice_rpa_upload(business_no: str):
"""按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。"""
user = _require_user()
data = request.get_json(silent=True) or {}
raw_artifact_id = data.get('artifact_id')
try:
artifact_id = int(raw_artifact_id) if raw_artifact_id is not None else None
except (TypeError, ValueError) as exc:
raise ValidationError('artifact_id must be an integer') from exc
return _ok(_start_notice_rpa_upload(
business_no=business_no, user_id=int(user.id), artifact_id=artifact_id,
), status=202)
@workspace_shipping_notice_bp.route('/shipping-notices/batch/confirm-uploaded', methods=['POST'])
def workspace_batch_confirm_shipping_notices_uploaded():
"""批量确认多个通知单已上传;每张通知单独立事务裁决,单项失败不回滚其他单。"""
user = _require_user()
data = request.get_json(silent=True) or {}
raw_values = data.get('business_nos')
if not isinstance(raw_values, list):
raise ValidationError('business_nos must be a non-empty list')
business_nos = list(dict.fromkeys(
str(value or '').strip().upper() for value in raw_values if str(value or '').strip()
))
if not business_nos or len(business_nos) > 100:
raise ValidationError('business_nos must contain 1 to 100 business numbers')
results: list[dict[str, Any]] = []
for business_no in business_nos:
try:
result = _confirm_notice_uploaded(business_no=business_no, user_id=int(user.id))
db.session.commit()
results.append({'business_no': business_no, 'status': 'confirmed', 'result': result})
except AppError as exc:
db.session.rollback()
results.append({'business_no': business_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message})
except Exception:
db.session.rollback()
raise
return _ok({'results': results})
@workspace_shipping_notice_bp.route('/shipping-notices/batch/rpa-upload', methods=['POST'])
def workspace_batch_start_shipping_notice_rpa_upload():
"""批量发起 RPA 上传;每个 business_no 独立提交,单项失败不影响其他通知单。"""
user = _require_user()
data = request.get_json(silent=True) or {}
raw_values = data.get('business_nos')
if not isinstance(raw_values, list):
raise ValidationError('business_nos must be a non-empty list')
business_nos = list(dict.fromkeys(
str(value or '').strip().upper() for value in raw_values if str(value or '').strip()
))
if not business_nos or len(business_nos) > 100:
raise ValidationError('business_nos must contain 1 to 100 business numbers')
results: list[dict[str, Any]] = []
for business_no in business_nos:
try:
result = _start_notice_rpa_upload(business_no=business_no, user_id=int(user.id))
db.session.commit()
result_status = 'accepted' if str(result.get('status') or '').lower() in {'ok', 'running'} else 'blocked'
results.append({'business_no': business_no, 'status': result_status, 'result': result})
except AppError as exc:
db.session.rollback()
results.append({'business_no': business_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message})
except Exception:
db.session.rollback()
raise
return _ok({'results': results}, status=202)
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET'])
def workspace_shipping_notice_export(business_no: str):
"""按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。"""
user = _require_user()
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
err_msg = task_export_error_message(task)
if err_msg:
raise NotFoundError(err_msg)
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
from app.services.shipping_notice.fulfillment_audit import record_access_audit
record_access_audit(
action='download_notice_excel',
aggregate_type='shipping_notice',
aggregate_id=str(task.business_no),
actor_id=user.id,
task_no=str(task.task_no),
reason_code='excel_downloaded',
metadata={'business_no': str(task.business_no), 'export': 'excel'},
)
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST'])
def workspace_shipping_notice_export_archive():
"""按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。"""
user = _require_user()
data = request.get_json(silent=True) or {}
raw_values = data.get('business_nos')
if not isinstance(raw_values, list):
raise ValidationError('business_nos must be a non-empty list')
business_nos = list(dict.fromkeys(
str(value or '').strip().upper() for value in raw_values if str(value or '').strip()
))
if not business_nos or len(business_nos) > 100:
raise ValidationError('business_nos must contain 1 to 100 business numbers')
from app.services.shipping_notice.export_archive import build_export_archive
stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos)
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
response.call_on_close(stream.close)
return response
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
@@ -1282,14 +1508,24 @@ def workspace_list_shipping_order_extraction_documents(run_no: str):
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/review', methods=['GET'])
def workspace_get_shipping_order_review_run(run_no: str):
"""读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照;访问留痕。"""
"""
读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照;访问留痕。
通过 Server-Timing 暴露查找与投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变
JSON 响应契约或业务数据。
"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.order_review_projection import serialize_review_run
from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user
payload = serialize_review_run(get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin))
lookup_started = perf_counter()
review_run = get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin)
lookup_ms = (perf_counter() - lookup_started) * 1000
projection_started = perf_counter()
payload = serialize_review_run(review_run)
projection_ms = (perf_counter() - projection_started) * 1000
record_access_audit(
action='view_order_review_run',
aggregate_type='order_extraction_run',
@@ -1297,20 +1533,34 @@ def workspace_get_shipping_order_review_run(run_no: str):
actor_id=user.id,
run_no=str(run_no),
)
return _ok(payload)
response = current_app.make_response(_ok(payload))
response.headers['Server-Timing'] = (
f'review_lookup;dur={lookup_ms:.1f}, '
f'review_projection;dur={projection_ms:.1f}'
)
return response
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-queue/<run_no>', methods=['GET'])
def workspace_get_shipping_order_review_queue(run_no: str):
"""读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。"""
"""
读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。
通过 Server-Timing 暴露查找与投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变
JSON 响应契约或业务数据。
"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.fulfillment_audit import record_access_audit
from app.services.shipping_notice.order_review_projection import serialize_review_queue
from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user
lookup_started = perf_counter()
runs = get_review_queue_visible_to_user(run_no, user.id, is_admin=is_admin)
lookup_ms = (perf_counter() - lookup_started) * 1000
projection_started = perf_counter()
payload = serialize_review_queue(runs)
projection_ms = (perf_counter() - projection_started) * 1000
record_access_audit(
action='view_order_review_queue',
aggregate_type='conversation',
@@ -1320,12 +1570,22 @@ def workspace_get_shipping_order_review_queue(run_no: str):
run_no=str(run_no),
metadata={'item_count': len(payload.get('items') or [])},
)
return _ok(payload)
response = current_app.make_response(_ok(payload))
response.headers['Server-Timing'] = (
f'queue_lookup;dur={lookup_ms:.1f}, '
f'queue_projection;dur={projection_ms:.1f}'
)
return response
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>', methods=['GET'])
def workspace_get_shipping_order_review_case(case_no: str):
"""读取当前用户的一份 PDF 复核完整快照;Case 编号不能跨 owner 越权访问;访问留痕。"""
"""
读取当前用户的一份 PDF 复核完整快照;Case 编号不能跨 owner 越权访问;访问留痕。
通过 Server-Timing 暴露查找与快照投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变
JSON 响应契约或业务数据。
"""
user = _require_user()
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
from app.services.shipping_notice.fulfillment_audit import record_access_audit
@@ -1335,10 +1595,12 @@ def workspace_get_shipping_order_review_case(case_no: str):
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
# 只读:禁止在 GET 中入队 STP(入队仅抽取收尾 / resume / 显式 retry POST)。
snapshot = build_order_review_case_snapshot(
get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin),
is_admin=is_admin,
)
lookup_started = perf_counter()
review_case = get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin)
lookup_ms = (perf_counter() - lookup_started) * 1000
projection_started = perf_counter()
snapshot = build_order_review_case_snapshot(review_case, is_admin=is_admin)
projection_ms = (perf_counter() - projection_started) * 1000
record_access_audit(
action='view_order_review_case',
aggregate_type='order_review_case',
@@ -1351,7 +1613,12 @@ def workspace_get_shipping_order_review_case(case_no: str):
else None
),
)
return _ok(snapshot)
response = current_app.make_response(_ok(snapshot))
response.headers['Server-Timing'] = (
f'case_lookup;dur={lookup_ms:.1f}, '
f'case_projection;dur={projection_ms:.1f}'
)
return response
@workspace_shipping_notice_bp.route(
@@ -63,12 +63,13 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non
try:
from app.services.shipping_notice.fulfillment_workflow import generate_excel
# [STEP] 为本 OT 生成/刷新发货 Excel;wave_no 写入上下文供审计与后续过滤。
# [STEP] 为本次独立 Notice 生成 Excel,禁止捎带同 PO 的其他项次。
gen = generate_excel({
'task_id': task.task_no,
'wave_no': wave_no,
'line_keys': list(frozen.get('line_keys') or []),
'post_ot_wave': True,
'_orchestrator_internal_dispatch': True,
})
status = str((gen or {}).get('status') or '').strip().lower()
if status in {'failed', 'error'}:
-2
View File
@@ -151,7 +151,6 @@ from app.models.shipping_receipt_report import (
from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession
from app.models.shipping_customer import (
ShippingBusinessSequence,
ShippingCase,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
@@ -290,7 +289,6 @@ __all__ = [
'ShippingCustomerSiteIdentifier',
'ShippingCustomerImportBatch',
'ShippingCustomerImportRow',
'ShippingCase',
'ShippingBusinessSequence',
'ShippingCustomerShadowResolution',
'ShippingCustomerShadowMatch',
+12 -9
View File
@@ -25,6 +25,7 @@ from typing import List, Optional
from sqlalchemy import (
Boolean,
CheckConstraint,
Date,
DateTime,
Float,
ForeignKey,
@@ -54,6 +55,7 @@ class ShippingNotice(Base):
Index('ix_shipping_notices_conversation', 'conversation_id'),
Index('ix_shipping_notices_current_step', 'current_step'),
Index('ix_shipping_notices_upload_status', 'upload_status'),
Index('ix_shipping_notices_business_no', 'business_no'),
Index('ix_shipping_notices_inventory_source_code', 'inventory_source_code'),
Index('ix_shipping_notices_inventory_source_status', 'inventory_source_status'),
Index('ix_shipping_notices_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
@@ -70,11 +72,16 @@ class ShippingNotice(Base):
id: Mapped[int] = mapped_column(primary_key=True)
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
shipping_case_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_cases.id'),
index=True,
nullable=True,
customer_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_customers.id'), index=True, nullable=True,
)
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
# 发货通知单的对外业务编号;同一 PO 的不同波次各自拥有独立编号。
business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True)
business_date: Mapped[Optional[datetime]] = mapped_column(Date, nullable=True)
business_sequence_value: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
business_numbering_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
source_type: Mapped[str] = mapped_column(String(32), default='manual')
@@ -234,11 +241,7 @@ class ShippingNotice(Base):
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
shipping_case: Mapped[Optional['ShippingCase']] = relationship(
'ShippingCase',
back_populates='tasks',
lazy='joined',
)
customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', lazy='joined')
events: Mapped[List['ShippingTaskEvent']] = relationship(
'ShippingTaskEvent',
back_populates='task',
+2 -37
View File
@@ -1,9 +1,9 @@
"""
backend/app/models/shipping_customer.py
用途:货代标准客户、客户识别证据、业务单聚合与业务编号流水模型。
用途:货代标准客户、客户识别证据与业务编号流水模型。
依赖:models.base.Base、users、shipping_notices。
逻辑:客户主数据提供稳定身份;ShippingCase 聚合 Notice 修订链;流水表供后续编号服务原子递增。
逻辑:客户主数据提供稳定身份;发货通知自持履约事实;流水表供编号服务原子递增。
"""
from __future__ import annotations
@@ -55,7 +55,6 @@ class ShippingCustomer(Base):
back_populates='customer',
cascade='all, delete-orphan',
)
cases: Mapped[List['ShippingCase']] = relationship('ShippingCase', back_populates='customer')
merged_into_customer: Mapped[Optional['ShippingCustomer']] = relationship(
'ShippingCustomer',
remote_side='ShippingCustomer.id',
@@ -189,40 +188,6 @@ class ShippingCustomerSiteIdentifier(Base):
site: Mapped['ShippingCustomerSite'] = relationship('ShippingCustomerSite', back_populates='identifiers')
class ShippingCase(Base):
"""一票发货业务聚合;多个线性任务修订版本共享同一业务单。"""
__tablename__ = 'shipping_cases'
__table_args__ = (
Index('ix_shipping_cases_customer_created', 'customer_id', 'created_at'),
Index('ix_shipping_cases_status_created', 'status', 'created_at'),
UniqueConstraint('replaces_case_id', name='uq_shipping_cases_replaces_case_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
case_no: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True)
business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True)
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
business_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
sequence_value: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
numbering_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
numbering_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
status: Mapped[str] = mapped_column(String(32), nullable=False, default='open', server_default='open')
replaces_case_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_cases.id'), nullable=True)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', back_populates='cases')
tasks: Mapped[List['ShippingNotice']] = relationship(
'ShippingNotice',
back_populates='shipping_case',
lazy='selectin',
)
class ShippingBusinessSequence(Base):
"""按业务类型、客户和 Asia/Shanghai 业务日期保存当前流水值。"""
@@ -4,7 +4,7 @@ models/shipping_excel_template.py
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列。
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。
"""
from __future__ import annotations
@@ -12,7 +12,7 @@ from app.models.base import Base
class ShippingFreightCancellation(Base):
"""已上传旧 Notice 的撤销申请与货代回执;成功前新版本不得履约。"""
"""已上传旧 Notice 的撤销申请与外部撤销确认;成功前新版本不得履约。"""
__tablename__ = 'shipping_notice_freight_cancellations'
__table_args__ = (
+2 -1
View File
@@ -155,8 +155,9 @@ class ShippingUploadAttempt(Base):
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
# 历史资产关联字段仅为兼容旧数据;新货代上传不写截图或文件证据。
evidence_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
# [BE-05] RPA 成功时持久化绿色 DOM 证据(kind/selector/observed_at/filename 等)。
# RPA 仅保存最小状态摘要(kind/selector/observed_at/filename 等),不保存截图或 DOM。
success_evidence_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
operator_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
@@ -1,7 +1,7 @@
"""
models/shipping_order_review_wave_line.py
用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一个 Task。
用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一张 Notice。
依赖:ShippingOrderReviewCase、ShippingNotice、ShippingOrderReviewConfirmedRevision。
逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入;
(review_case_id, line_key) 数据库唯一约束防并发重复入波次。
@@ -16,7 +16,6 @@ from sqlalchemy import select
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingBusinessSequence,
ShippingCase,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
@@ -27,6 +26,7 @@ from app.models import (
ShippingOrderCustomerMatch,
ShippingCustomerShadowMatch,
ShippingCustomerShadowResolution,
ShippingNotice,
)
@@ -62,7 +62,7 @@ def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, An
}
shadow_normalized = len(matched_resolution_ids)
blockers = {
'business_cases': db.session.query(ShippingCase.id).filter_by(customer_id=customer.id).count(),
'shipping_notices': db.session.query(ShippingNotice.id).filter_by(customer_id=customer.id).count(),
'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(),
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(),
'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(),
@@ -17,7 +17,6 @@ from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingCase,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
@@ -25,6 +24,7 @@ from app.models import (
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
ShippingIdentityEvidence,
ShippingNotice,
)
from app.services.shipping_notice.customer_normalization import (
clean_text,
@@ -117,7 +117,7 @@ def serialize_customer(
record: ShippingCustomer,
*,
include_identifiers: bool = False,
case_count: int | None = None,
notice_count: int | None = None,
identifier_count: int | None = None,
identity_evidence_count: int | None = None,
) -> dict[str, Any]:
@@ -127,7 +127,7 @@ def serialize_customer(
Args:
record: 标准客户 ORM 记录。
include_identifiers: 是否附带识别证据明细。
case_count: 列表查询预聚合的业务单数量;为空时现场查询。
notice_count: 列表查询预聚合的发货通知数量;为空时现场查询。
identifier_count: 历史固定类型证据数量,仅供存量审计显示。
identity_evidence_count: 配置化客户主体证据数量;为空时现场查询。
Returns:
@@ -144,7 +144,7 @@ def serialize_customer(
'updated_by_id': record.updated_by_id,
'created_at': record.created_at.isoformat() if record.created_at else None,
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
'case_count': case_count if case_count is not None else db.session.query(ShippingCase.id).filter_by(customer_id=record.id).count(),
'notice_count': notice_count if notice_count is not None else db.session.query(ShippingNotice.id).filter_by(customer_id=record.id).count(),
'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(),
'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query(
ShippingIdentityEvidence.id,
@@ -173,9 +173,9 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
Returns:
items、total、page、page_size、pages。
"""
case_counts = (
db.session.query(ShippingCase.customer_id.label('customer_id'), func.count(ShippingCase.id).label('case_count'))
.group_by(ShippingCase.customer_id)
notice_counts = (
db.session.query(ShippingNotice.customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count'))
.group_by(ShippingNotice.customer_id)
.subquery()
)
identifier_counts = (
@@ -207,12 +207,12 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
query = (
db.session.query(
ShippingCustomer,
func.coalesce(case_counts.c.case_count, 0),
func.coalesce(notice_counts.c.notice_count, 0),
func.coalesce(identifier_counts.c.identifier_count, 0),
func.coalesce(identity_evidence_counts.c.identity_evidence_count, 0)
+ func.coalesce(site_identity_evidence_counts.c.identity_evidence_count, 0),
)
.outerjoin(case_counts, case_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(notice_counts, notice_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(identifier_counts, identifier_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(identity_evidence_counts, identity_evidence_counts.c.customer_id == ShippingCustomer.id)
.outerjoin(site_identity_evidence_counts, site_identity_evidence_counts.c.customer_id == ShippingCustomer.id)
@@ -244,10 +244,10 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
return {
'items': [
serialize_customer(
customer, case_count=int(case_count), identifier_count=int(identifier_count),
customer, notice_count=int(notice_count), identifier_count=int(identifier_count),
identity_evidence_count=int(identity_evidence_count),
)
for customer, case_count, identifier_count, identity_evidence_count in items
for customer, notice_count, identifier_count, identity_evidence_count in items
],
'total': total,
'page': page,
@@ -301,9 +301,9 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi
pending_seen = True
if gate.status in {'pending', 'blocked_retryable'}:
return gate, None
# 上传回执是人工完成的外部事实,不是“重试业务动作”。登记成功后仅允许
# 服务端重新读取该事实并通过最后一个 Gate。
if gate.gate_code == 'upload_receipt_recorded' and gate.status == 'blocked_manual':
# 人工上传确认是外部完成声明,不是“重试业务动作”。确认成功后仅允许
# 服务端重新读取 Attempt 事实并通过最后一个 Gate。
if gate.gate_code == 'manual_upload_handoff' and gate.status == 'blocked_manual':
return gate, None
return None, None
return None, None
@@ -1,88 +0,0 @@
"""
services/shipping_notice/business_case_service.py
用途:为新建货代任务创建或继承业务单聚合。
依赖:db、ShippingCase、ShippingNotice、uuid/datetime。
逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from app import db
from app.core.errors import ConflictError
from app.models import ShippingCase, ShippingNotice
def generate_shipping_case_no() -> str:
"""生成内部业务单聚合编号;仅用于系统关联,不对外替代 business_no。"""
return f"SC-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
def create_shipping_case(*, created_by_id: int | None = None) -> ShippingCase:
"""
创建未绑定客户、未编号的业务单聚合。
Args:
created_by_id: 创建任务的用户 ID,可为空。
Returns:
尚未提交事务的 ShippingCase。
"""
case = ShippingCase(
case_no=generate_shipping_case_no(),
created_by_id=created_by_id,
numbering_status='pending',
status='open',
)
db.session.add(case)
db.session.flush()
return case
def resolve_shipping_case_for_new_task(
*,
supersedes_task_id: int | None = None,
duplicate_resolution_type: str | None = None,
created_by_id: int | None = None,
) -> ShippingCase:
"""
为即将创建的任务解析业务单归属。
核心逻辑:revision 必须继承父任务业务单;normal/force_create 均创建独立业务单,
保证强制新建重新占用未来流水。
Args:
supersedes_task_id: 修订目标任务主键,仅 revision 使用。
duplicate_resolution_type: normal/revision/force_create。
created_by_id: 新任务创建人。
Returns:
新任务应关联的 ShippingCase。
Raises:
ConflictError: revision 缺少或找不到父任务。
"""
resolution_type = str(duplicate_resolution_type or 'normal').strip().lower()
if resolution_type != 'revision':
return create_shipping_case(created_by_id=created_by_id)
if not supersedes_task_id:
raise ConflictError(
'修订任务缺少父任务',
code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
)
parent = db.session.get(ShippingNotice, int(supersedes_task_id))
if parent is None:
raise ConflictError(
'修订目标任务不存在',
code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
details={'supersedes_task_id': supersedes_task_id},
)
if parent.shipping_case is None:
raise ConflictError(
'修订目标任务缺少业务单关联',
code='SHIPPING_NOTICE.REVISION_CASE_MISSING',
details={'supersedes_task_id': supersedes_task_id},
)
return parent.shipping_case
@@ -2,7 +2,7 @@
services/shipping_notice/business_numbering_service.py
用途:为已确认客户的货代业务单分配不可变业务编号。
依赖:ShippingCase/Customer/BusinessSequence、Asia/Shanghai 时区、SQLAlchemy 方言能力。
依赖:ShippingNotice/Customer/BusinessSequence、Asia/Shanghai 时区、SQLAlchemy 方言能力。
逻辑:锁定业务单后按客户与上海业务日期原子递增流水;编号写入业务单快照,事务由调用方提交。
"""
@@ -15,7 +15,7 @@ from sqlalchemy import update
from app import db
from app.core.errors import ConflictError
from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice
from app.services.shipping_notice.customer_normalization import SHORT_CODE_RE
BUSINESS_TYPE = "shipping_notice"
@@ -121,50 +121,46 @@ def _next_sequence_value(customer_id: int, business_date: date) -> int:
return int(value)
def assign_business_number(case: ShippingCase, *, moment: datetime | None = None) -> str:
def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime | None = None) -> str:
"""
为业务单幂等分配业务编号,调用方负责同事务提交。
核心逻辑:已有编号直接返回;否则校验启用客户与简码快照,取得上海日期流水并写入不可变编号字段。
为单个发货通知分配不可变业务编号;同一 PO 的不同通知单不会复用编号。
Args:
case: 已加锁且已绑定标准客户的业务单。
moment: 可选测试时刻。
Returns:
分配或已存在的业务编号。
Raises:
ConflictError: 客户无效、简码缺失或当日两位流水耗尽。
"""
if case.business_no:
return str(case.business_no)
if case.customer_id is None:
raise ConflictError(
"Shipping case customer must be confirmed before numbering",
code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED",
)
customer = db.session.get(ShippingCustomer, int(case.customer_id))
if customer is None or customer.status != "active":
raise ConflictError(
"Active customer is required before numbering",
code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_INVALID",
)
notice: 已绑定客户的 ShippingNotice;客户事实只读取 Notice 本身。
moment: 可选时刻,测试时用于固定上海业务日期。
short_code = str(customer.short_code or "").strip().upper()
Returns:
分配或已存在的 business_no。
Raises:
ConflictError: 通知单缺少客户或客户无效。
"""
if notice.business_no:
return str(notice.business_no)
if notice.customer_id is None:
raise ConflictError(
'Shipping notice customer must be confirmed before numbering',
code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED',
)
customer = db.session.get(ShippingCustomer, int(notice.customer_id))
if customer is None or customer.status != 'active':
raise ConflictError(
'Active customer is required before numbering',
code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_INVALID',
)
short_code = str(customer.short_code or '').strip().upper()
if not SHORT_CODE_RE.fullmatch(short_code):
raise ConflictError(
"Customer short code is invalid for business numbering",
code="SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID",
details={"customer_id": customer.id, "short_code": short_code},
'Customer short code is invalid for business numbering',
code='SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID',
)
business_date = shanghai_business_date(moment)
sequence_value = _next_sequence_value(customer.id, business_date)
business_no = format_business_no(short_code, business_date, sequence_value)
case.customer_name_snapshot = customer.standard_name
case.customer_short_code_snapshot = short_code
case.business_date = business_date
case.sequence_value = sequence_value
case.numbering_rule_version = NUMBERING_RULE_VERSION
case.numbering_status = "assigned"
case.business_no = business_no
notice.business_no = format_business_no(short_code, business_date, sequence_value)
notice.business_date = business_date
notice.business_sequence_value = sequence_value
notice.business_numbering_rule_version = NUMBERING_RULE_VERSION
notice.customer_name_snapshot = customer.standard_name
notice.customer_short_code_snapshot = short_code
db.session.flush()
return business_no
return str(notice.business_no)
@@ -25,8 +25,6 @@ CANDIDATE_QUALIFICATION_STATUSES: Final[frozenset[str]] = frozenset({
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v3.0-unified-profile'
# 统一检查顺序(不可重排):后置项依赖前置放行语义由服务层解释。
# VC 门禁 vc_source_merged_clean 放在 field_conflicts_resolved 之后,
# 以便冲突项先被 PDF 优先裁决,剩余 needs_review 项再由本门禁拦截。
CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
'auto_create_enabled',
'route_stp_eligible',
@@ -35,7 +33,6 @@ CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
'key_fields_minimum_confidence',
'evidence_complete',
'field_conflicts_resolved',
'vc_source_merged_clean',
'duplicate_resolved',
'customer_confirmed',
'idempotency_ok',
@@ -50,7 +47,6 @@ CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = {
'key_fields_minimum_confidence': 'field_low_confidence',
'evidence_complete': 'evidence_missing',
'field_conflicts_resolved': 'field_conflict',
'vc_source_merged_clean': 'vc_source_conflict_unresolved',
'duplicate_resolved': 'duplicate_unresolved',
'customer_confirmed': 'customer_confirmation_required',
'idempotency_ok': 'task_already_exists',
@@ -67,8 +63,6 @@ CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES: Final[frozenset[str]] = frozenset({
'field_low_confidence',
# PDF 优先已选定当前值,但仍须人工确认冲突后方可自动建单。
'pdf_preferred_critical_conflict',
# Vendor Comments 三来源值不一致,须人工裁决但不硬阻塞人工建单。
'vc_source_conflict_unresolved',
})
# 解析来源(写入 parser_trace,不直接决定资格)。
@@ -35,11 +35,6 @@ from app.services.shipping_notice.candidate_qualification_contract import (
CANDIDATE_QUALIFICATION_GATE_REASON_CODES,
CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES,
)
from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import (
CQ_VC_BLOCKING_REASONS,
CQ_VC_REVIEW_REASONS,
collect_vc_candidate_conflicts,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.services.shipping_notice.tool_common import extraction_emergency_stop_enabled
@@ -126,10 +121,6 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
核心逻辑:过滤仅描述文档版面/坐标质量的诊断项;字段值冲突、跨来源冲突
与其他未知阻断项继续 fail-closed。
注意:Vendor Comments 三来源冲突由独立 vc_source_merged_clean 门禁
(见 _vc_gate_ok)评估,不入本集合,避免污染 field_conflicts_resolved
原有零回归语义。
Args:
candidate: ShippingOrderCandidate 或兼容替身。
@@ -164,66 +155,14 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
return blocking
# ---------------------------------------------------------------------------
# VC 三来源门禁:独立于 Candidate.conflicts_json,从 structured.extraction
# vendor_comments_merged 读,避免冲突历史与裁决历史相互污染。
# ---------------------------------------------------------------------------
def _vc_gate_ok(candidate: Any) -> bool:
def current_open_candidate_conflicts(candidate: Any) -> list[Any]:
"""返回当前仍开放且会阻断自动建单的 Candidate 冲突。
复核投影与资格门禁必须共享这一入口:历史冲突记录只有在明确标记为
``blocking + unresolved`` 时才是当前阻断事实;无法判定的旧结构继续
fail-closed,避免通过空投影或猜测放行自动建单。
"""
VC 三来源合并结果是否全部清洁(无阻断冲突)。
核心逻辑:缺 VC merged 载荷 → 视为未启用 → OK;
severity == blocking 的项 → 必须视为 fail(硬阻断);
severity == review_required 但 can_auto_create 场景下同样 fail,
交由上层 CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES 归类到
review_required 总体状态(允许人工建单,不允许 STP 自动建单)。
Args:
candidate: ShippingOrderCandidate 或兼容替身。
Returns:
True 表示 VC 路径「已干净」,可放行自动/人工建单。
"""
try:
items = collect_vc_candidate_conflicts(candidate)
except Exception: # noqa: BLE001 — 门禁 fail-closed:解析异常视为未通过
return False
for it in items:
if not isinstance(it, dict):
continue
severity = str(it.get('severity') or 'blocking').strip()
reason = str(it.get('reason') or '').strip()
if reason in CQ_VC_BLOCKING_REASONS:
return False
if severity == 'blocking':
return False
if severity == 'review_required':
# review_required 对自动建单门禁同样算失败(上层会映射为 review_required 总体状态)
# 对人工建单是允许的,但 CQ 门禁统一口径:needs_review → fail;
# 人工建单的门禁是独立路径,在 order_review_confirmation_service 中。
return False
return True
def _vc_fine_grained_reason(candidate: Any) -> str | None:
"""
VC 门禁失败时提取首个匹配的细因码,优先给出 format/region 错,
冲突类错其次,保留默认 vc_source_conflict_unresolved 兜底。
"""
try:
items = collect_vc_candidate_conflicts(candidate)
except Exception: # noqa: BLE001
return None
priority_order = [
'vc_source_region_unbound',
'vc_source_format_invalid',
'vc_source_conflict_unresolved',
]
seen = {str(x.get('reason') or '').strip() for x in items if isinstance(x, dict)}
for want in priority_order:
if want in seen:
return want
return None
return blocking_candidate_conflicts(candidate)
def resolve_candidate_customer_resolved(
@@ -410,7 +349,6 @@ def evaluate_candidate_qualification(
)
evidence_ok = _evidence_ok(candidate)
conflicts_ok = _conflicts_ok(candidate)
vc_ok = _vc_gate_ok(candidate)
duplicate_ok = _duplicate_ok(candidate)
customer_ok, customer_reason = _customer_ok(candidate, customer_resolved=customer_resolved)
idempotency_ok = _idempotency_ok(candidate)
@@ -423,7 +361,6 @@ def evaluate_candidate_qualification(
'key_fields_minimum_confidence': key_confidence_ok,
'evidence_complete': evidence_ok,
'field_conflicts_resolved': conflicts_ok,
'vc_source_merged_clean': vc_ok,
'duplicate_resolved': duplicate_ok,
'customer_confirmed': customer_ok,
'idempotency_ok': idempotency_ok,
@@ -441,11 +378,6 @@ def evaluate_candidate_qualification(
if pdf_reason:
blocking_reason_codes.append(pdf_reason)
continue
if key == 'vc_source_merged_clean':
vc_reason = _vc_fine_grained_reason(candidate)
if vc_reason:
blocking_reason_codes.append(vc_reason)
continue
blocking_reason_codes.append(
CANDIDATE_QUALIFICATION_GATE_REASON_CODES.get(key, 'order_freeze_not_ready')
)
@@ -459,20 +391,7 @@ def evaluate_candidate_qualification(
blocking_reason_codes=blocking_reason_codes,
)
# [STEP 3b] 证据快照追加 VC 合并概览(脱敏,仅计数)—— 注意:必须在 STEP 4 status
# 计算之后执行,因为 status 不依赖 evidence_snapshot,保证零回归。
evidence_snapshot = _evidence_snapshot(candidate)
try:
vc_items = collect_vc_candidate_conflicts(candidate)
except Exception: # noqa: BLE001
vc_items = []
vc_counts = {
'vc_total_candidates': len(vc_items),
'vc_review_required': len([x for x in vc_items if isinstance(x, dict) and str(x.get('severity') or '') == 'review_required']),
'vc_blocking': len([x for x in vc_items if isinstance(x, dict) and str(x.get('severity') or '') == 'blocking']),
}
if vc_counts['vc_total_candidates']:
evidence_snapshot = {**evidence_snapshot, **vc_counts}
score = _qualification_score(gates)
confidence_policy = {
'minimum_confidence': float(min_confidence),
@@ -15,7 +15,6 @@ from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingCase,
ShippingCustomer,
ShippingCustomerShadowResolution,
ShippingIdentityEvidence,
@@ -35,9 +34,8 @@ from app.services.shipping_notice.customer_normalization import (
normalize_domain,
normalize_email,
)
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int
from app.services.shipping_notice.business_case_service import generate_shipping_case_no
from app.services.shipping_notice.business_numbering_service import assign_business_number
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, generate_task_no
from app.services.shipping_notice.business_numbering_service import assign_notice_business_number
AUTO_RESOLUTION_VERSION = "customer-auto-v2"
CUSTOMER_AUDIT_EVENT_TYPES = (
@@ -297,8 +295,18 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
Returns:
status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。
"""
# [PARAM_TUNING] 业务策略改为:已发布识别指纹唯一命中即可自动确认;
# 不再以全局开关、历史标注样本量或准确率二次阻断唯一确定结果。
# [STEP 1] 总开关关闭时不评估证据,保证环境可安全降级至人工确认。
if not auto_customer_resolution_enabled():
return {
'status': 'disabled',
'rule_version': AUTO_RESOLUTION_VERSION,
'customer_id': None,
'evidence': [],
'quality_gate': {
'status': 'disabled',
'is_eligible': False,
},
}
if task.source_candidate_id is None:
return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
shadow = db.session.query(ShippingCustomerShadowResolution).filter_by(
@@ -313,11 +321,16 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
if shadow is None:
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
return {**_resolve_auto_customer_from_shadow_resolution(shadow), 'quality_gate': {
'status': 'bypassed_unique_match_policy',
'is_eligible': True,
'reason': '唯一识别指纹命中直接自动确认',
}}
decision = _resolve_auto_customer_from_shadow_resolution(shadow)
quality_gate = _auto_confirmation_quality_gate()
if not quality_gate['is_eligible']:
return {
**decision,
'status': str(quality_gate['status']),
'customer_id': None,
'quality_gate': quality_gate,
}
return {**decision, 'quality_gate': quality_gate}
def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
@@ -327,7 +340,7 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
核心逻辑:先写自动裁决审计,再复用人工确认的锁与编号事务;成功后将确认方法改为 auto_rule。
"""
if task.customer_resolution_status == "confirmed":
return {"status": "already_confirmed", "customer_id": task.shipping_case.customer_id if task.shipping_case else None}
return {"status": "already_confirmed", "customer_id": task.customer_id}
decision = resolve_auto_customer_from_shadow(task)
db.session.add(ShippingTaskEvent(
task_id=task.id,
@@ -350,11 +363,11 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
event_type="customer_auto_confirmed",
detail_json={
**decision,
"business_no": updated.shipping_case.business_no if updated.shipping_case else None,
"business_no": updated.business_no,
},
))
db.session.flush()
return {**decision, "status": "auto_confirmed", "business_no": updated.shipping_case.business_no}
return {**decision, "status": "auto_confirmed", "business_no": updated.business_no}
def correct_numbered_task_customer(
@@ -365,10 +378,10 @@ def correct_numbered_task_customer(
actor_id: int | None,
) -> dict[str, Any]:
"""
更正已编号业务单的标准客户,同时保留原号作废与替代关系。
更正已编号 Notice 的标准客户,同时保留原号作废与替代关系。
核心逻辑:锁定原业务单并校验未上传 → 创建替代业务单和新号 → 迁移整条任务版本链 →
清理当前版本的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。
核心逻辑:锁定原 Notice 并校验未上传 → 创建替代 Notice 和新号 → 作废原 Notice →
清理新 Notice 的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。
Args:
task: 原业务号或技术号定位到的当前任务版本。
@@ -387,31 +400,23 @@ def correct_numbered_task_customer(
"Customer correction reason is required",
code="SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED",
)
if task.shipping_case_id is None:
raise ConflictError(
"Numbered shipping case is required for customer correction",
code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED",
)
original_case = (
db.session.query(ShippingCase)
.filter(ShippingCase.id == int(task.shipping_case_id))
original = (
db.session.query(ShippingNotice)
.filter(ShippingNotice.id == int(task.id))
.with_for_update()
.one_or_none()
)
if original_case is None:
raise NotFoundError("Shipping case not found", code="SHIPPING.CASE_NOT_FOUND")
if not original_case.business_no:
if original is None or not original.business_no:
raise ConflictError(
"Numbered shipping case is required for customer correction",
"Numbered shipping notice is required for customer correction",
code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED",
)
existing_replacement = db.session.query(ShippingCase.id).filter_by(
replaces_case_id=original_case.id,
existing_replacement = db.session.query(ShippingNotice.id).filter_by(
supersedes_task_id=original.id,
).first()
if existing_replacement is not None or original_case.status == "voided":
if existing_replacement is not None or str(original.lifecycle_status or '') == 'voided':
raise ConflictError(
"Shipping case has already been replaced",
"Shipping notice has already been replaced",
code="SHIPPING.CUSTOMER_CORRECTION_ALREADY_REPLACED",
)
@@ -422,117 +427,79 @@ def correct_numbered_task_customer(
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_case.customer_id == customer.id:
if original.customer_id == customer.id:
raise ValidationError(
"Corrected customer must differ from the current customer",
code="SHIPPING.CUSTOMER_CORRECTION_UNCHANGED",
)
versions = (
db.session.query(ShippingNotice)
.filter_by(shipping_case_id=original_case.id)
.order_by(ShippingNotice.document_version.asc(), ShippingNotice.id.asc())
.with_for_update()
.all()
)
if not versions:
if str(getattr(original, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}:
raise ConflictError(
"Shipping case has no task versions",
code="SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING",
)
if any(
str(getattr(version, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}
or str(version.upload_status or "").lower() in {"uploaded", "succeeded", "success"}
for version in versions
):
raise ConflictError(
"Uploaded shipping cases require an external cancellation workflow before correction",
"Uploaded shipping notices require an external cancellation workflow before correction",
code="SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED",
)
old_business_no = str(original_case.business_no)
replacement = ShippingCase(
case_no=generate_shipping_case_no(),
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,
numbering_status="pending",
status="open",
replaces_case_id=original_case.id,
created_by_id=actor_id,
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_business_number(replacement)
original_case.status = "voided"
original_case.numbering_status = "voided"
now = datetime.utcnow()
customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest()
latest = max(versions, key=lambda item: (int(item.document_version or 1), int(item.id)))
for version in versions:
version.shipping_case_id = replacement.id
version.customer_resolution_status = "confirmed"
version.customer_resolution_method = "admin_correction"
version.customer_identity_fingerprint = customer_fingerprint
version.customer_confirmed_by = actor_id
version.customer_confirmed_at = now
db.session.add(ShippingTaskEvent(
task_id=version.id,
event_type="customer_correction_applied",
detail_json={
"old_case_id": original_case.id,
"new_case_id": replacement.id,
"old_business_no": old_business_no,
"new_business_no": new_business_no,
"old_customer_id": original_case.customer_id,
"new_customer_id": customer.id,
"reason": correction_reason,
"actor_id": actor_id,
},
))
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))
# 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。
latest.inventory_source_code = None
latest.inventory_connector_type = None
latest.inventory_warehouse_id = None
latest.inventory_source_status = None
latest.inventory_source_method = None
latest.inventory_source_confirmed_by = None
latest.inventory_source_confirmed_at = None
latest.inventory_source_config_version = None
latest.inventory_routing_fingerprint = None
latest.inventory_rpa_consumed_run_no = None
latest.inventory_snapshot_id = None
latest.inventory_lines_json = None
latest.match_status = None
latest.shortage_json = None
latest.line_results_json = None
latest.export_file_path = None
latest.export_file_name = None
latest.freight_ref_no = None
latest.upload_status = None
latest.upload_mode = None
latest.upload_attempt = 0
latest.upload_started_at = None
latest.upload_finished_at = None
latest.upload_error_code = None
latest.upload_error_message = None
latest.upload_receipt_json = None
latest.idempotency_key = None
latest.current_step = None
latest.review_status = None
latest.pending_human_reason = None
latest.error_message = None
db.session.commit()
return {
"task_no": latest.task_no,
"old_case_id": original_case.id,
"new_case_id": replacement.id,
"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": len(versions),
"affected_task_count": 1,
}
@@ -16,21 +16,17 @@ from sqlalchemy import or_
from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent
from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice.customer_normalization import clean_text
from app.services.shipping_notice.business_numbering_service import assign_business_number
CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
def customer_identity_is_confirmed(task: ShippingNotice) -> bool:
"""判断任务是否已关联业务单并通过标准客户确认。"""
if task.shipping_case_id is None:
"""判断 Notice 自身是否已通过标准客户确认。"""
if task.customer_id is None:
return False
case = task.shipping_case or db.session.get(ShippingCase, int(task.shipping_case_id))
if case is None or case.customer_id is None:
return False
customer = db.session.get(ShippingCustomer, int(case.customer_id))
customer = db.session.get(ShippingCustomer, int(task.customer_id))
return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed')
@@ -46,9 +42,6 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con
"""
if customer_identity_is_confirmed(task):
return
case = task.shipping_case or (
db.session.get(ShippingCase, int(task.shipping_case_id)) if task.shipping_case_id else None
)
raise AppError(
code=CUSTOMER_GATE_ERROR_CODE,
message='标准客户尚未确认,无法继续后续流程',
@@ -56,9 +49,8 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con
details={
'operation': operation,
'task_no': task.task_no,
'shipping_case_id': task.shipping_case_id,
'customer_resolution_status': task.customer_resolution_status or 'pending',
'customer_id': case.customer_id if case else None,
'customer_id': task.customer_id,
},
)
@@ -87,10 +79,10 @@ def confirm_task_customer(
commit: bool = True,
) -> ShippingNotice:
"""
人工确认任务所属标准客户,并同步共享业务单下所有任务版本。
人工确认 Notice 所属标准客户;业务编号留待首次 Excel 生成时分配。
核心逻辑:锁定业务单 → 校验启用客户 → 原子分配业务号 → 同步 revision 任务确认状态和事件。
客户确认与编号同事务提交,任何一步失败都不留下半确认状态。
核心逻辑:锁定客户归属 → 校验启用客户 → 固化 Notice 客户快照。
客户确认与客户快照同事务提交;业务编号由 Excel 生成事务独占写入。
Args:
task: 待确认客户的任务。
@@ -99,19 +91,14 @@ def confirm_task_customer(
resolution_method: manual/auto_rule 等审计方法。
commit: 是否提交事务;批次编排传 False 由外层统一提交。
"""
if task.shipping_case_id is None:
raise ConflictError(
'Shipping task is missing its required shipping case',
code='SHIPPING.CUSTOMER_CASE_REQUIRED',
)
case = (
db.session.query(ShippingCase)
.filter(ShippingCase.id == int(task.shipping_case_id))
.with_for_update()
.one_or_none()
task = (
db.session.query(ShippingNotice)
.filter(ShippingNotice.id == int(task.id))
# ShippingNotice.customer 使用 joined eager load,会形成 LEFT OUTER JOIN;
# PostgreSQL 不允许锁定该连接的可空侧,故只锁当前 Notice 行。
.with_for_update(of=ShippingNotice)
.one()
)
if case is None:
raise NotFoundError('Shipping case not found', code='SHIPPING.CASE_NOT_FOUND')
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
@@ -119,50 +106,35 @@ def confirm_task_customer(
raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
if customer.status != 'active':
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
if case.business_no and case.customer_id not in {None, customer.id}:
if task.business_no and task.customer_id not in {None, customer.id}:
raise ConflictError(
'Numbered shipping case customer cannot be changed silently',
code='SHIPPING.CUSTOMER_NUMBERED_CASE_LOCKED',
'Numbered shipping notice customer cannot be changed silently',
code='SHIPPING.CUSTOMER_NUMBERED_NOTICE_LOCKED',
)
now = datetime.utcnow()
previous_customer_id = case.customer_id
number_was_assigned = bool(case.business_no)
case.customer_id = customer.id
case.customer_name_snapshot = customer.standard_name
case.customer_short_code_snapshot = customer.short_code
business_no = assign_business_number(case)
previous_customer_id = task.customer_id
task.customer_id = customer.id
task.customer_name_snapshot = customer.standard_name
task.customer_short_code_snapshot = customer.short_code
fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest()
tasks = db.session.query(ShippingNotice).filter_by(shipping_case_id=case.id).all()
for version in tasks:
version.customer_resolution_status = 'confirmed'
version.customer_resolution_method = resolution_method
version.customer_identity_fingerprint = fingerprint
version.customer_confirmed_by = actor_id
version.customer_confirmed_at = now
db.session.add(ShippingTaskEvent(
task_id=version.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': business_no,
},
))
if not number_was_assigned:
db.session.add(ShippingTaskEvent(
task_id=version.id,
event_type='business_number_assigned',
detail_json={
'business_no': business_no,
'business_date': case.business_date.isoformat() if case.business_date else None,
'sequence_value': case.sequence_value,
'numbering_rule_version': case.numbering_rule_version,
},
))
task.customer_resolution_status = 'confirmed'
task.customer_resolution_method = resolution_method
task.customer_identity_fingerprint = fingerprint
task.customer_confirmed_by = actor_id
task.customer_confirmed_at = now
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:
db.session.commit()
return db.session.get(ShippingNotice, int(task.id))
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/customer_shadow_resolution.py
用途:对订单 Candidate 执行只读客户影子识别,并提供质量报告与人工标签。
依赖:客户主数据/识别证据、Candidate/Intake、customer_normalization。
逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingCase、ShippingNotice 或业务编号。
逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingNotice 或业务编号。
"""
from __future__ import annotations
@@ -1,231 +0,0 @@
"""
services/shipping_notice/document_layout/coordinate_region_source_adapter.py
用途:CoordinateRegionSourceAdapter——将 Profile.named_regions 圈选的物理区域映射为
可直接送入 Split Core 的区域原文 + 可引用 bbox 证据(page_no + 绝对坐标)。
依赖:profile_vendor_comments_contract.NamedRegion;coordinate_region_text.read_coordinate_region_text
与 visual_glyph_rows + positioned_token_spans(证据粒度生成)。
逻辑:不读 MinIO、不查 DB;只接收 caller 已加载的 glyphs/page 字典;严格按 Q14 约定
page_scope 规则选择「代表页」——last_page 时从多页集合取末页;失败不抛错,统一
返回 status=unavailable + 诊断码,供上游 ProfileFieldSourceMappingService 分支处理。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal
from app.services.shipping_notice.document_layout.coordinate_region_text import (
positioned_token_spans,
read_coordinate_region_text,
)
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
NamedRegion,
)
@dataclass
class CoordinateRegionEvidence:
"""单个命中的 token 级证据——供 Observation.evidence_metadata_json 直接序列化。"""
page_no: int
text: str
x0: float # 0..1 归一化
x1: float
y0: float
y1: float
@dataclass
class CoordinateRegionSourceResult:
"""区域抽取结果——对齐 Split Core 结果形状但不做拆分,仅负责原文渲染。"""
region_id: str
label: str
status: Literal['available', 'unavailable']
page_no: int | None = None
raw_text: str = ''
lines: list[str] = field(default_factory=list)
evidence_tokens: list[CoordinateRegionEvidence] = field(default_factory=list)
diagnostic_code: str | None = None
diagnostic_message: str | None = None
class CoordinateRegionSourceAdapter:
"""
将 NamedRegion → 原文 + 证据的薄适配器。
【AI 触发时机】:三来源收集阶段,上游遍历 field_source_mappings[].vendor_comments_enabled
条目并引用命名区域 ID 时调用。
核心逻辑:
[STEP 1] 按 page_scope 从 page_glyphs_map 中选「代表页」:
first_page → pages[0];last_page → pages[-1];all_pages 只看 p0(仅用于区域);
exact_page → 严格匹配 1-based page_no。
[STEP 2] 调 read_coordinate_region_text 取区域原文(0..1 归一化坐标)。
[STEP 3] 调 positioned_token_spans 生成 token 级 bbox 证据,用于 Review 高亮点位。
[STEP 4] 原文按换行拆为 lines,供后续 execute_base_split_rule_set(..., lines=) 复用。
Args:
region: NamedRegion 契约对象(已通过 validate_assignment 校验)。
page_glyphs_map: {1-based_page_no: {'glyphs': [...], 'page': {'width','height'}}} ——
caller 负责按当前 Document 加载,本类无网络 IO。
"""
def __init__(self, region: NamedRegion, page_glyphs_map: dict[int, dict[str, Any]]):
self.region = region
self.page_glyphs_map = page_glyphs_map
# ------------------------------------------------------------------
# 对外入口
# ------------------------------------------------------------------
def extract(self) -> CoordinateRegionSourceResult:
"""
执行区域抽取。失败不抛异常,统一置 status=unavailable + 稳定诊断码。
Returns:
CoordinateRegionSourceResult,上游据此决定是否跳过 Vendor Comments 来源。
"""
# [STEP 1] 选择代表页
page_no = self._resolve_representative_page_no()
if page_no is None:
return CoordinateRegionSourceResult(
region_id=self.region.region_id,
label=self.region.label,
status='unavailable',
diagnostic_code='named_region_page_not_found',
diagnostic_message=(
f'named region {self.region.region_id!r} page_scope={self.region.page_scope} '
f'page_no={self.region.page_no!r} has no loaded page'
),
)
page_bundle = self.page_glyphs_map[page_no]
glyphs = list(page_bundle.get('glyphs') or [])
page = dict(page_bundle.get('page') or {})
if not glyphs or 'width' not in page or 'height' not in page:
return CoordinateRegionSourceResult(
region_id=self.region.region_id,
label=self.region.label,
status='unavailable',
page_no=page_no,
diagnostic_code='named_region_empty_glyphs',
diagnostic_message='region target page has empty glyphs or missing page size',
)
region_coords = {
'x0': self.region.region.x0, 'y0': self.region.region.y0,
'x1': self.region.region.x1, 'y1': self.region.region.y1,
}
# [STEP 2] 渲染区域原文
raw_text = read_coordinate_region_text(
glyphs=glyphs, page=page, region=region_coords,
)
if not raw_text.strip():
return CoordinateRegionSourceResult(
region_id=self.region.region_id,
label=self.region.label,
status='unavailable',
page_no=page_no,
diagnostic_code='named_region_text_empty',
diagnostic_message=f'named region {self.region.region_id!r} has empty body text',
)
# [STEP 3] 生成 token 级证据(只保留区域中心在 box 内的 token)
tokens = self._collect_region_evidence_tokens(
glyphs=glyphs, page=page, region_coords=region_coords, page_no=page_no,
)
# [STEP 4] 拆行
lines = [ln.strip() for ln in raw_text.splitlines() if ln.strip()]
return CoordinateRegionSourceResult(
region_id=self.region.region_id,
label=self.region.label,
status='available',
page_no=page_no,
raw_text=raw_text.strip(),
lines=lines,
evidence_tokens=tokens,
)
# ------------------------------------------------------------------
# 内部帮助
# ------------------------------------------------------------------
def _resolve_representative_page_no(self) -> int | None:
"""按 page_scope 规则选择代表页。"""
sorted_pages = sorted(self.page_glyphs_map.keys())
if not sorted_pages:
return None
scope = self.region.page_scope
if scope == 'first_page':
return sorted_pages[0]
if scope == 'last_page':
return sorted_pages[-1]
if scope == 'all_pages':
# all_pages 的命名区域仅在第一页渲染(常见全页 Header);
# 若管理员要取多页块,应拆为多个命名区域并使用 exact_page。
return sorted_pages[0]
if scope == 'exact_page':
return self.region.page_no if self.region.page_no in self.page_glyphs_map else None
return None
@staticmethod
def _collect_region_evidence_tokens(
*,
glyphs: list[dict[str, Any]],
page: dict[str, Any],
region_coords: dict[str, float],
page_no: int,
) -> list[CoordinateRegionEvidence]:
"""筛选命名区域中心范围内的 token,并返回 0..1 归一化 bbox。"""
width, height = float(page['width']), float(page['height'])
rx0, ry0, rx1, ry1 = (region_coords[k] for k in ('x0', 'y0', 'x1', 'y1'))
all_spans = positioned_token_spans(glyphs, respect_explicit_spaces=True)
selected: list[CoordinateRegionEvidence] = []
for span in all_spans:
sx0 = float(span['x0']) / width
sx1 = float(span['x1']) / width
text = str(span.get('text') or '')
# y 边界:span 只返回横向边界;glyphs 中心用于 y 判定
# positioned_token_spans 不返回 y,重算 y0/y1 需回溯原 glyph——这里直接用
# glyphs 子集重算以保证引用不泄漏。
matched = [
g for g in glyphs
if _glyph_intersects_span(g, span, width) and _glyph_in_region_center(g, width, height, rx0, ry0, rx1, ry1)
]
if not matched:
continue
min_y0 = min(float(g['bbox']['y0']) / height for g in matched)
max_y1 = max(float(g['bbox']['y1']) / height for g in matched)
selected.append(CoordinateRegionEvidence(
page_no=page_no,
text=text,
x0=sx0, x1=sx1,
y0=min_y0, y1=max_y1,
))
return selected
def _glyph_intersects_span(glyph: dict[str, Any], span: dict[str, Any], width: float) -> bool:
try:
gx0 = float(glyph['bbox']['x0']) / width
gx1 = float(glyph['bbox']['x1']) / width
except (KeyError, TypeError, ValueError):
return False
return min(gx1, float(span['x1']) / width) > max(gx0, float(span['x0']) / width)
def _glyph_in_region_center(
glyph: dict[str, Any], width: float, height: float,
rx0: float, ry0: float, rx1: float, ry1: float,
) -> bool:
try:
b = glyph['bbox']
cx = (float(b['x0']) + float(b['x1'])) / (2 * width)
cy = (float(b['y0']) + float(b['y1'])) / (2 * height)
except (KeyError, TypeError, ValueError):
return False
return rx0 <= cx <= rx1 and ry0 <= cy <= ry1
@@ -22,6 +22,7 @@ from app.services.shipping_notice.document_layout.coordinate_transform import (
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
from app.services.shipping_notice.reservation_id import validated_reservation_id
@@ -31,6 +32,186 @@ _DELETED_PATTERN = re.compile(r'^\*+itemdeleted\*+$', re.IGNORECASE)
DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no'
def reconstruction_exclusion_regions(
table_region: dict[str, Any], *, include_header_layouts: bool = False,
) -> list[dict[str, Any]]:
"""返回明细重建的显式普通排除区;表头框只保留作语义和预览证据。"""
exclusions = [
dict(item) for item in (table_region.get('exclusion_regions') or [])
if isinstance(item, dict)
]
if include_header_layouts:
exclusions.extend(
dict(item['region'])
for item in (table_region.get('header_layouts') or [])
if isinstance(item, dict) and isinstance(item.get('region'), dict)
)
return exclusions
def coordinate_profile_character_candidates(
*,
table_region: dict[str, Any],
reference_page_frame: dict[str, Any] | None = None,
page_size: dict[str, Any],
page_characters: list[dict[str, Any]] | None,
table_characters: list[dict[str, Any]] | None,
raw_table_bbox: dict[str, Any] | None = None,
table_id: str | None = None,
page_no: int = 1,
coordinate_transform: dict[str, Any] | None = None,
allow_table_fallback: bool = True,
) -> tuple[list[dict[str, Any]] | None, dict[str, float] | None]:
"""按统一契约选择当前表区字符:整页证据优先,真实表框仅扩展纵向范围。
模板区域的横向边界始终有效;真实物理表的纵向边界用于覆盖跨行表框。
缺少整页证据时仅回退到该表的冻结字符,不把其它页面或其它表带入。
"""
try:
page_bbox = {
'x0': 0.0, 'y0': 0.0,
'x1': float(page_size['width']), 'y1': float(page_size['height']),
}
except (KeyError, TypeError, ValueError):
return None, None
if page_bbox['x1'] <= 0 or page_bbox['y1'] <= 0:
return None, None
projected = apply_coordinate_transform_to_region(
table_region, coordinate_transform=coordinate_transform,
)
if projected is None:
return None, page_bbox
try:
reference_width = float(reference_page_frame['width']) if reference_page_frame is not None else page_bbox['x1']
reference_height = float(reference_page_frame['height']) if reference_page_frame is not None else page_bbox['y1']
except (KeyError, TypeError, ValueError):
return None, page_bbox
if reference_width <= 0 or reference_height <= 0:
return None, page_bbox
region_bbox = {
'x0': projected['x0'] * reference_width, 'y0': projected['y0'] * reference_height,
'x1': projected['x1'] * reference_width, 'y1': projected['y1'] * reference_height,
}
is_virtual_page = str(table_id or '') == f'page-{int(page_no)}'
if not is_virtual_page and isinstance(raw_table_bbox, dict):
try:
if not (
float(raw_table_bbox['x0']) < region_bbox['x1']
and float(raw_table_bbox['x1']) > region_bbox['x0']
and float(raw_table_bbox['y0']) < region_bbox['y1']
and float(raw_table_bbox['y1']) > region_bbox['y0']
):
return None, page_bbox
evidence_bbox = dict(region_bbox)
evidence_bbox['y0'] = min(region_bbox['y0'], float(raw_table_bbox['y0']))
evidence_bbox['y1'] = max(region_bbox['y1'], float(raw_table_bbox['y1']))
except (KeyError, TypeError, ValueError):
return None, page_bbox
else:
evidence_bbox = region_bbox
if isinstance(page_characters, list):
page_candidates = [
item for item in page_characters
if isinstance(item, dict) and _character_center_in_region(item, evidence_bbox)
]
# 页级快照可能只包含订单头或被上游裁剪过;空的页级候选不能遮蔽
# 当前物理表仍然有效的冻结字符证据。
if page_candidates:
return page_candidates, page_bbox
if allow_table_fallback and isinstance(table_characters, list):
return table_characters, page_bbox
return None, page_bbox
def _character_center_in_region(character: dict[str, Any], region: dict[str, float]) -> bool:
"""判断字符中心点是否落入绝对坐标区域。"""
bbox = character.get('bbox') if isinstance(character.get('bbox'), dict) else None
if bbox is None:
return False
try:
center_x = (float(bbox['x0']) + float(bbox['x1'])) / 2
center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2
except (KeyError, TypeError, ValueError):
return False
return region['x0'] <= center_x <= region['x1'] and region['y0'] <= center_y <= region['y1']
def reconstruct_coordinate_profile_rows_with_strategy(
*,
characters: list[PositionedCharacter | dict[str, Any]],
table_bbox: LayoutBBox | dict[str, Any],
line_layouts: list[dict[str, Any]],
table_region: dict[str, Any] | None = None,
termination_rules: list[dict[str, Any]] | None = None,
exclusion_regions: list[dict[str, Any]] | None = None,
dynamic_exclusion_regions: list[dict[str, Any]] | None = None,
line_start_field_code: str | None = None,
include_deleted: bool = False,
schema_field_metadata: list[dict[str, Any]] | None = None,
initial_fields: dict[str, str] | None = None,
initial_next_offset: int = 0,
coordinate_transform: dict[str, Any] | None = None,
page_no: int = 1,
) -> tuple[list['CoordinateProfileLogicalRow'], Any]:
"""统一评估 fixed/adaptive/dynamic,并返回唯一安全的坐标明细结果。"""
from app.services.shipping_notice.document_layout.runtime_parse_strategy import (
resolve_runtime_parse_strategy,
)
fixed_rows = reconstruct_coordinate_profile_rows(
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
table_region=table_region, termination_rules=termination_rules,
exclusion_regions=exclusion_regions, line_start_field_code=line_start_field_code,
include_deleted=include_deleted, row_reconstruction_mode='fixed_subrows',
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform,
)
adaptive_rows = reconstruct_coordinate_profile_rows(
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
table_region=table_region, termination_rules=termination_rules,
exclusion_regions=exclusion_regions, line_start_field_code=line_start_field_code,
include_deleted=include_deleted, row_reconstruction_mode='adaptive_record_columns',
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform,
)
dynamic_rows = reconstruct_coordinate_profile_rows(
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
table_region=table_region, termination_rules=termination_rules,
exclusion_regions=dynamic_exclusion_regions or [], line_start_field_code=line_start_field_code,
include_deleted=include_deleted, row_reconstruction_mode='dynamic_x_columns',
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform,
)
def strategy_rows(rows: list[CoordinateProfileLogicalRow]) -> list[dict[str, Any]]:
return [
{
'status': 'parsed' if not row.issues else 'needs_review',
'issues': list(row.issues),
'fields': [
{'field_code': code, 'value': value}
for code, value in row.fields.items()
],
}
for row in rows
]
strategy = resolve_runtime_parse_strategy(
page_glyphs={str(page_no): characters},
fixed_rows=strategy_rows(fixed_rows),
adaptive_rows=strategy_rows(adaptive_rows),
dynamic_rows=strategy_rows(dynamic_rows),
)
if strategy.status != 'selected' or strategy.row_mode is None:
return [], strategy
return (
fixed_rows if strategy.row_mode == 'fixed_subrows'
else adaptive_rows if strategy.row_mode == 'adaptive_record_columns'
else dynamic_rows,
strategy,
)
def resolve_line_start_field_code(value: Any = None) -> str:
"""
规范化模板起行锚点字段编码。
@@ -60,6 +241,59 @@ def is_valid_line_start_value(raw: Any) -> bool:
return bool(text and _LINE_NUMBER_PATTERN.fullmatch(text))
def _is_record_start(
values: dict[str, str],
fields: list[dict[str, Any]],
line_start_field_code: str,
schema_fields: dict[str, dict[str, Any]] | None = None,
) -> bool:
"""用冻结 Schema 的字段类型/校验结果确认明细起行,不依赖业务字段名或列序。"""
if schema_fields is None:
start_value = values.get(line_start_field_code, '')
return is_valid_line_start_value(start_value)
start_field_configured = any(
str(field.get('field_code') or '') == line_start_field_code for field in fields
)
start_value = values.get(line_start_field_code, '')
def schema_valid(code: str, raw: str) -> bool:
config = schema_fields.get(code)
if not config or not str(raw or '').strip():
return False
try:
normalized = normalize_order_field_value(raw, config)
except Exception:
return False
return normalized not in (None, '') and validate_order_field_value(normalized, config)
# 起行字段的 Schema 类型只负责保留/解析值;它被模板配置为起行锚点后,
# 还必须满足通用行号形态,避免 string 字段把表头文本(如 ``0rd``/``B``)
# 当成明细起点。该规则只作用于配置的锚点,不依赖任何业务字段名。
has_start_anchor = (
is_valid_line_start_value(start_value)
and schema_valid(line_start_field_code, start_value)
)
corroborating = sum(
1 for field in fields
if (code := str(field.get('field_code') or ''))
and code != line_start_field_code
and schema_valid(code, values.get(code, ''))
)
configured_corroborating_fields = sum(
1 for field in fields
if (code := str(field.get('field_code') or ''))
and code != line_start_field_code
and code in schema_fields
)
if has_start_anchor:
# 若模板只绑定起行字段,Schema 没有第二个坐标字段可供交叉验证,
# 允许该锚点单独起行;一旦存在其它已绑定字段,必须有至少一个有效值。
return corroborating >= 1 or configured_corroborating_fields == 0
# A profile that explicitly configures a start field must not silently fall back
# to unrelated fields when that anchor is absent. Profiles without such a field
# may use a position-independent two-field business signature.
return not start_field_configured and corroborating >= 2
class CoordinateReconstructionModel(BaseModel):
"""为坐标重建的中间证据启用严格契约,禁止调用方注入未定义字段。"""
@@ -272,8 +506,9 @@ def reconstruct_coordinate_profile_rows(
include_deleted: bool = False,
line_start_field_code: str | None = None,
include_unanchored_rows: bool = False,
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows',
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns'] = 'fixed_subrows',
coordinate_transform: dict[str, Any] | None = None,
schema_field_metadata: list[dict[str, Any]] | None = None,
) -> list[CoordinateProfileLogicalRow]:
"""
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
@@ -301,6 +536,16 @@ def reconstruct_coordinate_profile_rows(
termination_rules = projected['termination_rules']
exclusion_regions = projected['exclusion_regions']
start_field_code = resolve_line_start_field_code(line_start_field_code)
schema_fields = {
str(item.get('field_code') or ''): item
for item in (schema_field_metadata or [])
if (
isinstance(item, dict)
and item.get('field_code')
and item.get('enabled', True)
and str(item.get('scope') or '') == 'line'
)
} if schema_field_metadata is not None else None
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1))
if not ordered_layouts or [item.get('row_offset') for item in ordered_layouts] != list(range(len(ordered_layouts))):
@@ -322,6 +567,11 @@ def reconstruct_coordinate_profile_rows(
_absolute_relative_region(bbox, item)
for item in (exclusion_regions or []) if isinstance(item, dict)
]
# 直接调用动态候选时,传入的旧式排除区无法区分表头/普通排除;为兼容其
# “表头可移动”语义不应用它。统一入口则显式传入 dynamic_exclusion_regions,
# 从而保留管理员配置的普通排除区。
if row_reconstruction_mode == 'dynamic_x_columns':
exclusions = []
# [STEP 1] 删除文字不是全局业务规则;只有管理员用排除区显式圈定后才授权删除上一条明细。
marker_indices: set[int] = set()
authorized_marker_indices: set[int] = set()
@@ -353,6 +603,16 @@ def reconstruct_coordinate_profile_rows(
# This mode is opt-in per table region. It supports documents whose stable
# columns stay put while optional descriptions move values across visual rows.
if row_reconstruction_mode == 'dynamic_x_columns':
return _reconstruct_dynamic_x_columns_profile_rows(
glyphs=glyphs,
table_bbox=bbox,
ordered_layouts=ordered_layouts,
termination_rules=termination_rules or [],
include_deleted=include_deleted,
line_start_field_code=start_field_code,
schema_fields=schema_fields,
)
if row_reconstruction_mode == 'adaptive_record_columns':
return _reconstruct_adaptive_record_columns_profile_rows(
glyphs=glyphs,
@@ -361,6 +621,7 @@ def reconstruct_coordinate_profile_rows(
termination_rules=termination_rules or [],
include_deleted=include_deleted,
line_start_field_code=start_field_code,
schema_fields=schema_fields,
)
relative_y_rows = _reconstruct_relative_y_profile_rows(
@@ -372,6 +633,7 @@ def reconstruct_coordinate_profile_rows(
include_deleted=include_deleted,
line_start_field_code=start_field_code,
include_unanchored_rows=include_unanchored_rows,
schema_fields=schema_fields,
)
if relative_y_rows is not None:
return relative_y_rows
@@ -434,7 +696,7 @@ def reconstruct_coordinate_profile_rows(
flush(role='deleted')
continue
main_values, main_evidence, main_issues = values_for(band, ordered_layouts[0])
if is_valid_line_start_value(main_values.get(start_field_code, '')):
if _is_record_start(main_values, ordered_layouts[0].get('field_regions') or [], start_field_code, schema_fields):
flush()
current, current_evidence = main_values, main_evidence
sources, next_offset, current_issues = [row_index], 1, main_issues
@@ -553,6 +815,7 @@ def _reconstruct_adaptive_record_columns_profile_rows(
termination_rules: list[dict[str, Any]],
include_deleted: bool,
line_start_field_code: str,
schema_fields: dict[str, dict[str, Any]] | None = None,
) -> list[CoordinateProfileLogicalRow]:
"""按起行锚点分段,并在每段内用字段列及格式读取可变视觉子行。"""
main_fields = ordered_layouts[0].get('field_regions') or []
@@ -583,6 +846,7 @@ def _reconstruct_adaptive_record_columns_profile_rows(
main_fields=main_fields,
table_bbox=table_bbox,
line_start_field_code=line_start_field_code,
schema_fields=schema_fields,
)
]
results: list[CoordinateProfileLogicalRow] = []
@@ -597,6 +861,17 @@ def _reconstruct_adaptive_record_columns_profile_rows(
for field in fields:
code = str(field['field_code'])
region = _absolute_relative_region(table_bbox, field['region'])
# 自适应列模式只能为单视觉 band 选择候选。若 Schema 绑定的
# 字段框明确跨越多个 band(如换行客户料号),该模式的单 band
# 候选必然不完整,必须交给 fixed 几何重建处理。
if schema_fields is not None:
intersecting = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
if len(intersecting) > 1:
issues.append(f'coordinate_profile_field_band_ambiguous:{code}')
continue
candidates: list[tuple[float, int, dict[str, str]]] = []
for band_index, (_, band) in enumerate(record):
raw = _adaptive_field_raw(band=band, region=region, field_code=code)
@@ -629,7 +904,7 @@ def _reconstruct_adaptive_record_columns_profile_rows(
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
else:
values[extracted_code] = extracted_value
if is_valid_line_start_value(values.get(line_start_field_code, '')):
if _is_record_start(values, main_fields, line_start_field_code, schema_fields):
results.append(CoordinateProfileLogicalRow(
fields=values,
source_row_indices=[row_index for row_index, _ in record],
@@ -639,6 +914,87 @@ def _reconstruct_adaptive_record_columns_profile_rows(
return results if include_deleted else [row for row in results if row.role != 'deleted']
def _reconstruct_dynamic_x_columns_profile_rows(
*,
glyphs: list[tuple[int, PositionedCharacter]],
table_bbox: LayoutBBox,
ordered_layouts: list[dict[str, Any]],
termination_rules: list[dict[str, Any]],
include_deleted: bool,
line_start_field_code: str,
schema_fields: dict[str, dict[str, Any]] | None = None,
) -> list[CoordinateProfileLogicalRow]:
"""按每条记录的有效起行锚点平移完整字段框,恢复稳定 X、漂移 Y 的明细。"""
main_fields = ordered_layouts[0].get('field_regions') or []
start_field = next(
(item for item in main_fields if isinstance(item, dict) and item.get('field_code') == line_start_field_code),
None,
)
if not isinstance(start_field, dict) or not isinstance(start_field.get('region'), dict):
return []
fields = [
field for layout in ordered_layouts for field in (layout.get('field_regions') or [])
if isinstance(field, dict) and isinstance(field.get('region'), dict) and field.get('field_code')
]
bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = []
for row_index, band in enumerate(_group_visual_rows(glyphs)):
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
if _SUMMARY_PATTERN.search(text) or _matches_termination_rule(band, table_bbox, termination_rules):
break
bands.append((row_index, band))
start_region = _absolute_relative_region(table_bbox, start_field['region'])
anchors = [
index for index, (_row_index, band) in enumerate(bands)
if _is_adaptive_record_start(
band=band, start_region=start_region, main_fields=main_fields,
table_bbox=table_bbox, line_start_field_code=line_start_field_code,
schema_fields=schema_fields,
)
]
results: list[CoordinateProfileLogicalRow] = []
expected_anchor_center = (start_region.y0 + start_region.y1) / 2
for anchor_index, start in enumerate(anchors):
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(bands)
record = bands[start:end]
anchor_box = _band_bbox(record[0][1])
delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center
values: dict[str, str] = {}
issues: list[str] = []
for field in fields:
code = str(field['field_code'])
saved = _absolute_relative_region(table_bbox, field['region'])
region = LayoutBBox(
x0=saved.x0, y0=saved.y0 + delta_y,
x1=saved.x1, y1=saved.y1 + delta_y,
)
selected_bands = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
raw = _text_in_multiline_region(
selected_bands, region,
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
)
if not raw:
continue
extracted = extract_profile_field_value(
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
)
for extracted_code, extracted_value in extracted.items():
previous = values.get(extracted_code)
if previous is not None and previous != extracted_value:
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
else:
values[extracted_code] = extracted_value
if _is_record_start(values, main_fields, line_start_field_code, schema_fields):
results.append(CoordinateProfileLogicalRow(
fields=values,
source_row_indices=[row_index for row_index, _band in record],
role='data', issues=issues,
))
return results if include_deleted else [row for row in results if row.role != 'deleted']
def _adaptive_field_raw(
*, band: list[tuple[int, PositionedCharacter]], region: LayoutBBox, field_code: str,
) -> str:
@@ -656,22 +1012,43 @@ def _adaptive_field_raw(
def _is_adaptive_record_start(
*, band: list[tuple[int, PositionedCharacter]], start_region: LayoutBBox,
main_fields: list[dict[str, Any]], table_bbox: LayoutBBox, line_start_field_code: str,
schema_fields: dict[str, dict[str, Any]] | None = None,
) -> bool:
"""要求起行号及同一主行的其他绑定字段共同成立,排除页眉、地址中的孤立数字。"""
if not is_valid_line_start_value(_text_in_horizontal_region(band, start_region)):
return False
evidence_fields = [
item for item in main_fields
if item.get('field_code') != line_start_field_code and item.get('field_code') in {
'part_number', 'customer_part_number', 'aws_part_number',
}
]
return all(
_is_compact_identifier(
_text_in_horizontal_region(band, _absolute_relative_region(table_bbox, field['region']))
"""按当前主视觉行的 Schema 字段值判断起行,不依赖业务字段名。"""
if schema_fields is None:
if not is_valid_line_start_value(_text_in_horizontal_region(band, start_region)):
return False
# 低层旧调用未提供 Schema 时仍使用通用文本形态交叉验证,
# 但不再按业务字段名建立白名单。
evidence_fields = [
item for item in main_fields
if isinstance(item, dict)
and item.get('field_code') != line_start_field_code
and isinstance(item.get('region'), dict)
]
return all(
_is_compact_identifier(
_text_in_horizontal_region(band, _absolute_relative_region(table_bbox, field['region']))
)
for field in evidence_fields
)
for field in evidence_fields
)
values: dict[str, str] = {}
for field in main_fields:
if not isinstance(field, dict) or not isinstance(field.get('region'), dict):
continue
code = str(field.get('field_code') or '')
if not code or code not in schema_fields:
continue
raw = _adaptive_field_raw(
band=band,
region=_absolute_relative_region(table_bbox, field['region']),
field_code=code,
)
extracted = extract_profile_field_value(
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
)
values.update(extracted)
return _is_record_start(values, main_fields, line_start_field_code, schema_fields)
def _is_compact_identifier(raw: str) -> bool:
@@ -717,6 +1094,7 @@ def _reconstruct_relative_y_profile_rows(
include_deleted: bool,
line_start_field_code: str,
include_unanchored_rows: bool,
schema_fields: dict[str, dict[str, Any]] | None = None,
) -> list[CoordinateProfileLogicalRow] | None:
"""
将单个多视觉行物理框按父行内相对 Y 投影到每条重复明细。
@@ -741,6 +1119,18 @@ def _reconstruct_relative_y_profile_rows(
)
if start_field is None:
return None
def values_for_band(band: list[tuple[int, PositionedCharacter]]) -> dict[str, str]:
values: dict[str, str] = {}
for field in fields:
code = str(field.get('field_code') or '')
region = _absolute_relative_region(table_bbox, field['region'])
raw = _text_in_horizontal_region(band, region)
extracted = extract_profile_field_value(
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
)
values.update(extracted)
return values
bands = _group_visual_rows(glyphs)
usable_bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = []
for row_index, band in enumerate(bands):
@@ -755,16 +1145,17 @@ def _reconstruct_relative_y_profile_rows(
anchors: list[int] = []
for index, (_, band) in enumerate(usable_bands):
start_text = _text_in_horizontal_region(band, start_region)
if is_valid_line_start_value(start_text):
if schema_fields is None and is_valid_line_start_value(start_text):
anchors.append(index)
elif schema_fields is not None:
values = values_for_band(band)
if _is_record_start(values, fields, line_start_field_code, schema_fields):
anchors.append(index)
if not anchors:
return []
sample_end = anchors[1] if len(anchors) > 1 else len(usable_bands)
sample_record = usable_bands[anchors[0]:sample_end]
field_band_indices = _calibrate_field_band_indices(
fields=fields, sample_record=sample_record, table_bbox=table_bbox,
)
start_region = _absolute_relative_region(table_bbox, start_field['region'])
expected_anchor_center = (start_region.y0 + start_region.y1) / 2
results: list[CoordinateProfileLogicalRow] = []
for anchor_index, start in enumerate(anchors):
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands)
@@ -774,23 +1165,34 @@ def _reconstruct_relative_y_profile_rows(
)) for _, band in record)
values: dict[str, str] = {}
issues: list[str] = []
matched_bands, alignment_issues = _match_field_band_groups(
fields=fields,
record=record,
expected_indices=field_band_indices,
table_bbox=table_bbox,
line_start_field_code=line_start_field_code,
)
issues.extend(alignment_issues)
anchor_box = _band_bbox(record[0][1])
delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center
for field in fields:
code = str(field.get('field_code') or '')
if not code:
continue
band_index = matched_bands.get(id(field))
if band_index is None:
saved = _absolute_relative_region(table_bbox, field['region'])
region = LayoutBBox(
x0=saved.x0, y0=saved.y0 + delta_y,
x1=saved.x1, y1=saved.y1 + delta_y,
)
# A visual field box may intentionally span multiple PDF text lines
# (for example a wrapped customer part number). The previous
# one-band assignment treated that as an ambiguity and dropped the
# field, which caused two vertically stacked part-number fields to
# become empty or reuse the same prefix. When the configured field
# region intersects multiple bands, read all of its own glyphs;
# single-band fields retain the calibrated matching behavior.
intersecting = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
if not intersecting:
continue
region = _absolute_relative_region(table_bbox, field['region'])
raw = _text_in_horizontal_region(record[band_index][1], region)
raw = _text_in_multiline_region(
intersecting, region,
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
)
if not raw:
continue
extracted = extract_profile_field_value(
@@ -802,7 +1204,7 @@ def _reconstruct_relative_y_profile_rows(
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
else:
values[extracted_code] = extracted_value
if is_valid_line_start_value(values.get(line_start_field_code, '')):
if _is_record_start(values, fields, line_start_field_code, schema_fields):
results.append(CoordinateProfileLogicalRow(
fields=values,
source_row_indices=[row_index for row_index, _ in record],
@@ -1202,7 +1604,7 @@ def reconstruct_multi_subrow_table(
continue
main_values = _band_field_values(band, anchors[0])
if is_valid_line_start_value(main_values.get(start_field_code, '')):
if _is_record_start(main_values, ordered_layouts[0].get('field_regions') or [], start_field_code):
flush()
current_fields = main_values
current_sources = [row_index]
@@ -1370,13 +1772,17 @@ def _absolute_relative_region(table_bbox: LayoutBBox, relative: dict[str, Any])
def _inside_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool:
"""仅收集中心在管理员框选区域内的字符,边缘字符不跨区域复制。"""
return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1 and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1
"""按纵向中心和有效横向重叠收集字符,避免字段边界截断字形。"""
return (
_inside_horizontal_region(glyph_bbox, region)
and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1
)
def _inside_horizontal_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool:
"""仅按标注框横向范围筛选字符,使同一行版式可应用到整张表的重复明细。"""
return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1
"""接受与字段框正向相交的字形,防止紧贴边界的料号标点被截断。"""
overlap = min(glyph_bbox.x1, region.x1) - max(glyph_bbox.x0, region.x0)
return overlap > 0
def _has_relative_y_subregions(parent: dict[str, Any], fields: list[dict[str, Any]]) -> bool:
@@ -1499,6 +1905,26 @@ def _text_in_region(
return render_positioned_row([glyph for _, glyph in selected], geometry_gap_limit=gap_limit)
def _regions_overlap_vertically(left: LayoutBBox, right: LayoutBBox) -> bool:
"""判断字段框与视觉 band 是否有纵向证据交集。"""
return min(left.y1, right.y1) > max(left.y0, right.y0)
def _text_in_multiline_region(
bands: list[list[tuple[int, PositionedCharacter]]],
region: LayoutBBox,
*,
compact: bool = False,
) -> str:
"""按视觉行顺序读取跨行字段,料号换行时去除行间空白。"""
lines: list[str] = []
for band in sorted(bands, key=lambda item: _band_bbox(item).y0):
text = _text_in_region(band, region).strip()
if text:
lines.append(text)
return ('' if compact else ' ').join(lines)
def _text_in_horizontal_region(
band: list[tuple[int, PositionedCharacter]], region: LayoutBBox,
) -> str:
@@ -11,6 +11,7 @@ backend/app/services/shipping_notice/document_layout/lifecycle.py
from __future__ import annotations
import hashlib
import gzip
import json
import logging
from datetime import datetime
@@ -22,6 +23,7 @@ from sqlalchemy import and_, func, or_, update
from app.extensions import db
from app.models import (
FileAsset,
ShippingDocumentLayoutVersion,
ShippingOrderDocument,
ShippingOrderIntake,
@@ -51,6 +53,81 @@ ON_DEMAND_COORDINATE_COMPACTION_ISSUES = frozenset({
'shipping_document_layout_candidate_glyphs_compacted',
'shipping_document_layout_candidate_page_metadata_compacted',
})
COORDINATE_EVIDENCE_REF_KEY = 'coordinate_evidence_ref'
COORDINATE_EVIDENCE_SCHEMA_VERSION = 'shipping_order_coordinate_evidence.v1'
def _coordinate_evidence_bytes(evidence: dict[str, Any]) -> bytes:
"""将完整坐标证据以稳定 gzip JSON 编码,供不可变 FileAsset 保存。"""
raw = json.dumps(evidence, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8')
return gzip.compress(raw, compresslevel=6, mtime=0)
def _persist_coordinate_evidence_asset(*, document: ShippingOrderDocument, evidence: dict[str, Any]) -> dict[str, Any] | None:
"""复用现有 FileAsset/MinIO 保存完整坐标证据并返回轻量引用。"""
tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
if not any(isinstance(value, list) and value for value in (*tables.values(), *page_glyphs.values())):
return None
from app.services.file_assets.service import create_derived_file_asset_from_bytes
parent = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None
intake = db.session.get(ShippingOrderIntake, int(document.intake_id))
user_id = getattr(intake, 'user_id', None)
if parent is None or user_id is None:
return None
data = _coordinate_evidence_bytes(evidence)
asset, created = create_derived_file_asset_from_bytes(
user_id=int(user_id), parent=parent, data=data,
filename=f'{document.id}-coordinate-evidence.json.gz',
mime_type='application/json+gzip', asset_role='layout_coordinate_evidence',
)
asset.lifecycle_status = 'referenced'
asset.expires_at = None
asset.deleted_at = None
if created or int(asset.reference_count or 0) == 0:
asset.reference_count = max(int(asset.reference_count or 0), 1)
return {
'asset_no': str(asset.asset_no),
'checksum': hashlib.sha256(data).hexdigest(),
'size': len(data),
'schema_version': str(evidence.get('version') or COORDINATE_EVIDENCE_SCHEMA_VERSION),
}
def _has_coordinate_evidence(evidence: Any) -> bool:
"""判断证据是否含有可外置的字符集合;空占位结构保持原快照兼容。"""
if not isinstance(evidence, dict):
return False
for key in ('tables', 'page_glyphs'):
values = evidence.get(key)
if isinstance(values, dict) and any(isinstance(item, list) and item for item in values.values()):
return True
return False
def _hydrate_coordinate_evidence(*, payload: dict[str, Any], document: ShippingOrderDocument) -> dict[str, Any]:
"""从现有 FileAsset 引用加载完整坐标证据;读取失败时保持缺证据状态。"""
ref = payload.get(COORDINATE_EVIDENCE_REF_KEY)
if not isinstance(ref, dict):
return payload
asset_no = str(ref.get('asset_no') or '').strip()
if not asset_no:
return payload
asset = FileAsset.query.filter_by(asset_no=asset_no, deleted_at=None).first()
if asset is None:
return payload
try:
from app.services.file_assets.service import read_asset_bytes
evidence = json.loads(gzip.decompress(read_asset_bytes(asset)).decode('utf-8'))
except Exception:
_LOGGER.exception('coordinate evidence asset load failed document_id=%s asset_no=%s', document.id, asset_no)
return payload
if _has_coordinate_evidence(evidence):
hydrated = dict(payload)
hydrated['coordinate_evidence'] = evidence
return hydrated
return payload
def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload: dict[str, Any]) -> bool:
@@ -61,10 +138,8 @@ def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload:
"""
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
return True
evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {}
complete = isinstance(evidence.get('pages'), dict) and isinstance(evidence.get('page_glyphs'), dict)
recoverable = bool(document.asset_id) and isinstance(payload.get('layout_candidate'), dict)
return complete or recoverable
ref = payload.get(COORDINATE_EVIDENCE_REF_KEY)
return isinstance(ref, dict) and bool(str(ref.get('asset_no') or '').strip())
def _layout_version_reusable(*, document: ShippingOrderDocument, version: ShippingDocumentLayoutVersion) -> bool:
@@ -207,14 +282,17 @@ def _fit_layout_payload_to_budget(
def current_layout_snapshot(document: ShippingOrderDocument) -> dict[str, Any] | None:
"""读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。"""
version = document.current_layout_version
version = (
db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id))
if document.current_layout_version_id else document.current_layout_version
)
if (
version is None
or str(version.status or '') not in CURRENT_LAYOUT_STATUSES
or not isinstance(version.payload_json, dict)
):
return None
return dict(version.payload_json)
return _hydrate_coordinate_evidence(payload=dict(version.payload_json), document=document)
def _bind_inline_xfa_structure_analysis(
@@ -322,6 +400,16 @@ def record_inline_layout_snapshot(
超大 payload 不落正文,只创建 failed 审计版本;相同内容/parser/checksum 重试复用旧终态。
"""
payload = dict(snapshot)
evidence = payload.get('coordinate_evidence')
if _has_coordinate_evidence(evidence):
evidence_ref = _persist_coordinate_evidence_asset(document=document, evidence=evidence)
if evidence_ref is None and str(payload.get('status') or '') == 'ready':
payload = {**payload, 'status': 'failed', 'issues': [
*list(payload.get('issues') or []), 'shipping_document_layout_coordinate_evidence_persist_failed',
]}
elif evidence_ref is not None:
payload.pop('coordinate_evidence', None)
payload[COORDINATE_EVIDENCE_REF_KEY] = evidence_ref
parser_key = str(parser_key or current_layout_parser_key())
max_bytes = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
@@ -943,19 +1031,30 @@ def complete_layout_version(
if version is None or version.status != 'running' or version.lease_token != lease_token:
db.session.rollback()
return False
payload = dict(snapshot)
evidence = payload.get('coordinate_evidence')
if _has_coordinate_evidence(evidence):
evidence_ref = _persist_coordinate_evidence_asset(document=version.document, evidence=evidence)
if evidence_ref is None and str(payload.get('status') or '') == 'ready':
payload = {**payload, 'status': 'failed', 'issues': [
*list(payload.get('issues') or []), 'shipping_document_layout_coordinate_evidence_persist_failed',
]}
elif evidence_ref is not None:
payload.pop('coordinate_evidence', None)
payload[COORDINATE_EVIDENCE_REF_KEY] = evidence_ref
max_bytes = max(int(current_app.config.get(
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
)), 1)
fitted_snapshot, compact_issues, payload_size = _fit_layout_payload_to_budget(
snapshot, max_bytes=max_bytes,
payload, max_bytes=max_bytes,
)
stored_for_identity = fitted_snapshot if fitted_snapshot is not None else snapshot
stored_for_identity = fitted_snapshot if fitted_snapshot is not None else payload
checksum, _ = canonical_layout_payload(stored_for_identity)
issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)} | set(compact_issues))
provider_status = str(snapshot.get('status') or 'failed')
issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)} | set(compact_issues))
provider_status = str(payload.get('status') or 'failed')
status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed'
if status == 'ready' and not _ready_layout_evidence_complete(
document=version.document, payload=snapshot,
document=version.document, payload=payload,
):
status = 'failed'
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_incomplete'})
@@ -967,12 +1066,12 @@ def complete_layout_version(
status = 'failed'
now = datetime.utcnow()
version.status = status
version.parser_version = str(snapshot.get('provider_version') or '')[:64] or None
version.backend = str(snapshot.get('backend') or LAYOUT_BACKEND)[:32]
version.parser_version = str(payload.get('provider_version') or '')[:64] or None
version.backend = str(payload.get('backend') or LAYOUT_BACKEND)[:32]
version.payload_json = stored_payload
version.payload_checksum = checksum
version.payload_size_bytes = payload_size
version.quality_json = dict(snapshot['capability']) if isinstance(snapshot.get('capability'), dict) else None
version.quality_json = dict(payload['capability']) if isinstance(payload.get('capability'), dict) else None
version.issues_json = sorted(set(issues))
version.lease_token = None
version.finished_at = now
@@ -93,56 +93,62 @@ def extract_native_pdf_pages(
"""
if not content or render_scale <= 0:
raise ValueError('native PDF content and positive render scale are required')
pdf = pdfium.PdfDocument(content)
pages: list[NativePdfPage] = []
for page_index in range(len(pdf)):
page = pdf[page_index]
width, height = page.get_size()
text_page = page.get_textpage()
characters: list[PositionedCharacter] = []
pending_boundary: str = 'none'
for char_index in range(text_page.count_chars()):
text = text_page.get_text_range(char_index, 1)
if not text:
continue
if not normalize_layout_text(text):
if any(character in {'\r', '\n'} for character in text):
pending_boundary = 'line_break'
elif pending_boundary == 'none' and any(character.isspace() for character in text):
pending_boundary = 'space'
continue
left, bottom, right, top = text_page.get_charbox(char_index, loose=True)
if right <= left or top <= bottom:
# 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。
pending_boundary = 'none'
continue
pdf = pdfium.PdfDocument(content)
try:
for page_index in range(len(pdf)):
page = pdf[page_index]
text_page = None
try:
# 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。
characters.append(PositionedCharacter(
text=text,
bbox=LayoutBBox(
x0=left, y0=height - top, x1=right, y1=height - bottom,
),
source_index=char_index,
boundary_before=pending_boundary,
width, height = page.get_size()
text_page = page.get_textpage()
characters: list[PositionedCharacter] = []
pending_boundary: str = 'none'
for char_index in range(text_page.count_chars()):
text = text_page.get_text_range(char_index, 1)
if not text:
continue
if not normalize_layout_text(text):
if any(character in {'\r', '\n'} for character in text):
pending_boundary = 'line_break'
elif pending_boundary == 'none' and any(character.isspace() for character in text):
pending_boundary = 'space'
continue
left, bottom, right, top = text_page.get_charbox(char_index, loose=True)
if right <= left or top <= bottom:
# 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。
pending_boundary = 'none'
continue
try:
# 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。
characters.append(PositionedCharacter(
text=text,
bbox=LayoutBBox(
x0=left, y0=height - top, x1=right, y1=height - bottom,
),
source_index=char_index,
boundary_before=pending_boundary,
))
pending_boundary = 'none'
except ValueError:
pending_boundary = 'none'
continue
characters = _assign_page_line_ids(characters, page_no=page_index + 1)
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
pages.append(NativePdfPage(
page_no=page_index + 1,
width=float(width),
height=float(height),
rotation=rotation if rotation in {0, 90, 180, 270} else 0,
characters=characters,
image=_render_native_pdf_page(page, render_scale) if render_images else None,
))
pending_boundary = 'none'
except ValueError:
pending_boundary = 'none'
continue
characters = _assign_page_line_ids(characters, page_no=page_index + 1)
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
pages.append(NativePdfPage(
page_no=page_index + 1,
width=float(width),
height=float(height),
rotation=rotation if rotation in {0, 90, 180, 270} else 0,
characters=characters,
image=(
np.asarray(page.render(scale=render_scale).to_numpy()).copy()
if render_images else None
),
))
finally:
if text_page is not None:
text_page.close()
page.close()
finally:
pdf.close()
return pages
@@ -191,27 +197,43 @@ def attach_native_pdf_page_images(
return []
if all(page.image is not None for page in pages):
return list(pages)
pdf = pdfium.PdfDocument(content)
attached: list[NativePdfPage] = []
for page in pages:
if page.image is not None:
attached.append(page)
continue
index = int(page.page_no) - 1
if index < 0 or index >= len(pdf):
raise ValueError('native PDF page_no is out of range for image attach')
image = np.asarray(pdf[index].render(scale=render_scale).to_numpy()).copy()
attached.append(NativePdfPage(
page_no=page.page_no,
width=page.width,
height=page.height,
rotation=page.rotation,
characters=page.characters,
image=image,
))
pdf = pdfium.PdfDocument(content)
try:
for native_page in pages:
if native_page.image is not None:
attached.append(native_page)
continue
index = int(native_page.page_no) - 1
if index < 0 or index >= len(pdf):
raise ValueError('native PDF page_no is out of range for image attach')
page = pdf[index]
try:
image = _render_native_pdf_page(page, render_scale)
finally:
page.close()
attached.append(NativePdfPage(
page_no=native_page.page_no,
width=native_page.width,
height=native_page.height,
rotation=native_page.rotation,
characters=native_page.characters,
image=image,
))
finally:
pdf.close()
return attached
def _render_native_pdf_page(page: Any, render_scale: float) -> np.ndarray:
"""将 PDFium 页面复制为独立 ndarray 后立即释放临时 bitmap,避免其 finalizer 滞留到进程退出。"""
bitmap = page.render(scale=render_scale)
try:
return np.asarray(bitmap.to_numpy()).copy()
finally:
bitmap.close()
def build_native_pdf_text_table_fallbacks(
content: bytes,
*,
@@ -232,17 +254,24 @@ def build_native_pdf_text_table_fallbacks(
continue
start_index, end_index = header
header_lines = lines[start_index:end_index + 1]
body_lines = lines[end_index + 1:]
stop_index = next((
index for index, line in enumerate(body_lines)
if _is_fallback_total(line) or _is_fallback_separator(line)
), len(body_lines))
body_lines = body_lines[:stop_index]
if not body_lines:
continue
boundaries = _fallback_column_boundaries(header_lines, page.width)
if len(boundaries) < 3:
continue
body_lines: list[dict[str, Any]] = []
has_data_row = False
for line in lines[end_index + 1:]:
if _is_fallback_total(line):
break
if _is_fallback_separator(line):
# 采购订单常在表头和首条明细之间画横线;只有已见明细后的横线才是表尾。
if has_data_row:
break
continue
body_lines.append(line)
if _fallback_data_row(_fallback_cells([line], boundaries)):
has_data_row = True
if not body_lines:
continue
header_cells = _fallback_cells(header_lines, boundaries)
body_cells = [_fallback_cells([line], boundaries) for line in body_lines]
if not any(_fallback_data_row(row) for row in body_cells):
@@ -23,6 +23,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
AnchorRule,
OrderCoordinateProfile,
OrderFieldLayout,
ReferencePageFrame,
RelativeRegion,
)
from app.services.shipping_notice.order_schema.field_rules import (
@@ -53,6 +54,7 @@ def extract_order_fields(
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False,
coordinate_transform: dict[str, Any] | None = None,
allow_fixed_region_confirmation: bool = False,
) -> list[OrderFieldExtraction]:
"""
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
@@ -63,6 +65,9 @@ def extract_order_fields(
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
allow_ocr_preview_fallback: 仅管理端视觉样本值预览可启用。它允许已确认的
PDF 坐标字段临时读取 OCR 候选,但结果仍固定为 needs_review,不能用于正式运行时取值。
allow_fixed_region_confirmation: 仅唯一匹配模板的正式运行或当前模板盲测回放可启用。
它只允许原生 PDF 坐标的无标签固定区域成为 confirmed;OCR、未匹配模板和
普通预览仍保持 needs_review。
Returns:
每个已绑定布局对应一个候选,按模板声明顺序返回。
@@ -78,7 +83,9 @@ def extract_order_fields(
layout=layout,
schema_fields=schema_fields,
coordinate_evidence=coordinate_evidence,
reference_page_frames=effective_profile.reference_page_frames,
allow_ocr_preview_fallback=allow_ocr_preview_fallback,
allow_fixed_region_confirmation=allow_fixed_region_confirmation,
)
for layout in effective_profile.order_field_layouts
]
@@ -103,7 +110,8 @@ def _project_coordinate_transform(
def _extract_layout(
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
allow_ocr_preview_fallback: bool = False,
reference_page_frames: dict[int, ReferencePageFrame],
allow_ocr_preview_fallback: bool = False, allow_fixed_region_confirmation: bool = False,
) -> OrderFieldExtraction:
"""处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。"""
config = schema_fields.get(layout.field_id)
@@ -139,6 +147,7 @@ def _extract_layout(
results: list[OrderFieldExtraction] = []
for page_no, glyphs, width, height, source in candidates:
reference_page_frame = reference_page_frames.get(page_no)
if not _source_allowed(
layout,
config=config,
@@ -150,18 +159,25 @@ def _extract_layout(
if layout.anchor is None:
results.append(_read_value_region(
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
region=_absolute_relative_region(layout.fallback_value_region, width=width, height=height), anchor_bbox=None,
fallback=True,
region=_absolute_relative_region(
layout.fallback_value_region, width=width, height=height,
reference_page_frame=reference_page_frame,
), anchor_bbox=None,
fallback=not (allow_fixed_region_confirmation and source == 'pdf_coordinate'),
))
continue
matches = _find_anchor_matches(
glyphs, layout.anchor, page_width=width, page_height=height,
ignore_reference_region=_uses_movable_anchor_value_region(layout=layout, width=width, height=height),
reference_page_frame=reference_page_frame,
ignore_reference_region=_uses_movable_anchor_value_region(
layout=layout, width=width, height=height, reference_page_frame=reference_page_frame,
),
)
if not matches:
reference_anchor = (
_anchor_from_reference_region(
glyphs, anchor=layout.anchor, page_width=width, page_height=height,
reference_page_frame=reference_page_frame,
)
if _is_placeholder_anchor_text(layout.anchor.text) else None
)
@@ -171,7 +187,10 @@ def _extract_layout(
# intent, but it must remain review-only until the label is fixed.
results.append(_read_value_region(
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
region=_absolute_value_region(layout=layout, anchor=reference_anchor, width=width, height=height),
region=_absolute_value_region(
layout=layout, anchor=reference_anchor, width=width, height=height,
reference_page_frame=reference_page_frame,
),
anchor_bbox=reference_anchor, fallback=False,
review_issue='order_field_anchor_text_mismatch',
))
@@ -187,7 +206,10 @@ def _extract_layout(
anchor_bbox, _indices = matches[0]
results.append(_read_value_region(
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
region=_absolute_value_region(layout=layout, anchor=anchor_bbox, width=width, height=height), anchor_bbox=anchor_bbox, fallback=False,
region=_absolute_value_region(
layout=layout, anchor=anchor_bbox, width=width, height=height,
reference_page_frame=reference_page_frame,
), anchor_bbox=anchor_bbox, fallback=False,
))
usable = [item for item in results if item.status != 'unavailable']
if len(usable) == 1:
@@ -321,6 +343,7 @@ def _recover_trailing_date_glyph(*, text: str, glyphs: list[dict[str, Any]], reg
def _find_anchor_matches(
glyphs: list[dict[str, Any]], anchor: AnchorRule, *, page_width: float | None = None, page_height: float | None = None,
reference_page_frame: ReferencePageFrame | None = None,
ignore_reference_region: bool = False,
) -> list[tuple[LayoutBBox, list[int]]]:
"""在每个视觉行内执行精确标签匹配,返回去重后的字符联合框。"""
@@ -348,23 +371,22 @@ def _find_anchor_matches(
compact, position=position, length=len(normalized), anchor=anchor,
):
bbox = _union_bbox([item for _index, item in consumed])
if ignore_reference_region or _anchor_bbox_in_reference_region(
bbox, anchor=anchor, page_width=page_width, page_height=page_height,
):
matches.append((bbox, [index for index, _item in consumed]))
# 先按文本收集全部精确命中;保存的参考框只用于多个同名标签
# 的消歧,不能让同版式样本中唯一但位置变化的标签直接丢失。
matches.append((bbox, [index for index, _item in consumed]))
start = position + max(len(label), 1)
unique: dict[tuple[float, float, float, float], tuple[LayoutBBox, list[int]]] = {}
for bbox, indices in matches:
unique[(bbox.x0, bbox.y0, bbox.x1, bbox.y1)] = (bbox, indices)
resolved = list(unique.values())
# An unlocked label may shift between documents, so its reference box must
# not suppress a sole match. When the same label occurs multiple times,
# however, the saved canvas position is decisive evidence for this sample.
# 唯一文本命中不受历史参考框限制;同名标签多次出现时,保存位置才是
# 当前样本的消歧证据。若位置也无法唯一消歧,调用方会进入人工复核。
if len(resolved) > 1 and anchor.region is not None and page_width and page_height:
positioned = [
item for item in resolved
if _anchor_bbox_in_reference_region(
item[0], anchor=anchor, page_width=page_width, page_height=page_height, enforce=True,
item[0], anchor=anchor, page_width=page_width, page_height=page_height,
reference_page_frame=reference_page_frame, enforce=True,
)
]
if len(positioned) == 1:
@@ -397,6 +419,7 @@ def _glyph_gap_is_word_boundary(left: dict[str, Any], right: dict[str, Any]) ->
def _anchor_bbox_in_reference_region(
bbox: LayoutBBox, *, anchor: AnchorRule, page_width: float | None, page_height: float | None,
reference_page_frame: ReferencePageFrame | None = None,
enforce: bool = False,
) -> bool:
"""锚点配置了参考区时只接受该页相对位置内的命中,避免页眉重复标签干扰。"""
@@ -404,17 +427,22 @@ def _anchor_bbox_in_reference_region(
return True
if page_width is None or page_height is None or page_width <= 0 or page_height <= 0:
return False
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
region = _absolute_relative_region(
anchor.region, width=page_width, height=page_height, reference_page_frame=reference_page_frame,
)
return _glyph_center_inside({'bbox': bbox.model_dump(mode='json')}, region)
def _anchor_from_reference_region(
glyphs: list[dict[str, Any]], *, anchor: AnchorRule, page_width: float, page_height: float,
reference_page_frame: ReferencePageFrame | None = None,
) -> LayoutBBox | None:
"""为历史占位标签保留参考框内的实际标签几何,且调用方必须降级为人工复核。"""
if anchor.region is None:
return None
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
region = _absolute_relative_region(
anchor.region, width=page_width, height=page_height, reference_page_frame=reference_page_frame,
)
selected = [glyph for glyph in glyphs if _glyph_center_inside(glyph, region)]
return _union_bbox(selected) if selected else None
@@ -500,11 +528,19 @@ def _source_allowed(
return not ('coordinate' in required_levels and source != 'pdf_coordinate')
def _absolute_relative_region(region: RelativeRegion | None, *, width: float, height: float) -> LayoutBBox:
"""将固定低可靠度归一化页区投影为当前页面绝对框。"""
def _absolute_relative_region(
region: RelativeRegion | None, *, width: float, height: float,
reference_page_frame: ReferencePageFrame | None = None,
) -> LayoutBBox:
"""将区域投影为 PDF 点坐标;有标注页框时不得随当前长页高度缩放。"""
if region is None:
raise ValueError('fallback order field region is required')
return LayoutBBox(x0=region.x0 * width, y0=region.y0 * height, x1=region.x1 * width, y1=region.y1 * height)
projection_width = reference_page_frame.width if reference_page_frame is not None else width
projection_height = reference_page_frame.height if reference_page_frame is not None else height
return LayoutBBox(
x0=region.x0 * projection_width, y0=region.y0 * projection_height,
x1=region.x1 * projection_width, y1=region.y1 * projection_height,
)
def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutBBox) -> LayoutBBox:
@@ -518,14 +554,17 @@ def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutB
)
def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float) -> LayoutBBox:
"""读取管理员值框;右侧/下方字段只随标签平移,绝不按标签框尺寸缩放。"""
def _absolute_value_region(
*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float,
reference_page_frame: ReferencePageFrame | None = None,
) -> LayoutBBox:
"""读取管理员值框;有保存参考锚点时整框随唯一命中标签平移,绝不缩放。"""
if layout.value_region is not None:
if layout.anchor is None or layout.anchor.region is None:
return _absolute_anchor_region(layout.value_region, anchor)
if layout.value_mode not in {'right_of_anchor', 'below_anchor'}:
return _absolute_anchor_region(layout.value_region, anchor)
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame)
saved = _absolute_anchor_region(layout.value_region, reference)
if layout.value_mode == 'right_of_anchor':
region = _absolute_anchor_region(layout.value_region, anchor)
@@ -536,19 +575,33 @@ def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, widt
x1=anchor.x1 + projected_width, y1=region.y1,
)
elif layout.absolute_value_region is not None:
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height, reference_page_frame=reference_page_frame)
if layout.anchor is None or layout.anchor.region is None:
return saved
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame)
else:
raise ValueError('anchored order field has no value region')
if layout.value_mode not in {'right_of_anchor', 'below_anchor'}:
# absolute_value_region 记录的是标注页上的完整取值框。标签在当前
# 文档因可选单头内容整体移动时,single_line/multi_line 也必须保留
# 框的形状,并以该字段自己的唯一锚点中心作同量平移。
if layout.absolute_value_region is not None:
reference_center_x = (reference.x0 + reference.x1) / 2
reference_center_y = (reference.y0 + reference.y1) / 2
anchor_center_x = (anchor.x0 + anchor.x1) / 2
anchor_center_y = (anchor.y0 + anchor.y1) / 2
return LayoutBBox(
x0=saved.x0 + anchor_center_x - reference_center_x,
y0=saved.y0 + anchor_center_y - reference_center_y,
x1=saved.x1 + anchor_center_x - reference_center_x,
y1=saved.y1 + anchor_center_y - reference_center_y,
)
return saved
anchor_center_x, anchor_center_y = (anchor.x0 + anchor.x1) / 2, (anchor.y0 + anchor.y1) / 2
if _regions_overlap(anchor, reference):
return saved
if layout.absolute_value_region is not None and not _uses_movable_anchor_value_region(
layout=layout, width=width, height=height,
layout=layout, width=width, height=height, reference_page_frame=reference_page_frame,
):
return saved
if layout.value_mode == 'right_of_anchor':
@@ -563,7 +616,10 @@ def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, widt
)
def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float, height: float) -> bool:
def _uses_movable_anchor_value_region(
*, layout: OrderFieldLayout, width: float, height: float,
reference_page_frame: ReferencePageFrame | None = None,
) -> bool:
"""判断新相对规则或同一行的旧右侧框是否应跟随实际标签移动。"""
if layout.value_region is not None:
return layout.value_mode in {'right_of_anchor', 'below_anchor'}
@@ -572,8 +628,8 @@ def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float,
or layout.value_mode not in {'right_of_anchor', 'below_anchor'}
):
return False
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame)
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height, reference_page_frame=reference_page_frame)
tolerance = max(reference.y1 - reference.y0, saved.y1 - saved.y0) * 2
return saved.y0 <= reference.y1 + tolerance and reference.y0 <= saved.y1 + tolerance
@@ -50,6 +50,15 @@ class RelativeRegion(OrderProfileModel):
return self
class ReferencePageFrame(OrderProfileModel):
"""冻结标注样本的 PDF CropBox 点尺寸,供跨页高变化时还原相对区域。"""
width: float = Field(gt=0)
height: float = Field(gt=0)
origin: Literal['pdf_top_left'] = 'pdf_top_left'
box: Literal['cropbox'] = 'cropbox'
class AnchorRelativeRegion(OrderProfileModel):
"""仅接收历史锚点相对值框;新模板统一保存 absolute_value_region。"""
@@ -251,7 +260,7 @@ class TableRegionProfile(OrderProfileModel):
page_no: int | None = Field(default=None, ge=1)
region: RelativeRegion
# 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。
line_start_field_code: str = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
line_start_field_code: str | None = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
# 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows'
# 人工确认本表区自动标注时采用的视觉几何来源;仅用于审计、盲测和冲突复核,
@@ -291,7 +300,7 @@ class TableRegionProfile(OrderProfileModel):
if len(fields) != len(set(fields)):
raise ValueError('field_code may bind to only one coordinate region per table')
# 草稿可先框物理行;一旦主行开始绑字段,就必须包含起行锚点。
if self.line_layouts and self.line_layouts[0].field_regions and self.line_start_field_code not in {
if self.line_start_field_code and self.line_layouts and self.line_layouts[0].field_regions and self.line_start_field_code not in {
field.field_code for field in self.line_layouts[0].field_regions
}:
raise ValueError('main line layout must bind the configured line-start field')
@@ -488,6 +497,7 @@ class OrderCoordinateProfile(OrderProfileModel):
order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list)
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list)
coordinate_model: CoordinateModel = Field(default_factory=CoordinateModel)
reference_page_frames: dict[int, ReferencePageFrame] = Field(default_factory=dict)
@model_validator(mode='after')
def validate_profile_rules(self) -> 'OrderCoordinateProfile':
@@ -150,6 +150,7 @@ def match_frozen_coordinate_profiles(
table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
coordinate_model=definition.get('coordinate_model') or {},
reference_page_frames=definition.get('reference_page_frames') or {},
)
except (TypeError, ValueError):
continue
@@ -506,29 +507,49 @@ def _extract_matching_signature(raw: dict[str, Any]) -> tuple[dict[str, Any] | N
def _resolve_coordinate_transform(
*, profile: OrderCoordinateProfile, pages: dict[str, Any], page_glyphs: dict[str, Any],
) -> tuple[dict[str, Any] | None, list[str]]:
"""根据 Profile 声明的唯一静态锚点求受限平移,任何不确定性都返回硬失败原因。
"""根据冻结的模板身份锚点求受限平移,任何不确定性都返回硬失败原因。
Args:
profile: 当前冻结坐标 Profile;仅 ``anchor_frame`` 启用此能力。
profile: 当前冻结坐标 Profile;旧 ``anchor_frame`` 优先,其他模板复用已框选的
必选文档匹配标签,不要求管理员选择坐标模型。
pages: 当前 Layout 的页尺寸证据。
page_glyphs: 当前 Layout 的页级 PDF/OCR 字符坐标。
Returns:
``(transform, reason_codes)``。legacy 返回 ``(None, [])``;anchor_frame 仅在
所有锚点唯一且变换位于声明上限内时返回 ``status=applied``。
``(transform, reason_codes)``。没有可证明的静态标签时返回 ``(None, [])``;
有标签时仅在全部唯一且变换位于受限范围内返回 ``status=applied``。
"""
model = profile.coordinate_model
anchors = list(model.anchors)
max_translate_x = model.max_translate_x
max_translate_y = model.max_translate_y
if model.type != 'anchor_frame':
anchors = [
AnchorRule(
anchor_id=anchor.anchor_id,
text=anchor.label,
match_mode='exact',
region=anchor.label_region,
position_locked=True,
minimum_evidence_level=anchor.minimum_evidence_level,
)
for anchor in profile.document_match.required_anchors
if anchor.label_region is not None
]
# 没有已框选的稳定标签时保持绝对坐标兼容;不从全文猜测校正基准。
if not anchors:
return None, []
if not anchors:
return None, []
deltas: list[tuple[float, float]] = []
anchor_points: list[tuple[float, float, float, float]] = []
anchor_ids: list[str] = []
for anchor in model.anchors:
for anchor in anchors:
found = _find_anchor_rule_matches(
anchor=anchor, pages=pages, page_glyphs=page_glyphs,
max_translate_x=min(.30, model.max_translate_x * 2),
max_translate_y=min(.30, model.max_translate_y * 2),
max_translate_x=min(.30, max_translate_x * 2),
max_translate_y=min(.30, max_translate_y * 2),
)
if not found:
return None, ['profile_anchor_frame_anchor_missing']
@@ -552,7 +573,7 @@ def _resolve_coordinate_transform(
anchor_points.append((expected_x, expected_y, observed_x, observed_y))
anchor_ids.append(anchor.anchor_id)
if model.transform_mode == 'affine':
if model.type == 'anchor_frame' and model.transform_mode == 'affine':
transform, reason = _resolve_affine_coordinate_transform(
anchor_points=anchor_points, anchor_ids=anchor_ids, model=model,
)
@@ -561,7 +582,7 @@ def _resolve_coordinate_transform(
first_x, first_y = deltas[0]
if any(abs(x - first_x) > .01 or abs(y - first_y) > .01 for x, y in deltas[1:]):
return None, ['profile_anchor_frame_anchor_inconsistent']
if abs(first_x) > model.max_translate_x or abs(first_y) > model.max_translate_y:
if abs(first_x) > max_translate_x or abs(first_y) > max_translate_y:
return None, ['profile_anchor_frame_transform_out_of_range']
return {
'status': 'applied',
@@ -51,6 +51,8 @@ def validate_profile_parse_candidate(
document_match=profile_def.get('document_match') or {'required_anchors': [], 'optional_anchors': []},
table_regions=profile_def.get('table_regions') or [],
order_field_layouts=profile_def.get('order_field_layouts') or [],
coordinate_model=profile_def.get('coordinate_model') or {},
reference_page_frames=profile_def.get('reference_page_frames') or {},
)
except (TypeError, ValueError):
return {
@@ -1,456 +0,0 @@
"""
services/shipping_notice/document_layout/profile_field_source_mapping_service.py
用途:Profile 字段来源映射服务(Q18 抽取层裁决前置)——独立收集 Header / Table 列 /
Vendor Comments 三个来源的候选观察,**不直接写 Observation 表**,只返回统一的
FieldSourceCandidate 列表供 SourceMergeService 做 Q18 裁决合并。
依赖:profile_vendor_comments_contract(parse_field_source_mappings/parse_named_regions)、
field_split_core(execute_base_split_rule_set 用于 Vendor Comments 区域拆分)、
coordinate_region_source_adapter(CoordinateRegionSourceAdapter 物理区域渲染)、
reservation_relation_projection(ReservationRelationProjection 关系投影)。
逻辑:严格「后端决定 UI」——本类输出每个候选的 target_scope/target_field_code/
effective_line_no/value/source/evidence_ref/source_observation_metadata,
前端只能消费这些投影字段,禁止自行推导业务状态。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal
from app.services.shipping_notice.document_layout.coordinate_region_source_adapter import (
CoordinateRegionEvidence,
CoordinateRegionSourceAdapter,
CoordinateRegionSourceResult,
)
from app.services.shipping_notice.document_layout.field_split_core import (
CoreCapturedRelation,
_CoreSegmentResult,
execute_base_split_rule_set,
)
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
NamedRegion,
ProfileFieldSourceMapping,
parse_field_source_mappings,
parse_named_regions,
)
from app.services.shipping_notice.document_layout.reservation_relation_projection import (
ReservationRelationProjection,
ReservationRelationProjectionResult,
)
FieldSourceLiteral = Literal['header_region', 'table_column', 'vendor_comments']
@dataclass
class FieldSourceCandidate:
"""
单来源单观察候选——Header/Table/Vendor Comments 各自产出后,由 SourceMergeService 裁决。
【后端决定 UI】:scope、line_no、value、format_valid、conflict_group_key 全部在本层
计算完毕,前端只读投影,禁止自己用逻辑 if/else 推导。
"""
source: FieldSourceLiteral
target_scope: Literal['header', 'line']
target_field_code: str
target_field_id: str
value: str
normalized_value: str
format_valid: bool | None # None = 本字段不需要格式校验(非 reservation)
format_reason_code: str | None # format_valid=False 时的稳定诊断码(例:reservation_format_invalid)
effective_line_no: int | None # 1-based;header 时为 None;default_all_lines 时为具体行号
resolution_hint: Literal[
'provisional', 'annotation_only', 'invalid_line_reference',
] = 'provisional'
relation_projection: ReservationRelationProjectionResult | None = None
# 证据区——写入 Observation.evidence_quote / evidence_ref / evidence_metadata_json
evidence_quote: str | None = None
evidence_ref: str | None = None
evidence_metadata: dict[str, Any] = field(default_factory=dict)
# SourceMergeService 内部使用:冲突分组键 = (target_scope, target_field_code, effective_line_no)
conflict_group_key: tuple[Any, ...] = ()
class ProfileFieldSourceMappingService:
"""
三来源候选独立收集服务(路径判断与事实分离)。
【AI 触发时机】:订单文档抽取阶段(order_extraction_workflow 在 Observation 写入前)
调用 collect_candidates() 返回候选列表,再交给 SourceMergeService 裁决合并。
核心执行顺序:
[STEP 1] 解析 Profile definition_json 的 named_regions + field_source_mappings。
[STEP 2] 对每个 mapping:
a. header_source_enabled → 从 header_observations_by_source_ref 取现成观察
b. table_source_enabled → 从 table_column_values 取(column_code + line_index)
c. vendor_comments_enabled → 调 CoordinateRegionSourceAdapter + execute_base_split_rule_set
[STEP 3] 对每个 Vendor Comments 拆分结果,调 ReservationRelationProjection.project
生成 effective_line_no / resolution_hint。
[STEP 4] 返回 FieldSourceCandidate 列表;未通过 format_policy 的候选保留
value 但标记 format_valid=False(Q15:格式失败的值不丢弃)。
"""
def __init__(
self,
*,
definition_json: dict[str, Any],
header_observations_by_source_ref: dict[str, list[dict[str, Any]]] | None = None,
table_column_values: dict[str, list[dict[str, Any]]] | None = None,
page_glyphs_map: dict[int, dict[str, Any]] | None = None,
# Reservation Relation Projection 三层判定表
explicit_line_column_values: dict[int, str] | None = None,
profile_business_line_numbers: dict[int, Any] | None = None,
classified_logical_line_numbers: dict[int, int] | None = None,
total_logical_lines: int = 0,
# 格式策略调用方(保留注入点,避免本类直接 import reservation 校验模块造成循环)
format_validator_callback=None,
):
self.definition_json = definition_json or {}
self.header_observations_by_source_ref = header_observations_by_source_ref or {}
self.table_column_values = table_column_values or {}
self.page_glyphs_map = page_glyphs_map or {}
self.explicit_line_column_values = explicit_line_column_values or {}
self.profile_business_line_numbers = profile_business_line_numbers or {}
self.classified_logical_line_numbers = classified_logical_line_numbers or {}
self.total_logical_lines = total_logical_lines
self.format_validator_callback = format_validator_callback
# 预先解析契约(若失败抛 ValidationError 阻断运行,避免输出坏数据)
self.named_regions: dict[str, NamedRegion] = parse_named_regions(
self.definition_json.get('named_regions'),
)
self.mappings: list[ProfileFieldSourceMapping] = parse_field_source_mappings(
self.definition_json.get('field_source_mappings'),
)
# ------------------------------------------------------------------
# 对外主入口
# ------------------------------------------------------------------
def collect_candidates(self) -> list[FieldSourceCandidate]:
"""
返回全量候选。任何内部失败都返回稳定 status 候选(不抛错阻断其他字段)。
调用方:SourceMergeService.merge_and_decide() → 再调用 obs 写入。
"""
candidates: list[FieldSourceCandidate] = []
for mapping in self.mappings:
if mapping.header_source_enabled and mapping.header_source_ref:
candidates.extend(self._collect_header_source(mapping))
if mapping.table_source_enabled and mapping.table_column_code:
candidates.extend(self._collect_table_source(mapping))
if mapping.vendor_comments_enabled and mapping.vendor_comments_region_ref:
candidates.extend(self._collect_vendor_comments_source(mapping))
for cand in candidates:
cand.conflict_group_key = (cand.target_scope, cand.target_field_code, cand.effective_line_no)
return candidates
# ------------------------------------------------------------------
# 三个来源分支(独立收集,不互相读数据——满足 Q18 先独立再裁决)
# ------------------------------------------------------------------
def _collect_header_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
"""Header 区域来源——从 caller 传入的 header_observations_by_source_ref 读取。"""
header_items = self.header_observations_by_source_ref.get(mapping.header_source_ref or '', [])
results: list[FieldSourceCandidate] = []
for item in header_items:
raw_value = str(item.get('value') or '')
format_valid, reason = self._check_format(mapping, raw_value)
results.append(FieldSourceCandidate(
source='header_region',
target_scope=mapping.target_scope,
target_field_code=mapping.target_field_code,
target_field_id=mapping.target_field_id,
value=raw_value,
normalized_value=_normalize_string(raw_value),
format_valid=format_valid,
format_reason_code=reason,
effective_line_no=None, # header scope 固定 None
evidence_quote=raw_value[:512],
evidence_ref=str(item.get('evidence_ref') or '') or None,
evidence_metadata=dict(item.get('evidence_metadata') or {}),
))
return results
def _collect_table_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
"""表身列来源——从 caller 传入的 table_column_values[column_code] 读取,每行一个候选。"""
rows = self.table_column_values.get(mapping.table_column_code or '', [])
results: list[FieldSourceCandidate] = []
for row in rows:
try:
line_no = int(row.get('line_index')) + 1 # 转 1-based
except (TypeError, ValueError):
continue
raw_value = str(row.get('value') or '')
format_valid, reason = self._check_format(mapping, raw_value)
results.append(FieldSourceCandidate(
source='table_column',
target_scope=mapping.target_scope,
target_field_code=mapping.target_field_code,
target_field_id=mapping.target_field_id,
value=raw_value,
normalized_value=_normalize_string(raw_value),
format_valid=format_valid,
format_reason_code=reason,
effective_line_no=line_no,
evidence_quote=raw_value[:512],
evidence_ref=str(row.get('evidence_ref') or '') or None,
evidence_metadata=dict(row.get('evidence_metadata') or {}),
))
return results
def _collect_vendor_comments_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
"""
Vendor Comments 来源——三步走:
1. CoordinateRegionSourceAdapter 渲染区域原文 + bbox 证据;
2. execute_base_split_rule_set 拆出段(带 captured_relation);
3. ReservationRelationProjection 投影关系到 effective_line_no / resolution_hint。
"""
region_ref = mapping.vendor_comments_region_ref or ''
region = self.named_regions.get(region_ref)
if region is None:
return [self._missing_region_fallback(mapping, region_ref)]
adapter = CoordinateRegionSourceAdapter(region, self.page_glyphs_map)
region_result: CoordinateRegionSourceResult = adapter.extract()
if region_result.status != 'available' or not mapping.vendor_comments_split_rule_set:
return [self._unavailable_region_candidate(mapping, region_result)]
split_result = execute_base_split_rule_set(
raw_value=region_result.raw_text,
rule_set=mapping.vendor_comments_split_rule_set,
lines=region_result.lines or None,
)
projector = ReservationRelationProjection(
relation_policy=mapping.relation_policy,
line_reference_basis=mapping.line_reference_basis,
missing_relation_policy=mapping.missing_relation_policy,
)
# 先收集 mapped 段,再收集 evidence_only 段(annotation_only 用)
all_segments: list[_CoreSegmentResult] = list(split_result.segments) + list(split_result.evidence_only_segments)
results: list[FieldSourceCandidate] = []
token_evidence_map = _build_evidence_ref_map(region_result.evidence_tokens)
for seg in all_segments:
rel_proj = projector.project(
captured_relation=seg.captured_relation,
explicit_line_column_values=self.explicit_line_column_values,
profile_business_line_numbers=self.profile_business_line_numbers,
classified_logical_line_numbers=self.classified_logical_line_numbers,
)
format_valid, reason = self._check_format(mapping, seg.normalized_text)
if rel_proj.resolution == 'bound_to_line':
results.append(self._make_vc_candidate(
mapping=mapping, seg=seg, rel_proj=rel_proj,
region_result=region_result, token_evidence_map=token_evidence_map,
effective_line_no=rel_proj.resolved_logical_line_no,
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
))
elif rel_proj.resolution == 'default_all_lines':
# 每行都生成一个(common case:整个 Vendor Comments 段没有 line 号引用)
for line_idx in range(1, max(1, self.total_logical_lines) + 1):
results.append(self._make_vc_candidate(
mapping=mapping, seg=seg, rel_proj=rel_proj,
region_result=region_result, token_evidence_map=token_evidence_map,
effective_line_no=line_idx if mapping.target_scope == 'line' else None,
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
))
elif rel_proj.resolution == 'annotation_only':
results.append(self._make_vc_candidate(
mapping=mapping, seg=seg, rel_proj=rel_proj,
region_result=region_result, token_evidence_map=token_evidence_map,
effective_line_no=None,
resolution_hint='annotation_only', format_valid=format_valid, format_reason=reason,
))
elif rel_proj.resolution == 'invalid_line_reference':
results.append(self._make_vc_candidate(
mapping=mapping, seg=seg, rel_proj=rel_proj,
region_result=region_result, token_evidence_map=token_evidence_map,
effective_line_no=None,
resolution_hint='invalid_line_reference', format_valid=False,
format_reason=reason or 'invalid_line_reference',
))
else:
# default_header_only / conflict_unresolved
results.append(self._make_vc_candidate(
mapping=mapping, seg=seg, rel_proj=rel_proj,
region_result=region_result, token_evidence_map=token_evidence_map,
effective_line_no=None if mapping.target_scope == 'header' else None,
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
))
return results
# ------------------------------------------------------------------
# 辅助:格式校验(Q15)+ Vendor Comments 候选构造
# ------------------------------------------------------------------
def _check_format(
self, mapping: ProfileFieldSourceMapping, value: str,
) -> tuple[bool | None, str | None]:
"""返回 (format_valid, reason_code);非 reservation 字段返回 (None, None)。"""
if mapping.target_field_code != 'reservation_id':
return None, None
if not value:
return False, 'reservation_format_empty'
if self.format_validator_callback is not None:
ok = bool(self.format_validator_callback(mapping.format_policy, value))
return (True, None) if ok else (False, 'reservation_format_invalid')
# 默认回退全局 validated_reservation_id(Q15 方案 A:本期不重构全局)
from app.services.shipping_notice.reservation_id import validated_reservation_id
ok = validated_reservation_id(value) is not None
return (True, None) if ok else (False, 'reservation_format_invalid')
@staticmethod
def _missing_region_fallback(mapping: ProfileFieldSourceMapping, region_ref: str) -> FieldSourceCandidate:
return FieldSourceCandidate(
source='vendor_comments',
target_scope=mapping.target_scope,
target_field_code=mapping.target_field_code,
target_field_id=mapping.target_field_id,
value='',
normalized_value='',
format_valid=None,
format_reason_code=None,
effective_line_no=None,
resolution_hint='provisional',
evidence_quote=None,
evidence_ref=None,
evidence_metadata={'reason': 'named_region_not_found', 'region_ref': region_ref},
)
@staticmethod
def _unavailable_region_candidate(
mapping: ProfileFieldSourceMapping, region_result: CoordinateRegionSourceResult,
) -> FieldSourceCandidate:
return FieldSourceCandidate(
source='vendor_comments',
target_scope=mapping.target_scope,
target_field_code=mapping.target_field_code,
target_field_id=mapping.target_field_id,
value='',
normalized_value='',
format_valid=None,
format_reason_code=None,
effective_line_no=None,
resolution_hint='provisional',
evidence_quote=region_result.raw_text[:512] or None,
evidence_ref=None,
evidence_metadata={
'reason': region_result.diagnostic_code or 'named_region_unavailable',
'diagnostic_message': region_result.diagnostic_message,
'region_id': region_result.region_id,
},
)
@staticmethod
def _make_vc_candidate(
*,
mapping: ProfileFieldSourceMapping,
seg: _CoreSegmentResult,
rel_proj: ReservationRelationProjectionResult,
region_result: CoordinateRegionSourceResult,
token_evidence_map: dict[str, list[CoordinateRegionEvidence]],
effective_line_no: int | None,
resolution_hint: Literal['provisional', 'annotation_only', 'invalid_line_reference'],
format_valid: bool | None,
format_reason: str | None,
) -> FieldSourceCandidate:
token_ev = _find_best_token_evidence(token_evidence_map, seg.normalized_text)
evidence_quote = seg.raw_text[:512] or None
evidence_ref = _vc_evidence_ref(region_result, seg, token_ev)
metadata: dict[str, Any] = {
'region_id': region_result.region_id,
'segment_id': seg.segment_id,
'rule_id': seg.rule_id,
'matcher_type': seg.matcher_type,
'handling': seg.handling,
'line_bounds_in_region': [seg.line_no, seg.line_end_no],
'captured_relation_raw': (
None if seg.captured_relation is None else {
'type': seg.captured_relation.type,
'line_no': seg.captured_relation.line_no,
'raw_text': seg.captured_relation.raw_text,
}
),
'relation_projection': _proj_to_json(rel_proj),
'best_token': (None if token_ev is None else {
'page_no': token_ev.page_no,
'x0': token_ev.x0, 'y0': token_ev.y0,
'x1': token_ev.x1, 'y1': token_ev.y1,
'text': token_ev.text,
}),
}
return FieldSourceCandidate(
source='vendor_comments',
target_scope=mapping.target_scope,
target_field_code=mapping.target_field_code,
target_field_id=mapping.target_field_id,
value=seg.raw_text,
normalized_value=seg.normalized_text,
format_valid=format_valid,
format_reason_code=format_reason,
effective_line_no=effective_line_no,
resolution_hint=resolution_hint,
relation_projection=rel_proj,
evidence_quote=evidence_quote,
evidence_ref=evidence_ref,
evidence_metadata=metadata,
)
# ---------------------------------------------------------------------------
# 模块级纯函数(避免每次 Service 实例化重复加载)
# ---------------------------------------------------------------------------
def _normalize_string(v: str) -> str:
return ' '.join(str(v or '').split()).strip()
def _build_evidence_ref_map(tokens: list[CoordinateRegionEvidence]) -> dict[str, list[CoordinateRegionEvidence]]:
out: dict[str, list[CoordinateRegionEvidence]] = {}
for t in tokens:
out.setdefault(_normalize_string(t.text), []).append(t)
return out
def _find_best_token_evidence(
evidence_map: dict[str, list[CoordinateRegionEvidence]], value: str,
) -> CoordinateRegionEvidence | None:
norm = _normalize_string(value)
if norm in evidence_map and evidence_map[norm]:
return evidence_map[norm][0]
# 降级:子串命中
for key, tokens in evidence_map.items():
if norm and (norm in key or key in norm) and tokens:
return tokens[0]
return None
def _vc_evidence_ref(
region_result: CoordinateRegionSourceResult,
seg: _CoreSegmentResult,
token: CoordinateRegionEvidence | None,
) -> str:
"""
稳定 Observation.evidence_ref。
格式:vc://<region_id>/p<page_no>/seg-<segment_id>[:<x0>-<y0>-<x1>-<y1>]
"""
base = f"vc://{region_result.region_id}/p{region_result.page_no}/seg-{seg.segment_id}"
if token is not None:
base += (
f":{round(token.x0, 4)}-{round(token.y0, 4)}-"
f"{round(token.x1, 4)}-{round(token.y1, 4)}"
)
return base[:512]
def _proj_to_json(p: ReservationRelationProjectionResult) -> dict[str, Any]:
return {
'line_reference_basis': p.line_reference_basis,
'resolution': p.resolution,
'resolved_logical_line_no': p.resolved_logical_line_no,
'annotation_reason': p.annotation_reason,
'invalid_reference_raw_value': p.invalid_reference_raw_value,
'invalid_reference_line_no': p.invalid_reference_line_no,
'audit_chain_count': 0 if p.audit_chain is None else len(p.audit_chain),
}
@@ -1,338 +0,0 @@
"""
services/shipping_notice/document_layout/profile_vendor_comments_contract.py
用途:Profile 顶层新增的 Vendor Comments 三来源契约(不修改现有 OrderCoordinateProfile 字段,
保持「路径判断与事实分离」——definition_json.get 读取命名区域和字段来源映射)。
依赖:Pydantic、field_split_core.BaseSplitRuleSet、RelativeRegion(来自 order_profile)。
逻辑:对外暴露 parse_named_regions() / parse_field_source_mappings() / validate_format_policy()
三个稳定入口;所有变更是否触发「回 Draft + 重新验证」由 profile_regions_require_draft()
判定,禁止各业务点自行假设回 Draft 条件。
"""
from __future__ import annotations
import hashlib
import json
import re
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from app.core.errors import ValidationError
from app.services.shipping_notice.document_layout.field_split_core import (
BaseSplitRuleSet,
)
from app.services.shipping_notice.document_layout.order_profile import (
RelativeRegion,
)
# ---------------------------------------------------------------------------
# 顶层 Pydantic 契约——definition_json 结构
# ---------------------------------------------------------------------------
VC_MODEL_CONFIG = ConfigDict(extra='forbid', validate_assignment=True)
class NamedRegion(BaseModel):
"""
物理来源命名区域(Q14 冻结)——管理员圈选的坐标框。
【关键约束】:不是 Schema 字段区域伪装,是 Vendor Comments 等非 XFA 正文块的真实
阅读区域。变更此对象必须回 Draft(由 profile_regions_require_draft 判定)。
"""
model_config = VC_MODEL_CONFIG
region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$')
label: str = Field(min_length=1, max_length=160)
region: RelativeRegion
page_scope: Literal['first_page', 'last_page', 'all_pages', 'exact_page'] = 'last_page'
page_no: int | None = Field(default=None, ge=1)
selection_mode: Literal['fixed_region', 'auto_take_last_qualified'] = 'fixed_region'
@model_validator(mode='after')
def validate_page_semantics(self) -> 'NamedRegion':
if self.page_scope == 'exact_page' and self.page_no is None:
raise ValueError('exact_page named region requires page_no')
if self.page_scope != 'exact_page' and self.page_no is not None:
raise ValueError('page_no is only allowed for exact_page named region')
return self
class ReservationFormatPolicy(BaseModel):
"""
Reservation 格式校验策略(Q15 冻结)——Profile 级受控策略,未配置时回退全局 5/10 纯数字。
首期仅支持 numeric_5_or_10 / custom_safe_regex 两种;custom_safe_regex 必须经过
长度限制、捕获组限制、危险表达式黑名单与超时上限 4 层门禁。
"""
model_config = VC_MODEL_CONFIG
mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex'] = 'inherit_global'
pattern: str | None = Field(default=None, min_length=1, max_length=1024)
max_capture_groups: int = Field(default=2, ge=0, le=8)
timeout_ms: int = Field(default=30, ge=10, le=500)
case_sensitive: bool = False
@model_validator(mode='after')
def validate_regex_policy(self) -> 'ReservationFormatPolicy':
if self.mode != 'custom_safe_regex':
if self.pattern is not None:
raise ValueError('pattern only allowed for custom_safe_regex mode')
return self
if not self.pattern:
raise ValueError('custom_safe_regex requires a non-empty pattern')
_validate_safe_regex_pattern(
self.pattern,
max_groups=self.max_capture_groups,
case_sensitive=self.case_sensitive,
)
return self
class ProfileFieldSourceMapping(BaseModel):
"""
Profile 级字段来源映射(Q9 冻结,并列 split_rules)——声明一个 Schema 字段从三来源
(header/table_column/vendor_comments)哪几个抽取,以及各自使用的拆分规则与关系策略。
"""
model_config = VC_MODEL_CONFIG
mapping_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
target_scope: Literal['header', 'line']
target_field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
target_field_id: str = Field(min_length=1, max_length=128)
# 三来源开关——未启用的来源在 ProfileFieldSourceMappingService 直接跳过
header_source_enabled: bool = False
header_source_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$')
header_normalizer_key: str | None = Field(default=None, min_length=1, max_length=64)
table_source_enabled: bool = False
table_column_code: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$')
vendor_comments_enabled: bool = False
vendor_comments_region_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_-]{0,95}$')
vendor_comments_split_rule_set: BaseSplitRuleSet | None = None
# 关系策略(Q2 双层设计)——本期仅 reservation_id 绑定明细行使用 bind_target_line
relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'] = 'no_relation'
missing_relation_policy: Literal['default_all_lines', 'default_header_only', 'fallback_single_line_when_no_reference'] = 'default_header_only'
line_reference_basis: Literal['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no'] = 'profile_business_line_no'
# 三来源空值互补策略——Q4 冲突矩阵里不同 scope 独立保留,同 scope 值不一致 Review
fill_missing_from_other_sources: bool = True
format_policy: ReservationFormatPolicy = Field(default_factory=ReservationFormatPolicy)
@model_validator(mode='after')
def validate_source_refs(self) -> 'ProfileFieldSourceMapping':
if self.header_source_enabled and not self.header_source_ref:
raise ValueError('header_source_ref is required when header_source_enabled')
if self.table_source_enabled and not self.table_column_code:
raise ValueError('table_column_code is required when table_source_enabled')
if self.vendor_comments_enabled:
if not self.vendor_comments_region_ref:
raise ValueError('vendor_comments_region_ref is required when vendor_comments_enabled')
if not self.vendor_comments_split_rule_set:
raise ValueError('vendor_comments_split_rule_set is required when vendor_comments_enabled')
return self
# ---------------------------------------------------------------------------
# 稳定读取工具:接受 None / 脏 dict,返回归一化契约对象(路径判断与事实分离)
# ---------------------------------------------------------------------------
def parse_named_regions(value: Any) -> dict[str, NamedRegion]:
"""
从 definition_json.named_regions(或 None)解析命名区域字典。
【AI 触发时机】:读取 Profile 配置阶段、预览阶段或变更比对阶段调用。
核心逻辑:值为 None/空 dict 时返回空字典(允许客户先不配 Vendor Comments 区域);
未知键直接保留映射,不抛错;坏值立刻抛 ValidationError 避免运行时污染。
Args:
value: Profile definition_json.get('named_regions') 原值。
Returns:
{region_id: NamedRegion} 字典。
"""
if value is None:
return {}
if not isinstance(value, dict):
raise ValidationError(
'definition_json.named_regions must be an object',
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
)
result: dict[str, NamedRegion] = {}
for key, raw in value.items():
if not re.match(r'^[a-z][a-z0-9_-]{0,95}$', str(key)):
raise ValidationError(
f'named region key {key!r} is invalid',
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
)
try:
item = NamedRegion.model_validate(raw) if isinstance(raw, dict) else raw
except ValueError as exc:
raise ValidationError(
f'named region {key!r} is invalid: {exc}',
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
) from exc
if item.region_id != key:
raise ValidationError(
f'named region key {key!r} must match nested region_id {item.region_id!r}',
code='SHIPPING.PROFILE_NAMED_REGIONS_MISMATCH',
)
result[key] = item
return result
def parse_field_source_mappings(value: Any) -> list[ProfileFieldSourceMapping]:
"""
从 definition_json.field_source_mappings(或 None)解析字段来源映射列表。
核心逻辑:返回值为稳定顺序列表,不做去重(重复的 target_scope/target_field_code
组合将由 SourceMergeService 在抽取层做 Q18 冲突裁决)。
"""
if value is None:
return []
if not isinstance(value, list):
raise ValidationError(
'definition_json.field_source_mappings must be a list',
code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID',
)
results: list[ProfileFieldSourceMapping] = []
for raw in value:
try:
results.append(ProfileFieldSourceMapping.model_validate(raw))
except ValueError as exc:
raise ValidationError(
f'field source mapping is invalid: {exc}',
code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID',
) from exc
return results
# ---------------------------------------------------------------------------
# 变更回 Draft 门禁(Q14 冻结:区域变化必须使 Profile 回 Draft)
# ---------------------------------------------------------------------------
REGION_CHANGE_REQUIRES_DRAFT_KEYS = frozenset({
'region', 'page_scope', 'page_no', 'selection_mode',
})
def profile_regions_require_draft(
*,
old_named_regions: Any,
new_named_regions: Any,
) -> bool:
"""
判断 named_regions 变更是否触发 Profile 回 Draft + 重新验证 + 盲测 + 发布。
核心逻辑(fail-safe):任何 region 主键、坐标、页作用域、选取模式的增删改一律回 Draft;
仅 label 文案调整(便于管理员标注说明)不触发。
"""
try:
old_map = parse_named_regions(old_named_regions)
new_map = parse_named_regions(new_named_regions)
except ValidationError:
return True # 解析失败默认回 Draft(fail-close)
if set(old_map.keys()) != set(new_map.keys()):
return True
for region_id in old_map:
old_region = old_map[region_id]
new_region = new_map[region_id]
for key in REGION_CHANGE_REQUIRES_DRAFT_KEYS:
if getattr(old_region, key) != getattr(new_region, key):
return True
return False
def field_source_mappings_require_draft(
*,
old_mappings: Any,
new_mappings: Any,
) -> bool:
"""
判断 field_source_mappings 变更是否触发回 Draft。
核心逻辑:除了纯 label 类改动外的任何增删改一律回 Draft(首期全量回 Draft,保留细粒度
门禁的未来扩展点)。
"""
try:
old_list = parse_field_source_mappings(old_mappings)
new_list = parse_field_source_mappings(new_mappings)
except ValidationError:
return True
if len(old_list) != len(new_list):
return True
old_payload = _stable_mapping_dumps(old_list)
new_payload = _stable_mapping_dumps(new_list)
return old_payload != new_payload
def _stable_mapping_dumps(items: list[ProfileFieldSourceMapping]) -> str:
payload = [m.model_dump(mode='json', sort_keys=True) for m in items]
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
# ---------------------------------------------------------------------------
# 安全正则门禁(Q15 custom_safe_regex 发布前必过)
# ---------------------------------------------------------------------------
_UNSAFE_PATTERN_MARKERS = (
r'\(.+[+*]\)\s*[+*]', # 嵌套量词 例: (a+)+
r'\(\.?\*\)\s*\*', # 多重.* 回溯
r'\(\[.*\]\)\{[0-9]+,[0-9]*\}', # 大范围字符类重复
r'(?<!\\)\\[bBwWsSdD].*[+*]', # 通用字符集 + 无限量词
r'\(\?:?\^?\$?.*\)\?\?', # 前后查找量词叠加
)
def _validate_safe_regex_pattern(pattern: str, *, max_groups: int, case_sensitive: bool) -> None:
"""
custom_safe_regex 的发布前样本验证门禁(Q15)——编译期就拦截危险表达式。
【注意】:运行时还需配合 timeout_ms 的 signal 看门狗(在 regex_runner_safe 中实现)。
"""
if len(pattern) > 1024:
raise ValueError('custom_safe_regex pattern exceeds 1024 characters')
for marker in _UNSAFE_PATTERN_MARKERS:
if re.search(marker, pattern):
raise ValueError('custom_safe_regex pattern looks potentially catastrophic')
flags = 0 if case_sensitive else re.IGNORECASE
try:
compiled = re.compile(pattern, flags)
except re.error as exc:
raise ValueError(f'custom_safe_regex pattern failed to compile: {exc}') from exc
if compiled.groups > max_groups:
raise ValueError(
f'custom_safe_regex has {compiled.groups} capture groups; limit is {max_groups}'
)
_ = compiled # 引用仅用于静态检查
# ---------------------------------------------------------------------------
# 校验和(盲测/发布基准比对)
# ---------------------------------------------------------------------------
def field_source_mappings_checksum(mappings: list[ProfileFieldSourceMapping]) -> str:
"""稳定 SHA-256 校验和,供发布冻结与审计引用。"""
payload = _stable_mapping_dumps(mappings).encode('utf-8')
return hashlib.sha256(payload).hexdigest()
def named_regions_checksum(regions: dict[str, NamedRegion]) -> str:
"""稳定 SHA-256 校验和,供区域变更历史比对。"""
payload = json.dumps(
{rid: r.model_dump(mode='json', sort_keys=True) for rid, r in regions.items()},
ensure_ascii=True, sort_keys=True, separators=(',', ':'),
).encode('utf-8')
return hashlib.sha256(payload).hexdigest()
@@ -1,152 +0,0 @@
"""
services/shipping_notice/document_layout/reservation_format_policy_service.py
用途:Q15 Reservation ID 格式策略服务——Profile 级 format_policy 受控入口。
首期(阶段 2)保持「回退全局 validated_reservation_id(numeric_5_or_10 硬编码)」
不变;为未来 custom_safe_regex / 字母型 Reservation 保留扩展点。
依赖:profile_vendor_comments_contract.ReservationFormatPolicy;
reservation_id.validated_reservation_id(全局回退)。
逻辑:【技术重试与业务决策分离】——本类只负责**格式判断**,不改变值、不生成 Observation,
调用方(ProfileFieldSourceMappingService._check_format)根据返回值标记
reservation_format_invalid,但不丢弃候选(保留为 Review 证据展示)。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Literal
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
ReservationFormatPolicy,
)
RESERVATION_NUMERIC_5_OR_10_RE = re.compile(r'^(?:\d{5}|\d{10})$')
@dataclass
class FormatPolicyResult:
"""格式校验结果——只描述事实,不携带业务动作。"""
valid: bool
mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex']
normalized_value: str | None = None # 仅 valid=True 时返回规范化值
reason_code: str | None = None # valid=False 时的稳定诊断码
@property
def should_block_auto_create(self) -> bool:
"""格式失败的值不得自动建单(Q15 冻结)。"""
return not self.valid
class ReservationFormatPolicyService:
"""
Profile 级 Reservation 格式策略受控入口。
【AI 触发时机】:ProfileFieldSourceMappingService 收集候选、或 Candidate
Qualification 最终门禁时调用 check()。禁止任何地方直接
if re.match(r'^\d{5,10}$', v) 绕过策略层。
"""
def check(self, policy: ReservationFormatPolicy, raw_value: str) -> FormatPolicyResult:
"""
执行一次格式校验。调用方不得丢弃失败候选,必须将原因码写入
FieldSourceCandidate.format_reason_code。
核心路径(Q15 冻结):
① mode=inherit_global → 调全局 validated_reservation_id 保持历史 71 调用方口径;
② mode=numeric_5_or_10 → 等价于全局(显式模式;便于未来全局重构时切换默认);
③ mode=custom_safe_regex → 调用发布前已通过 Pydantic 门禁的安全正则。
"""
value = (raw_value or '').strip()
if not value:
return FormatPolicyResult(
valid=False, mode=policy.mode, normalized_value=None,
reason_code='reservation_format_empty',
)
mode = policy.mode
if mode in {'inherit_global', 'numeric_5_or_10'}:
return self._check_numeric_5_or_10(value, mode)
if mode == 'custom_safe_regex':
return self._check_custom_safe_regex(policy, value)
return FormatPolicyResult(
valid=False, mode=mode, normalized_value=None,
reason_code='reservation_format_unknown_mode',
)
# ------------------------------------------------------------------
# 内部实现
# ------------------------------------------------------------------
@staticmethod
def _check_numeric_5_or_10(
value: str,
mode: Literal['inherit_global', 'numeric_5_or_10'],
) -> FormatPolicyResult:
"""纯数字 5/10 位——默认回退全局校验,但通过独立模块输出稳定结果。"""
# 先尝试全局 validated_reservation_id(保持与 71 调用方一致),失败再用本模块常量兜底
try:
from app.services.shipping_notice.reservation_id import validated_reservation_id
global_result = validated_reservation_id(value)
if global_result is not None:
return FormatPolicyResult(
valid=True, mode=mode, normalized_value=global_result,
reason_code=None,
)
except Exception: # fail-safe:若全局模块异常,不阻塞结果
pass
match = RESERVATION_NUMERIC_5_OR_10_RE.match(value)
if match:
return FormatPolicyResult(
valid=True, mode=mode, normalized_value=value,
reason_code=None,
)
return FormatPolicyResult(
valid=False, mode=mode, normalized_value=None,
reason_code='reservation_format_invalid',
)
@staticmethod
def _check_custom_safe_regex(policy: ReservationFormatPolicy, value: str) -> FormatPolicyResult:
"""安全正则匹配——编译缓存;捕获组第 1 组作为规范化值(否则整串)。"""
pattern = policy.pattern or ''
flags = 0 if policy.case_sensitive else re.IGNORECASE
try:
compiled = re.compile(pattern, flags)
except re.error as exc:
return FormatPolicyResult(
valid=False, mode='custom_safe_regex', normalized_value=None,
reason_code=f'reservation_format_regex_compile_error:{exc.__class__.__name__}',
)
# 发布前样本验证门禁已限制 catastrophic 风险;这里仅以标准 library 限制长度
if len(value) > 128:
return FormatPolicyResult(
valid=False, mode='custom_safe_regex', normalized_value=None,
reason_code='reservation_format_value_too_long',
)
match = compiled.search(value)
if not match:
return FormatPolicyResult(
valid=False, mode='custom_safe_regex', normalized_value=None,
reason_code='reservation_format_invalid',
)
# 规范化值:第 1 捕获组 → 整串
normalized: str = value
if compiled.groups >= 1:
try:
first_group = match.group(1)
if first_group:
normalized = str(first_group).strip()
except (IndexError, re.error):
normalized = match.group(0) or value
normalized = normalized.strip()
if not normalized:
return FormatPolicyResult(
valid=False, mode='custom_safe_regex', normalized_value=None,
reason_code='reservation_format_capture_empty',
)
return FormatPolicyResult(
valid=True, mode='custom_safe_regex', normalized_value=normalized,
reason_code=None,
)
@@ -1,228 +0,0 @@
"""
services/shipping_notice/document_layout/reservation_relation_projection.py
用途:Reservation 关系投影(Q2 双层设计 + Q12 invalid_line_reference 独立原因码)。
将拆分引擎内部捕获的 captured_relation + Profile 关系策略 relation_policy,
映射为「绑定到哪条行、是否 annotation_only、是否 invalid_line_reference 独立」三输出。
依赖:field_split_core.CoreCapturedRelation(来自 _CoreSegmentResult.captured_relation)、
ProfileFieldSourceMapping.relation_policy / line_reference_basis。
逻辑:严格遵循「路径判断与事实分离」——拆分引擎事实(line_no)只作为证据,
最终绑定路径必须经过 line_reference_basis 三层映射校验后裁决;
失败不抛异常,输出稳定 reason_code 供审计和前端翻译。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Literal
from app.services.shipping_notice.document_layout.field_split_core import (
CoreCapturedRelation,
)
@dataclass
class ReservationRelationProjectionResult:
"""关系投影最终结果——只输出明确分支,禁止上游自行判断。"""
line_reference_basis: Literal[
'explicit_line_column',
'profile_business_line_no',
'classified_logical_line_no',
]
resolution: Literal[
'bound_to_line', # bind_target_line 成功,resolved_logical_line_no 有值
'annotation_only', # 显式 annotation_only,Observation 存 metadata
'default_all_lines', # 关系缺失 + default_all_lines,每行都生成 Observation
'default_header_only', # 关系缺失 + default_header_only,写到 header scope
'invalid_line_reference', # 引用了不存在的行号,独立原因码 Q12
'conflict_unresolved', # 未来多层映射冲突保留(本期不输出)
]
resolved_logical_line_no: int | None = None # 1-based 逻辑行号,bound_to_line 时必填
annotation_reason: str | None = None # annotation_only 时写入 Observation metadata
invalid_reference_raw_value: str | None = None # invalid_line_reference 时返回 raw_text
invalid_reference_line_no: int | None = None
audit_chain: list[dict[str, Any]] | None = None # 路径判断全链路审计快照
@property
def should_generate_line_observation(self) -> bool:
return self.resolution == 'bound_to_line' or self.resolution == 'default_all_lines'
@property
def should_generate_header_observation(self) -> bool:
return self.resolution in {'default_header_only', 'annotation_only', 'invalid_line_reference'}
class ReservationRelationProjection:
"""
把 captured_relation(规则层事实) + profile relation_policy(解释层策略)
投影为最终绑定结果。
【AI 触发时机】:三来源合并前,为每个 Vendor Comments / Header Reservation 候选
决定「写行 Observation 还是写头 Observation 还是 invalid_line_reference」时调用。
核心路径:
[STEP 1] 若 relation_policy=annotation_only → 直接走 annotation_only 分支(审计记录原因)。
[STEP 2] 若缺失 captured_relation → 走 missing_relation_policy 分支
(default_all_lines / default_header_only / fallback_single_line_when_no_reference)。
[STEP 3] 若有 captured_relation.line_no,按 line_reference_basis 三层校验:
① explicit_line_column:对比 Schema Line 字段值(显式 Line 列),失败→invalid
② profile_business_line_no:对比 Profile 业务行号(默认客户 PO 行号)
③ classified_logical_line_no:逻辑行号(行序分类后的结果)
三层任何一层命中即返回 bound_to_line;全部失败输出 invalid_line_reference 独立原因码。
"""
def __init__(
self,
*,
relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'],
line_reference_basis: Literal[
'explicit_line_column',
'profile_business_line_no',
'classified_logical_line_no',
] = 'profile_business_line_no',
missing_relation_policy: Literal[
'default_all_lines',
'default_header_only',
'fallback_single_line_when_no_reference',
] = 'default_header_only',
):
self.relation_policy = relation_policy
self.line_reference_basis = line_reference_basis
self.missing_relation_policy = missing_relation_policy
# ------------------------------------------------------------------
# 对外入口
# ------------------------------------------------------------------
def project(
self,
*,
captured_relation: CoreCapturedRelation | None,
# 下面四个映射是 Line Reference Basis 的判定表(caller 注入,避免本类查 Schema)
explicit_line_column_values: dict[int, str] | None = None,
profile_business_line_numbers: dict[int, Any] | None = None,
classified_logical_line_numbers: dict[int, int] | None = None,
# 审计备注(annotation_only 时必须填写原因字符串,例如 'customer_commentary_only')
annotation_reason_override: str | None = None,
) -> ReservationRelationProjectionResult:
"""
执行关系投影。
【禁止 caller 自行推导】:不要在外部用 if captured_relation.line_no in ... 判断,
必须走 project() 返回的稳定 resolution 分支。
"""
audit: list[dict[str, Any]] = [
{'step': 'policy_in', 'relation_policy': self.relation_policy,
'line_reference_basis': self.line_reference_basis,
'missing_relation_policy': self.missing_relation_policy},
]
# [STEP 1] annotation_only 直接返回(本期用于 Customer 备注说明、不参与建单)
if self.relation_policy == 'annotation_only':
audit.append({'step': 'annotation_only',
'reason': annotation_reason_override or 'profile_relation_policy_annotation_only'})
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='annotation_only',
annotation_reason=annotation_reason_override or 'profile_relation_policy_annotation_only',
audit_chain=audit,
)
# [STEP 2] 缺失 captured_relation → 走 missing_relation_policy
if captured_relation is None or captured_relation.line_no is None:
audit.append({'step': 'missing_relation',
'raw_text': captured_relation.raw_text if captured_relation else None})
return self._resolve_missing_policy(audit)
# [STEP 3] 三层 line_reference_basis 判定(显式 Line 列值 → Profile 业务行号 → 逻辑行号)
rel_line_no = int(captured_relation.line_no)
audit.append({'step': 'relation_line_no_in', 'line_no': rel_line_no,
'raw_text': captured_relation.raw_text})
basis_order = self._basis_order()
for basis_name in basis_order:
resolved = self._try_basis(basis_name, rel_line_no, explicit_line_column_values or {},
profile_business_line_numbers or {},
classified_logical_line_numbers or {})
if resolved is not None:
audit.append({'step': 'basis_hit', 'basis': basis_name,
'logical_line_no': resolved})
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='bound_to_line',
resolved_logical_line_no=resolved,
audit_chain=audit,
)
# 三层全不命中 → invalid_line_reference(Q12 独立原因码 + 独立审计链)
audit.append({'step': 'invalid_line_reference', 'tried_bases': basis_order})
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='invalid_line_reference',
invalid_reference_raw_value=captured_relation.raw_text,
invalid_reference_line_no=rel_line_no,
audit_chain=audit,
)
# ------------------------------------------------------------------
# 内部步骤
# ------------------------------------------------------------------
def _basis_order(self) -> list[str]:
"""按 Profile.line_reference_basis 输出优先级顺序。"""
if self.line_reference_basis == 'explicit_line_column':
return ['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no']
if self.line_reference_basis == 'profile_business_line_no':
return ['profile_business_line_no', 'classified_logical_line_no', 'explicit_line_column']
return ['classified_logical_line_no', 'profile_business_line_no', 'explicit_line_column']
def _try_basis(
self,
basis: str,
rel_line_no: int,
explicit: dict[int, str],
profile_biz: dict[int, Any],
logical: dict[int, int],
) -> int | None:
"""尝试一层判定;命中则返回逻辑行号(1-based),否则返回 None。"""
if basis == 'explicit_line_column':
for logical_idx, raw in explicit.items():
if str(raw).strip() == str(rel_line_no):
return int(logical_idx)
return None
if basis == 'profile_business_line_no':
for logical_idx, raw in profile_biz.items():
if str(raw).strip() == str(rel_line_no):
return int(logical_idx)
return None
if basis == 'classified_logical_line_no':
for logical_idx, mapped in logical.items():
if int(mapped) == rel_line_no:
return int(logical_idx)
return None
return None
def _resolve_missing_policy(self, audit: list[dict[str, Any]]) -> ReservationRelationProjectionResult:
"""缺失关系时按 missing_relation_policy 落分支。"""
policy = self.missing_relation_policy
audit.append({'step': 'missing_policy', 'policy': policy})
if policy == 'default_all_lines':
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='default_all_lines',
audit_chain=audit,
)
if policy == 'fallback_single_line_when_no_reference':
# Q7 开关:默认 OFF;当前 Profile 显式开启时才使用——第一期所有客户 OFF
# 若未来启用,应当返回 bound_to_line → 1;本期保持 default_header_only 语义
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='default_header_only',
audit_chain=audit + [{'step': 'fallback_disabled_by_q7_default'}],
)
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='default_header_only',
audit_chain=audit,
)
@@ -0,0 +1,244 @@
"""
services/shipping_notice/document_layout/runtime_parse_strategy.py
用途:为已唯一命中的 Coordinate/OCR 订单模板按当前文档证据选择页范围与明细行重建方式。
依赖:仅标准库;由正式抽取与模板质量验证共同调用。
逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用,冲突统一转 Review。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Literal
RowMode = Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns']
StrategyStatus = Literal['selected', 'needs_review']
@dataclass(frozen=True)
class RuntimeParseStrategy:
"""当前文档的临时解析计划,不写回 Profile 或改变后续 Candidate Gate。"""
status: StrategyStatus
page_nos: tuple[int, ...]
row_mode: RowMode | None
reason_codes: tuple[str, ...]
def resolve_runtime_parse_strategy(
*, page_glyphs: dict[str, Any], fixed_rows: list[dict[str, Any]], adaptive_rows: list[dict[str, Any]],
dynamic_rows: list[dict[str, Any]] | None = None,
) -> RuntimeParseStrategy:
"""按页级证据与三种重建结果选择唯一安全策略。
Args:
page_glyphs: 当前 Layout 的页级坐标事实;空页不进入续页候选。
fixed_rows: 固定子行重建结果。
adaptive_rows: 自适应列重建结果。
dynamic_rows: 不受静态表头排除区影响的动态 X 列重建结果。
Returns:
``selected`` 时调用方只消费 ``row_mode`` 对应结果;关键行不同或均不可用时返回
``needs_review``,由既有 Route/Candidate Gate 阻断自动建单。
"""
page_nos = tuple(sorted(
int(page_no) for page_no, glyphs in page_glyphs.items()
if str(page_no).isdigit() and int(page_no) > 0 and isinstance(glyphs, list) and glyphs
))
fixed_valid = _valid_rows(fixed_rows)
adaptive_valid = _valid_rows(adaptive_rows)
dynamic_valid = _valid_rows(dynamic_rows or [])
baseline_rows: list[dict[str, Any]] = []
baseline = None
if fixed_valid and not adaptive_valid:
baseline_rows = fixed_valid
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
elif adaptive_valid and not fixed_valid:
baseline_rows = adaptive_valid
baseline = RuntimeParseStrategy(
'selected', page_nos, 'adaptive_record_columns',
('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',),
)
elif fixed_valid and adaptive_valid:
relation = _compare_row_field_completeness(fixed_valid, adaptive_valid)
if relation == 'fixed_preferred':
baseline_rows = fixed_valid
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
elif relation == 'adaptive_preferred':
baseline_rows = adaptive_valid
baseline = RuntimeParseStrategy(
'selected', page_nos, 'adaptive_record_columns',
('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',),
)
elif relation == 'same':
baseline_rows = fixed_valid
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
else:
return RuntimeParseStrategy(
'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',),
)
if baseline is None and dynamic_valid:
return RuntimeParseStrategy(
'selected', page_nos, 'dynamic_x_columns',
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
)
if baseline is not None and dynamic_valid:
relation = _compare_dynamic_row_coverage(
baseline_rows=baseline_rows, dynamic_rows=dynamic_valid,
)
if relation == 'dynamic_preferred':
return RuntimeParseStrategy(
'selected', page_nos, 'dynamic_x_columns',
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
)
if relation == 'ambiguous':
return RuntimeParseStrategy(
'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',),
)
if baseline is not None:
return baseline
return RuntimeParseStrategy(
'needs_review', page_nos, None, ('PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION',),
)
def select_runtime_region_ids(*, table_regions: list[dict[str, Any]], page_no: int) -> tuple[str, ...]:
"""为当前页选择候选表区,专属页优先,续页才回退到稳定基础表区。
历史 ``page_scope`` 仅描述样本标注页,不能要求管理员预判每份文件的续页。
当前页已有专属表区时只使用它;没有时复用首页/通用表区,后续仍由行重建结果
决定是否确实存在明细,避免把页面范围配置变成自动建单依据。
"""
if page_no < 1:
return ()
valid_regions = [
region for region in table_regions
if isinstance(region, dict) and str(region.get('region_id') or '')
]
exact = tuple(
str(region['region_id']) for region in valid_regions
if region.get('page_scope') == 'exact_page' and region.get('page_no') == page_no
)
if exact:
return exact
first_page = tuple(
str(region['region_id']) for region in valid_regions
if region.get('page_scope') == 'first_page'
)
if page_no == 1 and first_page:
return first_page
continuation = tuple(
str(region['region_id']) for region in valid_regions
if page_no > 1 and region.get('page_scope') == 'continuation_pages'
)
if continuation:
return continuation
all_pages = tuple(
str(region['region_id']) for region in valid_regions
if region.get('page_scope') == 'all_pages'
)
if all_pages:
return all_pages
if first_page:
return first_page
return tuple(
str(region['region_id']) for region in valid_regions
if region.get('page_scope') == 'exact_page' and region.get('page_no') == 1
)
def _valid_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""只接受无 issue 的已解析行;不将预览或待复核候选当作可自动建单事实。"""
return [
row for row in rows
if isinstance(row, dict) and row.get('status') == 'parsed' and not row.get('issues')
]
def _business_row_identity(rows: list[dict[str, Any]]) -> tuple[tuple[tuple[str, str], ...], ...]:
"""比较两种重建的完整业务字段,缺值也保留以避免静默视作相同。"""
result: list[tuple[tuple[str, str], ...]] = []
for row in rows:
values = [
(str(field.get('field_code') or ''), str(field.get('value') or ''))
for field in row.get('fields') or [] if isinstance(field, dict)
]
result.append(tuple(sorted(values)))
return tuple(result)
def _compare_row_field_completeness(
fixed_rows: list[dict[str, Any]], adaptive_rows: list[dict[str, Any]],
) -> Literal['fixed_preferred', 'adaptive_preferred', 'same', 'ambiguous']:
"""比较两种重建的字段集合,允许一方仅缺失字段而不丢弃整条明细。
只有对应行数量相同、重叠字段值一致,且所有行都呈现同一方向的字段超集关系时,
才自动选择更完整的结果;任一字段值冲突或方向不一致都继续进入 Review。
"""
if len(fixed_rows) != len(adaptive_rows):
return 'ambiguous'
directions: set[str] = set()
for fixed, adaptive in zip(fixed_rows, adaptive_rows):
fixed_fields = _row_fields(fixed)
adaptive_fields = _row_fields(adaptive)
shared = fixed_fields.keys() & adaptive_fields.keys()
conflicts = [code for code in shared if fixed_fields[code] != adaptive_fields[code]]
if conflicts:
# 坐标字段框是模板的权威边界。若 adaptive 只读到 fixed 值的
# 前缀(典型的跨视觉行料号),完整的 fixed 值应胜出;真正的
# 不同业务值仍保持 Review,避免把冲突静默吞掉。
if all(
fixed_fields[code].startswith(adaptive_fields[code])
and len(fixed_fields[code]) > len(adaptive_fields[code])
for code in conflicts
):
directions.add('fixed')
else:
return 'ambiguous'
if fixed_fields.keys() > adaptive_fields.keys():
directions.add('fixed')
elif adaptive_fields.keys() > fixed_fields.keys():
directions.add('adaptive')
if not directions:
return 'same'
if len(directions) == 1:
return 'fixed_preferred' if 'fixed' in directions else 'adaptive_preferred'
return 'ambiguous'
def _compare_dynamic_row_coverage(
*, baseline_rows: list[dict[str, Any]], dynamic_rows: list[dict[str, Any]],
) -> Literal['baseline_preferred', 'dynamic_preferred', 'ambiguous']:
"""仅当动态结果无冲突地覆盖基线每条记录并额外恢复记录时才切换策略。"""
if len(dynamic_rows) < len(baseline_rows):
return 'baseline_preferred'
remaining = [_row_fields(row) for row in dynamic_rows]
for baseline in baseline_rows:
baseline_fields = _row_fields(baseline)
matches = []
for index, dynamic_fields in enumerate(remaining):
if not baseline_fields.keys() <= dynamic_fields.keys():
continue
if all(
dynamic_fields[code] == value
or (
dynamic_fields[code].startswith(value)
and len(dynamic_fields[code]) > len(value)
)
for code, value in baseline_fields.items()
):
matches.append(index)
if len(matches) != 1:
return 'ambiguous' if len(dynamic_rows) >= len(baseline_rows) else 'baseline_preferred'
remaining.pop(matches[0])
return 'dynamic_preferred' if remaining else 'baseline_preferred'
def _row_fields(row: dict[str, Any]) -> dict[str, str]:
"""将策略行字段规整为可比较映射;不引入业务字段白名单。"""
return {
str(field.get('field_code') or ''): str(field.get('value') or '')
for field in row.get('fields') or []
if isinstance(field, dict) and str(field.get('field_code') or '')
}
@@ -1,342 +0,0 @@
"""
services/shipping_notice/document_layout/source_merge_service.py
用途:Q18 抽取层裁决——同一 conflict_group_key(scope/field_code/line_no)下的三来源候选
合并为最多一条「有效业务 Observation」,禁止同一 scope+line 下多个并列有效
Observation(防止 compute_effective_reservation_id / 库存匹配 / 履约门禁
/ Excel/RPA 误取其中一个,或冲突被后续静默覆盖)。
依赖:profile_field_source_mapping_service.FieldSourceCandidate。
逻辑:严格三步骤(同值合并 → 空值互补 → 值冲突),满足:
① merge 后只出一个有效 accepted(或 needs_review=无 accepted);
② 始终保留 source_observations[] 事实快照放入 metadata;
③ annotation_only / invalid_line_reference 的候选永不成为 accepted,
只保留在 conflict_payload 里作为 Review 证据。
输出:MergedObservationCandidate(直接落库前的 Observation 形状封装),
由 runtime 层实际 SQLAlchemy insert。
"""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any, Literal
from app.services.shipping_notice.document_layout.profile_field_source_mapping_service import (
FieldSourceCandidate,
)
SourceResolution = Literal[
'same_value_merged', # 多个来源值一致
'fill_missing', # 一个来源有值,另一来源为空 → 自动填补
'needs_review', # 同 scope+line 多来源值不一致
'no_value', # 所有来源均为空 → 本冲突组不生成有效 Observation
'single_source_direct', # 只有一个来源有值,直接落 Observation
'annotation_only_dropped', # 候选全是 annotation_only / invalid_line_reference
]
@dataclass
class SourceObservationSnapshot:
"""source_observations[] 事实快照——Observation.metadata 直接序列化。"""
source: Literal['header_region', 'table_column', 'vendor_comments']
value: str
normalized_value: str
evidence_ref: str | None
evidence_quote: str | None
line_no_in_source: int | None
format_valid: bool | None
format_reason_code: str | None
extra: dict[str, Any] = field(default_factory=dict)
@dataclass
class MergedObservationCandidate:
"""
合并后候选——最多一份(per conflict_group_key),由 runtime 层写数据库。
【后端决定 UI】:accepted_value 为 None 时,说明该字段+行=必须 Review;
frontend 不能以『第一个 source value』为事实,必须展示 source_observations[]。
"""
target_scope: Literal['header', 'line']
target_field_code: str
target_field_id: str
effective_line_no: int | None
accepted_value: str | None # needs_review/no_value 时为 None
decision_status: Literal['accepted', 'needs_review', 'blocked', 'missing']
resolution: SourceResolution
source_observations: list[SourceObservationSnapshot] = field(default_factory=list)
conflicts: list[dict[str, Any]] = field(default_factory=list)
# 用于直接映射到 Observation 数据库表列
evidence_quote: str | None = None
evidence_ref: str | None = None
evidence_metadata: dict[str, Any] = field(default_factory=dict)
# 用于 Observation.source_type / extractor(统一三来源来源标记)
source_type: str = 'profile_field_source_mapping'
extractor: str = 'merged_source_service.v1'
@property
def should_persist_observation(self) -> bool:
"""
有效 Observation 生成门禁:
必须有 accepted_value;annotation_only/invalid 全 drop 时也不输出。
"""
return self.accepted_value is not None and self.accepted_value != ''
class SourceMergeService:
"""
Q18 抽取层裁决服务(先对账再重试——三来源先对账)。
【AI 触发时机】:ProfileFieldSourceMappingService.collect_candidates() 返回候选后,
下一个函数调用必须是 merge_and_decide()。禁止上游在合并前直接挑一个 source 作为 Observation。
执行顺序(同 conflict_group_key 内):
[STEP 1] 过滤 annotation_only / invalid_line_reference 候选(永不 accepted)。
[STEP 2] 归一化所有来源 value(去空格、大小写、格式化残差)。
[STEP 3] 同值合并 same_value_merged → accepted
[STEP 4] 空值互补 fill_missing(需 mapping.fill_missing_from_other_sources=True)
[STEP 5] 以上都不通过 → conflict_needs_review,accepted_value=None
"""
def __init__(self, candidates: list[FieldSourceCandidate]):
self.candidates = list(candidates)
# 分组:(scope, field_code, line_no) → list[candidates]
self._groups: dict[tuple[Any, ...], list[FieldSourceCandidate]] = defaultdict(list)
for cand in self.candidates:
self._groups[cand.conflict_group_key].append(cand)
# ------------------------------------------------------------------
# 对外主入口
# ------------------------------------------------------------------
def merge_and_decide(self) -> list[MergedObservationCandidate]:
"""为每个 conflict_group_key 输出 0 或 1 个 MergedObservationCandidate。"""
merged: list[MergedObservationCandidate] = []
for _key, group in self._groups.items():
merged.append(self._merge_one_group(group))
return merged
# ------------------------------------------------------------------
# 单组合并核心
# ------------------------------------------------------------------
def _merge_one_group(self, group: list[FieldSourceCandidate]) -> MergedObservationCandidate:
first = group[0]
result = MergedObservationCandidate(
target_scope=first.target_scope,
target_field_code=first.target_field_code,
target_field_id=first.target_field_id,
effective_line_no=first.effective_line_no,
accepted_value=None,
decision_status='missing',
resolution='no_value',
)
# [STEP 1] 分离有效候选(排除 annotation_only / invalid)
qualified: list[FieldSourceCandidate] = []
for cand in group:
snap = self._to_snapshot(cand)
result.source_observations.append(snap)
if cand.resolution_hint == 'provisional':
qualified.append(cand)
else:
# annotation_only / invalid_line_reference 作为 review 证据保留
result.conflicts.append({
'resolution_hint': cand.resolution_hint,
'source': cand.source,
'value': cand.normalized_value or cand.value,
'reason': (
cand.format_reason_code
or cand.relation_projection.resolution
if cand.relation_projection else 'annotation_only'
),
})
# 无 qualified → 直接 annotation_only_dropped / no_value
if not qualified:
if group:
result.resolution = 'annotation_only_dropped'
result.decision_status = 'blocked'
else:
result.resolution = 'no_value'
result.decision_status = 'missing'
result.evidence_metadata = self._finalize_metadata(result, resolution_meta={})
return result
# 只有一个 qualified 且非空 → single_source_direct
non_empty = [c for c in qualified if (c.normalized_value or c.value) != '']
if len(qualified) == 1 and non_empty:
return self._finalize_single(result, qualified[0])
if not non_empty:
result.resolution = 'no_value'
result.decision_status = 'missing'
result.evidence_metadata = self._finalize_metadata(result, {})
return result
if len(non_empty) == 1:
return self._finalize_fill_missing(result, group, non_empty[0], qualified)
# [STEP 3] 同值合并 same_value_merged
values = {(c.normalized_value or c.value) for c in non_empty}
if len(values) == 1:
return self._finalize_same_value(result, group, next(iter(values)))
# [STEP 5] 冲突 → needs_review(多来源值不一致)
result.resolution = 'needs_review'
result.decision_status = 'needs_review'
result.accepted_value = None
for c in non_empty:
result.conflicts.append({
'source': c.source,
'value': (c.normalized_value or c.value),
'evidence_ref': c.evidence_ref,
'format_valid': c.format_valid,
})
result.evidence_metadata = self._finalize_metadata(result, {})
return result
# ------------------------------------------------------------------
# 结局封装(保证 evidence_metadata 统一包含 source_observations / resolution)
# ------------------------------------------------------------------
def _finalize_single(
self, result: MergedObservationCandidate, cand: FieldSourceCandidate,
) -> MergedObservationCandidate:
result.accepted_value = cand.normalized_value or cand.value
result.resolution = 'single_source_direct'
result.decision_status = 'accepted'
result.evidence_quote = cand.evidence_quote
result.evidence_ref = cand.evidence_ref
result.evidence_metadata = self._finalize_metadata(
result,
resolution_meta={
'accepted_source': cand.source,
'format_valid': cand.format_valid,
'format_reason_code': cand.format_reason_code,
},
primary_candidate=cand,
)
return result
def _finalize_fill_missing(
self, result: MergedObservationCandidate,
group: list[FieldSourceCandidate],
winner: FieldSourceCandidate,
all_qualified: list[FieldSourceCandidate],
) -> MergedObservationCandidate:
result.accepted_value = winner.normalized_value or winner.value
result.resolution = 'fill_missing'
result.decision_status = 'accepted'
result.evidence_quote = winner.evidence_quote
result.evidence_ref = winner.evidence_ref
missing = [
{'source': c.source, 'reason': 'empty_source'}
for c in all_qualified
if (c.normalized_value or c.value) == ''
]
result.evidence_metadata = self._finalize_metadata(
result,
resolution_meta={
'accepted_source': winner.source,
'missing_sources': missing,
'format_valid': winner.format_valid,
'format_reason_code': winner.format_reason_code,
},
primary_candidate=winner,
)
return result
def _finalize_same_value(
self, result: MergedObservationCandidate,
group: list[FieldSourceCandidate], shared_value: str,
) -> MergedObservationCandidate:
# 多来源同值:evidence 选 format_valid=True 中来源排序靠前的
# (vendor_comments 优先,因为有人工圈选证据点位更清晰)
source_priority = ['vendor_comments', 'table_column', 'header_region']
ordered = sorted(
group,
key=lambda c: (
0 if (c.format_valid is not False and (c.normalized_value or c.value) == shared_value) else 1,
source_priority.index(c.source) if c.source in source_priority else 99,
),
)
primary = ordered[0]
result.accepted_value = shared_value
result.resolution = 'same_value_merged'
result.decision_status = 'accepted'
result.evidence_quote = primary.evidence_quote
result.evidence_ref = primary.evidence_ref
merged_sources = sorted({c.source for c in ordered if (c.normalized_value or c.value) == shared_value})
result.evidence_metadata = self._finalize_metadata(
result,
resolution_meta={
'merged_from_sources': list(merged_sources),
'format_valid': primary.format_valid,
'format_reason_code': primary.format_reason_code,
},
primary_candidate=primary,
)
return result
# ------------------------------------------------------------------
# 帮助函数
# ------------------------------------------------------------------
@staticmethod
def _to_snapshot(cand: FieldSourceCandidate) -> SourceObservationSnapshot:
return SourceObservationSnapshot(
source=cand.source,
value=cand.value,
normalized_value=cand.normalized_value,
evidence_ref=cand.evidence_ref,
evidence_quote=cand.evidence_quote,
line_no_in_source=cand.effective_line_no,
format_valid=cand.format_valid,
format_reason_code=cand.format_reason_code,
extra=dict(cand.evidence_metadata or {}),
)
@staticmethod
def _finalize_metadata(
result: MergedObservationCandidate,
resolution_meta: dict[str, Any],
primary_candidate: FieldSourceCandidate | None = None,
) -> dict[str, Any]:
"""
组装 Observation.evidence_metadata_json 最终结构(Q18 冻结形状):
{
"source_observations": [...], // 事实快照(永不丢)
"resolution": "same_value_merged",
"accepted_value": "...",
"conflicts": [ ... ], // 冲突或 annotation_only 项
"resolution_meta": { ... }, // 来源细节
"primary": { // 选主证据说明
"source": "vendor_comments", "evidence_ref": "...", "line_no": 2
}
}
"""
payload: dict[str, Any] = {
'source_observations': [
{
'source': s.source, 'value': s.value,
'normalized_value': s.normalized_value,
'evidence_ref': s.evidence_ref, 'evidence_quote': s.evidence_quote,
'line_no_in_source': s.line_no_in_source,
'format_valid': s.format_valid, 'format_reason_code': s.format_reason_code,
'extra': s.extra or {},
} for s in result.source_observations
],
'resolution': result.resolution,
'accepted_value': result.accepted_value,
'conflicts': list(result.conflicts or []),
'resolution_meta': resolution_meta or {},
}
if primary_candidate is not None:
payload['primary'] = {
'source': primary_candidate.source,
'evidence_ref': primary_candidate.evidence_ref,
'line_no': primary_candidate.effective_line_no,
}
return payload
@@ -1,195 +0,0 @@
"""
services/shipping_notice/document_layout/vc_source_candidate_conflicts.py
用途:从 ProfileFieldSourceMappingService + SourceMergeService 的运行结果
产出 Candidate 级冲突项,接入 candidate.conflicts_json。
依赖:
- vc_source_gate_contract(冲突原因码、冲突项构造器)。
- profile_field_source_mapping_service(三来源候选收集)。
- source_merge_service(合并裁决 + needs_review 标记)。
- candidate_service / ShippingOrderCandidate.structured_result_json(落库载体)。
逻辑:
[STEP 1] 从 Candidate.structured_result_json 读三来源收集的原始快照;
缺失(旧数据或未启用 VC Profile)时安全返回空列表,不阻断。
[STEP 2] 扫描 merged_candidates,needs_review 且 conflict_group_key 未人工裁决 →
构造 make_vc_candidate_conflict_item(severity=review_required)。
[STEP 3] 扫描 format_valid=False 且 format_policy.inherit_global=False 的项 →
独立原因码 vc_source_format_invalid,severity=blocking。
[STEP 4] named_region_id 指向不存在区域 → vc_source_region_unbound。
幂等:同一 conflict_group_key 仅保留一项,合并 detail 不重复追加。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.document_layout.vc_source_gate_contract import (
CQ_REASON_VC_FORMAT_INVALID,
CQ_REASON_VC_REGION_UNBOUND,
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
CQ_VC_BLOCKING_REASONS,
CQ_VC_REVIEW_REASONS,
VC_SOURCE_KIND_LABELS,
make_vc_candidate_conflict_item,
)
# CQ_VC_BLOCKING_REASONS / CQ_VC_REVIEW_REASONS 定义在 vc_source_gate_contract.py(契约层),
# 这里保留薄 re-export,供 candidate_qualification_service 等调用方按旧路径 import,
# 避免修改大量调用点时引入遗漏。
_VC_CANDIDATE_KEY = 'vendor_comments_merged'
_VC_DETAIL_MAX = 8 # 单项 detail 保留最多 8 条来源快照,防止 JSON 膨胀。
def _vc_merged_payload(candidate: Any) -> dict[str, Any] | None:
"""
从 Candidate 提取 Vendor Comments merged payload。
支持三条路径,按顺序:
1) structured_result_json.extraction.vendor_comments_merged(新抽取路径)
2) result_json.extraction.vendor_comments_merged(兼容 Worker 旧写入点)
3) candidate_json.extraction.vendor_comments_merged(影子评估的替身 dict)
任一合法 dict 即返回,否则 None(缺路径视为未启用,安全放行)。
"""
for attr in ('structured_result_json', 'result_json', 'candidate_json'):
try:
raw = getattr(candidate, attr, None)
except Exception:
raw = None
if isinstance(raw, dict):
ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None
if ext and isinstance(ext.get(_VC_CANDIDATE_KEY), dict):
return ext[_VC_CANDIDATE_KEY]
return None
def _conflict_group_key(scope: str, field_code: str, line_no: str | None) -> str:
"""稳定冲突键:与 source_merge_service 的 (scope, field_code, line_no) 一致。"""
safe_scope = 'header' if scope == 'header' else 'line'
safe_line = str(line_no or '').strip() or '_'
return f'{safe_scope}:{str(field_code or "").strip()}:{safe_line}'
def _summarize_source_observations(cand: dict[str, Any]) -> list[dict[str, Any]]:
"""
脱敏压缩 source_observations:仅保留 source / value 摘要 / evidence_ref,禁止存完整正文。
"""
obs = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else []
summary: list[dict[str, Any]] = []
for raw in obs[:_VC_DETAIL_MAX]:
if not isinstance(raw, dict):
continue
summary.append({
'source': raw.get('source'),
'source_label': VC_SOURCE_KIND_LABELS.get(str(raw.get('source') or ''), str(raw.get('source') or '')),
'value_preview': (str(raw.get('value') or '')[:64] + ('…' if len(str(raw.get('value') or '')) > 64 else '')) if raw.get('value') is not None else None,
'evidence_ref': raw.get('evidence_ref'),
})
return summary
def collect_vc_candidate_conflicts(candidate: Any) -> list[dict[str, Any]]:
"""
扫描 Vendor Comments 三来源合并结果,生成 Candidate 冲突项。
【AI 触发时机】:当 Candidate Qualification 评估、STP 自动建单前
或复核工作台加载冲突列表时,追加本函数返回值到 Candidate.conflicts_json。
Args:
candidate: ShippingOrderCandidate ORM 对象或兼容 dict(替身)。
Returns:
符合 vc_source_gate_contract.make_vc_candidate_conflict_item 契约的列表;
无冲突或未启用 VC 时返回空列表(永不返回 None)。
"""
payload = _vc_merged_payload(candidate)
if payload is None:
return []
merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else []
named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {}
enabled = payload.get('field_source_mappings') if isinstance(payload.get('field_source_mappings'), dict) else {}
# [STEP 0] 先校验 named_region 绑定:所有启用 vendor_comments 的 mapping 其 region_id 必须存在。
seen_region_errors: set[str] = set()
items: list[dict[str, Any]] = []
for field_code, mapping in enabled.items():
if not isinstance(mapping, dict):
continue
if not bool(mapping.get('vendor_comments_enabled')):
continue
rid = str(mapping.get('vendor_comments_named_region_id') or '').strip()
if rid and rid not in named_regions:
key = f'region_missing:{rid}:{field_code}'
if key in seen_region_errors:
continue
seen_region_errors.add(key)
scope_val = str(mapping.get('vendor_comments_target_scope') or mapping.get('target_scope') or 'line').strip()
scope = 'header' if scope_val == 'header' else 'line'
ckey = _conflict_group_key(scope, field_code, None)
items.append(make_vc_candidate_conflict_item(
reason=CQ_REASON_VC_REGION_UNBOUND,
scope=scope, # type: ignore[arg-type]
field_code=field_code,
conflict_group_key=ckey,
detail={'missing_region_id': rid},
))
# [STEP 1] 扫描 merged_candidates:needs_review / format_invalid。
seen_groups: set[str] = set()
for cand in merged:
if not isinstance(cand, dict):
continue
field_code = str(cand.get('target_field_code') or cand.get('field_code') or '').strip()
if not field_code:
continue
scope = str(cand.get('target_scope') or cand.get('scope') or 'line').strip()
scope_ok = 'header' if scope == 'header' else 'line'
line_no_raw = cand.get('effective_line_no') or cand.get('line_no')
line_no_safe = None if line_no_raw is None else str(line_no_raw)
ckey = _conflict_group_key(scope_ok, field_code, line_no_safe)
resolution = str(cand.get('resolution') or '').strip()
decision = str(cand.get('decision_status') or '').strip()
format_valid = cand.get('format_valid')
# 显式 False 视为非法(None 表示未启用格式策略,安全放行)。
format_invalid = (format_valid is False)
conflict_pending = resolution == 'needs_review' and decision != 'dropped'
if ckey in seen_groups:
continue
detail = {
'resolution': resolution,
'decision_status': decision,
'format_valid': format_valid,
'sources': _summarize_source_observations(cand),
}
if conflict_pending:
seen_groups.add(ckey)
line_key = str(cand.get('line_key') or '').strip() or None
items.append(make_vc_candidate_conflict_item(
reason=CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
scope=scope_ok, # type: ignore[arg-type]
field_code=field_code,
line_key=line_key,
line_no=line_no_safe,
conflict_group_key=ckey,
detail=detail,
))
elif format_invalid:
seen_groups.add(ckey)
line_key = str(cand.get('line_key') or '').strip() or None
items.append(make_vc_candidate_conflict_item(
reason=CQ_REASON_VC_FORMAT_INVALID,
scope=scope_ok, # type: ignore[arg-type]
field_code=field_code,
line_key=line_key,
line_no=line_no_safe,
conflict_group_key=ckey,
detail=detail,
))
return items
@@ -1,230 +0,0 @@
"""
services/shipping_notice/document_layout/vc_source_evidence_integration.py
用途:将 Vendor Comments 三来源 source_observations 注入 ReviewEvidenceView,
供 Chatflow LLM Review(Phase 4)与复核工作台(Phase 5)共享同一事实源。
依赖:
- vc_source_gate_contract(VENDOR_COMMENTS_OBSERVATION_SOURCE、build_vc_evidence_ref、is_valid_vc_evidence_ref)。
- order_review_llm_contract ObservationSource 兼容扩展(新增 source 不在原 frozenset 时 fail-open,不抛错)。
- Candidate.structured_result_json.extraction.vendor_comments_merged(与 vc_source_candidate_conflicts.py 同一路径)。
逻辑:
[STEP 1] 提取 VC merged payload(与 Candidate Conflicts 共享 _vc_merged_payload 逻辑,不双份)。
[STEP 2] 对每个 merged_candidate,展开其 source_observations[]:
- 构造 evidence_ref(优先 vc: 区域引用,缺失时退化 build_evidence_ref layout:)。
- source 固定 VENDOR_COMMENTS_OBSERVATION_SOURCE;子 source_kind 写入 metadata.source_kind。
- 保留 quote(原文切片)、confidence、value_bbox。
[STEP 3] 仅追加,不覆盖/替换原有 Unit/Draft/Frozen 三源证据。
幂等:同一 (evidence_ref, source_kind, value) 仅插入一条,避免 LLM 重复上下文。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.document_layout.vc_source_gate_contract import (
VENDOR_COMMENTS_OBSERVATION_SOURCE,
build_vc_evidence_ref,
is_valid_vc_evidence_ref,
)
from app.services.shipping_notice.order_review_llm_contract import (
build_evidence_ref,
is_valid_evidence_ref,
)
def _vc_merged_payload(case_or_candidate: Any) -> dict[str, Any] | None:
"""
从 ReviewCase(通过 candidate.structured)或直接 Candidate 提取 VC 载荷。
与 vc_source_candidate_conflicts._vc_merged_payload 逻辑一致但独立实现,
避免引入相互 import(两模块均零 circular 原则)。
"""
# Case 路径:先取 candidate。
candidate = getattr(case_or_candidate, 'candidate', None)
attrs_chain: list[Any] = []
if candidate is not None:
attrs_chain.append(candidate)
attrs_chain.append(case_or_candidate)
for item in attrs_chain:
for attr in ('structured_result_json', 'result_json', 'candidate_json'):
try:
raw = getattr(item, attr, None)
except Exception:
raw = None
if isinstance(raw, dict):
ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None
if ext and isinstance(ext.get('vendor_comments_merged'), dict):
return ext['vendor_comments_merged']
return None
def _safe_str(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _normalize_source_obs(
raw: dict[str, Any],
*,
case_document_id: int,
field_code: str | None,
line_key: str | None,
named_regions: dict[str, Any],
) -> dict[str, Any] | None:
"""
将一条 source_observation 归一化为 ReviewEvidenceView.field_evidences 项形状。
核心:evidence_ref 优先取 vc:region;若 source_kind=vendor_comments 且命中命名区域
但缺 page_no,回退从 named_regions[region_id] 取代表页号。
"""
if not isinstance(raw, dict):
return None
source_kind = _safe_str(raw.get('source')) or 'header_region'
value = raw.get('value')
quote = _safe_str(raw.get('quote') or raw.get('raw_text'))
confidence_raw = raw.get('confidence')
try:
confidence = float(confidence_raw) if confidence_raw is not None else None
except (TypeError, ValueError):
confidence = None
doc_raw = raw.get('document_id') or case_document_id
try:
doc_id = int(doc_raw)
except (TypeError, ValueError):
doc_id = int(case_document_id or 0)
page_raw = raw.get('page_no')
try:
page_no = int(page_raw) if page_raw is not None else None
except (TypeError, ValueError):
page_no = None
# Vendor Comments:若缺 page_no,按 named_regions[region_id].page_scope 推导代表页。
rid = _safe_str(raw.get('region_id') or raw.get('named_region_id'))
if source_kind == 'vendor_comments' and page_no is None and rid and isinstance(named_regions.get(rid), dict):
region_def = named_regions[rid]
page_scope = _safe_str(region_def.get('page_scope')) or 'first_page'
exact = region_def.get('exact_page_no') or region_def.get('page_no')
if page_scope == 'last_page':
# last_page 未知实际页码时安全置 1,待后续有实际渲染页号再覆盖。
page_no = page_no or 1
elif page_scope == 'exact_page' and exact is not None:
try:
page_no = int(exact)
except (TypeError, ValueError):
page_no = page_no or 1
else:
page_no = page_no or 1
evidence_ref: str | None = None
pre_ref = raw.get('evidence_ref')
if isinstance(pre_ref, str) and (is_valid_vc_evidence_ref(pre_ref) or is_valid_evidence_ref(pre_ref)):
evidence_ref = pre_ref.strip()
if not evidence_ref and source_kind == 'vendor_comments' and doc_id > 0 and page_no and rid:
evidence_ref = build_vc_evidence_ref(document_id=doc_id, page_no=page_no, region_id=rid)
if not evidence_ref and doc_id > 0 and page_no:
table_id = raw.get('table_id') if isinstance(raw.get('table_id'), str) else None
row_index = None
try:
ri = raw.get('row_index')
row_index = int(ri) if ri is not None else None
except (TypeError, ValueError):
row_index = None
evidence_ref = build_evidence_ref(
document_id=doc_id,
page_no=page_no,
table_id=table_id,
row_index=row_index,
field_code=field_code,
)
bbox = raw.get('value_bbox') if isinstance(raw.get('value_bbox'), dict) else None
bbox_valid = (
isinstance(bbox, dict)
and all(k in bbox for k in ('x0', 'y0', 'x1', 'y1'))
and 0.0 <= float(bbox['x0']) < float(bbox['x1']) <= 1.01
and 0.0 <= float(bbox['y0']) < float(bbox['y1']) <= 1.01
) if bbox else False
doc_match = bool(doc_id) and int(case_document_id or 0) > 0 and int(doc_id) == int(case_document_id)
value_bbox_dict = dict(bbox) if bbox_valid else None
return {
'value': value,
'quote': quote,
'source': VENDOR_COMMENTS_OBSERVATION_SOURCE,
'source_kind': source_kind,
'confidence': confidence,
'evidence_ref': evidence_ref,
'provenance_ref': None, # VC 来源直接走 evidence_ref,不伪装 draft provenance。
'document_id': doc_id,
'page_no': page_no,
'table_id': raw.get('table_id') if isinstance(raw.get('table_id'), str) else None,
'cell_id': raw.get('cell_id') if isinstance(raw.get('cell_id'), str) else None,
'row_index': None, # 行级由 line_key 外部关联,row_index 仅 layout table 使用。
'value_bbox': value_bbox_dict,
'value_bbox_valid': bbox_valid,
'document_matches_case': doc_match,
'field_code': field_code,
'line_key': line_key,
}
def collect_vc_field_evidences(
*,
case_or_candidate: Any,
case_document_id: int,
) -> list[dict[str, Any]]:
"""
展开 Vendor Comments 三来源 source_observations 为 ReviewEvidenceView.field_evidences 条目。
【AI 触发时机】:
- Phase 4:构建 LLM 最小证据上下文时,追加三来源引用与 quote;
- Phase 5:复核工作台加载 evidence 对照面板。
Args:
case_or_candidate: ShippingOrderReviewCase 或 ShippingOrderCandidate。
case_document_id: 当前 Case 的主文档 document_id,用于 document_matches_case。
Returns:
归一化 observation 列表;未启用 VC 或路径缺数据返回空列表。
"""
payload = _vc_merged_payload(case_or_candidate)
if payload is None:
return []
named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {}
merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else []
results: list[dict[str, Any]] = []
seen: set[tuple[str, str, str]] = set()
for cand in merged:
if not isinstance(cand, dict):
continue
field_code = _safe_str(cand.get('target_field_code') or cand.get('field_code'))
line_key = _safe_str(cand.get('line_key'))
source_list = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else []
for raw in source_list:
if not isinstance(raw, dict):
continue
norm = _normalize_source_obs(
raw,
case_document_id=int(case_document_id or 0),
field_code=field_code,
line_key=line_key,
named_regions=named_regions,
)
if norm is None:
continue
key = (
str(norm.get('evidence_ref') or ''),
str(norm.get('source_kind') or ''),
str(norm.get('value') or '')[:64],
)
if key in seen:
continue
seen.add(key)
results.append(norm)
return results
@@ -1,204 +0,0 @@
"""
services/shipping_notice/document_layout/vc_source_gate_contract.py
用途:冻结 Vendor Comments 三来源的门禁枚举、证据引用格式、冲突原因码。
依赖:零 I/O 纯契约模块,禁止 import 业务服务,避免 circular。
逻辑:
- ObservationSource 新增 vendor_comments_region(与 order_review_llm_contract.py 对齐)。
- evidence_ref 格式 vc:document_id:pN:region:<region_id> 独立校验,禁止混入 layout: 前缀。
- CQ 门禁新增 vc_source_merged_clean;原因码分「业务冲突」「格式不合法」「区域未绑定」三类。
- 所有常量写入 frozenset/tuple,供 gate/preview/audit 三处共享,禁止双份维护。
"""
from __future__ import annotations
import re
from typing import Any, Final, Literal
# ---------------------------------------------------------------------------
# 三来源字段来源种类(与前端 vc.types.ts Section E VCFieldSourceKind 一一对应)
# ---------------------------------------------------------------------------
VC_SOURCE_KINDS: Final[frozenset[str]] = frozenset({
'header_region',
'table_column',
'vendor_comments',
})
VC_SOURCE_KIND_LABELS: Final[dict[str, str]] = {
'header_region': 'Header 区域',
'table_column': '表身列',
'vendor_comments': 'Vendor Comments',
}
VC_SOURCE_EVIDENCE_PRIORITY: Final[dict[str, int]] = {
# 优先级越大越优先;与 source_merge_service.py 证据选择顺序对齐。
'vendor_comments': 3,
'table_column': 2,
'header_region': 1,
}
# ---------------------------------------------------------------------------
# 扩展 ObservationSource(与 order_review_llm_contract 原 4 类互不污染)
# ---------------------------------------------------------------------------
VENDOR_COMMENTS_OBSERVATION_SOURCE: Final[str] = 'vendor_comments_region'
ALL_OBSERVATION_SOURCES_WITH_VC: Final[frozenset[str]] = frozenset({
'unit_observation',
'draft_observation',
'frozen_layout',
'text_fallback',
VENDOR_COMMENTS_OBSERVATION_SOURCE,
})
# ---------------------------------------------------------------------------
# VC 专用 evidence_ref:vc:<document_id>:p<page_no>:region:<region_id>
# 缺任意段即视为无效,不伪造占位。
# ---------------------------------------------------------------------------
_VC_EVIDENCE_REF_RE = re.compile(
r'^vc:(?P<doc>\d+):p(?P<page>\d+):region:(?P<region>[A-Za-z0-9_\-]{1,128})$'
)
def is_valid_vc_evidence_ref(value: Any) -> bool:
"""
校验 Vendor Comments evidence_ref 是否满足三段式契约。
【AI 触发时机】:当需要将 VC 来源写入 Observation evidence_ref、
或 LLM 解析 quote 需要定位到命名区域时调用。
Args:
value: 待校验字符串。
Returns:
True 当且仅当正则命中且段值为正整数。
"""
if not isinstance(value, str) or not value:
return False
matched = _VC_EVIDENCE_REF_RE.match(value.strip())
if not matched:
return False
try:
doc = int(matched.group('doc'))
page = int(matched.group('page'))
except (TypeError, ValueError):
return False
return doc > 0 and page > 0 and bool(matched.group('region'))
def build_vc_evidence_ref(
*,
document_id: int | None,
page_no: int | None,
region_id: str | None,
) -> str | None:
"""
按契约生成 VC evidence_ref;缺任意必需段返回 None,绝不伪造。
Args:
document_id: PDF 主键,>0。
page_no: 代表页号,>0。
region_id: NamedRegion.region_id,非空。
Returns:
合法 vc: 引用或 None。
"""
if not document_id or not page_no or not region_id:
return None
try:
doc_i = int(document_id)
page_i = int(page_no)
rid = str(region_id).strip()
except (TypeError, ValueError):
return None
if doc_i <= 0 or page_i <= 0 or not rid:
return None
ref = f'vc:{doc_i}:p{page_i}:region:{rid}'
return ref if is_valid_vc_evidence_ref(ref) else None
# ---------------------------------------------------------------------------
# Candidate Qualification 门禁:vc_source_merged_clean
# ---------------------------------------------------------------------------
CQ_GATE_VC_SOURCE_MERGED_CLEAN: Final[str] = 'vc_source_merged_clean'
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED: Final[str] = 'vc_source_conflict_unresolved'
CQ_REASON_VC_FORMAT_INVALID: Final[str] = 'vc_source_format_invalid'
CQ_REASON_VC_REGION_UNBOUND: Final[str] = 'vc_source_region_unbound'
CQ_VC_BLOCKING_REASONS: Final[frozenset[str]] = frozenset({
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
CQ_REASON_VC_FORMAT_INVALID,
CQ_REASON_VC_REGION_UNBOUND,
})
# 归入 review_required(轻量人工确认)而非 hard-blocked 的原因。
CQ_VC_REVIEW_REASONS: Final[frozenset[str]] = frozenset({
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
})
# ---------------------------------------------------------------------------
# 合并决议(与 SourceMergeService.resolution 对齐,前端只读不改)
# ---------------------------------------------------------------------------
VC_MERGE_RESOLUTIONS: Final[frozenset[str]] = frozenset({
'single_source_direct',
'same_value_merged',
'fill_missing',
'needs_review',
'annotation_only_dropped',
'invalid_line_reference_dropped',
})
VC_DECISION_STATUSES: Final[frozenset[str]] = frozenset({
'accepted',
'pending',
'dropped',
})
# ---------------------------------------------------------------------------
# 证据元数据键(与 Q18 metadata.shape 严格一致)
# ---------------------------------------------------------------------------
VC_EVIDENCE_META_KEYS: Final[frozenset[str]] = frozenset({
'source_observations',
'resolution',
'accepted_value',
'conflicts',
'resolution_meta',
'primary',
})
# ---------------------------------------------------------------------------
# VC Candidate Qualification 冲突项 shape(用于 candidate.conflicts_json 列表项)
# ---------------------------------------------------------------------------
def make_vc_candidate_conflict_item(
*,
reason: str,
scope: Literal['header', 'line'],
field_code: str,
line_key: str | None = None,
line_no: str | None = None,
conflict_group_key: str,
detail: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
构造符合 CQ 契约的 Vendor Comments 冲突项。
核心逻辑:reason 必须来自 CQ_VC_BLOCKING_REASONS;
conflict_group_key 用于幂等去重(同组多次评估只记一条)。
Args:
reason: 原因码,限 CQ_VC_BLOCKING_REASONS。
scope: header / line。
field_code: 订单字段,如 reservation_id。
line_key: line scope 时的逻辑行键,header 为 None。
line_no: 原始明细号字符串,便于审计。
conflict_group_key: (scope, field_code, line_no) 稳定键。
detail: 三来源 values / source_observations 快照,不含正文大对象。
Returns:
candidate.conflicts_json 列表中的一项字典。
"""
safe_reason = reason if reason in CQ_VC_BLOCKING_REASONS else CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED
return {
'kind': 'vc_source',
'reason': safe_reason,
'severity': 'review_required' if safe_reason in CQ_VC_REVIEW_REASONS else 'blocking',
'scope': scope,
'field_code': field_code,
'line_key': line_key,
'line_no': line_no,
'conflict_group_key': conflict_group_key,
'detail': dict(detail or {}),
}
@@ -63,6 +63,7 @@ XFA_SPLIT_UNMATCHED_PRIORITY: Final[int] = 3
XfaSplitHandling = Literal['mapped', 'evidence_only']
XfaSplitMatcherType = Literal['position', 'prefix', 'regex']
XfaSplitPostProcessorType = Literal['prefix']
XfaSplitSourceScope = Literal['header', 'line']
XfaSplitUnmatchedPolicy = Literal['evidence_only', 'needs_review']
XfaSplitDuplicatePolicy = Literal['needs_review']
@@ -170,6 +171,28 @@ class XfaSplitSegment(BaseSplitSegment):
return self
class XfaSplitPostProcessor(XfaContractModel):
"""位置/正则命中后的受限二次取值器,当前仅支持从标签后提取值。"""
type: XfaSplitPostProcessorType
value: str = Field(min_length=1, max_length=XFA_SPLIT_MAX_PREFIX_LENGTH)
separators: list[str] = Field(default_factory=lambda: [':', ':'])
case_sensitive: bool = False
@model_validator(mode='after')
def validate_prefix_shape(self) -> 'XfaSplitPostProcessor':
"""标签和分隔符均为受限静态文本,避免引入脚本式 pipeline。"""
value = str(self.value or '').strip()
separators = [str(item) for item in (self.separators or []) if str(item)]
if not value:
raise ValueError('prefix post processor requires non-empty value')
if not separators:
raise ValueError('prefix post processor requires at least one separator')
object.__setattr__(self, 'value', value)
object.__setattr__(self, 'separators', separators)
return self
class XfaSplitMatcher(BaseSplitMatcher):
"""
单行匹配器:position / prefix / regex。
@@ -185,6 +208,7 @@ class XfaSplitMatcher(BaseSplitMatcher):
case_sensitive: bool = False
pattern: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH)
capture_group: int | None = Field(default=None, ge=0, le=XFA_SPLIT_MAX_REGEX_GROUPS)
post_processors: list[XfaSplitPostProcessor] = Field(default_factory=list, max_length=1)
@model_validator(mode='after')
def validate_matcher_shape(self) -> 'XfaSplitMatcher':
@@ -27,6 +27,7 @@ from app.services.shipping_notice.document_layout.field_split_core import (
)
from app.services.shipping_notice.document_layout.xfa_dataset import XfaLeafValue
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
XfaSplitPostProcessor,
XfaSplitRuleSet,
)
@@ -139,6 +140,56 @@ def _core_result_to_xfa(core: _CoreSplitEngineResult) -> XfaSplitEngineResult:
)
def _apply_prefix_post_processor(value: str, processor: XfaSplitPostProcessor) -> str | None:
"""从已定位行中提取指定标签及分隔符后的值;未命中必须显式进入复核。"""
source = str(value or '')
comparable = source if processor.case_sensitive else source.lower()
label = processor.value if processor.case_sensitive else processor.value.lower()
start = comparable.find(label)
if start < 0:
return None
tail_start = start + len(label)
tail = source[tail_start:]
for separator in processor.separators:
if tail.startswith(separator):
return tail[len(separator):].strip()
return None
def _apply_xfa_post_processors(
result: XfaSplitEngineResult,
*,
rule_set: XfaSplitRuleSet,
) -> XfaSplitEngineResult:
"""对已由正式 matcher 定位的行执行受限后处理,并重新聚合正式字段。"""
rules = {rule.rule_id: rule for rule in rule_set.rules}
mapped_fields: dict[str, str] = {}
needs_review = result.status == 'needs_review'
for segment in result.segments:
rule = rules.get(segment.rule_id)
for processor in (rule.matcher.post_processors if rule else []):
extracted = _apply_prefix_post_processor(segment.normalized_text, processor)
if extracted is None:
segment.normalized_text = ''
segment.status = 'needs_review'
needs_review = True
result.diagnostics.append(XfaSplitDiagnostic(
code='post_processor_no_match',
message=f'Rule {segment.rule_id} post processor did not match the selected line',
line_no=segment.line_no,
field_code=segment.target_field_code,
rule_ids=[segment.rule_id],
))
break
segment.normalized_text = extracted
if segment.handling == 'mapped' and segment.target_field_code:
mapped_fields[segment.target_field_code] = segment.normalized_text
result.mapped_fields = mapped_fields
if needs_review:
result.status = 'needs_review'
return result
# ---------------------------------------------------------------------------
# 对外执行入口——签名 100% 不变
# ---------------------------------------------------------------------------
@@ -177,7 +228,7 @@ def execute_split_rule_set(
rule_set=rule_set,
lines=lines,
)
return _core_result_to_xfa(core_result)
return _apply_xfa_post_processors(_core_result_to_xfa(core_result), rule_set=rule_set)
def execute_split_on_leaf(
@@ -16,7 +16,7 @@ from decimal import Decimal
from typing import Any
from app import db
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingDocumentProfileTestRun,
ShippingDocumentProfileTestSample,
@@ -30,13 +30,18 @@ from app.models import (
ShippingOrderDocumentProfileSample,
)
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot, _hydrate_coordinate_evidence
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
coordinate_profile_character_candidates,
reconstruct_coordinate_profile_rows, reconstruction_exclusion_regions,
reconstruct_coordinate_profile_rows_with_strategy,
)
from app.services.shipping_notice.document_layout.runtime_parse_strategy import resolve_runtime_parse_strategy
from app.services.shipping_notice.document_layout.order_field_extraction import (
_is_placeholder_anchor_text, extract_order_fields,
)
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ensure_on_demand_coordinate_evidence
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
from app.services.shipping_notice import order_document_profile_service as profile_service
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
from app.services.shipping_notice.order_document_profile_service import (
@@ -44,6 +49,10 @@ from app.services.shipping_notice.order_document_profile_service import (
_normalize_definition, _require_schema_version,
)
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
from app.services.shipping_notice.reservation_region import (
apply_reservation_region_candidates,
extract_reservation_from_region_text,
)
# 日常模板维护采用一份独立样本门槛;字段 confirmed、人工真值一致、
@@ -126,109 +135,50 @@ def _table_html(document_id: int, table_id: str) -> str:
raise ValidationError('Test sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
def _coordinate_table_available(document_id: int, table_id: str) -> bool:
"""确认 v2 盲测有冻结页面尺寸和目标表的字符证据,不要求 MinerU HTML。"""
document = db.session.get(ShippingOrderDocument, int(document_id))
layout = current_layout_snapshot(document) if document is not None else {}
raw_table = next((item for item in (layout or {}).get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)), None)
evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {}
return bool(
isinstance(raw_table, dict)
and isinstance((evidence.get('tables') or {}).get(str(table_id)), list)
and isinstance((evidence.get('pages') or {}).get(str(raw_table.get('page_no') or '')), dict)
)
def _recover_coordinate_table_for_preview(
*, document: ShippingOrderDocument, layout: dict[str, Any], raw_table: dict[str, Any], table_id: str,
) -> dict[str, Any]:
"""仅为盲测复核临时恢复表格及整页坐标,不写回冻结布局或正式解析输入。"""
recovered = ensure_on_demand_coordinate_evidence(
document=document, layout=layout,
page_nos={int(raw_table.get('page_no') or 1)},
table_by_page={int(raw_table.get('page_no') or 1): raw_table},
)
evidence = recovered.get('coordinate_evidence') if isinstance(recovered.get('coordinate_evidence'), dict) else {}
if (
isinstance((evidence.get('tables') or {}).get(str(table_id)), list)
and isinstance((evidence.get('pages') or {}).get(str(raw_table.get('page_no') or 1)), dict)
):
return recovered
def _coordinate_table_available_in_layout(layout: dict[str, Any], *, table_id: str, page_no: int) -> bool:
"""判断运行期布局是否已有目标表与页面坐标证据。"""
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page_no = str(raw_table.get('page_no') or 1)
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
page_sources = (evidence.get('sources') or {}).get('pages') if isinstance(evidence.get('sources'), dict) else {}
if (
isinstance(tables.get(table_id), list)
and isinstance(pages.get(page_no), dict)
and isinstance(page_glyphs.get(page_no), list)
and str((page_sources or {}).get(page_no) or '') in {'pdf_coordinate', 'ocr_coordinate'}
):
return layout
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
return layout
try:
from app.models import FileAsset
from app.services.file_assets.service import read_asset_bytes
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
from app.services.shipping_notice.order_document_profile_service import (
_native_characters_in_table, _ocr_lines_to_characters, _ocr_lines_to_page_characters,
)
asset = db.session.get(FileAsset, document.asset_id)
if asset is None:
return layout
page = next(
item for item in extract_native_pdf_pages(read_asset_bytes(asset))
if item.page_no == int(raw_table.get('page_no') or 0)
)
native_characters = list(getattr(page, 'characters', []) or [])
full_page_characters = [item.model_dump(mode='json') for item in native_characters]
source = 'pdf_coordinate'
characters = _native_characters_in_table(
characters=native_characters, table_bbox=raw_table.get('bbox') or {},
)
if not characters:
ocr_lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
full_page_characters = _ocr_lines_to_page_characters(lines=ocr_lines)
characters = _ocr_lines_to_characters(lines=ocr_lines, table_bbox=raw_table.get('bbox') or {})
source = 'ocr_coordinate'
if not characters or not full_page_characters:
return layout
next_layout = dict(layout)
next_evidence = dict(evidence)
next_evidence['tables'] = {**tables, table_id: characters}
next_evidence['pages'] = {
**pages, str(page.page_no): {'width': page.width, 'height': page.height},
}
next_evidence['page_glyphs'] = {**page_glyphs, str(page.page_no): full_page_characters}
sources = dict(evidence.get('sources') or {})
sources['pages'] = {**dict(sources.get('pages') or {}), str(page.page_no): source}
next_evidence['sources'] = sources
next_layout['coordinate_evidence'] = next_evidence
return next_layout
except Exception:
return layout
return bool(
isinstance((evidence.get('tables') or {}).get(str(table_id)), list)
and isinstance((evidence.get('pages') or {}).get(str(page_no)), dict)
)
def _region_characters_for_quality(
*, region: Any, evidence: dict[str, Any], raw_table: dict[str, Any], table_id: str,
) -> list[dict[str, Any]] | None:
"""为盲测按模板显式策略选取冻结字符;旧模板始终沿用表格局部证据。"""
table_characters = (evidence.get('tables') or {}).get(str(table_id))
if getattr(region, 'row_reconstruction_mode', 'fixed_subrows') != 'adaptive_record_columns':
return table_characters if isinstance(table_characters, list) else None
"""为盲测选择当前页字符,确保与编辑器预览和正式解析共用同一输入事实。"""
page_no = str(raw_table.get('page_no') or 1)
page_characters = (evidence.get('page_glyphs') or {}).get(page_no)
if isinstance(page_characters, list):
return page_characters
# 冻结快照仍可能来自升级前的证据结构;保持该模板原有表格证据可读。
# 旧冻结快照可能没有页级坐标;仅在该事实缺失时回退当前物理表的字符。
table_characters = (evidence.get('tables') or {}).get(str(table_id))
return table_characters if isinstance(table_characters, list) else None
def _quality_page_characters(
*, region: Any, evidence: dict[str, Any], raw_table: dict[str, Any], page_no: int,
) -> list[dict[str, Any]] | None:
"""按表格实例隔离盲测行证据,禁止后续页重复消费首页 table glyphs。"""
table_page_no = int(raw_table.get('page_no') or 1)
if page_no == table_page_no:
return _region_characters_for_quality(
region=region, evidence=evidence, raw_table=raw_table,
table_id=str(raw_table.get('table_id') or ''),
)
continuation = getattr(region, 'continuation_rule', None)
allow_cross_page = bool(
continuation.get('allow_cross_page')
if isinstance(continuation, dict)
else getattr(continuation, 'allow_cross_page', False)
)
if not allow_cross_page:
return None
page_glyphs = (evidence.get('page_glyphs') or {}).get(str(page_no))
return page_glyphs if isinstance(page_glyphs, list) else None
def _ensure_order_field_evidence(
*, document: ShippingOrderDocument, layout: dict[str, Any], parser: OrderCoordinateProfile,
) -> dict[str, Any]:
@@ -396,7 +346,9 @@ def _candidate_for_sample(
'Blind-test preview layout changed',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE',
)
layout = dict(frozen_version.payload_json) if frozen_version is not None else (
layout = _hydrate_coordinate_evidence(
payload=dict(frozen_version.payload_json), document=document,
) if frozen_version is not None and document is not None else (
current_layout_snapshot(document) if document is not None else None
)
is_document_candidate = str(table_id) == DOCUMENT_CANDIDATE_TABLE_ID
@@ -409,21 +361,9 @@ def _candidate_for_sample(
# 失败版本不会成为“当前成功快照”,但文档级盲测仍需以其安全元数据
# 为起点从原文件临时恢复坐标;这里不把失败布局提升为正式快照。
layout = dict(document.current_layout_version.payload_json)
if document is None:
raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
if is_document_candidate and not layout:
# 上传与复核解耦后,后台 Layout 可能仍为 queued/running 且尚无 payload。
# 文档级候选从安全空骨架进入现有原 PDF 按需恢复链,不等待、不取消也不写回后台任务。
layout = {'status': 'pending', 'tables': [], 'issues': []}
if not layout:
if document is None or not layout:
raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
if isinstance(parser, OrderCoordinateProfile):
if is_document_candidate:
# [STEP 1] MinerU 未产出表格时,盲测仍以原文件字符坐标运行当前模板;
# 证据只驻留本次调用,绝不写回布局或改变生产模板命中输入。
layout = ensure_on_demand_coordinate_evidence(
document=document, layout=layout, page_nos=None,
)
layout = _ensure_order_field_evidence(document=document, layout=layout, parser=parser)
schema_fields = {
str(item.get('field_id') or ''): item
@@ -435,20 +375,12 @@ def _candidate_for_sample(
item for item in layout.get('tables') or []
if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)
), None)
if isinstance(raw_table, dict) and frozen_version is None:
layout = _recover_coordinate_table_for_preview(
document=document, layout=layout, raw_table=raw_table, table_id=str(table_id),
)
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
if (
not is_document_candidate
and not _coordinate_table_available(document_id, table_id)
and not isinstance((evidence.get('tables') or {}).get(str(table_id)), list)
):
if not isinstance((evidence.get('tables') or {}).get(str(table_id)), list):
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
if is_document_candidate and not any(isinstance(value, list) and value for value in page_glyphs.values()):
if not any(isinstance(value, list) and value for value in page_glyphs.values()):
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
rows: list[dict[str, Any]] = []
for region in parser.table_regions:
@@ -456,19 +388,14 @@ def _candidate_for_sample(
# layout. They are valid template regions, but cannot reconstruct rows.
if not region.line_layouts:
continue
if is_document_candidate:
eligible_pages = [
int(page_no) for page_no in pages
if str(page_no).isdigit()
and (
region.page_scope == 'all_pages'
or (region.page_scope == 'first_page' and int(page_no) == 1)
or (region.page_scope == 'continuation_pages' and int(page_no) > 1)
or (region.page_scope == 'exact_page' and int(page_no) == region.page_no)
)
]
else:
eligible_pages = [int(raw_table.get('page_no') or 1)] if isinstance(raw_table, dict) else []
# ``page_scope`` 是历史人工策略。验证必须与正式解析一致:检查当前样本中
# 每个有页级坐标事实的页面,由实际行结果决定是否属于续页。
eligible_pages = [
int(page_no) for page_no, glyphs in page_glyphs.items()
if str(page_no).isdigit() and isinstance(glyphs, list) and glyphs
]
if not eligible_pages and isinstance(raw_table, dict):
eligible_pages = [int(raw_table.get('page_no') or 1)]
for page_no in sorted(eligible_pages):
page = pages.get(str(page_no))
if not isinstance(page, dict):
@@ -477,31 +404,115 @@ def _candidate_for_sample(
table_bbox = {'x0': 0, 'y0': 0, 'x1': float(page['width']), 'y1': float(page['height'])}
except (KeyError, TypeError, ValueError):
continue
characters = (
page_glyphs.get(str(page_no))
if is_document_candidate
else _region_characters_for_quality(
region=region, evidence=evidence, raw_table=raw_table, table_id=str(table_id),
if is_document_candidate:
characters = page_glyphs.get(str(page_no))
elif not isinstance(raw_table, dict):
characters = None
else:
characters = _quality_page_characters(
region=region, evidence=evidence, raw_table=raw_table, page_no=page_no,
)
candidate_table_bbox = raw_table.get('bbox') if isinstance(raw_table, dict) and page_no == int(raw_table.get('page_no') or 1) else None
characters, _candidate_page_bbox = coordinate_profile_character_candidates(
table_region=region.region.model_dump(), page_size=page,
reference_page_frame=(
region_frame.model_dump()
if (region_frame := parser.reference_page_frames.get(page_no)) is not None else None
),
page_characters=characters if isinstance(characters, list) else None,
table_characters=(evidence.get('tables') or {}).get(str(raw_table.get('table_id') or '')) if isinstance(raw_table, dict) else None,
raw_table_bbox=candidate_table_bbox,
table_id=str(raw_table.get('table_id') or '') if isinstance(raw_table, dict) else None,
page_no=page_no,
allow_table_fallback=(
isinstance(raw_table, dict)
and page_no == int(raw_table.get('page_no') or 1)
),
)
if not isinstance(characters, list):
continue
rows.extend(item.fields for item in reconstruct_coordinate_profile_rows(
characters=[item for item in characters if isinstance(item, dict)], table_bbox=table_bbox,
# 表头布局只描述列语义和预览高亮,不能作为静态删除区;否则单头高度变化时
# 会在起行锚点识别前误删首条明细字符。仅应用管理员明确配置的普通排除区。
reconstruction_exclusions = reconstruction_exclusion_regions(region.model_dump())
reconstruction_table_bbox = (
{
'x0': 0, 'y0': 0,
'x1': region_frame.width, 'y1': region_frame.height,
}
if region_frame is not None else table_bbox
)
chosen_rows, strategy = reconstruct_coordinate_profile_rows_with_strategy(
characters=[item for item in characters if isinstance(item, dict)], table_bbox=reconstruction_table_bbox,
line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(),
termination_rules=[item.model_dump() for item in region.termination_rules],
exclusion_regions=[item.model_dump() for item in region.exclusion_regions],
exclusion_regions=reconstruction_exclusions,
dynamic_exclusion_regions=reconstruction_exclusions,
line_start_field_code=region.line_start_field_code,
row_reconstruction_mode=region.row_reconstruction_mode,
) if not item.issues)
schema_field_metadata=list(schema_fields.values()),
)
if strategy.status == 'selected':
rows.extend(item.fields for item in chosen_rows if not item.issues)
order_fields = [
{
'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status,
'field_id': item.field_id, 'scope': item.scope,
'page_no': item.page_no, 'issues': list(item.issues),
}
for item in extract_order_fields(profile=parser, schema_fields=schema_fields, coordinate_evidence=evidence)
for item in extract_order_fields(
profile=parser,
schema_fields=schema_fields,
coordinate_evidence=evidence,
allow_fixed_region_confirmation=True,
)
]
# 盲测与正式解析共用 Reservation 区域解析和归属契约;区域页可以不同于明细页。
profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
reservation_region = profile_definition.get('reservation_id_region')
if isinstance(reservation_region, dict):
region = reservation_region.get('region')
try:
reservation_page_no = int(reservation_region.get('page_no') or 0)
except (TypeError, ValueError):
reservation_page_no = 0
if isinstance(region, dict) and reservation_page_no > 0:
layout = _ensure_page_coordinate_evidence(
document=document, layout=layout, page_no=reservation_page_no,
)
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page = (evidence.get('pages') or {}).get(str(reservation_page_no))
glyphs = (evidence.get('page_glyphs') or {}).get(str(reservation_page_no))
if isinstance(page, dict) and isinstance(glyphs, list):
candidates = extract_reservation_from_region_text(
read_coordinate_region_text(glyphs=glyphs, page=page, region=region),
)
reservation_fields = {
str(field.get('scope') or ''): field
for field in schema_fields.values()
if str(field.get('field_code') or '') == 'reservation_id'
}
applied = apply_reservation_region_candidates(
candidates=candidates,
header_field_id=str((reservation_fields.get('header') or {}).get('field_id') or '') or None,
line_field_id=str((reservation_fields.get('line') or {}).get('field_id') or '') or None,
line_count=len(rows),
)
if applied.header_value and reservation_fields.get('header'):
header = reservation_fields['header']
order_fields.append({
'field_code': str(header.get('field_code') or ''), 'value': applied.header_value,
'status': 'confirmed', 'field_id': str(header.get('field_id') or ''), 'scope': 'header',
'page_no': reservation_page_no, 'issues': [],
})
if reservation_fields.get('line'):
for line_no, value in applied.line_values.items():
if isinstance(rows[line_no - 1], dict):
rows[line_no - 1]['reservation_id'] = value
if applied.needs_review:
return {
'document_id': document.id, 'table_id': str(table_id), 'rows': rows,
'order_fields': order_fields, 'reservation_region_status': 'needs_review',
'reservation_region_review_reasons': list(applied.review_reasons),
}
return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields}
raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
@@ -562,7 +573,7 @@ def _common_blind_sample_descriptors(
layout_version = ShippingDocumentLayoutVersion.query.filter_by(document_id=document.id).order_by(
ShippingDocumentLayoutVersion.version.desc(), ShippingDocumentLayoutVersion.id.desc(),
).first()
layout = dict(layout_version.payload_json) if layout_version is not None and isinstance(layout_version.payload_json, dict) else {}
layout = current_layout_snapshot(document) or {}
tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
if (
layout_version is None or layout_version.status != 'ready'
@@ -595,7 +606,9 @@ def _common_blind_sample_descriptors(
except ValidationError:
continue
header_preview = [slot.text for slot in (grid.rows[0] if grid.rows else []) if slot is not None and slot.text][:3]
coordinate_evidence_ready = _coordinate_table_available(document.id, table_id)
coordinate_evidence_ready = _coordinate_table_available_in_layout(
layout, table_id=table_id, page_no=int(table.get('page_no') or 1),
)
descriptors.append({
'document_id': document.id, 'table_id': table_id,
'page_no': int(table.get('page_no') or 1), 'filename': document.filename or '',
@@ -634,6 +647,11 @@ def _compare_blind_candidate(
failures: list[str] = []
total = 0
matched = 0
if candidate.get('reservation_region_status') == 'needs_review':
failures.extend([
f'reservation_region:{reason}'
for reason in candidate.get('reservation_region_review_reasons') or ['needs_review']
])
for field in candidate.get('order_fields') or []:
if not isinstance(field, dict):
continue
@@ -820,7 +838,7 @@ def _prepare_common_blind_sample(
or not isinstance(version.payload_json, dict)
):
raise ConflictError('Blind-test preview layout changed', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE')
layout = dict(version.payload_json)
layout = _hydrate_coordinate_evidence(payload=dict(version.payload_json), document=document)
raw_table = next((
item for item in layout.get('tables') or []
if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)
@@ -1084,11 +1102,6 @@ def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
or last_run.status != 'passed' or last_run.profile_checksum != _quality_checksum(profile)
):
raise ConflictError('A current passing blind test run is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY')
if int(actor_id) == int(suite.created_by_id):
raise ForbiddenError(
'Editor cannot approve own blind test suite',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY',
)
suite.status = 'approved'
# A coordinate-template approval is also its publish-quality credential.
# Validate the remaining publish prerequisites before committing approval so
@@ -41,7 +41,7 @@ def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str
if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}:
return 'closed'
upload = str(get('upload_status', '') or '').strip().lower()
if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no') or get('upload_receipt_json'):
if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no'):
return 'completed'
return 'active'
@@ -566,10 +566,10 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'inventory_preparation_waiting': _meta('worker', 'poll_inventory_preparation', '库存文件准备中,请稍后刷新'),
'inventory_preparation_failed': _meta('owner', 'retry_inventory_preparation', '库存准备失败,请重试或上传库存文件'),
'inventory_rpa_queued': _meta('worker', 'poll_inventory_preparation', 'RPA 任务已排队等待执行'),
'inventory_rpa_timeout': _meta('worker', 'retry_inventory_preparation', 'RPA 执行超时'),
'inventory_rpa_timeout': _meta('worker', 'reload_inventory_result', 'RPA 执行超时'),
'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'),
'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'),
'inventory_rpa_exhausted': _meta('owner', 'upload_inventory_file', '库存源重试次数已耗尽'),
'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'),
'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'),
'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'),
'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'),
@@ -583,7 +583,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'),
'excel_not_ready': _meta('system', 'recheck_excel_readiness', '当前尚不满足 Excel 生成条件'),
'artifact_generation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 生成失败'),
'manual_upload_pending': _meta('owner', 'mark_manual_uploaded', '请下载 Excel 后在货代平台上传并登记结果'),
'manual_upload_pending': _meta('owner', 'mark_manual_uploaded', '请下载 Excel 后在货代平台上传并确认已上传'),
'upload_rpa_pending': _meta('worker', 'poll_freight_upload_rpa', '货代平台上传任务等待执行'),
'upload_rpa_failed': _meta('worker', 'retry_freight_upload_rpa', '货代平台上传失败,可重试 RPA'),
'upload_rpa_login_failed': _meta('admin', 'retry_freight_upload_rpa', '货代平台登录失败,请检查凭据后重试'),
@@ -601,7 +601,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'void_blocked_external_uploaded': _meta('owner', '', '已存在外部履约,禁止作废,请归档'),
'task_rejected_by_user': _meta('owner', '', '订单候选/任务已由用户驳回'),
'task_closed_after_upload': _meta('owner', '', '上传完成后任务已关闭'),
'close_blocked_missing_receipt': _meta('owner', 'mark_manual_uploaded', '缺少上传回执,暂不可关闭'),
'close_blocked_missing_receipt': _meta('owner', 'mark_manual_uploaded', '尚未确认已上传,暂不可关闭'),
'late_callback_ignored': _meta('system', '', '迟到的外部回调已忽略'),
'excel_downloaded': _meta('owner', '', '已下载发货 Excel'),
'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'),
+99 -86
View File
@@ -24,9 +24,11 @@ from openpyxl import load_workbook
from openpyxl.cell.cell import MergedCell
from sqlalchemy import func
from app import db
from app.core.errors import ConflictError
from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingNoticeLine,
ShippingInventoryField,
ShippingInventorySource,
ShippingOrderSnapshot,
@@ -37,6 +39,31 @@ from app.path_utils import resolve_backend_relative_path
from app.services.file_assets.storage import file_asset_storage
def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None:
"""
确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。
Args:
task: 当前发货通知单。
Raises:
ConflictError: 已存在任意导出 Artifact;后续库存必须创建新的发货通知单。
"""
if task.id is None:
return
existing = ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first()
if existing is not None:
raise ConflictError(
'A shipping notice can generate only one Excel artifact',
code='SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED',
details={
'task_no': task.task_no,
'business_no': task.business_no,
'artifact_no': existing.artifact_no,
},
)
def _storage_root() -> Path:
"""返回发货通知文件根目录。"""
configured = str(current_app.config.get('SHIPPING_NOTICE_STORAGE_ROOT') or '').strip()
@@ -45,8 +72,22 @@ def _storage_root() -> Path:
return Path(current_app.instance_path) / 'shipping_notice'
def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
"""后续分批 Notice 回读同一 OT 的首个冻结 Notice,订单事实不复制。"""
if notice.order_snapshot_id:
return notice
if notice.order_task_id:
source = ShippingNotice.query.filter(
ShippingNotice.order_task_id == int(notice.order_task_id),
ShippingNotice.order_snapshot_id.isnot(None),
).order_by(ShippingNotice.id.asc()).first()
if source is not None:
return source
return notice
def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]:
"""从冻结 Snapshot 按稳定 field_id 返回 Header/Line 值,禁止履约阶段读取 FieldValue。"""
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
assert_task_not_supersession_blocked(task)
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
@@ -62,19 +103,10 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di
def _excel_business_no(task: ShippingNotice, *, export_date: date | None = None) -> str | None:
"""生成本次 Excel 使用的 Pull Request Number;不回写业务单主编号。"""
case = task.shipping_case
if case is None or not case.business_no:
return None
business_no = str(case.business_no).strip()
prefix = business_no[:-8] if len(business_no) > 8 else business_no
sequence = business_no[-2:] if len(business_no) >= 2 and business_no[-2:].isdigit() else ''
if not sequence and case.sequence_value:
sequence = f'{int(case.sequence_value):02d}'
if not sequence:
return None
export_date = export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date()
return f'{prefix}{export_date.strftime("%y%m%d")}{sequence}'
"""返回当前发货通知单编号;履约路径不回退到其他聚合标识。"""
if task.business_no:
return str(task.business_no).strip()
return None
def _clear_template_data_rows(ws: Any, start_row: int) -> None:
@@ -92,6 +124,7 @@ def _system_fact(
*,
export_sequence: int | None = None,
excel_business_no: str | None = None,
notice_no: str | None = None,
export_date: date | None = None,
) -> Any:
"""
@@ -106,8 +139,8 @@ def _system_fact(
对应系统事实值;未知键返回 None。
"""
values = {
'task_no': task.task_no,
'business_no': excel_business_no or (task.shipping_case.business_no if task.shipping_case else None),
'task_no': notice_no or task.task_no,
'business_no': notice_no or excel_business_no or task.business_no,
'warehouse_id': task.inventory_warehouse_id,
'inventory_source_code': task.inventory_source_code,
'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(),
@@ -160,6 +193,7 @@ def _mapping_value(
mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any],
header_values: dict[str, Any] | None = None, export_sequence: int | None = None,
excel_business_no: str | None = None,
notice_no: str | None = None,
export_date: date | None = None,
) -> Any:
"""
@@ -196,6 +230,7 @@ def _mapping_value(
task, key,
export_sequence=export_sequence if key == 'export_sequence' else None,
excel_business_no=excel_business_no,
notice_no=notice_no,
export_date=export_date,
)
if key == 'export_sequence' and value is None:
@@ -393,6 +428,7 @@ def _filename(
template: ShippingExcelTemplate,
*,
excel_business_no: str | None = None,
notice_no: str | None = None,
) -> str:
"""按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。"""
pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip()
@@ -401,16 +437,15 @@ def _filename(
if not pattern:
raise ValueError('发货 Excel 文件名规则未配置')
now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S')
shipping_case = task.shipping_case
values = {
'task_no': task.task_no,
'business_no': excel_business_no or (shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no),
'task_no': notice_no or task.task_no,
'business_no': notice_no or excel_business_no or task.business_no or task.task_no,
'source_code': task.inventory_source_code or '',
'ts': now,
'date': now[:8],
'customer_short_code': (shipping_case.customer_short_code_snapshot or '') if shipping_case else '',
'business_date': shipping_case.business_date.strftime('%y%m%d') if shipping_case and shipping_case.business_date else '',
'sequence': f'{int(shipping_case.sequence_value):02d}' if shipping_case and shipping_case.sequence_value else '',
'customer_short_code': task.customer_short_code_snapshot or '',
'business_date': task.business_date.strftime('%y%m%d') if task.business_date else '',
'sequence': f'{int(task.business_sequence_value):02d}' if task.business_sequence_value else '',
}
try:
return _safe_filename(pattern.format(**values))
@@ -422,6 +457,7 @@ def _input_checksum(
task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate,
snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
notice_id: int | None = None,
) -> str:
"""以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。"""
payload = {
@@ -430,12 +466,15 @@ def _input_checksum(
'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id,
'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines,
'notice_id': notice_id,
}
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExportArtifact]:
def generate_shipment_excel(
task: ShippingNotice,
) -> tuple[str, str, ShippingExportArtifact]:
"""
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
@@ -445,56 +484,16 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
Raises:
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
AppError: [T6 硬门禁] 行级库存匹配存在非 matched 行(shortage / not_found / conflict)。
AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。
"""
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
from app.core.errors import AppError
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
# [T6 E2 硬门禁] 生成 Excel 前复用库存满足性判定:每行须库存充足,
# 或为带原因的正式短缺放行;未匹配/冲突绝不能用放行绕过。
if task.id is not None:
pending_rows = db.session.query(
ShippingNoticeLineInventoryMatch.line_key,
ShippingNoticeLineInventoryMatch.match_result,
ShippingNoticeLineInventoryMatch.part_number,
ShippingNoticeLineInventoryMatch.reservation_id,
ShippingNoticeLineInventoryMatch.shortage_qty,
).filter(
ShippingNoticeLineInventoryMatch.task_id == task.id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
).limit(20).all()
# 行级库存事实是当前正式放行 Gate 的真相。历史导出任务可能只有
# Reservation 核验轮次;这类任务继续由下方 Reservation 选择保护,不能因
# 缺少新表事实被误判为“未匹配”。
has_line_match_facts = bool(pending_rows)
from app.services.shipping_notice.fulfillment_workflow import match_completed
if has_line_match_facts and not match_completed(task):
details = [
{
'line_key': r[0],
'match_result': r[1],
'part_number': r[2],
'reservation_id': r[3],
'shortage_qty': r[4],
}
for r in pending_rows
]
raise AppError(
code='SHIPPING.EXCEL_NOT_READY',
message='存在未满足或未放行的库存行,禁止生成发货 Excel(请先处理短缺或冲突)。',
http_status=409,
details={
'blocking_reason_code': 'inventory_match_incomplete',
'pending_count': len(pending_rows),
'pending_rows_preview': details,
'resume_suggestion': '调用 match_inventory 重匹配或人工逐行确认短缺/冲突后再导出。',
},
)
assert_notice_has_no_export_artifact(task)
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
source_code = str(task.inventory_source_code or '').strip().upper()
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
@@ -524,18 +523,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
# applies only when the published template actually consumes that system fact.
if _template_requires_system_warehouse_id(mappings) and not str(task.inventory_warehouse_id or '').strip():
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
active_artifact = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == task.id,
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
).first()
if active_artifact is not None:
raise ValueError('当前任务存在待上传的发货 Excel,必须先完成或授权作废该 Artifact')
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
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
if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task)
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
excel_business_no = _excel_business_no(task, export_date=export_date)
from app.services.shipping_notice.reservation_service import (
current_available_snapshot_line_ids,
reserve_available_for_artifact,
@@ -550,12 +543,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
released_source_line_indexes: set[int] = set()
if task.id is not None:
if source_notice.id is not None:
release_rows = (
ShippingOrderReviewLineDecision.query
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
)
@@ -574,10 +567,19 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
for source_index, line in enumerate(snapshot.lines)
if source_index in release_overrides_by_source_line
}
verification, available_line_ids = current_available_snapshot_line_ids(
task,
released_snapshot_line_ids=released_snapshot_line_ids,
)
selected_snapshot_line_ids = {
int(row.snapshot_line_id)
for row in ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).all()
if row.snapshot_line_id is not None
}
try:
verification, available_line_ids = current_available_snapshot_line_ids(
source_notice,
released_snapshot_line_ids=released_snapshot_line_ids,
selected_snapshot_line_ids=selected_snapshot_line_ids or None,
)
except ConflictError:
raise
# [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
line_values = []
for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)):
@@ -591,7 +593,7 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
# [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
inventory_lines = resolve_inventory_lines_for_execution(task)
inventory_lines = resolve_inventory_lines_for_execution(source_notice)
release_overrides_by_line = _release_overrides_for_export_lines(
line_values=line_values,
release_overrides_by_source_line=release_overrides_by_source_line,
@@ -613,9 +615,17 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values]
header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields)
# [STEP 4] Notice 的业务单号与首个 Excel 同一事务产生。此处已完成业务、
# 库存和导出行校验;随后 Excel、Artifact 或 Reservation 任一步失败都会回滚编号流水。
if not task.business_no:
from app.services.shipping_notice.business_numbering_service import assign_notice_business_number
assign_notice_business_number(task)
excel_business_no = _excel_business_no(task, export_date=export_date)
filename = _filename(task, template, excel_business_no=excel_business_no)
artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}'
directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no
directory_key = task.task_no
directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / directory_key
directory.mkdir(parents=True, exist_ok=True)
path = directory / f'{artifact_no}_{filename}'
template_bytes = file_asset_storage.get_bytes(template.storage_key)
@@ -658,14 +668,16 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
wb.close()
content = path.read_bytes()
# 滚动履约允许同一任务按后续库存分批导出;已就绪 Artifact 仍是
# 已占用预约单的审计事实,不能被新一轮导出整体覆盖为 superseded。
# 当前 Notice 的唯一 Excel;后续分批履约必须先创建新的 Notice,
# 因而不得在此处替换或追加当前 Notice 的 Artifact。
artifact = ShippingExportArtifact(
artifact_no=artifact_no, task_id=task.id, template_id=template.id,
artifact_no=artifact_no, task_id=task.id,
template_id=template.id,
order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id,
input_checksum=_input_checksum(
task, source, template, snapshot, header_values, line_values, inventory_lines,
notice_id=int(task.id),
),
file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(),
file_size=len(content), status='ready',
@@ -673,10 +685,11 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
db.session.add(artifact)
db.session.flush()
reserve_available_for_artifact(
task,
source_notice,
artifact=artifact,
verification=verification,
released_snapshot_line_ids=released_snapshot_line_ids,
selected_snapshot_line_ids=selected_snapshot_line_ids or None,
)
return str(path), filename, artifact
except Exception:
@@ -3,7 +3,7 @@ services/shipping_notice/export_archive.py
用途:为显式任务集合生成受权限控制的发货 Excel ZIP 下载包。
依赖:ShippingExportArtifact、query_service 用户归属查询、zipfile 与统一业务异常。
逻辑:选择每票全部 ready Artifact,校验文件 checksum,处理重名并写入 manifest.json。
逻辑:选择每张通知唯一可下载 Artifact,校验文件 checksum,处理重名并写入 manifest.json。
"""
from __future__ import annotations
@@ -23,15 +23,23 @@ from app.services.shipping_notice.query_service import get_task_for_user, resolv
MAX_ARCHIVE_TASKS = 100
def _select_tasks(*, user_id: int, task_nos: list[str] | None) -> tuple[list[ShippingNotice], str]:
"""按显式任务号选择当前用户任务,禁止部分越权成功。"""
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_nos or []) if str(item or '').strip()))
def _select_tasks(
*,
user_id: int,
task_refs: list[str] | None,
selection_name: str,
require_business_no: bool = False,
) -> tuple[list[ShippingNotice], str]:
"""按显式 task_no 或 business_no 选择当前用户通知,禁止部分越权成功。"""
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_refs or []) if str(item or '').strip()))
if not normalized_tasks:
raise ValidationError('task_nos is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
raise ValidationError(f'{selection_name} is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
tasks = []
for task_no in normalized_tasks:
task = get_task_for_user(task_no, user_id)
if task is None:
if task is None or (
require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper()
):
raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
tasks.append(task)
if not tasks:
@@ -77,14 +85,28 @@ def _archive_name(filename: str, task_no: str, used: set[str]) -> str:
return candidate
def build_export_archive(*, user_id: int, task_nos: list[str]) -> tuple[BinaryIO, str, dict]:
def build_export_archive(
*,
user_id: int,
task_nos: list[str] | None = None,
business_nos: list[str] | None = None,
) -> tuple[BinaryIO, str, dict]:
"""
生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。
Returns:
(定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。
"""
tasks, archive_key = _select_tasks(user_id=user_id, task_nos=task_nos)
if task_nos is not None and business_nos is not None:
raise ValidationError('select either task_nos or business_nos', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
selection_values = business_nos if business_nos is not None else task_nos
selection_name = 'business_nos' if business_nos is not None else 'task_nos'
tasks, archive_key = _select_tasks(
user_id=user_id,
task_refs=selection_values,
selection_name=selection_name,
require_business_no=business_nos is not None,
)
artifacts = _ready_artifacts(tasks)
# 小包驻留内存,超过 16 MiB 自动落到系统临时目录,避免批次下载挤占 worker 内存。
stream = SpooledTemporaryFile(max_size=16 * 1024 * 1024, mode='w+b')
@@ -113,7 +135,7 @@ def build_export_archive(*, user_id: int, task_nos: list[str]) -> tuple[BinaryIO
included += 1
entries.append(entry)
manifest = {
'archive_version': 1, 'selection': {'task_nos': task_nos},
'archive_version': 1, 'selection': {selection_name: selection_values},
'generated_at': datetime.utcnow().isoformat(), 'total_tasks': len(tasks),
'included_count': included, 'excluded_count': len(entries) - included, 'entries': entries,
}
@@ -1,10 +1,10 @@
"""
services/shipping_notice/freight_cancellation_service.py
用途:货代撤销回执登记,以及建单后取消时的只读 / 待作废软处置(禁止物理删除)。
用途:外部撤销确认登记,以及建单后取消时的只读 / 待作废软处置(禁止物理删除)。
依赖:ShippingFreightCancellation、ShippingNotice、ShippingTaskEvent、Workflow Item Version、
fulfillment_audit。
逻辑:complete_freight_cancellation 登记回执并作废旧任务;mark_cancelled_task_readonly
逻辑:complete_freight_cancellation 登记外部撤销确认并作废旧任务;mark_cancelled_task_readonly
在用户取消已建单 WorkflowItem 时将 Task 置 pending_void、Excel/Version 只读,
并写前后快照审计。
"""
@@ -24,19 +24,15 @@ def complete_freight_cancellation(
*,
cancellation_id: int,
actor_id: int,
freight_receipt_no: str,
receipt_asset_id: int,
note: str | None = None,
) -> ShippingFreightCancellation:
"""
登记可追溯的货代撤销回执,随后作废旧任务并解除新版本的履约阻断。
登记可追溯的外部撤销确认,随后作废旧任务并解除新版本的履约阻断。
Args:
cancellation_id: 撤销单主键。
actor_id: 操作人。
freight_receipt_no: 货代回执号。
receipt_asset_id: 回执 FileAsset。
note: 可选备注。
note: 外部撤销确认原因,必填。
Returns:
更新后的 ShippingFreightCancellation。
@@ -46,9 +42,9 @@ def complete_freight_cancellation(
raise NotFoundError('Freight cancellation not found', code='SHIPPING.FREIGHT_CANCELLATION_NOT_FOUND')
if row.status == 'cancelled':
return row
receipt = str(freight_receipt_no or '').strip()
if not receipt or not receipt_asset_id:
raise ValidationError('Cancellation receipt number and file are required', code='SHIPPING.FREIGHT_CANCELLATION_RECEIPT_REQUIRED')
confirmation_note = str(note or '').strip()
if not confirmation_note:
raise ValidationError('External cancellation confirmation note is required', code='SHIPPING.FREIGHT_CANCELLATION_CONFIRMATION_REQUIRED')
old = ShippingNotice.query.filter_by(id=row.old_task_id).with_for_update().one()
new = ShippingNotice.query.filter_by(id=row.new_task_id).with_for_update().one()
if new.supersedes_task_id != old.id:
@@ -56,9 +52,9 @@ def complete_freight_cancellation(
row.status = 'cancelled'
row.completed_by_id = int(actor_id)
row.completed_at = datetime.utcnow()
row.freight_receipt_no = receipt
row.receipt_asset_id = int(receipt_asset_id)
row.failure_reason = str(note or '').strip() or None
row.freight_receipt_no = None
row.receipt_asset_id = None
row.failure_reason = confirmation_note
old.lifecycle_status = 'voided'
old.voided_at = datetime.utcnow()
old.voided_by_id = int(actor_id)
@@ -72,7 +68,7 @@ def complete_freight_cancellation(
actor_id=actor_id,
detail_json={
'cancellation_id': row.id,
'receipt_no': receipt,
'confirmation_note': confirmation_note,
'new_task_no': new.task_no,
'reason_code': 'task_voided_for_correction',
},
@@ -83,7 +79,7 @@ def complete_freight_cancellation(
actor_id=actor_id,
detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no},
))
# 统一审计:货代回执登记必须可按 reason_code 检索
# 统一审计:外部撤销确认必须可按 reason_code 检索。
record_fulfillment_audit(
event_type='freight_cancellation_completed',
aggregate_type='shipping_task',
@@ -97,13 +93,13 @@ def complete_freight_cancellation(
before={'lifecycle_status': 'active'},
after={
'lifecycle_status': 'voided',
'freight_receipt_no': receipt,
'external_cancellation_confirmed': True,
'new_task_no': new.task_no,
'cancellation_id': int(row.id),
},
metadata={
'cancellation_id': int(row.id),
'receipt_asset_id': int(receipt_asset_id),
'confirmation_note': confirmation_note,
'new_task_no': str(new.task_no),
},
source='workspace_api',
@@ -7,12 +7,12 @@ services/shipping_notice/fulfillment_workflow.py
tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、
order_task_stage_machine。
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match;
STP 多候选:跨文件匹配后仅全部 ok 记 completed+100% 并自动 Excel;partial/冲突记 needs_human;
STP 多候选:跨文件匹配后仅全部 ok 记 completed+100%;partial 仍可按滚动库存生成已满足行 Excel;
AUTO_UPLOAD 默认 false(须环境显式 true;缺失键 fail-closed 并告警);
开启时 Excel 后先做货代 RPA 就绪校验再触发(stage=upload_rpa_pending);关闭时停于人工上传;
工作台操作人经 operator_id / actor_id / _trusted_user_id 写入匹配与审计事件;
upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工凭据);
RPA 成功须带白名单 kind + page_url + dom_snippet/dom_sha256,并尽量落 evidence_asset;
upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工确认);
RPA 成功须带受信回调中的白名单状态信息;不保存截图、DOM 文件或证据资产;
Excel 生成成功写路径清除 invalidated_from_stage(BE-02,禁止投影 GET 清库)。
"""
@@ -124,10 +124,10 @@ def _normalize_rpa_success_evidence(
expected_filename: str | None = None,
) -> dict[str, Any] | None:
"""
校验 RPA 成功回调中的 success_evidence(BE-05 fail-closed)。
校验 RPA 成功回调中的受信状态摘要(fail-closed)。
核心逻辑:kind 须在白名单;selector / observed_at / filename / page_url 必填;
必须带 dom_snippet + 匹配的 dom_sha256(不可变 DOM 证据);
必须带经 Worker 校验过的 selector、观察时间、文件名和页面定位;
若提供 expected_filename 则须与证据文件名一致(大小写不敏感)。
Args:
@@ -137,8 +137,6 @@ def _normalize_rpa_success_evidence(
Returns:
规范化 evidence dict;缺失/非法时 None。
"""
import hashlib
raw = payload.get('success_evidence')
if not isinstance(raw, dict):
return None
@@ -155,16 +153,13 @@ def _normalize_rpa_success_evidence(
return None
if not dom_snippet or not dom_sha256:
return None
# [BE-05] 片段与哈希必须自洽,防止 Worker 自报成功却无对应 DOM。
computed = hashlib.sha256(dom_snippet.encode('utf-8')).hexdigest().lower()
if computed != dom_sha256:
import hashlib
if hashlib.sha256(dom_snippet.encode('utf-8')).hexdigest().lower() != dom_sha256:
return None
if expected_filename:
expected = str(expected_filename).strip()
if expected and filename.lower() != expected.lower():
return None
screenshot_sha256 = str(raw.get('screenshot_sha256') or '').strip().lower() or None
screenshot_base64 = str(raw.get('screenshot_base64') or '').strip() or None
return {
'kind': kind,
'selector': selector,
@@ -174,42 +169,22 @@ def _normalize_rpa_success_evidence(
'page_url': page_url,
'dom_snippet': dom_snippet[:8000],
'dom_sha256': dom_sha256,
'screenshot_sha256': screenshot_sha256,
'screenshot_base64': screenshot_base64,
'screenshot_sha256': str(raw.get('screenshot_sha256') or '').strip().lower() or None,
'screenshot_base64': str(raw.get('screenshot_base64') or '').strip() or None,
}
def _persist_rpa_success_evidence_asset(
*,
task: 'ShippingNotice',
attempt: Any,
success_evidence: dict[str, Any],
) -> int | None:
"""
将 RPA 成功 DOM/截图落为 FileAsset,并回写 attempt.evidence_asset_id。
核心逻辑:优先截图 PNG;否则将脱敏 DOM 片段存为 .html;绑定后从 JSON 去掉 base64 大字段。
Args:
task: 发货 Notice。
attempt: ShippingUploadAttempt。
success_evidence: 已规范化证据(可含 screenshot_base64)。
Returns:
FileAsset.id;落库失败时 None(证据仍留在 success_evidence_json)。
"""
def _persist_rpa_success_evidence_asset(*, task: 'ShippingNotice', attempt: Any, success_evidence: dict[str, Any]) -> int | None:
"""将受信 RPA 的 DOM/可选截图保存为内部审计资产;人工上传路径不调用本函数。"""
import base64
import hashlib
from app.models import FileAsset
from app.services.file_assets.service import generate_asset_no, _build_storage_key
from app.services.file_assets.service import generate_asset_no, _build_storage_key, mark_asset_referenced
from app.services.file_assets.storage import file_asset_storage
from app.services.file_assets.service import mark_asset_referenced
if not getattr(task, 'user_id', None):
success_evidence.pop('screenshot_base64', None)
return None
raw_b64 = str(success_evidence.pop('screenshot_base64', None) or '').strip()
data: bytes | None = None
filename = f"rpa-success-{int(attempt.id)}.html"
@@ -220,41 +195,22 @@ def _persist_rpa_success_evidence_asset(
except Exception:
data = None
if data:
filename = f"rpa-success-{int(attempt.id)}.png"
mime_type = 'image/png'
filename, mime_type = f"rpa-success-{int(attempt.id)}.png", 'image/png'
if not data:
snippet = str(success_evidence.get('dom_snippet') or '').encode('utf-8')
if not snippet:
return None
data = snippet
data = str(success_evidence.get('dom_snippet') or '').encode('utf-8') or None
if not data:
return None
content_hash = hashlib.sha256(data).hexdigest().lower()
expected_shot = str(success_evidence.get('screenshot_sha256') or '').strip().lower()
if expected_shot and filename.endswith('.png') and expected_shot != content_hash:
return None
asset_no = generate_asset_no()
storage_key = _build_storage_key(
user_id=int(task.user_id),
asset_no=asset_no,
filename=filename,
)
asset = FileAsset(
asset_no=asset_no,
owner_user_id=int(task.user_id),
original_filename=filename,
parent_asset_id=None,
asset_role='rpa_success_evidence',
source_attachment_key=f'rpa-success:{int(attempt.id)}',
storage_provider='minio',
storage_bucket=file_asset_storage.bucket_name,
storage_key=storage_key,
content_hash=content_hash,
file_size=len(data),
mime_type=mime_type,
extension=filename.rsplit('.', 1)[-1],
upload_status='uploading',
lifecycle_status='temporary',
reference_count=0,
)
storage_key = _build_storage_key(user_id=int(task.user_id), asset_no=asset_no, filename=filename)
asset = FileAsset(asset_no=asset_no, owner_user_id=int(task.user_id), original_filename=filename,
parent_asset_id=None, asset_role='rpa_success_evidence', source_attachment_key=f'rpa-success:{int(attempt.id)}',
storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key,
content_hash=content_hash, file_size=len(data), mime_type=mime_type, extension=filename.rsplit('.', 1)[-1],
upload_status='uploading', lifecycle_status='temporary', reference_count=0)
db.session.add(asset)
db.session.flush()
try:
@@ -271,7 +227,6 @@ def _persist_rpa_success_evidence_asset(
return int(asset.id)
def _hash_rpa_evidence_field(value: str | None) -> str | None:
"""对 evidence 中的 filename/reference 做 sha256,审计禁止落原文。"""
if not value:
@@ -628,9 +583,9 @@ def _sync_workflow_stage(
def match_completed(task: ShippingNotice) -> bool:
"""
STP 制单门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时允许生成 Excel。
STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。
核心逻辑:禁止 partial / 任意一行短缺、冲突、未命中进入自动制单或 Excel 门禁。
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
"""
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewLineDecision
@@ -663,6 +618,52 @@ def match_completed(task: ShippingNotice) -> bool:
return True
def _released_snapshot_line_ids_for_export(task: ShippingNotice) -> set[int]:
"""读取当前任务已审计的短缺放行行,供滚动 Excel 资格筛选使用。"""
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ShippingOrderSnapshot
from app.services.shipping_notice.export import _source_notice_for_order_facts
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
if snapshot is None or source_notice.id is None:
return set()
decisions = (
ShippingOrderReviewLineDecision.query
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
.filter(
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
ShippingOrderReviewLineDecision.is_active.is_(True),
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
)
.all()
)
released_indexes = {
int(decision.line_index)
for decision in decisions
if decision.line_index is not None
}
return {
int(line.id)
for index, line in enumerate(snapshot.lines)
if index in released_indexes
}
def exportable_snapshot_line_ids(task: ShippingNotice) -> set[int]:
"""返回当前库存轮次可先行导出的冻结订单行;不代表整单已满足。"""
from app.services.shipping_notice.export import _source_notice_for_order_facts
from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids
try:
_verification, line_ids = current_available_snapshot_line_ids(
_source_notice_for_order_facts(task),
released_snapshot_line_ids=_released_snapshot_line_ids_for_export(task),
)
except ConflictError:
return set()
return set(line_ids)
def _match_step_progress_fields(
*,
match_status: str,
@@ -708,7 +709,8 @@ def excel_gate_error(task: ShippingNotice) -> str | None:
"""校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。"""
if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"} and task.export_file_path:
return None
if not match_completed(task):
# 滚动履约允许先导出当前完整满足/已审计放行的行;剩余短缺行继续保留在库存满足性 Gate。
if not match_completed(task) and not exportable_snapshot_line_ids(task):
return "workflow.fulfillment.excel_gate_unmatched"
return None
@@ -757,10 +759,10 @@ def try_auto_chain_after_match(
tool_payload = merge_tool_payload(task, payload)
# [STEP 1] 低风险:匹配成功后自动生成 Excel。
# [STEP 1] 低风险:存在可导出行时自动生成下一份滚动 Excel。
if _auto_generate_excel_enabled():
db.session.refresh(task)
if not task.export_file_path and match_completed(task):
if not task.export_file_path and excel_gate_error(task) is None:
gen = generate_excel(tool_payload)
if gen.get("status") != "ok":
return gen
@@ -904,6 +906,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str,
disposition_gate = _task_disposition_gate_response(task)
if disposition_gate is not None:
return disposition_gate
customer_gate = customer_gate_tool_response(task, operation='match_inventory_line')
if customer_gate is not None:
return customer_gate
@@ -1680,7 +1683,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
基于已匹配任务生成货代发货 Excel 并推进至 waiting_upload。
【AI 触发时机】:本轮至少一个预约单完整满足且用户确认制单时调用;未匹配前禁止调用。
核心逻辑:已有导出文件时直接返回成功;否则走 excel_gate_error 门禁 → generate_shipment_excel → 写 export_file_path → WAITING_UPLOAD。
核心逻辑:已有导出文件时直接返回成功;否则按当前可导出行通过 excel_gate_error,生成滚动 Excel;未满足行保留在库存满足性 Gate。
Args:
payload: 须含 task_id 或 conversation_id。
@@ -1766,7 +1769,11 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids
try:
_verification, available_line_ids = current_available_snapshot_line_ids(task)
from app.services.shipping_notice.export import _source_notice_for_order_facts
_verification, available_line_ids = current_available_snapshot_line_ids(
_source_notice_for_order_facts(task),
)
except ConflictError:
available_line_ids = set()
if not available_line_ids:
@@ -1780,7 +1787,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
)
# [STEP 2] 先校验是否满足导出门禁。
# 只有库存匹配完成后才允许生成货代 Excel;但 waiting_upload/uploaded 仍应视为“已完成匹配”。
# 只要当前库存轮次存在可导出行即可生成滚动 Excel;未满足行继续停留在库存满足性 Gate。
gate_error = excel_gate_error(task)
if gate_error:
return tool_response(
@@ -1894,22 +1901,25 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
status="ok",
task_id=task.task_no,
message=t("workflow.fulfillment.generate_done", lang=lang).format(file=filename),
data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"},
data={
**serialize_task_for_tool(task),
"download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export",
},
)
def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
"""
货代上传入口:RPA 自动/重试,或人工凭据登记。
货代上传入口:RPA 自动/重试,或人工确认唯一 Excel 已上传。
【AI 触发时机】:AUTO_UPLOAD 开启且 Excel 就绪时可由 auto_progress 以 mode=auto 调用;
人工接管后使用 mode=manual_confirm。
人工接管后使用 mode=manual_confirm;工作台对外必须先按 business_no 定位 Notice。
核心逻辑:mode=auto|retry_upload → 触发 RPA(受 AUTO_UPLOAD 与重试上限约束);
mode=manual_confirm → 校验凭据后标记 UPLOADED 并关闭 WorkflowItem。
mode=manual_confirm → 校验唯一 Artifact 后标记 UPLOADED 并关闭 WorkflowItem。
Args:
payload: 须含 task_id;mode=auto|retry_upload|manual_confirm;
manual_confirm 须含 evidence_asset_no、operator_id。
payload: 内部须含 task_id;mode=auto|retry_upload|manual_confirm;
manual_confirm 须含服务端可信 operator_id,不接收回执或截图/PDF。
Returns:
dict[str, Any]: status 可为 ok / running / needs_human / failed。
@@ -1973,11 +1983,11 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(
status='failed',
task=task,
message='货代自动上传未开启,请人工下载 Excel 并登记上传凭据。',
message='货代自动上传未开启,请人工下载 Excel 并确认已上传。',
data=serialize_task_for_tool(task),
forbidden_next_tools=['upload_to_freight'],
stop_agent_turn=True,
next_required_action='请在任务处理工作台使用「登记人工上传」。',
next_required_action='请在任务处理工作台使用「确认已上传」。',
)
return _trigger_freight_upload_rpa(
task,
@@ -1995,16 +2005,12 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
)
operator_id = payload.get('operator_id')
evidence_asset_no = str(payload.get('evidence_asset_no') or '')
freight_ref_no = str(payload.get('freight_ref_no') or '')
before_upload_status = str(task.upload_status or '')
try:
attempt = record_manual_upload(
task,
artifact_id=artifact_id,
evidence_asset_no=evidence_asset_no,
operator_id=int(operator_id),
freight_ref_no=freight_ref_no,
)
except (ConflictError, ValidationError, TypeError, ValueError) as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
@@ -2032,8 +2038,6 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
metadata={
'attempt_id': attempt.id,
'artifact_id': attempt.artifact_id,
'evidence_asset_no': evidence_asset_no,
'freight_ref_no': freight_ref_no or None,
},
source='workspace_api',
sensitivity_level='sensitive',
@@ -2072,7 +2076,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
说明:本期主流程不触发货代 RPA 上传;本回调仅保留兼容,不应由业务主动调用。
核心逻辑:success=True → UPLOADED + freight_ref_no;失败 → UPLOAD_FAILED,达最大重试转人工。
缺省或非法 success **fail-closed 为失败**;success=True 必须带 success_evidence.kind。
缺省或非法 success **fail-closed 为失败**;success=True 必须带受信状态摘要。
Args:
payload: 须含 task_id;success(bool,缺省视为失败);success_evidence(成功必填);
@@ -2123,37 +2127,14 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
task=task,
message=(
'RPA upload success requires success_evidence '
'(kind whitelist, selector, observed_at, filename matching artifact, '
'page_url, dom_snippet+dom_sha256)'
'(kind whitelist, selector, observed_at, filename matching artifact and page_url)'
),
data=serialize_task_for_tool(task),
)
# [BE-05] 结构化证据必须落 FileAsset;资产失败不得判定上传成功。
evidence_asset_id = _persist_rpa_success_evidence_asset(
task=task,
attempt=attempt,
success_evidence=success_evidence,
)
if evidence_asset_id is None:
return tool_response(
status='failed',
task=task,
message=(
'RPA upload success requires persisted evidence asset '
'(DOM/screenshot FileAsset); status remains recoverable'
),
data={
**serialize_task_for_tool(task),
'upload_evidence_persist_failed': True,
},
)
if _persist_rpa_success_evidence_asset(task=task, attempt=attempt, success_evidence=success_evidence) is None:
return tool_response(status='failed', task=task, message='RPA upload success requires persisted internal audit asset', data=serialize_task_for_tool(task))
if hasattr(attempt, 'success_evidence_json'):
# 回调体中的 base64 已在 persist 时 pop;落库保留 snippet/哈希/asset 引用。
attempt.success_evidence_json = {
key: value
for key, value in dict(success_evidence).items()
if key != 'screenshot_base64'
}
attempt.success_evidence_json = {key: value for key, value in dict(success_evidence).items() if key != 'screenshot_base64'}
try:
completed = complete_attempt(
attempt, success=success, callback_id=str(payload.get('callback_id') or f'rpa:{attempt.id}'),
@@ -26,6 +26,9 @@ from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
create_post_ot_fulfillment_wave,
list_eligible_post_ot_line_keys,
)
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
project_review_case_line_decisions,
)
from app.services.shipping_notice.post_ot_wave_progress_service import schedule_post_ot_wave_progress
@@ -114,6 +117,12 @@ def coordinate_post_ot_auto_fulfill(
}
eligible = list_eligible_post_ot_line_keys(case)
projection = project_review_case_line_decisions(case)
unassigned = [
str(item.get('line_key') or '')
for item in list(projection.get('lines') or [])
if str(item.get('line_status') or '') not in {'task_created', 'fulfilled', 'closed_unfulfillable'}
]
if not eligible:
return {
'status': 'idle',
@@ -122,6 +131,16 @@ def coordinate_post_ot_auto_fulfill(
'case_no': case.case_no,
'accepted_line_keys': [],
}
# [STEP] 自动制单只处理唯一开放明细。多条明细必须由用户勾选后合并,
# 绝不静默替用户决定 Notice 的合并范围。
if len(eligible) != 1 or set(eligible) != set(unassigned):
return {
'status': 'idle',
'reason': 'manual_wave_selection_required',
'trigger': trigger,
'case_no': case.case_no,
'accepted_line_keys': [],
}
idem_key = f'auto-fulfill:{case.case_no}:{trigger}:{",".join(sorted(eligible))}'
try:
@@ -14,13 +14,19 @@ from app import db
from app.models import ShippingNoticeLine, ShippingOrderSnapshot
def replace_notice_lines_from_snapshot(*, notice_id: int, snapshot: ShippingOrderSnapshot) -> int:
def replace_notice_lines_from_snapshot(
*,
notice_id: int,
snapshot: ShippingOrderSnapshot,
snapshot_line_ids: set[int] | None = None,
) -> int:
"""
用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。
Args:
notice_id: shipping_notices.id。
snapshot: 已 flush 且带 lines 的 Snapshot。
snapshot_line_ids: 仅写入本次发货通知选中的冻结行;为空时兼容整单冻结。
Returns:
写入行数。
@@ -28,7 +34,10 @@ def replace_notice_lines_from_snapshot(*, notice_id: int, snapshot: ShippingOrde
db.session.query(ShippingNoticeLine).filter_by(notice_id=int(notice_id)).delete(synchronize_session=False)
now = datetime.utcnow()
rows: list[ShippingNoticeLine] = []
selected_ids = {int(item) for item in (snapshot_line_ids or set())}
for line in list(snapshot.lines or []):
if selected_ids and int(line.id) not in selected_ids:
continue
rows.append(
ShippingNoticeLine(
notice_id=int(notice_id),
@@ -39,6 +39,8 @@ def _initial_coordinate_definition(main_table_id: str) -> dict[str, Any]:
"""生成未标注但合法的坐标草稿起点;编辑器后续才添加锚点、表头和行布局。"""
region_suffix = re.sub(r'[^a-z0-9_]+', '_', main_table_id.lower()).strip('_') or 'table'
return {
# 视觉主表身份必须随共同定义冻结;annotation/training 只保存该身份的样本绑定。
'main_table_id': str(main_table_id).strip(),
'document_match': {
'document_type': 'purchase_order', 'page_pattern': 'one_or_more',
'required_anchors': [], 'optional_anchors': [], 'minimum_score': 0, 'minimum_margin': 0,
@@ -550,6 +550,38 @@ def _fuse_header_regions_with_column_geometry(
})
if fused_headers:
result['header_regions'] = [*(result.get('header_regions') or []), *fused_headers]
# Widget 仅按“表格内有值控件”聚类,动态 XFA 的表头控件也可能带展示值。
# 表头文字已通过独立坐标证据确认时,与该表头带实质重叠的 Widget 行不能再
# 作为明细行候选,否则画布会同时保存 header_field 与 field。
def _overlaps_fused_header(layout: Any) -> bool:
if not isinstance(layout, dict) or not isinstance(layout.get('region'), dict):
return False
try:
lx0, ly0, lx1, ly1 = (float(layout['region'][key]) for key in ('x0', 'y0', 'x1', 'y1'))
except (KeyError, TypeError, ValueError):
return False
layout_width, layout_height = lx1 - lx0, ly1 - ly0
if layout_width <= 0 or layout_height <= 0:
return False
for header in fused_headers:
region = header.get('region') if isinstance(header, dict) else None
if not isinstance(region, dict):
continue
try:
hx0, hy0, hx1, hy1 = (float(region[key]) for key in ('x0', 'y0', 'x1', 'y1'))
except (KeyError, TypeError, ValueError):
continue
header_width, header_height = hx1 - hx0, hy1 - hy0
horizontal_overlap = max(0.0, min(lx1, hx1) - max(lx0, hx0))
vertical_overlap = max(0.0, min(ly1, hy1) - max(ly0, hy0))
if header_width > 0 and header_height > 0 and \
horizontal_overlap / min(layout_width, header_width) >= 0.8 and \
vertical_overlap / min(layout_height, header_height) >= 0.8:
return True
return False
result['subrow_layouts'] = [
layout for layout in layouts if not _overlaps_fused_header(layout)
]
return result
@@ -632,6 +664,41 @@ def _field_binding_source_conflicts(candidates: list[dict[str, Any]]) -> list[di
return conflicts
def _merge_duplicate_field_binding_candidates(candidates: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""合并同字段同页同坐标的多来源候选,保留全部证据来源。"""
merged: dict[tuple[str, str, str, int, tuple[float, float, float, float]], dict[str, Any]] = {}
order: list[tuple[str, str, str, int, tuple[float, float, float, float]]] = []
unkeyed_candidates: list[dict[str, Any]] = []
for candidate in candidates:
binding = candidate.get('binding') if isinstance(candidate, dict) else None
visual = binding.get('visual_binding') if isinstance(binding, dict) else None
bbox = visual.get('normalized_bbox') if isinstance(visual, dict) else None
if not isinstance(binding, dict) or not isinstance(visual, dict) or not isinstance(bbox, dict):
# 缺少完整坐标的候选无法安全判定为重复,但仍是待人工复核的视觉证据。
unkeyed_candidates.append(candidate)
continue
try:
geometry = tuple(round(float(bbox[key]), 6) for key in ('x0', 'y0', 'x1', 'y1'))
page_no = int(visual.get('page_no') or 1)
except (KeyError, TypeError, ValueError):
unkeyed_candidates.append(candidate)
continue
key = (
str(binding.get('field_id') or ''), str(binding.get('field_code') or ''),
str(binding.get('scope') or ''), page_no, geometry,
)
existing = merged.get(key)
if existing is None:
merged[key] = candidate
order.append(key)
continue
existing['evidence_sources'] = list(dict.fromkeys([
*(existing.get('evidence_sources') or []), *(candidate.get('evidence_sources') or []),
]))
existing['needs_review'] = bool(existing.get('needs_review') or candidate.get('needs_review'))
return [*unkeyed_candidates, *(merged[key] for key in order)]
def _execute_visual_automark(
*, payload: dict[str, Any], profile_id: int, document_id: int, table_id: str,
) -> dict[str, Any]:
@@ -873,8 +940,9 @@ def _execute_visual_automark(
table_candidates.append(_table_reconstruction_candidate(
source='opencv_geometry', reconstruction=opencv_reconstruction,
))
candidates = table_candidates + field_candidates + widget_candidates
field_conflicts = _field_binding_source_conflicts(field_candidates + widget_candidates)
field_candidates = _merge_duplicate_field_binding_candidates(field_candidates + widget_candidates)
candidates = table_candidates + field_candidates
field_conflicts = _field_binding_source_conflicts(field_candidates)
conflicts: list[dict[str, Any]] = []
reconstructions_by_source = {
'pdf_coordinate': native_reconstruction,
@@ -31,6 +31,7 @@ from app.services.shipping_notice.document_layout.coordinate_region_text import
from app.services.shipping_notice.preview_grant_store import preview_grant_store
from app.services.shipping_notice import order_document_profile_service as profile_service
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
from app.services.shipping_notice.reservation_region import extract_reservation_from_region_text
PREVIEW_GRANT_TTL_SECONDS = 120
@@ -7,7 +7,7 @@ services/shipping_notice/order_document_profile_publish_check_service.py
逻辑:报告冻结当前草稿身份与签名/重叠引用;XFA 模式使用结构签名、路径/集合/对账阻断,
以及字段级混合数据源可发布性与跨源 OCR mismatch 清零;
不再要求 flatten/synthetic ready / renderer_version / preview checksum;
消费时在同一事务再次校验并发布,草稿或签名变化只能令报告失效;编辑人不得批准自己的 Revision。
消费时在同一事务再次校验并发布,草稿或签名变化只能令报告失效;管理员可确认发布自己的草稿。
"""
from __future__ import annotations
@@ -15,11 +15,10 @@ import secrets
from datetime import datetime
from typing import Any
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db
from app.models import (
ShippingOrderDocumentProfile,
ShippingOrderDocumentProfileAudit,
ShippingOrderDocumentProfileDraftRevision,
ShippingOrderDocumentProfileEditLease,
ShippingOrderDocumentProfilePublishCheckReport,
@@ -121,40 +120,6 @@ def _signature_status(profile: ShippingOrderDocumentProfile, revision: ShippingO
return payload
def _find_last_profile_editor_id(profile_id: int) -> int | None:
"""
查找最近一次编辑 Profile 映射/拆分规则的管理员 ID。
核心逻辑:优先审计映射事件;回退至最新 DraftRevision.created_by_id。
"""
editor_events = (
'draft_saved',
'xfa_mapping_saved',
'xfa_split_rule_suggested',
'xfa_segment_mapping_updated',
)
audit = (
db.session.query(ShippingOrderDocumentProfileAudit)
.filter(
ShippingOrderDocumentProfileAudit.profile_id == int(profile_id),
ShippingOrderDocumentProfileAudit.event_type.in_(editor_events),
)
.order_by(ShippingOrderDocumentProfileAudit.id.desc())
.first()
)
if audit is not None and audit.actor_id is not None:
return int(audit.actor_id)
revision = (
db.session.query(ShippingOrderDocumentProfileDraftRevision)
.filter_by(profile_id=int(profile_id))
.order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc())
.first()
)
if revision is not None and revision.created_by_id is not None:
return int(revision.created_by_id)
return None
def _overlap_summary_from_run(
run: ShippingOrderDocumentProfileValidationRun | None,
) -> dict[str, Any] | None:
@@ -374,6 +339,7 @@ def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None
and candidate.run_type == 'layout_signature'
and candidate.status == 'passed'
and candidate.definition_checksum == revision.definition_checksum
and validation_service._signature_uses_current_evidence_contract(candidate)
):
signature_run = candidate
if signature_run is None:
@@ -491,14 +457,6 @@ def consume_report(profile_id: int, report_no: str, *, data: dict[str, Any], act
raise ConflictError('Publish check report is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID')
if row.blocking_items_json:
raise ValidationError('Publish check has blocking items', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID')
if actor_id is not None:
editor_id = _find_last_profile_editor_id(profile.id)
if editor_id is not None and int(editor_id) == int(actor_id):
raise ValidationError(
'Editor cannot approve own version',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID',
details={'key': 'editor_cannot_approve_own_version'},
)
confirmed = {str(item) for item in data.get('confirmed_warning_keys') or []}
required = {str(item.get('key')) for item in row.warning_items_json or []}
if confirmed != required:
@@ -9,6 +9,7 @@ backend/app/services/shipping_notice/order_document_profile_service.py
from __future__ import annotations
import base64
import hashlib
import io
import json
@@ -39,8 +40,11 @@ from app.models import (
)
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
coordinate_profile_character_candidates,
derive_incomplete_table_bbox,
reconstruct_coordinate_profile_rows,
reconstruct_coordinate_profile_rows_with_strategy,
reconstruction_exclusion_regions,
suggest_header_layouts,
suggest_header_regions,
suggest_multi_subrow_layouts,
@@ -71,6 +75,7 @@ from app.services.shipping_notice.order_profile_value_adapter import (
OrderProfileValueAdapter,
get_value_adapter,
)
from app.services.shipping_notice.reservation_region import extract_reservation_from_region_text
PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
@@ -423,6 +428,42 @@ def _normalize_definition(
)
profile_fields = _schema_profile_fields(schema_version)
reservation_region = raw.get('reservation_id_region')
if reservation_region is not None:
if not isinstance(reservation_region, dict):
raise ValidationError(
'reservation_id_region must be an object',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID',
)
reservation_fields = {
scope: field for (scope, code), field in profile_fields.items()
if code == 'reservation_id'
}
# 一个区域可以同时承载整单 Reservation 和指定明细行 Reservation:
# Header 是无行号值的权威落点;Line 字段启用后才消费带行号的值。
if 'header' not in reservation_fields:
raise ValidationError(
'Schema must enable header reservation_id for unnumbered Reservation values',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID',
details={'scopes': sorted(reservation_fields), 'required_scope': 'header'},
)
region = reservation_region.get('region')
page_no = reservation_region.get('page_no')
if not isinstance(region, dict) or page_no is None:
raise ValidationError(
'reservation_id_region requires region and page_no',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID',
)
try:
from app.services.shipping_notice.document_layout.order_profile import RelativeRegion
RelativeRegion.model_validate(region)
if int(page_no) < 1:
raise ValueError('page_no must be positive')
except (TypeError, ValueError) as exc:
raise ValidationError(
'reservation_id_region geometry is invalid',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID',
) from exc
if raw.get('header_mappings') is not None or raw.get('source_contract') is not None or raw.get('line_mapping') is not None:
raise ValidationError(
'Coordinate definition must not mix value-source mapping keys',
@@ -439,6 +480,8 @@ def _normalize_definition(
'table_regions': raw.get('table_regions'),
'order_field_layouts': raw.get('order_field_layouts') or [],
'draft_unbound_order_field_layouts': raw.get('draft_unbound_order_field_layouts') or [],
'coordinate_model': raw.get('coordinate_model') or {},
'reference_page_frames': raw.get('reference_page_frames') or {},
}
for table_region in normalized['table_regions'] or []:
if not isinstance(table_region, dict):
@@ -502,6 +545,13 @@ def _normalize_definition(
}
for target in sorted(outputs)
]
# Legacy Vendor Comments mappings are intentionally rejected at the API
# boundary; the only supported special evidence is reservation_id_region.
if raw.get('named_regions') is not None or raw.get('field_source_mappings') is not None:
raise ValidationError(
'Legacy Vendor Comments mappings are no longer supported; use reservation_id_region',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEGACY_VENDOR_COMMENTS_UNSUPPORTED',
)
for order_field in normalized['order_field_layouts']:
if not isinstance(order_field, dict):
continue
@@ -511,6 +561,24 @@ def _normalize_definition(
field = profile_fields.get(('header', code))
if field is None:
raise ValidationError('Order field binding must target a header Schema field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
# [STEP] Address layouts saved by the affected workbench version could inherit
# the first page anchor (Number). Reject that proven bad binding at the API
# boundary so stale browsers or direct requests cannot persist it again.
anchor = order_field.get('anchor')
anchor_text = (
str(anchor.get('text') or '').strip().casefold()
if isinstance(anchor, dict) else ''
)
if code in {'ship_to_address', 'bill_to_address'} and anchor_text == 'number':
raise ValidationError(
'Address field cannot bind to the Number anchor',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
details={
'reason': 'order_field_anchor_semantic_mismatch',
'field_code': code,
'anchor_text': str(anchor.get('text') or '').strip(),
},
)
order_field['field_id'] = str(field['field_id'])
order_field['scope'] = 'header'
normalizer = order_field.get('normalizer_key')
@@ -551,6 +619,8 @@ def _normalize_definition(
table_regions=normalized['table_regions'],
order_field_layouts=normalized['order_field_layouts'],
draft_unbound_order_field_layouts=normalized['draft_unbound_order_field_layouts'],
coordinate_model=normalized['coordinate_model'],
reference_page_frames=normalized['reference_page_frames'],
)
except (TypeError, ValueError) as exc:
# Pydantic locations only describe the submitted contract, so exposing the
@@ -577,11 +647,24 @@ def _normalize_definition(
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
) from exc
result = {
# 不能在坐标定义规范化时丢弃创建向导冻结的视觉主表身份。
'main_table_id': str(raw.get('main_table_id') or '').strip() or None,
'document_match': contract.document_match.model_dump(),
'table_regions': [item.model_dump() for item in contract.table_regions],
'order_field_layouts': [item.model_dump() for item in contract.order_field_layouts],
'draft_unbound_order_field_layouts': [item.model_dump() for item in contract.draft_unbound_order_field_layouts],
'coordinate_model': contract.coordinate_model.model_dump(),
'reference_page_frames': {
str(page_no): frame.model_dump()
for page_no, frame in contract.reference_page_frames.items()
},
}
if reservation_region is not None:
result['reservation_id_region'] = {
'region': dict(reservation_region['region']),
'page_scope': 'exact_page',
'page_no': int(reservation_region['page_no']),
}
if unified_bindings:
result['bindings'] = unified_bindings
result['template_mode'] = 'coordinate'
@@ -661,6 +744,8 @@ def _normalize_visual_definition_for_preview(
'table_regions': table_regions,
'order_field_layouts': order_field_layouts,
'draft_unbound_order_field_layouts': draft_unbound_order_field_layouts,
'coordinate_model': raw.get('coordinate_model') or {},
'reference_page_frames': raw.get('reference_page_frames') or {},
}
return _normalize_definition(visual, schema_version=schema_version, preferred_template_mode='coordinate')
@@ -675,6 +760,8 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordina
table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [],
coordinate_model=definition.get('coordinate_model') or {},
reference_page_frames=definition.get('reference_page_frames') or {},
)
@@ -1005,11 +1092,42 @@ def read_preview_page_region_text(
source = 'acroform_widget'
elif len(matched_widgets) > 1:
source = 'acroform_widget_ambiguous'
if not text:
text = _read_rendered_preview_crop_text(data.get('rendered_image_base64'))
if text:
source = 'xfa_rendered_ocr'
_audit(profile_id=int(profile_id), document_id=document.id, event_type='preview_region_text_read', actor_id=actor_id, detail={
'page_no': int(page_no), 'character_count': len(text), 'source': source,
})
db.session.commit()
return {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'}
result = {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'}
if data.get('purpose') == 'reservation_id_region':
result['reservation_candidates'] = extract_reservation_from_region_text(text)
return result
def _read_rendered_preview_crop_text(rendered_image_base64: Any) -> str:
"""读取浏览器 PDF.js XFA 画布的受控裁剪图文字,仅用于视觉标注回读。"""
raw = str(rendered_image_base64 or '')
prefix = 'data:image/png;base64,'
if not raw.startswith(prefix):
return ''
try:
payload = base64.b64decode(raw[len(prefix):], validate=True)
if not payload or len(payload) > 2 * 1024 * 1024:
return ''
import numpy as np
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
image = Image.open(io.BytesIO(payload)).convert('RGB')
pixels = np.asarray(image)
height, width = pixels.shape[:2]
if width < 8 or height < 8 or width * height > 4_000_000:
return ''
lines = extract_ocr_lines(pixels, page_width=float(width), page_height=float(height))
return ' '.join(str(item.text).strip() for item in lines if str(item.text).strip()).strip()
except Exception:
return ''
def preview_profile_region(
@@ -1033,6 +1151,8 @@ def preview_profile_region(
profile_code=profile.profile_code, version=profile.version,
document_match=definition['document_match'], table_regions=definition['table_regions'],
order_field_layouts=definition['order_field_layouts'],
coordinate_model=definition['coordinate_model'],
reference_page_frames=definition['reference_page_frames'],
)
table_id = str(data.get('table_id') or '').strip()
if not table_id:
@@ -1085,6 +1205,10 @@ def preview_profile_region(
except (KeyError, TypeError, ValueError) as exc:
raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
strict = bool(data.get('strict'))
schema_field_metadata = [
item for item in (profile.schema_version.definition_json or {}).get('fields') or []
if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'line'
]
rows = []
involved_field_codes: list[str] = []
seen_field_codes: set[str] = set()
@@ -1098,11 +1222,21 @@ def preview_profile_region(
# Header-only pages document column semantics but must never emit data rows.
if not table_region.line_layouts:
continue
# Adaptive regions explicitly require page evidence because a detected
# table bbox may contain headers only when MinerU misses detail rows.
region_characters = characters
if table_region.row_reconstruction_mode == 'adaptive_record_columns':
region_characters = (evidence.get('page_glyphs') or {}).get(str(raw_table.get('page_no') or 1))
# 表头区域只描述列语义与预览,运行时不得删除其覆盖的 glyph;起行 Schema
# 交叉校验会拒绝表头,普通 exclusion_regions 才是显式删除授权。
reconstruction_exclusions = reconstruction_exclusion_regions(table_region.model_dump())
reference_page_frame = contract.reference_page_frames.get(int(raw_table.get('page_no') or 1))
region_characters, _candidate_page_bbox = coordinate_profile_character_candidates(
table_region=table_region.region.model_dump(), page_size=page,
reference_page_frame=(
reference_page_frame.model_dump() if reference_page_frame is not None else None
),
page_characters=(evidence.get('page_glyphs') or {}).get(str(raw_table.get('page_no') or 1)),
table_characters=characters,
raw_table_bbox=raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None,
table_id=table_id, page_no=int(raw_table.get('page_no') or 1),
allow_table_fallback=True,
)
if not isinstance(region_characters, list):
continue
# ??????????????????????????? Schema ???
@@ -1117,31 +1251,22 @@ def preview_profile_region(
if field_code and field_code not in seen_field_codes:
seen_field_codes.add(field_code)
involved_field_codes.append(field_code)
reconstructed_rows = reconstruct_coordinate_profile_rows(
characters=[item for item in region_characters if isinstance(item, dict)], table_bbox=page_bbox,
reconstructed_rows, _strategy = reconstruct_coordinate_profile_rows_with_strategy(
characters=[item for item in region_characters if isinstance(item, dict)],
table_bbox=(
{'x0': 0, 'y0': 0, 'x1': reference_page_frame.width, 'y1': reference_page_frame.height}
if reference_page_frame is not None else page_bbox
),
line_layouts=[item.model_dump() for item in table_region.line_layouts],
table_region=table_region.region.model_dump(),
termination_rules=[item.model_dump() for item in table_region.termination_rules],
exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions],
exclusion_regions=reconstruction_exclusions,
dynamic_exclusion_regions=reconstruction_exclusions,
# ?????????????????????????????????
include_deleted=not strict,
line_start_field_code=table_region.line_start_field_code,
row_reconstruction_mode=table_region.row_reconstruction_mode,
schema_field_metadata=schema_field_metadata,
)
# Preview must expose coordinate reads for correction even when the current
# sample's start marker is missing; the production extraction path remains strict.
if not reconstructed_rows and not strict:
reconstructed_rows = reconstruct_coordinate_profile_rows(
characters=[item for item in region_characters if isinstance(item, dict)], table_bbox=page_bbox,
line_layouts=[item.model_dump() for item in table_region.line_layouts],
table_region=table_region.region.model_dump(),
termination_rules=[item.model_dump() for item in table_region.termination_rules],
exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions],
include_deleted=True,
line_start_field_code=table_region.line_start_field_code,
include_unanchored_rows=True,
row_reconstruction_mode=table_region.row_reconstruction_mode,
)
rows.extend(reconstructed_rows)
# ??????????????????????????????
if strict:
@@ -1198,6 +1323,8 @@ def suggest_profile_header(
profile_code=profile.profile_code, version=profile.version,
document_match=definition['document_match'], table_regions=definition['table_regions'],
order_field_layouts=definition['order_field_layouts'],
coordinate_model=definition['coordinate_model'],
reference_page_frames=definition['reference_page_frames'],
)
table_id = str(data.get('table_id') or '').strip()
layout = _document_layout(document)
@@ -1392,6 +1519,28 @@ def _document_layout(document: ShippingOrderDocument) -> dict[str, Any]:
return layout
def _reference_page_frames(layout: dict[str, Any]) -> dict[str, dict[str, Any]]:
"""从标注样本冻结 Layout 提取 PDF CropBox 点尺寸,拒绝使用浏览器提交的物理尺寸。"""
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
frames: dict[str, dict[str, Any]] = {}
for page_no, page in pages.items():
try:
normalized_page_no = int(page_no)
width, height = float(page['width']), float(page['height'])
except (KeyError, TypeError, ValueError):
continue
if normalized_page_no < 1 or width <= 0 or height <= 0:
continue
frames[str(normalized_page_no)] = {
'width': width,
'height': height,
'origin': 'pdf_top_left',
'box': 'cropbox',
}
return frames
def _current_ready_layout_version(document: ShippingOrderDocument) -> ShippingDocumentLayoutVersion:
"""????????? ready Layout ???????????????????????"""
version = document.current_layout_version
@@ -1648,7 +1797,7 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr
ensure_inline_xfa_structure_analysis_identity,
record_inline_layout_snapshot,
)
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ensure_on_demand_coordinate_evidence
from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence
samples = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).order_by(
ShippingOrderDocumentProfileSample.id.asc(),
@@ -1666,28 +1815,17 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
)
layout_version = _current_ready_layout_version(document)
required_pages = _profile_sample_coordinate_pages(
profile, sample=sample, layout_payload=layout_version.payload_json or {},
hydrated_layout = _hydrate_coordinate_evidence(
payload=dict(layout_version.payload_json or {}), document=document,
)
if not _layout_has_page_coordinate_evidence(layout_version.payload_json or {}, page_nos=required_pages):
# [STEP 1] ???????????????????
recovered = ensure_on_demand_coordinate_evidence(
document=document, layout=dict(layout_version.payload_json or {}), page_nos=required_pages,
required_pages = _profile_sample_coordinate_pages(
profile, sample=sample, layout_payload=hydrated_layout,
)
if not _layout_has_page_coordinate_evidence(hydrated_layout, page_nos=required_pages):
raise ConflictError(
'Profile sample page coordinate evidence is unavailable',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
)
if not _layout_has_page_coordinate_evidence(recovered, page_nos=required_pages):
raise ConflictError(
'Profile sample page coordinate evidence is unavailable',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
)
layout_version = record_inline_layout_snapshot(
document, recovered,
parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1',
)
if str(layout_version.status or '') != 'ready':
raise ConflictError(
'Profile sample page coordinate evidence cannot be frozen',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
)
# XFA 视觉补证生成的派生 Layout 必须具有同版本的 datasets 结构分析;
# 此处在共同样本冻结边界补齐历史快照,禁止值源 adapter 回退到旧 Layout。
ensure_inline_xfa_structure_analysis_identity(
@@ -1802,7 +1940,10 @@ def _page_coordinate_characters(layout: dict[str, Any], *, page_no: int) -> tupl
def _ensure_page_coordinate_evidence(
*, document: ShippingOrderDocument, layout: dict[str, Any], page_no: int,
) -> dict[str, Any]:
"""???????????????????????????????????"""
"""从当前布局的外置证据引用读取页面坐标;缺失时保持缺失,不重读原 PDF。"""
from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence
return _hydrate_coordinate_evidence(payload=dict(layout), document=document)
glyphs, source = _page_coordinate_characters(layout, page_no=page_no)
if glyphs and source in {'pdf_coordinate', 'ocr_coordinate'}:
return layout
@@ -2092,6 +2233,8 @@ def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) ->
document_match=definition['document_match'], table_regions=definition['table_regions'],
order_field_layouts=definition['order_field_layouts'],
draft_unbound_order_field_layouts=definition['draft_unbound_order_field_layouts'],
coordinate_model=definition['coordinate_model'],
reference_page_frames=definition['reference_page_frames'],
)
layout = _document_layout(document)
if isinstance(raw_page_nos, list) and any(item.page_scope == 'all_pages' for item in profile.order_field_layouts):
@@ -2239,7 +2382,7 @@ def _apply_acroform_widget_preview_fallback(
def _widget_is_within_visual_value_region(*, widget_bbox: Any, region: dict[str, float]) -> bool:
"""接受中心点落框或至少 80% 面积相交的 Widget,避免邻近控件串值。"""
"""仅接受几乎完整落入标注框的 Widget,禁止局部框回填整段 /V。"""
if not isinstance(widget_bbox, dict):
return False
try:
@@ -2248,9 +2391,10 @@ def _widget_is_within_visual_value_region(*, widget_bbox: Any, region: dict[str,
return False
if x1 <= x0 or y1 <= y0:
return False
center_inside = region['x0'] <= (x0 + x1) / 2 <= region['x1'] and region['y0'] <= (y0 + y1) / 2 <= region['y1']
intersection = max(0.0, min(x1, region['x1']) - max(x0, region['x0'])) * max(0.0, min(y1, region['y1']) - max(y0, region['y0']))
return center_inside or intersection / ((x1 - x0) * (y1 - y0)) >= .8
# Widget /V 是整个控件值。只要框没有完整覆盖控件,就无法证明 /V 属于局部区域;
# 此时必须交给浏览器当前画布的局部 OCR,而不能以中心点或部分面积猜测。
return intersection / ((x1 - x0) * (y1 - y0)) >= .98
def _read_acroform_widgets_for_preview(*, document: ShippingOrderDocument) -> list[Any]:
@@ -3236,6 +3380,16 @@ def save_draft(
)
mapping_issues = normalized.pop('_mapping_issues', None) if isinstance(normalized, dict) else None
definition = normalized
# [STEP 1] 坐标模板的物理参考框由 annotation Layout 生成;长页样本不会改变
# 已标注的 PDF 点坐标,客户端也不能伪造该基准。
if template_mode == 'coordinate' and annotation_document is not None:
reference_page_frames = _reference_page_frames(_document_layout(annotation_document))
if not reference_page_frames:
raise ValidationError(
'Annotation sample page dimensions are unavailable',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
)
definition['reference_page_frames'] = reference_page_frames
if value_adapter.requires_split_rule_confirmation and isinstance(definition, dict):
confirmation_tokens = data.get('split_rule_confirmation_tokens')
if not isinstance(confirmation_tokens, dict):
@@ -38,6 +38,10 @@ from app.services.shipping_notice.document_layout.xfa_contract import (
XFA_PARSER_IDENTITY,
)
# 签名生成必须先解引用压缩 Layout 的 FileAsset 坐标证据;旧签名不具备该输入契约。
LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION = 'v1'
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
"""读取可验证草稿;发布和退役版本不能被新的草稿验证记录替代。"""
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
@@ -448,8 +452,15 @@ def _training_samples(profile: ShippingOrderDocumentProfile) -> list[ShippingOrd
def _load_sample_layout(sample: ShippingOrderDocumentProfileSample) -> dict[str, Any]:
"""加载样本冻结或当前 ready layout;签名只消费坐标证据摘要,不复制原件。"""
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
"""加载样本冻结或当前 ready layout,并解引用压缩快照的 FileAsset 坐标证据。
冻结 Layout 是签名和发布校验的历史事实;当 payload 只保留
``coordinate_evidence_ref`` 时,必须恢复其不可变坐标证据,不能误判为无版面证据。
"""
from app.services.shipping_notice.document_layout.lifecycle import (
_hydrate_coordinate_evidence,
current_layout_snapshot,
)
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
ensure_on_demand_coordinate_evidence,
)
@@ -460,6 +471,11 @@ def _load_sample_layout(sample: ShippingOrderDocumentProfileSample) -> dict[str,
from app.models import ShippingDocumentLayoutVersion
frozen = db.session.get(ShippingDocumentLayoutVersion, int(sample.layout_version_id))
if frozen is not None and isinstance(frozen.payload_json, dict):
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
if document is not None:
return _hydrate_coordinate_evidence(
payload=dict(frozen.payload_json), document=document,
)
return dict(frozen.payload_json)
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
if document is None:
@@ -675,6 +691,7 @@ def _build_coordinate_identity_snapshot(
evidence = (snapshot.get('signature') or {}).get('evidence_quality') or {}
return snapshot, {
'signature_version': LAYOUT_SIGNATURE_ID,
'evidence_contract_version': LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION,
'signature_checksum': snapshot.get('signature_checksum'),
'matcher_policy_version': MATCHER_POLICY_ID,
'source_sample_count': evidence.get('source_sample_count') or len(samples),
@@ -728,7 +745,15 @@ def _resolve_profile_identity_signature_run(
or run.run_type != 'layout_signature'
or run.status != 'passed'
or run.definition_checksum != revision.definition_checksum
or not _signature_uses_current_evidence_contract(run)
):
if auto_run:
run_profile_identity_signature(
profile.id, data={}, actor_id=actor_id, browser_session_id=browser_session_id,
lease_token=lease_token, operation_id=str(operation_id or secrets.token_hex(16)),
)
db.session.refresh(profile)
return _resolve_profile_identity_signature_run(profile, revision, auto_run=False)
raise ValidationError(
'Profile identity signature is stale for the current draft',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE',
@@ -742,6 +767,12 @@ def _resolve_profile_identity_signature_run(
return run
def _signature_uses_current_evidence_contract(run: ShippingOrderDocumentProfileValidationRun) -> bool:
"""仅允许已按当前 FileAsset 解引用契约生成的签名进入发布唯一性校验。"""
summary = getattr(run, 'summary_json', None)
return isinstance(summary, dict) and summary.get('evidence_contract_version') == LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION
def resolve_profile_identity_signature(
profile: ShippingOrderDocumentProfile,
revision: ShippingOrderDocumentProfileDraftRevision,
@@ -785,10 +816,16 @@ def _match_thresholds(definition: dict[str, Any]) -> dict[str, float]:
"""从 document_match 提取发布唯一性门禁阈值。"""
document_match = definition.get('document_match') if isinstance(definition.get('document_match'), dict) else {}
thresholds = document_match.get('scoring_thresholds') if isinstance(document_match.get('scoring_thresholds'), dict) else {}
def configured_or_default(source: dict[str, Any], key: str, default: float) -> float:
"""保留合法的 0 阈值;只有缺失或空值才回退默认门禁。"""
value = source.get(key)
return float(default if value is None else value)
return {
'minimum_score': float(document_match.get('minimum_score') or 0.9),
'minimum_margin': float(document_match.get('minimum_margin') or 0.12),
'evidence_coverage_minimum': float(thresholds.get('evidence_coverage_minimum') or 0.70),
'minimum_score': configured_or_default(document_match, 'minimum_score', 0.9),
'minimum_margin': configured_or_default(document_match, 'minimum_margin', 0.12),
'evidence_coverage_minimum': configured_or_default(thresholds, 'evidence_coverage_minimum', 0.70),
}
@@ -1031,7 +1068,15 @@ def _resolve_layout_signature_run(
or run.run_type != 'layout_signature'
or run.status != 'passed'
or run.definition_checksum != revision.definition_checksum
or not _signature_uses_current_evidence_contract(run)
):
if auto_run:
run_profile_identity_signature(
profile.id, data={}, actor_id=actor_id, browser_session_id=browser_session_id,
lease_token=lease_token, operation_id=str(operation_id or secrets.token_hex(16)),
)
db.session.refresh(profile)
return _resolve_layout_signature_run(profile, revision, auto_run=False)
raise ValidationError(
'Layout signature is stale for the current draft',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE',
@@ -105,6 +105,11 @@ STABLE_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
'no_special_profile_feature',
'generic_extraction_disabled',
'generic_gate_blocked',
'coordinate_evidence_unavailable',
# Runtime Parse Strategy:当前文档的坐标/行结构判断无法唯一裁决时固定进入 Review。
'PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',
'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',
'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION',
'llm_review_disabled',
'extraction_emergency_stop',
'rejected',
@@ -3618,6 +3618,7 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str,
'primary_notice': workspace_projection.get('primary_notice'),
'user_visible_stage': workspace_projection.get('user_visible_stage'),
'health_tips': workspace_projection.get('health_tips') or [],
'lifecycle_progress': workspace_projection.get('lifecycle_progress') or {},
'cancellation': workspace_projection.get('cancellation'),
'progress_version': workspace_projection.get('progress_version'),
'elapsed_seconds': workspace_projection.get('elapsed_seconds'),
@@ -25,10 +25,18 @@ from app.services.shipping_notice.order_extraction_runtime_snapshot import (
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
coordinate_profile_character_candidates,
reconstruct_coordinate_profile_rows, reconstruct_coordinate_profile_rows_with_strategy,
reconstruction_exclusion_regions,
)
from app.services.shipping_notice.document_layout.coordinate_transform import (
apply_coordinate_transform_to_region,
)
from app.services.shipping_notice.document_layout.runtime_parse_strategy import (
resolve_runtime_parse_strategy,
select_runtime_region_ids,
)
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
from app.services.shipping_notice.document_layout.order_profile_matcher import (
ProfileMatchResult,
@@ -47,6 +55,10 @@ from app.services.shipping_notice.order_extraction_route_contract import (
from app.services.shipping_notice.tool_common import generic_extraction_enabled, profile_auto_selection_enabled
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
from app.services.shipping_notice.reservation_region import (
apply_reservation_region_candidates,
extract_reservation_from_vendor_comments_pages,
)
@dataclass(frozen=True)
@@ -281,6 +293,8 @@ def _frozen_order_profile(raw: dict[str, Any]) -> OrderCoordinateProfile:
table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [],
coordinate_model=definition.get('coordinate_model') or {},
reference_page_frames=definition.get('reference_page_frames') or {},
)
@@ -316,6 +330,7 @@ def _coordinate_profile_rows(
contract: Any, schema_fields: dict[str, dict[str, Any]], document_id: int | None = None,
initial_carry: dict[str, Any] | None = None,
coordinate_transform: dict[str, Any] | None = None,
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns'] = 'fixed_subrows',
) -> list[dict[str, Any]] | None:
"""
用模板表区和整页字符生成带字段坐标的紧凑行候选。
@@ -356,12 +371,13 @@ def _coordinate_profile_rows(
if page_bbox['x1'] <= 0 or page_bbox['y1'] <= 0:
return None
rows: list[dict[str, Any]] = []
runtime_region_ids = set(select_runtime_region_ids(
table_regions=[region.model_dump() for region in profile.table_regions], page_no=page_no,
))
for region in profile.table_regions:
if region.page_scope == 'first_page' and page_no != 1:
continue
if region.page_scope == 'continuation_pages' and page_no <= 1:
continue
if region.page_scope == 'exact_page' and page_no != region.page_no:
# 标注页优先;续页仅回退到稳定的基础表区。是否真正属于明细页仍由当前页
# 的坐标、起行字段与行重建结果裁决,不能仅依赖历史 page_scope 自动建单。
if region.region_id not in runtime_region_ids:
continue
# A continuation page may carry column headers only; it is not a data layout.
if not region.line_layouts:
@@ -369,47 +385,42 @@ def _coordinate_profile_rows(
relative_region = _coordinate_region_mapping(region.region)
if relative_region is None:
return None
evidence_relative_region = _translate_coordinate_region(
relative_region, coordinate_transform=coordinate_transform,
reference_page_frame = profile.reference_page_frames.get(page_no)
reconstruction_page_bbox = (
{
'x0': 0, 'y0': 0,
'x1': reference_page_frame.width, 'y1': reference_page_frame.height,
}
if reference_page_frame is not None else page_bbox
)
if evidence_relative_region is None:
return None
region_bbox = {
'x0': evidence_relative_region['x0'] * page_bbox['x1'],
'y0': evidence_relative_region['y0'] * page_bbox['y1'],
'x1': evidence_relative_region['x1'] * page_bbox['x1'],
'y1': evidence_relative_region['y1'] * page_bbox['y1'],
}
raw_bbox = raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None
if not is_virtual_page and raw_bbox is not None and not _coordinate_regions_overlap(raw_bbox, region_bbox):
continue
# [STEP] 横向边界服从模板;纵向取模板样例区与真实物理表的并集。模板 y 区间只描述
# 一条样例版式,不能截掉其后重复明细;MinerU 框过短时仍由模板区保住 continuation。
evidence_bbox = dict(region_bbox)
if raw_bbox is not None:
evidence_bbox['y0'] = min(region_bbox['y0'], float(raw_bbox.get('y0', region_bbox['y0'])))
evidence_bbox['y1'] = max(region_bbox['y1'], float(raw_bbox.get('y1', region_bbox['y1'])))
if isinstance(page_characters, list):
characters = [
item for item in page_characters
if isinstance(item, dict) and _coordinate_character_in_region(item, evidence_bbox)
]
else:
# 历史快照没有整页字符时保留表内字符兼容;新快照必须优先整页证据。
characters = tables.get(table_id)
characters, _candidate_page_bbox = coordinate_profile_character_candidates(
table_region=region.region.model_dump(), page_size=page_size,
reference_page_frame=(
reference_page_frame.model_dump() if reference_page_frame is not None 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,
raw_table_bbox=raw_bbox, table_id=table_id, page_no=page_no,
coordinate_transform=coordinate_transform,
allow_table_fallback=(not is_virtual_page and page_no == int(raw_table.get('page_no') or 1)),
)
if not isinstance(characters, list):
return None
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(
characters=[item for item in characters if isinstance(item, dict)], table_bbox=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],
table_region=relative_region,
termination_rules=[item.model_dump() for item in region.termination_rules],
exclusion_regions=[item.model_dump() for item in region.exclusion_regions],
exclusion_regions=reconstruction_exclusion_regions(
region.model_dump(),
),
initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0),
line_start_field_code=region.line_start_field_code,
row_reconstruction_mode=region.row_reconstruction_mode,
row_reconstruction_mode=row_reconstruction_mode,
coordinate_transform=coordinate_transform,
schema_field_metadata=list(schema_fields.values()),
):
values: list[dict[str, Any]] = []
issues = list(reconstructed.issues)
@@ -456,9 +467,17 @@ def _coordinate_profile_rows(
def _selected_coordinate_transform(
*, profile_match: dict[str, Any], raw_profile: dict[str, Any],
) -> dict[str, Any] | None:
"""从共同 matcher 的唯一选中候选取得运行时变换,禁止为行解析二次匹配。"""
"""仅为显式 anchor_frame 模板转交 matcher 的已选变换。
普通 legacy 模板的绝对字段坐标已由其发布盲测验证;matcher 为提高身份匹配
鲁棒性推导的临时位移不得改变这类模板的正式取值区域。
"""
if str(profile_match.get('status') or '') not in {'unique_match', 'selected_by_score'}:
return None
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
coordinate_model = definition.get('coordinate_model') if isinstance(definition.get('coordinate_model'), dict) else {}
if str(coordinate_model.get('type') or 'legacy') != 'anchor_frame':
return None
identity = (
str(raw_profile.get('profile_code') or ''),
int(raw_profile.get('version') or 0),
@@ -525,6 +544,69 @@ def _coordinate_regions_overlap(left: dict[str, Any], right: dict[str, Any]) ->
return False
def _physical_table_targets_profile_region(
*, raw_table: dict[str, Any], table_regions: list[dict[str, Any]], page_size: dict[str, Any] | None,
reference_page_frame: dict[str, Any] | None = None,
coordinate_transform: dict[str, Any] | None = None,
) -> bool:
"""判断物理表是否属于当前页模板的明细区域;未知几何保守保留为候选。
同页的页脚汇总、签章等 MinerU 物理表不属于订单明细模板,不能因其无法重建
而阻断已成功的目标表。虚拟页、缺失 bbox 或页尺寸异常时维持既有整页坐标回退,
避免表检测遗漏被错误跳过。
"""
page_no = int(raw_table.get('page_no') or 1)
if str(raw_table.get('table_id') or '') == f'page-{page_no}':
return True
raw_bbox = raw_table.get('bbox')
if not isinstance(raw_bbox, dict) or not isinstance(page_size, dict):
return True
try:
page_width, page_height = float(page_size['width']), float(page_size['height'])
projection_width = float(reference_page_frame['width']) if reference_page_frame is not None else page_width
projection_height = float(reference_page_frame['height']) if reference_page_frame is not None else page_height
except (KeyError, TypeError, ValueError):
return True
if page_width <= 0 or page_height <= 0 or projection_width <= 0 or projection_height <= 0:
return True
active_region_ids = set(select_runtime_region_ids(
table_regions=table_regions, page_no=page_no,
))
active_regions = [
region for region in table_regions
if isinstance(region, dict)
and str(region.get('region_id') or '') in active_region_ids
and isinstance(region.get('region'), dict)
and region.get('line_layouts')
]
if not active_regions:
return True
for region in active_regions:
projected = apply_coordinate_transform_to_region(
region['region'], coordinate_transform=coordinate_transform,
)
if projected is None:
continue
absolute_region = {
'x0': projected['x0'] * projection_width, 'y0': projected['y0'] * projection_height,
'x1': projected['x1'] * projection_width, 'y1': projected['y1'] * projection_height,
}
if _coordinate_regions_overlap(raw_bbox, absolute_region):
return True
return False
def _virtual_page_without_rows_is_nonblocking(
*, raw_table: dict[str, Any], fixed_rows: list[dict[str, Any]] | None,
adaptive_rows: list[dict[str, Any]] | None, dynamic_rows: list[dict[str, Any]] | None = None,
) -> bool:
"""空虚拟页只作为漏检表格的补偿候选,不能把已有目标表成功覆盖为失败。"""
page_no = int(raw_table.get('page_no') or 1)
if str(raw_table.get('table_id') or '') != f'page-{page_no}':
return False
return not (fixed_rows or []) and not (adaptive_rows or []) and not (dynamic_rows or [])
def _coordinate_character_in_region(character: dict[str, Any], region: dict[str, float]) -> bool:
"""按字符中心点裁剪模板表区,避免边缘字形重叠把页头或相邻表带入。"""
bbox = character.get('bbox') if isinstance(character.get('bbox'), dict) else None
@@ -729,13 +811,30 @@ def _profile_table_candidates(
if item.get('profile_code') == match.profile_code and int(item.get('version') or 0) == match.version
and str(item.get('checksum') or '') == match.checksum
]
# 只有唯一选中的模板显式标注了 Reservation 专区,才补齐全文坐标并开启
# Vendor Comments→Terms 跨页扫描;其他候选模板不得改变未标注模板的读取范围。
selected_reservation_region = (
(profiles[0].get('definition') or {}).get('reservation_id_region')
if len(profiles) == 1 and isinstance(profiles[0], dict) else None
)
if isinstance(selected_reservation_region, dict) and document_model is not None:
layout = ensure_on_demand_coordinate_evidence(
document=document_model, layout=layout, page_nos=None,
table_by_page={int(item.get('page_no') or 1): item for item in raw_tables},
)
if match_only:
reservation_region = (
_reservation_region_candidates(raw_profile=profiles[0], layout=layout)
if len(profiles) == 1 else {'candidates': [], 'reason': None}
)
return {
'matched': True,
'blocking': False,
'tables': [],
'issues': [],
'match': profile_match,
'reservation_region_candidates': reservation_region['candidates'],
'reservation_region_reason': reservation_region['reason'],
}
result_tables: list[dict[str, Any]] = []
issues: list[str] = []
@@ -781,6 +880,25 @@ def _profile_table_candidates(
coordinate_transform = _selected_coordinate_transform(
profile_match=profile_match, raw_profile=raw_profile,
)
profile_table_regions = [
item.model_dump() for item in profile.table_regions
if callable(getattr(item, 'model_dump', None))
]
evidence_pages = (
(layout.get('coordinate_evidence') or {}).get('pages') or {}
)
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))
if not _physical_table_targets_profile_region(
raw_table=raw_table,
table_regions=profile_table_regions,
page_size=page_size if isinstance(page_size, dict) else None,
reference_page_frame=(
reference_page_frame.model_dump() if reference_page_frame is not None else None
),
coordinate_transform=coordinate_transform,
):
continue
carry = None
parent_table_id = str(raw_table.get('continuation_of') or '')
if parent_table_id:
@@ -792,18 +910,51 @@ def _profile_table_candidates(
):
carry = candidate
break
coordinate_rows = _coordinate_profile_rows(
fixed_rows = _coordinate_profile_rows(
raw_profile=raw_profile, raw_table=raw_table, layout=layout,
contract=contract, schema_fields=schema_fields,
document_id=int(unit.document_id), initial_carry=carry,
coordinate_transform=coordinate_transform,
row_reconstruction_mode='fixed_subrows',
)
adaptive_rows = _coordinate_profile_rows(
raw_profile=raw_profile, raw_table=raw_table, layout=layout,
contract=contract, schema_fields=schema_fields,
document_id=int(unit.document_id), initial_carry=None,
coordinate_transform=coordinate_transform,
row_reconstruction_mode='adaptive_record_columns',
)
dynamic_rows = _coordinate_profile_rows(
raw_profile=raw_profile, raw_table=raw_table, layout=layout,
contract=contract, schema_fields=schema_fields,
document_id=int(unit.document_id), initial_carry=None,
coordinate_transform=coordinate_transform,
row_reconstruction_mode='dynamic_x_columns',
)
except (TypeError, ValueError):
issues.append('order_profile_snapshot_invalid')
continue
if coordinate_rows is None:
if fixed_rows is None or adaptive_rows is None or dynamic_rows is None:
issues.append('order_profile_coordinate_reconstruction_unavailable')
continue
if _virtual_page_without_rows_is_nonblocking(
raw_table=raw_table, fixed_rows=fixed_rows, adaptive_rows=adaptive_rows,
dynamic_rows=dynamic_rows,
):
continue
strategy = resolve_runtime_parse_strategy(
page_glyphs=(layout.get('coordinate_evidence') or {}).get('page_glyphs') or {},
fixed_rows=fixed_rows, adaptive_rows=adaptive_rows,
dynamic_rows=dynamic_rows,
)
if strategy.status != 'selected' or strategy.row_mode is None:
issues.extend(strategy.reason_codes)
continue
coordinate_rows = (
fixed_rows if strategy.row_mode == 'fixed_subrows'
else adaptive_rows if strategy.row_mode == 'adaptive_record_columns'
else dynamic_rows
)
if coordinate_rows:
complete_rows = []
for row in coordinate_rows:
@@ -811,7 +962,7 @@ def _profile_table_candidates(
if (
region is not None
and region.continuation_rule.allow_cross_page
and region.row_reconstruction_mode == 'fixed_subrows'
and strategy.row_mode == 'fixed_subrows'
and row.get('_coordinate_row_count', 0) < len(region.line_layouts)
):
cross_page_carries[(str(raw_profile.get('profile_code') or ''), table_id)] = {
@@ -838,6 +989,7 @@ def _profile_table_candidates(
issues.append('order_profile_multiple_matches')
continue
raw_profile, parsed = matches[0]
reservation_region = _reservation_region_candidates(raw_profile=raw_profile, layout=layout)
result_tables.append({
'profile_id': raw_profile.get('profile_id') or raw_profile.get('id'),
'profile_code': str(raw_profile.get('profile_code') or ''),
@@ -847,6 +999,13 @@ def _profile_table_candidates(
'page_no': int(raw_table.get('page_no') or 1),
'auto_create_approved': bool(raw_profile.get('auto_create_approved')),
'rows': parsed,
'reservation_region_candidates': reservation_region['candidates'],
'reservation_region_reason': reservation_region['reason'],
'runtime_parse_strategy': {
'page_nos': list(strategy.page_nos),
'row_mode': strategy.row_mode,
'reason_codes': list(strategy.reason_codes),
},
})
return {
'matched': matched_any,
@@ -1523,16 +1682,30 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
decision = adapter_result.decision
# [STEP 2] 公共建单:任何 adapter 只能交付 table/证据,不能自行裁决生命周期。
if adapter_result.table is not None:
reservation_candidates = (
adapter_result.table.get('reservation_region_candidates')
if isinstance(adapter_result.table, dict) else None
)
if not isinstance(reservation_candidates, list):
reservation_candidates = profile_result.get('reservation_region_candidates')
reservation_region_reason = (
adapter_result.table.get('reservation_region_reason')
if isinstance(adapter_result.table, dict) else None
) or profile_result.get('reservation_region_reason')
orders, reason_code = _build_approved_profile_order_result(
unit=unit, intake=intake, schema=schema, definition=definition,
table=adapter_result.table, confirmed_order_fields=adapter_result.confirmed_order_fields,
allow_manual_review=False,
reservation_region_candidates=reservation_candidates if isinstance(reservation_candidates, list) else None,
reservation_region_reason=str(reservation_region_reason or '') or None,
)
if orders is None and adapter_result.allow_manual_row_review and reason_code == 'row_needs_review':
orders, review_reason = _build_approved_profile_order_result(
unit=unit, intake=intake, schema=schema, definition=definition,
table=adapter_result.table, confirmed_order_fields=adapter_result.confirmed_order_fields,
allow_manual_review=True,
reservation_region_candidates=reservation_candidates if isinstance(reservation_candidates, list) else None,
reservation_region_reason=str(reservation_region_reason or '') or None,
)
if orders is not None:
decision['fallback_reason_codes'] = ['row_needs_review']
@@ -1553,6 +1726,11 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
)
decision['parsed_table_count'] = 1
decision['route_type'] = 'profile_deterministic'
if any(order.get('reservation_region_status') == 'needs_review' for order in orders):
decision['fallback_reason_codes'] = ['reservation_region_needs_review']
return _apply_stp_route_adjudication(
decision, execution_mode='review_required', orders=orders,
)
if decision.get('fallback_reason_codes'):
return _apply_stp_route_adjudication(
decision, execution_mode='review_required', orders=orders,
@@ -1621,6 +1799,8 @@ def _route_reason_for_issue(issue: str) -> str:
'order_profile_snapshot_field_mismatch': 'profile_schema_mismatch',
'order_profile_multiple_matches': 'profile_ambiguous',
'order_profile_coordinate_reconstruction_unavailable': 'coordinate_evidence_unavailable',
'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS': 'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',
'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION': 'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION',
}
# 第零层:on-demand 坐标恢复失败码直接收敛为证据不可用,不经过 fallback 误报为 drift。
if str(issue).startswith('coordinate_evidence_'):
@@ -1635,13 +1815,34 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfile:
profile_code=str(raw.get('profile_code') or ''), version=int(raw.get('version') or 0),
document_match=definition.get('document_match'), table_regions=definition.get('table_regions'),
order_field_layouts=definition.get('order_field_layouts') or [],
coordinate_model=definition.get('coordinate_model') or {},
reference_page_frames=definition.get('reference_page_frames') or {},
)
def _reservation_region_candidates(*, raw_profile: dict[str, Any], layout: dict[str, Any]) -> dict[str, Any]:
"""仅对已标注专区的模板,跨页读取 Vendor Comments 到首次 Terms 标题间的候选。"""
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
configured = definition.get('reservation_id_region')
if not isinstance(configured, dict):
return {'candidates': [], 'reason': None}
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
pages = [
(int(page_no), glyphs)
for page_no, glyphs in page_glyphs.items()
if str(page_no).isdigit() and isinstance(glyphs, list)
]
candidates, reason = extract_reservation_from_vendor_comments_pages(pages)
return {'candidates': candidates, 'reason': reason}
def _build_approved_profile_order_result(
*, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any],
table: dict[str, Any], confirmed_order_fields: list[dict[str, Any]] | None = None,
allow_manual_review: bool = False,
reservation_region_candidates: list[dict[str, Any]] | None = None,
reservation_region_reason: str | None = None,
) -> tuple[list[dict[str, Any]] | None, str | None]:
"""
把已批准 Profile 本次实际解析的唯一完整表格转换为零 Provider 订单。
@@ -1779,6 +1980,66 @@ def _build_approved_profile_order_result(
}
if source_missing_fields['header']['field_ids'] or source_missing_fields['lines']:
base_order['source_missing_fields'] = source_missing_fields
# Reservation 专用区域可同时生成整单默认值和指定行覆盖值。有效值的行优先
# 回退由 Schema Runtime 的 compute_effective_reservation_id 统一处理,无须复制 Header。
reservation_scope = {
str(item.get('scope') or ''): item for item in fields
if str(item.get('field_code') or '') == 'reservation_id'
}
candidates = reservation_region_candidates or list(table.get('reservation_region_candidates') or [])
reservation_region_reason = reservation_region_reason or str(table.get('reservation_region_reason') or '') or None
if reservation_region_reason:
base_order['reservation_region_status'] = 'needs_review'
base_order['reservation_region_review_reasons'] = [reservation_region_reason]
if candidates:
header_target = reservation_scope.get('header')
line_target = reservation_scope.get('line')
applied = apply_reservation_region_candidates(
candidates=candidates,
header_field_id=str(header_target.get('field_id') or '') if header_target else None,
line_field_id=str(line_target.get('field_id') or '') if line_target else None,
line_count=len(line_groups),
)
if applied.header_value and header_target:
header_evidence = next((item for item in candidates if item.get('scope') == 'header'), {})
header_fields.append({'field_id': str(header_target.get('field_id') or ''), 'observations': [{
'value': applied.header_value, 'document_id': int(unit.document_id),
'quote': str(header_evidence.get('raw_text') or '')[:1000], 'confidence': 1.0,
}]})
header_id = str(header_target.get('field_id') or '')
source_missing_fields['header']['field_ids'] = [
field_id for field_id in source_missing_fields['header']['field_ids'] if field_id != header_id
]
header_code = str(header_target.get('field_code') or '')
source_missing_fields['header']['field_codes'] = [
field_code for field_code in source_missing_fields['header']['field_codes'] if field_code != header_code
]
if line_target:
for line_no, value in applied.line_values.items():
line_evidence = next((
item for item in candidates
if item.get('scope') == 'line' and item.get('line_no') == line_no and item.get('value') == value
), {})
line_groups[line_no - 1].setdefault('fields', []).append({'field_id': str(line_target.get('field_id') or ''), 'observations': [{
'value': value, 'document_id': int(unit.document_id),
'quote': str(line_evidence.get('raw_text') or '')[:1000], 'confidence': 1.0,
}]})
line_id = str(line_target.get('field_id') or '')
line_code = str(line_target.get('field_code') or '')
for missing in source_missing_fields['lines']:
if isinstance(missing, dict) and int(missing.get('line_index') or -1) == line_no - 1:
missing['field_ids'] = [field_id for field_id in missing['field_ids'] if field_id != line_id]
missing['field_codes'] = [field_code for field_code in missing['field_codes'] if field_code != line_code]
source_missing_fields['lines'] = [
item for item in source_missing_fields['lines']
if item.get('field_ids') or item.get('field_codes')
]
if not source_missing_fields['header']['field_ids'] and not source_missing_fields['lines']:
base_order.pop('source_missing_fields', None)
if applied.needs_review:
base_order['reservation_region_candidates'] = candidates
base_order['reservation_region_status'] = 'needs_review'
base_order['reservation_region_review_reasons'] = list(applied.review_reasons)
if not has_review_rows:
base_order['_hxops_acceptance'] = 'approved_deterministic_profile_v1'
# 当前业务约束:一份 PDF 只能形成一个 PO;检测到多个 PO 必须整体拒识并转人工复核。
@@ -1927,6 +2188,7 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An
candidates = extract_order_fields(
profile=_frozen_coordinate_profile(raw), schema_fields=schema_fields,
coordinate_evidence=layout.get('coordinate_evidence') or {},
allow_fixed_region_confirmation=True,
coordinate_transform=_selected_coordinate_transform(
profile_match=match.model_dump(mode='json') if hasattr(match, 'model_dump') else match,
raw_profile=raw,
@@ -39,6 +39,141 @@ from app.services.shipping_notice.progress_feature_flags import (
ACTIVE_UNIT_STATUSES = {'pending', 'routing', 'matching_profile', 'extracting', 'merging_supplement'}
IN_FLIGHT_UNIT_STATUSES = {'routing', 'matching_profile', 'extracting', 'merging_supplement'}
# Run/ProgressEvent 的内部事件统一收敛为工作台可见步骤;用户态不暴露 Worker 状态名。
_LIFECYCLE_EVENT_STEP_CODES = {
'plan_created': 'document_queued',
'document_queued': 'document_queued',
'layout_parsing_started': 'layout_parsing_started',
'layout_parsing_completed': 'layout_parsing_completed',
'profile_matching': 'profile_matching',
'profile_candidates_scored': 'profile_matching',
'profile_auto_selected': 'profile_matched',
'profile_matched': 'profile_matched',
'table_reconstructed': 'table_reconstructed',
'order_fields_extracted': 'order_fields_extracted',
'email_supplement_merged': 'email_supplement_merged',
'candidate_ready': 'review_ready',
'review_required': 'review_required',
}
# 这些事件本身就是一个业务动作已经完成的事实。ProgressEvent 的 status 为了
# 兼容 Run/Unit 的实时状态,部分仍会记录为 running,不能据此把已完成步骤漏掉。
_LIFECYCLE_COMPLETION_EVENT_CODES = frozenset({
'layout_parsing_completed',
'profile_auto_selected',
'profile_matched',
'table_reconstructed',
'order_fields_extracted',
'email_supplement_merged',
'candidate_ready',
})
_LIFECYCLE_UNIT_STEP_CODES = {
'pending': 'document_queued',
'routing': 'profile_matching',
'matching_profile': 'profile_matching',
'extracting': 'order_fields_extracted',
'merging_supplement': 'email_supplement_merged',
'candidate_ready': 'review_ready',
'review_required': 'review_required',
}
def _build_lifecycle_progress(
run: ShippingOrderProcessingRun,
*,
units: list[ShippingOrderProcessingUnit],
effective_status: str,
current_activity: dict[str, Any] | None,
health_tips: list[dict[str, Any]],
) -> dict[str, Any]:
"""
构建复核工作台消费的用户态生命周期进度。
核心逻辑:复用当前 Run 的事件、状态、最后活动和健康提示,映射为五阶段中的
接收解析/订单复核及阶段内步骤;不返回正文、Provider、Job 或堆栈信息。
"""
event_rows = []
if getattr(run, 'id', None) is not None:
event_rows = (
ShippingOrderExtractionProgressEvent.query
.filter_by(run_id=run.id, visibility='workspace')
.order_by(ShippingOrderExtractionProgressEvent.sequence_no.asc(), ShippingOrderExtractionProgressEvent.id.asc())
.all()
)
completed: list[str] = []
seen: set[str] = set()
for event in event_rows:
event_code = str(event.event_code or '').strip()
if (
str(event.status or '').lower() != 'completed'
and event_code not in _LIFECYCLE_COMPLETION_EVENT_CODES
):
continue
step = _LIFECYCLE_EVENT_STEP_CODES.get(event_code)
if step and step not in seen:
seen.add(step)
completed.append(step)
raw_event = str((current_activity or {}).get('event_code') or '').strip()
current_step = _LIFECYCLE_EVENT_STEP_CODES.get(raw_event)
if raw_event in _LIFECYCLE_COMPLETION_EVENT_CODES:
active_unit = next((unit for unit in units if unit.status in ACTIVE_UNIT_STATUSES), None)
current_step = _LIFECYCLE_UNIT_STEP_CODES.get(str(active_unit.status or '')) if active_unit else None
if (
effective_status in {'queued', 'processing'}
and current_step == 'layout_parsing_started'
and not any(unit.status in IN_FLIGHT_UNIT_STATUSES for unit in units)
):
current_step = 'document_queued'
if not current_step:
current_step = 'document_queued' if effective_status in {'queued', 'processing'} else None
if current_step and current_step not in completed and effective_status in {'queued', 'processing'}:
# 当前运行中的步骤不能同时标记已完成;保留历史完成步骤顺序。
completed = [step for step in completed if step != current_step]
lifecycle_stage = 'intake_parse'
if current_step in {'review_ready', 'review_required'} or effective_status == 'review_required':
lifecycle_stage = 'order_review'
if effective_status in {'completed'}:
lifecycle_stage = 'order_review'
lifecycle_status = {
'queued': 'running',
'processing': 'running',
'review_required': 'waiting',
'failed': 'failed',
'cancelled': 'cancelled',
'completed': 'completed',
'partially_completed': 'waiting',
}.get(effective_status, 'waiting')
health_status = 'failed' if lifecycle_status == 'failed' else ('attention' if health_tips else 'normal')
last_activity_at = (current_activity or {}).get('last_activity_at') or (
run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None
)
blocking_reason_i18n_key = None
if lifecycle_status == 'failed':
blocking_reason_i18n_key = 'chat.shippingProcessing.progress.lifecycleReason.failed'
elif lifecycle_status == 'cancelled':
blocking_reason_i18n_key = 'chat.shippingProcessing.progress.lifecycleReason.cancelled'
elif effective_status == 'review_required':
blocking_reason_i18n_key = 'chat.shippingProcessing.progress.lifecycleReason.review_required'
elif health_tips:
tip_code = str(health_tips[0].get('code') or '').strip()
if tip_code:
blocking_reason_i18n_key = f'chat.shippingProcessing.progress.lifecycleReason.{tip_code}'
return {
'lifecycle_stage': lifecycle_stage,
'lifecycle_status': lifecycle_status,
'current_step_code': current_step,
'current_step_i18n_key': (
f'chat.shippingProcessing.progress.step.{current_step}' if current_step else None
),
'completed_step_codes': completed,
'last_activity_at': last_activity_at,
'health_status': health_status,
'blocking_reason_i18n_key': blocking_reason_i18n_key,
'primary_action': None,
}
# 候选待处理原因中偏「冲突/歧义」的码;其余有 missing_fields 或待补语义的归入待补信息。
_CANDIDATE_CONFLICT_REASON_CODES = frozenset({
'email_supplement_conflict',
@@ -536,6 +671,47 @@ def _latest_progress_events(run: ShippingOrderProcessingRun) -> tuple[dict[tuple
return events, current
def serialize_lifecycle_progress(
run: ShippingOrderProcessingRun,
*,
units: list[ShippingOrderProcessingUnit] | None = None,
effective_status: str | None = None,
current_event: ShippingOrderExtractionProgressEvent | None = None,
health_tips: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""构建轻量 Run 进度,供复核首屏读取,避免加载完整工作台文件与处理项投影。"""
resolved_units = units if units is not None else (
list(run.extraction_plan.units or []) if run.extraction_plan is not None else []
)
resolved_status = effective_status or _effective_run_status(run, units=resolved_units)
if current_event is None and getattr(run, 'id', None) is not None:
_, current_event = _latest_progress_events(run)
current_activity: dict[str, Any] | None = None
if resolved_status in {'queued', 'processing'}:
if str(run.phase or '') == 'waiting_layout':
current_activity = {'event_code': 'layout_parsing_started'}
elif current_event is not None:
current_activity = {'event_code': current_event.event_code}
else:
active_unit = next((unit for unit in resolved_units if unit.status in ACTIVE_UNIT_STATUSES), None)
current_activity = {
'event_code': ('document_queued' if run.status == 'queued' else active_unit.status)
if active_unit is not None else 'document_queued',
}
if current_activity is not None and run.last_activity_at is not None:
current_activity['last_activity_at'] = run.last_activity_at.isoformat() + 'Z'
resolved_tips = health_tips if health_tips is not None else (
_health_tips_for_run(run, resolved_units) if progress_ui_v3_enabled() else []
)
return _build_lifecycle_progress(
run,
units=resolved_units,
effective_status=resolved_status,
current_activity=current_activity,
health_tips=resolved_tips,
)
def _latest_layout_document_events(run: ShippingOrderProcessingRun) -> dict[tuple[int, str], ShippingOrderExtractionProgressEvent]:
"""按 PDF 收集版面解析事件;该阶段早于 Unit 创建,不能复用 Unit 事件映射。"""
events: dict[tuple[int, str], ShippingOrderExtractionProgressEvent] = {}
@@ -1670,6 +1846,14 @@ def serialize_workspace_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
else (run.last_activity_at.isoformat() + 'Z' if run.last_activity_at else None)
),
}
health_tips = _health_tips_for_run(run, units, now=now) if progress_ui_v3_enabled() else []
lifecycle_progress = serialize_lifecycle_progress(
run,
units=units,
effective_status=effective_status,
current_event=current_event,
health_tips=health_tips,
)
return {
'effective_status': effective_status,
'summary': {
@@ -1698,7 +1882,8 @@ def serialize_workspace_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
),
'user_visible_stage': 'failed' if effective_status == 'failed' else _run_user_visible_stage(run, units),
# 回滚进度 UI v3 时不下发健康提示,避免前端展示灰度未启用的细化提醒。
'health_tips': _health_tips_for_run(run, units, now=now) if progress_ui_v3_enabled() else [],
'health_tips': health_tips,
'lifecycle_progress': lifecycle_progress,
'cancellation': _cancellation_projection(run),
'progress_version': int(run.progress_version or 0),
'elapsed_seconds': _elapsed_seconds(started_at=run.started_at or run.created_at, finished_at=run.finished_at, now=now),
@@ -12,7 +12,7 @@ from typing import Any
from app import db
from app.models import ShippingOrderSnapshot, ShippingNotice
from app.services.shipping_notice.export import order_field_id_values
from app.services.shipping_notice.export import _source_notice_for_order_facts, order_field_id_values
_PURPOSE_BY_CAPABILITY = {
@@ -25,7 +25,8 @@ _PURPOSE_BY_CAPABILITY = {
def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | None = None) -> dict[str, str]:
"""读取冻结策略能力与字段 ID,防止 Schema 或策略后续发布重解释任务。"""
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
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
if snapshot is None:
raise ValueError('任务没有可用于履约的冻结订单快照')
rule = (snapshot.rule_versions_json or {}).get('fulfillment_rule')
@@ -22,11 +22,24 @@ def owns_definition(definition_or_mode: dict[str, Any] | str | None) -> bool:
def owns_layout(layout: dict[str, Any] | None) -> bool:
"""只按冻结 datasets capability 选择末端值源,不按 PDF provider 分流。"""
"""仅在 Layout 明确证明为受支持的 XFA hybrid 文档时选择 datasets 值源。
``xfa_capability`` 可能因历史复用、诊断失败或派生快照而存在,不能单独
作为 PDF 类型判断依据;必须同时满足结构分析已完成、文档类型为当前支持
的 XFA kind,且 XFA 功能开关开启。
"""
from app.services.shipping_notice.document_layout.xfa_contract import XFA_SUPPORTED_DOCUMENT_KINDS
capability = layout.get('xfa_capability') if isinstance(layout, dict) and isinstance(layout.get('xfa_capability'), dict) else {}
document_kind = str(
capability.get('document_kind')
or (layout.get('document_kind') if isinstance(layout, dict) else '')
or '',
).strip()
return bool(
xfa_enabled()
and isinstance(layout, dict)
and document_kind in XFA_SUPPORTED_DOCUMENT_KINDS
and (capability.get('structure_analysis_ready') or capability.get('dataset_structure_fingerprint'))
)
@@ -1330,13 +1343,42 @@ def blind_candidate(*, profile: Any, sample: Any) -> dict[str, Any]:
metrics = build_xfa_validation_metrics(definition=definition, extraction=extraction, cross_check_summary=validation.cross_check_summary, schema_field_ids=field_ids)
rows = [{str(field['field_code']): quality_service._json_value(field.get('value')) for field in row.get('fields') or [] if isinstance(field, dict) and field.get('field_code')} for row in extraction.rows]
datasets_candidate = {'order_fields': [{'field_code': item.field_code, 'value': quality_service._json_value(item.normalized_value), 'status': 'confirmed' if item.normalized_value not in (None, '') and not item.issues else 'failed', 'field_id': item.field_id, 'scope': 'header', 'page_no': 1, 'issues': list(item.issues)} for item in extraction.header_fields], 'rows': [row for row in rows if row]}
# Reservation 专用证据区不是 XFA 的拆分映射:它和坐标模板盲测共用同一解析器。
# 视觉候选中的整单值与指定行覆盖值应参与最终 blind candidate,避免盲测与正式
# 公共建单路径出现不同结果。
visual_reservation_headers = [
item for item in visual_candidate.get('order_fields') or []
if isinstance(item, dict) and item.get('field_code') == 'reservation_id'
]
if visual_reservation_headers:
datasets_candidate['order_fields'] = [
item for item in datasets_candidate['order_fields']
if not (item.get('field_code') == 'reservation_id' and item.get('scope') == 'header')
] + visual_reservation_headers
for index, visual_row in enumerate(visual_candidate.get('rows') or []):
if index >= len(datasets_candidate['rows']) or not isinstance(visual_row, dict):
continue
if visual_row.get('reservation_id') not in (None, ''):
datasets_candidate['rows'][index]['reservation_id'] = visual_row['reservation_id']
ocr_comparison = _blind_candidate_cross_check(
visual_candidate=visual_candidate, datasets_candidate=datasets_candidate,
)
reason_codes = list(extraction.reason_codes or []) + list(validation.reason_codes or [])
if ocr_comparison['status'] == 'mismatched':
reason_codes.append('ocr_datasets_mismatch')
return {'document_id': document.id, 'table_id': visual_table_id, **datasets_candidate, 'extraction_status': extraction.status, 'reason_codes': reason_codes, 'line_row_count': len(rows), 'visual_coverage_rate': float(metrics.get('visual_coverage_rate') or 0.0), 'mirror_consistency_rate': float(metrics.get('mirror_consistency_rate') or 0.0), 'evidence_retention_rate': float(metrics.get('evidence_retention_rate') or 0.0), 'cross_checks': dict(validation.cross_check_summary or {}), 'ocr_datasets_cross_check': ocr_comparison}
return {
'document_id': document.id, 'table_id': visual_table_id, **datasets_candidate,
'extraction_status': extraction.status, 'reason_codes': reason_codes,
'line_row_count': len(rows), 'visual_coverage_rate': float(metrics.get('visual_coverage_rate') or 0.0),
'mirror_consistency_rate': float(metrics.get('mirror_consistency_rate') or 0.0),
'evidence_retention_rate': float(metrics.get('evidence_retention_rate') or 0.0),
'cross_checks': dict(validation.cross_check_summary or {}),
'ocr_datasets_cross_check': ocr_comparison,
**({
'reservation_region_status': visual_candidate['reservation_region_status'],
'reservation_region_review_reasons': visual_candidate.get('reservation_region_review_reasons') or [],
} if visual_candidate.get('reservation_region_status') == 'needs_review' else {}),
}
def blind_gate_failures(*, candidate: dict[str, Any], sample_id: int) -> tuple[list[str], dict[str, float]]:
@@ -58,7 +58,6 @@ from app.services.shipping_notice.batch_create_idempotency import (
assert_no_exact_duplicate_notices,
normalize_create_idempotency_key,
)
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
from app.services.shipping_notice.business_fingerprint import build_business_fingerprint, build_content_fingerprint
from app.services.shipping_notice.candidate_service import ensure_candidate_fulfillment_ready
from app.services.shipping_notice.candidate_validation import normalize_candidate_business_summary
@@ -883,7 +882,7 @@ def _persist_wave_lines_for_task(
Args:
case: 复核 Case。
task: 本波次新建 Task。
task: 本波次新建的 Notice。
line_keys: 本波次完整行键。
wave_no: 波次序号(从 1 起)。
revision_id: 可选确认修订 ID。
@@ -1357,9 +1356,8 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
)
# [BE-06] Notice 创建及挂接后的消费/客户绑定失败须 fail-closed 回滚。
try:
shipping_case = resolve_shipping_case_for_new_task(created_by_id=int(user_id))
task = ShippingNotice(
task_no=generate_task_no(), shipping_case_id=int(shipping_case.id), user_id=int(user_id),
task_no=generate_task_no(), user_id=int(user_id),
conversation_id=case.run.conversation_id, source_type='review_confirmation', source_file_name=document.filename,
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),
@@ -29,9 +29,6 @@ from app.services.shipping_notice.order_review_llm_contract import (
build_provenance_ref,
is_valid_evidence_ref,
)
from app.services.shipping_notice.document_layout.vc_source_evidence_integration import (
collect_vc_field_evidences,
)
from app.services.shipping_notice.order_review_llm_policy_registry import (
resolve_llm_context_policy,
)
@@ -659,35 +656,6 @@ def build_review_evidence_view(case) -> dict[str, Any]:
)
fv['field_evidences'].append(norm)
# [SOURCE 4] Vendor Comments 三来源 source_observations(Phase 4 新增)
# 追加:不覆盖/替换原有 Unit/Draft/Frozen 三源,仅扩展 LLM 上下文与工作台证据对照。
# 在 finalize 之前插入,以便 _finalize_field_evidences 正确选 primary 与 value_source。
vc_evidences = collect_vc_field_evidences(
case_or_candidate=case,
case_document_id=case_document_id,
)
for vc_ev in vc_evidences:
if not isinstance(vc_ev, dict):
continue
scope_ok = str(vc_ev.get('field_code') or vc_ev.get('source_kind') or '').strip()
line_key = vc_ev.get('line_key')
field_code = vc_ev.get('field_code')
# 反查 field_id:优先用 schema_fields key→field_code 匹配;找不到则安全跳过不伪造。
fid = None
for f_id, meta in schema_fields.items():
if isinstance(meta, dict) and str(meta.get('field_code') or '').strip() == str(field_code or '').strip():
fid = f_id
break
if not fid:
# 找不到 schema 映射的 VC 字段不注入,防止污染未定义字段。
continue
scope_meta = schema_fields.get(fid, {})
scope = 'header' if str(scope_meta.get('scope') or '').strip() == 'header' or (isinstance(scope_meta, dict) and line_key is None) else 'line'
if scope == 'line' and line_key is None:
line_key = 'header'
fv = _ensure_field(fid, scope=scope, line_key=None if scope == 'header' else str(line_key or 'header'))
fv['field_evidences'].append(vc_ev)
# finalize:选 primary + value_source 判定
for fv in header_fields.values():
_finalize_field_evidences(fv)
@@ -17,6 +17,7 @@ from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingOrderCandidate, ShippingOrderReviewCase
from app.services.shipping_notice.candidate_qualification_service import (
current_open_candidate_conflicts,
field_evidence_gap_is_non_blocking,
recalculate_candidate_qualification,
resolve_review_case_customer_resolved,
@@ -35,11 +36,6 @@ from app.services.shipping_notice.pdf_priority_adjudication import (
is_primary_pdf_source_type,
)
from app.services.shipping_notice.progress_audit_contract import PDF_PRIORITY_EVIDENCE_RANKS
from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import (
collect_vc_candidate_conflicts,
)
_VC_CONFLICT_PREFIX = 'vc:'
_EVIDENCE_GAP_REASONS = frozenset({
'evidence_missing',
'pdf_evidence_missing',
@@ -265,91 +261,6 @@ def _finding_scope(case: ShippingOrderReviewCase, *, field_code: str, line_index
return 'unscoped'
def _project_vc_candidate_conflicts(
*,
case: ShippingOrderReviewCase,
candidate: ShippingOrderCandidate,
) -> list[dict[str, Any]]:
"""
将 Vendor Comments 三来源冲突项投影为与普通字段冲突兼容的工作台格式。
核心逻辑:
- conflict_key 加 vc: 前缀,避免与 line_index:field_code 格式冲突;
- 从 detail.sources 中提取候选来源值组装 options(含 vc_source_kind 标记);
- format_invalid / region_unbound 类冲突若仅有单一来源,则仍保留一项用于展示诊断。
"""
items: list[dict[str, Any]] = []
try:
vc_items = collect_vc_candidate_conflicts(candidate)
except Exception: # noqa: BLE001 — 投影层 fail-open:异常不影响其他冲突展示
return items
for vc in vc_items:
if not isinstance(vc, dict):
continue
field_code = str(vc.get('field_code') or '').strip()
if not field_code:
continue
scope_raw = str(vc.get('scope') or 'line').strip()
line_no_safe = vc.get('line_no')
try:
line_index = int(line_no_safe) - 1 if scope_raw != 'header' and line_no_safe not in (None, '') else -1
except (TypeError, ValueError):
line_index = -1
detail = vc.get('detail') if isinstance(vc.get('detail'), dict) else {}
sources = list(detail.get('sources') or []) if isinstance(detail.get('sources'), list) else []
options: list[dict[str, Any]] = []
seen: set[str] = set()
for src in sources:
if not isinstance(src, dict):
continue
vp = src.get('value_preview')
if vp in (None, ''):
continue
key = str(vp).strip()
if key in seen:
continue
seen.add(key)
source_kind = str(src.get('source') or '').strip()
source_label = str(src.get('source_label') or source_kind).strip()
options.append({
'value_key': key,
'display_value': vp,
'sources': [source_label] if source_label else [],
'source_type': None,
'source_types': [source_kind] if source_kind else [],
'evidence_role': 'auxiliary',
'evidence_rank': None,
'vc_source_kind': source_kind,
'vc_source_kind_label': source_label,
'evidence_ref': src.get('evidence_ref'),
})
# 对于 format_invalid / region_unbound 类诊断,即使无多选值也继续投影,便于工作台展示原因。
cg_key = str(vc.get('conflict_group_key') or '').strip()
conflict_key = _VC_CONFLICT_PREFIX + (cg_key or f'{scope_raw}:{field_code}:{line_no_safe or "_"}')
line_key = vc.get('line_key') if scope_raw != 'header' else (
_line_key_for_index(case, line_index) if line_index >= 0 else None
)
items.append({
'conflict_key': conflict_key,
'field_code': field_code,
'line_index': line_index if line_index >= 0 else None,
'line_key': line_key,
'severity': str(vc.get('severity') or 'blocking'),
'reason': str(vc.get('reason') or 'vc_source_conflict_unresolved'),
'options': options,
'observation_ids': [],
'vc_kind': True,
'vc_reason': str(vc.get('reason') or ''),
'vc_conflict_group_key': cg_key or None,
'vc_detail': {
'resolution': detail.get('resolution'),
'decision_status': detail.get('decision_status'),
'format_valid': detail.get('format_valid'),
},
})
return items
def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
"""
将 Candidate 的值冲突与证据缺失分区投影,并按稳定 Finding 身份去重。
@@ -365,6 +276,11 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu
evidence_issues: list[dict[str, Any]] = []
seen: set[tuple[str, str]] = set()
raw_conflicts = list(candidate.conflicts_json or [])
open_conflict_keys = {
_stored_conflict_key(item)
for item in current_open_candidate_conflicts(candidate)
if isinstance(item, dict)
}
adjudication = _adjudication_blob(candidate)
observations = _observations_index(adjudication)
for item in raw_conflicts:
@@ -382,12 +298,20 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu
line_index = -1
value_keys = [str(v) for v in (item.get('values') or []) if v not in (None, '')]
reason = str(item.get('reason') or 'field_conflict')
# 资格层仍认为该 Finding 阻断时,投影不得静默丢弃;即使候选值不完整,
# 也必须给用户一个可解释的 Review 入口,保持 UI/Gate 同源。
is_current_open_blocking = _stored_conflict_key(item) in open_conflict_keys
is_evidence_gap = reason in _EVIDENCE_GAP_REASONS
if is_evidence_gap and field_evidence_gap_is_non_blocking(candidate, item):
continue
# 只有多个候选值不一致才属于「字段冲突待裁决」。
if len(value_keys) < 2 and not is_evidence_gap:
if len(value_keys) < 2 and not is_evidence_gap and not is_current_open_blocking:
continue
if is_current_open_blocking and len(value_keys) < 2:
reason = str(reason or 'field_conflict')
recovery_action = str(item.get('recovery_action') or 'review_current_evidence').strip() or 'review_current_evidence'
else:
recovery_action = str(item.get('recovery_action') or '').strip() or None
observation_ids = [str(oid) for oid in (item.get('observation_ids') or []) if oid]
options = _finding_source_options(item) or [
_option_display(
@@ -409,7 +333,7 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu
'reason': reason,
'options': options,
'observation_ids': observation_ids,
'recovery_action': str(item.get('recovery_action') or '').strip() or None,
'recovery_action': recovery_action,
}
# 同一 scope/field/reason 只能有一个开放 Finding;重复来源合并为一张卡。
finding_identity = (finding['conflict_key'], reason)
@@ -417,7 +341,6 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu
continue
seen.add(finding_identity)
(evidence_issues if is_evidence_gap else value_conflicts).append(finding)
value_conflicts.extend(_project_vc_candidate_conflicts(case=case, candidate=candidate))
return value_conflicts, evidence_issues
@@ -433,56 +356,6 @@ def project_review_case_evidence_issues(case: ShippingOrderReviewCase) -> list[d
return evidence_issues
def _resolve_vc_candidate_decision(
*,
candidate: ShippingOrderCandidate,
conflict_group_key: str,
chosen_value: Any,
) -> None:
"""
在 Vendor Comments merged_candidates 快照中标记对应项为人工裁决接受。
核心逻辑:定位 conflict_group_key 匹配的 merged_candidate →
覆写 decision_status=accepted / resolution=manual_review / accepted_value=chosen_value →
后续 collect_vc_candidate_conflicts 将自动跳过该项(resolution!=needs_review 或 decision=accepted/dropped)。
"""
from datetime import datetime # noqa: PLC0415 — 延迟 import 避免模块级循环依赖
structured = dict(candidate.structured_result_json or {})
extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {}
vc_merged = extraction.get('vendor_comments_merged')
if not isinstance(vc_merged, dict):
return
merged_list = vc_merged.get('merged_candidates')
if not isinstance(merged_list, list):
return
updated_list: list[dict[str, Any]] = []
for cand in merged_list:
if not isinstance(cand, dict):
updated_list.append(cand)
continue
field_code = str(cand.get('target_field_code') or cand.get('field_code') or '').strip()
scope = str(cand.get('target_scope') or cand.get('scope') or 'line').strip()
scope_ok = 'header' if scope == 'header' else 'line'
line_no_raw = cand.get('effective_line_no') or cand.get('line_no')
line_no_safe = None if line_no_raw is None else str(line_no_raw)
safe_line = str(line_no_safe or '').strip() or '_'
ckey = f'{scope_ok}:{field_code}:{safe_line}'
if ckey == str(conflict_group_key or '').strip():
cand = {
**cand,
'decision_status': 'accepted',
'resolution': 'manual_review',
'accepted_value': chosen_value,
'manual_resolved_at': datetime.utcnow().isoformat(),
}
updated_list.append(cand)
vc_merged['merged_candidates'] = updated_list
extraction['vendor_comments_merged'] = vc_merged
structured['extraction'] = extraction
candidate.structured_result_json = structured
def resolve_review_case_field_conflict(
*,
user_id: int,
@@ -525,178 +398,66 @@ def resolve_review_case_field_conflict(
)
raw_key = str(conflict_key or '').strip()
is_vc_conflict = raw_key.startswith(_VC_CONFLICT_PREFIX)
field_code = ''
line_index = -1
chosen_display: Any = None
mode = str(resolution or '').strip().lower()
if is_vc_conflict:
vc_group_key = raw_key[len(_VC_CONFLICT_PREFIX):]
try:
vc_items = collect_vc_candidate_conflicts(candidate)
except Exception as exc: # noqa: BLE001
raise NotFoundError(
'VC conflict not accessible',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
details={'conflict_key': conflict_key},
) from exc
target_vc: dict[str, Any] | None = None
for vc in vc_items:
if not isinstance(vc, dict):
continue
scope_raw = str(vc.get('scope') or 'line').strip()
scope_ok = 'header' if scope_raw == 'header' else 'line'
line_no_safe = vc.get('line_no')
safe_line = str(line_no_safe or '').strip() or '_'
fcode = str(vc.get('field_code') or '').strip()
ckey = f'{scope_ok}:{fcode}:{safe_line}'
want_cg = str(vc.get('conflict_group_key') or ckey).strip()
if want_cg == vc_group_key:
target_vc = vc
field_code = fcode
if scope_ok != 'header' and line_no_safe not in (None, ''):
try:
line_index = int(line_no_safe) - 1
except (TypeError, ValueError):
line_index = -1
break
if target_vc is None:
raise NotFoundError(
'VC conflict not found',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
details={'conflict_key': conflict_key},
)
detail = target_vc.get('detail') if isinstance(target_vc.get('detail'), dict) else {}
sources = list(detail.get('sources') or []) if isinstance(detail.get('sources'), list) else []
value_options: list[tuple[str, Any]] = []
seen: set[str] = set()
for src in sources:
if not isinstance(src, dict):
continue
vp = src.get('value_preview')
if vp in (None, ''):
continue
k = str(vp).strip()
if k in seen:
continue
seen.add(k)
value_options.append((k, vp))
if mode == 'adopt_option':
if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_options):
raise ValidationError(
'option_index is required for adopt_option',
code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID',
)
chosen_display = value_options[int(option_index)][1]
elif mode == 'custom':
if custom_value in (None, ''):
raise ValidationError(
'custom_value is required',
code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED',
)
chosen_display = custom_value
else:
raise ValidationError(
'Invalid conflict resolution',
code='SHIPPING.INVALID_CONFLICT_RESOLUTION',
details={'resolution': resolution},
)
conflicts = list(candidate.conflicts_json or [])
target_idx = -1
target: dict[str, Any] | None = None
for idx, item in enumerate(conflicts):
if isinstance(item, dict) and _stored_conflict_key(item) == raw_key:
target_idx = idx
target = item
break
if target is None or target_idx < 0:
raise NotFoundError(
'Field conflict not found',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
details={'conflict_key': conflict_key},
)
field_code = str(target.get('field') or '').strip()
try:
line_index = int(target.get('line_index')) if target.get('line_index') is not None else -1
except (TypeError, ValueError):
line_index = -1
value_keys = [str(value) for value in (target.get('values') or []) if value not in (None, '')]
if mode == 'adopt_option':
if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_keys):
raise ValidationError('option_index is required for adopt_option', code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID')
options = _finding_source_options(target)
option = options[int(option_index)] if options else _option_display(
field=field_code, value_key=value_keys[int(option_index)],
observation_ids=[str(oid) for oid in (target.get('observation_ids') or []) if oid],
observations=_observations_index(_adjudication_blob(candidate)),
)
chosen_display = option.get('display_value')
elif mode == 'custom':
if custom_value in (None, ''):
raise ValidationError('custom_value is required', code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED')
chosen_display = custom_value
else:
conflicts = list(candidate.conflicts_json or [])
target_idx = -1
target: dict[str, Any] | None = None
for idx, item in enumerate(conflicts):
if not isinstance(item, dict):
continue
key = _stored_conflict_key(item)
if key == raw_key:
target_idx = idx
target = item
break
if target is None or target_idx < 0:
raise NotFoundError(
'Field conflict not found',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
details={'conflict_key': conflict_key},
)
field_code = str(target.get('field') or '').strip()
try:
line_index = int(target.get('line_index')) if target.get('line_index') is not None else -1
except (TypeError, ValueError):
line_index = -1
value_keys = [str(v) for v in (target.get('values') or []) if v not in (None, '')]
if mode == 'adopt_option':
if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_keys):
raise ValidationError(
'option_index is required for adopt_option',
code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID',
)
options = _finding_source_options(target)
if options:
option = options[int(option_index)]
else:
observations = _observations_index(_adjudication_blob(candidate))
option = _option_display(
field=field_code,
value_key=value_keys[int(option_index)],
observation_ids=[str(oid) for oid in (target.get('observation_ids') or []) if oid],
observations=observations,
)
chosen_display = option.get('display_value')
elif mode == 'custom':
if custom_value in (None, ''):
raise ValidationError(
'custom_value is required',
code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED',
)
chosen_display = custom_value
else:
raise ValidationError(
'Invalid conflict resolution',
code='SHIPPING.INVALID_CONFLICT_RESOLUTION',
details={'resolution': resolution},
)
# 解析历史可能保留同一稳定键的重复记录;一次人工裁决必须原子清空该 Finding 身份。
conflicts = [
item for item in conflicts
if not (
isinstance(item, dict)
and _stored_conflict_key(item) == raw_key
)
]
candidate.conflicts_json = conflicts
structured = dict(candidate.structured_result_json or {})
extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {}
adjudication = dict(extraction.get('field_adjudication') or {}) if isinstance(extraction.get('field_adjudication'), dict) else {}
decisions = list(adjudication.get('decisions') or [])
updated_decisions = []
for decision in decisions:
if not isinstance(decision, dict):
continue
same_field = str(decision.get('field') or '') == field_code
same_line = True
if line_index >= 0:
try:
same_line = int(decision.get('line_index')) == line_index
except (TypeError, ValueError):
same_line = False
if same_field and same_line:
updated_decisions.append({
**decision,
'status': 'selected',
'value': chosen_display,
'resolution_method': 'manual_review',
})
else:
updated_decisions.append(decision)
adjudication['decisions'] = updated_decisions
adjudication['conflicts'] = list(conflicts)
extraction['field_adjudication'] = adjudication
structured['extraction'] = extraction
candidate.structured_result_json = structured
db.session.flush()
raise ValidationError('Invalid conflict resolution', code='SHIPPING.INVALID_CONFLICT_RESOLUTION', details={'resolution': resolution})
conflicts = [item for item in conflicts if not (isinstance(item, dict) and _stored_conflict_key(item) == raw_key)]
candidate.conflicts_json = conflicts
structured = dict(candidate.structured_result_json or {})
extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {}
adjudication = dict(extraction.get('field_adjudication') or {}) if isinstance(extraction.get('field_adjudication'), dict) else {}
decisions = list(adjudication.get('decisions') or [])
adjudication['decisions'] = [
{**decision, 'status': 'selected', 'value': chosen_display, 'resolution_method': 'manual_review'}
if isinstance(decision, dict)
and str(decision.get('field') or '') == field_code
and (line_index < 0 or int(decision.get('line_index') or -1) == line_index)
else decision
for decision in decisions
]
adjudication['conflicts'] = list(conflicts)
extraction['field_adjudication'] = adjudication
structured['extraction'] = extraction
candidate.structured_result_json = structured
db.session.flush()
# [STEP 1] 写入 Draft 人工值(两条路径共享)。
scope = 'line' if line_index >= 0 else 'header'
@@ -737,16 +498,6 @@ def resolve_review_case_field_conflict(
change = _set_value(target_line, field, chosen_display, restore_machine=False)
case.current_draft.lines_json = lines
# [STEP 2] 按冲突类型分别处理 conflict_group_key 回写,并 flush。
if is_vc_conflict:
_resolve_vc_candidate_decision(
candidate=candidate,
conflict_group_key=raw_key[len(_VC_CONFLICT_PREFIX):],
chosen_value=chosen_display,
)
db.session.flush()
# 非 VC 分支:conflicts 删除 + adjudication decisions 更新已在上半段完成并 flush。
# [STEP 3] 重算资格并写审计;由路由层 commit。
customer_resolved = resolve_review_case_customer_resolved(case=case, candidate=candidate)
recalculate_candidate_qualification(
@@ -417,28 +417,43 @@ def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[s
def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, actor_id: int) -> None:
"""短缺放行后重投影并提交正式任务当前技术 Gate,不改写库存事实。"""
"""
短缺放行后同步正式 OT Gate,并异步触发唯一明细的独立 Notice/Excel 创建。
核心逻辑:Gate 重投影不改写库存事实;复用既有 auto-fulfill Job,由 Job 再判断
是否恰好只有一条开放且可履约的明细。多条明细不会自动合并,仍由用户勾选创建 wave。
"""
task_id = getattr(case, 'confirmed_task_id', None)
if task_id is None:
return
task = db.session.get(ShippingNotice, int(task_id))
execution_id = getattr(task, 'active_process_execution_id', None) if task is not None else None
if execution_id is None:
if task is None:
return
from app.models import ShippingProcessExecution
execution = db.session.get(ShippingProcessExecution, int(execution_id))
if execution is None or int(getattr(execution, 'task_id', 0) or 0) != int(task_id):
return
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=actor_id)
# 放行是库存充分性 Gate 的受控业务事实;重投影后由统一编排器重新读取当前
# Gate 并仅入队一个技术动作,避免 API 事务中直接生成 Excel 或绕过 Worker。
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
execution_id = getattr(task, 'active_process_execution_id', None)
if execution_id is not None:
from app.models import ShippingProcessExecution
execution = db.session.get(ShippingProcessExecution, int(execution_id))
if execution is not None and int(getattr(execution, 'task_id', 0) or 0) == int(task_id):
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=actor_id)
# 放行是库存充分性 Gate 的受控业务事实;重投影后由统一编排器重新读取当前
# Gate 并仅入队一个技术动作,避免 API 事务中直接生成 Excel 或绕过 Worker。
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
submit_auto_progress(
task=task,
submit_auto_progress(
task=task,
trigger='inventory_shortage_released',
operator_id=actor_id,
commit=False,
)
# 单条自动履约必须在提交后由 Worker 创建独立 Notice,不能在 API 事务内同步生成 Excel。
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
enqueue_post_ot_auto_fulfill_job,
)
enqueue_post_ot_auto_fulfill_job(
task_no=str(task.task_no),
trigger='inventory_shortage_released',
operator_id=actor_id,
commit=False,
)
@@ -802,9 +817,23 @@ def project_review_case_line_decisions(
for key, draft_line in draft_lines.items():
proj = projections.get(key) or {}
decision = by_key.get(key)
# 正式 OT 的库存数量以当前行匹配事实为准;草稿 validation_result 只保留
# 解析阶段投影,不能因为其中没有 available_qty 就错误阻断人工出单。
fact = match_facts.get(key)
fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {}
fulfill_proj = dict(proj)
if isinstance(fact, dict):
if fact.get('available_qty') is not None:
fulfill_proj['available_qty'] = fact.get('available_qty')
if fact.get('match_result'):
fulfill_proj['match_result'] = fact.get('match_result')
if fact.get('inventory_status'):
fulfill_proj['inventory_status'] = fact.get('inventory_status')
if fact.get('inventory_source_code'):
fulfill_proj['inventory_source_code'] = fact.get('inventory_source_code')
can_fulfill, _block, rq, aq = _assess_line_fulfill_complete(
draft_line,
proj,
fulfill_proj,
schema_fields=schema_fields,
)
required = str(rq) if rq is not None else (
@@ -829,8 +858,6 @@ def project_review_case_line_decisions(
getattr(decision, 'decision_source', None) if decision is not None else None
)
decision_snap = dict(decision.snapshot_json or {}) if decision is not None else {}
fact = match_facts.get(key)
fact_detail = dict((fact or {}).get('detail_json') or {}) if isinstance(fact, dict) else {}
auto_failed = bool(
decision_snap.get('auto_fulfill_failed')
or (fact or {}).get('auto_fulfill_failed')
@@ -117,6 +117,32 @@ def record_review_progress_event(
# [STEP 3] 兑现或丢弃 Savepoint,隔离主业务事务。
if wrote:
# Review Gate 变化必须推动同一订单工作项的版本,即使 OT 的 stage/status
# 没变化;否则工作台单调合并会继续保留旧 primary_action。
task_no = str(getattr(run, 'user_task_no', None) or '').strip()
from app.models import ShippingOrderTask
order_task = (
ShippingOrderTask.query.filter_by(task_no=task_no).first()
if task_no else None
)
if order_task is None and getattr(run, 'id', None) is not None:
order_task = (
ShippingOrderTask.query
.filter_by(extraction_run_id=int(run.id))
.order_by(ShippingOrderTask.id.desc())
.first()
)
if order_task is not None:
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
sync_order_task_processing_state(
order_task,
force_progress_bump=True,
actor_type='system',
actor_id='review_progress',
reason_code='review_gate_changed',
source='order_review_progress_bridge',
correlation_id=str(case.case_no or '')[:128] or None,
)
if nested.is_active:
nested.commit()
return True
@@ -1169,6 +1169,8 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
"""返回当前有效 Case 的轻量列表;superseded 版本仅保留在历史/审计中。"""
# Run 是执行审计容器,不拥有“当前复核版本”语义。历史数据即使遗留开放状态,
# 也只能由文件 Stream 的 current_case_id 决定是否出现在 Run 详情。
from app.services.shipping_notice.order_extraction_workspace_projection import serialize_lifecycle_progress
cases = (
db.session.query(ShippingOrderReviewCase)
.join(
@@ -1197,6 +1199,8 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
'superseded_by_run_no': superseding_run.run_no if superseding_run is not None else None,
'summary': counts,
'items': items,
# 复核首屏只需 Run 级进度;禁止为此读取完整文件、候选与处理项投影。
'lifecycle_progress': serialize_lifecycle_progress(run),
}
@@ -114,22 +114,31 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
effective = str(proj.get('effective_reservation_id') or '').strip() or None
line_key = str(proj.get('line_key') or '').strip() or None
block_reason = str(proj.get('block_reason') or '').strip() or None
reservation_blocked = (
not effective
or (block_reason and 'reservation' in block_reason.lower())
or any(
int(item.get('line_index') or -1) == idx
for item in issues
line_reservation_issue = next(
(
item for item in issues
if item.get('line_index') is not None
)
and int(item.get('line_index')) == idx
and str(item.get('code') or item.get('reason_code') or '') in _RESERVATION_ISSUE_CODES
),
None,
)
reservation_block_reason = (
str((line_reservation_issue or {}).get('code') or (line_reservation_issue or {}).get('reason_code') or '').strip()
or ('effective_reservation_missing' if not effective else None)
or (block_reason if block_reason and 'reservation' in block_reason.lower() else None)
)
reservation_blocked = (
reservation_block_reason is not None
)
lines_out.append({
'line_index': idx,
'line_key': line_key,
'effective_reservation_id': effective,
'can_build': bool(proj.get('can_build', True)),
'block_reason': block_reason,
'needs_attention': reservation_blocked and not bool(proj.get('can_build', True)),
# Reservation 面板只展示自身 Gate 原因,不能泄漏库存路由 block_reason。
'block_reason': reservation_block_reason,
'needs_attention': reservation_blocked,
})
# 无 line_projections 时仍从草稿行展示当前值,便于编辑入口。
@@ -225,6 +225,11 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
for pattern in (
'%Y-%m-%d', '%Y/%m/%d', '%Y.%m.%d', '%Y%m%d',
'%m/%d/%Y', '%m-%d-%Y', '%m.%d.%Y',
# Purchase orders also commonly use a two-digit year (for
# example ``06/16/26``). ``strptime`` applies the standard
# POSIX pivot for ``%y``; the normalized result is still an
# ISO date, so downstream validators receive one type.
'%m/%d/%y', '%m-%d-%y', '%m.%d.%y',
'%d-%b-%Y', '%d-%B-%Y',
):
try:
@@ -29,9 +29,6 @@ from app.models import (
from app.services.shipping_notice.candidate_qualification_service import (
recalculate_candidate_qualification,
)
from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import (
collect_vc_candidate_conflicts,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.order_review_confirmation_service import (
confirm_review_case,
@@ -214,47 +211,6 @@ def _stp_precheck(*, validation: dict[str, Any]) -> tuple[bool, str | None]:
return True, None
def _vc_stp_precheck(*, candidate: ShippingOrderCandidate | None) -> tuple[bool, str | None]:
"""
Vendor Comments 三来源建单前再次校验 VC 合并结果(防御 CQ 快照与实际抽取结果漂移)。
核心逻辑:
1. candidate 为空 → 放行(VC 未启用场景);
2. collect_vc_candidate_conflicts 结果中若存在 severity == blocking 的原因码 → 阻断;
3. review_required 的原因码 → 阻断自动建单(允许人工,不允许 STP);
4. 任何解析异常 → fail-closed 阻断自动建单。
Args:
candidate: Case 关联的当前 Candidate。
Returns:
(允许建单?, 阻断原因码);允许时 reason 为 None。
"""
if candidate is None:
return True, None
try:
items = collect_vc_candidate_conflicts(candidate)
except Exception as exc: # noqa: BLE001 — 门禁 fail-closed
_LOGGER.warning('vc_stp_precheck collect_vc_candidate_conflicts failed: %s', exc)
return False, 'vc_source_integration_error'
review_seen = False
for item in items:
if not isinstance(item, dict):
continue
reason = str(item.get('reason') or '').strip()
severity = str(item.get('severity') or 'blocking').strip()
if severity == 'blocking' or reason in {
'vc_source_region_unbound',
'vc_source_format_invalid',
}:
return False, reason or 'vc_source_blocking_conflict'
if severity == 'review_required' and not review_seen:
review_seen = True
if review_seen:
return False, 'vc_source_conflict_unresolved'
return True, None
def _traceability_metadata(
*,
run: ShippingOrderProcessingRun,
@@ -470,40 +426,6 @@ def ensure_stp_auto_create_for_case(
'error_code': 'SHIPPING.STP_NOT_ELIGIBLE',
}
vc_allowed, vc_block_reason = _vc_stp_precheck(candidate=candidate)
if not vc_allowed:
if case.status in {'unreviewed', 'draft', 'ready'}:
case.status = 'draft'
record_fulfillment_audit(
event_type='stp_auto_create_skipped',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action='stp_vc_conflict',
actor_type='system',
actor_id=None,
result='ignored',
metadata={
'run_no': str(resolved_run.run_no),
'reason_code': vc_block_reason,
'traceability': _traceability_metadata(
run=resolved_run, case=case, candidate=candidate, validation=validation,
),
},
source='stp_auto_create',
strict=True,
)
db.session.flush()
if commit:
db.session.commit()
return {
'case_no': case.case_no,
'status': 'skipped_needs_review',
'job_id': None,
'can_auto_create': False,
'blocking_reason_codes': [vc_block_reason] if vc_block_reason else [],
'error_code': 'SHIPPING.STP_NOT_ELIGIBLE',
}
if not (
validation.get('status') == 'ready'
and bool(validation.get('can_auto_create'))
@@ -46,6 +46,7 @@ def sync_order_task_processing_state(
stage: str | None = None,
status: str | None = None,
bump_progress: bool = True,
force_progress_bump: bool = False,
actor_type: str = 'system',
actor_id: str | int | None = None,
reason_code: str | None = None,
@@ -69,6 +70,7 @@ def sync_order_task_processing_state(
stage: 统一 ShippingProcessingStage;None 表示不改。
status: OT 投影 status;None 表示不改。
bump_progress: 是否递增乐观并发版本。
force_progress_bump: 仅业务事实变化但 stage/status 不变时,是否强制推进版本。
actor_type/actor_id: 操作主体(默认 system)。
reason_code/reason: 变更原因(码 + 可选说明)。
request_id/operation_id/correlation_id: 请求与幂等关联键。
@@ -93,8 +95,9 @@ def sync_order_task_processing_state(
if next_status is not None and before_status != next_status:
order_task.status = next_status
changed = True
if changed and bump_progress:
if (changed or force_progress_bump) and bump_progress:
order_task.progress_version = before_version + 1
changed = True
if changed:
order_task.updated_at = datetime.utcnow()
db.session.flush()
@@ -958,7 +961,10 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional
'shipping_notice_id': row.shipping_notice_id,
'candidate_id': row.candidate_id,
}
row.shipping_notice_id = int(notice_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
@@ -979,7 +985,7 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional
reason_code='notice_created',
before=before,
after={
'shipping_notice_id': int(notice_id),
'shipping_notice_id': row.shipping_notice_id,
'candidate_id': row.candidate_id,
'notice_task_no': str(getattr(notice, 'task_no', None) or '') or None,
},
@@ -22,11 +22,15 @@ from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingNotice,
ShippingOrderTask,
ShippingOrderReviewCase,
ShippingOrderReviewLineDecision,
ShippingOrderReviewWaveIdempotency,
ShippingOrderReviewWaveLine,
ShippingOrderSnapshot,
)
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
from app.services.shipping_notice.tool_common import generate_task_no
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
DECISION_FULFILL,
_STATUS_BY_DECISION,
@@ -71,7 +75,8 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal]
code='SHIPPING.REVIEW_LINE_MATCH_NOT_FULFILLABLE',
details={'line_key': line.get('line_key'), 'match_result': line.get('match_result')},
)
if line.get('is_shortage'):
is_released_shortage = str((line.get('decision') or {}).get('decision_code') or '') == 'release_inventory_shortage'
if line.get('is_shortage') and not is_released_shortage:
raise ConflictError(
'Line has inventory shortage',
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
@@ -79,7 +84,7 @@ def _assert_fact_allows_fulfill(line: dict[str, Any]) -> tuple[Decimal, Decimal]
)
req = _parse_qty(line.get('required_qty'))
avail = _parse_qty(line.get('available_qty'))
if req is None or avail is None or avail < req:
if req is None or (avail is None and not is_released_shortage) or (avail is not None and avail < req and not is_released_shortage):
raise ConflictError(
'Line cannot fulfill complete quantity with current inventory facts',
code='SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY',
@@ -164,7 +169,7 @@ def create_post_ot_fulfillment_wave(
idempotency_key: 可选幂等键(独立表强约束)。
Returns:
wave_no / task_no / accepted_line_keys / skipped_line_keys / line_fulfillment /
wave_no / task_no / notice_no / accepted_line_keys / skipped_line_keys / line_fulfillment /
idempotency_row_id / idempotent_replay。
"""
keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()]
@@ -256,6 +261,7 @@ def create_post_ot_fulfillment_wave(
accepted.append(key)
wave_no = None
notice = None
if accepted:
max_wave = (
db.session.query(func.max(ShippingOrderReviewWaveLine.wave_no))
@@ -266,9 +272,67 @@ def create_post_ot_fulfillment_wave(
from app.services.shipping_notice.order_review_confirmation_service import (
_persist_wave_lines_for_task,
)
from app.services.shipping_notice.export import _source_notice_for_order_facts
source_notice = _source_notice_for_order_facts(task)
snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id)
snapshot_line_ids = {
int(snapshot.lines[int((by_key[key] or {}).get('line_index'))].id)
for key in accepted
if snapshot is not None
and (by_key[key] or {}).get('line_index') is not None
and 0 <= int((by_key[key] or {}).get('line_index')) < len(snapshot.lines)
}
if len(snapshot_line_ids) != len(accepted):
raise ConflictError(
'Selected review lines do not map to frozen order lines',
code='SHIPPING.REVIEW_LINE_SNAPSHOT_MAPPING_MISSING',
)
order_task = db.session.get(ShippingOrderTask, int(task.order_task_id)) if task.order_task_id else None
if order_task is None:
raise ConflictError(
'Formal notice is not linked to an order task',
code='SHIPPING.REVIEW_POST_OT_WAVE_ORDER_TASK_REQUIRED',
)
# [STEP 1c] 每个履约波次都是独立 Notice,直接继承客户快照;
# 对外发货通知单号只能随该 Notice 的首个 Excel 在同一事务中分配。
if task.customer_id is None:
raise ConflictError(
'Formal notice customer is required before creating a fulfillment wave',
code='SHIPPING.REVIEW_POST_OT_WAVE_CUSTOMER_REQUIRED',
)
notice = ShippingNotice(
task_no=generate_task_no(),
order_task_id=int(order_task.id),
customer_id=task.customer_id,
customer_name_snapshot=task.customer_name_snapshot,
customer_short_code_snapshot=task.customer_short_code_snapshot,
user_id=task.user_id,
conversation_id=task.conversation_id,
source_type='post_ot_fulfillment_wave',
inventory_source_code=task.inventory_source_code,
inventory_connector_type=task.inventory_connector_type,
inventory_warehouse_id=task.inventory_warehouse_id,
inventory_source_status=task.inventory_source_status,
inventory_source_method=task.inventory_source_method,
inventory_source_config_version=task.inventory_source_config_version,
inventory_routing_fingerprint=task.inventory_routing_fingerprint,
inventory_snapshot_id=task.inventory_snapshot_id,
customer_resolution_status=task.customer_resolution_status,
customer_resolution_method=task.customer_resolution_method,
customer_identity_fingerprint=task.customer_identity_fingerprint,
customer_confirmed_by=task.customer_confirmed_by,
customer_confirmed_at=task.customer_confirmed_at,
)
db.session.add(notice)
db.session.flush()
notice.customer_resolution_status = 'confirmed'
replace_notice_lines_from_snapshot(
notice_id=int(notice.id), snapshot=snapshot, snapshot_line_ids=snapshot_line_ids,
)
_persist_wave_lines_for_task(
case=case,
task=task,
task=notice,
line_keys=accepted,
wave_no=wave_no,
revision_id=None,
@@ -282,6 +346,18 @@ def create_post_ot_fulfillment_wave(
current = _active_decision(case, key)
if current is not None and current.line_status in {'task_created', 'fulfilled'}:
continue
# [STEP 2a] 短缺放行的补录库存字段必须保留在活动审计决定中,
# 不能被通用 fulfill 决定覆盖,否则独立 Excel 将丢失放行字段来源。
if (
key in accepted
and current is not None
and current.decision_code == 'release_inventory_shortage'
):
current.line_status = 'task_created'
current.task_id = int(notice.id)
current.wave_no = int(wave_no) if wave_no is not None else None
current.updated_at = now
continue
if current is not None:
current.is_active = False
current.updated_at = now
@@ -301,7 +377,7 @@ def create_post_ot_fulfillment_wave(
available_qty=avail,
reservation_id=line.get('reservation_id'),
part_number=line.get('part_number'),
task_id=int(task.id),
task_id=int(notice.id) if key in accepted else int(task.id),
wave_no=wave_no if key in accepted else (
int(current.wave_no) if current is not None and current.wave_no is not None else None
),
@@ -342,8 +418,8 @@ def create_post_ot_fulfillment_wave(
review_case_no=str(case.case_no),
run_no=str(case.run.run_no) if case.run is not None else None,
task_no=str(task.task_no),
before_json={'line_keys': keys},
after_json={
before={'line_keys': keys},
after={
'wave_no': wave_no,
'accepted_line_keys': accepted,
'skipped_line_keys': skipped,
@@ -354,10 +430,11 @@ def create_post_ot_fulfillment_wave(
result = {
'case_no': case.case_no,
'task_no': task.task_no,
'task_id': int(task.id),
'task_no': notice.task_no if notice is not None else task.task_no,
'task_id': int(notice.id) if notice is not None else int(task.id),
'review_case_id': int(case.id),
'wave_no': wave_no,
'notice_no': notice.task_no if notice is not None else None,
'accepted_line_keys': accepted,
'skipped_line_keys': skipped,
'decision_source': source,
@@ -371,8 +448,8 @@ def create_post_ot_fulfillment_wave(
idem_row = ShippingOrderReviewWaveIdempotency(
idempotency_key=persist_key,
review_case_id=int(case.id),
task_id=int(task.id),
task_no=str(task.task_no),
task_id=int(notice.id) if notice is not None else int(task.id),
task_no=str(notice.task_no if notice is not None else task.task_no),
wave_no=wave_no,
decision_source=source,
line_keys_json=_stable_line_keys(keys),
@@ -396,7 +473,10 @@ def create_post_ot_fulfillment_wave(
def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]:
"""
列出可自动/人工完整履约的行(ready+matched+非短缺+未关闭+未终态)。
列出可自动/人工履约的行(ready+matched+未关闭+未终态)。
核心逻辑:库存充足行可直接入 wave;库存不足行只有在已留下
``release_inventory_shortage`` 审计决定后才能入 wave,不能因库存事实本身被放宽。
Args:
case: 复核 Case。
@@ -415,7 +495,8 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]:
continue
if str(item.get('match_result') or '') != 'matched':
continue
if item.get('is_shortage'):
decision_code = str((item.get('decision') or {}).get('decision_code') or '')
if item.get('is_shortage') and decision_code != 'release_inventory_shortage':
continue
if item.get('user_line_status') == 'auto_fulfill_failed':
continue
@@ -423,7 +504,10 @@ def list_eligible_post_ot_line_keys(case: ShippingOrderReviewCase) -> list[str]:
continue
req = _parse_qty(item.get('required_qty'))
avail = _parse_qty(item.get('available_qty'))
if req is None or avail is None or avail < req:
is_released_shortage = decision_code == 'release_inventory_shortage'
if req is None or (avail is None and not is_released_shortage) or (
avail is not None and avail < req and not is_released_shortage
):
continue
out.append(str(item.get('line_key') or ''))
return [k for k in out if k]
@@ -1164,10 +1164,8 @@ def sync_fulfillment_gates_from_task(
idempotency_key=f'fulfill:suff:{execution.execution_no}:{match_status}:{sufficiency_ok}:{shortage_reason or "ok"}',
force=True,
)
if not sufficiency_ok:
return
# [STEP 6] excel_readiness(资格)与 artifact_generation(产物)分离
# [STEP 6] excel_readiness(资格)与 artifact_generation(产物)分离。
# 库存不足仍停在 Gate 16,但滚动履约可为已满足/已审计放行行生成下一份 Excel。
excel_error = excel_gate_error(task)
excel_ready = excel_error is None
apply_gate_outcome(
@@ -366,6 +366,7 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
'recheck_freeze_readiness',
'retry_task_creation',
'retry_inventory_preparation',
'reload_inventory_result',
'poll_inventory_preparation',
'retry_inventory_field_mapping',
'retry_inventory_matching',
@@ -380,7 +381,7 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({
'poll_freight_upload_rpa',
'retry_freight_upload_rpa',
'regenerate_manual_upload_todo',
# 仅驱动前端打开人工上传凭据登记;不得通过普通 Gate POST 直接确认。
# 仅驱动前端打开人工上传确认;不得通过普通 Gate POST 直接确认。
'mark_manual_uploaded',
})
@@ -419,9 +420,9 @@ for _code, _ui_handler in {
'open_shortage_review': {'ui_handler': 'shortage_review'},
}.items():
PROCESS_GATE_ACTION_PRESENTATION[_code].update(_ui_handler)
# 人工上传凭据登记由 Gate 授权后打开既有对话框;它不是普通 Gate mutation。
# 人工上传确认由 Gate 授权后打开既有对话框;它不是普通 Gate mutation。
PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['dispatch'] = 'dialog'
PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['ui_handler'] = 'manual_upload_evidence'
PROCESS_GATE_ACTION_PRESENTATION['mark_manual_uploaded']['ui_handler'] = 'manual_upload_confirmation'
for _code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', 'retry_inventory_from_matching'}:
PROCESS_GATE_ACTION_PRESENTATION[_code]['kind'] = 'recovery'
for _code in {'poll_inventory_preparation', 'poll_freight_upload_rpa'}:
@@ -468,11 +469,17 @@ def is_business_user_action(action_code: str | None) -> bool:
return bool(code) and code in PROCESS_GATE_BUSINESS_USER_ACTION_CODES
def inventory_preparation_primary_action(status: str | None) -> str | None:
def inventory_preparation_primary_action(
status: str | None,
blocking_reason_code: str | None = None,
) -> str | None:
"""裁决库存准备 Gate 面向业务用户的主动作。"""
normalized_status = str(status or '').strip().lower()
normalized_reason = str(blocking_reason_code or '').strip().lower()
if normalized_status == 'waiting_external':
return 'poll_inventory_preparation'
if normalized_reason in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}:
return 'reload_inventory_result'
if normalized_status in {'blocked_manual', 'blocked_retryable'}:
return 'retry_inventory_preparation'
return None
@@ -817,6 +824,8 @@ def action_belongs_to_gate(*, gate_code: str, action_code: str) -> bool:
return True
if action == 'retry_inventory_matching' and code == 'inventory_sufficiency':
return True
if action == 'reload_inventory_result' and code == 'inventory_preparation':
return True
navigation_owners = {
'open_order_review': {'order_freeze_readiness', 'order_field_extraction'},
'open_profile_review': {'document_profile_routing'},
@@ -158,7 +158,8 @@ PROCESS_GATE_PREREQUISITES: Final[dict[str, tuple[str, ...]]] = {
'inventory_field_mapping': ('inventory_preparation',),
'inventory_matching': ('inventory_field_mapping',),
'inventory_sufficiency': ('inventory_matching',),
'excel_readiness': ('inventory_sufficiency',),
# 滚动导出仅要求已完成库存匹配;库存不足仍由 inventory_sufficiency 独立阻断未导出行。
'excel_readiness': ('inventory_matching',),
'artifact_generation': ('excel_readiness',),
'freight_upload_rpa': ('artifact_generation',),
'manual_upload_handoff': ('freight_upload_rpa',),
@@ -181,6 +181,7 @@ def _dispatch_action(
'retry_duplicate_detection': _handle_recheck_task_gates,
'retry_task_creation': _handle_retry_task_creation,
'retry_inventory_preparation': _handle_retry_inventory_preparation,
'reload_inventory_result': _handle_reload_inventory_result,
'poll_inventory_preparation': _handle_retry_inventory_preparation,
'retry_inventory_field_mapping': _handle_retry_inventory_field_mapping,
'retry_inventory_matching': _handle_retry_inventory_matching,
@@ -860,6 +861,58 @@ def _handle_retry_inventory_preparation(
return outcome
def _handle_reload_inventory_result(
*,
execution: ShippingProcessExecution,
gate: ShippingProcessGate,
payload: dict[str, Any],
) -> dict[str, Any]:
"""
重读已产生的库存快照,不重新触发库存 RPA。
核心逻辑:仅复用既有快照查询、身份校验、挂接和库存加载;未命中时保留当前
RPA 超时阻断,让用户明确选择“重新获取库存”或上传库存文件。
"""
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.process_gate_bridge import (
inventory_preparation_reason_code,
sync_fulfillment_gates_from_task,
)
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
if task is None:
return {
'outcome': 'blocked_retryable',
'blocking_reason_code': 'inventory_preparation_failed',
'effective_result_json': {'findings': []},
'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False},
}
response = _try_reuse_inventory_snapshot(
task,
task_rpa_inventory_source(task) or {},
mode='reload_result',
)
if response is None:
return {
'outcome': 'blocked_retryable',
'blocking_reason_code': inventory_preparation_reason_code(task),
'effective_result_json': {'findings': [], 'snapshot_found': False},
'output_snapshot': {'action_code': 'reload_inventory_result', 'snapshot_found': False},
}
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
actor_id=payload.get('actor_user_id'),
)
return _tool_outcome(
action_code='reload_inventory_result',
response=response,
blocking_reason_code=inventory_preparation_reason_code(task),
)
def _handle_retry_inventory_field_mapping(
*,
execution: ShippingProcessExecution,
@@ -1130,42 +1183,35 @@ def _handle_regenerate_excel(
gate: ShippingProcessGate,
payload: dict[str, Any],
) -> dict[str, Any]:
"""重新生成 Excel Artifact;上传 Gate 的跨阶段恢复先精确作废旧产物。"""
"""仅在尚未生成 Excel 时重试首次生成,已有 Artifact 时拒绝重生。"""
from app.models import ShippingExportArtifact, ShippingNotice
from app.services.shipping_notice.fulfillment_workflow import generate_excel
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
recovery_definition = recovery_plan_for_action(
current_gate=gate.gate_code,
action_code='regenerate_excel_artifact',
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
existing = (
ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first()
if task is not None and task.id is not None else None
)
invalidation = None
if recovery_definition is not None:
from app.services.shipping_notice.recovery_invalidation_service import invalidate_excel_regeneration_only
invalidation = invalidate_excel_regeneration_only(
execution=execution,
attempt_id=payload.get('attempt_id'),
actor_id=payload.get('actor_user_id'),
)
if existing is not None:
return {
'outcome': 'blocked_manual',
'blocking_reason_code': 'notice_excel_already_generated',
'blocking_reason_json': {'message': '同一发货通知单只能生成一个 Excel;请创建新的发货通知单'},
'effective_result_json': {'findings': []},
'output_snapshot': {'action_code': 'regenerate_excel_artifact', 'rejected': True},
}
response = generate_excel(_task_payload(execution, payload))
outcome = _tool_outcome(
action_code='regenerate_excel_artifact',
response=response,
blocking_reason_code='artifact_generation_failed',
)
if invalidation is not None:
outcome['output_snapshot']['invalidation'] = invalidation
sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id'))
if recovery_definition is not None and gate.gate_code == 'manual_upload_handoff' and outcome['outcome'] == 'passed':
# Gate 20 是恢复动作的授权载体,不是 Excel 生成的业务终点。新 Artifact
# 生成后仍须回到人工上传交接;否则 complete_gate_attempt 会把 Gate 20 误写为 passed。
outcome.update({
'outcome': 'blocked_manual',
'blocking_reason_code': 'manual_upload_pending',
'blocking_reason_json': {'message': '新的发货 Excel 已生成,请登记人工上传凭据'},
'effective_result_json': {'findings': [], 'regenerated': True},
})
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
actor_id=payload.get('actor_user_id'),
)
return outcome
@@ -77,20 +77,15 @@ def _projection_primary_next_action(*, gate_code: str, status: str) -> str | Non
return str(value) if value else None
# 库存 RPA / 准备失败原因:统一由业务用户触发「重新获取库存」(retry_inventory_preparation)。
# 与 error_explainability_contract.EXPLAINABILITY_REASON_META 中 inventory_file_empty 等
# 的 prescribed action 保持一致;这些原因在 process_gate_contract 中分类为 retryable_tech,
# 但因 inventory_preparation 的 responsible_party='worker',历史投影会按「worker/retry_ 技术
# 动作屏蔽」规则将其从业务按钮隐藏,导致用户只能看到被降级的人工上传入口。
# 库存准备失败由业务用户显式处理;RPA 超时/耗尽优先重读已落盘结果,其他失败才重试 RPA。
def _resolve_recovery_next_action(
*, blocking: dict[str, Any] | None, full: dict[str, Any], execution: Any,
) -> tuple[str | None, bool]:
"""
单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。
[STEP 1] 库存 RPA 失败(inventory_preparation Gate + retryable_tech 原因码)统一下发
``retry_inventory_preparation``(重新获取库存),绕过历史「worker/retry_ 技术动作屏蔽」
分支,使业务用户在库存 RPA 失败时可直接重试,而非被降级为人工上传入口。
[STEP 1] 库存 RPA 超时/耗尽先下发 ``reload_inventory_result``,只重读已有结果;
其他库存准备失败下发 ``retry_inventory_preparation``,由用户明确重新触发 RPA。
[STEP 2] 货代上传 RPA 失败保持 RPA 重试;人工交接只下发凭据登记入口。
[STEP 3] 其余沿用 Gate 合同默认 next_action(primary 或按 status 推导),并保留
RecoveryPlan 复核入口兜底;技术责任方的 retry_* 仍默认仅作系统执行动作。
@@ -102,9 +97,9 @@ def _resolve_recovery_next_action(
status = str((blocking or {}).get('status') or '').strip().lower()
has_formal_task = bool(execution and getattr(execution, 'task_id', None))
# [STEP 1] 库存准备失败统一允许业务用户手动重新获取库存;人工上传是辅助输入入口。
# [STEP 1] RPA 超时/耗尽时先重读已有结果,其他库存准备失败仍允许重新运行 RPA。
if blocking_gate_code == 'inventory_preparation':
inventory_action = inventory_preparation_primary_action(status)
inventory_action = inventory_preparation_primary_action(status, normalized_reason)
if inventory_action:
return inventory_action, False
@@ -553,7 +548,7 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
break
reason_code = (blocking or {}).get('blocking_reason_code')
# [STEP] 单一裁决:由阻断原因码 / Gate 状态推导业务用户主恢复动作。
# 库存 RPA 失败统一下发「重新获取库存」,不再因 worker 责任方被技术动作屏蔽。
# 库存 RPA 超时/耗尽优先下发「重新读取库存结果」,不触发新的 RPA 请求。
next_action, technical_auto_only = _resolve_recovery_next_action(
blocking=blocking,
full=full,
@@ -586,20 +581,23 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
target for target in recovery_targets
if str(target.get('action_code') or '').strip() == 'retry_inventory_preparation'
]
# [AUTHORITY] 上传阶段的 Excel 重生仅在旧 Artifact 仍是未上传 ready 状态时授权;
# 已有成功/未知外部结果或活动 RecoveryPlan 时,后端不下发按钮。
if any(str(target.get('action_code') or '').strip() == 'regenerate_excel_artifact' for target in recovery_targets):
if not _excel_regeneration_allowed(
execution=execution,
active_recovery_plans=list(full.get('active_recovery_plans') or []),
):
recovery_targets = [
target for target in recovery_targets
if str(target.get('action_code') or '').strip() != 'regenerate_excel_artifact'
]
# 一个 Notice 只能有一个 Excel;错误导出需要创建新的 Notice,而非替代旧 Artifact。
recovery_targets = [
target for target in recovery_targets
if str(target.get('action_code') or '').strip() != 'regenerate_excel_artifact'
]
if blocking:
if next_action and is_business_user_action(str(next_action)):
allowed_actions.append(str(next_action))
# 超时或耗尽后默认重读已有结果;保留显式 RPA 重试作为备用操作,
# 让用户在确实没有迟到结果时自行决定是否发起新一轮抓取。
if (
str(blocking.get('gate_code') or '').strip().lower() == 'inventory_preparation'
and str(reason_code or '').strip().lower()
in {'inventory_rpa_timeout', 'inventory_rpa_exhausted'}
and 'retry_inventory_preparation' not in allowed_actions
):
allowed_actions.append('retry_inventory_preparation')
# Gate 20 的人工凭据登记是主动作;货代 RPA 仍允许由用户显式重试。
# 该可选动作来自 Gate 契约,不能由前端根据自动上传开关自行补出。
if (
@@ -114,7 +114,7 @@ def _primary_recovery_action(
) -> str | None:
"""按用户投影同一事实裁决当前 Gate 的可提交主恢复动作。"""
if gate.gate_code == 'inventory_preparation':
return inventory_preparation_primary_action(gate.status)
return inventory_preparation_primary_action(gate.status, gate.blocking_reason_code)
# 正式 OT 的库存匹配不再接受仅导航的旧 Gate 动作;历史行仍保留原值供审计。
if gate.gate_code == 'inventory_matching' and execution.task_id:
return 'retry_inventory_matching'
@@ -236,11 +236,11 @@ def request_gate_action(
details={'action_code': action},
)
# Gate 20 的确认必须走 mark-manual-uploaded:该 API 强制校验截图/PDF 凭据与货代回执号。
# 禁止复用普通 Gate POST,避免调用方绕过人工上传证据门槛。
# Gate 20 的确认必须走 Notice 上传确认 API:该 API 按 business_no 与唯一 Artifact
# 校验当前履约事实,禁止普通 Gate POST 绕过该边界。
if action == 'mark_manual_uploaded':
raise ValidationError(
'Manual upload confirmation requires evidence registration',
'Manual upload confirmation must use the shipping notice endpoint',
code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED',
details={'action_code': action, 'gate_code': gate.gate_code},
)
@@ -1041,7 +1041,7 @@ def apply_user_projection_fields(
'excel_readiness': 5,
'artifact_generation': 6,
'manual_upload_handoff': 7,
'upload_receipt_recorded': 8,
'manual_upload_handoff': 8,
}
current_order = gate_order.get(gate_code)
facts['inventory_milestones'] = {
@@ -254,6 +254,10 @@ def run_task_auto_progress(
task = resolve_task_from_payload({'task_no': task_no}) if task_no else None
if not task:
return tool_response(status="failed", message=f"未找到任务编号 {task_no}")
# 新 Notice 以自身 customer_id 为唯一客户事实;在创建任何 Gate/Job 前 fail-closed。
customer_gate = customer_gate_tool_response(task, operation='auto_progress')
if customer_gate is not None:
return customer_gate
# P0-3:旧 facade 不再直接跨 Gate 调用库存/匹配/Excel。所有触发统一只提交
# 当前正式 Gate;Worker 在事实落库后才创建下一个 Job。
@@ -2,8 +2,8 @@
services/shipping_notice/query_service.py
用途:发货通知读模型 — 任务查询、排序与序列化投影(含版本链、待办分类与任务中心字段)。
依赖:ShippingCase、ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、
ShippingReservation、ShippingOrderReviewCase、ShippingOrderProcessingRun、
依赖:ShippingOrderCandidate、ShippingNotice、ShippingTaskEvent、
ShippingReservation、ShippingNoticeLine、ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、ShippingOrderProcessingRun、
ShippingOrderIntake / ShippingOrderProcessingRunIntake / FileAsset、state_machine、动态订单字段编辑器、
order_review_projection(任务中心 STP retry 动作投影)。
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
@@ -34,7 +34,6 @@ from app import db
from app.core.errors import ValidationError
from app.models import (
FileAsset,
ShippingCase,
ShippingExportArtifact,
ShippingExportArtifactLine,
ShippingInventoryVerification,
@@ -46,10 +45,13 @@ from app.models import (
ShippingOrderProcessingRunIntake,
ShippingOrderLine,
ShippingOrderReviewCase,
ShippingOrderSnapshot,
ShippingOrderReviewStream,
ShippingOrderSubmission,
ShippingReservation,
ShippingNotice,
ShippingNoticeLine,
ShippingNoticeLineInventoryMatch,
ShippingTaskEvent,
ShippingUploadAttempt,
)
@@ -83,6 +85,7 @@ from app.services.shipping_notice.task_order_field_editor import (
current_line_field_values_or_empty,
current_order_field_display_or_empty,
)
from app.services.shipping_notice.po_number import normalize_po_number
EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
@@ -130,12 +133,11 @@ _REVIEW_CASE_STATUS_TODO: dict[str, str] = {
}
def _review_case_lifecycle_entries(case: ShippingOrderReviewCase) -> list[dict[str, str]]:
"""裁决建单前 Review Case 的生命周期查看入口。
def _review_case_lifecycle_projection(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""复用统一生命周期投影裁决 Review Case 的当前阶段与入口。
只有关联当前有效订单 Candidate 的 Case 才能进入订单生命周期工作台;空 Case、
已替代 Candidate 与拒绝/过期 Candidate 仍是解析或处置对象,不能因待办列表存在
而获得订单复核、库存准备或通知完成入口。
当前有效 Candidate 才能进入订单复核;空、过期或被替代 Candidate 仍属于接收解析。
此处只组装已有事实并调用 ``project_lifecycle``,不新增状态机或前端专用阶段。
"""
candidate = (
db.session.get(ShippingOrderCandidate, int(case.candidate_id))
@@ -144,11 +146,23 @@ def _review_case_lifecycle_entries(case: ShippingOrderReviewCase) -> list[dict[s
)
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
if not is_current_reviewable_candidate(candidate):
return []
from app.services.shipping_notice.lifecycle_projection import lifecycle_entries
from app.services.shipping_notice.lifecycle_projection import project_lifecycle
return lifecycle_entries(lifecycle_stage='order_review', has_candidate_context=True)
has_candidate_context = is_current_reviewable_candidate(candidate)
if has_candidate_context:
return project_lifecycle(
current_gate=None,
blocking_reason=None,
has_candidate_context=True,
processing_stage='waiting_review',
)
return project_lifecycle(
current_gate=None,
blocking_reason=None,
has_candidate_context=False,
has_intake_parse_context=False,
processing_stage='document_parsing',
)
class TaskProjection(str, Enum):
@@ -211,33 +225,16 @@ def _fulfillment_timeline(task: ShippingNotice) -> dict[str, list[dict[str, Any]
def get_task_by_ref(task_ref: str) -> ShippingNotice | None:
"""按 task_no、business_no 或数字主键查找任务;作废原号跟随替代链返回当前最新版本。"""
"""按 task_no、business_no 或数字主键精确查找 Notice。"""
value = str(task_ref or "").strip()
if not value:
return None
task = ShippingNotice.query.filter_by(task_no=value).first()
if task:
return task
case = db.session.query(ShippingCase).filter_by(business_no=value.upper()).first()
if case is not None:
visited: set[int] = set()
while case.id not in visited:
visited.add(int(case.id))
replacement = (
db.session.query(ShippingCase)
.filter_by(replaces_case_id=case.id)
.order_by(ShippingCase.id.desc())
.first()
)
if replacement is None:
break
case = replacement
return (
db.session.query(ShippingNotice)
.filter_by(shipping_case_id=case.id)
.order_by(ShippingNotice.document_version.desc(), ShippingNotice.id.desc())
.first()
)
task = ShippingNotice.query.filter_by(business_no=value.upper()).first()
if task:
return task
if value.isdigit():
return db.session.get(ShippingNotice, int(value))
return None
@@ -385,9 +382,7 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
header = current_header_field_values_or_empty(task)
payload: dict[str, Any] = {
"task_no": task.task_no,
"shipping_case_id": task.shipping_case_id,
"case_no": task.shipping_case.case_no if task.shipping_case else None,
"business_no": task.shipping_case.business_no if task.shipping_case else None,
"business_no": task.business_no,
"current_step": task.current_step,
"review_status": task.review_status,
"match_status": task.match_status,
@@ -396,9 +391,9 @@ def _task_tool_payload(task: ShippingNotice) -> dict[str, Any]:
"customer_code": header.get('customer_code'),
"customer_resolution_status": task.customer_resolution_status,
"customer_resolution_method": task.customer_resolution_method,
"customer_id": task.shipping_case.customer_id if task.shipping_case else None,
"customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None,
"customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None,
"customer_id": task.customer_id,
"customer_name_snapshot": task.customer_name_snapshot,
"customer_short_code_snapshot": task.customer_short_code_snapshot,
"ship_to": header.get('ship_to') or header.get('ship_to_address'),
"po_number": header.get('po_number'),
"required_date": header.get('required_date'),
@@ -535,18 +530,16 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
data = {
"id": task.id,
"task_no": task.task_no,
"shipping_case_id": task.shipping_case_id,
"case_no": task.shipping_case.case_no if task.shipping_case else None,
"business_no": task.shipping_case.business_no if task.shipping_case else None,
"business_no": task.business_no,
"source_type": task.source_type,
"source_file_name": task.source_file_name,
"source_file_type": task.source_file_type,
"customer_name": header.get('customer_name') or header.get('bill_to_customer'),
"customer_resolution_status": task.customer_resolution_status,
"customer_resolution_method": task.customer_resolution_method,
"customer_id": task.shipping_case.customer_id if task.shipping_case else None,
"customer_name_snapshot": task.shipping_case.customer_name_snapshot if task.shipping_case else None,
"customer_short_code_snapshot": task.shipping_case.customer_short_code_snapshot if task.shipping_case else None,
"customer_id": task.customer_id,
"customer_name_snapshot": task.customer_name_snapshot,
"customer_short_code_snapshot": task.customer_short_code_snapshot,
"current_step": task.current_step,
"review_status": task.review_status,
"match_status": task.match_status,
@@ -608,7 +601,6 @@ def serialize_task(task: ShippingNotice, projection: TaskProjection) -> dict[str
"po_number": header.get('po_number'),
"required_date": header.get('required_date'),
"step_payload": step_payload,
"upload_receipt": task.upload_receipt_json or {},
"export_version": task.export_version,
"idempotency_key": task.idempotency_key,
"lines": current_line_field_values_or_empty(task),
@@ -701,7 +693,6 @@ def _todo_category_from_task_row(
ui = resolve_task_ui_state_from_fields(
review_status=getattr(row, "review_status", None),
pending_human_reason=getattr(row, "pending_human_reason", None),
shipping_case_id=getattr(row, "shipping_case_id", None),
customer_resolution_status=getattr(row, "customer_resolution_status", None),
order_snapshot_id=getattr(row, "order_snapshot_id", None),
inventory_lines_json=getattr(row, "inventory_lines_json", None),
@@ -797,6 +788,41 @@ def _artifact_summary_for_task(task: ShippingNotice) -> dict[str, Any] | None:
}
def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
"""
投影发货通知列表需要的项次、料号、数量与当前库存事实。
核心逻辑:Notice 行定义“本通知包含哪些业务行”;当前库存只读取同 Notice、
`is_current=true` 的匹配事实。未找到匹配事实时明确返回 null,禁止由前端估算库存。
"""
if task.id is None:
return []
matches_by_line_key = {
str(item.line_key): item
for item in ShippingNoticeLineInventoryMatch.query.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
).all()
if item.line_key
}
rows = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
).all()
return [{
'line_no': (item.field_values_json or {}).get('line_no') or item.position,
'part_number': item.part_number,
'customer_part_number': (item.field_values_json or {}).get('customer_part_number'),
'reservation_id': item.reservation_id,
'shipment_qty': str(item.required_qty) if item.required_qty is not None else None,
'available_qty': matches_by_line_key.get(str(item.line_key or '')).available_qty
if matches_by_line_key.get(str(item.line_key or '')) is not None else None,
'shortage_qty': matches_by_line_key.get(str(item.line_key or '')).shortage_qty
if matches_by_line_key.get(str(item.line_key or '')) is not None else None,
'inventory_status': matches_by_line_key.get(str(item.line_key or '')).inventory_status
if matches_by_line_key.get(str(item.line_key or '')) is not None else None,
} for item in rows]
def _inject_unified_processing_fields(task: ShippingNotice, data: dict[str, Any]) -> None:
"""
将 Notice 关联 OT 的统一进度写入任务中心字段(BE-02 / UI-04)。
@@ -888,6 +914,7 @@ def _enrich_task_center_fields(
data["can_handle"] = task_can_handle(task, int(viewer_user_id), is_admin=is_admin)
data["recent_event"] = _latest_task_event_summary(task)
data["artifact_summary"] = _artifact_summary_for_task(task)
data['notice_line_summary'] = _notice_line_summary_for_task(task)
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
from app.services.shipping_notice.ui_state import build_task_ui_state
@@ -1055,20 +1082,103 @@ def get_task_visible_to_user(
return task
def list_freight_notice_groups_for_task(
task: ShippingNotice,
*,
user_id: int,
is_admin: bool = False,
) -> dict[str, Any]:
"""
按当前 Notice 所属客户 PO 返回货代上传的 Notice 聚合行。
核心逻辑:一个 business_no 就是一张独立发货 Excel;同一 PO 后续补货产生的
Notice 必须作为另一组返回。查询只取当前用户可见的 active Notice,且强制排除尚未
分配 business_no 的历史/中间对象,前端不得由 PDF 草稿行猜测分组。
Args:
task: 当前订单工作台已授权读取的正式 Notice。
user_id: 当前用户;非管理员仅返回其创建的 Notice。
is_admin: 管理员只读可见范围。
Returns:
包含 PO 及一行一个 business_no 的货代上传聚合投影。
"""
po_number = _notice_po_number(task)
if not po_number:
return {'po_number': None, 'items': [], 'reason': 'po_missing'}
candidates = ShippingNotice.query.filter(
ShippingNotice.deleted_at.is_(None),
ShippingNotice.lifecycle_status == 'active',
ShippingNotice.business_no.isnot(None),
)
if not is_admin:
candidates = candidates.filter(ShippingNotice.user_id == int(user_id))
items: list[dict[str, Any]] = []
for notice in candidates.order_by(ShippingNotice.created_at.asc(), ShippingNotice.id.asc()).all():
if _notice_po_number(notice) != po_number:
continue
business_no = str(notice.business_no or '').strip()
if not business_no:
continue
# [STEP] 主区单条菜单只消费服务端已裁决的 Notice 动作,禁止按 upload_status 猜测。
from app.services.shipping_notice.ui_state import build_task_ui_state
actions = (build_task_ui_state(notice).get('actions') or {})
available_actions = [
str(action.get('code')).strip()
for action in [actions.get('primary'), *(actions.get('secondary') or [])]
if isinstance(action, dict) and action.get('enabled') is True and str(action.get('code') or '').strip()
]
items.append({
'business_no': business_no,
'po_number': po_number,
'upload_status': notice.upload_status,
'export_file_name': notice.export_file_name,
'available_actions': available_actions,
'lines': _notice_line_summary_for_task(notice),
})
return {
'po_number': po_number,
'items': items,
'reason': None if items else 'no_business_notice',
}
def _notice_po_number(notice: ShippingNotice) -> str:
"""读取 Notice 的正式客户 PO;动态 Schema、冻结快照和兼容投影按稳定顺序回退。"""
header = current_header_field_values_or_empty(notice)
for field_code in ('customer_po_number', 'po_number'):
normalized = normalize_po_number(header.get(field_code))
if normalized:
return normalized
snapshot = None
if notice.order_snapshot_id:
snapshot = db.session.get(ShippingOrderSnapshot, notice.order_snapshot_id)
if snapshot:
for value in (snapshot.customer_po_number, (snapshot.header_values_json or {}).get('po_number')):
normalized = normalize_po_number(value)
if normalized:
return normalized
candidate = (
db.session.get(ShippingOrderCandidate, notice.source_candidate_id)
if notice.source_candidate_id else None
)
normalized = normalize_po_number(getattr(candidate, 'po_number', None))
return normalized
def _task_matches_customer_filter(task: ShippingNotice, customer: str) -> bool:
"""待办列表客户关键字过滤:匹配 case 快照、来源文件名或当前订单头客户名。"""
"""待办列表客户关键字过滤:匹配 Notice 快照、来源文件名或当前订单头客户名。"""
needle = str(customer or "").strip().lower()
if not needle:
return True
case = task.shipping_case
candidates: list[str] = []
if case is not None:
for value in (
getattr(case, "customer_name_snapshot", None),
getattr(case, "customer_short_code_snapshot", None),
):
if value:
candidates.append(str(value))
for value in (task.customer_name_snapshot, task.customer_short_code_snapshot):
if value:
candidates.append(str(value))
if task.source_file_name:
candidates.append(str(task.source_file_name))
header = current_header_field_values_or_empty(task)
@@ -1133,7 +1243,19 @@ def serialize_review_case_todo(
del is_admin
run = db.session.get(ShippingOrderProcessingRun, case.run_id) if case.run_id else None
document = db.session.get(ShippingOrderDocument, case.document_id) if case.document_id else None
lifecycle_entries = _review_case_lifecycle_entries(case)
lifecycle = _review_case_lifecycle_projection(case)
lifecycle_stage = str(lifecycle.get('lifecycle_stage') or 'unclassified')
lifecycle_entries = list(lifecycle.get('lifecycle_entries') or [])
from app.services.shipping_notice.lifecycle_projection import LIFECYCLE_STAGES
stage_index = next(
(index for index, item in enumerate(LIFECYCLE_STAGES)
if item.get('code') == lifecycle_stage),
0,
)
stage_definition = next(
(item for item in LIFECYCLE_STAGES if item['code'] == lifecycle_stage),
{'code': lifecycle_stage, 'label': '状态待同步'},
)
source_name = None
if document is not None:
source_name = str(getattr(document, "filename", None) or "").strip() or None
@@ -1191,18 +1313,19 @@ def serialize_review_case_todo(
"updated_at": case.updated_at.isoformat() if case.updated_at else None,
"created_at": case.created_at.isoformat() if case.created_at else None,
"ui_state": {
"stage": {"code": "order_review", "label": "订单复核", "index": 2, "total": 4},
# [AUTHORITY] 任务中心、批次中心和工作台均消费该入口;禁止前端按 Case
# 状态或待办类别补造订单复核权限。
"lifecycle_stage": "order_review" if lifecycle_entries else None,
"stage": {**stage_definition, "index": stage_index + 1, "total": len(LIFECYCLE_STAGES)},
# [AUTHORITY] 任务中心、批次中心和工作台均消费统一生命周期投影;
# 前端不得按 Case 状态或待办类别补造订单复核权限。
"lifecycle_stage": lifecycle_stage,
"lifecycle_entries": lifecycle_entries,
"checkpoint": {"code": "order_review", "kind": str(CheckpointKind.MUST_HUMAN), "label": "订单复核"},
"intake_parse_authorized": lifecycle_stage == "intake_parse",
"checkpoint": {"code": lifecycle_stage, "kind": str(CheckpointKind.MUST_HUMAN), "label": stage_definition['label']},
"todo": {"title": current_todo, "message": current_todo},
"actions": {"primary": ({"code": action_buttons[0], "label": "重试自动建单", "kind": "recovery", "enabled": True, "requires_confirmation": False, "disabled_reason": None, "target_surface": "order_review", "expected_gate_version": None} if action_buttons else None), "secondary": []},
"reason": {"code": f"review_case_{case.status}", "message": current_todo},
"lifecycle_status": "active",
"process_gate": None,
"checkpoint_code": "order_review",
"checkpoint_code": lifecycle_stage,
"checkpoint_kind": str(CheckpointKind.MUST_HUMAN),
"summary": {
"title": "待人工复核",
@@ -1524,11 +1647,7 @@ def _task_todo_category_sql_expr():
(reason == PH_NOTICE_TEXT_EXTRACTION_FAILED, literal("review")),
(
db.and_(
ShippingNotice.shipping_case_id.isnot(None),
db.or_(
ShippingNotice.customer_resolution_status.is_(None),
ShippingNotice.customer_resolution_status != "confirmed",
),
ShippingNotice.customer_resolution_status.in_(("pending", "needs_review", "failed", "unresolved")),
),
literal("exception"),
),
@@ -1633,10 +1752,10 @@ def _todo_tasks_base_query(
if task_no:
q = q.filter(ShippingNotice.task_no == str(task_no).strip())
if customer_needle:
q = q.outerjoin(ShippingCase, ShippingCase.id == ShippingNotice.shipping_case_id).filter(
q = q.filter(
db.or_(
ShippingCase.customer_name_snapshot.ilike(customer_like),
ShippingCase.customer_short_code_snapshot.ilike(customer_like),
ShippingNotice.customer_name_snapshot.ilike(customer_like),
ShippingNotice.customer_short_code_snapshot.ilike(customer_like),
ShippingNotice.source_file_name.ilike(customer_like),
)
)
@@ -225,6 +225,7 @@ def claim_next_shipping_notice_job() -> Job | None:
JobType.SHIPPING_STP_AUTO_CREATE,
JobType.SHIPPING_LINE_AUTO_FULFILL,
JobType.SHIPPING_POST_OT_WAVE_PROGRESS,
JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS,
],
)
@@ -133,7 +133,7 @@ def invalidate_excel_regeneration_only(
).with_for_update().all()
for artifact in artifacts:
uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).with_for_update().all()
# 成功上传或已登记货代回执是不可逆外部事实,不能用 Excel 重生覆盖。
# 成功上传或已有外部上传参考是不可逆外部事实,不能用 Excel 重生覆盖。
if artifact.status == 'uploading' or any(
upload.status == 'succeeded' or str(upload.freight_ref_no or '').strip()
for upload in uploads
@@ -0,0 +1,160 @@
"""
Reservation ID 专用证据区域解析器。
用途:从管理员圈选的 Vendor Comments 区域提取 Reservation ID 和可选行号。
依赖:reservation_id 的统一格式校验。
逻辑:只消费区域文字,不依赖客户名称、固定坐标或旧的三来源映射;无行号仅标记为未归属,最终由 Schema scope 决定表头写入或明细复核。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Any
from app.services.shipping_notice.document_layout.coordinate_region_text import visual_text_lines
from app.services.shipping_notice.reservation_id import validated_reservation_id
_ID_RE = re.compile(r"(?<!\d)(\d{5}|\d{10})(?!\d)")
_LINE_RE = re.compile(r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b|\bfor\s+line\s*#?\s*(\d+)\b", re.I)
_RESERVATION_LABEL_RE = re.compile(r"\breservation\b\s*(?:id)?\s*(?:#|:|-)?", re.I)
_VENDOR_COMMENTS_HEADING_RE = re.compile(r'^\s*vendor\s+comments?\s*:?\s*$', re.I)
_TERMS_AND_CONDITIONS_HEADING_RE = re.compile(r'^\s*terms?\s+and\s+conditions?\s*:?\s*$', re.I)
@dataclass(frozen=True)
class ReservationRegionCandidate:
value: str
line_no: int | None
scope: str
raw_text: str
status: str
@dataclass(frozen=True)
class ReservationRegionApplication:
"""Reservation 区域候选的统一业务归属结果。"""
header_value: str | None
line_values: dict[int, str]
needs_review: bool
review_reasons: tuple[str, ...]
def extract_reservation_from_region(text: str) -> list[ReservationRegionCandidate]:
"""从区域原文提取候选;有行号归明细,无行号归订单头。"""
candidates: list[ReservationRegionCandidate] = []
for raw_line in (str(text or '').splitlines() or [str(text or '')]):
line = raw_line.strip()
# A selected comments area can also contain customer numbers, quantities,
# and dates. Only a value on a Reservation-labelled line is evidence.
if not line or not _RESERVATION_LABEL_RE.search(line):
continue
ids = [validated_reservation_id(m.group(1)) for m in _ID_RE.finditer(line)]
ids = [value for value in ids if value]
if not ids:
continue
line_match = _LINE_RE.search(line)
line_no = None
if line_match:
line_no = int(line_match.group(1) or line_match.group(2))
scope = 'line' if line_no is not None else 'header'
status = 'mapped' if line_no is not None else 'header'
for value in dict.fromkeys(ids):
candidates.append(ReservationRegionCandidate(value, line_no, scope, line, status))
return candidates
def extract_reservation_from_region_text(text: str) -> list[dict[str, object]]:
"""返回 API/预览可直接序列化的统一候选 DTO。"""
return [
{
'value': item.value,
'line_no': item.line_no,
'scope': item.scope,
'raw_text': item.raw_text,
'status': item.status,
}
for item in extract_reservation_from_region(text)
]
def extract_reservation_from_vendor_comments_pages(
pages: list[tuple[int, list[dict[str, Any]]]],
) -> tuple[list[dict[str, object]], str | None]:
"""从跨页 Vendor Comments 区块提取 Reservation;仅首个 Terms 标题前的文字有效。
核心逻辑:Reservation 专区已启用时,页面坐标只是提供稳定阅读顺序,不能作为固定
页码或矩形取值依据。缺少起止锚点时返回稳定原因,由调用方转人工复核。
"""
started = False
window_lines: list[str] = []
for _page_no, glyphs in sorted(pages, key=lambda item: item[0]):
for line in visual_text_lines(glyphs):
if not started:
if _VENDOR_COMMENTS_HEADING_RE.fullmatch(line):
started = True
continue
if _TERMS_AND_CONDITIONS_HEADING_RE.fullmatch(line):
return extract_reservation_from_region_text('\n'.join(window_lines)), None
window_lines.append(line)
if not started:
return [], 'vendor_comments_anchor_missing'
return [], 'terms_and_conditions_anchor_missing'
def apply_reservation_region_candidates(
*, candidates: list[dict[str, object]], header_field_id: str | None,
line_field_id: str | None, line_count: int,
) -> ReservationRegionApplication:
"""按固定契约将专用区域候选归属到订单头和逻辑明细行。
无行号 Reservation 是整单事实,最多接受一个不同值;带行号的值仅在
Schema 启用明细 Reservation 字段时写入对应逻辑行。冲突、越界行号或
多个不同整单值必须转人工复核,不能静默猜测。
"""
_ = header_field_id
header_values: list[str] = []
line_values_by_no: dict[int, list[str]] = {}
reasons: list[str] = []
for item in candidates:
if not isinstance(item, dict):
continue
value = str(item.get('value') or '')
if not value:
continue
if item.get('scope') == 'header':
header_values.append(value)
continue
if item.get('scope') != 'line' or item.get('line_no') is None:
continue
try:
line_no = int(item['line_no'])
except (TypeError, ValueError):
reasons.append('line_out_of_range')
continue
if line_no < 1 or line_no > line_count:
reasons.append('line_out_of_range')
continue
if line_field_id:
line_values_by_no.setdefault(line_no, []).append(value)
else:
reasons.append('line_field_unavailable')
unique_headers = list(dict.fromkeys(header_values))
if len(unique_headers) > 1:
reasons.append('conflicting_header_value')
resolved_lines: dict[int, str] = {}
for line_no, values in line_values_by_no.items():
unique_values = list(dict.fromkeys(values))
if len(unique_values) > 1:
reasons.append('conflicting_line_value')
continue
resolved_lines[line_no] = unique_values[0]
return ReservationRegionApplication(
header_value=unique_headers[0] if len(unique_headers) == 1 else None,
line_values=resolved_lines,
needs_review=bool(reasons),
review_reasons=tuple(dict.fromkeys(reasons)),
)
@@ -180,6 +180,7 @@ def reserve_available_for_artifact(
artifact: ShippingExportArtifact,
verification: ShippingInventoryVerification,
released_snapshot_line_ids: set[int] | None = None,
selected_snapshot_line_ids: set[int] | None = None,
) -> list[ShippingReservation]:
"""
锁定本轮可用或已审计短缺放行的预约单,并写入 Artifact 行。
@@ -193,6 +194,7 @@ def reserve_available_for_artifact(
artifact: 已落库但尚未提交的导出 Artifact。
verification: 当前库存核验轮次。
released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。
selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时不得占用集合外行。
Returns:
本次被 Artifact 占用的预约单。
@@ -226,7 +228,12 @@ def reserve_available_for_artifact(
)
if not rows:
raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
selected = [item for item in rows if item.id in verification_lines]
selected_ids = {int(item) for item in (selected_snapshot_line_ids or set())}
selected = [
item for item in rows
if item.id in verification_lines
and (not selected_ids or int(item.snapshot_line_id) in selected_ids)
]
if not selected:
raise ConflictError('Current verification has no available reservations', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
for reservation in selected:
@@ -244,6 +251,7 @@ def current_available_snapshot_line_ids(
task: ShippingNotice,
*,
released_snapshot_line_ids: set[int] | None = None,
selected_snapshot_line_ids: set[int] | None = None,
) -> tuple[ShippingInventoryVerification, set[int]]:
"""
取得最新核验中可导出的冻结订单行。
@@ -254,6 +262,7 @@ def current_available_snapshot_line_ids(
Args:
task: 当前正式发货任务。
released_snapshot_line_ids: 已审计短缺放行对应的冻结订单行 ID 集合。
selected_snapshot_line_ids: 独立通知已固化的冻结行 ID;提供时仅返回该集合。
Returns:
(最新核验轮次, 本次可导出的冻结订单行 ID)。
@@ -288,7 +297,11 @@ def current_available_snapshot_line_ids(
ShippingReservation.id.in_(reservation_ids),
ShippingReservation.status.in_({'available', 'pending'}),
).all() if reservation_ids else []
line_ids = {item.snapshot_line_id for item in reservations}
selected_ids = {int(item) for item in (selected_snapshot_line_ids or set())}
line_ids = {
item.snapshot_line_id for item in reservations
if not selected_ids or int(item.snapshot_line_id) in selected_ids
}
if not line_ids:
raise ConflictError('No available reservations can be exported', code='SHIPPING.ROLLING_EXPORT_NOT_READY')
return verification, line_ids
@@ -147,7 +147,6 @@ def resolve_task_ui_state_from_fields(
*,
review_status: str | None,
pending_human_reason: str | None,
shipping_case_id: int | None,
customer_resolution_status: str | None,
order_snapshot_id: int | None,
inventory_lines_json: Any,
@@ -188,7 +187,7 @@ def resolve_task_ui_state_from_fields(
if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED:
return _task_ui_state(CP_NOTICE_TEXT_EXTRACTION_FAILED)
if shipping_case_id is not None and customer_resolution_status != "confirmed":
if str(customer_resolution_status or "").strip().lower() in {"pending", "needs_review", "failed", "unresolved"}:
return _task_ui_state(CP_CUSTOMER_REVIEW)
# [STEP 3] 库存、Excel 与上传只能消费冻结快照;冻结由自动推进或任务工作台执行。
@@ -254,7 +253,6 @@ def resolve_task_ui_state(task: ShippingNotice) -> TaskUiState:
return resolve_task_ui_state_from_fields(
review_status=task.review_status,
pending_human_reason=task.pending_human_reason,
shipping_case_id=task.shipping_case_id,
customer_resolution_status=task.customer_resolution_status,
order_snapshot_id=task.order_snapshot_id,
inventory_lines_json=task.inventory_lines_json,
@@ -3,7 +3,7 @@ services/shipping_notice/task_disposition_service.py
用途:集中处理发货任务的回收站、作废与归档生命周期,避免混用业务阶段和生命周期。
依赖:ShippingNotice / ShippingTaskEvent、fulfillment_audit.record_fulfillment_audit、
SQLAlchemy 行锁、ShippingCase 生命周期事实。
SQLAlchemy 行锁、ShippingNotice 生命周期事实。
逻辑:workspace 批量处置 API 通过本模块锁定任务、重算资格;TaskEvent 与 ShippingAuditEvent
双写稳定 reason_code;编排与回调阶段读取本模块的 active 判定以阻断副作用。
"""
@@ -14,8 +14,6 @@ from dataclasses import dataclass
from datetime import datetime
from typing import Any, Literal
from sqlalchemy.orm import joinedload
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
@@ -99,7 +97,7 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice:
if not normalized_task_no:
raise ValidationError('task_no is required', code='SHIPPING.TASK_NO_REQUIRED')
task = (
ShippingNotice.query.options(joinedload(ShippingNotice.shipping_case))
ShippingNotice.query
.filter(ShippingNotice.task_no == normalized_task_no)
.with_for_update()
.first()
@@ -110,11 +108,10 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice:
def _has_external_fulfillment(task: ShippingNotice) -> bool:
"""识别已提交、正在提交或已有货代回执的任务;这些任务不可在平台单方作废。"""
"""识别已提交、正在提交或已有外部上传参考的任务;这些任务不可在平台单方作废。"""
upload_status = str(task.upload_status or '').strip().lower()
return bool(
task.freight_ref_no
or task.upload_receipt_json
or upload_status in _EXTERNAL_UPLOAD_STATUSES
)
@@ -285,7 +282,8 @@ def move_task_to_recycle_bin(
# [STEP 1] 已解析或已产生内部引用的任务先作废,再进入回收站;纯 created 误建仅隐藏。
has_internal_business_record = bool(
task.shipping_case_id
task.business_no
or task.customer_id
or task.source_candidate_id
or task.match_status
or task.export_file_path
@@ -421,7 +419,8 @@ def purge_task_permanently(
# [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。
blocking_counts = {
'shipping_case': int(bool(task.shipping_case_id)),
'business_number': int(bool(task.business_no)),
'customer': int(bool(task.customer_id)),
'source_asset': int(bool(task.source_asset_id)),
'source_intake': int(bool(task.source_intake_id)),
'source_candidate': int(bool(task.source_candidate_id)),
@@ -18,7 +18,7 @@ def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingN
raise ConflictError('Revision parent mismatch', code='SHIPPING.TASK_SUPERSESSION_INVALID')
if not task_is_active(old):
return
external = bool(old.freight_ref_no or old.upload_receipt_json or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'})
external = bool(old.freight_ref_no or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'})
if external:
existing = ShippingFreightCancellation.query.filter_by(old_task_id=old.id, new_task_id=new.id).one_or_none()
if existing is None:
@@ -51,7 +51,6 @@ from app.services.shipping_notice.batch_create_idempotency import (
acquire_notice_create_locks,
assert_no_exact_duplicate_notices,
)
from app.services.shipping_notice.business_case_service import resolve_shipping_case_for_new_task
from app.services.shipping_notice.candidate_qualification_service import (
assert_customer_confirmed_before_task_create,
resolve_confirmed_bill_to_customer_id,
@@ -140,35 +139,27 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
checkpoint=CP_TASK_EXISTS,
)
shipping_case = resolve_shipping_case_for_new_task(created_by_id=payload.get("user_id"))
# [STEP] 单票建单同样要求客户已确认,禁止创建后进入 customer_review。
customer_id = _parse_optional_customer_id(payload.get("customer_id"))
assert_customer_confirmed_before_task_create(
shipping_case=shipping_case,
customer_id=customer_id,
)
task = ShippingNotice(
task_no=generate_task_no(),
shipping_case_id=shipping_case.id,
customer_id=customer_id,
user_id=payload.get("user_id"),
conversation_id=str(payload.get("conversation_id") or "").strip() or None,
source_type=str(payload.get("source_type") or "manual"),
batch_index=1,
batch_total=1,
raw_content=str(payload.get("raw_content") or "").strip() or None,
customer_resolution_status=(
'confirmed' if shipping_case.customer_id is not None else 'pending'
),
customer_resolution_method=(
'inherited' if shipping_case.customer_id is not None else None
),
customer_resolution_status='pending',
)
db.session.add(task)
log_task_event(task, "task_created", {"source_type": task.source_type})
db.session.flush()
_bind_confirmed_customer_after_task_create(
task,
shipping_case=shipping_case,
customer_id=customer_id,
candidate=None,
actor_id=payload.get("user_id"),
@@ -201,7 +192,6 @@ def _parse_optional_customer_id(raw: Any) -> int | None:
def _bind_confirmed_customer_after_task_create(
task: ShippingNotice,
*,
shipping_case: Any,
customer_id: int | None,
candidate: ShippingOrderCandidate | None,
actor_id: Any,
@@ -209,12 +199,8 @@ def _bind_confirmed_customer_after_task_create(
"""
创建 Task 后立即绑定已确认客户,避免以 pending 进入 customer_review。
核心逻辑:业务单已有客户则标记 inherited;否则用显式 customer_id 或候选 Bill-to 确认。
核心逻辑:用显式 customer_id 或候选 Bill-to 直接确认当前 Notice。
"""
if getattr(shipping_case, 'customer_id', None) is not None:
task.customer_resolution_status = 'confirmed'
task.customer_resolution_method = task.customer_resolution_method or 'inherited'
return
bind_id = customer_id or resolve_confirmed_bill_to_customer_id(candidate=candidate)
if bind_id is None:
raise ConflictError(
@@ -92,8 +92,8 @@ _PAUSE_REASON_BY_CHECKPOINT: dict[str, tuple[str, str]] = {
CP_UPLOAD_FAILED: ("upload_failed", "货代上传失败"),
CP_UPLOAD_RESULT_UNKNOWN: ("upload_result_unknown", "货代上传结果未知"),
CP_WAITING_UPLOAD: ("waiting_upload", "待人工上传登记"),
CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据"),
CP_EXPORT_READY: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"),
CP_EXPORT_GENERATED: ("wait_manual_upload", "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传"),
}
def _task_lifecycle(
@@ -470,9 +470,9 @@ def _build_task_summary(
RS_SHORTAGE_REVIEW: "库存存在缺口,当前不能继续上传货代。",
CP_READY_MATCH: "库存已就绪,系统将自动执行匹配。",
CP_READY_EXPORT: "库存匹配已满足发货条件,系统将自动生成发货文件。",
CP_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
CP_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
CP_WAITING_UPLOAD: "待人工上传登记:请下载 Excel,在货代平台上传后于本系统登记凭据。",
CP_EXPORT_READY: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。",
CP_EXPORT_GENERATED: "Excel 已生成,请下载后在货代平台上传,并在本系统确认已上传。",
CP_WAITING_UPLOAD: "待人工上传确认:请下载 Excel,在货代平台上传后于本系统确认已上传。",
CP_UPLOAD_FAILED: "货代上传失败,请下载 Excel 后人工处理。",
CP_REJECTED: "任务已驳回,无需继续处理。",
CP_UPLOADED: "任务已完成上传。",
@@ -1,8 +1,8 @@
"""
services/shipping_notice/upload_attempt_service.py
用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工回执证据。
依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、FileAsset、任务状态机。
用途:以 Excel Artifact 为边界管理货代上传尝试、回调幂等和人工确认。
依赖:ShippingExportArtifact/ShippingUploadAttempt/ShippingReservation、任务状态机。
逻辑:RPA 与人工均先创建 Attempt;仅成功 Attempt 批量将所属预约单变为 uploaded,Task 字段仅保留聚合投影。
"""
@@ -21,7 +21,6 @@ from app.models import (
ShippingNotice,
ShippingUploadAttempt,
)
from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced
def current_upload_artifact(task: ShippingNotice, artifact_id: int | None = None) -> ShippingExportArtifact:
@@ -84,7 +83,7 @@ def has_verified_upload_success(task: ShippingNotice) -> bool:
"""判断任务是否具备可审计的货代上传成功事实。
业务完成必须同时满足 Task 聚合、全部预约单和成功 Attempt 三层事实;历史字段、
单独回执号或技术流程 completed 都不能替代该判定。该函数是 UI 生命周期、批次
单独外部参考或技术流程 completed 都不能替代该判定。该函数是 UI 生命周期、批次
已完成分组与停止轮询共用的唯一成功谓词。
"""
try:
@@ -182,41 +181,36 @@ def mark_attempt_result_unknown(attempt: ShippingUploadAttempt) -> ShippingUploa
return attempt
def record_manual_upload(task: ShippingNotice, *, artifact_id: int | None, evidence_asset_no: str, operator_id: int, freight_ref_no: str | None = None) -> ShippingUploadAttempt:
"""登记人工上传成功;必须持有当前用户已上传的私有截图或回执资产。"""
asset_no = str(evidence_asset_no or '').strip()
receipt_no = str(freight_ref_no or '').strip()
if not asset_no or not receipt_no:
raise ValidationError(
'Manual upload receipt number and evidence are required',
code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED',
details={'reason_code': 'close_blocked_missing_receipt'},
)
def record_manual_upload(task: ShippingNotice, *, artifact_id: int | None, operator_id: int) -> ShippingUploadAttempt:
"""
确认指定 Excel 已由人工上传;仅记录目标 Artifact 与服务端操作人,不再采集回执或截图/PDF。
Args:
task: 目标发货通知任务,必须处于可履约状态。
artifact_id: 当前通知单唯一待上传 Excel 的 Artifact 主键;为空时服务端选择唯一可上传 Artifact。
operator_id: 服务端会话中的操作人主键,禁止由客户端伪造。
Returns:
ShippingUploadAttempt: 已成功的人工上传确认尝试。
Raises:
ConflictError: 任务或 Artifact 不再允许上传时抛出。
"""
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
if not task_is_active(task):
raise ConflictError('Inactive task cannot be manually uploaded', code='SHIPPING.TASK_LIFECYCLE_CONFLICT')
assert_task_not_supersession_blocked(task)
artifact = current_upload_artifact(task, artifact_id)
asset = get_asset_for_user(asset_no, operator_id)
if asset.upload_status != 'ready' or asset.deleted_at is not None:
raise ValidationError(
'Manual upload evidence is unavailable',
code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED',
details={'reason_code': 'close_blocked_missing_receipt'},
)
attempt = ShippingUploadAttempt(
artifact_id=artifact.id,
attempt_no=ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id).count() + 1,
mode='manual', idempotency_key=f'manual:{artifact.id}:{uuid.uuid4().hex}',
status='running', started_at=datetime.utcnow(), evidence_asset_id=asset.id, operator_id=operator_id,
status='running', started_at=datetime.utcnow(), operator_id=operator_id,
)
db.session.add(attempt)
db.session.flush()
mark_asset_referenced(asset)
return complete_attempt(
attempt, success=True, callback_id=f'manual:{attempt.id}', freight_ref_no=receipt_no,
)
return complete_attempt(attempt, success=True, callback_id=f'manual:{attempt.id}')
def void_rejected_artifact(task: ShippingNotice, *, artifact_id: int, operator_id: int, reason: str) -> ShippingExportArtifact:
@@ -0,0 +1,64 @@
"""为 ShippingNotice 增加独立发货通知业务编号。
用途:支持同一 PO 多个发货通知单各自拥有 business_no。
依赖:shipping_notices、shipping_cases、shipping_business_sequences。
逻辑:新增可空字段并从旧 Case 回填仅能唯一映射的历史 Notice;无法唯一映射的记录保留空值等待业务迁移。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'hn7o8p9q0r1s'
down_revision = 'hm6n7o8p9q0r'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""新增 Notice 编号字段并安全回填一对一历史映射。"""
inspector = sa.inspect(op.get_bind())
columns = {item['name'] for item in inspector.get_columns('shipping_notices')}
with op.batch_alter_table('shipping_notices') as batch:
if 'business_no' not in columns:
batch.add_column(sa.Column('business_no', sa.String(length=32), nullable=True))
if 'business_date' not in columns:
batch.add_column(sa.Column('business_date', sa.Date(), nullable=True))
if 'business_sequence_value' not in columns:
batch.add_column(sa.Column('business_sequence_value', sa.Integer(), nullable=True))
if 'business_numbering_rule_version' not in columns:
batch.add_column(sa.Column('business_numbering_rule_version', sa.String(length=32), nullable=True))
indexes = {item['name'] for item in inspector.get_indexes('shipping_notices')}
if 'ix_shipping_notices_business_no' not in indexes:
batch.create_index('ix_shipping_notices_business_no', ['business_no'], unique=False)
uniques = {item['name'] for item in inspector.get_unique_constraints('shipping_notices')}
if 'uq_shipping_notices_business_no' not in uniques:
batch.create_unique_constraint('uq_shipping_notices_business_no', ['business_no'])
bind = op.get_bind()
bind.execute(sa.text("""
UPDATE shipping_notices AS n
SET business_no = c.business_no,
business_date = c.business_date,
business_sequence_value = c.sequence_value,
business_numbering_rule_version = c.numbering_rule_version
FROM shipping_cases AS c
WHERE n.shipping_case_id = c.id
AND c.business_no IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM shipping_notices AS other
WHERE other.business_no = c.business_no AND other.id <> n.id
)
"""))
def downgrade() -> None:
"""移除 Notice 独立编号字段;旧 Case 编号仍保留。"""
with op.batch_alter_table('shipping_notices') as batch:
batch.drop_constraint('uq_shipping_notices_business_no', type_='unique')
batch.drop_index('ix_shipping_notices_business_no')
batch.drop_column('business_numbering_rule_version')
batch.drop_column('business_sequence_value')
batch.drop_column('business_date')
batch.drop_column('business_no')
@@ -0,0 +1,60 @@
"""将客户身份事实迁移到 ShippingNotice。
用途:支持 Notice 在不依赖 ShippingCase 的情况下完成客户确认、业务编号和履约。
依赖:shipping_notices、shipping_customers、shipping_cases。
逻辑:新增 Notice 客户字段并从历史 Case 回填;旧 Case 外键暂留只读兼容。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'ho8p9q0r1s2t'
down_revision = 'hn7o8p9q0r1s'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""新增 Notice 客户字段并回填历史 Case 客户事实。"""
inspector = sa.inspect(op.get_bind())
columns = {item['name'] for item in inspector.get_columns('shipping_notices')}
with op.batch_alter_table('shipping_notices') as batch:
if 'customer_id' not in columns:
batch.add_column(sa.Column('customer_id', sa.Integer(), nullable=True))
if 'customer_name_snapshot' not in columns:
batch.add_column(sa.Column('customer_name_snapshot', sa.String(length=200), nullable=True))
if 'customer_short_code_snapshot' not in columns:
batch.add_column(sa.Column('customer_short_code_snapshot', sa.String(length=6), nullable=True))
indexes = {item['name'] for item in inspector.get_indexes('shipping_notices')}
if 'ix_shipping_notices_customer_id' not in indexes:
batch.create_index('ix_shipping_notices_customer_id', ['customer_id'], unique=False)
foreign_keys = {item.get('name') for item in inspector.get_foreign_keys('shipping_notices')}
if 'fk_shipping_notices_customer_id' not in foreign_keys:
batch.create_foreign_key(
'fk_shipping_notices_customer_id', 'shipping_customers', ['customer_id'], ['id'],
)
bind = op.get_bind()
bind.execute(sa.text("""
UPDATE shipping_notices AS n
SET customer_id = c.customer_id,
customer_name_snapshot = c.customer_name_snapshot,
customer_short_code_snapshot = c.customer_short_code_snapshot
FROM shipping_cases AS c
WHERE n.shipping_case_id = c.id
AND n.customer_id IS NULL
AND c.customer_id IS NOT NULL
"""))
def downgrade() -> None:
"""回滚 Notice 客户字段;历史 Case 字段不受影响。"""
with op.batch_alter_table('shipping_notices') as batch:
batch.drop_constraint('fk_shipping_notices_customer_id', type_='foreignkey')
batch.drop_index('ix_shipping_notices_customer_id')
batch.drop_column('customer_short_code_snapshot')
batch.drop_column('customer_name_snapshot')
batch.drop_column('customer_id')
@@ -0,0 +1,105 @@
"""物理移除已废弃的 ShippingCase 聚合层。
用途:在历史 Notice 已自持客户与 business_no 后,删除 shipping_cases 表及 Notice 外键。
依赖:shipping_notices、shipping_customers、shipping_business_sequences。
逻辑:先检查残留客户/编号事实,再断开 Notice 旧外键并删除历史聚合表;不影响 Review Case 或收料 RPA。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision = 'hp9q0r1s2t3u'
down_revision = 'ho8p9q0r1s2t'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""校验 Notice 已完成迁移后删除 Case 表和兼容字段。"""
bind = op.get_bind()
inspector = sa.inspect(bind)
if not inspector.has_table('shipping_cases'):
return
# 历史库可能错误标记为已执行 hn/ho,但物理表仍缺少其应新增的列。
# 最终删表迁移必须先自愈这些可由旧 Case 无损恢复的事实,不能引用缺失列。
notice_columns = {item['name'] for item in inspector.get_columns('shipping_notices')}
missing_columns = [
('business_no', sa.String(length=32)),
('business_date', sa.Date()),
('business_sequence_value', sa.Integer()),
('business_numbering_rule_version', sa.String(length=32)),
('customer_id', sa.Integer()),
('customer_name_snapshot', sa.String(length=200)),
('customer_short_code_snapshot', sa.String(length=6)),
]
missing_notice_fields = {name for name, _ in missing_columns if name not in notice_columns}
with op.batch_alter_table('shipping_notices') as batch:
for name, column_type in missing_columns:
if name in missing_notice_fields:
batch.add_column(sa.Column(name, column_type, nullable=True))
# 重新读取反射信息,确保修复后的 PostgreSQL/SQLite 结构都用于后续约束和校验。
inspector = sa.inspect(bind)
notice_columns = {item['name'] for item in inspector.get_columns('shipping_notices')}
case_columns = {item['name'] for item in inspector.get_columns('shipping_cases')}
copied_fields = [
('business_no', 'business_no'),
('business_date', 'business_date'),
('business_sequence_value', 'sequence_value'),
('business_numbering_rule_version', 'numbering_rule_version'),
('customer_id', 'customer_id'),
('customer_name_snapshot', 'customer_name_snapshot'),
('customer_short_code_snapshot', 'customer_short_code_snapshot'),
]
assignments = [
f"{notice_field} = COALESCE(n.{notice_field}, c.{case_field})"
for notice_field, case_field in copied_fields
if notice_field in missing_notice_fields and case_field in case_columns
]
if assignments:
bind.execute(sa.text(f"""
UPDATE shipping_notices AS n
SET {', '.join(assignments)}
FROM shipping_cases AS c
WHERE c.id = n.shipping_case_id
"""))
# Notice 是最终事实;旧 Case 若仍有未迁移编号或客户,拒绝静默丢失。
residual = bind.execute(sa.text("""
SELECT COUNT(*)
FROM shipping_notices AS n
JOIN shipping_cases AS c ON c.id = n.shipping_case_id
WHERE (c.business_no IS NOT NULL AND n.business_no IS NULL)
OR (c.customer_id IS NOT NULL AND n.customer_id IS NULL)
""")).scalar_one()
if int(residual or 0):
raise RuntimeError(
f'shipping_case migration incomplete: {int(residual)} Notice rows still miss copied facts'
)
notice_indexes = {item['name'] for item in inspector.get_indexes('shipping_notices')}
notice_fks = inspector.get_foreign_keys('shipping_notices')
with op.batch_alter_table('shipping_notices') as batch:
for fk in notice_fks:
referred = str(fk.get('referred_table') or '')
columns = set(fk.get('constrained_columns') or [])
if referred == 'shipping_cases' and 'shipping_case_id' in columns:
if fk.get('name'):
batch.drop_constraint(fk['name'], type_='foreignkey')
if 'ix_shipping_notices_shipping_case_id' in notice_indexes:
batch.drop_index('ix_shipping_notices_shipping_case_id')
if 'shipping_case_id' in notice_columns:
batch.drop_column('shipping_case_id')
# PostgreSQL 的 UNIQUE 约束拥有同名底层索引,不能先以 index 操作删除;
# DROP TABLE 会一并清理 Case 表上的普通索引和约束索引。
op.drop_table('shipping_cases')
def downgrade() -> None:
"""不自动恢复已删除的历史 Case 数据。"""
raise RuntimeError('ShippingCase removal migration is irreversible')
+1 -1
View File
@@ -251,7 +251,7 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction
db.session.flush()
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
customer = getattr(getattr(task, 'shipping_case', None), 'customer', None)
customer = getattr(task, 'customer', None)
if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by(
extraction_id=extraction.id, role='bill_to',
).one_or_none() is None:
@@ -16,7 +16,7 @@ from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingBusinessSequence,
ShippingCase,
ShippingNotice,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
@@ -74,14 +74,14 @@ def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app):
@pytest.mark.parametrize('reference_kind', [
'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
])
def test_business_and_audit_references_block_delete(app, reference_kind: str):
"""每类业务或识别审计引用都必须在统一影响结果中阻断永久删除。"""
with app.app_context():
customer = _customer()
if reference_kind == 'case':
db.session.add(ShippingCase(case_no='CASE-LIFECYCLE', customer_id=customer.id))
if reference_kind == 'notice':
db.session.add(ShippingNotice(task_no='SN-LIFECYCLE', customer_id=customer.id))
elif reference_kind == 'sequence':
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
elif reference_kind == 'external_ref':
@@ -194,14 +194,14 @@ def test_delete_unused_customer_cascades_configurable_identity_evidence(app):
@pytest.mark.parametrize('reference_kind', [
'case', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
])
def test_delete_rechecks_every_lifecycle_blocker(app, reference_kind: str):
"""永久删除必须复用完整生命周期统计,任一业务或审计引用均返回冲突。"""
with app.app_context():
customer = _customer('BLK')
if reference_kind == 'case':
db.session.add(ShippingCase(case_no='CASE-DELETE-BLOCK', customer_id=customer.id))
if reference_kind == 'notice':
db.session.add(ShippingNotice(task_no='SN-DELETE-BLOCK', customer_id=customer.id))
elif reference_kind == 'sequence':
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
elif reference_kind == 'external_ref':
@@ -267,13 +267,13 @@ def test_delete_blocks_reference_created_after_preview(app):
preview = get_customer_lifecycle_impact(customer.id)
assert preview['can_delete'] is True
db.session.add(ShippingCase(case_no='CASE-DELETE-RACE', customer_id=customer.id))
db.session.add(ShippingNotice(task_no='SN-DELETE-RACE', customer_id=customer.id))
db.session.commit()
with pytest.raises(ConflictError) as exc_info:
delete_customer(customer.id, confirmation_short_code='RCE', reason='误建', actor_id=None)
assert exc_info.value.code == 'SHIPPING.CUSTOMER_DELETE_BLOCKED'
assert exc_info.value.details['blockers']['business_cases'] == 1
assert exc_info.value.details['blockers']['shipping_notices'] == 1
assert db.session.get(ShippingCustomer, customer.id) is not None
@@ -16,7 +16,7 @@ from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import (
ShippingBusinessSequence,
ShippingCase,
ShippingNotice,
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
@@ -71,8 +71,8 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
normalized_value='same@example.com', status='approved', source='manual',
),
ShippingCustomerExternalRef(customer_id=source.id, source_system='ERP', legacy_customer_key='LEGACY-SRC'),
ShippingCase(
case_no='CASE-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601',
ShippingNotice(
task_no='SN-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601',
customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code,
),
ShippingBusinessSequence(customer_id=source.id, business_date=date(2026, 7, 16), current_value=1),
@@ -82,7 +82,7 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
target_id = target.id
preview = get_customer_merge_impact(source_id, target_id)
assert preview['historical_references']['business_cases'] == 1
assert preview['historical_references']['shipping_notices'] == 1
# 合并预检同时展示旧识别证据与阶段一可配置证据的迁移统计。
assert preview['migrate'] == {
'identifiers': 1, 'duplicate_identifiers': 1, 'identity_evidences': 0,
@@ -105,10 +105,10 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=source_id).count() == 0
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 2
assert db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=target_id).count() == 1
historical_case = db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-HISTORY').one()
assert historical_case.customer_id == source_id
assert historical_case.business_no == 'SRC26071601'
assert historical_case.customer_short_code_snapshot == 'SRC'
historical_notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-HISTORY').one()
assert historical_notice.customer_id == source_id
assert historical_notice.business_no == 'SRC26071601'
assert historical_notice.customer_short_code_snapshot == 'SRC'
assert db.session.query(ShippingBusinessSequence).filter_by(customer_id=source_id).count() == 1
merge = db.session.get(ShippingCustomerMerge, result['merge_id'])
assert merge is not None and merge.source_customer_id_snapshot == source_id
@@ -13,7 +13,7 @@ from sqlalchemy.exc import IntegrityError
from app import db
from app.core.errors import ConflictError, ValidationError
from app.models import ShippingCase, ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent
from app.models import ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice
from app.services.admin.shipping_customer_service import (
create_customer,
create_identifier,
@@ -219,7 +219,7 @@ def test_customer_list_returns_preaggregated_reference_counts(app):
"""列表返回业务单和识别证据数量,避免管理端逐客户补查。"""
with app.app_context():
customer = _create_customer()
db.session.add(ShippingCase(case_no='CASE-COUNT-1', customer_id=customer['id']))
db.session.add(ShippingNotice(task_no='SN-COUNT-1', customer_id=customer['id']))
db.session.add(ShippingCustomerIdentifier(
customer_id=customer['id'],
identifier_type='name_alias',
@@ -231,5 +231,5 @@ def test_customer_list_returns_preaggregated_reference_counts(app):
db.session.commit()
result = list_customers({'page': 1, 'page_size': 20})
assert result['items'][0]['case_count'] == 1
assert result['items'][0]['notice_count'] == 1
assert result['items'][0]['identifier_count'] == 1
+9 -11
View File
@@ -11,7 +11,6 @@ from __future__ import annotations
from app import db
from app.models import (
FileAsset,
ShippingCase,
ShippingCustomer,
ShippingCustomerIdentifier,
ShippingIdentityDefinition,
@@ -328,7 +327,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers(
customer = ShippingCustomer(standard_name='有业务客户', short_code='BLK', status='active')
db.session.add(customer)
db.session.flush()
db.session.add(ShippingCase(case_no='CASE-DELETE-API', customer_id=customer.id))
db.session.add(ShippingNotice(task_no='SN-DELETE-API', customer_id=customer.id))
db.session.commit()
customer_id = customer.id
@@ -364,7 +363,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias',
normalized_value='SOURCEALIAS', status='approved', source='manual',
),
ShippingCase(case_no='CASE-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
ShippingNotice(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
])
db.session.commit()
source_id = source.id
@@ -397,7 +396,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
with app.app_context():
assert db.session.get(ShippingCustomer, source_id).status == 'merged'
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 1
assert db.session.query(ShippingCase).filter_by(case_no='CASE-MERGE-API').one().customer_id == source_id
assert db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one().customer_id == source_id
def test_shipping_customer_merge_api_validates_target_confirmation_and_reason(app, client):
@@ -517,11 +516,10 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
_create_users()
wrong = ShippingCustomer(standard_name='错误客户', short_code='OLD', status='active')
correct = ShippingCustomer(standard_name='正确客户', short_code='NEW', status='active')
case = ShippingCase(case_no='CASE-CORRECTION-API', numbering_status='pending')
db.session.add_all([wrong, correct, case])
db.session.add_all([wrong, correct])
db.session.flush()
task = ShippingNotice(
task_no='SN-CORRECTION-API', shipping_case_id=case.id,
task_no='SN-CORRECTION-API',
source_type='manual', customer_resolution_status='pending',
)
db.session.add(task)
@@ -529,7 +527,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
confirm_task_customer(task, customer_id=wrong.id, actor_id=None)
old_business_no = task.shipping_case.business_no
old_business_no = task.business_no
correct_id = correct.id
forbidden = client.post(
@@ -549,7 +547,7 @@ def test_shipping_customer_numbered_correction_api_preserves_old_number(app, cli
assert payload['old_business_no'] == old_business_no
assert payload['new_business_no'].startswith('NEW')
with app.app_context():
old_case = ShippingCase.query.filter_by(business_no=old_business_no).one()
replacement = ShippingCase.query.filter_by(replaces_case_id=old_case.id).one()
assert old_case.status == 'voided'
old_notice = ShippingNotice.query.filter_by(business_no=old_business_no).one()
replacement = ShippingNotice.query.filter_by(supersedes_task_id=old_notice.id).one()
assert old_notice.lifecycle_status == 'voided'
assert replacement.business_no == payload['new_business_no']
@@ -55,6 +55,8 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi
assert created['profile_code'] != 'CLIENT_SUPPLIED_CODE'
assert created['draft_revision']['revision_no'] == 1
assert created['edit_lease']['browser_session_id'] == 'wizard-tab-a'
# 主表身份必须同时冻结在 Profile 定义和两类共同视觉样本上。
assert created['definition']['main_table_id'] == 'sample-table'
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='training').count() == 1
assert db.session.get(ShippingOrderDocumentProfile, profile_id).training_sample_count == 1
@@ -115,6 +117,27 @@ def test_public_identity_signature_owns_coordinate_run_lifecycle(app, monkeypatc
assert signature['run_type'] == 'layout_signature'
def test_runtime_adapter_does_not_route_plain_pdf_by_stale_xfa_capability(monkeypatch):
"""关键断言:普通 PDF 的残留 XFA capability 不得改变正式值源路由。"""
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
monkeypatch.setattr(xfa_dataset, 'xfa_enabled', lambda: True)
stale_plain_pdf_layout = {
'document_kind': 'plain_pdf',
'xfa_capability': {'structure_analysis_ready': True},
}
assert xfa_dataset.owns_layout(stale_plain_pdf_layout) is False
supported_xfa_layout = {
'document_kind': 'xfa_hybrid',
'xfa_capability': {
'document_kind': 'xfa_hybrid',
'structure_analysis_ready': True,
},
}
assert xfa_dataset.owns_layout(supported_xfa_layout) is True
def test_wizard_xfa_mode_creates_visual_main_table_draft_before_dataset_mapping(app, monkeypatch):
"""关键断言:XFA 向导只冻结视觉主表;datasets 选择留给编辑映射,发布仍 fail-closed。"""
from hashlib import sha256
Loaded 100 of 235 files, more files were not shown because too many files have changed in this diff. Show more