!11 feat(shipping-notice): 实现滚动履约功能,优化发货通知流程与代码清理
Merge pull request !11 from 曹惠鹏/hugo-shipping-notice
This commit is contained in:
402 files changed
+23045
-20484
No files matched your search
+3
-3
@@ -185,9 +185,9 @@ FAQ_HOT_BAD_SCORE=2 # 选代表答案时「差评」反馈
|
||||
# 货代客户自动确认默认关闭;仅 approved + auto_match_allowed 强规则唯一命中时可开启。
|
||||
SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED=true
|
||||
# OT 后行级自动履约(默认关):关闭时只上线匹配事实契约/明细库存列;禁止自动决定与 wave。
|
||||
SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=false
|
||||
SHIPPING_NOTICE_LINE_AUTO_FULFILL_ENABLED=true
|
||||
# 发货通知专用 Worker 进程数;版面解析为长任务,默认并发处理同批两份文档。
|
||||
SHIPPING_NOTICE_WORKER_CONCURRENCY=2
|
||||
SHIPPING_NOTICE_WORKER_CONCURRENCY=10
|
||||
# Layout Job 内整页 OCR 结果复用(PR-1);共享默认关,dev/test 环境文件覆盖为 true,prod 保持 false 灰度。
|
||||
SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=false
|
||||
# PDFium 字符预读复用与按需补图(PR-2);共享默认关,dev/test 开启,prod 灰度。
|
||||
@@ -212,7 +212,7 @@ SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE=dual
|
||||
SHIPPING_NOTICE_ORDER_LINES_READ_MODE=shadow
|
||||
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
|
||||
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
|
||||
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=
|
||||
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
|
||||
# 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300
|
||||
# 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。
|
||||
|
||||
@@ -28,7 +28,6 @@ import app.api.admin.shipping_field_assets # noqa: F401
|
||||
import app.api.admin.shipping_order_document_profiles # noqa: F401
|
||||
import app.api.admin.shipping_document_layouts # noqa: F401
|
||||
import app.api.admin.shipping_process_gate # noqa: F401
|
||||
import app.api.admin.shipping_legacy_stp_jobs # noqa: F401
|
||||
import app.api.admin.linked_services # noqa: F401
|
||||
import app.api.admin.procurement_contract # noqa: F401
|
||||
import app.api.admin.training_configs # noqa: F401
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_legacy_stp_jobs.py
|
||||
|
||||
用途:Phase 5-1 —— 管理后台「货代历史 STP Job(928/929)运维面板」只读 API。
|
||||
依赖:admin Blueprint、require_admin、legacy_stp_job_admin_service。
|
||||
逻辑:
|
||||
• GET /admin/shipping-notice/legacy-stp-jobs 分页列表(支持 q/case_no/error_code/created_from/created_to)
|
||||
• GET /admin/shipping-notice/legacy-stp-jobs/<job_id> 单条详情 + 回链 Review Case
|
||||
• 所有接口严格 require_admin;不允许写任何 DB。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.legacy_stp_job_admin_service import (
|
||||
get_admin_legacy_stp_job,
|
||||
list_admin_legacy_stp_jobs,
|
||||
)
|
||||
|
||||
|
||||
def _qint(name: str, default: int) -> int:
|
||||
raw = request.args.get(name)
|
||||
if raw in (None, ''):
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f'{name} must be an integer') from exc
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/legacy-stp-jobs', methods=['GET'])
|
||||
@require_admin
|
||||
def admin_list_legacy_stp_jobs():
|
||||
"""历史失败 STP Job(failed/dead)分页列表,供管理员做 928/929 回放前筛选。"""
|
||||
page = _qint('page', 1)
|
||||
page_size = _qint('page_size', 25)
|
||||
payload = list_admin_legacy_stp_jobs(
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
status=request.args.get('status'),
|
||||
job_type=request.args.get('job_type'),
|
||||
q=request.args.get('q'),
|
||||
case_no=request.args.get('case_no'),
|
||||
error_code=request.args.get('error_code'),
|
||||
blocking_reason=request.args.get('blocking_reason'),
|
||||
created_from=request.args.get('created_from'),
|
||||
created_to=request.args.get('created_to'),
|
||||
sort=request.args.get('sort') or '-created_at',
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/legacy-stp-jobs/<int:job_id>', methods=['GET'])
|
||||
@require_admin
|
||||
def admin_get_legacy_stp_job(job_id: int):
|
||||
"""单条历史失败 STP Job 详情 + 回链 Review Case + 回放建议(replay_plan)。"""
|
||||
payload = get_admin_legacy_stp_job(int(job_id))
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
@@ -32,6 +32,40 @@ def _query_int(name: str, default: int) -> int:
|
||||
raise ValidationError(f'{name} must be an integer') from exc
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/legacy-supplement-conflicts/reassess', methods=['POST'])
|
||||
@require_admin
|
||||
def reassess_shipping_legacy_supplement_conflicts():
|
||||
"""受控重评估历史正文补充冲突;全量操作必须显式确认,结果只返回脱敏统计。"""
|
||||
body = request.get_json(silent=True)
|
||||
if body is None:
|
||||
body = {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
include_all_raw = body.get('include_all', False)
|
||||
if not isinstance(include_all_raw, bool):
|
||||
raise ValidationError('include_all must be a boolean')
|
||||
include_all = include_all_raw
|
||||
if include_all and str(body.get('confirmation') or '') != 'REASSESS_LEGACY_SUPPLEMENT_CONFLICTS':
|
||||
raise ValidationError('confirmation is required for include_all')
|
||||
candidate_no = str(body.get('candidate_no') or '').strip() or None
|
||||
run_no = str(body.get('run_no') or '').strip() or None
|
||||
if not (candidate_no or run_no or include_all):
|
||||
raise ValidationError('candidate_no, run_no, or include_all is required')
|
||||
from app.services.shipping_notice.legacy_supplement_conflict_reassessment_service import (
|
||||
reassess_legacy_supplement_conflicts,
|
||||
)
|
||||
|
||||
result = reassess_legacy_supplement_conflicts(
|
||||
actor_id=int(g.current_user.id),
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
candidate_no=candidate_no,
|
||||
run_no=run_no,
|
||||
include_all=include_all,
|
||||
)
|
||||
db.session.commit()
|
||||
return ok(result, request_id=getattr(g, 'request_id', None))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-runs/health', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_extraction_health():
|
||||
|
||||
@@ -137,24 +137,21 @@ def _merge_user_attachments_from_terminal_event(
|
||||
def _build_chat_adapter_hints(
|
||||
*,
|
||||
shipping_task_id: str | None = None,
|
||||
shipping_batch_no: str | None = None,
|
||||
shipping_intake_nos: list[str] | None = None,
|
||||
) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示,
|
||||
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item or '').strip()})
|
||||
if not task_id and not batch_no and not intake_nos:
|
||||
if not task_id and not intake_nos:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
'intake_nos': intake_nos,
|
||||
'capability': 'order_extraction' if intake_nos else None,
|
||||
'contract_version': 'shipping-order-extraction-v1' if intake_nos else None,
|
||||
@@ -1574,7 +1571,6 @@ def chat_completions():
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
shipping_batch_no = str(data.get('batch_no') or '').strip()
|
||||
raw_shipping_intakes = data.get('shipping_intake_nos')
|
||||
if raw_shipping_intakes is not None and not isinstance(raw_shipping_intakes, list):
|
||||
raise ValidationError('shipping_intake_nos must be a list')
|
||||
@@ -1720,11 +1716,9 @@ def chat_completions():
|
||||
normalized_files=normalized_files,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
kb_type=kb_type,
|
||||
)
|
||||
|
||||
@@ -1763,7 +1757,6 @@ def chat_completions():
|
||||
user_role=user_proxy.role,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -39,7 +39,6 @@ def chat_completions():
|
||||
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
shipping_batch_no = str(data.get('batch_no') or '').strip()
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
files = data.get('files')
|
||||
request_id = uuid.uuid4().hex[:12]
|
||||
@@ -128,6 +127,13 @@ def chat_completions():
|
||||
else:
|
||||
session = _ensure_chat_session(user_id, agent_id, None, title=display_query, status='running')
|
||||
|
||||
# [STEP 1] SSE 生成器可能在请求 scoped Session 清理后才开始迭代;提前快照会话标量,
|
||||
# 避免流内事务提交使 ORM 实例过期后触发 DetachedInstanceError。
|
||||
local_session_id = str(session.session_id)
|
||||
initial_session_status = str(session.status or 'running')
|
||||
initial_external_conversation_id = str(external_conversation_id or '').strip() or None
|
||||
stream_session = SimpleNamespace(session_id=local_session_id)
|
||||
|
||||
normalized_files: list[dict] | None = None
|
||||
if files is not None:
|
||||
if not isinstance(files, list):
|
||||
@@ -162,16 +168,14 @@ def chat_completions():
|
||||
display_query=display_query,
|
||||
user=user_proxy,
|
||||
agent=agent_proxy,
|
||||
session=session,
|
||||
external_conversation_id=external_conversation_id,
|
||||
session=stream_session,
|
||||
external_conversation_id=initial_external_conversation_id,
|
||||
request_id=request_id,
|
||||
normalized_files=normalized_files,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
kb_type=kb_type,
|
||||
)
|
||||
|
||||
@@ -185,8 +189,8 @@ def chat_completions():
|
||||
agent=agent_proxy,
|
||||
query=query,
|
||||
agent_id=agent_id,
|
||||
session_id=session.session_id,
|
||||
external_conversation_id=external_conversation_id,
|
||||
session_id=local_session_id,
|
||||
external_conversation_id=initial_external_conversation_id,
|
||||
normalized_files=normalized_files,
|
||||
kb_type=kb_type,
|
||||
leave_supported=leave_supported,
|
||||
@@ -198,19 +202,18 @@ def chat_completions():
|
||||
query,
|
||||
user_proxy.id,
|
||||
agent_proxy,
|
||||
external_conversation_id,
|
||||
initial_external_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=session.session_id,
|
||||
session_id=local_session_id,
|
||||
files=normalized_files,
|
||||
inputs=build_chat_dify_inputs(
|
||||
agent_proxy,
|
||||
session_id=session.session_id,
|
||||
session_id=local_session_id,
|
||||
request_id=request_id,
|
||||
trigger_source="frontend_chat",
|
||||
user_role=user_proxy.role,
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -226,14 +229,14 @@ def chat_completions():
|
||||
relay_first_chunk_at: float | None = None
|
||||
created_event = {
|
||||
'event': 'session_created',
|
||||
'conversation_id': session.session_id,
|
||||
'provider_conversation_id': session.external_conversation_id,
|
||||
'session_status': session.status,
|
||||
'conversation_id': local_session_id,
|
||||
'provider_conversation_id': initial_external_conversation_id,
|
||||
'session_status': initial_session_status,
|
||||
}
|
||||
yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n"
|
||||
|
||||
known_provider_conversation_id = session.external_conversation_id
|
||||
known_status = session.status
|
||||
known_provider_conversation_id = initial_external_conversation_id
|
||||
known_status = initial_session_status
|
||||
emitted_handler_state_keys: set[str] = set()
|
||||
|
||||
from app.services.chat.stream_relay import (
|
||||
@@ -276,7 +279,7 @@ def chat_completions():
|
||||
updated_session = _update_chat_session(
|
||||
user_id,
|
||||
agent_id,
|
||||
session.session_id,
|
||||
local_session_id,
|
||||
status=known_status,
|
||||
external_conversation_id=known_provider_conversation_id,
|
||||
touch=True,
|
||||
@@ -285,7 +288,7 @@ def chat_completions():
|
||||
known_status = updated_session.status
|
||||
|
||||
event_data['provider_conversation_id'] = provider_conversation_id
|
||||
event_data['conversation_id'] = session.session_id
|
||||
event_data['conversation_id'] = local_session_id
|
||||
event_data['session_status'] = known_status
|
||||
if chat_perf_enabled() and event_name in ('message_end', 'workflow_finished'):
|
||||
relay_first_ms = int((relay_first_chunk_at - relay_started) * 1000) if relay_first_chunk_at else None
|
||||
@@ -293,7 +296,7 @@ def chat_completions():
|
||||
current_app.logger.info(
|
||||
'[chat-perf] relay request_id=%s session_id=%s first_chunk_ms=%s total_relay_ms=%s event=%s',
|
||||
request_id,
|
||||
session.session_id,
|
||||
local_session_id,
|
||||
relay_first_ms,
|
||||
relay_total_ms,
|
||||
event_name,
|
||||
@@ -311,8 +314,8 @@ def chat_completions():
|
||||
):
|
||||
yield terminal_line
|
||||
except Exception as exc:
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id)
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'}
|
||||
current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, local_session_id)
|
||||
payload = {'event': 'error', 'message': str(exc), 'conversation_id': local_session_id, 'session_status': 'error'}
|
||||
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
||||
|
||||
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
||||
|
||||
@@ -10,21 +10,19 @@ from __future__ import annotations
|
||||
from .shared import * # noqa: F403
|
||||
|
||||
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None, shipping_batch_no: str | None = None) -> dict | None:
|
||||
def _build_chat_adapter_hints(*, shipping_task_id: str | None = None) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task/batch 提示,
|
||||
核心逻辑:平台入口只暴露通用参数;像发货通知这类业务专用 task 提示,
|
||||
统一收敛到 adapter_hints 这个不透明容器里,避免平台函数签名泄漏领域字段。
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
if not task_id:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/api/chat_turns.py
|
||||
|
||||
用途:Chat Turn 流式 API 路由(POST /api/chat/turns/stream)。
|
||||
依赖:app.core.decorators、ChatTurnRuntime、notice_upload、batch_from_notices、chat_bp。
|
||||
依赖:app.core.decorators、ChatTurnRuntime、chat_bp。
|
||||
逻辑:支持 JSON 与 multipart(附件上传 + Turn);由 chat.py 注册到同一 Blueprint。
|
||||
"""
|
||||
|
||||
@@ -77,7 +77,6 @@ def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
|
||||
"""
|
||||
将 multipart 附件写入 Turn input.payload。
|
||||
|
||||
- shipping.create_batch_from_notices:预检 notice_items
|
||||
- shipping.upload_inventory / shipping.replace_notice:staged 原始文件字节
|
||||
"""
|
||||
if not uploads:
|
||||
@@ -87,26 +86,7 @@ def _inject_multipart_upload_payload(body: dict, uploads: list) -> None:
|
||||
payload = input_block.get("payload") if isinstance(input_block.get("payload"), dict) else {}
|
||||
payload = dict(payload)
|
||||
|
||||
if action_type == "shipping.create_batch_from_notices":
|
||||
from app.services.shipping_notice.batch_from_notices import intake_notice_uploads_for_batch
|
||||
from app.services.shipping_notice.notice_upload import cleanup_temp_notice_uploads
|
||||
|
||||
temp_request_id = uuid.uuid4().hex
|
||||
try:
|
||||
notice_items, file_summary = intake_notice_uploads_for_batch(temp_request_id, uploads)
|
||||
finally:
|
||||
cleanup_temp_notice_uploads(temp_request_id)
|
||||
if not notice_items:
|
||||
raise ValidationError(
|
||||
"未能从发货通知附件中抽取到可解析文本,请上传清晰版 PDF/文本后重试",
|
||||
details={"file_summary": file_summary},
|
||||
)
|
||||
payload["notice_items"] = notice_items
|
||||
payload["file_summary"] = file_summary
|
||||
conversation_id = str(body.get("conversation_id") or body.get("conversationId") or "").strip()
|
||||
if conversation_id:
|
||||
payload["conversation_id"] = conversation_id
|
||||
elif action_type in ("shipping.upload_inventory", "shipping.replace_notice"):
|
||||
if action_type in ("shipping.upload_inventory", "shipping.replace_notice"):
|
||||
staged = _stage_upload_files(uploads)
|
||||
if not staged:
|
||||
raise ValidationError("file is required")
|
||||
|
||||
@@ -3,15 +3,13 @@ api/shipping_notice_tools.py
|
||||
|
||||
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
|
||||
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url、
|
||||
batch_legacy_removed(create_batch 410)。
|
||||
tool_api_url。
|
||||
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError;
|
||||
`_payload()` 剥离 body 中的操作人伪造字段,禁止集成密钥冒充用户写审计;
|
||||
co8 后 /tools/create_batch 固定 410,改走 order-extraction-submissions。
|
||||
历史批次 Tool 已删除,订单抽取统一走 order-extraction-submissions。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
from flask import Blueprint, current_app, jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
@@ -118,11 +116,11 @@ def _payload() -> dict:
|
||||
return payload
|
||||
|
||||
|
||||
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None, batch_no: str | None = None) -> None:
|
||||
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None) -> None:
|
||||
"""Chatflow 只读查询必须携带短效会话能力令牌,不能仅依赖全局集成密钥。"""
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.chat_tool_capability import require_chat_capability
|
||||
claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no, batch_no=batch_no)
|
||||
claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no)
|
||||
db.session.add(ShippingAuditEvent(
|
||||
event_type='chatflow_tool_read', aggregate_type='chat_session', aggregate_id=str(claims['sid']),
|
||||
task_no=task_no, actor_type='chatflow', actor_id=str(claims['uid']),
|
||||
@@ -130,10 +128,6 @@ def _require_read_capability(payload: dict, *, scope: str, task_no: str | None =
|
||||
metadata_json={'tool': scope, 'token_nonce': str(claims['nonce'])[:16], 'success': True},
|
||||
))
|
||||
|
||||
def _generate_batch_no() -> str:
|
||||
from datetime import datetime
|
||||
return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
@shipping_notice_bp.route('/tools/openapi.json', methods=['GET'])
|
||||
def openapi_spec():
|
||||
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
|
||||
@@ -192,19 +186,6 @@ def tool_confirm_temporary_inventory_use():
|
||||
"""
|
||||
return jsonify(shipping_tools.confirm_temporary_inventory_use(_payload()))
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
|
||||
def tool_create_batch():
|
||||
"""
|
||||
历史建批 Tool(已下线)。
|
||||
【AI 触发时机】:禁止调用;shipping_batches 已物理删除,请改走 order-extraction-submissions。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed(action='tools.create_batch')
|
||||
|
||||
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
|
||||
def tool_update_notice_fields():
|
||||
"""
|
||||
@@ -328,32 +309,6 @@ def tool_get_task_status():
|
||||
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
|
||||
return jsonify(shipping_tools.get_task_status(payload))
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST'])
|
||||
def tool_get_batch_status():
|
||||
"""
|
||||
历史批次状态查询(已下线)。
|
||||
【AI 触发时机】:禁止调用;请改用 get_task_status 或 shipping-processing。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed(action='tools.get_batch_status')
|
||||
|
||||
@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST'])
|
||||
def tool_switch_focus_task():
|
||||
"""
|
||||
历史批次焦点切换(已下线)。
|
||||
【AI 触发时机】:禁止调用;shipping_batches 已物理删除。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed(action='tools.switch_focus_task')
|
||||
|
||||
@shipping_notice_bp.route('/rpa/heartbeat', methods=['POST'])
|
||||
def rpa_worker_heartbeat():
|
||||
"""
|
||||
|
||||
@@ -3,16 +3,17 @@ backend/app/api/workspace/shipping_notice.py
|
||||
|
||||
用途:HXOPS 工作台发货通知用户态 API(任务处理工作台为履约写操作入口;Chat 仅通知/上传)。
|
||||
依赖:app.core.auth.jwt、app.core.errors、app.core.response.ok、shipping_notice.query_service /
|
||||
tools / notice_upload / ui_state、shipping_processing_projection、batch_legacy_removed。
|
||||
tools / notice_upload / ui_state、shipping_processing_projection。
|
||||
逻辑:薄路由层鉴权与参数校验;成功响应统一走 `_ok`/`ok` envelope;写接口保留乐观锁、幂等键与
|
||||
统一 AppError;人工上传强制证据资产;Chat Turn 履约写路径已废弃,请改走本 Blueprint;
|
||||
`/shipping-processing/*` 为统一进度读源;co8 后 `/shipping-batches*` 写 410 / 读空或 404;
|
||||
统一 AppError;人工上传仅确认唯一 Excel 已上传,不采集回执或凭据;Chat Turn 履约写路径已废弃,请改走本 Blueprint;
|
||||
`/shipping-processing/*` 为统一进度读源;历史 `/shipping-batches*` 已删除;
|
||||
Workflow ledger 路由已整段删除,进度请读 shipping-processing / Run API。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from io import BytesIO
|
||||
from time import perf_counter
|
||||
from typing import Any
|
||||
|
||||
from flask import Blueprint, Response, current_app, g, request, send_file
|
||||
@@ -32,9 +33,7 @@ from app.services.shipping_notice.processing_ownership import assert_notice_task
|
||||
from app.services.shipping_notice.query_service import (
|
||||
EXPORT_MIME_TYPE,
|
||||
count_my_todos,
|
||||
get_conversation_batch_workspace,
|
||||
get_task_for_user,
|
||||
list_batches_for_user,
|
||||
list_my_todos,
|
||||
list_tasks_page_for_user,
|
||||
resolve_task_export_download,
|
||||
@@ -148,9 +147,8 @@ def _assert_fulfillment_task_ownership(task: ShippingNotice, user_id: int) -> No
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET'])
|
||||
def workspace_shipping_tasks():
|
||||
"""分页列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
|
||||
"""分页列出当前用户可见的发货任务,可按处理状态过滤。"""
|
||||
user = _require_user()
|
||||
batch_no = str(request.args.get('batch_no') or '').strip() or None
|
||||
lifecycle_status = str(request.args.get('lifecycle_status') or '').strip() or None
|
||||
try:
|
||||
page = int(request.args.get('page') or 1)
|
||||
@@ -161,7 +159,6 @@ def workspace_shipping_tasks():
|
||||
raise ValidationError('page must be positive and page_size must be between 1 and 100')
|
||||
return _ok(list_tasks_page_for_user(
|
||||
user.id,
|
||||
batch_no=batch_no,
|
||||
lifecycle_status=lifecycle_status,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
@@ -309,116 +306,16 @@ def workspace_batch_restore_shipping_tasks():
|
||||
"""批量恢复回收站内仍为 active 的纯误建任务。"""
|
||||
return _batch_dispose('restore')
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches', methods=['GET'])
|
||||
def workspace_shipping_batches():
|
||||
"""列出当前用户的发货批次摘要;co8 后 shipping_batches 已 DROP,恒返回空列表。"""
|
||||
user = _require_user()
|
||||
limit = int(request.args.get('limit') or 100)
|
||||
return _ok(list_batches_for_user(user.id, limit=limit))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_notices():
|
||||
"""
|
||||
历史:多附件建批(已下线)。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
_require_user()
|
||||
raise_shipping_batches_removed(action='workspace.create_from_notices')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>', methods=['GET'])
|
||||
def workspace_shipping_batch_detail(batch_no: str):
|
||||
"""批次详情;shipping_batches 已 DROP,恒 404。"""
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_batch_ui_state(batch_no: str):
|
||||
"""批次 UI State;shipping_batches 已 DROP,恒 404。"""
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/tasks', methods=['GET'])
|
||||
def workspace_shipping_batch_tasks(batch_no: str):
|
||||
"""批次任务列表;shipping_batches 已 DROP,恒 404。"""
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['GET'])
|
||||
def workspace_shipping_batch_focus_task(batch_no: str):
|
||||
"""批次焦点任务;shipping_batches 已 DROP,恒 404。"""
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise NotFoundError('Not found')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/focus-task', methods=['POST'])
|
||||
def workspace_switch_shipping_batch_focus_task(batch_no: str):
|
||||
"""
|
||||
切换批次焦点(已下线)。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise_shipping_batches_removed(action='workspace.switch_batch_focus')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/create-from-intakes', methods=['POST'])
|
||||
def workspace_create_shipping_batch_from_intakes():
|
||||
"""
|
||||
历史:从 Intake 建批(已下线)。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
_require_user()
|
||||
raise_shipping_batches_removed(action='workspace.create_from_intakes')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-batches/<batch_no>/retry-pending', methods=['POST'])
|
||||
def workspace_retry_shipping_batch_pending(batch_no: str):
|
||||
"""
|
||||
历史:重试批次待推进任务(已下线)。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
_require_user()
|
||||
del batch_no
|
||||
raise_shipping_batches_removed(action='workspace.retry_batch_pending')
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-exports/archive', methods=['POST'])
|
||||
def workspace_shipping_export_archive():
|
||||
"""按批次或显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
|
||||
"""按显式任务号下载当前用户可访问的 ready 发货 Excel ZIP。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
task_nos = data.get('task_nos')
|
||||
if task_nos is not None and not isinstance(task_nos, list):
|
||||
raise ValidationError('task_nos must be a list', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
stream, filename, _manifest = build_export_archive(
|
||||
user_id=user.id, batch_no=str(data.get('batch_no') or '').strip() or None, task_nos=task_nos,
|
||||
)
|
||||
stream, filename, _manifest = build_export_archive(user_id=user.id, task_nos=task_nos or [])
|
||||
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
@@ -565,13 +462,6 @@ def workspace_confirm_order_customer_match(extraction_id: int, role: str):
|
||||
db.session.commit()
|
||||
return _ok(result)
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-conversations/<conversation_id>/batch-workspace', methods=['GET'])
|
||||
def workspace_shipping_conversation_batch_workspace(conversation_id: str):
|
||||
"""返回一个 Agent 会话下的多批次执行工作台快照;co8 后恒为空工作台。"""
|
||||
user = _require_user()
|
||||
return _ok(get_conversation_batch_workspace(conversation_id, user.id))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/create-from-notice', methods=['POST'])
|
||||
def workspace_create_shipping_task_from_notice():
|
||||
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
|
||||
@@ -696,6 +586,22 @@ def workspace_list_shipping_task_audit_timeline(task_no: str):
|
||||
return _ok(payload)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/freight-notice-groups', methods=['GET'])
|
||||
def workspace_shipping_task_freight_notice_groups(task_no: str):
|
||||
"""读取当前 PO 下按 business_no 聚合的货代上传 Notice;仅供订单工作台展示。"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_visible_to_user,
|
||||
list_freight_notice_groups_for_task,
|
||||
)
|
||||
|
||||
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(list_freight_notice_groups_for_task(task, user_id=int(user.id), is_admin=is_admin))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/ui-state', methods=['GET'])
|
||||
def workspace_shipping_task_ui_state(task_no: str):
|
||||
"""
|
||||
@@ -719,60 +625,6 @@ def workspace_shipping_task_chat_actions(task_no: str):
|
||||
raise NotFoundError('Not found')
|
||||
return _ok(build_chat_actions_payload(task))
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/retry', methods=['POST'])
|
||||
def workspace_retry_shipping_task(task_no: str):
|
||||
"""
|
||||
用户侧重试当前正式 OT:统一决策器选择 resolve_source / fetch / rematch / auto_progress。
|
||||
|
||||
核心逻辑:委托 task_retry_decision_service.retry_task_with_decision(scope=task);
|
||||
不再直接调用通用 retry_task 重置编排器。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
|
||||
|
||||
return _ok(retry_task_with_decision(
|
||||
task_no=str(task.task_no),
|
||||
user_id=int(user.id),
|
||||
scope='task',
|
||||
reason=str(data.get('reason') or data.get('comment') or 'user_retry'),
|
||||
trigger='user_retry',
|
||||
continue_auto_progress=False,
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
'/shipping-tasks/<task_no>/lines/<line_key>/retry',
|
||||
methods=['POST'],
|
||||
)
|
||||
def workspace_retry_shipping_task_line(task_no: str, line_key: str):
|
||||
"""
|
||||
行级统一「重试」:与任务级共用决策器,scope=line。
|
||||
|
||||
核心逻辑:前端不传内部动作码;后端按行库存事实选择 fetch/rematch/needs_human。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
if not task:
|
||||
raise NotFoundError('Not found')
|
||||
_assert_fulfillment_task_ownership(task, user.id)
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
|
||||
|
||||
return _ok(retry_task_with_decision(
|
||||
task_no=str(task.task_no),
|
||||
user_id=int(user.id),
|
||||
scope='line',
|
||||
line_key=str(line_key or '').strip(),
|
||||
reason=str(data.get('reason') or 'user_retry_inventory'),
|
||||
trigger='user_line_retry',
|
||||
continue_auto_progress=False,
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-fields', methods=['POST'])
|
||||
def workspace_update_shipping_notice_fields(task_no: str):
|
||||
"""更新发货通知单头字段。"""
|
||||
@@ -802,7 +654,7 @@ def workspace_update_shipping_notice_fields(task_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-freight-cancellations/<int:cancellation_id>/complete', methods=['POST'])
|
||||
def workspace_complete_shipping_freight_cancellation(cancellation_id: int):
|
||||
"""登记货代撤销回执并解除合法后继版本的履约阻断。"""
|
||||
"""登记已取得外部撤销确认并解除合法后继版本的履约阻断。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.models import ShippingFreightCancellation
|
||||
@@ -814,9 +666,7 @@ def workspace_complete_shipping_freight_cancellation(cancellation_id: int):
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.freight_cancellation_service import complete_freight_cancellation
|
||||
row = complete_freight_cancellation(
|
||||
cancellation_id=cancellation.id, actor_id=int(user.id),
|
||||
freight_receipt_no=str(data.get('freight_receipt_no') or ''),
|
||||
receipt_asset_id=data.get('receipt_asset_id'), note=str(data.get('note') or ''),
|
||||
cancellation_id=cancellation.id, actor_id=int(user.id), note=str(data.get('note') or ''),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({'id': row.id, 'status': row.status, 'old_task_id': row.old_task_id, 'new_task_id': row.new_task_id})
|
||||
@@ -998,9 +848,10 @@ def workspace_auto_progress_shipping_task(task_no: str):
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/mark-manual-uploaded', methods=['POST'])
|
||||
def workspace_mark_manual_uploaded(task_no: str):
|
||||
"""
|
||||
登记人工货代上传;必须提交当前用户已上传的截图或回执 FileAsset 编号。
|
||||
兼容旧 task_no 的人工上传确认;不再提交或记录截图/PDF、货代回执号。
|
||||
|
||||
核心逻辑:委托 upload_to_freight(mode=manual_confirm);禁止 RPA。
|
||||
核心逻辑:仅委托 upload_to_freight(mode=manual_confirm),新客户端必须改用
|
||||
business_no 的 `/shipping-notices/<business_no>/confirm-uploaded`。
|
||||
"""
|
||||
user = _require_user()
|
||||
task = get_task_for_user(task_no, user.id)
|
||||
@@ -1016,21 +867,232 @@ def workspace_mark_manual_uploaded(task_no: str):
|
||||
'actor_id': user.id,
|
||||
'_trusted_user_id': user.id,
|
||||
'event_source': 'workspace_api',
|
||||
'evidence_asset_no': data.get('evidence_asset_no'),
|
||||
'freight_ref_no': data.get('freight_ref_no'),
|
||||
'artifact_id': data.get('artifact_id'),
|
||||
}
|
||||
result = shipping_tools.upload_to_freight(payload)
|
||||
if isinstance(result, dict) and str(result.get('status') or '') == 'ok':
|
||||
# 回执先由既有服务原子登记;随后仅提交 upload_receipt_recorded Gate,由服务端复核事实后 completed。
|
||||
# 人工确认已由服务原子登记;随后只推进最终上传 Gate。
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
|
||||
run_task_auto_progress(
|
||||
str(task.task_no), trigger='manual_upload_receipt_recorded', operator_id=int(user.id),
|
||||
str(task.task_no), trigger='manual_upload_confirmed', operator_id=int(user.id),
|
||||
)
|
||||
return _ok(result)
|
||||
|
||||
|
||||
def _confirm_notice_uploaded(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
|
||||
"""
|
||||
按发货通知单号确认唯一 Excel 已上传;内部 task_no 仅用于既有状态机和审计追溯。
|
||||
|
||||
Args:
|
||||
business_no: 对外发货通知单号,禁止调用方以 task_no 代替。
|
||||
user_id: 当前服务端会话用户。
|
||||
artifact_id: 可选唯一 Excel Artifact 主键;不传时由服务端解析。
|
||||
|
||||
Returns:
|
||||
包含 business_no 和既有上传结果的字典。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 通知单不存在或当前用户无写权限。
|
||||
"""
|
||||
task = get_task_for_user(str(business_no).strip().upper(), user_id)
|
||||
if task is None or str(task.business_no or '').upper() != str(business_no).strip().upper():
|
||||
raise NotFoundError('Shipping notice not found')
|
||||
_assert_fulfillment_task_ownership(task, user_id)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
result = shipping_tools.upload_to_freight({
|
||||
'task_id': task.task_no,
|
||||
'mode': 'manual_confirm',
|
||||
'operator_id': user_id,
|
||||
'actor_id': user_id,
|
||||
'_trusted_user_id': user_id,
|
||||
'event_source': 'workspace_api',
|
||||
'artifact_id': artifact_id,
|
||||
})
|
||||
if isinstance(result, dict) and str(result.get('status') or '') == 'ok':
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
|
||||
run_task_auto_progress(
|
||||
str(task.task_no), trigger='manual_upload_confirmed', operator_id=user_id,
|
||||
)
|
||||
return {'business_no': str(task.business_no), **dict(result or {})}
|
||||
|
||||
|
||||
def _load_business_notice_for_user(*, business_no: str, user_id: int) -> ShippingNotice:
|
||||
"""
|
||||
按精确发货通知单号加载当前用户可操作的 Notice。
|
||||
|
||||
核心逻辑:先由既有用户归属查询过滤,再二次比较 Notice.business_no;禁止 task_no、
|
||||
历史聚合编号或模糊引用进入新的货代操作入口。
|
||||
|
||||
Args:
|
||||
business_no: 对外发货通知单号。
|
||||
user_id: 当前服务端会话用户主键。
|
||||
|
||||
Returns:
|
||||
当前用户拥有履约写权限的 ShippingNotice。
|
||||
|
||||
Raises:
|
||||
NotFoundError: 编号不存在或用户不可访问。
|
||||
"""
|
||||
normalized = str(business_no or '').strip().upper()
|
||||
task = get_task_for_user(normalized, user_id)
|
||||
if task is None or str(task.business_no or '').strip().upper() != normalized:
|
||||
raise NotFoundError('Shipping notice not found')
|
||||
_assert_fulfillment_task_ownership(task, user_id)
|
||||
return task
|
||||
|
||||
|
||||
def _start_notice_rpa_upload(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
|
||||
"""按 business_no 发起单张通知的货代 RPA 上传或重试。"""
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=user_id)
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
|
||||
result = shipping_tools.upload_to_freight({
|
||||
'task_id': task.task_no,
|
||||
'mode': 'retry_upload',
|
||||
'operator_id': user_id,
|
||||
'actor_id': user_id,
|
||||
'_trusted_user_id': user_id,
|
||||
'event_source': 'workspace_api',
|
||||
'artifact_id': artifact_id,
|
||||
})
|
||||
return {'business_no': str(task.business_no), **dict(result or {})}
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/confirm-uploaded', methods=['POST'])
|
||||
def workspace_confirm_shipping_notice_uploaded(business_no: str):
|
||||
"""确认一张发货通知单的唯一 Excel 已人工上传,不接收回执号或截图/PDF。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_artifact_id = data.get('artifact_id')
|
||||
try:
|
||||
artifact_id = int(raw_artifact_id) if raw_artifact_id is not None else None
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('artifact_id must be an integer') from exc
|
||||
return _ok(_confirm_notice_uploaded(
|
||||
business_no=business_no, user_id=int(user.id), artifact_id=artifact_id,
|
||||
))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/rpa-upload', methods=['POST'])
|
||||
def workspace_start_shipping_notice_rpa_upload(business_no: str):
|
||||
"""按发货通知单号发起 RPA 上传;RPA 成功事实仍由受信回调裁决。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_artifact_id = data.get('artifact_id')
|
||||
try:
|
||||
artifact_id = int(raw_artifact_id) if raw_artifact_id is not None else None
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('artifact_id must be an integer') from exc
|
||||
return _ok(_start_notice_rpa_upload(
|
||||
business_no=business_no, user_id=int(user.id), artifact_id=artifact_id,
|
||||
), status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/batch/confirm-uploaded', methods=['POST'])
|
||||
def workspace_batch_confirm_shipping_notices_uploaded():
|
||||
"""批量确认多个通知单已上传;每张通知单独立事务裁决,单项失败不回滚其他单。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_values = data.get('business_nos')
|
||||
if not isinstance(raw_values, list):
|
||||
raise ValidationError('business_nos must be a non-empty list')
|
||||
business_nos = list(dict.fromkeys(
|
||||
str(value or '').strip().upper() for value in raw_values if str(value or '').strip()
|
||||
))
|
||||
if not business_nos or len(business_nos) > 100:
|
||||
raise ValidationError('business_nos must contain 1 to 100 business numbers')
|
||||
results: list[dict[str, Any]] = []
|
||||
for business_no in business_nos:
|
||||
try:
|
||||
result = _confirm_notice_uploaded(business_no=business_no, user_id=int(user.id))
|
||||
db.session.commit()
|
||||
results.append({'business_no': business_no, 'status': 'confirmed', 'result': result})
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
results.append({'business_no': business_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message})
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return _ok({'results': results})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/batch/rpa-upload', methods=['POST'])
|
||||
def workspace_batch_start_shipping_notice_rpa_upload():
|
||||
"""批量发起 RPA 上传;每个 business_no 独立提交,单项失败不影响其他通知单。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_values = data.get('business_nos')
|
||||
if not isinstance(raw_values, list):
|
||||
raise ValidationError('business_nos must be a non-empty list')
|
||||
business_nos = list(dict.fromkeys(
|
||||
str(value or '').strip().upper() for value in raw_values if str(value or '').strip()
|
||||
))
|
||||
if not business_nos or len(business_nos) > 100:
|
||||
raise ValidationError('business_nos must contain 1 to 100 business numbers')
|
||||
results: list[dict[str, Any]] = []
|
||||
for business_no in business_nos:
|
||||
try:
|
||||
result = _start_notice_rpa_upload(business_no=business_no, user_id=int(user.id))
|
||||
db.session.commit()
|
||||
result_status = 'accepted' if str(result.get('status') or '').lower() in {'ok', 'running'} else 'blocked'
|
||||
results.append({'business_no': business_no, 'status': result_status, 'result': result})
|
||||
except AppError as exc:
|
||||
db.session.rollback()
|
||||
results.append({'business_no': business_no, 'status': 'blocked', 'code': exc.code, 'message': exc.message})
|
||||
except Exception:
|
||||
db.session.rollback()
|
||||
raise
|
||||
return _ok({'results': results}, status=202)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/<business_no>/export', methods=['GET'])
|
||||
def workspace_shipping_notice_export(business_no: str):
|
||||
"""按发货通知单号下载该通知唯一的正式 Excel,并保留下载审计。"""
|
||||
user = _require_user()
|
||||
task = _load_business_notice_for_user(business_no=business_no, user_id=int(user.id))
|
||||
err_msg = task_export_error_message(task)
|
||||
if err_msg:
|
||||
raise NotFoundError(err_msg)
|
||||
resolved = resolve_task_export_download(task)
|
||||
assert resolved is not None
|
||||
path, download_name = resolved
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
record_access_audit(
|
||||
action='download_notice_excel',
|
||||
aggregate_type='shipping_notice',
|
||||
aggregate_id=str(task.business_no),
|
||||
actor_id=user.id,
|
||||
task_no=str(task.task_no),
|
||||
reason_code='excel_downloaded',
|
||||
metadata={'business_no': str(task.business_no), 'export': 'excel'},
|
||||
)
|
||||
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notices/batch/export', methods=['POST'])
|
||||
def workspace_shipping_notice_export_archive():
|
||||
"""按多个 business_no 下载各自唯一 Excel 的 ZIP;任一越权或缺文件均整体拒绝。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
raw_values = data.get('business_nos')
|
||||
if not isinstance(raw_values, list):
|
||||
raise ValidationError('business_nos must be a non-empty list')
|
||||
business_nos = list(dict.fromkeys(
|
||||
str(value or '').strip().upper() for value in raw_values if str(value or '').strip()
|
||||
))
|
||||
if not business_nos or len(business_nos) > 100:
|
||||
raise ValidationError('business_nos must contain 1 to 100 business numbers')
|
||||
from app.services.shipping_notice.export_archive import build_export_archive
|
||||
|
||||
stream, filename, _manifest = build_export_archive(user_id=int(user.id), business_nos=business_nos)
|
||||
response = send_file(stream, as_attachment=True, download_name=filename, mimetype='application/zip')
|
||||
response.call_on_close(stream.close)
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/export', methods=['GET'])
|
||||
def workspace_shipping_task_export(task_no: str):
|
||||
"""下载当前用户可访问任务的出货 Excel;写入统一访问审计。"""
|
||||
@@ -1265,11 +1327,17 @@ def workspace_get_shipping_processing_conversation(conversation_id: str):
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.shipping_processing_projection import (
|
||||
project_conversation_processing_items,
|
||||
project_conversation_processing_summary,
|
||||
)
|
||||
|
||||
agent_raw = request.args.get('agent_id')
|
||||
agent_id = int(agent_raw) if agent_raw not in (None, '') else None
|
||||
payload = project_conversation_processing_items(
|
||||
projector = (
|
||||
project_conversation_processing_summary
|
||||
if str(request.args.get('view') or '').strip().lower() == 'summary'
|
||||
else project_conversation_processing_items
|
||||
)
|
||||
payload = projector(
|
||||
user_id=user.id,
|
||||
conversation_id=str(conversation_id or '').strip(),
|
||||
agent_id=agent_id,
|
||||
@@ -1352,7 +1420,21 @@ def workspace_mark_conversation_task_viewed(task_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_extraction_run(run_no: str):
|
||||
"""查询当前用户的一次订单抽取 Run;正文快照不会暴露给前端;访问留痕。"""
|
||||
"""
|
||||
查询当前用户的一次订单抽取 Run,并返回可与浏览器 HAR 对齐的读取分段耗时。
|
||||
|
||||
核心逻辑:先按当前用户加载 Run,再投影为工作台 DTO;保留原有访问审计,响应仅新增
|
||||
`Server-Timing` 指标,不暴露正文快照或改变业务数据。
|
||||
|
||||
Args:
|
||||
run_no: 当前用户有权访问的订单抽取 Run 业务编号。
|
||||
|
||||
Returns:
|
||||
Flask 成功响应,正文为既有 Run DTO,Header 含 run_lookup 和 workspace_projection 耗时。
|
||||
|
||||
Raises:
|
||||
AppError: Run 不存在或当前用户无权访问时由服务层抛出。
|
||||
"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
@@ -1360,8 +1442,12 @@ def workspace_get_shipping_order_extraction_run(run_no: str):
|
||||
serialize_order_extraction_run,
|
||||
)
|
||||
|
||||
lookup_started = perf_counter()
|
||||
run = get_order_extraction_run(user_id=user.id, run_no=run_no)
|
||||
lookup_ms = (perf_counter() - lookup_started) * 1000
|
||||
projection_started = perf_counter()
|
||||
payload = serialize_order_extraction_run(run)
|
||||
projection_ms = (perf_counter() - projection_started) * 1000
|
||||
# 轮询接口 60s 节流:窗口内复用最近访问痕迹,仍可追溯访问者与范围。
|
||||
record_access_audit(
|
||||
action='view_order_extraction_run',
|
||||
@@ -1372,7 +1458,12 @@ def workspace_get_shipping_order_extraction_run(run_no: str):
|
||||
conversation_id=run.conversation_id,
|
||||
metadata={'status': str(run.status or ''), 'poll': True},
|
||||
)
|
||||
return _ok(payload)
|
||||
response = current_app.make_response(_ok(payload))
|
||||
response.headers['Server-Timing'] = (
|
||||
f'run_lookup;dur={lookup_ms:.1f}, '
|
||||
f'workspace_projection;dur={projection_ms:.1f}'
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/progress-events', methods=['GET'])
|
||||
@@ -1417,14 +1508,24 @@ def workspace_list_shipping_order_extraction_documents(run_no: str):
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>/review', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_run(run_no: str):
|
||||
"""读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照;访问留痕。"""
|
||||
"""
|
||||
读取当前用户 Run 的复核 Case 汇总;不返回机器原文或内部执行快照;访问留痕。
|
||||
|
||||
通过 Server-Timing 暴露查找与投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_run
|
||||
from app.services.shipping_notice.order_review_service import get_review_run_visible_to_user
|
||||
|
||||
payload = serialize_review_run(get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin))
|
||||
lookup_started = perf_counter()
|
||||
review_run = get_review_run_visible_to_user(run_no, user.id, is_admin=is_admin)
|
||||
lookup_ms = (perf_counter() - lookup_started) * 1000
|
||||
projection_started = perf_counter()
|
||||
payload = serialize_review_run(review_run)
|
||||
projection_ms = (perf_counter() - projection_started) * 1000
|
||||
record_access_audit(
|
||||
action='view_order_review_run',
|
||||
aggregate_type='order_extraction_run',
|
||||
@@ -1432,20 +1533,34 @@ def workspace_get_shipping_order_review_run(run_no: str):
|
||||
actor_id=user.id,
|
||||
run_no=str(run_no),
|
||||
)
|
||||
return _ok(payload)
|
||||
response = current_app.make_response(_ok(payload))
|
||||
response.headers['Server-Timing'] = (
|
||||
f'review_lookup;dur={lookup_ms:.1f}, '
|
||||
f'review_projection;dur={projection_ms:.1f}'
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-queue/<run_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_queue(run_no: str):
|
||||
"""读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。"""
|
||||
"""
|
||||
读取当前会话的有效订单队列;不改变单 Run 复核摘要 API 语义。
|
||||
|
||||
通过 Server-Timing 暴露查找与投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_queue
|
||||
from app.services.shipping_notice.order_review_service import get_review_queue_visible_to_user
|
||||
|
||||
lookup_started = perf_counter()
|
||||
runs = get_review_queue_visible_to_user(run_no, user.id, is_admin=is_admin)
|
||||
lookup_ms = (perf_counter() - lookup_started) * 1000
|
||||
projection_started = perf_counter()
|
||||
payload = serialize_review_queue(runs)
|
||||
projection_ms = (perf_counter() - projection_started) * 1000
|
||||
record_access_audit(
|
||||
action='view_order_review_queue',
|
||||
aggregate_type='conversation',
|
||||
@@ -1455,12 +1570,22 @@ def workspace_get_shipping_order_review_queue(run_no: str):
|
||||
run_no=str(run_no),
|
||||
metadata={'item_count': len(payload.get('items') or [])},
|
||||
)
|
||||
return _ok(payload)
|
||||
response = current_app.make_response(_ok(payload))
|
||||
response.headers['Server-Timing'] = (
|
||||
f'queue_lookup;dur={lookup_ms:.1f}, '
|
||||
f'queue_projection;dur={projection_ms:.1f}'
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-review-cases/<case_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_review_case(case_no: str):
|
||||
"""读取当前用户的一份 PDF 复核完整快照;Case 编号不能跨 owner 越权访问;访问留痕。"""
|
||||
"""
|
||||
读取当前用户的一份 PDF 复核完整快照;Case 编号不能跨 owner 越权访问;访问留痕。
|
||||
|
||||
通过 Server-Timing 暴露查找与快照投影的耗时边界,便于定位工作台文件切换的服务端瓶颈;不改变
|
||||
JSON 响应契约或业务数据。
|
||||
"""
|
||||
user = _require_user()
|
||||
is_admin = str(getattr(user, 'role', '') or '').lower() == 'admin'
|
||||
from app.services.shipping_notice.fulfillment_audit import record_access_audit
|
||||
@@ -1470,10 +1595,12 @@ def workspace_get_shipping_order_review_case(case_no: str):
|
||||
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
|
||||
|
||||
# 只读:禁止在 GET 中入队 STP(入队仅抽取收尾 / resume / 显式 retry POST)。
|
||||
snapshot = build_order_review_case_snapshot(
|
||||
get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin),
|
||||
is_admin=is_admin,
|
||||
)
|
||||
lookup_started = perf_counter()
|
||||
review_case = get_review_case_visible_to_user(case_no, user.id, is_admin=is_admin)
|
||||
lookup_ms = (perf_counter() - lookup_started) * 1000
|
||||
projection_started = perf_counter()
|
||||
snapshot = build_order_review_case_snapshot(review_case, is_admin=is_admin)
|
||||
projection_ms = (perf_counter() - projection_started) * 1000
|
||||
record_access_audit(
|
||||
action='view_order_review_case',
|
||||
aggregate_type='order_review_case',
|
||||
@@ -1486,7 +1613,12 @@ def workspace_get_shipping_order_review_case(case_no: str):
|
||||
else None
|
||||
),
|
||||
)
|
||||
return _ok(snapshot)
|
||||
response = current_app.make_response(_ok(snapshot))
|
||||
response.headers['Server-Timing'] = (
|
||||
f'case_lookup;dur={lookup_ms:.1f}, '
|
||||
f'case_projection;dur={projection_ms:.1f}'
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
@@ -1575,21 +1707,6 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str):
|
||||
source_content_hash = (
|
||||
str(payload.get('source_content_hash') or '').strip() or None
|
||||
)
|
||||
# [Phase 4] 管理员专用扩展:legacy_job_id(历史 Job 928/929 replay)与 replay_mode 透传;
|
||||
# 非管理员若传入 → 直接 422 拒绝(与 reconcile_and_progress PRE-CHECK 一致)。
|
||||
legacy_job_id_raw = payload.get('legacy_job_id')
|
||||
legacy_job_id: int | None = None
|
||||
if legacy_job_id_raw is not None:
|
||||
try:
|
||||
legacy_job_id = int(legacy_job_id_raw)
|
||||
except (TypeError, ValueError):
|
||||
raise ValidationError(
|
||||
'legacy_job_id must be integer if provided',
|
||||
code='SHIPPING.RECONCILE_INVALID_EXPECTED_VERSION',
|
||||
)
|
||||
replay_mode_raw = payload.get('replay_mode')
|
||||
replay_mode = bool(replay_mode_raw) if replay_mode_raw is not None else False
|
||||
|
||||
from app.services.shipping_notice.reconciliation_service import reconcile_and_progress
|
||||
|
||||
result = reconcile_and_progress(
|
||||
@@ -1600,8 +1717,6 @@ def workspace_reconcile_shipping_order_case_and_progress(case_no: str):
|
||||
expected_case_version=expected_case_version,
|
||||
source_content_hash=source_content_hash,
|
||||
is_admin=is_admin,
|
||||
legacy_job_id=legacy_job_id,
|
||||
replay_mode=replay_mode,
|
||||
)
|
||||
return _ok(result.to_public())
|
||||
|
||||
@@ -1808,26 +1923,24 @@ def workspace_delete_shipping_order_review_line(case_no: str, line_key: str):
|
||||
def workspace_validate_shipping_order_review_draft(case_no: str):
|
||||
"""显式重跑当前草稿校验,并触发统一恢复协调器(可 auto_gate)。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_review_draft_service import validate_draft
|
||||
from app.services.shipping_notice.order_review_resume_service import (
|
||||
attach_resume_outcome,
|
||||
resume_after_review_change,
|
||||
)
|
||||
|
||||
payload = _review_draft_payload(user_id=user.id, case_no=case_no, action='draft_validated')
|
||||
result = validate_draft(
|
||||
user_id=user.id, case_no=case_no, expected_draft_version=payload.get('expected_draft_version'),
|
||||
)
|
||||
db.session.commit()
|
||||
# 保存校验必须由统一恢复协调器编排:唯一客户候选自动确认 → Draft 校验 →
|
||||
# Gate/资格/STP。若先独立校验,会在同一次点击中把 unique_candidate 误判为未确认。
|
||||
resume = resume_after_review_change(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
trigger='draft_validated',
|
||||
change_type=None,
|
||||
skip_validate=True,
|
||||
skip_validate=False,
|
||||
allow_auto_create=True,
|
||||
expected_draft_version=payload.get('expected_draft_version'),
|
||||
)
|
||||
return _ok(attach_resume_outcome({'case': result}, resume))
|
||||
return _ok(attach_resume_outcome({'case': resume.get('case')}, resume))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
@@ -2003,24 +2116,13 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
|
||||
为选中完整明细行创建履约波次。
|
||||
|
||||
Body: line_keys[], expected_draft_version, idempotency_key, reason?
|
||||
已有正式 OT 时走 create_post_ot_fulfillment_wave + schedule_post_ot_wave_progress;
|
||||
禁止调用 schedule_auto_progress_after_review_confirm。
|
||||
无正式 OT 时保留历史 create_fulfillment_wave(BE-8 兼容分支,仅建单前兜底;
|
||||
响应标记 legacy_pre_ot_wave=true,后续版本可收敛删除)。
|
||||
只允许正式 OT 走 create_post_ot_fulfillment_wave +
|
||||
schedule_post_ot_wave_progress。无正式 OT 的历史波次路径已下线,调用方必须
|
||||
先完成正式建单,避免同一业务动作存在两套推进事实。
|
||||
"""
|
||||
import logging
|
||||
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.services.shipping_notice.order_review_confirmation_service import (
|
||||
finalize_sync_auto_progress_after_commit,
|
||||
resolve_confirm_outcome,
|
||||
schedule_auto_progress_after_review_confirm,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
create_fulfillment_wave,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
|
||||
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
|
||||
create_post_ot_fulfillment_wave,
|
||||
@@ -2064,40 +2166,12 @@ def workspace_create_shipping_order_review_fulfillment_wave(case_no: str):
|
||||
result['auto_progress'] = progress
|
||||
result['auto_progress_started'] = bool((progress or {}).get('auto_progress_started'))
|
||||
result['post_ot_wave'] = True
|
||||
result['legacy_pre_ot_wave'] = False
|
||||
return _ok(result)
|
||||
|
||||
# [STEP] BE-8:无正式 OT 的历史 wave→confirm 路径;仅兼容,不作为 OT 后主路径。
|
||||
logging.getLogger(__name__).warning(
|
||||
'shipping_review_fulfillment_wave_legacy_pre_ot case_no=%s line_count=%s',
|
||||
case_no,
|
||||
len(line_keys),
|
||||
raise ValidationError(
|
||||
'A formal order task is required before creating a fulfillment wave',
|
||||
code='SHIPPING.FORMAL_OT_REQUIRED',
|
||||
)
|
||||
result = create_fulfillment_wave(
|
||||
user_id=user.id,
|
||||
case_no=case_no,
|
||||
line_keys=line_keys,
|
||||
expected_draft_version=data.get('expected_draft_version'),
|
||||
idempotency_key=idem,
|
||||
reason=reason,
|
||||
)
|
||||
progress = schedule_auto_progress_after_review_confirm(
|
||||
task_no=result.get('task_no'),
|
||||
idempotent_replay=bool(result.get('idempotent_replay')),
|
||||
created_by_id=int(user.id),
|
||||
commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
progress = finalize_sync_auto_progress_after_commit(progress)
|
||||
result = dict(result)
|
||||
result.pop('trigger_auto_progress', None)
|
||||
result['confirm_ok'] = True
|
||||
result['confirm_outcome'] = resolve_confirm_outcome(progress)
|
||||
result['auto_progress'] = progress
|
||||
result['auto_progress_started'] = bool((progress or {}).get('auto_progress_started'))
|
||||
result['post_ot_wave'] = False
|
||||
result['legacy_pre_ot_wave'] = True
|
||||
return _ok(result)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route(
|
||||
@@ -2844,8 +2918,8 @@ def workspace_list_shipping_order_extraction_runs():
|
||||
page_raw = request.args.get('page')
|
||||
page_size_raw = request.args.get('page_size')
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
list_order_extraction_runs,
|
||||
serialize_order_extraction_run,
|
||||
list_order_extraction_run_summaries,
|
||||
serialize_order_extraction_run_list_item,
|
||||
)
|
||||
|
||||
if page_raw is not None or page_size_raw is not None:
|
||||
@@ -2854,7 +2928,7 @@ def workspace_list_shipping_order_extraction_runs():
|
||||
page_size = int(page_size_raw or 20)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('page and page_size must be integers') from exc
|
||||
payload = list_order_extraction_runs(
|
||||
payload = list_order_extraction_run_summaries(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
status=status,
|
||||
@@ -2863,7 +2937,7 @@ def workspace_list_shipping_order_extraction_runs():
|
||||
)
|
||||
assert isinstance(payload, dict)
|
||||
return _ok({
|
||||
'items': [serialize_order_extraction_run(row) for row in payload['items']],
|
||||
'items': [serialize_order_extraction_run_list_item(row) for row in payload['items']],
|
||||
'total': payload['total'],
|
||||
'page': payload['page'],
|
||||
'page_size': payload['page_size'],
|
||||
@@ -2873,14 +2947,14 @@ def workspace_list_shipping_order_extraction_runs():
|
||||
limit = int(request.args.get('limit') or 50)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('limit must be an integer') from exc
|
||||
rows = list_order_extraction_runs(
|
||||
rows = list_order_extraction_run_summaries(
|
||||
user_id=user.id,
|
||||
conversation_id=conversation_id,
|
||||
status=status,
|
||||
limit=limit,
|
||||
)
|
||||
assert isinstance(rows, list)
|
||||
return _ok({'items': [serialize_order_extraction_run(row) for row in rows]})
|
||||
return _ok({'items': [serialize_order_extraction_run_list_item(row) for row in rows]})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
|
||||
|
||||
@@ -17,7 +17,6 @@ from app.jobs.handlers import ( # noqa: F401
|
||||
shipping_notice_run,
|
||||
shipping_order_extraction,
|
||||
shipping_process_gate,
|
||||
shipping_auto_progress,
|
||||
shipping_stp_auto_create,
|
||||
shipping_line_auto_fulfill,
|
||||
shipping_post_ot_wave_progress,
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
"""
|
||||
jobs/handlers/shipping_auto_progress.py
|
||||
|
||||
用途:终态化历史 APX AutoProgress Job。
|
||||
依赖:JobContext、auto_progress_controller。
|
||||
逻辑:Job 已由通用队列领取为 running;本 Handler 仅委托控制器取消遗留 APX
|
||||
Job 并保留审计。正式 20-Gate 只能由 shipping_process_gate Handler 执行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.jobs.context import JobContext
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.services.shipping_notice.auto_progress_controller import run_auto_progress_job
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_AUTO_PROGRESS)
|
||||
def run_shipping_auto_progress(ctx: JobContext, payload: dict) -> None:
|
||||
"""终态化历史 APX Job;payload 必须含队列注入的 job_id。"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
if not raw_job_id:
|
||||
raise RuntimeError('missing_job_id_for_shipping_auto_progress')
|
||||
run_auto_progress_job(
|
||||
job_id=int(raw_job_id),
|
||||
worker_id=str(ctx.extras.get('worker_label') or f'shipping-auto-progress-{raw_job_id}'),
|
||||
)
|
||||
@@ -1018,7 +1018,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
1
|
||||
for order in merged_unit_orders if isinstance(order, dict)
|
||||
for conflict in order.get('conflicts') or [] if isinstance(conflict, dict)
|
||||
if str(conflict.get('reason') or '').strip() == 'supplement_relation_ambiguous'
|
||||
if str(conflict.get('reason') or '').strip() in {
|
||||
'supplement_relation_ambiguous', 'supplement_field_conflict',
|
||||
}
|
||||
)
|
||||
supplement_status = (
|
||||
'conflict'
|
||||
@@ -1148,7 +1150,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
)
|
||||
# 收口摘要保留可投影的处理事实,供 Run 级 handling_items 区分待补/冲突/冻结/复核。
|
||||
summary = {
|
||||
'run_no': run.run_no, 'batch_no': result.get('batch_no'),
|
||||
'run_no': run.run_no,
|
||||
'created_count': int(result.get('created_count') or 0),
|
||||
'opened_existing_count': int(result.get('opened_existing_count') or 0),
|
||||
'pending_count': int(result.get('pending_count') or 0),
|
||||
|
||||
@@ -63,12 +63,13 @@ def handle_shipping_post_ot_wave_progress(ctx: JobContext, payload: dict) -> Non
|
||||
try:
|
||||
from app.services.shipping_notice.fulfillment_workflow import generate_excel
|
||||
|
||||
# [STEP] 为本 OT 生成/刷新发货 Excel;wave_no 写入上下文供审计与后续过滤。
|
||||
# [STEP] 为本次独立 Notice 生成 Excel,禁止捎带同 PO 的其他项次。
|
||||
gen = generate_excel({
|
||||
'task_id': task.task_no,
|
||||
'wave_no': wave_no,
|
||||
'line_keys': list(frozen.get('line_keys') or []),
|
||||
'post_ot_wave': True,
|
||||
'_orchestrator_internal_dispatch': True,
|
||||
})
|
||||
status = str((gen or {}).get('status') or '').strip().lower()
|
||||
if status in {'failed', 'error'}:
|
||||
|
||||
@@ -22,8 +22,6 @@ class JobType(StrEnum):
|
||||
SHIPPING_PROCESS_GATE = 'shipping_process_gate'
|
||||
# RPA 回调 HTTP 只收件;Excel 校验、解析、任务关联由 shipping worker 异步完成。
|
||||
SHIPPING_INVENTORY_CALLBACK_PROCESS = 'shipping_inventory_callback_process'
|
||||
# 历史 APX 兼容:Worker 仅终态化,不再执行 Gate。
|
||||
SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress'
|
||||
# 统一 PDF 自动标记:按实际证据能力执行坐标重建或 XFA 多源视觉融合。
|
||||
SHIPPING_PDF_AUTOMARK = 'shipping_pdf_automark'
|
||||
# 资格达标后的 STP 自动建单入队(先 queued,再由 worker 执行 confirm)
|
||||
@@ -72,7 +70,6 @@ QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction',
|
||||
'shipping_document_layout', 'shipping_process_gate', 'shipping_pdf_automark',
|
||||
'shipping_inventory_callback_process',
|
||||
'shipping_auto_progress',
|
||||
'shipping_stp_auto_create', 'shipping_line_auto_fulfill',
|
||||
'shipping_post_ot_wave_progress', 'shipping_review_revalidate_progress',
|
||||
}),
|
||||
|
||||
@@ -151,7 +151,6 @@ from app.models.shipping_receipt_report import (
|
||||
from app.models.shipping_temporary_inventory import ShippingTemporaryInventorySession
|
||||
from app.models.shipping_customer import (
|
||||
ShippingBusinessSequence,
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
@@ -290,7 +289,6 @@ __all__ = [
|
||||
'ShippingCustomerSiteIdentifier',
|
||||
'ShippingCustomerImportBatch',
|
||||
'ShippingCustomerImportRow',
|
||||
'ShippingCase',
|
||||
'ShippingBusinessSequence',
|
||||
'ShippingCustomerShadowResolution',
|
||||
'ShippingCustomerShadowMatch',
|
||||
|
||||
@@ -30,25 +30,6 @@ class Job(Base):
|
||||
Index('ix_jobs_business_ref', 'domain', 'job_type', 'business_ref'),
|
||||
Index('ix_jobs_locked_at', 'locked_at'),
|
||||
Index('ix_jobs_retry_of_job_id', 'retry_of_job_id'),
|
||||
# P0-3:同一 Task 同时只允许一个正式 AutoProgress 决策 Job。库存源 RPA
|
||||
# Attempt 不使用该索引,因此可以按 source 并行执行。
|
||||
Index(
|
||||
'uq_jobs_shipping_auto_progress_one_active_task',
|
||||
'task_id',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
"domain = 'shipping_notice' "
|
||||
"AND job_type = 'shipping_auto_progress' "
|
||||
"AND status IN ('queued', 'running') "
|
||||
"AND task_id IS NOT NULL"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"domain = 'shipping_notice' "
|
||||
"AND job_type = 'shipping_auto_progress' "
|
||||
"AND status IN ('queued', 'running') "
|
||||
"AND task_id IS NOT NULL"
|
||||
),
|
||||
),
|
||||
# 仅预解析 Job:同业务锚点同时只允许一条 queued
|
||||
# (不含 running:retry 可在旧 running 残留时另建 queued;RUN 复查也不受限)
|
||||
Index(
|
||||
|
||||
@@ -25,6 +25,7 @@ from typing import List, Optional
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
Date,
|
||||
DateTime,
|
||||
Float,
|
||||
ForeignKey,
|
||||
@@ -54,6 +55,7 @@ class ShippingNotice(Base):
|
||||
Index('ix_shipping_notices_conversation', 'conversation_id'),
|
||||
Index('ix_shipping_notices_current_step', 'current_step'),
|
||||
Index('ix_shipping_notices_upload_status', 'upload_status'),
|
||||
Index('ix_shipping_notices_business_no', 'business_no'),
|
||||
Index('ix_shipping_notices_inventory_source_code', 'inventory_source_code'),
|
||||
Index('ix_shipping_notices_inventory_source_status', 'inventory_source_status'),
|
||||
Index('ix_shipping_notices_inventory_routing_fingerprint', 'inventory_routing_fingerprint'),
|
||||
@@ -70,11 +72,16 @@ class ShippingNotice(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
|
||||
shipping_case_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_cases.id'),
|
||||
index=True,
|
||||
nullable=True,
|
||||
customer_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_customers.id'), index=True, nullable=True,
|
||||
)
|
||||
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
|
||||
# 发货通知单的对外业务编号;同一 PO 的不同波次各自拥有独立编号。
|
||||
business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True)
|
||||
business_date: Mapped[Optional[datetime]] = mapped_column(Date, nullable=True)
|
||||
business_sequence_value: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
business_numbering_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
|
||||
source_type: Mapped[str] = mapped_column(String(32), default='manual')
|
||||
@@ -234,11 +241,7 @@ class ShippingNotice(Base):
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
shipping_case: Mapped[Optional['ShippingCase']] = relationship(
|
||||
'ShippingCase',
|
||||
back_populates='tasks',
|
||||
lazy='joined',
|
||||
)
|
||||
customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', lazy='joined')
|
||||
events: Mapped[List['ShippingTaskEvent']] = relationship(
|
||||
'ShippingTaskEvent',
|
||||
back_populates='task',
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/models/shipping_customer.py
|
||||
|
||||
用途:货代标准客户、客户识别证据、业务单聚合与业务编号流水模型。
|
||||
用途:货代标准客户、客户识别证据与业务编号流水模型。
|
||||
依赖:models.base.Base、users、shipping_notices。
|
||||
逻辑:客户主数据提供稳定身份;ShippingCase 聚合 Notice 修订链;流水表供后续编号服务原子递增。
|
||||
逻辑:客户主数据提供稳定身份;发货通知自持履约事实;流水表供编号服务原子递增。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -55,7 +55,6 @@ class ShippingCustomer(Base):
|
||||
back_populates='customer',
|
||||
cascade='all, delete-orphan',
|
||||
)
|
||||
cases: Mapped[List['ShippingCase']] = relationship('ShippingCase', back_populates='customer')
|
||||
merged_into_customer: Mapped[Optional['ShippingCustomer']] = relationship(
|
||||
'ShippingCustomer',
|
||||
remote_side='ShippingCustomer.id',
|
||||
@@ -189,40 +188,6 @@ class ShippingCustomerSiteIdentifier(Base):
|
||||
site: Mapped['ShippingCustomerSite'] = relationship('ShippingCustomerSite', back_populates='identifiers')
|
||||
|
||||
|
||||
class ShippingCase(Base):
|
||||
"""一票发货业务聚合;多个线性任务修订版本共享同一业务单。"""
|
||||
|
||||
__tablename__ = 'shipping_cases'
|
||||
__table_args__ = (
|
||||
Index('ix_shipping_cases_customer_created', 'customer_id', 'created_at'),
|
||||
Index('ix_shipping_cases_status_created', 'status', 'created_at'),
|
||||
UniqueConstraint('replaces_case_id', name='uq_shipping_cases_replaces_case_id'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
case_no: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
|
||||
customer_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_customers.id'), nullable=True, index=True)
|
||||
business_no: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True)
|
||||
customer_name_snapshot: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
|
||||
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(6), nullable=True)
|
||||
business_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
|
||||
sequence_value: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
numbering_rule_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
numbering_status: Mapped[str] = mapped_column(String(32), nullable=False, default='pending', server_default='pending')
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='open', server_default='open')
|
||||
replaces_case_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_cases.id'), nullable=True)
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
customer: Mapped[Optional['ShippingCustomer']] = relationship('ShippingCustomer', back_populates='cases')
|
||||
tasks: Mapped[List['ShippingNotice']] = relationship(
|
||||
'ShippingNotice',
|
||||
back_populates='shipping_case',
|
||||
lazy='selectin',
|
||||
)
|
||||
|
||||
|
||||
class ShippingBusinessSequence(Base):
|
||||
"""按业务类型、客户和 Asia/Shanghai 业务日期保存当前流水值。"""
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ models/shipping_excel_template.py
|
||||
用途:定义版本化发货 Excel 模板及不可变 Notice 导出产物。
|
||||
依赖:models.base.Base、库存源、订单 Schema、ShippingNotice 与库存快照模型。
|
||||
逻辑:库存源只绑定已发布模板版本;每次生成均新增 Artifact 并锁定输入版本与校验和;
|
||||
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列。
|
||||
co8e9f0a1b2c 已删除 export artifact 的 batch_id 列;Artifact 直接属于一张 Notice。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -12,7 +12,7 @@ from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingFreightCancellation(Base):
|
||||
"""已上传旧 Notice 的撤销申请与货代回执;成功前新版本不得履约。"""
|
||||
"""已上传旧 Notice 的撤销申请与外部撤销确认;成功前新版本不得履约。"""
|
||||
|
||||
__tablename__ = 'shipping_notice_freight_cancellations'
|
||||
__table_args__ = (
|
||||
|
||||
@@ -155,8 +155,9 @@ class ShippingUploadAttempt(Base):
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
# 历史资产关联字段仅为兼容旧数据;新货代上传不写截图或文件证据。
|
||||
evidence_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
|
||||
# [BE-05] RPA 成功时持久化绿色 DOM 证据(kind/selector/observed_at/filename 等)。
|
||||
# RPA 仅保存最小状态摘要(kind/selector/observed_at/filename 等),不保存截图或 DOM。
|
||||
success_evidence_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
operator_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
models/shipping_order_review_wave_line.py
|
||||
|
||||
用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一个 Task。
|
||||
用途:复核 Case 履约波次行归属(不可变),保证同一明细行最多进入一张 Notice。
|
||||
依赖:ShippingOrderReviewCase、ShippingNotice、ShippingOrderReviewConfirmedRevision。
|
||||
逻辑:由 order_review_confirmation_service 在建波次/整单确认时写入;
|
||||
(review_case_id, line_key) 数据库唯一约束防并发重复入波次。
|
||||
|
||||
@@ -16,7 +16,6 @@ from sqlalchemy import select
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingBusinessSequence,
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
@@ -27,6 +26,7 @@ from app.models import (
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingCustomerShadowMatch,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNotice,
|
||||
)
|
||||
|
||||
|
||||
@@ -62,7 +62,7 @@ def _build_customer_lifecycle_impact(customer: ShippingCustomer) -> dict[str, An
|
||||
}
|
||||
shadow_normalized = len(matched_resolution_ids)
|
||||
blockers = {
|
||||
'business_cases': db.session.query(ShippingCase.id).filter_by(customer_id=customer.id).count(),
|
||||
'shipping_notices': db.session.query(ShippingNotice.id).filter_by(customer_id=customer.id).count(),
|
||||
'business_sequences': db.session.query(ShippingBusinessSequence.id).filter_by(customer_id=customer.id).count(),
|
||||
'external_references': db.session.query(ShippingCustomerExternalRef.id).filter_by(customer_id=customer.id).count(),
|
||||
'order_customer_matches': db.session.query(ShippingOrderCustomerMatch.id).filter_by(customer_id=customer.id).count(),
|
||||
|
||||
@@ -17,7 +17,6 @@ from sqlalchemy.exc import IntegrityError
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
@@ -25,6 +24,7 @@ from app.models import (
|
||||
ShippingCustomerSite,
|
||||
ShippingCustomerSiteIdentifier,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
clean_text,
|
||||
@@ -117,7 +117,7 @@ def serialize_customer(
|
||||
record: ShippingCustomer,
|
||||
*,
|
||||
include_identifiers: bool = False,
|
||||
case_count: int | None = None,
|
||||
notice_count: int | None = None,
|
||||
identifier_count: int | None = None,
|
||||
identity_evidence_count: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
@@ -127,7 +127,7 @@ def serialize_customer(
|
||||
Args:
|
||||
record: 标准客户 ORM 记录。
|
||||
include_identifiers: 是否附带识别证据明细。
|
||||
case_count: 列表查询预聚合的业务单数量;为空时现场查询。
|
||||
notice_count: 列表查询预聚合的发货通知数量;为空时现场查询。
|
||||
identifier_count: 历史固定类型证据数量,仅供存量审计显示。
|
||||
identity_evidence_count: 配置化客户主体证据数量;为空时现场查询。
|
||||
Returns:
|
||||
@@ -144,7 +144,7 @@ def serialize_customer(
|
||||
'updated_by_id': record.updated_by_id,
|
||||
'created_at': record.created_at.isoformat() if record.created_at else None,
|
||||
'updated_at': record.updated_at.isoformat() if record.updated_at else None,
|
||||
'case_count': case_count if case_count is not None else db.session.query(ShippingCase.id).filter_by(customer_id=record.id).count(),
|
||||
'notice_count': notice_count if notice_count is not None else db.session.query(ShippingNotice.id).filter_by(customer_id=record.id).count(),
|
||||
'identifier_count': identifier_count if identifier_count is not None else db.session.query(ShippingCustomerIdentifier.id).filter_by(customer_id=record.id).count(),
|
||||
'identity_evidence_count': identity_evidence_count if identity_evidence_count is not None else db.session.query(
|
||||
ShippingIdentityEvidence.id,
|
||||
@@ -173,9 +173,9 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
|
||||
Returns:
|
||||
items、total、page、page_size、pages。
|
||||
"""
|
||||
case_counts = (
|
||||
db.session.query(ShippingCase.customer_id.label('customer_id'), func.count(ShippingCase.id).label('case_count'))
|
||||
.group_by(ShippingCase.customer_id)
|
||||
notice_counts = (
|
||||
db.session.query(ShippingNotice.customer_id.label('customer_id'), func.count(ShippingNotice.id).label('notice_count'))
|
||||
.group_by(ShippingNotice.customer_id)
|
||||
.subquery()
|
||||
)
|
||||
identifier_counts = (
|
||||
@@ -207,12 +207,12 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
|
||||
query = (
|
||||
db.session.query(
|
||||
ShippingCustomer,
|
||||
func.coalesce(case_counts.c.case_count, 0),
|
||||
func.coalesce(notice_counts.c.notice_count, 0),
|
||||
func.coalesce(identifier_counts.c.identifier_count, 0),
|
||||
func.coalesce(identity_evidence_counts.c.identity_evidence_count, 0)
|
||||
+ func.coalesce(site_identity_evidence_counts.c.identity_evidence_count, 0),
|
||||
)
|
||||
.outerjoin(case_counts, case_counts.c.customer_id == ShippingCustomer.id)
|
||||
.outerjoin(notice_counts, notice_counts.c.customer_id == ShippingCustomer.id)
|
||||
.outerjoin(identifier_counts, identifier_counts.c.customer_id == ShippingCustomer.id)
|
||||
.outerjoin(identity_evidence_counts, identity_evidence_counts.c.customer_id == ShippingCustomer.id)
|
||||
.outerjoin(site_identity_evidence_counts, site_identity_evidence_counts.c.customer_id == ShippingCustomer.id)
|
||||
@@ -244,10 +244,10 @@ def list_customers(params: dict[str, Any]) -> dict[str, Any]:
|
||||
return {
|
||||
'items': [
|
||||
serialize_customer(
|
||||
customer, case_count=int(case_count), identifier_count=int(identifier_count),
|
||||
customer, notice_count=int(notice_count), identifier_count=int(identifier_count),
|
||||
identity_evidence_count=int(identity_evidence_count),
|
||||
)
|
||||
for customer, case_count, identifier_count, identity_evidence_count in items
|
||||
for customer, notice_count, identifier_count, identity_evidence_count in items
|
||||
],
|
||||
'total': total,
|
||||
'page': page,
|
||||
|
||||
@@ -17,7 +17,7 @@ class ChatStreamContext:
|
||||
"""
|
||||
/api/chat/completions 单次流式请求上下文。
|
||||
|
||||
核心字段:用户/Agent/会话、Dify 入参、adapter_hints 与领域锚点(task_id/batch_no)。
|
||||
核心字段:用户/Agent/会话、Dify 入参、adapter_hints 与领域锚点(task_id)。
|
||||
"""
|
||||
|
||||
query: str
|
||||
@@ -30,7 +30,6 @@ class ChatStreamContext:
|
||||
normalized_files: list[dict] | None = None
|
||||
adapter_hints: dict[str, Any] | None = None
|
||||
shipping_task_id: str = ''
|
||||
shipping_batch_no: str = ''
|
||||
kb_type: str = '企业知识库'
|
||||
hxops_turn_id: str | None = None
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
"""
|
||||
用途:货代发货通知 Hybrid Handler,负责普通聊天中的任务/批次 UI State。
|
||||
用途:货代发货通知 Hybrid Handler,负责普通聊天中的任务 UI State。
|
||||
依赖:shipping_notice.query_service/ui_state、agent_registry.handlers.registry。
|
||||
逻辑:根据显式 task/batch 上下文构造并推送 UI State;订单抽取由后台 Run/Worker 独立执行。
|
||||
"""
|
||||
@@ -36,7 +36,7 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
"""
|
||||
货代发货通知业务 Handler。
|
||||
|
||||
核心逻辑:按 adapter_hints / task_id / batch_no 构造 shipping_ui_state,供实时消息使用。
|
||||
核心逻辑:按 adapter_hints / task_id 构造 shipping_ui_state,供实时消息使用。
|
||||
订单抽取状态卡由 Run API 和本地消息持久化恢复,不进入普通 Dify Chatflow 生命周期。
|
||||
"""
|
||||
|
||||
@@ -51,57 +51,36 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
"""
|
||||
构造 shipping_ui_state SSE 事件。
|
||||
|
||||
核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。
|
||||
核心逻辑:只接受显式 task_id;失败时记录日志并返回 None。
|
||||
"""
|
||||
if not _uses_shipping_ui_state_progress(ctx.agent):
|
||||
return None
|
||||
task_id = str(ctx.shipping_task_id or '').strip()
|
||||
batch_no = str(ctx.shipping_batch_no or '').strip()
|
||||
shipping_hints = self._shipping_hints(ctx)
|
||||
if not task_id and not batch_no:
|
||||
if not task_id:
|
||||
task_id = str(shipping_hints.get('task_id') or '').strip()
|
||||
batch_no = str(shipping_hints.get('batch_no') or '').strip()
|
||||
if not task_id and not batch_no:
|
||||
if not task_id:
|
||||
return None
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
from app.services.shipping_notice.ui_state import build_task_ui_state
|
||||
|
||||
task = get_task_by_ref(task_id) if task_id else None
|
||||
batch = get_batch_by_no(batch_no) if batch_no else None
|
||||
task = get_task_by_ref(task_id)
|
||||
session_id = str(getattr(ctx.session, 'session_id', '') or '')
|
||||
if task is not None:
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session_id,
|
||||
'task_no': task.task_no,
|
||||
'batch_no': None,
|
||||
'ui_state': build_task_ui_state(task),
|
||||
}
|
||||
if batch is not None:
|
||||
batch_ui_state = build_batch_ui_state(batch)
|
||||
focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {}
|
||||
focus_ui_state = (
|
||||
batch_ui_state.get('focus_task_ui_state')
|
||||
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
|
||||
else None
|
||||
)
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session_id,
|
||||
'batch_no': batch.batch_no,
|
||||
'task_no': focus_task.get('task_no'),
|
||||
'batch_ui_state': batch_ui_state,
|
||||
**({'ui_state': focus_ui_state} if focus_ui_state is not None else {}),
|
||||
}
|
||||
except Exception:
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
'[shipping-handler] build_ui_state failed request_id=%s task_id=%s batch_no=%s',
|
||||
'[shipping-handler] build_ui_state failed request_id=%s task_id=%s',
|
||||
ctx.request_id,
|
||||
task_id,
|
||||
batch_no,
|
||||
)
|
||||
return None
|
||||
|
||||
@@ -110,18 +89,11 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
if str(event.get('event') or '') != 'shipping_ui_state':
|
||||
return None
|
||||
ui_state = event.get('ui_state') if isinstance(event.get('ui_state'), dict) else {}
|
||||
batch_ui_state = event.get('batch_ui_state') if isinstance(event.get('batch_ui_state'), dict) else {}
|
||||
focus_state = (
|
||||
batch_ui_state.get('focus_task_ui_state')
|
||||
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
|
||||
else {}
|
||||
)
|
||||
checkpoint = ui_state.get('checkpoint') or focus_state.get('checkpoint')
|
||||
checkpoint = ui_state.get('checkpoint')
|
||||
return json.dumps({
|
||||
'task_no': event.get('task_no'),
|
||||
'batch_no': event.get('batch_no'),
|
||||
'checkpoint': checkpoint,
|
||||
'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'),
|
||||
'updated_at': ui_state.get('updated_at'),
|
||||
}, ensure_ascii=False, sort_keys=True)
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -28,7 +28,6 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
|
||||
"platform.request_id",
|
||||
"platform.locale",
|
||||
"platform.trigger_source",
|
||||
"refs.batch_no",
|
||||
"refs.task_no",
|
||||
"refs.run_purpose",
|
||||
"refs.capability",
|
||||
@@ -40,7 +39,6 @@ ALLOWED_PARSE_PATHS: frozenset[str] = frozenset(
|
||||
"refs.hxops_turn_id",
|
||||
"domain.type",
|
||||
"domain.summary",
|
||||
"domain.state_hint.batch_no",
|
||||
"domain.state_hint.focus_task_no",
|
||||
"domain.state_hint.schedule_task_id",
|
||||
"domain.state_hint.hxops_turn_id",
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/chat/action_registry.py
|
||||
|
||||
用途:Chat Turn Action Handler 注册与解析。
|
||||
依赖:turn_context.TurnContext、action_schema.TurnEvent、agent_registry.resolver。
|
||||
逻辑:各领域在 chat_action_handlers / maintenance_chat_actions 等模块注册 handler;turn_runtime 调用 resolve。
|
||||
逻辑:各领域在各自 action handler 模块注册 handler;turn_runtime 调用 resolve。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -78,8 +78,6 @@ def resolve_action_handler(ctx: TurnContext) -> ChatActionHandler:
|
||||
|
||||
def ensure_handlers_loaded() -> None:
|
||||
"""延迟导入各领域 handler 模块以完成注册。"""
|
||||
from app.services.shipping_notice import chat_action_handlers as _shipping_handlers # noqa: F401
|
||||
from app.services.shipping_notice import chat_action_extended_handlers as _shipping_extended # noqa: F401
|
||||
|
||||
_ = _shipping_handlers
|
||||
_ = _shipping_extended
|
||||
@@ -73,8 +73,6 @@ def emit_ui_state_updated(*, domain: str, conversation_id: str, payload: dict[st
|
||||
shipping_payload["ui_state"] = payload["ui_state"]
|
||||
if payload.get("task_no"):
|
||||
shipping_payload["task_no"] = payload["task_no"]
|
||||
if payload.get("batch_no"):
|
||||
shipping_payload["batch_no"] = payload["batch_no"]
|
||||
return modern + sse_frame(shipping_payload)
|
||||
|
||||
|
||||
|
||||
@@ -1,57 +0,0 @@
|
||||
"""
|
||||
APX 历史运行时只读清点。
|
||||
|
||||
用途:在正式 20-Gate 单轨切换前,统计数据库中仍处于运行态的 APX Execution/Job。
|
||||
依赖:ShippingProcessExecution、Job ORM 模型。
|
||||
逻辑:仅执行 SELECT,区分运行态与历史终态;调用方据此决定迁移或人工关闭,不在本模块修改数据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import Job, ShippingProcessExecution
|
||||
|
||||
|
||||
_EXECUTION_RUNTIME_STATUSES = ('active', 'blocked', 'waiting_external')
|
||||
_JOB_RUNTIME_STATUSES = ('queued', 'running', 'active')
|
||||
|
||||
|
||||
def audit_apx_runtime_state() -> dict[str, object]:
|
||||
"""只读统计 APX Execution/Job 运行态与历史态数量。
|
||||
|
||||
Returns:
|
||||
包含 execution/job 两组计数。APX Job 通过 execution_no、business_ref 或
|
||||
payload 中的 execution_id 关联;任何写操作都不在此函数执行。
|
||||
"""
|
||||
apx_executions = ShippingProcessExecution.query.filter(
|
||||
ShippingProcessExecution.execution_no.ilike('APX-%')
|
||||
).all()
|
||||
runtime_execution_ids = {
|
||||
int(row.id) for row in apx_executions
|
||||
if str(row.status or '').lower() in _EXECUTION_RUNTIME_STATUSES
|
||||
}
|
||||
apx_jobs = Job.query.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.status.in_(_JOB_RUNTIME_STATUSES),
|
||||
).all()
|
||||
runtime_job_count = 0
|
||||
for job in apx_jobs:
|
||||
if int(job.execution_id or 0) in runtime_execution_ids:
|
||||
runtime_job_count += 1
|
||||
continue
|
||||
if str(job.business_ref or '').upper().find('APX-') >= 0:
|
||||
runtime_job_count += 1
|
||||
continue
|
||||
payload = job.payload_json if isinstance(job.payload_json, dict) else {}
|
||||
if str(payload.get('execution_no') or '').upper().startswith('APX-'):
|
||||
runtime_job_count += 1
|
||||
|
||||
return {
|
||||
'execution': {
|
||||
'active_count': len(runtime_execution_ids),
|
||||
'historical_count': len(apx_executions) - len(runtime_execution_ids),
|
||||
},
|
||||
'job': {
|
||||
'active_count': runtime_job_count,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/attachment_integrity.py
|
||||
|
||||
用途:判定 Intake 的 EML/附件解析是否完整,供建批门禁与重试资格复用。
|
||||
依赖:error_explainability_contract(warning→稳定原因码)、标准库。
|
||||
逻辑:由 batch_from_intakes、intake_service.retry_intake_parse 调用;
|
||||
逻辑:由 intake_service.retry_intake_parse 调用;
|
||||
BLOCKING_WARNING_PREFIXES 与前端 shippingNoticeAttachmentIntegrity.ts 契约一致
|
||||
(由 tests 校验两端前缀集合);可投影 attachment_reason_codes 供审计/UI。
|
||||
"""
|
||||
|
||||
@@ -24,14 +24,6 @@ from app.services.shipping_notice.process_gate_contract import action_belongs_to
|
||||
from app.services.shipping_notice.tool_common import log_task_event
|
||||
|
||||
|
||||
AUTO_PROGRESS_GATE_CODES: tuple[str, ...] = (
|
||||
'inventory_candidates_calculated',
|
||||
'inventory_candidates_frozen',
|
||||
'inventory_snapshots_ready',
|
||||
'inventory_matched',
|
||||
'excel_generated',
|
||||
'upload_receipt_recorded',
|
||||
)
|
||||
_ACTIVE_JOB_STATUSES = ('queued', 'running')
|
||||
_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled', 'canceled'})
|
||||
|
||||
@@ -107,16 +99,6 @@ def _new_execution_no() -> str:
|
||||
return f'APX-{_utc_now().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}'
|
||||
|
||||
|
||||
def _create_execution(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution:
|
||||
"""
|
||||
禁止创建 APX 六 Gate Execution。
|
||||
|
||||
APX 仅保留历史数据兼容;新任务和恢复入口必须通过正式 20-Gate
|
||||
``ensure_execution_for_workflow_version`` 创建 Execution。
|
||||
"""
|
||||
raise RuntimeError('shipping_apx_creation_disabled')
|
||||
|
||||
|
||||
def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool:
|
||||
"""按完整 20-Gate 合同识别正式 Execution;Task-only 正式链同样有效。"""
|
||||
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES
|
||||
@@ -200,8 +182,7 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
|
||||
"""
|
||||
锁定并取得当前唯一活动 Execution。
|
||||
|
||||
核心逻辑:正式 20-Gate 链是唯一运行时状态机;历史 APX 仅可读,
|
||||
不得被重新激活或继续排队。候选版本变化仍按原规则 superseded。
|
||||
核心逻辑:正式 20-Gate 链是唯一运行时状态机;候选版本变化仍按原规则 superseded。
|
||||
"""
|
||||
all_active = (
|
||||
ShippingProcessExecution.query
|
||||
@@ -230,6 +211,10 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
|
||||
formal.updated_at = _utc_now()
|
||||
db.session.flush()
|
||||
return formal
|
||||
if all_active:
|
||||
raise RuntimeError('shipping_process_execution_contract_invalid')
|
||||
if execution is not None and not _is_formal_process_execution(execution):
|
||||
raise RuntimeError('shipping_process_execution_contract_invalid')
|
||||
if execution is not None and int(getattr(execution, 'candidate_set_id', 0) or 0) != int(candidate_set_id or 0):
|
||||
# 旧链永不覆盖:未完成 Gate 取消,Execution 留审计后由新 CandidateSet 建链。
|
||||
execution.status = 'superseded'
|
||||
@@ -238,7 +223,6 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
|
||||
ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')),
|
||||
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
|
||||
execution = None
|
||||
# APX 仅作为历史数据兼容:新任务或无正式链 Task 一律创建正式 20-Gate。
|
||||
if execution is not None:
|
||||
execution.status = 'superseded'
|
||||
execution.updated_at = _utc_now()
|
||||
@@ -286,10 +270,7 @@ def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None
|
||||
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
|
||||
Job.query.filter(
|
||||
Job.domain == 'shipping_notice',
|
||||
Job.job_type.in_((
|
||||
JobType.SHIPPING_AUTO_PROGRESS.value,
|
||||
JobType.SHIPPING_PROCESS_GATE.value,
|
||||
)),
|
||||
Job.job_type == JobType.SHIPPING_PROCESS_GATE.value,
|
||||
Job.task_id == int(task.id),
|
||||
Job.status == 'queued',
|
||||
).update({'status': 'cancelled', 'finished_at': _utc_now(), 'message': '候选版本已重冻结'}, synchronize_session=False)
|
||||
@@ -305,8 +286,7 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi
|
||||
ShippingProcessGate.query.filter_by(execution_id=int(execution.id))
|
||||
.order_by(ShippingProcessGate.sequence_no.asc()).with_for_update().all()
|
||||
)
|
||||
# 正式运行时只接受 20-Gate 合同;AUTO_PROGRESS_GATE_CODES 仅保留给历史
|
||||
# APX 数据读取/迁移测试,不能再作为新任务的状态机校验来源。
|
||||
# 正式运行时只接受 20-Gate 合同。
|
||||
from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES
|
||||
|
||||
expected = list(PROCESS_GATE_CODES)
|
||||
@@ -321,9 +301,9 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi
|
||||
pending_seen = True
|
||||
if gate.status in {'pending', 'blocked_retryable'}:
|
||||
return gate, None
|
||||
# 上传回执是人工完成的外部事实,不是“重试业务动作”。登记成功后仅允许
|
||||
# 服务端重新读取该事实并通过最后一个 Gate。
|
||||
if gate.gate_code == 'upload_receipt_recorded' and gate.status == 'blocked_manual':
|
||||
# 人工上传确认是外部完成声明,不是“重试业务动作”。确认成功后仅允许
|
||||
# 服务端重新读取 Attempt 事实并通过最后一个 Gate。
|
||||
if gate.gate_code == 'manual_upload_handoff' and gate.status == 'blocked_manual':
|
||||
return gate, None
|
||||
return None, None
|
||||
return None, None
|
||||
@@ -385,9 +365,8 @@ def submit_auto_progress(
|
||||
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)
|
||||
if _is_formal_process_execution(execution):
|
||||
# 正式 Case 的 20 Gate Execution 是唯一业务真相;APX 六 Gate 仅兼容
|
||||
# 无 Case 的旧 Task。先同步已落库事实,再把当前技术 Gate 交给唯一
|
||||
# ProcessGate Job/Attempt 通道;不得在此同步执行或退回 APX 六 Gate Job。
|
||||
# 正式 20-Gate Execution 是唯一业务真相;先同步已落库事实,再把当前技术
|
||||
# Gate 交给唯一 ProcessGate Job/Attempt 通道。
|
||||
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
|
||||
from app.services.shipping_notice.process_gate_contract import is_technical_gate_party
|
||||
from app.services.shipping_notice.process_gate_executor import is_navigation_action
|
||||
@@ -496,39 +475,5 @@ def submit_auto_progress(
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return result
|
||||
# 理论上 _active_execution_for_task 已将活动 APX 收敛为正式链;若仍出现
|
||||
# 非正式 Execution,必须 fail-closed,禁止重新创建旧 APX Job。
|
||||
if not _is_formal_process_execution(execution):
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'legacy_readonly',
|
||||
'reason_code': 'shipping_apx_runtime_disabled',
|
||||
'execution_id': int(execution.id),
|
||||
}
|
||||
|
||||
|
||||
def run_auto_progress_job(*, job_id: int, worker_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
将历史 APX AutoProgress Job 终态化,禁止六 Gate 状态机继续运行。
|
||||
|
||||
APX 已下线为只读历史兼容。Worker 仍消费遗留 queued/running Job,
|
||||
但只能取消并保留审计,绝不能触发库存、匹配、Excel 或下一 Gate。
|
||||
"""
|
||||
job = Job.query.filter_by(id=int(job_id)).with_for_update().first()
|
||||
if job is None or job.status != 'running':
|
||||
return {'status': 'noop'}
|
||||
now = _utc_now()
|
||||
gate = ShippingProcessGate.query.filter_by(id=int(job.gate_id or 0)).with_for_update().first()
|
||||
job.status = 'cancelled'
|
||||
job.finished_at = now
|
||||
job.message = 'APX historical auto-progress runtime disabled'
|
||||
if gate is not None and gate.status in {'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual'}:
|
||||
gate.status = 'cancelled'
|
||||
gate.updated_at = now
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'legacy_readonly',
|
||||
'reason_code': 'shipping_apx_runtime_disabled',
|
||||
'execution_id': int(job.execution_id) if job.execution_id else None,
|
||||
}
|
||||
# 运行时只接受正式合同;数据不一致时 fail-closed。
|
||||
raise RuntimeError('shipping_process_execution_contract_invalid')
|
||||
@@ -1,136 +1,22 @@
|
||||
"""
|
||||
services/shipping_notice/batch_create_idempotency.py
|
||||
|
||||
用途:发货通知建单幂等键标准化、跨请求文件内容重复校验(co8 起批次回查已移除)。
|
||||
依赖:models.ShippingNotice、query_service、batch_legacy_removed。
|
||||
逻辑:batch_from_notices 与 task_workflow 共用本模块;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。
|
||||
用途:发货通知跨请求文件内容重复校验。
|
||||
依赖:models.ShippingNotice。
|
||||
逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import re
|
||||
import zlib
|
||||
from typing import Any, Iterable
|
||||
from typing import Iterable
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError
|
||||
from app.models import ShippingNotice
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128
|
||||
_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$")
|
||||
|
||||
|
||||
|
||||
def normalize_create_idempotency_key(raw: str | None) -> str | None:
|
||||
"""
|
||||
标准化建单幂等键:去首尾空格、校验长度与安全字符集。
|
||||
|
||||
Args:
|
||||
raw: HTTP Header / payload 中的原始幂等键。
|
||||
|
||||
Returns:
|
||||
标准化后的幂等键;空值返回 None。
|
||||
|
||||
Raises:
|
||||
ValidationError: 键非空但格式或长度不合法(SHIPPING.IDEMPOTENCY_KEY_INVALID)。
|
||||
"""
|
||||
value = str(raw or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
if len(value) > _CREATE_IDEMPOTENCY_KEY_MAX_LEN:
|
||||
raise AppError(
|
||||
code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
|
||||
message=f"幂等键长度不能超过 {_CREATE_IDEMPOTENCY_KEY_MAX_LEN} 字符",
|
||||
http_status=400,
|
||||
)
|
||||
if not _CREATE_IDEMPOTENCY_KEY_PATTERN.match(value):
|
||||
raise AppError(
|
||||
code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
|
||||
message="幂等键仅允许字母、数字及 . _ : - 字符",
|
||||
http_status=400,
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def warn_missing_create_idempotency_key(*, source: str) -> None:
|
||||
"""兼容期记录缺少建单幂等键的告警,不阻断旧客户端。"""
|
||||
logger.warning(
|
||||
"shipping batch create without create_idempotency_key source=%s",
|
||||
source,
|
||||
)
|
||||
|
||||
|
||||
def compute_notice_items_content_fingerprint(notice_items: list[dict[str, Any]]) -> str:
|
||||
"""
|
||||
根据 notice_items 的 source_content_hash 计算稳定文件集合指纹。
|
||||
|
||||
核心逻辑:排序后拼接哈希再 SHA-256,与批次 process_summary_json.create_content_fingerprint 对齐。
|
||||
"""
|
||||
hashes: list[str] = []
|
||||
for item in notice_items:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
source_hash = str(item.get("source_content_hash") or "").strip().lower()
|
||||
if not source_hash:
|
||||
continue
|
||||
candidate_id = str(item.get("source_candidate_id") or "").strip()
|
||||
if candidate_id:
|
||||
hashes.append(
|
||||
"|".join(
|
||||
[
|
||||
candidate_id,
|
||||
source_hash,
|
||||
str(item.get("business_fingerprint") or "").strip().lower(),
|
||||
str(item.get("content_fingerprint") or "").strip().lower(),
|
||||
]
|
||||
)
|
||||
)
|
||||
else:
|
||||
# 旧单文件/直接上传路径保持纯文件哈希,兼容历史批次回放。
|
||||
hashes.append(source_hash)
|
||||
hashes = sorted(set(hashes))
|
||||
if not hashes:
|
||||
return ""
|
||||
return hashlib.sha256("|".join(hashes).encode("utf-8")).hexdigest().lower()
|
||||
|
||||
|
||||
def batch_stored_content_fingerprint(batch: Any) -> str | None:
|
||||
"""shipping_batches 已删除;保留签名供过渡调用方,固定返回 None。"""
|
||||
del batch
|
||||
return None
|
||||
|
||||
|
||||
def assert_idempotent_batch_content_matches(
|
||||
batch: Any,
|
||||
notice_items: list[dict[str, Any]],
|
||||
) -> None:
|
||||
"""shipping_batches 已删除;幂等批次内容校验不再适用。"""
|
||||
del batch, notice_items
|
||||
|
||||
|
||||
def find_batch_by_create_idempotency(user_id: int, create_idempotency_key: str) -> None:
|
||||
"""
|
||||
按用户与建单幂等键查找已有批次。
|
||||
|
||||
Returns:
|
||||
固定 None(shipping_batches 已删除)。
|
||||
"""
|
||||
del user_id, create_idempotency_key
|
||||
return None
|
||||
|
||||
|
||||
def build_existing_batch_tool_response(batch: Any, *, user_id: int) -> dict[str, Any]:
|
||||
"""shipping_batches 已删除;禁止构建批次重放响应。"""
|
||||
del batch, user_id
|
||||
raise_shipping_batches_removed()
|
||||
|
||||
|
||||
def _advisory_lock_key(*parts: str) -> int:
|
||||
@@ -161,7 +47,6 @@ def assert_no_exact_duplicate_notices(
|
||||
user_id: int,
|
||||
notice_items: list[dict[str, Any]],
|
||||
*,
|
||||
exclude_batch_id: int | None = None,
|
||||
exclude_task_ids: Iterable[int] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
@@ -175,7 +60,6 @@ def assert_no_exact_duplicate_notices(
|
||||
Args:
|
||||
user_id: 建单用户。
|
||||
notice_items: 含 source_content_hash / duplicate_resolution_type 的通知项。
|
||||
exclude_batch_id: 可选;忽略同批次内任务。
|
||||
exclude_task_ids: 可选;忽略这些已存在 Task(同 Case 既有波次)。
|
||||
|
||||
Raises:
|
||||
@@ -234,28 +118,25 @@ def dedupe_notice_items_by_content_hash(notice_items: list[dict[str, Any]]) -> l
|
||||
return unique
|
||||
|
||||
|
||||
def handle_batch_create_integrity_error(
|
||||
*,
|
||||
user_id: int,
|
||||
create_idempotency_key: str | None,
|
||||
exc: IntegrityError,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
捕获批次建单唯一约束竞争,回滚后回查已有批次。
|
||||
_CREATE_IDEMPOTENCY_KEY_MAX_LEN = 128
|
||||
_CREATE_IDEMPOTENCY_KEY_PATTERN = re.compile(r"^[A-Za-z0-9._:-]+$")
|
||||
|
||||
Returns:
|
||||
幂等重放响应;无法回查时返回 None,由上层继续抛出原异常。
|
||||
"""
|
||||
db.session.rollback()
|
||||
key = str(create_idempotency_key or "").strip()
|
||||
if not key:
|
||||
|
||||
def normalize_create_idempotency_key(raw: str | None) -> str | None:
|
||||
"""标准化 Review Case 确认幂等键,防止同一确认请求重复创建任务。"""
|
||||
value = str(raw or "").strip()
|
||||
if not value:
|
||||
return None
|
||||
batch = find_batch_by_create_idempotency(user_id, key)
|
||||
if not batch:
|
||||
return None
|
||||
logger.info(
|
||||
"shipping batch create idempotency race resolved batch_no=%s user_id=%s",
|
||||
batch.batch_no,
|
||||
user_id,
|
||||
)
|
||||
return build_existing_batch_tool_response(batch, user_id=user_id)
|
||||
if len(value) > _CREATE_IDEMPOTENCY_KEY_MAX_LEN:
|
||||
raise AppError(
|
||||
code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
|
||||
message=f"幂等键长度不能超过 {_CREATE_IDEMPOTENCY_KEY_MAX_LEN} 字符",
|
||||
http_status=400,
|
||||
)
|
||||
if not _CREATE_IDEMPOTENCY_KEY_PATTERN.match(value):
|
||||
raise AppError(
|
||||
code="SHIPPING.IDEMPOTENCY_KEY_INVALID",
|
||||
message="幂等键仅允许字母、数字及 . _ : - 字符",
|
||||
http_status=400,
|
||||
)
|
||||
return value
|
||||
@@ -1,50 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/batch_from_intakes.py
|
||||
|
||||
用途:从已解析 ShippingOrderIntake 确认建批的共享编排(co8 起 shipping_batches 已删除,入口阻断)。
|
||||
依赖:batch_legacy_removed。
|
||||
逻辑:workspace API 与 chat action shipping.create_batch_from_intakes 共用本模块;
|
||||
create_shipping_batch_from_intakes / create_shipping_batch_from_candidates 在入口抛出 ValidationError。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
|
||||
def create_shipping_batch_from_candidates(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str | None,
|
||||
intake_nos: list[str],
|
||||
candidate_nos: list[str],
|
||||
create_idempotency_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
根据选定 Candidate 创建批次。
|
||||
|
||||
Raises:
|
||||
ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。
|
||||
"""
|
||||
del user_id, conversation_id, intake_nos, candidate_nos, create_idempotency_key
|
||||
raise_shipping_batches_removed()
|
||||
|
||||
|
||||
def create_shipping_batch_from_intakes(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str | None,
|
||||
intake_nos: list[str],
|
||||
candidate_nos: list[str] | None = None,
|
||||
create_idempotency_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
根据已解析且未消费的 intake 列表创建批次。
|
||||
|
||||
Raises:
|
||||
ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。
|
||||
"""
|
||||
del user_id, conversation_id, intake_nos, candidate_nos, create_idempotency_key
|
||||
raise_shipping_batches_removed()
|
||||
@@ -1,142 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/batch_from_notices.py
|
||||
|
||||
用途:从发货通知附件创建批次的共享编排(workspace API 与 Chat Turn handler 共用)。
|
||||
依赖:shipping_tools、notice_upload、batch_orchestrator、batch_create_idempotency、query_service。
|
||||
逻辑:workspace/shipping_notice 与 chat_action_handlers 均调用本模块,避免建批逻辑双份维护。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.batch_create_idempotency import (
|
||||
assert_idempotent_batch_content_matches,
|
||||
build_existing_batch_tool_response,
|
||||
dedupe_notice_items_by_content_hash,
|
||||
find_batch_by_create_idempotency,
|
||||
handle_batch_create_integrity_error,
|
||||
normalize_create_idempotency_key,
|
||||
warn_missing_create_idempotency_key,
|
||||
)
|
||||
from app.services.shipping_notice.notice_upload import build_notice_file_summary
|
||||
from app.services.shipping_notice.query_service import get_focus_task_for_batch, serialize_task_summary
|
||||
|
||||
|
||||
def create_shipping_batch_from_notice_items(
|
||||
*,
|
||||
user_id: int,
|
||||
conversation_id: str | None,
|
||||
notice_items: list[dict[str, Any]],
|
||||
file_summary: dict[str, Any] | None = None,
|
||||
create_idempotency_key: str | None = None,
|
||||
defer_commit: bool = False,
|
||||
start_orchestrator: bool | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
根据已抽取的发货通知条目创建批次并可选启动编排器。
|
||||
|
||||
核心逻辑:优先按建单幂等键回查已有批次;新建时写入 create_idempotency_key 并捕获唯一约束竞争。
|
||||
intake 路径应传 defer_commit=True,避免批次先提交导致上层 ingested 关联/审计断点。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户 ID。
|
||||
conversation_id: 可选 Agent 会话 ID。
|
||||
notice_items: notice_upload 产出的 notice item 列表。
|
||||
file_summary: 可选文件预检摘要,写入响应供前端展示。
|
||||
create_idempotency_key: 建单幂等键(与 ShippingNotice.idempotency_key 货代上传幂等分离)。
|
||||
defer_commit: True 时下层仅 flush,由调用方最终 commit。
|
||||
start_orchestrator: 是否启动编排器;默认与 defer_commit 相反(延后提交时不启动)。
|
||||
|
||||
Returns:
|
||||
与 workspace create-from-notices 一致的结果字典,幂等重放时含 idempotent_replay=true。
|
||||
|
||||
Raises:
|
||||
ValidationError: notice_items 为空,或 shipping_batches 已删除(co8)。
|
||||
"""
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed()
|
||||
|
||||
|
||||
def format_batch_created_assistant_message(
|
||||
result: dict[str, Any],
|
||||
*,
|
||||
file_count: int = 0,
|
||||
) -> str:
|
||||
"""
|
||||
格式化建批成功后写入 Chat Turn assistant 气泡的文案。
|
||||
|
||||
核心逻辑:对齐前端 useChatShippingUploadHandler 原有本地 push 文案结构;幂等重放时提示已恢复批次。
|
||||
"""
|
||||
if bool(result.get("idempotent_replay")):
|
||||
batch_no = str(result.get("batch_no") or "").strip()
|
||||
return f"已恢复此前创建的批次。\n批次编号:{batch_no}" if batch_no else "已恢复此前创建的批次。"
|
||||
|
||||
data = result.get("data") if isinstance(result.get("data"), dict) else {}
|
||||
batch = data.get("batch") if isinstance(data.get("batch"), dict) else {}
|
||||
tasks = data.get("tasks") if isinstance(data.get("tasks"), list) else []
|
||||
focus_task = tasks[0] if tasks and isinstance(tasks[0], dict) else {}
|
||||
task_id = str(
|
||||
(data.get("focus_task") or {}).get("task_no")
|
||||
if isinstance(data.get("focus_task"), dict)
|
||||
else ""
|
||||
).strip() or str(result.get("task_id") or focus_task.get("task_id") or "").strip()
|
||||
batch_no = str(result.get("batch_no") or batch.get("batch_no") or "").strip()
|
||||
focus_progress = ""
|
||||
if focus_task.get("batch_index") and focus_task.get("batch_total"):
|
||||
focus_progress = f"当前第 {focus_task['batch_index']}/{focus_task['batch_total']} 票"
|
||||
count = int(file_count or batch.get("file_count") or len(tasks) or 0)
|
||||
hint = str(result.get("message") or "").strip()
|
||||
status = str(result.get("status") or "").strip()
|
||||
orchestrator_started = bool(data.get("orchestrator_started"))
|
||||
tail = "请根据提示进行确认/驳回。" if status == "needs_human" else ""
|
||||
lines = [
|
||||
hint or f"已处理 {count} 份发货通知附件",
|
||||
f"批次编号:{batch_no}" if batch_no else "",
|
||||
f"当前任务:{task_id}" if task_id else "",
|
||||
focus_progress,
|
||||
f"后台已开始按票拆分处理,本批 {count} 票会逐步更新状态。" if orchestrator_started else "",
|
||||
tail,
|
||||
]
|
||||
return "\n".join(line for line in lines if line)
|
||||
|
||||
|
||||
def intake_notice_uploads_for_batch(
|
||||
request_id: str,
|
||||
uploads: list,
|
||||
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
"""
|
||||
预检并抽取发货通知附件,返回 notice_items 与 file_summary。
|
||||
|
||||
Args:
|
||||
request_id: 请求级临时目录 ID。
|
||||
uploads: Werkzeug FileStorage 列表。
|
||||
|
||||
Returns:
|
||||
(notice_items, file_summary)
|
||||
"""
|
||||
max_files = max(int(current_app.config.get('SHIPPING_NOTICE_BATCH_MAX_FILES', 20) or 20), 1)
|
||||
if len(uploads) > max_files:
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
raise ValidationError(
|
||||
'批量上传文件数超过限制',
|
||||
code='SHIPPING_NOTICE.BATCH_FILE_LIMIT_EXCEEDED',
|
||||
details={'max_files': max_files, 'received_files': len(uploads)},
|
||||
)
|
||||
from app.services.shipping_notice.notice_upload import intake_temp_notice_uploads
|
||||
|
||||
accepted, rejected, duplicate_files = intake_temp_notice_uploads(request_id, uploads)
|
||||
file_summary = build_notice_file_summary(
|
||||
total_files=len(uploads),
|
||||
accepted=accepted,
|
||||
rejected=rejected,
|
||||
duplicate_files=duplicate_files,
|
||||
)
|
||||
notice_items = [item.to_notice_item() for item in accepted]
|
||||
return notice_items, file_summary
|
||||
@@ -1,40 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/batch_legacy_removed.py
|
||||
|
||||
用途:shipping_batches 表物理删除(co8e9f0a1b2c)后的统一阻断与文案常量。
|
||||
依赖:app.core.errors.AppError。
|
||||
逻辑:create_batch / batch_from_* 等写路径在入口调用 raise_shipping_batches_removed(HTTP 410);
|
||||
读路径 list API 返回空集,按 batch_no 查询返回 None。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.core.errors import AppError
|
||||
|
||||
SHIPPING_BATCHES_REMOVED_MESSAGE = (
|
||||
"shipping_batches removed (migration co8e9f0a1b2c)"
|
||||
)
|
||||
|
||||
|
||||
def raise_shipping_batches_removed(*, action: str | None = None) -> None:
|
||||
"""
|
||||
阻断仍依赖 shipping_batches 表的写路径。
|
||||
|
||||
核心逻辑:ORM 已移除 ShippingBatch;调用方须在入口尽早抛出,避免 SQLAlchemy 访问已 DROP 表。
|
||||
|
||||
Args:
|
||||
action: 可选调用方动作名,写入 error.details 便于排查。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410,code=SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
details = {'migration': 'co8e9f0a1b2c', 'replacement': 'order-extraction-submissions'}
|
||||
if action:
|
||||
details['action'] = str(action)
|
||||
raise AppError(
|
||||
code='SHIPPING.BATCHES_REMOVED',
|
||||
message=SHIPPING_BATCHES_REMOVED_MESSAGE,
|
||||
http_status=410,
|
||||
details=details,
|
||||
retryable=False,
|
||||
)
|
||||
@@ -1,34 +1,29 @@
|
||||
"""
|
||||
services/shipping_notice/batch_orchestrator.py
|
||||
|
||||
用途:发货通知批次/单票后台编排器。
|
||||
依赖:query_service、task_workflow、shipping_notice.tools、tool_common。
|
||||
逻辑:批次线程只推进已由订单抽取 Run 建立的正式 Task;无抽取的 created 旧壳任务安全停止;
|
||||
用途:发货通知单票后台编排器。
|
||||
依赖:query_service、shipping_notice.tools、tool_common。
|
||||
逻辑:持久化队列只推进已由订单抽取 Run 建立的正式 Task;无抽取的 created 旧壳任务安全停止;
|
||||
复核/STP 确认后已挂 current_order_extraction_id 的 created 任务走 auto_progress。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.constants import PH_RPA_PENDING
|
||||
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref, list_sorted_batch_tasks
|
||||
from app.services.shipping_notice.task_workflow import recompute_batch_summary
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
auto_progress_enabled,
|
||||
cfg_bool,
|
||||
cfg_int,
|
||||
log_task_event,
|
||||
switch_batch_focus,
|
||||
)
|
||||
from app.services.shipping_notice.tools import auto_progress, submit_decision
|
||||
from app.services.shipping_notice.tools import auto_progress
|
||||
|
||||
_RUNNING_BATCHES: set[str] = set()
|
||||
_RUNNING_TASKS: set[str] = set()
|
||||
|
||||
|
||||
@@ -37,11 +32,6 @@ def batch_orchestrator_enabled() -> bool:
|
||||
return cfg_bool("SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED", True)
|
||||
|
||||
|
||||
def batch_dispatch_concurrency() -> int:
|
||||
"""单个批次最多并发派发多少张票。"""
|
||||
return cfg_int("SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY", 3, min_value=1)
|
||||
|
||||
|
||||
def _normalize_ref(value: str | None) -> str:
|
||||
return str(value or "").strip().upper()
|
||||
|
||||
@@ -85,29 +75,6 @@ def _should_orchestrate_task(task: Any) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _is_retryable_task(task: Any) -> bool:
|
||||
"""判断任务是否允许由批次重试入口重新派发。"""
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
|
||||
if not task_is_active(task):
|
||||
return False
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}:
|
||||
return False
|
||||
if getattr(task, "review_status", None):
|
||||
return False
|
||||
if pending_reason in {PH_RPA_PENDING, PH_RPA_EXHAUSTED}:
|
||||
return True
|
||||
if getattr(task, "pending_human_reason", None):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _refresh_batch_focus(task_no: str) -> None:
|
||||
"""shipping_batches 已删除;批次焦点刷新无操作。"""
|
||||
del task_no
|
||||
|
||||
|
||||
def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
"""
|
||||
后台执行单票任务的一轮推进。
|
||||
@@ -141,9 +108,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
),
|
||||
}
|
||||
|
||||
_refresh_batch_focus(task.task_no)
|
||||
task = get_task_by_ref(normalized_task_no)
|
||||
assert task is not None
|
||||
log_task_event(
|
||||
task,
|
||||
"backend_orchestrator_task_started",
|
||||
@@ -235,70 +199,6 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
_unmark_running(_RUNNING_TASKS, normalized_task_no)
|
||||
|
||||
|
||||
def _background_task_runner(app: Any, task_no: str) -> None:
|
||||
try:
|
||||
with app.app_context():
|
||||
_run_single_task(task_no)
|
||||
finally:
|
||||
_unmark_running(_RUNNING_BATCHES, f"TASK::{task_no}")
|
||||
|
||||
|
||||
def _background_batch_runner(app: Any, batch_no: str) -> None:
|
||||
normalized_batch_no = _normalize_ref(batch_no)
|
||||
try:
|
||||
with app.app_context():
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
if not batch:
|
||||
return
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
|
||||
task_nos = [task.task_no for task in list_sorted_batch_tasks(batch)]
|
||||
if not task_nos:
|
||||
return
|
||||
|
||||
max_workers = min(batch_dispatch_concurrency(), len(task_nos))
|
||||
if max_workers <= 1:
|
||||
for task_no in task_nos:
|
||||
_refresh_batch_focus(task_no)
|
||||
_run_single_task(task_no)
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
if not batch:
|
||||
break
|
||||
else:
|
||||
app_obj = current_app._get_current_object()
|
||||
with ThreadPoolExecutor(
|
||||
max_workers=max_workers,
|
||||
thread_name_prefix=f"shipping-batch-{normalized_batch_no}",
|
||||
) as executor:
|
||||
future_map = {
|
||||
executor.submit(_run_task_with_app_context, app_obj, task_no): task_no
|
||||
for task_no in task_nos
|
||||
}
|
||||
for future in as_completed(future_map):
|
||||
task_no = future_map[future]
|
||||
try:
|
||||
future.result()
|
||||
except Exception as exc:
|
||||
task = get_task_by_ref(task_no)
|
||||
if task:
|
||||
task.error_message = str(exc)
|
||||
log_task_event(
|
||||
task,
|
||||
"backend_orchestrator_task_failed",
|
||||
{"error": str(exc)[:1000], "source": "batch_dispatcher"},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
if batch:
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
finally:
|
||||
db.session.remove()
|
||||
_unmark_running(_RUNNING_BATCHES, normalized_batch_no)
|
||||
|
||||
|
||||
def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
"""将单票后台任务写入持久化队列。"""
|
||||
normalized_task_no = _normalize_ref(task_no)
|
||||
@@ -308,80 +208,3 @@ def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
return ok and result in {"queued_for_worker", "already_queued", "done", "ok", "running", "needs_human", "skipped"}
|
||||
|
||||
|
||||
def start_batch_orchestrator(batch_no: str | None) -> bool:
|
||||
"""批次入口改为逐票入队,由 worker 消费,不再在 web 进程内起长线程。"""
|
||||
normalized_batch_no = _normalize_ref(batch_no)
|
||||
if not normalized_batch_no or not batch_orchestrator_enabled():
|
||||
return False
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
if not batch:
|
||||
return False
|
||||
|
||||
started = False
|
||||
for task in list_sorted_batch_tasks(batch):
|
||||
ok, _result = enqueue_shipping_notice_job(
|
||||
task_no=task.task_no,
|
||||
created_by_id=getattr(batch, "user_id", None),
|
||||
batch_no=batch.batch_no,
|
||||
)
|
||||
started = started or ok
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
return started
|
||||
|
||||
|
||||
def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
|
||||
"""重试批次中可恢复的任务;RPA 耗尽态会手动开启新一轮库存导出。"""
|
||||
normalized_batch_no = _normalize_ref(batch_no)
|
||||
if not normalized_batch_no:
|
||||
return {"status": "failed", "message": "batch_no is required"}
|
||||
batch = get_batch_by_no(normalized_batch_no)
|
||||
if not batch:
|
||||
return {"status": "failed", "message": "batch not found"}
|
||||
|
||||
started = 0
|
||||
skipped = 0
|
||||
for task in list_sorted_batch_tasks(batch):
|
||||
if not _is_retryable_task(task):
|
||||
skipped += 1
|
||||
continue
|
||||
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
|
||||
if pending_reason == PH_RPA_PENDING and not getattr(task, "inventory_lines_json", None):
|
||||
# 轮询既有请求仍只提交正式库存准备 Gate,由 Executor 读取 Attempt 状态。
|
||||
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
|
||||
|
||||
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
|
||||
status = str(result.get("status") or "").strip().lower()
|
||||
if status in {"ok", "running", "needs_human"}:
|
||||
started += 1
|
||||
else:
|
||||
skipped += 1
|
||||
continue
|
||||
if pending_reason == PH_RPA_EXHAUSTED:
|
||||
result = submit_decision({"task_id": task.task_no, "decision": "retry_rpa"})
|
||||
status = str(result.get("status") or "").strip().lower()
|
||||
if status in {"ok", "running", "needs_human"}:
|
||||
started += 1
|
||||
else:
|
||||
skipped += 1
|
||||
continue
|
||||
if start_task_orchestrator(task.task_no):
|
||||
started += 1
|
||||
else:
|
||||
skipped += 1
|
||||
|
||||
recompute_batch_summary(batch)
|
||||
db.session.commit()
|
||||
return {
|
||||
"status": "ok",
|
||||
"batch_no": batch.batch_no,
|
||||
"started": started,
|
||||
"skipped": skipped,
|
||||
"message": f"已为批次 {batch.batch_no} 重试 {started} 个任务,跳过 {skipped} 个任务。",
|
||||
}
|
||||
|
||||
|
||||
def _run_task_with_app_context(app: Any, task_no: str) -> dict[str, str | None]:
|
||||
"""批次派发时为单票补充独立 app/db 上下文,避免批次线程串行阻塞。"""
|
||||
with app.app_context():
|
||||
return _run_single_task(task_no)
|
||||
@@ -1,88 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/business_case_service.py
|
||||
|
||||
用途:为新建货代任务创建或继承业务单聚合。
|
||||
依赖:db、ShippingCase、ShippingNotice、uuid/datetime。
|
||||
逻辑:普通任务和强制新建任务创建新业务单;修订任务继承父任务业务单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingCase, ShippingNotice
|
||||
|
||||
|
||||
def generate_shipping_case_no() -> str:
|
||||
"""生成内部业务单聚合编号;仅用于系统关联,不对外替代 business_no。"""
|
||||
return f"SC-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def create_shipping_case(*, created_by_id: int | None = None) -> ShippingCase:
|
||||
"""
|
||||
创建未绑定客户、未编号的业务单聚合。
|
||||
|
||||
Args:
|
||||
created_by_id: 创建任务的用户 ID,可为空。
|
||||
Returns:
|
||||
尚未提交事务的 ShippingCase。
|
||||
"""
|
||||
case = ShippingCase(
|
||||
case_no=generate_shipping_case_no(),
|
||||
created_by_id=created_by_id,
|
||||
numbering_status='pending',
|
||||
status='open',
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
return case
|
||||
|
||||
|
||||
def resolve_shipping_case_for_new_task(
|
||||
*,
|
||||
supersedes_task_id: int | None = None,
|
||||
duplicate_resolution_type: str | None = None,
|
||||
created_by_id: int | None = None,
|
||||
) -> ShippingCase:
|
||||
"""
|
||||
为即将创建的任务解析业务单归属。
|
||||
|
||||
核心逻辑:revision 必须继承父任务业务单;normal/force_create 均创建独立业务单,
|
||||
保证强制新建重新占用未来流水。
|
||||
|
||||
Args:
|
||||
supersedes_task_id: 修订目标任务主键,仅 revision 使用。
|
||||
duplicate_resolution_type: normal/revision/force_create。
|
||||
created_by_id: 新任务创建人。
|
||||
Returns:
|
||||
新任务应关联的 ShippingCase。
|
||||
Raises:
|
||||
ConflictError: revision 缺少或找不到父任务。
|
||||
"""
|
||||
resolution_type = str(duplicate_resolution_type or 'normal').strip().lower()
|
||||
if resolution_type != 'revision':
|
||||
return create_shipping_case(created_by_id=created_by_id)
|
||||
|
||||
if not supersedes_task_id:
|
||||
raise ConflictError(
|
||||
'修订任务缺少父任务',
|
||||
code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
|
||||
)
|
||||
parent = db.session.get(ShippingNotice, int(supersedes_task_id))
|
||||
if parent is None:
|
||||
raise ConflictError(
|
||||
'修订目标任务不存在',
|
||||
code='SHIPPING_NOTICE.REVISION_TARGET_INVALID',
|
||||
details={'supersedes_task_id': supersedes_task_id},
|
||||
)
|
||||
if parent.shipping_case is None:
|
||||
raise ConflictError(
|
||||
'修订目标任务缺少业务单关联',
|
||||
code='SHIPPING_NOTICE.REVISION_CASE_MISSING',
|
||||
details={'supersedes_task_id': supersedes_task_id},
|
||||
)
|
||||
return parent.shipping_case
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/business_numbering_service.py
|
||||
|
||||
用途:为已确认客户的货代业务单分配不可变业务编号。
|
||||
依赖:ShippingCase/Customer/BusinessSequence、Asia/Shanghai 时区、SQLAlchemy 方言能力。
|
||||
依赖:ShippingNotice/Customer/BusinessSequence、Asia/Shanghai 时区、SQLAlchemy 方言能力。
|
||||
逻辑:锁定业务单后按客户与上海业务日期原子递增流水;编号写入业务单快照,事务由调用方提交。
|
||||
"""
|
||||
|
||||
@@ -15,7 +15,7 @@ from sqlalchemy import update
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingBusinessSequence, ShippingCase, ShippingCustomer
|
||||
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice
|
||||
from app.services.shipping_notice.customer_normalization import SHORT_CODE_RE
|
||||
|
||||
BUSINESS_TYPE = "shipping_notice"
|
||||
@@ -121,50 +121,46 @@ def _next_sequence_value(customer_id: int, business_date: date) -> int:
|
||||
return int(value)
|
||||
|
||||
|
||||
def assign_business_number(case: ShippingCase, *, moment: datetime | None = None) -> str:
|
||||
def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime | None = None) -> str:
|
||||
"""
|
||||
为业务单幂等分配业务编号,调用方负责同事务提交。
|
||||
|
||||
核心逻辑:已有编号直接返回;否则校验启用客户与简码快照,取得上海日期流水并写入不可变编号字段。
|
||||
为单个发货通知分配不可变业务编号;同一 PO 的不同通知单不会复用编号。
|
||||
|
||||
Args:
|
||||
case: 已加锁且已绑定标准客户的业务单。
|
||||
moment: 可选测试时刻。
|
||||
Returns:
|
||||
分配或已存在的业务编号。
|
||||
Raises:
|
||||
ConflictError: 客户无效、简码缺失或当日两位流水耗尽。
|
||||
"""
|
||||
if case.business_no:
|
||||
return str(case.business_no)
|
||||
if case.customer_id is None:
|
||||
raise ConflictError(
|
||||
"Shipping case customer must be confirmed before numbering",
|
||||
code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED",
|
||||
)
|
||||
customer = db.session.get(ShippingCustomer, int(case.customer_id))
|
||||
if customer is None or customer.status != "active":
|
||||
raise ConflictError(
|
||||
"Active customer is required before numbering",
|
||||
code="SHIPPING.BUSINESS_NUMBER_CUSTOMER_INVALID",
|
||||
)
|
||||
notice: 已绑定客户的 ShippingNotice;客户事实只读取 Notice 本身。
|
||||
moment: 可选时刻,测试时用于固定上海业务日期。
|
||||
|
||||
short_code = str(customer.short_code or "").strip().upper()
|
||||
Returns:
|
||||
分配或已存在的 business_no。
|
||||
|
||||
Raises:
|
||||
ConflictError: 通知单缺少客户或客户无效。
|
||||
"""
|
||||
if notice.business_no:
|
||||
return str(notice.business_no)
|
||||
if notice.customer_id is None:
|
||||
raise ConflictError(
|
||||
'Shipping notice customer must be confirmed before numbering',
|
||||
code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED',
|
||||
)
|
||||
customer = db.session.get(ShippingCustomer, int(notice.customer_id))
|
||||
if customer is None or customer.status != 'active':
|
||||
raise ConflictError(
|
||||
'Active customer is required before numbering',
|
||||
code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_INVALID',
|
||||
)
|
||||
short_code = str(customer.short_code or '').strip().upper()
|
||||
if not SHORT_CODE_RE.fullmatch(short_code):
|
||||
raise ConflictError(
|
||||
"Customer short code is invalid for business numbering",
|
||||
code="SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID",
|
||||
details={"customer_id": customer.id, "short_code": short_code},
|
||||
'Customer short code is invalid for business numbering',
|
||||
code='SHIPPING.BUSINESS_NUMBER_SHORT_CODE_INVALID',
|
||||
)
|
||||
business_date = shanghai_business_date(moment)
|
||||
sequence_value = _next_sequence_value(customer.id, business_date)
|
||||
business_no = format_business_no(short_code, business_date, sequence_value)
|
||||
case.customer_name_snapshot = customer.standard_name
|
||||
case.customer_short_code_snapshot = short_code
|
||||
case.business_date = business_date
|
||||
case.sequence_value = sequence_value
|
||||
case.numbering_rule_version = NUMBERING_RULE_VERSION
|
||||
case.numbering_status = "assigned"
|
||||
case.business_no = business_no
|
||||
notice.business_no = format_business_no(short_code, business_date, sequence_value)
|
||||
notice.business_date = business_date
|
||||
notice.business_sequence_value = sequence_value
|
||||
notice.business_numbering_rule_version = NUMBERING_RULE_VERSION
|
||||
notice.customer_name_snapshot = customer.standard_name
|
||||
notice.customer_short_code_snapshot = short_code
|
||||
db.session.flush()
|
||||
return business_no
|
||||
return str(notice.business_no)
|
||||
@@ -25,8 +25,6 @@ CANDIDATE_QUALIFICATION_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v3.0-unified-profile'
|
||||
|
||||
# 统一检查顺序(不可重排):后置项依赖前置放行语义由服务层解释。
|
||||
# VC 门禁 vc_source_merged_clean 放在 field_conflicts_resolved 之后,
|
||||
# 以便冲突项先被 PDF 优先裁决,剩余 needs_review 项再由本门禁拦截。
|
||||
CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
|
||||
'auto_create_enabled',
|
||||
'route_stp_eligible',
|
||||
@@ -35,7 +33,6 @@ CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
|
||||
'key_fields_minimum_confidence',
|
||||
'evidence_complete',
|
||||
'field_conflicts_resolved',
|
||||
'vc_source_merged_clean',
|
||||
'duplicate_resolved',
|
||||
'customer_confirmed',
|
||||
'idempotency_ok',
|
||||
@@ -50,7 +47,6 @@ CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = {
|
||||
'key_fields_minimum_confidence': 'field_low_confidence',
|
||||
'evidence_complete': 'evidence_missing',
|
||||
'field_conflicts_resolved': 'field_conflict',
|
||||
'vc_source_merged_clean': 'vc_source_conflict_unresolved',
|
||||
'duplicate_resolved': 'duplicate_unresolved',
|
||||
'customer_confirmed': 'customer_confirmation_required',
|
||||
'idempotency_ok': 'task_already_exists',
|
||||
@@ -67,8 +63,6 @@ CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES: Final[frozenset[str]] = frozenset({
|
||||
'field_low_confidence',
|
||||
# PDF 优先已选定当前值,但仍须人工确认冲突后方可自动建单。
|
||||
'pdf_preferred_critical_conflict',
|
||||
# Vendor Comments 三来源值不一致,须人工裁决但不硬阻塞人工建单。
|
||||
'vc_source_conflict_unresolved',
|
||||
})
|
||||
|
||||
# 解析来源(写入 parser_trace,不直接决定资格)。
|
||||
|
||||
@@ -26,6 +26,7 @@ from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderCandidateQualification,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderCustomerMatch,
|
||||
)
|
||||
from app.services.shipping_notice.candidate_qualification_contract import (
|
||||
@@ -34,11 +35,6 @@ from app.services.shipping_notice.candidate_qualification_contract import (
|
||||
CANDIDATE_QUALIFICATION_GATE_REASON_CODES,
|
||||
CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import (
|
||||
CQ_VC_BLOCKING_REASONS,
|
||||
CQ_VC_REVIEW_REASONS,
|
||||
collect_vc_candidate_conflicts,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
from app.services.shipping_notice.tool_common import extraction_emergency_stop_enabled
|
||||
|
||||
@@ -75,6 +71,47 @@ _CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85'
|
||||
# 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。
|
||||
# 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。
|
||||
_NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'})
|
||||
_OPTIONAL_INTERNAL_FIELD_CODES = frozenset({'line_no'})
|
||||
_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'})
|
||||
|
||||
|
||||
def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) -> bool:
|
||||
"""按冻结字段配置判断证据缺失是否只是可选字段诊断。
|
||||
|
||||
核心逻辑:优先读取 Candidate 关联 Extraction 的冻结 Schema;只有
|
||||
``required`` 或 ``auto_create_key_field`` 才能阻断。历史 Candidate 无法
|
||||
追溯 Schema 时,仅兼容已明确属于内部可派生字段的 ``line_no``,其余未知
|
||||
字段继续 fail-closed。
|
||||
"""
|
||||
reason = str(item.get('reason') or item.get('code') or '').strip()
|
||||
if reason not in _EVIDENCE_GAP_REASONS:
|
||||
return False
|
||||
field_code = str(item.get('field') or item.get('field_code') or '').strip()
|
||||
if not field_code:
|
||||
return False
|
||||
|
||||
config = item.get('field_config') if isinstance(item.get('field_config'), dict) else None
|
||||
extraction_id = getattr(candidate, 'order_extraction_id', None)
|
||||
if config is None and extraction_id is not None:
|
||||
try:
|
||||
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id))
|
||||
definition = (
|
||||
extraction.schema_version.definition_json
|
||||
if extraction is not None and extraction.schema_version is not None
|
||||
else {}
|
||||
)
|
||||
config = next(
|
||||
(
|
||||
raw for raw in (definition.get('fields') or [])
|
||||
if isinstance(raw, dict) and str(raw.get('field_code') or '').strip() == field_code
|
||||
),
|
||||
None,
|
||||
)
|
||||
except Exception: # noqa: BLE001 - 门禁读取配置失败时继续保守阻断
|
||||
config = None
|
||||
if config is not None:
|
||||
return not bool(config.get('required')) and not bool(config.get('auto_create_key_field'))
|
||||
return field_code in _OPTIONAL_INTERNAL_FIELD_CODES
|
||||
|
||||
|
||||
def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
|
||||
@@ -84,10 +121,6 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
|
||||
核心逻辑:过滤仅描述文档版面/坐标质量的诊断项;字段值冲突、跨来源冲突
|
||||
与其他未知阻断项继续 fail-closed。
|
||||
|
||||
注意:Vendor Comments 三来源冲突由独立 vc_source_merged_clean 门禁
|
||||
(见 _vc_gate_ok)评估,不入本集合,避免污染 field_conflicts_resolved
|
||||
原有零回归语义。
|
||||
|
||||
Args:
|
||||
candidate: ShippingOrderCandidate 或兼容替身。
|
||||
|
||||
@@ -97,76 +130,39 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
|
||||
conflicts = getattr(candidate, 'conflicts_json', None)
|
||||
if not isinstance(conflicts, list):
|
||||
return [] if not conflicts else [conflicts]
|
||||
return [
|
||||
item for item in conflicts
|
||||
if not (
|
||||
isinstance(item, dict)
|
||||
and str(item.get('reason') or item.get('code') or '').strip()
|
||||
in _NON_BLOCKING_CONFLICT_REASONS
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# VC 三来源门禁:独立于 Candidate.conflicts_json,从 structured.extraction
|
||||
# vendor_comments_merged 读,避免冲突历史与裁决历史相互污染。
|
||||
# ---------------------------------------------------------------------------
|
||||
def _vc_gate_ok(candidate: Any) -> bool:
|
||||
"""
|
||||
VC 三来源合并结果是否全部清洁(无阻断冲突)。
|
||||
|
||||
核心逻辑:缺 VC merged 载荷 → 视为未启用 → OK;
|
||||
severity == blocking 的项 → 必须视为 fail(硬阻断);
|
||||
severity == review_required 但 can_auto_create 场景下同样 fail,
|
||||
交由上层 CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES 归类到
|
||||
review_required 总体状态(允许人工建单,不允许 STP 自动建单)。
|
||||
|
||||
Args:
|
||||
candidate: ShippingOrderCandidate 或兼容替身。
|
||||
|
||||
Returns:
|
||||
True 表示 VC 路径「已干净」,可放行自动/人工建单。
|
||||
"""
|
||||
try:
|
||||
items = collect_vc_candidate_conflicts(candidate)
|
||||
except Exception: # noqa: BLE001 — 门禁 fail-closed:解析异常视为未通过
|
||||
return False
|
||||
for it in items:
|
||||
if not isinstance(it, dict):
|
||||
blocking: list[Any] = []
|
||||
for item in conflicts:
|
||||
# 非字典遗留值无法判明严重度与裁决状态,继续 fail-closed。
|
||||
if not isinstance(item, dict):
|
||||
blocking.append(item)
|
||||
continue
|
||||
severity = str(it.get('severity') or 'blocking').strip()
|
||||
reason = str(it.get('reason') or '').strip()
|
||||
if reason in CQ_VC_BLOCKING_REASONS:
|
||||
return False
|
||||
if severity == 'blocking':
|
||||
return False
|
||||
if severity == 'review_required':
|
||||
# review_required 对自动建单门禁同样算失败(上层会映射为 review_required 总体状态)
|
||||
# 对人工建单是允许的,但 CQ 门禁统一口径:needs_review → fail;
|
||||
# 人工建单的门禁是独立路径,在 order_review_confirmation_service 中。
|
||||
return False
|
||||
return True
|
||||
reason = str(item.get('reason') or item.get('code') or '').strip()
|
||||
if reason in _NON_BLOCKING_CONFLICT_REASONS:
|
||||
continue
|
||||
if field_evidence_gap_is_non_blocking(candidate, item):
|
||||
continue
|
||||
# 新 Finding 有稳定 key 时,Gate 只消费未解决的 blocking 项;禁止把可提示
|
||||
# 的 review_required 误升级为自动建单硬阻断。
|
||||
if str(item.get('conflict_key') or '').strip():
|
||||
if (
|
||||
str(item.get('severity') or '').strip() == 'blocking'
|
||||
and str(item.get('resolution_status') or 'unresolved').strip() == 'unresolved'
|
||||
):
|
||||
blocking.append(item)
|
||||
continue
|
||||
# 旧结构无稳定键/裁决状态,不能安全推定其已解决,保持历史 fail-closed。
|
||||
blocking.append(item)
|
||||
return blocking
|
||||
|
||||
|
||||
def _vc_fine_grained_reason(candidate: Any) -> str | None:
|
||||
def current_open_candidate_conflicts(candidate: Any) -> list[Any]:
|
||||
"""返回当前仍开放且会阻断自动建单的 Candidate 冲突。
|
||||
|
||||
复核投影与资格门禁必须共享这一入口:历史冲突记录只有在明确标记为
|
||||
``blocking + unresolved`` 时才是当前阻断事实;无法判定的旧结构继续
|
||||
fail-closed,避免通过空投影或猜测放行自动建单。
|
||||
"""
|
||||
VC 门禁失败时提取首个匹配的细因码,优先给出 format/region 错,
|
||||
冲突类错其次,保留默认 vc_source_conflict_unresolved 兜底。
|
||||
"""
|
||||
try:
|
||||
items = collect_vc_candidate_conflicts(candidate)
|
||||
except Exception: # noqa: BLE001
|
||||
return None
|
||||
priority_order = [
|
||||
'vc_source_region_unbound',
|
||||
'vc_source_format_invalid',
|
||||
'vc_source_conflict_unresolved',
|
||||
]
|
||||
seen = {str(x.get('reason') or '').strip() for x in items if isinstance(x, dict)}
|
||||
for want in priority_order:
|
||||
if want in seen:
|
||||
return want
|
||||
return None
|
||||
return blocking_candidate_conflicts(candidate)
|
||||
|
||||
|
||||
def resolve_candidate_customer_resolved(
|
||||
@@ -353,7 +349,6 @@ def evaluate_candidate_qualification(
|
||||
)
|
||||
evidence_ok = _evidence_ok(candidate)
|
||||
conflicts_ok = _conflicts_ok(candidate)
|
||||
vc_ok = _vc_gate_ok(candidate)
|
||||
duplicate_ok = _duplicate_ok(candidate)
|
||||
customer_ok, customer_reason = _customer_ok(candidate, customer_resolved=customer_resolved)
|
||||
idempotency_ok = _idempotency_ok(candidate)
|
||||
@@ -366,7 +361,6 @@ def evaluate_candidate_qualification(
|
||||
'key_fields_minimum_confidence': key_confidence_ok,
|
||||
'evidence_complete': evidence_ok,
|
||||
'field_conflicts_resolved': conflicts_ok,
|
||||
'vc_source_merged_clean': vc_ok,
|
||||
'duplicate_resolved': duplicate_ok,
|
||||
'customer_confirmed': customer_ok,
|
||||
'idempotency_ok': idempotency_ok,
|
||||
@@ -384,11 +378,6 @@ def evaluate_candidate_qualification(
|
||||
if pdf_reason:
|
||||
blocking_reason_codes.append(pdf_reason)
|
||||
continue
|
||||
if key == 'vc_source_merged_clean':
|
||||
vc_reason = _vc_fine_grained_reason(candidate)
|
||||
if vc_reason:
|
||||
blocking_reason_codes.append(vc_reason)
|
||||
continue
|
||||
blocking_reason_codes.append(
|
||||
CANDIDATE_QUALIFICATION_GATE_REASON_CODES.get(key, 'order_freeze_not_ready')
|
||||
)
|
||||
@@ -402,20 +391,7 @@ def evaluate_candidate_qualification(
|
||||
blocking_reason_codes=blocking_reason_codes,
|
||||
)
|
||||
|
||||
# [STEP 3b] 证据快照追加 VC 合并概览(脱敏,仅计数)—— 注意:必须在 STEP 4 status
|
||||
# 计算之后执行,因为 status 不依赖 evidence_snapshot,保证零回归。
|
||||
evidence_snapshot = _evidence_snapshot(candidate)
|
||||
try:
|
||||
vc_items = collect_vc_candidate_conflicts(candidate)
|
||||
except Exception: # noqa: BLE001
|
||||
vc_items = []
|
||||
vc_counts = {
|
||||
'vc_total_candidates': len(vc_items),
|
||||
'vc_review_required': len([x for x in vc_items if isinstance(x, dict) and str(x.get('severity') or '') == 'review_required']),
|
||||
'vc_blocking': len([x for x in vc_items if isinstance(x, dict) and str(x.get('severity') or '') == 'blocking']),
|
||||
}
|
||||
if vc_counts['vc_total_candidates']:
|
||||
evidence_snapshot = {**evidence_snapshot, **vc_counts}
|
||||
score = _qualification_score(gates)
|
||||
confidence_policy = {
|
||||
'minimum_confidence': float(min_confidence),
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/chat_action_extended_handlers.py
|
||||
|
||||
用途:货代 Chat Turn 扩展 Action Handler(通知重传/切票/缺口查询)。
|
||||
依赖:shipping_tools、task_workflow、batch_legacy_removed、shipping_turn_helpers、action_registry。
|
||||
用途:货代 Chat Turn 扩展 Action Handler(通知重传/缺口查询)。
|
||||
依赖:shipping_tools、task_workflow、shipping_turn_helpers、action_registry。
|
||||
逻辑:turn_runtime 路由至本模块;与 chat_action_handlers 分工,避免单文件过大;
|
||||
co8 后 switch_batch_focus 固定 410。
|
||||
历史批次焦点切换动作已删除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,7 +16,6 @@ from app.services.chat.action_registry import register_action_handler
|
||||
from app.services.chat.action_schema import TurnEvent
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_by_ref,
|
||||
get_task_for_user,
|
||||
@@ -164,21 +163,6 @@ class ShippingUploadInventoryAction:
|
||||
yield TurnEvent(event="step.completed", data={"step_id": "upload_inventory"})
|
||||
|
||||
|
||||
class ShippingSwitchBatchFocusAction:
|
||||
action_type = "shipping.switch_batch_focus"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
"""
|
||||
历史批次切票(已下线)。
|
||||
|
||||
Raises:
|
||||
AppError: HTTP 410 SHIPPING.BATCHES_REMOVED。
|
||||
"""
|
||||
del ctx
|
||||
raise_shipping_batches_removed(action='shipping.switch_batch_focus')
|
||||
yield from () # pragma: no cover — raise 后不可达,满足 Iterator 注解
|
||||
|
||||
|
||||
class ShippingQueryShortageDetailsAction:
|
||||
action_type = "shipping.query_shortage_details"
|
||||
|
||||
@@ -194,7 +178,6 @@ class ShippingQueryShortageDetailsAction:
|
||||
_HANDLERS = (
|
||||
ShippingReplaceNoticeAction(),
|
||||
ShippingUploadInventoryAction(),
|
||||
ShippingSwitchBatchFocusAction(),
|
||||
ShippingQueryShortageDetailsAction(),
|
||||
)
|
||||
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/chat_action_handlers.py
|
||||
|
||||
用途:货代发货通知 Chat Turn Action Handler 注册实现。
|
||||
依赖:query_service、ui_state、action_registry、
|
||||
batch_legacy_removed。
|
||||
逻辑:turn_runtime 按 action_type 路由至本模块 handler;handler 只编排 yield 事件,业务逻辑委托既有 workflow;
|
||||
co8 后 create_batch_* 动作统一 raise_shipping_batches_removed,改走 order-extraction-submissions。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Iterator
|
||||
|
||||
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
|
||||
|
||||
|
||||
class ShippingCreateBatchFromNoticesAction:
|
||||
"""历史:上传发货通知并创建 shipping_batches;co8 后已下线。"""
|
||||
|
||||
action_type = "shipping.create_batch_from_notices"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
"""
|
||||
拒绝旧建批 Turn。
|
||||
|
||||
核心逻辑:shipping_batches 已 DROP;客户端须走 Intake + order-extraction-submissions。
|
||||
"""
|
||||
del ctx
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed(action='shipping.create_batch_from_notices')
|
||||
if False: # pragma: no cover — 满足 Iterator 注解
|
||||
yield TurnEvent(event='step.started', data={})
|
||||
|
||||
|
||||
class ShippingCreateBatchFromIntakesAction:
|
||||
"""历史:基于 Intake 确认建批;co8 后已下线,改走订单抽取提交。"""
|
||||
|
||||
action_type = "shipping.create_batch_from_intakes"
|
||||
|
||||
def stream(self, ctx: TurnContext) -> Iterator[TurnEvent]:
|
||||
"""
|
||||
拒绝旧建批 Turn。
|
||||
|
||||
核心逻辑:请使用 POST /order-extraction-submissions 创建 OT/Run。
|
||||
"""
|
||||
del ctx
|
||||
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
|
||||
|
||||
raise_shipping_batches_removed(action='shipping.create_batch_from_intakes')
|
||||
if False: # pragma: no cover
|
||||
yield TurnEvent(event='step.started', data={})
|
||||
|
||||
|
||||
_HANDLERS = (
|
||||
ShippingCreateBatchFromNoticesAction(),
|
||||
ShippingCreateBatchFromIntakesAction(),
|
||||
)
|
||||
|
||||
for _handler in _HANDLERS:
|
||||
register_action_handler(_handler)
|
||||
@@ -26,7 +26,6 @@ def build_chat_actions_payload(task) -> dict:
|
||||
state = build_task_ui_state(task)
|
||||
return {
|
||||
"task_no": state.get("task_no"),
|
||||
"batch_no": state.get("batch_no"),
|
||||
"checkpoint": state.get("checkpoint"),
|
||||
"stage": state.get("stage"),
|
||||
"todo": state.get("todo"),
|
||||
|
||||
@@ -16,7 +16,7 @@ from app.core.errors import ForbiddenError
|
||||
from app.models import ChatSession, ShippingNotice
|
||||
|
||||
|
||||
READ_SCOPES = frozenset({'get_shipping_status', 'get_batch_status'})
|
||||
READ_SCOPES = frozenset({'get_shipping_status'})
|
||||
|
||||
|
||||
def _secret() -> bytes:
|
||||
@@ -26,15 +26,15 @@ def _secret() -> bytes:
|
||||
return value.encode('utf-8')
|
||||
|
||||
|
||||
def issue_chat_capability(*, user_id: int, session_id: str, agent_id: int, task_no: str | None, batch_no: str | None) -> str:
|
||||
def issue_chat_capability(*, user_id: int, session_id: str, agent_id: int, task_no: str | None) -> str:
|
||||
"""为单次 Chatflow 注入签名、短效且绑定会话/对象的只读令牌。"""
|
||||
body = {'uid': int(user_id), 'sid': str(session_id), 'aid': int(agent_id), 'task': str(task_no or '').upper(), 'batch': str(batch_no or '').upper(), 'scopes': sorted(READ_SCOPES), 'exp': int(time.time()) + 300, 'nonce': uuid.uuid4().hex}
|
||||
body = {'uid': int(user_id), 'sid': str(session_id), 'aid': int(agent_id), 'task': str(task_no or '').upper(), 'scopes': sorted(READ_SCOPES), 'exp': int(time.time()) + 300, 'nonce': uuid.uuid4().hex}
|
||||
raw = json.dumps(body, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
signature = hmac.new(_secret(), raw, hashlib.sha256).digest()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip('=') + '.' + base64.urlsafe_b64encode(signature).decode().rstrip('=')
|
||||
|
||||
|
||||
def require_chat_capability(*, token: Any, scope: str, task_no: str | None = None, batch_no: str | None = None) -> dict[str, Any]:
|
||||
def require_chat_capability(*, token: Any, scope: str, task_no: str | None = None) -> dict[str, Any]:
|
||||
"""验证令牌签名、时效、scope、会话归属及请求对象,拒绝猜测他人编号。"""
|
||||
try:
|
||||
encoded, signed = str(token or '').split('.', 1)
|
||||
@@ -53,6 +53,4 @@ def require_chat_capability(*, token: Any, scope: str, task_no: str | None = Non
|
||||
task = ShippingNotice.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none()
|
||||
if task is None or str(body.get('task') or '').upper() != task.task_no:
|
||||
raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED')
|
||||
if batch_no and str(body.get('batch') or '').upper() != str(batch_no).upper():
|
||||
raise ForbiddenError('Batch is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED')
|
||||
return body
|
||||
@@ -33,7 +33,7 @@ def build_shipping_notice_context_adapter(
|
||||
Args:
|
||||
agent: 当前对话 Agent(保留签名一致性;发货上下文主要依赖 session_id)。
|
||||
session_id: HXOPS 会话 ID。
|
||||
adapter_hints: 含 shipping_notice 子 dict 时可携带 task_id、batch_no。
|
||||
adapter_hints: 含 shipping_notice 子 dict 时可携带 task_id。
|
||||
request_id: 请求追踪 ID。
|
||||
trigger_source: 触发来源。
|
||||
locale: 用户语言。
|
||||
@@ -46,7 +46,6 @@ def build_shipping_notice_context_adapter(
|
||||
return build_dify_chat_inputs(
|
||||
session_id,
|
||||
task_id=shipping_hints.get('task_id'),
|
||||
batch_no=shipping_hints.get('batch_no'),
|
||||
trigger_source=trigger_source,
|
||||
request_id=request_id,
|
||||
locale=locale,
|
||||
|
||||
@@ -15,7 +15,6 @@ from typing import Any
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingCase,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingIdentityEvidence,
|
||||
@@ -35,9 +34,8 @@ from app.services.shipping_notice.customer_normalization import (
|
||||
normalize_domain,
|
||||
normalize_email,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int
|
||||
from app.services.shipping_notice.business_case_service import generate_shipping_case_no
|
||||
from app.services.shipping_notice.business_numbering_service import assign_business_number
|
||||
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, generate_task_no
|
||||
from app.services.shipping_notice.business_numbering_service import assign_notice_business_number
|
||||
|
||||
AUTO_RESOLUTION_VERSION = "customer-auto-v2"
|
||||
CUSTOMER_AUDIT_EVENT_TYPES = (
|
||||
@@ -297,8 +295,18 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
|
||||
Returns:
|
||||
status、规则版本、唯一 customer_id 与命中证据;歧义/关闭时 customer_id 为空。
|
||||
"""
|
||||
# [PARAM_TUNING] 业务策略改为:已发布识别指纹唯一命中即可自动确认;
|
||||
# 不再以全局开关、历史标注样本量或准确率二次阻断唯一确定结果。
|
||||
# [STEP 1] 总开关关闭时不评估证据,保证环境可安全降级至人工确认。
|
||||
if not auto_customer_resolution_enabled():
|
||||
return {
|
||||
'status': 'disabled',
|
||||
'rule_version': AUTO_RESOLUTION_VERSION,
|
||||
'customer_id': None,
|
||||
'evidence': [],
|
||||
'quality_gate': {
|
||||
'status': 'disabled',
|
||||
'is_eligible': False,
|
||||
},
|
||||
}
|
||||
if task.source_candidate_id is None:
|
||||
return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
shadow = db.session.query(ShippingCustomerShadowResolution).filter_by(
|
||||
@@ -313,11 +321,16 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
|
||||
if shadow is None:
|
||||
return {"status": "no_shadow", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
|
||||
|
||||
return {**_resolve_auto_customer_from_shadow_resolution(shadow), 'quality_gate': {
|
||||
'status': 'bypassed_unique_match_policy',
|
||||
'is_eligible': True,
|
||||
'reason': '唯一识别指纹命中直接自动确认',
|
||||
}}
|
||||
decision = _resolve_auto_customer_from_shadow_resolution(shadow)
|
||||
quality_gate = _auto_confirmation_quality_gate()
|
||||
if not quality_gate['is_eligible']:
|
||||
return {
|
||||
**decision,
|
||||
'status': str(quality_gate['status']),
|
||||
'customer_id': None,
|
||||
'quality_gate': quality_gate,
|
||||
}
|
||||
return {**decision, 'quality_gate': quality_gate}
|
||||
|
||||
|
||||
def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
|
||||
@@ -327,7 +340,7 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
|
||||
核心逻辑:先写自动裁决审计,再复用人工确认的锁与编号事务;成功后将确认方法改为 auto_rule。
|
||||
"""
|
||||
if task.customer_resolution_status == "confirmed":
|
||||
return {"status": "already_confirmed", "customer_id": task.shipping_case.customer_id if task.shipping_case else None}
|
||||
return {"status": "already_confirmed", "customer_id": task.customer_id}
|
||||
decision = resolve_auto_customer_from_shadow(task)
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
@@ -350,11 +363,11 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
|
||||
event_type="customer_auto_confirmed",
|
||||
detail_json={
|
||||
**decision,
|
||||
"business_no": updated.shipping_case.business_no if updated.shipping_case else None,
|
||||
"business_no": updated.business_no,
|
||||
},
|
||||
))
|
||||
db.session.flush()
|
||||
return {**decision, "status": "auto_confirmed", "business_no": updated.shipping_case.business_no}
|
||||
return {**decision, "status": "auto_confirmed", "business_no": updated.business_no}
|
||||
|
||||
|
||||
def correct_numbered_task_customer(
|
||||
@@ -365,10 +378,10 @@ def correct_numbered_task_customer(
|
||||
actor_id: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
更正已编号业务单的标准客户,同时保留原号作废与替代关系。
|
||||
更正已编号 Notice 的标准客户,同时保留原号作废与替代关系。
|
||||
|
||||
核心逻辑:锁定原业务单并校验未上传 → 创建替代业务单和新号 → 迁移整条任务版本链 →
|
||||
清理当前版本的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。
|
||||
核心逻辑:锁定原 Notice 并校验未上传 → 创建替代 Notice 和新号 → 作废原 Notice →
|
||||
清理新 Notice 的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。
|
||||
|
||||
Args:
|
||||
task: 原业务号或技术号定位到的当前任务版本。
|
||||
@@ -387,31 +400,23 @@ def correct_numbered_task_customer(
|
||||
"Customer correction reason is required",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED",
|
||||
)
|
||||
if task.shipping_case_id is None:
|
||||
raise ConflictError(
|
||||
"Numbered shipping case is required for customer correction",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED",
|
||||
)
|
||||
|
||||
original_case = (
|
||||
db.session.query(ShippingCase)
|
||||
.filter(ShippingCase.id == int(task.shipping_case_id))
|
||||
original = (
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(ShippingNotice.id == int(task.id))
|
||||
.with_for_update()
|
||||
.one_or_none()
|
||||
)
|
||||
if original_case is None:
|
||||
raise NotFoundError("Shipping case not found", code="SHIPPING.CASE_NOT_FOUND")
|
||||
if not original_case.business_no:
|
||||
if original is None or not original.business_no:
|
||||
raise ConflictError(
|
||||
"Numbered shipping case is required for customer correction",
|
||||
"Numbered shipping notice is required for customer correction",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED",
|
||||
)
|
||||
existing_replacement = db.session.query(ShippingCase.id).filter_by(
|
||||
replaces_case_id=original_case.id,
|
||||
existing_replacement = db.session.query(ShippingNotice.id).filter_by(
|
||||
supersedes_task_id=original.id,
|
||||
).first()
|
||||
if existing_replacement is not None or original_case.status == "voided":
|
||||
if existing_replacement is not None or str(original.lifecycle_status or '') == 'voided':
|
||||
raise ConflictError(
|
||||
"Shipping case has already been replaced",
|
||||
"Shipping notice has already been replaced",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_ALREADY_REPLACED",
|
||||
)
|
||||
|
||||
@@ -422,117 +427,79 @@ def correct_numbered_task_customer(
|
||||
raise ConflictError("Merged customer cannot be used", code="SHIPPING.CUSTOMER_MERGED_LOCKED")
|
||||
if customer.status != "active":
|
||||
raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE")
|
||||
if original_case.customer_id == customer.id:
|
||||
if original.customer_id == customer.id:
|
||||
raise ValidationError(
|
||||
"Corrected customer must differ from the current customer",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_UNCHANGED",
|
||||
)
|
||||
|
||||
versions = (
|
||||
db.session.query(ShippingNotice)
|
||||
.filter_by(shipping_case_id=original_case.id)
|
||||
.order_by(ShippingNotice.document_version.asc(), ShippingNotice.id.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
if not versions:
|
||||
if str(getattr(original, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}:
|
||||
raise ConflictError(
|
||||
"Shipping case has no task versions",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_TASK_MISSING",
|
||||
)
|
||||
if any(
|
||||
str(getattr(version, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}
|
||||
or str(version.upload_status or "").lower() in {"uploaded", "succeeded", "success"}
|
||||
for version in versions
|
||||
):
|
||||
raise ConflictError(
|
||||
"Uploaded shipping cases require an external cancellation workflow before correction",
|
||||
"Uploaded shipping notices require an external cancellation workflow before correction",
|
||||
code="SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED",
|
||||
)
|
||||
|
||||
old_business_no = str(original_case.business_no)
|
||||
replacement = ShippingCase(
|
||||
case_no=generate_shipping_case_no(),
|
||||
old_business_no = str(original.business_no)
|
||||
now = datetime.utcnow()
|
||||
customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest()
|
||||
replacement = ShippingNotice(
|
||||
task_no=generate_task_no(),
|
||||
user_id=original.user_id,
|
||||
conversation_id=original.conversation_id,
|
||||
source_type=original.source_type,
|
||||
source_file_name=original.source_file_name,
|
||||
source_file_type=original.source_file_type,
|
||||
source_content_hash=original.source_content_hash,
|
||||
source_asset_id=original.source_asset_id,
|
||||
source_intake_id=original.source_intake_id,
|
||||
source_candidate_id=original.source_candidate_id,
|
||||
order_task_id=original.order_task_id,
|
||||
business_fingerprint=original.business_fingerprint,
|
||||
fingerprint_version=original.fingerprint_version,
|
||||
content_fingerprint=original.content_fingerprint,
|
||||
content_fingerprint_version=original.content_fingerprint_version,
|
||||
document_version=int(original.document_version or 1) + 1,
|
||||
supersedes_task_id=original.id,
|
||||
raw_content=original.raw_content,
|
||||
customer_id=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
numbering_status="pending",
|
||||
status="open",
|
||||
replaces_case_id=original_case.id,
|
||||
created_by_id=actor_id,
|
||||
customer_resolution_status="confirmed",
|
||||
customer_resolution_method="admin_correction",
|
||||
customer_identity_fingerprint=customer_fingerprint,
|
||||
customer_confirmed_by=actor_id,
|
||||
customer_confirmed_at=now,
|
||||
)
|
||||
db.session.add(replacement)
|
||||
db.session.flush()
|
||||
new_business_no = assign_business_number(replacement)
|
||||
|
||||
original_case.status = "voided"
|
||||
original_case.numbering_status = "voided"
|
||||
now = datetime.utcnow()
|
||||
customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest()
|
||||
latest = max(versions, key=lambda item: (int(item.document_version or 1), int(item.id)))
|
||||
for version in versions:
|
||||
version.shipping_case_id = replacement.id
|
||||
version.customer_resolution_status = "confirmed"
|
||||
version.customer_resolution_method = "admin_correction"
|
||||
version.customer_identity_fingerprint = customer_fingerprint
|
||||
version.customer_confirmed_by = actor_id
|
||||
version.customer_confirmed_at = now
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=version.id,
|
||||
event_type="customer_correction_applied",
|
||||
detail_json={
|
||||
"old_case_id": original_case.id,
|
||||
"new_case_id": replacement.id,
|
||||
"old_business_no": old_business_no,
|
||||
"new_business_no": new_business_no,
|
||||
"old_customer_id": original_case.customer_id,
|
||||
"new_customer_id": customer.id,
|
||||
"reason": correction_reason,
|
||||
"actor_id": actor_id,
|
||||
},
|
||||
))
|
||||
new_business_no = assign_notice_business_number(replacement)
|
||||
original.lifecycle_status = 'voided'
|
||||
original.voided_at = now
|
||||
original.voided_by_id = actor_id
|
||||
original.void_reason = f'customer_correction:{correction_reason}'
|
||||
correction_detail = {
|
||||
"old_notice_id": original.id,
|
||||
"new_notice_id": replacement.id,
|
||||
"old_business_no": old_business_no,
|
||||
"new_business_no": new_business_no,
|
||||
"old_customer_id": original.customer_id,
|
||||
"new_customer_id": customer.id,
|
||||
"reason": correction_reason,
|
||||
"actor_id": actor_id,
|
||||
}
|
||||
db.session.add(ShippingTaskEvent(task_id=original.id, event_type="customer_correction_applied", detail_json=correction_detail))
|
||||
db.session.add(ShippingTaskEvent(task_id=replacement.id, event_type="customer_correction_applied", detail_json=correction_detail))
|
||||
|
||||
# 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。
|
||||
latest.inventory_source_code = None
|
||||
latest.inventory_connector_type = None
|
||||
latest.inventory_warehouse_id = None
|
||||
latest.inventory_source_status = None
|
||||
latest.inventory_source_method = None
|
||||
latest.inventory_source_confirmed_by = None
|
||||
latest.inventory_source_confirmed_at = None
|
||||
latest.inventory_source_config_version = None
|
||||
latest.inventory_routing_fingerprint = None
|
||||
latest.inventory_rpa_consumed_run_no = None
|
||||
latest.inventory_snapshot_id = None
|
||||
latest.inventory_lines_json = None
|
||||
latest.match_status = None
|
||||
latest.shortage_json = None
|
||||
latest.line_results_json = None
|
||||
latest.export_file_path = None
|
||||
latest.export_file_name = None
|
||||
latest.freight_ref_no = None
|
||||
latest.upload_status = None
|
||||
latest.upload_mode = None
|
||||
latest.upload_attempt = 0
|
||||
latest.upload_started_at = None
|
||||
latest.upload_finished_at = None
|
||||
latest.upload_error_code = None
|
||||
latest.upload_error_message = None
|
||||
latest.upload_receipt_json = None
|
||||
latest.idempotency_key = None
|
||||
latest.current_step = None
|
||||
latest.review_status = None
|
||||
latest.pending_human_reason = None
|
||||
latest.error_message = None
|
||||
db.session.commit()
|
||||
return {
|
||||
"task_no": latest.task_no,
|
||||
"old_case_id": original_case.id,
|
||||
"new_case_id": replacement.id,
|
||||
"task_no": replacement.task_no,
|
||||
"old_notice_id": original.id,
|
||||
"new_notice_id": replacement.id,
|
||||
"old_business_no": old_business_no,
|
||||
"new_business_no": new_business_no,
|
||||
"customer_id": customer.id,
|
||||
"affected_task_count": len(versions),
|
||||
"affected_task_count": 1,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -16,21 +16,17 @@ from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingCase, ShippingCustomer, ShippingNotice, ShippingTaskEvent
|
||||
from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent
|
||||
from app.services.shipping_notice.customer_normalization import clean_text
|
||||
from app.services.shipping_notice.business_numbering_service import assign_business_number
|
||||
|
||||
CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
|
||||
|
||||
def customer_identity_is_confirmed(task: ShippingNotice) -> bool:
|
||||
"""判断任务是否已关联业务单并通过标准客户确认。"""
|
||||
if task.shipping_case_id is None:
|
||||
"""判断 Notice 自身是否已通过标准客户确认。"""
|
||||
if task.customer_id is None:
|
||||
return False
|
||||
case = task.shipping_case or db.session.get(ShippingCase, int(task.shipping_case_id))
|
||||
if case is None or case.customer_id is None:
|
||||
return False
|
||||
customer = db.session.get(ShippingCustomer, int(case.customer_id))
|
||||
customer = db.session.get(ShippingCustomer, int(task.customer_id))
|
||||
return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed')
|
||||
|
||||
|
||||
@@ -46,9 +42,6 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con
|
||||
"""
|
||||
if customer_identity_is_confirmed(task):
|
||||
return
|
||||
case = task.shipping_case or (
|
||||
db.session.get(ShippingCase, int(task.shipping_case_id)) if task.shipping_case_id else None
|
||||
)
|
||||
raise AppError(
|
||||
code=CUSTOMER_GATE_ERROR_CODE,
|
||||
message='标准客户尚未确认,无法继续后续流程',
|
||||
@@ -56,9 +49,8 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con
|
||||
details={
|
||||
'operation': operation,
|
||||
'task_no': task.task_no,
|
||||
'shipping_case_id': task.shipping_case_id,
|
||||
'customer_resolution_status': task.customer_resolution_status or 'pending',
|
||||
'customer_id': case.customer_id if case else None,
|
||||
'customer_id': task.customer_id,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -87,10 +79,10 @@ def confirm_task_customer(
|
||||
commit: bool = True,
|
||||
) -> ShippingNotice:
|
||||
"""
|
||||
人工确认任务所属标准客户,并同步共享业务单下所有任务版本。
|
||||
人工确认 Notice 所属标准客户;业务编号留待首次 Excel 生成时分配。
|
||||
|
||||
核心逻辑:锁定业务单 → 校验启用客户 → 原子分配业务号 → 同步 revision 任务确认状态和事件。
|
||||
客户确认与编号同事务提交,任何一步失败都不留下半确认状态。
|
||||
核心逻辑:锁定客户归属 → 校验启用客户 → 固化 Notice 客户快照。
|
||||
客户确认与客户快照同事务提交;业务编号由 Excel 生成事务独占写入。
|
||||
|
||||
Args:
|
||||
task: 待确认客户的任务。
|
||||
@@ -99,19 +91,14 @@ def confirm_task_customer(
|
||||
resolution_method: manual/auto_rule 等审计方法。
|
||||
commit: 是否提交事务;批次编排传 False 由外层统一提交。
|
||||
"""
|
||||
if task.shipping_case_id is None:
|
||||
raise ConflictError(
|
||||
'Shipping task is missing its required shipping case',
|
||||
code='SHIPPING.CUSTOMER_CASE_REQUIRED',
|
||||
)
|
||||
case = (
|
||||
db.session.query(ShippingCase)
|
||||
.filter(ShippingCase.id == int(task.shipping_case_id))
|
||||
.with_for_update()
|
||||
.one_or_none()
|
||||
task = (
|
||||
db.session.query(ShippingNotice)
|
||||
.filter(ShippingNotice.id == int(task.id))
|
||||
# ShippingNotice.customer 使用 joined eager load,会形成 LEFT OUTER JOIN;
|
||||
# PostgreSQL 不允许锁定该连接的可空侧,故只锁当前 Notice 行。
|
||||
.with_for_update(of=ShippingNotice)
|
||||
.one()
|
||||
)
|
||||
if case is None:
|
||||
raise NotFoundError('Shipping case not found', code='SHIPPING.CASE_NOT_FOUND')
|
||||
customer = db.session.get(ShippingCustomer, int(customer_id))
|
||||
if customer is None:
|
||||
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
|
||||
@@ -119,50 +106,35 @@ def confirm_task_customer(
|
||||
raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
|
||||
if customer.status != 'active':
|
||||
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
|
||||
if case.business_no and case.customer_id not in {None, customer.id}:
|
||||
if task.business_no and task.customer_id not in {None, customer.id}:
|
||||
raise ConflictError(
|
||||
'Numbered shipping case customer cannot be changed silently',
|
||||
code='SHIPPING.CUSTOMER_NUMBERED_CASE_LOCKED',
|
||||
'Numbered shipping notice customer cannot be changed silently',
|
||||
code='SHIPPING.CUSTOMER_NUMBERED_NOTICE_LOCKED',
|
||||
)
|
||||
|
||||
now = datetime.utcnow()
|
||||
previous_customer_id = case.customer_id
|
||||
number_was_assigned = bool(case.business_no)
|
||||
case.customer_id = customer.id
|
||||
case.customer_name_snapshot = customer.standard_name
|
||||
case.customer_short_code_snapshot = customer.short_code
|
||||
business_no = assign_business_number(case)
|
||||
previous_customer_id = task.customer_id
|
||||
task.customer_id = customer.id
|
||||
task.customer_name_snapshot = customer.standard_name
|
||||
task.customer_short_code_snapshot = customer.short_code
|
||||
fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest()
|
||||
tasks = db.session.query(ShippingNotice).filter_by(shipping_case_id=case.id).all()
|
||||
for version in tasks:
|
||||
version.customer_resolution_status = 'confirmed'
|
||||
version.customer_resolution_method = resolution_method
|
||||
version.customer_identity_fingerprint = fingerprint
|
||||
version.customer_confirmed_by = actor_id
|
||||
version.customer_confirmed_at = now
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=version.id,
|
||||
event_type='customer_confirmed',
|
||||
detail_json={
|
||||
'customer_id': customer.id,
|
||||
'standard_name': customer.standard_name,
|
||||
'short_code': customer.short_code,
|
||||
'previous_customer_id': previous_customer_id,
|
||||
'method': resolution_method,
|
||||
'business_no': business_no,
|
||||
},
|
||||
))
|
||||
if not number_was_assigned:
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=version.id,
|
||||
event_type='business_number_assigned',
|
||||
detail_json={
|
||||
'business_no': business_no,
|
||||
'business_date': case.business_date.isoformat() if case.business_date else None,
|
||||
'sequence_value': case.sequence_value,
|
||||
'numbering_rule_version': case.numbering_rule_version,
|
||||
},
|
||||
))
|
||||
task.customer_resolution_status = 'confirmed'
|
||||
task.customer_resolution_method = resolution_method
|
||||
task.customer_identity_fingerprint = fingerprint
|
||||
task.customer_confirmed_by = actor_id
|
||||
task.customer_confirmed_at = now
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
event_type='customer_confirmed',
|
||||
detail_json={
|
||||
'customer_id': customer.id,
|
||||
'standard_name': customer.standard_name,
|
||||
'short_code': customer.short_code,
|
||||
'previous_customer_id': previous_customer_id,
|
||||
'method': resolution_method,
|
||||
'business_no': task.business_no,
|
||||
},
|
||||
))
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return db.session.get(ShippingNotice, int(task.id))
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/customer_shadow_resolution.py
|
||||
|
||||
用途:对订单 Candidate 执行只读客户影子识别,并提供质量报告与人工标签。
|
||||
依赖:客户主数据/识别证据、Candidate/Intake、customer_normalization。
|
||||
逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingCase、ShippingNotice 或业务编号。
|
||||
逻辑:确定性证据打分后只写 ShadowResolution;严禁修改 ShippingNotice 或业务编号。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/dify_inputs.py
|
||||
|
||||
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
|
||||
依赖:agent_runtime_context 平台协议、models.ShippingNotice、shipping_notice.runtime_context。
|
||||
逻辑:由 Context Adapter / api/chat 调用;本模块按会话号解析当前批次/任务焦点,
|
||||
逻辑:由 Context Adapter / api/chat 调用;本模块只使用显式任务锚点,
|
||||
仅输出 agent_runtime_context JSON 字符串,供 Dify 画布统一读取平台运行态快照。
|
||||
发货通知识别请使用 agent_registry.resolver.resolve_agent_code == 'shipping_notice'。
|
||||
"""
|
||||
@@ -19,14 +19,8 @@ from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPU
|
||||
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
|
||||
|
||||
|
||||
def _latest_batch_for_conversation(conversation_id: str) -> None:
|
||||
"""shipping_batches 已删除;固定返回 None。"""
|
||||
del conversation_id
|
||||
return None
|
||||
|
||||
|
||||
def _task_by_task_no(task_id: str) -> ShippingNotice | None:
|
||||
"""按显式 task_id 获取任务;仅用于补齐批次 ref,禁止按会话号猜测当前任务。"""
|
||||
"""按显式 task_id 获取任务;禁止按会话号猜测当前任务。"""
|
||||
normalized = str(task_id or "").strip().upper()
|
||||
if not normalized:
|
||||
return None
|
||||
@@ -66,8 +60,7 @@ def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -
|
||||
"""
|
||||
解析当前显式焦点任务行。
|
||||
|
||||
核心逻辑:优先复用已查出的显式 task;若焦点来自 batch.current_focus_task_no,再按 task_no 查询,
|
||||
但不在无焦点时回退到最近任务,避免多票批次串单。
|
||||
核心逻辑:优先复用已查出的显式 task;不在无焦点时回退到最近任务,避免多票串单。
|
||||
|
||||
Args:
|
||||
focus_task: 已解析出的焦点任务号。
|
||||
@@ -88,7 +81,6 @@ def build_dify_chat_inputs(
|
||||
conversation_id: str | None = None,
|
||||
*,
|
||||
task_id: str | None = None,
|
||||
batch_no: str | None = None,
|
||||
trigger_source: str | None = None,
|
||||
request_id: str | None = None,
|
||||
locale: str | None = None,
|
||||
@@ -108,7 +100,6 @@ def build_dify_chat_inputs(
|
||||
return {}
|
||||
|
||||
explicit_task = str(task_id or "").strip().upper()
|
||||
explicit_batch = str(batch_no or "").strip().upper()
|
||||
explicit_temporary_session = str(temporary_inventory_session_no or '').strip().upper()
|
||||
resolved_temporary_session = (
|
||||
explicit_temporary_session
|
||||
@@ -119,28 +110,12 @@ def build_dify_chat_inputs(
|
||||
)
|
||||
)
|
||||
|
||||
batch = _latest_batch_for_conversation(conv_id)
|
||||
explicit_task_row = _task_by_task_no(explicit_task)
|
||||
|
||||
focus_task = explicit_task
|
||||
if not focus_task and batch and batch.current_focus_task_no:
|
||||
focus_task = str(batch.current_focus_task_no or "").strip().upper()
|
||||
|
||||
focus_batch = explicit_batch
|
||||
if not focus_batch and batch and batch.batch_no:
|
||||
focus_batch = str(batch.batch_no or "").strip().upper()
|
||||
elif (
|
||||
not focus_batch
|
||||
and explicit_task_row
|
||||
and getattr(explicit_task_row, "batch", None) is not None
|
||||
and getattr(explicit_task_row.batch, "batch_no", None)
|
||||
):
|
||||
focus_batch = str(explicit_task_row.batch.batch_no or "").strip().upper()
|
||||
|
||||
runtime_context = build_shipping_runtime_context(
|
||||
session_id=conv_id,
|
||||
task=_focus_task_row(focus_task, explicit_task_row),
|
||||
batch=batch or getattr(explicit_task_row, "batch", None),
|
||||
trigger_source=trigger_source,
|
||||
request_id=request_id,
|
||||
locale=locale,
|
||||
@@ -161,7 +136,7 @@ def build_dify_chat_inputs(
|
||||
session = ChatSession.query.filter_by(session_id=conv_id).one_or_none()
|
||||
capability_token = issue_chat_capability(
|
||||
user_id=session.user_id, session_id=conv_id, agent_id=session.agent_id,
|
||||
task_no=focus_task, batch_no=focus_batch,
|
||||
task_no=focus_task,
|
||||
) if session is not None else None
|
||||
return {
|
||||
AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context),
|
||||
|
||||
@@ -431,6 +431,62 @@ def _serialize_candidate_brief(cand: ShippingOrderCandidate) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def _serialize_candidate_status_brief(
|
||||
cand: ShippingOrderCandidate,
|
||||
*,
|
||||
documents: dict[int, str | None],
|
||||
) -> dict[str, Any]:
|
||||
"""序列化 Intake 状态列表所需的 Candidate 最小字段,不读取审核证据详情。"""
|
||||
from app.services.shipping_notice.duplicate_detection import _allowed_actions_for
|
||||
|
||||
status = str(cand.duplicate_status or 'unchecked')
|
||||
blocking = status in {
|
||||
'exact_file',
|
||||
'same_active_task',
|
||||
'same_completed_task',
|
||||
'possible_duplicate',
|
||||
'same_business_content',
|
||||
'possible_revision',
|
||||
}
|
||||
strength = str(cand.fingerprint_strength or 'unavailable')
|
||||
if strength == 'unavailable' and status == 'none':
|
||||
blocking = False
|
||||
structured = cand.structured_result_json if isinstance(cand.structured_result_json, dict) else {}
|
||||
business_summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
|
||||
return {
|
||||
'candidate_no': cand.candidate_no,
|
||||
'primary_document_id': cand.primary_document_id,
|
||||
'primary_document_filename': documents.get(int(cand.primary_document_id))
|
||||
if cand.primary_document_id is not None else None,
|
||||
'po_number': cand.po_number or business_summary.get('po_number'),
|
||||
'validation_status': cand.validation_status,
|
||||
'candidate_status': cand.candidate_status,
|
||||
'acceptance_mode': cand.acceptance_mode,
|
||||
'extraction_source': cand.extraction_source,
|
||||
'selected': bool(cand.selected),
|
||||
'conflicts': list(cand.conflicts_json or []),
|
||||
'missing_fields': list(cand.missing_fields_json or []),
|
||||
'business_summary': business_summary,
|
||||
'duplicate': {
|
||||
'status': status,
|
||||
'blocking': blocking,
|
||||
'fingerprint_strength': strength,
|
||||
'matches': list(cand.duplicate_matches_json or []),
|
||||
'allowed_actions': _allowed_actions_for(
|
||||
status=status,
|
||||
fingerprint_strength=strength,
|
||||
matches=list(cand.duplicate_matches_json or []),
|
||||
),
|
||||
},
|
||||
'duplicate_resolution': {
|
||||
'action': cand.duplicate_resolution,
|
||||
'target_task_no': cand.duplicate_target_task_no,
|
||||
'reason': cand.duplicate_resolution_reason,
|
||||
} if cand.duplicate_resolution else None,
|
||||
'consumed_task_id': cand.consumed_task_id,
|
||||
}
|
||||
|
||||
|
||||
def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list[dict[str, Any]]:
|
||||
"""列出 Intake 下 Document 摘要。"""
|
||||
rows = (
|
||||
@@ -442,15 +498,36 @@ def list_intake_documents(intake_id: int, *, include_text: bool = False) -> list
|
||||
return [_serialize_document_brief(row, include_text=include_text) for row in rows]
|
||||
|
||||
|
||||
def list_intake_candidates(intake_id: int) -> list[dict[str, Any]]:
|
||||
"""列出 Intake 下 Candidate 摘要。"""
|
||||
def list_intake_candidates(
|
||||
intake_id: int,
|
||||
*,
|
||||
include_details: bool = True,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""列出 Intake 下 Candidate 摘要;状态列表可省略重型审核证据。"""
|
||||
rows = (
|
||||
db.session.query(ShippingOrderCandidate)
|
||||
.filter(ShippingOrderCandidate.intake_id == int(intake_id))
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [_serialize_candidate_brief(row) for row in rows]
|
||||
if include_details:
|
||||
return [_serialize_candidate_brief(row) for row in rows]
|
||||
|
||||
document_ids = {
|
||||
int(row.primary_document_id)
|
||||
for row in rows
|
||||
if row.primary_document_id is not None
|
||||
}
|
||||
documents = {
|
||||
int(row.id): row.filename
|
||||
for row in (
|
||||
db.session.query(ShippingOrderDocument.id, ShippingOrderDocument.filename)
|
||||
.filter(ShippingOrderDocument.id.in_(document_ids))
|
||||
.all()
|
||||
if document_ids else []
|
||||
)
|
||||
}
|
||||
return [_serialize_candidate_status_brief(row, documents=documents) for row in rows]
|
||||
|
||||
|
||||
_UNCHECKED_DUP: dict[str, Any] = {
|
||||
|
||||
-231
@@ -1,231 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/coordinate_region_source_adapter.py
|
||||
|
||||
用途:CoordinateRegionSourceAdapter——将 Profile.named_regions 圈选的物理区域映射为
|
||||
可直接送入 Split Core 的区域原文 + 可引用 bbox 证据(page_no + 绝对坐标)。
|
||||
依赖:profile_vendor_comments_contract.NamedRegion;coordinate_region_text.read_coordinate_region_text
|
||||
与 visual_glyph_rows + positioned_token_spans(证据粒度生成)。
|
||||
逻辑:不读 MinIO、不查 DB;只接收 caller 已加载的 glyphs/page 字典;严格按 Q14 约定
|
||||
page_scope 规则选择「代表页」——last_page 时从多页集合取末页;失败不抛错,统一
|
||||
返回 status=unavailable + 诊断码,供上游 ProfileFieldSourceMappingService 分支处理。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import (
|
||||
positioned_token_spans,
|
||||
read_coordinate_region_text,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
|
||||
NamedRegion,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class CoordinateRegionEvidence:
|
||||
"""单个命中的 token 级证据——供 Observation.evidence_metadata_json 直接序列化。"""
|
||||
|
||||
page_no: int
|
||||
text: str
|
||||
x0: float # 0..1 归一化
|
||||
x1: float
|
||||
y0: float
|
||||
y1: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class CoordinateRegionSourceResult:
|
||||
"""区域抽取结果——对齐 Split Core 结果形状但不做拆分,仅负责原文渲染。"""
|
||||
|
||||
region_id: str
|
||||
label: str
|
||||
status: Literal['available', 'unavailable']
|
||||
page_no: int | None = None
|
||||
raw_text: str = ''
|
||||
lines: list[str] = field(default_factory=list)
|
||||
evidence_tokens: list[CoordinateRegionEvidence] = field(default_factory=list)
|
||||
diagnostic_code: str | None = None
|
||||
diagnostic_message: str | None = None
|
||||
|
||||
|
||||
class CoordinateRegionSourceAdapter:
|
||||
"""
|
||||
将 NamedRegion → 原文 + 证据的薄适配器。
|
||||
|
||||
【AI 触发时机】:三来源收集阶段,上游遍历 field_source_mappings[].vendor_comments_enabled
|
||||
条目并引用命名区域 ID 时调用。
|
||||
|
||||
核心逻辑:
|
||||
[STEP 1] 按 page_scope 从 page_glyphs_map 中选「代表页」:
|
||||
first_page → pages[0];last_page → pages[-1];all_pages 只看 p0(仅用于区域);
|
||||
exact_page → 严格匹配 1-based page_no。
|
||||
[STEP 2] 调 read_coordinate_region_text 取区域原文(0..1 归一化坐标)。
|
||||
[STEP 3] 调 positioned_token_spans 生成 token 级 bbox 证据,用于 Review 高亮点位。
|
||||
[STEP 4] 原文按换行拆为 lines,供后续 execute_base_split_rule_set(..., lines=) 复用。
|
||||
|
||||
Args:
|
||||
region: NamedRegion 契约对象(已通过 validate_assignment 校验)。
|
||||
page_glyphs_map: {1-based_page_no: {'glyphs': [...], 'page': {'width','height'}}} ——
|
||||
caller 负责按当前 Document 加载,本类无网络 IO。
|
||||
"""
|
||||
|
||||
def __init__(self, region: NamedRegion, page_glyphs_map: dict[int, dict[str, Any]]):
|
||||
self.region = region
|
||||
self.page_glyphs_map = page_glyphs_map
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 对外入口
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def extract(self) -> CoordinateRegionSourceResult:
|
||||
"""
|
||||
执行区域抽取。失败不抛异常,统一置 status=unavailable + 稳定诊断码。
|
||||
|
||||
Returns:
|
||||
CoordinateRegionSourceResult,上游据此决定是否跳过 Vendor Comments 来源。
|
||||
"""
|
||||
# [STEP 1] 选择代表页
|
||||
page_no = self._resolve_representative_page_no()
|
||||
if page_no is None:
|
||||
return CoordinateRegionSourceResult(
|
||||
region_id=self.region.region_id,
|
||||
label=self.region.label,
|
||||
status='unavailable',
|
||||
diagnostic_code='named_region_page_not_found',
|
||||
diagnostic_message=(
|
||||
f'named region {self.region.region_id!r} page_scope={self.region.page_scope} '
|
||||
f'page_no={self.region.page_no!r} has no loaded page'
|
||||
),
|
||||
)
|
||||
page_bundle = self.page_glyphs_map[page_no]
|
||||
glyphs = list(page_bundle.get('glyphs') or [])
|
||||
page = dict(page_bundle.get('page') or {})
|
||||
if not glyphs or 'width' not in page or 'height' not in page:
|
||||
return CoordinateRegionSourceResult(
|
||||
region_id=self.region.region_id,
|
||||
label=self.region.label,
|
||||
status='unavailable',
|
||||
page_no=page_no,
|
||||
diagnostic_code='named_region_empty_glyphs',
|
||||
diagnostic_message='region target page has empty glyphs or missing page size',
|
||||
)
|
||||
|
||||
region_coords = {
|
||||
'x0': self.region.region.x0, 'y0': self.region.region.y0,
|
||||
'x1': self.region.region.x1, 'y1': self.region.region.y1,
|
||||
}
|
||||
|
||||
# [STEP 2] 渲染区域原文
|
||||
raw_text = read_coordinate_region_text(
|
||||
glyphs=glyphs, page=page, region=region_coords,
|
||||
)
|
||||
if not raw_text.strip():
|
||||
return CoordinateRegionSourceResult(
|
||||
region_id=self.region.region_id,
|
||||
label=self.region.label,
|
||||
status='unavailable',
|
||||
page_no=page_no,
|
||||
diagnostic_code='named_region_text_empty',
|
||||
diagnostic_message=f'named region {self.region.region_id!r} has empty body text',
|
||||
)
|
||||
|
||||
# [STEP 3] 生成 token 级证据(只保留区域中心在 box 内的 token)
|
||||
tokens = self._collect_region_evidence_tokens(
|
||||
glyphs=glyphs, page=page, region_coords=region_coords, page_no=page_no,
|
||||
)
|
||||
|
||||
# [STEP 4] 拆行
|
||||
lines = [ln.strip() for ln in raw_text.splitlines() if ln.strip()]
|
||||
|
||||
return CoordinateRegionSourceResult(
|
||||
region_id=self.region.region_id,
|
||||
label=self.region.label,
|
||||
status='available',
|
||||
page_no=page_no,
|
||||
raw_text=raw_text.strip(),
|
||||
lines=lines,
|
||||
evidence_tokens=tokens,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 内部帮助
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _resolve_representative_page_no(self) -> int | None:
|
||||
"""按 page_scope 规则选择代表页。"""
|
||||
sorted_pages = sorted(self.page_glyphs_map.keys())
|
||||
if not sorted_pages:
|
||||
return None
|
||||
scope = self.region.page_scope
|
||||
if scope == 'first_page':
|
||||
return sorted_pages[0]
|
||||
if scope == 'last_page':
|
||||
return sorted_pages[-1]
|
||||
if scope == 'all_pages':
|
||||
# all_pages 的命名区域仅在第一页渲染(常见全页 Header);
|
||||
# 若管理员要取多页块,应拆为多个命名区域并使用 exact_page。
|
||||
return sorted_pages[0]
|
||||
if scope == 'exact_page':
|
||||
return self.region.page_no if self.region.page_no in self.page_glyphs_map else None
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _collect_region_evidence_tokens(
|
||||
*,
|
||||
glyphs: list[dict[str, Any]],
|
||||
page: dict[str, Any],
|
||||
region_coords: dict[str, float],
|
||||
page_no: int,
|
||||
) -> list[CoordinateRegionEvidence]:
|
||||
"""筛选命名区域中心范围内的 token,并返回 0..1 归一化 bbox。"""
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
rx0, ry0, rx1, ry1 = (region_coords[k] for k in ('x0', 'y0', 'x1', 'y1'))
|
||||
all_spans = positioned_token_spans(glyphs, respect_explicit_spaces=True)
|
||||
selected: list[CoordinateRegionEvidence] = []
|
||||
for span in all_spans:
|
||||
sx0 = float(span['x0']) / width
|
||||
sx1 = float(span['x1']) / width
|
||||
text = str(span.get('text') or '')
|
||||
# y 边界:span 只返回横向边界;glyphs 中心用于 y 判定
|
||||
# positioned_token_spans 不返回 y,重算 y0/y1 需回溯原 glyph——这里直接用
|
||||
# glyphs 子集重算以保证引用不泄漏。
|
||||
matched = [
|
||||
g for g in glyphs
|
||||
if _glyph_intersects_span(g, span, width) and _glyph_in_region_center(g, width, height, rx0, ry0, rx1, ry1)
|
||||
]
|
||||
if not matched:
|
||||
continue
|
||||
min_y0 = min(float(g['bbox']['y0']) / height for g in matched)
|
||||
max_y1 = max(float(g['bbox']['y1']) / height for g in matched)
|
||||
selected.append(CoordinateRegionEvidence(
|
||||
page_no=page_no,
|
||||
text=text,
|
||||
x0=sx0, x1=sx1,
|
||||
y0=min_y0, y1=max_y1,
|
||||
))
|
||||
return selected
|
||||
|
||||
|
||||
def _glyph_intersects_span(glyph: dict[str, Any], span: dict[str, Any], width: float) -> bool:
|
||||
try:
|
||||
gx0 = float(glyph['bbox']['x0']) / width
|
||||
gx1 = float(glyph['bbox']['x1']) / width
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
return min(gx1, float(span['x1']) / width) > max(gx0, float(span['x0']) / width)
|
||||
|
||||
|
||||
def _glyph_in_region_center(
|
||||
glyph: dict[str, Any], width: float, height: float,
|
||||
rx0: float, ry0: float, rx1: float, ry1: float,
|
||||
) -> bool:
|
||||
try:
|
||||
b = glyph['bbox']
|
||||
cx = (float(b['x0']) + float(b['x1'])) / (2 * width)
|
||||
cy = (float(b['y0']) + float(b['y1'])) / (2 * height)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
return rx0 <= cx <= rx1 and ry0 <= cy <= ry1
|
||||
+642
-42
@@ -8,6 +8,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import re
|
||||
from statistics import median
|
||||
from typing import Any, Literal
|
||||
@@ -15,9 +16,13 @@ from typing import Any, Literal
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.coordinate_transform import (
|
||||
apply_coordinate_transform_to_region,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
|
||||
from app.services.shipping_notice.document_layout.text_cell_alignment import PositionedCharacter
|
||||
from app.services.shipping_notice.document_layout.order_profile_extractors import extract_profile_field_value
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
@@ -27,6 +32,186 @@ _DELETED_PATTERN = re.compile(r'^\*+itemdeleted\*+$', re.IGNORECASE)
|
||||
DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no'
|
||||
|
||||
|
||||
def reconstruction_exclusion_regions(
|
||||
table_region: dict[str, Any], *, include_header_layouts: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""返回明细重建的显式普通排除区;表头框只保留作语义和预览证据。"""
|
||||
exclusions = [
|
||||
dict(item) for item in (table_region.get('exclusion_regions') or [])
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
if include_header_layouts:
|
||||
exclusions.extend(
|
||||
dict(item['region'])
|
||||
for item in (table_region.get('header_layouts') or [])
|
||||
if isinstance(item, dict) and isinstance(item.get('region'), dict)
|
||||
)
|
||||
return exclusions
|
||||
|
||||
|
||||
def coordinate_profile_character_candidates(
|
||||
*,
|
||||
table_region: dict[str, Any],
|
||||
reference_page_frame: dict[str, Any] | None = None,
|
||||
page_size: dict[str, Any],
|
||||
page_characters: list[dict[str, Any]] | None,
|
||||
table_characters: list[dict[str, Any]] | None,
|
||||
raw_table_bbox: dict[str, Any] | None = None,
|
||||
table_id: str | None = None,
|
||||
page_no: int = 1,
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
allow_table_fallback: bool = True,
|
||||
) -> tuple[list[dict[str, Any]] | None, dict[str, float] | None]:
|
||||
"""按统一契约选择当前表区字符:整页证据优先,真实表框仅扩展纵向范围。
|
||||
|
||||
模板区域的横向边界始终有效;真实物理表的纵向边界用于覆盖跨行表框。
|
||||
缺少整页证据时仅回退到该表的冻结字符,不把其它页面或其它表带入。
|
||||
"""
|
||||
try:
|
||||
page_bbox = {
|
||||
'x0': 0.0, 'y0': 0.0,
|
||||
'x1': float(page_size['width']), 'y1': float(page_size['height']),
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None, None
|
||||
if page_bbox['x1'] <= 0 or page_bbox['y1'] <= 0:
|
||||
return None, None
|
||||
projected = apply_coordinate_transform_to_region(
|
||||
table_region, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if projected is None:
|
||||
return None, page_bbox
|
||||
try:
|
||||
reference_width = float(reference_page_frame['width']) if reference_page_frame is not None else page_bbox['x1']
|
||||
reference_height = float(reference_page_frame['height']) if reference_page_frame is not None else page_bbox['y1']
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None, page_bbox
|
||||
if reference_width <= 0 or reference_height <= 0:
|
||||
return None, page_bbox
|
||||
region_bbox = {
|
||||
'x0': projected['x0'] * reference_width, 'y0': projected['y0'] * reference_height,
|
||||
'x1': projected['x1'] * reference_width, 'y1': projected['y1'] * reference_height,
|
||||
}
|
||||
is_virtual_page = str(table_id or '') == f'page-{int(page_no)}'
|
||||
if not is_virtual_page and isinstance(raw_table_bbox, dict):
|
||||
try:
|
||||
if not (
|
||||
float(raw_table_bbox['x0']) < region_bbox['x1']
|
||||
and float(raw_table_bbox['x1']) > region_bbox['x0']
|
||||
and float(raw_table_bbox['y0']) < region_bbox['y1']
|
||||
and float(raw_table_bbox['y1']) > region_bbox['y0']
|
||||
):
|
||||
return None, page_bbox
|
||||
evidence_bbox = dict(region_bbox)
|
||||
evidence_bbox['y0'] = min(region_bbox['y0'], float(raw_table_bbox['y0']))
|
||||
evidence_bbox['y1'] = max(region_bbox['y1'], float(raw_table_bbox['y1']))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None, page_bbox
|
||||
else:
|
||||
evidence_bbox = region_bbox
|
||||
if isinstance(page_characters, list):
|
||||
page_candidates = [
|
||||
item for item in page_characters
|
||||
if isinstance(item, dict) and _character_center_in_region(item, evidence_bbox)
|
||||
]
|
||||
# 页级快照可能只包含订单头或被上游裁剪过;空的页级候选不能遮蔽
|
||||
# 当前物理表仍然有效的冻结字符证据。
|
||||
if page_candidates:
|
||||
return page_candidates, page_bbox
|
||||
if allow_table_fallback and isinstance(table_characters, list):
|
||||
return table_characters, page_bbox
|
||||
return None, page_bbox
|
||||
|
||||
|
||||
def _character_center_in_region(character: dict[str, Any], region: dict[str, float]) -> bool:
|
||||
"""判断字符中心点是否落入绝对坐标区域。"""
|
||||
bbox = character.get('bbox') if isinstance(character.get('bbox'), dict) else None
|
||||
if bbox is None:
|
||||
return False
|
||||
try:
|
||||
center_x = (float(bbox['x0']) + float(bbox['x1'])) / 2
|
||||
center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
return region['x0'] <= center_x <= region['x1'] and region['y0'] <= center_y <= region['y1']
|
||||
|
||||
|
||||
def reconstruct_coordinate_profile_rows_with_strategy(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox | dict[str, Any],
|
||||
line_layouts: list[dict[str, Any]],
|
||||
table_region: dict[str, Any] | None = None,
|
||||
termination_rules: list[dict[str, Any]] | None = None,
|
||||
exclusion_regions: list[dict[str, Any]] | None = None,
|
||||
dynamic_exclusion_regions: list[dict[str, Any]] | None = None,
|
||||
line_start_field_code: str | None = None,
|
||||
include_deleted: bool = False,
|
||||
schema_field_metadata: list[dict[str, Any]] | None = None,
|
||||
initial_fields: dict[str, str] | None = None,
|
||||
initial_next_offset: int = 0,
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
page_no: int = 1,
|
||||
) -> tuple[list['CoordinateProfileLogicalRow'], Any]:
|
||||
"""统一评估 fixed/adaptive/dynamic,并返回唯一安全的坐标明细结果。"""
|
||||
from app.services.shipping_notice.document_layout.runtime_parse_strategy import (
|
||||
resolve_runtime_parse_strategy,
|
||||
)
|
||||
|
||||
fixed_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
|
||||
table_region=table_region, termination_rules=termination_rules,
|
||||
exclusion_regions=exclusion_regions, line_start_field_code=line_start_field_code,
|
||||
include_deleted=include_deleted, row_reconstruction_mode='fixed_subrows',
|
||||
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
|
||||
initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
adaptive_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
|
||||
table_region=table_region, termination_rules=termination_rules,
|
||||
exclusion_regions=exclusion_regions, line_start_field_code=line_start_field_code,
|
||||
include_deleted=include_deleted, row_reconstruction_mode='adaptive_record_columns',
|
||||
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
|
||||
initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
dynamic_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
|
||||
table_region=table_region, termination_rules=termination_rules,
|
||||
exclusion_regions=dynamic_exclusion_regions or [], line_start_field_code=line_start_field_code,
|
||||
include_deleted=include_deleted, row_reconstruction_mode='dynamic_x_columns',
|
||||
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
|
||||
initial_next_offset=initial_next_offset, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
|
||||
def strategy_rows(rows: list[CoordinateProfileLogicalRow]) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{
|
||||
'status': 'parsed' if not row.issues else 'needs_review',
|
||||
'issues': list(row.issues),
|
||||
'fields': [
|
||||
{'field_code': code, 'value': value}
|
||||
for code, value in row.fields.items()
|
||||
],
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
strategy = resolve_runtime_parse_strategy(
|
||||
page_glyphs={str(page_no): characters},
|
||||
fixed_rows=strategy_rows(fixed_rows),
|
||||
adaptive_rows=strategy_rows(adaptive_rows),
|
||||
dynamic_rows=strategy_rows(dynamic_rows),
|
||||
)
|
||||
if strategy.status != 'selected' or strategy.row_mode is None:
|
||||
return [], strategy
|
||||
return (
|
||||
fixed_rows if strategy.row_mode == 'fixed_subrows'
|
||||
else adaptive_rows if strategy.row_mode == 'adaptive_record_columns'
|
||||
else dynamic_rows,
|
||||
strategy,
|
||||
)
|
||||
|
||||
|
||||
def resolve_line_start_field_code(value: Any = None) -> str:
|
||||
"""
|
||||
规范化模板起行锚点字段编码。
|
||||
@@ -56,6 +241,59 @@ def is_valid_line_start_value(raw: Any) -> bool:
|
||||
return bool(text and _LINE_NUMBER_PATTERN.fullmatch(text))
|
||||
|
||||
|
||||
def _is_record_start(
|
||||
values: dict[str, str],
|
||||
fields: list[dict[str, Any]],
|
||||
line_start_field_code: str,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> bool:
|
||||
"""用冻结 Schema 的字段类型/校验结果确认明细起行,不依赖业务字段名或列序。"""
|
||||
if schema_fields is None:
|
||||
start_value = values.get(line_start_field_code, '')
|
||||
return is_valid_line_start_value(start_value)
|
||||
start_field_configured = any(
|
||||
str(field.get('field_code') or '') == line_start_field_code for field in fields
|
||||
)
|
||||
start_value = values.get(line_start_field_code, '')
|
||||
def schema_valid(code: str, raw: str) -> bool:
|
||||
config = schema_fields.get(code)
|
||||
if not config or not str(raw or '').strip():
|
||||
return False
|
||||
try:
|
||||
normalized = normalize_order_field_value(raw, config)
|
||||
except Exception:
|
||||
return False
|
||||
return normalized not in (None, '') and validate_order_field_value(normalized, config)
|
||||
|
||||
# 起行字段的 Schema 类型只负责保留/解析值;它被模板配置为起行锚点后,
|
||||
# 还必须满足通用行号形态,避免 string 字段把表头文本(如 ``0rd``/``B``)
|
||||
# 当成明细起点。该规则只作用于配置的锚点,不依赖任何业务字段名。
|
||||
has_start_anchor = (
|
||||
is_valid_line_start_value(start_value)
|
||||
and schema_valid(line_start_field_code, start_value)
|
||||
)
|
||||
corroborating = sum(
|
||||
1 for field in fields
|
||||
if (code := str(field.get('field_code') or ''))
|
||||
and code != line_start_field_code
|
||||
and schema_valid(code, values.get(code, ''))
|
||||
)
|
||||
configured_corroborating_fields = sum(
|
||||
1 for field in fields
|
||||
if (code := str(field.get('field_code') or ''))
|
||||
and code != line_start_field_code
|
||||
and code in schema_fields
|
||||
)
|
||||
if has_start_anchor:
|
||||
# 若模板只绑定起行字段,Schema 没有第二个坐标字段可供交叉验证,
|
||||
# 允许该锚点单独起行;一旦存在其它已绑定字段,必须有至少一个有效值。
|
||||
return corroborating >= 1 or configured_corroborating_fields == 0
|
||||
# A profile that explicitly configures a start field must not silently fall back
|
||||
# to unrelated fields when that anchor is absent. Profiles without such a field
|
||||
# may use a position-independent two-field business signature.
|
||||
return not start_field_configured and corroborating >= 2
|
||||
|
||||
|
||||
|
||||
class CoordinateReconstructionModel(BaseModel):
|
||||
"""为坐标重建的中间证据启用严格契约,禁止调用方注入未定义字段。"""
|
||||
@@ -109,7 +347,7 @@ _HEADER_TERMS = frozenset({
|
||||
'brand', 'manufacturer', 'delivery', 'shipping', 'drawing', 'rev',
|
||||
})
|
||||
_SUMMARY_PATTERN = re.compile(
|
||||
r'(?:total\s*amount|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)',
|
||||
r'(?:\btotal(?:\s*amount)?\b|incl\.?\s*tax|subtotal|invoice\s*bill|terms?\s*and\s*conditions?)',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
@@ -268,7 +506,9 @@ def reconstruct_coordinate_profile_rows(
|
||||
include_deleted: bool = False,
|
||||
line_start_field_code: str | None = None,
|
||||
include_unanchored_rows: bool = False,
|
||||
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows',
|
||||
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns'] = 'fixed_subrows',
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
schema_field_metadata: list[dict[str, Any]] | None = None,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""
|
||||
按 v2 物理行和字段区域合并逻辑明细,不使用 MinerU 的行列结果。
|
||||
@@ -279,8 +519,33 @@ def reconstruct_coordinate_profile_rows(
|
||||
才是已授权的删除证据;未授权删除文字会被忽略。``include_deleted`` 仅供标注预览
|
||||
返回删除行证据;正式解析保持默认值,删除行不会进入业务结果。仅管理员预览可开启
|
||||
``include_unanchored_rows``,在没有任何有效起行值时返回待复核的主行字段,不能用于正式解析。
|
||||
``coordinate_transform`` 只能接收共同 matcher 已确认的 ``status=applied`` 平移;
|
||||
它只在当前调用的内存副本投影表区、物理行和字段区域,绝不修改冻结 Profile。
|
||||
"""
|
||||
projected = _project_coordinate_profile_regions(
|
||||
table_region=table_region,
|
||||
line_layouts=line_layouts,
|
||||
termination_rules=termination_rules,
|
||||
exclusion_regions=exclusion_regions,
|
||||
coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if projected is None:
|
||||
return []
|
||||
table_region = projected['table_region']
|
||||
line_layouts = projected['line_layouts']
|
||||
termination_rules = projected['termination_rules']
|
||||
exclusion_regions = projected['exclusion_regions']
|
||||
start_field_code = resolve_line_start_field_code(line_start_field_code)
|
||||
schema_fields = {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in (schema_field_metadata or [])
|
||||
if (
|
||||
isinstance(item, dict)
|
||||
and item.get('field_code')
|
||||
and item.get('enabled', True)
|
||||
and str(item.get('scope') or '') == 'line'
|
||||
)
|
||||
} if schema_field_metadata is not None else None
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
ordered_layouts = sorted((item for item in line_layouts if isinstance(item, dict)), key=lambda item: item.get('row_offset', -1))
|
||||
if not ordered_layouts or [item.get('row_offset') for item in ordered_layouts] != list(range(len(ordered_layouts))):
|
||||
@@ -302,6 +567,11 @@ def reconstruct_coordinate_profile_rows(
|
||||
_absolute_relative_region(bbox, item)
|
||||
for item in (exclusion_regions or []) if isinstance(item, dict)
|
||||
]
|
||||
# 直接调用动态候选时,传入的旧式排除区无法区分表头/普通排除;为兼容其
|
||||
# “表头可移动”语义不应用它。统一入口则显式传入 dynamic_exclusion_regions,
|
||||
# 从而保留管理员配置的普通排除区。
|
||||
if row_reconstruction_mode == 'dynamic_x_columns':
|
||||
exclusions = []
|
||||
# [STEP 1] 删除文字不是全局业务规则;只有管理员用排除区显式圈定后才授权删除上一条明细。
|
||||
marker_indices: set[int] = set()
|
||||
authorized_marker_indices: set[int] = set()
|
||||
@@ -333,6 +603,16 @@ def reconstruct_coordinate_profile_rows(
|
||||
|
||||
# This mode is opt-in per table region. It supports documents whose stable
|
||||
# columns stay put while optional descriptions move values across visual rows.
|
||||
if row_reconstruction_mode == 'dynamic_x_columns':
|
||||
return _reconstruct_dynamic_x_columns_profile_rows(
|
||||
glyphs=glyphs,
|
||||
table_bbox=bbox,
|
||||
ordered_layouts=ordered_layouts,
|
||||
termination_rules=termination_rules or [],
|
||||
include_deleted=include_deleted,
|
||||
line_start_field_code=start_field_code,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
if row_reconstruction_mode == 'adaptive_record_columns':
|
||||
return _reconstruct_adaptive_record_columns_profile_rows(
|
||||
glyphs=glyphs,
|
||||
@@ -341,6 +621,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
termination_rules=termination_rules or [],
|
||||
include_deleted=include_deleted,
|
||||
line_start_field_code=start_field_code,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
|
||||
relative_y_rows = _reconstruct_relative_y_profile_rows(
|
||||
@@ -352,6 +633,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
include_deleted=include_deleted,
|
||||
line_start_field_code=start_field_code,
|
||||
include_unanchored_rows=include_unanchored_rows,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
if relative_y_rows is not None:
|
||||
return relative_y_rows
|
||||
@@ -414,7 +696,7 @@ def reconstruct_coordinate_profile_rows(
|
||||
flush(role='deleted')
|
||||
continue
|
||||
main_values, main_evidence, main_issues = values_for(band, ordered_layouts[0])
|
||||
if is_valid_line_start_value(main_values.get(start_field_code, '')):
|
||||
if _is_record_start(main_values, ordered_layouts[0].get('field_regions') or [], start_field_code, schema_fields):
|
||||
flush()
|
||||
current, current_evidence = main_values, main_evidence
|
||||
sources, next_offset, current_issues = [row_index], 1, main_issues
|
||||
@@ -451,6 +733,80 @@ def reconstruct_coordinate_profile_rows(
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
|
||||
|
||||
def _project_coordinate_profile_regions(
|
||||
*,
|
||||
table_region: dict[str, Any] | None,
|
||||
line_layouts: list[dict[str, Any]],
|
||||
termination_rules: list[dict[str, Any]] | None,
|
||||
exclusion_regions: list[dict[str, Any]] | None,
|
||||
coordinate_transform: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""对当前重建调用复制并投影受 matcher 证明的统一坐标变换。
|
||||
|
||||
未传变换时保留 legacy 行为。传入变换必须是有限、页面内的 ``applied``
|
||||
变换;任何伪造、过界或未知状态都返回 ``None``,由调用方保持 Review,
|
||||
不能静默回退到旧绝对坐标。
|
||||
"""
|
||||
def project_region(region: Any) -> dict[str, float] | None:
|
||||
if not isinstance(region, dict):
|
||||
return None
|
||||
return apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform)
|
||||
|
||||
projected_table = project_region(table_region) if table_region is not None else None
|
||||
projected_layouts = []
|
||||
projected_terminations: list[dict[str, Any]] | None = [] if termination_rules is not None else None
|
||||
projected_exclusions: list[dict[str, float]] | None = [] if exclusion_regions is not None else None
|
||||
if table_region is not None and projected_table is None:
|
||||
return None
|
||||
for layout in line_layouts:
|
||||
if not isinstance(layout, dict):
|
||||
return None
|
||||
copied = dict(layout)
|
||||
region = copied.get('region')
|
||||
if region is not None:
|
||||
projected_region = project_region(region)
|
||||
if projected_region is None:
|
||||
return None
|
||||
copied['region'] = projected_region
|
||||
fields = []
|
||||
for field in copied.get('field_regions') or []:
|
||||
if not isinstance(field, dict):
|
||||
return None
|
||||
projected_field = dict(field)
|
||||
projected_region = project_region(field.get('region'))
|
||||
if projected_region is None:
|
||||
return None
|
||||
projected_field['region'] = projected_region
|
||||
fields.append(projected_field)
|
||||
copied['field_regions'] = fields
|
||||
projected_layouts.append(copied)
|
||||
for rule in termination_rules or []:
|
||||
if not isinstance(rule, dict):
|
||||
return None
|
||||
copied = dict(rule)
|
||||
anchor = copied.get('anchor')
|
||||
region = anchor.get('region') if isinstance(anchor, dict) else None
|
||||
if region is not None:
|
||||
projected_region = project_region(region)
|
||||
if projected_region is None:
|
||||
return None
|
||||
copied['anchor'] = {**anchor, 'region': projected_region}
|
||||
assert projected_terminations is not None
|
||||
projected_terminations.append(copied)
|
||||
for region in exclusion_regions or []:
|
||||
projected_region = project_region(region)
|
||||
if projected_region is None:
|
||||
return None
|
||||
assert projected_exclusions is not None
|
||||
projected_exclusions.append(projected_region)
|
||||
return {
|
||||
'table_region': projected_table,
|
||||
'line_layouts': projected_layouts,
|
||||
'termination_rules': projected_terminations,
|
||||
'exclusion_regions': projected_exclusions,
|
||||
}
|
||||
|
||||
|
||||
def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
*,
|
||||
glyphs: list[tuple[int, PositionedCharacter]],
|
||||
@@ -459,6 +815,7 @@ def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
termination_rules: list[dict[str, Any]],
|
||||
include_deleted: bool,
|
||||
line_start_field_code: str,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""按起行锚点分段,并在每段内用字段列及格式读取可变视觉子行。"""
|
||||
main_fields = ordered_layouts[0].get('field_regions') or []
|
||||
@@ -489,6 +846,7 @@ def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
main_fields=main_fields,
|
||||
table_bbox=table_bbox,
|
||||
line_start_field_code=line_start_field_code,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
]
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
@@ -503,6 +861,17 @@ def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
for field in fields:
|
||||
code = str(field['field_code'])
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
# 自适应列模式只能为单视觉 band 选择候选。若 Schema 绑定的
|
||||
# 字段框明确跨越多个 band(如换行客户料号),该模式的单 band
|
||||
# 候选必然不完整,必须交给 fixed 几何重建处理。
|
||||
if schema_fields is not None:
|
||||
intersecting = [
|
||||
band for _row_index, band in record
|
||||
if _regions_overlap_vertically(region, _band_bbox(band))
|
||||
]
|
||||
if len(intersecting) > 1:
|
||||
issues.append(f'coordinate_profile_field_band_ambiguous:{code}')
|
||||
continue
|
||||
candidates: list[tuple[float, int, dict[str, str]]] = []
|
||||
for band_index, (_, band) in enumerate(record):
|
||||
raw = _adaptive_field_raw(band=band, region=region, field_code=code)
|
||||
@@ -535,7 +904,7 @@ def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
if is_valid_line_start_value(values.get(line_start_field_code, '')):
|
||||
if _is_record_start(values, main_fields, line_start_field_code, schema_fields):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _ in record],
|
||||
@@ -545,6 +914,87 @@ def _reconstruct_adaptive_record_columns_profile_rows(
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
|
||||
|
||||
def _reconstruct_dynamic_x_columns_profile_rows(
|
||||
*,
|
||||
glyphs: list[tuple[int, PositionedCharacter]],
|
||||
table_bbox: LayoutBBox,
|
||||
ordered_layouts: list[dict[str, Any]],
|
||||
termination_rules: list[dict[str, Any]],
|
||||
include_deleted: bool,
|
||||
line_start_field_code: str,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> list[CoordinateProfileLogicalRow]:
|
||||
"""按每条记录的有效起行锚点平移完整字段框,恢复稳定 X、漂移 Y 的明细。"""
|
||||
main_fields = ordered_layouts[0].get('field_regions') or []
|
||||
start_field = next(
|
||||
(item for item in main_fields if isinstance(item, dict) and item.get('field_code') == line_start_field_code),
|
||||
None,
|
||||
)
|
||||
if not isinstance(start_field, dict) or not isinstance(start_field.get('region'), dict):
|
||||
return []
|
||||
fields = [
|
||||
field for layout in ordered_layouts for field in (layout.get('field_regions') or [])
|
||||
if isinstance(field, dict) and isinstance(field.get('region'), dict) and field.get('field_code')
|
||||
]
|
||||
bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = []
|
||||
for row_index, band in enumerate(_group_visual_rows(glyphs)):
|
||||
text = ''.join(glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)).strip()
|
||||
if _SUMMARY_PATTERN.search(text) or _matches_termination_rule(band, table_bbox, termination_rules):
|
||||
break
|
||||
bands.append((row_index, band))
|
||||
start_region = _absolute_relative_region(table_bbox, start_field['region'])
|
||||
anchors = [
|
||||
index for index, (_row_index, band) in enumerate(bands)
|
||||
if _is_adaptive_record_start(
|
||||
band=band, start_region=start_region, main_fields=main_fields,
|
||||
table_bbox=table_bbox, line_start_field_code=line_start_field_code,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
]
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
expected_anchor_center = (start_region.y0 + start_region.y1) / 2
|
||||
for anchor_index, start in enumerate(anchors):
|
||||
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(bands)
|
||||
record = bands[start:end]
|
||||
anchor_box = _band_bbox(record[0][1])
|
||||
delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center
|
||||
values: dict[str, str] = {}
|
||||
issues: list[str] = []
|
||||
for field in fields:
|
||||
code = str(field['field_code'])
|
||||
saved = _absolute_relative_region(table_bbox, field['region'])
|
||||
region = LayoutBBox(
|
||||
x0=saved.x0, y0=saved.y0 + delta_y,
|
||||
x1=saved.x1, y1=saved.y1 + delta_y,
|
||||
)
|
||||
selected_bands = [
|
||||
band for _row_index, band in record
|
||||
if _regions_overlap_vertically(region, _band_bbox(band))
|
||||
]
|
||||
raw = _text_in_multiline_region(
|
||||
selected_bands, region,
|
||||
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
|
||||
)
|
||||
if not raw:
|
||||
continue
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
|
||||
)
|
||||
for extracted_code, extracted_value in extracted.items():
|
||||
previous = values.get(extracted_code)
|
||||
if previous is not None and previous != extracted_value:
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
if _is_record_start(values, main_fields, line_start_field_code, schema_fields):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _band in record],
|
||||
role='data', issues=issues,
|
||||
))
|
||||
return results if include_deleted else [row for row in results if row.role != 'deleted']
|
||||
|
||||
|
||||
def _adaptive_field_raw(
|
||||
*, band: list[tuple[int, PositionedCharacter]], region: LayoutBBox, field_code: str,
|
||||
) -> str:
|
||||
@@ -562,22 +1012,43 @@ def _adaptive_field_raw(
|
||||
def _is_adaptive_record_start(
|
||||
*, band: list[tuple[int, PositionedCharacter]], start_region: LayoutBBox,
|
||||
main_fields: list[dict[str, Any]], table_bbox: LayoutBBox, line_start_field_code: str,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> bool:
|
||||
"""要求起行号及同一主行的其他绑定字段共同成立,排除页眉、地址中的孤立数字。"""
|
||||
if not is_valid_line_start_value(_text_in_horizontal_region(band, start_region)):
|
||||
return False
|
||||
evidence_fields = [
|
||||
item for item in main_fields
|
||||
if item.get('field_code') != line_start_field_code and item.get('field_code') in {
|
||||
'part_number', 'customer_part_number', 'aws_part_number',
|
||||
}
|
||||
]
|
||||
return all(
|
||||
_is_compact_identifier(
|
||||
_text_in_horizontal_region(band, _absolute_relative_region(table_bbox, field['region']))
|
||||
"""按当前主视觉行的 Schema 字段值判断起行,不依赖业务字段名。"""
|
||||
if schema_fields is None:
|
||||
if not is_valid_line_start_value(_text_in_horizontal_region(band, start_region)):
|
||||
return False
|
||||
# 低层旧调用未提供 Schema 时仍使用通用文本形态交叉验证,
|
||||
# 但不再按业务字段名建立白名单。
|
||||
evidence_fields = [
|
||||
item for item in main_fields
|
||||
if isinstance(item, dict)
|
||||
and item.get('field_code') != line_start_field_code
|
||||
and isinstance(item.get('region'), dict)
|
||||
]
|
||||
return all(
|
||||
_is_compact_identifier(
|
||||
_text_in_horizontal_region(band, _absolute_relative_region(table_bbox, field['region']))
|
||||
)
|
||||
for field in evidence_fields
|
||||
)
|
||||
for field in evidence_fields
|
||||
)
|
||||
values: dict[str, str] = {}
|
||||
for field in main_fields:
|
||||
if not isinstance(field, dict) or not isinstance(field.get('region'), dict):
|
||||
continue
|
||||
code = str(field.get('field_code') or '')
|
||||
if not code or code not in schema_fields:
|
||||
continue
|
||||
raw = _adaptive_field_raw(
|
||||
band=band,
|
||||
region=_absolute_relative_region(table_bbox, field['region']),
|
||||
field_code=code,
|
||||
)
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
|
||||
)
|
||||
values.update(extracted)
|
||||
return _is_record_start(values, main_fields, line_start_field_code, schema_fields)
|
||||
|
||||
|
||||
def _is_compact_identifier(raw: str) -> bool:
|
||||
@@ -623,6 +1094,7 @@ def _reconstruct_relative_y_profile_rows(
|
||||
include_deleted: bool,
|
||||
line_start_field_code: str,
|
||||
include_unanchored_rows: bool,
|
||||
schema_fields: dict[str, dict[str, Any]] | None = None,
|
||||
) -> list[CoordinateProfileLogicalRow] | None:
|
||||
"""
|
||||
将单个多视觉行物理框按父行内相对 Y 投影到每条重复明细。
|
||||
@@ -647,6 +1119,18 @@ def _reconstruct_relative_y_profile_rows(
|
||||
)
|
||||
if start_field is None:
|
||||
return None
|
||||
|
||||
def values_for_band(band: list[tuple[int, PositionedCharacter]]) -> dict[str, str]:
|
||||
values: dict[str, str] = {}
|
||||
for field in fields:
|
||||
code = str(field.get('field_code') or '')
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
raw = _text_in_horizontal_region(band, region)
|
||||
extracted = extract_profile_field_value(
|
||||
extractor_key=str(field.get('extractor_key') or 'direct'), field_code=code, raw=raw,
|
||||
)
|
||||
values.update(extracted)
|
||||
return values
|
||||
bands = _group_visual_rows(glyphs)
|
||||
usable_bands: list[tuple[int, list[tuple[int, PositionedCharacter]]]] = []
|
||||
for row_index, band in enumerate(bands):
|
||||
@@ -661,16 +1145,17 @@ def _reconstruct_relative_y_profile_rows(
|
||||
anchors: list[int] = []
|
||||
for index, (_, band) in enumerate(usable_bands):
|
||||
start_text = _text_in_horizontal_region(band, start_region)
|
||||
if is_valid_line_start_value(start_text):
|
||||
if schema_fields is None and is_valid_line_start_value(start_text):
|
||||
anchors.append(index)
|
||||
elif schema_fields is not None:
|
||||
values = values_for_band(band)
|
||||
if _is_record_start(values, fields, line_start_field_code, schema_fields):
|
||||
anchors.append(index)
|
||||
if not anchors:
|
||||
return []
|
||||
|
||||
sample_end = anchors[1] if len(anchors) > 1 else len(usable_bands)
|
||||
sample_record = usable_bands[anchors[0]:sample_end]
|
||||
field_band_indices = _calibrate_field_band_indices(
|
||||
fields=fields, sample_record=sample_record, table_bbox=table_bbox,
|
||||
)
|
||||
start_region = _absolute_relative_region(table_bbox, start_field['region'])
|
||||
expected_anchor_center = (start_region.y0 + start_region.y1) / 2
|
||||
results: list[CoordinateProfileLogicalRow] = []
|
||||
for anchor_index, start in enumerate(anchors):
|
||||
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands)
|
||||
@@ -680,23 +1165,34 @@ def _reconstruct_relative_y_profile_rows(
|
||||
)) for _, band in record)
|
||||
values: dict[str, str] = {}
|
||||
issues: list[str] = []
|
||||
matched_bands, alignment_issues = _match_field_band_groups(
|
||||
fields=fields,
|
||||
record=record,
|
||||
expected_indices=field_band_indices,
|
||||
table_bbox=table_bbox,
|
||||
line_start_field_code=line_start_field_code,
|
||||
)
|
||||
issues.extend(alignment_issues)
|
||||
anchor_box = _band_bbox(record[0][1])
|
||||
delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center
|
||||
for field in fields:
|
||||
code = str(field.get('field_code') or '')
|
||||
if not code:
|
||||
continue
|
||||
band_index = matched_bands.get(id(field))
|
||||
if band_index is None:
|
||||
saved = _absolute_relative_region(table_bbox, field['region'])
|
||||
region = LayoutBBox(
|
||||
x0=saved.x0, y0=saved.y0 + delta_y,
|
||||
x1=saved.x1, y1=saved.y1 + delta_y,
|
||||
)
|
||||
# A visual field box may intentionally span multiple PDF text lines
|
||||
# (for example a wrapped customer part number). The previous
|
||||
# one-band assignment treated that as an ambiguity and dropped the
|
||||
# field, which caused two vertically stacked part-number fields to
|
||||
# become empty or reuse the same prefix. When the configured field
|
||||
# region intersects multiple bands, read all of its own glyphs;
|
||||
# single-band fields retain the calibrated matching behavior.
|
||||
intersecting = [
|
||||
band for _row_index, band in record
|
||||
if _regions_overlap_vertically(region, _band_bbox(band))
|
||||
]
|
||||
if not intersecting:
|
||||
continue
|
||||
region = _absolute_relative_region(table_bbox, field['region'])
|
||||
raw = _text_in_horizontal_region(record[band_index][1], region)
|
||||
raw = _text_in_multiline_region(
|
||||
intersecting, region,
|
||||
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
|
||||
)
|
||||
if not raw:
|
||||
continue
|
||||
extracted = extract_profile_field_value(
|
||||
@@ -708,7 +1204,7 @@ def _reconstruct_relative_y_profile_rows(
|
||||
issues.append(f'coordinate_profile_composite_conflict:{extracted_code}')
|
||||
else:
|
||||
values[extracted_code] = extracted_value
|
||||
if is_valid_line_start_value(values.get(line_start_field_code, '')):
|
||||
if _is_record_start(values, fields, line_start_field_code, schema_fields):
|
||||
results.append(CoordinateProfileLogicalRow(
|
||||
fields=values,
|
||||
source_row_indices=[row_index for row_index, _ in record],
|
||||
@@ -819,6 +1315,86 @@ def suggest_multi_subrow_layouts(
|
||||
return suggestions
|
||||
|
||||
|
||||
def derive_incomplete_table_bbox(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
table_bbox: LayoutBBox | dict[str, Any],
|
||||
) -> dict[str, float] | None:
|
||||
"""从页级字符证据修复只覆盖表头的候选表格框。
|
||||
|
||||
该函数只允许沿原候选框的纵向向下扩展:必须先看到可靠的明细起行锚点,
|
||||
并在其后遇到明确的合计/终止行;否则返回 ``None``。横向边界始终继承原候选,
|
||||
因而不会把页面上的其他表格或普通文本合并进来。
|
||||
|
||||
Args:
|
||||
characters: 同页完整 PDF/OCR 字符坐标,而不是已按错误表框截取的字符。
|
||||
table_bbox: MinerU 或其他结构引擎产出的原始表格候选框。
|
||||
|
||||
Returns:
|
||||
可验证的派生绝对表格框;证据不唯一或缺失时返回 ``None``。
|
||||
"""
|
||||
bbox = table_bbox if isinstance(table_bbox, LayoutBBox) else LayoutBBox.model_validate(table_bbox)
|
||||
if bbox.x1 <= bbox.x0 or bbox.y1 <= bbox.y0:
|
||||
return None
|
||||
try:
|
||||
positioned = [
|
||||
(
|
||||
index,
|
||||
item if isinstance(item, PositionedCharacter)
|
||||
else PositionedCharacter.model_validate(item),
|
||||
)
|
||||
for index, item in enumerate(characters)
|
||||
]
|
||||
except Exception:
|
||||
return None
|
||||
# 只取原表横向范围内的字符,纵向上限使用页面证据的最大 y 值。
|
||||
candidates = [
|
||||
item for item in positioned
|
||||
if bbox.x0 <= (item[1].bbox.x0 + item[1].bbox.x1) / 2 <= bbox.x1
|
||||
and (item[1].bbox.y0 + item[1].bbox.y1) / 2 >= bbox.y0
|
||||
]
|
||||
if not candidates:
|
||||
return None
|
||||
bands = _group_visual_rows(candidates)
|
||||
anchor_bands: list[list[tuple[int, PositionedCharacter]]] = []
|
||||
summary_y0: float | None = None
|
||||
for band in bands:
|
||||
band_bbox = _band_bbox(band)
|
||||
text = ''.join(
|
||||
glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)
|
||||
).strip()
|
||||
if band_bbox.y1 <= bbox.y1:
|
||||
continue
|
||||
if _SUMMARY_PATTERN.search(text):
|
||||
if anchor_bands:
|
||||
summary_y0 = band_bbox.y0
|
||||
break
|
||||
continue
|
||||
if _band_starts_item(band, bbox):
|
||||
anchor_bands.append(band)
|
||||
if not anchor_bands:
|
||||
return None
|
||||
last_data_y1 = max(glyph.bbox.y1 for band in anchor_bands for _, glyph in band)
|
||||
# 续行属于同一表格,但不能将其误当成新的表格边界;取终止行前的最后字符。
|
||||
for band in bands:
|
||||
band_bbox = _band_bbox(band)
|
||||
if band_bbox.y0 < anchor_bands[0][0][1].bbox.y0:
|
||||
continue
|
||||
text = ''.join(
|
||||
glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)
|
||||
).strip()
|
||||
if _SUMMARY_PATTERN.search(text):
|
||||
break
|
||||
last_data_y1 = max(last_data_y1, band_bbox.y1)
|
||||
end_y = summary_y0 if summary_y0 is not None else last_data_y1
|
||||
if end_y <= bbox.y1:
|
||||
return None
|
||||
return {
|
||||
'x0': float(bbox.x0), 'y0': float(bbox.y0),
|
||||
'x1': float(bbox.x1), 'y1': float(end_y),
|
||||
}
|
||||
|
||||
|
||||
def suggest_header_regions(
|
||||
*,
|
||||
characters: list[PositionedCharacter | dict[str, Any]],
|
||||
@@ -1028,7 +1604,7 @@ def reconstruct_multi_subrow_table(
|
||||
continue
|
||||
|
||||
main_values = _band_field_values(band, anchors[0])
|
||||
if is_valid_line_start_value(main_values.get(start_field_code, '')):
|
||||
if _is_record_start(main_values, ordered_layouts[0].get('field_regions') or [], start_field_code):
|
||||
flush()
|
||||
current_fields = main_values
|
||||
current_sources = [row_index]
|
||||
@@ -1196,13 +1772,17 @@ def _absolute_relative_region(table_bbox: LayoutBBox, relative: dict[str, Any])
|
||||
|
||||
|
||||
def _inside_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool:
|
||||
"""仅收集中心在管理员框选区域内的字符,边缘字符不跨区域复制。"""
|
||||
return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1 and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1
|
||||
"""按纵向中心和有效横向重叠收集字符,避免字段边界截断字形。"""
|
||||
return (
|
||||
_inside_horizontal_region(glyph_bbox, region)
|
||||
and region.y0 <= (glyph_bbox.y0 + glyph_bbox.y1) / 2 <= region.y1
|
||||
)
|
||||
|
||||
|
||||
def _inside_horizontal_region(glyph_bbox: LayoutBBox, region: LayoutBBox) -> bool:
|
||||
"""仅按标注框横向范围筛选字符,使同一行版式可应用到整张表的重复明细。"""
|
||||
return region.x0 <= (glyph_bbox.x0 + glyph_bbox.x1) / 2 <= region.x1
|
||||
"""接受与字段框正向相交的字形,防止紧贴边界的料号标点被截断。"""
|
||||
overlap = min(glyph_bbox.x1, region.x1) - max(glyph_bbox.x0, region.x0)
|
||||
return overlap > 0
|
||||
|
||||
|
||||
def _has_relative_y_subregions(parent: dict[str, Any], fields: list[dict[str, Any]]) -> bool:
|
||||
@@ -1325,6 +1905,26 @@ def _text_in_region(
|
||||
return render_positioned_row([glyph for _, glyph in selected], geometry_gap_limit=gap_limit)
|
||||
|
||||
|
||||
def _regions_overlap_vertically(left: LayoutBBox, right: LayoutBBox) -> bool:
|
||||
"""判断字段框与视觉 band 是否有纵向证据交集。"""
|
||||
return min(left.y1, right.y1) > max(left.y0, right.y0)
|
||||
|
||||
|
||||
def _text_in_multiline_region(
|
||||
bands: list[list[tuple[int, PositionedCharacter]]],
|
||||
region: LayoutBBox,
|
||||
*,
|
||||
compact: bool = False,
|
||||
) -> str:
|
||||
"""按视觉行顺序读取跨行字段,料号换行时去除行间空白。"""
|
||||
lines: list[str] = []
|
||||
for band in sorted(bands, key=lambda item: _band_bbox(item).y0):
|
||||
text = _text_in_region(band, region).strip()
|
||||
if text:
|
||||
lines.append(text)
|
||||
return ('' if compact else ' ').join(lines)
|
||||
|
||||
|
||||
def _text_in_horizontal_region(
|
||||
band: list[tuple[int, PositionedCharacter]], region: LayoutBBox,
|
||||
) -> str:
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/coordinate_transform.py
|
||||
|
||||
用途:对冻结 Profile 的归一化几何区域应用 matcher 已证明的受限坐标变换。
|
||||
依赖:标准库数学运算;由 Profile matcher 求解、订单头和订单行解析共同消费。
|
||||
逻辑:默认保持 legacy 绝对坐标;仅接受已应用且通过残差/边界门禁的平移或仿射矩阵,
|
||||
任何无效、过界或无法由稳定锚点证明的变换都返回 None 以进入 Review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from copy import deepcopy
|
||||
from typing import Any
|
||||
|
||||
|
||||
def apply_coordinate_transform_to_region(
|
||||
region: dict[str, Any], *, coordinate_transform: dict[str, Any] | None,
|
||||
) -> dict[str, float] | None:
|
||||
"""将 Profile 相对区域投影到当前文档坐标系,非法变换 fail-closed。
|
||||
|
||||
Args:
|
||||
region: 含 x0/y0/x1/y1 的冻结归一化矩形。
|
||||
coordinate_transform: Matcher 唯一候选附带的 ``status=applied`` 变换;None 表示 legacy。
|
||||
|
||||
Returns:
|
||||
投影后的页内 bbox;矩阵将矩形四角包络,旋转后仍保留完整证据范围。
|
||||
"""
|
||||
try:
|
||||
corners = [
|
||||
(float(region['x0']), float(region['y0'])),
|
||||
(float(region['x0']), float(region['y1'])),
|
||||
(float(region['x1']), float(region['y0'])),
|
||||
(float(region['x1']), float(region['y1'])),
|
||||
]
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if not all(math.isfinite(value) for pair in corners for value in pair):
|
||||
return None
|
||||
if coordinate_transform is None:
|
||||
return _bounded_bbox(corners)
|
||||
matrix = coordinate_transform_matrix(coordinate_transform)
|
||||
if matrix is None:
|
||||
return None
|
||||
return _bounded_bbox([_apply_matrix(matrix, x=x, y=y) for x, y in corners])
|
||||
|
||||
|
||||
def coordinate_transform_matrix(value: dict[str, Any]) -> tuple[float, float, float, float, float, float] | None:
|
||||
"""解析并校验 matcher 输出;无 matrix 的历史 applied 结果仅视为平移。"""
|
||||
if not isinstance(value, dict) or value.get('status') != 'applied':
|
||||
return None
|
||||
raw = value.get('matrix')
|
||||
if isinstance(raw, list) and len(raw) == 6:
|
||||
try:
|
||||
matrix = tuple(float(item) for item in raw)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
else:
|
||||
try:
|
||||
matrix = (1.0, 0.0, float(value['translate_x']), 0.0, 1.0, float(value['translate_y']))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if not all(math.isfinite(item) for item in matrix):
|
||||
return None
|
||||
a, b, _tx, d, e, _ty = matrix
|
||||
determinant = a * e - b * d
|
||||
if determinant <= 0 or determinant < .50 or determinant > 1.50:
|
||||
return None
|
||||
return matrix
|
||||
|
||||
|
||||
def project_coordinate_profile_payload(
|
||||
payload: dict[str, Any], *, coordinate_transform: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""复制并统一投影 Profile 的订单头、表区、行区、字段和终止区,不回写冻结定义。"""
|
||||
if coordinate_transform is None:
|
||||
return deepcopy(payload)
|
||||
projected = deepcopy(payload)
|
||||
|
||||
def project(region: Any) -> bool:
|
||||
if not isinstance(region, dict):
|
||||
return False
|
||||
next_region = apply_coordinate_transform_to_region(region, coordinate_transform=coordinate_transform)
|
||||
if next_region is None:
|
||||
return False
|
||||
region.clear()
|
||||
region.update(next_region)
|
||||
return True
|
||||
|
||||
for layout in projected.get('order_field_layouts') or []:
|
||||
if not isinstance(layout, dict):
|
||||
return None
|
||||
for key in ('absolute_value_region', 'fallback_value_region'):
|
||||
region = layout.get(key)
|
||||
if region is not None and not project(region):
|
||||
return None
|
||||
anchor = layout.get('anchor')
|
||||
if isinstance(anchor, dict) and anchor.get('region') is not None and not project(anchor['region']):
|
||||
return None
|
||||
for table in projected.get('table_regions') or []:
|
||||
if not isinstance(table, dict) or not project(table.get('region')):
|
||||
return None
|
||||
for layout in [*(table.get('header_layouts') or []), *(table.get('line_layouts') or [])]:
|
||||
if not isinstance(layout, dict) or not project(layout.get('region')):
|
||||
return None
|
||||
for field in layout.get('field_regions') or []:
|
||||
if not isinstance(field, dict) or not project(field.get('region')):
|
||||
return None
|
||||
for rule in table.get('termination_rules') or []:
|
||||
anchor = rule.get('anchor') if isinstance(rule, dict) else None
|
||||
if isinstance(anchor, dict) and anchor.get('region') is not None and not project(anchor['region']):
|
||||
return None
|
||||
for region in table.get('exclusion_regions') or []:
|
||||
if not project(region):
|
||||
return None
|
||||
return projected
|
||||
|
||||
|
||||
def _apply_matrix(matrix: tuple[float, float, float, float, float, float], *, x: float, y: float) -> tuple[float, float]:
|
||||
"""应用二维仿射矩阵,输入输出均为页内归一化坐标。"""
|
||||
a, b, tx, d, e, ty = matrix
|
||||
return a * x + b * y + tx, d * x + e * y + ty
|
||||
|
||||
|
||||
def _bounded_bbox(corners: list[tuple[float, float]]) -> dict[str, float] | None:
|
||||
"""将投影角点收敛为页内 bbox;旋转后越页的区域必须 Review。"""
|
||||
if not corners or not all(math.isfinite(value) for pair in corners for value in pair):
|
||||
return None
|
||||
x0, x1 = min(x for x, _ in corners), max(x for x, _ in corners)
|
||||
y0, y1 = min(y for _, y in corners), max(y for _, y in corners)
|
||||
if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1):
|
||||
return None
|
||||
return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
|
||||
@@ -11,6 +11,7 @@ backend/app/services/shipping_notice/document_layout/lifecycle.py
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import gzip
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
@@ -22,6 +23,7 @@ from sqlalchemy import and_, func, or_, update
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderIntake,
|
||||
@@ -51,6 +53,81 @@ ON_DEMAND_COORDINATE_COMPACTION_ISSUES = frozenset({
|
||||
'shipping_document_layout_candidate_glyphs_compacted',
|
||||
'shipping_document_layout_candidate_page_metadata_compacted',
|
||||
})
|
||||
COORDINATE_EVIDENCE_REF_KEY = 'coordinate_evidence_ref'
|
||||
COORDINATE_EVIDENCE_SCHEMA_VERSION = 'shipping_order_coordinate_evidence.v1'
|
||||
|
||||
|
||||
def _coordinate_evidence_bytes(evidence: dict[str, Any]) -> bytes:
|
||||
"""将完整坐标证据以稳定 gzip JSON 编码,供不可变 FileAsset 保存。"""
|
||||
raw = json.dumps(evidence, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode('utf-8')
|
||||
return gzip.compress(raw, compresslevel=6, mtime=0)
|
||||
|
||||
|
||||
def _persist_coordinate_evidence_asset(*, document: ShippingOrderDocument, evidence: dict[str, Any]) -> dict[str, Any] | None:
|
||||
"""复用现有 FileAsset/MinIO 保存完整坐标证据并返回轻量引用。"""
|
||||
tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
if not any(isinstance(value, list) and value for value in (*tables.values(), *page_glyphs.values())):
|
||||
return None
|
||||
from app.services.file_assets.service import create_derived_file_asset_from_bytes
|
||||
|
||||
parent = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None
|
||||
intake = db.session.get(ShippingOrderIntake, int(document.intake_id))
|
||||
user_id = getattr(intake, 'user_id', None)
|
||||
if parent is None or user_id is None:
|
||||
return None
|
||||
data = _coordinate_evidence_bytes(evidence)
|
||||
asset, created = create_derived_file_asset_from_bytes(
|
||||
user_id=int(user_id), parent=parent, data=data,
|
||||
filename=f'{document.id}-coordinate-evidence.json.gz',
|
||||
mime_type='application/json+gzip', asset_role='layout_coordinate_evidence',
|
||||
)
|
||||
asset.lifecycle_status = 'referenced'
|
||||
asset.expires_at = None
|
||||
asset.deleted_at = None
|
||||
if created or int(asset.reference_count or 0) == 0:
|
||||
asset.reference_count = max(int(asset.reference_count or 0), 1)
|
||||
return {
|
||||
'asset_no': str(asset.asset_no),
|
||||
'checksum': hashlib.sha256(data).hexdigest(),
|
||||
'size': len(data),
|
||||
'schema_version': str(evidence.get('version') or COORDINATE_EVIDENCE_SCHEMA_VERSION),
|
||||
}
|
||||
|
||||
|
||||
def _has_coordinate_evidence(evidence: Any) -> bool:
|
||||
"""判断证据是否含有可外置的字符集合;空占位结构保持原快照兼容。"""
|
||||
if not isinstance(evidence, dict):
|
||||
return False
|
||||
for key in ('tables', 'page_glyphs'):
|
||||
values = evidence.get(key)
|
||||
if isinstance(values, dict) and any(isinstance(item, list) and item for item in values.values()):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _hydrate_coordinate_evidence(*, payload: dict[str, Any], document: ShippingOrderDocument) -> dict[str, Any]:
|
||||
"""从现有 FileAsset 引用加载完整坐标证据;读取失败时保持缺证据状态。"""
|
||||
ref = payload.get(COORDINATE_EVIDENCE_REF_KEY)
|
||||
if not isinstance(ref, dict):
|
||||
return payload
|
||||
asset_no = str(ref.get('asset_no') or '').strip()
|
||||
if not asset_no:
|
||||
return payload
|
||||
asset = FileAsset.query.filter_by(asset_no=asset_no, deleted_at=None).first()
|
||||
if asset is None:
|
||||
return payload
|
||||
try:
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
evidence = json.loads(gzip.decompress(read_asset_bytes(asset)).decode('utf-8'))
|
||||
except Exception:
|
||||
_LOGGER.exception('coordinate evidence asset load failed document_id=%s asset_no=%s', document.id, asset_no)
|
||||
return payload
|
||||
if _has_coordinate_evidence(evidence):
|
||||
hydrated = dict(payload)
|
||||
hydrated['coordinate_evidence'] = evidence
|
||||
return hydrated
|
||||
return payload
|
||||
|
||||
|
||||
def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload: dict[str, Any]) -> bool:
|
||||
@@ -61,10 +138,8 @@ def _ready_layout_evidence_complete(*, document: ShippingOrderDocument, payload:
|
||||
"""
|
||||
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
|
||||
return True
|
||||
evidence = payload.get('coordinate_evidence') if isinstance(payload.get('coordinate_evidence'), dict) else {}
|
||||
complete = isinstance(evidence.get('pages'), dict) and isinstance(evidence.get('page_glyphs'), dict)
|
||||
recoverable = bool(document.asset_id) and isinstance(payload.get('layout_candidate'), dict)
|
||||
return complete or recoverable
|
||||
ref = payload.get(COORDINATE_EVIDENCE_REF_KEY)
|
||||
return isinstance(ref, dict) and bool(str(ref.get('asset_no') or '').strip())
|
||||
|
||||
|
||||
def _layout_version_reusable(*, document: ShippingOrderDocument, version: ShippingDocumentLayoutVersion) -> bool:
|
||||
@@ -188,6 +263,13 @@ def _fit_layout_payload_to_budget(
|
||||
|
||||
coordinate_evidence = candidate.get('coordinate_evidence')
|
||||
if isinstance(coordinate_evidence, dict):
|
||||
# [STEP] 仅在即将删除逐字符坐标时固定模板身份特征,避免改变未压缩快照的
|
||||
# checksum;后续 matcher 只能读取此投影,不能退化为页面/表框高分猜测。
|
||||
if coordinate_evidence.get('page_glyphs') is not None or coordinate_evidence.get('tables') is not None:
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
build_layout_matching_features,
|
||||
)
|
||||
candidate['matching_features'] = build_layout_matching_features(layout=candidate)
|
||||
if coordinate_evidence.pop('page_glyphs', None) is not None:
|
||||
issues.append('shipping_document_layout_page_glyphs_compacted')
|
||||
if coordinate_evidence.pop('tables', None) is not None:
|
||||
@@ -200,14 +282,17 @@ def _fit_layout_payload_to_budget(
|
||||
|
||||
def current_layout_snapshot(document: ShippingOrderDocument) -> dict[str, Any] | None:
|
||||
"""读取 Document 当前可用冻结 payload;失败历史版本永不作为运行输入。"""
|
||||
version = document.current_layout_version
|
||||
version = (
|
||||
db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id))
|
||||
if document.current_layout_version_id else document.current_layout_version
|
||||
)
|
||||
if (
|
||||
version is None
|
||||
or str(version.status or '') not in CURRENT_LAYOUT_STATUSES
|
||||
or not isinstance(version.payload_json, dict)
|
||||
):
|
||||
return None
|
||||
return dict(version.payload_json)
|
||||
return _hydrate_coordinate_evidence(payload=dict(version.payload_json), document=document)
|
||||
|
||||
|
||||
def _bind_inline_xfa_structure_analysis(
|
||||
@@ -315,6 +400,16 @@ def record_inline_layout_snapshot(
|
||||
超大 payload 不落正文,只创建 failed 审计版本;相同内容/parser/checksum 重试复用旧终态。
|
||||
"""
|
||||
payload = dict(snapshot)
|
||||
evidence = payload.get('coordinate_evidence')
|
||||
if _has_coordinate_evidence(evidence):
|
||||
evidence_ref = _persist_coordinate_evidence_asset(document=document, evidence=evidence)
|
||||
if evidence_ref is None and str(payload.get('status') or '') == 'ready':
|
||||
payload = {**payload, 'status': 'failed', 'issues': [
|
||||
*list(payload.get('issues') or []), 'shipping_document_layout_coordinate_evidence_persist_failed',
|
||||
]}
|
||||
elif evidence_ref is not None:
|
||||
payload.pop('coordinate_evidence', None)
|
||||
payload[COORDINATE_EVIDENCE_REF_KEY] = evidence_ref
|
||||
parser_key = str(parser_key or current_layout_parser_key())
|
||||
max_bytes = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
|
||||
@@ -936,19 +1031,30 @@ def complete_layout_version(
|
||||
if version is None or version.status != 'running' or version.lease_token != lease_token:
|
||||
db.session.rollback()
|
||||
return False
|
||||
payload = dict(snapshot)
|
||||
evidence = payload.get('coordinate_evidence')
|
||||
if _has_coordinate_evidence(evidence):
|
||||
evidence_ref = _persist_coordinate_evidence_asset(document=version.document, evidence=evidence)
|
||||
if evidence_ref is None and str(payload.get('status') or '') == 'ready':
|
||||
payload = {**payload, 'status': 'failed', 'issues': [
|
||||
*list(payload.get('issues') or []), 'shipping_document_layout_coordinate_evidence_persist_failed',
|
||||
]}
|
||||
elif evidence_ref is not None:
|
||||
payload.pop('coordinate_evidence', None)
|
||||
payload[COORDINATE_EVIDENCE_REF_KEY] = evidence_ref
|
||||
max_bytes = max(int(current_app.config.get(
|
||||
'SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES', 2_000_000,
|
||||
)), 1)
|
||||
fitted_snapshot, compact_issues, payload_size = _fit_layout_payload_to_budget(
|
||||
snapshot, max_bytes=max_bytes,
|
||||
payload, max_bytes=max_bytes,
|
||||
)
|
||||
stored_for_identity = fitted_snapshot if fitted_snapshot is not None else snapshot
|
||||
stored_for_identity = fitted_snapshot if fitted_snapshot is not None else payload
|
||||
checksum, _ = canonical_layout_payload(stored_for_identity)
|
||||
issues = sorted({str(item) for item in (snapshot.get('issues') or []) if str(item)} | set(compact_issues))
|
||||
provider_status = str(snapshot.get('status') or 'failed')
|
||||
issues = sorted({str(item) for item in (payload.get('issues') or []) if str(item)} | set(compact_issues))
|
||||
provider_status = str(payload.get('status') or 'failed')
|
||||
status = provider_status if provider_status in TERMINAL_LAYOUT_STATUSES else 'failed'
|
||||
if status == 'ready' and not _ready_layout_evidence_complete(
|
||||
document=version.document, payload=snapshot,
|
||||
document=version.document, payload=payload,
|
||||
):
|
||||
status = 'failed'
|
||||
issues = sorted(set(issues) | {'shipping_document_layout_coordinate_evidence_incomplete'})
|
||||
@@ -960,12 +1066,12 @@ def complete_layout_version(
|
||||
status = 'failed'
|
||||
now = datetime.utcnow()
|
||||
version.status = status
|
||||
version.parser_version = str(snapshot.get('provider_version') or '')[:64] or None
|
||||
version.backend = str(snapshot.get('backend') or LAYOUT_BACKEND)[:32]
|
||||
version.parser_version = str(payload.get('provider_version') or '')[:64] or None
|
||||
version.backend = str(payload.get('backend') or LAYOUT_BACKEND)[:32]
|
||||
version.payload_json = stored_payload
|
||||
version.payload_checksum = checksum
|
||||
version.payload_size_bytes = payload_size
|
||||
version.quality_json = dict(snapshot['capability']) if isinstance(snapshot.get('capability'), dict) else None
|
||||
version.quality_json = dict(payload['capability']) if isinstance(payload.get('capability'), dict) else None
|
||||
version.issues_json = sorted(set(issues))
|
||||
version.lease_token = None
|
||||
version.finished_at = now
|
||||
|
||||
@@ -93,56 +93,62 @@ def extract_native_pdf_pages(
|
||||
"""
|
||||
if not content or render_scale <= 0:
|
||||
raise ValueError('native PDF content and positive render scale are required')
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
pages: list[NativePdfPage] = []
|
||||
for page_index in range(len(pdf)):
|
||||
page = pdf[page_index]
|
||||
width, height = page.get_size()
|
||||
text_page = page.get_textpage()
|
||||
characters: list[PositionedCharacter] = []
|
||||
pending_boundary: str = 'none'
|
||||
for char_index in range(text_page.count_chars()):
|
||||
text = text_page.get_text_range(char_index, 1)
|
||||
if not text:
|
||||
continue
|
||||
if not normalize_layout_text(text):
|
||||
if any(character in {'\r', '\n'} for character in text):
|
||||
pending_boundary = 'line_break'
|
||||
elif pending_boundary == 'none' and any(character.isspace() for character in text):
|
||||
pending_boundary = 'space'
|
||||
continue
|
||||
left, bottom, right, top = text_page.get_charbox(char_index, loose=True)
|
||||
if right <= left or top <= bottom:
|
||||
# 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。
|
||||
pending_boundary = 'none'
|
||||
continue
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
try:
|
||||
for page_index in range(len(pdf)):
|
||||
page = pdf[page_index]
|
||||
text_page = None
|
||||
try:
|
||||
# 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。
|
||||
characters.append(PositionedCharacter(
|
||||
text=text,
|
||||
bbox=LayoutBBox(
|
||||
x0=left, y0=height - top, x1=right, y1=height - bottom,
|
||||
),
|
||||
source_index=char_index,
|
||||
boundary_before=pending_boundary,
|
||||
width, height = page.get_size()
|
||||
text_page = page.get_textpage()
|
||||
characters: list[PositionedCharacter] = []
|
||||
pending_boundary: str = 'none'
|
||||
for char_index in range(text_page.count_chars()):
|
||||
text = text_page.get_text_range(char_index, 1)
|
||||
if not text:
|
||||
continue
|
||||
if not normalize_layout_text(text):
|
||||
if any(character in {'\r', '\n'} for character in text):
|
||||
pending_boundary = 'line_break'
|
||||
elif pending_boundary == 'none' and any(character.isspace() for character in text):
|
||||
pending_boundary = 'space'
|
||||
continue
|
||||
left, bottom, right, top = text_page.get_charbox(char_index, loose=True)
|
||||
if right <= left or top <= bottom:
|
||||
# 非空白可见字符若无有效坐标,不得把之前的空白错误转嫁到后续字符。
|
||||
pending_boundary = 'none'
|
||||
continue
|
||||
try:
|
||||
# 不修改 PDFium 原始坐标;仅转为左上原点页面坐标。
|
||||
characters.append(PositionedCharacter(
|
||||
text=text,
|
||||
bbox=LayoutBBox(
|
||||
x0=left, y0=height - top, x1=right, y1=height - bottom,
|
||||
),
|
||||
source_index=char_index,
|
||||
boundary_before=pending_boundary,
|
||||
))
|
||||
pending_boundary = 'none'
|
||||
except ValueError:
|
||||
pending_boundary = 'none'
|
||||
continue
|
||||
characters = _assign_page_line_ids(characters, page_no=page_index + 1)
|
||||
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
|
||||
pages.append(NativePdfPage(
|
||||
page_no=page_index + 1,
|
||||
width=float(width),
|
||||
height=float(height),
|
||||
rotation=rotation if rotation in {0, 90, 180, 270} else 0,
|
||||
characters=characters,
|
||||
image=_render_native_pdf_page(page, render_scale) if render_images else None,
|
||||
))
|
||||
pending_boundary = 'none'
|
||||
except ValueError:
|
||||
pending_boundary = 'none'
|
||||
continue
|
||||
characters = _assign_page_line_ids(characters, page_no=page_index + 1)
|
||||
rotation = int(getattr(page, 'get_rotation', lambda: 0)() or 0) % 360
|
||||
pages.append(NativePdfPage(
|
||||
page_no=page_index + 1,
|
||||
width=float(width),
|
||||
height=float(height),
|
||||
rotation=rotation if rotation in {0, 90, 180, 270} else 0,
|
||||
characters=characters,
|
||||
image=(
|
||||
np.asarray(page.render(scale=render_scale).to_numpy()).copy()
|
||||
if render_images else None
|
||||
),
|
||||
))
|
||||
finally:
|
||||
if text_page is not None:
|
||||
text_page.close()
|
||||
page.close()
|
||||
finally:
|
||||
pdf.close()
|
||||
return pages
|
||||
|
||||
|
||||
@@ -191,27 +197,43 @@ def attach_native_pdf_page_images(
|
||||
return []
|
||||
if all(page.image is not None for page in pages):
|
||||
return list(pages)
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
attached: list[NativePdfPage] = []
|
||||
for page in pages:
|
||||
if page.image is not None:
|
||||
attached.append(page)
|
||||
continue
|
||||
index = int(page.page_no) - 1
|
||||
if index < 0 or index >= len(pdf):
|
||||
raise ValueError('native PDF page_no is out of range for image attach')
|
||||
image = np.asarray(pdf[index].render(scale=render_scale).to_numpy()).copy()
|
||||
attached.append(NativePdfPage(
|
||||
page_no=page.page_no,
|
||||
width=page.width,
|
||||
height=page.height,
|
||||
rotation=page.rotation,
|
||||
characters=page.characters,
|
||||
image=image,
|
||||
))
|
||||
pdf = pdfium.PdfDocument(content)
|
||||
try:
|
||||
for native_page in pages:
|
||||
if native_page.image is not None:
|
||||
attached.append(native_page)
|
||||
continue
|
||||
index = int(native_page.page_no) - 1
|
||||
if index < 0 or index >= len(pdf):
|
||||
raise ValueError('native PDF page_no is out of range for image attach')
|
||||
page = pdf[index]
|
||||
try:
|
||||
image = _render_native_pdf_page(page, render_scale)
|
||||
finally:
|
||||
page.close()
|
||||
attached.append(NativePdfPage(
|
||||
page_no=native_page.page_no,
|
||||
width=native_page.width,
|
||||
height=native_page.height,
|
||||
rotation=native_page.rotation,
|
||||
characters=native_page.characters,
|
||||
image=image,
|
||||
))
|
||||
finally:
|
||||
pdf.close()
|
||||
return attached
|
||||
|
||||
|
||||
def _render_native_pdf_page(page: Any, render_scale: float) -> np.ndarray:
|
||||
"""将 PDFium 页面复制为独立 ndarray 后立即释放临时 bitmap,避免其 finalizer 滞留到进程退出。"""
|
||||
bitmap = page.render(scale=render_scale)
|
||||
try:
|
||||
return np.asarray(bitmap.to_numpy()).copy()
|
||||
finally:
|
||||
bitmap.close()
|
||||
|
||||
|
||||
def build_native_pdf_text_table_fallbacks(
|
||||
content: bytes,
|
||||
*,
|
||||
@@ -232,17 +254,24 @@ def build_native_pdf_text_table_fallbacks(
|
||||
continue
|
||||
start_index, end_index = header
|
||||
header_lines = lines[start_index:end_index + 1]
|
||||
body_lines = lines[end_index + 1:]
|
||||
stop_index = next((
|
||||
index for index, line in enumerate(body_lines)
|
||||
if _is_fallback_total(line) or _is_fallback_separator(line)
|
||||
), len(body_lines))
|
||||
body_lines = body_lines[:stop_index]
|
||||
if not body_lines:
|
||||
continue
|
||||
boundaries = _fallback_column_boundaries(header_lines, page.width)
|
||||
if len(boundaries) < 3:
|
||||
continue
|
||||
body_lines: list[dict[str, Any]] = []
|
||||
has_data_row = False
|
||||
for line in lines[end_index + 1:]:
|
||||
if _is_fallback_total(line):
|
||||
break
|
||||
if _is_fallback_separator(line):
|
||||
# 采购订单常在表头和首条明细之间画横线;只有已见明细后的横线才是表尾。
|
||||
if has_data_row:
|
||||
break
|
||||
continue
|
||||
body_lines.append(line)
|
||||
if _fallback_data_row(_fallback_cells([line], boundaries)):
|
||||
has_data_row = True
|
||||
if not body_lines:
|
||||
continue
|
||||
header_cells = _fallback_cells(header_lines, boundaries)
|
||||
body_cells = [_fallback_cells([line], boundaries) for line in body_lines]
|
||||
if not any(_fallback_data_row(row) for row in body_cells):
|
||||
|
||||
+47
-8
@@ -29,13 +29,32 @@ def ensure_on_demand_coordinate_evidence(
|
||||
for key in legacy_keys
|
||||
if isinstance(layout.get(key), dict)
|
||||
}
|
||||
# Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。
|
||||
# Run 快照可能早于最近一次布局重试;当前 Layout 是最新解析事实,同页坐标必须
|
||||
# 优先于 Run 快照,后者只能补齐当前 Layout 尚未保存的页或表。
|
||||
current_version = getattr(document, 'current_layout_version', None)
|
||||
current_payload = getattr(current_version, 'payload_json', None)
|
||||
if isinstance(current_payload, dict):
|
||||
current_evidence = current_payload.get('coordinate_evidence')
|
||||
if isinstance(current_evidence, dict):
|
||||
evidence = {**current_evidence, **evidence}
|
||||
merged_current = dict(evidence)
|
||||
for key in ('pages', 'page_glyphs', 'tables'):
|
||||
snapshot_mapping = _coordinate_mapping(evidence.get(key))
|
||||
current_mapping = _coordinate_mapping(current_evidence.get(key))
|
||||
# 仅合并实际存在的坐标类别。空 tables 不得写入轻量快照,否则会让
|
||||
# 顶层业务 tables 列表与坐标表映射的边界在后续调用中变得模糊。
|
||||
if snapshot_mapping or current_mapping:
|
||||
merged_current[key] = {**snapshot_mapping, **current_mapping}
|
||||
snapshot_sources = _coordinate_mapping(evidence.get('sources'))
|
||||
current_sources = _coordinate_mapping(current_evidence.get('sources'))
|
||||
merged_current['sources'] = {
|
||||
**snapshot_sources,
|
||||
**current_sources,
|
||||
'pages': {
|
||||
**_coordinate_mapping(snapshot_sources.get('pages')),
|
||||
**_coordinate_mapping(current_sources.get('pages')),
|
||||
},
|
||||
}
|
||||
evidence = merged_current
|
||||
for key in ('pages', 'page_glyphs', 'sources', 'tables'):
|
||||
if key not in evidence and isinstance(current_payload.get(key), dict):
|
||||
evidence[key] = current_payload[key]
|
||||
@@ -44,8 +63,24 @@ def ensure_on_demand_coordinate_evidence(
|
||||
sources = _coordinate_mapping(evidence.get('sources'))
|
||||
source_pages = _coordinate_mapping(sources.get('pages'))
|
||||
tables = _coordinate_mapping(evidence.get('tables'))
|
||||
if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}):
|
||||
return layout
|
||||
available_page_nos = {
|
||||
int(page_no) for page_no, glyphs in page_glyphs.items()
|
||||
if str(page_no).isdigit() and isinstance(glyphs, list) and glyphs
|
||||
}
|
||||
if page_nos is not None and page_nos.issubset(available_page_nos):
|
||||
# 当前 Layout 可能补齐了 Run 冻结快照中已被压缩的坐标证据。必须返回
|
||||
# 合并后的运行期 Layout;返回原 layout 会让调用方重新丢失这些字符坐标,
|
||||
# 从而使同版式 PDF 因快照压缩路径不同进入不同的匹配分支。
|
||||
next_layout = dict(layout)
|
||||
merged_evidence = {**evidence, 'pages': pages}
|
||||
if page_glyphs:
|
||||
merged_evidence['page_glyphs'] = page_glyphs
|
||||
if tables:
|
||||
merged_evidence['tables'] = tables
|
||||
if sources or source_pages:
|
||||
merged_evidence['sources'] = {**sources, 'pages': source_pages}
|
||||
next_layout['coordinate_evidence'] = merged_evidence
|
||||
return next_layout
|
||||
tables_by_page: dict[int, list[dict[str, Any]]] = {}
|
||||
for raw_table in layout.get('tables') or []:
|
||||
if not isinstance(raw_table, dict):
|
||||
@@ -108,8 +143,12 @@ def ensure_on_demand_coordinate_evidence(
|
||||
if table_id and chars:
|
||||
tables[table_id] = chars
|
||||
next_layout = dict(layout)
|
||||
next_layout['coordinate_evidence'] = {
|
||||
**evidence, 'pages': pages, 'page_glyphs': page_glyphs,
|
||||
'tables': tables, 'sources': {**sources, 'pages': source_pages},
|
||||
}
|
||||
merged_evidence = {**evidence, 'pages': pages}
|
||||
if page_glyphs:
|
||||
merged_evidence['page_glyphs'] = page_glyphs
|
||||
if tables:
|
||||
merged_evidence['tables'] = tables
|
||||
if sources or source_pages:
|
||||
merged_evidence['sources'] = {**sources, 'pages': source_pages}
|
||||
next_layout['coordinate_evidence'] = merged_evidence
|
||||
return next_layout
|
||||
@@ -14,12 +14,16 @@ from typing import Any, Literal
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.contracts import LayoutBBox
|
||||
from app.services.shipping_notice.document_layout.coordinate_transform import (
|
||||
project_coordinate_profile_payload,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import render_positioned_row
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
AnchorRelativeRegion,
|
||||
AnchorRule,
|
||||
OrderCoordinateProfile,
|
||||
OrderFieldLayout,
|
||||
ReferencePageFrame,
|
||||
RelativeRegion,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
@@ -49,6 +53,8 @@ class OrderFieldExtraction(BaseModel):
|
||||
def extract_order_fields(
|
||||
*, profile: OrderCoordinateProfile, schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_evidence: dict[str, Any], allow_ocr_preview_fallback: bool = False,
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
allow_fixed_region_confirmation: bool = False,
|
||||
) -> list[OrderFieldExtraction]:
|
||||
"""
|
||||
用唯一文字锚点和相对值区读取订单字段,缺少页级证据时严格失败关闭。
|
||||
@@ -59,24 +65,53 @@ def extract_order_fields(
|
||||
coordinate_evidence: 冻结页尺寸、page_glyphs 与来源;不接受表格内 glyph 兜底。
|
||||
allow_ocr_preview_fallback: 仅管理端视觉样本值预览可启用。它允许已确认的
|
||||
PDF 坐标字段临时读取 OCR 候选,但结果仍固定为 needs_review,不能用于正式运行时取值。
|
||||
allow_fixed_region_confirmation: 仅唯一匹配模板的正式运行或当前模板盲测回放可启用。
|
||||
它只允许原生 PDF 坐标的无标签固定区域成为 confirmed;OCR、未匹配模板和
|
||||
普通预览仍保持 needs_review。
|
||||
|
||||
Returns:
|
||||
每个已绑定布局对应一个候选,按模板声明顺序返回。
|
||||
"""
|
||||
effective_profile = _project_coordinate_transform(profile, coordinate_transform)
|
||||
if effective_profile is None:
|
||||
return [
|
||||
_unavailable(layout, 'order_field_coordinate_transform_invalid')
|
||||
for layout in profile.order_field_layouts
|
||||
]
|
||||
return [
|
||||
_extract_layout(
|
||||
layout=layout,
|
||||
schema_fields=schema_fields,
|
||||
coordinate_evidence=coordinate_evidence,
|
||||
reference_page_frames=effective_profile.reference_page_frames,
|
||||
allow_ocr_preview_fallback=allow_ocr_preview_fallback,
|
||||
allow_fixed_region_confirmation=allow_fixed_region_confirmation,
|
||||
)
|
||||
for layout in profile.order_field_layouts
|
||||
for layout in effective_profile.order_field_layouts
|
||||
]
|
||||
|
||||
|
||||
def _project_coordinate_transform(
|
||||
profile: OrderCoordinateProfile, coordinate_transform: dict[str, Any] | None,
|
||||
) -> OrderCoordinateProfile | None:
|
||||
"""把 matcher 唯一确认的统一变换投影到订单头布局,禁止二次估算。"""
|
||||
if coordinate_transform is None:
|
||||
return profile
|
||||
payload = project_coordinate_profile_payload(
|
||||
profile.model_dump(mode='python'), coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if payload is None:
|
||||
return None
|
||||
try:
|
||||
return OrderCoordinateProfile.model_validate(payload)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _extract_layout(
|
||||
*, layout: OrderFieldLayout, schema_fields: dict[str, dict[str, Any]], coordinate_evidence: dict[str, Any],
|
||||
allow_ocr_preview_fallback: bool = False,
|
||||
reference_page_frames: dict[int, ReferencePageFrame],
|
||||
allow_ocr_preview_fallback: bool = False, allow_fixed_region_confirmation: bool = False,
|
||||
) -> OrderFieldExtraction:
|
||||
"""处理一个订单字段布局,并把任何不确定性保留为 Review/Unavailable 而非猜测。"""
|
||||
config = schema_fields.get(layout.field_id)
|
||||
@@ -112,6 +147,7 @@ def _extract_layout(
|
||||
|
||||
results: list[OrderFieldExtraction] = []
|
||||
for page_no, glyphs, width, height, source in candidates:
|
||||
reference_page_frame = reference_page_frames.get(page_no)
|
||||
if not _source_allowed(
|
||||
layout,
|
||||
config=config,
|
||||
@@ -123,18 +159,25 @@ def _extract_layout(
|
||||
if layout.anchor is None:
|
||||
results.append(_read_value_region(
|
||||
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
|
||||
region=_absolute_relative_region(layout.fallback_value_region, width=width, height=height), anchor_bbox=None,
|
||||
fallback=True,
|
||||
region=_absolute_relative_region(
|
||||
layout.fallback_value_region, width=width, height=height,
|
||||
reference_page_frame=reference_page_frame,
|
||||
), anchor_bbox=None,
|
||||
fallback=not (allow_fixed_region_confirmation and source == 'pdf_coordinate'),
|
||||
))
|
||||
continue
|
||||
matches = _find_anchor_matches(
|
||||
glyphs, layout.anchor, page_width=width, page_height=height,
|
||||
ignore_reference_region=_uses_movable_anchor_value_region(layout=layout, width=width, height=height),
|
||||
reference_page_frame=reference_page_frame,
|
||||
ignore_reference_region=_uses_movable_anchor_value_region(
|
||||
layout=layout, width=width, height=height, reference_page_frame=reference_page_frame,
|
||||
),
|
||||
)
|
||||
if not matches:
|
||||
reference_anchor = (
|
||||
_anchor_from_reference_region(
|
||||
glyphs, anchor=layout.anchor, page_width=width, page_height=height,
|
||||
reference_page_frame=reference_page_frame,
|
||||
)
|
||||
if _is_placeholder_anchor_text(layout.anchor.text) else None
|
||||
)
|
||||
@@ -144,7 +187,10 @@ def _extract_layout(
|
||||
# intent, but it must remain review-only until the label is fixed.
|
||||
results.append(_read_value_region(
|
||||
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
|
||||
region=_absolute_value_region(layout=layout, anchor=reference_anchor, width=width, height=height),
|
||||
region=_absolute_value_region(
|
||||
layout=layout, anchor=reference_anchor, width=width, height=height,
|
||||
reference_page_frame=reference_page_frame,
|
||||
),
|
||||
anchor_bbox=reference_anchor, fallback=False,
|
||||
review_issue='order_field_anchor_text_mismatch',
|
||||
))
|
||||
@@ -160,7 +206,10 @@ def _extract_layout(
|
||||
anchor_bbox, _indices = matches[0]
|
||||
results.append(_read_value_region(
|
||||
layout=layout, config=config, glyphs=glyphs, page_no=page_no, source=source,
|
||||
region=_absolute_value_region(layout=layout, anchor=anchor_bbox, width=width, height=height), anchor_bbox=anchor_bbox, fallback=False,
|
||||
region=_absolute_value_region(
|
||||
layout=layout, anchor=anchor_bbox, width=width, height=height,
|
||||
reference_page_frame=reference_page_frame,
|
||||
), anchor_bbox=anchor_bbox, fallback=False,
|
||||
))
|
||||
usable = [item for item in results if item.status != 'unavailable']
|
||||
if len(usable) == 1:
|
||||
@@ -294,6 +343,7 @@ def _recover_trailing_date_glyph(*, text: str, glyphs: list[dict[str, Any]], reg
|
||||
|
||||
def _find_anchor_matches(
|
||||
glyphs: list[dict[str, Any]], anchor: AnchorRule, *, page_width: float | None = None, page_height: float | None = None,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
ignore_reference_region: bool = False,
|
||||
) -> list[tuple[LayoutBBox, list[int]]]:
|
||||
"""在每个视觉行内执行精确标签匹配,返回去重后的字符联合框。"""
|
||||
@@ -321,23 +371,22 @@ def _find_anchor_matches(
|
||||
compact, position=position, length=len(normalized), anchor=anchor,
|
||||
):
|
||||
bbox = _union_bbox([item for _index, item in consumed])
|
||||
if ignore_reference_region or _anchor_bbox_in_reference_region(
|
||||
bbox, anchor=anchor, page_width=page_width, page_height=page_height,
|
||||
):
|
||||
matches.append((bbox, [index for index, _item in consumed]))
|
||||
# 先按文本收集全部精确命中;保存的参考框只用于多个同名标签
|
||||
# 的消歧,不能让同版式样本中唯一但位置变化的标签直接丢失。
|
||||
matches.append((bbox, [index for index, _item in consumed]))
|
||||
start = position + max(len(label), 1)
|
||||
unique: dict[tuple[float, float, float, float], tuple[LayoutBBox, list[int]]] = {}
|
||||
for bbox, indices in matches:
|
||||
unique[(bbox.x0, bbox.y0, bbox.x1, bbox.y1)] = (bbox, indices)
|
||||
resolved = list(unique.values())
|
||||
# An unlocked label may shift between documents, so its reference box must
|
||||
# not suppress a sole match. When the same label occurs multiple times,
|
||||
# however, the saved canvas position is decisive evidence for this sample.
|
||||
# 唯一文本命中不受历史参考框限制;同名标签多次出现时,保存位置才是
|
||||
# 当前样本的消歧证据。若位置也无法唯一消歧,调用方会进入人工复核。
|
||||
if len(resolved) > 1 and anchor.region is not None and page_width and page_height:
|
||||
positioned = [
|
||||
item for item in resolved
|
||||
if _anchor_bbox_in_reference_region(
|
||||
item[0], anchor=anchor, page_width=page_width, page_height=page_height, enforce=True,
|
||||
item[0], anchor=anchor, page_width=page_width, page_height=page_height,
|
||||
reference_page_frame=reference_page_frame, enforce=True,
|
||||
)
|
||||
]
|
||||
if len(positioned) == 1:
|
||||
@@ -370,6 +419,7 @@ def _glyph_gap_is_word_boundary(left: dict[str, Any], right: dict[str, Any]) ->
|
||||
|
||||
def _anchor_bbox_in_reference_region(
|
||||
bbox: LayoutBBox, *, anchor: AnchorRule, page_width: float | None, page_height: float | None,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
enforce: bool = False,
|
||||
) -> bool:
|
||||
"""锚点配置了参考区时只接受该页相对位置内的命中,避免页眉重复标签干扰。"""
|
||||
@@ -377,17 +427,22 @@ def _anchor_bbox_in_reference_region(
|
||||
return True
|
||||
if page_width is None or page_height is None or page_width <= 0 or page_height <= 0:
|
||||
return False
|
||||
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
|
||||
region = _absolute_relative_region(
|
||||
anchor.region, width=page_width, height=page_height, reference_page_frame=reference_page_frame,
|
||||
)
|
||||
return _glyph_center_inside({'bbox': bbox.model_dump(mode='json')}, region)
|
||||
|
||||
|
||||
def _anchor_from_reference_region(
|
||||
glyphs: list[dict[str, Any]], *, anchor: AnchorRule, page_width: float, page_height: float,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
) -> LayoutBBox | None:
|
||||
"""为历史占位标签保留参考框内的实际标签几何,且调用方必须降级为人工复核。"""
|
||||
if anchor.region is None:
|
||||
return None
|
||||
region = _absolute_relative_region(anchor.region, width=page_width, height=page_height)
|
||||
region = _absolute_relative_region(
|
||||
anchor.region, width=page_width, height=page_height, reference_page_frame=reference_page_frame,
|
||||
)
|
||||
selected = [glyph for glyph in glyphs if _glyph_center_inside(glyph, region)]
|
||||
return _union_bbox(selected) if selected else None
|
||||
|
||||
@@ -473,11 +528,19 @@ def _source_allowed(
|
||||
return not ('coordinate' in required_levels and source != 'pdf_coordinate')
|
||||
|
||||
|
||||
def _absolute_relative_region(region: RelativeRegion | None, *, width: float, height: float) -> LayoutBBox:
|
||||
"""将固定低可靠度归一化页区投影为当前页面绝对框。"""
|
||||
def _absolute_relative_region(
|
||||
region: RelativeRegion | None, *, width: float, height: float,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
) -> LayoutBBox:
|
||||
"""将区域投影为 PDF 点坐标;有标注页框时不得随当前长页高度缩放。"""
|
||||
if region is None:
|
||||
raise ValueError('fallback order field region is required')
|
||||
return LayoutBBox(x0=region.x0 * width, y0=region.y0 * height, x1=region.x1 * width, y1=region.y1 * height)
|
||||
projection_width = reference_page_frame.width if reference_page_frame is not None else width
|
||||
projection_height = reference_page_frame.height if reference_page_frame is not None else height
|
||||
return LayoutBBox(
|
||||
x0=region.x0 * projection_width, y0=region.y0 * projection_height,
|
||||
x1=region.x1 * projection_width, y1=region.y1 * projection_height,
|
||||
)
|
||||
|
||||
|
||||
def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutBBox) -> LayoutBBox:
|
||||
@@ -491,14 +554,17 @@ def _absolute_anchor_region(region: AnchorRelativeRegion | None, anchor: LayoutB
|
||||
)
|
||||
|
||||
|
||||
def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float) -> LayoutBBox:
|
||||
"""读取管理员值框;右侧/下方字段只随标签平移,绝不按标签框尺寸缩放。"""
|
||||
def _absolute_value_region(
|
||||
*, layout: OrderFieldLayout, anchor: LayoutBBox, width: float, height: float,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
) -> LayoutBBox:
|
||||
"""读取管理员值框;有保存参考锚点时整框随唯一命中标签平移,绝不缩放。"""
|
||||
if layout.value_region is not None:
|
||||
if layout.anchor is None or layout.anchor.region is None:
|
||||
return _absolute_anchor_region(layout.value_region, anchor)
|
||||
if layout.value_mode not in {'right_of_anchor', 'below_anchor'}:
|
||||
return _absolute_anchor_region(layout.value_region, anchor)
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame)
|
||||
saved = _absolute_anchor_region(layout.value_region, reference)
|
||||
if layout.value_mode == 'right_of_anchor':
|
||||
region = _absolute_anchor_region(layout.value_region, anchor)
|
||||
@@ -509,19 +575,33 @@ def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, widt
|
||||
x1=anchor.x1 + projected_width, y1=region.y1,
|
||||
)
|
||||
elif layout.absolute_value_region is not None:
|
||||
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
|
||||
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height, reference_page_frame=reference_page_frame)
|
||||
if layout.anchor is None or layout.anchor.region is None:
|
||||
return saved
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame)
|
||||
else:
|
||||
raise ValueError('anchored order field has no value region')
|
||||
if layout.value_mode not in {'right_of_anchor', 'below_anchor'}:
|
||||
# absolute_value_region 记录的是标注页上的完整取值框。标签在当前
|
||||
# 文档因可选单头内容整体移动时,single_line/multi_line 也必须保留
|
||||
# 框的形状,并以该字段自己的唯一锚点中心作同量平移。
|
||||
if layout.absolute_value_region is not None:
|
||||
reference_center_x = (reference.x0 + reference.x1) / 2
|
||||
reference_center_y = (reference.y0 + reference.y1) / 2
|
||||
anchor_center_x = (anchor.x0 + anchor.x1) / 2
|
||||
anchor_center_y = (anchor.y0 + anchor.y1) / 2
|
||||
return LayoutBBox(
|
||||
x0=saved.x0 + anchor_center_x - reference_center_x,
|
||||
y0=saved.y0 + anchor_center_y - reference_center_y,
|
||||
x1=saved.x1 + anchor_center_x - reference_center_x,
|
||||
y1=saved.y1 + anchor_center_y - reference_center_y,
|
||||
)
|
||||
return saved
|
||||
anchor_center_x, anchor_center_y = (anchor.x0 + anchor.x1) / 2, (anchor.y0 + anchor.y1) / 2
|
||||
if _regions_overlap(anchor, reference):
|
||||
return saved
|
||||
if layout.absolute_value_region is not None and not _uses_movable_anchor_value_region(
|
||||
layout=layout, width=width, height=height,
|
||||
layout=layout, width=width, height=height, reference_page_frame=reference_page_frame,
|
||||
):
|
||||
return saved
|
||||
if layout.value_mode == 'right_of_anchor':
|
||||
@@ -536,7 +616,10 @@ def _absolute_value_region(*, layout: OrderFieldLayout, anchor: LayoutBBox, widt
|
||||
)
|
||||
|
||||
|
||||
def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float, height: float) -> bool:
|
||||
def _uses_movable_anchor_value_region(
|
||||
*, layout: OrderFieldLayout, width: float, height: float,
|
||||
reference_page_frame: ReferencePageFrame | None = None,
|
||||
) -> bool:
|
||||
"""判断新相对规则或同一行的旧右侧框是否应跟随实际标签移动。"""
|
||||
if layout.value_region is not None:
|
||||
return layout.value_mode in {'right_of_anchor', 'below_anchor'}
|
||||
@@ -545,8 +628,8 @@ def _uses_movable_anchor_value_region(*, layout: OrderFieldLayout, width: float,
|
||||
or layout.value_mode not in {'right_of_anchor', 'below_anchor'}
|
||||
):
|
||||
return False
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height)
|
||||
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height)
|
||||
reference = _absolute_relative_region(layout.anchor.region, width=width, height=height, reference_page_frame=reference_page_frame)
|
||||
saved = _absolute_relative_region(layout.absolute_value_region, width=width, height=height, reference_page_frame=reference_page_frame)
|
||||
tolerance = max(reference.y1 - reference.y0, saved.y1 - saved.y0) * 2
|
||||
return saved.y0 <= reference.y1 + tolerance and reference.y0 <= saved.y1 + tolerance
|
||||
|
||||
|
||||
@@ -50,6 +50,15 @@ class RelativeRegion(OrderProfileModel):
|
||||
return self
|
||||
|
||||
|
||||
class ReferencePageFrame(OrderProfileModel):
|
||||
"""冻结标注样本的 PDF CropBox 点尺寸,供跨页高变化时还原相对区域。"""
|
||||
|
||||
width: float = Field(gt=0)
|
||||
height: float = Field(gt=0)
|
||||
origin: Literal['pdf_top_left'] = 'pdf_top_left'
|
||||
box: Literal['cropbox'] = 'cropbox'
|
||||
|
||||
|
||||
class AnchorRelativeRegion(OrderProfileModel):
|
||||
"""仅接收历史锚点相对值框;新模板统一保存 absolute_value_region。"""
|
||||
|
||||
@@ -251,7 +260,7 @@ class TableRegionProfile(OrderProfileModel):
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
region: RelativeRegion
|
||||
# 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。
|
||||
line_start_field_code: str = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
line_start_field_code: str | None = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
# 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。
|
||||
row_reconstruction_mode: Literal['fixed_subrows', 'adaptive_record_columns'] = 'fixed_subrows'
|
||||
# 人工确认本表区自动标注时采用的视觉几何来源;仅用于审计、盲测和冲突复核,
|
||||
@@ -291,7 +300,7 @@ class TableRegionProfile(OrderProfileModel):
|
||||
if len(fields) != len(set(fields)):
|
||||
raise ValueError('field_code may bind to only one coordinate region per table')
|
||||
# 草稿可先框物理行;一旦主行开始绑字段,就必须包含起行锚点。
|
||||
if self.line_layouts and self.line_layouts[0].field_regions and self.line_start_field_code not in {
|
||||
if self.line_start_field_code and self.line_layouts and self.line_layouts[0].field_regions and self.line_start_field_code not in {
|
||||
field.field_code for field in self.line_layouts[0].field_regions
|
||||
}:
|
||||
raise ValueError('main line layout must bind the configured line-start field')
|
||||
@@ -427,6 +436,58 @@ class DocumentMatchProfile(OrderProfileModel):
|
||||
return self
|
||||
|
||||
|
||||
class AnchorFrameCoordinateModel(OrderProfileModel):
|
||||
"""声明以稳定静态文字建立运行时受限几何坐标框架的 Profile 能力。"""
|
||||
|
||||
type: Literal['anchor_frame']
|
||||
anchors: list[AnchorRule] = Field(min_length=1, max_length=4)
|
||||
max_translate_x: float = Field(default=.03, ge=0, le=.15)
|
||||
max_translate_y: float = Field(default=.06, ge=0, le=.20)
|
||||
transform_mode: Literal['translate', 'affine'] = 'translate'
|
||||
max_scale_delta: float = Field(default=.03, ge=0, le=.10)
|
||||
max_rotation_degrees: float = Field(default=2.0, ge=0, le=5.0)
|
||||
max_residual: float = Field(default=.01, gt=0, le=.05)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_anchor_frame(self) -> 'AnchorFrameCoordinateModel':
|
||||
"""要求每个框架锚点都有基线区域且身份唯一,避免运行时从全文猜测基准。"""
|
||||
if any(anchor.region is None for anchor in self.anchors):
|
||||
raise ValueError('anchor frame anchors require baseline regions')
|
||||
ids = [anchor.anchor_id for anchor in self.anchors]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('anchor frame anchor ids must be unique')
|
||||
if self.transform_mode == 'affine' and len(self.anchors) < 3:
|
||||
raise ValueError('affine coordinate model requires at least three frame anchors')
|
||||
return self
|
||||
|
||||
|
||||
class CoordinateModel(OrderProfileModel):
|
||||
"""定义坐标模板是否启用锚点框架;legacy 保持既有绝对坐标行为。"""
|
||||
|
||||
type: Literal['legacy', 'anchor_frame'] = 'legacy'
|
||||
anchors: list[AnchorRule] = Field(default_factory=list, max_length=4)
|
||||
max_translate_x: float = Field(default=.03, ge=0, le=.15)
|
||||
max_translate_y: float = Field(default=.06, ge=0, le=.20)
|
||||
transform_mode: Literal['translate', 'affine'] = 'translate'
|
||||
max_scale_delta: float = Field(default=.03, ge=0, le=.10)
|
||||
max_rotation_degrees: float = Field(default=2.0, ge=0, le=5.0)
|
||||
max_residual: float = Field(default=.01, gt=0, le=.05)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_coordinate_model(self) -> 'CoordinateModel':
|
||||
"""仅 anchor_frame 允许锚点配置;legacy 必须是空声明以保证路径隔离。"""
|
||||
if self.type == 'legacy' and self.anchors:
|
||||
raise ValueError('legacy coordinate model must not define frame anchors')
|
||||
if self.type == 'anchor_frame':
|
||||
AnchorFrameCoordinateModel(
|
||||
type='anchor_frame', anchors=self.anchors,
|
||||
max_translate_x=self.max_translate_x, max_translate_y=self.max_translate_y,
|
||||
transform_mode=self.transform_mode, max_scale_delta=self.max_scale_delta,
|
||||
max_rotation_degrees=self.max_rotation_degrees, max_residual=self.max_residual,
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class OrderCoordinateProfile(OrderProfileModel):
|
||||
"""唯一的订单坐标模板定义;运行时和管理端只消费这一种契约。"""
|
||||
profile_code: str = Field(pattern=r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
@@ -435,6 +496,8 @@ class OrderCoordinateProfile(OrderProfileModel):
|
||||
table_regions: list[TableRegionProfile] = Field(min_length=1)
|
||||
order_field_layouts: list[OrderFieldLayout] = Field(default_factory=list)
|
||||
draft_unbound_order_field_layouts: list[DraftUnboundOrderFieldLayout] = Field(default_factory=list)
|
||||
coordinate_model: CoordinateModel = Field(default_factory=CoordinateModel)
|
||||
reference_page_frames: dict[int, ReferencePageFrame] = Field(default_factory=dict)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_profile_rules(self) -> 'OrderCoordinateProfile':
|
||||
|
||||
@@ -9,6 +9,8 @@ services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from copy import deepcopy
|
||||
import math
|
||||
import re
|
||||
from typing import Any, Literal
|
||||
|
||||
@@ -17,8 +19,13 @@ from pydantic import BaseModel, ConfigDict, Field
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import (
|
||||
positioned_token_spans,
|
||||
read_coordinate_region_text,
|
||||
visual_glyph_rows,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.coordinate_transform import (
|
||||
apply_coordinate_transform_to_region,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
AnchorRule,
|
||||
CRITICAL_STRUCTURE_DIMENSION_KEYS,
|
||||
MatchDimensionResult,
|
||||
MatchDimensionState,
|
||||
@@ -31,6 +38,11 @@ from app.services.shipping_notice.document_layout.order_profile_signature import
|
||||
)
|
||||
|
||||
|
||||
# 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义,
|
||||
# 避免无意义的版本兼容分支。
|
||||
LAYOUT_MATCHING_FEATURES_VERSION = 'v1'
|
||||
|
||||
|
||||
def _anchor_comparable_text(value: Any) -> str:
|
||||
"""规范化锚点比较文本,兼容 PDF 字符逐字拼接后丢失的版面空白。"""
|
||||
return ''.join(str(value or '').casefold().split())
|
||||
@@ -66,6 +78,7 @@ class ProfileMatchCandidate(BaseModel):
|
||||
dimension_scores: ProfileMatchDimensionScores | None = None
|
||||
dimension_states: dict[str, MatchDimensionState] = Field(default_factory=dict)
|
||||
margin_to_next: float | None = Field(default=None, ge=0, le=1)
|
||||
coordinate_transform: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class ProfileMatchResult(BaseModel):
|
||||
@@ -136,15 +149,24 @@ def match_frozen_coordinate_profiles(
|
||||
document_match=definition.get('document_match'),
|
||||
table_regions=definition.get('table_regions'),
|
||||
order_field_layouts=definition.get('order_field_layouts') or [],
|
||||
coordinate_model=definition.get('coordinate_model') or {},
|
||||
reference_page_frames=definition.get('reference_page_frames') or {},
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
|
||||
reason_codes: list[str] = []
|
||||
signature_body, signature_meta = _extract_matching_signature(raw)
|
||||
coordinate_transform, transform_reasons = _resolve_coordinate_transform(
|
||||
profile=profile, pages=pages, page_glyphs=page_glyphs,
|
||||
)
|
||||
reason_codes.extend(transform_reasons)
|
||||
observed_signature = _translate_signature(
|
||||
signature=signature_body, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
observed = _observe_layout_features(
|
||||
layout=layout, tables=tables, pages=pages, glyph_tables=glyph_tables,
|
||||
page_glyphs=page_glyphs, signature=signature_body,
|
||||
page_glyphs=page_glyphs, signature=observed_signature,
|
||||
)
|
||||
if signature_body is None:
|
||||
reason_codes.append('profile_signature_missing')
|
||||
@@ -190,7 +212,7 @@ def match_frozen_coordinate_profiles(
|
||||
|
||||
dimension_results, hard_conflict_codes = _compute_dimension_results(
|
||||
profile=profile,
|
||||
signature=signature_body,
|
||||
signature=observed_signature,
|
||||
observed=observed,
|
||||
tables=tables,
|
||||
pages=pages,
|
||||
@@ -200,6 +222,11 @@ def match_frozen_coordinate_profiles(
|
||||
customer_hint_id=customer_hint_id,
|
||||
)
|
||||
reason_codes.extend(hard_conflict_codes)
|
||||
if _profile_requires_unavailable_structure_evidence(
|
||||
signature=observed_signature,
|
||||
dimension_results=dimension_results,
|
||||
):
|
||||
reason_codes.append('profile_coordinate_evidence_unavailable')
|
||||
|
||||
weights = profile.document_match.scoring_weights
|
||||
score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results)
|
||||
@@ -223,6 +250,7 @@ def match_frozen_coordinate_profiles(
|
||||
matched_anchor_count=sum(required_hits) + sum(optional_hits),
|
||||
dimension_scores=dimension_scores,
|
||||
dimension_states=dimension_states,
|
||||
coordinate_transform=coordinate_transform,
|
||||
)))
|
||||
|
||||
rendered = sorted(
|
||||
@@ -251,6 +279,11 @@ def match_frozen_coordinate_profiles(
|
||||
candidate.margin_to_next = round(max(0.0, candidate.score - next_score), 6)
|
||||
|
||||
if not hard_valid:
|
||||
if any('profile_coordinate_evidence_unavailable' in item.reason_codes for item in rendered):
|
||||
return ProfileMatchResult(
|
||||
status='evidence_insufficient', candidates=rendered,
|
||||
top1_score=top1_score, top2_score=top2_score, margin=margin,
|
||||
)
|
||||
if not rendered:
|
||||
return ProfileMatchResult(
|
||||
status='no_match', candidates=rendered,
|
||||
@@ -305,6 +338,134 @@ def match_frozen_coordinate_profiles(
|
||||
)
|
||||
|
||||
|
||||
def build_layout_matching_features(*, layout: dict[str, Any]) -> dict[str, Any]:
|
||||
"""从完整坐标证据派生可持久化的候选表头特征,不保留逐字符正文。
|
||||
|
||||
特征生成不依赖任何 Profile;保存所有候选视觉行,运行时再由冻结签名选择,
|
||||
避免“无 Profile 时猜一条表头”导致压缩后永久保存错误列拓扑。
|
||||
"""
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
first_page = pages.get('1') or pages.get(1) or next(iter(pages.values()), None)
|
||||
aspect_ratio = 0.0
|
||||
if isinstance(first_page, dict):
|
||||
try:
|
||||
width, height = float(first_page.get('width') or 0), float(first_page.get('height') or 0)
|
||||
aspect_ratio = round(width / height, 6) if width > 0 and height > 0 else 0.0
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
rendered_tables: list[dict[str, Any]] = []
|
||||
for table in tables:
|
||||
bbox = _normalized_table_bbox(table=table, pages=pages)
|
||||
if bbox is None:
|
||||
continue
|
||||
candidates = _observe_header_candidates(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
primary_bbox=bbox,
|
||||
)
|
||||
rendered_tables.append({
|
||||
'bbox': bbox,
|
||||
'header_candidates': candidates,
|
||||
})
|
||||
result = {
|
||||
'version': LAYOUT_MATCHING_FEATURES_VERSION,
|
||||
'page_structure': {
|
||||
'aspect_ratio': aspect_ratio,
|
||||
'page_count': len(pages),
|
||||
'table_count': len(tables),
|
||||
},
|
||||
'tables': rendered_tables,
|
||||
'static_text_centers': _observe_static_text_centers(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
),
|
||||
}
|
||||
if not result['static_text_centers']:
|
||||
result.pop('static_text_centers')
|
||||
return result
|
||||
|
||||
|
||||
def _observe_header_candidates(
|
||||
*, glyph_tables: dict[str, Any], page_glyphs: dict[str, Any],
|
||||
pages: dict[str, Any], primary_bbox: list[float],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""提取主表顶部视觉行候选;不把数据行固化成唯一表头。"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return []
|
||||
page = pages.get('1') or pages.get(1)
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
|
||||
if not isinstance(glyphs, list):
|
||||
glyphs = [g for values in glyph_tables.values() if isinstance(values, list) for g in values]
|
||||
if not isinstance(page, dict) or not glyphs:
|
||||
return []
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
if width <= 0 or height <= 0:
|
||||
return []
|
||||
table_height = max(0.001, primary_bbox[3] - primary_bbox[1])
|
||||
rows = visual_glyph_rows(glyphs)
|
||||
candidates: list[dict[str, Any]] = []
|
||||
for row in rows:
|
||||
centers_y = [
|
||||
((float(g['bbox']['y0']) + float(g['bbox']['y1'])) / 2) / height
|
||||
for g in row if isinstance(g.get('bbox'), dict)
|
||||
]
|
||||
if not centers_y:
|
||||
continue
|
||||
y = sum(centers_y) / len(centers_y)
|
||||
if y < primary_bbox[1] or y > primary_bbox[1] + table_height * 0.30:
|
||||
continue
|
||||
spans = [
|
||||
item for item in positioned_token_spans(row, respect_explicit_spaces=False)
|
||||
if _usable_observed_header_token(str(item.get('text') or ''))
|
||||
][:32]
|
||||
if not spans:
|
||||
continue
|
||||
tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
|
||||
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
|
||||
table_span = max(primary_bbox[2] - primary_bbox[0], 0.0001)
|
||||
widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
|
||||
bbox = [
|
||||
round(min(float(g['bbox']['x0']) for g in row if isinstance(g.get('bbox'), dict)) / width, 6),
|
||||
round(min(float(g['bbox']['y0']) for g in row if isinstance(g.get('bbox'), dict)) / height, 6),
|
||||
round(max(float(g['bbox']['x1']) for g in row if isinstance(g.get('bbox'), dict)) / width, 6),
|
||||
round(max(float(g['bbox']['y1']) for g in row if isinstance(g.get('bbox'), dict)) / height, 6),
|
||||
]
|
||||
candidates.append({'bbox': bbox, 'header_tokens': tokens, 'column_centers': centers, 'column_width_ratios': widths})
|
||||
candidates.sort(key=lambda item: (item['bbox'][1], -len(item['header_tokens'])))
|
||||
return candidates[:8]
|
||||
|
||||
|
||||
def _normalized_table_bbox(*, table: dict[str, Any], pages: dict[str, Any]) -> list[float] | None:
|
||||
"""将 Layout 表框转为页内归一化坐标;缺页尺寸时仅接受已经归一化的表框。"""
|
||||
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
|
||||
if bbox is None:
|
||||
return None
|
||||
try:
|
||||
values = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None
|
||||
if values[2] <= values[0] or values[3] <= values[1]:
|
||||
return None
|
||||
if max(values) <= 1:
|
||||
return [round(value, 6) for value in values]
|
||||
page_no = table.get('page_no') or 1
|
||||
page = pages.get(str(page_no)) or pages.get(page_no)
|
||||
if not isinstance(page, dict):
|
||||
return None
|
||||
try:
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if width <= 0 or height <= 0:
|
||||
return None
|
||||
return [
|
||||
round(values[0] / width, 6), round(values[1] / height, 6),
|
||||
round(values[2] / width, 6), round(values[3] / height, 6),
|
||||
]
|
||||
|
||||
|
||||
def _selected_result(
|
||||
*,
|
||||
raw: dict[str, Any],
|
||||
@@ -343,6 +504,340 @@ def _extract_matching_signature(raw: dict[str, Any]) -> tuple[dict[str, Any] | N
|
||||
return signature, matching if isinstance(matching, dict) else {}
|
||||
|
||||
|
||||
def _resolve_coordinate_transform(
|
||||
*, profile: OrderCoordinateProfile, pages: dict[str, Any], page_glyphs: dict[str, Any],
|
||||
) -> tuple[dict[str, Any] | None, list[str]]:
|
||||
"""根据冻结的模板身份锚点求受限平移,任何不确定性都返回硬失败原因。
|
||||
|
||||
Args:
|
||||
profile: 当前冻结坐标 Profile;旧 ``anchor_frame`` 优先,其他模板复用已框选的
|
||||
必选文档匹配标签,不要求管理员选择坐标模型。
|
||||
pages: 当前 Layout 的页尺寸证据。
|
||||
page_glyphs: 当前 Layout 的页级 PDF/OCR 字符坐标。
|
||||
|
||||
Returns:
|
||||
``(transform, reason_codes)``。没有可证明的静态标签时返回 ``(None, [])``;
|
||||
有标签时仅在全部唯一且变换位于受限范围内返回 ``status=applied``。
|
||||
"""
|
||||
model = profile.coordinate_model
|
||||
anchors = list(model.anchors)
|
||||
max_translate_x = model.max_translate_x
|
||||
max_translate_y = model.max_translate_y
|
||||
if model.type != 'anchor_frame':
|
||||
anchors = [
|
||||
AnchorRule(
|
||||
anchor_id=anchor.anchor_id,
|
||||
text=anchor.label,
|
||||
match_mode='exact',
|
||||
region=anchor.label_region,
|
||||
position_locked=True,
|
||||
minimum_evidence_level=anchor.minimum_evidence_level,
|
||||
)
|
||||
for anchor in profile.document_match.required_anchors
|
||||
if anchor.label_region is not None
|
||||
]
|
||||
# 没有已框选的稳定标签时保持绝对坐标兼容;不从全文猜测校正基准。
|
||||
if not anchors:
|
||||
return None, []
|
||||
if not anchors:
|
||||
return None, []
|
||||
|
||||
deltas: list[tuple[float, float]] = []
|
||||
anchor_points: list[tuple[float, float, float, float]] = []
|
||||
anchor_ids: list[str] = []
|
||||
for anchor in anchors:
|
||||
found = _find_anchor_rule_matches(
|
||||
anchor=anchor, pages=pages, page_glyphs=page_glyphs,
|
||||
max_translate_x=min(.30, max_translate_x * 2),
|
||||
max_translate_y=min(.30, max_translate_y * 2),
|
||||
)
|
||||
if not found:
|
||||
return None, ['profile_anchor_frame_anchor_missing']
|
||||
if len(found) != 1:
|
||||
return None, ['profile_anchor_frame_anchor_ambiguous']
|
||||
page_no, bbox = found[0]
|
||||
page = pages.get(str(page_no)) or pages.get(page_no)
|
||||
if not isinstance(page, dict) or anchor.region is None:
|
||||
return None, ['profile_anchor_frame_coordinate_evidence_unavailable']
|
||||
try:
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None, ['profile_anchor_frame_coordinate_evidence_unavailable']
|
||||
if width <= 0 or height <= 0:
|
||||
return None, ['profile_anchor_frame_coordinate_evidence_unavailable']
|
||||
observed_x = (bbox[0] + bbox[2]) / 2 / width
|
||||
observed_y = (bbox[1] + bbox[3]) / 2 / height
|
||||
expected_x = (anchor.region.x0 + anchor.region.x1) / 2
|
||||
expected_y = (anchor.region.y0 + anchor.region.y1) / 2
|
||||
deltas.append((observed_x - expected_x, observed_y - expected_y))
|
||||
anchor_points.append((expected_x, expected_y, observed_x, observed_y))
|
||||
anchor_ids.append(anchor.anchor_id)
|
||||
|
||||
if model.type == 'anchor_frame' and model.transform_mode == 'affine':
|
||||
transform, reason = _resolve_affine_coordinate_transform(
|
||||
anchor_points=anchor_points, anchor_ids=anchor_ids, model=model,
|
||||
)
|
||||
return transform, [] if transform is not None else [reason]
|
||||
|
||||
first_x, first_y = deltas[0]
|
||||
if any(abs(x - first_x) > .01 or abs(y - first_y) > .01 for x, y in deltas[1:]):
|
||||
return None, ['profile_anchor_frame_anchor_inconsistent']
|
||||
if abs(first_x) > max_translate_x or abs(first_y) > max_translate_y:
|
||||
return None, ['profile_anchor_frame_transform_out_of_range']
|
||||
return {
|
||||
'status': 'applied',
|
||||
'translate_x': round(first_x, 6),
|
||||
'translate_y': round(first_y, 6),
|
||||
'anchor_ids': anchor_ids,
|
||||
'reason_codes': [],
|
||||
}, []
|
||||
|
||||
|
||||
def _resolve_affine_coordinate_transform(
|
||||
*, anchor_points: list[tuple[float, float, float, float]], anchor_ids: list[str], model: Any,
|
||||
) -> tuple[dict[str, Any] | None, str]:
|
||||
"""以 Profile 显式声明的三个以上稳定锚点求受限仿射,无法证明即失败关闭。"""
|
||||
if len(anchor_points) < 3:
|
||||
return None, 'profile_anchor_frame_affine_anchor_insufficient'
|
||||
matrix_x = _least_squares_affine_axis(anchor_points, observed_index=2)
|
||||
matrix_y = _least_squares_affine_axis(anchor_points, observed_index=3)
|
||||
if matrix_x is None or matrix_y is None:
|
||||
return None, 'profile_anchor_frame_affine_anchor_degenerate'
|
||||
a, b, tx = matrix_x
|
||||
d, e, ty = matrix_y
|
||||
determinant = a * e - b * d
|
||||
scale_x, scale_y = math.hypot(a, d), math.hypot(b, e)
|
||||
rotation_degrees = abs(math.degrees(math.atan2(d, a)))
|
||||
residual = max(
|
||||
math.hypot(a * x + b * y + tx - observed_x, d * x + e * y + ty - observed_y)
|
||||
for x, y, observed_x, observed_y in anchor_points
|
||||
)
|
||||
if not all(math.isfinite(value) for value in (determinant, scale_x, scale_y, rotation_degrees, residual)):
|
||||
return None, 'profile_anchor_frame_affine_invalid'
|
||||
if determinant <= 0:
|
||||
return None, 'profile_anchor_frame_affine_invalid'
|
||||
if max(abs(scale_x - 1), abs(scale_y - 1)) > model.max_scale_delta:
|
||||
return None, 'profile_anchor_frame_affine_scale_out_of_range'
|
||||
if rotation_degrees > model.max_rotation_degrees:
|
||||
return None, 'profile_anchor_frame_affine_rotation_out_of_range'
|
||||
if residual > model.max_residual:
|
||||
return None, 'profile_anchor_frame_affine_residual_out_of_range'
|
||||
if abs(tx) > model.max_translate_x or abs(ty) > model.max_translate_y:
|
||||
return None, 'profile_anchor_frame_transform_out_of_range'
|
||||
return {
|
||||
'status': 'applied',
|
||||
'matrix': [round(value, 6) for value in (a, b, tx, d, e, ty)],
|
||||
'translate_x': round(tx, 6),
|
||||
'translate_y': round(ty, 6),
|
||||
'anchor_ids': anchor_ids,
|
||||
'residual': round(residual, 6),
|
||||
'reason_codes': [],
|
||||
}, ''
|
||||
|
||||
|
||||
def _least_squares_affine_axis(
|
||||
points: list[tuple[float, float, float, float]], *, observed_index: int,
|
||||
) -> tuple[float, float, float] | None:
|
||||
"""用正规方程拟合单个仿射轴;共线锚点会因奇异矩阵而被拒绝。"""
|
||||
count = float(len(points))
|
||||
sum_x = sum(item[0] for item in points)
|
||||
sum_y = sum(item[1] for item in points)
|
||||
sum_xx = sum(item[0] * item[0] for item in points)
|
||||
sum_xy = sum(item[0] * item[1] for item in points)
|
||||
sum_yy = sum(item[1] * item[1] for item in points)
|
||||
sum_z = sum(item[observed_index] for item in points)
|
||||
sum_xz = sum(item[0] * item[observed_index] for item in points)
|
||||
sum_yz = sum(item[1] * item[observed_index] for item in points)
|
||||
determinant = (
|
||||
sum_xx * (sum_yy * count - sum_y * sum_y)
|
||||
- sum_xy * (sum_xy * count - sum_y * sum_x)
|
||||
+ sum_x * (sum_xy * sum_y - sum_yy * sum_x)
|
||||
)
|
||||
if not math.isfinite(determinant) or abs(determinant) < 1e-9:
|
||||
return None
|
||||
matrix = ((sum_xx, sum_xy, sum_x), (sum_xy, sum_yy, sum_y), (sum_x, sum_y, count))
|
||||
target = (sum_xz, sum_yz, sum_z)
|
||||
values = []
|
||||
for column in range(3):
|
||||
replaced = tuple(
|
||||
tuple(target[row] if index == column else matrix[row][index] for index in range(3))
|
||||
for row in range(3)
|
||||
)
|
||||
value = _determinant_3x3(replaced) / determinant
|
||||
if not math.isfinite(value):
|
||||
return None
|
||||
values.append(value)
|
||||
return values[0], values[1], values[2]
|
||||
|
||||
|
||||
def _determinant_3x3(matrix: tuple[tuple[float, float, float], ...]) -> float:
|
||||
"""返回 3x3 矩阵行列式,供无额外数值依赖的仿射拟合使用。"""
|
||||
return (
|
||||
matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1][2] * matrix[2][1])
|
||||
- matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0])
|
||||
+ matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0])
|
||||
)
|
||||
|
||||
|
||||
def _find_anchor_rule_matches(
|
||||
*, anchor: AnchorRule, pages: dict[str, Any], page_glyphs: dict[str, Any],
|
||||
max_translate_x: float, max_translate_y: float,
|
||||
) -> list[tuple[int, list[float]]]:
|
||||
"""在基线区加声明平移窗口内寻找唯一锚点,绝不退化为全文弱匹配。"""
|
||||
if anchor.region is None:
|
||||
return []
|
||||
expected = [_anchor_comparable_text(value) for value in [anchor.text, *anchor.aliases]]
|
||||
rendered: list[tuple[int, list[float]]] = []
|
||||
for raw_page_no, page in pages.items():
|
||||
try:
|
||||
page_no, width, height = int(raw_page_no), float(page['width']), float(page['height'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no)
|
||||
if width <= 0 or height <= 0 or not isinstance(glyphs, list):
|
||||
continue
|
||||
for line in _group_glyph_lines(glyphs):
|
||||
ordered = sorted(line, key=lambda item: float((item.get('bbox') or {}).get('x0') or 0))
|
||||
comparable_parts: list[str] = []
|
||||
glyph_spans: list[tuple[int, int, dict[str, Any]]] = []
|
||||
for item in ordered:
|
||||
part = _anchor_comparable_text(item.get('text') or '')
|
||||
if not part:
|
||||
continue
|
||||
start = len(''.join(comparable_parts))
|
||||
comparable_parts.append(part)
|
||||
glyph_spans.append((start, start + len(part), item))
|
||||
text = ''.join(comparable_parts)
|
||||
if not text:
|
||||
continue
|
||||
matched_box_sets: list[list[dict[str, Any]]] = []
|
||||
for value in expected:
|
||||
if not value:
|
||||
continue
|
||||
starts: list[int] = []
|
||||
offset = text.find(value)
|
||||
while offset >= 0:
|
||||
starts.append(offset)
|
||||
offset = text.find(value, offset + 1)
|
||||
if anchor.match_mode == 'exact' and not _anchor_rule_text_matches(value, text, mode='contains'):
|
||||
starts = []
|
||||
for start in starts:
|
||||
end = start + len(value)
|
||||
matched_box_sets.append([
|
||||
item for span_start, span_end, item in glyph_spans
|
||||
if span_start < end and span_end > start
|
||||
])
|
||||
if matched_box_sets:
|
||||
break
|
||||
if len(matched_box_sets) != 1 or not matched_box_sets[0]:
|
||||
if len(matched_box_sets) > 1:
|
||||
rendered.extend((page_no, [
|
||||
min(float(item['bbox']['x0']) for item in boxes if isinstance(item.get('bbox'), dict)),
|
||||
min(float(item['bbox']['y0']) for item in boxes if isinstance(item.get('bbox'), dict)),
|
||||
max(float(item['bbox']['x1']) for item in boxes if isinstance(item.get('bbox'), dict)),
|
||||
max(float(item['bbox']['y1']) for item in boxes if isinstance(item.get('bbox'), dict)),
|
||||
]) for boxes in matched_box_sets if boxes)
|
||||
continue
|
||||
matched_boxes = matched_box_sets[0]
|
||||
if not matched_boxes:
|
||||
continue
|
||||
boxes = [item.get('bbox') for item in matched_boxes if isinstance(item.get('bbox'), dict)]
|
||||
if not boxes:
|
||||
continue
|
||||
bbox = [
|
||||
min(float(item['x0']) for item in boxes), min(float(item['y0']) for item in boxes),
|
||||
max(float(item['x1']) for item in boxes), max(float(item['y1']) for item in boxes),
|
||||
]
|
||||
center_x, center_y = (bbox[0] + bbox[2]) / 2 / width, (bbox[1] + bbox[3]) / 2 / height
|
||||
if (
|
||||
max(0, anchor.region.x0 - max_translate_x) <= center_x <= min(1, anchor.region.x1 + max_translate_x)
|
||||
and max(0, anchor.region.y0 - max_translate_y) <= center_y <= min(1, anchor.region.y1 + max_translate_y)
|
||||
):
|
||||
rendered.append((page_no, bbox))
|
||||
return rendered
|
||||
|
||||
|
||||
def _group_glyph_lines(glyphs: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
|
||||
"""按字符中心 Y 聚合视觉行,供框架锚点精确匹配,不改变既有字段提取逻辑。"""
|
||||
lines: list[list[dict[str, Any]]] = []
|
||||
for glyph in sorted((item for item in glyphs if isinstance(item, dict) and isinstance(item.get('bbox'), dict)), key=lambda item: (float(item['bbox'].get('y0') or 0), float(item['bbox'].get('x0') or 0))):
|
||||
bbox = glyph['bbox']
|
||||
try:
|
||||
center_y = (float(bbox['y0']) + float(bbox['y1'])) / 2
|
||||
glyph_height = max(.01, float(bbox['y1']) - float(bbox['y0']))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if lines:
|
||||
previous = lines[-1][0]['bbox']
|
||||
previous_y = (float(previous['y0']) + float(previous['y1'])) / 2
|
||||
previous_height = max(.01, float(previous['y1']) - float(previous['y0']))
|
||||
if abs(center_y - previous_y) <= max(glyph_height, previous_height) * .65:
|
||||
lines[-1].append(glyph)
|
||||
continue
|
||||
lines.append([glyph])
|
||||
return lines
|
||||
|
||||
|
||||
def _anchor_rule_text_matches(expected: str, observed: str, *, mode: str) -> bool:
|
||||
"""按 AnchorRule 的 exact/contains 合约比较已规范化文本。"""
|
||||
return expected == observed if mode == 'exact' else expected in observed
|
||||
|
||||
|
||||
def _translate_signature(
|
||||
*, signature: dict[str, Any] | None, coordinate_transform: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""将当前 Profile 签名映射到共同坐标框架,非法变换必须使证据失效。"""
|
||||
if not signature or not coordinate_transform or coordinate_transform.get('status') != 'applied':
|
||||
return signature
|
||||
translated = deepcopy(signature)
|
||||
|
||||
def project_bbox(value: Any) -> list[float] | None:
|
||||
if not isinstance(value, list) or len(value) != 4:
|
||||
return None
|
||||
projected = apply_coordinate_transform_to_region(
|
||||
{'x0': value[0], 'y0': value[1], 'x1': value[2], 'y1': value[3]},
|
||||
coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if projected is None:
|
||||
return None
|
||||
return [projected['x0'], projected['y0'], projected['x1'], projected['y1']]
|
||||
|
||||
for pattern in translated.get('table_patterns') or []:
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else {}
|
||||
median = bbox.get('median') if isinstance(bbox.get('median'), list) else None
|
||||
if median:
|
||||
projected = project_bbox(median)
|
||||
if projected is None:
|
||||
return None
|
||||
bbox['median'] = projected
|
||||
header = pattern.get('header_bbox')
|
||||
if header is not None:
|
||||
projected = project_bbox(header)
|
||||
if projected is None:
|
||||
return None
|
||||
pattern['header_bbox'] = projected
|
||||
for relation in translated.get('field_relation_graph') or []:
|
||||
if isinstance(relation, dict):
|
||||
# 同一平移不会改变两锚点的相对关系,特意不修改 dx/dy。
|
||||
continue
|
||||
return translated
|
||||
|
||||
|
||||
def _profile_requires_unavailable_structure_evidence(
|
||||
*, signature: dict[str, Any] | None,
|
||||
dimension_results: dict[str, MatchDimensionResult],
|
||||
) -> bool:
|
||||
"""关键模板结构维度缺证据即禁止自动选中,不能靠缩小评分分母获得 hard match。"""
|
||||
if not signature:
|
||||
return False
|
||||
return any(
|
||||
dimension_results[key].state == 'unavailable'
|
||||
for key in CRITICAL_STRUCTURE_DIMENSION_KEYS
|
||||
)
|
||||
|
||||
|
||||
def _aggregate_dimension_score(
|
||||
*,
|
||||
weights: Any,
|
||||
@@ -664,6 +1159,17 @@ def _observe_layout_features(
|
||||
signature: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""从冻结 layout 聚合非敏感结构特征供维度比对。"""
|
||||
persisted = layout.get('matching_features')
|
||||
# 完整坐标存在时必须以当前证据重算;压缩快照才允许使用 v1 投影。
|
||||
if isinstance(page_glyphs, dict) and any(isinstance(value, list) and value for value in page_glyphs.values()):
|
||||
persisted = None
|
||||
if isinstance(persisted, dict) and persisted.get('version') == LAYOUT_MATCHING_FEATURES_VERSION:
|
||||
observed = _observed_features_from_persisted_projection(
|
||||
features=persisted, signature=signature,
|
||||
)
|
||||
if observed is not None:
|
||||
return observed
|
||||
|
||||
first_page = pages.get('1') or pages.get(1) or next(iter(pages.values()), None)
|
||||
aspect_ratio = 0.0
|
||||
if isinstance(first_page, dict):
|
||||
@@ -699,6 +1205,127 @@ def _observe_layout_features(
|
||||
}
|
||||
|
||||
|
||||
def _observed_features_from_persisted_projection(
|
||||
*, features: dict[str, Any], signature: dict[str, Any] | None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""将完整的事实投影恢复为 matcher 输入,缺任一关键结构则拒绝匹配。
|
||||
|
||||
投影生成时没有 Profile 上下文,因此会保留同一主表的多个视觉行候选。运行期只能
|
||||
根据冻结签名的 token、顺序和列几何联合选择;按列数选最近候选会把数据行误作表头。
|
||||
"""
|
||||
page_structure = features.get('page_structure')
|
||||
tables = features.get('tables')
|
||||
if not isinstance(page_structure, dict) or not isinstance(tables, list):
|
||||
return None
|
||||
candidates = [
|
||||
item for item in tables
|
||||
if isinstance(item, dict)
|
||||
and _is_complete_persisted_table_candidate(item)
|
||||
]
|
||||
if not candidates:
|
||||
return None
|
||||
selected = _select_persisted_header_candidate(candidates=candidates, signature=signature)
|
||||
if selected is None:
|
||||
return None
|
||||
primary, bbox = selected
|
||||
centers = primary.get('column_centers')
|
||||
widths = primary.get('column_width_ratios')
|
||||
tokens = primary.get('header_tokens')
|
||||
if not (
|
||||
isinstance(bbox, list) and len(bbox) == 4
|
||||
and isinstance(centers, list) and isinstance(widths, list) and isinstance(tokens, list)
|
||||
):
|
||||
return None
|
||||
return {
|
||||
'aspect_ratio': float(page_structure.get('aspect_ratio') or 0),
|
||||
'table_count': int(page_structure.get('table_count') or len(candidates)),
|
||||
'page_count': int(page_structure.get('page_count') or 0),
|
||||
'primary_table_bbox': bbox,
|
||||
'header_tokens': tokens,
|
||||
'column_count': len(centers),
|
||||
'column_centers': centers,
|
||||
'column_width_ratios': widths,
|
||||
'static_text_centers': (
|
||||
features.get('static_text_centers')
|
||||
if isinstance(features.get('static_text_centers'), dict) else {}
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _is_complete_persisted_table_candidate(candidate: dict[str, Any]) -> bool:
|
||||
"""校验 v1 投影的表和表头候选契约,防止不完整旧数据参与高分匹配。"""
|
||||
bbox = candidate.get('bbox')
|
||||
headers = candidate.get('header_candidates')
|
||||
if not isinstance(bbox, list) or len(bbox) != 4 or not isinstance(headers, list):
|
||||
return False
|
||||
return any(_is_complete_persisted_header_candidate(item) for item in headers if isinstance(item, dict))
|
||||
|
||||
|
||||
def _is_complete_persisted_header_candidate(candidate: dict[str, Any]) -> bool:
|
||||
"""候选行必须同时保留 token、列中心和列宽,不能用残缺结构猜测。"""
|
||||
tokens = candidate.get('header_tokens')
|
||||
centers = candidate.get('column_centers')
|
||||
widths = candidate.get('column_width_ratios')
|
||||
return (
|
||||
isinstance(tokens, list)
|
||||
and isinstance(centers, list)
|
||||
and isinstance(widths, list)
|
||||
and bool(tokens)
|
||||
and bool(centers)
|
||||
and len(centers) == len(widths)
|
||||
)
|
||||
|
||||
|
||||
def _select_persisted_header_candidate(
|
||||
*, candidates: list[dict[str, Any]], signature: dict[str, Any] | None,
|
||||
) -> tuple[dict[str, Any], list[float]] | None:
|
||||
"""按冻结签名联合选择投影表头,证据不足时返回 None 而非按列数猜测。"""
|
||||
expected_tokens = [
|
||||
str(token).casefold()
|
||||
for pattern in (signature or {}).get('table_patterns') or []
|
||||
if isinstance(pattern, dict)
|
||||
for token in pattern.get('header_tokens') or []
|
||||
]
|
||||
expected_order = [
|
||||
str(token).casefold()
|
||||
for pattern in (signature or {}).get('table_patterns') or []
|
||||
if isinstance(pattern, dict)
|
||||
for token in pattern.get('header_order') or []
|
||||
]
|
||||
expected_centers = _signature_column_values(signature or {}, 'column_centers')
|
||||
expected_widths = _signature_column_values(signature or {}, 'column_width_ratios')
|
||||
if not expected_tokens or not expected_centers:
|
||||
return None
|
||||
|
||||
scored: list[tuple[float, float, float, int, dict[str, Any], list[float]]] = []
|
||||
for table in candidates:
|
||||
bbox = table['bbox']
|
||||
for header in table['header_candidates']:
|
||||
if not isinstance(header, dict) or not _is_complete_persisted_header_candidate(header):
|
||||
continue
|
||||
tokens = [str(token).casefold() for token in header['header_tokens']]
|
||||
centers = header['column_centers']
|
||||
widths = header['column_width_ratios']
|
||||
token_ratio = sum(token in tokens for token in expected_tokens) / len(expected_tokens)
|
||||
shared = [token for token in expected_order if token in tokens]
|
||||
order_ratio = 1.0
|
||||
if len(shared) > 1:
|
||||
positions = [tokens.index(token) for token in shared]
|
||||
order_ratio = sum(left < right for left, right in zip(positions, positions[1:])) / (len(positions) - 1)
|
||||
center_ratio = _sequence_similarity(expected_centers, centers, tolerance=0.08)
|
||||
width_ratio = _sequence_similarity(expected_widths, widths, tolerance=0.16) if expected_widths else 1.0
|
||||
count_ratio = min(len(expected_centers), len(centers)) / max(len(expected_centers), len(centers))
|
||||
score = .50 * token_ratio + .15 * order_ratio + .25 * center_ratio + .05 * width_ratio + .05 * count_ratio
|
||||
# token 语义或几何任一缺失都不足以把压缩投影作为结构事实。
|
||||
if token_ratio < .50 or center_ratio < .50:
|
||||
continue
|
||||
scored.append((score, token_ratio, center_ratio, len(tokens), header, bbox))
|
||||
if not scored:
|
||||
return None
|
||||
_, _, _, _, header, bbox = max(scored, key=lambda item: item[:4])
|
||||
return header, bbox
|
||||
|
||||
|
||||
def _select_signature_primary_table_bbox(
|
||||
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
|
||||
) -> list[float] | None:
|
||||
@@ -881,11 +1508,13 @@ def _observe_static_text_centers(
|
||||
result: dict[str, list[float]] = {}
|
||||
for row in rows:
|
||||
ordered = sorted(row, key=lambda item: item['bbox'].get('x0', 0))
|
||||
text = _anchor_comparable_text(''.join(str(item.get('text') or '') for item in ordered))
|
||||
if not text:
|
||||
text = _anchor_comparable_text(''.join(str(item.get('text') or '') for item in ordered))[:80]
|
||||
if not text or len(text) >= 80:
|
||||
continue
|
||||
xs = [(float(item['bbox'].get('x0', 0)) + float(item['bbox'].get('x1', 0))) / 2 / width for item in ordered]
|
||||
ys = [(float(item['bbox'].get('y0', 0)) + float(item['bbox'].get('y1', 0))) / 2 / height for item in ordered]
|
||||
if len(result) >= 32:
|
||||
break
|
||||
result[text] = [round(sum(xs) / len(xs), 4), round(sum(ys) / len(ys), 4)]
|
||||
return result
|
||||
|
||||
|
||||
@@ -51,6 +51,8 @@ def validate_profile_parse_candidate(
|
||||
document_match=profile_def.get('document_match') or {'required_anchors': [], 'optional_anchors': []},
|
||||
table_regions=profile_def.get('table_regions') or [],
|
||||
order_field_layouts=profile_def.get('order_field_layouts') or [],
|
||||
coordinate_model=profile_def.get('coordinate_model') or {},
|
||||
reference_page_frames=profile_def.get('reference_page_frames') or {},
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
return {
|
||||
|
||||
-456
@@ -1,456 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/profile_field_source_mapping_service.py
|
||||
|
||||
用途:Profile 字段来源映射服务(Q18 抽取层裁决前置)——独立收集 Header / Table 列 /
|
||||
Vendor Comments 三个来源的候选观察,**不直接写 Observation 表**,只返回统一的
|
||||
FieldSourceCandidate 列表供 SourceMergeService 做 Q18 裁决合并。
|
||||
依赖:profile_vendor_comments_contract(parse_field_source_mappings/parse_named_regions)、
|
||||
field_split_core(execute_base_split_rule_set 用于 Vendor Comments 区域拆分)、
|
||||
coordinate_region_source_adapter(CoordinateRegionSourceAdapter 物理区域渲染)、
|
||||
reservation_relation_projection(ReservationRelationProjection 关系投影)。
|
||||
逻辑:严格「后端决定 UI」——本类输出每个候选的 target_scope/target_field_code/
|
||||
effective_line_no/value/source/evidence_ref/source_observation_metadata,
|
||||
前端只能消费这些投影字段,禁止自行推导业务状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_source_adapter import (
|
||||
CoordinateRegionEvidence,
|
||||
CoordinateRegionSourceAdapter,
|
||||
CoordinateRegionSourceResult,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.field_split_core import (
|
||||
CoreCapturedRelation,
|
||||
_CoreSegmentResult,
|
||||
execute_base_split_rule_set,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
|
||||
NamedRegion,
|
||||
ProfileFieldSourceMapping,
|
||||
parse_field_source_mappings,
|
||||
parse_named_regions,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.reservation_relation_projection import (
|
||||
ReservationRelationProjection,
|
||||
ReservationRelationProjectionResult,
|
||||
)
|
||||
|
||||
|
||||
FieldSourceLiteral = Literal['header_region', 'table_column', 'vendor_comments']
|
||||
|
||||
|
||||
@dataclass
|
||||
class FieldSourceCandidate:
|
||||
"""
|
||||
单来源单观察候选——Header/Table/Vendor Comments 各自产出后,由 SourceMergeService 裁决。
|
||||
|
||||
【后端决定 UI】:scope、line_no、value、format_valid、conflict_group_key 全部在本层
|
||||
计算完毕,前端只读投影,禁止自己用逻辑 if/else 推导。
|
||||
"""
|
||||
|
||||
source: FieldSourceLiteral
|
||||
target_scope: Literal['header', 'line']
|
||||
target_field_code: str
|
||||
target_field_id: str
|
||||
value: str
|
||||
normalized_value: str
|
||||
format_valid: bool | None # None = 本字段不需要格式校验(非 reservation)
|
||||
format_reason_code: str | None # format_valid=False 时的稳定诊断码(例:reservation_format_invalid)
|
||||
effective_line_no: int | None # 1-based;header 时为 None;default_all_lines 时为具体行号
|
||||
resolution_hint: Literal[
|
||||
'provisional', 'annotation_only', 'invalid_line_reference',
|
||||
] = 'provisional'
|
||||
relation_projection: ReservationRelationProjectionResult | None = None
|
||||
# 证据区——写入 Observation.evidence_quote / evidence_ref / evidence_metadata_json
|
||||
evidence_quote: str | None = None
|
||||
evidence_ref: str | None = None
|
||||
evidence_metadata: dict[str, Any] = field(default_factory=dict)
|
||||
# SourceMergeService 内部使用:冲突分组键 = (target_scope, target_field_code, effective_line_no)
|
||||
conflict_group_key: tuple[Any, ...] = ()
|
||||
|
||||
|
||||
class ProfileFieldSourceMappingService:
|
||||
"""
|
||||
三来源候选独立收集服务(路径判断与事实分离)。
|
||||
|
||||
【AI 触发时机】:订单文档抽取阶段(order_extraction_workflow 在 Observation 写入前)
|
||||
调用 collect_candidates() 返回候选列表,再交给 SourceMergeService 裁决合并。
|
||||
|
||||
核心执行顺序:
|
||||
[STEP 1] 解析 Profile definition_json 的 named_regions + field_source_mappings。
|
||||
[STEP 2] 对每个 mapping:
|
||||
a. header_source_enabled → 从 header_observations_by_source_ref 取现成观察
|
||||
b. table_source_enabled → 从 table_column_values 取(column_code + line_index)
|
||||
c. vendor_comments_enabled → 调 CoordinateRegionSourceAdapter + execute_base_split_rule_set
|
||||
[STEP 3] 对每个 Vendor Comments 拆分结果,调 ReservationRelationProjection.project
|
||||
生成 effective_line_no / resolution_hint。
|
||||
[STEP 4] 返回 FieldSourceCandidate 列表;未通过 format_policy 的候选保留
|
||||
value 但标记 format_valid=False(Q15:格式失败的值不丢弃)。
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
definition_json: dict[str, Any],
|
||||
header_observations_by_source_ref: dict[str, list[dict[str, Any]]] | None = None,
|
||||
table_column_values: dict[str, list[dict[str, Any]]] | None = None,
|
||||
page_glyphs_map: dict[int, dict[str, Any]] | None = None,
|
||||
# Reservation Relation Projection 三层判定表
|
||||
explicit_line_column_values: dict[int, str] | None = None,
|
||||
profile_business_line_numbers: dict[int, Any] | None = None,
|
||||
classified_logical_line_numbers: dict[int, int] | None = None,
|
||||
total_logical_lines: int = 0,
|
||||
# 格式策略调用方(保留注入点,避免本类直接 import reservation 校验模块造成循环)
|
||||
format_validator_callback=None,
|
||||
):
|
||||
self.definition_json = definition_json or {}
|
||||
self.header_observations_by_source_ref = header_observations_by_source_ref or {}
|
||||
self.table_column_values = table_column_values or {}
|
||||
self.page_glyphs_map = page_glyphs_map or {}
|
||||
self.explicit_line_column_values = explicit_line_column_values or {}
|
||||
self.profile_business_line_numbers = profile_business_line_numbers or {}
|
||||
self.classified_logical_line_numbers = classified_logical_line_numbers or {}
|
||||
self.total_logical_lines = total_logical_lines
|
||||
self.format_validator_callback = format_validator_callback
|
||||
# 预先解析契约(若失败抛 ValidationError 阻断运行,避免输出坏数据)
|
||||
self.named_regions: dict[str, NamedRegion] = parse_named_regions(
|
||||
self.definition_json.get('named_regions'),
|
||||
)
|
||||
self.mappings: list[ProfileFieldSourceMapping] = parse_field_source_mappings(
|
||||
self.definition_json.get('field_source_mappings'),
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 对外主入口
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def collect_candidates(self) -> list[FieldSourceCandidate]:
|
||||
"""
|
||||
返回全量候选。任何内部失败都返回稳定 status 候选(不抛错阻断其他字段)。
|
||||
调用方:SourceMergeService.merge_and_decide() → 再调用 obs 写入。
|
||||
"""
|
||||
candidates: list[FieldSourceCandidate] = []
|
||||
for mapping in self.mappings:
|
||||
if mapping.header_source_enabled and mapping.header_source_ref:
|
||||
candidates.extend(self._collect_header_source(mapping))
|
||||
if mapping.table_source_enabled and mapping.table_column_code:
|
||||
candidates.extend(self._collect_table_source(mapping))
|
||||
if mapping.vendor_comments_enabled and mapping.vendor_comments_region_ref:
|
||||
candidates.extend(self._collect_vendor_comments_source(mapping))
|
||||
for cand in candidates:
|
||||
cand.conflict_group_key = (cand.target_scope, cand.target_field_code, cand.effective_line_no)
|
||||
return candidates
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 三个来源分支(独立收集,不互相读数据——满足 Q18 先独立再裁决)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _collect_header_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
|
||||
"""Header 区域来源——从 caller 传入的 header_observations_by_source_ref 读取。"""
|
||||
header_items = self.header_observations_by_source_ref.get(mapping.header_source_ref or '', [])
|
||||
results: list[FieldSourceCandidate] = []
|
||||
for item in header_items:
|
||||
raw_value = str(item.get('value') or '')
|
||||
format_valid, reason = self._check_format(mapping, raw_value)
|
||||
results.append(FieldSourceCandidate(
|
||||
source='header_region',
|
||||
target_scope=mapping.target_scope,
|
||||
target_field_code=mapping.target_field_code,
|
||||
target_field_id=mapping.target_field_id,
|
||||
value=raw_value,
|
||||
normalized_value=_normalize_string(raw_value),
|
||||
format_valid=format_valid,
|
||||
format_reason_code=reason,
|
||||
effective_line_no=None, # header scope 固定 None
|
||||
evidence_quote=raw_value[:512],
|
||||
evidence_ref=str(item.get('evidence_ref') or '') or None,
|
||||
evidence_metadata=dict(item.get('evidence_metadata') or {}),
|
||||
))
|
||||
return results
|
||||
|
||||
def _collect_table_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
|
||||
"""表身列来源——从 caller 传入的 table_column_values[column_code] 读取,每行一个候选。"""
|
||||
rows = self.table_column_values.get(mapping.table_column_code or '', [])
|
||||
results: list[FieldSourceCandidate] = []
|
||||
for row in rows:
|
||||
try:
|
||||
line_no = int(row.get('line_index')) + 1 # 转 1-based
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
raw_value = str(row.get('value') or '')
|
||||
format_valid, reason = self._check_format(mapping, raw_value)
|
||||
results.append(FieldSourceCandidate(
|
||||
source='table_column',
|
||||
target_scope=mapping.target_scope,
|
||||
target_field_code=mapping.target_field_code,
|
||||
target_field_id=mapping.target_field_id,
|
||||
value=raw_value,
|
||||
normalized_value=_normalize_string(raw_value),
|
||||
format_valid=format_valid,
|
||||
format_reason_code=reason,
|
||||
effective_line_no=line_no,
|
||||
evidence_quote=raw_value[:512],
|
||||
evidence_ref=str(row.get('evidence_ref') or '') or None,
|
||||
evidence_metadata=dict(row.get('evidence_metadata') or {}),
|
||||
))
|
||||
return results
|
||||
|
||||
def _collect_vendor_comments_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
|
||||
"""
|
||||
Vendor Comments 来源——三步走:
|
||||
1. CoordinateRegionSourceAdapter 渲染区域原文 + bbox 证据;
|
||||
2. execute_base_split_rule_set 拆出段(带 captured_relation);
|
||||
3. ReservationRelationProjection 投影关系到 effective_line_no / resolution_hint。
|
||||
"""
|
||||
region_ref = mapping.vendor_comments_region_ref or ''
|
||||
region = self.named_regions.get(region_ref)
|
||||
if region is None:
|
||||
return [self._missing_region_fallback(mapping, region_ref)]
|
||||
adapter = CoordinateRegionSourceAdapter(region, self.page_glyphs_map)
|
||||
region_result: CoordinateRegionSourceResult = adapter.extract()
|
||||
if region_result.status != 'available' or not mapping.vendor_comments_split_rule_set:
|
||||
return [self._unavailable_region_candidate(mapping, region_result)]
|
||||
|
||||
split_result = execute_base_split_rule_set(
|
||||
raw_value=region_result.raw_text,
|
||||
rule_set=mapping.vendor_comments_split_rule_set,
|
||||
lines=region_result.lines or None,
|
||||
)
|
||||
|
||||
projector = ReservationRelationProjection(
|
||||
relation_policy=mapping.relation_policy,
|
||||
line_reference_basis=mapping.line_reference_basis,
|
||||
missing_relation_policy=mapping.missing_relation_policy,
|
||||
)
|
||||
# 先收集 mapped 段,再收集 evidence_only 段(annotation_only 用)
|
||||
all_segments: list[_CoreSegmentResult] = list(split_result.segments) + list(split_result.evidence_only_segments)
|
||||
results: list[FieldSourceCandidate] = []
|
||||
token_evidence_map = _build_evidence_ref_map(region_result.evidence_tokens)
|
||||
for seg in all_segments:
|
||||
rel_proj = projector.project(
|
||||
captured_relation=seg.captured_relation,
|
||||
explicit_line_column_values=self.explicit_line_column_values,
|
||||
profile_business_line_numbers=self.profile_business_line_numbers,
|
||||
classified_logical_line_numbers=self.classified_logical_line_numbers,
|
||||
)
|
||||
format_valid, reason = self._check_format(mapping, seg.normalized_text)
|
||||
if rel_proj.resolution == 'bound_to_line':
|
||||
results.append(self._make_vc_candidate(
|
||||
mapping=mapping, seg=seg, rel_proj=rel_proj,
|
||||
region_result=region_result, token_evidence_map=token_evidence_map,
|
||||
effective_line_no=rel_proj.resolved_logical_line_no,
|
||||
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
|
||||
))
|
||||
elif rel_proj.resolution == 'default_all_lines':
|
||||
# 每行都生成一个(common case:整个 Vendor Comments 段没有 line 号引用)
|
||||
for line_idx in range(1, max(1, self.total_logical_lines) + 1):
|
||||
results.append(self._make_vc_candidate(
|
||||
mapping=mapping, seg=seg, rel_proj=rel_proj,
|
||||
region_result=region_result, token_evidence_map=token_evidence_map,
|
||||
effective_line_no=line_idx if mapping.target_scope == 'line' else None,
|
||||
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
|
||||
))
|
||||
elif rel_proj.resolution == 'annotation_only':
|
||||
results.append(self._make_vc_candidate(
|
||||
mapping=mapping, seg=seg, rel_proj=rel_proj,
|
||||
region_result=region_result, token_evidence_map=token_evidence_map,
|
||||
effective_line_no=None,
|
||||
resolution_hint='annotation_only', format_valid=format_valid, format_reason=reason,
|
||||
))
|
||||
elif rel_proj.resolution == 'invalid_line_reference':
|
||||
results.append(self._make_vc_candidate(
|
||||
mapping=mapping, seg=seg, rel_proj=rel_proj,
|
||||
region_result=region_result, token_evidence_map=token_evidence_map,
|
||||
effective_line_no=None,
|
||||
resolution_hint='invalid_line_reference', format_valid=False,
|
||||
format_reason=reason or 'invalid_line_reference',
|
||||
))
|
||||
else:
|
||||
# default_header_only / conflict_unresolved
|
||||
results.append(self._make_vc_candidate(
|
||||
mapping=mapping, seg=seg, rel_proj=rel_proj,
|
||||
region_result=region_result, token_evidence_map=token_evidence_map,
|
||||
effective_line_no=None if mapping.target_scope == 'header' else None,
|
||||
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
|
||||
))
|
||||
return results
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 辅助:格式校验(Q15)+ Vendor Comments 候选构造
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _check_format(
|
||||
self, mapping: ProfileFieldSourceMapping, value: str,
|
||||
) -> tuple[bool | None, str | None]:
|
||||
"""返回 (format_valid, reason_code);非 reservation 字段返回 (None, None)。"""
|
||||
if mapping.target_field_code != 'reservation_id':
|
||||
return None, None
|
||||
if not value:
|
||||
return False, 'reservation_format_empty'
|
||||
if self.format_validator_callback is not None:
|
||||
ok = bool(self.format_validator_callback(mapping.format_policy, value))
|
||||
return (True, None) if ok else (False, 'reservation_format_invalid')
|
||||
# 默认回退全局 validated_reservation_id(Q15 方案 A:本期不重构全局)
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
ok = validated_reservation_id(value) is not None
|
||||
return (True, None) if ok else (False, 'reservation_format_invalid')
|
||||
|
||||
@staticmethod
|
||||
def _missing_region_fallback(mapping: ProfileFieldSourceMapping, region_ref: str) -> FieldSourceCandidate:
|
||||
return FieldSourceCandidate(
|
||||
source='vendor_comments',
|
||||
target_scope=mapping.target_scope,
|
||||
target_field_code=mapping.target_field_code,
|
||||
target_field_id=mapping.target_field_id,
|
||||
value='',
|
||||
normalized_value='',
|
||||
format_valid=None,
|
||||
format_reason_code=None,
|
||||
effective_line_no=None,
|
||||
resolution_hint='provisional',
|
||||
evidence_quote=None,
|
||||
evidence_ref=None,
|
||||
evidence_metadata={'reason': 'named_region_not_found', 'region_ref': region_ref},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _unavailable_region_candidate(
|
||||
mapping: ProfileFieldSourceMapping, region_result: CoordinateRegionSourceResult,
|
||||
) -> FieldSourceCandidate:
|
||||
return FieldSourceCandidate(
|
||||
source='vendor_comments',
|
||||
target_scope=mapping.target_scope,
|
||||
target_field_code=mapping.target_field_code,
|
||||
target_field_id=mapping.target_field_id,
|
||||
value='',
|
||||
normalized_value='',
|
||||
format_valid=None,
|
||||
format_reason_code=None,
|
||||
effective_line_no=None,
|
||||
resolution_hint='provisional',
|
||||
evidence_quote=region_result.raw_text[:512] or None,
|
||||
evidence_ref=None,
|
||||
evidence_metadata={
|
||||
'reason': region_result.diagnostic_code or 'named_region_unavailable',
|
||||
'diagnostic_message': region_result.diagnostic_message,
|
||||
'region_id': region_result.region_id,
|
||||
},
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _make_vc_candidate(
|
||||
*,
|
||||
mapping: ProfileFieldSourceMapping,
|
||||
seg: _CoreSegmentResult,
|
||||
rel_proj: ReservationRelationProjectionResult,
|
||||
region_result: CoordinateRegionSourceResult,
|
||||
token_evidence_map: dict[str, list[CoordinateRegionEvidence]],
|
||||
effective_line_no: int | None,
|
||||
resolution_hint: Literal['provisional', 'annotation_only', 'invalid_line_reference'],
|
||||
format_valid: bool | None,
|
||||
format_reason: str | None,
|
||||
) -> FieldSourceCandidate:
|
||||
token_ev = _find_best_token_evidence(token_evidence_map, seg.normalized_text)
|
||||
evidence_quote = seg.raw_text[:512] or None
|
||||
evidence_ref = _vc_evidence_ref(region_result, seg, token_ev)
|
||||
metadata: dict[str, Any] = {
|
||||
'region_id': region_result.region_id,
|
||||
'segment_id': seg.segment_id,
|
||||
'rule_id': seg.rule_id,
|
||||
'matcher_type': seg.matcher_type,
|
||||
'handling': seg.handling,
|
||||
'line_bounds_in_region': [seg.line_no, seg.line_end_no],
|
||||
'captured_relation_raw': (
|
||||
None if seg.captured_relation is None else {
|
||||
'type': seg.captured_relation.type,
|
||||
'line_no': seg.captured_relation.line_no,
|
||||
'raw_text': seg.captured_relation.raw_text,
|
||||
}
|
||||
),
|
||||
'relation_projection': _proj_to_json(rel_proj),
|
||||
'best_token': (None if token_ev is None else {
|
||||
'page_no': token_ev.page_no,
|
||||
'x0': token_ev.x0, 'y0': token_ev.y0,
|
||||
'x1': token_ev.x1, 'y1': token_ev.y1,
|
||||
'text': token_ev.text,
|
||||
}),
|
||||
}
|
||||
return FieldSourceCandidate(
|
||||
source='vendor_comments',
|
||||
target_scope=mapping.target_scope,
|
||||
target_field_code=mapping.target_field_code,
|
||||
target_field_id=mapping.target_field_id,
|
||||
value=seg.raw_text,
|
||||
normalized_value=seg.normalized_text,
|
||||
format_valid=format_valid,
|
||||
format_reason_code=format_reason,
|
||||
effective_line_no=effective_line_no,
|
||||
resolution_hint=resolution_hint,
|
||||
relation_projection=rel_proj,
|
||||
evidence_quote=evidence_quote,
|
||||
evidence_ref=evidence_ref,
|
||||
evidence_metadata=metadata,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 模块级纯函数(避免每次 Service 实例化重复加载)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _normalize_string(v: str) -> str:
|
||||
return ' '.join(str(v or '').split()).strip()
|
||||
|
||||
|
||||
def _build_evidence_ref_map(tokens: list[CoordinateRegionEvidence]) -> dict[str, list[CoordinateRegionEvidence]]:
|
||||
out: dict[str, list[CoordinateRegionEvidence]] = {}
|
||||
for t in tokens:
|
||||
out.setdefault(_normalize_string(t.text), []).append(t)
|
||||
return out
|
||||
|
||||
|
||||
def _find_best_token_evidence(
|
||||
evidence_map: dict[str, list[CoordinateRegionEvidence]], value: str,
|
||||
) -> CoordinateRegionEvidence | None:
|
||||
norm = _normalize_string(value)
|
||||
if norm in evidence_map and evidence_map[norm]:
|
||||
return evidence_map[norm][0]
|
||||
# 降级:子串命中
|
||||
for key, tokens in evidence_map.items():
|
||||
if norm and (norm in key or key in norm) and tokens:
|
||||
return tokens[0]
|
||||
return None
|
||||
|
||||
|
||||
def _vc_evidence_ref(
|
||||
region_result: CoordinateRegionSourceResult,
|
||||
seg: _CoreSegmentResult,
|
||||
token: CoordinateRegionEvidence | None,
|
||||
) -> str:
|
||||
"""
|
||||
稳定 Observation.evidence_ref。
|
||||
格式:vc://<region_id>/p<page_no>/seg-<segment_id>[:<x0>-<y0>-<x1>-<y1>]
|
||||
"""
|
||||
base = f"vc://{region_result.region_id}/p{region_result.page_no}/seg-{seg.segment_id}"
|
||||
if token is not None:
|
||||
base += (
|
||||
f":{round(token.x0, 4)}-{round(token.y0, 4)}-"
|
||||
f"{round(token.x1, 4)}-{round(token.y1, 4)}"
|
||||
)
|
||||
return base[:512]
|
||||
|
||||
|
||||
def _proj_to_json(p: ReservationRelationProjectionResult) -> dict[str, Any]:
|
||||
return {
|
||||
'line_reference_basis': p.line_reference_basis,
|
||||
'resolution': p.resolution,
|
||||
'resolved_logical_line_no': p.resolved_logical_line_no,
|
||||
'annotation_reason': p.annotation_reason,
|
||||
'invalid_reference_raw_value': p.invalid_reference_raw_value,
|
||||
'invalid_reference_line_no': p.invalid_reference_line_no,
|
||||
'audit_chain_count': 0 if p.audit_chain is None else len(p.audit_chain),
|
||||
}
|
||||
-338
@@ -1,338 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/profile_vendor_comments_contract.py
|
||||
|
||||
用途:Profile 顶层新增的 Vendor Comments 三来源契约(不修改现有 OrderCoordinateProfile 字段,
|
||||
保持「路径判断与事实分离」——definition_json.get 读取命名区域和字段来源映射)。
|
||||
依赖:Pydantic、field_split_core.BaseSplitRuleSet、RelativeRegion(来自 order_profile)。
|
||||
逻辑:对外暴露 parse_named_regions() / parse_field_source_mappings() / validate_format_policy()
|
||||
三个稳定入口;所有变更是否触发「回 Draft + 重新验证」由 profile_regions_require_draft()
|
||||
判定,禁止各业务点自行假设回 Draft 条件。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Literal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.field_split_core import (
|
||||
BaseSplitRuleSet,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
RelativeRegion,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 顶层 Pydantic 契约——definition_json 结构
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
VC_MODEL_CONFIG = ConfigDict(extra='forbid', validate_assignment=True)
|
||||
|
||||
|
||||
class NamedRegion(BaseModel):
|
||||
"""
|
||||
物理来源命名区域(Q14 冻结)——管理员圈选的坐标框。
|
||||
|
||||
【关键约束】:不是 Schema 字段区域伪装,是 Vendor Comments 等非 XFA 正文块的真实
|
||||
阅读区域。变更此对象必须回 Draft(由 profile_regions_require_draft 判定)。
|
||||
"""
|
||||
|
||||
model_config = VC_MODEL_CONFIG
|
||||
|
||||
region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$')
|
||||
label: str = Field(min_length=1, max_length=160)
|
||||
region: RelativeRegion
|
||||
page_scope: Literal['first_page', 'last_page', 'all_pages', 'exact_page'] = 'last_page'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
selection_mode: Literal['fixed_region', 'auto_take_last_qualified'] = 'fixed_region'
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_page_semantics(self) -> 'NamedRegion':
|
||||
if self.page_scope == 'exact_page' and self.page_no is None:
|
||||
raise ValueError('exact_page named region requires page_no')
|
||||
if self.page_scope != 'exact_page' and self.page_no is not None:
|
||||
raise ValueError('page_no is only allowed for exact_page named region')
|
||||
return self
|
||||
|
||||
|
||||
class ReservationFormatPolicy(BaseModel):
|
||||
"""
|
||||
Reservation 格式校验策略(Q15 冻结)——Profile 级受控策略,未配置时回退全局 5/10 纯数字。
|
||||
|
||||
首期仅支持 numeric_5_or_10 / custom_safe_regex 两种;custom_safe_regex 必须经过
|
||||
长度限制、捕获组限制、危险表达式黑名单与超时上限 4 层门禁。
|
||||
"""
|
||||
|
||||
model_config = VC_MODEL_CONFIG
|
||||
|
||||
mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex'] = 'inherit_global'
|
||||
pattern: str | None = Field(default=None, min_length=1, max_length=1024)
|
||||
max_capture_groups: int = Field(default=2, ge=0, le=8)
|
||||
timeout_ms: int = Field(default=30, ge=10, le=500)
|
||||
case_sensitive: bool = False
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_regex_policy(self) -> 'ReservationFormatPolicy':
|
||||
if self.mode != 'custom_safe_regex':
|
||||
if self.pattern is not None:
|
||||
raise ValueError('pattern only allowed for custom_safe_regex mode')
|
||||
return self
|
||||
if not self.pattern:
|
||||
raise ValueError('custom_safe_regex requires a non-empty pattern')
|
||||
_validate_safe_regex_pattern(
|
||||
self.pattern,
|
||||
max_groups=self.max_capture_groups,
|
||||
case_sensitive=self.case_sensitive,
|
||||
)
|
||||
return self
|
||||
|
||||
|
||||
class ProfileFieldSourceMapping(BaseModel):
|
||||
"""
|
||||
Profile 级字段来源映射(Q9 冻结,并列 split_rules)——声明一个 Schema 字段从三来源
|
||||
(header/table_column/vendor_comments)哪几个抽取,以及各自使用的拆分规则与关系策略。
|
||||
"""
|
||||
|
||||
model_config = VC_MODEL_CONFIG
|
||||
|
||||
mapping_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
target_scope: Literal['header', 'line']
|
||||
target_field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
target_field_id: str = Field(min_length=1, max_length=128)
|
||||
|
||||
# 三来源开关——未启用的来源在 ProfileFieldSourceMappingService 直接跳过
|
||||
header_source_enabled: bool = False
|
||||
header_source_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
header_normalizer_key: str | None = Field(default=None, min_length=1, max_length=64)
|
||||
|
||||
table_source_enabled: bool = False
|
||||
table_column_code: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
|
||||
vendor_comments_enabled: bool = False
|
||||
vendor_comments_region_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_-]{0,95}$')
|
||||
vendor_comments_split_rule_set: BaseSplitRuleSet | None = None
|
||||
|
||||
# 关系策略(Q2 双层设计)——本期仅 reservation_id 绑定明细行使用 bind_target_line
|
||||
relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'] = 'no_relation'
|
||||
missing_relation_policy: Literal['default_all_lines', 'default_header_only', 'fallback_single_line_when_no_reference'] = 'default_header_only'
|
||||
line_reference_basis: Literal['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no'] = 'profile_business_line_no'
|
||||
|
||||
# 三来源空值互补策略——Q4 冲突矩阵里不同 scope 独立保留,同 scope 值不一致 Review
|
||||
fill_missing_from_other_sources: bool = True
|
||||
|
||||
format_policy: ReservationFormatPolicy = Field(default_factory=ReservationFormatPolicy)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_source_refs(self) -> 'ProfileFieldSourceMapping':
|
||||
if self.header_source_enabled and not self.header_source_ref:
|
||||
raise ValueError('header_source_ref is required when header_source_enabled')
|
||||
if self.table_source_enabled and not self.table_column_code:
|
||||
raise ValueError('table_column_code is required when table_source_enabled')
|
||||
if self.vendor_comments_enabled:
|
||||
if not self.vendor_comments_region_ref:
|
||||
raise ValueError('vendor_comments_region_ref is required when vendor_comments_enabled')
|
||||
if not self.vendor_comments_split_rule_set:
|
||||
raise ValueError('vendor_comments_split_rule_set is required when vendor_comments_enabled')
|
||||
return self
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 稳定读取工具:接受 None / 脏 dict,返回归一化契约对象(路径判断与事实分离)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def parse_named_regions(value: Any) -> dict[str, NamedRegion]:
|
||||
"""
|
||||
从 definition_json.named_regions(或 None)解析命名区域字典。
|
||||
|
||||
【AI 触发时机】:读取 Profile 配置阶段、预览阶段或变更比对阶段调用。
|
||||
核心逻辑:值为 None/空 dict 时返回空字典(允许客户先不配 Vendor Comments 区域);
|
||||
未知键直接保留映射,不抛错;坏值立刻抛 ValidationError 避免运行时污染。
|
||||
|
||||
Args:
|
||||
value: Profile definition_json.get('named_regions') 原值。
|
||||
|
||||
Returns:
|
||||
{region_id: NamedRegion} 字典。
|
||||
"""
|
||||
if value is None:
|
||||
return {}
|
||||
if not isinstance(value, dict):
|
||||
raise ValidationError(
|
||||
'definition_json.named_regions must be an object',
|
||||
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
|
||||
)
|
||||
result: dict[str, NamedRegion] = {}
|
||||
for key, raw in value.items():
|
||||
if not re.match(r'^[a-z][a-z0-9_-]{0,95}$', str(key)):
|
||||
raise ValidationError(
|
||||
f'named region key {key!r} is invalid',
|
||||
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
|
||||
)
|
||||
try:
|
||||
item = NamedRegion.model_validate(raw) if isinstance(raw, dict) else raw
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
f'named region {key!r} is invalid: {exc}',
|
||||
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
|
||||
) from exc
|
||||
if item.region_id != key:
|
||||
raise ValidationError(
|
||||
f'named region key {key!r} must match nested region_id {item.region_id!r}',
|
||||
code='SHIPPING.PROFILE_NAMED_REGIONS_MISMATCH',
|
||||
)
|
||||
result[key] = item
|
||||
return result
|
||||
|
||||
|
||||
def parse_field_source_mappings(value: Any) -> list[ProfileFieldSourceMapping]:
|
||||
"""
|
||||
从 definition_json.field_source_mappings(或 None)解析字段来源映射列表。
|
||||
|
||||
核心逻辑:返回值为稳定顺序列表,不做去重(重复的 target_scope/target_field_code
|
||||
组合将由 SourceMergeService 在抽取层做 Q18 冲突裁决)。
|
||||
"""
|
||||
if value is None:
|
||||
return []
|
||||
if not isinstance(value, list):
|
||||
raise ValidationError(
|
||||
'definition_json.field_source_mappings must be a list',
|
||||
code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID',
|
||||
)
|
||||
results: list[ProfileFieldSourceMapping] = []
|
||||
for raw in value:
|
||||
try:
|
||||
results.append(ProfileFieldSourceMapping.model_validate(raw))
|
||||
except ValueError as exc:
|
||||
raise ValidationError(
|
||||
f'field source mapping is invalid: {exc}',
|
||||
code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID',
|
||||
) from exc
|
||||
return results
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 变更回 Draft 门禁(Q14 冻结:区域变化必须使 Profile 回 Draft)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
REGION_CHANGE_REQUIRES_DRAFT_KEYS = frozenset({
|
||||
'region', 'page_scope', 'page_no', 'selection_mode',
|
||||
})
|
||||
|
||||
|
||||
def profile_regions_require_draft(
|
||||
*,
|
||||
old_named_regions: Any,
|
||||
new_named_regions: Any,
|
||||
) -> bool:
|
||||
"""
|
||||
判断 named_regions 变更是否触发 Profile 回 Draft + 重新验证 + 盲测 + 发布。
|
||||
|
||||
核心逻辑(fail-safe):任何 region 主键、坐标、页作用域、选取模式的增删改一律回 Draft;
|
||||
仅 label 文案调整(便于管理员标注说明)不触发。
|
||||
"""
|
||||
try:
|
||||
old_map = parse_named_regions(old_named_regions)
|
||||
new_map = parse_named_regions(new_named_regions)
|
||||
except ValidationError:
|
||||
return True # 解析失败默认回 Draft(fail-close)
|
||||
if set(old_map.keys()) != set(new_map.keys()):
|
||||
return True
|
||||
for region_id in old_map:
|
||||
old_region = old_map[region_id]
|
||||
new_region = new_map[region_id]
|
||||
for key in REGION_CHANGE_REQUIRES_DRAFT_KEYS:
|
||||
if getattr(old_region, key) != getattr(new_region, key):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def field_source_mappings_require_draft(
|
||||
*,
|
||||
old_mappings: Any,
|
||||
new_mappings: Any,
|
||||
) -> bool:
|
||||
"""
|
||||
判断 field_source_mappings 变更是否触发回 Draft。
|
||||
|
||||
核心逻辑:除了纯 label 类改动外的任何增删改一律回 Draft(首期全量回 Draft,保留细粒度
|
||||
门禁的未来扩展点)。
|
||||
"""
|
||||
try:
|
||||
old_list = parse_field_source_mappings(old_mappings)
|
||||
new_list = parse_field_source_mappings(new_mappings)
|
||||
except ValidationError:
|
||||
return True
|
||||
if len(old_list) != len(new_list):
|
||||
return True
|
||||
old_payload = _stable_mapping_dumps(old_list)
|
||||
new_payload = _stable_mapping_dumps(new_list)
|
||||
return old_payload != new_payload
|
||||
|
||||
|
||||
def _stable_mapping_dumps(items: list[ProfileFieldSourceMapping]) -> str:
|
||||
payload = [m.model_dump(mode='json', sort_keys=True) for m in items]
|
||||
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 安全正则门禁(Q15 custom_safe_regex 发布前必过)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
_UNSAFE_PATTERN_MARKERS = (
|
||||
r'\(.+[+*]\)\s*[+*]', # 嵌套量词 例: (a+)+
|
||||
r'\(\.?\*\)\s*\*', # 多重.* 回溯
|
||||
r'\(\[.*\]\)\{[0-9]+,[0-9]*\}', # 大范围字符类重复
|
||||
r'(?<!\\)\\[bBwWsSdD].*[+*]', # 通用字符集 + 无限量词
|
||||
r'\(\?:?\^?\$?.*\)\?\?', # 前后查找量词叠加
|
||||
)
|
||||
|
||||
|
||||
def _validate_safe_regex_pattern(pattern: str, *, max_groups: int, case_sensitive: bool) -> None:
|
||||
"""
|
||||
custom_safe_regex 的发布前样本验证门禁(Q15)——编译期就拦截危险表达式。
|
||||
【注意】:运行时还需配合 timeout_ms 的 signal 看门狗(在 regex_runner_safe 中实现)。
|
||||
"""
|
||||
if len(pattern) > 1024:
|
||||
raise ValueError('custom_safe_regex pattern exceeds 1024 characters')
|
||||
for marker in _UNSAFE_PATTERN_MARKERS:
|
||||
if re.search(marker, pattern):
|
||||
raise ValueError('custom_safe_regex pattern looks potentially catastrophic')
|
||||
flags = 0 if case_sensitive else re.IGNORECASE
|
||||
try:
|
||||
compiled = re.compile(pattern, flags)
|
||||
except re.error as exc:
|
||||
raise ValueError(f'custom_safe_regex pattern failed to compile: {exc}') from exc
|
||||
if compiled.groups > max_groups:
|
||||
raise ValueError(
|
||||
f'custom_safe_regex has {compiled.groups} capture groups; limit is {max_groups}'
|
||||
)
|
||||
_ = compiled # 引用仅用于静态检查
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 校验和(盲测/发布基准比对)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def field_source_mappings_checksum(mappings: list[ProfileFieldSourceMapping]) -> str:
|
||||
"""稳定 SHA-256 校验和,供发布冻结与审计引用。"""
|
||||
payload = _stable_mapping_dumps(mappings).encode('utf-8')
|
||||
return hashlib.sha256(payload).hexdigest()
|
||||
|
||||
|
||||
def named_regions_checksum(regions: dict[str, NamedRegion]) -> str:
|
||||
"""稳定 SHA-256 校验和,供区域变更历史比对。"""
|
||||
payload = json.dumps(
|
||||
{rid: r.model_dump(mode='json', sort_keys=True) for rid, r in regions.items()},
|
||||
ensure_ascii=True, sort_keys=True, separators=(',', ':'),
|
||||
).encode('utf-8')
|
||||
return hashlib.sha256(payload).hexdigest()
|
||||
-152
@@ -1,152 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/reservation_format_policy_service.py
|
||||
|
||||
用途:Q15 Reservation ID 格式策略服务——Profile 级 format_policy 受控入口。
|
||||
首期(阶段 2)保持「回退全局 validated_reservation_id(numeric_5_or_10 硬编码)」
|
||||
不变;为未来 custom_safe_regex / 字母型 Reservation 保留扩展点。
|
||||
依赖:profile_vendor_comments_contract.ReservationFormatPolicy;
|
||||
reservation_id.validated_reservation_id(全局回退)。
|
||||
逻辑:【技术重试与业务决策分离】——本类只负责**格式判断**,不改变值、不生成 Observation,
|
||||
调用方(ProfileFieldSourceMappingService._check_format)根据返回值标记
|
||||
reservation_format_invalid,但不丢弃候选(保留为 Review 证据展示)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
|
||||
ReservationFormatPolicy,
|
||||
)
|
||||
|
||||
|
||||
RESERVATION_NUMERIC_5_OR_10_RE = re.compile(r'^(?:\d{5}|\d{10})$')
|
||||
|
||||
|
||||
@dataclass
|
||||
class FormatPolicyResult:
|
||||
"""格式校验结果——只描述事实,不携带业务动作。"""
|
||||
|
||||
valid: bool
|
||||
mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex']
|
||||
normalized_value: str | None = None # 仅 valid=True 时返回规范化值
|
||||
reason_code: str | None = None # valid=False 时的稳定诊断码
|
||||
|
||||
@property
|
||||
def should_block_auto_create(self) -> bool:
|
||||
"""格式失败的值不得自动建单(Q15 冻结)。"""
|
||||
return not self.valid
|
||||
|
||||
|
||||
class ReservationFormatPolicyService:
|
||||
"""
|
||||
Profile 级 Reservation 格式策略受控入口。
|
||||
|
||||
【AI 触发时机】:ProfileFieldSourceMappingService 收集候选、或 Candidate
|
||||
Qualification 最终门禁时调用 check()。禁止任何地方直接
|
||||
if re.match(r'^\d{5,10}$', v) 绕过策略层。
|
||||
"""
|
||||
|
||||
def check(self, policy: ReservationFormatPolicy, raw_value: str) -> FormatPolicyResult:
|
||||
"""
|
||||
执行一次格式校验。调用方不得丢弃失败候选,必须将原因码写入
|
||||
FieldSourceCandidate.format_reason_code。
|
||||
|
||||
核心路径(Q15 冻结):
|
||||
① mode=inherit_global → 调全局 validated_reservation_id 保持历史 71 调用方口径;
|
||||
② mode=numeric_5_or_10 → 等价于全局(显式模式;便于未来全局重构时切换默认);
|
||||
③ mode=custom_safe_regex → 调用发布前已通过 Pydantic 门禁的安全正则。
|
||||
"""
|
||||
value = (raw_value or '').strip()
|
||||
if not value:
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode=policy.mode, normalized_value=None,
|
||||
reason_code='reservation_format_empty',
|
||||
)
|
||||
mode = policy.mode
|
||||
if mode in {'inherit_global', 'numeric_5_or_10'}:
|
||||
return self._check_numeric_5_or_10(value, mode)
|
||||
if mode == 'custom_safe_regex':
|
||||
return self._check_custom_safe_regex(policy, value)
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode=mode, normalized_value=None,
|
||||
reason_code='reservation_format_unknown_mode',
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 内部实现
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _check_numeric_5_or_10(
|
||||
value: str,
|
||||
mode: Literal['inherit_global', 'numeric_5_or_10'],
|
||||
) -> FormatPolicyResult:
|
||||
"""纯数字 5/10 位——默认回退全局校验,但通过独立模块输出稳定结果。"""
|
||||
# 先尝试全局 validated_reservation_id(保持与 71 调用方一致),失败再用本模块常量兜底
|
||||
try:
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
global_result = validated_reservation_id(value)
|
||||
if global_result is not None:
|
||||
return FormatPolicyResult(
|
||||
valid=True, mode=mode, normalized_value=global_result,
|
||||
reason_code=None,
|
||||
)
|
||||
except Exception: # fail-safe:若全局模块异常,不阻塞结果
|
||||
pass
|
||||
match = RESERVATION_NUMERIC_5_OR_10_RE.match(value)
|
||||
if match:
|
||||
return FormatPolicyResult(
|
||||
valid=True, mode=mode, normalized_value=value,
|
||||
reason_code=None,
|
||||
)
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode=mode, normalized_value=None,
|
||||
reason_code='reservation_format_invalid',
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _check_custom_safe_regex(policy: ReservationFormatPolicy, value: str) -> FormatPolicyResult:
|
||||
"""安全正则匹配——编译缓存;捕获组第 1 组作为规范化值(否则整串)。"""
|
||||
pattern = policy.pattern or ''
|
||||
flags = 0 if policy.case_sensitive else re.IGNORECASE
|
||||
try:
|
||||
compiled = re.compile(pattern, flags)
|
||||
except re.error as exc:
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode='custom_safe_regex', normalized_value=None,
|
||||
reason_code=f'reservation_format_regex_compile_error:{exc.__class__.__name__}',
|
||||
)
|
||||
# 发布前样本验证门禁已限制 catastrophic 风险;这里仅以标准 library 限制长度
|
||||
if len(value) > 128:
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode='custom_safe_regex', normalized_value=None,
|
||||
reason_code='reservation_format_value_too_long',
|
||||
)
|
||||
match = compiled.search(value)
|
||||
if not match:
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode='custom_safe_regex', normalized_value=None,
|
||||
reason_code='reservation_format_invalid',
|
||||
)
|
||||
# 规范化值:第 1 捕获组 → 整串
|
||||
normalized: str = value
|
||||
if compiled.groups >= 1:
|
||||
try:
|
||||
first_group = match.group(1)
|
||||
if first_group:
|
||||
normalized = str(first_group).strip()
|
||||
except (IndexError, re.error):
|
||||
normalized = match.group(0) or value
|
||||
normalized = normalized.strip()
|
||||
if not normalized:
|
||||
return FormatPolicyResult(
|
||||
valid=False, mode='custom_safe_regex', normalized_value=None,
|
||||
reason_code='reservation_format_capture_empty',
|
||||
)
|
||||
return FormatPolicyResult(
|
||||
valid=True, mode='custom_safe_regex', normalized_value=normalized,
|
||||
reason_code=None,
|
||||
)
|
||||
-228
@@ -1,228 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/reservation_relation_projection.py
|
||||
|
||||
用途:Reservation 关系投影(Q2 双层设计 + Q12 invalid_line_reference 独立原因码)。
|
||||
将拆分引擎内部捕获的 captured_relation + Profile 关系策略 relation_policy,
|
||||
映射为「绑定到哪条行、是否 annotation_only、是否 invalid_line_reference 独立」三输出。
|
||||
依赖:field_split_core.CoreCapturedRelation(来自 _CoreSegmentResult.captured_relation)、
|
||||
ProfileFieldSourceMapping.relation_policy / line_reference_basis。
|
||||
逻辑:严格遵循「路径判断与事实分离」——拆分引擎事实(line_no)只作为证据,
|
||||
最终绑定路径必须经过 line_reference_basis 三层映射校验后裁决;
|
||||
失败不抛异常,输出稳定 reason_code 供审计和前端翻译。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.field_split_core import (
|
||||
CoreCapturedRelation,
|
||||
)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReservationRelationProjectionResult:
|
||||
"""关系投影最终结果——只输出明确分支,禁止上游自行判断。"""
|
||||
|
||||
line_reference_basis: Literal[
|
||||
'explicit_line_column',
|
||||
'profile_business_line_no',
|
||||
'classified_logical_line_no',
|
||||
]
|
||||
resolution: Literal[
|
||||
'bound_to_line', # bind_target_line 成功,resolved_logical_line_no 有值
|
||||
'annotation_only', # 显式 annotation_only,Observation 存 metadata
|
||||
'default_all_lines', # 关系缺失 + default_all_lines,每行都生成 Observation
|
||||
'default_header_only', # 关系缺失 + default_header_only,写到 header scope
|
||||
'invalid_line_reference', # 引用了不存在的行号,独立原因码 Q12
|
||||
'conflict_unresolved', # 未来多层映射冲突保留(本期不输出)
|
||||
]
|
||||
resolved_logical_line_no: int | None = None # 1-based 逻辑行号,bound_to_line 时必填
|
||||
annotation_reason: str | None = None # annotation_only 时写入 Observation metadata
|
||||
invalid_reference_raw_value: str | None = None # invalid_line_reference 时返回 raw_text
|
||||
invalid_reference_line_no: int | None = None
|
||||
audit_chain: list[dict[str, Any]] | None = None # 路径判断全链路审计快照
|
||||
|
||||
@property
|
||||
def should_generate_line_observation(self) -> bool:
|
||||
return self.resolution == 'bound_to_line' or self.resolution == 'default_all_lines'
|
||||
|
||||
@property
|
||||
def should_generate_header_observation(self) -> bool:
|
||||
return self.resolution in {'default_header_only', 'annotation_only', 'invalid_line_reference'}
|
||||
|
||||
|
||||
class ReservationRelationProjection:
|
||||
"""
|
||||
把 captured_relation(规则层事实) + profile relation_policy(解释层策略)
|
||||
投影为最终绑定结果。
|
||||
|
||||
【AI 触发时机】:三来源合并前,为每个 Vendor Comments / Header Reservation 候选
|
||||
决定「写行 Observation 还是写头 Observation 还是 invalid_line_reference」时调用。
|
||||
|
||||
核心路径:
|
||||
[STEP 1] 若 relation_policy=annotation_only → 直接走 annotation_only 分支(审计记录原因)。
|
||||
[STEP 2] 若缺失 captured_relation → 走 missing_relation_policy 分支
|
||||
(default_all_lines / default_header_only / fallback_single_line_when_no_reference)。
|
||||
[STEP 3] 若有 captured_relation.line_no,按 line_reference_basis 三层校验:
|
||||
① explicit_line_column:对比 Schema Line 字段值(显式 Line 列),失败→invalid
|
||||
② profile_business_line_no:对比 Profile 业务行号(默认客户 PO 行号)
|
||||
③ classified_logical_line_no:逻辑行号(行序分类后的结果)
|
||||
三层任何一层命中即返回 bound_to_line;全部失败输出 invalid_line_reference 独立原因码。
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'],
|
||||
line_reference_basis: Literal[
|
||||
'explicit_line_column',
|
||||
'profile_business_line_no',
|
||||
'classified_logical_line_no',
|
||||
] = 'profile_business_line_no',
|
||||
missing_relation_policy: Literal[
|
||||
'default_all_lines',
|
||||
'default_header_only',
|
||||
'fallback_single_line_when_no_reference',
|
||||
] = 'default_header_only',
|
||||
):
|
||||
self.relation_policy = relation_policy
|
||||
self.line_reference_basis = line_reference_basis
|
||||
self.missing_relation_policy = missing_relation_policy
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 对外入口
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def project(
|
||||
self,
|
||||
*,
|
||||
captured_relation: CoreCapturedRelation | None,
|
||||
# 下面四个映射是 Line Reference Basis 的判定表(caller 注入,避免本类查 Schema)
|
||||
explicit_line_column_values: dict[int, str] | None = None,
|
||||
profile_business_line_numbers: dict[int, Any] | None = None,
|
||||
classified_logical_line_numbers: dict[int, int] | None = None,
|
||||
# 审计备注(annotation_only 时必须填写原因字符串,例如 'customer_commentary_only')
|
||||
annotation_reason_override: str | None = None,
|
||||
) -> ReservationRelationProjectionResult:
|
||||
"""
|
||||
执行关系投影。
|
||||
|
||||
【禁止 caller 自行推导】:不要在外部用 if captured_relation.line_no in ... 判断,
|
||||
必须走 project() 返回的稳定 resolution 分支。
|
||||
"""
|
||||
audit: list[dict[str, Any]] = [
|
||||
{'step': 'policy_in', 'relation_policy': self.relation_policy,
|
||||
'line_reference_basis': self.line_reference_basis,
|
||||
'missing_relation_policy': self.missing_relation_policy},
|
||||
]
|
||||
|
||||
# [STEP 1] annotation_only 直接返回(本期用于 Customer 备注说明、不参与建单)
|
||||
if self.relation_policy == 'annotation_only':
|
||||
audit.append({'step': 'annotation_only',
|
||||
'reason': annotation_reason_override or 'profile_relation_policy_annotation_only'})
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='annotation_only',
|
||||
annotation_reason=annotation_reason_override or 'profile_relation_policy_annotation_only',
|
||||
audit_chain=audit,
|
||||
)
|
||||
|
||||
# [STEP 2] 缺失 captured_relation → 走 missing_relation_policy
|
||||
if captured_relation is None or captured_relation.line_no is None:
|
||||
audit.append({'step': 'missing_relation',
|
||||
'raw_text': captured_relation.raw_text if captured_relation else None})
|
||||
return self._resolve_missing_policy(audit)
|
||||
|
||||
# [STEP 3] 三层 line_reference_basis 判定(显式 Line 列值 → Profile 业务行号 → 逻辑行号)
|
||||
rel_line_no = int(captured_relation.line_no)
|
||||
audit.append({'step': 'relation_line_no_in', 'line_no': rel_line_no,
|
||||
'raw_text': captured_relation.raw_text})
|
||||
|
||||
basis_order = self._basis_order()
|
||||
for basis_name in basis_order:
|
||||
resolved = self._try_basis(basis_name, rel_line_no, explicit_line_column_values or {},
|
||||
profile_business_line_numbers or {},
|
||||
classified_logical_line_numbers or {})
|
||||
if resolved is not None:
|
||||
audit.append({'step': 'basis_hit', 'basis': basis_name,
|
||||
'logical_line_no': resolved})
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='bound_to_line',
|
||||
resolved_logical_line_no=resolved,
|
||||
audit_chain=audit,
|
||||
)
|
||||
|
||||
# 三层全不命中 → invalid_line_reference(Q12 独立原因码 + 独立审计链)
|
||||
audit.append({'step': 'invalid_line_reference', 'tried_bases': basis_order})
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='invalid_line_reference',
|
||||
invalid_reference_raw_value=captured_relation.raw_text,
|
||||
invalid_reference_line_no=rel_line_no,
|
||||
audit_chain=audit,
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 内部步骤
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _basis_order(self) -> list[str]:
|
||||
"""按 Profile.line_reference_basis 输出优先级顺序。"""
|
||||
if self.line_reference_basis == 'explicit_line_column':
|
||||
return ['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no']
|
||||
if self.line_reference_basis == 'profile_business_line_no':
|
||||
return ['profile_business_line_no', 'classified_logical_line_no', 'explicit_line_column']
|
||||
return ['classified_logical_line_no', 'profile_business_line_no', 'explicit_line_column']
|
||||
|
||||
def _try_basis(
|
||||
self,
|
||||
basis: str,
|
||||
rel_line_no: int,
|
||||
explicit: dict[int, str],
|
||||
profile_biz: dict[int, Any],
|
||||
logical: dict[int, int],
|
||||
) -> int | None:
|
||||
"""尝试一层判定;命中则返回逻辑行号(1-based),否则返回 None。"""
|
||||
if basis == 'explicit_line_column':
|
||||
for logical_idx, raw in explicit.items():
|
||||
if str(raw).strip() == str(rel_line_no):
|
||||
return int(logical_idx)
|
||||
return None
|
||||
if basis == 'profile_business_line_no':
|
||||
for logical_idx, raw in profile_biz.items():
|
||||
if str(raw).strip() == str(rel_line_no):
|
||||
return int(logical_idx)
|
||||
return None
|
||||
if basis == 'classified_logical_line_no':
|
||||
for logical_idx, mapped in logical.items():
|
||||
if int(mapped) == rel_line_no:
|
||||
return int(logical_idx)
|
||||
return None
|
||||
return None
|
||||
|
||||
def _resolve_missing_policy(self, audit: list[dict[str, Any]]) -> ReservationRelationProjectionResult:
|
||||
"""缺失关系时按 missing_relation_policy 落分支。"""
|
||||
policy = self.missing_relation_policy
|
||||
audit.append({'step': 'missing_policy', 'policy': policy})
|
||||
if policy == 'default_all_lines':
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='default_all_lines',
|
||||
audit_chain=audit,
|
||||
)
|
||||
if policy == 'fallback_single_line_when_no_reference':
|
||||
# Q7 开关:默认 OFF;当前 Profile 显式开启时才使用——第一期所有客户 OFF
|
||||
# 若未来启用,应当返回 bound_to_line → 1;本期保持 default_header_only 语义
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='default_header_only',
|
||||
audit_chain=audit + [{'step': 'fallback_disabled_by_q7_default'}],
|
||||
)
|
||||
return ReservationRelationProjectionResult(
|
||||
line_reference_basis=self.line_reference_basis,
|
||||
resolution='default_header_only',
|
||||
audit_chain=audit,
|
||||
)
|
||||
@@ -0,0 +1,244 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/runtime_parse_strategy.py
|
||||
|
||||
用途:为已唯一命中的 Coordinate/OCR 订单模板按当前文档证据选择页范围与明细行重建方式。
|
||||
依赖:仅标准库;由正式抽取与模板质量验证共同调用。
|
||||
逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用,冲突统一转 Review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
|
||||
RowMode = Literal['fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns']
|
||||
StrategyStatus = Literal['selected', 'needs_review']
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuntimeParseStrategy:
|
||||
"""当前文档的临时解析计划,不写回 Profile 或改变后续 Candidate Gate。"""
|
||||
|
||||
status: StrategyStatus
|
||||
page_nos: tuple[int, ...]
|
||||
row_mode: RowMode | None
|
||||
reason_codes: tuple[str, ...]
|
||||
|
||||
|
||||
def resolve_runtime_parse_strategy(
|
||||
*, page_glyphs: dict[str, Any], fixed_rows: list[dict[str, Any]], adaptive_rows: list[dict[str, Any]],
|
||||
dynamic_rows: list[dict[str, Any]] | None = None,
|
||||
) -> RuntimeParseStrategy:
|
||||
"""按页级证据与三种重建结果选择唯一安全策略。
|
||||
|
||||
Args:
|
||||
page_glyphs: 当前 Layout 的页级坐标事实;空页不进入续页候选。
|
||||
fixed_rows: 固定子行重建结果。
|
||||
adaptive_rows: 自适应列重建结果。
|
||||
dynamic_rows: 不受静态表头排除区影响的动态 X 列重建结果。
|
||||
|
||||
Returns:
|
||||
``selected`` 时调用方只消费 ``row_mode`` 对应结果;关键行不同或均不可用时返回
|
||||
``needs_review``,由既有 Route/Candidate Gate 阻断自动建单。
|
||||
"""
|
||||
page_nos = tuple(sorted(
|
||||
int(page_no) for page_no, glyphs in page_glyphs.items()
|
||||
if str(page_no).isdigit() and int(page_no) > 0 and isinstance(glyphs, list) and glyphs
|
||||
))
|
||||
fixed_valid = _valid_rows(fixed_rows)
|
||||
adaptive_valid = _valid_rows(adaptive_rows)
|
||||
dynamic_valid = _valid_rows(dynamic_rows or [])
|
||||
baseline_rows: list[dict[str, Any]] = []
|
||||
baseline = None
|
||||
if fixed_valid and not adaptive_valid:
|
||||
baseline_rows = fixed_valid
|
||||
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
|
||||
elif adaptive_valid and not fixed_valid:
|
||||
baseline_rows = adaptive_valid
|
||||
baseline = RuntimeParseStrategy(
|
||||
'selected', page_nos, 'adaptive_record_columns',
|
||||
('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',),
|
||||
)
|
||||
elif fixed_valid and adaptive_valid:
|
||||
relation = _compare_row_field_completeness(fixed_valid, adaptive_valid)
|
||||
if relation == 'fixed_preferred':
|
||||
baseline_rows = fixed_valid
|
||||
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
|
||||
elif relation == 'adaptive_preferred':
|
||||
baseline_rows = adaptive_valid
|
||||
baseline = RuntimeParseStrategy(
|
||||
'selected', page_nos, 'adaptive_record_columns',
|
||||
('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',),
|
||||
)
|
||||
elif relation == 'same':
|
||||
baseline_rows = fixed_valid
|
||||
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
|
||||
else:
|
||||
return RuntimeParseStrategy(
|
||||
'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',),
|
||||
)
|
||||
if baseline is None and dynamic_valid:
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'dynamic_x_columns',
|
||||
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
|
||||
)
|
||||
if baseline is not None and dynamic_valid:
|
||||
relation = _compare_dynamic_row_coverage(
|
||||
baseline_rows=baseline_rows, dynamic_rows=dynamic_valid,
|
||||
)
|
||||
if relation == 'dynamic_preferred':
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'dynamic_x_columns',
|
||||
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
|
||||
)
|
||||
if relation == 'ambiguous':
|
||||
return RuntimeParseStrategy(
|
||||
'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',),
|
||||
)
|
||||
if baseline is not None:
|
||||
return baseline
|
||||
return RuntimeParseStrategy(
|
||||
'needs_review', page_nos, None, ('PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION',),
|
||||
)
|
||||
|
||||
|
||||
def select_runtime_region_ids(*, table_regions: list[dict[str, Any]], page_no: int) -> tuple[str, ...]:
|
||||
"""为当前页选择候选表区,专属页优先,续页才回退到稳定基础表区。
|
||||
|
||||
历史 ``page_scope`` 仅描述样本标注页,不能要求管理员预判每份文件的续页。
|
||||
当前页已有专属表区时只使用它;没有时复用首页/通用表区,后续仍由行重建结果
|
||||
决定是否确实存在明细,避免把页面范围配置变成自动建单依据。
|
||||
"""
|
||||
if page_no < 1:
|
||||
return ()
|
||||
valid_regions = [
|
||||
region for region in table_regions
|
||||
if isinstance(region, dict) and str(region.get('region_id') or '')
|
||||
]
|
||||
exact = tuple(
|
||||
str(region['region_id']) for region in valid_regions
|
||||
if region.get('page_scope') == 'exact_page' and region.get('page_no') == page_no
|
||||
)
|
||||
if exact:
|
||||
return exact
|
||||
first_page = tuple(
|
||||
str(region['region_id']) for region in valid_regions
|
||||
if region.get('page_scope') == 'first_page'
|
||||
)
|
||||
if page_no == 1 and first_page:
|
||||
return first_page
|
||||
continuation = tuple(
|
||||
str(region['region_id']) for region in valid_regions
|
||||
if page_no > 1 and region.get('page_scope') == 'continuation_pages'
|
||||
)
|
||||
if continuation:
|
||||
return continuation
|
||||
all_pages = tuple(
|
||||
str(region['region_id']) for region in valid_regions
|
||||
if region.get('page_scope') == 'all_pages'
|
||||
)
|
||||
if all_pages:
|
||||
return all_pages
|
||||
if first_page:
|
||||
return first_page
|
||||
return tuple(
|
||||
str(region['region_id']) for region in valid_regions
|
||||
if region.get('page_scope') == 'exact_page' and region.get('page_no') == 1
|
||||
)
|
||||
|
||||
|
||||
def _valid_rows(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""只接受无 issue 的已解析行;不将预览或待复核候选当作可自动建单事实。"""
|
||||
return [
|
||||
row for row in rows
|
||||
if isinstance(row, dict) and row.get('status') == 'parsed' and not row.get('issues')
|
||||
]
|
||||
|
||||
|
||||
def _business_row_identity(rows: list[dict[str, Any]]) -> tuple[tuple[tuple[str, str], ...], ...]:
|
||||
"""比较两种重建的完整业务字段,缺值也保留以避免静默视作相同。"""
|
||||
result: list[tuple[tuple[str, str], ...]] = []
|
||||
for row in rows:
|
||||
values = [
|
||||
(str(field.get('field_code') or ''), str(field.get('value') or ''))
|
||||
for field in row.get('fields') or [] if isinstance(field, dict)
|
||||
]
|
||||
result.append(tuple(sorted(values)))
|
||||
return tuple(result)
|
||||
|
||||
|
||||
def _compare_row_field_completeness(
|
||||
fixed_rows: list[dict[str, Any]], adaptive_rows: list[dict[str, Any]],
|
||||
) -> Literal['fixed_preferred', 'adaptive_preferred', 'same', 'ambiguous']:
|
||||
"""比较两种重建的字段集合,允许一方仅缺失字段而不丢弃整条明细。
|
||||
|
||||
只有对应行数量相同、重叠字段值一致,且所有行都呈现同一方向的字段超集关系时,
|
||||
才自动选择更完整的结果;任一字段值冲突或方向不一致都继续进入 Review。
|
||||
"""
|
||||
if len(fixed_rows) != len(adaptive_rows):
|
||||
return 'ambiguous'
|
||||
directions: set[str] = set()
|
||||
for fixed, adaptive in zip(fixed_rows, adaptive_rows):
|
||||
fixed_fields = _row_fields(fixed)
|
||||
adaptive_fields = _row_fields(adaptive)
|
||||
shared = fixed_fields.keys() & adaptive_fields.keys()
|
||||
conflicts = [code for code in shared if fixed_fields[code] != adaptive_fields[code]]
|
||||
if conflicts:
|
||||
# 坐标字段框是模板的权威边界。若 adaptive 只读到 fixed 值的
|
||||
# 前缀(典型的跨视觉行料号),完整的 fixed 值应胜出;真正的
|
||||
# 不同业务值仍保持 Review,避免把冲突静默吞掉。
|
||||
if all(
|
||||
fixed_fields[code].startswith(adaptive_fields[code])
|
||||
and len(fixed_fields[code]) > len(adaptive_fields[code])
|
||||
for code in conflicts
|
||||
):
|
||||
directions.add('fixed')
|
||||
else:
|
||||
return 'ambiguous'
|
||||
if fixed_fields.keys() > adaptive_fields.keys():
|
||||
directions.add('fixed')
|
||||
elif adaptive_fields.keys() > fixed_fields.keys():
|
||||
directions.add('adaptive')
|
||||
if not directions:
|
||||
return 'same'
|
||||
if len(directions) == 1:
|
||||
return 'fixed_preferred' if 'fixed' in directions else 'adaptive_preferred'
|
||||
return 'ambiguous'
|
||||
|
||||
|
||||
def _compare_dynamic_row_coverage(
|
||||
*, baseline_rows: list[dict[str, Any]], dynamic_rows: list[dict[str, Any]],
|
||||
) -> Literal['baseline_preferred', 'dynamic_preferred', 'ambiguous']:
|
||||
"""仅当动态结果无冲突地覆盖基线每条记录并额外恢复记录时才切换策略。"""
|
||||
if len(dynamic_rows) < len(baseline_rows):
|
||||
return 'baseline_preferred'
|
||||
remaining = [_row_fields(row) for row in dynamic_rows]
|
||||
for baseline in baseline_rows:
|
||||
baseline_fields = _row_fields(baseline)
|
||||
matches = []
|
||||
for index, dynamic_fields in enumerate(remaining):
|
||||
if not baseline_fields.keys() <= dynamic_fields.keys():
|
||||
continue
|
||||
if all(
|
||||
dynamic_fields[code] == value
|
||||
or (
|
||||
dynamic_fields[code].startswith(value)
|
||||
and len(dynamic_fields[code]) > len(value)
|
||||
)
|
||||
for code, value in baseline_fields.items()
|
||||
):
|
||||
matches.append(index)
|
||||
if len(matches) != 1:
|
||||
return 'ambiguous' if len(dynamic_rows) >= len(baseline_rows) else 'baseline_preferred'
|
||||
remaining.pop(matches[0])
|
||||
return 'dynamic_preferred' if remaining else 'baseline_preferred'
|
||||
|
||||
|
||||
def _row_fields(row: dict[str, Any]) -> dict[str, str]:
|
||||
"""将策略行字段规整为可比较映射;不引入业务字段白名单。"""
|
||||
return {
|
||||
str(field.get('field_code') or ''): str(field.get('value') or '')
|
||||
for field in row.get('fields') or []
|
||||
if isinstance(field, dict) and str(field.get('field_code') or '')
|
||||
}
|
||||
@@ -1,342 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/source_merge_service.py
|
||||
|
||||
用途:Q18 抽取层裁决——同一 conflict_group_key(scope/field_code/line_no)下的三来源候选
|
||||
合并为最多一条「有效业务 Observation」,禁止同一 scope+line 下多个并列有效
|
||||
Observation(防止 compute_effective_reservation_id / 库存匹配 / 履约门禁
|
||||
/ Excel/RPA 误取其中一个,或冲突被后续静默覆盖)。
|
||||
依赖:profile_field_source_mapping_service.FieldSourceCandidate。
|
||||
逻辑:严格三步骤(同值合并 → 空值互补 → 值冲突),满足:
|
||||
① merge 后只出一个有效 accepted(或 needs_review=无 accepted);
|
||||
② 始终保留 source_observations[] 事实快照放入 metadata;
|
||||
③ annotation_only / invalid_line_reference 的候选永不成为 accepted,
|
||||
只保留在 conflict_payload 里作为 Review 证据。
|
||||
输出:MergedObservationCandidate(直接落库前的 Observation 形状封装),
|
||||
由 runtime 层实际 SQLAlchemy insert。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Literal
|
||||
|
||||
from app.services.shipping_notice.document_layout.profile_field_source_mapping_service import (
|
||||
FieldSourceCandidate,
|
||||
)
|
||||
|
||||
|
||||
SourceResolution = Literal[
|
||||
'same_value_merged', # 多个来源值一致
|
||||
'fill_missing', # 一个来源有值,另一来源为空 → 自动填补
|
||||
'needs_review', # 同 scope+line 多来源值不一致
|
||||
'no_value', # 所有来源均为空 → 本冲突组不生成有效 Observation
|
||||
'single_source_direct', # 只有一个来源有值,直接落 Observation
|
||||
'annotation_only_dropped', # 候选全是 annotation_only / invalid_line_reference
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class SourceObservationSnapshot:
|
||||
"""source_observations[] 事实快照——Observation.metadata 直接序列化。"""
|
||||
|
||||
source: Literal['header_region', 'table_column', 'vendor_comments']
|
||||
value: str
|
||||
normalized_value: str
|
||||
evidence_ref: str | None
|
||||
evidence_quote: str | None
|
||||
line_no_in_source: int | None
|
||||
format_valid: bool | None
|
||||
format_reason_code: str | None
|
||||
extra: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MergedObservationCandidate:
|
||||
"""
|
||||
合并后候选——最多一份(per conflict_group_key),由 runtime 层写数据库。
|
||||
|
||||
【后端决定 UI】:accepted_value 为 None 时,说明该字段+行=必须 Review;
|
||||
frontend 不能以『第一个 source value』为事实,必须展示 source_observations[]。
|
||||
"""
|
||||
|
||||
target_scope: Literal['header', 'line']
|
||||
target_field_code: str
|
||||
target_field_id: str
|
||||
effective_line_no: int | None
|
||||
accepted_value: str | None # needs_review/no_value 时为 None
|
||||
decision_status: Literal['accepted', 'needs_review', 'blocked', 'missing']
|
||||
resolution: SourceResolution
|
||||
source_observations: list[SourceObservationSnapshot] = field(default_factory=list)
|
||||
conflicts: list[dict[str, Any]] = field(default_factory=list)
|
||||
# 用于直接映射到 Observation 数据库表列
|
||||
evidence_quote: str | None = None
|
||||
evidence_ref: str | None = None
|
||||
evidence_metadata: dict[str, Any] = field(default_factory=dict)
|
||||
# 用于 Observation.source_type / extractor(统一三来源来源标记)
|
||||
source_type: str = 'profile_field_source_mapping'
|
||||
extractor: str = 'merged_source_service.v1'
|
||||
|
||||
@property
|
||||
def should_persist_observation(self) -> bool:
|
||||
"""
|
||||
有效 Observation 生成门禁:
|
||||
必须有 accepted_value;annotation_only/invalid 全 drop 时也不输出。
|
||||
"""
|
||||
return self.accepted_value is not None and self.accepted_value != ''
|
||||
|
||||
|
||||
class SourceMergeService:
|
||||
"""
|
||||
Q18 抽取层裁决服务(先对账再重试——三来源先对账)。
|
||||
|
||||
【AI 触发时机】:ProfileFieldSourceMappingService.collect_candidates() 返回候选后,
|
||||
下一个函数调用必须是 merge_and_decide()。禁止上游在合并前直接挑一个 source 作为 Observation。
|
||||
|
||||
执行顺序(同 conflict_group_key 内):
|
||||
[STEP 1] 过滤 annotation_only / invalid_line_reference 候选(永不 accepted)。
|
||||
[STEP 2] 归一化所有来源 value(去空格、大小写、格式化残差)。
|
||||
[STEP 3] 同值合并 same_value_merged → accepted
|
||||
[STEP 4] 空值互补 fill_missing(需 mapping.fill_missing_from_other_sources=True)
|
||||
[STEP 5] 以上都不通过 → conflict_needs_review,accepted_value=None
|
||||
"""
|
||||
|
||||
def __init__(self, candidates: list[FieldSourceCandidate]):
|
||||
self.candidates = list(candidates)
|
||||
# 分组:(scope, field_code, line_no) → list[candidates]
|
||||
self._groups: dict[tuple[Any, ...], list[FieldSourceCandidate]] = defaultdict(list)
|
||||
for cand in self.candidates:
|
||||
self._groups[cand.conflict_group_key].append(cand)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 对外主入口
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def merge_and_decide(self) -> list[MergedObservationCandidate]:
|
||||
"""为每个 conflict_group_key 输出 0 或 1 个 MergedObservationCandidate。"""
|
||||
merged: list[MergedObservationCandidate] = []
|
||||
for _key, group in self._groups.items():
|
||||
merged.append(self._merge_one_group(group))
|
||||
return merged
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 单组合并核心
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _merge_one_group(self, group: list[FieldSourceCandidate]) -> MergedObservationCandidate:
|
||||
first = group[0]
|
||||
result = MergedObservationCandidate(
|
||||
target_scope=first.target_scope,
|
||||
target_field_code=first.target_field_code,
|
||||
target_field_id=first.target_field_id,
|
||||
effective_line_no=first.effective_line_no,
|
||||
accepted_value=None,
|
||||
decision_status='missing',
|
||||
resolution='no_value',
|
||||
)
|
||||
|
||||
# [STEP 1] 分离有效候选(排除 annotation_only / invalid)
|
||||
qualified: list[FieldSourceCandidate] = []
|
||||
for cand in group:
|
||||
snap = self._to_snapshot(cand)
|
||||
result.source_observations.append(snap)
|
||||
if cand.resolution_hint == 'provisional':
|
||||
qualified.append(cand)
|
||||
else:
|
||||
# annotation_only / invalid_line_reference 作为 review 证据保留
|
||||
result.conflicts.append({
|
||||
'resolution_hint': cand.resolution_hint,
|
||||
'source': cand.source,
|
||||
'value': cand.normalized_value or cand.value,
|
||||
'reason': (
|
||||
cand.format_reason_code
|
||||
or cand.relation_projection.resolution
|
||||
if cand.relation_projection else 'annotation_only'
|
||||
),
|
||||
})
|
||||
|
||||
# 无 qualified → 直接 annotation_only_dropped / no_value
|
||||
if not qualified:
|
||||
if group:
|
||||
result.resolution = 'annotation_only_dropped'
|
||||
result.decision_status = 'blocked'
|
||||
else:
|
||||
result.resolution = 'no_value'
|
||||
result.decision_status = 'missing'
|
||||
result.evidence_metadata = self._finalize_metadata(result, resolution_meta={})
|
||||
return result
|
||||
|
||||
# 只有一个 qualified 且非空 → single_source_direct
|
||||
non_empty = [c for c in qualified if (c.normalized_value or c.value) != '']
|
||||
if len(qualified) == 1 and non_empty:
|
||||
return self._finalize_single(result, qualified[0])
|
||||
if not non_empty:
|
||||
result.resolution = 'no_value'
|
||||
result.decision_status = 'missing'
|
||||
result.evidence_metadata = self._finalize_metadata(result, {})
|
||||
return result
|
||||
if len(non_empty) == 1:
|
||||
return self._finalize_fill_missing(result, group, non_empty[0], qualified)
|
||||
|
||||
# [STEP 3] 同值合并 same_value_merged
|
||||
values = {(c.normalized_value or c.value) for c in non_empty}
|
||||
if len(values) == 1:
|
||||
return self._finalize_same_value(result, group, next(iter(values)))
|
||||
|
||||
# [STEP 5] 冲突 → needs_review(多来源值不一致)
|
||||
result.resolution = 'needs_review'
|
||||
result.decision_status = 'needs_review'
|
||||
result.accepted_value = None
|
||||
for c in non_empty:
|
||||
result.conflicts.append({
|
||||
'source': c.source,
|
||||
'value': (c.normalized_value or c.value),
|
||||
'evidence_ref': c.evidence_ref,
|
||||
'format_valid': c.format_valid,
|
||||
})
|
||||
result.evidence_metadata = self._finalize_metadata(result, {})
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 结局封装(保证 evidence_metadata 统一包含 source_observations / resolution)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _finalize_single(
|
||||
self, result: MergedObservationCandidate, cand: FieldSourceCandidate,
|
||||
) -> MergedObservationCandidate:
|
||||
result.accepted_value = cand.normalized_value or cand.value
|
||||
result.resolution = 'single_source_direct'
|
||||
result.decision_status = 'accepted'
|
||||
result.evidence_quote = cand.evidence_quote
|
||||
result.evidence_ref = cand.evidence_ref
|
||||
result.evidence_metadata = self._finalize_metadata(
|
||||
result,
|
||||
resolution_meta={
|
||||
'accepted_source': cand.source,
|
||||
'format_valid': cand.format_valid,
|
||||
'format_reason_code': cand.format_reason_code,
|
||||
},
|
||||
primary_candidate=cand,
|
||||
)
|
||||
return result
|
||||
|
||||
def _finalize_fill_missing(
|
||||
self, result: MergedObservationCandidate,
|
||||
group: list[FieldSourceCandidate],
|
||||
winner: FieldSourceCandidate,
|
||||
all_qualified: list[FieldSourceCandidate],
|
||||
) -> MergedObservationCandidate:
|
||||
result.accepted_value = winner.normalized_value or winner.value
|
||||
result.resolution = 'fill_missing'
|
||||
result.decision_status = 'accepted'
|
||||
result.evidence_quote = winner.evidence_quote
|
||||
result.evidence_ref = winner.evidence_ref
|
||||
missing = [
|
||||
{'source': c.source, 'reason': 'empty_source'}
|
||||
for c in all_qualified
|
||||
if (c.normalized_value or c.value) == ''
|
||||
]
|
||||
result.evidence_metadata = self._finalize_metadata(
|
||||
result,
|
||||
resolution_meta={
|
||||
'accepted_source': winner.source,
|
||||
'missing_sources': missing,
|
||||
'format_valid': winner.format_valid,
|
||||
'format_reason_code': winner.format_reason_code,
|
||||
},
|
||||
primary_candidate=winner,
|
||||
)
|
||||
return result
|
||||
|
||||
def _finalize_same_value(
|
||||
self, result: MergedObservationCandidate,
|
||||
group: list[FieldSourceCandidate], shared_value: str,
|
||||
) -> MergedObservationCandidate:
|
||||
# 多来源同值:evidence 选 format_valid=True 中来源排序靠前的
|
||||
# (vendor_comments 优先,因为有人工圈选证据点位更清晰)
|
||||
source_priority = ['vendor_comments', 'table_column', 'header_region']
|
||||
ordered = sorted(
|
||||
group,
|
||||
key=lambda c: (
|
||||
0 if (c.format_valid is not False and (c.normalized_value or c.value) == shared_value) else 1,
|
||||
source_priority.index(c.source) if c.source in source_priority else 99,
|
||||
),
|
||||
)
|
||||
primary = ordered[0]
|
||||
result.accepted_value = shared_value
|
||||
result.resolution = 'same_value_merged'
|
||||
result.decision_status = 'accepted'
|
||||
result.evidence_quote = primary.evidence_quote
|
||||
result.evidence_ref = primary.evidence_ref
|
||||
merged_sources = sorted({c.source for c in ordered if (c.normalized_value or c.value) == shared_value})
|
||||
result.evidence_metadata = self._finalize_metadata(
|
||||
result,
|
||||
resolution_meta={
|
||||
'merged_from_sources': list(merged_sources),
|
||||
'format_valid': primary.format_valid,
|
||||
'format_reason_code': primary.format_reason_code,
|
||||
},
|
||||
primary_candidate=primary,
|
||||
)
|
||||
return result
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 帮助函数
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _to_snapshot(cand: FieldSourceCandidate) -> SourceObservationSnapshot:
|
||||
return SourceObservationSnapshot(
|
||||
source=cand.source,
|
||||
value=cand.value,
|
||||
normalized_value=cand.normalized_value,
|
||||
evidence_ref=cand.evidence_ref,
|
||||
evidence_quote=cand.evidence_quote,
|
||||
line_no_in_source=cand.effective_line_no,
|
||||
format_valid=cand.format_valid,
|
||||
format_reason_code=cand.format_reason_code,
|
||||
extra=dict(cand.evidence_metadata or {}),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _finalize_metadata(
|
||||
result: MergedObservationCandidate,
|
||||
resolution_meta: dict[str, Any],
|
||||
primary_candidate: FieldSourceCandidate | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
组装 Observation.evidence_metadata_json 最终结构(Q18 冻结形状):
|
||||
{
|
||||
"source_observations": [...], // 事实快照(永不丢)
|
||||
"resolution": "same_value_merged",
|
||||
"accepted_value": "...",
|
||||
"conflicts": [ ... ], // 冲突或 annotation_only 项
|
||||
"resolution_meta": { ... }, // 来源细节
|
||||
"primary": { // 选主证据说明
|
||||
"source": "vendor_comments", "evidence_ref": "...", "line_no": 2
|
||||
}
|
||||
}
|
||||
"""
|
||||
payload: dict[str, Any] = {
|
||||
'source_observations': [
|
||||
{
|
||||
'source': s.source, 'value': s.value,
|
||||
'normalized_value': s.normalized_value,
|
||||
'evidence_ref': s.evidence_ref, 'evidence_quote': s.evidence_quote,
|
||||
'line_no_in_source': s.line_no_in_source,
|
||||
'format_valid': s.format_valid, 'format_reason_code': s.format_reason_code,
|
||||
'extra': s.extra or {},
|
||||
} for s in result.source_observations
|
||||
],
|
||||
'resolution': result.resolution,
|
||||
'accepted_value': result.accepted_value,
|
||||
'conflicts': list(result.conflicts or []),
|
||||
'resolution_meta': resolution_meta or {},
|
||||
}
|
||||
if primary_candidate is not None:
|
||||
payload['primary'] = {
|
||||
'source': primary_candidate.source,
|
||||
'evidence_ref': primary_candidate.evidence_ref,
|
||||
'line_no': primary_candidate.effective_line_no,
|
||||
}
|
||||
return payload
|
||||
-195
@@ -1,195 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/vc_source_candidate_conflicts.py
|
||||
|
||||
用途:从 ProfileFieldSourceMappingService + SourceMergeService 的运行结果
|
||||
产出 Candidate 级冲突项,接入 candidate.conflicts_json。
|
||||
依赖:
|
||||
- vc_source_gate_contract(冲突原因码、冲突项构造器)。
|
||||
- profile_field_source_mapping_service(三来源候选收集)。
|
||||
- source_merge_service(合并裁决 + needs_review 标记)。
|
||||
- candidate_service / ShippingOrderCandidate.structured_result_json(落库载体)。
|
||||
逻辑:
|
||||
[STEP 1] 从 Candidate.structured_result_json 读三来源收集的原始快照;
|
||||
缺失(旧数据或未启用 VC Profile)时安全返回空列表,不阻断。
|
||||
[STEP 2] 扫描 merged_candidates,needs_review 且 conflict_group_key 未人工裁决 →
|
||||
构造 make_vc_candidate_conflict_item(severity=review_required)。
|
||||
[STEP 3] 扫描 format_valid=False 且 format_policy.inherit_global=False 的项 →
|
||||
独立原因码 vc_source_format_invalid,severity=blocking。
|
||||
[STEP 4] named_region_id 指向不存在区域 → vc_source_region_unbound。
|
||||
幂等:同一 conflict_group_key 仅保留一项,合并 detail 不重复追加。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.vc_source_gate_contract import (
|
||||
CQ_REASON_VC_FORMAT_INVALID,
|
||||
CQ_REASON_VC_REGION_UNBOUND,
|
||||
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
|
||||
CQ_VC_BLOCKING_REASONS,
|
||||
CQ_VC_REVIEW_REASONS,
|
||||
VC_SOURCE_KIND_LABELS,
|
||||
make_vc_candidate_conflict_item,
|
||||
)
|
||||
|
||||
# CQ_VC_BLOCKING_REASONS / CQ_VC_REVIEW_REASONS 定义在 vc_source_gate_contract.py(契约层),
|
||||
# 这里保留薄 re-export,供 candidate_qualification_service 等调用方按旧路径 import,
|
||||
# 避免修改大量调用点时引入遗漏。
|
||||
|
||||
|
||||
_VC_CANDIDATE_KEY = 'vendor_comments_merged'
|
||||
_VC_DETAIL_MAX = 8 # 单项 detail 保留最多 8 条来源快照,防止 JSON 膨胀。
|
||||
|
||||
|
||||
def _vc_merged_payload(candidate: Any) -> dict[str, Any] | None:
|
||||
"""
|
||||
从 Candidate 提取 Vendor Comments merged payload。
|
||||
|
||||
支持三条路径,按顺序:
|
||||
1) structured_result_json.extraction.vendor_comments_merged(新抽取路径)
|
||||
2) result_json.extraction.vendor_comments_merged(兼容 Worker 旧写入点)
|
||||
3) candidate_json.extraction.vendor_comments_merged(影子评估的替身 dict)
|
||||
|
||||
任一合法 dict 即返回,否则 None(缺路径视为未启用,安全放行)。
|
||||
"""
|
||||
for attr in ('structured_result_json', 'result_json', 'candidate_json'):
|
||||
try:
|
||||
raw = getattr(candidate, attr, None)
|
||||
except Exception:
|
||||
raw = None
|
||||
if isinstance(raw, dict):
|
||||
ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None
|
||||
if ext and isinstance(ext.get(_VC_CANDIDATE_KEY), dict):
|
||||
return ext[_VC_CANDIDATE_KEY]
|
||||
return None
|
||||
|
||||
|
||||
def _conflict_group_key(scope: str, field_code: str, line_no: str | None) -> str:
|
||||
"""稳定冲突键:与 source_merge_service 的 (scope, field_code, line_no) 一致。"""
|
||||
safe_scope = 'header' if scope == 'header' else 'line'
|
||||
safe_line = str(line_no or '').strip() or '_'
|
||||
return f'{safe_scope}:{str(field_code or "").strip()}:{safe_line}'
|
||||
|
||||
|
||||
def _summarize_source_observations(cand: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
脱敏压缩 source_observations:仅保留 source / value 摘要 / evidence_ref,禁止存完整正文。
|
||||
"""
|
||||
obs = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else []
|
||||
summary: list[dict[str, Any]] = []
|
||||
for raw in obs[:_VC_DETAIL_MAX]:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
summary.append({
|
||||
'source': raw.get('source'),
|
||||
'source_label': VC_SOURCE_KIND_LABELS.get(str(raw.get('source') or ''), str(raw.get('source') or '')),
|
||||
'value_preview': (str(raw.get('value') or '')[:64] + ('…' if len(str(raw.get('value') or '')) > 64 else '')) if raw.get('value') is not None else None,
|
||||
'evidence_ref': raw.get('evidence_ref'),
|
||||
})
|
||||
return summary
|
||||
|
||||
|
||||
def collect_vc_candidate_conflicts(candidate: Any) -> list[dict[str, Any]]:
|
||||
"""
|
||||
扫描 Vendor Comments 三来源合并结果,生成 Candidate 冲突项。
|
||||
|
||||
【AI 触发时机】:当 Candidate Qualification 评估、STP 自动建单前
|
||||
或复核工作台加载冲突列表时,追加本函数返回值到 Candidate.conflicts_json。
|
||||
|
||||
Args:
|
||||
candidate: ShippingOrderCandidate ORM 对象或兼容 dict(替身)。
|
||||
|
||||
Returns:
|
||||
符合 vc_source_gate_contract.make_vc_candidate_conflict_item 契约的列表;
|
||||
无冲突或未启用 VC 时返回空列表(永不返回 None)。
|
||||
"""
|
||||
payload = _vc_merged_payload(candidate)
|
||||
if payload is None:
|
||||
return []
|
||||
|
||||
merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else []
|
||||
named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {}
|
||||
enabled = payload.get('field_source_mappings') if isinstance(payload.get('field_source_mappings'), dict) else {}
|
||||
|
||||
# [STEP 0] 先校验 named_region 绑定:所有启用 vendor_comments 的 mapping 其 region_id 必须存在。
|
||||
seen_region_errors: set[str] = set()
|
||||
items: list[dict[str, Any]] = []
|
||||
|
||||
for field_code, mapping in enabled.items():
|
||||
if not isinstance(mapping, dict):
|
||||
continue
|
||||
if not bool(mapping.get('vendor_comments_enabled')):
|
||||
continue
|
||||
rid = str(mapping.get('vendor_comments_named_region_id') or '').strip()
|
||||
if rid and rid not in named_regions:
|
||||
key = f'region_missing:{rid}:{field_code}'
|
||||
if key in seen_region_errors:
|
||||
continue
|
||||
seen_region_errors.add(key)
|
||||
scope_val = str(mapping.get('vendor_comments_target_scope') or mapping.get('target_scope') or 'line').strip()
|
||||
scope = 'header' if scope_val == 'header' else 'line'
|
||||
ckey = _conflict_group_key(scope, field_code, None)
|
||||
items.append(make_vc_candidate_conflict_item(
|
||||
reason=CQ_REASON_VC_REGION_UNBOUND,
|
||||
scope=scope, # type: ignore[arg-type]
|
||||
field_code=field_code,
|
||||
conflict_group_key=ckey,
|
||||
detail={'missing_region_id': rid},
|
||||
))
|
||||
|
||||
# [STEP 1] 扫描 merged_candidates:needs_review / format_invalid。
|
||||
seen_groups: set[str] = set()
|
||||
for cand in merged:
|
||||
if not isinstance(cand, dict):
|
||||
continue
|
||||
field_code = str(cand.get('target_field_code') or cand.get('field_code') or '').strip()
|
||||
if not field_code:
|
||||
continue
|
||||
scope = str(cand.get('target_scope') or cand.get('scope') or 'line').strip()
|
||||
scope_ok = 'header' if scope == 'header' else 'line'
|
||||
line_no_raw = cand.get('effective_line_no') or cand.get('line_no')
|
||||
line_no_safe = None if line_no_raw is None else str(line_no_raw)
|
||||
ckey = _conflict_group_key(scope_ok, field_code, line_no_safe)
|
||||
|
||||
resolution = str(cand.get('resolution') or '').strip()
|
||||
decision = str(cand.get('decision_status') or '').strip()
|
||||
format_valid = cand.get('format_valid')
|
||||
# 显式 False 视为非法(None 表示未启用格式策略,安全放行)。
|
||||
format_invalid = (format_valid is False)
|
||||
conflict_pending = resolution == 'needs_review' and decision != 'dropped'
|
||||
|
||||
if ckey in seen_groups:
|
||||
continue
|
||||
detail = {
|
||||
'resolution': resolution,
|
||||
'decision_status': decision,
|
||||
'format_valid': format_valid,
|
||||
'sources': _summarize_source_observations(cand),
|
||||
}
|
||||
if conflict_pending:
|
||||
seen_groups.add(ckey)
|
||||
line_key = str(cand.get('line_key') or '').strip() or None
|
||||
items.append(make_vc_candidate_conflict_item(
|
||||
reason=CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
|
||||
scope=scope_ok, # type: ignore[arg-type]
|
||||
field_code=field_code,
|
||||
line_key=line_key,
|
||||
line_no=line_no_safe,
|
||||
conflict_group_key=ckey,
|
||||
detail=detail,
|
||||
))
|
||||
elif format_invalid:
|
||||
seen_groups.add(ckey)
|
||||
line_key = str(cand.get('line_key') or '').strip() or None
|
||||
items.append(make_vc_candidate_conflict_item(
|
||||
reason=CQ_REASON_VC_FORMAT_INVALID,
|
||||
scope=scope_ok, # type: ignore[arg-type]
|
||||
field_code=field_code,
|
||||
line_key=line_key,
|
||||
line_no=line_no_safe,
|
||||
conflict_group_key=ckey,
|
||||
detail=detail,
|
||||
))
|
||||
|
||||
return items
|
||||
-230
@@ -1,230 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/vc_source_evidence_integration.py
|
||||
|
||||
用途:将 Vendor Comments 三来源 source_observations 注入 ReviewEvidenceView,
|
||||
供 Chatflow LLM Review(Phase 4)与复核工作台(Phase 5)共享同一事实源。
|
||||
依赖:
|
||||
- vc_source_gate_contract(VENDOR_COMMENTS_OBSERVATION_SOURCE、build_vc_evidence_ref、is_valid_vc_evidence_ref)。
|
||||
- order_review_llm_contract ObservationSource 兼容扩展(新增 source 不在原 frozenset 时 fail-open,不抛错)。
|
||||
- Candidate.structured_result_json.extraction.vendor_comments_merged(与 vc_source_candidate_conflicts.py 同一路径)。
|
||||
逻辑:
|
||||
[STEP 1] 提取 VC merged payload(与 Candidate Conflicts 共享 _vc_merged_payload 逻辑,不双份)。
|
||||
[STEP 2] 对每个 merged_candidate,展开其 source_observations[]:
|
||||
- 构造 evidence_ref(优先 vc: 区域引用,缺失时退化 build_evidence_ref layout:)。
|
||||
- source 固定 VENDOR_COMMENTS_OBSERVATION_SOURCE;子 source_kind 写入 metadata.source_kind。
|
||||
- 保留 quote(原文切片)、confidence、value_bbox。
|
||||
[STEP 3] 仅追加,不覆盖/替换原有 Unit/Draft/Frozen 三源证据。
|
||||
幂等:同一 (evidence_ref, source_kind, value) 仅插入一条,避免 LLM 重复上下文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.vc_source_gate_contract import (
|
||||
VENDOR_COMMENTS_OBSERVATION_SOURCE,
|
||||
build_vc_evidence_ref,
|
||||
is_valid_vc_evidence_ref,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_llm_contract import (
|
||||
build_evidence_ref,
|
||||
is_valid_evidence_ref,
|
||||
)
|
||||
|
||||
|
||||
def _vc_merged_payload(case_or_candidate: Any) -> dict[str, Any] | None:
|
||||
"""
|
||||
从 ReviewCase(通过 candidate.structured)或直接 Candidate 提取 VC 载荷。
|
||||
|
||||
与 vc_source_candidate_conflicts._vc_merged_payload 逻辑一致但独立实现,
|
||||
避免引入相互 import(两模块均零 circular 原则)。
|
||||
"""
|
||||
# Case 路径:先取 candidate。
|
||||
candidate = getattr(case_or_candidate, 'candidate', None)
|
||||
attrs_chain: list[Any] = []
|
||||
if candidate is not None:
|
||||
attrs_chain.append(candidate)
|
||||
attrs_chain.append(case_or_candidate)
|
||||
for item in attrs_chain:
|
||||
for attr in ('structured_result_json', 'result_json', 'candidate_json'):
|
||||
try:
|
||||
raw = getattr(item, attr, None)
|
||||
except Exception:
|
||||
raw = None
|
||||
if isinstance(raw, dict):
|
||||
ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None
|
||||
if ext and isinstance(ext.get('vendor_comments_merged'), dict):
|
||||
return ext['vendor_comments_merged']
|
||||
return None
|
||||
|
||||
|
||||
def _safe_str(value: Any) -> str | None:
|
||||
if value is None:
|
||||
return None
|
||||
text = str(value).strip()
|
||||
return text or None
|
||||
|
||||
|
||||
def _normalize_source_obs(
|
||||
raw: dict[str, Any],
|
||||
*,
|
||||
case_document_id: int,
|
||||
field_code: str | None,
|
||||
line_key: str | None,
|
||||
named_regions: dict[str, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
将一条 source_observation 归一化为 ReviewEvidenceView.field_evidences 项形状。
|
||||
|
||||
核心:evidence_ref 优先取 vc:region;若 source_kind=vendor_comments 且命中命名区域
|
||||
但缺 page_no,回退从 named_regions[region_id] 取代表页号。
|
||||
"""
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
source_kind = _safe_str(raw.get('source')) or 'header_region'
|
||||
value = raw.get('value')
|
||||
quote = _safe_str(raw.get('quote') or raw.get('raw_text'))
|
||||
confidence_raw = raw.get('confidence')
|
||||
try:
|
||||
confidence = float(confidence_raw) if confidence_raw is not None else None
|
||||
except (TypeError, ValueError):
|
||||
confidence = None
|
||||
|
||||
doc_raw = raw.get('document_id') or case_document_id
|
||||
try:
|
||||
doc_id = int(doc_raw)
|
||||
except (TypeError, ValueError):
|
||||
doc_id = int(case_document_id or 0)
|
||||
|
||||
page_raw = raw.get('page_no')
|
||||
try:
|
||||
page_no = int(page_raw) if page_raw is not None else None
|
||||
except (TypeError, ValueError):
|
||||
page_no = None
|
||||
|
||||
# Vendor Comments:若缺 page_no,按 named_regions[region_id].page_scope 推导代表页。
|
||||
rid = _safe_str(raw.get('region_id') or raw.get('named_region_id'))
|
||||
if source_kind == 'vendor_comments' and page_no is None and rid and isinstance(named_regions.get(rid), dict):
|
||||
region_def = named_regions[rid]
|
||||
page_scope = _safe_str(region_def.get('page_scope')) or 'first_page'
|
||||
exact = region_def.get('exact_page_no') or region_def.get('page_no')
|
||||
if page_scope == 'last_page':
|
||||
# last_page 未知实际页码时安全置 1,待后续有实际渲染页号再覆盖。
|
||||
page_no = page_no or 1
|
||||
elif page_scope == 'exact_page' and exact is not None:
|
||||
try:
|
||||
page_no = int(exact)
|
||||
except (TypeError, ValueError):
|
||||
page_no = page_no or 1
|
||||
else:
|
||||
page_no = page_no or 1
|
||||
|
||||
evidence_ref: str | None = None
|
||||
pre_ref = raw.get('evidence_ref')
|
||||
if isinstance(pre_ref, str) and (is_valid_vc_evidence_ref(pre_ref) or is_valid_evidence_ref(pre_ref)):
|
||||
evidence_ref = pre_ref.strip()
|
||||
if not evidence_ref and source_kind == 'vendor_comments' and doc_id > 0 and page_no and rid:
|
||||
evidence_ref = build_vc_evidence_ref(document_id=doc_id, page_no=page_no, region_id=rid)
|
||||
if not evidence_ref and doc_id > 0 and page_no:
|
||||
table_id = raw.get('table_id') if isinstance(raw.get('table_id'), str) else None
|
||||
row_index = None
|
||||
try:
|
||||
ri = raw.get('row_index')
|
||||
row_index = int(ri) if ri is not None else None
|
||||
except (TypeError, ValueError):
|
||||
row_index = None
|
||||
evidence_ref = build_evidence_ref(
|
||||
document_id=doc_id,
|
||||
page_no=page_no,
|
||||
table_id=table_id,
|
||||
row_index=row_index,
|
||||
field_code=field_code,
|
||||
)
|
||||
|
||||
bbox = raw.get('value_bbox') if isinstance(raw.get('value_bbox'), dict) else None
|
||||
bbox_valid = (
|
||||
isinstance(bbox, dict)
|
||||
and all(k in bbox for k in ('x0', 'y0', 'x1', 'y1'))
|
||||
and 0.0 <= float(bbox['x0']) < float(bbox['x1']) <= 1.01
|
||||
and 0.0 <= float(bbox['y0']) < float(bbox['y1']) <= 1.01
|
||||
) if bbox else False
|
||||
|
||||
doc_match = bool(doc_id) and int(case_document_id or 0) > 0 and int(doc_id) == int(case_document_id)
|
||||
value_bbox_dict = dict(bbox) if bbox_valid else None
|
||||
|
||||
return {
|
||||
'value': value,
|
||||
'quote': quote,
|
||||
'source': VENDOR_COMMENTS_OBSERVATION_SOURCE,
|
||||
'source_kind': source_kind,
|
||||
'confidence': confidence,
|
||||
'evidence_ref': evidence_ref,
|
||||
'provenance_ref': None, # VC 来源直接走 evidence_ref,不伪装 draft provenance。
|
||||
'document_id': doc_id,
|
||||
'page_no': page_no,
|
||||
'table_id': raw.get('table_id') if isinstance(raw.get('table_id'), str) else None,
|
||||
'cell_id': raw.get('cell_id') if isinstance(raw.get('cell_id'), str) else None,
|
||||
'row_index': None, # 行级由 line_key 外部关联,row_index 仅 layout table 使用。
|
||||
'value_bbox': value_bbox_dict,
|
||||
'value_bbox_valid': bbox_valid,
|
||||
'document_matches_case': doc_match,
|
||||
'field_code': field_code,
|
||||
'line_key': line_key,
|
||||
}
|
||||
|
||||
|
||||
def collect_vc_field_evidences(
|
||||
*,
|
||||
case_or_candidate: Any,
|
||||
case_document_id: int,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
展开 Vendor Comments 三来源 source_observations 为 ReviewEvidenceView.field_evidences 条目。
|
||||
|
||||
【AI 触发时机】:
|
||||
- Phase 4:构建 LLM 最小证据上下文时,追加三来源引用与 quote;
|
||||
- Phase 5:复核工作台加载 evidence 对照面板。
|
||||
|
||||
Args:
|
||||
case_or_candidate: ShippingOrderReviewCase 或 ShippingOrderCandidate。
|
||||
case_document_id: 当前 Case 的主文档 document_id,用于 document_matches_case。
|
||||
|
||||
Returns:
|
||||
归一化 observation 列表;未启用 VC 或路径缺数据返回空列表。
|
||||
"""
|
||||
payload = _vc_merged_payload(case_or_candidate)
|
||||
if payload is None:
|
||||
return []
|
||||
named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {}
|
||||
merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else []
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
seen: set[tuple[str, str, str]] = set()
|
||||
for cand in merged:
|
||||
if not isinstance(cand, dict):
|
||||
continue
|
||||
field_code = _safe_str(cand.get('target_field_code') or cand.get('field_code'))
|
||||
line_key = _safe_str(cand.get('line_key'))
|
||||
source_list = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else []
|
||||
for raw in source_list:
|
||||
if not isinstance(raw, dict):
|
||||
continue
|
||||
norm = _normalize_source_obs(
|
||||
raw,
|
||||
case_document_id=int(case_document_id or 0),
|
||||
field_code=field_code,
|
||||
line_key=line_key,
|
||||
named_regions=named_regions,
|
||||
)
|
||||
if norm is None:
|
||||
continue
|
||||
key = (
|
||||
str(norm.get('evidence_ref') or ''),
|
||||
str(norm.get('source_kind') or ''),
|
||||
str(norm.get('value') or '')[:64],
|
||||
)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
results.append(norm)
|
||||
return results
|
||||
@@ -1,204 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/document_layout/vc_source_gate_contract.py
|
||||
|
||||
用途:冻结 Vendor Comments 三来源的门禁枚举、证据引用格式、冲突原因码。
|
||||
依赖:零 I/O 纯契约模块,禁止 import 业务服务,避免 circular。
|
||||
逻辑:
|
||||
- ObservationSource 新增 vendor_comments_region(与 order_review_llm_contract.py 对齐)。
|
||||
- evidence_ref 格式 vc:document_id:pN:region:<region_id> 独立校验,禁止混入 layout: 前缀。
|
||||
- CQ 门禁新增 vc_source_merged_clean;原因码分「业务冲突」「格式不合法」「区域未绑定」三类。
|
||||
- 所有常量写入 frozenset/tuple,供 gate/preview/audit 三处共享,禁止双份维护。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any, Final, Literal
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 三来源字段来源种类(与前端 vc.types.ts Section E VCFieldSourceKind 一一对应)
|
||||
# ---------------------------------------------------------------------------
|
||||
VC_SOURCE_KINDS: Final[frozenset[str]] = frozenset({
|
||||
'header_region',
|
||||
'table_column',
|
||||
'vendor_comments',
|
||||
})
|
||||
VC_SOURCE_KIND_LABELS: Final[dict[str, str]] = {
|
||||
'header_region': 'Header 区域',
|
||||
'table_column': '表身列',
|
||||
'vendor_comments': 'Vendor Comments',
|
||||
}
|
||||
VC_SOURCE_EVIDENCE_PRIORITY: Final[dict[str, int]] = {
|
||||
# 优先级越大越优先;与 source_merge_service.py 证据选择顺序对齐。
|
||||
'vendor_comments': 3,
|
||||
'table_column': 2,
|
||||
'header_region': 1,
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 扩展 ObservationSource(与 order_review_llm_contract 原 4 类互不污染)
|
||||
# ---------------------------------------------------------------------------
|
||||
VENDOR_COMMENTS_OBSERVATION_SOURCE: Final[str] = 'vendor_comments_region'
|
||||
ALL_OBSERVATION_SOURCES_WITH_VC: Final[frozenset[str]] = frozenset({
|
||||
'unit_observation',
|
||||
'draft_observation',
|
||||
'frozen_layout',
|
||||
'text_fallback',
|
||||
VENDOR_COMMENTS_OBSERVATION_SOURCE,
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# VC 专用 evidence_ref:vc:<document_id>:p<page_no>:region:<region_id>
|
||||
# 缺任意段即视为无效,不伪造占位。
|
||||
# ---------------------------------------------------------------------------
|
||||
_VC_EVIDENCE_REF_RE = re.compile(
|
||||
r'^vc:(?P<doc>\d+):p(?P<page>\d+):region:(?P<region>[A-Za-z0-9_\-]{1,128})$'
|
||||
)
|
||||
|
||||
|
||||
def is_valid_vc_evidence_ref(value: Any) -> bool:
|
||||
"""
|
||||
校验 Vendor Comments evidence_ref 是否满足三段式契约。
|
||||
|
||||
【AI 触发时机】:当需要将 VC 来源写入 Observation evidence_ref、
|
||||
或 LLM 解析 quote 需要定位到命名区域时调用。
|
||||
|
||||
Args:
|
||||
value: 待校验字符串。
|
||||
|
||||
Returns:
|
||||
True 当且仅当正则命中且段值为正整数。
|
||||
"""
|
||||
if not isinstance(value, str) or not value:
|
||||
return False
|
||||
matched = _VC_EVIDENCE_REF_RE.match(value.strip())
|
||||
if not matched:
|
||||
return False
|
||||
try:
|
||||
doc = int(matched.group('doc'))
|
||||
page = int(matched.group('page'))
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
return doc > 0 and page > 0 and bool(matched.group('region'))
|
||||
|
||||
|
||||
def build_vc_evidence_ref(
|
||||
*,
|
||||
document_id: int | None,
|
||||
page_no: int | None,
|
||||
region_id: str | None,
|
||||
) -> str | None:
|
||||
"""
|
||||
按契约生成 VC evidence_ref;缺任意必需段返回 None,绝不伪造。
|
||||
|
||||
Args:
|
||||
document_id: PDF 主键,>0。
|
||||
page_no: 代表页号,>0。
|
||||
region_id: NamedRegion.region_id,非空。
|
||||
|
||||
Returns:
|
||||
合法 vc: 引用或 None。
|
||||
"""
|
||||
if not document_id or not page_no or not region_id:
|
||||
return None
|
||||
try:
|
||||
doc_i = int(document_id)
|
||||
page_i = int(page_no)
|
||||
rid = str(region_id).strip()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
if doc_i <= 0 or page_i <= 0 or not rid:
|
||||
return None
|
||||
ref = f'vc:{doc_i}:p{page_i}:region:{rid}'
|
||||
return ref if is_valid_vc_evidence_ref(ref) else None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Candidate Qualification 门禁:vc_source_merged_clean
|
||||
# ---------------------------------------------------------------------------
|
||||
CQ_GATE_VC_SOURCE_MERGED_CLEAN: Final[str] = 'vc_source_merged_clean'
|
||||
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED: Final[str] = 'vc_source_conflict_unresolved'
|
||||
CQ_REASON_VC_FORMAT_INVALID: Final[str] = 'vc_source_format_invalid'
|
||||
CQ_REASON_VC_REGION_UNBOUND: Final[str] = 'vc_source_region_unbound'
|
||||
CQ_VC_BLOCKING_REASONS: Final[frozenset[str]] = frozenset({
|
||||
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
|
||||
CQ_REASON_VC_FORMAT_INVALID,
|
||||
CQ_REASON_VC_REGION_UNBOUND,
|
||||
})
|
||||
# 归入 review_required(轻量人工确认)而非 hard-blocked 的原因。
|
||||
CQ_VC_REVIEW_REASONS: Final[frozenset[str]] = frozenset({
|
||||
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 合并决议(与 SourceMergeService.resolution 对齐,前端只读不改)
|
||||
# ---------------------------------------------------------------------------
|
||||
VC_MERGE_RESOLUTIONS: Final[frozenset[str]] = frozenset({
|
||||
'single_source_direct',
|
||||
'same_value_merged',
|
||||
'fill_missing',
|
||||
'needs_review',
|
||||
'annotation_only_dropped',
|
||||
'invalid_line_reference_dropped',
|
||||
})
|
||||
VC_DECISION_STATUSES: Final[frozenset[str]] = frozenset({
|
||||
'accepted',
|
||||
'pending',
|
||||
'dropped',
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 证据元数据键(与 Q18 metadata.shape 严格一致)
|
||||
# ---------------------------------------------------------------------------
|
||||
VC_EVIDENCE_META_KEYS: Final[frozenset[str]] = frozenset({
|
||||
'source_observations',
|
||||
'resolution',
|
||||
'accepted_value',
|
||||
'conflicts',
|
||||
'resolution_meta',
|
||||
'primary',
|
||||
})
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# VC Candidate Qualification 冲突项 shape(用于 candidate.conflicts_json 列表项)
|
||||
# ---------------------------------------------------------------------------
|
||||
def make_vc_candidate_conflict_item(
|
||||
*,
|
||||
reason: str,
|
||||
scope: Literal['header', 'line'],
|
||||
field_code: str,
|
||||
line_key: str | None = None,
|
||||
line_no: str | None = None,
|
||||
conflict_group_key: str,
|
||||
detail: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
构造符合 CQ 契约的 Vendor Comments 冲突项。
|
||||
|
||||
核心逻辑:reason 必须来自 CQ_VC_BLOCKING_REASONS;
|
||||
conflict_group_key 用于幂等去重(同组多次评估只记一条)。
|
||||
|
||||
Args:
|
||||
reason: 原因码,限 CQ_VC_BLOCKING_REASONS。
|
||||
scope: header / line。
|
||||
field_code: 订单字段,如 reservation_id。
|
||||
line_key: line scope 时的逻辑行键,header 为 None。
|
||||
line_no: 原始明细号字符串,便于审计。
|
||||
conflict_group_key: (scope, field_code, line_no) 稳定键。
|
||||
detail: 三来源 values / source_observations 快照,不含正文大对象。
|
||||
|
||||
Returns:
|
||||
candidate.conflicts_json 列表中的一项字典。
|
||||
"""
|
||||
safe_reason = reason if reason in CQ_VC_BLOCKING_REASONS else CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED
|
||||
return {
|
||||
'kind': 'vc_source',
|
||||
'reason': safe_reason,
|
||||
'severity': 'review_required' if safe_reason in CQ_VC_REVIEW_REASONS else 'blocking',
|
||||
'scope': scope,
|
||||
'field_code': field_code,
|
||||
'line_key': line_key,
|
||||
'line_no': line_no,
|
||||
'conflict_group_key': conflict_group_key,
|
||||
'detail': dict(detail or {}),
|
||||
}
|
||||
@@ -63,6 +63,7 @@ XFA_SPLIT_UNMATCHED_PRIORITY: Final[int] = 3
|
||||
|
||||
XfaSplitHandling = Literal['mapped', 'evidence_only']
|
||||
XfaSplitMatcherType = Literal['position', 'prefix', 'regex']
|
||||
XfaSplitPostProcessorType = Literal['prefix']
|
||||
XfaSplitSourceScope = Literal['header', 'line']
|
||||
XfaSplitUnmatchedPolicy = Literal['evidence_only', 'needs_review']
|
||||
XfaSplitDuplicatePolicy = Literal['needs_review']
|
||||
@@ -170,6 +171,28 @@ class XfaSplitSegment(BaseSplitSegment):
|
||||
return self
|
||||
|
||||
|
||||
class XfaSplitPostProcessor(XfaContractModel):
|
||||
"""位置/正则命中后的受限二次取值器,当前仅支持从标签后提取值。"""
|
||||
|
||||
type: XfaSplitPostProcessorType
|
||||
value: str = Field(min_length=1, max_length=XFA_SPLIT_MAX_PREFIX_LENGTH)
|
||||
separators: list[str] = Field(default_factory=lambda: [':', ':'])
|
||||
case_sensitive: bool = False
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_prefix_shape(self) -> 'XfaSplitPostProcessor':
|
||||
"""标签和分隔符均为受限静态文本,避免引入脚本式 pipeline。"""
|
||||
value = str(self.value or '').strip()
|
||||
separators = [str(item) for item in (self.separators or []) if str(item)]
|
||||
if not value:
|
||||
raise ValueError('prefix post processor requires non-empty value')
|
||||
if not separators:
|
||||
raise ValueError('prefix post processor requires at least one separator')
|
||||
object.__setattr__(self, 'value', value)
|
||||
object.__setattr__(self, 'separators', separators)
|
||||
return self
|
||||
|
||||
|
||||
class XfaSplitMatcher(BaseSplitMatcher):
|
||||
"""
|
||||
单行匹配器:position / prefix / regex。
|
||||
@@ -185,6 +208,7 @@ class XfaSplitMatcher(BaseSplitMatcher):
|
||||
case_sensitive: bool = False
|
||||
pattern: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_REGEX_PATTERN_LENGTH)
|
||||
capture_group: int | None = Field(default=None, ge=0, le=XFA_SPLIT_MAX_REGEX_GROUPS)
|
||||
post_processors: list[XfaSplitPostProcessor] = Field(default_factory=list, max_length=1)
|
||||
|
||||
@model_validator(mode='after')
|
||||
def validate_matcher_shape(self) -> 'XfaSplitMatcher':
|
||||
|
||||
@@ -27,6 +27,7 @@ from app.services.shipping_notice.document_layout.field_split_core import (
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.xfa_dataset import XfaLeafValue
|
||||
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
|
||||
XfaSplitPostProcessor,
|
||||
XfaSplitRuleSet,
|
||||
)
|
||||
|
||||
@@ -139,6 +140,56 @@ def _core_result_to_xfa(core: _CoreSplitEngineResult) -> XfaSplitEngineResult:
|
||||
)
|
||||
|
||||
|
||||
def _apply_prefix_post_processor(value: str, processor: XfaSplitPostProcessor) -> str | None:
|
||||
"""从已定位行中提取指定标签及分隔符后的值;未命中必须显式进入复核。"""
|
||||
source = str(value or '')
|
||||
comparable = source if processor.case_sensitive else source.lower()
|
||||
label = processor.value if processor.case_sensitive else processor.value.lower()
|
||||
start = comparable.find(label)
|
||||
if start < 0:
|
||||
return None
|
||||
tail_start = start + len(label)
|
||||
tail = source[tail_start:]
|
||||
for separator in processor.separators:
|
||||
if tail.startswith(separator):
|
||||
return tail[len(separator):].strip()
|
||||
return None
|
||||
|
||||
|
||||
def _apply_xfa_post_processors(
|
||||
result: XfaSplitEngineResult,
|
||||
*,
|
||||
rule_set: XfaSplitRuleSet,
|
||||
) -> XfaSplitEngineResult:
|
||||
"""对已由正式 matcher 定位的行执行受限后处理,并重新聚合正式字段。"""
|
||||
rules = {rule.rule_id: rule for rule in rule_set.rules}
|
||||
mapped_fields: dict[str, str] = {}
|
||||
needs_review = result.status == 'needs_review'
|
||||
for segment in result.segments:
|
||||
rule = rules.get(segment.rule_id)
|
||||
for processor in (rule.matcher.post_processors if rule else []):
|
||||
extracted = _apply_prefix_post_processor(segment.normalized_text, processor)
|
||||
if extracted is None:
|
||||
segment.normalized_text = ''
|
||||
segment.status = 'needs_review'
|
||||
needs_review = True
|
||||
result.diagnostics.append(XfaSplitDiagnostic(
|
||||
code='post_processor_no_match',
|
||||
message=f'Rule {segment.rule_id} post processor did not match the selected line',
|
||||
line_no=segment.line_no,
|
||||
field_code=segment.target_field_code,
|
||||
rule_ids=[segment.rule_id],
|
||||
))
|
||||
break
|
||||
segment.normalized_text = extracted
|
||||
if segment.handling == 'mapped' and segment.target_field_code:
|
||||
mapped_fields[segment.target_field_code] = segment.normalized_text
|
||||
result.mapped_fields = mapped_fields
|
||||
if needs_review:
|
||||
result.status = 'needs_review'
|
||||
return result
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 对外执行入口——签名 100% 不变
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -177,7 +228,7 @@ def execute_split_rule_set(
|
||||
rule_set=rule_set,
|
||||
lines=lines,
|
||||
)
|
||||
return _core_result_to_xfa(core_result)
|
||||
return _apply_xfa_post_processors(_core_result_to_xfa(core_result), rule_set=rule_set)
|
||||
|
||||
|
||||
def execute_split_on_leaf(
|
||||
|
||||
@@ -16,7 +16,7 @@ from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingDocumentProfileTestRun,
|
||||
ShippingDocumentProfileTestSample,
|
||||
@@ -30,13 +30,18 @@ from app.models import (
|
||||
ShippingOrderDocumentProfileSample,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot, _hydrate_coordinate_evidence
|
||||
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import reconstruct_coordinate_profile_rows
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
|
||||
coordinate_profile_character_candidates,
|
||||
reconstruct_coordinate_profile_rows, reconstruction_exclusion_regions,
|
||||
reconstruct_coordinate_profile_rows_with_strategy,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.runtime_parse_strategy import resolve_runtime_parse_strategy
|
||||
from app.services.shipping_notice.document_layout.order_field_extraction import (
|
||||
_is_placeholder_anchor_text, extract_order_fields,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ensure_on_demand_coordinate_evidence
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
from app.services.shipping_notice.order_document_profile_service import (
|
||||
@@ -44,6 +49,10 @@ from app.services.shipping_notice.order_document_profile_service import (
|
||||
_normalize_definition, _require_schema_version,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
|
||||
from app.services.shipping_notice.reservation_region import (
|
||||
apply_reservation_region_candidates,
|
||||
extract_reservation_from_region_text,
|
||||
)
|
||||
|
||||
|
||||
# 日常模板维护采用一份独立样本门槛;字段 confirmed、人工真值一致、
|
||||
@@ -126,109 +135,50 @@ def _table_html(document_id: int, table_id: str) -> str:
|
||||
raise ValidationError('Test sample table is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
|
||||
|
||||
def _coordinate_table_available(document_id: int, table_id: str) -> bool:
|
||||
"""确认 v2 盲测有冻结页面尺寸和目标表的字符证据,不要求 MinerU HTML。"""
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
layout = current_layout_snapshot(document) if document is not None else {}
|
||||
raw_table = next((item for item in (layout or {}).get('tables') or [] if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)), None)
|
||||
evidence = (layout or {}).get('coordinate_evidence') if isinstance((layout or {}).get('coordinate_evidence'), dict) else {}
|
||||
return bool(
|
||||
isinstance(raw_table, dict)
|
||||
and isinstance((evidence.get('tables') or {}).get(str(table_id)), list)
|
||||
and isinstance((evidence.get('pages') or {}).get(str(raw_table.get('page_no') or '')), dict)
|
||||
)
|
||||
|
||||
|
||||
def _recover_coordinate_table_for_preview(
|
||||
*, document: ShippingOrderDocument, layout: dict[str, Any], raw_table: dict[str, Any], table_id: str,
|
||||
) -> dict[str, Any]:
|
||||
"""仅为盲测复核临时恢复表格及整页坐标,不写回冻结布局或正式解析输入。"""
|
||||
recovered = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=layout,
|
||||
page_nos={int(raw_table.get('page_no') or 1)},
|
||||
table_by_page={int(raw_table.get('page_no') or 1): raw_table},
|
||||
)
|
||||
evidence = recovered.get('coordinate_evidence') if isinstance(recovered.get('coordinate_evidence'), dict) else {}
|
||||
if (
|
||||
isinstance((evidence.get('tables') or {}).get(str(table_id)), list)
|
||||
and isinstance((evidence.get('pages') or {}).get(str(raw_table.get('page_no') or 1)), dict)
|
||||
):
|
||||
return recovered
|
||||
def _coordinate_table_available_in_layout(layout: dict[str, Any], *, table_id: str, page_no: int) -> bool:
|
||||
"""判断运行期布局是否已有目标表与页面坐标证据。"""
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page_no = str(raw_table.get('page_no') or 1)
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
page_sources = (evidence.get('sources') or {}).get('pages') if isinstance(evidence.get('sources'), dict) else {}
|
||||
if (
|
||||
isinstance(tables.get(table_id), list)
|
||||
and isinstance(pages.get(page_no), dict)
|
||||
and isinstance(page_glyphs.get(page_no), list)
|
||||
and str((page_sources or {}).get(page_no) or '') in {'pdf_coordinate', 'ocr_coordinate'}
|
||||
):
|
||||
return layout
|
||||
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
|
||||
return layout
|
||||
try:
|
||||
from app.models import FileAsset
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
from app.services.shipping_notice.document_layout.native_pdf import extract_native_pdf_pages
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
|
||||
from app.services.shipping_notice.order_document_profile_service import (
|
||||
_native_characters_in_table, _ocr_lines_to_characters, _ocr_lines_to_page_characters,
|
||||
)
|
||||
|
||||
asset = db.session.get(FileAsset, document.asset_id)
|
||||
if asset is None:
|
||||
return layout
|
||||
page = next(
|
||||
item for item in extract_native_pdf_pages(read_asset_bytes(asset))
|
||||
if item.page_no == int(raw_table.get('page_no') or 0)
|
||||
)
|
||||
native_characters = list(getattr(page, 'characters', []) or [])
|
||||
full_page_characters = [item.model_dump(mode='json') for item in native_characters]
|
||||
source = 'pdf_coordinate'
|
||||
characters = _native_characters_in_table(
|
||||
characters=native_characters, table_bbox=raw_table.get('bbox') or {},
|
||||
)
|
||||
if not characters:
|
||||
ocr_lines = extract_ocr_lines(page.image, page_width=page.width, page_height=page.height)
|
||||
full_page_characters = _ocr_lines_to_page_characters(lines=ocr_lines)
|
||||
characters = _ocr_lines_to_characters(lines=ocr_lines, table_bbox=raw_table.get('bbox') or {})
|
||||
source = 'ocr_coordinate'
|
||||
if not characters or not full_page_characters:
|
||||
return layout
|
||||
next_layout = dict(layout)
|
||||
next_evidence = dict(evidence)
|
||||
next_evidence['tables'] = {**tables, table_id: characters}
|
||||
next_evidence['pages'] = {
|
||||
**pages, str(page.page_no): {'width': page.width, 'height': page.height},
|
||||
}
|
||||
next_evidence['page_glyphs'] = {**page_glyphs, str(page.page_no): full_page_characters}
|
||||
sources = dict(evidence.get('sources') or {})
|
||||
sources['pages'] = {**dict(sources.get('pages') or {}), str(page.page_no): source}
|
||||
next_evidence['sources'] = sources
|
||||
next_layout['coordinate_evidence'] = next_evidence
|
||||
return next_layout
|
||||
except Exception:
|
||||
return layout
|
||||
return bool(
|
||||
isinstance((evidence.get('tables') or {}).get(str(table_id)), list)
|
||||
and isinstance((evidence.get('pages') or {}).get(str(page_no)), dict)
|
||||
)
|
||||
|
||||
|
||||
def _region_characters_for_quality(
|
||||
*, region: Any, evidence: dict[str, Any], raw_table: dict[str, Any], table_id: str,
|
||||
) -> list[dict[str, Any]] | None:
|
||||
"""为盲测按模板显式策略选取冻结字符;旧模板始终沿用表格局部证据。"""
|
||||
table_characters = (evidence.get('tables') or {}).get(str(table_id))
|
||||
if getattr(region, 'row_reconstruction_mode', 'fixed_subrows') != 'adaptive_record_columns':
|
||||
return table_characters if isinstance(table_characters, list) else None
|
||||
"""为盲测选择当前页字符,确保与编辑器预览和正式解析共用同一输入事实。"""
|
||||
page_no = str(raw_table.get('page_no') or 1)
|
||||
page_characters = (evidence.get('page_glyphs') or {}).get(page_no)
|
||||
if isinstance(page_characters, list):
|
||||
return page_characters
|
||||
# 冻结快照仍可能来自升级前的证据结构;保持该模板原有表格证据可读。
|
||||
# 旧冻结快照可能没有页级坐标;仅在该事实缺失时回退当前物理表的字符。
|
||||
table_characters = (evidence.get('tables') or {}).get(str(table_id))
|
||||
return table_characters if isinstance(table_characters, list) else None
|
||||
|
||||
|
||||
def _quality_page_characters(
|
||||
*, region: Any, evidence: dict[str, Any], raw_table: dict[str, Any], page_no: int,
|
||||
) -> list[dict[str, Any]] | None:
|
||||
"""按表格实例隔离盲测行证据,禁止后续页重复消费首页 table glyphs。"""
|
||||
table_page_no = int(raw_table.get('page_no') or 1)
|
||||
if page_no == table_page_no:
|
||||
return _region_characters_for_quality(
|
||||
region=region, evidence=evidence, raw_table=raw_table,
|
||||
table_id=str(raw_table.get('table_id') or ''),
|
||||
)
|
||||
continuation = getattr(region, 'continuation_rule', None)
|
||||
allow_cross_page = bool(
|
||||
continuation.get('allow_cross_page')
|
||||
if isinstance(continuation, dict)
|
||||
else getattr(continuation, 'allow_cross_page', False)
|
||||
)
|
||||
if not allow_cross_page:
|
||||
return None
|
||||
page_glyphs = (evidence.get('page_glyphs') or {}).get(str(page_no))
|
||||
return page_glyphs if isinstance(page_glyphs, list) else None
|
||||
|
||||
|
||||
def _ensure_order_field_evidence(
|
||||
*, document: ShippingOrderDocument, layout: dict[str, Any], parser: OrderCoordinateProfile,
|
||||
) -> dict[str, Any]:
|
||||
@@ -396,7 +346,9 @@ def _candidate_for_sample(
|
||||
'Blind-test preview layout changed',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE',
|
||||
)
|
||||
layout = dict(frozen_version.payload_json) if frozen_version is not None else (
|
||||
layout = _hydrate_coordinate_evidence(
|
||||
payload=dict(frozen_version.payload_json), document=document,
|
||||
) if frozen_version is not None and document is not None else (
|
||||
current_layout_snapshot(document) if document is not None else None
|
||||
)
|
||||
is_document_candidate = str(table_id) == DOCUMENT_CANDIDATE_TABLE_ID
|
||||
@@ -409,21 +361,9 @@ def _candidate_for_sample(
|
||||
# 失败版本不会成为“当前成功快照”,但文档级盲测仍需以其安全元数据
|
||||
# 为起点从原文件临时恢复坐标;这里不把失败布局提升为正式快照。
|
||||
layout = dict(document.current_layout_version.payload_json)
|
||||
if document is None:
|
||||
raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
if is_document_candidate and not layout:
|
||||
# 上传与复核解耦后,后台 Layout 可能仍为 queued/running 且尚无 payload。
|
||||
# 文档级候选从安全空骨架进入现有原 PDF 按需恢复链,不等待、不取消也不写回后台任务。
|
||||
layout = {'status': 'pending', 'tables': [], 'issues': []}
|
||||
if not layout:
|
||||
if document is None or not layout:
|
||||
raise NotFoundError('Order document test sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
if isinstance(parser, OrderCoordinateProfile):
|
||||
if is_document_candidate:
|
||||
# [STEP 1] MinerU 未产出表格时,盲测仍以原文件字符坐标运行当前模板;
|
||||
# 证据只驻留本次调用,绝不写回布局或改变生产模板命中输入。
|
||||
layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=layout, page_nos=None,
|
||||
)
|
||||
layout = _ensure_order_field_evidence(document=document, layout=layout, parser=parser)
|
||||
schema_fields = {
|
||||
str(item.get('field_id') or ''): item
|
||||
@@ -435,20 +375,12 @@ def _candidate_for_sample(
|
||||
item for item in layout.get('tables') or []
|
||||
if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)
|
||||
), None)
|
||||
if isinstance(raw_table, dict) and frozen_version is None:
|
||||
layout = _recover_coordinate_table_for_preview(
|
||||
document=document, layout=layout, raw_table=raw_table, table_id=str(table_id),
|
||||
)
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
if (
|
||||
not is_document_candidate
|
||||
and not _coordinate_table_available(document_id, table_id)
|
||||
and not isinstance((evidence.get('tables') or {}).get(str(table_id)), list)
|
||||
):
|
||||
if not isinstance((evidence.get('tables') or {}).get(str(table_id)), list):
|
||||
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
if is_document_candidate and not any(isinstance(value, list) and value for value in page_glyphs.values()):
|
||||
if not any(isinstance(value, list) and value for value in page_glyphs.values()):
|
||||
raise ValidationError('Test sample coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID')
|
||||
rows: list[dict[str, Any]] = []
|
||||
for region in parser.table_regions:
|
||||
@@ -456,19 +388,14 @@ def _candidate_for_sample(
|
||||
# layout. They are valid template regions, but cannot reconstruct rows.
|
||||
if not region.line_layouts:
|
||||
continue
|
||||
if is_document_candidate:
|
||||
eligible_pages = [
|
||||
int(page_no) for page_no in pages
|
||||
if str(page_no).isdigit()
|
||||
and (
|
||||
region.page_scope == 'all_pages'
|
||||
or (region.page_scope == 'first_page' and int(page_no) == 1)
|
||||
or (region.page_scope == 'continuation_pages' and int(page_no) > 1)
|
||||
or (region.page_scope == 'exact_page' and int(page_no) == region.page_no)
|
||||
)
|
||||
]
|
||||
else:
|
||||
eligible_pages = [int(raw_table.get('page_no') or 1)] if isinstance(raw_table, dict) else []
|
||||
# ``page_scope`` 是历史人工策略。验证必须与正式解析一致:检查当前样本中
|
||||
# 每个有页级坐标事实的页面,由实际行结果决定是否属于续页。
|
||||
eligible_pages = [
|
||||
int(page_no) for page_no, glyphs in page_glyphs.items()
|
||||
if str(page_no).isdigit() and isinstance(glyphs, list) and glyphs
|
||||
]
|
||||
if not eligible_pages and isinstance(raw_table, dict):
|
||||
eligible_pages = [int(raw_table.get('page_no') or 1)]
|
||||
for page_no in sorted(eligible_pages):
|
||||
page = pages.get(str(page_no))
|
||||
if not isinstance(page, dict):
|
||||
@@ -477,31 +404,115 @@ def _candidate_for_sample(
|
||||
table_bbox = {'x0': 0, 'y0': 0, 'x1': float(page['width']), 'y1': float(page['height'])}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
characters = (
|
||||
page_glyphs.get(str(page_no))
|
||||
if is_document_candidate
|
||||
else _region_characters_for_quality(
|
||||
region=region, evidence=evidence, raw_table=raw_table, table_id=str(table_id),
|
||||
if is_document_candidate:
|
||||
characters = page_glyphs.get(str(page_no))
|
||||
elif not isinstance(raw_table, dict):
|
||||
characters = None
|
||||
else:
|
||||
characters = _quality_page_characters(
|
||||
region=region, evidence=evidence, raw_table=raw_table, page_no=page_no,
|
||||
)
|
||||
candidate_table_bbox = raw_table.get('bbox') if isinstance(raw_table, dict) and page_no == int(raw_table.get('page_no') or 1) else None
|
||||
characters, _candidate_page_bbox = coordinate_profile_character_candidates(
|
||||
table_region=region.region.model_dump(), page_size=page,
|
||||
reference_page_frame=(
|
||||
region_frame.model_dump()
|
||||
if (region_frame := parser.reference_page_frames.get(page_no)) is not None else None
|
||||
),
|
||||
page_characters=characters if isinstance(characters, list) else None,
|
||||
table_characters=(evidence.get('tables') or {}).get(str(raw_table.get('table_id') or '')) if isinstance(raw_table, dict) else None,
|
||||
raw_table_bbox=candidate_table_bbox,
|
||||
table_id=str(raw_table.get('table_id') or '') if isinstance(raw_table, dict) else None,
|
||||
page_no=page_no,
|
||||
allow_table_fallback=(
|
||||
isinstance(raw_table, dict)
|
||||
and page_no == int(raw_table.get('page_no') or 1)
|
||||
),
|
||||
)
|
||||
if not isinstance(characters, list):
|
||||
continue
|
||||
rows.extend(item.fields for item in reconstruct_coordinate_profile_rows(
|
||||
characters=[item for item in characters if isinstance(item, dict)], table_bbox=table_bbox,
|
||||
# 表头布局只描述列语义和预览高亮,不能作为静态删除区;否则单头高度变化时
|
||||
# 会在起行锚点识别前误删首条明细字符。仅应用管理员明确配置的普通排除区。
|
||||
reconstruction_exclusions = reconstruction_exclusion_regions(region.model_dump())
|
||||
reconstruction_table_bbox = (
|
||||
{
|
||||
'x0': 0, 'y0': 0,
|
||||
'x1': region_frame.width, 'y1': region_frame.height,
|
||||
}
|
||||
if region_frame is not None else table_bbox
|
||||
)
|
||||
chosen_rows, strategy = reconstruct_coordinate_profile_rows_with_strategy(
|
||||
characters=[item for item in characters if isinstance(item, dict)], table_bbox=reconstruction_table_bbox,
|
||||
line_layouts=[item.model_dump() for item in region.line_layouts], table_region=region.region.model_dump(),
|
||||
termination_rules=[item.model_dump() for item in region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in region.exclusion_regions],
|
||||
exclusion_regions=reconstruction_exclusions,
|
||||
dynamic_exclusion_regions=reconstruction_exclusions,
|
||||
line_start_field_code=region.line_start_field_code,
|
||||
row_reconstruction_mode=region.row_reconstruction_mode,
|
||||
) if not item.issues)
|
||||
schema_field_metadata=list(schema_fields.values()),
|
||||
)
|
||||
if strategy.status == 'selected':
|
||||
rows.extend(item.fields for item in chosen_rows if not item.issues)
|
||||
order_fields = [
|
||||
{
|
||||
'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status,
|
||||
'field_id': item.field_id, 'scope': item.scope,
|
||||
'page_no': item.page_no, 'issues': list(item.issues),
|
||||
}
|
||||
for item in extract_order_fields(profile=parser, schema_fields=schema_fields, coordinate_evidence=evidence)
|
||||
for item in extract_order_fields(
|
||||
profile=parser,
|
||||
schema_fields=schema_fields,
|
||||
coordinate_evidence=evidence,
|
||||
allow_fixed_region_confirmation=True,
|
||||
)
|
||||
]
|
||||
# 盲测与正式解析共用 Reservation 区域解析和归属契约;区域页可以不同于明细页。
|
||||
profile_definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
reservation_region = profile_definition.get('reservation_id_region')
|
||||
if isinstance(reservation_region, dict):
|
||||
region = reservation_region.get('region')
|
||||
try:
|
||||
reservation_page_no = int(reservation_region.get('page_no') or 0)
|
||||
except (TypeError, ValueError):
|
||||
reservation_page_no = 0
|
||||
if isinstance(region, dict) and reservation_page_no > 0:
|
||||
layout = _ensure_page_coordinate_evidence(
|
||||
document=document, layout=layout, page_no=reservation_page_no,
|
||||
)
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
page = (evidence.get('pages') or {}).get(str(reservation_page_no))
|
||||
glyphs = (evidence.get('page_glyphs') or {}).get(str(reservation_page_no))
|
||||
if isinstance(page, dict) and isinstance(glyphs, list):
|
||||
candidates = extract_reservation_from_region_text(
|
||||
read_coordinate_region_text(glyphs=glyphs, page=page, region=region),
|
||||
)
|
||||
reservation_fields = {
|
||||
str(field.get('scope') or ''): field
|
||||
for field in schema_fields.values()
|
||||
if str(field.get('field_code') or '') == 'reservation_id'
|
||||
}
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=candidates,
|
||||
header_field_id=str((reservation_fields.get('header') or {}).get('field_id') or '') or None,
|
||||
line_field_id=str((reservation_fields.get('line') or {}).get('field_id') or '') or None,
|
||||
line_count=len(rows),
|
||||
)
|
||||
if applied.header_value and reservation_fields.get('header'):
|
||||
header = reservation_fields['header']
|
||||
order_fields.append({
|
||||
'field_code': str(header.get('field_code') or ''), 'value': applied.header_value,
|
||||
'status': 'confirmed', 'field_id': str(header.get('field_id') or ''), 'scope': 'header',
|
||||
'page_no': reservation_page_no, 'issues': [],
|
||||
})
|
||||
if reservation_fields.get('line'):
|
||||
for line_no, value in applied.line_values.items():
|
||||
if isinstance(rows[line_no - 1], dict):
|
||||
rows[line_no - 1]['reservation_id'] = value
|
||||
if applied.needs_review:
|
||||
return {
|
||||
'document_id': document.id, 'table_id': str(table_id), 'rows': rows,
|
||||
'order_fields': order_fields, 'reservation_region_status': 'needs_review',
|
||||
'reservation_region_review_reasons': list(applied.review_reasons),
|
||||
}
|
||||
return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields}
|
||||
raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
|
||||
@@ -562,7 +573,7 @@ def _common_blind_sample_descriptors(
|
||||
layout_version = ShippingDocumentLayoutVersion.query.filter_by(document_id=document.id).order_by(
|
||||
ShippingDocumentLayoutVersion.version.desc(), ShippingDocumentLayoutVersion.id.desc(),
|
||||
).first()
|
||||
layout = dict(layout_version.payload_json) if layout_version is not None and isinstance(layout_version.payload_json, dict) else {}
|
||||
layout = current_layout_snapshot(document) or {}
|
||||
tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
|
||||
if (
|
||||
layout_version is None or layout_version.status != 'ready'
|
||||
@@ -595,7 +606,9 @@ def _common_blind_sample_descriptors(
|
||||
except ValidationError:
|
||||
continue
|
||||
header_preview = [slot.text for slot in (grid.rows[0] if grid.rows else []) if slot is not None and slot.text][:3]
|
||||
coordinate_evidence_ready = _coordinate_table_available(document.id, table_id)
|
||||
coordinate_evidence_ready = _coordinate_table_available_in_layout(
|
||||
layout, table_id=table_id, page_no=int(table.get('page_no') or 1),
|
||||
)
|
||||
descriptors.append({
|
||||
'document_id': document.id, 'table_id': table_id,
|
||||
'page_no': int(table.get('page_no') or 1), 'filename': document.filename or '',
|
||||
@@ -634,6 +647,11 @@ def _compare_blind_candidate(
|
||||
failures: list[str] = []
|
||||
total = 0
|
||||
matched = 0
|
||||
if candidate.get('reservation_region_status') == 'needs_review':
|
||||
failures.extend([
|
||||
f'reservation_region:{reason}'
|
||||
for reason in candidate.get('reservation_region_review_reasons') or ['needs_review']
|
||||
])
|
||||
for field in candidate.get('order_fields') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
@@ -820,7 +838,7 @@ def _prepare_common_blind_sample(
|
||||
or not isinstance(version.payload_json, dict)
|
||||
):
|
||||
raise ConflictError('Blind-test preview layout changed', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_PREVIEW_STALE')
|
||||
layout = dict(version.payload_json)
|
||||
layout = _hydrate_coordinate_evidence(payload=dict(version.payload_json), document=document)
|
||||
raw_table = next((
|
||||
item for item in layout.get('tables') or []
|
||||
if isinstance(item, dict) and str(item.get('table_id') or '') == str(table_id)
|
||||
@@ -1084,11 +1102,6 @@ def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
or last_run.status != 'passed' or last_run.profile_checksum != _quality_checksum(profile)
|
||||
):
|
||||
raise ConflictError('A current passing blind test run is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY')
|
||||
if int(actor_id) == int(suite.created_by_id):
|
||||
raise ForbiddenError(
|
||||
'Editor cannot approve own blind test suite',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_READY',
|
||||
)
|
||||
suite.status = 'approved'
|
||||
# A coordinate-template approval is also its publish-quality credential.
|
||||
# Validate the remaining publish prerequisites before committing approval so
|
||||
|
||||
@@ -41,7 +41,7 @@ def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str
|
||||
if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}:
|
||||
return 'closed'
|
||||
upload = str(get('upload_status', '') or '').strip().lower()
|
||||
if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no') or get('upload_receipt_json'):
|
||||
if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no'):
|
||||
return 'completed'
|
||||
return 'active'
|
||||
|
||||
|
||||
@@ -61,19 +61,31 @@ def _normalize_schema_row(
|
||||
|
||||
|
||||
def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[int, str], list[str]]:
|
||||
"""将首行映射为 Schema 订单字段或邮件专属字段;重复映射直接标为复核。"""
|
||||
"""将首行映射为 Schema 订单字段;同字段多个别名按 Schema 顺序保留首选列。"""
|
||||
schema_headers = _schema_headers(schema_definition)
|
||||
mapped: dict[int, str] = {}
|
||||
selected_by_field: dict[str, tuple[int, int]] = {}
|
||||
issues: list[str] = []
|
||||
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)
|
||||
hits = [schema_field] if schema_field else []
|
||||
if len(hits) == 1:
|
||||
if hits[0] in mapped.values():
|
||||
issues.append('email_supplement_duplicate_header')
|
||||
field_code = str(hits[0])
|
||||
priority = _schema_header_priority(schema_definition, field_code, normalized)
|
||||
previous = selected_by_field.get(field_code)
|
||||
if previous is None:
|
||||
mapped[column] = field_code
|
||||
selected_by_field[field_code] = (priority, column)
|
||||
else:
|
||||
mapped[column] = hits[0]
|
||||
previous_priority, previous_column = previous
|
||||
# 同一业务字段出现两个已配置别名时,按 Schema 中 field_code、
|
||||
# display_name、aliases 的声明顺序选择唯一证据列;不把同一行
|
||||
# 的 Source / hub code 误判为冲突,也不允许后一个列覆盖首选值。
|
||||
if priority < previous_priority:
|
||||
mapped.pop(previous_column, None)
|
||||
mapped[column] = field_code
|
||||
selected_by_field[field_code] = (priority, column)
|
||||
elif len(hits) > 1:
|
||||
issues.append('email_supplement_header_ambiguous')
|
||||
if not ({'customer_po_number', 'po_number'} & set(mapped.values())):
|
||||
@@ -81,6 +93,21 @@ def _field_map(grid: Any, *, schema_definition: dict[str, Any]) -> tuple[dict[in
|
||||
return mapped, sorted(set(issues))
|
||||
|
||||
|
||||
def _schema_header_priority(schema_definition: dict[str, Any], field_code: str, normalized_header: str) -> int:
|
||||
"""返回字段表头的 Schema 声明顺序,供同字段多别名确定性裁决。"""
|
||||
priorities: list[int] = []
|
||||
for raw in schema_definition.get('fields') or []:
|
||||
if not isinstance(raw, dict) or not raw.get('enabled', True):
|
||||
continue
|
||||
if str(raw.get('field_code') or '').strip() != field_code:
|
||||
continue
|
||||
candidates = (field_code, raw.get('display_name'), *(raw.get('aliases') or []))
|
||||
for priority, value in enumerate(candidates):
|
||||
if normalize_table_header(value).casefold() == normalized_header:
|
||||
priorities.append(priority)
|
||||
return min(priorities) if priorities else 2**31 - 1
|
||||
|
||||
|
||||
def _schema_headers(schema_definition: dict[str, Any]) -> dict[str, str | None]:
|
||||
"""收集邮件补充允许的 Schema 别名;跨字段冲突必须显式保留为不可映射。"""
|
||||
headers: dict[str, str | None] = {}
|
||||
|
||||
@@ -531,7 +531,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'字段已按 PDF 优先裁决,请核对辅助证据差异',
|
||||
),
|
||||
'evidence_missing': _meta('owner', 'open_order_review', '关键识别结果缺少有效证据'),
|
||||
'customer_unresolved': _meta('owner', 'confirm_customer', '未能识别客户'),
|
||||
'customer_unresolved': _meta('owner', 'confirm_customer', '客户尚未确认'),
|
||||
'customer_ambiguous': _meta('owner', 'confirm_customer', '匹配到多个客户'),
|
||||
'customer_out_of_scope': _meta('owner', 'confirm_customer', '客户不在当前业务范围内'),
|
||||
'reservation_missing': _meta('owner', 'edit_reservation', '缺少有效 Reservation'),
|
||||
@@ -566,10 +566,10 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'inventory_preparation_waiting': _meta('worker', 'poll_inventory_preparation', '库存文件准备中,请稍后刷新'),
|
||||
'inventory_preparation_failed': _meta('owner', 'retry_inventory_preparation', '库存准备失败,请重试或上传库存文件'),
|
||||
'inventory_rpa_queued': _meta('worker', 'poll_inventory_preparation', 'RPA 任务已排队等待执行'),
|
||||
'inventory_rpa_timeout': _meta('worker', 'retry_inventory_preparation', 'RPA 执行超时'),
|
||||
'inventory_rpa_timeout': _meta('worker', 'reload_inventory_result', 'RPA 执行超时'),
|
||||
'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'),
|
||||
'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'),
|
||||
'inventory_rpa_exhausted': _meta('owner', 'upload_inventory_file', '库存源重试次数已耗尽'),
|
||||
'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'),
|
||||
'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'),
|
||||
'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'),
|
||||
'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'),
|
||||
@@ -583,7 +583,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'inventory_shortage_review_required': _meta('owner', 'open_shortage_review', '存在库存缺口,需要人工处理'),
|
||||
'excel_not_ready': _meta('system', 'recheck_excel_readiness', '当前尚不满足 Excel 生成条件'),
|
||||
'artifact_generation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 生成失败'),
|
||||
'manual_upload_pending': _meta('owner', 'mark_manual_uploaded', '请下载 Excel 后在货代平台上传并登记结果'),
|
||||
'manual_upload_pending': _meta('owner', 'mark_manual_uploaded', '请下载 Excel 后在货代平台上传并确认已上传'),
|
||||
'upload_rpa_pending': _meta('worker', 'poll_freight_upload_rpa', '货代平台上传任务等待执行'),
|
||||
'upload_rpa_failed': _meta('worker', 'retry_freight_upload_rpa', '货代平台上传失败,可重试 RPA'),
|
||||
'upload_rpa_login_failed': _meta('admin', 'retry_freight_upload_rpa', '货代平台登录失败,请检查凭据后重试'),
|
||||
@@ -601,7 +601,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
|
||||
'void_blocked_external_uploaded': _meta('owner', '', '已存在外部履约,禁止作废,请归档'),
|
||||
'task_rejected_by_user': _meta('owner', '', '订单候选/任务已由用户驳回'),
|
||||
'task_closed_after_upload': _meta('owner', '', '上传完成后任务已关闭'),
|
||||
'close_blocked_missing_receipt': _meta('owner', 'mark_manual_uploaded', '缺少上传回执,暂不可关闭'),
|
||||
'close_blocked_missing_receipt': _meta('owner', 'mark_manual_uploaded', '尚未确认已上传,暂不可关闭'),
|
||||
'late_callback_ignored': _meta('system', '', '迟到的外部回调已忽略'),
|
||||
'excel_downloaded': _meta('owner', '', '已下载发货 Excel'),
|
||||
'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'),
|
||||
|
||||
@@ -24,9 +24,11 @@ from openpyxl import load_workbook
|
||||
from openpyxl.cell.cell import MergedCell
|
||||
from sqlalchemy import func
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import (
|
||||
ShippingExcelTemplate,
|
||||
ShippingExportArtifact,
|
||||
ShippingNoticeLine,
|
||||
ShippingInventoryField,
|
||||
ShippingInventorySource,
|
||||
ShippingOrderSnapshot,
|
||||
@@ -37,6 +39,31 @@ from app.path_utils import resolve_backend_relative_path
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
|
||||
|
||||
def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None:
|
||||
"""
|
||||
确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。
|
||||
|
||||
Args:
|
||||
task: 当前发货通知单。
|
||||
|
||||
Raises:
|
||||
ConflictError: 已存在任意导出 Artifact;后续库存必须创建新的发货通知单。
|
||||
"""
|
||||
if task.id is None:
|
||||
return
|
||||
existing = ShippingExportArtifact.query.filter_by(task_id=int(task.id)).first()
|
||||
if existing is not None:
|
||||
raise ConflictError(
|
||||
'A shipping notice can generate only one Excel artifact',
|
||||
code='SHIPPING.NOTICE_EXCEL_ALREADY_GENERATED',
|
||||
details={
|
||||
'task_no': task.task_no,
|
||||
'business_no': task.business_no,
|
||||
'artifact_no': existing.artifact_no,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _storage_root() -> Path:
|
||||
"""返回发货通知文件根目录。"""
|
||||
configured = str(current_app.config.get('SHIPPING_NOTICE_STORAGE_ROOT') or '').strip()
|
||||
@@ -45,8 +72,22 @@ def _storage_root() -> Path:
|
||||
return Path(current_app.instance_path) / 'shipping_notice'
|
||||
|
||||
|
||||
def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
|
||||
"""后续分批 Notice 回读同一 OT 的首个冻结 Notice,订单事实不复制。"""
|
||||
if notice.order_snapshot_id:
|
||||
return notice
|
||||
if notice.order_task_id:
|
||||
source = ShippingNotice.query.filter(
|
||||
ShippingNotice.order_task_id == int(notice.order_task_id),
|
||||
ShippingNotice.order_snapshot_id.isnot(None),
|
||||
).order_by(ShippingNotice.id.asc()).first()
|
||||
if source is not None:
|
||||
return source
|
||||
return notice
|
||||
|
||||
|
||||
def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""从冻结 Snapshot 按稳定 field_id 返回 Header/Line 值,禁止履约阶段读取 FieldValue。"""
|
||||
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
assert_task_not_supersession_blocked(task)
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
|
||||
@@ -62,19 +103,10 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di
|
||||
|
||||
|
||||
def _excel_business_no(task: ShippingNotice, *, export_date: date | None = None) -> str | None:
|
||||
"""生成本次 Excel 使用的 Pull Request Number;不回写业务单主编号。"""
|
||||
case = task.shipping_case
|
||||
if case is None or not case.business_no:
|
||||
return None
|
||||
business_no = str(case.business_no).strip()
|
||||
prefix = business_no[:-8] if len(business_no) > 8 else business_no
|
||||
sequence = business_no[-2:] if len(business_no) >= 2 and business_no[-2:].isdigit() else ''
|
||||
if not sequence and case.sequence_value:
|
||||
sequence = f'{int(case.sequence_value):02d}'
|
||||
if not sequence:
|
||||
return None
|
||||
export_date = export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date()
|
||||
return f'{prefix}{export_date.strftime("%y%m%d")}{sequence}'
|
||||
"""返回当前发货通知单编号;履约路径不回退到其他聚合标识。"""
|
||||
if task.business_no:
|
||||
return str(task.business_no).strip()
|
||||
return None
|
||||
|
||||
|
||||
def _clear_template_data_rows(ws: Any, start_row: int) -> None:
|
||||
@@ -92,6 +124,7 @@ def _system_fact(
|
||||
*,
|
||||
export_sequence: int | None = None,
|
||||
excel_business_no: str | None = None,
|
||||
notice_no: str | None = None,
|
||||
export_date: date | None = None,
|
||||
) -> Any:
|
||||
"""
|
||||
@@ -106,8 +139,8 @@ def _system_fact(
|
||||
对应系统事实值;未知键返回 None。
|
||||
"""
|
||||
values = {
|
||||
'task_no': task.task_no,
|
||||
'business_no': excel_business_no or (task.shipping_case.business_no if task.shipping_case else None),
|
||||
'task_no': notice_no or task.task_no,
|
||||
'business_no': notice_no or excel_business_no or task.business_no,
|
||||
'warehouse_id': task.inventory_warehouse_id,
|
||||
'inventory_source_code': task.inventory_source_code,
|
||||
'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(),
|
||||
@@ -160,6 +193,7 @@ def _mapping_value(
|
||||
mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any],
|
||||
header_values: dict[str, Any] | None = None, export_sequence: int | None = None,
|
||||
excel_business_no: str | None = None,
|
||||
notice_no: str | None = None,
|
||||
export_date: date | None = None,
|
||||
) -> Any:
|
||||
"""
|
||||
@@ -196,12 +230,17 @@ def _mapping_value(
|
||||
task, key,
|
||||
export_sequence=export_sequence if key == 'export_sequence' else None,
|
||||
excel_business_no=excel_business_no,
|
||||
notice_no=notice_no,
|
||||
export_date=export_date,
|
||||
)
|
||||
if key == 'export_sequence' and value is None:
|
||||
value = order_values.get('__export_sequence')
|
||||
else:
|
||||
value = key
|
||||
# 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串;
|
||||
# 尤其金额字段不得由数量/单价等相邻字段隐式推导或伪装为已提供。
|
||||
if kind == 'order_field' and value is None:
|
||||
return None
|
||||
return _format_value(value, mapping['formatter'])
|
||||
|
||||
|
||||
@@ -389,6 +428,7 @@ def _filename(
|
||||
template: ShippingExcelTemplate,
|
||||
*,
|
||||
excel_business_no: str | None = None,
|
||||
notice_no: str | None = None,
|
||||
) -> str:
|
||||
"""按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。"""
|
||||
pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip()
|
||||
@@ -397,16 +437,15 @@ def _filename(
|
||||
if not pattern:
|
||||
raise ValueError('发货 Excel 文件名规则未配置')
|
||||
now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S')
|
||||
shipping_case = task.shipping_case
|
||||
values = {
|
||||
'task_no': task.task_no,
|
||||
'business_no': excel_business_no or (shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no),
|
||||
'task_no': notice_no or task.task_no,
|
||||
'business_no': notice_no or excel_business_no or task.business_no or task.task_no,
|
||||
'source_code': task.inventory_source_code or '',
|
||||
'ts': now,
|
||||
'date': now[:8],
|
||||
'customer_short_code': (shipping_case.customer_short_code_snapshot or '') if shipping_case else '',
|
||||
'business_date': shipping_case.business_date.strftime('%y%m%d') if shipping_case and shipping_case.business_date else '',
|
||||
'sequence': f'{int(shipping_case.sequence_value):02d}' if shipping_case and shipping_case.sequence_value else '',
|
||||
'customer_short_code': task.customer_short_code_snapshot or '',
|
||||
'business_date': task.business_date.strftime('%y%m%d') if task.business_date else '',
|
||||
'sequence': f'{int(task.business_sequence_value):02d}' if task.business_sequence_value else '',
|
||||
}
|
||||
try:
|
||||
return _safe_filename(pattern.format(**values))
|
||||
@@ -418,6 +457,7 @@ def _input_checksum(
|
||||
task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate,
|
||||
snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]],
|
||||
inventory_lines: list[dict[str, Any]],
|
||||
notice_id: int | None = None,
|
||||
) -> str:
|
||||
"""以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。"""
|
||||
payload = {
|
||||
@@ -426,12 +466,15 @@ def _input_checksum(
|
||||
'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id,
|
||||
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id,
|
||||
'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines,
|
||||
'notice_id': notice_id,
|
||||
}
|
||||
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str)
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExportArtifact]:
|
||||
def generate_shipment_excel(
|
||||
task: ShippingNotice,
|
||||
) -> tuple[str, str, ShippingExportArtifact]:
|
||||
"""
|
||||
按库存源发布模板生成 Excel,并在当前事务新增不可变 Artifact。
|
||||
【AI 触发时机】:仅由 generate_excel Tool 在库存匹配完成后调用;Agent 禁止传模板或字段映射。
|
||||
@@ -441,56 +484,16 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
|
||||
Raises:
|
||||
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
|
||||
AppError: [T6 硬门禁] 行级库存匹配存在非 matched 行(shortage / not_found / conflict)。
|
||||
AppError: 没有可导出的满足/已审计放行行,或输入事实不完整。
|
||||
"""
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
|
||||
from app.core.errors import AppError
|
||||
|
||||
if not task_is_active(task):
|
||||
raise ValueError('已作废或归档的任务不能生成发货 Excel')
|
||||
assert_task_not_supersession_blocked(task)
|
||||
# [T6 E2 硬门禁] 生成 Excel 前复用库存满足性判定:每行须库存充足,
|
||||
# 或为带原因的正式短缺放行;未匹配/冲突绝不能用放行绕过。
|
||||
if task.id is not None:
|
||||
pending_rows = db.session.query(
|
||||
ShippingNoticeLineInventoryMatch.line_key,
|
||||
ShippingNoticeLineInventoryMatch.match_result,
|
||||
ShippingNoticeLineInventoryMatch.part_number,
|
||||
ShippingNoticeLineInventoryMatch.reservation_id,
|
||||
ShippingNoticeLineInventoryMatch.shortage_qty,
|
||||
).filter(
|
||||
ShippingNoticeLineInventoryMatch.task_id == task.id,
|
||||
ShippingNoticeLineInventoryMatch.is_current.is_(True),
|
||||
).limit(20).all()
|
||||
# 行级库存事实是当前正式放行 Gate 的真相。历史导出任务可能只有
|
||||
# Reservation 核验轮次;这类任务继续由下方 Reservation 选择保护,不能因
|
||||
# 缺少新表事实被误判为“未匹配”。
|
||||
has_line_match_facts = bool(pending_rows)
|
||||
from app.services.shipping_notice.fulfillment_workflow import match_completed
|
||||
if has_line_match_facts and not match_completed(task):
|
||||
details = [
|
||||
{
|
||||
'line_key': r[0],
|
||||
'match_result': r[1],
|
||||
'part_number': r[2],
|
||||
'reservation_id': r[3],
|
||||
'shortage_qty': r[4],
|
||||
}
|
||||
for r in pending_rows
|
||||
]
|
||||
raise AppError(
|
||||
code='SHIPPING.EXCEL_NOT_READY',
|
||||
message='存在未满足或未放行的库存行,禁止生成发货 Excel(请先处理短缺或冲突)。',
|
||||
http_status=409,
|
||||
details={
|
||||
'blocking_reason_code': 'inventory_match_incomplete',
|
||||
'pending_count': len(pending_rows),
|
||||
'pending_rows_preview': details,
|
||||
'resume_suggestion': '调用 match_inventory 重匹配或人工逐行确认短缺/冲突后再导出。',
|
||||
},
|
||||
)
|
||||
assert_notice_has_no_export_artifact(task)
|
||||
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
|
||||
source_code = str(task.inventory_source_code or '').strip().upper()
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
@@ -520,18 +523,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
# applies only when the published template actually consumes that system fact.
|
||||
if _template_requires_system_warehouse_id(mappings) and not str(task.inventory_warehouse_id or '').strip():
|
||||
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
|
||||
active_artifact = ShippingExportArtifact.query.filter(
|
||||
ShippingExportArtifact.task_id == task.id,
|
||||
ShippingExportArtifact.status.in_({'ready', 'uploading'}),
|
||||
).first()
|
||||
if active_artifact is not None:
|
||||
raise ValueError('当前任务存在待上传的发货 Excel,必须先完成或授权作废该 Artifact')
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
|
||||
source_notice = _source_notice_for_order_facts(task)
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None
|
||||
if snapshot is None:
|
||||
raise ValueError('任务没有可用于导出的冻结订单快照')
|
||||
header_values, all_line_values = order_field_id_values(task)
|
||||
export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date()
|
||||
excel_business_no = _excel_business_no(task, export_date=export_date)
|
||||
from app.services.shipping_notice.reservation_service import (
|
||||
current_available_snapshot_line_ids,
|
||||
reserve_available_for_artifact,
|
||||
@@ -546,12 +543,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
|
||||
release_overrides_by_source_line: dict[int, dict[str, Any]] = {}
|
||||
released_source_line_indexes: set[int] = set()
|
||||
if task.id is not None:
|
||||
if source_notice.id is not None:
|
||||
release_rows = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(task.id),
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
|
||||
)
|
||||
@@ -570,10 +567,19 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
for source_index, line in enumerate(snapshot.lines)
|
||||
if source_index in release_overrides_by_source_line
|
||||
}
|
||||
verification, available_line_ids = current_available_snapshot_line_ids(
|
||||
task,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
)
|
||||
selected_snapshot_line_ids = {
|
||||
int(row.snapshot_line_id)
|
||||
for row in ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).all()
|
||||
if row.snapshot_line_id is not None
|
||||
}
|
||||
try:
|
||||
verification, available_line_ids = current_available_snapshot_line_ids(
|
||||
source_notice,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
selected_snapshot_line_ids=selected_snapshot_line_ids or None,
|
||||
)
|
||||
except ConflictError:
|
||||
raise
|
||||
# [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
|
||||
line_values = []
|
||||
for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)):
|
||||
@@ -587,7 +593,7 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
|
||||
|
||||
# [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
|
||||
inventory_lines = resolve_inventory_lines_for_execution(task)
|
||||
inventory_lines = resolve_inventory_lines_for_execution(source_notice)
|
||||
release_overrides_by_line = _release_overrides_for_export_lines(
|
||||
line_values=line_values,
|
||||
release_overrides_by_source_line=release_overrides_by_source_line,
|
||||
@@ -609,9 +615,17 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values]
|
||||
header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields)
|
||||
|
||||
# [STEP 4] Notice 的业务单号与首个 Excel 同一事务产生。此处已完成业务、
|
||||
# 库存和导出行校验;随后 Excel、Artifact 或 Reservation 任一步失败都会回滚编号流水。
|
||||
if not task.business_no:
|
||||
from app.services.shipping_notice.business_numbering_service import assign_notice_business_number
|
||||
|
||||
assign_notice_business_number(task)
|
||||
excel_business_no = _excel_business_no(task, export_date=export_date)
|
||||
filename = _filename(task, template, excel_business_no=excel_business_no)
|
||||
artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}'
|
||||
directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no
|
||||
directory_key = task.task_no
|
||||
directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / directory_key
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f'{artifact_no}_{filename}'
|
||||
template_bytes = file_asset_storage.get_bytes(template.storage_key)
|
||||
@@ -654,14 +668,16 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
wb.close()
|
||||
|
||||
content = path.read_bytes()
|
||||
# 滚动履约允许同一任务按后续库存分批导出;已就绪 Artifact 仍是
|
||||
# 已占用预约单的审计事实,不能被新一轮导出整体覆盖为 superseded。
|
||||
# 当前 Notice 的唯一 Excel;后续分批履约必须先创建新的 Notice,
|
||||
# 因而不得在此处替换或追加当前 Notice 的 Artifact。
|
||||
artifact = ShippingExportArtifact(
|
||||
artifact_no=artifact_no, task_id=task.id, template_id=template.id,
|
||||
artifact_no=artifact_no, task_id=task.id,
|
||||
template_id=template.id,
|
||||
order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id,
|
||||
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id,
|
||||
input_checksum=_input_checksum(
|
||||
task, source, template, snapshot, header_values, line_values, inventory_lines,
|
||||
notice_id=int(task.id),
|
||||
),
|
||||
file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(),
|
||||
file_size=len(content), status='ready',
|
||||
@@ -669,10 +685,11 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
|
||||
db.session.add(artifact)
|
||||
db.session.flush()
|
||||
reserve_available_for_artifact(
|
||||
task,
|
||||
source_notice,
|
||||
artifact=artifact,
|
||||
verification=verification,
|
||||
released_snapshot_line_ids=released_snapshot_line_ids,
|
||||
selected_snapshot_line_ids=selected_snapshot_line_ids or None,
|
||||
)
|
||||
return str(path), filename, artifact
|
||||
except Exception:
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/export_archive.py
|
||||
|
||||
用途:为一个批次或显式任务集合生成受权限控制的发货 Excel ZIP 下载包。
|
||||
用途:为显式任务集合生成受权限控制的发货 Excel ZIP 下载包。
|
||||
依赖:ShippingExportArtifact、query_service 用户归属查询、zipfile 与统一业务异常。
|
||||
逻辑:选择每票全部 ready Artifact,校验文件 checksum,处理重名并写入 manifest.json。
|
||||
逻辑:选择每张通知唯一可下载 Artifact,校验文件 checksum,处理重名并写入 manifest.json。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,36 +18,30 @@ from zipfile import ZIP_DEFLATED, ZipFile
|
||||
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import ShippingExportArtifact, ShippingNotice
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_batch_for_user,
|
||||
get_task_for_user,
|
||||
list_sorted_batch_tasks,
|
||||
resolve_task_export_download,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import get_task_for_user, resolve_task_export_download
|
||||
|
||||
MAX_ARCHIVE_TASKS = 100
|
||||
|
||||
|
||||
def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | None) -> tuple[list[ShippingNotice], str]:
|
||||
"""按批次或任务号选择当前用户任务;两种模式互斥且禁止部分越权成功。"""
|
||||
normalized_batch = str(batch_no or '').strip()
|
||||
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_nos or []) if str(item or '').strip()))
|
||||
if bool(normalized_batch) == bool(normalized_tasks):
|
||||
raise ValidationError('Provide exactly one of batch_no or task_nos', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
|
||||
if normalized_batch:
|
||||
batch = get_batch_for_user(normalized_batch, user_id)
|
||||
if batch is None:
|
||||
raise NotFoundError('Shipping batch not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
|
||||
tasks = list_sorted_batch_tasks(batch)
|
||||
archive_key = normalized_batch
|
||||
else:
|
||||
tasks = []
|
||||
for task_no in normalized_tasks:
|
||||
task = get_task_for_user(task_no, user_id)
|
||||
if task is None:
|
||||
raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
|
||||
tasks.append(task)
|
||||
archive_key = 'selected'
|
||||
def _select_tasks(
|
||||
*,
|
||||
user_id: int,
|
||||
task_refs: list[str] | None,
|
||||
selection_name: str,
|
||||
require_business_no: bool = False,
|
||||
) -> tuple[list[ShippingNotice], str]:
|
||||
"""按显式 task_no 或 business_no 选择当前用户通知,禁止部分越权成功。"""
|
||||
normalized_tasks = list(dict.fromkeys(str(item or '').strip() for item in (task_refs or []) if str(item or '').strip()))
|
||||
if not normalized_tasks:
|
||||
raise ValidationError(f'{selection_name} is required', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
|
||||
tasks = []
|
||||
for task_no in normalized_tasks:
|
||||
task = get_task_for_user(task_no, user_id)
|
||||
if task is None or (
|
||||
require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper()
|
||||
):
|
||||
raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
|
||||
tasks.append(task)
|
||||
if not tasks:
|
||||
raise ValidationError('No shipping tasks selected', code='SHIPPING.EXPORT_ARCHIVE_EMPTY')
|
||||
if len(tasks) > MAX_ARCHIVE_TASKS:
|
||||
@@ -55,7 +49,7 @@ def _select_tasks(*, user_id: int, batch_no: str | None, task_nos: list[str] | N
|
||||
f'At most {MAX_ARCHIVE_TASKS} tasks can be downloaded at once',
|
||||
code='SHIPPING.EXPORT_ARCHIVE_TOO_LARGE', details={'max_tasks': MAX_ARCHIVE_TASKS},
|
||||
)
|
||||
return tasks, archive_key
|
||||
return tasks, 'selected'
|
||||
|
||||
|
||||
def _ready_artifacts(tasks: list[ShippingNotice]) -> dict[int, list[ShippingExportArtifact]]:
|
||||
@@ -92,7 +86,10 @@ def _archive_name(filename: str, task_no: str, used: set[str]) -> str:
|
||||
|
||||
|
||||
def build_export_archive(
|
||||
*, user_id: int, batch_no: str | None = None, task_nos: list[str] | None = None,
|
||||
*,
|
||||
user_id: int,
|
||||
task_nos: list[str] | None = None,
|
||||
business_nos: list[str] | None = None,
|
||||
) -> tuple[BinaryIO, str, dict]:
|
||||
"""
|
||||
生成 ZIP 和 manifest;缺失/损坏票据保留在 manifest,但不阻止其余有效文件下载。
|
||||
@@ -100,7 +97,16 @@ def build_export_archive(
|
||||
Returns:
|
||||
(定位到开头的 ZIP 字节流, 下载文件名, manifest 字典)。
|
||||
"""
|
||||
tasks, archive_key = _select_tasks(user_id=user_id, batch_no=batch_no, task_nos=task_nos)
|
||||
if task_nos is not None and business_nos is not None:
|
||||
raise ValidationError('select either task_nos or business_nos', code='SHIPPING.EXPORT_ARCHIVE_SELECTION_INVALID')
|
||||
selection_values = business_nos if business_nos is not None else task_nos
|
||||
selection_name = 'business_nos' if business_nos is not None else 'task_nos'
|
||||
tasks, archive_key = _select_tasks(
|
||||
user_id=user_id,
|
||||
task_refs=selection_values,
|
||||
selection_name=selection_name,
|
||||
require_business_no=business_nos is not None,
|
||||
)
|
||||
artifacts = _ready_artifacts(tasks)
|
||||
# 小包驻留内存,超过 16 MiB 自动落到系统临时目录,避免批次下载挤占 worker 内存。
|
||||
stream = SpooledTemporaryFile(max_size=16 * 1024 * 1024, mode='w+b')
|
||||
@@ -129,7 +135,7 @@ def build_export_archive(
|
||||
included += 1
|
||||
entries.append(entry)
|
||||
manifest = {
|
||||
'archive_version': 1, 'selection': {'batch_no': batch_no, 'task_nos': task_nos or []},
|
||||
'archive_version': 1, 'selection': {selection_name: selection_values},
|
||||
'generated_at': datetime.utcnow().isoformat(), 'total_tasks': len(tasks),
|
||||
'included_count': included, 'excluded_count': len(entries) - included, 'entries': entries,
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
services/shipping_notice/freight_cancellation_service.py
|
||||
|
||||
用途:货代撤销回执登记,以及建单后取消时的只读 / 待作废软处置(禁止物理删除)。
|
||||
用途:外部撤销确认登记,以及建单后取消时的只读 / 待作废软处置(禁止物理删除)。
|
||||
依赖:ShippingFreightCancellation、ShippingNotice、ShippingTaskEvent、Workflow Item Version、
|
||||
fulfillment_audit。
|
||||
逻辑:complete_freight_cancellation 登记回执并作废旧任务;mark_cancelled_task_readonly
|
||||
逻辑:complete_freight_cancellation 登记外部撤销确认并作废旧任务;mark_cancelled_task_readonly
|
||||
在用户取消已建单 WorkflowItem 时将 Task 置 pending_void、Excel/Version 只读,
|
||||
并写前后快照审计。
|
||||
"""
|
||||
@@ -24,19 +24,15 @@ def complete_freight_cancellation(
|
||||
*,
|
||||
cancellation_id: int,
|
||||
actor_id: int,
|
||||
freight_receipt_no: str,
|
||||
receipt_asset_id: int,
|
||||
note: str | None = None,
|
||||
) -> ShippingFreightCancellation:
|
||||
"""
|
||||
登记可追溯的货代撤销回执,随后作废旧任务并解除新版本的履约阻断。
|
||||
登记可追溯的外部撤销确认,随后作废旧任务并解除新版本的履约阻断。
|
||||
|
||||
Args:
|
||||
cancellation_id: 撤销单主键。
|
||||
actor_id: 操作人。
|
||||
freight_receipt_no: 货代回执号。
|
||||
receipt_asset_id: 回执 FileAsset。
|
||||
note: 可选备注。
|
||||
note: 外部撤销确认原因,必填。
|
||||
|
||||
Returns:
|
||||
更新后的 ShippingFreightCancellation。
|
||||
@@ -46,9 +42,9 @@ def complete_freight_cancellation(
|
||||
raise NotFoundError('Freight cancellation not found', code='SHIPPING.FREIGHT_CANCELLATION_NOT_FOUND')
|
||||
if row.status == 'cancelled':
|
||||
return row
|
||||
receipt = str(freight_receipt_no or '').strip()
|
||||
if not receipt or not receipt_asset_id:
|
||||
raise ValidationError('Cancellation receipt number and file are required', code='SHIPPING.FREIGHT_CANCELLATION_RECEIPT_REQUIRED')
|
||||
confirmation_note = str(note or '').strip()
|
||||
if not confirmation_note:
|
||||
raise ValidationError('External cancellation confirmation note is required', code='SHIPPING.FREIGHT_CANCELLATION_CONFIRMATION_REQUIRED')
|
||||
old = ShippingNotice.query.filter_by(id=row.old_task_id).with_for_update().one()
|
||||
new = ShippingNotice.query.filter_by(id=row.new_task_id).with_for_update().one()
|
||||
if new.supersedes_task_id != old.id:
|
||||
@@ -56,9 +52,9 @@ def complete_freight_cancellation(
|
||||
row.status = 'cancelled'
|
||||
row.completed_by_id = int(actor_id)
|
||||
row.completed_at = datetime.utcnow()
|
||||
row.freight_receipt_no = receipt
|
||||
row.receipt_asset_id = int(receipt_asset_id)
|
||||
row.failure_reason = str(note or '').strip() or None
|
||||
row.freight_receipt_no = None
|
||||
row.receipt_asset_id = None
|
||||
row.failure_reason = confirmation_note
|
||||
old.lifecycle_status = 'voided'
|
||||
old.voided_at = datetime.utcnow()
|
||||
old.voided_by_id = int(actor_id)
|
||||
@@ -72,7 +68,7 @@ def complete_freight_cancellation(
|
||||
actor_id=actor_id,
|
||||
detail_json={
|
||||
'cancellation_id': row.id,
|
||||
'receipt_no': receipt,
|
||||
'confirmation_note': confirmation_note,
|
||||
'new_task_no': new.task_no,
|
||||
'reason_code': 'task_voided_for_correction',
|
||||
},
|
||||
@@ -83,7 +79,7 @@ def complete_freight_cancellation(
|
||||
actor_id=actor_id,
|
||||
detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no},
|
||||
))
|
||||
# 统一审计:货代回执登记必须可按 reason_code 检索
|
||||
# 统一审计:外部撤销确认必须可按 reason_code 检索。
|
||||
record_fulfillment_audit(
|
||||
event_type='freight_cancellation_completed',
|
||||
aggregate_type='shipping_task',
|
||||
@@ -97,13 +93,13 @@ def complete_freight_cancellation(
|
||||
before={'lifecycle_status': 'active'},
|
||||
after={
|
||||
'lifecycle_status': 'voided',
|
||||
'freight_receipt_no': receipt,
|
||||
'external_cancellation_confirmed': True,
|
||||
'new_task_no': new.task_no,
|
||||
'cancellation_id': int(row.id),
|
||||
},
|
||||
metadata={
|
||||
'cancellation_id': int(row.id),
|
||||
'receipt_asset_id': int(receipt_asset_id),
|
||||
'confirmation_note': confirmation_note,
|
||||
'new_task_no': str(new.task_no),
|
||||
},
|
||||
source='workspace_api',
|
||||
|
||||
@@ -7,12 +7,12 @@ services/shipping_notice/fulfillment_workflow.py
|
||||
tool_common、tool_response、fulfillment_audit、task_workflow(Excel 就绪清失效)、
|
||||
order_task_stage_machine。
|
||||
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match;
|
||||
STP 多候选:跨文件匹配后仅全部 ok 记 completed+100% 并自动 Excel;partial/冲突记 needs_human;
|
||||
STP 多候选:跨文件匹配后仅全部 ok 记 completed+100%;partial 仍可按滚动库存生成已满足行 Excel;
|
||||
AUTO_UPLOAD 默认 false(须环境显式 true;缺失键 fail-closed 并告警);
|
||||
开启时 Excel 后先做货代 RPA 就绪校验再触发(stage=upload_rpa_pending);关闭时停于人工上传;
|
||||
工作台操作人经 operator_id / actor_id / _trusted_user_id 写入匹配与审计事件;
|
||||
upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工凭据);
|
||||
RPA 成功须带白名单 kind + page_url + dom_snippet/dom_sha256,并尽量落 evidence_asset;
|
||||
upload_to_freight 支持 mode=auto|retry_upload(RPA)与 manual_confirm(人工确认);
|
||||
RPA 成功须带受信回调中的白名单状态信息;不保存截图、DOM 文件或证据资产;
|
||||
Excel 生成成功写路径清除 invalidated_from_stage(BE-02,禁止投影 GET 清库)。
|
||||
"""
|
||||
|
||||
@@ -124,10 +124,10 @@ def _normalize_rpa_success_evidence(
|
||||
expected_filename: str | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
校验 RPA 成功回调中的 success_evidence(BE-05 fail-closed)。
|
||||
校验 RPA 成功回调中的受信状态摘要(fail-closed)。
|
||||
|
||||
核心逻辑:kind 须在白名单;selector / observed_at / filename / page_url 必填;
|
||||
必须带 dom_snippet + 匹配的 dom_sha256(不可变 DOM 证据);
|
||||
必须带经 Worker 校验过的 selector、观察时间、文件名和页面定位;
|
||||
若提供 expected_filename 则须与证据文件名一致(大小写不敏感)。
|
||||
|
||||
Args:
|
||||
@@ -137,8 +137,6 @@ def _normalize_rpa_success_evidence(
|
||||
Returns:
|
||||
规范化 evidence dict;缺失/非法时 None。
|
||||
"""
|
||||
import hashlib
|
||||
|
||||
raw = payload.get('success_evidence')
|
||||
if not isinstance(raw, dict):
|
||||
return None
|
||||
@@ -155,16 +153,13 @@ def _normalize_rpa_success_evidence(
|
||||
return None
|
||||
if not dom_snippet or not dom_sha256:
|
||||
return None
|
||||
# [BE-05] 片段与哈希必须自洽,防止 Worker 自报成功却无对应 DOM。
|
||||
computed = hashlib.sha256(dom_snippet.encode('utf-8')).hexdigest().lower()
|
||||
if computed != dom_sha256:
|
||||
import hashlib
|
||||
if hashlib.sha256(dom_snippet.encode('utf-8')).hexdigest().lower() != dom_sha256:
|
||||
return None
|
||||
if expected_filename:
|
||||
expected = str(expected_filename).strip()
|
||||
if expected and filename.lower() != expected.lower():
|
||||
return None
|
||||
screenshot_sha256 = str(raw.get('screenshot_sha256') or '').strip().lower() or None
|
||||
screenshot_base64 = str(raw.get('screenshot_base64') or '').strip() or None
|
||||
return {
|
||||
'kind': kind,
|
||||
'selector': selector,
|
||||
@@ -174,42 +169,22 @@ def _normalize_rpa_success_evidence(
|
||||
'page_url': page_url,
|
||||
'dom_snippet': dom_snippet[:8000],
|
||||
'dom_sha256': dom_sha256,
|
||||
'screenshot_sha256': screenshot_sha256,
|
||||
'screenshot_base64': screenshot_base64,
|
||||
'screenshot_sha256': str(raw.get('screenshot_sha256') or '').strip().lower() or None,
|
||||
'screenshot_base64': str(raw.get('screenshot_base64') or '').strip() or None,
|
||||
}
|
||||
|
||||
|
||||
def _persist_rpa_success_evidence_asset(
|
||||
*,
|
||||
task: 'ShippingNotice',
|
||||
attempt: Any,
|
||||
success_evidence: dict[str, Any],
|
||||
) -> int | None:
|
||||
"""
|
||||
将 RPA 成功 DOM/截图落为 FileAsset,并回写 attempt.evidence_asset_id。
|
||||
|
||||
核心逻辑:优先截图 PNG;否则将脱敏 DOM 片段存为 .html;绑定后从 JSON 去掉 base64 大字段。
|
||||
|
||||
Args:
|
||||
task: 发货 Notice。
|
||||
attempt: ShippingUploadAttempt。
|
||||
success_evidence: 已规范化证据(可含 screenshot_base64)。
|
||||
|
||||
Returns:
|
||||
FileAsset.id;落库失败时 None(证据仍留在 success_evidence_json)。
|
||||
"""
|
||||
def _persist_rpa_success_evidence_asset(*, task: 'ShippingNotice', attempt: Any, success_evidence: dict[str, Any]) -> int | None:
|
||||
"""将受信 RPA 的 DOM/可选截图保存为内部审计资产;人工上传路径不调用本函数。"""
|
||||
import base64
|
||||
import hashlib
|
||||
|
||||
from app.models import FileAsset
|
||||
from app.services.file_assets.service import generate_asset_no, _build_storage_key
|
||||
from app.services.file_assets.service import generate_asset_no, _build_storage_key, mark_asset_referenced
|
||||
from app.services.file_assets.storage import file_asset_storage
|
||||
from app.services.file_assets.service import mark_asset_referenced
|
||||
|
||||
if not getattr(task, 'user_id', None):
|
||||
success_evidence.pop('screenshot_base64', None)
|
||||
return None
|
||||
|
||||
raw_b64 = str(success_evidence.pop('screenshot_base64', None) or '').strip()
|
||||
data: bytes | None = None
|
||||
filename = f"rpa-success-{int(attempt.id)}.html"
|
||||
@@ -220,41 +195,22 @@ def _persist_rpa_success_evidence_asset(
|
||||
except Exception:
|
||||
data = None
|
||||
if data:
|
||||
filename = f"rpa-success-{int(attempt.id)}.png"
|
||||
mime_type = 'image/png'
|
||||
filename, mime_type = f"rpa-success-{int(attempt.id)}.png", 'image/png'
|
||||
if not data:
|
||||
snippet = str(success_evidence.get('dom_snippet') or '').encode('utf-8')
|
||||
if not snippet:
|
||||
return None
|
||||
data = snippet
|
||||
data = str(success_evidence.get('dom_snippet') or '').encode('utf-8') or None
|
||||
if not data:
|
||||
return None
|
||||
content_hash = hashlib.sha256(data).hexdigest().lower()
|
||||
expected_shot = str(success_evidence.get('screenshot_sha256') or '').strip().lower()
|
||||
if expected_shot and filename.endswith('.png') and expected_shot != content_hash:
|
||||
return None
|
||||
asset_no = generate_asset_no()
|
||||
storage_key = _build_storage_key(
|
||||
user_id=int(task.user_id),
|
||||
asset_no=asset_no,
|
||||
filename=filename,
|
||||
)
|
||||
asset = FileAsset(
|
||||
asset_no=asset_no,
|
||||
owner_user_id=int(task.user_id),
|
||||
original_filename=filename,
|
||||
parent_asset_id=None,
|
||||
asset_role='rpa_success_evidence',
|
||||
source_attachment_key=f'rpa-success:{int(attempt.id)}',
|
||||
storage_provider='minio',
|
||||
storage_bucket=file_asset_storage.bucket_name,
|
||||
storage_key=storage_key,
|
||||
content_hash=content_hash,
|
||||
file_size=len(data),
|
||||
mime_type=mime_type,
|
||||
extension=filename.rsplit('.', 1)[-1],
|
||||
upload_status='uploading',
|
||||
lifecycle_status='temporary',
|
||||
reference_count=0,
|
||||
)
|
||||
storage_key = _build_storage_key(user_id=int(task.user_id), asset_no=asset_no, filename=filename)
|
||||
asset = FileAsset(asset_no=asset_no, owner_user_id=int(task.user_id), original_filename=filename,
|
||||
parent_asset_id=None, asset_role='rpa_success_evidence', source_attachment_key=f'rpa-success:{int(attempt.id)}',
|
||||
storage_provider='minio', storage_bucket=file_asset_storage.bucket_name, storage_key=storage_key,
|
||||
content_hash=content_hash, file_size=len(data), mime_type=mime_type, extension=filename.rsplit('.', 1)[-1],
|
||||
upload_status='uploading', lifecycle_status='temporary', reference_count=0)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
try:
|
||||
@@ -271,7 +227,6 @@ def _persist_rpa_success_evidence_asset(
|
||||
return int(asset.id)
|
||||
|
||||
|
||||
|
||||
def _hash_rpa_evidence_field(value: str | None) -> str | None:
|
||||
"""对 evidence 中的 filename/reference 做 sha256,审计禁止落原文。"""
|
||||
if not value:
|
||||
@@ -628,9 +583,9 @@ def _sync_workflow_stage(
|
||||
|
||||
def match_completed(task: ShippingNotice) -> bool:
|
||||
"""
|
||||
STP 制单门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时允许生成 Excel。
|
||||
STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。
|
||||
|
||||
核心逻辑:禁止 partial / 任意一行短缺、冲突、未命中进入自动制单或 Excel 门禁。
|
||||
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
|
||||
"""
|
||||
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewLineDecision
|
||||
|
||||
@@ -663,6 +618,52 @@ def match_completed(task: ShippingNotice) -> bool:
|
||||
return True
|
||||
|
||||
|
||||
def _released_snapshot_line_ids_for_export(task: ShippingNotice) -> set[int]:
|
||||
"""读取当前任务已审计的短缺放行行,供滚动 Excel 资格筛选使用。"""
|
||||
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision, ShippingOrderSnapshot
|
||||
from app.services.shipping_notice.export import _source_notice_for_order_facts
|
||||
|
||||
source_notice = _source_notice_for_order_facts(task)
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None
|
||||
if snapshot is None or source_notice.id is None:
|
||||
return set()
|
||||
decisions = (
|
||||
ShippingOrderReviewLineDecision.query
|
||||
.join(ShippingOrderReviewCase, ShippingOrderReviewLineDecision.review_case_id == ShippingOrderReviewCase.id)
|
||||
.filter(
|
||||
ShippingOrderReviewCase.confirmed_task_id == int(source_notice.id),
|
||||
ShippingOrderReviewLineDecision.is_active.is_(True),
|
||||
ShippingOrderReviewLineDecision.decision_code == 'release_inventory_shortage',
|
||||
)
|
||||
.all()
|
||||
)
|
||||
released_indexes = {
|
||||
int(decision.line_index)
|
||||
for decision in decisions
|
||||
if decision.line_index is not None
|
||||
}
|
||||
return {
|
||||
int(line.id)
|
||||
for index, line in enumerate(snapshot.lines)
|
||||
if index in released_indexes
|
||||
}
|
||||
|
||||
|
||||
def exportable_snapshot_line_ids(task: ShippingNotice) -> set[int]:
|
||||
"""返回当前库存轮次可先行导出的冻结订单行;不代表整单已满足。"""
|
||||
from app.services.shipping_notice.export import _source_notice_for_order_facts
|
||||
from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids
|
||||
|
||||
try:
|
||||
_verification, line_ids = current_available_snapshot_line_ids(
|
||||
_source_notice_for_order_facts(task),
|
||||
released_snapshot_line_ids=_released_snapshot_line_ids_for_export(task),
|
||||
)
|
||||
except ConflictError:
|
||||
return set()
|
||||
return set(line_ids)
|
||||
|
||||
|
||||
def _match_step_progress_fields(
|
||||
*,
|
||||
match_status: str,
|
||||
@@ -708,7 +709,8 @@ def excel_gate_error(task: ShippingNotice) -> str | None:
|
||||
"""校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。"""
|
||||
if str(getattr(task, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"} and task.export_file_path:
|
||||
return None
|
||||
if not match_completed(task):
|
||||
# 滚动履约允许先导出当前完整满足/已审计放行的行;剩余短缺行继续保留在库存满足性 Gate。
|
||||
if not match_completed(task) and not exportable_snapshot_line_ids(task):
|
||||
return "workflow.fulfillment.excel_gate_unmatched"
|
||||
return None
|
||||
|
||||
@@ -757,10 +759,10 @@ def try_auto_chain_after_match(
|
||||
|
||||
tool_payload = merge_tool_payload(task, payload)
|
||||
|
||||
# [STEP 1] 低风险:匹配成功后自动生成 Excel。
|
||||
# [STEP 1] 低风险:存在可导出行时自动生成下一份滚动 Excel。
|
||||
if _auto_generate_excel_enabled():
|
||||
db.session.refresh(task)
|
||||
if not task.export_file_path and match_completed(task):
|
||||
if not task.export_file_path and excel_gate_error(task) is None:
|
||||
gen = generate_excel(tool_payload)
|
||||
if gen.get("status") != "ok":
|
||||
return gen
|
||||
@@ -904,6 +906,7 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str,
|
||||
disposition_gate = _task_disposition_gate_response(task)
|
||||
if disposition_gate is not None:
|
||||
return disposition_gate
|
||||
|
||||
customer_gate = customer_gate_tool_response(task, operation='match_inventory_line')
|
||||
if customer_gate is not None:
|
||||
return customer_gate
|
||||
@@ -1680,7 +1683,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
基于已匹配任务生成货代发货 Excel 并推进至 waiting_upload。
|
||||
【AI 触发时机】:本轮至少一个预约单完整满足且用户确认制单时调用;未匹配前禁止调用。
|
||||
|
||||
核心逻辑:已有导出文件时直接返回成功;否则走 excel_gate_error 门禁 → generate_shipment_excel → 写 export_file_path → WAITING_UPLOAD。
|
||||
核心逻辑:已有导出文件时直接返回成功;否则按当前可导出行通过 excel_gate_error,生成滚动 Excel;未满足行保留在库存满足性 Gate。
|
||||
|
||||
Args:
|
||||
payload: 须含 task_id 或 conversation_id。
|
||||
@@ -1766,7 +1769,11 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids
|
||||
|
||||
try:
|
||||
_verification, available_line_ids = current_available_snapshot_line_ids(task)
|
||||
from app.services.shipping_notice.export import _source_notice_for_order_facts
|
||||
|
||||
_verification, available_line_ids = current_available_snapshot_line_ids(
|
||||
_source_notice_for_order_facts(task),
|
||||
)
|
||||
except ConflictError:
|
||||
available_line_ids = set()
|
||||
if not available_line_ids:
|
||||
@@ -1780,7 +1787,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
# [STEP 2] 先校验是否满足导出门禁。
|
||||
# 只有库存匹配完成后才允许生成货代 Excel;但 waiting_upload/uploaded 仍应视为“已完成匹配”。
|
||||
# 只要当前库存轮次存在可导出行即可生成滚动 Excel;未满足行继续停留在库存满足性 Gate。
|
||||
gate_error = excel_gate_error(task)
|
||||
if gate_error:
|
||||
return tool_response(
|
||||
@@ -1894,22 +1901,25 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
status="ok",
|
||||
task_id=task.task_no,
|
||||
message=t("workflow.fulfillment.generate_done", lang=lang).format(file=filename),
|
||||
data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"},
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
"download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
货代上传入口:RPA 自动/重试,或人工凭据登记。
|
||||
货代上传入口:RPA 自动/重试,或人工确认唯一 Excel 已上传。
|
||||
【AI 触发时机】:AUTO_UPLOAD 开启且 Excel 就绪时可由 auto_progress 以 mode=auto 调用;
|
||||
人工接管后使用 mode=manual_confirm。
|
||||
人工接管后使用 mode=manual_confirm;工作台对外必须先按 business_no 定位 Notice。
|
||||
|
||||
核心逻辑:mode=auto|retry_upload → 触发 RPA(受 AUTO_UPLOAD 与重试上限约束);
|
||||
mode=manual_confirm → 校验凭据后标记 UPLOADED 并关闭 WorkflowItem。
|
||||
mode=manual_confirm → 校验唯一 Artifact 后标记 UPLOADED 并关闭 WorkflowItem。
|
||||
|
||||
Args:
|
||||
payload: 须含 task_id;mode=auto|retry_upload|manual_confirm;
|
||||
manual_confirm 须含 evidence_asset_no、operator_id。
|
||||
payload: 内部须含 task_id;mode=auto|retry_upload|manual_confirm;
|
||||
manual_confirm 须含服务端可信 operator_id,不接收回执或截图/PDF。
|
||||
|
||||
Returns:
|
||||
dict[str, Any]: status 可为 ok / running / needs_human / failed。
|
||||
@@ -1973,11 +1983,11 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
return tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
message='货代自动上传未开启,请人工下载 Excel 并登记上传凭据。',
|
||||
message='货代自动上传未开启,请人工下载 Excel 并确认已上传。',
|
||||
data=serialize_task_for_tool(task),
|
||||
forbidden_next_tools=['upload_to_freight'],
|
||||
stop_agent_turn=True,
|
||||
next_required_action='请在任务处理工作台使用「登记人工上传」。',
|
||||
next_required_action='请在任务处理工作台使用「确认已上传」。',
|
||||
)
|
||||
return _trigger_freight_upload_rpa(
|
||||
task,
|
||||
@@ -1995,16 +2005,12 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
|
||||
operator_id = payload.get('operator_id')
|
||||
evidence_asset_no = str(payload.get('evidence_asset_no') or '')
|
||||
freight_ref_no = str(payload.get('freight_ref_no') or '')
|
||||
before_upload_status = str(task.upload_status or '')
|
||||
try:
|
||||
attempt = record_manual_upload(
|
||||
task,
|
||||
artifact_id=artifact_id,
|
||||
evidence_asset_no=evidence_asset_no,
|
||||
operator_id=int(operator_id),
|
||||
freight_ref_no=freight_ref_no,
|
||||
)
|
||||
except (ConflictError, ValidationError, TypeError, ValueError) as exc:
|
||||
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
|
||||
@@ -2032,8 +2038,6 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
metadata={
|
||||
'attempt_id': attempt.id,
|
||||
'artifact_id': attempt.artifact_id,
|
||||
'evidence_asset_no': evidence_asset_no,
|
||||
'freight_ref_no': freight_ref_no or None,
|
||||
},
|
||||
source='workspace_api',
|
||||
sensitivity_level='sensitive',
|
||||
@@ -2072,7 +2076,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
说明:本期主流程不触发货代 RPA 上传;本回调仅保留兼容,不应由业务主动调用。
|
||||
|
||||
核心逻辑:success=True → UPLOADED + freight_ref_no;失败 → UPLOAD_FAILED,达最大重试转人工。
|
||||
缺省或非法 success **fail-closed 为失败**;success=True 必须带 success_evidence.kind。
|
||||
缺省或非法 success **fail-closed 为失败**;success=True 必须带受信状态摘要。
|
||||
|
||||
Args:
|
||||
payload: 须含 task_id;success(bool,缺省视为失败);success_evidence(成功必填);
|
||||
@@ -2123,37 +2127,14 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task=task,
|
||||
message=(
|
||||
'RPA upload success requires success_evidence '
|
||||
'(kind whitelist, selector, observed_at, filename matching artifact, '
|
||||
'page_url, dom_snippet+dom_sha256)'
|
||||
'(kind whitelist, selector, observed_at, filename matching artifact and page_url)'
|
||||
),
|
||||
data=serialize_task_for_tool(task),
|
||||
)
|
||||
# [BE-05] 结构化证据必须落 FileAsset;资产失败不得判定上传成功。
|
||||
evidence_asset_id = _persist_rpa_success_evidence_asset(
|
||||
task=task,
|
||||
attempt=attempt,
|
||||
success_evidence=success_evidence,
|
||||
)
|
||||
if evidence_asset_id is None:
|
||||
return tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
message=(
|
||||
'RPA upload success requires persisted evidence asset '
|
||||
'(DOM/screenshot FileAsset); status remains recoverable'
|
||||
),
|
||||
data={
|
||||
**serialize_task_for_tool(task),
|
||||
'upload_evidence_persist_failed': True,
|
||||
},
|
||||
)
|
||||
if _persist_rpa_success_evidence_asset(task=task, attempt=attempt, success_evidence=success_evidence) is None:
|
||||
return tool_response(status='failed', task=task, message='RPA upload success requires persisted internal audit asset', data=serialize_task_for_tool(task))
|
||||
if hasattr(attempt, 'success_evidence_json'):
|
||||
# 回调体中的 base64 已在 persist 时 pop;落库保留 snippet/哈希/asset 引用。
|
||||
attempt.success_evidence_json = {
|
||||
key: value
|
||||
for key, value in dict(success_evidence).items()
|
||||
if key != 'screenshot_base64'
|
||||
}
|
||||
attempt.success_evidence_json = {key: value for key, value in dict(success_evidence).items() if key != 'screenshot_base64'}
|
||||
try:
|
||||
completed = complete_attempt(
|
||||
attempt, success=success, callback_id=str(payload.get('callback_id') or f'rpa:{attempt.id}'),
|
||||
|
||||
@@ -22,6 +22,7 @@ from app.services.shipping_notice.generic_order_parser import (
|
||||
parse_generic_orders,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_route_contract import GENERIC_GATE_POLICY_VERSION
|
||||
from app.services.shipping_notice.generic_parse_plan import validate_generic_parse_plan
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -49,6 +50,9 @@ def evaluate_generic_extraction_gate(
|
||||
schema: dict[str, Any],
|
||||
intake: dict[str, Any],
|
||||
unit: Any,
|
||||
parse_plan: dict[str, Any] | None = None,
|
||||
layout_snapshot: dict[str, Any] | None = None,
|
||||
require_parse_plan: bool = False,
|
||||
) -> GenericGateResult:
|
||||
"""
|
||||
执行通用解析并评估完整性门禁;fail-closed 于未映射列、未知行、多 PO/客户、续行与必填字段缺失。
|
||||
@@ -68,13 +72,28 @@ def evaluate_generic_extraction_gate(
|
||||
Returns:
|
||||
GenericGateResult;passed 为 True 时 parse_result.orders 非空。
|
||||
"""
|
||||
completeness = build_generic_completeness_report(candidates)
|
||||
# 生产工作流必须传入冻结 Plan;保留无 Plan 参数的纯函数调用,供已有诊断和
|
||||
# 单元测试直接评估候选完整性,不把它接入自动建单路径。
|
||||
plan_validation = None
|
||||
effective_candidates = candidates
|
||||
if parse_plan is not None or require_parse_plan:
|
||||
plan_validation = validate_generic_parse_plan(
|
||||
plan=parse_plan,
|
||||
schema_checksum=str(schema.get('checksum') or ''),
|
||||
layout_snapshot=layout_snapshot or {},
|
||||
runtime_candidates=candidates,
|
||||
)
|
||||
effective_candidates = plan_validation.candidates
|
||||
completeness = build_generic_completeness_report(effective_candidates)
|
||||
gate_codes: list[str] = []
|
||||
stable_codes: list[str] = []
|
||||
|
||||
if plan_validation is not None and not plan_validation.passed:
|
||||
gate_codes.extend(plan_validation.reason_codes)
|
||||
|
||||
gate_codes.extend(_completeness_gate_codes(completeness))
|
||||
parse_result = parse_generic_orders(
|
||||
candidates=candidates,
|
||||
candidates=effective_candidates,
|
||||
definition=definition,
|
||||
schema=schema,
|
||||
intake=intake,
|
||||
@@ -83,7 +102,7 @@ def evaluate_generic_extraction_gate(
|
||||
if parse_result.reason_code:
|
||||
stable_codes.append(parse_result.reason_code)
|
||||
|
||||
customer_values = collect_customer_field_values(candidates, definition=definition)
|
||||
customer_values = collect_customer_field_values(effective_candidates, definition=definition)
|
||||
if len(customer_values) > 1:
|
||||
gate_codes.append('multiple_customer')
|
||||
stable_codes.append('generic_gate_blocked')
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"""
|
||||
services/shipping_notice/generic_parse_plan.py
|
||||
|
||||
用途:将自动标注的 layout_schema_candidates 编译为 Run 冻结的通用解析计划。
|
||||
依赖:冻结 Schema、Layout candidate 与 schema_mapping 的 cell 级证据。
|
||||
逻辑:候选映射只可作为 Plan 输入;生产通用解析必须先校验 Plan 的 Schema、Layout、
|
||||
候选和字段证据身份,不能直接把运行时候选当作业务事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
|
||||
GENERIC_PARSE_PLAN_VERSION = 'generic_parse_plan.v1'
|
||||
|
||||
|
||||
def _checksum(payload: Any) -> str:
|
||||
"""生成稳定 JSON checksum;Plan 身份不得依赖字典插入顺序。"""
|
||||
encoded = json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
|
||||
return hashlib.sha256(encoded.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def layout_checksum(layout_snapshot: dict[str, Any]) -> str | None:
|
||||
"""提取结构 Layout 身份;按需坐标补全不应改变已冻结的版面身份。"""
|
||||
candidate = layout_snapshot.get('layout_candidate') if isinstance(layout_snapshot, dict) else None
|
||||
return _checksum(candidate) if isinstance(candidate, dict) else None
|
||||
|
||||
|
||||
def _field_evidence_errors(candidates: list[dict[str, Any]]) -> list[str]:
|
||||
"""校验每个将进入订单的字段都能回溯到冻结 Layout cell 证据。"""
|
||||
errors: list[str] = []
|
||||
for table_index, table in enumerate(candidates):
|
||||
if not isinstance(table, dict):
|
||||
errors.append(f'table:{table_index}:invalid')
|
||||
continue
|
||||
for row in table.get('rows') or []:
|
||||
if not isinstance(row, dict) or str(row.get('role') or '') != 'data':
|
||||
continue
|
||||
for field in row.get('fields') or []:
|
||||
if not isinstance(field, dict) or field.get('value') in (None, ''):
|
||||
continue
|
||||
if not field.get('field_id'):
|
||||
errors.append(f'table:{table_index}:field_id_missing')
|
||||
if not field.get('evidence_ref') or not field.get('cell_id'):
|
||||
errors.append(f'table:{table_index}:field_evidence_missing')
|
||||
return sorted(set(errors))
|
||||
|
||||
|
||||
def compile_generic_parse_plan(
|
||||
*,
|
||||
candidates: list[dict[str, Any]],
|
||||
schema_checksum: str,
|
||||
layout_snapshot: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将自动标注候选编译为可冻结 Parse Plan。
|
||||
|
||||
自动标注本身不具有生产资格。该函数只记录候选的输入身份和字段证据,后续仍由
|
||||
generic_order_gate 检查表/行完整性、必填字段和业务冲突。
|
||||
"""
|
||||
# Plan 冻结前仍在同一 Worker 内构建订单;不得借深拷贝把 Decimal/date 等
|
||||
# 业务值提前变成字符串,JSON 落库阶段由 Run 的统一冻结器处理。
|
||||
copied = deepcopy(candidates if isinstance(candidates, list) else [])
|
||||
source_statuses = [
|
||||
str(item.get('mapping_status') or 'candidate')
|
||||
for item in copied if isinstance(item, dict)
|
||||
]
|
||||
errors = _field_evidence_errors(copied)
|
||||
if not str(schema_checksum or '').strip():
|
||||
errors.append('schema_checksum_missing')
|
||||
resolved_layout_checksum = layout_checksum(layout_snapshot)
|
||||
if not resolved_layout_checksum:
|
||||
errors.append('layout_checksum_missing')
|
||||
if any(status not in {'accepted', 'candidate'} for status in source_statuses):
|
||||
errors.append('mapping_status_unqualified')
|
||||
payload = {
|
||||
'version': GENERIC_PARSE_PLAN_VERSION,
|
||||
'schema_checksum': str(schema_checksum or ''),
|
||||
'layout_checksum': resolved_layout_checksum,
|
||||
'candidates': copied,
|
||||
'candidate_checksum': _checksum(copied),
|
||||
'mapping_decisions': [{
|
||||
'page_no': item.get('page_no'), 'table_id': item.get('table_id'),
|
||||
'source_mapping_status': str(item.get('mapping_status') or 'candidate'),
|
||||
'decision': 'auto_qualified' if str(item.get('mapping_status') or 'candidate') in {'accepted', 'candidate'} else 'rejected',
|
||||
} for item in copied if isinstance(item, dict)],
|
||||
'evidence_errors': sorted(set(errors)),
|
||||
}
|
||||
payload['status'] = 'qualified' if not payload['evidence_errors'] else 'rejected'
|
||||
payload['checksum'] = _checksum(payload)
|
||||
return payload
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class GenericParsePlanValidation:
|
||||
"""生产 Gate 使用的 Parse Plan 校验结论。"""
|
||||
|
||||
passed: bool
|
||||
reason_codes: list[str]
|
||||
candidates: list[dict[str, Any]]
|
||||
|
||||
|
||||
def validate_generic_parse_plan(
|
||||
*,
|
||||
plan: Any,
|
||||
schema_checksum: str,
|
||||
layout_snapshot: dict[str, Any],
|
||||
runtime_candidates: list[dict[str, Any]] | None = None,
|
||||
) -> GenericParsePlanValidation:
|
||||
"""验证冻结 Plan 未被 Schema、Layout 或候选映射漂移污染。"""
|
||||
if not isinstance(plan, dict):
|
||||
return GenericParsePlanValidation(False, ['generic_parse_plan_missing'], [])
|
||||
candidates = plan.get('candidates') if isinstance(plan.get('candidates'), list) else []
|
||||
reasons: list[str] = []
|
||||
if str(plan.get('version') or '') != GENERIC_PARSE_PLAN_VERSION:
|
||||
reasons.append('generic_parse_plan_version_invalid')
|
||||
payload = {key: value for key, value in plan.items() if key != 'checksum'}
|
||||
if str(plan.get('checksum') or '') != _checksum(payload):
|
||||
reasons.append('generic_parse_plan_checksum_invalid')
|
||||
if str(plan.get('status') or '') != 'qualified':
|
||||
reasons.append('generic_parse_plan_unqualified')
|
||||
if str(plan.get('schema_checksum') or '') != str(schema_checksum or ''):
|
||||
reasons.append('generic_parse_plan_schema_changed')
|
||||
if str(plan.get('layout_checksum') or '') != str(layout_checksum(layout_snapshot) or ''):
|
||||
reasons.append('generic_parse_plan_layout_changed')
|
||||
if str(plan.get('candidate_checksum') or '') != _checksum(candidates):
|
||||
reasons.append('generic_parse_plan_candidate_changed')
|
||||
if runtime_candidates is not None and _checksum(runtime_candidates) != str(plan.get('candidate_checksum') or ''):
|
||||
reasons.append('generic_parse_plan_runtime_candidate_changed')
|
||||
if plan.get('evidence_errors'):
|
||||
reasons.append('generic_parse_plan_evidence_missing')
|
||||
return GenericParsePlanValidation(not reasons, sorted(set(reasons)), candidates)
|
||||
@@ -172,6 +172,7 @@ def serialize_intake(
|
||||
*,
|
||||
asset: FileAsset | None = None,
|
||||
include_parse_texts: bool = False,
|
||||
include_candidate_details: bool = True,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
对外序列化接入记录(含业务摘要、Document/Candidate 与重复检测)。
|
||||
@@ -179,6 +180,8 @@ def serialize_intake(
|
||||
Args:
|
||||
include_parse_texts: True 时返回 structured 中的附件全文/正文(详情接口),
|
||||
并附带 documents 全文;False 时返回瘦身 parse_summary 与精简 documents/candidates。
|
||||
include_candidate_details: False 时仅返回恢复输入状态所需的 Candidate 字段,
|
||||
避免活跃列表传输 evidence / field_adjudication 等重型审核数据。
|
||||
"""
|
||||
from app.services.shipping_notice.document_candidate_persist import (
|
||||
list_intake_candidates,
|
||||
@@ -198,7 +201,10 @@ def serialize_intake(
|
||||
}
|
||||
parse_summary = structured if include_parse_texts else _lean_parse_summary(structured)
|
||||
documents = list_intake_documents(int(intake.id), include_text=include_parse_texts)
|
||||
candidates = list_intake_candidates(int(intake.id))
|
||||
candidates = list_intake_candidates(
|
||||
int(intake.id),
|
||||
include_details=include_candidate_details,
|
||||
)
|
||||
layout_summary = _serialize_intake_layout_summary(int(intake.id))
|
||||
payload: dict[str, Any] = {
|
||||
'intake_no': intake.intake_no,
|
||||
@@ -571,7 +577,14 @@ def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str |
|
||||
if conv:
|
||||
query = query.filter(ShippingOrderIntake.conversation_id == conv)
|
||||
rows = query.order_by(ShippingOrderIntake.created_at.desc()).limit(50).all()
|
||||
return [serialize_intake(intake, asset=asset) for intake, asset in rows]
|
||||
return [
|
||||
serialize_intake(
|
||||
intake,
|
||||
asset=asset,
|
||||
include_candidate_details=False,
|
||||
)
|
||||
for intake, asset in rows
|
||||
]
|
||||
|
||||
|
||||
def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str, Any]]:
|
||||
@@ -588,7 +601,14 @@ def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str
|
||||
)
|
||||
.all()
|
||||
)
|
||||
return [serialize_intake(intake, asset=asset) for intake, asset in rows]
|
||||
return [
|
||||
serialize_intake(
|
||||
intake,
|
||||
asset=asset,
|
||||
include_candidate_details=False,
|
||||
)
|
||||
for intake, asset in rows
|
||||
]
|
||||
|
||||
|
||||
def retry_intake_parse(*, user_id: int, intake_no: str) -> dict[str, Any]:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
services/shipping_notice/inventory_file_store.py
|
||||
|
||||
用途:管理货代发货批次级库存快照文件、任务 link 与解析结果投影。
|
||||
用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影。
|
||||
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。
|
||||
逻辑:inventory_workflow 上传或解析库存时写入库存快照;fulfillment_workflow 匹配前从 link 解析当前任务库存。
|
||||
"""
|
||||
@@ -30,8 +30,6 @@ from app.services.shipping_notice.inventory_source_gate import (
|
||||
task_inventory_identity,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
|
||||
from app.services.shipping_notice.query_service import list_sorted_batch_tasks
|
||||
|
||||
def _can_relink_inventory(task: ShippingNotice) -> bool:
|
||||
"""判断任务是否允许被新的批次库存快照影响;终态任务不能回退。"""
|
||||
return str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} \
|
||||
@@ -228,13 +226,13 @@ def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) ->
|
||||
)
|
||||
|
||||
|
||||
def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile:
|
||||
def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> ShippingInventoryFile:
|
||||
"""
|
||||
保存库存 Excel 并创建批次级库存快照。
|
||||
保存库存 Excel 并创建任务级库存快照。
|
||||
|
||||
【AI 触发时机】:用户为一批发货需求上传库存快照时调用;有 batch 时默认 link 本批全部票。
|
||||
【AI 触发时机】:用户为当前发货任务上传库存快照时调用。
|
||||
核心逻辑:文件必须通过库存站点 published 解析方案的结构门禁并完成确定性解析;
|
||||
快照须携带任务正式库存源身份,批次 link 仅覆盖与上传票库存源一致的可重链任务。
|
||||
快照须携带任务正式库存源身份,只绑定当前任务。
|
||||
"""
|
||||
if not is_inventory_source_stable(task):
|
||||
raise AppError(
|
||||
@@ -360,7 +358,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh
|
||||
)
|
||||
raise AppError(
|
||||
code="SHIPPING.INVENTORY_IDENTITY_MISMATCH",
|
||||
message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝批次绑定",
|
||||
message=f"任务 {item.task_no} 与库存快照身份不一致,已拒绝快照绑定",
|
||||
http_status=409,
|
||||
)
|
||||
created_links.append(link)
|
||||
|
||||
@@ -18,13 +18,10 @@ from app.services.shipping_notice.constants import (
|
||||
CP_INVENTORY_SOURCE_REVIEW,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
save_batch_inventory_upload,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_file_store import save_task_inventory_upload
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_task_by_ref,
|
||||
resolve_task_from_payload,
|
||||
serialize_batch_for_tool,
|
||||
serialize_task_for_tool,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_gate import task_reservation_gate_issues
|
||||
@@ -176,7 +173,7 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
detail=t("workflow.inventory.uploading_detail", lang=lang).format(filename=filename),
|
||||
)
|
||||
db.session.flush()
|
||||
inv_file = save_batch_inventory_upload(task, upload)
|
||||
inv_file = save_task_inventory_upload(task, upload)
|
||||
inventory_lines = [
|
||||
item for item in (inv_file.inventory_lines_json or []) if isinstance(item, dict)
|
||||
]
|
||||
@@ -220,7 +217,6 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
|
||||
{
|
||||
"inventory_file_no": inv_file.inventory_file_no,
|
||||
"share_mode": inv_file.share_mode,
|
||||
"batch_no": None,
|
||||
},
|
||||
)
|
||||
return inventory_loaded_response(
|
||||
|
||||
@@ -1,297 +0,0 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/legacy_stp_job_admin_service.py
|
||||
|
||||
用途:Phase 5-1 —— 管理员历史 STP Job 面板的只读投影服务(928/929 运维面板专用)。
|
||||
依赖:models.job.Job、JobType(若有)、ShippingOrderReviewCase。
|
||||
逻辑:
|
||||
1. list_admin_legacy_stp_jobs —— 按 domain=shipping_notice + job_type=shipping_stp_auto_create
|
||||
+ status IN {failed,dead} 分页返回;支持筛选 case_no / q / error_code / created_from / created_to。
|
||||
2. get_admin_legacy_stp_job —— 单条 Job 详情 + 关联 Review Case(若可通过 reference_key==case_no 回链)。
|
||||
禁止事项(严格 fail-closed):
|
||||
• 不允许写任何数据(禁 Job.status 修改,禁 db.session.commit/add/flush 等)。
|
||||
• 不输出敏感字段(result_json 中若含 token/password 自动脱敏)。
|
||||
• 所有接口仅 allow_admin,路由层 require_admin 再守门一道。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import and_, or_
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
# 失败 / 死 Job 白名单:历史 928/929 仅针对 shipping_stp_auto_create
|
||||
_LEGACY_DOMAIN = 'shipping_notice'
|
||||
_LEGACY_JOB_TYPES: frozenset[str] = frozenset({
|
||||
'shipping_stp_auto_create',
|
||||
})
|
||||
_LEGACY_STATUSES: frozenset[str] = frozenset({'failed', 'dead'})
|
||||
|
||||
# 脱敏正则(非常粗:防止 secret/password/token/key 等明文进入管理面板)
|
||||
_SENSITIVE_KEY_RE = re.compile(
|
||||
r'(password|passwd|secret|token|api[_-]?key|credential|authorization)',
|
||||
flags=re.IGNORECASE,
|
||||
)
|
||||
|
||||
|
||||
def _mask_sensitive(obj: Any) -> Any:
|
||||
"""递归递归脱敏 dict/list 中疑似密钥字段的值(fail-safe,不抛错)。"""
|
||||
if isinstance(obj, dict):
|
||||
out: dict[str, Any] = {}
|
||||
for k, v in obj.items():
|
||||
if isinstance(k, str) and _SENSITIVE_KEY_RE.search(k):
|
||||
out[k] = '***MASKED***'
|
||||
else:
|
||||
out[k] = _mask_sensitive(v)
|
||||
return out
|
||||
if isinstance(obj, list):
|
||||
return [_mask_sensitive(i) for i in obj]
|
||||
if isinstance(obj, tuple):
|
||||
return tuple(_mask_sensitive(i) for i in obj)
|
||||
return obj
|
||||
|
||||
|
||||
def _serialize_job_row(job) -> dict[str, Any]:
|
||||
"""把 Job ORM 行 → 管理员摘要 JSON(只读投影)。"""
|
||||
result_json = dict(job.result_json or {}) if isinstance(job.result_json, dict) else {}
|
||||
payload_json = dict(job.payload_json or {}) if isinstance(job.payload_json, dict) else {}
|
||||
blocking_reason = (
|
||||
result_json.get('blocking_reason')
|
||||
or result_json.get('reason_code')
|
||||
or result_json.get('error_code')
|
||||
or None
|
||||
)
|
||||
if isinstance(blocking_reason, dict):
|
||||
blocking_reason = blocking_reason.get('code') if isinstance(blocking_reason.get('code'), str) else None
|
||||
return {
|
||||
'job_id': int(job.id),
|
||||
'domain': str(job.domain or ''),
|
||||
'job_type': str(job.job_type or ''),
|
||||
'status': str(job.status or ''),
|
||||
'business_ref': str(job.business_ref or ''),
|
||||
'reference_key': str(getattr(job, 'reference_key', None) or ''), # 兼容旧 Job
|
||||
'case_no': (
|
||||
str(getattr(job, 'reference_key', None) or '') or
|
||||
str(payload_json.get('case_no') or '') or None
|
||||
),
|
||||
'priority': int(job.priority or 0),
|
||||
'attempts': int(job.attempts or 0),
|
||||
'max_attempts': int(job.max_attempts or 0),
|
||||
'message': str(job.message or '') or None,
|
||||
'error_message': str(job.error_message or '') or None,
|
||||
'error_code': str(result_json.get('error_code') or ''),
|
||||
'blocking_reason': (str(blocking_reason) if blocking_reason else None),
|
||||
'retryable': bool(result_json.get('retryable')) if result_json.get('retryable') is not None else None,
|
||||
'next_action': result_json.get('next_action'),
|
||||
'retry_of_job_id': (int(job.retry_of_job_id) if job.retry_of_job_id else None),
|
||||
'created_by_id': (int(job.created_by_id) if job.created_by_id else None),
|
||||
'result_json_masked': _mask_sensitive(result_json),
|
||||
'payload_json_masked': _mask_sensitive(payload_json),
|
||||
'created_at': str(job.created_at.isoformat()) if isinstance(job.created_at, datetime) else None,
|
||||
'updated_at': str(job.updated_at.isoformat()) if isinstance(job.updated_at, datetime) else None,
|
||||
'started_at': str(job.started_at.isoformat()) if isinstance(job.started_at, datetime) else None,
|
||||
'finished_at': str(job.finished_at.isoformat()) if isinstance(job.finished_at, datetime) else None,
|
||||
}
|
||||
|
||||
|
||||
def _parse_iso_dt(value: str | None, *, field: str):
|
||||
"""解析可选 ISO 日期时间;抛 ValidationError。"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
if value in (None, ''):
|
||||
return None
|
||||
try:
|
||||
text = str(value).strip()
|
||||
if text.endswith('Z'):
|
||||
text = text[:-1] + '+00:00'
|
||||
return datetime.fromisoformat(text)
|
||||
except ValueError as exc:
|
||||
raise ValidationError(f'{field} must be ISO datetime (YYYY-MM-DDTHH:MM:SS)') from exc
|
||||
|
||||
|
||||
def list_admin_legacy_stp_jobs(
|
||||
*,
|
||||
page: int = 1,
|
||||
page_size: int = 25,
|
||||
status: str | None = None,
|
||||
job_type: str | None = None,
|
||||
q: str | None = None,
|
||||
case_no: str | None = None,
|
||||
error_code: str | None = None,
|
||||
blocking_reason: str | None = None,
|
||||
created_from: str | None = None,
|
||||
created_to: str | None = None,
|
||||
sort: str = '-created_at',
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
管理员只读列表:domain=shipping_notice + job_type=shipping_stp_auto_create + status IN {failed, dead}。
|
||||
用于运维面板快速定位历史 928/929 这类失败死 Job。
|
||||
"""
|
||||
from app.core.errors import ValidationError
|
||||
from app.models.job import Job
|
||||
from app import db # type: ignore
|
||||
|
||||
if not isinstance(page, int) or page < 1:
|
||||
raise ValidationError('page must be positive integer')
|
||||
if not isinstance(page_size, int) or not 1 <= page_size <= 100:
|
||||
raise ValidationError('page_size must be between 1 and 100')
|
||||
if status and str(status) not in _LEGACY_STATUSES:
|
||||
raise ValidationError(f'status must be one of: {sorted(_LEGACY_STATUSES)}')
|
||||
if job_type and str(job_type) not in _LEGACY_JOB_TYPES:
|
||||
raise ValidationError(f'job_type must be one of: {sorted(_LEGACY_JOB_TYPES)}')
|
||||
|
||||
created_from_dt = _parse_iso_dt(created_from, field='created_from')
|
||||
created_to_dt = _parse_iso_dt(created_to, field='created_to')
|
||||
|
||||
# 只拿失败/死 STP Job
|
||||
where = [
|
||||
Job.domain == _LEGACY_DOMAIN,
|
||||
Job.job_type.in_(list(_LEGACY_JOB_TYPES)),
|
||||
Job.status.in_(list(_LEGACY_STATUSES)),
|
||||
]
|
||||
if status:
|
||||
where.append(Job.status == str(status))
|
||||
if job_type:
|
||||
where.append(Job.job_type == str(job_type))
|
||||
if case_no:
|
||||
case_no_s = str(case_no).strip()
|
||||
where.append(or_(
|
||||
getattr(Job, 'reference_key', None) == case_no_s
|
||||
if hasattr(Job, 'reference_key')
|
||||
else False,
|
||||
# 兼容旧模型:从 payload_json->case_no 查(JSON 跨库差异大,仅包含匹配)
|
||||
Job.payload_json.contains({'case_no': case_no_s}),
|
||||
))
|
||||
if error_code:
|
||||
where.append(Job.result_json.contains({'error_code': str(error_code).strip()}))
|
||||
if blocking_reason:
|
||||
br = str(blocking_reason).strip()
|
||||
where.append(or_(
|
||||
Job.result_json.contains({'blocking_reason': br}),
|
||||
Job.result_json.contains({'reason_code': br}),
|
||||
))
|
||||
if created_from_dt is not None:
|
||||
where.append(Job.created_at >= created_from_dt)
|
||||
if created_to_dt is not None:
|
||||
where.append(Job.created_at <= created_to_dt)
|
||||
if q and str(q).strip():
|
||||
qs = f'%{str(q).strip()}%'
|
||||
where.append(or_(
|
||||
Job.business_ref.ilike(qs),
|
||||
Job.message.ilike(qs),
|
||||
Job.error_message.ilike(qs),
|
||||
))
|
||||
|
||||
# 排序
|
||||
sort_exprs = []
|
||||
for raw in str(sort or '-created_at').split(','):
|
||||
s = raw.strip()
|
||||
if not s:
|
||||
continue
|
||||
descending = s.startswith('-')
|
||||
key = s[1:] if descending else s
|
||||
if key == 'created_at':
|
||||
expr = Job.created_at.desc() if descending else Job.created_at.asc()
|
||||
elif key == 'updated_at':
|
||||
expr = Job.updated_at.desc() if descending else Job.updated_at.asc()
|
||||
elif key == 'id':
|
||||
expr = Job.id.desc() if descending else Job.id.asc()
|
||||
elif key == 'attempts':
|
||||
expr = Job.attempts.desc() if descending else Job.attempts.asc()
|
||||
else:
|
||||
continue
|
||||
sort_exprs.append(expr)
|
||||
if not sort_exprs:
|
||||
sort_exprs = [Job.created_at.desc()]
|
||||
|
||||
stmt = db.select(Job).where(and_(*where)).order_by(*sort_exprs)
|
||||
total = len(db.session.scalars(db.select(Job.id).where(and_(*where))).all())
|
||||
items = db.session.scalars(
|
||||
stmt.offset((int(page) - 1) * int(page_size)).limit(int(page_size)),
|
||||
).all()
|
||||
return {
|
||||
'items': [_serialize_job_row(j) for j in items],
|
||||
'pagination': {
|
||||
'page': int(page),
|
||||
'page_size': int(page_size),
|
||||
'total': int(total),
|
||||
'total_pages': ((int(total) + int(page_size) - 1) // int(page_size)) if total > 0 else 0,
|
||||
},
|
||||
'filters': {
|
||||
'domain': _LEGACY_DOMAIN,
|
||||
'job_types': sorted(_LEGACY_JOB_TYPES),
|
||||
'statuses': sorted(_LEGACY_STATUSES),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def get_admin_legacy_stp_job(job_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
管理员单条历史 STP Job 详情:返回 Job 投影 + 回链 Review Case(若 reference_key==case_no 存在)。
|
||||
仅允许失败/死 Job:若 Job 是 queued/running → 抛 ValidationError(避免管理员误对活跃 Job 做 replay)。
|
||||
"""
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models.job import Job
|
||||
from app.models.shipping.shipping_order_review_case import ShippingOrderReviewCase
|
||||
|
||||
job = db.session.get(Job, int(job_id))
|
||||
if job is None:
|
||||
raise NotFoundError(f'legacy job not found: {job_id}', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
|
||||
if str(job.domain or '') != _LEGACY_DOMAIN:
|
||||
raise ValidationError(f'legacy job must be domain={_LEGACY_DOMAIN}')
|
||||
if str(job.job_type or '') not in _LEGACY_JOB_TYPES:
|
||||
raise ValidationError(f'legacy job must be job_type in {sorted(_LEGACY_JOB_TYPES)}')
|
||||
if str(job.status or '') not in _LEGACY_STATUSES:
|
||||
raise ValidationError(
|
||||
f'legacy job must be status in {sorted(_LEGACY_STATUSES)} (current={job.status})',
|
||||
code='SHIPPING.RECONCILE_INVALID_USER_ACTION',
|
||||
)
|
||||
job_row = _serialize_job_row(job)
|
||||
|
||||
# 回链 Review Case(只读:若能通过 reference_key==case_no 找得到)
|
||||
case_no = (
|
||||
str(getattr(job, 'reference_key', None) or '')
|
||||
or str((job.payload_json or {}).get('case_no') or '')
|
||||
or None
|
||||
)
|
||||
case_row: dict[str, Any] | None = None
|
||||
if case_no:
|
||||
case_obj = (
|
||||
ShippingOrderReviewCase.query
|
||||
.filter_by(case_no=str(case_no).strip())
|
||||
.order_by(ShippingOrderReviewCase.id.desc())
|
||||
.first()
|
||||
)
|
||||
if case_obj is not None:
|
||||
case_row = {
|
||||
'case_id': int(case_obj.id),
|
||||
'case_no': str(case_obj.case_no or ''),
|
||||
'status': str(case_obj.status or ''),
|
||||
'candidate_id': int(case_obj.candidate_id) if case_obj.candidate_id else None,
|
||||
'confirmed_task_id': int(case_obj.confirmed_task_id) if case_obj.confirmed_task_id else None,
|
||||
'document_id': int(case_obj.document_id) if case_obj.document_id else None,
|
||||
'owner_user_id': int(case_obj.owner_user_id) if case_obj.owner_user_id else None,
|
||||
'created_at': str(case_obj.created_at.isoformat()) if getattr(case_obj, 'created_at', None) else None,
|
||||
'updated_at': str(case_obj.updated_at.isoformat()) if getattr(case_obj, 'updated_at', None) else None,
|
||||
}
|
||||
return {
|
||||
'job': job_row,
|
||||
'case': case_row,
|
||||
'replay_plan': {
|
||||
'supported': True,
|
||||
'recommended_user_action': (
|
||||
'force_create'
|
||||
if case_row and str(case_row.get('status') or '') in {'draft', 'ready', 'unreviewed'}
|
||||
else 'create_revision'
|
||||
),
|
||||
'needs_replay_mode': bool(case_row and job_row.get('case_no') != case_row.get('case_no')),
|
||||
'reconcile_and_progress_endpoint': (
|
||||
f'/workspace/shipping-notice/order-review-cases/{case_no}/reconcile-and-progress'
|
||||
if case_no else None
|
||||
),
|
||||
},
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
"""
|
||||
services/shipping_notice/legacy_supplement_conflict_reassessment_service.py
|
||||
|
||||
用途:将历史邮件正文补充冲突升级为可展示、可追溯的统一 Finding,并重算 Candidate 资格。
|
||||
依赖:ShippingOrderCandidate/Run、candidate_qualification_service、fulfillment_audit。
|
||||
逻辑:历史 `{field, reason}` 没有双方值或证据,不能猜测为已解决;本服务仅将其转为
|
||||
`supplement_conflict_evidence_insufficient`,保留 blocking 门禁并给出重新识别恢复入口。
|
||||
已含 conflict_key 的新 Finding 不改写;真实值比较仍由冻结输入的新解析链负责。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderProcessingPlan,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderProcessingUnit,
|
||||
)
|
||||
from app.services.shipping_notice.candidate_qualification_service import (
|
||||
recalculate_candidate_qualification,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
|
||||
|
||||
|
||||
_LEGACY_REASON = 'supplement_field_conflict'
|
||||
_EVIDENCE_GAP_REASON = 'supplement_conflict_evidence_insufficient'
|
||||
|
||||
|
||||
def _legacy_finding_key(item: dict[str, Any]) -> str:
|
||||
"""为无法复原证据的旧 Finding 生成稳定键,避免继续以无键记录阻断。"""
|
||||
field = str(item.get('field') or 'unknown_field').strip() or 'unknown_field'
|
||||
try:
|
||||
line_index = int(item.get('line_index')) if item.get('line_index') is not None else -1
|
||||
except (TypeError, ValueError):
|
||||
line_index = -1
|
||||
return f'{line_index}:{field}'
|
||||
|
||||
|
||||
def is_legacy_supplement_conflict(item: Any) -> bool:
|
||||
"""判断记录是否是没有稳定裁决身份与双方证据的历史正文补充冲突。"""
|
||||
return (
|
||||
isinstance(item, dict)
|
||||
and str(item.get('reason') or '').strip() == _LEGACY_REASON
|
||||
and not str(item.get('conflict_key') or '').strip()
|
||||
)
|
||||
|
||||
|
||||
def upgrade_legacy_supplement_conflicts(conflicts: Any) -> tuple[list[Any], int]:
|
||||
"""
|
||||
将旧简略冲突升级为统一证据缺失 Finding。
|
||||
|
||||
核心逻辑:旧记录仅有字段与原因,缺失 PDF/EML 原值、document_id、evidence_ref,
|
||||
无法安全裁决或判定为格式等价;因此保持 fail-closed,但使 Case 显示明确恢复动作。
|
||||
|
||||
Returns:
|
||||
(升级后的冲突列表, 本次升级数量)。
|
||||
"""
|
||||
source = list(conflicts or []) if isinstance(conflicts, list) else []
|
||||
upgraded: list[Any] = []
|
||||
changed = 0
|
||||
seen_keys: set[str] = set()
|
||||
for item in source:
|
||||
if not is_legacy_supplement_conflict(item):
|
||||
upgraded.append(item)
|
||||
if isinstance(item, dict):
|
||||
key = str(item.get('conflict_key') or '').strip()
|
||||
if key:
|
||||
seen_keys.add(key)
|
||||
continue
|
||||
key = _legacy_finding_key(item)
|
||||
if key in seen_keys:
|
||||
changed += 1
|
||||
continue
|
||||
seen_keys.add(key)
|
||||
field = str(item.get('field') or 'unknown_field').strip() or 'unknown_field'
|
||||
try:
|
||||
line_index = int(item.get('line_index')) if item.get('line_index') is not None else -1
|
||||
except (TypeError, ValueError):
|
||||
line_index = -1
|
||||
upgraded.append({
|
||||
'conflict_key': key,
|
||||
'severity': 'blocking',
|
||||
'reason': _EVIDENCE_GAP_REASON,
|
||||
'resolution_status': 'unresolved',
|
||||
'field': field,
|
||||
'scope': str(item.get('scope') or 'unscoped'),
|
||||
'line_index': line_index if line_index >= 0 else None,
|
||||
'values': [],
|
||||
'sources': [],
|
||||
'rule_version': 'legacy-supplement-conflict.v1',
|
||||
'legacy_reason': _LEGACY_REASON,
|
||||
'recovery_action': 'reparse_current_pdf',
|
||||
})
|
||||
changed += 1
|
||||
return upgraded, changed
|
||||
|
||||
|
||||
def _without_legacy_supplement_conflicts(conflicts: Any) -> list[Any]:
|
||||
"""去除待重建的旧 Finding,保留其他解析/业务门禁。"""
|
||||
return [
|
||||
item for item in (conflicts or [])
|
||||
if not is_legacy_supplement_conflict(item)
|
||||
] if isinstance(conflicts, list) else []
|
||||
|
||||
|
||||
def _supplement_findings(conflicts: Any) -> list[dict[str, Any]]:
|
||||
"""从重算订单结果读取当前正文补充 Finding,不借用其他门禁事实。"""
|
||||
return [
|
||||
item for item in (conflicts or [])
|
||||
if isinstance(item, dict)
|
||||
and str(item.get('reason') or '').strip() == _LEGACY_REASON
|
||||
] if isinstance(conflicts, list) else []
|
||||
|
||||
|
||||
def reassess_legacy_supplement_conflicts_from_frozen_order(
|
||||
*,
|
||||
candidate_conflicts: Any,
|
||||
frozen_order: Any,
|
||||
supplements_by_intake: Any,
|
||||
schema_definition: Any,
|
||||
) -> tuple[list[Any], str, int]:
|
||||
"""
|
||||
使用冻结订单和邮件补充事实按当前合并规则重算旧冲突。
|
||||
|
||||
Returns:
|
||||
(新冲突, rebuilt|evidence_insufficient|not_applicable, 处理的旧记录数)。
|
||||
"""
|
||||
legacy_count = sum(1 for item in (candidate_conflicts or []) if is_legacy_supplement_conflict(item)) \
|
||||
if isinstance(candidate_conflicts, list) else 0
|
||||
if not legacy_count:
|
||||
return list(candidate_conflicts or []) if isinstance(candidate_conflicts, list) else [], 'not_applicable', 0
|
||||
if not (
|
||||
isinstance(frozen_order, dict)
|
||||
and isinstance(supplements_by_intake, dict)
|
||||
and isinstance(schema_definition, dict)
|
||||
and isinstance(schema_definition.get('fields'), list)
|
||||
):
|
||||
upgraded, _ = upgrade_legacy_supplement_conflicts(candidate_conflicts)
|
||||
return upgraded, 'evidence_insufficient', legacy_count
|
||||
replay_order = dict(frozen_order)
|
||||
replay_order['conflicts'] = _without_legacy_supplement_conflicts(replay_order.get('conflicts'))
|
||||
try:
|
||||
rebuilt_order = merge_email_supplements(
|
||||
orders=[replay_order],
|
||||
supplements_by_intake=supplements_by_intake,
|
||||
schema_definition=schema_definition,
|
||||
)[0]
|
||||
except (TypeError, ValueError):
|
||||
upgraded, _ = upgrade_legacy_supplement_conflicts(candidate_conflicts)
|
||||
return upgraded, 'evidence_insufficient', legacy_count
|
||||
# Candidate 的非补充门禁由其自身持有;只用重算结果替换旧正文补充项。
|
||||
preserved = _without_legacy_supplement_conflicts(candidate_conflicts)
|
||||
rebuilt = _supplement_findings(rebuilt_order.get('conflicts'))
|
||||
return [*preserved, *rebuilt], 'rebuilt', legacy_count
|
||||
|
||||
|
||||
def _frozen_reassessment_inputs(
|
||||
*, candidate: ShippingOrderCandidate, run: ShippingOrderProcessingRun | None,
|
||||
) -> tuple[dict[str, Any] | None, dict[int, dict[str, Any]] | None, dict[str, Any] | None]:
|
||||
"""按 Candidate 所属 Unit 定位冻结订单、邮件补充与 Schema;歧义时拒绝猜测。"""
|
||||
if run is None:
|
||||
return None, None, None
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else None
|
||||
supplements = {
|
||||
int(intake.get('intake_id') or 0): supplement
|
||||
for intake in snapshot.get('intakes') or [] if isinstance(intake, dict)
|
||||
for supplement in intake.get('email_supplements') or [] if isinstance(supplement, dict)
|
||||
if int(intake.get('intake_id') or 0) > 0
|
||||
}
|
||||
units = (
|
||||
ShippingOrderProcessingUnit.query
|
||||
.join(ShippingOrderProcessingPlan, ShippingOrderProcessingPlan.id == ShippingOrderProcessingUnit.plan_id)
|
||||
.filter(
|
||||
ShippingOrderProcessingPlan.run_id == int(run.id),
|
||||
ShippingOrderProcessingUnit.document_id == int(candidate.primary_document_id),
|
||||
)
|
||||
.order_by(ShippingOrderProcessingUnit.id.asc())
|
||||
.all()
|
||||
)
|
||||
if len(units) != 1:
|
||||
return None, supplements, definition
|
||||
orders = (units[0].result_json or {}).get('orders') if isinstance(units[0].result_json, dict) else None
|
||||
if not isinstance(orders, list):
|
||||
return None, supplements, definition
|
||||
index = candidate.source_order_index
|
||||
if isinstance(index, int) and 0 <= index < len(orders) and isinstance(orders[index], dict):
|
||||
return dict(orders[index]), supplements, definition
|
||||
exact = [
|
||||
item for item in orders
|
||||
if isinstance(item, dict)
|
||||
and int(item.get('primary_document_id') or 0) == int(candidate.primary_document_id)
|
||||
]
|
||||
return (dict(exact[0]) if len(exact) == 1 else None), supplements, definition
|
||||
|
||||
|
||||
def reassess_legacy_supplement_conflicts(
|
||||
*,
|
||||
actor_id: int,
|
||||
request_id: str | None = None,
|
||||
candidate_no: str | None = None,
|
||||
run_no: str | None = None,
|
||||
include_all: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
对指定范围的旧正文补充冲突执行一次可审计重评估。
|
||||
|
||||
AI 触发时机:仅管理员确认历史数据修复时调用;普通用户保存草稿或读取 Case 不调用。
|
||||
范围必须指定 Candidate、Run,或显式 include_all,避免误触发全量写操作。
|
||||
"""
|
||||
normalized_candidate_no = str(candidate_no or '').strip().upper() or None
|
||||
normalized_run_no = str(run_no or '').strip().upper() or None
|
||||
if not (normalized_candidate_no or normalized_run_no or include_all):
|
||||
raise ValueError('candidate_no, run_no, or include_all is required')
|
||||
|
||||
query = ShippingOrderCandidate.query.filter(ShippingOrderCandidate.is_current_version.is_(True))
|
||||
if normalized_candidate_no:
|
||||
query = query.filter(ShippingOrderCandidate.candidate_no == normalized_candidate_no)
|
||||
if normalized_run_no:
|
||||
query = query.join(
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingOrderProcessingRun.id == ShippingOrderCandidate.order_extraction_run_id,
|
||||
).filter(ShippingOrderProcessingRun.run_no == normalized_run_no)
|
||||
|
||||
report = {
|
||||
'scanned_count': 0,
|
||||
'legacy_conflict_candidate_count': 0,
|
||||
'upgraded_finding_count': 0,
|
||||
'qualification_recalculated_count': 0,
|
||||
'candidate_nos': [],
|
||||
'scope': {
|
||||
'candidate_no': normalized_candidate_no,
|
||||
'run_no': normalized_run_no,
|
||||
'include_all': bool(include_all),
|
||||
},
|
||||
}
|
||||
for candidate in query.with_for_update().all():
|
||||
report['scanned_count'] += 1
|
||||
legacy_count = sum(
|
||||
1 for item in (candidate.conflicts_json or []) if is_legacy_supplement_conflict(item)
|
||||
) if isinstance(candidate.conflicts_json, list) else 0
|
||||
if not legacy_count:
|
||||
continue
|
||||
run = (
|
||||
db.session.get(ShippingOrderProcessingRun, int(candidate.order_extraction_run_id))
|
||||
if candidate.order_extraction_run_id else None
|
||||
)
|
||||
frozen_order, supplements, definition = _frozen_reassessment_inputs(candidate=candidate, run=run)
|
||||
after_conflicts, reassessment_status, changed = reassess_legacy_supplement_conflicts_from_frozen_order(
|
||||
candidate_conflicts=candidate.conflicts_json,
|
||||
frozen_order=frozen_order,
|
||||
supplements_by_intake=supplements,
|
||||
schema_definition=definition,
|
||||
)
|
||||
before = {'legacy_supplement_conflict_count': legacy_count}
|
||||
candidate.conflicts_json = after_conflicts
|
||||
report['legacy_conflict_candidate_count'] += 1
|
||||
if reassessment_status == 'evidence_insufficient':
|
||||
report['upgraded_finding_count'] += changed
|
||||
else:
|
||||
report.setdefault('rebuilt_candidate_count', 0)
|
||||
report['rebuilt_candidate_count'] += 1
|
||||
report['candidate_nos'].append(str(candidate.candidate_no))
|
||||
recalculate_candidate_qualification(
|
||||
candidate=candidate,
|
||||
run=run,
|
||||
evaluated_by_id=actor_id,
|
||||
request_id=request_id,
|
||||
)
|
||||
report['qualification_recalculated_count'] += 1
|
||||
record_fulfillment_audit(
|
||||
event_type='legacy_supplement_conflict_reassessed',
|
||||
aggregate_type='shipping_notice_candidate',
|
||||
aggregate_id=str(candidate.candidate_no),
|
||||
action='reassess_legacy_supplement_conflict',
|
||||
actor_type='admin',
|
||||
actor_id=actor_id,
|
||||
run_no=str(run.run_no) if run is not None else None,
|
||||
reason_code=_EVIDENCE_GAP_REASON,
|
||||
before=before,
|
||||
after={
|
||||
'reassessment_status': reassessment_status,
|
||||
'replaced_legacy_finding_count': changed,
|
||||
'remaining_supplement_finding_count': len(_supplement_findings(after_conflicts)),
|
||||
'recovery_action': 'reparse_current_pdf' if reassessment_status == 'evidence_insufficient' else None,
|
||||
},
|
||||
metadata={'request_id': request_id, 'migration_version': 'legacy-supplement-conflict.v1'},
|
||||
source='legacy_supplement_conflict_reassessment',
|
||||
)
|
||||
report['candidate_nos'].sort()
|
||||
return report
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
services/shipping_notice/lifecycle_projection.py
|
||||
|
||||
用途:为批次进度、任务详情与订单生命周期工作台裁决同一份四阶段业务生命周期。
|
||||
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或历史兜底事实。
|
||||
逻辑:正式 Process Gate 优先,其次是可解释阻断原因;仅无正式事实时才使用旧阶段兜底。
|
||||
用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。
|
||||
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。
|
||||
逻辑:正式 Process Gate 优先,其次是可解释阻断原因;无正式事实时保持未分类。
|
||||
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
|
||||
"""
|
||||
|
||||
@@ -18,6 +18,7 @@ LIFECYCLE_STAGES: tuple[dict[str, str], ...] = (
|
||||
{'code': 'intake_parse', 'label': '接收解析'},
|
||||
{'code': 'order_review', 'label': '订单复核'},
|
||||
{'code': 'fulfillment_prep', 'label': '通知准备'},
|
||||
{'code': 'freight_upload', 'label': '货代上传'},
|
||||
{'code': 'upload_complete', 'label': '通知完成'},
|
||||
)
|
||||
|
||||
@@ -43,26 +44,33 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
|
||||
'inventory_sufficiency': 'fulfillment_prep',
|
||||
'excel_readiness': 'fulfillment_prep',
|
||||
'artifact_generation': 'fulfillment_prep',
|
||||
'freight_upload_rpa': 'upload_complete',
|
||||
'manual_upload_handoff': 'upload_complete',
|
||||
'freight_upload_rpa': 'freight_upload',
|
||||
'manual_upload_handoff': 'freight_upload',
|
||||
}
|
||||
|
||||
# 没有正式 Gate 的历史项才能使用此映射。它必须保持在共享裁决器内,避免各入口漂移。
|
||||
LIFECYCLE_STAGE_RANGES: tuple[tuple[str, set[str]], ...] = (
|
||||
('intake_parse', {'upload_received', 'email_parsing', 'email_adjudicating', 'document_parsing', 'candidate_creating'}),
|
||||
('order_review', {
|
||||
'customer_resolving', 'duplicate_checking', 'order_creating', 'review_required',
|
||||
'waiting_review', 'waiting_human_review', 'waiting_human', 'pre_ot_stp', 'order_review',
|
||||
}),
|
||||
('fulfillment_prep', {
|
||||
'inventory_source_resolving', 'inventory_fetching', 'inventory_fetch', 'inventory_preparation',
|
||||
'inventory_candidates_calculated', 'inventory_candidates_frozen', 'inventory_snapshots_ready',
|
||||
'inventory_matching', 'inventory_match', 'inventory_matched', 'excel_generating',
|
||||
'excel_generate', 'excel_generated',
|
||||
}),
|
||||
('upload_complete', {'freight_uploading', 'freight_upload', 'upload_receipt_recorded', 'completed'}),
|
||||
)
|
||||
|
||||
# 已持久化的 Processing 技术阶段到五阶段业务工作面的唯一映射。它只用于
|
||||
# 读模型展示,不推进订单、不创建任务,也不授予任何动作。正式 Gate 仍在
|
||||
# 技术阶段缺失时提供兜底,避免历史数据被无条件覆盖。
|
||||
LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
|
||||
'upload_received': 'intake_parse',
|
||||
'email_parsing': 'intake_parse',
|
||||
'document_parsing': 'intake_parse',
|
||||
'email_adjudicating': 'intake_parse',
|
||||
'candidate_creating': 'intake_parse',
|
||||
'waiting_review': 'order_review',
|
||||
'customer_resolving': 'order_review',
|
||||
'duplicate_checking': 'order_review',
|
||||
'inventory_source_resolving': 'order_review',
|
||||
'order_creating': 'fulfillment_prep',
|
||||
'inventory_fetching': 'fulfillment_prep',
|
||||
'inventory_preparation': 'fulfillment_prep',
|
||||
'inventory_matching': 'fulfillment_prep',
|
||||
'inventory_sufficiency': 'fulfillment_prep',
|
||||
'excel_generating': 'fulfillment_prep',
|
||||
'freight_uploading': 'freight_upload',
|
||||
'manual_upload_handoff': 'freight_upload',
|
||||
'completed': 'upload_complete',
|
||||
}
|
||||
|
||||
def lifecycle_entries(
|
||||
*,
|
||||
@@ -101,19 +109,32 @@ def project_lifecycle(
|
||||
*,
|
||||
current_gate: dict[str, Any] | None,
|
||||
blocking_reason: dict[str, Any] | None,
|
||||
legacy_stage: str | None,
|
||||
has_candidate_context: bool,
|
||||
has_intake_parse_context: bool = False,
|
||||
verified_upload_success: bool = False,
|
||||
processing_stage: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""按 Gate → 阻断归属 → 历史阶段的固定优先级裁决生命周期和入口。
|
||||
"""按成功事实 → Gate → 已持久化阶段 → 阻断归属的固定优先级裁决生命周期。
|
||||
|
||||
``authority`` 仅用于诊断/迁移观测;前端不得据此再计算阶段或放开按钮。
|
||||
``processing_stage`` 是订单处理流程已写入的事实,仅映射展示工作面;它不能
|
||||
授权动作或推进流程。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算
|
||||
阶段或放开按钮。
|
||||
"""
|
||||
gate = current_gate if isinstance(current_gate, dict) else {}
|
||||
gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower()
|
||||
if gate_code in LIFECYCLE_STAGE_BY_GATE:
|
||||
# 成功事实高于当前 Gate/历史阶段:异步回调成功后旧 Gate 尚未清理时,用户仍应
|
||||
# 看到已完成;反之任何技术完成、回执文本或旧 completed 都不能越过此条件。
|
||||
if verified_upload_success:
|
||||
lifecycle_stage = 'upload_complete'
|
||||
authority = 'verified_upload_success'
|
||||
elif gate_code in LIFECYCLE_STAGE_BY_GATE:
|
||||
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
|
||||
authority = 'process_gate'
|
||||
elif str(processing_stage or '').strip().lower() in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
|
||||
lifecycle_stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[
|
||||
str(processing_stage or '').strip().lower()
|
||||
]
|
||||
authority = 'processing_stage'
|
||||
else:
|
||||
reason = blocking_reason if isinstance(blocking_reason, dict) else {}
|
||||
reason_code = str(reason.get('code') or reason.get('blocking_reason_code') or '').strip()
|
||||
@@ -122,12 +143,8 @@ def project_lifecycle(
|
||||
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[owning_gate]
|
||||
authority = 'blocking_reason'
|
||||
else:
|
||||
normalized_legacy = str(legacy_stage or '').strip().lower()
|
||||
lifecycle_stage = next(
|
||||
(code for code, aliases in LIFECYCLE_STAGE_RANGES if normalized_legacy in aliases),
|
||||
normalized_legacy if normalized_legacy in LIFECYCLE_STAGE_CODES else None,
|
||||
)
|
||||
authority = 'legacy_fallback' if lifecycle_stage else 'unclassified'
|
||||
lifecycle_stage = None
|
||||
authority = 'unclassified'
|
||||
return {
|
||||
'lifecycle_stage': lifecycle_stage,
|
||||
'lifecycle_entries': lifecycle_entries(
|
||||
|
||||
@@ -26,6 +26,9 @@ from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
|
||||
create_post_ot_fulfillment_wave,
|
||||
list_eligible_post_ot_line_keys,
|
||||
)
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
project_review_case_line_decisions,
|
||||
)
|
||||
from app.services.shipping_notice.post_ot_wave_progress_service import schedule_post_ot_wave_progress
|
||||
|
||||
|
||||
@@ -114,6 +117,12 @@ def coordinate_post_ot_auto_fulfill(
|
||||
}
|
||||
|
||||
eligible = list_eligible_post_ot_line_keys(case)
|
||||
projection = project_review_case_line_decisions(case)
|
||||
unassigned = [
|
||||
str(item.get('line_key') or '')
|
||||
for item in list(projection.get('lines') or [])
|
||||
if str(item.get('line_status') or '') not in {'task_created', 'fulfilled', 'closed_unfulfillable'}
|
||||
]
|
||||
if not eligible:
|
||||
return {
|
||||
'status': 'idle',
|
||||
@@ -122,6 +131,16 @@ def coordinate_post_ot_auto_fulfill(
|
||||
'case_no': case.case_no,
|
||||
'accepted_line_keys': [],
|
||||
}
|
||||
# [STEP] 自动制单只处理唯一开放明细。多条明细必须由用户勾选后合并,
|
||||
# 绝不静默替用户决定 Notice 的合并范围。
|
||||
if len(eligible) != 1 or set(eligible) != set(unassigned):
|
||||
return {
|
||||
'status': 'idle',
|
||||
'reason': 'manual_wave_selection_required',
|
||||
'trigger': trigger,
|
||||
'case_no': case.case_no,
|
||||
'accepted_line_keys': [],
|
||||
}
|
||||
|
||||
idem_key = f'auto-fulfill:{case.case_no}:{trigger}:{",".join(sorted(eligible))}'
|
||||
try:
|
||||
|
||||
@@ -14,13 +14,19 @@ from app import db
|
||||
from app.models import ShippingNoticeLine, ShippingOrderSnapshot
|
||||
|
||||
|
||||
def replace_notice_lines_from_snapshot(*, notice_id: int, snapshot: ShippingOrderSnapshot) -> int:
|
||||
def replace_notice_lines_from_snapshot(
|
||||
*,
|
||||
notice_id: int,
|
||||
snapshot: ShippingOrderSnapshot,
|
||||
snapshot_line_ids: set[int] | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。
|
||||
|
||||
Args:
|
||||
notice_id: shipping_notices.id。
|
||||
snapshot: 已 flush 且带 lines 的 Snapshot。
|
||||
snapshot_line_ids: 仅写入本次发货通知选中的冻结行;为空时兼容整单冻结。
|
||||
|
||||
Returns:
|
||||
写入行数。
|
||||
@@ -28,7 +34,10 @@ def replace_notice_lines_from_snapshot(*, notice_id: int, snapshot: ShippingOrde
|
||||
db.session.query(ShippingNoticeLine).filter_by(notice_id=int(notice_id)).delete(synchronize_session=False)
|
||||
now = datetime.utcnow()
|
||||
rows: list[ShippingNoticeLine] = []
|
||||
selected_ids = {int(item) for item in (snapshot_line_ids or set())}
|
||||
for line in list(snapshot.lines or []):
|
||||
if selected_ids and int(line.id) not in selected_ids:
|
||||
continue
|
||||
rows.append(
|
||||
ShippingNoticeLine(
|
||||
notice_id=int(notice_id),
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/open_existing_reservation_backfill.py
|
||||
|
||||
用途:exact_file/open_existing 场景下将 Candidate 字段安全对账到旧任务(兼容入口)。
|
||||
用途:exact_file/open_existing 场景下将 Candidate 字段安全对账到既有任务。
|
||||
依赖:task_candidate_reconciliation、tool_common。
|
||||
逻辑:batch_from_intakes 仍调用本模块;内部委托通用字段对账,并保留 applied/skipped/conflicted 审计语义。
|
||||
逻辑:内部委托通用字段对账,并保留 applied/skipped/conflicted 审计语义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,353 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/order_auto_freeze_execution.py
|
||||
|
||||
用途:消费 Run 级自动冻结门禁摘要,把当前 Run 已接受的候选订单落成 Task 并冻结为 Snapshot。
|
||||
依赖:Run/Candidate/Task 模型、候选建批编排与订单冻结服务。
|
||||
逻辑:只有当 run.auto_freeze_policy_json 已明确放行时才执行;执行范围严格限定在当前 Run,
|
||||
建单与冻结均只处理本轮 eligible 的 accepted + selected 候选集合,禁止扩大到 Run 内其它已消费候选;
|
||||
单任务冻结使用 savepoint,失败回滚该任务半成品,禁止外层误提交已冻结状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderProcessingRun,
|
||||
ShippingNotice,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
|
||||
def maybe_execute_run_auto_freeze(
|
||||
*,
|
||||
run: ShippingOrderProcessingRun,
|
||||
submission_result: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""在门禁已放行时消费当前 Run 的 accepted Candidate,并自动冻结其新建任务。"""
|
||||
result = dict(submission_result or {})
|
||||
policy = run.auto_freeze_policy_json if isinstance(run.auto_freeze_policy_json, dict) else {}
|
||||
if not bool(policy.get('enabled')):
|
||||
return result
|
||||
|
||||
# [STEP 1] 冻结候选集合在建单前冻结;后续冻结不得重新扩大范围。
|
||||
candidate_nos = _eligible_candidate_nos(run)
|
||||
create_result: dict[str, Any] | None = None
|
||||
if candidate_nos:
|
||||
create_result = create_shipping_batch_from_candidates(
|
||||
user_id=int(run.user_id),
|
||||
conversation_id=run.conversation_id,
|
||||
intake_nos=_snapshot_intake_nos(run),
|
||||
candidate_nos=candidate_nos,
|
||||
create_idempotency_key=f"extract:{str(run.input_snapshot_hash or '')[:48]}",
|
||||
)
|
||||
|
||||
frozen_task_nos, blocked_tasks = _freeze_created_tasks(
|
||||
run=run,
|
||||
policy=policy,
|
||||
candidate_nos=candidate_nos,
|
||||
)
|
||||
refreshed = _refresh_submission_result(
|
||||
run=run,
|
||||
previous_result=result,
|
||||
create_result=create_result,
|
||||
)
|
||||
refreshed['auto_freeze'] = {
|
||||
'enabled': True,
|
||||
'frozen_task_nos': frozen_task_nos,
|
||||
'blocked_tasks': blocked_tasks,
|
||||
'eligible_candidate_nos': list(candidate_nos),
|
||||
}
|
||||
return refreshed
|
||||
|
||||
|
||||
def _eligible_candidate_nos(run: ShippingOrderProcessingRun) -> list[str]:
|
||||
"""只返回当前 Run 中可以自动建单的 accepted + selected 候选。"""
|
||||
rows = (
|
||||
ShippingOrderCandidate.query
|
||||
.filter_by(
|
||||
order_extraction_run_id=int(run.id),
|
||||
is_current_version=True,
|
||||
candidate_status='accepted',
|
||||
selected=True,
|
||||
)
|
||||
.filter(ShippingOrderCandidate.consumed_task_id.is_(None))
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [str(item.candidate_no) for item in rows if str(item.candidate_no or '').strip()]
|
||||
|
||||
|
||||
def _snapshot_intake_nos(run: ShippingOrderProcessingRun) -> list[str]:
|
||||
"""从 Run 冻结快照提取 Intake 编号,确保自动消费范围不越过本轮输入。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
return [
|
||||
str(item.get('intake_no') or '').strip().upper()
|
||||
for item in intakes
|
||||
if isinstance(item, dict) and str(item.get('intake_no') or '').strip()
|
||||
]
|
||||
|
||||
|
||||
def _freeze_created_tasks(
|
||||
*,
|
||||
run: ShippingOrderProcessingRun,
|
||||
policy: dict[str, Any],
|
||||
candidate_nos: list[str],
|
||||
) -> tuple[list[str], list[dict[str, Any]]]:
|
||||
"""
|
||||
冻结本轮 eligible 且已消费的任务。
|
||||
|
||||
核心逻辑:候选集合必须与建单前 `_eligible_candidate_nos` 完全一致;
|
||||
禁止扫描 Run 下全部 consumed 候选(避免误冻人工/其它路径任务)。
|
||||
"""
|
||||
eligible = {
|
||||
str(item).strip()
|
||||
for item in (candidate_nos or [])
|
||||
if str(item).strip()
|
||||
}
|
||||
if not eligible:
|
||||
return [], []
|
||||
|
||||
candidates = (
|
||||
ShippingOrderCandidate.query
|
||||
.filter_by(
|
||||
order_extraction_run_id=int(run.id),
|
||||
is_current_version=True,
|
||||
candidate_status='accepted',
|
||||
selected=True,
|
||||
)
|
||||
.filter(ShippingOrderCandidate.consumed_task_id.isnot(None))
|
||||
.filter(ShippingOrderCandidate.candidate_no.in_(tuple(eligible)))
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
frozen_task_nos: list[str] = []
|
||||
blocked_tasks: list[dict[str, Any]] = []
|
||||
for candidate in candidates:
|
||||
if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing':
|
||||
continue
|
||||
task = db.session.get(ShippingNotice, int(candidate.consumed_task_id or 0))
|
||||
if task is None:
|
||||
continue
|
||||
# [STEP] 单任务 savepoint:冻结失败必须回滚本任务已 flush 的快照/指针/客户继承,
|
||||
# 禁止外层事务提交“返回阻断但库内已冻结”的半成品。
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
_inherit_confirmed_ordering_customer(run=run, task=task, policy=policy)
|
||||
snapshot = freeze_order_snapshot(
|
||||
task,
|
||||
actor_id=None,
|
||||
expected_order_data_version=int(task.order_data_version or 1),
|
||||
freeze_mode='auto',
|
||||
auto_freeze_policy=policy,
|
||||
)
|
||||
# [STEP] 与冻结同 savepoint:进度事件失败则回滚本任务冻结半成品。
|
||||
from app.services.shipping_notice.order_extraction_progress import record_run_progress
|
||||
|
||||
record_run_progress(
|
||||
run=run,
|
||||
event_code='order_auto_frozen',
|
||||
summary={
|
||||
'task_no': str(task.task_no or ''),
|
||||
'candidate_no': str(candidate.candidate_no or ''),
|
||||
'snapshot_id': int(getattr(snapshot, 'id', 0) or 0) or None,
|
||||
'freeze_source': str((policy or {}).get('freeze_source') or '') or None,
|
||||
},
|
||||
commit=False,
|
||||
)
|
||||
frozen_task_nos.append(str(task.task_no or f"snapshot-{snapshot.id}"))
|
||||
except Exception as exc: # pragma: no cover - 阻断明细由调用侧测试断言
|
||||
blocked_tasks.append({
|
||||
'candidate_no': str(candidate.candidate_no or ''),
|
||||
'task_no': str(task.task_no or ''),
|
||||
'code': str(getattr(exc, 'code', '') or ''),
|
||||
'message': str(exc),
|
||||
'details': getattr(exc, 'details', None),
|
||||
})
|
||||
return frozen_task_nos, blocked_tasks
|
||||
|
||||
|
||||
def _inherit_confirmed_ordering_customer(
|
||||
*,
|
||||
run: ShippingOrderProcessingRun,
|
||||
task: ShippingNotice,
|
||||
policy: dict[str, Any],
|
||||
) -> None:
|
||||
"""把 Run 已确认的唯一 Bill-to 客户补写到当前任务 Extraction,供自动冻结门禁复用。"""
|
||||
confirmed_ids = sorted({
|
||||
int(item)
|
||||
for item in (policy.get('confirmed_customer_ids') or [])
|
||||
if str(item).strip().isdigit()
|
||||
})
|
||||
if len(confirmed_ids) != 1 or not task.current_order_extraction_id:
|
||||
return
|
||||
extraction = db.session.get(ShippingOrderExtraction, int(task.current_order_extraction_id))
|
||||
if extraction is None:
|
||||
return
|
||||
target = ShippingOrderCustomerMatch.query.filter_by(
|
||||
extraction_id=int(extraction.id),
|
||||
role='bill_to',
|
||||
).one_or_none()
|
||||
if (
|
||||
target is not None
|
||||
and target.status == 'confirmed'
|
||||
and int(target.customer_id or 0) == confirmed_ids[0]
|
||||
and bool(target.customer_short_code_snapshot)
|
||||
and bool(target.identity_fingerprint)
|
||||
and bool(target.identity_rule_version)
|
||||
):
|
||||
return
|
||||
if target is not None and target.status == 'confirmed' and target.customer_id not in {None, confirmed_ids[0]}:
|
||||
return
|
||||
source = (
|
||||
ShippingOrderCustomerMatch.query
|
||||
.join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id)
|
||||
.filter(
|
||||
ShippingOrderExtraction.run_id == int(run.id),
|
||||
ShippingOrderCustomerMatch.role == 'bill_to',
|
||||
ShippingOrderCustomerMatch.status == 'confirmed',
|
||||
ShippingOrderCustomerMatch.customer_id == confirmed_ids[0],
|
||||
)
|
||||
.order_by(ShippingOrderCustomerMatch.confirmed_at.desc(), ShippingOrderCustomerMatch.id.desc())
|
||||
.first()
|
||||
)
|
||||
if source is None:
|
||||
return
|
||||
if target is None:
|
||||
target = ShippingOrderCustomerMatch(
|
||||
extraction_id=int(extraction.id),
|
||||
role='bill_to',
|
||||
identity_components_json={},
|
||||
candidates_json=[],
|
||||
)
|
||||
db.session.add(target)
|
||||
target.raw_name = source.raw_name
|
||||
target.normalized_name = source.normalized_name
|
||||
target.source_system = source.source_system
|
||||
target.external_code = source.external_code
|
||||
target.identity_fingerprint = source.identity_fingerprint
|
||||
target.identity_rule_version = source.identity_rule_version
|
||||
target.identity_components_json = dict(source.identity_components_json or {})
|
||||
target.status = 'confirmed'
|
||||
target.customer_id = source.customer_id
|
||||
target.site_id = source.site_id
|
||||
target.customer_name_snapshot = source.customer_name_snapshot
|
||||
target.customer_short_code_snapshot = source.customer_short_code_snapshot
|
||||
target.candidates_json = list(source.candidates_json or [])
|
||||
target.resolution_method = source.resolution_method or 'run_auto_freeze_inherited'
|
||||
target.confirmation_reason = source.confirmation_reason or 'run_auto_freeze_inherited'
|
||||
target.confirmed_by_id = source.confirmed_by_id
|
||||
target.confirmed_at = source.confirmed_at or datetime.utcnow()
|
||||
target.updated_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _refresh_submission_result(
|
||||
*,
|
||||
run: ShippingOrderProcessingRun,
|
||||
previous_result: dict[str, Any],
|
||||
create_result: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""按当前 Run 持久化事实重建摘要,确保自动建单后 created/pending 计数可恢复。"""
|
||||
candidates = (
|
||||
ShippingOrderCandidate.query
|
||||
.filter_by(order_extraction_run_id=int(run.id), is_current_version=True)
|
||||
.order_by(ShippingOrderCandidate.id.asc())
|
||||
.all()
|
||||
)
|
||||
pending_by_candidate_no = {
|
||||
str(item.get('candidate_no') or ''): item
|
||||
for item in previous_result.get('pending_orders') or []
|
||||
if isinstance(item, dict) and str(item.get('candidate_no') or '').strip()
|
||||
}
|
||||
created: list[dict[str, Any]] = []
|
||||
opened_existing: list[dict[str, Any]] = []
|
||||
pending_orders: list[dict[str, Any]] = []
|
||||
created_with_missing_fields_count = 0
|
||||
for candidate in candidates:
|
||||
if candidate.consumed_task_id is None:
|
||||
pending_item = pending_by_candidate_no.get(str(candidate.candidate_no or ''))
|
||||
if pending_item is not None:
|
||||
pending_orders.append(pending_item)
|
||||
continue
|
||||
task = db.session.get(ShippingNotice, int(candidate.consumed_task_id))
|
||||
if task is None:
|
||||
continue
|
||||
if str(candidate.duplicate_resolution or '').strip().lower() == 'open_existing':
|
||||
opened_existing.append({
|
||||
'candidate_no': candidate.candidate_no,
|
||||
'task_no': task.task_no,
|
||||
'batch_no': None,
|
||||
})
|
||||
continue
|
||||
created.append({'task_no': task.task_no})
|
||||
if candidate.missing_fields_json:
|
||||
created_with_missing_fields_count += 1
|
||||
created_with_missing_fields_count = min(created_with_missing_fields_count, len(created))
|
||||
non_shipping_orders = list(previous_result.get('non_shipping_orders') or [])
|
||||
refreshed = {
|
||||
'status': 'ok',
|
||||
'request_id': str(run.run_no),
|
||||
'batch_no': (
|
||||
create_result.get('batch_no')
|
||||
if isinstance(create_result, dict) and create_result.get('batch_no')
|
||||
else previous_result.get('batch_no')
|
||||
),
|
||||
'created': created,
|
||||
'opened_existing': opened_existing,
|
||||
'pending_orders': pending_orders,
|
||||
'non_shipping_orders': non_shipping_orders,
|
||||
'created_count': len(created),
|
||||
'opened_existing_count': len(opened_existing),
|
||||
'pending_count': len(pending_orders),
|
||||
'non_shipping_count': len(non_shipping_orders),
|
||||
'created_with_missing_fields_count': created_with_missing_fields_count,
|
||||
}
|
||||
refreshed['message'] = _build_submission_message(
|
||||
created_count=refreshed['created_count'],
|
||||
opened_existing_count=refreshed['opened_existing_count'],
|
||||
pending_count=refreshed['pending_count'],
|
||||
non_shipping_count=refreshed['non_shipping_count'],
|
||||
created_with_missing_fields_count=created_with_missing_fields_count,
|
||||
)
|
||||
return refreshed
|
||||
|
||||
|
||||
def _build_submission_message(
|
||||
*,
|
||||
created_count: int,
|
||||
opened_existing_count: int,
|
||||
pending_count: int,
|
||||
non_shipping_count: int,
|
||||
created_with_missing_fields_count: int,
|
||||
) -> str:
|
||||
"""生成自动冻结执行后的统一结果摘要,保持与订单抽取主链路文案一致。"""
|
||||
if not created_count and not opened_existing_count and not pending_count:
|
||||
if non_shipping_count:
|
||||
return f'未识别到需要处理的发货订单,已忽略 {non_shipping_count} 项非发货内容;本次未创建任务。'
|
||||
return '未识别到发货订单,本次未创建任务。'
|
||||
|
||||
parts: list[str] = []
|
||||
if created_count:
|
||||
parts.append(f'已创建 {created_count} 个发货任务')
|
||||
if opened_existing_count:
|
||||
parts.append(f'已打开 {opened_existing_count} 个已有任务')
|
||||
if pending_count:
|
||||
prefix = '另有' if parts else '有'
|
||||
parts.append(f'{prefix} {pending_count} 个订单需要补充信息或处理冲突')
|
||||
if non_shipping_count:
|
||||
parts.append(f'已忽略 {non_shipping_count} 项非发货内容')
|
||||
message = ';'.join(parts) + '。'
|
||||
if created_with_missing_fields_count:
|
||||
message += (
|
||||
f'其中 {created_with_missing_fields_count} 个新建任务仍缺少 Reservation ID,'
|
||||
'可通过自然对话补充。'
|
||||
)
|
||||
return message
|
||||
@@ -39,6 +39,8 @@ def _initial_coordinate_definition(main_table_id: str) -> dict[str, Any]:
|
||||
"""生成未标注但合法的坐标草稿起点;编辑器后续才添加锚点、表头和行布局。"""
|
||||
region_suffix = re.sub(r'[^a-z0-9_]+', '_', main_table_id.lower()).strip('_') or 'table'
|
||||
return {
|
||||
# 视觉主表身份必须随共同定义冻结;annotation/training 只保存该身份的样本绑定。
|
||||
'main_table_id': str(main_table_id).strip(),
|
||||
'document_match': {
|
||||
'document_type': 'purchase_order', 'page_pattern': 'one_or_more',
|
||||
'required_anchors': [], 'optional_anchors': [], 'minimum_score': 0, 'minimum_margin': 0,
|
||||
|
||||
+74
-15
@@ -550,6 +550,38 @@ def _fuse_header_regions_with_column_geometry(
|
||||
})
|
||||
if fused_headers:
|
||||
result['header_regions'] = [*(result.get('header_regions') or []), *fused_headers]
|
||||
# Widget 仅按“表格内有值控件”聚类,动态 XFA 的表头控件也可能带展示值。
|
||||
# 表头文字已通过独立坐标证据确认时,与该表头带实质重叠的 Widget 行不能再
|
||||
# 作为明细行候选,否则画布会同时保存 header_field 与 field。
|
||||
def _overlaps_fused_header(layout: Any) -> bool:
|
||||
if not isinstance(layout, dict) or not isinstance(layout.get('region'), dict):
|
||||
return False
|
||||
try:
|
||||
lx0, ly0, lx1, ly1 = (float(layout['region'][key]) for key in ('x0', 'y0', 'x1', 'y1'))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return False
|
||||
layout_width, layout_height = lx1 - lx0, ly1 - ly0
|
||||
if layout_width <= 0 or layout_height <= 0:
|
||||
return False
|
||||
for header in fused_headers:
|
||||
region = header.get('region') if isinstance(header, dict) else None
|
||||
if not isinstance(region, dict):
|
||||
continue
|
||||
try:
|
||||
hx0, hy0, hx1, hy1 = (float(region[key]) for key in ('x0', 'y0', 'x1', 'y1'))
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
header_width, header_height = hx1 - hx0, hy1 - hy0
|
||||
horizontal_overlap = max(0.0, min(lx1, hx1) - max(lx0, hx0))
|
||||
vertical_overlap = max(0.0, min(ly1, hy1) - max(ly0, hy0))
|
||||
if header_width > 0 and header_height > 0 and \
|
||||
horizontal_overlap / min(layout_width, header_width) >= 0.8 and \
|
||||
vertical_overlap / min(layout_height, header_height) >= 0.8:
|
||||
return True
|
||||
return False
|
||||
result['subrow_layouts'] = [
|
||||
layout for layout in layouts if not _overlaps_fused_header(layout)
|
||||
]
|
||||
return result
|
||||
|
||||
|
||||
@@ -632,6 +664,41 @@ def _field_binding_source_conflicts(candidates: list[dict[str, Any]]) -> list[di
|
||||
return conflicts
|
||||
|
||||
|
||||
def _merge_duplicate_field_binding_candidates(candidates: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""合并同字段同页同坐标的多来源候选,保留全部证据来源。"""
|
||||
merged: dict[tuple[str, str, str, int, tuple[float, float, float, float]], dict[str, Any]] = {}
|
||||
order: list[tuple[str, str, str, int, tuple[float, float, float, float]]] = []
|
||||
unkeyed_candidates: list[dict[str, Any]] = []
|
||||
for candidate in candidates:
|
||||
binding = candidate.get('binding') if isinstance(candidate, dict) else None
|
||||
visual = binding.get('visual_binding') if isinstance(binding, dict) else None
|
||||
bbox = visual.get('normalized_bbox') if isinstance(visual, dict) else None
|
||||
if not isinstance(binding, dict) or not isinstance(visual, dict) or not isinstance(bbox, dict):
|
||||
# 缺少完整坐标的候选无法安全判定为重复,但仍是待人工复核的视觉证据。
|
||||
unkeyed_candidates.append(candidate)
|
||||
continue
|
||||
try:
|
||||
geometry = tuple(round(float(bbox[key]), 6) for key in ('x0', 'y0', 'x1', 'y1'))
|
||||
page_no = int(visual.get('page_no') or 1)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
unkeyed_candidates.append(candidate)
|
||||
continue
|
||||
key = (
|
||||
str(binding.get('field_id') or ''), str(binding.get('field_code') or ''),
|
||||
str(binding.get('scope') or ''), page_no, geometry,
|
||||
)
|
||||
existing = merged.get(key)
|
||||
if existing is None:
|
||||
merged[key] = candidate
|
||||
order.append(key)
|
||||
continue
|
||||
existing['evidence_sources'] = list(dict.fromkeys([
|
||||
*(existing.get('evidence_sources') or []), *(candidate.get('evidence_sources') or []),
|
||||
]))
|
||||
existing['needs_review'] = bool(existing.get('needs_review') or candidate.get('needs_review'))
|
||||
return [*unkeyed_candidates, *(merged[key] for key in order)]
|
||||
|
||||
|
||||
def _execute_visual_automark(
|
||||
*, payload: dict[str, Any], profile_id: int, document_id: int, table_id: str,
|
||||
) -> dict[str, Any]:
|
||||
@@ -873,8 +940,9 @@ def _execute_visual_automark(
|
||||
table_candidates.append(_table_reconstruction_candidate(
|
||||
source='opencv_geometry', reconstruction=opencv_reconstruction,
|
||||
))
|
||||
candidates = table_candidates + field_candidates + widget_candidates
|
||||
field_conflicts = _field_binding_source_conflicts(field_candidates + widget_candidates)
|
||||
field_candidates = _merge_duplicate_field_binding_candidates(field_candidates + widget_candidates)
|
||||
candidates = table_candidates + field_candidates
|
||||
field_conflicts = _field_binding_source_conflicts(field_candidates)
|
||||
conflicts: list[dict[str, Any]] = []
|
||||
reconstructions_by_source = {
|
||||
'pdf_coordinate': native_reconstruction,
|
||||
@@ -941,24 +1009,15 @@ def enqueue_pdf_automark(
|
||||
).order_by(ShippingOrderDocumentProfileSample.id.asc()).first()
|
||||
if annotation is None or annotation.table_id != resolved_table_id:
|
||||
raise ValidationError('Automark requires the frozen annotation sample table', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
if not annotation.layout_version_id or not annotation.layout_payload_checksum:
|
||||
raise ValidationError('Annotation sample layout evidence is not frozen', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
from app.services.shipping_notice.order_document_profile_service import require_profile_sample_automark_ready
|
||||
readiness = require_profile_sample_automark_ready(profile=profile, sample=annotation, actor_id=actor_id)
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
current_checksum = str(
|
||||
getattr(getattr(document, 'current_layout_version', None), 'payload_checksum', '') or '',
|
||||
)
|
||||
if (
|
||||
document is None
|
||||
or int(document.current_layout_version_id or 0) != int(annotation.layout_version_id)
|
||||
or current_checksum != str(annotation.layout_payload_checksum)
|
||||
):
|
||||
raise ValidationError('Annotation sample layout is stale and must be refrozen', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
payload = {
|
||||
'profile_id': int(profile_id), 'document_id': int(document_id), 'table_id': resolved_table_id,
|
||||
'schema_version_id': int(schema_version_id) if schema_version_id else None,
|
||||
'page_no': int(page_no) if page_no else 1, 'actor_id': int(actor_id),
|
||||
'layout_version_id': int(annotation.layout_version_id),
|
||||
'layout_payload_checksum': str(annotation.layout_payload_checksum),
|
||||
'layout_version_id': int(readiness['layout_version_id']),
|
||||
'layout_payload_checksum': str(readiness['layout_payload_checksum']),
|
||||
}
|
||||
ref = f'pdf-automark:{int(profile_id)}:{int(document_id)}:{payload["table_id"] or "page"}:{payload["page_no"]}'
|
||||
job_id = enqueue(
|
||||
|
||||
@@ -31,6 +31,7 @@ from app.services.shipping_notice.document_layout.coordinate_region_text import
|
||||
from app.services.shipping_notice.preview_grant_store import preview_grant_store
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
from app.services.shipping_notice.order_profile_value_adapter import get_value_adapter
|
||||
from app.services.shipping_notice.reservation_region import extract_reservation_from_region_text
|
||||
|
||||
|
||||
PREVIEW_GRANT_TTL_SECONDS = 120
|
||||
|
||||
+3
-45
@@ -7,7 +7,7 @@ services/shipping_notice/order_document_profile_publish_check_service.py
|
||||
逻辑:报告冻结当前草稿身份与签名/重叠引用;XFA 模式使用结构签名、路径/集合/对账阻断,
|
||||
以及字段级混合数据源可发布性与跨源 OCR mismatch 清零;
|
||||
不再要求 flatten/synthetic ready / renderer_version / preview checksum;
|
||||
消费时在同一事务再次校验并发布,草稿或签名变化只能令报告失效;编辑人不得批准自己的 Revision。
|
||||
消费时在同一事务再次校验并发布,草稿或签名变化只能令报告失效;管理员可确认发布自己的草稿。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -15,11 +15,10 @@ import secrets
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileEditLease,
|
||||
ShippingOrderDocumentProfilePublishCheckReport,
|
||||
@@ -121,40 +120,6 @@ def _signature_status(profile: ShippingOrderDocumentProfile, revision: ShippingO
|
||||
return payload
|
||||
|
||||
|
||||
def _find_last_profile_editor_id(profile_id: int) -> int | None:
|
||||
"""
|
||||
查找最近一次编辑 Profile 映射/拆分规则的管理员 ID。
|
||||
|
||||
核心逻辑:优先审计映射事件;回退至最新 DraftRevision.created_by_id。
|
||||
"""
|
||||
editor_events = (
|
||||
'draft_saved',
|
||||
'xfa_mapping_saved',
|
||||
'xfa_split_rule_suggested',
|
||||
'xfa_segment_mapping_updated',
|
||||
)
|
||||
audit = (
|
||||
db.session.query(ShippingOrderDocumentProfileAudit)
|
||||
.filter(
|
||||
ShippingOrderDocumentProfileAudit.profile_id == int(profile_id),
|
||||
ShippingOrderDocumentProfileAudit.event_type.in_(editor_events),
|
||||
)
|
||||
.order_by(ShippingOrderDocumentProfileAudit.id.desc())
|
||||
.first()
|
||||
)
|
||||
if audit is not None and audit.actor_id is not None:
|
||||
return int(audit.actor_id)
|
||||
revision = (
|
||||
db.session.query(ShippingOrderDocumentProfileDraftRevision)
|
||||
.filter_by(profile_id=int(profile_id))
|
||||
.order_by(ShippingOrderDocumentProfileDraftRevision.revision_no.desc())
|
||||
.first()
|
||||
)
|
||||
if revision is not None and revision.created_by_id is not None:
|
||||
return int(revision.created_by_id)
|
||||
return None
|
||||
|
||||
|
||||
def _overlap_summary_from_run(
|
||||
run: ShippingOrderDocumentProfileValidationRun | None,
|
||||
) -> dict[str, Any] | None:
|
||||
@@ -374,6 +339,7 @@ def create_report(profile_id: int, *, data: dict[str, Any], actor_id: int | None
|
||||
and candidate.run_type == 'layout_signature'
|
||||
and candidate.status == 'passed'
|
||||
and candidate.definition_checksum == revision.definition_checksum
|
||||
and validation_service._signature_uses_current_evidence_contract(candidate)
|
||||
):
|
||||
signature_run = candidate
|
||||
if signature_run is None:
|
||||
@@ -491,14 +457,6 @@ def consume_report(profile_id: int, report_no: str, *, data: dict[str, Any], act
|
||||
raise ConflictError('Publish check report is invalid', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID')
|
||||
if row.blocking_items_json:
|
||||
raise ValidationError('Publish check has blocking items', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID')
|
||||
if actor_id is not None:
|
||||
editor_id = _find_last_profile_editor_id(profile.id)
|
||||
if editor_id is not None and int(editor_id) == int(actor_id):
|
||||
raise ValidationError(
|
||||
'Editor cannot approve own version',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_CHECK_INVALID',
|
||||
details={'key': 'editor_cannot_approve_own_version'},
|
||||
)
|
||||
confirmed = {str(item) for item in data.get('confirmed_warning_keys') or []}
|
||||
required = {str(item.get('key')) for item in row.warning_items_json or []}
|
||||
if confirmed != required:
|
||||
|
||||
@@ -9,6 +9,7 @@ backend/app/services/shipping_notice/order_document_profile_service.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
@@ -39,7 +40,11 @@ from app.models import (
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
|
||||
coordinate_profile_character_candidates,
|
||||
derive_incomplete_table_bbox,
|
||||
reconstruct_coordinate_profile_rows,
|
||||
reconstruct_coordinate_profile_rows_with_strategy,
|
||||
reconstruction_exclusion_regions,
|
||||
suggest_header_layouts,
|
||||
suggest_header_regions,
|
||||
suggest_multi_subrow_layouts,
|
||||
@@ -70,6 +75,7 @@ from app.services.shipping_notice.order_profile_value_adapter import (
|
||||
OrderProfileValueAdapter,
|
||||
get_value_adapter,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_region import extract_reservation_from_region_text
|
||||
|
||||
|
||||
PROFILE_CODE_PATTERN = re.compile(r'^[A-Z0-9][A-Z0-9_-]{1,63}$')
|
||||
@@ -422,6 +428,42 @@ def _normalize_definition(
|
||||
)
|
||||
|
||||
profile_fields = _schema_profile_fields(schema_version)
|
||||
reservation_region = raw.get('reservation_id_region')
|
||||
if reservation_region is not None:
|
||||
if not isinstance(reservation_region, dict):
|
||||
raise ValidationError(
|
||||
'reservation_id_region must be an object',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID',
|
||||
)
|
||||
reservation_fields = {
|
||||
scope: field for (scope, code), field in profile_fields.items()
|
||||
if code == 'reservation_id'
|
||||
}
|
||||
# 一个区域可以同时承载整单 Reservation 和指定明细行 Reservation:
|
||||
# Header 是无行号值的权威落点;Line 字段启用后才消费带行号的值。
|
||||
if 'header' not in reservation_fields:
|
||||
raise ValidationError(
|
||||
'Schema must enable header reservation_id for unnumbered Reservation values',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID',
|
||||
details={'scopes': sorted(reservation_fields), 'required_scope': 'header'},
|
||||
)
|
||||
region = reservation_region.get('region')
|
||||
page_no = reservation_region.get('page_no')
|
||||
if not isinstance(region, dict) or page_no is None:
|
||||
raise ValidationError(
|
||||
'reservation_id_region requires region and page_no',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID',
|
||||
)
|
||||
try:
|
||||
from app.services.shipping_notice.document_layout.order_profile import RelativeRegion
|
||||
RelativeRegion.model_validate(region)
|
||||
if int(page_no) < 1:
|
||||
raise ValueError('page_no must be positive')
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'reservation_id_region geometry is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_RESERVATION_REGION_INVALID',
|
||||
) from exc
|
||||
if raw.get('header_mappings') is not None or raw.get('source_contract') is not None or raw.get('line_mapping') is not None:
|
||||
raise ValidationError(
|
||||
'Coordinate definition must not mix value-source mapping keys',
|
||||
@@ -438,6 +480,8 @@ def _normalize_definition(
|
||||
'table_regions': raw.get('table_regions'),
|
||||
'order_field_layouts': raw.get('order_field_layouts') or [],
|
||||
'draft_unbound_order_field_layouts': raw.get('draft_unbound_order_field_layouts') or [],
|
||||
'coordinate_model': raw.get('coordinate_model') or {},
|
||||
'reference_page_frames': raw.get('reference_page_frames') or {},
|
||||
}
|
||||
for table_region in normalized['table_regions'] or []:
|
||||
if not isinstance(table_region, dict):
|
||||
@@ -501,6 +545,13 @@ def _normalize_definition(
|
||||
}
|
||||
for target in sorted(outputs)
|
||||
]
|
||||
# Legacy Vendor Comments mappings are intentionally rejected at the API
|
||||
# boundary; the only supported special evidence is reservation_id_region.
|
||||
if raw.get('named_regions') is not None or raw.get('field_source_mappings') is not None:
|
||||
raise ValidationError(
|
||||
'Legacy Vendor Comments mappings are no longer supported; use reservation_id_region',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_LEGACY_VENDOR_COMMENTS_UNSUPPORTED',
|
||||
)
|
||||
for order_field in normalized['order_field_layouts']:
|
||||
if not isinstance(order_field, dict):
|
||||
continue
|
||||
@@ -510,6 +561,24 @@ def _normalize_definition(
|
||||
field = profile_fields.get(('header', code))
|
||||
if field is None:
|
||||
raise ValidationError('Order field binding must target a header Schema field', code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID')
|
||||
# [STEP] Address layouts saved by the affected workbench version could inherit
|
||||
# the first page anchor (Number). Reject that proven bad binding at the API
|
||||
# boundary so stale browsers or direct requests cannot persist it again.
|
||||
anchor = order_field.get('anchor')
|
||||
anchor_text = (
|
||||
str(anchor.get('text') or '').strip().casefold()
|
||||
if isinstance(anchor, dict) else ''
|
||||
)
|
||||
if code in {'ship_to_address', 'bill_to_address'} and anchor_text == 'number':
|
||||
raise ValidationError(
|
||||
'Address field cannot bind to the Number anchor',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
details={
|
||||
'reason': 'order_field_anchor_semantic_mismatch',
|
||||
'field_code': code,
|
||||
'anchor_text': str(anchor.get('text') or '').strip(),
|
||||
},
|
||||
)
|
||||
order_field['field_id'] = str(field['field_id'])
|
||||
order_field['scope'] = 'header'
|
||||
normalizer = order_field.get('normalizer_key')
|
||||
@@ -550,6 +619,8 @@ def _normalize_definition(
|
||||
table_regions=normalized['table_regions'],
|
||||
order_field_layouts=normalized['order_field_layouts'],
|
||||
draft_unbound_order_field_layouts=normalized['draft_unbound_order_field_layouts'],
|
||||
coordinate_model=normalized['coordinate_model'],
|
||||
reference_page_frames=normalized['reference_page_frames'],
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
# Pydantic locations only describe the submitted contract, so exposing the
|
||||
@@ -576,11 +647,24 @@ def _normalize_definition(
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
) from exc
|
||||
result = {
|
||||
# 不能在坐标定义规范化时丢弃创建向导冻结的视觉主表身份。
|
||||
'main_table_id': str(raw.get('main_table_id') or '').strip() or None,
|
||||
'document_match': contract.document_match.model_dump(),
|
||||
'table_regions': [item.model_dump() for item in contract.table_regions],
|
||||
'order_field_layouts': [item.model_dump() for item in contract.order_field_layouts],
|
||||
'draft_unbound_order_field_layouts': [item.model_dump() for item in contract.draft_unbound_order_field_layouts],
|
||||
'coordinate_model': contract.coordinate_model.model_dump(),
|
||||
'reference_page_frames': {
|
||||
str(page_no): frame.model_dump()
|
||||
for page_no, frame in contract.reference_page_frames.items()
|
||||
},
|
||||
}
|
||||
if reservation_region is not None:
|
||||
result['reservation_id_region'] = {
|
||||
'region': dict(reservation_region['region']),
|
||||
'page_scope': 'exact_page',
|
||||
'page_no': int(reservation_region['page_no']),
|
||||
}
|
||||
if unified_bindings:
|
||||
result['bindings'] = unified_bindings
|
||||
result['template_mode'] = 'coordinate'
|
||||
@@ -660,6 +744,8 @@ def _normalize_visual_definition_for_preview(
|
||||
'table_regions': table_regions,
|
||||
'order_field_layouts': order_field_layouts,
|
||||
'draft_unbound_order_field_layouts': draft_unbound_order_field_layouts,
|
||||
'coordinate_model': raw.get('coordinate_model') or {},
|
||||
'reference_page_frames': raw.get('reference_page_frames') or {},
|
||||
}
|
||||
return _normalize_definition(visual, schema_version=schema_version, preferred_template_mode='coordinate')
|
||||
|
||||
@@ -674,6 +760,8 @@ def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordina
|
||||
table_regions=definition.get('table_regions'),
|
||||
order_field_layouts=definition.get('order_field_layouts') or [],
|
||||
draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [],
|
||||
coordinate_model=definition.get('coordinate_model') or {},
|
||||
reference_page_frames=definition.get('reference_page_frames') or {},
|
||||
)
|
||||
|
||||
|
||||
@@ -1004,11 +1092,42 @@ def read_preview_page_region_text(
|
||||
source = 'acroform_widget'
|
||||
elif len(matched_widgets) > 1:
|
||||
source = 'acroform_widget_ambiguous'
|
||||
if not text:
|
||||
text = _read_rendered_preview_crop_text(data.get('rendered_image_base64'))
|
||||
if text:
|
||||
source = 'xfa_rendered_ocr'
|
||||
_audit(profile_id=int(profile_id), document_id=document.id, event_type='preview_region_text_read', actor_id=actor_id, detail={
|
||||
'page_no': int(page_no), 'character_count': len(text), 'source': source,
|
||||
})
|
||||
db.session.commit()
|
||||
return {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'}
|
||||
result = {'document_id': document.id, 'page_no': int(page_no), 'text': text, 'source': source, 'status': 'needs_review'}
|
||||
if data.get('purpose') == 'reservation_id_region':
|
||||
result['reservation_candidates'] = extract_reservation_from_region_text(text)
|
||||
return result
|
||||
|
||||
|
||||
def _read_rendered_preview_crop_text(rendered_image_base64: Any) -> str:
|
||||
"""读取浏览器 PDF.js XFA 画布的受控裁剪图文字,仅用于视觉标注回读。"""
|
||||
raw = str(rendered_image_base64 or '')
|
||||
prefix = 'data:image/png;base64,'
|
||||
if not raw.startswith(prefix):
|
||||
return ''
|
||||
try:
|
||||
payload = base64.b64decode(raw[len(prefix):], validate=True)
|
||||
if not payload or len(payload) > 2 * 1024 * 1024:
|
||||
return ''
|
||||
import numpy as np
|
||||
from app.services.shipping_notice.document_layout.ocr_pdf import extract_ocr_lines
|
||||
|
||||
image = Image.open(io.BytesIO(payload)).convert('RGB')
|
||||
pixels = np.asarray(image)
|
||||
height, width = pixels.shape[:2]
|
||||
if width < 8 or height < 8 or width * height > 4_000_000:
|
||||
return ''
|
||||
lines = extract_ocr_lines(pixels, page_width=float(width), page_height=float(height))
|
||||
return ' '.join(str(item.text).strip() for item in lines if str(item.text).strip()).strip()
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def preview_profile_region(
|
||||
@@ -1032,6 +1151,8 @@ def preview_profile_region(
|
||||
profile_code=profile.profile_code, version=profile.version,
|
||||
document_match=definition['document_match'], table_regions=definition['table_regions'],
|
||||
order_field_layouts=definition['order_field_layouts'],
|
||||
coordinate_model=definition['coordinate_model'],
|
||||
reference_page_frames=definition['reference_page_frames'],
|
||||
)
|
||||
table_id = str(data.get('table_id') or '').strip()
|
||||
if not table_id:
|
||||
@@ -1084,6 +1205,10 @@ def preview_profile_region(
|
||||
except (KeyError, TypeError, ValueError) as exc:
|
||||
raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
|
||||
strict = bool(data.get('strict'))
|
||||
schema_field_metadata = [
|
||||
item for item in (profile.schema_version.definition_json or {}).get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'line'
|
||||
]
|
||||
rows = []
|
||||
involved_field_codes: list[str] = []
|
||||
seen_field_codes: set[str] = set()
|
||||
@@ -1097,11 +1222,21 @@ def preview_profile_region(
|
||||
# Header-only pages document column semantics but must never emit data rows.
|
||||
if not table_region.line_layouts:
|
||||
continue
|
||||
# Adaptive regions explicitly require page evidence because a detected
|
||||
# table bbox may contain headers only when MinerU misses detail rows.
|
||||
region_characters = characters
|
||||
if table_region.row_reconstruction_mode == 'adaptive_record_columns':
|
||||
region_characters = (evidence.get('page_glyphs') or {}).get(str(raw_table.get('page_no') or 1))
|
||||
# 表头区域只描述列语义与预览,运行时不得删除其覆盖的 glyph;起行 Schema
|
||||
# 交叉校验会拒绝表头,普通 exclusion_regions 才是显式删除授权。
|
||||
reconstruction_exclusions = reconstruction_exclusion_regions(table_region.model_dump())
|
||||
reference_page_frame = contract.reference_page_frames.get(int(raw_table.get('page_no') or 1))
|
||||
region_characters, _candidate_page_bbox = coordinate_profile_character_candidates(
|
||||
table_region=table_region.region.model_dump(), page_size=page,
|
||||
reference_page_frame=(
|
||||
reference_page_frame.model_dump() if reference_page_frame is not None else None
|
||||
),
|
||||
page_characters=(evidence.get('page_glyphs') or {}).get(str(raw_table.get('page_no') or 1)),
|
||||
table_characters=characters,
|
||||
raw_table_bbox=raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None,
|
||||
table_id=table_id, page_no=int(raw_table.get('page_no') or 1),
|
||||
allow_table_fallback=True,
|
||||
)
|
||||
if not isinstance(region_characters, list):
|
||||
continue
|
||||
# ??????????????????????????? Schema ???
|
||||
@@ -1116,31 +1251,22 @@ def preview_profile_region(
|
||||
if field_code and field_code not in seen_field_codes:
|
||||
seen_field_codes.add(field_code)
|
||||
involved_field_codes.append(field_code)
|
||||
reconstructed_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=[item for item in region_characters if isinstance(item, dict)], table_bbox=page_bbox,
|
||||
reconstructed_rows, _strategy = reconstruct_coordinate_profile_rows_with_strategy(
|
||||
characters=[item for item in region_characters if isinstance(item, dict)],
|
||||
table_bbox=(
|
||||
{'x0': 0, 'y0': 0, 'x1': reference_page_frame.width, 'y1': reference_page_frame.height}
|
||||
if reference_page_frame is not None else page_bbox
|
||||
),
|
||||
line_layouts=[item.model_dump() for item in table_region.line_layouts],
|
||||
table_region=table_region.region.model_dump(),
|
||||
termination_rules=[item.model_dump() for item in table_region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions],
|
||||
exclusion_regions=reconstruction_exclusions,
|
||||
dynamic_exclusion_regions=reconstruction_exclusions,
|
||||
# ?????????????????????????????????
|
||||
include_deleted=not strict,
|
||||
line_start_field_code=table_region.line_start_field_code,
|
||||
row_reconstruction_mode=table_region.row_reconstruction_mode,
|
||||
schema_field_metadata=schema_field_metadata,
|
||||
)
|
||||
# Preview must expose coordinate reads for correction even when the current
|
||||
# sample's start marker is missing; the production extraction path remains strict.
|
||||
if not reconstructed_rows and not strict:
|
||||
reconstructed_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=[item for item in region_characters if isinstance(item, dict)], table_bbox=page_bbox,
|
||||
line_layouts=[item.model_dump() for item in table_region.line_layouts],
|
||||
table_region=table_region.region.model_dump(),
|
||||
termination_rules=[item.model_dump() for item in table_region.termination_rules],
|
||||
exclusion_regions=[item.model_dump() for item in table_region.exclusion_regions],
|
||||
include_deleted=True,
|
||||
line_start_field_code=table_region.line_start_field_code,
|
||||
include_unanchored_rows=True,
|
||||
row_reconstruction_mode=table_region.row_reconstruction_mode,
|
||||
)
|
||||
rows.extend(reconstructed_rows)
|
||||
# ??????????????????????????????
|
||||
if strict:
|
||||
@@ -1197,6 +1323,8 @@ def suggest_profile_header(
|
||||
profile_code=profile.profile_code, version=profile.version,
|
||||
document_match=definition['document_match'], table_regions=definition['table_regions'],
|
||||
order_field_layouts=definition['order_field_layouts'],
|
||||
coordinate_model=definition['coordinate_model'],
|
||||
reference_page_frames=definition['reference_page_frames'],
|
||||
)
|
||||
table_id = str(data.get('table_id') or '').strip()
|
||||
layout = _document_layout(document)
|
||||
@@ -1391,6 +1519,28 @@ def _document_layout(document: ShippingOrderDocument) -> dict[str, Any]:
|
||||
return layout
|
||||
|
||||
|
||||
def _reference_page_frames(layout: dict[str, Any]) -> dict[str, dict[str, Any]]:
|
||||
"""从标注样本冻结 Layout 提取 PDF CropBox 点尺寸,拒绝使用浏览器提交的物理尺寸。"""
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
frames: dict[str, dict[str, Any]] = {}
|
||||
for page_no, page in pages.items():
|
||||
try:
|
||||
normalized_page_no = int(page_no)
|
||||
width, height = float(page['width']), float(page['height'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if normalized_page_no < 1 or width <= 0 or height <= 0:
|
||||
continue
|
||||
frames[str(normalized_page_no)] = {
|
||||
'width': width,
|
||||
'height': height,
|
||||
'origin': 'pdf_top_left',
|
||||
'box': 'cropbox',
|
||||
}
|
||||
return frames
|
||||
|
||||
|
||||
def _current_ready_layout_version(document: ShippingOrderDocument) -> ShippingDocumentLayoutVersion:
|
||||
"""????????? ready Layout ???????????????????????"""
|
||||
version = document.current_layout_version
|
||||
@@ -1406,6 +1556,166 @@ def _current_ready_layout_version(document: ShippingOrderDocument) -> ShippingDo
|
||||
return version
|
||||
|
||||
|
||||
def refresh_profile_sample_readiness(
|
||||
*, profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample,
|
||||
actor_id: int | None = None, commit: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""刷新模板样本的 Layout/主表/证据状态,并在条件满足时幂等冻结现有证据字段。
|
||||
|
||||
[STEP 1] 上传物化、Layout ready、主表绑定和证据冻结是四个独立状态;
|
||||
本函数只在 ready Layout 且内容身份一致时写回既有样本字段,绝不创建新实体,
|
||||
也不会在 Layout 尚未完成时把样本伪装成可自动标注。
|
||||
|
||||
Args:
|
||||
profile: 必须是当前模板 Profile。
|
||||
sample: Profile 的 annotation/training 样本绑定。
|
||||
actor_id: 产生冻结审计时的管理员身份,可为空(后台布局收口)。
|
||||
commit: 是否提交当前事务;保存草稿时由外层事务统一提交。
|
||||
|
||||
Returns:
|
||||
包含 layout_status、main_table_status、evidence_status 和 automark_ready 的安全状态。
|
||||
"""
|
||||
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
|
||||
if document is None:
|
||||
return {
|
||||
'profile_id': int(profile.id), 'sample_id': int(sample.id),
|
||||
'document_id': int(sample.document_id), 'layout_status': 'missing',
|
||||
'main_table_status': 'missing', 'evidence_status': 'unavailable',
|
||||
'automark_ready': False, 'reason_code': 'document_missing',
|
||||
}
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
|
||||
layout = current_layout_snapshot(document) or {}
|
||||
version = (
|
||||
db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id))
|
||||
if document.current_layout_version_id else None
|
||||
)
|
||||
if (
|
||||
version is None or str(version.status or '') != 'ready'
|
||||
or not isinstance(version.payload_json, dict)
|
||||
):
|
||||
return {
|
||||
'profile_id': int(profile.id), 'sample_id': int(sample.id),
|
||||
'document_id': int(document.id), 'layout_status': str(getattr(version, 'status', None) or 'pending'),
|
||||
'main_table_status': 'pending', 'evidence_status': 'pending',
|
||||
'automark_ready': False, 'reason_code': 'layout_not_ready',
|
||||
}
|
||||
tables = [
|
||||
item for item in (layout.get('tables') or [])
|
||||
if isinstance(item, dict) and str(item.get('table_id') or '').strip()
|
||||
]
|
||||
table_id = str(sample.table_id or '').strip()
|
||||
if not table_id:
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
configured = str(definition.get('main_table_id') or '').strip()
|
||||
if configured:
|
||||
table_id = configured
|
||||
elif len(tables) == 1:
|
||||
table_id = str(tables[0]['table_id']).strip()
|
||||
else:
|
||||
return {
|
||||
'profile_id': int(profile.id), 'sample_id': int(sample.id),
|
||||
'document_id': int(document.id), 'layout_status': 'ready',
|
||||
'main_table_status': 'ambiguous' if tables else 'missing',
|
||||
'evidence_status': 'pending', 'automark_ready': False,
|
||||
'reason_code': 'main_table_ambiguous' if tables else 'main_table_missing',
|
||||
}
|
||||
if not any(str(item.get('table_id') or '') == table_id for item in tables):
|
||||
return {
|
||||
'profile_id': int(profile.id), 'sample_id': int(sample.id),
|
||||
'document_id': int(document.id), 'layout_status': 'ready',
|
||||
'main_table_status': 'missing', 'evidence_status': 'stale',
|
||||
'automark_ready': False, 'reason_code': 'main_table_missing',
|
||||
}
|
||||
content_hash = str(document.content_hash or '').strip().lower()
|
||||
source_hash = str(version.source_content_hash or '').strip().lower()
|
||||
if len(content_hash) != 64 or len(source_hash) != 64 or content_hash != source_hash:
|
||||
return {
|
||||
'profile_id': int(profile.id), 'sample_id': int(sample.id),
|
||||
'document_id': int(document.id), 'layout_status': 'ready',
|
||||
'main_table_status': 'bound', 'evidence_status': 'stale',
|
||||
'automark_ready': False, 'reason_code': 'layout_content_hash_mismatch',
|
||||
}
|
||||
from app.services.shipping_notice.document_layout.lifecycle import canonical_layout_payload
|
||||
payload_checksum, _ = canonical_layout_payload(version.payload_json or {})
|
||||
stored_checksum = str(version.payload_checksum or '').strip().lower()
|
||||
if len(stored_checksum) != 64 or payload_checksum != stored_checksum:
|
||||
return {
|
||||
'profile_id': int(profile.id), 'sample_id': int(sample.id),
|
||||
'document_id': int(document.id), 'layout_status': 'ready',
|
||||
'main_table_status': 'bound', 'evidence_status': 'stale',
|
||||
'automark_ready': False, 'reason_code': 'layout_checksum_mismatch',
|
||||
}
|
||||
changed = (
|
||||
sample.table_id != table_id
|
||||
or sample.layout_version_id != int(version.id)
|
||||
or str(sample.layout_payload_checksum or '').lower() != stored_checksum
|
||||
or str(sample.source_content_hash or '').lower() != content_hash
|
||||
or str(sample.layout_contract_version or '') != str(version.contract_version or '').strip()
|
||||
or str(sample.parser_key or '') != str(version.parser_key or '').strip()
|
||||
or str(sample.parser_name or '') != str(version.parser_name or '').strip()
|
||||
or str(sample.parser_version or '') != str(version.parser_version or '').strip()
|
||||
)
|
||||
sample.table_id = table_id
|
||||
sample.layout_version_id = int(version.id)
|
||||
sample.layout_payload_checksum = stored_checksum
|
||||
sample.source_content_hash = content_hash
|
||||
sample.layout_contract_version = str(version.contract_version or '').strip() or None
|
||||
sample.parser_key = str(version.parser_key or '').strip() or None
|
||||
sample.parser_name = str(version.parser_name or '').strip() or None
|
||||
sample.parser_version = str(version.parser_version or '').strip() or None
|
||||
# Layout identity or parser provenance changed means this is a new evidence freeze,
|
||||
# not merely a repeated read of the same frozen sample.
|
||||
sample.evidence_frozen_at = datetime.utcnow() if changed else sample.evidence_frozen_at
|
||||
sample.source_filename_snapshot = str(document.filename or '').strip() or None
|
||||
sample.page_count_snapshot = _layout_page_count(version.payload_json or {})
|
||||
sample.table_identity_snapshot = _layout_table_identity_snapshot(version.payload_json or {}, table_id)
|
||||
if changed:
|
||||
_audit(
|
||||
profile_id=profile.id, document_id=document.id,
|
||||
event_type='profile_sample_evidence_frozen', actor_id=actor_id,
|
||||
detail={
|
||||
'sample_id': int(sample.id), 'sample_role': sample.sample_role,
|
||||
'layout_version_id': int(version.id), 'table_id': table_id,
|
||||
'layout_payload_checksum': stored_checksum,
|
||||
},
|
||||
)
|
||||
if commit:
|
||||
db.session.commit()
|
||||
return {
|
||||
'profile_id': int(profile.id), 'sample_id': int(sample.id),
|
||||
'document_id': int(document.id), 'table_id': table_id,
|
||||
'layout_status': 'ready', 'main_table_status': 'bound',
|
||||
'evidence_status': 'frozen', 'automark_ready': True,
|
||||
'layout_version_id': int(version.id), 'layout_payload_checksum': stored_checksum,
|
||||
'reason_code': None,
|
||||
}
|
||||
|
||||
|
||||
def require_profile_sample_automark_ready(
|
||||
*, profile: ShippingOrderDocumentProfile, sample: ShippingOrderDocumentProfileSample,
|
||||
actor_id: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""自动标注入队前唯一强门禁;未满足证据条件时返回稳定、可操作的错误码。"""
|
||||
state = refresh_profile_sample_readiness(profile=profile, sample=sample, actor_id=actor_id, commit=False)
|
||||
if state.get('automark_ready'):
|
||||
return state
|
||||
reason = str(state.get('reason_code') or 'profile_sample_not_ready')
|
||||
code_by_reason = {
|
||||
'layout_not_ready': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_NOT_READY',
|
||||
'main_table_missing': 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_REQUIRED',
|
||||
'main_table_ambiguous': 'SHIPPING.ORDER_DOCUMENT_PROFILE_MAIN_TABLE_AMBIGUOUS',
|
||||
'layout_content_hash_mismatch': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE',
|
||||
'layout_checksum_mismatch': 'SHIPPING.ORDER_DOCUMENT_PROFILE_LAYOUT_STALE',
|
||||
'document_missing': 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND',
|
||||
}
|
||||
raise ValidationError(
|
||||
'Profile sample is not ready for PDF automark',
|
||||
code=code_by_reason.get(reason, 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID'),
|
||||
details=state,
|
||||
)
|
||||
|
||||
|
||||
def _layout_page_count(payload: dict[str, Any]) -> int | None:
|
||||
"""????????????? payload ?? pages?????????????"""
|
||||
pages = payload.get('pages')
|
||||
@@ -1487,7 +1797,7 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr
|
||||
ensure_inline_xfa_structure_analysis_identity,
|
||||
record_inline_layout_snapshot,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import ensure_on_demand_coordinate_evidence
|
||||
from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence
|
||||
|
||||
samples = ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).order_by(
|
||||
ShippingOrderDocumentProfileSample.id.asc(),
|
||||
@@ -1505,28 +1815,17 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
layout_version = _current_ready_layout_version(document)
|
||||
required_pages = _profile_sample_coordinate_pages(
|
||||
profile, sample=sample, layout_payload=layout_version.payload_json or {},
|
||||
hydrated_layout = _hydrate_coordinate_evidence(
|
||||
payload=dict(layout_version.payload_json or {}), document=document,
|
||||
)
|
||||
if not _layout_has_page_coordinate_evidence(layout_version.payload_json or {}, page_nos=required_pages):
|
||||
# [STEP 1] ???????????????????
|
||||
recovered = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=dict(layout_version.payload_json or {}), page_nos=required_pages,
|
||||
required_pages = _profile_sample_coordinate_pages(
|
||||
profile, sample=sample, layout_payload=hydrated_layout,
|
||||
)
|
||||
if not _layout_has_page_coordinate_evidence(hydrated_layout, page_nos=required_pages):
|
||||
raise ConflictError(
|
||||
'Profile sample page coordinate evidence is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
if not _layout_has_page_coordinate_evidence(recovered, page_nos=required_pages):
|
||||
raise ConflictError(
|
||||
'Profile sample page coordinate evidence is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
layout_version = record_inline_layout_snapshot(
|
||||
document, recovered,
|
||||
parser_key='shipping_order_profile_freeze:page_coordinate_evidence.v1',
|
||||
)
|
||||
if str(layout_version.status or '') != 'ready':
|
||||
raise ConflictError(
|
||||
'Profile sample page coordinate evidence cannot be frozen',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
# XFA 视觉补证生成的派生 Layout 必须具有同版本的 datasets 结构分析;
|
||||
# 此处在共同样本冻结边界补齐历史快照,禁止值源 adapter 回退到旧 Layout。
|
||||
ensure_inline_xfa_structure_analysis_identity(
|
||||
@@ -1641,7 +1940,10 @@ def _page_coordinate_characters(layout: dict[str, Any], *, page_no: int) -> tupl
|
||||
def _ensure_page_coordinate_evidence(
|
||||
*, document: ShippingOrderDocument, layout: dict[str, Any], page_no: int,
|
||||
) -> dict[str, Any]:
|
||||
"""???????????????????????????????????"""
|
||||
"""从当前布局的外置证据引用读取页面坐标;缺失时保持缺失,不重读原 PDF。"""
|
||||
from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence
|
||||
|
||||
return _hydrate_coordinate_evidence(payload=dict(layout), document=document)
|
||||
glyphs, source = _page_coordinate_characters(layout, page_no=page_no)
|
||||
if glyphs and source in {'pdf_coordinate', 'ocr_coordinate'}:
|
||||
return layout
|
||||
@@ -1931,6 +2233,8 @@ def preview_order_field_values(data: dict[str, Any], *, actor_id: int | None) ->
|
||||
document_match=definition['document_match'], table_regions=definition['table_regions'],
|
||||
order_field_layouts=definition['order_field_layouts'],
|
||||
draft_unbound_order_field_layouts=definition['draft_unbound_order_field_layouts'],
|
||||
coordinate_model=definition['coordinate_model'],
|
||||
reference_page_frames=definition['reference_page_frames'],
|
||||
)
|
||||
layout = _document_layout(document)
|
||||
if isinstance(raw_page_nos, list) and any(item.page_scope == 'all_pages' for item in profile.order_field_layouts):
|
||||
@@ -2078,7 +2382,7 @@ def _apply_acroform_widget_preview_fallback(
|
||||
|
||||
|
||||
def _widget_is_within_visual_value_region(*, widget_bbox: Any, region: dict[str, float]) -> bool:
|
||||
"""接受中心点落框或至少 80% 面积相交的 Widget,避免邻近控件串值。"""
|
||||
"""仅接受几乎完整落入标注框的 Widget,禁止局部框回填整段 /V。"""
|
||||
if not isinstance(widget_bbox, dict):
|
||||
return False
|
||||
try:
|
||||
@@ -2087,9 +2391,10 @@ def _widget_is_within_visual_value_region(*, widget_bbox: Any, region: dict[str,
|
||||
return False
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
return False
|
||||
center_inside = region['x0'] <= (x0 + x1) / 2 <= region['x1'] and region['y0'] <= (y0 + y1) / 2 <= region['y1']
|
||||
intersection = max(0.0, min(x1, region['x1']) - max(x0, region['x0'])) * max(0.0, min(y1, region['y1']) - max(y0, region['y0']))
|
||||
return center_inside or intersection / ((x1 - x0) * (y1 - y0)) >= .8
|
||||
# Widget /V 是整个控件值。只要框没有完整覆盖控件,就无法证明 /V 属于局部区域;
|
||||
# 此时必须交给浏览器当前画布的局部 OCR,而不能以中心点或部分面积猜测。
|
||||
return intersection / ((x1 - x0) * (y1 - y0)) >= .98
|
||||
|
||||
|
||||
def _read_acroform_widgets_for_preview(*, document: ShippingOrderDocument) -> list[Any]:
|
||||
@@ -2510,6 +2815,36 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st
|
||||
if intake is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
documents = ShippingOrderDocument.query.filter_by(intake_id=intake.id).all()
|
||||
readiness: list[dict[str, Any]] = []
|
||||
document_layout_states: list[str] = []
|
||||
for document in documents:
|
||||
# 测试/后台轮询都可能只载入 current_layout_version_id;显式按 ID 读取,
|
||||
# 不能因 ORM relationship 尚未加载把实际 failed/ready 误报为 pending。
|
||||
version = (
|
||||
db.session.get(ShippingDocumentLayoutVersion, int(document.current_layout_version_id))
|
||||
if document.current_layout_version_id else None
|
||||
)
|
||||
if version is None:
|
||||
# failed Layout 不会成为 current_layout_version;上传状态仍须如实展示最近一次
|
||||
# 解析结论,不能因为没有 current 指针把失败伪装成仍在等待。
|
||||
version = (
|
||||
ShippingDocumentLayoutVersion.query
|
||||
.filter_by(document_id=document.id)
|
||||
.order_by(ShippingDocumentLayoutVersion.version.desc())
|
||||
.first()
|
||||
)
|
||||
document_layout_states.append(str(getattr(version, 'status', None) or 'pending'))
|
||||
bindings = ShippingOrderDocumentProfileSample.query.filter_by(document_id=document.id).all()
|
||||
for sample in bindings:
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(sample.profile_id))
|
||||
if profile is None or profile.status != 'draft':
|
||||
continue
|
||||
state = refresh_profile_sample_readiness(
|
||||
profile=profile, sample=sample, actor_id=actor_id, commit=False,
|
||||
)
|
||||
readiness.append(state)
|
||||
if readiness:
|
||||
db.session.commit()
|
||||
if intake.parse_status in {'parse_failed', 'failed', 'error'}:
|
||||
status = 'failed'
|
||||
error_code = intake.error_code
|
||||
@@ -2520,12 +2855,29 @@ def get_sample_intake_status(intake_no: str, *, actor_id: int | None) -> dict[st
|
||||
# ???? PDF Document??????? EML / Layout?
|
||||
status = 'parsing'
|
||||
error_code = None
|
||||
ready_values = [bool(item.get('automark_ready')) for item in readiness]
|
||||
return {
|
||||
'intake_no': intake.intake_no,
|
||||
'parse_status': status,
|
||||
'document_count': len(documents),
|
||||
'document_ids': [int(document.id) for document in documents],
|
||||
'error_code': error_code,
|
||||
'layout_status': (
|
||||
'ready' if readiness and all(item.get('layout_status') == 'ready' for item in readiness)
|
||||
else (
|
||||
readiness[0].get('layout_status')
|
||||
if readiness
|
||||
else ('ready' if document_layout_states and all(item == 'ready' for item in document_layout_states)
|
||||
else (document_layout_states[0] if document_layout_states else 'pending'))
|
||||
)
|
||||
),
|
||||
'evidence_status': (
|
||||
'frozen' if readiness and all(item.get('evidence_status') == 'frozen' for item in readiness)
|
||||
else (readiness[0].get('evidence_status') if readiness else 'pending')
|
||||
),
|
||||
'automark_ready': bool(readiness) and all(ready_values),
|
||||
'automark_reason_code': next((item.get('reason_code') for item in readiness if item.get('reason_code')), None),
|
||||
'sample_readiness': readiness,
|
||||
}
|
||||
|
||||
|
||||
@@ -2683,11 +3035,33 @@ def suggest_coordinate_reconstruction(
|
||||
if field.get('auto_annotation_enabled', True)
|
||||
and set(field.get('allowed_sources') or []) & {'pdf_coordinate', 'ocr_coordinate'}
|
||||
]
|
||||
effective_characters = characters
|
||||
effective_table_bbox = dict(raw_table['bbox'])
|
||||
table_bbox_source = 'layout_table'
|
||||
suggestions = suggest_multi_subrow_layouts(
|
||||
characters=characters, table_bbox=raw_table['bbox'],
|
||||
characters=effective_characters, table_bbox=effective_table_bbox,
|
||||
)
|
||||
if not suggestions:
|
||||
raise ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID')
|
||||
# MinerU can return a header-only table bbox. Use complete page evidence
|
||||
# to derive a candidate boundary, while retaining the original fact.
|
||||
page_characters, page_source = _page_coordinate_characters(
|
||||
layout, page_no=int(raw_table.get('page_no') or 1),
|
||||
)
|
||||
if page_characters and page_source in {'pdf_coordinate', 'ocr_coordinate'}:
|
||||
derived_bbox = derive_incomplete_table_bbox(
|
||||
characters=page_characters, table_bbox=effective_table_bbox,
|
||||
)
|
||||
if derived_bbox is not None:
|
||||
derived_suggestions = suggest_multi_subrow_layouts(
|
||||
characters=page_characters, table_bbox=derived_bbox,
|
||||
)
|
||||
if derived_suggestions:
|
||||
effective_characters = page_characters
|
||||
effective_table_bbox = derived_bbox
|
||||
suggestions = derived_suggestions
|
||||
table_bbox_source = 'page_coordinate_derived'
|
||||
if not suggestions:
|
||||
raise ValidationError('No item rows could be detected', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_INVALID')
|
||||
raw_row_offset = data.get('row_offset')
|
||||
if raw_row_offset is not None:
|
||||
try:
|
||||
@@ -2709,14 +3083,16 @@ def suggest_coordinate_reconstruction(
|
||||
page = (layout.get('coordinate_evidence') or {}).get('pages', {}).get(str(raw_table.get('page_no') or 1), {})
|
||||
try:
|
||||
page_width, page_height = float(page['width']), float(page['height'])
|
||||
table_bbox = raw_table['bbox']
|
||||
table_bbox = effective_table_bbox
|
||||
table_region = {
|
||||
'x0': float(table_bbox['x0']) / page_width, 'y0': float(table_bbox['y0']) / page_height,
|
||||
'x1': float(table_bbox['x1']) / page_width, 'y1': float(table_bbox['y1']) / page_height,
|
||||
}
|
||||
except (KeyError, TypeError, ValueError, ZeroDivisionError) as exc:
|
||||
raise ValidationError('Coordinate evidence is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_RECONSTRUCTION_UNAVAILABLE') from exc
|
||||
header_suggestions = suggest_header_regions(characters=characters, table_bbox=raw_table['bbox'])
|
||||
header_suggestions = suggest_header_regions(
|
||||
characters=effective_characters, table_bbox=effective_table_bbox,
|
||||
)
|
||||
# Only exact, unique aliases can bind a column. Position is considered only after
|
||||
# the label itself is proven, preventing shifted documents from remapping fields.
|
||||
aliases: dict[str, str | None] = {}
|
||||
@@ -2791,6 +3167,8 @@ def suggest_coordinate_reconstruction(
|
||||
'table_region': table_region,
|
||||
'header_regions': serialized_headers,
|
||||
'subrow_layouts': serialized,
|
||||
'table_bbox_source': table_bbox_source,
|
||||
'original_table_bbox': dict(raw_table['bbox']),
|
||||
'status': 'needs_review',
|
||||
}
|
||||
|
||||
@@ -3002,6 +3380,16 @@ def save_draft(
|
||||
)
|
||||
mapping_issues = normalized.pop('_mapping_issues', None) if isinstance(normalized, dict) else None
|
||||
definition = normalized
|
||||
# [STEP 1] 坐标模板的物理参考框由 annotation Layout 生成;长页样本不会改变
|
||||
# 已标注的 PDF 点坐标,客户端也不能伪造该基准。
|
||||
if template_mode == 'coordinate' and annotation_document is not None:
|
||||
reference_page_frames = _reference_page_frames(_document_layout(annotation_document))
|
||||
if not reference_page_frames:
|
||||
raise ValidationError(
|
||||
'Annotation sample page dimensions are unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
definition['reference_page_frames'] = reference_page_frames
|
||||
if value_adapter.requires_split_rule_confirmation and isinstance(definition, dict):
|
||||
confirmation_tokens = data.get('split_rule_confirmation_tokens')
|
||||
if not isinstance(confirmation_tokens, dict):
|
||||
@@ -3114,6 +3502,9 @@ def save_draft(
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
db.session.add(sample)
|
||||
# readiness audit records sample_id; assign it within this outer save transaction
|
||||
# before the shared evidence-freeze service is invoked.
|
||||
db.session.flush()
|
||||
layout = _document_layout(annotation_document)
|
||||
if not any(
|
||||
isinstance(item, dict) and str(item.get('table_id') or '') == visual_main_table_id
|
||||
@@ -3124,6 +3515,8 @@ def save_draft(
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID',
|
||||
)
|
||||
sample.table_id = visual_main_table_id
|
||||
# Layout ready 后立即尝试冻结样本证据;尚未 ready 时保留草稿并由状态接口/自动标注入口继续门禁。
|
||||
refresh_profile_sample_readiness(profile=profile, sample=sample, actor_id=actor_id, commit=False)
|
||||
_refresh_training_sample_count(profile)
|
||||
audit_summary = _definition_audit_summary(definition)
|
||||
if previous_definition is None:
|
||||
|
||||
@@ -38,6 +38,10 @@ from app.services.shipping_notice.document_layout.xfa_contract import (
|
||||
XFA_PARSER_IDENTITY,
|
||||
)
|
||||
|
||||
|
||||
# 签名生成必须先解引用压缩 Layout 的 FileAsset 坐标证据;旧签名不具备该输入契约。
|
||||
LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION = 'v1'
|
||||
|
||||
def _profile(profile_id: int) -> ShippingOrderDocumentProfile:
|
||||
"""读取可验证草稿;发布和退役版本不能被新的草稿验证记录替代。"""
|
||||
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
|
||||
@@ -448,8 +452,15 @@ def _training_samples(profile: ShippingOrderDocumentProfile) -> list[ShippingOrd
|
||||
|
||||
|
||||
def _load_sample_layout(sample: ShippingOrderDocumentProfileSample) -> dict[str, Any]:
|
||||
"""加载样本冻结或当前 ready layout;签名只消费坐标证据摘要,不复制原件。"""
|
||||
from app.services.shipping_notice.document_layout.lifecycle import current_layout_snapshot
|
||||
"""加载样本冻结或当前 ready layout,并解引用压缩快照的 FileAsset 坐标证据。
|
||||
|
||||
冻结 Layout 是签名和发布校验的历史事实;当 payload 只保留
|
||||
``coordinate_evidence_ref`` 时,必须恢复其不可变坐标证据,不能误判为无版面证据。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
_hydrate_coordinate_evidence,
|
||||
current_layout_snapshot,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
@@ -460,6 +471,11 @@ def _load_sample_layout(sample: ShippingOrderDocumentProfileSample) -> dict[str,
|
||||
from app.models import ShippingDocumentLayoutVersion
|
||||
frozen = db.session.get(ShippingDocumentLayoutVersion, int(sample.layout_version_id))
|
||||
if frozen is not None and isinstance(frozen.payload_json, dict):
|
||||
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
|
||||
if document is not None:
|
||||
return _hydrate_coordinate_evidence(
|
||||
payload=dict(frozen.payload_json), document=document,
|
||||
)
|
||||
return dict(frozen.payload_json)
|
||||
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
|
||||
if document is None:
|
||||
@@ -675,6 +691,7 @@ def _build_coordinate_identity_snapshot(
|
||||
evidence = (snapshot.get('signature') or {}).get('evidence_quality') or {}
|
||||
return snapshot, {
|
||||
'signature_version': LAYOUT_SIGNATURE_ID,
|
||||
'evidence_contract_version': LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION,
|
||||
'signature_checksum': snapshot.get('signature_checksum'),
|
||||
'matcher_policy_version': MATCHER_POLICY_ID,
|
||||
'source_sample_count': evidence.get('source_sample_count') or len(samples),
|
||||
@@ -728,7 +745,15 @@ def _resolve_profile_identity_signature_run(
|
||||
or run.run_type != 'layout_signature'
|
||||
or run.status != 'passed'
|
||||
or run.definition_checksum != revision.definition_checksum
|
||||
or not _signature_uses_current_evidence_contract(run)
|
||||
):
|
||||
if auto_run:
|
||||
run_profile_identity_signature(
|
||||
profile.id, data={}, actor_id=actor_id, browser_session_id=browser_session_id,
|
||||
lease_token=lease_token, operation_id=str(operation_id or secrets.token_hex(16)),
|
||||
)
|
||||
db.session.refresh(profile)
|
||||
return _resolve_profile_identity_signature_run(profile, revision, auto_run=False)
|
||||
raise ValidationError(
|
||||
'Profile identity signature is stale for the current draft',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE',
|
||||
@@ -742,6 +767,12 @@ def _resolve_profile_identity_signature_run(
|
||||
return run
|
||||
|
||||
|
||||
def _signature_uses_current_evidence_contract(run: ShippingOrderDocumentProfileValidationRun) -> bool:
|
||||
"""仅允许已按当前 FileAsset 解引用契约生成的签名进入发布唯一性校验。"""
|
||||
summary = getattr(run, 'summary_json', None)
|
||||
return isinstance(summary, dict) and summary.get('evidence_contract_version') == LAYOUT_SIGNATURE_EVIDENCE_CONTRACT_VERSION
|
||||
|
||||
|
||||
def resolve_profile_identity_signature(
|
||||
profile: ShippingOrderDocumentProfile,
|
||||
revision: ShippingOrderDocumentProfileDraftRevision,
|
||||
@@ -785,10 +816,16 @@ def _match_thresholds(definition: dict[str, Any]) -> dict[str, float]:
|
||||
"""从 document_match 提取发布唯一性门禁阈值。"""
|
||||
document_match = definition.get('document_match') if isinstance(definition.get('document_match'), dict) else {}
|
||||
thresholds = document_match.get('scoring_thresholds') if isinstance(document_match.get('scoring_thresholds'), dict) else {}
|
||||
|
||||
def configured_or_default(source: dict[str, Any], key: str, default: float) -> float:
|
||||
"""保留合法的 0 阈值;只有缺失或空值才回退默认门禁。"""
|
||||
value = source.get(key)
|
||||
return float(default if value is None else value)
|
||||
|
||||
return {
|
||||
'minimum_score': float(document_match.get('minimum_score') or 0.9),
|
||||
'minimum_margin': float(document_match.get('minimum_margin') or 0.12),
|
||||
'evidence_coverage_minimum': float(thresholds.get('evidence_coverage_minimum') or 0.70),
|
||||
'minimum_score': configured_or_default(document_match, 'minimum_score', 0.9),
|
||||
'minimum_margin': configured_or_default(document_match, 'minimum_margin', 0.12),
|
||||
'evidence_coverage_minimum': configured_or_default(thresholds, 'evidence_coverage_minimum', 0.70),
|
||||
}
|
||||
|
||||
|
||||
@@ -1031,7 +1068,15 @@ def _resolve_layout_signature_run(
|
||||
or run.run_type != 'layout_signature'
|
||||
or run.status != 'passed'
|
||||
or run.definition_checksum != revision.definition_checksum
|
||||
or not _signature_uses_current_evidence_contract(run)
|
||||
):
|
||||
if auto_run:
|
||||
run_profile_identity_signature(
|
||||
profile.id, data={}, actor_id=actor_id, browser_session_id=browser_session_id,
|
||||
lease_token=lease_token, operation_id=str(operation_id or secrets.token_hex(16)),
|
||||
)
|
||||
db.session.refresh(profile)
|
||||
return _resolve_layout_signature_run(profile, revision, auto_run=False)
|
||||
raise ValidationError(
|
||||
'Layout signature is stale for the current draft',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_SIGNATURE_STALE',
|
||||
|
||||
@@ -13,6 +13,24 @@ backend/app/services/shipping_notice/order_extraction.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
def reconcile_review_case_after_unit(*, run: Any, unit: Any) -> Any:
|
||||
"""
|
||||
Unit 结果已消费时,确保 Review Case 后仍执行统一校验/自动推进协调。
|
||||
|
||||
Args:
|
||||
run: Unit 所属的订单抽取 Run。
|
||||
unit: 已消费、需要回放的 PDF Unit。
|
||||
|
||||
Returns:
|
||||
确保后的 Review Case;协调器副作用会刷新校验结果并按资格决定后续自动推进。
|
||||
"""
|
||||
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import maybe_stp_auto_create_for_run
|
||||
|
||||
case = ensure_review_case_for_unit(run=run, unit=unit)
|
||||
maybe_stp_auto_create_for_run(run=run)
|
||||
return case
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime
|
||||
@@ -34,7 +52,6 @@ from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
|
||||
from app.services.shipping_notice.business_fingerprint import (
|
||||
build_business_fingerprint,
|
||||
build_content_fingerprint,
|
||||
@@ -53,6 +70,47 @@ from app.services.shipping_notice.context_fields.runtime import canonical_mail_c
|
||||
from app.services.shipping_notice.order_extraction_workflow import frozen_document_text_for_parser
|
||||
|
||||
|
||||
def _discard_resolved_worker_field_conflicts(
|
||||
conflicts: list[dict[str, Any]],
|
||||
*,
|
||||
decisions: list[dict[str, Any]],
|
||||
blocked_fields: list[str],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""移除已由最终动态裁决解决的 Worker 早期字段证据缺失阻断。
|
||||
|
||||
Worker 可能在派生前先报告 ``evidence_missing``;Candidate 必须以
|
||||
persist_dynamic_order 的最终 Decision/blocked_fields 为准。仅移除字段级、
|
||||
字段完整性归属的早期缺证冲突:真实跨来源冲突、非字段完整性冲突,以及最终
|
||||
仍处于 blocked_fields 的必填或建单关键字段,一律保留。
|
||||
|
||||
Args:
|
||||
conflicts: Worker 原始阻断冲突。
|
||||
decisions: 动态 Schema 最终字段裁决。
|
||||
blocked_fields: 派生后最终仍阻断流程的字段编码。
|
||||
|
||||
Returns:
|
||||
仍应投影到 Candidate 的阻断冲突。
|
||||
"""
|
||||
unresolved = {str(code).strip() for code in blocked_fields if str(code or '').strip()}
|
||||
resolved_fields = {
|
||||
str(item.get('field_code') or '').strip()
|
||||
for item in decisions
|
||||
if isinstance(item, dict)
|
||||
and item.get('status') in {'accepted', 'corroborated', 'derived'}
|
||||
and str(item.get('field_code') or '').strip() not in unresolved
|
||||
}
|
||||
return [
|
||||
item for item in conflicts
|
||||
if not (
|
||||
str(item.get('field') or '').strip() in resolved_fields
|
||||
and str(item.get('reason') or '') == 'evidence_missing'
|
||||
and str(item.get('owning_gate_code') or '') in {
|
||||
'field_completeness', 'order_field_extraction',
|
||||
}
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _runtime_session_for_run(run: Any) -> ChatSession | SimpleNamespace:
|
||||
"""读取 Run 的 UI 会话;历史会话已清理时使用冻结身份继续持久化业务结果。
|
||||
|
||||
@@ -419,6 +477,11 @@ def persist_order_extraction_result(
|
||||
},
|
||||
frozen_evidence_text_by_document=frozen_evidence_text_by_document,
|
||||
)
|
||||
blocking_conflicts = _discard_resolved_worker_field_conflicts(
|
||||
blocking_conflicts,
|
||||
decisions=list(dynamic.get('decisions') or []),
|
||||
blocked_fields=list(dynamic.get('blocked_fields') or []),
|
||||
)
|
||||
if run_id is not None:
|
||||
dynamic['extraction'].run_id = int(run_id)
|
||||
layout_evidence_issues = [
|
||||
@@ -856,67 +919,103 @@ def persist_order_extraction_result(
|
||||
),
|
||||
)
|
||||
|
||||
auto_candidate_nos = [row.candidate_no for row in auto_candidates]
|
||||
create_result: dict[str, Any] | None = None
|
||||
if auto_candidate_nos:
|
||||
idem = f"extract:{current_snapshot[:48]}"
|
||||
create_result = create_shipping_batch_from_candidates(
|
||||
user_id=int(session.user_id),
|
||||
conversation_id=session.session_id,
|
||||
intake_nos=intake_nos,
|
||||
candidate_nos=auto_candidate_nos,
|
||||
create_idempotency_key=idem,
|
||||
)
|
||||
# 建批事务已在启动编排器前绑定 Task 与已接受 Extraction;此处只完成本轮提交收口。
|
||||
db.session.commit()
|
||||
else:
|
||||
# [STEP 4] 没有待处理订单时(空数组或仅明确非发货内容),消费 Intake 但不产生 Batch/Task。
|
||||
if not pending:
|
||||
now = datetime.utcnow()
|
||||
for intake in intakes:
|
||||
intake.parse_status = 'consumed'
|
||||
intake.consumed_at = now
|
||||
intake.order_extraction_status = 'completed'
|
||||
intake.updated_at = now
|
||||
db.session.commit()
|
||||
|
||||
create_data = (create_result or {}).get('data')
|
||||
create_data = create_data if isinstance(create_data, dict) else {}
|
||||
created = list(create_data.get('tasks') or [])
|
||||
opened_existing = list(
|
||||
(create_result or {}).get('opened_existing')
|
||||
or create_data.get('opened_existing')
|
||||
or []
|
||||
)
|
||||
for item in (create_result or {}).get('reconciliation_pending') or []:
|
||||
if not isinstance(item, dict):
|
||||
# [STEP 4] open_existing 是既有任务的安全跳转/字段对账,不是新建单路径。
|
||||
# 它必须在此单独收口,禁止借已删除批次编排器实现,也不得触发新单或自动推进。
|
||||
opened_existing: list[dict[str, Any]] = []
|
||||
for candidate in auto_candidates:
|
||||
if (
|
||||
candidate.duplicate_resolution != 'open_existing'
|
||||
or candidate.consumed_task_id is not None
|
||||
or candidate.validation_status != 'ready'
|
||||
):
|
||||
continue
|
||||
reconciliation = (
|
||||
item.get('reconciliation')
|
||||
if isinstance(item.get('reconciliation'), dict)
|
||||
else {}
|
||||
target_no = str(candidate.duplicate_target_task_no or '').strip().upper()
|
||||
if not target_no:
|
||||
continue
|
||||
target = (
|
||||
db.session.query(ShippingNotice)
|
||||
.filter_by(task_no=target_no, user_id=int(session.user_id))
|
||||
.with_for_update()
|
||||
.first()
|
||||
)
|
||||
pending.append({
|
||||
'candidate_no': item.get('candidate_no'),
|
||||
'task_no': item.get('task_no'),
|
||||
'reasons': [
|
||||
str(reconciliation.get('reason') or 'open_existing_reconciliation_required')
|
||||
],
|
||||
'reconciliation': reconciliation,
|
||||
if target is None:
|
||||
continue
|
||||
reconciliation: dict[str, Any] | None = None
|
||||
duplicate_status = str(candidate.duplicate_status or '').strip()
|
||||
if duplicate_status == 'exact_file':
|
||||
from app.services.shipping_notice.open_existing_reservation_backfill import (
|
||||
backfill_exact_file_open_existing_reservations,
|
||||
)
|
||||
|
||||
structured = (
|
||||
candidate.structured_result_json
|
||||
if isinstance(candidate.structured_result_json, dict)
|
||||
else {}
|
||||
)
|
||||
extraction = (
|
||||
structured.get('extraction')
|
||||
if isinstance(structured.get('extraction'), dict)
|
||||
else {}
|
||||
)
|
||||
reconciliation = backfill_exact_file_open_existing_reservations(
|
||||
task=target,
|
||||
candidate=candidate,
|
||||
candidate_summary=(
|
||||
structured.get('business_summary')
|
||||
if isinstance(structured.get('business_summary'), dict)
|
||||
else {}
|
||||
),
|
||||
duplicate_status=duplicate_status,
|
||||
duplicate_matches=[{'task_no': target.task_no}],
|
||||
verified_reservation_evidence=list(
|
||||
extraction.get('verified_reservation_evidence') or []
|
||||
),
|
||||
)
|
||||
# 对账服务仍以既有任务的动态字段及旧安全态为唯一依据;其内会在字段
|
||||
# 已安全补齐后推进到 parse_review,不能在这里二次推导或覆盖阶段。
|
||||
if (
|
||||
reconciliation.get('status') != 'applied'
|
||||
and reconciliation.get('reason') not in {
|
||||
'duplicate_status_not_exact_file',
|
||||
'target_already_complete',
|
||||
'target_task_not_safe',
|
||||
}
|
||||
):
|
||||
candidate.selected = False
|
||||
pending_item = {
|
||||
'candidate_no': candidate.candidate_no,
|
||||
'task_no': target.task_no,
|
||||
'reasons': [str(reconciliation.get('reason') or 'open_existing_reconciliation_required')],
|
||||
'reconciliation': reconciliation,
|
||||
}
|
||||
pending.append(pending_item)
|
||||
pending_by_intake[int(candidate.intake_id)].append(pending_item)
|
||||
continue
|
||||
candidate.consumed_task_id = int(target.id)
|
||||
candidate.updated_at = datetime.utcnow()
|
||||
opened_existing.append({
|
||||
'candidate_no': candidate.candidate_no,
|
||||
'task_no': target.task_no,
|
||||
**({'reconciliation': reconciliation} if reconciliation is not None else {}),
|
||||
})
|
||||
created_count = len(created)
|
||||
|
||||
# Candidate 只进入 Review Case/STP;禁止旧抽取链绕过确认直接创建批次或 Task。
|
||||
if not pending:
|
||||
now = datetime.utcnow()
|
||||
for intake in intakes:
|
||||
intake.parse_status = 'consumed'
|
||||
intake.consumed_at = now
|
||||
intake.order_extraction_status = 'completed'
|
||||
intake.updated_at = now
|
||||
db.session.commit()
|
||||
|
||||
created: list[dict[str, Any]] = []
|
||||
created_count = 0
|
||||
opened_existing_count = len(opened_existing)
|
||||
created_with_missing_fields_count = sum(
|
||||
1
|
||||
for candidate in auto_candidates
|
||||
if candidate.duplicate_resolution != 'open_existing' and candidate.missing_fields_json
|
||||
)
|
||||
# 下层响应缺失任务明细属于契约异常;摘要只能陈述已持久化并返回的 Task,不能回退到 Candidate 数。
|
||||
created_with_missing_fields_count = min(created_with_missing_fields_count, created_count)
|
||||
created_with_missing_fields_count = 0
|
||||
result = {
|
||||
'status': 'ok',
|
||||
'request_id': request_id,
|
||||
'batch_no': create_result.get('batch_no') if create_result else None,
|
||||
'created': created,
|
||||
'opened_existing': opened_existing,
|
||||
'pending_orders': pending,
|
||||
@@ -1014,7 +1113,6 @@ def submit_order_extraction_run_result(
|
||||
result = {
|
||||
'status': 'ok',
|
||||
'request_id': str(run.run_no),
|
||||
'batch_no': None,
|
||||
'created': [{'task_no': task_no} for task_no in task_nos],
|
||||
'opened_existing': [],
|
||||
'pending_orders': [{'candidate_no': item.candidate_no} for item in pending],
|
||||
@@ -1060,7 +1158,6 @@ def submit_order_extraction_run_result(
|
||||
result = {
|
||||
'status': 'ok',
|
||||
'request_id': str(run.run_no),
|
||||
'batch_no': None,
|
||||
'created': [],
|
||||
'opened_existing': [],
|
||||
'pending_orders': [],
|
||||
@@ -1258,7 +1355,6 @@ def submit_order_extraction_unit_result(
|
||||
result = {
|
||||
'status': 'ok',
|
||||
'request_id': str(run.run_no),
|
||||
'batch_no': None,
|
||||
'created': [{'task_no': task_no} for task_no in task_nos],
|
||||
'opened_existing': [],
|
||||
'pending_orders': [],
|
||||
@@ -1271,8 +1367,7 @@ def submit_order_extraction_unit_result(
|
||||
'idempotent_replay': True,
|
||||
'unit_id': int(unit.id),
|
||||
}
|
||||
from app.services.shipping_notice.order_review_service import ensure_review_case_for_unit
|
||||
ensure_review_case_for_unit(run=run, unit=unit)
|
||||
reconcile_review_case_after_unit(run=run, unit=unit)
|
||||
return result
|
||||
|
||||
session = _runtime_session_for_run(run)
|
||||
|
||||
Loaded 100 of 402 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user