feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置 新增收料报表管理的前端页面、路由和侧边栏入口 新增后端收料报表配置接口、数据库模型和RPA脚本 优化发货通知流程的重试策略,将shipping相关job默认不自动重试 移除废弃的库存源确认相关逻辑,更新流程门禁规则 重构订单模板的值适配器模块,新增坐标OCR值适配器 清理前端shipping菜单和action的废弃选项 更新相关文档和测试用例,调整.gitignore忽略规则
This commit is contained in:
1 parent
260465b72d
commit
1b6483a4ea
466 files changed
+32115
-33796
No files matched your search
@@ -21,7 +21,9 @@ from app.models import (
|
||||
ShippingInventoryConfigurationTestRun, ShippingInventoryStructureAnalysis,
|
||||
ShippingExcelTemplate,
|
||||
ShippingInventorySourceParsingBindingAudit,
|
||||
ShippingReceiptReportConfig,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.credential_crypto import encrypt_credential
|
||||
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
|
||||
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
|
||||
@@ -245,6 +247,94 @@ def _source_payload(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _receipt_report_config_payload(config: ShippingReceiptReportConfig) -> dict[str, Any]:
|
||||
"""序列化独立收料配置,禁止把库存路径或凭据透传至管理端。"""
|
||||
return {
|
||||
'id': config.id, 'inventory_source_id': config.inventory_source_id, 'enabled': bool(config.enabled),
|
||||
'report_path_json': config.report_path_json or {},
|
||||
'query_parameters_json': config.query_parameters_json or [],
|
||||
'warehouse_ids_json': config.warehouse_ids_json or [], 'config_version': config.config_version,
|
||||
'created_at': _iso(config.created_at), 'updated_at': _iso(config.updated_at),
|
||||
}
|
||||
|
||||
|
||||
def _validate_receipt_report_config(
|
||||
source: ShippingInventorySource, data: dict[str, Any],
|
||||
) -> tuple[bool, dict[str, str], list[dict[str, Any]], list[str]]:
|
||||
"""规范收料配置,确保日期保持空值、DBS/Crane 路径与仓库拆分规则不混用。"""
|
||||
enabled = _bool(data, 'enabled', True)
|
||||
try:
|
||||
parameters = _validate_query_parameters(data)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
|
||||
# 报表日期不筛选,避免管理端误传日期使跨日排程导出产生漏数。
|
||||
if any('date' in str(item.get('name') or '').strip().lower() for item in parameters):
|
||||
raise ValidationError('Receipt report date filtering is not supported', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
raw_warehouses = _json_string_list(data, 'warehouse_ids_json')
|
||||
raw_path = _json_object(data, 'report_path_json')
|
||||
if source.connector_type == 'dbs':
|
||||
try:
|
||||
path = _validate_report_path('dbs', raw_path)
|
||||
except ValidationError as exc:
|
||||
raise ValidationError(str(exc), code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID') from exc
|
||||
if enabled and not raw_warehouses:
|
||||
raise ValidationError('DBS receipt report requires warehouse_ids_json', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
return enabled, path, parameters, raw_warehouses
|
||||
if source.connector_type == 'crane':
|
||||
if raw_warehouses:
|
||||
raise ValidationError('Crane receipt report does not support Warehouse split', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
if set(raw_path) - {'report_name'} or raw_path.get('report_name') not in (None, '', 'Inbound Details'):
|
||||
raise ValidationError('Crane receipt report is fixed to Inbound Details', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
if parameters:
|
||||
raise ValidationError(
|
||||
'Crane receipt report does not support query parameters',
|
||||
code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID',
|
||||
)
|
||||
return enabled, {'report_name': 'Inbound Details'}, [], []
|
||||
raise ValidationError('Unsupported receipt connector type', code='SHIPPING.RECEIPT_REPORT_CONFIG_INVALID')
|
||||
|
||||
|
||||
def get_receipt_report_config(source_id: int) -> dict[str, Any] | None:
|
||||
"""读取站点的收料配置;不存在时返回空,供抽屉初始化而非创建库存配置。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
|
||||
return _receipt_report_config_payload(config) if config else None
|
||||
|
||||
|
||||
def save_receipt_report_config(source_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
|
||||
"""保存站点内独立收料配置并追加配置前后快照审计,不写入库存 Source 字段。"""
|
||||
source = db.session.get(ShippingInventorySource, source_id)
|
||||
if source is None:
|
||||
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
|
||||
enabled, path, parameters, warehouses = _validate_receipt_report_config(source, data)
|
||||
config = ShippingReceiptReportConfig.query.filter_by(inventory_source_id=source.id).one_or_none()
|
||||
before = _receipt_report_config_payload(config) if config else None
|
||||
is_new = config is None
|
||||
if config is None:
|
||||
config = ShippingReceiptReportConfig(inventory_source_id=source.id)
|
||||
config.created_by = actor_id
|
||||
db.session.add(config)
|
||||
else:
|
||||
config.config_version += 1
|
||||
config.enabled = enabled
|
||||
config.report_path_json = path
|
||||
config.query_parameters_json = parameters
|
||||
config.warehouse_ids_json = warehouses
|
||||
config.updated_by = actor_id
|
||||
db.session.flush()
|
||||
after = _receipt_report_config_payload(config)
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_type='shipping_receipt_report_config',
|
||||
aggregate_id=str(source.id), actor_type='admin', actor_id=actor_id, action='create' if is_new else 'update',
|
||||
result='success', before=before, after=after,
|
||||
metadata={'inventory_source_id': source.id, 'connector_type': source.connector_type},
|
||||
)
|
||||
db.session.commit()
|
||||
return after
|
||||
|
||||
|
||||
def _binding_snapshot(source: ShippingInventorySource) -> dict[str, Any]:
|
||||
"""冻结解析绑定变更的最小站点上下文,避免审计依赖后续可变主数据。"""
|
||||
return {
|
||||
|
||||
@@ -23,7 +23,7 @@ class TurnInput:
|
||||
Args:
|
||||
type: 输入类型;第一阶段仅开放 action / form_submit。
|
||||
display_text: 写入 ChatLog.query 与前端 user 气泡的可见文案。
|
||||
action_type: action / form_submit 时的全局唯一动作标识,如 shipping.submit_decision。
|
||||
action_type: action / form_submit 时的全局唯一动作标识,如 shipping.create_order_extraction。
|
||||
text: type=text 时的原始问题。
|
||||
payload: 业务动作参数,由各领域 handler 自行解析。
|
||||
"""
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"""独立收料 RPA 排程等待态收口辅助。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
from app.services.schedule import normalize_platform_api_path
|
||||
from app.services.schedule.freight_receipt_rpa_job import AWAITING_RECEIPT_RPA_CALLBACK_STATUS, RECEIPT_RPA_JOB_KEY
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def should_defer_receipt_schedule_run(task: ScheduleTask, step_logs: list | None) -> bool:
|
||||
"""仅当独立收料 job 成功写入 trigger 后延后终态,避免影响库存 job 判断。"""
|
||||
return bool(
|
||||
task.schedule_type == 'platform_job'
|
||||
and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY
|
||||
and any(isinstance(row, dict) and row.get('status') == AWAITING_RECEIPT_RPA_CALLBACK_STATUS for row in step_logs or [])
|
||||
)
|
||||
|
||||
|
||||
def is_awaiting_receipt_rpa_schedule_run(run: ScheduleRun | None) -> bool:
|
||||
"""判断 run 是否为独立收料 callback 等待态,供 worker 启动恢复时保护。"""
|
||||
summary = run.response_summary_json if run is not None and isinstance(run.response_summary_json, dict) else {}
|
||||
return bool(run is not None and run.status == 'running' and summary.get('awaiting_receipt_rpa'))
|
||||
|
||||
|
||||
def apply_deferred_receipt_schedule_run_state(
|
||||
run: ScheduleRun, task: ScheduleTask, *, total_count: int, details: list[dict], errors: list[str], step_logs: list[dict],
|
||||
) -> ScheduleRun:
|
||||
"""将收料 run 保持为 awaiting callback,终态由所有收料单元回调完成后专用服务写入。"""
|
||||
run.status = 'running'
|
||||
run.started_at = run.started_at or datetime.utcnow()
|
||||
run.total_count = total_count
|
||||
run.success_count = 0
|
||||
run.failed_count = 0
|
||||
run.skipped_count = 0
|
||||
run.finished_at = None
|
||||
run.step_logs = step_logs
|
||||
run.response_summary_json = {'awaiting_receipt_rpa': True, 'pending_details': details, 'errors': errors[:20]}
|
||||
db.session.commit()
|
||||
return run
|
||||
|
||||
|
||||
def finalize_receipt_schedule_run_if_complete(schedule_run_id: int) -> dict:
|
||||
"""当收料 run 的全部单元已回调后写入独立排程终态,不读取库存回调结果。"""
|
||||
run = db.session.get(ScheduleRun, schedule_run_id)
|
||||
if run is None:
|
||||
return {'finalized': False, 'reason': 'schedule_run_not_found'}
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if not summary.get('awaiting_receipt_rpa'):
|
||||
return {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
|
||||
units = ShippingReceiptRpaUnitRun.query.filter_by(schedule_run_id=run.id).all()
|
||||
terminal = {'success', 'empty', 'failed', 'cancelled'}
|
||||
if any(unit.status not in terminal for unit in units):
|
||||
return {'finalized': False, 'reason': 'units_pending'}
|
||||
success_count = sum(unit.status == 'success' for unit in units)
|
||||
skipped_count = sum(unit.status == 'empty' for unit in units)
|
||||
failed_count = sum(unit.status in {'failed', 'cancelled'} for unit in units)
|
||||
run.total_count = len(units)
|
||||
run.success_count = success_count
|
||||
run.skipped_count = skipped_count
|
||||
run.failed_count = failed_count
|
||||
run.finished_at = datetime.utcnow()
|
||||
run.duration_ms = int((run.finished_at - run.started_at).total_seconds() * 1000) if run.started_at else 0
|
||||
run.status = 'success' if failed_count == 0 else 'failed' if success_count == 0 else 'partial_failed'
|
||||
run.error_message = '; '.join(filter(None, (unit.error_message for unit in units if unit.status == 'failed')))[:2000] or None
|
||||
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'success_count': success_count, 'empty_count': skipped_count, 'failed_count': failed_count}
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.receipt_report_notification import deliver_schedule_receipt_summary
|
||||
deliver_schedule_receipt_summary(run.id)
|
||||
return {'finalized': True, 'status': run.status}
|
||||
|
||||
|
||||
def _receipt_timeout_seconds() -> int:
|
||||
"""读取收料回调等待上限;超时只标记失败,不会自动重试或重发。"""
|
||||
try:
|
||||
return max(60, int(current_app.config.get('SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS', 900)))
|
||||
except (TypeError, ValueError):
|
||||
return 900
|
||||
|
||||
|
||||
def is_freight_receipt_rpa_task(task: ScheduleTask | None) -> bool:
|
||||
"""识别独立收料 RPA 排程,避免超时回收影响库存或其他平台任务。"""
|
||||
return bool(
|
||||
task
|
||||
and task.schedule_type == 'platform_job'
|
||||
and normalize_platform_api_path(task.platform_api_path) == RECEIPT_RPA_JOB_KEY
|
||||
)
|
||||
|
||||
|
||||
def _recover_stale_receipt_run(run: ScheduleRun, *, cutoff: datetime, timeout_seconds: int) -> bool:
|
||||
"""将无回调的独立收料运行收口为失败,保留其单元与触发审计事实。"""
|
||||
summary = run.response_summary_json if isinstance(run.response_summary_json, dict) else {}
|
||||
if not summary.get('awaiting_receipt_rpa') or run.status != 'running' or not run.started_at or run.started_at > cutoff:
|
||||
return False
|
||||
task = run.task or db.session.get(ScheduleTask, run.schedule_task_id)
|
||||
if not is_freight_receipt_rpa_task(task):
|
||||
return False
|
||||
now = datetime.utcnow()
|
||||
pending = ShippingReceiptRpaUnitRun.query.filter(
|
||||
ShippingReceiptRpaUnitRun.schedule_run_id == run.id,
|
||||
ShippingReceiptRpaUnitRun.status.in_({'queued', 'awaiting_rpa', 'processing'}),
|
||||
).all()
|
||||
for unit in pending:
|
||||
before = {'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message}
|
||||
unit.status = 'failed'
|
||||
unit.error_code = 'RPA.RECEIPT_CALLBACK_TIMEOUT'
|
||||
unit.error_message = f'Receipt RPA callback timed out after {timeout_seconds} seconds'
|
||||
unit.finished_at = now
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_rpa_callback_timeout', aggregate_type='shipping_receipt_unit',
|
||||
aggregate_id=str(unit.id), run_no=run.run_no, actor_type='worker', actor_id='schedule-recovery',
|
||||
unit_id=unit.id, result='failure', before=before,
|
||||
after={'status': unit.status, 'error_code': unit.error_code, 'error_message': unit.error_message},
|
||||
metadata={'timeout_seconds': timeout_seconds},
|
||||
)
|
||||
run.status = 'failed'
|
||||
run.finished_at = now
|
||||
run.duration_ms = int((now - run.started_at).total_seconds() * 1000)
|
||||
run.failed_count = len(pending) or max(1, int(run.failed_count or 0))
|
||||
run.error_message = f'收料 RPA 回调等待超时({timeout_seconds} 秒)'
|
||||
run.step_logs = [*(run.step_logs or []), {
|
||||
'step': 'freight_receipt_rpa', 'status': 'failed',
|
||||
'detail': {'message': run.error_message, 'timeout_seconds': timeout_seconds},
|
||||
}]
|
||||
run.response_summary_json = {**summary, 'awaiting_receipt_rpa': False, 'recovered_reason': 'receipt_rpa_callback_timeout'}
|
||||
return True
|
||||
|
||||
|
||||
def recover_stale_receipt_rpa_schedule_runs(task: ScheduleTask) -> int:
|
||||
"""在同一收料排程开始前回收超时运行,解除后续 Cron/手动执行的互斥。"""
|
||||
if not is_freight_receipt_rpa_task(task):
|
||||
return 0
|
||||
timeout_seconds = _receipt_timeout_seconds()
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
|
||||
recovered = sum(
|
||||
_recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
|
||||
for run in ScheduleRun.query.filter_by(schedule_task_id=task.id, status='running').all()
|
||||
)
|
||||
if recovered:
|
||||
db.session.commit()
|
||||
return recovered
|
||||
|
||||
|
||||
def recover_all_stale_receipt_rpa_schedule_runs() -> int:
|
||||
"""Worker 启动时扫描全部超时收料回调,避免重启后运行永久卡住。"""
|
||||
timeout_seconds = _receipt_timeout_seconds()
|
||||
cutoff = datetime.utcnow() - timedelta(seconds=timeout_seconds)
|
||||
recovered = sum(
|
||||
_recover_stale_receipt_run(run, cutoff=cutoff, timeout_seconds=timeout_seconds)
|
||||
for run in ScheduleRun.query.filter_by(status='running').all()
|
||||
)
|
||||
if recovered:
|
||||
db.session.commit()
|
||||
return recovered
|
||||
@@ -0,0 +1,113 @@
|
||||
"""独立收料 RPA 排程:冻结站点配置并按 DBS Warehouse 展开执行单元。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportConfig, ShippingReceiptRpaUnitRun
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
|
||||
RECEIPT_RPA_JOB_KEY = 'freight-receipt-rpa'
|
||||
AWAITING_RECEIPT_RPA_CALLBACK_STATUS = 'awaiting_receipt_rpa_callback'
|
||||
ScheduleExecuteResult = tuple[int, int, int, int, list[dict[str, Any]], list[str], list[dict[str, Any]]]
|
||||
|
||||
|
||||
def _wanted_source_codes(task: ScheduleTask) -> set[str]:
|
||||
"""提取结构化 source_codes;留空代表全部具备有效收料配置的站点。"""
|
||||
params = task.job_params if isinstance(task.job_params, dict) else {}
|
||||
values = params.get('source_codes') or []
|
||||
if isinstance(values, str):
|
||||
values = [values]
|
||||
return {str(value).strip().upper() for value in values if str(value).strip()}
|
||||
|
||||
|
||||
def _eligible_sources(task: ScheduleTask) -> list[tuple[ShippingInventorySource, ShippingReceiptReportConfig]]:
|
||||
"""读取已启用且收料配置已启用的站点,不依赖库存报表路径或解析绑定。"""
|
||||
wanted = _wanted_source_codes(task)
|
||||
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
|
||||
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
|
||||
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
|
||||
return [(source, config) for source, config in rows if not wanted or source.source_code.upper() in wanted]
|
||||
|
||||
|
||||
def _build_unit(source: ShippingInventorySource, config: ShippingReceiptReportConfig, warehouse_id: str | None) -> ShippingReceiptRpaUnitRun:
|
||||
"""冻结可审计的收料执行单元;DBS 日期字段不进入查询快照。"""
|
||||
callback_id = f'receipt:{uuid.uuid4().hex}'
|
||||
snapshot = {
|
||||
'config_id': config.id, 'config_version': config.config_version, 'connector_type': source.connector_type,
|
||||
'report_path_json': config.report_path_json or {}, 'query_parameters_json': config.query_parameters_json or [],
|
||||
'warehouse_id': warehouse_id, 'rpa_profile_id': source.rpa_profile_id,
|
||||
}
|
||||
return ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=0, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type=source.connector_type, warehouse_id=warehouse_id, callback_id=callback_id,
|
||||
status='awaiting_rpa', config_snapshot_json=snapshot,
|
||||
)
|
||||
|
||||
|
||||
def _serialize_trigger_unit(unit: ShippingReceiptRpaUnitRun) -> dict[str, Any]:
|
||||
"""生成 Worker 唯一可见的冻结执行载荷;密文凭据只随 receipt trigger 下发。"""
|
||||
source = unit.inventory_source
|
||||
profile = source.rpa_profile if source is not None else None
|
||||
if source is None or profile is None or not profile.enabled:
|
||||
raise RuntimeError(f'receipt source profile unavailable: {unit.source_code}')
|
||||
snapshot = dict(unit.config_snapshot_json or {})
|
||||
return {
|
||||
'unit_run_id': unit.id,
|
||||
'callback_id': unit.callback_id,
|
||||
'source_code': unit.source_code,
|
||||
'connector_type': unit.connector_type,
|
||||
'warehouse_id': unit.warehouse_id,
|
||||
'rpa_profile_id': profile.id,
|
||||
'rpa_profile_code': profile.profile_code,
|
||||
'login_url': profile.login_url,
|
||||
'login_config': dict(profile.login_config_json or {}),
|
||||
'credential_envelope': {
|
||||
'username_ciphertext': profile.username_ciphertext,
|
||||
'password_ciphertext': profile.password_ciphertext,
|
||||
},
|
||||
'report_path_json': dict(snapshot.get('report_path_json') or {}),
|
||||
'query_parameters_json': list(snapshot.get('query_parameters_json') or []),
|
||||
'config_snapshot': snapshot,
|
||||
}
|
||||
|
||||
|
||||
def run_freight_receipt_rpa_schedule(task: ScheduleTask, run: ScheduleRun) -> ScheduleExecuteResult:
|
||||
"""写独立收料 trigger;一个 DBS Warehouse 或一个 Crane 站点对应一个单元。"""
|
||||
units: list[ShippingReceiptRpaUnitRun] = []
|
||||
for source, config in _eligible_sources(task):
|
||||
warehouses = config.warehouse_ids_json or [] if source.connector_type == 'dbs' else [None]
|
||||
for warehouse_id in warehouses:
|
||||
unit = _build_unit(source, config, str(warehouse_id) if warehouse_id else None)
|
||||
unit.schedule_run_id = run.id
|
||||
units.append(unit)
|
||||
if not units:
|
||||
return 0, 0, 0, 1, [], ['no enabled receipt report sources'], [{'step': 'freight_receipt_rpa', 'status': 'skipped'}]
|
||||
db.session.add_all(units)
|
||||
db.session.flush()
|
||||
try:
|
||||
trigger_units = [_serialize_trigger_unit(unit) for unit in units]
|
||||
except RuntimeError as exc:
|
||||
for unit in units:
|
||||
unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_PROFILE_UNAVAILABLE'; unit.error_message = str(exc)
|
||||
db.session.commit()
|
||||
return len(units), 0, len(units), 0, [], [str(exc)], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
|
||||
for unit, trigger_unit in zip(units, trigger_units):
|
||||
unit.trigger_snapshot_json = trigger_unit
|
||||
trigger_path = write_receipt_export_batch_trigger(run.run_no, trigger_units, {
|
||||
'schedule_run_id': run.id, 'schedule_task_id': task.id, 'schema_version': 'shipping_receipt_rpa.v1',
|
||||
})
|
||||
if not trigger_path:
|
||||
for unit in units:
|
||||
unit.status = 'failed'; unit.error_code = 'RPA.RECEIPT_TRIGGER_UNAVAILABLE'; unit.error_message = 'receipt trigger directory unavailable'
|
||||
db.session.commit()
|
||||
return len(units), 0, len(units), 0, [], ['receipt trigger directory unavailable'], [{'step': 'freight_receipt_rpa', 'status': 'failed'}]
|
||||
details = [{'source_code': unit.source_code, 'warehouse_id': unit.warehouse_id, 'callback_id': unit.callback_id} for unit in units]
|
||||
run.api_request_json = {'run_no': run.run_no, 'trigger_path': trigger_path, 'source_codes': sorted({unit.source_code for unit in units})}
|
||||
db.session.commit()
|
||||
return len(units), 0, 0, 0, details, [], [{
|
||||
'step': 'freight_receipt_rpa', 'status': AWAITING_RECEIPT_RPA_CALLBACK_STATUS,
|
||||
'detail': {'trigger_path': trigger_path, 'unit_count': len(units)},
|
||||
}]
|
||||
@@ -0,0 +1,49 @@
|
||||
"""收料原样归档三年到期对象清理。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def run_freight_receipt_rpa_retention_schedule(task: Any, run: Any) -> tuple[int, int, int, int, list[dict], list[str], list[dict]]:
|
||||
"""仅删除已到三年保留期的 MinIO 对象,永不删除文件事实、运行或审计。"""
|
||||
limit = max(1, min(int((getattr(task, 'job_params', {}) or {}).get('limit', 100)), 1000))
|
||||
now = datetime.utcnow()
|
||||
rows = ShippingReceiptReportFile.query.filter(
|
||||
ShippingReceiptReportFile.archive_expires_at.is_not(None),
|
||||
ShippingReceiptReportFile.archive_expires_at <= now,
|
||||
ShippingReceiptReportFile.archive_deleted_at.is_(None),
|
||||
).order_by(ShippingReceiptReportFile.id).limit(limit).all()
|
||||
success = failed = 0
|
||||
errors: list[str] = []
|
||||
for report_file in rows:
|
||||
try:
|
||||
file_asset_storage.delete_object(report_file.storage_key)
|
||||
report_file.archive_deleted_at = now
|
||||
report_file.archive_delete_result_json = {'status': 'deleted', 'deleted_at': now.isoformat()}
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_archive_deleted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='success',
|
||||
before={'status': 'archived'}, after={'status': 'archive_deleted'},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
success += 1
|
||||
except Exception as exc:
|
||||
errors.append(f'{report_file.id}: {exc}')
|
||||
append_shipping_audit_event(
|
||||
event_type='shipping_receipt_report_archive_delete_attempted', aggregate_type='shipping_receipt_file',
|
||||
aggregate_id=str(report_file.id), actor_type='worker', actor_id='receipt-retention',
|
||||
unit_id=report_file.unit_run_id, result='failed',
|
||||
before={'status': 'archived'}, after={'status': 'archived', 'delete_error': str(exc)[:2000]},
|
||||
artifact_refs=[{'kind': 'receipt_report', 'id': str(report_file.id), 'sha256': report_file.sha256}],
|
||||
)
|
||||
failed += 1
|
||||
db.session.commit()
|
||||
return len(rows), success, failed, 0, [{'file_id': row.id} for row in rows], errors, [{'step': 'receipt_retention', 'status': 'completed'}]
|
||||
@@ -11,6 +11,8 @@ from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
def _agent_apps_options() -> list[dict[str, Any]]:
|
||||
"""启用中的 Agent 应用列表(value=agents.id)。"""
|
||||
@@ -49,10 +51,24 @@ def _shipping_inventory_sources_options() -> list[dict[str, Any]]:
|
||||
]
|
||||
|
||||
|
||||
def _shipping_receipt_sources_options() -> list[dict[str, Any]]:
|
||||
"""已启用且已配置收料报表的站点,供独立收料排程选择。"""
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
|
||||
rows = db.session.query(ShippingInventorySource, ShippingReceiptReportConfig).join(
|
||||
ShippingReceiptReportConfig, ShippingReceiptReportConfig.inventory_source_id == ShippingInventorySource.id,
|
||||
).filter(ShippingInventorySource.enabled.is_(True), ShippingReceiptReportConfig.enabled.is_(True)).all()
|
||||
return [{
|
||||
'label': source.display_name or source.source_code, 'value': source.source_code,
|
||||
'description': f'{source.connector_type} · 收料已配置',
|
||||
} for source, _config in rows]
|
||||
|
||||
|
||||
# options_source 注册表:新增来源只需在此登记 provider,不动 API 层
|
||||
_OPTIONS_PROVIDERS: dict[str, Callable[[], list[dict[str, Any]]]] = {
|
||||
"agent_apps": _agent_apps_options,
|
||||
"shipping_inventory_sources": _shipping_inventory_sources_options,
|
||||
"shipping_receipt_sources": _shipping_receipt_sources_options,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -133,6 +133,8 @@ def _register_builtin_platform_jobs() -> None:
|
||||
from app.services.schedule.fixed_assets_snapshot_job import run_fixed_assets_snapshot_schedule
|
||||
from app.services.schedule.shipping_audit_retention_job import run_shipping_audit_retention_schedule
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.schedule.freight_receipt_rpa_job import run_freight_receipt_rpa_schedule
|
||||
from app.services.schedule.freight_receipt_rpa_retention_job import run_freight_receipt_rpa_retention_schedule
|
||||
from app.services.schedule.shipping_order_extraction_progress_cleanup_job import run_shipping_order_extraction_progress_cleanup_schedule
|
||||
from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import (
|
||||
run_shipping_post_ot_auto_fulfill_compensation_schedule,
|
||||
@@ -233,6 +235,25 @@ def _register_builtin_platform_jobs() -> None:
|
||||
),
|
||||
defaults={"source_codes": []},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="freight-receipt-rpa",
|
||||
label="货代收料 RPA",
|
||||
handler=run_freight_receipt_rpa_schedule,
|
||||
description="按计划从已配置收料报表的站点导出并归档收料文件。",
|
||||
category="shipping",
|
||||
params_schema=({
|
||||
"key": "source_codes", "type": "multi_select", "label": "收料站点", "required": False,
|
||||
"default": [], "options_source": "shipping_receipt_sources",
|
||||
"help": "选择需要执行的收料站点;留空则执行所有已启用收料配置。",
|
||||
},),
|
||||
defaults={"source_codes": []},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key='freight-receipt-rpa-retention', label='货代收料归档到期清理',
|
||||
handler=run_freight_receipt_rpa_retention_schedule,
|
||||
description='仅删除已过三年保留期的收料对象,保留运行、文件事实和审计记录。', category='shipping',
|
||||
params_schema=({'key': 'limit', 'type': 'number', 'label': '单批上限', 'required': False, 'default': 100},), defaults={'limit': 100},
|
||||
))
|
||||
register_platform_job(PlatformJobDefinition(
|
||||
key="faq-aggregate-hot",
|
||||
label="FAQ 热点聚合",
|
||||
|
||||
@@ -20,6 +20,11 @@ from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
recover_all_stale_awaiting_rpa_schedule_runs,
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
recover_all_stale_receipt_rpa_schedule_runs,
|
||||
recover_stale_receipt_rpa_schedule_runs,
|
||||
is_awaiting_receipt_rpa_schedule_run,
|
||||
)
|
||||
from app.services.schedule.timezone_util import compute_next_run_at, utc_now_naive
|
||||
|
||||
_worker_initialized = False
|
||||
@@ -126,6 +131,7 @@ def enqueue_manual_schedule_run(
|
||||
if task is None:
|
||||
raise LookupError(f"schedule task {task_id} not found")
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
recover_stale_receipt_rpa_schedule_runs(task)
|
||||
active = _active_run(task.id)
|
||||
if active is not None:
|
||||
job = (
|
||||
@@ -180,6 +186,10 @@ def enqueue_due_schedule_runs(*, limit: int = 5) -> int:
|
||||
|
||||
created = 0
|
||||
for task in tasks:
|
||||
# 每轮都回收当前任务已超时的外部 RPA 回调,不能仅依赖 worker 启动时扫一次;
|
||||
# 这只是终态化失败,不会自动重新导出。
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
recover_stale_receipt_rpa_schedule_runs(task)
|
||||
if _active_run(task.id) is None:
|
||||
_create_queued_run(task, trigger_type="cron", triggered_by_user_id=None)
|
||||
_advance_next_run(task)
|
||||
@@ -229,7 +239,7 @@ def prepare_schedule_queue() -> int:
|
||||
legacy_running = db.session.query(ScheduleRun).filter(ScheduleRun.status == "running").all()
|
||||
interrupted = 0
|
||||
for run in legacy_running:
|
||||
if is_awaiting_rpa_schedule_run(run):
|
||||
if is_awaiting_rpa_schedule_run(run) or is_awaiting_receipt_rpa_schedule_run(run):
|
||||
continue
|
||||
active_job = (
|
||||
db.session.query(Job.id)
|
||||
@@ -254,6 +264,9 @@ def prepare_schedule_queue() -> int:
|
||||
recovered = recover_all_stale_awaiting_rpa_schedule_runs()
|
||||
if recovered:
|
||||
current_app.logger.info("[schedule-worker] recovered %d stale awaiting RPA runs", recovered)
|
||||
receipt_recovered = recover_all_stale_receipt_rpa_schedule_runs()
|
||||
if receipt_recovered:
|
||||
current_app.logger.info("[schedule-worker] recovered %d stale receipt RPA runs", receipt_recovered)
|
||||
from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
recover_pending_rpa_callback_cleanup_jobs,
|
||||
)
|
||||
|
||||
@@ -28,6 +28,11 @@ from app.services.schedule.shipping_inventory_rpa_finalize import (
|
||||
recover_stale_awaiting_rpa_schedule_runs,
|
||||
should_defer_schedule_run_finalization,
|
||||
)
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import (
|
||||
apply_deferred_receipt_schedule_run_state,
|
||||
recover_stale_receipt_rpa_schedule_runs,
|
||||
should_defer_receipt_schedule_run,
|
||||
)
|
||||
from app.services.schedule.job_params import normalize_job_params_for_contract
|
||||
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
|
||||
from app.services.schedule.timezone_util import compute_next_run_at, normalize_schedule_timezone
|
||||
@@ -489,6 +494,7 @@ def enable_task(task: ScheduleTask, *, commit: bool = True, check_options: bool
|
||||
|
||||
def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id: int | None, run: ScheduleRun | None = None) -> ScheduleRun:
|
||||
recover_stale_awaiting_rpa_schedule_runs(task)
|
||||
recover_stale_receipt_rpa_schedule_runs(task)
|
||||
|
||||
if run is None:
|
||||
existing = db.session.query(ScheduleRun).filter(
|
||||
@@ -550,6 +556,10 @@ def run_task_now(task: ScheduleTask, *, trigger_type: str, triggered_by_user_id:
|
||||
errors=errors,
|
||||
step_logs=step_logs,
|
||||
)
|
||||
if should_defer_receipt_schedule_run(task, step_logs):
|
||||
return apply_deferred_receipt_schedule_run_state(
|
||||
run, task, total_count=total_count, details=details, errors=errors, step_logs=step_logs,
|
||||
)
|
||||
|
||||
duration_ms = int((time.time() - start_ts) * 1000)
|
||||
if current_app:
|
||||
|
||||
@@ -4,7 +4,7 @@ services/shipping_notice/attachment_selection.py
|
||||
用途:基于 Intake 快览事实生成可审计的附件选择计划。
|
||||
依赖:ShippingOrderIntake、标准库正则与哈希;只读取 structured_result_json,不回读 Document/布局结果。
|
||||
逻辑:发送阶段调用本文件,把当前批次附件目录转换为“为何选择/为何跳过”的稳定计划;
|
||||
后续深度解析、预算扩展与审计都应复用这份快照,而不是重新猜测附件优先级。
|
||||
所有预算内附件先物化为同一 Run 的 Unit,Worker 再按并发预算执行,避免把排队误建模为扩批。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -150,8 +150,8 @@ def build_attachment_selection_snapshot(
|
||||
|
||||
Args:
|
||||
intakes: 当前发送批次的 Intake;必须已经通过上传快览。
|
||||
max_initial_attachments: 首轮自动选择上限。
|
||||
max_initial_concurrency: 首轮并发上限。
|
||||
max_initial_attachments: 兼容旧快照的首轮附件字段;新计划不以它限制 Unit 创建。
|
||||
max_initial_concurrency: Worker 最大并发,仅限制执行,不限制 Unit 创建。
|
||||
expansion_batch_size: 后续每轮扩展的附件上限。
|
||||
max_total_attachments: 单次邮件深度解析总附件预算上限。
|
||||
|
||||
@@ -232,17 +232,13 @@ def build_attachment_selection_snapshot(
|
||||
if byte_budget and planned_bytes + size > byte_budget:
|
||||
row['skip_reason_codes'] = ['budget_total_bytes']
|
||||
continue
|
||||
if index < max_initial_attachments:
|
||||
# [STEP 1] 同一发送批次内的预算内附件必须全部创建 Unit。执行并发由
|
||||
# max_initial_concurrency 在物化/Worker 层控制,不能借“首轮选择”延迟附件身份。
|
||||
if index < max_total_attachments:
|
||||
row['selected'] = True
|
||||
row['selection_batch'] = 1
|
||||
planned_bytes += size
|
||||
continue
|
||||
if index < max_total_attachments:
|
||||
row['planned_selection_batch'] = (
|
||||
2 + ((index - max_initial_attachments) // max(1, int(expansion_batch_size or 1)))
|
||||
)
|
||||
planned_bytes += size
|
||||
continue
|
||||
row['skip_reason_codes'] = ['budget_total_limit']
|
||||
|
||||
group_counts: dict[str, int] = defaultdict(int)
|
||||
|
||||
@@ -51,15 +51,6 @@ from app.services.shipping_notice.progress_audit_contract import (
|
||||
)
|
||||
|
||||
# XFA 视觉绑定 / 拆分 / 统一迁移相关审计事件(管理端筛选分组)。
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENT_TYPES: frozenset[str] = frozenset({
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
'xfa_ocr_started',
|
||||
'xfa_ocr_completed',
|
||||
'xfa_ocr_failed',
|
||||
})
|
||||
XFA_SPLIT_AUDIT_EVENT_TYPES: frozenset[str] = frozenset({
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
@@ -71,12 +62,10 @@ XFA_SPLIT_AUDIT_EVENT_TYPES: frozenset[str] = frozenset({
|
||||
'xfa_segment_mapping_updated',
|
||||
})
|
||||
XFA_UNIFIED_AUDIT_EVENT_TYPES: frozenset[str] = (
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENT_TYPES
|
||||
| XFA_SPLIT_AUDIT_EVENT_TYPES
|
||||
XFA_SPLIT_AUDIT_EVENT_TYPES
|
||||
| frozenset({
|
||||
'order_profile_unified_migration_dry_run',
|
||||
'order_profile_unified_migration_executed',
|
||||
'xfa_profile_draft_saved',
|
||||
'xfa_mapping_saved',
|
||||
'xfa_structure_analysis_reused',
|
||||
'xfa_structure_analysis_reuse_rejected',
|
||||
@@ -407,10 +396,6 @@ def _apply_filters(query, *, filters: dict[str, Any]):
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(ORDER_EMAIL_ADJUDICATION_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {'xfa_visual', 'xfa_visual_binding', 'visual_binding'}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(XFA_VISUAL_BINDING_AUDIT_EVENT_TYPES))
|
||||
)
|
||||
elif event_type_group in {'xfa_split', 'xfa_split_rule', 'split_rule'}:
|
||||
query = query.filter(
|
||||
ShippingAuditEvent.event_type.in_(sorted(XFA_SPLIT_AUDIT_EVENT_TYPES))
|
||||
|
||||
@@ -20,6 +20,7 @@ from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
|
||||
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
|
||||
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
|
||||
@@ -68,13 +69,14 @@ def _recover_stale_active_job(job: Job) -> bool:
|
||||
在用户触发入口原子回收超时的 AutoProgress running Job。
|
||||
|
||||
核心逻辑:仅处理 started_at 已超过通用发货 Job 超时的 running 行;旧 Job
|
||||
终态保留审计,关联 running/queued Gate 改为 blocked_retryable,使当前事务可重新入队。
|
||||
终态保留审计,关联 running/queued Gate 改为 blocked_manual。超时不会自动续跑;
|
||||
用户必须在当前 Gate 选择明确的恢复动作。
|
||||
|
||||
Args:
|
||||
job: 已由 submit_auto_progress 锁定的活动 Job。
|
||||
|
||||
Returns:
|
||||
True 表示旧 Job 已回收,调用方应继续创建新 Job;False 表示仍有效并复用。
|
||||
True 表示旧 Job 已回收,调用方不得据此自动创建新 Job;False 表示仍有效并复用。
|
||||
"""
|
||||
if str(job.status or '') != 'running' or job.started_at is None:
|
||||
return False
|
||||
@@ -85,7 +87,7 @@ def _recover_stale_active_job(job: Job) -> bool:
|
||||
return False
|
||||
now = _utc_now()
|
||||
job.status = 'failed'
|
||||
job.message = f'自动推进任务执行超时(超过 {int(timeout_seconds)}s),已允许重新入队'
|
||||
job.message = f'自动推进任务执行超时(超过 {int(timeout_seconds)}s),已停止,等待用户选择下一步动作'
|
||||
job.error_message = 'shipping_auto_progress_timeout'
|
||||
job.finished_at = now
|
||||
job.locked_by = None
|
||||
@@ -93,8 +95,8 @@ def _recover_stale_active_job(job: Job) -> bool:
|
||||
job.updated_at = now
|
||||
gate = db.session.get(ShippingProcessGate, int(job.gate_id)) if job.gate_id else None
|
||||
if gate is not None and gate.status in {'queued', 'running'}:
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.blocking_reason_code = 'technical_retry_exhausted'
|
||||
gate.status = 'blocked_manual'
|
||||
gate.blocking_reason_code = 'technical_failure_present'
|
||||
gate.updated_at = now
|
||||
db.session.flush()
|
||||
return True
|
||||
@@ -363,20 +365,22 @@ def submit_auto_progress(
|
||||
).with_for_update().order_by(Job.id.desc()).first()
|
||||
)
|
||||
if active is not None:
|
||||
if not _recover_stale_active_job(active):
|
||||
if _recover_stale_active_job(active):
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'queued' if active.status == 'queued' else 'running',
|
||||
'status': 'blocked_manual',
|
||||
'job_id': int(active.id), 'execution_id': active.execution_id,
|
||||
'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True,
|
||||
'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': False,
|
||||
'stopped_reason': 'shipping_auto_progress_timeout',
|
||||
}
|
||||
log_task_event(locked_task, 'auto_progress_stale_job_recovered', {
|
||||
'stale_job_id': int(active.id),
|
||||
'execution_id': active.execution_id,
|
||||
'gate_id': active.gate_id,
|
||||
'trigger': trigger,
|
||||
}, actor_id=operator_id, source=trigger)
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'queued' if active.status == 'queued' else 'running',
|
||||
'job_id': int(active.id), 'execution_id': active.execution_id,
|
||||
'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True,
|
||||
}
|
||||
candidate = get_active_candidate_set(locked_task)
|
||||
candidate_set_id = int(candidate.id) if candidate is not None else None
|
||||
execution = _active_execution_for_task(locked_task, candidate_set_id=candidate_set_id)
|
||||
@@ -435,6 +439,7 @@ def submit_auto_progress(
|
||||
if (
|
||||
gate is not None
|
||||
and action_code
|
||||
and action_belongs_to_gate(gate_code=str(gate.gate_code), action_code=action_code)
|
||||
and not is_navigation_action(action_code)
|
||||
and is_technical_gate_party(execution.responsible_party)
|
||||
):
|
||||
|
||||
@@ -21,15 +21,15 @@ CANDIDATE_QUALIFICATION_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
})
|
||||
|
||||
# 资格评估器版本;快照持久化时写入 evaluator_version。
|
||||
# 变更点:2026-08-08 引入 VC 三来源门禁,版本 bump。
|
||||
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v2.1-vc'
|
||||
# 变更点:模板值源改为内部证据适配,资格不再按 XFA/坐标模板分叉。
|
||||
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v3.0-unified-profile'
|
||||
|
||||
# 统一检查顺序(不可重排):后置项依赖前置放行语义由服务层解释。
|
||||
# XFA 专属门禁对非 XFA Candidate 恒为 True(N/A 放行)。
|
||||
# VC 门禁 vc_source_merged_clean 放在 field_conflicts_resolved 之后,
|
||||
# 以便冲突项先被 PDF 优先裁决,剩余 needs_review 项再由本门禁拦截。
|
||||
CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
|
||||
'auto_create_enabled',
|
||||
'route_stp_eligible',
|
||||
'classification_confidence',
|
||||
'required_fields_complete',
|
||||
'key_fields_minimum_confidence',
|
||||
@@ -39,16 +39,12 @@ 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',
|
||||
'xfa_unified_profile_snapshot',
|
||||
)
|
||||
|
||||
# 检查项失败 → 稳定用户原因码(对话 / Process Gate / 复核摘要共用)。
|
||||
CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = {
|
||||
'auto_create_enabled': 'auto_create_disabled',
|
||||
'route_stp_eligible': 'review_required',
|
||||
'classification_confidence': 'classification_low_confidence',
|
||||
'required_fields_complete': 'final_required_field_missing',
|
||||
'key_fields_minimum_confidence': 'field_low_confidence',
|
||||
@@ -58,15 +54,11 @@ 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',
|
||||
'xfa_unified_profile_snapshot': 'xfa_visual_coverage_insufficient',
|
||||
}
|
||||
|
||||
# 偏向「需人工轻量确认」而非硬阻断的原因码。
|
||||
CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'review_required',
|
||||
'customer_confirmation_required',
|
||||
'customer_ambiguous',
|
||||
'customer_unresolved',
|
||||
|
||||
@@ -10,8 +10,7 @@ services/shipping_notice/candidate_qualification_service.py
|
||||
模板 Profile 批准仅写入 parser_trace;LLM 路径不再天然阻断;
|
||||
分类/LLM 字段置信度缺失 fail-closed;阈值来源写入 confidence_policy;
|
||||
duplicate unchecked 与关键字段证据缺失均 fail-closed;
|
||||
XFA 硬门禁:shadow 阻断、盲测批准、客户/checksum/场景白名单(自动建单总开关走 Schema/CQ);
|
||||
另要求 evidence 计数与四项 cross-check 齐全且仅为 matched/passed/skipped;
|
||||
XFA datasets 的身份/交叉校验结果作为统一证据门禁输入,不新增模板类型专属放行规则;
|
||||
PDF 优先关键冲突(conflicts_json.reason=pdf_preferred_critical_conflict)
|
||||
映射为 review_required,阻断 can_auto_create。
|
||||
硬冻结 2026-08-07:不再叠加 XFA_AUTO_CREATE / flatten / 审计补偿等模板类型特例到 can_auto_create。
|
||||
@@ -41,16 +40,7 @@ from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts
|
||||
collect_vc_candidate_conflicts,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
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,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import extraction_emergency_stop_enabled
|
||||
|
||||
|
||||
def _candidate_field(candidate: Any, key: str, default: Any = None) -> Any:
|
||||
@@ -345,6 +335,10 @@ def evaluate_candidate_qualification(
|
||||
emergency_stop = True
|
||||
|
||||
auto_create_enabled = bool(schema_auto_create_enabled) and not emergency_stop
|
||||
route = _route_decision(unit=unit, run=run)
|
||||
# 路由已明确 needs_review 时,候选字段再完整也不能重获自动建单资格。
|
||||
# 缺省保持历史候选兼容;所有新 Worker 路由都会持久化该裁决。
|
||||
route_stp_eligible = str(route.get('route_decision') or '').strip() != 'needs_review'
|
||||
|
||||
min_confidence, confidence_source = _resolve_minimum_confidence(candidate)
|
||||
classification_ok = _classification_confidence_ok(
|
||||
@@ -364,19 +358,9 @@ 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,
|
||||
'route_stp_eligible': route_stp_eligible,
|
||||
'classification_confidence': classification_ok,
|
||||
'required_fields_complete': required_ok,
|
||||
'key_fields_minimum_confidence': key_confidence_ok,
|
||||
@@ -386,23 +370,15 @@ 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']),
|
||||
'xfa_unified_profile_snapshot': bool(xfa_eval['gates'].get('xfa_unified_profile_snapshot', True)),
|
||||
}
|
||||
failed = [key for key in CANDIDATE_QUALIFICATION_GATE_KEYS if not gates.get(key)]
|
||||
|
||||
# [STEP 3] 映射原因码;客户细因 / XFA 细因 / PDF 关键冲突细因 / VC 细因覆盖默认码。
|
||||
# [STEP 3] 映射原因码;客户细因 / PDF 关键冲突细因 / VC 细因覆盖默认码。
|
||||
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:
|
||||
@@ -429,8 +405,6 @@ def evaluate_candidate_qualification(
|
||||
# [STEP 3b] 证据快照追加 VC 合并概览(脱敏,仅计数)—— 注意:必须在 STEP 4 status
|
||||
# 计算之后执行,因为 status 不依赖 evidence_snapshot,保证零回归。
|
||||
evidence_snapshot = _evidence_snapshot(candidate)
|
||||
if xfa_eval.get('evidence_extra'):
|
||||
evidence_snapshot = {**evidence_snapshot, **xfa_eval['evidence_extra']}
|
||||
try:
|
||||
vc_items = collect_vc_candidate_conflicts(candidate)
|
||||
except Exception: # noqa: BLE001
|
||||
@@ -468,7 +442,7 @@ def evaluate_candidate_qualification(
|
||||
'evidence_snapshot': evidence_snapshot,
|
||||
'qualification_score': score,
|
||||
'can_auto_create': can_auto_create,
|
||||
'shadow_would_auto_create': bool(xfa_eval.get('shadow_would_auto_create')),
|
||||
'shadow_would_auto_create': False,
|
||||
'evaluator_version': CANDIDATE_QUALIFICATION_EVALUATOR_VERSION,
|
||||
'confidence_policy': confidence_policy,
|
||||
}
|
||||
@@ -655,308 +629,8 @@ def _route_decision(*, unit: Any | None, run: Any | None) -> dict[str, Any]:
|
||||
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,
|
||||
'xfa_unified_profile_snapshot': 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'
|
||||
|
||||
# [STEP 6] 统一 Profile 快照指标:视觉/证据/镜像须 100%,checksum 须与路由一致。
|
||||
# 指标来源优先 route.xfa_unified_metrics,其次 structured / parser_trace 顶层率字段。
|
||||
unified_metrics = route.get('xfa_unified_metrics')
|
||||
if not isinstance(unified_metrics, dict):
|
||||
structured = getattr(candidate, 'structured_result_json', None)
|
||||
if isinstance(structured, dict):
|
||||
nested = structured.get('_hxops_xfa_unified_metrics')
|
||||
unified_metrics = nested if isinstance(nested, dict) else None
|
||||
if not isinstance(unified_metrics, dict):
|
||||
# 兼容 parser_trace 直接携带 visual/evidence 率(阶段 6 契约)。
|
||||
trace_metrics = {
|
||||
key: parser_trace.get(key)
|
||||
for key in (
|
||||
'visual_coverage_rate',
|
||||
'evidence_retention_rate',
|
||||
'mirror_consistency_rate',
|
||||
'profile_checksum',
|
||||
)
|
||||
if parser_trace.get(key) is not None
|
||||
}
|
||||
if any(k.endswith('_rate') for k in trace_metrics):
|
||||
unified_metrics = trace_metrics
|
||||
unified_ok = True
|
||||
unified_reason = None
|
||||
if isinstance(unified_metrics, dict):
|
||||
for metric_key, reason_code in (
|
||||
('visual_coverage_rate', 'xfa_visual_coverage_insufficient'),
|
||||
('evidence_retention_rate', 'xfa_evidence_retention_insufficient'),
|
||||
('mirror_consistency_rate', 'xfa_mirror_consistency_insufficient'),
|
||||
):
|
||||
raw_rate = unified_metrics.get(metric_key)
|
||||
if raw_rate is not None and float(raw_rate) < 1.0:
|
||||
unified_ok = False
|
||||
unified_reason = reason_code
|
||||
break
|
||||
metrics_checksum = str(unified_metrics.get('profile_checksum') or '').strip()
|
||||
if unified_ok and metrics_checksum and checksum and metrics_checksum != checksum:
|
||||
unified_ok = False
|
||||
unified_reason = 'xfa_profile_checksum_mismatch'
|
||||
|
||||
gates = {
|
||||
'xfa_auto_create_policy': policy_ok,
|
||||
'xfa_profile_blind_approved': blind_ok,
|
||||
'xfa_pilot_allowlist': allowlist_ok,
|
||||
'xfa_evidence_integrity': evidence_ok,
|
||||
'xfa_unified_profile_snapshot': unified_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,
|
||||
'xfa_unified_profile_snapshot': unified_reason,
|
||||
}
|
||||
|
||||
# shadow:在其余试点门禁(除真实建单开关外)满足时记录 would_auto_create。
|
||||
shadow_base_ok = (
|
||||
blind_ok and allowlist_ok and evidence_ok and unified_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()),
|
||||
'xfa_visual_coverage_rate': (
|
||||
float(unified_metrics.get('visual_coverage_rate'))
|
||||
if isinstance(unified_metrics, dict) and unified_metrics.get('visual_coverage_rate') is not None
|
||||
else None
|
||||
),
|
||||
'xfa_evidence_retention_rate': (
|
||||
float(unified_metrics.get('evidence_retention_rate'))
|
||||
if isinstance(unified_metrics, dict) and unified_metrics.get('evidence_retention_rate') is not None
|
||||
else None
|
||||
),
|
||||
'xfa_mirror_consistency_rate': (
|
||||
float(unified_metrics.get('mirror_consistency_rate'))
|
||||
if isinstance(unified_metrics, dict) and unified_metrics.get('mirror_consistency_rate') is not None
|
||||
else None
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _build_parser_trace(*, candidate: Any, run: Any | None, unit: Any | None) -> dict[str, Any]:
|
||||
"""组装解析链路痕迹;坐标模板批准仅作治理信息,XFA 另有硬门禁。"""
|
||||
"""组装解析链路痕迹;模板取值 adapter 不改变统一资格门禁。"""
|
||||
route = _route_decision(unit=unit, run=run)
|
||||
|
||||
extraction_source = str(getattr(candidate, 'extraction_source', '') or '').strip().lower()
|
||||
|
||||
@@ -1,253 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/case_retry_auto_progress_service.py
|
||||
|
||||
用途:单个 Case 精确自动推进恢复(Case 级 retry-auto-progress API 服务层)。
|
||||
依赖:reconciliation_service.assert_case_not_blocked_manual、
|
||||
order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress、
|
||||
order_review_service.get_review_case_visible_to_user(兜底 soft_load_review_case_for_audit)、
|
||||
fulfillment_audit.record_fulfillment_audit、order_review_projection.serialize_review_case。
|
||||
逻辑:可见性 → 业务阻断双校验 → 终态检查(幂等)→ reconcile_single_case → 审计 → 返回摘要。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError
|
||||
from app.models import ShippingOrderReviewCase
|
||||
|
||||
|
||||
def case_retry_auto_progress(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
单个 Case 精确自动推进恢复入口。
|
||||
|
||||
用途(第一层):为单个指定 Review Case 执行「客户协调 + Draft 校验 + STP 入队」
|
||||
全链路自动推进,适用于 Projection primary_action.code = retry_auto_progress。
|
||||
禁止 duplicate 等业务阻断对象调用;assert_case_not_blocked_manual 前置双校验,
|
||||
防止用技术重试绕过人工裁决门禁。
|
||||
|
||||
依赖(第二层):
|
||||
- reconciliation_service.assert_case_not_blocked_manual:业务阻断前置双校验。
|
||||
- order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress:
|
||||
客户协调 + validate_draft + ensure_stp_auto_create_for_case 统一执行。
|
||||
- order_review_service.get_review_case_visible_to_user(兜底:
|
||||
order_review_draft_service.soft_load_review_case_for_audit):Case 可见性校验。
|
||||
- fulfillment_audit.record_fulfillment_audit:写 case_retry_auto_progress_invoked 审计。
|
||||
- order_review_projection.serialize_review_case:返回体附带 Case 安全投影。
|
||||
|
||||
逻辑(第三层):
|
||||
STEP 1 可见性校验 → STEP 2 业务阻断前置校验 → STEP 3 终态幂等检查
|
||||
→ STEP 4 调用 reconcile_single_case_for_auto_progress(trigger=case_api_retry_auto_progress)
|
||||
→ STEP 5 审计 → STEP 6 返回统一摘要结构。
|
||||
|
||||
Args:
|
||||
user_id: 操作人(必须为 Case owner 或 admin)。
|
||||
case_no: 目标复核 Case 编号。
|
||||
is_admin: 是否管理员(影响可见性与 serialize 投影粒度)。
|
||||
|
||||
Returns:
|
||||
``{success, operation, case_no, customer_step_status, validate_status,
|
||||
enqueue_status, job_id, idempotency_key, error, case}``。
|
||||
已终态时返回 success=True + already_confirmed=True + enqueue_status=already_confirmed,
|
||||
不抛错(幂等友好)。
|
||||
|
||||
Raises:
|
||||
NotFoundError: Case 不存在或当前用户越权。
|
||||
ConflictError (SHIPPING.RETRY_STP_BLOCKED_MANUAL): 命中 duplicate 等业务阻断,
|
||||
禁止用 retry API 绕过,引导走 reconcile-and-progress。
|
||||
"""
|
||||
import logging as _rt_logging
|
||||
_rt_log = _rt_logging.getLogger(__name__)
|
||||
|
||||
normalized_case_no = str(case_no or '').strip().upper()
|
||||
user_id_int = int(user_id or 0)
|
||||
fallback = {
|
||||
'success': False,
|
||||
'operation': 'retry_auto_progress',
|
||||
'case_no': normalized_case_no,
|
||||
'already_confirmed': False,
|
||||
'customer_step_status': 'failed',
|
||||
'validate_status': 'failed',
|
||||
'enqueue_status': 'not_eligible',
|
||||
'job_id': None,
|
||||
'idempotency_key': None,
|
||||
'error': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
|
||||
'reconcile_result': {},
|
||||
'case': None,
|
||||
}
|
||||
|
||||
# ========================================================================
|
||||
# [STEP 0] 模块级 delay import 统一包 try/except,与路由/协调器双层防护对齐。
|
||||
# 任一依赖模块 SyntaxError/ImportError → 返回结构化 fallback,
|
||||
# 不冒泡为 HTTP 500 或整批拖死协调器循环。
|
||||
# ========================================================================
|
||||
try:
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
|
||||
reconcile_single_case_for_auto_progress,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.reconciliation_service import (
|
||||
assert_case_not_blocked_manual,
|
||||
)
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress module import error case_no=%s err=%s',
|
||||
normalized_case_no, type(mod_err).__name__,
|
||||
)
|
||||
fallback['error'] = 'SHIPPING.MODULE_IMPORT_ERROR'
|
||||
fallback['import_error'] = type(mod_err).__name__
|
||||
return fallback
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress import unexpected error case_no=%s',
|
||||
normalized_case_no,
|
||||
)
|
||||
fallback['error_type'] = type(exc).__name__
|
||||
return fallback
|
||||
|
||||
try:
|
||||
# ====================================================================
|
||||
# [STEP 1] 可见性校验:优先 get_review_case_visible_to_user,
|
||||
# ImportError 兜底走 soft_load_review_case_for_audit(写审计场景同款门禁)。
|
||||
# ====================================================================
|
||||
try:
|
||||
from app.services.shipping_notice.order_review_service import (
|
||||
get_review_case_visible_to_user,
|
||||
)
|
||||
|
||||
case: ShippingOrderReviewCase = get_review_case_visible_to_user(
|
||||
normalized_case_no,
|
||||
user_id_int,
|
||||
is_admin=bool(is_admin),
|
||||
)
|
||||
except AppError:
|
||||
raise
|
||||
except Exception:
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
soft_load_review_case_for_audit,
|
||||
)
|
||||
|
||||
case = soft_load_review_case_for_audit(
|
||||
user_id=user_id_int,
|
||||
case_no=normalized_case_no,
|
||||
)
|
||||
if case is None:
|
||||
from app.core.errors import NotFoundError
|
||||
|
||||
raise NotFoundError(
|
||||
'Order review case not found',
|
||||
code='SHIPPING.REVIEW_CASE_NOT_FOUND',
|
||||
)
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 2] 业务阻断前置校验:duplicate 类必须走 reconcile-and-progress。
|
||||
# 若命中 → 抛 409 ConflictError,明确 alternative_api 指向。
|
||||
# ====================================================================
|
||||
assert_case_not_blocked_manual(case_no=normalized_case_no, case=case)
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 3] 终态检查:confirmed_task_id 或 status=confirmed/终态 → 幂等返回。
|
||||
# 不抛错,保留 already_confirmed 标识让前端区分「本次执行」与「原本已终态」。
|
||||
# ====================================================================
|
||||
_TERMINAL = frozenset({
|
||||
'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending',
|
||||
})
|
||||
already_confirmed = (
|
||||
bool(getattr(case, 'confirmed_task_id', None))
|
||||
or str(getattr(case, 'status', '') or '') in _TERMINAL
|
||||
)
|
||||
if already_confirmed:
|
||||
return {
|
||||
'success': True,
|
||||
'operation': 'retry_auto_progress',
|
||||
'case_no': normalized_case_no,
|
||||
'already_confirmed': True,
|
||||
'customer_step_status': 'skipped',
|
||||
'validate_status': 'skipped',
|
||||
'enqueue_status': 'already_confirmed_or_terminal',
|
||||
'job_id': None,
|
||||
'idempotency_key': None,
|
||||
'error': None,
|
||||
'reconcile_result': {},
|
||||
'case': serialize_review_case(case, is_admin=bool(is_admin)),
|
||||
}
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 4] 核心执行:reconcile_single_case_for_auto_progress(统一协调器)。
|
||||
# trigger=case_api_retry_auto_progress,refresh_validation=True 重跑校验。
|
||||
# ====================================================================
|
||||
reconcile_result: dict[str, Any] = reconcile_single_case_for_auto_progress(
|
||||
case=case,
|
||||
trigger='case_api_retry_auto_progress',
|
||||
refresh_validation=True,
|
||||
)
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 5] 审计:case_retry_auto_progress_invoked。
|
||||
# metadata 附带 reconcile_result 全量摘要,strict=False 降级不阻断。
|
||||
# ====================================================================
|
||||
try:
|
||||
record_fulfillment_audit(
|
||||
event_type='case_retry_auto_progress_invoked',
|
||||
aggregate_type='order_review_case',
|
||||
aggregate_id=normalized_case_no,
|
||||
action='retry_auto_progress',
|
||||
actor_type='user',
|
||||
actor_id=user_id_int,
|
||||
review_case_no=normalized_case_no,
|
||||
owner_user_id=int(getattr(case, 'owner_user_id', 0) or 0),
|
||||
result=(
|
||||
'success'
|
||||
if not reconcile_result.get('error')
|
||||
and str(reconcile_result.get('enqueue_status') or '') in {
|
||||
'queued', 'reused', 'already_queued', 'already_running', 'enqueued',
|
||||
}
|
||||
else 'failed'
|
||||
),
|
||||
metadata={'reconcile_result': dict(reconcile_result or {})},
|
||||
source='case_retry_auto_progress_service',
|
||||
strict=False,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 6] 统一返回:success + operation + case_no + reconcile_result 平铺字段
|
||||
# + serialized case 投影。
|
||||
# ====================================================================
|
||||
return {
|
||||
'success': True,
|
||||
'operation': 'retry_auto_progress',
|
||||
'case_no': normalized_case_no,
|
||||
'already_confirmed': False,
|
||||
'customer_step_status': reconcile_result.get('customer_step_status'),
|
||||
'validate_status': reconcile_result.get('validate_status'),
|
||||
'enqueue_status': reconcile_result.get('enqueue_status'),
|
||||
'job_id': reconcile_result.get('job_id'),
|
||||
'idempotency_key': reconcile_result.get('idempotency_key'),
|
||||
'error': reconcile_result.get('error'),
|
||||
'reconcile_result': dict(reconcile_result or {}),
|
||||
'case': serialize_review_case(case, is_admin=bool(is_admin)),
|
||||
}
|
||||
except (AppError, ConflictError):
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
_rt_log.exception(
|
||||
'case_retry_auto_progress execution error case_no=%s', normalized_case_no,
|
||||
)
|
||||
fallback['error_type'] = type(exc).__name__
|
||||
try:
|
||||
fallback['case'] = (
|
||||
serialize_review_case(case, is_admin=bool(is_admin))
|
||||
if 'case' in locals() and case is not None else None
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
return fallback
|
||||
@@ -2,7 +2,7 @@
|
||||
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、
|
||||
依赖: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。
|
||||
@@ -10,89 +10,11 @@ backend/app/services/shipping_notice/chat_action_handlers.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Iterator
|
||||
from typing import Iterator
|
||||
|
||||
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.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_task_ui_state_event as _shipping_ui_state_event,
|
||||
stream_text_events as _stream_text_events,
|
||||
tool_result_message as _tool_result_message,
|
||||
)
|
||||
|
||||
|
||||
def _payload_str(payload: dict[str, Any], *keys: str) -> str:
|
||||
for key in keys:
|
||||
value = str(payload.get(key) or "").strip()
|
||||
if value:
|
||||
return value
|
||||
return ""
|
||||
|
||||
|
||||
def _require_task(ctx: TurnContext):
|
||||
task_no = resolve_shipping_task_no(ctx)
|
||||
if not task_no:
|
||||
raise ValidationError("task_no is required")
|
||||
user_id = ctx.user_id
|
||||
if user_id is None:
|
||||
raise ValidationError("user context is required")
|
||||
task = get_task_for_user(task_no, user_id)
|
||||
if task is None:
|
||||
raise NotFoundError(f"Task not found: {task_no}")
|
||||
return task
|
||||
|
||||
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_MSG = (
|
||||
"该操作已迁移至工作台「我的待办」任务处理页,请从侧栏进入任务处理后再操作。"
|
||||
)
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_CODE = "SHIPPING.CHAT_FULFILLMENT_WRITE_DISABLED"
|
||||
|
||||
|
||||
def _reject_chat_fulfillment_write() -> None:
|
||||
"""
|
||||
拒绝 Chat Turn 履约写路径,引导用户改走任务工作台。
|
||||
|
||||
核心逻辑:STP 验收要求货代上传、Excel 生成、库存匹配等写操作仅在工作台执行。
|
||||
"""
|
||||
raise ValidationError(
|
||||
_CHAT_FULFILLMENT_WRITE_DISABLED_MSG,
|
||||
code=_CHAT_FULFILLMENT_WRITE_DISABLED_CODE,
|
||||
)
|
||||
|
||||
|
||||
def _format_decision_message(decision: str, result: dict[str, Any], task_no: str) -> str:
|
||||
"""对齐前端 shippingDecisionFormat.ts 的助手摘要格式。"""
|
||||
lines = [_tool_result_message(result) or "操作已完成。"]
|
||||
if decision == "reparse_inventory":
|
||||
lines.extend(["", "请点击「选择库存文件」重新上传。"])
|
||||
lines.extend(["", f"任务编号:{task_no}"])
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _match_result_payload(task_no: str, result: dict[str, Any]) -> dict[str, Any]:
|
||||
"""构建匹配结果展示 payload;按钮统一来自后端 ui_state.actions。"""
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
line_results = data.get("line_results") if isinstance(data.get("line_results"), list) else []
|
||||
shortage = data.get("shortage") if isinstance(data.get("shortage"), dict) else {}
|
||||
shortage_lines = shortage.get("lines") if isinstance(shortage.get("lines"), list) else []
|
||||
ui_state = result.get("ui_state") if isinstance(result.get("ui_state"), dict) else {}
|
||||
actions = ui_state.get("actions") if isinstance(ui_state.get("actions"), dict) else {
|
||||
"primary": None,
|
||||
"secondary": [],
|
||||
}
|
||||
return {
|
||||
"taskId": task_no,
|
||||
"match_status": data.get("match_status"),
|
||||
"line_results": line_results,
|
||||
"shortage_lines": shortage_lines,
|
||||
"actions": actions,
|
||||
}
|
||||
|
||||
|
||||
class ShippingCreateBatchFromNoticesAction:
|
||||
@@ -133,167 +55,9 @@ class ShippingCreateBatchFromIntakesAction:
|
||||
yield TurnEvent(event='step.started', data={})
|
||||
|
||||
|
||||
class ShippingSubmitDecisionAction:
|
||||
"""提交人工决策:confirm / reject / rematch / retry_rpa 等。"""
|
||||
|
||||
action_type = "shipping.submit_decision"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
decision = _payload_str(payload, "decision").lower()
|
||||
if not decision:
|
||||
raise ValidationError("decision is required")
|
||||
yield TurnEvent(event="step.started", data={"step_id": "submit_decision", "label": "提交决策..."})
|
||||
result = submit_decision({
|
||||
"task_id": task.task_no,
|
||||
"decision": decision,
|
||||
"comment": _payload_str(payload, "comment"),
|
||||
"event_source": "chat_turn",
|
||||
})
|
||||
if not isinstance(result, dict):
|
||||
raise ValidationError("invalid submit_decision response")
|
||||
if str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result) or "submit_decision failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
content = _format_decision_message(decision, result, task.task_no)
|
||||
yield TurnEvent(
|
||||
event="message.completed",
|
||||
data={
|
||||
"content": content,
|
||||
"message_type": "text",
|
||||
"payload": {
|
||||
"decision": decision,
|
||||
"task_no": task.task_no,
|
||||
"tool_result": result,
|
||||
},
|
||||
},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "submit_decision"})
|
||||
|
||||
|
||||
class ShippingGenerateExcelAction:
|
||||
action_type = "shipping.generate_excel"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingFreezeOrderAction:
|
||||
"""冻结已复核订单,使后续履约只读取不可变 Snapshot。
|
||||
|
||||
AI 触发时机:订单字段和订购客户已在对话中确认、界面显示“冻结订单”时调用。
|
||||
必须携带用户看到订单时的 expected_order_data_version;版本变化由乐观锁拒绝,要求刷新后重试。
|
||||
"""
|
||||
|
||||
action_type = "shipping.freeze_order"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
try:
|
||||
expected_version = int(payload.get("expected_order_data_version"))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError("expected_order_data_version is required") from exc
|
||||
yield TurnEvent(event="step.started", data={"step_id": "freeze_order", "label": "冻结订单..."})
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
snapshot = freeze_order_snapshot(
|
||||
task,
|
||||
actor_id=int(ctx.user_id),
|
||||
expected_order_data_version=expected_version,
|
||||
)
|
||||
db.session.commit()
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
yield from _stream_text_events(
|
||||
f"订单已冻结为履约快照 #{snapshot.id}。接下来可以继续库存处理。\n\n任务编号:{task.task_no}",
|
||||
message_type="text",
|
||||
payload={"task_no": task.task_no, "snapshot_id": snapshot.id},
|
||||
)
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "freeze_order"})
|
||||
|
||||
|
||||
class ShippingRetryUploadAction:
|
||||
action_type = "shipping.retry_upload"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingMatchInventoryAction:
|
||||
action_type = "shipping.match_inventory"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
_require_task(ctx)
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
class ShippingConfirmInventorySourceAction:
|
||||
action_type = "shipping.confirm_inventory_source"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
source_code = _payload_str(payload, "source_code", "sourceCode").upper()
|
||||
if not source_code:
|
||||
raise ValidationError("source_code is required")
|
||||
yield TurnEvent(event="step.started", data={"step_id": "confirm_inventory_source", "label": "确认库存源..."})
|
||||
result = shipping_tools.confirm_inventory_source({
|
||||
"task_id": task.task_no,
|
||||
"source_code": source_code,
|
||||
"event_source": "chat_turn",
|
||||
"_trusted_user_id": ctx.user_id,
|
||||
})
|
||||
if not isinstance(result, dict) or str(result.get("status") or "").lower() == "failed":
|
||||
raise ValidationError(_tool_result_message(result if isinstance(result, dict) else {}) or "confirm_inventory_source failed")
|
||||
refreshed = get_task_by_ref(task.task_no) or task
|
||||
yield _shipping_ui_state_event(refreshed)
|
||||
content = _tool_result_message(result) or f"已确认库存源 {source_code}。"
|
||||
yield TurnEvent(event="message.completed", data={"content": content, "message_type": "text"})
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "confirm_inventory_source"})
|
||||
|
||||
|
||||
class ShippingMarkManualUploadedAction:
|
||||
"""以 Chat 中上传的截图或回执确认人工货代上传。
|
||||
|
||||
AI 触发时机:用户明确已在货代系统上传并已通过 Chat 选择回执文件时调用。
|
||||
payload 必须含 evidence_asset_no;操作者只从当前 Chat 用户上下文取得,不能由客户端伪造。
|
||||
"""
|
||||
|
||||
action_type = "shipping.mark_manual_uploaded"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
task = _require_task(ctx)
|
||||
payload = ctx.input.payload if isinstance(ctx.input.payload, dict) else {}
|
||||
evidence_asset_no = str(payload.get("evidence_asset_no") or "").strip()
|
||||
if not evidence_asset_no:
|
||||
raise ValidationError("evidence_asset_no is required", code="SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED")
|
||||
_reject_chat_fulfillment_write()
|
||||
return
|
||||
yield # pragma: no cover — satisfies Generator type; unreachable after reject
|
||||
|
||||
|
||||
_HANDLERS = (
|
||||
ShippingCreateBatchFromNoticesAction(),
|
||||
ShippingCreateBatchFromIntakesAction(),
|
||||
ShippingSubmitDecisionAction(),
|
||||
ShippingFreezeOrderAction(),
|
||||
ShippingGenerateExcelAction(),
|
||||
ShippingRetryUploadAction(),
|
||||
ShippingMatchInventoryAction(),
|
||||
ShippingConfirmInventorySourceAction(),
|
||||
ShippingMarkManualUploadedAction(),
|
||||
)
|
||||
|
||||
for _handler in _HANDLERS:
|
||||
|
||||
@@ -1,38 +1,14 @@
|
||||
"""
|
||||
services/shipping_notice/chat_actions.py
|
||||
|
||||
用途:发货通知状态机旧模块名的向后兼容 re-export 入口。
|
||||
依赖:state_machine(ACTION_SPECS、CHECKPOINT_REGISTRY、apply_task_transition 等)、ui_state。
|
||||
逻辑:历史代码 import chat_actions;新代码应直接引用 state_machine.py / ui_state.py,本模块仅保留兼容导出。
|
||||
用途:发货通知聊天只读状态适配。
|
||||
依赖:state_machine(checkpoint 与内部状态迁移)、ui_state。
|
||||
逻辑:Chat 不再拥有动作目录或写入口;仅输出 Gate 已裁决的只读 UI State。
|
||||
"""
|
||||
|
||||
from app.services.shipping_notice.state_machine import (
|
||||
ACTION_SPECS,
|
||||
ALL_ACTION_IDS,
|
||||
ALL_CHECKPOINT_IDS,
|
||||
CHECKPOINT_REGISTRY,
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
TaskTransition,
|
||||
TaskUiState,
|
||||
action_buttons_for_checkpoint,
|
||||
apply_task_transition,
|
||||
build_action_buttons,
|
||||
build_checkpoint_catalog,
|
||||
checkpoint_for_task,
|
||||
human_options_for_checkpoint,
|
||||
human_options_for_task,
|
||||
human_options_for_task_or_checkpoint,
|
||||
inventory_source_action_buttons,
|
||||
resolve_task_ui_state,
|
||||
ui_state_for_checkpoint,
|
||||
upload_req_options_for_task,
|
||||
validate_registry,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, checkpoint_for_task, resolve_task_ui_state, validate_registry
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
# Legacy alias
|
||||
CHECKPOINT_OPTIONS = CHECKPOINT_REGISTRY
|
||||
|
||||
|
||||
def build_chat_actions_payload(task) -> dict:
|
||||
"""
|
||||
@@ -63,24 +39,10 @@ def build_chat_actions_payload(task) -> dict:
|
||||
}
|
||||
|
||||
__all__ = [
|
||||
"ACTION_SPECS",
|
||||
"ALL_ACTION_IDS",
|
||||
"ALL_CHECKPOINT_IDS",
|
||||
"CHECKPOINT_OPTIONS",
|
||||
"CHECKPOINT_REGISTRY",
|
||||
"TaskTransition",
|
||||
"TaskUiState",
|
||||
"action_buttons_for_checkpoint",
|
||||
"apply_task_transition",
|
||||
"build_action_buttons",
|
||||
"build_chat_actions_payload",
|
||||
"build_checkpoint_catalog",
|
||||
"checkpoint_for_task",
|
||||
"human_options_for_checkpoint",
|
||||
"human_options_for_task",
|
||||
"human_options_for_task_or_checkpoint",
|
||||
"resolve_task_ui_state",
|
||||
"ui_state_for_checkpoint",
|
||||
"upload_req_options_for_task",
|
||||
"validate_registry",
|
||||
]
|
||||
@@ -544,6 +544,19 @@ def _resolve_workflow_no(run: ShippingOrderProcessingRun) -> str | None:
|
||||
return str(getattr(workflow, 'workflow_no', None) or '').strip() or None
|
||||
|
||||
|
||||
def _has_current_non_terminal_review_case(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""判断该 Run 是否仍承载文件 Stream 的当前非终态 Case;历史 Case 不得影响任务入口。"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewStream
|
||||
|
||||
return db.session.query(ShippingOrderReviewCase.id).join(
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||||
).filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.status.notin_(('superseded', 'non_order')),
|
||||
).first() is not None
|
||||
|
||||
|
||||
def _resolve_task_actions(run: ShippingOrderProcessingRun) -> tuple[str | None, list[str]]:
|
||||
"""
|
||||
聚合任务级权威操作;前端禁止自行按状态推导按钮。
|
||||
@@ -578,8 +591,7 @@ def _resolve_task_actions(run: ShippingOrderProcessingRun) -> tuple[str | None,
|
||||
|
||||
# 当前 Run 已有可见 Review Case 时,任务卡不能再提供“打开订单复核”导航;
|
||||
# 用户已经位于该工作台,继续动作必须由 Case/当前 Gate 投影提供。
|
||||
review_cases = list(getattr(run, 'review_cases', None) or [])
|
||||
if any(str(getattr(case, 'status', '') or '') not in {'superseded', 'non_order'} for case in review_cases):
|
||||
if _has_current_non_terminal_review_case(run):
|
||||
actions = [action for action in actions if action not in {
|
||||
'open_review', 'enter_manual_review', 'open_order_review',
|
||||
}]
|
||||
@@ -595,6 +607,7 @@ def _resolve_task_actions(run: ShippingOrderProcessingRun) -> tuple[str | None,
|
||||
'retry_failed_documents',
|
||||
'retry_failed_attachments',
|
||||
'retry_parse',
|
||||
'reparse_batch',
|
||||
):
|
||||
if candidate in actions:
|
||||
primary = candidate
|
||||
|
||||
@@ -1,997 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/conversation_retry_auto_progress_service.py
|
||||
|
||||
用途:对话级「重试自动推进」投影与批量执行(Case STP / 正式 OT 统一决策器)。
|
||||
依赖:order_review_projection、order_stp_auto_create_service、task_retry_decision_service、
|
||||
fulfillment_audit、ShippingOrderReviewCase / ShippingOrderProcessingRun / ShippingNotice。
|
||||
逻辑:eligible 唯一依据 automation.retryable=true;建单前 Case→retry_stp_auto_create,
|
||||
正式 OT→task_retry_decision_service(与任务级 /retry 同源);不批量行库存;
|
||||
写 conversation_retry_auto_progress 汇总审计,对象级审计由既有链路写入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, NotFoundError, ValidationError
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingNotice,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewDraft,
|
||||
)
|
||||
from app.services.shipping_notice.recovery_contract import should_general_retry_be_removed
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ACTION_RETRY_AUTO_PROGRESS = 'retry_auto_progress'
|
||||
ACTION_RETRY_STP = 'retry_stp_auto_create'
|
||||
OBJECT_REVIEW_CASE = 'review_case'
|
||||
OBJECT_FORMAL_TASK = 'formal_task'
|
||||
|
||||
# [STEP P1-13] 业务阻断黑名单:duplicate 类命中即禁止对话级重试,需走 reconcile-and-progress
|
||||
_DUPLICATE_BLOCKING_CODES = frozenset({
|
||||
'duplicate_decision_required',
|
||||
'SHIPPING.NOTICE_EXACT_DUPLICATE',
|
||||
'NOTICE_EXACT_DUPLICATE',
|
||||
})
|
||||
|
||||
# [STEP P1-13-d] 允许强制重试的 manual_fallback 原因码(不含 duplicate 类)
|
||||
_FORCE_RETRYABLE_BLOCKING_CODES = frozenset({
|
||||
'STP_NOT_ELIGIBLE',
|
||||
'SHIPPING.STP_NOT_ELIGIBLE',
|
||||
'profile_schema_mismatch',
|
||||
'SHIPPING.profile_schema_mismatch',
|
||||
})
|
||||
|
||||
# needs_human 并不总是终止态:库存快照/RPA 暂态失败仍可由统一重试决策器
|
||||
# 重新触发库存准备;重复、短缺、冲突等业务裁决原因不得自动放行。
|
||||
_INVENTORY_RETRYABLE_HUMAN_CODES = frozenset({
|
||||
'inventory_snapshot_prepare_failed',
|
||||
'inventory_snapshots_pending',
|
||||
'inventory_rpa_failed',
|
||||
'inventory_rpa_exhausted',
|
||||
'inventory_file_missing',
|
||||
'rpa_failed',
|
||||
'trigger_not_claimed_missing',
|
||||
'trigger_not_claimed_timeout',
|
||||
'inventory_trigger_missing',
|
||||
'inventory_trigger_write_failed',
|
||||
# 库存门禁/匹配阻断属于可重新检查的技术中间态;对话级重试不得直接跳过。
|
||||
'inventory_candidates_required',
|
||||
'inventory_candidates_frozen_required',
|
||||
'inventory_snapshot_prepare_failed',
|
||||
'inventory_snapshots_pending',
|
||||
'inventory_match_not_ready',
|
||||
'inventory_match_incomplete',
|
||||
})
|
||||
_BUSINESS_HUMAN_CODES = frozenset({
|
||||
'inventory_shortage',
|
||||
'inventory_source_conflict',
|
||||
'inventory_source_candidates_need_human',
|
||||
'duplicate_decision_required',
|
||||
})
|
||||
|
||||
|
||||
def project_conversation_allowed_actions(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
投影对话级可执行动作(当前仅重试自动推进)。
|
||||
|
||||
核心逻辑:扫描会话下 Case;automation.retryable=true 计入 eligible_count;
|
||||
无合格对象时返回空列表(前端不渲染禁用空按钮)。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户。
|
||||
conversation_id: 会话 ID。
|
||||
|
||||
Returns:
|
||||
``[{code, eligible_count}]`` 或 ``[]``。
|
||||
"""
|
||||
normalized = str(conversation_id or '').strip()
|
||||
if not normalized or not user_id:
|
||||
return []
|
||||
eligible = _list_eligible_targets(user_id=int(user_id), conversation_id=normalized)
|
||||
if not eligible:
|
||||
return []
|
||||
return [{
|
||||
'code': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'eligible_count': len(eligible),
|
||||
}]
|
||||
|
||||
|
||||
def retry_auto_progress_for_conversation(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str,
|
||||
reason: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
对话级批量重试自动推进。
|
||||
|
||||
核心逻辑:按 conversation_id 服务端扫描;逐对象重读最新 automation 后执行;
|
||||
Case→STP(内部 refresh_validation);正式 OT→auto_progress;不批量行库存。
|
||||
|
||||
Args:
|
||||
user_id: 操作人。
|
||||
conversation_id: 会话 ID。
|
||||
reason: 可选原因(写入审计 metadata)。
|
||||
|
||||
Returns:
|
||||
``{conversation_id, summary, items}``。
|
||||
|
||||
Raises:
|
||||
ValidationError: conversation_id 为空。
|
||||
NotFoundError: 会话下无可访问对象且会话不存在于用户范围。
|
||||
"""
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
normalized = str(conversation_id or '').strip()
|
||||
if not normalized:
|
||||
raise ValidationError('conversation_id is required')
|
||||
|
||||
cases = _list_conversation_cases(user_id=int(user_id), conversation_id=normalized)
|
||||
if not cases and not _conversation_has_any_asset(user_id=int(user_id), conversation_id=normalized):
|
||||
raise NotFoundError('Conversation not found')
|
||||
|
||||
items: list[dict[str, Any]] = []
|
||||
for case in cases:
|
||||
items.append(_retry_one_case(user_id=int(user_id), case=case))
|
||||
|
||||
summary = _summarize_items(items)
|
||||
record_fulfillment_audit(
|
||||
event_type='conversation_retry_auto_progress',
|
||||
aggregate_type='shipping_conversation',
|
||||
aggregate_id=normalized,
|
||||
action='retry_auto_progress',
|
||||
actor_id=int(user_id),
|
||||
conversation_id=normalized,
|
||||
owner_user_id=int(user_id),
|
||||
result='success' if summary['failed'] == 0 else 'failure',
|
||||
metadata={
|
||||
'reason': str(reason or 'user_retry_auto_progress')[:200],
|
||||
'summary': summary,
|
||||
'items': items,
|
||||
},
|
||||
source='api',
|
||||
)
|
||||
try:
|
||||
db.session.commit()
|
||||
except Exception: # noqa: BLE001
|
||||
db.session.rollback()
|
||||
_LOGGER.exception('conversation retry audit commit failed conversation_id=%s', normalized)
|
||||
|
||||
return {
|
||||
'conversation_id': normalized,
|
||||
'summary': summary,
|
||||
'items': items,
|
||||
}
|
||||
|
||||
|
||||
def _conversation_has_any_asset(*, user_id: int, conversation_id: str) -> bool:
|
||||
"""会话是否存在属于当前用户的 Run / 正式任务(用于 404 判定)。"""
|
||||
run_exists = (
|
||||
ShippingOrderProcessingRun.query
|
||||
.filter_by(user_id=int(user_id), conversation_id=conversation_id)
|
||||
.limit(1)
|
||||
.first()
|
||||
)
|
||||
if run_exists is not None:
|
||||
return True
|
||||
notice_exists = (
|
||||
ShippingNotice.query
|
||||
.filter_by(user_id=int(user_id), conversation_id=conversation_id)
|
||||
.limit(1)
|
||||
.first()
|
||||
)
|
||||
return notice_exists is not None
|
||||
|
||||
|
||||
def _list_conversation_cases(*, user_id: int, conversation_id: str) -> list[ShippingOrderReviewCase]:
|
||||
"""
|
||||
列出会话下全部复核 Case(按 id 升序,稳定执行顺序)。
|
||||
|
||||
核心逻辑:经 ProcessingRun.conversation_id + user_id 关联,禁止跨会话/跨用户。
|
||||
"""
|
||||
return (
|
||||
db.session.query(ShippingOrderReviewCase)
|
||||
.join(
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase.run_id == ShippingOrderProcessingRun.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderProcessingRun.conversation_id == conversation_id,
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
)
|
||||
.order_by(ShippingOrderReviewCase.id.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _automation_for_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""投影 Case automation(与工作台同源)。"""
|
||||
from app.services.shipping_notice.order_review_projection import (
|
||||
_project_case_automation_status,
|
||||
_project_post_confirm_auto_progress,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_workbench_projection import (
|
||||
enrich_automation_status,
|
||||
resolve_formal_ot,
|
||||
)
|
||||
|
||||
draft = case.current_draft
|
||||
validation = dict(draft.validation_result_json or {}) if draft is not None else None
|
||||
post_confirm = _project_post_confirm_auto_progress(case)
|
||||
automation = _project_case_automation_status(
|
||||
case,
|
||||
validation=validation,
|
||||
post_confirm=post_confirm,
|
||||
)
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
return enrich_automation_status(
|
||||
automation if isinstance(automation, dict) else {},
|
||||
formal_ot=formal_ot,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
|
||||
def _formal_task_no(case: ShippingOrderReviewCase, automation: dict[str, Any]) -> str | None:
|
||||
"""解析正式 OT 编号(有则走 auto-progress,无则走 STP)。"""
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
|
||||
formal = resolve_formal_ot(case)
|
||||
if formal.get('task_missing'):
|
||||
return None
|
||||
if not formal.get('has_formal_ot'):
|
||||
return None
|
||||
task_no = str(
|
||||
automation.get('task_no')
|
||||
or getattr(case, 'confirmed_task_no', None)
|
||||
or ''
|
||||
).strip()
|
||||
return task_no or None
|
||||
|
||||
|
||||
def _list_eligible_targets(*, user_id: int, conversation_id: str) -> list[dict[str, Any]]:
|
||||
"""
|
||||
扫描可重试对象(P1-13 扩展三类 c / d / e,OR 语义)。
|
||||
|
||||
目标候选扩展说明(文档 Q8 合同测试要求):
|
||||
[STEP P1-13-e] 原有:automation.retryable=true 且未命中业务阻断(保留,不删)。
|
||||
|
||||
[STEP P1-13-c] stp_enqueue_missing:
|
||||
• Case.status IN ('unreviewed','draft','ready')
|
||||
• confirmed_task_id IS NULL
|
||||
• Draft.validation.status = 'ready' 且 can_auto_create = true
|
||||
• 最近 Job(若有)的 retryable != false
|
||||
或 blocking_reason 非 duplicate_decision_required / NOTICE_EXACT_DUPLICATE
|
||||
• 当前无 queued/running STP Job
|
||||
→ 这类对象 Draft 校验就绪但从未成功入队 STP,可通过 retry_auto_progress 自动推进。
|
||||
|
||||
[STEP P1-13-d] manual_fallback 且允许强制重试:
|
||||
• 最近 STP Job.result_json.status = failed
|
||||
• result_json.blocking_reason 非 duplicate 类
|
||||
• retryable_flag = False 但 blocking_reason 命中允许
|
||||
retry_stp_auto_create_for_case 强制重试的类型
|
||||
(如 STP_NOT_ELIGIBLE / profile_schema_mismatch,不含 duplicate)
|
||||
→ 这类对象标记了 manual_fallback,但实际是技术可恢复的原因,允许批量重试。
|
||||
|
||||
除上述条件外,全部对象必须通过 should_general_retry_be_removed 二次门禁。
|
||||
"""
|
||||
targets: list[dict[str, Any]] = []
|
||||
for case in _list_conversation_cases(user_id=user_id, conversation_id=conversation_id):
|
||||
automation = _automation_for_case(case)
|
||||
retryable_flag = bool(automation.get('retryable'))
|
||||
blocking_reason = (
|
||||
automation.get('blocking_reason')
|
||||
if isinstance(automation.get('blocking_reason'), dict)
|
||||
else None
|
||||
)
|
||||
br_code = (
|
||||
str(blocking_reason.get('code') or '')
|
||||
if isinstance(blocking_reason, dict)
|
||||
else str(blocking_reason or '')
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 取 Case 维度最近一条 STP Job(用于 c / d 条件判断)
|
||||
# 说明:Job 模型没有 reference_type / reference_key,通过 business_ref 前缀匹配。
|
||||
# STP business_ref = stp-auto:{run_no}:doc-{document_id}:v{draft_version},
|
||||
# 按 run_no+document_id 前缀可覆盖同一 Case 的所有 draft_version。
|
||||
# ------------------------------------------------------------------
|
||||
_run_no = str(getattr(getattr(case, 'run', None), 'run_no', '') or '').strip()
|
||||
_doc_id = getattr(case, 'document_id', None)
|
||||
_stp_prefix = None
|
||||
if _run_no and _doc_id is not None:
|
||||
_stp_prefix = f'stp-auto:{_run_no}:doc-{int(_doc_id)}:'
|
||||
|
||||
latest_stp_job: Job | None = None
|
||||
running_stp_exists = False
|
||||
if _stp_prefix is not None:
|
||||
latest_stp_job = (
|
||||
Job.query
|
||||
.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
|
||||
Job.business_ref.like(f"{_stp_prefix}%"),
|
||||
)
|
||||
.order_by(Job.created_at.desc())
|
||||
.first()
|
||||
)
|
||||
running_stp_exists = (
|
||||
Job.query
|
||||
.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
|
||||
Job.business_ref.like(f"{_stp_prefix}%"),
|
||||
Job.status.in_(['queued', 'running']),
|
||||
)
|
||||
.limit(1)
|
||||
.first()
|
||||
) is not None
|
||||
|
||||
latest_rj: dict[str, Any] = (
|
||||
dict(latest_stp_job.result_json)
|
||||
if latest_stp_job is not None and isinstance(latest_stp_job.result_json, dict)
|
||||
else {}
|
||||
)
|
||||
latest_retryable_flag: bool = bool(latest_rj.get('retryable', True))
|
||||
latest_br_raw = latest_rj.get('blocking_reason')
|
||||
latest_br_code = (
|
||||
str(latest_br_raw.get('code') or '')
|
||||
if isinstance(latest_br_raw, dict)
|
||||
else str(latest_br_raw or '')
|
||||
)
|
||||
latest_status: str = str(latest_rj.get('status') or '').strip().lower()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Draft 校验:status=ready + can_auto_create(c 条件需要)
|
||||
# ------------------------------------------------------------------
|
||||
draft: ShippingOrderReviewDraft | None = case.current_draft
|
||||
validation: dict[str, Any] = (
|
||||
dict(draft.validation_result_json)
|
||||
if draft is not None and isinstance(draft.validation_result_json, dict)
|
||||
else {}
|
||||
)
|
||||
draft_ready_ok = (
|
||||
draft is not None
|
||||
and str(validation.get('status') or '') == 'ready'
|
||||
and bool(validation.get('can_auto_create'))
|
||||
)
|
||||
case_status_ok = str(case.status or '') in {'unreviewed', 'draft', 'ready'}
|
||||
no_confirmed_task = not bool(case.confirmed_task_id)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# P1-13:三类候选 OR 判定
|
||||
# ------------------------------------------------------------------
|
||||
# [STEP P1-13-e] 原有 automation.retryable=true(保留,不删)
|
||||
eligible_e = retryable_flag and not should_general_retry_be_removed(
|
||||
retryable_flag=retryable_flag,
|
||||
blocking_reason=blocking_reason,
|
||||
)
|
||||
|
||||
# [STEP P1-13-c] stp_enqueue_missing:Draft 校验就绪但从未入队或可恢复
|
||||
eligible_c = (
|
||||
case_status_ok
|
||||
and no_confirmed_task
|
||||
and draft_ready_ok
|
||||
and not running_stp_exists
|
||||
and (
|
||||
latest_stp_job is None
|
||||
or latest_retryable_flag
|
||||
or latest_br_code not in _DUPLICATE_BLOCKING_CODES
|
||||
)
|
||||
)
|
||||
|
||||
# [STEP P1-13-d] manual_fallback 允许强制重试:最近失败、非 duplicate、命中允许码
|
||||
eligible_d = (
|
||||
no_confirmed_task
|
||||
and latest_stp_job is not None
|
||||
and latest_status == 'failed'
|
||||
and latest_br_code not in _DUPLICATE_BLOCKING_CODES
|
||||
and (
|
||||
latest_br_code in _FORCE_RETRYABLE_BLOCKING_CODES
|
||||
or br_code in _FORCE_RETRYABLE_BLOCKING_CODES
|
||||
)
|
||||
)
|
||||
|
||||
is_eligible = eligible_e or eligible_c or eligible_d
|
||||
if not is_eligible:
|
||||
continue
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 二次门禁:should_general_retry_be_removed(duplicate 类再次拦截)
|
||||
# ------------------------------------------------------------------
|
||||
if eligible_e and should_general_retry_be_removed(
|
||||
retryable_flag=retryable_flag,
|
||||
blocking_reason=blocking_reason,
|
||||
):
|
||||
continue
|
||||
|
||||
task_no = _formal_task_no(case, automation)
|
||||
if task_no:
|
||||
targets.append({
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'case_no': case.case_no,
|
||||
'category': (
|
||||
'e_retryable_true' if eligible_e
|
||||
else 'c_stp_enqueue_missing' if eligible_c
|
||||
else 'd_manual_fallback_force'
|
||||
),
|
||||
})
|
||||
elif not case.confirmed_task_id:
|
||||
targets.append({
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'case_no': case.case_no,
|
||||
'category': (
|
||||
'e_retryable_true' if eligible_e
|
||||
else 'c_stp_enqueue_missing' if eligible_c
|
||||
else 'd_manual_fallback_force'
|
||||
),
|
||||
})
|
||||
return targets
|
||||
|
||||
|
||||
def _skip_reason_from_automation(automation: dict[str, Any], *, task_missing: bool) -> str | None:
|
||||
"""
|
||||
根据最新 automation 返回跳过原因;可执行时返回 None。
|
||||
|
||||
核心逻辑:queued/running/completed/task_missing 跳过;needs_human 跳过;
|
||||
manual_fallback 的 owner_type=human 仍可 retryable,不得误判为人工阻断跳过。
|
||||
"""
|
||||
if task_missing:
|
||||
return 'task_missing'
|
||||
status = str(automation.get('status') or '').strip().lower()
|
||||
if status in {'queued', 'running'}:
|
||||
return 'already_running'
|
||||
if status in {'completed', 'succeeded'}:
|
||||
return 'already_completed'
|
||||
if status == 'needs_human':
|
||||
# 库存准备失败是“需要人工关注但仍可技术重试”的中间态;只有
|
||||
# retryable=true 且原因码在白名单内才允许继续到正式 OT 决策器。
|
||||
reason_candidates = (
|
||||
automation.get('reason_code'),
|
||||
automation.get('blocking_reason_code'),
|
||||
automation.get('error_code'),
|
||||
)
|
||||
reason_codes = {
|
||||
str(item or '').strip().lower()
|
||||
for item in reason_candidates
|
||||
if str(item or '').strip()
|
||||
}
|
||||
if reason_codes & _DUPLICATE_BLOCKING_CODES:
|
||||
return 'human_blocking'
|
||||
if reason_codes & _BUSINESS_HUMAN_CODES:
|
||||
return 'human_blocking'
|
||||
if bool(automation.get('retryable')) and reason_codes & _INVENTORY_RETRYABLE_HUMAN_CODES:
|
||||
return None
|
||||
# 正式 OT 的 needs_human 可能只是上一轮匹配/门禁结果;对话级“重试自动推进”
|
||||
# 的职责是重新读取当前库存事实并重新检查。只有重复订单等明确业务裁决才跳过。
|
||||
return None
|
||||
if not bool(automation.get('retryable')):
|
||||
return 'not_retryable'
|
||||
return None
|
||||
|
||||
|
||||
def _formal_task_has_retryable_inventory_trigger_failure(task_no: str) -> bool:
|
||||
"""读取正式 OT 最新逐源 Attempt,识别 Trigger 缺失等可强制重发的技术失败。"""
|
||||
try:
|
||||
from app.services.shipping_notice.task_retry_decision_service import (
|
||||
summarize_inventory_rpa_latest_attempts,
|
||||
)
|
||||
task = ShippingNotice.query.filter_by(task_no=str(task_no).strip()).first()
|
||||
if task is None:
|
||||
return False
|
||||
summary = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
|
||||
technical_codes = {
|
||||
'trigger_not_claimed_missing',
|
||||
'trigger_not_claimed_timeout',
|
||||
'inventory_trigger_missing',
|
||||
'inventory_trigger_write_failed',
|
||||
}
|
||||
return any(
|
||||
str((item or {}).get('error_code') or '').strip().lower() in technical_codes
|
||||
and str((item or {}).get('status') or '').strip().lower() in {'failed', 'exhausted'}
|
||||
for item in (summary.get('latest_attempts') or {}).values()
|
||||
)
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('inventory trigger failure lookup failed task_no=%s', task_no)
|
||||
return False
|
||||
|
||||
|
||||
def _formal_task_has_active_attempt(task_no: str) -> bool:
|
||||
"""按正式 Attempt + Job 双重事实判断任务是否真的仍在执行。"""
|
||||
try:
|
||||
from app.services.shipping_notice.task_retry_decision_service import (
|
||||
summarize_inventory_rpa_latest_attempts,
|
||||
)
|
||||
task = ShippingNotice.query.filter_by(task_no=str(task_no).strip()).first()
|
||||
if task is None:
|
||||
return False
|
||||
summary = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
|
||||
return int(summary.get('active_attempt_count') or 0) > 0
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('active attempt lookup failed task_no=%s', task_no)
|
||||
# 状态无法确认时 fail-closed,禁止重复执行。
|
||||
return True
|
||||
|
||||
|
||||
def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str, Any]:
|
||||
"""
|
||||
对单个 Case 执行重试或跳过。
|
||||
|
||||
核心逻辑(P1-13 升级):
|
||||
[STEP 1] 重新读最新 DB 状态(禁止信任传入 case 为可信快照)
|
||||
[STEP 2] 调 assert_case_not_blocked_manual 双校验;业务阻断 → skipped(而非失败)
|
||||
[STEP 3] 正式 OT → auto_progress(保持不变);
|
||||
建单前 Case → 统一调 case_retry_auto_progress(复用客户协调 + Draft 校验 + STP 入队)
|
||||
[STEP 4] 保留原有 items 返回契约(不 break 前端),新增 P1-13 分类字段放入 metadata。
|
||||
"""
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
from app.services.shipping_notice.reconciliation_service import (
|
||||
assert_case_not_blocked_manual,
|
||||
)
|
||||
from app.core.errors import ConflictError
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 1 P1-13] 重新读最新 DB 状态(不信任调用方传入的 case 对象,避免前端竞态脏读)
|
||||
# ====================================================================
|
||||
fresh_case: ShippingOrderReviewCase | None = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(id=int(case.id))
|
||||
.first()
|
||||
)
|
||||
if fresh_case is None:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'case_missing',
|
||||
'metadata': {'p13_category': None},
|
||||
}
|
||||
|
||||
automation = _automation_for_case(fresh_case)
|
||||
formal = resolve_formal_ot(fresh_case)
|
||||
task_missing = bool(formal.get('task_missing'))
|
||||
task_no = _formal_task_no(fresh_case, automation)
|
||||
|
||||
if task_no:
|
||||
skip = _skip_reason_from_automation(automation, task_missing=task_missing)
|
||||
# Automation 是展示投影,可能滞后于正式 Job。只有 Attempt 与 Job 都仍活动时
|
||||
# 才能返回 already_running;Job 已失败的 queued Attempt 是待恢复残留。
|
||||
if skip == 'already_running' and not _formal_task_has_active_attempt(task_no):
|
||||
skip = None
|
||||
# Trigger 缺失/未领取是库存 RPA 的正式技术失败事实;不得被
|
||||
# automation 投影中的历史 completed/not_retryable/human_blocking 覆盖。
|
||||
# 只要当前没有 queued/running Attempt,就必须重新进入 retry_rpa。
|
||||
if skip not in {None, 'already_running', 'task_missing'} and _formal_task_has_retryable_inventory_trigger_failure(task_no):
|
||||
# Automation 可能仍被历史 Job 的错误码污染;逐源 Attempt 是库存 Trigger
|
||||
# 的正式事实,技术领取失败必须重新进入 retry_rpa,而不是继续 skipped。
|
||||
skip = None
|
||||
if skip:
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': skip,
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
return _execute_formal_task_retry(user_id=user_id, task_no=task_no)
|
||||
|
||||
if task_missing or fresh_case.confirmed_task_id:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': fresh_case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'task_missing' if task_missing else 'already_confirmed',
|
||||
'metadata': {'p13_category': None},
|
||||
}
|
||||
|
||||
skip = _skip_reason_from_automation(automation, task_missing=False)
|
||||
if skip:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': fresh_case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': skip,
|
||||
'metadata': {'p13_category': None},
|
||||
}
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 2 P1-13] assert_case_not_blocked_manual 二次校验;业务阻断 → skipped(不回滚整批)
|
||||
# [DUPLICATE-GUARD-3] 第三道:对话级批量重试单条执行前双校验 —
|
||||
# 命中 duplicate 等阻断时单条标记 skipped,不影响其他 Case
|
||||
# ====================================================================
|
||||
try:
|
||||
assert_case_not_blocked_manual(case_no=str(fresh_case.case_no), case=fresh_case)
|
||||
except ConflictError as blocked_err:
|
||||
code = str(getattr(blocked_err, 'code', None) or 'SHIPPING.RETRY_STP_BLOCKED_MANUAL')
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': fresh_case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': code,
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'blocked_by': 'assert_case_not_blocked_manual',
|
||||
'blocking_details': getattr(blocked_err, 'details', None),
|
||||
},
|
||||
}
|
||||
|
||||
# ====================================================================
|
||||
# [STEP 3 P1-13] 统一调 case_retry_auto_progress 核心服务
|
||||
# (不再复制 STP 入队逻辑,复用客户协调 + validate + STP)
|
||||
# ====================================================================
|
||||
return _execute_case_retry_auto_progress(user_id=user_id, case=fresh_case)
|
||||
|
||||
|
||||
def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]:
|
||||
"""调用既有 STP retry;捕获业务错误为逐对象 outcome。(保留为兼容降级路径)"""
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import (
|
||||
retry_stp_auto_create_for_case,
|
||||
)
|
||||
|
||||
result = retry_stp_auto_create_for_case(user_id=user_id, case_no=case_no)
|
||||
status = str(result.get('status') or '').strip().lower()
|
||||
if status in {'queued', 'reused', 'enqueued'}:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'queued',
|
||||
'reason_code': None,
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': status or 'not_retryable',
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
except AppError as err:
|
||||
code = str(getattr(err, 'code', None) or 'SHIPPING.STP_ENQUEUE_FAILED')
|
||||
if 'ALREADY_CONFIRMED' in code:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'already_confirmed',
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
if 'NOT_ELIGIBLE' in code:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'failed',
|
||||
'reason_code': code,
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'failed',
|
||||
'reason_code': code,
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_LOGGER.exception(
|
||||
'conversation STP retry module import error case_no=%s err=%s',
|
||||
case_no, type(mod_err).__name__,
|
||||
)
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR',
|
||||
'metadata': {
|
||||
'p13_category': 'legacy_stp_retry',
|
||||
'import_error': type(mod_err).__name__,
|
||||
},
|
||||
}
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('conversation STP retry failed case_no=%s', case_no)
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case_no,
|
||||
'action': ACTION_RETRY_STP,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.STP_ENQUEUE_FAILED',
|
||||
'metadata': {'p13_category': 'legacy_stp_retry'},
|
||||
}
|
||||
|
||||
|
||||
def _execute_case_retry_auto_progress(
|
||||
*,
|
||||
user_id: int,
|
||||
case: ShippingOrderReviewCase,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
P1-13 统一执行入口:调 case_retry_auto_progress 核心服务(客户协调 + validate + STP)。
|
||||
|
||||
保留原有 items 返回契约(object_type / object_ref / action / outcome / reason_code),
|
||||
新增 P1-13 分类字段与执行摘要放入 metadata,不 break 前端。
|
||||
"""
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.case_retry_auto_progress_service import (
|
||||
case_retry_auto_progress,
|
||||
)
|
||||
|
||||
result = case_retry_auto_progress(
|
||||
user_id=int(user_id),
|
||||
case_no=str(case.case_no),
|
||||
is_admin=False,
|
||||
)
|
||||
except AppError as err:
|
||||
code = str(getattr(err, 'code', None) or 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED')
|
||||
if 'ALREADY_CONFIRMED' in code:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'already_confirmed',
|
||||
'metadata': {'p13_category': None, 'error': code},
|
||||
}
|
||||
if 'BLOCKED_MANUAL' in code or 'RECONCILE' in code:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': code,
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'blocked_by': 'case_retry_auto_progress_assertion',
|
||||
'details': getattr(err, 'details', None),
|
||||
},
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': code,
|
||||
'metadata': {'p13_category': None, 'error': code},
|
||||
}
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_LOGGER.exception(
|
||||
'conversation case_retry_auto_progress module import error case_no=%s err=%s',
|
||||
case.case_no, type(mod_err).__name__,
|
||||
)
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR',
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'import_error': type(mod_err).__name__,
|
||||
},
|
||||
}
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('conversation case_retry_auto_progress failed case_no=%s', case.case_no)
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
|
||||
'metadata': {'p13_category': None, 'error': 'unexpected_exception'},
|
||||
}
|
||||
|
||||
# 解析执行结果:success + enqueue_status → outcome
|
||||
enqueue_status = str(result.get('enqueue_status') or '').strip().lower()
|
||||
if result.get('already_confirmed'):
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': None,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'already_confirmed',
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'enqueue_status': enqueue_status,
|
||||
'already_confirmed': True,
|
||||
},
|
||||
}
|
||||
queued_set = {
|
||||
'queued', 'reused', 'already_queued', 'already_running', 'enqueued',
|
||||
}
|
||||
if enqueue_status in queued_set:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'queued',
|
||||
'reason_code': None,
|
||||
'metadata': {
|
||||
'p13_category': result.get('case_no'),
|
||||
'customer_step_status': result.get('customer_step_status'),
|
||||
'validate_status': result.get('validate_status'),
|
||||
'enqueue_status': enqueue_status,
|
||||
'job_id': result.get('job_id'),
|
||||
'idempotency_key': result.get('idempotency_key'),
|
||||
},
|
||||
}
|
||||
if enqueue_status in {'already_confirmed_or_terminal', 'not_eligible'}:
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': enqueue_status,
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'enqueue_status': enqueue_status,
|
||||
'error': result.get('error'),
|
||||
},
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_REVIEW_CASE,
|
||||
'object_ref': case.case_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed' if result.get('error') else 'skipped',
|
||||
'reason_code': enqueue_status or (result.get('error') and 'execution_error') or 'not_retryable',
|
||||
'metadata': {
|
||||
'p13_category': None,
|
||||
'enqueue_status': enqueue_status,
|
||||
'error': result.get('error'),
|
||||
'customer_step_status': result.get('customer_step_status'),
|
||||
'validate_status': result.get('validate_status'),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
|
||||
"""正式 OT 重试:委托统一决策器(与任务级 /retry 同源)。metadata 追加 P1-13 分类不 break 前端。"""
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
|
||||
|
||||
result = retry_task_with_decision(
|
||||
task_no=str(task_no),
|
||||
user_id=int(user_id),
|
||||
scope='task',
|
||||
reason='conversation_retry_auto_progress',
|
||||
trigger='conversation_retry',
|
||||
continue_auto_progress=False,
|
||||
)
|
||||
except AppError as err:
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': str(getattr(err, 'code', None) or 'SHIPPING.AUTO_PROGRESS_FAILED'),
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
except (SyntaxError, ImportError) as mod_err:
|
||||
_LOGGER.exception(
|
||||
'conversation task retry module import error task_no=%s err=%s',
|
||||
task_no, type(mod_err).__name__,
|
||||
)
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR',
|
||||
'metadata': {
|
||||
'p13_category': 'e_formal_ot',
|
||||
'import_error': type(mod_err).__name__,
|
||||
},
|
||||
}
|
||||
except Exception: # noqa: BLE001
|
||||
_LOGGER.exception('conversation task retry failed task_no=%s', task_no)
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': ACTION_RETRY_AUTO_PROGRESS,
|
||||
'outcome': 'failed',
|
||||
'reason_code': 'SHIPPING.AUTO_PROGRESS_FAILED',
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
|
||||
status = str((result or {}).get('status') or '').strip().lower()
|
||||
action = str((result or {}).get('action') or '') or ACTION_RETRY_AUTO_PROGRESS
|
||||
if status == 'needs_human':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
# 对话级重试已实际重新检查;门禁仍阻断时应归为失败/需处理,
|
||||
# 不能计入“已跳过”,否则用户无法区分未执行与执行后被阻断。
|
||||
'outcome': 'failed',
|
||||
'reason_code': str((result or {}).get('reason_code') or 'human_blocking'),
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
if status == 'failed':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'failed',
|
||||
'reason_code': str((result or {}).get('reason_code') or status),
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
if action == 'noop' and str((result or {}).get('reason_code') or '') == 'already_running':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': 'already_running',
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
if action == 'noop' and status == 'completed':
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': str((result or {}).get('reason_code') or 'already_completed'),
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
if status in {'running', 'completed', 'queued'}:
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'queued',
|
||||
'reason_code': None,
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
return {
|
||||
'object_type': OBJECT_FORMAL_TASK,
|
||||
'object_ref': task_no,
|
||||
'action': action,
|
||||
'outcome': 'skipped',
|
||||
'reason_code': str((result or {}).get('reason_code') or status or 'not_retryable'),
|
||||
'metadata': {'p13_category': 'e_formal_ot'},
|
||||
}
|
||||
|
||||
|
||||
def _summarize_items(items: list[dict[str, Any]]) -> dict[str, int]:
|
||||
"""汇总逐对象结果。"""
|
||||
retried = skipped = failed = blocked = 0
|
||||
for item in items:
|
||||
outcome = str(item.get('outcome') or '').strip().lower()
|
||||
if outcome == 'queued':
|
||||
retried += 1
|
||||
elif outcome == 'failed':
|
||||
failed += 1
|
||||
elif outcome == 'blocked':
|
||||
blocked += 1
|
||||
else:
|
||||
skipped += 1
|
||||
return {
|
||||
'total': len(items),
|
||||
'retried': retried,
|
||||
'skipped': skipped,
|
||||
'failed': failed,
|
||||
'blocked': blocked,
|
||||
}
|
||||
@@ -182,7 +182,6 @@ def customer_gate_tool_response(task: ShippingNotice, *, operation: str) -> dict
|
||||
task=task,
|
||||
message='标准客户尚未确认,请先选择正式客户后再继续。',
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=['confirm_customer'],
|
||||
checkpoint='customer_review',
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=[
|
||||
@@ -216,7 +215,6 @@ def confirm_customer(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task=task,
|
||||
message='请选择标准客户。',
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=['confirm_customer'],
|
||||
checkpoint='customer_review',
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
@@ -152,7 +152,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message="当前库存已解除关联,请重新选择库存文件。系统将按库存站点已发布的解析方案校验并解析。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint="upload_req",
|
||||
human_options=["upload_inventory_file", "retry_rpa"],
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
@@ -282,7 +281,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task=task,
|
||||
message="库存源尚未确定,请先完成库存源确认。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
@@ -332,7 +330,6 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"destination_candidates": adjudication.destination_candidates,
|
||||
},
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
human_options=resolve_task_ui_state(task).human_options,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
if not task.inventory_lines_json:
|
||||
|
||||
@@ -15,7 +15,8 @@ from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
@@ -24,6 +25,7 @@ from app.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderProcessingUnit,
|
||||
)
|
||||
from app.services.file_assets.service import (
|
||||
create_derived_file_asset_from_bytes,
|
||||
@@ -49,6 +51,25 @@ from app.services.shipping_notice.order_candidate_builder import (
|
||||
BODY_ATTACHMENT_KEY = 'body'
|
||||
|
||||
|
||||
def _json_safe_value(value: Any) -> Any:
|
||||
"""将动态订单字段结果归一化为 SQLAlchemy JSON 可持久化的原生值。
|
||||
|
||||
邮件正文补充表会按冻结 Schema 将日期/金额转换为 ``date``/``Decimal``;
|
||||
这些类型可参与业务裁决,但不能直接写入 PostgreSQL JSON 字段。
|
||||
"""
|
||||
if value is None or isinstance(value, (str, int, float, bool)):
|
||||
return value
|
||||
if isinstance(value, (date, datetime)):
|
||||
return value.isoformat()
|
||||
if isinstance(value, Decimal):
|
||||
return format(value, 'f')
|
||||
if isinstance(value, dict):
|
||||
return {str(key): _json_safe_value(item) for key, item in value.items()}
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [_json_safe_value(item) for item in value]
|
||||
raise TypeError(f'Unsupported JSON value: {type(value).__name__}')
|
||||
|
||||
|
||||
def generate_candidate_no() -> str:
|
||||
"""生成 SNC-YYYYMMDD-XXXXXXXX 格式候选编号。"""
|
||||
return f"SNC-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
@@ -567,7 +588,9 @@ def persist_documents_and_candidates(
|
||||
schema_definition=definition,
|
||||
)
|
||||
supplement['document_id'] = int(body_doc.id)
|
||||
body_doc.order_extraction_result_json = {'email_supplement': supplement}
|
||||
body_doc.order_extraction_result_json = _json_safe_value({
|
||||
'email_supplement': supplement,
|
||||
})
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
append_shipping_audit_event(
|
||||
event_type='email_supplement_parsed',
|
||||
@@ -757,13 +780,31 @@ def persist_documents_and_candidates(
|
||||
)
|
||||
.all()
|
||||
)
|
||||
stale_ids = {int(d.id) for d in stale_docs}
|
||||
# 已冻结的 Processing Unit 以 Document 为不可变输入锚点。重物化时附件目录可能
|
||||
# 已变化,但在该 Unit 完成、取消或由后继 Run 接管前,不能删除其 Document;否则
|
||||
# 会破坏 Run 审计并触发 document/intake 复合外键,导致整个 Candidate 阶段回滚。
|
||||
referenced_document_ids = {
|
||||
int(row.document_id)
|
||||
for row in (
|
||||
db.session.query(ShippingOrderProcessingUnit.document_id)
|
||||
.filter(
|
||||
ShippingOrderProcessingUnit.intake_id == int(intake.id),
|
||||
ShippingOrderProcessingUnit.document_id.in_([int(doc.id) for doc in stale_docs]),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
}
|
||||
deletable_stale_docs = [
|
||||
document for document in stale_docs
|
||||
if int(document.id) not in referenced_document_ids
|
||||
]
|
||||
stale_ids = {int(d.id) for d in deletable_stale_docs}
|
||||
if 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:
|
||||
for doc in deletable_stale_docs:
|
||||
_release_document_asset(int(doc.asset_id) if doc.asset_id else None)
|
||||
db.session.delete(doc)
|
||||
|
||||
|
||||
@@ -54,10 +54,11 @@ ON_DEMAND_COORDINATE_COMPACTION_ISSUES = frozenset({
|
||||
|
||||
|
||||
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'
|
||||
"""判断布局快照是否可直接使用,或可由原 PDF 在订单识别时按需恢复。
|
||||
|
||||
所有 PDF 一律以共同坐标证据判断;没有视觉 Layout 的历史快照会安全重解析,
|
||||
不能因其曾携带某个值源 capability 而被当成可复用的业务路径。
|
||||
"""
|
||||
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
|
||||
return True
|
||||
evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {}
|
||||
@@ -209,6 +210,99 @@ def current_layout_snapshot(document: ShippingOrderDocument) -> dict[str, Any] |
|
||||
return dict(version.payload_json)
|
||||
|
||||
|
||||
def _bind_inline_xfa_structure_analysis(
|
||||
*,
|
||||
document: ShippingOrderDocument,
|
||||
version: ShippingDocumentLayoutVersion,
|
||||
) -> None:
|
||||
"""本地化派生 Layout 的 XFA Analysis,禁止新快照引用旧 Layout 的分析主键。
|
||||
|
||||
坐标/OCR 补证会从现有 Layout 派生一个新版本。XFA Analysis 是
|
||||
``document_id + layout_version_id`` 共同冻结的正式值源证据,不能把旧版本的
|
||||
``structure_analysis_id`` 原样带到新版本;否则样本重新冻结时会因身份不一致
|
||||
fail-closed。首次写入(Analysis 尚未绑定 Layout)只回填本身,派生写入则
|
||||
克隆安全摘要并将新 ID 写回该 Layout。
|
||||
"""
|
||||
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
|
||||
capability = payload.get('xfa_capability') if isinstance(payload.get('xfa_capability'), dict) else {}
|
||||
raw_analysis_id = capability.get('structure_analysis_id')
|
||||
if raw_analysis_id in (None, ''):
|
||||
return
|
||||
try:
|
||||
analysis = db.session.get(ShippingXfaStructureAnalysis, int(raw_analysis_id))
|
||||
except (TypeError, ValueError):
|
||||
return
|
||||
if analysis is None or int(analysis.document_id) != int(document.id):
|
||||
return
|
||||
if str(analysis.analysis_status or '') != 'ready':
|
||||
return
|
||||
if str(analysis.source_content_hash or '').lower() != str(document.content_hash or '').lower():
|
||||
return
|
||||
if analysis.layout_version_id in (None, ''):
|
||||
analysis.layout_version_id = int(version.id)
|
||||
return
|
||||
if int(analysis.layout_version_id) == int(version.id):
|
||||
return
|
||||
|
||||
# [STEP 1] 派生 Layout 不能窃取旧 Analysis 的 Layout 身份;复制的仅是脱敏结构摘要。
|
||||
localized = ShippingXfaStructureAnalysis(
|
||||
document_id=int(document.id),
|
||||
layout_version_id=int(version.id),
|
||||
source_content_hash=str(document.content_hash or '').lower(),
|
||||
document_kind=analysis.document_kind,
|
||||
analysis_status='ready',
|
||||
template_packet_checksum=analysis.template_packet_checksum,
|
||||
datasets_packet_checksum=analysis.datasets_packet_checksum,
|
||||
dataset_structure_fingerprint=analysis.dataset_structure_fingerprint,
|
||||
packet_checksums_json=dict(analysis.packet_checksums_json or {}),
|
||||
stats_json=dict(analysis.stats_json or {}),
|
||||
security_summary_json=dict(analysis.security_summary_json or {}),
|
||||
tree_summary_json=dict(analysis.tree_summary_json or {}),
|
||||
error_code=None,
|
||||
route_reason=analysis.route_reason,
|
||||
encrypted_snapshot_ref=None,
|
||||
parser_identity=analysis.parser_identity,
|
||||
contract_version=analysis.contract_version,
|
||||
finished_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(localized)
|
||||
db.session.flush()
|
||||
|
||||
# [STEP 2] 重算 checksum,保证 Layout 载荷和结构分析 ID 仍是同一不可变身份。
|
||||
localized_capability = dict(capability)
|
||||
localized_capability['structure_analysis_id'] = int(localized.id)
|
||||
localized_payload = dict(payload)
|
||||
localized_payload['xfa_capability'] = localized_capability
|
||||
if isinstance(localized_payload.get('capability'), dict):
|
||||
localized_payload['capability'] = {
|
||||
**dict(localized_payload['capability']),
|
||||
'structure_analysis_id': int(localized.id),
|
||||
}
|
||||
checksum, payload_size = canonical_layout_payload(localized_payload)
|
||||
version.payload_json = localized_payload
|
||||
version.payload_checksum = checksum
|
||||
version.payload_size_bytes = payload_size
|
||||
version.quality_json = (
|
||||
dict(localized_payload['capability'])
|
||||
if isinstance(localized_payload.get('capability'), dict) else version.quality_json
|
||||
)
|
||||
|
||||
|
||||
def ensure_inline_xfa_structure_analysis_identity(
|
||||
*,
|
||||
document: ShippingOrderDocument,
|
||||
version: ShippingDocumentLayoutVersion,
|
||||
) -> ShippingDocumentLayoutVersion:
|
||||
"""确保当前 inline Layout 的 XFA Analysis 与其自身版本号一致。
|
||||
|
||||
Profile 冻结会直接读取当前 ready Layout;历史坐标补证版本即使已存在,也必须
|
||||
在该正式冻结边界完成 analysis identity 本地化,不能依赖再次生成同一快照。
|
||||
"""
|
||||
if str(version.status or '') in CURRENT_LAYOUT_STATUSES:
|
||||
_bind_inline_xfa_structure_analysis(document=document, version=version)
|
||||
return version
|
||||
|
||||
|
||||
def record_inline_layout_snapshot(
|
||||
document: ShippingOrderDocument,
|
||||
snapshot: dict[str, Any],
|
||||
@@ -248,6 +342,9 @@ def record_inline_layout_snapshot(
|
||||
)
|
||||
if existing is not None:
|
||||
if existing.status in CURRENT_LAYOUT_STATUSES:
|
||||
# 历史坐标补证快照可能在 XFA Analysis 身份本地化修复前已经落库;
|
||||
# 复用时补齐同一 Layout 的 Analysis,避免冻结样本永久卡在旧 identity。
|
||||
ensure_inline_xfa_structure_analysis_identity(document=document, version=existing)
|
||||
document.current_layout_version_id = existing.id
|
||||
return existing
|
||||
|
||||
@@ -289,6 +386,8 @@ def record_inline_layout_snapshot(
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
if status in CURRENT_LAYOUT_STATUSES:
|
||||
ensure_inline_xfa_structure_analysis_identity(document=document, version=version)
|
||||
if status in CURRENT_LAYOUT_STATUSES:
|
||||
document.current_layout_version_id = version.id
|
||||
return version
|
||||
@@ -411,7 +510,11 @@ def _clone_reusable_layout_for_document(
|
||||
target_analysis: ShippingXfaStructureAnalysis | None = None
|
||||
source_analysis: ShippingXfaStructureAnalysis | None = None
|
||||
reject_reason: str | None = None
|
||||
if str(copied_payload.get('provider') or '') == 'xfa':
|
||||
# XFA structure analysis is document-scoped evidence. Both the retired
|
||||
# XFA-only snapshot format and the current shared visual Layout carry it in
|
||||
# xfa_capability, so reuse must localize it by capability rather than by
|
||||
# the layout provider.
|
||||
if isinstance(copied_payload.get('xfa_capability'), dict):
|
||||
capability = (
|
||||
copied_payload.get('xfa_capability')
|
||||
if isinstance(copied_payload.get('xfa_capability'), dict)
|
||||
|
||||
@@ -38,7 +38,7 @@ class OrderFieldExtraction(BaseModel):
|
||||
scope: Literal['header']
|
||||
value: Any = None
|
||||
status: Literal['confirmed', 'needs_review', 'unavailable']
|
||||
source: Literal['pdf_coordinate', 'ocr_coordinate'] | None = None
|
||||
source: Literal['pdf_coordinate', 'ocr_coordinate', 'acroform_widget'] | None = None
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
anchor_bbox: LayoutBBox | None = None
|
||||
value_bbox: LayoutBBox | None = None
|
||||
@@ -48,7 +48,7 @@ class OrderFieldExtraction(BaseModel):
|
||||
|
||||
def extract_order_fields(
|
||||
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_evidence: dict[str, Any],
|
||||
coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False,
|
||||
) -> list[OrderFieldExtraction]:
|
||||
"""
|
||||
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
|
||||
@@ -57,18 +57,26 @@ def extract_order_fields(
|
||||
profile: Run 冻结的坐标模板,不得包含待重新绑定字段。
|
||||
schema_fields: 以 stable field_id 为键的冻结启用 Schema 字段。
|
||||
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
|
||||
allow_ocr_preview_fallback: 仅管理端视觉样本值预览可启用。它允许已确认的
|
||||
PDF 坐标字段临时读取 OCR 候选,但结果仍固定为 needs_review,不能用于正式运行时取值。
|
||||
|
||||
Returns:
|
||||
每个已绑定布局对应一个候选,按模板声明顺序返回。
|
||||
"""
|
||||
return [
|
||||
_extract_layout(layout=layout, schema_fields=schema_fields, coordinate_evidence=coordinate_evidence)
|
||||
_extract_layout(
|
||||
layout=layout,
|
||||
schema_fields=schema_fields,
|
||||
coordinate_evidence=coordinate_evidence,
|
||||
allow_ocr_preview_fallback=allow_ocr_preview_fallback,
|
||||
)
|
||||
for layout in profile.order_field_layouts
|
||||
]
|
||||
|
||||
|
||||
def _extract_layout(
|
||||
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
|
||||
allow_ocr_preview_fallback: bool = False,
|
||||
) -> OrderFieldExtraction:
|
||||
"""处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。"""
|
||||
config = schema_fields.get(layout.field_id)
|
||||
@@ -104,7 +112,12 @@ def _extract_layout(
|
||||
|
||||
results: list[OrderFieldExtraction] = []
|
||||
for page_no, glyphs, width, height, source in candidates:
|
||||
if not _source_allowed(layout, config=config, source=source):
|
||||
if not _source_allowed(
|
||||
layout,
|
||||
config=config,
|
||||
source=source,
|
||||
allow_ocr_preview_fallback=allow_ocr_preview_fallback,
|
||||
):
|
||||
results.append(_unavailable(layout, 'order_field_coordinate_source_not_allowed', page_no=page_no, source=source))
|
||||
continue
|
||||
if layout.anchor is None:
|
||||
@@ -441,8 +454,16 @@ def _layout_applies_to_page(layout: OrderFieldLayout, page_no: int) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def _source_allowed(layout: OrderFieldLayout, *, config: dict[str, Any], source: str) -> bool:
|
||||
"""同时满足布局和 Schema 的坐标来源授权,OCR 永远不提升为 confirmed。"""
|
||||
def _source_allowed(
|
||||
layout: OrderFieldLayout,
|
||||
*,
|
||||
config: dict[str, Any],
|
||||
source: str,
|
||||
allow_ocr_preview_fallback: bool = False,
|
||||
) -> bool:
|
||||
"""同时满足布局和 Schema 的坐标来源授权;仅样本预览可临时展示 OCR 候选。"""
|
||||
if source == 'ocr_coordinate' and allow_ocr_preview_fallback:
|
||||
return True
|
||||
allowed = set(config.get('allowed_sources') or [])
|
||||
if source not in allowed:
|
||||
return False
|
||||
|
||||
@@ -254,6 +254,11 @@ class TableRegionProfile(OrderProfileModel):
|
||||
line_start_field_code: str = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
# 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。
|
||||
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows'
|
||||
# 人工确认本表区自动标注时采用的视觉几何来源;仅用于审计、盲测和冲突复核,
|
||||
# 不参与普通 PDF/XFA 的正式字段取值,更不能替代 XFA datasets。
|
||||
visual_evidence_source: Literal[
|
||||
'pdf_coordinate', 'ocr_coordinate', 'opencv_geometry', 'acroform_widget_geometry',
|
||||
] | None = None
|
||||
header_layouts: list[HeaderLayout] = Field(default_factory=list)
|
||||
line_layouts: list[LineLayout] = Field(default_factory=list)
|
||||
continuation_rule: ContinuationRule = Field(default_factory=ContinuationRule)
|
||||
|
||||
@@ -4,7 +4,8 @@ services/shipping_notice/document_layout/order_profile_extractors.py
|
||||
用途:执行订单坐标 Profile v2 的有限注册字段解析器。
|
||||
依赖:订单料号复合解析与数值解析。
|
||||
逻辑:坐标重建先取得管理员框选的原文,本模块再将其安全拆成固定业务字段;任何拆分失败均不返回部分字段。
|
||||
另提供 XFA/坐标共用的 ``unit_price / price_unit``(如 ``898.72 / 1``)确定性拆分。
|
||||
单价、价格单位等业务字段必须由管理员分别框选,或通过 XFA 显式拆分规则映射;
|
||||
本模块不按值形态隐式生成 Schema 字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,44 +20,9 @@ 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()
|
||||
@@ -92,8 +58,6 @@ 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 {}
|
||||
|
||||
|
||||
@@ -109,6 +73,4 @@ 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()
|
||||
@@ -672,24 +672,11 @@ def _observe_layout_features(
|
||||
if width > 0 and height > 0:
|
||||
aspect_ratio = width / height
|
||||
|
||||
primary_bbox = None
|
||||
if tables:
|
||||
bbox = tables[0].get('bbox') if isinstance(tables[0].get('bbox'), dict) else None
|
||||
if isinstance(bbox, dict):
|
||||
try:
|
||||
primary_bbox = [
|
||||
float(bbox.get('x0', 0)), float(bbox.get('y0', 0)),
|
||||
float(bbox.get('x1', 1)), float(bbox.get('y1', 1)),
|
||||
]
|
||||
if max(primary_bbox) > 1 and isinstance(first_page, dict):
|
||||
page_width, page_height = float(first_page.get('width') or 0), float(first_page.get('height') or 0)
|
||||
if page_width > 0 and page_height > 0:
|
||||
primary_bbox = [
|
||||
primary_bbox[0] / page_width, primary_bbox[1] / page_height,
|
||||
primary_bbox[2] / page_width, primary_bbox[3] / page_height,
|
||||
]
|
||||
except (TypeError, ValueError):
|
||||
primary_bbox = None
|
||||
# [STEP 1] 与签名生成一致,按签名表区选择实际业务表;MinerU 的 tables[0]
|
||||
# 可能是抬头/元数据表,不能作为运行时默认主表。
|
||||
primary_bbox = _select_signature_primary_table_bbox(
|
||||
tables=tables, pages=pages, signature=signature,
|
||||
)
|
||||
|
||||
header_tokens, column_centers, column_width_ratios = _observe_primary_table_header(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
@@ -712,6 +699,60 @@ def _observe_layout_features(
|
||||
}
|
||||
|
||||
|
||||
def _select_signature_primary_table_bbox(
|
||||
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
|
||||
) -> list[float] | None:
|
||||
"""按签名表区选取重叠最大的实际表;无可用签名时才保持首表兼容行为。"""
|
||||
normalized_tables: list[list[float]] = []
|
||||
for table in tables:
|
||||
page = pages.get(str(table.get('page_no') or 1)) or pages.get(table.get('page_no') or 1)
|
||||
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
|
||||
if not isinstance(page, dict) or not isinstance(bbox, dict):
|
||||
continue
|
||||
try:
|
||||
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if raw[2] <= raw[0] or raw[3] <= raw[1] or width <= 0 or height <= 0:
|
||||
continue
|
||||
normalized_tables.append(raw if max(raw) <= 1 else [
|
||||
raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height,
|
||||
])
|
||||
if not normalized_tables:
|
||||
return None
|
||||
patterns = [
|
||||
item for item in ((signature or {}).get('table_patterns') or [])
|
||||
if isinstance(item, dict)
|
||||
and isinstance(item.get('bbox'), dict)
|
||||
and isinstance(item['bbox'].get('median'), list)
|
||||
and len(item['bbox']['median']) == 4
|
||||
]
|
||||
if not patterns:
|
||||
return normalized_tables[0]
|
||||
best_bbox = normalized_tables[0]
|
||||
best_overlap = -1.0
|
||||
for candidate in normalized_tables:
|
||||
for pattern in patterns:
|
||||
try:
|
||||
expected = [float(value) for value in pattern['bbox']['median']]
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
overlap = _bbox_overlap(expected, candidate)
|
||||
if overlap > best_overlap:
|
||||
best_overlap, best_bbox = overlap, candidate
|
||||
return best_bbox
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
_HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
|
||||
|
||||
|
||||
|
||||
@@ -43,53 +43,6 @@ 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
|
||||
@@ -124,16 +77,6 @@ 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:
|
||||
_record_xfa_page_count(xfa_snapshot, diagnostics=diagnostics)
|
||||
return xfa_snapshot
|
||||
native_pages: list[Any] | None = None
|
||||
if extension == '.pdf' and document_id and content_hash:
|
||||
try:
|
||||
@@ -408,32 +351,6 @@ def _diagnostics_from_maps(
|
||||
)
|
||||
|
||||
|
||||
def _record_xfa_page_count(
|
||||
snapshot: dict[str, Any],
|
||||
*,
|
||||
diagnostics: LayoutJobDiagnostics | None,
|
||||
) -> None:
|
||||
"""
|
||||
XFA 早退路径仅回填可安全取得的 page_count,不引入 OCR/OpenCV 逻辑。
|
||||
|
||||
Args:
|
||||
snapshot: XFA layout 快照。
|
||||
diagnostics: 可选诊断上下文。
|
||||
"""
|
||||
if diagnostics is None:
|
||||
return
|
||||
capability = snapshot.get('xfa_capability') if isinstance(snapshot.get('xfa_capability'), dict) else {}
|
||||
page_count = capability.get('page_count')
|
||||
if page_count is None:
|
||||
pages = snapshot.get('pages')
|
||||
if isinstance(pages, list):
|
||||
page_count = len(pages)
|
||||
try:
|
||||
diagnostics.counts['page_count'] = int(page_count or 0)
|
||||
except (TypeError, ValueError):
|
||||
diagnostics.counts['page_count'] = 0
|
||||
|
||||
|
||||
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,
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/document_layout/xfa_acroform.py
|
||||
|
||||
用途:读取 AcroForm 字段值/Widget 几何,并生成与 datasets 叶子节点的对账与路径候选。
|
||||
依赖:pypdf、xfa_dataset.XfaDatasetAnalysis、xfa_contract.hash_data_path。
|
||||
逻辑:由 xfa_analysis、xfa_visual_binding、xfa_validation 调用;按短名聚合多实例值
|
||||
逻辑:由 xfa_analysis、datasets 末端映射和 xfa_validation 调用;按短名聚合多实例值
|
||||
供行对齐对账;Widget 摘要含页码与归一化 bbox,供统一视觉绑定评分。
|
||||
"""
|
||||
|
||||
|
||||
@@ -307,6 +307,23 @@ def persist_xfa_structure_analysis(
|
||||
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)
|
||||
# [STEP 2] Layout 与 datasets identity 必须落在同一冻结快照;仅更新 outcome
|
||||
# 会导致后续 Profile/盲测按 Layout 重放时找不到本次 structure analysis。
|
||||
if layout_version_id:
|
||||
layout_version = db.session.get(ShippingDocumentLayoutVersion, int(layout_version_id))
|
||||
if layout_version is not None:
|
||||
payload = dict(layout_version.payload_json or {})
|
||||
capability_payload = payload.get('xfa_capability')
|
||||
if not isinstance(capability_payload, dict):
|
||||
capability_payload = dict(payload.get('capability') or {})
|
||||
capability_payload['structure_analysis_id'] = int(record.id)
|
||||
payload['xfa_capability'] = capability_payload
|
||||
if isinstance(payload.get('capability'), dict):
|
||||
payload['capability'] = {
|
||||
**dict(payload['capability']),
|
||||
'structure_analysis_id': int(record.id),
|
||||
}
|
||||
layout_version.payload_json = payload
|
||||
outcome.analysis_record = record
|
||||
return record
|
||||
|
||||
|
||||
@@ -2,12 +2,12 @@
|
||||
services/shipping_notice/document_layout/xfa_contract.py
|
||||
|
||||
用途:冻结 XFA 数据路径 Profile 契约——template_mode、受控路径语法、结构指纹、
|
||||
统一字段 binding(value_binding + visual_binding)、鉴别联合 definition、
|
||||
统一字段 binding(共同视觉 field_layout_id + value_binding)、鉴别联合 definition、
|
||||
evidence 与安全投影、合成预览审计事件与错误码注册。
|
||||
依赖:Pydantic 2、标准库 hashlib/json/re/unicodedata;被 order_extraction_route_contract、
|
||||
Profile 校验、拆分契约、xfa_preview_* 与后续 xfa_*.py 解析器引用。
|
||||
逻辑:本模块只定义契约与纯函数校验,不读 PDF/XML、不执行脚本、不接正式流量;
|
||||
禁止混入 coordinate 表区键,但允许 visual_binding 归一化框作为视觉证据。
|
||||
共同视觉布局与末端 datasets 映射分层,历史 visual_binding 仅兼容读取。
|
||||
header_mappings / line_mapping.fields 仅作**迁移输入**解析(order_profile_unified_migration);
|
||||
正式 validate/save/extract 须 bindings-only,legacy-only 或 dual-source 均 fail-closed。
|
||||
"""
|
||||
@@ -28,9 +28,9 @@ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_valida
|
||||
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'
|
||||
# Historical ``xfa_structure_signature`` Run records remain readable through the
|
||||
# ORM enum/migration compatibility path. New code must use the common
|
||||
# ``layout_signature`` lifecycle and must not introduce a second XFA signature.
|
||||
|
||||
OrderProfileTemplateMode = Literal['coordinate', 'xfa_dataset']
|
||||
ORDER_PROFILE_TEMPLATE_MODES: Final[frozenset[str]] = frozenset({
|
||||
@@ -144,12 +144,6 @@ XFA_ERROR_CODES: Final[frozenset[str]] = frozenset({
|
||||
'XFA_SPLIT_RULE_INVALID',
|
||||
'XFA_SPLIT_FIELD_CONFLICT',
|
||||
'XFA_SPLIT_MIRROR_MISMATCH',
|
||||
# 合成预览(阶段 1 POC)
|
||||
'XFA_PREVIEW_STALE',
|
||||
'XFA_PREVIEW_FAILED',
|
||||
'XFA_PREVIEW_UNAVAILABLE',
|
||||
'XFA_PREVIEW_PAGE_INCONSISTENT',
|
||||
'XFA_PREVIEW_VALUE_MISMATCH',
|
||||
})
|
||||
|
||||
XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
@@ -176,22 +170,13 @@ XFA_ROUTE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_split_field_conflict',
|
||||
'xfa_split_mirror_mismatch',
|
||||
# 统一视觉绑定 / 发布门禁 / 运行时再验(阶段 5–6)
|
||||
'xfa_visual_bindings_required',
|
||||
'xfa_visual_binding_incomplete',
|
||||
'xfa_mapping_required',
|
||||
'xfa_visual_coverage_insufficient',
|
||||
'xfa_evidence_retention_insufficient',
|
||||
'xfa_mirror_consistency_insufficient',
|
||||
'xfa_profile_checksum_mismatch',
|
||||
'xfa_visual_not_publishable',
|
||||
'xfa_split_rule_unconfirmed',
|
||||
# 合成预览发布门禁(阶段 5)
|
||||
'xfa_synthetic_preview_not_ready',
|
||||
'xfa_preview_render_checksum_missing',
|
||||
'xfa_preview_pages_incomplete',
|
||||
'xfa_preview_page_box_invalid',
|
||||
'xfa_ocr_unresolved_mismatch',
|
||||
'xfa_preview_checksum_drift',
|
||||
'xfa_preview_renderer_version_mismatch',
|
||||
})
|
||||
|
||||
XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
@@ -221,11 +206,6 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_cross_check_completed',
|
||||
'xfa_structure_signature_frozen',
|
||||
'xfa_audit_snapshot_viewed',
|
||||
# 统一视觉绑定(阶段 2)
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
# 字段拆分映射审计(阶段 3/7)
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_split_rule_previewed',
|
||||
@@ -235,26 +215,16 @@ XFA_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'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_value_adapter_extracted',
|
||||
'profile_value_adapter_needs_review',
|
||||
# 统一 binding 一次性迁移(阶段 7)
|
||||
'order_profile_unified_migration_dry_run',
|
||||
'order_profile_unified_migration_executed',
|
||||
# 合成预览(阶段 1 POC)
|
||||
'xfa_preview_requested',
|
||||
'xfa_preview_generated',
|
||||
'xfa_preview_failed',
|
||||
'xfa_preview_viewed',
|
||||
'xfa_preview_stale',
|
||||
# OCR 自动标记建议(阶段 3)
|
||||
'xfa_ocr_started',
|
||||
'xfa_ocr_completed',
|
||||
'xfa_ocr_failed',
|
||||
})
|
||||
|
||||
# Profile / Run / 分析 DTO 禁止键(大小写不敏感);完整 XML / PDF bytes / 存储地址不得外泄。
|
||||
@@ -314,22 +284,29 @@ class XfaContractModel(BaseModel):
|
||||
|
||||
|
||||
class XfaSourceContract(XfaContractModel):
|
||||
"""冻结 XFA 模板结构身份:packet checksum + 结构指纹 + 权威集合路径。"""
|
||||
"""冻结 XFA 模板结构身份;权威集合在草稿的末端值映射阶段才配置。"""
|
||||
|
||||
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)
|
||||
authoritative_line_collection_path: str | None = Field(default=None, 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:
|
||||
"""校验必填受控路径语法。"""
|
||||
"""校验 datasets 根路径语法。"""
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
@field_validator('authoritative_line_collection_path', mode='before')
|
||||
@classmethod
|
||||
def validate_optional_authoritative_path(cls, value: Any) -> str | None:
|
||||
"""草稿允许未配置 datasets 行集合;发布前由统一门禁 fail-closed。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
@field_validator('mirror_collection_paths', mode='before')
|
||||
@@ -395,13 +372,15 @@ class XfaLineMapping(XfaContractModel):
|
||||
Execute 后须为空,正式值绑定仅经 bindings[]。
|
||||
"""
|
||||
|
||||
row_path: str = Field(min_length=1, max_length=512)
|
||||
row_path: str | None = Field(default=None, 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:
|
||||
"""行集合路径必须通过受控语法。"""
|
||||
def validate_row_path(cls, value: Any) -> str | None:
|
||||
"""草稿可暂未配置行集合,正式提取前必须由发布门禁补齐。"""
|
||||
if value in (None, ''):
|
||||
return None
|
||||
return validate_controlled_data_path(value)
|
||||
|
||||
|
||||
@@ -418,6 +397,9 @@ class XfaCrossChecks(XfaContractModel):
|
||||
# 统一字段绑定(value_binding + visual_binding)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# ``bindings[]`` 是所有 Profile 共用的末端取值 DTO;具体 adapter 的 Profile
|
||||
# 契约再收紧允许类型。这样坐标/OCR 与 datasets 共用编辑、审计和迁移结构,
|
||||
# 同时 XFA 不会把视觉证据误作正式值。
|
||||
XfaValueBindingType = Literal['xfa_dataset', 'pdf_coordinate', 'ocr_coordinate']
|
||||
XfaVisualBindingSource = Literal[
|
||||
'acroform_widget',
|
||||
@@ -456,7 +438,7 @@ class XfaNormalizedBBox(XfaContractModel):
|
||||
|
||||
|
||||
class XfaValueBinding(XfaContractModel):
|
||||
"""正式值绑定:XFA 仅允许 datasets 路径;普通 PDF 允许坐标/OCR。"""
|
||||
"""共同正式值绑定;XFA Profile 的上层契约仍只允许 datasets 路径。"""
|
||||
|
||||
type: XfaValueBindingType
|
||||
path_id: str | None = Field(default=None, max_length=128)
|
||||
@@ -485,7 +467,7 @@ class XfaValueBinding(XfaContractModel):
|
||||
|
||||
|
||||
class XfaVisualBinding(XfaContractModel):
|
||||
"""视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须 confirmed。
|
||||
"""视觉绑定:页码 + 归一化框 + 确认状态;正式字段发布前须原生页 confirmed。
|
||||
|
||||
合成预览确认证据(阶段 4+):confirmed 时须携带 preview_render_checksum /
|
||||
render_mode=xfa_dataset_preview / confirmed_on=xfa_dataset_preview。
|
||||
@@ -516,21 +498,23 @@ class XfaUnifiedFieldBinding(XfaContractModel):
|
||||
"""
|
||||
统一字段绑定:同一 Schema 字段在同一作用域最多一个正式来源。
|
||||
|
||||
核心逻辑:value_binding 决定正式取值;visual_binding 决定页面证据;
|
||||
split_rule_ref 可选指向已确认拆分段。
|
||||
核心逻辑:value_binding 决定正式取值;field_layout_id 指向共同订单字段标签
|
||||
(order_field_layouts),不重复保存或确认一套 XFA 专属值框;split_rule_ref
|
||||
可选指向已确认拆分段。visual_binding 仅用于读取历史草稿,禁止新保存依赖它。
|
||||
"""
|
||||
|
||||
binding_id: str = Field(min_length=8, max_length=64)
|
||||
field_id: str = Field(min_length=1, max_length=64)
|
||||
field_code: str = Field(min_length=1, max_length=128)
|
||||
scope: XfaBindingScope
|
||||
field_layout_id: str | None = Field(default=None, min_length=1, max_length=128)
|
||||
value_binding: XfaValueBinding
|
||||
visual_binding: XfaVisualBinding
|
||||
visual_binding: XfaVisualBinding | None = None
|
||||
split_rule_ref: XfaSplitRuleRef | None = None
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_xfa_scope_value_type(self) -> 'XfaUnifiedFieldBinding':
|
||||
"""同模板允许字段级混合数据源;具体约束由 value_binding / 发布门禁执行。"""
|
||||
def validate_shared_scope_value_type(self) -> 'XfaUnifiedFieldBinding':
|
||||
"""统一 binding 本身不判模板类型;XFA Profile 上层单独拒绝坐标取值。"""
|
||||
return self
|
||||
|
||||
|
||||
@@ -539,9 +523,8 @@ def is_formal_binding_publishable(binding: XfaUnifiedFieldBinding) -> bool:
|
||||
判断统一绑定是否满足发布门禁(字段级混合数据源口径)。
|
||||
|
||||
核心逻辑:
|
||||
- xfa_dataset:正式 path 已配置即可发布(视觉框可选);
|
||||
- pdf_coordinate / ocr_coordinate:必须视觉 confirmed;
|
||||
- 旧合成预览确认(confirmed_on/render_mode=xfa_dataset_preview)视为未重确认。
|
||||
- xfa_dataset:正式 path 配置完毕;视觉存在性由共同 order_field_layouts 门禁处理;
|
||||
- 历史 visual_binding 不再作为新草稿的发布前提。
|
||||
|
||||
Args:
|
||||
binding: 统一字段绑定。
|
||||
@@ -550,17 +533,9 @@ def is_formal_binding_publishable(binding: XfaUnifiedFieldBinding) -> bool:
|
||||
满足对应类型发布条件时为 True。
|
||||
"""
|
||||
value_type = binding.value_binding.type
|
||||
visual = binding.visual_binding
|
||||
confirmed_on = str(visual.confirmed_on or '').strip()
|
||||
render_mode = str(visual.render_mode or '').strip()
|
||||
# 旧 flatten/synthetic 坐标系确认框须在原生 PDF 画布重确认。
|
||||
if visual.status == 'confirmed' and (
|
||||
confirmed_on == 'xfa_dataset_preview' or render_mode == 'xfa_dataset_preview'
|
||||
):
|
||||
return False
|
||||
if value_type == 'xfa_dataset':
|
||||
return bool(binding.value_binding.path_id and binding.value_binding.data_path)
|
||||
return visual.status == 'confirmed'
|
||||
return value_type in {'pdf_coordinate', 'ocr_coordinate'} and bool(binding.value_binding.region_id)
|
||||
|
||||
|
||||
def canonical_unified_bindings_payload(
|
||||
@@ -591,10 +566,20 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
xfa_dataset 模式的鉴别联合 definition。
|
||||
|
||||
核心逻辑:header_mappings / line_mapping.fields 仅迁移输入(须 bindings-only 正式运行);
|
||||
validate 拒绝 legacy-only 与 dual-source;拒绝 coordinate 表区键;可选 split_rules。
|
||||
validate 拒绝 legacy-only 与 dual-source;保留共同视觉匹配契约;可选 split_rules。
|
||||
"""
|
||||
|
||||
template_mode: Literal['xfa_dataset'] = 'xfa_dataset'
|
||||
# 统一视觉 Layout 的主表身份;正式明细模板必须先冻结该身份,
|
||||
# datasets 只负责字段最终取值,不再替代视觉表格建模。
|
||||
# 历史已发布版本在迁移前可能没有该键;创建/发布入口分别负责拒绝未补齐的草稿,
|
||||
# 契约层保持可读,避免历史冻结快照无法审计。
|
||||
main_table_id: str | None = Field(default=None, min_length=1, max_length=128)
|
||||
# 所有模板共享的视觉候选选择契约。它只决定“哪个 Profile”,绝不参与 XFA 最终取值。
|
||||
document_match: dict[str, Any] | None = None
|
||||
table_regions: list[dict[str, Any]] = Field(default_factory=list)
|
||||
order_field_layouts: list[dict[str, Any]] = Field(default_factory=list)
|
||||
draft_unbound_order_field_layouts: list[dict[str, Any]] = Field(default_factory=list)
|
||||
source_contract: XfaSourceContract
|
||||
# 迁移输入兼容:禁止正式运行时单独携带非空 legacy mappings(须 bindings-only)。
|
||||
header_mappings: list[XfaHeaderMapping] = Field(default_factory=list)
|
||||
@@ -602,26 +587,21 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
bindings: list[XfaUnifiedFieldBinding] = Field(default_factory=list)
|
||||
cross_checks: XfaCrossChecks = Field(default_factory=XfaCrossChecks)
|
||||
split_rules: list[dict[str, Any]] = Field(default_factory=list)
|
||||
# 合成预览摘要(可选;发布门禁优先读取 status / preview_render_checksum)
|
||||
# 仅为读取已存历史草稿而保留;运行时、确认和发布均不读取此字段。
|
||||
xfa_preview: dict[str, Any] | None = None
|
||||
# OCR 自动标记摘要(可选;未解决 mismatch 计数供发布门禁读取)
|
||||
xfa_ocr_automark: dict[str, Any] | None = None
|
||||
|
||||
@model_validator(mode='before')
|
||||
@classmethod
|
||||
def reject_coordinate_keys(cls, data: Any) -> Any:
|
||||
"""
|
||||
拒绝 coordinate 表区 / layout 键混入 XFA definition。
|
||||
拒绝已废弃 coordinate 重建键混入 XFA definition。
|
||||
|
||||
注意:不拒绝 visual_binding / normalized_bbox(统一绑定的视觉证据)。
|
||||
注意:共同视觉 matcher 的 document_match/table_regions 是合法键;
|
||||
共同视觉布局字段是合法键;历史 visual_binding 仅兼容读取。
|
||||
"""
|
||||
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',
|
||||
@@ -654,13 +634,81 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
mapping_ids.append(item.mapping_id)
|
||||
binding_ids: list[str] = []
|
||||
binding_field_keys: list[tuple[str, str]] = []
|
||||
rule_sets = parse_split_rule_sets(self.split_rules)
|
||||
split_segments = {
|
||||
str(rule.segment.segment_id): {
|
||||
'source_path_id': str(rule_set.source_path_id),
|
||||
'target_field_code': str(rule.segment.target_field_code or ''),
|
||||
}
|
||||
for rule_set in rule_sets
|
||||
for rule in rule_set.rules
|
||||
if rule.segment.handling == 'mapped'
|
||||
}
|
||||
shared_layouts = {
|
||||
str(item.get('layout_id') or '').strip(): item
|
||||
for item in self.order_field_layouts
|
||||
if isinstance(item, dict) and str(item.get('layout_id') or '').strip()
|
||||
}
|
||||
for table in self.table_regions:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
for line in table.get('line_layouts') or []:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
for field in line.get('field_regions') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
layout_id = str(
|
||||
field.get('region_id')
|
||||
or field.get('layout_id')
|
||||
or f"{line.get('layout_id') or ''}:{field.get('field_code') or ''}"
|
||||
).strip(':')
|
||||
if layout_id:
|
||||
shared_layouts[layout_id] = {**field, 'scope': 'line'}
|
||||
for binding in self.bindings:
|
||||
# 硬冻结(2026-08-07):同模板允许 xfa_dataset / pdf_coordinate / ocr_coordinate 混用。
|
||||
if binding.value_binding.type not in {'xfa_dataset', 'pdf_coordinate', 'ocr_coordinate'}:
|
||||
raise ValueError(
|
||||
'OrderXfaDatasetProfile bindings must use value_binding.type in '
|
||||
'xfa_dataset|pdf_coordinate|ocr_coordinate',
|
||||
)
|
||||
if binding.value_binding.type != 'xfa_dataset':
|
||||
raise ValueError('XFA value bindings must use xfa_dataset')
|
||||
# 新定义以共同 Editor 的 order_field_layouts 为唯一视觉字段模型。
|
||||
# 没有共同布局的历史草稿仍可读取,保存与发布会在 adapter 门禁 fail-closed。
|
||||
if shared_layouts:
|
||||
layout_id = str(binding.field_layout_id or '').strip()
|
||||
if not layout_id:
|
||||
raise ValueError('field_layout_id is required when order_field_layouts are present')
|
||||
layout = shared_layouts.get(layout_id)
|
||||
if layout is None:
|
||||
raise ValueError('field_layout_id must reference an order_field_layouts entry')
|
||||
layout_field_code = str(layout.get('field_code') or '')
|
||||
if layout_field_code != binding.field_code:
|
||||
# 一个多行源值(MATNR)可以通过已确认拆分规则产出多个行字段。
|
||||
# 每个目标仍指向同一个真实 MATNR 框,避免伪造重叠视觉框。
|
||||
split_ref = binding.split_rule_ref
|
||||
segment = split_segments.get(str(split_ref.segment_id)) if split_ref else None
|
||||
is_split_target_visual_reuse = bool(
|
||||
binding.scope == 'line'
|
||||
and str(layout.get('scope') or '') == 'line'
|
||||
and binding.value_binding.type == 'xfa_dataset'
|
||||
and segment
|
||||
and segment['target_field_code'] == binding.field_code
|
||||
and segment['source_path_id'] == str(binding.value_binding.path_id or '')
|
||||
)
|
||||
if not is_split_target_visual_reuse:
|
||||
raise ValueError('field_layout_id field_code must match binding field_code')
|
||||
layout_scope = str(layout.get('scope') or 'header')
|
||||
if layout_scope != binding.scope:
|
||||
# 全单 Header 值(例如 Reservation)可被显式投影至每条明细。
|
||||
# 此时共同视觉证据必须保留其真实 Header 框,不能伪造表格内框;
|
||||
# 保存 adapter 仍会校验该 path 是当前 XFA 分析确认的 Header 叶子。
|
||||
authoritative_prefix = self.source_contract.authoritative_line_collection_path.rstrip('/') if self.source_contract.authoritative_line_collection_path else ''
|
||||
is_line_header_visual_inheritance = bool(
|
||||
binding.scope == 'line'
|
||||
and layout_scope == 'header'
|
||||
and binding.value_binding.type == 'xfa_dataset'
|
||||
and authoritative_prefix
|
||||
and binding.value_binding.data_path
|
||||
and not binding.value_binding.data_path.startswith(f'{authoritative_prefix}/')
|
||||
)
|
||||
if not is_line_header_visual_inheritance:
|
||||
raise ValueError('field_layout_id scope must match binding scope')
|
||||
binding_ids.append(binding.binding_id)
|
||||
binding_field_keys.append((binding.scope, binding.field_id))
|
||||
field_ids.append(binding.field_id)
|
||||
@@ -668,12 +716,22 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
raise ValueError('duplicate binding_id values are not allowed')
|
||||
if len(binding_field_keys) != len(set(binding_field_keys)):
|
||||
raise ValueError('duplicate Schema field_id bindings in the same scope are not allowed')
|
||||
rule_sets = parse_split_rule_sets(self.split_rules)
|
||||
split_target_field_ids: list[str] = []
|
||||
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)
|
||||
split_target_field_ids.append(rule.segment.target_field_id)
|
||||
has_legacy_mappings = bool(self.header_mappings) or bool(self.line_mapping.fields)
|
||||
if not self.source_contract.authoritative_line_collection_path and (
|
||||
self.bindings
|
||||
or has_legacy_mappings
|
||||
or self.line_mapping.row_path
|
||||
or rule_sets
|
||||
):
|
||||
raise ValueError(
|
||||
'authoritative_line_collection_required: XFA value mappings and split rules '
|
||||
'require an authoritative datasets line collection',
|
||||
)
|
||||
if self.bindings and has_legacy_mappings:
|
||||
raise ValueError(
|
||||
'xfa_dual_binding_source: bindings cannot coexist with '
|
||||
@@ -686,9 +744,17 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
)
|
||||
if len(field_ids) != len(set(field_ids)):
|
||||
raise ValueError('duplicate Schema field_id bindings are not allowed')
|
||||
# 拆分段的字段目标独立于 bindings[] 去重:同一字段的 binding 正是其共享
|
||||
# 视觉源框引用,不能被误判为双重正式取值;两个拆分段映射同一字段仍不允许。
|
||||
if len(split_target_field_ids) != len(set(split_target_field_ids)):
|
||||
raise ValueError('duplicate Schema field_id split targets 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:
|
||||
if (
|
||||
self.line_mapping.row_path
|
||||
and self.source_contract.authoritative_line_collection_path
|
||||
and self.line_mapping.row_path != self.source_contract.authoritative_line_collection_path
|
||||
):
|
||||
raise ValueError('line_mapping.row_path must equal authoritative_line_collection_path')
|
||||
object.__setattr__(
|
||||
self,
|
||||
|
||||
@@ -565,7 +565,7 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
|
||||
|
||||
Args:
|
||||
node: 数据集树节点。
|
||||
include_values: 是否包含当前管理端使用的完整样本值。
|
||||
include_values: 是否包含受控的样本展示值;不得暴露 raw_value。
|
||||
|
||||
Returns:
|
||||
安全 DTO 字典。
|
||||
@@ -583,10 +583,12 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
|
||||
'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'] = str(node.raw_value or '')
|
||||
payload['sample_value_display'] = str(node.raw_value or '')
|
||||
payload['display_policy'] = 'full'
|
||||
payload['can_reveal'] = False
|
||||
# 字段树是批量 DTO:即使管理端需要映射辅助,也绝不能把 datasets
|
||||
# 原文放入可缓存/可下载的树响应。完整值只能经单值受控读取与审计接口取得。
|
||||
payload['sample_value_masked'] = str(node.sample_value_masked or '')
|
||||
payload['sample_value_display'] = str(node.sample_value_display or '')
|
||||
payload['display_policy'] = str(node.display_policy or 'empty')
|
||||
payload['can_reveal'] = bool(node.can_reveal)
|
||||
payload['line_count'] = len(node.lines or [])
|
||||
return payload
|
||||
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_preview_cache.py
|
||||
|
||||
用途:XFA 合成预览进程内缓存(Phase 1 POC);按身份指纹键存取预览结果。
|
||||
依赖:threading、xfa_preview_contract.build_preview_identity_fingerprint。
|
||||
逻辑:由预览编排层调用;可选后续替换为 Redis;本模块不做 IO/渲染。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
|
||||
PreviewIdentityContext,
|
||||
build_preview_identity_fingerprint,
|
||||
)
|
||||
|
||||
_LOCK = threading.RLock()
|
||||
_CACHE: dict[str, tuple[float, dict[str, Any]]] = {}
|
||||
_DEFAULT_TTL_SECONDS = 30 * 60
|
||||
|
||||
|
||||
def build_preview_cache_key(
|
||||
*,
|
||||
structure_analysis_id: int | str | None,
|
||||
template_packet_checksum: str,
|
||||
datasets_packet_checksum: str,
|
||||
dataset_structure_fingerprint: str,
|
||||
source_content_hash: str,
|
||||
renderer_version: str,
|
||||
) -> str:
|
||||
"""
|
||||
构造预览缓存键(analysis_id + checksums + renderer_version)。
|
||||
|
||||
核心逻辑:委托 PreviewIdentityContext 指纹,page_count/preview_render_checksum 置空
|
||||
以便在渲染前即可定位缓存槽。
|
||||
|
||||
Args:
|
||||
structure_analysis_id: 冻结结构分析 ID。
|
||||
template_packet_checksum: template packet 校验和。
|
||||
datasets_packet_checksum: datasets packet 校验和。
|
||||
dataset_structure_fingerprint: datasets 结构指纹。
|
||||
source_content_hash: 源 PDF 内容哈希。
|
||||
renderer_version: 合成器版本。
|
||||
|
||||
Returns:
|
||||
稳定十六进制缓存键。
|
||||
"""
|
||||
ctx = PreviewIdentityContext(
|
||||
document_id=None,
|
||||
layout_version_id=None,
|
||||
structure_analysis_id=structure_analysis_id,
|
||||
source_content_hash=str(source_content_hash or ''),
|
||||
template_packet_checksum=str(template_packet_checksum or ''),
|
||||
datasets_packet_checksum=str(datasets_packet_checksum or ''),
|
||||
dataset_structure_fingerprint=str(dataset_structure_fingerprint or ''),
|
||||
preview_render_checksum='',
|
||||
renderer_version=str(renderer_version or ''),
|
||||
page_count=0,
|
||||
)
|
||||
return build_preview_identity_fingerprint(ctx)
|
||||
|
||||
|
||||
def get_preview_cache(key: str) -> dict[str, Any] | None:
|
||||
"""
|
||||
读取预览缓存条目。
|
||||
|
||||
核心逻辑:持锁检查 TTL;过期则删除并返回 None。
|
||||
|
||||
Args:
|
||||
key: build_preview_cache_key 结果。
|
||||
|
||||
Returns:
|
||||
缓存的预览结果字典;未命中或过期时为 None。
|
||||
"""
|
||||
text = str(key or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
now = time.time()
|
||||
with _LOCK:
|
||||
item = _CACHE.get(text)
|
||||
if item is None:
|
||||
return None
|
||||
expires_at, payload = item
|
||||
if expires_at <= now:
|
||||
_CACHE.pop(text, None)
|
||||
return None
|
||||
return dict(payload)
|
||||
|
||||
|
||||
def set_preview_cache(
|
||||
key: str,
|
||||
value: dict[str, Any],
|
||||
*,
|
||||
ttl_seconds: int = _DEFAULT_TTL_SECONDS,
|
||||
) -> None:
|
||||
"""
|
||||
写入预览缓存条目。
|
||||
|
||||
Args:
|
||||
key: 缓存键。
|
||||
value: 可浅拷贝的预览结果字典(调用方勿放入不可序列化巨型对象以外的副作用状态)。
|
||||
ttl_seconds: 存活秒数;最小 1。
|
||||
"""
|
||||
text = str(key or '').strip()
|
||||
if not text or not isinstance(value, dict):
|
||||
return
|
||||
expires_at = time.time() + max(1, int(ttl_seconds))
|
||||
with _LOCK:
|
||||
_CACHE[text] = (expires_at, dict(value))
|
||||
|
||||
|
||||
def invalidate_preview_cache(key: str | None = None) -> None:
|
||||
"""
|
||||
使预览缓存失效。
|
||||
|
||||
核心逻辑:key 为空时清空全部;否则仅删除指定键。
|
||||
|
||||
Args:
|
||||
key: 可选缓存键;None/空串表示清空。
|
||||
"""
|
||||
with _LOCK:
|
||||
if not key:
|
||||
_CACHE.clear()
|
||||
return
|
||||
_CACHE.pop(str(key), None)
|
||||
|
||||
|
||||
def clear_preview_cache() -> None:
|
||||
"""清空全部预览缓存(测试辅助)。"""
|
||||
invalidate_preview_cache(None)
|
||||
@@ -1,185 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_preview_contract.py
|
||||
|
||||
用途:冻结 XFA 自研静态合成预览(Phase 1 POC)契约——render_mode、预览状态、
|
||||
错误码、身份上下文、审计事件名与确定性指纹辅助。
|
||||
依赖:标准库 dataclasses/hashlib/json;被 xfa_preview_renderer / xfa_preview_cache /
|
||||
后续预览 API 与审计接线引用。
|
||||
逻辑:本模块只定义纯数据与纯函数,不读 PDF、不渲染、不落库;身份字段与
|
||||
preview_render_checksum 必须与合成器输出一致,供 stale 判定与发布证据绑定。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
from typing import Any, Final, Literal
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 渲染模式 / 预览状态
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
RENDER_MODE: Final[str] = 'xfa_dataset_preview'
|
||||
|
||||
XfaPreviewStatus = Literal['ready', 'needs_review', 'failed', 'stale']
|
||||
XFA_PREVIEW_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'ready',
|
||||
'needs_review',
|
||||
'failed',
|
||||
'stale',
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 稳定错误码(短码;AppError 层可映射为 SHIPPING.ORDER_DOCUMENT_PROFILE_*)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_PREVIEW_STALE: Final[str] = 'XFA_PREVIEW_STALE'
|
||||
XFA_PREVIEW_FAILED: Final[str] = 'XFA_PREVIEW_FAILED'
|
||||
XFA_PREVIEW_UNAVAILABLE: Final[str] = 'XFA_PREVIEW_UNAVAILABLE'
|
||||
XFA_PREVIEW_PAGE_INCONSISTENT: Final[str] = 'XFA_PREVIEW_PAGE_INCONSISTENT'
|
||||
XFA_PREVIEW_VALUE_MISMATCH: Final[str] = 'XFA_PREVIEW_VALUE_MISMATCH'
|
||||
|
||||
XFA_PREVIEW_ERROR_CODES: Final[frozenset[str]] = frozenset({
|
||||
XFA_PREVIEW_STALE,
|
||||
XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
XFA_PREVIEW_PAGE_INCONSISTENT,
|
||||
XFA_PREVIEW_VALUE_MISMATCH,
|
||||
})
|
||||
|
||||
# AppError / i18n 完整码(与 SHIPPING.ORDER_DOCUMENT_PROFILE_* 风格对齐)
|
||||
SHIPPING_XFA_PREVIEW_STALE: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_STALE'
|
||||
SHIPPING_XFA_PREVIEW_FAILED: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_FAILED'
|
||||
SHIPPING_XFA_PREVIEW_UNAVAILABLE: Final[str] = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_UNAVAILABLE'
|
||||
SHIPPING_XFA_PREVIEW_PAGE_INCONSISTENT: Final[str] = (
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_PAGE_INCONSISTENT'
|
||||
)
|
||||
SHIPPING_XFA_PREVIEW_VALUE_MISMATCH: Final[str] = (
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_PREVIEW_VALUE_MISMATCH'
|
||||
)
|
||||
|
||||
XFA_PREVIEW_SHIPPING_ERROR_BY_CODE: Final[dict[str, str]] = {
|
||||
XFA_PREVIEW_STALE: SHIPPING_XFA_PREVIEW_STALE,
|
||||
XFA_PREVIEW_FAILED: SHIPPING_XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_UNAVAILABLE: SHIPPING_XFA_PREVIEW_UNAVAILABLE,
|
||||
XFA_PREVIEW_PAGE_INCONSISTENT: SHIPPING_XFA_PREVIEW_PAGE_INCONSISTENT,
|
||||
XFA_PREVIEW_VALUE_MISMATCH: SHIPPING_XFA_PREVIEW_VALUE_MISMATCH,
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 审计事件(预览生命周期)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
XFA_PREVIEW_AUDIT_EVENT_TYPES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_preview_requested',
|
||||
'xfa_preview_generated',
|
||||
'xfa_preview_failed',
|
||||
'xfa_preview_viewed',
|
||||
'xfa_preview_stale',
|
||||
})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PreviewIdentityContext:
|
||||
"""
|
||||
合成预览身份上下文:发布视觉证据与 stale 判定的冻结字段集合。
|
||||
|
||||
任一关键校验和/指纹变化即视为预览身份漂移,不得继续当作 ready 证据。
|
||||
"""
|
||||
|
||||
document_id: int | None
|
||||
layout_version_id: int | None
|
||||
structure_analysis_id: int | str | None
|
||||
source_content_hash: str
|
||||
template_packet_checksum: str
|
||||
datasets_packet_checksum: str
|
||||
dataset_structure_fingerprint: str
|
||||
preview_render_checksum: str
|
||||
render_mode: str = RENDER_MODE
|
||||
renderer_version: str = ''
|
||||
page_count: int = 0
|
||||
|
||||
|
||||
def shipping_error_code_for_preview(error_code: str | None) -> str | None:
|
||||
"""
|
||||
将预览短错误码映射为 SHIPPING.ORDER_DOCUMENT_PROFILE_* AppError 码。
|
||||
|
||||
核心逻辑:查 XFA_PREVIEW_SHIPPING_ERROR_BY_CODE;未知码原样返回。
|
||||
|
||||
Args:
|
||||
error_code: 预览短错误码或已是完整 SHIPPING.* 码。
|
||||
|
||||
Returns:
|
||||
完整业务错误码;输入为空时返回 None。
|
||||
"""
|
||||
text = str(error_code or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
if text.startswith('SHIPPING.'):
|
||||
return text
|
||||
return XFA_PREVIEW_SHIPPING_ERROR_BY_CODE.get(text, text)
|
||||
|
||||
|
||||
def preview_identity_to_dict(ctx: PreviewIdentityContext) -> dict[str, Any]:
|
||||
"""
|
||||
将 PreviewIdentityContext 序列化为可审计/可缓存的普通字典。
|
||||
|
||||
Args:
|
||||
ctx: 预览身份上下文。
|
||||
|
||||
Returns:
|
||||
字段字典(不含额外派生键)。
|
||||
"""
|
||||
return asdict(ctx)
|
||||
|
||||
|
||||
def build_preview_identity_fingerprint(ctx: PreviewIdentityContext) -> str:
|
||||
"""
|
||||
计算预览身份指纹(不含 preview_render_checksum 本身,避免循环依赖)。
|
||||
|
||||
核心逻辑:对 document/layout/analysis/内容哈希/packet/结构指纹/render_mode/
|
||||
renderer_version/page_count 做稳定 JSON 序列化后 SHA-256。
|
||||
|
||||
Args:
|
||||
ctx: 预览身份上下文。
|
||||
|
||||
Returns:
|
||||
64 位十六进制指纹字符串。
|
||||
"""
|
||||
payload = {
|
||||
'document_id': ctx.document_id,
|
||||
'layout_version_id': ctx.layout_version_id,
|
||||
'structure_analysis_id': ctx.structure_analysis_id,
|
||||
'source_content_hash': str(ctx.source_content_hash or ''),
|
||||
'template_packet_checksum': str(ctx.template_packet_checksum or ''),
|
||||
'datasets_packet_checksum': str(ctx.datasets_packet_checksum or ''),
|
||||
'dataset_structure_fingerprint': str(ctx.dataset_structure_fingerprint or ''),
|
||||
'render_mode': str(ctx.render_mode or RENDER_MODE),
|
||||
'renderer_version': str(ctx.renderer_version or ''),
|
||||
'page_count': int(ctx.page_count or 0),
|
||||
}
|
||||
raw = json.dumps(payload, sort_keys=True, separators=(',', ':'), ensure_ascii=True)
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def is_preview_identity_stale(
|
||||
*,
|
||||
expected: PreviewIdentityContext,
|
||||
actual: PreviewIdentityContext,
|
||||
) -> bool:
|
||||
"""
|
||||
判断实际预览身份是否相对期望身份已过期(stale)。
|
||||
|
||||
核心逻辑:比较身份指纹与 preview_render_checksum;任一不等即 stale。
|
||||
|
||||
Args:
|
||||
expected: 期望/冻结身份(例如绑定证据快照)。
|
||||
actual: 当前重新计算的身份。
|
||||
|
||||
Returns:
|
||||
True 表示应标记 stale 并重新生成/重确认。
|
||||
"""
|
||||
if build_preview_identity_fingerprint(expected) != build_preview_identity_fingerprint(actual):
|
||||
return True
|
||||
return str(expected.preview_render_checksum or '') != str(actual.preview_render_checksum or '')
|
||||
@@ -1,200 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_preview_renderer.py
|
||||
|
||||
用途:XFA 离线完整 flatten 入口(硬冻结 §0)。当前未接入可复现 flatten 引擎时
|
||||
一律 fail-closed 返回 needs_review;禁止静态 overlay / 壳图充当 ready。
|
||||
依赖:xfa_preview_contract;未来真实引擎须离线、禁不受控脚本、输出可复现 checksum。
|
||||
逻辑:由预览编排服务调用 compose_xfa_dataset_preview_pages;settings
|
||||
SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY=true 且引擎实现就绪后才可返回 ready。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
|
||||
RENDER_MODE,
|
||||
XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
XfaPreviewStatus,
|
||||
)
|
||||
|
||||
# 版本号:v0_pending 表示尚未交付完整 flatten;不得与历史 overlay checksum 混用。
|
||||
RENDERER_VERSION = 'hxops.xfa_flatten.v0_pending'
|
||||
|
||||
|
||||
@dataclass
|
||||
class DrawnFieldEcho:
|
||||
"""单页上 flatten 回显痕迹(完整引擎就绪后使用)。"""
|
||||
|
||||
path_id: str
|
||||
value: str
|
||||
normalized_bbox: dict[str, float]
|
||||
page_no: int = 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaPreviewComposeResult:
|
||||
"""flatten / 预览文档级结果;status!=ready 时 pages 为空。"""
|
||||
|
||||
status: XfaPreviewStatus
|
||||
error_code: str | None
|
||||
render_mode: str
|
||||
renderer_version: str
|
||||
page_count: int
|
||||
preview_render_checksum: str | None
|
||||
pages: list[dict[str, Any]] = field(default_factory=list)
|
||||
diagnostics: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""序列化为普通字典。"""
|
||||
return {
|
||||
'status': self.status,
|
||||
'error_code': self.error_code,
|
||||
'render_mode': self.render_mode,
|
||||
'renderer_version': self.renderer_version,
|
||||
'page_count': self.page_count,
|
||||
'preview_render_checksum': self.preview_render_checksum,
|
||||
'pages': self.pages,
|
||||
'diagnostics': self.diagnostics,
|
||||
}
|
||||
|
||||
|
||||
def compute_preview_render_checksum(
|
||||
*,
|
||||
renderer_version: str,
|
||||
pages: list[dict[str, Any]],
|
||||
) -> str:
|
||||
"""
|
||||
计算可复现的预览渲染校验和。
|
||||
|
||||
核心逻辑:串联 renderer_version 与各页宽高/回显指纹/图像哈希后 SHA-256。
|
||||
|
||||
Args:
|
||||
renderer_version: 合成器版本。
|
||||
pages: 含 width/height/drawn_field_echoes/png_bytes 的页列表。
|
||||
|
||||
Returns:
|
||||
hex digest 字符串。
|
||||
"""
|
||||
parts: list[str] = [str(renderer_version or '')]
|
||||
for page in pages:
|
||||
page_no = int(page.get('page_no') or 0)
|
||||
width = float(page.get('width') or 0)
|
||||
height = float(page.get('height') or 0)
|
||||
echoes = page.get('drawn_field_echoes') if isinstance(page.get('drawn_field_echoes'), list) else []
|
||||
echo_fp = '|'.join(
|
||||
f"{item.get('path_id')}:{item.get('value')}"
|
||||
for item in echoes
|
||||
if isinstance(item, dict)
|
||||
)
|
||||
png = page.get('png_bytes')
|
||||
img_hash = ''
|
||||
if isinstance(png, (bytes, bytearray)) and png:
|
||||
img_hash = hashlib.sha256(bytes(png)).hexdigest()
|
||||
parts.append(f'{page_no}:{width}x{height}:{echo_fp}:{img_hash}')
|
||||
return hashlib.sha256('\n'.join(parts).encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def is_xfa_flatten_engine_ready() -> bool:
|
||||
"""
|
||||
完整离线 flatten 引擎是否已启用且可对外返回 ready。
|
||||
|
||||
核心逻辑:读取 settings.SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY;默认 false。
|
||||
引擎实现与人眼一致性完成前必须保持关闭。
|
||||
|
||||
Returns:
|
||||
True 仅当显式开启(当前仍无真实引擎实现,开启也不会 ready)。
|
||||
"""
|
||||
try:
|
||||
from app.core.config.settings import Settings
|
||||
|
||||
return bool(getattr(Settings, 'SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY', False))
|
||||
except Exception: # noqa: BLE001
|
||||
return False
|
||||
|
||||
|
||||
def attempt_offline_xfa_flatten(
|
||||
*,
|
||||
pdf_bytes: bytes,
|
||||
analysis_or_nodes: Any,
|
||||
page_boxes: list[dict[str, Any]] | None = None,
|
||||
template_bytes: bytes | None = None,
|
||||
) -> XfaPreviewComposeResult:
|
||||
"""
|
||||
尝试离线完整 XFA flatten(template + datasets → 有效 PDF/PNG)。
|
||||
|
||||
核心逻辑:硬冻结要求删除 overlay;真实引擎未交付前一律 needs_review。
|
||||
不得用 PDFium 壳图或黄框叠加冒充 ready。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 源 XFA PDF 字节。
|
||||
analysis_or_nodes: datasets 分析或叶子映射(预留)。
|
||||
page_boxes: 可选期望页框(预留)。
|
||||
template_bytes: 可选 template packet(预留)。
|
||||
|
||||
Returns:
|
||||
当前恒为 needs_review / failed;未来引擎就绪后返回 ready + pages。
|
||||
"""
|
||||
del analysis_or_nodes, page_boxes, template_bytes # 真实引擎接入时启用
|
||||
if not pdf_bytes:
|
||||
return XfaPreviewComposeResult(
|
||||
status='failed',
|
||||
error_code=XFA_PREVIEW_FAILED,
|
||||
render_mode=RENDER_MODE,
|
||||
renderer_version=RENDERER_VERSION,
|
||||
page_count=0,
|
||||
preview_render_checksum=None,
|
||||
pages=[],
|
||||
diagnostics={'reason': 'empty_pdf_bytes'},
|
||||
)
|
||||
# [STEP] 完整 flatten 未交付:fail-closed(禁止 overlay ready)
|
||||
return XfaPreviewComposeResult(
|
||||
status='needs_review',
|
||||
error_code=XFA_PREVIEW_UNAVAILABLE,
|
||||
render_mode=RENDER_MODE,
|
||||
renderer_version=RENDERER_VERSION,
|
||||
page_count=0,
|
||||
preview_render_checksum=None,
|
||||
pages=[],
|
||||
diagnostics={
|
||||
'reason': 'flatten_engine_unavailable',
|
||||
'message': (
|
||||
'Offline reproducible XFA flatten is not available; '
|
||||
'shell PDF / PDFium shell / overlay must not be used as canvas source'
|
||||
),
|
||||
'flatten_engine_ready_flag': is_xfa_flatten_engine_ready(),
|
||||
'operational_status': 'OPERATIONAL_PENDING',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def compose_xfa_dataset_preview_pages(
|
||||
*,
|
||||
pdf_bytes: bytes,
|
||||
analysis_or_nodes: Any,
|
||||
page_boxes: list[dict[str, Any]] | None = None,
|
||||
template_bytes: bytes | None = None,
|
||||
) -> XfaPreviewComposeResult:
|
||||
"""
|
||||
XFA 标注图源编排入口(对外保持原函数名以兼容调用方)。
|
||||
|
||||
核心逻辑:委托 attempt_offline_xfa_flatten;未完成完整 flatten 前不得返回 ready。
|
||||
|
||||
Args:
|
||||
pdf_bytes: 源 PDF 字节。
|
||||
analysis_or_nodes: datasets 分析或叶子映射。
|
||||
page_boxes: 可选期望页框。
|
||||
template_bytes: 可选 template packet。
|
||||
|
||||
Returns:
|
||||
XfaPreviewComposeResult;当前预期 status=needs_review。
|
||||
"""
|
||||
return attempt_offline_xfa_flatten(
|
||||
pdf_bytes=pdf_bytes,
|
||||
analysis_or_nodes=analysis_or_nodes,
|
||||
page_boxes=page_boxes,
|
||||
template_bytes=template_bytes,
|
||||
)
|
||||
@@ -18,9 +18,6 @@ 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,
|
||||
@@ -47,6 +44,21 @@ from app.services.shipping_notice.order_schema.field_rules import (
|
||||
)
|
||||
|
||||
|
||||
# 引擎保留命中集合用于可审计诊断;这些信息本身不表示歧义,不能污染行级门禁。
|
||||
_SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES = frozenset({
|
||||
'line_match_candidates',
|
||||
})
|
||||
|
||||
|
||||
def _split_blocking_issue_codes(split_result: Any) -> list[str]:
|
||||
"""只将会影响正式取值可信度的拆分诊断投影为业务 issue。"""
|
||||
return [
|
||||
f'xfa_split:{item.code}'
|
||||
for item in split_result.diagnostics
|
||||
if item.code and item.code not in _SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class XfaExtractedField:
|
||||
"""单字段提取结果(含内部原始值,对外投影时剥离)。"""
|
||||
@@ -354,9 +366,7 @@ def _apply_split_rules_for_header(
|
||||
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
|
||||
)
|
||||
issues.extend(_split_blocking_issue_codes(split_result))
|
||||
for segment in split_result.evidence_only_segments:
|
||||
evidence.append({
|
||||
'segment_id': segment.segment_id,
|
||||
@@ -441,9 +451,7 @@ def _apply_split_rules_for_row(
|
||||
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}')
|
||||
issues.extend(_split_blocking_issue_codes(split_result))
|
||||
for segment in split_result.evidence_only_segments:
|
||||
split_evidence.append({
|
||||
'segment_id': segment.segment_id,
|
||||
@@ -507,7 +515,7 @@ def extract_xfa_profile(
|
||||
|
||||
核心逻辑:校验 definition → 要求 bindings-only(拒绝 legacy mappings)→
|
||||
按 scope 迭代 bindings → 读权威集合行 → 从 schema_fields 标准化;
|
||||
无 bindings → xfa_visual_bindings_required;双源 → xfa_dual_binding_source。
|
||||
无 bindings → xfa_mapping_required;双源 → xfa_dual_binding_source。
|
||||
|
||||
Args:
|
||||
raw_profile: 冻结 Profile 快照(含 definition / checksum)。
|
||||
@@ -531,7 +539,7 @@ def extract_xfa_profile(
|
||||
if not has_bindings:
|
||||
return XfaExtractionResult(
|
||||
status='failed',
|
||||
reason_codes=['xfa_visual_bindings_required'],
|
||||
reason_codes=['xfa_mapping_required'],
|
||||
packet_checksum=packet_checksum,
|
||||
dataset_structure_fingerprint=dataset_structure_fingerprint,
|
||||
profile_checksum=str(raw_profile.get('checksum') or '') or None,
|
||||
@@ -690,32 +698,30 @@ def extract_xfa_profile(
|
||||
'evidence_ref': header.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
})
|
||||
pending_price_unit_raw: str | None = None
|
||||
pending_price_unit_path: str | None = None
|
||||
for binding in line_bindings:
|
||||
if str(binding.field_code or '') in split_produced_codes:
|
||||
continue
|
||||
if str(binding.value_binding.path_id or '') in split_source_path_ids:
|
||||
continue
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
raw_value = row_values.get(data_path)
|
||||
extract_raw = raw_value
|
||||
# 业务字段属于 line 不代表 datasets 值必须物理存放在每条 DATA 中。
|
||||
# 部分供应商 XFA 将整单 Reservation 放在 Header;该 binding 仍须由管理员
|
||||
# 显式确认到共同明细字段框,随后把同一份 datasets 正式证据投影到每行。
|
||||
inherited_from_header = bool(
|
||||
data_path and not data_path.startswith(f'{normalized_auth_path}/')
|
||||
)
|
||||
raw_value = (
|
||||
read_dataset_value(dataset_analysis, data_path)
|
||||
if inherited_from_header
|
||||
else row_values.get(data_path)
|
||||
)
|
||||
value_type, normalizer_key, validator_key = _schema_metadata_for_field(
|
||||
schema_fields=schema_fields,
|
||||
field_id=binding.field_id,
|
||||
field_code=binding.field_code,
|
||||
)
|
||||
# [STEP] NETPR 复合值:拆出单价;价格单位若无独立 binding 则稍后补齐。
|
||||
if str(binding.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 = data_path
|
||||
extracted = _extract_one_field(
|
||||
raw_value=extract_raw if extract_raw is not None else raw_value,
|
||||
raw_value=raw_value,
|
||||
mapping_id=binding.binding_id,
|
||||
field_id=binding.field_id,
|
||||
field_code=binding.field_code,
|
||||
@@ -727,24 +733,6 @@ def extract_xfa_profile(
|
||||
document_id=document_id,
|
||||
packet_checksum=packet_checksum,
|
||||
)
|
||||
# 保留原文 quote(含 ``898.72 / 1``)便于审计对账。
|
||||
if (
|
||||
str(binding.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:
|
||||
@@ -759,52 +747,9 @@ def extract_xfa_profile(
|
||||
'evidence_ref': extracted.evidence,
|
||||
'highlight_source': 'xfa_dataset',
|
||||
'row_index': index,
|
||||
**({'inherited_from_header': True} if inherited_from_header else {}),
|
||||
})
|
||||
|
||||
# 仅映射 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',
|
||||
@@ -817,6 +762,8 @@ def extract_xfa_profile(
|
||||
if has_unconfirmed_split_rules:
|
||||
reason_codes.append('xfa_split_rule_unconfirmed')
|
||||
source_mapping_incomplete = bool(required_missing)
|
||||
if source_mapping_incomplete:
|
||||
reason_codes.append('xfa_source_mapping_incomplete')
|
||||
|
||||
evidence_summary = sanitize_xfa_dto({
|
||||
'header_field_count': len(header_fields),
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
"""
|
||||
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=[],
|
||||
)
|
||||
@@ -156,10 +156,21 @@ def compile_safe_regex(
|
||||
flags = 0 if case_sensitive else re.IGNORECASE
|
||||
if _HAS_RE2 and _re2 is not None:
|
||||
try:
|
||||
re2_flags = _re2.Flags(0)
|
||||
if not case_sensitive:
|
||||
re2_flags = _re2.Flags.CASE_INSENSITIVE # type: ignore[attr-defined]
|
||||
compiled_re2 = _re2.compile(str(pattern), re2_flags)
|
||||
# google-re2 bindings have two public shapes: older bindings expose
|
||||
# Flags, while current pybind bindings accept an Options instance.
|
||||
# Keep RE2 linear-time execution in both cases; never silently fall
|
||||
# through to in-process Python ``re`` merely because the API changed.
|
||||
if hasattr(_re2, 'Flags'):
|
||||
re2_flags = _re2.Flags(0)
|
||||
if not case_sensitive:
|
||||
re2_flags = _re2.Flags.CASE_INSENSITIVE # type: ignore[attr-defined]
|
||||
compiled_re2 = _re2.compile(str(pattern), re2_flags)
|
||||
elif hasattr(_re2, 'Options'):
|
||||
options = _re2.Options()
|
||||
options.case_sensitive = bool(case_sensitive)
|
||||
compiled_re2 = _re2.compile(str(pattern), options)
|
||||
else:
|
||||
raise SafeRegexError('unsupported re2 binding API')
|
||||
group_count = compiled_re2.groups if hasattr(compiled_re2, 'groups') else 0
|
||||
if int(group_count or 0) > max_groups:
|
||||
raise SafeRegexError('regex capture groups exceed limit')
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
backend/app/services/shipping_notice/document_layout/xfa_signature.py
|
||||
|
||||
用途:计算 XFA template packet checksum、datasets 结构指纹、统一 binding/拆分
|
||||
内容指纹与治理用 structure signature。
|
||||
内容指纹,供 xfa_dataset value adapter 身份复验。
|
||||
依赖:xfa_contract、xfa_dataset.XfaDatasetNode、标准库 hashlib/json。
|
||||
逻辑:由 xfa_analysis / 验证服务调用;指纹忽略业务值与行数;structure signature
|
||||
与 definition checksum 覆盖视觉绑定与拆分规则业务字段。
|
||||
逻辑:由 xfa_analysis / 验证服务调用;指纹忽略业务值与行数;共同 Profile
|
||||
视觉身份只使用 layout_signature,XFA 仅提供末端取值 adapter 证据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +15,6 @@ import json
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_STRUCTURE_SIGNATURE_ID,
|
||||
XfaStructureNodeSpec,
|
||||
XfaUnifiedFieldBinding,
|
||||
canonical_unified_bindings_payload,
|
||||
@@ -100,56 +99,6 @@ def build_signature_summary(
|
||||
}
|
||||
|
||||
|
||||
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),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def compute_unified_bindings_checksum(
|
||||
bindings: list[XfaUnifiedFieldBinding] | list[dict[str, Any]],
|
||||
) -> str:
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/document_layout/xfa_split_preview_token.py
|
||||
|
||||
用途:签发与校验 XFA 拆分规则预览确认令牌,防止客户端自行声明 confirmed。
|
||||
依赖:Flask current_app.SECRET_KEY、hmac、hashlib、time、secrets、redis_client。
|
||||
逻辑:由 preview_xfa_split_rules 签发;save_draft / 确认接口经 verify_and_consume 原子消费 jti;
|
||||
逻辑:由 datasets adapter 的拆分预览签发;共同保存流经 adapter 原子消费 jti;
|
||||
生产/预发/多 Worker:Redis 不可用时 fail-closed(STORE_UNAVAILABLE);
|
||||
仅 TESTING 或单进程 development(ALLOW_MEMORY_JTI)允许进程内兜底。
|
||||
"""
|
||||
|
||||
@@ -371,6 +371,9 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -
|
||||
payload.pop('requires_confirmation', None)
|
||||
payload.pop('rule_version', None)
|
||||
payload.pop('rule_id', None)
|
||||
# 指纹排除映射语义,但不得原地修改 definition_json 中的规则;调用者还会
|
||||
# 将同一规则对象交给 normalize/save,原地 pop 会使已确认草稿不可再次编辑。
|
||||
payload = json.loads(json.dumps(payload))
|
||||
for rule in payload.get('rules') or []:
|
||||
segment = rule.get('segment') if isinstance(rule, dict) else None
|
||||
if not isinstance(segment, dict):
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/xfa_template_parser.py
|
||||
|
||||
用途:防御性解析 XFA template packet,提取 field/draw 节点的 bind 引用与近似几何
|
||||
(x/y/w/h 属性),供自研静态合成预览定位回显文本。
|
||||
依赖:lxml、xfa_packets.preflight_xml_bytes、xfa_dataset._hardened_parser 模式。
|
||||
逻辑:由 xfa_preview_renderer 调用;不执行 JS/FormCalc、不联网;解析失败返回空列表。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from lxml import etree
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_packets import XfaPacketError, preflight_xml_bytes
|
||||
|
||||
_DIMENSION_RE = re.compile(
|
||||
r'^\s*(?P<value>-?\d+(?:\.\d+)?)\s*(?P<unit>pt|mm|in|cm|px)?\s*$',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# 常见页面参考尺寸(Letter pt),仅用于将绝对单位粗略归一化。
|
||||
_DEFAULT_PAGE_WIDTH_PT = 612.0
|
||||
_DEFAULT_PAGE_HEIGHT_PT = 792.0
|
||||
_FIELD_DRAW_LOCAL_NAMES = frozenset({'field', 'draw'})
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class XfaTemplateFieldGeometry:
|
||||
"""
|
||||
template 中可定位的 field/draw 摘要。
|
||||
|
||||
坐标为页面相对归一化框(左上原点 0..1);无法可靠归一化时 normalized_bbox 为空。
|
||||
"""
|
||||
|
||||
name: str
|
||||
bind_ref: str
|
||||
page_no: int
|
||||
raw_x: float | None
|
||||
raw_y: float | None
|
||||
raw_w: float | None
|
||||
raw_h: float | None
|
||||
normalized_bbox: dict[str, float] | None
|
||||
local_name: str
|
||||
|
||||
|
||||
def _local_name(tag: str) -> str:
|
||||
"""提取 XML localName,忽略命名空间前缀。"""
|
||||
return str(tag or '').rsplit('}', 1)[-1].lower()
|
||||
|
||||
|
||||
def _hardened_parser() -> etree.XMLParser:
|
||||
"""
|
||||
构造禁用外部实体与 DTD 的 lxml 解析器。
|
||||
|
||||
Returns:
|
||||
与 datasets 解析同策略的安全 XMLParser。
|
||||
"""
|
||||
return etree.XMLParser(
|
||||
resolve_entities=False,
|
||||
load_dtd=False,
|
||||
no_network=True,
|
||||
huge_tree=False,
|
||||
)
|
||||
|
||||
|
||||
def _parse_dimension(raw: str | None) -> float | None:
|
||||
"""
|
||||
解析 XFA 尺寸属性(可带 pt/mm/in/cm/px 后缀)为浮点数。
|
||||
|
||||
核心逻辑:无单位时原样返回数值;有单位时统一换算为 pt(近似)。
|
||||
|
||||
Args:
|
||||
raw: 属性字符串,如 ``36pt``、``10mm``、``0.25``。
|
||||
|
||||
Returns:
|
||||
数值(pt 或无单位原值);无法解析时返回 None。
|
||||
"""
|
||||
text = str(raw or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
match = _DIMENSION_RE.match(text)
|
||||
if not match:
|
||||
return None
|
||||
try:
|
||||
value = float(match.group('value'))
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
unit = (match.group('unit') or '').lower()
|
||||
if not unit or unit == 'pt' or unit == 'px':
|
||||
return value
|
||||
if unit == 'in':
|
||||
return value * 72.0
|
||||
if unit == 'mm':
|
||||
return value * 72.0 / 25.4
|
||||
if unit == 'cm':
|
||||
return value * 72.0 / 2.54
|
||||
return value
|
||||
|
||||
|
||||
def _attr(element: etree._Element, *names: str) -> str:
|
||||
"""按候选属性名读取第一个非空值(忽略命名空间前缀)。"""
|
||||
for name in names:
|
||||
for key, value in element.attrib.items():
|
||||
local = str(key).rsplit('}', 1)[-1]
|
||||
if local.lower() == name.lower() and str(value or '').strip():
|
||||
return str(value).strip()
|
||||
return ''
|
||||
|
||||
|
||||
def _extract_bind_ref(element: etree._Element) -> str:
|
||||
"""
|
||||
从 field/draw 或其 bind 子节点提取 dataRef。
|
||||
|
||||
核心逻辑:优先读子节点 ``bind`` 的 ref/dataRef;否则读自身 bind/ref 属性。
|
||||
"""
|
||||
direct = _attr(element, 'bind', 'ref', 'dataRef')
|
||||
if direct:
|
||||
return direct
|
||||
for child in element:
|
||||
if not isinstance(child.tag, str):
|
||||
continue
|
||||
if _local_name(child.tag) != 'bind':
|
||||
continue
|
||||
ref = _attr(child, 'ref', 'dataRef', 'match')
|
||||
if ref and ref.lower() not in {'none', 'dataref', 'once', 'global', 'dataRef'.lower()}:
|
||||
return ref
|
||||
# match="dataRef" 时真正路径常在 ref
|
||||
ref2 = _attr(child, 'ref', 'dataRef')
|
||||
if ref2:
|
||||
return ref2
|
||||
return ''
|
||||
|
||||
|
||||
def _normalize_bbox_from_raw(
|
||||
*,
|
||||
x: float | None,
|
||||
y: float | None,
|
||||
w: float | None,
|
||||
h: float | None,
|
||||
page_width: float,
|
||||
page_height: float,
|
||||
) -> dict[str, float] | None:
|
||||
"""
|
||||
将 template 原始 x/y/w/h 粗略归一化为左上原点 0..1 框。
|
||||
|
||||
核心逻辑:若数值均落在 0..1 则视为已归一化;否则按 page pt 尺寸换算。
|
||||
XFA 模板常以左下为原点,此处按「y 为距底边」尝试翻转;若翻转后越界则按左上解释。
|
||||
|
||||
Args:
|
||||
x/y/w/h: 原始尺寸(pt 或相对)。
|
||||
page_width/page_height: 参考页尺寸(pt)。
|
||||
|
||||
Returns:
|
||||
``{x0,y0,x1,y1}``;无法构成有效框时返回 None。
|
||||
"""
|
||||
if x is None or y is None or w is None or h is None:
|
||||
return None
|
||||
if w <= 0 or h <= 0:
|
||||
return None
|
||||
if page_width <= 0 or page_height <= 0:
|
||||
return None
|
||||
|
||||
# [STEP 1] 已是相对坐标
|
||||
if 0.0 <= x <= 1.0 and 0.0 <= y <= 1.0 and 0.0 < w <= 1.0 and 0.0 < h <= 1.0:
|
||||
x0, y0, x1, y1 = x, y, x + w, y + h
|
||||
else:
|
||||
# [STEP 2] 绝对 pt:优先按 PDF 左下原点翻转
|
||||
x0 = x / page_width
|
||||
x1 = (x + w) / page_width
|
||||
y0_flip = 1.0 - ((y + h) / page_height)
|
||||
y1_flip = 1.0 - (y / page_height)
|
||||
y0_top = y / page_height
|
||||
y1_top = (y + h) / page_height
|
||||
if 0.0 <= y0_flip <= 1.0 and 0.0 <= y1_flip <= 1.0 and y1_flip > y0_flip:
|
||||
y0, y1 = y0_flip, y1_flip
|
||||
else:
|
||||
y0, y1 = y0_top, y1_top
|
||||
|
||||
x0 = max(0.0, min(1.0, x0))
|
||||
x1 = max(0.0, min(1.0, x1))
|
||||
y0 = max(0.0, min(1.0, y0))
|
||||
y1 = max(0.0, min(1.0, y1))
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return None
|
||||
return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
|
||||
|
||||
|
||||
def _resolve_page_no(element: etree._Element, default_page: int = 1) -> int:
|
||||
"""从节点或其祖先读取 page/pageNum 属性;非法时回退 default_page。"""
|
||||
current: etree._Element | None = element
|
||||
while current is not None:
|
||||
raw = _attr(current, 'page', 'pageNum', 'page_no')
|
||||
if raw:
|
||||
try:
|
||||
value = int(float(raw))
|
||||
if value >= 1:
|
||||
return value
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
parent = current.getparent()
|
||||
current = parent if isinstance(parent, etree._Element) else None
|
||||
return max(1, int(default_page))
|
||||
|
||||
|
||||
def parse_xfa_template_field_geometries(
|
||||
template_bytes: bytes,
|
||||
*,
|
||||
page_width: float = _DEFAULT_PAGE_WIDTH_PT,
|
||||
page_height: float = _DEFAULT_PAGE_HEIGHT_PT,
|
||||
) -> list[XfaTemplateFieldGeometry]:
|
||||
"""
|
||||
解析 XFA template packet,提取带 bind 与近似位置的 field/draw 节点。
|
||||
|
||||
核心逻辑:preflight → hardened lxml 解析 → 遍历 field/draw;读取 name/bind 与
|
||||
x/y/w/h;失败或不可解析时返回空列表(不抛给调用方)。
|
||||
|
||||
Args:
|
||||
template_bytes: template packet XML 字节。
|
||||
page_width: 用于绝对坐标归一化的参考页宽(pt)。
|
||||
page_height: 用于绝对坐标归一化的参考页高(pt)。
|
||||
|
||||
Returns:
|
||||
几何摘要列表;不可解析时为空列表。
|
||||
"""
|
||||
if not template_bytes:
|
||||
return []
|
||||
try:
|
||||
preflight_xml_bytes(template_bytes)
|
||||
root = etree.fromstring(template_bytes, parser=_hardened_parser())
|
||||
except (XfaPacketError, etree.XMLSyntaxError, ValueError, TypeError, OSError):
|
||||
return []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
results: list[XfaTemplateFieldGeometry] = []
|
||||
for element in root.iter():
|
||||
if not isinstance(element.tag, str):
|
||||
continue
|
||||
local = _local_name(element.tag)
|
||||
if local not in _FIELD_DRAW_LOCAL_NAMES:
|
||||
continue
|
||||
name = _attr(element, 'name') or local
|
||||
bind_ref = _extract_bind_ref(element)
|
||||
x = _parse_dimension(_attr(element, 'x'))
|
||||
y = _parse_dimension(_attr(element, 'y'))
|
||||
w = _parse_dimension(_attr(element, 'w', 'width'))
|
||||
h = _parse_dimension(_attr(element, 'h', 'height'))
|
||||
page_no = _resolve_page_no(element)
|
||||
bbox = _normalize_bbox_from_raw(
|
||||
x=x, y=y, w=w, h=h, page_width=page_width, page_height=page_height,
|
||||
)
|
||||
results.append(XfaTemplateFieldGeometry(
|
||||
name=name,
|
||||
bind_ref=bind_ref,
|
||||
page_no=page_no,
|
||||
raw_x=x,
|
||||
raw_y=y,
|
||||
raw_w=w,
|
||||
raw_h=h,
|
||||
normalized_bbox=bbox,
|
||||
local_name=local,
|
||||
))
|
||||
return results
|
||||
|
||||
|
||||
def serialize_template_field_geometries(
|
||||
items: list[XfaTemplateFieldGeometry],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
将 template 几何摘要序列化为普通字典列表(测试/诊断用)。
|
||||
|
||||
Args:
|
||||
items: parse_xfa_template_field_geometries 结果。
|
||||
|
||||
Returns:
|
||||
可 JSON 化的字典列表。
|
||||
"""
|
||||
return [
|
||||
{
|
||||
'name': item.name,
|
||||
'bind_ref': item.bind_ref,
|
||||
'page_no': item.page_no,
|
||||
'raw_x': item.raw_x,
|
||||
'raw_y': item.raw_y,
|
||||
'raw_w': item.raw_w,
|
||||
'raw_h': item.raw_h,
|
||||
'normalized_bbox': item.normalized_bbox,
|
||||
'local_name': item.local_name,
|
||||
}
|
||||
for item in items
|
||||
]
|
||||
@@ -74,7 +74,7 @@ def _normalize_comparable(value: Any, *, value_type: str | None = None) -> str |
|
||||
"""
|
||||
将 datasets / AcroForm 展示值收敛为可比较的标准化字符串。
|
||||
|
||||
核心逻辑:金额去千分位;日期接受 ISO 与 DD/MM/YYYY;数量去尾随零。
|
||||
核心逻辑:金额去千分位;日期接受 ISO、数字日期及明确英文月份;数量去尾随零。
|
||||
"""
|
||||
if value is None:
|
||||
return None
|
||||
@@ -83,7 +83,10 @@ def _normalize_comparable(value: Any, *, value_type: str | None = None) -> str |
|
||||
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')
|
||||
date_patterns = (
|
||||
'%Y-%m-%d', '%Y/%m/%d', '%d/%m/%Y', '%m/%d/%Y', '%d-%m-%Y', '%Y%m%d',
|
||||
'%d-%b-%Y', '%d-%B-%Y',
|
||||
)
|
||||
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:
|
||||
@@ -115,8 +118,10 @@ def _normalize_comparable(value: Any, *, value_type: str | None = None) -> str |
|
||||
return text.casefold()
|
||||
|
||||
|
||||
def _field_map_from_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""从提取行中收集 field_code → value 映射(按行)。"""
|
||||
def _field_map_from_rows(
|
||||
rows: list[dict[str, Any]], *, registered_field_codes: set[str] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""从提取行中收集已正式绑定的 field_code → value 映射(按行)。"""
|
||||
result: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
mapping: dict[str, Any] = {}
|
||||
@@ -124,24 +129,39 @@ def _field_map_from_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
code = str(item.get('field_code') or '').strip()
|
||||
if code:
|
||||
if code and (registered_field_codes is None or code in registered_field_codes):
|
||||
mapping[code] = item.get('value')
|
||||
result.append(mapping)
|
||||
return result
|
||||
|
||||
|
||||
def _line_amount_operands(mapping: dict[str, Any]) -> tuple[Any, Any, Any]:
|
||||
"""读取通用金额恒等式的数量、单价与金额字段。"""
|
||||
return (
|
||||
mapping.get('quantity', mapping.get('qty')),
|
||||
mapping.get('unit_price'),
|
||||
mapping.get('amount', mapping.get('line_amount_with_tax')),
|
||||
)
|
||||
|
||||
|
||||
def _line_amount_expected(*, quantity: Decimal, unit_price: Decimal) -> Decimal:
|
||||
"""计算通用金额恒等式的预期值:数量 × 已归一化单价。"""
|
||||
return quantity * unit_price
|
||||
|
||||
|
||||
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'))
|
||||
quantity_value, unit_price_value, amount_value = _line_amount_operands(mapping)
|
||||
quantity = _to_decimal(quantity_value)
|
||||
unit_price = _to_decimal(unit_price_value)
|
||||
amount = _to_decimal(amount_value)
|
||||
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
|
||||
expected = _line_amount_expected(
|
||||
quantity=quantity,
|
||||
unit_price=unit_price,
|
||||
)
|
||||
if expected.quantize(Decimal('0.01')) != amount.quantize(Decimal('0.01')):
|
||||
# 允许未量化的精确相等。
|
||||
if expected != amount:
|
||||
@@ -150,30 +170,35 @@ def _validate_line_amount_formula(line_maps: list[dict[str, Any]]) -> bool:
|
||||
|
||||
|
||||
def _line_amount_failures(line_maps: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""返回明细金额校验失败的具体行和值,供模板管理员定位映射或数据问题。"""
|
||||
"""返回通用金额恒等式校验失败的具体行和值。"""
|
||||
failures: list[dict[str, Any]] = []
|
||||
for row_index, mapping in enumerate(line_maps, start=1):
|
||||
quantity = _to_decimal(mapping.get('quantity'))
|
||||
unit_price = _to_decimal(mapping.get('unit_price'))
|
||||
amount = _to_decimal(mapping.get('amount'))
|
||||
price_unit = _to_decimal(mapping.get('price_unit')) or Decimal('1')
|
||||
if quantity is None or unit_price is None or amount is None or price_unit == 0:
|
||||
quantity_value, unit_price_value, amount_value = _line_amount_operands(mapping)
|
||||
quantity = _to_decimal(quantity_value)
|
||||
unit_price = _to_decimal(unit_price_value)
|
||||
amount = _to_decimal(amount_value)
|
||||
expected = (
|
||||
_line_amount_expected(
|
||||
quantity=quantity,
|
||||
unit_price=unit_price,
|
||||
)
|
||||
if quantity is not None and unit_price is not None
|
||||
else None
|
||||
)
|
||||
if quantity is None or unit_price is None or amount is None or expected is None:
|
||||
failures.append({
|
||||
'row_index': row_index,
|
||||
'quantity': mapping.get('quantity'),
|
||||
'unit_price': mapping.get('unit_price'),
|
||||
'price_unit': mapping.get('price_unit'),
|
||||
'amount': mapping.get('amount'),
|
||||
'quantity': quantity_value,
|
||||
'unit_price': unit_price_value,
|
||||
'amount': amount_value,
|
||||
'reason': 'missing_or_invalid_operand',
|
||||
})
|
||||
continue
|
||||
expected = (quantity * unit_price) / price_unit
|
||||
if expected.quantize(Decimal('0.01')) != amount.quantize(Decimal('0.01')) and expected != amount:
|
||||
failures.append({
|
||||
'row_index': row_index,
|
||||
'quantity': str(quantity),
|
||||
'unit_price': str(unit_price),
|
||||
'price_unit': str(price_unit),
|
||||
'amount': str(amount),
|
||||
'expected_amount': str(expected),
|
||||
'reason': 'amount_mismatch',
|
||||
@@ -421,6 +446,10 @@ def _validate_acroform(
|
||||
)
|
||||
if not dataset_values:
|
||||
continue
|
||||
# 只有明确指向已确认拆分段的 binding 才能跳过原始 Widget 全文对账;
|
||||
# 不再按字段名猜测“单价/价格单位”复合语义。
|
||||
if binding.split_rule_ref is not None:
|
||||
continue
|
||||
if not acro_values:
|
||||
missing_counterpart += len(dataset_values)
|
||||
continue
|
||||
@@ -719,11 +748,19 @@ def validate_xfa_extraction(
|
||||
summary['acroform_status'] = acro_status
|
||||
summary['acroform_mismatches'] = acro_mismatches
|
||||
|
||||
line_maps = _field_map_from_rows(extraction.rows)
|
||||
registered_line_field_codes = {
|
||||
str(binding.field_code or '') for binding in profile.bindings
|
||||
if binding.scope == 'line' and str(binding.field_code or '').strip()
|
||||
}
|
||||
line_maps = _field_map_from_rows(
|
||||
extraction.rows, registered_field_codes=registered_line_field_codes,
|
||||
)
|
||||
|
||||
# [STEP 3] 明细金额公式
|
||||
if profile.cross_checks.line_amount_formula == 'quantity_times_unit_price':
|
||||
line_amount_failures = _line_amount_failures(line_maps)
|
||||
line_amount_failures = _line_amount_failures(
|
||||
line_maps,
|
||||
)
|
||||
if line_amount_failures:
|
||||
reason_codes.append('xfa_business_validation_failed')
|
||||
summary['line_amount_status'] = 'failed'
|
||||
|
||||
@@ -1,336 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/document_layout/xfa_visual_binding.py
|
||||
|
||||
用途:XFA 统一视觉绑定的候选评分、歧义诊断与建议结果组装(纯函数,不写数据库)。
|
||||
依赖:xfa_acroform、xfa_dataset、xfa_contract(归一化框与 path 哈希)。
|
||||
逻辑:由 order_document_profile_visual_binding_service 调用;画框或 Widget 命中后
|
||||
返回 suggested 候选列表与 diagnostics;高置信也不得自动 confirmed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.xfa_acroform import (
|
||||
XfaAcroformWidget,
|
||||
build_widget_path_candidates,
|
||||
read_acroform_widgets,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import hash_data_path
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaDatasetAnalysis
|
||||
|
||||
|
||||
VisualCandidateStatus = Literal['suggested']
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class VisualPathCandidate:
|
||||
"""datasets 路径候选摘要(不含完整 XPath 明文时可仅含 hash)。"""
|
||||
|
||||
path_id: str
|
||||
data_path_hash: str
|
||||
dataset_value_masked: str
|
||||
match_hint: str
|
||||
confidence: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class VisualBindingCandidate:
|
||||
"""单个 Widget/区域视觉绑定候选;status 恒为 suggested,禁止自动 confirmed。"""
|
||||
|
||||
candidate_id: str
|
||||
widget_id: str
|
||||
page_no: int
|
||||
normalized_bbox: dict[str, float]
|
||||
acroform_field_name_tail: str
|
||||
display_value_masked: str
|
||||
path_candidates: list[VisualPathCandidate] = field(default_factory=list)
|
||||
overlap_score: float = 0.0
|
||||
value_match_score: float = 0.0
|
||||
confidence: float = 0.0
|
||||
status: VisualCandidateStatus = 'suggested'
|
||||
|
||||
|
||||
@dataclass
|
||||
class VisualBindingDiagnostics:
|
||||
"""歧义与覆盖诊断;供管理员确认前展示。"""
|
||||
|
||||
candidate_count: int = 0
|
||||
ambiguous: bool = False
|
||||
ambiguity_reason: str | None = None
|
||||
top_confidence: float = 0.0
|
||||
second_confidence: float = 0.0
|
||||
auto_confirm_blocked: bool = True
|
||||
notes: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
def _bbox_area(bbox: dict[str, float]) -> float:
|
||||
"""计算归一化框面积;非法框返回 0。"""
|
||||
x0 = float(bbox.get('x0') or 0)
|
||||
y0 = float(bbox.get('y0') or 0)
|
||||
x1 = float(bbox.get('x1') or 0)
|
||||
y1 = float(bbox.get('y1') or 0)
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return 0.0
|
||||
return (x1 - x0) * (y1 - y0)
|
||||
|
||||
|
||||
def _bbox_intersection_area(a: dict[str, float], b: dict[str, float]) -> float:
|
||||
"""两框交集面积。"""
|
||||
x0 = max(float(a.get('x0') or 0), float(b.get('x0') or 0))
|
||||
y0 = max(float(a.get('y0') or 0), float(b.get('y0') or 0))
|
||||
x1 = min(float(a.get('x1') or 0), float(b.get('x1') or 0))
|
||||
y1 = min(float(a.get('y1') or 0), float(b.get('y1') or 0))
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return 0.0
|
||||
return (x1 - x0) * (y1 - y0)
|
||||
|
||||
|
||||
def _bbox_overlap_score(region: dict[str, float], widget_bbox: dict[str, float]) -> float:
|
||||
"""
|
||||
区域与 Widget 框重叠得分(IoU 优先,退化时为交集占区域面积比)。
|
||||
|
||||
Args:
|
||||
region: 用户画框或查询区域(0..1)。
|
||||
widget_bbox: AcroForm Widget 归一化框。
|
||||
|
||||
Returns:
|
||||
0..1 重叠得分。
|
||||
"""
|
||||
intersection = _bbox_intersection_area(region, widget_bbox)
|
||||
if intersection <= 0:
|
||||
return 0.0
|
||||
region_area = _bbox_area(region)
|
||||
widget_area = _bbox_area(widget_bbox)
|
||||
union = region_area + widget_area - intersection
|
||||
if union > 0:
|
||||
return intersection / union
|
||||
return intersection / region_area if region_area > 0 else 0.0
|
||||
|
||||
|
||||
def _normalize_compare_value(value: str) -> str:
|
||||
"""值对账用的空白无关规范化。"""
|
||||
return ''.join(str(value or '').casefold().split())
|
||||
|
||||
|
||||
def _value_match_score(display_value: str, dataset_value: str) -> float:
|
||||
"""
|
||||
页面展示值与 datasets 叶子值的标准化匹配分。
|
||||
|
||||
Returns:
|
||||
1.0 精确匹配;0.5 包含关系;0 不匹配。
|
||||
"""
|
||||
left = _normalize_compare_value(display_value)
|
||||
right = _normalize_compare_value(dataset_value)
|
||||
if not left or not right:
|
||||
return 0.0
|
||||
if left == right:
|
||||
return 1.0
|
||||
if left in right or right in left:
|
||||
return 0.5
|
||||
return 0.0
|
||||
|
||||
|
||||
def _candidate_id(widget_id: str, path_id: str) -> str:
|
||||
"""生成稳定的候选 ID(不含敏感明文)。"""
|
||||
digest = hashlib.sha256(f'{widget_id}:{path_id}'.encode('utf-8')).hexdigest()[:16]
|
||||
return f'vbc-{digest}'
|
||||
|
||||
|
||||
def _diagnose_ambiguity(candidates: list[VisualBindingCandidate]) -> VisualBindingDiagnostics:
|
||||
"""
|
||||
诊断候选歧义;同分或接近时标记 ambiguous,且始终阻断自动确认。
|
||||
|
||||
Args:
|
||||
candidates: 已按 confidence 降序排列的候选。
|
||||
|
||||
Returns:
|
||||
诊断摘要。
|
||||
"""
|
||||
diagnostics = VisualBindingDiagnostics(candidate_count=len(candidates))
|
||||
if not candidates:
|
||||
diagnostics.notes.append('no_widget_overlap')
|
||||
return diagnostics
|
||||
diagnostics.top_confidence = float(candidates[0].confidence)
|
||||
if len(candidates) > 1:
|
||||
diagnostics.second_confidence = float(candidates[1].confidence)
|
||||
# [STEP 1] 高置信接近时视为歧义,禁止自动确认
|
||||
if len(candidates) >= 2 and abs(diagnostics.top_confidence - diagnostics.second_confidence) < 0.05:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = 'top_candidates_too_close'
|
||||
elif len(candidates) >= 2 and diagnostics.top_confidence >= 0.85 and diagnostics.second_confidence >= 0.75:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = 'multiple_high_confidence'
|
||||
top_paths = candidates[0].path_candidates
|
||||
if len(top_paths) > 1:
|
||||
diagnostics.ambiguous = True
|
||||
diagnostics.ambiguity_reason = diagnostics.ambiguity_reason or 'multiple_path_candidates'
|
||||
diagnostics.auto_confirm_blocked = True
|
||||
return diagnostics
|
||||
|
||||
|
||||
def suggest_visual_binding_candidates(
|
||||
*,
|
||||
page_no: int,
|
||||
normalized_bbox: dict[str, float],
|
||||
dataset_analysis: XfaDatasetAnalysis,
|
||||
pdf_bytes: bytes | None = None,
|
||||
widgets: list[XfaAcroformWidget] | None = None,
|
||||
min_overlap: float = 0.05,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为指定页面区域生成 AcroForm Widget → datasets 路径的视觉绑定候选。
|
||||
|
||||
核心逻辑:按框重叠筛选 Widget → 为每个 Widget 生成路径候选 → 综合重叠与值匹配
|
||||
评分;所有候选 status 恒为 suggested,歧义写入 diagnostics。
|
||||
|
||||
Args:
|
||||
page_no: 目标 PDF 页码(1-based)。
|
||||
normalized_bbox: 用户画框或查询区域(0..1,左上原点)。
|
||||
dataset_analysis: 已解析的 datasets 结构。
|
||||
pdf_bytes: 原始 PDF;widgets 未传入时用于读取 AcroForm Widget。
|
||||
widgets: 可选预读 Widget 列表(测试/mock 用)。
|
||||
min_overlap: 最小 IoU/重叠阈值。
|
||||
|
||||
Returns:
|
||||
{candidates, diagnostics, page_no, normalized_bbox} 安全 DTO。
|
||||
"""
|
||||
region = {
|
||||
'x0': float(normalized_bbox.get('x0') or 0),
|
||||
'y0': float(normalized_bbox.get('y0') or 0),
|
||||
'x1': float(normalized_bbox.get('x1') or 0),
|
||||
'y1': float(normalized_bbox.get('y1') or 0),
|
||||
}
|
||||
if _bbox_area(region) <= 0:
|
||||
return {
|
||||
'page_no': int(page_no),
|
||||
'normalized_bbox': region,
|
||||
'candidates': [],
|
||||
'diagnostics': VisualBindingDiagnostics(
|
||||
candidate_count=0,
|
||||
notes=['invalid_region_bbox'],
|
||||
).__dict__,
|
||||
}
|
||||
|
||||
widget_list = list(widgets or [])
|
||||
if not widget_list and pdf_bytes:
|
||||
widget_list = read_acroform_widgets(pdf_bytes)
|
||||
|
||||
candidates: list[VisualBindingCandidate] = []
|
||||
for widget in widget_list:
|
||||
if int(widget.page_no) != int(page_no):
|
||||
continue
|
||||
overlap = _bbox_overlap_score(region, widget.normalized_bbox)
|
||||
if overlap < float(min_overlap):
|
||||
continue
|
||||
path_items = build_widget_path_candidates(
|
||||
widget=widget,
|
||||
dataset_analysis=dataset_analysis,
|
||||
)
|
||||
path_candidates: list[VisualPathCandidate] = []
|
||||
best_value_score = 0.0
|
||||
for item in path_items:
|
||||
value_score = _value_match_score(widget.value, item.get('raw_value') or '')
|
||||
best_value_score = max(best_value_score, value_score)
|
||||
path_candidates.append(VisualPathCandidate(
|
||||
path_id=str(item.get('path_id') or ''),
|
||||
data_path_hash=str(item.get('data_path_hash') or ''),
|
||||
dataset_value_masked=str(item.get('dataset_value_masked') or ''),
|
||||
match_hint=str(item.get('match_hint') or 'unmatched'),
|
||||
confidence=round(min(1.0, overlap * 0.6 + value_score * 0.4), 4),
|
||||
))
|
||||
confidence = round(min(1.0, overlap * 0.55 + best_value_score * 0.45), 4)
|
||||
top_path_id = path_candidates[0].path_id if path_candidates else ''
|
||||
candidates.append(VisualBindingCandidate(
|
||||
candidate_id=_candidate_id(widget.widget_id, top_path_id or widget.widget_id),
|
||||
widget_id=widget.widget_id,
|
||||
page_no=int(widget.page_no),
|
||||
normalized_bbox=dict(widget.normalized_bbox),
|
||||
acroform_field_name_tail=widget.short_name,
|
||||
display_value_masked=widget.value_masked,
|
||||
path_candidates=path_candidates,
|
||||
overlap_score=round(overlap, 4),
|
||||
value_match_score=round(best_value_score, 4),
|
||||
confidence=confidence,
|
||||
status='suggested',
|
||||
))
|
||||
|
||||
candidates.sort(key=lambda item: (-item.confidence, item.widget_id))
|
||||
diagnostics = _diagnose_ambiguity(candidates)
|
||||
|
||||
return {
|
||||
'page_no': int(page_no),
|
||||
'normalized_bbox': region,
|
||||
'candidates': [
|
||||
{
|
||||
'candidate_id': item.candidate_id,
|
||||
'widget_id': item.widget_id,
|
||||
'page_no': item.page_no,
|
||||
'normalized_bbox': item.normalized_bbox,
|
||||
'acroform_field_name_tail': item.acroform_field_name_tail,
|
||||
'display_value_masked': item.display_value_masked,
|
||||
'path_candidates': [
|
||||
{
|
||||
'path_id': path.path_id,
|
||||
'data_path_hash': path.data_path_hash,
|
||||
'dataset_value_masked': path.dataset_value_masked,
|
||||
'match_hint': path.match_hint,
|
||||
'confidence': path.confidence,
|
||||
}
|
||||
for path in item.path_candidates
|
||||
],
|
||||
'overlap_score': item.overlap_score,
|
||||
'value_match_score': item.value_match_score,
|
||||
'confidence': item.confidence,
|
||||
'status': item.status,
|
||||
}
|
||||
for item in candidates
|
||||
],
|
||||
'diagnostics': {
|
||||
'candidate_count': diagnostics.candidate_count,
|
||||
'ambiguous': diagnostics.ambiguous,
|
||||
'ambiguity_reason': diagnostics.ambiguity_reason,
|
||||
'top_confidence': diagnostics.top_confidence,
|
||||
'second_confidence': diagnostics.second_confidence,
|
||||
'auto_confirm_blocked': diagnostics.auto_confirm_blocked,
|
||||
'notes': list(diagnostics.notes),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def visual_binding_audit_snapshot(binding: dict[str, Any] | None) -> dict[str, Any] | None:
|
||||
"""
|
||||
提取视觉绑定审计摘要(before/after 用),不含 datasets 明文路径。
|
||||
|
||||
Args:
|
||||
binding: 统一 binding 字典或 None。
|
||||
|
||||
Returns:
|
||||
含 status、bbox、page_no、confidence 的摘要;None 表示无绑定。
|
||||
"""
|
||||
if not isinstance(binding, dict):
|
||||
return None
|
||||
visual = binding.get('visual_binding') if isinstance(binding.get('visual_binding'), dict) else {}
|
||||
if not visual:
|
||||
return None
|
||||
bbox = visual.get('normalized_bbox') if isinstance(visual.get('normalized_bbox'), dict) else {}
|
||||
value = binding.get('value_binding') if isinstance(binding.get('value_binding'), dict) else {}
|
||||
return {
|
||||
'binding_id': binding.get('binding_id'),
|
||||
'field_id': binding.get('field_id'),
|
||||
'field_code': binding.get('field_code'),
|
||||
'status': visual.get('status'),
|
||||
'page_no': visual.get('page_no'),
|
||||
'normalized_bbox': {
|
||||
'x0': bbox.get('x0'),
|
||||
'y0': bbox.get('y0'),
|
||||
'x1': bbox.get('x1'),
|
||||
'y1': bbox.get('y1'),
|
||||
},
|
||||
'source': visual.get('source'),
|
||||
'confidence': visual.get('confidence'),
|
||||
'path_id': value.get('path_id'),
|
||||
'data_path_hash': hash_data_path(str(value.get('data_path') or '')) if value.get('data_path') else None,
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -14,27 +14,50 @@ from app.services.shipping_notice.email_supplement_contract import (
|
||||
EMAIL_SUPPLEMENT_VERSION,
|
||||
empty_email_supplement_result,
|
||||
)
|
||||
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 normalize_table_header
|
||||
from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
_STATIC_HEADERS = {
|
||||
'allocation_id': {'allocation id', 'allocation'},
|
||||
'source_from_party': {'source from party', 'source from', 'from party', 'supplier'},
|
||||
'allocated_entity': {'allocated entity', 'allocation entity'},
|
||||
'allocated_qty': {'allocated qty', 'allocated quantity', 'allocation qty', 'allocation quantity'},
|
||||
}
|
||||
_NORMALIZED_STATIC_HEADERS = {
|
||||
field: {normalize_table_header(item).casefold() for item in aliases}
|
||||
for field, aliases in _STATIC_HEADERS.items()
|
||||
}
|
||||
_SCHEMA_FIELD_TO_SUPPLEMENT_FIELD = {
|
||||
'customer_po_number': 'po_number',
|
||||
'part_number': 'mpn',
|
||||
'reservation_id': 'reservation_id',
|
||||
'inventory_source_hint': 'source_type',
|
||||
}
|
||||
def _schema_configs(schema_definition: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
"""返回冻结 Schema 的启用字段配置,EML 只可产生其中声明的订单字段。"""
|
||||
return {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in schema_definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True) and str(item.get('field_code') or '')
|
||||
}
|
||||
|
||||
|
||||
def _normalize_schema_row(
|
||||
values: dict[str, str], *, schema_definition: dict[str, Any], issues: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
"""按冻结 Schema 规范化并校验 EML 单元格;非法字段不参与任何补充裁决。"""
|
||||
configs = _schema_configs(schema_definition)
|
||||
normalized: dict[str, Any] = {}
|
||||
for field_code, raw_value in values.items():
|
||||
config = configs.get(field_code)
|
||||
if config is None:
|
||||
normalized[field_code] = raw_value
|
||||
continue
|
||||
try:
|
||||
value = normalize_order_field_value(raw_value, config)
|
||||
except Exception:
|
||||
issues.append('email_supplement_field_invalid')
|
||||
return None
|
||||
if value is None or not validate_order_field_value(value, config):
|
||||
issues.append('email_supplement_field_invalid')
|
||||
return None
|
||||
normalized[field_code] = value
|
||||
po_code = 'customer_po_number' if 'customer_po_number' in normalized else 'po_number'
|
||||
po_number = normalize_po_number(normalized.get(po_code))
|
||||
if not po_number:
|
||||
issues.append('email_supplement_row_po_missing')
|
||||
return None
|
||||
normalized[po_code] = po_number
|
||||
return normalized
|
||||
|
||||
|
||||
def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[int, str], list[str]]:
|
||||
@@ -45,8 +68,7 @@ def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[in
|
||||
for column, slot in enumerate(grid.rows[0]):
|
||||
normalized = normalize_table_header(slot.text if slot is not None else '').casefold()
|
||||
schema_field = schema_headers.get(normalized)
|
||||
static_hits = [field for field, aliases in _NORMALIZED_STATIC_HEADERS.items() if normalized in aliases]
|
||||
hits = ([schema_field] if schema_field else []) + static_hits
|
||||
hits = [schema_field] if schema_field else []
|
||||
if len(hits) == 1:
|
||||
if hits[0] in mapped.values():
|
||||
issues.append('email_supplement_duplicate_header')
|
||||
@@ -54,7 +76,7 @@ def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[in
|
||||
mapped[column] = hits[0]
|
||||
elif len(hits) > 1:
|
||||
issues.append('email_supplement_header_ambiguous')
|
||||
if 'po_number' not in mapped.values():
|
||||
if not ({'customer_po_number', 'po_number'} & set(mapped.values())):
|
||||
issues.append('email_supplement_po_header_missing')
|
||||
return mapped, sorted(set(issues))
|
||||
|
||||
@@ -65,15 +87,15 @@ def _schema_headers(schema_definition: dict[str, Any]) -> dict[str, str | None]:
|
||||
for raw in schema_definition.get('fields') or []:
|
||||
if not isinstance(raw, dict) or not raw.get('enabled', True):
|
||||
continue
|
||||
supplement_field = _SCHEMA_FIELD_TO_SUPPLEMENT_FIELD.get(str(raw.get('field_code') or ''))
|
||||
if not supplement_field:
|
||||
field_code = str(raw.get('field_code') or '').strip()
|
||||
if not field_code:
|
||||
continue
|
||||
for value in (raw.get('display_name'), *(raw.get('aliases') or [])):
|
||||
for value in (field_code, raw.get('display_name'), *(raw.get('aliases') or [])):
|
||||
normalized = normalize_table_header(value).casefold()
|
||||
if normalized:
|
||||
if normalized not in headers:
|
||||
headers[normalized] = supplement_field
|
||||
elif headers[normalized] != supplement_field:
|
||||
headers[normalized] = field_code
|
||||
elif headers[normalized] != field_code:
|
||||
headers[normalized] = None
|
||||
return headers
|
||||
|
||||
@@ -107,19 +129,13 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str,
|
||||
'column_index': column, 'cell_id': slot.cell_id,
|
||||
'raw_value': value,
|
||||
}
|
||||
po_number = normalize_po_number(values.get('po_number'))
|
||||
if not po_number:
|
||||
issues.append('email_supplement_row_po_missing')
|
||||
normalized = _normalize_schema_row(
|
||||
values, schema_definition=schema_definition, issues=issues,
|
||||
)
|
||||
if normalized is None:
|
||||
continue
|
||||
values['po_number'] = po_number
|
||||
if values.get('reservation_id'):
|
||||
normalized = validated_reservation_id(values['reservation_id'])
|
||||
if normalized:
|
||||
values['reservation_id'] = normalized
|
||||
else:
|
||||
issues.append('email_supplement_reservation_invalid')
|
||||
rows.append({
|
||||
**values, 'evidence': evidence, 'table_index': table_index,
|
||||
**normalized, 'evidence': evidence, 'table_index': table_index,
|
||||
'row_index': row_index,
|
||||
})
|
||||
result.update({'rows': rows, 'issues': sorted(set(issues))})
|
||||
@@ -134,28 +150,20 @@ def parse_email_allocation_text(*, body_text: str, content_hash: str, schema_def
|
||||
"""
|
||||
result = empty_email_supplement_result()
|
||||
tokens = [line.strip() for line in str(body_text or '').splitlines() if line.strip()]
|
||||
expected = [
|
||||
'allocation_id', 'reservation_id', 'source_from_party', 'source_type',
|
||||
'allocated_entity', 'mpn', 'allocated_qty', 'po_number',
|
||||
]
|
||||
normalized = [normalize_table_header(token) for token in tokens]
|
||||
schema_headers = _schema_headers(schema_definition)
|
||||
aliases: dict[str, set[str]] = {
|
||||
field: {header for header, mapped_field in schema_headers.items() if mapped_field == field}
|
||||
for field in _SCHEMA_FIELD_TO_SUPPLEMENT_FIELD.values()
|
||||
}
|
||||
aliases.update(_NORMALIZED_STATIC_HEADERS)
|
||||
casefold_aliases = {
|
||||
field: {value.casefold() for value in values}
|
||||
for field, values in aliases.items()
|
||||
}
|
||||
start = next((
|
||||
index for index in range(0, len(tokens) - len(expected) + 1)
|
||||
if all(normalized[index + offset].casefold() in casefold_aliases[field] for offset, field in enumerate(expected))
|
||||
), None)
|
||||
header_map = dict(schema_headers)
|
||||
start = next((index for index, value in enumerate(normalized) if header_map.get(value.casefold())), None)
|
||||
if start is None:
|
||||
return result
|
||||
|
||||
expected: list[str] = []
|
||||
for value in normalized[start:]:
|
||||
field = header_map.get(value.casefold())
|
||||
if not field or field in expected:
|
||||
break
|
||||
expected.append(field)
|
||||
if not ({'customer_po_number', 'po_number'} & set(expected)):
|
||||
return result
|
||||
column_count = len(expected)
|
||||
rows: list[dict[str, Any]] = []
|
||||
seen_rows: set[tuple[str, ...]] = set()
|
||||
@@ -163,8 +171,11 @@ def parse_email_allocation_text(*, body_text: str, content_hash: str, schema_def
|
||||
values = tokens[offset:offset + column_count]
|
||||
if len(values) != column_count:
|
||||
break
|
||||
po_number = normalize_po_number(values[-1])
|
||||
if not po_number:
|
||||
row = _normalize_schema_row(
|
||||
{field: value for field, value in zip(expected, values)},
|
||||
schema_definition=schema_definition, issues=result['issues'],
|
||||
)
|
||||
if row is None:
|
||||
# 正文表结束后的普通段落不得作为一条不完整记录继续吞入。
|
||||
break
|
||||
identity = tuple(values)
|
||||
@@ -172,13 +183,6 @@ def parse_email_allocation_text(*, body_text: str, content_hash: str, schema_def
|
||||
if identity in seen_rows:
|
||||
continue
|
||||
seen_rows.add(identity)
|
||||
row = {field: value for field, value in zip(expected, values)}
|
||||
row['po_number'] = po_number
|
||||
reservation_id = validated_reservation_id(row.get('reservation_id'))
|
||||
if not reservation_id:
|
||||
result['issues'].append('email_supplement_reservation_invalid')
|
||||
continue
|
||||
row['reservation_id'] = reservation_id
|
||||
row['evidence'] = {
|
||||
field: {
|
||||
'table_index': None, 'row_index': len(rows) + 1, 'column_index': column,
|
||||
|
||||
@@ -11,7 +11,7 @@ from typing import Any
|
||||
|
||||
EMAIL_SUPPLEMENT_VERSION = 'email-supplement.v1'
|
||||
SUPPLEMENT_FIELDS = (
|
||||
'po_number', 'mpn', 'reservation_id', 'allocation_id', 'source_type',
|
||||
'po_number', 'mpn', 'ampn', 'reservation_id', 'allocation_id', 'source_type',
|
||||
'source_from_party', 'allocated_entity', 'allocated_qty',
|
||||
)
|
||||
|
||||
|
||||
@@ -33,6 +33,19 @@ _SIGNATURE_LOGO_NAME_RE = re.compile(
|
||||
)
|
||||
_HTML_TABLE_TAGS = frozenset({'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td'})
|
||||
_HTML_DROP_TAGS = frozenset({'script', 'style', 'img', 'svg', 'object', 'embed', 'iframe', 'template'})
|
||||
_EML_PREVIEW_TAGS = frozenset({
|
||||
'html', 'body', 'div', 'p', 'span', 'br', 'hr', 'blockquote', 'pre',
|
||||
'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td',
|
||||
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'strong', 'b', 'em', 'i', 'u',
|
||||
})
|
||||
_EML_PREVIEW_STYLE_PROPERTIES = frozenset({
|
||||
'background',
|
||||
'background-color', 'border', 'border-bottom', 'border-collapse', 'border-color', 'border-style',
|
||||
'border-width', 'color', 'font-family', 'font-size', 'font-style', 'font-weight', 'line-height',
|
||||
'margin', 'margin-bottom', 'margin-left', 'margin-right', 'margin-top', 'padding', 'padding-bottom',
|
||||
'padding-left', 'padding-right', 'padding-top', 'text-align', 'text-decoration', 'vertical-align',
|
||||
'white-space', 'width',
|
||||
})
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -260,6 +273,11 @@ def _part_as_text(part: Message) -> str:
|
||||
return text.strip()
|
||||
|
||||
|
||||
def _part_as_raw_html(part: Message) -> str:
|
||||
"""按 MIME charset 解码 HTML 原文,供视觉预览使用;不得经过 HTML 转文本。"""
|
||||
return _decode_part_text(part, _read_part_payload(part))
|
||||
|
||||
|
||||
def _is_attached_multipart(part: Message) -> bool:
|
||||
"""
|
||||
判定 multipart 是否应视为「文件附件容器」(而非可选正文结构)。
|
||||
@@ -380,6 +398,86 @@ def _extract_body_html_tables(msg: Message) -> list[str]:
|
||||
return result
|
||||
|
||||
|
||||
def sanitize_eml_preview_html(html: str) -> str:
|
||||
"""
|
||||
清洗 EML 正文 HTML 为可在 sandbox iframe 中展示的有限视觉快照。
|
||||
|
||||
核心逻辑:仅保留邮件阅读必需的文字/表格标签与有限内联样式;图片、链接、脚本、
|
||||
事件属性和定位/URL 样式全部剥离,避免邮件主动内容影响 HXOPS 页面。
|
||||
|
||||
Args:
|
||||
html: EML 的单个 text/html 正文部件,不得传入附件或嵌套邮件正文。
|
||||
|
||||
Returns:
|
||||
安全 HTML 片段;没有可展示内容时返回空字符串。
|
||||
"""
|
||||
soup = BeautifulSoup(str(html or ''), 'html.parser')
|
||||
for comment in soup.find_all(string=lambda value: isinstance(value, Comment)):
|
||||
comment.extract()
|
||||
for tag in list(soup.find_all(True)):
|
||||
name = str(tag.name or '').lower()
|
||||
if name == 'style':
|
||||
css = str(tag.string or '')
|
||||
css = re.sub(r'(?is)@import[^;]*;', '', css)
|
||||
css = re.sub(r'(?is)url\s*\([^)]*\)', '', css)
|
||||
css = re.sub(r'(?is)expression\s*\([^)]*\)', '', css)
|
||||
tag.string = css
|
||||
continue
|
||||
if name in _HTML_DROP_TAGS or name in {'form', 'input', 'button', 'textarea', 'select', 'option', 'base'}:
|
||||
tag.decompose()
|
||||
continue
|
||||
# 邮件 CSS 由隔离 iframe 自己消费;只禁止外部资源和主动导航,不重写布局属性。
|
||||
for key in list(tag.attrs):
|
||||
key_name = str(key).lower()
|
||||
if key_name.startswith('on') or key_name in {'action', 'formaction', 'src', 'srcset', 'href', 'xlink:href'}:
|
||||
tag.attrs.pop(key, None)
|
||||
if name == 'meta' and str(tag.attrs.get('http-equiv') or '').lower() == 'refresh':
|
||||
tag.decompose()
|
||||
continue
|
||||
inline_styles = [
|
||||
f'{property_name}: {value}'
|
||||
for property_name, value in _parse_inline_style(str(tag.attrs.get('style') or ''))
|
||||
if property_name in _EML_PREVIEW_STYLE_PROPERTIES
|
||||
]
|
||||
if inline_styles:
|
||||
tag.attrs['style'] = '; '.join(inline_styles)
|
||||
else:
|
||||
tag.attrs.pop('style', None)
|
||||
return str(soup).strip()
|
||||
|
||||
|
||||
def _parse_inline_style(value: str) -> list[tuple[str, str]]:
|
||||
"""解析有限 CSS 声明,拒绝 URL、表达式与控制字符等主动样式值。"""
|
||||
result: list[tuple[str, str]] = []
|
||||
for item in str(value or '').split(';'):
|
||||
property_name, separator, raw_value = item.partition(':')
|
||||
name = property_name.strip().lower()
|
||||
normalized = re.sub(r'\s+', ' ', raw_value).strip()
|
||||
if not separator or not name or not normalized:
|
||||
continue
|
||||
if any(token in normalized.lower() for token in ('url(', 'expression(', '@import', '\x00')):
|
||||
continue
|
||||
result.append((name, normalized[:256]))
|
||||
return result
|
||||
|
||||
|
||||
def extract_eml_preview_html(data: bytes) -> str:
|
||||
"""
|
||||
从原始 EML 提取根消息首个 HTML 正文并生成安全视觉快照。
|
||||
|
||||
Args:
|
||||
data: 原始 EML 字节;禁止传入附件展开后的任意子文件。
|
||||
|
||||
Returns:
|
||||
已清洗 HTML;邮件无 HTML 正文时返回空字符串。
|
||||
"""
|
||||
message = BytesParser(policy=policy.default).parsebytes(data or b'')
|
||||
for part in _iter_local_body_candidates(message):
|
||||
if str(part.get_content_type() or '').lower() == 'text/html':
|
||||
return sanitize_eml_preview_html(_part_as_raw_html(part))
|
||||
return ''
|
||||
|
||||
|
||||
def _is_collectible_text_leaf(msg: Message) -> bool:
|
||||
"""判定部件是否可作为附件容器内的可落库文本叶子(非 filename 附件)。"""
|
||||
ctype = str(msg.get_content_type() or "").lower()
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
"""
|
||||
services/shipping_notice/eml_preview_service.py
|
||||
|
||||
用途:按内容身份生成并复用 EML 安全 HTML 预览快照。
|
||||
依赖:FileAsset、ShippingOrderDocument/Intake、eml_parse、file_assets.service。
|
||||
逻辑:复核证据服务在 Case 鉴权后调用;原始 EML 仅在快照缺失时读取,失败由调用方回退纯文本。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
|
||||
from bs4 import BeautifulSoup, NavigableString
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import FileAsset, ShippingEmlPreviewSnapshot, ShippingOrderDocument, ShippingOrderIntake
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.eml_parse import extract_eml_preview_html, sanitize_eml_preview_html
|
||||
from app.services.shipping_notice.preview_grant_store import preview_grant_store
|
||||
|
||||
EML_PREVIEW_SANITIZER_VERSION = 'eml-preview-v3'
|
||||
EML_PREVIEW_MAX_BYTES = 500_000
|
||||
EML_PREVIEW_GRANT_TTL_SECONDS = 120
|
||||
EML_PREVIEW_GRANT_KEY_PREFIX = 'shipping:eml-preview:'
|
||||
|
||||
|
||||
def highlight_eml_preview_html(html: str, quote: str | None) -> str:
|
||||
"""
|
||||
在安全 EML 快照中标出唯一命中的字段证据引文。
|
||||
|
||||
核心逻辑:仅在单个可见文本节点中恰好命中一次时插入无行为的 mark;
|
||||
缺失、跨节点或多处命中均原样返回,禁止按字段值猜测高亮位置。
|
||||
|
||||
Args:
|
||||
html: 已由 sanitize_eml_preview_html 生成的安全 HTML。
|
||||
quote: 当前字段 Observation 的独立引文,不得传机器字段值作为替代。
|
||||
|
||||
Returns:
|
||||
安全 HTML;可靠唯一定位时含 data-hxops-evidence-mark 的 mark 标签。
|
||||
"""
|
||||
needle = str(quote or '').strip()
|
||||
if not needle:
|
||||
return str(html or '')
|
||||
soup = BeautifulSoup(str(html or ''), 'html.parser')
|
||||
matches: list[tuple[NavigableString, int]] = []
|
||||
for node in soup.find_all(string=True):
|
||||
text = str(node)
|
||||
start = text.find(needle)
|
||||
if start < 0:
|
||||
continue
|
||||
if text.find(needle, start + len(needle)) >= 0:
|
||||
return str(html or '')
|
||||
matches.append((node, start))
|
||||
if len(matches) > 1:
|
||||
return str(html or '')
|
||||
if len(matches) != 1:
|
||||
return str(html or '')
|
||||
node, start = matches[0]
|
||||
text = str(node)
|
||||
mark = soup.new_tag('mark')
|
||||
mark['data-hxops-evidence-mark'] = 'true'
|
||||
mark['style'] = 'background: #fde047; color: inherit; outline: 2px solid #ca8a04; outline-offset: 1px;'
|
||||
mark.string = needle
|
||||
node.replace_with(NavigableString(text[:start]), mark, NavigableString(text[start + len(needle):]))
|
||||
return str(soup)
|
||||
|
||||
|
||||
def _eml_preview_grant_store():
|
||||
"""返回 EML iframe 单用途预览令牌存储;生产必须使用 Redis。"""
|
||||
return preview_grant_store()
|
||||
|
||||
|
||||
def issue_eml_preview_grant(*, user_id: int, case_no: str, document_id: int, html: str) -> str:
|
||||
"""签发绑定用户、Case 与正文 Document 的短时单用途 iframe 预览令牌。"""
|
||||
token = secrets.token_urlsafe(32)
|
||||
payload = json.dumps({
|
||||
'user_id': int(user_id), 'case_no': str(case_no), 'document_id': int(document_id), 'html': str(html),
|
||||
}, separators=(',', ':'))
|
||||
_eml_preview_grant_store().setex(
|
||||
f'{EML_PREVIEW_GRANT_KEY_PREFIX}{token}', EML_PREVIEW_GRANT_TTL_SECONDS, payload,
|
||||
)
|
||||
return token
|
||||
|
||||
|
||||
def consume_eml_preview_grant(*, token: str, user_id: int | None = None, case_no: str, document_id: int | None = None) -> str:
|
||||
"""消费单用途令牌并只返回匹配当前用户/Case 的安全 HTML。"""
|
||||
raw = _eml_preview_grant_store().getdel(f'{EML_PREVIEW_GRANT_KEY_PREFIX}{str(token or "").strip()}')
|
||||
if not raw:
|
||||
return ''
|
||||
try:
|
||||
payload = json.loads(raw)
|
||||
except (TypeError, ValueError):
|
||||
return ''
|
||||
if (
|
||||
(user_id is not None and int(payload.get('user_id') or 0) != int(user_id))
|
||||
or str(payload.get('case_no') or '') != str(case_no)
|
||||
or (document_id is not None and int(payload.get('document_id') or 0) != int(document_id))
|
||||
):
|
||||
return ''
|
||||
return str(payload.get('html') or '')
|
||||
|
||||
|
||||
def get_or_create_eml_preview_html(*, document: ShippingOrderDocument) -> str:
|
||||
"""
|
||||
读取或生成邮件正文安全 HTML 快照。
|
||||
|
||||
核心逻辑:以正文 Document 内容哈希和清洗器版本唯一定位;未命中时才读取其 Intake 根 EML,
|
||||
生成成功后写入快照。调用者已负责 Case 属主鉴权,本函数绝不返回存储地址。
|
||||
|
||||
Args:
|
||||
document: 同 Intake 的 email_body Document;其它类型调用返回空字符串。
|
||||
|
||||
Returns:
|
||||
可嵌入 sandbox iframe 的已清洗 HTML;无 HTML 正文或读取失败时为空字符串。
|
||||
"""
|
||||
if str(document.document_type or '') != 'email_body':
|
||||
return ''
|
||||
intake = db.session.get(ShippingOrderIntake, int(document.intake_id))
|
||||
asset = db.session.get(FileAsset, int(intake.asset_id)) if intake and intake.asset_id else None
|
||||
if asset is None:
|
||||
return ''
|
||||
# [STEP 1] 视觉快照按原始 EML 哈希隔离,不能使用只覆盖文本/表格的 Document 哈希。
|
||||
source_hash = str(asset.content_hash or '').strip().lower()
|
||||
if len(source_hash) != 64:
|
||||
return ''
|
||||
existing = ShippingEmlPreviewSnapshot.query.filter_by(
|
||||
document_id=int(document.id), source_content_hash=source_hash,
|
||||
sanitizer_version=EML_PREVIEW_SANITIZER_VERSION,
|
||||
).one_or_none()
|
||||
if existing is not None:
|
||||
return str(existing.html or '')
|
||||
try:
|
||||
html = extract_eml_preview_html(read_asset_bytes(asset))
|
||||
except Exception: # noqa: BLE001 - 预览失败必须回退文本,不能影响复核主链。
|
||||
return ''
|
||||
if not html:
|
||||
return ''
|
||||
encoded = html.encode('utf-8')
|
||||
if len(encoded) > EML_PREVIEW_MAX_BYTES:
|
||||
return ''
|
||||
snapshot = ShippingEmlPreviewSnapshot(
|
||||
document_id=int(document.id), source_content_hash=source_hash,
|
||||
sanitizer_version=EML_PREVIEW_SANITIZER_VERSION, html=html,
|
||||
html_checksum=hashlib.sha256(encoded).hexdigest(), html_size_bytes=len(encoded),
|
||||
)
|
||||
try:
|
||||
# [STEP 2] 并发首次预览只竞争本快照,不能 rollback 当前 Case 读取事务。
|
||||
with db.session.begin_nested():
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
except IntegrityError:
|
||||
reused = ShippingEmlPreviewSnapshot.query.filter_by(
|
||||
document_id=int(document.id), source_content_hash=source_hash,
|
||||
sanitizer_version=EML_PREVIEW_SANITIZER_VERSION,
|
||||
).one_or_none()
|
||||
return str(reused.html or '') if reused is not None else ''
|
||||
return html
|
||||
|
||||
|
||||
__all__ = [
|
||||
'EML_PREVIEW_MAX_BYTES', 'EML_PREVIEW_SANITIZER_VERSION', 'EML_PREVIEW_GRANT_TTL_SECONDS',
|
||||
'consume_eml_preview_grant', 'get_or_create_eml_preview_html', 'issue_eml_preview_grant',
|
||||
'sanitize_eml_preview_html', 'highlight_eml_preview_html',
|
||||
]
|
||||
@@ -90,7 +90,16 @@ DOCUMENT_PARSE_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'xfa_profile_checksum_not_allowlisted',
|
||||
'xfa_scenario_not_allowlisted',
|
||||
'xfa_evidence_incomplete',
|
||||
'xfa_fallback_requires_review',
|
||||
'xfa_cross_check_failed',
|
||||
# adapter 证据与统一视觉发布门禁:均须进入同一 Review / Gate 投影契约。
|
||||
'xfa_mapping_required',
|
||||
'xfa_visual_coverage_insufficient',
|
||||
'xfa_evidence_retention_insufficient',
|
||||
'xfa_mirror_consistency_insufficient',
|
||||
'xfa_profile_checksum_mismatch',
|
||||
'xfa_visual_not_publishable',
|
||||
'xfa_split_rule_unconfirmed',
|
||||
})
|
||||
|
||||
# 字段抽取、客户与订单校验
|
||||
@@ -217,13 +226,14 @@ EXPLAINABILITY_REASON_ALIASES: Final[dict[str, str]] = {
|
||||
'document_profile_not_matched': 'profile_not_matched',
|
||||
'document_profile_ambiguous': 'profile_ambiguous',
|
||||
'document_profile_drifted': 'profile_drift',
|
||||
# Job 历史误写 → 跨门禁技术重试耗尽
|
||||
'technical_failure': 'technical_retry_exhausted',
|
||||
# 历史“重试耗尽”不再对用户暴露;统一为停止后的中性技术失败。
|
||||
'technical_failure': 'technical_failure_present',
|
||||
'technical_retry_exhausted': 'technical_failure_present',
|
||||
# 订单识别 Run.error_code(DOMAIN.SUBTYPE)→ 稳定业务原因码
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED': 'layout_parse_failed',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_SCHEDULING_FAILED': 'layout_parse_failed',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT': 'extraction_incomplete',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED': 'technical_retry_exhausted',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_JOB_FAILED': 'technical_failure_present',
|
||||
# 抽取失败 / 取消必须可区分,禁止一并降级为 unknown_business_failure
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED': 'order_extraction_failed',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED': 'order_extraction_cancelled',
|
||||
@@ -437,10 +447,10 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'xfa_evidence_retention_insufficient': _meta('owner', 'open_order_review', 'XFA 证据留存不足,请进入复核补充证据'),
|
||||
'xfa_mirror_consistency_insufficient': _meta('owner', 'open_order_review', 'XFA 镜像明细一致性不足,请进入复核'),
|
||||
'xfa_profile_checksum_mismatch': _meta('admin', 'open_profile_review', 'XFA 模板校验和不一致,请联系管理员检查模板版本'),
|
||||
'xfa_visual_binding_incomplete': _meta('owner', 'open_profile_review', 'XFA 可视化字段绑定不完整,请补充模板绑定'),
|
||||
'xfa_visual_bindings_required': _meta('owner', 'open_profile_review', 'XFA 尚未完成可视化字段绑定'),
|
||||
'xfa_mapping_required': _meta('owner', 'open_profile_review', '末端值源映射不完整,请补充字段映射'),
|
||||
'xfa_visual_coverage_insufficient': _meta('owner', 'open_profile_review', 'XFA 可视化字段覆盖不足,请补充模板映射'),
|
||||
'xfa_visual_not_publishable': _meta('admin', 'open_profile_review', 'XFA 可视化模板未达到发布条件,请检查模板质量'),
|
||||
'xfa_split_rule_unconfirmed': _meta('owner', 'open_profile_review', 'XFA 字段拆分规则尚未完成确认,请复核后保存模板'),
|
||||
# 附件
|
||||
'attachment_format_unsupported': _meta('owner', 'rematerialize_document', '附件格式不支持'),
|
||||
'attachment_size_exceeded': _meta('owner', 'rematerialize_document', '附件超过系统大小限制'),
|
||||
@@ -491,6 +501,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'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_fallback_requires_review': _meta('owner', 'open_order_review', 'XFA datasets 未能产值,已使用 PDF 证据链,请人工复核'),
|
||||
'xfa_cross_check_failed': _meta('owner', 'open_order_review', 'XFA 对账或业务恒等式未通过'),
|
||||
# Gate 既有阻断码
|
||||
'document_unavailable': _meta('system', 'rematerialize_document', '发货通知文档不可用,请重新上传或物化文档'),
|
||||
@@ -536,20 +547,20 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'task_already_exists': _meta('owner', 'open_order_review', '已存在相同订单任务'),
|
||||
'task_state_not_creatable': _meta('owner', 'open_order_review', '当前任务状态不允许重复创建'),
|
||||
# 库存源路由
|
||||
'no_inventory_source_candidates': _meta('owner', 'open_inventory_source_review', '未匹配到库存源规则'),
|
||||
'inventory_source_unavailable': _meta('admin', 'open_inventory_source_review', '规则命中的库存源当前不可用'),
|
||||
'require_manual_review': _meta('owner', 'open_inventory_source_review', '库存源规则冲突或要求人工确认'),
|
||||
'manual_inventory_source_reason_required': _meta('owner', 'open_inventory_source_review', '须填写人工选源原因'),
|
||||
'manual_inventory_source_invalid': _meta('owner', 'open_inventory_source_review', '所选库存源无效或未启用'),
|
||||
'source_not_found': _meta('admin', 'open_inventory_source_review', '规则命中的库存源不存在'),
|
||||
'source_disabled': _meta('admin', 'open_inventory_source_review', '规则命中的库存源未启用'),
|
||||
'source_runtime_unavailable': _meta('admin', 'open_inventory_source_review', '库存源 RPA 运行配置不可用'),
|
||||
'source_profile_disabled': _meta('admin', 'open_inventory_source_review', '库存源对应的 RPA Profile 未启用'),
|
||||
'parsing_profile_unavailable': _meta('admin', 'open_inventory_source_review', '库存解析 Profile 未发布'),
|
||||
'source_excel_template_unavailable': _meta('admin', 'open_inventory_source_review', '库存 Excel 模板未发布'),
|
||||
'inventory_source_conflicted': _meta('owner', 'open_inventory_source_review', '多条规则产生冲突,需要人工确认'),
|
||||
'inventory_source_changed': _meta('owner', 'open_inventory_source_review', '原已确认库存源配置已变化'),
|
||||
'inventory_source_identity_mismatch': _meta('owner', 'open_inventory_source_review', '当前任务与库存源/仓库身份不一致'),
|
||||
'no_inventory_source_candidates': _meta('system', 'retry_with_latest_rules', '未匹配到库存源规则'),
|
||||
'inventory_source_unavailable': _meta('admin', 'retry_with_latest_rules', '规则命中的库存源当前不可用'),
|
||||
'require_manual_review': _meta('system', 'retry_with_latest_rules', '库存源规则冲突,需修复规则后自动重新裁决'),
|
||||
'manual_inventory_source_reason_required': _meta('system', 'retry_with_latest_rules', '历史人工选源请求已下线,请修复路由规则'),
|
||||
'manual_inventory_source_invalid': _meta('system', 'retry_with_latest_rules', '历史人工选源无效,请修复路由规则'),
|
||||
'source_not_found': _meta('admin', 'retry_with_latest_rules', '规则命中的库存源不存在'),
|
||||
'source_disabled': _meta('admin', 'retry_with_latest_rules', '规则命中的库存源未启用'),
|
||||
'source_runtime_unavailable': _meta('admin', 'retry_with_latest_rules', '库存源 RPA 运行配置不可用'),
|
||||
'source_profile_disabled': _meta('admin', 'retry_with_latest_rules', '库存源对应的 RPA Profile 未启用'),
|
||||
'parsing_profile_unavailable': _meta('admin', 'retry_with_latest_rules', '库存解析 Profile 未发布'),
|
||||
'source_excel_template_unavailable': _meta('admin', 'retry_with_latest_rules', '库存 Excel 模板未发布'),
|
||||
'inventory_source_conflicted': _meta('system', 'retry_with_latest_rules', '多条规则产生冲突,需修复规则后自动重新裁决'),
|
||||
'inventory_source_changed': _meta('system', 'retry_with_latest_rules', '库存源配置已变化,系统将重新裁决'),
|
||||
'inventory_source_identity_mismatch': _meta('system', 'retry_with_latest_rules', '当前任务与库存源身份不一致,需修复规则或订单事实'),
|
||||
'effective_reservation_missing': _meta('owner', 'edit_reservation', '缺少有效的预约单号'),
|
||||
# 库存准备 / RPA / 匹配 / Excel / 上传
|
||||
'inventory_preparation_waiting': _meta('worker', 'poll_inventory_preparation', '库存文件准备中,请稍后刷新'),
|
||||
@@ -560,13 +571,13 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'),
|
||||
'inventory_rpa_exhausted': _meta('owner', 'upload_inventory_file', '库存源重试次数已耗尽'),
|
||||
'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'),
|
||||
'inventory_candidates_missing': _meta('owner', 'open_inventory_source_review', '正式库存候选版本缺失'),
|
||||
'inventory_candidate_data_incomplete': _meta('owner', 'open_inventory_source_review', '库存候选事实不完整'),
|
||||
'inventory_candidate_version_stale': _meta('owner', 'open_inventory_source_review', '库存候选版本已切换'),
|
||||
'inventory_match_out_of_candidate_scope': _meta('owner', 'open_inventory_source_review', '库存命中超出当前候选范围'),
|
||||
'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'),
|
||||
'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'),
|
||||
'inventory_candidate_version_stale': _meta('system', 'retry_with_latest_rules', '库存候选版本已切换'),
|
||||
'inventory_match_out_of_candidate_scope': _meta('system', 'retry_with_latest_rules', '库存命中超出当前候选范围'),
|
||||
'inventory_file_identity_mismatch': _meta('owner', 'retry_inventory_preparation', '返回文件与所选库存源不一致'),
|
||||
'inventory_file_empty': _meta('owner', 'retry_inventory_preparation', '库存文件为空或没有有效库存记录'),
|
||||
'inventory_mapping_required': _meta('owner', 'confirm_inventory_field_mapping', '库存字段映射待确认'),
|
||||
'inventory_mapping_required': _meta('system', 'retry_inventory_field_mapping', '库存字段映射待自动校验'),
|
||||
'inventory_match_failed': _meta('owner', 'open_inventory_match_review', '库存匹配失败'),
|
||||
'inventory_insufficient': _meta('owner', 'open_shortage_review', '库存不足'),
|
||||
'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'),
|
||||
@@ -581,11 +592,6 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'review_required': _meta('owner', 'open_order_review', '需要人工复核后才能继续'),
|
||||
'gate_invalidated': _meta('system', 'recheck_freeze_readiness', '上游结果已变化,当前门禁需重新评估'),
|
||||
'technical_failure_present': _meta('system', 'open_order_review', '存在技术失败,需处理后继续'),
|
||||
'technical_retry_exhausted': _meta(
|
||||
'system',
|
||||
'open_order_review',
|
||||
'系统自动重试已耗尽,请打开订单复核或联系管理员处理',
|
||||
),
|
||||
'order_extraction_failed': _meta('worker', 'retry_order_extraction', '订单字段抽取失败,请重试或进入复核'),
|
||||
'order_extraction_cancelled': _meta('owner', 'open_order_review', '订单抽取已取消'),
|
||||
# 关闭 / 作废 / 访问审计动作码
|
||||
@@ -601,8 +607,8 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'),
|
||||
'excel_input_incomplete': _meta('owner', 'recheck_excel_readiness', '生成 Excel 所需输入不完整'),
|
||||
'artifact_validation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 产物校验失败'),
|
||||
'inventory_required_column_missing': _meta('owner', 'confirm_inventory_field_mapping', '库存文件缺少必填列'),
|
||||
'inventory_column_ambiguous': _meta('owner', 'confirm_inventory_field_mapping', '库存列映射存在歧义'),
|
||||
'inventory_required_column_missing': _meta('system', 'retry_inventory_field_mapping', '库存文件缺少必填列'),
|
||||
'inventory_column_ambiguous': _meta('system', 'retry_inventory_field_mapping', '库存列映射存在歧义'),
|
||||
'inventory_sku_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 SKU'),
|
||||
'inventory_reservation_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 Reservation'),
|
||||
'inventory_warehouse_mismatch': _meta('owner', 'open_inventory_match_review', '仓库与订单要求不一致'),
|
||||
|
||||
@@ -116,6 +116,21 @@ def _system_fact(
|
||||
return values.get(key)
|
||||
|
||||
|
||||
def _template_requires_system_warehouse_id(mappings: list[dict[str, Any]]) -> bool:
|
||||
"""判断发布模板是否实际消费任务级 ``system_fact:warehouse_id``。
|
||||
|
||||
模板将库位作为 ``inventory_field`` 消费时,值来自库存快照或已审计的
|
||||
短缺放行补录字段;不得额外要求任务级 Warehouse ID。只有模板显式引用
|
||||
系统事实时才保留该 fail-closed 门禁。
|
||||
"""
|
||||
return any(
|
||||
isinstance(mapping, dict)
|
||||
and str(mapping.get('source_kind') or '').strip() == 'system_fact'
|
||||
and str(mapping.get('source_key') or '').strip() == 'warehouse_id'
|
||||
for mapping in mappings
|
||||
)
|
||||
|
||||
|
||||
def _format_value(value: Any, formatter: str) -> Any:
|
||||
"""应用发布契约允许的确定性格式化器。"""
|
||||
if value is None:
|
||||
@@ -227,26 +242,40 @@ def _inventory_field_user_label(field_id: str) -> str:
|
||||
return f'库存字段(编号 {normalized or "未知"})'
|
||||
|
||||
|
||||
def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set[str]) -> dict[str, Any]:
|
||||
"""多库存行仅在模板所需字段值一致时合并,避免任意选择第一行。"""
|
||||
def _collapse_inventory_matches(
|
||||
rows: list[dict[str, Any]],
|
||||
required_fields: set[str],
|
||||
*,
|
||||
release_overrides: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""多库存行仅在模板所需字段值一致时合并;短缺放行仅可覆盖该行已审计字段。"""
|
||||
if not rows:
|
||||
return {}
|
||||
resolved = dict(rows[0])
|
||||
for field in required_fields:
|
||||
values = {_match_text(row.get(field)) for row in rows if _match_text(row.get(field))}
|
||||
override = str((release_overrides or {}).get(field) or '').strip()
|
||||
if len(values) > 1:
|
||||
if override:
|
||||
resolved[field] = override
|
||||
continue
|
||||
label = _inventory_field_user_label(field)
|
||||
raise ValueError(f'订单行匹配到多个库存记录,库存字段“{label}”的值不一致,请检查库存映射或库存文件')
|
||||
if values:
|
||||
resolved[field] = next(row.get(field) for row in rows if _match_text(row.get(field)))
|
||||
elif override:
|
||||
resolved[field] = override
|
||||
return resolved
|
||||
|
||||
|
||||
def _match_inventory_lines(
|
||||
order_lines: list[dict[str, Any]], inventory_lines: list[dict[str, Any]],
|
||||
match_keys: list[dict[str, str]], required_fields: set[str],
|
||||
*,
|
||||
release_overrides_by_line: dict[int, dict[str, Any]] | None = None,
|
||||
released_export_line_indexes: set[int] | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按 published 解析 Profile 的稳定字段匹配键解析每条订单行对应库存投影。"""
|
||||
"""按发布匹配键解析库存投影;已审计短缺放行可在导出时使用订单与补录事实。"""
|
||||
if not order_lines:
|
||||
return []
|
||||
if not match_keys:
|
||||
@@ -287,11 +316,60 @@ def _match_inventory_lines(
|
||||
if all(_match_text(row.get(inventory_field)) == value for value, inventory_field in expected)
|
||||
]
|
||||
if not matched:
|
||||
# 短缺放行不改写或伪造库存匹配事实。它只授权导出阶段在匹配键
|
||||
# (例如 Reservation ID)未命中时,以冻结订单字段及已审计补录值
|
||||
# 写模板;模板不消费库存字段时,空映射也是完整、可审计的输入。
|
||||
overrides = (release_overrides_by_line or {}).get(position - 1) or {}
|
||||
resolved_overrides = {
|
||||
field: value
|
||||
for field, value in overrides.items()
|
||||
if field in required_fields and _match_text(value)
|
||||
}
|
||||
is_released = (position - 1) in (released_export_line_indexes or set())
|
||||
if is_released and set(resolved_overrides) == required_fields:
|
||||
result.append(resolved_overrides)
|
||||
continue
|
||||
raise ValueError(f'第 {position} 条订单行没有匹配的库存记录')
|
||||
result.append(_collapse_inventory_matches(matched, required_fields))
|
||||
result.append(_collapse_inventory_matches(
|
||||
matched,
|
||||
required_fields,
|
||||
release_overrides=(release_overrides_by_line or {}).get(position - 1),
|
||||
))
|
||||
return result
|
||||
|
||||
|
||||
def _release_overrides_for_export_lines(
|
||||
*,
|
||||
line_values: list[dict[str, Any]],
|
||||
release_overrides_by_source_line: dict[int, dict[str, Any]],
|
||||
) -> dict[int, dict[str, Any]]:
|
||||
"""
|
||||
将冻结订单原始行索引映射为本次 Excel 连续行索引。
|
||||
|
||||
核心逻辑:原始首行索引 ``0`` 是有效业务值,不能以 ``or`` 回退为缺失值;
|
||||
仅传递该行已审计的短缺放行字段,其他行不受影响。
|
||||
|
||||
Args:
|
||||
line_values: 已按本次可导出集合筛选的订单行,含 ``__order_line_index``。
|
||||
release_overrides_by_source_line: 原始冻结订单行索引 → 放行补录字段。
|
||||
|
||||
Returns:
|
||||
Excel 连续行索引 → 放行补录字段。
|
||||
"""
|
||||
overrides: dict[int, dict[str, Any]] = {}
|
||||
for export_index, row in enumerate(line_values):
|
||||
source_index = row.get('__order_line_index')
|
||||
if isinstance(source_index, bool):
|
||||
continue
|
||||
try:
|
||||
normalized_source_index = int(source_index)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if normalized_source_index in release_overrides_by_source_line:
|
||||
overrides[export_index] = release_overrides_by_source_line[normalized_source_index]
|
||||
return overrides
|
||||
|
||||
|
||||
def _header_inventory_values(
|
||||
matched_lines: list[dict[str, Any]], required_fields: set[str],
|
||||
) -> dict[str, Any]:
|
||||
@@ -373,8 +451,8 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
if not task_is_active(task):
|
||||
raise ValueError('已作废或归档的任务不能生成发货 Excel')
|
||||
assert_task_not_supersession_blocked(task)
|
||||
# [T6 E2 硬门禁] 生成 Excel 前强制断言所有当前行匹配结果均为 matched;
|
||||
# 即使单源任务有明确 inventory_source_code,行级短缺/冲突仍须先处理,避免导出不完整数据。
|
||||
# [T6 E2 硬门禁] 生成 Excel 前复用库存满足性判定:每行须库存充足,
|
||||
# 或为带原因的正式短缺放行;未匹配/冲突绝不能用放行绕过。
|
||||
if task.id is not None:
|
||||
pending_rows = db.session.query(
|
||||
ShippingNoticeLineInventoryMatch.line_key,
|
||||
@@ -385,14 +463,13 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
).filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == task.id,
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.match_result != 'matched',
|
||||
).limit(20).all()
|
||||
pending_count = db.session.query(func.count(ShippingNoticeLineInventoryMatch.id)).filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == task.id,
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.match_result != 'matched',
|
||||
).scalar() or 0
|
||||
if pending_count > 0:
|
||||
# 行级库存事实是当前正式放行 Gate 的真相。历史导出任务可能只有
|
||||
# Reservation 核验轮次;这类任务继续由下方 Reservation 选择保护,不能因
|
||||
# 缺少新表事实被误判为“未匹配”。
|
||||
has_line_match_facts = bool(pending_rows)
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed
|
||||
if has_line_match_facts and not match_completed(task):
|
||||
details = [
|
||||
{
|
||||
'line_key': r[0],
|
||||
@@ -404,12 +481,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
for r in pending_rows
|
||||
]
|
||||
raise AppError(
|
||||
error_code='excel_not_ready',
|
||||
status_code=409,
|
||||
blocking_reason_code='inventory_match_incomplete',
|
||||
message=f'存在 {pending_count} 行库存未完全匹配,禁止生成发货 Excel(请先处理短缺或冲突)。',
|
||||
code='SHIPPING.EXCEL_NOT_READY',
|
||||
message='存在未满足或未放行的库存行,禁止生成发货 Excel(请先处理短缺或冲突)。',
|
||||
http_status=409,
|
||||
details={
|
||||
'pending_count': int(pending_count),
|
||||
'blocking_reason_code': 'inventory_match_incomplete',
|
||||
'pending_count': len(pending_rows),
|
||||
'pending_rows_preview': details,
|
||||
'resume_suggestion': '调用 match_inventory 重匹配或人工逐行确认短缺/冲突后再导出。',
|
||||
},
|
||||
@@ -429,15 +506,20 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code_candidate, enabled=True).first() if source_code_candidate else None
|
||||
if source is None:
|
||||
raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
|
||||
# Fixed Sources receive this value from configuration; dynamic Sources receive it
|
||||
# only after Reservation ID + Part Number resolves a unique inventory Warehouse.
|
||||
if not str(task.inventory_warehouse_id or '').strip():
|
||||
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
|
||||
template = source.excel_template
|
||||
if template is None or template.status != 'published':
|
||||
raise ValueError('库存源未绑定已发布的发货 Excel 模板')
|
||||
if source.parsing_profile is None or source.parsing_profile.status != 'published':
|
||||
raise ValueError('库存源未绑定已发布的库存解析模板')
|
||||
definition = template.definition_json or {}
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
if not mappings:
|
||||
raise ValueError('发货 Excel 模板没有已发布的字段映射')
|
||||
# Fixed Sources receive task Warehouse ID from configuration; dynamic Sources
|
||||
# resolve it only after Reservation ID + Part Number matches. This requirement
|
||||
# applies only when the published template actually consumes that system fact.
|
||||
if _template_requires_system_warehouse_id(mappings) and not str(task.inventory_warehouse_id or '').strip():
|
||||
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
|
||||
active_artifact = ShippingExportArtifact.query.filter(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
|
||||
@@ -454,30 +536,76 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
current_available_snapshot_line_ids,
|
||||
reserve_available_for_artifact,
|
||||
)
|
||||
verification, available_line_ids = current_available_snapshot_line_ids(task)
|
||||
# [STEP 1] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
|
||||
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
|
||||
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
|
||||
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
|
||||
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
|
||||
# [STEP 1] 短缺放行的人工字段仅从该行的活动决定审计快照读取,
|
||||
# 只能补模板行级库存字段,不能污染快照或任务级库存输入。
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
|
||||
released_source_line_indexes: set[int] = set()
|
||||
if task.id is not None:
|
||||
release_rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
for decision in release_rows:
|
||||
values = dict(decision.snapshot_json or {}).get('release_field_values')
|
||||
if isinstance(values, dict) and decision.line_index is not None:
|
||||
source_line_index = int(decision.line_index)
|
||||
released_source_line_indexes.add(source_line_index)
|
||||
release_overrides_by_source_line[source_line_index] = {
|
||||
str(key): value for key, value in values.items()
|
||||
}
|
||||
released_snapshot_line_ids = {
|
||||
int(line.id)
|
||||
for source_index, line in enumerate(snapshot.lines)
|
||||
if source_index in release_overrides_by_source_line
|
||||
}
|
||||
verification, available_line_ids = current_available_snapshot_line_ids(
|
||||
task,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
)
|
||||
# [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
|
||||
line_values = []
|
||||
for line, values in zip(snapshot.lines, all_line_values, strict=True):
|
||||
for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)):
|
||||
if line.id not in available_line_ids:
|
||||
continue
|
||||
row = dict(values)
|
||||
row['__order_line_index'] = source_index
|
||||
line_values.append(row)
|
||||
for index, row in enumerate(line_values, start=1):
|
||||
row['__export_sequence'] = index
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
|
||||
|
||||
# [STEP 2] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
|
||||
# [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
|
||||
inventory_lines = resolve_inventory_lines_for_execution(task)
|
||||
definition = template.definition_json or {}
|
||||
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
|
||||
if not mappings:
|
||||
raise ValueError('发货 Excel 模板没有已发布的字段映射')
|
||||
profile_definition = source.parsing_profile.definition_json if isinstance(source.parsing_profile.definition_json, dict) else {}
|
||||
match_keys = profile_definition.get('match_keys') if isinstance(profile_definition.get('match_keys'), list) else []
|
||||
line_inventory_fields = _inventory_fields_by_mode(mappings, 'line')
|
||||
header_inventory_fields = _inventory_fields_by_mode(mappings, 'header')
|
||||
release_overrides_by_line = _release_overrides_for_export_lines(
|
||||
line_values=line_values,
|
||||
release_overrides_by_source_line=release_overrides_by_source_line,
|
||||
)
|
||||
released_export_line_indexes = {
|
||||
export_index
|
||||
for export_index, row in enumerate(line_values)
|
||||
if isinstance(row.get('__order_line_index'), int)
|
||||
and not isinstance(row.get('__order_line_index'), bool)
|
||||
and int(row['__order_line_index']) in released_source_line_indexes
|
||||
}
|
||||
matched_inventory_lines = _match_inventory_lines(
|
||||
line_values, inventory_lines, match_keys, line_inventory_fields | header_inventory_fields,
|
||||
line_values,
|
||||
inventory_lines,
|
||||
match_keys,
|
||||
line_inventory_fields | header_inventory_fields,
|
||||
release_overrides_by_line=release_overrides_by_line,
|
||||
released_export_line_indexes=released_export_line_indexes,
|
||||
) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values]
|
||||
header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields)
|
||||
|
||||
@@ -540,7 +668,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
)
|
||||
db.session.add(artifact)
|
||||
db.session.flush()
|
||||
reserve_available_for_artifact(task, artifact=artifact, verification=verification)
|
||||
reserve_available_for_artifact(
|
||||
task,
|
||||
artifact=artifact,
|
||||
verification=verification,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
)
|
||||
return str(path), filename, artifact
|
||||
except Exception:
|
||||
if path.is_file():
|
||||
|
||||
@@ -146,6 +146,22 @@ def _heuristic_extract(
|
||||
warnings,
|
||||
)
|
||||
|
||||
# Schema 已明确时,表格没有通过冻结表头契约就不能再退回固定正则猜字段。
|
||||
if schema_definition:
|
||||
warnings.append("schema_table_no_lines")
|
||||
return (
|
||||
{
|
||||
"customer_name": customer_name,
|
||||
"customer_code": "",
|
||||
"ship_to": "",
|
||||
"required_date": "",
|
||||
"lines": [],
|
||||
"confidence": 0.0,
|
||||
},
|
||||
0.0,
|
||||
warnings,
|
||||
)
|
||||
|
||||
lines = []
|
||||
for m in re.finditer(r"([A-Za-z0-9\-_]{3,})\s*[xX×*]\s*(\d+(?:\.\d+)?)", text):
|
||||
lines.append({"part_number": m.group(1), "qty": float(m.group(2))})
|
||||
|
||||
@@ -21,6 +21,7 @@ from __future__ import annotations
|
||||
from pathlib import Path
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
@@ -43,6 +44,14 @@ from app.services.shipping_notice.query_service import (
|
||||
)
|
||||
from app.services.shipping_notice.i18n import resolve_lang, t
|
||||
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
|
||||
|
||||
|
||||
def _line_shortage_qty(value: Any) -> Decimal:
|
||||
"""将行短缺数量安全归一;非法值不得被误判为已放行。"""
|
||||
try:
|
||||
return Decimal(str(value or '0'))
|
||||
except (InvalidOperation, ValueError):
|
||||
return Decimal('0')
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
from app.services.shipping_notice.task_field_gate import field_conflict_gate_response
|
||||
from app.services.shipping_notice.upload_attempt_service import (
|
||||
@@ -623,16 +632,35 @@ def match_completed(task: ShippingNotice) -> bool:
|
||||
|
||||
核心逻辑:禁止 partial / 任意一行短缺、冲突、未命中进入自动制单或 Excel 门禁。
|
||||
"""
|
||||
if str(task.match_status or '').strip() != 'fulfillable':
|
||||
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
if task.id is None:
|
||||
return False
|
||||
lines = task.line_results_json
|
||||
if not isinstance(lines, list) or not lines:
|
||||
rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
|
||||
if not rows:
|
||||
return False
|
||||
return all(
|
||||
isinstance(item, dict)
|
||||
and str(item.get('line_status') or item.get('disposition') or '').strip() == 'ok'
|
||||
for item in lines
|
||||
)
|
||||
released_keys = {
|
||||
str(row.line_key)
|
||||
for row in (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
}
|
||||
for row in rows:
|
||||
result = str(row.match_result or '').strip()
|
||||
shortage = _line_shortage_qty(getattr(row, 'shortage_qty', None))
|
||||
if result == 'matched' and shortage <= 0:
|
||||
continue
|
||||
if str(row.line_key) in released_keys and shortage > 0:
|
||||
continue
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _match_step_progress_fields(
|
||||
@@ -760,7 +788,6 @@ def try_auto_chain_after_match(
|
||||
or "Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。"
|
||||
),
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
@@ -2035,7 +2062,6 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message=t("workflow.fulfillment.manual_done_message", lang=lang).format(task_no=task.task_no),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
human_options=[] if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
)
|
||||
|
||||
|
||||
@@ -2195,7 +2221,6 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
message=t("workflow.fulfillment.rpa_uploaded_done", lang=lang),
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
human_options=[] if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
|
||||
)
|
||||
|
||||
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
|
||||
@@ -2271,7 +2296,6 @@ def run_auto_progress_fulfillment_steps(
|
||||
task=task,
|
||||
message="Excel 已生成,请下载后在货代平台上传,并在本系统登记凭据。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint,
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["upload_to_freight"],
|
||||
|
||||
@@ -13,6 +13,18 @@ from __future__ import annotations
|
||||
from typing import Any
|
||||
|
||||
|
||||
def _runtime_value_source(source: Any) -> str:
|
||||
"""将 layout 内部来源收敛为运行时 observation 的稳定值源枚举。"""
|
||||
normalized = str(source or '').strip().lower()
|
||||
if normalized in {'acroform_widget', 'widget', 'widget_template'}:
|
||||
return 'acroform_widget'
|
||||
if normalized in {'ocr', 'ocr_glyph', 'ocr_coordinate'}:
|
||||
return 'ocr'
|
||||
if normalized.startswith('native') or normalized in {'pdf_coordinate', 'native_glyph'}:
|
||||
return 'native_pdf'
|
||||
return 'unknown'
|
||||
|
||||
|
||||
def build_field_observation(
|
||||
*,
|
||||
field: dict[str, Any],
|
||||
@@ -79,6 +91,7 @@ def build_field_observation(
|
||||
layout_evidence[key] = field.get(key)
|
||||
return {
|
||||
'value': value,
|
||||
'value_source': _runtime_value_source(field.get('source')),
|
||||
'document_id': int(document_id),
|
||||
'quote': quote,
|
||||
'confidence': 1.0,
|
||||
|
||||
@@ -551,7 +551,7 @@ def sync_intake_after_parse_job_recovery(job: Any) -> None:
|
||||
if job_status == 'queued':
|
||||
if intake_status not in {'parsing', 'parse_failed'}:
|
||||
return
|
||||
# Handler 可能已先提交 parse_failed;Job 自动重试时恢复为 queued 同一语义
|
||||
# Handler 可能已先提交 parse_failed;失败即停止,后续只能由用户明确重新识别。
|
||||
locked.parse_status = 'queued'
|
||||
locked.parse_lease = None
|
||||
locked.error_code = None
|
||||
|
||||
@@ -284,8 +284,8 @@ def build_inventory_candidate_blocking_reason(
|
||||
}
|
||||
|
||||
|
||||
def build_inventory_candidate_primary_action(code: str = 'open_inventory_source_review') -> dict[str, Any]:
|
||||
"""构造统一主动作 DTO。"""
|
||||
def build_inventory_candidate_primary_action(code: str = 'retry_with_latest_rules') -> dict[str, Any]:
|
||||
"""构造库存源规则自动重算动作 DTO,不提供人工选源入口。"""
|
||||
return {
|
||||
'code': code,
|
||||
'i18n_key': f'workspace.shippingNotice.processGate.actionCodes.{code}',
|
||||
|
||||
@@ -91,6 +91,22 @@ def inventory_loaded_response(
|
||||
for linked_task in linked_tasks:
|
||||
if linked_task.id != task.id:
|
||||
apply_task_transition(linked_task, TaskTransition.INVENTORY_READY)
|
||||
# [STEP] 库存回调已改变 Notice 履约事实;同步所有受影响 OT,令统一 Projection
|
||||
# 的 progress_version 与库存文件/库存匹配 Gate 同事务前进。
|
||||
from app.services.shipping_notice.order_task_stage_machine import (
|
||||
sync_order_task_stage_for_notice,
|
||||
)
|
||||
|
||||
affected_tasks: list[ShippingNotice] = []
|
||||
affected_task_ids: set[int] = set()
|
||||
for affected_task in [task, *linked_tasks]:
|
||||
affected_task_id = int(affected_task.id)
|
||||
if affected_task_id in affected_task_ids:
|
||||
continue
|
||||
affected_task_ids.add(affected_task_id)
|
||||
affected_tasks.append(affected_task)
|
||||
for affected_task in affected_tasks:
|
||||
sync_order_task_stage_for_notice(affected_task)
|
||||
log_task_event(
|
||||
task,
|
||||
event_type,
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_rpa_workflow.py
|
||||
|
||||
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)与库存源人工确认。
|
||||
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。
|
||||
依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、
|
||||
inventory_mapping_workflow、query_service、动态订单字段、tool_common、state_machine、tool_response。
|
||||
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;
|
||||
confirm_inventory_source 写入操作人与前后生命周期快照(TaskEvent 双写统一审计);
|
||||
Reservation 门禁从当前 Extraction 的动态 FieldValue 读取。
|
||||
库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,18 +21,13 @@ from typing import Any
|
||||
from app import db
|
||||
from app.core.errors import AppError, ServiceUnavailableError
|
||||
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
CP_PARSE_OK,
|
||||
CP_UPLOAD_REQ,
|
||||
PH_INVENTORY_SOURCE_UNRESOLVED,
|
||||
PH_RPA_PENDING,
|
||||
)
|
||||
from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
find_latest_ready_snapshot,
|
||||
get_or_create_rpa_inventory_snapshot,
|
||||
link_snapshot_to_task,
|
||||
link_snapshot_to_task_for_preparation,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_upload import (
|
||||
delete_staged_task_inventory_file,
|
||||
@@ -51,7 +45,6 @@ from app.services.shipping_notice.inventory_rpa_callback_cleanup import (
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
assert_inventory_source_gate,
|
||||
confirm_task_inventory_source,
|
||||
inventory_identities_match,
|
||||
is_inventory_source_stable,
|
||||
)
|
||||
@@ -74,7 +67,6 @@ from app.services.shipping_notice.rpa import (
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import RPA_WORKER_OFFLINE_MESSAGE
|
||||
from app.services.shipping_notice.rpa_attempts import (
|
||||
inventory_rpa_attempts,
|
||||
max_rpa_inventory_attempts,
|
||||
)
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
@@ -102,14 +94,12 @@ def _inventory_rpa_attempt_label(*, attempt_no: int, max_attempts: int, manual_r
|
||||
生成库存 RPA 尝试状态文案。
|
||||
【AI 触发时机】:需要向前台说明当前 RPA 库存获取已触发或仍在等待时调用。
|
||||
|
||||
核心逻辑:前台不展示“第 N 次”这类内部排障指标,避免用户误解自动重试策略;
|
||||
真正的 attempt 仍保留在 ShippingTaskEvent.detail 里供运维排查。
|
||||
核心逻辑:前台不展示尝试计数或自动重试策略;一次 RPA 执行失败即停止,
|
||||
后续只能由用户点击明确的重新获取库存动作触发。
|
||||
"""
|
||||
if manual_retry_round:
|
||||
return "已手动重新触发库存获取"
|
||||
if max_attempts <= 1:
|
||||
return "当前配置为单次自动尝试"
|
||||
return "库存获取自动尝试中"
|
||||
return "已触发库存获取"
|
||||
|
||||
|
||||
def _inventory_rpa_running_prefix(*, attempt_no: int, max_attempts: int) -> str:
|
||||
@@ -124,13 +114,6 @@ def _inventory_rpa_triggered_prefix(*, attempt_no: int, max_attempts: int, manua
|
||||
return "已触发库存获取。"
|
||||
|
||||
|
||||
def _inventory_rpa_exhausted_message(attempts: int) -> str:
|
||||
"""生成库存 RPA 已耗尽时的用户文案;单次模式明确提示“已尝试一次”。"""
|
||||
if max_rpa_inventory_attempts() <= 1:
|
||||
return "已尝试 1 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。"
|
||||
return f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。"
|
||||
|
||||
|
||||
def _try_reuse_inventory_snapshot(
|
||||
task: ShippingNotice,
|
||||
rpa_source: dict[str, Any],
|
||||
@@ -255,7 +238,7 @@ def _inventory_rpa_triggered_message(*, attempt_no: int, max_attempts: int, manu
|
||||
max_attempts=max_attempts,
|
||||
manual_retry_round=manual_retry_round,
|
||||
)
|
||||
return f"{prefix}若长时间无结果,可手动重试,或上传库存 Excel。"
|
||||
return f"{prefix}若本次失败,请选择重新获取库存或上传库存 Excel。"
|
||||
|
||||
|
||||
def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int | None, int | None]:
|
||||
@@ -299,7 +282,8 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
|
||||
对已超时的库存 RPA 等待态做一次幂等复查。
|
||||
【AI 触发时机】:工作台查询发现任务仍卡在 RPA 等待且已超过超时时间时调用;常规链路仍由 worker 调度。
|
||||
|
||||
核心逻辑:未超时立即返回 None;已超时则复用 ensure_inventory_via_rpa,让既有状态机负责失败事件、自动重试和耗尽转人工。
|
||||
核心逻辑:未超时立即返回 None;已超时只记录失败并停在 Gate,
|
||||
不会自动再次触发 RPA。
|
||||
Args:
|
||||
task: 当前发货通知任务。
|
||||
source: 复查来源,用于审计排障。
|
||||
@@ -318,7 +302,16 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
|
||||
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
|
||||
)
|
||||
db.session.flush()
|
||||
return ensure_inventory_via_rpa(task, mode="auto")
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
task.error_message = "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel"
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=task.error_message,
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
)
|
||||
|
||||
|
||||
def _expected_snapshot_identity_from_task(task: ShippingNotice) -> tuple[str, str]:
|
||||
@@ -979,221 +972,29 @@ def _batch_snapshot_verify_warehouse_id(
|
||||
def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[str, Any]) -> str | None:
|
||||
"""
|
||||
校验批量回调 Worker 返回的 Source/Warehouse 身份与启用配置一致。
|
||||
核心逻辑:定时/无任务成功项必须显式携带 source/warehouse;动态仓接受库存文件返回的 Warehouse。
|
||||
核心逻辑:固定仓成功项必须显式携带 source/warehouse;动态仓文件在库存行
|
||||
解析后才按订单键得出 Warehouse,因此回调层允许 warehouse_id 为空。
|
||||
"""
|
||||
callback_source = str(item.get("source_code") or "").strip().upper()
|
||||
callback_wh = str(item.get("warehouse_id") or "").strip().upper()
|
||||
if not callback_source:
|
||||
return "source_code_missing"
|
||||
if not callback_wh:
|
||||
return "warehouse_id_missing"
|
||||
|
||||
cfg_source = str(source.get("source_code") or "").strip().upper()
|
||||
cfg_wh = str(source.get("fixed_warehouse_id") or source.get("warehouse_id") or "").strip().upper()
|
||||
if callback_source != cfg_source:
|
||||
return "source_code_mismatch"
|
||||
if str(source.get('warehouse_resolution_mode') or '') == 'inventory_match':
|
||||
if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'inventory_match':
|
||||
return None
|
||||
|
||||
if not callback_wh:
|
||||
return "warehouse_id_missing"
|
||||
|
||||
if callback_wh != cfg_wh:
|
||||
return "warehouse_id_mismatch"
|
||||
return None
|
||||
|
||||
|
||||
def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
确认当前任务的库存来源;库存源门禁或匹配多源阻断均可调用。
|
||||
|
||||
【AI 触发时机】:用户在库存源检查点或匹配多源冲突待办中选择 source_code 后调用。
|
||||
核心逻辑:原门禁路径确认后进入库存准备;shortage + 多源/多文件冲突路径写入
|
||||
forced_match_source_code 并立即重匹配,消除多源 Excel 阻断。
|
||||
"""
|
||||
from app.services.shipping_notice.constants import PH_SHORTAGE, RS_SHORTAGE_REVIEW
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
from app.services.shipping_notice.stp_line_inventory_match import (
|
||||
multi_source_recovery_source_codes,
|
||||
needs_multi_source_manual_recovery,
|
||||
)
|
||||
|
||||
task = resolve_task_from_payload(payload)
|
||||
if not task:
|
||||
return tool_response(status="failed", message="未找到任务编号")
|
||||
source_code = str(payload.get("source_code") or "").strip().upper()
|
||||
if not source_code:
|
||||
return tool_response(status="failed", task=task, message="请提供库存源编码 source_code")
|
||||
|
||||
from app.services.shipping_notice.tool_common import task_lifecycle_audit_snapshot
|
||||
|
||||
pending = str(task.pending_human_reason or "").strip()
|
||||
on_source_gate = pending == PH_INVENTORY_SOURCE_UNRESOLVED
|
||||
on_multi_source_block = (
|
||||
(task.review_status == RS_SHORTAGE_REVIEW or pending == PH_SHORTAGE)
|
||||
and needs_multi_source_manual_recovery(task)
|
||||
)
|
||||
if not on_source_gate and not on_multi_source_block:
|
||||
return tool_response(status="failed", task=task, message="当前任务不在库存源确认节点")
|
||||
|
||||
before_snapshot = task_lifecycle_audit_snapshot(task)
|
||||
|
||||
if on_multi_source_block:
|
||||
allowed = set(multi_source_recovery_source_codes(task))
|
||||
if source_code not in allowed:
|
||||
return tool_response(
|
||||
status="failed",
|
||||
task=task,
|
||||
message=f"库存源 {source_code} 不在可指定候选内:{', '.join(sorted(allowed)) or '-'}",
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
source = get_database_inventory_source(source_code)
|
||||
if source is None:
|
||||
return tool_response(status="failed", task=task, message=f"库存源配置不存在:{source_code}")
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload['forced_match_source_code'] = source_code
|
||||
step_payload['multi_source_excel_block'] = False
|
||||
step_payload['resolved_ok_source_codes'] = [source_code]
|
||||
step_payload['inventory_source_resolution'] = {
|
||||
'status': 'resolved',
|
||||
'candidates': [{'source_code': source_code, 'display_name': source.get('display_name') or source_code}],
|
||||
'selected_source_code': source_code,
|
||||
'reason': 'manual_multi_source_resolve',
|
||||
}
|
||||
task.step_payload_json = step_payload
|
||||
task.inventory_source_code = source_code
|
||||
task.inventory_connector_type = str(source.get('connector_type') or '') or None
|
||||
if str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
|
||||
task.inventory_warehouse_id = str(source.get('fixed_warehouse_id') or '').upper() or None
|
||||
# 与门禁确认路径对齐:resolved 属 STABLE;保留既有 fingerprint/config_version。
|
||||
task.inventory_source_status = 'resolved'
|
||||
task.inventory_source_method = 'manual_multi_source_resolve'
|
||||
task.inventory_source_confirmed_by = payload.get('_trusted_user_id')
|
||||
task.inventory_source_confirmed_at = datetime.now(timezone.utc)
|
||||
task.pending_human_reason = None
|
||||
task.review_status = None
|
||||
task.error_message = None
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_confirmed",
|
||||
{
|
||||
"source_code": source_code,
|
||||
"connector_type": task.inventory_connector_type,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"confirmed_by": payload.get("_trusted_user_id") or "integration_tool",
|
||||
"reason_code": "manual_multi_source_resolve",
|
||||
"resolved_ok_source_codes": [source_code],
|
||||
},
|
||||
actor_id=payload.get("_trusted_user_id") or payload.get("operator_id") or payload.get("actor_id"),
|
||||
source='workspace_api' if (
|
||||
payload.get("_trusted_user_id") or payload.get("operator_id") or payload.get("actor_id")
|
||||
) else 'system',
|
||||
before=before_snapshot,
|
||||
after=task_lifecycle_audit_snapshot(task),
|
||||
)
|
||||
apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
|
||||
task.current_step = "step5_match_inventory"
|
||||
db.session.flush()
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_inventory
|
||||
trusted_uid = payload.get("_trusted_user_id")
|
||||
# [T6 选择性重匹] 默认只重匹 match_result≠matched 行;force_full_rematch=true 才全量重匹。
|
||||
# 实现:非全量模式先把 line_matches 中 is_current=true 且 match_result≠matched 的条目
|
||||
# 置为 is_current=false,待 match_inventory 补齐;已 matched 的保留不覆盖,避免稳定证据哈希失效。
|
||||
force_full = False
|
||||
if isinstance(payload, dict):
|
||||
force_flag = payload.get('force_full_rematch') or payload.get('force_full') or payload.get('full_rematch')
|
||||
force_full = bool(force_flag and str(force_flag).lower() not in {'0', 'false', 'no', 'none', ''})
|
||||
if not force_full and task.id is not None:
|
||||
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
|
||||
cleared = (
|
||||
db.session.query(ShippingNoticeLineInventoryMatch)
|
||||
.filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
ShippingNoticeLineInventoryMatch.match_result != 'matched',
|
||||
)
|
||||
.update(
|
||||
{
|
||||
'is_current': False,
|
||||
'updated_at': datetime.now(timezone.utc),
|
||||
},
|
||||
synchronize_session=False,
|
||||
)
|
||||
)
|
||||
log_task_event(
|
||||
task,
|
||||
'match_inventory_selective_reset',
|
||||
{
|
||||
'cleared_pending_count': int(cleared or 0),
|
||||
'force_full_rematch': False,
|
||||
},
|
||||
actor_id=trusted_uid,
|
||||
source='workspace_api' if trusted_uid else 'system',
|
||||
)
|
||||
rematch_payload = {
|
||||
"task_id": task.task_no,
|
||||
"_trusted_user_id": trusted_uid,
|
||||
"operator_id": trusted_uid,
|
||||
"actor_id": trusted_uid,
|
||||
"event_source": "workspace_api" if trusted_uid else "system",
|
||||
"force_full_rematch": force_full,
|
||||
}
|
||||
return match_inventory(rematch_payload)
|
||||
|
||||
adjudication = confirm_task_inventory_source(
|
||||
task,
|
||||
source_code,
|
||||
user_id=payload.get("_trusted_user_id"),
|
||||
)
|
||||
if not is_inventory_source_stable(task):
|
||||
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
|
||||
task.current_step = "step2_parse_confirm"
|
||||
task.error_message = adjudication.reason or "库存源确认失败"
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message="库存源确认未通过,请重新选择或检查配置。",
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"inventory_source_candidates": adjudication.candidates,
|
||||
"inventory_source_status": adjudication.status,
|
||||
"inventory_source_reason": adjudication.reason,
|
||||
},
|
||||
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
|
||||
confirmed_by = payload.get("_trusted_user_id") or payload.get("operator_id") or payload.get("actor_id")
|
||||
apply_task_transition(task, TaskTransition.PARSED)
|
||||
task.pending_human_reason = None
|
||||
task.review_status = None
|
||||
task.error_message = None
|
||||
task.current_step = "step3_inventory_prepare"
|
||||
# [STEP] 状态变更后再写事件,保证 after 快照含确认后的领域事实 / phase。
|
||||
log_task_event(
|
||||
task,
|
||||
"inventory_source_confirmed",
|
||||
{
|
||||
"source_code": task.inventory_source_code,
|
||||
"connector_type": task.inventory_connector_type,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"confirmed_by": confirmed_by or "integration_tool",
|
||||
"reason_code": "inventory_source_confirmed",
|
||||
},
|
||||
actor_id=confirmed_by,
|
||||
source='workspace_api' if confirmed_by else 'system',
|
||||
before=before_snapshot,
|
||||
after=task_lifecycle_audit_snapshot(task),
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
return tool_response(
|
||||
status="ok",
|
||||
task=task,
|
||||
message="库存源已确认;将使用该来源已导出的有效库存文件。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_PARSE_OK,
|
||||
)
|
||||
|
||||
|
||||
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
|
||||
@@ -1256,20 +1057,33 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
|
||||
rpa_source = task_rpa_inventory_source(task) or {}
|
||||
|
||||
# retry_rpa 使用逐源 Attempt 编排,确保 Trigger 携带 source_run_no/lease_token,
|
||||
# Worker 回调后可以精确绑定到本次 Attempt;自动模式继续使用下方旧兼容路径。
|
||||
if manual_retry_round:
|
||||
# 首次自动与人工重试都必须创建逐源 Attempt。只有该路径会冻结
|
||||
# source_run_no/lease_token/candidate_set/execution/gate 身份,Worker 回调才可精确收口。
|
||||
# 下方保留的旧单票逻辑仅用于历史代码阅读,所有受支持 mode 均在这里返回。
|
||||
if mode in {'auto', 'retry_rpa'}:
|
||||
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
|
||||
|
||||
prepared = ensure_all_required_sources_prepared(task, mode='retry_rpa')
|
||||
prepared = ensure_all_required_sources_prepared(task, mode=mode)
|
||||
db.session.flush()
|
||||
if prepared.pending_source_codes:
|
||||
apply_task_transition(task, TaskTransition.RPA_PENDING)
|
||||
task.error_message = None
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
step_title='获取库存',
|
||||
status='running',
|
||||
message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。',
|
||||
progress_percent=60,
|
||||
current=len(prepared.prepared_source_codes),
|
||||
total=len(prepared.prepared_source_codes) + len(prepared.pending_source_codes),
|
||||
detail='等待库存 RPA 回调',
|
||||
extra={'manual_retry_round': manual_retry_round, 'source_attempts': prepared.source_attempts},
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status='running', task_id=task.task_no,
|
||||
message='已重新触发库存获取,等待各库存源回调。',
|
||||
message='已重新触发库存获取,等待各库存源回调。' if manual_retry_round else '已触发库存获取,等待各库存源回调。',
|
||||
data={**serialize_task_for_tool(task), 'rpa': {
|
||||
'pending_source_codes': prepared.pending_source_codes,
|
||||
'source_attempts': prepared.source_attempts,
|
||||
@@ -1277,6 +1091,19 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
)
|
||||
if prepared.all_prepared:
|
||||
return tool_response(status='completed', task=task, message='库存快照已准备完成。')
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message='库存 RPA 未能为全部库存源生成结果。',
|
||||
progress_percent=100,
|
||||
current=len(prepared.prepared_source_codes),
|
||||
total=len(prepared.prepared_source_codes) + len(prepared.failed_source_codes),
|
||||
detail='请重新获取库存或上传库存 Excel。',
|
||||
extra={'source_attempts': prepared.source_attempts},
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status='needs_human', task=task,
|
||||
message='库存 RPA 未能为全部库存源生成结果。',
|
||||
@@ -1302,24 +1129,20 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
if last_trigger and isinstance(last_trigger.created_at, datetime):
|
||||
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
|
||||
if elapsed < timeout_seconds:
|
||||
max_attempts = max_rpa_inventory_attempts()
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
remaining = max(timeout_seconds - elapsed, 1)
|
||||
return tool_response(
|
||||
status="running",
|
||||
task_id=task.task_no,
|
||||
message=_inventory_rpa_running_message(
|
||||
attempt_no=max(attempts, 1),
|
||||
max_attempts=max_attempts,
|
||||
max_attempts=max(attempts, 1),
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"rpa": {
|
||||
"attempts": max(attempts, 1),
|
||||
"max_attempts": max_attempts,
|
||||
"elapsed_seconds": elapsed,
|
||||
"timeout_seconds": timeout_seconds,
|
||||
"retry_after_seconds": remaining,
|
||||
},
|
||||
},
|
||||
)
|
||||
@@ -1336,21 +1159,20 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
},
|
||||
)
|
||||
db.session.flush( )
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
task.error_message = "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel"
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=task.error_message,
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=CP_UPLOAD_REQ,
|
||||
)
|
||||
|
||||
# [STEP 2] 处理重试上限;禁止消费全局 drop 目录未校验文件,必须等待 RPA 回调或复用正式快照。
|
||||
# [STEP 2] 仅本次用户或系统明确触发可创建一次 RPA 尝试。
|
||||
# 禁止消费全局 drop 目录未校验文件,必须等待 RPA 回调或复用正式快照。
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
max_attempts = max_rpa_inventory_attempts()
|
||||
if attempts >= max_attempts and not task.inventory_lines_json and not manual_retry_round:
|
||||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||||
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
|
||||
log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempts})
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=_inventory_rpa_exhausted_message(attempts),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
# [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。
|
||||
# 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。
|
||||
@@ -1378,7 +1200,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
)
|
||||
progress_detail = _inventory_rpa_attempt_label(
|
||||
attempt_no=attempt_no,
|
||||
max_attempts=max_attempts,
|
||||
max_attempts=attempt_no,
|
||||
manual_retry_round=manual_retry_round,
|
||||
)
|
||||
set_task_step_progress(
|
||||
@@ -1389,7 +1211,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
message=progress_message,
|
||||
progress_percent=60,
|
||||
current=attempt_no,
|
||||
total=max(attempt_no, max_attempts),
|
||||
total=attempt_no,
|
||||
detail=progress_detail,
|
||||
extra={"manual_retry_round": manual_retry_round} if manual_retry_round else None,
|
||||
)
|
||||
@@ -1410,14 +1232,13 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
|
||||
task_id=task.task_no,
|
||||
message=_inventory_rpa_triggered_message(
|
||||
attempt_no=attempt_no,
|
||||
max_attempts=max_attempts,
|
||||
max_attempts=attempt_no,
|
||||
manual_retry_round=manual_retry_round,
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"rpa": {
|
||||
"attempts": attempt_no,
|
||||
"max_attempts": max_attempts,
|
||||
"timeout_seconds": timeout_seconds,
|
||||
},
|
||||
},
|
||||
@@ -1629,7 +1450,7 @@ def _handle_rpa_inventory_failed(
|
||||
*,
|
||||
commit: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""处理 failed 回调:记录稳定失败码、累计尝试并在耗尽后转人工上传兜底。"""
|
||||
"""处理 failed 回调:记录失败事实并保留用户可重试/上传的恢复入口。"""
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500]
|
||||
log_task_event(task, "inventory_rpa_failed", {
|
||||
@@ -1637,24 +1458,17 @@ def _handle_rpa_inventory_failed(
|
||||
"error_code": str(payload.get("error_code") or "rpa_export_failed"),
|
||||
"rpa_runtime": runtime,
|
||||
})
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key='step3_inventory_prepare',
|
||||
step_title='获取库存',
|
||||
status='needs_human',
|
||||
message=task.error_message,
|
||||
progress_percent=100,
|
||||
detail='请重新获取库存或上传库存 Excel。',
|
||||
extra={'error_code': str(payload.get('error_code') or 'rpa_export_failed')},
|
||||
)
|
||||
db.session.flush()
|
||||
attempts = inventory_rpa_attempts(task)
|
||||
if attempts >= max_rpa_inventory_attempts():
|
||||
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
|
||||
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
|
||||
log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempts})
|
||||
_mark_inventory_rpa_run_no_consumed(task, _resolve_effective_callback_run_no(task, payload))
|
||||
if commit:
|
||||
db.session.commit()
|
||||
else:
|
||||
db.session.flush()
|
||||
return tool_response(
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=_inventory_rpa_exhausted_message(attempts),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
|
||||
_mark_inventory_rpa_run_no_consumed(task, _resolve_effective_callback_run_no(task, payload))
|
||||
if commit:
|
||||
db.session.commit()
|
||||
@@ -1917,7 +1731,7 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
item_savepoint = db.session.begin_nested()
|
||||
response: dict[str, Any] | None = None
|
||||
try:
|
||||
link = link_snapshot_to_task(
|
||||
link = link_snapshot_to_task_for_preparation(
|
||||
task,
|
||||
inv_file,
|
||||
reason="rpa_callback",
|
||||
@@ -2424,7 +2238,13 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
'error': 'RPA callback identity does not match the active preparation attempt.',
|
||||
})
|
||||
continue
|
||||
if per_source_code not in {'validated', 'not_found'}:
|
||||
# trigger_identity_invalid 是 Worker 对已领取 trigger 的明确失败事实。
|
||||
# per_source handler 已收口 Attempt;仍须继续到下面的 Task/Gate 收口,
|
||||
# 不能像普通身份不匹配一样只记回调审计后等待 900 秒超时。
|
||||
if not (
|
||||
per_source_code == 'failed'
|
||||
and str(merged_item.get('error_code') or '').strip() == 'trigger_identity_invalid'
|
||||
) and per_source_code not in {'validated', 'not_found'}:
|
||||
failed.append({
|
||||
'source_code': source_code,
|
||||
'warehouse_id': warehouse_id,
|
||||
@@ -2465,6 +2285,23 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
"message": merged_item.get("message") or merged_item.get("error_message") or "",
|
||||
})
|
||||
else:
|
||||
# [STEP] 结构化逐源 Attempt 是库存准备轮次的正式事实。失败回调
|
||||
# 必须先收口 Attempt/SourceAttempt;否则 Task 虽已记录失败,
|
||||
# PreparationAttempt 仍会停在 waiting_external,页面会错误显示
|
||||
# “等待外部系统回执”。
|
||||
if source_run_no_item and structured_attempt:
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
|
||||
|
||||
per_source_callback_handler(
|
||||
task,
|
||||
source_code=source_code,
|
||||
run_no=source_run_no_item,
|
||||
callback_payload={
|
||||
**dict(merged_item),
|
||||
'error_code': str(merged_item.get('error_code') or 'rpa_export_failed'),
|
||||
'error_message': str(merged_item.get('error_message') or 'RPA inventory export failed'),
|
||||
},
|
||||
)
|
||||
_handle_rpa_inventory_failed(task, merged_item, runtime, commit=False)
|
||||
# 失败回调已把 Task 从 rpa_pending 还原为库存不可用;必须立即同步正式 Gate,
|
||||
# 否则 Execution 仍是 waiting_external,前端会错误停在“系统处理中”。
|
||||
@@ -2533,64 +2370,6 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
continue
|
||||
|
||||
if raw_status == "success":
|
||||
# 定时批量成功项必须显式携带 Warehouse 身份;先做身份校验,
|
||||
# 避免缺 Warehouse 被后续文件路径错误遮蔽。
|
||||
if not warehouse_id:
|
||||
# [STEP] RPA 声称导出成功但缺少仓库身份时,文件绝不能成为可匹配
|
||||
# 快照;同时必须终态化本次逐源 Attempt/准备轮次,避免前端永久显示
|
||||
# “处理中”或允许重复触发同一运行中的 Attempt。
|
||||
if task and source_run_no_item and structured_attempt:
|
||||
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
|
||||
|
||||
per_source_callback_handler(
|
||||
task,
|
||||
source_code=source_code,
|
||||
run_no=source_run_no_item,
|
||||
callback_payload={
|
||||
**dict(merged_item),
|
||||
'error_code': 'warehouse_id_missing',
|
||||
'error_message': 'RPA 回调缺少 warehouse_id,无法确认库存归属。',
|
||||
},
|
||||
)
|
||||
if task:
|
||||
runtime = _save_last_inventory_rpa_runtime(task, merged_item)
|
||||
_handle_rpa_inventory_failed(
|
||||
task,
|
||||
{
|
||||
**dict(merged_item),
|
||||
'error_code': 'warehouse_id_missing',
|
||||
'error_message': 'RPA 回调缺少 warehouse_id,无法确认库存归属。',
|
||||
},
|
||||
runtime,
|
||||
commit=False,
|
||||
)
|
||||
# 与显式 failed 回调保持相同的 Gate 收口语义:Task 已从
|
||||
# rpa_pending 转为可重试失败,正式 Execution 不能继续停在
|
||||
# waiting_external,否则右侧页面会显示过期的“处理中”。
|
||||
if task.active_process_execution_id:
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
|
||||
execution = db.session.get(
|
||||
ShippingProcessExecution,
|
||||
int(task.active_process_execution_id),
|
||||
)
|
||||
if (
|
||||
execution is not None
|
||||
and int(getattr(execution, 'task_id', 0) or 0) == int(task.id)
|
||||
and str(getattr(execution, 'status', '') or '').strip().lower() != 'superseded'
|
||||
):
|
||||
sync_fulfillment_gates_from_task(
|
||||
execution=execution,
|
||||
actor_type='system',
|
||||
)
|
||||
failed.append({
|
||||
"source_code": source_code,
|
||||
"warehouse_id": warehouse_id,
|
||||
"task_no": task_no or None,
|
||||
"error": "warehouse_id_missing",
|
||||
})
|
||||
continue
|
||||
file_path = str(merged_item.get("file_path") or "").strip()
|
||||
path = _received_batch_callback_file_path(
|
||||
file_path,
|
||||
@@ -2709,7 +2488,7 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
|
||||
batch_new_storage_paths.append(item_orphan_path)
|
||||
|
||||
if task_no and task:
|
||||
link = link_snapshot_to_task(
|
||||
link = link_snapshot_to_task_for_preparation(
|
||||
task,
|
||||
inv_file,
|
||||
reason="rpa_batch_callback",
|
||||
|
||||
@@ -402,7 +402,8 @@ def create_empty_rpa_inventory_snapshot(
|
||||
share_mode='warehouse_pool', line_count=0, inventory_lines_json=[], warehouse_id=warehouse_id,
|
||||
warehouse_code=warehouse_id, source_code=source_code or None,
|
||||
source_type=str(source.get('connector_type') or '').strip() or None,
|
||||
source_config_version=inventory_sources_runtime_version(), identity_status='not_applicable',
|
||||
# 空快照没有可验证的行级身份;使用数据库枚举中的 unknown,避免审计入库失败。
|
||||
source_config_version=inventory_sources_runtime_version(), identity_status='unknown',
|
||||
snapshot_status=_SNAPSHOT_STATUS_EMPTY, exported_at=exported_at, expires_at=snapshot_expires_at(exported_at),
|
||||
rpa_run_no=run_no, schedule_run_id=schedule_run_id,
|
||||
source_query_json={'trigger_type': trigger_type, 'export_result': 'empty'},
|
||||
@@ -454,7 +455,13 @@ def link_snapshot_to_task(
|
||||
fallback_warehouse_id=inv_file.warehouse_id,
|
||||
)
|
||||
if not resolution.warehouse_id:
|
||||
inv_file.identity_status = resolution.reason
|
||||
# identity_status 受数据库枚举约束,仅保存状态;具体动态仓解析原因
|
||||
# 属于审计信息,不能写入该字段,否则会使已导出的快照整体回滚。
|
||||
inv_file.identity_status = 'pending'
|
||||
inv_file.schema_preview_json = {
|
||||
**(inv_file.schema_preview_json or {}),
|
||||
'identity_resolution_reason': resolution.reason,
|
||||
}
|
||||
return None
|
||||
resolved_warehouse_id = resolution.warehouse_id
|
||||
|
||||
@@ -510,6 +517,55 @@ def link_snapshot_to_task(
|
||||
return link
|
||||
|
||||
|
||||
def link_snapshot_to_task_for_preparation(
|
||||
task: ShippingNotice,
|
||||
inv_file: ShippingInventoryFile,
|
||||
*,
|
||||
reason: str,
|
||||
audit_payload: dict[str, Any] | None = None,
|
||||
) -> ShippingTaskInventoryLink | None:
|
||||
"""将 RPA 已准备快照关联任务;动态仓身份待匹配时保留文件事实。
|
||||
|
||||
动态仓的 Warehouse 只能由下一阶段用订单键匹配库存行得出。若该匹配尚无结论,
|
||||
本函数保留已通过结构校验的快照并标记 pending_matching,禁止回滚导出文件;
|
||||
fixed 仓仍完全沿用正式身份校验,不得降级关联。
|
||||
"""
|
||||
link = link_snapshot_to_task(
|
||||
task,
|
||||
inv_file,
|
||||
reason=reason,
|
||||
audit_payload=audit_payload,
|
||||
)
|
||||
if link is not None:
|
||||
return link
|
||||
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
|
||||
source = get_database_inventory_source(task.inventory_source_code)
|
||||
if (
|
||||
source is None
|
||||
or str(source.get('warehouse_resolution_mode') or '').strip().lower() != 'inventory_match'
|
||||
or not _can_relink_inventory(task)
|
||||
or not is_snapshot_fresh(inv_file)
|
||||
):
|
||||
return None
|
||||
|
||||
from app.services.shipping_notice.inventory_file_store import replace_task_inventory_link
|
||||
|
||||
link = replace_task_inventory_link(task, inv_file)
|
||||
link.link_reason = f'{reason}_pending_matching'
|
||||
link.matched_source_code = inv_file.source_code
|
||||
link.identity_check_status = 'pending_matching'
|
||||
link.audit_payload_json = {
|
||||
**(audit_payload or {}),
|
||||
'source_code': inv_file.source_code,
|
||||
'inventory_file_no': inv_file.inventory_file_no,
|
||||
'identity_status': inv_file.identity_status,
|
||||
}
|
||||
task.inventory_snapshot_id = inv_file.id
|
||||
return link
|
||||
|
||||
|
||||
def serialize_inventory_snapshot_link(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""序列化任务当前 active 库存快照摘要,供工作台/Tool 展示。"""
|
||||
if task.id is None:
|
||||
|
||||
@@ -9,7 +9,6 @@ services/shipping_notice/inventory_source_gate.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import AppError
|
||||
@@ -17,7 +16,6 @@ from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
InventorySourceAdjudication,
|
||||
adjudicate_inventory_source,
|
||||
confirm_inventory_source_by_code,
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
resolve_ambiguous_source_from_ready_snapshots,
|
||||
@@ -31,14 +29,13 @@ from app.services.shipping_notice.inventory_source_repository import (
|
||||
)
|
||||
|
||||
|
||||
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "user_confirmed", "candidates_frozen"})
|
||||
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "candidates_frozen"})
|
||||
|
||||
INVENTORY_SOURCE_ERROR_CODES = {
|
||||
"unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED",
|
||||
"ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS",
|
||||
"invalid": "SHIPPING.INVENTORY_SOURCE_INVALID",
|
||||
"conflicted": "SHIPPING.INVENTORY_SOURCE_CONFLICTED",
|
||||
"confirmation_required": "SHIPPING.INVENTORY_SOURCE_CONFIRMATION_REQUIRED",
|
||||
"changed": "SHIPPING.INVENTORY_SOURCE_CHANGED",
|
||||
"identity_mismatch": "SHIPPING.INVENTORY_IDENTITY_MISMATCH",
|
||||
"gate_blocked": "SHIPPING.INVENTORY_SOURCE_GATE_BLOCKED",
|
||||
@@ -102,7 +99,7 @@ def is_inventory_source_stable(task: ShippingNotice) -> bool:
|
||||
|
||||
|
||||
def routing_fingerprint_changed(task: ShippingNotice, context: dict[str, Any]) -> bool:
|
||||
"""比较当前路由上下文与任务已存指纹,判断人工确认是否因重解析或配置变更失效。"""
|
||||
"""比较当前路由上下文与任务已存指纹,判断库存源裁决是否因事实变化失效。"""
|
||||
previous = str(task.inventory_routing_fingerprint or "").strip()
|
||||
if not previous:
|
||||
return False
|
||||
@@ -110,7 +107,7 @@ def routing_fingerprint_changed(task: ShippingNotice, context: dict[str, Any]) -
|
||||
|
||||
|
||||
def inventory_source_config_changed(task: ShippingNotice) -> bool:
|
||||
"""配置版本变化会使已确认库存源失效。"""
|
||||
"""配置版本变化会使已有库存源裁决失效。"""
|
||||
stored = str(task.inventory_source_config_version or "").strip()
|
||||
if not stored:
|
||||
return bool(str(task.inventory_source_status or "").strip())
|
||||
@@ -126,7 +123,7 @@ def apply_destination_fields(task: ShippingNotice, context: dict[str, Any]) -> N
|
||||
|
||||
|
||||
def clear_inventory_source_confirmation(task: ShippingNotice) -> None:
|
||||
"""路由指纹或配置版本变化时清除旧人工确认信息及过期 RPA 参数。"""
|
||||
"""路由指纹或配置版本变化时清除历史人工确认信息及过期 RPA 参数。"""
|
||||
task.inventory_source_confirmed_by = None
|
||||
task.inventory_source_confirmed_at = None
|
||||
if str(task.inventory_source_status or "").strip() == "user_confirmed":
|
||||
@@ -137,27 +134,9 @@ def clear_inventory_source_confirmation(task: ShippingNotice) -> None:
|
||||
task.step_payload_json = payload
|
||||
|
||||
|
||||
def _adjudication_from_stable_task(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
"""从已稳定任务字段重建裁决结果,供跳过重复裁决时使用。"""
|
||||
context = extract_routing_context(task)
|
||||
return InventorySourceAdjudication(
|
||||
status=str(task.inventory_source_status or "").strip(),
|
||||
method=str(task.inventory_source_method or "").strip() or None,
|
||||
source_code=str(task.inventory_source_code or "").strip().upper() or None,
|
||||
connector_type=str(task.inventory_connector_type or "").strip() or None,
|
||||
warehouse_id=str(task.inventory_warehouse_id or "").strip().upper() or None,
|
||||
config_version=str(task.inventory_source_config_version or "").strip() or None,
|
||||
routing_fingerprint=str(task.inventory_routing_fingerprint or "").strip()
|
||||
or compute_routing_fingerprint(context),
|
||||
destination_candidates=context.get("destination_candidates") or [],
|
||||
)
|
||||
|
||||
|
||||
def apply_inventory_source_adjudication(
|
||||
task: ShippingNotice,
|
||||
adjudication: InventorySourceAdjudication,
|
||||
*,
|
||||
confirmed_by_user_id: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将裁决结果写入任务独立字段,并同步候选/证据到 step_payload_json。
|
||||
@@ -176,9 +155,6 @@ def apply_inventory_source_adjudication(
|
||||
task.inventory_source_code = adjudication.source_code
|
||||
task.inventory_connector_type = adjudication.connector_type
|
||||
task.inventory_warehouse_id = adjudication.warehouse_id or None
|
||||
if adjudication.status == "user_confirmed" and confirmed_by_user_id:
|
||||
task.inventory_source_confirmed_by = confirmed_by_user_id
|
||||
task.inventory_source_confirmed_at = datetime.utcnow()
|
||||
elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES:
|
||||
task.inventory_source_code = None
|
||||
task.inventory_connector_type = None
|
||||
@@ -219,43 +195,14 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour
|
||||
if inventory_source_config_changed(task) or routing_fingerprint_changed(task, context):
|
||||
clear_inventory_source_confirmation(task)
|
||||
|
||||
if (
|
||||
str(task.inventory_source_status or "").strip() == "user_confirmed"
|
||||
and is_inventory_source_stable(task)
|
||||
and not routing_fingerprint_changed(task, context)
|
||||
and not inventory_source_config_changed(task)
|
||||
):
|
||||
return _adjudication_from_stable_task(task)
|
||||
|
||||
adjudication = adjudicate_inventory_source(task)
|
||||
# Multiple routing candidates may be resolved only from already-exported
|
||||
# snapshots; this never starts RPA or uses inventory quantity as a signal.
|
||||
adjudication = resolve_ambiguous_source_from_ready_snapshots(task, adjudication)
|
||||
if (
|
||||
str(task.inventory_source_status or "").strip() == "user_confirmed"
|
||||
and adjudication.status == "resolved"
|
||||
and adjudication.source_code
|
||||
and str(adjudication.source_code).strip().upper() == str(task.inventory_source_code or "").strip().upper()
|
||||
and is_inventory_source_stable(task)
|
||||
):
|
||||
adjudication = InventorySourceAdjudication(
|
||||
status="user_confirmed",
|
||||
method="user_confirmed",
|
||||
source_code=adjudication.source_code,
|
||||
connector_type=adjudication.connector_type,
|
||||
warehouse_id=adjudication.warehouse_id,
|
||||
config_version=adjudication.config_version,
|
||||
routing_fingerprint=adjudication.routing_fingerprint,
|
||||
candidates=adjudication.candidates,
|
||||
destination_candidates=adjudication.destination_candidates,
|
||||
evidence=adjudication.evidence,
|
||||
reason=adjudication.reason,
|
||||
)
|
||||
|
||||
# [T3: 决策 A1 + C1] ambiguous 且有候选时,不再进入 inventory_source_review 人工阻断;
|
||||
# 多库存源是合法自动链路,直接冻结到 Set/Source/Line 结构化表 + Snapshot JSON 副本,
|
||||
# 状态升级为 candidates_frozen(属于 STABLE_INVENTORY_SOURCE_STATUSES,可进入库存准备)。
|
||||
# 零候选 / conflicted / unresolved 等情况仍保持旧逻辑进入人工复核。
|
||||
# 零候选 / conflicted / unresolved 仅进入自动规则重算 Gate,不产生人工选源入口。
|
||||
if (
|
||||
adjudication.status == "ambiguous"
|
||||
and getattr(task, "id", None) is not None
|
||||
@@ -293,7 +240,7 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour
|
||||
)
|
||||
except ValueError:
|
||||
# 冻结服务抛 ValueError = 候选集合为空(保护分支,正常应命中不进入),
|
||||
# 保留原 ambiguous 让下游 is_inventory_source_stable 正确进入人工阻断。
|
||||
# 保留原 ambiguous 让下游 is_inventory_source_stable 正确进入规则重算阻断。
|
||||
pass
|
||||
|
||||
apply_inventory_source_adjudication(task, adjudication)
|
||||
@@ -307,9 +254,9 @@ def transition_task_to_inventory_source_review(
|
||||
error_message: str | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
将任务持久化到库存源人工复核检查点,并写入候选裁决信息。
|
||||
将任务持久化到库存源规则重算检查点,并写入候选裁决信息。
|
||||
|
||||
核心逻辑:统一状态机转换 + current_step + step_payload 候选,供 UI 展示确认按钮。
|
||||
核心逻辑:保留 checkpoint 作为内部恢复事实,但不产生人工选源按钮;
|
||||
解析复核必须在进入本检查点前完成,不保存延后复核标记。
|
||||
"""
|
||||
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
|
||||
@@ -334,10 +281,10 @@ def transition_task_to_inventory_source_review(
|
||||
|
||||
def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
"""
|
||||
对已通过解析确认但库存源仍不稳定的任务,补做裁决并落库到 inventory_source_review。
|
||||
对已通过解析确认但库存源仍不稳定的任务,补做规则裁决并落库到内部恢复检查点。
|
||||
|
||||
【AI 触发时机】:confirm_parse / auto_progress / ensure_inventory 等入口发现门禁未通过时调用。
|
||||
核心逻辑:新业务顺序固定为先完成解析复核,再进入库存源确认。
|
||||
核心逻辑:新业务顺序固定为先完成解析复核,再进入库存源自动裁决。
|
||||
"""
|
||||
adjudication = adjudicate_and_apply_inventory_source(task)
|
||||
if not is_inventory_source_stable(task):
|
||||
@@ -345,21 +292,6 @@ def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourc
|
||||
return adjudication
|
||||
|
||||
|
||||
def confirm_task_inventory_source(
|
||||
task: ShippingNotice,
|
||||
source_code: str,
|
||||
*,
|
||||
user_id: int | None = None,
|
||||
) -> InventorySourceAdjudication:
|
||||
"""
|
||||
用户选择 source_code 后由后端重新校验并写入正式库存源。
|
||||
核心逻辑:前端只提交 source_code;站点与库位始终从配置生成。
|
||||
"""
|
||||
adjudication = confirm_inventory_source_by_code(task, source_code)
|
||||
apply_inventory_source_adjudication(task, adjudication, confirmed_by_user_id=user_id)
|
||||
return adjudication
|
||||
|
||||
|
||||
def assert_inventory_source_gate(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
|
||||
@@ -71,7 +71,7 @@ def compute_routing_fingerprint(context: dict[str, Any]) -> str:
|
||||
|
||||
|
||||
def _candidate(source: dict[str, Any]) -> dict[str, Any]:
|
||||
"""构造不泄露凭据的人工确认候选。"""
|
||||
"""构造不泄露凭据的规则裁决候选。"""
|
||||
return {
|
||||
'source_code': source['source_code'],
|
||||
'display_name': source['display_name'],
|
||||
@@ -82,7 +82,7 @@ def _candidate(source: dict[str, Any]) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _from_source(*, status: str, source: dict[str, Any], method: str, context: dict[str, Any], evidence: list[dict[str, Any]] | None = None) -> InventorySourceAdjudication:
|
||||
"""由数据库 Source 生成 resolved/user_confirmed 裁决。"""
|
||||
"""由数据库 Source 生成规则裁决。"""
|
||||
resolution = resolve_inventory_source_identity(source, context)
|
||||
if not resolution.ok or not resolution.identity:
|
||||
return InventorySourceAdjudication('invalid', reason=resolution.reason, config_version=inventory_sources_runtime_version())
|
||||
@@ -245,18 +245,6 @@ def adjudicate_inventory_source(task: ShippingNotice) -> InventorySourceAdjudica
|
||||
return _result_to_adjudication(task_result, context)
|
||||
|
||||
|
||||
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)
|
||||
if not source:
|
||||
return InventorySourceAdjudication(
|
||||
'invalid', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context),
|
||||
candidates=[_candidate(item) for item in list_database_inventory_sources()], reason='source_code_not_found',
|
||||
)
|
||||
return _from_source(status='user_confirmed', source=source, method='user_confirmed', context=context)
|
||||
|
||||
|
||||
def resolve_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication:
|
||||
"""兼容调用名,委托当前通用规则裁决。"""
|
||||
return adjudicate_inventory_source(task)
|
||||
@@ -277,15 +265,16 @@ def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
|
||||
|
||||
def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None:
|
||||
"""兼容旧入口,将确认结果委托库存源门禁持久化。"""
|
||||
"""持久化规则裁决结果;禁止根据调用方传入 source_code 人工覆盖。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
selected = resolution or confirm_inventory_source_by_code(task, str(source.get('source_code') or ''))
|
||||
del source
|
||||
selected = resolution or adjudicate_inventory_source(task)
|
||||
apply_inventory_source_adjudication(task, selected)
|
||||
|
||||
|
||||
def mark_inventory_source_review(task: ShippingNotice, resolution: InventorySourceAdjudication) -> None:
|
||||
"""兼容旧入口,写入待人工确认的 Source 候选。"""
|
||||
"""兼容旧入口,写入规则裁决候选;不触发人工库存源确认。"""
|
||||
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
|
||||
|
||||
apply_inventory_source_adjudication(task, resolution)
|
||||
@@ -126,7 +126,6 @@ def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lan
|
||||
task=task,
|
||||
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
|
||||
data=serialize_task_for_tool(task),
|
||||
human_options=ui.human_options,
|
||||
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
|
||||
stop_agent_turn=True,
|
||||
)
|
||||
@@ -320,7 +319,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
**serialize_task_for_tool(task),
|
||||
'blocking_reason': {
|
||||
'code': prep.get('error_code'),
|
||||
'primary_action': 'open_inventory_source_review',
|
||||
'primary_action': 'retry_with_latest_rules',
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
@@ -64,10 +64,28 @@ LIFECYCLE_STAGE_RANGES: tuple[tuple[str, set[str]], ...] = (
|
||||
)
|
||||
|
||||
|
||||
def lifecycle_entries(*, lifecycle_stage: str | None, has_candidate_context: bool) -> list[dict[str, str]]:
|
||||
"""返回只读生命周期入口;无有效 Candidate/正式任务时不开放任何订单生命周期面。"""
|
||||
if not has_candidate_context or lifecycle_stage not in LIFECYCLE_STAGE_CODES:
|
||||
def lifecycle_entries(
|
||||
*,
|
||||
lifecycle_stage: str | None,
|
||||
has_candidate_context: bool,
|
||||
has_intake_parse_context: bool = False,
|
||||
) -> list[dict[str, str]]:
|
||||
"""返回只读生命周期入口;空 Case 仅允许停留在接收解析阶段。"""
|
||||
if lifecycle_stage not in LIFECYCLE_STAGE_CODES:
|
||||
return []
|
||||
if not has_candidate_context:
|
||||
# 接收解析 Case 是已持久化的受控对象,允许在批次页展示其当前阶段;
|
||||
# 但不能借此开放订单复核及后续阶段。
|
||||
if not has_intake_parse_context or lifecycle_stage != 'intake_parse':
|
||||
return []
|
||||
return [
|
||||
{
|
||||
'code': code,
|
||||
'state': 'current' if code == 'intake_parse' else 'unavailable',
|
||||
'target_surface': 'order_lifecycle_workbench',
|
||||
}
|
||||
for code in LIFECYCLE_STAGE_CODES
|
||||
]
|
||||
current_index = LIFECYCLE_STAGE_CODES.index(str(lifecycle_stage))
|
||||
return [
|
||||
{
|
||||
@@ -85,6 +103,7 @@ def project_lifecycle(
|
||||
blocking_reason: dict[str, Any] | None,
|
||||
legacy_stage: str | None,
|
||||
has_candidate_context: bool,
|
||||
has_intake_parse_context: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。
|
||||
|
||||
@@ -114,6 +133,7 @@ def project_lifecycle(
|
||||
'lifecycle_entries': lifecycle_entries(
|
||||
lifecycle_stage=lifecycle_stage,
|
||||
has_candidate_context=has_candidate_context,
|
||||
has_intake_parse_context=has_intake_parse_context,
|
||||
),
|
||||
'lifecycle_authority': authority,
|
||||
}
|
||||
@@ -15,6 +15,7 @@ from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryFile,
|
||||
ShippingNotice,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderReviewCase,
|
||||
@@ -102,6 +103,12 @@ def persist_line_inventory_match_facts(
|
||||
snap_id = inventory_snapshot_id
|
||||
if snap_id is None and getattr(task, 'inventory_snapshot_id', None) is not None:
|
||||
snap_id = int(task.inventory_snapshot_id)
|
||||
# 匹配器结果可能未回填 inventory_file_no,但当前快照本身已是行匹配的
|
||||
# 正式文件身份。持久化必须补齐,避免“有快照却无行级下载证据”。
|
||||
snapshot_file_no = None
|
||||
if snap_id is not None:
|
||||
snapshot = ShippingInventoryFile.query.get(int(snap_id))
|
||||
snapshot_file_no = str(getattr(snapshot, 'inventory_file_no', '') or '').strip() or None
|
||||
|
||||
line_results = [
|
||||
item for item in list(match_payload.get('line_results') or []) if isinstance(item, dict)
|
||||
@@ -213,7 +220,7 @@ def persist_line_inventory_match_facts(
|
||||
)
|
||||
# [T6 E1] 行级证据哈希:SHA256(source_code|file_no|row_index|reservation_id|part_number)
|
||||
src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None
|
||||
file_no = str(result.get('inventory_file_no') or '')[:128] or None
|
||||
file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None
|
||||
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
|
||||
try:
|
||||
row_index = int(row_index_raw) if row_index_raw is not None and str(row_index_raw).strip() else None
|
||||
@@ -295,7 +302,7 @@ def persist_line_inventory_match_facts(
|
||||
else:
|
||||
# [T6 E1] 更新分支:同样重算 evidence_ref、matched_file_no、matched_row_index
|
||||
src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None
|
||||
file_no = str(result.get('inventory_file_no') or '')[:128] or None
|
||||
file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None
|
||||
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
|
||||
try:
|
||||
row_index = int(row_index_raw) if row_index_raw is not None and str(row_index_raw).strip() else None
|
||||
|
||||
@@ -36,6 +36,7 @@ STATUS_INVALID_KEY = 'invalid_key'
|
||||
ACTION_RETRY_PREPARATION = 'retry_inventory_preparation'
|
||||
ACTION_RETRY_MATCHING = 'retry_inventory_matching'
|
||||
ACTION_CLOSE = 'close_unfulfillable'
|
||||
ACTION_RELEASE_SHORTAGE = 'release_inventory_shortage'
|
||||
ACTION_VIEW_FULFILLMENT = 'view_fulfillment_detail' # 已下线:不得再下发 UI
|
||||
|
||||
|
||||
@@ -238,6 +239,8 @@ def project_user_line_status(
|
||||
stored = str(stored_line_status or '').strip()
|
||||
if stored in {'closed_unfulfillable'}:
|
||||
return 'closed'
|
||||
if stored in {'released_shortage'}:
|
||||
return 'released_shortage'
|
||||
if stored in {'fulfilled'}:
|
||||
return 'fulfilled'
|
||||
if stored in {'task_created'}:
|
||||
@@ -294,8 +297,8 @@ def resolve_inventory_allowed_actions(
|
||||
user_status = str(user_line_status or '').strip()
|
||||
if not has_formal_ot:
|
||||
return []
|
||||
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable'} or user_status in {
|
||||
'wave_created', 'fulfilled', 'closed',
|
||||
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable', 'released_shortage'} or user_status in {
|
||||
'wave_created', 'fulfilled', 'closed', 'released_shortage',
|
||||
}:
|
||||
return []
|
||||
if inventory_rpa_running or user_status == 'acquiring_inventory':
|
||||
@@ -310,7 +313,12 @@ def resolve_inventory_allowed_actions(
|
||||
return []
|
||||
|
||||
if is_shortage or result == MATCH_NOT_FOUND or user_status == 'shortage':
|
||||
return [ACTION_RETRY_PREPARATION]
|
||||
# 短缺既可能需要重新取最新库存,也可能仅需用当前有效快照重匹;
|
||||
# 两种意图并列下发,前端不得因已有快照隐藏刷新库存入口。
|
||||
actions = [ACTION_RETRY_PREPARATION]
|
||||
if has_usable_snapshot:
|
||||
actions.append(ACTION_RETRY_MATCHING)
|
||||
return actions
|
||||
|
||||
if (
|
||||
status == STATUS_MAPPING_FAILED
|
||||
@@ -351,7 +359,7 @@ def resolve_line_allowed_actions(
|
||||
user_line_status: str | None,
|
||||
) -> list[str]:
|
||||
"""
|
||||
行生命周期动作;仅 close_unfulfillable。
|
||||
行生命周期动作;短缺行可关闭或填写原因放行。
|
||||
|
||||
核心逻辑:已完成/已关闭/已入波次不开放行动作;彻底移除 view_fulfillment_detail。
|
||||
"""
|
||||
@@ -359,11 +367,14 @@ def resolve_line_allowed_actions(
|
||||
return []
|
||||
stored = str(stored_line_status or '').strip()
|
||||
user_status = str(user_line_status or '').strip()
|
||||
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable'} or user_status in {
|
||||
'wave_created', 'fulfilled', 'closed',
|
||||
if stored in {'task_created', 'fulfilled', 'closed_unfulfillable', 'released_shortage'} or user_status in {
|
||||
'wave_created', 'fulfilled', 'closed', 'released_shortage',
|
||||
}:
|
||||
return []
|
||||
return [ACTION_CLOSE]
|
||||
actions = [ACTION_CLOSE]
|
||||
if user_status == 'shortage':
|
||||
actions.append(ACTION_RELEASE_SHORTAGE)
|
||||
return actions
|
||||
|
||||
|
||||
def resolve_allowed_actions(
|
||||
@@ -491,7 +502,7 @@ def project_line_inventory_view(
|
||||
|
||||
Args:
|
||||
fallback_inventory_source: Task 级回退库存源事实(行级匹配缺失时使用)。
|
||||
支持:resolved / user_confirmed / candidates_frozen / resolving 四种语义。
|
||||
支持:resolved / candidates_frozen / resolving 三种语义。
|
||||
仅影响 inventory_source 展示对象,不得污染 inventory_status / match_result /
|
||||
available_qty / shortage_qty / is_shortage / allowed_actions。
|
||||
|
||||
@@ -518,7 +529,6 @@ def project_line_inventory_view(
|
||||
if fallback.get('code') and fallback.get('status') in {
|
||||
SOURCE_STATUS_RESOLVED,
|
||||
'resolved',
|
||||
'user_confirmed',
|
||||
}:
|
||||
pre_source = {
|
||||
'code': fallback.get('code'),
|
||||
@@ -618,7 +628,7 @@ def project_line_inventory_view(
|
||||
fb_code = str(fallback.get('code') or '').strip().upper() or None
|
||||
fb_status = str(fallback.get('status') or '').strip()
|
||||
if not line_source_code and fallback:
|
||||
if fb_code and fb_status in {'resolved', 'user_confirmed', SOURCE_STATUS_RESOLVED}:
|
||||
if fb_code and fb_status in {'resolved', SOURCE_STATUS_RESOLVED}:
|
||||
label_val = str(fallback.get('label') or '').strip() or (
|
||||
(source_labels or {}).get(fb_code)
|
||||
)
|
||||
|
||||
@@ -20,7 +20,7 @@ NOTICE_LINE_FIELDS = (
|
||||
"customer_part_number",
|
||||
"aws_part_number",
|
||||
"uom",
|
||||
"remark",
|
||||
"line_remark",
|
||||
"po_number",
|
||||
"allocation_id",
|
||||
"inventory_source_hint",
|
||||
@@ -40,4 +40,5 @@ NOTICE_FIELD_LABELS = {
|
||||
"po_number": "PO Number",
|
||||
"allocation_id": "Allocation ID",
|
||||
"inventory_source_hint": "库存来源提示 / Hub Code",
|
||||
"line_remark": "行备注",
|
||||
}
|
||||
@@ -130,7 +130,7 @@ def parse_notice_row(
|
||||
|
||||
for field in (
|
||||
'currency', 'uom', 'required_date', 'po_number', 'inventory_source_hint',
|
||||
'customer_part_number', 'aws_part_number',
|
||||
'customer_part_number', 'aws_part_number', 'line_remark',
|
||||
):
|
||||
idx = columns.get(field)
|
||||
if idx is None:
|
||||
|
||||
@@ -87,7 +87,7 @@ def resolve_notice_columns(
|
||||
核心逻辑:逐列匹配冻结契约;同一字段命中多个列时记录歧义并清空该映射。
|
||||
"""
|
||||
columns: dict[str, int | list[str] | None] = {
|
||||
field: None for field in NOTICE_LINE_FIELDS if field not in {"uom", "remark"}
|
||||
field: None for field in NOTICE_LINE_FIELDS if field not in {"uom", "line_remark"}
|
||||
}
|
||||
ambiguous: set[str] = set()
|
||||
for i, header in enumerate(headers):
|
||||
|
||||
@@ -103,6 +103,61 @@ def non_atomic_part_number_field(raw: dict[str, Any] | None) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
def _canonicalize_schema_line_aliases(
|
||||
raw: dict[str, Any], *, schema_definition: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
以本次冻结 Schema 的明细字段别名将输入键归一化为 field_code。
|
||||
|
||||
核心逻辑:字段代码优先于别名;同一原始行的多个别名同时映射一个字段时不静默选值,
|
||||
仅保留已存在的字段代码。无 Schema 时只接受调用方提供的正式字段代码。
|
||||
Args:
|
||||
raw: 原始订单行,键可能为邮件/PDF 表头或正式字段代码。
|
||||
schema_definition: 本次 Run 冻结的完整订单 Schema。
|
||||
Returns:
|
||||
使用正式 field_code 作为键的订单行副本。
|
||||
"""
|
||||
canonical = dict(raw)
|
||||
if not schema_definition:
|
||||
return canonical
|
||||
|
||||
aliases: dict[str, str] = {}
|
||||
ambiguous_aliases: set[str] = set()
|
||||
for field in schema_definition.get('fields') or []:
|
||||
if not isinstance(field, dict) or not field.get('enabled', True):
|
||||
continue
|
||||
if str(field.get('scope') or 'line').strip().lower() != 'line':
|
||||
continue
|
||||
field_code = str(field.get('field_code') or '').strip()
|
||||
if not field_code:
|
||||
continue
|
||||
for name in (field_code, field.get('display_name'), *(field.get('aliases') or [])):
|
||||
normalized = norm_header(name)
|
||||
if not normalized:
|
||||
continue
|
||||
previous = aliases.get(normalized)
|
||||
if previous is None:
|
||||
aliases[normalized] = field_code
|
||||
elif previous != field_code:
|
||||
ambiguous_aliases.add(normalized)
|
||||
|
||||
mapped_values: dict[str, Any] = {}
|
||||
ambiguous_codes: set[str] = set()
|
||||
for name, value in raw.items():
|
||||
normalized_name = norm_header(name)
|
||||
field_code = None if normalized_name in ambiguous_aliases else aliases.get(normalized_name)
|
||||
if not field_code or field_code in canonical:
|
||||
continue
|
||||
if field_code in mapped_values:
|
||||
ambiguous_codes.add(field_code)
|
||||
continue
|
||||
mapped_values[field_code] = value
|
||||
for field_code, value in mapped_values.items():
|
||||
if field_code not in ambiguous_codes:
|
||||
canonical[field_code] = value
|
||||
return canonical
|
||||
|
||||
|
||||
def normalize_notice_line(
|
||||
raw: dict[str, Any] | None,
|
||||
*,
|
||||
@@ -121,6 +176,7 @@ def normalize_notice_line(
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
raw = _canonicalize_schema_line_aliases(raw, schema_definition=schema_definition)
|
||||
if non_atomic_part_number_field(raw):
|
||||
return None
|
||||
|
||||
@@ -130,7 +186,7 @@ def normalize_notice_line(
|
||||
if not part_number or "/" in part_number:
|
||||
return None
|
||||
|
||||
qty = parse_number(raw.get("qty") if raw.get("qty") is not None else raw.get("quantity"))
|
||||
qty = parse_number(raw.get("qty"))
|
||||
if qty is None or qty <= 0:
|
||||
return None
|
||||
|
||||
@@ -145,89 +201,51 @@ def normalize_notice_line(
|
||||
if raw_uom and field_enabled("uom"):
|
||||
line["uom"] = raw_uom
|
||||
|
||||
line_no = normalize_line_no(
|
||||
raw.get("line_no")
|
||||
or raw.get("lineNo")
|
||||
or raw.get("item")
|
||||
or raw.get("item_no")
|
||||
or raw.get("itemNo")
|
||||
or raw.get("Item")
|
||||
or raw.get("Item No")
|
||||
)
|
||||
line_no = normalize_line_no(raw.get("line_no"))
|
||||
if line_no and field_enabled("line_no"):
|
||||
line["line_no"] = line_no
|
||||
|
||||
reservation_id = extract_reservation_id(
|
||||
raw.get("reservation_id")
|
||||
or raw.get("reservationId")
|
||||
or raw.get("com_id")
|
||||
or raw.get("reservation_order")
|
||||
or raw.get("pr_number")
|
||||
or raw.get("prNumber")
|
||||
or raw.get("PR Number")
|
||||
)
|
||||
reservation_id = extract_reservation_id(raw.get("reservation_id"))
|
||||
if reservation_id and field_enabled("reservation_id"):
|
||||
line["reservation_id"] = reservation_id
|
||||
evidence = raw.get("reservation_id_evidence")
|
||||
if isinstance(evidence, dict) and field_enabled("reservation_id"):
|
||||
line["reservation_id_evidence"] = dict(evidence)
|
||||
|
||||
unit_price = parse_number(raw.get("unit_price") if raw.get("unit_price") is not None else raw.get("price"))
|
||||
unit_price = parse_number(raw.get("unit_price"))
|
||||
if unit_price is not None and field_enabled("unit_price"):
|
||||
line["unit_price"] = unit_price
|
||||
|
||||
amount = parse_number(raw.get("amount") if raw.get("amount") is not None else raw.get("total"))
|
||||
amount = parse_number(raw.get("amount"))
|
||||
if amount is not None and field_enabled("amount"):
|
||||
line["amount"] = amount
|
||||
elif unit_price is not None and field_enabled("amount"):
|
||||
line["amount"] = round(unit_price * qty, 4)
|
||||
|
||||
currency = normalize_currency(raw.get("currency") or raw.get("Currency"))
|
||||
currency = normalize_currency(raw.get("currency"))
|
||||
if not currency:
|
||||
currency = extract_currency(
|
||||
raw.get("unit_price"),
|
||||
raw.get("price"),
|
||||
raw.get("amount"),
|
||||
raw.get("total"),
|
||||
raw.get("unit_price"), raw.get("amount"),
|
||||
)
|
||||
if currency and field_enabled("currency"):
|
||||
line["currency"] = currency
|
||||
|
||||
required_date = normalize_required_date(
|
||||
raw.get("required_date")
|
||||
or raw.get("delivery_date")
|
||||
or raw.get("deliveryDate")
|
||||
or raw.get("eta")
|
||||
or raw.get("ETA")
|
||||
)
|
||||
required_date = normalize_required_date(raw.get("required_date"))
|
||||
if required_date and field_enabled("required_date"):
|
||||
line["required_date"] = required_date
|
||||
|
||||
optional_aliases = {
|
||||
"po_number": ("po_number", "poNumber", "PO", "PO Number"),
|
||||
"allocation_id": ("allocation_id", "allocationId", "Allocation ID"),
|
||||
"inventory_source_hint": (
|
||||
"inventory_source_hint",
|
||||
"Source Type",
|
||||
"Hub Code",
|
||||
"Hub",
|
||||
"HUB",
|
||||
),
|
||||
"customer_part_number": ("customer_part_number", "Customer Part Number", "Customer PN", "Allocated HHPN"),
|
||||
"aws_part_number": ("aws_part_number", "AWS Sku", "AWS SKU"),
|
||||
}
|
||||
optional_fields = (
|
||||
"po_number", "allocation_id", "inventory_source_hint",
|
||||
"customer_part_number", "aws_part_number", "line_remark",
|
||||
)
|
||||
if composite.get('customer_part_number'):
|
||||
if field_enabled('customer_part_number'):
|
||||
line['customer_part_number'] = composite['customer_part_number']
|
||||
for field, aliases in optional_aliases.items():
|
||||
value = next((str(raw.get(alias) or "").strip() for alias in aliases if raw.get(alias)), "")
|
||||
for field in optional_fields:
|
||||
value = str(raw.get(field) or "").strip()
|
||||
if value and field_enabled(field):
|
||||
line[field] = value
|
||||
|
||||
remark = str(raw.get("remark") or raw.get("note") or "").strip()
|
||||
if remark and field_enabled("remark"):
|
||||
line["remark"] = remark
|
||||
|
||||
return line
|
||||
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ def _post_op(
|
||||
"200": {
|
||||
"description": (
|
||||
"Tool response (status: ok|running|needs_human|failed). "
|
||||
"May include checkpoint and human_options; business buttons are exposed only by ui_state.actions."
|
||||
"May include checkpoint; business buttons are exposed only by ui_state.actions."
|
||||
),
|
||||
"content": {
|
||||
"application/json": {
|
||||
@@ -86,7 +86,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"paths": {
|
||||
"/tools/get_task_status": _post_op(
|
||||
"get_task_status",
|
||||
"查询任务当前状态与 human_options;响应含库存连接器独立字段与候选结构",
|
||||
"查询任务当前状态;响应含库存连接器独立字段与候选结构",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID"),
|
||||
@@ -96,9 +96,8 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
description=(
|
||||
"返回 inventory_source_code、inventory_connector_type、"
|
||||
"inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|"
|
||||
"user_confirmed|invalid|conflicted)、inventory_source_method、"
|
||||
"candidates_frozen|invalid|conflicted)、inventory_source_method、"
|
||||
"inventory_source_config_version、inventory_routing_fingerprint、"
|
||||
"inventory_source_confirmed_by、inventory_source_confirmed_at,"
|
||||
"以及 step_payload.inventory_source_resolution.candidates。"
|
||||
),
|
||||
),
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
services/shipping_notice/order_auto_freeze_policy.py
|
||||
|
||||
用途:统一生成订单抽取 Run 的自动冻结门禁摘要,不让各处各自拼 policy JSON。
|
||||
依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与分路径/XFA 开关;
|
||||
依赖:Run/Unit/RouteDecision/Qualification 模型;tool_common 紧急停止与通用开关;
|
||||
process_gate_contract(原因唯一归属 order_freeze_readiness)。
|
||||
逻辑:Run 创建时冻结初始人工确认策略;结果落库后按解析路径、技术失败、预算停止、
|
||||
紧急停止和复核状态刷新 Run 级摘要。
|
||||
模板 Profile 批准写入 parser / qualification 痕迹,不再作为唯一放行条件;
|
||||
LLM 路径可进入 Candidate Qualification,不再天然追加 llm_path_cannot_auto_freeze;
|
||||
XFA 写入 shadow/可选观测白名单痕迹;真实自动建单与坐标共用统一 Candidate Qualification。
|
||||
XFA datasets 仅写入值源身份痕迹;真实自动建单与坐标共用统一 Candidate Qualification。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -30,10 +30,6 @@ 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'
|
||||
@@ -80,7 +76,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),
|
||||
'value_adapter': _value_adapter_trace(run),
|
||||
}
|
||||
|
||||
# [STEP 1] 全局紧急停止:新 Run 自动冻结立即为 0。
|
||||
@@ -215,33 +211,20 @@ def evaluate_run_auto_freeze_policy(
|
||||
return policy
|
||||
|
||||
|
||||
def _xfa_policy_trace(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
def _value_adapter_trace(run: ShippingOrderProcessingRun) -> dict[str, Any]:
|
||||
"""
|
||||
汇总 Run 级 XFA 策略痕迹(真实放行仍由 CQ/STP 硬门禁裁决)。
|
||||
汇总 Run 级末端取值 adapter 身份痕迹。
|
||||
|
||||
核心逻辑:记录 shadow 与白名单规模,供审计对账;空白名单在 CQ 层 fail-closed。
|
||||
核心逻辑:仅记录数据集 adapter 是否参与,不能读取或冻结模板类型专属放行策略。
|
||||
"""
|
||||
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()),
|
||||
'adapter_kind': 'xfa_dataset' if has_xfa else 'coordinate_ocr',
|
||||
'datasets_adapter_present': has_xfa,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -217,14 +217,6 @@ def classify_inventory_source_codes(codes: list[str]) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _validate_enabled_sources(codes: list[str]) -> tuple[list[str], list[str]]:
|
||||
"""
|
||||
校验库存源已启用且具备有效解析 Profile;返回 (valid_codes, invalid_codes)。
|
||||
"""
|
||||
classified = classify_inventory_source_codes(codes)
|
||||
return list(classified['available']), list(classified['unavailable'])
|
||||
|
||||
|
||||
def _rule_suggestion_from_result(rule_result: InventoryRoutingResult) -> dict[str, Any]:
|
||||
"""
|
||||
将引擎原始结果折叠为「规则建议」:过滤不可用源后重算建议状态。
|
||||
@@ -270,11 +262,6 @@ def _rule_suggestion_from_result(rule_result: InventoryRoutingResult) -> dict[st
|
||||
}
|
||||
|
||||
|
||||
def _codes_equal(left: list[str] | tuple[str, ...] | None, right: list[str] | tuple[str, ...] | None) -> bool:
|
||||
"""比较两组库存源编码是否集合相等。"""
|
||||
return set(_normalize_manual_codes(left)) == set(_normalize_manual_codes(right))
|
||||
|
||||
|
||||
def project_line_inventory_candidates(
|
||||
*,
|
||||
fields: dict[str, dict[str, Any]],
|
||||
@@ -296,13 +283,6 @@ def project_line_inventory_candidates(
|
||||
Returns:
|
||||
含有效候选、原始候选、不可用候选、规则建议与建单门禁的字典。
|
||||
"""
|
||||
meta = line_meta if isinstance(line_meta, dict) else {}
|
||||
routing_overlay = meta.get('inventory_routing') if isinstance(meta.get('inventory_routing'), dict) else {}
|
||||
manual_codes = _normalize_manual_codes(routing_overlay.get('candidate_inventory_source_codes'))
|
||||
manual_reason = str(routing_overlay.get('manual_reason') or '').strip()
|
||||
selection_mode = str(routing_overlay.get('selection_mode') or '').strip().lower()
|
||||
stored_pending = bool(routing_overlay.get('suggestion_pending'))
|
||||
|
||||
header_ids, line_ids = _field_id_maps(
|
||||
fields=fields, header_by_code=header_by_code, line_by_code=line_by_code,
|
||||
)
|
||||
@@ -341,46 +321,6 @@ def project_line_inventory_candidates(
|
||||
},
|
||||
}
|
||||
|
||||
if selection_mode == 'manual' and manual_codes:
|
||||
valid, invalid = _validate_enabled_sources(manual_codes)
|
||||
suggestion_pending = stored_pending and not _codes_equal(valid, suggestion['source_codes'])
|
||||
if not manual_reason:
|
||||
return {
|
||||
**base_fields,
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'routing_status': 'conflicted',
|
||||
'can_build': False,
|
||||
'block_reason': 'manual_inventory_source_reason_required',
|
||||
'invalid_source_codes': invalid,
|
||||
'suggestion_pending': suggestion_pending,
|
||||
'evidence': {'manual_override': True, 'rule': suggestion['evidence']},
|
||||
}
|
||||
if invalid or not valid:
|
||||
return {
|
||||
**base_fields,
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'routing_status': 'unresolved',
|
||||
'can_build': False,
|
||||
'block_reason': 'manual_inventory_source_invalid',
|
||||
'invalid_source_codes': invalid,
|
||||
'suggestion_pending': suggestion_pending,
|
||||
'evidence': {'manual_override': True, 'rule': suggestion['evidence']},
|
||||
}
|
||||
return {
|
||||
**base_fields,
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'routing_status': 'resolved' if len(valid) == 1 else 'ambiguous',
|
||||
'can_build': True,
|
||||
'block_reason': None,
|
||||
'manual_reason': manual_reason,
|
||||
'invalid_source_codes': [],
|
||||
'suggestion_pending': suggestion_pending,
|
||||
'evidence': {'manual_override': True, 'rule': suggestion['evidence']},
|
||||
}
|
||||
|
||||
# [STEP 2] 无人工决定:规则建议直接成为有效结果(唯一命中即可建单)。
|
||||
return {
|
||||
**base_fields,
|
||||
@@ -394,7 +334,6 @@ def project_line_inventory_candidates(
|
||||
'evidence': dict(suggestion['evidence']),
|
||||
}
|
||||
|
||||
|
||||
def assess_auto_build_gates(
|
||||
*,
|
||||
fields_complete: bool,
|
||||
@@ -746,184 +685,3 @@ def assess_order_build_eligibility(
|
||||
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 [],
|
||||
}
|
||||
|
||||
|
||||
def apply_manual_inventory_candidates(
|
||||
*,
|
||||
line_meta: dict[str, Any],
|
||||
source_codes: list[str],
|
||||
reason: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将人工候选选择写入 Draft 行 inventory_routing 覆盖层。
|
||||
|
||||
Args:
|
||||
line_meta: Draft 行对象(会被就地更新并返回)。
|
||||
source_codes: 已启用库存源编码(1..N)。
|
||||
reason: 强制人工原因。
|
||||
|
||||
Returns:
|
||||
更新后的 inventory_routing 片段。
|
||||
|
||||
Raises:
|
||||
ValueError: 原因或候选无效。
|
||||
"""
|
||||
codes = _normalize_manual_codes(source_codes)
|
||||
text = str(reason or '').strip()
|
||||
if not text:
|
||||
raise ValueError('manual_inventory_source_reason_required')
|
||||
if not codes:
|
||||
raise ValueError('manual_inventory_source_empty')
|
||||
valid, invalid = _validate_enabled_sources(codes)
|
||||
if invalid or not valid:
|
||||
raise ValueError('manual_inventory_source_invalid')
|
||||
previous = line_meta.get('inventory_routing') if isinstance(line_meta.get('inventory_routing'), dict) else {}
|
||||
overlay = {
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'manual_reason': text,
|
||||
# 人工改选后清除待确认建议,避免静默与旧建议混用。
|
||||
'suggestion_pending': False,
|
||||
}
|
||||
if isinstance(previous.get('rule_suggestion'), dict):
|
||||
overlay['rule_suggestion'] = previous.get('rule_suggestion')
|
||||
line_meta['inventory_routing'] = overlay
|
||||
return overlay
|
||||
|
||||
|
||||
def apply_rule_suggestion_as_effective(
|
||||
*,
|
||||
line_meta: dict[str, Any],
|
||||
suggestion: dict[str, Any],
|
||||
reason: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将规则建议采用为当前有效候选(明确动作,非静默覆盖)。
|
||||
|
||||
核心逻辑:写入 selection_mode=rule 的有效编码;记录 adopt 动作语义与原因;
|
||||
清除 suggestion_pending。
|
||||
|
||||
Args:
|
||||
line_meta: Draft 行对象。
|
||||
suggestion: 规则建议片段(须含 source_codes)。
|
||||
reason: 采用原因或动作说明。
|
||||
|
||||
Returns:
|
||||
更新后的 inventory_routing。
|
||||
|
||||
Raises:
|
||||
ValueError: 建议无效。
|
||||
"""
|
||||
codes = _normalize_manual_codes(suggestion.get('source_codes'))
|
||||
text = str(reason or '').strip() or 'adopt_rule_suggestion'
|
||||
if not codes:
|
||||
raise ValueError('rule_suggestion_empty')
|
||||
valid, invalid = _validate_enabled_sources(codes)
|
||||
if invalid or not valid:
|
||||
raise ValueError('rule_suggestion_invalid')
|
||||
overlay = {
|
||||
'selection_mode': 'rule',
|
||||
'candidate_inventory_source_codes': valid,
|
||||
'manual_reason': text,
|
||||
'adopted_from_rule': True,
|
||||
'suggestion_pending': False,
|
||||
'rule_suggestion': {
|
||||
'source_codes': valid,
|
||||
'raw_source_codes': list(suggestion.get('raw_source_codes') or valid),
|
||||
'unavailable_source_codes': list(suggestion.get('unavailable_source_codes') or []),
|
||||
'unavailable_reasons': dict(suggestion.get('unavailable_reasons') or {}),
|
||||
'routing_status': str(
|
||||
suggestion.get('routing_status') or ('resolved' if len(valid) == 1 else 'ambiguous')
|
||||
),
|
||||
'matched_rule_ids': list(suggestion.get('matched_rule_ids') or []),
|
||||
'matched_rules': list(suggestion.get('matched_rules') or []),
|
||||
'rule_versions': list(suggestion.get('rule_versions') or []),
|
||||
},
|
||||
}
|
||||
line_meta['inventory_routing'] = overlay
|
||||
return overlay
|
||||
|
||||
|
||||
def mark_keep_manual_inventory_decision(
|
||||
*,
|
||||
line_meta: dict[str, Any],
|
||||
reason: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
明确保留人工库存源决定并拒绝当前规则建议。
|
||||
|
||||
Args:
|
||||
line_meta: Draft 行对象(须已有 manual 覆盖)。
|
||||
reason: 保留原因或动作说明。
|
||||
|
||||
Returns:
|
||||
更新后的 inventory_routing。
|
||||
|
||||
Raises:
|
||||
ValueError: 当前无人工决定。
|
||||
"""
|
||||
previous = line_meta.get('inventory_routing') if isinstance(line_meta.get('inventory_routing'), dict) else {}
|
||||
if str(previous.get('selection_mode') or '').strip().lower() != 'manual':
|
||||
raise ValueError('manual_inventory_decision_missing')
|
||||
codes = _normalize_manual_codes(previous.get('candidate_inventory_source_codes'))
|
||||
if not codes:
|
||||
raise ValueError('manual_inventory_decision_missing')
|
||||
text = str(reason or '').strip() or 'keep_manual_inventory_decision'
|
||||
overlay = {
|
||||
**previous,
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': codes,
|
||||
'suggestion_pending': False,
|
||||
'rejected_rule_suggestion': previous.get('rule_suggestion'),
|
||||
'keep_manual_reason': text[:500],
|
||||
}
|
||||
line_meta['inventory_routing'] = overlay
|
||||
return overlay
|
||||
|
||||
|
||||
def attach_rule_suggestion_without_override(
|
||||
*,
|
||||
line_meta: dict[str, Any],
|
||||
suggestion: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
重路由后写入规则建议;若存在人工决定则不覆盖有效候选。
|
||||
|
||||
核心逻辑:人工决定存在时仅更新 rule_suggestion 与 suggestion_pending;
|
||||
无人工决定时清除残留覆盖层,有效结果由实时规则投影得出。
|
||||
|
||||
Args:
|
||||
line_meta: Draft 行对象。
|
||||
suggestion: 最新规则建议。
|
||||
|
||||
Returns:
|
||||
更新后的 inventory_routing;无人工决定时返回空 dict。
|
||||
"""
|
||||
previous = line_meta.get('inventory_routing') if isinstance(line_meta.get('inventory_routing'), dict) else {}
|
||||
suggestion_payload = {
|
||||
'source_codes': list(suggestion.get('source_codes') or []),
|
||||
'raw_source_codes': list(suggestion.get('raw_source_codes') or []),
|
||||
'unavailable_source_codes': list(suggestion.get('unavailable_source_codes') or []),
|
||||
'unavailable_reasons': dict(suggestion.get('unavailable_reasons') or {}),
|
||||
'routing_status': str(suggestion.get('routing_status') or 'unresolved'),
|
||||
'matched_rule_ids': list(suggestion.get('matched_rule_ids') or []),
|
||||
'matched_rules': list(suggestion.get('matched_rules') or []),
|
||||
'rule_versions': list(suggestion.get('rule_versions') or []),
|
||||
}
|
||||
selection_mode = str(previous.get('selection_mode') or '').strip().lower()
|
||||
manual_codes = _normalize_manual_codes(previous.get('candidate_inventory_source_codes'))
|
||||
if selection_mode == 'manual' and manual_codes:
|
||||
pending = not _codes_equal(manual_codes, suggestion_payload['source_codes'])
|
||||
overlay = {
|
||||
**previous,
|
||||
'selection_mode': 'manual',
|
||||
'candidate_inventory_source_codes': manual_codes,
|
||||
'rule_suggestion': suggestion_payload,
|
||||
'suggestion_pending': pending,
|
||||
}
|
||||
line_meta['inventory_routing'] = overlay
|
||||
return overlay
|
||||
|
||||
if previous:
|
||||
line_meta.pop('inventory_routing', None)
|
||||
return {}
|
||||
@@ -1,356 +1,18 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_audit_service.py
|
||||
|
||||
用途:提供订单模板版本中心的审计时间线查询与只读访问留痕;视觉绑定变更双写 Profile 审计与统一平台快照。
|
||||
依赖:ShippingOrderDocumentProfile、ShippingOrderDocumentProfileAudit、User ORM、profile service 审计助手、
|
||||
audit_service.append_shipping_audit_event、audit_service.project_audit_snapshot。
|
||||
逻辑:审计列表使用游标分页避免新增事件导致翻页重复;读接口返回安全摘要,不暴露 PDF、正文或盲测真值;
|
||||
confirm/reject/suggest/updated 路径在 Profile _audit 后追加 append_shipping_audit_event(含加密 full 快照)。
|
||||
"""
|
||||
"""订单模板版本治理审计时间线查询。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, time
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import String, cast, or_
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileAudit, User
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
XFA_VISUAL_BINDING_AUDIT_EVENTS: frozenset[str] = frozenset({
|
||||
'xfa_visual_binding_suggested',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
})
|
||||
|
||||
_VISUAL_BINDING_PLATFORM_ACTIONS: dict[str, str] = {
|
||||
'xfa_visual_binding_suggested': 'suggest_visual_binding',
|
||||
'xfa_visual_binding_confirmed': 'confirm_visual_binding',
|
||||
'xfa_visual_binding_rejected': 'reject_visual_binding',
|
||||
'xfa_visual_binding_updated': 'update_visual_binding',
|
||||
}
|
||||
|
||||
|
||||
def build_profile_audit_context(profile: ShippingOrderDocumentProfile | dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""
|
||||
组装 Profile 上下文供统一审计 full 快照与白名单投影使用。
|
||||
|
||||
核心逻辑:从 ORM 或调用方 dict 提取 profile_code/version/checksum/revision/template_mode。
|
||||
|
||||
Args:
|
||||
profile: Profile ORM 或已投影的上下文字典。
|
||||
|
||||
Returns:
|
||||
非敏感 Profile 上下文字典;profile 为空时返回空 dict。
|
||||
"""
|
||||
if profile is None:
|
||||
return {}
|
||||
if isinstance(profile, dict):
|
||||
return {
|
||||
key: profile[key]
|
||||
for key in (
|
||||
'profile_code',
|
||||
'profile_version',
|
||||
'definition_checksum',
|
||||
'revision_no',
|
||||
'template_mode',
|
||||
)
|
||||
if key in profile and profile[key] is not None
|
||||
}
|
||||
definition = profile.definition_json if isinstance(getattr(profile, 'definition_json', None), dict) else {}
|
||||
profile_code = getattr(profile, 'profile_code', None)
|
||||
version = getattr(profile, 'version', None)
|
||||
structure_fingerprint = getattr(profile, 'structure_fingerprint', None)
|
||||
lock_version = getattr(profile, 'lock_version', None)
|
||||
template_mode = getattr(profile, 'template_mode', None)
|
||||
return {
|
||||
key: value
|
||||
for key, value in {
|
||||
'profile_code': profile_code,
|
||||
'profile_version': int(version) if version is not None else None,
|
||||
'definition_checksum': structure_fingerprint,
|
||||
'revision_no': int(lock_version) if lock_version is not None else None,
|
||||
'template_mode': str(template_mode or definition.get('template_mode') or 'xfa_dataset'),
|
||||
}.items()
|
||||
if value is not None
|
||||
}
|
||||
|
||||
|
||||
def _project_visual_binding_whitelist_snapshot(
|
||||
*,
|
||||
binding_summary: dict[str, Any] | None,
|
||||
profile_context: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
将 binding 摘要与 Profile 上下文投影为统一审计白名单快照。
|
||||
|
||||
核心逻辑:合并 profile 上下文与 field_code/status,委托 project_audit_snapshot 过滤。
|
||||
|
||||
Args:
|
||||
binding_summary: visual_binding_audit_snapshot 或 _binding_audit_snapshot 输出。
|
||||
profile_context: build_profile_audit_context 返回值。
|
||||
|
||||
Returns:
|
||||
白名单 before/after 快照,或 None。
|
||||
"""
|
||||
if binding_summary is None and not profile_context:
|
||||
return None
|
||||
from app.services.shipping_notice.audit_service import project_audit_snapshot
|
||||
|
||||
merged: dict[str, Any] = dict(profile_context or {})
|
||||
if isinstance(binding_summary, dict):
|
||||
field_code = binding_summary.get('field_code')
|
||||
if field_code:
|
||||
merged['field_code'] = field_code
|
||||
status = binding_summary.get('status') or binding_summary.get('visual_status')
|
||||
if status:
|
||||
merged['status'] = status
|
||||
projected = project_audit_snapshot(merged)
|
||||
return projected or None
|
||||
|
||||
|
||||
def _build_visual_binding_full_snapshot(
|
||||
*,
|
||||
binding: dict[str, Any] | None,
|
||||
binding_summary: dict[str, Any] | None,
|
||||
profile_context: dict[str, Any],
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
组装视觉绑定加密完整快照载荷(binding 摘要 + Profile 上下文)。
|
||||
|
||||
核心逻辑:优先使用 raw binding;缺失时降级 binding_summary;可附加 suggest 等区域元数据。
|
||||
|
||||
Args:
|
||||
binding: 原始 binding dict(可为 None)。
|
||||
binding_summary: 审计摘要(可为 None)。
|
||||
profile_context: Profile 上下文。
|
||||
extra: 可选附加非敏感字段(如 page_no、candidate_count)。
|
||||
|
||||
Returns:
|
||||
full_before/full_after 载荷;两者皆空且无 extra 时返回 None。
|
||||
"""
|
||||
if binding is None and binding_summary is None and not extra:
|
||||
return None
|
||||
payload: dict[str, Any] = dict(profile_context or {})
|
||||
if binding is not None:
|
||||
payload['binding'] = binding
|
||||
elif binding_summary is not None:
|
||||
payload['binding_summary'] = binding_summary
|
||||
if extra:
|
||||
payload.update(extra)
|
||||
return payload
|
||||
|
||||
|
||||
def _append_visual_binding_platform_audit_event(
|
||||
*,
|
||||
profile_id: int,
|
||||
document_id: int | None,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
request_id: str | None,
|
||||
operation_id: str | None,
|
||||
action: str | None,
|
||||
binding_id: str | None,
|
||||
page_no: int | None,
|
||||
before_summary: dict[str, Any] | None,
|
||||
after_summary: dict[str, Any] | None,
|
||||
raw_binding_before: dict[str, Any] | None,
|
||||
raw_binding_after: dict[str, Any] | None,
|
||||
profile_context: dict[str, Any],
|
||||
metadata_extra: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
双写统一货代审计事件(含白名单 before/after 与加密 full 快照)。
|
||||
|
||||
核心逻辑:投影白名单 → 组装 full 载荷 → append_shipping_audit_event;
|
||||
context_refs/metadata 携带 binding_id、action、page_no。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 可选样本文档 ID。
|
||||
event_type: 与 Profile 审计同名的事件码。
|
||||
actor_id: 操作者 ID。
|
||||
request_id: HTTP request_id。
|
||||
operation_id: 幂等 operation_id。
|
||||
action: 业务动作(confirm/reject/suggest/created/deleted/updated)。
|
||||
binding_id: 目标 binding_id。
|
||||
page_no: 页码(可选)。
|
||||
before_summary: 变更前 binding 审计摘要。
|
||||
after_summary: 变更后 binding 审计摘要。
|
||||
raw_binding_before: 变更前 raw binding。
|
||||
raw_binding_after: 变更后 raw binding。
|
||||
profile_context: Profile 上下文。
|
||||
metadata_extra: 附加 metadata(须已脱敏)。
|
||||
|
||||
Returns:
|
||||
None;由调用方与业务在同一事务提交。
|
||||
"""
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
safe_action = str(action or _VISUAL_BINDING_PLATFORM_ACTIONS.get(event_type) or event_type)[:64]
|
||||
safe_binding_id = str(binding_id or '').strip() or None
|
||||
context_refs: dict[str, Any] = {}
|
||||
if safe_binding_id:
|
||||
context_refs['binding_id'] = safe_binding_id
|
||||
if safe_action:
|
||||
context_refs['action'] = safe_action
|
||||
if page_no is not None:
|
||||
context_refs['page_no'] = int(page_no)
|
||||
|
||||
metadata: dict[str, Any] = dict(metadata_extra or {})
|
||||
if safe_binding_id:
|
||||
metadata.setdefault('binding_id', safe_binding_id)
|
||||
if safe_action:
|
||||
metadata.setdefault('action', safe_action)
|
||||
if page_no is not None:
|
||||
metadata.setdefault('page_no', int(page_no))
|
||||
|
||||
whitelist_before = _project_visual_binding_whitelist_snapshot(
|
||||
binding_summary=before_summary,
|
||||
profile_context=profile_context if before_summary is not None else None,
|
||||
)
|
||||
whitelist_after = _project_visual_binding_whitelist_snapshot(
|
||||
binding_summary=after_summary,
|
||||
profile_context=profile_context if after_summary is not None else profile_context or None,
|
||||
)
|
||||
full_before = _build_visual_binding_full_snapshot(
|
||||
binding=raw_binding_before,
|
||||
binding_summary=before_summary,
|
||||
profile_context=profile_context,
|
||||
)
|
||||
full_after = _build_visual_binding_full_snapshot(
|
||||
binding=raw_binding_after,
|
||||
binding_summary=after_summary,
|
||||
profile_context=profile_context,
|
||||
extra=dict(metadata_extra or {}) if event_type == 'xfa_visual_binding_suggested' and after_summary else None,
|
||||
)
|
||||
|
||||
append_shipping_audit_event(
|
||||
event_type=event_type,
|
||||
aggregate_type='shipping_order_document_profile',
|
||||
aggregate_id=str(int(profile_id)),
|
||||
document_id=document_id,
|
||||
actor_type='admin',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
result='success',
|
||||
action=safe_action,
|
||||
sensitivity_level='sensitive',
|
||||
before=whitelist_before,
|
||||
after=whitelist_after,
|
||||
full_before=full_before,
|
||||
full_after=full_after,
|
||||
context_refs=context_refs or None,
|
||||
metadata=metadata or None,
|
||||
)
|
||||
|
||||
|
||||
def record_visual_binding_audit(
|
||||
*,
|
||||
profile_id: int,
|
||||
document_id: int | None,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
before: dict[str, Any] | None,
|
||||
after: dict[str, Any] | None,
|
||||
detail: dict[str, Any] | None = None,
|
||||
request_id: str | None = None,
|
||||
operation_id: str | None = None,
|
||||
raw_binding_before: dict[str, Any] | None = None,
|
||||
raw_binding_after: dict[str, Any] | None = None,
|
||||
profile_context: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
写入 XFA 视觉绑定审计事件(含 before/after bbox 摘要)。
|
||||
|
||||
核心逻辑:委托 profile_service._audit 写 Profile 时间线;再双写 append_shipping_audit_event
|
||||
(白名单 before/after + 加密 full 快照)。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 可选样本文档 ID。
|
||||
event_type: suggested|confirmed|rejected|updated。
|
||||
actor_id: 操作者 ID。
|
||||
before: 变更前 visual 摘要。
|
||||
after: 变更后 visual 摘要。
|
||||
detail: 附加非敏感 detail。
|
||||
request_id: HTTP request_id。
|
||||
operation_id: 幂等 operation_id。
|
||||
raw_binding_before: 变更前完整 binding(供 full_before)。
|
||||
raw_binding_after: 变更后完整 binding(供 full_after)。
|
||||
profile_context: Profile 上下文;省略时按 profile_id 加载。
|
||||
|
||||
Raises:
|
||||
ValidationError: event_type 未注册。
|
||||
"""
|
||||
safe_event = str(event_type or '').strip()
|
||||
if safe_event not in XFA_VISUAL_BINDING_AUDIT_EVENTS:
|
||||
raise ValidationError(
|
||||
'visual binding audit event_type is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
safe_detail = dict(detail or {})
|
||||
profile_service._audit(
|
||||
profile_id=int(profile_id),
|
||||
document_id=document_id,
|
||||
event_type=safe_event,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
detail={
|
||||
**safe_detail,
|
||||
'before_visual_binding': before,
|
||||
'after_visual_binding': after,
|
||||
},
|
||||
)
|
||||
|
||||
resolved_context = dict(profile_context or {})
|
||||
if not resolved_context:
|
||||
profile_row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
resolved_context = build_profile_audit_context(profile_row)
|
||||
|
||||
binding_id = str(safe_detail.get('binding_id') or (after or {}).get('binding_id') or (before or {}).get('binding_id') or '').strip() or None
|
||||
page_no_raw = safe_detail.get('page_no')
|
||||
if page_no_raw is None and isinstance(after, dict):
|
||||
page_no_raw = after.get('page_no')
|
||||
if page_no_raw is None and isinstance(before, dict):
|
||||
page_no_raw = before.get('page_no')
|
||||
page_no = int(page_no_raw) if page_no_raw is not None else None
|
||||
|
||||
_append_visual_binding_platform_audit_event(
|
||||
profile_id=int(profile_id),
|
||||
document_id=document_id,
|
||||
event_type=safe_event,
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
action=str(safe_detail.get('action') or '').strip() or None,
|
||||
binding_id=binding_id,
|
||||
page_no=page_no,
|
||||
before_summary=before,
|
||||
after_summary=after,
|
||||
raw_binding_before=raw_binding_before,
|
||||
raw_binding_after=raw_binding_after,
|
||||
profile_context=resolved_context,
|
||||
metadata_extra={
|
||||
key: safe_detail[key]
|
||||
for key in ('reason_code', 'candidate_count', 'normalized_bbox')
|
||||
if key in safe_detail
|
||||
} or None,
|
||||
)
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取当前模板版本;不存在时复用版本中心统一 not-found 契约。"""
|
||||
"""读取模板主体;审计查询仍须拒绝不存在的 Profile。"""
|
||||
row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if row is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
@@ -358,179 +20,93 @@ def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
|
||||
|
||||
def _parse_datetime(raw: str | None, *, is_end: bool) -> datetime | None:
|
||||
"""解析日期或 ISO 时间字符串;纯日期默认扩展到当天起止。"""
|
||||
"""解析治理列表的 ISO 日期筛选,日期结尾扩展至当天最后时刻。"""
|
||||
value = str(raw or '').strip()
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
'audit datetime filter is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
) from exc
|
||||
if 'T' not in value and ' ' not in value:
|
||||
raise ValidationError('Audit date filter is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID') from exc
|
||||
if len(value) == 10:
|
||||
return datetime.combine(parsed.date(), time.max if is_end else time.min)
|
||||
return parsed
|
||||
|
||||
|
||||
def _actor_payload(row: ShippingOrderDocumentProfileAudit, actor: User | None) -> dict[str, Any]:
|
||||
"""返回操作者展示摘要;用户缺失时降级为 unknown actor。"""
|
||||
username = str(getattr(actor, 'username', '') or '').strip() or None
|
||||
"""投影审计操作者,不暴露账号敏感字段。"""
|
||||
return {
|
||||
'id': int(row.actor_id) if row.actor_id else None,
|
||||
'username': username,
|
||||
'display_name': username or 'unknown_actor',
|
||||
'id': row.actor_id,
|
||||
'display_name': getattr(actor, 'display_name', None) or getattr(actor, 'username', None) or 'unknown_actor',
|
||||
'username': getattr(actor, 'username', None),
|
||||
}
|
||||
|
||||
|
||||
def _event_payload(row: ShippingOrderDocumentProfileAudit, actor: User | None) -> dict[str, Any]:
|
||||
"""序列化单条审计事件;detail_json 已由写侧保证为非敏感摘要(含 XFA checksum)。"""
|
||||
detail = dict(row.detail_json or {})
|
||||
"""将 Profile 审计行转换为分页 DTO。"""
|
||||
return {
|
||||
'id': int(row.id),
|
||||
'id': 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': detail,
|
||||
'definition_checksum': detail.get('definition_checksum'),
|
||||
'before_definition_checksum': detail.get('before_definition_checksum'),
|
||||
'document_id': row.document_id,
|
||||
'revision_no': row.revision_no,
|
||||
'request_id': row.request_id,
|
||||
'operation_id': row.operation_id,
|
||||
'detail': row.detail_json or {},
|
||||
'created_at': row.created_at.isoformat() if row.created_at else None,
|
||||
'actor': _actor_payload(row, actor),
|
||||
}
|
||||
|
||||
|
||||
def _write_view_audit_safely(
|
||||
*,
|
||||
profile_id: int,
|
||||
actor_id: int | None,
|
||||
request_id: str | None,
|
||||
event_type: str,
|
||||
detail: dict[str, Any],
|
||||
) -> None:
|
||||
"""为只读页面访问追加留痕;提交失败不阻断读取接口。"""
|
||||
def _write_view_audit_safely(*, profile_id: int, actor_id: int | None, request_id: str | None, filters: dict[str, Any]) -> None:
|
||||
"""记录列表浏览,但浏览审计失败不得影响管理员读取历史。"""
|
||||
try:
|
||||
profile_service._audit(
|
||||
profile_id=int(profile_id),
|
||||
event_type=event_type,
|
||||
profile_id=profile_id,
|
||||
event_type='version_audit_viewed',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
detail=detail,
|
||||
detail={'filters': filters},
|
||||
)
|
||||
db.session.commit()
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
_LOGGER.exception('order document profile audit view logging failed profile_id=%s event_type=%s', profile_id, event_type)
|
||||
|
||||
|
||||
def list_profile_audit_events(
|
||||
*,
|
||||
profile_id: int,
|
||||
actor_id: int | None,
|
||||
request_id: str | None,
|
||||
event_type: str | None = None,
|
||||
actor_query: str | None = None,
|
||||
request_filter: str | None = None,
|
||||
created_from: str | None = None,
|
||||
created_to: str | None = None,
|
||||
before_id: int | None = None,
|
||||
limit: int = 20,
|
||||
*, profile_id: int, actor_id: int | None, request_id: str | None,
|
||||
event_type: str | None = None, actor_query: str | None = None, request_filter: str | None = None,
|
||||
created_from: str | None = None, created_to: str | None = None, before_id: int | None = None,
|
||||
limit: int = 50,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
返回模板版本治理时间线,支持事件类型、操作者、日期和 request_id 过滤。
|
||||
|
||||
Args:
|
||||
profile_id: 模板版本主键。
|
||||
actor_id: 当前管理员主键,仅用于记录访问留痕。
|
||||
request_id: 当前 HTTP request_id,仅写入 view audit。
|
||||
event_type: 可选事件类型精确过滤。
|
||||
actor_query: 可选操作者过滤,支持 username 模糊匹配或 actor_id 精确匹配。
|
||||
request_filter: 可选请求链路过滤。
|
||||
created_from: ISO 日期/时间起点。
|
||||
created_to: ISO 日期/时间终点。
|
||||
before_id: 向后翻页游标;仅返回更早事件。
|
||||
limit: 单次页大小,范围由路由层约束。
|
||||
Returns:
|
||||
profile 摘要、过滤条件、倒序事件列表与下一页游标。
|
||||
"""
|
||||
profile = _profile(profile_id)
|
||||
safe_event_type = str(event_type or '').strip() or None
|
||||
safe_actor_query = str(actor_query or '').strip() or None
|
||||
safe_request_filter = str(request_filter or '').strip() or None
|
||||
created_from_dt = _parse_datetime(created_from, is_end=False)
|
||||
created_to_dt = _parse_datetime(created_to, is_end=True)
|
||||
|
||||
query = (
|
||||
db.session.query(ShippingOrderDocumentProfileAudit, User)
|
||||
.outerjoin(User, User.id == ShippingOrderDocumentProfileAudit.actor_id)
|
||||
.filter(ShippingOrderDocumentProfileAudit.profile_id == int(profile.id))
|
||||
)
|
||||
if safe_event_type:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.event_type == safe_event_type)
|
||||
if safe_request_filter:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.request_id == safe_request_filter)
|
||||
if created_from_dt is not None:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.created_at >= created_from_dt)
|
||||
if created_to_dt is not None:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.created_at <= created_to_dt)
|
||||
if before_id is not None:
|
||||
"""按游标返回模板治理审计;公共时间线仅含共同 Profile 事件。"""
|
||||
_profile(profile_id)
|
||||
safe_limit = max(1, min(int(limit), 100))
|
||||
query = ShippingOrderDocumentProfileAudit.query.filter_by(profile_id=int(profile_id))
|
||||
if event_type:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.event_type == str(event_type).strip())
|
||||
if request_filter:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.request_id == str(request_filter).strip())
|
||||
if before_id:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.id < int(before_id))
|
||||
if safe_actor_query:
|
||||
if safe_actor_query.isdigit():
|
||||
query = query.filter(
|
||||
or_(
|
||||
ShippingOrderDocumentProfileAudit.actor_id == int(safe_actor_query),
|
||||
User.username.ilike(f'%{safe_actor_query}%'),
|
||||
),
|
||||
)
|
||||
else:
|
||||
query = query.filter(
|
||||
or_(
|
||||
User.username.ilike(f'%{safe_actor_query}%'),
|
||||
cast(ShippingOrderDocumentProfileAudit.actor_id, String).ilike(f'%{safe_actor_query}%'),
|
||||
),
|
||||
)
|
||||
|
||||
rows = (
|
||||
query
|
||||
.order_by(ShippingOrderDocumentProfileAudit.id.desc())
|
||||
.limit(int(limit) + 1)
|
||||
.all()
|
||||
)
|
||||
has_more = len(rows) > int(limit)
|
||||
visible_rows = rows[:int(limit)]
|
||||
payload = {
|
||||
'profile': {
|
||||
'id': int(profile.id),
|
||||
'profile_code': profile.profile_code,
|
||||
'version': int(profile.version),
|
||||
'status': profile.status,
|
||||
},
|
||||
'filters': {
|
||||
'event_type': safe_event_type,
|
||||
'actor': safe_actor_query,
|
||||
'request_id': safe_request_filter,
|
||||
'created_from': created_from_dt.isoformat() if created_from_dt else None,
|
||||
'created_to': created_to_dt.isoformat() if created_to_dt else None,
|
||||
},
|
||||
'items': [_event_payload(audit, actor) for audit, actor in visible_rows],
|
||||
'page': {
|
||||
'limit': int(limit),
|
||||
'before_id': int(before_id) if before_id is not None else None,
|
||||
'next_before_id': int(visible_rows[-1][0].id) if has_more and visible_rows else None,
|
||||
'has_more': has_more,
|
||||
},
|
||||
}
|
||||
start, end = _parse_datetime(created_from, is_end=False), _parse_datetime(created_to, is_end=True)
|
||||
if start:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.created_at >= start)
|
||||
if end:
|
||||
query = query.filter(ShippingOrderDocumentProfileAudit.created_at <= end)
|
||||
if actor_query:
|
||||
term = f"%{str(actor_query).strip()}%"
|
||||
query = query.join(User, User.id == ShippingOrderDocumentProfileAudit.actor_id).filter(
|
||||
(User.username.ilike(term)) | (User.display_name.ilike(term))
|
||||
)
|
||||
rows = query.order_by(ShippingOrderDocumentProfileAudit.id.desc()).limit(safe_limit + 1).all()
|
||||
has_more = len(rows) > safe_limit
|
||||
rows = rows[:safe_limit]
|
||||
actors = {row.actor_id: db.session.get(User, row.actor_id) for row in rows if row.actor_id}
|
||||
_write_view_audit_safely(
|
||||
profile_id=int(profile.id),
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
event_type='version_audit_viewed',
|
||||
detail={
|
||||
'filters': payload['filters'],
|
||||
'result_count': len(payload['items']),
|
||||
},
|
||||
profile_id=int(profile_id), actor_id=actor_id, request_id=request_id,
|
||||
filters={'event_type': event_type, 'actor': actor_query, 'request_id': request_filter, 'created_from': created_from, 'created_to': created_to},
|
||||
)
|
||||
return payload
|
||||
return {
|
||||
'items': [_event_payload(row, actors.get(row.actor_id)) for row in rows],
|
||||
'page': {'has_more': has_more, 'next_before_id': rows[-1].id if has_more and rows else None},
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_creation_service.py
|
||||
|
||||
用途:完成订单模板三步创建向导的最终原子提交(coordinate 或 xfa_dataset)。
|
||||
用途:完成订单模板三步创建向导的最终原子提交。
|
||||
依赖:Profile 保存、样本布局/XFA 结构分析、Revision、EditLease 与 Profile 审计模型。
|
||||
逻辑:前两步只在浏览器保存临时状态;本服务在最后一步一次创建草稿、首份建模/训练样本绑定、
|
||||
Revision 审计和编辑租约。样本能力决定模板模式:XFA 不要求 table_id,坐标模式仍校验主表。
|
||||
Revision 审计和编辑租约。所有有明细的模板都先冻结统一视觉 main_table_id;末端才选择正式值源 adapter。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -22,9 +22,9 @@ from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileEditLease,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingXfaStructureAnalysis,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_runtime_value_adapter
|
||||
|
||||
|
||||
def _browser_session_id(value: Any) -> str:
|
||||
@@ -60,28 +60,14 @@ def _initial_coordinate_definition(main_table_id: str) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _frozen_ready_xfa_analysis(document: ShippingOrderDocument) -> ShippingXfaStructureAnalysis | None:
|
||||
"""
|
||||
读取文档当前 Layout 冻结的 ready 态 XFA 结构分析。
|
||||
|
||||
核心逻辑:委托 resolve_frozen_xfa_structure_analysis;缺失时返回 None(由调用方 fail-closed)。
|
||||
|
||||
Args:
|
||||
document: ShippingOrderDocument。
|
||||
|
||||
Returns:
|
||||
ready 分析记录;冻结身份不可用则 None。
|
||||
"""
|
||||
from app.core.errors import ValidationError as _ValidationError
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import (
|
||||
resolve_frozen_xfa_structure_analysis,
|
||||
)
|
||||
|
||||
try:
|
||||
_layout, analysis, _capability = resolve_frozen_xfa_structure_analysis(document)
|
||||
except _ValidationError:
|
||||
return None
|
||||
return analysis
|
||||
def _build_coordinate_initial_definition(
|
||||
_document: ShippingOrderDocument,
|
||||
_analysis: Any | None,
|
||||
main_table_id: str,
|
||||
_data: dict[str, Any],
|
||||
) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""构造 coordinate/OCR adapter 的空白末端映射定义。"""
|
||||
return _initial_coordinate_definition(main_table_id), {'main_table_id': main_table_id}
|
||||
|
||||
|
||||
def _new_profile_code() -> str:
|
||||
@@ -93,12 +79,11 @@ 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。
|
||||
核心逻辑:按样本能力选择 value adapter,但所有模板先校验统一视觉 main_table_id;
|
||||
XFA 的权威集合在编辑器配置字段 value_binding 时再选择,发布门禁仍 fail-closed。
|
||||
|
||||
Args:
|
||||
data: 模板名称、已解析样本文档、Schema、浏览器会话;XFA 另含权威/镜像集合 path_id;
|
||||
坐标另含 main_table_id。系统编码由服务端生成。
|
||||
data: 模板名称、已解析样本文档、Schema、浏览器会话和 main_table_id;系统编码由服务端生成。
|
||||
actor_id: 当前管理员主键。
|
||||
|
||||
Returns:
|
||||
@@ -118,63 +103,41 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND',
|
||||
)
|
||||
layout = profile_service._document_layout(document)
|
||||
xfa_ready = profile_service._layout_is_xfa_analysis_ready(layout)
|
||||
analysis = _frozen_ready_xfa_analysis(document) if xfa_ready else None
|
||||
if xfa_ready and analysis is None:
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import (
|
||||
resolve_frozen_xfa_structure_analysis,
|
||||
)
|
||||
|
||||
# 再走一次以抛出精确 MISSING / IDENTITY_MISMATCH / STALE 错误码
|
||||
resolve_frozen_xfa_structure_analysis(document)
|
||||
|
||||
# [STEP 1] 按样本能力分支:XFA 不要求 table_id;坐标仍校验主表。
|
||||
# [STEP 1] 所有模板先冻结统一视觉主表;末端值源随后写入自身 contract。
|
||||
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,
|
||||
table_id = str(data.get('main_table_id') or '').strip()
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
# 新建草稿必须有可验证的视觉表格;历史空 Layout 只能作为既有数据只读/迁移,
|
||||
# 不得再生成会绕过共享画布的 XFA 草稿。
|
||||
if not tables:
|
||||
raise ValidationError(
|
||||
'A parsed visual main table is required for the unified template path',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
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}
|
||||
if not table_id:
|
||||
raise ValidationError(
|
||||
'main_table_id is required for the unified visual template path',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
if table_id and 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',
|
||||
)
|
||||
sample_table_id = table_id or None
|
||||
# [STEP 2] 值源选择是末端适配边界;共同向导不识别 PDF 类型或 datasets 结构。
|
||||
adapter = get_runtime_value_adapter(layout=layout, selected_profile=None)
|
||||
adapter_context = adapter.prepare_context(document)
|
||||
definition, wizard_detail_extra = adapter.initial_definition(
|
||||
document=document,
|
||||
analysis=adapter_context.get('analysis'),
|
||||
main_table_id=table_id,
|
||||
data=data,
|
||||
)
|
||||
template_mode = adapter.legacy_template_mode
|
||||
change_source = 'wizard_created'
|
||||
wizard_event = 'wizard_created'
|
||||
|
||||
for _attempt in range(3):
|
||||
profile_code = _new_profile_code()
|
||||
@@ -195,18 +158,23 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
'definition': definition,
|
||||
'change_note': 'Created from template wizard',
|
||||
'template_mode': template_mode,
|
||||
'sample_document_id': document.id if template_mode == 'xfa_dataset' else None,
|
||||
'sample_document_id': document.id,
|
||||
},
|
||||
actor_id=actor_id, browser_session_id=session_id, operation_id=operation_id,
|
||||
change_source=change_source, commit=False,
|
||||
)
|
||||
profile_id = int(saved['id'])
|
||||
# 首份样本既承载画布/映射,也作为训练证据;盲测仍必须另选独立文档。
|
||||
# 首份样本既承载画布/映射,也作为训练证据;annotation 已由共同 save_draft
|
||||
# 路径创建并冻结主表,此处只补齐尚未存在的共同样本角色。
|
||||
for sample_role in ('annotation', 'training'):
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile_id, document_id=document.id, table_id=sample_table_id,
|
||||
sample_role=sample_role, created_by_id=actor_id,
|
||||
))
|
||||
sample = ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=profile_id, document_id=document.id, sample_role=sample_role,
|
||||
).first()
|
||||
if sample is None:
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
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'])
|
||||
@@ -216,20 +184,9 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
|
||||
detail={
|
||||
'schema_version_id': schema_version_id, 'profile_code': profile_code,
|
||||
'template_mode': template_mode, 'sample_roles': ['annotation', 'training'],
|
||||
**wizard_detail_extra,
|
||||
'adapter_evidence': 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(
|
||||
|
||||
+948
-44
File diff suppressed because it is too large.
Load diff
@@ -29,105 +29,14 @@ from app.models import (
|
||||
from app.services.shipping_notice.document_layout.lifecycle import CURRENT_LAYOUT_STATUSES, canonical_layout_payload
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
|
||||
from app.services.shipping_notice.preview_grant_store import preview_grant_store
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
|
||||
|
||||
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': True,
|
||||
'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()
|
||||
@@ -156,17 +65,8 @@ def _audit(
|
||||
|
||||
|
||||
def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) -> bool:
|
||||
"""旧未冻结样本不得伪装成可审计只读画布;XFA 以 structure identity 快照为准。"""
|
||||
"""所有模板必须先具备共同视觉 Layout/主表冻结证据。"""
|
||||
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,
|
||||
@@ -176,56 +76,12 @@ def _sample_frozen_evidence_ready(sample: ShippingOrderDocumentProfileSample) ->
|
||||
sample.parser_name,
|
||||
sample.evidence_frozen_at,
|
||||
)
|
||||
return all(required)
|
||||
|
||||
|
||||
def _is_xfa_frozen_sample(sample: ShippingOrderDocumentProfileSample) -> bool:
|
||||
"""判断样本是否以 XFA 结构身份冻结(非 coordinate 表格)。"""
|
||||
identity = sample.table_identity_snapshot if isinstance(sample.table_identity_snapshot, dict) else {}
|
||||
return str(identity.get('kind') or '') == 'xfa_structure'
|
||||
|
||||
|
||||
def _validate_frozen_xfa_layout_identity(
|
||||
sample: ShippingOrderDocumentProfileSample,
|
||||
layout_version: ShippingDocumentLayoutVersion,
|
||||
) -> None:
|
||||
"""
|
||||
校验 XFA 冻结样本的 layout/结构身份,不依赖 table_regions。
|
||||
|
||||
核心逻辑:比对 datasets/structure fingerprint 与 structure_analysis_id 快照。
|
||||
"""
|
||||
identity = dict(sample.table_identity_snapshot or {})
|
||||
expected_analysis_id = identity.get('structure_analysis_id')
|
||||
capability = (
|
||||
layout_version.payload_json.get('xfa_capability')
|
||||
if isinstance(layout_version.payload_json, dict)
|
||||
else {}
|
||||
)
|
||||
if not isinstance(capability, dict):
|
||||
capability = (
|
||||
layout_version.payload_json.get('capability')
|
||||
if isinstance(layout_version.payload_json, dict)
|
||||
else {}
|
||||
)
|
||||
if expected_analysis_id is not None and capability.get('structure_analysis_id') not in (None, expected_analysis_id):
|
||||
raise ValidationError(
|
||||
'Frozen XFA structure analysis no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
expected_fingerprint = str(identity.get('dataset_structure_fingerprint') or '').strip().lower()
|
||||
actual_fingerprint = str(capability.get('dataset_structure_fingerprint') or '').strip().lower()
|
||||
if expected_fingerprint and actual_fingerprint and expected_fingerprint != actual_fingerprint:
|
||||
raise ValidationError(
|
||||
'Frozen XFA dataset fingerprint no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
expected_template = str(identity.get('template_packet_checksum') or '').strip().lower()
|
||||
actual_template = str(capability.get('template_packet_checksum') or '').strip().lower()
|
||||
if expected_template and actual_template and expected_template != actual_template:
|
||||
raise ValidationError(
|
||||
'Frozen XFA template checksum no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
if not all(required):
|
||||
return False
|
||||
adapter_evidence = identity.get('value_adapter_evidence') if isinstance(identity.get('value_adapter_evidence'), dict) else None
|
||||
if adapter_evidence is None:
|
||||
return True
|
||||
return get_value_adapter(str(adapter_evidence.get('adapter') or '')).frozen_evidence_ready(adapter_evidence)
|
||||
|
||||
|
||||
def _frozen_table_identity_ready(
|
||||
@@ -323,21 +179,27 @@ def _frozen_sample_context(
|
||||
'Frozen layout source hash no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
if _is_xfa_frozen_sample(sample):
|
||||
# [STEP 1] XFA 冻结样本以 structure identity 为准,不用 coordinate layout checksum。
|
||||
_validate_frozen_xfa_layout_identity(sample, layout_version)
|
||||
else:
|
||||
actual_checksum, _ = canonical_layout_payload(layout_version.payload_json)
|
||||
expected_checksum = str(sample.layout_payload_checksum or '').strip().lower()
|
||||
if (
|
||||
actual_checksum != expected_checksum
|
||||
or str(layout_version.payload_checksum or '').strip().lower() != expected_checksum
|
||||
):
|
||||
raise ValidationError(
|
||||
'Frozen layout checksum no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
_frozen_table_identity_ready(sample, layout_payload=layout_version.payload_json)
|
||||
# [STEP 1] 所有模板先校验同一 Layout checksum 与视觉 main_table_id;
|
||||
# 末端值源只能在下方作为附加身份,绝不能替代或绕过共同 PDF 画布证据。
|
||||
actual_checksum, _ = canonical_layout_payload(layout_version.payload_json)
|
||||
expected_checksum = str(sample.layout_payload_checksum or '').strip().lower()
|
||||
if (
|
||||
actual_checksum != expected_checksum
|
||||
or str(layout_version.payload_checksum or '').strip().lower() != expected_checksum
|
||||
):
|
||||
raise ValidationError(
|
||||
'Frozen layout checksum no longer matches the published evidence',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
_frozen_table_identity_ready(sample, layout_payload=layout_version.payload_json)
|
||||
adapter_evidence = (
|
||||
sample.table_identity_snapshot.get('value_adapter_evidence')
|
||||
if isinstance(sample.table_identity_snapshot, dict) else None
|
||||
)
|
||||
if isinstance(adapter_evidence, dict):
|
||||
get_value_adapter(str(adapter_evidence.get('adapter') or '')).validate_frozen_layout_identity(
|
||||
evidence=adapter_evidence, layout_version=layout_version,
|
||||
)
|
||||
if str(layout_version.contract_version or '').strip() != str(sample.layout_contract_version or '').strip():
|
||||
raise ValidationError(
|
||||
'Frozen layout contract version no longer matches the published evidence',
|
||||
@@ -432,7 +294,9 @@ def authorize_frozen_sample_preview_pages(
|
||||
'page_count': len(pages),
|
||||
'ttl_seconds': PREVIEW_GRANT_TTL_SECONDS,
|
||||
'mode': 'frozen_sample',
|
||||
'template_mode': 'xfa_dataset' if _is_xfa_profile(profile) else 'coordinate',
|
||||
'value_adapter': profile_service._publish_value_adapter(
|
||||
profile_service._profile_template_mode(profile),
|
||||
).key,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
@@ -472,8 +336,13 @@ 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,
|
||||
force_ocr: bool = False,
|
||||
) -> tuple[dict[str, Any] | None, list[dict[str, Any]], str | None]:
|
||||
"""从已校验哈希的冻结 PDF 临时恢复单页坐标,仅供历史版本只读诊断。"""
|
||||
"""从已校验哈希的冻结 PDF 临时恢复单页坐标,仅供历史版本只读诊断。
|
||||
|
||||
``force_ocr`` 仅用于 hybrid XFA 的单个空视觉框:原生 glyph 可能只含标签,
|
||||
其填写值仍在 PDFium 外观层。结果不写回冻结 Layout,也不作为正式值源。
|
||||
"""
|
||||
if not str(getattr(document, 'filename', '') or '').lower().endswith('.pdf'):
|
||||
return None, [], None
|
||||
try:
|
||||
@@ -490,8 +359,9 @@ def _recover_frozen_page_coordinates(
|
||||
)
|
||||
glyphs = [item.model_dump(mode='json') for item in getattr(native_page, 'characters', []) or []]
|
||||
source = 'pdf_coordinate'
|
||||
if not glyphs:
|
||||
# OCR 回退需要页面图;原生文字快速路径不额外渲染图片。
|
||||
if force_ocr or not glyphs:
|
||||
# OCR 回退需要页面图;仅字段级空值强制读取外观层,避免整页部分 glyph
|
||||
# 将 XFA 填写值误判为已可用。
|
||||
rendered_page = next(
|
||||
item for item in extract_native_pdf_pages(read_asset_bytes(asset))
|
||||
if int(item.page_no) == int(page_no)
|
||||
@@ -667,7 +537,8 @@ def frozen_sample_region_diagnostics(
|
||||
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)):
|
||||
diagnostic_regions = _diagnostic_regions(profile, page_no=int(page_no))
|
||||
for item in diagnostic_regions:
|
||||
recognized = read_coordinate_region_text(glyphs=glyphs, page=page, region=item['region'])
|
||||
configured = item.get('configured_value')
|
||||
matches = None
|
||||
@@ -677,6 +548,37 @@ def frozen_sample_region_diagnostics(
|
||||
'region_id': item['region_id'], 'kind': item['kind'], 'label': item['label'],
|
||||
'recognized_value': recognized, 'configured_value': configured, 'matches_configured': matches,
|
||||
})
|
||||
# [STEP 2] 页面原生字符不为空不等于每个受控视觉框都可取值。只对当前为空的
|
||||
# value 区域临时 OCR;标签、已有值和任何 datasets 正式值均不受影响。
|
||||
empty_value_indexes = [
|
||||
index for index, item in enumerate(items)
|
||||
if not str(item.get('recognized_value') or '').strip()
|
||||
and str(item.get('kind') or '') not in {'document_anchor_label'}
|
||||
]
|
||||
if empty_value_indexes:
|
||||
ocr_page, ocr_glyphs, ocr_source = _recover_frozen_page_coordinates(
|
||||
document=document,
|
||||
asset=asset,
|
||||
payload=payload,
|
||||
page_no=int(page_no),
|
||||
force_ocr=True,
|
||||
)
|
||||
if isinstance(ocr_page, dict) and ocr_glyphs:
|
||||
for index in empty_value_indexes:
|
||||
recognized = read_coordinate_region_text(
|
||||
glyphs=ocr_glyphs,
|
||||
page=ocr_page,
|
||||
region=diagnostic_regions[index]['region'],
|
||||
)
|
||||
if not recognized:
|
||||
continue
|
||||
items[index]['recognized_value'] = recognized
|
||||
configured = items[index].get('configured_value')
|
||||
items[index]['matches_configured'] = (
|
||||
''.join(str(configured).casefold().split()) in ''.join(recognized.casefold().split())
|
||||
if configured is not None else None
|
||||
)
|
||||
coordinate_source = ocr_source or coordinate_source
|
||||
_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,
|
||||
|
||||
+47
-511
@@ -28,19 +28,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.order_profile_value_adapter import get_value_adapter
|
||||
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 _profile_value_adapter(profile: ShippingOrderDocumentProfile) -> str:
|
||||
"""从 Profile 共享 adapter 注册表返回末端值源,发布编排不判断模板模式。"""
|
||||
return get_value_adapter(profile.definition_json).key
|
||||
|
||||
|
||||
def _adapter_publish_checks(
|
||||
profile: ShippingOrderDocumentProfile,
|
||||
validation: ShippingOrderDocumentProfileValidationRun | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""返回值源 adapter 的发布阻断项,供公共报告编排统一汇总。
|
||||
|
||||
核心逻辑:发布生命周期不再在 create_report 内按模板模式分叉;coordinate
|
||||
当前无额外值源门禁,XFA 仍保留 datasets、视觉 binding 与对账的 fail-closed 检查。
|
||||
|
||||
Args:
|
||||
profile: 当前草稿模板。
|
||||
validation: 与当前 Revision 对应的 current_sample 运行,可为空。
|
||||
|
||||
Returns:
|
||||
可直接写入 blocking_items 的稳定阻断项列表。
|
||||
"""
|
||||
return get_value_adapter(profile.definition_json).publish_checks(profile, validation=validation)
|
||||
|
||||
|
||||
def _append_publish_check_ledger_event(
|
||||
@@ -78,8 +92,9 @@ def _current_revision(profile: ShippingOrderDocumentProfile) -> ShippingOrderDoc
|
||||
|
||||
|
||||
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'
|
||||
"""派生统一 Profile 身份签名状态;adapter 细节只附加在 identity_details。"""
|
||||
value_adapter = get_value_adapter(profile.definition_json)
|
||||
expected_run_type = '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))
|
||||
@@ -94,45 +109,29 @@ def _signature_status(profile: ShippingOrderDocumentProfile, revision: ShippingO
|
||||
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,
|
||||
'signature_kind': 'profile_identity_signature',
|
||||
'adapter_run_type': 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'),
|
||||
})
|
||||
payload['identity_details'] = value_adapter.identity_summary(summary, snapshot)
|
||||
return payload
|
||||
|
||||
|
||||
def _find_last_profile_editor_id(profile_id: int) -> int | None:
|
||||
"""
|
||||
查找最近一次编辑 Profile 映射/视觉绑定/拆分规则的管理员 ID。
|
||||
查找最近一次编辑 Profile 映射/拆分规则的管理员 ID。
|
||||
|
||||
核心逻辑:优先审计事件(含视觉确认/驳回/更新);回退至最新 DraftRevision.created_by_id。
|
||||
核心逻辑:优先审计映射事件;回退至最新 DraftRevision.created_by_id。
|
||||
"""
|
||||
editor_events = (
|
||||
'draft_saved',
|
||||
'xfa_mapping_saved',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_segment_mapping_updated',
|
||||
'xfa_profile_draft_saved',
|
||||
'xfa_visual_binding_confirmed',
|
||||
'xfa_visual_binding_rejected',
|
||||
'xfa_visual_binding_updated',
|
||||
'xfa_visual_binding_suggested',
|
||||
)
|
||||
audit = (
|
||||
db.session.query(ShippingOrderDocumentProfileAudit)
|
||||
@@ -156,460 +155,10 @@ def _find_last_profile_editor_id(profile_id: int) -> int | None:
|
||||
return None
|
||||
|
||||
|
||||
def _blocking_xfa_definition(
|
||||
profile: ShippingOrderDocumentProfile,
|
||||
validation: ShippingOrderDocumentProfileValidationRun | None,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
汇总 XFA 发布阻断项:缺失路径、集合歧义、对账失败、视觉绑定与验证指标。
|
||||
|
||||
核心逻辑:检查 source_contract / 映射覆盖 / 统一 bindings 视觉确认 /
|
||||
current_sample 摘要中的对账失败码与 visual/evidence 阈值(要求 100%)。
|
||||
"""
|
||||
blocking: list[dict[str, Any]] = []
|
||||
definition = dict(profile.definition_json or {})
|
||||
# 硬冻结(2026-08-07):flatten 未就绪不再阻断人工模板发布。
|
||||
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)]
|
||||
bindings_list = [item for item in (definition.get('bindings') or []) if isinstance(item, dict)]
|
||||
has_legacy_mappings = bool(header_mappings or line_fields)
|
||||
has_bindings = bool(bindings_list)
|
||||
|
||||
if has_bindings and has_legacy_mappings:
|
||||
blocking.append({
|
||||
'key': 'xfa_dual_binding_source',
|
||||
'message': 'XFA profile must not mix unified bindings with legacy header_mappings or line_mapping.fields.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_dual_binding_source',
|
||||
})
|
||||
|
||||
if has_bindings:
|
||||
if any(
|
||||
not (item.get('value_binding') or {}).get('data_path') or not item.get('field_id')
|
||||
for item in bindings_list
|
||||
if isinstance(item.get('value_binding'), dict)
|
||||
):
|
||||
blocking.append({
|
||||
'key': 'xfa_mapping_path_missing',
|
||||
'message': 'Every XFA binding must bind a known data path.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
})
|
||||
elif has_legacy_mappings and 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 (bindings_list if has_bindings else 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('value_binding') or {}).get('path_id') or '')
|
||||
for item in bindings_list
|
||||
if has_bindings and isinstance(item.get('value_binding'), dict) and (item.get('value_binding') or {}).get('path_id')
|
||||
} if has_bindings else {
|
||||
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],
|
||||
})
|
||||
|
||||
# [STEP] 统一视觉绑定发布门禁:XFA 须 bindings-only 且视觉已确认。
|
||||
blocking.extend(_blocking_xfa_visual_bindings(
|
||||
definition=definition,
|
||||
schema_field_ids=set(schema_fields.keys()),
|
||||
))
|
||||
|
||||
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],
|
||||
})
|
||||
# 指标阈值:存在时视觉/证据须 100%。
|
||||
blocking.extend(_blocking_xfa_validation_metrics(summary))
|
||||
return blocking
|
||||
|
||||
|
||||
def _resolve_xfa_preview_publish_evidence(
|
||||
definition: dict[str, Any],
|
||||
bindings_list: list[Any],
|
||||
) -> tuple[str | None, str | None]:
|
||||
"""
|
||||
从 definition.xfa_preview 或已确认 visual_binding 共识解析发布用合成预览证据。
|
||||
|
||||
核心逻辑:优先读 definition.xfa_preview;否则要求每个 confirmed binding 携带相同
|
||||
非空 preview_render_checksum,并据此推断 preview_status=ready。
|
||||
|
||||
Args:
|
||||
definition: XFA definition JSON。
|
||||
bindings_list: definition.bindings 列表。
|
||||
|
||||
Returns:
|
||||
(preview_status, preview_render_checksum);证据不足时 checksum 为 None。
|
||||
"""
|
||||
preview_meta = definition.get('xfa_preview') if isinstance(definition.get('xfa_preview'), dict) else {}
|
||||
status = str(preview_meta.get('status') or '').strip().lower() or None
|
||||
checksum = str(preview_meta.get('preview_render_checksum') or '').strip() or None
|
||||
|
||||
confirmed_checksums: set[str] = set()
|
||||
confirmed_missing = False
|
||||
for raw in bindings_list:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
visual = raw.get('visual_binding') if isinstance(raw.get('visual_binding'), dict) else {}
|
||||
if str(visual.get('status') or '') != 'confirmed':
|
||||
continue
|
||||
item_checksum = str(visual.get('preview_render_checksum') or '').strip()
|
||||
if not item_checksum:
|
||||
confirmed_missing = True
|
||||
continue
|
||||
confirmed_checksums.add(item_checksum)
|
||||
|
||||
if not checksum:
|
||||
if confirmed_missing or not confirmed_checksums:
|
||||
return status, None
|
||||
if len(confirmed_checksums) != 1:
|
||||
return status, None
|
||||
checksum = next(iter(confirmed_checksums))
|
||||
if not status:
|
||||
status = 'ready'
|
||||
elif confirmed_checksums and (checksum not in confirmed_checksums or confirmed_missing):
|
||||
# 已确认绑定缺少或与 definition 摘要不一致 → 视为缺证据
|
||||
return status, None
|
||||
elif not status and checksum:
|
||||
status = 'ready'
|
||||
return status, checksum
|
||||
|
||||
|
||||
def _blocking_xfa_visual_bindings(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
schema_field_ids: set[str],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
校验统一绑定是否满足发布门禁(原生 PDF 画布 + 字段级混合数据源)。
|
||||
|
||||
核心逻辑:XFA 无 bindings 一律阻断;bindings 与 legacy mappings 共存 →
|
||||
xfa_dual_binding_source;正式字段须 is_formal_binding_publishable
|
||||
(datasets 视觉可选;坐标/OCR 须 confirmed);未处理跨源 OCR mismatch 必须为 0。
|
||||
不再要求 synthetic preview ready / renderer_version / preview checksum。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XfaUnifiedFieldBinding,
|
||||
is_formal_binding_publishable,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_validation import (
|
||||
collect_formal_schema_field_ids,
|
||||
compute_visual_coverage_rate,
|
||||
)
|
||||
|
||||
blocking: list[dict[str, Any]] = []
|
||||
bindings_raw = definition.get('bindings')
|
||||
bindings_list = bindings_raw if isinstance(bindings_raw, list) else []
|
||||
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)]
|
||||
has_legacy_mappings = bool(header_mappings or line_fields)
|
||||
has_xfa_dataset = isinstance(definition.get('source_contract'), dict) and bool(
|
||||
(definition.get('source_contract') or {}).get('dataset_structure_fingerprint')
|
||||
)
|
||||
|
||||
if bindings_list and has_legacy_mappings:
|
||||
blocking.append({
|
||||
'key': 'xfa_dual_binding_source',
|
||||
'message': 'XFA profile must not mix unified bindings with legacy header_mappings or line_mapping.fields.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_dual_binding_source',
|
||||
})
|
||||
return blocking
|
||||
|
||||
if has_xfa_dataset and not bindings_list:
|
||||
blocking.append({
|
||||
'key': 'xfa_visual_bindings_required',
|
||||
'message': 'Unified field bindings are required before publishing an XFA profile.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_visual_bindings_required',
|
||||
})
|
||||
return blocking
|
||||
|
||||
if not bindings_list:
|
||||
return blocking
|
||||
|
||||
formal_ids = collect_formal_schema_field_ids(
|
||||
definition,
|
||||
schema_field_ids=schema_field_ids or None,
|
||||
)
|
||||
publishable_by_field: dict[str, bool] = {}
|
||||
for raw in bindings_list:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
try:
|
||||
binding = XfaUnifiedFieldBinding.model_validate(raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
field_id = str(binding.field_id)
|
||||
publishable_by_field[field_id] = (
|
||||
publishable_by_field.get(field_id, False) or is_formal_binding_publishable(binding)
|
||||
)
|
||||
incomplete = sorted(
|
||||
field_id for field_id in formal_ids if not publishable_by_field.get(field_id)
|
||||
)
|
||||
if incomplete:
|
||||
blocking.append({
|
||||
'key': 'xfa_visual_binding_incomplete',
|
||||
'message': (
|
||||
'Every formal Schema-mapped field must have a publishable binding '
|
||||
'(datasets path, or confirmed visual for coordinate/OCR).'
|
||||
),
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_visual_binding_incomplete',
|
||||
'field_ids': incomplete[:20],
|
||||
})
|
||||
coverage = compute_visual_coverage_rate(definition, schema_field_ids=schema_field_ids or None)
|
||||
if coverage < 1.0 and 'xfa_visual_binding_incomplete' not in {item.get('key') for item in blocking}:
|
||||
blocking.append({
|
||||
'key': 'xfa_visual_coverage_insufficient',
|
||||
'message': 'Formal field publishable coverage must be 100% before publish.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_visual_coverage_insufficient',
|
||||
'visual_coverage_rate': coverage,
|
||||
})
|
||||
|
||||
# [STEP] 跨源 OCR mismatch 清零(不再要求 synthetic ready / checksum / renderer)
|
||||
if has_xfa_dataset or str(definition.get('template_mode') or '') == 'xfa_dataset':
|
||||
mismatch_blocking = _blocking_xfa_unresolved_ocr_mismatch(definition)
|
||||
existing_keys = {item.get('key') for item in blocking}
|
||||
for item in mismatch_blocking:
|
||||
if item.get('key') in existing_keys:
|
||||
continue
|
||||
blocking.append(item)
|
||||
existing_keys.add(item.get('key'))
|
||||
return blocking
|
||||
|
||||
|
||||
def _blocking_xfa_unresolved_ocr_mismatch(definition: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
发布前要求未处理跨源 OCR/datasets mismatch 为 0。
|
||||
|
||||
核心逻辑:读取 definition.xfa_ocr_automark / xfa_preview 中的
|
||||
unresolved_ocr_mismatch_count;缺失视为 0。
|
||||
|
||||
Args:
|
||||
definition: XFA definition。
|
||||
|
||||
Returns:
|
||||
阻断项列表(至多一项)。
|
||||
"""
|
||||
preview_meta = definition.get('xfa_preview') if isinstance(definition.get('xfa_preview'), dict) else {}
|
||||
automark_meta = (
|
||||
definition.get('xfa_ocr_automark')
|
||||
if isinstance(definition.get('xfa_ocr_automark'), dict)
|
||||
else {}
|
||||
)
|
||||
unresolved = preview_meta.get('unresolved_ocr_mismatch_count')
|
||||
if unresolved is None:
|
||||
unresolved = automark_meta.get('unresolved_ocr_mismatch_count', 0)
|
||||
try:
|
||||
unresolved_count = int(unresolved or 0)
|
||||
except (TypeError, ValueError):
|
||||
unresolved_count = 0
|
||||
if unresolved_count <= 0:
|
||||
return []
|
||||
return [{
|
||||
'key': 'xfa_ocr_unresolved_mismatch',
|
||||
'message': 'Unresolved OCR/datasets mismatches must be cleared before publish.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_OCR_MISMATCH',
|
||||
'reason_code': 'xfa_ocr_unresolved_mismatch',
|
||||
'unresolved_ocr_mismatch_count': unresolved_count,
|
||||
}]
|
||||
|
||||
def _blocking_xfa_validation_metrics(summary: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
当 current-sample 摘要含统一指标时,要求视觉/证据覆盖率均为 100%。
|
||||
|
||||
Args:
|
||||
summary: validation.run.summary_json。
|
||||
|
||||
Returns:
|
||||
阻断项列表。
|
||||
"""
|
||||
blocking: list[dict[str, Any]] = []
|
||||
has_metrics = any(
|
||||
key in summary
|
||||
for key in ('visual_coverage_rate', 'evidence_retention_rate', 'mirror_consistency_rate')
|
||||
)
|
||||
if not has_metrics:
|
||||
return blocking
|
||||
visual = summary.get('visual_coverage_rate')
|
||||
if visual is not None and float(visual) < 1.0:
|
||||
blocking.append({
|
||||
'key': 'xfa_visual_coverage_insufficient',
|
||||
'message': 'Visual coverage rate must be 100% on the current sample.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_visual_coverage_insufficient',
|
||||
'visual_coverage_rate': float(visual),
|
||||
})
|
||||
evidence = summary.get('evidence_retention_rate')
|
||||
if evidence is not None and float(evidence) < 1.0:
|
||||
blocking.append({
|
||||
'key': 'xfa_evidence_retention_insufficient',
|
||||
'message': 'evidence_only retention rate must be 100% on the current sample.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_evidence_retention_insufficient',
|
||||
'evidence_retention_rate': float(evidence),
|
||||
})
|
||||
mirror = summary.get('mirror_consistency_rate')
|
||||
if mirror is not None and float(mirror) < 1.0:
|
||||
blocking.append({
|
||||
'key': 'xfa_mirror_consistency_insufficient',
|
||||
'message': 'Mirror consistency rate must be 100% on the current sample.',
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'reason_code': 'xfa_mirror_consistency_insufficient',
|
||||
'mirror_consistency_rate': float(mirror),
|
||||
})
|
||||
return blocking
|
||||
|
||||
|
||||
def _overlap_summary_from_run(run: ShippingOrderDocumentProfileValidationRun | None) -> dict[str, Any] | None:
|
||||
"""从 cross_template_overlap 运行提取唯一性摘要与冲突卡片。"""
|
||||
def _overlap_summary_from_run(
|
||||
run: ShippingOrderDocumentProfileValidationRun | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""从已冻结的跨模板重叠验证运行提取公共发布摘要。"""
|
||||
if run is None:
|
||||
return None
|
||||
snapshot = dict(run.result_snapshot_json or {})
|
||||
@@ -678,12 +227,8 @@ def _payload(row: ShippingOrderDocumentProfilePublishCheckReport, profile: Shipp
|
||||
'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,
|
||||
'profile_identity_signature_status': signature_status,
|
||||
'profile_identity_signature_summary': dict(signature_run.summary_json or {}) if signature_run is not None 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,
|
||||
@@ -800,7 +345,7 @@ def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None
|
||||
"""
|
||||
生成冻结当前草稿、签名引用与重叠验证的发布检查报告;阻断项只可修复不能确认绕过。
|
||||
|
||||
核心逻辑:校验 current_sample → 解析/自动生成 layout_signature 或 xfa_structure_signature →
|
||||
核心逻辑:校验 current_sample → 解析/自动生成统一 Profile 身份签名 →
|
||||
解析/自动运行 cross_template_overlap → 汇总阻断项并持久化报告引用。
|
||||
"""
|
||||
profile = _profile(profile_id)
|
||||
@@ -817,34 +362,25 @@ def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None
|
||||
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))
|
||||
blocking.extend(_adapter_publish_checks(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.run_type == 'layout_signature'
|
||||
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,
|
||||
)
|
||||
signature_run = validation_service.resolve_profile_identity_signature(
|
||||
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')
|
||||
@@ -890,7 +426,7 @@ def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None
|
||||
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)
|
||||
or str(((signature_run.summary_json if signature_run is not None else {}) or {}).get('signature_version') or 'profile-identity-signature.v1')
|
||||
),
|
||||
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,
|
||||
@@ -917,7 +453,7 @@ def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None
|
||||
'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',
|
||||
'value_adapter': _profile_value_adapter(profile),
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+135
-169
@@ -1,11 +1,12 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_suggestion_service.py
|
||||
|
||||
用途:XFA 统一映射建议(视觉 + 拆分规则)与算法建议决定冻结。
|
||||
依赖:order_document_profile_service、order_document_profile_visual_binding_service、
|
||||
xfa_analysis、xfa_split_rule_contract、Profile 草稿与 SuggestionDecision ORM。
|
||||
逻辑:suggest/preview 路径只读不写 Draft/业务表;决定写入走 decide() 且需租约;
|
||||
拆分建议 status 固定 draft/suggested,禁止直接 confirmed。
|
||||
用途:XFA datasets adapter 的拆分规则建议与算法建议决定冻结。
|
||||
依赖:order_document_profile_service、xfa_split_rule_contract、Profile 草稿与
|
||||
SuggestionDecision ORM。
|
||||
逻辑:建议/预览路径只读不写 Draft/业务表;决定写入走 decide() 且需租约;
|
||||
拆分建议 status 固定 draft/suggested,禁止直接 confirmed。视觉候选统一由
|
||||
shipping_pdf_automark 提供,不在此创建第二条 XFA 视觉建议路径。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,15 +19,17 @@ from typing import Any
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingOrderDocumentProfileSuggestionDecision,
|
||||
)
|
||||
from app.jobs.types import JobType
|
||||
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.document_layout.xfa_analysis import analyze_xfa_pdf
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import sanitize_xfa_dto
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XfaSplitMatcher,
|
||||
@@ -37,9 +40,6 @@ from app.services.shipping_notice.document_layout.xfa_split_rule_contract import
|
||||
new_segment_id,
|
||||
split_rule_content_fingerprint,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_visual_binding import (
|
||||
suggest_visual_binding_candidates,
|
||||
)
|
||||
|
||||
|
||||
def suggestion_identity(summary: dict[str, Any]) -> dict[str, str]:
|
||||
@@ -57,6 +57,101 @@ def suggestion_identity(summary: dict[str, Any]) -> dict[str, str]:
|
||||
return {'suggestion_id': checksum[:32], 'suggestion_checksum': checksum}
|
||||
|
||||
|
||||
def _verify_automark_evidence_source(
|
||||
*, profile_id: int, summary: dict[str, Any], selected_evidence_source: Any,
|
||||
require_field_selections: bool = False,
|
||||
) -> bool:
|
||||
"""按已完成统一自动标注 Job 重新计算多证据来源门禁。
|
||||
|
||||
浏览器摘要仅携带 Job 身份,不能自证候选数量或来源。只要建议声明
|
||||
``automark_job_id``,本函数就验证该 Job 的 Profile/document/table/page 身份,
|
||||
并以冻结 result_json 中的 table_reconstruction candidates 决定是否必须选择来源。
|
||||
非自动标注建议不含 Job ID,保持既有决定契约。
|
||||
"""
|
||||
job_id = summary.get('automark_job_id')
|
||||
if job_id is None:
|
||||
return False
|
||||
if not str(job_id).isdigit():
|
||||
raise ValidationError('Automark job identity is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
job = db.session.get(Job, int(job_id))
|
||||
if job is None or str(job.job_type or '') != JobType.SHIPPING_PDF_AUTOMARK.value or str(job.status or '') != 'success':
|
||||
raise ValidationError('Automark job is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
payload = dict(job.payload_json or {}) if isinstance(job.payload_json, dict) else {}
|
||||
if int(payload.get('profile_id') or 0) != int(profile_id):
|
||||
raise ValidationError('Automark job does not belong to this profile', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
for key in ('document_id', 'page_no'):
|
||||
if str(summary.get(key) or '') != str(payload.get(key) or ''):
|
||||
raise ValidationError('Automark suggestion identity does not match its job', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
if str(summary.get('table_id') or '') != str(payload.get('table_id') or ''):
|
||||
raise ValidationError('Automark suggestion table does not match its job', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
document = db.session.get(ShippingOrderDocument, int(payload.get('document_id') or 0))
|
||||
current_checksum = str(
|
||||
getattr(getattr(document, 'current_layout_version', None), 'payload_checksum', '') or '',
|
||||
)
|
||||
frozen_checksum = str(payload.get('layout_payload_checksum') or '')
|
||||
if (
|
||||
document is None
|
||||
or int(document.current_layout_version_id or 0) != int(payload.get('layout_version_id') or 0)
|
||||
or not frozen_checksum
|
||||
or current_checksum != frozen_checksum
|
||||
):
|
||||
raise ValidationError(
|
||||
'Automark candidates are stale after document layout reparse',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
annotation = ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=int(profile_id), document_id=int(payload.get('document_id') or 0),
|
||||
sample_role='annotation', table_id=str(payload.get('table_id') or ''),
|
||||
).order_by(ShippingOrderDocumentProfileSample.id.asc()).first()
|
||||
if annotation is None:
|
||||
raise ValidationError('Automark annotation sample is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
if (
|
||||
int(payload.get('layout_version_id') or 0) != int(annotation.layout_version_id or 0)
|
||||
or str(payload.get('layout_payload_checksum') or '') != str(annotation.layout_payload_checksum or '')
|
||||
):
|
||||
raise ValidationError('Automark candidates are stale after layout or sample change', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
result = dict(job.result_json or {}) if isinstance(job.result_json, dict) else {}
|
||||
sources = {
|
||||
str((item.get('evidence_sources') or [''])[0])
|
||||
for item in (result.get('candidates') or [])
|
||||
if isinstance(item, dict)
|
||||
and item.get('candidate_kind') == 'table_reconstruction'
|
||||
and isinstance(item.get('evidence_sources'), list)
|
||||
and item.get('evidence_sources')
|
||||
}
|
||||
if selected_evidence_source and str(selected_evidence_source) not in sources:
|
||||
raise ValidationError('Selected visual evidence source is not in automark candidates', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
if require_field_selections:
|
||||
diagnostics = result.get('diagnostics') if isinstance(result.get('diagnostics'), dict) else {}
|
||||
field_conflicts = diagnostics.get('field_conflicts') if isinstance(diagnostics.get('field_conflicts'), list) else []
|
||||
selected_fields = summary.get('selected_field_evidence_sources')
|
||||
if selected_fields is None:
|
||||
selected_fields = {}
|
||||
if not isinstance(selected_fields, dict):
|
||||
raise ValidationError('Field visual evidence selections are invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
for conflict in field_conflicts:
|
||||
if not isinstance(conflict, dict) or conflict.get('code') != 'field_binding_source_conflict':
|
||||
continue
|
||||
field_id = str(conflict.get('field_id') or '').strip()
|
||||
allowed_sources = {
|
||||
str(source).strip() for source in (conflict.get('sources') or []) if str(source).strip()
|
||||
}
|
||||
chosen = selected_fields.get(field_id)
|
||||
if not field_id or not allowed_sources or not isinstance(chosen, str) or chosen not in allowed_sources:
|
||||
raise ValidationError(
|
||||
'A visual evidence source must be selected for every conflicting field',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
details={'reason': 'field_visual_evidence_source_required', 'field_id': field_id},
|
||||
)
|
||||
known_field_ids = {
|
||||
str(item.get('field_id') or '').strip()
|
||||
for item in field_conflicts if isinstance(item, dict) and item.get('code') == 'field_binding_source_conflict'
|
||||
}
|
||||
if any(str(field_id) not in known_field_ids for field_id in selected_fields):
|
||||
raise ValidationError('Selected field visual evidence source is not in automark conflicts', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
return len(sources) > 1
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取 Profile;不存在时统一 not-found。"""
|
||||
row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
@@ -72,8 +167,8 @@ def _require_xfa_draft(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
'Suggestions require a draft profile',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
mode = str(profile.template_mode or (profile.definition_json or {}).get('template_mode') or '')
|
||||
if mode != 'xfa_dataset':
|
||||
adapter = profile_service._publish_value_adapter(profile_service._profile_template_mode(profile))
|
||||
if not adapter.requires_path_context:
|
||||
raise ValidationError(
|
||||
'Unified mapping suggestions are only available for XFA profiles',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
@@ -81,27 +176,6 @@ def _require_xfa_draft(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
return dict(profile.definition_json or {})
|
||||
|
||||
|
||||
def _sample_pdf_bytes(document_id: int) -> bytes:
|
||||
"""读取样本文档 PDF 字节。"""
|
||||
from app.models import ShippingOrderDocument
|
||||
from app.models import FileAsset
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if document is None or not document.asset_id:
|
||||
raise ValidationError(
|
||||
'Profile sample document is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
asset = db.session.get(FileAsset, int(document.asset_id))
|
||||
if asset is None:
|
||||
raise ValidationError(
|
||||
'Profile sample file is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
return read_asset_bytes(asset)
|
||||
|
||||
|
||||
def _resolve_matnr_path_id(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
@@ -115,7 +189,7 @@ def _resolve_matnr_path_id(
|
||||
|
||||
Args:
|
||||
definition: 当前 Profile definition。
|
||||
path_context: resolve_xfa_path_context 结果。
|
||||
path_context: 当前末端值源 adapter 的冻结路径上下文。
|
||||
path_id: 可选显式 path_id。
|
||||
|
||||
Returns:
|
||||
@@ -163,7 +237,8 @@ def _schema_field_ids(profile_id: int) -> dict[str, dict[str, Any]]:
|
||||
Returns:
|
||||
field_code 索引的 Schema 字段 dict。
|
||||
"""
|
||||
return profile_service._resolve_schema_fields_for_split(profile_id=profile_id)
|
||||
profile = _profile(profile_id)
|
||||
return get_value_adapter(dict(profile.definition_json or {})).mapping_schema_fields(profile_id=profile_id)
|
||||
|
||||
|
||||
def build_matnr_split_rule_suggestion(
|
||||
@@ -278,7 +353,7 @@ def suggest_xfa_split_rules(
|
||||
definition = _require_xfa_draft(profile)
|
||||
profile_service._bound_sample_document(int(profile_id), int(document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
path_context = profile_service.resolve_xfa_path_context(document)
|
||||
path_context = get_value_adapter(definition).prepare_context(document)
|
||||
resolved_path_id, data_path = _resolve_matnr_path_id(
|
||||
definition=definition,
|
||||
path_context=path_context,
|
||||
@@ -317,136 +392,6 @@ def suggest_xfa_split_rules(
|
||||
})
|
||||
|
||||
|
||||
def suggest_xfa_visual_bindings_readonly(
|
||||
profile_id: int,
|
||||
*,
|
||||
document_id: int,
|
||||
page_no: int,
|
||||
normalized_bbox: dict[str, Any],
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为页面区域生成视觉绑定候选(纯内存,不写 Draft/审计)。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 样本 document ID。
|
||||
page_no: 页码。
|
||||
normalized_bbox: 归一化查询区域。
|
||||
actor_id: 管理员 ID。
|
||||
|
||||
Returns:
|
||||
候选与 diagnostics;候选 status 均为 suggested。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
profile = _profile(profile_id)
|
||||
_require_xfa_draft(profile)
|
||||
profile_service._bound_sample_document(int(profile_id), int(document_id))
|
||||
pdf_bytes = _sample_pdf_bytes(int(document_id))
|
||||
outcome = analyze_xfa_pdf(pdf_bytes)
|
||||
if outcome.dataset_analysis is None:
|
||||
raise ValidationError(
|
||||
'XFA dataset analysis is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
|
||||
)
|
||||
bbox = {
|
||||
'x0': float(normalized_bbox.get('x0') or 0),
|
||||
'y0': float(normalized_bbox.get('y0') or 0),
|
||||
'x1': float(normalized_bbox.get('x1') or 0),
|
||||
'y1': float(normalized_bbox.get('y1') or 0),
|
||||
}
|
||||
result = suggest_visual_binding_candidates(
|
||||
page_no=int(page_no),
|
||||
normalized_bbox=bbox,
|
||||
dataset_analysis=outcome.dataset_analysis,
|
||||
pdf_bytes=pdf_bytes,
|
||||
)
|
||||
for candidate in result.get('candidates') or []:
|
||||
if isinstance(candidate, dict):
|
||||
candidate['status'] = 'suggested'
|
||||
return {
|
||||
'profile_id': int(profile.id),
|
||||
'document_id': int(document_id),
|
||||
**result,
|
||||
}
|
||||
|
||||
|
||||
def suggest_xfa_unified_mapping(
|
||||
profile_id: int,
|
||||
*,
|
||||
document_id: int,
|
||||
page_no: int,
|
||||
normalized_bbox: dict[str, Any],
|
||||
actor_id: int | None,
|
||||
path_id: str | None = None,
|
||||
include_visual: bool = True,
|
||||
include_split: bool = True,
|
||||
write_audit: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
统一入口:返回视觉建议 + 拆分规则建议(不写 Draft)。
|
||||
|
||||
核心逻辑:分别调用只读视觉候选与 MATNR 拆分建议;默认零写库。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 样本 document ID。
|
||||
page_no: 页码(视觉建议)。
|
||||
normalized_bbox: 查询区域(视觉建议)。
|
||||
actor_id: 管理员 ID。
|
||||
path_id: 可选拆分源 path_id。
|
||||
include_visual: 是否包含视觉候选。
|
||||
include_split: 是否包含拆分规则建议。
|
||||
write_audit: 是否写只读审计(默认 False)。
|
||||
|
||||
Returns:
|
||||
visual_suggestion、split_rule_suggestion 与 suggestion_status=suggested。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise ValidationError(
|
||||
'actor_id is required for unified mapping suggestion',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
details={'reason': 'actor_required'},
|
||||
)
|
||||
visual_payload: dict[str, Any] | None = None
|
||||
split_payload: dict[str, Any] | None = None
|
||||
if include_visual:
|
||||
visual_payload = suggest_xfa_visual_bindings_readonly(
|
||||
profile_id,
|
||||
document_id=int(document_id),
|
||||
page_no=int(page_no),
|
||||
normalized_bbox=normalized_bbox,
|
||||
actor_id=actor_id,
|
||||
)
|
||||
if include_split:
|
||||
split_payload = suggest_xfa_split_rules(
|
||||
profile_id,
|
||||
document_id=int(document_id),
|
||||
path_id=path_id,
|
||||
actor_id=actor_id,
|
||||
write_audit=write_audit,
|
||||
)
|
||||
summary = {
|
||||
'kind': 'xfa_unified_mapping_suggestion',
|
||||
'algorithm_version': 'xfa-unified-suggest-v1',
|
||||
'include_visual': bool(include_visual),
|
||||
'include_split': bool(include_split),
|
||||
'visual_candidate_count': len((visual_payload or {}).get('candidates') or []),
|
||||
'split_rule_set_id': (split_payload or {}).get('rule_set', {}).get('rule_set_id'),
|
||||
}
|
||||
identity = suggestion_identity(summary)
|
||||
return sanitize_xfa_dto({
|
||||
'profile_id': int(profile_id),
|
||||
'document_id': int(document_id),
|
||||
'suggestion_status': 'suggested',
|
||||
'suggestion_id': identity['suggestion_id'],
|
||||
'suggestion_checksum': identity['suggestion_checksum'],
|
||||
'visual_suggestion': visual_payload,
|
||||
'split_rule_suggestion': split_payload,
|
||||
})
|
||||
|
||||
|
||||
def decide(
|
||||
profile_id: int, *, data: dict[str, Any], actor_id: int | None,
|
||||
browser_session_id: str | None, lease_token: str | None, operation_id: str,
|
||||
@@ -474,12 +419,27 @@ def decide(
|
||||
summary = data.get('suggestion_summary')
|
||||
if not isinstance(summary, dict):
|
||||
raise ValidationError('suggestion_summary is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
identity = suggestion_identity(summary)
|
||||
if data.get('suggestion_id') != identity['suggestion_id'] or data.get('suggestion_checksum') != identity['suggestion_checksum']:
|
||||
raise ValidationError('Suggestion identity is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
decision = str(data.get('decision') or '')
|
||||
if decision not in {'accepted', 'accepted_adjusted', 'rejected'}:
|
||||
raise ValidationError('Suggestion decision is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
selected_evidence_source = summary.get('selected_evidence_source')
|
||||
evidence_source_required = _verify_automark_evidence_source(
|
||||
profile_id=profile.id, summary=summary, selected_evidence_source=selected_evidence_source,
|
||||
require_field_selections=decision != 'rejected',
|
||||
) or summary.get('evidence_source_required') is True
|
||||
if evidence_source_required and str(data.get('decision') or '') != 'rejected' and not selected_evidence_source:
|
||||
raise ValidationError(
|
||||
'A visual evidence source must be selected before accepting this suggestion',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
details={'reason': 'visual_evidence_source_required'},
|
||||
)
|
||||
if selected_evidence_source is not None and str(selected_evidence_source) not in {
|
||||
'pdf_coordinate', 'ocr_coordinate', 'opencv_geometry', 'acroform_widget_geometry',
|
||||
}:
|
||||
raise ValidationError('Suggestion evidence source is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
identity = suggestion_identity(summary)
|
||||
if data.get('suggestion_id') != identity['suggestion_id'] or data.get('suggestion_checksum') != identity['suggestion_checksum']:
|
||||
raise ValidationError('Suggestion identity is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
if decision == 'accepted_adjusted' and not isinstance(data.get('adjustment_summary'), dict):
|
||||
raise ValidationError('adjustment_summary is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
prior = ShippingOrderDocumentProfileSuggestionDecision.query.filter_by(profile_id=profile.id, suggestion_id=identity['suggestion_id']).one_or_none()
|
||||
@@ -497,7 +457,13 @@ def decide(
|
||||
parser_version=sample.parser_version if sample else None, schema_version_id=profile.schema_version_id,
|
||||
algorithm_version=str(summary.get('algorithm_version') or 'coordinate-suggest-v1')[:64], suggestion_id=identity['suggestion_id'],
|
||||
suggestion_checksum=identity['suggestion_checksum'], decision=decision, actor_id=actor_id, operation_id=operation_id,
|
||||
detail_json={'kind': str(summary.get('kind') or 'region'), 'adjustment_summary': data.get('adjustment_summary') if decision == 'accepted_adjusted' else None},
|
||||
detail_json={
|
||||
'kind': str(summary.get('kind') or 'region'),
|
||||
# 管理员在多证据候选中选择的来源必须可审计;它不改变 XFA datasets
|
||||
# 的正式值源,仅说明本次视觉区域是基于哪一路几何确认。
|
||||
'selected_evidence_source': str(selected_evidence_source) if selected_evidence_source is not None else None,
|
||||
'adjustment_summary': data.get('adjustment_summary') if decision == 'accepted_adjusted' else None,
|
||||
},
|
||||
)
|
||||
db.session.add(item)
|
||||
profile_service._audit(profile_id=profile.id, event_type='suggestion_decided', actor_id=actor_id, browser_session_id=browser_session_id, operation_id=operation_id, revision_no=revision.revision_no, detail={'suggestion_id': identity['suggestion_id'], 'decision': decision, 'algorithm_version': item.algorithm_version})
|
||||
|
||||
+377
-927
File diff suppressed because it is too large.
Load diff
@@ -19,6 +19,7 @@ from app.models import (
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
summarize_unified_migration_status,
|
||||
)
|
||||
@@ -30,37 +31,40 @@ def _profile_event_time(profile: ShippingOrderDocumentProfile) -> datetime:
|
||||
|
||||
|
||||
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/order-field 视觉布局;adapter 只追加
|
||||
最终取值所需的附加证据数量,版本概览不得因值源不同隐藏共同画布的真实配置。
|
||||
"""
|
||||
adapter = get_value_adapter(definition)
|
||||
table_regions = [
|
||||
item for item in (definition.get('table_regions') or [])
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
return {
|
||||
shared = {
|
||||
'value_adapter': adapter.key,
|
||||
'table_region_count': len(table_regions),
|
||||
'header_layout_count': sum(len(item.get('header_layouts') or []) for item in table_regions),
|
||||
'line_layout_count': sum(len(item.get('line_layouts') or []) for item in table_regions),
|
||||
'order_field_layout_count': len(definition.get('order_field_layouts') or []),
|
||||
'draft_unbound_order_field_layout_count': len(definition.get('draft_unbound_order_field_layouts') or []),
|
||||
}
|
||||
if adapter.requires_path_context:
|
||||
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 {
|
||||
**shared,
|
||||
'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 []),
|
||||
}
|
||||
return shared
|
||||
|
||||
|
||||
def _xfa_structure_identity_summary(definition: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""返回版本详情允许展示的 XFA 结构身份摘要(无明文路径值)。"""
|
||||
if str(definition.get('template_mode') or '') != 'xfa_dataset':
|
||||
def _value_source_identity_summary(definition: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""返回末端值源可安全展示的身份摘要(无明文路径值)。"""
|
||||
adapter = get_value_adapter(definition)
|
||||
if not adapter.requires_path_context:
|
||||
return None
|
||||
source = definition.get('source_contract') if isinstance(definition.get('source_contract'), dict) else {}
|
||||
return {
|
||||
@@ -240,16 +244,15 @@ def get_profile_detail(profile_id: int) -> dict[str, Any]:
|
||||
'checksum': safe.get('schema_checksum'),
|
||||
},
|
||||
'definition_stats': _definition_scale_summary(definition),
|
||||
'xfa_structure_identity': _xfa_structure_identity_summary(definition),
|
||||
'value_source_identity': _value_source_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)
|
||||
value_adapter = get_value_adapter(profile.definition_json)
|
||||
mapping_evidence = value_adapter.readonly_mapping_evidence(profile)
|
||||
if mapping_evidence is not None:
|
||||
payload['value_source_readonly_mapping'] = mapping_evidence
|
||||
return payload
|
||||
|
||||
|
||||
|
||||
-485
@@ -1,485 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_visual_binding_service.py
|
||||
|
||||
用途:XFA 统一视觉绑定的建议、确认、驳回编排(Lease、definition 更新与审计)。
|
||||
依赖:xfa_visual_binding、xfa_analysis、order_document_profile_service、
|
||||
lease_service、order_document_profile_audit_service(双写 Profile + 平台快照)。
|
||||
逻辑:admin API 调用本模块;建议只读不写 Draft;确认/驳回需租约并写 before/after 审计;
|
||||
确认绑定原生 PDF 画布(confirmed_on=native_pdf);旧 synthetic 确认须重确认。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import secrets
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import ShippingOrderDocument, ShippingOrderDocumentProfile
|
||||
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.document_layout.xfa_analysis import analyze_xfa_pdf
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
OrderXfaDatasetProfile,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_visual_binding import (
|
||||
suggest_visual_binding_candidates,
|
||||
visual_binding_audit_snapshot,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_audit_service import (
|
||||
build_profile_audit_context,
|
||||
record_visual_binding_audit,
|
||||
)
|
||||
|
||||
# 原生 PDF 画布确认标识(硬冻结 2026-08-07)。
|
||||
NATIVE_PDF_CONFIRM_MODE = 'native_pdf'
|
||||
_CONFIRM_REQUIRES_PAGE = 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_CONFIRM_REQUIRES_PAGE'
|
||||
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取 Profile;不存在时统一 not-found。"""
|
||||
row = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
if row is None:
|
||||
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
|
||||
return row
|
||||
|
||||
|
||||
def _require_xfa_draft(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""校验 XFA 草稿 definition 并返回可变副本。"""
|
||||
if str(profile.status or '') != 'draft':
|
||||
raise ValidationError(
|
||||
'Visual binding changes require a draft profile',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
mode = str(profile.template_mode or (profile.definition_json or {}).get('template_mode') or '')
|
||||
if mode != 'xfa_dataset':
|
||||
raise ValidationError(
|
||||
'Visual binding is only available for XFA profiles',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
return dict(profile.definition_json or {})
|
||||
|
||||
|
||||
def _sample_pdf_bytes(document_id: int) -> bytes:
|
||||
"""读取样本文档 PDF 字节。"""
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if document is None or not document.asset_id:
|
||||
raise ValidationError(
|
||||
'Profile sample document is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
from app.models import FileAsset
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
|
||||
asset = db.session.get(FileAsset, int(document.asset_id))
|
||||
if asset is None:
|
||||
raise ValidationError(
|
||||
'Profile sample file is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
return read_asset_bytes(asset)
|
||||
|
||||
|
||||
def _resolve_path_from_definition(definition: dict[str, Any], path_id: str) -> str | None:
|
||||
"""从 header/line mappings 或 bindings 反查 data_path。"""
|
||||
for item in definition.get('header_mappings') or []:
|
||||
if isinstance(item, dict) and str(item.get('path_id') or '') == path_id:
|
||||
return str(item.get('data_path') or '').strip() or None
|
||||
line_mapping = definition.get('line_mapping') if isinstance(definition.get('line_mapping'), dict) else {}
|
||||
for item in line_mapping.get('fields') or []:
|
||||
if isinstance(item, dict) and str(item.get('path_id') or '') == path_id:
|
||||
return str(item.get('data_path') or '').strip() or None
|
||||
for item in definition.get('bindings') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
value = item.get('value_binding') if isinstance(item.get('value_binding'), dict) else {}
|
||||
if str(value.get('path_id') or '') == path_id:
|
||||
return str(value.get('data_path') or '').strip() or None
|
||||
return None
|
||||
|
||||
|
||||
def suggest_xfa_visual_bindings(
|
||||
profile_id: int,
|
||||
*,
|
||||
document_id: int,
|
||||
page_no: int,
|
||||
normalized_bbox: dict[str, Any],
|
||||
actor_id: int | None,
|
||||
request_id: str | None = None,
|
||||
write_audit: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为页面区域生成 XFA 视觉绑定候选(默认不写 Draft、不 commit)。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 绑定样本 document ID。
|
||||
page_no: 页码。
|
||||
normalized_bbox: 归一化查询区域。
|
||||
actor_id: 管理员 ID。
|
||||
request_id: HTTP request_id。
|
||||
write_audit: 为 True 时写只读建议审计并 commit(默认 False)。
|
||||
|
||||
Returns:
|
||||
候选列表与 diagnostics;所有候选 status=suggested。
|
||||
"""
|
||||
from app.services.shipping_notice import order_document_profile_suggestion_service as suggestion_service
|
||||
|
||||
result = suggestion_service.suggest_xfa_visual_bindings_readonly(
|
||||
profile_id,
|
||||
document_id=int(document_id),
|
||||
page_no=int(page_no),
|
||||
normalized_bbox=normalized_bbox,
|
||||
actor_id=actor_id,
|
||||
)
|
||||
if write_audit:
|
||||
profile = _profile(profile_id)
|
||||
record_visual_binding_audit(
|
||||
profile_id=int(profile_id),
|
||||
document_id=int(document_id),
|
||||
event_type='xfa_visual_binding_suggested',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
before=None,
|
||||
after={'page_no': int(page_no), 'candidate_count': len(result.get('candidates') or [])},
|
||||
detail={
|
||||
'page_no': int(page_no),
|
||||
'normalized_bbox': normalized_bbox,
|
||||
'diagnostics': result.get('diagnostics'),
|
||||
'candidate_count': len(result.get('candidates') or []),
|
||||
'action': 'suggest',
|
||||
},
|
||||
profile_context=build_profile_audit_context(profile),
|
||||
)
|
||||
db.session.commit()
|
||||
return result
|
||||
|
||||
|
||||
def _find_binding(definition: dict[str, Any], binding_id: str) -> tuple[int, dict[str, Any]]:
|
||||
"""在 definition.bindings 中定位 binding 索引。"""
|
||||
bindings = definition.get('bindings') if isinstance(definition.get('bindings'), list) else []
|
||||
for index, item in enumerate(bindings):
|
||||
if isinstance(item, dict) and str(item.get('binding_id') or '') == str(binding_id):
|
||||
return index, item
|
||||
raise NotFoundError(
|
||||
'Visual binding not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_BINDING_NOT_FOUND',
|
||||
)
|
||||
|
||||
|
||||
def demote_legacy_synthetic_visual_bindings(definition: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
将旧合成预览确认框降级为待重确认(不自动迁移坐标系)。
|
||||
|
||||
核心逻辑:confirmed_on/render_mode 为 xfa_dataset_preview 的 confirmed 绑定
|
||||
→ status=suggested,并清除合成证据字段。
|
||||
|
||||
Args:
|
||||
definition: XFA definition(就地修改并返回)。
|
||||
|
||||
Returns:
|
||||
处理后的 definition。
|
||||
"""
|
||||
bindings = definition.get('bindings')
|
||||
if not isinstance(bindings, list):
|
||||
return definition
|
||||
changed = False
|
||||
next_bindings: list[Any] = []
|
||||
for raw in bindings:
|
||||
if not isinstance(raw, dict):
|
||||
next_bindings.append(raw)
|
||||
continue
|
||||
visual = raw.get('visual_binding') if isinstance(raw.get('visual_binding'), dict) else None
|
||||
if not visual:
|
||||
next_bindings.append(raw)
|
||||
continue
|
||||
confirmed_on = str(visual.get('confirmed_on') or '').strip()
|
||||
render_mode = str(visual.get('render_mode') or '').strip()
|
||||
if visual.get('status') == 'confirmed' and (
|
||||
confirmed_on == 'xfa_dataset_preview' or render_mode == 'xfa_dataset_preview'
|
||||
):
|
||||
next_visual = dict(visual)
|
||||
next_visual['status'] = 'suggested'
|
||||
next_visual.pop('preview_render_checksum', None)
|
||||
next_visual.pop('confirmed_on', None)
|
||||
next_visual.pop('renderer_version', None)
|
||||
next_visual['render_mode'] = NATIVE_PDF_CONFIRM_MODE
|
||||
next_raw = dict(raw)
|
||||
next_raw['visual_binding'] = next_visual
|
||||
next_bindings.append(next_raw)
|
||||
changed = True
|
||||
else:
|
||||
next_bindings.append(raw)
|
||||
if changed:
|
||||
definition['bindings'] = next_bindings
|
||||
return definition
|
||||
|
||||
|
||||
def confirm_xfa_visual_binding(
|
||||
profile_id: int,
|
||||
binding_id: str,
|
||||
*,
|
||||
visual_binding: dict[str, Any],
|
||||
path_id: str | None,
|
||||
actor_id: int | None,
|
||||
browser_session_id: str | None,
|
||||
lease_token: str | None,
|
||||
operation_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
preview_render_checksum: str | None = None,
|
||||
render_mode: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
管理员确认视觉绑定;写 definition 与 before/after 审计。
|
||||
|
||||
核心逻辑:在原生 PDF 画布上确认——须有 page_no 与 normalized_bbox;
|
||||
confirmed_on/render_mode 写为 native_pdf。不再要求合成预览 checksum。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
binding_id: 目标 binding_id。
|
||||
visual_binding: 确认的 visual_binding(须含 page_no、normalized_bbox)。
|
||||
path_id: 可选 value path_id;省略时保留既有 value_binding。
|
||||
actor_id: 管理员 ID。
|
||||
browser_session_id: 浏览器会话。
|
||||
lease_token: 编辑租约令牌。
|
||||
operation_id: 幂等操作 ID。
|
||||
request_id: HTTP request_id。
|
||||
preview_render_checksum: 兼容旧客户端;忽略。
|
||||
render_mode: 兼容旧客户端;写入时强制 native_pdf。
|
||||
|
||||
Returns:
|
||||
更新后的 binding 摘要。
|
||||
|
||||
Raises:
|
||||
ValidationError: 缺少页码或 bbox。
|
||||
ConflictError: 缺少编辑租约。
|
||||
NotFoundError: Profile / binding 不存在。
|
||||
"""
|
||||
del preview_render_checksum, render_mode # 兼容入参;确认证据改绑原生 PDF
|
||||
if actor_id is None:
|
||||
raise ConflictError('Edit lease is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
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,
|
||||
)
|
||||
definition = _require_xfa_draft(profile)
|
||||
demote_legacy_synthetic_visual_bindings(definition)
|
||||
|
||||
# [STEP 1] 原生 PDF 确认门禁:页码与 bbox 必填
|
||||
next_visual = dict(visual_binding or {})
|
||||
page_no = next_visual.get('page_no')
|
||||
bbox = next_visual.get('normalized_bbox')
|
||||
if not page_no or not isinstance(bbox, dict):
|
||||
raise ValidationError(
|
||||
'Visual binding confirm requires page_no and normalized_bbox on native PDF canvas',
|
||||
code=_CONFIRM_REQUIRES_PAGE,
|
||||
details={
|
||||
'page_no_present': bool(page_no),
|
||||
'normalized_bbox_present': isinstance(bbox, dict),
|
||||
'expected_confirmed_on': NATIVE_PDF_CONFIRM_MODE,
|
||||
},
|
||||
)
|
||||
|
||||
index, binding = _find_binding(definition, binding_id)
|
||||
before = visual_binding_audit_snapshot(binding)
|
||||
|
||||
# [STEP 2] 写入确认状态与原生 PDF 证据(保留 region_kind)
|
||||
next_visual['status'] = 'confirmed'
|
||||
next_visual.setdefault('source', 'manual_draw')
|
||||
next_visual.setdefault('confidence', 1.0)
|
||||
existing_visual = binding.get('visual_binding') if isinstance(binding.get('visual_binding'), dict) else {}
|
||||
if not next_visual.get('region_kind'):
|
||||
next_visual['region_kind'] = existing_visual.get('region_kind') or 'field'
|
||||
next_visual.pop('preview_render_checksum', None)
|
||||
next_visual.pop('renderer_version', None)
|
||||
next_visual['render_mode'] = NATIVE_PDF_CONFIRM_MODE
|
||||
next_visual['confirmed_on'] = NATIVE_PDF_CONFIRM_MODE
|
||||
|
||||
updated = deepcopy(binding)
|
||||
updated['visual_binding'] = next_visual
|
||||
if path_id:
|
||||
data_path = _resolve_path_from_definition(definition, str(path_id))
|
||||
if not data_path:
|
||||
raise ValidationError(
|
||||
'path_id is unknown for this profile',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
value = updated.get('value_binding') if isinstance(updated.get('value_binding'), dict) else {}
|
||||
# 仅在调用方提供 path 时更新 datasets 绑定;不强制覆盖已选的坐标/OCR 类型。
|
||||
if str(value.get('type') or 'xfa_dataset') == 'xfa_dataset':
|
||||
value.update({'type': 'xfa_dataset', 'path_id': str(path_id), 'data_path': data_path})
|
||||
updated['value_binding'] = value
|
||||
|
||||
bindings = list(definition.get('bindings') or [])
|
||||
bindings[index] = updated
|
||||
definition['bindings'] = bindings
|
||||
OrderXfaDatasetProfile.model_validate(definition)
|
||||
|
||||
profile.definition_json = definition
|
||||
db.session.flush()
|
||||
after = visual_binding_audit_snapshot(updated)
|
||||
record_visual_binding_audit(
|
||||
profile_id=int(profile.id),
|
||||
document_id=None,
|
||||
event_type='xfa_visual_binding_confirmed',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
before=before,
|
||||
after=after,
|
||||
detail={
|
||||
'binding_id': binding_id,
|
||||
'action': 'confirm',
|
||||
'render_mode': NATIVE_PDF_CONFIRM_MODE,
|
||||
'confirmed_on': NATIVE_PDF_CONFIRM_MODE,
|
||||
},
|
||||
raw_binding_before=binding,
|
||||
raw_binding_after=updated,
|
||||
profile_context=build_profile_audit_context(profile),
|
||||
)
|
||||
db.session.commit()
|
||||
return {'binding_id': binding_id, 'visual_binding': next_visual, 'status': 'confirmed'}
|
||||
|
||||
|
||||
def reject_xfa_visual_binding(
|
||||
profile_id: int,
|
||||
binding_id: str,
|
||||
*,
|
||||
reason_code: str | None,
|
||||
actor_id: int | None,
|
||||
browser_session_id: str | None,
|
||||
lease_token: str | None,
|
||||
operation_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
管理员驳回视觉绑定建议;写 before/after 审计。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
binding_id: 目标 binding_id。
|
||||
reason_code: 可选驳回原因码。
|
||||
actor_id: 管理员 ID。
|
||||
browser_session_id: 浏览器会话。
|
||||
lease_token: 编辑租约令牌。
|
||||
operation_id: 幂等操作 ID。
|
||||
request_id: HTTP request_id。
|
||||
|
||||
Returns:
|
||||
驳回后的 binding 摘要。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise ConflictError('Edit lease is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
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,
|
||||
)
|
||||
definition = _require_xfa_draft(profile)
|
||||
index, binding = _find_binding(definition, binding_id)
|
||||
before = visual_binding_audit_snapshot(binding)
|
||||
|
||||
updated = deepcopy(binding)
|
||||
visual = updated.get('visual_binding') if isinstance(updated.get('visual_binding'), dict) else {}
|
||||
visual['status'] = 'rejected'
|
||||
visual.setdefault('source', 'suggested')
|
||||
updated['visual_binding'] = visual
|
||||
|
||||
bindings = list(definition.get('bindings') or [])
|
||||
bindings[index] = updated
|
||||
definition['bindings'] = bindings
|
||||
OrderXfaDatasetProfile.model_validate(definition)
|
||||
|
||||
profile.definition_json = definition
|
||||
db.session.flush()
|
||||
after = visual_binding_audit_snapshot(updated)
|
||||
record_visual_binding_audit(
|
||||
profile_id=int(profile.id),
|
||||
document_id=None,
|
||||
event_type='xfa_visual_binding_rejected',
|
||||
actor_id=actor_id,
|
||||
request_id=request_id,
|
||||
operation_id=operation_id,
|
||||
before=before,
|
||||
after=after,
|
||||
detail={'binding_id': binding_id, 'action': 'reject', 'reason_code': reason_code},
|
||||
raw_binding_before=binding,
|
||||
raw_binding_after=updated,
|
||||
profile_context=build_profile_audit_context(profile),
|
||||
)
|
||||
db.session.commit()
|
||||
return {'binding_id': binding_id, 'visual_binding': visual, 'status': 'rejected'}
|
||||
|
||||
|
||||
def ensure_binding_stub(
|
||||
profile_id: int,
|
||||
*,
|
||||
field_id: str,
|
||||
field_code: str,
|
||||
scope: str,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
actor_id: int | None,
|
||||
browser_session_id: str | None,
|
||||
lease_token: str | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为字段创建带 suggested 视觉状态的 binding 占位(供测试/编辑器初始化)。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
field_id: Schema field_id。
|
||||
field_code: 字段编码。
|
||||
scope: header|line。
|
||||
path_id: datasets path_id。
|
||||
data_path: datasets 路径。
|
||||
actor_id: 管理员 ID。
|
||||
browser_session_id: 浏览器会话。
|
||||
lease_token: 租约令牌。
|
||||
|
||||
Returns:
|
||||
新建 binding 摘要。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise ConflictError('Edit lease is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED')
|
||||
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,
|
||||
)
|
||||
definition = _require_xfa_draft(profile)
|
||||
bindings = list(definition.get('bindings') or [])
|
||||
binding_id = f'bind-{secrets.token_hex(8)}'
|
||||
binding = {
|
||||
'binding_id': binding_id,
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'scope': scope,
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': path_id,
|
||||
'data_path': data_path,
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.0, 'y0': 0.0, 'x1': 0.01, 'y1': 0.01},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.0,
|
||||
},
|
||||
}
|
||||
bindings.append(binding)
|
||||
definition['bindings'] = bindings
|
||||
OrderXfaDatasetProfile.model_validate(definition)
|
||||
profile.definition_json = definition
|
||||
db.session.commit()
|
||||
return binding
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,902 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/order_document_profile_xfa_preview_service.py
|
||||
|
||||
用途:订单文档样本的 XFA 合成预览编排(Phase 1–2)——按冻结 Layout/Analysis 生成、
|
||||
缓存并签发单页 PNG 授权;禁止“按 document 最新 Analysis”回退。
|
||||
依赖:resolve_frozen_xfa_structure_analysis、compose_xfa_dataset_preview_pages、
|
||||
xfa_preview_cache、xfa_preview_contract、preview_grant_store、FileAsset、ProfileAudit。
|
||||
逻辑:Admin API POST/GET xfa/preview* 调用本模块;身份不一致 fail-closed 抛 ValidationError。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import secrets
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingXfaStructureAnalysis,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_cache import (
|
||||
build_preview_cache_key,
|
||||
get_preview_cache,
|
||||
set_preview_cache,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_contract import (
|
||||
RENDER_MODE,
|
||||
XFA_PREVIEW_FAILED,
|
||||
XFA_PREVIEW_STALE,
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
XFA_PREVIEW_VALUE_MISMATCH,
|
||||
PreviewIdentityContext,
|
||||
is_preview_identity_stale,
|
||||
preview_identity_to_dict,
|
||||
shipping_error_code_for_preview,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_preview_renderer import (
|
||||
RENDERER_VERSION,
|
||||
compose_xfa_dataset_preview_pages,
|
||||
)
|
||||
from app.services.shipping_notice.preview_grant_store import preview_grant_store
|
||||
|
||||
PREVIEW_GRANT_TTL_SECONDS = 120
|
||||
PREVIEW_GRANT_KEY_PREFIX = 'shipping:order-profile-xfa-synth-preview:'
|
||||
_XFA_PREVIEW_KINDS = frozenset({'xfa_hybrid', 'pure_xfa'})
|
||||
|
||||
|
||||
def _raise_preview_error(
|
||||
short_code: str,
|
||||
message: str,
|
||||
*,
|
||||
details: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
以预览短码映射 SHIPPING.* 后抛出 ValidationError(fail-closed)。
|
||||
|
||||
Args:
|
||||
short_code: xfa_preview_contract 短错误码。
|
||||
message: 英文技术消息。
|
||||
details: 可选诊断细节(不含 PNG/明文路径原文)。
|
||||
|
||||
Raises:
|
||||
ValidationError: 始终抛出。
|
||||
"""
|
||||
raise ValidationError(
|
||||
message,
|
||||
code=shipping_error_code_for_preview(short_code) or short_code,
|
||||
details=dict(details or {}),
|
||||
)
|
||||
|
||||
|
||||
def _audit(
|
||||
*,
|
||||
document_id: int,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
detail: dict[str, Any] | None = None,
|
||||
profile_id: int | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
写入 Profile 审计表(合成预览生命周期事件)。
|
||||
|
||||
核心逻辑:复用 ShippingOrderDocumentProfileAudit;detail 仅放身份与状态摘要,
|
||||
禁止写入 PNG、token 明文或 datasets 全文。
|
||||
"""
|
||||
db.session.add(ShippingOrderDocumentProfileAudit(
|
||||
profile_id=profile_id,
|
||||
document_id=int(document_id),
|
||||
event_type=str(event_type or '').strip()[:48] or 'xfa_preview_requested',
|
||||
actor_id=actor_id,
|
||||
detail_json=dict(detail or {}),
|
||||
))
|
||||
|
||||
|
||||
def _require_sample_document(document_id: int) -> ShippingOrderDocument:
|
||||
"""按主键加载样本文档;缺失时 NotFoundError。"""
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if document is None:
|
||||
raise NotFoundError(
|
||||
'Order profile sample document not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND',
|
||||
)
|
||||
return document
|
||||
|
||||
|
||||
def _preview_grant_store() -> Any:
|
||||
"""返回合成预览页授权存储(可被测试 monkeypatch)。"""
|
||||
return preview_grant_store()
|
||||
|
||||
|
||||
def _norm(value: Any) -> str:
|
||||
"""规范化校验和/指纹比较用字符串。"""
|
||||
return str(value or '').strip().lower()
|
||||
|
||||
|
||||
def _build_identity_context(
|
||||
*,
|
||||
document: ShippingOrderDocument,
|
||||
layout_version_id: int,
|
||||
analysis: ShippingXfaStructureAnalysis,
|
||||
preview_render_checksum: str = '',
|
||||
page_count: int = 0,
|
||||
) -> PreviewIdentityContext:
|
||||
"""
|
||||
从冻结 Analysis 构造预览身份上下文。
|
||||
|
||||
Args:
|
||||
document: 样本文档。
|
||||
layout_version_id: 冻结 LayoutVersion 主键。
|
||||
analysis: 冻结 StructureAnalysis。
|
||||
preview_render_checksum: 合成后的 render checksum;生成前可为空。
|
||||
page_count: 页数。
|
||||
|
||||
Returns:
|
||||
PreviewIdentityContext。
|
||||
"""
|
||||
return PreviewIdentityContext(
|
||||
document_id=int(document.id),
|
||||
layout_version_id=int(layout_version_id),
|
||||
structure_analysis_id=int(analysis.id),
|
||||
source_content_hash=_norm(document.content_hash or analysis.source_content_hash),
|
||||
template_packet_checksum=_norm(analysis.template_packet_checksum),
|
||||
datasets_packet_checksum=_norm(analysis.datasets_packet_checksum),
|
||||
dataset_structure_fingerprint=_norm(analysis.dataset_structure_fingerprint),
|
||||
preview_render_checksum=_norm(preview_render_checksum),
|
||||
render_mode=RENDER_MODE,
|
||||
renderer_version=RENDERER_VERSION,
|
||||
page_count=int(page_count or 0),
|
||||
)
|
||||
|
||||
|
||||
def _cache_key_for_analysis(
|
||||
*,
|
||||
analysis: ShippingXfaStructureAnalysis,
|
||||
document: ShippingOrderDocument,
|
||||
) -> str:
|
||||
"""按冻结 Analysis 身份构造预览缓存键(不含 render checksum)。"""
|
||||
return build_preview_cache_key(
|
||||
structure_analysis_id=int(analysis.id),
|
||||
template_packet_checksum=_norm(analysis.template_packet_checksum),
|
||||
datasets_packet_checksum=_norm(analysis.datasets_packet_checksum),
|
||||
dataset_structure_fingerprint=_norm(analysis.dataset_structure_fingerprint),
|
||||
source_content_hash=_norm(document.content_hash or analysis.source_content_hash),
|
||||
renderer_version=RENDERER_VERSION,
|
||||
)
|
||||
|
||||
|
||||
def _identity_from_cached(payload: dict[str, Any]) -> PreviewIdentityContext | None:
|
||||
"""从缓存条目还原 PreviewIdentityContext;字段缺失时返回 None。"""
|
||||
raw = payload.get('identity') if isinstance(payload.get('identity'), dict) else None
|
||||
if not raw:
|
||||
return None
|
||||
try:
|
||||
return PreviewIdentityContext(
|
||||
document_id=int(raw['document_id']) if raw.get('document_id') is not None else None,
|
||||
layout_version_id=(
|
||||
int(raw['layout_version_id']) if raw.get('layout_version_id') is not None else None
|
||||
),
|
||||
structure_analysis_id=raw.get('structure_analysis_id'),
|
||||
source_content_hash=_norm(raw.get('source_content_hash')),
|
||||
template_packet_checksum=_norm(raw.get('template_packet_checksum')),
|
||||
datasets_packet_checksum=_norm(raw.get('datasets_packet_checksum')),
|
||||
dataset_structure_fingerprint=_norm(raw.get('dataset_structure_fingerprint')),
|
||||
preview_render_checksum=_norm(raw.get('preview_render_checksum')),
|
||||
render_mode=str(raw.get('render_mode') or RENDER_MODE),
|
||||
renderer_version=str(raw.get('renderer_version') or ''),
|
||||
page_count=int(raw.get('page_count') or 0),
|
||||
)
|
||||
except (TypeError, ValueError, KeyError):
|
||||
return None
|
||||
|
||||
|
||||
def _assert_capability_matches_analysis(
|
||||
*,
|
||||
capability: dict[str, Any],
|
||||
analysis: ShippingXfaStructureAnalysis,
|
||||
document_id: int,
|
||||
layout_version_id: int,
|
||||
) -> None:
|
||||
"""
|
||||
校验 Layout.xfa_capability 与冻结 Analysis 身份一致。
|
||||
|
||||
核心逻辑:structure_analysis_id / template / fingerprint 任一漂移 → STALE。
|
||||
"""
|
||||
cap_id = capability.get('structure_analysis_id')
|
||||
if cap_id not in (None, '') and int(cap_id) != int(analysis.id):
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_STALE,
|
||||
'Cached XFA preview identity is stale relative to frozen analysis',
|
||||
details={
|
||||
'document_id': document_id,
|
||||
'layout_version_id': layout_version_id,
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'capability_structure_analysis_id': int(cap_id),
|
||||
'reason': 'structure_analysis_id_mismatch',
|
||||
},
|
||||
)
|
||||
expected_fp = _norm(analysis.dataset_structure_fingerprint)
|
||||
actual_fp = _norm(capability.get('dataset_structure_fingerprint'))
|
||||
if expected_fp and actual_fp and expected_fp != actual_fp:
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_STALE,
|
||||
'Frozen XFA dataset fingerprint no longer matches layout capability',
|
||||
details={
|
||||
'document_id': document_id,
|
||||
'layout_version_id': layout_version_id,
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'reason': 'dataset_structure_fingerprint_mismatch',
|
||||
},
|
||||
)
|
||||
expected_tpl = _norm(analysis.template_packet_checksum)
|
||||
actual_tpl = _norm(capability.get('template_packet_checksum'))
|
||||
if expected_tpl and actual_tpl and expected_tpl != actual_tpl:
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_STALE,
|
||||
'Frozen XFA template checksum no longer matches layout capability',
|
||||
details={
|
||||
'document_id': document_id,
|
||||
'layout_version_id': layout_version_id,
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'reason': 'template_packet_checksum_mismatch',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _assert_live_packets_match_analysis(
|
||||
*,
|
||||
analysis: ShippingXfaStructureAnalysis,
|
||||
live_capability: dict[str, Any],
|
||||
document_id: int,
|
||||
) -> None:
|
||||
"""
|
||||
校验即时解析的 packet/指纹与冻结 Analysis 一致。
|
||||
|
||||
核心逻辑:指纹或 datasets checksum 不等 → VALUE_MISMATCH(禁止用漂移数据合成)。
|
||||
"""
|
||||
live_fp = _norm(live_capability.get('dataset_structure_fingerprint'))
|
||||
frozen_fp = _norm(analysis.dataset_structure_fingerprint)
|
||||
if frozen_fp and live_fp and frozen_fp != live_fp:
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_VALUE_MISMATCH,
|
||||
'Live XFA datasets fingerprint does not match frozen analysis',
|
||||
details={
|
||||
'document_id': document_id,
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'reason': 'live_dataset_fingerprint_mismatch',
|
||||
},
|
||||
)
|
||||
packet_checksums = live_capability.get('packet_checksums')
|
||||
if isinstance(packet_checksums, dict):
|
||||
live_datasets = _norm(packet_checksums.get('datasets'))
|
||||
frozen_datasets = _norm(analysis.datasets_packet_checksum)
|
||||
if frozen_datasets and live_datasets and frozen_datasets != live_datasets:
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_VALUE_MISMATCH,
|
||||
'Live XFA datasets packet checksum does not match frozen analysis',
|
||||
details={
|
||||
'document_id': document_id,
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'reason': 'live_datasets_checksum_mismatch',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _page_metas_without_images(pages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""将合成页列表投影为不含 png_bytes 的元数据。"""
|
||||
metas: list[dict[str, Any]] = []
|
||||
for page in pages:
|
||||
if not isinstance(page, dict):
|
||||
continue
|
||||
echoes = page.get('drawn_field_echoes') or []
|
||||
metas.append({
|
||||
'page_no': int(page.get('page_no') or 0),
|
||||
'width': float(page.get('width') or 0),
|
||||
'height': float(page.get('height') or 0),
|
||||
'drawn_echo_count': len(echoes) if isinstance(echoes, list) else 0,
|
||||
})
|
||||
return metas
|
||||
|
||||
|
||||
def _issue_page_grants(
|
||||
*,
|
||||
document_id: int,
|
||||
structure_analysis_id: int,
|
||||
actor_id: int,
|
||||
pages: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
为合成预览各页签发短时一次性 token。
|
||||
|
||||
Returns:
|
||||
``[{page_no, preview_token, width?, height?}, ...]``
|
||||
"""
|
||||
store = _preview_grant_store()
|
||||
grants: list[dict[str, Any]] = []
|
||||
for page in pages:
|
||||
if not isinstance(page, dict):
|
||||
continue
|
||||
page_no = int(page.get('page_no') or 0)
|
||||
if page_no <= 0:
|
||||
continue
|
||||
grant_token = secrets.token_urlsafe(24)
|
||||
store.setex(
|
||||
f'{PREVIEW_GRANT_KEY_PREFIX}{grant_token}',
|
||||
PREVIEW_GRANT_TTL_SECONDS,
|
||||
json.dumps({
|
||||
'document_id': int(document_id),
|
||||
'structure_analysis_id': int(structure_analysis_id),
|
||||
'actor_id': int(actor_id),
|
||||
'page_no': page_no,
|
||||
}, separators=(',', ':')),
|
||||
)
|
||||
item: dict[str, Any] = {
|
||||
'page_no': page_no,
|
||||
'preview_token': grant_token,
|
||||
}
|
||||
if page.get('width') is not None:
|
||||
item['width'] = float(page.get('width') or 0)
|
||||
if page.get('height') is not None:
|
||||
item['height'] = float(page.get('height') or 0)
|
||||
if 'drawn_echo_count' in page:
|
||||
item['drawn_echo_count'] = int(page.get('drawn_echo_count') or 0)
|
||||
grants.append(item)
|
||||
return grants
|
||||
|
||||
|
||||
def _resolve_frozen_preview_context(
|
||||
document_id: int,
|
||||
*,
|
||||
actor_id: int | None,
|
||||
) -> tuple[ShippingOrderDocument, Any, ShippingXfaStructureAnalysis, dict[str, Any]]:
|
||||
"""
|
||||
解析冻结 Layout/Analysis;禁止 document 最新 Analysis 回退。
|
||||
|
||||
Returns:
|
||||
(document, layout_version, analysis, capability)。
|
||||
"""
|
||||
if actor_id is None:
|
||||
raise NotFoundError(
|
||||
'Order profile sample not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND',
|
||||
)
|
||||
document = _require_sample_document(document_id)
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import (
|
||||
resolve_frozen_xfa_structure_analysis,
|
||||
)
|
||||
|
||||
layout_version, analysis, capability = resolve_frozen_xfa_structure_analysis(document)
|
||||
kind = str(analysis.document_kind or capability.get('document_kind') or '').strip()
|
||||
if kind and kind not in _XFA_PREVIEW_KINDS:
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
'Synthetic XFA preview is only available for xfa_hybrid/pure_xfa documents',
|
||||
details={
|
||||
'document_id': int(document.id),
|
||||
'document_kind': kind,
|
||||
'reason': 'unsupported_document_kind',
|
||||
},
|
||||
)
|
||||
_assert_capability_matches_analysis(
|
||||
capability=capability,
|
||||
analysis=analysis,
|
||||
document_id=int(document.id),
|
||||
layout_version_id=int(layout_version.id),
|
||||
)
|
||||
return document, layout_version, analysis, capability
|
||||
|
||||
|
||||
def _load_cached_ready_preview(
|
||||
*,
|
||||
document: ShippingOrderDocument,
|
||||
layout_version_id: int,
|
||||
analysis: ShippingXfaStructureAnalysis,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
读取并校验与冻结身份绑定的 ready 缓存;stale/缺失 fail-closed。
|
||||
|
||||
Returns:
|
||||
缓存预览字典(含 pages/png_bytes)。
|
||||
"""
|
||||
cache_key = _cache_key_for_analysis(analysis=analysis, document=document)
|
||||
cached = get_preview_cache(cache_key)
|
||||
if not isinstance(cached, dict):
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
'Synthetic XFA preview is not available; request generation first',
|
||||
details={
|
||||
'document_id': int(document.id),
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'reason': 'cache_miss',
|
||||
},
|
||||
)
|
||||
cached_identity = _identity_from_cached(cached)
|
||||
expected = _build_identity_context(
|
||||
document=document,
|
||||
layout_version_id=layout_version_id,
|
||||
analysis=analysis,
|
||||
preview_render_checksum=(
|
||||
cached_identity.preview_render_checksum if cached_identity else ''
|
||||
),
|
||||
page_count=int(cached.get('page_count') or 0),
|
||||
)
|
||||
if cached_identity is None or is_preview_identity_stale(
|
||||
expected=expected,
|
||||
actual=cached_identity,
|
||||
):
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_STALE,
|
||||
'Synthetic XFA preview cache is stale relative to frozen analysis identity',
|
||||
details={
|
||||
'document_id': int(document.id),
|
||||
'layout_version_id': layout_version_id,
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'reason': 'preview_identity_stale',
|
||||
},
|
||||
)
|
||||
status = str(cached.get('status') or '').strip()
|
||||
if status != 'ready':
|
||||
short = str(cached.get('error_code') or XFA_PREVIEW_UNAVAILABLE)
|
||||
_raise_preview_error(
|
||||
short if short.startswith('XFA_PREVIEW_') else XFA_PREVIEW_UNAVAILABLE,
|
||||
'Synthetic XFA preview is not ready',
|
||||
details={
|
||||
'document_id': int(document.id),
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'status': status,
|
||||
'reason': 'preview_not_ready',
|
||||
},
|
||||
)
|
||||
return cached
|
||||
|
||||
|
||||
def build_xfa_preview_definition_meta(cached: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
从合成预览缓存构造可写入 definition.xfa_preview 的发布证据摘要。
|
||||
|
||||
核心逻辑:剥离 png_bytes,保留 status/checksum/renderer_version 与逐页
|
||||
source/synthetic page box + page_identity_hash,供 publish gate(BE-3)消费。
|
||||
|
||||
Args:
|
||||
cached: 预览缓存字典(compose 结果或 get_preview_cache 命中)。
|
||||
|
||||
Returns:
|
||||
definition.xfa_preview 兼容字典(无大图)。
|
||||
"""
|
||||
diagnostics = cached.get('diagnostics') if isinstance(cached.get('diagnostics'), dict) else {}
|
||||
page_count = int(cached.get('page_count') or 0)
|
||||
status = str(cached.get('status') or '').strip().lower()
|
||||
page_evidence = diagnostics.get('pages') if isinstance(diagnostics.get('pages'), list) else []
|
||||
safe_pages: list[dict[str, Any]] = []
|
||||
for raw in page_evidence:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
safe_pages.append({
|
||||
'page_no': raw.get('page_no'),
|
||||
'source_page_box': raw.get('source_page_box'),
|
||||
'synthetic_page_box': raw.get('synthetic_page_box'),
|
||||
'page_identity_hash': raw.get('page_identity_hash'),
|
||||
})
|
||||
source_count = diagnostics.get('source_page_count')
|
||||
synthetic_count = diagnostics.get('synthetic_page_count')
|
||||
if source_count is None:
|
||||
source_count = page_count if safe_pages else None
|
||||
if synthetic_count is None:
|
||||
synthetic_count = page_count if safe_pages else None
|
||||
return {
|
||||
'status': cached.get('status'),
|
||||
'preview_render_checksum': cached.get('preview_render_checksum'),
|
||||
'render_mode': cached.get('render_mode') or RENDER_MODE,
|
||||
'renderer_version': cached.get('renderer_version') or RENDERER_VERSION,
|
||||
'page_count': page_count,
|
||||
'pages_ready': list(range(1, page_count + 1)) if status == 'ready' and page_count > 0 else [],
|
||||
'source_page_count': source_count,
|
||||
'synthetic_page_count': synthetic_count,
|
||||
'pages': safe_pages,
|
||||
}
|
||||
|
||||
|
||||
def _public_preview_payload(
|
||||
*,
|
||||
cached: dict[str, Any],
|
||||
page_grants: list[dict[str, Any]],
|
||||
cache_hit: bool,
|
||||
) -> dict[str, Any]:
|
||||
"""构造 API 安全响应(不含 png_bytes;含 definition_preview_meta 供草稿落库)。"""
|
||||
identity = cached.get('identity') if isinstance(cached.get('identity'), dict) else {}
|
||||
diagnostics = cached.get('diagnostics') if isinstance(cached.get('diagnostics'), dict) else {}
|
||||
definition_meta = build_xfa_preview_definition_meta(cached)
|
||||
safe_diagnostics = {
|
||||
key: diagnostics[key]
|
||||
for key in (
|
||||
'reason',
|
||||
'drawn_echo_count',
|
||||
'leaf_count',
|
||||
'widget_count',
|
||||
'source_page_count',
|
||||
'synthetic_page_count',
|
||||
'pages',
|
||||
)
|
||||
if key in diagnostics
|
||||
}
|
||||
if 'pages' not in safe_diagnostics and definition_meta.get('pages'):
|
||||
safe_diagnostics['pages'] = definition_meta['pages']
|
||||
if 'source_page_count' not in safe_diagnostics and definition_meta.get('source_page_count') is not None:
|
||||
safe_diagnostics['source_page_count'] = definition_meta['source_page_count']
|
||||
if 'synthetic_page_count' not in safe_diagnostics and definition_meta.get('synthetic_page_count') is not None:
|
||||
safe_diagnostics['synthetic_page_count'] = definition_meta['synthetic_page_count']
|
||||
return {
|
||||
'document_id': identity.get('document_id'),
|
||||
'identity': identity,
|
||||
'status': cached.get('status'),
|
||||
'error_code': shipping_error_code_for_preview(cached.get('error_code')),
|
||||
'render_mode': cached.get('render_mode') or RENDER_MODE,
|
||||
'renderer_version': cached.get('renderer_version') or RENDERER_VERSION,
|
||||
'page_count': int(cached.get('page_count') or 0),
|
||||
'preview_render_checksum': cached.get('preview_render_checksum'),
|
||||
'pages': page_grants,
|
||||
'expires_in_seconds': PREVIEW_GRANT_TTL_SECONDS,
|
||||
'cache_hit': bool(cache_hit),
|
||||
'diagnostics': safe_diagnostics,
|
||||
# BE-3:前端/保存草稿直接写入 definition.xfa_preview,避免发布时缺页身份证据
|
||||
'definition_preview_meta': definition_meta,
|
||||
'source_page_count': definition_meta.get('source_page_count'),
|
||||
'synthetic_page_count': definition_meta.get('synthetic_page_count'),
|
||||
}
|
||||
|
||||
|
||||
def request_xfa_synthetic_preview(
|
||||
document_id: int,
|
||||
*,
|
||||
actor_id: int | None,
|
||||
force: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为冻结 Layout Analysis 生成或复用合成预览,并签发页级短时 token。
|
||||
|
||||
核心逻辑:
|
||||
1. resolve_frozen_xfa_structure_analysis(禁止最新 Analysis 回退);
|
||||
2. 命中且身份一致的 ready 缓存则复用;
|
||||
3. 否则读 PDF → 即时解析 datasets 并校验指纹 → compose_xfa_dataset_preview_pages;
|
||||
4. 写入 xfa_preview_cache;返回身份 + 状态 + 页元数据(无大图)。
|
||||
|
||||
Args:
|
||||
document_id: ShippingOrderDocument 主键。
|
||||
actor_id: 管理员 ID(必填)。
|
||||
force: True 时忽略 ready 缓存强制重生成。
|
||||
|
||||
Returns:
|
||||
预览摘要字典(含 pages[].preview_token)。
|
||||
|
||||
Raises:
|
||||
NotFoundError / ValidationError: 样本缺失或身份/合成失败。
|
||||
"""
|
||||
document, layout_version, analysis, _capability = _resolve_frozen_preview_context(
|
||||
document_id, actor_id=actor_id,
|
||||
)
|
||||
_audit(
|
||||
document_id=int(document.id),
|
||||
event_type='xfa_preview_requested',
|
||||
actor_id=actor_id,
|
||||
detail={
|
||||
'layout_version_id': int(layout_version.id),
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'force': bool(force),
|
||||
},
|
||||
)
|
||||
|
||||
cache_key = _cache_key_for_analysis(analysis=analysis, document=document)
|
||||
cached = None if force else get_preview_cache(cache_key)
|
||||
cache_hit = False
|
||||
if isinstance(cached, dict) and str(cached.get('status') or '') == 'ready':
|
||||
try:
|
||||
cached = _load_cached_ready_preview(
|
||||
document=document,
|
||||
layout_version_id=int(layout_version.id),
|
||||
analysis=analysis,
|
||||
)
|
||||
cache_hit = True
|
||||
except ValidationError:
|
||||
cached = None
|
||||
|
||||
if not cache_hit:
|
||||
# [STEP 1] 读取 PDF 并即时解析 datasets,校验与冻结 Analysis 身份一致
|
||||
asset = db.session.get(FileAsset, int(document.asset_id or 0)) if document.asset_id else None
|
||||
if asset is None:
|
||||
_audit(
|
||||
document_id=int(document.id),
|
||||
event_type='xfa_preview_failed',
|
||||
actor_id=actor_id,
|
||||
detail={'reason': 'asset_missing', 'structure_analysis_id': int(analysis.id)},
|
||||
)
|
||||
db.session.commit()
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
'XFA sample asset is unavailable for synthetic preview',
|
||||
details={'document_id': int(document.id), 'reason': 'asset_missing'},
|
||||
)
|
||||
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf
|
||||
|
||||
try:
|
||||
pdf_bytes = read_asset_bytes(asset)
|
||||
except Exception as exc: # noqa: BLE001 — 读失败统一 UNAVAILABLE
|
||||
_audit(
|
||||
document_id=int(document.id),
|
||||
event_type='xfa_preview_failed',
|
||||
actor_id=actor_id,
|
||||
detail={'reason': 'asset_read_failed', 'structure_analysis_id': int(analysis.id)},
|
||||
)
|
||||
db.session.commit()
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
'Failed to read XFA sample bytes for synthetic preview',
|
||||
details={'document_id': int(document.id), 'reason': 'asset_read_failed', 'detail': str(exc)[:200]},
|
||||
)
|
||||
|
||||
outcome = analyze_xfa_pdf(pdf_bytes)
|
||||
live_cap = (
|
||||
(outcome.snapshot or {}).get('xfa_capability')
|
||||
if isinstance(outcome.snapshot, dict)
|
||||
else {}
|
||||
)
|
||||
if not isinstance(live_cap, dict):
|
||||
live_cap = {}
|
||||
try:
|
||||
_assert_live_packets_match_analysis(
|
||||
analysis=analysis,
|
||||
live_capability=live_cap,
|
||||
document_id=int(document.id),
|
||||
)
|
||||
except ValidationError:
|
||||
_audit(
|
||||
document_id=int(document.id),
|
||||
event_type='xfa_preview_failed',
|
||||
actor_id=actor_id,
|
||||
detail={
|
||||
'reason': 'value_mismatch',
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'error_code': XFA_PREVIEW_VALUE_MISMATCH,
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
raise
|
||||
|
||||
if outcome.dataset_analysis is None:
|
||||
_audit(
|
||||
document_id=int(document.id),
|
||||
event_type='xfa_preview_failed',
|
||||
actor_id=actor_id,
|
||||
detail={'reason': 'dataset_analysis_missing', 'structure_analysis_id': int(analysis.id)},
|
||||
)
|
||||
db.session.commit()
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_UNAVAILABLE,
|
||||
'XFA datasets analysis is unavailable for synthetic preview',
|
||||
details={'document_id': int(document.id), 'reason': 'dataset_analysis_missing'},
|
||||
)
|
||||
|
||||
# [STEP 2] 合成预览页
|
||||
template_bytes = None
|
||||
if outcome.packet_result is not None:
|
||||
template_bytes = outcome.packet_result.packet_bytes_by_name.get('template')
|
||||
compose_result = compose_xfa_dataset_preview_pages(
|
||||
pdf_bytes=pdf_bytes,
|
||||
analysis_or_nodes=outcome.dataset_analysis,
|
||||
template_bytes=template_bytes,
|
||||
)
|
||||
identity = _build_identity_context(
|
||||
document=document,
|
||||
layout_version_id=int(layout_version.id),
|
||||
analysis=analysis,
|
||||
preview_render_checksum=str(compose_result.preview_render_checksum or ''),
|
||||
page_count=int(compose_result.page_count or 0),
|
||||
)
|
||||
cached = {
|
||||
'identity': preview_identity_to_dict(identity),
|
||||
'status': compose_result.status,
|
||||
'error_code': compose_result.error_code,
|
||||
'render_mode': compose_result.render_mode,
|
||||
'renderer_version': compose_result.renderer_version,
|
||||
'page_count': compose_result.page_count,
|
||||
'preview_render_checksum': compose_result.preview_render_checksum,
|
||||
'pages': list(compose_result.pages or []),
|
||||
'diagnostics': dict(compose_result.diagnostics or {}),
|
||||
}
|
||||
set_preview_cache(cache_key, cached)
|
||||
|
||||
if compose_result.status != 'ready':
|
||||
_audit(
|
||||
document_id=int(document.id),
|
||||
event_type='xfa_preview_failed',
|
||||
actor_id=actor_id,
|
||||
detail={
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'status': compose_result.status,
|
||||
'error_code': compose_result.error_code,
|
||||
'diagnostics': {
|
||||
key: compose_result.diagnostics.get(key)
|
||||
for key in ('reason', 'drawn_echo_count')
|
||||
if key in (compose_result.diagnostics or {})
|
||||
},
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
short = str(compose_result.error_code or XFA_PREVIEW_FAILED)
|
||||
_raise_preview_error(
|
||||
short if short.startswith('XFA_PREVIEW_') else XFA_PREVIEW_FAILED,
|
||||
'Synthetic XFA preview generation failed',
|
||||
details={
|
||||
'document_id': int(document.id),
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'status': compose_result.status,
|
||||
'error_code': short,
|
||||
},
|
||||
)
|
||||
|
||||
_audit(
|
||||
document_id=int(document.id),
|
||||
event_type='xfa_preview_generated',
|
||||
actor_id=actor_id,
|
||||
detail={
|
||||
'layout_version_id': int(layout_version.id),
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'page_count': int(compose_result.page_count or 0),
|
||||
'preview_render_checksum': compose_result.preview_render_checksum,
|
||||
'renderer_version': RENDERER_VERSION,
|
||||
},
|
||||
)
|
||||
|
||||
page_metas = _page_metas_without_images(list(cached.get('pages') or []))
|
||||
page_grants = _issue_page_grants(
|
||||
document_id=int(document.id),
|
||||
structure_analysis_id=int(analysis.id),
|
||||
actor_id=int(actor_id),
|
||||
pages=page_metas,
|
||||
)
|
||||
db.session.commit()
|
||||
return _public_preview_payload(cached=cached, page_grants=page_grants, cache_hit=cache_hit)
|
||||
|
||||
|
||||
def list_xfa_synthetic_preview_pages(
|
||||
document_id: int,
|
||||
*,
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
列出绑定冻结 Analysis 的最新 ready 合成预览页元数据并重新签发 token。
|
||||
|
||||
核心逻辑:resolve_frozen → 校验缓存身份 → 无图元数据 + grant。
|
||||
|
||||
Args:
|
||||
document_id: 样本文档主键。
|
||||
actor_id: 管理员 ID。
|
||||
|
||||
Returns:
|
||||
与 request 同形的预览摘要(cache_hit=True)。
|
||||
"""
|
||||
document, layout_version, analysis, _capability = _resolve_frozen_preview_context(
|
||||
document_id, actor_id=actor_id,
|
||||
)
|
||||
cached = _load_cached_ready_preview(
|
||||
document=document,
|
||||
layout_version_id=int(layout_version.id),
|
||||
analysis=analysis,
|
||||
)
|
||||
page_metas = _page_metas_without_images(list(cached.get('pages') or []))
|
||||
page_grants = _issue_page_grants(
|
||||
document_id=int(document.id),
|
||||
structure_analysis_id=int(analysis.id),
|
||||
actor_id=int(actor_id),
|
||||
pages=page_metas,
|
||||
)
|
||||
_audit(
|
||||
document_id=int(document.id),
|
||||
event_type='xfa_preview_viewed',
|
||||
actor_id=actor_id,
|
||||
detail={
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'layout_version_id': int(layout_version.id),
|
||||
'page_count': int(cached.get('page_count') or 0),
|
||||
'mode': 'list_pages',
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return _public_preview_payload(cached=cached, page_grants=page_grants, cache_hit=True)
|
||||
|
||||
|
||||
def render_xfa_synthetic_preview_page(
|
||||
document_id: int,
|
||||
*,
|
||||
page_no: int,
|
||||
token: str,
|
||||
actor_id: int | None,
|
||||
) -> bytes:
|
||||
"""
|
||||
消费一次性 token,返回绑定冻结 Analysis 的合成预览单页 PNG。
|
||||
|
||||
核心逻辑:校验 grant → 再校验冻结身份与缓存 → 取出 png_bytes。
|
||||
|
||||
Args:
|
||||
document_id: 样本文档主键。
|
||||
page_no: 1-based 页码。
|
||||
token: preview_token。
|
||||
actor_id: 管理员 ID。
|
||||
|
||||
Returns:
|
||||
PNG 字节。
|
||||
|
||||
Raises:
|
||||
NotFoundError: token 无效/重放/越权。
|
||||
ValidationError: 预览 stale 或页不存在。
|
||||
"""
|
||||
store = _preview_grant_store()
|
||||
raw_grant = store.getdel(f'{PREVIEW_GRANT_KEY_PREFIX}{str(token or "")}')
|
||||
try:
|
||||
grant = json.loads(raw_grant) if raw_grant else None
|
||||
except (TypeError, json.JSONDecodeError):
|
||||
grant = None
|
||||
if (
|
||||
not isinstance(grant, dict)
|
||||
or actor_id is None
|
||||
or grant.get('actor_id') != int(actor_id)
|
||||
or grant.get('page_no') != int(page_no)
|
||||
or grant.get('document_id') != int(document_id)
|
||||
):
|
||||
raise NotFoundError(
|
||||
'Order profile XFA synthetic preview not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND',
|
||||
)
|
||||
|
||||
document, layout_version, analysis, _capability = _resolve_frozen_preview_context(
|
||||
document_id, actor_id=actor_id,
|
||||
)
|
||||
if int(grant.get('structure_analysis_id') or 0) != int(analysis.id):
|
||||
_raise_preview_error(
|
||||
XFA_PREVIEW_STALE,
|
||||
'Synthetic preview grant is bound to a different frozen analysis',
|
||||
details={
|
||||
'document_id': int(document.id),
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'grant_structure_analysis_id': grant.get('structure_analysis_id'),
|
||||
'reason': 'grant_analysis_mismatch',
|
||||
},
|
||||
)
|
||||
|
||||
cached = _load_cached_ready_preview(
|
||||
document=document,
|
||||
layout_version_id=int(layout_version.id),
|
||||
analysis=analysis,
|
||||
)
|
||||
page = next(
|
||||
(
|
||||
item for item in (cached.get('pages') or [])
|
||||
if isinstance(item, dict) and int(item.get('page_no') or 0) == int(page_no)
|
||||
),
|
||||
None,
|
||||
)
|
||||
png = page.get('png_bytes') if isinstance(page, dict) else None
|
||||
if not isinstance(png, (bytes, bytearray)) or not png:
|
||||
raise NotFoundError(
|
||||
'Order profile XFA synthetic preview page not found',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND',
|
||||
)
|
||||
|
||||
_audit(
|
||||
document_id=int(document.id),
|
||||
event_type='xfa_preview_viewed',
|
||||
actor_id=actor_id,
|
||||
detail={
|
||||
'structure_analysis_id': int(analysis.id),
|
||||
'layout_version_id': int(layout_version.id),
|
||||
'page_no': int(page_no),
|
||||
'mode': 'page_png',
|
||||
},
|
||||
)
|
||||
db.session.commit()
|
||||
return bytes(png)
|
||||
@@ -336,6 +336,7 @@ def persist_order_extraction_result(
|
||||
documents_by_intake: dict[int, list[ShippingOrderDocument]] = {}
|
||||
for document in documents:
|
||||
documents_by_intake.setdefault(int(document.intake_id), []).append(document)
|
||||
scoped_document_ids = {int(document.id) for document in documents}
|
||||
|
||||
class_threshold = float(current_app.config.get('SHIPPING_NOTICE_ORDER_CLASSIFICATION_CONFIDENCE') or 0.85)
|
||||
auto_candidates: list[ShippingOrderCandidate] = []
|
||||
@@ -351,6 +352,7 @@ def persist_order_extraction_result(
|
||||
# [STEP 1] 新 Run 先撤销旧版本候选的可消费资格;旧记录仍保留用于审计与重识别失败回退。
|
||||
current_candidates = db.session.query(ShippingOrderCandidate).filter(
|
||||
ShippingOrderCandidate.intake_id.in_([int(row.id) for row in intakes]),
|
||||
ShippingOrderCandidate.primary_document_id.in_(tuple(scoped_document_ids)),
|
||||
ShippingOrderCandidate.consumed_task_id.is_(None),
|
||||
ShippingOrderCandidate.is_current_version.is_(True),
|
||||
)
|
||||
@@ -752,7 +754,6 @@ def persist_order_extraction_result(
|
||||
# [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(ShippingOrderCandidate).filter(
|
||||
|
||||
@@ -27,7 +27,8 @@ import json
|
||||
import logging
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import date, datetime, timedelta
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -104,6 +105,37 @@ def _canonical_json(payload: Any) -> str:
|
||||
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
|
||||
|
||||
|
||||
def _freeze_json_snapshot(payload: Any) -> Any:
|
||||
"""
|
||||
将 Run 冻结输入转换为数据库 JSON 列可持久化的原生值。
|
||||
|
||||
核心逻辑:订单字段规范化会产生 ``date`` 和 ``Decimal``;它们可参与内存中的
|
||||
裁决,但不能直接写入 SQLAlchemy JSON 列。冻结边界统一转为无损文本,避免请求
|
||||
哈希的 ``default=str`` 掩盖了后续 flush 失败。
|
||||
|
||||
Args:
|
||||
payload: 已构建但尚未持久化的 Run 输入快照,只允许 JSON 容器和业务标量。
|
||||
|
||||
Returns:
|
||||
仅含 JSON 原生类型的等价冻结快照;日期和时间为 ISO 8601 字符串,十进制为
|
||||
无科学计数法的字符串。
|
||||
|
||||
Raises:
|
||||
TypeError: 快照包含未声明的非 JSON 业务对象时抛出,禁止静默序列化。
|
||||
"""
|
||||
if payload is None or isinstance(payload, (str, int, float, bool)):
|
||||
return payload
|
||||
if isinstance(payload, (date, datetime)):
|
||||
return payload.isoformat()
|
||||
if isinstance(payload, Decimal):
|
||||
return format(payload, 'f')
|
||||
if isinstance(payload, dict):
|
||||
return {str(key): _freeze_json_snapshot(value) for key, value in payload.items()}
|
||||
if isinstance(payload, (list, tuple)):
|
||||
return [_freeze_json_snapshot(value) for value in payload]
|
||||
raise TypeError(f'Unsupported Run snapshot value: {type(payload).__name__}')
|
||||
|
||||
|
||||
def _sha256(payload: Any) -> str:
|
||||
"""返回业务输入的 SHA-256;输入必须先经过稳定 JSON 编码。"""
|
||||
return hashlib.sha256(_canonical_json(payload).encode('ascii')).hexdigest()
|
||||
@@ -940,7 +972,9 @@ def _build_snapshot(
|
||||
reason='documents_incomplete',
|
||||
),
|
||||
)
|
||||
return {
|
||||
# _build_snapshot 是所有 Run 输入重建路径的共同出口;在此冻结才能避免 Worker
|
||||
# 物化、扩批或重试绕过创建路径的 JSON 原生值约束。
|
||||
return _freeze_json_snapshot({
|
||||
'snapshot_version': 3,
|
||||
'user_id': user_id,
|
||||
'owner_agent_id': owner_agent_id,
|
||||
@@ -982,7 +1016,101 @@ def _build_snapshot(
|
||||
for intake in intakes
|
||||
],
|
||||
'attachment_selection': selection_snapshot,
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
def synchronize_order_extraction_expansion_snapshot(
|
||||
run: ShippingOrderProcessingRun,
|
||||
*,
|
||||
selection_batch: int,
|
||||
) -> None:
|
||||
"""将已物化的历史扩批附件补入 Run/Plan 冻结快照。
|
||||
|
||||
AI 触发时机:无需直接调用;订单 Worker 在旧版延迟扩批路径物化附件后调用。
|
||||
核心逻辑:扩批不是读取当前 Intake 的隐式范围扩大,而是把冻结选择计划中该批
|
||||
附件显式提升为已选,再重建同一 Schema 下的 Document 快照并同步 Plan 哈希。
|
||||
这样新增 Unit 在运行时仍能从其所属 Run 的冻结输入定位,避免留下孤立 Unit。
|
||||
|
||||
Args:
|
||||
run: 已锁定、已完成目标批次 Document 物化的订单抽取 Run。
|
||||
selection_batch: 大于 1 的历史扩批编号。
|
||||
"""
|
||||
normalized_batch = int(selection_batch or 0)
|
||||
if normalized_batch <= 1:
|
||||
return
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
raw_selection = snapshot.get('attachment_selection')
|
||||
if not isinstance(raw_selection, dict):
|
||||
raise ValidationError(
|
||||
'Frozen attachment selection is unavailable',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
|
||||
)
|
||||
selection = json.loads(_canonical_json(raw_selection))
|
||||
selected_now = 0
|
||||
for row in selection.get('items') or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
row_batch = int(row.get('selection_batch') or row.get('planned_selection_batch') or 0)
|
||||
if row_batch != normalized_batch:
|
||||
continue
|
||||
row['selected'] = True
|
||||
row['selection_batch'] = normalized_batch
|
||||
row.pop('planned_selection_batch', None)
|
||||
selected_now += 1
|
||||
if not selected_now:
|
||||
raise ValidationError(
|
||||
'Frozen extraction attachment batch is unavailable',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
|
||||
)
|
||||
selection['selected_attachment_count'] = sum(
|
||||
1 for row in selection.get('items') or []
|
||||
if isinstance(row, dict) and bool(row.get('selected'))
|
||||
)
|
||||
pending_batches = selection.get('pending_expansion_batches')
|
||||
if isinstance(pending_batches, dict):
|
||||
pending_batches.pop(str(normalized_batch), None)
|
||||
pending_batches.pop(normalized_batch, None)
|
||||
|
||||
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
schema_version_id = int(schema.get('schema_version_id') or run.schema_version_id or 0)
|
||||
schema_version = db.session.get(ShippingOrderSchemaVersion, schema_version_id)
|
||||
if schema_version is None:
|
||||
raise ValidationError(
|
||||
'Frozen order schema is unavailable',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
|
||||
)
|
||||
intake_ids = [
|
||||
int(item.get('intake_id'))
|
||||
for item in snapshot.get('intakes') or []
|
||||
if isinstance(item, dict) and item.get('intake_id') is not None
|
||||
]
|
||||
intakes = (
|
||||
ShippingOrderIntake.query.filter(ShippingOrderIntake.id.in_(intake_ids))
|
||||
.order_by(ShippingOrderIntake.id.asc())
|
||||
.all()
|
||||
) if intake_ids else []
|
||||
if len(intakes) != len(set(intake_ids)):
|
||||
raise ValidationError(
|
||||
'Frozen shipping notice intake is unavailable',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
|
||||
)
|
||||
refreshed = _build_snapshot(
|
||||
user_id=int(run.user_id),
|
||||
owner_agent_id=int(run.owner_agent_id),
|
||||
conversation_id=str(run.conversation_id or ''),
|
||||
intakes=intakes,
|
||||
schema_version=schema_version,
|
||||
attachment_selection=selection,
|
||||
)
|
||||
for key in ('auto_freeze_policy', 'upload_batch_id', 'review_reparse'):
|
||||
if key in snapshot:
|
||||
refreshed[key] = snapshot[key]
|
||||
run.input_snapshot_json = refreshed
|
||||
run.input_snapshot_hash = _sha256(refreshed)
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
if plan is not None:
|
||||
plan.input_snapshot_hash = str(run.input_snapshot_hash)
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _run_snapshot_document_ids(run: ShippingOrderProcessingRun) -> set[int]:
|
||||
@@ -1288,6 +1416,24 @@ def materialize_order_extraction_run_inputs(
|
||||
from sqlalchemy.orm.attributes import flag_modified
|
||||
flag_modified(run, 'input_snapshot_json')
|
||||
run.input_snapshot_hash = _sha256(snapshot)
|
||||
# 此分支只允许同一冻结 Document 集合的布局证据刷新;Plan 的
|
||||
# input_snapshot_hash 因而必须与 Run 同步,避免随后幂等校验把
|
||||
# 自己刚写入的证据更新误判为外部篡改。
|
||||
plan_document_ids = {
|
||||
int(unit.document_id)
|
||||
for unit in existing_plan.units
|
||||
}
|
||||
snapshot_document_ids = {
|
||||
int(document.id)
|
||||
for document in documents
|
||||
if str(document.document_type or '') != 'email_body'
|
||||
}
|
||||
if plan_document_ids != snapshot_document_ids:
|
||||
raise ConflictError(
|
||||
'Order extraction plan documents do not match the frozen run',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PLAN_CHANGED',
|
||||
)
|
||||
existing_plan.input_snapshot_hash = run.input_snapshot_hash
|
||||
db.session.flush()
|
||||
return ensure_order_extraction_plan(run)
|
||||
db.session.delete(existing_plan)
|
||||
@@ -1349,9 +1495,18 @@ def materialize_order_extraction_run_inputs(
|
||||
return ensure_order_extraction_plan(run)
|
||||
|
||||
|
||||
def _active_run_for_intakes(intake_ids: list[int]) -> ShippingOrderProcessingRun | None:
|
||||
"""读取占用任一 Intake 的未释放 Run,供并发唯一约束冲突后返回明确业务结果。"""
|
||||
return (
|
||||
def _active_run_for_intakes(
|
||||
intake_ids: list[int],
|
||||
*,
|
||||
selected_document_id: int | None = None,
|
||||
) -> ShippingOrderProcessingRun | None:
|
||||
"""
|
||||
读取占用输入的活动 Run;PDF 级重解析按同一目标 Document 互斥。
|
||||
|
||||
同一 EML 的不同 PDF 可在同一次批次重解析中并行创建子 Run;没有目标
|
||||
Document 的普通 Intake 提交仍保持 Intake 级互斥,避免放宽到无边界并发。
|
||||
"""
|
||||
rows = (
|
||||
db.session.query(ShippingOrderProcessingRun)
|
||||
.join(ShippingOrderProcessingRunIntake)
|
||||
.filter(
|
||||
@@ -1359,8 +1514,15 @@ def _active_run_for_intakes(intake_ids: list[int]) -> ShippingOrderProcessingRun
|
||||
ShippingOrderProcessingRunIntake.released_at.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderProcessingRun.created_at.desc())
|
||||
.first()
|
||||
.all()
|
||||
)
|
||||
if selected_document_id is None:
|
||||
return rows[0] if rows else None
|
||||
target_id = int(selected_document_id)
|
||||
for row in rows:
|
||||
if _run_snapshot_document_ids(row) == {target_id}:
|
||||
return row
|
||||
return None
|
||||
|
||||
|
||||
def _active_run_for_conversation(
|
||||
@@ -1705,6 +1867,7 @@ def create_order_extraction_run(
|
||||
reparse_source_candidate_id: int | None = None,
|
||||
reparse_source_order_task_no: str | None = None,
|
||||
reparse_requested_by_user_id: int | None = None,
|
||||
batch_reparse_id: str | None = None,
|
||||
allow_parallel_conversation_runs: bool = True,
|
||||
composer_context_id: str | None = None,
|
||||
client_submission_id: str | None = None,
|
||||
@@ -1736,6 +1899,7 @@ def create_order_extraction_run(
|
||||
reparse_source_candidate_id: 复核 Case 原 Candidate;换绑时校验禁止串到兄弟 OT。
|
||||
reparse_source_order_task_no: Case 对应 OT(可为兄弟号);须与 user_task_no 一致。
|
||||
reparse_requested_by_user_id: 发起重识别的用户;审计发起人,执行主体仍为 system。
|
||||
batch_reparse_id: 批次重解析请求号;仅作为跨文件子 Run 的不可变审计关联。
|
||||
allow_parallel_conversation_runs: False 时恢复旧「同会话仅一活跃」冲突(测试/兼容)。
|
||||
composer_context_id: 输入区短生命周期上下文;非业务主键。
|
||||
client_submission_id: 客户端提交幂等键。
|
||||
@@ -1861,6 +2025,54 @@ def create_order_extraction_run(
|
||||
}
|
||||
if int(reparse_attempt_no or 0) > 0:
|
||||
snapshot['review_reparse']['attempt_no'] = int(reparse_attempt_no)
|
||||
if str(batch_reparse_id or '').strip():
|
||||
snapshot['review_reparse']['batch_reparse_id'] = str(batch_reparse_id).strip()[:64]
|
||||
|
||||
# [STEP] 新建/重解析 Run 在冻结输入前补齐压缩布局的按需坐标证据。
|
||||
# 这样正常解析、单文件重解析和批量重试不会因入口不同而得到不同的
|
||||
# tables/coordinate_evidence 快照;证据恢复成功时同时写回正式 LayoutVersion。
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
hydrated_layouts: dict[int, dict[str, Any]] = {}
|
||||
for raw_intake in snapshot.get('intakes') or []:
|
||||
if not isinstance(raw_intake, dict):
|
||||
continue
|
||||
for raw_document in raw_intake.get('documents') or []:
|
||||
if not isinstance(raw_document, dict):
|
||||
continue
|
||||
document_id = int(raw_document.get('document_id') or 0)
|
||||
filename = str(raw_document.get('filename') or '').lower()
|
||||
layout = raw_document.get('layout_snapshot') if isinstance(raw_document.get('layout_snapshot'), dict) else {}
|
||||
if document_id <= 0 or not filename.endswith('.pdf') or not layout:
|
||||
continue
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
if isinstance(evidence.get('page_glyphs'), dict) and evidence.get('page_glyphs'):
|
||||
continue
|
||||
document = db.session.get(ShippingOrderDocument, document_id)
|
||||
if document is None:
|
||||
continue
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
enriched = ensure_on_demand_coordinate_evidence(
|
||||
document=document,
|
||||
layout=layout,
|
||||
page_nos={int(item.get('page_no') or 1) for item in tables} or {1},
|
||||
table_by_page={int(item.get('page_no') or 1): item for item in tables},
|
||||
)
|
||||
next_evidence = enriched.get('coordinate_evidence') if isinstance(enriched, dict) else None
|
||||
if isinstance(next_evidence, dict) and isinstance(next_evidence.get('page_glyphs'), dict) and next_evidence.get('page_glyphs'):
|
||||
record_inline_layout_snapshot(document, enriched)
|
||||
hydrated_layouts[document_id] = enriched
|
||||
for raw_intake in snapshot.get('intakes') or []:
|
||||
if not isinstance(raw_intake, dict):
|
||||
continue
|
||||
for raw_document in raw_intake.get('documents') or []:
|
||||
if isinstance(raw_document, dict) and int(raw_document.get('document_id') or 0) in hydrated_layouts:
|
||||
raw_document['layout_snapshot'] = hydrated_layouts[int(raw_document['document_id'])]
|
||||
# [STEP] 先压平为 JSON 原生快照,再计算哈希和写入两份 JSON 列;否则 date/Decimal
|
||||
# 会被哈希的 default=str 掩盖,却在 db.session.flush() 时以 500 失败。
|
||||
snapshot = _freeze_json_snapshot(snapshot)
|
||||
snapshot_hash = _sha256(snapshot)
|
||||
idempotency_key = _sha256({
|
||||
'user_id': user.id,
|
||||
@@ -1883,13 +2095,16 @@ def create_order_extraction_run(
|
||||
'reparse_source_order_task_no': (
|
||||
str(reparse_source_order_task_no or '').strip() or None
|
||||
),
|
||||
'batch_reparse_id': str(batch_reparse_id or '').strip() or None,
|
||||
})
|
||||
if selected_document_id is not None and isinstance(snapshot.get('review_reparse'), dict):
|
||||
snapshot['review_reparse']['idempotency_key'] = idempotency_key
|
||||
existing = _run_by_idempotency_key(idempotency_key)
|
||||
if existing is not None:
|
||||
return existing, True
|
||||
active = _active_run_for_intakes([intake.id for intake in intakes])
|
||||
active = _active_run_for_intakes(
|
||||
[intake.id for intake in intakes], selected_document_id=selected_document_id,
|
||||
)
|
||||
if active is not None:
|
||||
raise ConflictError(
|
||||
'A selected intake already belongs to another active extraction run',
|
||||
@@ -2087,7 +2302,9 @@ def create_order_extraction_run(
|
||||
existing = _run_by_idempotency_key(idempotency_key)
|
||||
if existing is not None:
|
||||
return existing, True
|
||||
active = _active_run_for_intakes([intake.id for intake in intakes])
|
||||
active = _active_run_for_intakes(
|
||||
[intake.id for intake in intakes], selected_document_id=selected_document_id,
|
||||
)
|
||||
if active is not None:
|
||||
raise ConflictError(
|
||||
'A selected intake already belongs to another active extraction run',
|
||||
@@ -2878,6 +3095,106 @@ def retry_order_extraction_run(*, user_id: int, run_no: str) -> tuple[ShippingOr
|
||||
details={'run_no': conflicting_run.run_no},
|
||||
)
|
||||
|
||||
# [STEP] 重试前先把压缩布局快照补齐为正式坐标证据。
|
||||
# 正常单文件重解析会经过独立的布局/坐标准备;Run 级批量重试不能只把
|
||||
# failed→pending 后直接入队,否则 Worker 会继续读取 tables 存在但
|
||||
# coordinate_evidence.page_glyphs/tables 为空的旧冻结快照,最终得到
|
||||
# unique_match + business_table_not_found。
|
||||
snapshot_refreshed = False
|
||||
retry_layouts_by_document_id: dict[int, dict[str, Any]] = {}
|
||||
snapshot_documents = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
for raw_intake in snapshot_documents.get('intakes') or []:
|
||||
if not isinstance(raw_intake, dict):
|
||||
continue
|
||||
for raw_document in raw_intake.get('documents') or []:
|
||||
if not isinstance(raw_document, dict):
|
||||
continue
|
||||
document_id = int(raw_document.get('document_id') or 0)
|
||||
if document_id <= 0:
|
||||
continue
|
||||
unit = next((item for item in (run.extraction_plan.units if run.extraction_plan else [])
|
||||
if int(item.document_id or 0) == document_id and item.status == 'failed'), None)
|
||||
if unit is None:
|
||||
continue
|
||||
document = db.session.get(ShippingOrderDocument, document_id)
|
||||
if document is None or str(document.filename or '').lower().rsplit('.', 1)[-1] != 'pdf':
|
||||
continue
|
||||
layout = raw_document.get('layout_snapshot') if isinstance(raw_document.get('layout_snapshot'), dict) else {}
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
page_nos = {int(item.get('page_no') or 1) for item in tables}
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
record_inline_layout_snapshot,
|
||||
)
|
||||
enriched = ensure_on_demand_coordinate_evidence(
|
||||
document=document,
|
||||
layout=layout,
|
||||
page_nos=page_nos or {1},
|
||||
table_by_page={int(item.get('page_no') or 1): item for item in tables},
|
||||
)
|
||||
evidence = enriched.get('coordinate_evidence') if isinstance(enriched, dict) else None
|
||||
if not isinstance(evidence, dict) or not isinstance(evidence.get('page_glyphs'), dict) or not evidence.get('page_glyphs'):
|
||||
raise ConflictError(
|
||||
'Order PDF coordinate evidence is unavailable for retry',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_COORDINATE_EVIDENCE_UNAVAILABLE',
|
||||
details={'document_id': document_id, 'run_no': run.run_no},
|
||||
)
|
||||
record_inline_layout_snapshot(document, enriched)
|
||||
# LayoutVersion 受大小上限会再次压缩 glyph;Run 重试快照是本次执行的
|
||||
# 不可变输入,必须保留刚恢复的完整证据,不能再从压缩版反读。
|
||||
retry_layouts_by_document_id[document_id] = enriched
|
||||
snapshot_refreshed = True
|
||||
|
||||
if snapshot_refreshed:
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
schema_version = db.session.get(
|
||||
ShippingOrderSchemaVersion,
|
||||
int(schema.get('schema_version_id') or run.schema_version_id or 0),
|
||||
)
|
||||
intake_ids = [
|
||||
int(item.get('intake_id')) for item in snapshot.get('intakes') or []
|
||||
if isinstance(item, dict) and item.get('intake_id') is not None
|
||||
]
|
||||
intakes = (
|
||||
ShippingOrderIntake.query.filter(ShippingOrderIntake.id.in_(intake_ids))
|
||||
.order_by(ShippingOrderIntake.id.asc()).all()
|
||||
) if intake_ids else []
|
||||
if schema_version is None or len(intakes) != len(set(intake_ids)):
|
||||
raise ConflictError(
|
||||
'Frozen order extraction input is unavailable for retry',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
|
||||
details={'run_no': run.run_no},
|
||||
)
|
||||
refreshed = _build_snapshot(
|
||||
user_id=int(run.user_id),
|
||||
owner_agent_id=int(run.owner_agent_id),
|
||||
conversation_id=str(run.conversation_id or ''),
|
||||
intakes=intakes,
|
||||
schema_version=schema_version,
|
||||
attachment_selection=snapshot.get('attachment_selection'),
|
||||
)
|
||||
for raw_intake in refreshed.get('intakes') or []:
|
||||
if not isinstance(raw_intake, dict):
|
||||
continue
|
||||
for raw_document in raw_intake.get('documents') or []:
|
||||
if not isinstance(raw_document, dict):
|
||||
continue
|
||||
document_id = int(raw_document.get('document_id') or 0)
|
||||
if document_id in retry_layouts_by_document_id:
|
||||
raw_document['layout_snapshot'] = retry_layouts_by_document_id[document_id]
|
||||
for key in ('auto_freeze_policy', 'upload_batch_id', 'review_reparse'):
|
||||
if key in snapshot:
|
||||
refreshed[key] = snapshot[key]
|
||||
run.input_snapshot_json = refreshed
|
||||
run.input_snapshot_hash = _sha256(refreshed)
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
if plan is not None:
|
||||
plan.input_snapshot_hash = str(run.input_snapshot_hash)
|
||||
db.session.flush()
|
||||
|
||||
# [STEP] 手工重试从稳定检查点恢复:终态业务结果保留,失败/中断执行态统一回到 pending。
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ from app.services.shipping_notice.order_schema.table_contract import compile_tab
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
|
||||
|
||||
def _ready_layout(document: dict[str, Any]) -> dict[str, Any] | None:
|
||||
@@ -141,10 +142,9 @@ def assert_frozen_profile_signatures(run: Any) -> None:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
definition = item.get('definition') if isinstance(item.get('definition'), dict) else {}
|
||||
template_mode = str(
|
||||
item.get('template_mode') or definition.get('template_mode') or 'coordinate'
|
||||
).strip()
|
||||
if template_mode == 'xfa_dataset':
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
adapter = get_value_adapter(definition or item.get('template_mode'))
|
||||
if adapter.requires_path_context:
|
||||
source = definition.get('source_contract') if isinstance(definition.get('source_contract'), dict) else {}
|
||||
if not str(source.get('template_packet_checksum') or '').strip():
|
||||
raise ValidationError(
|
||||
|
||||
@@ -4,7 +4,8 @@ backend/app/services/shipping_notice/order_extraction_workflow.py
|
||||
用途:提供冻结订单抽取快照的确定性模板路由及 STP 裁决(straight_through / needs_review)。
|
||||
依赖:MinerU 紧凑快照、订单 Profile(coordinate / xfa_dataset)、Schema 校验、
|
||||
order_extraction_route_contract、xfa_profile_*、统一错误类型。
|
||||
逻辑:Worker 先调用本模块裁决;XFA capability 优先于坐标/通用路径且失败关闭不回退;
|
||||
逻辑:Worker 先调用本模块裁决;所有 PDF 先走共同视觉路径,datasets 仅在末端取正式值;
|
||||
datasets 缺失或冲突时共同 OCR 仅作复核/兜底证据并强制 needs_review;
|
||||
路由产出 Candidate 后由 Candidate Qualification 统一评估自动建单资格;
|
||||
模板 auto_create_approved 仅作解析器质量痕迹;主链不调用 Dify。
|
||||
"""
|
||||
@@ -34,21 +35,14 @@ from app.services.shipping_notice.document_layout.order_profile_parse_validation
|
||||
validate_profile_parse_candidate,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ensure_on_demand_coordinate_evidence
|
||||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_PARSER_IDENTITY
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_extraction import extract_xfa_profile
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_matcher import match_frozen_xfa_profiles
|
||||
from app.services.shipping_notice.document_layout.xfa_validation import validate_xfa_extraction
|
||||
from app.services.shipping_notice.order_extraction_route_contract import (
|
||||
default_policy_versions,
|
||||
normalize_reason_codes,
|
||||
project_safe_route_decision,
|
||||
route_type_from_profile_path,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
generic_extraction_enabled,
|
||||
profile_auto_selection_enabled,
|
||||
xfa_enabled,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import generic_extraction_enabled, profile_auto_selection_enabled
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
|
||||
|
||||
|
||||
@@ -71,6 +65,20 @@ class DeterministicRouteResult:
|
||||
decision: dict[str, Any]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ValueAdapterExtractionResult:
|
||||
"""末端值源 adapter 的标准产物;公共 Route 独占建单、fallback 与 STP 裁决。"""
|
||||
|
||||
decision: dict[str, Any]
|
||||
table: dict[str, Any] | None = None
|
||||
evidence: dict[str, Any] | None = None
|
||||
confirmed_order_fields: list[dict[str, Any]] | None = None
|
||||
review_evidence_allowed: bool = False
|
||||
force_needs_review_after_evidence: bool = False
|
||||
allow_manual_row_review: bool = True
|
||||
attach_formal_evidence: bool = False
|
||||
|
||||
|
||||
def _apply_stp_route_adjudication(
|
||||
decision: dict[str, Any],
|
||||
*,
|
||||
@@ -564,12 +572,22 @@ def _validate_table_header_outputs(rows: list[dict[str, Any]], *, schema_fields:
|
||||
return True
|
||||
|
||||
|
||||
def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
def _profile_table_candidates(
|
||||
run: Any,
|
||||
*,
|
||||
unit: Any,
|
||||
profiles: list[dict[str, Any]] | None = None,
|
||||
match_only: bool = False,
|
||||
selected_match: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
用 Run 冻结 Profile 解析 MinerU HTML,并生成不含坐标/HTML的紧凑字段候选。
|
||||
用 Run 冻结 Profile 执行共同视觉匹配;coordinate adapter 才继续重建字段行。
|
||||
|
||||
同一表命中多个 Profile 或命中 unsupported Profile 时设 blocking,调用方不得自动选择。
|
||||
坐标模板的成功匹配事实随候选一起返回,供路由审计记录实际使用的模板身份。
|
||||
``match_only=True`` 时只返回唯一视觉候选,供 XFA datasets adapter 在末端做
|
||||
自己的身份复验与取值;禁止在这一步触发坐标/OCR 行重建。
|
||||
``selected_match`` 仅由共同 matcher 的内部结果传入:跳过第二次模板决胜,但仍会
|
||||
对该唯一冻结 Profile 重建坐标明细行,不能把 match_only 的空 tables 误作无业务表。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
@@ -579,7 +597,7 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
str(item.get('field_id') or ''): item for item in definition.get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
|
||||
}
|
||||
profiles = [
|
||||
profiles = profiles if profiles is not None else [
|
||||
item for item in snapshot.get('order_document_profiles') or []
|
||||
if isinstance(item, dict)
|
||||
and int(item.get('schema_version_id') or 0) == int(run.schema_version_id)
|
||||
@@ -594,16 +612,8 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
'match': {'status': 'no_special_profile_feature', 'candidates': []},
|
||||
}
|
||||
profile_match: dict[str, Any] = {}
|
||||
# 坐标路径仅消费 coordinate 模板;xfa_dataset 由 route_deterministic_unit STEP 0 处理。
|
||||
coordinate_profiles = [
|
||||
item for item in profiles
|
||||
if isinstance(item.get('definition'), dict)
|
||||
and str(
|
||||
item.get('template_mode')
|
||||
or item.get('definition', {}).get('template_mode')
|
||||
or 'coordinate'
|
||||
).strip() != 'xfa_dataset'
|
||||
]
|
||||
# 候选选择只有共同视觉 matcher;末端取值 adapter 不影响此处 Profile 决胜。
|
||||
coordinate_profiles = list(profiles)
|
||||
if coordinate_profiles:
|
||||
raw_tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
required_pages = {
|
||||
@@ -626,33 +636,63 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
if not isinstance(layout.get('layout_candidate'), dict) or not isinstance(evidence.get('pages'), dict) or not isinstance(evidence.get('page_glyphs'), dict):
|
||||
return {'matched': False, 'blocking': True, 'tables': [], 'issues': ['order_layout_evidence_incomplete']}
|
||||
match = match_frozen_coordinate_profiles(profiles=coordinate_profiles, layout=layout)
|
||||
match = _apply_parse_validation_gate(
|
||||
match=match,
|
||||
coordinate_profiles=coordinate_profiles,
|
||||
layout=layout,
|
||||
definition=definition,
|
||||
)
|
||||
match, affinity_applied = _apply_reparse_profile_affinity(
|
||||
run=run, unit=unit, profiles=coordinate_profiles, match=match, layout=layout,
|
||||
)
|
||||
accepted_match_statuses = {'unique_match'}
|
||||
if profile_auto_selection_enabled():
|
||||
accepted_match_statuses.add('selected_by_score')
|
||||
if match.status not in accepted_match_statuses:
|
||||
if isinstance(selected_match, dict):
|
||||
profile_match = dict(selected_match)
|
||||
expected = (
|
||||
str(profile_match.get('profile_code') or ''),
|
||||
int(profile_match.get('version') or 0),
|
||||
str(profile_match.get('checksum') or ''),
|
||||
)
|
||||
profiles = [
|
||||
item for item in coordinate_profiles
|
||||
if (
|
||||
str(item.get('profile_code') or ''), int(item.get('version') or 0),
|
||||
str(item.get('checksum') or ''),
|
||||
) == expected
|
||||
]
|
||||
if str(profile_match.get('status') or '') not in {'unique_match', 'selected_by_score'} or len(profiles) != 1:
|
||||
return {
|
||||
'matched': False, 'blocking': True, 'tables': [],
|
||||
'issues': ['order_profile_selected_identity_invalid'], 'match': profile_match,
|
||||
}
|
||||
else:
|
||||
match = match_frozen_coordinate_profiles(profiles=coordinate_profiles, layout=layout)
|
||||
affinity_applied = False
|
||||
if not match_only:
|
||||
match = _apply_parse_validation_gate(
|
||||
match=match,
|
||||
coordinate_profiles=coordinate_profiles,
|
||||
layout=layout,
|
||||
definition=definition,
|
||||
)
|
||||
match, affinity_applied = _apply_reparse_profile_affinity(
|
||||
run=run, unit=unit, profiles=coordinate_profiles, match=match, layout=layout,
|
||||
)
|
||||
accepted_match_statuses = {'unique_match'}
|
||||
if profile_auto_selection_enabled():
|
||||
accepted_match_statuses.add('selected_by_score')
|
||||
if match.status not in accepted_match_statuses:
|
||||
return {
|
||||
'matched': False, 'blocking': True, 'tables': [],
|
||||
'issues': [f'order_profile_{match.status}'],
|
||||
'match': match.model_dump(mode='json'),
|
||||
}
|
||||
profile_match = match.model_dump(mode='json')
|
||||
if affinity_applied:
|
||||
profile_match['selection_reason'] = 'reparse_profile_affinity'
|
||||
profiles = [
|
||||
item for item in coordinate_profiles
|
||||
if item.get('profile_code') == match.profile_code and int(item.get('version') or 0) == match.version
|
||||
and str(item.get('checksum') or '') == match.checksum
|
||||
]
|
||||
if match_only:
|
||||
return {
|
||||
'matched': False, 'blocking': True, 'tables': [],
|
||||
'issues': [f'order_profile_{match.status}'],
|
||||
'match': match.model_dump(mode='json'),
|
||||
'matched': True,
|
||||
'blocking': False,
|
||||
'tables': [],
|
||||
'issues': [],
|
||||
'match': profile_match,
|
||||
}
|
||||
profile_match = match.model_dump(mode='json')
|
||||
if affinity_applied:
|
||||
profile_match['selection_reason'] = 'reparse_profile_affinity'
|
||||
profiles = [
|
||||
item for item in coordinate_profiles
|
||||
if item.get('profile_code') == match.profile_code and int(item.get('version') or 0) == match.version
|
||||
and str(item.get('checksum') or '') == match.checksum
|
||||
]
|
||||
result_tables: list[dict[str, Any]] = []
|
||||
issues: list[str] = []
|
||||
matched_any = False
|
||||
@@ -794,16 +834,31 @@ def _apply_parse_validation_gate(
|
||||
# 测试替身或历史结果可能缺少 candidates/model_copy;此时不做二次门禁。
|
||||
if not hasattr(match, 'candidates') or not hasattr(match, 'model_copy'):
|
||||
return match
|
||||
hard_candidates = [
|
||||
item for item in match.candidates if getattr(item, 'hard_match', False)
|
||||
][:3]
|
||||
if not hard_candidates:
|
||||
return match
|
||||
|
||||
profile_by_key = {
|
||||
(str(item.get('profile_code') or ''), int(item.get('version') or 0)): item
|
||||
for item in coordinate_profiles
|
||||
}
|
||||
# 解析可用性是已合格模板的补充验证,不能绕过 matcher 的分数和证据覆盖门禁。
|
||||
hard_candidates = []
|
||||
for candidate in match.candidates:
|
||||
raw = profile_by_key.get((candidate.profile_code, candidate.version))
|
||||
definition = raw.get('definition') if isinstance(raw, dict) and isinstance(raw.get('definition'), dict) else {}
|
||||
document_match = definition.get('document_match') if isinstance(definition.get('document_match'), dict) else {}
|
||||
thresholds = document_match.get('scoring_thresholds') if isinstance(document_match.get('scoring_thresholds'), dict) else {}
|
||||
try:
|
||||
eligible = (
|
||||
bool(getattr(candidate, 'hard_match', False))
|
||||
and candidate.score >= float(document_match.get('minimum_score', 0.9))
|
||||
and candidate.evidence_coverage >= float(thresholds.get('evidence_coverage_minimum', 0.7))
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
eligible = False
|
||||
if eligible:
|
||||
hard_candidates.append(candidate)
|
||||
hard_candidates = hard_candidates[:3]
|
||||
if not hard_candidates:
|
||||
return match
|
||||
|
||||
parse_passed: list[tuple[str, int, str]] = []
|
||||
parse_audit: dict[str, dict[str, Any]] = {}
|
||||
for candidate in hard_candidates:
|
||||
@@ -1179,14 +1234,11 @@ def _merge_confirmed_profile_order_fields(run: Any, *, unit: Any, orders: list[d
|
||||
return orders
|
||||
|
||||
|
||||
def _layout_is_xfa_capable(layout: dict[str, Any] | None) -> bool:
|
||||
"""判断 layout 快照是否为 XFA datasets 能力文档。"""
|
||||
if not isinstance(layout, dict):
|
||||
return False
|
||||
if str(layout.get('provider') or '').strip() == 'xfa':
|
||||
return True
|
||||
capability = layout.get('xfa_capability') if isinstance(layout.get('xfa_capability'), dict) else {}
|
||||
return bool(capability.get('structure_analysis_ready') or capability.get('dataset_structure_fingerprint'))
|
||||
def _profile_visual_main_table_id(profile: dict[str, Any], layout: dict[str, Any]) -> str | None:
|
||||
"""返回模板冻结的共同视觉主表身份。"""
|
||||
definition = profile.get('definition') if isinstance(profile.get('definition'), dict) else {}
|
||||
table_id = str(definition.get('main_table_id') or '').strip()
|
||||
return table_id or None
|
||||
|
||||
|
||||
def _load_unit_pdf_bytes(document: dict[str, Any]) -> bytes | None:
|
||||
@@ -1213,7 +1265,7 @@ def _load_unit_pdf_bytes(document: dict[str, Any]) -> bytes | None:
|
||||
return None
|
||||
|
||||
|
||||
def _route_xfa_deterministic_unit(
|
||||
def _extract_coordinate_value_adapter_result(
|
||||
*,
|
||||
run: Any,
|
||||
unit: Any,
|
||||
@@ -1221,289 +1273,33 @@ def _route_xfa_deterministic_unit(
|
||||
document: dict[str, Any],
|
||||
schema: dict[str, Any],
|
||||
definition: dict[str, Any],
|
||||
) -> DeterministicRouteResult:
|
||||
selected_profile: dict[str, Any] | None = None,
|
||||
shared_profile_result: dict[str, Any] | None = None,
|
||||
) -> ValueAdapterExtractionResult:
|
||||
"""coordinate/OCR adapter 仅从共同 matcher 已选 Profile 重建最终字段值。
|
||||
|
||||
通用 PDF/OCR fallback、建单、STP 与 Review 都由 ``route_deterministic_unit``
|
||||
统一处理;本 adapter 不再推进第二套顶层业务路径。
|
||||
"""
|
||||
执行 XFA 正式确定性提取;失败关闭为 review_required,禁止回退坐标/OCR/通用正式提取。
|
||||
|
||||
核心逻辑:读 PDF → analyze_xfa_pdf → 精确匹配 published 冻结 Profile →
|
||||
路径提取 → AcroForm/镜像/金额校验 → 组装订单;Run 决策写入结构指纹与 parser identity。
|
||||
未命中或校验失败时返回 review_required + fallback_reason_codes,由上层原样返回。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.xfa_analysis import analyze_xfa_pdf
|
||||
|
||||
decision: dict[str, Any] = {
|
||||
'match_status': 'no_match',
|
||||
'selected_profile_code': None,
|
||||
'selected_profile_version': None,
|
||||
'selected_profile_checksum': None,
|
||||
'selected_profile_id': None,
|
||||
'candidate_count': 0,
|
||||
'table_count': 0,
|
||||
'document_table_count': 0,
|
||||
'business_table_count': 0,
|
||||
'matched_table_count': 0,
|
||||
'parsed_table_count': 0,
|
||||
'approved_table_count': 0,
|
||||
'candidate_summary': [],
|
||||
'fallback_reason_codes': [],
|
||||
'capability_kind': 'xfa_dataset',
|
||||
'template_mode': 'xfa_dataset',
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'policy_versions': {
|
||||
**default_policy_versions(),
|
||||
'xfa_parser_identity': XFA_PARSER_IDENTITY,
|
||||
},
|
||||
}
|
||||
|
||||
if not xfa_enabled():
|
||||
decision['fallback_reason_codes'] = ['xfa_unsupported_document']
|
||||
decision['match_status'] = 'no_match'
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
profiles = [
|
||||
item for item in snapshot.get('order_document_profiles') or []
|
||||
if isinstance(item, dict)
|
||||
and int(item.get('schema_version_id') or 0) == int(run.schema_version_id)
|
||||
and str(
|
||||
item.get('template_mode')
|
||||
or ((item.get('definition') or {}).get('template_mode') if isinstance(item.get('definition'), dict) else '')
|
||||
or ''
|
||||
).strip() == 'xfa_dataset'
|
||||
and str(item.get('status') or 'published').strip() == 'published'
|
||||
]
|
||||
decision['candidate_count'] = len(profiles)
|
||||
|
||||
pdf_bytes = _load_unit_pdf_bytes(document)
|
||||
if not pdf_bytes:
|
||||
decision['fallback_reason_codes'] = ['xfa_dataset_missing']
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
|
||||
outcome = analyze_xfa_pdf(pdf_bytes)
|
||||
if outcome.dataset_analysis is None or outcome.error_code:
|
||||
reason = str(outcome.route_reason or 'xfa_dataset_missing')
|
||||
decision['fallback_reason_codes'] = [reason]
|
||||
decision['xfa_structure'] = project_safe_route_decision({
|
||||
'error_code': outcome.error_code,
|
||||
'route_reason': reason,
|
||||
})
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
|
||||
capability = (
|
||||
document.get('layout_snapshot', {}).get('xfa_capability')
|
||||
if isinstance(document.get('layout_snapshot'), dict)
|
||||
else {}
|
||||
)
|
||||
if not isinstance(capability, dict):
|
||||
capability = {}
|
||||
live_template = (
|
||||
outcome.snapshot.get('xfa_capability', {}).get('template_packet_checksum')
|
||||
if isinstance(outcome.snapshot.get('xfa_capability'), dict)
|
||||
else None
|
||||
) or capability.get('template_packet_checksum')
|
||||
live_fingerprint = (
|
||||
outcome.snapshot.get('xfa_capability', {}).get('dataset_structure_fingerprint')
|
||||
if isinstance(outcome.snapshot.get('xfa_capability'), dict)
|
||||
else None
|
||||
) or capability.get('dataset_structure_fingerprint')
|
||||
# Prefer live analysis signature summary when capability keys missing.
|
||||
if not live_template or not live_fingerprint:
|
||||
from app.services.shipping_notice.document_layout.xfa_signature import build_signature_summary
|
||||
from app.services.shipping_notice.document_layout.xfa_packets import read_xfa_packets
|
||||
|
||||
packets = read_xfa_packets(pdf_bytes)
|
||||
summary = build_signature_summary(
|
||||
template_bytes=packets.packet_bytes_by_name.get('template'),
|
||||
dataset_nodes=outcome.dataset_analysis.nodes,
|
||||
_ = intake, document, schema, definition
|
||||
shared_match = shared_profile_result if isinstance(shared_profile_result, dict) else None
|
||||
shared_match_payload = shared_match.get('match') if isinstance(shared_match, dict) and isinstance(shared_match.get('match'), dict) else None
|
||||
# Route 先以 match_only 冻结唯一 Profile 身份。coordinate adapter 必须以该身份
|
||||
# 重新进入坐标行重建,而不是消费 match_only 约定中的空 tables。
|
||||
profile_result = (
|
||||
_profile_table_candidates(
|
||||
run,
|
||||
unit=unit,
|
||||
profiles=[selected_profile],
|
||||
selected_match=shared_match_payload,
|
||||
)
|
||||
live_template = live_template or summary.get('template_packet_checksum')
|
||||
live_fingerprint = live_fingerprint or summary.get('dataset_structure_fingerprint')
|
||||
|
||||
datasets_checksum = None
|
||||
if outcome.packet_result is not None:
|
||||
for packet in outcome.packet_result.packets:
|
||||
if str(packet.name).lower() == 'datasets':
|
||||
datasets_checksum = packet.checksum
|
||||
break
|
||||
datasets_checksum = datasets_checksum or str(live_template or '')
|
||||
|
||||
decision['xfa_structure'] = project_safe_route_decision({
|
||||
'template_packet_checksum': live_template,
|
||||
'dataset_structure_fingerprint': live_fingerprint,
|
||||
'parser_identity': XFA_PARSER_IDENTITY,
|
||||
'schema_checksum': (snapshot.get('schema') or {}).get('checksum') if isinstance(snapshot.get('schema'), dict) else None,
|
||||
})
|
||||
|
||||
match = match_frozen_xfa_profiles(
|
||||
profiles=profiles,
|
||||
template_packet_checksum=str(live_template or '') or None,
|
||||
dataset_structure_fingerprint=str(live_fingerprint or '') or None,
|
||||
if isinstance(selected_profile, dict) and isinstance(shared_match_payload, dict)
|
||||
else (shared_match if isinstance(shared_match, dict) else _profile_table_candidates(
|
||||
run,
|
||||
unit=unit,
|
||||
profiles=[selected_profile] if isinstance(selected_profile, dict) else [],
|
||||
))
|
||||
)
|
||||
decision['match_status'] = match.status
|
||||
decision['candidate_summary'] = [item.model_dump(mode='json') for item in match.candidates]
|
||||
decision['match'] = match.model_dump_safe()
|
||||
|
||||
if match.status != 'unique_match':
|
||||
reason = (
|
||||
'xfa_profile_ambiguous' if match.status == 'ambiguous'
|
||||
else (match.reason_codes[0] if match.reason_codes else 'xfa_profile_not_matched')
|
||||
)
|
||||
decision['fallback_reason_codes'] = [reason]
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
|
||||
selected = next(
|
||||
(
|
||||
item for item in profiles
|
||||
if item.get('profile_code') == match.profile_code
|
||||
and int(item.get('version') or 0) == int(match.version or 0)
|
||||
and str(item.get('checksum') or '') == str(match.checksum or '')
|
||||
),
|
||||
None,
|
||||
)
|
||||
if selected is None:
|
||||
decision['fallback_reason_codes'] = ['xfa_profile_not_matched']
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
|
||||
decision.update({
|
||||
'selected_profile_code': match.profile_code,
|
||||
'selected_profile_version': match.version,
|
||||
'selected_profile_checksum': match.checksum,
|
||||
'selected_profile_id': match.profile_id or selected.get('profile_id'),
|
||||
'auto_create_approved': bool(selected.get('auto_create_approved')),
|
||||
'business_table_count': 1,
|
||||
'matched_table_count': 1,
|
||||
'document_table_count': 1,
|
||||
'table_count': 1,
|
||||
})
|
||||
|
||||
extraction = extract_xfa_profile(
|
||||
raw_profile=selected,
|
||||
dataset_analysis=outcome.dataset_analysis,
|
||||
schema_definition=definition,
|
||||
document_id=int(unit.document_id),
|
||||
packet_checksum=str(datasets_checksum),
|
||||
dataset_structure_fingerprint=str(live_fingerprint or '') or None,
|
||||
)
|
||||
decision['xfa_evidence_summary'] = extraction.evidence_summary
|
||||
# [STEP] 正式提取审计:成功与 needs_review 分流事件(不含原文敏感值)。
|
||||
try:
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
audit_event = (
|
||||
'xfa_profile_formal_extracted'
|
||||
if extraction.status == 'parsed' and not extraction.reason_codes
|
||||
else 'xfa_profile_needs_review'
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type=audit_event,
|
||||
aggregate_type='shipping_notice_document',
|
||||
aggregate_id=str(unit.document_id),
|
||||
document_id=int(unit.document_id),
|
||||
actor_type='system',
|
||||
actor_id=None,
|
||||
# 审计 result 只表达调用结果;needs_review 业务裁决由 event_type/reason_codes 承载。
|
||||
result='success' if audit_event == 'xfa_profile_formal_extracted' else 'failure',
|
||||
action='xfa_formal_extract',
|
||||
sensitivity_level='normal',
|
||||
after={
|
||||
'profile_code': match.profile_code,
|
||||
'profile_version': match.version,
|
||||
'profile_checksum': match.checksum,
|
||||
'extraction_status': extraction.status,
|
||||
'reason_codes': list(extraction.reason_codes or [])[:20],
|
||||
'line_row_count': len(extraction.rows),
|
||||
'split_evidence_row_count': sum(
|
||||
1 for row in extraction.rows
|
||||
if isinstance(row, dict) and row.get('split_evidence')
|
||||
),
|
||||
},
|
||||
metadata={
|
||||
'template_mode': 'xfa_dataset',
|
||||
'parser_identity': extraction.parser_identity,
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
# 审计失败不得阻断正式提取主路径;上层仍有 extraction 状态机。
|
||||
pass
|
||||
if extraction.status != 'parsed' or extraction.reason_codes:
|
||||
decision['fallback_reason_codes'] = list(extraction.reason_codes or ['xfa_required_field_missing'])
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
|
||||
validation = validate_xfa_extraction(
|
||||
raw_profile=selected,
|
||||
dataset_analysis=outcome.dataset_analysis,
|
||||
extraction=extraction,
|
||||
pdf_bytes=pdf_bytes,
|
||||
)
|
||||
decision['xfa_cross_checks'] = validation.cross_check_summary
|
||||
from app.services.shipping_notice.document_layout.xfa_validation import build_xfa_validation_metrics
|
||||
definition_payload = (
|
||||
selected.get('definition') if isinstance(selected.get('definition'), dict) else {}
|
||||
)
|
||||
unified_metrics = build_xfa_validation_metrics(
|
||||
definition=definition_payload,
|
||||
extraction=extraction,
|
||||
cross_check_summary=validation.cross_check_summary,
|
||||
)
|
||||
unified_metrics['profile_checksum'] = str(selected.get('checksum') or '')
|
||||
decision['xfa_unified_metrics'] = unified_metrics
|
||||
if not validation.passed:
|
||||
decision['fallback_reason_codes'] = list(validation.reason_codes or ['xfa_business_validation_failed'])
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
|
||||
table = {
|
||||
'profile_id': selected.get('profile_id') or selected.get('id'),
|
||||
'profile_code': str(selected.get('profile_code') or ''),
|
||||
'profile_version': int(selected.get('version') or 0),
|
||||
'profile_checksum': str(selected.get('checksum') or ''),
|
||||
'table_id': 'xfa-authoritative-lines',
|
||||
'page_no': 1,
|
||||
'auto_create_approved': bool(selected.get('auto_create_approved')),
|
||||
'rows': extraction.rows,
|
||||
}
|
||||
orders, reason_code = _build_approved_profile_order_result(
|
||||
unit=unit, intake=intake, schema=schema, definition=definition, table=table,
|
||||
)
|
||||
if orders is None:
|
||||
decision['fallback_reason_codes'] = [reason_code or 'xfa_required_field_missing']
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
|
||||
# 在订单上附着安全 XFA evidence(不含 XML)。
|
||||
for order in orders:
|
||||
order['_hxops_xfa_evidence'] = extraction.evidence_summary
|
||||
order['_hxops_xfa_structure'] = decision.get('xfa_structure')
|
||||
decision['parsed_table_count'] = 1
|
||||
decision['route_type'] = 'profile_deterministic'
|
||||
decision['fallback_reason_codes'] = []
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
|
||||
|
||||
|
||||
def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult:
|
||||
"""计算单元的模板/通用路由并返回含 STP 裁决的脱敏结构化结果。
|
||||
|
||||
AI 触发时机:无需调用。Worker 在每个 Unit 执行前调用;已批准模板或通用 Schema
|
||||
确定性解析可走 deterministic;其余进入复核或 LLM 辅助建议。
|
||||
识别到 xfa_hybrid 且 XFA 启用时走 xfa_dataset;失败立即返回 review_required,
|
||||
禁止回退坐标/OCR/通用正式提取(建模期 OCR 辅助不受影响)。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
schema = (
|
||||
schema_snapshot.get('extraction_contract')
|
||||
if isinstance(schema_snapshot.get('extraction_contract'), dict)
|
||||
else {}
|
||||
)
|
||||
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
|
||||
intake, document = _unit_snapshot(run, unit)
|
||||
layout = document.get('layout_snapshot') if isinstance(document.get('layout_snapshot'), dict) else {}
|
||||
|
||||
# [STEP 0] XFA capability:优先 xfa_dataset;非 deterministic 成功时立即返回,禁止坐标/OCR/通用回退。
|
||||
if _layout_is_xfa_capable(layout) and xfa_enabled():
|
||||
return _route_xfa_deterministic_unit(
|
||||
run=run, unit=unit, intake=intake, document=document,
|
||||
schema=schema, definition=definition,
|
||||
)
|
||||
|
||||
profile_result = _profile_table_candidates(run, unit=unit)
|
||||
match = profile_result.get('match') if isinstance(profile_result.get('match'), dict) else {}
|
||||
tables = profile_result.get('tables') if isinstance(profile_result.get('tables'), list) else []
|
||||
candidates = match.get('candidates') if isinstance(match.get('candidates'), list) else []
|
||||
@@ -1529,7 +1325,7 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
|
||||
'capability_kind': 'coordinate',
|
||||
}
|
||||
|
||||
# [STEP 1] 模板确定性路径:唯一匹配表且解析完整时优先走 profile_deterministic。
|
||||
# 共同 matcher 已选择 Profile;本 adapter 只恢复该 Profile 的坐标行。
|
||||
if not profile_result.get('blocking') and len(tables) == 1:
|
||||
selected = tables[0]
|
||||
decision.update({
|
||||
@@ -1541,65 +1337,41 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
|
||||
'business_table_count': 1,
|
||||
'matched_table_count': 1,
|
||||
})
|
||||
confirmed_order_fields = _confirmed_profile_order_fields(run, unit=unit)
|
||||
orders, reason_code = _build_approved_profile_order_result(
|
||||
unit=unit, intake=intake, schema=schema, definition=definition, table=selected,
|
||||
confirmed_order_fields=confirmed_order_fields,
|
||||
return ValueAdapterExtractionResult(
|
||||
decision=decision,
|
||||
table=selected,
|
||||
confirmed_order_fields=_confirmed_profile_order_fields(run, unit=unit),
|
||||
)
|
||||
if orders is None and reason_code in {'row_needs_review'}:
|
||||
orders, review_reason = _build_approved_profile_order_result(
|
||||
unit=unit, intake=intake, schema=schema, definition=definition, table=selected,
|
||||
confirmed_order_fields=confirmed_order_fields, allow_manual_review=True,
|
||||
)
|
||||
if orders is not None:
|
||||
decision['fallback_reason_codes'] = ['row_needs_review']
|
||||
decision['parsed_table_count'] = 1
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
|
||||
reason_code = review_reason or reason_code
|
||||
if orders is not None:
|
||||
decision['parsed_table_count'] = 1
|
||||
decision['business_table_count'] = 1
|
||||
decision['matched_table_count'] = 1
|
||||
decision['document_table_count'] = len(tables)
|
||||
# 模板 auto_create_approved 仅写入决策痕迹;不得剥离验收标记或降级 STP。
|
||||
decision['auto_create_approved'] = bool(selected.get('auto_create_approved'))
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
|
||||
if reason_code == 'row_needs_review':
|
||||
decision['review_details'] = _profile_row_review_details(selected)
|
||||
|
||||
# [STEP 2] 通用确定性路径:模板未命中,或模板命中但模板解析未产出订单时,
|
||||
# 均尝试通用解析。模板优先级只决定“先试模板”,不应把模板失败变成终态失败。
|
||||
# 通用证据 fallback 由公共 Route 决定,adapter 仅如实提供可否进入它的条件。
|
||||
if _should_attempt_generic_extraction(match_status=match_status, profile_result=profile_result):
|
||||
if not generic_extraction_enabled():
|
||||
decision['fallback_reason_codes'] = ['generic_extraction_disabled']
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
return _route_generic_deterministic_unit(
|
||||
run=run, unit=unit, intake=intake, document=document,
|
||||
schema=schema, definition=definition, decision=decision,
|
||||
)
|
||||
return ValueAdapterExtractionResult(decision=decision)
|
||||
return ValueAdapterExtractionResult(decision=decision, review_evidence_allowed=True)
|
||||
|
||||
# [STEP 3] 仅在布局前置条件本身不可用,或通用解析被配置关闭时进入复核。
|
||||
if profile_result.get('blocking'):
|
||||
issues = profile_result.get('issues') if isinstance(profile_result.get('issues'), list) else []
|
||||
decision['fallback_reason_codes'] = [_route_reason_for_issue(str(issue)) for issue in issues]
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
return ValueAdapterExtractionResult(decision=decision)
|
||||
if not tables:
|
||||
decision['fallback_reason_codes'] = ['business_table_not_found']
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
return ValueAdapterExtractionResult(decision=decision)
|
||||
if len(tables) != 1:
|
||||
decision['fallback_reason_codes'] = ['multiple_business_tables']
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
return ValueAdapterExtractionResult(decision=decision)
|
||||
decision['fallback_reason_codes'] = ['business_table_not_found']
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
return ValueAdapterExtractionResult(decision=decision)
|
||||
|
||||
|
||||
def _should_attempt_generic_extraction(*, match_status: str, profile_result: dict[str, Any]) -> bool:
|
||||
"""
|
||||
判断是否允许进入通用 Schema 确定性解析。
|
||||
|
||||
核心逻辑:仅用于非 XFA 正式路径。无异型特征或未命中坐标模板时可尝试通用路径;
|
||||
layout_drift / ambiguous / evidence_insufficient / structure_identity_changed 保持 fail-closed。
|
||||
XFA-capable 且启用时不会进入本函数(STEP 0 已失败关闭)。
|
||||
核心逻辑:所有未命中已发布模板的 PDF 共用此判定;无异型特征或未命中模板时可尝试
|
||||
通用路径。layout_drift / ambiguous / evidence_insufficient / structure_identity_changed 保持 fail-closed。
|
||||
已命中 datasets 模板时才由末端 adapter 追加 datasets 取值和交叉裁决。
|
||||
"""
|
||||
status = str(match_status or '').strip()
|
||||
if status in {
|
||||
@@ -1610,9 +1382,8 @@ def _should_attempt_generic_extraction(*, match_status: str, profile_result: dic
|
||||
return status in {'no_special_profile_feature', 'no_match'}
|
||||
|
||||
|
||||
def _route_generic_deterministic_unit(
|
||||
def _extract_generic_evidence_result(
|
||||
*,
|
||||
run: Any,
|
||||
unit: Any,
|
||||
intake: dict[str, Any],
|
||||
document: dict[str, Any],
|
||||
@@ -1658,6 +1429,101 @@ def _route_generic_deterministic_unit(
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
|
||||
|
||||
def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult:
|
||||
"""执行唯一的确定性 Route 生命周期;adapter 只负责末端取值及必要证据。
|
||||
|
||||
核心顺序固定为:共同视觉 matcher 选 Profile → adapter 取值 → 公共建单、
|
||||
通用证据 fallback、STP/Review 裁决。不得按 XFA 与否进入第二套 Route。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
schema = schema_snapshot.get('extraction_contract') if isinstance(schema_snapshot.get('extraction_contract'), dict) else {}
|
||||
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
|
||||
intake, document = _unit_snapshot(run, unit)
|
||||
frozen_profiles = [
|
||||
item for item in snapshot.get('order_document_profiles') or []
|
||||
if isinstance(item, dict)
|
||||
and int(item.get('schema_version_id') or 0) == int(run.schema_version_id)
|
||||
and str(item.get('status') or 'published').strip() == 'published'
|
||||
]
|
||||
# [STEP 1] 所有已发布 Profile(包括 XFA)先参加同一个视觉候选选择器。
|
||||
# 没有 Profile 时不存在候选工作;直接由 adapter 产出统一的未命中事实,
|
||||
# 避免为 XFA 正式值源失败额外调用一条“坐标 fallback”路径。
|
||||
profile_result = (
|
||||
_profile_table_candidates(run, unit=unit, profiles=frozen_profiles, match_only=True)
|
||||
if frozen_profiles else {}
|
||||
)
|
||||
match = profile_result.get('match') if isinstance(profile_result.get('match'), dict) else {}
|
||||
selected_profile = next((
|
||||
item for item in frozen_profiles
|
||||
if str(item.get('profile_code') or '') == str(match.get('profile_code') or '')
|
||||
and int(item.get('version') or 0) == int(match.get('version') or 0)
|
||||
and str(item.get('checksum') or '') == str(match.get('checksum') or '')
|
||||
), None)
|
||||
# 仅共同视觉 matcher 已选中的模板可以决定末端正式值源。未命中时必须
|
||||
# 复用普通 PDF 的共同 OCR/通用证据流程,不能按文档是否带 XFA datasets 分叉。
|
||||
value_adapter = get_value_adapter(selected_profile.get('definition') if selected_profile else None)
|
||||
adapter_result = value_adapter.extract(
|
||||
run=run, unit=unit, intake=intake, document=document, schema=schema, definition=definition,
|
||||
selected_profile=selected_profile, shared_profile_result=profile_result,
|
||||
)
|
||||
adapter_name = value_adapter.key
|
||||
decision = adapter_result.decision
|
||||
# [STEP 2] 公共建单:任何 adapter 只能交付 table/证据,不能自行裁决生命周期。
|
||||
if adapter_result.table is not None:
|
||||
orders, reason_code = _build_approved_profile_order_result(
|
||||
unit=unit, intake=intake, schema=schema, definition=definition,
|
||||
table=adapter_result.table, confirmed_order_fields=adapter_result.confirmed_order_fields,
|
||||
allow_manual_review=False,
|
||||
)
|
||||
if orders is None and adapter_result.allow_manual_row_review and reason_code == 'row_needs_review':
|
||||
orders, review_reason = _build_approved_profile_order_result(
|
||||
unit=unit, intake=intake, schema=schema, definition=definition,
|
||||
table=adapter_result.table, confirmed_order_fields=adapter_result.confirmed_order_fields,
|
||||
allow_manual_review=True,
|
||||
)
|
||||
if orders is not None:
|
||||
decision['fallback_reason_codes'] = ['row_needs_review']
|
||||
else:
|
||||
reason_code = review_reason or reason_code
|
||||
if orders is not None:
|
||||
for order in orders:
|
||||
if adapter_result.attach_formal_evidence:
|
||||
order['_hxops_formal_evidence'] = (adapter_result.evidence or {}).get('formal_evidence_summary')
|
||||
order['_hxops_value_source_identity'] = (adapter_result.evidence or {}).get('value_source_identity')
|
||||
decision['parsed_table_count'] = 1
|
||||
decision['route_type'] = 'profile_deterministic'
|
||||
if decision.get('fallback_reason_codes'):
|
||||
return _apply_stp_route_adjudication(
|
||||
decision, execution_mode='review_required', orders=orders,
|
||||
)
|
||||
decision['fallback_reason_codes'] = []
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
|
||||
decision['fallback_reason_codes'] = [reason_code or f'{adapter_name}_required_field_missing']
|
||||
if reason_code == 'row_needs_review':
|
||||
decision['review_details'] = _profile_row_review_details(adapter_result.table)
|
||||
|
||||
# [STEP 3] 共同 PDF/OCR 证据 fallback。datasets adapter 可开放证据,但必须
|
||||
# 明确强制 needs_review,禁止 OCR 结果取得 XFA 的正式/STP 资格。
|
||||
if adapter_result.review_evidence_allowed and generic_extraction_enabled():
|
||||
prior_codes = list(decision.get('fallback_reason_codes') or [])
|
||||
if adapter_result.force_needs_review_after_evidence:
|
||||
decision['fallback_from'] = adapter_name
|
||||
decision['fallback_evidence_policy'] = 'datasets_then_pdfium_widget_ocr'
|
||||
result = _extract_generic_evidence_result(
|
||||
unit=unit, intake=intake, document=document, schema=schema, definition=definition, decision=decision,
|
||||
)
|
||||
if adapter_result.force_needs_review_after_evidence:
|
||||
result.decision['fallback_reason_codes'] = list(dict.fromkeys(
|
||||
prior_codes + list(result.decision.get('fallback_reason_codes') or []),
|
||||
))
|
||||
return _apply_stp_route_adjudication(
|
||||
result.decision, execution_mode='review_required', orders=result.orders,
|
||||
)
|
||||
return result
|
||||
return _apply_stp_route_adjudication(decision, execution_mode='review_required', orders=[])
|
||||
|
||||
|
||||
def _profile_row_review_details(table: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""将本次模板行校验问题压缩为可展示、可定位的人工复核清单。"""
|
||||
details: list[dict[str, Any]] = []
|
||||
|
||||
@@ -18,12 +18,15 @@ from collections import Counter
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderRouteDecision,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderProcessingUnit,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewStream,
|
||||
)
|
||||
from app.services.shipping_notice.error_explainability_contract import build_explainability_reason
|
||||
from app.services.shipping_notice.progress_audit_contract import HEALTH_TIP_THRESHOLDS_SECONDS
|
||||
@@ -885,9 +888,15 @@ def build_handling_items(
|
||||
primary_action='retry_failed_attachments',
|
||||
))
|
||||
|
||||
current_review_cases = _current_non_terminal_review_cases(run)
|
||||
current_review_document_ids = {int(case.document_id) for case in current_review_cases}
|
||||
review_units = [
|
||||
unit for unit in unit_rows
|
||||
if str(unit.status or '') == 'review_required' and int(unit.document_id or 0) not in open_ids
|
||||
if (
|
||||
str(unit.status or '') == 'review_required'
|
||||
and int(unit.document_id or 0) in current_review_document_ids
|
||||
and int(unit.document_id or 0) not in open_ids
|
||||
)
|
||||
]
|
||||
review_refs = claim([
|
||||
{
|
||||
@@ -900,12 +909,8 @@ def build_handling_items(
|
||||
if not review_refs:
|
||||
review_refs = claim([
|
||||
{'type': 'document', 'document_id': int(case.document_id), 'case_no': case.case_no}
|
||||
for case in getattr(run, 'review_cases', []) or []
|
||||
if (
|
||||
str(case.status or '') not in {'confirmed', 'non_order', 'superseded'}
|
||||
and int(case.document_id or 0) not in open_ids
|
||||
and int(case.document_id or 0) > 0
|
||||
)
|
||||
for case in current_review_cases
|
||||
if int(case.document_id or 0) not in open_ids and int(case.document_id or 0) > 0
|
||||
])
|
||||
if review_refs:
|
||||
codes = _trim_reason_codes([
|
||||
@@ -1097,6 +1102,16 @@ def _run_available_actions(
|
||||
actions.append('enter_manual_review')
|
||||
if categories & {'document_review'} and 'enter_manual_review' not in actions:
|
||||
actions.append('enter_manual_review')
|
||||
# 批次重解析是跨阶段的受控批量命令:必须基于整个 Run 谱系而非当前 Run
|
||||
# 关系上的旧 Case 判断,否则首次局部重解析后来源 Run 会错误丢失入口。
|
||||
# 单 PDF 的 reparse 仍只由 Case 承载。
|
||||
if (
|
||||
str(run.status or '') in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}
|
||||
):
|
||||
from app.services.shipping_notice.order_review_disposition_service import has_reparseable_batch_documents
|
||||
|
||||
if has_reparseable_batch_documents(user_id=int(run.user_id), run=run):
|
||||
actions.append('reparse_batch')
|
||||
if run.status == 'failed' or any(unit.status == 'failed' for unit in units) or 'technical_failure' in categories:
|
||||
if 'retry_failed_attachments' not in actions:
|
||||
actions.append('retry_failed_attachments')
|
||||
@@ -1115,18 +1130,30 @@ def _unresolved_review_document_count(
|
||||
open_existing_doc_ids: set[int] | None = None,
|
||||
) -> int:
|
||||
"""统计用户仍需处理的 PDF 复核 Case;open_existing 已关联任务的 PDF 不计复核。"""
|
||||
resolved_statuses = {'confirmed', 'non_order', 'superseded'}
|
||||
open_ids = open_existing_doc_ids if open_existing_doc_ids is not None else set()
|
||||
return len({
|
||||
int(case.document_id)
|
||||
for case in getattr(run, 'review_cases', []) or []
|
||||
if (
|
||||
str(case.status or '') not in resolved_statuses
|
||||
and int(case.document_id or 0) not in open_ids
|
||||
)
|
||||
for case in _current_non_terminal_review_cases(run)
|
||||
if int(case.document_id or 0) not in open_ids
|
||||
})
|
||||
|
||||
|
||||
def _current_non_terminal_review_cases(run: ShippingOrderProcessingRun) -> list[ShippingOrderReviewCase]:
|
||||
"""返回该 Run 产出的文件 Stream 当前非终态 Case;Run 的历史 Case 不参与工作台统计。"""
|
||||
return (
|
||||
db.session.query(ShippingOrderReviewCase)
|
||||
.join(
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.run_id == int(run.id),
|
||||
ShippingOrderReviewCase.status.notin_(('confirmed', 'non_order', 'superseded')),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
|
||||
def _result_opened_existing_count(run: ShippingOrderProcessingRun) -> int:
|
||||
"""从 Run.result_json 读取已打开已有任务数。"""
|
||||
result = run.result_json if isinstance(run.result_json, dict) else {}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""订单模板正式值源的公共协议入口。
|
||||
|
||||
用途:向共同 Profile、验证、发布和运行时流程暴露无格式语义的 adapter 获取接口。
|
||||
依赖:具体值源注册与实现位于 order_profile_value_adapters 包。
|
||||
逻辑:本模块不得识别 PDF 类型、持久化模板模式或 datasets;调用方只获得协议对象。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.order_profile_value_adapters import (
|
||||
OrderProfileValueAdapter,
|
||||
adapter_key,
|
||||
get_runtime_value_adapter,
|
||||
get_value_adapter,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'OrderProfileValueAdapter',
|
||||
'adapter_key',
|
||||
'get_runtime_value_adapter',
|
||||
'get_value_adapter',
|
||||
]
|
||||
@@ -0,0 +1,124 @@
|
||||
"""订单模板正式值源 adapter 注册与无格式协议。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable
|
||||
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class OrderProfileValueAdapter:
|
||||
"""共同生命周期使用的正式值源协议,不暴露文件格式分支。"""
|
||||
|
||||
key: str
|
||||
legacy_template_mode: str
|
||||
requires_path_context: bool = False
|
||||
requires_annotation_document: bool = False
|
||||
requires_split_rule_confirmation: bool = False
|
||||
requires_split_rule_publish_permission: bool = False
|
||||
records_mapping_audit: bool = False
|
||||
operations: dict[str, Callable[..., Any]] | None = None
|
||||
|
||||
def _call(self, name: str, *args: Any, **kwargs: Any) -> Any:
|
||||
operation = (self.operations or {}).get(name)
|
||||
if operation is None:
|
||||
raise ValidationError('Order profile value adapter is unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
return operation(*args, **kwargs)
|
||||
|
||||
def audit_evidence(self, definition: dict[str, Any]) -> dict[str, Any] | None: return self._call('audit_evidence', definition)
|
||||
def validate_definition(self, profile: Any, definition: dict[str, Any]) -> None: self._call('validate_definition', profile, definition)
|
||||
def freeze_evidence(self, profile: Any, frozen_at: Any) -> int: return self._call('freeze_evidence', profile, frozen_at)
|
||||
def extract(self, **context: Any) -> Any: return self._call('extract', **context)
|
||||
def publish_checks(self, profile: Any, *, validation: Any | None) -> list[dict[str, Any]]: return self._call('publish_checks', profile, validation=validation)
|
||||
def instant_summary(self, profile: Any) -> dict[str, Any]: return self._call('instant_summary', profile)
|
||||
def extract_current_sample(self, *, profile: Any, sample: Any, actor_id: int | None) -> tuple[str, dict[str, Any], dict[str, Any]]: return self._call('extract_current_sample', profile=profile, sample=sample, actor_id=actor_id)
|
||||
def build_identity_snapshot(self, *, profile: Any, revision: Any, samples: list[Any]) -> tuple[dict[str, Any], dict[str, Any]]: return self._call('build_identity_snapshot', profile=profile, revision=revision, samples=samples)
|
||||
def build_overlap_evidence(self, *, profile: Any, signature_run: Any, training_samples: list[Any], blind_samples: list[Any]) -> tuple[str, dict[str, Any], dict[str, Any]]: return self._call('build_overlap_evidence', profile=profile, signature_run=signature_run, training_samples=training_samples, blind_samples=blind_samples)
|
||||
def blind_parser(self, profile: Any) -> Any: return self._call('blind_parser', profile)
|
||||
def blind_candidate(self, *, profile: Any, sample: Any) -> dict[str, Any]: return self._call('blind_candidate', profile=profile, sample=sample)
|
||||
def blind_gate_failures(self, *, candidate: dict[str, Any], sample_id: int) -> tuple[list[str], dict[str, float] | None]: return self._call('blind_gate_failures', candidate=candidate, sample_id=sample_id)
|
||||
def initial_definition(self, **context: Any) -> tuple[dict[str, Any], dict[str, Any]]: return self._call('initial_definition', **context)
|
||||
def readonly_mapping_evidence(self, profile: Any) -> dict[str, Any] | None: return self._call('readonly_mapping_evidence', profile)
|
||||
def frozen_evidence_ready(self, evidence: dict[str, Any] | None) -> bool: return self._call('frozen_evidence_ready', evidence)
|
||||
def validate_frozen_layout_identity(self, *, evidence: dict[str, Any], layout_version: Any) -> None: self._call('validate_frozen_layout_identity', evidence=evidence, layout_version=layout_version)
|
||||
def prepare_context(self, document: Any, *, layout_version_id: int | None = None) -> dict[str, Any]: return self._call('prepare_context', document, layout_version_id=layout_version_id)
|
||||
def normalize_definition(self, raw: dict[str, Any], *, schema_version: Any, path_context: dict[str, Any] | None) -> dict[str, Any]: return self._call('normalize_definition', raw, schema_version=schema_version, path_context=path_context)
|
||||
def match_evidence(self, definition: dict[str, Any]) -> dict[str, Any] | None: return self._call('match_evidence', definition)
|
||||
def definition_audit_summary(self, definition: dict[str, Any]) -> dict[str, Any] | None: return self._call('definition_audit_summary', definition)
|
||||
def business_fingerprint(self, definition: dict[str, Any]) -> str | None: return self._call('business_fingerprint', definition)
|
||||
def record_mapping_audit(self, **context: Any) -> None: self._call('record_mapping_audit', **context)
|
||||
def identity_summary(self, summary: dict[str, Any], snapshot: dict[str, Any]) -> dict[str, Any]: return self._call('identity_summary', summary, snapshot)
|
||||
def mapping_field_tree(self, *, document_id: int, actor_id: int | None) -> dict[str, Any]: return self._call('mapping_field_tree', document_id=document_id, actor_id=actor_id)
|
||||
def mapping_collections(self, *, document_id: int, actor_id: int | None) -> dict[str, Any]: return self._call('mapping_collections', document_id=document_id, actor_id=actor_id)
|
||||
def mapping_value_preview(self, *, document_id: int, path_id: str, actor_id: int | None, include_full_value: bool) -> dict[str, Any]: return self._call('mapping_value_preview', document_id=document_id, path_id=path_id, actor_id=actor_id, include_full_value=include_full_value)
|
||||
def mapping_split_preview(self, **context: Any) -> dict[str, Any]: return self._call('mapping_split_preview', **context)
|
||||
def mapping_split_validation(self, **context: Any) -> dict[str, Any]: return self._call('mapping_split_validation', **context)
|
||||
def mapping_schema_fields(self, *, profile_id: int | None = None, schema_version_id: int | None = None) -> dict[str, dict[str, Any]]: return self._call('mapping_schema_fields', profile_id=profile_id, schema_version_id=schema_version_id)
|
||||
def mapping_rules_changed(self, previous: dict[str, Any], next_definition: dict[str, Any]) -> bool: return self._call('mapping_rules_changed', previous, next_definition)
|
||||
def enforce_mapping_confirmation(self, **context: Any) -> dict[str, Any]: return self._call('enforce_mapping_confirmation', **context)
|
||||
|
||||
|
||||
def _coordinate_operations() -> dict[str, Callable[..., Any]]:
|
||||
def no_evidence(_definition: dict[str, Any]) -> None: return None
|
||||
def validate(profile: Any, _definition: dict[str, Any]) -> None:
|
||||
from app.services.shipping_notice import order_document_profile_service as service
|
||||
service._definition_contract(profile)
|
||||
def freeze(_profile: Any, _frozen_at: Any) -> int: return 0
|
||||
def extract(**context: Any) -> Any:
|
||||
from app.services.shipping_notice import order_extraction_workflow as workflow
|
||||
return workflow._extract_coordinate_value_adapter_result(**context)
|
||||
def instant(profile: Any) -> dict[str, Any]:
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as service
|
||||
return service._instant_coordinate_summary(profile)
|
||||
def current(*, profile: Any, sample: Any, actor_id: int | None) -> Any:
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as service
|
||||
return service._extract_coordinate_current_sample(profile=profile, sample=sample, actor_id=actor_id)
|
||||
def identity(*, profile: Any, revision: Any, samples: list[Any]) -> Any:
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as service
|
||||
_ = revision
|
||||
return service._build_coordinate_identity_snapshot(profile=profile, samples=samples)
|
||||
def overlap(**context: Any) -> Any:
|
||||
from app.services.shipping_notice import order_document_profile_validation_service as service
|
||||
return service._build_coordinate_overlap_evidence(**context)
|
||||
def parser(profile: Any) -> Any:
|
||||
from app.services.shipping_notice import document_profile_quality_service as service
|
||||
return service._definition_contract(profile)
|
||||
def candidate(*, profile: Any, sample: Any) -> dict[str, Any]:
|
||||
from app.services.shipping_notice import document_profile_quality_service as service
|
||||
return service._candidate_for_sample(profile=profile, document_id=sample.document_id, table_id=sample.table_id, layout_version_id=sample.layout_version_id, layout_payload_checksum=sample.layout_payload_checksum)
|
||||
def gates(**_context: Any) -> tuple[list[str], None]: return [], None
|
||||
def initial(**context: Any) -> Any:
|
||||
from app.services.shipping_notice import order_document_profile_creation_service as service
|
||||
return service._build_coordinate_initial_definition(context['document'], context.get('analysis'), context['main_table_id'], context['data'])
|
||||
def prepare_context(_document: Any, **_context: Any) -> dict[str, Any]: return {}
|
||||
def normalize(raw: dict[str, Any], *, schema_version: Any, **_context: Any) -> dict[str, Any]:
|
||||
from app.services.shipping_notice import order_document_profile_service as service
|
||||
return service._normalize_coordinate_definition(raw, schema_version=schema_version)
|
||||
def identity_summary(summary: dict[str, Any], snapshot: dict[str, Any]) -> dict[str, Any]:
|
||||
signature = snapshot.get('signature') if isinstance(snapshot.get('signature'), dict) else {}
|
||||
return {'adapter': 'coordinate_ocr', 'tables_with_header_tokens': summary.get('tables_with_header_tokens'), 'header_token_coverage': summary.get('header_token_coverage'), 'provider_versions': signature.get('provider_versions')}
|
||||
def unsupported(**_context: Any) -> dict[str, Any]:
|
||||
raise ValidationError('This value source has no mapping workspace', code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE')
|
||||
return {'audit_evidence': no_evidence, 'validate_definition': validate, 'freeze_evidence': freeze, 'extract': extract, 'publish_checks': lambda _profile, **_kw: [], 'instant_summary': instant, 'extract_current_sample': current, 'build_identity_snapshot': identity, 'build_overlap_evidence': overlap, 'blind_parser': parser, 'blind_candidate': candidate, 'blind_gate_failures': gates, 'initial_definition': initial, 'readonly_mapping_evidence': lambda _profile: None, 'frozen_evidence_ready': lambda _evidence: True, 'validate_frozen_layout_identity': lambda **_context: None, 'prepare_context': prepare_context, 'normalize_definition': normalize, 'match_evidence': lambda _definition: None, 'definition_audit_summary': lambda _definition: None, 'business_fingerprint': lambda _definition: None, 'record_mapping_audit': lambda **_context: None, 'identity_summary': identity_summary, 'mapping_field_tree': unsupported, 'mapping_collections': unsupported, 'mapping_value_preview': unsupported, 'mapping_split_preview': unsupported, 'mapping_split_validation': unsupported, 'mapping_schema_fields': unsupported, 'mapping_rules_changed': lambda _previous, _next: False, 'enforce_mapping_confirmation': lambda **context: context['definition']}
|
||||
|
||||
|
||||
_COORDINATE = OrderProfileValueAdapter(key='coordinate_ocr', legacy_template_mode='coordinate', operations=_coordinate_operations())
|
||||
|
||||
|
||||
def get_value_adapter(definition_or_mode: dict[str, Any] | str | None) -> OrderProfileValueAdapter:
|
||||
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
|
||||
return xfa_dataset.get_adapter() if xfa_dataset.owns_definition(definition_or_mode) else _COORDINATE
|
||||
|
||||
|
||||
def adapter_key(definition_or_mode: dict[str, Any] | str | None) -> str:
|
||||
return get_value_adapter(definition_or_mode).key
|
||||
|
||||
|
||||
def get_runtime_value_adapter(*, layout: dict[str, Any] | None, selected_profile: dict[str, Any] | None) -> OrderProfileValueAdapter:
|
||||
if isinstance(selected_profile, dict):
|
||||
definition = selected_profile.get('definition') if isinstance(selected_profile.get('definition'), dict) else {}
|
||||
return get_value_adapter(definition or selected_profile.get('template_mode'))
|
||||
from app.services.shipping_notice.order_profile_value_adapters import xfa_dataset
|
||||
return xfa_dataset.get_adapter() if xfa_dataset.owns_layout(layout) else _COORDINATE
|
||||
@@ -0,0 +1,24 @@
|
||||
"""坐标/OCR 正式取值 adapter。
|
||||
|
||||
用途:提供坐标/OCR 值源在共同模板生命周期中的末端扩展点。
|
||||
依赖:由 order_profile_value_adapter 调用。
|
||||
逻辑:共同视觉与发布门禁已经在公共层处理,本模块不增加值源专属发布条件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def publish_checks(*, profile: Any, validation: Any | None) -> list[dict[str, Any]]:
|
||||
"""返回坐标/OCR 值源的附加发布阻断项。
|
||||
|
||||
Args:
|
||||
profile: 当前草稿模板;用于和其他 adapter 保持统一调用协议。
|
||||
validation: 当前样本验证运行;用于和其他 adapter 保持统一调用协议。
|
||||
|
||||
Returns:
|
||||
空列表,表示没有额外的末端值源门禁。
|
||||
"""
|
||||
_ = profile, validation
|
||||
return []
|
||||
File diff suppressed because it is too large.
Load diff
@@ -26,6 +26,7 @@ from app.models import (
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewStream,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_review_customer_service import (
|
||||
@@ -53,6 +54,14 @@ _TERMINAL_STATUSES = frozenset({
|
||||
})
|
||||
|
||||
|
||||
def _is_current_review_stream_case(case: ShippingOrderReviewCase) -> bool:
|
||||
"""仅允许文件 Stream 当前 Case 进入自动协调,历史版本即使状态异常也必须跳过。"""
|
||||
return db.session.query(ShippingOrderReviewStream.id).filter(
|
||||
ShippingOrderReviewStream.id == int(case.stream_id or 0),
|
||||
ShippingOrderReviewStream.current_case_id == int(case.id),
|
||||
).first() is not None
|
||||
|
||||
|
||||
# build_review_revalidate_job_ref 已经移动到 recovery_contract.py 作为契约层函数,
|
||||
# 这里保留薄 re-export,确保历史调用方(如有)不被破坏。
|
||||
# (draft_service 已改为从 recovery_contract import,断环。)
|
||||
@@ -218,6 +227,14 @@ def reconcile_single_case_for_auto_progress(
|
||||
return result
|
||||
result['case_no'] = str(loaded_case.case_no or '')
|
||||
|
||||
# [STREAM-CURRENT] Run/Case 都是审计谱系;非当前版本禁止触发客户确认、
|
||||
# Draft 校验或 STP 入队,以免历史开放状态重新推进业务。
|
||||
if not _is_current_review_stream_case(loaded_case):
|
||||
result['enqueue_status'] = 'not_current_stream_case'
|
||||
result['customer_step_status'] = 'skipped'
|
||||
result['validate_status'] = 'skipped'
|
||||
return result
|
||||
|
||||
# [STEP 1] 终态检查 + 已确认检查
|
||||
if loaded_case.confirmed_task_id or str(loaded_case.status or '') in _TERMINAL_STATUSES:
|
||||
result['enqueue_status'] = 'already_confirmed_or_terminal'
|
||||
@@ -314,12 +331,17 @@ def reconcile_run_review_cases_for_auto_progress(
|
||||
"""
|
||||
results: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 0] 加载 Run 下全部 Case 主键列表(固定顺序,避免重复扫描)
|
||||
# [STEP 0] Run 只提供执行范围;自动推进只能枚举文件 Stream 当前 Case,
|
||||
# 不能因旧 Case 状态残留而重启已替代版本。
|
||||
case_ids = [
|
||||
int(row.id)
|
||||
for row in (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(run_id=int(run.id))
|
||||
.join(
|
||||
ShippingOrderReviewStream,
|
||||
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
|
||||
)
|
||||
.filter(ShippingOrderReviewCase.run_id == int(run.id))
|
||||
.order_by(ShippingOrderReviewCase.id.asc())
|
||||
.with_entities(ShippingOrderReviewCase.id)
|
||||
.all()
|
||||
|
||||
@@ -1524,6 +1524,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
case.status = 'confirmed'
|
||||
case.confirmed_task_id = int(task.id)
|
||||
case.confirmed_at = datetime.utcnow()
|
||||
# [STEP] 文件主线锁定已确认版本;后完成的并行重解析不得覆盖正式履约事实。
|
||||
from app.services.shipping_notice.review_stream_service import mark_review_stream_confirmed
|
||||
mark_review_stream_confirmed(case=case)
|
||||
db.session.add(ShippingOrderReviewCaseEvent(
|
||||
case_id=int(case.id), event_type='case_confirmed', draft_version=int(case.current_draft.draft_version),
|
||||
actor_user_id=int(user_id), operation_json={
|
||||
|
||||
@@ -14,6 +14,7 @@ WorkflowItem 已关闭等)在抛错前独立 commit 拒绝审计,避免 API
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from typing import Any, NoReturn
|
||||
|
||||
from app import db
|
||||
@@ -21,10 +22,12 @@ from app.core.errors import AppError, ConflictError, NotFoundError, ValidationEr
|
||||
from app.models import (
|
||||
Agent,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewCaseEvent,
|
||||
ShippingOrderReviewDraft,
|
||||
ShippingOrderReviewStream,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
@@ -38,7 +41,201 @@ _QUALITY_REASONS = frozenset({
|
||||
})
|
||||
_NON_ORDER_REASONS = frozenset({'non_order', 'duplicate_file', 'other'})
|
||||
_TERMINAL_DISPOSITION_STATUSES = frozenset({'confirmed', 'non_order', 'superseded', 'reparse_pending'})
|
||||
_REPLACEMENT_ALLOWED_STATUSES = frozenset({'quality_issue', 'draft', 'ready', 'unreviewed'})
|
||||
|
||||
|
||||
def _run_lineage_root(*, run: ShippingOrderProcessingRun) -> ShippingOrderProcessingRun:
|
||||
"""沿重解析父链定位批次的初始 Run,阻止从局部子 Run 缩小原批次范围。"""
|
||||
current = run
|
||||
seen_ids = {int(run.id)}
|
||||
while current.reparse_of_run_id:
|
||||
parent = db.session.get(ShippingOrderProcessingRun, int(current.reparse_of_run_id))
|
||||
if parent is None or int(parent.id) in seen_ids:
|
||||
break
|
||||
seen_ids.add(int(parent.id))
|
||||
current = parent
|
||||
return current
|
||||
|
||||
|
||||
def _lineage_runs(*, root: ShippingOrderProcessingRun, user_id: int) -> list[ShippingOrderProcessingRun]:
|
||||
"""
|
||||
收集根 Run 的全部后继版本,供批次命令逐 PDF 选择当前 Case。
|
||||
|
||||
核心逻辑:谱系闭包仅沿 `reparse_of_run_id` 展开,不按会话或文件名扩大范围;
|
||||
每轮只查询尚未发现的父 Run,防止异常循环造成无限遍历。
|
||||
"""
|
||||
by_id = {int(root.id): root}
|
||||
frontier = {int(root.id)}
|
||||
while frontier:
|
||||
children = ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.user_id == int(user_id),
|
||||
ShippingOrderProcessingRun.reparse_of_run_id.in_(frontier),
|
||||
).all()
|
||||
next_frontier: set[int] = set()
|
||||
for child in children:
|
||||
child_id = int(child.id)
|
||||
if child_id in by_id:
|
||||
continue
|
||||
by_id[child_id] = child
|
||||
next_frontier.add(child_id)
|
||||
frontier = next_frontier
|
||||
return sorted(by_id.values(), key=lambda item: (item.created_at, int(item.id)))
|
||||
|
||||
|
||||
def _case_document_identity(*, case: ShippingOrderReviewCase, documents_by_id: dict[int, ShippingOrderDocument]) -> str:
|
||||
"""返回批次 Case 的稳定文件身份:内容哈希优先,缺失时才退回原始 Document ID。"""
|
||||
document_id = int(case.document_id or 0)
|
||||
document = documents_by_id.get(document_id)
|
||||
content_hash = str(getattr(document, 'content_hash', None) or '').strip().lower()
|
||||
if content_hash:
|
||||
return f'content-hash:{content_hash}'
|
||||
return f'document:{document_id}'
|
||||
|
||||
|
||||
def select_current_batch_reparse_cases(
|
||||
*, user_id: int, run: ShippingOrderProcessingRun,
|
||||
) -> tuple[ShippingOrderProcessingRun, list[ShippingOrderReviewCase]]:
|
||||
"""
|
||||
从批次 Run 谱系为每个原 PDF 选择最新 Review Case。
|
||||
|
||||
该函数是“重新解析本批次”的唯一选取边界:来源 Run 的旧 Case 即使已被
|
||||
局部重解析替代,也会由后继 Run 的同文件 Case 接管;同名不同内容不会合并。
|
||||
返回根 Run 供审计固定批次身份,返回的 Case 按稳定文件身份排序以保证响应稳定。
|
||||
"""
|
||||
# Stream 已建立后,它才是文件级当前版本事实;避免从批次 Run 支路回退到旧 Case。
|
||||
from app.models import ShippingOrderReviewStream
|
||||
stream_cases = (
|
||||
db.session.query(ShippingOrderReviewCase)
|
||||
.join(ShippingOrderReviewStream, ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id)
|
||||
.join(ShippingOrderProcessingRun, ShippingOrderProcessingRun.id == ShippingOrderReviewCase.run_id)
|
||||
.filter(
|
||||
ShippingOrderReviewStream.owner_user_id == int(user_id),
|
||||
ShippingOrderProcessingRun.conversation_id == str(run.conversation_id),
|
||||
)
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
if stream_cases:
|
||||
root = _run_lineage_root(run=run)
|
||||
return root, sorted(stream_cases, key=lambda item: int(item.document_id))
|
||||
root = _run_lineage_root(run=run)
|
||||
runs = _lineage_runs(root=root, user_id=user_id)
|
||||
run_ids = [int(item.id) for item in runs]
|
||||
cases = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter(
|
||||
ShippingOrderReviewCase.owner_user_id == int(user_id),
|
||||
ShippingOrderReviewCase.run_id.in_(run_ids),
|
||||
)
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
document_ids = {int(case.document_id) for case in cases if int(case.document_id or 0) > 0}
|
||||
documents_by_id = {
|
||||
int(document.id): document
|
||||
for document in ShippingOrderDocument.query.filter(ShippingOrderDocument.id.in_(document_ids)).all()
|
||||
} if document_ids else {}
|
||||
run_recency = {int(item.id): index for index, item in enumerate(runs)}
|
||||
selected: dict[str, ShippingOrderReviewCase] = {}
|
||||
for case in cases:
|
||||
identity = _case_document_identity(case=case, documents_by_id=documents_by_id)
|
||||
existing = selected.get(identity)
|
||||
if existing is None or run_recency[int(case.run_id)] > run_recency[int(existing.run_id)]:
|
||||
selected[identity] = case
|
||||
return root, [selected[key] for key in sorted(selected)]
|
||||
|
||||
|
||||
def has_reparseable_batch_documents(*, user_id: int, run: ShippingOrderProcessingRun) -> bool:
|
||||
"""供投影判断批次操作可见性;确认/履约与非订单文件不作为可重解析目标。"""
|
||||
_root, cases = select_current_batch_reparse_cases(user_id=user_id, run=run)
|
||||
return any(
|
||||
str(case.status or '').strip().lower() in {'unreviewed', 'draft', 'ready', 'quality_issue', 'reparse_pending'}
|
||||
and case.confirmed_task_id is None
|
||||
for case in cases
|
||||
)
|
||||
|
||||
|
||||
def reparse_batch_documents(
|
||||
*, user_id: int, run_no: str, reason: str, comment: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为一个批次内仍可替换的 PDF 创建独立重解析子 Run。
|
||||
|
||||
核心逻辑:批次入口跨订单复核阶段可用,但只纳入未确认、未进入履约且未被
|
||||
其他版本替代的 Case;每个 Case 仍复用单 PDF 重识别路径,故成功后才局部
|
||||
替换,失败则恢复旧草稿。被排除的已确认/终态文件明确返回原因,绝不静默覆盖。
|
||||
"""
|
||||
source = (
|
||||
ShippingOrderProcessingRun.query
|
||||
.filter_by(user_id=int(user_id), run_no=str(run_no or '').strip())
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
if source is None:
|
||||
raise NotFoundError('Shipping order extraction run not found', code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND')
|
||||
if str(source.status or '') not in {'completed', 'partially_completed', 'review_required', 'failed', 'cancelled'}:
|
||||
raise ConflictError(
|
||||
'Only terminal order extraction runs can be reparsed',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE', details={'status': source.status},
|
||||
)
|
||||
normalized = str(reason or '').strip().lower()
|
||||
if normalized not in _REPARSE_REASONS:
|
||||
raise ValidationError('Invalid reparse reason', code='SHIPPING_NOTICE.ORDER_EXTRACTION_REPARSE_REASON_INVALID')
|
||||
|
||||
batch_reparse_id = f'BRP-{uuid.uuid4().hex[:16].upper()}'
|
||||
root, cases = select_current_batch_reparse_cases(user_id=user_id, run=source)
|
||||
created: list[dict[str, Any]] = []
|
||||
excluded: list[dict[str, Any]] = []
|
||||
for case in cases:
|
||||
status = str(case.status or '').strip().lower()
|
||||
if status in {'confirmed', 'confirming'} or case.confirmed_task_id is not None:
|
||||
excluded.append({'case_no': case.case_no, 'document_id': case.document_id, 'reason_code': 'confirmed_or_fulfillment_started'})
|
||||
continue
|
||||
if status in {'non_order', 'superseded'}:
|
||||
excluded.append({'case_no': case.case_no, 'document_id': case.document_id, 'reason_code': f'case_{status}'})
|
||||
continue
|
||||
run, reused = reparse_case_document(
|
||||
user_id=user_id,
|
||||
case_no=case.case_no,
|
||||
reason=normalized,
|
||||
comment=comment,
|
||||
batch_reparse_id=batch_reparse_id,
|
||||
)
|
||||
created.append({
|
||||
'case_no': case.case_no,
|
||||
'document_id': int(case.document_id),
|
||||
'run_no': run.run_no,
|
||||
'reused': bool(reused),
|
||||
})
|
||||
|
||||
record_fulfillment_audit(
|
||||
event_type='batch_document_reparse_requested',
|
||||
aggregate_type='order_extraction_batch',
|
||||
aggregate_id=str(root.run_no),
|
||||
action='reparse_batch',
|
||||
actor_type='user',
|
||||
actor_id=user_id,
|
||||
owner_user_id=user_id,
|
||||
run_no=root.run_no,
|
||||
conversation_id=str(source.conversation_id or '') or None,
|
||||
reason_code=normalized,
|
||||
reason=str(comment or '').strip()[:500] or None,
|
||||
before={'status': source.status, 'selected_document_count': len(cases)},
|
||||
after={'status': source.status, 'created_document_count': len(created), 'excluded_document_count': len(excluded)},
|
||||
metadata={
|
||||
'batch_reparse_id': batch_reparse_id,
|
||||
'created_document_count': len(created),
|
||||
'excluded_document_count': len(excluded),
|
||||
'excluded_reason_codes': sorted({str(item['reason_code']) for item in excluded}),
|
||||
},
|
||||
source='order_review',
|
||||
)
|
||||
return {
|
||||
'batch_reparse_id': batch_reparse_id,
|
||||
'source_run_no': source.run_no,
|
||||
'root_run_no': root.run_no,
|
||||
'created': created,
|
||||
'excluded': excluded,
|
||||
}
|
||||
|
||||
|
||||
def _locked_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
|
||||
@@ -600,7 +797,14 @@ def mark_quality_issue(*, user_id: int, case_no: str, reason: str, comment: str
|
||||
return serialize_review_case(case)
|
||||
|
||||
|
||||
def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: str | None = None) -> tuple[ShippingOrderProcessingRun, bool]:
|
||||
def reparse_case_document(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
reason: str,
|
||||
comment: str | None = None,
|
||||
batch_reparse_id: str | None = None,
|
||||
) -> tuple[ShippingOrderProcessingRun, bool]:
|
||||
"""
|
||||
仅以当前 Case 的 Document 创建新版 Run;重复点击复用同一后继 Run。
|
||||
|
||||
@@ -611,6 +815,7 @@ def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: s
|
||||
case_no: 复核 Case 编号。
|
||||
reason: 重识别原因码。
|
||||
comment: 自由说明。
|
||||
batch_reparse_id: 批次重解析请求号;仅关联审计与文件子 Run,不改变 Case 边界。
|
||||
|
||||
Returns:
|
||||
(后继 Run, 是否复用既有 Run)。
|
||||
@@ -625,6 +830,22 @@ def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: s
|
||||
error=ConflictError('Order review case cannot be reparsed', code='SHIPPING.REVIEW_REPARSE_NOT_ALLOWED'),
|
||||
reason_code=str(reason or '').strip().lower()[:64] or None,
|
||||
)
|
||||
# 重解析只能从文件 Stream 当前版本发起;历史 Case 即使 status 被旧数据
|
||||
# 错误恢复为开放态,也不得再次创建 Run 或制造新的版本分支。
|
||||
if case.stream_id is not None:
|
||||
stream = db.session.get(ShippingOrderReviewStream, int(case.stream_id))
|
||||
if stream is not None and stream.current_case_id != int(case.id):
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='document_reparse_requested',
|
||||
action='reparse_document',
|
||||
error=ConflictError(
|
||||
'Only the current review stream case can be reparsed',
|
||||
code='SHIPPING.REVIEW_REPARSE_NOT_ALLOWED',
|
||||
),
|
||||
reason_code=str(reason or '').strip().lower()[:64] or None,
|
||||
)
|
||||
normalized = _require_reason(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
@@ -737,6 +958,7 @@ def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: s
|
||||
reparse_source_candidate_id=int(case.candidate_id) if case.candidate_id is not None else None,
|
||||
reparse_source_order_task_no=str(order_task.task_no) if order_task is not None else None,
|
||||
reparse_requested_by_user_id=int(user_id),
|
||||
batch_reparse_id=batch_reparse_id,
|
||||
)
|
||||
if reused:
|
||||
_audit_idempotent_reparse_reuse(
|
||||
@@ -792,231 +1014,6 @@ def reparse_case_document(*, user_id: int, case_no: str, reason: str, comment: s
|
||||
return run, False
|
||||
|
||||
|
||||
def create_replacement_upload_intake(*, user_id: int, case_no: str, asset_no: str) -> dict[str, Any]:
|
||||
"""为质量异常 PDF 建立新的私有 Intake;新文件永不覆盖原 Document 或旧 Case。"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status not in _REPLACEMENT_ALLOWED_STATUSES:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_intake_created',
|
||||
action='create_replacement_intake',
|
||||
error=ConflictError('Order review case cannot upload a replacement', code='SHIPPING.REVIEW_REPLACEMENT_NOT_ALLOWED'),
|
||||
)
|
||||
source = db.session.get(ShippingOrderProcessingRun, int(case.run_id))
|
||||
if source is None:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_intake_created',
|
||||
action='create_replacement_intake',
|
||||
error=ConflictError('Review replacement source is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID'),
|
||||
)
|
||||
from app.services.file_assets.service import get_asset_for_user
|
||||
from app.services.shipping_notice.intake_service import create_shipping_notice_intake
|
||||
|
||||
try:
|
||||
asset = get_asset_for_user(str(asset_no or '').strip(), int(user_id))
|
||||
except AppError as err:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_intake_created',
|
||||
action='create_replacement_intake',
|
||||
error=err,
|
||||
metadata={'asset_no': str(asset_no or '').strip()[:64] or None},
|
||||
)
|
||||
extension = str(asset.extension or '').strip().lower()
|
||||
if extension != 'pdf':
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_intake_created',
|
||||
action='create_replacement_intake',
|
||||
error=ValidationError('Replacement file must be a PDF', code='SHIPPING.REVIEW_REPLACEMENT_FILE_INVALID'),
|
||||
)
|
||||
intake = create_shipping_notice_intake(
|
||||
user_id=int(user_id), asset_no=str(asset.asset_no), conversation_id=str(source.conversation_id),
|
||||
upload_batch_id=f'review-replacement-{case.case_no.lower()}',
|
||||
)
|
||||
_append_event(case, actor_id=user_id, event_type='replacement_upload_created', operation={
|
||||
'replacement_intake_no': intake['intake_no'],
|
||||
})
|
||||
_record_unified_disposition_audit(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_intake_created',
|
||||
action='create_replacement_intake',
|
||||
before={'status': case.status},
|
||||
after={'status': case.status, 'replacement_intake_no': intake['intake_no']},
|
||||
metadata={'replacement_intake_no': intake['intake_no']},
|
||||
)
|
||||
db.session.flush()
|
||||
return intake
|
||||
|
||||
|
||||
def create_replacement_document_run(*, user_id: int, case_no: str, intake_no: str) -> tuple[ShippingOrderProcessingRun, bool]:
|
||||
"""
|
||||
在替代 Intake 已解析为唯一 PDF Document 后创建新 Run,并把旧 Case 置为等待替代结果。
|
||||
|
||||
核心逻辑:create 返回 reused 时仍写 Case 级幂等审计;状态/解析不满足时写拒绝审计。
|
||||
"""
|
||||
case = _locked_case(user_id=user_id, case_no=case_no)
|
||||
if case.status not in _REPLACEMENT_ALLOWED_STATUSES:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=ConflictError('Order review case cannot use a replacement', code='SHIPPING.REVIEW_REPLACEMENT_NOT_ALLOWED'),
|
||||
)
|
||||
source = db.session.get(ShippingOrderProcessingRun, int(case.run_id))
|
||||
user = db.session.get(User, int(user_id))
|
||||
owner_agent = db.session.get(Agent, int(source.owner_agent_id)) if source is not None else None
|
||||
if source is None or user is None or owner_agent is None:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=ConflictError('Review replacement source is unavailable', code='SHIPPING.REVIEW_REPARSE_SOURCE_INVALID'),
|
||||
)
|
||||
from app.models import ShippingOrderDocument, ShippingOrderIntake
|
||||
|
||||
intake = ShippingOrderIntake.query.filter_by(
|
||||
intake_no=str(intake_no or '').strip().upper(), user_id=int(user_id), purpose='shipping_notice',
|
||||
).with_for_update().first()
|
||||
if intake is None or str(intake.conversation_id or '') != str(source.conversation_id or ''):
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=NotFoundError('Replacement intake not found', code='SHIPPING.REVIEW_REPLACEMENT_NOT_FOUND'),
|
||||
metadata={'replacement_intake_no': str(intake_no or '').strip().upper() or None},
|
||||
)
|
||||
if intake.parse_status != 'parsed':
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=ConflictError('Replacement PDF is still parsing', code='SHIPPING.REVIEW_REPLACEMENT_PENDING'),
|
||||
metadata={'replacement_intake_no': intake.intake_no, 'parse_status': str(intake.parse_status or '')},
|
||||
)
|
||||
documents = ShippingOrderDocument.query.filter_by(intake_id=int(intake.id)).filter(
|
||||
ShippingOrderDocument.document_type != 'email_body',
|
||||
).all()
|
||||
pdfs = [item for item in documents if str(item.filename or '').lower().endswith('.pdf')]
|
||||
if len(pdfs) != 1:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=ConflictError('Replacement intake must contain exactly one PDF', code='SHIPPING.REVIEW_REPLACEMENT_DOCUMENT_INVALID'),
|
||||
metadata={'replacement_intake_no': intake.intake_no, 'pdf_count': len(pdfs)},
|
||||
)
|
||||
_reject_if_work_item_closed(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
reason_code='document_quality',
|
||||
reason=f'replacement for {case.case_no}',
|
||||
)
|
||||
order_task = None
|
||||
if case.candidate_id is not None:
|
||||
try:
|
||||
order_task = _resolve_case_order_task(case)
|
||||
except ConflictError as exc:
|
||||
_reject_case_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=exc,
|
||||
reason_code='document_quality',
|
||||
reason=f'replacement for {case.case_no}',
|
||||
)
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user, agent_id=int(owner_agent.id), conversation_id=str(source.conversation_id), intake_nos=[intake.intake_no],
|
||||
upload_batch_id=intake.upload_batch_id, reparse_of_run=source, reparse_reason='document_quality',
|
||||
reparse_comment=f'replacement for {case.case_no}', selected_document_id=int(pdfs[0].id), reparse_case_no=case.case_no,
|
||||
user_task_no=str(order_task.task_no) if order_task is not None else None,
|
||||
reparse_source_candidate_id=int(case.candidate_id) if case.candidate_id is not None else None,
|
||||
reparse_source_order_task_no=str(order_task.task_no) if order_task is not None else None,
|
||||
reparse_requested_by_user_id=int(user_id),
|
||||
)
|
||||
if reused:
|
||||
_audit_idempotent_reparse_reuse(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
successor_run=run,
|
||||
reason_code='document_quality',
|
||||
reason=f'replacement for {case.case_no}',
|
||||
metadata={
|
||||
'replacement_intake_no': intake.intake_no,
|
||||
'replacement_document_id': int(pdfs[0].id),
|
||||
},
|
||||
)
|
||||
db.session.flush()
|
||||
return run, True
|
||||
previous = case.status
|
||||
case.status = 'reparse_pending'
|
||||
_append_event(case, actor_id=user_id, event_type='replacement_reparse_started', operation={
|
||||
'previous_status': previous, 'replacement_intake_no': intake.intake_no,
|
||||
'replacement_document_id': int(pdfs[0].id), 'successor_run_no': run.run_no,
|
||||
})
|
||||
_record_unified_disposition_audit(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
before={'status': previous},
|
||||
after={
|
||||
'status': case.status,
|
||||
'replacement_intake_no': intake.intake_no,
|
||||
'successor_run_no': run.run_no,
|
||||
},
|
||||
reason_code='document_quality',
|
||||
metadata={
|
||||
'replacement_document_id': int(pdfs[0].id),
|
||||
'successor_run_no': run.run_no,
|
||||
},
|
||||
run_no=run.run_no,
|
||||
)
|
||||
from app.services.shipping_notice.workflow_ledger_service import mark_reparse_started
|
||||
try:
|
||||
mark_reparse_started(
|
||||
case=case,
|
||||
successor_run=run,
|
||||
reason='document_quality',
|
||||
comment=f'replacement for {case.case_no}',
|
||||
actor_id=user_id,
|
||||
replacement_document_id=int(pdfs[0].id),
|
||||
)
|
||||
except ConflictError as err:
|
||||
_reject_reparse_after_dirty_failure(
|
||||
case_no=str(case.case_no),
|
||||
owner_user_id=int(case.owner_user_id),
|
||||
actor_id=user_id,
|
||||
event_type='review_replacement_reparse_started',
|
||||
action='start_replacement_reparse',
|
||||
error=err,
|
||||
reason_code='document_quality',
|
||||
reason=f'replacement for {case.case_no}',
|
||||
metadata={
|
||||
'replacement_intake_no': intake.intake_no,
|
||||
'successor_run_no': run.run_no,
|
||||
},
|
||||
)
|
||||
db.session.flush()
|
||||
return run, False
|
||||
|
||||
|
||||
def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: bool) -> None:
|
||||
"""在新版 Run 终态收口旧 Case:成功替代,失败恢复原草稿的原生命周期。"""
|
||||
marker = (run.input_snapshot_json or {}).get('review_reparse')
|
||||
@@ -1038,17 +1035,26 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo
|
||||
if source_case is None or source_case.status != 'reparse_pending':
|
||||
return
|
||||
if succeeded:
|
||||
source_case.status = 'superseded'
|
||||
source_case.disposition = 'reparsed'
|
||||
replacement_case = ShippingOrderReviewCase.query.filter_by(
|
||||
run_id=int(run.id), document_id=document_id,
|
||||
).with_for_update().first()
|
||||
if replacement_case is None:
|
||||
# Run 已到终态但没有可复核新版本时,不可废弃旧草稿。
|
||||
return
|
||||
from app.services.shipping_notice.review_stream_service import activate_review_case
|
||||
activate_review_case(
|
||||
case=replacement_case,
|
||||
trigger='batch_reparse_succeeded' if marker.get('batch_reparse_id') else 'document_reparse_succeeded',
|
||||
)
|
||||
_append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={
|
||||
'successor_run_no': run.run_no,
|
||||
'replacement_case_no': replacement_case.case_no,
|
||||
})
|
||||
# 成功切换由 bind_cases_for_run(新 Case 初始化)完成版本指针;此处不提前改指针。
|
||||
return
|
||||
previous = 'quality_issue'
|
||||
event = ShippingOrderReviewCaseEvent.query.filter(
|
||||
ShippingOrderReviewCaseEvent.case_id == int(source_case.id),
|
||||
ShippingOrderReviewCaseEvent.event_type.in_({'document_reparse_started', 'replacement_reparse_started'}),
|
||||
ShippingOrderReviewCaseEvent.event_type == 'document_reparse_started',
|
||||
).order_by(ShippingOrderReviewCaseEvent.id.desc()).first()
|
||||
if event is not None and isinstance(event.operation_json, dict):
|
||||
requested = str(event.operation_json.get('previous_status') or '')
|
||||
|
||||
@@ -39,11 +39,7 @@ from app.models import (
|
||||
ShippingOrderReviewSuggestion,
|
||||
)
|
||||
from app.services.shipping_notice.order_build_eligibility_service import (
|
||||
apply_manual_inventory_candidates,
|
||||
apply_rule_suggestion_as_effective,
|
||||
attach_rule_suggestion_without_override,
|
||||
assess_order_build_eligibility,
|
||||
mark_keep_manual_inventory_decision,
|
||||
project_line_inventory_candidates,
|
||||
)
|
||||
# 注意:build_review_revalidate_job_ref 放在 recovery_contract.py(零依赖契约模块),
|
||||
@@ -1090,70 +1086,6 @@ def validate_draft(*, user_id: int, case_no: str, expected_draft_version: Any) -
|
||||
return _record_change(case, actor_id=user_id, event_type=action, operation={}, validate=True)
|
||||
|
||||
|
||||
def set_line_inventory_candidates(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
line_key: str,
|
||||
source_codes: list[str],
|
||||
reason: str,
|
||||
expected_draft_version: Any,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
人工为明细选择 1..N 个已启用库存源候选(强制填写原因)。
|
||||
|
||||
核心逻辑:写入行级 inventory_routing 覆盖层并跑全量校验;不修改机器 Candidate。
|
||||
|
||||
Args:
|
||||
user_id: 操作人。
|
||||
case_no: 复核 Case 编号。
|
||||
line_key: 稳定行键。
|
||||
source_codes: 候选库存源编码。
|
||||
reason: 人工选择原因。
|
||||
expected_draft_version: 乐观锁版本。
|
||||
|
||||
Returns:
|
||||
序列化后的 Case 详情。
|
||||
"""
|
||||
action = 'line_inventory_candidates_selected'
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
|
||||
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
target = _find_line(case, lines, line_key, actor_id=user_id, action=action)
|
||||
try:
|
||||
overlay = apply_manual_inventory_candidates(
|
||||
line_meta=target,
|
||||
source_codes=list(source_codes or []),
|
||||
reason=reason,
|
||||
)
|
||||
except ValueError as exc:
|
||||
code = str(exc)
|
||||
_reject_draft_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
action=action,
|
||||
error=ValidationError(
|
||||
'Manual inventory source selection is invalid',
|
||||
code='SHIPPING.REVIEW_INVENTORY_CANDIDATES_INVALID',
|
||||
details={'reason': code},
|
||||
),
|
||||
metadata={'line_key': str(line_key)[:64], 'reason': code},
|
||||
)
|
||||
case.current_draft.lines_json = lines
|
||||
return _record_change(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type=action,
|
||||
operation={
|
||||
'line_key': line_key,
|
||||
'candidate_inventory_source_codes': list(overlay.get('candidate_inventory_source_codes') or []),
|
||||
'manual_reason': str(overlay.get('manual_reason') or '')[:200],
|
||||
'new_value': list(overlay.get('candidate_inventory_source_codes') or []),
|
||||
},
|
||||
validate=True,
|
||||
)
|
||||
|
||||
|
||||
# 路由恢复幂等历史上限;超限按插入顺序淘汰最旧条目。
|
||||
_ROUTING_IDEMPOTENCY_HISTORY_LIMIT = 64
|
||||
_ROUTING_IDEMPOTENCY_STORE_KEY = 'inventory_routing_recovery_idempotency'
|
||||
@@ -1363,10 +1295,7 @@ def reroute_inventory_routing(
|
||||
},
|
||||
line_meta={**raw, 'inventory_routing': {}},
|
||||
)
|
||||
attach_rule_suggestion_without_override(
|
||||
line_meta=raw,
|
||||
suggestion=dict(suggestion_projection.get('rule_suggestion') or {}),
|
||||
)
|
||||
raw.pop('inventory_routing', None)
|
||||
after_rows.append(_line_routing_snapshot(raw, fields, header_by_code))
|
||||
touched_keys.append(current_key)
|
||||
|
||||
@@ -1636,168 +1565,6 @@ def _sync_review_gates_safe(
|
||||
)
|
||||
|
||||
|
||||
def adopt_inventory_routing_suggestion(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
line_key: str,
|
||||
expected_draft_version: Any,
|
||||
idempotency_key: str | None = None,
|
||||
reason: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
采用当前规则建议为有效库存源候选(明确动作)。
|
||||
|
||||
Args:
|
||||
user_id / case_no / line_key: 定位目标。
|
||||
expected_draft_version: 乐观锁。
|
||||
idempotency_key: 可选幂等键。
|
||||
reason: 采用说明;缺省写入动作语义 adopt_rule_suggestion。
|
||||
|
||||
Returns:
|
||||
序列化 Case。
|
||||
"""
|
||||
action = 'inventory_routing_suggestion_adopted'
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
|
||||
replay = _routing_recovery_replay(case, action=f'{action}:{line_key}', idempotency_key=str(idempotency_key or ''))
|
||||
if replay is not None:
|
||||
return replay
|
||||
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
|
||||
|
||||
fields = _schema_fields(case)
|
||||
header_by_code = _header_by_code_for_case(case, fields)
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
target = _find_line(case, lines, line_key, actor_id=user_id, action=action)
|
||||
before = _line_routing_snapshot(target, fields, header_by_code)
|
||||
# 实时重算建议,避免采用陈旧 overlay。
|
||||
live = project_line_inventory_candidates(
|
||||
fields=fields,
|
||||
header_by_code=header_by_code,
|
||||
line_by_code={
|
||||
str(field.get('field_code') or field_id): _current_value(target, field_id)
|
||||
for field_id, field in fields.items()
|
||||
if str(field.get('scope') or '') == 'line'
|
||||
},
|
||||
line_meta=target,
|
||||
)
|
||||
suggestion = dict(live.get('rule_suggestion') or {})
|
||||
try:
|
||||
overlay = apply_rule_suggestion_as_effective(
|
||||
line_meta=target,
|
||||
suggestion=suggestion,
|
||||
reason=str(reason or 'adopt_rule_suggestion'),
|
||||
)
|
||||
except ValueError as exc:
|
||||
_reject_draft_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
action=action,
|
||||
error=ValidationError(
|
||||
'Rule inventory suggestion cannot be adopted',
|
||||
code='SHIPPING.REVIEW_INVENTORY_ROUTING_ADOPT_INVALID',
|
||||
details={'reason': str(exc)},
|
||||
),
|
||||
metadata={'line_key': str(line_key)[:64], 'reason': str(exc)},
|
||||
)
|
||||
case.current_draft.lines_json = lines
|
||||
after = _line_routing_snapshot(target, fields, header_by_code)
|
||||
_store_routing_recovery_idempotency(
|
||||
case,
|
||||
action=f'{action}:{line_key}',
|
||||
idempotency_key=str(idempotency_key or ''),
|
||||
line_keys=[str(line_key)],
|
||||
)
|
||||
return _record_change(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type=action,
|
||||
operation={
|
||||
'line_key': line_key,
|
||||
'idempotency_key': _normalize_routing_idempotency_key(idempotency_key) or None,
|
||||
'previous_value': before,
|
||||
'new_value': after,
|
||||
'candidate_inventory_source_codes': list(overlay.get('candidate_inventory_source_codes') or []),
|
||||
'rule_versions': list(after.get('rule_versions') or []),
|
||||
'action_semantics': 'adopt_rule_suggestion',
|
||||
},
|
||||
validate=True,
|
||||
)
|
||||
|
||||
|
||||
def keep_manual_inventory_routing(
|
||||
*,
|
||||
user_id: int,
|
||||
case_no: str,
|
||||
line_key: str,
|
||||
expected_draft_version: Any,
|
||||
idempotency_key: str | None = None,
|
||||
reason: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
明确保留人工库存源决定,拒绝当前规则建议。
|
||||
|
||||
Args:
|
||||
user_id / case_no / line_key: 定位目标。
|
||||
expected_draft_version: 乐观锁。
|
||||
idempotency_key: 可选幂等键。
|
||||
reason: 保留说明。
|
||||
|
||||
Returns:
|
||||
序列化 Case。
|
||||
"""
|
||||
action = 'inventory_routing_manual_kept'
|
||||
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
|
||||
replay = _routing_recovery_replay(case, action=f'{action}:{line_key}', idempotency_key=str(idempotency_key or ''))
|
||||
if replay is not None:
|
||||
return replay
|
||||
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
|
||||
|
||||
fields = _schema_fields(case)
|
||||
header_by_code = _header_by_code_for_case(case, fields)
|
||||
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
|
||||
target = _find_line(case, lines, line_key, actor_id=user_id, action=action)
|
||||
before = _line_routing_snapshot(target, fields, header_by_code)
|
||||
try:
|
||||
overlay = mark_keep_manual_inventory_decision(
|
||||
line_meta=target,
|
||||
reason=str(reason or 'keep_manual_inventory_decision'),
|
||||
)
|
||||
except ValueError as exc:
|
||||
_reject_draft_operation(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
action=action,
|
||||
error=ValidationError(
|
||||
'Manual inventory decision cannot be kept',
|
||||
code='SHIPPING.REVIEW_INVENTORY_ROUTING_KEEP_INVALID',
|
||||
details={'reason': str(exc)},
|
||||
),
|
||||
metadata={'line_key': str(line_key)[:64], 'reason': str(exc)},
|
||||
)
|
||||
case.current_draft.lines_json = lines
|
||||
after = _line_routing_snapshot(target, fields, header_by_code)
|
||||
_store_routing_recovery_idempotency(
|
||||
case,
|
||||
action=f'{action}:{line_key}',
|
||||
idempotency_key=str(idempotency_key or ''),
|
||||
line_keys=[str(line_key)],
|
||||
)
|
||||
return _record_change(
|
||||
case,
|
||||
actor_id=user_id,
|
||||
event_type=action,
|
||||
operation={
|
||||
'line_key': line_key,
|
||||
'idempotency_key': _normalize_routing_idempotency_key(idempotency_key) or None,
|
||||
'previous_value': before,
|
||||
'new_value': after,
|
||||
'candidate_inventory_source_codes': list(overlay.get('candidate_inventory_source_codes') or []),
|
||||
'action_semantics': 'keep_manual_inventory_decision',
|
||||
},
|
||||
validate=True,
|
||||
)
|
||||
|
||||
|
||||
def _set_llm_suggested_value(
|
||||
container: dict[str, Any],
|
||||
field: dict[str, Any],
|
||||
|
||||
@@ -630,6 +630,28 @@ def get_case_intake_parse_context(*, user_id: int, case_no: str) -> dict[str, An
|
||||
document_type='email_body',
|
||||
).one_or_none()
|
||||
)
|
||||
preview_html = ''
|
||||
preview_url = None
|
||||
if body is not None:
|
||||
from app.services.shipping_notice.eml_preview_service import (
|
||||
get_or_create_eml_preview_html,
|
||||
issue_eml_preview_grant,
|
||||
)
|
||||
|
||||
preview_html = get_or_create_eml_preview_html(document=body)
|
||||
if preview_html:
|
||||
preview_url = (
|
||||
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/email-preview'
|
||||
f'?preview_token={issue_eml_preview_grant(user_id=user_id, case_no=case.case_no, document_id=body.id, html=preview_html)}'
|
||||
)
|
||||
email_payload = None if body is None else {
|
||||
'document_id': int(body.id),
|
||||
'filename': str(body.filename or 'email.eml')[:255],
|
||||
'render_kind': 'safe_html' if preview_html else 'text',
|
||||
'text': str(body.extracted_text or '')[:20_000],
|
||||
}
|
||||
if preview_url:
|
||||
email_payload['preview_url'] = preview_url
|
||||
return {
|
||||
'case_no': case.case_no,
|
||||
'attachment': {
|
||||
@@ -638,16 +660,14 @@ def get_case_intake_parse_context(*, user_id: int, case_no: str) -> dict[str, An
|
||||
'mime_type': str(asset.mime_type or '') if asset else None,
|
||||
'preview_kind': 'pdf' if is_pdf else 'unsupported',
|
||||
},
|
||||
'email': None if body is None else {
|
||||
'document_id': int(body.id),
|
||||
'filename': str(body.filename or 'email.eml')[:255],
|
||||
'text': str(body.extracted_text or '')[:20_000],
|
||||
},
|
||||
'email': email_payload,
|
||||
}
|
||||
|
||||
|
||||
def get_case_email_evidence_text(*, user_id: int, case_no: str, document_id: int) -> dict[str, Any]:
|
||||
"""返回同一 Intake 邮件正文的已解析文本,禁止读取原始 EML、附件或存储地址。"""
|
||||
def get_case_email_evidence_text(
|
||||
*, user_id: int, case_no: str, document_id: int, evidence_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""返回同 Intake 邮件证据的安全预览;仅唯一引文可获得 HTML 范围高亮。"""
|
||||
case = get_user_review_case(user_id=user_id, case_no=case_no)
|
||||
case_document = db.session.get(ShippingOrderDocument, int(case.document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
@@ -658,9 +678,34 @@ def get_case_email_evidence_text(*, user_id: int, case_no: str, document_id: int
|
||||
or str(document.document_type or '') != 'email_body'
|
||||
):
|
||||
raise NotFoundError('Email evidence preview is unavailable', code='SHIPPING.REVIEW_EVIDENCE_PREVIEW_NOT_FOUND')
|
||||
return {
|
||||
payload = {
|
||||
'document_id': int(document.id),
|
||||
'document_type': 'email_body',
|
||||
'filename': str(document.filename or 'email.eml')[:255],
|
||||
'text': str(document.extracted_text or '')[:20_000],
|
||||
}
|
||||
from app.services.shipping_notice.eml_preview_service import (
|
||||
get_or_create_eml_preview_html,
|
||||
highlight_eml_preview_html,
|
||||
issue_eml_preview_grant,
|
||||
)
|
||||
|
||||
html = get_or_create_eml_preview_html(document=document)
|
||||
if not html:
|
||||
payload['render_kind'] = 'text'
|
||||
return payload
|
||||
quote = None
|
||||
if evidence_id:
|
||||
evidence = get_case_evidence(user_id=user_id, case_no=case_no, evidence_id=evidence_id)
|
||||
if int(evidence.get('document_id') or 0) == int(document.id):
|
||||
quote = evidence.get('quote')
|
||||
highlighted = highlight_eml_preview_html(html, quote)
|
||||
payload.update({
|
||||
'render_kind': 'safe_html',
|
||||
'preview_url': (
|
||||
f'/api/workspace/shipping-notice/order-review-cases/{case.case_no}/email-preview'
|
||||
f'?preview_token={issue_eml_preview_grant(user_id=user_id, case_no=case.case_no, document_id=document.id, html=highlighted)}'
|
||||
),
|
||||
'highlighted': highlighted != html,
|
||||
})
|
||||
return payload
|
||||
@@ -39,6 +39,7 @@ from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts
|
||||
)
|
||||
|
||||
_VC_CONFLICT_PREFIX = 'vc:'
|
||||
_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'})
|
||||
|
||||
|
||||
def _conflict_key(*, field: str, line_index: Any) -> str:
|
||||
@@ -202,6 +203,26 @@ def _field_id_for_code(case: ShippingOrderReviewCase, field_code: str, *, scope:
|
||||
return None
|
||||
|
||||
|
||||
def _finding_scope(case: ShippingOrderReviewCase, *, field_code: str, line_index: int) -> str:
|
||||
"""推断遗留 Finding 的作用域;缺行号的明细字段必须显式标记为未定位。"""
|
||||
if line_index >= 0:
|
||||
return 'line'
|
||||
run = getattr(case, 'run', None)
|
||||
snapshot = getattr(run, 'input_snapshot_json', None) if run is not None else None
|
||||
schema = snapshot.get('schema') if isinstance(snapshot, dict) and isinstance(snapshot.get('schema'), dict) else {}
|
||||
definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else {}
|
||||
scopes = {
|
||||
str(raw.get('scope') or '')
|
||||
for raw in (definition.get('fields') or [])
|
||||
if isinstance(raw, dict) and str(raw.get('field_code') or '') == str(field_code or '')
|
||||
}
|
||||
if 'header' in scopes:
|
||||
return 'header'
|
||||
if scopes == {'line'}:
|
||||
return 'line_unassigned'
|
||||
return 'unscoped'
|
||||
|
||||
|
||||
def _project_vc_candidate_conflicts(
|
||||
*,
|
||||
case: ShippingOrderReviewCase,
|
||||
@@ -287,21 +308,20 @@ def _project_vc_candidate_conflicts(
|
||||
return items
|
||||
|
||||
|
||||
def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
|
||||
def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""
|
||||
投影建单前仍未裁决的字段冲突,供复核工作台集中展示。
|
||||
|
||||
合并两类冲突:
|
||||
1. 传统 Observation/Adjudication 字段冲突(来自 candidate.conflicts_json);
|
||||
2. Vendor Comments 三来源冲突(collect_vc_candidate_conflicts 动态产出,vc_kind=True)。
|
||||
将 Candidate 的值冲突与证据缺失分区投影,并按稳定 Finding 身份去重。
|
||||
|
||||
Returns:
|
||||
冲突列表;每项含 conflict_key、field_code、line_index、options、reason。
|
||||
(value_conflicts, evidence_issues)。证据缺失不是多来源值冲突,必须独立展示,
|
||||
以免用户在已有 Draft 值时被错误要求再次填写。
|
||||
"""
|
||||
candidate = _candidate_for_case(case)
|
||||
if candidate is None:
|
||||
return []
|
||||
projected: list[dict[str, Any]] = []
|
||||
return [], []
|
||||
value_conflicts: list[dict[str, Any]] = []
|
||||
evidence_issues: list[dict[str, Any]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
raw_conflicts = list(candidate.conflicts_json or [])
|
||||
adjudication = _adjudication_blob(candidate)
|
||||
observations = _observations_index(adjudication)
|
||||
@@ -320,9 +340,9 @@ def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[d
|
||||
line_index = -1
|
||||
value_keys = [str(v) for v in (item.get('values') or []) if v not in (None, '')]
|
||||
reason = str(item.get('reason') or 'field_conflict')
|
||||
# 证据缺失/单值冲突没有可供二选一的 values,但仍会阻断自动建单。
|
||||
# 必须投影给工作台,避免资格摘要与字段裁决区同时丢失定位事实。
|
||||
if len(value_keys) < 2 and reason not in {'evidence_missing', 'pdf_evidence_missing'}:
|
||||
is_evidence_gap = reason in _EVIDENCE_GAP_REASONS
|
||||
# 只有多个候选值不一致才属于「字段冲突待裁决」。
|
||||
if len(value_keys) < 2 and not is_evidence_gap:
|
||||
continue
|
||||
observation_ids = [str(oid) for oid in (item.get('observation_ids') or []) if oid]
|
||||
options = [
|
||||
@@ -335,18 +355,37 @@ def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[d
|
||||
for key in value_keys
|
||||
]
|
||||
line_key = _line_key_for_index(case, line_index) if line_index >= 0 else None
|
||||
projected.append({
|
||||
finding = {
|
||||
'conflict_key': _conflict_key(field=field, line_index=line_index),
|
||||
'field_code': field,
|
||||
'line_index': line_index if line_index >= 0 else None,
|
||||
'line_key': line_key,
|
||||
'scope': _finding_scope(case, field_code=field, line_index=line_index),
|
||||
'severity': str(item.get('severity') or 'blocking'),
|
||||
'reason': reason,
|
||||
'options': options,
|
||||
'observation_ids': observation_ids,
|
||||
})
|
||||
projected.extend(_project_vc_candidate_conflicts(case=case, candidate=candidate))
|
||||
return projected
|
||||
}
|
||||
# 同一 scope/field/reason 只能有一个开放 Finding;重复来源合并为一张卡。
|
||||
finding_identity = (finding['conflict_key'], reason)
|
||||
if finding_identity in seen:
|
||||
continue
|
||||
seen.add(finding_identity)
|
||||
(evidence_issues if is_evidence_gap else value_conflicts).append(finding)
|
||||
value_conflicts.extend(_project_vc_candidate_conflicts(case=case, candidate=candidate))
|
||||
return value_conflicts, evidence_issues
|
||||
|
||||
|
||||
def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
|
||||
"""投影仅需人工选择候选值的字段冲突;不混入证据缺失门禁。"""
|
||||
value_conflicts, _ = _project_review_case_candidate_findings(case)
|
||||
return value_conflicts
|
||||
|
||||
|
||||
def project_review_case_evidence_issues(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
|
||||
"""投影关键字段证据缺失;只读提示并定位证据,不伪装为值裁决。"""
|
||||
_, evidence_issues = _project_review_case_candidate_findings(case)
|
||||
return evidence_issues
|
||||
|
||||
|
||||
def _resolve_vc_candidate_decision(
|
||||
@@ -570,7 +609,14 @@ def resolve_review_case_field_conflict(
|
||||
code='SHIPPING.INVALID_CONFLICT_RESOLUTION',
|
||||
details={'resolution': resolution},
|
||||
)
|
||||
conflicts.pop(target_idx)
|
||||
# 解析历史可能保留同一稳定键的重复记录;一次人工裁决必须原子清空该 Finding 身份。
|
||||
conflicts = [
|
||||
item for item in conflicts
|
||||
if not (
|
||||
isinstance(item, dict)
|
||||
and _conflict_key(field=item.get('field'), line_index=item.get('line_index')) == raw_key
|
||||
)
|
||||
]
|
||||
candidate.conflicts_json = conflicts
|
||||
structured = dict(candidate.structured_result_json or {})
|
||||
extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {}
|
||||
|
||||
+436
-10
@@ -20,10 +20,14 @@ from typing import Any
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryFile,
|
||||
ShippingInventorySource,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLineDecision,
|
||||
ShippingOrderReviewWaveLine,
|
||||
ShippingNotice,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
)
|
||||
from app.services.shipping_notice.workflow_ledger_service import (
|
||||
assert_case_is_current_workflow_version,
|
||||
@@ -42,6 +46,7 @@ DECISION_CLOSE = 'close_unfulfillable'
|
||||
DECISION_REOPEN = 'reopen'
|
||||
DECISION_USE_NEW_FILE = 'use_new_inventory_file'
|
||||
DECISION_CHANGE_SOURCE = 'change_inventory_source'
|
||||
DECISION_RELEASE_SHORTAGE = 'release_inventory_shortage'
|
||||
|
||||
ALLOWED_DECISIONS = frozenset({
|
||||
DECISION_WAIT,
|
||||
@@ -50,6 +55,7 @@ ALLOWED_DECISIONS = frozenset({
|
||||
DECISION_REOPEN,
|
||||
DECISION_USE_NEW_FILE,
|
||||
DECISION_CHANGE_SOURCE,
|
||||
DECISION_RELEASE_SHORTAGE,
|
||||
})
|
||||
|
||||
_STATUS_BY_DECISION = {
|
||||
@@ -59,9 +65,10 @@ _STATUS_BY_DECISION = {
|
||||
DECISION_REOPEN: 'reopened',
|
||||
DECISION_USE_NEW_FILE: 'waiting_inventory',
|
||||
DECISION_CHANGE_SOURCE: 'pending_decision',
|
||||
DECISION_RELEASE_SHORTAGE: 'released_shortage',
|
||||
}
|
||||
|
||||
_TERMINAL_ACTIVE = frozenset({'task_created', 'fulfilled', 'closed_unfulfillable'})
|
||||
_TERMINAL_ACTIVE = frozenset({'task_created', 'fulfilled', 'closed_unfulfillable', 'released_shortage'})
|
||||
|
||||
|
||||
def _load_writable_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
|
||||
@@ -103,6 +110,339 @@ def _parse_qty(value: Any) -> Decimal | None:
|
||||
return qty
|
||||
|
||||
|
||||
def _manual_release_fields_from_inventory_candidates(
|
||||
*,
|
||||
mappings: list[dict[str, Any]],
|
||||
candidates: list[dict[str, Any]],
|
||||
field_labels: dict[str, str],
|
||||
) -> list[dict[str, str]]:
|
||||
"""返回短缺放行时无法从当前库存快照唯一确定的行级模板字段。"""
|
||||
required: list[dict[str, str]] = []
|
||||
seen: set[str] = set()
|
||||
for mapping in mappings:
|
||||
if not isinstance(mapping, dict) or mapping.get('row_mode') != 'line':
|
||||
continue
|
||||
if mapping.get('source_kind') != 'inventory_field':
|
||||
continue
|
||||
field_id = str(mapping.get('source_key') or '').strip()
|
||||
if not field_id or field_id in seen:
|
||||
continue
|
||||
seen.add(field_id)
|
||||
values = {
|
||||
str(row.get(field_id) or '').strip()
|
||||
for row in candidates if str(row.get(field_id) or '').strip()
|
||||
}
|
||||
if len(values) != 1:
|
||||
required.append({
|
||||
'field_id': field_id,
|
||||
'display_name': field_labels.get(field_id) or f'库存字段(编号 {field_id})',
|
||||
})
|
||||
return required
|
||||
|
||||
|
||||
def _release_template_inventory_fields(
|
||||
*,
|
||||
mappings: list[dict[str, Any]],
|
||||
candidates: list[dict[str, Any]],
|
||||
field_labels: dict[str, str],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""解析发货模板实际消费的库存字段:唯一快照值只读,其余必须人工补录。"""
|
||||
fields: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
for mapping in mappings:
|
||||
if not isinstance(mapping, dict) or mapping.get('row_mode') not in {'header', 'line'}:
|
||||
continue
|
||||
if mapping.get('source_kind') != 'inventory_field':
|
||||
continue
|
||||
field_id = str(mapping.get('source_key') or '').strip()
|
||||
if not field_id or field_id in seen:
|
||||
continue
|
||||
seen.add(field_id)
|
||||
values = {
|
||||
str(row.get(field_id) or '').strip()
|
||||
for row in candidates if str(row.get(field_id) or '').strip()
|
||||
}
|
||||
value = next(iter(values)) if len(values) == 1 else None
|
||||
fields.append({
|
||||
'field_id': field_id,
|
||||
'display_name': field_labels.get(field_id) or f'库存字段(编号 {field_id})',
|
||||
'value': value,
|
||||
'value_source': 'inventory_snapshot' if value is not None else 'manual_required',
|
||||
'requires_manual': value is None,
|
||||
})
|
||||
return fields
|
||||
|
||||
|
||||
def _release_template_system_fields(
|
||||
*,
|
||||
mappings: list[dict[str, Any]],
|
||||
warehouse_id: Any,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""投影模板实际消费但当前任务缺失的受控系统事实,禁止放行后再以空值导出。"""
|
||||
has_warehouse_mapping = any(
|
||||
isinstance(mapping, dict)
|
||||
and mapping.get('row_mode') in {'header', 'line'}
|
||||
and mapping.get('source_kind') == 'system_fact'
|
||||
and str(mapping.get('source_key') or '').strip() == 'warehouse_id'
|
||||
for mapping in mappings
|
||||
)
|
||||
value = str(warehouse_id or '').strip().upper() or None
|
||||
if not has_warehouse_mapping:
|
||||
return []
|
||||
return [{
|
||||
'field_id': 'system_fact:warehouse_id',
|
||||
'display_name': 'Warehouse ID',
|
||||
'value': value,
|
||||
'value_source': 'task_fact' if value is not None else 'manual_required',
|
||||
'requires_manual': value is None,
|
||||
}]
|
||||
|
||||
|
||||
def _validate_inventory_shortage_release_fields(
|
||||
*,
|
||||
required_fields: list[dict[str, str]],
|
||||
supplied_values: dict[str, Any],
|
||||
) -> dict[str, str]:
|
||||
"""校验短缺放行的模板库存字段人工补录,返回仅含受控字段的值。"""
|
||||
normalized = {
|
||||
str(key).strip(): str(value).strip()
|
||||
for key, value in (supplied_values or {}).items()
|
||||
if str(key).strip() and value is not None and str(value).strip()
|
||||
}
|
||||
missing = [
|
||||
field for field in required_fields
|
||||
if not normalized.get(str(field.get('field_id') or '').strip())
|
||||
]
|
||||
if missing:
|
||||
raise ConflictError(
|
||||
'Template inventory fields are required before shortage release',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_FIELDS_REQUIRED',
|
||||
details={'required_fields': missing},
|
||||
)
|
||||
allowed = {str(field.get('field_id') or '').strip() for field in required_fields}
|
||||
return {key: value for key, value in normalized.items() if key in allowed}
|
||||
|
||||
|
||||
def _release_fact_identity(fact: dict[str, Any] | None) -> tuple[int | None, int | None, str | None]:
|
||||
"""从行库存事实投影(dict)提取放行模板判定所需的快照身份。"""
|
||||
current = fact if isinstance(fact, dict) else {}
|
||||
return (
|
||||
current.get('line_index'),
|
||||
current.get('inventory_snapshot_id'),
|
||||
current.get('inventory_source_code'),
|
||||
)
|
||||
|
||||
|
||||
def _resolve_shortage_release_inventory_source(
|
||||
*,
|
||||
fact_source_code: Any,
|
||||
task_source_code: Any,
|
||||
snapshot_source_code: Any,
|
||||
) -> str | None:
|
||||
"""按行事实、OT、快照顺序恢复短缺放行所需的库存源。"""
|
||||
for value in (fact_source_code, task_source_code, snapshot_source_code):
|
||||
normalized = str(value or '').strip().upper()
|
||||
if normalized:
|
||||
return normalized
|
||||
return None
|
||||
|
||||
|
||||
def _is_shortage_match_fact(fact: Any) -> bool:
|
||||
"""判定当前 OT 行匹配事实是否库存不足,不能使用草稿期的预测投影。"""
|
||||
if fact is None:
|
||||
return False
|
||||
|
||||
def _value(name: str) -> Any:
|
||||
return fact.get(name) if isinstance(fact, dict) else getattr(fact, name, None)
|
||||
|
||||
if str(_value('match_result') or '').strip() == 'not_found':
|
||||
return True
|
||||
shortage = _parse_qty(_value('shortage_qty'))
|
||||
if shortage is not None:
|
||||
return True
|
||||
if str(_value('inventory_status') or '').strip() != 'ready':
|
||||
return False
|
||||
try:
|
||||
required = Decimal(str(_value('required_qty')).strip())
|
||||
available = Decimal(str(_value('available_qty')).strip())
|
||||
except (InvalidOperation, ValueError, AttributeError):
|
||||
return False
|
||||
return required > 0 and available >= 0 and available < required
|
||||
|
||||
|
||||
def _has_terminal_inventory_rpa_failure(
|
||||
task: ShippingNotice,
|
||||
*,
|
||||
attempts: list[ShippingTaskInventoryRpaAttempt] | None = None,
|
||||
) -> bool:
|
||||
"""仅在已投递的库存 RPA 全部终态失败且无活动 Attempt 时允许无快照人工放行。"""
|
||||
task_no = str(getattr(task, 'task_no', '') or '').strip()
|
||||
if not task_no:
|
||||
return False
|
||||
source_codes: set[str] = set()
|
||||
try:
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
source_codes = {str(item or '').strip().upper() for item in task_frozen_inventory_source_codes(task)}
|
||||
except Exception: # noqa: BLE001 - 放行资格宁可拒绝,不能因冻结读取异常绕过。
|
||||
source_codes = set()
|
||||
source_code = str(getattr(task, 'inventory_source_code', '') or '').strip().upper()
|
||||
if source_code:
|
||||
source_codes.add(source_code)
|
||||
rows = attempts if attempts is not None else (
|
||||
ShippingTaskInventoryRpaAttempt.query
|
||||
.filter_by(task_no=task_no)
|
||||
.order_by(ShippingTaskInventoryRpaAttempt.attempt_no.desc(), ShippingTaskInventoryRpaAttempt.id.desc())
|
||||
.all()
|
||||
)
|
||||
relevant = [row for row in rows if not source_codes or str(getattr(row, 'source_code', '') or '').strip().upper() in source_codes]
|
||||
if not relevant or any(str(getattr(row, 'status', '') or '').lower() in {'queued', 'running'} for row in relevant):
|
||||
return False
|
||||
latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {}
|
||||
for row in relevant:
|
||||
code = str(getattr(row, 'source_code', '') or '').strip().upper()
|
||||
if code and code not in latest_by_source:
|
||||
latest_by_source[code] = row
|
||||
if source_codes and set(latest_by_source) != source_codes:
|
||||
return False
|
||||
return bool(latest_by_source) and all(
|
||||
str(getattr(row, 'status', '') or '').lower() in {'failed', 'exhausted'}
|
||||
and bool(str(getattr(row, 'trigger_file_path', '') or '').strip())
|
||||
and str(getattr(row, 'execution_phase', '') or '').strip() in {'trigger_written', 'worker_claimed'}
|
||||
for row in latest_by_source.values()
|
||||
)
|
||||
|
||||
|
||||
def _shortage_release_required_fields(
|
||||
*,
|
||||
task: ShippingNotice,
|
||||
line_index: int | None,
|
||||
inventory_snapshot_id: int | None,
|
||||
inventory_source_code: str | None,
|
||||
) -> list[dict[str, str]]:
|
||||
"""按该行快照、库存源解析方案和发货模板计算短缺放行补录字段。"""
|
||||
if line_index is None:
|
||||
raise ConflictError(
|
||||
'Current line inventory evidence is unavailable',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
snapshot = db.session.get(ShippingInventoryFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None
|
||||
if inventory_snapshot_id is not None and (snapshot is None or not isinstance(snapshot.inventory_lines_json, list)):
|
||||
raise ConflictError(
|
||||
'Current inventory snapshot is unavailable',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
resolved_source_code = _resolve_shortage_release_inventory_source(
|
||||
fact_source_code=inventory_source_code,
|
||||
task_source_code=getattr(task, 'inventory_source_code', None),
|
||||
snapshot_source_code=getattr(snapshot, 'source_code', None) if snapshot is not None else None,
|
||||
)
|
||||
if not resolved_source_code:
|
||||
raise ConflictError(
|
||||
'Current line inventory evidence is unavailable',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
source = ShippingInventorySource.query.filter_by(
|
||||
source_code=resolved_source_code, enabled=True,
|
||||
).first()
|
||||
template = getattr(source, 'excel_template', None) if source is not None else None
|
||||
profile = getattr(source, 'parsing_profile', None) if source is not None else None
|
||||
if template is None or profile is None:
|
||||
raise ConflictError(
|
||||
'Inventory source export template is unavailable',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_TEMPLATE_UNAVAILABLE',
|
||||
)
|
||||
from app.services.shipping_notice.export import _match_text, order_field_id_values
|
||||
|
||||
_header, order_lines = order_field_id_values(task)
|
||||
if line_index < 0 or line_index >= len(order_lines):
|
||||
raise ConflictError('Order line is unavailable', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
|
||||
mappings = list((template.definition_json or {}).get('mappings') or [])
|
||||
if snapshot is None:
|
||||
# 没有快照时不能伪造库存候选:模板消费的全部库存字段均由用户补录。
|
||||
field_ids = {
|
||||
int(str(item.get('source_key') or '').strip())
|
||||
for item in mappings if isinstance(item, dict)
|
||||
and item.get('source_kind') == 'inventory_field'
|
||||
and str(item.get('source_key') or '').strip().isdigit()
|
||||
}
|
||||
labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {}
|
||||
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels) + _release_template_system_fields(mappings=mappings, warehouse_id=getattr(task, 'inventory_warehouse_id', None))
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else []
|
||||
expected = [
|
||||
(str(item.get('inventory_field_id') or '').strip(), _match_text(order_lines[line_index].get(str(item.get('order_field_id') or ''))))
|
||||
for item in match_keys if isinstance(item, dict)
|
||||
]
|
||||
if not expected or any(not inventory_field or not value for inventory_field, value in expected):
|
||||
raise ConflictError(
|
||||
'Inventory matching keys are unavailable',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
|
||||
)
|
||||
candidates = [
|
||||
dict(row) for row in snapshot.inventory_lines_json if isinstance(row, dict)
|
||||
and all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
|
||||
]
|
||||
field_ids = {
|
||||
int(str(item.get('source_key') or '').strip())
|
||||
for item in mappings
|
||||
if isinstance(item, dict)
|
||||
and item.get('row_mode') in {'header', 'line'}
|
||||
and item.get('source_kind') == 'inventory_field'
|
||||
and str(item.get('source_key') or '').strip().isdigit()
|
||||
}
|
||||
labels = {
|
||||
str(row.id): str(row.display_name or '').strip()
|
||||
for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()
|
||||
} if field_ids else {}
|
||||
return _release_template_inventory_fields(
|
||||
mappings=mappings,
|
||||
candidates=candidates,
|
||||
field_labels=labels,
|
||||
) + _release_template_system_fields(
|
||||
mappings=mappings,
|
||||
warehouse_id=getattr(task, 'inventory_warehouse_id', None),
|
||||
)
|
||||
|
||||
|
||||
def _manual_required_release_fields(fields: list[dict[str, Any]]) -> list[dict[str, str]]:
|
||||
"""从模板字段投影筛出确实不能由受控库存快照唯一确定的人工项。"""
|
||||
return [
|
||||
{
|
||||
'field_id': str(field.get('field_id') or ''),
|
||||
'display_name': str(field.get('display_name') or ''),
|
||||
}
|
||||
for field in fields
|
||||
if bool(field.get('requires_manual'))
|
||||
]
|
||||
|
||||
|
||||
def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, actor_id: int) -> None:
|
||||
"""短缺放行后重投影并提交正式任务当前技术 Gate,不改写库存事实。"""
|
||||
task_id = getattr(case, 'confirmed_task_id', None)
|
||||
if task_id is None:
|
||||
return
|
||||
task = db.session.get(ShippingNotice, int(task_id))
|
||||
execution_id = getattr(task, 'active_process_execution_id', None) if task is not None else None
|
||||
if execution_id is None:
|
||||
return
|
||||
from app.models import ShippingProcessExecution
|
||||
execution = db.session.get(ShippingProcessExecution, int(execution_id))
|
||||
if execution is None or int(getattr(execution, 'task_id', 0) or 0) != int(task_id):
|
||||
return
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=actor_id)
|
||||
# 放行是库存充分性 Gate 的受控业务事实;重投影后由统一编排器重新读取当前
|
||||
# Gate 并仅入队一个技术动作,避免 API 事务中直接生成 Excel 或绕过 Worker。
|
||||
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
|
||||
|
||||
submit_auto_progress(
|
||||
task=task,
|
||||
trigger='inventory_shortage_released',
|
||||
operator_id=actor_id,
|
||||
commit=False,
|
||||
)
|
||||
|
||||
|
||||
def _line_reservation_id(draft_line: dict[str, Any], proj: dict[str, Any]) -> str | None:
|
||||
"""解析行有效 Reservation(履约表权威字段 reservation_id)。"""
|
||||
value = str(
|
||||
@@ -277,6 +617,7 @@ def _serialize_decision(row: ShippingOrderReviewLineDecision) -> dict[str, Any]:
|
||||
'line_status': row.line_status,
|
||||
'is_active': bool(row.is_active),
|
||||
'reason': row.reason,
|
||||
'release_field_values': dict(row.snapshot_json or {}).get('release_field_values') or {},
|
||||
'required_qty': row.required_qty,
|
||||
'available_qty': row.available_qty,
|
||||
'reservation_id': row.reservation_id,
|
||||
@@ -394,8 +735,11 @@ def project_review_case_line_decisions(
|
||||
formal_ot = resolve_formal_ot(case)
|
||||
has_formal_ot = bool(formal_ot.get('has_formal_ot'))
|
||||
task = formal_ot.get('task') if isinstance(formal_ot.get('task'), ShippingNotice) else None
|
||||
if task is None and getattr(case, 'confirmed_task_id', None) is not None:
|
||||
task = db.session.get(ShippingNotice, int(case.confirmed_task_id))
|
||||
rpa_failure_release_allowed = bool(task is not None and _has_terminal_inventory_rpa_failure(task))
|
||||
# [STEP] 构造 Task 级库存源回退事实(行级匹配缺失时兜底,仅影响展示)
|
||||
# 优先级:行级 inventory_source_code > Task resolved/user_confirmed 正式源 > candidates_frozen > resolving
|
||||
# 优先级:行级 inventory_source_code > Task resolved 正式源 > candidates_frozen > resolving
|
||||
from app.services.shipping_notice.stp_inventory_freeze import (
|
||||
task_frozen_inventory_source_codes,
|
||||
)
|
||||
@@ -404,7 +748,7 @@ def project_review_case_line_decisions(
|
||||
if task is not None:
|
||||
task_source_code = str(task.inventory_source_code or '').strip().upper() or None
|
||||
task_source_status = str(task.inventory_source_status or '').strip()
|
||||
if task_source_code and task_source_status in {'resolved', 'user_confirmed'}:
|
||||
if task_source_code and task_source_status == 'resolved':
|
||||
fallback_inventory_source = {
|
||||
'code': task_source_code,
|
||||
'label': None,
|
||||
@@ -510,6 +854,28 @@ def project_review_case_line_decisions(
|
||||
source_labels=labels,
|
||||
fallback_inventory_source=fallback_inventory_source,
|
||||
)
|
||||
release_template_fields: list[dict[str, Any]] = []
|
||||
release_field_resolution_error: str | None = None
|
||||
if (
|
||||
task is not None
|
||||
and (bool(inv_view.get('is_shortage')) or rpa_failure_release_allowed)
|
||||
and getattr(decision, 'decision_code', None) != DECISION_RELEASE_SHORTAGE
|
||||
):
|
||||
try:
|
||||
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
|
||||
if release_line_index is None:
|
||||
release_line_index = draft_line.get('_line_index')
|
||||
if not release_source_code:
|
||||
release_source_code = getattr(task, 'inventory_source_code', None)
|
||||
release_template_fields = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=release_line_index,
|
||||
inventory_snapshot_id=release_snapshot_id,
|
||||
inventory_source_code=release_source_code,
|
||||
)
|
||||
except ConflictError as exc:
|
||||
# [STEP] 字段无法受控解析时禁止呈现放行动作,不能降级为“只填原因”。
|
||||
release_field_resolution_error = exc.code
|
||||
# [STEP] OT 后数量以匹配事实投影覆盖(含 not_found→0 / result_missing→null)
|
||||
if has_formal_ot:
|
||||
available = inv_view.get('available_qty')
|
||||
@@ -547,17 +913,30 @@ def project_review_case_line_decisions(
|
||||
'decision_source': inv_view.get('decision_source'),
|
||||
'retryable': bool(inv_view.get('retryable')),
|
||||
'inventory_allowed_actions': list(inv_view.get('inventory_allowed_actions') or []),
|
||||
'line_allowed_actions': list(inv_view.get('line_allowed_actions') or []),
|
||||
'allowed_actions': list(inv_view.get('allowed_actions') or []),
|
||||
'line_allowed_actions': list(inv_view.get('line_allowed_actions') or []) + (
|
||||
[DECISION_RELEASE_SHORTAGE]
|
||||
if rpa_failure_release_allowed
|
||||
and DECISION_RELEASE_SHORTAGE not in (inv_view.get('line_allowed_actions') or [])
|
||||
and status not in _TERMINAL_ACTIVE else []
|
||||
),
|
||||
'allowed_actions': list(inv_view.get('allowed_actions') or []) + (
|
||||
[DECISION_RELEASE_SHORTAGE]
|
||||
if rpa_failure_release_allowed
|
||||
and DECISION_RELEASE_SHORTAGE not in (inv_view.get('allowed_actions') or [])
|
||||
and status not in _TERMINAL_ACTIVE else []
|
||||
),
|
||||
'auto_fulfill_error_message': inv_view.get('auto_fulfill_error_message'),
|
||||
'auto_fulfill_failed': bool(auto_failed),
|
||||
'release_template_fields': release_template_fields,
|
||||
'release_required_fields': _manual_required_release_fields(release_template_fields),
|
||||
'release_field_resolution_error': release_field_resolution_error,
|
||||
'decision': _serialize_decision(decision) if decision is not None else None,
|
||||
'block_reason': proj.get('block_reason'),
|
||||
})
|
||||
|
||||
open_lines = [
|
||||
item for item in lines_out
|
||||
if item.get('line_status') not in {'task_created', 'fulfilled', 'closed_unfulfillable'}
|
||||
if item.get('line_status') not in {'task_created', 'fulfilled', 'closed_unfulfillable', 'released_shortage'}
|
||||
]
|
||||
ready = [
|
||||
item for item in lines_out
|
||||
@@ -647,6 +1026,7 @@ def decide_review_line_fulfillment(
|
||||
line_key: str,
|
||||
decision_code: str,
|
||||
reason: str | None = None,
|
||||
release_field_values: dict[str, Any] | None = None,
|
||||
expected_draft_version: Any = None,
|
||||
actor_is_admin: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
@@ -654,14 +1034,16 @@ def decide_review_line_fulfillment(
|
||||
写入一行履约决定(版本化)。
|
||||
|
||||
核心逻辑:停用旧活动决定;task_created/fulfilled 不可逆;
|
||||
reopen 仅 closed_unfulfillable 且管理员;fulfill 强制最新库存充足。
|
||||
reopen 仅 closed_unfulfillable 且管理员;fulfill 强制最新库存充足;
|
||||
release_inventory_shortage 必须留下原因、模板库存补录字段且仅能用于当前库存不足行。
|
||||
|
||||
Args:
|
||||
user_id: 操作人。
|
||||
case_no: Case 编号。
|
||||
line_key: 草稿行键。
|
||||
decision_code: 决定码。
|
||||
reason: 关闭/重开必填原因。
|
||||
reason: 关闭/重开/短缺放行必填原因。
|
||||
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
|
||||
expected_draft_version: 可选草稿乐观锁。
|
||||
actor_is_admin: 是否管理员(重开授权)。
|
||||
|
||||
@@ -675,7 +1057,7 @@ def decide_review_line_fulfillment(
|
||||
code='SHIPPING.REVIEW_LINE_DECISION_INVALID',
|
||||
details={'decision_code': code},
|
||||
)
|
||||
if code in {DECISION_CLOSE, DECISION_REOPEN} and not str(reason or '').strip():
|
||||
if code in {DECISION_CLOSE, DECISION_REOPEN, DECISION_RELEASE_SHORTAGE} and not str(reason or '').strip():
|
||||
raise ValidationError(
|
||||
'Reason is required',
|
||||
code='SHIPPING.REVIEW_LINE_DECISION_REASON_REQUIRED',
|
||||
@@ -740,6 +1122,44 @@ def decide_review_line_fulfillment(
|
||||
proj=proj,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
if code == DECISION_RELEASE_SHORTAGE:
|
||||
from app.models import ShippingNoticeLineInventoryMatch
|
||||
|
||||
task_id = getattr(case, 'confirmed_task_id', None)
|
||||
task = db.session.get(ShippingNotice, int(task_id)) if task_id is not None else None
|
||||
fact = (
|
||||
ShippingNoticeLineInventoryMatch.query
|
||||
.filter_by(task_id=int(task.id), line_key=key, is_current=True)
|
||||
.first()
|
||||
if task is not None else None
|
||||
)
|
||||
rpa_failure_release_allowed = bool(task is not None and _has_terminal_inventory_rpa_failure(task))
|
||||
if not _is_shortage_match_fact(fact) and not rpa_failure_release_allowed:
|
||||
raise ConflictError(
|
||||
'Only shortage lines can be released',
|
||||
code='SHIPPING.REVIEW_LINE_RELEASE_NOT_ALLOWED',
|
||||
details={'line_key': key},
|
||||
)
|
||||
release_line_index = getattr(fact, 'line_index', None) if fact is not None else draft_line.get('_line_index')
|
||||
release_template_fields = _shortage_release_required_fields(
|
||||
task=task,
|
||||
line_index=release_line_index,
|
||||
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
|
||||
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else getattr(task, 'inventory_source_code', None),
|
||||
) if task is not None else []
|
||||
release_required_fields = _manual_required_release_fields(release_template_fields)
|
||||
release_values = _validate_inventory_shortage_release_fields(
|
||||
required_fields=release_required_fields,
|
||||
supplied_values=release_field_values or {},
|
||||
)
|
||||
supplied_warehouse_id = str(release_values.get('system_fact:warehouse_id') or '').strip().upper()
|
||||
if supplied_warehouse_id:
|
||||
# Header Warehouse ID 是动态库存源导出的任务级系统事实;人工放行时必须
|
||||
# 显式固化,供后续 Excel 生成消费,并同时保留在决定快照中审计。
|
||||
task.inventory_warehouse_id = supplied_warehouse_id
|
||||
else:
|
||||
release_required_fields = []
|
||||
release_values = {}
|
||||
|
||||
# [STEP 1] 停用旧活动决定
|
||||
if current is not None:
|
||||
@@ -774,11 +1194,17 @@ def decide_review_line_fulfillment(
|
||||
'required_qty': str(req_qty) if req_qty is not None else None,
|
||||
'available_qty': str(avail_qty) if avail_qty is not None else None,
|
||||
'line_key': key,
|
||||
'release_field_values': release_values,
|
||||
'release_required_fields': release_required_fields,
|
||||
},
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(row)
|
||||
# [STEP 2] 审计 after 投影依赖数据库分配的主键,必须先 flush。
|
||||
db.session.flush()
|
||||
if code == DECISION_RELEASE_SHORTAGE:
|
||||
_sync_confirmed_task_fulfillment_gates(case=case, actor_id=int(user_id))
|
||||
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
@@ -796,12 +1222,12 @@ def decide_review_line_fulfillment(
|
||||
'decision_code': code,
|
||||
'decision_version': int(row.decision_version),
|
||||
'line_status': status,
|
||||
'release_field_count': len(release_values),
|
||||
},
|
||||
before=_serialize_decision(current) if current is not None else None,
|
||||
after=_serialize_decision(row),
|
||||
source='order_review_fulfillment_decision',
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
from app.services.shipping_notice.order_review_resume_service import (
|
||||
attach_resume_outcome,
|
||||
|
||||
Loaded 100 of 466 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user