Merge branch 'dev-new' into runny827
This commit is contained in:
commit
f1beb6fefb
112 files changed
+6300
-586
No files matched your search
@@ -1,11 +1,12 @@
|
||||
"""
|
||||
backend/app/api/contract_payment.py
|
||||
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要和同步 API。
|
||||
用途:采购合同付款预警 Agent 的合同台账、付款计划、待发送摘要、台账汇总卡和同步 API。
|
||||
依赖:JWT 当前用户、统一响应 envelope、ForbiddenError、contract_payment 服务和通用 Job 队列。
|
||||
逻辑:页面查询合同、节点与本周待发送摘要;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
逻辑:页面查询合同、节点、本周待发送摘要与四张汇总卡;同步和预警操作入队,避免请求线程执行外部系统和企微调用。
|
||||
合同序列化时对 parse_issues 去重,避免 MinerU 重复抽取把同一原因展示多遍。
|
||||
鉴权:所有接口要求已登录且具备 `contract_payment.access`(admin 默认开,可显式授予普通用户)。
|
||||
鉴权:查询接口要求 `contract_payment.access`(admin 默认开,可显式授予普通用户);
|
||||
同步/扫描/周汇总发送仅 `role=admin`。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -28,6 +29,11 @@ from app.models import (
|
||||
FileAsset,
|
||||
)
|
||||
from app.services.contract_payment.alert_service import build_weekly_alert_summary
|
||||
from app.services.contract_payment.ledger_focus import (
|
||||
LEDGER_FOCUS_VALUES,
|
||||
apply_ledger_focus,
|
||||
ledger_focus_counts,
|
||||
)
|
||||
from app.services.contract_payment.parse_service import unique_parse_issues
|
||||
from app.services.contract_payment.sync_service import build_payment_plan, build_payment_plan_from_bytes
|
||||
from app.services.file_assets.service import read_asset_bytes
|
||||
@@ -92,6 +98,30 @@ def _require_contract_payment_access():
|
||||
return user
|
||||
|
||||
|
||||
def _require_contract_payment_admin():
|
||||
"""
|
||||
确保当前用户既有合同付款预警访问权,又是平台管理员。
|
||||
|
||||
核心逻辑:普通授权用户可查台账;同步 OA、强制覆盖、批量重解析、扫描预警和发送周汇总
|
||||
会改写外部系统或触发企微,因此仅 `role=admin` 可调用。
|
||||
|
||||
Args:
|
||||
无。当前请求身份由 JWT 上下文提供。
|
||||
Returns:
|
||||
已认证的管理员用户。
|
||||
Raises:
|
||||
UnauthorizedError: 请求没有有效登录身份。
|
||||
ForbiddenError: 无合同付款访问权,或已授权但不是管理员。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
if getattr(user, "role", None) != "admin":
|
||||
raise ForbiddenError(
|
||||
'Admin privilege required for contract payment jobs',
|
||||
code='CONTRACT_PAYMENT.ADMIN_REQUIRED',
|
||||
)
|
||||
return user
|
||||
|
||||
|
||||
def _serialize_contract(row: ContractPaymentContract) -> dict:
|
||||
"""
|
||||
序列化合同台账、付款节点及预警记录,供列表和详情共用。
|
||||
@@ -170,7 +200,7 @@ def list_contracts():
|
||||
"""
|
||||
查询合同台账。
|
||||
|
||||
核心逻辑:支持合同编号、流程编号、采购单号和解析状态筛选,并按 offset 分页返回台账,避免工作台一次加载全部合同。
|
||||
核心逻辑:支持合同编号、流程编号、采购单号、供应商名称、解析状态和汇总卡口径(focus)筛选,并按 offset 分页返回台账。
|
||||
Args:
|
||||
无。筛选条件从 query string 读取。
|
||||
Returns:
|
||||
@@ -185,6 +215,7 @@ def list_contracts():
|
||||
ContractPaymentContract.contract_no.ilike(like)
|
||||
| ContractPaymentContract.workflow_no.ilike(like)
|
||||
| ContractPaymentContract.purchase_order_no.ilike(like)
|
||||
| ContractPaymentContract.supplier_name.ilike(like)
|
||||
)
|
||||
parse_status = str(request.args.get("parse_status") or "").strip()
|
||||
review_only = str(request.args.get("review_only") or "").strip().lower() in {"1", "true", "yes"}
|
||||
@@ -195,6 +226,13 @@ def list_contracts():
|
||||
else:
|
||||
# 自动付款预警台账仅展示关键解析事实完整的合同;待确认合同由独立导航集中处理。
|
||||
query = query.filter_by(parse_status="parsed")
|
||||
focus = str(request.args.get("focus") or "").strip()
|
||||
if focus:
|
||||
if review_only:
|
||||
raise ValidationError("待确认列表不支持汇总卡筛选", details={"focus": focus})
|
||||
if focus not in LEDGER_FOCUS_VALUES:
|
||||
raise ValidationError("不支持的汇总卡筛选", details={"focus": focus})
|
||||
query = apply_ledger_focus(query, focus, session=db.session)
|
||||
page = max(_query_int("page", default=1), 1)
|
||||
page_size = min(max(_query_int("page_size", default=20), 1), 100)
|
||||
total = query.count()
|
||||
@@ -215,6 +253,21 @@ def list_contracts():
|
||||
}, request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
@contract_payment_bp.route("/contracts/summary", methods=["GET"])
|
||||
def get_ledger_summary():
|
||||
"""
|
||||
查询合同台账四张汇总卡的合同份数。
|
||||
|
||||
核心逻辑:始终统计全部已解析台账,不跟页面 keyword;口径与点卡片过滤列表共用 ledger_focus。
|
||||
Args:
|
||||
无。
|
||||
Returns:
|
||||
标准成功 envelope,含 due、overdue、needs_completion、due_this_month。
|
||||
"""
|
||||
_require_contract_payment_access()
|
||||
return ok(ledger_focus_counts(session=db.session), request_id=getattr(g, "request_id", None))
|
||||
|
||||
|
||||
def _query_int(key: str, *, default: int) -> int:
|
||||
"""读取正整数查询参数;非法值回退默认值,防止分页接口返回 500。"""
|
||||
try:
|
||||
@@ -279,12 +332,15 @@ def enqueue_sync():
|
||||
"""
|
||||
将 OA 合同、验收和厂商预付款请款同步任务入队。
|
||||
|
||||
核心逻辑:仅管理员可入队;force / reparse_existing 仍走同一 Job,避免普通授权用户改写 OA 字段。
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
Raises:
|
||||
ForbiddenError: 非管理员或无合同付款访问权。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
user = _require_contract_payment_admin()
|
||||
data = request.get_json(silent=True) or {}
|
||||
force_value = data.get("force", False)
|
||||
if not isinstance(force_value, bool):
|
||||
@@ -303,12 +359,15 @@ def enqueue_alert_scan():
|
||||
"""
|
||||
将四阶段三轮合同付款预警扫描任务入队。
|
||||
|
||||
核心逻辑:仅管理员可手动补扫;日常扫描仍由排程触发。
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
Raises:
|
||||
ForbiddenError: 非管理员或无合同付款访问权。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
user = _require_contract_payment_admin()
|
||||
job_id = enqueue(JobType.CONTRACT_PAYMENT_ALERT, {}, domain="procurement_contract", business_ref="daily-alert", created_by_id=user.id, message="等待计算合同付款预警")
|
||||
return ok({"job_id": job_id}, request_id=getattr(g, "request_id", None), status=202)
|
||||
|
||||
@@ -331,12 +390,15 @@ def get_alert_summary():
|
||||
def enqueue_weekly_alert_send():
|
||||
"""将合同付款预警周汇总发送任务入队。
|
||||
|
||||
核心逻辑:仅管理员可手动补发;周五 18:00 排程不受此限制。
|
||||
Args:
|
||||
无。操作用户由 JWT 上下文读取。
|
||||
Returns:
|
||||
HTTP 202 与后台 Job ID。
|
||||
Raises:
|
||||
ForbiddenError: 非管理员或无合同付款访问权。
|
||||
"""
|
||||
user = _require_contract_payment_access()
|
||||
user = _require_contract_payment_admin()
|
||||
job_id = enqueue(
|
||||
JobType.CONTRACT_PAYMENT_ALERT_WEEKLY,
|
||||
{},
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
"""
|
||||
backend/app/api/kb/common.py
|
||||
|
||||
用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览)。
|
||||
用途:知识库 API 共享 helper(鉴权、序列化、Markdown 预览、下载头)。
|
||||
依赖:app.core.*、models、services/kb/storage、edkb_system。
|
||||
逻辑:dify/groups/documents/jobs 子模块共用;存储读写见 services/kb/storage。
|
||||
"""
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
from flask import current_app
|
||||
from sqlalchemy.exc import DatabaseError, OperationalError
|
||||
|
||||
@@ -31,6 +34,31 @@ def require_user():
|
||||
raise UnauthorizedError()
|
||||
return user
|
||||
|
||||
|
||||
def build_content_disposition(filename: str, *, as_attachment: bool = True) -> str:
|
||||
"""
|
||||
构造 RFC 5987 Content-Disposition,保证中文源文件名不被浏览器拼成怪名。
|
||||
|
||||
核心逻辑:quoted ASCII 回退名(保留扩展名)+ filename*=UTF-8''百分号编码原名。
|
||||
浏览器优先 filename*;旧客户端才用 ASCII 回退。ASCII 段必须加引号且不含分号。
|
||||
|
||||
Args:
|
||||
filename: 用户可见的原始文件名。禁止路径分隔与换行。
|
||||
as_attachment: True 为下载(attachment),False 为预览(inline)。
|
||||
|
||||
Returns:
|
||||
可直接写入响应头的 Content-Disposition 字符串。
|
||||
"""
|
||||
safe_name = Path(str(filename or '').replace('\\', '/')).name
|
||||
safe_name = safe_name.replace('\r', '').replace('\n', '').replace('"', '').strip() or 'download'
|
||||
suffix = Path(safe_name).suffix
|
||||
stem_ascii = Path(safe_name).stem.encode('ascii', 'ignore').decode('ascii').strip() or 'download'
|
||||
ascii_name = f'{stem_ascii}{suffix}' if suffix else stem_ascii
|
||||
encoded = quote(safe_name, safe='')
|
||||
disposition = 'attachment' if as_attachment else 'inline'
|
||||
return f'{disposition}; filename="{ascii_name}"; filename*=UTF-8\'\'{encoded}'
|
||||
|
||||
|
||||
def run_db_read(label: str, loader):
|
||||
try:
|
||||
return loader()
|
||||
|
||||
@@ -3,13 +3,19 @@ backend/app/api/kb/documents.py
|
||||
|
||||
用途:知识库文档版本、Markdown、上传/清洗/同步 API(薄路由层)。
|
||||
依赖:kb.blueprint、kb.common、services/kb/document_service。
|
||||
逻辑:/documents* 与 /document-versions* 路由;业务见 document_service。
|
||||
逻辑:/documents* 与 /document-versions* 路由;业务见 document_service;源文件下载覆盖 RFC 5987 Content-Disposition。
|
||||
"""
|
||||
from flask import jsonify, request, send_file
|
||||
|
||||
from app import db
|
||||
from app.api.kb.blueprint import knowledge_base_bp
|
||||
from app.api.kb.common import require_user, serialize_document, serialize_sync_record, serialize_version
|
||||
from app.api.kb.common import (
|
||||
build_content_disposition,
|
||||
require_user,
|
||||
serialize_document,
|
||||
serialize_sync_record,
|
||||
serialize_version,
|
||||
)
|
||||
from app.core.auth.jwt import get_current_user
|
||||
from app.core.decorators import require_admin
|
||||
from app.services.kb import document_service
|
||||
@@ -24,10 +30,18 @@ def list_document_versions(document_id: int):
|
||||
|
||||
@knowledge_base_bp.route('/document-versions/<int:version_id>/source-file', methods=['GET'])
|
||||
def get_document_version_source_file(version_id: int):
|
||||
"""
|
||||
返回知识库版本原始文件。
|
||||
|
||||
用途:工作台源文件信息弹窗下载原件;?download=1 时按附件下发,保存名与上传时一致。
|
||||
核心逻辑:send_file 后再覆盖 Content-Disposition 为 RFC 5987,避免 Werkzeug ASCII 回退名无引号导致浏览器拼名。
|
||||
"""
|
||||
require_user()
|
||||
source_path, filename = document_service.resolve_source_file_path(version_id)
|
||||
as_attachment = str(request.args.get('download') or '').strip() == '1'
|
||||
return send_file(source_path, as_attachment=as_attachment, download_name=filename)
|
||||
response = send_file(source_path, as_attachment=as_attachment, download_name=filename)
|
||||
response.headers['Content-Disposition'] = build_content_disposition(filename, as_attachment=as_attachment)
|
||||
return response
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/document-versions/<int:version_id>/training-preview-file', methods=['GET'])
|
||||
@@ -41,7 +55,9 @@ def get_training_preview_file(version_id: int):
|
||||
require_user()
|
||||
preview_path, filename = document_service.resolve_training_preview_file_path(version_id)
|
||||
as_attachment = str(request.args.get('download') or '').strip() == '1'
|
||||
return send_file(preview_path, as_attachment=as_attachment, download_name=filename)
|
||||
response = send_file(preview_path, as_attachment=as_attachment, download_name=filename)
|
||||
response.headers['Content-Disposition'] = build_content_disposition(filename, as_attachment=as_attachment)
|
||||
return response
|
||||
|
||||
|
||||
@knowledge_base_bp.route('/documents/<int:document_id>/sync-records', methods=['GET'])
|
||||
|
||||
@@ -4,10 +4,11 @@ backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
用途:消费订单抽取 Run,使用固定模板/通用确定性解析并持久化可复核结果。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务、版面排程、
|
||||
ensure_workflow_items_for_run(物化后兜底建 Item)、order_extraction_merge、
|
||||
order_supplement_merge(仅 eml)。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行;每个 Unit 按 STP route_decision
|
||||
直通或落 provisional;needs_review 剥离验收标记;不调用 Dify 主链。
|
||||
阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
|
||||
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行;有 ready PDF 即按 Unit 抽取并下游推进,
|
||||
兄弟文件 layout pending 时 Job 以 partial_units_done 回到 waiting_layout;
|
||||
每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记;
|
||||
不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
|
||||
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
|
||||
"""
|
||||
|
||||
@@ -44,6 +45,8 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
complete_input_freeze,
|
||||
mark_order_extraction_persistence_started,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
order_extraction_layouts_pending,
|
||||
order_extraction_ready_document_ids,
|
||||
materialize_order_extraction_run_inputs,
|
||||
ensure_workflow_items_for_run,
|
||||
progress_ready_extraction_unit,
|
||||
@@ -661,7 +664,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行一次纯确定性订单抽取 Job。
|
||||
|
||||
核心逻辑:物化附件与排版面 Job 纳入主 try;排程 ValidationError(如 MinerU 关闭)非重试,同步将 Run 标为 failed。
|
||||
核心逻辑:物化附件与排版面 Job 纳入主 try;有 ready PDF 时按 Unit 抽取并立刻下游推进;
|
||||
仍有 layout pending 时 Job 成功收口并回到 waiting_layout,不终态 Run。
|
||||
排程 ValidationError(如 MinerU 关闭)非重试,同步将 Run 标为 failed。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文,仅用于安全日志。
|
||||
@@ -703,47 +708,72 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
ensure_workflow_items_for_run(run, stage_when_ready='extracting')
|
||||
schedule_order_extraction_layouts(run, created_by_id=run.user_id)
|
||||
|
||||
# [STEP 2] 订单解析绝不能把仍在生成或缺失的版面快照当作“没有订单表”。
|
||||
# [STEP 2] 按 Unit 放行:仅当零 ready PDF 时整 Job defer;有 ready 则抽 ready Unit。
|
||||
layout_issues = order_extraction_layout_prerequisite_issues(run)
|
||||
if 'layout_pending' in layout_issues.values():
|
||||
# 布局等待期已进入 freezing;仍禁止追加,待布局就绪后完成冻结。
|
||||
run.phase = 'waiting_layout'
|
||||
record_run_progress(run=run, event_code='layout_parsing_started', commit=False)
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'waiting_layout': True,
|
||||
'handoff_status': 'deferred_to_layout',
|
||||
},
|
||||
message='已转交附件版面解析,完成后自动创建后继订单识别任务',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
if layout_issues:
|
||||
complete_input_freeze(run)
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_prerequisite_failed')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', phase='layout_prerequisite_failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
error_message='Order PDF layout prerequisites are incomplete',
|
||||
)
|
||||
record_run_progress(
|
||||
run=run, event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
summary={'document_count': len(layout_issues)}, job_id=job.id, commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'layout_issues': layout_issues}, message='订单附件解析条件不完整', owned_attempt=owned_attempt)
|
||||
return
|
||||
pending_layout_ids = {
|
||||
document_id
|
||||
for document_id, code in layout_issues.items()
|
||||
if code == 'layout_pending'
|
||||
}
|
||||
hard_layout_issues = {
|
||||
document_id: code
|
||||
for document_id, code in layout_issues.items()
|
||||
if code != 'layout_pending'
|
||||
}
|
||||
ready_document_ids = order_extraction_ready_document_ids(run)
|
||||
if not ready_document_ids:
|
||||
if pending_layout_ids:
|
||||
# 布局等待期已进入 freezing;仍禁止追加,待任一布局就绪后再抽。
|
||||
run.phase = 'waiting_layout'
|
||||
record_run_progress(run=run, event_code='layout_parsing_started', commit=False)
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'waiting_layout': True,
|
||||
'handoff_status': 'deferred_to_layout',
|
||||
},
|
||||
message='已转交附件版面解析,完成后自动创建后继订单识别任务',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
if hard_layout_issues:
|
||||
complete_input_freeze(run)
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_prerequisite_failed')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', phase='layout_prerequisite_failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
error_message='Order PDF layout prerequisites are incomplete',
|
||||
)
|
||||
record_run_progress(
|
||||
run=run, event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
summary={'document_count': len(hard_layout_issues)}, job_id=job.id, commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
result={'run_no': run.run_no, 'layout_issues': hard_layout_issues},
|
||||
message='订单附件解析条件不完整',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
|
||||
# [STEP 3] 所有 PDF 布局就绪后重建快照,此时才冻结带坐标证据的执行计划。
|
||||
# [STEP 3] 至少一个 PDF 版式就绪即可建 Plan 并冻结输入;未 ready 的 Unit 留 pending。
|
||||
plan = materialize_order_extraction_run_inputs(run)
|
||||
if plan is None:
|
||||
raise RuntimeError('order extraction plan was not finalized')
|
||||
# [BE-F03] 物化完成 → frozen,再进入 processing。
|
||||
complete_input_freeze(run)
|
||||
# 物化可能回填刚就绪的坐标证据;按最新前置条件决定本轮抽哪些 Unit。
|
||||
layout_issues = order_extraction_layout_prerequisite_issues(run)
|
||||
pending_layout_ids = {
|
||||
document_id
|
||||
for document_id, code in layout_issues.items()
|
||||
if code == 'layout_pending'
|
||||
}
|
||||
ready_document_ids = order_extraction_ready_document_ids(run)
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase='deterministic_parsing')
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
@@ -751,6 +781,7 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
selection = (run.input_snapshot_json or {}).get('attachment_selection') or {}
|
||||
max_runtime_seconds = max(0, int(selection.get('max_runtime_seconds') or 0))
|
||||
runtime_budget_stopped = False
|
||||
layout_blocked_in_wave = False
|
||||
run.current_job_id = job.id
|
||||
run.attempt_count = owned_attempt
|
||||
record_run_progress(
|
||||
@@ -759,6 +790,8 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
summary={
|
||||
**_selection_progress_summary(run),
|
||||
'unit_count': int(getattr(plan, 'unit_count', 0) or 0),
|
||||
'ready_document_count': len(ready_document_ids),
|
||||
'pending_layout_count': len(pending_layout_ids),
|
||||
'job_attempt': owned_attempt,
|
||||
},
|
||||
job_id=job.id,
|
||||
@@ -829,6 +862,29 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
continue
|
||||
if unit.status == 'review_required':
|
||||
continue
|
||||
unit_layout_issue = layout_issues.get(int(unit.document_id or 0))
|
||||
if unit_layout_issue == 'layout_pending':
|
||||
layout_blocked_in_wave = True
|
||||
continue
|
||||
if unit_layout_issue:
|
||||
# 硬前置失败:pending→routing→failed,避免 Unit 永久挂起阻塞收口。
|
||||
if str(unit.status or '') == 'pending':
|
||||
transition_order_extraction_unit(unit, target_status='routing')
|
||||
transition_order_extraction_unit(
|
||||
unit,
|
||||
target_status='failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
error_message=f'layout prerequisite: {unit_layout_issue}',
|
||||
)
|
||||
record_unit_progress(
|
||||
run=run,
|
||||
unit=unit,
|
||||
event_code='technical_failed',
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED',
|
||||
summary={'layout_issue': unit_layout_issue},
|
||||
job_id=job.id,
|
||||
)
|
||||
continue
|
||||
unit_orders = _process_unit_with_retries(run=run, unit=unit, job=job, owned_attempt=owned_attempt)
|
||||
db.session.expire_all()
|
||||
unit = db.session.get(ShippingOrderProcessingUnit, int(unit.id))
|
||||
@@ -839,6 +895,9 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
wave_orders.extend(unit_orders)
|
||||
if runtime_budget_stopped:
|
||||
break
|
||||
# 同批仍有 layout pending 的 Unit:禁止扩附,交 partial defer。
|
||||
if layout_blocked_in_wave:
|
||||
break
|
||||
wave_orders = _wave_orders_for_expansion(run, orders=wave_orders)
|
||||
expansion_reason_codes = _expansion_trigger_reason_codes(wave_units=units, wave_orders=wave_orders)
|
||||
|
||||
@@ -1094,6 +1153,23 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
job_id=job.id,
|
||||
)
|
||||
raise
|
||||
# [STEP] 仍有兄弟文件版式未完成:已抽 Unit 保留,Job 成功收口并回到 waiting_layout,禁止 Run 终态。
|
||||
if layout_blocked_in_wave or order_extraction_layouts_pending(run):
|
||||
run.phase = 'waiting_layout'
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'waiting_layout': True,
|
||||
'handoff_status': 'partial_units_done',
|
||||
'merged_unit_count': len(pending_merge_unit_ids),
|
||||
'ready_document_ids': sorted(ready_document_ids),
|
||||
},
|
||||
message='已完成就绪附件的订单识别,其余附件版面解析完成后继续',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
orders = persisted_orders + merged_orders
|
||||
execution = {
|
||||
'mode': 'deterministic',
|
||||
|
||||
@@ -280,22 +280,24 @@ def _node_paid_date(node: ContractPaymentNode) -> str | None:
|
||||
|
||||
|
||||
def _build_excel(items) -> tuple[bytes, dict[str, object]]:
|
||||
"""生成收件人专属逐笔付款预警明细 Excel。"""
|
||||
"""生成收件人专属逐笔付款预警明细 Excel。
|
||||
|
||||
核心逻辑:按合同/节点逐行输出;「收件人」列写该批次实际收件人姓名,「状态」列写中文,不再输出岗位名称或 pending 英文码。
|
||||
"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "付款预警明细"
|
||||
headers = ["合同编号", "采购编号", "供应商", "合同金额", "付款阶段", "付款金额", "比例", "付款日期", "到期日", "预警轮次", "收件岗位", "状态"]
|
||||
headers = ["合同编号", "采购编号", "供应商", "合同金额", "付款阶段", "付款金额", "比例", "付款日期", "到期日", "预警轮次", "收件人", "状态"]
|
||||
ws.append(headers)
|
||||
for cell in ws[1]:
|
||||
cell.font = Font(bold=True)
|
||||
counts = Counter()
|
||||
for alert, contract, node, _user in items:
|
||||
role = _ALERT_RULES[node.node_type][alert.alert_round - 1][1]
|
||||
for alert, contract, node, user in items:
|
||||
ws.append([
|
||||
contract.contract_no or "待解析", contract.purchase_order_no or "—", contract.supplier_name or "—",
|
||||
str(contract.total_amount or ""), _node_label(node.node_type), str(node.amount or ""),
|
||||
str(node.percentage or ""), _node_paid_date(node) or "—", (node.due_date or node.anchor_date).isoformat() if (node.due_date or node.anchor_date) else "—",
|
||||
f"第{alert.alert_round}次", _role_label(role), alert.status,
|
||||
f"第{alert.alert_round}次", _recipient_display_name(user), _alert_status_label(alert.status),
|
||||
])
|
||||
counts[node.node_type] += 1
|
||||
ws.freeze_panes = "A2"
|
||||
@@ -305,6 +307,25 @@ def _build_excel(items) -> tuple[bytes, dict[str, object]]:
|
||||
return output.getvalue(), {"total": len(items), "stages": {_node_label(k): v for k, v in counts.items()}}
|
||||
|
||||
|
||||
def _recipient_display_name(user: User | None) -> str:
|
||||
"""
|
||||
返回 Excel「收件人」列展示的人名。
|
||||
|
||||
核心逻辑:优先真实姓名;姓名为空时回退用户名,避免再写出岗位名称。
|
||||
Args:
|
||||
user: 本行预警对应的系统用户;缺失时写「—」。
|
||||
Returns:
|
||||
去空白后的姓名或用户名;都没有时为「—」。
|
||||
"""
|
||||
if user is None:
|
||||
return "—"
|
||||
name = str(getattr(user, "real_name", None) or "").strip()
|
||||
if name:
|
||||
return name
|
||||
username = str(getattr(user, "username", None) or "").strip()
|
||||
return username or "—"
|
||||
|
||||
|
||||
def _build_summary_message(summary: dict[str, object]) -> str:
|
||||
stages = summary.get("stages") or {}
|
||||
detail = "、".join(f"{key}{value}笔" for key, value in stages.items()) or "无"
|
||||
@@ -464,6 +485,22 @@ def _node_label(node_type: str) -> str:
|
||||
return {"prepayment": "预付款", "shipment": "出货款", "acceptance": "验收款", "warranty": "质保款"}.get(node_type, node_type)
|
||||
|
||||
|
||||
def _role_label(role: str) -> str:
|
||||
"""返回提醒岗位中文名称。"""
|
||||
return {"owner": "采购负责人", "department_head": "采购部负责人", "procurement_leader": "采购分管领导"}.get(role, role)
|
||||
def _alert_status_label(status: str | None) -> str:
|
||||
"""返回预警状态的中文名称,供企微 Excel「状态」列使用。
|
||||
|
||||
核心逻辑:与工作台 alertStatus 口径一致;未知编码原样回写,避免掩盖新增状态。
|
||||
Args:
|
||||
status: 预警记录内部状态码。
|
||||
Returns:
|
||||
中文状态;空值写「—」。
|
||||
"""
|
||||
code = str(status or "").strip().lower()
|
||||
if not code:
|
||||
return "—"
|
||||
return {
|
||||
"pending": "待发送",
|
||||
"sent": "已发送",
|
||||
"failed": "发送失败",
|
||||
"resolved": "已关闭",
|
||||
"sending": "发送中",
|
||||
}.get(code, str(status).strip())
|
||||
@@ -0,0 +1,220 @@
|
||||
"""
|
||||
backend/app/services/contract_payment/ledger_focus.py
|
||||
|
||||
用途:合同台账汇总卡口径——即将到期、逾期未付、待补充、本月应付,均按合同计数。
|
||||
依赖:ContractPaymentContract、ContractPaymentNode、业务时区 Asia/Shanghai。
|
||||
逻辑:由 list/summary API 调用;分类规则与台账行状态标签对齐,本月应付可与前两项重叠。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from datetime import date, datetime
|
||||
from typing import Any, Iterable
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from sqlalchemy.orm import Query, Session
|
||||
from sqlalchemy.sql.expression import false
|
||||
|
||||
from app.models import ContractPaymentContract, ContractPaymentNode
|
||||
|
||||
LEDGER_FOCUS_DUE = "due"
|
||||
LEDGER_FOCUS_OVERDUE = "overdue"
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION = "needs_completion"
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH = "due_this_month"
|
||||
LEDGER_FOCUS_VALUES = {
|
||||
LEDGER_FOCUS_DUE,
|
||||
LEDGER_FOCUS_OVERDUE,
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION,
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH,
|
||||
}
|
||||
_NEAR_DUE_DAYS = 7
|
||||
_SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||
|
||||
|
||||
def business_today(*, today: date | None = None) -> date:
|
||||
"""
|
||||
返回汇总卡使用的业务日(上海日历)。
|
||||
|
||||
Args:
|
||||
today: 测试注入的业务日;缺省为 Asia/Shanghai 当天。
|
||||
Returns:
|
||||
用于 7 日内到期、逾期和本月判断的日期。
|
||||
"""
|
||||
return today or datetime.now(_SHANGHAI).date()
|
||||
|
||||
|
||||
def node_due_reference(due_date: date | None, anchor_date: date | None) -> date | None:
|
||||
"""
|
||||
付款节点到期判断基准日。
|
||||
|
||||
核心逻辑:与前台 paymentStatus.nodeDueReference 一致,优先 due_date,否则回退 anchor_date。
|
||||
Args:
|
||||
due_date: 节点到期日。
|
||||
anchor_date: 节点锚点日。
|
||||
Returns:
|
||||
可用于比较的日期;两者皆空时为 None。
|
||||
"""
|
||||
return due_date or anchor_date
|
||||
|
||||
|
||||
def classify_ledger_status(
|
||||
*,
|
||||
contract_status: str | None,
|
||||
parse_status: str | None,
|
||||
nodes: Iterable[dict[str, Any]],
|
||||
today: date,
|
||||
) -> str:
|
||||
"""
|
||||
按合同聚合出台账状态,与列表「状态」列一致。
|
||||
|
||||
核心逻辑:非激活或待确认 → 待补充;无进行中节点则按是否已付分为已完成/待补充;
|
||||
进行中节点若已过到期日 → 逾期,若在今天起 7 天内 → 即将到期,否则进行中。
|
||||
Args:
|
||||
contract_status: 合同主状态。
|
||||
parse_status: 解析状态。
|
||||
nodes: 轻量节点 dict,含 status / due_date / anchor_date / paid_at。
|
||||
today: 业务日。
|
||||
Returns:
|
||||
overdue / due / active / completed / needs_completion。
|
||||
"""
|
||||
node_list = list(nodes)
|
||||
if str(contract_status or "").strip() != "active" or str(parse_status or "").strip() == "needs_review":
|
||||
return LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
if not node_list:
|
||||
return LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
active = [node for node in node_list if str(node.get("status") or "").strip().lower() == "active"]
|
||||
if not active:
|
||||
has_paid = any(
|
||||
str(node.get("status") or "").strip().lower() == "paid" or bool(node.get("paid_at"))
|
||||
for node in node_list
|
||||
)
|
||||
return "completed" if has_paid else LEDGER_FOCUS_NEEDS_COMPLETION
|
||||
refs = [
|
||||
ref
|
||||
for node in active
|
||||
if (ref := node_due_reference(node.get("due_date"), node.get("anchor_date")))
|
||||
]
|
||||
if any((ref - today).days < 0 for ref in refs):
|
||||
return LEDGER_FOCUS_OVERDUE
|
||||
if any(0 <= (ref - today).days <= _NEAR_DUE_DAYS for ref in refs):
|
||||
return LEDGER_FOCUS_DUE
|
||||
return "active"
|
||||
|
||||
|
||||
def has_unpaid_due_this_month(nodes: Iterable[dict[str, Any]], today: date) -> bool:
|
||||
"""
|
||||
合同是否有未付节点的到期日落在本自然月。
|
||||
|
||||
核心逻辑:只看 status=active 的节点;月份按 today 所在自然月(含 today 所在月的逾期节点)。
|
||||
Args:
|
||||
nodes: 轻量节点 dict。
|
||||
today: 业务日,用于确定自然月。
|
||||
Returns:
|
||||
存在本月未付到期节点时为 True。
|
||||
"""
|
||||
month_start = today.replace(day=1)
|
||||
month_end = date(today.year + 1, 1, 1) if today.month == 12 else date(today.year, today.month + 1, 1)
|
||||
for node in nodes:
|
||||
if str(node.get("status") or "").strip().lower() != "active":
|
||||
continue
|
||||
ref = node_due_reference(node.get("due_date"), node.get("anchor_date"))
|
||||
if ref and month_start <= ref < month_end:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _node_payload(node: ContractPaymentNode) -> dict[str, Any]:
|
||||
"""把 ORM 节点收成分类所需的轻量字段。"""
|
||||
return {
|
||||
"status": node.status,
|
||||
"due_date": node.due_date,
|
||||
"anchor_date": node.anchor_date,
|
||||
"paid_at": (node.evidence_json or {}).get("paid_at"),
|
||||
}
|
||||
|
||||
|
||||
def collect_ledger_focus(*, session: Session, today: date | None = None) -> dict[str, set[int]]:
|
||||
"""
|
||||
扫描全部已解析台账合同,按汇总卡口径收集合同 ID。
|
||||
|
||||
核心逻辑:不应用页面 keyword;待确认合同不进入台账汇总。本月应付可与即将到期/逾期重叠。
|
||||
Args:
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
Returns:
|
||||
四个 focus 键到合同 ID 集合的映射。
|
||||
"""
|
||||
as_of = business_today(today=today)
|
||||
contracts = (
|
||||
session.query(ContractPaymentContract.id, ContractPaymentContract.status, ContractPaymentContract.parse_status)
|
||||
.filter(ContractPaymentContract.parse_status == "parsed")
|
||||
.all()
|
||||
)
|
||||
buckets: dict[str, set[int]] = {
|
||||
LEDGER_FOCUS_DUE: set(),
|
||||
LEDGER_FOCUS_OVERDUE: set(),
|
||||
LEDGER_FOCUS_NEEDS_COMPLETION: set(),
|
||||
LEDGER_FOCUS_DUE_THIS_MONTH: set(),
|
||||
}
|
||||
if not contracts:
|
||||
return buckets
|
||||
contract_ids = [row.id for row in contracts]
|
||||
nodes_by_contract: dict[int, list[dict[str, Any]]] = defaultdict(list)
|
||||
node_rows = (
|
||||
session.query(ContractPaymentNode)
|
||||
.filter(ContractPaymentNode.contract_id.in_(contract_ids))
|
||||
.all()
|
||||
)
|
||||
for node in node_rows:
|
||||
nodes_by_contract[node.contract_id].append(_node_payload(node))
|
||||
for row in contracts:
|
||||
nodes = nodes_by_contract.get(row.id, [])
|
||||
status = classify_ledger_status(
|
||||
contract_status=row.status,
|
||||
parse_status=row.parse_status,
|
||||
nodes=nodes,
|
||||
today=as_of,
|
||||
)
|
||||
if status == LEDGER_FOCUS_DUE:
|
||||
buckets[LEDGER_FOCUS_DUE].add(row.id)
|
||||
elif status == LEDGER_FOCUS_OVERDUE:
|
||||
buckets[LEDGER_FOCUS_OVERDUE].add(row.id)
|
||||
elif status == LEDGER_FOCUS_NEEDS_COMPLETION:
|
||||
buckets[LEDGER_FOCUS_NEEDS_COMPLETION].add(row.id)
|
||||
if has_unpaid_due_this_month(nodes, as_of):
|
||||
buckets[LEDGER_FOCUS_DUE_THIS_MONTH].add(row.id)
|
||||
return buckets
|
||||
|
||||
|
||||
def ledger_focus_counts(*, session: Session, today: date | None = None) -> dict[str, int]:
|
||||
"""
|
||||
返回四张汇总卡的合同份数。
|
||||
|
||||
Args:
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
Returns:
|
||||
due / overdue / needs_completion / due_this_month 的计数。
|
||||
"""
|
||||
buckets = collect_ledger_focus(session=session, today=today)
|
||||
return {key: len(ids) for key, ids in buckets.items()}
|
||||
|
||||
|
||||
def apply_ledger_focus(query: Query, focus: str, *, session: Session, today: date | None = None) -> Query:
|
||||
"""
|
||||
按汇总卡口径把台账查询限制到对应合同 ID。
|
||||
|
||||
核心逻辑:空集合时强制无结果,避免 SQL IN () 退化成不过滤。
|
||||
Args:
|
||||
query: 已按解析状态/关键词过滤的合同查询。
|
||||
focus: 四个合法口径之一。
|
||||
session: 当前请求的 SQLAlchemy 会话。
|
||||
today: 可选业务日。
|
||||
Returns:
|
||||
叠加 ID 过滤后的查询。
|
||||
"""
|
||||
ids = collect_ledger_focus(session=session, today=today).get(focus) or set()
|
||||
if not ids:
|
||||
return query.filter(false())
|
||||
return query.filter(ContractPaymentContract.id.in_(ids))
|
||||
@@ -1,10 +1,11 @@
|
||||
"""
|
||||
backend/app/services/schedule/shipping_inventory_rpa_archive.py
|
||||
|
||||
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)。
|
||||
用途:货代库存 RPA 排程 run 的原始库存 ZIP 归档(finalize 预生成 + 下载直传)与企微展示名。
|
||||
依赖:ScheduleRun、ShippingInventoryFile、shipping_inventory_rpa_finalize.is_shipping_inventory_rpa_task。
|
||||
逻辑:finalize 调用 persist_inventory_rpa_raw_zip_archive 写入磁盘与 summary;
|
||||
query_service 只读 summary;api/schedule/runs 按 raw_inventory_zip_path send_file。
|
||||
企微/下载展示名用「库存RPA-日期-时刻-结果|库存」;包内条目仅「序号_仓码」;
|
||||
完整 source_code / inventory_file_no 只写在 manifest.json;磁盘归档键仍为 {run_no}.zip。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -12,6 +13,7 @@ from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
import zipfile
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
@@ -21,6 +23,7 @@ from app import db
|
||||
from app.core.errors import NotFoundError
|
||||
from app.models import ScheduleRun, ShippingInventoryFile
|
||||
from app.services.schedule.shipping_inventory_rpa_finalize import is_shipping_inventory_rpa_task
|
||||
from app.services.schedule.timezone_util import resolve_schedule_tzinfo
|
||||
|
||||
_RAW_ZIP_NOT_FOUND_MESSAGE = "原始库存包不存在,请重新执行或联系管理员"
|
||||
|
||||
@@ -48,9 +51,63 @@ def get_inventory_archive_dir() -> str:
|
||||
return str(archive_dir)
|
||||
|
||||
|
||||
def inventory_raw_zip_download_name(run_no: str) -> str:
|
||||
"""浏览器下载时使用的 ZIP 文件名。"""
|
||||
return f"inventory-rpa-raw-{run_no}.zip"
|
||||
def _attachment_when_from_run(run: ScheduleRun) -> datetime:
|
||||
"""
|
||||
推导企微/下载展示名中的当地时刻。
|
||||
|
||||
核心逻辑:started_at → created_at → finished_at → 解析 RUN{yyyyMMddHHmmss}* → utcnow;
|
||||
上述时刻在库内均为 UTC naive(含 run_no 时间戳),格式化前转到任务
|
||||
schedule_timezone(缺省 Asia/Shanghai)。完整 run_no 仍留在卡片与磁盘归档键。
|
||||
"""
|
||||
when_utc: datetime | None = None
|
||||
for value in (run.started_at, run.created_at, run.finished_at):
|
||||
if isinstance(value, datetime):
|
||||
when_utc = value
|
||||
break
|
||||
if when_utc is None:
|
||||
match = re.match(r"^RUN(\d{14})", str(run.run_no or "").strip())
|
||||
if match:
|
||||
try:
|
||||
when_utc = datetime.strptime(match.group(1), "%Y%m%d%H%M%S")
|
||||
except ValueError:
|
||||
when_utc = None
|
||||
if when_utc is None:
|
||||
when_utc = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
|
||||
task = getattr(run, "task", None)
|
||||
tz_name = getattr(task, "schedule_timezone", None) if task is not None else None
|
||||
tz = resolve_schedule_tzinfo(tz_name)
|
||||
if when_utc.tzinfo is None:
|
||||
when_utc = when_utc.replace(tzinfo=timezone.utc)
|
||||
return when_utc.astimezone(tz)
|
||||
|
||||
|
||||
def inventory_rpa_attachment_stem(run: ScheduleRun) -> str:
|
||||
"""
|
||||
库存 RPA 企微附件共用前缀:库存RPA-{yyyyMMdd}-{HHmm}(业务时区当地时间)。
|
||||
|
||||
Args:
|
||||
run: 排程执行记录。
|
||||
|
||||
Returns:
|
||||
不含角色后缀与扩展名的展示名前缀。
|
||||
"""
|
||||
when = _attachment_when_from_run(run)
|
||||
return f"库存RPA-{when.strftime('%Y%m%d')}-{when.strftime('%H%M')}"
|
||||
|
||||
|
||||
def inventory_rpa_result_excel_name(run: ScheduleRun) -> str:
|
||||
"""库存 RPA 结果 Excel 的企微/下载展示名。"""
|
||||
return f"{inventory_rpa_attachment_stem(run)}-结果.xlsx"
|
||||
|
||||
|
||||
def inventory_raw_zip_download_name(run: ScheduleRun) -> str:
|
||||
"""
|
||||
库存 ZIP 的企微/浏览器下载展示名。
|
||||
|
||||
核心逻辑:磁盘归档仍为 {run_no}.zip;本函数只影响 Content-Disposition 与企微 filename。
|
||||
"""
|
||||
return f"{inventory_rpa_attachment_stem(run)}-库存.zip"
|
||||
|
||||
|
||||
def _inventory_raw_zip_archive_path(run_no: str) -> Path:
|
||||
@@ -157,7 +214,6 @@ def persist_inventory_rpa_raw_zip_archive(
|
||||
index=zip_index,
|
||||
source_code=source_code,
|
||||
warehouse_id=warehouse_id,
|
||||
inventory_file_no=inventory_file_no,
|
||||
original_suffix=storage_path.suffix or ".xlsx",
|
||||
)
|
||||
archive.write(storage_path, arcname=entry_name)
|
||||
@@ -236,7 +292,7 @@ def resolve_inventory_raw_zip_download(run: ScheduleRun) -> tuple[Path, str]:
|
||||
if not _is_allowed_inventory_archive_path(zip_path):
|
||||
raise NotFoundError(_RAW_ZIP_NOT_FOUND_MESSAGE)
|
||||
|
||||
return zip_path.resolve(), inventory_raw_zip_download_name(run.run_no)
|
||||
return zip_path.resolve(), inventory_raw_zip_download_name(run)
|
||||
|
||||
|
||||
def _sanitize_zip_segment(value: str) -> str:
|
||||
@@ -245,25 +301,33 @@ def _sanitize_zip_segment(value: str) -> str:
|
||||
return cleaned or "unknown"
|
||||
|
||||
|
||||
def _zip_entry_label(*, source_code: str, warehouse_id: str) -> str:
|
||||
"""
|
||||
包内短标签:优先 source_code(库存站点业务键,Crane 等无固定仓码也能辨认)。
|
||||
|
||||
warehouse_id / inventory_file_no 已写入 manifest.json;条目名不必再叠仓码。
|
||||
"""
|
||||
source = str(source_code or "").strip()
|
||||
if source:
|
||||
return source
|
||||
warehouse = str(warehouse_id or "").strip()
|
||||
if warehouse and warehouse.lower() != "unknown":
|
||||
return warehouse
|
||||
return "inventory"
|
||||
|
||||
|
||||
def _build_zip_entry_name(
|
||||
*,
|
||||
index: int,
|
||||
source_code: str,
|
||||
warehouse_id: str,
|
||||
inventory_file_no: str,
|
||||
original_suffix: str,
|
||||
) -> str:
|
||||
"""生成 ZIP 内单文件条目名(不含目录)。"""
|
||||
base = "_".join(
|
||||
filter(
|
||||
None,
|
||||
[
|
||||
f"{index:03d}",
|
||||
_sanitize_zip_segment(source_code),
|
||||
_sanitize_zip_segment(warehouse_id),
|
||||
_sanitize_zip_segment(inventory_file_no),
|
||||
],
|
||||
)
|
||||
)
|
||||
"""
|
||||
生成 ZIP 内单文件条目名(不含目录)。
|
||||
|
||||
核心逻辑:`{序号}_{source_code}.{ext}`;序号保证极端撞名时仍唯一。
|
||||
"""
|
||||
label = _sanitize_zip_segment(_zip_entry_label(source_code=source_code, warehouse_id=warehouse_id))
|
||||
suffix = original_suffix if original_suffix.startswith(".") else f".{original_suffix}"
|
||||
return f"{base}{suffix}"
|
||||
return f"{index:03d}_{label}{suffix}"
|
||||
@@ -493,6 +493,11 @@ def _finalize_shipping_inventory_schedule_run_impl(
|
||||
errors.append(f"Excel导出失败: {excel_exc}")
|
||||
if status == "success":
|
||||
status = "partial_failed"
|
||||
else:
|
||||
# 企微/下载展示名:库存RPA-{日期}-{时刻}-结果.xlsx(完整 run_no 留在卡片与 DB)。
|
||||
from app.services.schedule.shipping_inventory_rpa_archive import inventory_rpa_result_excel_name
|
||||
|
||||
file_name = inventory_rpa_result_excel_name(run)
|
||||
|
||||
step_logs = list(run.step_logs or [])
|
||||
step_logs.append({
|
||||
|
||||
@@ -3,13 +3,61 @@ services/shipping_notice/document_layout/coordinate_region_text.py
|
||||
|
||||
用途:统一从页面坐标字符中读取受控区域文字,并恢复可靠的原始文本流空白。
|
||||
依赖:冻结 layout 的 page_glyphs/tables 字符坐标契约、PositionedCharacter 可选边界字段。
|
||||
逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则。
|
||||
逻辑:标注取字、模板匹配、字段抽取和版本诊断共享“原始边界优先、几何间距兜底”的渲染规则;
|
||||
另提供单逻辑表头折行合并(x 回退副标签并入最近列,不拆成新身份列)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Literal
|
||||
|
||||
# 单逻辑表头:列中心相对页宽回退超过该阈值,视为同列折行副标签。
|
||||
_HEADER_CENTER_X_REGRESSION_TOLERANCE = 0.02
|
||||
|
||||
|
||||
def merge_header_identity_wrap_tokens(
|
||||
tokens: list[str],
|
||||
centers: list[float] | None,
|
||||
widths: list[float] | None = None,
|
||||
) -> tuple[list[str], list[float] | None, list[float] | None]:
|
||||
"""
|
||||
将单逻辑表头中的折行副标签并入所属列,保留文案、不新增身份列。
|
||||
|
||||
核心逻辑:主行列中心近似单调递增;若下一 token 的中心明显回退,则并入与其
|
||||
x 最近的已有列(如 Part Number 下 Vendor Item#、Requested Arrival 下 Date)。
|
||||
多行正式表头不要调用本函数。
|
||||
|
||||
Args:
|
||||
tokens: 按阅读序的 header_tokens(可含第二视觉行)。
|
||||
centers: 与 tokens 对齐的列中心(0..1);缺失或长度不一致时原样返回。
|
||||
widths: 可选列宽比;对齐时随列保留(被并入列沿用主行宽度)。
|
||||
|
||||
Returns:
|
||||
合并后的 (tokens, centers, widths)。
|
||||
"""
|
||||
if not tokens or not centers or len(centers) != len(tokens):
|
||||
return tokens, centers, widths
|
||||
has_widths = isinstance(widths, list) and len(widths) == len(tokens)
|
||||
merged_tokens: list[str] = []
|
||||
merged_centers: list[float] = []
|
||||
merged_widths: list[float] | None = [] if has_widths else None
|
||||
max_center = float('-inf')
|
||||
for index, token in enumerate(tokens):
|
||||
center = float(centers[index])
|
||||
if merged_centers and center < max_center - _HEADER_CENTER_X_REGRESSION_TOLERANCE:
|
||||
parent = min(
|
||||
range(len(merged_centers)),
|
||||
key=lambda item: abs(merged_centers[item] - center),
|
||||
)
|
||||
merged_tokens[parent] = f'{merged_tokens[parent]} {token}'.strip()
|
||||
continue
|
||||
merged_tokens.append(str(token))
|
||||
merged_centers.append(center)
|
||||
if merged_widths is not None:
|
||||
merged_widths.append(float(widths[index]))
|
||||
max_center = max(max_center, center)
|
||||
return merged_tokens, merged_centers, merged_widths
|
||||
|
||||
|
||||
def render_positioned_row(
|
||||
glyphs: list[Any], *, geometry_gap_limit: float | None = None,
|
||||
|
||||
+19
-13
@@ -153,10 +153,13 @@ def reconstruct_coordinate_profile_rows_with_strategy(
|
||||
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/adaptive/dynamic,并返回坐标明细与策略结果。
|
||||
|
||||
核心逻辑:三种重建模式都跑一遍再交给策略裁决;``selected`` 时只返回被选中模式。
|
||||
策略为 ``needs_review`` 时仍返回 fixed→adaptive→dynamic 的最佳努力明细,供盲测/
|
||||
验证人工核对;正式自动建单路径必须自行检查 ``strategy.status == 'selected'``。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout import runtime_parse_strategy as parse_strategy
|
||||
|
||||
fixed_rows = reconstruct_coordinate_profile_rows(
|
||||
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
|
||||
@@ -197,20 +200,23 @@ def reconstruct_coordinate_profile_rows_with_strategy(
|
||||
for row in rows
|
||||
]
|
||||
|
||||
strategy = resolve_runtime_parse_strategy(
|
||||
strategy = parse_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,
|
||||
)
|
||||
if strategy.status == 'selected' and strategy.row_mode is not None:
|
||||
return (
|
||||
fixed_rows if strategy.row_mode == 'fixed_subrows'
|
||||
else adaptive_rows if strategy.row_mode == 'adaptive_record_columns'
|
||||
else dynamic_rows,
|
||||
strategy,
|
||||
)
|
||||
# 策略需复核时仍返回最佳努力明细,供盲测/验证人工核对;正式自动建单仍以
|
||||
# strategy.status == 'selected' 为准,不得把 fallback 当成可自动建单结果。
|
||||
fallback = fixed_rows or adaptive_rows or dynamic_rows
|
||||
return fallback, strategy
|
||||
|
||||
|
||||
def resolve_line_start_field_code(value: Any = None) -> str:
|
||||
|
||||
@@ -6,6 +6,7 @@ backend/app/services/shipping_notice/document_layout/order_profile.py
|
||||
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费
|
||||
DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成
|
||||
matching_signature 供运行时硬门禁与维度比对。自动决胜 critical 仅 header+column。
|
||||
表区 region_role 区分主明细与同文档 LN 补料号补充表(line_field_supplement)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -259,6 +260,8 @@ class TableRegionProfile(OrderProfileModel):
|
||||
page_scope: Literal['first_page', 'all_pages', 'continuation_pages', 'exact_page'] = 'all_pages'
|
||||
page_no: int | None = Field(default=None, ge=1)
|
||||
region: RelativeRegion
|
||||
# business_lines=主明细命中源;line_field_supplement=同文档按 LN 补料号(如 COO),不进业务表匹配。
|
||||
region_role: Literal['business_lines', 'line_field_supplement'] = 'business_lines'
|
||||
# 逻辑明细起行锚点;默认客户 PO 行号,可使用任一已绑定明细字段。
|
||||
line_start_field_code: str | None = Field(default='customer_po_line_no', pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
# 默认沿用既有固定物理子行;自适应模式仅在模板显式选择时允许字段跨视觉行匹配。
|
||||
@@ -304,6 +307,22 @@ class TableRegionProfile(OrderProfileModel):
|
||||
field.field_code for field in self.line_layouts[0].field_regions
|
||||
}:
|
||||
raise ValueError('main line layout must bind the configured line-start field')
|
||||
if self.region_role == 'line_field_supplement':
|
||||
# 补充表只允许起行 + 客户料号/Vendor,禁止绑数量金额等以免误当业务明细。
|
||||
bound = {
|
||||
field.field_code
|
||||
for item in self.line_layouts
|
||||
for field in item.field_regions
|
||||
}
|
||||
if not self.line_start_field_code or self.line_start_field_code not in bound:
|
||||
raise ValueError('line_field_supplement requires the configured line-start field')
|
||||
allowed = {self.line_start_field_code, 'customer_part_number', 'part_number'}
|
||||
extra = sorted(bound - allowed)
|
||||
if extra:
|
||||
raise ValueError(
|
||||
'line_field_supplement may only bind line-start and part number fields; '
|
||||
f'unexpected: {", ".join(extra)}'
|
||||
)
|
||||
# A physical text band must have exactly one layout interpretation. Allowing
|
||||
# overlapping header/line regions would reintroduce the cross-row ambiguity
|
||||
# that v2 coordinate profiles are intended to eliminate.
|
||||
@@ -505,6 +524,11 @@ class OrderCoordinateProfile(OrderProfileModel):
|
||||
ids = [item.region_id for item in self.table_regions]
|
||||
if len(ids) != len(set(ids)):
|
||||
raise ValueError('table region ids must be unique')
|
||||
if not any(
|
||||
str(getattr(item, 'region_role', None) or 'business_lines') == 'business_lines'
|
||||
for item in self.table_regions
|
||||
):
|
||||
raise ValueError('at least one business_lines table region is required')
|
||||
for index, left in enumerate(self.table_regions):
|
||||
for right in self.table_regions[index + 1:]:
|
||||
# Different exact pages may use identical coordinates without competing at runtime.
|
||||
|
||||
@@ -5,8 +5,12 @@ services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
依赖:OrderCoordinateProfile、order_profile_signature.MATCHER_POLICY_ID、coordinate_region_text。
|
||||
逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜;
|
||||
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
|
||||
主表优先按签名表头原子亲和度选择(避免 MinerU 抬头 KV 小表抢主表),并列再比表区重叠;
|
||||
无 hard_valid 时仅当全部候选均坐标结构不可用才抬升 evidence_insufficient;
|
||||
身份表头只读「签名 header_bbox 按主表顶边 deltaY 对齐」后的窗口,禁止表顶宽带兜底;
|
||||
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
|
||||
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁。
|
||||
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
|
||||
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,6 +23,7 @@ from typing import Any, Literal
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import (
|
||||
merge_header_identity_wrap_tokens,
|
||||
positioned_token_spans,
|
||||
read_coordinate_region_text,
|
||||
visual_glyph_rows,
|
||||
@@ -44,6 +49,8 @@ from app.services.shipping_notice.document_layout.order_profile_signature import
|
||||
# 当前项目尚无历史运行数据;保持既有 v1 标识并在现版本一次性修正其事实投影语义,
|
||||
# 避免无意义的版本兼容分支。
|
||||
LAYOUT_MATCHING_FEATURES_VERSION = 'v1'
|
||||
# 多表时签名表头原子交集占比达到该阈值才优先于纯 bbox 重叠选主表。
|
||||
_PRIMARY_TABLE_HEADER_AFFINITY_MINIMUM = 0.5
|
||||
|
||||
|
||||
def _anchor_comparable_text(value: Any) -> str:
|
||||
@@ -284,7 +291,12 @@ 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):
|
||||
# [STEP] 仅当全部候选都缺关键坐标结构时才抬升 evidence_insufficient;
|
||||
# 禁止无关远亲候选的坐标码掩盖近亲模板的真实 header/topology 冲突。
|
||||
if rendered and all(
|
||||
'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,
|
||||
@@ -960,13 +972,11 @@ def _score_header_semantic_position(
|
||||
"""比对真实表头 token、横向顺序和位置。
|
||||
|
||||
核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。
|
||||
期望侧先截断单逻辑表头的折行副标签污染。
|
||||
"""
|
||||
if signature is None:
|
||||
return MatchDimensionResult(state='unavailable', score=0.0)
|
||||
expected_tokens: list[str] = []
|
||||
for table in signature.get('table_patterns') or []:
|
||||
if isinstance(table, dict):
|
||||
expected_tokens.extend(str(item).casefold() for item in table.get('header_tokens') or [])
|
||||
expected_tokens = [str(item).casefold() for item in _signature_identity_header_tokens(signature)]
|
||||
observed_tokens = [str(item).casefold() for item in observed.get('header_tokens') or []]
|
||||
required_ratio = (sum(required_hits) / len(required_hits)) if required_hits else 1.0
|
||||
if not expected_tokens:
|
||||
@@ -986,7 +996,7 @@ def _score_header_semantic_position(
|
||||
return MatchDimensionResult(state='mismatched', score=0.0)
|
||||
matched = sum(1 for token in expected_tokens if token in observed_tokens)
|
||||
token_ratio = matched / len(expected_tokens)
|
||||
expected_order = [str(item).casefold() for table in signature.get('table_patterns') or [] if isinstance(table, dict) for item in table.get('header_order') or []]
|
||||
expected_order = [str(item).casefold() for item in _signature_identity_header_order(signature)]
|
||||
observed_order = observed.get('header_tokens') or []
|
||||
shared = [item for item in expected_order if item in observed_order]
|
||||
order_ratio = 1.0
|
||||
@@ -1006,20 +1016,80 @@ def _score_header_semantic_position(
|
||||
|
||||
_HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'})
|
||||
_HEADER_ATOM_MIN_LEN = 3
|
||||
_HEADER_PAREN_GLOSS = re.compile(r'[\((][^\))]*[\))]')
|
||||
|
||||
|
||||
def _sanitize_signature_table_identity(
|
||||
pattern: dict[str, Any],
|
||||
) -> tuple[list[str], list[float] | None, list[float] | None]:
|
||||
"""
|
||||
按需合并单逻辑表头签名中的折行副标签。
|
||||
|
||||
核心逻辑:header_row_count==1 时按 column_centers 回退把副标签并入最近列;
|
||||
多行正式表头原样返回。兼容尚未重冻、仍把 Vendor Item#/Date 列为独立 token 的旧签名。
|
||||
"""
|
||||
raw_tokens = [str(item) for item in pattern.get('header_tokens') or []]
|
||||
centers = pattern.get('column_centers') if isinstance(pattern.get('column_centers'), list) else None
|
||||
widths = pattern.get('column_width_ratios') if isinstance(pattern.get('column_width_ratios'), list) else None
|
||||
try:
|
||||
center_values = [float(item) for item in centers] if centers is not None else None
|
||||
except (TypeError, ValueError):
|
||||
center_values = None
|
||||
try:
|
||||
width_values = [float(item) for item in widths] if widths is not None else None
|
||||
except (TypeError, ValueError):
|
||||
width_values = None
|
||||
if int(pattern.get('header_row_count') or 1) > 1:
|
||||
return raw_tokens, center_values, width_values
|
||||
return merge_header_identity_wrap_tokens(raw_tokens, center_values, width_values)
|
||||
|
||||
|
||||
def _signature_identity_header_tokens(signature: dict[str, Any] | None) -> list[str]:
|
||||
"""读取截断折行副标签后的签名表头身份 token。"""
|
||||
tokens: list[str] = []
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
if isinstance(pattern, dict):
|
||||
trimmed, _, _ = _sanitize_signature_table_identity(pattern)
|
||||
tokens.extend(trimmed)
|
||||
return tokens
|
||||
|
||||
|
||||
def _signature_identity_header_order(signature: dict[str, Any] | None) -> list[str]:
|
||||
"""读取合并折行后的 header_order;与身份 token 对齐。"""
|
||||
ordered: list[str] = []
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
tokens, _, _ = _sanitize_signature_table_identity(pattern)
|
||||
ordered.extend(tokens)
|
||||
return ordered
|
||||
|
||||
|
||||
def _signature_single_logical_header(signature: dict[str, Any] | None) -> bool:
|
||||
"""签名是否全部为逻辑一行表头(可含格内折行)。"""
|
||||
patterns = [
|
||||
item for item in (signature or {}).get('table_patterns') or []
|
||||
if isinstance(item, dict)
|
||||
]
|
||||
if not patterns:
|
||||
return True
|
||||
return all(int(item.get('header_row_count') or 1) <= 1 for item in patterns)
|
||||
|
||||
|
||||
def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
|
||||
"""
|
||||
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
|
||||
|
||||
核心逻辑:去撇号后按非字母数字切分;过滤过短词与虚词,避免 Q'TY/No. 噪声。
|
||||
核心逻辑:先拼接 token 再去掉括号注记(通用印刷 gloss,跨 token 空格切开时
|
||||
仍可剥除),再去撇号并按非字母数字切分;过滤过短词与虚词。签名侧与运行时共用。
|
||||
"""
|
||||
joined = ' '.join(str(token) for token in tokens)
|
||||
normalized = _HEADER_PAREN_GLOSS.sub(' ', joined.casefold())
|
||||
normalized = re.sub(r"['’]", '', normalized)
|
||||
atoms: set[str] = set()
|
||||
for token in tokens:
|
||||
normalized = re.sub(r"['’]", '', str(token).casefold())
|
||||
for part in re.split(r'[^a-z0-9]+', normalized):
|
||||
if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
|
||||
atoms.add(part)
|
||||
for part in re.split(r'[^a-z0-9]+', normalized):
|
||||
if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
|
||||
atoms.add(part)
|
||||
return frozenset(atoms)
|
||||
|
||||
|
||||
@@ -1031,10 +1101,7 @@ def _header_discriminator_atoms_conflict(
|
||||
"""签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。"""
|
||||
if signature is None or not signature.get('table_patterns'):
|
||||
return False
|
||||
expected_tokens: list[str] = []
|
||||
for table in signature.get('table_patterns') or []:
|
||||
if isinstance(table, dict):
|
||||
expected_tokens.extend(str(item) for item in table.get('header_tokens') or [])
|
||||
expected_tokens = _signature_identity_header_tokens(signature)
|
||||
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
|
||||
if not expected_tokens or not observed_tokens:
|
||||
return False
|
||||
@@ -1075,9 +1142,15 @@ def _score_column_topology(
|
||||
for pattern, expected in zip(patterns, expected_counts):
|
||||
if expected <= 0:
|
||||
continue
|
||||
count_score = min(observed_count, expected) / max(observed_count, expected)
|
||||
expected_centers = pattern.get('column_centers') if isinstance(pattern.get('column_centers'), list) else []
|
||||
expected_widths = pattern.get('column_width_ratios') if isinstance(pattern.get('column_width_ratios'), list) else []
|
||||
tokens, expected_centers_raw, expected_widths_raw = _sanitize_signature_table_identity(pattern)
|
||||
expected_identity_count = len(tokens) or expected
|
||||
count_score = min(observed_count, expected_identity_count) / max(observed_count, expected_identity_count)
|
||||
expected_centers = expected_centers_raw if isinstance(expected_centers_raw, list) else []
|
||||
expected_widths = expected_widths_raw if isinstance(expected_widths_raw, list) else []
|
||||
if not expected_centers and isinstance(pattern.get('column_centers'), list):
|
||||
expected_centers = pattern.get('column_centers') or []
|
||||
if not expected_widths and isinstance(pattern.get('column_width_ratios'), list):
|
||||
expected_widths = pattern.get('column_width_ratios') or []
|
||||
if expected_centers and observed_centers:
|
||||
center_score = _sequence_similarity(expected_centers, observed_centers, tolerance=0.08)
|
||||
width_score = _sequence_similarity(expected_widths, observed_widths, tolerance=0.16) if expected_widths and observed_widths else 0.0
|
||||
@@ -1261,10 +1334,11 @@ def _observe_layout_features(
|
||||
if width > 0 and height > 0:
|
||||
aspect_ratio = width / height
|
||||
|
||||
# [STEP 1] 与签名生成一致,按签名表区选择实际业务表;MinerU 的 tables[0]
|
||||
# 可能是抬头/元数据表,不能作为运行时默认主表。
|
||||
# [STEP 1] 与签名生成一致,按签名表头亲和度与表区选择实际业务表;MinerU 的
|
||||
# tables[0] 可能是抬头/元数据 KV 表,不能作为运行时默认主表。
|
||||
primary_bbox = _select_signature_primary_table_bbox(
|
||||
tables=tables, pages=pages, signature=signature,
|
||||
page_glyphs=page_glyphs, glyph_tables=glyph_tables,
|
||||
)
|
||||
# [STEP 1b] 业务行裁剪:仅按模板 termination/exclusion 截断粘连高度。
|
||||
primary_bbox = _clip_observed_primary_table_bbox(
|
||||
@@ -1373,18 +1447,8 @@ 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_tokens = [str(token).casefold() for token in _signature_identity_header_tokens(signature)]
|
||||
expected_order = [str(token).casefold() for token in _signature_identity_header_order(signature)]
|
||||
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:
|
||||
@@ -1420,9 +1484,21 @@ def _select_persisted_header_candidate(
|
||||
|
||||
|
||||
def _select_signature_primary_table_bbox(
|
||||
*, tables: list[dict[str, Any]], pages: dict[str, Any], signature: dict[str, Any] | None,
|
||||
*,
|
||||
tables: list[dict[str, Any]],
|
||||
pages: dict[str, Any],
|
||||
signature: dict[str, Any] | None,
|
||||
page_glyphs: dict[str, Any] | None = None,
|
||||
glyph_tables: dict[str, Any] | None = None,
|
||||
) -> list[float] | None:
|
||||
"""按签名表区选取重叠最大的实际表;无可用签名时才保持首表兼容行为。"""
|
||||
"""
|
||||
选取运行时主表框:签名表头亲和度优先,其次表区重叠;无签名时首表兼容。
|
||||
|
||||
核心逻辑:MinerU 常把右上角 ORDER DATE/NO 等 KV 块拆成独立表且排在 tables[0];
|
||||
仅靠 bbox 重叠在全页 glyphs 场景下仍可能读错表头。对每个候选表顶部观测 header
|
||||
atoms,与签名 identity header 算交集占比;占比 ≥ 阈值时优先该表,并列再比
|
||||
table_patterns.bbox.median 重叠。
|
||||
"""
|
||||
normalized_tables: list[list[float]] = []
|
||||
for table in tables:
|
||||
page = pages.get(str(table.get('page_no') or 1)) or pages.get(table.get('page_no') or 1)
|
||||
@@ -1448,22 +1524,99 @@ def _select_signature_primary_table_bbox(
|
||||
and isinstance(item['bbox'].get('median'), list)
|
||||
and len(item['bbox']['median']) == 4
|
||||
]
|
||||
if not patterns:
|
||||
return normalized_tables[0]
|
||||
best_bbox = normalized_tables[0]
|
||||
best_overlap = -1.0
|
||||
for candidate in normalized_tables:
|
||||
expected_atoms = _header_token_atoms(_signature_identity_header_tokens(signature))
|
||||
glyph_pages = page_glyphs if isinstance(page_glyphs, dict) else {}
|
||||
table_glyph_map = glyph_tables if isinstance(glyph_tables, dict) else {}
|
||||
|
||||
def _best_pattern_overlap(candidate: list[float]) -> float:
|
||||
best = -1.0
|
||||
for pattern in patterns:
|
||||
try:
|
||||
expected = [float(value) for value in pattern['bbox']['median']]
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
overlap = _bbox_overlap(expected, candidate)
|
||||
if overlap > best_overlap:
|
||||
best_overlap, best_bbox = overlap, candidate
|
||||
best = max(best, _bbox_overlap(expected, candidate))
|
||||
return best
|
||||
|
||||
if expected_atoms and (glyph_pages or table_glyph_map):
|
||||
affinity_scored: list[tuple[float, float, list[float]]] = []
|
||||
for candidate in normalized_tables:
|
||||
tokens = _header_tokens_for_table_bbox(
|
||||
bbox=candidate,
|
||||
tables=tables,
|
||||
pages=pages,
|
||||
page_glyphs=glyph_pages,
|
||||
glyph_tables=table_glyph_map,
|
||||
)
|
||||
observed_atoms = _header_token_atoms(tokens)
|
||||
affinity = (
|
||||
len(observed_atoms & expected_atoms) / len(expected_atoms)
|
||||
if expected_atoms else 0.0
|
||||
)
|
||||
affinity_scored.append((affinity, _best_pattern_overlap(candidate), candidate))
|
||||
affinity_scored.sort(key=lambda item: (item[0], item[1]))
|
||||
best_affinity, best_overlap, best_bbox = affinity_scored[-1]
|
||||
if best_affinity >= _PRIMARY_TABLE_HEADER_AFFINITY_MINIMUM:
|
||||
return best_bbox
|
||||
if not patterns:
|
||||
return best_bbox if best_affinity > 0 else normalized_tables[0]
|
||||
|
||||
if not patterns:
|
||||
return normalized_tables[0]
|
||||
best_bbox = normalized_tables[0]
|
||||
best_overlap = -1.0
|
||||
for candidate in normalized_tables:
|
||||
overlap = _best_pattern_overlap(candidate)
|
||||
if overlap > best_overlap:
|
||||
best_overlap, best_bbox = overlap, candidate
|
||||
return best_bbox
|
||||
|
||||
|
||||
def _header_tokens_for_table_bbox(
|
||||
*,
|
||||
bbox: list[float],
|
||||
tables: list[dict[str, Any]],
|
||||
pages: dict[str, Any],
|
||||
page_glyphs: dict[str, Any],
|
||||
glyph_tables: dict[str, Any],
|
||||
) -> list[str]:
|
||||
"""
|
||||
在候选表顶部条带观测表头 token,供主表亲和度打分。
|
||||
|
||||
核心逻辑:取相对坐标表框顶边向下 max(6%, 18% 表高) 的条带,用页级 glyphs
|
||||
(不足时回退 table glyphs)拼 token;不做折行合并,仅服务选表。
|
||||
"""
|
||||
if not isinstance(bbox, list) or len(bbox) != 4:
|
||||
return []
|
||||
page_no, page = _page_for_primary_table_bbox(bbox, tables=tables, pages=pages)
|
||||
if not isinstance(page, dict):
|
||||
return []
|
||||
glyphs = None
|
||||
if page_no is not None:
|
||||
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no)
|
||||
if not isinstance(glyphs, list) or not glyphs:
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1) or []
|
||||
if not isinstance(glyphs, list) or not glyphs:
|
||||
glyphs = []
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
glyphs.extend(table_glyphs)
|
||||
if not glyphs:
|
||||
return []
|
||||
region = {
|
||||
'x0': float(bbox[0]),
|
||||
'y0': float(bbox[1]),
|
||||
'x1': float(bbox[2]),
|
||||
'y1': float(bbox[1]) + max(0.06, (float(bbox[3]) - float(bbox[1])) * 0.18),
|
||||
}
|
||||
header_glyphs = _glyphs_in_relative_region(glyphs, page=page, region=region)
|
||||
spans = [
|
||||
item for item in positioned_token_spans(header_glyphs, respect_explicit_spaces=False)
|
||||
if _usable_observed_header_token(str(item.get('text') or ''))
|
||||
][:32]
|
||||
return [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
|
||||
|
||||
|
||||
def _clip_observed_primary_table_bbox(
|
||||
primary_bbox: list[float] | None,
|
||||
*,
|
||||
@@ -1566,26 +1719,62 @@ def _bbox_overlap(left: list[float], right: list[float]) -> float:
|
||||
_HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
|
||||
|
||||
|
||||
def _band_headers_match_signature(
|
||||
*, band_tokens: list[str], signature: dict[str, Any] | None,
|
||||
) -> bool:
|
||||
"""判断冻结表头带读到的 token 是否足以代表签名表头。
|
||||
def _signature_table_bbox_median(signature: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取签名首个可用 table_patterns.bbox.median(归一化四点)。"""
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
|
||||
if not isinstance(bbox, dict):
|
||||
continue
|
||||
median = bbox.get('median')
|
||||
if isinstance(median, list) and len(median) == 4:
|
||||
try:
|
||||
return [float(item) for item in median]
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return None
|
||||
|
||||
只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”,
|
||||
直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行)
|
||||
需要回退到表体顶部的结构搜索。
|
||||
|
||||
def _align_signature_header_bbox_to_primary(
|
||||
*,
|
||||
signature: dict[str, Any] | None,
|
||||
primary_bbox: list[float],
|
||||
) -> list[float] | None:
|
||||
"""
|
||||
expected = [
|
||||
str(token).casefold()
|
||||
for pattern in (signature or {}).get('table_patterns') or []
|
||||
if isinstance(pattern, dict)
|
||||
for token in pattern.get('header_tokens') or []
|
||||
]
|
||||
if not expected or not band_tokens:
|
||||
return False
|
||||
observed = [str(token).casefold() for token in band_tokens]
|
||||
matched = sum(1 for token in expected if token in observed)
|
||||
return matched / len(expected) >= 0.5
|
||||
将签名冻结的表头框按当前主表顶边做整体 deltaY 对齐。
|
||||
|
||||
核心逻辑:x/高度保持签名 header_bbox;只用 primary_bbox.y0 - signature_table.y0
|
||||
平移;再把 y 夹在主表竖向范围内,避免落到明细数据行。无 header_bbox 时返回 None。
|
||||
"""
|
||||
if not isinstance(primary_bbox, list) or len(primary_bbox) != 4:
|
||||
return None
|
||||
header_bbox = _signature_header_bbox(signature)
|
||||
if header_bbox is None:
|
||||
return None
|
||||
table_median = _signature_table_bbox_median(signature)
|
||||
try:
|
||||
hx0, hy0, hx1, hy1 = (float(header_bbox[i]) for i in range(4))
|
||||
py0, py1 = float(primary_bbox[1]), float(primary_bbox[3])
|
||||
except (TypeError, ValueError, IndexError):
|
||||
return None
|
||||
if hy1 <= hy0 or py1 <= py0:
|
||||
return None
|
||||
delta_y = 0.0
|
||||
if table_median is not None:
|
||||
try:
|
||||
delta_y = py0 - float(table_median[1])
|
||||
except (TypeError, ValueError, IndexError):
|
||||
delta_y = 0.0
|
||||
aligned_y0 = hy0 + delta_y
|
||||
aligned_y1 = hy1 + delta_y
|
||||
# [STEP] 夹在主表内;保持最小可读高度。
|
||||
height = max(0.02, aligned_y1 - aligned_y0)
|
||||
clipped_y0 = min(max(aligned_y0, py0), max(py0, py1 - height))
|
||||
clipped_y1 = min(clipped_y0 + height, py1)
|
||||
if clipped_y1 <= clipped_y0:
|
||||
return None
|
||||
return [hx0, clipped_y0, hx1, clipped_y1]
|
||||
|
||||
|
||||
def _observe_primary_table_header(
|
||||
@@ -1596,12 +1785,12 @@ def _observe_primary_table_header(
|
||||
primary_bbox: list[float] | None,
|
||||
signature: dict[str, Any] | None,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。
|
||||
"""
|
||||
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
|
||||
|
||||
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用(保持既有行为,
|
||||
不影响正常模板)。若固定带失准(表体因上方内容折行/加行而上移或下移,带读空或读到
|
||||
错误行),则基于已定位表体顶部做表头行搜索(与压缩快照路径一致的候选行选择逻辑),
|
||||
从而对上移/下移/任意行数位移都健壮,且不依赖上方可变内容。
|
||||
核心逻辑:有签名 header_bbox 时按主表顶边 deltaY 对齐后只读该窗口;无签名表头框
|
||||
时才用主表顶 18% 保守带(与签名生成兜底一致)。禁止固定带失准后改走表顶多行
|
||||
宽带搜索,避免印刷括号注记污染身份原子。
|
||||
"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return [], [], []
|
||||
@@ -1614,14 +1803,23 @@ def _observe_primary_table_header(
|
||||
page = pages.get('1') or pages.get(1)
|
||||
if not isinstance(glyphs, list) or not glyphs or not isinstance(page, dict):
|
||||
return [], [], []
|
||||
header_bbox = _signature_header_bbox(signature)
|
||||
region = (
|
||||
{'x0': header_bbox[0], 'y0': header_bbox[1], 'x1': header_bbox[2], 'y1': header_bbox[3]}
|
||||
if header_bbox is not None else {
|
||||
'x0': primary_bbox[0], 'y0': primary_bbox[1], 'x1': primary_bbox[2],
|
||||
'y1': primary_bbox[1] + max(0.06, (primary_bbox[3] - primary_bbox[1]) * 0.18),
|
||||
}
|
||||
aligned = _align_signature_header_bbox_to_primary(
|
||||
signature=signature, primary_bbox=primary_bbox,
|
||||
)
|
||||
if aligned is not None:
|
||||
region = {
|
||||
'x0': float(aligned[0]), 'y0': float(aligned[1]),
|
||||
'x1': float(aligned[2]), 'y1': float(aligned[3]),
|
||||
}
|
||||
else:
|
||||
region = {
|
||||
'x0': float(primary_bbox[0]),
|
||||
'y0': float(primary_bbox[1]),
|
||||
'x1': float(primary_bbox[2]),
|
||||
'y1': float(primary_bbox[1]) + max(
|
||||
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
|
||||
),
|
||||
}
|
||||
width = float(page.get('width') or 0)
|
||||
if width <= 0:
|
||||
return [], [], []
|
||||
@@ -1632,28 +1830,68 @@ def _observe_primary_table_header(
|
||||
][:32]
|
||||
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
|
||||
band_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)
|
||||
band_widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
|
||||
# 固定带有效 → 直接沿用(对正常模板零影响)。
|
||||
if _band_headers_match_signature(band_tokens=band_tokens, signature=signature):
|
||||
return band_tokens, band_centers, band_widths
|
||||
# 固定带失准(位移场景)→ 基于已定位表体顶部做表头行搜索,选与签名最匹配的一行。
|
||||
candidates = [{
|
||||
'bbox': primary_bbox,
|
||||
'header_candidates': _observe_header_candidates(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox,
|
||||
),
|
||||
}]
|
||||
selected = _select_persisted_header_candidate(candidates=candidates, signature=signature)
|
||||
if selected is not None:
|
||||
header, _ = selected
|
||||
table_span = max(float(primary_bbox[2]) - float(primary_bbox[0]), 0.0001)
|
||||
band_widths = [
|
||||
round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans
|
||||
]
|
||||
if _signature_single_logical_header(signature):
|
||||
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
|
||||
band_tokens, band_centers, band_widths,
|
||||
)
|
||||
return (
|
||||
[str(token).casefold() for token in header['header_tokens']],
|
||||
header['column_centers'], header['column_width_ratios'],
|
||||
[str(item).casefold() for item in merged_tokens],
|
||||
list(merged_centers or []),
|
||||
list(merged_widths or []),
|
||||
)
|
||||
return band_tokens, band_centers, band_widths
|
||||
|
||||
|
||||
def _merge_following_wrap_candidate(
|
||||
*,
|
||||
header: dict[str, Any],
|
||||
header_candidates: list[dict[str, Any]],
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""
|
||||
将选中主表头行与紧邻下一视觉行合并(折行副标签)。
|
||||
|
||||
核心逻辑:下一行 token 的列中心若相对主行回退,merge_header_identity_wrap_tokens
|
||||
会把它们并入所属列;若不构成回退则合并结果与主行等价或略增列,仍可安全返回。
|
||||
"""
|
||||
tokens = [str(token).casefold() for token in header.get('header_tokens') or []]
|
||||
centers = [float(item) for item in header.get('column_centers') or []]
|
||||
widths = [float(item) for item in header.get('column_width_ratios') or []]
|
||||
header_y1 = float((header.get('bbox') or [0, 0, 0, 0])[3])
|
||||
following = None
|
||||
for candidate in header_candidates:
|
||||
if candidate is header:
|
||||
continue
|
||||
bbox = candidate.get('bbox') if isinstance(candidate.get('bbox'), list) else None
|
||||
if not bbox or len(bbox) != 4:
|
||||
continue
|
||||
y0 = float(bbox[1])
|
||||
if y0 + 1e-6 < header_y1:
|
||||
continue
|
||||
if following is None or y0 < float(following['bbox'][1]):
|
||||
following = candidate
|
||||
if following is None:
|
||||
return tokens, centers, widths
|
||||
wrap_tokens = [str(token).casefold() for token in following.get('header_tokens') or []]
|
||||
wrap_centers = [float(item) for item in following.get('column_centers') or []]
|
||||
wrap_widths = [float(item) for item in following.get('column_width_ratios') or []]
|
||||
if not wrap_tokens or len(wrap_tokens) != len(wrap_centers):
|
||||
return tokens, centers, widths
|
||||
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
|
||||
tokens + wrap_tokens,
|
||||
centers + wrap_centers,
|
||||
widths + wrap_widths if len(widths) == len(tokens) else None,
|
||||
)
|
||||
return (
|
||||
[str(item).casefold() for item in merged_tokens],
|
||||
list(merged_centers or []),
|
||||
list(merged_widths or []),
|
||||
)
|
||||
|
||||
|
||||
def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取候选签名冻结的表头标注区域;每个候选独立取证,禁止共享整页猜测结果。"""
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
@@ -1690,9 +1928,15 @@ def _usable_observed_header_token(token: str) -> bool:
|
||||
|
||||
|
||||
def _signature_column_values(signature: dict[str, Any], key: str) -> list[float]:
|
||||
"""读取签名中首个可用表格的列结构向量。"""
|
||||
"""读取签名中首个可用表格的列结构向量,单逻辑表头时合并折行副标签后再取。"""
|
||||
for pattern in signature.get('table_patterns') or []:
|
||||
if isinstance(pattern, dict) and isinstance(pattern.get(key), list):
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
_, centers, widths = _sanitize_signature_table_identity(pattern)
|
||||
selected = centers if key == 'column_centers' else widths if key == 'column_width_ratios' else None
|
||||
if isinstance(selected, list) and selected:
|
||||
return list(selected)
|
||||
if isinstance(pattern.get(key), list):
|
||||
try:
|
||||
return [float(item) for item in pattern[key]]
|
||||
except (TypeError, ValueError):
|
||||
|
||||
+18
-6
@@ -5,6 +5,7 @@ services/shipping_notice/document_layout/order_profile_parse_validation.py
|
||||
依赖:OrderCoordinateProfile、coordinate_region_text、order_profile 契约。
|
||||
逻辑:由 order_extraction_workflow 在 matcher 硬门禁后调用;确定性/idempotent;
|
||||
返回 passed/reason_codes/metrics 供 unique_match 二次裁决。
|
||||
类型 sanity 接受 MM/DD/YY;字段覆盖仅统计 business_lines。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,8 +27,9 @@ from app.services.shipping_notice.document_layout.coordinate_table_reconstructio
|
||||
|
||||
|
||||
_NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$')
|
||||
# Hyve 等 PO 常见 MM/DD/YY;亦接受 YYYY-MM-DD / MM/DD/YYYY。
|
||||
_DATE_PATTERN = re.compile(
|
||||
r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{4})$',
|
||||
r'^(?:\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}|\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4})$',
|
||||
)
|
||||
|
||||
|
||||
@@ -94,8 +96,13 @@ def validate_profile_parse_candidate(
|
||||
)
|
||||
|
||||
# [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报)
|
||||
# 补充表不参与发布解析门禁的字段覆盖/类型检查(正式路径另行按 LN 合并)。
|
||||
business_tables = [
|
||||
table for table in profile.table_regions
|
||||
if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines'
|
||||
]
|
||||
line_fields = [
|
||||
field for table in profile.table_regions for layout in table.line_layouts
|
||||
field for table in business_tables for layout in table.line_layouts
|
||||
for field in layout.field_regions if field.scope == 'line'
|
||||
]
|
||||
line_coverage = _line_region_coverage_shift_tolerant(
|
||||
@@ -130,7 +137,7 @@ def validate_profile_parse_candidate(
|
||||
|
||||
required_line_codes = {
|
||||
field.field_code
|
||||
for table in profile.table_regions
|
||||
for table in business_tables
|
||||
for layout in table.line_layouts
|
||||
for field in layout.field_regions
|
||||
if field.scope == 'line'
|
||||
@@ -245,8 +252,13 @@ def _line_region_coverage_shift_tolerant(
|
||||
"""
|
||||
if not profile.table_regions:
|
||||
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
|
||||
business_tables = [
|
||||
table for table in profile.table_regions
|
||||
if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines'
|
||||
]
|
||||
tables_for_lines = business_tables or list(profile.table_regions)
|
||||
line_fields = [
|
||||
field for table in profile.table_regions for layout_item in table.line_layouts
|
||||
field for table in tables_for_lines for layout_item in table.line_layouts
|
||||
for field in layout_item.field_regions if field.scope == 'line'
|
||||
]
|
||||
if not line_fields:
|
||||
@@ -254,9 +266,9 @@ def _line_region_coverage_shift_tolerant(
|
||||
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
page_glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
|
||||
# 定位与主表区(首个含 line_layouts 的表区)重叠且在 page 上的物理表;取重叠面积最大者。
|
||||
# 定位与主表区(首个 business_lines 且含 line_layouts)重叠且在 page 上的物理表;取重叠面积最大者。
|
||||
primary_region = next(
|
||||
(table for table in profile.table_regions if table.line_layouts), None,
|
||||
(table for table in tables_for_lines if table.line_layouts), None,
|
||||
)
|
||||
raw_table = _locate_overlapping_raw_table(
|
||||
primary_region=primary_region, layout=layout, page=page, profile=profile,
|
||||
|
||||
@@ -5,6 +5,8 @@ services/shipping_notice/document_layout/order_profile_signature.py
|
||||
依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。
|
||||
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
|
||||
另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。
|
||||
单逻辑表头行将格内折行副标签按 x 并入所属列,保留文案、不拆成新身份列。
|
||||
table_patterns 仅纳入 business_lines;line_field_supplement 不进匹配身份。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,6 +18,7 @@ import statistics
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.coordinate_region_text import (
|
||||
merge_header_identity_wrap_tokens,
|
||||
positioned_token_spans,
|
||||
read_coordinate_region_text,
|
||||
visual_glyph_rows,
|
||||
@@ -196,8 +199,9 @@ def build_layout_signature(
|
||||
"""
|
||||
生成版面签名快照;相同输入必须得到相同 checksum。
|
||||
|
||||
核心逻辑:解析模板表区/表头/字段关系 → 从样本区域读取固定文字 → 多样本聚合
|
||||
中位数与容差 → 过滤动态值与单样本噪声 → 计算稳定 checksum。
|
||||
核心逻辑:解析模板表区/表头/字段关系 → 仅对 business_lines 建 table_patterns →
|
||||
从样本区域读取固定文字 → 多样本聚合中位数与容差 → 过滤动态值与单样本噪声 →
|
||||
计算稳定 checksum。line_field_supplement 只服务按 LN 补料号,不进匹配身份。
|
||||
|
||||
Args:
|
||||
definition: 当前草稿或冻结 Profile 定义 JSON。
|
||||
@@ -223,11 +227,15 @@ def build_layout_signature(
|
||||
order_field_layouts=definition.get('order_field_layouts') or [],
|
||||
)
|
||||
|
||||
# [STEP 2] 页面与表区几何模式
|
||||
# [STEP 2] 页面与主表明细几何模式(排除 line_field_supplement)
|
||||
page_patterns = _build_page_patterns(sample_layouts=sample_layouts)
|
||||
matching_tables = [
|
||||
table for table in profile.table_regions
|
||||
if str(getattr(table, 'region_role', None) or 'business_lines') == 'business_lines'
|
||||
]
|
||||
table_patterns = [
|
||||
_build_table_pattern(table=table, sample_layouts=sample_layouts)
|
||||
for table in profile.table_regions
|
||||
for table in matching_tables
|
||||
]
|
||||
field_relation_graph = _build_field_relation_graph(profile, sample_layouts=sample_layouts)
|
||||
evidence_quality = _build_evidence_quality(
|
||||
@@ -353,12 +361,15 @@ def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) ->
|
||||
default=0,
|
||||
)
|
||||
|
||||
# 1 个 header_layout = 逻辑一行表头(可含格内折行);多 layout 才是多行正式表头。
|
||||
single_logical_header_row = len(header_layouts) <= 1
|
||||
for layout in sample_layouts:
|
||||
observed = _observe_sample_table(
|
||||
layout,
|
||||
target_region=region,
|
||||
header_region=header_region,
|
||||
table_region=table,
|
||||
single_logical_header_row=single_logical_header_row,
|
||||
)
|
||||
if observed is None:
|
||||
continue
|
||||
@@ -433,6 +444,7 @@ def _observe_sample_table(
|
||||
layout: dict[str, Any], *, target_region: RelativeRegion,
|
||||
header_region: RelativeRegion | None,
|
||||
table_region: Any | None = None,
|
||||
single_logical_header_row: bool = True,
|
||||
) -> dict[str, Any] | None:
|
||||
"""读取样本中与标注区域重叠最高的真实表格及其页级字符几何。"""
|
||||
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
|
||||
@@ -469,7 +481,10 @@ def _observe_sample_table(
|
||||
table_glyphs, page=page, bbox=bbox, header_bbox=header_bbox,
|
||||
)
|
||||
header_tokens, centers, widths = _header_observation(
|
||||
header_glyphs, page=page, bbox=bbox,
|
||||
header_glyphs,
|
||||
page=page,
|
||||
bbox=bbox,
|
||||
single_logical_header_row=single_logical_header_row,
|
||||
)
|
||||
header_y1 = header_bbox[3] if isinstance(header_bbox, list) and len(header_bbox) == 4 else None
|
||||
termination_rules = [
|
||||
@@ -556,9 +571,18 @@ def _union_relative_regions(regions: list[RelativeRegion]) -> RelativeRegion | N
|
||||
|
||||
|
||||
def _header_observation(
|
||||
glyphs: list[dict[str, Any]], *, page: dict[str, Any], bbox: list[float],
|
||||
glyphs: list[dict[str, Any]],
|
||||
*,
|
||||
page: dict[str, Any],
|
||||
bbox: list[float],
|
||||
single_logical_header_row: bool = True,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。"""
|
||||
"""
|
||||
从表头 token 边界生成文本、中心和宽度,禁止按单字符连续间距伪造业务列。
|
||||
|
||||
核心逻辑:读出带内全部视觉行后,对逻辑一行表头按列中心回退把折行副标签并入
|
||||
所属列(保留 Vendor Item# / Date 文案);多行正式表头不做合并。
|
||||
"""
|
||||
try:
|
||||
page_width = float(page['width'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
@@ -571,6 +595,15 @@ def _header_observation(
|
||||
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / page_width, 4) for item in spans]
|
||||
span = max(bbox[2] - bbox[0], 0.0001)
|
||||
widths = [round((float(item['x1']) - float(item['x0'])) / page_width / span, 4) for item in spans]
|
||||
if single_logical_header_row:
|
||||
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
|
||||
tokens, centers, widths,
|
||||
)
|
||||
return (
|
||||
list(merged_tokens),
|
||||
list(merged_centers or []),
|
||||
list(merged_widths or []),
|
||||
)
|
||||
return tokens, centers, widths
|
||||
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@ services/shipping_notice/document_layout/runtime_parse_strategy.py
|
||||
|
||||
用途:为已唯一命中的 Coordinate/OCR 订单模板按当前文档证据选择页范围与明细行重建方式。
|
||||
依赖:仅标准库;由正式抽取与模板质量验证共同调用。
|
||||
逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用,冲突统一转 Review。
|
||||
逻辑:不修改模板,不猜测业务值;固定/自适应重建结果只有唯一可用时才被采用;
|
||||
二者业务值冲突时,若动态列能单侧确认其一则采用该侧(或更完整的动态结果),否则转 Review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -75,6 +76,15 @@ def resolve_runtime_parse_strategy(
|
||||
baseline_rows = fixed_valid
|
||||
baseline = RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
|
||||
else:
|
||||
# [STEP] 固定/自适应业务值冲突:不得静默猜一侧;若动态列能单侧确认,再落选。
|
||||
resolved = _resolve_fixed_adaptive_ambiguity_with_dynamic(
|
||||
page_nos=page_nos,
|
||||
fixed_rows=fixed_valid,
|
||||
adaptive_rows=adaptive_valid,
|
||||
dynamic_rows=dynamic_valid,
|
||||
)
|
||||
if resolved is not None:
|
||||
return resolved
|
||||
return RuntimeParseStrategy(
|
||||
'needs_review', page_nos, None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',),
|
||||
)
|
||||
@@ -103,6 +113,67 @@ def resolve_runtime_parse_strategy(
|
||||
)
|
||||
|
||||
|
||||
def _resolve_fixed_adaptive_ambiguity_with_dynamic(
|
||||
*,
|
||||
page_nos: tuple[int, ...],
|
||||
fixed_rows: list[dict[str, Any]],
|
||||
adaptive_rows: list[dict[str, Any]],
|
||||
dynamic_rows: list[dict[str, Any]],
|
||||
) -> RuntimeParseStrategy | None:
|
||||
"""
|
||||
固定与自适应冲突时,用动态列做单侧确认。
|
||||
|
||||
核心逻辑:动态相对某一侧可覆盖(baseline/dynamic preferred),且相对另一侧
|
||||
仍 ambiguous,则采用被确认的一侧;两侧都被动态确认且动态更完整时采用动态。
|
||||
无动态证据或仍双边不清时返回 None,由调用方转 Review。
|
||||
|
||||
Args:
|
||||
page_nos: 当前有坐标证据的页码。
|
||||
fixed_rows: 有效固定子行。
|
||||
adaptive_rows: 有效自适应行。
|
||||
dynamic_rows: 有效动态列行;空则无法仲裁。
|
||||
|
||||
Returns:
|
||||
可安全选中的策略;无法仲裁时为 None。
|
||||
"""
|
||||
if not dynamic_rows:
|
||||
return None
|
||||
fixed_vs_dyn = _compare_dynamic_row_coverage(
|
||||
baseline_rows=fixed_rows, dynamic_rows=dynamic_rows,
|
||||
)
|
||||
adaptive_vs_dyn = _compare_dynamic_row_coverage(
|
||||
baseline_rows=adaptive_rows, dynamic_rows=dynamic_rows,
|
||||
)
|
||||
fixed_ok = fixed_vs_dyn != 'ambiguous'
|
||||
adaptive_ok = adaptive_vs_dyn != 'ambiguous'
|
||||
if fixed_ok and adaptive_ok:
|
||||
if fixed_vs_dyn == 'dynamic_preferred' or adaptive_vs_dyn == 'dynamic_preferred':
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'dynamic_x_columns',
|
||||
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
|
||||
)
|
||||
# 动态完整覆盖两侧且无额外行:冲突本身未消除,不能借动态消歧。
|
||||
return None
|
||||
if fixed_ok and not adaptive_ok:
|
||||
if fixed_vs_dyn == 'dynamic_preferred':
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'dynamic_x_columns',
|
||||
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
|
||||
)
|
||||
return RuntimeParseStrategy('selected', page_nos, 'fixed_subrows', ())
|
||||
if adaptive_ok and not fixed_ok:
|
||||
if adaptive_vs_dyn == 'dynamic_preferred':
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'dynamic_x_columns',
|
||||
('PARSE_STRATEGY_DYNAMIC_X_COLUMNS',),
|
||||
)
|
||||
return RuntimeParseStrategy(
|
||||
'selected', page_nos, 'adaptive_record_columns',
|
||||
('PARSE_STRATEGY_ADAPTIVE_ROW_RECONSTRUCTION',),
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def select_runtime_region_ids(*, table_regions: list[dict[str, Any]], page_no: int) -> tuple[str, ...]:
|
||||
"""为当前页选择候选表区,专属页优先,续页才回退到稳定基础表区。
|
||||
|
||||
@@ -210,29 +281,33 @@ def _compare_row_field_completeness(
|
||||
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]
|
||||
extended = False
|
||||
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()
|
||||
):
|
||||
compatible = True
|
||||
for code, value in baseline_fields.items():
|
||||
dyn_value = dynamic_fields[code]
|
||||
if dyn_value == value:
|
||||
continue
|
||||
if dyn_value.startswith(value) and len(dyn_value) > len(value):
|
||||
extended = True
|
||||
continue
|
||||
compatible = False
|
||||
break
|
||||
if compatible:
|
||||
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'
|
||||
return 'dynamic_preferred' if remaining or extended else 'baseline_preferred'
|
||||
|
||||
|
||||
def _row_fields(row: dict[str, Any]) -> dict[str, str]:
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
services/shipping_notice/document_profile_quality_service.py
|
||||
|
||||
用途:治理订单文档 Profile 的盲测候选、样本、执行结果和确定性自动建单资格。
|
||||
依赖:Profile 服务、MinerU 当前布局快照、XFA 结构分析、xfa_validation 指标、Profile 纯解析器与质量 ORM 模型。
|
||||
依赖:Profile 服务、MinerU 当前布局快照、XFA 结构分析、xfa_validation 指标、坐标重建与运行时策略、Profile 纯解析器与质量 ORM 模型。
|
||||
逻辑:管理员先固化一份独立样本的期望行,服务按冻结 Profile 执行比对;
|
||||
共同坐标回放完成视觉证据,末端值源 adapter 再补充正式字段和结构校验;
|
||||
策略需复核时仍展示最佳努力明细供人工核对,正式自动建单仍要求策略 selected;
|
||||
盲测主明细仅 business_lines,随后按 LN 合并 line_field_supplement 料号;
|
||||
盲测执行附加 visual/split/evidence 指标,XFA 任一指标 < 1.0 即失败;样本通过并批准后才放行自动建单。
|
||||
"""
|
||||
|
||||
@@ -41,7 +43,6 @@ from app.services.shipping_notice.document_layout.runtime_parse_strategy import
|
||||
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.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 (
|
||||
@@ -51,7 +52,7 @@ from app.services.shipping_notice.order_document_profile_service import (
|
||||
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,
|
||||
reservation_region_candidates_from_layout,
|
||||
)
|
||||
|
||||
|
||||
@@ -378,6 +379,17 @@ def _candidate_for_sample(
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
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')
|
||||
# 明细页坐标可能尚未因订单头字段补齐;盲测重建前先确保表所在页有整页证据。
|
||||
if isinstance(raw_table, dict):
|
||||
try:
|
||||
table_page_no = int(raw_table.get('page_no') or 1)
|
||||
except (TypeError, ValueError):
|
||||
table_page_no = 1
|
||||
if table_page_no > 0:
|
||||
layout = _ensure_page_coordinate_evidence(
|
||||
document=document, layout=layout, page_no=table_page_no,
|
||||
)
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
if not any(isinstance(value, list) and value for value in page_glyphs.values()):
|
||||
@@ -388,6 +400,9 @@ def _candidate_for_sample(
|
||||
# layout. They are valid template regions, but cannot reconstruct rows.
|
||||
if not region.line_layouts:
|
||||
continue
|
||||
# COO 等补充表不进入盲测主明细行;稍后按 LN 合并料号。
|
||||
if str(getattr(region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
|
||||
continue
|
||||
# ``page_scope`` 是历史人工策略。验证必须与正式解析一致:检查当前样本中
|
||||
# 每个有页级坐标事实的页面,由实际行结果决定是否属于续页。
|
||||
eligible_pages = [
|
||||
@@ -450,8 +465,32 @@ def _candidate_for_sample(
|
||||
line_start_field_code=region.line_start_field_code,
|
||||
schema_field_metadata=list(schema_fields.values()),
|
||||
)
|
||||
if strategy.status == 'selected':
|
||||
rows.extend(item.fields for item in chosen_rows if not item.issues)
|
||||
# selected 与 needs_review 的 fallback 明细都要展示;后者仅供盲测人工复核。
|
||||
rows.extend(item.fields for item in chosen_rows if not item.issues)
|
||||
# 与正式解析共用:按 LN 合并 line_field_supplement(如 COO)料号。
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_reconstruct_line_field_supplement_rows,
|
||||
)
|
||||
from app.services.shipping_notice.line_field_supplement_merge import (
|
||||
merge_line_field_supplement,
|
||||
)
|
||||
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
|
||||
raw_profile={
|
||||
'definition': profile.definition_json if isinstance(profile.definition_json, dict) else {},
|
||||
'profile_code': profile.profile_code,
|
||||
'version': profile.version,
|
||||
'checksum': profile.checksum,
|
||||
},
|
||||
layout=layout,
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
supplement_reasons: list[str] = []
|
||||
if supplement_rows:
|
||||
rows, supplement_reasons = merge_line_field_supplement(
|
||||
rows,
|
||||
supplement_rows,
|
||||
line_start_field_code=line_start or 'customer_po_line_no',
|
||||
)
|
||||
order_fields = [
|
||||
{
|
||||
'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status,
|
||||
@@ -465,55 +504,58 @@ def _candidate_for_sample(
|
||||
allow_fixed_region_confirmation=True,
|
||||
)
|
||||
]
|
||||
# 盲测与正式解析共用 Reservation 区域解析和归属契约;区域页可以不同于明细页。
|
||||
# 盲测与正式解析共用 Vendor Comments→Terms 锚点;page_no/region 仅表示专区已启用。
|
||||
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,
|
||||
if isinstance(profile_definition.get('reservation_id_region'), dict):
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=layout, page_nos=None,
|
||||
)
|
||||
reservation = reservation_region_candidates_from_layout(
|
||||
definition=profile_definition, layout=layout,
|
||||
)
|
||||
candidates = list(reservation.get('candidates') or [])
|
||||
reservation_reason = reservation.get('reason')
|
||||
reservation_fields = {
|
||||
str(field.get('scope') or ''): field
|
||||
for field in schema_fields.values()
|
||||
if str(field.get('field_code') or '') == 'reservation_id'
|
||||
}
|
||||
review_reasons: list[str] = [str(reservation_reason)] if reservation_reason else []
|
||||
if candidates:
|
||||
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),
|
||||
)
|
||||
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}
|
||||
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': 1, '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:
|
||||
review_reasons.extend(list(applied.review_reasons))
|
||||
if review_reasons:
|
||||
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(dict.fromkeys(review_reasons)),
|
||||
'line_field_supplement_reasons': list(supplement_reasons),
|
||||
}
|
||||
return {
|
||||
'document_id': document.id, 'table_id': str(table_id), 'rows': rows,
|
||||
'order_fields': order_fields,
|
||||
'line_field_supplement_reasons': list(supplement_reasons),
|
||||
}
|
||||
raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
|
||||
|
||||
|
||||
@@ -356,8 +356,20 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = str(payload.get('error_message') or '测试导出失败')[:500]; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
path = Path(str(payload.get('file_path') or ''))
|
||||
if not path.is_file():
|
||||
# Windows Worker 回传 C:\HxopsRpa...\inventory_drop\file.xlsx;Linux 后端必须映射到
|
||||
# SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR 下同名文件,否则 Path(windows).is_file() 恒假。
|
||||
raw_file_path = str(payload.get('file_path') or '').strip()
|
||||
path: Path | None = None
|
||||
from app.services.shipping_notice.rpa import inventory_drop_dir
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import _resolve_shared_inventory_drop_file
|
||||
drop_root = inventory_drop_dir()
|
||||
if drop_root is not None:
|
||||
path = _resolve_shared_inventory_drop_file(raw_file_path, allowed_root=drop_root)
|
||||
if path is None:
|
||||
candidate = Path(raw_file_path)
|
||||
if candidate.is_file():
|
||||
path = candidate
|
||||
if path is None or not path.is_file():
|
||||
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
return _payload(run)
|
||||
|
||||
@@ -5,7 +5,8 @@ services/shipping_notice/inventory_rpa_workflow.py
|
||||
依赖:customer_identity_gate、reservation_gate、rpa、rpa_attempts、inventory_snapshot、
|
||||
inventory_mapping_workflow、query_service、动态订单字段、tool_common、state_machine、tool_response。
|
||||
逻辑:inventory_workflow.ensure_inventory 在 auto 时仅复用快照、在 retry_rpa 时委托本模块触发刷新;
|
||||
库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取。
|
||||
库存源始终由规则 Gate 自动裁决;Reservation 门禁从当前 Extraction 的动态 FieldValue 读取;
|
||||
复用 ready 快照走 link_snapshot_to_task_for_preparation(动态仓未决可 pending_matching)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -148,7 +149,8 @@ def _try_reuse_inventory_snapshot(
|
||||
优先复用未过期库存快照,避免重复触发 RPA。
|
||||
【AI 触发时机】:ensure_inventory_via_rpa 已确定库存源且 mode 非 retry_rpa 时调用。
|
||||
|
||||
核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则 link 并进入待匹配状态。
|
||||
核心逻辑:按 source_code + 发货 Excel warehouse id 查找 ready 快照;命中则用
|
||||
preparation 软绑定并进入待匹配状态(动态仓未决不视为缺文件)。
|
||||
retry_rpa 必须跳过缓存强制重新导出。
|
||||
"""
|
||||
if mode == "retry_rpa":
|
||||
@@ -163,7 +165,7 @@ def _try_reuse_inventory_snapshot(
|
||||
if not snapshot:
|
||||
return None
|
||||
|
||||
link = link_snapshot_to_task(
|
||||
link = link_snapshot_to_task_for_preparation(
|
||||
task,
|
||||
snapshot,
|
||||
reason="reuse_latest",
|
||||
|
||||
@@ -6,7 +6,8 @@ services/shipping_notice/inventory_workflow.py
|
||||
inventory_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。
|
||||
逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除;
|
||||
payload.source_codes 可收窄 ensure_inventory / RPA 作用源(行级重抓);
|
||||
STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File。
|
||||
STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File;
|
||||
动态仓复用走 link_snapshot_to_task_for_preparation,仓未决不得谎称库存文件缺失。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -65,8 +66,9 @@ def _link_ready_candidate_prep_or_block(
|
||||
STP 候选库存 ready 后,确保 OT 已绑定有效库存文件再允许写回解析结果。
|
||||
|
||||
核心逻辑:已有 active link 直接放行;否则取 evidence(或行标签)中首个 loaded
|
||||
快照并 ``link_snapshot_to_task``(与单源 reuse 对齐)。绑定失败返回 needs_human,
|
||||
禁止抛出「未绑定库存文件」ValueError 把 Gate Job 打成 technical_failure。
|
||||
快照并 ``link_snapshot_to_task_for_preparation``。动态仓仓库识别失败时仍保留文件绑定
|
||||
(pending_matching),仓/匹配问题留给 inventory_matching,禁止把「有文件」投影成
|
||||
inventory_file_missing。仅当真的无法绑定文件时才 needs_human。
|
||||
|
||||
Args:
|
||||
task: 已冻结候选源的订单任务。
|
||||
@@ -78,7 +80,9 @@ def _link_ready_candidate_prep_or_block(
|
||||
"""
|
||||
from app.models import ShippingInventoryFile
|
||||
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
|
||||
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
|
||||
from app.services.shipping_notice.inventory_snapshot_store import (
|
||||
link_snapshot_to_task_for_preparation,
|
||||
)
|
||||
|
||||
# [STEP 1] 已绑定则无需重复 link。
|
||||
if active_inventory_file_for_task(task) is not None:
|
||||
@@ -109,11 +113,12 @@ def _link_ready_candidate_prep_or_block(
|
||||
)
|
||||
link = None
|
||||
if inv_file is not None:
|
||||
link = link_snapshot_to_task(
|
||||
# [STEP] 与 RPA 回调同权:文件事实先挂 OT;动态仓未决 → pending_matching,
|
||||
# 不因 warehouse_configuration_invalid 谎称「库存文件未准备」。
|
||||
link = link_snapshot_to_task_for_preparation(
|
||||
task,
|
||||
inv_file,
|
||||
reason='stp_candidate_prep',
|
||||
role='owner',
|
||||
audit_payload={
|
||||
'candidate_set_id': prep.get('candidate_set_id'),
|
||||
'loaded_source_codes': list(prep.get('loaded_source_codes') or []),
|
||||
@@ -123,7 +128,7 @@ def _link_ready_candidate_prep_or_block(
|
||||
db.session.flush()
|
||||
return None
|
||||
|
||||
# [STEP 3] 无法绑定:软阻断,留给人工重试/上传,勿让 Gate Job 因 ValueError 失败。
|
||||
# [STEP 3] 真的没有可绑定文件:软阻断,勿让 Gate Job 因 ValueError 失败。
|
||||
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
|
||||
set_task_step_progress(
|
||||
task,
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
"""
|
||||
services/shipping_notice/line_field_supplement_merge.py
|
||||
|
||||
用途:将同文档「明细字段补充表」(如 Hyve COO)按 LN 保守合并进主表明细。
|
||||
依赖:无外部 IO;仅字符串规范化与行字典读写。
|
||||
逻辑:由正式解析 / 盲测 / 验证在主表重建后调用;只补 customer_part_number、part_number;
|
||||
空值直补、主表为补充值前缀则补全、冲突不覆盖并写稳定 reason。不改数量/单价/金额。
|
||||
``REASON_APPLIED`` 仅写入表级 reasons 审计,不进入行 ``issues``(成功补齐不得触发 row_needs_review)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
LINE_FIELD_SUPPLEMENT_CODES = frozenset({'customer_part_number', 'part_number'})
|
||||
DEFAULT_LINE_START_FIELD_CODE = 'customer_po_line_no'
|
||||
|
||||
REASON_APPLIED = 'line_field_supplement_applied'
|
||||
REASON_CONFLICT = 'line_field_supplement_conflict'
|
||||
REASON_LN_AMBIGUOUS = 'line_field_supplement_ln_ambiguous'
|
||||
REASON_LN_MISSING = 'line_field_supplement_ln_missing'
|
||||
|
||||
# 表级审计码:不得当作行级缺陷拦截确定性建单。
|
||||
NON_BLOCKING_ROW_ISSUE_CODES = frozenset({REASON_APPLIED})
|
||||
|
||||
|
||||
def normalize_line_start_key(raw: Any) -> str:
|
||||
"""
|
||||
将行号规范为对齐键:去空白;纯数字去掉无意义前导零(保留至少一位)。
|
||||
|
||||
Args:
|
||||
raw: 主表或补充表上的起行字段值。
|
||||
|
||||
Returns:
|
||||
非空对齐键;无法规范化时返回空串。
|
||||
"""
|
||||
text = re.sub(r'\s+', '', str(raw or '')).strip()
|
||||
if not text:
|
||||
return ''
|
||||
if text.isdigit():
|
||||
return str(int(text))
|
||||
return text
|
||||
|
||||
|
||||
def normalize_part_value(raw: Any) -> str:
|
||||
"""料号比较用:去掉空白,保留连字符等符号。"""
|
||||
return re.sub(r'\s+', '', str(raw or '')).strip()
|
||||
|
||||
|
||||
def _row_field_map(row: dict[str, Any]) -> dict[str, str]:
|
||||
"""将扁平行或 workflow ``fields`` 列表统一为 field_code -> 文本值。"""
|
||||
if not isinstance(row, dict):
|
||||
return {}
|
||||
fields = row.get('fields')
|
||||
if isinstance(fields, list):
|
||||
result: dict[str, str] = {}
|
||||
for item in fields:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
code = str(item.get('field_code') or '').strip()
|
||||
if not code:
|
||||
continue
|
||||
result[code] = str(item.get('value') or '').strip()
|
||||
return result
|
||||
return {
|
||||
str(key): str(value or '').strip()
|
||||
for key, value in row.items()
|
||||
if key not in {'fields', 'issues', 'status', 'row_index', 'role', 'source_row_indices'}
|
||||
and not str(key).startswith('_')
|
||||
}
|
||||
|
||||
|
||||
def _set_row_field(row: dict[str, Any], field_code: str, value: str) -> None:
|
||||
"""按行形态写回字段值;workflow 行写入 ``fields`` 列表。"""
|
||||
fields = row.get('fields')
|
||||
if isinstance(fields, list):
|
||||
target = next(
|
||||
(
|
||||
item for item in fields
|
||||
if isinstance(item, dict) and str(item.get('field_code') or '') == field_code
|
||||
),
|
||||
None,
|
||||
)
|
||||
if target is None:
|
||||
fields.append({'field_code': field_code, 'value': value})
|
||||
else:
|
||||
target['value'] = value
|
||||
return
|
||||
row[field_code] = value
|
||||
|
||||
|
||||
def _append_row_issue(row: dict[str, Any], code: str) -> None:
|
||||
"""为 workflow 行追加 issue;扁平行写入 ``issues`` 列表供调用方读取。"""
|
||||
issues = row.get('issues')
|
||||
if not isinstance(issues, list):
|
||||
row['issues'] = [code]
|
||||
return
|
||||
if code not in issues:
|
||||
issues.append(code)
|
||||
|
||||
|
||||
def _index_rows_by_line(
|
||||
rows: list[dict[str, Any]],
|
||||
*,
|
||||
line_start_field_code: str,
|
||||
) -> tuple[dict[str, dict[str, Any]], set[str], list[str]]:
|
||||
"""
|
||||
按规范化 LN 建唯一索引。
|
||||
|
||||
Returns:
|
||||
(唯一行映射, 重复 LN 集合, 缺 LN 的全局 reasons)
|
||||
"""
|
||||
buckets: dict[str, list[dict[str, Any]]] = {}
|
||||
missing_reasons: list[str] = []
|
||||
for row in rows:
|
||||
key = normalize_line_start_key(_row_field_map(row).get(line_start_field_code))
|
||||
if not key:
|
||||
missing_reasons.append(REASON_LN_MISSING)
|
||||
continue
|
||||
buckets.setdefault(key, []).append(row)
|
||||
unique: dict[str, dict[str, Any]] = {}
|
||||
ambiguous: set[str] = set()
|
||||
for key, items in buckets.items():
|
||||
if len(items) != 1:
|
||||
ambiguous.add(key)
|
||||
continue
|
||||
unique[key] = items[0]
|
||||
return unique, ambiguous, missing_reasons
|
||||
|
||||
|
||||
def merge_line_field_supplement(
|
||||
main_rows: list[dict[str, Any]],
|
||||
supplement_rows: list[dict[str, Any]],
|
||||
*,
|
||||
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
|
||||
field_codes: frozenset[str] = LINE_FIELD_SUPPLEMENT_CODES,
|
||||
) -> tuple[list[dict[str, Any]], list[str]]:
|
||||
"""
|
||||
按 LN 将补充表料号合并进主表明细。
|
||||
|
||||
核心逻辑:只处理 ``field_codes``;空值直补;主表规范化值是补充值前缀则补全;
|
||||
两边完整且不同则写冲突 reason 且不覆盖;补充侧或主侧 LN 重复/缺失则跳过该键。
|
||||
成功补齐仅写入返回的 reasons(``REASON_APPLIED``),不写入行 ``issues``。
|
||||
|
||||
Args:
|
||||
main_rows: 主表明细(扁平 dict 或含 ``fields`` 的 workflow 行)。
|
||||
supplement_rows: 补充表重建行,形态同主表。
|
||||
line_start_field_code: 对齐用起行字段,默认 customer_po_line_no。
|
||||
field_codes: 允许补齐的字段集合。
|
||||
|
||||
Returns:
|
||||
(合并后的主表行深拷贝, 稳定 reason 列表;可含表级审计码与行级冲突码)
|
||||
"""
|
||||
if not main_rows or not supplement_rows:
|
||||
return [copy.deepcopy(row) for row in main_rows], []
|
||||
|
||||
merged = [copy.deepcopy(row) for row in main_rows]
|
||||
main_index, main_ambiguous, main_missing = _index_rows_by_line(
|
||||
merged, line_start_field_code=line_start_field_code,
|
||||
)
|
||||
supplement_index, supplement_ambiguous, supplement_missing = _index_rows_by_line(
|
||||
supplement_rows, line_start_field_code=line_start_field_code,
|
||||
)
|
||||
|
||||
reasons: list[str] = []
|
||||
reasons.extend(main_missing)
|
||||
reasons.extend(supplement_missing)
|
||||
for key in sorted(main_ambiguous | supplement_ambiguous):
|
||||
reasons.append(REASON_LN_AMBIGUOUS)
|
||||
if key in main_index:
|
||||
_append_row_issue(main_index[key], REASON_LN_AMBIGUOUS)
|
||||
for row in merged:
|
||||
if normalize_line_start_key(_row_field_map(row).get(line_start_field_code)) == key:
|
||||
_append_row_issue(row, REASON_LN_AMBIGUOUS)
|
||||
|
||||
for line_key, main_row in main_index.items():
|
||||
if line_key in main_ambiguous or line_key in supplement_ambiguous:
|
||||
continue
|
||||
supplement_row = supplement_index.get(line_key)
|
||||
if supplement_row is None:
|
||||
continue
|
||||
main_fields = _row_field_map(main_row)
|
||||
supplement_fields = _row_field_map(supplement_row)
|
||||
for code in sorted(field_codes):
|
||||
supplement_raw = supplement_fields.get(code) or ''
|
||||
if not supplement_raw:
|
||||
continue
|
||||
main_raw = main_fields.get(code) or ''
|
||||
main_norm = normalize_part_value(main_raw)
|
||||
supplement_norm = normalize_part_value(supplement_raw)
|
||||
if not supplement_norm:
|
||||
continue
|
||||
if not main_norm:
|
||||
# [STEP] 成功直补:只记表级审计,不写行 issues(避免误判 row_needs_review)。
|
||||
_set_row_field(main_row, code, supplement_raw)
|
||||
reasons.append(REASON_APPLIED)
|
||||
continue
|
||||
if main_norm == supplement_norm:
|
||||
continue
|
||||
if supplement_norm.startswith(main_norm) and len(supplement_norm) > len(main_norm):
|
||||
# [STEP] 前缀补全成功:同上,审计进 reasons,不写入 issues。
|
||||
_set_row_field(main_row, code, supplement_raw)
|
||||
reasons.append(REASON_APPLIED)
|
||||
continue
|
||||
_append_row_issue(main_row, REASON_CONFLICT)
|
||||
reasons.append(REASON_CONFLICT)
|
||||
|
||||
# 保持 reason 顺序稳定且去重保留首次出现,便于审计对照。
|
||||
deduped: list[str] = []
|
||||
seen: set[str] = set()
|
||||
for code in reasons:
|
||||
if code in seen:
|
||||
continue
|
||||
seen.add(code)
|
||||
deduped.append(code)
|
||||
return merged, deduped
|
||||
|
||||
|
||||
def project_line_field_supplement_onto_validation_evidence(
|
||||
evidence: dict[str, Any],
|
||||
*,
|
||||
supplement_rows: list[dict[str, Any]],
|
||||
line_start_field_code: str = DEFAULT_LINE_START_FIELD_CODE,
|
||||
) -> tuple[dict[str, Any], list[str]]:
|
||||
"""
|
||||
将补充表合并结果写回验证证据的 lines 字段。
|
||||
|
||||
Args:
|
||||
evidence: 含 header_fields / lines 的验证 DTO。
|
||||
supplement_rows: workflow 或扁平行。
|
||||
line_start_field_code: LN 对齐字段。
|
||||
|
||||
Returns:
|
||||
(更新后的 evidence 深拷贝, reason 列表)
|
||||
"""
|
||||
if not isinstance(evidence, dict) or not supplement_rows:
|
||||
return copy.deepcopy(evidence) if isinstance(evidence, dict) else {}, []
|
||||
result = copy.deepcopy(evidence)
|
||||
lines = result.get('lines') if isinstance(result.get('lines'), list) else []
|
||||
main_rows: list[dict[str, Any]] = []
|
||||
for line in lines:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
fields = []
|
||||
for item in line.get('fields') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
fields.append({
|
||||
'field_code': str(item.get('field_code') or ''),
|
||||
'value': str(item.get('raw_value') or item.get('normalized_value') or ''),
|
||||
})
|
||||
main_rows.append({'fields': fields, 'issues': []})
|
||||
if not main_rows:
|
||||
return result, []
|
||||
merged, reasons = merge_line_field_supplement(
|
||||
main_rows, supplement_rows, line_start_field_code=line_start_field_code,
|
||||
)
|
||||
for index, row in enumerate(merged):
|
||||
if index >= len(lines) or not isinstance(lines[index], dict):
|
||||
continue
|
||||
values = _row_field_map(row)
|
||||
issues = list(row.get('issues') or [])
|
||||
for field in lines[index].get('fields') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
code = str(field.get('field_code') or '')
|
||||
if code not in LINE_FIELD_SUPPLEMENT_CODES or code not in values:
|
||||
continue
|
||||
value = values[code]
|
||||
field['raw_value'] = value or None
|
||||
field['normalized_value'] = value or None
|
||||
field['status'] = 'passed' if value else field.get('status') or 'missing'
|
||||
if issues:
|
||||
field['issues'] = list(dict.fromkeys([*(field.get('issues') or []), *issues]))
|
||||
result['line_field_supplement_reasons'] = list(reasons)
|
||||
return result, reasons
|
||||
+12
-2
@@ -265,14 +265,21 @@ def _resolve_overlap_run(
|
||||
|
||||
|
||||
def _blocking_from_overlap(summary: dict[str, Any] | None, overlap_run: ShippingOrderDocumentProfileValidationRun | None, revision: ShippingOrderDocumentProfileDraftRevision) -> list[dict[str, Any]]:
|
||||
"""将重叠验证摘要转为发布阻断项。"""
|
||||
"""
|
||||
将重叠验证摘要转为发布阻断项。
|
||||
|
||||
核心逻辑:仅在 definition_checksum 漂移时标为 stale;当前草稿上的 failed 运行
|
||||
必须展开真实门禁(如 self_match_not_unique),禁止误报“验证已过期”。
|
||||
"""
|
||||
blocking: list[dict[str, Any]] = []
|
||||
if overlap_run is None:
|
||||
blocking.append({'key': 'overlap_validation_required', 'message': 'Cross-template overlap validation is required.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
return blocking
|
||||
if overlap_run.definition_checksum != revision.definition_checksum or overlap_run.status != 'passed':
|
||||
# [STEP 1] checksum 漂移才是 stale;failed≠过期。
|
||||
if overlap_run.definition_checksum != revision.definition_checksum:
|
||||
blocking.append({'key': 'overlap_validation_stale', 'message': 'Cross-template overlap validation is stale.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
return blocking
|
||||
# [STEP 2] 当前草稿的 passed/failed 一律按摘要指标展开,避免掩盖真实阻断原因。
|
||||
summary = summary or dict(overlap_run.summary_json or {})
|
||||
snapshot = dict(overlap_run.result_snapshot_json or {})
|
||||
if float(summary.get('self_unique_hit_rate_training') or 0) < 1.0:
|
||||
@@ -303,6 +310,9 @@ def _blocking_from_overlap(summary: dict[str, Any] | None, overlap_run: Shipping
|
||||
'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED',
|
||||
'conflict_profiles': list(snapshot.get('conflict_profiles') or []),
|
||||
})
|
||||
# [STEP 3] failed 但摘要未给出可映射指标时,回落为明确失败文案,禁止冒充 stale。
|
||||
if not blocking and overlap_run.status != 'passed':
|
||||
blocking.append({'key': 'overlap_validation_failed', 'message': 'Cross-template overlap validation failed.', 'code': 'SHIPPING.ORDER_DOCUMENT_PROFILE_OVERLAP_DETECTED'})
|
||||
return blocking
|
||||
|
||||
|
||||
|
||||
@@ -75,7 +75,6 @@ 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}$')
|
||||
@@ -1155,7 +1154,22 @@ def read_preview_page_region_text(
|
||||
db.session.commit()
|
||||
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)
|
||||
# 画布预览候选与正式解析共用 Vendor Comments→Terms;矩形 text 仅作圈选回显。
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_region import reservation_region_candidates_from_layout
|
||||
|
||||
full_layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=_document_layout(document), page_nos=None,
|
||||
)
|
||||
scanned = reservation_region_candidates_from_layout(
|
||||
definition={'reservation_id_region': {'page_no': int(page_no), 'region': region}},
|
||||
layout=full_layout,
|
||||
)
|
||||
result['reservation_candidates'] = scanned.get('candidates') or []
|
||||
if scanned.get('reason'):
|
||||
result['reservation_region_reason'] = scanned['reason']
|
||||
return result
|
||||
|
||||
|
||||
@@ -1275,6 +1289,9 @@ def preview_profile_region(
|
||||
# Header-only pages document column semantics but must never emit data rows.
|
||||
if not table_region.line_layouts:
|
||||
continue
|
||||
# 补充表不进入预览主网格;验证/正式路径另行按 LN 合并。
|
||||
if str(getattr(table_region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
|
||||
continue
|
||||
# 表头区域只描述列语义与预览,运行时不得删除其覆盖的 glyph;起行 Schema
|
||||
# 交叉校验会拒绝表头,普通 exclusion_regions 才是显式删除授权。
|
||||
reconstruction_exclusions = reconstruction_exclusion_regions(table_region.model_dump())
|
||||
|
||||
@@ -2,10 +2,12 @@
|
||||
services/shipping_notice/order_document_profile_validation_service.py
|
||||
|
||||
用途:执行订单文档 Profile 草稿的不可变即时检查、当前样本试运行、版面/XFA 结构签名与跨模板唯一性验证。
|
||||
依赖:Profile Revision、受控样本、版面签名/匹配服务、XFA 提取与结构签名、解析校验、Profile 保存服务及编辑租约服务。
|
||||
逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;XFA current-sample 另附脱敏字段级 Header/Line;
|
||||
签名成功后更新 Profile 轻量引用;跨模板重叠验证消费已发布快照与统一 matcher;
|
||||
查询时根据当前 checksum 派生 stale,绝不改写历史运行。
|
||||
依赖:Profile Revision、受控样本、版面签名/匹配服务、XFA 提取与结构签名、解析校验、
|
||||
Profile 保存服务、编辑租约服务、Reservation 专区锚点投影、line_field_supplement_merge。
|
||||
逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;坐标 current-sample 在表格/
|
||||
表头试读后投影 Vendor Comments Reservation,并按 LN 合并 COO 等补充表料号;
|
||||
XFA current-sample 另附脱敏字段级 Header/Line;签名成功后更新 Profile 轻量引用;
|
||||
查询时根据当前 checksum 派生 stale。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -344,6 +346,14 @@ def _extract_coordinate_current_sample(
|
||||
actor_id: int | None,
|
||||
) -> tuple[str, dict[str, Any], dict[str, Any]]:
|
||||
"""通过 coordinate value adapter 生成与 XFA 相同的当前样本结果 DTO。"""
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_region import (
|
||||
project_reservation_onto_validation_evidence,
|
||||
reservation_region_candidates_from_layout,
|
||||
)
|
||||
|
||||
table_id = profile_service.resolve_profile_sample_table_id(profile, sample)
|
||||
preview = profile_service.preview_profile_region(profile.id, data={
|
||||
'document_id': sample.document_id, 'table_id': table_id,
|
||||
@@ -385,11 +395,70 @@ def _extract_coordinate_current_sample(
|
||||
header_required_missing_count=len(required_header_ids - readable_header_ids),
|
||||
sample_role=sample.sample_role,
|
||||
)
|
||||
summary['validation_evidence'] = _build_coordinate_validation_evidence(
|
||||
evidence = _build_coordinate_validation_evidence(
|
||||
rows=list(rows[1:]) if isinstance(rows, list) else [],
|
||||
field_codes=list(fields or []),
|
||||
header_fields=list(header_fields),
|
||||
)
|
||||
# [STEP] Reservation 专区与正式解析共用 Vendor Comments 锚点;验证页必须展示同一结果。
|
||||
if isinstance(definition.get('reservation_id_region'), dict):
|
||||
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
|
||||
layout = _load_sample_layout(sample) if document is not None else {}
|
||||
if document is not None and isinstance(layout, dict):
|
||||
layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=layout, page_nos=None,
|
||||
)
|
||||
reservation = reservation_region_candidates_from_layout(definition=definition, layout=layout)
|
||||
schema_fields = {
|
||||
str(item.get('field_id') or ''): item
|
||||
for item in (profile.schema_version.definition_json or {}).get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
|
||||
}
|
||||
evidence = project_reservation_onto_validation_evidence(
|
||||
evidence,
|
||||
candidates=list(reservation.get('candidates') or []),
|
||||
reason=reservation.get('reason'),
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
# [STEP] COO 等明细字段补充表按 LN 合并进验证 lines(与正式/盲测同契约)。
|
||||
if any(
|
||||
isinstance(item, dict) and str(item.get('region_role') or '') == 'line_field_supplement'
|
||||
for item in definition.get('table_regions') or []
|
||||
):
|
||||
from app.services.shipping_notice.line_field_supplement_merge import (
|
||||
project_line_field_supplement_onto_validation_evidence,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
_reconstruct_line_field_supplement_rows,
|
||||
)
|
||||
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
|
||||
layout = _load_sample_layout(sample) if document is not None else {}
|
||||
if document is not None and isinstance(layout, dict):
|
||||
layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=layout, page_nos=None,
|
||||
)
|
||||
schema_fields = {
|
||||
str(item.get('field_id') or ''): item
|
||||
for item in (profile.schema_version.definition_json or {}).get('fields') or []
|
||||
if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')
|
||||
}
|
||||
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
|
||||
raw_profile={
|
||||
'definition': definition,
|
||||
'profile_code': profile.profile_code,
|
||||
'version': profile.version,
|
||||
'checksum': profile.checksum,
|
||||
},
|
||||
layout=layout if isinstance(layout, dict) else {},
|
||||
schema_fields=schema_fields,
|
||||
)
|
||||
if supplement_rows:
|
||||
evidence, _reasons = project_line_field_supplement_onto_validation_evidence(
|
||||
evidence,
|
||||
supplement_rows=supplement_rows,
|
||||
line_start_field_code=line_start or 'customer_po_line_no',
|
||||
)
|
||||
summary['validation_evidence'] = evidence
|
||||
return status, summary, snapshot
|
||||
|
||||
|
||||
|
||||
@@ -1201,6 +1201,88 @@ def order_extraction_layouts_pending(run: ShippingOrderProcessingRun) -> bool:
|
||||
return 'layout_pending' in order_extraction_layout_prerequisite_issues(run).values()
|
||||
|
||||
|
||||
_EXTRACT_DONE_UNIT_STATUSES = frozenset({
|
||||
'candidate_ready', 'review_required', 'failed', 'cancelled',
|
||||
})
|
||||
# layout 与 extraction 共 shipping 队列且默认 priority=0;resume 抬高后才能插队,
|
||||
# 否则「单文件版式完成」的 extraction 仍排在剩余 layout FIFO 之后。
|
||||
_ORDER_EXTRACTION_READY_PRIORITY = 10
|
||||
|
||||
|
||||
def _enqueue_ready_order_extraction_job(
|
||||
run: ShippingOrderProcessingRun, *, message: str,
|
||||
) -> int:
|
||||
"""
|
||||
为已有 ready 活的 Run 入队(或复用)extraction Job,并抬高 queued 优先级以便插队。
|
||||
|
||||
核心逻辑:enqueue 去重可能返回仍在排队的早建 Job;必须把其 priority 提到
|
||||
_ORDER_EXTRACTION_READY_PRIORITY,否则 claim 仍按 created_at 先消化 layout。
|
||||
"""
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run.run_no},
|
||||
domain='shipping_notice',
|
||||
business_ref=run.run_no,
|
||||
created_by_id=run.user_id,
|
||||
priority=_ORDER_EXTRACTION_READY_PRIORITY,
|
||||
max_attempts=3,
|
||||
message=message,
|
||||
commit=False,
|
||||
)
|
||||
job = db.session.get(Job, int(job_id))
|
||||
if (
|
||||
job is not None
|
||||
and str(job.status or '') == 'queued'
|
||||
and int(job.priority or 0) < _ORDER_EXTRACTION_READY_PRIORITY
|
||||
):
|
||||
job.priority = _ORDER_EXTRACTION_READY_PRIORITY
|
||||
job.message = message
|
||||
return int(job_id)
|
||||
|
||||
|
||||
def order_extraction_ready_document_ids(run: ShippingOrderProcessingRun) -> set[int]:
|
||||
"""
|
||||
返回本 Run 快照中已通过版面前置条件、可立即抽取的订单 PDF Document ID。
|
||||
|
||||
核心逻辑:复用 order_extraction_layout_prerequisite_issues;未出现在 issues 中的 PDF
|
||||
视为 ready。非 PDF 不参与。
|
||||
"""
|
||||
issues = order_extraction_layout_prerequisite_issues(run)
|
||||
ready: set[int] = set()
|
||||
for document in _run_layout_documents(run):
|
||||
if Path(str(document.filename or '')).suffix.lower() != '.pdf':
|
||||
continue
|
||||
document_id = int(document.id)
|
||||
if document_id not in issues:
|
||||
ready.add(document_id)
|
||||
return ready
|
||||
|
||||
|
||||
def order_extraction_has_extractable_ready_work(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""
|
||||
判断是否存在「版式已就绪、Unit 尚未收口」的可抽取工作。
|
||||
|
||||
核心逻辑:有 ready PDF 且(尚无 Plan / Plan 为空 → 需要建计划抽取;或存在对应
|
||||
Unit 未到 candidate_ready/review_required/failed/cancelled)。
|
||||
"""
|
||||
ready_ids = order_extraction_ready_document_ids(run)
|
||||
if not ready_ids:
|
||||
return False
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
if plan is None or int(plan.unit_count or 0) <= 0:
|
||||
return True
|
||||
units = ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all()
|
||||
for unit in units:
|
||||
if int(unit.document_id or 0) not in ready_ids:
|
||||
continue
|
||||
if str(unit.status or '') not in _EXTRACT_DONE_UNIT_STATUSES:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def order_extraction_layouts_failed(run: ShippingOrderProcessingRun) -> bool:
|
||||
"""判断当前应消费的布局是否最终失败;历史失败版本不得污染后续成功重识别。
|
||||
|
||||
@@ -1311,17 +1393,63 @@ def schedule_order_extraction_layouts(
|
||||
|
||||
|
||||
def resume_runs_waiting_for_layout(*, document_id: int) -> int:
|
||||
"""布局任务完成后唤醒所有已具备完整布局的 Run,确保订单任务不会早于版面快照执行。"""
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
"""
|
||||
单份附件布局完成后唤醒仍等待版式的 Run。
|
||||
|
||||
核心逻辑:不再要求 Run 内全部 PDF 版式就绪;只要存在可抽取的 ready Document,
|
||||
即以抬高 priority 入队(或复用活跃)shipping_order_extraction,避免被剩余 layout
|
||||
FIFO 堵住。无 ready 活且无 pending、仅有失败版式、且尚未抽出任何 Unit 时整 Run 失败。
|
||||
"""
|
||||
resumed = 0
|
||||
runs = ShippingOrderProcessingRun.query.filter_by(status='queued', phase='waiting_layout').with_for_update().all()
|
||||
# processing + waiting_layout:部分 Unit 已抽完、仍等兄弟文件版式。
|
||||
runs = (
|
||||
ShippingOrderProcessingRun.query.filter(
|
||||
ShippingOrderProcessingRun.status.in_(('queued', 'processing')),
|
||||
ShippingOrderProcessingRun.phase == 'waiting_layout',
|
||||
)
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
for run in runs:
|
||||
if int(document_id) not in _run_snapshot_document_ids(run) or order_extraction_layouts_pending(run):
|
||||
if int(document_id) not in _run_snapshot_document_ids(run):
|
||||
continue
|
||||
if order_extraction_has_extractable_ready_work(run):
|
||||
job_id = _enqueue_ready_order_extraction_job(
|
||||
run, message='附件解析完成,等待订单识别',
|
||||
)
|
||||
run.current_job_id = job_id
|
||||
# 仍有兄弟 layout pending 时保持 waiting_layout,便于再次 resume;
|
||||
# 已无 pending 则改为 queued,表示本轮可抽尽。
|
||||
run.phase = 'waiting_layout' if order_extraction_layouts_pending(run) else 'queued'
|
||||
record_run_progress(
|
||||
run=run,
|
||||
event_code='layout_parsing_completed',
|
||||
summary={'document_id': int(document_id), 'partial': order_extraction_layouts_pending(run)},
|
||||
commit=False,
|
||||
)
|
||||
resumed += 1
|
||||
continue
|
||||
if order_extraction_layouts_pending(run):
|
||||
continue
|
||||
if order_extraction_layouts_failed(run):
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_failed')
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
progressed = False
|
||||
if plan is not None:
|
||||
progressed = any(
|
||||
str(unit.status or '') in _EXTRACT_DONE_UNIT_STATUSES
|
||||
for unit in ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all()
|
||||
)
|
||||
if progressed:
|
||||
# 已有 Unit 成功/复核:再入队一次让 Worker 收口,禁止整 Run 抹掉部分成果。
|
||||
job_id = _enqueue_ready_order_extraction_job(
|
||||
run, message='部分附件版式失败,等待订单识别收口',
|
||||
)
|
||||
run.current_job_id = job_id
|
||||
run.phase = 'queued'
|
||||
resumed += 1
|
||||
continue
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase='layout_failed')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', phase='layout_failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED',
|
||||
@@ -1332,16 +1460,6 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED', commit=False,
|
||||
)
|
||||
resumed += 1
|
||||
continue
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run.run_no}, domain='shipping_notice', business_ref=run.run_no,
|
||||
created_by_id=run.user_id, max_attempts=3, message='附件解析完成,等待订单识别', commit=False,
|
||||
)
|
||||
run.current_job_id = job_id
|
||||
run.phase = 'queued'
|
||||
record_run_progress(run=run, event_code='layout_parsing_completed', commit=False)
|
||||
resumed += 1
|
||||
if resumed:
|
||||
db.session.commit()
|
||||
return resumed
|
||||
@@ -1355,7 +1473,8 @@ def materialize_order_extraction_run_inputs(
|
||||
|
||||
AI 触发时机:仅订单抽取 Job 开始时调用;HTTP 发送路径严禁调用。
|
||||
核心逻辑:使用创建时冻结的 Schema/附件选择和 Intake 标识,先物化首轮;
|
||||
布局任务尚未完成时只刷新 Document 快照,待布局就绪后再冻结计划。
|
||||
允许在部分 PDF 版式仍 pending 时 finalize Plan(未 ready 的 Unit 挂 pending),
|
||||
供按 Unit 流水线抽取;已存在 Plan 时只刷新各 Document 的当前布局证据。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
|
||||
@@ -2266,8 +2385,8 @@ def create_order_extraction_run(
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
# 立即建立 Job 保持 Run 的可追踪性;Handler 发现 waiting_layout 后只安全收口,
|
||||
# 绝不开始订单提取。最后一份布局完成会创建真正可执行的后继 Job。
|
||||
# 立即建立 Job 保持 Run 的可追踪性;Handler 在零 ready 时只安全收口,
|
||||
# 有 ready PDF 时按 Unit 抽取。任一布局完成即可 resume 后继 Job(无需等齐)。
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run.run_no},
|
||||
|
||||
@@ -3,11 +3,12 @@ backend/app/services/shipping_notice/order_extraction_workflow.py
|
||||
|
||||
用途:提供冻结订单抽取快照的确定性模板路由及 STP 裁决(straight_through / needs_review)。
|
||||
依赖:MinerU 紧凑快照、订单 Profile(coordinate / xfa_dataset)、Schema 校验、
|
||||
order_extraction_route_contract、xfa_profile_*、统一错误类型。
|
||||
order_extraction_route_contract、xfa_profile_*、line_field_supplement_merge、统一错误类型。
|
||||
逻辑:Worker 先调用本模块裁决;所有 PDF 先走共同视觉路径,datasets 仅在末端取正式值;
|
||||
datasets 缺失或冲突时共同 OCR 仅作复核/兜底证据并强制 needs_review;
|
||||
唯一 PO 提升到 Header 后从明细剥离,避免 persist 因 scope 不匹配失败;
|
||||
路由产出 Candidate 后由 Candidate Qualification 统一评估自动建单资格;
|
||||
主明细仅来自 region_role=business_lines;line_field_supplement 按 LN 补料号;
|
||||
模板 auto_create_approved 仅作解析器质量痕迹;主链不调用 Dify。
|
||||
"""
|
||||
|
||||
@@ -38,6 +39,10 @@ from app.services.shipping_notice.document_layout.runtime_parse_strategy import
|
||||
resolve_runtime_parse_strategy,
|
||||
select_runtime_region_ids,
|
||||
)
|
||||
from app.services.shipping_notice.line_field_supplement_merge import (
|
||||
NON_BLOCKING_ROW_ISSUE_CODES,
|
||||
merge_line_field_supplement,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.order_field_extraction import extract_order_fields
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
ProfileMatchResult,
|
||||
@@ -58,7 +63,6 @@ from app.services.shipping_notice.order_profile_value_adapter import get_value_a
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
|
||||
from app.services.shipping_notice.reservation_region import (
|
||||
apply_reservation_region_candidates,
|
||||
extract_reservation_from_vendor_comments_pages,
|
||||
)
|
||||
|
||||
|
||||
@@ -380,6 +384,9 @@ def _coordinate_profile_rows(
|
||||
# 的坐标、起行字段与行重建结果裁决,不能仅依赖历史 page_scope 自动建单。
|
||||
if region.region_id not in runtime_region_ids:
|
||||
continue
|
||||
# 补充表不参与主明细重建,避免 COO 等副表进入 matches / multiple_business_tables。
|
||||
if str(getattr(region, 'region_role', None) or 'business_lines') == 'line_field_supplement':
|
||||
continue
|
||||
# A continuation page may carry column headers only; it is not a data layout.
|
||||
if not region.line_layouts:
|
||||
continue
|
||||
@@ -470,6 +477,239 @@ def _coordinate_profile_rows(
|
||||
return rows
|
||||
|
||||
|
||||
def _pick_overlapping_layout_table(
|
||||
*,
|
||||
layout_tables: list[Any],
|
||||
page_no: int,
|
||||
region_relative: dict[str, Any],
|
||||
page_size: dict[str, Any],
|
||||
reference_page_frame: dict[str, Any] | None = None,
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
) -> tuple[str | None, dict[str, float] | None]:
|
||||
"""
|
||||
在同页 layout.tables 中选取与补充表相对区重叠的物理表。
|
||||
|
||||
核心逻辑:将相对区投影为页绝对框后与 MinerU 表求交,取纵向重叠面积最大者。
|
||||
用于样本仅 1 行 COO 时,盲测多行仍能纵向扩到整张物理表读 glyph。
|
||||
|
||||
Args:
|
||||
layout_tables: layout.tables 列表。
|
||||
page_no: 当前页号。
|
||||
region_relative: 补充表区相对 bbox。
|
||||
page_size: 当前页宽高。
|
||||
reference_page_frame: 可选参考页框;缺省用 page_size。
|
||||
coordinate_transform: 可选坐标变换。
|
||||
|
||||
Returns:
|
||||
(table_id, 绝对 bbox) 或 (None, None)。
|
||||
"""
|
||||
projected = apply_coordinate_transform_to_region(
|
||||
region_relative, coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if projected is None:
|
||||
return None, None
|
||||
try:
|
||||
ref_w = float(reference_page_frame['width']) if reference_page_frame is not None else float(page_size['width'])
|
||||
ref_h = float(reference_page_frame['height']) if reference_page_frame is not None else float(page_size['height'])
|
||||
region_bbox = {
|
||||
'x0': float(projected['x0']) * ref_w,
|
||||
'y0': float(projected['y0']) * ref_h,
|
||||
'x1': float(projected['x1']) * ref_w,
|
||||
'y1': float(projected['y1']) * ref_h,
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return None, None
|
||||
best_id: str | None = None
|
||||
best_bbox: dict[str, float] | None = None
|
||||
best_overlap = 0.0
|
||||
for item in layout_tables:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
if int(item.get('page_no') or 1) != int(page_no):
|
||||
continue
|
||||
bbox = item.get('bbox')
|
||||
if not isinstance(bbox, dict):
|
||||
continue
|
||||
try:
|
||||
x0, y0, x1, y1 = float(bbox['x0']), float(bbox['y0']), float(bbox['x1']), float(bbox['y1'])
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if not (x0 < region_bbox['x1'] and x1 > region_bbox['x0'] and y0 < region_bbox['y1'] and y1 > region_bbox['y0']):
|
||||
continue
|
||||
overlap_h = max(0.0, min(x1, region_bbox['x1']) - max(x0, region_bbox['x0']))
|
||||
overlap_v = max(0.0, min(y1, region_bbox['y1']) - max(y0, region_bbox['y0']))
|
||||
overlap_area = overlap_h * overlap_v
|
||||
if overlap_area <= best_overlap:
|
||||
continue
|
||||
best_overlap = overlap_area
|
||||
best_id = str(item.get('table_id') or '') or None
|
||||
best_bbox = {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1}
|
||||
return best_id, best_bbox
|
||||
|
||||
|
||||
def _reconstruct_line_field_supplement_rows(
|
||||
*,
|
||||
raw_profile: dict[str, Any],
|
||||
layout: dict[str, Any],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
) -> tuple[list[dict[str, Any]], str | None]:
|
||||
"""
|
||||
从 Profile 的 line_field_supplement 表区按页坐标重建补充行(如 COO)。
|
||||
|
||||
核心逻辑:不把补充表当作业务表命中源;在补充区相对框内读 page_glyphs。
|
||||
若同页存在与标注区重叠的 MinerU 物理表,则用其 bbox 纵向扩展字符范围
|
||||
(样本单行 / 盲测多行时仍能读到整张 COO)。再以 with_strategy 取最佳努力行供 LN 合并。
|
||||
|
||||
Returns:
|
||||
(workflow 形态行列表, line_start_field_code 或 None)
|
||||
"""
|
||||
try:
|
||||
profile = _frozen_coordinate_profile(raw_profile)
|
||||
except (TypeError, ValueError, ValidationError):
|
||||
return [], None
|
||||
supplement_regions = [
|
||||
region for region in profile.table_regions
|
||||
if str(getattr(region, 'region_role', None) or '') == 'line_field_supplement'
|
||||
and region.line_layouts
|
||||
]
|
||||
if not supplement_regions:
|
||||
return [], None
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
|
||||
layout_tables = layout.get('tables') if isinstance(layout.get('tables'), list) else []
|
||||
rows: list[dict[str, Any]] = []
|
||||
line_start = None
|
||||
for region in supplement_regions:
|
||||
line_start = region.line_start_field_code or 'customer_po_line_no'
|
||||
runtime_ids = set(select_runtime_region_ids(
|
||||
table_regions=[_coordinate_object_mapping(item) for item in profile.table_regions],
|
||||
page_no=int(region.page_no or 1) if region.page_scope == 'exact_page' else 1,
|
||||
))
|
||||
# exact_page 补充区按其页;all_pages/first_page 扫有 glyph 的页。
|
||||
if region.page_scope == 'exact_page':
|
||||
candidate_pages = [int(region.page_no or 1)]
|
||||
else:
|
||||
candidate_pages = sorted(
|
||||
int(page_no) for page_no in page_glyphs
|
||||
if str(page_no).isdigit() and isinstance(page_glyphs.get(str(page_no)), list)
|
||||
)
|
||||
if region.page_scope == 'first_page':
|
||||
candidate_pages = [page for page in candidate_pages if page == 1] or [1]
|
||||
for page_no in candidate_pages:
|
||||
if region.page_scope == 'exact_page' and region.region_id not in runtime_ids and str(page_no) not in {str(region.page_no)}:
|
||||
continue
|
||||
page_size = pages.get(str(page_no))
|
||||
characters = page_glyphs.get(str(page_no))
|
||||
if not isinstance(page_size, dict) or not isinstance(characters, list) or not characters:
|
||||
continue
|
||||
try:
|
||||
page_bbox = {
|
||||
'x0': 0, 'y0': 0,
|
||||
'x1': float(page_size['width']), 'y1': float(page_size['height']),
|
||||
}
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
reference_page_frames = getattr(profile, 'reference_page_frames', {})
|
||||
reference_page_frame = (
|
||||
reference_page_frames.get(page_no)
|
||||
if isinstance(reference_page_frames, dict) else None
|
||||
)
|
||||
reconstruction_page_bbox = (
|
||||
{
|
||||
'x0': 0, 'y0': 0,
|
||||
'x1': reference_page_frame.width, 'y1': reference_page_frame.height,
|
||||
}
|
||||
if reference_page_frame is not None else page_bbox
|
||||
)
|
||||
relative_region = _coordinate_region_mapping(region.region)
|
||||
if relative_region is None:
|
||||
continue
|
||||
ref_frame_mapping = (
|
||||
_coordinate_object_mapping(reference_page_frame)
|
||||
if reference_page_frame is not None else None
|
||||
)
|
||||
# [STEP 1] 样本单行标注的相对框常盖不住盲测多行;重叠物理表纵向扩 glyph。
|
||||
overlap_table_id, overlap_table_bbox = _pick_overlapping_layout_table(
|
||||
layout_tables=layout_tables,
|
||||
page_no=page_no,
|
||||
region_relative=_coordinate_object_mapping(region.region),
|
||||
page_size=page_size,
|
||||
reference_page_frame=ref_frame_mapping,
|
||||
coordinate_transform=coordinate_transform,
|
||||
)
|
||||
filtered, _ = coordinate_profile_character_candidates(
|
||||
table_region=_coordinate_object_mapping(region.region),
|
||||
page_size=page_size,
|
||||
reference_page_frame=ref_frame_mapping,
|
||||
page_characters=characters,
|
||||
table_characters=None,
|
||||
raw_table_bbox=overlap_table_bbox,
|
||||
table_id=overlap_table_id,
|
||||
page_no=page_no,
|
||||
coordinate_transform=coordinate_transform,
|
||||
allow_table_fallback=False,
|
||||
)
|
||||
if not isinstance(filtered, list) or not filtered:
|
||||
continue
|
||||
chosen_rows, _strategy = reconstruct_coordinate_profile_rows_with_strategy(
|
||||
characters=[item for item in filtered if isinstance(item, dict)],
|
||||
table_bbox=reconstruction_page_bbox,
|
||||
line_layouts=[_coordinate_object_mapping(item) for item in region.line_layouts],
|
||||
table_region=relative_region,
|
||||
termination_rules=[_coordinate_object_mapping(item) for item in region.termination_rules],
|
||||
exclusion_regions=reconstruction_exclusion_regions(_coordinate_object_mapping(region)),
|
||||
line_start_field_code=region.line_start_field_code,
|
||||
schema_field_metadata=list(schema_fields.values()),
|
||||
coordinate_transform=coordinate_transform,
|
||||
page_no=page_no,
|
||||
)
|
||||
for reconstructed in chosen_rows:
|
||||
values = [
|
||||
{'field_code': code, 'value': str(raw or '')}
|
||||
for code, raw in reconstructed.fields.items()
|
||||
]
|
||||
rows.append({
|
||||
'fields': values,
|
||||
'issues': list(reconstructed.issues),
|
||||
'page_no': page_no,
|
||||
})
|
||||
return rows, line_start
|
||||
|
||||
|
||||
def _apply_line_field_supplement(
|
||||
*,
|
||||
raw_profile: dict[str, Any],
|
||||
layout: dict[str, Any],
|
||||
parsed_rows: list[dict[str, Any]],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
coordinate_transform: dict[str, Any] | None = None,
|
||||
) -> tuple[list[dict[str, Any]], list[str]]:
|
||||
"""主表明细重建后,按 LN 合并 line_field_supplement 料号。"""
|
||||
supplement_rows, line_start = _reconstruct_line_field_supplement_rows(
|
||||
raw_profile=raw_profile,
|
||||
layout=layout,
|
||||
schema_fields=schema_fields,
|
||||
coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if not supplement_rows:
|
||||
return parsed_rows, []
|
||||
merged, reasons = merge_line_field_supplement(
|
||||
parsed_rows,
|
||||
supplement_rows,
|
||||
line_start_field_code=line_start or 'customer_po_line_no',
|
||||
)
|
||||
for row in merged:
|
||||
issue_list = row.get('issues') if isinstance(row.get('issues'), list) else []
|
||||
if any(
|
||||
code in {'line_field_supplement_conflict', 'line_field_supplement_ln_ambiguous'}
|
||||
for code in issue_list
|
||||
):
|
||||
row['status'] = 'needs_review'
|
||||
return merged, reasons
|
||||
|
||||
|
||||
def _selected_coordinate_transform(
|
||||
*, profile_match: dict[str, Any], raw_profile: dict[str, Any],
|
||||
) -> dict[str, Any] | None:
|
||||
@@ -621,10 +861,11 @@ def _physical_table_targets_profile_region(
|
||||
):
|
||||
return False
|
||||
return True
|
||||
# [STEP 2] 仅含 line_layouts 的明细区才是重建目标;纯表头壳直接跳过。
|
||||
# [STEP 2] 仅含 line_layouts 的业务明细区才是重建目标;纯表头壳与补充表直接跳过。
|
||||
active_regions = [
|
||||
region for region in page_regions
|
||||
if region.get('line_layouts')
|
||||
and str(region.get('region_role') or 'business_lines') != 'line_field_supplement'
|
||||
]
|
||||
if not active_regions:
|
||||
return False
|
||||
@@ -1043,6 +1284,18 @@ def _profile_table_candidates(
|
||||
issues.append('order_profile_multiple_matches')
|
||||
continue
|
||||
raw_profile, parsed = matches[0]
|
||||
coordinate_transform = _selected_coordinate_transform(
|
||||
profile_match=profile_match, raw_profile=raw_profile,
|
||||
)
|
||||
parsed, supplement_reasons = _apply_line_field_supplement(
|
||||
raw_profile=raw_profile,
|
||||
layout=layout,
|
||||
parsed_rows=parsed,
|
||||
schema_fields=schema_fields,
|
||||
coordinate_transform=coordinate_transform,
|
||||
)
|
||||
if any(code.endswith('_conflict') or code.endswith('_ambiguous') for code in supplement_reasons):
|
||||
issues.extend(supplement_reasons)
|
||||
reservation_region = _reservation_region_candidates(raw_profile=raw_profile, layout=layout)
|
||||
result_tables.append({
|
||||
'profile_id': raw_profile.get('profile_id') or raw_profile.get('id'),
|
||||
@@ -1053,6 +1306,7 @@ def _profile_table_candidates(
|
||||
'page_no': int(raw_table.get('page_no') or 1),
|
||||
'auto_create_approved': bool(raw_profile.get('auto_create_approved')),
|
||||
'rows': parsed,
|
||||
'line_field_supplement_reasons': list(supplement_reasons),
|
||||
'reservation_region_candidates': reservation_region['candidates'],
|
||||
'reservation_region_reason': reservation_region['reason'],
|
||||
'runtime_parse_strategy': {
|
||||
@@ -1876,19 +2130,10 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfile:
|
||||
|
||||
def _reservation_region_candidates(*, raw_profile: dict[str, Any], layout: dict[str, Any]) -> dict[str, Any]:
|
||||
"""仅对已标注专区的模板,跨页读取 Vendor Comments 到首次 Terms 标题间的候选。"""
|
||||
from app.services.shipping_notice.reservation_region import reservation_region_candidates_from_layout
|
||||
|
||||
definition = raw_profile.get('definition') if isinstance(raw_profile.get('definition'), dict) else {}
|
||||
configured = definition.get('reservation_id_region')
|
||||
if not isinstance(configured, dict):
|
||||
return {'candidates': [], 'reason': None}
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
pages = [
|
||||
(int(page_no), glyphs)
|
||||
for page_no, glyphs in page_glyphs.items()
|
||||
if str(page_no).isdigit() and isinstance(glyphs, list)
|
||||
]
|
||||
candidates, reason = extract_reservation_from_vendor_comments_pages(pages)
|
||||
return {'candidates': candidates, 'reason': reason}
|
||||
return reservation_region_candidates_from_layout(definition=definition, layout=layout)
|
||||
|
||||
|
||||
def _build_approved_profile_order_result(
|
||||
@@ -1935,7 +2180,13 @@ def _build_approved_profile_order_result(
|
||||
# Profile parser 已判定 deleted/invalid 行不可进入订单;禁止把部分解析结果当作完整订单。
|
||||
if not isinstance(row, dict) or row.get('status') == 'deleted':
|
||||
continue
|
||||
if row.get('status') != 'parsed' or row.get('issues'):
|
||||
# [STEP] 忽略成功补料号等非阻塞审计码;仅真实缺陷才触发 row_needs_review。
|
||||
raw_issues = row.get('issues') if isinstance(row.get('issues'), list) else []
|
||||
blocking_issues = [
|
||||
code for code in raw_issues
|
||||
if str(code or '').strip() and str(code) not in NON_BLOCKING_ROW_ISSUE_CODES
|
||||
]
|
||||
if row.get('status') != 'parsed' or blocking_issues:
|
||||
if not allow_manual_review:
|
||||
return None, 'row_needs_review'
|
||||
has_review_rows = True
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""把冻结 EML 正文补充事实保守合并到 PDF 确定性订单。
|
||||
|
||||
依赖:Run 冻结 Schema、正文补充表契约和 PO 标准化。
|
||||
逻辑:优先 PO+MPN;仅唯一 Reservation 的 PO 可降级广播,歧义只写复核原因。
|
||||
依赖:Run 冻结 Schema、正文补充表契约、PO 标准化、Reservation ID 校验。
|
||||
逻辑:优先 PO+MPN;其次同 PO+合法 reservation_id 对齐;仅唯一签名的 PO 可降级广播;
|
||||
歧义只写复核原因。reservation 对齐与「PO+料号灌预约号」同趟单次合并,不互相重入。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,6 +12,7 @@ from typing import Any
|
||||
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
|
||||
from app.services.shipping_notice.po_number import normalize_atomic_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
def _values(fields: Any, code: str, codes: dict[str, str]) -> set[str]:
|
||||
@@ -51,6 +53,27 @@ def _schema_field_values(row: dict[str, Any], field_codes: set[str]) -> set[str]
|
||||
}
|
||||
|
||||
|
||||
def _validated_reservation_set(values: set[str]) -> set[str]:
|
||||
"""将原始预约号集合收成合法 5/10 位数字键;非法值不参与对齐。"""
|
||||
return {
|
||||
reservation
|
||||
for raw in values
|
||||
if (reservation := validated_reservation_id(raw))
|
||||
}
|
||||
|
||||
|
||||
def _line_reservation_values(line: dict[str, Any], ids: dict[str, str]) -> set[str]:
|
||||
"""读取 PDF 行上已抽取的合法 reservation_id 集合。"""
|
||||
return _validated_reservation_set(
|
||||
_values(line.get('fields'), 'reservation_id', {v: k for k, v in ids.items()}),
|
||||
)
|
||||
|
||||
|
||||
def _row_reservation_value(row: dict[str, Any]) -> str:
|
||||
"""读取邮件补充行的合法 reservation_id;非法或空返回空串。"""
|
||||
return validated_reservation_id(row.get('reservation_id'))
|
||||
|
||||
|
||||
def _canonical_field_value(value: Any, config: dict[str, Any]) -> Any:
|
||||
"""返回冻结 Schema 下用于跨来源比较的字段规范值,保留调用方持有的原始证据值。
|
||||
|
||||
@@ -250,7 +273,12 @@ def _supplement_multi_value_conflict(
|
||||
|
||||
|
||||
def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_intake: dict[int, dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。"""
|
||||
"""
|
||||
按冻结 Schema 逐字段合并正文事实,并对歧义订单附加复核冲突。
|
||||
|
||||
核心逻辑:同趟单次合并,优先级为 po_mpn → po_reservation → po_fallback → mpn_fallback;
|
||||
不因写入 reservation 再重入。po_reservation 按行对齐合法预约号,用于灌入库存源线索等。
|
||||
"""
|
||||
configs = {
|
||||
str(item.get('field_code') or ''): item
|
||||
for item in schema_definition.get('fields') or []
|
||||
@@ -280,6 +308,19 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
exact = [row for row in candidates if _schema_field_values(row, part_codes) & order_part_values]
|
||||
selected = exact
|
||||
relation = 'po_mpn'
|
||||
# [STEP] 料号对不上时,用 PDF 已有合法预约号与邮件行对齐(allocation 表常见 APN≠MPN)。
|
||||
if not selected and candidates:
|
||||
order_reservation_values: set[str] = set()
|
||||
for line in order.get('lines') or []:
|
||||
if isinstance(line, dict):
|
||||
order_reservation_values.update(_line_reservation_values(line, ids))
|
||||
reservation_exact = [
|
||||
row for row in candidates
|
||||
if (reservation := _row_reservation_value(row)) and reservation in order_reservation_values
|
||||
]
|
||||
if reservation_exact:
|
||||
selected = reservation_exact
|
||||
relation = 'po_reservation'
|
||||
if not selected and candidates:
|
||||
row_signatures = {tuple(str(row.get(code) or '').strip().upper() for code in configs if code not in {'customer_po_number', 'po_number'}) for row in candidates}
|
||||
if len(row_signatures) == 1:
|
||||
@@ -307,12 +348,19 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
continue
|
||||
for source_row in selected:
|
||||
row_part_values = _schema_field_values(source_row, part_codes)
|
||||
row_reservation = _row_reservation_value(source_row)
|
||||
indexed_target_lines = [
|
||||
(index, line)
|
||||
for index, line in enumerate(order.get('lines') or [])
|
||||
if isinstance(line, dict)
|
||||
]
|
||||
if relation != 'po_fallback':
|
||||
if relation == 'po_reservation':
|
||||
# 预约号精确命中只写入同 reservation 的 PDF 行,禁止跨行广播多站点线索。
|
||||
indexed_target_lines = [
|
||||
(index, line) for index, line in indexed_target_lines
|
||||
if row_reservation and row_reservation in _line_reservation_values(line, ids)
|
||||
]
|
||||
elif relation != 'po_fallback':
|
||||
# 精确料号命中(含 PN/AMPN × 内部/客户料号四种组合)只写入交集行。
|
||||
indexed_target_lines = [
|
||||
(index, line) for index, line in indexed_target_lines
|
||||
@@ -324,7 +372,6 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
if not indexed_target_lines:
|
||||
order.setdefault('conflicts', []).append({'severity': 'blocking', 'reason': 'supplement_relation_ambiguous'})
|
||||
continue
|
||||
target_lines = [line for _, line in indexed_target_lines]
|
||||
for target_code, config in configs.items():
|
||||
target_groups = (
|
||||
[(-1, order.get('header_fields'))]
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"""
|
||||
Reservation ID 专用证据区域解析器。
|
||||
|
||||
用途:从管理员圈选的 Vendor Comments 区域提取 Reservation ID 和可选行号。
|
||||
依赖:reservation_id 的统一格式校验。
|
||||
逻辑:只消费区域文字,不依赖客户名称、固定坐标或旧的三来源映射;无行号仅标记为未归属,最终由 Schema scope 决定表头写入或明细复核。
|
||||
用途:从已启用的 Vendor Comments→Terms 锚点窗提取 Reservation ID 与可选行号,
|
||||
并投影到验证证据 / 订单归属契约。
|
||||
依赖:reservation_id 格式校验、coordinate_region_text 视觉行序。
|
||||
逻辑:reservation_id_region 仅作启用标记;画布预览、盲测、正式解析共用本模块的
|
||||
锚点扫描与 apply/project,不再按保存矩形截取正式值;行号含 line# / L# / LN#。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,10 +19,21 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
|
||||
_ID_RE = re.compile(r"(?<!\d)(\d{5}|\d{10})(?!\d)")
|
||||
_LINE_RE = re.compile(r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b|\bfor\s+line\s*#?\s*(\d+)\b", re.I)
|
||||
# 行号写法:Line 1 / line#1 / for line#1 / Hyve 缩写 L#1、LN#1。
|
||||
_LINE_RE = re.compile(
|
||||
r"(?:"
|
||||
r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b"
|
||||
r"|\bfor\s+line\s*#?\s*(\d+)\b"
|
||||
r"|\bl(?:n)?\s*#\s*(\d+)\b"
|
||||
r")",
|
||||
re.I,
|
||||
)
|
||||
_RESERVATION_LABEL_RE = re.compile(r"\breservation\b\s*(?:id)?\s*(?:#|:|-)?", re.I)
|
||||
_VENDOR_COMMENTS_HEADING_RE = re.compile(r'^\s*vendor\s+comments?\s*:?\s*$', re.I)
|
||||
_TERMS_AND_CONDITIONS_HEADING_RE = re.compile(r'^\s*terms?\s+and\s+conditions?\s*:?\s*$', re.I)
|
||||
_VENDOR_COMMENTS_HEADING_RE = re.compile(r'^\s*vendor\s+comments?\b', re.I)
|
||||
_TERMS_AND_CONDITIONS_HEADING_RE = re.compile(
|
||||
r'^\s*(?:\d+[\.\)]\s*)?terms?\s*(?:&|and)\s*conditions?\b',
|
||||
re.I,
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -43,7 +56,11 @@ class ReservationRegionApplication:
|
||||
|
||||
|
||||
def extract_reservation_from_region(text: str) -> list[ReservationRegionCandidate]:
|
||||
"""从区域原文提取候选;有行号归明细,无行号归订单头。"""
|
||||
"""从区域原文提取候选;有行号归明细,无行号归订单头。
|
||||
|
||||
核心逻辑:同行须含 Reservation 标签;行号支持 ``line#1`` / ``for line#1`` /
|
||||
``L#1`` / ``LN#1`` 等写法,命中后 scope=line,禁止误写入订单头。
|
||||
"""
|
||||
candidates: list[ReservationRegionCandidate] = []
|
||||
for raw_line in (str(text or '').splitlines() or [str(text or '')]):
|
||||
line = raw_line.strip()
|
||||
@@ -58,7 +75,8 @@ def extract_reservation_from_region(text: str) -> list[ReservationRegionCandidat
|
||||
line_match = _LINE_RE.search(line)
|
||||
line_no = None
|
||||
if line_match:
|
||||
line_no = int(line_match.group(1) or line_match.group(2))
|
||||
captured = next((group for group in line_match.groups() if group is not None), None)
|
||||
line_no = int(captured) if captured is not None else None
|
||||
scope = 'line' if line_no is not None else 'header'
|
||||
status = 'mapped' if line_no is not None else 'header'
|
||||
for value in dict.fromkeys(ids):
|
||||
@@ -86,22 +104,147 @@ def extract_reservation_from_vendor_comments_pages(
|
||||
"""从跨页 Vendor Comments 区块提取 Reservation;仅首个 Terms 标题前的文字有效。
|
||||
|
||||
核心逻辑:Reservation 专区已启用时,页面坐标只是提供稳定阅读顺序,不能作为固定
|
||||
页码或矩形取值依据。缺少起止锚点时返回稳定原因,由调用方转人工复核。
|
||||
页码或矩形取值依据。起止标题按行首短语匹配(允许「Terms and Conditions of …」等
|
||||
加长标题);缺少起始锚点时不扫描;缺少结束锚点时仍返回已累计窗内候选,但附带稳
|
||||
定原因,由调用方标 Review,禁止当成可自动建单封闭证据。
|
||||
"""
|
||||
started = False
|
||||
window_lines: list[str] = []
|
||||
for _page_no, glyphs in sorted(pages, key=lambda item: item[0]):
|
||||
for line in visual_text_lines(glyphs):
|
||||
if not started:
|
||||
if _VENDOR_COMMENTS_HEADING_RE.fullmatch(line):
|
||||
if _VENDOR_COMMENTS_HEADING_RE.match(line):
|
||||
started = True
|
||||
continue
|
||||
if _TERMS_AND_CONDITIONS_HEADING_RE.fullmatch(line):
|
||||
if _TERMS_AND_CONDITIONS_HEADING_RE.match(line):
|
||||
return extract_reservation_from_region_text('\n'.join(window_lines)), None
|
||||
window_lines.append(line)
|
||||
if not started:
|
||||
return [], 'vendor_comments_anchor_missing'
|
||||
return [], 'terms_and_conditions_anchor_missing'
|
||||
# 结束锚点缺失:保留窗内候选供验证/盲测展示与人工复核,不能假装封闭成功。
|
||||
return extract_reservation_from_region_text('\n'.join(window_lines)), 'terms_and_conditions_anchor_missing'
|
||||
|
||||
|
||||
def reservation_region_candidates_from_layout(
|
||||
*,
|
||||
definition: dict[str, Any] | None,
|
||||
layout: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""仅当模板标注了 reservation_id_region 时,按 Vendor Comments→Terms 提取候选。
|
||||
|
||||
核心逻辑:page_no/region 只表示专区已启用,正式取值必须与画布预览、盲测、
|
||||
正式解析共用同一锚点窗,禁止再按保存矩形截取。
|
||||
|
||||
Args:
|
||||
definition: Profile definition;无 reservation_id_region 时不扫描。
|
||||
layout: 含 coordinate_evidence.page_glyphs 的版面快照。
|
||||
|
||||
Returns:
|
||||
``{'candidates': [...], 'reason': str | None}``;reason 非空表示锚点异常。
|
||||
"""
|
||||
raw = definition if isinstance(definition, dict) else {}
|
||||
if not isinstance(raw.get('reservation_id_region'), dict):
|
||||
return {'candidates': [], 'reason': None}
|
||||
evidence = layout.get('coordinate_evidence') if isinstance(layout, dict) else None
|
||||
evidence = evidence if isinstance(evidence, dict) else {}
|
||||
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
|
||||
pages = [
|
||||
(int(page_no), glyphs)
|
||||
for page_no, glyphs in page_glyphs.items()
|
||||
if str(page_no).isdigit() and isinstance(glyphs, list)
|
||||
]
|
||||
candidates, reason = extract_reservation_from_vendor_comments_pages(pages)
|
||||
return {'candidates': candidates, 'reason': reason}
|
||||
|
||||
|
||||
def project_reservation_onto_validation_evidence(
|
||||
evidence: dict[str, Any],
|
||||
*,
|
||||
candidates: list[dict[str, object]],
|
||||
reason: str | None,
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""将专区候选投影到验证页共用的 header_fields / lines 证据 DTO。
|
||||
|
||||
核心逻辑:复用 apply_reservation_region_candidates 归属契约;锚点缺失或冲突时
|
||||
写入 reservation_region_*,不臆造字段值。
|
||||
|
||||
Args:
|
||||
evidence: 现有 validation_evidence。
|
||||
candidates: 锚点窗候选。
|
||||
reason: 锚点扫描失败原因;有值时强制 needs_review。
|
||||
schema_fields: field_id → Schema 字段(须含 enabled reservation_id)。
|
||||
|
||||
Returns:
|
||||
新的 evidence 字典;未启用专区字段时仅透传或附加 review 元数据。
|
||||
"""
|
||||
projected = {
|
||||
'header_fields': [
|
||||
dict(item) for item in (evidence.get('header_fields') or []) if isinstance(item, dict)
|
||||
],
|
||||
'lines': [
|
||||
{
|
||||
'row_index': int(line.get('row_index') or index),
|
||||
'fields': [
|
||||
dict(field) for field in (line.get('fields') or []) if isinstance(field, dict)
|
||||
],
|
||||
}
|
||||
for index, line in enumerate(evidence.get('lines') or [])
|
||||
if isinstance(line, dict)
|
||||
],
|
||||
'cross_checks': dict(evidence.get('cross_checks') or {}),
|
||||
}
|
||||
reservation_scope = {
|
||||
str(item.get('scope') or ''): item
|
||||
for item in schema_fields.values()
|
||||
if isinstance(item, dict) and str(item.get('field_code') or '') == 'reservation_id'
|
||||
}
|
||||
if reason:
|
||||
projected['reservation_region_status'] = 'needs_review'
|
||||
projected['reservation_region_review_reasons'] = [str(reason)]
|
||||
if not candidates and not reason:
|
||||
return projected
|
||||
|
||||
applied = apply_reservation_region_candidates(
|
||||
candidates=candidates,
|
||||
header_field_id=str((reservation_scope.get('header') or {}).get('field_id') or '') or None,
|
||||
line_field_id=str((reservation_scope.get('line') or {}).get('field_id') or '') or None,
|
||||
line_count=len(projected['lines']),
|
||||
)
|
||||
header_target = reservation_scope.get('header')
|
||||
if applied.header_value and header_target:
|
||||
projected['header_fields'] = [
|
||||
item for item in projected['header_fields']
|
||||
if str(item.get('field_code') or '') != 'reservation_id'
|
||||
] + [{
|
||||
'field_id': str(header_target.get('field_id') or ''),
|
||||
'field_code': 'reservation_id',
|
||||
'raw_value': applied.header_value,
|
||||
'normalized_value': applied.header_value,
|
||||
'status': 'passed',
|
||||
'issues': [],
|
||||
}]
|
||||
line_target = reservation_scope.get('line')
|
||||
if line_target:
|
||||
for line_no, value in applied.line_values.items():
|
||||
if line_no < 1 or line_no > len(projected['lines']):
|
||||
continue
|
||||
line = projected['lines'][line_no - 1]
|
||||
line['fields'] = [
|
||||
item for item in line['fields']
|
||||
if str(item.get('field_code') or '') != 'reservation_id'
|
||||
] + [{
|
||||
'field_id': str(line_target.get('field_id') or ''),
|
||||
'field_code': 'reservation_id',
|
||||
'raw_value': value,
|
||||
'normalized_value': value,
|
||||
'status': 'passed',
|
||||
'issues': [],
|
||||
}]
|
||||
if applied.needs_review:
|
||||
projected['reservation_region_status'] = 'needs_review'
|
||||
projected['reservation_region_review_reasons'] = list(applied.review_reasons)
|
||||
return projected
|
||||
|
||||
|
||||
def apply_reservation_region_candidates(
|
||||
|
||||
Reference in new issue
Block a user