feat(shipping-notice): 完善订单解析、模板管理与库存 RPA 流程
- 优化订单文档解析、补充合并与坐标重建 - 完善订单模板校验、发布及前端管理界面 - 改进库存 RPA 下载回退与工作流处理 - 补充后端、前端及 RPA 自动化测试 - 更新 Shipping Notice 技术文档与四语言文案
This commit is contained in:
1 parent
c4a27324c8
commit
8f2f568f92
46 files changed
+1745
-265
No files matched your search
@@ -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',
|
||||
|
||||
+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:
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
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;
|
||||
盲测执行附加 visual/split/evidence 指标,XFA 任一指标 < 1.0 即失败;样本通过并批准后才放行自动建单。
|
||||
"""
|
||||
|
||||
@@ -41,7 +42,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 +51,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 +378,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()):
|
||||
@@ -450,8 +461,8 @@ 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)
|
||||
order_fields = [
|
||||
{
|
||||
'field_code': item.field_code, 'value': _json_value(item.value), 'status': item.status,
|
||||
@@ -465,54 +476,52 @@ 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),
|
||||
}
|
||||
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)),
|
||||
}
|
||||
return {'document_id': document.id, 'table_id': str(table_id), 'rows': rows, 'order_fields': order_fields}
|
||||
raise ValidationError('Profile samples are unsupported', code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID')
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
+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
|
||||
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
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 专区锚点投影。
|
||||
逻辑:每次运行先冻结草稿和样本证据身份,再只保存安全摘要;坐标 current-sample 在表格/
|
||||
表头试读后投影 Vendor Comments Reservation;XFA current-sample 另附脱敏字段级
|
||||
Header/Line;签名成功后更新 Profile 轻量引用;查询时根据当前 checksum 派生 stale。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -344,6 +345,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 +394,32 @@ 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,
|
||||
)
|
||||
summary['validation_evidence'] = evidence
|
||||
return status, summary, snapshot
|
||||
|
||||
|
||||
|
||||
@@ -1201,6 +1201,51 @@ 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',
|
||||
})
|
||||
|
||||
|
||||
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 +1356,72 @@ def schedule_order_extraction_layouts(
|
||||
|
||||
|
||||
def resume_runs_waiting_for_layout(*, document_id: int) -> int:
|
||||
"""布局任务完成后唤醒所有已具备完整布局的 Run,确保订单任务不会早于版面快照执行。"""
|
||||
"""
|
||||
单份附件布局完成后唤醒仍等待版式的 Run。
|
||||
|
||||
核心逻辑:不再要求 Run 内全部 PDF 版式就绪;只要存在可抽取的 ready Document,
|
||||
即入队(或复用活跃)shipping_order_extraction。无 ready 活且无 pending、仅有失败版式、
|
||||
且尚未抽出任何 Unit 时,整 Run 失败收口。
|
||||
"""
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
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(
|
||||
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
|
||||
# 仍有兄弟 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(
|
||||
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'
|
||||
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 +1432,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 +1445,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 +2357,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},
|
||||
|
||||
@@ -58,7 +58,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,
|
||||
)
|
||||
|
||||
|
||||
@@ -1876,19 +1875,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(
|
||||
|
||||
@@ -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,不再按保存矩形截取正式值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -19,8 +21,11 @@ from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
_ID_RE = re.compile(r"(?<!\d)(\d{5}|\d{10})(?!\d)")
|
||||
_LINE_RE = re.compile(r"\b(?:reservation\s+)?line\s*#?\s*(\d+)\b|\bfor\s+line\s*#?\s*(\d+)\b", re.I)
|
||||
_RESERVATION_LABEL_RE = re.compile(r"\breservation\b\s*(?:id)?\s*(?:#|:|-)?", re.I)
|
||||
_VENDOR_COMMENTS_HEADING_RE = re.compile(r'^\s*vendor\s+comments?\s*:?\s*$', re.I)
|
||||
_TERMS_AND_CONDITIONS_HEADING_RE = re.compile(r'^\s*terms?\s+and\s+conditions?\s*:?\s*$', re.I)
|
||||
_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)
|
||||
@@ -86,22 +91,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(
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""验证 EML 正文补充表的确定性解析、关联和数量保护。
|
||||
|
||||
依赖:正文补充解析器与合并服务。
|
||||
逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威,歧义稳定进入复核。
|
||||
逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威;关联优先 PO+料号,
|
||||
其次 PO+预约号,歧义稳定进入复核。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -345,6 +346,81 @@ def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_
|
||||
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
def test_email_supplement_po_reservation_injects_hint_when_parts_do_not_match():
|
||||
"""同 PO 下 PDF 已有预约号、邮件仅 APN 不对料号时,按 reservation 对齐灌入库存源线索。
|
||||
|
||||
回归:AWS allocation 表 Component APN 对不上 Wistron MPN 时,不得因缺 po_mpn
|
||||
把多行 VMI-* 线索整单丢掉。
|
||||
"""
|
||||
order = {
|
||||
'_hxops_intake_id': 1,
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': '16776707'}]}],
|
||||
'lines': [
|
||||
{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000002'}]},
|
||||
{'field_id': 'reservation', 'observations': [{'value': '2000484577'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 30}]},
|
||||
]},
|
||||
{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000003'}]},
|
||||
{'field_id': 'reservation', 'observations': [{'value': '2000484578'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 24}]},
|
||||
]},
|
||||
],
|
||||
'conflicts': [],
|
||||
}
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [
|
||||
{
|
||||
'customer_po_number': '16776707',
|
||||
'part_number': '504-006055-001',
|
||||
'reservation_id': '2000484577',
|
||||
'inventory_source_hint': 'VMI-RTM01',
|
||||
'evidence': {'inventory_source_hint': {'raw_value': 'VMI-RTM01'}},
|
||||
},
|
||||
{
|
||||
'customer_po_number': '16776707',
|
||||
'part_number': '504-006056-001',
|
||||
'reservation_id': '2000484578',
|
||||
'inventory_source_hint': 'VMI-DUB',
|
||||
'evidence': {'inventory_source_hint': {'raw_value': 'VMI-DUB'}},
|
||||
},
|
||||
],
|
||||
}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
# 关键断言:关联码为 po_reservation;两行分别灌入对应线索,数量不被覆盖。
|
||||
assert merged['_hxops_email_supplement_relation'] == 'po_reservation'
|
||||
assert _value(merged['lines'][0]['fields'], 'source') == 'VMI-RTM01'
|
||||
assert _value(merged['lines'][1]['fields'], 'source') == 'VMI-DUB'
|
||||
assert _value(merged['lines'][0]['fields'], 'qty') == 30
|
||||
assert _value(merged['lines'][1]['fields'], 'qty') == 24
|
||||
assert not any(item.get('reason') == 'supplement_relation_ambiguous' for item in merged['conflicts'])
|
||||
|
||||
|
||||
def test_email_supplement_po_mpn_still_preferred_over_po_reservation():
|
||||
"""料号能精确命中时仍走 po_mpn,不得因两边都有预约号改走 reservation 档。"""
|
||||
order = _order()
|
||||
order['lines'][0]['fields'].append({
|
||||
'field_id': 'reservation', 'observations': [{'value': '2000484577'}],
|
||||
})
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'customer_po_number': '4518738152',
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577',
|
||||
'inventory_source_hint': 'DSB CMH',
|
||||
'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert merged['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
assert _value(merged['lines'][0]['fields'], 'source') == 'DSB CMH'
|
||||
|
||||
|
||||
def test_email_supplement_po_fallback_writes_unique_reservation_without_part_match():
|
||||
"""唯一 PO 兜底不得在写入阶段重新要求邮件料号匹配。"""
|
||||
result = merge_email_supplements(
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
"""
|
||||
inventory RPA:Playwright Download.save_as 因浏览器关闭失败时,应按 downloads_path 目录兜底落盘。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _load_worker():
|
||||
module_path = (
|
||||
Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
)
|
||||
scripts_dir = str(module_path.parent)
|
||||
if scripts_dir not in sys.path:
|
||||
sys.path.insert(0, scripts_dir)
|
||||
# common/ 需可 import download_artifact_fallback
|
||||
common_dir = str(module_path.parent.parent / "common")
|
||||
if common_dir not in sys.path:
|
||||
sys.path.insert(0, common_dir)
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_save_fallback_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
class _ClosedBrowserDownload:
|
||||
"""模拟 Playwright Download:save_as 时浏览器已关闭。"""
|
||||
|
||||
suggested_filename = "OnHandInventory.xlsx"
|
||||
|
||||
def save_as(self, dest: str) -> None:
|
||||
raise RuntimeError("Download.save_as: Target page, context or browser has been closed")
|
||||
|
||||
|
||||
def test_save_batch_download_falls_back_when_browser_closed(monkeypatch):
|
||||
"""save_as 因浏览器关闭失败、目录已有稳定 xlsx 时,应改名落盘并返回规范路径。"""
|
||||
worker = _load_worker()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
drop_dir = Path(tmp) / "drop"
|
||||
drop_dir.mkdir()
|
||||
(drop_dir / "noise.txt").write_text("old", encoding="utf-8")
|
||||
landed = drop_dir / "chromium_download.xlsx"
|
||||
landed.write_bytes(b"PK" + b"0" * 600)
|
||||
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
|
||||
out = worker._save_batch_download(
|
||||
_ClosedBrowserDownload(),
|
||||
drop_dir,
|
||||
"BATCH-RUN-1",
|
||||
{"source_code": "DSV360_AWSSG", "warehouse_id": "AWSSG"},
|
||||
baseline_names={"noise.txt"},
|
||||
)
|
||||
|
||||
assert out.exists()
|
||||
assert out.parent == drop_dir
|
||||
assert "DSV360_AWSSG" in out.name
|
||||
assert "AWSSG" in out.name
|
||||
assert out.suffix == ".xlsx"
|
||||
assert not landed.exists()
|
||||
|
||||
|
||||
def test_save_batch_download_reraises_when_fallback_missing(monkeypatch):
|
||||
"""浏览器关闭且目录无新文件时,应继续抛出原 save_as 错误。"""
|
||||
worker = _load_worker()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
drop_dir = Path(tmp) / "drop"
|
||||
drop_dir.mkdir()
|
||||
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
monkeypatch.setattr(
|
||||
worker,
|
||||
"_wait_for_new_download_file",
|
||||
lambda **_kwargs: None,
|
||||
)
|
||||
|
||||
try:
|
||||
worker._save_batch_download(
|
||||
_ClosedBrowserDownload(),
|
||||
drop_dir,
|
||||
"BATCH-RUN-2",
|
||||
{"source_code": "DSV360_AWSSG", "warehouse_id": "AWSSG"},
|
||||
baseline_names=set(),
|
||||
fallback_timeout_seconds=0.1,
|
||||
)
|
||||
raise AssertionError("expected RuntimeError")
|
||||
except RuntimeError as exc:
|
||||
# 断言:错误信息仍指向浏览器关闭,避免被吞成模糊失败
|
||||
assert "has been closed" in str(exc).lower()
|
||||
|
||||
|
||||
def test_save_download_falls_back_when_browser_closed(monkeypatch):
|
||||
"""单票路径同样在 save_as 浏览器关闭后走目录兜底。"""
|
||||
worker = _load_worker()
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
drop_dir = Path(tmp) / "drop"
|
||||
drop_dir.mkdir()
|
||||
landed = drop_dir / "raw.xlsx"
|
||||
landed.write_bytes(b"PK" + b"0" * 600)
|
||||
monkeypatch.setattr(worker, "_validate_inventory_excel", lambda _path: None)
|
||||
|
||||
out = worker._save_download(
|
||||
_ClosedBrowserDownload(),
|
||||
drop_dir,
|
||||
"OT-1",
|
||||
"DSV360_AWSSG",
|
||||
baseline_names=set(),
|
||||
)
|
||||
|
||||
assert out.exists()
|
||||
assert "DSV360_AWSSG" in out.name
|
||||
assert not landed.exists()
|
||||
@@ -14,6 +14,7 @@ from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
ShippingOrderDocumentProfileValidationRun,
|
||||
User,
|
||||
)
|
||||
@@ -196,12 +197,19 @@ def test_report_ignores_submitted_pre_hydration_signature(app, monkeypatch):
|
||||
|
||||
|
||||
def test_report_blocks_when_overlap_failed(app, monkeypatch):
|
||||
"""关键断言:重叠验证 failed 时报告写入 overlap 阻断项与 conflict 引用。"""
|
||||
"""关键断言:当前草稿上的 overlap failed 展开真实门禁,不得误报 overlap_validation_stale。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr('app.services.shipping_notice.document_profile_quality_service.assert_profile_publishable', lambda _: None)
|
||||
schema = _schema_version(); draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-overlap-create')
|
||||
lease = _lease(draft['id']); run = _passing_run(draft); _signature_run(draft)
|
||||
failed_overlap = _overlap_run(draft, status='failed')
|
||||
failed_overlap.summary_json = {
|
||||
**dict(failed_overlap.summary_json or {}),
|
||||
'self_unique_hit_rate_training': 0.0,
|
||||
'training_sample_count': 2,
|
||||
'blind_sample_count': 0,
|
||||
}
|
||||
db.session.commit()
|
||||
monkeypatch.setattr(
|
||||
validation_service, 'run_cross_template_overlap',
|
||||
lambda *args, **kwargs: {'id': failed_overlap.id, 'status': 'failed', 'stored_status': 'failed'},
|
||||
@@ -211,10 +219,37 @@ def test_report_blocks_when_overlap_failed(app, monkeypatch):
|
||||
actor_id=None, browser_session_id='publish-check-tab', lease_token=lease['lease_token'], operation_id='pc-overlap-report',
|
||||
)
|
||||
keys = {str(item.get('key')) for item in report['blocking_items']}
|
||||
assert 'overlap_validation_stale' in keys or 'overlap_validation_required' in keys or 'self_match_not_unique' in keys
|
||||
assert 'self_match_not_unique' in keys
|
||||
assert 'overlap_validation_stale' not in keys
|
||||
assert report['overlap_validation_run_id'] == failed_overlap.id
|
||||
|
||||
|
||||
def test_blocking_from_overlap_marks_stale_only_on_checksum_drift(app):
|
||||
"""关键断言:仅 definition_checksum 漂移才标 stale;同 checksum 的 failed 展开指标。"""
|
||||
with app.app_context():
|
||||
schema = _schema_version()
|
||||
draft = profiles.save_draft(_data(schema.id), actor_id=None, operation_id='pc-stale-vs-failed')
|
||||
revision = ShippingOrderDocumentProfileDraftRevision.query.filter_by(
|
||||
profile_id=draft['id'], revision_no=draft['draft_revision']['revision_no'],
|
||||
).one()
|
||||
stale_run = _overlap_run(draft, status='passed')
|
||||
stale_run.definition_checksum = 'not-current-checksum'
|
||||
db.session.commit()
|
||||
stale_keys = {item['key'] for item in checks._blocking_from_overlap(None, stale_run, revision)}
|
||||
assert stale_keys == {'overlap_validation_stale'}
|
||||
|
||||
failed_run = _overlap_run(draft, status='failed')
|
||||
failed_run.summary_json = {
|
||||
**dict(failed_run.summary_json or {}),
|
||||
'self_unique_hit_rate_training': 0.0,
|
||||
'training_sample_count': 1,
|
||||
}
|
||||
db.session.commit()
|
||||
failed_keys = {item['key'] for item in checks._blocking_from_overlap(dict(failed_run.summary_json), failed_run, revision)}
|
||||
assert 'self_match_not_unique' in failed_keys
|
||||
assert 'overlap_validation_stale' not in failed_keys
|
||||
|
||||
|
||||
def test_report_invalidates_when_signature_cleared(app, monkeypatch):
|
||||
"""关键断言:草稿签名引用清空后既有报告查询即 invalidated。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -160,13 +160,22 @@ def test_profile_without_reservation_region_does_not_scan_vendor_comments():
|
||||
|
||||
|
||||
def test_enabled_reservation_region_requires_review_when_terms_heading_is_missing():
|
||||
"""专区缺少结束锚点时,不得把未封闭文本区的值当成可自动建单证据。"""
|
||||
"""专区缺少结束锚点时,窗内候选可展示/归属,但订单必须标 needs_review。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=RESERVATION_DEFINITION, table={'rows': [_row('PO-1', 'P-1')]},
|
||||
reservation_region_candidates=[{
|
||||
'value': '1000143920', 'scope': 'line', 'line_no': 1,
|
||||
'raw_text': 'DBS Reservation Line 1: 1000143920', 'status': 'mapped',
|
||||
}],
|
||||
reservation_region_reason='terms_and_conditions_anchor_missing',
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
|
||||
assert (orders or [])[0]['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing']
|
||||
order = (orders or [])[0]
|
||||
assert order['reservation_region_status'] == 'needs_review'
|
||||
assert order['reservation_region_review_reasons'] == ['terms_and_conditions_anchor_missing']
|
||||
assert any(
|
||||
item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == '1000143920'
|
||||
for item in order['lines'][0]['fields']
|
||||
)
|
||||
@@ -1717,3 +1717,37 @@ def test_table_region_profile_freezes_confirmed_visual_geometry_source_only():
|
||||
}).visual_evidence_source == 'acroform_widget_geometry'
|
||||
with pytest.raises(ValueError, match='visual_evidence_source'):
|
||||
TableRegionProfile.model_validate({**payload, 'visual_evidence_source': 'xfa_dataset'})
|
||||
|
||||
|
||||
def test_strategy_needs_review_still_returns_best_effort_rows_for_display(monkeypatch):
|
||||
"""策略需复核时仍返回最佳努力明细,盲测/验证才能展示,不能整表吞掉。"""
|
||||
from app.services.shipping_notice.document_layout import runtime_parse_strategy as strategy_module
|
||||
from app.services.shipping_notice.document_layout.runtime_parse_strategy import RuntimeParseStrategy
|
||||
|
||||
def _force_review(**_kwargs):
|
||||
return RuntimeParseStrategy('needs_review', (1,), None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',))
|
||||
|
||||
monkeypatch.setattr(strategy_module, 'resolve_runtime_parse_strategy', _force_review)
|
||||
rows, strategy = reconstruct_coordinate_profile_rows_with_strategy(
|
||||
characters=_glyphs(
|
||||
[('1', 10), ('PART-A', 80)],
|
||||
[('2', 10), ('PART-B', 80)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
table_region={'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
line_layouts=[{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
],
|
||||
}],
|
||||
line_start_field_code='customer_po_line_no',
|
||||
)
|
||||
|
||||
assert strategy.status == 'needs_review'
|
||||
assert [row.fields for row in rows] == [
|
||||
{'customer_po_line_no': '1', 'part_number': 'PART-A'},
|
||||
{'customer_po_line_no': '2', 'part_number': 'PART-B'},
|
||||
]
|
||||
@@ -710,6 +710,59 @@ def test_coordinate_blind_candidate_excludes_header_layouts_from_rows(app):
|
||||
assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_coordinate_blind_candidate_keeps_rows_when_strategy_needs_review(app, monkeypatch):
|
||||
"""关键断言:策略需复核时盲测预览仍展示最佳努力明细,不能整表吞掉。"""
|
||||
from app.services.shipping_notice.document_layout.runtime_parse_strategy import RuntimeParseStrategy
|
||||
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
profile.definition_json = {
|
||||
'document_match': {'required_anchors': []},
|
||||
'table_regions': [{
|
||||
'region_id': 'lines', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_id': 'line-id', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': .3, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'scope': 'line',
|
||||
'region': {'x0': .3, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
}],
|
||||
}], 'order_field_layouts': [],
|
||||
}
|
||||
glyphs = [
|
||||
{'text': char, 'bbox': {'x0': 20 + index * 4, 'y0': 40, 'x1': 23 + index * 4, 'y1': 50}}
|
||||
for index, char in enumerate('20')
|
||||
] + [
|
||||
{'text': char, 'bbox': {'x0': 80 + index * 4, 'y0': 40, 'x1': 83 + index * 4, 'y1': 50}}
|
||||
for index, char in enumerate('PART-A')
|
||||
]
|
||||
record_inline_layout_snapshot(documents[1], {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1}],
|
||||
'coordinate_evidence': {
|
||||
'tables': {'table-1': glyphs}, 'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs}, 'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
})
|
||||
db.session.commit()
|
||||
|
||||
def _force_review(**_kwargs):
|
||||
return RuntimeParseStrategy('needs_review', (1,), None, ('PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',))
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.runtime_parse_strategy.resolve_runtime_parse_strategy',
|
||||
_force_review,
|
||||
)
|
||||
candidate = quality._candidate_for_sample(
|
||||
profile=profile, document_id=documents[1].id, table_id='table-1',
|
||||
)
|
||||
assert candidate['rows'] == [{'customer_po_line_no': '20', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_profile_checksum_change_invalidates_approved_quality_credential(app):
|
||||
"""关键断言:Profile checksum 变更后,旧盲测凭证绝不能继续放行。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -2409,7 +2409,7 @@ def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch,
|
||||
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
|
||||
)
|
||||
|
||||
def _fake_link(actual_task, inv_file, *, reason, role='member', audit_payload=None):
|
||||
def _fake_link(actual_task, inv_file, *, reason, audit_payload=None):
|
||||
call_order.append(f'link:{reason}')
|
||||
assert actual_task is task
|
||||
assert inv_file is snapshot
|
||||
@@ -2424,7 +2424,7 @@ def test_stp_candidate_ready_links_snapshot_before_inventory_loaded(monkeypatch,
|
||||
return {'status': 'ok', 'message': 'linked-and-loaded'}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task',
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation',
|
||||
_fake_link,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -2495,7 +2495,7 @@ def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app):
|
||||
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task',
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation',
|
||||
lambda *_a, **_k: None,
|
||||
)
|
||||
|
||||
@@ -2516,3 +2516,85 @@ def test_stp_candidate_ready_link_failure_returns_needs_human(monkeypatch, app):
|
||||
|
||||
assert result['status'] == 'needs_human'
|
||||
assert result['data']['blocking_reason']['code'] == 'inventory_file_missing'
|
||||
|
||||
|
||||
def test_stp_candidate_ready_uses_preparation_link_when_warehouse_pending(monkeypatch, app):
|
||||
"""[断言] 动态仓未决时 preparation 软绑定仍推进,不得投影 inventory_file_missing。"""
|
||||
from app.services.shipping_notice import inventory_workflow
|
||||
|
||||
task = SimpleNamespace(
|
||||
task_no='OT-STP-SOFT-LINK',
|
||||
id=703,
|
||||
inventory_lines_json=None,
|
||||
inventory_source_status='candidates_frozen',
|
||||
active_inventory_candidate_set_id=11,
|
||||
)
|
||||
snapshot = SimpleNamespace(inventory_file_no='INV-WH-PENDING', source_code='CRANE', warehouse_id=None)
|
||||
call_order: list[str] = []
|
||||
|
||||
monkeypatch.setattr(inventory_workflow, 'resolve_task_from_payload', lambda _payload: task)
|
||||
monkeypatch.setattr(inventory_workflow, '_inventory_source_gate_response', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(inventory_workflow, 'serialize_task_for_tool', lambda _task: {})
|
||||
monkeypatch.setattr(inventory_workflow, 'tool_response', lambda **kwargs: kwargs)
|
||||
monkeypatch.setattr(inventory_workflow.db.session, 'flush', lambda: None)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_inventory_freeze.task_frozen_inventory_source_codes',
|
||||
lambda _task: ['CRANE'],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_line_inventory_match.prepare_candidate_inventory_lines',
|
||||
lambda _task: {
|
||||
'status': 'ready',
|
||||
'candidate_set_id': 11,
|
||||
'lines': [{'part_number': 'P1', '__source_code': 'CRANE', '__inventory_file_no': 'INV-WH-PENDING'}],
|
||||
'missing_source_codes': [],
|
||||
'loaded_source_codes': ['CRANE'],
|
||||
'evidence': [{
|
||||
'source_code': 'CRANE',
|
||||
'status': 'loaded',
|
||||
'inventory_file_no': 'INV-WH-PENDING',
|
||||
'line_count': 1,
|
||||
'required': True,
|
||||
}],
|
||||
'required_source_codes': ['CRANE'],
|
||||
},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.active_inventory_file_for_task',
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
ShippingInventoryFile,
|
||||
'query',
|
||||
SimpleNamespace(filter_by=lambda **_kw: SimpleNamespace(first=lambda: snapshot)),
|
||||
)
|
||||
|
||||
def _fake_prep_link(actual_task, inv_file, *, reason, audit_payload=None):
|
||||
call_order.append(f'prep:{reason}')
|
||||
assert reason == 'stp_candidate_prep'
|
||||
assert inv_file is snapshot
|
||||
return SimpleNamespace(id=99, identity_check_status='pending_matching')
|
||||
|
||||
def _fake_loaded(actual_task, lines, **kwargs):
|
||||
call_order.append('loaded')
|
||||
assert kwargs.get('persist_lines') is False
|
||||
return {'status': 'ok', 'message': 'soft-linked'}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_snapshot_store.link_snapshot_to_task_for_preparation',
|
||||
_fake_prep_link,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_mapping_workflow.inventory_loaded_response',
|
||||
_fake_loaded,
|
||||
)
|
||||
monkeypatch.setattr(inventory_workflow, 'inventory_loaded_response', _fake_loaded)
|
||||
|
||||
result = inventory_workflow.ensure_inventory({
|
||||
'task_id': task.task_no,
|
||||
'mode': 'auto',
|
||||
'_orchestrator_internal_dispatch': True,
|
||||
})
|
||||
|
||||
assert result['status'] == 'ok'
|
||||
assert call_order == ['prep:stp_candidate_prep', 'loaded']
|
||||
@@ -8,6 +8,8 @@ from app.services.shipping_notice.reservation_region import (
|
||||
apply_reservation_region_candidates,
|
||||
extract_reservation_from_region_text,
|
||||
extract_reservation_from_vendor_comments_pages,
|
||||
project_reservation_onto_validation_evidence,
|
||||
reservation_region_candidates_from_layout,
|
||||
)
|
||||
|
||||
|
||||
@@ -106,8 +108,23 @@ def test_vendor_comments_window_crosses_pages_and_stops_at_first_terms_heading()
|
||||
assert [item['value'] for item in candidates] == ['33008', '3000098851']
|
||||
|
||||
|
||||
def test_terms_heading_matches_when_phrase_is_only_part_of_title():
|
||||
"""结束锚点只需标题含 Terms and Conditions,不要求整行仅有该短语。"""
|
||||
candidates, reason = extract_reservation_from_vendor_comments_pages([
|
||||
(1, _glyph_lines(
|
||||
'Vendor Comments',
|
||||
'DBS Reservation Line 1: 1000143920',
|
||||
'7. Terms and Conditions of Sale',
|
||||
'Reservation#99999',
|
||||
)),
|
||||
])
|
||||
|
||||
assert reason is None
|
||||
assert [item['value'] for item in candidates] == ['1000143920']
|
||||
|
||||
|
||||
def test_vendor_comments_window_requires_start_and_end_headings():
|
||||
"""缺少任一边界时不能把全文中的 Reservation 当作专区证据。"""
|
||||
"""缺少起始锚点时不得扫描全文;缺少结束锚点时仍返回窗内候选但必须带复核原因。"""
|
||||
candidates, reason = extract_reservation_from_vendor_comments_pages([
|
||||
(1, _glyph_lines('Reservation#33008')),
|
||||
])
|
||||
@@ -115,6 +132,18 @@ def test_vendor_comments_window_requires_start_and_end_headings():
|
||||
assert candidates == []
|
||||
assert reason == 'vendor_comments_anchor_missing'
|
||||
|
||||
open_candidates, open_reason = extract_reservation_from_vendor_comments_pages([
|
||||
(1, _glyph_lines(
|
||||
'Vendor Comments:',
|
||||
'DBS Reservation Line 1: 1000143920',
|
||||
'End Customer: D1',
|
||||
)),
|
||||
])
|
||||
assert open_reason == 'terms_and_conditions_anchor_missing'
|
||||
assert [item['value'] for item in open_candidates] == ['1000143920']
|
||||
assert open_candidates[0]['scope'] == 'line'
|
||||
assert open_candidates[0]['line_no'] == 1
|
||||
|
||||
|
||||
def test_reservation_region_applies_header_and_line_override_together():
|
||||
"""整单值是默认值,指定行的 Reservation 仅覆盖对应明细。"""
|
||||
@@ -165,3 +194,71 @@ def test_reservation_gate_blocks_empty_and_malformed_order_lines():
|
||||
|
||||
assert reservation_gate_issues([])[0]["reason"] == "missing_order_lines"
|
||||
assert reservation_gate_issues(["invalid-line"])[0]["reason"] == "invalid_order_line"
|
||||
|
||||
|
||||
def test_reservation_region_candidates_from_layout_requires_configured_region():
|
||||
"""未标注专区时不得扫描 Vendor Comments;标注后必须走锚点窗而非 page_no/region。"""
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 800, 'height': 600}},
|
||||
'page_glyphs': {
|
||||
'1': _glyph_lines(
|
||||
'Vendor Comments:',
|
||||
'DBS Reservation Line 1: 1000143920',
|
||||
'Terms and Conditions:',
|
||||
),
|
||||
},
|
||||
},
|
||||
}
|
||||
assert reservation_region_candidates_from_layout(definition={}, layout=layout) == {
|
||||
'candidates': [], 'reason': None,
|
||||
}
|
||||
result = reservation_region_candidates_from_layout(
|
||||
definition={'reservation_id_region': {'page_no': 9, 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1}}},
|
||||
layout=layout,
|
||||
)
|
||||
assert result['reason'] is None
|
||||
assert [item['value'] for item in result['candidates']] == ['1000143920']
|
||||
assert result['candidates'][0]['scope'] == 'line'
|
||||
assert result['candidates'][0]['line_no'] == 1
|
||||
|
||||
|
||||
def test_project_reservation_onto_validation_evidence_writes_line_and_review_reason():
|
||||
"""验证证据必须落入与正式解析相同的 header/line 字段,并保留锚点缺失原因。"""
|
||||
evidence = {
|
||||
'header_fields': [{
|
||||
'field_id': 'f-po', 'field_code': 'customer_po_number', 'raw_value': 'PO-1',
|
||||
'normalized_value': 'PO-1', 'status': 'passed', 'issues': [],
|
||||
}],
|
||||
'lines': [{'row_index': 0, 'fields': [{
|
||||
'field_id': 'f-part', 'field_code': 'part_number', 'raw_value': 'P-1',
|
||||
'normalized_value': 'P-1', 'status': 'passed', 'issues': [],
|
||||
}]}],
|
||||
'cross_checks': {},
|
||||
}
|
||||
projected = project_reservation_onto_validation_evidence(
|
||||
evidence,
|
||||
candidates=[{
|
||||
'value': '1000143920', 'line_no': 1, 'scope': 'line',
|
||||
'raw_text': 'DBS Reservation Line 1: 1000143920', 'status': 'mapped',
|
||||
}],
|
||||
reason=None,
|
||||
schema_fields={
|
||||
'header-reservation': {
|
||||
'field_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header',
|
||||
},
|
||||
'line-reservation': {
|
||||
'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
},
|
||||
},
|
||||
)
|
||||
assert projected['lines'][0]['fields'][-1] == {
|
||||
'field_id': 'line-reservation', 'field_code': 'reservation_id',
|
||||
'raw_value': '1000143920', 'normalized_value': '1000143920',
|
||||
'status': 'passed', 'issues': [],
|
||||
}
|
||||
missing = project_reservation_onto_validation_evidence(
|
||||
evidence, candidates=[], reason='vendor_comments_anchor_missing', schema_fields={},
|
||||
)
|
||||
assert missing['reservation_region_status'] == 'needs_review'
|
||||
assert missing['reservation_region_review_reasons'] == ['vendor_comments_anchor_missing']
|
||||
@@ -676,7 +676,7 @@ def test_create_run_scopes_to_selected_intakes_only(app):
|
||||
|
||||
@pytest.mark.parametrize('layout_status', ['queued', 'running'])
|
||||
def test_create_run_waits_for_active_document_layout_before_enqueuing_extraction(app, layout_status):
|
||||
"""发送后必须先完成版面解析;订单 Job 不得与布局 Job 并行抢跑。"""
|
||||
"""发送后若 PDF 版式仍在进行,Run 进入 waiting_layout;不得对未 ready 的 PDF 抽取。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
user, agent, session, intake, document = _seed_run_input(suffix=f'LAYOUT-{layout_status.upper()}')
|
||||
@@ -750,14 +750,14 @@ def test_create_run_accepts_a_reused_layout_from_an_identical_document(app):
|
||||
assert run.status == 'queued'
|
||||
|
||||
|
||||
def test_last_layout_completion_enqueues_waiting_run_once(app):
|
||||
"""最后一份附件布局完成才唤醒 Run,提前完成其中一份不能启动订单提取。"""
|
||||
def test_first_layout_completion_enqueues_waiting_run_for_ready_unit(app):
|
||||
"""任一份附件布局完成即可唤醒 Run;无需等齐全部版式。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='WAIT-ALL')
|
||||
user, agent, session, intake, first = _seed_run_input(suffix='WAIT-PARTIAL')
|
||||
second = ShippingOrderDocument(
|
||||
intake_id=intake.id, asset_id=first.asset_id, document_type='attachment',
|
||||
attachment_key='orders-WAIT-ALL-2.pdf', filename='orders-WAIT-ALL-2.pdf',
|
||||
attachment_key='orders-WAIT-PARTIAL-2.pdf', filename='orders-WAIT-PARTIAL-2.pdf',
|
||||
content_hash='b' * 64, classification='order_notice', parse_status='parsed', extracted_text='PO 2',
|
||||
)
|
||||
db.session.add(second)
|
||||
@@ -770,12 +770,28 @@ def test_last_layout_completion_enqueues_waiting_run_once(app):
|
||||
ShippingDocumentLayoutVersion.document_id.in_([first.id, second.id]),
|
||||
).all()
|
||||
assert len(layouts) == 2
|
||||
ready_payload = {
|
||||
'status': 'ready',
|
||||
'layout_candidate': {},
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
},
|
||||
}
|
||||
layouts[0].status = 'ready'
|
||||
layouts[0].payload_json = dict(ready_payload)
|
||||
first.current_layout_version_id = layouts[0].id
|
||||
db.session.commit()
|
||||
assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 0
|
||||
assert db.session.get(Job, run.current_job_id) is not None
|
||||
# 关键断言:第一份 ready 即可 resume(活跃 Job 去重仍只保留一条 extraction)。
|
||||
assert resume_runs_waiting_for_layout(document_id=layouts[0].document_id) == 1
|
||||
db.session.refresh(run)
|
||||
first_job_id = run.current_job_id
|
||||
assert db.session.get(Job, first_job_id) is not None
|
||||
assert run.phase == 'waiting_layout'
|
||||
|
||||
layouts[1].status = 'ready'
|
||||
layouts[1].payload_json = dict(ready_payload)
|
||||
second.current_layout_version_id = layouts[1].id
|
||||
db.session.commit()
|
||||
assert resume_runs_waiting_for_layout(document_id=layouts[1].document_id) == 1
|
||||
db.session.refresh(run)
|
||||
|
||||
@@ -67,6 +67,7 @@ def test_worker_materializes_inputs_before_reading_execution_plan(monkeypatch):
|
||||
monkeypatch.setattr(handler, 'materialize_order_extraction_run_inputs', fake_materialize)
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda _run, *, created_by_id: events.append('schedule') or False)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {1})
|
||||
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: events.append('units') or [])
|
||||
monkeypatch.setattr(handler, '_next_existing_batch', lambda _plan, *, after_batch: None)
|
||||
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda _run, _plan: [])
|
||||
@@ -113,6 +114,7 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
|
||||
lambda _run, *, created_by_id: events.append('schedule') or True,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {357: 'layout_pending'})
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: set())
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: events.append('waiting'))
|
||||
def fake_finish_job(*_args, **kwargs):
|
||||
events.append('finished')
|
||||
@@ -134,6 +136,116 @@ def test_worker_waits_after_materializing_pdf_and_scheduling_layout(monkeypatch)
|
||||
assert finished['message'] == '已转交附件版面解析,完成后自动创建后继订单识别任务'
|
||||
|
||||
|
||||
def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(monkeypatch):
|
||||
"""部分 PDF 版式就绪时只抽 ready Unit,Job 以 partial_units_done 收口且不终态 Run。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
finished: dict = {}
|
||||
run = SimpleNamespace(
|
||||
id=4, user_id=9, run_no='SNER-WORKER-PARTIAL', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
|
||||
input_snapshot_json={'attachment_selection': {}, 'intakes': []},
|
||||
execution_result_json=None, extraction_completed_at=None,
|
||||
)
|
||||
job = SimpleNamespace(id=4, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
ready_unit = SimpleNamespace(
|
||||
id=41, document_id=101, intake_id=1, status='pending', result_json=None, position=1,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
pending_unit = SimpleNamespace(
|
||||
id=42, document_id=102, intake_id=1, status='pending', result_json=None, position=2,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
plan = SimpleNamespace(id=4, unit_count=2, units=[ready_unit, pending_unit])
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else ready_unit)
|
||||
monkeypatch.setattr(
|
||||
handler, 'ShippingOrderProcessingRun',
|
||||
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
with_for_update=lambda: SimpleNamespace(first=lambda: run),
|
||||
))),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
|
||||
position=SimpleNamespace(asc=lambda: None),
|
||||
status=SimpleNamespace(in_=lambda *_a, **_k: True),
|
||||
query=SimpleNamespace(
|
||||
filter_by=lambda **_kwargs: SimpleNamespace(
|
||||
order_by=lambda *_args: SimpleNamespace(all=lambda: [ready_unit, pending_unit]),
|
||||
),
|
||||
),
|
||||
))
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
|
||||
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: events.append('freeze_begin'))
|
||||
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: events.append('freeze_complete'))
|
||||
monkeypatch.setattr(
|
||||
handler, 'materialize_order_extraction_run_inputs',
|
||||
lambda _run, *, finalize_plan=True: events.append('finalize' if finalize_plan else 'materialize') or (plan if finalize_plan else None),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: events.append('schedule') or False)
|
||||
monkeypatch.setattr(
|
||||
handler, 'order_extraction_layout_prerequisite_issues',
|
||||
lambda _run: {102: 'layout_pending'},
|
||||
)
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {101})
|
||||
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: True)
|
||||
monkeypatch.setattr(
|
||||
handler, 'transition_order_extraction_run',
|
||||
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
|
||||
)
|
||||
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [ready_unit, pending_unit])
|
||||
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
|
||||
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {})
|
||||
|
||||
def _fake_transition(unit, *, target_status, **_kwargs):
|
||||
unit.status = target_status
|
||||
events.append(f'transition:{target_status}')
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
|
||||
_fake_transition,
|
||||
)
|
||||
|
||||
def _process(**_kwargs):
|
||||
events.append('processed')
|
||||
ready_unit.status = 'merging_supplement'
|
||||
return [{'po_number': 'PO-1', '_hxops_intake_id': 1}]
|
||||
|
||||
monkeypatch.setattr(handler, '_process_unit_with_retries', _process)
|
||||
monkeypatch.setattr(
|
||||
handler, 'merge_unit_orders',
|
||||
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
|
||||
)
|
||||
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: events.append('progressed') or {})
|
||||
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {})
|
||||
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
|
||||
|
||||
def fake_finish(*_args, **kwargs):
|
||||
events.append('finished')
|
||||
finished.update(kwargs)
|
||||
|
||||
monkeypatch.setattr(handler, 'finish_job', fake_finish)
|
||||
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
|
||||
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
|
||||
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
|
||||
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
|
||||
|
||||
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 4})
|
||||
|
||||
assert 'processed' in events
|
||||
assert 'progressed' in events
|
||||
assert 'terminalized' not in events
|
||||
assert 'persist_started' not in events
|
||||
assert run.phase == 'waiting_layout'
|
||||
assert run.status == 'processing'
|
||||
assert finished['result']['handoff_status'] == 'partial_units_done'
|
||||
assert finished['result']['waiting_layout'] is True
|
||||
|
||||
|
||||
def test_worker_marks_run_failed_when_layout_scheduling_fails(monkeypatch):
|
||||
"""版面 Job 创建失败(如 MinerU 关闭)时必须同步收口 Run,禁止仅失败 Job 而留下 queued。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
@@ -72,7 +72,7 @@
|
||||
### 运行时事实与路由
|
||||
|
||||
- 原 PDF 是不可变源事实。`ensure_on_demand_coordinate_evidence()` 是唯一坐标补全入口:当前 Layout -> Run 快照补缺 -> 原生 PDF -> OCR;返回合并后的当前 Layout。任一关键坐标无法取得时固定输出 `coordinate_evidence_unavailable` 并进入 `review_required`。
|
||||
- **Reservation ID 专区动态锚点(2026-08-25)**:仅当已选中模板定义了 `reservation_id_region` 时启用。该配置不再以保存时的 `page_no/region` 作为正式取值位置,而是补齐全文页面坐标证据后,按阅读顺序从首次 `Vendor Comments` 标题之后累计到首次 `Terms and Condition` / `Terms and Conditions` 标题之前;区块可跨页。只在此封闭区块内解析带 `Reservation` 标签的合法 5/10 位数字,并复用既有行号归属和冲突规则。缺失任一起止锚点、边界顺序异常或值冲突均固定进入 Review,禁止自动猜测;未定义该专区的模板不扫描全文,原解析行为不变。
|
||||
- **Reservation ID 专区动态锚点(2026-08-25)**:仅当已选中模板定义了 `reservation_id_region` 时启用。该配置不再以保存时的 `page_no/region` 作为正式取值位置,而是补齐全文页面坐标证据后,按阅读顺序从首次 `Vendor Comments` 标题之后累计到首次 `Terms and Condition` / `Terms and Conditions` / `Terms & Conditions` 标题之前;区块可跨页。只在此封闭区块内解析带 `Reservation` 标签的合法 5/10 位数字,并复用既有行号归属和冲突规则。缺失起始锚点不扫描;缺失结束锚点时仍返回已累计窗内候选供展示与归属,但固定 `needs_review`,禁止当成可自动建单封闭证据;值冲突同样进入 Review。未定义该专区的模板不扫描全文,原解析行为不变。**画布预览候选、验证 current_sample、盲测候选与正式解析共用同一锚点扫描与归属契约**(2026-09-08);验证证据写入 `validation_evidence` 的 header/line `reservation_id` 字段,并在需复核时附带 `reservation_region_status/review_reasons`。
|
||||
- `matching_features.v1` 在压缩 `page_glyphs` 前持久化页面结构、主表框、表头及顺序、列数/中心/宽度和静态字段关系。它是稳定匹配输入,不升级命名;缺少关键特征不得从评分分母剔除后形成 `hard_match`。
|
||||
- **坐标证据外置为 FileAsset(2026-08-26/30 决策)**:`coordinate_evidence` 不再内联在布局快照的 `payload_json` 中。`record_inline_layout_snapshot` / `complete_layout_version` 在证据含非空 `page_glyphs`/`tables` 时,将其外置为派生 `FileAsset`(`asset_role=layout_coordinate_evidence`、`application/json+gzip`),从 payload 移除 `coordinate_evidence` 并写入轻量 `coordinate_evidence_ref`(`{asset_no, checksum, size, schema_version}`)。PDF 布局仅当 `coordinate_evidence_ref.asset_no` 存在时才视为 ready:否则 `complete_layout_version` 回退 `failed` 并写入 `shipping_document_layout_coordinate_evidence_incomplete`;仅当外置资产持久化失败时才写入 `shipping_document_layout_coordinate_evidence_persist_failed`。读取侧 `current_layout_snapshot()` 经 `_hydrate_coordinate_evidence` 从该资产回填 `coordinate_evidence`;`ensure_on_demand_coordinate_evidence()` 是唯一坐标补全入口,优先使用当前 Layout(坐标来自外置资产 hydration),缺页再从原 PDF 原生字形/OCR 补齐。原 PDF 始终是不可变源事实。
|
||||
- Profile 只识别版式身份;Schema 是唯一业务字段契约。订单头由 `page_glyphs + Profile field layout + Schema` 取值,订单行由 `table_glyphs + Profile table layout + Schema` 重建;两者共享同一个 Profile、Layout、Schema 和 `CoordinateTransform`。
|
||||
@@ -86,6 +86,7 @@
|
||||
- 自动标注只生成 Draft 的 `layout_schema_candidates`/建议,不能直接作为生产规则、不能自动接受、更不能自动发布。生产通用解析必须有冻结 `generic_parse_plan`,绑定 Schema、Layout、候选 checksum、映射决定及字段 `cell_id/evidence_ref`;Plan 缺失、漂移或证据缺失即 Review。
|
||||
- **模板样本就绪门禁(2026-08-21)**:上传成功只表示 PDF/EML 已物化为 `ShippingOrderDocument`,不表示可自动标注。Draft annotation sample 必须由同一 `refresh_profile_sample_readiness()` 在当前 ready Layout 上验证视觉主表、内容 hash、canonical payload checksum、parser provenance,并冻结 `layout_version_id + layout_payload_checksum` 后,才返回 `automark_ready=true`。保存草稿、样本状态轮询和 `/pdf-automark` 入队共用此服务;一旦主表缺失/歧义、Layout 尚未完成或身份不一致,返回稳定原因码并禁止入队,绝不降级成“配置无效”或猜测。Worker 执行期仍复验 Job 的冻结身份。状态按 `profile_id + annotation sample` 隔离,同一文档被其他 Draft 引用不会影响当前模板。该回填仅更新现有 Draft sample 字段和追加式审计,不新建 Profile 版本、不修改已发布版本。
|
||||
- Profile 仅允许 `draft -> published`;发布前必须满足 Schema/字段绑定校验、训练样本、独立盲测、双人批准、冻结样本证据及发布检查。已发布/退役版本只读;演进只能克隆为新 Draft,旧发布版本退役。管理端不提供自动接受、自动批准或自动发布路径。
|
||||
- **盲测预览明细展示(2026-09-09)**:`reconstruct_coordinate_profile_rows_with_strategy` 在运行时策略为 `needs_review` 时仍返回 fixed→adaptive→dynamic 的最佳努力明细,供盲测/验证人工核对;正式自动建单路径仍要求 `strategy.status == 'selected'`,不得把 fallback 当成可自动建单结果。盲测候选重建前还会确保表所在页的整页坐标证据已补齐。
|
||||
|
||||
### Dify 手工配置说明
|
||||
|
||||
@@ -1186,6 +1187,8 @@ OpenCV 当前结论:可保留为 L0/L2 的严格有框表候选和后续人工
|
||||
| `pending` / `document_queued` | `pending` / `document_queued` | 已接收,排队等待处理 |
|
||||
| `waiting_layout` / `layout_parsing_started` | `waiting_layout` / `layout_parsing_started` | 正在预处理文档结构 |
|
||||
| `routing` | `routing` | 正在识别文件类型与处理规则 |
|
||||
|
||||
> **版式→抽取放行(Unit 级,2026-09-08)**:`waiting_layout` 表示 Run 内仍有 PDF 版式未完成,不再要求全部 layout 就绪才开始订单抽取。任一 PDF layout ready 即可抽取对应 Unit 并 `progress_ready_extraction_unit`;兄弟文件继续等待。Run 终态仍须等全部 Unit 收敛。
|
||||
| `matching_profile` / `profile_matching` | `matching_profile` | 正在匹配订单解析模板 |
|
||||
| `extracting` / `table_reconstructed` / `order_fields_extracted` | `extracting` | 正在提取订单信息 |
|
||||
| `merging_supplement` / `email_supplement_merged` | `merging_supplement` | 正在合并邮件正文补充信息 |
|
||||
@@ -3310,7 +3313,7 @@ API 层
|
||||
|
||||
邮件正文保持 `email_context`,但其受控 HTML 表会被确定性解析为 PO 级补充事实,而不是订单 Candidate 或订单抽取 Unit。每个补充值冻结 EML Intake、正文 Document、表格/行/列、DOM `cell_id`、原始值与规范化值;Run 仅冻结这项事实,Worker 不会对正文单独执行订单解析。
|
||||
|
||||
合并优先使用 `PO + MPN`;只有同一 PO 的正文行唯一或唯一对应一个 Reservation 时,才能以 `po_fallback` 补齐。正文可覆盖/补齐 Reservation、Allocation 与库存来源提示,但绝不覆盖 PDF 的 PO、料号或数量;`allocated_qty` 仅作审计参考。多 Reservation、多来源、行无法唯一关联和无效表头均添加 `supplement_relation_ambiguous` 或稳定解析原因,并转入人工复核。
|
||||
合并优先使用 `PO + MPN`;其次同 PO 且双方均有合法 `reservation_id` 时以 `po_reservation` 按行对齐(解决 allocation 表 APN 对不上 PDF 料号时仍可补库存源线索);只有同一 PO 的正文行唯一或唯一对应一个 Reservation 时,才能以 `po_fallback` 补齐。正文可覆盖/补齐 Reservation、Allocation 与库存来源提示,但绝不覆盖 PDF 的 PO、料号或数量;`allocated_qty` 仅作审计参考。多 Reservation、多来源、行无法唯一关联和无效表头均添加 `supplement_relation_ambiguous` 或稳定解析原因,并转入人工复核。
|
||||
|
||||
#### 阶段 3:PDF 模板解析、PO 拆分与严格拒识(2026-07-27,迁移前历史)
|
||||
|
||||
|
||||
@@ -589,7 +589,15 @@ export const readOrderProfilePreviewPageRegionText = (
|
||||
signal?: AbortSignal,
|
||||
purpose?: 'reservation_id_region',
|
||||
renderedImageBase64?: string | null,
|
||||
) => requestJson<{ document_id: number; page_no: number; text: string; source: string | null; status: 'needs_review'; reservation_candidates?: Array<{ value: string; line_no: number | null; scope: 'header' | 'line'; raw_text: string; status: string }> }>(
|
||||
) => requestJson<{
|
||||
document_id: number;
|
||||
page_no: number;
|
||||
text: string;
|
||||
source: string | null;
|
||||
status: 'needs_review';
|
||||
reservation_candidates?: Array<{ value: string; line_no: number | null; scope: 'header' | 'line'; raw_text: string; status: string }>;
|
||||
reservation_region_reason?: string | null;
|
||||
}>(
|
||||
`/api/admin/shipping-notice/order-document-profiles/${profileId}/preview-pages/${pageNo}/region-text`, {
|
||||
method: 'POST', body: JSON.stringify({ document_id: documentId, region, ...(purpose ? { purpose } : {}), ...(renderedImageBase64 ? { rendered_image_base64: renderedImageBase64 } : {}) }), signal, ...jsonAuth(),
|
||||
},
|
||||
|
||||
+8
@@ -442,6 +442,14 @@ onBeforeUnmount(() => {
|
||||
<section v-if="candidate" class="card candidate-card">
|
||||
<h2>{{ t('admin.shippingOrderProfiles.blindTest.reviewHint') }}</h2>
|
||||
<p v-if="!candidate.confirmable" class="training-required">{{ t('admin.shippingOrderProfiles.blindTest.diagnosticOnly') }}</p>
|
||||
<p
|
||||
v-if="candidate.reservation_region_status === 'needs_review'"
|
||||
class="training-required"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.blindTest.reservationRegionNeedsReview', {
|
||||
reasons: (candidate.reservation_region_review_reasons || []).join(', ') || candidate.reservation_region_status,
|
||||
}) }}
|
||||
</p>
|
||||
<p v-if="!candidate.rows.length">{{ t('admin.shippingOrderProfiles.blindTest.candidateRowsEmpty') }}</p>
|
||||
<article v-for="(row, index) in candidate.rows" :key="index" class="review-item">
|
||||
<template v-if="rowReviews[index]">
|
||||
|
||||
+21
-6
@@ -5,7 +5,8 @@
|
||||
XfaDatasetTree、XfaCollectionSelector、XfaSplitRulePanel、shippingOrderField.utils。
|
||||
逻辑:PDF 与 XFA 共用同一 desk DOM(main + aside.config + OrderProfileDocumentCanvas);
|
||||
XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区;
|
||||
未绑定订单字段框通过横幅 + 画布高亮强制展示,避免空白底图漏看导致发布失败。
|
||||
未绑定订单字段框通过横幅 + 画布高亮强制展示,避免空白底图漏看导致发布失败;
|
||||
选中已有标注时退出绘制模式,避免 drawing 态吞掉缩放导致标签高度无法调整。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
@@ -467,6 +468,7 @@ const reservationIdCandidates = ref<Array<{
|
||||
raw_text: string;
|
||||
status: string;
|
||||
}>>([]);
|
||||
const reservationIdRegionReason = ref<string | null>(null);
|
||||
const reservationIdCandidateState = ref<'idle' | 'loading' | 'ready' | 'failed'>('idle');
|
||||
/**
|
||||
* 共同画布的字段选项只决定视觉定位;coordinate 末端值源仍必须由 Schema 显式授权
|
||||
@@ -556,7 +558,11 @@ const ensureTableRegionSetting = (targetPageNo: number) => {
|
||||
/** coordinate 末端取值 adapter 投影的画布动作。 */
|
||||
const coordinateCanvasActions = computed<OrderProfileCanvasActions>(() => ({
|
||||
create: (region) => createDrawnRegion(region),
|
||||
select: (id) => { selectedId.value = id; },
|
||||
select: (id) => {
|
||||
// 选中已有框时退出绘制,否则 .drawing 会吞掉缩放手柄事件,表现为高度无法调整。
|
||||
creationKind.value = null;
|
||||
selectedId.value = id;
|
||||
},
|
||||
dragStart: (id) => beginRegionGesture(id),
|
||||
dragEnd: () => endRegionGesture(),
|
||||
change: (id, region) => updateRegion(id, region),
|
||||
@@ -1038,18 +1044,22 @@ const updateReservationIdRegion = (region: OrderProfileRelativeRegion): void =>
|
||||
};
|
||||
const clearReservationIdRegion = (): void => {
|
||||
reservationIdRegion.value = null;
|
||||
reservationIdCandidates.value = [];
|
||||
reservationIdRegionReason.value = null;
|
||||
reservationIdCandidateState.value = 'idle';
|
||||
reservationIdRegionDirty.value = true;
|
||||
markLocalChange();
|
||||
scheduleAutosave();
|
||||
};
|
||||
/**
|
||||
* 读取当前圈选区域的 Reservation 候选。
|
||||
* 核心逻辑:编辑器预览调用与正式解析相同的后端固定解析器,前端不自行推断行归属。
|
||||
* 读取当前专区启用后的 Reservation 候选(与正式解析相同的 Vendor Comments 锚点)。
|
||||
* 核心逻辑:编辑器预览调用后端锚点扫描;矩形仅作启用标记,前端不自行推断行归属。
|
||||
*/
|
||||
const refreshReservationIdCandidates = async (): Promise<void> => {
|
||||
const configured = reservationIdRegion.value;
|
||||
if (!active.value || !form.documentId || !configured) {
|
||||
reservationIdCandidates.value = [];
|
||||
reservationIdRegionReason.value = null;
|
||||
reservationIdCandidateState.value = 'idle';
|
||||
return;
|
||||
}
|
||||
@@ -1064,9 +1074,11 @@ const refreshReservationIdCandidates = async (): Promise<void> => {
|
||||
'reservation_id_region',
|
||||
);
|
||||
reservationIdCandidates.value = result.reservation_candidates || [];
|
||||
reservationIdRegionReason.value = result.reservation_region_reason || null;
|
||||
reservationIdCandidateState.value = 'ready';
|
||||
} catch {
|
||||
reservationIdCandidates.value = [];
|
||||
reservationIdRegionReason.value = null;
|
||||
reservationIdCandidateState.value = 'failed';
|
||||
}
|
||||
};
|
||||
@@ -3360,11 +3372,14 @@ onBeforeUnmount(() => {
|
||||
>
|
||||
清除区域
|
||||
</button>
|
||||
<small v-if="reservationIdRegion">已标记第 {{ reservationIdRegion.page_no }} 页区域;解析结果由预览/复核统一返回。</small>
|
||||
<small v-if="reservationIdRegion">已标记第 {{ reservationIdRegion.page_no }} 页区域;正式取值按 Vendor Comments→Terms 锚点,与验证/盲测/正式解析一致。</small>
|
||||
<p v-if="reservationIdCandidateState === 'loading'" class="reservation-region-config__status">正在识别 Reservation ID…</p>
|
||||
<p v-else-if="reservationIdCandidateState === 'failed'" class="reservation-region-config__status">区域预览失败;保存后可在盲测/复核中再次确认。</p>
|
||||
<template v-else-if="reservationIdCandidateState === 'ready'">
|
||||
<p v-if="!reservationIdCandidates.length" class="reservation-region-config__status">未识别到 Reservation ID,请检查圈选范围。</p>
|
||||
<p v-if="reservationIdRegionReason" class="reservation-region-config__status reservation-region-config__review">
|
||||
专区锚点异常:{{ reservationIdRegionReason }}
|
||||
</p>
|
||||
<p v-else-if="!reservationIdCandidates.length" class="reservation-region-config__status">未识别到 Reservation ID,请检查 Vendor Comments / Terms 锚点。</p>
|
||||
<ul v-else class="reservation-region-config__candidates">
|
||||
<li v-for="candidate in reservationIdCandidates" :key="`${candidate.value}:${candidate.line_no}:${candidate.raw_text}`">
|
||||
<code>{{ candidate.value }}</code>
|
||||
|
||||
+19
-15
@@ -261,20 +261,23 @@ onMounted(loadFamilies);
|
||||
</small>
|
||||
</td>
|
||||
<td class="profile-library__actions">
|
||||
<button v-if="item.draft_profile_id" class="btn-ghost btn-sm" type="button" @click="continueEditing(item)">{{ t('admin.shippingOrderProfiles.versionCenter.continueEditing') }}</button>
|
||||
<button v-if="item.draft_profile_id" class="btn-danger btn-sm" type="button" @click="requestDeleteDraft(item)">{{ t('admin.delete') }}</button>
|
||||
<button v-else-if="item.published_profile_id && !schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="createNewVersion(item)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
|
||||
<button v-if="!item.draft_profile_id && item.published_profile_id && schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="openSchemaMigration(item)">{{ t('admin.shippingOrderProfiles.schemaMigration.listAction') }}</button>
|
||||
<button class="btn-ghost btn-sm" type="button" @click="viewVersion(item)">{{ t('admin.shippingOrderProfiles.versionCenter.viewVersion') }}</button>
|
||||
<button
|
||||
v-if="item.unified_binding_status === 'needs_migration' || item.unified_needs_migration"
|
||||
class="btn-ghost btn-sm"
|
||||
type="button"
|
||||
data-testid="order-profile-unified-migration-open"
|
||||
@click="openUnifiedMigration(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.unifiedMigration.open') }}
|
||||
</button>
|
||||
<!-- flex 必须放在 td 内层,避免破坏 table-cell 盒模型导致行分隔线错位 -->
|
||||
<div class="profile-library__actions-inner">
|
||||
<button v-if="item.draft_profile_id" class="btn-ghost btn-sm" type="button" @click="continueEditing(item)">{{ t('admin.shippingOrderProfiles.versionCenter.continueEditing') }}</button>
|
||||
<button v-if="item.draft_profile_id" class="btn-danger btn-sm" type="button" @click="requestDeleteDraft(item)">{{ t('admin.delete') }}</button>
|
||||
<button v-else-if="item.published_profile_id && !schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="createNewVersion(item)">{{ t('admin.shippingOrderProfiles.newVersion') }}</button>
|
||||
<button v-if="!item.draft_profile_id && item.published_profile_id && schemaMigrationRequired(item)" class="btn-secondary btn-sm" type="button" @click="openSchemaMigration(item)">{{ t('admin.shippingOrderProfiles.schemaMigration.listAction') }}</button>
|
||||
<button class="btn-ghost btn-sm" type="button" @click="viewVersion(item)">{{ t('admin.shippingOrderProfiles.versionCenter.viewVersion') }}</button>
|
||||
<button
|
||||
v-if="item.unified_binding_status === 'needs_migration' || item.unified_needs_migration"
|
||||
class="btn-ghost btn-sm"
|
||||
type="button"
|
||||
data-testid="order-profile-unified-migration-open"
|
||||
@click="openUnifiedMigration(item)"
|
||||
>
|
||||
{{ t('admin.shippingOrderProfiles.unifiedMigration.open') }}
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -326,7 +329,8 @@ onMounted(loadFamilies);
|
||||
.status-badge.published { border-color: #bbf7d0; background: #f0fdf4; color: #15803d; }
|
||||
.schema-status { display: block; margin-top: 5px; color: #64748b; font-size: 11px; white-space: nowrap; }.schema-status.warning { color: #b45309; }
|
||||
.actions-heading { min-width: 190px; }
|
||||
.profile-library__actions { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
|
||||
.profile-library__actions { vertical-align: middle; }
|
||||
.profile-library__actions-inner { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; }
|
||||
|
||||
@media (max-width: 700px) {
|
||||
.page-header { flex-direction: column; }
|
||||
|
||||
+22
@@ -55,10 +55,19 @@ const validationEvidence = computed<OrderProfileValidationEvidence | null>(() =>
|
||||
cross_checks: value.cross_checks && typeof value.cross_checks === 'object' && !Array.isArray(value.cross_checks)
|
||||
? value.cross_checks as Record<string, unknown>
|
||||
: {},
|
||||
reservation_region_status: typeof value.reservation_region_status === 'string'
|
||||
? value.reservation_region_status
|
||||
: undefined,
|
||||
reservation_region_review_reasons: Array.isArray(value.reservation_region_review_reasons)
|
||||
? value.reservation_region_review_reasons.map((item) => String(item))
|
||||
: undefined,
|
||||
};
|
||||
});
|
||||
const evidenceHeaderFields = computed(() => validationEvidence.value?.header_fields || []);
|
||||
const evidenceLines = computed(() => validationEvidence.value?.lines || []);
|
||||
const reservationRegionReviewReasons = computed(
|
||||
() => validationEvidence.value?.reservation_region_review_reasons || [],
|
||||
);
|
||||
const ADAPTER_CROSS_CHECK_KEYS = [
|
||||
'mirror_status',
|
||||
'acroform_status',
|
||||
@@ -330,6 +339,16 @@ onMounted(async () => {
|
||||
</dl>
|
||||
<p v-else>{{ t('admin.orderProfileValidation.noHeaderResults') }}</p>
|
||||
|
||||
<section
|
||||
v-if="validationEvidence?.reservation_region_status === 'needs_review' || reservationRegionReviewReasons.length"
|
||||
class="reservation-region-review"
|
||||
>
|
||||
<h3>{{ t('admin.orderProfileValidation.reservationRegionTitle') }}</h3>
|
||||
<p>{{ t('admin.orderProfileValidation.reservationRegionNeedsReview', {
|
||||
reasons: reservationRegionReviewReasons.join(', ') || validationEvidence?.reservation_region_status || '-',
|
||||
}) }}</p>
|
||||
</section>
|
||||
|
||||
<h3>{{ t('admin.orderProfileValidation.lineResults') }}</h3>
|
||||
<div v-if="evidenceLines.length" class="line-results">
|
||||
<article v-for="line in evidenceLines" :key="String(line.row_index)" class="xfa-line-card">
|
||||
@@ -371,6 +390,9 @@ button:disabled { cursor: not-allowed; opacity: .55; }
|
||||
.results { margin-top: 20px; padding: 16px; }.results-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; }.results h2, .results h3 { margin: 0; color: #1e293b; }.results h2 { font-size: 15px; }.results h3 { margin-top: 20px; font-size: 14px; }.results-heading p { margin: 5px 0 0; color: #64748b; font-size: 13px; line-height: 1.5; }.header-results { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; margin: 12px 0 0; }.header-results div { border: 1px solid #e5ebf1; border-radius: 6px; background: #fbfdff; padding: 10px; }.header-results dt { color: #475569; font-size: 13px; font-weight: 600; }.header-results dd { margin: 4px 0 0; overflow-wrap: anywhere; }.header-results .field-code, .line-results th small { color: #94a3b8; font-size: 11px; font-weight: 400; }.line-results { margin-top: 12px; overflow-x: auto; border: 1px solid #e5ebf1; border-radius: 6px; }.line-results table { width: 100%; min-width: 560px; border-collapse: collapse; }.line-results th, .line-results td { padding: 10px 12px; border-bottom: 1px solid #e5ebf1; text-align: left; vertical-align: top; overflow-wrap: anywhere; }.line-results tbody tr:last-child td { border-bottom: 0; }.line-results th { background: #f8fafc; color: #64748b; font-size: 12px; font-weight: 600; }.line-results th span, .line-results th small { display: block; }.deleted-row { color: #94a3b8; text-decoration: line-through; }.result-error { color: #b91c1c; }
|
||||
.header-results .field-needs_review, .header-results .field-unavailable, .header-results .field-failed, .header-results .field-missing { border-color: #fed7aa; background: #fff7ed; }.header-results .field-issues { color: #b45309; font-size: 11px; }
|
||||
.header-results .field-passed { border-color: #bbf7d0; background: #f0fdf4; }
|
||||
.reservation-region-review { margin-top: 16px; padding: 12px; border: 1px solid #fed7aa; border-radius: 8px; background: #fff7ed; }
|
||||
.reservation-region-review h3 { margin: 0; color: #9a3412; font-size: 14px; }
|
||||
.reservation-region-review p { margin: 6px 0 0; color: #b45309; font-size: 13px; }
|
||||
.xfa-line-card { margin-top: 12px; padding: 12px; border: 1px solid #e5ebf1; border-radius: 8px; background: #fbfdff; }.xfa-line-card h4 { margin: 0 0 8px; font-size: 13px; color: #475569; }
|
||||
@media (max-width: 767px) { .validation-page { padding: 16px; } header, .validation-state, .current-draft-validation > header, .checks article, .blind-test-gate, .results-heading { display: grid; }.validation-state button, .current-draft-validation > header button, .blind-test-gate button, .results-heading button { width: 100%; } }
|
||||
</style>
|
||||
+106
@@ -142,6 +142,112 @@ describe('OrderProfileDocumentCanvas PDF preview', () => {
|
||||
expect(region.attributes('aria-label')).toContain('待绑定');
|
||||
});
|
||||
|
||||
it('ignores wheel zoom while a vertical resize drag is active', async () => {
|
||||
const shortAnchor = {
|
||||
id: 'order_field_1_1_anchor',
|
||||
kind: 'order_anchor' as const,
|
||||
label: 'Number',
|
||||
pageNo: 1,
|
||||
region: { x0: .78, y0: .12, x1: .84, y1: .158 },
|
||||
};
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: {
|
||||
profileId: 8,
|
||||
grant: { page_no: 1, preview_token: 'page-token' },
|
||||
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/8/preview-pages',
|
||||
regions: [shortAnchor],
|
||||
selectedRegionId: shortAnchor.id,
|
||||
pageNo: 1,
|
||||
pageCount: 1,
|
||||
},
|
||||
global: {
|
||||
plugins: [createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: { shippingOrderProfiles: { workbench: { pagePreviewAlt: 'page', resizeHandle: '{direction}' } } },
|
||||
},
|
||||
},
|
||||
})],
|
||||
},
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
const stage = wrapper.find('.canvas-stage').element as HTMLElement;
|
||||
Object.defineProperty(stage, 'getBoundingClientRect', {
|
||||
value: () => ({ left: 0, top: 0, width: 1000, height: 1000, right: 1000, bottom: 1000, x: 0, y: 0, toJSON: () => ({}) }),
|
||||
});
|
||||
|
||||
const southEdge = wrapper.find('.resize-edge-s');
|
||||
southEdge.element.dispatchEvent(new PointerEvent('pointerdown', {
|
||||
bubbles: true, cancelable: true, clientX: 810, clientY: 158, pointerId: 1,
|
||||
}));
|
||||
// 拖高过程中触控板滚轮不得改缩放,否则纵向手势表现为“高度拉不动”。
|
||||
const beforeZoom = wrapper.find('.zoom-control output').text();
|
||||
await wrapper.find('.canvas-viewport').trigger('wheel', { deltaY: -120 });
|
||||
expect(wrapper.find('.zoom-control output').text()).toBe(beforeZoom);
|
||||
|
||||
window.dispatchEvent(new PointerEvent('pointermove', { clientX: 810, clientY: 240 }));
|
||||
window.dispatchEvent(new PointerEvent('pointerup', { clientX: 810, clientY: 240 }));
|
||||
await flushPromises();
|
||||
|
||||
const change = wrapper.emitted('change')?.at(-1);
|
||||
expect((change?.[1] as { y1: number }).y1).toBeGreaterThan(shortAnchor.region.y1);
|
||||
expect(wrapper.find('.region').attributes('style')).toContain('bottom:');
|
||||
});
|
||||
|
||||
it('allows shrinking label height below the legacy 0.01 floor', async () => {
|
||||
const tallAnchor = {
|
||||
id: 'order_field_1_2_anchor',
|
||||
kind: 'order_anchor' as const,
|
||||
label: 'Number',
|
||||
pageNo: 1,
|
||||
region: { x0: .70, y0: .035, x1: .85, y1: .055 },
|
||||
};
|
||||
const wrapper = mount(OrderProfileDocumentCanvas, {
|
||||
props: {
|
||||
profileId: 8,
|
||||
grant: { page_no: 1, preview_token: 'page-token' },
|
||||
previewPagePath: '/api/admin/shipping-notice/order-document-profiles/8/preview-pages',
|
||||
regions: [tallAnchor],
|
||||
selectedRegionId: tallAnchor.id,
|
||||
pageNo: 1,
|
||||
pageCount: 1,
|
||||
},
|
||||
global: {
|
||||
plugins: [createI18n({
|
||||
legacy: false,
|
||||
locale: 'zh-CN',
|
||||
messages: {
|
||||
'zh-CN': {
|
||||
admin: { shippingOrderProfiles: { workbench: { pagePreviewAlt: 'page', resizeHandle: '{direction}' } } },
|
||||
},
|
||||
},
|
||||
})],
|
||||
},
|
||||
});
|
||||
await flushPromises();
|
||||
|
||||
const stage = wrapper.find('.canvas-stage').element as HTMLElement;
|
||||
Object.defineProperty(stage, 'getBoundingClientRect', {
|
||||
value: () => ({ left: 0, top: 0, width: 1000, height: 1000, right: 1000, bottom: 1000, x: 0, y: 0, toJSON: () => ({}) }),
|
||||
});
|
||||
|
||||
// 从下边向上拖,目标高度约 0.006(低于旧下限 0.01,高于新下限 0.002)。
|
||||
wrapper.find('.resize-edge-s').element.dispatchEvent(new PointerEvent('pointerdown', {
|
||||
bubbles: true, cancelable: true, clientX: 775, clientY: 55, pointerId: 1,
|
||||
}));
|
||||
window.dispatchEvent(new PointerEvent('pointermove', { clientX: 775, clientY: 41 }));
|
||||
window.dispatchEvent(new PointerEvent('pointerup', { clientX: 775, clientY: 41 }));
|
||||
await flushPromises();
|
||||
|
||||
const next = wrapper.emitted('change')?.at(-1)?.[1] as { y0: number; y1: number };
|
||||
// 关键断言:单行标签可缩到 <0.01;旧硬编码 .01 会把 y1 卡在 y0+0.01。
|
||||
expect(next.y1 - next.y0).toBeLessThan(0.01);
|
||||
expect(next.y1 - next.y0).toBeGreaterThanOrEqual(0.002);
|
||||
});
|
||||
|
||||
it('captures the selected XFA appearance from the unscaled PDF.js canvas', async () => {
|
||||
const drawImage = vi.fn();
|
||||
const toDataURL = vi.fn(() => 'data:image/png;base64,canvas-crop');
|
||||
|
||||
+91
-19
@@ -5,6 +5,9 @@
|
||||
逻辑:父级签发单页令牌并提供分页动作;mode=readonly 时只允许查看/缩放/切页,不允许写入任何标注改动;
|
||||
PNG 预览 token 为一次性消费,组件内按页缓存 blob,翻页回访不再重新拉 token;
|
||||
未绑定订单字段框强制高亮(region--unbound),并暴露 scrollRegionIntoView 供横幅定位删除;
|
||||
选中框用 top/right/bottom/left 定位(避免 height% 在内容撑高容器上失效);
|
||||
拖拽/缩放进行中忽略滚轮缩放,避免触控板纵向手势把高度调整抢走;
|
||||
绘制模式下仍允许操作当前选中框;整边 resize 热区便于矮标签拉高;
|
||||
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
@@ -245,20 +248,39 @@ const onRetryClick = () => {
|
||||
emit('retry');
|
||||
};
|
||||
|
||||
/**
|
||||
* 画布框最小边长(相对页坐标)。
|
||||
* 旧值 0.01(页高 1%)对单行标签过粗,例如 Number 框会被卡在高度差 ≥0.01;
|
||||
* 0.002 仍保证正面积,又能贴紧字形。
|
||||
*/
|
||||
const MIN_REGION_SPAN = 0.002;
|
||||
|
||||
/**
|
||||
* 判断缩放手柄是否包含指定轴向。
|
||||
* 核心逻辑:用显式枚举替代 `includes('n')`,避免手柄命名变更时误匹配。
|
||||
*/
|
||||
const resizeAffects = (handle: ResizeHandle, axis: 'n' | 'e' | 's' | 'w'): boolean => {
|
||||
if (axis === 'n') return handle === 'n' || handle === 'ne' || handle === 'nw';
|
||||
if (axis === 's') return handle === 's' || handle === 'se' || handle === 'sw';
|
||||
if (axis === 'e') return handle === 'e' || handle === 'ne' || handle === 'se';
|
||||
return handle === 'w' || handle === 'nw' || handle === 'sw';
|
||||
};
|
||||
|
||||
/** 将指针移动映射为相对坐标;readonly 模式只保留选中,不允许几何变化。 */
|
||||
const move = (event: PointerEvent) => {
|
||||
if (!activeDrag || !canvas.value || readonlyMode.value) return;
|
||||
const bounds = canvas.value.getBoundingClientRect();
|
||||
if (bounds.width < 1 || bounds.height < 1) return;
|
||||
const dx = (event.clientX - activeDrag.startX) / bounds.width;
|
||||
const dy = (event.clientY - activeDrag.startY) / bounds.height;
|
||||
if (activeDrag.mode !== 'move') {
|
||||
const handle = activeDrag.mode;
|
||||
const prior = activeDrag.region;
|
||||
const next = {
|
||||
x0: handle.includes('w') ? Math.max(0, Math.min(prior.x1 - .01, prior.x0 + dx)) : prior.x0,
|
||||
y0: handle.includes('n') ? Math.max(0, Math.min(prior.y1 - .01, prior.y0 + dy)) : prior.y0,
|
||||
x1: handle.includes('e') ? Math.max(prior.x0 + .01, Math.min(1, prior.x1 + dx)) : prior.x1,
|
||||
y1: handle.includes('s') ? Math.max(prior.y0 + .01, Math.min(1, prior.y1 + dy)) : prior.y1,
|
||||
x0: resizeAffects(handle, 'w') ? Math.max(0, Math.min(prior.x1 - MIN_REGION_SPAN, prior.x0 + dx)) : prior.x0,
|
||||
y0: resizeAffects(handle, 'n') ? Math.max(0, Math.min(prior.y1 - MIN_REGION_SPAN, prior.y0 + dy)) : prior.y0,
|
||||
x1: resizeAffects(handle, 'e') ? Math.max(prior.x0 + MIN_REGION_SPAN, Math.min(1, prior.x1 + dx)) : prior.x1,
|
||||
y1: resizeAffects(handle, 's') ? Math.max(prior.y0 + MIN_REGION_SPAN, Math.min(1, prior.y1 + dy)) : prior.y1,
|
||||
};
|
||||
emit('change', activeDrag.id, next);
|
||||
return;
|
||||
@@ -279,6 +301,7 @@ const beginDrag = (event: PointerEvent, region: OrderProfileCanvasRegion, mode:
|
||||
activeDrag = { id: region.id, mode, startX: event.clientX, startY: event.clientY, region: { ...region.region } };
|
||||
window.addEventListener('pointermove', move);
|
||||
window.addEventListener('pointerup', endMove, { once: true });
|
||||
window.addEventListener('pointercancel', endMove, { once: true });
|
||||
};
|
||||
|
||||
/** 结束一次区域移动并停止全局事件监听。 */
|
||||
@@ -286,6 +309,7 @@ const endMove = () => {
|
||||
activeDrag = null;
|
||||
emit('end');
|
||||
window.removeEventListener('pointermove', move);
|
||||
window.removeEventListener('pointercancel', endMove);
|
||||
};
|
||||
/** 未处于绘制模式时以左键拖动画布视口,避免依赖横纵滚动条定位放大页面。 */
|
||||
const beginPan = (event: PointerEvent) => {
|
||||
@@ -321,7 +345,7 @@ const updateCreation = (event: PointerEvent) => {
|
||||
};
|
||||
const endCreation = () => {
|
||||
const region = creationRegion.value;
|
||||
if (region && region.x1 - region.x0 >= .01 && region.y1 - region.y0 >= .01) emit('create', region);
|
||||
if (region && region.x1 - region.x0 >= MIN_REGION_SPAN && region.y1 - region.y0 >= MIN_REGION_SPAN) emit('create', region);
|
||||
creationStart = null;
|
||||
creationRegion.value = null;
|
||||
window.removeEventListener('pointermove', updateCreation);
|
||||
@@ -357,8 +381,11 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
|
||||
const adjustZoom = (delta: number) => { zoom.value = Math.max(.5, Math.min(4, Math.round((zoom.value + delta) * 100) / 100)); };
|
||||
/** 恢复适合工作台宽度的默认倍率,便于快速定位整页。 */
|
||||
const resetZoom = () => { zoom.value = 1; };
|
||||
/** 在画布上滚动时缩放页面,避免管理员来回点击工具栏中断标注。 */
|
||||
const handleWheel = (event: WheelEvent) => { adjustZoom(event.deltaY < 0 ? .1 : -.1); };
|
||||
/** 在画布上滚动时缩放页面;拖拽/绘制进行中忽略,避免触控板纵向手势抢走高度调整。 */
|
||||
const handleWheel = (event: WheelEvent) => {
|
||||
if (activeDrag || activePan || creationStart) return;
|
||||
adjustZoom(event.deltaY < 0 ? .1 : -.1);
|
||||
};
|
||||
/** 校验页码输入并请求父工作台切页;超出范围时吸附到最近有效页。 */
|
||||
const goToPage = () => {
|
||||
const nextPage = Math.max(1, Math.min(props.pageCount || 1, Math.round(Number(pageInput.value) || props.pageNo)));
|
||||
@@ -511,7 +538,12 @@ onBeforeUnmount(() => {
|
||||
},
|
||||
region.visualBindingStatus ? `region-visual--${region.visualBindingStatus}` : '',
|
||||
]"
|
||||
:style="{ left: `${region.region.x0 * 100}%`, top: `${region.region.y0 * 100}%`, width: `${(region.region.x1 - region.region.x0) * 100}%`, height: `${(region.region.y1 - region.region.y0) * 100}%` }"
|
||||
:style="{
|
||||
left: `${region.region.x0 * 100}%`,
|
||||
top: `${region.region.y0 * 100}%`,
|
||||
right: `${(1 - region.region.x1) * 100}%`,
|
||||
bottom: `${(1 - region.region.y1) * 100}%`,
|
||||
}"
|
||||
:aria-label="displayRegionLabel(region)"
|
||||
@pointerdown.stop="beginDrag($event, region, 'move')"
|
||||
@keydown.enter="emit('select', region.id)"
|
||||
@@ -521,9 +553,39 @@ onBeforeUnmount(() => {
|
||||
<template v-if="region.kind === 'line' && !readonlyMode && !region.isPreview">
|
||||
<span v-for="edge in ['n', 'e', 's', 'w']" :key="edge" class="line-hit-edge" :class="`line-hit-${edge}`" @pointerdown.stop="beginDrag($event, region, 'move')" />
|
||||
</template>
|
||||
<button v-if="!readonlyMode && !region.isPreview" v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]" :key="handle" type="button" class="resize-handle" :class="`handle-${handle}`" :aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })" @pointerdown.stop="beginDrag($event, region, handle)" />
|
||||
<!-- 整边缩放热区:矮标签框拖上下边时不再落入整体 move。角点手柄叠在热区之上。 -->
|
||||
<template v-if="!readonlyMode && !region.isPreview && selected.has(region.id)">
|
||||
<span
|
||||
v-for="edge in ['n', 'e', 's', 'w'] as ResizeHandle[]"
|
||||
:key="`edge-${edge}`"
|
||||
class="resize-edge"
|
||||
:class="`resize-edge-${edge}`"
|
||||
:aria-hidden="true"
|
||||
@pointerdown.stop="beginDrag($event, region, edge)"
|
||||
/>
|
||||
</template>
|
||||
<span
|
||||
v-if="!readonlyMode && !region.isPreview"
|
||||
v-for="handle in ['n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw'] as ResizeHandle[]"
|
||||
:key="handle"
|
||||
role="button"
|
||||
tabindex="-1"
|
||||
class="resize-handle"
|
||||
:class="`handle-${handle}`"
|
||||
:aria-label="t('admin.shippingOrderProfiles.workbench.resizeHandle', { direction: handle })"
|
||||
@pointerdown.stop="beginDrag($event, region, handle)"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="creationRegion" class="creation-region" :style="{ left: `${creationRegion.x0 * 100}%`, top: `${creationRegion.y0 * 100}%`, width: `${(creationRegion.x1 - creationRegion.x0) * 100}%`, height: `${(creationRegion.y1 - creationRegion.y0) * 100}%` }" />
|
||||
<div
|
||||
v-if="creationRegion"
|
||||
class="creation-region"
|
||||
:style="{
|
||||
left: `${creationRegion.x0 * 100}%`,
|
||||
top: `${creationRegion.y0 * 100}%`,
|
||||
right: `${(1 - creationRegion.x1) * 100}%`,
|
||||
bottom: `${(1 - creationRegion.y1) * 100}%`,
|
||||
}"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -578,6 +640,9 @@ onBeforeUnmount(() => {
|
||||
.canvas-stage img { display: block; width: 100%; user-select: none; }
|
||||
.canvas-stage canvas.pdf-page { display: block; background: white; pointer-events: none; user-select: none; }
|
||||
.canvas-stage.drawing { cursor: crosshair; }
|
||||
.canvas-stage.drawing .region { pointer-events: none; }
|
||||
/* 绘制模式下仍可缩放/移动当前选中框,避免点了标签工具后高度完全拉不动。 */
|
||||
.canvas-stage.drawing .region.selected { pointer-events: auto; }
|
||||
.creation-region { position: absolute; z-index: 5; box-sizing: border-box; border: 2px dashed #34d399; background: rgb(16 185 129 / .18); pointer-events: none; }
|
||||
.annotation-tools { display: grid; align-content: start; gap: .3rem; flex: 0 0 2.65rem; padding: .3rem; border: 1px solid rgb(71 85 105 / .9); border-radius: .5rem; background: rgb(15 23 42 / .94); box-shadow: 0 8px 24px rgb(15 23 42 / .3); }
|
||||
.annotation-tools button { display: grid; min-height: 2rem; place-items: center; border: 1px solid transparent; border-radius: .35rem; background: #1e293b; padding: .35rem; color: #e2e8f0; }
|
||||
@@ -589,16 +654,24 @@ onBeforeUnmount(() => {
|
||||
.suggestion-preview-badge { color: #fbbf24; font-size: .68rem; }
|
||||
.region { position: absolute; box-sizing: border-box; z-index: 2; border: 2px solid #38bdf8; background: rgb(14 165 233 / .10); color: #e0f2fe; cursor: move; text-align: left; touch-action: none; }
|
||||
.region:focus-visible { outline: 3px solid white; outline-offset: 2px; }
|
||||
.region-label { position: absolute; top: -1.65rem; left: -2px; max-width: min(18rem, 100%); overflow: hidden; border: 1px solid rgb(255 255 255 / .7); border-radius: .25rem .25rem 0 0; background: #0369a1; padding: .2rem .45rem; color: white; font: 700 .7rem/1.15 ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.resize-handle { position: absolute; z-index: 3; width: 10px; height: 10px; border: 2px solid white; border-radius: 2px; background: #0ea5e9; box-shadow: 0 1px 2px rgb(15 23 42 / .55); padding: 0; touch-action: none; }
|
||||
.handle-n, .handle-s { left: 50%; margin-left: -5px; cursor: ns-resize; }
|
||||
.handle-e, .handle-w { top: 50%; margin-top: -5px; cursor: ew-resize; }
|
||||
.region-label { position: absolute; z-index: 2; top: -1.65rem; left: -2px; max-width: min(18rem, 100%); overflow: hidden; border: 1px solid rgb(255 255 255 / .7); border-radius: .25rem .25rem 0 0; background: #0369a1; padding: .2rem .45rem; color: white; font: 700 .7rem/1.15 ui-monospace, SFMono-Regular, Menlo, monospace; text-overflow: ellipsis; white-space: nowrap; }
|
||||
/* 整边热区略伸出框外,左右缩进避开角点,保证矮框上下边可拉高。 */
|
||||
.resize-edge { position: absolute; z-index: 4; touch-action: none; }
|
||||
.resize-edge-n, .resize-edge-s { left: 8px; right: 8px; height: 14px; cursor: ns-resize; }
|
||||
.resize-edge-e, .resize-edge-w { top: 8px; bottom: 8px; width: 14px; cursor: ew-resize; }
|
||||
.resize-edge-n { top: -7px; }
|
||||
.resize-edge-s { bottom: -7px; }
|
||||
.resize-edge-e { right: -7px; }
|
||||
.resize-edge-w { left: -7px; }
|
||||
.resize-handle { position: absolute; z-index: 5; box-sizing: border-box; width: 12px; height: 12px; border: 2px solid white; border-radius: 2px; background: #0ea5e9; box-shadow: 0 1px 2px rgb(15 23 42 / .55); padding: 0; touch-action: none; cursor: pointer; }
|
||||
.handle-n, .handle-s { left: 50%; margin-left: -6px; cursor: ns-resize; }
|
||||
.handle-e, .handle-w { top: 50%; margin-top: -6px; cursor: ew-resize; }
|
||||
.handle-nw, .handle-se { cursor: nwse-resize; }
|
||||
.handle-ne, .handle-sw { cursor: nesw-resize; }
|
||||
.handle-n, .handle-nw, .handle-ne { top: -6px; }
|
||||
.handle-s, .handle-sw, .handle-se { bottom: -6px; }
|
||||
.handle-e, .handle-ne, .handle-se { right: -6px; }
|
||||
.handle-w, .handle-nw, .handle-sw { left: -6px; }
|
||||
.handle-n, .handle-nw, .handle-ne { top: -7px; }
|
||||
.handle-s, .handle-sw, .handle-se { bottom: -7px; }
|
||||
.handle-e, .handle-ne, .handle-se { right: -7px; }
|
||||
.handle-w, .handle-nw, .handle-sw { left: -7px; }
|
||||
.region-header_field { z-index: 2; border: 1.5px solid #f59e0b; background: rgb(245 158 11 / .08); }
|
||||
.region-header_field .region-label, .region-header_field .resize-handle { background: #b45309; }
|
||||
.region-order_field { z-index: 2; border: 1.5px solid #22c55e; background: rgb(34 197 94 / .08); }
|
||||
@@ -652,7 +725,6 @@ onBeforeUnmount(() => {
|
||||
.region.selected:not(.region-line) { z-index: 4; }
|
||||
.region-preview { z-index: 5; border-style: dashed; border-width: 2px; border-color: #fbbf24; background: rgb(245 158 11 / .18); color: #fef3c7; cursor: default; pointer-events: auto; }
|
||||
.region-preview .region-label { background: #a16207; }
|
||||
.canvas-stage.drawing .region { pointer-events: none; }
|
||||
@media (max-width: 900px) {
|
||||
.canvas-shell { height: auto; min-height: 36rem; }
|
||||
.canvas-toolbar { grid-template-columns: 1fr auto; }
|
||||
|
||||
+7
-1
@@ -763,7 +763,13 @@ export const selectCurrentDatasetsValidationEvidence = (
|
||||
lines: value.lines,
|
||||
cross_checks: value.cross_checks && typeof value.cross_checks === 'object' && !Array.isArray(value.cross_checks)
|
||||
? value.cross_checks : {},
|
||||
} as OrderProfileValidationEvidence;
|
||||
...(typeof value.reservation_region_status === 'string'
|
||||
? { reservation_region_status: value.reservation_region_status }
|
||||
: {}),
|
||||
...(Array.isArray(value.reservation_region_review_reasons)
|
||||
? { reservation_region_review_reasons: value.reservation_region_review_reasons.map((item) => String(item)) }
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -577,6 +577,9 @@ export interface OrderProfileValidationEvidence {
|
||||
header_fields: OrderProfileValidationEvidenceField[];
|
||||
lines: OrderProfileValidationEvidenceLine[];
|
||||
cross_checks: Record<string, unknown>;
|
||||
/** Vendor Comments 专区与正式解析共用;仅 needs_review 时出现。 */
|
||||
reservation_region_status?: string;
|
||||
reservation_region_review_reasons?: string[];
|
||||
}
|
||||
|
||||
/** 绑定精确草稿 checksum 的不可变验证运行摘要。 */
|
||||
@@ -936,6 +939,8 @@ export interface OrderProfileBlindTestCandidate {
|
||||
layout_version_id: number | null; layout_payload_checksum: string | null;
|
||||
layout_parser_key: string | null; layout_parser_version: string | null;
|
||||
order_fields: Array<{ field_id: string; field_code: string; scope: 'header'; value: unknown; status: 'confirmed' | 'needs_review' | 'unavailable'; page_no: number | null; issues: string[] }>;
|
||||
reservation_region_status?: string;
|
||||
reservation_region_review_reasons?: string[];
|
||||
}
|
||||
|
||||
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
|
||||
|
||||
@@ -1068,29 +1068,54 @@ describe('useShippingOrderReview build eligibility writes', () => {
|
||||
build_eligibility: { can_build: true, status: 'ready', line_projections: [] },
|
||||
},
|
||||
});
|
||||
api.getCase.mockResolvedValue(readyCase);
|
||||
const confirmedCase = {
|
||||
...readyCase,
|
||||
status: 'confirmed',
|
||||
confirmed_task_no: 'OT-1',
|
||||
order_task_no: 'OT-1',
|
||||
has_formal_ot: true,
|
||||
};
|
||||
api.getCase.mockResolvedValue(confirmedCase);
|
||||
api.getRun.mockResolvedValue({
|
||||
run_no: 'RUN-1', summary: {},
|
||||
items: [{ case_no: 'CASE-1', document_id: 1, status: 'ready', available_actions: ['confirm'] }],
|
||||
});
|
||||
api.getQueue.mockResolvedValue({
|
||||
summary: { total: 1, needs_action: 1, processing: 0, completed: 0 },
|
||||
items: [{
|
||||
case_no: 'CASE-1', document_id: 1, source_run_no: 'RUN-1', status: 'confirmed',
|
||||
lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
}],
|
||||
});
|
||||
api.getEvidence.mockResolvedValue({ items: [] });
|
||||
api.getPreview.mockResolvedValue({ preview_url: '' });
|
||||
api.getProcessingWorkItem.mockResolvedValue({
|
||||
work_item_no: 'OT-1', status: 'blocked', user_status: 'waiting_human',
|
||||
workItemNo: 'OT-1',
|
||||
status: 'waiting_human',
|
||||
userStatus: 'waiting_human',
|
||||
stage: 'inventory_matching',
|
||||
currentGate: { gateCode: 'inventory_matching', status: 'blocked_manual' },
|
||||
uiState: {
|
||||
status: 'waiting_human',
|
||||
lifecycleStage: 'fulfillment_prep',
|
||||
lifecycleEntries: [{ code: 'fulfillment_prep', state: 'current' }],
|
||||
},
|
||||
});
|
||||
api.confirmCase.mockResolvedValue({
|
||||
task_no: 'SN-1', order_task_no: 'OT-1', shipping_notice_no: 'SN-1', idempotent_replay: false,
|
||||
case: { ...readyCase, status: 'confirmed', order_task_no: 'OT-1' }, auto_progress_started: true,
|
||||
case: confirmedCase, auto_progress_started: true,
|
||||
});
|
||||
|
||||
const review = useShippingOrderReview();
|
||||
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
|
||||
const queueCallsBeforeConfirm = api.getQueue.mock.calls.length;
|
||||
await review.confirm();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
|
||||
await Promise.resolve();
|
||||
// 中断(waiting_human,即“等待人工处理”)视为线性终态:结果不会自行变化,必须停止轮询。
|
||||
// 中断(waiting_human)停轮询前须刷新 Case/Queue,否则自动跳阶段拿不到 lifecycle。
|
||||
expect(api.getQueue.mock.calls.length).toBeGreaterThan(queueCallsBeforeConfirm);
|
||||
expect(review.workflowProgressPolling.value).toBe(false);
|
||||
|
||||
review.stopWorkflowProgressPolling();
|
||||
|
||||
@@ -621,9 +621,12 @@ export function useShippingOrderReview(options: {
|
||||
};
|
||||
|
||||
/**
|
||||
* 轮询正式 OT / Extraction Run 的处理投影,驱动工作流进度与阶段条。
|
||||
*
|
||||
* OT ShippingProcessing Extraction Run
|
||||
* WorkflowItem OT Run
|
||||
* 核心逻辑:有权威 OT 时刷 shipping processing;投影进入 waiting_human/failed 等
|
||||
* 终态前先 await refreshActiveAutomationLifecycle,保证五阶段条能跟随跳转后再停轮询。
|
||||
*
|
||||
* @param itemNo - 可选工作流/OT 编号覆盖
|
||||
*/
|
||||
const startWorkflowProgressPolling = (itemNo?: string | null) => {
|
||||
stopWorkflowProgressPolling();
|
||||
@@ -658,12 +661,8 @@ export function useShippingOrderReview(options: {
|
||||
lastUnifiedStatus = unifiedStatus;
|
||||
options.onWorkflowRefresh?.();
|
||||
}
|
||||
if (UNIFIED_TERMINAL.has(unifiedStatus)) {
|
||||
stopWorkflowProgressPolling();
|
||||
return;
|
||||
}
|
||||
// 顶部五阶段取 Case/Queue 的 lifecycle_entries。仅当 OT 投影的阶段/门禁发生变化
|
||||
// 时刷新一次,避免每 2.5 秒重复读取队列;不等待该读取,保证终态轮询及时停止。
|
||||
// 时刷新一次,避免每 2.5 秒重复读取队列。
|
||||
const lifecycleFingerprint = [
|
||||
unifiedStatus,
|
||||
String(shippingProcessingProjection.value?.stage || ''),
|
||||
@@ -672,7 +671,13 @@ export function useShippingOrderReview(options: {
|
||||
].join('|');
|
||||
if (lifecycleFingerprint !== lastLifecycleFingerprint) {
|
||||
lastLifecycleFingerprint = lifecycleFingerprint;
|
||||
void refreshActiveAutomationLifecycle();
|
||||
// [STEP] waiting_human/failed 也会停轮询,但停前必须落地一次阶段投影,
|
||||
// 否则提交订单后秒级阻断时五阶段条卡在订单复核、自动跳转永不触发。
|
||||
await refreshActiveAutomationLifecycle();
|
||||
}
|
||||
if (UNIFIED_TERMINAL.has(unifiedStatus)) {
|
||||
stopWorkflowProgressPolling();
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1999,6 +1999,47 @@ describe('ShippingOrderReviewView layout phase 1', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('follows the backend stage advance when the route has no lifecycle_stage deep link', async () => {
|
||||
// 无 lifecycle_stage = 尚未钉工作面,应跟随系统 current,不能因空深链永久停在订单复核。
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0],
|
||||
lifecycle_stage: 'order_review',
|
||||
lifecycle_entries: [
|
||||
{ code: 'order_review', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'unavailable', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
}],
|
||||
};
|
||||
const wrapper = await mountView({});
|
||||
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
|
||||
.toBeUndefined();
|
||||
|
||||
reviewQueue.value = {
|
||||
...reviewQueue.value,
|
||||
items: [{
|
||||
...reviewQueue.value.items[0],
|
||||
lifecycle_stage: 'fulfillment_prep',
|
||||
lifecycle_entries: [
|
||||
{ code: 'order_review', state: 'available', targetSurface: 'order_lifecycle_workbench' },
|
||||
{ code: 'fulfillment_prep', state: 'current', targetSurface: 'order_lifecycle_workbench' },
|
||||
],
|
||||
}],
|
||||
};
|
||||
await nextTick();
|
||||
await flushPromises();
|
||||
|
||||
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
|
||||
.toBe('fulfillment_prep');
|
||||
expect(messageMocks.success).toHaveBeenCalledWith('已自动推进到通知准备');
|
||||
} finally {
|
||||
reviewQueue.value = originalQueue;
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps a manually revisited earlier lifecycle stage when the backend advances', async () => {
|
||||
const originalQueue = reviewQueue.value;
|
||||
try {
|
||||
|
||||
@@ -4451,8 +4451,10 @@ watch(
|
||||
) return;
|
||||
// 只响应后端 current 阶段的真实推进:用户点击已完成阶段只会改路由,
|
||||
// 绝不能触发自动跳转而被带回当前阶段。
|
||||
// 无 lifecycle_stage 深链 = 尚未钉工作面,视为仍跟随系统(与「仍停在旧 current」同权)。
|
||||
const requested = String(route.query.lifecycle_stage || '').trim();
|
||||
if (requested !== previousStage) return;
|
||||
const followingSystem = !requested || requested === previousStage;
|
||||
if (!followingSystem) return;
|
||||
if (lifecycleStagePinnedByUserForCase.value === String(activeCase.value?.case_no || '').trim()) return;
|
||||
const previousIndex = LIFECYCLE_STAGE_CODES.indexOf(previousStage);
|
||||
const currentIndex = LIFECYCLE_STAGE_CODES.indexOf(currentStage);
|
||||
|
||||
@@ -2859,6 +2859,8 @@
|
||||
"noHeaderResults": "No order header fields were read from the current sample.",
|
||||
"noLineResults": "No order lines were read from the current sample.",
|
||||
"noValue": "No value read",
|
||||
"reservationRegionTitle": "Reservation ID region",
|
||||
"reservationRegionNeedsReview": "Reservation region needs review: {reasons}",
|
||||
"rowStatus": "Status",
|
||||
"deleted": "Deleted; excluded",
|
||||
"read": "Read",
|
||||
@@ -2961,9 +2963,9 @@
|
||||
"signatureRequired": "A valid layout signature is required before publication.",
|
||||
"signatureStale": "The layout signature is stale. Regenerate it before publishing.",
|
||||
"overlapRequired": "Cross-template overlap validation is required before publication.",
|
||||
"overlapStale": "Cross-template overlap validation is stale. Re-run the publish check.",
|
||||
"overlapFailed": "Cross-template overlap validation failed.",
|
||||
"selfMatchNotUnique": "Training samples do not uniquely match the current draft.",
|
||||
"overlapStale": "Cross-template overlap validation is stale because the draft changed. Re-run the publish check.",
|
||||
"overlapFailed": "Cross-template overlap validation did not pass. Fix the blocking items before publishing.",
|
||||
"selfMatchNotUnique": "Training/annotation samples do not uniquely match the current draft. Check that required document-match anchor labels can be fully read from the sample (including punctuation).",
|
||||
"selfMatchNotUniqueBlind": "Blind-test samples do not uniquely match the current draft.",
|
||||
"crossTemplateFalseHit": "Cross-template false hits were detected.",
|
||||
"crossTemplateAmbiguous": "Cross-template matching is ambiguous.",
|
||||
@@ -3490,6 +3492,7 @@
|
||||
"sampleMaterializationFailed": "Could not create the sample document. Upload again or choose an existing sample.",
|
||||
"noIndependentSamples": "No independent sample is available. Upload another matching order first.",
|
||||
"reviewHint": "Mark every item correct or incorrect. Provide a correction for incorrect items; unreviewed items cannot be added.",
|
||||
"reservationRegionNeedsReview": "Reservation ID region needs review: {reasons}",
|
||||
"xfaReviewHint": "XFA blind tests review structure-analysis extraction results without a blank PDF; truths are not echoed in ordinary DTOs.",
|
||||
"row": "Line {index}",
|
||||
"correct": "Correct",
|
||||
@@ -3770,7 +3773,7 @@
|
||||
"schemaField": "Schema field",
|
||||
"lineLayout": "Physical line",
|
||||
"selectField": "Select field",
|
||||
"dragHint": "Drag the selected region or its lower-right edge; numeric coordinates stay hidden.",
|
||||
"dragHint": "Drag the selected region to move it, or drag any edge/corner to resize; numeric coordinates stay hidden.",
|
||||
"deleteRegion": "Delete region",
|
||||
"deleteRegionShortcut": "Delete region (Delete)",
|
||||
"chooseRegion": "Choose a region or add one to begin annotation.",
|
||||
|
||||
@@ -435,6 +435,7 @@
|
||||
},
|
||||
"shippingOrderExtractionEmailSupplementRelation": {
|
||||
"po_mpn": "Relation: PO + part number",
|
||||
"po_reservation": "Relation: PO + reservation ID",
|
||||
"po_fallback": "Relation: matched by PO",
|
||||
"unknown": "Relation pending confirmation"
|
||||
},
|
||||
|
||||
@@ -2728,6 +2728,8 @@
|
||||
"noHeaderResults": "ไม่พบฟิลด์ส่วนหัวจากตัวอย่างปัจจุบัน",
|
||||
"noLineResults": "ไม่พบรายการจากตัวอย่างปัจจุบัน",
|
||||
"noValue": "ไม่พบค่า",
|
||||
"reservationRegionTitle": "พื้นที่ Reservation ID",
|
||||
"reservationRegionNeedsReview": "พื้นที่ Reservation ต้องตรวจสอบ: {reasons}",
|
||||
"rowStatus": "สถานะ",
|
||||
"deleted": "ลบแล้ว ไม่นับผล",
|
||||
"read": "อ่านแล้ว",
|
||||
@@ -2830,9 +2832,9 @@
|
||||
"signatureRequired": "ต้องมีลายเซ็นเลย์เอาต์ที่ถูกต้องก่อนเผยแพร่",
|
||||
"signatureStale": "ลายเซ็นเลย์เอาต์หมดอายุแล้ว โปรดสร้างใหม่ก่อนเผยแพร่",
|
||||
"overlapRequired": "ต้องตรวจความไม่ซ้ำข้ามเทมเพลตก่อนเผยแพร่",
|
||||
"overlapStale": "การตรวจความไม่ซ้ำข้ามเทมเพลตหมดอายุแล้ว โปรดตรวจสอบการเผยแพร่อีกครั้ง",
|
||||
"overlapFailed": "การตรวจความไม่ซ้ำข้ามเทมเพลตล้มเหลว",
|
||||
"selfMatchNotUnique": "ตัวอย่างฝึกไม่ได้จับคู่กับฉบับร่างปัจจุบันอย่างไม่ซ้ำ",
|
||||
"overlapStale": "การตรวจความไม่ซ้ำข้ามเทมเพลตหมดอายุแล้ว (ฉบับร่างมีการเปลี่ยนแปลง) โปรดตรวจสอบการเผยแพร่อีกครั้ง",
|
||||
"overlapFailed": "การตรวจความไม่ซ้ำข้ามเทมเพลตไม่ผ่าน โปรดแก้รายการที่บล็อกก่อนเผยแพร่",
|
||||
"selfMatchNotUnique": "ตัวอย่างฝึก/กำกับไม่ได้จับคู่กับฉบับร่างปัจจุบันอย่างไม่ซ้ำ โปรดตรวจว่าป้ายจุดยึดจับคู่เอกสารที่จำเป็นอ่านจากตัวอย่างได้ครบ (รวมเครื่องหมายวรรคตอน)",
|
||||
"selfMatchNotUniqueBlind": "ตัวอย่าง blind test ไม่ได้จับคู่กับฉบับร่างปัจจุบันอย่างไม่ซ้ำ",
|
||||
"crossTemplateFalseHit": "ตรวจพบการจับคู่ผิดข้ามเทมเพลต",
|
||||
"crossTemplateAmbiguous": "การจับคู่ข้ามเทมเพลตกำกวม",
|
||||
@@ -3359,6 +3361,7 @@
|
||||
"sampleMaterializationFailed": "สร้างเอกสารตัวอย่างไม่สำเร็จ โปรดอัปโหลดใหม่หรือเลือกตัวอย่างเดิม",
|
||||
"noIndependentSamples": "ไม่มีตัวอย่างอิสระ โปรดอัปโหลดคำสั่งซื้อประเภทเดียวกันอีกฉบับก่อน",
|
||||
"reviewHint": "ทำเครื่องหมายแต่ละรายการว่าถูกต้องหรือผิดพลาด หากผิดพลาดต้องระบุค่าที่แก้ไข รายการที่ยังไม่ตรวจทานจะเพิ่มไม่ได้",
|
||||
"reservationRegionNeedsReview": "พื้นที่ Reservation ID ต้องตรวจสอบ: {reasons}",
|
||||
"xfaReviewHint": "การทดสอบแบบปิดบังของ XFA ตรวจทานผลจากการวิเคราะห์โครงสร้างโดยไม่ใช้ PDF ว่าง และไม่ส่งค่าจริงกลับใน DTO ทั่วไป",
|
||||
"row": "รายการ {index}",
|
||||
"correct": "ถูกต้อง",
|
||||
@@ -3639,7 +3642,7 @@
|
||||
"schemaField": "ฟิลด์ Schema",
|
||||
"lineLayout": "แถวจริงที่สังกัด",
|
||||
"selectField": "เลือกฟิลด์",
|
||||
"dragHint": "ลากพื้นที่ที่เลือกหรือขอบล่างขวาเพื่อกำหนดตำแหน่ง โดยซ่อนตัวเลขพิกัดไว้",
|
||||
"dragHint": "ลากพื้นที่ที่เลือกเพื่อย้าย หรือลากขอบ/มุมเพื่อปรับขนาด โดยซ่อนตัวเลขพิกัดไว้",
|
||||
"deleteRegion": "ลบพื้นที่",
|
||||
"deleteRegionShortcut": "ลบพื้นที่ (Delete)",
|
||||
"chooseRegion": "เลือกหรือเพิ่มพื้นที่เพื่อเริ่มทำคำอธิบายประกอบ",
|
||||
|
||||
@@ -435,6 +435,7 @@
|
||||
},
|
||||
"shippingOrderExtractionEmailSupplementRelation": {
|
||||
"po_mpn": "วิธีเชื่อมโยง: PO + หมายเลขชิ้นส่วน",
|
||||
"po_reservation": "วิธีเชื่อมโยง: PO + รหัสการจอง",
|
||||
"po_fallback": "วิธีเชื่อมโยง: จับคู่ด้วย PO",
|
||||
"unknown": "รอยืนยันวิธีเชื่อมโยง"
|
||||
},
|
||||
|
||||
@@ -2971,6 +2971,8 @@
|
||||
"noHeaderResults": "当前样本未读取到订单表头字段。",
|
||||
"noLineResults": "当前样本未读取到订单明细。",
|
||||
"noValue": "未读取到值",
|
||||
"reservationRegionTitle": "Reservation ID 专区",
|
||||
"reservationRegionNeedsReview": "专区需复核:{reasons}",
|
||||
"rowStatus": "状态",
|
||||
"deleted": "已删除,不纳入结果",
|
||||
"read": "已读取",
|
||||
@@ -3073,9 +3075,9 @@
|
||||
"signatureRequired": "发布前必须生成有效的版面签名。",
|
||||
"signatureStale": "版面签名已过期,请重新生成后再发布。",
|
||||
"overlapRequired": "发布前必须完成跨模板唯一性验证。",
|
||||
"overlapStale": "跨模板唯一性验证已过期,请重新执行发布检查。",
|
||||
"overlapFailed": "跨模板唯一性验证失败。",
|
||||
"selfMatchNotUnique": "训练样本未能唯一命中当前草稿。",
|
||||
"overlapStale": "跨模板唯一性验证已过期(草稿已变更),请重新执行发布检查。",
|
||||
"overlapFailed": "跨模板唯一性验证未通过,请根据阻断项修复后再发布。",
|
||||
"selfMatchNotUnique": "训练/标注样本未能唯一命中当前草稿。请检查必选文档匹配锚点的标签能否在样本中完整读出(含标点)。",
|
||||
"selfMatchNotUniqueBlind": "盲测样本未能唯一命中当前草稿。",
|
||||
"crossTemplateFalseHit": "检测到跨模板误命中。",
|
||||
"crossTemplateAmbiguous": "跨模板匹配存在歧义。",
|
||||
@@ -3602,6 +3604,7 @@
|
||||
"sampleMaterializationFailed": "样本文档建立失败,请重新上传或选择已有样本。",
|
||||
"noIndependentSamples": "没有可用的独立样本;请先上传另一份同类订单。",
|
||||
"reviewHint": "请逐项勾选正确或错误;标为错误时填写更正值,未勾选不能加入盲测。",
|
||||
"reservationRegionNeedsReview": "Reservation ID 专区需复核:{reasons}",
|
||||
"xfaReviewHint": "XFA 盲测基于结构分析与路径提取结果复核,不读取空白 PDF;真值不会回显到普通 DTO。",
|
||||
"row": "明细 {index}",
|
||||
"correct": "正确",
|
||||
@@ -3882,7 +3885,7 @@
|
||||
"schemaField": "Schema 字段",
|
||||
"lineLayout": "所属物理行",
|
||||
"selectField": "选择字段",
|
||||
"dragHint": "在页面上拖动或拖右下角边界定位;刻意不显示坐标数字。",
|
||||
"dragHint": "在页面上拖动选区,或拖四边/角点调整宽高;刻意不显示坐标数字。",
|
||||
"deleteRegion": "删除区域",
|
||||
"deleteRegionShortcut": "删除区域(Delete)",
|
||||
"chooseRegion": "选择一个区域或添加区域后开始标注。",
|
||||
|
||||
@@ -469,6 +469,7 @@
|
||||
},
|
||||
"shippingOrderExtractionEmailSupplementRelation": {
|
||||
"po_mpn": "关联方式:PO + 料号",
|
||||
"po_reservation": "关联方式:PO + 预约号",
|
||||
"po_fallback": "关联方式:按 PO 匹配",
|
||||
"unknown": "关联方式待确认"
|
||||
},
|
||||
|
||||
@@ -2733,6 +2733,8 @@
|
||||
"noHeaderResults": "目前樣本未讀取到訂單表頭欄位。",
|
||||
"noLineResults": "目前樣本未讀取到訂單明細。",
|
||||
"noValue": "未讀取到值",
|
||||
"reservationRegionTitle": "Reservation ID 專區",
|
||||
"reservationRegionNeedsReview": "專區需複核:{reasons}",
|
||||
"rowStatus": "狀態",
|
||||
"deleted": "已刪除,不納入結果",
|
||||
"read": "已讀取",
|
||||
@@ -2835,9 +2837,9 @@
|
||||
"signatureRequired": "發布前必須產生有效的版面簽名。",
|
||||
"signatureStale": "版面簽名已過期,請重新產生後再發布。",
|
||||
"overlapRequired": "發布前必須完成跨範本唯一性驗證。",
|
||||
"overlapStale": "跨範本唯一性驗證已過期,請重新執行發布檢查。",
|
||||
"overlapFailed": "跨範本唯一性驗證失敗。",
|
||||
"selfMatchNotUnique": "訓練樣本未能唯一命中目前草稿。",
|
||||
"overlapStale": "跨範本唯一性驗證已過期(草稿已變更),請重新執行發布檢查。",
|
||||
"overlapFailed": "跨範本唯一性驗證未通過,請依阻斷項修復後再發布。",
|
||||
"selfMatchNotUnique": "訓練/標註樣本未能唯一命中目前草稿。請檢查必選文件匹配錨點的標籤能否在樣本中完整讀出(含標點)。",
|
||||
"selfMatchNotUniqueBlind": "盲測樣本未能唯一命中目前草稿。",
|
||||
"crossTemplateFalseHit": "偵測到跨範本誤命中。",
|
||||
"crossTemplateAmbiguous": "跨範本匹配存在歧義。",
|
||||
@@ -3364,6 +3366,7 @@
|
||||
"sampleMaterializationFailed": "樣本文件建立失敗,請重新上傳或選擇既有樣本。",
|
||||
"noIndependentSamples": "沒有可用的獨立樣本;請先上傳另一份同類訂單。",
|
||||
"reviewHint": "請逐項勾選正確或錯誤;標示錯誤時填寫更正值,未勾選不能加入盲測。",
|
||||
"reservationRegionNeedsReview": "Reservation ID 專區需複核:{reasons}",
|
||||
"xfaReviewHint": "XFA 盲測依結構分析與路徑提取結果複核,不讀取空白 PDF;真值不會回顯到普通 DTO。",
|
||||
"row": "明細 {index}",
|
||||
"correct": "正確",
|
||||
@@ -3644,7 +3647,7 @@
|
||||
"schemaField": "Schema 欄位",
|
||||
"lineLayout": "所屬實體行",
|
||||
"selectField": "選擇欄位",
|
||||
"dragHint": "在頁面拖曳或拖右下角邊界定位;刻意不顯示座標數字。",
|
||||
"dragHint": "在頁面拖曳選區,或拖四邊/角點調整寬高;刻意不顯示座標數字。",
|
||||
"deleteRegion": "刪除區域",
|
||||
"deleteRegionShortcut": "刪除區域(Delete)",
|
||||
"chooseRegion": "選擇一個區域或新增區域後開始標註。",
|
||||
|
||||
@@ -435,6 +435,7 @@
|
||||
},
|
||||
"shippingOrderExtractionEmailSupplementRelation": {
|
||||
"po_mpn": "關聯方式:PO + 料號",
|
||||
"po_reservation": "關聯方式:PO + 預約號",
|
||||
"po_fallback": "關聯方式:依 PO 配對",
|
||||
"unknown": "關聯方式待確認"
|
||||
},
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
scripts/rpa/download_artifact_fallback.py
|
||||
|
||||
用途:在浏览器实际已落盘但 Playwright 未返回 Download 对象时,按下载目录中的新文件构造兼容适配器。
|
||||
用途:在浏览器实际已落盘但 Playwright Download 句柄不可用时,按下载目录中的新文件构造兼容适配器。
|
||||
依赖:pathlib、shutil、time。
|
||||
逻辑:由 DSV 导出链路在 `expect_download` 超时后调用;不改变站点交互,只补文件系统兜底。
|
||||
逻辑:DSV/Crane 在 expect_download 超时后调用;库存 worker 在 Download.save_as 因浏览器关闭失败时同样调用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -86,6 +86,9 @@ from dsv_report_export import NoInventoryDataError # noqa: E402
|
||||
import dsv_session # noqa: E402
|
||||
import rpa_heartbeat # noqa: E402
|
||||
import worker_disk_cleanup # noqa: E402
|
||||
from download_artifact_fallback import ( # noqa: E402
|
||||
wait_for_new_download_file as _wait_for_new_download_file,
|
||||
)
|
||||
|
||||
# 测试与 smoke 向后兼容 re-export
|
||||
_maybe_auto_login_dsv = dsv_session.maybe_auto_login_dsv
|
||||
@@ -693,11 +696,82 @@ def _validate_inventory_excel(path: Path) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _save_download(download: Any, drop_dir: Path, task_no: str, source_code: str) -> Path:
|
||||
def _download_dir_baseline_names(drop_dir: Path) -> set[str]:
|
||||
"""
|
||||
导出前拍摄下载目录已有文件名,供目录兜底识别“本次新文件”。
|
||||
核心逻辑:仅收集普通文件名;目录不可读时返回空集合。
|
||||
"""
|
||||
try:
|
||||
return {path.name for path in drop_dir.iterdir() if path.is_file()}
|
||||
except OSError:
|
||||
return set()
|
||||
|
||||
|
||||
def _is_playwright_target_closed_error(exc: BaseException) -> bool:
|
||||
"""
|
||||
判断是否为 Playwright 页面/上下文/浏览器已关闭导致的下载落盘失败。
|
||||
核心逻辑:匹配常见 TargetClosed 文案;用于决定是否启用 downloads_path 目录兜底。
|
||||
"""
|
||||
message = str(exc).lower()
|
||||
return "has been closed" in message or "target closed" in message or "targetclosed" in message
|
||||
|
||||
|
||||
def _persist_download_to_dest(
|
||||
download: Any,
|
||||
dest: Path,
|
||||
*,
|
||||
drop_dir: Path,
|
||||
baseline_names: set[str] | None = None,
|
||||
fallback_timeout_seconds: float = 60.0,
|
||||
) -> None:
|
||||
"""
|
||||
将 Playwright Download(或目录适配器)落到规范路径。
|
||||
核心逻辑:先 save_as;若浏览器已关闭则按 baseline 在 downloads_path 等待稳定新文件再搬迁。
|
||||
大报表场景下 expect_download 仅表示开始,收尾时 Chromium 偶发已死,目录才是完成条件。
|
||||
"""
|
||||
try:
|
||||
download.save_as(str(dest))
|
||||
return
|
||||
except Exception as exc:
|
||||
if not _is_playwright_target_closed_error(exc):
|
||||
raise
|
||||
print(
|
||||
"[inventory-artifact] stage=download_save status=fallback "
|
||||
f"reason=browser_closed path={dest.name!r}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
artifact = _wait_for_new_download_file(
|
||||
download_dir=drop_dir,
|
||||
baseline_names=set(baseline_names or ()),
|
||||
timeout_seconds=fallback_timeout_seconds,
|
||||
)
|
||||
if artifact is None:
|
||||
raise
|
||||
artifact.save_as(str(dest))
|
||||
|
||||
|
||||
def _save_download(
|
||||
download: Any,
|
||||
drop_dir: Path,
|
||||
task_no: str,
|
||||
source_code: str,
|
||||
*,
|
||||
baseline_names: set[str] | None = None,
|
||||
fallback_timeout_seconds: float = 60.0,
|
||||
) -> Path:
|
||||
"""
|
||||
单票库存下载落盘到 drop_dir,必要时在浏览器关闭后走目录兜底。
|
||||
"""
|
||||
suggested = str(download.suggested_filename or "")
|
||||
suffix = Path(suggested).suffix or ".xlsx"
|
||||
dest = drop_dir / _download_name(task_no, source_code, suffix=suffix)
|
||||
download.save_as(str(dest))
|
||||
_persist_download_to_dest(
|
||||
download,
|
||||
dest,
|
||||
drop_dir=drop_dir,
|
||||
baseline_names=baseline_names,
|
||||
fallback_timeout_seconds=fallback_timeout_seconds,
|
||||
)
|
||||
if suffix.lower() in {".xlsx", ".xlsm", ".xltx", ".xltm"}:
|
||||
_validate_inventory_excel(dest)
|
||||
return dest
|
||||
@@ -711,14 +785,31 @@ def _batch_download_name(run_no: str, source_code: str, warehouse_id: str, suffi
|
||||
return f"inventory_{safe_run}_{safe_source}_{safe_wh}_{stamp}{suffix}"
|
||||
|
||||
|
||||
def _save_batch_download(download: Any, drop_dir: Path, run_no: str, source: dict[str, Any]) -> Path:
|
||||
def _save_batch_download(
|
||||
download: Any,
|
||||
drop_dir: Path,
|
||||
run_no: str,
|
||||
source: dict[str, Any],
|
||||
*,
|
||||
baseline_names: set[str] | None = None,
|
||||
fallback_timeout_seconds: float = 60.0,
|
||||
) -> Path:
|
||||
"""
|
||||
批量库存下载落盘到 drop_dir;Playwright save_as 因浏览器关闭失败时按目录新文件兜底。
|
||||
"""
|
||||
suggested = str(download.suggested_filename or "")
|
||||
suffix = Path(suggested).suffix or ".xlsx"
|
||||
source_code = str(source.get("source_code") or "UNKNOWN")
|
||||
warehouse_id = str(source.get("warehouse_id") or "WH")
|
||||
dest = drop_dir / _batch_download_name(run_no, source_code, warehouse_id, suffix=suffix)
|
||||
save_started_at = time.monotonic()
|
||||
download.save_as(str(dest))
|
||||
_persist_download_to_dest(
|
||||
download,
|
||||
dest,
|
||||
drop_dir=drop_dir,
|
||||
baseline_names=baseline_names,
|
||||
fallback_timeout_seconds=fallback_timeout_seconds,
|
||||
)
|
||||
print(
|
||||
"[inventory-artifact] stage=download_save status=end "
|
||||
f"elapsedMs={int((time.monotonic() - save_started_at) * 1000)} path={dest.name!r}"
|
||||
@@ -1218,13 +1309,15 @@ def _download_inventory_with_browser(trigger: dict[str, Any], drop_dir: Path) ->
|
||||
profile_code=_source_rpa_profile_code(source),
|
||||
)
|
||||
with _profile_credentials(source):
|
||||
# [STEP] 导出前拍摄目录基线:save_as 若因浏览器关闭失败,可识别 downloads_path 新文件。
|
||||
baseline_names = _download_dir_baseline_names(drop_dir)
|
||||
if connector_type == "dsv360":
|
||||
download = _download_dsv360_inventory(page, trigger, source)
|
||||
elif connector_type == "crane_footprint":
|
||||
download = _download_crane_inventory(page, trigger, source)
|
||||
else:
|
||||
raise RuntimeError(f"unsupported inventory connector_type: {connector_type}")
|
||||
return _save_download(download, drop_dir, task_no, source_code)
|
||||
return _save_download(download, drop_dir, task_no, source_code, baseline_names=baseline_names)
|
||||
except Exception:
|
||||
failed = True
|
||||
raise
|
||||
@@ -1583,8 +1676,16 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
|
||||
_ensure_crane_session(page, entry_url)
|
||||
else:
|
||||
_reset_crane_export_entry(page, entry_url)
|
||||
# [STEP] 导出点击前拍摄目录基线,供 save_as 浏览器关闭时的目录兜底。
|
||||
baseline_names = _download_dir_baseline_names(drop_dir)
|
||||
download = export_fn(page, body, source, skip_navigation=skip_navigation) if site == "dsv360" else export_fn(page, body, source)
|
||||
out_file = _save_batch_download(download, drop_dir, run_no, source)
|
||||
out_file = _save_batch_download(
|
||||
download,
|
||||
drop_dir,
|
||||
run_no,
|
||||
source,
|
||||
baseline_names=baseline_names,
|
||||
)
|
||||
record_result({"source_code": code, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or source.get("task_no") or None, "validation_run_no": source.get("validation_run_no"), **{k: source.get(k) for k in ("attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")}})
|
||||
print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}")
|
||||
except NoInventoryDataError as exc:
|
||||
|
||||
Reference in new issue
Block a user