feat(shipping-notice): 落地 XFA 拆分、版面签名、统一进度与处理域履约
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
3a9fbac2fc
commit
d2b3d74def
571 files changed
+78064
-24681
No files matched your search
@@ -15,7 +15,7 @@ from app.extensions import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingInventoryExternalMapping, ShippingInventoryFile, ShippingInventoryRoutingRule, ShippingInventoryRoutingRuleCondition,
|
||||
ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingTask,
|
||||
ShippingInventoryRoutingRuleVersion, ShippingInventorySource, ShippingRpaProfile, ScheduleRun, ScheduleTask, ShippingNotice,
|
||||
ShippingOrderField,
|
||||
ShippingInventoryParsingProfile,
|
||||
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
|
||||
@@ -389,7 +389,7 @@ def delete_source(source_id: int) -> None:
|
||||
for candidates in [(rule.action_payload_json or {}).get('source_codes', [])]
|
||||
if isinstance(candidates, list)
|
||||
)
|
||||
has_task = ShippingTask.query.filter_by(inventory_source_code=source_code).count() > 0
|
||||
has_task = ShippingNotice.query.filter_by(inventory_source_code=source_code).count() > 0
|
||||
has_export_run = any(
|
||||
source_code in {str(code).strip().upper() for code in source_codes}
|
||||
for run in ScheduleRun.query.all()
|
||||
|
||||
@@ -53,8 +53,8 @@ agent_types:
|
||||
conversation_mode_default: task_chat
|
||||
runtime_provider_default: hybrid
|
||||
models:
|
||||
- ShippingBatch
|
||||
- ShippingTask
|
||||
- ShippingNotice
|
||||
- ShippingOrderTask
|
||||
- ShippingTaskEvent
|
||||
required_fields: []
|
||||
default_capabilities:
|
||||
|
||||
@@ -71,18 +71,12 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
task = get_task_by_ref(task_id) if task_id else None
|
||||
batch = get_batch_by_no(batch_no) if batch_no else None
|
||||
session_id = str(getattr(ctx.session, 'session_id', '') or '')
|
||||
if task is None and batch is not None:
|
||||
focus_task_no = str(batch.current_focus_task_no or '').strip()
|
||||
if focus_task_no:
|
||||
candidate = get_task_by_ref(focus_task_no)
|
||||
if candidate is not None and candidate.batch_id == batch.id:
|
||||
task = candidate
|
||||
if task is not None:
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session_id,
|
||||
'task_no': task.task_no,
|
||||
'batch_no': task.batch.batch_no if task.batch is not None else None,
|
||||
'batch_no': None,
|
||||
'ui_state': build_task_ui_state(task),
|
||||
}
|
||||
if batch is not None:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/file_assets/cleanup.py
|
||||
|
||||
用途:过期未引用 FileAsset 与关联 intake 的清理编排。
|
||||
依赖:file_assets.storage、models.FileAsset/ShippingNoticeIntake。
|
||||
依赖:file_assets.storage、models.FileAsset/ShippingOrderIntake。
|
||||
逻辑:由排程或 file_asset_cleanup Job 调用;先标记 expired → 删 MinIO → 成功后 mark deleted;
|
||||
MinIO 删除失败不伪装成功,保留记录供下次重试。
|
||||
"""
|
||||
@@ -15,7 +15,7 @@ from datetime import datetime
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.models import FileAsset, ShippingNoticeIntake
|
||||
from app.models import FileAsset, ShippingOrderIntake
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -49,10 +49,10 @@ def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
|
||||
stats = {'scanned': len(assets), 'expired': 0, 'deleted': 0, 'errors': 0}
|
||||
for asset in assets:
|
||||
consumed = (
|
||||
db.session.query(ShippingNoticeIntake.id)
|
||||
db.session.query(ShippingOrderIntake.id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.asset_id == asset.id,
|
||||
ShippingNoticeIntake.parse_status == 'consumed',
|
||||
ShippingOrderIntake.asset_id == asset.id,
|
||||
ShippingOrderIntake.parse_status == 'consumed',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
@@ -61,11 +61,11 @@ def cleanup_expired_temporary_assets(*, limit: int = 100) -> dict[str, int]:
|
||||
stats['expired'] += 1
|
||||
asset.lifecycle_status = 'expired'
|
||||
(
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.asset_id == asset.id,
|
||||
ShippingNoticeIntake.consumed_at.is_(None),
|
||||
ShippingNoticeIntake.parse_status.notin_(('consumed', 'cancelled')),
|
||||
ShippingOrderIntake.asset_id == asset.id,
|
||||
ShippingOrderIntake.consumed_at.is_(None),
|
||||
ShippingOrderIntake.parse_status.notin_(('consumed', 'cancelled')),
|
||||
)
|
||||
.update({'parse_status': 'expired', 'updated_at': now}, synchronize_session=False)
|
||||
)
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
"""
|
||||
services/schedule/shipping_audit_retention_job.py
|
||||
|
||||
用途:货代统一审计到期清理与哈希链抽样校验的 platform Job 入口。
|
||||
依赖:audit_query_service.purge_expired_shipping_audit_events、
|
||||
用途:货代统一审计到期清理、XFA 加密快照到期清理与哈希链抽样校验的 platform Job 入口。
|
||||
依赖:audit_query_service.purge_expired_shipping_audit_events / purge_expired_xfa_audit_snapshots、
|
||||
audit_snapshot_service.verify_event_hash_chain、progress_feature_flags.audit_retention_days。
|
||||
逻辑:platform_api_path=shipping-audit-retention 时由 job_registry 调用;仅清理
|
||||
retention_expires_at 非空且已到期的事件;新写入事件永久保留(expires=None)永不删除;
|
||||
PostgreSQL 上 purge 在同事务设置 hxops.shipping_audit_purge=1,配合 append-only DELETE 触发器;
|
||||
可选对近期聚合抽样校验 previous_event_hash / event_hash 链完整性。
|
||||
retention_expires_at 非空且已到期的事件与 XFA 快照;新写入事件永久保留(expires=None)
|
||||
永不删除;XFA 快照默认 3 年;哈希校验抽样检测篡改断链。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,7 +16,10 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_query_service import purge_expired_shipping_audit_events
|
||||
from app.services.shipping_notice.audit_query_service import (
|
||||
purge_expired_shipping_audit_events,
|
||||
purge_expired_xfa_audit_snapshots,
|
||||
)
|
||||
from app.services.shipping_notice.audit_snapshot_service import verify_event_hash_chain
|
||||
from app.services.shipping_notice.progress_feature_flags import audit_retention_days
|
||||
|
||||
@@ -94,6 +96,11 @@ def run_shipping_audit_retention_schedule(task: Any, run: Any) -> dict[str, Any]
|
||||
actor_id=f'schedule:{getattr(task, "id", "unknown")}',
|
||||
)
|
||||
result['retention_days'] = audit_retention_days()
|
||||
result['xfa_snapshots'] = purge_expired_xfa_audit_snapshots(
|
||||
limit=int(params.get('xfa_snapshot_limit') or params.get('limit') or 1000),
|
||||
dry_run=dry_run,
|
||||
actor_id=f'schedule:{getattr(task, "id", "unknown")}',
|
||||
)
|
||||
|
||||
hash_verify_enabled = bool(
|
||||
current_app.config.get('SHIPPING_NOTICE_AUDIT_HASH_VERIFY_ENABLED', True)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/attachment_selection.py
|
||||
|
||||
用途:基于 Intake 快览事实生成可审计的附件选择计划。
|
||||
依赖:ShippingNoticeIntake、标准库正则与哈希;只读取 structured_result_json,不回读 Document/布局结果。
|
||||
依赖:ShippingOrderIntake、标准库正则与哈希;只读取 structured_result_json,不回读 Document/布局结果。
|
||||
逻辑:发送阶段调用本文件,把当前批次附件目录转换为“为何选择/为何跳过”的稳定计划;
|
||||
后续深度解析、预算扩展与审计都应复用这份快照,而不是重新猜测附件优先级。
|
||||
"""
|
||||
@@ -13,7 +13,7 @@ import re
|
||||
from collections import defaultdict
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingNoticeIntake
|
||||
from app.models import ShippingOrderIntake
|
||||
|
||||
_PO_HINT_RE = re.compile(r'\b(?:PO[-_ ]*)?([A-Z]{0,4}\d{5,})\b', re.IGNORECASE)
|
||||
_TOKEN_RE = re.compile(r'[A-Z0-9]{4,}', re.IGNORECASE)
|
||||
@@ -57,7 +57,7 @@ _NEGATIVE_NAME_HINTS: tuple[tuple[str, int, str], ...] = (
|
||||
)
|
||||
|
||||
|
||||
def _structured(intake: ShippingNoticeIntake) -> dict[str, Any]:
|
||||
def _structured(intake: ShippingOrderIntake) -> dict[str, Any]:
|
||||
"""读取 Intake 快览摘要;缺失时返回空对象,调用方决定是否视为不可选。"""
|
||||
return intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
|
||||
@@ -134,7 +134,7 @@ def _score_attachment(*, filename: str, mime_type: str, size: int, mail_text: st
|
||||
|
||||
def build_attachment_selection_snapshot(
|
||||
*,
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
intakes: list[ShippingOrderIntake],
|
||||
max_initial_attachments: int = 2,
|
||||
max_initial_concurrency: int = 2,
|
||||
expansion_batch_size: int = 2,
|
||||
|
||||
@@ -1,15 +1,16 @@
|
||||
"""
|
||||
services/shipping_notice/audit_query_service.py
|
||||
|
||||
用途:管理员货代审计查询、关联链追溯、权限裁剪脱敏详情、哈希链校验、受控导出与到期清理。
|
||||
依赖:ShippingAuditEvent、audit_service、audit_snapshot_service、fulfillment_audit、
|
||||
progress_audit_contract、SQLAlchemy。
|
||||
逻辑:由 admin API 调用;列表/详情/导出/关联链均做管理员访问审计(失败阻断查询);
|
||||
敏感 before/after/diff 仅当调用方具备 shipping_notice.audit_sensitive_read;
|
||||
支持 event_type_group=review_workbench|chat_workbench|process_gate|
|
||||
candidate_qualification|workflow_node;支持 candidate_no / gate_code 筛选;
|
||||
PostgreSQL 清理前在同事务 set_config('hxops.shipping_audit_purge','1'),
|
||||
以便 DB 触发器仅放行已到期行的 DELETE;SQLite/测试仍用 Core DELETE + ORM 守卫。
|
||||
用途:管理员货代审计查询、关联链追溯、权限裁剪脱敏详情、哈希链校验、受控导出与到期清理;
|
||||
XFA 加密完整快照的敏感读(每次再审计);另提供业务用户 Case 审计时间线(无敏感快照)。
|
||||
依赖:ShippingAuditEvent、ShippingXfaAuditSnapshot、audit_service、audit_snapshot_service、
|
||||
fulfillment_audit、progress_audit_contract、SQLAlchemy。
|
||||
逻辑:由 admin API 调用列表/详情/导出/关联链/完整快照读(失败阻断查询);
|
||||
workspace `list_review_case_audit_timeline` / `list_task_audit_timeline` 返回业务摘要;
|
||||
任务工作台时间线按 task_no 种子 + 关联键扩张,不另建事件表。
|
||||
敏感 before/after/diff 与 XFA 完整快照仅当调用方具备 shipping_notice.audit_sensitive_read;
|
||||
普通导出仅脱敏摘要,禁止完整密文/明文;支持 event_type_group 与关联键筛选;
|
||||
PostgreSQL 清理前 set_config purge GUC;XFA 快照到期清理使用独立 GUC。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,12 +27,22 @@ from app import db
|
||||
from app.core.errors import NotFoundError, ServiceUnavailableError, ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.audit_snapshot_service import verify_event_hash_chain
|
||||
from app.services.shipping_notice.audit_snapshot_service import (
|
||||
decrypt_xfa_audit_snapshot_row,
|
||||
get_xfa_audit_snapshot_row,
|
||||
serialize_xfa_audit_snapshot_summary,
|
||||
verify_event_hash_chain,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import resolve_request_audit_context
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
AUDIT_SNAPSHOT_ALLOWED_KEYS,
|
||||
CANDIDATE_QUALIFICATION_AUDIT_EVENT_TYPES,
|
||||
CHAT_WORKBENCH_AUDIT_EVENT_TYPES,
|
||||
CONVERSATION_PROCESSING_TASK_AUDIT_EVENT_TYPES,
|
||||
FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES,
|
||||
ORDER_DOCUMENT_AUDIT_EVENT_TYPES,
|
||||
ORDER_EMAIL_ADJUDICATION_AUDIT_EVENT_TYPES,
|
||||
ORDER_SUBMISSION_INTAKE_AUDIT_EVENT_TYPES,
|
||||
PROCESS_GATE_AUDIT_EVENT_TYPES,
|
||||
REVIEW_WORKBENCH_AUDIT_EVENT_TYPES,
|
||||
WORKFLOW_NODE_AUDIT_EVENT_TYPES,
|
||||
@@ -162,7 +173,9 @@ def serialize_shipping_audit_event(
|
||||
'retention_expires_at': _iso(event.retention_expires_at),
|
||||
'created_at': _iso(event.created_at),
|
||||
'has_snapshots': bool(event.before_snapshot_json or event.after_snapshot_json),
|
||||
'has_xfa_full_snapshots': _has_xfa_full_snapshot_refs(event),
|
||||
'sensitive_redacted': False,
|
||||
'xfa_snapshot_refs': _xfa_snapshot_refs_from_event(event),
|
||||
}
|
||||
if include_snapshots:
|
||||
# [STEP 1] 敏感事件无权限时脱敏:不回传 before/after/diff 正文。
|
||||
@@ -182,12 +195,136 @@ def serialize_shipping_audit_event(
|
||||
return payload
|
||||
|
||||
|
||||
def _xfa_snapshot_refs_from_event(event: ShippingAuditEvent) -> list[dict[str, Any]]:
|
||||
"""从 context_refs / evidence_refs 提取 XFA 完整快照引用(不含密文)。"""
|
||||
refs: list[dict[str, Any]] = []
|
||||
context = event.context_refs_json if isinstance(event.context_refs_json, dict) else {}
|
||||
for key, purpose in (
|
||||
('snapshot_before_ref', 'before'),
|
||||
('snapshot_after_ref', 'after'),
|
||||
('snapshot_full_ref', 'full'),
|
||||
):
|
||||
value = str(context.get(key) or '').strip()
|
||||
if value:
|
||||
refs.append({'purpose': purpose, 'snapshot_ref': value})
|
||||
evidence = event.evidence_refs_json if isinstance(event.evidence_refs_json, list) else []
|
||||
for item in evidence:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if str(item.get('kind') or '') != 'xfa_audit_snapshot':
|
||||
continue
|
||||
ref = str(item.get('snapshot_ref') or '').strip()
|
||||
if not ref:
|
||||
continue
|
||||
if any(row['snapshot_ref'] == ref for row in refs):
|
||||
continue
|
||||
refs.append({
|
||||
'purpose': str(item.get('purpose') or 'full'),
|
||||
'snapshot_ref': ref,
|
||||
'plaintext_sha256': item.get('plaintext_sha256'),
|
||||
})
|
||||
return refs
|
||||
|
||||
|
||||
def _has_xfa_full_snapshot_refs(event: ShippingAuditEvent) -> bool:
|
||||
"""事件是否挂接了 XFA 加密完整快照引用。"""
|
||||
return bool(_xfa_snapshot_refs_from_event(event))
|
||||
|
||||
|
||||
def get_xfa_audit_full_snapshot(
|
||||
*,
|
||||
admin_user_id: int,
|
||||
request_id: str | None,
|
||||
snapshot_ref: str,
|
||||
include_sensitive: bool,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
读取 XFA 加密完整快照。
|
||||
|
||||
核心逻辑:无 shipping_notice.audit_sensitive_read 时仅返回脱敏摘要并再写访问审计;
|
||||
有权限时解密完整载荷,并追加 xfa_audit_snapshot_viewed 审计事件(同事务提交)。
|
||||
|
||||
Args:
|
||||
admin_user_id: 管理员用户 ID。
|
||||
request_id: 请求关联 ID。
|
||||
snapshot_ref: 快照稳定引用。
|
||||
include_sensitive: 调用方是否具备敏感读权限。
|
||||
|
||||
Returns:
|
||||
{summary, payload|null, sensitive_redacted}。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 快照不存在。
|
||||
ValidationError: 密文篡改。
|
||||
ServiceUnavailableError: 密钥缺失导致无法解密。
|
||||
"""
|
||||
row = get_xfa_audit_snapshot_row(snapshot_ref)
|
||||
summary = serialize_xfa_audit_snapshot_summary(row)
|
||||
if not include_sensitive:
|
||||
append_shipping_audit_event(
|
||||
event_type='xfa_audit_snapshot_viewed',
|
||||
aggregate_type='shipping_xfa_audit_snapshot',
|
||||
aggregate_id=row.snapshot_ref,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
request_id=request_id,
|
||||
operation_id=request_id,
|
||||
action='read_xfa_snapshot_redacted',
|
||||
result='success',
|
||||
sensitivity_level='normal',
|
||||
metadata={
|
||||
'snapshot_ref': row.snapshot_ref,
|
||||
'purpose': row.purpose,
|
||||
'sensitive_redacted': True,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
'summary': summary,
|
||||
'payload': None,
|
||||
'sensitive_redacted': True,
|
||||
}
|
||||
|
||||
# [STEP 1] 解密并校验完整性。
|
||||
try:
|
||||
payload = decrypt_xfa_audit_snapshot_row(row)
|
||||
except ServiceUnavailableError:
|
||||
raise
|
||||
# [STEP 2] 每次完整读必须再审计;审计失败则回滚,禁止无痕泄露。
|
||||
append_shipping_audit_event(
|
||||
event_type='xfa_audit_snapshot_viewed',
|
||||
aggregate_type='shipping_xfa_audit_snapshot',
|
||||
aggregate_id=row.snapshot_ref,
|
||||
actor_type='admin',
|
||||
actor_id=admin_user_id,
|
||||
request_id=request_id,
|
||||
operation_id=request_id,
|
||||
action='read_xfa_snapshot_full',
|
||||
result='success',
|
||||
sensitivity_level='sensitive',
|
||||
metadata={
|
||||
'snapshot_ref': row.snapshot_ref,
|
||||
'purpose': row.purpose,
|
||||
'plaintext_sha256': row.plaintext_sha256,
|
||||
'sensitive_redacted': False,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
'summary': summary,
|
||||
'payload': payload,
|
||||
'sensitive_redacted': False,
|
||||
}
|
||||
|
||||
|
||||
def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
"""按管理员筛选条件收窄查询;禁止自由文本全文检索正文。"""
|
||||
event_type_group = str(filters.get('event_type_group') or '').strip().lower()
|
||||
# [STEP] 事件分组:与 progress_audit_contract 各字典一一对齐,禁止前端私造分组名。
|
||||
if event_type_group in {'review_workbench', 'order_review_workbench'}:
|
||||
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(REVIEW_WORKBENCH_AUDIT_EVENT_TYPES)))
|
||||
elif event_type_group in {'formal_task_edit', 'formal_task'}:
|
||||
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(FORMAL_TASK_EDIT_AUDIT_EVENT_TYPES)))
|
||||
elif event_type_group in {'chat_workbench', 'chat'}:
|
||||
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(CHAT_WORKBENCH_AUDIT_EVENT_TYPES)))
|
||||
elif event_type_group in {'process_gate', 'process_gates'}:
|
||||
@@ -198,6 +335,34 @@ def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
)
|
||||
elif event_type_group in {'workflow_node', 'workflow_nodes'}:
|
||||
query = query.filter(ShippingAuditEvent.event_type.in_(sorted(WORKFLOW_NODE_AUDIT_EVENT_TYPES)))
|
||||
elif event_type_group in {
|
||||
'conversation_processing',
|
||||
'conversation_processing_task',
|
||||
'conversation_tasks',
|
||||
}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(CONVERSATION_PROCESSING_TASK_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {
|
||||
'order_intake',
|
||||
'order_submission_intake',
|
||||
'shipping_order_intake',
|
||||
}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(ORDER_SUBMISSION_INTAKE_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {'order_document', 'shipping_order_document'}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(ORDER_DOCUMENT_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {
|
||||
'order_email_adjudication',
|
||||
'email_adjudication',
|
||||
'pdf_priority_adjudication',
|
||||
}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(ORDER_EMAIL_ADJUDICATION_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
if filters.get('event_type'):
|
||||
query = query.filter(ShippingAuditEvent.event_type == str(filters['event_type'])[:64])
|
||||
if filters.get('actor_type'):
|
||||
@@ -810,3 +975,324 @@ def purge_expired_shipping_audit_events(
|
||||
'deleted': deleted,
|
||||
'cutoff': _iso(current),
|
||||
}
|
||||
|
||||
|
||||
def purge_expired_xfa_audit_snapshots(
|
||||
*,
|
||||
limit: int = 1000,
|
||||
dry_run: bool = False,
|
||||
now: datetime | None = None,
|
||||
actor_id: str | int | None = 'system',
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
清理已过保留期的 XFA 加密审计快照。
|
||||
|
||||
核心逻辑:仅删除 retention_expires_at 已到期行;归档不改写哈希链引用字段;
|
||||
PostgreSQL 须 set_config('hxops.shipping_xfa_audit_purge','1')。
|
||||
|
||||
Args:
|
||||
limit: 单批上限。
|
||||
dry_run: True 时只统计。
|
||||
now: 可注入当前时间。
|
||||
actor_id: 执行者。
|
||||
|
||||
Returns:
|
||||
{dry_run, scanned, deleted, cutoff}。
|
||||
"""
|
||||
from app.models import ShippingXfaAuditSnapshot
|
||||
|
||||
current = now or datetime.utcnow()
|
||||
safe_limit = min(5000, max(1, int(limit or 1000)))
|
||||
candidate_ids = [
|
||||
int(row[0])
|
||||
for row in db.session.query(ShippingXfaAuditSnapshot.id)
|
||||
.filter(ShippingXfaAuditSnapshot.retention_expires_at < current)
|
||||
.order_by(ShippingXfaAuditSnapshot.retention_expires_at.asc(), ShippingXfaAuditSnapshot.id.asc())
|
||||
.limit(safe_limit)
|
||||
.all()
|
||||
]
|
||||
if dry_run or not candidate_ids:
|
||||
return {
|
||||
'dry_run': bool(dry_run),
|
||||
'scanned': len(candidate_ids),
|
||||
'deleted': 0,
|
||||
'cutoff': _iso(current),
|
||||
}
|
||||
|
||||
tracked = [
|
||||
obj
|
||||
for eid in candidate_ids
|
||||
if (obj := db.session.get(ShippingXfaAuditSnapshot, eid)) is not None
|
||||
]
|
||||
if db.engine.dialect.name == 'postgresql':
|
||||
db.session.execute(text("SELECT set_config('hxops.shipping_xfa_audit_purge', '1', true)"))
|
||||
result = db.session.execute(
|
||||
delete(ShippingXfaAuditSnapshot).where(ShippingXfaAuditSnapshot.id.in_(candidate_ids))
|
||||
)
|
||||
deleted = int(result.rowcount or 0)
|
||||
for obj in tracked:
|
||||
db.session.expunge(obj)
|
||||
|
||||
append_shipping_audit_event(
|
||||
event_type='audit_retention_purged',
|
||||
aggregate_type='shipping_xfa_audit_snapshot',
|
||||
aggregate_id=f'purge:{current.strftime("%Y%m%d%H%M%S")}',
|
||||
actor_type='system',
|
||||
actor_id=actor_id,
|
||||
source='retention_job',
|
||||
result='success',
|
||||
action='purge_expired_xfa_snapshots',
|
||||
metadata={'deleted': deleted, 'limit': safe_limit, 'dry_run': False},
|
||||
persist_snapshots=False,
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
'dry_run': False,
|
||||
'scanned': len(candidate_ids),
|
||||
'deleted': deleted,
|
||||
'cutoff': _iso(current),
|
||||
}
|
||||
|
||||
|
||||
def _serialize_workspace_audit_timeline_item(
|
||||
row: ShippingAuditEvent,
|
||||
*,
|
||||
include_snapshots: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将 ShippingAuditEvent 序列化为工作台业务用户可读时间线条目。
|
||||
|
||||
核心逻辑:调用 serialize_shipping_audit_event 并裁剪为前端时间线所需字段;
|
||||
敏感快照对业务用户脱敏(sensitive_redacted=True)。
|
||||
|
||||
Args:
|
||||
row: 审计事件 ORM。
|
||||
include_snapshots: 是否附带白名单 before/after/diff。
|
||||
|
||||
Returns:
|
||||
含 id/event_type/actor_display/created_at 等业务摘要 dict。
|
||||
"""
|
||||
serialized = serialize_shipping_audit_event(
|
||||
row,
|
||||
include_snapshots=bool(include_snapshots),
|
||||
include_sensitive=False,
|
||||
)
|
||||
return {
|
||||
'id': serialized['id'],
|
||||
'event_type': serialized.get('event_type'),
|
||||
'action': serialized.get('action'),
|
||||
'result': serialized.get('result'),
|
||||
'actor_type': serialized.get('actor_type'),
|
||||
'actor_display': serialized.get('actor_display'),
|
||||
'task_no': serialized.get('task_no'),
|
||||
'error_code': serialized.get('error_code'),
|
||||
'reason': serialized.get('reason'),
|
||||
'reason_code': serialized.get('reason_code'),
|
||||
'metadata': serialized.get('metadata') or {},
|
||||
'created_at': serialized.get('created_at'),
|
||||
'source': serialized.get('source'),
|
||||
'has_snapshots': bool(serialized.get('has_snapshots')),
|
||||
'sensitive_redacted': bool(serialized.get('sensitive_redacted')),
|
||||
'before_snapshot': serialized.get('before_snapshot') if include_snapshots else None,
|
||||
'after_snapshot': serialized.get('after_snapshot') if include_snapshots else None,
|
||||
'diff': serialized.get('diff') if include_snapshots else [],
|
||||
}
|
||||
|
||||
|
||||
def _collect_task_audit_seed_values(*, task_no: str, task: Any | None = None) -> dict[str, set[str]]:
|
||||
"""
|
||||
收集任务工作台审计时间线的关联种子键。
|
||||
|
||||
核心逻辑:以 task_no 为主种子;若传入 ShippingNotice,则补充 confirmed Case 的
|
||||
review_case_no / run_no / document_id,便于关联建单前 Run 与复核事件。
|
||||
|
||||
Args:
|
||||
task_no: 对外任务编号(ShippingNotice.task_no)。
|
||||
task: 可选已校验可见的任务 ORM。
|
||||
|
||||
Returns:
|
||||
关联键 → 编号集合;至少含 task_no(非空时)。
|
||||
"""
|
||||
seeds: dict[str, set[str]] = {}
|
||||
normalized = str(task_no or '').strip()[:64]
|
||||
if normalized:
|
||||
seeds['task_no'] = {normalized}
|
||||
if task is None:
|
||||
return seeds
|
||||
try:
|
||||
from app.models import ShippingOrderReviewCase
|
||||
|
||||
cases = (
|
||||
ShippingOrderReviewCase.query.filter_by(confirmed_task_id=int(task.id))
|
||||
.order_by(ShippingOrderReviewCase.updated_at.desc())
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
for case in cases:
|
||||
case_no = str(getattr(case, 'case_no', '') or '').strip()
|
||||
if case_no:
|
||||
seeds.setdefault('review_case_no', set()).add(case_no[:64])
|
||||
run = getattr(case, 'run', None)
|
||||
run_no = str(getattr(run, 'run_no', '') or '').strip()
|
||||
if run_no:
|
||||
seeds.setdefault('run_no', set()).add(run_no[:64])
|
||||
document_id = getattr(case, 'document_id', None)
|
||||
if document_id is not None:
|
||||
seeds.setdefault('document_id', set()).add(str(document_id)[:64])
|
||||
except Exception:
|
||||
pass
|
||||
return seeds
|
||||
|
||||
|
||||
def _task_audit_association_clause(*, task_no: str, task: Any | None = None):
|
||||
"""
|
||||
构建任务工作台审计时间线的 OR 关联过滤条件。
|
||||
|
||||
核心逻辑:种子键直查 → 从命中行扩张 workflow/run/case 等稳定编号 → 全链 OR;
|
||||
无种子时返回 None。
|
||||
|
||||
Args:
|
||||
task_no: 任务编号。
|
||||
task: 可选已校验任务,用于补充 Case/Run 种子。
|
||||
|
||||
Returns:
|
||||
SQLAlchemy OR 子句或 None。
|
||||
"""
|
||||
seeds = _collect_task_audit_seed_values(task_no=task_no, task=task)
|
||||
if not seeds:
|
||||
return None
|
||||
column_map = {
|
||||
'workflow_id': ShippingAuditEvent.workflow_id,
|
||||
'workflow_item_id': ShippingAuditEvent.workflow_item_id,
|
||||
'run_no': ShippingAuditEvent.run_no,
|
||||
'document_id': ShippingAuditEvent.document_id,
|
||||
'review_case_no': ShippingAuditEvent.review_case_no,
|
||||
'task_no': ShippingAuditEvent.task_no,
|
||||
}
|
||||
seed_clauses = []
|
||||
for key, values in seeds.items():
|
||||
column = column_map.get(key)
|
||||
if column is not None and values:
|
||||
seed_clauses.append(column.in_(sorted(values)))
|
||||
if not seed_clauses:
|
||||
return None
|
||||
seed_rows = (
|
||||
ShippingAuditEvent.query
|
||||
.filter(or_(*seed_clauses))
|
||||
.order_by(ShippingAuditEvent.id.asc())
|
||||
.limit(500)
|
||||
.all()
|
||||
)
|
||||
expanded = _expand_association_keys(seed_rows)
|
||||
for key, values in seeds.items():
|
||||
expanded.setdefault(key, set()).update(values)
|
||||
return _association_or_clause(expanded)
|
||||
|
||||
|
||||
def list_review_case_audit_timeline(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
include_snapshots: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
业务用户可读的 Case 审计时间线。
|
||||
|
||||
核心逻辑:按 review_case_no 过滤;返回白名单 before/after/diff;
|
||||
sensitivity=sensitive 的快照对业务用户脱敏(sensitive_redacted=True)。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户(仅用于可见性由调用方保证)。
|
||||
case_no: 复核 Case 编号。
|
||||
page: 页码。
|
||||
page_size: 页大小(最大 100)。
|
||||
include_snapshots: 是否附带变更前后快照与字段差异。
|
||||
|
||||
Returns:
|
||||
items/total/page/page_size;条目含业务摘要与可选快照。
|
||||
"""
|
||||
del user_id # 可见性由 workspace 路由预先校验
|
||||
safe_page = max(1, int(page or 1))
|
||||
safe_page_size = min(100, max(1, int(page_size or 50)))
|
||||
query = ShippingAuditEvent.query.filter(
|
||||
ShippingAuditEvent.review_case_no == str(case_no)[:64],
|
||||
)
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(ShippingAuditEvent.created_at.desc(), ShippingAuditEvent.id.desc())
|
||||
.offset((safe_page - 1) * safe_page_size)
|
||||
.limit(safe_page_size)
|
||||
.all()
|
||||
)
|
||||
items = [
|
||||
_serialize_workspace_audit_timeline_item(row, include_snapshots=bool(include_snapshots))
|
||||
for row in rows
|
||||
]
|
||||
return {
|
||||
'items': items,
|
||||
'total': total,
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
'case_no': str(case_no),
|
||||
}
|
||||
|
||||
|
||||
def list_task_audit_timeline(
|
||||
*,
|
||||
user_id: int,
|
||||
task_no: str,
|
||||
task: Any | None = None,
|
||||
page: int = 1,
|
||||
page_size: int = 50,
|
||||
include_snapshots: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
业务用户可读的任务工作台审计时间线(统一 ShippingAuditEvent)。
|
||||
|
||||
核心逻辑:以 task_no 及关联 Case/Run 为种子,扩张关联键后分页返回;
|
||||
默认不含快照正文(工作台时间线只读摘要);敏感事件仍标记 sensitive_redacted。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户(可见性由 workspace 路由预先校验)。
|
||||
task_no: 发货任务编号。
|
||||
task: 可选已校验可见的 ShippingNotice,用于补充关联种子。
|
||||
page: 页码。
|
||||
page_size: 页大小(最大 100)。
|
||||
include_snapshots: 是否附带变更前后快照与字段差异。
|
||||
|
||||
Returns:
|
||||
items/total/page/page_size/task_no。
|
||||
"""
|
||||
del user_id
|
||||
safe_page = max(1, int(page or 1))
|
||||
safe_page_size = min(100, max(1, int(page_size or 50)))
|
||||
clause = _task_audit_association_clause(task_no=task_no, task=task)
|
||||
if clause is None:
|
||||
return {
|
||||
'items': [],
|
||||
'total': 0,
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
'task_no': str(task_no),
|
||||
}
|
||||
query = ShippingAuditEvent.query.filter(clause)
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(ShippingAuditEvent.created_at.desc(), ShippingAuditEvent.id.desc())
|
||||
.offset((safe_page - 1) * safe_page_size)
|
||||
.limit(safe_page_size)
|
||||
.all()
|
||||
)
|
||||
items = [
|
||||
_serialize_workspace_audit_timeline_item(row, include_snapshots=bool(include_snapshots))
|
||||
for row in rows
|
||||
]
|
||||
return {
|
||||
'items': items,
|
||||
'total': total,
|
||||
'page': safe_page,
|
||||
'page_size': safe_page_size,
|
||||
'task_no': str(task_no),
|
||||
}
|
||||
@@ -2,14 +2,14 @@
|
||||
backend/app/services/shipping_notice/audit_service.py
|
||||
|
||||
用途:货代领域统一审计事件的唯一写入入口;要求操作上下文与前后快照(可为空),
|
||||
写入 Workflow 软引用与哈希链字段。
|
||||
写入 Workflow 软引用与哈希链字段;XFA 敏感变更可同事务挂接加密完整快照引用。
|
||||
依赖:ShippingAuditEvent、progress_audit_contract、audit_snapshot_service(在 append 内导入以避免环)、
|
||||
SQLAlchemy 会话。
|
||||
逻辑:Run、Task、Workflow Item、库存、门禁 Attempt 和 Chatflow 服务调用本模块写入状态与决策事实;
|
||||
写入前投影白名单快照 → 计算 diff → 解析同聚合 previous_event_hash → 计算 event_hash;
|
||||
本服务不提交事务,由调用方保证业务与审计原子性。支持 operation_id、白名单前后快照、
|
||||
证据引用、Workflow 软引用(非 session_item)、属主;actor_type 含 worker(门禁 Job);
|
||||
货代全业务审计事件永久保留(retention_expires_at=None),清理 Job 仅处理历史遗留到期行。
|
||||
逻辑:Run、Task、Workflow Item、库存、门禁 Attempt、Chatflow 与 XFA Profile 服务调用本模块;
|
||||
写入前投影白名单快照 → 可选创建 XFA 加密完整快照 → 计算 diff → 解析同聚合
|
||||
previous_event_hash → 计算 event_hash;本服务不提交事务,由调用方保证业务与审计原子性;
|
||||
审计/快照写入失败时业务不得提交。支持 operation_id、白名单前后快照、证据引用、
|
||||
Workflow 软引用、属主;actor_type 含 worker;货代统一账本永久保留(expires=None)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -210,6 +210,10 @@ def append_shipping_audit_event(
|
||||
sensitivity_level: str | None = None,
|
||||
retention_expires_at: datetime | None = None,
|
||||
persist_snapshots: bool = True,
|
||||
full_before: dict[str, Any] | None = None,
|
||||
full_after: dict[str, Any] | None = None,
|
||||
full_payload: dict[str, Any] | None = None,
|
||||
full_payload_purpose: str = 'full',
|
||||
) -> ShippingAuditEvent:
|
||||
"""
|
||||
追加一条货代审计事实(唯一写入口)。
|
||||
@@ -230,18 +234,23 @@ def append_shipping_audit_event(
|
||||
evidence_refs/artifact_refs: FileAsset ID、SHA-256、版本与证据坐标,禁止 URL/正文。
|
||||
metadata: 仅允许原因码、计数、版本等脱敏诊断事实。
|
||||
persist_snapshots: False 时只写哈希(兼容历史调用方仅传 before/after 哈希语义)。
|
||||
full_before/full_after/full_payload: XFA 完整敏感载荷;加密写入 shipping_xfa_audit_snapshots,
|
||||
引用挂到 context_refs.snapshot_*_ref;缺主密钥时失败关闭。
|
||||
full_payload_purpose: full_payload 的用途标签(默认 full)。
|
||||
|
||||
Returns:
|
||||
尚未提交的审计事件,由调用方与业务写入在同一事务提交。
|
||||
|
||||
Raises:
|
||||
ValidationError: actor 类型、元数据或快照包含正文、凭据等敏感字段。
|
||||
ServiceUnavailableError: 需要加密快照但主密钥缺失。
|
||||
"""
|
||||
# 延迟导入:audit_snapshot_service.sanitize_snapshot 会回引 project_audit_snapshot,避免模块环。
|
||||
from app.services.shipping_notice.audit_snapshot_service import (
|
||||
build_event_hash_payload,
|
||||
compute_event_hash,
|
||||
compute_snapshot_diff,
|
||||
create_xfa_audit_snapshot,
|
||||
resolve_previous_event_hash,
|
||||
)
|
||||
|
||||
@@ -256,8 +265,66 @@ def append_shipping_audit_event(
|
||||
before_snapshot = project_audit_snapshot(before) if before is not None else None
|
||||
after_snapshot = project_audit_snapshot(after) if after is not None else None
|
||||
diff_json = compute_snapshot_diff(before_snapshot, after_snapshot)
|
||||
if context_refs is not None:
|
||||
_sanitize_metadata(context_refs)
|
||||
|
||||
# [STEP 1b] XFA 完整载荷 → 加密不可变快照;失败则阻断业务提交。
|
||||
resolved_context = dict(context_refs or {}) if context_refs is not None else {}
|
||||
snapshot_refs: list[dict[str, Any]] = []
|
||||
if full_before is not None:
|
||||
before_row = create_xfa_audit_snapshot(
|
||||
payload=full_before,
|
||||
object_type=str(aggregate_type)[:64],
|
||||
object_id=str(aggregate_id)[:128],
|
||||
purpose='before',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
resolved_context['snapshot_before_ref'] = before_row.snapshot_ref
|
||||
snapshot_refs.append({
|
||||
'kind': 'xfa_audit_snapshot',
|
||||
'purpose': 'before',
|
||||
'snapshot_ref': before_row.snapshot_ref,
|
||||
'plaintext_sha256': before_row.plaintext_sha256,
|
||||
})
|
||||
if full_after is not None:
|
||||
after_row = create_xfa_audit_snapshot(
|
||||
payload=full_after,
|
||||
object_type=str(aggregate_type)[:64],
|
||||
object_id=str(aggregate_id)[:128],
|
||||
purpose='after',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
resolved_context['snapshot_after_ref'] = after_row.snapshot_ref
|
||||
snapshot_refs.append({
|
||||
'kind': 'xfa_audit_snapshot',
|
||||
'purpose': 'after',
|
||||
'snapshot_ref': after_row.snapshot_ref,
|
||||
'plaintext_sha256': after_row.plaintext_sha256,
|
||||
})
|
||||
if full_payload is not None:
|
||||
full_row = create_xfa_audit_snapshot(
|
||||
payload=full_payload,
|
||||
object_type=str(aggregate_type)[:64],
|
||||
object_id=str(aggregate_id)[:128],
|
||||
purpose=str(full_payload_purpose or 'full'),
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
)
|
||||
resolved_context['snapshot_full_ref'] = full_row.snapshot_ref
|
||||
snapshot_refs.append({
|
||||
'kind': 'xfa_audit_snapshot',
|
||||
'purpose': full_row.purpose,
|
||||
'snapshot_ref': full_row.snapshot_ref,
|
||||
'plaintext_sha256': full_row.plaintext_sha256,
|
||||
})
|
||||
if resolved_context:
|
||||
_sanitize_metadata(resolved_context)
|
||||
merged_evidence = list(evidence_refs or [])
|
||||
if snapshot_refs:
|
||||
merged_evidence.extend(snapshot_refs)
|
||||
|
||||
resolved_ip_hash = client_ip_hash or hash_client_context_value(client_ip)
|
||||
resolved_ua_hash = user_agent_hash or hash_client_context_value(user_agent)
|
||||
@@ -361,13 +428,14 @@ def append_shipping_audit_event(
|
||||
previous_event_hash=previous_event_hash,
|
||||
event_hash=event_hash,
|
||||
sensitivity_level=resolved_sensitivity,
|
||||
evidence_refs_json=_sanitize_refs(evidence_refs, field_name='evidence_refs'),
|
||||
evidence_refs_json=_sanitize_refs(merged_evidence or None, field_name='evidence_refs'),
|
||||
artifact_refs_json=_sanitize_refs(artifact_refs, field_name='artifact_refs'),
|
||||
context_refs_json=dict(context_refs) if context_refs else None,
|
||||
context_refs_json=resolved_context or None,
|
||||
metadata_json=_sanitize_metadata(metadata),
|
||||
retention_expires_at=resolved_retention,
|
||||
)
|
||||
db.session.add(event)
|
||||
db.session.flush()
|
||||
return event
|
||||
|
||||
|
||||
|
||||
@@ -1,23 +1,59 @@
|
||||
"""
|
||||
services/shipping_notice/audit_snapshot_service.py
|
||||
|
||||
用途:审计快照标准化、敏感字段脱敏、前后差异与哈希链计算。
|
||||
依赖:progress_audit_contract、hashlib/json;由 audit_service 写入前调用。
|
||||
用途:审计快照标准化、敏感字段脱敏、前后差异、哈希链,以及 XFA 加密不可变完整快照。
|
||||
依赖:progress_audit_contract、ShippingAuditEvent、ShippingXfaAuditSnapshot、cryptography.fernet、
|
||||
Flask current_app(SECRET_KEY);由 audit_service / audit_query_service / XFA 写路径调用。
|
||||
逻辑:业务写路径先投影白名单快照 → 计算 diff → 读取同聚合上一条 event_hash
|
||||
作为 previous_event_hash → 再计算本条 event_hash;保留任务可离线校验链完整性。
|
||||
作为 previous_event_hash → 再计算本条 event_hash;XFA 敏感写另将完整载荷
|
||||
用 SECRET_KEY 派生 Fernet 加密落入 shipping_xfa_audit_snapshots(无独立审计密钥),
|
||||
并在事件 context_refs 挂 ref;SECRET_KEY 缺失时敏感写失败关闭;
|
||||
完整解密仅敏感读路径且每次再写访问审计。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingAuditEvent
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.models import ShippingAuditEvent, ShippingXfaAuditSnapshot
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
AUDIT_SNAPSHOT_ALLOWED_KEYS,
|
||||
is_forbidden_audit_key,
|
||||
)
|
||||
from app.services.shipping_notice.progress_feature_flags import audit_retention_days
|
||||
|
||||
XFA_AUDIT_SNAPSHOT_SCHEMA = 'xfa_audit_v1'
|
||||
XFA_AUDIT_SNAPSHOT_PURPOSES = frozenset({'before', 'after', 'request', 'full', 'sample_values'})
|
||||
# 完整快照脱敏摘要允许键;禁止 XML / 明文订单值。
|
||||
XFA_REDACTED_SUMMARY_KEYS = frozenset({
|
||||
'template_mode',
|
||||
'definition_checksum',
|
||||
'template_packet_checksum',
|
||||
'datasets_packet_checksum',
|
||||
'dataset_structure_fingerprint',
|
||||
'authoritative_collection_path_hash',
|
||||
'header_mapping_count',
|
||||
'line_mapping_count',
|
||||
'bound_field_count',
|
||||
'mirror_collection_count',
|
||||
'xfa_document_kind',
|
||||
'analysis_id',
|
||||
'revision_no',
|
||||
'profile_code',
|
||||
'profile_version',
|
||||
'path_id_hash',
|
||||
'field_count',
|
||||
'purpose',
|
||||
})
|
||||
|
||||
|
||||
def _canonical_json(value: Any) -> str:
|
||||
@@ -267,3 +303,315 @@ def verify_event_hash_chain(
|
||||
})
|
||||
previous_hash = event.event_hash
|
||||
return (len(failures) == 0, failures)
|
||||
|
||||
|
||||
def _xfa_snapshot_fernet() -> Fernet:
|
||||
"""
|
||||
构造 XFA 审计快照加密器。
|
||||
|
||||
核心逻辑:仅用应用 SECRET_KEY 派生稳定 Fernet 密钥,**不存在也不读取**
|
||||
独立审计密钥环境变量;SECRET_KEY 缺失时失败关闭。
|
||||
|
||||
Returns:
|
||||
Fernet 实例。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: SECRET_KEY 缺失。
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
|
||||
secret = str(current_app.config.get('SECRET_KEY') or '').strip()
|
||||
if not secret:
|
||||
raise ServiceUnavailableError(
|
||||
'SECRET_KEY is not configured for XFA audit snapshots',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_SECRET_MISSING',
|
||||
)
|
||||
digest = hashlib.sha256(f'shipping-xfa-audit-snapshot-v1:{secret}'.encode('utf-8')).digest()
|
||||
return Fernet(base64.urlsafe_b64encode(digest))
|
||||
|
||||
|
||||
def require_xfa_audit_crypto() -> None:
|
||||
"""
|
||||
敏感写路径前置检查:确认 SECRET_KEY 可派生快照加密器。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: SECRET_KEY 未配置。
|
||||
"""
|
||||
_xfa_snapshot_fernet()
|
||||
|
||||
|
||||
def require_xfa_audit_snapshot_key() -> None:
|
||||
"""
|
||||
兼容旧调用名;等价于 require_xfa_audit_crypto(无独立审计密钥)。
|
||||
|
||||
Raises:
|
||||
ServiceUnavailableError: SECRET_KEY 未配置。
|
||||
"""
|
||||
require_xfa_audit_crypto()
|
||||
|
||||
|
||||
def encrypt_xfa_audit_payload(payload: dict[str, Any]) -> tuple[str, str, str]:
|
||||
"""
|
||||
将完整 XFA 审计载荷加密为 Fernet 密文。
|
||||
|
||||
Args:
|
||||
payload: 可 JSON 化的完整快照对象(definition / 受控原值等)。
|
||||
|
||||
Returns:
|
||||
(ciphertext, ciphertext_sha256, plaintext_sha256)。
|
||||
|
||||
Raises:
|
||||
ValidationError: payload 非对象。
|
||||
ServiceUnavailableError: 主密钥缺失。
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot payload must be an object',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
)
|
||||
plaintext = _canonical_json(payload)
|
||||
plaintext_sha = hashlib.sha256(plaintext.encode('ascii')).hexdigest()
|
||||
ciphertext = _xfa_snapshot_fernet().encrypt(plaintext.encode('utf-8')).decode('ascii')
|
||||
ciphertext_sha = hashlib.sha256(ciphertext.encode('ascii')).hexdigest()
|
||||
return ciphertext, ciphertext_sha, plaintext_sha
|
||||
|
||||
|
||||
def decrypt_xfa_audit_payload(ciphertext: str) -> dict[str, Any]:
|
||||
"""
|
||||
解密 XFA 审计完整快照。
|
||||
|
||||
Args:
|
||||
ciphertext: 数据库中的 Fernet 密文。
|
||||
|
||||
Returns:
|
||||
明文 dict。
|
||||
|
||||
Raises:
|
||||
ValidationError: 密文空/损坏/密钥不匹配。
|
||||
ServiceUnavailableError: 主密钥缺失。
|
||||
"""
|
||||
value = str(ciphertext or '').strip()
|
||||
if not value:
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot ciphertext is missing',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
)
|
||||
try:
|
||||
raw = _xfa_snapshot_fernet().decrypt(value.encode('ascii')).decode('utf-8')
|
||||
payload = json.loads(raw)
|
||||
except (InvalidToken, UnicodeDecodeError, json.JSONDecodeError) as exc:
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot ciphertext is invalid',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
) from exc
|
||||
if not isinstance(payload, dict):
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot plaintext must be an object',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
)
|
||||
return payload
|
||||
|
||||
|
||||
def build_xfa_redacted_summary(payload: dict[str, Any] | None, *, purpose: str) -> dict[str, Any]:
|
||||
"""
|
||||
从完整载荷提取可导出的脱敏摘要。
|
||||
|
||||
核心逻辑:仅保留 XFA_REDACTED_SUMMARY_KEYS;禁止敏感键进入摘要。
|
||||
|
||||
Args:
|
||||
payload: 完整或半完整载荷。
|
||||
purpose: 快照用途标签。
|
||||
|
||||
Returns:
|
||||
脱敏摘要 dict。
|
||||
"""
|
||||
source = payload if isinstance(payload, dict) else {}
|
||||
summary: dict[str, Any] = {'purpose': purpose}
|
||||
for key in sorted(XFA_REDACTED_SUMMARY_KEYS):
|
||||
if key == 'purpose':
|
||||
continue
|
||||
if key not in source:
|
||||
continue
|
||||
if is_forbidden_audit_key(key):
|
||||
continue
|
||||
summary[key] = source[key]
|
||||
return summary
|
||||
|
||||
|
||||
def default_xfa_snapshot_retention_expires_at(*, now: datetime | None = None) -> datetime:
|
||||
"""
|
||||
计算 XFA 快照保留到期时间(默认 3 年 / 1095 天)。
|
||||
|
||||
Args:
|
||||
now: 可选当前时间。
|
||||
|
||||
Returns:
|
||||
UTC naive 到期时间。
|
||||
"""
|
||||
base = now or datetime.utcnow()
|
||||
return base + timedelta(days=audit_retention_days())
|
||||
|
||||
|
||||
def create_xfa_audit_snapshot(
|
||||
*,
|
||||
payload: dict[str, Any],
|
||||
object_type: str,
|
||||
object_id: str,
|
||||
purpose: str,
|
||||
actor_id: str | int | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
redacted_summary: dict[str, Any] | None = None,
|
||||
retention_expires_at: datetime | None = None,
|
||||
) -> ShippingXfaAuditSnapshot:
|
||||
"""
|
||||
在当前事务中写入一条加密不可变 XFA 审计快照。
|
||||
|
||||
核心逻辑:缺密钥失败关闭 → 加密 → 落库密文与双 checksum → 返回 ORM(未 commit)。
|
||||
调用方须与业务变更、ShippingAuditEvent 同事务提交;任一失败整体回滚。
|
||||
|
||||
Args:
|
||||
payload: 完整敏感载荷。
|
||||
object_type/object_id: 业务对象身份。
|
||||
purpose: before/after/request/full/sample_values。
|
||||
actor_id/request_id/operation_id: 操作上下文。
|
||||
redacted_summary: 可选预计算脱敏摘要;缺省由 payload 投影。
|
||||
retention_expires_at: 可选到期时间;缺省 3 年。
|
||||
|
||||
Returns:
|
||||
尚未提交的 ShippingXfaAuditSnapshot。
|
||||
|
||||
Raises:
|
||||
ValidationError: purpose 非法或 payload 非法。
|
||||
ServiceUnavailableError: 主密钥缺失。
|
||||
"""
|
||||
safe_purpose = str(purpose or '').strip()
|
||||
if safe_purpose not in XFA_AUDIT_SNAPSHOT_PURPOSES:
|
||||
raise ValidationError(
|
||||
'Invalid XFA audit snapshot purpose',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
details={'purpose': safe_purpose},
|
||||
)
|
||||
# [STEP 1] 加密完整载荷(缺密钥在此失败关闭)。
|
||||
ciphertext, ciphertext_sha, plaintext_sha = encrypt_xfa_audit_payload(payload)
|
||||
summary = redacted_summary if isinstance(redacted_summary, dict) else build_xfa_redacted_summary(
|
||||
payload, purpose=safe_purpose,
|
||||
)
|
||||
# [STEP 2] 生成不可猜测的 snapshot_ref 并登记密文行。
|
||||
row = ShippingXfaAuditSnapshot(
|
||||
snapshot_ref=f'xfa-snap-{uuid.uuid4().hex}',
|
||||
object_type=str(object_type)[:64],
|
||||
object_id=str(object_id)[:128],
|
||||
purpose=safe_purpose,
|
||||
schema_version=XFA_AUDIT_SNAPSHOT_SCHEMA,
|
||||
encryption_alg='fernet-v1',
|
||||
key_id='primary',
|
||||
ciphertext=ciphertext,
|
||||
ciphertext_sha256=ciphertext_sha,
|
||||
plaintext_sha256=plaintext_sha,
|
||||
redacted_summary_json=summary,
|
||||
actor_id=str(actor_id)[:128] if actor_id is not None else None,
|
||||
request_id=str(request_id)[:64] if request_id else None,
|
||||
operation_id=str(operation_id)[:64] if operation_id else None,
|
||||
retention_expires_at=retention_expires_at or default_xfa_snapshot_retention_expires_at(),
|
||||
created_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(row)
|
||||
db.session.flush()
|
||||
return row
|
||||
|
||||
|
||||
def get_xfa_audit_snapshot_row(snapshot_ref: str) -> ShippingXfaAuditSnapshot:
|
||||
"""
|
||||
按 snapshot_ref 加载快照行(不含解密)。
|
||||
|
||||
Args:
|
||||
snapshot_ref: 稳定引用。
|
||||
|
||||
Returns:
|
||||
ORM 行。
|
||||
|
||||
Raises:
|
||||
ValidationError: ref 为空。
|
||||
上层用 NotFoundError 包装缺失。
|
||||
"""
|
||||
ref = str(snapshot_ref or '').strip()
|
||||
if not ref:
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot_ref is required',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_INVALID',
|
||||
)
|
||||
row = ShippingXfaAuditSnapshot.query.filter_by(snapshot_ref=ref).first()
|
||||
if row is None:
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
raise NotFoundError(
|
||||
'XFA audit snapshot not found',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_NOT_FOUND',
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def serialize_xfa_audit_snapshot_summary(row: ShippingXfaAuditSnapshot) -> dict[str, Any]:
|
||||
"""
|
||||
序列化普通权限可见的快照摘要(无密文、无明文)。
|
||||
|
||||
Args:
|
||||
row: 快照 ORM。
|
||||
|
||||
Returns:
|
||||
脱敏摘要 dict。
|
||||
"""
|
||||
return {
|
||||
'snapshot_ref': row.snapshot_ref,
|
||||
'object_type': row.object_type,
|
||||
'object_id': row.object_id,
|
||||
'purpose': row.purpose,
|
||||
'schema_version': row.schema_version,
|
||||
'encryption_alg': row.encryption_alg,
|
||||
'ciphertext_sha256': row.ciphertext_sha256,
|
||||
'plaintext_sha256': row.plaintext_sha256,
|
||||
'redacted_summary': (
|
||||
dict(row.redacted_summary_json)
|
||||
if isinstance(row.redacted_summary_json, dict)
|
||||
else {}
|
||||
),
|
||||
'operation_id': row.operation_id,
|
||||
'request_id': row.request_id,
|
||||
'retention_expires_at': (
|
||||
row.retention_expires_at.isoformat() if row.retention_expires_at else None
|
||||
),
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def decrypt_xfa_audit_snapshot_row(row: ShippingXfaAuditSnapshot) -> dict[str, Any]:
|
||||
"""
|
||||
解密快照并校验 ciphertext / plaintext 完整性。
|
||||
|
||||
核心逻辑:重算密文 sha;解密后校验 plaintext sha;任一不匹配视为篡改。
|
||||
|
||||
Args:
|
||||
row: 快照 ORM。
|
||||
|
||||
Returns:
|
||||
明文 payload。
|
||||
|
||||
Raises:
|
||||
ValidationError: 哈希不匹配或密文无效。
|
||||
"""
|
||||
expected_cipher = hashlib.sha256(str(row.ciphertext or '').encode('ascii')).hexdigest()
|
||||
if expected_cipher != str(row.ciphertext_sha256 or ''):
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot ciphertext integrity check failed',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_TAMPERED',
|
||||
)
|
||||
payload = decrypt_xfa_audit_payload(row.ciphertext)
|
||||
actual_plain = stable_content_hash(payload)
|
||||
if actual_plain != str(row.plaintext_sha256 or ''):
|
||||
raise ValidationError(
|
||||
'XFA audit snapshot plaintext integrity check failed',
|
||||
code='SHIPPING_NOTICE.XFA_AUDIT_SNAPSHOT_TAMPERED',
|
||||
)
|
||||
return payload
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/batch_create_idempotency.py
|
||||
|
||||
用途:发货通知建单幂等键标准化、批次回查与跨请求文件内容重复校验。
|
||||
依赖:models.ShippingBatch/ShippingTask、query_service、tool_response 序列化。
|
||||
逻辑:batch_from_notices 与 task_workflow 共用本模块;与 ShippingTask.idempotency_key(货代上传幂等)语义分离。
|
||||
用途:发货通知建单幂等键标准化、跨请求文件内容重复校验(co8 起批次回查已移除)。
|
||||
依赖:models.ShippingNotice、query_service、batch_legacy_removed。
|
||||
逻辑:batch_from_notices 与 task_workflow 共用本模块;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,13 +19,8 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_focus_task_for_batch,
|
||||
list_sorted_batch_tasks,
|
||||
serialize_batch_for_tool,
|
||||
serialize_task_summary,
|
||||
)
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -108,52 +103,35 @@ def compute_notice_items_content_fingerprint(notice_items: list[dict[str, Any]])
|
||||
return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower()
|
||||
|
||||
|
||||
def batch_stored_content_fingerprint(batch: ShippingBatch) -> str | None:
|
||||
"""
|
||||
读取批次已持久化的文件集合指纹;历史批次无字段时从任务 source_content_hash 推导。
|
||||
"""
|
||||
summary = batch.process_summary_json if isinstance(batch.process_summary_json, dict) else {}
|
||||
stored = str(summary.get("create_content_fingerprint") or "").strip().lower()
|
||||
if stored:
|
||||
return stored
|
||||
tasks = list_sorted_batch_tasks(batch)
|
||||
hashes = sorted(
|
||||
{
|
||||
str(task.source_content_hash or "").strip().lower()
|
||||
for task in tasks
|
||||
if str(task.source_content_hash or "").strip()
|
||||
}
|
||||
)
|
||||
if not hashes:
|
||||
return None
|
||||
return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower()
|
||||
def batch_stored_content_fingerprint(batch: Any) -> str | None:
|
||||
"""shipping_batches 已删除;保留签名供过渡调用方,固定返回 None。"""
|
||||
del batch
|
||||
return None
|
||||
|
||||
|
||||
def assert_idempotent_batch_content_matches(
|
||||
batch: ShippingBatch,
|
||||
batch: Any,
|
||||
notice_items: list[dict[str, Any]],
|
||||
) -> None:
|
||||
"""
|
||||
校验幂等键命中时,本次文件集合与已有批次一致。
|
||||
"""shipping_batches 已删除;幂等批次内容校验不再适用。"""
|
||||
del batch, notice_items
|
||||
|
||||
Raises:
|
||||
ConflictError: 文件集合不一致(SHIPPING.BATCH_IDEMPOTENCY_CONFLICT)。
|
||||
|
||||
def find_batch_by_create_idempotency(user_id: int, create_idempotency_key: str) -> None:
|
||||
"""
|
||||
stored_fp = batch_stored_content_fingerprint(batch)
|
||||
request_fp = compute_notice_items_content_fingerprint(notice_items)
|
||||
if not stored_fp or not request_fp:
|
||||
return
|
||||
if stored_fp == request_fp:
|
||||
return
|
||||
raise ConflictError(
|
||||
"建单幂等键对应的文件集合与本次上传不一致,请更换幂等键后重试",
|
||||
code="SHIPPING.BATCH_IDEMPOTENCY_CONFLICT",
|
||||
details={
|
||||
"batch_no": batch.batch_no,
|
||||
"stored_content_fingerprint": stored_fp,
|
||||
"request_content_fingerprint": request_fp,
|
||||
},
|
||||
)
|
||||
按用户与建单幂等键查找已有批次。
|
||||
|
||||
Returns:
|
||||
固定 None(shipping_batches 已删除)。
|
||||
"""
|
||||
del user_id, create_idempotency_key
|
||||
return None
|
||||
|
||||
|
||||
def build_existing_batch_tool_response(batch: Any, *, user_id: int) -> dict[str, Any]:
|
||||
"""shipping_batches 已删除;禁止构建批次重放响应。"""
|
||||
del batch, user_id
|
||||
raise_shipping_batches_removed()
|
||||
|
||||
|
||||
def _advisory_lock_key(*parts: str) -> int:
|
||||
@@ -179,72 +157,32 @@ def acquire_notice_create_locks(user_id: int, content_hashes: Iterable[str]) ->
|
||||
db.session.execute(text("SELECT pg_advisory_xact_lock(:lock_key)"), {"lock_key": lock_key})
|
||||
|
||||
|
||||
def find_batch_by_create_idempotency(user_id: int, create_idempotency_key: str) -> ShippingBatch | None:
|
||||
"""
|
||||
按用户与建单幂等键查找已有批次。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户 ID。
|
||||
create_idempotency_key: 已标准化的建单幂等键。
|
||||
|
||||
Returns:
|
||||
匹配的 ShippingBatch 或 None。
|
||||
"""
|
||||
key = str(create_idempotency_key or "").strip()
|
||||
if not key:
|
||||
return None
|
||||
return (
|
||||
ShippingBatch.query.filter_by(user_id=user_id, create_idempotency_key=key).first()
|
||||
)
|
||||
|
||||
|
||||
def build_existing_batch_tool_response(batch: ShippingBatch, *, user_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
将已有批次序列化为 create_batch_tasks 兼容的 Tool 响应结构。
|
||||
|
||||
核心逻辑:不创建新任务、不启动编排器;供幂等重放与唯一约束竞争回查共用。
|
||||
"""
|
||||
tasks = list_sorted_batch_tasks(batch)
|
||||
focus_task = get_focus_task_for_batch(batch.batch_no, user_id)
|
||||
created_tasks = [
|
||||
{
|
||||
"task_id": task.task_no,
|
||||
"batch_index": task.batch_index,
|
||||
"parse_status": "deferred",
|
||||
}
|
||||
for task in tasks
|
||||
]
|
||||
data: dict[str, Any] = {
|
||||
"batch": serialize_batch_for_tool(batch),
|
||||
"tasks": created_tasks,
|
||||
"orchestrator_started": False,
|
||||
}
|
||||
if focus_task:
|
||||
data["focus_task"] = serialize_task_summary(focus_task)
|
||||
return {
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"message": f"已恢复此前创建的批次 {batch.batch_no}",
|
||||
"data": data,
|
||||
"idempotent_replay": True,
|
||||
}
|
||||
|
||||
|
||||
def assert_no_exact_duplicate_notices(
|
||||
user_id: int,
|
||||
notice_items: list[dict[str, Any]],
|
||||
*,
|
||||
exclude_batch_id: int | None = None,
|
||||
exclude_task_ids: Iterable[int] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
校验跨请求是否存在相同文件内容且仍在进行中的任务。
|
||||
|
||||
核心逻辑:须在 acquire_notice_create_locks 之后调用,避免不同幂等键并发重复建单。
|
||||
合法的 duplicate_resolution_type=revision|force_create 跳过哈希阻断(业务 Gate 已授权)。
|
||||
exclude_task_ids 用于同一复核 Case 合法后续履约波次:豁免本 Case 已建非终态 Task,
|
||||
不得用于取消跨 Case / 跨入口的精确重复检查。
|
||||
|
||||
Args:
|
||||
user_id: 建单用户。
|
||||
notice_items: 含 source_content_hash / duplicate_resolution_type 的通知项。
|
||||
exclude_batch_id: 可选;忽略同批次内任务。
|
||||
exclude_task_ids: 可选;忽略这些已存在 Task(同 Case 既有波次)。
|
||||
|
||||
Raises:
|
||||
ConflictError: SHIPPING.NOTICE_EXACT_DUPLICATE,details 含已有 task_no。
|
||||
"""
|
||||
skipped_ids = {int(item) for item in (exclude_task_ids or []) if item is not None}
|
||||
hashes: list[tuple[str, str]] = []
|
||||
for item in notice_items:
|
||||
if not isinstance(item, dict):
|
||||
@@ -262,16 +200,14 @@ def assert_no_exact_duplicate_notices(
|
||||
return
|
||||
|
||||
for content_hash, _filename in hashes:
|
||||
query = ShippingTask.query.filter(
|
||||
ShippingTask.user_id == user_id,
|
||||
ShippingTask.source_content_hash == content_hash,
|
||||
ShippingTask.process_status.notin_(list(_TERMINAL_TASK_STATUSES)),
|
||||
query = ShippingNotice.query.filter(
|
||||
ShippingNotice.user_id == user_id,
|
||||
ShippingNotice.source_content_hash == content_hash,
|
||||
ShippingNotice.process_status.notin_(list(_TERMINAL_TASK_STATUSES)),
|
||||
)
|
||||
if exclude_batch_id is not None:
|
||||
query = query.filter(
|
||||
(ShippingTask.batch_id.is_(None)) | (ShippingTask.batch_id != exclude_batch_id)
|
||||
)
|
||||
existing = query.order_by(ShippingTask.id.desc()).first()
|
||||
if skipped_ids:
|
||||
query = query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
|
||||
existing = query.order_by(ShippingNotice.id.desc()).first()
|
||||
if existing:
|
||||
raise ConflictError(
|
||||
f"该文件已存在于进行中的任务 {existing.task_no}",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -48,7 +48,7 @@ def create_shipping_batch_from_notice_items(
|
||||
conversation_id: 可选 Agent 会话 ID。
|
||||
notice_items: notice_upload 产出的 notice item 列表。
|
||||
file_summary: 可选文件预检摘要,写入响应供前端展示。
|
||||
create_idempotency_key: 建单幂等键(与 ShippingTask.idempotency_key 货代上传幂等分离)。
|
||||
create_idempotency_key: 建单幂等键(与 ShippingNotice.idempotency_key 货代上传幂等分离)。
|
||||
defer_commit: True 时下层仅 flush,由调用方最终 commit。
|
||||
start_orchestrator: 是否启动编排器;默认与 defer_commit 相反(延后提交时不启动)。
|
||||
|
||||
@@ -56,77 +56,11 @@ def create_shipping_batch_from_notice_items(
|
||||
与 workspace create-from-notices 一致的结果字典,幂等重放时含 idempotent_replay=true。
|
||||
|
||||
Raises:
|
||||
ValidationError: notice_items 为空。
|
||||
ValidationError: notice_items 为空,或 shipping_batches 已删除(co8)。
|
||||
"""
|
||||
normalized_key = normalize_create_idempotency_key(create_idempotency_key)
|
||||
if not normalized_key:
|
||||
warn_missing_create_idempotency_key(source="create_shipping_batch_from_notice_items")
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
notice_items = dedupe_notice_items_by_content_hash(notice_items)
|
||||
if not notice_items:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError(
|
||||
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
|
||||
details={"file_summary": file_summary or {}},
|
||||
)
|
||||
|
||||
if normalized_key:
|
||||
existing_batch = find_batch_by_create_idempotency(user_id, normalized_key)
|
||||
if existing_batch:
|
||||
assert_idempotent_batch_content_matches(existing_batch, notice_items)
|
||||
created = build_existing_batch_tool_response(existing_batch, user_id=user_id)
|
||||
if file_summary:
|
||||
created["file_summary"] = file_summary
|
||||
return created
|
||||
|
||||
payload = {
|
||||
"user_id": user_id,
|
||||
"conversation_id": conversation_id or None,
|
||||
"file_count": len(notice_items),
|
||||
"notice_items": notice_items,
|
||||
"defer_parse": True,
|
||||
"create_idempotency_key": normalized_key,
|
||||
"defer_commit": bool(defer_commit),
|
||||
}
|
||||
try:
|
||||
created = shipping_tools.create_batch_tasks(payload)
|
||||
except IntegrityError as exc:
|
||||
replay = handle_batch_create_integrity_error(
|
||||
user_id=user_id,
|
||||
create_idempotency_key=normalized_key,
|
||||
exc=exc,
|
||||
)
|
||||
if replay is None:
|
||||
raise
|
||||
created = replay
|
||||
|
||||
if not isinstance(created, dict):
|
||||
return {"status": "failed", "message": "create batch failed"}
|
||||
|
||||
idempotent_replay = bool(created.get("idempotent_replay"))
|
||||
data = created.get("data") if isinstance(created.get("data"), dict) else {}
|
||||
batch_data = data.get("batch") if isinstance(data.get("batch"), dict) else {}
|
||||
batch_no = str(created.get("batch_no") or batch_data.get("batch_no") or "").strip()
|
||||
should_start = start_orchestrator if start_orchestrator is not None else (not defer_commit)
|
||||
orchestrator_started = False
|
||||
if batch_no and not idempotent_replay and should_start:
|
||||
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
|
||||
|
||||
orchestrator_started = start_batch_orchestrator(batch_no)
|
||||
if batch_no and isinstance(data, dict):
|
||||
focus_task = get_focus_task_for_batch(batch_no, user_id)
|
||||
if focus_task:
|
||||
data["focus_task"] = serialize_task_summary(focus_task)
|
||||
data["orchestrator_started"] = orchestrator_started
|
||||
base_message = str(created.get("message") or "").strip()
|
||||
if orchestrator_started:
|
||||
created["message"] = f"{base_message},后台已开始逐票处理。" if base_message else "后台已开始逐票处理。"
|
||||
if idempotent_replay:
|
||||
created["idempotent_replay"] = True
|
||||
if file_summary:
|
||||
created["file_summary"] = file_summary
|
||||
return created
|
||||
raise_shipping_batches_removed()
|
||||
|
||||
|
||||
def format_batch_created_assistant_message(
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/batch_legacy_removed.py
|
||||
|
||||
用途:shipping_batches 表物理删除(co8e9f0a1b2c)后的统一阻断与文案常量。
|
||||
依赖:app.core.errors.AppError。
|
||||
逻辑:create_batch / batch_from_* 等写路径在入口调用 raise_shipping_batches_removed(HTTP 410);
|
||||
读路径 list API 返回空集,按 batch_no 查询返回 None。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
SHIPPING_BATCHES_REMOVED_MESSAGE = (
|
||||
"shipping_batches removed (migration co8e9f0a1b2c)"
|
||||
)
|
||||
|
||||
|
||||
def raise_shipping_batches_removed(*, action: str | None = None) -> None:
|
||||
"""
|
||||
阻断仍依赖 shipping_batches 表的写路径。
|
||||
|
||||
核心逻辑:ORM 已移除 ShippingBatch;调用方须在入口尽早抛出,避免 SQLAlchemy 访问已 DROP 表。
|
||||
|
||||
Args:
|
||||
action: 可选调用方动作名,写入 error.details 便于排查。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410,code=SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
details = {'migration': 'co8e9f0a1b2c', 'replacement': 'order-extraction-submissions'}
|
||||
if action:
|
||||
details['action'] = str(action)
|
||||
raise AppError(
|
||||
code='SHIPPING.BATCHES_REMOVED',
|
||||
message=SHIPPING_BATCHES_REMOVED_MESSAGE,
|
||||
http_status=410,
|
||||
details=details,
|
||||
retryable=False,
|
||||
)
|
||||
@@ -108,18 +108,8 @@ def _is_retryable_task(task: Any) -> bool:
|
||||
|
||||
|
||||
def _refresh_batch_focus(task_no: str) -> None:
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task or not task.batch:
|
||||
return
|
||||
switch_batch_focus(
|
||||
task.batch,
|
||||
task,
|
||||
source="backend_orchestrator",
|
||||
event_type="focus_auto_switched",
|
||||
emit_when_unchanged=False,
|
||||
)
|
||||
recompute_batch_summary(task.batch)
|
||||
db.session.commit()
|
||||
"""shipping_batches 已删除;批次焦点刷新无操作。"""
|
||||
del task_no
|
||||
|
||||
|
||||
def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
@@ -226,8 +216,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
|
||||
refreshed = get_task_by_ref(normalized_task_no)
|
||||
if refreshed:
|
||||
if refreshed.batch:
|
||||
recompute_batch_summary(refreshed.batch)
|
||||
log_task_event(
|
||||
refreshed,
|
||||
"backend_orchestrator_task_finished",
|
||||
@@ -248,8 +236,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
if task:
|
||||
task.error_message = str(exc)
|
||||
log_task_event(task, "backend_orchestrator_task_failed", {"error": str(exc)[:1000]})
|
||||
if task.batch:
|
||||
recompute_batch_summary(task.batch)
|
||||
db.session.commit()
|
||||
return {"status": "failed", "message": str(exc)[:500] or "background task failed"}
|
||||
finally:
|
||||
@@ -310,8 +296,6 @@ def _background_batch_runner(app: Any, batch_no: str) -> None:
|
||||
"backend_orchestrator_task_failed",
|
||||
{"error": str(exc)[:1000], "source": "batch_dispatcher"},
|
||||
)
|
||||
if task.batch:
|
||||
recompute_batch_summary(task.batch)
|
||||
db.session.commit()
|
||||
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/business_case_service.py
|
||||
|
||||
用途:为新建货代任务创建或继承业务单聚合。
|
||||
依赖:db、ShippingCase、ShippingTask、uuid/datetime。
|
||||
依赖:db、ShippingCase、ShippingNotice、uuid/datetime。
|
||||
逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单。
|
||||
"""
|
||||
|
||||
@@ -13,7 +13,7 @@ from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingCase, ShippingTask
|
||||
from app.models import ShippingCase, ShippingNotice
|
||||
|
||||
|
||||
def generate_shipping_case_no() -> str:
|
||||
@@ -71,7 +71,7 @@ def resolve_shipping_case_for_new_task(
|
||||
'修订任务缺少父任务',
|
||||
code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
|
||||
)
|
||||
parent = db.session.get(ShippingTask, int(supersedes_task_id))
|
||||
parent = db.session.get(ShippingNotice, int(supersedes_task_id))
|
||||
if parent is None:
|
||||
raise ConflictError(
|
||||
'修订目标任务不存在',
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/candidate_evidence_service.py
|
||||
|
||||
用途:将 Candidate 主/辅/冲突证据写入 shipping_order_candidate_evidences(蓝图 §六)。
|
||||
依赖:ShippingOrderCandidateEvidence、ShippingOrderCandidate、ShippingOrderDocument、db。
|
||||
逻辑:由 document_candidate_persist / PDF 优先裁决路径调用;替换式写入避免重解析膨胀。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderCandidateEvidence,
|
||||
ShippingOrderDocument,
|
||||
)
|
||||
from app.services.shipping_notice.pdf_priority_adjudication import PDF_PRIORITY_DECISION_RULE_VERSION
|
||||
|
||||
|
||||
def _hash_value(value: Any) -> str | None:
|
||||
"""对值做 sha256;空值返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
return hashlib.sha256(text.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _kind_for_document(document: ShippingOrderDocument | None) -> str:
|
||||
"""按 Document 类型推断 evidence_kind。"""
|
||||
if document is None:
|
||||
return 'other'
|
||||
dtype = str(document.document_type or '').strip().lower()
|
||||
filename = str(document.filename or '').strip().lower()
|
||||
if dtype in {'pdf', 'attachment_pdf'} or filename.endswith('.pdf'):
|
||||
return 'pdf'
|
||||
if dtype in {'email_body', 'body'}:
|
||||
return 'email_body'
|
||||
if 'xls' in filename or dtype in {'excel', 'spreadsheet'}:
|
||||
return 'excel'
|
||||
if filename.endswith('.doc') or filename.endswith('.docx') or dtype == 'word':
|
||||
return 'word'
|
||||
if any(filename.endswith(ext) for ext in ('.png', '.jpg', '.jpeg', '.tif', '.tiff', '.webp')):
|
||||
return 'image'
|
||||
return 'other'
|
||||
|
||||
|
||||
def _kind_from_source_type(source_type: str | None) -> str:
|
||||
"""将 Observation source_type 映射为 evidence_kind。"""
|
||||
st = str(source_type or '').strip().lower()
|
||||
if st.startswith('pdf_') or st in {'attachment_text', 'attachment_table'}:
|
||||
return 'pdf'
|
||||
if st.startswith('email_body'):
|
||||
return 'email_body'
|
||||
if 'excel' in st or 'xls' in st:
|
||||
return 'excel'
|
||||
if 'word' in st or 'doc' in st:
|
||||
return 'word'
|
||||
if st.startswith('image') or 'ocr' in st:
|
||||
return 'ocr'
|
||||
if 'model' in st or 'llm' in st:
|
||||
return 'model'
|
||||
return 'other'
|
||||
|
||||
|
||||
def replace_candidate_evidences_from_persist(
|
||||
candidate: ShippingOrderCandidate,
|
||||
*,
|
||||
document: ShippingOrderDocument,
|
||||
evidence: dict[str, Any] | None = None,
|
||||
conflicts: list[dict[str, Any]] | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
按 Candidate 落库结果替换证据行。
|
||||
|
||||
核心逻辑:删除该 Candidate 旧行;写入主文档 primary;再写入 evidence.items 与 conflicts。
|
||||
|
||||
Args:
|
||||
candidate: 已 flush 的 Candidate。
|
||||
document: 主文档。
|
||||
evidence: 持久化时的 evidence 字典(含 items)。
|
||||
conflicts: 冲突列表。
|
||||
|
||||
Returns:
|
||||
写入行数。
|
||||
"""
|
||||
candidate_id = int(candidate.id)
|
||||
db.session.query(ShippingOrderCandidateEvidence).filter_by(candidate_id=candidate_id).delete(
|
||||
synchronize_session=False
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
rows: list[ShippingOrderCandidateEvidence] = [
|
||||
ShippingOrderCandidateEvidence(
|
||||
candidate_id=candidate_id,
|
||||
document_id=int(document.id),
|
||||
evidence_role='primary_pdf' if _kind_for_document(document) == 'pdf' else 'context',
|
||||
evidence_kind=_kind_for_document(document),
|
||||
is_primary=True,
|
||||
payload_json={
|
||||
'document_type': document.document_type,
|
||||
'filename': document.filename,
|
||||
'content_hash': document.content_hash,
|
||||
},
|
||||
decision_rule_version=PDF_PRIORITY_DECISION_RULE_VERSION,
|
||||
created_at=now,
|
||||
)
|
||||
]
|
||||
items = list((evidence or {}).get('items') or []) if isinstance(evidence, dict) else []
|
||||
for item in items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
kind = _kind_from_source_type(str(item.get('source_type') or item.get('kind') or ''))
|
||||
rows.append(
|
||||
ShippingOrderCandidateEvidence(
|
||||
candidate_id=candidate_id,
|
||||
document_id=int(item['document_id']) if item.get('document_id') else None,
|
||||
evidence_role='auxiliary',
|
||||
evidence_kind=kind,
|
||||
is_primary=False,
|
||||
field_code=str(item.get('field_code') or '').strip() or None,
|
||||
value_hash=_hash_value(item.get('value')),
|
||||
payload_json={
|
||||
'ref': item.get('ref') or item.get('evidence_ref'),
|
||||
'source_type': item.get('source_type'),
|
||||
},
|
||||
decision_rule_version=PDF_PRIORITY_DECISION_RULE_VERSION,
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
for conflict in list(conflicts or []):
|
||||
if not isinstance(conflict, dict):
|
||||
continue
|
||||
rows.append(
|
||||
ShippingOrderCandidateEvidence(
|
||||
candidate_id=candidate_id,
|
||||
document_id=None,
|
||||
evidence_role='conflict',
|
||||
evidence_kind=_kind_from_source_type(str(conflict.get('source_type') or '')),
|
||||
is_primary=False,
|
||||
field_code=str(conflict.get('field_code') or conflict.get('code') or '').strip() or None,
|
||||
value_hash=_hash_value(conflict.get('value') or conflict.get('message')),
|
||||
payload_json={
|
||||
'reason_code': conflict.get('reason_code') or conflict.get('code'),
|
||||
'blocked_auto_create': conflict.get('blocked_auto_create'),
|
||||
},
|
||||
decision_rule_version=PDF_PRIORITY_DECISION_RULE_VERSION,
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
db.session.add_all(rows)
|
||||
db.session.flush()
|
||||
return len(rows)
|
||||
|
||||
|
||||
def append_pdf_priority_field_evidences(
|
||||
*,
|
||||
candidate_id: int,
|
||||
document_id: Optional[int],
|
||||
field_code: str,
|
||||
audit_payload: dict[str, Any],
|
||||
) -> int:
|
||||
"""
|
||||
为 PDF 优先字段裁决追加主/辅/冲突证据行(不整表替换)。
|
||||
|
||||
Args:
|
||||
candidate_id: Candidate 主键。
|
||||
document_id: 主 PDF Document(可空)。
|
||||
field_code: 字段码。
|
||||
audit_payload: build_pdf_priority_audit_payload 结果。
|
||||
|
||||
Returns:
|
||||
追加行数。
|
||||
"""
|
||||
if not candidate_id or not field_code:
|
||||
return 0
|
||||
now = datetime.utcnow()
|
||||
rows: list[ShippingOrderCandidateEvidence] = []
|
||||
if audit_payload.get('pdf_value_hash'):
|
||||
rows.append(
|
||||
ShippingOrderCandidateEvidence(
|
||||
candidate_id=int(candidate_id),
|
||||
document_id=int(document_id) if document_id else None,
|
||||
evidence_role='primary_pdf',
|
||||
evidence_kind='pdf',
|
||||
is_primary=True,
|
||||
field_code=str(field_code),
|
||||
value_hash=str(audit_payload.get('pdf_value_hash')),
|
||||
payload_json={
|
||||
'evidence_ref': audit_payload.get('evidence_ref'),
|
||||
'value_source': audit_payload.get('value_source'),
|
||||
},
|
||||
decision_rule_version=str(
|
||||
audit_payload.get('decision_rule_version') or PDF_PRIORITY_DECISION_RULE_VERSION
|
||||
),
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
if audit_payload.get('auxiliary_value_hash'):
|
||||
rows.append(
|
||||
ShippingOrderCandidateEvidence(
|
||||
candidate_id=int(candidate_id),
|
||||
document_id=None,
|
||||
evidence_role='conflict' if audit_payload.get('conflict') else 'auxiliary',
|
||||
evidence_kind='other',
|
||||
is_primary=False,
|
||||
field_code=str(field_code),
|
||||
value_hash=str(audit_payload.get('auxiliary_value_hash')),
|
||||
payload_json={
|
||||
'evidence_ref': audit_payload.get('auxiliary_evidence_ref'),
|
||||
'blocked_auto_create': audit_payload.get('blocked_auto_create'),
|
||||
},
|
||||
decision_rule_version=str(
|
||||
audit_payload.get('decision_rule_version') or PDF_PRIORITY_DECISION_RULE_VERSION
|
||||
),
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
if not rows:
|
||||
return 0
|
||||
db.session.add_all(rows)
|
||||
db.session.flush()
|
||||
return len(rows)
|
||||
@@ -21,9 +21,10 @@ CANDIDATE_QUALIFICATION_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
})
|
||||
|
||||
# 资格评估器版本;快照持久化时写入 evaluator_version。
|
||||
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v1'
|
||||
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v2-xfa'
|
||||
|
||||
# 统一检查顺序(不可重排):后置项依赖前置放行语义由服务层解释。
|
||||
# XFA 专属门禁对非 XFA Candidate 恒为 True(N/A 放行)。
|
||||
CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
|
||||
'auto_create_enabled',
|
||||
'classification_confidence',
|
||||
@@ -34,6 +35,10 @@ CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
|
||||
'duplicate_resolved',
|
||||
'customer_confirmed',
|
||||
'idempotency_ok',
|
||||
'xfa_auto_create_policy',
|
||||
'xfa_profile_blind_approved',
|
||||
'xfa_pilot_allowlist',
|
||||
'xfa_evidence_integrity',
|
||||
)
|
||||
|
||||
# 检查项失败 → 稳定用户原因码(对话 / Process Gate / 复核摘要共用)。
|
||||
@@ -47,6 +52,10 @@ CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = {
|
||||
'duplicate_resolved': 'duplicate_unresolved',
|
||||
'customer_confirmed': 'customer_confirmation_required',
|
||||
'idempotency_ok': 'task_already_exists',
|
||||
'xfa_auto_create_policy': 'xfa_auto_create_disabled',
|
||||
'xfa_profile_blind_approved': 'xfa_profile_not_blind_approved',
|
||||
'xfa_pilot_allowlist': 'xfa_allowlist_unconfigured',
|
||||
'xfa_evidence_integrity': 'xfa_evidence_incomplete',
|
||||
}
|
||||
|
||||
# 偏向「需人工轻量确认」而非硬阻断的原因码。
|
||||
@@ -57,6 +66,8 @@ CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'duplicate_unresolved',
|
||||
'classification_low_confidence',
|
||||
'field_low_confidence',
|
||||
# PDF 优先已选定当前值,但仍须人工确认冲突后方可自动建单。
|
||||
'pdf_preferred_critical_conflict',
|
||||
})
|
||||
|
||||
# 解析来源(写入 parser_trace,不直接决定资格)。
|
||||
|
||||
@@ -3,12 +3,17 @@ services/shipping_notice/candidate_qualification_service.py
|
||||
|
||||
用途:评估并追加持久化 Candidate 级统一自动建单资格快照。
|
||||
依赖:candidate_qualification_contract、order_schema.service(自动建单开关 / minimum_confidence)、
|
||||
ShippingNoticeCandidate / ShippingOrderCandidateQualification、fulfillment_audit。
|
||||
ShippingOrderCandidate / ShippingOrderCandidateQualification、fulfillment_audit、
|
||||
xfa_contract(XFA 对账可自动建单状态集)。
|
||||
逻辑:由抽取收尾、建单资格与 STP 自动建单调用;三种解析来源统一门禁;
|
||||
每次评估追加不可变历史行并写统一审计 before/after;
|
||||
模板 Profile 批准仅写入 parser_trace;LLM 路径不再天然阻断;
|
||||
分类/LLM 字段置信度缺失 fail-closed;阈值来源写入 confidence_policy;
|
||||
duplicate unchecked 与关键字段证据缺失均 fail-closed。
|
||||
duplicate unchecked 与关键字段证据缺失均 fail-closed;
|
||||
XFA 硬门禁:shadow 阻断、盲测批准、客户/checksum/场景白名单(自动建单总开关走 Schema/CQ);
|
||||
另要求 evidence 计数与四项 cross-check 齐全且仅为 matched/passed/skipped;
|
||||
PDF 优先关键冲突(conflicts_json.reason=pdf_preferred_critical_conflict)
|
||||
映射为 review_required,阻断 can_auto_create。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,10 +24,9 @@ from typing import Any
|
||||
from app.core.errors import ConflictError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderCandidateQualification,
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
from app.services.shipping_notice.candidate_qualification_contract import (
|
||||
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION,
|
||||
@@ -31,8 +35,18 @@ from app.services.shipping_notice.candidate_qualification_contract import (
|
||||
CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES,
|
||||
)
|
||||
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
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_CROSS_CHECK_AUTO_CREATE_OK_STATUSES,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
extraction_emergency_stop_enabled,
|
||||
xfa_customer_allowlist,
|
||||
xfa_profile_checksum_allowlist,
|
||||
xfa_scenario_allowlist,
|
||||
xfa_shadow_mode_enabled,
|
||||
)
|
||||
|
||||
_DEFAULT_BUSINESS_SCENARIO = 'shipping_notice_order'
|
||||
|
||||
# 分类置信度默认下限;仅当 Schema auto_creation_policy 未配置 minimum_confidence 时回退。
|
||||
# 回退来源会写入评估结果 confidence_policy,供管理端核对,禁止静默偏离界面配置。
|
||||
@@ -41,6 +55,36 @@ _CONFIDENCE_SOURCE_SCHEMA_POLICY = 'schema_auto_creation_policy'
|
||||
_CONFIDENCE_SOURCE_KEY_FIELD_MIN = 'key_field_minimum_confidence'
|
||||
_CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85'
|
||||
|
||||
# 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。
|
||||
# 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。
|
||||
_NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'})
|
||||
|
||||
|
||||
def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
|
||||
"""
|
||||
返回真正阻断建单的 Candidate 冲突。
|
||||
|
||||
核心逻辑:过滤仅描述文档版面/坐标质量的诊断项;字段值冲突、跨来源冲突
|
||||
与其他未知阻断项继续 fail-closed。
|
||||
|
||||
Args:
|
||||
candidate: ShippingOrderCandidate 或兼容替身。
|
||||
|
||||
Returns:
|
||||
仍需阻断建单的冲突列表。
|
||||
"""
|
||||
conflicts = getattr(candidate, 'conflicts_json', None)
|
||||
if not isinstance(conflicts, list):
|
||||
return [] if not conflicts else [conflicts]
|
||||
return [
|
||||
item for item in conflicts
|
||||
if not (
|
||||
isinstance(item, dict)
|
||||
and str(item.get('reason') or item.get('code') or '').strip()
|
||||
in _NON_BLOCKING_CONFLICT_REASONS
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def resolve_candidate_customer_resolved(
|
||||
*,
|
||||
@@ -151,7 +195,8 @@ def resolve_review_case_customer_resolved(
|
||||
"""
|
||||
判定复核 Case 关联客户是否已确认(建单前 fail-closed)。
|
||||
|
||||
核心逻辑:Candidate/Extraction 确认优先;否则查同 Run 已确认 Bill-to。
|
||||
核心逻辑:只读取当前 Case 关联 Candidate/Extraction 的 Bill-to 确认结果。
|
||||
同一 Run 可包含多份 PDF;不得把其他 PDF 的已确认客户串入当前 Case。
|
||||
|
||||
Args:
|
||||
case: ShippingOrderReviewCase。
|
||||
@@ -160,26 +205,7 @@ def resolve_review_case_customer_resolved(
|
||||
Returns:
|
||||
True 表示客户已确认。
|
||||
"""
|
||||
if resolve_candidate_customer_resolved(candidate=candidate):
|
||||
return True
|
||||
run_id = getattr(case, 'run_id', None)
|
||||
if run_id is None:
|
||||
return False
|
||||
row = (
|
||||
ShippingOrderCustomerMatch.query
|
||||
.join(
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderExtraction.run_id == int(run_id),
|
||||
ShippingOrderCustomerMatch.role == 'bill_to',
|
||||
ShippingOrderCustomerMatch.status == 'confirmed',
|
||||
ShippingOrderCustomerMatch.customer_id.isnot(None),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
return row is not None
|
||||
return resolve_candidate_customer_resolved(candidate=candidate)
|
||||
|
||||
|
||||
def evaluate_candidate_qualification(
|
||||
@@ -198,7 +224,7 @@ def evaluate_candidate_qualification(
|
||||
汇总 blocking_reason_codes 后映射 eligible / review_required / blocked / rejected。
|
||||
|
||||
Args:
|
||||
candidate: ShippingNoticeCandidate 或兼容 SimpleNamespace。
|
||||
candidate: ShippingOrderCandidate 或兼容 SimpleNamespace。
|
||||
run: 可选 Run(读取紧急停止 / auto_freeze_policy)。
|
||||
unit: 可选 Unit(读取路由摘要,仅 parser_trace)。
|
||||
fields_complete: 调用方已汇总的必填完整标志;缺省时读 missing_fields_json。
|
||||
@@ -244,6 +270,17 @@ def evaluate_candidate_qualification(
|
||||
customer_ok, customer_reason = _customer_ok(candidate, customer_resolved=customer_resolved)
|
||||
idempotency_ok = _idempotency_ok(candidate)
|
||||
|
||||
# [STEP 2b] XFA 专属硬门禁(非 XFA 恒 True)+ evidence/cross-check 完整性。
|
||||
xfa_eval = _evaluate_xfa_auto_create_gates(
|
||||
candidate=candidate,
|
||||
run=run,
|
||||
unit=unit,
|
||||
parser_trace=parser_trace,
|
||||
customer_resolved=customer_resolved,
|
||||
emergency_stop=emergency_stop,
|
||||
)
|
||||
parser_trace = {**parser_trace, **xfa_eval['parser_trace_extra']}
|
||||
|
||||
gates = {
|
||||
'auto_create_enabled': auto_create_enabled,
|
||||
'classification_confidence': classification_ok,
|
||||
@@ -254,19 +291,31 @@ def evaluate_candidate_qualification(
|
||||
'duplicate_resolved': duplicate_ok,
|
||||
'customer_confirmed': customer_ok,
|
||||
'idempotency_ok': idempotency_ok,
|
||||
'xfa_auto_create_policy': bool(xfa_eval['gates']['xfa_auto_create_policy']),
|
||||
'xfa_profile_blind_approved': bool(xfa_eval['gates']['xfa_profile_blind_approved']),
|
||||
'xfa_pilot_allowlist': bool(xfa_eval['gates']['xfa_pilot_allowlist']),
|
||||
'xfa_evidence_integrity': bool(xfa_eval['gates']['xfa_evidence_integrity']),
|
||||
}
|
||||
failed = [key for key in CANDIDATE_QUALIFICATION_GATE_KEYS if not gates.get(key)]
|
||||
|
||||
# [STEP 3] 映射原因码;客户细因覆盖默认码。
|
||||
# [STEP 3] 映射原因码;客户细因 / XFA 细因 / PDF 关键冲突细因覆盖默认码。
|
||||
blocking_reason_codes: list[str] = []
|
||||
for key in failed:
|
||||
if key == 'customer_confirmed' and customer_reason:
|
||||
blocking_reason_codes.append(customer_reason)
|
||||
continue
|
||||
if key in xfa_eval['reason_by_gate'] and xfa_eval['reason_by_gate'].get(key):
|
||||
blocking_reason_codes.append(str(xfa_eval['reason_by_gate'][key]))
|
||||
continue
|
||||
if key == 'field_conflicts_resolved':
|
||||
pdf_reason = _pdf_priority_conflict_reason(candidate)
|
||||
if pdf_reason:
|
||||
blocking_reason_codes.append(pdf_reason)
|
||||
continue
|
||||
blocking_reason_codes.append(
|
||||
CANDIDATE_QUALIFICATION_GATE_REASON_CODES.get(key, 'order_freeze_not_ready')
|
||||
)
|
||||
if emergency_stop and 'auto_create_disabled' not in blocking_reason_codes:
|
||||
if emergency_stop and 'extraction_emergency_stop' not in blocking_reason_codes:
|
||||
blocking_reason_codes.insert(0, 'extraction_emergency_stop')
|
||||
|
||||
# [STEP 4] 状态归类。
|
||||
@@ -276,6 +325,8 @@ def evaluate_candidate_qualification(
|
||||
blocking_reason_codes=blocking_reason_codes,
|
||||
)
|
||||
evidence_snapshot = _evidence_snapshot(candidate)
|
||||
if xfa_eval.get('evidence_extra'):
|
||||
evidence_snapshot = {**evidence_snapshot, **xfa_eval['evidence_extra']}
|
||||
score = _qualification_score(gates)
|
||||
confidence_policy = {
|
||||
'minimum_confidence': float(min_confidence),
|
||||
@@ -287,6 +338,7 @@ def evaluate_candidate_qualification(
|
||||
'confidence_policy': confidence_policy,
|
||||
}
|
||||
|
||||
can_auto_create = status == 'eligible'
|
||||
return {
|
||||
'status': status,
|
||||
'gates': gates,
|
||||
@@ -295,7 +347,8 @@ def evaluate_candidate_qualification(
|
||||
'parser_trace': parser_trace,
|
||||
'evidence_snapshot': evidence_snapshot,
|
||||
'qualification_score': score,
|
||||
'can_auto_create': status == 'eligible',
|
||||
'can_auto_create': can_auto_create,
|
||||
'shadow_would_auto_create': bool(xfa_eval.get('shadow_would_auto_create')),
|
||||
'evaluator_version': CANDIDATE_QUALIFICATION_EVALUATOR_VERSION,
|
||||
'confidence_policy': confidence_policy,
|
||||
}
|
||||
@@ -326,7 +379,7 @@ def build_qualification_snapshot(evaluation: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
def recalculate_candidate_qualification(
|
||||
*,
|
||||
candidate: ShippingNoticeCandidate,
|
||||
candidate: ShippingOrderCandidate,
|
||||
run: Any | None = None,
|
||||
unit: Any | None = None,
|
||||
fields_complete: bool | None = None,
|
||||
@@ -450,11 +503,269 @@ def recalculate_candidate_qualification(
|
||||
return evaluation
|
||||
|
||||
|
||||
def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) -> dict[str, Any]:
|
||||
"""组装解析链路痕迹;模板批准仅作治理信息。"""
|
||||
def _route_decision(*, unit: Any | None, run: Any | None) -> dict[str, Any]:
|
||||
"""合并 Unit 路由决策与 Run 冻结策略中的 Profile 身份。"""
|
||||
route: dict[str, Any] = {}
|
||||
if unit is not None and isinstance(getattr(unit, 'route_decision_json', None), dict):
|
||||
route = dict(unit.route_decision_json or {})
|
||||
if run is not None:
|
||||
policy = getattr(run, 'auto_freeze_policy_json', None)
|
||||
if isinstance(policy, dict):
|
||||
if policy.get('selected_profile_id') and not route.get('selected_profile_id'):
|
||||
route = {
|
||||
**route,
|
||||
'selected_profile_id': policy.get('selected_profile_id'),
|
||||
'selected_profile_code': policy.get('selected_profile_code'),
|
||||
'selected_profile_checksum': policy.get('selected_profile_checksum'),
|
||||
}
|
||||
return route
|
||||
|
||||
|
||||
def _is_xfa_candidate(*, candidate: Any, route: dict[str, Any]) -> bool:
|
||||
"""
|
||||
判定 Candidate 是否来自 XFA 数据路径。
|
||||
|
||||
核心逻辑:优先 route.capability_kind / template_mode / xfa_* 摘要;
|
||||
其次 structured_result 上的 `_hxops_xfa_*` 痕迹。
|
||||
"""
|
||||
if str(route.get('capability_kind') or '').strip() == 'xfa_dataset':
|
||||
return True
|
||||
if str(route.get('template_mode') or '').strip() == 'xfa_dataset':
|
||||
return True
|
||||
if route.get('xfa_evidence_summary') or route.get('xfa_cross_checks') or route.get('xfa_structure'):
|
||||
return True
|
||||
extraction = str(getattr(candidate, 'extraction_source', '') or '').strip().lower()
|
||||
if extraction in {'xfa', 'xfa_dataset'}:
|
||||
return True
|
||||
structured = getattr(candidate, 'structured_result_json', None)
|
||||
if isinstance(structured, dict):
|
||||
if structured.get('_hxops_xfa_evidence') or structured.get('_hxops_xfa_structure'):
|
||||
return True
|
||||
if str(structured.get('template_mode') or '').strip() == 'xfa_dataset':
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _resolve_xfa_candidate_customer_id(candidate: Any) -> int | None:
|
||||
"""
|
||||
解析 XFA Candidate 的确认客户 ID(供白名单硬门禁)。
|
||||
|
||||
核心逻辑:优先 structured_result_json.customer.customer_id;再回退 bill_to 匹配表。
|
||||
"""
|
||||
structured = getattr(candidate, 'structured_result_json', None)
|
||||
if isinstance(structured, dict):
|
||||
customer = structured.get('customer')
|
||||
if isinstance(customer, dict) and customer.get('customer_id') is not None:
|
||||
try:
|
||||
return int(customer.get('customer_id'))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
try:
|
||||
return resolve_confirmed_bill_to_customer_id(candidate=candidate)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _evaluate_xfa_auto_create_gates(
|
||||
*,
|
||||
candidate: Any,
|
||||
run: Any | None,
|
||||
unit: Any | None,
|
||||
parser_trace: dict[str, Any],
|
||||
customer_resolved: bool | None,
|
||||
emergency_stop: bool,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
评估 XFA 试点硬门禁(并入统一 Candidate Qualification)。
|
||||
|
||||
核心逻辑(非 XFA 四门禁恒 True):
|
||||
1. 自动建单总开关由 Schema `auto_creation_policy` / CQ `auto_create_enabled` 统一裁决,
|
||||
本函数不再读取独立 XFA AUTO_CREATE 环境变量;
|
||||
2. shadow 开启时阻断真实建单但可写 would_auto_create;
|
||||
3. 当前 Profile checksum 须具备盲测批准(route/parser_trace.auto_create_approved);
|
||||
4. 客户 / Profile checksum / 场景白名单均须命中;空客户或空 checksum 名单 fail-closed;
|
||||
5. evidence 计数与四项 cross-check 状态齐全且仅为 matched/passed/skipped。
|
||||
|
||||
Returns:
|
||||
gates / reason_by_gate / parser_trace_extra / shadow_would_auto_create / evidence_extra。
|
||||
"""
|
||||
route = _route_decision(unit=unit, run=run)
|
||||
is_xfa = _is_xfa_candidate(candidate=candidate, route=route)
|
||||
na_gates = {
|
||||
'xfa_auto_create_policy': True,
|
||||
'xfa_profile_blind_approved': True,
|
||||
'xfa_pilot_allowlist': True,
|
||||
'xfa_evidence_integrity': True,
|
||||
}
|
||||
if not is_xfa:
|
||||
return {
|
||||
'gates': na_gates,
|
||||
'reason_by_gate': {},
|
||||
'parser_trace_extra': {
|
||||
'xfa_candidate': False,
|
||||
},
|
||||
'shadow_would_auto_create': False,
|
||||
'evidence_extra': {},
|
||||
}
|
||||
|
||||
# [STEP 1] 读取 shadow 与白名单;自动建单总开关不在此读取。
|
||||
shadow = False
|
||||
allow_customers: list[int] = []
|
||||
allow_checksums: list[str] = []
|
||||
allow_scenarios: list[str] = []
|
||||
try:
|
||||
shadow = bool(xfa_shadow_mode_enabled())
|
||||
allow_customers = list(xfa_customer_allowlist())
|
||||
allow_checksums = list(xfa_profile_checksum_allowlist())
|
||||
allow_scenarios = list(xfa_scenario_allowlist())
|
||||
except RuntimeError:
|
||||
shadow = False
|
||||
allow_customers, allow_checksums, allow_scenarios = [], [], ['shipping_notice_order']
|
||||
|
||||
profile_approved = bool(
|
||||
route.get('auto_create_approved')
|
||||
or parser_trace.get('profile_auto_create_approved')
|
||||
)
|
||||
|
||||
# [STEP 2] shadow 阻断真实建单;总开关由统一 auto_create_enabled 门禁负责。
|
||||
policy_ok = True
|
||||
policy_reason = None
|
||||
if shadow:
|
||||
policy_ok = False
|
||||
policy_reason = 'xfa_shadow_mode'
|
||||
|
||||
# [STEP 3] 盲测批准。
|
||||
blind_ok = profile_approved
|
||||
blind_reason = None if blind_ok else 'xfa_profile_not_blind_approved'
|
||||
|
||||
# [STEP 4] 三类白名单(空客户/checksum fail-closed)。
|
||||
allowlist_ok = True
|
||||
allowlist_reason = None
|
||||
customer_id = _resolve_xfa_candidate_customer_id(candidate)
|
||||
checksum = str(route.get('selected_profile_checksum') or parser_trace.get('profile_checksum') or '').strip()
|
||||
scenario = str(
|
||||
route.get('business_scenario')
|
||||
or parser_trace.get('business_scenario')
|
||||
or _DEFAULT_BUSINESS_SCENARIO
|
||||
).strip().lower()
|
||||
if not allow_customers or not allow_checksums:
|
||||
allowlist_ok = False
|
||||
allowlist_reason = 'xfa_allowlist_unconfigured'
|
||||
elif customer_id is None or int(customer_id) not in allow_customers:
|
||||
allowlist_ok = False
|
||||
allowlist_reason = 'xfa_customer_not_allowlisted'
|
||||
elif not checksum or checksum not in allow_checksums:
|
||||
allowlist_ok = False
|
||||
allowlist_reason = 'xfa_profile_checksum_not_allowlisted'
|
||||
elif scenario not in {str(item).strip().lower() for item in allow_scenarios}:
|
||||
allowlist_ok = False
|
||||
allowlist_reason = 'xfa_scenario_not_allowlisted'
|
||||
|
||||
# [STEP 5] evidence + cross-check 完整性。
|
||||
evidence_summary = route.get('xfa_evidence_summary')
|
||||
cross_checks = route.get('xfa_cross_checks')
|
||||
structured = getattr(candidate, 'structured_result_json', None)
|
||||
if not isinstance(evidence_summary, dict) and isinstance(structured, dict):
|
||||
evidence_summary = structured.get('_hxops_xfa_evidence')
|
||||
if not isinstance(cross_checks, dict) and isinstance(structured, dict):
|
||||
cross_checks = (
|
||||
structured.get('_hxops_xfa_cross_checks')
|
||||
if isinstance(structured.get('_hxops_xfa_cross_checks'), dict)
|
||||
else None
|
||||
)
|
||||
if not isinstance(evidence_summary, dict):
|
||||
evidence_summary = {}
|
||||
if not isinstance(cross_checks, dict):
|
||||
cross_checks = {}
|
||||
|
||||
evidence_ok = True
|
||||
evidence_reason = None
|
||||
header_count = int(evidence_summary.get('header_field_count') or 0)
|
||||
line_count = int(evidence_summary.get('line_row_count') or 0)
|
||||
required_cross_check_keys = (
|
||||
'mirror_status',
|
||||
'acroform_status',
|
||||
'line_amount_status',
|
||||
'total_amount_status',
|
||||
)
|
||||
if header_count <= 0 or line_count <= 0:
|
||||
evidence_ok = False
|
||||
evidence_reason = 'xfa_evidence_incomplete'
|
||||
else:
|
||||
missing_keys = [
|
||||
key for key in required_cross_check_keys
|
||||
if not str(cross_checks.get(key) or '').strip()
|
||||
]
|
||||
if missing_keys:
|
||||
evidence_ok = False
|
||||
evidence_reason = 'xfa_evidence_incomplete'
|
||||
else:
|
||||
statuses = {
|
||||
key: str(cross_checks.get(key) or '').strip().lower()
|
||||
for key in required_cross_check_keys
|
||||
}
|
||||
incomplete = {
|
||||
status for status in statuses.values()
|
||||
if status not in XFA_CROSS_CHECK_AUTO_CREATE_OK_STATUSES
|
||||
}
|
||||
if incomplete:
|
||||
evidence_ok = False
|
||||
evidence_reason = 'xfa_cross_check_failed'
|
||||
|
||||
gates = {
|
||||
'xfa_auto_create_policy': policy_ok,
|
||||
'xfa_profile_blind_approved': blind_ok,
|
||||
'xfa_pilot_allowlist': allowlist_ok,
|
||||
'xfa_evidence_integrity': evidence_ok,
|
||||
}
|
||||
reason_by_gate = {
|
||||
'xfa_auto_create_policy': policy_reason,
|
||||
'xfa_profile_blind_approved': blind_reason,
|
||||
'xfa_pilot_allowlist': allowlist_reason,
|
||||
'xfa_evidence_integrity': evidence_reason,
|
||||
}
|
||||
|
||||
# shadow:在其余试点门禁(除真实建单开关外)满足时记录 would_auto_create。
|
||||
shadow_base_ok = (
|
||||
blind_ok and allowlist_ok and evidence_ok and not emergency_stop
|
||||
)
|
||||
shadow_would = bool(shadow and shadow_base_ok)
|
||||
|
||||
_ = customer_resolved # 客户确认由统一 customer_confirmed 门禁负责。
|
||||
return {
|
||||
'gates': gates,
|
||||
'reason_by_gate': {k: v for k, v in reason_by_gate.items() if v},
|
||||
'parser_trace_extra': {
|
||||
'xfa_candidate': True,
|
||||
'xfa_shadow_mode': shadow,
|
||||
'xfa_auto_create_uses_schema_policy': True,
|
||||
'xfa_profile_blind_approved': profile_approved,
|
||||
'xfa_allowlist': {
|
||||
'customer_id': customer_id,
|
||||
'profile_checksum': checksum or None,
|
||||
'business_scenario': scenario,
|
||||
'customer_allowlisted': bool(
|
||||
customer_id is not None and int(customer_id) in allow_customers
|
||||
),
|
||||
'checksum_allowlisted': bool(checksum and checksum in allow_checksums),
|
||||
'scenario_allowlisted': scenario in {
|
||||
str(item).strip().lower() for item in allow_scenarios
|
||||
},
|
||||
},
|
||||
'note': 'xfa_hard_gates_plus_unified_candidate_qualification',
|
||||
},
|
||||
'shadow_would_auto_create': shadow_would,
|
||||
'evidence_extra': {
|
||||
'xfa_header_field_count': header_count,
|
||||
'xfa_line_row_count': line_count,
|
||||
'xfa_cross_check_keys': sorted(str(k) for k in cross_checks.keys()),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) -> dict[str, Any]:
|
||||
"""组装解析链路痕迹;坐标模板批准仅作治理信息,XFA 另有硬门禁。"""
|
||||
route = _route_decision(unit=unit, run=run)
|
||||
|
||||
extraction_source = str(getattr(candidate, 'extraction_source', '') or '').strip().lower()
|
||||
route_type = str(route.get('route_type') or '').strip()
|
||||
@@ -465,7 +776,7 @@ def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) ->
|
||||
route_type = 'llm_assisted'
|
||||
elif extraction_source in {'generic', 'generic_deterministic'}:
|
||||
route_type = 'generic_deterministic'
|
||||
elif extraction_source in {'profile', 'template', 'profile_deterministic'}:
|
||||
elif extraction_source in {'profile', 'template', 'profile_deterministic', 'xfa', 'xfa_dataset'}:
|
||||
route_type = 'profile_deterministic'
|
||||
else:
|
||||
route_type = 'unknown'
|
||||
@@ -476,13 +787,6 @@ def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) ->
|
||||
policy = getattr(run, 'auto_freeze_policy_json', None)
|
||||
if isinstance(policy, dict):
|
||||
policy_profile_status = policy.get('qualification_status')
|
||||
if policy.get('selected_profile_id') and not route.get('selected_profile_id'):
|
||||
route = {
|
||||
**route,
|
||||
'selected_profile_id': policy.get('selected_profile_id'),
|
||||
'selected_profile_code': policy.get('selected_profile_code'),
|
||||
'selected_profile_checksum': policy.get('selected_profile_checksum'),
|
||||
}
|
||||
|
||||
return {
|
||||
'parser_source': route_type,
|
||||
@@ -492,6 +796,8 @@ def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) ->
|
||||
'profile_checksum': route.get('selected_profile_checksum'),
|
||||
'profile_auto_create_approved': profile_approved,
|
||||
'profile_qualification_status': policy_profile_status,
|
||||
'capability_kind': route.get('capability_kind'),
|
||||
'template_mode': route.get('template_mode'),
|
||||
'note': 'template_quality_only_not_auto_create_gate',
|
||||
}
|
||||
|
||||
@@ -650,27 +956,9 @@ def _key_fields_confidence_ok(
|
||||
if value < threshold:
|
||||
return False
|
||||
|
||||
# LLM 且未标注关键字段:要求每条置信度声明均可解析且达阈值。
|
||||
if is_llm and key_fields_seen == 0:
|
||||
numeric_only = all(not isinstance(v, dict) for v in raw.values())
|
||||
if numeric_only:
|
||||
for value in raw.values():
|
||||
try:
|
||||
if float(value) < default_threshold:
|
||||
return False
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return True
|
||||
for item in raw.values():
|
||||
if not isinstance(item, dict):
|
||||
return False
|
||||
if item.get('confidence', item.get('value')) is None:
|
||||
return False
|
||||
try:
|
||||
if float(item.get('confidence', item.get('value'))) < default_threshold:
|
||||
return False
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
# 没有任何字段被配置为自动建单关键字段时,字段置信度只做诊断,
|
||||
# 不得把普通字段的低分误作为自动建单阻断。
|
||||
if key_fields_seen == 0:
|
||||
return True
|
||||
|
||||
numeric_only = all(not isinstance(v, dict) for v in raw.values())
|
||||
@@ -733,13 +1021,36 @@ def _evidence_ok(candidate: Any) -> bool:
|
||||
|
||||
|
||||
def _conflicts_ok(candidate: Any) -> bool:
|
||||
"""字段冲突是否已清空。"""
|
||||
"""真正影响订单事实的字段冲突是否已清空;版面质量诊断不参与门禁。"""
|
||||
return len(blocking_candidate_conflicts(candidate)) == 0
|
||||
|
||||
|
||||
def _pdf_priority_conflict_reason(candidate: Any) -> str | None:
|
||||
"""
|
||||
从 Candidate.conflicts_json 提取 PDF 优先冲突细因码。
|
||||
|
||||
核心逻辑:优先返回 pdf_preferred_critical_conflict;其次 pdf_preferred;
|
||||
无匹配则返回 None,由门禁默认 field_conflict 承接。
|
||||
|
||||
Args:
|
||||
candidate: Candidate 或兼容替身。
|
||||
|
||||
Returns:
|
||||
细因码或 None。
|
||||
"""
|
||||
conflicts = getattr(candidate, 'conflicts_json', None)
|
||||
if not conflicts:
|
||||
return True
|
||||
if isinstance(conflicts, list):
|
||||
return len(conflicts) == 0
|
||||
return False
|
||||
if not isinstance(conflicts, list):
|
||||
return None
|
||||
reasons = {
|
||||
str(item.get('reason') or item.get('reason_code') or '').strip()
|
||||
for item in conflicts
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
if 'pdf_preferred_critical_conflict' in reasons:
|
||||
return 'pdf_preferred_critical_conflict'
|
||||
if 'pdf_preferred' in reasons:
|
||||
return 'pdf_preferred'
|
||||
return None
|
||||
|
||||
|
||||
def _duplicate_ok(candidate: Any) -> bool:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/candidate_service.py
|
||||
|
||||
用途:提供订单候选的用户态查询、选择与重复决策能力;含 STP 严格建单门禁。
|
||||
依赖:ShippingNoticeCandidate/Document/Intake、duplicate_detection、business_fingerprint。
|
||||
依赖:ShippingOrderCandidate/Document/Intake、duplicate_detection、business_fingerprint。
|
||||
逻辑:workspace API 调用本模块;所有写操作锁定 Candidate,并在字段变化后重算双指纹和重复状态;
|
||||
仅严格门禁通过且客户已确认的 Candidate 可物化 Task
|
||||
(缺字段/低置信/缺证据/重复冲突/客户未确认 → 拒绝)。
|
||||
@@ -15,7 +15,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import FileAsset, ShippingNoticeCandidate, ShippingNoticeDocument, ShippingNoticeIntake, ShippingTask, User
|
||||
from app.models import FileAsset, ShippingOrderCandidate, ShippingOrderDocument, ShippingOrderIntake, ShippingNotice, User
|
||||
from app.services.shipping_notice.business_fingerprint import build_business_fingerprint, build_content_fingerprint
|
||||
from app.services.shipping_notice.document_candidate_persist import _serialize_candidate_brief
|
||||
from app.services.shipping_notice.duplicate_detection import apply_duplicate_result_to_candidate, detect_duplicates_for_candidate
|
||||
@@ -25,7 +25,7 @@ _ACTIONS = frozenset({'open_existing', 'create_revision', 'force_create'})
|
||||
_STP_DUPLICATE_OK = frozenset({'none', 'unchecked'})
|
||||
|
||||
|
||||
def evaluate_candidate_stp_gate(candidate: ShippingNoticeCandidate) -> tuple[bool, list[str]]:
|
||||
def evaluate_candidate_stp_gate(candidate: ShippingOrderCandidate) -> tuple[bool, list[str]]:
|
||||
"""
|
||||
评估 Candidate 是否通过 STP 严格建单门禁(不抛异常)。
|
||||
|
||||
@@ -43,7 +43,9 @@ def evaluate_candidate_stp_gate(candidate: ShippingNoticeCandidate) -> tuple[boo
|
||||
reasons: list[str] = []
|
||||
if str(candidate.validation_status or '') != 'ready':
|
||||
reasons.append('incomplete_fields')
|
||||
if candidate.conflicts_json:
|
||||
from app.services.shipping_notice.candidate_qualification_service import blocking_candidate_conflicts
|
||||
|
||||
if blocking_candidate_conflicts(candidate):
|
||||
reasons.append('blocking_conflict')
|
||||
missing = list(candidate.missing_fields_json or [])
|
||||
if missing:
|
||||
@@ -64,7 +66,7 @@ def evaluate_candidate_stp_gate(candidate: ShippingNoticeCandidate) -> tuple[boo
|
||||
return not reasons, sorted(set(reasons))
|
||||
|
||||
|
||||
def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> None:
|
||||
def ensure_candidate_fulfillment_ready(candidate: ShippingOrderCandidate) -> None:
|
||||
"""
|
||||
统一履约门禁:已接受、当前、无阻断;建 Task 前客户必须已确认;
|
||||
automatic 候选额外通过 STP 严格门禁。
|
||||
@@ -83,7 +85,9 @@ def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> No
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SUPERSEDED', message='订单候选已被重新识别版本替代')
|
||||
if candidate.consumed_task_id is not None:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选已被消费')
|
||||
if str(candidate.validation_status or '') != 'ready' or candidate.conflicts_json:
|
||||
from app.services.shipping_notice.candidate_qualification_service import blocking_candidate_conflicts
|
||||
|
||||
if str(candidate.validation_status or '') != 'ready' or blocking_candidate_conflicts(candidate):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
|
||||
message='订单候选仍有字段冲突或未完成审核',
|
||||
@@ -104,15 +108,15 @@ def ensure_candidate_fulfillment_ready(candidate: ShippingNoticeCandidate) -> No
|
||||
)
|
||||
|
||||
|
||||
def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument]:
|
||||
def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False) -> tuple[ShippingOrderCandidate, ShippingOrderIntake, ShippingOrderDocument]:
|
||||
"""按候选编号和用户加载 Candidate、Intake、Document;写路径可加行锁。"""
|
||||
query = (
|
||||
db.session.query(ShippingNoticeCandidate, ShippingNoticeIntake, ShippingNoticeDocument)
|
||||
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeCandidate.intake_id)
|
||||
.join(ShippingNoticeDocument, ShippingNoticeDocument.id == ShippingNoticeCandidate.primary_document_id)
|
||||
db.session.query(ShippingOrderCandidate, ShippingOrderIntake, ShippingOrderDocument)
|
||||
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderCandidate.intake_id)
|
||||
.join(ShippingOrderDocument, ShippingOrderDocument.id == ShippingOrderCandidate.primary_document_id)
|
||||
.filter(
|
||||
ShippingNoticeCandidate.candidate_no == str(candidate_no or '').strip().upper(),
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingOrderCandidate.candidate_no == str(candidate_no or '').strip().upper(),
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
)
|
||||
)
|
||||
if lock:
|
||||
@@ -123,7 +127,7 @@ def _candidate_for_user(candidate_no: str, user_id: int, *, lock: bool = False)
|
||||
return row
|
||||
|
||||
|
||||
def _refresh_candidate(candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake, document: ShippingNoticeDocument) -> dict[str, Any]:
|
||||
def _refresh_candidate(candidate: ShippingOrderCandidate, intake: ShippingOrderIntake, document: ShippingOrderDocument) -> dict[str, Any]:
|
||||
"""重算 Candidate 双指纹和重复状态,不提交事务。"""
|
||||
structured = candidate.structured_result_json if isinstance(candidate.structured_result_json, dict) else {}
|
||||
summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
|
||||
@@ -166,7 +170,7 @@ def update_candidate(*, user_id: int, candidate_no: str, selected: bool) -> dict
|
||||
return _serialize_candidate_brief(candidate)
|
||||
|
||||
|
||||
def _append_candidate_decision_history(candidate: ShippingNoticeCandidate, *, action: str, user_id: int, reason: str | None = None) -> None:
|
||||
def _append_candidate_decision_history(candidate: ShippingOrderCandidate, *, action: str, user_id: int, reason: str | None = None) -> None:
|
||||
"""记录人工采纳或驳回事件,便于审核回放。"""
|
||||
structured = dict(candidate.structured_result_json or {})
|
||||
history = list(structured.get('manual_review_history') or [])
|
||||
@@ -192,7 +196,13 @@ def promote_candidate(*, user_id: int, candidate_no: str) -> dict[str, Any]:
|
||||
if candidate.consumed_task_id is not None or not candidate.is_current_version:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_ALREADY_CONSUMED', message='订单候选不可再采纳')
|
||||
_refresh_candidate(candidate, intake, document)
|
||||
if candidate.validation_status != 'ready' or candidate.conflicts_json or candidate.duplicate_status not in {'none', 'unchecked'}:
|
||||
from app.services.shipping_notice.candidate_qualification_service import blocking_candidate_conflicts
|
||||
|
||||
if (
|
||||
candidate.validation_status != 'ready'
|
||||
or blocking_candidate_conflicts(candidate)
|
||||
or candidate.duplicate_status not in {'none', 'unchecked'}
|
||||
):
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED', message='请先完成字段和重复审核')
|
||||
candidate.candidate_status = 'accepted'
|
||||
candidate.acceptance_mode = 'manual'
|
||||
@@ -283,7 +293,7 @@ def resolve_candidate_duplicate(*, user_id: int, candidate_no: str, action: str,
|
||||
)
|
||||
if not target_no or not any(str(item.get('task_no') or '').upper() == target_no for item in matches):
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在或已变化')
|
||||
target = db.session.query(ShippingTask).filter_by(task_no=target_no, user_id=int(user_id)).first()
|
||||
target = db.session.query(ShippingNotice).filter_by(task_no=target_no, user_id=int(user_id)).first()
|
||||
if target is None:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.DUPLICATE_TARGET_NOT_FOUND', message='重复目标任务不存在')
|
||||
if action_norm == 'force_create':
|
||||
|
||||
@@ -13,6 +13,7 @@ from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.notice_lines import non_atomic_part_number_field, normalize_notice_line
|
||||
from app.services.shipping_notice.notice_line_values import parse_number
|
||||
from app.services.shipping_notice.order_schema.field_rules import compute_effective_reservation_id
|
||||
from app.services.shipping_notice.po_number import normalize_atomic_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
@@ -40,6 +41,7 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
raw_lines = raw.get('lines') if isinstance(raw.get('lines'), list) else []
|
||||
normalized_lines: list[dict[str, Any]] = []
|
||||
invalid_lines: list[dict[str, Any]] = []
|
||||
missing_required: set[str] = set()
|
||||
for index, item in enumerate(raw_lines):
|
||||
raw_line = item if isinstance(item, dict) else None
|
||||
non_atomic_field = non_atomic_part_number_field(raw_line)
|
||||
@@ -52,7 +54,23 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
continue
|
||||
normalized = normalize_notice_line(raw_line)
|
||||
if normalized is None:
|
||||
invalid_lines.append({'line_index': index, 'reason': 'missing_part_number_or_positive_qty'})
|
||||
raw_part_number = str((raw_line or {}).get('part_number') or '').strip()
|
||||
raw_qty = parse_number(
|
||||
(raw_line or {}).get('qty')
|
||||
if (raw_line or {}).get('qty') is not None
|
||||
else (raw_line or {}).get('quantity')
|
||||
)
|
||||
line_missing = []
|
||||
if not raw_part_number:
|
||||
line_missing.append('part_number')
|
||||
if raw_qty is None or raw_qty <= 0:
|
||||
line_missing.append('qty')
|
||||
missing_required.update(line_missing)
|
||||
invalid_lines.append({
|
||||
'line_index': index,
|
||||
'reason': 'missing_part_number_or_positive_qty',
|
||||
'fields': line_missing,
|
||||
})
|
||||
continue
|
||||
raw_reservation = str(normalized.get('reservation_id') or '').strip()
|
||||
if raw_reservation and not validated_reservation_id(raw_reservation):
|
||||
@@ -81,9 +99,8 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
))
|
||||
})
|
||||
|
||||
missing_required: list[str] = []
|
||||
if not normalized_lines:
|
||||
missing_required.extend(BUILD_REQUIRED_FIELDS)
|
||||
if not normalized_lines and not invalid_lines:
|
||||
missing_required.update(BUILD_REQUIRED_FIELDS)
|
||||
# 有效 Reservation 是逐行匹配键;头级可回填行级缺失。
|
||||
missing_process = [
|
||||
field
|
||||
@@ -103,7 +120,7 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
'normalized_summary': normalized_summary,
|
||||
'can_create_task': bool(normalized_lines) and not invalid_lines,
|
||||
'can_auto_progress': bool(normalized_lines) and not invalid_lines and not missing_process,
|
||||
'missing_required_fields': sorted(set(missing_required)),
|
||||
'missing_required_fields': sorted(missing_required),
|
||||
'missing_process_fields': missing_process,
|
||||
'invalid_lines': invalid_lines,
|
||||
'process_issues': [],
|
||||
|
||||
@@ -2,39 +2,36 @@
|
||||
backend/app/services/shipping_notice/chat_action_extended_handlers.py
|
||||
|
||||
用途:货代 Chat Turn 扩展 Action Handler(通知重传/切票/缺口查询)。
|
||||
依赖:shipping_tools、task_workflow、tool_common、shipping_turn_helpers、action_registry。
|
||||
逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大。
|
||||
依赖:shipping_tools、task_workflow、batch_legacy_removed、shipping_turn_helpers、action_registry。
|
||||
逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大;
|
||||
co8 后 switch_batch_focus 固定 410。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Iterator
|
||||
|
||||
from app import db
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.services.chat.action_registry import register_action_handler
|
||||
from app.services.chat.action_schema import TurnEvent
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_batch_for_user,
|
||||
get_task_by_ref,
|
||||
get_task_for_user,
|
||||
serialize_task_detail,
|
||||
)
|
||||
from app.services.shipping_notice.shortage_details import format_shortage_details_message
|
||||
from app.services.shipping_notice.shipping_turn_context import (
|
||||
resolve_shipping_batch_no,
|
||||
resolve_shipping_task_no,
|
||||
)
|
||||
from app.services.shipping_notice.shipping_turn_helpers import (
|
||||
shipping_batch_ui_state_event,
|
||||
shipping_task_ui_state_event,
|
||||
stream_text_events,
|
||||
tool_result_message,
|
||||
)
|
||||
from app.services.shipping_notice.task_workflow import replace_task_notice
|
||||
from app.services.shipping_notice.tool_common import switch_batch_focus
|
||||
|
||||
|
||||
def _payload_str(payload: dict[str, Any], *keys: str) -> str:
|
||||
@@ -126,15 +123,10 @@ class ShippingReplaceNoticeAction:
|
||||
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield shipping_task_ui_state_event(refreshed)
|
||||
batch_no = refreshed.batch.batch_no if refreshed.batch is not None else None
|
||||
if batch_no and ctx.user_id is not None:
|
||||
batch_event = shipping_batch_ui_state_event(batch_no, ctx.user_id)
|
||||
if batch_event is not None:
|
||||
yield batch_event
|
||||
content = _format_replace_notice_message(result, task.task_no)
|
||||
yield from stream_text_events(
|
||||
content,
|
||||
payload={"task_no": task.task_no, "batch_no": batch_no, "tool_result": result},
|
||||
payload={"task_no": task.task_no, "tool_result": result},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "replace_notice"})
|
||||
|
||||
@@ -176,41 +168,15 @@ class ShippingSwitchBatchFocusAction:
|
||||
action_type = "shipping.switch_batch_focus"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
user_id = ctx.user_id
|
||||
if user_id is None:
|
||||
raise ValidationError("user context is required")
|
||||
batch_no = resolve_shipping_batch_no(ctx)
|
||||
if not batch_no:
|
||||
raise ValidationError("batch_no is required")
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
task_no = _payload_str(payload, "task_no", "taskNo", "target_task_no").upper()
|
||||
if not task_no:
|
||||
task_no = resolve_shipping_task_no(ctx)
|
||||
if not task_no:
|
||||
raise ValidationError("task_no is required")
|
||||
batch = get_batch_for_user(batch_no, user_id)
|
||||
if batch is None:
|
||||
raise NotFoundError(f"Batch not found: {batch_no}")
|
||||
task = get_task_for_user(task_no, user_id)
|
||||
if task is None or task.batch_id != batch.id:
|
||||
raise NotFoundError("Task not found in batch")
|
||||
yield TurnEvent(event="step.started", data={"step_id": "switch_batch_focus", "label": "切换焦点任务..."})
|
||||
switch_batch_focus(
|
||||
batch,
|
||||
task,
|
||||
source="chat_turn",
|
||||
comment=_payload_str(payload, "comment") or None,
|
||||
extra={"actor_user_id": user_id},
|
||||
)
|
||||
db.session.commit()
|
||||
batch_event = shipping_batch_ui_state_event(batch_no, user_id)
|
||||
if batch_event is not None:
|
||||
yield batch_event
|
||||
else:
|
||||
yield shipping_task_ui_state_event(task)
|
||||
content = f"已切换到任务 {task_no},请继续当前票处理。"
|
||||
yield from stream_text_events(content, payload={"batch_no": batch_no, "task_no": task_no})
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "switch_batch_focus"})
|
||||
"""
|
||||
历史批次切票(已下线)。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
del ctx
|
||||
raise_shipping_batches_removed(action='shipping.switch_batch_focus')
|
||||
yield from () # pragma: no cover — raise 后不可达,满足 Iterator 注解
|
||||
|
||||
|
||||
class ShippingQueryShortageDetailsAction:
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
backend/app/services/shipping_notice/chat_action_handlers.py
|
||||
|
||||
用途:货代发货通知 Chat Turn Action Handler 注册实现。
|
||||
依赖:decision_workflow、fulfillment_workflow、inventory_rpa_workflow、query_service、ui_state、action_registry。
|
||||
逻辑:turn_runtime 按 action_type 路由至本模块 handler;handler 只编排 yield 事件,业务逻辑委托既有 workflow。
|
||||
依赖:decision_workflow、fulfillment_workflow、inventory_rpa_workflow、query_service、ui_state、action_registry、
|
||||
batch_legacy_removed。
|
||||
逻辑:turn_runtime 按 action_type 路由至本模块 handler;handler 只编排 yield 事件,业务逻辑委托既有 workflow;
|
||||
co8 后 create_batch_* 动作统一 raise_shipping_batches_removed,改走 order-extraction-submissions。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,7 +21,6 @@ from app.services.shipping_notice.decision_workflow import submit_decision
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref, get_task_for_user
|
||||
from app.services.shipping_notice.shipping_turn_context import resolve_shipping_task_no
|
||||
from app.services.shipping_notice.shipping_turn_helpers import (
|
||||
shipping_batch_ui_state_event as _shipping_batch_ui_state_event,
|
||||
shipping_task_ui_state_event as _shipping_ui_state_event,
|
||||
stream_text_events as _stream_text_events,
|
||||
tool_result_message as _tool_result_message,
|
||||
@@ -90,135 +91,41 @@ def _match_result_payload(task_no: str, result: dict[str, Any]) -> dict[str, Any
|
||||
|
||||
|
||||
class ShippingCreateBatchFromNoticesAction:
|
||||
"""上传发货通知附件并创建批次。"""
|
||||
"""历史:上传发货通知并创建 shipping_batches;co8 后已下线。"""
|
||||
|
||||
action_type = "shipping.create_batch_from_notices"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
user_id = ctx.user_id
|
||||
if user_id is None:
|
||||
raise ValidationError("user context is required")
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
notice_items = payload.get("notice_items")
|
||||
if not isinstance(notice_items, list) or not notice_items:
|
||||
raise ValidationError("notice_items is required")
|
||||
file_summary = payload.get("file_summary") if isinstance(payload.get("file_summary"), dict) else None
|
||||
conversation_id = _payload_str(payload, "conversation_id", "conversationId") or None
|
||||
idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None
|
||||
"""
|
||||
拒绝旧建批 Turn。
|
||||
|
||||
yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_notices", "label": "处理发货通知..."})
|
||||
核心逻辑:shipping_batches 已 DROP;客户端须走 Intake + order-extraction-submissions。
|
||||
"""
|
||||
del ctx
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
from app.services.shipping_notice.batch_from_notices import (
|
||||
create_shipping_batch_from_notice_items,
|
||||
format_batch_created_assistant_message,
|
||||
)
|
||||
|
||||
result = create_shipping_batch_from_notice_items(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
notice_items=notice_items,
|
||||
file_summary=file_summary,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
batch_no = str(result.get("batch_no") or "").strip()
|
||||
if batch_no:
|
||||
batch_event = _shipping_batch_ui_state_event(batch_no, user_id)
|
||||
if batch_event is not None:
|
||||
yield batch_event
|
||||
|
||||
file_count = len(notice_items)
|
||||
content = format_batch_created_assistant_message(result, file_count=file_count)
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
|
||||
message_payload = {
|
||||
"batch_no": batch_no,
|
||||
"task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(),
|
||||
"orchestrator_started": bool(data.get("orchestrator_started")),
|
||||
"idempotent_replay": bool(result.get("idempotent_replay")),
|
||||
}
|
||||
yield from _stream_text_events(content, message_type="text", payload=message_payload)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_notices"})
|
||||
raise_shipping_batches_removed(action='shipping.create_batch_from_notices')
|
||||
if False: # pragma: no cover — 满足 Iterator 注解
|
||||
yield TurnEvent(event='step.started', data={})
|
||||
|
||||
|
||||
class ShippingCreateBatchFromIntakesAction:
|
||||
"""基于已解析接入记录确认建批(第二阶段主路径)。"""
|
||||
"""历史:基于 Intake 确认建批;co8 后已下线,改走订单抽取提交。"""
|
||||
|
||||
action_type = "shipping.create_batch_from_intakes"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
user_id = ctx.user_id
|
||||
if user_id is None:
|
||||
raise ValidationError("user context is required")
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
intake_nos = payload.get("intake_nos")
|
||||
if not isinstance(intake_nos, list) or not intake_nos:
|
||||
raise ValidationError("intake_nos is required")
|
||||
# 空白新会话 payload 常无 conversation_id;回退到 Chat Turn 刚创建的本地 session_id
|
||||
conversation_id = (
|
||||
_payload_str(payload, "conversation_id", "conversationId")
|
||||
or str(getattr(ctx, "session_id", "") or "").strip()
|
||||
or None
|
||||
)
|
||||
idempotency_key = _payload_str(payload, "idempotency_key", "idempotencyKey") or None
|
||||
candidate_nos = payload.get("candidate_nos")
|
||||
if candidate_nos is not None and not isinstance(candidate_nos, list):
|
||||
raise ValidationError("candidate_nos must be a list")
|
||||
"""
|
||||
拒绝旧建批 Turn。
|
||||
|
||||
yield TurnEvent(event="step.started", data={"step_id": "create_batch_from_intakes", "label": "确认建单..."})
|
||||
核心逻辑:请使用 POST /order-extraction-submissions 创建 OT/Run。
|
||||
"""
|
||||
del ctx
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_intakes
|
||||
from app.services.shipping_notice.batch_from_notices import format_batch_created_assistant_message
|
||||
|
||||
result = create_shipping_batch_from_intakes(
|
||||
user_id=user_id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=[str(item) for item in intake_nos],
|
||||
candidate_nos=[str(item) for item in candidate_nos] if isinstance(candidate_nos, list) else None,
|
||||
create_idempotency_key=idempotency_key,
|
||||
)
|
||||
opened = result.get("opened_existing") if isinstance(result.get("opened_existing"), list) else []
|
||||
if opened and not str(result.get("batch_no") or "").strip():
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
|
||||
task_no = str(focus_task.get("task_no") or opened[0].get("task_no") or "").strip()
|
||||
if task_no:
|
||||
task = get_task_by_ref(task_no)
|
||||
if task is not None:
|
||||
yield _shipping_ui_state_event(task)
|
||||
content = str(result.get("message") or "已打开已有任务,未创建新批次")
|
||||
yield from _stream_text_events(
|
||||
content,
|
||||
message_type="text",
|
||||
payload={
|
||||
"opened_existing": True,
|
||||
"task_no": task_no,
|
||||
"intake_nos": [str(item.get("intake_no") or "") for item in opened],
|
||||
},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_intakes"})
|
||||
return
|
||||
|
||||
batch_no = str(result.get("batch_no") or "").strip()
|
||||
if batch_no:
|
||||
batch_event = _shipping_batch_ui_state_event(batch_no, user_id)
|
||||
if batch_event is not None:
|
||||
yield batch_event
|
||||
|
||||
file_count = len(candidate_nos) if isinstance(candidate_nos, list) and candidate_nos else len(intake_nos)
|
||||
content = format_batch_created_assistant_message(result, file_count=file_count)
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
focus_task = data.get("focus_task") if isinstance(data.get("focus_task"), dict) else {}
|
||||
message_payload = {
|
||||
"batch_no": batch_no,
|
||||
"task_no": str(focus_task.get("task_no") or result.get("task_id") or "").strip(),
|
||||
"orchestrator_started": bool(data.get("orchestrator_started")),
|
||||
"idempotent_replay": bool(result.get("idempotent_replay")),
|
||||
"document_version": focus_task.get("document_version"),
|
||||
"duplicate_resolution_type": focus_task.get("duplicate_resolution_type"),
|
||||
"supersedes_task_no": focus_task.get("supersedes_task_no"),
|
||||
}
|
||||
yield from _stream_text_events(content, message_type="text", payload=message_payload)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "create_batch_from_intakes"})
|
||||
raise_shipping_batches_removed(action='shipping.create_batch_from_intakes')
|
||||
if False: # pragma: no cover
|
||||
yield TurnEvent(event='step.started', data={})
|
||||
|
||||
|
||||
class ShippingSubmitDecisionAction:
|
||||
|
||||
@@ -42,7 +42,7 @@ def build_chat_actions_payload(task) -> dict:
|
||||
action_buttons 已由 ui_state 在存在 ProcessExecution 时按 Gate 规则收缩(阻断清零)。
|
||||
|
||||
Args:
|
||||
task: ShippingTask 模型实例。
|
||||
task: ShippingNotice 模型实例。
|
||||
|
||||
Returns:
|
||||
包含 task_no、checkpoint、process_gate、action_buttons 与摘要的字典。
|
||||
|
||||
@@ -13,7 +13,7 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import ForbiddenError
|
||||
from app.models import ChatSession, ShippingTask
|
||||
from app.models import ChatSession, ShippingNotice
|
||||
|
||||
|
||||
READ_SCOPES = frozenset({'get_shipping_status', 'get_batch_status'})
|
||||
@@ -50,7 +50,7 @@ def require_chat_capability(*, token: Any, scope: str, task_no: str | None = Non
|
||||
if session is None:
|
||||
raise ForbiddenError('Chat capability session is invalid', code='SHIPPING.CHAT_CAPABILITY_DENIED')
|
||||
if task_no:
|
||||
task = ShippingTask.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none()
|
||||
task = ShippingNotice.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none()
|
||||
if task is None or str(body.get('task') or '').upper() != task.task_no:
|
||||
raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED')
|
||||
if batch_no and str(body.get('batch') or '').upper() != str(batch_no).upper():
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/context_fields/runtime.py
|
||||
|
||||
用途:从 Intake 冻结邮件元数据采集通用上下文字段,并写入统一 Observation/Decision/FieldValue 链路。
|
||||
依赖:ShippingNoticeIntake、订单动态字段模型、customer_normalization。
|
||||
依赖:ShippingOrderIntake、订单动态字段模型、customer_normalization。
|
||||
逻辑:只读取原始 EML From;按发布快照 option_key 投影邮箱/域名,缺失或非法时形成 missing Decision。
|
||||
"""
|
||||
|
||||
@@ -14,7 +14,7 @@ from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
@@ -23,7 +23,7 @@ from app.models import (
|
||||
from app.services.shipping_notice.customer_normalization import normalize_domain, normalize_email
|
||||
|
||||
|
||||
def canonical_mail_context(intake: ShippingNoticeIntake) -> dict[str, str]:
|
||||
def canonical_mail_context(intake: ShippingOrderIntake) -> dict[str, str]:
|
||||
"""从 Intake 的 EML From 解析唯一规范邮箱及域名,供快照和裁决共用。"""
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
email_meta = structured.get('email') if isinstance(structured.get('email'), dict) else {}
|
||||
@@ -52,7 +52,7 @@ def _existing_value(extraction_id: int, field_id: str) -> tuple[ShippingOrderFie
|
||||
|
||||
|
||||
def persist_deterministic_context_fields(
|
||||
*, extraction: ShippingOrderExtraction, intake: ShippingNoticeIntake,
|
||||
*, extraction: ShippingOrderExtraction, intake: ShippingOrderIntake,
|
||||
configs: list[dict[str, Any]], frozen_values: dict[str, Any] | None = None,
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]], list[str]]:
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,851 @@
|
||||
"""
|
||||
services/shipping_notice/conversation_processing_projection.py
|
||||
|
||||
用途:将会话内订单抽取 Run 投影为「本次处理中」用户可见任务分组。
|
||||
依赖:ShippingOrderProcessingRun、progress_audit_contract、
|
||||
order_extraction_run_service.evaluate_can_append、workflow_ledger_service.find_workflow_for_run、
|
||||
order_extraction_workspace_projection._run_available_actions。
|
||||
逻辑:由 GET conversations/{id}/processing 与统一提交响应内嵌;按 needs_action /
|
||||
processing / completed / history 分组;未查看成功结果进 completed,与异常态分离;
|
||||
先加载全部当前有效右侧候选 Run(无归并前截断),再加载同 OT 的历史谱系;
|
||||
每个 PDF 独立选择最新有效版本,归并后再按任务数截断;
|
||||
任务—PDF 两层:单 PDF 用文件名作 title;多 PDF 用 display_kind=multi_document_task,
|
||||
file_count 按 content_hash/root/document 去重;objects 含当前 PDF 子对象。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingAuditEvent,
|
||||
ShippingOrderProcessingRun,
|
||||
)
|
||||
from app.services.shipping_notice.progress_audit_contract import (
|
||||
CONVERSATION_PROCESSING_TASK_GROUPS,
|
||||
)
|
||||
|
||||
_NEEDS_ACTION_RUN_STATUSES = frozenset({
|
||||
'review_required',
|
||||
'failed',
|
||||
'partially_completed',
|
||||
})
|
||||
_PROCESSING_RUN_STATUSES = frozenset({
|
||||
'queued',
|
||||
'processing',
|
||||
})
|
||||
_HISTORY_RUN_STATUSES = frozenset({
|
||||
'completed',
|
||||
'cancelled',
|
||||
})
|
||||
# 右侧可能展示的 Run 状态(未替代前提下);completed 还需未查看才输出。
|
||||
_RIGHT_PANEL_RUN_STATUSES = frozenset({
|
||||
'queued',
|
||||
'processing',
|
||||
'failed',
|
||||
'review_required',
|
||||
'partially_completed',
|
||||
'completed',
|
||||
})
|
||||
_NEEDS_ACTION_ITEM_LIFECYCLES = frozenset({
|
||||
'pending_review',
|
||||
'manual_upload_pending',
|
||||
'failed',
|
||||
'reparse_failed',
|
||||
})
|
||||
_PROCESSING_ITEM_LIFECYCLES = frozenset({
|
||||
'queued',
|
||||
'layout_parsing',
|
||||
'extracting',
|
||||
'building_order',
|
||||
'inventory_matching',
|
||||
'generating_excel',
|
||||
})
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
"""UTC ISO8601(带 Z);空值返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
return value.isoformat() + 'Z'
|
||||
|
||||
|
||||
def _iter_snapshot_business_documents(run: ShippingOrderProcessingRun) -> list[dict[str, Any]]:
|
||||
"""
|
||||
收集 Run 快照中的业务 PDF 行(排除 email_body)。
|
||||
|
||||
核心逻辑:优先 input_snapshot,再回退 request_snapshot;保留快照原始字段供去重。
|
||||
"""
|
||||
rows: list[dict[str, Any]] = []
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
request = run.request_snapshot_json if isinstance(run.request_snapshot_json, dict) else {}
|
||||
for source in (snapshot, request):
|
||||
for intake_index, intake in enumerate(source.get('intakes') or []):
|
||||
if not isinstance(intake, dict):
|
||||
continue
|
||||
for doc_index, document in enumerate(intake.get('documents') or []):
|
||||
if not isinstance(document, dict):
|
||||
continue
|
||||
if str(document.get('document_type') or '') == 'email_body':
|
||||
continue
|
||||
rows.append({
|
||||
**document,
|
||||
'_intake_index': intake_index,
|
||||
'_doc_index': doc_index,
|
||||
})
|
||||
if rows:
|
||||
break
|
||||
if rows:
|
||||
return rows
|
||||
# 快照尚无 documents 时,回退选择计划中的附件行。
|
||||
for source in (snapshot, request):
|
||||
selection = source.get('attachment_selection') if isinstance(source.get('attachment_selection'), dict) else {}
|
||||
for item_index, item in enumerate(selection.get('items') or []):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if not bool(item.get('selected')) and not int(item.get('selection_batch') or 0):
|
||||
continue
|
||||
rows.append({
|
||||
'document_id': item.get('document_id'),
|
||||
'root_document_id': item.get('root_document_id'),
|
||||
'filename': item.get('filename'),
|
||||
'content_hash': item.get('content_hash') or item.get('asset_content_hash'),
|
||||
'document_type': 'attachment',
|
||||
'_intake_index': 0,
|
||||
'_doc_index': item_index,
|
||||
})
|
||||
if rows:
|
||||
break
|
||||
return rows
|
||||
|
||||
|
||||
def _document_identity_key(document: dict[str, Any]) -> str:
|
||||
"""
|
||||
业务 PDF 稳定身份:content_hash → root_document_id → document_id。
|
||||
|
||||
禁止仅用文件名去重(同名不同内容必须计为两个 PDF)。
|
||||
"""
|
||||
content_hash = str(
|
||||
document.get('content_hash') or document.get('asset_content_hash') or '',
|
||||
).strip().lower()
|
||||
if content_hash:
|
||||
return f'hash:{content_hash}'
|
||||
root_id = int(document.get('root_document_id') or 0)
|
||||
if root_id > 0:
|
||||
return f'root:{root_id}'
|
||||
document_id = int(document.get('document_id') or 0)
|
||||
if document_id > 0:
|
||||
return f'doc:{document_id}'
|
||||
# 无稳定 ID 时按快照位置区分,避免同名不同文件被误合并。
|
||||
return (
|
||||
f'anon:{int(document.get("_intake_index") or 0)}:'
|
||||
f'{int(document.get("_doc_index") or 0)}:'
|
||||
f'{str(document.get("filename") or "").strip().lower()}'
|
||||
)
|
||||
|
||||
|
||||
def _document_identity_keys(document: dict[str, Any]) -> list[str]:
|
||||
"""
|
||||
返回 PDF 的全部稳定身份别名,供多数据源交叉去重。
|
||||
|
||||
核心逻辑:哈希用于识别跨 document_id 重传;root/document ID 用于消除同一文档在
|
||||
快照、Unit、WorkflowItem 中字段完整度不同造成的重复。无稳定字段时回退单一匿名键。
|
||||
|
||||
Args:
|
||||
document: 任一来源的业务 PDF 行。
|
||||
|
||||
Returns:
|
||||
按 content_hash → root_document_id → document_id 排序的身份键列表。
|
||||
"""
|
||||
keys: list[str] = []
|
||||
content_hash = str(
|
||||
document.get('content_hash') or document.get('asset_content_hash') or '',
|
||||
).strip().lower()
|
||||
root_id = int(document.get('root_document_id') or 0)
|
||||
document_id = int(document.get('document_id') or 0)
|
||||
if content_hash:
|
||||
keys.append(f'hash:{content_hash}')
|
||||
if root_id > 0:
|
||||
keys.append(f'root:{root_id}')
|
||||
if document_id > 0:
|
||||
keys.append(f'doc:{document_id}')
|
||||
return keys or [_document_identity_key(document)]
|
||||
|
||||
|
||||
def _iter_unit_business_documents(run: ShippingOrderProcessingRun) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从 ExtractionUnit + Document ORM 收集业务 PDF。
|
||||
|
||||
核心逻辑:快照可能尚未写全 documents,但 Unit 已按文档拆分;以 ORM 为准补齐。
|
||||
"""
|
||||
from app.models import ShippingOrderDocument
|
||||
|
||||
plan = getattr(run, 'extraction_plan', None)
|
||||
units = list(getattr(plan, 'units', None) or []) if plan is not None else []
|
||||
rows: list[dict[str, Any]] = []
|
||||
for index, unit in enumerate(units):
|
||||
document_id = int(getattr(unit, 'document_id', 0) or 0)
|
||||
if document_id <= 0:
|
||||
continue
|
||||
document = db.session.get(ShippingOrderDocument, document_id)
|
||||
if document is None:
|
||||
continue
|
||||
if str(getattr(document, 'document_type', None) or '') == 'email_body':
|
||||
continue
|
||||
rows.append({
|
||||
'document_id': int(document.id),
|
||||
'root_document_id': int(document.id),
|
||||
'document_type': str(getattr(document, 'document_type', None) or 'attachment'),
|
||||
'filename': str(getattr(document, 'filename', None) or '').strip() or None,
|
||||
'content_hash': str(getattr(document, 'content_hash', None) or '').strip().lower() or None,
|
||||
'unit_status': str(getattr(unit, 'status', None) or '').strip() or None,
|
||||
'_intake_index': 0,
|
||||
'_doc_index': index,
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def _iter_workflow_item_documents(run: ShippingOrderProcessingRun) -> list[dict[str, Any]]:
|
||||
"""
|
||||
历史:从 WorkflowItem 收集业务 PDF;co8 后台账已 DROP。
|
||||
|
||||
核心逻辑:直接返回空列表,由快照/Unit 路径提供文件列表。
|
||||
|
||||
Args:
|
||||
run: 抽取 Run(保留签名以兼容调用方)。
|
||||
|
||||
Returns:
|
||||
空列表。
|
||||
"""
|
||||
del run
|
||||
return []
|
||||
|
||||
|
||||
def _unique_business_documents(run: ShippingOrderProcessingRun) -> list[dict[str, Any]]:
|
||||
"""
|
||||
按稳定身份去重后的当前业务 PDF 列表(同一内容只保留一条)。
|
||||
|
||||
核心逻辑:合并快照 + ExtractionUnit + WorkflowItem 三路来源;
|
||||
同 hash 的重传不增加 file_count;同名不同 hash 计为多个。
|
||||
"""
|
||||
snapshot_documents = _iter_snapshot_business_documents(run)
|
||||
unit_documents = _iter_unit_business_documents(run)
|
||||
workflow_documents = _iter_workflow_item_documents(run)
|
||||
# [STEP 1] 完整快照是 Run 的审计事实;只有 Unit/Workflow 明确包含更多 PDF 时才补齐。
|
||||
# 这样既支持生产中的稀疏快照,也避免 ORM 中旧文件名/哈希覆盖已冻结快照。
|
||||
supplemental_count = max(len(unit_documents), len(workflow_documents))
|
||||
documents = list(snapshot_documents)
|
||||
if not snapshot_documents or supplemental_count > len(snapshot_documents):
|
||||
documents.extend(unit_documents)
|
||||
documents.extend(workflow_documents)
|
||||
|
||||
# [STEP 2] 对最终来源按全部稳定身份别名交叉去重。
|
||||
unique: list[dict[str, Any]] = []
|
||||
seen: dict[str, int] = {}
|
||||
for document in documents:
|
||||
keys = _document_identity_keys(document)
|
||||
existing_index = next((seen[key] for key in keys if key in seen), None)
|
||||
if existing_index is None:
|
||||
for key in keys:
|
||||
seen[key] = len(unique)
|
||||
unique.append(document)
|
||||
continue
|
||||
# 同身份保留 document_id 更大的当前版,并补齐缺失文件名/哈希。
|
||||
previous = unique[existing_index]
|
||||
prev_id = int(previous.get('document_id') or 0)
|
||||
next_id = int(document.get('document_id') or 0)
|
||||
merged = dict(previous)
|
||||
if next_id >= prev_id:
|
||||
merged.update({k: v for k, v in document.items() if v not in (None, '')})
|
||||
# update 可能留下旧 id;显式采用较大 document_id。
|
||||
if next_id > 0:
|
||||
merged['document_id'] = next_id
|
||||
else:
|
||||
for key_name in ('filename', 'content_hash', 'root_document_id', 'unit_status'):
|
||||
if not merged.get(key_name) and document.get(key_name):
|
||||
merged[key_name] = document.get(key_name)
|
||||
unique[existing_index] = merged
|
||||
for key in _document_identity_keys(merged):
|
||||
seen[key] = existing_index
|
||||
return unique
|
||||
|
||||
|
||||
def _file_count(run: ShippingOrderProcessingRun) -> int:
|
||||
"""统计去重后的业务 PDF 数(不含 email_body,不按文件名去重)。"""
|
||||
return len(_unique_business_documents(run))
|
||||
|
||||
|
||||
def _unit_status_by_document_id(run: ShippingOrderProcessingRun) -> dict[int, str]:
|
||||
"""从 ExtractionUnit 读取文档级状态,供 PDF 子对象投影。"""
|
||||
plan = getattr(run, 'extraction_plan', None)
|
||||
units = list(getattr(plan, 'units', None) or []) if plan is not None else []
|
||||
mapping: dict[int, str] = {}
|
||||
for unit in units:
|
||||
document_id = int(getattr(unit, 'document_id', 0) or 0)
|
||||
if document_id <= 0:
|
||||
continue
|
||||
mapping[document_id] = str(getattr(unit, 'status', None) or '').strip() or 'pending'
|
||||
return mapping
|
||||
|
||||
|
||||
def _task_title_and_display_kind(
|
||||
documents: list[dict[str, Any]],
|
||||
) -> tuple[str | None, str, list[str]]:
|
||||
"""
|
||||
解析任务标题与展示类型。
|
||||
|
||||
核心逻辑:仅单 PDF 允许用文件名作 title;多 PDF 返回 title=None + multi_document_task。
|
||||
|
||||
Returns:
|
||||
(title, display_kind, document_names)
|
||||
"""
|
||||
names: list[str] = []
|
||||
for document in documents:
|
||||
name = str(document.get('filename') or '').strip()
|
||||
if name:
|
||||
names.append(name)
|
||||
if len(documents) == 1:
|
||||
title = names[0] if names else None
|
||||
return title, 'single_document_task', names
|
||||
return None, 'multi_document_task', names
|
||||
|
||||
|
||||
def _attachment_fingerprint_key(run: ShippingOrderProcessingRun) -> tuple[str, ...] | None:
|
||||
"""会话投影用的附件身份键;空指纹返回 None。"""
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
_business_attachment_fingerprint,
|
||||
)
|
||||
|
||||
snapshot = (
|
||||
run.request_snapshot_json
|
||||
if isinstance(run.request_snapshot_json, dict)
|
||||
else run.input_snapshot_json
|
||||
)
|
||||
fingerprint = _business_attachment_fingerprint(snapshot if isinstance(snapshot, dict) else None)
|
||||
return fingerprint or None
|
||||
|
||||
|
||||
def _resolve_task_group(run: ShippingOrderProcessingRun) -> str:
|
||||
"""
|
||||
将「当前有效 Run」映射为会话顶层分组。
|
||||
|
||||
核心逻辑(版本维度与业务状态分离):
|
||||
- superseded_by_run_id 非空 → history(已被新版本替代);
|
||||
- needs_action:复核/失败/部分完成(异常或需人工决策);
|
||||
- processing:queued/processing;
|
||||
- completed 且尚未查看 → completed(成功通知,与 needs_action 分离);
|
||||
- completed 已查看 / cancelled → history(右侧不展示)。
|
||||
"""
|
||||
if getattr(run, 'superseded_by_run_id', None) is not None:
|
||||
return 'history'
|
||||
status = str(run.status or '')
|
||||
if status in _NEEDS_ACTION_RUN_STATUSES:
|
||||
return 'needs_action'
|
||||
if status in _PROCESSING_RUN_STATUSES:
|
||||
return 'processing'
|
||||
if status == 'completed':
|
||||
# [UI-01] 未查看的成功完成进入 completed 分组,不与失败/复核混排。
|
||||
if run.seen_at is None:
|
||||
return 'completed'
|
||||
if run.attention_generated_at is not None and run.seen_at < run.attention_generated_at:
|
||||
return 'completed'
|
||||
return 'history'
|
||||
if status in _HISTORY_RUN_STATUSES:
|
||||
return 'history'
|
||||
return 'history'
|
||||
|
||||
|
||||
def _status_label(run: ShippingOrderProcessingRun) -> str:
|
||||
"""
|
||||
用户可见状态码(前端 i18n);禁止直接拼自然语言。
|
||||
|
||||
映射为稳定展示码:queued / processing / pending_review / failed /
|
||||
completed / cancelling / cancelled / unknown。
|
||||
"""
|
||||
if getattr(run, 'cancellation_requested_at', None) is not None and str(run.status or '') not in {
|
||||
'cancelled', 'completed',
|
||||
}:
|
||||
return 'cancelling'
|
||||
status = str(run.status or '').strip() or 'unknown'
|
||||
if status == 'review_required':
|
||||
return 'pending_review'
|
||||
if status == 'partially_completed':
|
||||
return 'pending_review'
|
||||
if status in {
|
||||
'queued', 'processing', 'failed', 'completed', 'cancelled',
|
||||
}:
|
||||
return status
|
||||
return status or 'unknown'
|
||||
|
||||
|
||||
def _is_current_effective_run(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""未被后继 Run 替代的当前有效版本。"""
|
||||
return getattr(run, 'superseded_by_run_id', None) is None
|
||||
|
||||
|
||||
def _run_recency_key(run: ShippingOrderProcessingRun) -> tuple:
|
||||
"""版本选择键:优先未替代 → 最近活动 → 最近创建 → 更大 id。"""
|
||||
activity = run.last_activity_at or run.created_at
|
||||
created = run.created_at
|
||||
return (
|
||||
1 if _is_current_effective_run(run) else 0,
|
||||
activity or datetime.min,
|
||||
created or datetime.min,
|
||||
int(run.id or 0),
|
||||
)
|
||||
|
||||
def _latest_focused_task_no(*, user_id: int, conversation_id: str) -> str | None:
|
||||
"""
|
||||
从最近一次 focus 审计恢复会话焦点(无 ChatSession 元数据时的轻量回退)。
|
||||
|
||||
Args:
|
||||
user_id: 属主用户。
|
||||
conversation_id: 聊天会话 ID。
|
||||
|
||||
Returns:
|
||||
最近聚焦的 user_task_no;无记录返回 None。
|
||||
"""
|
||||
row = (
|
||||
ShippingAuditEvent.query.filter(
|
||||
ShippingAuditEvent.event_type == 'conversation_processing_task_focused',
|
||||
ShippingAuditEvent.conversation_id == str(conversation_id),
|
||||
ShippingAuditEvent.owner_user_id == str(user_id),
|
||||
)
|
||||
.order_by(ShippingAuditEvent.id.desc())
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
meta = row.metadata_json if isinstance(row.metadata_json, dict) else {}
|
||||
task_no = str(meta.get('user_task_no') or row.task_no or '').strip()
|
||||
return task_no or None
|
||||
|
||||
|
||||
def _effective_business_documents(
|
||||
runs: list[ShippingOrderProcessingRun],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从同一用户任务的 Run 谱系中解析当前有效 PDF 集合。
|
||||
|
||||
核心逻辑:按 content_hash → root_document_id → document_id 识别 PDF;每个身份
|
||||
独立选择最近 Run 中的版本,避免局部重识别时把旧 Run 内未重识别的 PDF 一并丢失。
|
||||
|
||||
Args:
|
||||
runs: 同一用户任务的全部 Run,允许包含已被后继替代的来源 Run。
|
||||
|
||||
Returns:
|
||||
去重后的当前有效 PDF 行;每行附带 `_source_run` 供对象级状态与 Run 号投影。
|
||||
"""
|
||||
selected: list[tuple[tuple, dict[str, Any]]] = []
|
||||
identity_indexes: dict[str, int] = {}
|
||||
for run in runs:
|
||||
for document in _unique_business_documents(run):
|
||||
identities = _document_identity_keys(document)
|
||||
candidate = {
|
||||
**document,
|
||||
'_source_run': run,
|
||||
}
|
||||
key = (
|
||||
_run_recency_key(run),
|
||||
int(document.get('document_id') or 0),
|
||||
)
|
||||
existing_index = next(
|
||||
(identity_indexes[identity] for identity in identities if identity in identity_indexes),
|
||||
None,
|
||||
)
|
||||
if existing_index is None:
|
||||
existing_index = len(selected)
|
||||
selected.append((key, candidate))
|
||||
for identity in identities:
|
||||
identity_indexes[identity] = existing_index
|
||||
continue
|
||||
if key > selected[existing_index][0]:
|
||||
selected[existing_index] = (key, candidate)
|
||||
for identity in identities:
|
||||
identity_indexes[identity] = existing_index
|
||||
return [row[1] for row in selected]
|
||||
|
||||
|
||||
def _simplified_objects(
|
||||
run: ShippingOrderProcessingRun,
|
||||
*,
|
||||
documents: list[dict[str, Any]] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
投影任务下对象行:当前 Run + 去重后的当前 PDF 文档(不含历史版本重复)。
|
||||
|
||||
Args:
|
||||
run: 任务级操作与状态的代表 Run。
|
||||
documents: 可选的跨 Run 当前有效 PDF 集合;空时仅使用代表 Run。
|
||||
|
||||
Returns:
|
||||
ConversationProcessingObject 形状列表。
|
||||
"""
|
||||
user_task_no = str(getattr(run, 'user_task_no', None) or '').strip() or None
|
||||
objects: list[dict[str, Any]] = [{
|
||||
'kind': 'run',
|
||||
'object_key': f'RUN-{run.run_no}',
|
||||
'label': str(run.run_no),
|
||||
'status_label': _status_label(run),
|
||||
'run_no': run.run_no,
|
||||
'user_task_no': user_task_no,
|
||||
'focused': False,
|
||||
}]
|
||||
effective_documents = documents if documents is not None else _unique_business_documents(run)
|
||||
unit_status_by_run_id: dict[int, dict[int, str]] = {}
|
||||
for document in effective_documents:
|
||||
source_run = document.get('_source_run') or run
|
||||
source_run_id = int(getattr(source_run, 'id', 0) or 0)
|
||||
if source_run_id not in unit_status_by_run_id:
|
||||
unit_status_by_run_id[source_run_id] = _unit_status_by_document_id(source_run)
|
||||
unit_status = unit_status_by_run_id[source_run_id]
|
||||
document_id = int(document.get('document_id') or 0) or None
|
||||
root_document_id = int(document.get('root_document_id') or 0) or document_id
|
||||
filename = str(document.get('filename') or '').strip() or None
|
||||
content_hash = str(
|
||||
document.get('content_hash') or document.get('asset_content_hash') or '',
|
||||
).strip().lower() or None
|
||||
status_label = (
|
||||
str(document.get('unit_status') or '').strip()
|
||||
or (
|
||||
unit_status.get(int(document_id))
|
||||
if document_id is not None
|
||||
else None
|
||||
)
|
||||
or _status_label(source_run)
|
||||
)
|
||||
object_key = (
|
||||
f'DOC-{document_id}'
|
||||
if document_id is not None
|
||||
else f'DOC-{_document_identity_key(document)}'
|
||||
)
|
||||
objects.append({
|
||||
'kind': 'document',
|
||||
'object_key': object_key,
|
||||
'label': filename or object_key,
|
||||
'status_label': status_label,
|
||||
'run_no': source_run.run_no,
|
||||
'user_task_no': user_task_no,
|
||||
'document_id': document_id,
|
||||
'root_document_id': root_document_id,
|
||||
'filename': filename,
|
||||
'content_hash': content_hash,
|
||||
'current_run_no': source_run.run_no,
|
||||
'focused': False,
|
||||
})
|
||||
return objects
|
||||
|
||||
|
||||
def _resolve_workflow_no(run: ShippingOrderProcessingRun) -> str | None:
|
||||
"""
|
||||
解析用户任务所属 Workflow 编号,供前端跨批次切换文件列表。
|
||||
|
||||
核心逻辑:委托 find_workflow_for_run(Item.current_run_id / 重识别源 Case)。
|
||||
"""
|
||||
from app.services.shipping_notice.workflow_ledger_service import find_workflow_for_run
|
||||
|
||||
workflow = find_workflow_for_run(run=run)
|
||||
if workflow is None:
|
||||
return None
|
||||
return str(getattr(workflow, 'workflow_no', None) or '').strip() or None
|
||||
|
||||
|
||||
def _resolve_task_actions(run: ShippingOrderProcessingRun) -> tuple[str | None, list[str]]:
|
||||
"""
|
||||
聚合任务级权威操作;前端禁止自行按状态推导按钮。
|
||||
|
||||
核心逻辑:复用 workspace `_run_available_actions`,再映射会话任务卡常用动作码。
|
||||
|
||||
Returns:
|
||||
(primary_action, available_actions)
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_workspace_projection import (
|
||||
_run_available_actions,
|
||||
)
|
||||
|
||||
plan = getattr(run, 'extraction_plan', None)
|
||||
units = list(getattr(plan, 'units', None) or []) if plan is not None else []
|
||||
raw_actions = _run_available_actions(run, units)
|
||||
# 会话任务卡动作别名:与评审契约对齐,同时保留既有 workspace 动作码。
|
||||
actions: list[str] = []
|
||||
for action in raw_actions:
|
||||
code = str(action or '').strip()
|
||||
if not code:
|
||||
continue
|
||||
if code not in actions:
|
||||
actions.append(code)
|
||||
if code == 'enter_manual_review' and 'open_review' not in actions:
|
||||
actions.append('open_review')
|
||||
if code == 'cancel_run' and 'cancel_task' not in actions:
|
||||
actions.append('cancel_task')
|
||||
if code == 'retry_failed_attachments' and 'retry_failed_documents' not in actions:
|
||||
actions.append('retry_failed_documents')
|
||||
|
||||
if 'view_details' not in actions:
|
||||
actions.insert(0, 'view_details')
|
||||
|
||||
primary: str | None = None
|
||||
for candidate in (
|
||||
'open_review',
|
||||
'enter_manual_review',
|
||||
'retry_failed_documents',
|
||||
'retry_failed_attachments',
|
||||
'cancel_task',
|
||||
'cancel_run',
|
||||
'view_details',
|
||||
):
|
||||
if candidate in actions:
|
||||
primary = candidate
|
||||
break
|
||||
return primary, actions
|
||||
|
||||
|
||||
def _project_user_task(
|
||||
run: ShippingOrderProcessingRun,
|
||||
*,
|
||||
focused_task_no: str | None,
|
||||
documents: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将单个 Run 投影为用户可见任务摘要。
|
||||
|
||||
Args:
|
||||
run: 当前用户会话内负责任务级状态与操作的代表 Run。
|
||||
focused_task_no: 当前焦点任务号。
|
||||
documents: 同 OT 跨 Run 汇总后的当前有效 PDF;空时仅投影代表 Run。
|
||||
|
||||
Returns:
|
||||
ConversationProcessingUserTask 字典。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
evaluate_can_append,
|
||||
)
|
||||
|
||||
can_append, block_reason = evaluate_can_append(run)
|
||||
# [UI-01 / BE-03] 仅暴露已持久化的 OT 编号;Candidate 前不得派生伪 OT。
|
||||
user_task_no = str(getattr(run, 'user_task_no', None) or '').strip()
|
||||
group = _resolve_task_group(run)
|
||||
assert group in CONVERSATION_PROCESSING_TASK_GROUPS
|
||||
viewed = run.seen_at is not None and run.attention_generated_at is not None and (
|
||||
run.seen_at >= run.attention_generated_at
|
||||
)
|
||||
primary_action, available_actions = _resolve_task_actions(run)
|
||||
effective_documents = documents if documents is not None else _unique_business_documents(run)
|
||||
title, display_kind, document_names = _task_title_and_display_kind(effective_documents)
|
||||
return {
|
||||
'user_task_no': user_task_no,
|
||||
'submission_ordinal': getattr(run, 'submission_ordinal', None),
|
||||
'title': title,
|
||||
'display_kind': display_kind,
|
||||
'document_names': document_names,
|
||||
'group': group,
|
||||
'status_label': _status_label(run),
|
||||
'file_count': len(effective_documents),
|
||||
'run_no': run.run_no,
|
||||
'workflow_no': _resolve_workflow_no(run),
|
||||
'can_append': can_append,
|
||||
'append_block_reason': block_reason,
|
||||
'input_lifecycle': getattr(run, 'input_lifecycle', None) or 'open',
|
||||
'input_frozen_at': _iso(getattr(run, 'input_frozen_at', None)),
|
||||
'focused': bool(focused_task_no and focused_task_no == user_task_no),
|
||||
'viewed': bool(viewed),
|
||||
'acknowledged': False,
|
||||
'last_activity_at': _iso(run.last_activity_at or run.updated_at),
|
||||
'created_at': _iso(run.created_at),
|
||||
'recent_append_count': None,
|
||||
'recently_created': False,
|
||||
'primary_action': primary_action,
|
||||
'available_actions': available_actions,
|
||||
'objects': _simplified_objects(run, documents=effective_documents),
|
||||
}
|
||||
|
||||
|
||||
def project_conversation_processing(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
focused_task_no: str | None = None,
|
||||
recent_task_no: str | None = None,
|
||||
recent_decision: str | None = None,
|
||||
recent_append_count: int | None = None,
|
||||
limit: int = 50,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
投影会话级「本次处理中」用户可见任务。
|
||||
|
||||
核心逻辑:
|
||||
1. 先筛未替代且右侧可见状态的当前 Run,确定需要展示的用户任务;
|
||||
2. 加载这些 OT 的全部 Run 谱系,每个 PDF 身份独立选择最新版本;
|
||||
3. 同一 user_task_no 只输出一张任务卡,再按附件指纹归并重复任务;
|
||||
4. 输出 needs_action / processing / completed,最后按 task_limit 截断。
|
||||
"""
|
||||
normalized = str(conversation_id or '').strip()
|
||||
|
||||
focused = str(focused_task_no or '').strip() or None
|
||||
if not focused:
|
||||
focused = _latest_focused_task_no(user_id=int(user_id), conversation_id=normalized)
|
||||
|
||||
task_limit = max(1, min(int(limit or 50), 200))
|
||||
# [BE-02] 候选集仅含当前有效 + 右侧可见状态;不得在归并前用固定窗口截断。
|
||||
# 极端会话硬顶仅防失控读放大,远高于常规用户任务上限。
|
||||
# [UI-01 / BE-03] Candidate 前 user_task_no 为 NULL:不进右侧「订单任务」卡。
|
||||
candidate_hard_cap = 5000
|
||||
runs = (
|
||||
ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
ShippingOrderProcessingRun.conversation_id == normalized,
|
||||
ShippingOrderProcessingRun.superseded_by_run_id.is_(None),
|
||||
ShippingOrderProcessingRun.user_task_no.isnot(None),
|
||||
ShippingOrderProcessingRun.status.in_(sorted(_RIGHT_PANEL_RUN_STATUSES)),
|
||||
)
|
||||
.order_by(
|
||||
ShippingOrderProcessingRun.last_activity_at.desc().nullslast(),
|
||||
ShippingOrderProcessingRun.created_at.desc(),
|
||||
)
|
||||
.limit(candidate_hard_cap)
|
||||
.all()
|
||||
)
|
||||
|
||||
# [STEP 1] 同一 OT 只选择一个代表 Run(重识别不产生新用户任务)。
|
||||
latest_by_task: dict[str, ShippingOrderProcessingRun] = {}
|
||||
for run in runs:
|
||||
task_no = str(getattr(run, 'user_task_no', None) or '').strip()
|
||||
if not task_no:
|
||||
continue
|
||||
if task_no not in latest_by_task:
|
||||
latest_by_task[task_no] = run
|
||||
|
||||
active_task_nos = list(latest_by_task)
|
||||
lineage_runs = (
|
||||
ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
ShippingOrderProcessingRun.conversation_id == normalized,
|
||||
ShippingOrderProcessingRun.user_task_no.in_(active_task_nos),
|
||||
)
|
||||
.order_by(
|
||||
ShippingOrderProcessingRun.last_activity_at.asc().nullsfirst(),
|
||||
ShippingOrderProcessingRun.created_at.asc(),
|
||||
)
|
||||
.all()
|
||||
if active_task_nos
|
||||
else []
|
||||
)
|
||||
runs_by_task: dict[str, list[ShippingOrderProcessingRun]] = {
|
||||
task_no: [] for task_no in active_task_nos
|
||||
}
|
||||
for lineage_run in lineage_runs:
|
||||
task_no = str(getattr(lineage_run, 'user_task_no', None) or '').strip()
|
||||
if task_no in runs_by_task:
|
||||
runs_by_task[task_no].append(lineage_run)
|
||||
|
||||
# [STEP 2][BE-02] 按附件指纹归并任务卡;PDF 集合仍按各 OT 谱系独立汇总。
|
||||
latest_by_identity: dict[str, ShippingOrderProcessingRun] = {}
|
||||
task_nos_by_identity: dict[str, list[str]] = {}
|
||||
identity_order: list[str] = []
|
||||
for run in latest_by_task.values():
|
||||
fingerprint = _attachment_fingerprint_key(run)
|
||||
identity = (
|
||||
'fp:' + '|'.join(fingerprint)
|
||||
if fingerprint
|
||||
else f'task:{getattr(run, "user_task_no", None) or run.run_no}'
|
||||
)
|
||||
existing = latest_by_identity.get(identity)
|
||||
if existing is None:
|
||||
latest_by_identity[identity] = run
|
||||
task_nos_by_identity[identity] = [
|
||||
str(getattr(run, 'user_task_no', None) or '').strip(),
|
||||
]
|
||||
identity_order.append(identity)
|
||||
continue
|
||||
task_no = str(getattr(run, 'user_task_no', None) or '').strip()
|
||||
if task_no and task_no not in task_nos_by_identity[identity]:
|
||||
task_nos_by_identity[identity].append(task_no)
|
||||
if _run_recency_key(run) > _run_recency_key(existing):
|
||||
latest_by_identity[identity] = run
|
||||
|
||||
needs_action: list[dict[str, Any]] = []
|
||||
processing: list[dict[str, Any]] = []
|
||||
completed: list[dict[str, Any]] = []
|
||||
recent = str(recent_task_no or '').strip() or None
|
||||
decision = str(recent_decision or '').strip().lower() or None
|
||||
append_count = (
|
||||
max(0, int(recent_append_count))
|
||||
if recent_append_count is not None
|
||||
else None
|
||||
)
|
||||
for identity in identity_order:
|
||||
run = latest_by_identity[identity]
|
||||
# 已被替代的版本不进入右侧。
|
||||
if not _is_current_effective_run(run):
|
||||
continue
|
||||
source_runs: list[ShippingOrderProcessingRun] = []
|
||||
for task_no in task_nos_by_identity.get(identity, []):
|
||||
source_runs.extend(runs_by_task.get(task_no) or [latest_by_task[task_no]])
|
||||
effective_documents = _effective_business_documents(source_runs or [run])
|
||||
task = _project_user_task(
|
||||
run,
|
||||
focused_task_no=focused,
|
||||
documents=effective_documents,
|
||||
)
|
||||
if recent and task['user_task_no'] == recent:
|
||||
if decision == 'appended':
|
||||
task['recent_append_count'] = append_count if append_count is not None else 1
|
||||
task['recently_created'] = False
|
||||
else:
|
||||
task['recently_created'] = True
|
||||
task['recent_append_count'] = None
|
||||
group = task['group']
|
||||
if group == 'needs_action':
|
||||
needs_action.append(task)
|
||||
elif group == 'processing':
|
||||
processing.append(task)
|
||||
elif group == 'completed':
|
||||
completed.append(task)
|
||||
|
||||
# [STEP 3] 组内按最近活动时间降序;再按任务数截断(非原始 Run 数)。
|
||||
def _sort_key(item: dict[str, Any]) -> str:
|
||||
return str(item.get('last_activity_at') or item.get('created_at') or '')
|
||||
|
||||
needs_action.sort(key=_sort_key, reverse=True)
|
||||
processing.sort(key=_sort_key, reverse=True)
|
||||
completed.sort(key=_sort_key, reverse=True)
|
||||
|
||||
# 优先保留需处理与处理中,再填已完成通知。
|
||||
kept: list[tuple[str, dict[str, Any]]] = []
|
||||
for bucket, rows in (
|
||||
('needs_action', needs_action),
|
||||
('processing', processing),
|
||||
('completed', completed),
|
||||
):
|
||||
for row in rows:
|
||||
if len(kept) >= task_limit:
|
||||
break
|
||||
kept.append((bucket, row))
|
||||
if len(kept) >= task_limit:
|
||||
break
|
||||
needs_action = [row for bucket, row in kept if bucket == 'needs_action']
|
||||
processing = [row for bucket, row in kept if bucket == 'processing']
|
||||
completed = [row for bucket, row in kept if bucket == 'completed']
|
||||
|
||||
total_files = sum(
|
||||
int(item.get('file_count') or 0) for item in needs_action + processing + completed
|
||||
)
|
||||
total = len(needs_action) + len(processing) + len(completed)
|
||||
return {
|
||||
'summary': {
|
||||
'total_tasks': total,
|
||||
'total_files': total_files,
|
||||
'processing': len(processing),
|
||||
'needs_action': len(needs_action),
|
||||
'completed': len(completed),
|
||||
'history': 0,
|
||||
},
|
||||
'focused_task_no': focused,
|
||||
'recent_task_no': recent,
|
||||
'needs_action': needs_action,
|
||||
'processing': processing,
|
||||
'completed': completed,
|
||||
'history': [],
|
||||
}
|
||||
@@ -20,12 +20,12 @@ from app.models import (
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingTask,
|
||||
ShippingNotice,
|
||||
ShippingTaskEvent,
|
||||
)
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
@@ -49,7 +49,7 @@ CUSTOMER_AUDIT_EVENT_TYPES = (
|
||||
|
||||
def auto_customer_resolution_enabled() -> bool:
|
||||
"""读取自动客户确认总开关;默认关闭以支持安全降级。"""
|
||||
return cfg_bool("SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED", False)
|
||||
return cfg_bool("SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED", True)
|
||||
|
||||
|
||||
def _auto_confirmation_quality_gate() -> dict[str, Any]:
|
||||
@@ -227,7 +227,12 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
|
||||
if not definition or not normalized:
|
||||
continue
|
||||
verified_normalized = _verified_shadow_value(shadow, definition, evidence)
|
||||
if verified_normalized is None or verified_normalized != normalized:
|
||||
# 影子记录可能来自旧版本规则快照,邮箱/编码的大小写规范化存在历史差异。
|
||||
# 使用同一指纹的大小写无关比较,避免合法唯一命中被误判为 unmatched。
|
||||
if (
|
||||
verified_normalized is None
|
||||
or verified_normalized.casefold() != normalized.casefold()
|
||||
):
|
||||
continue
|
||||
field_value_source = evidence['source']
|
||||
if (
|
||||
@@ -238,16 +243,26 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
|
||||
continue
|
||||
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
context_source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
|
||||
# 兼容旧规则快照:若未保存 context_source,则从定义编码识别邮箱/域名指纹类型。
|
||||
option_key = str(context_source.get('option_key') or '').strip().lower()
|
||||
if not option_key:
|
||||
definition_code = str(definition.get('definition_code') or '').lower()
|
||||
if 'email' in definition_code or 'mail' in definition_code:
|
||||
option_key = 'from_email'
|
||||
elif 'domain' in definition_code:
|
||||
option_key = 'from_domain'
|
||||
email_domain = normalized.rsplit('@', 1)[-1] if '@' in normalized else normalized
|
||||
if context_source.get('option_key') in {'from_email', 'from_domain'} and is_public_email_domain(email_domain):
|
||||
if option_key in {'from_email', 'from_domain'} and is_public_email_domain(email_domain):
|
||||
continue
|
||||
records = db.session.query(ShippingIdentityEvidence).filter_by(
|
||||
definition_id=definition_id,
|
||||
normalized_value=normalized,
|
||||
status='approved',
|
||||
auto_match_allowed=True,
|
||||
).all()
|
||||
for record in records:
|
||||
# 主数据中历史录入值也可能保留不同大小写;按指纹语义比较而非原始字符串比较。
|
||||
if str(record.normalized_value or '').strip().casefold() != normalized.casefold():
|
||||
continue
|
||||
if record.customer_id is None:
|
||||
continue
|
||||
customer = db.session.get(ShippingCustomer, int(record.customer_id))
|
||||
@@ -273,7 +288,7 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
|
||||
return result
|
||||
|
||||
|
||||
def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
|
||||
def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""
|
||||
使用任务来源 Candidate 的影子证据执行受控自动裁决。
|
||||
|
||||
@@ -282,24 +297,15 @@ def resolve_auto_customer_from_shadow(task: ShippingTask) -> dict[str, Any]:
|
||||
Returns:
|
||||
status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。
|
||||
"""
|
||||
if not auto_customer_resolution_enabled():
|
||||
return {"status": "disabled", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
quality_gate = _auto_confirmation_quality_gate()
|
||||
if not quality_gate['is_eligible']:
|
||||
return {
|
||||
'status': quality_gate['status'],
|
||||
'rule_version': AUTO_RESOLUTION_VERSION,
|
||||
'customer_id': None,
|
||||
'evidence': [],
|
||||
'quality_gate': quality_gate,
|
||||
}
|
||||
# [PARAM_TUNING] 业务策略改为:已发布识别指纹唯一命中即可自动确认;
|
||||
# 不再以全局开关、历史标注样本量或准确率二次阻断唯一确定结果。
|
||||
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(
|
||||
candidate_id=int(task.source_candidate_id),
|
||||
).first()
|
||||
if shadow is None:
|
||||
candidate = db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id))
|
||||
candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id))
|
||||
if candidate is not None:
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
|
||||
|
||||
@@ -307,10 +313,14 @@ def resolve_auto_customer_from_shadow(task: ShippingTask) -> 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': quality_gate}
|
||||
return {**_resolve_auto_customer_from_shadow_resolution(shadow), 'quality_gate': {
|
||||
'status': 'bypassed_unique_match_policy',
|
||||
'is_eligible': True,
|
||||
'reason': '唯一识别指纹命中直接自动确认',
|
||||
}}
|
||||
|
||||
|
||||
def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]:
|
||||
def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""
|
||||
尝试自动确认并生成业务编号;未达门槛时保持 customer_review。
|
||||
|
||||
@@ -348,7 +358,7 @@ def try_auto_confirm_task_customer(task: ShippingTask) -> dict[str, Any]:
|
||||
|
||||
|
||||
def correct_numbered_task_customer(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
customer_id: int,
|
||||
reason: str,
|
||||
@@ -419,9 +429,9 @@ def correct_numbered_task_customer(
|
||||
)
|
||||
|
||||
versions = (
|
||||
db.session.query(ShippingTask)
|
||||
db.session.query(ShippingNotice)
|
||||
.filter_by(shipping_case_id=original_case.id)
|
||||
.order_by(ShippingTask.document_version.asc(), ShippingTask.id.asc())
|
||||
.order_by(ShippingNotice.document_version.asc(), ShippingNotice.id.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
@@ -539,8 +549,8 @@ def get_auto_resolution_metrics() -> dict[str, Any]:
|
||||
event_type="customer_correction_applied",
|
||||
).distinct().count()
|
||||
recent_events = (
|
||||
db.session.query(ShippingTaskEvent, ShippingTask.task_no)
|
||||
.join(ShippingTask, ShippingTask.id == ShippingTaskEvent.task_id)
|
||||
db.session.query(ShippingTaskEvent, ShippingNotice.task_no)
|
||||
.join(ShippingNotice, ShippingNotice.id == ShippingTaskEvent.task_id)
|
||||
.filter(ShippingTaskEvent.event_type.in_(CUSTOMER_AUDIT_EVENT_TYPES))
|
||||
.order_by(ShippingTaskEvent.id.desc())
|
||||
.limit(100)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/customer_identity_gate.py
|
||||
|
||||
用途:货代任务标准客户确认、业务编号生成、候选查询与统一下游硬门禁。
|
||||
依赖:ShippingTask/Case/Customer/Event、business_numbering_service、统一 AppError、customer_normalization。
|
||||
依赖:ShippingNotice/Case/Customer/Event、business_numbering_service、统一 AppError、customer_normalization。
|
||||
逻辑:业务用户只能选择已启用标准客户;确认与业务编号在同一事务完成,并同步业务单全部任务版本。
|
||||
"""
|
||||
|
||||
@@ -16,14 +16,14 @@ from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingCase, ShippingCustomer, ShippingTask, ShippingTaskEvent
|
||||
from app.models import ShippingCase, 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: ShippingTask) -> bool:
|
||||
def customer_identity_is_confirmed(task: ShippingNotice) -> bool:
|
||||
"""判断任务是否已关联业务单并通过标准客户确认。"""
|
||||
if task.shipping_case_id is None:
|
||||
return False
|
||||
@@ -34,7 +34,7 @@ def customer_identity_is_confirmed(task: ShippingTask) -> bool:
|
||||
return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed')
|
||||
|
||||
|
||||
def assert_customer_identity_gate(task: ShippingTask, *, operation: str = 'continue') -> None:
|
||||
def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'continue') -> None:
|
||||
"""
|
||||
标准客户硬门禁;业务单缺失或客户未确认时阻断库存、RPA、匹配、Excel 与上传。
|
||||
|
||||
@@ -79,13 +79,13 @@ def list_customer_options(*, query: str = '', limit: int = 100) -> list[dict[str
|
||||
|
||||
|
||||
def confirm_task_customer(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
customer_id: int,
|
||||
actor_id: int | None,
|
||||
resolution_method: str = 'manual',
|
||||
commit: bool = True,
|
||||
) -> ShippingTask:
|
||||
) -> ShippingNotice:
|
||||
"""
|
||||
人工确认任务所属标准客户,并同步共享业务单下所有任务版本。
|
||||
|
||||
@@ -133,7 +133,7 @@ def confirm_task_customer(
|
||||
case.customer_short_code_snapshot = customer.short_code
|
||||
business_no = assign_business_number(case)
|
||||
fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest()
|
||||
tasks = db.session.query(ShippingTask).filter_by(shipping_case_id=case.id).all()
|
||||
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
|
||||
@@ -165,12 +165,12 @@ def confirm_task_customer(
|
||||
))
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return db.session.get(ShippingTask, int(task.id))
|
||||
return db.session.get(ShippingNotice, int(task.id))
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def customer_gate_tool_response(task: ShippingTask, *, operation: str) -> dict[str, Any] | None:
|
||||
def customer_gate_tool_response(task: ShippingNotice, *, operation: str) -> dict[str, Any] | None:
|
||||
"""Tool 公共入口将客户 Gate 转为 needs_human 响应,未阻断时返回 None。"""
|
||||
if customer_identity_is_confirmed(task):
|
||||
return None
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/customer_shadow_resolution.py
|
||||
|
||||
用途:对订单 Candidate 执行只读客户影子识别,并提供质量报告与人工标签。
|
||||
依赖:客户主数据/识别证据、Candidate/Intake、customer_normalization。
|
||||
逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingCase、ShippingTask 或业务编号。
|
||||
逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingCase、ShippingNotice 或业务编号。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,17 +20,17 @@ from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowMatch,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderIntake,
|
||||
)
|
||||
from app.services.shipping_notice.identity_resolution import resolve_candidate_identity
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def refresh_candidate_shadow_resolution(candidate: ShippingNoticeCandidate) -> ShippingCustomerShadowResolution:
|
||||
def refresh_candidate_shadow_resolution(candidate: ShippingOrderCandidate) -> ShippingCustomerShadowResolution:
|
||||
"""幂等刷新 Candidate 影子识别;只写审计结果,不执行客户绑定或自动确认。"""
|
||||
intake = db.session.get(ShippingNoticeIntake, int(candidate.intake_id))
|
||||
intake = db.session.get(ShippingOrderIntake, int(candidate.intake_id))
|
||||
if intake is None:
|
||||
raise NotFoundError('Shipping intake not found', code='SHIPPING_NOTICE.INTAKE_NOT_FOUND')
|
||||
resolution = resolve_candidate_identity(candidate, intake)
|
||||
@@ -82,7 +82,7 @@ def refresh_candidate_shadow_resolution(candidate: ShippingNoticeCandidate) -> S
|
||||
return row
|
||||
|
||||
|
||||
def refresh_candidate_shadow_resolution_safely(candidate: ShippingNoticeCandidate) -> None:
|
||||
def refresh_candidate_shadow_resolution_safely(candidate: ShippingOrderCandidate) -> None:
|
||||
"""用 SAVEPOINT 隔离影子识别异常;任何失败均不得中断 Candidate 主流程。"""
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
@@ -144,13 +144,13 @@ def label_shadow_resolution(resolution_id: int, *, customer_id: int, actor_id: i
|
||||
def serialize_shadow_resolution(
|
||||
row: ShippingCustomerShadowResolution,
|
||||
*,
|
||||
candidate: ShippingNoticeCandidate | None = None,
|
||||
intake: ShippingNoticeIntake | None = None,
|
||||
candidate: ShippingOrderCandidate | None = None,
|
||||
intake: ShippingOrderIntake | None = None,
|
||||
manual_customer: ShippingCustomer | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""序列化影子识别结果;报告可传入批量预加载对象以避免 N+1。"""
|
||||
candidate = candidate or db.session.get(ShippingNoticeCandidate, int(row.candidate_id))
|
||||
intake = intake or db.session.get(ShippingNoticeIntake, int(row.intake_id))
|
||||
candidate = candidate or db.session.get(ShippingOrderCandidate, int(row.candidate_id))
|
||||
intake = intake or db.session.get(ShippingOrderIntake, int(row.intake_id))
|
||||
if manual_customer is None and row.manual_customer_id is not None:
|
||||
manual_customer = db.session.get(ShippingCustomer, int(row.manual_customer_id))
|
||||
return {
|
||||
@@ -195,11 +195,11 @@ def get_shadow_quality_report(*, limit: int = 100) -> dict[str, Any]:
|
||||
manual_customer_ids = [int(item.manual_customer_id) for item in rows if item.manual_customer_id is not None]
|
||||
candidates = {
|
||||
item.id: item
|
||||
for item in db.session.query(ShippingNoticeCandidate).filter(ShippingNoticeCandidate.id.in_(candidate_ids)).all()
|
||||
for item in db.session.query(ShippingOrderCandidate).filter(ShippingOrderCandidate.id.in_(candidate_ids)).all()
|
||||
} if candidate_ids else {}
|
||||
intakes = {
|
||||
item.id: item
|
||||
for item in db.session.query(ShippingNoticeIntake).filter(ShippingNoticeIntake.id.in_(intake_ids)).all()
|
||||
for item in db.session.query(ShippingOrderIntake).filter(ShippingOrderIntake.id.in_(intake_ids)).all()
|
||||
} if intake_ids else {}
|
||||
manual_customers = {
|
||||
item.id: item
|
||||
|
||||
@@ -13,7 +13,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeCandidate, ShippingOrderExtractionRun, ShippingTaskInventoryLink
|
||||
from app.models import ShippingOrderCandidate, ShippingOrderProcessingRun, ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_PARSE_OK,
|
||||
@@ -467,14 +467,14 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
# [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。
|
||||
if decision == "reparse":
|
||||
candidate = (
|
||||
db.session.get(ShippingNoticeCandidate, int(task.source_candidate_id))
|
||||
db.session.get(ShippingOrderCandidate, int(task.source_candidate_id))
|
||||
if task.source_candidate_id else None
|
||||
)
|
||||
source_run_id = candidate.order_extraction_run_id if candidate is not None else None
|
||||
if source_run_id:
|
||||
from app.services.shipping_notice.order_extraction_run_service import reparse_order_extraction_run
|
||||
|
||||
run = db.session.get(ShippingOrderExtractionRun, source_run_id)
|
||||
run = db.session.get(ShippingOrderProcessingRun, source_run_id)
|
||||
if run is not None:
|
||||
replacement, reused = reparse_order_extraction_run(
|
||||
user_id=int(task.user_id), run_no=run.run_no, reason="other", comment=comment or None,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/dify_inputs.py
|
||||
|
||||
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
|
||||
依赖:agent_runtime_context 平台协议、models.ShippingBatch/ShippingTask、shipping_notice.runtime_context。
|
||||
依赖:agent_runtime_context 平台协议、models.ShippingNotice、shipping_notice.runtime_context。
|
||||
逻辑:由 Context Adapter / api/chat 调用;本模块按会话号解析当前批次/任务焦点,
|
||||
仅输出 agent_runtime_context JSON 字符串,供 Dify 画布统一读取平台运行态快照。
|
||||
发货通知识别请使用 agent_registry.resolver.resolve_agent_code == 'shipping_notice'。
|
||||
@@ -13,30 +13,24 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingBatch, ShippingTask, ShippingTemporaryInventorySession
|
||||
from app.models import ShippingNotice, ShippingTemporaryInventorySession
|
||||
from app.services.agent_runtime_context.builder import serialize_for_dify
|
||||
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
|
||||
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
|
||||
|
||||
|
||||
def _latest_batch_for_conversation(conversation_id: str) -> ShippingBatch | None:
|
||||
"""按会话号获取最近一个发货批次,用于恢复当前批次焦点。"""
|
||||
conv_id = str(conversation_id or "").strip()
|
||||
if not conv_id:
|
||||
return None
|
||||
return (
|
||||
ShippingBatch.query.filter_by(conversation_id=conv_id)
|
||||
.order_by(ShippingBatch.id.desc())
|
||||
.first()
|
||||
)
|
||||
def _latest_batch_for_conversation(conversation_id: str) -> None:
|
||||
"""shipping_batches 已删除;固定返回 None。"""
|
||||
del conversation_id
|
||||
return None
|
||||
|
||||
|
||||
def _task_by_task_no(task_id: str) -> ShippingTask | None:
|
||||
def _task_by_task_no(task_id: str) -> ShippingNotice | None:
|
||||
"""按显式 task_id 获取任务;仅用于补齐批次 ref,禁止按会话号猜测当前任务。"""
|
||||
normalized = str(task_id or "").strip().upper()
|
||||
if not normalized:
|
||||
return None
|
||||
return ShippingTask.query.filter_by(task_no=normalized).first()
|
||||
return ShippingNotice.query.filter_by(task_no=normalized).first()
|
||||
|
||||
|
||||
def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None:
|
||||
@@ -68,7 +62,7 @@ def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | N
|
||||
return str(item.session_no or '').strip().upper() or None if item else None
|
||||
|
||||
|
||||
def _focus_task_row(focus_task: str, explicit_task_row: ShippingTask | None) -> ShippingTask | None:
|
||||
def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -> ShippingNotice | None:
|
||||
"""
|
||||
解析当前显式焦点任务行。
|
||||
|
||||
@@ -87,7 +81,7 @@ def _focus_task_row(focus_task: str, explicit_task_row: ShippingTask | None) ->
|
||||
return None
|
||||
if explicit_task_row and str(explicit_task_row.task_no or "").strip().upper() == normalized:
|
||||
return explicit_task_row
|
||||
return ShippingTask.query.filter_by(task_no=normalized).first()
|
||||
return ShippingNotice.query.filter_by(task_no=normalized).first()
|
||||
|
||||
|
||||
def build_dify_chat_inputs(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_candidate_persist.py
|
||||
|
||||
用途:阶段二——EML 附件派生 FileAsset、ShippingNoticeDocument / Candidate 幂等落库。
|
||||
用途:阶段二——EML 附件派生 FileAsset、ShippingOrderDocument / Candidate 幂等落库。
|
||||
依赖:file_assets.service、intake_business_parser、business_fingerprint、duplicate_detection、客户影子识别、eml_parse。
|
||||
逻辑:由 intake_parse_workflow.run_intake_parse 在文本落库成功后调用;重试按
|
||||
(parent, content_hash)、(intake, attachment_key)、(intake, primary_document_id) 复用,不重复创建。
|
||||
@@ -21,9 +21,9 @@ from typing import Any
|
||||
from app import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
)
|
||||
from app.services.file_assets.service import (
|
||||
create_derived_file_asset_from_bytes,
|
||||
@@ -151,7 +151,7 @@ def _should_persist_attachment_asset(item: dict[str, Any], payload: bytes) -> bo
|
||||
|
||||
def _upsert_document(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
attachment_key: str,
|
||||
document_type: str,
|
||||
filename: str | None,
|
||||
@@ -162,17 +162,17 @@ def _upsert_document(
|
||||
asset_id: int | None,
|
||||
classification: str,
|
||||
layout_snapshot: dict[str, Any] | None = None,
|
||||
) -> ShippingNoticeDocument:
|
||||
) -> ShippingOrderDocument:
|
||||
row = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
db.session.query(ShippingOrderDocument)
|
||||
.filter(
|
||||
ShippingNoticeDocument.intake_id == int(intake.id),
|
||||
ShippingNoticeDocument.attachment_key == attachment_key,
|
||||
ShippingOrderDocument.intake_id == int(intake.id),
|
||||
ShippingOrderDocument.attachment_key == attachment_key,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
row = ShippingNoticeDocument(
|
||||
row = ShippingOrderDocument(
|
||||
intake_id=int(intake.id),
|
||||
attachment_key=attachment_key,
|
||||
document_type=document_type,
|
||||
@@ -206,8 +206,8 @@ def _upsert_document(
|
||||
|
||||
def _upsert_candidate(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
document: ShippingNoticeDocument,
|
||||
intake: ShippingOrderIntake,
|
||||
document: ShippingOrderDocument,
|
||||
business_summary: dict[str, Any],
|
||||
fingerprint: dict[str, Any],
|
||||
content_fingerprint: dict[str, Any],
|
||||
@@ -221,18 +221,18 @@ def _upsert_candidate(
|
||||
conflicts: list[dict[str, Any]] | None = None,
|
||||
validation_status: str = 'ready',
|
||||
evidence: dict[str, Any] | None = None,
|
||||
) -> ShippingNoticeCandidate:
|
||||
) -> ShippingOrderCandidate:
|
||||
"""按 Intake + candidate_key 幂等写入一个订单草稿及其抽取审计。"""
|
||||
row = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
db.session.query(ShippingOrderCandidate)
|
||||
.filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
ShippingNoticeCandidate.candidate_key == str(candidate_key),
|
||||
ShippingOrderCandidate.intake_id == int(intake.id),
|
||||
ShippingOrderCandidate.candidate_key == str(candidate_key),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
row = ShippingNoticeCandidate(
|
||||
row = ShippingOrderCandidate(
|
||||
candidate_no=generate_candidate_no(),
|
||||
intake_id=int(intake.id),
|
||||
primary_document_id=int(document.id),
|
||||
@@ -284,10 +284,20 @@ def _upsert_candidate(
|
||||
)
|
||||
|
||||
refresh_candidate_shadow_resolution_safely(row)
|
||||
from app.services.shipping_notice.candidate_evidence_service import (
|
||||
replace_candidate_evidences_from_persist,
|
||||
)
|
||||
|
||||
replace_candidate_evidences_from_persist(
|
||||
row,
|
||||
document=document,
|
||||
evidence=evidence if isinstance(evidence, dict) else None,
|
||||
conflicts=list(conflicts or []),
|
||||
)
|
||||
return row
|
||||
|
||||
|
||||
def _serialize_document_brief(doc: ShippingNoticeDocument, *, include_text: bool) -> dict[str, Any]:
|
||||
def _serialize_document_brief(doc: ShippingOrderDocument, *, include_text: bool) -> dict[str, Any]:
|
||||
asset = db.session.get(FileAsset, int(doc.asset_id)) if doc.asset_id else None
|
||||
payload: dict[str, Any] = {
|
||||
'id': doc.id,
|
||||
@@ -308,7 +318,7 @@ def _serialize_document_brief(doc: ShippingNoticeDocument, *, include_text: bool
|
||||
return payload
|
||||
|
||||
|
||||
def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
|
||||
def _serialize_candidate_brief(cand: ShippingOrderCandidate) -> dict[str, Any]:
|
||||
"""序列化 Candidate 审核摘要,并保持 duplicate 契约与 Intake 一致。"""
|
||||
from app.services.shipping_notice.duplicate_detection import _allowed_actions_for
|
||||
|
||||
@@ -340,7 +350,7 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
|
||||
if isinstance(extraction.get('field_adjudication'), dict)
|
||||
else {}
|
||||
)
|
||||
document = db.session.get(ShippingNoticeDocument, int(cand.primary_document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(cand.primary_document_id))
|
||||
action_buttons: list[str] = []
|
||||
if cand.candidate_status == 'provisional' and cand.consumed_task_id is None and cand.is_current_version:
|
||||
action_buttons.extend(['edit', 'evidence', 'reject'])
|
||||
@@ -409,9 +419,9 @@ def _serialize_candidate_brief(cand: ShippingNoticeCandidate) -> dict[str, Any]:
|
||||
def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list[dict[str, Any]]:
|
||||
"""列出 Intake 下 Document 摘要。"""
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
.filter(ShippingNoticeDocument.intake_id == int(intake_id))
|
||||
.order_by(ShippingNoticeDocument.id.asc())
|
||||
db.session.query(ShippingOrderDocument)
|
||||
.filter(ShippingOrderDocument.intake_id == int(intake_id))
|
||||
.order_by(ShippingOrderDocument.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [_serialize_document_brief(row, include_text=include_text) for row in rows]
|
||||
@@ -420,9 +430,9 @@ def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list
|
||||
def list_intake_candidates(intake_id: int) -> list[dict[str, Any]]:
|
||||
"""列出 Intake 下 Candidate 摘要。"""
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter(ShippingNoticeCandidate.intake_id == int(intake_id))
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
db.session.query(ShippingOrderCandidate)
|
||||
.filter(ShippingOrderCandidate.intake_id == int(intake_id))
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [_serialize_candidate_brief(row) for row in rows]
|
||||
@@ -442,7 +452,7 @@ _UNCHECKED_DUP: dict[str, Any] = {
|
||||
|
||||
def persist_documents_and_candidates(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
parent_asset: FileAsset,
|
||||
result: NoticeIntakeResult,
|
||||
uploaded_storage_keys: list[str] | None = None,
|
||||
@@ -489,8 +499,8 @@ def persist_documents_and_candidates(
|
||||
active_keys: set[str] = set()
|
||||
linked_asset_count = 0
|
||||
created_asset_count = 0
|
||||
documents: list[ShippingNoticeDocument] = []
|
||||
candidates: list[ShippingNoticeCandidate] = []
|
||||
documents: list[ShippingOrderDocument] = []
|
||||
candidates: list[ShippingOrderCandidate] = []
|
||||
active_candidate_doc_ids: set[int] = set()
|
||||
|
||||
# [STEP 1] 正文 Document:仅邮件级上下文,不生成 Candidate
|
||||
@@ -746,32 +756,39 @@ def persist_documents_and_candidates(
|
||||
|
||||
# [STEP 4] 清理消失的 Document,并释放其派生资产
|
||||
stale_docs = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
db.session.query(ShippingOrderDocument)
|
||||
.filter(
|
||||
ShippingNoticeDocument.intake_id == int(intake.id),
|
||||
ShippingNoticeDocument.attachment_key.notin_(tuple(active_keys) or ('__none__',)),
|
||||
ShippingOrderDocument.intake_id == int(intake.id),
|
||||
ShippingOrderDocument.attachment_key.notin_(tuple(active_keys) or ('__none__',)),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
stale_ids = {int(d.id) for d in stale_docs}
|
||||
if stale_ids:
|
||||
db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
ShippingNoticeCandidate.primary_document_id.in_(tuple(stale_ids)),
|
||||
db.session.query(ShippingOrderCandidate).filter(
|
||||
ShippingOrderCandidate.intake_id == int(intake.id),
|
||||
ShippingOrderCandidate.primary_document_id.in_(tuple(stale_ids)),
|
||||
).delete(synchronize_session=False)
|
||||
for doc in stale_docs:
|
||||
_release_document_asset(int(doc.asset_id) if doc.asset_id else None)
|
||||
db.session.delete(doc)
|
||||
|
||||
# [STEP 5] 清理本轮不再具备候选资格的旧 Candidate(Document 仍在但 classification 变了)
|
||||
stale_cand_q = db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
# [STEP 5] Document 仍在但已不具备候选资格时,保留可能已被 Case/OT
|
||||
# 引用的历史 Candidate,只撤销其当前版本资格。
|
||||
stale_cand_q = db.session.query(ShippingOrderCandidate).filter(
|
||||
ShippingOrderCandidate.intake_id == int(intake.id),
|
||||
)
|
||||
if active_candidate_doc_ids:
|
||||
stale_cand_q = stale_cand_q.filter(
|
||||
ShippingNoticeCandidate.primary_document_id.notin_(tuple(active_candidate_doc_ids)),
|
||||
ShippingOrderCandidate.primary_document_id.notin_(tuple(active_candidate_doc_ids)),
|
||||
)
|
||||
stale_cand_q.filter(ShippingNoticeCandidate.consumed_task_id.is_(None)).delete(synchronize_session=False)
|
||||
for candidate in stale_cand_q.filter(ShippingOrderCandidate.consumed_task_id.is_(None)).all():
|
||||
if candidate.is_current_version:
|
||||
candidate.selected_before_superseded = bool(candidate.selected)
|
||||
candidate.candidate_status_before_superseded = candidate.candidate_status
|
||||
candidate.selected = False
|
||||
candidate.candidate_status = 'expired'
|
||||
candidate.is_current_version = False
|
||||
|
||||
# [STEP 6] 剥离 payload,防止后续 structured_result 泄漏
|
||||
strip_attachment_payloads(meta)
|
||||
@@ -793,7 +810,7 @@ def persist_documents_and_candidates(
|
||||
|
||||
def persist_intake_documents(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
parent_asset: FileAsset,
|
||||
result: NoticeIntakeResult,
|
||||
uploaded_storage_keys: list[str] | None = None,
|
||||
@@ -826,7 +843,7 @@ def persist_intake_documents(
|
||||
)
|
||||
|
||||
|
||||
def clear_intake_stage2_structured_projection(intake: ShippingNoticeIntake) -> None:
|
||||
def clear_intake_stage2_structured_projection(intake: ShippingOrderIntake) -> None:
|
||||
"""
|
||||
清理 structured_result_json 中的阶段二投影(document/candidate 计数与附件资产标识)。
|
||||
|
||||
@@ -855,7 +872,7 @@ def clear_intake_stage2_structured_projection(intake: ShippingNoticeIntake) -> N
|
||||
intake.updated_at = datetime.utcnow()
|
||||
|
||||
|
||||
def release_unconsumed_intake_stage2(*, intake: ShippingNoticeIntake) -> dict[str, int]:
|
||||
def release_unconsumed_intake_stage2(*, intake: ShippingOrderIntake) -> dict[str, int]:
|
||||
"""
|
||||
删除未消费 Intake 的 Document/Candidate,并释放派生资产引用。
|
||||
|
||||
@@ -869,13 +886,13 @@ def release_unconsumed_intake_stage2(*, intake: ShippingNoticeIntake) -> dict[st
|
||||
删除的 candidate/document 数量及释放的 asset 次数。
|
||||
"""
|
||||
candidates = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter(ShippingNoticeCandidate.intake_id == int(intake.id))
|
||||
db.session.query(ShippingOrderCandidate)
|
||||
.filter(ShippingOrderCandidate.intake_id == int(intake.id))
|
||||
.all()
|
||||
)
|
||||
documents = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
.filter(ShippingNoticeDocument.intake_id == int(intake.id))
|
||||
db.session.query(ShippingOrderDocument)
|
||||
.filter(ShippingOrderDocument.intake_id == int(intake.id))
|
||||
.all()
|
||||
)
|
||||
for cand in candidates:
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/contracts.py
|
||||
|
||||
用途:定义解析器无关的 shipping_document_layout.v1 契约、稳定标识和完整性校验。
|
||||
用途:定义解析器无关的 shipping_document_layout.v1 契约、稳定标识和完整性校验;
|
||||
并再导出 XFA 阶段 0 契约入口,供布局与 Profile 模块统一引用。
|
||||
依赖:Pydantic 2、标准库 hashlib/json/unicodedata;字段高亮质量枚举与
|
||||
field_highlight_contract 对齐(本模块只声明可挂载到 LayoutCell 的状态字面量)。
|
||||
field_highlight_contract 对齐;XFA 鉴别联合与路径语法见同目录 xfa_contract。
|
||||
逻辑:PDF/OCR/HTML 解析器先构造 LayoutDocument;持久化、Schema 映射和评测只接受通过
|
||||
本模块校验的结果;复核高亮投影消费 cell/token 坐标,但不在本契约内裁决绘制质量。
|
||||
本模块校验的结果;XFA datasets 模式不走本模块几何契约,改由 xfa_contract 约束。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,6 +19,21 @@ from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import ( # noqa: F401
|
||||
ORDER_PROFILE_TEMPLATE_MODES,
|
||||
XFA_CONTRACT_VERSION,
|
||||
XFA_DOCUMENT_KINDS,
|
||||
XFA_DTO_FORBIDDEN_KEYS,
|
||||
XFA_EVIDENCE_SOURCES,
|
||||
XFA_SUPPORTED_DOCUMENT_KINDS,
|
||||
OrderXfaDatasetProfile,
|
||||
compute_dataset_structure_fingerprint,
|
||||
normalize_template_mode,
|
||||
sanitize_xfa_dto,
|
||||
validate_controlled_data_path,
|
||||
validate_xfa_dataset_definition,
|
||||
)
|
||||
|
||||
|
||||
LAYOUT_SCHEMA_VERSION = 'shipping_document_layout.v1'
|
||||
# 与 field_highlight_contract.HIGHLIGHT_QUALITY_VALUES 对齐;Cell 可选挂载,禁止自创同义状态。
|
||||
|
||||
@@ -1,26 +1,99 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/coordinate_region_text.py
|
||||
|
||||
用途:统一从页面坐标字符中读取受控区域文字。
|
||||
依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约。
|
||||
逻辑:标注取字、模板匹配和版本诊断共同使用视觉行聚类与行内横坐标排序,避免阅读顺序分叉。
|
||||
用途:统一从页面坐标字符中读取受控区域文字,并恢复可靠的原始文本流空白。
|
||||
依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约、PositionedCharacter 可选边界字段。
|
||||
逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from typing import Any, Literal
|
||||
|
||||
|
||||
def visual_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
|
||||
def render_positioned_row(
|
||||
glyphs: list[Any], *, geometry_gap_limit: float | None = None,
|
||||
geometry_gap_ratio: float | None = None,
|
||||
geometry_width_mode: Literal['previous', 'average'] = 'average',
|
||||
minimum_gap_limit: float = 0.0,
|
||||
) -> str:
|
||||
"""
|
||||
将坐标字符按视觉行恢复为阅读顺序文本。
|
||||
将单个视觉行按横坐标渲染,优先采用 PDF 原始文本流的明确空白边界。
|
||||
|
||||
核心逻辑:boundary_before 为 space/line_break 时恢复一个普通空格;只有旧版证据或
|
||||
OCR 没有该边界时,才按调用方提供的几何阈值兜底,避免料号、金额被全局拆分。
|
||||
|
||||
Args:
|
||||
glyphs: 含 text 与 bbox 的页面字符;无效字符会被忽略。
|
||||
glyphs: 字典或 PositionedCharacter;必须包含 text 与 bbox。
|
||||
geometry_gap_limit: 可选固定几何阈值,适合以中位字宽计算的旧链路。
|
||||
geometry_gap_ratio: 可选动态比例;按相邻字宽逐对计算,保持旧版模板阈值口径。
|
||||
geometry_width_mode: previous 使用左字符宽度,average 使用相邻平均字宽。
|
||||
minimum_gap_limit: 动态阈值的最小页面距离,防止极窄 glyph 过度分词。
|
||||
|
||||
Returns:
|
||||
从上到下的文本行;同行字符按 x0 排序,并按视觉间距恢复单个空格。
|
||||
保留原文字面值的单行文本;相邻重复空白折叠为一个普通空格。
|
||||
"""
|
||||
ordered = sorted(glyphs, key=lambda item: (_glyph_bbox_value(item, 'x0'), _glyph_source_index(item)))
|
||||
parts: list[str] = []
|
||||
previous_x1: float | None = None
|
||||
previous_width: float | None = None
|
||||
for glyph in ordered:
|
||||
text = _glyph_value(glyph, 'text')
|
||||
if not text:
|
||||
continue
|
||||
boundary = str(_glyph_value(glyph, 'boundary_before') or 'none')
|
||||
x0, x1 = _glyph_bbox_value(glyph, 'x0'), _glyph_bbox_value(glyph, 'x1')
|
||||
width = max(0.01, x1 - x0)
|
||||
explicit_space = boundary in {'space', 'line_break'}
|
||||
resolved_gap_limit = geometry_gap_limit
|
||||
if geometry_gap_ratio is not None and previous_width is not None:
|
||||
reference_width = (
|
||||
previous_width if geometry_width_mode == 'previous'
|
||||
else (previous_width + width) / 2
|
||||
)
|
||||
resolved_gap_limit = max(minimum_gap_limit, reference_width * geometry_gap_ratio)
|
||||
fallback_space = (
|
||||
boundary == 'none'
|
||||
and resolved_gap_limit is not None
|
||||
and previous_x1 is not None
|
||||
and x0 - previous_x1 > resolved_gap_limit
|
||||
)
|
||||
if (explicit_space or fallback_space) and parts and not parts[-1].endswith(' ') and not text.isspace():
|
||||
parts.append(' ')
|
||||
parts.append(text)
|
||||
previous_x1 = x1
|
||||
previous_width = width
|
||||
return ''.join(parts).strip()
|
||||
|
||||
|
||||
def _glyph_value(glyph: Any, key: str) -> Any:
|
||||
"""兼容冻结字典和 Pydantic 字符模型读取字段,避免各坐标链路重复分支。"""
|
||||
return glyph.get(key) if isinstance(glyph, dict) else getattr(glyph, key, None)
|
||||
|
||||
|
||||
def _glyph_bbox_value(glyph: Any, key: str) -> float:
|
||||
"""从字典或 LayoutBBox 中读取坐标;调用方已过滤缺失 bbox 的异常字符。"""
|
||||
bbox = _glyph_value(glyph, 'bbox')
|
||||
value = bbox.get(key) if isinstance(bbox, dict) else getattr(bbox, key)
|
||||
return float(value)
|
||||
|
||||
|
||||
def _glyph_source_index(glyph: Any) -> int:
|
||||
"""以原始文本流序号稳定同坐标字符顺序;旧证据缺失时保持横坐标排序结果。"""
|
||||
value = _glyph_value(glyph, 'source_index')
|
||||
return int(value) if value is not None else 0
|
||||
|
||||
|
||||
def visual_glyph_rows(glyphs: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
|
||||
"""将坐标字符按视觉行分组,供表头签名与运行时 Matcher 共享同一阅读顺序。
|
||||
|
||||
Args:
|
||||
glyphs: 含 text 与 bbox 的页面字符。
|
||||
|
||||
Returns:
|
||||
从上到下的字符行;每行字符已按 x0 排序。
|
||||
"""
|
||||
# 行高容差与锨点匹配保持一致,防止同一 PDF 在签名和运行比对时产生不同行序。
|
||||
rows: list[list[dict[str, Any]]] = []
|
||||
for glyph in sorted(
|
||||
glyphs,
|
||||
@@ -46,20 +119,75 @@ def visual_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
|
||||
continue
|
||||
rows.append([glyph])
|
||||
|
||||
lines: list[str] = []
|
||||
for row in rows:
|
||||
ordered = sorted(row, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
|
||||
parts: list[str] = []
|
||||
return [
|
||||
sorted(row, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
|
||||
for row in rows
|
||||
]
|
||||
|
||||
|
||||
def positioned_token_spans(
|
||||
glyphs: list[dict[str, Any]], *, respect_explicit_spaces: bool = True,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从视觉行中恢复带横向边界的 token。
|
||||
|
||||
Args:
|
||||
glyphs: 含坐标的页面字符。
|
||||
respect_explicit_spaces: False 时仅依赖显著几何间隔分列,用于抹平新旧
|
||||
PDF 证据是否保存 boundary_before 的差异。
|
||||
|
||||
Returns:
|
||||
从上到下、从左到右的 token 及其绝对横向边界。
|
||||
"""
|
||||
spans: list[dict[str, Any]] = []
|
||||
for row in visual_glyph_rows(glyphs):
|
||||
current: list[dict[str, Any]] = []
|
||||
previous_x1: float | None = None
|
||||
previous_width = 0.0
|
||||
for item in ordered:
|
||||
box = item['bbox']
|
||||
x0, x1 = float(box['x0']), float(box['x1'])
|
||||
if previous_x1 is not None and x0 - previous_x1 > max(1.5, previous_width * 1.45):
|
||||
parts.append(' ')
|
||||
parts.append(str(item.get('text') or ''))
|
||||
previous_x1, previous_width = x1, max(1.0, x1 - x0)
|
||||
text = ''.join(parts).strip()
|
||||
previous_width: float | None = None
|
||||
for glyph in row:
|
||||
bbox = glyph.get('bbox') or {}
|
||||
try:
|
||||
x0, x1 = float(bbox['x0']), float(bbox['x1'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
width = max(0.01, x1 - x0)
|
||||
boundary = str(glyph.get('boundary_before') or 'none')
|
||||
geometry_space = (
|
||||
previous_x1 is not None
|
||||
and previous_width is not None
|
||||
and x0 - previous_x1 > max(1.5, previous_width * (1.45 if respect_explicit_spaces else 0.75))
|
||||
)
|
||||
explicit_space = respect_explicit_spaces and boundary in {'space', 'line_break'}
|
||||
if current and (explicit_space or geometry_space):
|
||||
spans.append(_positioned_span(current))
|
||||
current = []
|
||||
current.append(glyph)
|
||||
previous_x1, previous_width = x1, width
|
||||
if current:
|
||||
spans.append(_positioned_span(current))
|
||||
return [item for item in spans if item.get('text')]
|
||||
|
||||
|
||||
def _positioned_span(glyphs: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""渲染单个 token 并返回其绝对横向边界。"""
|
||||
ordered = sorted(glyphs, key=lambda item: float((item.get('bbox') or {}).get('x0', 0)))
|
||||
return {
|
||||
'text': render_positioned_row(ordered),
|
||||
'x0': min(float(item['bbox']['x0']) for item in ordered),
|
||||
'x1': max(float(item['bbox']['x1']) for item in ordered),
|
||||
}
|
||||
|
||||
|
||||
def visual_text_lines(glyphs: list[dict[str, Any]]) -> list[str]:
|
||||
"""将坐标字符按视觉行恢复为阅读顺序文本。"""
|
||||
lines: list[str] = []
|
||||
for ordered in visual_glyph_rows(glyphs):
|
||||
text = render_positioned_row(
|
||||
ordered,
|
||||
geometry_gap_ratio=1.45,
|
||||
geometry_width_mode='previous',
|
||||
minimum_gap_limit=1.5,
|
||||
)
|
||||
if text:
|
||||
lines.append(text)
|
||||
return lines
|
||||
|
||||
+58
-31
@@ -15,6 +15,7 @@ from typing import Any, Literal
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
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.reservation_id import validated_reservation_id
|
||||
@@ -186,9 +187,10 @@ class HeaderLayoutSuggestion(CoordinateReconstructionModel):
|
||||
|
||||
|
||||
class CoordinateProfileLogicalRow(CoordinateReconstructionModel):
|
||||
"""v2 坐标模板重建的一条逻辑明细,字段仍由上层 Schema 规范化。"""
|
||||
"""坐标模板重建的一条逻辑明细,并保留每个字段的原生 glyph 几何证据。"""
|
||||
|
||||
fields: dict[str, str] = Field(default_factory=dict)
|
||||
field_evidence: dict[str, dict[str, Any]] = Field(default_factory=dict)
|
||||
source_row_indices: list[int] = Field(min_length=1)
|
||||
role: Literal['data', 'deleted'] = 'data'
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
@@ -354,9 +356,12 @@ def reconstruct_coordinate_profile_rows(
|
||||
if relative_y_rows is not None:
|
||||
return relative_y_rows
|
||||
|
||||
def values_for(band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any]) -> tuple[dict[str, str], list[str]]:
|
||||
"""按当前物理行读取字段列;标注区域的纵向位置只表达子行版式,不限定绝对页坐标。"""
|
||||
def values_for(
|
||||
band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any],
|
||||
) -> tuple[dict[str, str], dict[str, dict[str, Any]], list[str]]:
|
||||
"""读取字段值和同源 glyph 几何;纵向位置只表达子行版式,不限定绝对页坐标。"""
|
||||
values: dict[str, str] = {}
|
||||
evidence: dict[str, dict[str, Any]] = {}
|
||||
issues: list[str] = []
|
||||
for field in layout.get('field_regions') or []:
|
||||
if not isinstance(field, dict) or not isinstance(field.get('region'), dict):
|
||||
@@ -365,7 +370,8 @@ def reconstruct_coordinate_profile_rows(
|
||||
if not code:
|
||||
continue
|
||||
region = _absolute_relative_region(bbox, field['region'])
|
||||
text = _text_in_horizontal_region(band, region)
|
||||
selected = [item for item in band if _inside_horizontal_region(item[1].bbox, region)]
|
||||
text = _text_in_horizontal_region(selected, region)
|
||||
if text:
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=text,
|
||||
@@ -378,21 +384,24 @@ def reconstruct_coordinate_profile_rows(
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
return values, issues
|
||||
evidence[extracted_code] = _field_glyph_evidence(selected, text=text)
|
||||
return values, evidence, issues
|
||||
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
current: dict[str, str] | None = dict(initial_fields) if initial_fields else None
|
||||
current_evidence: dict[str, dict[str, Any]] = {}
|
||||
sources: list[int] = []
|
||||
next_offset = initial_next_offset if current is not None else 0
|
||||
current_issues: list[str] = []
|
||||
|
||||
def flush(*, role: Literal['data', 'deleted'] = 'data') -> None:
|
||||
nonlocal current, sources, next_offset, current_issues
|
||||
nonlocal current, current_evidence, sources, next_offset, current_issues
|
||||
if current is not None and (sources or initial_fields):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=current, source_row_indices=sources, role=role, issues=current_issues,
|
||||
fields=current, field_evidence=current_evidence,
|
||||
source_row_indices=sources, role=role, issues=current_issues,
|
||||
))
|
||||
current, sources, next_offset, current_issues = None, [], 0, []
|
||||
current, current_evidence, sources, next_offset, current_issues = None, {}, [], 0, []
|
||||
|
||||
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()
|
||||
@@ -404,10 +413,11 @@ def reconstruct_coordinate_profile_rows(
|
||||
# the role to exclude it rather than silently losing the document row.
|
||||
flush(role='deleted')
|
||||
continue
|
||||
main_values, main_issues = values_for(band, ordered_layouts[0])
|
||||
main_values, main_evidence, main_issues = values_for(band, ordered_layouts[0])
|
||||
if is_valid_line_start_value(main_values.get(start_field_code, '')):
|
||||
flush()
|
||||
current, sources, next_offset, current_issues = main_values, [row_index], 1, main_issues
|
||||
current, current_evidence = main_values, main_evidence
|
||||
sources, next_offset, current_issues = [row_index], 1, main_issues
|
||||
continue
|
||||
if current is None or next_offset >= len(ordered_layouts):
|
||||
if include_unanchored_rows and main_values:
|
||||
@@ -418,7 +428,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
current_issues.append('coordinate_profile_layout_region_mismatch')
|
||||
flush()
|
||||
continue
|
||||
continuation, continuation_issues = values_for(band, ordered_layouts[next_offset])
|
||||
continuation, continuation_evidence, continuation_issues = values_for(band, ordered_layouts[next_offset])
|
||||
if not continuation:
|
||||
# Once a logical row has started, its declared physical rows must be consecutive.
|
||||
# Continuing after an unexpected region would silently mix two visual records.
|
||||
@@ -432,6 +442,8 @@ def reconstruct_coordinate_profile_rows(
|
||||
current_issues.append(f'coordinate_profile_composite_conflict:{code}')
|
||||
else:
|
||||
current[code] = value
|
||||
if code in continuation_evidence:
|
||||
current_evidence[code] = continuation_evidence[code]
|
||||
sources.append(row_index)
|
||||
current_issues.extend(continuation_issues)
|
||||
next_offset += 1
|
||||
@@ -1310,15 +1322,7 @@ def _text_in_region(
|
||||
return ''
|
||||
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in selected]
|
||||
gap_limit = max(1.5, median(widths) * 0.65)
|
||||
result: list[str] = []
|
||||
for index, (_, glyph) in enumerate(selected):
|
||||
if index:
|
||||
previous = selected[index - 1][1]
|
||||
gap = glyph.bbox.x0 - previous.bbox.x1
|
||||
if gap > gap_limit and not result[-1].isspace() and not glyph.text.isspace():
|
||||
result.append(' ')
|
||||
result.append(glyph.text)
|
||||
return ''.join(result).strip()
|
||||
return render_positioned_row([glyph for _, glyph in selected], geometry_gap_limit=gap_limit)
|
||||
|
||||
|
||||
def _text_in_horizontal_region(
|
||||
@@ -1333,15 +1337,7 @@ def _text_in_horizontal_region(
|
||||
return ''
|
||||
widths = [glyph.bbox.x1 - glyph.bbox.x0 for _, glyph in selected]
|
||||
gap_limit = max(1.5, median(widths) * 0.65)
|
||||
result: list[str] = []
|
||||
for index, (_, glyph) in enumerate(selected):
|
||||
if index:
|
||||
previous = selected[index - 1][1]
|
||||
gap = glyph.bbox.x0 - previous.bbox.x1
|
||||
if gap > gap_limit and not result[-1].isspace() and not glyph.text.isspace():
|
||||
result.append(' ')
|
||||
result.append(glyph.text)
|
||||
return ''.join(result).strip()
|
||||
return render_positioned_row([glyph for _, glyph in selected], geometry_gap_limit=gap_limit)
|
||||
|
||||
|
||||
def _normalized_header_text(value: str) -> str:
|
||||
@@ -1461,15 +1457,46 @@ def _field_content_score(text: str, field_code: str | None) -> float:
|
||||
|
||||
|
||||
def _cell_from_glyphs(column_index: int, glyphs: list[tuple[int, PositionedCharacter]]) -> ReconstructedCell:
|
||||
"""合并同一视觉行、同一列的 glyph,保留按页面位置排序的证据索引。"""
|
||||
"""合并同一视觉行、同一列 glyph,保留原始空白和按页面位置排序的证据索引。"""
|
||||
ordered = sorted(glyphs, key=lambda item: item[1].bbox.x0)
|
||||
boxes = [item.bbox for _, item in ordered]
|
||||
return ReconstructedCell(
|
||||
column_index=column_index,
|
||||
text=''.join(item.text for _, item in ordered).strip(),
|
||||
text=render_positioned_row([item for _, item in ordered]),
|
||||
bbox=LayoutBBox(
|
||||
x0=min(item.x0 for item in boxes), y0=min(item.y0 for item in boxes),
|
||||
x1=max(item.x1 for item in boxes), y1=max(item.y1 for item in boxes),
|
||||
),
|
||||
glyph_indices=[index for index, _ in ordered],
|
||||
)
|
||||
|
||||
|
||||
def _field_glyph_evidence(
|
||||
glyphs: list[tuple[int, PositionedCharacter]], *, text: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
汇总字段实际消费的原生字符,供上层 Observation 生成字段级高亮。
|
||||
|
||||
Args:
|
||||
glyphs: 已按字段横向区域筛选的字符及稳定来源索引。
|
||||
text: 字段解析器消费的原始引文。
|
||||
|
||||
Returns:
|
||||
value_bbox、glyph_indices 与独立 bbox_text;无字符时返回空字典。
|
||||
"""
|
||||
if not glyphs:
|
||||
return {}
|
||||
boxes = [glyph.bbox for _, glyph in glyphs]
|
||||
return {
|
||||
'value_bbox': {
|
||||
'x0': min(item.x0 for item in boxes), 'y0': min(item.y0 for item in boxes),
|
||||
'x1': max(item.x1 for item in boxes), 'y1': max(item.y1 for item in boxes),
|
||||
},
|
||||
'glyph_indices': [index for index, _glyph in glyphs],
|
||||
'bbox_text': text[:1000],
|
||||
'quote_source': 'glyph_region',
|
||||
'source': 'pdf_coordinate',
|
||||
'has_value_coordinate': True,
|
||||
'coordinate_status': 'candidate',
|
||||
'highlight_quality': 'candidate',
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/lifecycle.py
|
||||
|
||||
用途:管理 ShippingNoticeDocument 的版面版本、checksum、大小门禁和当前成功快照。
|
||||
用途:管理 ShippingOrderDocument 的版面版本、checksum、大小门禁和当前成功快照。
|
||||
依赖:ShippingDocumentLayoutVersion、Flask 配置、SQLAlchemy Session、workflow_ledger_service
|
||||
(claim/complete/recovery 尽力同步 WorkflowItem,缺 Item 不阻断版面收口)。
|
||||
逻辑:相同内容/parser/checksum 幂等复用;失败版本保留审计,只有可用终态更新 Document 当前引用。
|
||||
@@ -20,7 +20,7 @@ from flask import current_app
|
||||
from sqlalchemy import and_, func, or_, update
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingDocumentLayoutVersion, ShippingNoticeDocument, ShippingNoticeIntake
|
||||
from app.models import ShippingDocumentLayoutVersion, ShippingOrderDocument, ShippingOrderIntake
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -38,6 +38,34 @@ LAYOUT_FINGERPRINT_FILES = (
|
||||
)
|
||||
CURRENT_LAYOUT_STATUSES = frozenset({'ready', 'needs_review'})
|
||||
TERMINAL_LAYOUT_STATUSES = frozenset({'ready', 'needs_review', 'failed', 'unsupported'})
|
||||
ON_DEMAND_COORDINATE_COMPACTION_ISSUES = frozenset({
|
||||
'shipping_document_layout_page_glyphs_compacted',
|
||||
'shipping_document_layout_table_glyphs_compacted',
|
||||
'shipping_document_layout_page_metadata_compacted',
|
||||
'shipping_document_layout_candidate_glyphs_compacted',
|
||||
'shipping_document_layout_candidate_page_metadata_compacted',
|
||||
})
|
||||
|
||||
|
||||
def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload: dict[str, Any]) -> bool:
|
||||
"""判断布局快照是否可直接使用,或可由原 PDF 在订单识别时按需恢复。"""
|
||||
if str(payload.get('provider') or '') == 'xfa':
|
||||
capability = payload.get('xfa_capability') if isinstance(payload.get('xfa_capability'), dict) else {}
|
||||
return bool(capability.get('structure_analysis_ready')) and str(payload.get('status') or '') == 'ready'
|
||||
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
|
||||
|
||||
|
||||
def _layout_version_reusable(*, document: ShippingOrderDocument, version: ShippingDocumentLayoutVersion) -> bool:
|
||||
"""仅复用可直接读取或能从原附件按需恢复坐标的成功布局版本。"""
|
||||
if str(version.status or '') not in CURRENT_LAYOUT_STATUSES:
|
||||
return False
|
||||
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
|
||||
return _ready_layout_evidence_complete(document=document, payload=payload)
|
||||
|
||||
|
||||
def _conversation_id_for_document(document_id: int) -> str | None:
|
||||
@@ -45,15 +73,15 @@ def _conversation_id_for_document(document_id: int) -> str | None:
|
||||
从 Document → Intake 解析会话 ID,供 WorkflowItem 定位。
|
||||
|
||||
Args:
|
||||
document_id: ShippingNoticeDocument 主键。
|
||||
document_id: ShippingOrderDocument 主键。
|
||||
|
||||
Returns:
|
||||
conversation_id 或 None。
|
||||
"""
|
||||
row = (
|
||||
db.session.query(ShippingNoticeIntake.conversation_id)
|
||||
.join(ShippingNoticeDocument, ShippingNoticeDocument.intake_id == ShippingNoticeIntake.id)
|
||||
.filter(ShippingNoticeDocument.id == int(document_id))
|
||||
db.session.query(ShippingOrderIntake.conversation_id)
|
||||
.join(ShippingOrderDocument, ShippingOrderDocument.intake_id == ShippingOrderIntake.id)
|
||||
.filter(ShippingOrderDocument.id == int(document_id))
|
||||
.first()
|
||||
)
|
||||
if row is None:
|
||||
@@ -70,65 +98,15 @@ def _sync_workflow_item_for_layout(
|
||||
reason: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
尽力同步版面阶段的 WorkflowItem 状态/事件;Item 缺失时仅记日志。
|
||||
历史:同步版面阶段 WorkflowItem;co8 后台账已 DROP,本函数为 no-op。
|
||||
|
||||
Args:
|
||||
document_id: 版面所属 Document。
|
||||
lifecycle_status: 可选目标生命周期(queued/layout_parsing/failed 等)。
|
||||
event_code: 可选用户可见事件码(如 layout_completed)。
|
||||
reason: 迁移理由。
|
||||
document_id: 版面所属 Document(忽略)。
|
||||
lifecycle_status: 忽略。
|
||||
event_code: 忽略。
|
||||
reason: 忽略。
|
||||
"""
|
||||
try:
|
||||
from app.models.shipping_notice_workflow import ShippingNoticeWorkflow
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
append_workflow_event,
|
||||
find_item_by_root,
|
||||
transition_item_status,
|
||||
)
|
||||
|
||||
conversation_id = _conversation_id_for_document(int(document_id))
|
||||
if not conversation_id:
|
||||
return
|
||||
item = find_item_by_root(
|
||||
conversation_id=conversation_id,
|
||||
root_document_id=int(document_id),
|
||||
for_update=True,
|
||||
)
|
||||
if item is None:
|
||||
return
|
||||
if lifecycle_status and str(item.lifecycle_status or '') != str(lifecycle_status):
|
||||
if str(item.lifecycle_status or '') not in {
|
||||
'closed', 'cancelled', 'manual_upload_pending', 'pending_review',
|
||||
}:
|
||||
transition_item_status(
|
||||
item=item,
|
||||
lifecycle_status=str(lifecycle_status),
|
||||
stage=str(lifecycle_status),
|
||||
actor_type='system',
|
||||
actor_id='layout',
|
||||
reason=reason or f'layout:{lifecycle_status}',
|
||||
)
|
||||
if event_code:
|
||||
workflow = db.session.get(ShippingNoticeWorkflow, int(item.workflow_id))
|
||||
if workflow is not None:
|
||||
append_workflow_event(
|
||||
workflow=workflow,
|
||||
item=item,
|
||||
event_code=str(event_code),
|
||||
stage_code=str(item.current_stage or item.lifecycle_status),
|
||||
message_code=f'shipping.workflow_item.{event_code}',
|
||||
actor_type='system',
|
||||
actor_id='layout',
|
||||
payload={'document_id': int(document_id)},
|
||||
reason=reason,
|
||||
)
|
||||
except Exception:
|
||||
_LOGGER.exception(
|
||||
'layout workflow sync skipped document_id=%s status=%s event=%s',
|
||||
document_id,
|
||||
lifecycle_status,
|
||||
event_code,
|
||||
)
|
||||
del document_id, lifecycle_status, event_code, reason
|
||||
|
||||
|
||||
def layout_parser_implementation_fingerprint() -> str:
|
||||
@@ -176,8 +154,8 @@ def _fit_layout_payload_to_budget(
|
||||
) -> tuple[dict[str, Any] | None, list[str], int]:
|
||||
"""按证据优先级压缩布局快照,避免可重建证据阻断业务表保存。
|
||||
|
||||
核心逻辑:表格 HTML/结构是模板建模的核心;整页 glyph、文本块和页面尺寸
|
||||
属于可选证据。压缩过程只删除可重建字段,并返回最终大小与诊断码。
|
||||
核心逻辑:表格 HTML/结构是模板建模的核心;整页/表内 glyph、文本块和页面尺寸
|
||||
属于可从原 PDF 按需恢复的证据。压缩过程只删除可重建字段,并返回最终大小与诊断码。
|
||||
"""
|
||||
candidate = json.loads(json.dumps(payload, ensure_ascii=True))
|
||||
issues: list[str] = []
|
||||
@@ -185,16 +163,6 @@ def _fit_layout_payload_to_budget(
|
||||
if size <= max_bytes:
|
||||
return candidate, issues, size
|
||||
|
||||
evidence = candidate.get('coordinate_evidence')
|
||||
if isinstance(evidence, dict):
|
||||
if evidence.pop('page_glyphs', None) is not None:
|
||||
issues.append('shipping_document_layout_page_glyphs_compacted')
|
||||
if evidence.pop('pages', None) is not None:
|
||||
issues.append('shipping_document_layout_page_metadata_compacted')
|
||||
_, size = canonical_layout_payload(candidate)
|
||||
if size <= max_bytes:
|
||||
return candidate, issues, size
|
||||
|
||||
if candidate.pop('text_blocks', None) is not None:
|
||||
issues.append('shipping_document_layout_text_blocks_compacted')
|
||||
_, size = canonical_layout_payload(candidate)
|
||||
@@ -208,12 +176,22 @@ def _fit_layout_payload_to_budget(
|
||||
if layout_candidate.pop('pages', None) is not None:
|
||||
issues.append('shipping_document_layout_candidate_page_metadata_compacted')
|
||||
_, size = canonical_layout_payload(candidate)
|
||||
if size <= max_bytes:
|
||||
return candidate, issues, size
|
||||
|
||||
coordinate_evidence = candidate.get('coordinate_evidence')
|
||||
if isinstance(coordinate_evidence, dict):
|
||||
if coordinate_evidence.pop('page_glyphs', None) is not None:
|
||||
issues.append('shipping_document_layout_page_glyphs_compacted')
|
||||
if coordinate_evidence.pop('tables', None) is not None:
|
||||
issues.append('shipping_document_layout_table_glyphs_compacted')
|
||||
_, size = canonical_layout_payload(candidate)
|
||||
if size <= max_bytes:
|
||||
return candidate, issues, size
|
||||
return None, issues + ['shipping_document_layout_snapshot_size_exceeded'], size
|
||||
|
||||
|
||||
def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any] | None:
|
||||
def current_layout_snapshot(document: ShippingOrderDocument) -> dict[str, Any] | None:
|
||||
"""读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。"""
|
||||
version = document.current_layout_version
|
||||
if (
|
||||
@@ -226,7 +204,7 @@ def current_layout_snapshot(document: ShippingNoticeDocument) -> dict[str, Any]
|
||||
|
||||
|
||||
def record_inline_layout_snapshot(
|
||||
document: ShippingNoticeDocument,
|
||||
document: ShippingOrderDocument,
|
||||
snapshot: dict[str, Any],
|
||||
*,
|
||||
parser_key: str | None = None,
|
||||
@@ -276,6 +254,8 @@ def record_inline_layout_snapshot(
|
||||
'ready', 'needs_review', 'failed', 'unsupported',
|
||||
} else 'failed'
|
||||
issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)} | set(compact_issues))
|
||||
if status == 'ready' and ON_DEMAND_COORDINATE_COMPACTION_ISSUES.intersection(compact_issues):
|
||||
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_on_demand'})
|
||||
stored_payload: dict[str, Any] | None = fitted_payload
|
||||
if stored_payload is None:
|
||||
status = 'failed'
|
||||
@@ -309,7 +289,7 @@ def record_inline_layout_snapshot(
|
||||
|
||||
|
||||
def _clone_reusable_layout_for_document(
|
||||
document: ShippingNoticeDocument,
|
||||
document: ShippingOrderDocument,
|
||||
reusable: ShippingDocumentLayoutVersion,
|
||||
) -> ShippingDocumentLayoutVersion | None:
|
||||
"""
|
||||
@@ -335,7 +315,7 @@ def _clone_reusable_layout_for_document(
|
||||
|
||||
|
||||
def schedule_layout_version(
|
||||
document: ShippingNoticeDocument,
|
||||
document: ShippingOrderDocument,
|
||||
*,
|
||||
force: bool = False,
|
||||
created_by_id: int | None = None,
|
||||
@@ -355,22 +335,27 @@ def schedule_layout_version(
|
||||
if len(source_hash) != 64:
|
||||
return None
|
||||
# Identical files from the same owner reuse a completed layout rather than waiting for MinerU again.
|
||||
owner_id = db.session.query(ShippingNoticeIntake.user_id).filter(
|
||||
ShippingNoticeIntake.id == document.intake_id,
|
||||
owner_id = db.session.query(ShippingOrderIntake.user_id).filter(
|
||||
ShippingOrderIntake.id == document.intake_id,
|
||||
).scalar()
|
||||
if not force:
|
||||
reusable_from_owner = (
|
||||
ShippingDocumentLayoutVersion.query
|
||||
.join(ShippingNoticeDocument, ShippingNoticeDocument.id == ShippingDocumentLayoutVersion.document_id)
|
||||
.join(ShippingNoticeIntake, ShippingNoticeIntake.id == ShippingNoticeDocument.intake_id)
|
||||
.join(ShippingOrderDocument, ShippingOrderDocument.id == ShippingDocumentLayoutVersion.document_id)
|
||||
.join(ShippingOrderIntake, ShippingOrderIntake.id == ShippingOrderDocument.intake_id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == owner_id,
|
||||
ShippingNoticeDocument.content_hash == source_hash,
|
||||
ShippingOrderIntake.user_id == owner_id,
|
||||
ShippingOrderDocument.content_hash == source_hash,
|
||||
ShippingDocumentLayoutVersion.parser_key == current_layout_parser_key(),
|
||||
ShippingDocumentLayoutVersion.status.in_(tuple(CURRENT_LAYOUT_STATUSES)),
|
||||
)
|
||||
.order_by(ShippingDocumentLayoutVersion.finished_at.desc(), ShippingDocumentLayoutVersion.id.desc())
|
||||
.first()
|
||||
.all()
|
||||
)
|
||||
reusable_from_owner = next(
|
||||
(version for version in reusable_from_owner
|
||||
if _layout_version_reusable(document=document, version=version)),
|
||||
None,
|
||||
)
|
||||
if reusable_from_owner is not None:
|
||||
localized = _clone_reusable_layout_for_document(document, reusable_from_owner)
|
||||
@@ -383,12 +368,17 @@ def schedule_layout_version(
|
||||
if active is not None:
|
||||
return active
|
||||
if not force:
|
||||
reusable = ShippingDocumentLayoutVersion.query.filter_by(
|
||||
reusable_candidates = ShippingDocumentLayoutVersion.query.filter_by(
|
||||
document_id=int(document.id), source_content_hash=source_hash,
|
||||
parser_key=current_layout_parser_key(),
|
||||
).filter(ShippingDocumentLayoutVersion.status.in_(tuple(CURRENT_LAYOUT_STATUSES))).order_by(
|
||||
ShippingDocumentLayoutVersion.version.desc(),
|
||||
).first()
|
||||
).all()
|
||||
reusable = next(
|
||||
(version for version in reusable_candidates
|
||||
if _layout_version_reusable(document=document, version=version)),
|
||||
None,
|
||||
)
|
||||
if reusable is not None:
|
||||
document.current_layout_version_id = reusable.id
|
||||
return reusable
|
||||
@@ -416,7 +406,7 @@ def schedule_layout_version(
|
||||
|
||||
|
||||
def schedule_document_layouts(
|
||||
documents: list[ShippingNoticeDocument], *, created_by_id: int | None = None,
|
||||
documents: list[ShippingOrderDocument], *, created_by_id: int | None = None,
|
||||
) -> list[ShippingDocumentLayoutVersion]:
|
||||
"""在 Document 持久化事务内为支持附件建立独立布局版本,超量文档保留 skipped 审计。"""
|
||||
from pathlib import Path
|
||||
@@ -424,7 +414,7 @@ def schedule_document_layouts(
|
||||
from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS
|
||||
|
||||
max_documents = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4,
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 10,
|
||||
)), 0)
|
||||
eligible = [
|
||||
item for item in documents
|
||||
@@ -495,7 +485,7 @@ def serialize_layout_version(version: ShippingDocumentLayoutVersion) -> dict[str
|
||||
|
||||
def list_layout_versions(document_id: int) -> list[dict[str, Any]]:
|
||||
"""列出一个 Document 的布局版本安全摘要。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if document is None:
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
@@ -511,7 +501,7 @@ def request_layout_reparse(
|
||||
document_id: int, *, created_by_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""管理员显式创建下一布局版本;活动版本存在时幂等返回同一版本。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if document is None:
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
@@ -591,6 +581,14 @@ def complete_layout_version(
|
||||
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')
|
||||
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,
|
||||
):
|
||||
status = 'failed'
|
||||
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_incomplete'})
|
||||
elif status == 'ready' and ON_DEMAND_COORDINATE_COMPACTION_ISSUES.intersection(compact_issues):
|
||||
# [STEP] 快照压缩只影响持久化体积;原 PDF 仍可读时由订单识别按需恢复坐标。
|
||||
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_on_demand'})
|
||||
stored_payload: dict[str, Any] | None = fitted_snapshot
|
||||
if stored_payload is None:
|
||||
status = 'failed'
|
||||
|
||||
@@ -73,7 +73,10 @@ def extract_native_pdf_pages(
|
||||
content: bytes, *, render_scale: float = 2.0, render_images: bool = True,
|
||||
) -> list[NativePdfPage]:
|
||||
"""
|
||||
从 PDF bytes 提取左上原点字符坐标和页面图。
|
||||
从 PDF bytes 提取左上原点字符坐标、原始文本流边界和页面图。
|
||||
|
||||
核心逻辑:可见字符保留 PDFium 原始 char_index;零 bbox 空白不生成伪坐标,
|
||||
而是记录到下一个有效字符的 boundary_before,供文本重建优先于几何猜测使用。
|
||||
|
||||
Args:
|
||||
content: 原始 PDF 字节,不写文件和日志。
|
||||
@@ -93,12 +96,21 @@ def extract_native_pdf_pages(
|
||||
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 or not normalize_layout_text(text):
|
||||
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 原始坐标;仅转为左上原点页面坐标。
|
||||
@@ -107,9 +119,12 @@ def extract_native_pdf_pages(
|
||||
bbox=LayoutBBox(
|
||||
x0=left, y0=height - top, x1=right, y1=height - bottom,
|
||||
),
|
||||
source_index=len(characters),
|
||||
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
|
||||
@@ -316,7 +331,7 @@ def build_native_pdf_layout_candidate(
|
||||
组合 MinerU HTML 与 PDFium 独立证据,生成始终 needs_review 的 layout.v1 候选。
|
||||
|
||||
Args:
|
||||
document_id: 当前 ShippingNoticeDocument 主键。
|
||||
document_id: 当前 ShippingOrderDocument 主键。
|
||||
content_hash: 当前附件 SHA-256,用于稳定 ID 和契约校验。
|
||||
content: 原始 PDF 字节。
|
||||
mineru: 同一文件的 MinerU pipeline 候选。
|
||||
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
"""按需从原始 PDF 恢复坐标证据;不改变上传阶段的轻量布局快照。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import FileAsset, ShippingOrderDocument
|
||||
|
||||
|
||||
def _coordinate_mapping(value: Any) -> dict[str, Any]:
|
||||
"""仅接受坐标证据的键值映射;业务表格列表不得被 `dict(...)` 误解释。"""
|
||||
return dict(value) if isinstance(value, dict) else {}
|
||||
|
||||
|
||||
def ensure_on_demand_coordinate_evidence(
|
||||
*, document: ShippingOrderDocument, layout: dict[str, Any], page_nos: set[int] | None,
|
||||
table_by_page: dict[int, dict[str, Any] | list[dict[str, Any]]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。"""
|
||||
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
|
||||
return layout
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
# 兼容历史布局快照:布局任务曾将坐标证据写在顶层,正式抽取仍需复用它。
|
||||
if not evidence:
|
||||
legacy_keys = ('pages', 'page_glyphs', 'sources', 'tables')
|
||||
evidence = {
|
||||
key: layout.get(key)
|
||||
for key in legacy_keys
|
||||
if isinstance(layout.get(key), dict)
|
||||
}
|
||||
# Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。
|
||||
current_version = getattr(document, 'current_layout_version', None)
|
||||
current_payload = getattr(current_version, 'payload_json', None)
|
||||
if isinstance(current_payload, dict):
|
||||
current_evidence = current_payload.get('coordinate_evidence')
|
||||
if isinstance(current_evidence, dict):
|
||||
evidence = {**current_evidence, **evidence}
|
||||
for key in ('pages', 'page_glyphs', 'sources', 'tables'):
|
||||
if key not in evidence and isinstance(current_payload.get(key), dict):
|
||||
evidence[key] = current_payload[key]
|
||||
pages = _coordinate_mapping(evidence.get('pages'))
|
||||
page_glyphs = _coordinate_mapping(evidence.get('page_glyphs'))
|
||||
sources = _coordinate_mapping(evidence.get('sources'))
|
||||
source_pages = _coordinate_mapping(sources.get('pages'))
|
||||
tables = _coordinate_mapping(evidence.get('tables'))
|
||||
if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}):
|
||||
return layout
|
||||
tables_by_page: dict[int, list[dict[str, Any]]] = {}
|
||||
for raw_table in layout.get('tables') or []:
|
||||
if not isinstance(raw_table, dict):
|
||||
continue
|
||||
tables_by_page.setdefault(int(raw_table.get('page_no') or 1), []).append(raw_table)
|
||||
for raw_page_no, raw_tables in (table_by_page or {}).items():
|
||||
candidates = raw_tables if isinstance(raw_tables, list) else [raw_tables]
|
||||
page_tables = tables_by_page.setdefault(int(raw_page_no), [])
|
||||
existing_ids = {str(item.get('table_id') or '') for item in page_tables}
|
||||
for raw_table in candidates:
|
||||
if not isinstance(raw_table, dict):
|
||||
continue
|
||||
table_id = str(raw_table.get('table_id') or '')
|
||||
if table_id and table_id not in existing_ids:
|
||||
page_tables.append(raw_table)
|
||||
existing_ids.add(table_id)
|
||||
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, int(document.asset_id))
|
||||
if asset is None:
|
||||
return layout
|
||||
try:
|
||||
native_pages = extract_native_pdf_pages(read_asset_bytes(asset))
|
||||
except Exception:
|
||||
return layout
|
||||
for page in native_pages:
|
||||
if page_nos is not None and int(page.page_no) not in page_nos:
|
||||
continue
|
||||
glyphs = [item.model_dump(mode='json') for item in getattr(page, 'characters', []) or []]
|
||||
source = 'pdf_coordinate'
|
||||
if not glyphs:
|
||||
try:
|
||||
lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
|
||||
glyphs = _ocr_lines_to_page_characters(lines=lines)
|
||||
source = 'ocr_coordinate'
|
||||
except Exception:
|
||||
glyphs = []
|
||||
if not glyphs:
|
||||
continue
|
||||
page_key = str(page.page_no)
|
||||
pages[page_key] = {'width': page.width, 'height': page.height}
|
||||
page_glyphs[page_key] = glyphs
|
||||
source_pages[page_key] = source
|
||||
for table in tables_by_page.get(int(page.page_no), []):
|
||||
table_id = str(table.get('table_id') or '')
|
||||
chars = _native_characters_in_table(
|
||||
characters=list(getattr(page, 'characters', []) or []),
|
||||
table_bbox=table.get('bbox') or {},
|
||||
)
|
||||
if not chars:
|
||||
try:
|
||||
lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
|
||||
chars = _ocr_lines_to_characters(lines=lines, table_bbox=table.get('bbox') or {})
|
||||
except Exception:
|
||||
chars = []
|
||||
if table_id and chars:
|
||||
tables[table_id] = chars
|
||||
next_layout = dict(layout)
|
||||
next_layout['coordinate_evidence'] = {
|
||||
**evidence, 'pages': pages, 'page_glyphs': page_glyphs,
|
||||
'tables': tables, 'sources': {**sources, 'pages': source_pages},
|
||||
}
|
||||
return next_layout
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/document_layout/order_field_extraction.py
|
||||
|
||||
用途:从冻结的整页 PDF/OCR 字符坐标中确定性提取独立订单级字段。
|
||||
依赖:OrderCoordinateProfileV2、冻结 Schema 字段规则和 LayoutBBox。
|
||||
依赖:OrderCoordinateProfile、冻结 Schema 字段规则和 LayoutBBox。
|
||||
逻辑:订单工作流先唯一匹配模板,再调用本模块;本模块仅返回可追溯候选,绝不回读资产、数据库或调用模型。
|
||||
"""
|
||||
|
||||
@@ -14,10 +14,11 @@ from typing import Any, Literal
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
AnchorRelativeRegion,
|
||||
AnchorRule,
|
||||
OrderCoordinateProfileV2,
|
||||
OrderCoordinateProfile,
|
||||
OrderFieldLayout,
|
||||
RelativeRegion,
|
||||
)
|
||||
@@ -46,14 +47,14 @@ class OrderFieldExtraction(BaseModel):
|
||||
|
||||
|
||||
def extract_order_fields(
|
||||
*, profile: OrderCoordinateProfileV2, schema_fields: dict[str, dict[str, Any]],
|
||||
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_evidence: dict[str, Any],
|
||||
) -> list[OrderFieldExtraction]:
|
||||
"""
|
||||
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
|
||||
|
||||
Args:
|
||||
profile: Run 冻结的 v2 坐标模板,不得包含待重新绑定字段。
|
||||
profile: Run 冻结的坐标模板,不得包含待重新绑定字段。
|
||||
schema_fields: 以 stable field_id 为键的冻结启用 Schema 字段。
|
||||
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
|
||||
|
||||
@@ -405,18 +406,14 @@ def _render_value(selected: list[tuple[int, dict[str, Any]]], *, multi_line: boo
|
||||
|
||||
|
||||
def _render_visual_row(row: list[tuple[int, dict[str, Any]]]) -> str:
|
||||
"""以字距推断缺失的 PDF 空白;仅大于常规字符间隔时补一个普通空格。"""
|
||||
rendered: list[str] = []
|
||||
previous: LayoutBBox | None = None
|
||||
for _index, glyph in row:
|
||||
bbox = _glyph_bbox(glyph)
|
||||
if previous is not None:
|
||||
typical_width = max((previous.x1 - previous.x0 + bbox.x1 - bbox.x0) / 2, 0.01)
|
||||
if bbox.x0 - previous.x1 > typical_width * 0.75:
|
||||
rendered.append(' ')
|
||||
rendered.append(str(glyph.get('text') or ''))
|
||||
previous = bbox
|
||||
return ''.join(rendered).strip()
|
||||
"""优先恢复原始 PDF 空白;旧证据继续沿用既有平均字宽阈值,避免模板行为漂移。"""
|
||||
glyphs = [glyph for _index, glyph in row]
|
||||
return render_positioned_row(
|
||||
glyphs,
|
||||
geometry_gap_ratio=0.75,
|
||||
geometry_width_mode='average',
|
||||
minimum_gap_limit=0.01,
|
||||
)
|
||||
|
||||
|
||||
def _visual_rows(items: list[tuple[int, dict[str, Any]]]) -> list[list[tuple[int, dict[str, Any]]]]:
|
||||
|
||||
@@ -1,38 +1,26 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/order_profile.py
|
||||
|
||||
用途:定义订单文档坐标模板 v2 的纯契约和受控字段绑定。
|
||||
用途:定义唯一的订单文档坐标模板契约与 v2 版面签名匹配评分维度。
|
||||
依赖:Pydantic、坐标 bbox 契约、订单字段规则和已注册解析器。
|
||||
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;运行时匹配器与坐标解析器只消费该不可变定义。
|
||||
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费
|
||||
DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成
|
||||
matching_signature 供运行时硬门禁与维度比对。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import html
|
||||
import json
|
||||
import re
|
||||
from decimal import Decimal
|
||||
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.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid, parse_html_grid
|
||||
from app.services.shipping_notice.notice_line_values import parse_number
|
||||
from app.services.shipping_notice.notice_lines import resolve_composite_part_numbers
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import (
|
||||
TableHeaderContract,
|
||||
normalize_table_header,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import HtmlGrid
|
||||
|
||||
|
||||
ORDER_PROFILE_VERSION = 'order_coordinate_profile.v2'
|
||||
PROFILE_EXTRACTORS = frozenset({'direct', 'temp_internal_parts', 'quantity_uom', 'amount_currency', 'price_currency'})
|
||||
HEADER_LINE_ITEM_VALUE_PATTERN = re.compile(
|
||||
r'\b(?:item|line)\s*(?:no\.?|number|#)?\s*[:#-]?\s*0{2,}\d+\b',
|
||||
@@ -319,27 +307,64 @@ class TableRegionProfile(OrderProfileModel):
|
||||
|
||||
|
||||
SCORING_DIMENSION_KEYS = (
|
||||
'table_topology',
|
||||
'row_structure',
|
||||
'anchor_geometry',
|
||||
'header_regions',
|
||||
'header_semantic_position',
|
||||
'column_topology',
|
||||
'table_geometry',
|
||||
'page_structure',
|
||||
'header_path',
|
||||
'customer_hint',
|
||||
'field_spatial_relation',
|
||||
'optional_static_text',
|
||||
'trusted_business_context',
|
||||
)
|
||||
CRITICAL_STRUCTURE_DIMENSION_KEYS = ('table_topology', 'row_structure', 'anchor_geometry')
|
||||
CRITICAL_STRUCTURE_DIMENSION_KEYS = (
|
||||
'header_semantic_position',
|
||||
'column_topology',
|
||||
'table_geometry',
|
||||
)
|
||||
# 历史 v1 权重键 → v2 键;供 model_validator 迁移旧模板配置。
|
||||
_LEGACY_SCORING_WEIGHT_KEYS: dict[str, str] = {
|
||||
'table_topology': 'column_topology',
|
||||
'row_structure': 'table_geometry',
|
||||
'anchor_geometry': 'header_semantic_position',
|
||||
'header_regions': 'field_spatial_relation',
|
||||
'page_structure': 'page_structure',
|
||||
'header_path': 'optional_static_text',
|
||||
'customer_hint': 'trusted_business_context',
|
||||
}
|
||||
|
||||
MatchDimensionState = Literal['matched', 'mismatched', 'unavailable']
|
||||
|
||||
|
||||
class MatchDimensionResult(OrderProfileModel):
|
||||
"""单维匹配结果:三态 + 0~1 得分;unavailable 不计入相似度分母。"""
|
||||
|
||||
state: MatchDimensionState
|
||||
score: float = Field(ge=0, le=1)
|
||||
|
||||
|
||||
class ProfileScoringWeights(OrderProfileModel):
|
||||
"""分项权重;七维之和必须为 1.0,供 matcher 加权汇总确定性评分。"""
|
||||
"""v2 分项权重;七维之和必须为 1.0,供 matcher 加权汇总确定性评分。"""
|
||||
|
||||
table_topology: float = Field(default=0.25, ge=0, le=1)
|
||||
row_structure: float = Field(default=0.20, ge=0, le=1)
|
||||
anchor_geometry: float = Field(default=0.20, ge=0, le=1)
|
||||
header_regions: float = Field(default=0.10, ge=0, le=1)
|
||||
header_semantic_position: float = Field(default=0.30, ge=0, le=1)
|
||||
column_topology: float = Field(default=0.25, ge=0, le=1)
|
||||
table_geometry: float = Field(default=0.15, ge=0, le=1)
|
||||
page_structure: float = Field(default=0.10, ge=0, le=1)
|
||||
header_path: float = Field(default=0.10, ge=0, le=1)
|
||||
customer_hint: float = Field(default=0.05, ge=0, le=1)
|
||||
field_spatial_relation: float = Field(default=0.10, ge=0, le=1)
|
||||
optional_static_text: float = Field(default=0.05, ge=0, le=1)
|
||||
trusted_business_context: float = Field(default=0.05, ge=0, le=1)
|
||||
|
||||
@model_validator(mode='before')
|
||||
@classmethod
|
||||
def migrate_legacy_weight_keys(cls, value: Any) -> Any:
|
||||
"""将 v1 七维权重键映射为 v2,避免历史模板在升级前无法解析。"""
|
||||
if not isinstance(value, dict):
|
||||
return value
|
||||
if any(key in value for key in SCORING_DIMENSION_KEYS):
|
||||
return value
|
||||
migrated = dict(value)
|
||||
for legacy_key, new_key in _LEGACY_SCORING_WEIGHT_KEYS.items():
|
||||
if legacy_key in migrated and new_key not in migrated:
|
||||
migrated[new_key] = migrated.pop(legacy_key)
|
||||
return migrated
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_weight_sum(self) -> 'ProfileScoringWeights':
|
||||
@@ -351,10 +376,11 @@ class ProfileScoringWeights(OrderProfileModel):
|
||||
|
||||
|
||||
class ProfileScoringThresholds(OrderProfileModel):
|
||||
"""自动决胜与关键结构单项阈值;与 minimum_score/minimum_margin 并存,服务多候选评分决胜。"""
|
||||
"""自动决胜阈值;evidence_coverage_minimum 与 matcher 硬门禁对齐。"""
|
||||
|
||||
auto_select_minimum_score: float = Field(default=0.95, ge=0, le=1)
|
||||
auto_select_minimum_margin: float = Field(default=0.15, ge=0, le=1)
|
||||
auto_select_minimum_score: float = Field(default=0.90, ge=0, le=1)
|
||||
auto_select_minimum_margin: float = Field(default=0.12, ge=0, le=1)
|
||||
evidence_coverage_minimum: float = Field(default=0.70, ge=0, le=1)
|
||||
critical_structure_minimum: float = Field(default=0.90, ge=0, le=1)
|
||||
|
||||
|
||||
@@ -378,24 +404,26 @@ class DocumentMatchProfile(OrderProfileModel):
|
||||
page_pattern: Literal['one_or_more'] = 'one_or_more'
|
||||
required_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
|
||||
optional_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
|
||||
negative_anchors: list[DocumentMatchAnchor] = Field(default_factory=list)
|
||||
minimum_score: float = Field(default=0.9, ge=0, le=1)
|
||||
minimum_margin: float = Field(default=0.15, ge=0, le=1)
|
||||
minimum_margin: float = Field(default=0.12, ge=0, le=1)
|
||||
scoring_weights: ProfileScoringWeights = Field(default_factory=ProfileScoringWeights)
|
||||
scoring_thresholds: ProfileScoringThresholds = Field(default_factory=ProfileScoringThresholds)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_anchor_ids(self) -> 'DocumentMatchProfile':
|
||||
"""要求必选和可选锚点名称唯一,避免评分器使用含糊证据。"""
|
||||
ids = [item.anchor_id for item in self.required_anchors + self.optional_anchors]
|
||||
"""要求必选、可选与排除锚点名称唯一,避免评分器使用含糊证据。"""
|
||||
ids = [
|
||||
item.anchor_id
|
||||
for item in self.required_anchors + self.optional_anchors + self.negative_anchors
|
||||
]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('document match anchor ids must be unique')
|
||||
return self
|
||||
|
||||
|
||||
class OrderCoordinateProfileV2(OrderProfileModel):
|
||||
"""保存阶段 0 评审中的订单坐标模板 v2 定义,尚未接入旧运行路径。"""
|
||||
|
||||
contract_version: Literal[ORDER_PROFILE_VERSION] = ORDER_PROFILE_VERSION
|
||||
class OrderCoordinateProfile(OrderProfileModel):
|
||||
"""唯一的订单坐标模板定义;运行时和管理端只消费这一种契约。"""
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
version: int = Field(ge=1)
|
||||
document_match: DocumentMatchProfile
|
||||
@@ -404,7 +432,7 @@ class OrderCoordinateProfileV2(OrderProfileModel):
|
||||
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderCoordinateProfileV2':
|
||||
def validate_profile_rules(self) -> 'OrderCoordinateProfile':
|
||||
"""阻断重复表区和重叠表区,确保一个字段位置只有唯一模板解释。"""
|
||||
ids = [item.region_id for item in self.table_regions]
|
||||
if len(ids) != len(set(ids)):
|
||||
@@ -414,7 +442,14 @@ class OrderCoordinateProfileV2(OrderProfileModel):
|
||||
# Different exact pages may use identical coordinates without competing at runtime.
|
||||
if _table_regions_can_apply_same_page(left, right):
|
||||
_validate_non_overlapping_regions([left.region, right.region])
|
||||
anchor_ids = {item.anchor_id for item in self.document_match.required_anchors + self.document_match.optional_anchors}
|
||||
anchor_ids = {
|
||||
item.anchor_id
|
||||
for item in (
|
||||
self.document_match.required_anchors
|
||||
+ self.document_match.optional_anchors
|
||||
+ self.document_match.negative_anchors
|
||||
)
|
||||
}
|
||||
for table in self.table_regions:
|
||||
if not set(table.continuation_rule.required_anchor_ids).issubset(anchor_ids):
|
||||
raise ValueError('cross-page continuation anchor must be a document match anchor')
|
||||
@@ -451,108 +486,6 @@ def _table_regions_can_apply_same_page(left: TableRegionProfile, right: TableReg
|
||||
return left.page_scope == right.page_scope
|
||||
|
||||
|
||||
# Transitional adapters keep the currently deployed extraction workflow importable while its
|
||||
# callers are migrated to the v2 coordinate runtime in later gated stages. They are not part
|
||||
# of the persisted v2 contract and must not be used by new Profile writes.
|
||||
class OrderProfileColumnRule(OrderProfileModel):
|
||||
"""Legacy runtime column rule retained only until the frozen-run migration is complete."""
|
||||
|
||||
column_index: int = Field(ge=0)
|
||||
extractor_key: Literal['direct', 'temp_internal_parts']
|
||||
target_field_codes: list[str] = Field(min_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_extractor_targets(self) -> 'OrderProfileColumnRule':
|
||||
"""Preserve the established finite extractor whitelist for historical frozen snapshots."""
|
||||
targets = set(self.target_field_codes)
|
||||
if len(targets) != len(self.target_field_codes):
|
||||
raise ValueError('order profile target fields must be unique')
|
||||
if self.extractor_key == 'direct' and len(targets) != 1:
|
||||
raise ValueError('direct order profile extractor requires one target field')
|
||||
if self.extractor_key == 'temp_internal_parts' and targets != {'customer_part_number', 'part_number'}:
|
||||
raise ValueError('TEMP/internal extractor targets are fixed')
|
||||
return self
|
||||
|
||||
|
||||
class CoordinateReconstructionProfile(OrderProfileModel):
|
||||
"""Legacy frozen-run coordinate reconstruction adapter; v2 uses FieldRegion instead."""
|
||||
|
||||
method: Literal['native_pdf_coordinates.v1', 'ocr_pdf_coordinates.v1'] = 'native_pdf_coordinates.v1'
|
||||
column_boundaries: list[float] = Field(default_factory=list)
|
||||
column_field_codes: list[str | None] = Field(default_factory=list)
|
||||
line_start_column_index: int = Field(default=0, ge=0)
|
||||
subrow_layouts: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_boundaries(self) -> 'CoordinateReconstructionProfile':
|
||||
"""Validate historical settings so existing frozen Run snapshots remain safe to load."""
|
||||
if self.subrow_layouts:
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import CoordinateSubrowLayout
|
||||
layouts = [CoordinateSubrowLayout.model_validate(item) for item in self.subrow_layouts]
|
||||
offsets = [item.row_offset for item in layouts]
|
||||
if len(offsets) != len(set(offsets)) or sorted(offsets) != list(range(len(offsets))) or sum(item.role == 'main' for item in layouts) != 1:
|
||||
raise ValueError('coordinate subrow layouts require contiguous offsets and one main row')
|
||||
return self
|
||||
if len(self.column_boundaries) < 3 or self.column_boundaries[0] != 0 or self.column_boundaries[-1] != 1:
|
||||
raise ValueError('coordinate reconstruction boundaries must cover the table')
|
||||
if any(left >= right for left, right in zip(self.column_boundaries, self.column_boundaries[1:])):
|
||||
raise ValueError('coordinate reconstruction boundaries must be strictly increasing')
|
||||
if self.column_field_codes and len(self.column_field_codes) != len(self.column_boundaries) - 1:
|
||||
raise ValueError('coordinate reconstruction field codes must match column count')
|
||||
return self
|
||||
|
||||
|
||||
class OrderDocumentProfile(OrderProfileModel):
|
||||
"""保存当前已发布运行路径的模板结构、列覆盖、数据起始行和质量策略。"""
|
||||
|
||||
contract_version: Literal['shipping_order_document_profile.v1'] = 'shipping_order_document_profile.v1'
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
version: int = Field(ge=1)
|
||||
structure_fingerprint: str = Field(pattern=r'^[0-9a-f]{64}$')
|
||||
header_row_index: int = Field(ge=0)
|
||||
data_start_row_index: int = Field(ge=1)
|
||||
row_structure: Literal['preserved', 'unsupported_row_structure'] = 'preserved'
|
||||
column_rules: list[OrderProfileColumnRule] = Field(default_factory=list)
|
||||
coordinate_reconstruction: CoordinateReconstructionProfile | None = None
|
||||
drop_zero_qty: bool = True
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderDocumentProfile':
|
||||
"""禁止列规则重复;不支持的行结构只能作为识别/路由 Profile,不能配置字段解析。"""
|
||||
columns = [item.column_index for item in self.column_rules]
|
||||
if len(columns) != len(set(columns)):
|
||||
raise ValueError('order profile source columns must be unique')
|
||||
targets = [code for item in self.column_rules for code in item.target_field_codes]
|
||||
if len(targets) != len(set(targets)):
|
||||
raise ValueError('order profile target fields must be unique across columns')
|
||||
if self.data_start_row_index <= self.header_row_index:
|
||||
raise ValueError('order profile data rows must start after the header')
|
||||
if self.row_structure == 'unsupported_row_structure' and self.column_rules:
|
||||
raise ValueError('unsupported row structure profile cannot expose column mappings')
|
||||
if self.row_structure == 'preserved' and not self.column_rules:
|
||||
raise ValueError('preserved row structure profile requires column mappings')
|
||||
return self
|
||||
|
||||
|
||||
class OrderProfileRowResult(OrderProfileModel):
|
||||
"""保存一条模板行的字段值或删除/复核状态,不包含来源原文。"""
|
||||
|
||||
row_index: int = Field(ge=0)
|
||||
status: Literal['parsed', 'deleted', 'needs_review']
|
||||
fields: dict[str, Any] = Field(default_factory=dict)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class OrderProfileParseResult(OrderProfileModel):
|
||||
"""汇总 Profile 是否精确命中以及模板行解析结果。"""
|
||||
|
||||
matched: bool
|
||||
profile_code: str | None = None
|
||||
profile_version: int | None = Field(default=None, ge=1)
|
||||
rows: list[OrderProfileRowResult] = Field(default_factory=list)
|
||||
issues: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
def diagnose_order_profile_header(grid: HtmlGrid, *, header_row_index: int) -> list[str]:
|
||||
"""
|
||||
诊断管理员所选表头是否已经混入明显的订单明细值。
|
||||
@@ -606,266 +539,3 @@ def order_profile_structure_fingerprint(
|
||||
}
|
||||
encoded = json.dumps(payload, sort_keys=True, ensure_ascii=True, separators=(',', ':')).encode()
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def reconstruct_order_profile_html(
|
||||
*, characters: list[dict[str, Any]], table_bbox: dict[str, Any],
|
||||
reconstruction: CoordinateReconstructionProfile,
|
||||
) -> str:
|
||||
"""
|
||||
利用冻结坐标证据生成带稳定虚拟表头的逻辑明细 HTML。
|
||||
|
||||
核心逻辑:先按 x/y 重建物理行,再将 continuation 按列并入最近 data 行;deleted
|
||||
回写最近明细状态,summary 终止数据区。虚拟表头只表达列序,不依赖数据页表头是否完整。
|
||||
|
||||
Args:
|
||||
characters: 当前表格 bbox 内的原生或 OCR 字符坐标。
|
||||
table_bbox: 当前表格页面坐标。
|
||||
reconstruction: 管理员确认的相对列边界。
|
||||
Returns:
|
||||
可由既有 Profile 解析器消费的 HTML;行角色保存在 ``data-row-role`` 属性中。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
|
||||
CoordinateColumnAnchor,
|
||||
reconstruct_multi_subrow_table,
|
||||
reconstruct_table_from_positioned_text,
|
||||
)
|
||||
|
||||
bbox = LayoutBBox.model_validate(table_bbox)
|
||||
if reconstruction.subrow_layouts:
|
||||
logical_rows = reconstruct_multi_subrow_table(
|
||||
characters=characters,
|
||||
table_bbox=bbox,
|
||||
subrow_layouts=reconstruction.subrow_layouts,
|
||||
)
|
||||
field_codes = []
|
||||
for layout in reconstruction.subrow_layouts:
|
||||
for code in layout.get('column_field_codes') or []:
|
||||
if code and code not in field_codes:
|
||||
field_codes.append(code)
|
||||
header = '<tr data-row-role="header">' + ''.join(
|
||||
f'<th>{html.escape(code)}</th>' for code in field_codes
|
||||
) + '</tr>'
|
||||
body = ''.join(
|
||||
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
|
||||
row.role, ','.join(str(index) for index in row.source_row_indices),
|
||||
''.join(f'<td>{html.escape(row.fields.get(code, ""))}</td>' for code in field_codes),
|
||||
)
|
||||
for row in logical_rows
|
||||
)
|
||||
return f'<table>{header}{body}</table>'
|
||||
boundaries = reconstruction.column_boundaries
|
||||
width = bbox.x1 - bbox.x0
|
||||
anchors = [CoordinateColumnAnchor(
|
||||
column_index=index,
|
||||
field_code=(reconstruction.column_field_codes[index] if reconstruction.column_field_codes else None),
|
||||
bbox=LayoutBBox(
|
||||
x0=bbox.x0 + width * boundaries[index], y0=bbox.y0,
|
||||
x1=bbox.x0 + width * boundaries[index + 1], y1=bbox.y1,
|
||||
),
|
||||
) for index in range(len(boundaries) - 1)]
|
||||
result = reconstruct_table_from_positioned_text(
|
||||
characters=characters, table_bbox=bbox, column_anchors=anchors,
|
||||
line_start_column_index=reconstruction.line_start_column_index,
|
||||
)
|
||||
if not result.rows:
|
||||
raise ValidationError(
|
||||
'No coordinate reconstruction rows were produced',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE',
|
||||
)
|
||||
logical_rows: list[dict[str, Any]] = []
|
||||
for row in result.rows:
|
||||
values = {cell.column_index: cell.text for cell in row.cells}
|
||||
if row.role == 'data':
|
||||
logical_rows.append({'role': 'data', 'values': values, 'source_rows': [row.row_index]})
|
||||
elif row.role == 'continuation' and logical_rows:
|
||||
current = logical_rows[-1]
|
||||
for column_index, value in values.items():
|
||||
previous = str(current['values'].get(column_index) or '').strip()
|
||||
current['values'][column_index] = f'{previous} {value}'.strip()
|
||||
current['source_rows'].append(row.row_index)
|
||||
elif row.role == 'deleted' and logical_rows:
|
||||
logical_rows[-1]['role'] = 'deleted'
|
||||
logical_rows[-1]['source_rows'].append(row.row_index)
|
||||
elif row.role == 'summary':
|
||||
break
|
||||
|
||||
header = '<tr data-row-role="header">' + ''.join(
|
||||
f'<th>coordinate_column_{index + 1}</th>' for index in range(len(anchors))
|
||||
) + '</tr>'
|
||||
body = ''.join(
|
||||
'<tr data-row-role="{}" data-source-rows="{}">{}</tr>'.format(
|
||||
row['role'], ','.join(str(index) for index in row['source_rows']),
|
||||
''.join(
|
||||
f'<td>{html.escape(str(row["values"].get(index, "")))}</td>'
|
||||
for index in range(len(anchors))
|
||||
),
|
||||
)
|
||||
for row in logical_rows
|
||||
)
|
||||
return f'<table>{header}{body}</table>'
|
||||
|
||||
|
||||
def parse_html_table_with_order_profile(
|
||||
html: str,
|
||||
*,
|
||||
table_id: str,
|
||||
profile: OrderDocumentProfile,
|
||||
contract: TableHeaderContract,
|
||||
) -> OrderProfileParseResult:
|
||||
"""
|
||||
在结构指纹精确命中时按模板列规则解析订单行。
|
||||
|
||||
Args:
|
||||
html: MinerU 或 EML 提供的单张 HTML table。
|
||||
table_id: 当前文档内稳定表格 ID。
|
||||
profile: Run 锁定的 published 模板 Profile 快照。
|
||||
contract: Run 锁定订单 Schema 表头/字段契约。
|
||||
Returns:
|
||||
未命中时不产生行;不支持行结构时返回阻断问题;命中时逐行解析。
|
||||
"""
|
||||
grid = parse_html_grid(html, table_id=table_id)
|
||||
actual = order_profile_structure_fingerprint(
|
||||
grid,
|
||||
header_row_index=profile.header_row_index,
|
||||
)
|
||||
if actual != profile.structure_fingerprint:
|
||||
return OrderProfileParseResult(matched=False, issues=['order_profile_structure_mismatch'])
|
||||
if profile.row_structure == 'unsupported_row_structure':
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
issues=['order_profile_row_structure_unsupported'],
|
||||
)
|
||||
if any(rule.column_index >= grid.column_count for rule in profile.column_rules):
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
issues=['order_profile_column_out_of_range'],
|
||||
)
|
||||
row_roles = _profile_html_row_roles(html)
|
||||
rows = [
|
||||
_parse_profile_row(
|
||||
grid,
|
||||
row_index=index,
|
||||
profile=profile,
|
||||
contract=contract,
|
||||
source_role=row_roles[index] if index < len(row_roles) else 'data',
|
||||
)
|
||||
for index in range(profile.data_start_row_index, grid.row_count)
|
||||
]
|
||||
if not rows:
|
||||
return OrderProfileParseResult(matched=False)
|
||||
return OrderProfileParseResult(
|
||||
matched=True,
|
||||
profile_code=profile.profile_code,
|
||||
profile_version=profile.version,
|
||||
rows=rows,
|
||||
)
|
||||
|
||||
|
||||
def _parse_profile_row(
|
||||
grid: HtmlGrid,
|
||||
*,
|
||||
row_index: int,
|
||||
profile: OrderDocumentProfile,
|
||||
contract: TableHeaderContract,
|
||||
source_role: str = 'data',
|
||||
) -> OrderProfileRowResult:
|
||||
"""执行一条逻辑模板行;坐标重建删除状态和零 Qty 均映射为 deleted。"""
|
||||
fields: dict[str, Any] = {}
|
||||
issues: list[str] = []
|
||||
explicit_qty: float | None = None
|
||||
for rule in profile.column_rules:
|
||||
slot = grid.rows[row_index][rule.column_index]
|
||||
raw = slot.text.strip() if slot is not None else ''
|
||||
extracted = (
|
||||
{rule.target_field_codes[0]: raw}
|
||||
if rule.extractor_key == 'direct'
|
||||
else _apply_profile_extractor(rule.extractor_key, raw)
|
||||
)
|
||||
for code in rule.target_field_codes:
|
||||
candidate = extracted.get(code)
|
||||
if candidate in (None, ''):
|
||||
continue
|
||||
if code == 'qty':
|
||||
explicit_qty = parse_number(candidate)
|
||||
config = contract.fields_by_code.get(code)
|
||||
value = _normalize_profile_value(candidate, config)
|
||||
if value is None:
|
||||
issues.append(f'order_profile_field_invalid:{code}')
|
||||
continue
|
||||
fields[code] = _profile_json_value(value)
|
||||
if source_role == 'deleted' or (profile.drop_zero_qty and explicit_qty == 0):
|
||||
return OrderProfileRowResult(row_index=row_index, status='deleted')
|
||||
required_build = {'part_number', 'qty'}
|
||||
if not required_build.issubset(fields):
|
||||
issues.append('order_profile_build_fields_missing')
|
||||
return OrderProfileRowResult(
|
||||
row_index=row_index,
|
||||
status='parsed' if not issues else 'needs_review',
|
||||
fields=fields,
|
||||
issues=sorted(set(issues)),
|
||||
)
|
||||
|
||||
|
||||
def _profile_html_row_roles(source_html: str) -> list[str]:
|
||||
"""读取坐标重建写入的受控行角色;普通 MinerU HTML 默认按 data 处理。"""
|
||||
from bs4 import BeautifulSoup
|
||||
|
||||
table = BeautifulSoup(source_html or '', 'html.parser').find('table')
|
||||
if table is None:
|
||||
return []
|
||||
return [str(row.get('data-row-role') or 'data') for row in table.find_all('tr')]
|
||||
|
||||
|
||||
def _apply_profile_extractor(extractor_key: str, raw: str) -> dict[str, Any]:
|
||||
"""执行代码注册的有限解析器;未知 key 不允许运行。"""
|
||||
if extractor_key == 'temp_internal_parts':
|
||||
resolved = resolve_composite_part_numbers(raw)
|
||||
if resolved:
|
||||
return resolved
|
||||
customer = re.search(r'\b(?:AM)?TEMP-[A-Z0-9._-]+\b', raw, re.IGNORECASE)
|
||||
internal = re.search(r'\bD4-[A-Z0-9._-]+\b', raw, re.IGNORECASE)
|
||||
if customer and internal:
|
||||
return {
|
||||
'customer_part_number': customer.group(0),
|
||||
'part_number': internal.group(0),
|
||||
}
|
||||
return {}
|
||||
raise ValueError('order profile extractor is not registered')
|
||||
|
||||
|
||||
def _normalize_profile_value(raw: Any, config: dict[str, Any] | None) -> Any:
|
||||
"""按冻结 Schema 类型和 validator 规范化模板字段;模板日期兼容常见美式订单格式。"""
|
||||
if config is None:
|
||||
return None
|
||||
value_type = str(config.get('value_type') or 'string')
|
||||
candidate = raw
|
||||
if value_type == 'date':
|
||||
text = str(raw or '').strip()
|
||||
matched = re.fullmatch(r'(\d{1,2})/(\d{1,2})/(\d{4})', text)
|
||||
if matched:
|
||||
candidate = f'{matched.group(3)}-{int(matched.group(1)):02d}-{int(matched.group(2)):02d}'
|
||||
if value_type in {'decimal', 'integer'}:
|
||||
candidate = parse_number(raw)
|
||||
if candidate is None:
|
||||
return None
|
||||
if value_type == 'integer':
|
||||
if not float(candidate).is_integer():
|
||||
return None
|
||||
candidate = int(candidate)
|
||||
try:
|
||||
value = normalize_order_field_value(candidate, config)
|
||||
return value if value is not None and validate_order_field_value(value, config) else None
|
||||
except (ArithmeticError, TypeError, ValueError, ValidationError):
|
||||
return None
|
||||
|
||||
|
||||
def _profile_json_value(value: Any) -> Any:
|
||||
"""把字段规则返回值转换为数据库 JSON 可序列化标量。"""
|
||||
if isinstance(value, Decimal):
|
||||
return int(value) if value == value.to_integral_value() else float(value)
|
||||
return value.isoformat() if hasattr(value, 'isoformat') else value
|
||||
@@ -4,6 +4,7 @@ services/shipping_notice/document_layout/order_profile_extractors.py
|
||||
用途:执行订单坐标 Profile v2 的有限注册字段解析器。
|
||||
依赖:订单料号复合解析与数值解析。
|
||||
逻辑:坐标重建先取得管理员框选的原文,本模块再将其安全拆成固定业务字段;任何拆分失败均不返回部分字段。
|
||||
另提供 XFA/坐标共用的 ``unit_price / price_unit``(如 ``898.72 / 1``)确定性拆分。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,9 +19,44 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
_NUMBER_UNIT = re.compile(r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*([A-Za-z]{1,12})\s*$')
|
||||
_MONEY_CURRENCY = re.compile(r'^\s*([A-Za-z]{3}|[$€£¥])\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*$')
|
||||
_CURRENCY_MONEY = re.compile(r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*([A-Za-z]{3}|[$€£¥])\s*$')
|
||||
# 真实 XFA NETPR 常见写法:单价 / 价格单位,例如 ``898.72 / 1``。
|
||||
_UNIT_PRICE_PER_PRICE_UNIT = re.compile(
|
||||
r'^\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*/\s*([+-]?(?:\d+(?:,\d{3})*|\d*)(?:\.\d+)?)\s*$'
|
||||
)
|
||||
_CURRENCY_SYMBOLS = {'$': 'USD', '€': 'EUR', '£': 'GBP', '¥': 'CNY'}
|
||||
|
||||
|
||||
def parse_unit_price_with_price_unit(raw: str | None) -> dict[str, str] | None:
|
||||
"""
|
||||
解析 ``单价 / 价格单位`` 复合文本。
|
||||
|
||||
核心逻辑:仅接受确定性 ``number / number``;逗号千分位剔除后返回两段字符串。
|
||||
不匹配时返回 None(调用方回退单字段 Decimal 解析)。
|
||||
|
||||
Args:
|
||||
raw: datasets / 单元格原文,例如 ``898.72 / 1``。
|
||||
|
||||
Returns:
|
||||
``{'unit_price': '...', 'price_unit': '...'}`` 或 None。
|
||||
"""
|
||||
text = str(raw or '').strip()
|
||||
if not text or '/' not in text:
|
||||
return None
|
||||
matched = _UNIT_PRICE_PER_PRICE_UNIT.fullmatch(text)
|
||||
if not matched:
|
||||
return None
|
||||
unit_price = matched.group(1).replace(',', '')
|
||||
price_unit = matched.group(2).replace(',', '')
|
||||
try:
|
||||
Decimal(unit_price)
|
||||
Decimal(price_unit)
|
||||
except (InvalidOperation, ValueError):
|
||||
return None
|
||||
if not unit_price or not price_unit:
|
||||
return None
|
||||
return {'unit_price': unit_price, 'price_unit': price_unit}
|
||||
|
||||
|
||||
def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str) -> dict[str, str]:
|
||||
"""将已确认区域按注册解析器拆分,并把预约单号统一为合法纯数字。"""
|
||||
text = str(raw or '').strip()
|
||||
@@ -56,6 +92,8 @@ def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str
|
||||
'line_amount_before_tax' if extractor_key == 'amount_currency' else 'unit_price': amount.replace(',', ''),
|
||||
'currency': _CURRENCY_SYMBOLS.get(currency, currency.upper()),
|
||||
}
|
||||
if extractor_key == 'unit_price_price_unit':
|
||||
return parse_unit_price_with_price_unit(text) or {}
|
||||
return {}
|
||||
|
||||
|
||||
@@ -71,4 +109,6 @@ def registered_extractor_output_codes(*, extractor_key: str, field_code: str) ->
|
||||
return {'line_amount_before_tax', 'currency'}
|
||||
if extractor_key == 'price_currency':
|
||||
return {'unit_price', 'currency'}
|
||||
if extractor_key == 'unit_price_price_unit':
|
||||
return {'unit_price', 'price_unit'}
|
||||
return set()
|
||||
File diff suppressed because it is too large.
Load diff
+257
@@ -0,0 +1,257 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/order_profile_parse_validation.py
|
||||
|
||||
用途:对模板匹配候选做只读解析可行性校验,不创建 Candidate/Order/Task。
|
||||
依赖:OrderCoordinateProfile、coordinate_region_text、order_profile 契约。
|
||||
逻辑:由 order_extraction_workflow 在 matcher 硬门禁后调用;确定性/idempotent;
|
||||
返回 passed/reason_codes/metrics 供 unique_match 二次裁决。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
|
||||
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
|
||||
|
||||
|
||||
_NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$')
|
||||
_DATE_PATTERN = re.compile(
|
||||
r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{4})$',
|
||||
)
|
||||
|
||||
|
||||
def validate_profile_parse_candidate(
|
||||
*,
|
||||
profile_snapshot: dict[str, Any],
|
||||
layout: dict[str, Any],
|
||||
definition: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
校验 Profile 是否具备在当前 layout 上完成坐标解析的结构前提。
|
||||
|
||||
核心逻辑:解析模板定义 → 统计 header/line 字段区覆盖 → 估计明细行数 →
|
||||
检测未知列与基础类型合理性;只读,不写入任何业务实体。
|
||||
|
||||
Args:
|
||||
profile_snapshot: 冻结 Profile 快照(含 definition)。
|
||||
layout: 冻结 layout 快照,含 coordinate_evidence。
|
||||
definition: Schema definition_json,用于字段 scope/类型参考。
|
||||
|
||||
Returns:
|
||||
{passed: bool, reason_codes: list[str], metrics: dict}。
|
||||
"""
|
||||
reason_codes: list[str] = []
|
||||
profile_def = profile_snapshot.get('definition') if isinstance(profile_snapshot.get('definition'), dict) else {}
|
||||
try:
|
||||
profile = OrderCoordinateProfile(
|
||||
profile_code=str(profile_snapshot.get('profile_code') or profile_def.get('profile_code') or 'TMP'),
|
||||
version=int(profile_snapshot.get('version') or profile_def.get('version') or 1),
|
||||
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 [],
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return {
|
||||
'passed': False,
|
||||
'reason_codes': ['profile_parse_definition_invalid'],
|
||||
'metrics': {},
|
||||
}
|
||||
|
||||
schema_fields = {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_code')
|
||||
}
|
||||
glyphs, page = _page_glyphs(layout)
|
||||
if glyphs is None or page is None:
|
||||
return {
|
||||
'passed': False,
|
||||
'reason_codes': ['profile_parse_evidence_missing'],
|
||||
'metrics': {'layouts_with_pages': 0},
|
||||
}
|
||||
|
||||
# [STEP 1] Header 字段覆盖
|
||||
header_required = [
|
||||
item for item in profile.order_field_layouts
|
||||
if item.scope == 'header' and item.required
|
||||
]
|
||||
header_bound = [item for item in profile.order_field_layouts if item.scope == 'header']
|
||||
header_coverage = _field_region_coverage(
|
||||
fields=header_bound, glyphs=glyphs, page=page,
|
||||
)
|
||||
|
||||
# [STEP 2] Line 字段覆盖
|
||||
line_fields = [
|
||||
field for table in profile.table_regions for layout in table.line_layouts
|
||||
for field in layout.field_regions if field.scope == 'line'
|
||||
]
|
||||
line_coverage = _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page)
|
||||
|
||||
# [STEP 3] 明细行数启发式
|
||||
line_count = _estimate_line_count(profile=profile, glyphs=glyphs, page=page)
|
||||
min_lines = 1
|
||||
max_lines = max(500, len(glyphs) // max(1, len(line_fields) or 1))
|
||||
valid_line_count = min_lines <= line_count <= max_lines
|
||||
if not valid_line_count:
|
||||
reason_codes.append('profile_parse_line_count_invalid')
|
||||
|
||||
# [STEP 4] 未知列启发式:line 字段区无文字的比例
|
||||
empty_regions = line_coverage.get('empty_region_count', 0)
|
||||
total_regions = line_coverage.get('total_region_count', 0)
|
||||
unknown_column_ratio = (empty_regions / total_regions) if total_regions else 0.0
|
||||
if unknown_column_ratio > 0.6:
|
||||
reason_codes.append('profile_parse_unknown_columns')
|
||||
|
||||
# [STEP 5] 类型 sanity(轻量)
|
||||
type_issues = _type_sanity_issues(
|
||||
line_fields=line_fields, glyphs=glyphs, page=page, schema_fields=schema_fields,
|
||||
)
|
||||
if type_issues:
|
||||
reason_codes.append('profile_parse_type_sanity_failed')
|
||||
|
||||
required_header_ratio = header_coverage.get('coverage_ratio', 0.0)
|
||||
if header_required and required_header_ratio < 0.5:
|
||||
reason_codes.append('profile_parse_header_coverage_insufficient')
|
||||
|
||||
required_line_codes = {
|
||||
field.field_code
|
||||
for table in profile.table_regions
|
||||
for layout in table.line_layouts
|
||||
for field in layout.field_regions
|
||||
if field.scope == 'line'
|
||||
}
|
||||
if required_line_codes and line_coverage.get('coverage_ratio', 0.0) < 0.4:
|
||||
reason_codes.append('profile_parse_line_coverage_insufficient')
|
||||
|
||||
metrics = {
|
||||
'header_field_count': len(header_bound),
|
||||
'header_coverage_ratio': round(required_header_ratio, 4),
|
||||
'line_field_count': len(line_fields),
|
||||
'line_coverage_ratio': round(line_coverage.get('coverage_ratio', 0.0), 4),
|
||||
'estimated_line_count': line_count,
|
||||
'unknown_column_ratio': round(unknown_column_ratio, 4),
|
||||
'type_issue_count': len(type_issues),
|
||||
}
|
||||
passed = not reason_codes
|
||||
if not passed:
|
||||
reason_codes.append('profile_parse_validation_failed')
|
||||
return {
|
||||
'passed': passed,
|
||||
'reason_codes': sorted(set(reason_codes)),
|
||||
'metrics': metrics,
|
||||
}
|
||||
|
||||
|
||||
def _page_glyphs(layout: dict[str, Any]) -> tuple[list[dict[str, Any]] | None, dict[str, Any] | None]:
|
||||
"""读取首页字符与页尺寸。"""
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page = pages.get('1') or pages.get(1)
|
||||
if not isinstance(page, dict):
|
||||
return None, None
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
|
||||
if not isinstance(glyphs, list):
|
||||
glyphs = []
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
glyphs.extend(table_glyphs)
|
||||
if not isinstance(glyphs, list) or not glyphs:
|
||||
return None, page
|
||||
return glyphs, page
|
||||
|
||||
|
||||
def _field_region_coverage(
|
||||
*,
|
||||
fields: list[Any],
|
||||
glyphs: list[dict[str, Any]],
|
||||
page: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""统计字段区域是否有非空文字。"""
|
||||
if not fields:
|
||||
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
|
||||
non_empty = 0
|
||||
measurable = 0
|
||||
for field in fields:
|
||||
region = _field_validation_region(field)
|
||||
if region is None:
|
||||
continue
|
||||
measurable += 1
|
||||
text = read_coordinate_region_text(glyphs=glyphs, page=page, region=region)
|
||||
if str(text or '').strip():
|
||||
non_empty += 1
|
||||
total = measurable
|
||||
return {
|
||||
'coverage_ratio': non_empty / total if total else 1.0,
|
||||
'empty_region_count': total - non_empty,
|
||||
'total_region_count': total,
|
||||
}
|
||||
|
||||
|
||||
def _field_validation_region(field: Any) -> dict[str, Any] | None:
|
||||
"""
|
||||
读取 FieldRegion 或 OrderFieldLayout 可直接验证的绝对区域。
|
||||
|
||||
核心逻辑:订单头相对 anchor 的 value_region 需要先定位锚点,当前轻量验证器不重复执行字段抽取;
|
||||
仅验证 absolute_value_region/fallback_value_region,无法直接度量时返回 None 而不是抛异常。
|
||||
"""
|
||||
for key in ('region', 'absolute_value_region', 'fallback_value_region'):
|
||||
value = getattr(field, key, None)
|
||||
if value is not None:
|
||||
return value.model_dump() if hasattr(value, 'model_dump') else value
|
||||
return None
|
||||
|
||||
|
||||
def _estimate_line_count(
|
||||
*,
|
||||
profile: OrderCoordinateProfile,
|
||||
glyphs: list[dict[str, Any]],
|
||||
page: dict[str, Any],
|
||||
) -> int:
|
||||
"""按主表区垂直带内非空行带估计明细行数。"""
|
||||
if not profile.table_regions:
|
||||
return 0
|
||||
table = profile.table_regions[0]
|
||||
region = table.region.model_dump()
|
||||
height = float(page.get('height') or 1)
|
||||
y0 = float(region.get('y0', 0)) * height
|
||||
y1 = float(region.get('y1', 1)) * height
|
||||
row_height = max(8.0, (y1 - y0) / max(1, len(table.line_layouts) or 1) / 3)
|
||||
lines: set[int] = set()
|
||||
for glyph in glyphs:
|
||||
bbox = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else {}
|
||||
try:
|
||||
center_y = (float(bbox.get('y0', 0)) + float(bbox.get('y1', 0))) / 2
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if y0 <= center_y <= y1 and str(glyph.get('text') or '').strip():
|
||||
lines.add(int(center_y // row_height))
|
||||
return max(0, len(lines))
|
||||
|
||||
|
||||
def _type_sanity_issues(
|
||||
*,
|
||||
line_fields: list[Any],
|
||||
glyphs: list[dict[str, Any]],
|
||||
page: dict[str, Any],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
) -> list[str]:
|
||||
"""对数量/日期类字段做轻量类型检查。"""
|
||||
issues: list[str] = []
|
||||
for field in line_fields:
|
||||
schema = schema_fields.get(field.field_code) or {}
|
||||
value_type = str(schema.get('value_type') or schema.get('type') or '').lower()
|
||||
if value_type not in {'number', 'integer', 'decimal', 'date', 'datetime'}:
|
||||
continue
|
||||
region = field.region.model_dump() if hasattr(field.region, 'model_dump') else field.region
|
||||
text = str(read_coordinate_region_text(glyphs=glyphs, page=page, region=region) or '').strip()
|
||||
if not text:
|
||||
continue
|
||||
if value_type in {'number', 'integer', 'decimal'} and not _NUMERIC_PATTERN.match(text.replace(',', '')):
|
||||
issues.append(field.field_code)
|
||||
if value_type in {'date', 'datetime'} and not _DATE_PATTERN.match(text):
|
||||
issues.append(field.field_code)
|
||||
return issues
|
||||
@@ -0,0 +1,576 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/order_profile_signature.py
|
||||
|
||||
用途:从模板定义与冻结样本坐标证据生成不可变版面签名(统计摘要,不含正文/URL)。
|
||||
依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。
|
||||
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
from typing import Any
|
||||
|
||||
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.order_profile import OrderCoordinateProfile, RelativeRegion
|
||||
from app.services.shipping_notice.order_extraction_route_contract import PROFILE_SCORING_POLICY_ID
|
||||
|
||||
|
||||
# 稳定签名类型用于审计识别,不参与运行时版本分支。
|
||||
LAYOUT_SIGNATURE_ID = 'order-profile-layout-signature'
|
||||
MATCHER_POLICY_ID = PROFILE_SCORING_POLICY_ID
|
||||
|
||||
# 动态业务值不得进入表头签名;仅保留多样本稳定出现的固定文字。
|
||||
_DYNAMIC_TOKEN_PATTERNS = (
|
||||
re.compile(r'^\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}$'),
|
||||
re.compile(r'^\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4}$'),
|
||||
re.compile(r'^[A-Z]{0,4}\d{5,}[A-Z0-9\-]*$', re.IGNORECASE),
|
||||
re.compile(r'^\d+([.,]\d+)?$'),
|
||||
re.compile(r'^(po|p\.?o\.?|qty|quantity|amount|price|date|no\.?|#)\s*[:#-]?\s*\S+', re.IGNORECASE),
|
||||
)
|
||||
|
||||
|
||||
def build_layout_signature(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
sample_layouts: list[dict[str, Any]],
|
||||
source_sample_refs: list[dict[str, Any]] | None = None,
|
||||
layout_version_refs: list[dict[str, Any]] | None = None,
|
||||
provider_versions: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
生成版面签名快照;相同输入必须得到相同 checksum。
|
||||
|
||||
核心逻辑:解析模板表区/表头/字段关系 → 从样本区域读取固定文字 → 多样本聚合
|
||||
中位数与容差 → 过滤动态值与单样本噪声 → 计算稳定 checksum。
|
||||
|
||||
Args:
|
||||
definition: 当前草稿或冻结 Profile 定义 JSON。
|
||||
sample_layouts: 冻结 layout 快照列表,含 coordinate_evidence。
|
||||
source_sample_refs: 安全样本身份引用(id/role/content_hash),不含文件名正文。
|
||||
layout_version_refs: Layout 版本身份引用。
|
||||
provider_versions: Provider/Parser 版本摘要。
|
||||
|
||||
Returns:
|
||||
含 signature / signature_checksum / matcher_policy_version 的快照字典。
|
||||
|
||||
Raises:
|
||||
ValueError: 定义无法解析为 OrderCoordinateProfile。
|
||||
"""
|
||||
# [STEP 1] 解析模板契约
|
||||
profile = OrderCoordinateProfile(
|
||||
profile_code=str(definition.get('profile_code') or 'TMP'),
|
||||
version=int(definition.get('version') or 1),
|
||||
document_match=definition.get('document_match') or {
|
||||
'required_anchors': [], 'optional_anchors': [],
|
||||
},
|
||||
table_regions=definition.get('table_regions') or [],
|
||||
order_field_layouts=definition.get('order_field_layouts') or [],
|
||||
)
|
||||
|
||||
# [STEP 2] 页面与表区几何模式
|
||||
page_patterns = _build_page_patterns(sample_layouts=sample_layouts)
|
||||
table_patterns = [
|
||||
_build_table_pattern(table=table, sample_layouts=sample_layouts)
|
||||
for table in profile.table_regions
|
||||
]
|
||||
field_relation_graph = _build_field_relation_graph(profile, sample_layouts=sample_layouts)
|
||||
evidence_quality = _build_evidence_quality(
|
||||
sample_layouts=sample_layouts,
|
||||
table_patterns=table_patterns,
|
||||
source_sample_count=len(sample_layouts),
|
||||
)
|
||||
|
||||
signature = {
|
||||
'signature_version': LAYOUT_SIGNATURE_ID,
|
||||
'page_patterns': page_patterns,
|
||||
'table_patterns': table_patterns,
|
||||
'field_relation_graph': field_relation_graph,
|
||||
'applicable_dimensions': [
|
||||
'header_semantic_position',
|
||||
'column_topology',
|
||||
'table_geometry',
|
||||
'page_structure',
|
||||
'field_spatial_relation',
|
||||
'optional_static_text',
|
||||
'trusted_business_context',
|
||||
],
|
||||
'evidence_quality': evidence_quality,
|
||||
}
|
||||
checksum = signature_checksum(signature)
|
||||
return {
|
||||
'signature': signature,
|
||||
'signature_checksum': checksum,
|
||||
'source_sample_refs': list(source_sample_refs or []),
|
||||
'layout_version_refs': list(layout_version_refs or []),
|
||||
'provider_versions': list(provider_versions or []),
|
||||
'matcher_policy_version': MATCHER_POLICY_ID,
|
||||
}
|
||||
|
||||
|
||||
def signature_checksum(signature: dict[str, Any]) -> str:
|
||||
"""
|
||||
对签名主体计算稳定 SHA-256;忽略非签名元数据字段。
|
||||
|
||||
Args:
|
||||
signature: 签名主体(不含 checksum / refs)。
|
||||
|
||||
Returns:
|
||||
64 位十六进制 checksum。
|
||||
"""
|
||||
encoded = json.dumps(signature, sort_keys=True, ensure_ascii=True, separators=(',', ':')).encode()
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def signature_is_safe_for_audit(snapshot: dict[str, Any]) -> bool:
|
||||
"""
|
||||
检查签名快照是否不含原件 URL、凭据或超长正文。
|
||||
|
||||
Args:
|
||||
snapshot: ValidationRun.result_snapshot_json 候选。
|
||||
|
||||
Returns:
|
||||
True 表示可通过审计安全边界。
|
||||
"""
|
||||
forbidden_substrings = ('http://', 'https://', 'minio', 'password', 'token=', 'secret')
|
||||
blob = json.dumps(snapshot, ensure_ascii=True).casefold()
|
||||
if any(item in blob for item in forbidden_substrings):
|
||||
return False
|
||||
# 表头 token 单条过长视为可能混入正文
|
||||
signature = snapshot.get('signature') if isinstance(snapshot.get('signature'), dict) else {}
|
||||
for table in signature.get('table_patterns') or []:
|
||||
for token in (table.get('header_tokens') or []):
|
||||
if len(str(token)) > 80:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _build_page_patterns(*, sample_layouts: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""汇总首页宽高比与表格数量范围。"""
|
||||
ratios: list[float] = []
|
||||
table_counts: list[int] = []
|
||||
for layout in sample_layouts:
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
first = pages.get('1') or pages.get(1) or next(iter(pages.values()), None)
|
||||
if isinstance(first, dict):
|
||||
width = float(first.get('width') or 0)
|
||||
height = float(first.get('height') or 0)
|
||||
if width > 0 and height > 0:
|
||||
ratios.append(width / height)
|
||||
tables = [item for item in (layout.get('tables') or []) if isinstance(item, dict)]
|
||||
if tables:
|
||||
table_counts.append(len(tables))
|
||||
# Evidence missing in every sample is not a template-shaped default. The
|
||||
# matcher will mark this dimension unavailable instead of rewarding config.
|
||||
if not ratios or not table_counts:
|
||||
return []
|
||||
median_ratio = statistics.median(ratios)
|
||||
low = min(table_counts)
|
||||
high = max(table_counts)
|
||||
return [{
|
||||
'page_scope': 'first_page',
|
||||
'aspect_ratio': {
|
||||
'median': round(median_ratio, 4),
|
||||
'tolerance': 0.03,
|
||||
},
|
||||
'table_count_range': [low, high],
|
||||
}]
|
||||
|
||||
|
||||
def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""从样本实际表格与字符坐标聚合版面特征,不以标注框伪造观测结果。"""
|
||||
region = table.region
|
||||
bbox_samples: list[list[float]] = []
|
||||
header_tokens_by_sample: list[list[str]] = []
|
||||
column_centers_by_sample: list[list[float]] = []
|
||||
column_widths_by_sample: list[list[float]] = []
|
||||
|
||||
header_layouts = list(table.header_layouts or [])
|
||||
header_region = _union_relative_regions([item.region for item in header_layouts])
|
||||
field_regions = [
|
||||
field for layout in header_layouts for field in (layout.field_regions or [])
|
||||
] or [
|
||||
field for layout in (table.line_layouts or []) for field in (layout.field_regions or [])
|
||||
]
|
||||
column_count = len(field_regions) or max(
|
||||
(len(layout.field_regions or []) for layout in (table.line_layouts or [])),
|
||||
default=0,
|
||||
)
|
||||
|
||||
for layout in sample_layouts:
|
||||
observed = _observe_sample_table(
|
||||
layout, target_region=region, header_region=header_region,
|
||||
)
|
||||
if observed is None:
|
||||
continue
|
||||
bbox_samples.append(observed['bbox'])
|
||||
header_tokens_by_sample.append(observed['header_tokens'])
|
||||
if observed['column_centers']:
|
||||
column_centers_by_sample.append(observed['column_centers'])
|
||||
column_widths_by_sample.append(observed['column_width_ratios'])
|
||||
|
||||
stable_tokens = _stable_tokens(header_tokens_by_sample)
|
||||
median_bbox = _median_vector(bbox_samples)
|
||||
median_centers = _median_columns(column_centers_by_sample)
|
||||
median_widths = _median_columns(column_widths_by_sample)
|
||||
|
||||
return {
|
||||
'region_id': table.region_id,
|
||||
'page_scope': table.page_scope,
|
||||
'bbox': {
|
||||
'median': [round(v, 4) for v in median_bbox] if median_bbox else None,
|
||||
'tolerance': [0.03, 0.04, 0.03, 0.05],
|
||||
},
|
||||
'header_bbox': [
|
||||
header_region.x0, header_region.y0, header_region.x1, header_region.y1,
|
||||
] if header_region is not None else None,
|
||||
'header_row_count': max(1, len(header_layouts)),
|
||||
'column_count': int(len(median_centers) or column_count),
|
||||
'column_centers': median_centers,
|
||||
'column_width_ratios': median_widths,
|
||||
'header_tokens': stable_tokens,
|
||||
'header_order': list(stable_tokens),
|
||||
}
|
||||
|
||||
|
||||
def _build_field_relation_graph(
|
||||
profile: OrderCoordinateProfile, *, sample_layouts: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""记录样本中实际静态标签的相对位置;缺观测不以模板坐标替代。"""
|
||||
relations: list[dict[str, Any]] = []
|
||||
layouts = list(profile.order_field_layouts or [])
|
||||
for index, left in enumerate(layouts):
|
||||
if left.anchor is None:
|
||||
continue
|
||||
left_label = str(left.anchor.text or '').strip()
|
||||
if not left_label:
|
||||
continue
|
||||
for right in layouts[index + 1:]:
|
||||
if right.anchor is None:
|
||||
continue
|
||||
right_label = str(right.anchor.text or '').strip()
|
||||
if not right_label:
|
||||
continue
|
||||
offsets = []
|
||||
for sample in sample_layouts:
|
||||
left_center = _find_text_center(sample, left_label)
|
||||
right_center = _find_text_center(sample, right_label)
|
||||
if left_center and right_center:
|
||||
offsets.append((right_center[0] - left_center[0], right_center[1] - left_center[1]))
|
||||
if not offsets:
|
||||
continue
|
||||
relations.append({
|
||||
'left_field_code': left.field_code,
|
||||
'right_field_code': right.field_code,
|
||||
'left_label': left_label,
|
||||
'right_label': right_label,
|
||||
'dx': round(statistics.median(item[0] for item in offsets), 4),
|
||||
'dy': round(statistics.median(item[1] for item in offsets), 4),
|
||||
})
|
||||
return relations[:32]
|
||||
|
||||
|
||||
def _observe_sample_table(
|
||||
layout: dict[str, Any], *, target_region: RelativeRegion,
|
||||
header_region: RelativeRegion | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""读取样本中与标注区域重叠最高的真实表格及其页级字符几何。"""
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
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 {}
|
||||
selected: tuple[dict[str, Any], dict[str, Any], list[float]] | None = None
|
||||
for item in tables:
|
||||
page = pages.get(str(item.get('page_no') or 1)) or pages.get(item.get('page_no') or 1)
|
||||
bbox = item.get('bbox') if isinstance(item.get('bbox'), dict) else {}
|
||||
if not isinstance(page, dict):
|
||||
continue
|
||||
normalized = _normalized_bbox(bbox, page=page)
|
||||
if normalized is None:
|
||||
glyphs = page_glyphs.get(str(item.get('page_no') or 1)) or page_glyphs.get(item.get('page_no') or 1) or []
|
||||
normalized = _glyph_union_bbox(glyphs, page=page)
|
||||
if normalized is None:
|
||||
continue
|
||||
overlap = _bbox_overlap(normalized, [target_region.x0, target_region.y0, target_region.x1, target_region.y1])
|
||||
if selected is None or overlap > _bbox_overlap(selected[2], [target_region.x0, target_region.y0, target_region.x1, target_region.y1]):
|
||||
selected = (item, page, normalized)
|
||||
if selected is None:
|
||||
return None
|
||||
item, page, bbox = selected
|
||||
glyphs = page_glyphs.get(str(item.get('page_no') or 1)) or page_glyphs.get(item.get('page_no') or 1) or []
|
||||
if not isinstance(glyphs, list):
|
||||
return None
|
||||
table_glyphs = [glyph for glyph in glyphs if _glyph_center_in_bbox(glyph, bbox, page=page)]
|
||||
header_bbox = (
|
||||
[header_region.x0, header_region.y0, header_region.x1, header_region.y1]
|
||||
if header_region is not None else None
|
||||
)
|
||||
header_glyphs = _header_glyphs(
|
||||
table_glyphs, page=page, bbox=bbox, header_bbox=header_bbox,
|
||||
)
|
||||
header_tokens, centers, widths = _header_observation(
|
||||
header_glyphs, page=page, bbox=bbox,
|
||||
)
|
||||
return {
|
||||
'bbox': bbox,
|
||||
'header_tokens': header_tokens,
|
||||
'column_centers': centers,
|
||||
'column_width_ratios': widths,
|
||||
}
|
||||
|
||||
|
||||
def _normalized_bbox(bbox: dict[str, Any], *, page: dict[str, Any]) -> list[float] | None:
|
||||
"""将 MinerU/PDF 表格 bbox 统一为 0..1 坐标。"""
|
||||
try:
|
||||
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
|
||||
width, height = float(page.get('width')), float(page.get('height'))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if width <= 0 or height <= 0 or raw[2] <= raw[0] or raw[3] <= raw[1]:
|
||||
return None
|
||||
if max(raw) <= 1.0:
|
||||
return raw
|
||||
return [raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height]
|
||||
|
||||
|
||||
def _bbox_overlap(left: list[float], right: list[float]) -> float:
|
||||
"""计算两个规范化矩形的 IoU,供选择实际表格。"""
|
||||
x0, y0 = max(left[0], right[0]), max(left[1], right[1])
|
||||
x1, y1 = min(left[2], right[2]), min(left[3], right[3])
|
||||
intersection = max(0.0, x1 - x0) * max(0.0, y1 - y0)
|
||||
union = (left[2] - left[0]) * (left[3] - left[1]) + (right[2] - right[0]) * (right[3] - right[1]) - intersection
|
||||
return intersection / union if union > 0 else 0.0
|
||||
|
||||
|
||||
def _glyph_center_in_bbox(glyph: dict[str, Any], bbox: list[float], *, page: dict[str, Any]) -> bool:
|
||||
"""判断字符中心是否位于真实表格中。"""
|
||||
raw = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else {}
|
||||
try:
|
||||
x = (float(raw.get('x0')) + float(raw.get('x1'))) / 2 / float(page['width'])
|
||||
y = (float(raw.get('y0')) + float(raw.get('y1'))) / 2 / float(page['height'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
return bbox[0] <= x <= bbox[2] and bbox[1] <= y <= bbox[3]
|
||||
|
||||
|
||||
def _header_glyphs(
|
||||
glyphs: list[dict[str, Any]], *, page: dict[str, Any], bbox: list[float],
|
||||
header_bbox: list[float] | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""优先消费管理员标注的表头区域;旧定义缺失时才使用保守顶部区域。"""
|
||||
region = header_bbox or [
|
||||
bbox[0], bbox[1], bbox[2],
|
||||
bbox[1] + max(0.06, (bbox[3] - bbox[1]) * 0.18),
|
||||
]
|
||||
return [
|
||||
item for item in glyphs
|
||||
if _glyph_center_in_bbox(item, region, page=page)
|
||||
]
|
||||
|
||||
|
||||
def _union_relative_regions(regions: list[RelativeRegion]) -> RelativeRegion | None:
|
||||
"""合并多行表头标注区域,冻结为 Matcher 可直接消费的唯一相对坐标框。"""
|
||||
if not regions:
|
||||
return None
|
||||
return RelativeRegion(
|
||||
x0=min(item.x0 for item in regions), y0=min(item.y0 for item in regions),
|
||||
x1=max(item.x1 for item in regions), y1=max(item.y1 for item in regions),
|
||||
)
|
||||
|
||||
|
||||
def _header_observation(
|
||||
glyphs: list[dict[str, Any]], *, page: dict[str, Any], bbox: list[float],
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。"""
|
||||
try:
|
||||
page_width = float(page['width'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return [], [], []
|
||||
spans = [
|
||||
item for item in positioned_token_spans(glyphs, respect_explicit_spaces=False)
|
||||
if _usable_header_token(str(item.get('text') or ''))
|
||||
][:32]
|
||||
tokens = [_normalize_header_token(str(item['text'])) for item in spans]
|
||||
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / page_width, 4) for item in spans]
|
||||
span = max(bbox[2] - bbox[0], 0.0001)
|
||||
widths = [round((float(item['x1']) - float(item['x0'])) / page_width / span, 4) for item in spans]
|
||||
return tokens, centers, widths
|
||||
|
||||
|
||||
def _usable_header_token(token: str) -> bool:
|
||||
"""过滤分隔线、动态值和无意义短 token,仅冻结稳定表头文字。"""
|
||||
normalized = _normalize_header_token(token)
|
||||
if not normalized or not re.search(r'[A-Za-z\u3400-\u9fff]', normalized):
|
||||
return False
|
||||
return not _is_dynamic_token(normalized)
|
||||
|
||||
|
||||
def _find_text_center(layout: dict[str, Any], text: str) -> tuple[float, float] | None:
|
||||
"""在页级字符中定位静态标签中心;仅返回归一化坐标。"""
|
||||
expected = ''.join(text.casefold().split())
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
glyph_pages = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
for key, page in pages.items():
|
||||
glyphs = glyph_pages.get(key) or glyph_pages.get(str(key)) or []
|
||||
if not isinstance(page, dict) or not isinstance(glyphs, list):
|
||||
continue
|
||||
ordered = sorted((item for item in glyphs if isinstance(item.get('bbox'), dict)), key=lambda item: (item['bbox'].get('y0', 0), item['bbox'].get('x0', 0)))
|
||||
joined = ''.join(str(item.get('text') or '') for item in ordered).casefold()
|
||||
start = ''.join(joined.split()).find(expected)
|
||||
if start < 0:
|
||||
continue
|
||||
# Character evidence is normally one glyph per character; find the matching
|
||||
# compact-text span without persisting any document text.
|
||||
compact_index = 0
|
||||
matched: list[dict[str, Any]] = []
|
||||
for item in ordered:
|
||||
chars = ''.join(str(item.get('text') or '').casefold().split())
|
||||
if not chars:
|
||||
continue
|
||||
if start <= compact_index < start + len(expected):
|
||||
matched.append(item)
|
||||
compact_index += len(chars)
|
||||
if matched:
|
||||
try:
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
xs = [(float(item['bbox']['x0']) + float(item['bbox']['x1'])) / 2 / width for item in matched]
|
||||
ys = [(float(item['bbox']['y0']) + float(item['bbox']['y1'])) / 2 / height for item in matched]
|
||||
return statistics.median(xs), statistics.median(ys)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _glyph_union_bbox(glyphs: Any, *, page: dict[str, Any]) -> list[float] | None:
|
||||
"""在 Provider 未给表框时由实际表内字符求并集,绝不回退模板标注框。"""
|
||||
if not isinstance(glyphs, list):
|
||||
return None
|
||||
try:
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
boxes = [item['bbox'] for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)]
|
||||
if not boxes:
|
||||
return None
|
||||
return [
|
||||
min(float(box['x0']) for box in boxes) / width,
|
||||
min(float(box['y0']) for box in boxes) / height,
|
||||
max(float(box['x1']) for box in boxes) / width,
|
||||
max(float(box['y1']) for box in boxes) / height,
|
||||
]
|
||||
except (KeyError, TypeError, ValueError, ZeroDivisionError):
|
||||
return None
|
||||
|
||||
|
||||
def _build_evidence_quality(
|
||||
*,
|
||||
sample_layouts: list[dict[str, Any]],
|
||||
table_patterns: list[dict[str, Any]],
|
||||
source_sample_count: int,
|
||||
) -> dict[str, Any]:
|
||||
"""输出证据质量摘要,供发布门禁与审计使用。"""
|
||||
headers_with_tokens = sum(1 for item in table_patterns if item.get('header_tokens'))
|
||||
pages_present = sum(
|
||||
1 for layout in sample_layouts
|
||||
if isinstance((layout.get('coordinate_evidence') or {}).get('pages'), dict)
|
||||
and (layout.get('coordinate_evidence') or {}).get('pages')
|
||||
)
|
||||
return {
|
||||
'source_sample_count': int(source_sample_count),
|
||||
'layouts_with_pages': pages_present,
|
||||
'tables_with_header_tokens': headers_with_tokens,
|
||||
'header_token_coverage': (
|
||||
round(headers_with_tokens / max(1, len(table_patterns)), 4) if table_patterns else 0.0
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _read_region_text(layout: dict[str, Any], region: RelativeRegion) -> str:
|
||||
"""从冻结 layout 首页坐标证据读取区域内文字;失败返回空串。"""
|
||||
try:
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page = pages.get('1') or pages.get(1)
|
||||
if not isinstance(page, dict):
|
||||
return ''
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1) or []
|
||||
if not glyphs:
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
glyphs = list(glyphs) + table_glyphs
|
||||
if not isinstance(glyphs, list) or not glyphs:
|
||||
return ''
|
||||
return read_coordinate_region_text(
|
||||
glyphs=glyphs,
|
||||
page=page,
|
||||
region={'x0': region.x0, 'y0': region.y0, 'x1': region.x1, 'y1': region.y1},
|
||||
)
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def _normalize_header_token(text: str) -> str:
|
||||
"""规范化表头 token:折叠空白并截断。"""
|
||||
return ' '.join(str(text or '').split())[:80]
|
||||
|
||||
|
||||
def _split_header_tokens(text: str) -> list[str]:
|
||||
"""将表头区域整体文字按空白拆成候选 token。"""
|
||||
return [_normalize_header_token(part) for part in re.split(r'[\s|/]+', text) if part.strip()]
|
||||
|
||||
|
||||
def _is_dynamic_token(token: str) -> bool:
|
||||
"""判断 token 是否像 PO/日期/数量等动态值。"""
|
||||
compact = token.strip()
|
||||
if not compact or len(compact) <= 1:
|
||||
return True
|
||||
return any(pattern.search(compact) for pattern in _DYNAMIC_TOKEN_PATTERNS)
|
||||
|
||||
|
||||
def _stable_tokens(samples: list[list[str]]) -> list[str]:
|
||||
"""仅保留在多数样本中出现的 token,排除单样本噪声。"""
|
||||
if not samples:
|
||||
return []
|
||||
threshold = max(1, (len(samples) + 1) // 2)
|
||||
counts: dict[str, int] = {}
|
||||
for tokens in samples:
|
||||
for token in dict.fromkeys(tokens):
|
||||
counts[token] = counts.get(token, 0) + 1
|
||||
stable = [token for token, count in counts.items() if count >= threshold]
|
||||
# 保持首次样本中的相对顺序
|
||||
order_index = {token: index for index, token in enumerate(samples[0])}
|
||||
return sorted(stable, key=lambda item: order_index.get(item, 10_000))
|
||||
|
||||
|
||||
def _median_vector(vectors: list[list[float]]) -> list[float] | None:
|
||||
"""计算等长向量各维中位数。"""
|
||||
if not vectors:
|
||||
return None
|
||||
width = len(vectors[0])
|
||||
return [
|
||||
round(statistics.median(row[index] for row in vectors if len(row) == width), 4)
|
||||
for index in range(width)
|
||||
]
|
||||
|
||||
|
||||
def _median_columns(samples: list[list[float]]) -> list[float]:
|
||||
"""对列中心/列宽多样本取中位数;列数取众数。"""
|
||||
if not samples:
|
||||
return []
|
||||
lengths = [len(item) for item in samples]
|
||||
target = max(set(lengths), key=lengths.count)
|
||||
aligned = [item for item in samples if len(item) == target]
|
||||
if not aligned:
|
||||
return list(samples[0])
|
||||
return [
|
||||
round(statistics.median(row[index] for row in aligned), 4)
|
||||
for index in range(target)
|
||||
]
|
||||
@@ -37,6 +37,53 @@ def _enabled() -> bool:
|
||||
return bool(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED', False))
|
||||
|
||||
|
||||
def _try_build_xfa_layout_snapshot(
|
||||
*,
|
||||
content: bytes,
|
||||
document_id: int | None = None,
|
||||
content_hash: str | None = None,
|
||||
timings: dict[str, int] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
在 MinerU/PDFium 表格路径前探测 XFA;supported hybrid 直接返回 XFA capability 快照。
|
||||
|
||||
核心逻辑:仅对 PDF 字节调用 xfa_analysis;xfa_hybrid 成功时跳过 MinerU,不要求 table ready。
|
||||
|
||||
Args:
|
||||
content: PDF 原始字节。
|
||||
document_id/content_hash: 文档身份(写入 capability 摘要)。
|
||||
timings: 可选运维耗时字典。
|
||||
|
||||
Returns:
|
||||
XFA 快照;非 XFA 或 plain/acroform 时返回 None 以继续常规 layout 路径。
|
||||
"""
|
||||
if not content or not content.startswith(b'%PDF'):
|
||||
return None
|
||||
started = perf_counter()
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import default_xfa_resource_limits
|
||||
|
||||
limits = default_xfa_resource_limits()
|
||||
outcome = analyze_xfa_pdf(content, limits=limits)
|
||||
if timings is not None:
|
||||
timings['xfa_probe_ms'] = round((perf_counter() - started) * 1000)
|
||||
packet_result = outcome.packet_result
|
||||
if packet_result is None:
|
||||
return None
|
||||
# plain_pdf / acroform:不拦截,继续 MinerU 表格路径。
|
||||
if packet_result.document_kind in {'plain_pdf', 'acroform'}:
|
||||
return None
|
||||
snapshot = dict(outcome.snapshot)
|
||||
if document_id:
|
||||
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
|
||||
capability['document_id'] = int(document_id)
|
||||
if content_hash:
|
||||
capability['content_hash'] = str(content_hash)
|
||||
snapshot['xfa_capability'] = capability
|
||||
snapshot['capability'] = capability
|
||||
return snapshot
|
||||
|
||||
|
||||
def mineru_layout_capture_enabled(filename: str) -> bool:
|
||||
"""判断文件是否需要读取二进制并调用 MinerU,供上传链避免默认关闭时重复对象存储 I/O。"""
|
||||
return _enabled() and Path(str(filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS
|
||||
@@ -54,8 +101,8 @@ def build_mineru_table_snapshot(
|
||||
"""
|
||||
为一个受支持附件生成紧凑 MinerU 文本与表格快照。
|
||||
|
||||
核心逻辑:文字型 PDF 先用本地坐标和严格表头门槛恢复表格,成功即跳过 MinerU;
|
||||
本地证据不足时再调用 MinerU。两条路径都冻结相同的页面坐标契约。
|
||||
核心逻辑:PDFium 仅在 MinerU 前轻量预读原生字符;表格结构始终优先调用 MinerU。
|
||||
MinerU 空表、配置缺失、调用失败或响应非法时,才允许严格原生文字回退。
|
||||
|
||||
Args:
|
||||
filename: 原附件名,仅用于扩展名和 MinerU multipart,不进入返回错误详情。
|
||||
@@ -68,6 +115,15 @@ def build_mineru_table_snapshot(
|
||||
extension = Path(str(filename or '')).suffix.lower()
|
||||
if not mineru_layout_capture_enabled(filename) or not content:
|
||||
return None
|
||||
if extension == '.pdf':
|
||||
xfa_snapshot = _try_build_xfa_layout_snapshot(
|
||||
content=content,
|
||||
document_id=document_id,
|
||||
content_hash=content_hash,
|
||||
timings=timings,
|
||||
)
|
||||
if xfa_snapshot is not None:
|
||||
return xfa_snapshot
|
||||
native_pages: list[Any] | None = None
|
||||
if extension == '.pdf' and document_id and content_hash:
|
||||
try:
|
||||
@@ -77,24 +133,17 @@ def build_mineru_table_snapshot(
|
||||
native_pages = extract_native_pdf_pages(content, render_images=False)
|
||||
if timings is not None:
|
||||
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
|
||||
fast_snapshot = _native_pdf_fast_snapshot(
|
||||
content=content,
|
||||
document_id=int(document_id),
|
||||
content_hash=str(content_hash),
|
||||
native_pages=native_pages,
|
||||
timings=timings,
|
||||
)
|
||||
if fast_snapshot is not None:
|
||||
if timings is not None:
|
||||
timings['layout_fast_path'] = 1
|
||||
return fast_snapshot
|
||||
except Exception:
|
||||
native_pages = None
|
||||
if native_pages is not None:
|
||||
# 本地文字门槛未命中时,后续 MinerU 增强路径需要完整页面图,按需重新提取。
|
||||
native_pages = None
|
||||
base_url = str(current_app.config.get('SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL') or '').strip()
|
||||
if not base_url:
|
||||
fallback = _native_pdf_fallback_snapshot(
|
||||
content=content, document_id=document_id, content_hash=content_hash,
|
||||
native_pages=native_pages, timings=timings,
|
||||
provider_issue='mineru_base_url_missing',
|
||||
)
|
||||
if fallback is not None:
|
||||
return fallback
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'mineru',
|
||||
@@ -124,6 +173,13 @@ def build_mineru_table_snapshot(
|
||||
if timings is not None:
|
||||
timings['mineru_result_parse_ms'] = round((perf_counter() - result_parse_started) * 1000)
|
||||
except AppError as exc:
|
||||
fallback = _native_pdf_fallback_snapshot(
|
||||
content=content, document_id=document_id, content_hash=content_hash,
|
||||
native_pages=native_pages, timings=timings,
|
||||
provider_issue=str(exc.code),
|
||||
)
|
||||
if fallback is not None:
|
||||
return fallback
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'mineru',
|
||||
@@ -133,6 +189,13 @@ def build_mineru_table_snapshot(
|
||||
'issues': [str(exc.code)],
|
||||
}
|
||||
except (TypeError, ValueError):
|
||||
fallback = _native_pdf_fallback_snapshot(
|
||||
content=content, document_id=document_id, content_hash=content_hash,
|
||||
native_pages=native_pages, timings=timings,
|
||||
provider_issue='SHIPPING_NOTICE.LAYOUT_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
if fallback is not None:
|
||||
return fallback
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'mineru',
|
||||
@@ -152,6 +215,7 @@ def build_mineru_table_snapshot(
|
||||
total_html_chars = 0
|
||||
total_text_chars = 0
|
||||
issues = list(candidate.capability.issues)
|
||||
mineru_has_tables = any(page.tables for page in candidate.pages)
|
||||
for page in candidate.pages:
|
||||
for block in sorted(
|
||||
page.text_blocks,
|
||||
@@ -209,16 +273,18 @@ def build_mineru_table_snapshot(
|
||||
extract_native_pdf_pages,
|
||||
)
|
||||
|
||||
if native_pages is None:
|
||||
native_started = perf_counter()
|
||||
native_pages = extract_native_pdf_pages(content)
|
||||
if timings is not None:
|
||||
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
|
||||
# MinerU 成功后进入坐标增强链;此时按需补齐页面图,供严格 OpenCV/OCR 门禁使用。
|
||||
# 前置轻量预读只缓存字符,不得因为已有无图页面而跳过必要的增强证据。
|
||||
native_started = perf_counter()
|
||||
native_pages = extract_native_pdf_pages(content)
|
||||
if timings is not None:
|
||||
timings['native_pdf_extract_ms'] = round((perf_counter() - native_started) * 1000)
|
||||
|
||||
layout_source_candidate = candidate
|
||||
# MinerU occasionally returns only text blocks for unbordered purchase-order lines.
|
||||
# Restrict the fallback to an otherwise empty table result so normal templates retain
|
||||
# the provider's original table structure unchanged.
|
||||
if not tables:
|
||||
if not tables and not mineru_has_tables:
|
||||
fallback_tables = build_native_pdf_text_table_fallbacks(
|
||||
content,
|
||||
native_pages=native_pages,
|
||||
@@ -226,15 +292,26 @@ def build_mineru_table_snapshot(
|
||||
if fallback_tables:
|
||||
tables.extend(fallback_tables)
|
||||
snapshot['tables'] = tables
|
||||
snapshot['issues'] = sorted(set(
|
||||
issue for issue in snapshot['issues']
|
||||
if issue not in {'mineru_table_structure_missing', 'mineru_cell_coordinates_missing'}
|
||||
) | {'native_pdf_text_table_fallback_used'})
|
||||
layout_source_candidate = _native_pdf_candidate_from_tables(
|
||||
native_pages=native_pages,
|
||||
tables=fallback_tables,
|
||||
)
|
||||
snapshot.update({
|
||||
'provider': 'pdfium',
|
||||
'provider_version': 'native-text-v1',
|
||||
'backend': 'native_pdf',
|
||||
'capability': layout_source_candidate.capability.model_dump(mode='json'),
|
||||
})
|
||||
snapshot['issues'] = sorted(set(snapshot['issues']) | {
|
||||
'mineru_provider_fallback_used',
|
||||
'mineru_table_structure_missing',
|
||||
'native_pdf_text_table_fallback_used',
|
||||
})
|
||||
|
||||
layout_started = perf_counter()
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=int(document_id), content_hash=str(content_hash),
|
||||
content=content, mineru=candidate, native_pages=native_pages,
|
||||
content=content, mineru=layout_source_candidate, native_pages=native_pages,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
|
||||
@@ -260,37 +337,89 @@ def build_mineru_table_snapshot(
|
||||
return snapshot
|
||||
|
||||
|
||||
def _native_pdf_fast_snapshot(
|
||||
*, content: bytes, document_id: int, content_hash: str,
|
||||
native_pages: list[Any], timings: dict[str, int] | None,
|
||||
def _native_pdf_fallback_snapshot(
|
||||
*, content: bytes, document_id: int | None, content_hash: str | None,
|
||||
native_pages: list[Any] | None, timings: dict[str, int] | None,
|
||||
provider_issue: str,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
用严格原生文字表格证据生成可立即消费的布局快照。
|
||||
在 MinerU 不可用时,用严格原生文字表格证据生成降级布局快照。
|
||||
|
||||
AI/调用方触发时机:版面 Job 收到文字型 PDF 时先调用;只有表头、列边界和
|
||||
数据行同时成立才返回快照,否则返回 None 继续 MinerU,禁止宽松猜测表格。
|
||||
AI/调用方触发时机:仅在 MinerU 配置缺失、调用失败或响应非法后调用;MinerU
|
||||
正常返回时不得调用本函数替换 Provider 表格。只有表头、列边界和数据行同时成立
|
||||
才返回快照,否则返回 None 并保留原 Provider 失败,禁止宽松猜测表格。
|
||||
|
||||
Args:
|
||||
content: 当前 PDF 字节,仅传给既有布局构建器,不持久化。
|
||||
document_id/content_hash: 当前不可变 Document 身份。
|
||||
native_pages: 已完成一次 PDFium 提取的页面,后续阶段必须复用。
|
||||
document_id/content_hash: 当前不可变 Document 身份;缺失时禁止降级。
|
||||
native_pages: MinerU 调用前已轻量预读的 PDFium 页面;缺失时禁止降级。
|
||||
timings: 可选运维阶段耗时,不进入快照。
|
||||
provider_issue: 触发降级的 MinerU 稳定问题码。
|
||||
|
||||
Returns:
|
||||
证据充分时返回 ready 快照;无法证明业务表格时返回 None。
|
||||
证据充分时返回带 Provider 失败原因的 ready 降级快照;否则返回 None。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
build_native_pdf_layout_candidate,
|
||||
build_native_pdf_text_table_fallbacks,
|
||||
)
|
||||
if not document_id or not content_hash or not native_pages:
|
||||
return None
|
||||
try:
|
||||
from app.services.shipping_notice.document_layout.native_pdf import (
|
||||
build_native_pdf_layout_candidate,
|
||||
build_native_pdf_text_table_fallbacks,
|
||||
)
|
||||
|
||||
fallback_started = perf_counter()
|
||||
tables = build_native_pdf_text_table_fallbacks(content, native_pages=native_pages)
|
||||
if timings is not None:
|
||||
timings['native_table_detect_ms'] = round((perf_counter() - fallback_started) * 1000)
|
||||
if not tables:
|
||||
fallback_started = perf_counter()
|
||||
tables = build_native_pdf_text_table_fallbacks(content, native_pages=native_pages)
|
||||
if timings is not None:
|
||||
timings['native_table_detect_ms'] = round((perf_counter() - fallback_started) * 1000)
|
||||
if not tables:
|
||||
return None
|
||||
|
||||
candidate = _native_pdf_candidate_from_tables(
|
||||
native_pages=native_pages,
|
||||
tables=tables,
|
||||
)
|
||||
layout_started = perf_counter()
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=int(document_id), content_hash=str(content_hash),
|
||||
content=content, mineru=candidate, native_pages=native_pages,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
|
||||
layout_payload_preview = layout.model_dump(mode='json')
|
||||
capability = _capability_with_layout_cells(
|
||||
candidate.capability.model_dump(mode='json'),
|
||||
layout_payload=layout_payload_preview,
|
||||
)
|
||||
evidence_started = perf_counter()
|
||||
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
|
||||
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
|
||||
evidence = _table_coordinate_evidence(
|
||||
pages=native_pages, tables=tables, include_page_glyphs=False,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'pdfium', 'provider_version': 'native-text-v1', 'backend': 'native_pdf',
|
||||
'status': 'ready', 'text_blocks': [], 'tables': tables,
|
||||
'capability': capability,
|
||||
'layout_candidate': layout_payload_preview,
|
||||
'coordinate_evidence': evidence,
|
||||
'issues': sorted({
|
||||
'mineru_provider_fallback_used',
|
||||
'native_pdf_text_table_fallback_used',
|
||||
str(provider_issue or 'mineru_provider_failed'),
|
||||
}),
|
||||
}
|
||||
except Exception:
|
||||
# 降级链不是新的业务真相来源;自身异常时保留 MinerU 原始失败,禁止反向覆盖。
|
||||
return None
|
||||
|
||||
|
||||
def _native_pdf_candidate_from_tables(
|
||||
*, native_pages: list[Any], tables: list[dict[str, Any]],
|
||||
) -> MinerUParseCandidate:
|
||||
"""把严格 PDFium 回退表转换为统一布局候选;仅供 MinerU 空表或失败降级使用。"""
|
||||
page_candidates = []
|
||||
for page in native_pages:
|
||||
page_tables = []
|
||||
@@ -308,7 +437,7 @@ def _native_pdf_fast_snapshot(
|
||||
page_no=int(page.page_no), width=float(page.width), height=float(page.height),
|
||||
text_blocks=[], tables=page_tables,
|
||||
))
|
||||
candidate = MinerUParseCandidate(
|
||||
return MinerUParseCandidate(
|
||||
provider_version='pdfium-native-text-v1', backend='native_pdf', pages=page_candidates,
|
||||
capability=MinerUCapabilityReport(
|
||||
provider_version='pdfium-native-text-v1', backend='native_pdf',
|
||||
@@ -322,35 +451,6 @@ def _native_pdf_fast_snapshot(
|
||||
issues=['native_pdf_text_table_fallback_used'],
|
||||
),
|
||||
)
|
||||
layout_started = perf_counter()
|
||||
layout = build_native_pdf_layout_candidate(
|
||||
document_id=document_id, content_hash=content_hash,
|
||||
content=content, mineru=candidate, native_pages=native_pages,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['native_layout_build_ms'] = round((perf_counter() - layout_started) * 1000)
|
||||
layout_payload_preview = layout.model_dump(mode='json')
|
||||
capability = _capability_with_layout_cells(
|
||||
candidate.capability.model_dump(mode='json'),
|
||||
layout_payload=layout_payload_preview,
|
||||
)
|
||||
evidence_started = perf_counter()
|
||||
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
|
||||
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
|
||||
evidence = _table_coordinate_evidence(
|
||||
pages=native_pages, tables=tables, include_page_glyphs=False,
|
||||
)
|
||||
if timings is not None:
|
||||
timings['coordinate_evidence_ms'] = round((perf_counter() - evidence_started) * 1000)
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'pdfium', 'provider_version': 'native-text-v1', 'backend': 'native_pdf',
|
||||
'status': 'ready', 'text_blocks': [], 'tables': tables,
|
||||
'capability': capability,
|
||||
'layout_candidate': layout_payload_preview,
|
||||
'coordinate_evidence': evidence,
|
||||
'issues': ['native_pdf_text_table_fallback_used'],
|
||||
}
|
||||
|
||||
|
||||
def _table_coordinate_evidence(
|
||||
@@ -505,7 +605,7 @@ def attach_mineru_layout_snapshots(result: Any, *, root_asset_bytes: bytes | Non
|
||||
and mineru_layout_capture_enabled(str(item.get('filename') or ''))
|
||||
]
|
||||
max_documents = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 4,
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE', 10,
|
||||
)), 0)
|
||||
concurrency = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY', 2,
|
||||
|
||||
@@ -32,12 +32,13 @@ class TextCellAlignmentModel(BaseModel):
|
||||
|
||||
|
||||
class PositionedCharacter(TextCellAlignmentModel):
|
||||
"""保存 PDF 原生文本层的单个可见字符、页面坐标与视觉行身份。"""
|
||||
"""保存 PDF 原生可见字符、坐标及其前置文本流边界;零 bbox 空白不伪造成 glyph。"""
|
||||
|
||||
text: str = Field(min_length=1, max_length=8)
|
||||
bbox: LayoutBBox
|
||||
source_index: int | None = Field(default=None, ge=0)
|
||||
line_id: str | None = None
|
||||
boundary_before: Literal['none', 'space', 'line_break'] = 'none'
|
||||
|
||||
|
||||
class TextAlignedCell(TextCellAlignmentModel):
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_acroform.py
|
||||
|
||||
用途:读取 AcroForm 字段值并生成与 datasets 叶子节点的对账候选。
|
||||
依赖:pypdf、xfa_dataset.XfaDatasetAnalysis。
|
||||
逻辑:由 xfa_analysis / xfa_validation 调用;按短名聚合多实例值供行对齐对账;
|
||||
此处只做候选与分组,不因 display formatting 差异判失败。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import unicodedata
|
||||
from dataclasses import dataclass
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from pypdf import PdfReader
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import hash_data_path
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetAnalysis, mask_value_for_dto
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaAcroformField:
|
||||
"""单个 AcroForm 字段摘要。"""
|
||||
|
||||
qualified_name: str
|
||||
short_name: str
|
||||
value: str
|
||||
value_masked: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaReconciliationCandidate:
|
||||
"""datasets 叶子与 AcroForm 字段的对账候选。"""
|
||||
|
||||
data_path_hash: str
|
||||
dataset_value_masked: str
|
||||
acroform_field_name: str | None
|
||||
acroform_value_masked: str | None
|
||||
match_hint: str
|
||||
|
||||
|
||||
def _local_tail(name: str) -> str:
|
||||
"""
|
||||
取 SOM 路径最后一段业务短名(忽略实例下标)。
|
||||
|
||||
核心逻辑:`form[0].ITEMS[1].MENGE[0]` → `MENGE`;数字段与空段丢弃,
|
||||
便于按短名聚合多行 Widget 实例。
|
||||
"""
|
||||
text = str(name or '').strip()
|
||||
if not text:
|
||||
return ''
|
||||
parts = [part for part in re.split(r'[\.\[\]]+', text) if part and not part.isdigit()]
|
||||
return parts[-1] if parts else text
|
||||
|
||||
|
||||
def _instance_sort_key(qualified_name: str) -> tuple[int, ...]:
|
||||
"""
|
||||
从 SOM 限定名提取实例下标序列,用于多行 Widget 与明细行对齐排序。
|
||||
|
||||
Args:
|
||||
qualified_name: 如 `form[0].Page1[0].MENGE[2]`。
|
||||
|
||||
Returns:
|
||||
下标元组;无下标时返回 (0,)。
|
||||
"""
|
||||
matches = re.findall(r'\[(\d+)\]', str(qualified_name or ''))
|
||||
if not matches:
|
||||
return (0,)
|
||||
return tuple(int(item) for item in matches)
|
||||
|
||||
|
||||
def _normalize_key(value: str) -> str:
|
||||
"""用于候选匹配的规范化键(大小写/空白/标点无关)。"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).strip().lower()
|
||||
return re.sub(r'[^a-z0-9]+', '', text)
|
||||
|
||||
|
||||
def read_acroform_fields(pdf_bytes: bytes) -> list[XfaAcroformField]:
|
||||
"""
|
||||
读取 PDF AcroForm 字段值。
|
||||
|
||||
核心逻辑:通过 pypdf get_fields 读取 `/V` 展示值;不执行任何脚本。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 原始 PDF 字节。
|
||||
|
||||
Returns:
|
||||
AcroForm 字段摘要列表;无 AcroForm 时返回空列表。
|
||||
"""
|
||||
try:
|
||||
reader = PdfReader(BytesIO(pdf_bytes), strict=False)
|
||||
raw_fields = reader.get_fields() or {}
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
result: list[XfaAcroformField] = []
|
||||
for qualified_name, field_obj in raw_fields.items():
|
||||
if not isinstance(field_obj, dict):
|
||||
continue
|
||||
value = field_obj.get('/V')
|
||||
if value is None:
|
||||
continue
|
||||
text = str(getattr(value, 'name', value) or value).strip()
|
||||
if not text:
|
||||
continue
|
||||
short_name = _local_tail(str(qualified_name))
|
||||
result.append(XfaAcroformField(
|
||||
qualified_name=str(qualified_name),
|
||||
short_name=short_name,
|
||||
value=text,
|
||||
value_masked=mask_value_for_dto(text),
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def build_reconciliation_candidates(
|
||||
*,
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
acroform_fields: list[XfaAcroformField],
|
||||
) -> list[XfaReconciliationCandidate]:
|
||||
"""
|
||||
为 datasets 叶子生成 AcroForm 对账候选。
|
||||
|
||||
核心逻辑:按 localName / 路径尾段做弱匹配;不在此阶段因 display formatting 差异判失败。
|
||||
|
||||
Args:
|
||||
dataset_analysis: datasets 结构分析。
|
||||
acroform_fields: AcroForm 字段列表。
|
||||
|
||||
Returns:
|
||||
对账候选列表。
|
||||
"""
|
||||
by_short_name: dict[str, list[XfaAcroformField]] = {}
|
||||
by_normalized: dict[str, list[XfaAcroformField]] = {}
|
||||
ordered = sorted(acroform_fields, key=lambda item: _instance_sort_key(item.qualified_name))
|
||||
for item in ordered:
|
||||
by_short_name.setdefault(item.short_name.upper(), []).append(item)
|
||||
by_normalized.setdefault(_normalize_key(item.short_name), []).append(item)
|
||||
|
||||
candidates: list[XfaReconciliationCandidate] = []
|
||||
for data_path, raw_value in dataset_analysis.leaf_values_by_path.items():
|
||||
local_name = data_path.rsplit('/', 1)[-1]
|
||||
dataset_masked = mask_value_for_dto(raw_value)
|
||||
matched: XfaAcroformField | None = None
|
||||
match_hint = 'unmatched'
|
||||
|
||||
exact = by_short_name.get(local_name.upper()) or []
|
||||
if len(exact) == 1:
|
||||
matched = exact[0]
|
||||
match_hint = 'local_name_exact'
|
||||
elif len(exact) > 1:
|
||||
matched = exact[0]
|
||||
match_hint = 'local_name_ambiguous'
|
||||
else:
|
||||
normalized = _normalize_key(local_name)
|
||||
fuzzy = by_normalized.get(normalized) or []
|
||||
if len(fuzzy) == 1:
|
||||
matched = fuzzy[0]
|
||||
match_hint = 'normalized_exact'
|
||||
elif len(fuzzy) > 1:
|
||||
matched = fuzzy[0]
|
||||
match_hint = 'normalized_ambiguous'
|
||||
|
||||
candidates.append(XfaReconciliationCandidate(
|
||||
data_path_hash=hash_data_path(data_path),
|
||||
dataset_value_masked=dataset_masked,
|
||||
acroform_field_name=matched.qualified_name if matched else None,
|
||||
acroform_value_masked=matched.value_masked if matched else None,
|
||||
match_hint=match_hint,
|
||||
))
|
||||
return candidates
|
||||
|
||||
|
||||
def group_acroform_values_by_short_name(fields: list[XfaAcroformField]) -> dict[str, list[str]]:
|
||||
"""
|
||||
按短名聚合 AcroForm 多实例值(SOM 下标排序)。
|
||||
|
||||
核心逻辑:同名多 Widget 全部保留,供明细行一一对账;禁止只取首个。
|
||||
|
||||
Args:
|
||||
fields: AcroForm 字段列表。
|
||||
|
||||
Returns:
|
||||
short_name.upper() → 按实例顺序排列的原始展示值列表。
|
||||
"""
|
||||
buckets: dict[str, list[XfaAcroformField]] = {}
|
||||
for item in fields:
|
||||
key = str(item.short_name or '').strip().upper()
|
||||
if not key:
|
||||
continue
|
||||
buckets.setdefault(key, []).append(item)
|
||||
result: dict[str, list[str]] = {}
|
||||
for key, items in buckets.items():
|
||||
ordered = sorted(items, key=lambda field: _instance_sort_key(field.qualified_name))
|
||||
result[key] = [field.value for field in ordered]
|
||||
return result
|
||||
|
||||
|
||||
def serialize_acroform_fields(fields: list[XfaAcroformField]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
序列化 AcroForm 字段供安全 DTO 返回。
|
||||
|
||||
Args:
|
||||
fields: AcroForm 字段列表。
|
||||
|
||||
Returns:
|
||||
不含原始 PDF 或完整路径明文的摘要列表。
|
||||
"""
|
||||
return [
|
||||
{
|
||||
'qualified_name_tail': item.short_name,
|
||||
'value_masked': item.value_masked,
|
||||
}
|
||||
for item in fields
|
||||
]
|
||||
@@ -0,0 +1,437 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_analysis.py
|
||||
|
||||
用途:编排 XFA packet 读取、datasets 解析、签名计算与布局快照/持久化。
|
||||
依赖:xfa_packets、xfa_dataset、xfa_signature、xfa_acroform、xfa_contract、
|
||||
ShippingXfaStructureAnalysis 模型。
|
||||
逻辑:由 runtime 与 shipping_document_layout Job 调用;成功时写入结构分析记录并返回
|
||||
不含 XML/PDF 正文的 capability 快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingXfaStructureAnalysis
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import (
|
||||
build_reconciliation_candidates,
|
||||
read_acroform_fields,
|
||||
serialize_acroform_fields,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_CONTRACT_VERSION,
|
||||
XFA_PARSER_IDENTITY,
|
||||
hash_data_path,
|
||||
sanitize_xfa_dto,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import (
|
||||
XfaDatasetAnalysis,
|
||||
XfaDatasetParseError,
|
||||
parse_xfa_datasets,
|
||||
serialize_tree_node,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_packets import (
|
||||
XfaPacketError,
|
||||
XfaPacketReadResult,
|
||||
is_deterministic_xfa_error,
|
||||
read_xfa_packets,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_signature import build_signature_summary
|
||||
from app.services.shipping_notice.document_layout.runtime import LAYOUT_SNAPSHOT_VERSION
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaAnalysisOutcome:
|
||||
"""XFA 结构分析完整结果。"""
|
||||
|
||||
snapshot: dict[str, Any]
|
||||
packet_result: XfaPacketReadResult | None = None
|
||||
dataset_analysis: XfaDatasetAnalysis | None = None
|
||||
error_code: str | None = None
|
||||
route_reason: str | None = None
|
||||
deterministic: bool = False
|
||||
analysis_record: ShippingXfaStructureAnalysis | None = None
|
||||
issues: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def analyze_xfa_pdf(
|
||||
pdf_bytes: bytes,
|
||||
*,
|
||||
limits: dict[str, int] | None = None,
|
||||
) -> XfaAnalysisOutcome:
|
||||
"""
|
||||
对 PDF 执行完整 XFA 结构分析(纯函数,不写数据库)。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 原始 PDF 字节。
|
||||
limits: 可选资源上限。
|
||||
|
||||
Returns:
|
||||
XfaAnalysisOutcome:含 layout 快照或结构化失败码。
|
||||
"""
|
||||
issues: list[str] = []
|
||||
try:
|
||||
packet_result = read_xfa_packets(pdf_bytes, limits=limits)
|
||||
except XfaPacketError as exc:
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=_failed_snapshot(
|
||||
document_kind='unsupported',
|
||||
error_code=exc.error_code,
|
||||
route_reason=exc.route_reason,
|
||||
issues=[exc.route_reason],
|
||||
),
|
||||
error_code=exc.error_code,
|
||||
route_reason=exc.route_reason,
|
||||
deterministic=is_deterministic_xfa_error(exc.error_code),
|
||||
issues=[exc.route_reason],
|
||||
)
|
||||
|
||||
document_kind = packet_result.document_kind
|
||||
if packet_result.error_code and not packet_result.supported:
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=_failed_snapshot(
|
||||
document_kind=document_kind,
|
||||
error_code=packet_result.error_code,
|
||||
route_reason=packet_result.route_reason or 'xfa_unsupported_document',
|
||||
issues=[packet_result.route_reason or packet_result.error_code],
|
||||
packet_result=packet_result,
|
||||
),
|
||||
packet_result=packet_result,
|
||||
error_code=packet_result.error_code,
|
||||
route_reason=packet_result.route_reason,
|
||||
deterministic=is_deterministic_xfa_error(packet_result.error_code),
|
||||
issues=[packet_result.route_reason or packet_result.error_code],
|
||||
)
|
||||
|
||||
if not packet_result.supported:
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=_unsupported_snapshot(packet_result),
|
||||
packet_result=packet_result,
|
||||
error_code='XFA_UNSUPPORTED_DOCUMENT',
|
||||
route_reason='xfa_unsupported_document',
|
||||
deterministic=True,
|
||||
issues=['xfa_unsupported_document'],
|
||||
)
|
||||
|
||||
datasets_bytes = packet_result.packet_bytes_by_name.get('datasets')
|
||||
if not datasets_bytes:
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=_failed_snapshot(
|
||||
document_kind=document_kind,
|
||||
error_code='XFA_DATASET_MISSING',
|
||||
route_reason='xfa_dataset_missing',
|
||||
issues=['xfa_dataset_missing'],
|
||||
packet_result=packet_result,
|
||||
),
|
||||
packet_result=packet_result,
|
||||
error_code='XFA_DATASET_MISSING',
|
||||
route_reason='xfa_dataset_missing',
|
||||
deterministic=True,
|
||||
issues=['xfa_dataset_missing'],
|
||||
)
|
||||
|
||||
try:
|
||||
dataset_analysis = parse_xfa_datasets(datasets_bytes, limits=limits)
|
||||
except XfaDatasetParseError as exc:
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=_failed_snapshot(
|
||||
document_kind=document_kind,
|
||||
error_code=exc.error_code,
|
||||
route_reason=exc.route_reason,
|
||||
issues=[exc.route_reason],
|
||||
packet_result=packet_result,
|
||||
),
|
||||
packet_result=packet_result,
|
||||
error_code=exc.error_code,
|
||||
route_reason=exc.route_reason,
|
||||
deterministic=is_deterministic_xfa_error(exc.error_code),
|
||||
issues=[exc.route_reason],
|
||||
)
|
||||
|
||||
template_bytes = packet_result.packet_bytes_by_name.get('template')
|
||||
signatures = build_signature_summary(
|
||||
template_bytes=template_bytes,
|
||||
dataset_nodes=dataset_analysis.nodes,
|
||||
)
|
||||
acroform_fields = read_acroform_fields(pdf_bytes)
|
||||
reconciliation = build_reconciliation_candidates(
|
||||
dataset_analysis=dataset_analysis,
|
||||
acroform_fields=acroform_fields,
|
||||
)
|
||||
packet_checksums = {item.name: item.checksum for item in packet_result.packets}
|
||||
capability = {
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'contract_version': XFA_CONTRACT_VERSION,
|
||||
'document_kind': document_kind,
|
||||
'structure_analysis_ready': True,
|
||||
'xfa_dataset_ready': True,
|
||||
'has_table_structure': False,
|
||||
'has_page_coordinates': False,
|
||||
'has_cell_coordinates': False,
|
||||
'deterministic_cell_evidence_ready': False,
|
||||
'template_packet_checksum': signatures.get('template_packet_checksum'),
|
||||
'dataset_structure_fingerprint': signatures.get('dataset_structure_fingerprint'),
|
||||
'dataset_root_path': dataset_analysis.dataset_root_path,
|
||||
'packet_checksums': packet_checksums,
|
||||
'stats': dict(dataset_analysis.stats),
|
||||
'header_candidate_count': len(dataset_analysis.header_candidates),
|
||||
'collection_candidate_count': len(dataset_analysis.collection_candidates),
|
||||
'acroform_field_count': len(acroform_fields),
|
||||
'reconciliation_candidate_count': len(reconciliation),
|
||||
'issues': [],
|
||||
}
|
||||
issues.append('xfa_document_kind_detected')
|
||||
issues.append('xfa_structure_analysis_ready')
|
||||
snapshot = {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'xfa',
|
||||
'provider_version': XFA_PARSER_IDENTITY,
|
||||
'backend': 'xfa_hardened_parser',
|
||||
'status': 'ready',
|
||||
'document_kind': document_kind,
|
||||
'tables': [],
|
||||
'text_blocks': [],
|
||||
'xfa_capability': capability,
|
||||
'capability': capability,
|
||||
'issues': sorted(set(issues)),
|
||||
}
|
||||
return XfaAnalysisOutcome(
|
||||
snapshot=snapshot,
|
||||
packet_result=packet_result,
|
||||
dataset_analysis=dataset_analysis,
|
||||
issues=snapshot['issues'],
|
||||
)
|
||||
|
||||
|
||||
def persist_xfa_structure_analysis(
|
||||
*,
|
||||
document_id: int,
|
||||
layout_version_id: int | None,
|
||||
source_content_hash: str,
|
||||
outcome: XfaAnalysisOutcome,
|
||||
) -> ShippingXfaStructureAnalysis:
|
||||
"""
|
||||
将 XFA 结构分析摘要持久化到数据库。
|
||||
|
||||
Args:
|
||||
document_id: ShippingOrderDocument 主键。
|
||||
layout_version_id: 关联布局版本 ID(可空)。
|
||||
source_content_hash: 文档内容哈希。
|
||||
outcome: analyze_xfa_pdf 的结果。
|
||||
|
||||
Returns:
|
||||
新建或更新的 ShippingXfaStructureAnalysis 记录。
|
||||
"""
|
||||
packet_result = outcome.packet_result
|
||||
dataset_analysis = outcome.dataset_analysis
|
||||
capability = (
|
||||
outcome.snapshot.get('xfa_capability')
|
||||
if isinstance(outcome.snapshot.get('xfa_capability'), dict)
|
||||
else {}
|
||||
)
|
||||
packet_checksums = capability.get('packet_checksums') if isinstance(capability.get('packet_checksums'), dict) else {}
|
||||
stats = capability.get('stats') if isinstance(capability.get('stats'), dict) else {}
|
||||
security_summary = {
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'resolve_entities': False,
|
||||
'load_dtd': False,
|
||||
'no_network': True,
|
||||
'huge_tree': False,
|
||||
'scripts_executed': False,
|
||||
'preflight_rejected': outcome.error_code == 'XFA_UNSAFE_XML',
|
||||
}
|
||||
tree_summary: dict[str, Any] = {}
|
||||
if dataset_analysis is not None:
|
||||
tree_summary = {
|
||||
'dataset_root_path_hash': hash_data_path(dataset_analysis.dataset_root_path),
|
||||
'header_candidates': list(dataset_analysis.header_candidates),
|
||||
'collection_candidates': [
|
||||
{
|
||||
'collection_path_hash': hash_data_path(item.collection_path),
|
||||
'path_id': item.path_id,
|
||||
'row_count': item.row_count,
|
||||
'local_name': item.collection_path.rstrip('/').rsplit('/', 1)[-1],
|
||||
'path_label': ' / '.join(item.collection_path.strip('/').split('/')[-3:]),
|
||||
'sibling_collection_path_hashes': [
|
||||
hash_data_path(path) for path in item.sibling_collection_paths
|
||||
],
|
||||
}
|
||||
for item in dataset_analysis.collection_candidates
|
||||
],
|
||||
'known_path_ids': sorted(dataset_analysis.known_path_ids),
|
||||
}
|
||||
|
||||
status = 'ready' if outcome.snapshot.get('status') == 'ready' else 'failed'
|
||||
if outcome.error_code == 'XFA_UNSAFE_XML':
|
||||
status = 'rejected'
|
||||
|
||||
record = ShippingXfaStructureAnalysis(
|
||||
document_id=int(document_id),
|
||||
layout_version_id=int(layout_version_id) if layout_version_id else None,
|
||||
source_content_hash=str(source_content_hash or '').lower()[:64],
|
||||
document_kind=str(
|
||||
(packet_result.document_kind if packet_result else None)
|
||||
or outcome.snapshot.get('document_kind')
|
||||
or 'unsupported',
|
||||
),
|
||||
analysis_status=status,
|
||||
template_packet_checksum=capability.get('template_packet_checksum'),
|
||||
datasets_packet_checksum=packet_checksums.get('datasets'),
|
||||
dataset_structure_fingerprint=capability.get('dataset_structure_fingerprint'),
|
||||
packet_checksums_json=dict(packet_checksums),
|
||||
stats_json=dict(stats),
|
||||
security_summary_json=security_summary,
|
||||
tree_summary_json=sanitize_xfa_dto(tree_summary),
|
||||
error_code=outcome.error_code,
|
||||
route_reason=outcome.route_reason,
|
||||
encrypted_snapshot_ref=None,
|
||||
parser_identity=XFA_PARSER_IDENTITY,
|
||||
contract_version=XFA_CONTRACT_VERSION,
|
||||
finished_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(record)
|
||||
db.session.flush()
|
||||
if status == 'ready':
|
||||
outcome.snapshot.setdefault('xfa_capability', {})['structure_analysis_id'] = int(record.id)
|
||||
if isinstance(outcome.snapshot.get('capability'), dict):
|
||||
outcome.snapshot['capability']['structure_analysis_id'] = int(record.id)
|
||||
outcome.analysis_record = record
|
||||
return record
|
||||
|
||||
|
||||
def _failed_snapshot(
|
||||
*,
|
||||
document_kind: str,
|
||||
error_code: str,
|
||||
route_reason: str,
|
||||
issues: list[str],
|
||||
packet_result: XfaPacketReadResult | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""构造 failed 状态的 XFA 布局快照。"""
|
||||
capability = {
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'contract_version': XFA_CONTRACT_VERSION,
|
||||
'document_kind': document_kind,
|
||||
'structure_analysis_ready': False,
|
||||
'xfa_dataset_ready': False,
|
||||
'has_table_structure': False,
|
||||
'error_code': error_code,
|
||||
'route_reason': route_reason,
|
||||
}
|
||||
if packet_result is not None:
|
||||
capability['packet_checksums'] = {item.name: item.checksum for item in packet_result.packets}
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'xfa',
|
||||
'provider_version': XFA_PARSER_IDENTITY,
|
||||
'backend': 'xfa_hardened_parser',
|
||||
'status': 'failed',
|
||||
'document_kind': document_kind,
|
||||
'tables': [],
|
||||
'text_blocks': [],
|
||||
'xfa_capability': capability,
|
||||
'capability': capability,
|
||||
'issues': sorted(set(issues)),
|
||||
}
|
||||
|
||||
|
||||
def _unsupported_snapshot(packet_result: XfaPacketReadResult) -> dict[str, Any]:
|
||||
"""构造 unsupported 状态的 XFA 布局快照。"""
|
||||
return {
|
||||
'snapshot_version': LAYOUT_SNAPSHOT_VERSION,
|
||||
'provider': 'xfa',
|
||||
'provider_version': XFA_PARSER_IDENTITY,
|
||||
'backend': 'xfa_hardened_parser',
|
||||
'status': 'unsupported',
|
||||
'document_kind': packet_result.document_kind,
|
||||
'tables': [],
|
||||
'text_blocks': [],
|
||||
'xfa_capability': {
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'document_kind': packet_result.document_kind,
|
||||
'structure_analysis_ready': False,
|
||||
'packet_checksums': {item.name: item.checksum for item in packet_result.packets},
|
||||
},
|
||||
'capability': {
|
||||
'document_kind': packet_result.document_kind,
|
||||
'structure_analysis_ready': False,
|
||||
'has_table_structure': False,
|
||||
},
|
||||
'issues': sorted({'xfa_unsupported_document'}),
|
||||
}
|
||||
|
||||
|
||||
def project_field_tree(analysis: ShippingXfaStructureAnalysis, *, include_values: bool = False) -> dict[str, Any]:
|
||||
"""
|
||||
从持久化分析记录投影字段树 DTO(不含 XML 明文路径)。
|
||||
|
||||
Args:
|
||||
analysis: 结构分析记录。
|
||||
include_values: 是否包含脱敏样本值。
|
||||
|
||||
Returns:
|
||||
安全字段树摘要。
|
||||
"""
|
||||
# tree_summary 存的是候选摘要;完整树在 analyze 时重建需 layout job 再解析或存结构 JSON。
|
||||
# 阶段 1:从 tree_summary_json 返回已脱敏的节点摘要。
|
||||
summary = analysis.tree_summary_json if isinstance(analysis.tree_summary_json, dict) else {}
|
||||
return sanitize_xfa_dto({
|
||||
'analysis_id': analysis.id,
|
||||
'document_kind': analysis.document_kind,
|
||||
'dataset_root_path_hash': analysis.dataset_structure_fingerprint,
|
||||
'header_candidates': summary.get('header_candidates') or [],
|
||||
'known_path_ids': summary.get('known_path_ids') or [],
|
||||
'stats': analysis.stats_json or {},
|
||||
})
|
||||
|
||||
|
||||
def get_latest_analysis_for_document(document_id: int) -> ShippingXfaStructureAnalysis | None:
|
||||
"""
|
||||
读取文档最近一次成功的 XFA 结构分析。
|
||||
|
||||
Args:
|
||||
document_id: ShippingOrderDocument 主键。
|
||||
|
||||
Returns:
|
||||
分析记录或 None。
|
||||
"""
|
||||
return (
|
||||
ShippingXfaStructureAnalysis.query.filter_by(document_id=int(document_id))
|
||||
.order_by(ShippingXfaStructureAnalysis.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def rebuild_tree_dto_from_analysis(
|
||||
analysis: ShippingXfaStructureAnalysis,
|
||||
pdf_bytes: bytes,
|
||||
*,
|
||||
include_values: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按需从 PDF 重建字段树 DTO(管理员 API 用,不持久化 XML)。
|
||||
|
||||
Args:
|
||||
analysis: 已有结构分析记录。
|
||||
pdf_bytes: 原始 PDF 字节。
|
||||
include_values: 是否包含脱敏值。
|
||||
|
||||
Returns:
|
||||
字段树 DTO。
|
||||
"""
|
||||
outcome = analyze_xfa_pdf(pdf_bytes)
|
||||
if outcome.dataset_analysis is None:
|
||||
return project_field_tree(analysis, include_values=include_values)
|
||||
root = outcome.dataset_analysis.nodes[0] if outcome.dataset_analysis.nodes else None
|
||||
tree = serialize_tree_node(root, include_values=include_values) if root else {}
|
||||
return sanitize_xfa_dto({
|
||||
'analysis_id': analysis.id,
|
||||
'document_kind': analysis.document_kind,
|
||||
'dataset_structure_fingerprint': analysis.dataset_structure_fingerprint,
|
||||
'tree': tree,
|
||||
'header_candidates': outcome.dataset_analysis.header_candidates,
|
||||
'stats': outcome.dataset_analysis.stats,
|
||||
})
|
||||
@@ -0,0 +1,733 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_contract.py
|
||||
|
||||
用途:冻结 XFA 数据路径 Profile 的阶段 0 契约——template_mode、受控路径语法、
|
||||
结构指纹算法、资源上限、支持/拒绝矩阵、鉴别联合 definition、evidence 与安全投影。
|
||||
依赖:Pydantic 2、标准库 hashlib/json/re/unicodedata;被 order_extraction_route_contract、
|
||||
error_explainability_contract、Profile 校验与后续 xfa_*.py 解析器引用。
|
||||
逻辑:本模块只定义契约与纯函数校验,不读 PDF/XML、不执行脚本、不接正式流量;
|
||||
coordinate 行为保持不变,xfa_dataset 定义不得混入坐标 region。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import unicodedata
|
||||
from typing import Any, Final, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 契约版本与模式
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_CONTRACT_VERSION: Final[str] = 'shipping-xfa-dataset-contract.v1'
|
||||
XFA_PARSER_IDENTITY: Final[str] = 'shipping-xfa-hardened-parser.v1'
|
||||
XFA_STRUCTURE_FINGERPRINT_VERSION: Final[str] = 'xfa-dataset-structure-fingerprint.v1'
|
||||
XFA_STRUCTURE_SIGNATURE_ID: Final[str] = 'xfa-structure-signature.v1'
|
||||
# 盲测/正式提取共用的文档级 table_id 占位;XFA 无物理表格。
|
||||
XFA_DOCUMENT_TABLE_ID: Final[str] = 'xfa-authoritative-lines'
|
||||
|
||||
OrderProfileTemplateMode = Literal['coordinate', 'xfa_dataset']
|
||||
ORDER_PROFILE_TEMPLATE_MODES: Final[frozenset[str]] = frozenset({
|
||||
'coordinate',
|
||||
'xfa_dataset',
|
||||
})
|
||||
|
||||
XfaDocumentKind = Literal[
|
||||
'plain_pdf',
|
||||
'acroform',
|
||||
'xfa_hybrid',
|
||||
'pure_xfa',
|
||||
'unsupported',
|
||||
]
|
||||
XFA_DOCUMENT_KINDS: Final[frozenset[str]] = frozenset({
|
||||
'plain_pdf',
|
||||
'acroform',
|
||||
'xfa_hybrid',
|
||||
'pure_xfa',
|
||||
'unsupported',
|
||||
})
|
||||
|
||||
# 第一版正式支持:datasets 已含最终业务值的混合型 XFA。
|
||||
XFA_SUPPORTED_DOCUMENT_KINDS: Final[frozenset[str]] = frozenset({
|
||||
'xfa_hybrid',
|
||||
})
|
||||
|
||||
XFA_REJECTED_CAPABILITIES: Final[frozenset[str]] = frozenset({
|
||||
'execute_javascript',
|
||||
'execute_formcalc',
|
||||
'external_data_connection',
|
||||
'network_fetch',
|
||||
'fuzzy_template_match',
|
||||
'auto_merge_line_collections',
|
||||
'ocr_fallback',
|
||||
'vlm_fallback',
|
||||
'blank_page_coordinate_evidence',
|
||||
'flatten_legal_equivalent_pdf',
|
||||
})
|
||||
|
||||
XfaEvidenceSource = Literal['xfa_dataset']
|
||||
XFA_EVIDENCE_SOURCES: Final[frozenset[str]] = frozenset({'xfa_dataset'})
|
||||
|
||||
XfaCrossCheckStatus = Literal[
|
||||
'matched',
|
||||
'partial',
|
||||
'mismatched',
|
||||
'skipped',
|
||||
'unavailable',
|
||||
'failed',
|
||||
]
|
||||
XFA_CROSS_CHECK_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'matched',
|
||||
'partial',
|
||||
'mismatched',
|
||||
'skipped',
|
||||
'unavailable',
|
||||
'failed',
|
||||
})
|
||||
# 自动建单 CQ 仅接受可证明完整性的对账状态(不含 partial/unavailable)。
|
||||
XFA_CROSS_CHECK_AUTO_CREATE_OK_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'matched',
|
||||
'passed',
|
||||
'skipped',
|
||||
})
|
||||
|
||||
XfaMirrorCollectionPolicy = Literal['must_match_when_present', 'ignore']
|
||||
XFA_MIRROR_COLLECTION_POLICIES: Final[frozenset[str]] = frozenset({
|
||||
'must_match_when_present',
|
||||
'ignore',
|
||||
})
|
||||
|
||||
XfaLineAmountFormula = Literal['quantity_times_unit_price', 'disabled']
|
||||
XfaTotalAmountPolicy = Literal['must_equal_line_sum', 'disabled']
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 资源上限(与验收/实施方案一致;后续可由 settings 覆盖,但契约默认值冻结)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_DEFAULT_MAX_PDF_BYTES: Final[int] = 20 * 1024 * 1024
|
||||
XFA_DEFAULT_MAX_PACKET_BYTES: Final[int] = 10 * 1024 * 1024
|
||||
XFA_DEFAULT_MAX_XML_DEPTH: Final[int] = 64
|
||||
XFA_DEFAULT_MAX_XML_NODES: Final[int] = 100_000
|
||||
XFA_DEFAULT_MAX_LINE_ROWS: Final[int] = 2_000
|
||||
XFA_DEFAULT_PARSE_TIMEOUT_SECONDS: Final[int] = 30
|
||||
XFA_DEFAULT_MAX_RETRIES: Final[int] = 2
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 稳定错误码 / 路由原因码(阶段 0 冻结;后续只追加不改语义)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_ERROR_CODES: Final[frozenset[str]] = frozenset({
|
||||
'XFA_DATASET_MISSING',
|
||||
'XFA_UNSAFE_XML',
|
||||
'XFA_PACKET_TOO_LARGE',
|
||||
'XFA_XML_DEPTH_EXCEEDED',
|
||||
'XFA_XML_NODE_LIMIT_EXCEEDED',
|
||||
'XFA_LINE_ROW_LIMIT_EXCEEDED',
|
||||
'XFA_PARSE_TIMEOUT',
|
||||
'XFA_UNSUPPORTED_DOCUMENT',
|
||||
'XFA_PROFILE_NOT_MATCHED',
|
||||
'XFA_PROFILE_AMBIGUOUS',
|
||||
'XFA_REQUIRED_FIELD_MISSING',
|
||||
'XFA_MIRROR_COLLECTION_MISMATCH',
|
||||
'XFA_ACROFORM_MISMATCH',
|
||||
'XFA_BUSINESS_VALIDATION_FAILED',
|
||||
'XFA_AUTHORITATIVE_COLLECTION_MISSING',
|
||||
'XFA_PATH_INVALID',
|
||||
'XFA_PATH_UNKNOWN',
|
||||
'XFA_DEFINITION_INVALID',
|
||||
'XFA_SPLIT_RULE_INVALID',
|
||||
'XFA_SPLIT_FIELD_CONFLICT',
|
||||
'XFA_SPLIT_MIRROR_MISMATCH',
|
||||
})
|
||||
|
||||
XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_dataset_missing',
|
||||
'xfa_unsafe_xml',
|
||||
'xfa_packet_too_large',
|
||||
'xfa_xml_depth_exceeded',
|
||||
'xfa_xml_node_limit_exceeded',
|
||||
'xfa_line_row_limit_exceeded',
|
||||
'xfa_parse_timeout',
|
||||
'xfa_unsupported_document',
|
||||
'xfa_profile_not_matched',
|
||||
'xfa_profile_ambiguous',
|
||||
'xfa_required_field_missing',
|
||||
'xfa_mirror_collection_mismatch',
|
||||
'xfa_acroform_mismatch',
|
||||
'xfa_business_validation_failed',
|
||||
'xfa_authoritative_collection_missing',
|
||||
'xfa_path_invalid',
|
||||
'xfa_path_unknown',
|
||||
'xfa_definition_invalid',
|
||||
'xfa_structure_identity_changed',
|
||||
'xfa_split_rule_invalid',
|
||||
'xfa_split_field_conflict',
|
||||
'xfa_split_mirror_mismatch',
|
||||
})
|
||||
|
||||
XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_sample_uploaded',
|
||||
'xfa_parse_started',
|
||||
'xfa_parse_completed',
|
||||
'xfa_parse_failed',
|
||||
'xfa_parse_rejected_unsafe',
|
||||
'xfa_document_kind_detected',
|
||||
'xfa_packet_parsed',
|
||||
'xfa_structure_analysis_ready',
|
||||
'xfa_field_tree_accessed',
|
||||
'xfa_collections_accessed',
|
||||
'xfa_sensitive_sample_value_read',
|
||||
'xfa_draft_created',
|
||||
'xfa_mapping_saved',
|
||||
'xfa_authoritative_collection_selected',
|
||||
'xfa_normalizer_changed',
|
||||
'xfa_profile_matched',
|
||||
'xfa_profile_not_matched',
|
||||
'xfa_profile_ambiguous',
|
||||
'xfa_extraction_completed',
|
||||
'xfa_extraction_failed',
|
||||
'xfa_cross_check_completed',
|
||||
'xfa_structure_signature_frozen',
|
||||
'xfa_audit_snapshot_viewed',
|
||||
# 字段拆分映射审计(阶段 3/7)
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
'xfa_split_rule_validated',
|
||||
'xfa_split_segment_created',
|
||||
'xfa_split_segment_updated',
|
||||
'xfa_split_segment_deleted',
|
||||
'xfa_segment_mapping_updated',
|
||||
'xfa_profile_draft_saved',
|
||||
'xfa_profile_validation_executed',
|
||||
'blind_test_executed',
|
||||
'blind_test_approved',
|
||||
'xfa_profile_published',
|
||||
'xfa_profile_formal_extracted',
|
||||
'xfa_profile_needs_review',
|
||||
})
|
||||
|
||||
# Profile / Run / 分析 DTO 禁止键(大小写不敏感);完整 XML / PDF bytes / 存储地址不得外泄。
|
||||
XFA_DTO_FORBIDDEN_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'xml',
|
||||
'raw_xml',
|
||||
'xfa_xml',
|
||||
'datasets_xml',
|
||||
'packet_bytes',
|
||||
'pdf_bytes',
|
||||
'file_bytes',
|
||||
'object_key',
|
||||
'object_url',
|
||||
'minio',
|
||||
'storage_url',
|
||||
'presigned_url',
|
||||
'api_key',
|
||||
'secret',
|
||||
'password',
|
||||
'authorization',
|
||||
'credential',
|
||||
'audit_snapshot_key',
|
||||
'raw_value', # 普通 DTO 仅允许脱敏预览或 encrypted ref
|
||||
'full_xml_path', # 普通用户 DTO 不返回明文路径;管理员敏感读另走受控 API
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 受控数据路径语法
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# 路径形态:/localName[/localName...];禁止通配、函数、父级逃逸、属性谓词与脚本。
|
||||
_XFA_PATH_SEGMENT_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_.-]*$')
|
||||
_XFA_FORBIDDEN_PATH_SUBSTRINGS = (
|
||||
'*',
|
||||
'//',
|
||||
'..',
|
||||
'(',
|
||||
')',
|
||||
'[',
|
||||
']',
|
||||
'@',
|
||||
'=',
|
||||
'|',
|
||||
'::',
|
||||
)
|
||||
_XFA_FORBIDDEN_PATH_SEGMENTS = frozenset({
|
||||
'script',
|
||||
'javascript',
|
||||
'formcalc',
|
||||
})
|
||||
|
||||
|
||||
class XfaContractModel(BaseModel):
|
||||
"""XFA 契约模型基类:禁止额外字段,赋值时再次校验。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class XfaSourceContract(XfaContractModel):
|
||||
"""冻结 XFA 模板结构身份:packet checksum + 结构指纹 + 权威集合路径。"""
|
||||
|
||||
template_packet_checksum: str = Field(min_length=16, max_length=128)
|
||||
dataset_structure_fingerprint: str = Field(min_length=16, max_length=128)
|
||||
dataset_root_path: str = Field(min_length=1, max_length=512)
|
||||
authoritative_line_collection_path: str = Field(min_length=1, max_length=512)
|
||||
mirror_collection_paths: list[str] = Field(default_factory=list)
|
||||
|
||||
@field_validator(
|
||||
'dataset_root_path',
|
||||
'authoritative_line_collection_path',
|
||||
mode='before',
|
||||
)
|
||||
@classmethod
|
||||
def validate_required_paths(cls, value: Any) -> str:
|
||||
"""校验必填受控路径语法。"""
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
@field_validator('mirror_collection_paths', mode='before')
|
||||
@classmethod
|
||||
def validate_mirror_paths(cls, value: Any) -> list[str]:
|
||||
"""校验镜像集合路径列表;允许空列表。"""
|
||||
items = list(value or [])
|
||||
return [validate_controlled_data_path(item) for item in items]
|
||||
|
||||
|
||||
class XfaHeaderMapping(XfaContractModel):
|
||||
"""Header 字段:Schema field ↔ 受控 datasets 路径。"""
|
||||
|
||||
mapping_id: str = Field(min_length=1, max_length=64)
|
||||
field_id: str = Field(min_length=1, max_length=64)
|
||||
field_code: str = Field(min_length=1, max_length=128)
|
||||
data_path: str = Field(min_length=1, max_length=512)
|
||||
path_id: str = Field(min_length=1, max_length=128)
|
||||
value_type: str = Field(min_length=1, max_length=64)
|
||||
normalizer_key: str | None = Field(default=None, max_length=64)
|
||||
validator_key: str | None = Field(default=None, max_length=64)
|
||||
|
||||
@field_validator('data_path', mode='before')
|
||||
@classmethod
|
||||
def validate_data_path(cls, value: Any) -> str:
|
||||
"""Header 映射路径必须通过受控语法。"""
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
|
||||
class XfaLineFieldMapping(XfaContractModel):
|
||||
"""明细行字段映射。"""
|
||||
|
||||
mapping_id: str = Field(min_length=1, max_length=64)
|
||||
field_id: str = Field(min_length=1, max_length=64)
|
||||
field_code: str = Field(min_length=1, max_length=128)
|
||||
data_path: str = Field(min_length=1, max_length=512)
|
||||
path_id: str = Field(min_length=1, max_length=128)
|
||||
value_type: str = Field(min_length=1, max_length=64)
|
||||
normalizer_key: str | None = Field(default=None, max_length=64)
|
||||
validator_key: str | None = Field(default=None, max_length=64)
|
||||
|
||||
@field_validator('data_path', mode='before')
|
||||
@classmethod
|
||||
def validate_data_path(cls, value: Any) -> str:
|
||||
"""明细映射路径必须通过受控语法。"""
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
|
||||
class XfaLineMapping(XfaContractModel):
|
||||
"""权威明细集合路径及行内字段映射。"""
|
||||
|
||||
row_path: str = Field(min_length=1, max_length=512)
|
||||
fields: list[XfaLineFieldMapping] = Field(default_factory=list)
|
||||
|
||||
@field_validator('row_path', mode='before')
|
||||
@classmethod
|
||||
def validate_row_path(cls, value: Any) -> str:
|
||||
"""行集合路径必须通过受控语法。"""
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
|
||||
class XfaCrossChecks(XfaContractModel):
|
||||
"""对账与业务恒等式策略。"""
|
||||
|
||||
acroform_enabled: bool = True
|
||||
mirror_collection_policy: XfaMirrorCollectionPolicy = 'must_match_when_present'
|
||||
line_amount_formula: XfaLineAmountFormula = 'quantity_times_unit_price'
|
||||
total_amount_policy: XfaTotalAmountPolicy = 'must_equal_line_sum'
|
||||
|
||||
|
||||
class OrderXfaDatasetProfile(XfaContractModel):
|
||||
"""
|
||||
xfa_dataset 模式的鉴别联合 definition。
|
||||
|
||||
核心逻辑:仅允许 XFA 映射字段;显式拒绝 coordinate 的 table_regions /
|
||||
order_field_layouts 等键混入;可选 split_rules 声明式多行拆分。
|
||||
"""
|
||||
|
||||
template_mode: Literal['xfa_dataset'] = 'xfa_dataset'
|
||||
source_contract: XfaSourceContract
|
||||
header_mappings: list[XfaHeaderMapping] = Field(default_factory=list)
|
||||
line_mapping: XfaLineMapping
|
||||
cross_checks: XfaCrossChecks = Field(default_factory=XfaCrossChecks)
|
||||
split_rules: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
@model_validator(mode='before')
|
||||
@classmethod
|
||||
def reject_coordinate_keys(cls, data: Any) -> Any:
|
||||
"""拒绝 coordinate region / layout 键混入 XFA definition。"""
|
||||
if not isinstance(data, dict):
|
||||
return data
|
||||
forbidden = {
|
||||
'table_regions',
|
||||
'order_field_layouts',
|
||||
'draft_unbound_order_field_layouts',
|
||||
'document_match',
|
||||
'structure_fingerprint',
|
||||
'column_rules',
|
||||
'row_structure',
|
||||
'coordinate_reconstruction',
|
||||
}
|
||||
present = sorted(key for key in forbidden if key in data)
|
||||
if present:
|
||||
raise ValueError(
|
||||
f'xfa_dataset definition must not mix coordinate keys: {", ".join(present)}',
|
||||
)
|
||||
mode = str(data.get('template_mode') or 'xfa_dataset').strip()
|
||||
if mode != 'xfa_dataset':
|
||||
raise ValueError('OrderXfaDatasetProfile requires template_mode=xfa_dataset')
|
||||
return data
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_unique_bindings(self) -> 'OrderXfaDatasetProfile':
|
||||
"""同一 Schema 字段与同一 mapping_id 不得重复绑定;校验 split_rules 契约。"""
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
parse_split_rule_sets,
|
||||
)
|
||||
|
||||
field_ids: list[str] = []
|
||||
mapping_ids: list[str] = []
|
||||
for item in self.header_mappings:
|
||||
field_ids.append(item.field_id)
|
||||
mapping_ids.append(item.mapping_id)
|
||||
for item in self.line_mapping.fields:
|
||||
field_ids.append(item.field_id)
|
||||
mapping_ids.append(item.mapping_id)
|
||||
rule_sets = parse_split_rule_sets(self.split_rules)
|
||||
for rule_set in rule_sets:
|
||||
for rule in rule_set.rules:
|
||||
if rule.segment.handling == 'mapped' and rule.segment.target_field_id:
|
||||
field_ids.append(rule.segment.target_field_id)
|
||||
if len(field_ids) != len(set(field_ids)):
|
||||
raise ValueError('duplicate Schema field_id bindings are not allowed')
|
||||
if len(mapping_ids) != len(set(mapping_ids)):
|
||||
raise ValueError('duplicate mapping_id values are not allowed')
|
||||
if self.line_mapping.row_path != self.source_contract.authoritative_line_collection_path:
|
||||
raise ValueError('line_mapping.row_path must equal authoritative_line_collection_path')
|
||||
# 回写规范化后的 split_rules(model_dump 形状)。
|
||||
object.__setattr__(
|
||||
self,
|
||||
'split_rules',
|
||||
[item.model_dump(mode='json') for item in rule_sets],
|
||||
)
|
||||
return self
|
||||
|
||||
class XfaFieldEvidenceRef(XfaContractModel):
|
||||
"""字段证据引用:普通 DTO 仅含哈希与标准化值,不含明文路径与原始 XML。"""
|
||||
|
||||
source: XfaEvidenceSource = 'xfa_dataset'
|
||||
document_id: int = Field(ge=1)
|
||||
packet_checksum: str = Field(min_length=16, max_length=128)
|
||||
data_path_hash: str = Field(min_length=16, max_length=128)
|
||||
mapping_id: str = Field(min_length=1, max_length=64)
|
||||
raw_value_snapshot_ref: str | None = Field(default=None, max_length=256)
|
||||
normalized_value: str | None = None
|
||||
normalizer_key: str | None = Field(default=None, max_length=64)
|
||||
cross_check_status: XfaCrossCheckStatus = 'unavailable'
|
||||
|
||||
|
||||
class XfaStructureNodeSpec(XfaContractModel):
|
||||
"""结构指纹输入节点:只含名称/层级/基数/命名空间,不含业务值。"""
|
||||
|
||||
local_name: str = Field(min_length=1, max_length=256)
|
||||
namespace_uri: str = ''
|
||||
depth: int = Field(ge=0, le=XFA_DEFAULT_MAX_XML_DEPTH)
|
||||
cardinality: Literal['one', 'many'] = 'one'
|
||||
children: list['XfaStructureNodeSpec'] = Field(default_factory=list)
|
||||
|
||||
|
||||
XfaStructureNodeSpec.model_rebuild()
|
||||
|
||||
|
||||
def normalize_template_mode(value: Any) -> OrderProfileTemplateMode:
|
||||
"""
|
||||
将输入规范化为合法 template_mode。
|
||||
|
||||
Args:
|
||||
value: 原始模式字符串。
|
||||
|
||||
Returns:
|
||||
coordinate | xfa_dataset。
|
||||
|
||||
Raises:
|
||||
ValueError: 非法或不支持的模式。
|
||||
"""
|
||||
mode = str(value or '').strip()
|
||||
if mode not in ORDER_PROFILE_TEMPLATE_MODES:
|
||||
raise ValueError(
|
||||
f'template_mode must be one of {sorted(ORDER_PROFILE_TEMPLATE_MODES)}; got {mode!r}',
|
||||
)
|
||||
return mode # type: ignore[return-value]
|
||||
|
||||
|
||||
def validate_controlled_data_path(value: Any) -> str:
|
||||
"""
|
||||
校验受控数据路径语法。
|
||||
|
||||
核心逻辑:仅允许以 `/` 分段的 localName 路径;拒绝通配符、函数调用、
|
||||
父级逃逸、属性谓词、命名空间轴与脚本关键字。
|
||||
|
||||
Args:
|
||||
value: 候选路径字符串。
|
||||
|
||||
Returns:
|
||||
规范化后的绝对路径(保留段名大小写)。
|
||||
|
||||
Raises:
|
||||
ValueError: 路径语法非法。
|
||||
"""
|
||||
path = str(value or '').strip()
|
||||
if not path:
|
||||
raise ValueError('data path is required')
|
||||
lowered = path.lower()
|
||||
for token in _XFA_FORBIDDEN_PATH_SUBSTRINGS:
|
||||
if token in path or token in lowered:
|
||||
raise ValueError(f'data path contains forbidden token: {token}')
|
||||
if not path.startswith('/'):
|
||||
raise ValueError('data path must be absolute and start with /')
|
||||
if path != '/' and path.endswith('/'):
|
||||
raise ValueError('data path must not end with /')
|
||||
segments = [part for part in path.split('/') if part != '']
|
||||
if not segments:
|
||||
raise ValueError('data path must contain at least one segment')
|
||||
for segment in segments:
|
||||
if segment.lower() in _XFA_FORBIDDEN_PATH_SEGMENTS:
|
||||
raise ValueError(f'data path contains forbidden segment: {segment}')
|
||||
if not _XFA_PATH_SEGMENT_RE.fullmatch(segment):
|
||||
raise ValueError(f'invalid data path segment: {segment!r}')
|
||||
return '/' + '/'.join(segments)
|
||||
|
||||
|
||||
def assert_path_id_known(path_id: str, known_path_ids: set[str] | frozenset[str]) -> str:
|
||||
"""
|
||||
断言 path_id 属于当前结构分析记录中的已知集合。
|
||||
|
||||
Args:
|
||||
path_id: 映射保存的路径身份。
|
||||
known_path_ids: 分析记录产生的合法 path ID 集合。
|
||||
|
||||
Returns:
|
||||
原 path_id。
|
||||
|
||||
Raises:
|
||||
ValueError: path_id 未知。
|
||||
"""
|
||||
normalized = str(path_id or '').strip()
|
||||
if not normalized:
|
||||
raise ValueError('path_id is required')
|
||||
if normalized not in known_path_ids:
|
||||
raise ValueError(f'unknown path_id: {normalized}')
|
||||
return normalized
|
||||
|
||||
|
||||
def hash_data_path(path: str) -> str:
|
||||
"""
|
||||
对受控路径计算稳定 SHA-256(带 sha256: 前缀),供 evidence 与审计脱敏使用。
|
||||
|
||||
Args:
|
||||
path: 已通过语法校验的数据路径。
|
||||
|
||||
Returns:
|
||||
`sha256:<hex>` 字符串。
|
||||
"""
|
||||
validated = validate_controlled_data_path(path)
|
||||
digest = hashlib.sha256(validated.encode('utf-8')).hexdigest()
|
||||
return f'sha256:{digest}'
|
||||
|
||||
|
||||
def canonical_structure_payload(nodes: list[XfaStructureNodeSpec] | list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""
|
||||
生成结构指纹的 canonical 载荷。
|
||||
|
||||
核心逻辑:仅序列化 local_name / namespace_uri / depth / cardinality / children;
|
||||
不包含订单值、文件名或明细行数量。
|
||||
|
||||
Args:
|
||||
nodes: 结构树根列表(模型或 dict)。
|
||||
|
||||
Returns:
|
||||
可稳定哈希的字典。
|
||||
"""
|
||||
validated = [
|
||||
item if isinstance(item, XfaStructureNodeSpec) else XfaStructureNodeSpec.model_validate(item)
|
||||
for item in nodes
|
||||
]
|
||||
|
||||
def _dump(node: XfaStructureNodeSpec) -> dict[str, Any]:
|
||||
return {
|
||||
'local_name': node.local_name,
|
||||
'namespace_uri': node.namespace_uri or '',
|
||||
'depth': node.depth,
|
||||
'cardinality': node.cardinality,
|
||||
'children': [_dump(child) for child in node.children],
|
||||
}
|
||||
|
||||
return {
|
||||
'fingerprint_version': XFA_STRUCTURE_FINGERPRINT_VERSION,
|
||||
'roots': [_dump(node) for node in validated],
|
||||
}
|
||||
|
||||
|
||||
def compute_dataset_structure_fingerprint(
|
||||
nodes: list[XfaStructureNodeSpec] | list[dict[str, Any]],
|
||||
) -> str:
|
||||
"""
|
||||
计算 dataset 结构指纹。
|
||||
|
||||
Args:
|
||||
nodes: 不含业务值的结构树。
|
||||
|
||||
Returns:
|
||||
`sha256:<hex>` 指纹。
|
||||
"""
|
||||
payload = canonical_structure_payload(nodes)
|
||||
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
return f'sha256:{hashlib.sha256(raw.encode("utf-8")).hexdigest()}'
|
||||
|
||||
|
||||
def validate_xfa_dataset_definition(payload: dict[str, Any] | OrderXfaDatasetProfile) -> OrderXfaDatasetProfile:
|
||||
"""
|
||||
将字典校验为 OrderXfaDatasetProfile。
|
||||
|
||||
Args:
|
||||
payload: 原始 definition 或已构造模型。
|
||||
|
||||
Returns:
|
||||
通过鉴别联合与路径语法校验的模型。
|
||||
|
||||
Raises:
|
||||
pydantic.ValidationError / ValueError: 契约不合法。
|
||||
"""
|
||||
if isinstance(payload, OrderXfaDatasetProfile):
|
||||
return OrderXfaDatasetProfile.model_validate(payload.model_dump(mode='json'))
|
||||
return OrderXfaDatasetProfile.model_validate(payload)
|
||||
|
||||
|
||||
def sanitize_xfa_dto(payload: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
递归剥离 Profile/Run/分析 DTO 中的禁止键。
|
||||
|
||||
核心逻辑:键名大小写不敏感匹配 XFA_DTO_FORBIDDEN_KEYS;用于阶段 0 契约测试
|
||||
与后续 API 投影共用。
|
||||
|
||||
Args:
|
||||
payload: 候选字典。
|
||||
|
||||
Returns:
|
||||
脱敏后的浅拷贝字典。
|
||||
"""
|
||||
if not isinstance(payload, dict):
|
||||
return {}
|
||||
forbidden = {key.lower() for key in XFA_DTO_FORBIDDEN_KEYS}
|
||||
|
||||
def _walk(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
cleaned: dict[str, Any] = {}
|
||||
for key, item in value.items():
|
||||
if str(key).lower() in forbidden:
|
||||
continue
|
||||
cleaned[str(key)] = _walk(item)
|
||||
return cleaned
|
||||
if isinstance(value, list):
|
||||
return [_walk(item) for item in value]
|
||||
return value
|
||||
|
||||
return _walk(payload)
|
||||
|
||||
|
||||
_XFA_FULL_DISPLAY_FIELD_NAMES: Final[frozenset[str]] = frozenset({
|
||||
'AMOUNT', 'BEDAT', 'COUNTRY', 'EBELP', 'EINDT', 'INCO1', 'INCO2',
|
||||
'MEINS', 'MENGE', 'NETPR', 'PEINH', 'POST_CODE1', 'TOTAL_AMOUNT',
|
||||
'WAERS', 'WERKS', 'ZTERM',
|
||||
})
|
||||
_XFA_RESTRICTED_FIELD_TOKENS: Final[tuple[str, ...]] = (
|
||||
'ADDRESS', 'CITY', 'FAX', 'HOUSE', 'INSTRUCTION', 'INSPECTION', 'NAME',
|
||||
'PHONE', 'REMARK', 'SPECIFICATION', 'STRAS', 'STREET', 'TEL', 'VENDOR',
|
||||
)
|
||||
|
||||
|
||||
def mask_sample_value(value: Any, *, keep_head: int = 4, keep_tail: int = 3) -> str:
|
||||
"""
|
||||
对样本原值做默认脱敏展示。
|
||||
|
||||
Args:
|
||||
value: 原始业务值。
|
||||
keep_head: 保留前缀字符数。
|
||||
keep_tail: 保留后缀字符数。
|
||||
|
||||
Returns:
|
||||
脱敏字符串;短值整体替换为 `***`。
|
||||
"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).strip()
|
||||
if not text:
|
||||
return ''
|
||||
if len(text) <= keep_head + keep_tail:
|
||||
return '***'
|
||||
return f'{text[:keep_head]}{"•" * 3}{text[-keep_tail:]}'
|
||||
|
||||
|
||||
def xfa_mapping_sample_display(field_name: str, value: Any) -> dict[str, Any]:
|
||||
"""
|
||||
为 XFA 映射工作台生成可辨识且分级受控的样本展示。
|
||||
|
||||
核心逻辑:业务代码、日期、数量、金额与单位完整展示;订单/物料等标识符保留
|
||||
足够前后缀;名称、地址、电话和自由文本默认限制展示并允许授权后临时展开。
|
||||
|
||||
Args:
|
||||
field_name: XML 叶子节点 localName。
|
||||
value: datasets 原始业务值。
|
||||
|
||||
Returns:
|
||||
display_value、display_policy 与 can_reveal 组成的安全展示字典。
|
||||
"""
|
||||
text = unicodedata.normalize('NFKC', str(value or '')).strip()
|
||||
name = unicodedata.normalize('NFKC', str(field_name or '')).strip().upper()
|
||||
if not text:
|
||||
return {'display_value': '', 'display_policy': 'empty', 'can_reveal': False}
|
||||
if name in _XFA_FULL_DISPLAY_FIELD_NAMES:
|
||||
return {'display_value': text, 'display_policy': 'full', 'can_reveal': False}
|
||||
if any(token in name for token in _XFA_RESTRICTED_FIELD_TOKENS):
|
||||
if len(text) <= 4:
|
||||
display = f'{text[:1]}•••'
|
||||
else:
|
||||
display = f'{text[: min(8, max(2, len(text) // 3))]}•••'
|
||||
return {'display_value': display, 'display_policy': 'restricted', 'can_reveal': True}
|
||||
|
||||
# 标识符需要足以区分字段和值;短标识不再整体压成无法判断语义的 ***。
|
||||
if len(text) <= 4:
|
||||
display = text
|
||||
elif len(text) <= 8:
|
||||
display = f'{text[:2]}••{text[-2:]}'
|
||||
else:
|
||||
head = min(16, max(4, len(text) // 2))
|
||||
display = f'{text[:head]}…{text[-3:]}'
|
||||
return {'display_value': display, 'display_policy': 'partial', 'can_reveal': True}
|
||||
|
||||
|
||||
def default_xfa_resource_limits() -> dict[str, int]:
|
||||
"""返回阶段 0 冻结的默认资源上限字典。"""
|
||||
return {
|
||||
'max_pdf_bytes': XFA_DEFAULT_MAX_PDF_BYTES,
|
||||
'max_packet_bytes': XFA_DEFAULT_MAX_PACKET_BYTES,
|
||||
'max_xml_depth': XFA_DEFAULT_MAX_XML_DEPTH,
|
||||
'max_xml_nodes': XFA_DEFAULT_MAX_XML_NODES,
|
||||
'max_line_rows': XFA_DEFAULT_MAX_LINE_ROWS,
|
||||
'parse_timeout_seconds': XFA_DEFAULT_PARSE_TIMEOUT_SECONDS,
|
||||
'max_retries': XFA_DEFAULT_MAX_RETRIES,
|
||||
}
|
||||
@@ -0,0 +1,605 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_dataset.py
|
||||
|
||||
用途: hardened 解析 XFA datasets XML,构建受控路径树并识别 Header/集合候选;
|
||||
提供单叶子与权威集合行读取供正式提取使用;叶子保留 raw/normalized/lines
|
||||
三层中间表示,供字段拆分规则引擎消费。
|
||||
依赖:lxml、xfa_contract(路径语法/指纹/脱敏)、xfa_packets.preflight_xml_bytes。
|
||||
逻辑:由 xfa_analysis、xfa_profile_extraction 与 admin XFA API 调用;
|
||||
只读内存 XML,不联网、不执行脚本;raw_value/lines 仅存内存树,不进入普通 DTO。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_DEFAULT_MAX_LINE_ROWS,
|
||||
XFA_DEFAULT_MAX_XML_DEPTH,
|
||||
XFA_DEFAULT_MAX_XML_NODES,
|
||||
hash_data_path,
|
||||
mask_sample_value,
|
||||
xfa_mapping_sample_display,
|
||||
validate_controlled_data_path,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_packets import XfaPacketError, preflight_xml_bytes
|
||||
|
||||
_CARDINALITY = Literal['one', 'many']
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaLeafValue:
|
||||
"""
|
||||
叶子业务值的三层中间表示(阶段 1:字段拆分前置)。
|
||||
|
||||
raw_value:保留原始换行(统一为 \\n);
|
||||
normalized_value:空白折叠,供搜索/比较;
|
||||
lines:按换行切分后的行列表(含空行,规则引擎再按 normalization 过滤)。
|
||||
"""
|
||||
|
||||
raw_value: str
|
||||
normalized_value: str
|
||||
lines: list[str]
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaDatasetNode:
|
||||
"""受控路径树节点。"""
|
||||
|
||||
path_id: str
|
||||
local_name: str
|
||||
namespace_uri: str
|
||||
data_path: str
|
||||
depth: int
|
||||
cardinality: _CARDINALITY
|
||||
is_leaf: bool
|
||||
is_header_candidate: bool = False
|
||||
is_collection_candidate: bool = False
|
||||
sample_value_masked: str | None = None
|
||||
sample_value_display: str | None = None
|
||||
display_policy: str = 'empty'
|
||||
can_reveal: bool = False
|
||||
# 仅内存内部使用;serialize_tree_node / 普通 DTO 不得外泄原文。
|
||||
raw_value: str | None = None
|
||||
normalized_value: str | None = None
|
||||
lines: list[str] = field(default_factory=list)
|
||||
children: list['XfaDatasetNode'] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaCollectionCandidate:
|
||||
"""重复明细集合候选。"""
|
||||
|
||||
collection_path: str
|
||||
path_id: str
|
||||
row_count: int
|
||||
sibling_collection_paths: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaDatasetAnalysis:
|
||||
"""datasets 结构分析结果。"""
|
||||
|
||||
dataset_root_path: str
|
||||
nodes: list[XfaDatasetNode]
|
||||
header_candidates: list[dict[str, Any]]
|
||||
collection_candidates: list[XfaCollectionCandidate]
|
||||
stats: dict[str, Any]
|
||||
leaf_values_by_path: dict[str, str]
|
||||
known_path_ids: set[str]
|
||||
|
||||
|
||||
class XfaDatasetParseError(XfaPacketError):
|
||||
"""datasets 解析失败。"""
|
||||
|
||||
|
||||
def _local_name(tag: str) -> str:
|
||||
"""提取 XML localName,忽略命名空间前缀。"""
|
||||
return str(tag or '').rsplit('}', 1)[-1]
|
||||
|
||||
|
||||
def _namespace_uri(tag: str) -> str:
|
||||
"""提取命名空间 URI。"""
|
||||
text = str(tag or '')
|
||||
if text.startswith('{') and '}' in text:
|
||||
return text[1:text.index('}')]
|
||||
return ''
|
||||
|
||||
|
||||
def _normalize_leaf_text(value: str) -> str:
|
||||
"""
|
||||
将叶子文本折叠为单行规范化串(搜索/比较用)。
|
||||
|
||||
注意:不得用于正式拆分输入;拆分必须使用保留换行的 raw_value / lines。
|
||||
"""
|
||||
return re.sub(r'\s+', ' ', str(value or '')).strip()
|
||||
|
||||
|
||||
def build_xfa_leaf_value(text: str) -> XfaLeafValue:
|
||||
"""
|
||||
从 XML 叶子原文构建三层中间表示。
|
||||
|
||||
核心逻辑:统一 \\r\\n/\\r 为 \\n 且保留行结构;去掉整段首尾换行(pretty-print);
|
||||
normalized 折叠空白;lines 按 \\n 切分(含空行,供 position matcher 使用)。
|
||||
|
||||
Args:
|
||||
text: element.itertext() 拼接后的原文。
|
||||
|
||||
Returns:
|
||||
XfaLeafValue。
|
||||
"""
|
||||
raw = str(text or '').replace('\r\n', '\n').replace('\r', '\n').strip('\n')
|
||||
lines = raw.split('\n') if raw != '' else []
|
||||
return XfaLeafValue(
|
||||
raw_value=raw,
|
||||
normalized_value=_normalize_leaf_text(raw),
|
||||
lines=lines,
|
||||
)
|
||||
|
||||
|
||||
def _path_id_for(data_path: str) -> str:
|
||||
"""为受控路径生成稳定 path_id。"""
|
||||
digest = hashlib.sha256(data_path.encode('utf-8')).hexdigest()[:16]
|
||||
return f'path-{digest}'
|
||||
|
||||
|
||||
def _hardened_parser() -> etree.XMLParser:
|
||||
"""构造禁用外部实体与 DTD 的 lxml 解析器。"""
|
||||
return etree.XMLParser(
|
||||
resolve_entities=False,
|
||||
load_dtd=False,
|
||||
no_network=True,
|
||||
huge_tree=False,
|
||||
)
|
||||
|
||||
|
||||
def _iter_element_nodes(root: etree._Element) -> list[tuple[etree._Element, int]]:
|
||||
"""
|
||||
深度优先遍历元素节点并附带深度。
|
||||
|
||||
Args:
|
||||
root: XML 根元素。
|
||||
|
||||
Returns:
|
||||
(element, depth) 列表;depth 从 1 开始。
|
||||
"""
|
||||
result: list[tuple[etree._Element, int]] = []
|
||||
|
||||
def _walk(node: etree._Element, depth: int) -> None:
|
||||
result.append((node, depth))
|
||||
for child in node:
|
||||
if isinstance(child.tag, str):
|
||||
_walk(child, depth + 1)
|
||||
|
||||
_walk(root, 1)
|
||||
return result
|
||||
|
||||
|
||||
def _detect_cardinality(element: etree._Element) -> _CARDINALITY:
|
||||
"""
|
||||
根据同级重复 localName 判断基数。
|
||||
|
||||
核心逻辑:DATA 行容器在结构层始终视为 many,使明细行数量变化不影响指纹。
|
||||
"""
|
||||
local = _local_name(element.tag)
|
||||
if local.upper() == 'DATA':
|
||||
return 'many'
|
||||
if element.getparent() is None:
|
||||
return 'one'
|
||||
siblings = [
|
||||
_local_name(item.tag)
|
||||
for item in element.getparent()
|
||||
if isinstance(item.tag, str)
|
||||
]
|
||||
return 'many' if siblings.count(local) > 1 else 'one'
|
||||
|
||||
|
||||
def _build_tree(
|
||||
element: etree._Element,
|
||||
*,
|
||||
parent_path: str,
|
||||
depth: int,
|
||||
limits: dict[str, int],
|
||||
counters: dict[str, int],
|
||||
leaf_values: dict[str, str],
|
||||
) -> XfaDatasetNode:
|
||||
"""
|
||||
递归构建受控路径树。
|
||||
|
||||
Args:
|
||||
element: 当前 XML 元素。
|
||||
parent_path: 父级受控路径。
|
||||
depth: 当前深度。
|
||||
limits: 资源上限。
|
||||
counters: 可变计数器(node_count、max_depth、line_rows)。
|
||||
leaf_values: 输出叶子原值映射(仅内部使用,不外泄)。
|
||||
|
||||
Returns:
|
||||
XfaDatasetNode 子树。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 深度/节点/行数超限。
|
||||
"""
|
||||
local = _local_name(element.tag)
|
||||
data_path = validate_controlled_data_path(f'{parent_path}/{local}' if parent_path else f'/{local}')
|
||||
counters['node_count'] = int(counters.get('node_count', 0)) + 1
|
||||
counters['max_depth'] = max(int(counters.get('max_depth', 0)), depth)
|
||||
if counters['node_count'] > limits['max_xml_nodes']:
|
||||
raise XfaDatasetParseError(
|
||||
error_code='XFA_XML_NODE_LIMIT_EXCEEDED',
|
||||
route_reason='xfa_xml_node_limit_exceeded',
|
||||
)
|
||||
if depth > limits['max_xml_depth']:
|
||||
raise XfaDatasetParseError(
|
||||
error_code='XFA_XML_DEPTH_EXCEEDED',
|
||||
route_reason='xfa_xml_depth_exceeded',
|
||||
)
|
||||
|
||||
element_children = [child for child in element if isinstance(child.tag, str)]
|
||||
is_leaf = not element_children
|
||||
cardinality = _detect_cardinality(element)
|
||||
masked_value: str | None = None
|
||||
raw_value: str | None = None
|
||||
normalized_value: str | None = None
|
||||
lines: list[str] = []
|
||||
if is_leaf:
|
||||
leaf = build_xfa_leaf_value(''.join(element.itertext()))
|
||||
leaf_values[data_path] = leaf.raw_value
|
||||
raw_value = leaf.raw_value
|
||||
normalized_value = leaf.normalized_value
|
||||
lines = list(leaf.lines)
|
||||
masked_value = mask_sample_value(leaf.normalized_value) if leaf.normalized_value else ''
|
||||
display = xfa_mapping_sample_display(local, leaf.normalized_value)
|
||||
else:
|
||||
display = {'display_value': '', 'display_policy': 'empty', 'can_reveal': False}
|
||||
|
||||
child_nodes: list[XfaDatasetNode] = []
|
||||
for child in element_children:
|
||||
child_nodes.append(
|
||||
_build_tree(
|
||||
child,
|
||||
parent_path=data_path,
|
||||
depth=depth + 1,
|
||||
limits=limits,
|
||||
counters=counters,
|
||||
leaf_values=leaf_values,
|
||||
),
|
||||
)
|
||||
|
||||
return XfaDatasetNode(
|
||||
path_id=_path_id_for(data_path),
|
||||
local_name=local,
|
||||
namespace_uri=_namespace_uri(element.tag),
|
||||
data_path=data_path,
|
||||
depth=depth,
|
||||
cardinality=cardinality,
|
||||
is_leaf=is_leaf,
|
||||
sample_value_masked=masked_value,
|
||||
sample_value_display=str(display['display_value']),
|
||||
display_policy=str(display['display_policy']),
|
||||
can_reveal=bool(display['can_reveal']),
|
||||
raw_value=raw_value,
|
||||
normalized_value=normalized_value,
|
||||
lines=lines,
|
||||
children=child_nodes,
|
||||
)
|
||||
|
||||
|
||||
def _mark_header_candidates(root: XfaDatasetNode) -> list[dict[str, Any]]:
|
||||
"""
|
||||
识别 Header 候选:位于 HEADER 子树下的叶子节点。
|
||||
|
||||
Args:
|
||||
root: 数据集根节点。
|
||||
|
||||
Returns:
|
||||
Header 候选摘要列表。
|
||||
"""
|
||||
candidates: list[dict[str, Any]] = []
|
||||
|
||||
def _walk(node: XfaDatasetNode, under_header: bool) -> None:
|
||||
in_header = under_header or node.local_name.upper() == 'HEADER'
|
||||
if in_header and node.is_leaf:
|
||||
node.is_header_candidate = True
|
||||
candidates.append({
|
||||
'path_id': node.path_id,
|
||||
'data_path_hash': hash_data_path(node.data_path),
|
||||
'local_name': node.local_name,
|
||||
'value_type': 'string',
|
||||
'sample_value_masked': node.sample_value_masked or '',
|
||||
})
|
||||
for child in node.children:
|
||||
_walk(child, in_header)
|
||||
|
||||
_walk(root, False)
|
||||
return candidates
|
||||
|
||||
|
||||
def _is_line_row_container(node: XfaDatasetNode) -> bool:
|
||||
"""判断 DATA 节点是否表现为明细行容器(子节点均为叶子字段)。"""
|
||||
if node.local_name.upper() != 'DATA':
|
||||
return False
|
||||
if not node.children:
|
||||
return node.is_leaf
|
||||
return all(child.is_leaf for child in node.children)
|
||||
|
||||
|
||||
def _mark_collection_candidates(
|
||||
root: XfaDatasetNode,
|
||||
*,
|
||||
limits: dict[str, int],
|
||||
) -> list[XfaCollectionCandidate]:
|
||||
"""
|
||||
识别独立重复集合候选,例如 ITEMS/DATA 与 ITEMS1/DATA。
|
||||
|
||||
核心逻辑:在每个父节点下查找 DATA 行容器;同一父下多行 DATA 只登记一次候选,
|
||||
row_count 为行数;ITEMS 与 ITEMS1 视为互不合并的独立集合。
|
||||
|
||||
Args:
|
||||
root: 数据集根节点。
|
||||
limits: 资源上限(用于行数统计)。
|
||||
|
||||
Returns:
|
||||
集合候选列表。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 明细行数超过上限。
|
||||
"""
|
||||
candidates: list[XfaCollectionCandidate] = []
|
||||
total_line_rows = 0
|
||||
|
||||
def _walk(node: XfaDatasetNode) -> None:
|
||||
nonlocal total_line_rows
|
||||
data_children = [child for child in node.children if _is_line_row_container(child)]
|
||||
if data_children:
|
||||
sibling_paths = [item.data_path for item in data_children]
|
||||
total_line_rows += len(data_children)
|
||||
if total_line_rows > limits['max_line_rows']:
|
||||
raise XfaDatasetParseError(
|
||||
error_code='XFA_LINE_ROW_LIMIT_EXCEEDED',
|
||||
route_reason='xfa_line_row_limit_exceeded',
|
||||
)
|
||||
# 同一父节点下多行 DATA 共享同一集合路径;候选只登记一次,row_count=行数。
|
||||
for data_node in data_children:
|
||||
data_node.is_collection_candidate = True
|
||||
first = data_children[0]
|
||||
candidates.append(XfaCollectionCandidate(
|
||||
collection_path=first.data_path,
|
||||
path_id=first.path_id,
|
||||
row_count=len(data_children),
|
||||
sibling_collection_paths=sibling_paths,
|
||||
))
|
||||
for child in node.children:
|
||||
_walk(child)
|
||||
|
||||
_walk(root)
|
||||
return candidates
|
||||
|
||||
|
||||
def _collect_known_path_ids(node: XfaDatasetNode) -> set[str]:
|
||||
"""递归收集全部 path_id。"""
|
||||
ids = {node.path_id}
|
||||
for child in node.children:
|
||||
ids.update(_collect_known_path_ids(child))
|
||||
return ids
|
||||
|
||||
|
||||
def parse_xfa_datasets(
|
||||
xml_bytes: bytes,
|
||||
*,
|
||||
limits: dict[str, int] | None = None,
|
||||
) -> XfaDatasetAnalysis:
|
||||
"""
|
||||
安全解析 XFA datasets XML 并生成结构分析。
|
||||
|
||||
Args:
|
||||
xml_bytes: datasets packet 原始字节。
|
||||
limits: 可选 max_xml_depth/max_xml_nodes/max_line_rows 覆盖。
|
||||
|
||||
Returns:
|
||||
XfaDatasetAnalysis:含路径树、Header/集合候选与统计。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 不安全 XML 或资源超限。
|
||||
"""
|
||||
resolved = {
|
||||
'max_xml_depth': XFA_DEFAULT_MAX_XML_DEPTH,
|
||||
'max_xml_nodes': XFA_DEFAULT_MAX_XML_NODES,
|
||||
'max_line_rows': XFA_DEFAULT_MAX_LINE_ROWS,
|
||||
}
|
||||
if isinstance(limits, dict):
|
||||
resolved.update({key: int(limits[key]) for key in resolved if key in limits})
|
||||
|
||||
try:
|
||||
preflight_xml_bytes(xml_bytes)
|
||||
except XfaPacketError as exc:
|
||||
raise XfaDatasetParseError(
|
||||
error_code=exc.error_code,
|
||||
route_reason=exc.route_reason,
|
||||
message=str(exc),
|
||||
) from exc
|
||||
parser = _hardened_parser()
|
||||
try:
|
||||
root_element = etree.fromstring(xml_bytes, parser=parser)
|
||||
except etree.XMLSyntaxError as exc:
|
||||
raise XfaDatasetParseError(
|
||||
error_code='XFA_UNSAFE_XML',
|
||||
route_reason='xfa_unsafe_xml',
|
||||
message='xml syntax error',
|
||||
) from exc
|
||||
|
||||
counters: dict[str, int] = {'node_count': 0, 'max_depth': 0}
|
||||
leaf_values: dict[str, str] = {}
|
||||
dataset_root_path = validate_controlled_data_path(f"/{_local_name(root_element.tag)}")
|
||||
root_node = _build_tree(
|
||||
root_element,
|
||||
parent_path='',
|
||||
depth=1,
|
||||
limits=resolved,
|
||||
counters=counters,
|
||||
leaf_values=leaf_values,
|
||||
)
|
||||
header_candidates = _mark_header_candidates(root_node)
|
||||
collection_candidates = _mark_collection_candidates(root_node, limits=resolved)
|
||||
known_path_ids = _collect_known_path_ids(root_node)
|
||||
|
||||
stats = {
|
||||
'node_count': counters['node_count'],
|
||||
'max_depth': counters['max_depth'],
|
||||
'leaf_count': len(leaf_values),
|
||||
'header_candidate_count': len(header_candidates),
|
||||
'collection_candidate_count': len(collection_candidates),
|
||||
'line_row_count': sum(item.row_count for item in collection_candidates),
|
||||
}
|
||||
return XfaDatasetAnalysis(
|
||||
dataset_root_path=dataset_root_path,
|
||||
nodes=[root_node],
|
||||
header_candidates=header_candidates,
|
||||
collection_candidates=collection_candidates,
|
||||
stats=stats,
|
||||
leaf_values_by_path=leaf_values,
|
||||
known_path_ids=known_path_ids,
|
||||
)
|
||||
|
||||
|
||||
def read_dataset_value(analysis: XfaDatasetAnalysis, data_path: str) -> str | None:
|
||||
"""
|
||||
按受控路径读取 datasets 叶子原值(保留换行)。
|
||||
|
||||
Args:
|
||||
analysis: 已完成的 datasets 分析。
|
||||
data_path: 绝对受控路径。
|
||||
|
||||
Returns:
|
||||
叶子 raw_value 或 None(路径不存在/非叶子)。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 路径语法非法。
|
||||
"""
|
||||
leaf = read_dataset_leaf_value(analysis, data_path)
|
||||
return None if leaf is None else leaf.raw_value
|
||||
|
||||
|
||||
def read_dataset_leaf_value(analysis: XfaDatasetAnalysis, data_path: str) -> XfaLeafValue | None:
|
||||
"""
|
||||
按受控路径读取叶子三层中间表示。
|
||||
|
||||
核心逻辑:优先从内存树节点取 raw/normalized/lines;若仅有 leaf map 则重建。
|
||||
|
||||
Args:
|
||||
analysis: 已完成的 datasets 分析。
|
||||
data_path: 绝对受控路径。
|
||||
|
||||
Returns:
|
||||
XfaLeafValue;路径不存在时 None。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 路径语法非法。
|
||||
"""
|
||||
normalized = validate_controlled_data_path(data_path)
|
||||
for root in analysis.nodes or []:
|
||||
for node in _iter_nodes(root):
|
||||
if node.data_path == normalized and node.is_leaf:
|
||||
return XfaLeafValue(
|
||||
raw_value=str(node.raw_value or ''),
|
||||
normalized_value=str(node.normalized_value or ''),
|
||||
lines=list(node.lines or []),
|
||||
)
|
||||
raw = analysis.leaf_values_by_path.get(normalized)
|
||||
if raw is None:
|
||||
return None
|
||||
return build_xfa_leaf_value(raw)
|
||||
|
||||
|
||||
def _iter_nodes(node: XfaDatasetNode) -> list[XfaDatasetNode]:
|
||||
"""深度优先展开路径树节点。"""
|
||||
result = [node]
|
||||
for child in node.children:
|
||||
result.extend(_iter_nodes(child))
|
||||
return result
|
||||
|
||||
|
||||
def read_collection_rows(
|
||||
analysis: XfaDatasetAnalysis,
|
||||
collection_path: str,
|
||||
) -> list[dict[str, str]]:
|
||||
"""
|
||||
按权威/镜像集合路径读取每一行叶子字段原值。
|
||||
|
||||
核心逻辑:查找 data_path 等于集合路径的全部 DATA 行容器;每行以
|
||||
子叶子的绝对受控路径为键返回原值。同路径多行互不覆盖(与 leaf_values_by_path 不同)。
|
||||
|
||||
Args:
|
||||
analysis: 已完成的 datasets 分析。
|
||||
collection_path: 权威或镜像集合绝对路径(如 /data/ITEMS/DATA)。
|
||||
|
||||
Returns:
|
||||
行字典列表;集合不存在时返回空列表。
|
||||
|
||||
Raises:
|
||||
XfaDatasetParseError: 路径语法非法。
|
||||
"""
|
||||
normalized = validate_controlled_data_path(collection_path)
|
||||
rows: list[dict[str, str]] = []
|
||||
roots = list(analysis.nodes or [])
|
||||
for root in roots:
|
||||
for node in _iter_nodes(root):
|
||||
if node.data_path != normalized or not _is_line_row_container(node):
|
||||
continue
|
||||
row: dict[str, str] = {}
|
||||
for child in node.children:
|
||||
if child.is_leaf:
|
||||
row[child.data_path] = str(child.raw_value or '')
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -> dict[str, Any]:
|
||||
"""
|
||||
序列化单个树节点供 API 返回。
|
||||
|
||||
Args:
|
||||
node: 数据集树节点。
|
||||
include_values: 是否包含脱敏样本值。
|
||||
|
||||
Returns:
|
||||
安全 DTO 字典。
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
'path_id': node.path_id,
|
||||
'local_name': node.local_name,
|
||||
'namespace_uri': node.namespace_uri,
|
||||
'data_path_hash': hash_data_path(node.data_path),
|
||||
'depth': node.depth,
|
||||
'cardinality': node.cardinality,
|
||||
'is_leaf': node.is_leaf,
|
||||
'is_header_candidate': node.is_header_candidate,
|
||||
'is_collection_candidate': node.is_collection_candidate,
|
||||
'children': [serialize_tree_node(child, include_values=include_values) for child in node.children],
|
||||
}
|
||||
if include_values and node.is_leaf:
|
||||
payload['sample_value_masked'] = node.sample_value_masked or ''
|
||||
payload['sample_value_display'] = node.sample_value_display or ''
|
||||
payload['display_policy'] = node.display_policy
|
||||
payload['can_reveal'] = bool(node.can_reveal)
|
||||
# 仅暴露行数,不返回 lines 原文(完整值走受控 reveal)。
|
||||
payload['line_count'] = len(node.lines or [])
|
||||
return payload
|
||||
|
||||
|
||||
def mask_value_for_dto(value: Any) -> str:
|
||||
"""
|
||||
将业务原值转为 DTO 允许返回的脱敏字符串。
|
||||
|
||||
Args:
|
||||
value: 任意原值。
|
||||
|
||||
Returns:
|
||||
脱敏字符串。
|
||||
"""
|
||||
return mask_sample_value(value)
|
||||
@@ -0,0 +1,367 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_packets.py
|
||||
|
||||
用途:从 PDF 读取 AcroForm/XFA packet,识别文档类型并返回受控 packet 摘要。
|
||||
依赖:pypdf、xfa_contract 资源上限与文档类型枚举。
|
||||
逻辑:由 runtime 与 layout Job 在 MinerU 前调用;只读 packet 字节,不执行脚本、不联网。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from dataclasses import dataclass, field
|
||||
from io import BytesIO
|
||||
from typing import Any, Literal
|
||||
|
||||
from pypdf import PdfReader
|
||||
from pypdf.errors import PdfReadError
|
||||
from pypdf.generic import ArrayObject, IndirectObject, StreamObject
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_DEFAULT_MAX_PACKET_BYTES,
|
||||
XFA_DEFAULT_MAX_PDF_BYTES,
|
||||
XFA_SUPPORTED_DOCUMENT_KINDS,
|
||||
XfaDocumentKind,
|
||||
default_xfa_resource_limits,
|
||||
)
|
||||
|
||||
XFA_PACKET_NAMES = frozenset({
|
||||
'template',
|
||||
'datasets',
|
||||
'config',
|
||||
'templateCache',
|
||||
'xfdf',
|
||||
'xslt',
|
||||
'pdf',
|
||||
'form',
|
||||
})
|
||||
|
||||
_UNSAFE_XML_MARKERS = re.compile(
|
||||
r'<!DOCTYPE|<!ENTITY|&[A-Za-z_][A-Za-z0-9_-]*;|<!ELEMENT|<!ATTLIST',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class XfaPacket:
|
||||
"""单个 XFA packet 的受控摘要;不含持久化所需的完整 XML 外泄面。"""
|
||||
|
||||
name: str
|
||||
byte_length: int
|
||||
checksum: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaPacketReadResult:
|
||||
"""XFA packet 读取结果。"""
|
||||
|
||||
document_kind: XfaDocumentKind
|
||||
packets: list[XfaPacket] = field(default_factory=list)
|
||||
packet_bytes_by_name: dict[str, bytes] = field(default_factory=dict)
|
||||
has_acroform: bool = False
|
||||
has_acroform_fields: bool = False
|
||||
has_xfa: bool = False
|
||||
page_count: int = 0
|
||||
error_code: str | None = None
|
||||
route_reason: str | None = None
|
||||
supported: bool = False
|
||||
|
||||
|
||||
class XfaPacketError(Exception):
|
||||
"""XFA packet 读取阶段的确定性业务失败。"""
|
||||
|
||||
def __init__(self, *, error_code: str, route_reason: str, message: str = '') -> None:
|
||||
super().__init__(message or error_code)
|
||||
self.error_code = error_code
|
||||
self.route_reason = route_reason
|
||||
|
||||
|
||||
def compute_packet_checksum(packet_bytes: bytes) -> str:
|
||||
"""
|
||||
计算 packet 稳定 SHA-256 校验和。
|
||||
|
||||
Args:
|
||||
packet_bytes: 原始 packet 字节。
|
||||
|
||||
Returns:
|
||||
带 `sha256:` 前缀的十六进制摘要。
|
||||
"""
|
||||
return f'sha256:{hashlib.sha256(packet_bytes).hexdigest()}'
|
||||
|
||||
|
||||
def _resolve_limits(limits: dict[str, int] | None) -> dict[str, int]:
|
||||
"""合并调用方 limits 与契约默认值。"""
|
||||
merged = default_xfa_resource_limits()
|
||||
if isinstance(limits, dict):
|
||||
merged.update({key: int(value) for key, value in limits.items() if key in merged})
|
||||
return merged
|
||||
|
||||
|
||||
def _stream_bytes(value: Any) -> bytes:
|
||||
"""从 pypdf StreamObject 或原始 bytes/str 提取 packet 字节。"""
|
||||
if isinstance(value, bytes):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
return value.encode('utf-8', errors='ignore')
|
||||
if isinstance(value, StreamObject):
|
||||
raw = value.get_data()
|
||||
return raw if isinstance(raw, bytes) else bytes(raw or b'')
|
||||
if isinstance(value, IndirectObject):
|
||||
resolved = value.get_object()
|
||||
return _stream_bytes(resolved)
|
||||
return bytes(value or b'')
|
||||
|
||||
|
||||
def _collect_xfa_packets_from_reader(
|
||||
reader: PdfReader,
|
||||
*,
|
||||
max_packet_bytes: int,
|
||||
) -> tuple[dict[str, bytes], list[XfaPacket], str | None]:
|
||||
"""
|
||||
从 PdfReader 提取命名 XFA packet。
|
||||
|
||||
核心逻辑:兼容 pypdf 的 reader.xfa 字典与 AcroForm `/XFA` 数组/单流两种容器形态。
|
||||
|
||||
Args:
|
||||
reader: 已打开的 PDF 阅读器。
|
||||
max_packet_bytes: 单 packet 字节上限。
|
||||
|
||||
Returns:
|
||||
(packet_bytes_by_name, packet_summaries, error_code)。
|
||||
"""
|
||||
packet_bytes: dict[str, bytes] = {}
|
||||
summaries: list[XfaPacket] = []
|
||||
|
||||
def _register(name: str, payload: bytes) -> str | None:
|
||||
normalized_name = str(name or '').strip()
|
||||
if not normalized_name:
|
||||
return None
|
||||
if len(payload) > max_packet_bytes:
|
||||
return 'XFA_PACKET_TOO_LARGE'
|
||||
checksum = compute_packet_checksum(payload)
|
||||
packet_bytes[normalized_name] = payload
|
||||
summaries.append(XfaPacket(name=normalized_name, byte_length=len(payload), checksum=checksum))
|
||||
return None
|
||||
|
||||
xfa_obj = getattr(reader, 'xfa', None)
|
||||
xfa_map = xfa_obj if isinstance(xfa_obj, dict) else getattr(xfa_obj, 'xfa', None)
|
||||
if isinstance(xfa_map, dict) and xfa_map:
|
||||
for name, payload in xfa_map.items():
|
||||
error_code = _register(str(name), _stream_bytes(payload))
|
||||
if error_code:
|
||||
return packet_bytes, summaries, error_code
|
||||
|
||||
try:
|
||||
root = reader.trailer.get('/Root') or reader.trailer['/Root']
|
||||
acroform = root.get('/AcroForm') if hasattr(root, 'get') else None
|
||||
if acroform is not None and hasattr(acroform, 'get_object'):
|
||||
acroform = acroform.get_object()
|
||||
xfa_ref = acroform.get('/XFA') if isinstance(acroform, dict) or hasattr(acroform, 'get') else None
|
||||
if xfa_ref is not None and hasattr(xfa_ref, 'get_object'):
|
||||
xfa_ref = xfa_ref.get_object()
|
||||
except Exception:
|
||||
xfa_ref = None
|
||||
|
||||
if isinstance(xfa_ref, ArrayObject):
|
||||
index = 0
|
||||
while index < len(xfa_ref):
|
||||
name_obj = xfa_ref[index]
|
||||
index += 1
|
||||
if index >= len(xfa_ref):
|
||||
break
|
||||
payload_obj = xfa_ref[index]
|
||||
index += 1
|
||||
name = str(getattr(name_obj, 'name', name_obj) or name_obj or '').strip().lstrip('/')
|
||||
error_code = _register(name, _stream_bytes(payload_obj))
|
||||
if error_code:
|
||||
return packet_bytes, summaries, error_code
|
||||
elif xfa_ref is not None and not packet_bytes:
|
||||
error_code = _register('xfa', _stream_bytes(xfa_ref))
|
||||
if error_code:
|
||||
return packet_bytes, summaries, error_code
|
||||
|
||||
return packet_bytes, summaries, None
|
||||
|
||||
|
||||
def _has_acroform_fields(reader: PdfReader) -> bool:
|
||||
"""判断 AcroForm 是否包含可读取字段。"""
|
||||
try:
|
||||
fields = reader.get_fields() or {}
|
||||
return bool(fields)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _detect_document_kind(
|
||||
*,
|
||||
has_acroform: bool,
|
||||
has_xfa: bool,
|
||||
has_datasets: bool,
|
||||
page_count: int,
|
||||
has_acroform_fields: bool,
|
||||
) -> XfaDocumentKind:
|
||||
"""
|
||||
根据 PDF 结构探测 document_kind。
|
||||
|
||||
Args:
|
||||
has_acroform: 是否存在 AcroForm 字典。
|
||||
has_xfa: 是否检测到 XFA packet 容器。
|
||||
has_datasets: 是否包含 datasets packet。
|
||||
page_count: 页面数。
|
||||
has_acroform_fields: 是否存在 AcroForm 字段。
|
||||
|
||||
Returns:
|
||||
plain_pdf | acroform | xfa_hybrid | pure_xfa | unsupported。
|
||||
"""
|
||||
if not has_xfa:
|
||||
if has_acroform and has_acroform_fields:
|
||||
return 'acroform'
|
||||
return 'plain_pdf'
|
||||
if not has_datasets:
|
||||
return 'unsupported'
|
||||
if page_count > 0 or has_acroform_fields:
|
||||
return 'xfa_hybrid'
|
||||
return 'pure_xfa'
|
||||
|
||||
|
||||
def read_xfa_packets(
|
||||
pdf_bytes: bytes,
|
||||
*,
|
||||
limits: dict[str, int] | None = None,
|
||||
) -> XfaPacketReadResult:
|
||||
"""
|
||||
读取 PDF 中的 XFA packet 并识别文档类型。
|
||||
|
||||
核心逻辑:先校验 PDF 总大小,再用 pypdf 只读 AcroForm/XFA;不执行 JavaScript/FormCalc,
|
||||
不触发任何网络访问。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 原始 PDF 字节。
|
||||
limits: 可选资源上限覆盖项。
|
||||
|
||||
Returns:
|
||||
XfaPacketReadResult:含 packet 摘要、document_kind 与支持标记。
|
||||
|
||||
Raises:
|
||||
XfaPacketError: PDF 损坏或 packet 超限等确定性失败。
|
||||
"""
|
||||
resolved = _resolve_limits(limits)
|
||||
if len(pdf_bytes) > resolved['max_pdf_bytes']:
|
||||
raise XfaPacketError(
|
||||
error_code='XFA_PACKET_TOO_LARGE',
|
||||
route_reason='xfa_packet_too_large',
|
||||
message='pdf exceeds max_pdf_bytes',
|
||||
)
|
||||
if not pdf_bytes:
|
||||
raise XfaPacketError(
|
||||
error_code='XFA_UNSUPPORTED_DOCUMENT',
|
||||
route_reason='xfa_unsupported_document',
|
||||
message='empty pdf',
|
||||
)
|
||||
|
||||
try:
|
||||
reader = PdfReader(BytesIO(pdf_bytes), strict=False)
|
||||
except PdfReadError as exc:
|
||||
raise XfaPacketError(
|
||||
error_code='XFA_UNSUPPORTED_DOCUMENT',
|
||||
route_reason='xfa_unsupported_document',
|
||||
message='pdf unreadable',
|
||||
) from exc
|
||||
|
||||
page_count = len(reader.pages)
|
||||
has_acroform = False
|
||||
try:
|
||||
root = reader.trailer.get('/Root') or reader.trailer['/Root']
|
||||
acroform = root.get('/AcroForm') if hasattr(root, 'get') else None
|
||||
has_acroform = acroform is not None
|
||||
except Exception:
|
||||
has_acroform = False
|
||||
|
||||
packet_bytes, summaries, packet_error = _collect_xfa_packets_from_reader(
|
||||
reader,
|
||||
max_packet_bytes=int(resolved['max_packet_bytes']),
|
||||
)
|
||||
if packet_error:
|
||||
route = 'xfa_packet_too_large' if packet_error == 'XFA_PACKET_TOO_LARGE' else 'xfa_unsupported_document'
|
||||
raise XfaPacketError(error_code=packet_error, route_reason=route)
|
||||
|
||||
has_xfa = bool(packet_bytes)
|
||||
has_datasets = 'datasets' in packet_bytes
|
||||
has_acroform_fields = _has_acroform_fields(reader) if has_acroform else False
|
||||
document_kind = _detect_document_kind(
|
||||
has_acroform=has_acroform,
|
||||
has_xfa=has_xfa,
|
||||
has_datasets=has_datasets,
|
||||
page_count=page_count,
|
||||
has_acroform_fields=has_acroform_fields,
|
||||
)
|
||||
supported = document_kind in XFA_SUPPORTED_DOCUMENT_KINDS
|
||||
error_code: str | None = None
|
||||
route_reason: str | None = None
|
||||
if has_xfa and not has_datasets:
|
||||
error_code = 'XFA_DATASET_MISSING'
|
||||
route_reason = 'xfa_dataset_missing'
|
||||
elif document_kind == 'pure_xfa':
|
||||
error_code = 'XFA_UNSUPPORTED_DOCUMENT'
|
||||
route_reason = 'xfa_unsupported_document'
|
||||
elif document_kind == 'unsupported':
|
||||
error_code = 'XFA_UNSUPPORTED_DOCUMENT'
|
||||
route_reason = 'xfa_unsupported_document'
|
||||
|
||||
return XfaPacketReadResult(
|
||||
document_kind=document_kind,
|
||||
packets=summaries,
|
||||
packet_bytes_by_name=packet_bytes,
|
||||
has_acroform=has_acroform,
|
||||
has_acroform_fields=has_acroform_fields,
|
||||
has_xfa=has_xfa,
|
||||
page_count=page_count,
|
||||
error_code=error_code,
|
||||
route_reason=route_reason,
|
||||
supported=supported,
|
||||
)
|
||||
|
||||
|
||||
def preflight_xml_bytes(xml_bytes: bytes) -> None:
|
||||
"""
|
||||
在 lxml 解析前拒绝 DOCTYPE/ENTITY 等不安全标记。
|
||||
|
||||
Args:
|
||||
xml_bytes: 待解析 XML 字节。
|
||||
|
||||
Raises:
|
||||
XfaPacketError: 检测到不安全 XML 结构。
|
||||
"""
|
||||
sample = xml_bytes[:65536].decode('utf-8', errors='ignore')
|
||||
if _UNSAFE_XML_MARKERS.search(sample):
|
||||
raise XfaPacketError(
|
||||
error_code='XFA_UNSAFE_XML',
|
||||
route_reason='xfa_unsafe_xml',
|
||||
message='unsafe xml marker detected',
|
||||
)
|
||||
|
||||
|
||||
def is_deterministic_xfa_error(error_code: str | None) -> bool:
|
||||
"""
|
||||
判断 XFA 错误码是否属于确定性业务失败(不应重试)。
|
||||
|
||||
Args:
|
||||
error_code: XFA_ERROR_CODES 中的稳定错误码。
|
||||
|
||||
Returns:
|
||||
True 表示 Worker 不应重试。
|
||||
"""
|
||||
deterministic = {
|
||||
'XFA_DATASET_MISSING',
|
||||
'XFA_UNSAFE_XML',
|
||||
'XFA_PACKET_TOO_LARGE',
|
||||
'XFA_XML_DEPTH_EXCEEDED',
|
||||
'XFA_XML_NODE_LIMIT_EXCEEDED',
|
||||
'XFA_LINE_ROW_LIMIT_EXCEEDED',
|
||||
'XFA_UNSUPPORTED_DOCUMENT',
|
||||
'XFA_PATH_INVALID',
|
||||
'XFA_PATH_UNKNOWN',
|
||||
'XFA_DEFINITION_INVALID',
|
||||
}
|
||||
return str(error_code or '') in deterministic
|
||||
@@ -0,0 +1,761 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_profile_extraction.py
|
||||
|
||||
用途:按冻结 published XFA Profile 路径映射提取 Header/Lines,并产出安全 evidence refs。
|
||||
依赖:xfa_contract、xfa_dataset、xfa_split_rule_contract、xfa_split_rule_engine、
|
||||
order_schema.field_rules、order_profile_extractors、XfaProfileMatchResult。
|
||||
逻辑:由 order_extraction_workflow XFA 分支在精确命中后调用;失败由上层回退坐标/OCR/通用;
|
||||
普通结果不含完整 XML / 明文路径;NETPR ``单价 / 价格单位`` 确定性拆分为 unit_price + price_unit;
|
||||
多行源字段经已确认 split_rules 引擎产出 mapped 字段与 evidence_only 段(非 Schema 字段)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.order_profile_extractors import (
|
||||
parse_unit_price_with_price_unit,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
OrderXfaDatasetProfile,
|
||||
XfaFieldEvidenceRef,
|
||||
XFA_PARSER_IDENTITY,
|
||||
hash_data_path,
|
||||
sanitize_xfa_dto,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import (
|
||||
XfaDatasetAnalysis,
|
||||
read_collection_rows,
|
||||
read_dataset_value,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XfaSplitRuleSet,
|
||||
parse_split_rule_sets,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_engine import (
|
||||
execute_split_rule_set,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaExtractedField:
|
||||
"""单字段提取结果(含内部原始值,对外投影时剥离)。"""
|
||||
|
||||
field_id: str
|
||||
field_code: str
|
||||
mapping_id: str
|
||||
data_path: str
|
||||
raw_value: str | None
|
||||
normalized_value: Any
|
||||
quote: str
|
||||
normalizer_key: str | None
|
||||
evidence: dict[str, Any]
|
||||
issues: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaExtractionResult:
|
||||
"""XFA 正式提取结果;rows 形状对齐坐标路径以便复用订单组装。"""
|
||||
|
||||
status: str
|
||||
reason_codes: list[str] = field(default_factory=list)
|
||||
header_fields: list[XfaExtractedField] = field(default_factory=list)
|
||||
rows: list[dict[str, Any]] = field(default_factory=list)
|
||||
packet_checksum: str | None = None
|
||||
dataset_structure_fingerprint: str | None = None
|
||||
parser_identity: str = XFA_PARSER_IDENTITY
|
||||
profile_checksum: str | None = None
|
||||
evidence_summary: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
def _schema_field_config(
|
||||
*,
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
value_type: str,
|
||||
normalizer_key: str | None,
|
||||
validator_key: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""合并 Schema 字段配置与映射上的类型/normalizer。"""
|
||||
config = dict(schema_fields.get(field_id) or {})
|
||||
if not config:
|
||||
config = {
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'value_type': value_type or 'string',
|
||||
'normalizer_key': normalizer_key or 'trim',
|
||||
'validator_keys': [validator_key] if validator_key else [],
|
||||
}
|
||||
else:
|
||||
config = dict(config)
|
||||
config.setdefault('field_id', field_id)
|
||||
config.setdefault('field_code', field_code)
|
||||
if value_type:
|
||||
config['value_type'] = value_type
|
||||
if normalizer_key:
|
||||
config['normalizer_key'] = normalizer_key
|
||||
if validator_key:
|
||||
keys = list(config.get('validator_keys') or [])
|
||||
if validator_key not in keys:
|
||||
keys.append(validator_key)
|
||||
config['validator_keys'] = keys
|
||||
return config
|
||||
|
||||
|
||||
def _normalize_display_value(value: Any) -> Any:
|
||||
"""
|
||||
将 Decimal/date 收敛为 JSON 可序列化的业务可读形式。
|
||||
|
||||
核心逻辑:整数型 Decimal → int(30.000 → 30);非整数 Decimal → 去尾零字符串;
|
||||
date → ISO 字符串。与订单组装 json.dumps 共识逻辑兼容。
|
||||
"""
|
||||
if isinstance(value, Decimal):
|
||||
normalized = value.normalize()
|
||||
if normalized == normalized.to_integral_value():
|
||||
return int(normalized)
|
||||
text = format(normalized, 'f')
|
||||
if '.' in text:
|
||||
text = text.rstrip('0').rstrip('.')
|
||||
return text
|
||||
if isinstance(value, datetime):
|
||||
return value.date().isoformat()
|
||||
if isinstance(value, date):
|
||||
return value.isoformat()
|
||||
return value
|
||||
|
||||
|
||||
def _build_evidence_ref(
|
||||
*,
|
||||
document_id: int,
|
||||
packet_checksum: str,
|
||||
data_path: str,
|
||||
mapping_id: str,
|
||||
normalized_value: Any,
|
||||
normalizer_key: str | None,
|
||||
cross_check_status: str = 'unavailable',
|
||||
) -> dict[str, Any]:
|
||||
"""构建普通 DTO 允许的字段 evidence(无明文路径/XML)。"""
|
||||
display = normalized_value
|
||||
if isinstance(display, Decimal):
|
||||
display = format(display, 'f')
|
||||
elif display is not None and not isinstance(display, (str, int, float, bool)):
|
||||
display = str(display)
|
||||
ref = XfaFieldEvidenceRef(
|
||||
source='xfa_dataset',
|
||||
document_id=max(int(document_id or 1), 1),
|
||||
packet_checksum=packet_checksum,
|
||||
data_path_hash=hash_data_path(data_path),
|
||||
mapping_id=mapping_id,
|
||||
raw_value_snapshot_ref=None,
|
||||
normalized_value=None if display is None else str(display),
|
||||
normalizer_key=normalizer_key,
|
||||
cross_check_status=cross_check_status, # type: ignore[arg-type]
|
||||
)
|
||||
return sanitize_xfa_dto(ref.model_dump(mode='json'))
|
||||
|
||||
|
||||
def _extract_one_field(
|
||||
*,
|
||||
raw_value: str | None,
|
||||
mapping_id: str,
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
data_path: str,
|
||||
value_type: str,
|
||||
normalizer_key: str | None,
|
||||
validator_key: str | None,
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
document_id: int,
|
||||
packet_checksum: str,
|
||||
) -> XfaExtractedField:
|
||||
"""标准化并校验单个映射字段。"""
|
||||
config = _schema_field_config(
|
||||
schema_fields=schema_fields,
|
||||
field_id=field_id,
|
||||
field_code=field_code,
|
||||
value_type=value_type,
|
||||
normalizer_key=normalizer_key,
|
||||
validator_key=validator_key,
|
||||
)
|
||||
issues: list[str] = []
|
||||
normalized: Any = None
|
||||
if raw_value in (None, ''):
|
||||
issues.append(f'order_profile_field_invalid:{field_code}')
|
||||
else:
|
||||
try:
|
||||
typed = normalize_order_field_value(raw_value, config)
|
||||
except (TypeError, ValueError, ValidationError):
|
||||
typed = None
|
||||
issues.append(f'order_profile_field_invalid:{field_code}')
|
||||
if typed is not None and not validate_order_field_value(typed, config):
|
||||
issues.append(f'order_profile_field_invalid:{field_code}')
|
||||
typed = None
|
||||
if typed is not None:
|
||||
normalized = _normalize_display_value(typed)
|
||||
evidence = _build_evidence_ref(
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
data_path=data_path,
|
||||
mapping_id=mapping_id,
|
||||
normalized_value=normalized,
|
||||
normalizer_key=str(config.get('normalizer_key') or normalizer_key or '') or None,
|
||||
)
|
||||
return XfaExtractedField(
|
||||
field_id=str(config.get('field_id') or field_id),
|
||||
field_code=str(config.get('field_code') or field_code),
|
||||
mapping_id=mapping_id,
|
||||
data_path=data_path,
|
||||
raw_value=raw_value,
|
||||
normalized_value=normalized,
|
||||
quote=str(raw_value or '')[:1000],
|
||||
normalizer_key=str(config.get('normalizer_key') or '') or None,
|
||||
evidence=evidence,
|
||||
issues=issues,
|
||||
)
|
||||
|
||||
|
||||
def _is_formal_ready_split_rule_set(rule_set: XfaSplitRuleSet) -> bool:
|
||||
"""
|
||||
判断拆分规则集是否可用于正式提取。
|
||||
|
||||
核心逻辑:须 confirmed/published、非 requires_confirmation、非 system_suggestion。
|
||||
"""
|
||||
if rule_set.requires_confirmation:
|
||||
return False
|
||||
if rule_set.status not in ('confirmed', 'published'):
|
||||
return False
|
||||
if rule_set.source == 'system_suggestion':
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _build_path_id_to_data_path(profile: OrderXfaDatasetProfile) -> dict[str, str]:
|
||||
"""从 Header/Line 映射构建 path_id → data_path 索引。"""
|
||||
mapping: dict[str, str] = {}
|
||||
for item in profile.header_mappings:
|
||||
if item.path_id and item.data_path:
|
||||
mapping[str(item.path_id)] = str(item.data_path)
|
||||
for item in profile.line_mapping.fields:
|
||||
if item.path_id and item.data_path:
|
||||
mapping[str(item.path_id)] = str(item.data_path)
|
||||
return mapping
|
||||
|
||||
|
||||
def _resolve_split_source_data_path(
|
||||
rule_set: XfaSplitRuleSet,
|
||||
*,
|
||||
line_fields: list[Any],
|
||||
path_id_to_data_path: dict[str, str],
|
||||
) -> str | None:
|
||||
"""
|
||||
解析拆分规则集源字段 data_path。
|
||||
|
||||
核心逻辑:优先使用服务端冻结的 source_data_path,其次按 source_path_id 命中映射;
|
||||
旧定义最后按 data_path 后缀兼容匹配 source_field_code。
|
||||
"""
|
||||
if rule_set.source_data_path:
|
||||
return str(rule_set.source_data_path)
|
||||
path_id = str(rule_set.source_path_id or '')
|
||||
if path_id in path_id_to_data_path:
|
||||
return path_id_to_data_path[path_id]
|
||||
suffix = f'/{rule_set.source_field_code}'
|
||||
for mapping in line_fields:
|
||||
data_path = str(getattr(mapping, 'data_path', '') or '')
|
||||
mapping_path_id = str(getattr(mapping, 'path_id', '') or '')
|
||||
if mapping_path_id == path_id or data_path.endswith(suffix):
|
||||
return data_path or None
|
||||
return None
|
||||
|
||||
|
||||
def _apply_split_rules_for_header(
|
||||
*,
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
rule_sets: list[XfaSplitRuleSet],
|
||||
path_id_to_data_path: dict[str, str],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
schema_by_code: dict[str, dict[str, Any]],
|
||||
document_id: int,
|
||||
packet_checksum: str,
|
||||
) -> tuple[list[XfaExtractedField], list[dict[str, Any]], list[str], bool]:
|
||||
"""
|
||||
对文档级源字段执行拆分规则一次。
|
||||
|
||||
Returns:
|
||||
(header_fields, split_evidence, issues, required_missing)
|
||||
"""
|
||||
fields: list[XfaExtractedField] = []
|
||||
evidence: list[dict[str, Any]] = []
|
||||
issues: list[str] = []
|
||||
required_missing = False
|
||||
for rule_set in rule_sets:
|
||||
data_path = _resolve_split_source_data_path(
|
||||
rule_set,
|
||||
line_fields=[],
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
)
|
||||
if not data_path:
|
||||
issues.append('xfa_split_rule_unconfirmed')
|
||||
continue
|
||||
raw_value = read_dataset_value(dataset_analysis, data_path)
|
||||
split_result = execute_split_rule_set(raw_value=raw_value or '', rule_set=rule_set)
|
||||
if split_result.status != 'parsed':
|
||||
issues.append('xfa_split_rule_needs_review')
|
||||
issues.extend(
|
||||
f'xfa_split:{item.code}' for item in split_result.diagnostics if item.code
|
||||
)
|
||||
for segment in split_result.evidence_only_segments:
|
||||
evidence.append({
|
||||
'segment_id': segment.segment_id,
|
||||
'segment_code': segment.segment_code,
|
||||
'display_name': segment.display_name,
|
||||
'line_no': segment.line_no,
|
||||
'line_end_no': segment.line_end_no,
|
||||
'raw_text': segment.raw_text,
|
||||
'normalized_text': segment.normalized_text,
|
||||
'rule_id': segment.rule_id,
|
||||
'source_path_id': rule_set.source_path_id,
|
||||
})
|
||||
for field_code, mapped_raw in split_result.mapped_fields.items():
|
||||
cfg = schema_by_code.get(field_code) or {}
|
||||
extracted = _extract_one_field(
|
||||
raw_value=mapped_raw,
|
||||
mapping_id=f'split-{rule_set.rule_id}-{field_code}'[:64],
|
||||
field_id=str(cfg.get('field_id') or field_code),
|
||||
field_code=field_code,
|
||||
data_path=data_path,
|
||||
value_type=str(cfg.get('value_type') or 'string'),
|
||||
normalizer_key=str(cfg.get('normalizer_key') or 'trim') or None,
|
||||
validator_key=(cfg.get('validator_keys') or [None])[0],
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
fields.append(extracted)
|
||||
issues.extend(extracted.issues)
|
||||
if extracted.normalized_value is None:
|
||||
required_missing = True
|
||||
return fields, evidence, issues, required_missing
|
||||
|
||||
|
||||
def _schema_by_field_code(schema_fields: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]:
|
||||
"""field_code → Schema 配置。"""
|
||||
indexed: dict[str, dict[str, Any]] = {}
|
||||
for item in schema_fields.values():
|
||||
code = str(item.get('field_code') or '').strip()
|
||||
if code:
|
||||
indexed[code] = item
|
||||
return indexed
|
||||
|
||||
|
||||
def _apply_split_rules_for_row(
|
||||
*,
|
||||
row_values: dict[str, str],
|
||||
rule_sets: list[XfaSplitRuleSet],
|
||||
line_fields: list[Any],
|
||||
path_id_to_data_path: dict[str, str],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
schema_by_code: dict[str, dict[str, Any]],
|
||||
document_id: int,
|
||||
packet_checksum: str,
|
||||
row_index: int,
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]], set[str], list[str], bool]:
|
||||
"""
|
||||
对单行执行已确认拆分规则并产出 Schema 字段值与 evidence_only 段。
|
||||
|
||||
Returns:
|
||||
(values, split_evidence, produced_field_codes, issues, required_missing)
|
||||
"""
|
||||
values: list[dict[str, Any]] = []
|
||||
split_evidence: list[dict[str, Any]] = []
|
||||
produced_codes: set[str] = set()
|
||||
issues: list[str] = []
|
||||
required_missing = False
|
||||
|
||||
for rule_set in rule_sets:
|
||||
data_path = _resolve_split_source_data_path(
|
||||
rule_set,
|
||||
line_fields=line_fields,
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
)
|
||||
if not data_path:
|
||||
issues.append('xfa_split_rule_unconfirmed')
|
||||
continue
|
||||
raw_value = row_values.get(data_path)
|
||||
split_result = execute_split_rule_set(raw_value=raw_value or '', rule_set=rule_set)
|
||||
if split_result.status != 'parsed':
|
||||
issues.append('xfa_split_rule_needs_review')
|
||||
for diagnostic in split_result.diagnostics:
|
||||
if diagnostic.code:
|
||||
issues.append(f'xfa_split:{diagnostic.code}')
|
||||
for segment in split_result.evidence_only_segments:
|
||||
split_evidence.append({
|
||||
'segment_id': segment.segment_id,
|
||||
'segment_code': segment.segment_code,
|
||||
'display_name': segment.display_name,
|
||||
'line_no': segment.line_no,
|
||||
'line_end_no': segment.line_end_no,
|
||||
'raw_text': segment.raw_text,
|
||||
'normalized_text': segment.normalized_text,
|
||||
'rule_id': segment.rule_id,
|
||||
'source_path_id': rule_set.source_path_id,
|
||||
'row_index': row_index,
|
||||
})
|
||||
for field_code, mapped_raw in split_result.mapped_fields.items():
|
||||
cfg = schema_by_code.get(field_code) or {}
|
||||
field_id = str(cfg.get('field_id') or field_code)
|
||||
extracted = _extract_one_field(
|
||||
raw_value=mapped_raw,
|
||||
mapping_id=f'split-{rule_set.rule_id}-{field_code}'[:64],
|
||||
field_id=field_id,
|
||||
field_code=field_code,
|
||||
data_path=data_path,
|
||||
value_type=str(cfg.get('value_type') or 'string'),
|
||||
normalizer_key=str(cfg.get('normalizer_key') or 'trim') or None,
|
||||
validator_key=(cfg.get('validator_keys') or [None])[0],
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
if extracted.issues:
|
||||
issues.extend(extracted.issues)
|
||||
if extracted.normalized_value is None:
|
||||
required_missing = True
|
||||
continue
|
||||
produced_codes.add(field_code)
|
||||
values.append({
|
||||
'field_id': extracted.field_id,
|
||||
'field_code': extracted.field_code,
|
||||
'value': extracted.normalized_value,
|
||||
'quote': extracted.quote,
|
||||
'source': 'xfa_dataset',
|
||||
'evidence_ref': extracted.evidence,
|
||||
'highlight_source': 'xfa_split',
|
||||
'row_index': row_index,
|
||||
'split_rule_id': rule_set.rule_id,
|
||||
})
|
||||
return values, split_evidence, produced_codes, issues, required_missing
|
||||
|
||||
|
||||
def extract_xfa_profile(
|
||||
*,
|
||||
raw_profile: dict[str, Any],
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
schema_definition: dict[str, Any],
|
||||
document_id: int,
|
||||
packet_checksum: str,
|
||||
dataset_structure_fingerprint: str | None = None,
|
||||
) -> XfaExtractionResult:
|
||||
"""
|
||||
按冻结 XFA Profile 提取 Header 与权威明细行。
|
||||
|
||||
核心逻辑:校验 definition → 读 Header 叶子 → 读权威集合行 → Schema 标准化;
|
||||
权威集合缺失时 fail-closed(reason=xfa_authoritative_collection_missing)。
|
||||
|
||||
Args:
|
||||
raw_profile: 冻结 Profile 快照(含 definition / checksum)。
|
||||
dataset_analysis: 当前文档 datasets 分析。
|
||||
schema_definition: Run 冻结 Schema definition_json。
|
||||
document_id: 当前文档 ID(写入 evidence)。
|
||||
packet_checksum: datasets packet checksum。
|
||||
dataset_structure_fingerprint: 结构指纹(写入摘要)。
|
||||
|
||||
Returns:
|
||||
XfaExtractionResult:含 rows(对齐坐标路径)与安全 evidence_summary。
|
||||
"""
|
||||
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
|
||||
try:
|
||||
profile = OrderXfaDatasetProfile.model_validate(definition)
|
||||
except (TypeError, ValueError):
|
||||
return XfaExtractionResult(
|
||||
status='failed',
|
||||
reason_codes=['xfa_definition_invalid'],
|
||||
packet_checksum=packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
profile_checksum=str(raw_profile.get('checksum') or '') or None,
|
||||
)
|
||||
|
||||
schema_fields = {
|
||||
str(item.get('field_id') or ''): item
|
||||
for item in (schema_definition.get('fields') or [])
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
|
||||
}
|
||||
|
||||
# [STEP 1] Header 映射
|
||||
header_fields: list[XfaExtractedField] = []
|
||||
header_issues: list[str] = []
|
||||
for mapping in profile.header_mappings:
|
||||
raw_value = read_dataset_value(dataset_analysis, mapping.data_path)
|
||||
extracted = _extract_one_field(
|
||||
raw_value=raw_value,
|
||||
mapping_id=mapping.mapping_id,
|
||||
field_id=mapping.field_id,
|
||||
field_code=mapping.field_code,
|
||||
data_path=mapping.data_path,
|
||||
value_type=mapping.value_type,
|
||||
normalizer_key=mapping.normalizer_key,
|
||||
validator_key=mapping.validator_key,
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
header_fields.append(extracted)
|
||||
header_issues.extend(extracted.issues)
|
||||
|
||||
# [STEP 2] 权威集合行
|
||||
auth_path = profile.source_contract.authoritative_line_collection_path
|
||||
line_rows = read_collection_rows(dataset_analysis, auth_path)
|
||||
if not line_rows:
|
||||
return XfaExtractionResult(
|
||||
status='failed',
|
||||
reason_codes=['xfa_authoritative_collection_missing'],
|
||||
header_fields=header_fields,
|
||||
packet_checksum=packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
profile_checksum=str(raw_profile.get('checksum') or '') or None,
|
||||
evidence_summary={
|
||||
'header_field_count': len(header_fields),
|
||||
'line_row_count': 0,
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
},
|
||||
)
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
required_missing = False
|
||||
all_split_rule_sets = parse_split_rule_sets(profile.split_rules or [])
|
||||
# [STEP] 任意规则集未确认 → 彻底 fail-closed:不执行任何拆分产出 mapped 字段。
|
||||
has_unconfirmed_split_rules = bool(all_split_rule_sets) and any(
|
||||
not _is_formal_ready_split_rule_set(item) for item in all_split_rule_sets
|
||||
)
|
||||
formal_split_rule_sets = (
|
||||
[]
|
||||
if has_unconfirmed_split_rules
|
||||
else [item for item in all_split_rule_sets if _is_formal_ready_split_rule_set(item)]
|
||||
)
|
||||
path_id_to_data_path = _build_path_id_to_data_path(profile)
|
||||
schema_by_code = _schema_by_field_code(schema_fields)
|
||||
split_global_issues: list[str] = []
|
||||
normalized_auth_path = auth_path.rstrip('/')
|
||||
header_split_rule_sets = [
|
||||
item for item in formal_split_rule_sets
|
||||
if item.source_data_path and not str(item.source_data_path).startswith(f'{normalized_auth_path}/')
|
||||
]
|
||||
line_split_rule_sets = [item for item in formal_split_rule_sets if item not in header_split_rule_sets]
|
||||
header_split_evidence: list[dict[str, Any]] = []
|
||||
if header_split_rule_sets:
|
||||
split_headers, header_split_evidence, split_header_issues, split_header_missing = (
|
||||
_apply_split_rules_for_header(
|
||||
dataset_analysis=dataset_analysis,
|
||||
rule_sets=header_split_rule_sets,
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
schema_fields=schema_fields,
|
||||
schema_by_code=schema_by_code,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
)
|
||||
header_fields.extend(split_headers)
|
||||
header_issues.extend(split_header_issues)
|
||||
required_missing = required_missing or split_header_missing
|
||||
split_source_path_ids = {str(item.source_path_id) for item in line_split_rule_sets}
|
||||
if has_unconfirmed_split_rules:
|
||||
split_global_issues.append('xfa_split_rule_unconfirmed')
|
||||
|
||||
for index, row_values in enumerate(line_rows, start=1):
|
||||
values: list[dict[str, Any]] = []
|
||||
issues = list(header_issues) + list(split_global_issues)
|
||||
split_evidence: list[dict[str, Any]] = []
|
||||
split_produced_codes: set[str] = set()
|
||||
# [STEP 2a] 已确认拆分规则:mapped 字段 + evidence_only 段。
|
||||
if line_split_rule_sets:
|
||||
split_values, split_evidence, split_produced_codes, split_issues, split_required_missing = (
|
||||
_apply_split_rules_for_row(
|
||||
row_values=row_values,
|
||||
rule_sets=line_split_rule_sets,
|
||||
line_fields=list(profile.line_mapping.fields),
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
schema_fields=schema_fields,
|
||||
schema_by_code=schema_by_code,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
row_index=index,
|
||||
)
|
||||
)
|
||||
values.extend(split_values)
|
||||
issues.extend(split_issues)
|
||||
if split_required_missing:
|
||||
required_missing = True
|
||||
# Header 字段挂到每行,供 _build_approved_profile_order_result 聚合。
|
||||
for header in header_fields:
|
||||
if header.normalized_value is None:
|
||||
required_missing = True
|
||||
continue
|
||||
values.append({
|
||||
'field_id': header.field_id,
|
||||
'field_code': header.field_code,
|
||||
'value': header.normalized_value,
|
||||
'quote': header.quote,
|
||||
'source': 'xfa_dataset',
|
||||
'evidence_ref': header.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
})
|
||||
pending_price_unit_raw: str | None = None
|
||||
pending_price_unit_path: str | None = None
|
||||
for mapping in profile.line_mapping.fields:
|
||||
if str(mapping.field_code or '') in split_produced_codes:
|
||||
continue
|
||||
if str(mapping.path_id or '') in split_source_path_ids:
|
||||
continue
|
||||
raw_value = row_values.get(mapping.data_path)
|
||||
extract_raw = raw_value
|
||||
# [STEP] NETPR 复合值:拆出单价;价格单位若无独立映射则稍后补齐。
|
||||
if str(mapping.field_code or '') == 'unit_price':
|
||||
composite = parse_unit_price_with_price_unit(
|
||||
None if raw_value is None else str(raw_value)
|
||||
)
|
||||
if composite:
|
||||
extract_raw = composite['unit_price']
|
||||
pending_price_unit_raw = composite['price_unit']
|
||||
pending_price_unit_path = mapping.data_path
|
||||
extracted = _extract_one_field(
|
||||
raw_value=extract_raw if extract_raw is not None else raw_value,
|
||||
mapping_id=mapping.mapping_id,
|
||||
field_id=mapping.field_id,
|
||||
field_code=mapping.field_code,
|
||||
data_path=mapping.data_path,
|
||||
value_type=mapping.value_type,
|
||||
normalizer_key=mapping.normalizer_key,
|
||||
validator_key=mapping.validator_key,
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
# 保留原文 quote(含 ``898.72 / 1``)便于审计对账。
|
||||
if (
|
||||
str(mapping.field_code or '') == 'unit_price'
|
||||
and raw_value not in (None, '')
|
||||
and extract_raw != raw_value
|
||||
):
|
||||
extracted = XfaExtractedField(
|
||||
field_id=extracted.field_id,
|
||||
field_code=extracted.field_code,
|
||||
mapping_id=extracted.mapping_id,
|
||||
data_path=extracted.data_path,
|
||||
raw_value=str(raw_value),
|
||||
normalized_value=extracted.normalized_value,
|
||||
quote=str(raw_value)[:1000],
|
||||
normalizer_key=extracted.normalizer_key,
|
||||
evidence=extracted.evidence,
|
||||
issues=extracted.issues,
|
||||
)
|
||||
if extracted.issues:
|
||||
issues.extend(extracted.issues)
|
||||
if extracted.normalized_value is None:
|
||||
required_missing = True
|
||||
continue
|
||||
values.append({
|
||||
'field_id': extracted.field_id,
|
||||
'field_code': extracted.field_code,
|
||||
'value': extracted.normalized_value,
|
||||
'quote': extracted.quote,
|
||||
'source': 'xfa_dataset',
|
||||
'evidence_ref': extracted.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
'row_index': index,
|
||||
})
|
||||
|
||||
# 仅映射 NETPR 复合值、未单独映射 PEINH 时,补齐 price_unit。
|
||||
present_codes = {
|
||||
str(item.get('field_code') or '')
|
||||
for item in values
|
||||
if isinstance(item, dict)
|
||||
}
|
||||
if pending_price_unit_raw and 'price_unit' not in present_codes:
|
||||
pu_schema = next(
|
||||
(
|
||||
item for item in schema_fields.values()
|
||||
if str(item.get('field_code') or '') == 'price_unit'
|
||||
),
|
||||
None,
|
||||
)
|
||||
pu_field_id = str((pu_schema or {}).get('field_id') or 'price_unit')
|
||||
pu_extracted = _extract_one_field(
|
||||
raw_value=pending_price_unit_raw,
|
||||
mapping_id='derived-unit-price-price-unit',
|
||||
field_id=pu_field_id,
|
||||
field_code='price_unit',
|
||||
data_path=str(pending_price_unit_path or '/data'),
|
||||
value_type=str((pu_schema or {}).get('value_type') or 'integer'),
|
||||
normalizer_key=str((pu_schema or {}).get('normalizer_key') or 'trim') or None,
|
||||
validator_key=None,
|
||||
schema_fields=schema_fields,
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
if pu_extracted.issues:
|
||||
issues.extend(pu_extracted.issues)
|
||||
if pu_extracted.normalized_value is None:
|
||||
required_missing = True
|
||||
else:
|
||||
values.append({
|
||||
'field_id': pu_extracted.field_id,
|
||||
'field_code': 'price_unit',
|
||||
'value': pu_extracted.normalized_value,
|
||||
'quote': pu_extracted.quote,
|
||||
'source': 'xfa_dataset',
|
||||
'evidence_ref': pu_extracted.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
'row_index': index,
|
||||
'derived_from': 'unit_price_price_unit',
|
||||
})
|
||||
rows.append({
|
||||
'row_index': index,
|
||||
'status': 'parsed' if not issues else 'needs_review',
|
||||
'fields': values,
|
||||
'issues': sorted(set(issues)),
|
||||
'split_evidence': split_evidence,
|
||||
})
|
||||
|
||||
reason_codes: list[str] = []
|
||||
if has_unconfirmed_split_rules:
|
||||
reason_codes.append('xfa_split_rule_unconfirmed')
|
||||
if required_missing or any(row.get('status') != 'parsed' for row in rows):
|
||||
reason_codes.append('xfa_required_field_missing')
|
||||
|
||||
evidence_summary = sanitize_xfa_dto({
|
||||
'header_field_count': len(header_fields),
|
||||
'line_row_count': len(rows),
|
||||
'packet_checksum': packet_checksum,
|
||||
'dataset_structure_fingerprint': dataset_structure_fingerprint,
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'profile_checksum': str(raw_profile.get('checksum') or '') or None,
|
||||
'header_split_evidence': header_split_evidence,
|
||||
'field_evidence_refs': [
|
||||
item.evidence for item in header_fields
|
||||
] + [
|
||||
field.get('evidence_ref')
|
||||
for row in rows
|
||||
for field in row.get('fields') or []
|
||||
if isinstance(field, dict) and field.get('evidence_ref')
|
||||
and str(field.get('field_code') or '') not in {h.field_code for h in header_fields}
|
||||
],
|
||||
})
|
||||
|
||||
return XfaExtractionResult(
|
||||
status='parsed' if not reason_codes else 'needs_review',
|
||||
reason_codes=reason_codes,
|
||||
header_fields=header_fields,
|
||||
rows=rows,
|
||||
packet_checksum=packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
profile_checksum=str(raw_profile.get('checksum') or '') or None,
|
||||
evidence_summary=evidence_summary,
|
||||
)
|
||||
@@ -0,0 +1,191 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_profile_matcher.py
|
||||
|
||||
用途:对冻结 published XFA Profile 做精确结构身份匹配(禁止模糊/OCR/VLM)。
|
||||
依赖:xfa_contract(OrderXfaDatasetProfile / sanitize)、ProfileMatchResult 形状对齐。
|
||||
逻辑:由 order_extraction_workflow XFA 分支调用;仅比较
|
||||
template_packet_checksum + dataset_structure_fingerprint;草稿/retired 不在快照内。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
OrderXfaDatasetProfile,
|
||||
sanitize_xfa_dto,
|
||||
)
|
||||
|
||||
|
||||
class XfaProfileMatchCandidate(BaseModel):
|
||||
"""单个冻结 XFA Profile 的精确身份匹配摘要(无业务值)。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
profile_code: str
|
||||
version: int = Field(ge=1)
|
||||
checksum: str | None = None
|
||||
hard_match: bool = False
|
||||
reason_codes: list[str] = Field(default_factory=list)
|
||||
template_packet_checksum: str | None = None
|
||||
dataset_structure_fingerprint: str | None = None
|
||||
|
||||
|
||||
class XfaProfileMatchResult(BaseModel):
|
||||
"""文档级 XFA Profile 精确匹配结果;仅 unique_match 可启动正式提取。"""
|
||||
|
||||
model_config = ConfigDict(extra='forbid')
|
||||
|
||||
status: Literal[
|
||||
'unique_match',
|
||||
'no_match',
|
||||
'ambiguous',
|
||||
'evidence_insufficient',
|
||||
'structure_identity_changed',
|
||||
]
|
||||
profile_code: str | None = None
|
||||
version: int | None = None
|
||||
checksum: str | None = None
|
||||
profile_id: int | None = None
|
||||
template_packet_checksum: str | None = None
|
||||
dataset_structure_fingerprint: str | None = None
|
||||
candidates: list[XfaProfileMatchCandidate] = Field(default_factory=list)
|
||||
reason_codes: list[str] = Field(default_factory=list)
|
||||
|
||||
def model_dump_safe(self) -> dict[str, Any]:
|
||||
"""返回经 sanitize 的可持久化字典。"""
|
||||
return sanitize_xfa_dto(self.model_dump(mode='json'))
|
||||
|
||||
|
||||
def _is_xfa_definition(definition: dict[str, Any] | None) -> bool:
|
||||
"""判断 definition 是否为 xfa_dataset 模式。"""
|
||||
if not isinstance(definition, dict):
|
||||
return False
|
||||
return str(definition.get('template_mode') or '').strip() == 'xfa_dataset'
|
||||
|
||||
|
||||
def match_frozen_xfa_profiles(
|
||||
*,
|
||||
profiles: list[dict[str, Any]],
|
||||
template_packet_checksum: str | None,
|
||||
dataset_structure_fingerprint: str | None,
|
||||
) -> XfaProfileMatchResult:
|
||||
"""
|
||||
对同一文档的冻结 published XFA Profile 做精确结构身份匹配。
|
||||
|
||||
核心逻辑:仅当 template_packet_checksum 与 dataset_structure_fingerprint
|
||||
同时相等时计为 hard_match;0 命中 → no_match,1 → unique_match,≥2 → ambiguous。
|
||||
禁止模糊相似度、客户 ID 单独命中或字段名猜测。
|
||||
|
||||
Args:
|
||||
profiles: Run 冻结的 order_document_profiles(应已排除 draft/retired)。
|
||||
template_packet_checksum: 当前文档 live template packet checksum。
|
||||
dataset_structure_fingerprint: 当前文档 live dataset 结构指纹。
|
||||
|
||||
Returns:
|
||||
XfaProfileMatchResult:含候选摘要与稳定 reason_codes。
|
||||
"""
|
||||
live_template = str(template_packet_checksum or '').strip() or None
|
||||
live_fingerprint = str(dataset_structure_fingerprint or '').strip() or None
|
||||
if not live_template or not live_fingerprint:
|
||||
return XfaProfileMatchResult(
|
||||
status='evidence_insufficient',
|
||||
reason_codes=['xfa_structure_identity_changed'],
|
||||
template_packet_checksum=live_template,
|
||||
dataset_structure_fingerprint=live_fingerprint,
|
||||
)
|
||||
|
||||
candidates: list[XfaProfileMatchCandidate] = []
|
||||
hard_matches: list[tuple[dict[str, Any], XfaProfileMatchCandidate]] = []
|
||||
|
||||
for raw in profiles:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
definition = raw.get('definition') if isinstance(raw.get('definition'), dict) else {}
|
||||
if not _is_xfa_definition(definition):
|
||||
continue
|
||||
# 防御:即使快照误含非 published,也不参与新 Run 匹配。
|
||||
status = str(raw.get('status') or 'published').strip()
|
||||
if status in {'draft', 'retired'}:
|
||||
continue
|
||||
reason_codes: list[str] = []
|
||||
try:
|
||||
profile = OrderXfaDatasetProfile.model_validate(definition)
|
||||
except (TypeError, ValueError):
|
||||
reason_codes.append('xfa_definition_invalid')
|
||||
candidates.append(XfaProfileMatchCandidate(
|
||||
profile_code=str(raw.get('profile_code') or ''),
|
||||
version=max(int(raw.get('version') or 1), 1),
|
||||
checksum=str(raw.get('checksum') or '') or None,
|
||||
hard_match=False,
|
||||
reason_codes=reason_codes,
|
||||
))
|
||||
continue
|
||||
|
||||
source = profile.source_contract
|
||||
profile_template = str(source.template_packet_checksum or '').strip()
|
||||
profile_fingerprint = str(source.dataset_structure_fingerprint or '').strip()
|
||||
hard = (
|
||||
bool(profile_template)
|
||||
and bool(profile_fingerprint)
|
||||
and profile_template == live_template
|
||||
and profile_fingerprint == live_fingerprint
|
||||
and bool(str(raw.get('checksum') or '').strip())
|
||||
)
|
||||
if not hard:
|
||||
if profile_template != live_template or profile_fingerprint != live_fingerprint:
|
||||
reason_codes.append('xfa_structure_identity_changed')
|
||||
else:
|
||||
reason_codes.append('xfa_profile_not_matched')
|
||||
candidate = XfaProfileMatchCandidate(
|
||||
profile_code=str(raw.get('profile_code') or ''),
|
||||
version=max(int(raw.get('version') or 1), 1),
|
||||
checksum=str(raw.get('checksum') or '') or None,
|
||||
hard_match=hard,
|
||||
reason_codes=reason_codes,
|
||||
template_packet_checksum=profile_template or None,
|
||||
dataset_structure_fingerprint=profile_fingerprint or None,
|
||||
)
|
||||
candidates.append(candidate)
|
||||
if hard:
|
||||
hard_matches.append((raw, candidate))
|
||||
|
||||
if not candidates:
|
||||
return XfaProfileMatchResult(
|
||||
status='no_match',
|
||||
reason_codes=['xfa_profile_not_matched'],
|
||||
template_packet_checksum=live_template,
|
||||
dataset_structure_fingerprint=live_fingerprint,
|
||||
candidates=candidates,
|
||||
)
|
||||
if len(hard_matches) == 0:
|
||||
return XfaProfileMatchResult(
|
||||
status='no_match',
|
||||
reason_codes=['xfa_profile_not_matched'],
|
||||
template_packet_checksum=live_template,
|
||||
dataset_structure_fingerprint=live_fingerprint,
|
||||
candidates=candidates,
|
||||
)
|
||||
if len(hard_matches) > 1:
|
||||
return XfaProfileMatchResult(
|
||||
status='ambiguous',
|
||||
reason_codes=['xfa_profile_ambiguous'],
|
||||
template_packet_checksum=live_template,
|
||||
dataset_structure_fingerprint=live_fingerprint,
|
||||
candidates=candidates,
|
||||
)
|
||||
|
||||
raw, winner = hard_matches[0]
|
||||
return XfaProfileMatchResult(
|
||||
status='unique_match',
|
||||
profile_code=winner.profile_code,
|
||||
version=winner.version,
|
||||
checksum=winner.checksum,
|
||||
profile_id=int(raw.get('profile_id') or raw.get('id') or 0) or None,
|
||||
template_packet_checksum=live_template,
|
||||
dataset_structure_fingerprint=live_fingerprint,
|
||||
candidates=candidates,
|
||||
reason_codes=[],
|
||||
)
|
||||
@@ -0,0 +1,147 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_signature.py
|
||||
|
||||
用途:计算 XFA template packet checksum、datasets 结构指纹与治理用 structure signature。
|
||||
依赖:xfa_contract、xfa_dataset.XfaDatasetNode、标准库 hashlib/json。
|
||||
逻辑:由 xfa_analysis / 验证服务调用;指纹忽略业务值与行数;structure signature
|
||||
冻结 analysis 与 packet 身份供发布门禁引用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_STRUCTURE_SIGNATURE_ID,
|
||||
XfaStructureNodeSpec,
|
||||
compute_dataset_structure_fingerprint,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetNode
|
||||
from app.services.shipping_notice.document_layout.xfa_packets import compute_packet_checksum
|
||||
|
||||
|
||||
def compute_template_packet_checksum(template_bytes: bytes | None) -> str | None:
|
||||
"""
|
||||
计算 template packet 的稳定 checksum。
|
||||
|
||||
Args:
|
||||
template_bytes: template packet 原始字节;缺失时返回 None。
|
||||
|
||||
Returns:
|
||||
`sha256:<hex>` 或 None。
|
||||
"""
|
||||
if not template_bytes:
|
||||
return None
|
||||
return compute_packet_checksum(template_bytes)
|
||||
|
||||
|
||||
def dataset_nodes_to_structure_specs(nodes: list[XfaDatasetNode]) -> list[XfaStructureNodeSpec]:
|
||||
"""
|
||||
将受控路径树转换为结构指纹输入节点。
|
||||
|
||||
核心逻辑:只保留 local_name/namespace/depth/cardinality/children;不包含样本值与行计数。
|
||||
|
||||
Args:
|
||||
nodes: datasets 路径树根列表。
|
||||
|
||||
Returns:
|
||||
XfaStructureNodeSpec 列表。
|
||||
"""
|
||||
|
||||
def _convert(node: XfaDatasetNode) -> XfaStructureNodeSpec:
|
||||
return XfaStructureNodeSpec(
|
||||
local_name=node.local_name,
|
||||
namespace_uri=node.namespace_uri,
|
||||
depth=node.depth,
|
||||
cardinality=node.cardinality,
|
||||
children=[_convert(child) for child in node.children],
|
||||
)
|
||||
|
||||
return [_convert(item) for item in nodes]
|
||||
|
||||
|
||||
def compute_dataset_structure_fingerprint_from_nodes(nodes: list[XfaDatasetNode]) -> str:
|
||||
"""
|
||||
基于路径树计算 dataset 结构指纹。
|
||||
|
||||
Args:
|
||||
nodes: datasets 路径树根列表。
|
||||
|
||||
Returns:
|
||||
`sha256:<hex>` 结构指纹。
|
||||
"""
|
||||
specs = dataset_nodes_to_structure_specs(nodes)
|
||||
return compute_dataset_structure_fingerprint(specs)
|
||||
|
||||
|
||||
def build_signature_summary(
|
||||
*,
|
||||
template_bytes: bytes | None,
|
||||
dataset_nodes: list[XfaDatasetNode],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
汇总 template checksum 与 datasets 结构指纹。
|
||||
|
||||
Args:
|
||||
template_bytes: template packet 字节。
|
||||
dataset_nodes: 已解析 datasets 路径树。
|
||||
|
||||
Returns:
|
||||
含 template_packet_checksum 与 dataset_structure_fingerprint 的字典。
|
||||
"""
|
||||
return {
|
||||
'template_packet_checksum': compute_template_packet_checksum(template_bytes),
|
||||
'dataset_structure_fingerprint': compute_dataset_structure_fingerprint_from_nodes(dataset_nodes),
|
||||
}
|
||||
|
||||
|
||||
def build_xfa_structure_signature(
|
||||
*,
|
||||
template_packet_checksum: str | None,
|
||||
dataset_structure_fingerprint: str | None,
|
||||
datasets_packet_checksum: str | None,
|
||||
definition_checksum: str,
|
||||
analysis_ids: list[int],
|
||||
parser_identity: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
生成 XFA 结构签名快照(替代 coordinate layout_signature)。
|
||||
|
||||
核心逻辑:对 analysis/packet/structure/definition/parser 身份做稳定哈希;
|
||||
不含订单值、文件名或明细行数。
|
||||
|
||||
Args:
|
||||
template_packet_checksum: template packet 身份。
|
||||
dataset_structure_fingerprint: datasets 结构指纹。
|
||||
datasets_packet_checksum: datasets packet 内容 checksum(可与 template 不同)。
|
||||
definition_checksum: 当前草稿 definition checksum。
|
||||
analysis_ids: 冻结的结构分析记录 ID 列表。
|
||||
parser_identity: 解析器身份常量。
|
||||
|
||||
Returns:
|
||||
含 signature_version / signature_checksum / evidence 的安全快照。
|
||||
"""
|
||||
payload = {
|
||||
'signature_version': XFA_STRUCTURE_SIGNATURE_ID,
|
||||
'template_packet_checksum': str(template_packet_checksum or ''),
|
||||
'dataset_structure_fingerprint': str(dataset_structure_fingerprint or ''),
|
||||
'datasets_packet_checksum': str(datasets_packet_checksum or ''),
|
||||
'definition_checksum': str(definition_checksum or ''),
|
||||
'analysis_ids': sorted(int(item) for item in analysis_ids),
|
||||
'parser_identity': str(parser_identity or ''),
|
||||
}
|
||||
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
checksum = hashlib.sha256(encoded).hexdigest()
|
||||
return {
|
||||
'signature_version': XFA_STRUCTURE_SIGNATURE_ID,
|
||||
'signature_checksum': checksum,
|
||||
'signature': payload,
|
||||
'evidence_quality': {
|
||||
'source_sample_count': len(analysis_ids),
|
||||
'analysis_count': len(analysis_ids),
|
||||
'has_template_checksum': bool(template_packet_checksum),
|
||||
'has_structure_fingerprint': bool(dataset_structure_fingerprint),
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_split_rule_contract.py
|
||||
|
||||
用途:冻结 XFA 字段拆分规则契约——自定义 segment、多阶段 stages 白名单、
|
||||
Schema 映射限制、evidence_only 边界与正则资源上限。
|
||||
依赖:Pydantic 2、标准库 re/uuid;被 xfa_split_rule_engine、
|
||||
order_document_profile_service 与正式提取路径引用。
|
||||
逻辑:仅声明式校验,不执行规则、不读 PDF、不接网络;非法契约以 ValidationError
|
||||
或 ValueError 拒绝;不提供系统推荐;若残留 source=system_suggestion 必须 draft。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import uuid
|
||||
from typing import Any, Final, Literal
|
||||
|
||||
from pydantic import Field, field_validator, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XfaContractModel,
|
||||
validate_controlled_data_path,
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 资源上限(防止灾难性回溯与规则爆炸)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_SPLIT_MAX_RULES_PER_SET: Final[int] = 32
|
||||
XFA_SPLIT_MAX_RULE_SETS: Final[int] = 64
|
||||
XFA_SPLIT_MAX_STAGES_PER_RULE: Final[int] = 16
|
||||
XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH: Final[int] = 128
|
||||
XFA_SPLIT_MAX_REGEX_GROUPS: Final[int] = 5
|
||||
XFA_SPLIT_MAX_PREFIX_LENGTH: Final[int] = 64
|
||||
XFA_SPLIT_MAX_SEGMENT_CODE_LENGTH: Final[int] = 64
|
||||
XFA_SPLIT_MAX_DISPLAY_NAME_LENGTH: Final[int] = 128
|
||||
XFA_SPLIT_MAX_REPLACE_LENGTH: Final[int] = 128
|
||||
XFA_SPLIT_REGEX_TIMEOUT_MS: Final[int] = 50
|
||||
|
||||
XfaSplitHandling = Literal['mapped', 'evidence_only']
|
||||
XfaSplitStageType = Literal[
|
||||
'split_lines',
|
||||
'select_line',
|
||||
'select_line_range',
|
||||
'extract_prefix',
|
||||
'regex_capture',
|
||||
'replace',
|
||||
'substring',
|
||||
'normalize',
|
||||
]
|
||||
XfaSplitStrategy = Literal['pipeline']
|
||||
XfaSplitUnmatchedPolicy = Literal['evidence_only', 'needs_review']
|
||||
XfaSplitDuplicatePolicy = Literal['needs_review']
|
||||
XfaSplitRuleStatus = Literal['draft', 'confirmed', 'published']
|
||||
XfaSplitRuleSource = Literal['system_suggestion', 'user', 'imported']
|
||||
|
||||
_SEGMENT_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
|
||||
_REGEX_FORBIDDEN = (
|
||||
'(?P', # named groups
|
||||
'(?R', # recursive
|
||||
'(?&',
|
||||
'\\g',
|
||||
)
|
||||
# 常见灾难性回溯形态(启发式,不保证穷尽)
|
||||
_REGEX_CATASTROPHIC = (
|
||||
re.compile(r'\([^)]*[+*][^)]*\)[+*]'),
|
||||
re.compile(r'\([^)]*[+*][^)]*\)\{'),
|
||||
)
|
||||
|
||||
|
||||
class XfaSplitSegment(XfaContractModel):
|
||||
"""自定义拆分段:与 Schema 字段分离;mapped 时绑定冻结 Schema。"""
|
||||
|
||||
segment_id: str = Field(min_length=8, max_length=64)
|
||||
segment_code: str = Field(min_length=2, max_length=XFA_SPLIT_MAX_SEGMENT_CODE_LENGTH)
|
||||
display_name: str = Field(min_length=1, max_length=XFA_SPLIT_MAX_DISPLAY_NAME_LENGTH)
|
||||
handling: XfaSplitHandling
|
||||
target_field_id: str | None = Field(default=None, max_length=64)
|
||||
target_field_code: str | None = Field(default=None, max_length=128)
|
||||
note: str | None = Field(default=None, max_length=256)
|
||||
|
||||
@field_validator('segment_code', mode='before')
|
||||
@classmethod
|
||||
def validate_segment_code(cls, value: Any) -> str:
|
||||
"""segment_code 必须为小写蛇形,Profile 内唯一由上层校验。"""
|
||||
code = str(value or '').strip()
|
||||
if not _SEGMENT_CODE_RE.fullmatch(code):
|
||||
raise ValueError(
|
||||
'segment_code must be lowercase snake_case starting with a letter',
|
||||
)
|
||||
return code
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_handling_targets(self) -> 'XfaSplitSegment':
|
||||
"""mapped 必须绑定目标字段;evidence_only 禁止目标字段。"""
|
||||
if self.handling == 'mapped':
|
||||
if not self.target_field_id or not self.target_field_code:
|
||||
raise ValueError('mapped segment requires target_field_id and target_field_code')
|
||||
else:
|
||||
if self.target_field_id or self.target_field_code:
|
||||
raise ValueError('evidence_only segment must not set target fields')
|
||||
return self
|
||||
|
||||
|
||||
class XfaSplitStage(XfaContractModel):
|
||||
"""
|
||||
单阶段处理步骤(声明式流水线节点)。
|
||||
|
||||
状态机:split_lines 产出行列表;select_line/select_line_range 产出标量并记录行号范围;
|
||||
其余阶段在标量文本上变换。
|
||||
"""
|
||||
|
||||
stage_id: str = Field(min_length=1, max_length=64)
|
||||
type: XfaSplitStageType
|
||||
# split_lines / normalize
|
||||
trim: bool = True
|
||||
remove_empty_lines: bool = True
|
||||
line_breaks: list[str] = Field(default_factory=lambda: ['\r\n', '\r', '\n'])
|
||||
# select_line
|
||||
line_index: int | None = Field(default=None, ge=1, le=1000)
|
||||
# select_line_range
|
||||
line_start: int | None = Field(default=None, ge=1, le=1000)
|
||||
line_end: int | None = Field(default=None, ge=1, le=1000)
|
||||
join_with: Literal['newline', 'space', 'comma'] = 'newline'
|
||||
# extract_prefix
|
||||
value: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_PREFIX_LENGTH)
|
||||
case_sensitive: bool = False
|
||||
separators: list[str] = Field(default_factory=lambda: [':', ':'])
|
||||
# regex_capture
|
||||
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)
|
||||
# replace
|
||||
find: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REPLACE_LENGTH)
|
||||
replace_with: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REPLACE_LENGTH)
|
||||
# substring(0-based,end 不含)
|
||||
start: int | None = Field(default=None, ge=0, le=10_000)
|
||||
end: int | None = Field(default=None, ge=0, le=10_000)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_stage_shape(self) -> 'XfaSplitStage':
|
||||
"""按 type 校验必填字段与正则安全边界。"""
|
||||
if self.type == 'split_lines':
|
||||
breaks = [str(item) for item in (self.line_breaks or []) if str(item)]
|
||||
if not breaks:
|
||||
raise ValueError('split_lines requires at least one line_break')
|
||||
object.__setattr__(self, 'line_breaks', breaks)
|
||||
elif self.type == 'select_line':
|
||||
if self.line_index is None:
|
||||
raise ValueError('select_line requires line_index (1-based)')
|
||||
elif self.type == 'select_line_range':
|
||||
if self.line_start is None or self.line_end is None:
|
||||
raise ValueError('select_line_range requires line_start and line_end (1-based)')
|
||||
if self.line_end < self.line_start:
|
||||
raise ValueError('select_line_range requires line_end >= line_start')
|
||||
elif self.type == 'extract_prefix':
|
||||
label = str(self.value or '').strip()
|
||||
if not label:
|
||||
raise ValueError('extract_prefix requires non-empty value')
|
||||
seps = [str(item) for item in (self.separators or []) if str(item)]
|
||||
if not seps:
|
||||
raise ValueError('extract_prefix requires at least one separator')
|
||||
object.__setattr__(self, 'separators', seps)
|
||||
object.__setattr__(self, 'value', label)
|
||||
elif self.type == 'regex_capture':
|
||||
pattern = str(self.pattern or '')
|
||||
if not pattern:
|
||||
raise ValueError('regex_capture requires pattern')
|
||||
if len(pattern) > XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH:
|
||||
raise ValueError('regex pattern exceeds max length')
|
||||
for token in _REGEX_FORBIDDEN:
|
||||
if token in pattern:
|
||||
raise ValueError(f'regex pattern contains forbidden construct: {token}')
|
||||
for probe in _REGEX_CATASTROPHIC:
|
||||
if probe.search(pattern):
|
||||
raise ValueError('regex pattern looks catastrophic (nested quantifiers)')
|
||||
try:
|
||||
compiled = re.compile(pattern)
|
||||
except re.error as exc:
|
||||
raise ValueError(f'invalid regex pattern: {exc}') from exc
|
||||
if compiled.groups > XFA_SPLIT_MAX_REGEX_GROUPS:
|
||||
raise ValueError('regex capture groups exceed limit')
|
||||
if self.capture_group is not None and self.capture_group > compiled.groups:
|
||||
raise ValueError('capture_group exceeds pattern groups')
|
||||
elif self.type == 'replace':
|
||||
if self.find is None or str(self.find) == '':
|
||||
raise ValueError('replace requires non-empty find')
|
||||
if self.replace_with is None:
|
||||
object.__setattr__(self, 'replace_with', '')
|
||||
elif self.type == 'substring':
|
||||
if self.start is None:
|
||||
raise ValueError('substring requires start')
|
||||
if self.end is not None and self.end < self.start:
|
||||
raise ValueError('substring end must be >= start')
|
||||
elif self.type == 'normalize':
|
||||
pass
|
||||
return self
|
||||
|
||||
|
||||
class XfaSplitRule(XfaContractModel):
|
||||
"""单条输出流水线:显式 order + stages[] + segment。"""
|
||||
|
||||
rule_id: str = Field(min_length=1, max_length=64)
|
||||
order: int = Field(ge=1, le=10_000)
|
||||
segment: XfaSplitSegment
|
||||
stages: list[XfaSplitStage] = Field(min_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_pipeline(self) -> 'XfaSplitRule':
|
||||
"""校验 stages 数量与 stage_id 唯一。"""
|
||||
if len(self.stages) > XFA_SPLIT_MAX_STAGES_PER_RULE:
|
||||
raise ValueError(f'stages exceed max {XFA_SPLIT_MAX_STAGES_PER_RULE}')
|
||||
stage_ids = [item.stage_id for item in self.stages]
|
||||
if len(stage_ids) != len(set(stage_ids)):
|
||||
raise ValueError('duplicate stage_id within split rule')
|
||||
return self
|
||||
|
||||
|
||||
class XfaSplitNormalization(XfaContractModel):
|
||||
"""
|
||||
规则集级默认换行策略:用于未匹配行盘点与无 split_lines 时的行清单。
|
||||
|
||||
流水线内仍以 stages.split_lines 为准。
|
||||
"""
|
||||
|
||||
trim: bool = True
|
||||
remove_empty_lines: bool = True
|
||||
line_breaks: list[str] = Field(default_factory=lambda: ['\r\n', '\r', '\n'])
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_breaks(self) -> 'XfaSplitNormalization':
|
||||
"""line_breaks 不可为空。"""
|
||||
breaks = [str(item) for item in (self.line_breaks or []) if str(item)]
|
||||
if not breaks:
|
||||
raise ValueError('normalization.line_breaks requires at least one value')
|
||||
object.__setattr__(self, 'line_breaks', breaks)
|
||||
return self
|
||||
|
||||
|
||||
class XfaSplitRuleSet(XfaContractModel):
|
||||
"""
|
||||
针对单一源字段的拆分规则集,存于 Profile definition_json.split_rules。
|
||||
|
||||
规则由管理员手工配置(source=user/imported)。若出现历史 source=system_suggestion,
|
||||
必须保持 draft + requires_confirmation,且不得进入正式提取/发布。
|
||||
"""
|
||||
|
||||
rule_id: str = Field(min_length=1, max_length=128)
|
||||
rule_version: int = Field(ge=1, le=10_000)
|
||||
source_path_id: str = Field(min_length=1, max_length=128)
|
||||
source_field_code: str = Field(min_length=1, max_length=128)
|
||||
source_data_path: str | None = Field(default=None, min_length=1, max_length=512)
|
||||
strategy: XfaSplitStrategy = 'pipeline'
|
||||
normalization: XfaSplitNormalization = Field(default_factory=XfaSplitNormalization)
|
||||
rules: list[XfaSplitRule] = Field(default_factory=list)
|
||||
unmatched_line_policy: XfaSplitUnmatchedPolicy = 'evidence_only'
|
||||
duplicate_match_policy: XfaSplitDuplicatePolicy = 'needs_review'
|
||||
same_field_multiple_segment_policy: XfaSplitDuplicatePolicy = 'needs_review'
|
||||
source: XfaSplitRuleSource = 'user'
|
||||
status: XfaSplitRuleStatus = 'draft'
|
||||
requires_confirmation: bool = False
|
||||
|
||||
@field_validator('source_data_path', mode='before')
|
||||
@classmethod
|
||||
def validate_source_data_path(cls, value: Any) -> str | None:
|
||||
"""校验由服务端写入的拆分源路径;旧定义允许为空以兼容读取。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_rule_set_invariants(self) -> 'XfaSplitRuleSet':
|
||||
"""规则集内唯一性与数量上限。"""
|
||||
if len(self.rules) > XFA_SPLIT_MAX_RULES_PER_SET:
|
||||
raise ValueError(f'rules exceed max {XFA_SPLIT_MAX_RULES_PER_SET}')
|
||||
rule_ids = [item.rule_id for item in self.rules]
|
||||
if len(rule_ids) != len(set(rule_ids)):
|
||||
raise ValueError('duplicate rule_id within split rule set')
|
||||
orders = [item.order for item in self.rules]
|
||||
if len(orders) != len(set(orders)):
|
||||
raise ValueError('duplicate order within split rule set')
|
||||
segment_ids = [item.segment.segment_id for item in self.rules]
|
||||
if len(segment_ids) != len(set(segment_ids)):
|
||||
raise ValueError('duplicate segment_id within split rule set')
|
||||
segment_codes = [item.segment.segment_code for item in self.rules]
|
||||
if len(segment_codes) != len(set(segment_codes)):
|
||||
raise ValueError('duplicate segment_code within split rule set')
|
||||
if self.source == 'system_suggestion':
|
||||
if self.status != 'draft' or not self.requires_confirmation:
|
||||
raise ValueError(
|
||||
'system_suggestion must be draft with requires_confirmation=true',
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
def new_segment_id() -> str:
|
||||
"""
|
||||
生成不可变 segment_id。
|
||||
|
||||
Returns:
|
||||
形如 seg-<uuid4hex> 的稳定标识。
|
||||
"""
|
||||
return f'seg-{uuid.uuid4().hex}'
|
||||
|
||||
|
||||
def new_rule_id(prefix: str = 'rule') -> str:
|
||||
"""
|
||||
生成规则条目 ID。
|
||||
|
||||
Args:
|
||||
prefix: ID 前缀。
|
||||
|
||||
Returns:
|
||||
形如 ``{prefix}-<hex>`` 的标识。
|
||||
"""
|
||||
safe = re.sub(r'[^a-z0-9_]+', '_', str(prefix or 'rule').strip().lower()) or 'rule'
|
||||
return f'{safe}-{uuid.uuid4().hex[:12]}'
|
||||
|
||||
|
||||
def new_stage_id(prefix: str = 'stage') -> str:
|
||||
"""
|
||||
生成 stage_id。
|
||||
|
||||
Args:
|
||||
prefix: ID 前缀。
|
||||
|
||||
Returns:
|
||||
形如 ``{prefix}-<hex>`` 的标识。
|
||||
"""
|
||||
safe = re.sub(r'[^a-z0-9_]+', '_', str(prefix or 'stage').strip().lower()) or 'stage'
|
||||
return f'{safe}-{uuid.uuid4().hex[:10]}'
|
||||
|
||||
|
||||
def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -> str:
|
||||
"""
|
||||
计算规则集内容指纹(排除 status / requires_confirmation / rule_version)。
|
||||
|
||||
核心逻辑:用于判断 confirmed 规则内容是否被篡改,需强制回退 Draft。
|
||||
|
||||
Args:
|
||||
rule_set: 模型或 dict。
|
||||
|
||||
Returns:
|
||||
稳定 JSON 字符串指纹素材(调用方可再 hash)。
|
||||
"""
|
||||
import json
|
||||
|
||||
if isinstance(rule_set, XfaSplitRuleSet):
|
||||
payload = rule_set.model_dump(mode='json')
|
||||
else:
|
||||
payload = dict(rule_set or {})
|
||||
payload.pop('status', None)
|
||||
payload.pop('requires_confirmation', None)
|
||||
payload.pop('rule_version', None)
|
||||
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
|
||||
|
||||
|
||||
def validate_split_rules_against_schema(
|
||||
rule_sets: list[XfaSplitRuleSet],
|
||||
*,
|
||||
known_schema_fields: dict[str, dict[str, Any]],
|
||||
known_path_ids: set[str] | None = None,
|
||||
source_scopes: dict[str, str] | None = None,
|
||||
) -> list[XfaSplitRuleSet]:
|
||||
"""
|
||||
相对冻结 Schema 与已知 path_id 校验拆分规则集。
|
||||
|
||||
核心逻辑:目标字段必须存在、启用且与拆分源节点 scope 一致;
|
||||
source_path_id 必须已知(若提供集合)。
|
||||
|
||||
Args:
|
||||
rule_sets: 待校验规则集。
|
||||
known_schema_fields: field_code → Schema 字段配置(仅 enabled)。
|
||||
known_path_ids: 分析记录合法 path_id;None 时跳过路径存在性检查。
|
||||
source_scopes: source_path_id → header/line;未提供时仅校验字段存在性。
|
||||
|
||||
Returns:
|
||||
校验通过的同一列表。
|
||||
|
||||
Raises:
|
||||
ValueError: 契约或 Schema 引用非法。
|
||||
"""
|
||||
if len(rule_sets) > XFA_SPLIT_MAX_RULE_SETS:
|
||||
raise ValueError(f'split_rules exceed max {XFA_SPLIT_MAX_RULE_SETS}')
|
||||
all_codes: list[str] = []
|
||||
all_segment_ids: list[str] = []
|
||||
for rule_set in rule_sets:
|
||||
if known_path_ids is not None and rule_set.source_path_id not in known_path_ids:
|
||||
raise ValueError(f'unknown source_path_id: {rule_set.source_path_id}')
|
||||
for rule in rule_set.rules:
|
||||
all_codes.append(rule.segment.segment_code)
|
||||
all_segment_ids.append(rule.segment.segment_id)
|
||||
if rule.segment.handling != 'mapped':
|
||||
continue
|
||||
code = str(rule.segment.target_field_code or '')
|
||||
field = known_schema_fields.get(code)
|
||||
if field is None:
|
||||
raise ValueError(f'target Schema field not found or disabled: {code}')
|
||||
scope = str(field.get('scope') or '').strip().lower()
|
||||
expected_scope = str((source_scopes or {}).get(rule_set.source_path_id) or '').strip().lower()
|
||||
if expected_scope and scope != expected_scope:
|
||||
raise ValueError(
|
||||
f'target Schema field {code} must have scope={expected_scope}; got {scope or "missing"}',
|
||||
)
|
||||
expected_id = str(field.get('field_id') or '')
|
||||
if expected_id and rule.segment.target_field_id != expected_id:
|
||||
raise ValueError(
|
||||
f'target_field_id mismatch for {code}: '
|
||||
f'expected {expected_id}, got {rule.segment.target_field_id}',
|
||||
)
|
||||
if len(all_codes) != len(set(all_codes)):
|
||||
raise ValueError('segment_code must be unique across Profile split_rules')
|
||||
if len(all_segment_ids) != len(set(all_segment_ids)):
|
||||
raise ValueError('segment_id must be unique across Profile split_rules')
|
||||
return rule_sets
|
||||
|
||||
|
||||
def parse_split_rule_sets(raw: Any) -> list[XfaSplitRuleSet]:
|
||||
"""
|
||||
将 definition_json.split_rules 解析为模型列表。
|
||||
|
||||
Args:
|
||||
raw: JSON 列表或 None。
|
||||
|
||||
Returns:
|
||||
XfaSplitRuleSet 列表;空输入返回 []。
|
||||
|
||||
Raises:
|
||||
ValueError: 形状或契约非法。
|
||||
"""
|
||||
if raw is None:
|
||||
return []
|
||||
if not isinstance(raw, list):
|
||||
raise ValueError('split_rules must be a list')
|
||||
return [XfaSplitRuleSet.model_validate(item) for item in raw]
|
||||
@@ -0,0 +1,512 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_split_rule_engine.py
|
||||
|
||||
用途:声明式执行 XFA 多阶段拆分流水线,产出 mapped Schema 值与 evidence_only 段。
|
||||
依赖:xfa_split_rule_contract、concurrent.futures(正则超时)。
|
||||
逻辑:由预览 API 与正式提取调用;无网络、无脚本、无 LLM;
|
||||
每条 rule 按 stages[] 顺序独立变换;显式 order 决定冲突判定次序;
|
||||
同一行被多条流水线 select_line/select_line_range 认领 → needs_review;正式字段冲突 → needs_review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from concurrent.futures import TimeoutError as FuturesTimeoutError
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaLeafValue
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XFA_SPLIT_REGEX_TIMEOUT_MS,
|
||||
XfaSplitRule,
|
||||
XfaSplitRuleSet,
|
||||
XfaSplitStage,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaSplitSegmentResult:
|
||||
"""单段执行结果(含起止行号与证据文本)。"""
|
||||
|
||||
segment_id: str
|
||||
segment_code: str
|
||||
display_name: str
|
||||
line_no: int | None
|
||||
line_end_no: int | None
|
||||
raw_text: str
|
||||
normalized_text: str
|
||||
handling: str
|
||||
target_field_id: str | None
|
||||
target_field_code: str | None
|
||||
rule_id: str
|
||||
status: str
|
||||
matcher_type: str # 兼容预览字段名:末级 stage type 或 unmatched
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaSplitDiagnostic:
|
||||
"""规则执行诊断。"""
|
||||
|
||||
code: str
|
||||
message: str
|
||||
line_no: int | None = None
|
||||
field_code: str | None = None
|
||||
rule_ids: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaSplitEngineResult:
|
||||
"""规则引擎输出。"""
|
||||
|
||||
status: str
|
||||
segments: list[XfaSplitSegmentResult] = field(default_factory=list)
|
||||
mapped_fields: dict[str, str] = field(default_factory=dict)
|
||||
evidence_only_segments: list[XfaSplitSegmentResult] = field(default_factory=list)
|
||||
diagnostics: list[XfaSplitDiagnostic] = field(default_factory=list)
|
||||
rule_id: str | None = None
|
||||
rule_version: int | None = None
|
||||
|
||||
|
||||
def _split_text_by_breaks(text: str, line_breaks: list[str]) -> list[str]:
|
||||
"""
|
||||
按声明的 line_breaks 切分文本(长分隔符优先)。
|
||||
|
||||
Args:
|
||||
text: 原始文本。
|
||||
line_breaks: 换行符列表。
|
||||
|
||||
Returns:
|
||||
切分后的行列表(尚未 trim / 去空行)。
|
||||
"""
|
||||
if not text:
|
||||
return []
|
||||
pattern = '|'.join(re.escape(item) for item in sorted(line_breaks, key=len, reverse=True))
|
||||
if not pattern:
|
||||
return [text]
|
||||
return re.split(pattern, text)
|
||||
|
||||
|
||||
def _apply_line_normalization(
|
||||
lines: list[str],
|
||||
*,
|
||||
trim: bool,
|
||||
remove_empty_lines: bool,
|
||||
) -> list[str]:
|
||||
"""对行列表应用 trim / 去空行。"""
|
||||
out = list(lines)
|
||||
if trim:
|
||||
out = [item.strip() for item in out]
|
||||
if remove_empty_lines:
|
||||
out = [item for item in out if item]
|
||||
return out
|
||||
|
||||
|
||||
def _inventory_lines(raw_value: str, rule_set: XfaSplitRuleSet) -> list[str]:
|
||||
"""
|
||||
用规则集级 normalization 生成未匹配行盘点用的行清单。
|
||||
|
||||
核心逻辑:尊重 normalization.line_breaks(不再忽略配置)。
|
||||
"""
|
||||
norm = rule_set.normalization
|
||||
lines = _split_text_by_breaks(raw_value or '', list(norm.line_breaks))
|
||||
return _apply_line_normalization(
|
||||
lines,
|
||||
trim=bool(norm.trim),
|
||||
remove_empty_lines=bool(norm.remove_empty_lines),
|
||||
)
|
||||
|
||||
|
||||
def _extract_prefix(text: str, stage: XfaSplitStage) -> str | None:
|
||||
"""前缀提取:标签 + 分隔符后的值。"""
|
||||
label = str(stage.value or '')
|
||||
hay = text if stage.case_sensitive else text.casefold()
|
||||
needle = label if stage.case_sensitive else label.casefold()
|
||||
if not hay.startswith(needle):
|
||||
return None
|
||||
rest = text[len(label):]
|
||||
for sep in stage.separators:
|
||||
if rest.startswith(sep):
|
||||
return rest[len(sep):].strip()
|
||||
stripped = rest.lstrip()
|
||||
if stripped.startswith(sep):
|
||||
return stripped[len(sep):].strip()
|
||||
return None
|
||||
|
||||
|
||||
def _regex_search(text: str, pattern: str, *, case_sensitive: bool) -> re.Match[str] | None:
|
||||
"""
|
||||
带超时的正则搜索。
|
||||
|
||||
Raises:
|
||||
TimeoutError: 超过 XFA_SPLIT_REGEX_TIMEOUT_MS。
|
||||
re.error: 编译失败。
|
||||
"""
|
||||
flags = 0 if case_sensitive else re.IGNORECASE
|
||||
compiled = re.compile(pattern, flags)
|
||||
timeout_s = max(XFA_SPLIT_REGEX_TIMEOUT_MS, 1) / 1000.0
|
||||
|
||||
def _run() -> re.Match[str] | None:
|
||||
return compiled.search(text)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=1) as pool:
|
||||
future = pool.submit(_run)
|
||||
try:
|
||||
return future.result(timeout=timeout_s)
|
||||
except FuturesTimeoutError as exc:
|
||||
future.cancel()
|
||||
raise TimeoutError('regex execution timed out') from exc
|
||||
|
||||
|
||||
def _regex_capture(text: str, stage: XfaSplitStage) -> tuple[str | None, str | None]:
|
||||
"""
|
||||
正则捕获。
|
||||
|
||||
Returns:
|
||||
(value, error_code);成功时 error_code 为 None。
|
||||
"""
|
||||
try:
|
||||
matched = _regex_search(
|
||||
text,
|
||||
str(stage.pattern or ''),
|
||||
case_sensitive=bool(stage.case_sensitive),
|
||||
)
|
||||
except TimeoutError:
|
||||
return None, 'regex_timeout'
|
||||
except re.error:
|
||||
return None, 'regex_failed'
|
||||
if not matched:
|
||||
return None, 'regex_not_matched'
|
||||
group = stage.capture_group
|
||||
try:
|
||||
if group is None:
|
||||
if matched.lastindex:
|
||||
return str(matched.group(1) or '').strip(), None
|
||||
return str(matched.group(0) or '').strip(), None
|
||||
return str(matched.group(group) or '').strip(), None
|
||||
except IndexError:
|
||||
return None, 'regex_failed'
|
||||
|
||||
|
||||
def _run_pipeline(
|
||||
*,
|
||||
raw_value: str,
|
||||
rule: XfaSplitRule,
|
||||
) -> tuple[str | None, set[int], str, str | None]:
|
||||
"""
|
||||
执行单条规则的 stages 流水线。
|
||||
|
||||
Returns:
|
||||
(output_text, claimed_line_numbers, last_stage_type, error_code)
|
||||
error_code 非空表示流水线失败。
|
||||
"""
|
||||
state: str | list[str] = raw_value or ''
|
||||
claimed_lines: set[int] = set()
|
||||
last_type = 'pipeline'
|
||||
for stage in rule.stages:
|
||||
last_type = stage.type
|
||||
if stage.type == 'split_lines':
|
||||
if not isinstance(state, str):
|
||||
return None, claimed_lines, last_type, 'stage_type_mismatch'
|
||||
lines = _split_text_by_breaks(state, list(stage.line_breaks))
|
||||
state = _apply_line_normalization(
|
||||
lines,
|
||||
trim=bool(stage.trim),
|
||||
remove_empty_lines=bool(stage.remove_empty_lines),
|
||||
)
|
||||
continue
|
||||
if stage.type == 'select_line':
|
||||
if not isinstance(state, list):
|
||||
return None, claimed_lines, last_type, 'stage_type_mismatch'
|
||||
idx = int(stage.line_index or 0)
|
||||
if idx < 1 or idx > len(state):
|
||||
return None, claimed_lines, last_type, 'select_line_out_of_range'
|
||||
claimed_lines = {idx}
|
||||
state = state[idx - 1]
|
||||
continue
|
||||
if stage.type == 'select_line_range':
|
||||
if not isinstance(state, list):
|
||||
return None, claimed_lines, last_type, 'stage_type_mismatch'
|
||||
start = int(stage.line_start or 0)
|
||||
end = int(stage.line_end or 0)
|
||||
if start < 1 or end < start or end > len(state):
|
||||
return None, claimed_lines, last_type, 'select_line_range_out_of_range'
|
||||
claimed_lines = set(range(start, end + 1))
|
||||
separator = {'newline': '\n', 'space': ' ', 'comma': ', '}.get(stage.join_with, '\n')
|
||||
state = separator.join(state[start - 1:end])
|
||||
continue
|
||||
if not isinstance(state, str):
|
||||
return None, claimed_lines, last_type, 'stage_type_mismatch'
|
||||
if stage.type == 'extract_prefix':
|
||||
value = _extract_prefix(state, stage)
|
||||
if value is None:
|
||||
return None, claimed_lines, last_type, 'prefix_not_matched'
|
||||
state = value
|
||||
elif stage.type == 'regex_capture':
|
||||
value, err = _regex_capture(state, stage)
|
||||
if err:
|
||||
return None, claimed_lines, last_type, err
|
||||
state = str(value or '')
|
||||
elif stage.type == 'replace':
|
||||
state = state.replace(str(stage.find or ''), str(stage.replace_with or ''))
|
||||
elif stage.type == 'substring':
|
||||
start = int(stage.start or 0)
|
||||
end = len(state) if stage.end is None else int(stage.end)
|
||||
state = state[start:end]
|
||||
elif stage.type == 'normalize':
|
||||
text = state.strip() if stage.trim else state
|
||||
if stage.remove_empty_lines:
|
||||
text = re.sub(r'\s+', ' ', text).strip()
|
||||
state = text
|
||||
else:
|
||||
return None, claimed_lines, last_type, 'unknown_stage'
|
||||
if not isinstance(state, str):
|
||||
return None, claimed_lines, last_type, 'pipeline_ended_on_lines'
|
||||
return state, claimed_lines, last_type, None
|
||||
|
||||
|
||||
def execute_split_rule_set(
|
||||
*,
|
||||
raw_value: str,
|
||||
rule_set: XfaSplitRuleSet,
|
||||
lines: list[str] | None = None,
|
||||
) -> XfaSplitEngineResult:
|
||||
"""
|
||||
对单个源字段原值执行多阶段拆分规则集。
|
||||
|
||||
核心逻辑:
|
||||
1. 按 order 升序执行每条输出流水线;
|
||||
2. select_line/select_line_range 认领行号;范围重叠 → duplicate_line_match;
|
||||
3. 未认领行按 unmatched_line_policy;
|
||||
4. 同一正式字段多段命中 → needs_review;
|
||||
5. evidence_only 全部保留。
|
||||
|
||||
Args:
|
||||
raw_value: 保留换行的原始叶子值。
|
||||
rule_set: 已校验规则集。
|
||||
lines: 可选预切分行(仅覆盖未匹配盘点;流水线仍从 raw 起步)。
|
||||
|
||||
Returns:
|
||||
XfaSplitEngineResult。
|
||||
"""
|
||||
inventory = list(lines) if lines is not None else _inventory_lines(raw_value, rule_set)
|
||||
diagnostics: list[XfaSplitDiagnostic] = []
|
||||
segments: list[XfaSplitSegmentResult] = []
|
||||
line_claims: dict[int, list[str]] = {}
|
||||
|
||||
ordered_rules = sorted(rule_set.rules, key=lambda item: (item.order, item.rule_id))
|
||||
|
||||
# [STEP 1] 独立执行各输出流水线。
|
||||
for rule in ordered_rules:
|
||||
text, claimed_lines, last_type, error = _run_pipeline(raw_value=raw_value, rule=rule)
|
||||
claimed_start = min(claimed_lines) if claimed_lines else None
|
||||
claimed_end = max(claimed_lines) if claimed_lines else None
|
||||
seg = rule.segment
|
||||
if error:
|
||||
diagnostics.append(XfaSplitDiagnostic(
|
||||
code=error,
|
||||
message=f'Pipeline {rule.rule_id} failed at stage type={last_type}: {error}',
|
||||
line_no=claimed_start,
|
||||
field_code=seg.target_field_code,
|
||||
rule_ids=[rule.rule_id],
|
||||
))
|
||||
continue
|
||||
assert text is not None
|
||||
for claimed_line in claimed_lines:
|
||||
line_claims.setdefault(claimed_line, []).append(rule.rule_id)
|
||||
status = 'parsed'
|
||||
if not str(text).strip() and seg.handling == 'mapped':
|
||||
status = 'needs_review'
|
||||
diagnostics.append(XfaSplitDiagnostic(
|
||||
code='mapped_value_empty',
|
||||
message=f'Mapped segment {seg.segment_code} extracted empty value',
|
||||
line_no=claimed_start,
|
||||
field_code=seg.target_field_code,
|
||||
rule_ids=[rule.rule_id],
|
||||
))
|
||||
segments.append(XfaSplitSegmentResult(
|
||||
segment_id=seg.segment_id,
|
||||
segment_code=seg.segment_code,
|
||||
display_name=seg.display_name,
|
||||
line_no=claimed_start,
|
||||
line_end_no=claimed_end,
|
||||
raw_text=str(text),
|
||||
normalized_text=str(text).strip(),
|
||||
handling=seg.handling,
|
||||
target_field_id=seg.target_field_id,
|
||||
target_field_code=seg.target_field_code,
|
||||
rule_id=rule.rule_id,
|
||||
status=status,
|
||||
matcher_type=last_type,
|
||||
))
|
||||
|
||||
# [STEP 2] 同行多规则认领冲突(不再 break 短路)。
|
||||
for line_no, rule_ids in sorted(line_claims.items()):
|
||||
if len(rule_ids) > 1:
|
||||
diagnostics.append(XfaSplitDiagnostic(
|
||||
code='duplicate_line_match',
|
||||
message='Multiple pipelines claimed the same line',
|
||||
line_no=line_no,
|
||||
rule_ids=list(rule_ids),
|
||||
))
|
||||
|
||||
claimed_lines = set(line_claims)
|
||||
|
||||
# [STEP 3] 未匹配行。
|
||||
for line_index, line in enumerate(inventory, start=1):
|
||||
if line_index in claimed_lines:
|
||||
continue
|
||||
status = 'needs_review' if rule_set.unmatched_line_policy == 'needs_review' else 'parsed'
|
||||
if status == 'needs_review':
|
||||
diagnostics.append(XfaSplitDiagnostic(
|
||||
code='unmatched_line',
|
||||
message='Unmatched line requires review',
|
||||
line_no=line_index,
|
||||
))
|
||||
segments.append(XfaSplitSegmentResult(
|
||||
segment_id=f'unmatched-{line_index}',
|
||||
segment_code=f'unmatched_line_{line_index}',
|
||||
display_name=f'其他编码/{line_index}',
|
||||
line_no=line_index,
|
||||
line_end_no=line_index,
|
||||
raw_text=line,
|
||||
normalized_text=line.strip(),
|
||||
handling='evidence_only',
|
||||
target_field_id=None,
|
||||
target_field_code=None,
|
||||
rule_id='unmatched',
|
||||
status=status,
|
||||
matcher_type='unmatched',
|
||||
))
|
||||
|
||||
# [STEP 4] 聚合正式字段。
|
||||
mapped_fields: dict[str, str] = {}
|
||||
field_sources: dict[str, list[str]] = {}
|
||||
overall = 'parsed'
|
||||
for item in segments:
|
||||
if item.status == 'needs_review':
|
||||
overall = 'needs_review'
|
||||
if item.handling != 'mapped' or not item.target_field_code:
|
||||
continue
|
||||
code = item.target_field_code
|
||||
field_sources.setdefault(code, []).append(item.rule_id)
|
||||
if code in mapped_fields:
|
||||
overall = 'needs_review'
|
||||
diagnostics.append(XfaSplitDiagnostic(
|
||||
code='same_field_multiple_segment',
|
||||
message=f'Schema field {code} hit by multiple segments',
|
||||
field_code=code,
|
||||
rule_ids=list(field_sources[code]),
|
||||
))
|
||||
else:
|
||||
mapped_fields[code] = item.normalized_text
|
||||
|
||||
for _code, sources in field_sources.items():
|
||||
if len(sources) > 1 and rule_set.same_field_multiple_segment_policy == 'needs_review':
|
||||
overall = 'needs_review'
|
||||
|
||||
if any(d.code == 'duplicate_line_match' for d in diagnostics):
|
||||
if rule_set.duplicate_match_policy == 'needs_review':
|
||||
overall = 'needs_review'
|
||||
|
||||
if any(d.code in {
|
||||
'prefix_not_matched', 'regex_not_matched', 'regex_timeout', 'regex_failed',
|
||||
'select_line_out_of_range', 'select_line_range_out_of_range',
|
||||
'stage_type_mismatch', 'pipeline_ended_on_lines',
|
||||
} for d in diagnostics):
|
||||
overall = 'needs_review'
|
||||
|
||||
evidence_only = [item for item in segments if item.handling == 'evidence_only']
|
||||
return XfaSplitEngineResult(
|
||||
status=overall,
|
||||
segments=segments,
|
||||
mapped_fields=mapped_fields,
|
||||
evidence_only_segments=evidence_only,
|
||||
diagnostics=diagnostics,
|
||||
rule_id=rule_set.rule_id,
|
||||
rule_version=rule_set.rule_version,
|
||||
)
|
||||
|
||||
|
||||
def execute_split_on_leaf(
|
||||
*,
|
||||
leaf: XfaLeafValue,
|
||||
rule_set: XfaSplitRuleSet,
|
||||
) -> XfaSplitEngineResult:
|
||||
"""
|
||||
对 XfaLeafValue 执行拆分。
|
||||
|
||||
Args:
|
||||
leaf: 三层中间表示。
|
||||
rule_set: 规则集。
|
||||
|
||||
Returns:
|
||||
XfaSplitEngineResult。
|
||||
"""
|
||||
return execute_split_rule_set(raw_value=leaf.raw_value, rule_set=rule_set)
|
||||
|
||||
|
||||
def project_split_result_safe(
|
||||
result: XfaSplitEngineResult,
|
||||
*,
|
||||
include_full_values: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将引擎结果投影为普通 DTO。
|
||||
|
||||
核心逻辑:默认脱敏 mapped/segment 文本;仅当调用方已通过敏感读权限且
|
||||
include_full_values=True 时返回 raw_text / 完整 mapped 值。
|
||||
evidence_only_segments 仅作兼容字段;完整列表以 segments 为准。
|
||||
|
||||
Args:
|
||||
result: 引擎输出。
|
||||
include_full_values: 是否返回完整业务值(需上游权限门禁)。
|
||||
|
||||
Returns:
|
||||
JSON 可序列化 dict。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import mask_value_for_dto
|
||||
|
||||
def _text(value: str) -> str:
|
||||
return str(value) if include_full_values else mask_value_for_dto(value)
|
||||
|
||||
mapped = {
|
||||
code: _text(value)
|
||||
for code, value in result.mapped_fields.items()
|
||||
}
|
||||
return {
|
||||
'status': result.status,
|
||||
'rule_id': result.rule_id,
|
||||
'rule_version': result.rule_version,
|
||||
'full_values_revealed': bool(include_full_values),
|
||||
'mapped_fields': mapped,
|
||||
'segments': [
|
||||
{
|
||||
'segment_id': item.segment_id,
|
||||
'segment_code': item.segment_code,
|
||||
'display_name': item.display_name,
|
||||
'line_no': item.line_no,
|
||||
'line_end_no': item.line_end_no,
|
||||
'raw_text': _text(item.raw_text),
|
||||
'normalized_text': _text(item.normalized_text),
|
||||
'handling': item.handling,
|
||||
'target_field_id': item.target_field_id,
|
||||
'target_field_code': item.target_field_code,
|
||||
'rule_id': item.rule_id,
|
||||
'status': item.status,
|
||||
'matcher_type': item.matcher_type,
|
||||
}
|
||||
for item in result.segments
|
||||
],
|
||||
'evidence_only_segments': [], # 避免与 segments 重复展示;兼容字段置空
|
||||
'diagnostics': [
|
||||
{
|
||||
'code': item.code,
|
||||
'message': item.message,
|
||||
'line_no': item.line_no,
|
||||
'field_code': item.field_code,
|
||||
'rule_ids': list(item.rule_ids),
|
||||
}
|
||||
for item in result.diagnostics
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_validation.py
|
||||
|
||||
用途:XFA 正式提取后的 AcroForm / 镜像集合 / 金额恒等式业务校验。
|
||||
依赖:Decimal、xfa_contract、xfa_dataset、xfa_acroform、field_rules。
|
||||
逻辑:由 order_extraction_workflow 在提取成功后调用;硬失败(mismatched/公式失败)
|
||||
写入稳定 reason_code 进入 needs_review;AcroForm 状态区分
|
||||
matched/partial/unavailable/skipped/mismatched,避免“缺字段却记 matched”。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import (
|
||||
XfaAcroformField,
|
||||
group_acroform_values_by_short_name,
|
||||
read_acroform_fields,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
OrderXfaDatasetProfile,
|
||||
sanitize_xfa_dto,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import (
|
||||
XfaDatasetAnalysis,
|
||||
read_collection_rows,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_extraction import (
|
||||
XfaExtractionResult,
|
||||
_is_formal_ready_split_rule_set,
|
||||
_resolve_split_source_data_path,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XfaSplitRuleSet,
|
||||
parse_split_rule_sets,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_engine import (
|
||||
execute_split_rule_set,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaValidationResult:
|
||||
"""业务校验汇总;passed=False 时 reason_codes 非空。"""
|
||||
|
||||
passed: bool
|
||||
reason_codes: list[str] = field(default_factory=list)
|
||||
cross_check_summary: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
def _to_decimal(value: Any) -> Decimal | None:
|
||||
"""将标准化值转为 Decimal;失败返回 None。"""
|
||||
if value is None or value == '':
|
||||
return None
|
||||
if isinstance(value, Decimal):
|
||||
return value
|
||||
if isinstance(value, (int, float)):
|
||||
return Decimal(str(value))
|
||||
text = str(value).replace(',', '').strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return Decimal(text)
|
||||
except (InvalidOperation, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_comparable(value: Any, *, value_type: str | None = None) -> str | None:
|
||||
"""
|
||||
将 datasets / AcroForm 展示值收敛为可比较的标准化字符串。
|
||||
|
||||
核心逻辑:金额去千分位;日期接受 ISO 与 DD/MM/YYYY;数量去尾随零。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
lowered_type = str(value_type or '').strip().lower()
|
||||
# 日期优先:避免把 14/07/2026 误判为数值。
|
||||
date_patterns = ('%Y-%m-%d', '%Y/%m/%d', '%d/%m/%Y', '%m/%d/%Y', '%d-%m-%Y', '%Y%m%d')
|
||||
if lowered_type in {'date', 'datetime'} or any(sep in text for sep in ('/', '-')) and text.count('/') + text.count('-') >= 2:
|
||||
for pattern in date_patterns:
|
||||
try:
|
||||
return datetime.strptime(text, pattern).date().isoformat()
|
||||
except ValueError:
|
||||
continue
|
||||
if isinstance(value, date) and not isinstance(value, datetime):
|
||||
return value.isoformat()
|
||||
# 数值:覆盖 30 vs 30.000、26,961.6 vs 26961.60。
|
||||
if lowered_type in {'decimal', 'integer', 'amount', 'quantity', 'unit_price', ''} or any(
|
||||
ch.isdigit() for ch in text
|
||||
):
|
||||
numeric = _to_decimal(text)
|
||||
if numeric is not None and any(ch.isdigit() for ch in text):
|
||||
slash_parts = text.replace('.', '/').replace('-', '/').split('/')
|
||||
if not (len(slash_parts) == 3 and all(part.isdigit() for part in slash_parts if part)):
|
||||
normalized = numeric.normalize()
|
||||
if normalized == normalized.to_integral_value():
|
||||
return str(int(normalized))
|
||||
rendered = format(normalized, 'f')
|
||||
if '.' in rendered:
|
||||
rendered = rendered.rstrip('0').rstrip('.')
|
||||
return rendered
|
||||
for pattern in date_patterns:
|
||||
try:
|
||||
return datetime.strptime(text, pattern).date().isoformat()
|
||||
except ValueError:
|
||||
continue
|
||||
return text.casefold()
|
||||
|
||||
|
||||
def _field_map_from_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""从提取行中收集 field_code → value 映射(按行)。"""
|
||||
result: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
mapping: dict[str, Any] = {}
|
||||
for item in row.get('fields') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
code = str(item.get('field_code') or '').strip()
|
||||
if code:
|
||||
mapping[code] = item.get('value')
|
||||
result.append(mapping)
|
||||
return result
|
||||
|
||||
|
||||
def _validate_line_amount_formula(line_maps: list[dict[str, Any]]) -> bool:
|
||||
"""校验 quantity × unit_price / price_unit == amount。"""
|
||||
for mapping in line_maps:
|
||||
quantity = _to_decimal(mapping.get('quantity'))
|
||||
unit_price = _to_decimal(mapping.get('unit_price'))
|
||||
amount = _to_decimal(mapping.get('amount'))
|
||||
if quantity is None or unit_price is None or amount is None:
|
||||
return False
|
||||
price_unit = _to_decimal(mapping.get('price_unit')) or Decimal('1')
|
||||
if price_unit == 0:
|
||||
return False
|
||||
expected = (quantity * unit_price) / price_unit
|
||||
if expected.quantize(Decimal('0.01')) != amount.quantize(Decimal('0.01')):
|
||||
# 允许未量化的精确相等。
|
||||
if expected != amount:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _validate_total_equals_line_sum(
|
||||
*,
|
||||
header_fields: list[Any],
|
||||
line_maps: list[dict[str, Any]],
|
||||
) -> bool:
|
||||
"""校验 Header total_amount 与明细 amount 合计一致。"""
|
||||
total: Decimal | None = None
|
||||
for item in header_fields:
|
||||
code = str(getattr(item, 'field_code', '') or '')
|
||||
if code in {'total_amount', 'order_amount', 'amount'}:
|
||||
total = _to_decimal(getattr(item, 'normalized_value', None))
|
||||
break
|
||||
if total is None:
|
||||
# Header 未映射总金额时不因缺失阻断(由 required 字段门禁负责)。
|
||||
return True
|
||||
line_sum = Decimal('0')
|
||||
for mapping in line_maps:
|
||||
amount = _to_decimal(mapping.get('amount'))
|
||||
if amount is None:
|
||||
return False
|
||||
line_sum += amount
|
||||
return total.quantize(Decimal('0.01')) == line_sum.quantize(Decimal('0.01')) or total == line_sum
|
||||
|
||||
|
||||
def _split_mirror_compare_plan(
|
||||
profile: OrderXfaDatasetProfile,
|
||||
) -> tuple[list[XfaSplitRuleSet], set[str], set[str], dict[str, str]]:
|
||||
"""
|
||||
构建镜像对账用的拆分规则计划。
|
||||
|
||||
Returns:
|
||||
(formal_rule_sets, split_source_paths, split_field_codes, path_id_to_data_path)
|
||||
"""
|
||||
authoritative_path = profile.source_contract.authoritative_line_collection_path.rstrip('/')
|
||||
rule_sets = [
|
||||
item for item in parse_split_rule_sets(profile.split_rules or [])
|
||||
if _is_formal_ready_split_rule_set(item)
|
||||
and (
|
||||
item.source_data_path is None
|
||||
or str(item.source_data_path).startswith(f'{authoritative_path}/')
|
||||
)
|
||||
]
|
||||
path_id_to_data_path = {
|
||||
str(item.path_id): str(item.data_path)
|
||||
for item in profile.line_mapping.fields
|
||||
if item.path_id and item.data_path
|
||||
}
|
||||
split_source_paths: set[str] = set()
|
||||
split_field_codes: set[str] = set()
|
||||
line_fields = list(profile.line_mapping.fields)
|
||||
for rule_set in rule_sets:
|
||||
data_path = _resolve_split_source_data_path(
|
||||
rule_set,
|
||||
line_fields=line_fields,
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
)
|
||||
if data_path:
|
||||
split_source_paths.add(data_path)
|
||||
for rule in rule_set.rules:
|
||||
if rule.segment.handling == 'mapped' and rule.segment.target_field_code:
|
||||
split_field_codes.add(str(rule.segment.target_field_code))
|
||||
return rule_sets, split_source_paths, split_field_codes, path_id_to_data_path
|
||||
|
||||
|
||||
def _validate_mirror_collections(
|
||||
*,
|
||||
profile: OrderXfaDatasetProfile,
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
line_field_paths: dict[str, str],
|
||||
) -> tuple[bool, str]:
|
||||
"""
|
||||
镜像集合存在时,按字段标准化结果逐行对比权威集合。
|
||||
|
||||
核心逻辑:有 split_rules 时,对拆分覆盖字段比较引擎 mapped 值而非整段 raw;
|
||||
evidence_only 段不参与镜像不一致判定。
|
||||
|
||||
Args:
|
||||
profile: 已校验 XFA definition。
|
||||
dataset_analysis: datasets 分析。
|
||||
line_field_paths: field_code → data_path(权威集合路径形态)。
|
||||
|
||||
Returns:
|
||||
(hard_ok, status):status 为 matched|mismatched|skipped|unavailable。
|
||||
hard_ok=False 仅当存在镜像且内容不一致。
|
||||
"""
|
||||
if profile.cross_checks.mirror_collection_policy != 'must_match_when_present':
|
||||
return True, 'skipped'
|
||||
mirrors = list(profile.source_contract.mirror_collection_paths or [])
|
||||
if not mirrors:
|
||||
return True, 'skipped'
|
||||
auth_rows = read_collection_rows(
|
||||
dataset_analysis,
|
||||
profile.source_contract.authoritative_line_collection_path,
|
||||
)
|
||||
formal_rule_sets, split_source_paths, split_field_codes, path_id_to_data_path = (
|
||||
_split_mirror_compare_plan(profile)
|
||||
)
|
||||
line_fields = list(profile.line_mapping.fields)
|
||||
present_count = 0
|
||||
for mirror_path in mirrors:
|
||||
mirror_rows = read_collection_rows(dataset_analysis, mirror_path)
|
||||
if not mirror_rows:
|
||||
# 镜像集合不存在:must_match_when_present 可接受,但不得记 matched。
|
||||
continue
|
||||
present_count += 1
|
||||
if len(mirror_rows) != len(auth_rows):
|
||||
return False, 'mismatched'
|
||||
for auth_row, mirror_row in zip(auth_rows, mirror_rows):
|
||||
for field_code, auth_path in line_field_paths.items():
|
||||
if field_code in split_field_codes or auth_path in split_source_paths:
|
||||
continue
|
||||
suffix = auth_path[len(profile.source_contract.authoritative_line_collection_path):]
|
||||
mirror_field_path = f'{mirror_path}{suffix}'
|
||||
left = _normalize_comparable(auth_row.get(auth_path))
|
||||
right = _normalize_comparable(mirror_row.get(mirror_field_path))
|
||||
if left != right:
|
||||
return False, 'mismatched'
|
||||
for rule_set in formal_rule_sets:
|
||||
auth_source_path = _resolve_split_source_data_path(
|
||||
rule_set,
|
||||
line_fields=line_fields,
|
||||
path_id_to_data_path=path_id_to_data_path,
|
||||
)
|
||||
if not auth_source_path:
|
||||
continue
|
||||
suffix = auth_source_path[len(profile.source_contract.authoritative_line_collection_path):]
|
||||
mirror_source_path = f'{mirror_path}{suffix}'
|
||||
auth_result = execute_split_rule_set(
|
||||
raw_value=auth_row.get(auth_source_path) or '',
|
||||
rule_set=rule_set,
|
||||
)
|
||||
mirror_result = execute_split_rule_set(
|
||||
raw_value=mirror_row.get(mirror_source_path) or '',
|
||||
rule_set=rule_set,
|
||||
)
|
||||
for field_code in auth_result.mapped_fields:
|
||||
left = _normalize_comparable(auth_result.mapped_fields.get(field_code))
|
||||
right = _normalize_comparable(mirror_result.mapped_fields.get(field_code))
|
||||
if left != right:
|
||||
return False, 'mismatched'
|
||||
if present_count == 0:
|
||||
return True, 'unavailable'
|
||||
return True, 'matched'
|
||||
|
||||
|
||||
def _acroform_values_by_local_name(fields: list[XfaAcroformField]) -> dict[str, list[str]]:
|
||||
"""按短名建立 AcroForm 多实例值列表(委托 xfa_acroform)。"""
|
||||
return group_acroform_values_by_short_name(fields)
|
||||
|
||||
|
||||
def _dataset_line_values_by_mapping(
|
||||
*,
|
||||
extraction: XfaExtractionResult,
|
||||
mapping_field_code: str,
|
||||
) -> list[Any]:
|
||||
"""按提取行顺序收集某一 line mapping 的标准化值列表。"""
|
||||
values: list[Any] = []
|
||||
for row in extraction.rows:
|
||||
row_value = None
|
||||
for item in row.get('fields') or []:
|
||||
if isinstance(item, dict) and str(item.get('field_code') or '') == mapping_field_code:
|
||||
row_value = item.get('value')
|
||||
break
|
||||
values.append(row_value)
|
||||
return values
|
||||
|
||||
|
||||
def _validate_acroform(
|
||||
*,
|
||||
profile: OrderXfaDatasetProfile,
|
||||
extraction: XfaExtractionResult,
|
||||
pdf_bytes: bytes | None,
|
||||
) -> tuple[bool, str]:
|
||||
"""
|
||||
对账 datasets 标准化值与 AcroForm 展示值(表头单值 + 明细按行对齐)。
|
||||
|
||||
核心逻辑:
|
||||
- 允许展示格式不同,标准化后必须相同;
|
||||
- 明细按 AcroForm 同名多实例下标与提取行一一对应,禁止“全行扫到首个 field_code”;
|
||||
- 无 Fields / 无重叠字段 → unavailable;仅部分字段可对 → partial;冲突 → mismatched。
|
||||
|
||||
Returns:
|
||||
(hard_ok, status):hard_ok=False 仅 mismatched;其余状态不阻断正式提取硬失败,
|
||||
由 CQ 决定是否允许自动建单。
|
||||
"""
|
||||
if not profile.cross_checks.acroform_enabled:
|
||||
return True, 'skipped'
|
||||
if not pdf_bytes:
|
||||
return True, 'unavailable'
|
||||
acro_fields = read_acroform_fields(pdf_bytes)
|
||||
if not acro_fields:
|
||||
return True, 'unavailable'
|
||||
|
||||
by_name = _acroform_values_by_local_name(acro_fields)
|
||||
compared = 0
|
||||
mismatched = 0
|
||||
missing_counterpart = 0
|
||||
|
||||
# [STEP 1] Header:每个映射对应短名的首个 AcroForm 实例。
|
||||
for mapping in profile.header_mappings:
|
||||
local = mapping.data_path.rsplit('/', 1)[-1].upper()
|
||||
acro_values = by_name.get(local) or []
|
||||
if not acro_values:
|
||||
missing_counterpart += 1
|
||||
continue
|
||||
dataset_value = None
|
||||
for header in extraction.header_fields:
|
||||
if header.mapping_id == mapping.mapping_id:
|
||||
dataset_value = header.normalized_value
|
||||
break
|
||||
left = _normalize_comparable(dataset_value, value_type=mapping.value_type)
|
||||
right = _normalize_comparable(acro_values[0], value_type=mapping.value_type)
|
||||
if left is None or right is None:
|
||||
missing_counterpart += 1
|
||||
continue
|
||||
compared += 1
|
||||
if left != right:
|
||||
mismatched += 1
|
||||
|
||||
# [STEP 2] Line:按行索引对齐同名多实例 Widget。
|
||||
for mapping in profile.line_mapping.fields:
|
||||
local = mapping.data_path.rsplit('/', 1)[-1].upper()
|
||||
acro_values = by_name.get(local) or []
|
||||
dataset_values = _dataset_line_values_by_mapping(
|
||||
extraction=extraction,
|
||||
mapping_field_code=mapping.field_code,
|
||||
)
|
||||
if not dataset_values:
|
||||
continue
|
||||
if not acro_values:
|
||||
missing_counterpart += len(dataset_values)
|
||||
continue
|
||||
for row_index, dataset_value in enumerate(dataset_values):
|
||||
if row_index >= len(acro_values):
|
||||
missing_counterpart += 1
|
||||
continue
|
||||
left = _normalize_comparable(dataset_value, value_type=mapping.value_type)
|
||||
right = _normalize_comparable(acro_values[row_index], value_type=mapping.value_type)
|
||||
if left is None or right is None:
|
||||
missing_counterpart += 1
|
||||
continue
|
||||
compared += 1
|
||||
if left != right:
|
||||
mismatched += 1
|
||||
|
||||
if mismatched > 0:
|
||||
return False, 'mismatched'
|
||||
if compared == 0:
|
||||
return True, 'unavailable'
|
||||
if missing_counterpart > 0:
|
||||
return True, 'partial'
|
||||
return True, 'matched'
|
||||
|
||||
|
||||
def validate_xfa_extraction(
|
||||
*,
|
||||
raw_profile: dict[str, Any],
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
extraction: XfaExtractionResult,
|
||||
pdf_bytes: bytes | None = None,
|
||||
) -> XfaValidationResult:
|
||||
"""
|
||||
执行 XFA 提取后的确定性业务校验。
|
||||
|
||||
核心逻辑(任一失败即 fail-closed):
|
||||
1. 镜像集合标准化一致性;
|
||||
2. AcroForm 关键字段标准化一致性;
|
||||
3. 明细金额公式 quantity×unit_price;
|
||||
4. Header 总金额与明细合计。
|
||||
|
||||
Args:
|
||||
raw_profile: 冻结 Profile 快照。
|
||||
dataset_analysis: datasets 分析。
|
||||
extraction: 提取结果。
|
||||
pdf_bytes: 可选原始 PDF,用于 AcroForm 对账。
|
||||
|
||||
Returns:
|
||||
XfaValidationResult。
|
||||
"""
|
||||
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
|
||||
try:
|
||||
profile = OrderXfaDatasetProfile.model_validate(definition)
|
||||
except (TypeError, ValueError):
|
||||
return XfaValidationResult(
|
||||
passed=False,
|
||||
reason_codes=['xfa_definition_invalid'],
|
||||
cross_check_summary={'status': 'failed'},
|
||||
)
|
||||
|
||||
reason_codes: list[str] = []
|
||||
line_field_paths = {
|
||||
item.field_code: item.data_path for item in profile.line_mapping.fields
|
||||
}
|
||||
summary: dict[str, Any] = {
|
||||
'mirror_collection_policy': profile.cross_checks.mirror_collection_policy,
|
||||
'acroform_enabled': profile.cross_checks.acroform_enabled,
|
||||
'line_amount_formula': profile.cross_checks.line_amount_formula,
|
||||
'total_amount_policy': profile.cross_checks.total_amount_policy,
|
||||
}
|
||||
|
||||
# [STEP 1] 镜像集合
|
||||
mirror_ok, mirror_status = _validate_mirror_collections(
|
||||
profile=profile,
|
||||
dataset_analysis=dataset_analysis,
|
||||
line_field_paths=line_field_paths,
|
||||
)
|
||||
if not mirror_ok:
|
||||
reason_codes.append('xfa_mirror_collection_mismatch')
|
||||
summary['mirror_status'] = mirror_status
|
||||
|
||||
# [STEP 2] AcroForm(按行对齐;状态含 matched/partial/unavailable)
|
||||
acro_ok, acro_status = _validate_acroform(
|
||||
profile=profile,
|
||||
extraction=extraction,
|
||||
pdf_bytes=pdf_bytes,
|
||||
)
|
||||
if not acro_ok:
|
||||
reason_codes.append('xfa_acroform_mismatch')
|
||||
summary['acroform_status'] = acro_status
|
||||
|
||||
line_maps = _field_map_from_rows(extraction.rows)
|
||||
|
||||
# [STEP 3] 明细金额公式
|
||||
if profile.cross_checks.line_amount_formula == 'quantity_times_unit_price':
|
||||
if not _validate_line_amount_formula(line_maps):
|
||||
reason_codes.append('xfa_business_validation_failed')
|
||||
summary['line_amount_status'] = 'failed'
|
||||
else:
|
||||
summary['line_amount_status'] = 'passed'
|
||||
else:
|
||||
summary['line_amount_status'] = 'skipped'
|
||||
|
||||
# [STEP 4] Header 总计
|
||||
if profile.cross_checks.total_amount_policy == 'must_equal_line_sum':
|
||||
if not _validate_total_equals_line_sum(
|
||||
header_fields=extraction.header_fields,
|
||||
line_maps=line_maps,
|
||||
):
|
||||
if 'xfa_business_validation_failed' not in reason_codes:
|
||||
reason_codes.append('xfa_business_validation_failed')
|
||||
summary['total_amount_status'] = 'failed'
|
||||
else:
|
||||
summary['total_amount_status'] = 'passed'
|
||||
else:
|
||||
summary['total_amount_status'] = 'skipped'
|
||||
|
||||
return XfaValidationResult(
|
||||
passed=not reason_codes,
|
||||
reason_codes=reason_codes,
|
||||
cross_check_summary=sanitize_xfa_dto(summary),
|
||||
)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,9 +2,10 @@
|
||||
backend/app/services/shipping_notice/duplicate_detection.py
|
||||
|
||||
用途:发货通知业务重复检测(文件哈希 + 业务指纹),产出统一 duplicate 结果。
|
||||
依赖:models.ShippingTask/FileAsset/Document/Candidate、business_fingerprint、core.response.utc_iso。
|
||||
依赖:models.ShippingNotice/FileAsset/Document/Candidate、business_fingerprint、core.response.utc_iso。
|
||||
逻辑:Intake 级与 Candidate 级共用匹配规则;候选 A 重复只写回 A,不连带阻断同信其它候选;
|
||||
刷新入口按 Candidate 重检再聚合到 Intake;检测异常可 clear 为 unchecked;
|
||||
Candidate 级可 exclude_task_ids 豁免同复核 Case 既有履约波次;
|
||||
范围限定当前 user_id,不跨用户泄露。
|
||||
"""
|
||||
|
||||
@@ -17,11 +18,11 @@ from app import db
|
||||
from app.core.response import utc_iso
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingTask,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice.business_fingerprint import (
|
||||
CONTENT_FINGERPRINT_VERSION,
|
||||
@@ -61,7 +62,7 @@ def classify_task_lifecycle(process_status: str | None) -> str:
|
||||
return 'unknown'
|
||||
|
||||
|
||||
def is_irreversible_task(task: ShippingTask) -> bool:
|
||||
def is_irreversible_task(task: ShippingNotice) -> bool:
|
||||
"""已 uploaded 或终态任务不可原地覆盖源文件。"""
|
||||
status = str(task.process_status or '').strip().lower()
|
||||
if status in _IRREVERSIBLE_PROCESS_STATUSES:
|
||||
@@ -70,7 +71,7 @@ def is_irreversible_task(task: ShippingTask) -> bool:
|
||||
return upload_status in {'uploaded', 'succeeded', 'success'}
|
||||
|
||||
|
||||
def _match_payload(task: ShippingTask, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]:
|
||||
def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
'task_no': task.task_no,
|
||||
'process_status': task.process_status,
|
||||
@@ -84,7 +85,7 @@ def _match_payload(task: ShippingTask, *, match_type: str, matched_fields: list[
|
||||
}
|
||||
|
||||
|
||||
def _reservation_differences(task: ShippingTask, summary: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
def _reservation_differences(task: ShippingNotice, summary: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""比较候选与目标冻结订单的同 Reservation 行,供人工修订确认前展示。"""
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
|
||||
if snapshot is None:
|
||||
@@ -134,7 +135,7 @@ def _allowed_actions_for(
|
||||
|
||||
def detect_duplicates_for_intake(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
asset: FileAsset | None = None,
|
||||
business_summary: dict[str, Any] | None = None,
|
||||
fingerprint_result: dict[str, Any] | None = None,
|
||||
@@ -176,13 +177,13 @@ def detect_duplicates_for_intake(
|
||||
content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower()
|
||||
if content_hash:
|
||||
hash_tasks = (
|
||||
db.session.query(ShippingTask)
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(
|
||||
ShippingTask.user_id == int(intake.user_id),
|
||||
ShippingTask.source_content_hash == content_hash,
|
||||
ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
ShippingNotice.user_id == int(intake.user_id),
|
||||
ShippingNotice.source_content_hash == content_hash,
|
||||
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
)
|
||||
.order_by(ShippingTask.id.desc())
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.limit(10)
|
||||
.all()
|
||||
)
|
||||
@@ -200,13 +201,13 @@ def detect_duplicates_for_intake(
|
||||
# [STEP 2] 业务指纹
|
||||
if fingerprint and strength in {'strong', 'medium'}:
|
||||
fp_tasks = (
|
||||
db.session.query(ShippingTask)
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(
|
||||
ShippingTask.user_id == int(intake.user_id),
|
||||
ShippingTask.business_fingerprint == fingerprint,
|
||||
ShippingTask.fingerprint_version == version,
|
||||
ShippingNotice.user_id == int(intake.user_id),
|
||||
ShippingNotice.business_fingerprint == fingerprint,
|
||||
ShippingNotice.fingerprint_version == version,
|
||||
)
|
||||
.order_by(ShippingTask.id.desc())
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
@@ -247,14 +248,14 @@ def detect_duplicates_for_intake(
|
||||
elif fingerprint and strength == 'weak' and status == 'none':
|
||||
# 弱指纹:仅标记疑似,不按 active 强阻断
|
||||
fp_tasks = (
|
||||
db.session.query(ShippingTask)
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(
|
||||
ShippingTask.user_id == int(intake.user_id),
|
||||
ShippingTask.business_fingerprint == fingerprint,
|
||||
ShippingTask.fingerprint_version == version,
|
||||
ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
ShippingNotice.user_id == int(intake.user_id),
|
||||
ShippingNotice.business_fingerprint == fingerprint,
|
||||
ShippingNotice.fingerprint_version == version,
|
||||
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
)
|
||||
.order_by(ShippingTask.id.desc())
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
.limit(5)
|
||||
.all()
|
||||
)
|
||||
@@ -278,7 +279,7 @@ def detect_duplicates_for_intake(
|
||||
if strength == 'unavailable' and status == 'none':
|
||||
blocking = False
|
||||
for match in matches:
|
||||
task = db.session.query(ShippingTask).filter_by(task_no=match['task_no']).one_or_none()
|
||||
task = db.session.query(ShippingNotice).filter_by(task_no=match['task_no']).one_or_none()
|
||||
if task is not None:
|
||||
match['reservation_differences'] = _reservation_differences(task, summary)
|
||||
|
||||
@@ -300,7 +301,7 @@ def detect_duplicates_for_intake(
|
||||
|
||||
|
||||
def apply_duplicate_result_to_intake(
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
result: dict[str, Any],
|
||||
) -> None:
|
||||
"""将检测结果写回 intake ORM 字段(不 commit)。"""
|
||||
@@ -319,7 +320,7 @@ def apply_duplicate_result_to_intake(
|
||||
intake.updated_at = datetime.utcnow()
|
||||
|
||||
|
||||
def clear_duplicate_state_to_unchecked(*, intake: ShippingNoticeIntake) -> None:
|
||||
def clear_duplicate_state_to_unchecked(*, intake: ShippingOrderIntake) -> None:
|
||||
"""
|
||||
将 Intake 与其 Candidate 的重复结果/决策统一清空为 unchecked。
|
||||
|
||||
@@ -339,8 +340,8 @@ def clear_duplicate_state_to_unchecked(*, intake: ShippingNoticeIntake) -> None:
|
||||
intake.duplicate_resolved_at = None
|
||||
intake.updated_at = now
|
||||
candidates = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter(ShippingNoticeCandidate.intake_id == int(intake.id))
|
||||
db.session.query(ShippingOrderCandidate)
|
||||
.filter(ShippingOrderCandidate.intake_id == int(intake.id))
|
||||
.all()
|
||||
)
|
||||
for candidate in candidates:
|
||||
@@ -354,7 +355,7 @@ def clear_duplicate_state_to_unchecked(*, intake: ShippingNoticeIntake) -> None:
|
||||
|
||||
|
||||
def apply_duplicate_result_to_candidate(
|
||||
candidate: ShippingNoticeCandidate,
|
||||
candidate: ShippingOrderCandidate,
|
||||
result: dict[str, Any],
|
||||
*,
|
||||
clear_resolution: bool = True,
|
||||
@@ -388,7 +389,7 @@ def apply_duplicate_result_to_candidate(
|
||||
|
||||
def refresh_candidates_and_aggregate_intake(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
parent_asset: FileAsset | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -402,9 +403,9 @@ def refresh_candidates_and_aggregate_intake(
|
||||
聚合后的 duplicate 结果(已 apply 到 Intake;Candidate 已写回)。
|
||||
"""
|
||||
candidates = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
.filter(ShippingNoticeCandidate.intake_id == int(intake.id))
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
db.session.query(ShippingOrderCandidate)
|
||||
.filter(ShippingOrderCandidate.intake_id == int(intake.id))
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
if not candidates:
|
||||
@@ -428,7 +429,7 @@ def refresh_candidates_and_aggregate_intake(
|
||||
|
||||
candidate_results: list[dict[str, Any]] = []
|
||||
for candidate in candidates:
|
||||
document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(candidate.primary_document_id))
|
||||
structured = (
|
||||
candidate.structured_result_json
|
||||
if isinstance(candidate.structured_result_json, dict)
|
||||
@@ -469,18 +470,26 @@ def refresh_candidates_and_aggregate_intake(
|
||||
|
||||
def detect_duplicates_for_candidate(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
asset: FileAsset | None = None,
|
||||
document: ShippingNoticeDocument | None = None,
|
||||
document: ShippingOrderDocument | None = None,
|
||||
business_summary: dict[str, Any] | None = None,
|
||||
fingerprint_result: dict[str, Any] | None = None,
|
||||
content_fingerprint_result: dict[str, Any] | None = None,
|
||||
exclude_task_ids: set[int] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
对单个订单候选执行重复检测(不写 Intake,不影响同信其它候选)。
|
||||
|
||||
核心逻辑:与 detect_duplicates_for_intake 同源规则,但 exact_file 优先用
|
||||
Document/派生资产 content_hash(单 PDF),避免整封 EML 哈希误伤其它订单。
|
||||
exclude_task_ids 用于同一复核 Case 合法后续履约波次豁免本 Case 既有 Task。
|
||||
|
||||
Args:
|
||||
intake: 来源 Intake。
|
||||
asset / document: 可选文件资产与 PDF 文档。
|
||||
business_summary / fingerprint_result / content_fingerprint_result: 指纹输入。
|
||||
exclude_task_ids: 可选;忽略这些 Task(同 Case 既有波次)。
|
||||
|
||||
Returns:
|
||||
与 intake 检测相同结构的结果字典。
|
||||
@@ -494,6 +503,7 @@ def detect_duplicates_for_candidate(
|
||||
content_fp = content_fingerprint_result or build_content_fingerprint(summary)
|
||||
content_fingerprint = content_fp.get('fingerprint')
|
||||
content_version = str(content_fp.get('version') or CONTENT_FINGERPRINT_VERSION)
|
||||
skipped_ids = {int(item) for item in (exclude_task_ids or []) if item is not None}
|
||||
|
||||
content_hash = ''
|
||||
if document is not None and str(document.content_hash or '').strip():
|
||||
@@ -506,17 +516,17 @@ def detect_duplicates_for_candidate(
|
||||
|
||||
# [STEP 1] 精确文件哈希(附件级)
|
||||
if content_hash:
|
||||
hash_tasks = (
|
||||
db.session.query(ShippingTask)
|
||||
hash_query = (
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(
|
||||
ShippingTask.user_id == int(intake.user_id),
|
||||
ShippingTask.source_content_hash == content_hash,
|
||||
ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
ShippingNotice.user_id == int(intake.user_id),
|
||||
ShippingNotice.source_content_hash == content_hash,
|
||||
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
)
|
||||
.order_by(ShippingTask.id.desc())
|
||||
.limit(10)
|
||||
.all()
|
||||
)
|
||||
if skipped_ids:
|
||||
hash_query = hash_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
|
||||
hash_tasks = hash_query.order_by(ShippingNotice.id.desc()).limit(10).all()
|
||||
for task in hash_tasks:
|
||||
matches.append(
|
||||
_match_payload(
|
||||
@@ -530,17 +540,17 @@ def detect_duplicates_for_candidate(
|
||||
|
||||
# [STEP 2] 业务指纹
|
||||
if fingerprint and strength in {'strong', 'medium'}:
|
||||
fp_tasks = (
|
||||
db.session.query(ShippingTask)
|
||||
fp_query = (
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(
|
||||
ShippingTask.user_id == int(intake.user_id),
|
||||
ShippingTask.business_fingerprint == fingerprint,
|
||||
ShippingTask.fingerprint_version == version,
|
||||
ShippingNotice.user_id == int(intake.user_id),
|
||||
ShippingNotice.business_fingerprint == fingerprint,
|
||||
ShippingNotice.fingerprint_version == version,
|
||||
)
|
||||
.order_by(ShippingTask.id.desc())
|
||||
.limit(20)
|
||||
.all()
|
||||
)
|
||||
if skipped_ids:
|
||||
fp_query = fp_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
|
||||
fp_tasks = fp_query.order_by(ShippingNotice.id.desc()).limit(20).all()
|
||||
matched_fields = list(components.keys())
|
||||
for task in fp_tasks:
|
||||
if any(m.get('task_no') == task.task_no for m in matches):
|
||||
@@ -572,18 +582,18 @@ def detect_duplicates_for_candidate(
|
||||
else:
|
||||
status = 'possible_duplicate'
|
||||
elif fingerprint and strength == 'weak' and status == 'none':
|
||||
fp_tasks = (
|
||||
db.session.query(ShippingTask)
|
||||
weak_query = (
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(
|
||||
ShippingTask.user_id == int(intake.user_id),
|
||||
ShippingTask.business_fingerprint == fingerprint,
|
||||
ShippingTask.fingerprint_version == version,
|
||||
ShippingTask.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
ShippingNotice.user_id == int(intake.user_id),
|
||||
ShippingNotice.business_fingerprint == fingerprint,
|
||||
ShippingNotice.fingerprint_version == version,
|
||||
ShippingNotice.process_status.notin_(list(_CLOSED_PROCESS_STATUSES)),
|
||||
)
|
||||
.order_by(ShippingTask.id.desc())
|
||||
.limit(5)
|
||||
.all()
|
||||
)
|
||||
if skipped_ids:
|
||||
weak_query = weak_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
|
||||
fp_tasks = weak_query.order_by(ShippingNotice.id.desc()).limit(5).all()
|
||||
for task in fp_tasks:
|
||||
matches.append(
|
||||
_match_payload(
|
||||
@@ -606,7 +616,7 @@ def detect_duplicates_for_candidate(
|
||||
if strength == 'unavailable' and status == 'none':
|
||||
blocking = False
|
||||
for match in matches:
|
||||
task = db.session.query(ShippingTask).filter_by(task_no=match['task_no']).one_or_none()
|
||||
task = db.session.query(ShippingNotice).filter_by(task_no=match['task_no']).one_or_none()
|
||||
if task is not None:
|
||||
match['reservation_differences'] = _reservation_differences(task, summary)
|
||||
|
||||
@@ -630,7 +640,7 @@ def detect_duplicates_for_candidate(
|
||||
|
||||
|
||||
def aggregate_intake_duplicate_from_candidates(
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
candidate_results: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
|
||||
@@ -5,7 +5,7 @@ services/shipping_notice/error_explainability_contract.py
|
||||
统一投影结构;作为阶段 0 真相源,后续阶段逐步接线,禁止前端按状态猜原因。
|
||||
依赖:process_gate_contract(门禁阻断码 / 责任方 / 动作码交叉校验)。
|
||||
逻辑:本模块只冻结名称与投影规则,不执行业务;与 process_gate_contract 共存:
|
||||
Gate 阻断码仍以门禁契约为准;本模块补充附件/解析/行级/源级等细粒度码,
|
||||
Gate 阻断码仍以门禁契约为准;本模块补充附件/解析/行级/源级/XFA 等细粒度码,
|
||||
以及「规则未命中 ≠ 命中但不可用 ≠ 冲突」的分层语义;
|
||||
AUDIT_COVERAGE_MATRIX 锁定阶段 4 关键失败/关闭节点的顶层 reason_code 接线源。
|
||||
"""
|
||||
@@ -56,6 +56,38 @@ DOCUMENT_PARSE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'generic_gate_blocked',
|
||||
'order_extraction_failed',
|
||||
'order_extraction_cancelled',
|
||||
# XFA 数据路径(阶段 0 冻结)
|
||||
'xfa_dataset_missing',
|
||||
'xfa_unsafe_xml',
|
||||
'xfa_packet_too_large',
|
||||
'xfa_xml_depth_exceeded',
|
||||
'xfa_xml_node_limit_exceeded',
|
||||
'xfa_line_row_limit_exceeded',
|
||||
'xfa_parse_timeout',
|
||||
'xfa_unsupported_document',
|
||||
'xfa_profile_not_matched',
|
||||
'xfa_profile_ambiguous',
|
||||
'xfa_required_field_missing',
|
||||
'xfa_mirror_collection_mismatch',
|
||||
'xfa_acroform_mismatch',
|
||||
'xfa_business_validation_failed',
|
||||
'xfa_authoritative_collection_missing',
|
||||
'xfa_path_invalid',
|
||||
'xfa_path_unknown',
|
||||
'xfa_definition_invalid',
|
||||
'xfa_structure_identity_changed',
|
||||
'xfa_split_rule_invalid',
|
||||
'xfa_split_field_conflict',
|
||||
'xfa_split_mirror_mismatch',
|
||||
'xfa_auto_create_disabled',
|
||||
'xfa_shadow_mode',
|
||||
'xfa_profile_not_blind_approved',
|
||||
'xfa_allowlist_unconfigured',
|
||||
'xfa_customer_not_allowlisted',
|
||||
'xfa_profile_checksum_not_allowlisted',
|
||||
'xfa_scenario_not_allowlisted',
|
||||
'xfa_evidence_incomplete',
|
||||
'xfa_cross_check_failed',
|
||||
})
|
||||
|
||||
# 字段抽取、客户与订单校验
|
||||
@@ -197,6 +229,28 @@ EXPLAINABILITY_REASON_ALIASES: Final[dict[str, str]] = {
|
||||
'effective_reservation_missing': 'reservation_missing',
|
||||
# Candidate 人工驳回历史码 → 关闭类稳定码
|
||||
'manual_rejected': 'task_rejected_by_user',
|
||||
# XFA AppError / 大写错误码 → 稳定原因码
|
||||
'XFA_DATASET_MISSING': 'xfa_dataset_missing',
|
||||
'XFA_UNSAFE_XML': 'xfa_unsafe_xml',
|
||||
'XFA_PACKET_TOO_LARGE': 'xfa_packet_too_large',
|
||||
'XFA_XML_DEPTH_EXCEEDED': 'xfa_xml_depth_exceeded',
|
||||
'XFA_XML_NODE_LIMIT_EXCEEDED': 'xfa_xml_node_limit_exceeded',
|
||||
'XFA_LINE_ROW_LIMIT_EXCEEDED': 'xfa_line_row_limit_exceeded',
|
||||
'XFA_PARSE_TIMEOUT': 'xfa_parse_timeout',
|
||||
'XFA_UNSUPPORTED_DOCUMENT': 'xfa_unsupported_document',
|
||||
'XFA_PROFILE_NOT_MATCHED': 'xfa_profile_not_matched',
|
||||
'XFA_PROFILE_AMBIGUOUS': 'xfa_profile_ambiguous',
|
||||
'XFA_REQUIRED_FIELD_MISSING': 'xfa_required_field_missing',
|
||||
'XFA_MIRROR_COLLECTION_MISMATCH': 'xfa_mirror_collection_mismatch',
|
||||
'XFA_ACROFORM_MISMATCH': 'xfa_acroform_mismatch',
|
||||
'XFA_BUSINESS_VALIDATION_FAILED': 'xfa_business_validation_failed',
|
||||
'XFA_AUTHORITATIVE_COLLECTION_MISSING': 'xfa_authoritative_collection_missing',
|
||||
'XFA_PATH_INVALID': 'xfa_path_invalid',
|
||||
'XFA_PATH_UNKNOWN': 'xfa_path_unknown',
|
||||
'XFA_DEFINITION_INVALID': 'xfa_definition_invalid',
|
||||
'XFA_SPLIT_RULE_INVALID': 'xfa_split_rule_invalid',
|
||||
'XFA_SPLIT_FIELD_CONFLICT': 'xfa_split_field_conflict',
|
||||
'XFA_SPLIT_MIRROR_MISMATCH': 'xfa_split_mirror_mismatch',
|
||||
}
|
||||
|
||||
# 当前已接线、允许出现在 API 投影中的库存源不可用明细码
|
||||
@@ -361,6 +415,38 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'document_profile_ambiguous': _meta('owner', 'open_profile_review', '同时匹配到多个订单模板'),
|
||||
'document_profile_drifted': _meta('owner', 'open_profile_review', '文档结构与模板版本不一致'),
|
||||
'generic_gate_blocked': _meta('owner', 'open_order_review', '通用订单识别门禁未通过,需要人工复核'),
|
||||
# XFA 数据路径
|
||||
'xfa_dataset_missing': _meta('owner', 'open_profile_review', '文档缺少可用的 XFA datasets'),
|
||||
'xfa_unsafe_xml': _meta('owner', 'rematerialize_document', 'XFA XML 包含不安全结构,已拒绝解析'),
|
||||
'xfa_packet_too_large': _meta('owner', 'rematerialize_document', 'XFA packet 超过大小限制'),
|
||||
'xfa_xml_depth_exceeded': _meta('owner', 'rematerialize_document', 'XFA XML 嵌套深度超过限制'),
|
||||
'xfa_xml_node_limit_exceeded': _meta('owner', 'rematerialize_document', 'XFA XML 节点数超过限制'),
|
||||
'xfa_line_row_limit_exceeded': _meta('owner', 'open_order_review', 'XFA 明细行数超过限制'),
|
||||
'xfa_parse_timeout': _meta('worker', 'retry_order_extraction', 'XFA 解析超时'),
|
||||
'xfa_unsupported_document': _meta('owner', 'open_profile_review', '当前文档类型不受 XFA 数据路径模式支持'),
|
||||
'xfa_profile_not_matched': _meta('owner', 'open_profile_review', '未命中已发布的 XFA 模板'),
|
||||
'xfa_profile_ambiguous': _meta('owner', 'open_profile_review', '同时命中多个 XFA 模板'),
|
||||
'xfa_required_field_missing': _meta('owner', 'open_order_review', 'XFA 必填字段缺失'),
|
||||
'xfa_mirror_collection_mismatch': _meta('owner', 'open_order_review', 'XFA 镜像明细集合与权威集合不一致'),
|
||||
'xfa_acroform_mismatch': _meta('owner', 'open_order_review', 'XFA datasets 与 AcroForm 对账不一致'),
|
||||
'xfa_business_validation_failed': _meta('owner', 'open_order_review', 'XFA 业务恒等式校验失败'),
|
||||
'xfa_authoritative_collection_missing': _meta('owner', 'open_profile_review', '权威明细集合不存在'),
|
||||
'xfa_path_invalid': _meta('admin', 'open_profile_review', 'XFA 数据路径语法非法'),
|
||||
'xfa_path_unknown': _meta('admin', 'open_profile_review', 'XFA 数据路径不在结构分析记录中'),
|
||||
'xfa_definition_invalid': _meta('admin', 'open_profile_review', 'XFA 模板定义不合法'),
|
||||
'xfa_structure_identity_changed': _meta('owner', 'open_profile_review', 'XFA 结构身份已变化,需重新治理模板'),
|
||||
'xfa_split_rule_invalid': _meta('admin', 'open_profile_review', 'XFA 字段拆分规则不合法'),
|
||||
'xfa_split_field_conflict': _meta('owner', 'open_order_review', 'XFA 拆分段映射到同一正式字段发生冲突'),
|
||||
'xfa_split_mirror_mismatch': _meta('owner', 'open_order_review', 'XFA 拆分后正式字段权威/镜像不一致'),
|
||||
'xfa_auto_create_disabled': _meta('admin', 'open_order_review', '自动建单总开关未启用(Schema/CQ)'),
|
||||
'xfa_shadow_mode': _meta('admin', 'open_order_review', 'XFA 处于 shadow 模式,仅评估不自动建单'),
|
||||
'xfa_profile_not_blind_approved': _meta('admin', 'open_profile_review', 'XFA 模板当前 checksum 未通过盲测批准'),
|
||||
'xfa_allowlist_unconfigured': _meta('admin', 'open_profile_review', 'XFA 试点白名单未配置'),
|
||||
'xfa_customer_not_allowlisted': _meta('admin', 'open_order_review', '客户不在 XFA 自动建单白名单'),
|
||||
'xfa_profile_checksum_not_allowlisted': _meta('admin', 'open_profile_review', 'Profile checksum 不在 XFA 试点白名单'),
|
||||
'xfa_scenario_not_allowlisted': _meta('admin', 'open_order_review', '业务场景不在 XFA 试点白名单'),
|
||||
'xfa_evidence_incomplete': _meta('owner', 'open_order_review', 'XFA 证据不完整'),
|
||||
'xfa_cross_check_failed': _meta('owner', 'open_order_review', 'XFA 对账或业务恒等式未通过'),
|
||||
# Gate 既有阻断码
|
||||
'document_unavailable': _meta('system', 'rematerialize_document', '发货通知文档不可用,请重新上传或物化文档'),
|
||||
'layout_parse_failed': _meta('worker', 'retry_layout_parsing', 'PDF 版面解析失败,请重试解析'),
|
||||
@@ -374,6 +460,16 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'classification_low_confidence': _meta('owner', 'open_order_review', '订单分类置信度不足'),
|
||||
'field_conflict': _meta('owner', 'resolve_field_conflicts', '同一字段存在不同来源值冲突'),
|
||||
'cross_source_conflict': _meta('owner', 'resolve_field_conflicts', '跨来源字段冲突,请解决冲突后继续'),
|
||||
'pdf_preferred_critical_conflict': _meta(
|
||||
'owner',
|
||||
'resolve_field_conflicts',
|
||||
'关键字段 PDF 与辅助证据冲突:已取 PDF 当前值,须人工确认后建单',
|
||||
),
|
||||
'pdf_preferred': _meta(
|
||||
'owner',
|
||||
'resolve_field_conflicts',
|
||||
'字段已按 PDF 优先裁决,请核对辅助证据差异',
|
||||
),
|
||||
'evidence_missing': _meta('owner', 'open_order_review', '关键识别结果缺少有效证据'),
|
||||
'customer_unresolved': _meta('owner', 'confirm_customer', '未能识别客户'),
|
||||
'customer_ambiguous': _meta('owner', 'confirm_customer', '匹配到多个客户'),
|
||||
|
||||
@@ -28,7 +28,7 @@ from app.models import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventorySource,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingTask,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.path_utils import resolve_backend_relative_path
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
@@ -42,7 +42,7 @@ def _storage_root() -> Path:
|
||||
return Path(current_app.instance_path) / 'shipping_notice'
|
||||
|
||||
|
||||
def order_field_id_values(task: ShippingTask) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""从冻结 Snapshot 按稳定 field_id 返回 Header/Line 值,禁止履约阶段读取 FieldValue。"""
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
assert_task_not_supersession_blocked(task)
|
||||
@@ -58,7 +58,7 @@ def order_field_id_values(task: ShippingTask) -> tuple[dict[str, Any], list[dict
|
||||
return header, lines
|
||||
|
||||
|
||||
def _system_fact(task: ShippingTask, key: str, *, export_sequence: int | None = None) -> Any:
|
||||
def _system_fact(task: ShippingNotice, key: str, *, export_sequence: int | None = None) -> Any:
|
||||
"""
|
||||
读取受控任务事实,模板不能通过任意属性路径访问 ORM。
|
||||
|
||||
@@ -107,7 +107,7 @@ def _format_value(value: Any, formatter: str) -> Any:
|
||||
|
||||
|
||||
def _mapping_value(
|
||||
mapping: dict[str, Any], *, task: ShippingTask, order_values: dict[str, Any], inventory_values: dict[str, Any],
|
||||
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,
|
||||
) -> Any:
|
||||
"""
|
||||
@@ -251,7 +251,7 @@ def _safe_filename(name: str) -> str:
|
||||
return cleaned if cleaned.lower().endswith('.xlsx') else f'{cleaned}.xlsx'
|
||||
|
||||
|
||||
def _filename(task: ShippingTask, template: ShippingExcelTemplate) -> str:
|
||||
def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str:
|
||||
"""按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。"""
|
||||
pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip()
|
||||
if not pattern:
|
||||
@@ -277,7 +277,7 @@ def _filename(task: ShippingTask, template: ShippingExcelTemplate) -> str:
|
||||
|
||||
|
||||
def _input_checksum(
|
||||
task: ShippingTask, source: ShippingInventorySource, template: ShippingExcelTemplate,
|
||||
task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate,
|
||||
snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]],
|
||||
) -> str:
|
||||
"""计算完整生成输入指纹,供审计和重复生成差异判断。"""
|
||||
@@ -292,7 +292,7 @@ def _input_checksum(
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str, ShippingExportArtifact]:
|
||||
def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExportArtifact]:
|
||||
"""
|
||||
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
|
||||
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
|
||||
@@ -398,7 +398,7 @@ def generate_shipment_excel(task: ShippingTask) -> tuple[str, str, ShippingExpor
|
||||
# 滚动履约允许同一任务按后续库存分批导出;已就绪 Artifact 仍是
|
||||
# 已占用预约单的审计事实,不能被新一轮导出整体覆盖为 superseded。
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=task.id, batch_id=task.batch_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),
|
||||
|
||||
@@ -17,13 +17,13 @@ from typing import BinaryIO
|
||||
from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ShippingExportArtifact, ShippingTask
|
||||
from app.models import ShippingExportArtifact, ShippingNotice
|
||||
from app.services.shipping_notice.query_service import get_batch_for_user, get_task_for_user, list_sorted_batch_tasks
|
||||
|
||||
MAX_ARCHIVE_TASKS = 100
|
||||
|
||||
|
||||
def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | None) -> tuple[list[ShippingTask], str]:
|
||||
def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | None) -> tuple[list[ShippingNotice], str]:
|
||||
"""按批次或任务号选择当前用户任务;两种模式互斥且禁止部分越权成功。"""
|
||||
normalized_batch = str(batch_no or '').strip()
|
||||
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_nos or []) if str(item or '').strip()))
|
||||
@@ -53,10 +53,10 @@ def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | N
|
||||
return tasks, archive_key
|
||||
|
||||
|
||||
def _ready_artifacts(tasks: list[ShippingTask]) -> dict[int, list[ShippingExportArtifact]]:
|
||||
def _ready_artifacts(tasks: list[ShippingNotice]) -> dict[int, list[ShippingExportArtifact]]:
|
||||
"""批量查询每票全部可下载 Artifact,滚动履约不得遗漏前一轮 Excel。"""
|
||||
task_ids = [int(task.id) for task in tasks if task.id is not None]
|
||||
rows = ShippingExportArtifact.query.join(ShippingTask, ShippingTask.id == ShippingExportArtifact.task_id).filter(
|
||||
rows = ShippingExportArtifact.query.join(ShippingNotice, ShippingNotice.id == ShippingExportArtifact.task_id).filter(
|
||||
ShippingExportArtifact.task_id.in_(task_ids), ShippingExportArtifact.status == 'ready',
|
||||
).order_by(ShippingExportArtifact.created_at, ShippingExportArtifact.id).all()
|
||||
result: dict[int, list[ShippingExportArtifact]] = {}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/field_adjudication.py
|
||||
|
||||
用途:把后端表格解析与 Dify LLM 输出转换为不可变字段 Observation,并生成规范订单行裁决结果。
|
||||
依赖:ShippingNoticeDocument、notice_lines、标准库 hashlib/json/re。
|
||||
依赖:ShippingOrderDocument、notice_lines、标准库 hashlib/json/re。
|
||||
逻辑:后台 Run 结果持久化在 Candidate 校验前调用;原始 Observation 只追加不互相覆盖,裁决结果另行投影。
|
||||
"""
|
||||
|
||||
@@ -14,7 +14,7 @@ import re
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingNoticeDocument
|
||||
from app.models import ShippingOrderDocument
|
||||
from app.services.shipping_notice.notice_lines import normalize_notice_line, parse_notice_table_text
|
||||
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
|
||||
|
||||
@@ -70,7 +70,7 @@ def _quote_supports_value(field: str, value: Any, quote: str) -> bool:
|
||||
def _evidence_for_field(
|
||||
*,
|
||||
evidence_items: list[dict[str, Any]],
|
||||
documents_by_id: dict[int, ShippingNoticeDocument],
|
||||
documents_by_id: dict[int, ShippingOrderDocument],
|
||||
line_index: int,
|
||||
field: str,
|
||||
value: Any,
|
||||
@@ -129,7 +129,7 @@ def _make_observation(
|
||||
|
||||
|
||||
def _backend_rows(
|
||||
documents: list[ShippingNoticeDocument], *, schema_definition: dict[str, Any],
|
||||
documents: list[ShippingOrderDocument], *, schema_definition: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""从每个锁定 Document 的保留列边界文本生成后端表格 Observation 原料。"""
|
||||
contract = compile_table_header_contract(schema_definition)
|
||||
@@ -170,7 +170,7 @@ def _dify_observations(
|
||||
normalized_line: dict[str, Any],
|
||||
line_index: int,
|
||||
evidence_items: list[dict[str, Any]],
|
||||
documents_by_id: dict[int, ShippingNoticeDocument],
|
||||
documents_by_id: dict[int, ShippingOrderDocument],
|
||||
field_confidence: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""将 Dify 行转换为 Observation;自报 confidence 只贡献最多 10 分。"""
|
||||
@@ -326,7 +326,7 @@ def adjudicate_order_fields(
|
||||
summary: dict[str, Any],
|
||||
*,
|
||||
raw_order: dict[str, Any],
|
||||
documents: list[ShippingNoticeDocument],
|
||||
documents: list[ShippingOrderDocument],
|
||||
schema_definition: dict[str, Any],
|
||||
field_confidence: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
|
||||
@@ -18,7 +18,7 @@ from app.models import (
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingTask,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import required_field_configs
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
@@ -32,7 +32,7 @@ _OWNING_GATE = 'order_freeze_readiness'
|
||||
|
||||
def evaluate_freeze_readiness_gate(
|
||||
*,
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
extraction: ShippingOrderExtraction,
|
||||
configs: dict[str, dict[str, Any]],
|
||||
freeze_mode: str = 'manual',
|
||||
@@ -146,7 +146,7 @@ def evaluate_freeze_readiness_gate(
|
||||
|
||||
def assert_freeze_readiness(
|
||||
*,
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
extraction: ShippingOrderExtraction,
|
||||
configs: dict[str, dict[str, Any]],
|
||||
freeze_mode: str = 'manual',
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/freight_cancellation_service.py
|
||||
|
||||
用途:货代撤销回执登记,以及建单后取消时的只读 / 待作废软处置(禁止物理删除)。
|
||||
依赖:ShippingFreightCancellation、ShippingTask、ShippingTaskEvent、Workflow Item Version、
|
||||
依赖:ShippingFreightCancellation、ShippingNotice、ShippingTaskEvent、Workflow Item Version、
|
||||
fulfillment_audit。
|
||||
逻辑:complete_freight_cancellation 登记回执并作废旧任务;mark_cancelled_task_readonly
|
||||
在用户取消已建单 WorkflowItem 时将 Task 置 pending_void、Excel/Version 只读,
|
||||
@@ -16,7 +16,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingFreightCancellation, ShippingTask, ShippingTaskEvent
|
||||
from app.models import ShippingFreightCancellation, ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
|
||||
@@ -49,8 +49,8 @@ def complete_freight_cancellation(
|
||||
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')
|
||||
old = ShippingTask.query.filter_by(id=row.old_task_id).with_for_update().one()
|
||||
new = ShippingTask.query.filter_by(id=row.new_task_id).with_for_update().one()
|
||||
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:
|
||||
raise ConflictError('Cancellation task relationship is invalid', code='SHIPPING.FREIGHT_CANCELLATION_INVALID')
|
||||
row.status = 'cancelled'
|
||||
@@ -111,7 +111,7 @@ def complete_freight_cancellation(
|
||||
return row
|
||||
|
||||
|
||||
def _task_cancel_snapshot(task: ShippingTask) -> dict[str, Any]:
|
||||
def _task_cancel_snapshot(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""构造取消处置前后快照(白名单字段)。"""
|
||||
return {
|
||||
'task_no': str(task.task_no),
|
||||
@@ -125,7 +125,7 @@ def _task_cancel_snapshot(task: ShippingTask) -> dict[str, Any]:
|
||||
|
||||
def mark_cancelled_task_readonly(
|
||||
*,
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
actor_id: int,
|
||||
reason: str,
|
||||
workflow_item_no: str | None = None,
|
||||
@@ -136,7 +136,7 @@ def mark_cancelled_task_readonly(
|
||||
核心逻辑:不 unlink 导出文件、不 purge 任务行;写统一审计(reason + before/after)。
|
||||
|
||||
Args:
|
||||
task: 已加载且加锁的 ShippingTask。
|
||||
task: 已加载且加锁的 ShippingNotice。
|
||||
actor_id: 取消操作人。
|
||||
reason: 必填取消原因。
|
||||
workflow_item_no: 可选关联 WorkflowItem 编号。
|
||||
@@ -156,17 +156,7 @@ def mark_cancelled_task_readonly(
|
||||
task.lifecycle_status = 'pending_void'
|
||||
task.void_reason = reason_text
|
||||
task.pending_human_reason = 'pending_void'
|
||||
# Version / Excel 只读:按任务号定位当前 Workflow Version。
|
||||
from app.models.shipping_notice_workflow import ShippingNoticeWorkflowItemVersion
|
||||
|
||||
versions = (
|
||||
ShippingNoticeWorkflowItemVersion.query
|
||||
.filter_by(task_no=str(task.task_no))
|
||||
.all()
|
||||
)
|
||||
for version in versions:
|
||||
version.is_readonly = True
|
||||
version.updated_at = datetime.utcnow()
|
||||
# co8:Workflow Version 已 DROP;只读语义改由 Task.lifecycle_status=pending_void 表达。
|
||||
after = _task_cancel_snapshot(task)
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=int(task.id),
|
||||
|
||||
@@ -10,7 +10,8 @@ services/shipping_notice/fulfillment_workflow.py
|
||||
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(人工凭据)。
|
||||
upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工凭据);
|
||||
RPA 成功须带白名单 kind + page_url + dom_snippet/dom_sha256,并尽量落 evidence_asset。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,7 +25,7 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError
|
||||
from app.models import ShippingTask
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.constants import CP_UPLOADED
|
||||
from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task
|
||||
@@ -79,19 +80,197 @@ def _cfg_bool(key: str, default: bool = False) -> bool:
|
||||
|
||||
|
||||
def _rpa_callback_success(value: Any) -> bool:
|
||||
"""严格解析 Worker 上传回调结果,拒绝把字符串 ``"false"`` 当作成功。"""
|
||||
"""
|
||||
严格解析 Worker 上传回调结果。
|
||||
|
||||
核心逻辑:缺省/None → False(fail-closed);仅显式 True/'true'/'1' 视为成功;
|
||||
非法值抛 ValidationError,禁止把未知字符串当成功。
|
||||
"""
|
||||
if value is None:
|
||||
return False
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
if isinstance(value, str):
|
||||
normalized = value.strip().lower()
|
||||
if normalized in {'true', '1'}:
|
||||
return True
|
||||
if normalized in {'false', '0'}:
|
||||
if normalized in {'false', '0', ''}:
|
||||
return False
|
||||
raise ValidationError('Upload callback success must be boolean', code='SHIPPING.UPLOAD_CALLBACK_INVALID')
|
||||
|
||||
|
||||
def _task_disposition_gate_response(task: ShippingTask) -> dict[str, Any] | None:
|
||||
# [BE-05] RPA 绿色 DOM 成功证据允许的 kind 白名单(与 freight_rpa_worker 对齐)。
|
||||
_RPA_SUCCESS_EVIDENCE_KINDS = frozenset({
|
||||
'configured_success_selector',
|
||||
'dsv_history_green_dom',
|
||||
'green_success_dom',
|
||||
})
|
||||
|
||||
|
||||
def _normalize_rpa_success_evidence(
|
||||
payload: dict[str, Any],
|
||||
*,
|
||||
expected_filename: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
校验 RPA 成功回调中的 success_evidence(BE-05 fail-closed)。
|
||||
|
||||
核心逻辑:kind 须在白名单;selector / observed_at / filename / page_url 必填;
|
||||
必须带 dom_snippet + 匹配的 dom_sha256(不可变 DOM 证据);
|
||||
若提供 expected_filename 则须与证据文件名一致(大小写不敏感)。
|
||||
|
||||
Args:
|
||||
payload: Worker 回调 JSON。
|
||||
expected_filename: 本次 Artifact 文件名;传入时强制比对。
|
||||
|
||||
Returns:
|
||||
规范化 evidence dict;缺失/非法时 None。
|
||||
"""
|
||||
import hashlib
|
||||
|
||||
raw = payload.get('success_evidence')
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
kind = str(raw.get('kind') or '').strip()
|
||||
if kind not in _RPA_SUCCESS_EVIDENCE_KINDS:
|
||||
return None
|
||||
selector = str(raw.get('selector') or '').strip()
|
||||
observed_at = str(raw.get('observed_at') or '').strip()
|
||||
filename = str(raw.get('filename') or '').strip()
|
||||
page_url = str(raw.get('page_url') or raw.get('url') or '').strip()
|
||||
dom_snippet = str(raw.get('dom_snippet') or '').strip()
|
||||
dom_sha256 = str(raw.get('dom_sha256') or '').strip().lower()
|
||||
if not selector or not observed_at or not filename or not page_url:
|
||||
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:
|
||||
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,
|
||||
'filename': filename,
|
||||
'reference': str(raw.get('reference') or '').strip() or None,
|
||||
'observed_at': observed_at,
|
||||
'page_url': page_url,
|
||||
'dom_snippet': dom_snippet[:8000],
|
||||
'dom_sha256': dom_sha256,
|
||||
'screenshot_sha256': screenshot_sha256,
|
||||
'screenshot_base64': screenshot_base64,
|
||||
}
|
||||
|
||||
|
||||
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)。
|
||||
"""
|
||||
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.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"
|
||||
mime_type = 'text/html; charset=utf-8'
|
||||
if raw_b64:
|
||||
try:
|
||||
data = base64.b64decode(raw_b64, validate=False)
|
||||
except Exception:
|
||||
data = None
|
||||
if data:
|
||||
filename = f"rpa-success-{int(attempt.id)}.png"
|
||||
mime_type = 'image/png'
|
||||
if not data:
|
||||
snippet = str(success_evidence.get('dom_snippet') or '').encode('utf-8')
|
||||
if not snippet:
|
||||
return None
|
||||
data = snippet
|
||||
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,
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
try:
|
||||
file_asset_storage.upload_bytes(storage_key=storage_key, data=data, content_type=mime_type)
|
||||
asset.upload_status = 'ready'
|
||||
except Exception:
|
||||
db.session.delete(asset)
|
||||
db.session.flush()
|
||||
return None
|
||||
attempt.evidence_asset_id = int(asset.id)
|
||||
mark_asset_referenced(asset)
|
||||
success_evidence['evidence_asset_id'] = int(asset.id)
|
||||
success_evidence['evidence_asset_no'] = asset_no
|
||||
return int(asset.id)
|
||||
|
||||
|
||||
|
||||
def _hash_rpa_evidence_field(value: str | None) -> str | None:
|
||||
"""对 evidence 中的 filename/reference 做 sha256,审计禁止落原文。"""
|
||||
if not value:
|
||||
return None
|
||||
import hashlib
|
||||
|
||||
return hashlib.sha256(value.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _task_disposition_gate_response(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""在履约副作用前阻断回收站、作废或归档任务,避免迟到请求继续改变业务事实。"""
|
||||
reason = task_execution_block_reason(task)
|
||||
if reason is None:
|
||||
@@ -106,7 +285,7 @@ def _task_disposition_gate_response(task: ShippingTask) -> dict[str, Any] | None
|
||||
|
||||
|
||||
def _reservation_gate_response(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
lang: str,
|
||||
forbidden_next_tools: list[str],
|
||||
@@ -206,7 +385,7 @@ def _rpa_upload_timeout_seconds() -> int:
|
||||
|
||||
|
||||
def _trigger_freight_upload_rpa(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
payload: dict[str, Any] | None = None,
|
||||
lang: str | None = None,
|
||||
@@ -398,7 +577,7 @@ def _event_actor_id(payload: dict[str, Any]) -> int | None:
|
||||
|
||||
|
||||
def _sync_workflow_stage(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
lifecycle_status: str,
|
||||
event_code: str,
|
||||
@@ -432,7 +611,7 @@ def _sync_workflow_stage(
|
||||
)
|
||||
|
||||
|
||||
def match_completed(task: ShippingTask) -> bool:
|
||||
def match_completed(task: ShippingNotice) -> bool:
|
||||
"""
|
||||
STP 制单门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时允许生成 Excel。
|
||||
|
||||
@@ -491,7 +670,7 @@ def _match_step_progress_fields(
|
||||
}
|
||||
|
||||
|
||||
def excel_gate_error(task: ShippingTask) -> str | None:
|
||||
def excel_gate_error(task: ShippingNotice) -> str | None:
|
||||
"""校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。"""
|
||||
if task.process_status == "uploaded" and task.export_file_path:
|
||||
return None
|
||||
@@ -513,7 +692,7 @@ def should_auto_chain_after_match(payload: dict[str, Any] | None) -> bool:
|
||||
|
||||
|
||||
def try_auto_chain_after_match(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
match_result: dict[str, Any],
|
||||
*,
|
||||
payload: dict[str, Any] | None = None,
|
||||
@@ -526,7 +705,7 @@ def try_auto_chain_after_match(
|
||||
关闭时停在 wait_manual_upload 待人工登记。
|
||||
|
||||
Args:
|
||||
task: 当前 ShippingTask。
|
||||
task: 当前 ShippingNotice。
|
||||
match_result: match_inventory 的 Tool 响应。
|
||||
payload: 原始请求体,用于读取 auto_chain_fallback 与 lang 等字段。
|
||||
|
||||
@@ -585,7 +764,7 @@ def try_auto_chain_after_match(
|
||||
|
||||
|
||||
def _order_extraction_gate_response(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
forbidden_next_tools: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
@@ -1251,9 +1430,11 @@ 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。
|
||||
|
||||
Args:
|
||||
payload: 须含 task_id;success(bool,默认 True);可选 freight_ref_no、error_message。
|
||||
payload: 须含 task_id;success(bool,缺省视为失败);success_evidence(成功必填);
|
||||
可选 freight_ref_no、error_message。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: 成功时 checkpoint=uploaded;失败时 needs_human 并附带 error_message。
|
||||
@@ -1282,9 +1463,55 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if artifact is None or artifact.task_id != task.id:
|
||||
return tool_response(status='failed', task=task, message='Upload attempt does not belong to this task', data=serialize_task_for_tool(task))
|
||||
try:
|
||||
success = _rpa_callback_success(payload.get("success", True))
|
||||
success = _rpa_callback_success(payload.get("success"))
|
||||
except ValidationError as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
success_evidence: dict[str, Any] | None = None
|
||||
if success:
|
||||
expected_filename = (
|
||||
str(getattr(artifact, 'file_name', None) or getattr(artifact, 'filename', None) or '').strip()
|
||||
or None
|
||||
)
|
||||
success_evidence = _normalize_rpa_success_evidence(
|
||||
payload, expected_filename=expected_filename,
|
||||
)
|
||||
if success_evidence is None:
|
||||
return tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
message=(
|
||||
'RPA upload success requires success_evidence '
|
||||
'(kind whitelist, selector, observed_at, filename matching artifact, '
|
||||
'page_url, dom_snippet+dom_sha256)'
|
||||
),
|
||||
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 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'
|
||||
}
|
||||
try:
|
||||
completed = complete_attempt(
|
||||
attempt, success=success, callback_id=str(payload.get('callback_id') or f'rpa:{attempt.id}'),
|
||||
@@ -1294,8 +1521,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
# 重复 callback 由 Attempt 的持久化结果决定,不能按本次请求值重写 UI 状态。
|
||||
if completed.status == 'succeeded':
|
||||
if task.process_status == 'uploaded':
|
||||
apply_task_transition(task, TaskTransition.UPLOADED)
|
||||
apply_task_transition(task, TaskTransition.UPLOADED)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step7_upload_freight",
|
||||
@@ -1319,7 +1545,25 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
result='success',
|
||||
before={'status': 'uploading'},
|
||||
after={'status': 'uploaded'},
|
||||
metadata={'attempt_id': int(completed.id), 'artifact_id': int(completed.artifact_id or 0) or None},
|
||||
metadata={
|
||||
'attempt_id': int(completed.id),
|
||||
'artifact_id': int(completed.artifact_id or 0) or None,
|
||||
'artifact_file_checksum': str(getattr(artifact, 'file_checksum', None) or '') or None,
|
||||
'success_evidence': {
|
||||
'kind': success_evidence.get('kind') if success_evidence else None,
|
||||
'selector': success_evidence.get('selector') if success_evidence else None,
|
||||
'observed_at': success_evidence.get('observed_at') if success_evidence else None,
|
||||
'page_url_hash': _hash_rpa_evidence_field(
|
||||
success_evidence.get('page_url') if success_evidence else None
|
||||
),
|
||||
'filename_hash': _hash_rpa_evidence_field(
|
||||
success_evidence.get('filename') if success_evidence else None
|
||||
),
|
||||
'reference_hash': _hash_rpa_evidence_field(
|
||||
success_evidence.get('reference') if success_evidence else None
|
||||
),
|
||||
},
|
||||
},
|
||||
source='rpa_callback',
|
||||
)
|
||||
db.session.commit()
|
||||
@@ -1361,7 +1605,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
def run_auto_progress_fulfillment_steps(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
payload: dict[str, Any],
|
||||
steps: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
|
||||
@@ -15,8 +15,8 @@ from app.models import (
|
||||
ShippingCustomerSite,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
@@ -54,7 +54,7 @@ def _published_rule_set() -> ShippingIdentityRuleSet | None:
|
||||
return ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none()
|
||||
|
||||
|
||||
def _accepted_header_values(candidate: ShippingNoticeCandidate) -> tuple[ShippingOrderExtraction | None, dict[str, dict[str, Any]]]:
|
||||
def _accepted_header_values(candidate: ShippingOrderCandidate) -> tuple[ShippingOrderExtraction | None, dict[str, dict[str, Any]]]:
|
||||
"""读取已裁决 Header FieldValue 及其决定主键,保留自动确认所需完整追溯链。"""
|
||||
if candidate.order_extraction_id is None:
|
||||
return None, {}
|
||||
@@ -124,7 +124,7 @@ def _resolved_context_field_id(
|
||||
|
||||
|
||||
def _source_evidence(
|
||||
definitions: list[dict[str, Any]], *, candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake,
|
||||
definitions: list[dict[str, Any]], *, candidate: ShippingOrderCandidate, intake: ShippingOrderIntake,
|
||||
) -> tuple[list[dict[str, Any]], ShippingOrderExtraction | None]:
|
||||
"""按规则快照编译证据;Schema UUID 漂移时仅映射语义兼容的 Header 字段。"""
|
||||
extraction, header_values = _accepted_header_values(candidate)
|
||||
@@ -232,7 +232,7 @@ def _rank_site_matches(evidence: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
], key=lambda item: (-float(item['score']), int(item['site_id'])))
|
||||
|
||||
|
||||
def resolve_candidate_identity(candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake) -> dict[str, Any]:
|
||||
def resolve_candidate_identity(candidate: ShippingOrderCandidate, intake: ShippingOrderIntake) -> dict[str, Any]:
|
||||
"""
|
||||
解析一个 Candidate 的身份影子候选。
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/intake_business_parser.py
|
||||
|
||||
用途:从发货通知抽取文本产出稳定业务摘要(预解析阶段,不创建 ShippingTask)。
|
||||
用途:从发货通知抽取文本产出稳定业务摘要(预解析阶段,不创建 ShippingNotice)。
|
||||
依赖:extract.extract_notice_fields、notice_lines。
|
||||
逻辑:由 intake_parse_workflow 在文本抽取成功后调用;仅作预解析摘要,不参与正式动态订单落库。
|
||||
"""
|
||||
|
||||
@@ -23,10 +23,10 @@ from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.notice_upload import (
|
||||
@@ -366,7 +366,7 @@ def _db_parse_status(intake_id: int) -> str | None:
|
||||
|
||||
核心逻辑:expire 本地缓存后 refresh,避免抽取耗时窗口内他事务 cancel 后仍读到 parsing。
|
||||
"""
|
||||
obj = db.session.get(ShippingNoticeIntake, int(intake_id))
|
||||
obj = db.session.get(ShippingOrderIntake, int(intake_id))
|
||||
if obj is None:
|
||||
return None
|
||||
db.session.expire(obj)
|
||||
@@ -374,19 +374,19 @@ def _db_parse_status(intake_id: int) -> str | None:
|
||||
return str(obj.parse_status or '')
|
||||
|
||||
|
||||
def _lock_intake_row(intake_id: int) -> ShippingNoticeIntake | None:
|
||||
def _lock_intake_row(intake_id: int) -> ShippingOrderIntake | None:
|
||||
"""
|
||||
FOR UPDATE 锁定 Intake 行(与 cancel / refresh / retry 同序之首)。
|
||||
|
||||
核心逻辑:先 expire 本地缓存并以 populate_existing 重读,避免抽取窗口内他事务
|
||||
已 cancel 而身份映射仍返回 parsing。
|
||||
"""
|
||||
cached = db.session.get(ShippingNoticeIntake, int(intake_id))
|
||||
cached = db.session.get(ShippingOrderIntake, int(intake_id))
|
||||
if cached is not None:
|
||||
db.session.expire(cached)
|
||||
return (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.id == int(intake_id))
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(ShippingOrderIntake.id == int(intake_id))
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
@@ -408,7 +408,7 @@ def _strip_stage2_keys_from_summary(summary: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _parse_lease_matches(
|
||||
locked: ShippingNoticeIntake,
|
||||
locked: ShippingOrderIntake,
|
||||
*,
|
||||
required_lease: str | None,
|
||||
) -> bool:
|
||||
@@ -437,7 +437,7 @@ def _fail_intake_with_stage2_cleanup(
|
||||
parse_warnings_json: list[str] | None,
|
||||
allowed_statuses: frozenset[str] | None = None,
|
||||
commit: bool = True,
|
||||
locked_intake: ShippingNoticeIntake | None = None,
|
||||
locked_intake: ShippingOrderIntake | None = None,
|
||||
required_lease: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -534,8 +534,8 @@ def sync_intake_after_parse_job_recovery(job: Any) -> None:
|
||||
return
|
||||
|
||||
locked = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == intake_no)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(ShippingOrderIntake.intake_no == intake_no)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
.first()
|
||||
@@ -621,7 +621,7 @@ def sync_intake_after_parse_job_recovery(job: Any) -> None:
|
||||
|
||||
|
||||
def _run_business_dedup_after_parse(
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
asset: FileAsset,
|
||||
*,
|
||||
extracted_text: str,
|
||||
@@ -684,7 +684,7 @@ def _run_business_dedup_after_parse(
|
||||
|
||||
|
||||
def run_intake_parse(
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
asset: FileAsset,
|
||||
*,
|
||||
parse_lease: str | None = None,
|
||||
@@ -793,7 +793,7 @@ def run_intake_parse(
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts
|
||||
|
||||
layout_versions = schedule_document_layouts(
|
||||
ShippingNoticeDocument.query.filter_by(intake_id=locked.id).all(),
|
||||
ShippingOrderDocument.query.filter_by(intake_id=locked.id).all(),
|
||||
created_by_id=locked.user_id,
|
||||
)
|
||||
persist_info['layout_version_count'] = len(layout_versions)
|
||||
@@ -905,7 +905,7 @@ def run_intake_parse(
|
||||
)
|
||||
|
||||
|
||||
def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dict[str, Any]:
|
||||
def intake_to_notice_item(intake: ShippingOrderIntake, asset: FileAsset) -> dict[str, Any]:
|
||||
"""
|
||||
将已解析 intake 转为兼容 create_batch 的 notice_item(含业务指纹与重复决策元数据)。
|
||||
|
||||
@@ -933,8 +933,8 @@ def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dic
|
||||
target_no = str(intake.duplicate_target_task_no or '').strip().upper()
|
||||
if resolution == 'create_revision' and target_no:
|
||||
target = (
|
||||
db.session.query(ShippingTask)
|
||||
.filter(ShippingTask.task_no == target_no)
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(ShippingNotice.task_no == target_no)
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
@@ -945,8 +945,8 @@ def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dic
|
||||
details={'target_task_no': target_no},
|
||||
)
|
||||
existing_successor = (
|
||||
db.session.query(ShippingTask.id)
|
||||
.filter(ShippingTask.supersedes_task_id == int(target.id))
|
||||
db.session.query(ShippingNotice.id)
|
||||
.filter(ShippingNotice.supersedes_task_id == int(target.id))
|
||||
.first()
|
||||
)
|
||||
if existing_successor is not None:
|
||||
@@ -960,8 +960,8 @@ def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dic
|
||||
item['duplicate_resolution_type'] = 'revision'
|
||||
elif resolution == 'force_create' and target_no:
|
||||
target = (
|
||||
db.session.query(ShippingTask)
|
||||
.filter(ShippingTask.task_no == target_no)
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(ShippingNotice.task_no == target_no)
|
||||
.first()
|
||||
)
|
||||
if target:
|
||||
@@ -972,9 +972,9 @@ def intake_to_notice_item(intake: ShippingNoticeIntake, asset: FileAsset) -> dic
|
||||
|
||||
|
||||
def candidate_to_notice_item(
|
||||
candidate: ShippingNoticeCandidate,
|
||||
intake: ShippingNoticeIntake,
|
||||
document: ShippingNoticeDocument,
|
||||
candidate: ShippingOrderCandidate,
|
||||
intake: ShippingOrderIntake,
|
||||
document: ShippingOrderDocument,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将已审核 Candidate 转换为独立 notice_item。
|
||||
@@ -1009,20 +1009,20 @@ def candidate_to_notice_item(
|
||||
target_no = str(candidate.duplicate_target_task_no or '').strip().upper()
|
||||
if resolution == 'create_revision' and target_no:
|
||||
target = (
|
||||
db.session.query(ShippingTask)
|
||||
db.session.query(ShippingNotice)
|
||||
.filter_by(task_no=target_no, user_id=int(intake.user_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if target is None:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.REVISION_TARGET_INVALID', message='修订目标任务不存在')
|
||||
if db.session.query(ShippingTask.id).filter_by(supersedes_task_id=int(target.id)).first():
|
||||
if db.session.query(ShippingNotice.id).filter_by(supersedes_task_id=int(target.id)).first():
|
||||
raise ConflictError(code='SHIPPING_NOTICE.REVISION_CONFLICT', message='目标任务已有修订版本')
|
||||
item['supersedes_task_id'] = int(target.id)
|
||||
item['document_version'] = int(target.document_version or 1) + 1
|
||||
item['duplicate_resolution_type'] = 'revision'
|
||||
elif resolution == 'force_create' and target_no:
|
||||
target = db.session.query(ShippingTask).filter_by(
|
||||
target = db.session.query(ShippingNotice).filter_by(
|
||||
task_no=target_no,
|
||||
user_id=int(intake.user_id),
|
||||
).first()
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/intake_service.py
|
||||
|
||||
用途:发货通知接入记录(ShippingNoticeIntake)业务编排(含重复决策投影与权限)。
|
||||
用途:发货通知接入记录(ShippingOrderIntake)业务编排(含重复决策投影与权限)。
|
||||
依赖:file_assets.service、intake_parse_workflow、order_extraction、jobs.queue、models、
|
||||
duplicate_detection、attachment_integrity、document_layout 生命周期模型。
|
||||
duplicate_detection、attachment_integrity、document_layout 生命周期模型、
|
||||
order_submission_service(阶段 1 上传 Submission / source_type)。
|
||||
逻辑:由 workspace API 与 chat action 调用;解析 Job 由 intake_parse_workflow 执行;
|
||||
创建 Intake:SAVEPOINT 插入 + IntegrityError 回落,mutate/enqueue 前 FOR UPDATE;
|
||||
业务 purpose 创建时挂接 shipping_order_submissions 并写入 eml|direct_pdf;
|
||||
cancelled/expired 拒绝复活;重投仅复用 queued Job(与 retry 同口径);
|
||||
状态轮询用瘦身 parse_summary。
|
||||
"""
|
||||
@@ -27,14 +29,20 @@ from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderSubmission,
|
||||
ShippingNotice,
|
||||
User,
|
||||
)
|
||||
from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced
|
||||
from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
|
||||
|
||||
from app.services.shipping_notice.order_submission_service import (
|
||||
attach_intake_to_order_submission,
|
||||
ensure_order_submission_for_upload_batch,
|
||||
resolve_order_intake_source_type,
|
||||
serialize_order_submission,
|
||||
)
|
||||
from app.services.shipping_notice.queue_service import SHIPPING_NOTICE_JOB_DOMAIN
|
||||
|
||||
ACTIVE_INTAKE_STATUSES = frozenset(
|
||||
@@ -67,7 +75,7 @@ def generate_intake_no() -> str:
|
||||
return f"SNI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def _duplicate_payload_from_intake(intake: ShippingNoticeIntake) -> dict[str, Any]:
|
||||
def _duplicate_payload_from_intake(intake: ShippingOrderIntake) -> dict[str, Any]:
|
||||
"""
|
||||
从 intake 投影 duplicate 载荷(供轮询/卡片展示)。
|
||||
|
||||
@@ -160,7 +168,7 @@ def _lean_parse_summary(structured: dict[str, Any] | None) -> dict[str, Any]:
|
||||
|
||||
|
||||
def serialize_intake(
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
*,
|
||||
asset: FileAsset | None = None,
|
||||
include_parse_texts: bool = False,
|
||||
@@ -197,6 +205,8 @@ def serialize_intake(
|
||||
'asset_no': asset.asset_no if asset else None,
|
||||
'conversation_id': intake.conversation_id,
|
||||
'upload_batch_id': intake.upload_batch_id,
|
||||
'source_type': intake.source_type,
|
||||
'submission_no': None,
|
||||
'parse_status': intake.parse_status,
|
||||
'parser_version': intake.parser_version,
|
||||
'order_extraction_status': intake.order_extraction_status,
|
||||
@@ -223,6 +233,11 @@ def serialize_intake(
|
||||
'created_at': utc_iso(intake.created_at),
|
||||
'updated_at': utc_iso(intake.updated_at),
|
||||
}
|
||||
if intake.order_submission_id:
|
||||
submission = db.session.get(ShippingOrderSubmission, int(intake.order_submission_id))
|
||||
if submission is not None:
|
||||
payload['submission_no'] = submission.submission_no
|
||||
payload['order_submission'] = serialize_order_submission(submission)
|
||||
if asset:
|
||||
payload['original_filename'] = asset.original_filename
|
||||
payload['file_size'] = asset.file_size
|
||||
@@ -235,7 +250,7 @@ def _serialize_intake_layout_summary(intake_id: int) -> dict[str, Any]:
|
||||
汇总 Intake 下已调度的文档版面任务,供聊天页判断订单识别是否可启动。
|
||||
|
||||
Args:
|
||||
intake_id: ShippingNoticeIntake 主键;只统计其派生 Document 的布局版本。
|
||||
intake_id: ShippingOrderIntake 主键;只统计其派生 Document 的布局版本。
|
||||
|
||||
Returns:
|
||||
脱敏状态与数量。processing 表示仍有 queued/running;completed 表示所有任务已终结;
|
||||
@@ -244,10 +259,10 @@ def _serialize_intake_layout_summary(intake_id: int) -> dict[str, Any]:
|
||||
rows = (
|
||||
db.session.query(ShippingDocumentLayoutVersion.status)
|
||||
.join(
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeDocument.id == ShippingDocumentLayoutVersion.document_id,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocument.id == ShippingDocumentLayoutVersion.document_id,
|
||||
)
|
||||
.filter(ShippingNoticeDocument.intake_id == int(intake_id))
|
||||
.filter(ShippingOrderDocument.intake_id == int(intake_id))
|
||||
.all()
|
||||
)
|
||||
counts = {
|
||||
@@ -272,12 +287,12 @@ def _serialize_intake_layout_summary(intake_id: int) -> dict[str, Any]:
|
||||
return {'status': status, 'total': total, **counts}
|
||||
|
||||
|
||||
def get_intake_for_user(intake_no: str, user_id: int) -> ShippingNoticeIntake:
|
||||
def get_intake_for_user(intake_no: str, user_id: int) -> ShippingOrderIntake:
|
||||
"""按编号查询当前用户的接入记录。"""
|
||||
normalized = str(intake_no or '').strip().upper()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no == normalized)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(ShippingOrderIntake.intake_no == normalized)
|
||||
.first()
|
||||
)
|
||||
if not intake or int(intake.user_id) != int(user_id):
|
||||
@@ -294,7 +309,7 @@ def get_intake_detail(*, user_id: int, intake_no: str) -> dict[str, Any]:
|
||||
return serialize_intake(intake, asset=asset, include_parse_texts=True)
|
||||
|
||||
|
||||
def _load_asset_for_intake(intake: ShippingNoticeIntake) -> FileAsset:
|
||||
def _load_asset_for_intake(intake: ShippingOrderIntake) -> FileAsset:
|
||||
asset = db.session.get(FileAsset, intake.asset_id)
|
||||
if not asset or asset.deleted_at is not None:
|
||||
raise NotFoundError(code='FILE_ASSET.NOT_FOUND', message='关联文件资产不存在')
|
||||
@@ -306,7 +321,7 @@ def _lock_intake_for_asset_purpose_parser(
|
||||
asset_id: int,
|
||||
purpose: str,
|
||||
parser_version: str,
|
||||
) -> ShippingNoticeIntake | None:
|
||||
) -> ShippingOrderIntake | None:
|
||||
"""
|
||||
FOR UPDATE 锁定同一资产目的+解析器版本下的 Intake(创建/重投入口串行化)。
|
||||
|
||||
@@ -314,11 +329,11 @@ def _lock_intake_for_asset_purpose_parser(
|
||||
锁定的 Intake;不存在则 None。
|
||||
"""
|
||||
return (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.asset_id == int(asset_id),
|
||||
ShippingNoticeIntake.purpose == purpose,
|
||||
ShippingNoticeIntake.parser_version == parser_version,
|
||||
ShippingOrderIntake.asset_id == int(asset_id),
|
||||
ShippingOrderIntake.purpose == purpose,
|
||||
ShippingOrderIntake.parser_version == parser_version,
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
@@ -326,6 +341,50 @@ def _lock_intake_for_asset_purpose_parser(
|
||||
)
|
||||
|
||||
|
||||
def _link_intake_to_upload_submission(
|
||||
*,
|
||||
intake: ShippingOrderIntake,
|
||||
asset: FileAsset,
|
||||
user_id: int,
|
||||
upload_batch_id: str,
|
||||
conversation_id: str | None,
|
||||
) -> None:
|
||||
"""
|
||||
将业务 Intake 幂等挂接到同一 upload_batch 的 ShippingOrderSubmission。
|
||||
|
||||
核心逻辑:补齐 source_type;仅当尚未挂接时创建/复用 Submission 并写审计;
|
||||
已挂接则只在 source_type 缺失时回填。Submission 创建失败 fail-closed(抛 ConflictError)。
|
||||
模板样本 purpose 不调用本函数。
|
||||
|
||||
Args:
|
||||
intake: 当前 Intake。
|
||||
asset: 根 FileAsset(用于推断扩展名)。
|
||||
user_id: 上传用户。
|
||||
upload_batch_id: 文件选择批次。
|
||||
conversation_id: 可选会话。
|
||||
"""
|
||||
source_type = intake.source_type or resolve_order_intake_source_type(
|
||||
extension=getattr(asset, 'extension', None),
|
||||
filename=getattr(asset, 'original_filename', None),
|
||||
)
|
||||
if intake.source_type is None and source_type is not None:
|
||||
intake.source_type = source_type
|
||||
if intake.order_submission_id is not None:
|
||||
return
|
||||
submission = ensure_order_submission_for_upload_batch(
|
||||
user_id=user_id,
|
||||
upload_batch_id=upload_batch_id,
|
||||
conversation_id=conversation_id or intake.conversation_id,
|
||||
actor_id=user_id,
|
||||
)
|
||||
attach_intake_to_order_submission(
|
||||
submission=submission,
|
||||
intake=intake,
|
||||
source_type=source_type,
|
||||
actor_id=user_id,
|
||||
)
|
||||
|
||||
|
||||
def create_shipping_notice_intake(
|
||||
*,
|
||||
user_id: int,
|
||||
@@ -393,13 +452,18 @@ def _create_intake_for_asset(
|
||||
parser_version=parser_version,
|
||||
)
|
||||
if intake is None:
|
||||
candidate = ShippingNoticeIntake(
|
||||
source_type = resolve_order_intake_source_type(
|
||||
extension=getattr(asset, 'extension', None),
|
||||
filename=getattr(asset, 'original_filename', None),
|
||||
)
|
||||
candidate = ShippingOrderIntake(
|
||||
intake_no=generate_intake_no(),
|
||||
asset_id=int(asset.id),
|
||||
user_id=int(user_id),
|
||||
conversation_id=conv,
|
||||
upload_batch_id=batch_id or str(uuid.uuid4()),
|
||||
purpose=purpose,
|
||||
source_type=source_type,
|
||||
parse_status='created',
|
||||
parser_version=parser_version,
|
||||
expires_at=datetime.utcnow() + timedelta(hours=_intake_ttl_hours()),
|
||||
@@ -426,6 +490,16 @@ def _create_intake_for_asset(
|
||||
message='Uploaded asset already belongs to another input batch',
|
||||
)
|
||||
|
||||
# [STEP 1.5] 业务 Intake 挂接上传 Submission,并固化 eml|direct_pdf 来源。
|
||||
if purpose == 'shipping_notice':
|
||||
_link_intake_to_upload_submission(
|
||||
intake=intake,
|
||||
asset=asset,
|
||||
user_id=int(user_id),
|
||||
upload_batch_id=str(intake.upload_batch_id),
|
||||
conversation_id=conv,
|
||||
)
|
||||
|
||||
# [STEP 2] 终态 / 已在飞 / 禁止复活
|
||||
status_now = str(intake.parse_status or '')
|
||||
if status_now in {'parsed', 'consumed', 'queued', 'parsing'}:
|
||||
@@ -487,16 +561,16 @@ def _create_intake_for_asset(
|
||||
def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | None) -> list[dict[str, Any]]:
|
||||
"""列出会话下未消费的活跃接入记录,供页面恢复。"""
|
||||
conv = str(conversation_id or '').strip()
|
||||
query = db.session.query(ShippingNoticeIntake, FileAsset).join(
|
||||
FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id
|
||||
query = db.session.query(ShippingOrderIntake, FileAsset).join(
|
||||
FileAsset, FileAsset.id == ShippingOrderIntake.asset_id
|
||||
).filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.parse_status.in_(tuple(ACTIVE_INTAKE_STATUSES - {'consumed', 'expired', 'cancelled'})),
|
||||
ShippingNoticeIntake.consumed_at.is_(None),
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
ShippingOrderIntake.parse_status.in_(tuple(ACTIVE_INTAKE_STATUSES - {'consumed', 'expired', 'cancelled'})),
|
||||
ShippingOrderIntake.consumed_at.is_(None),
|
||||
)
|
||||
if conv:
|
||||
query = query.filter(ShippingNoticeIntake.conversation_id == conv)
|
||||
rows = query.order_by(ShippingNoticeIntake.created_at.desc()).limit(50).all()
|
||||
query = query.filter(ShippingOrderIntake.conversation_id == conv)
|
||||
rows = query.order_by(ShippingOrderIntake.created_at.desc()).limit(50).all()
|
||||
return [serialize_intake(intake, asset=asset) for intake, asset in rows]
|
||||
|
||||
|
||||
@@ -506,11 +580,11 @@ def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str
|
||||
if not normalized:
|
||||
return []
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeIntake, FileAsset)
|
||||
.join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id)
|
||||
db.session.query(ShippingOrderIntake, FileAsset)
|
||||
.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
ShippingOrderIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
@@ -528,10 +602,10 @@ def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]:
|
||||
|
||||
normalized = str(intake_no or '').strip().upper()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.intake_no == normalized,
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingOrderIntake.intake_no == normalized,
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
@@ -599,10 +673,10 @@ def cancel_intake(*, user_id: int, intake_no: str) -> None:
|
||||
|
||||
normalized = str(intake_no or '').strip().upper()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.intake_no == normalized,
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingOrderIntake.intake_no == normalized,
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
@@ -646,10 +720,10 @@ def refresh_intake_duplicate_detection(*, user_id: int, intake_no: str) -> dict[
|
||||
|
||||
normalized = str(intake_no or '').strip().upper()
|
||||
intake = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
db.session.query(ShippingOrderIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.intake_no == normalized,
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingOrderIntake.intake_no == normalized,
|
||||
ShippingOrderIntake.user_id == int(user_id),
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
@@ -725,8 +799,8 @@ def resolve_intake_duplicate(
|
||||
target_task = None
|
||||
if target_no:
|
||||
target_task = (
|
||||
db.session.query(ShippingTask)
|
||||
.filter(ShippingTask.task_no == target_no, ShippingTask.user_id == int(user_id))
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(ShippingNotice.task_no == target_no, ShippingNotice.user_id == int(user_id))
|
||||
.first()
|
||||
)
|
||||
if not target_task:
|
||||
@@ -778,21 +852,22 @@ def resolve_intake_duplicate(
|
||||
|
||||
def mark_intakes_consumed(
|
||||
*,
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
intakes: list[ShippingOrderIntake],
|
||||
batch_id: int | None,
|
||||
task_ids_by_intake: dict[int, int] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
标记 intake 为 consumed 并增加资产引用计数。
|
||||
|
||||
核心逻辑:可在建批 commit 前预占(batch_id=None),避免 FOR UPDATE 在 create_batch_tasks 提交后释放导致并发双消费。
|
||||
核心逻辑:可在建单 commit 前预占(batch_id 已废弃,仅保留参数兼容);
|
||||
以 consumed_task_id / consumed_at 标记消费,避免 FOR UPDATE 释放后并发双消费。
|
||||
"""
|
||||
del batch_id # co8 起 shipping_batches / consumed_batch_id 已删除
|
||||
now = datetime.utcnow()
|
||||
task_map = task_ids_by_intake or {}
|
||||
for intake in intakes:
|
||||
intake.parse_status = 'consumed'
|
||||
intake.consumed_at = now
|
||||
intake.consumed_batch_id = int(batch_id) if batch_id else None
|
||||
intake.consumed_task_id = task_map.get(intake.id)
|
||||
intake.updated_at = now
|
||||
asset = db.session.get(FileAsset, intake.asset_id)
|
||||
|
||||
@@ -18,7 +18,7 @@ from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
from app.services.shipping_notice.inventory_snapshot import (
|
||||
parse_inventory_excel_with_meta,
|
||||
@@ -34,7 +34,7 @@ from app.services.shipping_notice.query_service import list_sorted_batch_tasks
|
||||
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
|
||||
|
||||
|
||||
def _can_relink_inventory(task: ShippingTask) -> bool:
|
||||
def _can_relink_inventory(task: ShippingNotice) -> bool:
|
||||
"""判断任务是否允许被新的批次库存快照影响;终态任务不能回退。"""
|
||||
return str(task.process_status or "").strip().lower() not in _TERMINAL_PROCESS_STATUSES
|
||||
|
||||
@@ -122,7 +122,7 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def active_inventory_file_for_task(task: ShippingTask) -> ShippingInventoryFile | None:
|
||||
def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None:
|
||||
"""读取任务当前 active link 指向的库存快照。"""
|
||||
if task.id is None:
|
||||
return None
|
||||
@@ -134,7 +134,7 @@ def active_inventory_file_for_task(task: ShippingTask) -> ShippingInventoryFile
|
||||
return link.inventory_file if link else None
|
||||
|
||||
|
||||
def active_inventory_lines_for_task(task: ShippingTask) -> list[dict[str, Any]]:
|
||||
def active_inventory_lines_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
|
||||
"""解析任务可用于匹配的库存行;批次库存快照优先,单票任务回退到任务投影字段。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file and isinstance(inv_file.inventory_lines_json, list):
|
||||
@@ -142,7 +142,7 @@ def active_inventory_lines_for_task(task: ShippingTask) -> list[dict[str, Any]]:
|
||||
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
|
||||
|
||||
|
||||
def has_uploaded_inventory_file(task: ShippingTask) -> bool:
|
||||
def has_uploaded_inventory_file(task: ShippingNotice) -> bool:
|
||||
"""任务是否已有可读取的库存上传文件。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if inv_file:
|
||||
@@ -150,7 +150,7 @@ def has_uploaded_inventory_file(task: ShippingTask) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _same_stable_inventory_identity(lhs: ShippingTask, rhs: ShippingTask) -> bool:
|
||||
def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) -> bool:
|
||||
"""判断两票任务是否具备相同且稳定的库存源身份,供批次库存快照共用。"""
|
||||
if not is_inventory_source_stable(lhs) or not is_inventory_source_stable(rhs):
|
||||
return False
|
||||
@@ -162,7 +162,7 @@ def _same_stable_inventory_identity(lhs: ShippingTask, rhs: ShippingTask) -> boo
|
||||
)
|
||||
|
||||
|
||||
def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> ShippingInventoryFile:
|
||||
def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile:
|
||||
"""
|
||||
保存库存 Excel 并创建批次级库存快照。
|
||||
|
||||
@@ -247,7 +247,6 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
||||
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
batch_id=task.batch_id,
|
||||
user_id=task.user_id,
|
||||
source_file_name=str(upload.filename or "").strip() or path.name,
|
||||
storage_path=str(path),
|
||||
@@ -269,7 +268,7 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
||||
db.session.add(inv_file)
|
||||
db.session.flush()
|
||||
|
||||
candidates = list_sorted_batch_tasks(task.batch) if task.batch_id and task.batch else [task]
|
||||
candidates = [task]
|
||||
linked_tasks = [
|
||||
item
|
||||
for item in candidates
|
||||
@@ -312,7 +311,7 @@ def save_batch_inventory_upload(task: ShippingTask, upload: FileStorage) -> Ship
|
||||
|
||||
|
||||
def save_task_inventory_file_from_local_path(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
source_path: str | Path,
|
||||
*,
|
||||
source_file_name: str | None = None,
|
||||
@@ -349,7 +348,6 @@ def save_task_inventory_file_from_local_path(
|
||||
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
batch_id=task.batch_id,
|
||||
user_id=task.user_id,
|
||||
source_file_name=str(source_file_name or source.name or path.name).strip() or path.name,
|
||||
storage_path=str(path),
|
||||
@@ -364,7 +362,7 @@ def save_task_inventory_file_from_local_path(
|
||||
|
||||
|
||||
def replace_task_inventory_link(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
inv_file: ShippingInventoryFile,
|
||||
*,
|
||||
role: str = "member",
|
||||
@@ -397,7 +395,7 @@ def replace_task_inventory_link(
|
||||
return new_link
|
||||
|
||||
|
||||
def read_linked_inventory_schema_preview(task: ShippingTask) -> dict[str, Any]:
|
||||
def read_linked_inventory_schema_preview(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""读取任务 active 库存快照的 schema preview。"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
if not inv_file:
|
||||
@@ -451,7 +449,7 @@ def apply_inventory_parse_result_to_linked_tasks(
|
||||
field_mapping: dict[str, str] | None = None,
|
||||
mapping_source: str | None = None,
|
||||
mapping_confirmed: bool = False,
|
||||
) -> list[ShippingTask]:
|
||||
) -> list[ShippingNotice]:
|
||||
"""把库存快照解析结果写到文件层,并同步投影到所有 active link 任务。"""
|
||||
inv_file.inventory_lines_json = inventory_lines
|
||||
inv_file.line_count = len(inventory_lines)
|
||||
@@ -461,7 +459,7 @@ def apply_inventory_parse_result_to_linked_tasks(
|
||||
inv_file.mapping_source = mapping_source
|
||||
inv_file.mapping_confirmed = bool(mapping_confirmed)
|
||||
|
||||
linked_tasks: list[ShippingTask] = []
|
||||
linked_tasks: list[ShippingNotice] = []
|
||||
for link in inv_file.links or []:
|
||||
if not link.is_active or not link.task:
|
||||
continue
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingTask
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_file_for_task,
|
||||
apply_inventory_parse_result_to_linked_tasks,
|
||||
@@ -26,7 +26,7 @@ from app.services.shipping_notice.tool_response import tool_response
|
||||
|
||||
|
||||
def inventory_loaded_response(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
*,
|
||||
warnings: list[str] | None = None,
|
||||
@@ -55,7 +55,7 @@ def inventory_loaded_response(
|
||||
Tool 标准响应;成功后任务可直接进入库存匹配。
|
||||
"""
|
||||
inv_file = active_inventory_file_for_task(task)
|
||||
linked_tasks: list[ShippingTask] = []
|
||||
linked_tasks: list[ShippingNotice] = []
|
||||
if inv_file:
|
||||
linked_tasks = apply_inventory_parse_result_to_linked_tasks(
|
||||
inv_file,
|
||||
|
||||
@@ -259,7 +259,7 @@ def evaluate_inventory_source_rules_for_field_values(
|
||||
基于 field_id→值映射评估路由(建单前 Draft / 资格服务)。
|
||||
|
||||
核心逻辑:未传 scope 时,有 line_field_values 则评 line,否则评 task;
|
||||
不依赖 ShippingTask / Snapshot,便于复核草稿阶段投影候选。
|
||||
不依赖 ShippingNotice / Snapshot,便于复核草稿阶段投影候选。
|
||||
|
||||
Args:
|
||||
header_field_values: Header 字段值,键为稳定 field_id。
|
||||
|
||||
@@ -21,7 +21,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError
|
||||
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_PARSE_OK,
|
||||
@@ -85,7 +85,7 @@ from app.services.shipping_notice.tool_response import tool_response
|
||||
from app.services.shipping_notice.task_disposition_service import task_execution_block_reason
|
||||
|
||||
|
||||
def latest_task_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent | None:
|
||||
def latest_task_event(task: ShippingNotice, event_type: str) -> ShippingTaskEvent | None:
|
||||
"""返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试用)。"""
|
||||
if task.id is None:
|
||||
return None
|
||||
@@ -131,7 +131,7 @@ def _inventory_rpa_exhausted_message(attempts: int) -> str:
|
||||
|
||||
|
||||
def _try_reuse_inventory_snapshot(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
rpa_source: dict[str, Any],
|
||||
*,
|
||||
mode: str,
|
||||
@@ -214,7 +214,7 @@ def _try_reuse_inventory_snapshot(
|
||||
)
|
||||
|
||||
|
||||
def _save_last_inventory_rpa_runtime(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
def _save_last_inventory_rpa_runtime(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""保存 worker 回调上报的实际执行模式,供前端显示本次真实来源。"""
|
||||
raw_mode = str(payload.get("rpa_mode") or payload.get("mode") or "").strip().lower()
|
||||
mode = raw_mode if raw_mode in {"browser", "mock"} else None
|
||||
@@ -258,7 +258,7 @@ def _inventory_rpa_triggered_message(*, attempt_no: int, max_attempts: int, manu
|
||||
return f"{prefix}若长时间无结果,可手动重试,或上传库存 Excel。"
|
||||
|
||||
|
||||
def inventory_rpa_wait_seconds(task: ShippingTask) -> tuple[int | None, int | None, int | None]:
|
||||
def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int | None, int | None]:
|
||||
"""
|
||||
返回库存 RPA 当前等待耗时、超时时间和剩余秒数。
|
||||
【AI 触发时机】:需要判断库存 RPA 是否还应等待、是否该调度复查或兜底推进时调用。
|
||||
@@ -284,7 +284,7 @@ def inventory_rpa_wait_seconds(task: ShippingTask) -> tuple[int | None, int | No
|
||||
return elapsed, timeout_seconds, remaining
|
||||
|
||||
|
||||
def next_inventory_rpa_recheck_at(task: ShippingTask) -> datetime | None:
|
||||
def next_inventory_rpa_recheck_at(task: ShippingNotice) -> datetime | None:
|
||||
"""
|
||||
计算库存 RPA 下一次复查时间点。
|
||||
【AI 触发时机】:worker 给等待外部 RPA 回执的任务创建延迟复查 job 时调用。
|
||||
@@ -295,7 +295,7 @@ def next_inventory_rpa_recheck_at(task: ShippingTask) -> datetime | None:
|
||||
return datetime.utcnow() + timedelta(seconds=max(remaining, 1))
|
||||
|
||||
|
||||
def maybe_recheck_inventory_rpa_wait(task: ShippingTask, *, source: str = "workspace_fallback") -> dict[str, Any] | None:
|
||||
def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "workspace_fallback") -> dict[str, Any] | None:
|
||||
"""
|
||||
对已超时的库存 RPA 等待态做一次幂等复查。
|
||||
【AI 触发时机】:工作台查询发现任务仍卡在 RPA 等待且已超过超时时间时调用;常规链路仍由 worker 调度。
|
||||
@@ -322,7 +322,7 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingTask, *, source: str = "works
|
||||
return ensure_inventory_via_rpa(task, mode="auto")
|
||||
|
||||
|
||||
def _expected_snapshot_identity_from_task(task: ShippingTask) -> tuple[str, str]:
|
||||
def _expected_snapshot_identity_from_task(task: ShippingNotice) -> tuple[str, str]:
|
||||
"""从任务正式库存身份推导快照预期二元组。"""
|
||||
return (
|
||||
str(task.inventory_source_code or "").strip().upper(),
|
||||
@@ -517,7 +517,7 @@ def _flush_pending_callback_moves(
|
||||
|
||||
|
||||
def _try_rebuild_task_inventory_attachment(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
inv_file: ShippingInventoryFile,
|
||||
post_commit_warnings: list[str],
|
||||
) -> bool:
|
||||
@@ -559,7 +559,7 @@ def _should_flush_batch_callback_moves(
|
||||
|
||||
|
||||
def _persist_post_commit_task_event(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
event_type: str,
|
||||
detail: dict[str, Any],
|
||||
) -> None:
|
||||
@@ -600,7 +600,7 @@ def _is_legacy_trigger_run_no(run_no: str) -> bool:
|
||||
return str(run_no or "").strip().upper().startswith("LEGACY-")
|
||||
|
||||
|
||||
def _expected_rpa_callback_run_no(task: ShippingTask) -> str:
|
||||
def _expected_rpa_callback_run_no(task: ShippingNotice) -> str:
|
||||
"""读取任务最近一次 RPA 触发记录的 run_no。"""
|
||||
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
|
||||
if not last_trigger:
|
||||
@@ -612,7 +612,7 @@ def _expected_rpa_callback_run_no(task: ShippingTask) -> str:
|
||||
return _extract_run_no_from_trigger(str(detail.get("trigger") or ""))
|
||||
|
||||
|
||||
def _validate_rpa_callback_run_no(task: ShippingTask, callback_run_no: str) -> str | None:
|
||||
def _validate_rpa_callback_run_no(task: ShippingNotice, callback_run_no: str) -> str | None:
|
||||
"""校验回调 run_no 属于当前任务最近一次有效触发轮次。"""
|
||||
provided = str(callback_run_no or "").strip()
|
||||
expected = _expected_rpa_callback_run_no(task)
|
||||
@@ -627,7 +627,7 @@ def _validate_rpa_callback_run_no(task: ShippingTask, callback_run_no: str) -> s
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_effective_callback_run_no(task: ShippingTask, payload: dict[str, Any]) -> str:
|
||||
def _resolve_effective_callback_run_no(task: ShippingNotice, payload: dict[str, Any]) -> str:
|
||||
"""解析回调实际归属的 run_no(显式传入优先,否则回退当前触发轮次)。"""
|
||||
provided = str(payload.get("run_no") or "").strip()
|
||||
if provided:
|
||||
@@ -635,19 +635,19 @@ def _resolve_effective_callback_run_no(task: ShippingTask, payload: dict[str, An
|
||||
return _expected_rpa_callback_run_no(task)
|
||||
|
||||
|
||||
def _lock_task_for_rpa_callback(task: ShippingTask) -> ShippingTask:
|
||||
def _lock_task_for_rpa_callback(task: ShippingNotice) -> ShippingNotice:
|
||||
"""对任务行加悲观锁,防止并发回调重复消费同一轮次。"""
|
||||
if task.id is None:
|
||||
return task
|
||||
return db.session.query(ShippingTask).filter_by(id=task.id).with_for_update().one()
|
||||
return db.session.query(ShippingNotice).filter_by(id=task.id).with_for_update().one()
|
||||
|
||||
|
||||
def _get_consumed_inventory_rpa_run_no(task: ShippingTask) -> str:
|
||||
def _get_consumed_inventory_rpa_run_no(task: ShippingNotice) -> str:
|
||||
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
|
||||
return str(task.inventory_rpa_consumed_run_no or "").strip()
|
||||
|
||||
|
||||
def _mark_inventory_rpa_run_no_consumed(task: ShippingTask, run_no: str) -> None:
|
||||
def _mark_inventory_rpa_run_no_consumed(task: ShippingNotice, run_no: str) -> None:
|
||||
"""标记当前 RPA 轮次已被回调消费,防止同一 run_no 重放重复入库。"""
|
||||
effective = str(run_no or "").strip()
|
||||
if not effective:
|
||||
@@ -655,7 +655,7 @@ def _mark_inventory_rpa_run_no_consumed(task: ShippingTask, run_no: str) -> None
|
||||
task.inventory_rpa_consumed_run_no = effective
|
||||
|
||||
|
||||
def _validate_rpa_callback_not_replayed(task: ShippingTask, run_no: str) -> str | None:
|
||||
def _validate_rpa_callback_not_replayed(task: ShippingNotice, run_no: str) -> str | None:
|
||||
"""拒绝同一 run_no 的重复成功/失败/跳过回调。"""
|
||||
effective = str(run_no or "").strip()
|
||||
consumed = _get_consumed_inventory_rpa_run_no(task)
|
||||
@@ -664,7 +664,7 @@ def _validate_rpa_callback_not_replayed(task: ShippingTask, run_no: str) -> str
|
||||
return None
|
||||
|
||||
|
||||
def _validate_rpa_callback_round(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""
|
||||
校验 RPA 回调轮次契约(run_no + 幂等)。
|
||||
核心逻辑:success/skipped/failed 共用;无有效触发或旧轮次/重放均拒绝。
|
||||
@@ -711,7 +711,7 @@ def _validate_rpa_callback_round(task: ShippingTask, payload: dict[str, Any]) ->
|
||||
return None
|
||||
|
||||
|
||||
def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None:
|
||||
def _validate_rpa_callback_gate(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""
|
||||
复核 RPA 触发后可能漂移的订单与路由门禁(skipped/failed/success 共用)。
|
||||
|
||||
@@ -774,7 +774,7 @@ def _validate_rpa_callback_gate(task: ShippingTask) -> dict[str, Any] | None:
|
||||
return None
|
||||
|
||||
|
||||
def _validate_rpa_callback_success_identity(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""
|
||||
成功回调的身份契约:Source 必须与任务一致;fixed Source 的 Warehouse 还须一致。
|
||||
核心逻辑:动态 Source 的 Warehouse 由库存行按 Reservation + PN 解析,回调不预先裁决。
|
||||
@@ -849,7 +849,7 @@ def _validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callba
|
||||
return None
|
||||
|
||||
|
||||
def _validate_rpa_callback_inventory_source(task: ShippingTask, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
def _validate_rpa_callback_inventory_source(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""
|
||||
校验 RPA 成功回调是否允许处理当前任务库存(门禁 + 轮次 + 身份)。
|
||||
核心逻辑:batch 成功项在合并顶层 run_no 后委托本函数。
|
||||
@@ -864,7 +864,7 @@ def _validate_rpa_callback_inventory_source(task: ShippingTask, payload: dict[st
|
||||
|
||||
|
||||
def _resolve_batch_callback_source(
|
||||
task: ShippingTask | None,
|
||||
task: ShippingNotice | None,
|
||||
item: dict[str, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
@@ -882,7 +882,7 @@ def _resolve_batch_callback_source(
|
||||
|
||||
|
||||
def _batch_snapshot_verify_warehouse_id(
|
||||
task: ShippingTask | None,
|
||||
task: ShippingNotice | None,
|
||||
source: dict[str, Any],
|
||||
item: dict[str, Any] | None = None,
|
||||
) -> str | None:
|
||||
@@ -1082,7 +1082,7 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
|
||||
def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]:
|
||||
def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, Any]:
|
||||
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。"""
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
manual_retry_round = mode == "retry_rpa"
|
||||
@@ -1429,7 +1429,7 @@ def _inventory_rpa_skipped_message(*, skip_reason: str, detail: str) -> str:
|
||||
|
||||
|
||||
def _handle_rpa_inventory_skipped(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
payload: dict[str, Any],
|
||||
runtime: dict[str, Any],
|
||||
*,
|
||||
@@ -1482,7 +1482,7 @@ def _handle_rpa_inventory_skipped(
|
||||
|
||||
|
||||
def _handle_rpa_inventory_failed(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
payload: dict[str, Any],
|
||||
runtime: dict[str, Any],
|
||||
*,
|
||||
@@ -1595,7 +1595,6 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
trigger_type="on_demand",
|
||||
success=True,
|
||||
user_id=task.user_id,
|
||||
batch_id=task.batch_id,
|
||||
verify_warehouse_id=task_wh if (task_wh := str(task.inventory_warehouse_id or "").strip().upper()) else None,
|
||||
)
|
||||
if not created_new:
|
||||
@@ -1846,7 +1845,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
warehouse_id = str(merged_item.get("warehouse_id") or "").strip().upper()
|
||||
raw_status = _normalize_rpa_inventory_batch_item_status(merged_item)
|
||||
task_no = str(merged_item.get("task_no") or "").strip()
|
||||
task: ShippingTask | None = None
|
||||
task: ShippingNotice | None = None
|
||||
if task_no:
|
||||
task = resolve_task_from_payload({"task_id": task_no, "task_no": task_no})
|
||||
if task is None:
|
||||
@@ -2215,7 +2214,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _validate_repair_inventory_snapshot(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
inv_file: ShippingInventoryFile | None,
|
||||
*,
|
||||
requested_file_no: str | None = None,
|
||||
|
||||
@@ -16,7 +16,7 @@ from typing import Any
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingInventoryFile, ShippingTask, ShippingTaskEvent, ShippingTaskInventoryLink
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
_can_relink_inventory,
|
||||
generate_inventory_file_no,
|
||||
@@ -322,7 +322,6 @@ def create_inventory_snapshot_from_rpa(
|
||||
|
||||
inv_file = ShippingInventoryFile(
|
||||
inventory_file_no=inventory_file_no,
|
||||
batch_id=batch_id,
|
||||
user_id=user_id,
|
||||
source_file_name=str(source_file_name or (path.name if path else "")).strip() or None,
|
||||
storage_path=storage_path or f"failed://{inventory_file_no}",
|
||||
@@ -417,7 +416,7 @@ def create_empty_rpa_inventory_snapshot(
|
||||
|
||||
|
||||
def link_snapshot_to_task(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
inv_file: ShippingInventoryFile,
|
||||
*,
|
||||
reason: str,
|
||||
@@ -514,7 +513,7 @@ def link_snapshot_to_task(
|
||||
return link
|
||||
|
||||
|
||||
def serialize_inventory_snapshot_link(task: ShippingTask) -> dict[str, Any] | None:
|
||||
def serialize_inventory_snapshot_link(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""序列化任务当前 active 库存快照摘要,供工作台/Tool 展示。"""
|
||||
if task.id is None:
|
||||
return None
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/inventory_source_gate.py
|
||||
|
||||
用途:库存源稳定性门禁、独立字段写入与路由指纹管理。
|
||||
依赖:inventory_source_rules、inventory_source_repository、models.ShippingTask、core.errors。
|
||||
依赖:inventory_source_rules、inventory_source_repository、models.ShippingNotice、core.errors。
|
||||
逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备);
|
||||
解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。
|
||||
"""
|
||||
@@ -13,7 +13,7 @@ from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingTask
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
adjudicate_inventory_source,
|
||||
@@ -42,7 +42,7 @@ INVENTORY_SOURCE_ERROR_CODES = {
|
||||
}
|
||||
|
||||
|
||||
def _inventory_source_config_current(task: ShippingTask) -> bool:
|
||||
def _inventory_source_config_current(task: ShippingNotice) -> bool:
|
||||
"""任务上记录的库存源配置版本须与当前数据库版本一致。"""
|
||||
stored = str(task.inventory_source_config_version or "").strip()
|
||||
current = inventory_sources_runtime_version()
|
||||
@@ -51,7 +51,7 @@ def _inventory_source_config_current(task: ShippingTask) -> bool:
|
||||
return stored == current
|
||||
|
||||
|
||||
def is_inventory_source_stable(task: ShippingTask) -> bool:
|
||||
def is_inventory_source_stable(task: ShippingNotice) -> bool:
|
||||
"""
|
||||
判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
|
||||
|
||||
@@ -97,7 +97,7 @@ def is_inventory_source_stable(task: ShippingTask) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def routing_fingerprint_changed(task: ShippingTask, context: dict[str, Any]) -> bool:
|
||||
def routing_fingerprint_changed(task: ShippingNotice, context: dict[str, Any]) -> bool:
|
||||
"""比较当前路由上下文与任务已存指纹,判断人工确认是否因重解析或配置变更失效。"""
|
||||
previous = str(task.inventory_routing_fingerprint or "").strip()
|
||||
if not previous:
|
||||
@@ -105,7 +105,7 @@ def routing_fingerprint_changed(task: ShippingTask, context: dict[str, Any]) ->
|
||||
return previous != compute_routing_fingerprint(context)
|
||||
|
||||
|
||||
def inventory_source_config_changed(task: ShippingTask) -> bool:
|
||||
def inventory_source_config_changed(task: ShippingNotice) -> bool:
|
||||
"""配置版本变化会使已确认库存源失效。"""
|
||||
stored = str(task.inventory_source_config_version or "").strip()
|
||||
if not stored:
|
||||
@@ -113,7 +113,7 @@ def inventory_source_config_changed(task: ShippingTask) -> bool:
|
||||
return stored != inventory_sources_runtime_version()
|
||||
|
||||
|
||||
def apply_destination_fields(task: ShippingTask, context: dict[str, Any]) -> None:
|
||||
def apply_destination_fields(task: ShippingNotice, context: dict[str, Any]) -> None:
|
||||
"""将标准化目的地线索写入任务独立字段。"""
|
||||
task.destination_code = str(context.get("destination_code") or "").strip().upper() or None
|
||||
task.destination_city = str(context.get("destination_city") or "").strip() or None
|
||||
@@ -121,7 +121,7 @@ def apply_destination_fields(task: ShippingTask, context: dict[str, Any]) -> Non
|
||||
task.warehouse_hint = str(context.get("warehouse_hint") or "").strip() or None
|
||||
|
||||
|
||||
def clear_inventory_source_confirmation(task: ShippingTask) -> None:
|
||||
def clear_inventory_source_confirmation(task: ShippingNotice) -> None:
|
||||
"""路由指纹或配置版本变化时清除旧人工确认信息及过期 RPA 参数。"""
|
||||
task.inventory_source_confirmed_by = None
|
||||
task.inventory_source_confirmed_at = None
|
||||
@@ -133,7 +133,7 @@ def clear_inventory_source_confirmation(task: ShippingTask) -> None:
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def _adjudication_from_stable_task(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
def _adjudication_from_stable_task(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
"""从已稳定任务字段重建裁决结果,供跳过重复裁决时使用。"""
|
||||
context = extract_routing_context(task)
|
||||
return InventorySourceAdjudication(
|
||||
@@ -150,7 +150,7 @@ def _adjudication_from_stable_task(task: ShippingTask) -> InventorySourceAdjudic
|
||||
|
||||
|
||||
def apply_inventory_source_adjudication(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
*,
|
||||
confirmed_by_user_id: int | None = None,
|
||||
@@ -206,7 +206,7 @@ def apply_inventory_source_adjudication(
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
"""
|
||||
对任务执行库存源裁决并写入独立字段。
|
||||
【AI 触发时机】:订单抽取提交完成后由后端编排调用;重解析时同样调用以刷新裁决。
|
||||
@@ -252,7 +252,7 @@ def adjudicate_and_apply_inventory_source(task: ShippingTask) -> InventorySource
|
||||
|
||||
|
||||
def transition_task_to_inventory_source_review(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
*,
|
||||
error_message: str | None = None,
|
||||
@@ -283,7 +283,7 @@ def transition_task_to_inventory_source_review(
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def ensure_inventory_source_review_state(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
"""
|
||||
对已通过解析确认但库存源仍不稳定的任务,补做裁决并落库到 inventory_source_review。
|
||||
|
||||
@@ -297,7 +297,7 @@ def ensure_inventory_source_review_state(task: ShippingTask) -> InventorySourceA
|
||||
|
||||
|
||||
def confirm_task_inventory_source(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
source_code: str,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
@@ -312,7 +312,7 @@ def confirm_task_inventory_source(
|
||||
|
||||
|
||||
def assert_inventory_source_gate(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
operation: str = "continue",
|
||||
) -> None:
|
||||
@@ -357,7 +357,7 @@ def assert_inventory_source_gate(
|
||||
)
|
||||
|
||||
|
||||
def task_inventory_identity(task: ShippingTask) -> dict[str, str | None]:
|
||||
def task_inventory_identity(task: ShippingNotice) -> dict[str, str | None]:
|
||||
"""返回任务当前正式库存身份;多候选冻结时 source 摘要可为空。"""
|
||||
return {
|
||||
"inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None,
|
||||
@@ -366,7 +366,7 @@ def task_inventory_identity(task: ShippingTask) -> dict[str, str | None]:
|
||||
|
||||
|
||||
def inventory_identities_match(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
source_code: str | None,
|
||||
warehouse_id: str | None,
|
||||
|
||||
@@ -15,7 +15,7 @@ from dataclasses import dataclass, field, replace
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingTask
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
|
||||
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
@@ -48,7 +48,7 @@ class InventorySourceAdjudication:
|
||||
InventorySourceResolution = InventorySourceAdjudication
|
||||
|
||||
|
||||
def extract_routing_context(task: ShippingTask) -> dict[str, Any]:
|
||||
def extract_routing_context(task: ShippingNotice) -> dict[str, Any]:
|
||||
"""投影任务字段为路由审计上下文,不依赖 YAML 目的地别名。"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
header = current_header_field_values_or_empty(task)
|
||||
@@ -125,7 +125,7 @@ def _snapshot_match_key(row: dict[str, Any]) -> tuple[str, str] | None:
|
||||
return (part_number, reservation_id) if part_number and reservation_id else None
|
||||
|
||||
|
||||
def _task_routing_lines(task: ShippingTask, *, required: set[str] | None = None) -> list[dict[str, Any]]:
|
||||
def _task_routing_lines(task: ShippingNotice, *, required: set[str] | None = None) -> list[dict[str, Any]]:
|
||||
"""读取锁定 Extraction 的行用途值并保留位置,供路由规则和快照键关联使用。"""
|
||||
try:
|
||||
values = task_line_purpose_values(task, required=required)
|
||||
@@ -135,7 +135,7 @@ def _task_routing_lines(task: ShippingTask, *, required: set[str] | None = None)
|
||||
|
||||
|
||||
def resolve_ambiguous_source_from_ready_snapshots(
|
||||
task: ShippingTask,
|
||||
task: ShippingNotice,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
) -> InventorySourceAdjudication:
|
||||
"""
|
||||
@@ -226,7 +226,7 @@ def resolve_ambiguous_source_from_ready_snapshots(
|
||||
)
|
||||
|
||||
|
||||
def adjudicate_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
def adjudicate_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
"""先评估任务级规则,再在所有订单行一致时接受行级规则结果。"""
|
||||
context = extract_routing_context(task)
|
||||
task_result = evaluate_inventory_source_rules(task=task)
|
||||
@@ -245,7 +245,7 @@ def adjudicate_inventory_source(task: ShippingTask) -> InventorySourceAdjudicati
|
||||
return _result_to_adjudication(task_result, context)
|
||||
|
||||
|
||||
def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> InventorySourceAdjudication:
|
||||
def confirm_inventory_source_by_code(task: ShippingNotice, source_code: str) -> InventorySourceAdjudication:
|
||||
"""人工从已启用数据库 Source 中选择来源;不要求预先确定动态 Warehouse。"""
|
||||
context = extract_routing_context(task)
|
||||
source = get_database_inventory_source(source_code)
|
||||
@@ -257,12 +257,12 @@ def confirm_inventory_source_by_code(task: ShippingTask, source_code: str) -> In
|
||||
return _from_source(status='user_confirmed', source=source, method='user_confirmed', context=context)
|
||||
|
||||
|
||||
def resolve_inventory_source(task: ShippingTask) -> InventorySourceAdjudication:
|
||||
def resolve_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
"""兼容调用名,委托当前通用规则裁决。"""
|
||||
return adjudicate_inventory_source(task)
|
||||
|
||||
|
||||
def task_rpa_inventory_source(task: ShippingTask) -> dict[str, Any] | None:
|
||||
def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""按任务 Source 或冻结多候选中的首个可用源读取 RPA/快照配置。"""
|
||||
primary = get_database_inventory_source(task.inventory_source_code)
|
||||
if primary is not None:
|
||||
@@ -276,7 +276,7 @@ def task_rpa_inventory_source(task: ShippingTask) -> dict[str, Any] | None:
|
||||
return None
|
||||
|
||||
|
||||
def save_task_rpa_inventory_source(task: ShippingTask, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None:
|
||||
def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None:
|
||||
"""兼容旧入口,将确认结果委托库存源门禁持久化。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
@@ -284,7 +284,7 @@ def save_task_rpa_inventory_source(task: ShippingTask, source: dict[str, Any], *
|
||||
apply_inventory_source_adjudication(task, selected)
|
||||
|
||||
|
||||
def mark_inventory_source_review(task: ShippingTask, resolution: InventorySourceAdjudication) -> None:
|
||||
def mark_inventory_source_review(task: ShippingNotice, resolution: InventorySourceAdjudication) -> None:
|
||||
"""兼容旧入口,写入待人工确认的 Source 候选。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ from typing import Any
|
||||
from flask import current_app
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app.models import ShippingInventoryFile, ShippingTask
|
||||
from app.models import ShippingInventoryFile, ShippingNotice
|
||||
from app.services.shipping_notice.export import _storage_root
|
||||
from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path
|
||||
_TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv")
|
||||
@@ -163,7 +163,7 @@ def install_task_inventory_attachment_from_file(
|
||||
|
||||
|
||||
def rebuild_task_inventory_attachment_from_snapshot(
|
||||
task: ShippingTask | str,
|
||||
task: ShippingNotice | str,
|
||||
inv_file: ShippingInventoryFile,
|
||||
) -> Path:
|
||||
"""
|
||||
@@ -177,7 +177,7 @@ def rebuild_task_inventory_attachment_from_snapshot(
|
||||
Returns:
|
||||
重建后的任务正式附件路径。
|
||||
"""
|
||||
task_no = task.task_no if isinstance(task, ShippingTask) else str(task or "").strip()
|
||||
task_no = task.task_no if isinstance(task, ShippingNotice) else str(task or "").strip()
|
||||
if not task_no:
|
||||
raise ValueError("task_no is required")
|
||||
storage_path = Path(str(inv_file.storage_path or ""))
|
||||
|
||||
@@ -13,7 +13,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingTask
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
)
|
||||
@@ -56,7 +56,7 @@ def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | Non
|
||||
return None
|
||||
|
||||
|
||||
def _reservation_gate_response(task: ShippingTask, *, lang: str) -> dict[str, Any] | None:
|
||||
def _reservation_gate_response(task: ShippingNotice, *, lang: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
库存入口统一检查订单侧 Reservation ID。
|
||||
|
||||
@@ -90,7 +90,7 @@ def _reservation_gate_response(task: ShippingTask, *, lang: str) -> dict[str, An
|
||||
)
|
||||
|
||||
|
||||
def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang: str) -> dict[str, Any] | None:
|
||||
def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lang: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。
|
||||
核心逻辑:先拦客户与 Reservation,再检查库存源稳定性;仅捕获预期 AppError。
|
||||
@@ -222,7 +222,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
{
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"share_mode": inv_file.share_mode,
|
||||
"batch_no": task.batch.batch_no if task.batch else None,
|
||||
"batch_no": None,
|
||||
},
|
||||
)
|
||||
return inventory_loaded_response(
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/notice_line_service.py
|
||||
|
||||
用途:冻结 Snapshot 后双写 shipping_notice_lines。
|
||||
依赖:ShippingNoticeLine、ShippingOrderSnapshot、db。
|
||||
逻辑:由 order_freeze_service 调用;按 notice_id 替换式写入,保证与 Snapshot 行一致。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeLine, ShippingOrderSnapshot
|
||||
|
||||
|
||||
def replace_notice_lines_from_snapshot(*, notice_id: int, snapshot: ShippingOrderSnapshot) -> int:
|
||||
"""
|
||||
用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。
|
||||
|
||||
Args:
|
||||
notice_id: shipping_notices.id。
|
||||
snapshot: 已 flush 且带 lines 的 Snapshot。
|
||||
|
||||
Returns:
|
||||
写入行数。
|
||||
"""
|
||||
db.session.query(ShippingNoticeLine).filter_by(notice_id=int(notice_id)).delete(synchronize_session=False)
|
||||
now = datetime.utcnow()
|
||||
rows: list[ShippingNoticeLine] = []
|
||||
for line in list(snapshot.lines or []):
|
||||
rows.append(
|
||||
ShippingNoticeLine(
|
||||
notice_id=int(notice_id),
|
||||
snapshot_line_id=int(line.id) if getattr(line, 'id', None) else None,
|
||||
position=int(line.position),
|
||||
line_key=str(getattr(line, 'line_no', None) or '').strip() or None,
|
||||
part_number=getattr(line, 'part_number', None),
|
||||
reservation_id=getattr(line, 'reservation_id', None),
|
||||
required_qty=getattr(line, 'qty', None),
|
||||
field_values_json=dict(getattr(line, 'field_values_json', None) or {}),
|
||||
created_at=now,
|
||||
)
|
||||
)
|
||||
if rows:
|
||||
db.session.add_all(rows)
|
||||
db.session.flush()
|
||||
return len(rows)
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingNoticeCandidate, ShippingTask
|
||||
from app.models import ShippingOrderCandidate, ShippingNotice
|
||||
from app.services.shipping_notice.task_candidate_reconciliation import (
|
||||
reconcile_exact_file_open_existing,
|
||||
)
|
||||
@@ -19,8 +19,8 @@ from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
def _record_outcome(
|
||||
*,
|
||||
task: ShippingTask,
|
||||
candidate: ShippingNoticeCandidate,
|
||||
task: ShippingNotice,
|
||||
candidate: ShippingOrderCandidate,
|
||||
status: str,
|
||||
reason: str,
|
||||
updated_line_indexes: list[int] | None = None,
|
||||
@@ -53,8 +53,8 @@ def _record_outcome(
|
||||
|
||||
def backfill_exact_file_open_existing_reservations(
|
||||
*,
|
||||
task: ShippingTask,
|
||||
candidate: ShippingNoticeCandidate,
|
||||
task: ShippingNotice,
|
||||
candidate: ShippingOrderCandidate,
|
||||
candidate_summary: dict[str, Any],
|
||||
duplicate_status: str,
|
||||
duplicate_matches: list[dict[str, Any]],
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
services/shipping_notice/openapi_spec.py
|
||||
|
||||
用途:构建发货通知 Tool API 的 OpenAPI 描述,供 Dify 导入和联调用。
|
||||
依赖:shipping_notice.constants 中的请求字段常量、标准 `typing` 类型。
|
||||
逻辑:由 api/shipping_notice_tools.py 调用本文件生成 JSON/YAML OpenAPI 文档,再暴露给 Dify 或开发工具。
|
||||
依赖:标准 `typing` 类型。
|
||||
逻辑:由 api/shipping_notice_tools.py 调用本文件生成 JSON/YAML OpenAPI 文档,再暴露给 Dify 或开发工具;
|
||||
co8 起不再导出 get_batch_status(shipping_batches 已 DROP)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -70,10 +71,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
server = f"{server}/api/shipping-notice" if server else "/api/shipping-notice"
|
||||
|
||||
task_id = _str_prop("发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501")
|
||||
batch_id = _str_prop("发货批次编号(batch id),如 SB-20260617-ABCD1234")
|
||||
runtime_context = _str_prop(
|
||||
"HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
|
||||
)
|
||||
capability_token = _str_prop("HXOPS 每轮注入的短效只读能力令牌;必须原样透传")
|
||||
return {
|
||||
"openapi": "3.0.0",
|
||||
@@ -105,14 +102,5 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"以及 step_payload.inventory_source_resolution.candidates。"
|
||||
),
|
||||
),
|
||||
"/tools/get_batch_status": _post_op(
|
||||
"get_batch_status",
|
||||
"查询批次当前状态、任务列表与当前聚焦任务",
|
||||
{
|
||||
"batch_no": batch_id,
|
||||
"shipping_chat_capability_token": capability_token,
|
||||
},
|
||||
required=["batch_no", "shipping_chat_capability_token"],
|
||||
),
|
||||
},
|
||||
}
|
||||
@@ -15,11 +15,11 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingTask,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
@@ -27,7 +27,7 @@ from app.services.shipping_notice.order_freeze_service import freeze_order_snaps
|
||||
|
||||
def maybe_execute_run_auto_freeze(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
run: ShippingOrderProcessingRun,
|
||||
submission_result: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""在门禁已放行时消费当前 Run 的 accepted Candidate,并自动冻结其新建任务。"""
|
||||
@@ -67,24 +67,24 @@ def maybe_execute_run_auto_freeze(
|
||||
return refreshed
|
||||
|
||||
|
||||
def _eligible_candidate_nos(run: ShippingOrderExtractionRun) -> list[str]:
|
||||
def _eligible_candidate_nos(run: ShippingOrderProcessingRun) -> list[str]:
|
||||
"""只返回当前 Run 中可以自动建单的 accepted + selected 候选。"""
|
||||
rows = (
|
||||
ShippingNoticeCandidate.query
|
||||
ShippingOrderCandidate.query
|
||||
.filter_by(
|
||||
order_extraction_run_id=int(run.id),
|
||||
is_current_version=True,
|
||||
candidate_status='accepted',
|
||||
selected=True,
|
||||
)
|
||||
.filter(ShippingNoticeCandidate.consumed_task_id.is_(None))
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
.filter(ShippingOrderCandidate.consumed_task_id.is_(None))
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [str(item.candidate_no) for item in rows if str(item.candidate_no or '').strip()]
|
||||
|
||||
|
||||
def _snapshot_intake_nos(run: ShippingOrderExtractionRun) -> list[str]:
|
||||
def _snapshot_intake_nos(run: ShippingOrderProcessingRun) -> list[str]:
|
||||
"""从 Run 冻结快照提取 Intake 编号,确保自动消费范围不越过本轮输入。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
@@ -97,7 +97,7 @@ def _snapshot_intake_nos(run: ShippingOrderExtractionRun) -> list[str]:
|
||||
|
||||
def _freeze_created_tasks(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
run: ShippingOrderProcessingRun,
|
||||
policy: dict[str, Any],
|
||||
candidate_nos: list[str],
|
||||
) -> tuple[list[str], list[dict[str, Any]]]:
|
||||
@@ -116,16 +116,16 @@ def _freeze_created_tasks(
|
||||
return [], []
|
||||
|
||||
candidates = (
|
||||
ShippingNoticeCandidate.query
|
||||
ShippingOrderCandidate.query
|
||||
.filter_by(
|
||||
order_extraction_run_id=int(run.id),
|
||||
is_current_version=True,
|
||||
candidate_status='accepted',
|
||||
selected=True,
|
||||
)
|
||||
.filter(ShippingNoticeCandidate.consumed_task_id.isnot(None))
|
||||
.filter(ShippingNoticeCandidate.candidate_no.in_(tuple(eligible)))
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
.filter(ShippingOrderCandidate.consumed_task_id.isnot(None))
|
||||
.filter(ShippingOrderCandidate.candidate_no.in_(tuple(eligible)))
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
frozen_task_nos: list[str] = []
|
||||
@@ -133,7 +133,7 @@ def _freeze_created_tasks(
|
||||
for candidate in candidates:
|
||||
if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing':
|
||||
continue
|
||||
task = db.session.get(ShippingTask, int(candidate.consumed_task_id or 0))
|
||||
task = db.session.get(ShippingNotice, int(candidate.consumed_task_id or 0))
|
||||
if task is None:
|
||||
continue
|
||||
# [STEP] 单任务 savepoint:冻结失败必须回滚本任务已 flush 的快照/指针/客户继承,
|
||||
@@ -176,8 +176,8 @@ def _freeze_created_tasks(
|
||||
|
||||
def _inherit_confirmed_ordering_customer(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
task: ShippingTask,
|
||||
run: ShippingOrderProcessingRun,
|
||||
task: ShippingNotice,
|
||||
policy: dict[str, Any],
|
||||
) -> None:
|
||||
"""把 Run 已确认的唯一 Bill-to 客户补写到当前任务 Extraction,供自动冻结门禁复用。"""
|
||||
@@ -251,15 +251,15 @@ def _inherit_confirmed_ordering_customer(
|
||||
|
||||
def _refresh_submission_result(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
run: ShippingOrderProcessingRun,
|
||||
previous_result: dict[str, Any],
|
||||
create_result: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""按当前 Run 持久化事实重建摘要,确保自动建单后 created/pending 计数可恢复。"""
|
||||
candidates = (
|
||||
ShippingNoticeCandidate.query
|
||||
ShippingOrderCandidate.query
|
||||
.filter_by(order_extraction_run_id=int(run.id), is_current_version=True)
|
||||
.order_by(ShippingNoticeCandidate.id.asc())
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
pending_by_candidate_no = {
|
||||
@@ -277,7 +277,7 @@ def _refresh_submission_result(
|
||||
if pending_item is not None:
|
||||
pending_orders.append(pending_item)
|
||||
continue
|
||||
task = db.session.get(ShippingTask, int(candidate.consumed_task_id))
|
||||
task = db.session.get(ShippingNotice, int(candidate.consumed_task_id))
|
||||
if task is None:
|
||||
continue
|
||||
if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing':
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
services/shipping_notice/order_auto_freeze_policy.py
|
||||
|
||||
用途:统一生成订单抽取 Run 的自动冻结门禁摘要,不让各处各自拼 policy JSON。
|
||||
依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与分路径开关;
|
||||
依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与分路径/XFA 开关;
|
||||
process_gate_contract(原因唯一归属 order_freeze_readiness)。
|
||||
逻辑:Run 创建时冻结初始人工确认策略;结果落库后按解析路径、技术失败、预算停止、
|
||||
紧急停止和复核状态刷新 Run 级摘要。
|
||||
模板 Profile 批准写入 parser / qualification 痕迹,不再作为唯一放行条件;
|
||||
LLM 路径可进入 Candidate Qualification,不再天然追加 llm_path_cannot_auto_freeze;
|
||||
订单是否自动建单以 Candidate Qualification 为准(见 candidate_qualification_service)。
|
||||
XFA 写入 shadow/可选观测白名单痕迹;真实自动建单与坐标共用统一 Candidate Qualification。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,8 +20,8 @@ from app.models import (
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderRouteDecision,
|
||||
ShippingOrderProcessingRun,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
build_process_finding,
|
||||
@@ -30,6 +30,10 @@ from app.services.shipping_notice.process_gate_contract import (
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
extraction_emergency_stop_enabled,
|
||||
generic_auto_freeze_enabled,
|
||||
xfa_customer_allowlist,
|
||||
xfa_profile_checksum_allowlist,
|
||||
xfa_scenario_allowlist,
|
||||
xfa_shadow_mode_enabled,
|
||||
)
|
||||
|
||||
_DEFAULT_BUSINESS_SCENARIO = 'shipping_notice_order'
|
||||
@@ -49,7 +53,7 @@ def build_initial_auto_freeze_policy(*, schema_policy_version: str | None) -> di
|
||||
|
||||
def evaluate_run_auto_freeze_policy(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
run: ShippingOrderProcessingRun,
|
||||
submission_result: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
@@ -76,6 +80,7 @@ def evaluate_run_auto_freeze_policy(
|
||||
'profile_auto_create_approved': False,
|
||||
'llm_route_present': _has_llm_assisted_route(run),
|
||||
'note': 'template_quality_only_not_auto_create_gate',
|
||||
'xfa': _xfa_policy_trace(run),
|
||||
}
|
||||
|
||||
# [STEP 1] 全局紧急停止:新 Run 自动冻结立即为 0。
|
||||
@@ -210,6 +215,36 @@ def evaluate_run_auto_freeze_policy(
|
||||
return policy
|
||||
|
||||
|
||||
def _xfa_policy_trace(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
"""
|
||||
汇总 Run 级 XFA 策略痕迹(真实放行仍由 CQ/STP 硬门禁裁决)。
|
||||
|
||||
核心逻辑:记录 shadow 与白名单规模,供审计对账;空白名单在 CQ 层 fail-closed。
|
||||
"""
|
||||
has_xfa = any(
|
||||
str(_route_contract(route).get('capability_kind') or '').strip() == 'xfa_dataset'
|
||||
or bool(_route_contract(route).get('xfa_evidence_summary'))
|
||||
for route in (run.route_decisions or [])
|
||||
)
|
||||
try:
|
||||
shadow = bool(xfa_shadow_mode_enabled())
|
||||
customers = list(xfa_customer_allowlist())
|
||||
checksums = list(xfa_profile_checksum_allowlist())
|
||||
scenarios = list(xfa_scenario_allowlist())
|
||||
except RuntimeError:
|
||||
shadow = False
|
||||
customers, checksums, scenarios = [], [], ['shipping_notice_order']
|
||||
return {
|
||||
'xfa_route_present': has_xfa,
|
||||
'hard_gates_enabled': True,
|
||||
'shadow_mode': shadow,
|
||||
'customer_allowlist_count': len(customers),
|
||||
'profile_checksum_allowlist_count': len(checksums),
|
||||
'scenario_allowlist': scenarios,
|
||||
'emergency_stop_blocks_auto_create': bool(extraction_emergency_stop_enabled()),
|
||||
}
|
||||
|
||||
|
||||
def _freeze_finding(reason_code: str) -> dict[str, Any]:
|
||||
"""
|
||||
将自动冻结原因投影为 order_freeze_readiness 所属 Finding。
|
||||
@@ -233,7 +268,7 @@ def _freeze_finding(reason_code: str) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
|
||||
def _route_contract(route: ShippingOrderExtractionRouteDecision) -> dict[str, Any]:
|
||||
def _route_contract(route: ShippingOrderRouteDecision) -> dict[str, Any]:
|
||||
"""从 candidate_summary_json 尾部提取阶段 0 路由契约摘要。"""
|
||||
items = route.candidate_summary_json if isinstance(route.candidate_summary_json, list) else []
|
||||
for item in reversed(items):
|
||||
@@ -242,7 +277,7 @@ def _route_contract(route: ShippingOrderExtractionRouteDecision) -> dict[str, An
|
||||
return {}
|
||||
|
||||
|
||||
def _route_type(route: ShippingOrderExtractionRouteDecision) -> str:
|
||||
def _route_type(route: ShippingOrderRouteDecision) -> str:
|
||||
"""从契约摘要或 selected_profile 推断路由类型。"""
|
||||
route_type = str(_route_contract(route).get('route_type') or '').strip()
|
||||
if route_type:
|
||||
@@ -252,7 +287,7 @@ def _route_type(route: ShippingOrderExtractionRouteDecision) -> str:
|
||||
return ''
|
||||
|
||||
|
||||
def _profile_routes(run: ShippingOrderExtractionRun) -> list[ShippingOrderExtractionRouteDecision]:
|
||||
def _profile_routes(run: ShippingOrderProcessingRun) -> list[ShippingOrderRouteDecision]:
|
||||
"""
|
||||
返回模板确定性分流决策(含未批准模板)。
|
||||
|
||||
@@ -265,19 +300,19 @@ def _profile_routes(run: ShippingOrderExtractionRun) -> list[ShippingOrderExtrac
|
||||
]
|
||||
|
||||
|
||||
def _approved_profile_routes(run: ShippingOrderExtractionRun) -> list[ShippingOrderExtractionRouteDecision]:
|
||||
def _approved_profile_routes(run: ShippingOrderProcessingRun) -> list[ShippingOrderRouteDecision]:
|
||||
"""返回模板质量已批准的确定性分流决策(兼容旧调用方)。"""
|
||||
return [route for route in _profile_routes(run) if bool(route.auto_create_approved)]
|
||||
|
||||
|
||||
def _approved_generic_routes(run: ShippingOrderExtractionRun) -> list[ShippingOrderExtractionRouteDecision]:
|
||||
def _approved_generic_routes(run: ShippingOrderProcessingRun) -> list[ShippingOrderRouteDecision]:
|
||||
"""
|
||||
返回 STP 直通的通用确定性分流决策。
|
||||
|
||||
核心逻辑:仅 `route_type=generic_deterministic` 且契约 `route_decision=straight_through`
|
||||
可进入自动冻结候选;不得用 execution_mode=`deterministic`(含 needs_review)放宽。
|
||||
"""
|
||||
result: list[ShippingOrderExtractionRouteDecision] = []
|
||||
result: list[ShippingOrderRouteDecision] = []
|
||||
for route in (run.route_decisions or []):
|
||||
contract = _route_contract(route)
|
||||
route_type = str(contract.get('route_type') or '').strip()
|
||||
@@ -287,13 +322,13 @@ def _approved_generic_routes(run: ShippingOrderExtractionRun) -> list[ShippingOr
|
||||
return result
|
||||
|
||||
|
||||
def _has_llm_assisted_route(run: ShippingOrderExtractionRun) -> bool:
|
||||
def _has_llm_assisted_route(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""任一单元走 LLM 辅助复核则禁止自动冻结。"""
|
||||
return any(_route_type(route) == 'llm_assisted_review' for route in (run.route_decisions or []))
|
||||
|
||||
|
||||
def _qualification_for_route(
|
||||
route: ShippingOrderExtractionRouteDecision,
|
||||
route: ShippingOrderRouteDecision,
|
||||
) -> ShippingDocumentProfileAutoFreezeQualification | None:
|
||||
"""按命中的模板版本读取当前资格状态;缺失时按 fail-closed 处理。"""
|
||||
return ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
|
||||
@@ -302,7 +337,7 @@ def _qualification_for_route(
|
||||
).one_or_none()
|
||||
|
||||
|
||||
def _confirmed_customer_ids(run: ShippingOrderExtractionRun) -> list[int]:
|
||||
def _confirmed_customer_ids(run: ShippingOrderProcessingRun) -> list[int]:
|
||||
"""读取本轮已确认的 Bill-to 客户;跨订单多客户时必须维持 fail-closed。"""
|
||||
rows = (
|
||||
ShippingOrderCustomerMatch.query
|
||||
@@ -358,7 +393,7 @@ def _evaluate_business_scenario_scope(
|
||||
return 'matched', []
|
||||
|
||||
|
||||
def _has_technical_failure(run: ShippingOrderExtractionRun) -> bool:
|
||||
def _has_technical_failure(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""任一单元技术失败或技术失败事件均阻断自动冻结。"""
|
||||
units = (run.extraction_plan.units if run.extraction_plan is not None else [])
|
||||
if any(str(unit.technical_failure_reason_code or '').strip() for unit in units):
|
||||
@@ -369,13 +404,13 @@ def _has_technical_failure(run: ShippingOrderExtractionRun) -> bool:
|
||||
).first() is not None
|
||||
|
||||
|
||||
def _has_review_required_unit(run: ShippingOrderExtractionRun) -> bool:
|
||||
def _has_review_required_unit(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""任一 Unit 已要求人工复核时,禁止其余订单绕过整体 Run 门禁自动冻结。"""
|
||||
units = run.extraction_plan.units if run.extraction_plan is not None else []
|
||||
return any(str(unit.status or '') == 'review_required' for unit in units)
|
||||
|
||||
|
||||
def _has_budget_stop(run: ShippingOrderExtractionRun) -> bool:
|
||||
def _has_budget_stop(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""预算停止事件是自动冻结硬阻断。"""
|
||||
return ShippingOrderExtractionProgressEvent.query.filter_by(
|
||||
run_id=int(run.id),
|
||||
|
||||
@@ -5,7 +5,7 @@ services/shipping_notice/order_build_eligibility_service.py
|
||||
Candidate Qualification 统一自动建单检查。
|
||||
依赖:candidate_qualification_service(含 confidence_policy)、candidate_validation、field_rules、
|
||||
inventory_routing_engine、inventory_source_repository、
|
||||
ShippingNoticeCandidate / ShippingOrderExtractionUnit / ShippingOrderExtractionRun、
|
||||
ShippingOrderCandidate / ShippingOrderProcessingUnit / ShippingOrderProcessingRun、
|
||||
ShippingInventorySource、process_gate_contract(原因唯一归属)。
|
||||
逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核阻断;
|
||||
人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离;
|
||||
@@ -74,6 +74,39 @@ def _issue_with_explainability(issue: dict[str, Any]) -> dict[str, Any]:
|
||||
'explainability': explainability,
|
||||
}
|
||||
|
||||
|
||||
def _low_confidence_field_details(candidate: Any | None, qualification: dict[str, Any] | None) -> list[dict[str, Any]]:
|
||||
"""将统一资格快照中的低置信字段投影为用户可定位事实。"""
|
||||
raw = getattr(candidate, 'field_confidence_json', None)
|
||||
if not isinstance(raw, dict):
|
||||
return []
|
||||
policy = qualification.get('confidence_policy') if isinstance(qualification, dict) else {}
|
||||
try:
|
||||
default_threshold = float((policy or {}).get('minimum_confidence', 0.85))
|
||||
except (TypeError, ValueError):
|
||||
default_threshold = 0.85
|
||||
marked = [
|
||||
(str(code).strip(), item) for code, item in raw.items()
|
||||
if isinstance(item, dict) and (item.get('auto_create_key_field') is True or item.get('key_field') is True)
|
||||
]
|
||||
# 未配置关键字段时不展示普通字段低置信度,也不作为自动建单阻断事实。
|
||||
if not marked:
|
||||
return []
|
||||
entries = marked
|
||||
result: list[dict[str, Any]] = []
|
||||
for code, item in entries:
|
||||
if not code:
|
||||
continue
|
||||
value = item.get('confidence', item.get('value')) if isinstance(item, dict) else item
|
||||
threshold = (item.get('minimum_confidence', default_threshold) if isinstance(item, dict) else default_threshold)
|
||||
try:
|
||||
confidence = float(value) if value is not None else None
|
||||
minimum = float(threshold)
|
||||
except (TypeError, ValueError):
|
||||
confidence, minimum = None, default_threshold
|
||||
if confidence is None or confidence < minimum:
|
||||
result.append({'field_code': code, 'confidence': confidence, 'minimum_confidence': minimum})
|
||||
return result
|
||||
# 自动建单内部检查键:与 Candidate Qualification 门禁对齐;禁止平行投影为多条用户阻断。
|
||||
# 兼容别名:fields_complete / evidence_passed 等旧键仍可通过评估结果派生。
|
||||
AUTO_BUILD_GATE_KEYS: tuple[str, ...] = tuple(CANDIDATE_QUALIFICATION_GATE_KEYS)
|
||||
@@ -378,9 +411,9 @@ def assess_auto_build_gates(
|
||||
|
||||
Args:
|
||||
fields_complete: Schema 必填与建单字段是否已齐备。
|
||||
candidate: 可选 ShippingNoticeCandidate。
|
||||
unit: 可选 ShippingOrderExtractionUnit(含 route_decision_json,仅 parser_trace)。
|
||||
run: 可选 ShippingOrderExtractionRun(紧急停止等)。
|
||||
candidate: 可选 ShippingOrderCandidate。
|
||||
unit: 可选 ShippingOrderProcessingUnit(含 route_decision_json,仅 parser_trace)。
|
||||
run: 可选 ShippingOrderProcessingRun(紧急停止等)。
|
||||
customer_resolved: 可选客户确认结果,透传给资格评估。
|
||||
|
||||
Returns:
|
||||
@@ -616,7 +649,9 @@ def assess_order_build_eligibility(
|
||||
)
|
||||
# [STEP] Candidate Qualification:失败只阻断自动建单;用户投影折叠到唯一 Finding。
|
||||
gate_result = assess_auto_build_gates(
|
||||
fields_complete=fields_complete and can_build,
|
||||
# 必填字段门禁只反映字段是否缺失;不能把库存/客户/重复等其他阻断
|
||||
# 叠加进来后再把 required_fields_complete 错标为失败。
|
||||
fields_complete=fields_complete,
|
||||
candidate=candidate,
|
||||
unit=unit,
|
||||
run=run,
|
||||
@@ -626,6 +661,12 @@ def assess_order_build_eligibility(
|
||||
findings = list(gate_result.get('findings') or [])
|
||||
user_finding = gate_result.get('user_blocking_finding')
|
||||
if user_finding and can_build and not can_auto_create:
|
||||
details = {
|
||||
'blocking_reason_codes': [user_finding.get('reason_code')],
|
||||
'qualification_status': gate_result.get('qualification', {}).get('status') if isinstance(gate_result.get('qualification'), dict) else None,
|
||||
}
|
||||
if user_finding.get('reason_code') == 'field_low_confidence' or 'key_fields_minimum_confidence' in (gate_result.get('failed_gates') or []):
|
||||
details['low_confidence_fields'] = _low_confidence_field_details(candidate, gate_result.get('qualification'))
|
||||
issues.append({
|
||||
'code': 'candidate_qualification_blocked',
|
||||
'severity': 'auto_create_blocking',
|
||||
@@ -633,6 +674,7 @@ def assess_order_build_eligibility(
|
||||
'reason_code': user_finding.get('reason_code'),
|
||||
'finding_code': user_finding.get('finding_code'),
|
||||
'message': '自动建单资格未通过',
|
||||
'low_confidence_fields': details.get('low_confidence_fields', []),
|
||||
})
|
||||
|
||||
enabled_sources = list_database_inventory_sources(enabled_only=True)
|
||||
@@ -649,11 +691,26 @@ def assess_order_build_eligibility(
|
||||
continue
|
||||
label = str(item.get('display_name') or '').strip() or code
|
||||
inventory_source_labels[code] = label[:120]
|
||||
# [STEP] fail-closed 结果必须带可解释阻断事实,禁止出现“不可建单但无原因”的空状态。
|
||||
if not can_build and not issues:
|
||||
failed_gate = next((str(item) for item in gate_result.get('failed_gates') or [] if item), '')
|
||||
fallback_reason = _AUTO_BUILD_GATE_REASON_CODES.get(failed_gate, 'order_freeze_not_ready')
|
||||
issues.append({
|
||||
'code': 'build_eligibility_blocked',
|
||||
'reason_code': fallback_reason,
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': owning_gate_for_reason(fallback_reason) or 'order_freeze_readiness',
|
||||
'message': '整单建单资格未通过,请查看具体阻断项。',
|
||||
})
|
||||
|
||||
# [STEP] 统一附加 explainability,供复核台顶部摘要与 issue 列表共用
|
||||
explained_issues = [_issue_with_explainability(item) for item in issues]
|
||||
return {
|
||||
'can_build': can_build,
|
||||
'can_auto_create': can_auto_create,
|
||||
'shadow_would_auto_create': bool(
|
||||
(gate_result.get('qualification') or {}).get('shadow_would_auto_create')
|
||||
) if isinstance(gate_result.get('qualification'), dict) else False,
|
||||
'gates': dict(gate_result.get('gates') or {}),
|
||||
'failed_gates': list(gate_result.get('failed_gates') or []),
|
||||
'findings': findings,
|
||||
@@ -662,14 +719,30 @@ def assess_order_build_eligibility(
|
||||
'status': 'ready' if can_build else 'needs_review',
|
||||
'issues': explained_issues,
|
||||
'line_projections': line_projections,
|
||||
# 零规则候选时供复核台从已启用库存源人工选择(须填原因)。
|
||||
'enabled_inventory_source_codes': enabled_codes,
|
||||
'inventory_source_labels': inventory_source_labels,
|
||||
'assessment': {
|
||||
'can_create_task': bool(assessment.get('can_create_task')),
|
||||
'missing_required_fields': list(assessment.get('missing_required_fields') or []),
|
||||
'invalid_lines': list(assessment.get('invalid_lines') or []),
|
||||
},
|
||||
# 零规则候选时供复核台从已启用库存源人工选择(须填原因)。
|
||||
'enabled_inventory_source_codes': enabled_codes,
|
||||
'inventory_source_labels': inventory_source_labels,
|
||||
# 自动建单门禁的权威诊断;人工建单资格与自动建单资格必须可分别解释。
|
||||
'auto_create_diagnostics': {
|
||||
'failed_gates': list(gate_result.get('failed_gates') or []),
|
||||
'reason_codes': list(gate_result.get('qualification', {}).get('blocking_reason_codes') or [])
|
||||
if isinstance(gate_result.get('qualification'), dict) else [],
|
||||
'confidence_policy': dict(gate_result.get('confidence_policy') or {}),
|
||||
'parser_source': str((gate_result.get('qualification', {}).get('parser_trace') or {}).get('parser_source') or '')
|
||||
if isinstance(gate_result.get('qualification'), dict) else '',
|
||||
},
|
||||
'auto_create_failure_reasons': [
|
||||
{
|
||||
'code': str(code),
|
||||
'message': str(build_explainability_reason(reason_code=str(code), details={}).get('message') or code),
|
||||
}
|
||||
for code in (gate_result.get('qualification', {}).get('blocking_reason_codes') or [])
|
||||
] if isinstance(gate_result.get('qualification'), dict) and not can_auto_create else [],
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -58,14 +58,19 @@ def _actor_payload(row: ShippingOrderDocumentProfileAudit, actor: User | None) -
|
||||
|
||||
|
||||
def _event_payload(row: ShippingOrderDocumentProfileAudit, actor: User | None) -> dict[str, Any]:
|
||||
"""序列化单条审计事件;detail_json 已由写侧保证为非敏感摘要。"""
|
||||
"""序列化单条审计事件;detail_json 已由写侧保证为非敏感摘要(含 XFA checksum)。"""
|
||||
detail = dict(row.detail_json or {})
|
||||
return {
|
||||
'id': int(row.id),
|
||||
'event_type': row.event_type,
|
||||
'request_id': str(row.request_id or '') or None,
|
||||
'operation_id': str(row.operation_id or '') or None,
|
||||
'document_id': int(row.document_id) if row.document_id else None,
|
||||
'revision_no': int(row.revision_no) if row.revision_no is not None else None,
|
||||
'actor': _actor_payload(row, actor),
|
||||
'detail': dict(row.detail_json or {}),
|
||||
'detail': detail,
|
||||
'definition_checksum': detail.get('definition_checksum'),
|
||||
'before_definition_checksum': detail.get('before_definition_checksum'),
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_creation_service.py
|
||||
|
||||
用途:完成订单模板三步创建向导的最终原子提交。
|
||||
依赖:Profile 保存、样本布局、Revision、EditLease 与 Profile 审计模型。
|
||||
逻辑:前两步只在浏览器保存临时状态;本服务在最后一步一次创建草稿、首份建模/训练样本绑定、Revision 审计和编辑租约,任一失败整体回滚。
|
||||
用途:完成订单模板三步创建向导的最终原子提交(coordinate 或 xfa_dataset)。
|
||||
依赖:Profile 保存、样本布局/XFA 结构分析、Revision、EditLease 与 Profile 审计模型。
|
||||
逻辑:前两步只在浏览器保存临时状态;本服务在最后一步一次创建草稿、首份建模/训练样本绑定、
|
||||
Revision 审计和编辑租约。样本能力决定模板模式:XFA 不要求 table_id,坐标模式仍校验主表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,10 +18,11 @@ from typing import Any
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileEditLease,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingXfaStructureAnalysis,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
@@ -33,11 +35,10 @@ def _browser_session_id(value: Any) -> str:
|
||||
return session_id
|
||||
|
||||
|
||||
def _initial_definition(main_table_id: str) -> dict[str, Any]:
|
||||
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 {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {
|
||||
'document_type': 'purchase_order', 'page_pattern': 'one_or_more',
|
||||
'required_anchors': [], 'optional_anchors': [], 'minimum_score': 0, 'minimum_margin': 0,
|
||||
@@ -59,6 +60,25 @@ def _initial_definition(main_table_id: str) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _latest_ready_xfa_analysis(document_id: int) -> ShippingXfaStructureAnalysis | None:
|
||||
"""
|
||||
读取文档最新 ready 态 XFA 结构分析。
|
||||
|
||||
Args:
|
||||
document_id: ShippingOrderDocument 主键。
|
||||
|
||||
Returns:
|
||||
ready 分析记录;不存在则 None。
|
||||
"""
|
||||
return (
|
||||
ShippingXfaStructureAnalysis.query.filter_by(
|
||||
document_id=int(document_id), analysis_status='ready',
|
||||
)
|
||||
.order_by(ShippingXfaStructureAnalysis.id.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _new_profile_code() -> str:
|
||||
"""生成新模板族的服务端系统编码,避免客户端命名参与解析、版本和审计主键。"""
|
||||
return f"ODP-{datetime.utcnow():%Y%m%d}-{secrets.token_hex(6).upper()}"
|
||||
@@ -68,8 +88,12 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
"""
|
||||
以单事务完成创建向导。
|
||||
|
||||
核心逻辑:按样本 Layout/XFA 分析能力自动选择 coordinate 或 xfa_dataset;
|
||||
XFA 路径要求权威集合 path_id、禁止 table_id;坐标路径仍校验 main_table_id。
|
||||
|
||||
Args:
|
||||
data: 模板名称、已解析样本文档、主表格、Schema 和浏览器会话身份;系统编码由服务端生成。
|
||||
data: 模板名称、已解析样本文档、Schema、浏览器会话;XFA 另含权威/镜像集合 path_id;
|
||||
坐标另含 main_table_id。系统编码由服务端生成。
|
||||
actor_id: 当前管理员主键。
|
||||
|
||||
Returns:
|
||||
@@ -80,55 +104,125 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
schema_version_id = int(data.get('schema_version_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('wizard identity is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') from exc
|
||||
table_id = str(data.get('main_table_id') or '').strip()
|
||||
if not table_id:
|
||||
raise ValidationError('main_table_id is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
session_id = _browser_session_id(data.get('browser_session_id'))
|
||||
operation_id = str(data.get('operation_id') or secrets.token_hex(16)).strip()
|
||||
document = db.session.get(ShippingNoticeDocument, document_id)
|
||||
document = db.session.get(ShippingOrderDocument, document_id)
|
||||
if document is None:
|
||||
raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
raise NotFoundError(
|
||||
'Order profile sample document not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND',
|
||||
)
|
||||
layout = profile_service._document_layout(document)
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
if not any(str(item.get('table_id') or '') == table_id for item in tables):
|
||||
raise ValidationError('Selected main table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
xfa_ready = profile_service._layout_is_xfa_analysis_ready(layout)
|
||||
analysis = _latest_ready_xfa_analysis(document.id) if xfa_ready else None
|
||||
if xfa_ready and analysis is None:
|
||||
raise ValidationError(
|
||||
'XFA structure analysis is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE',
|
||||
)
|
||||
|
||||
# [STEP 1] 按样本能力分支:XFA 不要求 table_id;坐标仍校验主表。
|
||||
sample_table_id: str | None = None
|
||||
if analysis is not None:
|
||||
authoritative_path_id = str(data.get('authoritative_collection_path_id') or '').strip()
|
||||
if not authoritative_path_id:
|
||||
raise ValidationError(
|
||||
'authoritative_collection_path_id is required for XFA wizard',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
mirror_path_ids = [
|
||||
str(item).strip()
|
||||
for item in (data.get('mirror_collection_path_ids') or [])
|
||||
if str(item).strip()
|
||||
]
|
||||
definition = profile_service.build_initial_xfa_definition(
|
||||
document=document,
|
||||
analysis=analysis,
|
||||
authoritative_collection_path_id=authoritative_path_id,
|
||||
mirror_collection_path_ids=mirror_path_ids,
|
||||
)
|
||||
template_mode = 'xfa_dataset'
|
||||
change_source = 'xfa_wizard_created'
|
||||
wizard_event = 'xfa_draft_created'
|
||||
wizard_detail_extra = {
|
||||
'authoritative_collection_path_id': authoritative_path_id,
|
||||
'mirror_collection_path_ids': mirror_path_ids,
|
||||
'analysis_id': int(analysis.id),
|
||||
}
|
||||
else:
|
||||
table_id = str(data.get('main_table_id') or '').strip()
|
||||
if not table_id:
|
||||
raise ValidationError(
|
||||
'main_table_id is required',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
if not any(str(item.get('table_id') or '') == table_id for item in tables):
|
||||
raise ValidationError(
|
||||
'Selected main table is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
definition = _initial_coordinate_definition(table_id)
|
||||
sample_table_id = table_id
|
||||
template_mode = 'coordinate'
|
||||
change_source = 'wizard_created'
|
||||
wizard_event = 'wizard_created'
|
||||
wizard_detail_extra = {'main_table_id': table_id}
|
||||
|
||||
for _attempt in range(3):
|
||||
profile_code = _new_profile_code()
|
||||
if ShippingOrderDocumentProfile.query.filter_by(profile_code=profile_code).first() is None:
|
||||
break
|
||||
else:
|
||||
raise ConflictError('Could not allocate order document profile code', code='SHIPPING.ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS')
|
||||
raise ConflictError(
|
||||
'Could not allocate order document profile code',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_DRAFT_EXISTS',
|
||||
)
|
||||
try:
|
||||
# [STEP 2] 原子创建草稿、样本绑定、审计与编辑租约。
|
||||
saved = profile_service.save_draft(
|
||||
{
|
||||
'profile_code': profile_code,
|
||||
'display_name': data.get('display_name'),
|
||||
'schema_version_id': schema_version_id,
|
||||
'definition': _initial_definition(table_id),
|
||||
'definition': definition,
|
||||
'change_note': 'Created from template wizard',
|
||||
'template_mode': template_mode,
|
||||
'sample_document_id': document.id if template_mode == 'xfa_dataset' else None,
|
||||
},
|
||||
actor_id=actor_id, browser_session_id=session_id, operation_id=operation_id,
|
||||
change_source='wizard_created', commit=False,
|
||||
change_source=change_source, commit=False,
|
||||
)
|
||||
profile_id = int(saved['id'])
|
||||
# 首份样本既承载画布标注,也作为训练证据;盲测仍必须另选独立文档。
|
||||
# 首份样本既承载画布/映射,也作为训练证据;盲测仍必须另选独立文档。
|
||||
for sample_role in ('annotation', 'training'):
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile_id, document_id=document.id, table_id=table_id,
|
||||
profile_id=profile_id, document_id=document.id, table_id=sample_table_id,
|
||||
sample_role=sample_role, created_by_id=actor_id,
|
||||
))
|
||||
db.session.flush()
|
||||
profile_service._refresh_training_sample_count(db.session.get(ShippingOrderDocumentProfile, profile_id))
|
||||
revision_no = int(saved['draft_revision']['revision_no'])
|
||||
profile_service._audit(
|
||||
profile_id=profile_id, document_id=document.id, event_type='wizard_created', actor_id=actor_id,
|
||||
profile_id=profile_id, document_id=document.id, event_type=wizard_event, actor_id=actor_id,
|
||||
operation_id=operation_id, browser_session_id=session_id, revision_no=revision_no,
|
||||
detail={
|
||||
'main_table_id': table_id, 'schema_version_id': schema_version_id, 'profile_code': profile_code,
|
||||
'sample_roles': ['annotation', 'training'],
|
||||
'schema_version_id': schema_version_id, 'profile_code': profile_code,
|
||||
'template_mode': template_mode, 'sample_roles': ['annotation', 'training'],
|
||||
**wizard_detail_extra,
|
||||
},
|
||||
)
|
||||
if template_mode == 'xfa_dataset':
|
||||
profile_service._audit(
|
||||
profile_id=profile_id, document_id=document.id,
|
||||
event_type='xfa_authoritative_collection_selected', actor_id=actor_id,
|
||||
operation_id=operation_id, browser_session_id=session_id, revision_no=revision_no,
|
||||
detail={
|
||||
'authoritative_collection_path_id': wizard_detail_extra['authoritative_collection_path_id'],
|
||||
'mirror_collection_path_ids': wizard_detail_extra['mirror_collection_path_ids'],
|
||||
'source': 'wizard',
|
||||
},
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
token = secrets.token_urlsafe(32)
|
||||
db.session.add(ShippingOrderDocumentProfileEditLease(
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/shipping_notice/order_document_profile_diff.py
|
||||
|
||||
用途:计算订单模板版本之间的服务端语义差异,供版本中心详情页直接展示。
|
||||
依赖:ShippingOrderDocumentProfile、version_service 的安全详情 DTO。
|
||||
逻辑:先按 profile_code 约束比较范围,再用稳定身份配对 layout/field/sample,并对坐标使用统一容差避免浮点噪声。
|
||||
依赖:ShippingOrderDocumentProfile、version_service 的安全详情 DTO、xfa_contract 路径哈希。
|
||||
逻辑:先按 profile_code 约束比较范围;coordinate 比较 region/field,xfa_dataset 按
|
||||
mapping_id/field_id/data_path_hash 比较映射与集合,并对坐标使用统一容差避免浮点噪声。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,6 +31,9 @@ _ENTITY_ORDER = {
|
||||
'exclusion_region': 80,
|
||||
'order_field_layout': 90,
|
||||
'sample_binding': 100,
|
||||
'xfa_source_contract': 15,
|
||||
'xfa_header_mapping': 45,
|
||||
'xfa_line_mapping': 55,
|
||||
}
|
||||
|
||||
|
||||
@@ -704,6 +708,123 @@ def _compare_samples(before_detail: dict[str, Any] | None, after_detail: dict[st
|
||||
return items
|
||||
|
||||
|
||||
def _compare_xfa_definitions(before_def: dict[str, Any] | None, after_def: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
比较 XFA definition:source_contract、header/line 映射(按 mapping_id)。
|
||||
|
||||
Args:
|
||||
before_def: 基线 definition。
|
||||
after_def: 当前 definition。
|
||||
|
||||
Returns:
|
||||
结构化 diff 项列表。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import hash_data_path
|
||||
|
||||
items: list[dict[str, Any]] = []
|
||||
before_source = (before_def or {}).get('source_contract') if isinstance((before_def or {}).get('source_contract'), dict) else {}
|
||||
after_source = after_def.get('source_contract') if isinstance(after_def.get('source_contract'), dict) else {}
|
||||
source_changes = _scalar_changes(
|
||||
{
|
||||
'template_packet_checksum': before_source.get('template_packet_checksum'),
|
||||
'dataset_structure_fingerprint': before_source.get('dataset_structure_fingerprint'),
|
||||
'authoritative_collection_path_hash': (
|
||||
hash_data_path(str(before_source['authoritative_line_collection_path']))
|
||||
if before_source.get('authoritative_line_collection_path') else None
|
||||
),
|
||||
'mirror_collection_count': len(before_source.get('mirror_collection_paths') or []),
|
||||
},
|
||||
{
|
||||
'template_packet_checksum': after_source.get('template_packet_checksum'),
|
||||
'dataset_structure_fingerprint': after_source.get('dataset_structure_fingerprint'),
|
||||
'authoritative_collection_path_hash': (
|
||||
hash_data_path(str(after_source['authoritative_line_collection_path']))
|
||||
if after_source.get('authoritative_line_collection_path') else None
|
||||
),
|
||||
'mirror_collection_count': len(after_source.get('mirror_collection_paths') or []),
|
||||
},
|
||||
(
|
||||
'template_packet_checksum',
|
||||
'dataset_structure_fingerprint',
|
||||
'authoritative_collection_path_hash',
|
||||
'mirror_collection_count',
|
||||
),
|
||||
)
|
||||
if source_changes:
|
||||
items.append(_item(
|
||||
entity_type='xfa_source_contract',
|
||||
entity_id='source_contract',
|
||||
parent_id=None,
|
||||
label='XFA source contract',
|
||||
before=before_source or None,
|
||||
after=after_source or None,
|
||||
changes=source_changes,
|
||||
sort_key='015:source_contract',
|
||||
))
|
||||
|
||||
def _mapping_map(definition: dict[str, Any] | None, *, line: bool) -> dict[str, dict[str, Any]]:
|
||||
if not isinstance(definition, dict):
|
||||
return {}
|
||||
if line:
|
||||
body = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
rows = body.get('fields') or []
|
||||
else:
|
||||
rows = definition.get('header_mappings') or []
|
||||
result: dict[str, dict[str, Any]] = {}
|
||||
for index, item in enumerate(rows):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
key = str(item.get('mapping_id') or item.get('field_id') or f'index:{index}')
|
||||
result[key] = item
|
||||
return result
|
||||
|
||||
for line, entity_type, label_prefix, sort_prefix in (
|
||||
(False, 'xfa_header_mapping', 'XFA header mapping', '045'),
|
||||
(True, 'xfa_line_mapping', 'XFA line mapping', '055'),
|
||||
):
|
||||
previous_map = _mapping_map(before_def, line=line)
|
||||
current_map = _mapping_map(after_def, line=line)
|
||||
for mapping_id in sorted(set(previous_map) | set(current_map)):
|
||||
previous = previous_map.get(mapping_id)
|
||||
current = current_map.get(mapping_id)
|
||||
previous_body = previous or {}
|
||||
current_body = current or {}
|
||||
changes = _scalar_changes(
|
||||
{
|
||||
'field_id': previous_body.get('field_id'),
|
||||
'field_code': previous_body.get('field_code'),
|
||||
'path_id': previous_body.get('path_id'),
|
||||
'data_path_hash': (
|
||||
hash_data_path(str(previous_body['data_path']))
|
||||
if previous_body.get('data_path') else None
|
||||
),
|
||||
'normalizer_key': previous_body.get('normalizer_key'),
|
||||
},
|
||||
{
|
||||
'field_id': current_body.get('field_id'),
|
||||
'field_code': current_body.get('field_code'),
|
||||
'path_id': current_body.get('path_id'),
|
||||
'data_path_hash': (
|
||||
hash_data_path(str(current_body['data_path']))
|
||||
if current_body.get('data_path') else None
|
||||
),
|
||||
'normalizer_key': current_body.get('normalizer_key'),
|
||||
},
|
||||
('field_id', 'field_code', 'path_id', 'data_path_hash', 'normalizer_key'),
|
||||
)
|
||||
items.append(_item(
|
||||
entity_type=entity_type,
|
||||
entity_id=mapping_id,
|
||||
parent_id=None,
|
||||
label=f'{label_prefix} {mapping_id}',
|
||||
before=previous,
|
||||
after=current,
|
||||
changes=changes,
|
||||
sort_key=f'{sort_prefix}:{mapping_id}',
|
||||
))
|
||||
return items
|
||||
|
||||
|
||||
def compare_profile_details(before_detail: dict[str, Any] | None, after_detail: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
比较两个安全详情 DTO,返回稳定排序的语义差异。
|
||||
@@ -718,9 +839,18 @@ def compare_profile_details(before_detail: dict[str, Any] | None, after_detail:
|
||||
before_definition = None if before_detail is None else dict(before_detail.get('definition') or {})
|
||||
items: list[dict[str, Any]] = []
|
||||
items.extend(_compare_profile_meta(before_detail, after_detail))
|
||||
items.extend(_compare_document_match(before_definition, after_definition))
|
||||
items.extend(_compare_table_regions(before_definition, after_definition))
|
||||
items.extend(_compare_order_field_layouts(before_definition, after_definition))
|
||||
after_mode = str(after_definition.get('template_mode') or after_detail.get('template_mode') or 'coordinate')
|
||||
before_mode = str(
|
||||
(before_definition or {}).get('template_mode')
|
||||
or ((before_detail or {}).get('template_mode') if before_detail else '')
|
||||
or after_mode,
|
||||
)
|
||||
if after_mode == 'xfa_dataset' or before_mode == 'xfa_dataset':
|
||||
items.extend(_compare_xfa_definitions(before_definition, after_definition))
|
||||
else:
|
||||
items.extend(_compare_document_match(before_definition, after_definition))
|
||||
items.extend(_compare_table_regions(before_definition, after_definition))
|
||||
items.extend(_compare_order_field_layouts(before_definition, after_definition))
|
||||
items.extend(_compare_samples(before_detail, after_detail))
|
||||
ordered = _sort_items(items)
|
||||
summary = {'added': 0, 'removed': 0, 'modified': 0, 'unchanged': 0}
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
backend/app/services/shipping_notice/order_document_profile_preview_service.py
|
||||
|
||||
用途:提供订单模板版本中心的冻结样本只读预览链路。
|
||||
依赖:Profile/Sample/Layout 模型、preview_grant_store、PDF 渲染能力。
|
||||
逻辑:预览必须绑定 profile sample,并校验冻结的 document/layout/hash/checksum 后才签发一次性 token。
|
||||
依赖:Profile/Sample/Layout 模型、preview_grant_store、PDF 渲染能力、XFA 只读映射 DTO。
|
||||
逻辑:预览必须绑定 profile sample,并校验冻结的 document/layout/hash/checksum 后才签发一次性 token;
|
||||
XFA 模式禁止空白 PDF 页预览,改为返回只读映射证据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,7 +21,7 @@ from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
@@ -34,6 +35,99 @@ PREVIEW_GRANT_TTL_SECONDS = 120
|
||||
PREVIEW_GRANT_KEY_PREFIX = 'shipping:order-profile-frozen-preview:'
|
||||
|
||||
|
||||
def _is_xfa_profile(profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""判断 Profile 是否为 xfa_dataset 模式。"""
|
||||
mode = str(profile.template_mode or '').strip()
|
||||
if not mode:
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
mode = str(definition.get('template_mode') or '').strip()
|
||||
return mode == 'xfa_dataset'
|
||||
|
||||
|
||||
def build_xfa_readonly_mapping_evidence(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""
|
||||
构造 XFA 发布版本只读映射证据 DTO(不含空白 PDF、明文路径原文树可选)。
|
||||
|
||||
核心逻辑:从 definition 投影 Header/Line 映射、集合策略与结构身份摘要;
|
||||
不签发 PDF preview token,不返回 XML 或盲测真值。
|
||||
|
||||
Args:
|
||||
profile: 任意状态 Profile(通常 published/retired)。
|
||||
|
||||
Returns:
|
||||
前端 XfaReadOnlyMapping 可消费的安全摘要。
|
||||
"""
|
||||
definition = dict(profile.definition_json or {})
|
||||
source = definition.get('source_contract') if isinstance(definition.get('source_contract'), dict) else {}
|
||||
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
cross_checks = definition.get('cross_checks') if isinstance(definition.get('cross_checks'), dict) else {}
|
||||
header_maps = []
|
||||
for item in definition.get('header_mappings') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
header_maps.append({
|
||||
'mapping_id': item.get('mapping_id'),
|
||||
'field_id': item.get('field_id'),
|
||||
'field_code': item.get('field_code'),
|
||||
'path_id': item.get('path_id'),
|
||||
'value_type': item.get('value_type'),
|
||||
'normalizer_key': item.get('normalizer_key'),
|
||||
})
|
||||
line_maps = []
|
||||
for item in line_mapping.get('fields') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
line_maps.append({
|
||||
'mapping_id': item.get('mapping_id'),
|
||||
'field_id': item.get('field_id'),
|
||||
'field_code': item.get('field_code'),
|
||||
'path_id': item.get('path_id'),
|
||||
'value_type': item.get('value_type'),
|
||||
'normalizer_key': item.get('normalizer_key'),
|
||||
})
|
||||
frozen_samples = []
|
||||
for sample in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).order_by(
|
||||
ShippingOrderDocumentProfileSample.id.asc(),
|
||||
).all():
|
||||
if sample.sample_role == 'blind_test':
|
||||
continue
|
||||
identity = dict(sample.table_identity_snapshot or {})
|
||||
frozen_samples.append({
|
||||
'sample_binding_id': sample.id,
|
||||
'sample_role': sample.sample_role,
|
||||
'document_id': sample.document_id,
|
||||
'filename': sample.source_filename_snapshot,
|
||||
'structure_analysis_id': identity.get('structure_analysis_id'),
|
||||
'template_packet_checksum': identity.get('template_packet_checksum'),
|
||||
'dataset_structure_fingerprint': identity.get('dataset_structure_fingerprint'),
|
||||
'parser_identity': identity.get('parser_identity') or sample.parser_version,
|
||||
'evidence_frozen_at': sample.evidence_frozen_at.isoformat() if sample.evidence_frozen_at else None,
|
||||
})
|
||||
return {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'pdf_preview_available': False,
|
||||
'source_contract': {
|
||||
'template_packet_checksum': source.get('template_packet_checksum'),
|
||||
'dataset_structure_fingerprint': source.get('dataset_structure_fingerprint'),
|
||||
'dataset_root_path': source.get('dataset_root_path'),
|
||||
'authoritative_line_collection_path': source.get('authoritative_line_collection_path'),
|
||||
'mirror_collection_paths': list(source.get('mirror_collection_paths') or []),
|
||||
},
|
||||
'header_mappings': header_maps,
|
||||
'line_mappings': line_maps,
|
||||
'cross_checks': {
|
||||
'acroform_enabled': cross_checks.get('acroform_enabled'),
|
||||
'mirror_collection_policy': cross_checks.get('mirror_collection_policy'),
|
||||
'line_amount_formula': cross_checks.get('line_amount_formula'),
|
||||
'total_amount_policy': cross_checks.get('total_amount_policy'),
|
||||
},
|
||||
'frozen_samples': frozen_samples,
|
||||
'matching_signature_checksum': profile.matching_signature_checksum,
|
||||
'matching_signature_version': profile.matching_signature_version,
|
||||
'profile_checksum': profile.checksum or profile.structure_fingerprint,
|
||||
}
|
||||
|
||||
|
||||
def _preview_grant_store() -> Any:
|
||||
"""返回冻结样本页预览的授权存储。"""
|
||||
return preview_grant_store()
|
||||
@@ -62,7 +156,17 @@ def _audit(
|
||||
|
||||
|
||||
def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) -> bool:
|
||||
"""旧未冻结样本不得伪装成可审计只读画布。"""
|
||||
"""旧未冻结样本不得伪装成可审计只读画布;XFA 以 structure identity 快照为准。"""
|
||||
identity = sample.table_identity_snapshot if isinstance(sample.table_identity_snapshot, dict) else {}
|
||||
if str(identity.get('kind') or '') == 'xfa_structure':
|
||||
return bool(
|
||||
sample.source_content_hash
|
||||
and sample.parser_key
|
||||
and sample.evidence_frozen_at
|
||||
and identity.get('structure_analysis_id')
|
||||
and identity.get('template_packet_checksum')
|
||||
and identity.get('dataset_structure_fingerprint')
|
||||
)
|
||||
required = (
|
||||
sample.layout_version_id,
|
||||
sample.source_content_hash,
|
||||
@@ -116,7 +220,7 @@ def _frozen_sample_context(
|
||||
) -> tuple[
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderDocument,
|
||||
ShippingDocumentLayoutVersion,
|
||||
FileAsset,
|
||||
]:
|
||||
@@ -137,7 +241,7 @@ def _frozen_sample_context(
|
||||
'Frozen evidence is unavailable for this sample',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
document = db.session.get(ShippingNoticeDocument, int(sample.document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
|
||||
if document is None or not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
|
||||
raise ValidationError(
|
||||
'Frozen sample file is unavailable',
|
||||
@@ -231,6 +335,14 @@ def authorize_frozen_sample_preview_pages(
|
||||
'Order profile sample not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND',
|
||||
)
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
if _is_xfa_profile(profile):
|
||||
raise ValidationError(
|
||||
'XFA profiles do not support blank PDF page preview',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
_, sample, document, _layout_version, asset = _frozen_sample_context(
|
||||
profile_id=int(profile_id), sample_binding_id=int(sample_binding_id),
|
||||
)
|
||||
@@ -301,6 +413,48 @@ def _page_glyphs(layout_payload: dict[str, Any], *, page_no: int) -> list[dict[s
|
||||
]
|
||||
|
||||
|
||||
def _recover_frozen_page_coordinates(
|
||||
*, document: ShippingOrderDocument, asset: FileAsset, payload: dict[str, Any], page_no: int,
|
||||
) -> tuple[dict[str, Any] | None, list[dict[str, Any]], str | None]:
|
||||
"""从已校验哈希的冻结 PDF 临时恢复单页坐标,仅供历史版本只读诊断。"""
|
||||
if not str(getattr(document, 'filename', '') or '').lower().endswith('.pdf'):
|
||||
return None, [], None
|
||||
try:
|
||||
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 _ocr_lines_to_page_characters
|
||||
|
||||
native_page = next(
|
||||
item for item in extract_native_pdf_pages(
|
||||
read_asset_bytes(asset), render_images=False,
|
||||
)
|
||||
if int(item.page_no) == int(page_no)
|
||||
)
|
||||
glyphs = [item.model_dump(mode='json') for item in getattr(native_page, 'characters', []) or []]
|
||||
source = 'pdf_coordinate'
|
||||
if not glyphs:
|
||||
# OCR 回退需要页面图;原生文字快速路径不额外渲染图片。
|
||||
rendered_page = next(
|
||||
item for item in extract_native_pdf_pages(read_asset_bytes(asset))
|
||||
if int(item.page_no) == int(page_no)
|
||||
)
|
||||
lines = extract_ocr_lines(
|
||||
rendered_page.image, page_width=rendered_page.width, page_height=rendered_page.height,
|
||||
)
|
||||
glyphs = _ocr_lines_to_page_characters(lines=lines)
|
||||
native_page = rendered_page
|
||||
source = 'ocr_coordinate'
|
||||
if not glyphs:
|
||||
return None, [], None
|
||||
return {
|
||||
'width': float(native_page.width), 'height': float(native_page.height),
|
||||
}, glyphs, source
|
||||
except Exception:
|
||||
# 历史详情增强失败不能阻断已冻结 PDF 主画布,也不能改用最新布局。
|
||||
return None, [], None
|
||||
|
||||
|
||||
def _diagnostic_regions(profile: ShippingOrderDocumentProfile, *, page_no: int) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从模板定义派生当前页允许诊断的标签和值区域,禁止客户端传入任意坐标。
|
||||
@@ -430,15 +584,31 @@ def frozen_sample_region_diagnostics(
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
profile, sample, document, layout_version, _asset = _frozen_sample_context(
|
||||
profile, sample, document, layout_version, asset = _frozen_sample_context(
|
||||
profile_id=int(profile_id), sample_binding_id=int(sample_binding_id),
|
||||
)
|
||||
payload = dict(layout_version.payload_json or {})
|
||||
evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {}
|
||||
page = (evidence.get('pages') or {}).get(str(page_no))
|
||||
if not isinstance(page, dict):
|
||||
raise NotFoundError('Order profile preview page not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND')
|
||||
glyphs = _page_glyphs(payload, page_no=int(page_no))
|
||||
coordinate_source = 'frozen_layout'
|
||||
if not isinstance(page, dict) or not glyphs:
|
||||
# [STEP 1] 兼容早期冻结版本:其 checksum 对应的 payload 只有 table glyph,
|
||||
# 但原 PDF 内容哈希已在 _frozen_sample_context 中校验,可安全临时恢复整页坐标。
|
||||
page, glyphs, recovered_source = _recover_frozen_page_coordinates(
|
||||
document=document, asset=asset, payload=payload, page_no=int(page_no),
|
||||
)
|
||||
coordinate_source = recovered_source or 'unavailable'
|
||||
if not isinstance(page, dict) or not glyphs:
|
||||
# 冻结样本可能只有 PDF/表格布局、没有字符坐标证据;这不影响整页 PNG 预览。
|
||||
# 区域诊断是增强能力,返回空结果而不是伪装成“预览页不存在”。
|
||||
_audit(
|
||||
profile_id=int(profile_id), document_id=int(document.id), sample_binding_id=int(sample.id),
|
||||
event_type='preview_region_diagnostics_viewed', actor_id=actor_id,
|
||||
detail={'page_no': int(page_no), 'region_count': 0, 'mode': 'frozen_sample', 'coordinate_evidence': 'unavailable'},
|
||||
)
|
||||
db.session.commit()
|
||||
return {'sample_binding_id': int(sample.id), 'page_no': int(page_no), 'items': []}
|
||||
items: list[dict[str, Any]] = []
|
||||
for item in _diagnostic_regions(profile, page_no=int(page_no)):
|
||||
recognized = read_coordinate_region_text(glyphs=glyphs, page=page, region=item['region'])
|
||||
@@ -453,7 +623,10 @@ def frozen_sample_region_diagnostics(
|
||||
_audit(
|
||||
profile_id=int(profile_id), document_id=int(document.id), sample_binding_id=int(sample.id),
|
||||
event_type='preview_region_diagnostics_viewed', actor_id=actor_id,
|
||||
detail={'page_no': int(page_no), 'region_count': len(items), 'mode': 'frozen_sample'},
|
||||
detail={
|
||||
'page_no': int(page_no), 'region_count': len(items), 'mode': 'frozen_sample',
|
||||
'coordinate_evidence': coordinate_source,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return {'sample_binding_id': int(sample.id), 'page_no': int(page_no), 'items': items}
|
||||
|
||||
+575
-25
@@ -2,8 +2,9 @@
|
||||
services/shipping_notice/order_document_profile_publish_check_service.py
|
||||
|
||||
用途:生成、确认和消费订单模板不可变发布检查报告。
|
||||
依赖:草稿 Revision、验证运行、语义差异、发布服务和编辑租约服务。
|
||||
逻辑:报告冻结当前草稿身份;消费时在同一事务再次校验并发布,草稿变化只能令报告失效。
|
||||
依赖:草稿 Revision、验证运行、版面/XFA 结构签名、跨模板重叠验证、语义差异、发布服务和编辑租约服务。
|
||||
逻辑:报告冻结当前草稿身份与签名/重叠引用;XFA 模式使用结构签名与路径/集合/对账阻断;
|
||||
消费时在同一事务再次校验并发布,草稿或签名变化只能令报告失效。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -11,10 +12,11 @@ import secrets
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileEditLease,
|
||||
ShippingOrderDocumentProfilePublishCheckReport,
|
||||
@@ -23,6 +25,33 @@ from app.models import (
|
||||
from app.services.shipping_notice import order_document_profile_diff as diff_service
|
||||
from app.services.shipping_notice import order_document_profile_lease_service as lease_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
|
||||
from app.services.shipping_notice.document_layout.order_profile_signature import MATCHER_POLICY_ID
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_STRUCTURE_SIGNATURE_ID
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def _is_xfa_profile(profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""判断草稿是否为 xfa_dataset 模式。"""
|
||||
mode = str(profile.template_mode or '').strip()
|
||||
if not mode:
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
mode = str(definition.get('template_mode') or '').strip()
|
||||
return mode == 'xfa_dataset'
|
||||
|
||||
|
||||
def _append_publish_check_ledger_event(
|
||||
*, profile: ShippingOrderDocumentProfile, event_type: str, actor_id: int | None,
|
||||
operation_id: str, result: str, before: dict[str, Any], after: dict[str, Any],
|
||||
metadata: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""将发布检查创建、失效和消费同步写入统一不可变审计账本。"""
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type, aggregate_type='order_document_profile', aggregate_id=str(profile.id),
|
||||
actor_type='admin' if actor_id is not None else 'system', actor_id=actor_id,
|
||||
operation_id=operation_id, action=event_type, result=result, version_no=profile.version,
|
||||
before=before, after=after, metadata=metadata or {},
|
||||
)
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
@@ -45,28 +74,448 @@ def _current_revision(profile: ShippingOrderDocumentProfile) -> ShippingOrderDoc
|
||||
return revision
|
||||
|
||||
|
||||
def _payload(row: ShippingOrderDocumentProfilePublishCheckReport) -> dict[str, Any]:
|
||||
def _signature_status(profile: ShippingOrderDocumentProfile, revision: ShippingOrderDocumentProfileDraftRevision) -> dict[str, Any]:
|
||||
"""派生当前草稿版面/XFA 结构签名状态与可展示摘要。"""
|
||||
expected_run_type = 'xfa_structure_signature' if _is_xfa_profile(profile) else 'layout_signature'
|
||||
if not profile.matching_signature_run_id or not profile.matching_signature_checksum:
|
||||
return {'status': 'missing', 'signature_kind': expected_run_type}
|
||||
run = db.session.get(ShippingOrderDocumentProfileValidationRun, int(profile.matching_signature_run_id))
|
||||
stale = (
|
||||
run is None
|
||||
or run.profile_id != profile.id
|
||||
or run.run_type != expected_run_type
|
||||
or run.status != 'passed'
|
||||
or run.definition_checksum != revision.definition_checksum
|
||||
)
|
||||
summary = dict(run.summary_json or {}) if run is not None else {}
|
||||
snapshot = dict(run.result_snapshot_json or {}) if run is not None else {}
|
||||
payload = {
|
||||
'status': 'stale' if stale else 'valid',
|
||||
'signature_kind': expected_run_type,
|
||||
'run_id': profile.matching_signature_run_id,
|
||||
'signature_checksum': profile.matching_signature_checksum,
|
||||
'signature_version': profile.matching_signature_version or summary.get('signature_version'),
|
||||
'source_sample_count': summary.get('source_sample_count'),
|
||||
'matcher_policy_version': summary.get('matcher_policy_version') or snapshot.get('matcher_policy_version'),
|
||||
}
|
||||
if expected_run_type == 'layout_signature':
|
||||
payload.update({
|
||||
'tables_with_header_tokens': summary.get('tables_with_header_tokens'),
|
||||
'header_token_coverage': summary.get('header_token_coverage'),
|
||||
'provider_versions': (snapshot.get('signature') or {}).get('provider_versions')
|
||||
if isinstance(snapshot.get('signature'), dict) else None,
|
||||
})
|
||||
else:
|
||||
payload.update({
|
||||
'template_packet_checksum': summary.get('template_packet_checksum'),
|
||||
'dataset_structure_fingerprint': summary.get('dataset_structure_fingerprint'),
|
||||
'parser_identity': summary.get('parser_identity'),
|
||||
'analysis_count': summary.get('analysis_count'),
|
||||
})
|
||||
return payload
|
||||
|
||||
|
||||
def _find_last_profile_editor_id(profile_id: int) -> int | None:
|
||||
"""
|
||||
查找最近一次编辑 Profile 映射/拆分规则的管理员 ID。
|
||||
|
||||
核心逻辑:优先审计事件;回退至最新 DraftRevision.created_by_id。
|
||||
"""
|
||||
editor_events = (
|
||||
'xfa_mapping_saved',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_segment_mapping_updated',
|
||||
'xfa_profile_draft_saved',
|
||||
)
|
||||
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 _blocking_xfa_definition(
|
||||
profile: ShippingOrderDocumentProfile,
|
||||
validation: ShippingOrderDocumentProfileValidationRun | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
汇总 XFA 发布阻断项:缺失路径、集合歧义、对账失败、stale 验证。
|
||||
|
||||
核心逻辑:检查 source_contract / 映射覆盖 / current_sample 摘要中的对账失败码。
|
||||
"""
|
||||
blocking: list[dict[str, Any]] = []
|
||||
definition = dict(profile.definition_json or {})
|
||||
source = definition.get('source_contract') if isinstance(definition.get('source_contract'), dict) else {}
|
||||
if not source.get('template_packet_checksum') or not source.get('dataset_structure_fingerprint'):
|
||||
blocking.append({
|
||||
'key': 'xfa_structure_identity_missing',
|
||||
'message': 'XFA template packet checksum and dataset structure fingerprint are required.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_REQUIRED',
|
||||
})
|
||||
if not source.get('authoritative_line_collection_path'):
|
||||
blocking.append({
|
||||
'key': 'xfa_authoritative_collection_missing',
|
||||
'message': 'An authoritative line collection path must be selected.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
})
|
||||
header_mappings = [item for item in (definition.get('header_mappings') or []) if isinstance(item, dict)]
|
||||
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
line_fields = [item for item in (line_mapping.get('fields') or []) if isinstance(item, dict)]
|
||||
if any(not item.get('data_path') or not item.get('field_id') for item in header_mappings + line_fields):
|
||||
blocking.append({
|
||||
'key': 'xfa_mapping_path_missing',
|
||||
'message': 'Every XFA mapping must bind a known data path.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
})
|
||||
schema_fields = {
|
||||
str(item.get('field_id') or ''): item
|
||||
for item in ((profile.schema_version.definition_json or {}).get('fields') or [])
|
||||
if isinstance(item, dict) and item.get('enabled', True)
|
||||
}
|
||||
mapped_ids = {
|
||||
str(item.get('field_id') or '')
|
||||
for item in header_mappings + line_fields
|
||||
if item.get('field_id')
|
||||
}
|
||||
split_rules_raw = definition.get('split_rules') or []
|
||||
if split_rules_raw:
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
parse_split_rule_sets,
|
||||
validate_split_rules_against_schema,
|
||||
)
|
||||
known_path_ids = {
|
||||
str(item.get('path_id') or '')
|
||||
for item in header_mappings + line_fields
|
||||
if item.get('path_id')
|
||||
}
|
||||
authoritative_path = str(source.get('authoritative_line_collection_path') or '').rstrip('/')
|
||||
try:
|
||||
split_rule_sets = parse_split_rule_sets(split_rules_raw)
|
||||
source_scopes = {
|
||||
item.source_path_id: (
|
||||
'line'
|
||||
if item.source_data_path
|
||||
and str(item.source_data_path).startswith(f'{authoritative_path}/')
|
||||
else 'header'
|
||||
)
|
||||
for item in split_rule_sets
|
||||
if item.source_data_path
|
||||
}
|
||||
validate_split_rules_against_schema(
|
||||
split_rule_sets,
|
||||
known_schema_fields={
|
||||
str(cfg.get('field_code') or field_id): cfg
|
||||
for field_id, cfg in schema_fields.items()
|
||||
if cfg.get('field_code')
|
||||
},
|
||||
known_path_ids=None,
|
||||
source_scopes=source_scopes,
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
blocking.append({
|
||||
'key': 'xfa_split_rules_invalid',
|
||||
'message': 'XFA split rules contract validation failed.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'detail': str(exc)[:200],
|
||||
})
|
||||
split_rule_sets = []
|
||||
for rule_set in split_rule_sets:
|
||||
if not rule_set.source_data_path:
|
||||
blocking.append({
|
||||
'key': 'xfa_split_rule_source_path_missing',
|
||||
'message': 'Every XFA split rule must have a frozen source data path.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'rule_id': rule_set.rule_id,
|
||||
})
|
||||
if (
|
||||
rule_set.requires_confirmation
|
||||
or rule_set.status == 'draft'
|
||||
or rule_set.source == 'system_suggestion'
|
||||
):
|
||||
blocking.append({
|
||||
'key': 'xfa_split_rules_unconfirmed',
|
||||
'message': 'All split rules must be confirmed before publish.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'rule_id': rule_set.rule_id,
|
||||
})
|
||||
for rule in rule_set.rules:
|
||||
if rule.segment.handling != 'mapped':
|
||||
continue
|
||||
target_id = str(rule.segment.target_field_id or '')
|
||||
if target_id:
|
||||
mapped_ids.add(target_id)
|
||||
missing_required = [
|
||||
str(cfg.get('field_code') or field_id)
|
||||
for field_id, cfg in schema_fields.items()
|
||||
if (cfg.get('required') is True or cfg.get('auto_create_key_field') is True)
|
||||
and field_id not in mapped_ids
|
||||
]
|
||||
if missing_required:
|
||||
blocking.append({
|
||||
'key': 'xfa_required_path_coverage_incomplete',
|
||||
'message': 'Required or auto-create-key Schema fields are missing XFA path mappings.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'field_codes': missing_required[:20],
|
||||
})
|
||||
if validation is not None:
|
||||
summary = dict(validation.summary_json or {})
|
||||
if validation.definition_checksum != profile.structure_fingerprint or validation.status != 'passed':
|
||||
blocking.append({
|
||||
'key': 'current_validation_stale',
|
||||
'message': 'Current-sample validation is stale for the draft checksum.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID',
|
||||
})
|
||||
failures = list(summary.get('cross_check_failures') or [])
|
||||
if int(summary.get('header_required_missing_count') or 0) > 0:
|
||||
blocking.append({
|
||||
'key': 'xfa_required_fields_unreadable',
|
||||
'message': 'Required mapped fields are missing readable values on the current sample.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
})
|
||||
if int(summary.get('auto_create_key_missing_count') or 0) > 0:
|
||||
blocking.append({
|
||||
'key': 'xfa_auto_create_key_incomplete',
|
||||
'message': 'Auto-create key fields are incomplete on the current sample.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
})
|
||||
if 'xfa_mirror_collection_mismatch' in failures:
|
||||
blocking.append({
|
||||
'key': 'xfa_collection_ambiguity',
|
||||
'message': 'Mirror collection reconciliation failed.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
})
|
||||
if 'xfa_acroform_mismatch' in failures or 'xfa_business_validation_failed' in failures:
|
||||
blocking.append({
|
||||
'key': 'xfa_reconciliation_failed',
|
||||
'message': 'XFA AcroForm or business reconciliation failed.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
})
|
||||
if any(code.startswith('xfa_') for code in failures) and not any(
|
||||
item.get('key') in {
|
||||
'xfa_collection_ambiguity', 'xfa_reconciliation_failed',
|
||||
'xfa_required_fields_unreadable', 'xfa_auto_create_key_incomplete',
|
||||
}
|
||||
for item in blocking
|
||||
):
|
||||
blocking.append({
|
||||
'key': 'xfa_current_sample_failed',
|
||||
'message': 'XFA current-sample validation reported failures.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'failure_codes': failures[:10],
|
||||
})
|
||||
return blocking
|
||||
|
||||
|
||||
def _overlap_summary_from_run(run: ShippingOrderDocumentProfileValidationRun | None) -> dict[str, Any] | None:
|
||||
"""从 cross_template_overlap 运行提取唯一性摘要与冲突卡片。"""
|
||||
if run is None:
|
||||
return None
|
||||
snapshot = dict(run.result_snapshot_json or {})
|
||||
summary = dict(run.summary_json or {})
|
||||
return {
|
||||
'run_id': run.id,
|
||||
'status': run.status,
|
||||
'definition_checksum': run.definition_checksum,
|
||||
'matcher_policy_version': summary.get('matcher_policy_version'),
|
||||
'self_unique_hit_rate_training': summary.get('self_unique_hit_rate_training'),
|
||||
'self_unique_hit_rate_blind': summary.get('self_unique_hit_rate_blind'),
|
||||
'false_hit_other_count': summary.get('false_hit_other_count'),
|
||||
'reverse_false_hit_count': summary.get('reverse_false_hit_count'),
|
||||
'reverse_ambiguous_count': summary.get('reverse_ambiguous_count'),
|
||||
'reverse_skipped_profile_count': summary.get('reverse_skipped_profile_count'),
|
||||
'ambiguous_count': summary.get('ambiguous_count'),
|
||||
'min_evidence_coverage': summary.get('min_evidence_coverage'),
|
||||
'min_margin': summary.get('min_margin'),
|
||||
'parse_validation_failed_count': summary.get('parse_validation_failed_count'),
|
||||
'sample_role_pollution': summary.get('sample_role_pollution'),
|
||||
'thresholds': summary.get('thresholds') if isinstance(summary.get('thresholds'), dict) else None,
|
||||
'conflict_profiles': list(snapshot.get('conflict_profiles') or []),
|
||||
}
|
||||
|
||||
|
||||
def _payload(row: ShippingOrderDocumentProfilePublishCheckReport, profile: ShippingOrderDocumentProfile | None = None) -> dict[str, Any]:
|
||||
"""返回报告安全投影,不返回 PDF、盲测真值或原始审计详情。"""
|
||||
return {'id': row.id, 'report_no': row.report_no, 'profile_id': row.profile_id, 'revision_no': row.revision_no,
|
||||
'definition_checksum': row.definition_checksum, 'lock_version': row.lock_version, 'validation_run_id': row.validation_run_id,
|
||||
'status': row.status, 'expires_reason': row.expires_reason, 'semantic_diff': dict(row.semantic_diff_json or {}),
|
||||
'blocking_items': list(row.blocking_items_json or []), 'warning_items': list(row.warning_items_json or []),
|
||||
'confirmed_warning_keys': list(row.confirmed_warning_keys_json or []), 'operation_id': row.operation_id,
|
||||
'created_at': row.created_at.isoformat(), 'consumed_at': row.consumed_at.isoformat() if row.consumed_at else None}
|
||||
signature_run = db.session.get(ShippingOrderDocumentProfileValidationRun, int(row.matching_signature_run_id or 0)) if row.matching_signature_run_id else None
|
||||
overlap_run = db.session.get(ShippingOrderDocumentProfileValidationRun, int(row.overlap_validation_run_id or 0)) if row.overlap_validation_run_id else None
|
||||
revision = None
|
||||
signature_status = None
|
||||
if profile is not None:
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=profile.id, definition_checksum=profile.structure_fingerprint,
|
||||
).order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc()).first()
|
||||
if revision is not None:
|
||||
signature_status = _signature_status(profile, revision)
|
||||
overlap_stale = (
|
||||
overlap_run is None
|
||||
or overlap_run.profile_id != row.profile_id
|
||||
or overlap_run.run_type != 'cross_template_overlap'
|
||||
or overlap_run.definition_checksum != row.definition_checksum
|
||||
or overlap_run.status != 'passed'
|
||||
)
|
||||
overlap_summary = _overlap_summary_from_run(overlap_run)
|
||||
if overlap_summary is not None and overlap_stale:
|
||||
overlap_summary = {**overlap_summary, 'status': 'stale'}
|
||||
return {
|
||||
'id': row.id,
|
||||
'report_no': row.report_no,
|
||||
'profile_id': row.profile_id,
|
||||
'revision_no': row.revision_no,
|
||||
'definition_checksum': row.definition_checksum,
|
||||
'lock_version': row.lock_version,
|
||||
'validation_run_id': row.validation_run_id,
|
||||
'matching_signature_run_id': row.matching_signature_run_id,
|
||||
'matching_signature_checksum': row.matching_signature_checksum,
|
||||
'overlap_validation_run_id': row.overlap_validation_run_id,
|
||||
'matcher_policy_version': row.matcher_policy_version,
|
||||
'status': row.status,
|
||||
'expires_reason': row.expires_reason,
|
||||
'semantic_diff': dict(row.semantic_diff_json or {}),
|
||||
'blocking_items': list(row.blocking_items_json or []),
|
||||
'warning_items': list(row.warning_items_json or []),
|
||||
'confirmed_warning_keys': list(row.confirmed_warning_keys_json or []),
|
||||
'operation_id': row.operation_id,
|
||||
'created_at': row.created_at.isoformat(),
|
||||
'consumed_at': row.consumed_at.isoformat() if row.consumed_at else None,
|
||||
'layout_signature_status': signature_status if signature_status and signature_status.get('signature_kind') != 'xfa_structure_signature' else (
|
||||
None if signature_status and signature_status.get('signature_kind') == 'xfa_structure_signature' else signature_status
|
||||
),
|
||||
'xfa_structure_signature_status': signature_status if signature_status and signature_status.get('signature_kind') == 'xfa_structure_signature' else None,
|
||||
'layout_signature_summary': dict(signature_run.summary_json or {}) if signature_run is not None and signature_run.run_type == 'layout_signature' else None,
|
||||
'xfa_structure_signature_summary': dict(signature_run.summary_json or {}) if signature_run is not None and signature_run.run_type == 'xfa_structure_signature' else None,
|
||||
'overlap_summary': overlap_summary,
|
||||
'conflict_profiles': list((overlap_run.result_snapshot_json or {}).get('conflict_profiles') or []) if overlap_run is not None else [],
|
||||
'template_mode': profile.template_mode if profile is not None else None,
|
||||
}
|
||||
|
||||
|
||||
def _invalidate_if_changed(row: ShippingOrderDocumentProfilePublishCheckReport, profile: ShippingOrderDocumentProfile) -> bool:
|
||||
"""将草稿有效变化显式固化为报告失效,避免旧报告被误消费。"""
|
||||
if row.status == 'valid' and (row.definition_checksum != profile.structure_fingerprint or row.lock_version != profile.lock_version):
|
||||
row.status, row.expires_reason = 'invalidated', 'draft_changed'
|
||||
profile_service._audit(profile_id=profile.id, event_type='publish_check_invalidated', actor_id=None, operation_id=row.operation_id,
|
||||
revision_no=row.revision_no, detail={'report_id': row.id, 'reason': 'draft_changed'})
|
||||
"""将草稿有效变化或签名/重叠引用漂移显式固化为报告失效。"""
|
||||
stale_signature = (
|
||||
row.matching_signature_run_id != profile.matching_signature_run_id
|
||||
or row.matching_signature_checksum != profile.matching_signature_checksum
|
||||
)
|
||||
overlap_run = db.session.get(ShippingOrderDocumentProfileValidationRun, int(row.overlap_validation_run_id or 0)) if row.overlap_validation_run_id else None
|
||||
stale_overlap = (
|
||||
overlap_run is None
|
||||
or overlap_run.definition_checksum != row.definition_checksum
|
||||
or overlap_run.status != 'passed'
|
||||
)
|
||||
if row.status == 'valid' and (
|
||||
row.definition_checksum != profile.structure_fingerprint
|
||||
or row.lock_version != profile.lock_version
|
||||
or stale_signature
|
||||
or stale_overlap
|
||||
):
|
||||
reason = 'draft_changed'
|
||||
if stale_signature and row.definition_checksum == profile.structure_fingerprint:
|
||||
reason = 'signature_changed'
|
||||
elif stale_overlap and row.definition_checksum == profile.structure_fingerprint:
|
||||
reason = 'overlap_validation_stale'
|
||||
row.status, row.expires_reason = 'invalidated', reason
|
||||
profile_service._audit(
|
||||
profile_id=profile.id, event_type='publish_check_invalidated', actor_id=None, operation_id=row.operation_id,
|
||||
revision_no=row.revision_no, detail={'report_id': row.id, 'reason': reason},
|
||||
)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _resolve_validation_run(profile: ShippingOrderDocumentProfile, revision: ShippingOrderDocumentProfileDraftRevision, run_id: Any) -> ShippingOrderDocumentProfileValidationRun | None:
|
||||
"""读取并校验 current_sample 通过运行。"""
|
||||
validation = db.session.get(ShippingOrderDocumentProfileValidationRun, int(run_id)) if str(run_id or '').isdigit() else None
|
||||
if (
|
||||
validation is None
|
||||
or validation.profile_id != profile.id
|
||||
or validation.run_type != 'current_sample'
|
||||
or validation.status != 'passed'
|
||||
or validation.definition_checksum != revision.definition_checksum
|
||||
):
|
||||
return None
|
||||
return validation
|
||||
|
||||
|
||||
def _resolve_overlap_run(
|
||||
profile: ShippingOrderDocumentProfile,
|
||||
revision: ShippingOrderDocumentProfileDraftRevision,
|
||||
run_id: Any,
|
||||
) -> ShippingOrderDocumentProfileValidationRun | None:
|
||||
"""读取并校验 cross_template_overlap 通过运行。"""
|
||||
overlap = db.session.get(ShippingOrderDocumentProfileValidationRun, int(run_id)) if str(run_id or '').isdigit() else None
|
||||
if (
|
||||
overlap is None
|
||||
or overlap.profile_id != profile.id
|
||||
or overlap.run_type != 'cross_template_overlap'
|
||||
or overlap.status != 'passed'
|
||||
or overlap.definition_checksum != revision.definition_checksum
|
||||
):
|
||||
return None
|
||||
return overlap
|
||||
|
||||
|
||||
def _blocking_from_overlap(summary: dict[str, Any] | None, overlap_run: ShippingOrderDocumentProfileValidationRun | None, revision: ShippingOrderDocumentProfileDraftRevision) -> list[dict[str, Any]]:
|
||||
"""将重叠验证摘要转为发布阻断项。"""
|
||||
blocking: list[dict[str, Any]] = []
|
||||
if overlap_run is None:
|
||||
blocking.append({'key': 'overlap_validation_required', 'message': 'Cross-template overlap validation is required.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
return blocking
|
||||
if overlap_run.definition_checksum != revision.definition_checksum or overlap_run.status != 'passed':
|
||||
blocking.append({'key': 'overlap_validation_stale', 'message': 'Cross-template overlap validation is stale.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
return blocking
|
||||
summary = summary or dict(overlap_run.summary_json or {})
|
||||
snapshot = dict(overlap_run.result_snapshot_json or {})
|
||||
if float(summary.get('self_unique_hit_rate_training') or 0) < 1.0:
|
||||
blocking.append({'key': 'self_match_not_unique', 'message': 'Training samples must uniquely match the current draft.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
if int(summary.get('blind_sample_count') or 0) > 0 and float(summary.get('self_unique_hit_rate_blind') or 0) < 1.0:
|
||||
blocking.append({'key': 'self_match_not_unique_blind', 'message': 'Blind-test samples must uniquely match the current draft.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
if int(summary.get('false_hit_other_count') or 0) > 0 or int(summary.get('reverse_false_hit_count') or 0) > 0:
|
||||
blocking.append({'key': 'cross_template_false_hit', 'message': 'Cross-template false hits were detected.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
if int(summary.get('reverse_ambiguous_count') or 0) > 0:
|
||||
blocking.append({'key': 'cross_template_reverse_ambiguous', 'message': 'Published-template samples became ambiguous.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
if int(summary.get('reverse_skipped_profile_count') or 0) > 0:
|
||||
blocking.append({'key': 'cross_template_reverse_evidence_missing', 'message': 'Every published-template representative sample requires usable layout evidence.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
if int(summary.get('ambiguous_count') or 0) > 0:
|
||||
blocking.append({'key': 'cross_template_ambiguous', 'message': 'Cross-template matching is ambiguous.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
if int(summary.get('parse_validation_failed_count') or 0) > 0:
|
||||
blocking.append({'key': 'cross_template_parse_failed', 'message': 'Parse validation failed during overlap checks.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
thresholds = summary.get('thresholds') if isinstance(summary.get('thresholds'), dict) else {}
|
||||
if float(summary.get('min_evidence_coverage') or 0) < float(thresholds.get('evidence_coverage_minimum') or 0.70):
|
||||
blocking.append({'key': 'cross_template_coverage_insufficient', 'message': 'Evidence coverage is below the required threshold.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
if float(summary.get('min_margin') or 0) < float(thresholds.get('minimum_margin') or 0.12):
|
||||
blocking.append({'key': 'cross_template_margin_insufficient', 'message': 'Match margin is below the required threshold.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
if summary.get('sample_role_pollution'):
|
||||
blocking.append({'key': 'sample_role_pollution', 'message': 'Training or annotation samples must not also be bound as blind-test samples.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
if snapshot.get('conflict_profiles'):
|
||||
blocking.append({
|
||||
'key': 'cross_template_conflict_profiles',
|
||||
'message': 'Conflicting published templates were detected.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED',
|
||||
'conflict_profiles': list(snapshot.get('conflict_profiles') or []),
|
||||
})
|
||||
return blocking
|
||||
|
||||
|
||||
def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None, browser_session_id: str | None, lease_token: str | None, operation_id: str) -> dict[str, Any]:
|
||||
"""生成冻结当前草稿和通过验证运行的发布检查报告;阻断项只可修复不能确认绕过。"""
|
||||
"""
|
||||
生成冻结当前草稿、签名引用与重叠验证的发布检查报告;阻断项只可修复不能确认绕过。
|
||||
|
||||
核心逻辑:校验 current_sample → 解析/自动生成 layout_signature 或 xfa_structure_signature →
|
||||
解析/自动运行 cross_template_overlap → 汇总阻断项并持久化报告引用。
|
||||
"""
|
||||
profile = _profile(profile_id)
|
||||
lease_service.require_active_lease(profile.id, actor_id=actor_id, browser_session_id=browser_session_id, lease_token=lease_token)
|
||||
op = str(operation_id or secrets.token_hex(16))
|
||||
@@ -74,36 +523,122 @@ def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None
|
||||
if existing is not None:
|
||||
_invalidate_if_changed(existing, profile)
|
||||
db.session.commit()
|
||||
return _payload(existing)
|
||||
return _payload(existing, profile)
|
||||
revision = _current_revision(profile)
|
||||
run_id = data.get('validation_run_id')
|
||||
validation = db.session.get(ShippingOrderDocumentProfileValidationRun, int(run_id)) if str(run_id or '').isdigit() else None
|
||||
validation = _resolve_validation_run(profile, revision, data.get('validation_run_id'))
|
||||
blocking: list[dict[str, Any]] = []
|
||||
if validation is None or validation.profile_id != profile.id or validation.run_type != 'current_sample' or validation.status != 'passed' or validation.definition_checksum != revision.definition_checksum:
|
||||
if validation is None:
|
||||
blocking.append({'key': 'current_validation_required', 'message': 'A passing validation run for the current draft is required.'})
|
||||
|
||||
is_xfa = _is_xfa_profile(profile)
|
||||
if is_xfa:
|
||||
blocking.extend(_blocking_xfa_definition(profile, validation))
|
||||
|
||||
signature_run: ShippingOrderDocumentProfileValidationRun | None = None
|
||||
expected_signature_type = 'xfa_structure_signature' if is_xfa else 'layout_signature'
|
||||
try:
|
||||
if str(data.get('matching_signature_run_id') or '').isdigit():
|
||||
candidate = db.session.get(ShippingOrderDocumentProfileValidationRun, int(data['matching_signature_run_id']))
|
||||
if (
|
||||
candidate is not None
|
||||
and candidate.profile_id == profile.id
|
||||
and candidate.run_type == expected_signature_type
|
||||
and candidate.status == 'passed'
|
||||
and candidate.definition_checksum == revision.definition_checksum
|
||||
):
|
||||
signature_run = candidate
|
||||
if signature_run is None:
|
||||
if is_xfa:
|
||||
signature_run = validation_service._resolve_xfa_structure_signature_run(
|
||||
profile, revision, auto_run=True,
|
||||
actor_id=actor_id, browser_session_id=browser_session_id, lease_token=lease_token, operation_id=op,
|
||||
)
|
||||
else:
|
||||
signature_run = validation_service._resolve_layout_signature_run(
|
||||
profile, revision, auto_run=True,
|
||||
actor_id=actor_id, browser_session_id=browser_session_id, lease_token=lease_token, operation_id=op,
|
||||
)
|
||||
db.session.refresh(profile)
|
||||
except ValidationError as exc:
|
||||
code = getattr(exc, 'code', 'SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_REQUIRED')
|
||||
key = 'signature_stale' if code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE' else 'signature_required'
|
||||
blocking.append({'key': key, 'message': str(exc), 'code': code})
|
||||
|
||||
overlap_run: ShippingOrderDocumentProfileValidationRun | None = None
|
||||
overlap_summary: dict[str, Any] | None = None
|
||||
if signature_run is not None:
|
||||
overlap_run = _resolve_overlap_run(profile, revision, data.get('overlap_validation_run_id'))
|
||||
if overlap_run is None:
|
||||
try:
|
||||
overlap_payload = validation_service.run_cross_template_overlap(
|
||||
profile.id,
|
||||
data={'auto_generate_signature': False},
|
||||
actor_id=actor_id,
|
||||
browser_session_id=browser_session_id,
|
||||
lease_token=lease_token,
|
||||
operation_id=f'{op}-overlap',
|
||||
auto_generate_signature=False,
|
||||
)
|
||||
overlap_run = db.session.get(ShippingOrderDocumentProfileValidationRun, int(overlap_payload['id']))
|
||||
except ValidationError as exc:
|
||||
blocking.append({'key': 'overlap_validation_failed', 'message': str(exc), 'code': getattr(exc, 'code', 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED')})
|
||||
if overlap_run is not None:
|
||||
overlap_summary = _overlap_summary_from_run(overlap_run)
|
||||
blocking.extend(_blocking_from_overlap(overlap_summary, overlap_run, revision))
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.document_profile_quality_service import assert_profile_publishable
|
||||
assert_profile_publishable(profile)
|
||||
except Exception as exc:
|
||||
blocking.append({'key': getattr(exc, 'code', 'publish_prerequisite_failed'), 'message': 'Blind-test or profile publish prerequisites are not satisfied.'})
|
||||
|
||||
previous = ShippingOrderDocumentProfile.query.filter_by(profile_code=profile.profile_code, status='published').first()
|
||||
semantic_diff = diff_service.get_profile_diff(profile.id, against_profile_id=previous.id if previous else None)
|
||||
warnings = [{'key': 'semantic_diff_review', 'message': 'Semantic changes must be reviewed before publication.'}] if semantic_diff.get('changes') else []
|
||||
row = ShippingOrderDocumentProfilePublishCheckReport(
|
||||
report_no=f'OPPC-{secrets.token_hex(8).upper()}', profile_id=profile.id, revision_no=revision.revision_no,
|
||||
definition_checksum=revision.definition_checksum, lock_version=profile.lock_version, validation_run_id=validation.id if validation else None,
|
||||
matching_signature_run_id=signature_run.id if signature_run is not None else profile.matching_signature_run_id,
|
||||
matching_signature_checksum=profile.matching_signature_checksum,
|
||||
overlap_validation_run_id=overlap_run.id if overlap_run is not None else None,
|
||||
matcher_policy_version=(
|
||||
(overlap_summary or {}).get('matcher_policy_version')
|
||||
or (XFA_STRUCTURE_SIGNATURE_ID if is_xfa else MATCHER_POLICY_ID)
|
||||
),
|
||||
base_published_profile_id=previous.id if previous else None, semantic_diff_json=semantic_diff, blocking_items_json=blocking,
|
||||
warning_items_json=warnings, confirmed_warning_keys_json=[], status='valid', operation_id=op, actor_id=actor_id,
|
||||
)
|
||||
db.session.add(row)
|
||||
profile_service._audit(profile_id=profile.id, event_type='publish_check_created', actor_id=actor_id, operation_id=op, revision_no=revision.revision_no,
|
||||
detail={'report_no': row.report_no, 'validation_run_id': row.validation_run_id, 'blocking_count': len(blocking), 'warning_count': len(warnings)})
|
||||
_append_publish_check_ledger_event(
|
||||
profile=profile, event_type='profile_publish_check_created', actor_id=actor_id,
|
||||
operation_id=op, result='success' if not blocking else 'rejected',
|
||||
before={'profile_code': profile.profile_code, 'profile_version': profile.version, 'profile_checksum': profile.structure_fingerprint, 'status': profile.status},
|
||||
after={
|
||||
'profile_code': profile.profile_code, 'profile_version': profile.version,
|
||||
'profile_checksum': profile.structure_fingerprint, 'status': row.status,
|
||||
'matching_signature_run_id': row.matching_signature_run_id,
|
||||
'overlap_validation_run_id': row.overlap_validation_run_id,
|
||||
},
|
||||
metadata={'report_no': row.report_no, 'blocking_count': len(blocking), 'warning_count': len(warnings)},
|
||||
)
|
||||
profile_service._audit(
|
||||
profile_id=profile.id, event_type='publish_check_created', actor_id=actor_id, operation_id=op, revision_no=revision.revision_no,
|
||||
detail={
|
||||
'report_no': row.report_no,
|
||||
'validation_run_id': row.validation_run_id,
|
||||
'matching_signature_run_id': row.matching_signature_run_id,
|
||||
'overlap_validation_run_id': row.overlap_validation_run_id,
|
||||
'blocking_count': len(blocking),
|
||||
'warning_count': len(warnings),
|
||||
'template_mode': 'xfa_dataset' if is_xfa else 'coordinate',
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return _payload(row)
|
||||
return _payload(row, profile)
|
||||
|
||||
|
||||
def get_report(profile_id: int, report_no: str) -> dict[str, Any]:
|
||||
"""读取报告并在发现草稿变化时立刻持久化失效状态。"""
|
||||
"""读取报告并在发现草稿或签名/重叠漂移时立刻持久化失效状态。"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
@@ -112,7 +647,7 @@ def get_report(profile_id: int, report_no: str) -> dict[str, Any]:
|
||||
raise NotFoundError('Publish check report not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID')
|
||||
if profile.status == 'draft' and _invalidate_if_changed(row, profile):
|
||||
db.session.commit()
|
||||
return _payload(row)
|
||||
return _payload(row, profile)
|
||||
|
||||
|
||||
def consume_report(profile_id: int, report_no: str, *, data: dict[str, Any], actor_id: int | None, browser_session_id: str | None, lease_token: str | None, operation_id: str) -> dict[str, Any]:
|
||||
@@ -133,6 +668,14 @@ 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:
|
||||
@@ -140,6 +683,13 @@ def consume_report(profile_id: int, report_no: str, *, data: dict[str, Any], act
|
||||
try:
|
||||
published = profile_service.publish(profile.id, actor_id=actor_id, expected_lock_version=row.lock_version, commit=False)
|
||||
row.confirmed_warning_keys_json, row.status, row.consumed_at = sorted(confirmed), 'consumed', datetime.utcnow()
|
||||
_append_publish_check_ledger_event(
|
||||
profile=profile, event_type='profile_publish_check_consumed', actor_id=actor_id,
|
||||
operation_id=str(operation_id or row.operation_id), result='success',
|
||||
before={'profile_code': profile.profile_code, 'profile_version': profile.version, 'profile_checksum': profile.structure_fingerprint, 'status': 'draft', 'lock_version': row.lock_version},
|
||||
after={'profile_code': profile.profile_code, 'profile_version': profile.version, 'profile_checksum': profile.structure_fingerprint, 'status': 'published', 'lock_version': profile.lock_version},
|
||||
metadata={'report_no': row.report_no, 'confirmed_warning_count': len(confirmed)},
|
||||
)
|
||||
profile_service._audit(profile_id=profile.id, event_type='publish_check_consumed', actor_id=actor_id,
|
||||
operation_id=str(operation_id or row.operation_id), revision_no=row.revision_no, detail={'report_no': row.report_no})
|
||||
lease = ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile.id).one_or_none()
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_revision_service.py
|
||||
|
||||
用途:提供订单模板草稿 Revision 的查询与恢复。
|
||||
用途:提供订单模板草稿 Revision 的查询与恢复(coordinate / xfa_dataset 共用)。
|
||||
依赖:Profile、DraftRevision、Profile 保存服务和编辑租约服务。
|
||||
逻辑:恢复只读取旧快照并作为新的有效保存写入,历史 Revision 绝不覆盖或删除。
|
||||
逻辑:恢复只读取旧快照并作为新的有效保存写入,历史 Revision 绝不覆盖或删除;
|
||||
XFA 快照的 definition checksum 与语义摘要由 save_draft / change_summary_json 承载。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -17,11 +17,11 @@ from sqlalchemy import and_, func, or_
|
||||
from app.core.errors import NotFoundError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderRouteDecision,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderProcessingUnit,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
@@ -36,7 +36,7 @@ def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
return row
|
||||
|
||||
|
||||
def _mask_document_label(document: ShippingNoticeDocument | None, *, document_id: int | None) -> str:
|
||||
def _mask_document_label(document: ShippingOrderDocument | None, *, document_id: int | None) -> str:
|
||||
"""返回适合管理员列表展示的脱敏文档名称,避免把原始文件名完整暴露到列表。"""
|
||||
name = str(
|
||||
(getattr(document, 'filename', None) or getattr(document, 'attachment_key', None) or '').strip()
|
||||
@@ -51,7 +51,7 @@ def _mask_document_label(document: ShippingNoticeDocument | None, *, document_id
|
||||
return f'{stem[:2]}***{stem[-2:]}{suffix}'
|
||||
|
||||
|
||||
def _reason_codes(route: ShippingOrderExtractionRouteDecision, unit: ShippingOrderExtractionUnit) -> list[str]:
|
||||
def _reason_codes(route: ShippingOrderRouteDecision, unit: ShippingOrderProcessingUnit) -> list[str]:
|
||||
"""合并分流与执行阶段的失败/降级原因,按首次出现顺序去重。"""
|
||||
values = [
|
||||
*(route.fallback_reason_codes_json or []),
|
||||
@@ -113,52 +113,52 @@ def list_profile_usages(
|
||||
profile = _profile(profile_id)
|
||||
latest_subquery = (
|
||||
db.session.query(
|
||||
ShippingOrderExtractionRouteDecision.unit_id.label('unit_id'),
|
||||
func.max(ShippingOrderExtractionRouteDecision.id).label('route_decision_id'),
|
||||
ShippingOrderRouteDecision.unit_id.label('unit_id'),
|
||||
func.max(ShippingOrderRouteDecision.id).label('route_decision_id'),
|
||||
)
|
||||
.group_by(ShippingOrderExtractionRouteDecision.unit_id)
|
||||
.group_by(ShippingOrderRouteDecision.unit_id)
|
||||
.subquery()
|
||||
)
|
||||
|
||||
snapshot_match = and_(
|
||||
ShippingOrderExtractionRouteDecision.selected_profile_id.is_(None),
|
||||
ShippingOrderExtractionRouteDecision.selected_profile_code == profile.profile_code,
|
||||
ShippingOrderExtractionRouteDecision.selected_profile_version == profile.version,
|
||||
ShippingOrderExtractionRouteDecision.selected_profile_checksum == profile.checksum,
|
||||
ShippingOrderRouteDecision.selected_profile_id.is_(None),
|
||||
ShippingOrderRouteDecision.selected_profile_code == profile.profile_code,
|
||||
ShippingOrderRouteDecision.selected_profile_version == profile.version,
|
||||
ShippingOrderRouteDecision.selected_profile_checksum == profile.checksum,
|
||||
)
|
||||
direct_match = ShippingOrderExtractionRouteDecision.selected_profile_id == profile.id
|
||||
direct_match = ShippingOrderRouteDecision.selected_profile_id == profile.id
|
||||
|
||||
query = (
|
||||
db.session.query(
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingNoticeDocument,
|
||||
ShippingOrderRouteDecision,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderProcessingUnit,
|
||||
ShippingOrderDocument,
|
||||
)
|
||||
.join(
|
||||
latest_subquery,
|
||||
ShippingOrderExtractionRouteDecision.id == latest_subquery.c.route_decision_id,
|
||||
ShippingOrderRouteDecision.id == latest_subquery.c.route_decision_id,
|
||||
)
|
||||
.join(
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRun.id == ShippingOrderExtractionRouteDecision.run_id,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderProcessingRun.id == ShippingOrderRouteDecision.run_id,
|
||||
)
|
||||
.join(
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderExtractionUnit.id == ShippingOrderExtractionRouteDecision.unit_id,
|
||||
ShippingOrderProcessingUnit,
|
||||
ShippingOrderProcessingUnit.id == ShippingOrderRouteDecision.unit_id,
|
||||
)
|
||||
.outerjoin(
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeDocument.id == ShippingOrderExtractionUnit.document_id,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocument.id == ShippingOrderProcessingUnit.document_id,
|
||||
)
|
||||
.filter(or_(direct_match, snapshot_match))
|
||||
)
|
||||
if before_id is not None:
|
||||
query = query.filter(ShippingOrderExtractionRouteDecision.id < int(before_id))
|
||||
query = query.filter(ShippingOrderRouteDecision.id < int(before_id))
|
||||
|
||||
rows = (
|
||||
query
|
||||
.order_by(ShippingOrderExtractionRouteDecision.id.desc())
|
||||
.order_by(ShippingOrderRouteDecision.id.desc())
|
||||
.limit(int(limit) + 1)
|
||||
.all()
|
||||
)
|
||||
@@ -189,7 +189,7 @@ def list_profile_usages(
|
||||
'reason_codes': _reason_codes(route, unit),
|
||||
'created_at': route.created_at.isoformat() if route.created_at else None,
|
||||
'diagnostic_entry': {
|
||||
'route_name': 'AdminShippingOrderExtractionRuns',
|
||||
'route_name': 'AdminShippingOrderProcessingRuns',
|
||||
'run_no': str(run.run_no),
|
||||
},
|
||||
})
|
||||
|
||||
+1518
-48
File diff suppressed because it is too large.
Load diff
@@ -26,8 +26,22 @@ def _profile_event_time(profile: ShippingOrderDocumentProfile) -> datetime:
|
||||
return profile.retired_at or profile.published_at or profile.updated_at or profile.created_at
|
||||
|
||||
|
||||
def _definition_scale_summary(definition: dict[str, Any]) -> dict[str, int]:
|
||||
def _definition_scale_summary(definition: dict[str, Any]) -> dict[str, Any]:
|
||||
"""提取配置规模统计,避免版本列表直接返回整份 definition。"""
|
||||
if str(definition.get('template_mode') or '') == 'xfa_dataset':
|
||||
source = definition.get('source_contract') if isinstance(definition.get('source_contract'), dict) else {}
|
||||
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
return {
|
||||
'template_mode': 'xfa_dataset',
|
||||
'header_mapping_count': len(definition.get('header_mappings') or []),
|
||||
'line_mapping_count': len(line_mapping.get('fields') or []),
|
||||
'mirror_collection_count': len(source.get('mirror_collection_paths') or []),
|
||||
'table_region_count': 0,
|
||||
'header_layout_count': 0,
|
||||
'line_layout_count': 0,
|
||||
'order_field_layout_count': len(definition.get('header_mappings') or []),
|
||||
'draft_unbound_order_field_layout_count': 0,
|
||||
}
|
||||
table_regions = [
|
||||
item for item in (definition.get('table_regions') or [])
|
||||
if isinstance(item, dict)
|
||||
@@ -41,6 +55,23 @@ def _definition_scale_summary(definition: dict[str, Any]) -> dict[str, int]:
|
||||
}
|
||||
|
||||
|
||||
def _xfa_structure_identity_summary(definition: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""返回版本详情允许展示的 XFA 结构身份摘要(无明文路径值)。"""
|
||||
if str(definition.get('template_mode') or '') != 'xfa_dataset':
|
||||
return None
|
||||
source = definition.get('source_contract') if isinstance(definition.get('source_contract'), dict) else {}
|
||||
return {
|
||||
'template_packet_checksum': source.get('template_packet_checksum'),
|
||||
'dataset_structure_fingerprint': source.get('dataset_structure_fingerprint'),
|
||||
'has_authoritative_collection': bool(source.get('authoritative_line_collection_path')),
|
||||
'mirror_collection_count': len(source.get('mirror_collection_paths') or []),
|
||||
'header_mapping_count': len(definition.get('header_mappings') or []),
|
||||
'line_mapping_count': len(
|
||||
((definition.get('line_mapping') or {}) if isinstance(definition.get('line_mapping'), dict) else {}).get('fields') or []
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _version_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""返回模板族版本列表用的轻量摘要。"""
|
||||
safe = profile_service.payload(profile)
|
||||
@@ -186,18 +217,26 @@ def get_profile_detail(profile_id: int) -> dict[str, Any]:
|
||||
if profile is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
safe = profile_service.payload(profile)
|
||||
return {
|
||||
definition = dict(profile.definition_json or {})
|
||||
payload = {
|
||||
**safe,
|
||||
'schema_summary': {
|
||||
'id': safe['schema_version_id'],
|
||||
'version': safe.get('schema_version'),
|
||||
'checksum': safe.get('schema_checksum'),
|
||||
},
|
||||
'definition_stats': _definition_scale_summary(dict(profile.definition_json or {})),
|
||||
'definition_stats': _definition_scale_summary(definition),
|
||||
'xfa_structure_identity': _xfa_structure_identity_summary(definition),
|
||||
'sample_summary': _sample_summary(profile),
|
||||
'test_summary': _test_summary(profile),
|
||||
'source_version': _source_version_summary(profile),
|
||||
}
|
||||
if str(definition.get('template_mode') or profile.template_mode or '') == 'xfa_dataset':
|
||||
from app.services.shipping_notice.order_document_profile_preview_service import (
|
||||
build_xfa_readonly_mapping_evidence,
|
||||
)
|
||||
payload['xfa_readonly_mapping'] = build_xfa_readonly_mapping_evidence(profile)
|
||||
return payload
|
||||
|
||||
|
||||
def get_profile_detail_by_family_version(profile_code: str, version: int) -> dict[str, Any]:
|
||||
|
||||
@@ -2,12 +2,13 @@
|
||||
backend/app/services/shipping_notice/order_extraction.py
|
||||
|
||||
用途:持久化后台订单抽取 Run 的结构化结果,完成校验、判重与审计,并收敛至 STP 自动建单。
|
||||
依赖:ChatSession、ShippingNoticeIntake/Document/Candidate、动态 Schema、Review Case STP 建单、
|
||||
process_gate Finding 归属(Candidate 冲突只投影最终 blocked_fields)。
|
||||
依赖:ChatSession、ShippingOrderIntake/Document/Candidate、动态 Schema、Review Case STP 建单、
|
||||
process_gate Finding 归属、order_task_service(Candidate 形成后双写 OT)。
|
||||
逻辑:Worker 校验 Run 冻结快照后提交 orders[];HXOPS 逐订单落 Candidate,
|
||||
仅模板/通用确定性验收标记可自动接受;权威自动建单入口为 maybe_stp_auto_create_for_run,
|
||||
不再并行调用 Candidate 旧自动冻结建单路径;
|
||||
派生前 missing Decision 不得进入 Candidate 冲突;诊断 Finding 不进入用户阻断。
|
||||
Candidate flush 后才 upsert/重识别换绑 OT;派生前 missing Decision 不得进入 Candidate 冲突;
|
||||
诊断 Finding 不进入用户阻断。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,6 +16,7 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
@@ -25,10 +27,11 @@ from app.core.errors import ConflictError, ForbiddenError, NotFoundError, Valida
|
||||
from app.models import (
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderTask,
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
|
||||
@@ -50,21 +53,44 @@ from app.services.shipping_notice.context_fields.runtime import canonical_mail_c
|
||||
from app.services.shipping_notice.order_extraction_workflow import frozen_document_text_for_parser
|
||||
|
||||
|
||||
def _runtime_session_for_run(run: Any) -> ChatSession | SimpleNamespace:
|
||||
"""读取 Run 的 UI 会话;历史会话已清理时使用冻结身份继续持久化业务结果。
|
||||
|
||||
核心逻辑:ChatSession 仅承载界面导航上下文,不是 Candidate/Case 的业务外键;
|
||||
缺失时使用 Run 冻结的 user_id/conversation_id,后续仍由 Intake 归属和内容哈希校验。
|
||||
|
||||
Args:
|
||||
run: 已通过 Worker 领取与冻结快照校验的订单抽取 Run。
|
||||
|
||||
Returns:
|
||||
可提供 user_id/session_id 的现存 ChatSession 或只读运行期上下文。
|
||||
"""
|
||||
session = db.session.query(ChatSession).filter_by(session_id=str(run.conversation_id)).one_or_none()
|
||||
if session is not None:
|
||||
if int(session.user_id) != int(run.user_id):
|
||||
raise ForbiddenError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID',
|
||||
message='订单识别会话归属与冻结 Run 不一致',
|
||||
)
|
||||
return session
|
||||
return SimpleNamespace(user_id=int(run.user_id), session_id=str(run.conversation_id))
|
||||
|
||||
|
||||
def _load_intakes(
|
||||
*,
|
||||
session: ChatSession,
|
||||
intake_nos: list[str],
|
||||
lock: bool,
|
||||
allow_consumed: bool = False,
|
||||
) -> list[ShippingNoticeIntake]:
|
||||
) -> list[ShippingOrderIntake]:
|
||||
"""按会话用户加载并可选锁定 Intake;提交重放可读取已消费记录。"""
|
||||
query = db.session.query(ShippingNoticeIntake).filter(
|
||||
ShippingNoticeIntake.user_id == int(session.user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(intake_nos),
|
||||
query = db.session.query(ShippingOrderIntake).filter(
|
||||
ShippingOrderIntake.user_id == int(session.user_id),
|
||||
ShippingOrderIntake.intake_no.in_(intake_nos),
|
||||
)
|
||||
if lock:
|
||||
query = query.with_for_update()
|
||||
rows = query.order_by(ShippingNoticeIntake.id.asc()).all()
|
||||
rows = query.order_by(ShippingOrderIntake.id.asc()).all()
|
||||
if {row.intake_no for row in rows} != set(intake_nos):
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='部分发货通知接入记录不存在')
|
||||
for row in rows:
|
||||
@@ -86,17 +112,17 @@ def _load_intakes(
|
||||
return rows
|
||||
|
||||
|
||||
def _load_documents(intakes: list[ShippingNoticeIntake], *, lock: bool) -> list[ShippingNoticeDocument]:
|
||||
def _load_documents(intakes: list[ShippingOrderIntake], *, lock: bool) -> list[ShippingOrderDocument]:
|
||||
"""加载本轮 Intake 的全部 Document,保持稳定排序供快照和 LLM输入复用。"""
|
||||
query = db.session.query(ShippingNoticeDocument).filter(
|
||||
ShippingNoticeDocument.intake_id.in_([int(row.id) for row in intakes])
|
||||
query = db.session.query(ShippingOrderDocument).filter(
|
||||
ShippingOrderDocument.intake_id.in_([int(row.id) for row in intakes])
|
||||
)
|
||||
if lock:
|
||||
query = query.with_for_update()
|
||||
return query.order_by(ShippingNoticeDocument.intake_id.asc(), ShippingNoticeDocument.id.asc()).all()
|
||||
return query.order_by(ShippingOrderDocument.intake_id.asc(), ShippingOrderDocument.id.asc()).all()
|
||||
|
||||
|
||||
def _order_extraction_submission(intake: ShippingNoticeIntake) -> dict[str, Any]:
|
||||
def _order_extraction_submission(intake: ShippingOrderIntake) -> dict[str, Any]:
|
||||
"""读取已持久化的订单抽取提交事实;非法结构统一视为空。"""
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
submission = structured.get('order_extraction_submission')
|
||||
@@ -105,7 +131,7 @@ def _order_extraction_submission(intake: ShippingNoticeIntake) -> dict[str, Any]
|
||||
|
||||
def _store_run_submission_result(
|
||||
*,
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
intakes: list[ShippingOrderIntake],
|
||||
snapshot_hash: str,
|
||||
request_id: str,
|
||||
result: dict[str, Any],
|
||||
@@ -231,8 +257,8 @@ def _resolve_automatic_acceptance(raw_order: dict[str, Any]) -> dict[str, str] |
|
||||
def persist_order_extraction_result(
|
||||
*,
|
||||
session: ChatSession,
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
documents: list[ShippingNoticeDocument],
|
||||
intakes: list[ShippingOrderIntake],
|
||||
documents: list[ShippingOrderDocument],
|
||||
current_snapshot: str,
|
||||
request_id: str,
|
||||
orders: list[dict[str, Any]],
|
||||
@@ -256,7 +282,7 @@ def persist_order_extraction_result(
|
||||
current_snapshot: 已与 Run 冻结输入核对一致的内容摘要。
|
||||
request_id: Run 编号,作为 Candidate/Submission 的服务端幂等围栏。
|
||||
orders: 固定模板解析器输出的结构化订单数组。
|
||||
run_id: ShippingOrderExtractionRun 主键;生产 Run 必须提供,领域单测可为空。
|
||||
run_id: ShippingOrderProcessingRun 主键;生产 Run 必须提供,领域单测可为空。
|
||||
schema_version_id: Run 冻结的 published Schema 版本。
|
||||
extraction_source: 固定为确定性解析来源,不接受用户输入。
|
||||
frozen_context_by_intake: Run 按 Intake 冻结的确定性上下文;后台 Run 必须提供。
|
||||
@@ -298,7 +324,6 @@ def persist_order_extraction_result(
|
||||
row.parse_status == 'consumed'
|
||||
and row.consumed_at is not None
|
||||
and row.consumed_task_id is None
|
||||
and row.consumed_batch_id is None
|
||||
for row in intakes
|
||||
)
|
||||
):
|
||||
@@ -308,12 +333,12 @@ def persist_order_extraction_result(
|
||||
)
|
||||
intake_by_no = {row.intake_no: row for row in intakes}
|
||||
document_by_id = {int(row.id): row for row in documents}
|
||||
documents_by_intake: dict[int, list[ShippingNoticeDocument]] = {}
|
||||
documents_by_intake: dict[int, list[ShippingOrderDocument]] = {}
|
||||
for document in documents:
|
||||
documents_by_intake.setdefault(int(document.intake_id), []).append(document)
|
||||
|
||||
class_threshold = float(current_app.config.get('SHIPPING_NOTICE_ORDER_CLASSIFICATION_CONFIDENCE') or 0.85)
|
||||
auto_candidates: list[ShippingNoticeCandidate] = []
|
||||
auto_candidates: list[ShippingOrderCandidate] = []
|
||||
pending: list[dict[str, Any]] = []
|
||||
non_shipping: list[dict[str, Any]] = []
|
||||
duplicate_results_by_intake: dict[int, list[dict[str, Any]]] = {}
|
||||
@@ -324,13 +349,13 @@ def persist_order_extraction_result(
|
||||
document_non_shipping_indexes: dict[int, list[int]] = {int(row.id): [] for row in documents}
|
||||
|
||||
# [STEP 1] 新 Run 先撤销旧版本候选的可消费资格;旧记录仍保留用于审计与重识别失败回退。
|
||||
current_candidates = db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.intake_id.in_([int(row.id) for row in intakes]),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
ShippingNoticeCandidate.is_current_version.is_(True),
|
||||
current_candidates = db.session.query(ShippingOrderCandidate).filter(
|
||||
ShippingOrderCandidate.intake_id.in_([int(row.id) for row in intakes]),
|
||||
ShippingOrderCandidate.consumed_task_id.is_(None),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
)
|
||||
if run_id is not None:
|
||||
current_candidates = current_candidates.filter(ShippingNoticeCandidate.order_extraction_run_id != int(run_id))
|
||||
current_candidates = current_candidates.filter(ShippingOrderCandidate.order_extraction_run_id != int(run_id))
|
||||
current_candidates.update({'selected': False, 'is_current_version': False}, synchronize_session=False)
|
||||
current_candidates.update({'selected': False}, synchronize_session=False)
|
||||
|
||||
@@ -406,7 +431,12 @@ def persist_order_extraction_result(
|
||||
)
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
blocking_conflicts.extend(layout_evidence_issues)
|
||||
# `layout_table_needs_review` 只表示表格坐标/版面质量不足,不是订单字段值冲突。
|
||||
# 该诊断保留在 Extraction.validation_result_json,禁止再复制到 Candidate 建单门禁。
|
||||
blocking_conflicts.extend([
|
||||
item for item in layout_evidence_issues
|
||||
if str(item.get('reason') or '') != 'layout_table_needs_review'
|
||||
])
|
||||
summary = {**dynamic['header'], 'lines': dynamic['lines']}
|
||||
# Bill-to 是业务归属客户原文;简称只保存在 customer_matches 主数据快照中。
|
||||
if summary.get('bill_to_customer'):
|
||||
@@ -426,7 +456,11 @@ def persist_order_extraction_result(
|
||||
'reason': item.get('reason_code') or 'dynamic_schema_required_or_evidence_gate',
|
||||
'owning_gate_code': (
|
||||
'field_conflict_resolution'
|
||||
if str(item.get('reason_code') or '') == 'cross_source_conflict'
|
||||
if str(item.get('reason_code') or '') in {
|
||||
'cross_source_conflict',
|
||||
'pdf_preferred_critical_conflict',
|
||||
'pdf_preferred',
|
||||
}
|
||||
else 'field_completeness'
|
||||
if str(item.get('reason_code') or '') in {'required_field_missing', 'evidence_missing'}
|
||||
and str(item.get('field_code') or '') in blocked_set
|
||||
@@ -485,7 +519,7 @@ def persist_order_extraction_result(
|
||||
candidate_key = _candidate_key(intake_no, raw_order, normalized, index)
|
||||
active_keys_by_intake[int(intake.id)].add(candidate_key)
|
||||
candidate = (
|
||||
db.session.query(ShippingNoticeCandidate)
|
||||
db.session.query(ShippingOrderCandidate)
|
||||
.filter_by(
|
||||
intake_id=int(intake.id),
|
||||
candidate_key=candidate_key,
|
||||
@@ -497,7 +531,7 @@ def persist_order_extraction_result(
|
||||
document_candidate_keys[int(document.id)].append(candidate_key)
|
||||
continue
|
||||
if candidate is None:
|
||||
candidate = ShippingNoticeCandidate(
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=generate_candidate_no(),
|
||||
intake_id=int(intake.id),
|
||||
primary_document_id=int(document.id),
|
||||
@@ -715,18 +749,28 @@ def persist_order_extraction_result(
|
||||
document.order_extraction_error_code = None
|
||||
document.order_extraction_error_message = None
|
||||
|
||||
# [STEP 3] 只清理同一 Run 回放中消失的候选;不同 Run 的旧版本不得删除。
|
||||
# [STEP 3] 只对本次 documents 作用域内消失的 Candidate 做版本失效。
|
||||
# Unit 增量提交仅带当前 PDF,禁止把同 Intake/Run 的兄弟 PDF Candidate
|
||||
# 误判为 stale;历史 Candidate 可能已被 Case/OT 引用,不得物理删除。
|
||||
scoped_document_ids = {int(document.id) for document in documents}
|
||||
for intake in intakes:
|
||||
active_keys = active_keys_by_intake[int(intake.id)]
|
||||
stale = db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
ShippingNoticeCandidate.extraction_source == extraction_source,
|
||||
ShippingNoticeCandidate.order_extraction_run_id == (int(run_id) if run_id is not None else None),
|
||||
stale = db.session.query(ShippingOrderCandidate).filter(
|
||||
ShippingOrderCandidate.intake_id == int(intake.id),
|
||||
ShippingOrderCandidate.primary_document_id.in_(tuple(scoped_document_ids)),
|
||||
ShippingOrderCandidate.consumed_task_id.is_(None),
|
||||
ShippingOrderCandidate.extraction_source == extraction_source,
|
||||
ShippingOrderCandidate.order_extraction_run_id == (int(run_id) if run_id is not None else None),
|
||||
)
|
||||
if active_keys:
|
||||
stale = stale.filter(ShippingNoticeCandidate.candidate_key.notin_(tuple(active_keys)))
|
||||
stale.delete(synchronize_session=False)
|
||||
stale = stale.filter(ShippingOrderCandidate.candidate_key.notin_(tuple(active_keys)))
|
||||
for candidate in stale.all():
|
||||
if candidate.is_current_version:
|
||||
candidate.selected_before_superseded = bool(candidate.selected)
|
||||
candidate.candidate_status_before_superseded = candidate.candidate_status
|
||||
candidate.selected = False
|
||||
candidate.candidate_status = 'expired'
|
||||
candidate.is_current_version = False
|
||||
aggregate = aggregate_intake_duplicate_from_candidates(
|
||||
intake,
|
||||
duplicate_results_by_intake.get(int(intake.id), []),
|
||||
@@ -742,6 +786,66 @@ def persist_order_extraction_result(
|
||||
intake.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
|
||||
# [BE-01 / BE-04] 仅在本轮已形成 Candidate 后创建/刷新 OT;一 Candidate 一 OT。
|
||||
if run_id is not None:
|
||||
from app.models import ShippingOrderProcessingRun
|
||||
from app.services.shipping_notice.order_task_service import (
|
||||
allocate_user_task_no_for_run,
|
||||
upsert_order_task_for_candidate_formation,
|
||||
)
|
||||
|
||||
run = db.session.get(ShippingOrderProcessingRun, int(run_id))
|
||||
current_candidates = (
|
||||
ShippingOrderCandidate.query.filter(
|
||||
ShippingOrderCandidate.order_extraction_run_id == int(run_id),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
)
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
if run is not None and current_candidates:
|
||||
# PDF 级复核重识别:Run.user_task_no 已是 Case 对应 OT(可能是兄弟号),
|
||||
# 禁止再按 index=0 当根号、给其他 Candidate 派生 -C{id}。
|
||||
marker = (getattr(run, 'input_snapshot_json', None) or {}).get('review_reparse')
|
||||
is_document_reparse = isinstance(marker, dict) and marker.get('document_id') is not None
|
||||
root_task_no = allocate_user_task_no_for_run(run)
|
||||
for index, candidate in enumerate(current_candidates):
|
||||
bound_task = ShippingOrderTask.query.filter_by(candidate_id=int(candidate.id)).one_or_none()
|
||||
if bound_task is not None:
|
||||
# Unit 重放/全量收口只刷新既有 Candidate 自己的 OT,禁止按当前
|
||||
# 列表 index 重算 task_no,否则历史人工确认会导致根 OT 被其它 Candidate 抢占。
|
||||
sibling_task_no = str(bound_task.task_no)
|
||||
else:
|
||||
sibling_task_no = (
|
||||
root_task_no
|
||||
if is_document_reparse or index == 0
|
||||
else f'{root_task_no}-C{int(candidate.id)}'
|
||||
)
|
||||
candidate_intake = (
|
||||
db.session.get(ShippingOrderIntake, int(candidate.intake_id))
|
||||
if candidate.intake_id
|
||||
else (intakes[0] if intakes else None)
|
||||
)
|
||||
upsert_order_task_for_candidate_formation(
|
||||
run,
|
||||
task_no=sibling_task_no,
|
||||
intake_id=int(candidate_intake.id) if candidate_intake is not None else None,
|
||||
candidate_id=int(candidate.id),
|
||||
submission_id=(
|
||||
getattr(candidate_intake, 'order_submission_id', None)
|
||||
if candidate_intake is not None
|
||||
else None
|
||||
),
|
||||
source_type=(
|
||||
str(getattr(candidate_intake, 'source_type', None) or '').strip() or None
|
||||
if candidate_intake is not None
|
||||
else None
|
||||
),
|
||||
stage='waiting_review'
|
||||
if str(getattr(run, 'status', None) or '') == 'review_required'
|
||||
else 'candidate_creating',
|
||||
)
|
||||
|
||||
auto_candidate_nos = [row.candidate_no for row in auto_candidates]
|
||||
create_result: dict[str, Any] | None = None
|
||||
if auto_candidate_nos:
|
||||
@@ -844,7 +948,7 @@ def submit_order_extraction_run_result(
|
||||
将后台 Workflow 输出提交到既有 HXOPS 裁决与持久化核心。
|
||||
|
||||
Args:
|
||||
run: `ShippingOrderExtractionRun`;必须包含冻结用户、会话、Intake 和 Schema。
|
||||
run: `ShippingOrderProcessingRun`;必须包含冻结用户、会话、Intake 和 Schema。
|
||||
orders: Workflow 输出的结构化订单数组;禁止包含 Provider 选择或用户身份。
|
||||
Returns:
|
||||
不含 Provider 配置或输入文档的安全业务摘要。
|
||||
@@ -875,14 +979,14 @@ def submit_order_extraction_run_result(
|
||||
}
|
||||
intake_nos = [str(item.get('intake_no') or '').strip().upper() for item in snapshot_intakes]
|
||||
intake_nos = [item for item in intake_nos if item]
|
||||
intakes = db.session.query(ShippingNoticeIntake).filter(
|
||||
ShippingNoticeIntake.user_id == int(run.user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(intake_nos),
|
||||
).order_by(ShippingNoticeIntake.intake_no.asc()).all()
|
||||
intakes = db.session.query(ShippingOrderIntake).filter(
|
||||
ShippingOrderIntake.user_id == int(run.user_id),
|
||||
ShippingOrderIntake.intake_no.in_(intake_nos),
|
||||
).order_by(ShippingOrderIntake.intake_no.asc()).all()
|
||||
if len(intakes) != len(intake_nos):
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='Run 输入 Intake 不完整')
|
||||
run_extractions = ShippingOrderExtraction.query.filter_by(run_id=int(run.id)).all()
|
||||
run_candidates = ShippingNoticeCandidate.query.filter_by(order_extraction_run_id=int(run.id)).all()
|
||||
run_candidates = ShippingOrderCandidate.query.filter_by(order_extraction_run_id=int(run.id)).all()
|
||||
if run_extractions and run_candidates and all(
|
||||
extraction.status in {'accepted', 'needs_review'}
|
||||
for extraction in run_extractions
|
||||
@@ -894,7 +998,7 @@ def submit_order_extraction_run_result(
|
||||
}
|
||||
task_nos = sorted({
|
||||
str(task.task_no)
|
||||
for task in ShippingTask.query.filter(ShippingTask.id.in_(consumed_task_ids)).all()
|
||||
for task in ShippingNotice.query.filter(ShippingNotice.id.in_(consumed_task_ids)).all()
|
||||
}) if consumed_task_ids else []
|
||||
pending = [candidate for candidate in run_candidates if candidate.consumed_task_id is None]
|
||||
result = {
|
||||
@@ -989,11 +1093,10 @@ def submit_order_extraction_run_result(
|
||||
intake.parse_status == 'consumed'
|
||||
and intake.consumed_at is not None
|
||||
and intake.consumed_task_id is None
|
||||
and intake.consumed_batch_id is None
|
||||
for intake in intakes
|
||||
)
|
||||
)
|
||||
session = db.session.query(ChatSession).filter_by(session_id=run.conversation_id).one()
|
||||
session = _runtime_session_for_run(run)
|
||||
current_intakes = _load_intakes(
|
||||
session=session,
|
||||
intake_nos=intake_nos,
|
||||
@@ -1078,8 +1181,8 @@ def submit_order_extraction_unit_result(
|
||||
通过门禁的 automatic Candidate 建批后由编排器触发 auto_progress;最后幂等初始化 Review Case。
|
||||
|
||||
Args:
|
||||
run: 所属 ShippingOrderExtractionRun。
|
||||
unit: 已进入 candidate_ready 的 ShippingOrderExtractionUnit。
|
||||
run: 所属 ShippingOrderProcessingRun。
|
||||
unit: 已进入 candidate_ready 的 ShippingOrderProcessingUnit。
|
||||
orders: 该 Unit 合并邮件补充后的订单数组。
|
||||
|
||||
Returns:
|
||||
@@ -1122,24 +1225,24 @@ def submit_order_extraction_unit_result(
|
||||
for document in intake.get('documents') or []
|
||||
if isinstance(document, dict) and str(document.get('document_id') or '').isdigit()
|
||||
}
|
||||
intake = db.session.get(ShippingNoticeIntake, unit_intake_id)
|
||||
document = db.session.get(ShippingNoticeDocument, unit_document_id)
|
||||
intake = db.session.get(ShippingOrderIntake, unit_intake_id)
|
||||
document = db.session.get(ShippingOrderDocument, unit_document_id)
|
||||
if intake is None or document is None or int(document.intake_id) != unit_intake_id:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='Unit Intake/Document 不存在')
|
||||
if int(intake.user_id) != int(run.user_id):
|
||||
raise ForbiddenError(code='SHIPPING_NOTICE.FORBIDDEN', message='Unit Intake 不属于 Run 用户')
|
||||
|
||||
# 幂等:本 Unit 候选已消费建单则直接回放,避免重复建批。
|
||||
consumed = ShippingNoticeCandidate.query.filter(
|
||||
ShippingNoticeCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingNoticeCandidate.primary_document_id == unit_document_id,
|
||||
ShippingNoticeCandidate.consumed_task_id.isnot(None),
|
||||
consumed = ShippingOrderCandidate.query.filter(
|
||||
ShippingOrderCandidate.order_extraction_run_id == int(run.id),
|
||||
ShippingOrderCandidate.primary_document_id == unit_document_id,
|
||||
ShippingOrderCandidate.consumed_task_id.isnot(None),
|
||||
).all()
|
||||
if consumed:
|
||||
task_nos = sorted({
|
||||
str(task.task_no)
|
||||
for task in ShippingTask.query.filter(
|
||||
ShippingTask.id.in_([int(row.consumed_task_id) for row in consumed])
|
||||
for task in ShippingNotice.query.filter(
|
||||
ShippingNotice.id.in_([int(row.consumed_task_id) for row in consumed])
|
||||
).all()
|
||||
})
|
||||
result = {
|
||||
@@ -1162,7 +1265,7 @@ def submit_order_extraction_unit_result(
|
||||
ensure_run_review_cases(run=run)
|
||||
return result
|
||||
|
||||
session = db.session.query(ChatSession).filter_by(session_id=run.conversation_id).one()
|
||||
session = _runtime_session_for_run(run)
|
||||
# A prior PDF Unit may validly consume the shared Intake before its sibling Unit
|
||||
# persists. Only reuse that Intake when this exact Run wrote the submission and
|
||||
# no Task or Batch has consumed it.
|
||||
@@ -1170,17 +1273,15 @@ def submit_order_extraction_unit_result(
|
||||
intake.parse_status == 'consumed'
|
||||
and intake.consumed_at is not None
|
||||
and intake.consumed_task_id is None
|
||||
and intake.consumed_batch_id is None
|
||||
and str(_order_extraction_submission(intake).get('request_id') or '') == str(run.run_no)
|
||||
)
|
||||
# 重识别沿用原 PDF/Intake;旧版空结果会把 Intake 标记 consumed,但只要未建 Task/Batch,
|
||||
# 重识别沿用原 PDF/Intake;旧版空结果会把 Intake 标记 consumed,但只要未建 Task,
|
||||
# 新版仍可落自己的 Candidate。真实业务消费保持 fail-closed。
|
||||
is_orphaned_reparse = (
|
||||
run.reparse_of_run_id is not None
|
||||
and intake.parse_status == 'consumed'
|
||||
and intake.consumed_at is not None
|
||||
and intake.consumed_task_id is None
|
||||
and intake.consumed_batch_id is None
|
||||
)
|
||||
current_intakes = _load_intakes(
|
||||
session=session,
|
||||
|
||||
@@ -18,8 +18,8 @@ from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderProcessingUnit,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
@@ -63,7 +63,7 @@ def _operation_id(explicit: str | None = None) -> str:
|
||||
return f'cancel-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}-{id(object()) % 10_000_000}'
|
||||
|
||||
|
||||
def _resolve_cancellation_operation_id(run: ShippingOrderExtractionRun, explicit: str | None = None) -> str:
|
||||
def _resolve_cancellation_operation_id(run: ShippingOrderProcessingRun, explicit: str | None = None) -> str:
|
||||
"""
|
||||
复用取消请求时的 operation_id,避免 Worker 收口生成新链路。
|
||||
|
||||
@@ -89,13 +89,13 @@ def _is_admin(actor: User) -> bool:
|
||||
return str(getattr(actor, 'role', '') or '') == 'admin'
|
||||
|
||||
|
||||
def _lock_run_for_actor(*, actor: User, run_no: str) -> ShippingOrderExtractionRun:
|
||||
def _lock_run_for_actor(*, actor: User, run_no: str) -> ShippingOrderProcessingRun:
|
||||
"""
|
||||
按权限锁定 Run。
|
||||
|
||||
核心逻辑:普通用户只能锁定自己的 Run;管理员可锁定任意 Run。
|
||||
"""
|
||||
query = db.session.query(ShippingOrderExtractionRun).filter_by(run_no=str(run_no or '').strip())
|
||||
query = db.session.query(ShippingOrderProcessingRun).filter_by(run_no=str(run_no or '').strip())
|
||||
if not _is_admin(actor):
|
||||
query = query.filter_by(user_id=int(actor.id))
|
||||
run = query.with_for_update().first()
|
||||
@@ -107,7 +107,7 @@ def _lock_run_for_actor(*, actor: User, run_no: str) -> ShippingOrderExtractionR
|
||||
return run
|
||||
|
||||
|
||||
def _validate_cancel_permission(*, actor: User, run: ShippingOrderExtractionRun, reason: str | None) -> None:
|
||||
def _validate_cancel_permission(*, actor: User, run: ShippingOrderProcessingRun, reason: str | None) -> None:
|
||||
"""
|
||||
校验取消权限与原因。
|
||||
|
||||
@@ -145,7 +145,7 @@ def _apply_fields(target: Any, fields: dict[str, Any]) -> None:
|
||||
setattr(target, key, value)
|
||||
|
||||
|
||||
def _unit_snapshot(unit: ShippingOrderExtractionUnit) -> dict[str, Any]:
|
||||
def _unit_snapshot(unit: ShippingOrderProcessingUnit) -> dict[str, Any]:
|
||||
"""Unit 审计白名单投影。"""
|
||||
return {
|
||||
'status': unit.status,
|
||||
@@ -155,7 +155,7 @@ def _unit_snapshot(unit: ShippingOrderExtractionUnit) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _run_snapshot(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
def _run_snapshot(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
"""Run 审计白名单投影。"""
|
||||
return {
|
||||
'status': run.status,
|
||||
@@ -167,8 +167,8 @@ def _run_snapshot(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
|
||||
def _cancel_pending_unit(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
run: ShippingOrderProcessingRun,
|
||||
unit: ShippingOrderProcessingUnit,
|
||||
fields: dict[str, Any],
|
||||
operation_id: str,
|
||||
) -> None:
|
||||
@@ -210,8 +210,8 @@ def _cancel_pending_unit(
|
||||
|
||||
def _request_inflight_unit_cancel(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
unit: ShippingOrderExtractionUnit,
|
||||
run: ShippingOrderProcessingRun,
|
||||
unit: ShippingOrderProcessingUnit,
|
||||
fields: dict[str, Any],
|
||||
operation_id: str,
|
||||
) -> None:
|
||||
@@ -252,7 +252,7 @@ def _request_inflight_unit_cancel(
|
||||
)
|
||||
|
||||
|
||||
def _has_inflight_units(units: list[ShippingOrderExtractionUnit]) -> bool:
|
||||
def _has_inflight_units(units: list[ShippingOrderProcessingUnit]) -> bool:
|
||||
"""是否仍有执行中、尚未取消完成的 Unit。"""
|
||||
for unit in units:
|
||||
if unit.status in IN_FLIGHT_UNIT_STATUSES and unit.cancellation_completed_at is None:
|
||||
@@ -264,7 +264,7 @@ def _has_inflight_units(units: list[ShippingOrderExtractionUnit]) -> bool:
|
||||
|
||||
def finalize_run_cancellation_if_ready(
|
||||
*,
|
||||
run: ShippingOrderExtractionRun,
|
||||
run: ShippingOrderProcessingRun,
|
||||
operation_id: str | None = None,
|
||||
actor_type: str = 'system',
|
||||
actor_id: str | None = None,
|
||||
@@ -334,7 +334,7 @@ def finalize_run_cancellation_if_ready(
|
||||
return True
|
||||
|
||||
|
||||
def apply_worker_cancellation_checkpoint(*, run: ShippingOrderExtractionRun) -> bool:
|
||||
def apply_worker_cancellation_checkpoint(*, run: ShippingOrderProcessingRun) -> bool:
|
||||
"""
|
||||
Worker 安全检查点:取消剩余 pending,并收口已请求取消的 in-flight Unit。
|
||||
|
||||
@@ -402,7 +402,7 @@ def apply_worker_cancellation_checkpoint(*, run: ShippingOrderExtractionRun) ->
|
||||
return True
|
||||
|
||||
|
||||
def should_abort_unit_for_cancellation(*, run: ShippingOrderExtractionRun, unit: ShippingOrderExtractionUnit) -> bool:
|
||||
def should_abort_unit_for_cancellation(*, run: ShippingOrderProcessingRun, unit: ShippingOrderProcessingUnit) -> bool:
|
||||
"""
|
||||
判断 Unit 在外部副作用前是否应中止。
|
||||
|
||||
@@ -418,7 +418,7 @@ def cancel_order_extraction_run(
|
||||
reason: str | None = None,
|
||||
reason_code: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingOrderExtractionRun:
|
||||
) -> ShippingOrderProcessingRun:
|
||||
"""
|
||||
请求取消整批订单抽取 Run。
|
||||
|
||||
@@ -515,7 +515,7 @@ def cancel_order_extraction_unit(
|
||||
reason: str | None = None,
|
||||
reason_code: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
) -> ShippingOrderExtractionUnit:
|
||||
) -> ShippingOrderProcessingUnit:
|
||||
"""
|
||||
请求取消单个 PDF Unit。
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/order_extraction_evidence.py
|
||||
|
||||
用途:校验订单抽取字段证据,并用后端表格解析结果裁决 Reservation ID 来源冲突。
|
||||
依赖:ShippingNoticeDocument、notice_lines.adjudicate_notice_lines、reservation_id。
|
||||
依赖:ShippingOrderDocument、notice_lines.adjudicate_notice_lines、reservation_id。
|
||||
逻辑:order_extraction 在 Candidate 落库前调用;可信证据随抽取审计保存,供 open_existing 回填门禁复用。
|
||||
"""
|
||||
|
||||
@@ -10,7 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.models import ShippingNoticeDocument
|
||||
from app.models import ShippingOrderDocument
|
||||
from app.services.shipping_notice.notice_lines import adjudicate_notice_lines
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
@@ -18,7 +18,7 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
def verify_reservation_evidence(
|
||||
order: dict[str, Any],
|
||||
*,
|
||||
documents: list[ShippingNoticeDocument],
|
||||
documents: list[ShippingOrderDocument],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
验证每条非空 Reservation ID 的字段级原文证据。
|
||||
@@ -76,7 +76,7 @@ def verify_reservation_evidence(
|
||||
def adjudicate_order_reservations(
|
||||
summary: dict[str, Any],
|
||||
*,
|
||||
documents: list[ShippingNoticeDocument],
|
||||
documents: list[ShippingOrderDocument],
|
||||
schema_definition: dict[str, Any],
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/order_extraction_materialization.py
|
||||
|
||||
用途:在点击发送后,按附件选择计划为 Run 物化本次真正需要的输入文档。
|
||||
依赖:ShippingNoticeIntake/FileAsset、notice_upload、document_candidate_persist、
|
||||
依赖:ShippingOrderIntake/FileAsset、notice_upload、document_candidate_persist、
|
||||
attachment_selection、attachment_integrity。
|
||||
逻辑:上传阶段保持快览轻量;发送阶段只为本次计划选中的附件和邮件正文创建 Document/派生资产,
|
||||
不把未选附件偷偷升级成可执行输入;附件不完整 ConflictError 附带稳定 reason_code。
|
||||
@@ -20,7 +20,7 @@ from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import FileAsset, ShippingNoticeDocument, ShippingNoticeIntake
|
||||
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderIntake
|
||||
from app.services.shipping_notice.attachment_integrity import attachment_incomplete_error_details
|
||||
from app.services.shipping_notice.attachment_selection import build_attachment_selection_snapshot
|
||||
from app.services.shipping_notice.document_candidate_persist import persist_intake_documents
|
||||
@@ -32,11 +32,11 @@ from app.services.shipping_notice.notice_upload import (
|
||||
from app.services.shipping_notice.intake_parse_workflow import extract_notice_from_asset
|
||||
|
||||
|
||||
def _existing_document_keys(intake: ShippingNoticeIntake) -> set[str]:
|
||||
def _existing_document_keys(intake: ShippingOrderIntake) -> set[str]:
|
||||
"""返回当前 Intake 已落库文档键,供发送阶段判断是否需要补物化。"""
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeDocument.attachment_key)
|
||||
.filter(ShippingNoticeDocument.intake_id == int(intake.id))
|
||||
db.session.query(ShippingOrderDocument.attachment_key)
|
||||
.filter(ShippingOrderDocument.intake_id == int(intake.id))
|
||||
.all()
|
||||
)
|
||||
return {str(value or '').strip() for (value,) in rows if str(value or '').strip()}
|
||||
@@ -44,7 +44,7 @@ def _existing_document_keys(intake: ShippingNoticeIntake) -> set[str]:
|
||||
|
||||
def _selected_attachment_keys_for_intake(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
attachment_selection: dict[str, Any],
|
||||
selection_batches: set[int] | None = None,
|
||||
) -> set[str]:
|
||||
@@ -73,7 +73,7 @@ def _selected_attachment_keys_for_intake(
|
||||
|
||||
|
||||
def _require_selected_document_keys(
|
||||
*, intake: ShippingNoticeIntake, selected_attachment_keys: set[str],
|
||||
*, intake: ShippingOrderIntake, selected_attachment_keys: set[str],
|
||||
) -> None:
|
||||
"""校验本次授权附件已全部物化,阻止空输入进入版面和订单任务。
|
||||
|
||||
@@ -124,7 +124,7 @@ def _parse_attachment_payload(
|
||||
|
||||
def _build_selected_eml_result(
|
||||
*,
|
||||
intake: ShippingNoticeIntake,
|
||||
intake: ShippingOrderIntake,
|
||||
parent_asset: FileAsset,
|
||||
selected_attachment_keys: set[str],
|
||||
max_concurrency: int = 1,
|
||||
@@ -262,7 +262,7 @@ def _build_single_file_result_in_thread(*, parent_asset: Any, flask_app: Any) ->
|
||||
|
||||
def ensure_order_extraction_input_documents(
|
||||
*,
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
intakes: list[ShippingOrderIntake],
|
||||
attachment_selection: dict[str, Any],
|
||||
schema_definition: dict[str, Any] | None = None,
|
||||
selection_batches: set[int] | None = None,
|
||||
@@ -279,8 +279,8 @@ def ensure_order_extraction_input_documents(
|
||||
definition = dict(schema_definition or {})
|
||||
allowed_batches = {int(batch) for batch in (selection_batches or {1}) if int(batch) > 0}
|
||||
max_concurrency = max(1, int(attachment_selection.get('max_initial_concurrency') or 1))
|
||||
normal_inputs: list[tuple[ShippingNoticeIntake, FileAsset]] = []
|
||||
eml_inputs: list[tuple[ShippingNoticeIntake, FileAsset, set[str]]] = []
|
||||
normal_inputs: list[tuple[ShippingOrderIntake, FileAsset]] = []
|
||||
eml_inputs: list[tuple[ShippingOrderIntake, FileAsset, set[str]]] = []
|
||||
for intake in intakes:
|
||||
parent_asset = db.session.get(FileAsset, int(intake.asset_id)) if intake.asset_id else None
|
||||
if parent_asset is None:
|
||||
|
||||
@@ -5,6 +5,8 @@ services/shipping_notice/order_extraction_merge.py
|
||||
依赖:Run 冻结动态 Schema field_id/field_code 映射。
|
||||
逻辑:同 Intake 下仅 PO 一致或 Line 的 part_number+reservation_id 一致时合并;
|
||||
跨文档 Reservation 补全优先使用 part_number / customer_po_line_no(兼容历史 line_no)。
|
||||
阶段 2:默认 keep_primary_documents_separate=True,不同 primary_document_id
|
||||
(多 PDF)不得合并为同一 Candidate;EML 内补充仍走 order_supplement_merge。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -164,8 +166,27 @@ def _merge_order(
|
||||
target.setdefault('source_document_ids', []).append(incoming.get('primary_document_id'))
|
||||
|
||||
|
||||
def merge_unit_orders(*, orders: list[dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""按冻结 Schema 稳定字段身份合并单元订单,返回确定顺序的新列表。"""
|
||||
def merge_unit_orders(
|
||||
*,
|
||||
orders: list[dict[str, Any]],
|
||||
schema_definition: dict[str, Any],
|
||||
keep_primary_documents_separate: bool = True,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
按冻结 Schema 稳定字段身份合并单元订单,返回确定顺序的新列表。
|
||||
|
||||
核心逻辑:同 Intake 且 PO/强行身份匹配时可合并 Observation;
|
||||
keep_primary_documents_separate=True(阶段 2 默认)时,primary_document_id
|
||||
不同的订单永不合并,保证 EML 多 PDF / 直接 PDF 各成 Candidate。
|
||||
|
||||
Args:
|
||||
orders: 单元抽出的订单字典列表。
|
||||
schema_definition: Run 冻结 Schema definition(含 fields)。
|
||||
keep_primary_documents_separate: True 时禁止跨 primary_document_id 合并。
|
||||
|
||||
Returns:
|
||||
合并后的订单列表(深拷贝,含 source_document_ids)。
|
||||
"""
|
||||
codes = {
|
||||
str(item.get('field_id') or ''): str(item.get('field_code') or '')
|
||||
for item in schema_definition.get('fields') or [] if isinstance(item, dict)
|
||||
@@ -174,14 +195,21 @@ def merge_unit_orders(*, orders: list[dict[str, Any]], schema_definition: dict[s
|
||||
for raw in orders:
|
||||
order = copy.deepcopy(raw)
|
||||
intake_no = str(order.get('source_intake_no') or '').strip().upper()
|
||||
primary_document_id = order.get('primary_document_id')
|
||||
po_numbers, line_keys = _order_identity(order, codes)
|
||||
match = None
|
||||
matched_by_po = False
|
||||
for candidate in merged:
|
||||
# A Dify order may never inherit an approved-profile acceptance marker.
|
||||
if candidate.get('_hxops_acceptance') != order.get('_hxops_acceptance'):
|
||||
continue
|
||||
if str(candidate.get('source_intake_no') or '').strip().upper() != intake_no:
|
||||
continue
|
||||
if (
|
||||
keep_primary_documents_separate
|
||||
and candidate.get('primary_document_id') != primary_document_id
|
||||
):
|
||||
continue
|
||||
candidate_pos, candidate_lines = _order_identity(candidate, codes)
|
||||
matched_by_po = len(po_numbers) == 1 and po_numbers == candidate_pos
|
||||
if matched_by_po or bool(line_keys & candidate_lines):
|
||||
|
||||
Loaded 100 of 571 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user