Merge branch 'dev' into snow
# Conflicts: # frontend/package-lock.json
This commit is contained in:
commit
590a21515a
81 files changed
+7045
-1079
No files matched your search
@@ -811,9 +811,19 @@ def approve_order_document_profile_test_suite(suite_id: int):
|
||||
)
|
||||
@require_admin
|
||||
def get_order_document_profile_sample_value_field_tree(document_id: int):
|
||||
"""返回当前值源字段树安全投影;不含原始正文。"""
|
||||
"""
|
||||
返回当前值源字段树安全投影。
|
||||
|
||||
核心逻辑:默认脱敏展示;reveal=true 且具备 audit_sensitive_read 时,
|
||||
树节点 sample_value_display 写入完整样本值(仍不输出 raw_value 键),供映射台选型。
|
||||
"""
|
||||
reveal = str(request.args.get('reveal') or '').strip().lower() in {'1', 'true', 'yes'}
|
||||
if reveal:
|
||||
_require_audit_sensitive_read_permission()
|
||||
return _private_ok(_sample_mapping_adapter(document_id).mapping_field_tree(
|
||||
document_id=document_id, actor_id=_actor_id(),
|
||||
document_id=document_id,
|
||||
actor_id=_actor_id(),
|
||||
include_full_values=reveal,
|
||||
))
|
||||
|
||||
|
||||
@@ -922,7 +932,7 @@ def _require_value_mapping_edit_permission() -> None:
|
||||
)
|
||||
@require_admin
|
||||
def suggest_order_document_profile_value_split_rules(profile_id: int):
|
||||
"""生成 MATNR 类拆分规则建议;不写 Draft、不 commit。"""
|
||||
"""生成拆分规则建议(任意 datasets 源字段);不写 Draft、不 commit。"""
|
||||
_require_value_mapping_preview_permission()
|
||||
data = request.get_json(silent=True) or {}
|
||||
return _private_ok(suggestion_service.suggest_xfa_split_rules(
|
||||
|
||||
@@ -553,8 +553,10 @@ class Config:
|
||||
WECOM_NOTIFY_ENABLED = os.getenv('WECOM_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_NOTIFY_BASE_URL = os.getenv('WECOM_NOTIFY_BASE_URL')
|
||||
WECOM_NOTIFY_EVENTS = os.getenv('WECOM_NOTIFY_EVENTS', 'task_completed,schedule_completed,password_reset,contract_payment_warning,training_lean_overdue,training_lean_task_initial,training_lean_targeted_reminder')
|
||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>,默认 16)。
|
||||
WECOM_LEAN_TRAINING_JUMP_AGENT_ID = int(os.getenv('WECOM_LEAN_TRAINING_JUMP_AGENT_ID', '16'))
|
||||
# 精益培训企微提醒卡片跳转的员工培训聊天页 agent id(前端路由 /chat/<id>,默认 27=员工培训)。
|
||||
# 注意:默认值必须指向 content_profile=training 的培训 agent;历史默认 16 实为「通用入口」,
|
||||
# 会导致卡片落地非培训 agent、前端精益页签深链不消费([FIX] 2026-09-11)。
|
||||
WECOM_LEAN_TRAINING_JUMP_AGENT_ID = int(os.getenv('WECOM_LEAN_TRAINING_JUMP_AGENT_ID', '27'))
|
||||
WECOM_FEEDBACK_NOTIFY_ENABLED = os.getenv('WECOM_FEEDBACK_NOTIFY_ENABLED', 'true').lower() == 'true'
|
||||
WECOM_FEEDBACK_NOTIFY_BASE_URL = os.getenv('WECOM_FEEDBACK_NOTIFY_BASE_URL')
|
||||
WECOM_FEEDBACK_BOT_WEBHOOK = os.getenv('WECOM_FEEDBACK_BOT_WEBHOOK')
|
||||
|
||||
@@ -7,6 +7,7 @@ backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
order_supplement_merge(仅 eml)、order_extraction_ready_document_ids(Unit 级放行)。
|
||||
逻辑:物化附件与排版面 Job 均在主 try 内执行;有 ready PDF 即按 Unit 抽取并下游推进,
|
||||
兄弟文件 layout pending 时 Job 以 partial_units_done 回到 waiting_layout;
|
||||
运行时预算耗尽且仍有 pending Unit 时入队续抽,禁止终态 partially_completed;
|
||||
每个 Unit 按 STP route_decision 直通或落 provisional;needs_review 剥离验收标记;
|
||||
不调用 Dify 主链。阶段 2:direct_pdf 跳过 email_supplements 与 ORDER_EMAIL_ADJUDICATION_*;
|
||||
合并默认 keep_primary_documents_separate(多 PDF 各成 Candidate)。
|
||||
@@ -41,6 +42,7 @@ from app.services.shipping_notice.audit_service import append_shipping_audit_eve
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
_enqueue_ready_order_extraction_job,
|
||||
begin_input_freeze,
|
||||
complete_input_freeze,
|
||||
mark_order_extraction_persistence_started,
|
||||
@@ -50,6 +52,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
materialize_order_extraction_run_inputs,
|
||||
ensure_workflow_items_for_run,
|
||||
progress_ready_extraction_unit,
|
||||
revive_layout_prerequisite_failed_units,
|
||||
schedule_order_extraction_layouts,
|
||||
synchronize_order_extraction_expansion_snapshot,
|
||||
transition_order_extraction_run,
|
||||
@@ -774,6 +777,8 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
if code == 'layout_pending'
|
||||
}
|
||||
ready_document_ids = order_extraction_ready_document_ids(run)
|
||||
# 版面已就绪时复活此前因 layout 前置失败的 Unit,避免永久 failed。
|
||||
revive_layout_prerequisite_failed_units(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
|
||||
@@ -1170,6 +1175,50 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
# [STEP] 运行时预算耗尽且仍有 pending Unit:保留已抽成果,入队续抽,禁止终态 partially_completed。
|
||||
units = ShippingOrderProcessingUnit.query.filter_by(plan_id=plan.id).order_by(
|
||||
ShippingOrderProcessingUnit.position.asc(),
|
||||
).all()
|
||||
pending_left = any(str(unit.status or '') == 'pending' for unit in units)
|
||||
if runtime_budget_stopped and pending_left:
|
||||
record_run_progress(
|
||||
run=run,
|
||||
event_code='budget_stopped',
|
||||
reason_code='budget_runtime_limit',
|
||||
summary={
|
||||
**_selection_progress_summary(run),
|
||||
'max_runtime_seconds': max_runtime_seconds,
|
||||
'pending_unit_count': sum(
|
||||
1 for unit in units if str(unit.status or '') == 'pending'
|
||||
),
|
||||
'merged_unit_count': len(pending_merge_unit_ids),
|
||||
},
|
||||
job_id=job.id,
|
||||
commit=False,
|
||||
)
|
||||
continue_job_id = _enqueue_ready_order_extraction_job(
|
||||
run, message='运行时预算已用尽,继续识别剩余附件',
|
||||
)
|
||||
run.current_job_id = continue_job_id
|
||||
run.phase = 'waiting_layout'
|
||||
db.session.commit()
|
||||
finish_job(
|
||||
job.id,
|
||||
result={
|
||||
'run_no': run.run_no,
|
||||
'budget_stopped': True,
|
||||
'waiting_continue': True,
|
||||
'handoff_status': 'runtime_budget_continue',
|
||||
'merged_unit_count': len(pending_merge_unit_ids),
|
||||
'pending_unit_count': sum(
|
||||
1 for unit in units if str(unit.status or '') == 'pending'
|
||||
),
|
||||
'continue_job_id': int(continue_job_id),
|
||||
},
|
||||
message='运行时预算已用尽,已排队继续识别剩余附件',
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
return
|
||||
orders = persisted_orders + merged_orders
|
||||
execution = {
|
||||
'mode': 'deterministic',
|
||||
|
||||
@@ -52,9 +52,10 @@ def _send_reminder(
|
||||
db.session.flush()
|
||||
except IntegrityError:
|
||||
return "skipped"
|
||||
# [STEP] 企微卡片跳转地址:指向员工培训聊天页(agent 16),由前端消费 training_type=lean_management
|
||||
# 自动展开精益页签;agent id 走配置,便于多环境调整,避免硬编码。
|
||||
jump_agent_id = int(current_app.config.get("WECOM_LEAN_TRAINING_JUMP_AGENT_ID") or 16)
|
||||
# [STEP] 企微卡片跳转地址:指向员工培训聊天页(默认 agent 27,content_profile=training),
|
||||
# 由前端 TrainingWorkspacePanel 消费 training_type=lean_management 自动展开精益页签;
|
||||
# agent id 走配置(app_settings/env 覆盖),便于多环境调整,避免硬编码。
|
||||
jump_agent_id = int(current_app.config.get("WECOM_LEAN_TRAINING_JUMP_AGENT_ID") or 27)
|
||||
result = send_wecom_event_message(
|
||||
event_type=event_type,
|
||||
user=recipient,
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/document_layout/field_split_core.py
|
||||
|
||||
用途:共享的声明式字段拆分核心——承接 XFA(XML Forms Architecture)拆分引擎的纯文本执行能力,
|
||||
为 Vendor Comments / Coordinate Region 等非 XFA 数据源提供统一的 prefix / regex / position
|
||||
匹配、优先级仲裁、多规则冲突诊断、mapped/evidence_only 处理与规则内容指纹。
|
||||
匹配(position 支持连续多行合并)、优先级仲裁、多规则冲突诊断、mapped/evidence_only 处理与规则内容指纹。
|
||||
依赖:Pydantic 2、xfa_contract(复用 XfaContractModel 作为 Base Model 保持一致性)、
|
||||
xfa_safe_regex(危险正则黑名单、超时限制、最大捕获组校验)。
|
||||
逻辑:对外暴露 BaseSplit* 契约与 execute_base_split_rule_set() 执行入口;
|
||||
@@ -55,6 +55,7 @@ SPLIT_UNMATCHED_PRIORITY: Final[int] = 3
|
||||
|
||||
SplitHandling = Literal['mapped', 'evidence_only']
|
||||
SplitMatcherType = Literal['position', 'prefix', 'regex']
|
||||
SplitJoinWith = Literal['newline', 'space', 'comma']
|
||||
SplitSourceScope = Literal['header', 'line']
|
||||
SplitUnmatchedPolicy = Literal['evidence_only', 'needs_review']
|
||||
SplitDuplicatePolicy = Literal['needs_review']
|
||||
@@ -63,6 +64,12 @@ SplitRuleSource = Literal['system_suggestion', 'user', 'imported']
|
||||
RelationCaptureType = Literal['line_reference']
|
||||
RelationPolicyType = Literal['bind_target_line', 'annotation_only']
|
||||
|
||||
_JOIN_WITH_SEPARATORS: Final[dict[str, str]] = {
|
||||
'newline': '\n',
|
||||
'space': ' ',
|
||||
'comma': ', ',
|
||||
}
|
||||
|
||||
_SEGMENT_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
|
||||
|
||||
|
||||
@@ -190,15 +197,18 @@ class BaseSplitSegment(XfaContractModel):
|
||||
|
||||
class BaseSplitMatcher(XfaContractModel):
|
||||
"""
|
||||
共享单行匹配器:position / prefix / regex。
|
||||
共享匹配器:position(可连续多行)/ prefix / regex。
|
||||
优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。
|
||||
|
||||
position 可通过 line_end(含)与 join_with 合并连续多行;缺省时仍为单行。
|
||||
新增 relation_capture:当前仅 line_reference(Q2);XFA 链路当前不启用,
|
||||
但 Base 契约提前引入避免阶段 2 再次改造。
|
||||
"""
|
||||
|
||||
type: SplitMatcherType
|
||||
line_index: int | None = Field(default=None, ge=1, le=1000)
|
||||
line_end: int | None = Field(default=None, ge=1, le=1000)
|
||||
join_with: SplitJoinWith | None = None
|
||||
value: str | None = Field(default=None, max_length=SPLIT_MAX_PREFIX_LENGTH)
|
||||
separators: list[str] = Field(default_factory=lambda: [':', ':'])
|
||||
case_sensitive: bool = False
|
||||
@@ -216,6 +226,19 @@ class BaseSplitMatcher(XfaContractModel):
|
||||
if self.type == 'position':
|
||||
if self.line_index is None:
|
||||
raise ValueError('position matcher requires line_index (1-based)')
|
||||
# 单行保持 line_end=None,避免历史确认指纹漂移;连续多行才写入 line_end。
|
||||
if self.line_end is not None:
|
||||
if int(self.line_end) < int(self.line_index):
|
||||
raise ValueError('position matcher line_end must be >= line_index')
|
||||
if int(self.line_end) == int(self.line_index):
|
||||
object.__setattr__(self, 'line_end', None)
|
||||
object.__setattr__(self, 'join_with', None)
|
||||
elif self.join_with is None:
|
||||
object.__setattr__(self, 'join_with', 'newline')
|
||||
elif self.join_with not in _JOIN_WITH_SEPARATORS:
|
||||
raise ValueError('position matcher join_with must be newline/space/comma')
|
||||
else:
|
||||
object.__setattr__(self, 'join_with', None)
|
||||
elif self.type == 'prefix':
|
||||
label = str(self.value or '').strip()
|
||||
if not label:
|
||||
@@ -356,6 +379,7 @@ def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any])
|
||||
核心逻辑:只冻结 matcher、normalization 与 relation_capture 定义;
|
||||
segment 的 Schema 映射字段(handling/target_field_*)不属于拆分逻辑本身,
|
||||
后续绑定或解绑目标字段不得取消已确认状态。
|
||||
单行 position 的空 line_end/join_with 不进入指纹,避免新增可选字段导致历史令牌失效。
|
||||
|
||||
Args:
|
||||
rule_set: 模型或 dict。
|
||||
@@ -374,7 +398,16 @@ def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any])
|
||||
payload.pop('rule_version', None)
|
||||
payload.pop('rule_id', None)
|
||||
for rule in payload.get('rules') or []:
|
||||
segment = rule.get('segment') if isinstance(rule, dict) else None
|
||||
if not isinstance(rule, dict):
|
||||
continue
|
||||
matcher = rule.get('matcher')
|
||||
if isinstance(matcher, dict):
|
||||
# [STEP] 单行 position 不序列化空连续行字段,保持与升级前指纹兼容。
|
||||
if matcher.get('line_end') in (None, matcher.get('line_index')):
|
||||
matcher.pop('line_end', None)
|
||||
if not matcher.get('join_with'):
|
||||
matcher.pop('join_with', None)
|
||||
segment = rule.get('segment')
|
||||
if not isinstance(segment, dict):
|
||||
continue
|
||||
segment.pop('handling', None)
|
||||
@@ -445,7 +478,7 @@ class _CoreSplitEngineResult:
|
||||
|
||||
@dataclass
|
||||
class _LineMatch:
|
||||
"""单行候选命中(共享核心版,含 relation 捕获)。"""
|
||||
"""单行/连续多行候选命中(共享核心版,含 relation 捕获)。"""
|
||||
|
||||
rule: BaseSplitRule
|
||||
matcher_type: str
|
||||
@@ -453,9 +486,43 @@ class _LineMatch:
|
||||
line_text: str
|
||||
normalized_text: str
|
||||
raw_line: str
|
||||
line_end_no: int | None = None
|
||||
claimed_line_nos: tuple[int, ...] = ()
|
||||
captured_relation: CoreCapturedRelation | None = None
|
||||
|
||||
|
||||
def position_line_span(matcher: BaseSplitMatcher) -> tuple[int, int]:
|
||||
"""
|
||||
解析 position matcher 的起止行(1-based,含两端)。
|
||||
|
||||
Args:
|
||||
matcher: position 匹配器。
|
||||
|
||||
Returns:
|
||||
(line_start, line_end)。
|
||||
"""
|
||||
start = int(matcher.line_index or 0)
|
||||
end = int(matcher.line_end or start or 0)
|
||||
if end < start:
|
||||
end = start
|
||||
return start, end
|
||||
|
||||
|
||||
def join_position_lines(lines: list[str], join_with: str | None) -> str:
|
||||
"""
|
||||
按 join_with 合并连续多行文本。
|
||||
|
||||
Args:
|
||||
lines: 已按行号切好的原文行。
|
||||
join_with: newline / space / comma;缺省按换行合并。
|
||||
|
||||
Returns:
|
||||
合并后的文本。
|
||||
"""
|
||||
separator = _JOIN_WITH_SEPARATORS.get(str(join_with or 'newline'), '\n')
|
||||
return separator.join(lines)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# [STEP 3] 纯文本执行函数——从 XFA 拆分引擎原封不动迁移,保持字节级一致
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -599,9 +666,17 @@ def _match_line(
|
||||
line_no: int,
|
||||
line: str,
|
||||
rule: BaseSplitRule,
|
||||
*,
|
||||
inventory: list[str] | None = None,
|
||||
) -> tuple[_LineMatch | None, str | None]:
|
||||
"""
|
||||
判断单条规则是否命中指定行(共享核心版,支持 relation 捕获)。
|
||||
判断单条规则是否命中指定行(共享核心版,支持 relation 捕获与连续多行 position)。
|
||||
|
||||
Args:
|
||||
line_no: 当前行号(1-based)。
|
||||
line: 当前行文本。
|
||||
rule: 待匹配规则。
|
||||
inventory: 完整行清单;position 连续多行时用于合并起止范围内的文本。
|
||||
|
||||
Returns:
|
||||
(match, error_code):命中时 error_code 为 None;未命中时 match 为 None。
|
||||
@@ -612,16 +687,27 @@ def _match_line(
|
||||
return None, 'unknown_matcher'
|
||||
|
||||
if matcher.type == 'position':
|
||||
if int(matcher.line_index or 0) != line_no:
|
||||
start, end = position_line_span(matcher)
|
||||
if int(start) != line_no:
|
||||
return None, None
|
||||
normalized = line.strip() if line else ''
|
||||
lines = list(inventory or [])
|
||||
if not lines:
|
||||
lines = [line]
|
||||
if end > len(lines):
|
||||
return None, 'position_line_range_out_of_bounds'
|
||||
span_lines = lines[start - 1:end]
|
||||
joined_raw = join_position_lines(span_lines, matcher.join_with) if end > start else line
|
||||
normalized = joined_raw.strip() if joined_raw else ''
|
||||
claimed = tuple(range(start, end + 1))
|
||||
return _LineMatch(
|
||||
rule=rule,
|
||||
matcher_type='position',
|
||||
priority=priority,
|
||||
line_text=line,
|
||||
line_text=joined_raw,
|
||||
normalized_text=normalized,
|
||||
raw_line=line,
|
||||
raw_line=joined_raw,
|
||||
line_end_no=end,
|
||||
claimed_line_nos=claimed,
|
||||
), None
|
||||
|
||||
if matcher.type == 'prefix':
|
||||
@@ -635,6 +721,8 @@ def _match_line(
|
||||
line_text=line,
|
||||
normalized_text=extracted,
|
||||
raw_line=line,
|
||||
line_end_no=line_no,
|
||||
claimed_line_nos=(line_no,),
|
||||
), None
|
||||
|
||||
if matcher.type == 'regex':
|
||||
@@ -650,6 +738,8 @@ def _match_line(
|
||||
line_text=line,
|
||||
normalized_text=value,
|
||||
raw_line=line,
|
||||
line_end_no=line_no,
|
||||
claimed_line_nos=(line_no,),
|
||||
captured_relation=relation,
|
||||
), None
|
||||
|
||||
@@ -712,6 +802,7 @@ def execute_base_split_rule_set(
|
||||
核心逻辑:
|
||||
1. normalization.line_breaks 拆行;
|
||||
2. 逐行收集命中规则,按 prefix > regex > position 决出唯一 segment;
|
||||
position 可声明 line_end 合并连续多行,并一次性认领起止范围内行;
|
||||
3. 同优先级多个 mapped 命中 → duplicate_line_match / needs_review;
|
||||
4. 未认领行按 unmatched_line_policy;
|
||||
5. evidence_only 全部保留;
|
||||
@@ -741,15 +832,17 @@ def execute_base_split_rule_set(
|
||||
segments: list[_CoreSegmentResult] = []
|
||||
claimed_lines: set[int] = set()
|
||||
|
||||
# [STEP 1] 逐行匹配并按优先级决出胜出规则。
|
||||
# [STEP 1] 逐行匹配并按优先级决出胜出规则;连续多行 position 一次性认领范围。
|
||||
for line_no, line in enumerate(inventory, start=1):
|
||||
if line_no in claimed_lines:
|
||||
continue
|
||||
matches: list[_LineMatch] = []
|
||||
for rule in rule_set.rules:
|
||||
outcome, error = _match_line(line_no, line, rule)
|
||||
outcome, error = _match_line(line_no, line, rule, inventory=inventory)
|
||||
if error:
|
||||
diagnostics.append(CoreSplitDiagnostic(
|
||||
code=error,
|
||||
message=f'Rule {rule.rule_id} regex failed on line {line_no}',
|
||||
message=f'Rule {rule.rule_id} failed on line {line_no}',
|
||||
line_no=line_no,
|
||||
field_code=rule.segment.target_field_code,
|
||||
rule_ids=[rule.rule_id],
|
||||
@@ -762,7 +855,9 @@ def execute_base_split_rule_set(
|
||||
if winner is None:
|
||||
continue
|
||||
|
||||
claimed_lines.add(line_no)
|
||||
span = winner.claimed_line_nos or (line_no,)
|
||||
claimed_lines.update(span)
|
||||
line_end_no = winner.line_end_no or max(span)
|
||||
seg = winner.rule.segment
|
||||
status = 'parsed'
|
||||
if not str(winner.normalized_text).strip() and seg.handling == 'mapped':
|
||||
@@ -779,7 +874,7 @@ def execute_base_split_rule_set(
|
||||
segment_code=seg.segment_code,
|
||||
display_name=seg.display_name,
|
||||
line_no=line_no,
|
||||
line_end_no=line_no,
|
||||
line_end_no=line_end_no,
|
||||
raw_text=winner.raw_line,
|
||||
normalized_text=winner.normalized_text,
|
||||
handling=seg.handling,
|
||||
|
||||
@@ -866,10 +866,29 @@ def schedule_layout_version(
|
||||
return version
|
||||
|
||||
|
||||
def _document_has_active_or_current_layout(document: ShippingOrderDocument) -> bool:
|
||||
"""
|
||||
判断文档是否已有进行中或可用的版面,从而本轮不必再占配额新建。
|
||||
|
||||
核心逻辑:queued/running 算进行中;current 指向 ready/needs_review 算可用。
|
||||
历史 unsupported(含预算跳过审计)不算可用,允许后续波次重新排程。
|
||||
"""
|
||||
for item in list(getattr(document, 'layout_versions', None) or []):
|
||||
if str(item.status or '') in {'queued', 'running'}:
|
||||
return True
|
||||
current = getattr(document, 'current_layout_version', None)
|
||||
return current is not None and str(current.status or '') in CURRENT_LAYOUT_STATUSES
|
||||
|
||||
|
||||
def schedule_document_layouts(
|
||||
documents: list[ShippingOrderDocument], *, created_by_id: int | None = None,
|
||||
) -> list[ShippingDocumentLayoutVersion]:
|
||||
"""在 Document 持久化事务内为支持附件建立独立布局版本,超量文档保留 skipped 审计。"""
|
||||
"""
|
||||
在 Document 持久化事务内为支持附件建立独立布局版本。
|
||||
|
||||
核心逻辑:只对尚无进行中/可用版面的 PDF 占配额;本轮最多新建 max_documents 个 Job。
|
||||
超出配额的文档本轮不排程、不写 unsupported 伪终态,留给后续 schedule 调用继续排。
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
from app.services.shipping_notice.document_layout.mineru import MINERU_SUPPORTED_EXTENSIONS
|
||||
@@ -882,30 +901,9 @@ def schedule_document_layouts(
|
||||
if item.asset_id is not None
|
||||
and Path(str(item.filename or '')).suffix.lower() in MINERU_SUPPORTED_EXTENSIONS
|
||||
]
|
||||
needing = [item for item in eligible if not _document_has_active_or_current_layout(item)]
|
||||
result: list[ShippingDocumentLayoutVersion] = []
|
||||
for index, document in enumerate(eligible):
|
||||
if index >= max_documents:
|
||||
existing = ShippingDocumentLayoutVersion.query.filter_by(
|
||||
document_id=int(document.id), source_content_hash=str(document.content_hash or ''),
|
||||
parser_key=current_layout_parser_key(), status='unsupported',
|
||||
).first()
|
||||
if existing is None:
|
||||
version_no = int(db.session.query(func.max(ShippingDocumentLayoutVersion.version)).filter_by(
|
||||
document_id=int(document.id),
|
||||
).scalar() or 0) + 1
|
||||
existing = ShippingDocumentLayoutVersion(
|
||||
document_id=int(document.id), version=version_no, status='unsupported',
|
||||
source_content_hash=str(document.content_hash or ''),
|
||||
parser_key=current_layout_parser_key(),
|
||||
parser_name=LAYOUT_PARSER_NAME, backend=LAYOUT_BACKEND,
|
||||
contract_version=LAYOUT_CONTRACT_VERSION,
|
||||
issues_json=['mineru_intake_document_budget_exceeded'], attempt_count=0,
|
||||
finished_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(existing)
|
||||
db.session.flush()
|
||||
result.append(existing)
|
||||
continue
|
||||
for document in needing[:max_documents]:
|
||||
version = schedule_layout_version(document, created_by_id=created_by_id)
|
||||
if version is not None:
|
||||
result.append(version)
|
||||
|
||||
@@ -147,6 +147,9 @@ class FieldRegion(OrderProfileModel):
|
||||
field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
|
||||
scope: Literal['header', 'line']
|
||||
region: RelativeRegion
|
||||
# 画布框稳定身份;XFA datasets binding.field_layout_id 优先引用本字段,
|
||||
# 避免仅用「行:field_code」时同名字段/复制框互相抢绑。
|
||||
region_id: str | None = Field(default=None, max_length=128)
|
||||
extractor_key: Literal['direct', 'temp_internal_parts', 'quantity_uom', 'amount_currency', 'price_currency'] = 'direct'
|
||||
allowed_sources: list[Literal['pdf_coordinate', 'ocr_coordinate']] = Field(min_length=1)
|
||||
minimum_evidence_level: Literal['coordinate', 'ocr_coordinate'] = 'coordinate'
|
||||
|
||||
@@ -7,7 +7,8 @@ services/shipping_notice/document_layout/order_profile_matcher.py
|
||||
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
|
||||
主表优先按签名表头原子亲和度选择(避免 MinerU 抬头 KV 小表抢主表),并列再比表区重叠;
|
||||
无 hard_valid 时仅当全部候选均坐标结构不可用才抬升 evidence_insufficient;
|
||||
身份表头只读「签名 header_bbox 按主表顶边 deltaY 对齐」后的窗口,禁止表顶宽带兜底;
|
||||
身份表头按各 table_patterns.header_bbox 对齐到对应表区后只读窗口(正确页码),
|
||||
禁止表顶宽带兜底;多 pattern 观测结果并集与签名身份 token 口径一致;
|
||||
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
|
||||
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁;
|
||||
单逻辑表头将折行副标签按 x 并入所属列(保留文案),不拆成新身份列。
|
||||
@@ -1352,7 +1353,7 @@ def _observe_layout_features(
|
||||
)
|
||||
|
||||
header_tokens, column_centers, column_width_ratios = _observe_primary_table_header(
|
||||
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
primary_bbox=primary_bbox, signature=signature,
|
||||
)
|
||||
static_text_centers = _observe_static_text_centers(
|
||||
@@ -1722,53 +1723,71 @@ _HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
|
||||
def _signature_table_bbox_median(signature: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取签名首个可用 table_patterns.bbox.median(归一化四点)。"""
|
||||
for pattern in (signature or {}).get('table_patterns') or []:
|
||||
if not isinstance(pattern, dict):
|
||||
continue
|
||||
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
|
||||
if not isinstance(bbox, dict):
|
||||
continue
|
||||
median = bbox.get('median')
|
||||
if isinstance(median, list) and len(median) == 4:
|
||||
try:
|
||||
return [float(item) for item in median]
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
median = _pattern_table_bbox_median(pattern if isinstance(pattern, dict) else None)
|
||||
if median is not None:
|
||||
return median
|
||||
return None
|
||||
|
||||
|
||||
def _align_signature_header_bbox_to_primary(
|
||||
def _pattern_header_bbox(pattern: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取单个 table_pattern 的 header_bbox。"""
|
||||
if not isinstance(pattern, dict):
|
||||
return None
|
||||
value = pattern.get('header_bbox')
|
||||
if isinstance(value, list) and len(value) == 4:
|
||||
try:
|
||||
return [float(item) for item in value]
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _pattern_table_bbox_median(pattern: dict[str, Any] | None) -> list[float] | None:
|
||||
"""读取单个 table_pattern.bbox.median。"""
|
||||
if not isinstance(pattern, dict):
|
||||
return None
|
||||
bbox = pattern.get('bbox') if isinstance(pattern.get('bbox'), dict) else None
|
||||
if not isinstance(bbox, dict):
|
||||
return None
|
||||
median = bbox.get('median')
|
||||
if isinstance(median, list) and len(median) == 4:
|
||||
try:
|
||||
return [float(item) for item in median]
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _align_header_bbox_to_table(
|
||||
*,
|
||||
signature: dict[str, Any] | None,
|
||||
primary_bbox: list[float],
|
||||
header_bbox: list[float],
|
||||
signature_table_y0: float | None,
|
||||
table_bbox: list[float],
|
||||
) -> list[float] | None:
|
||||
"""
|
||||
将签名冻结的表头框按当前主表顶边做整体 deltaY 对齐。
|
||||
将签名表头框按目标表顶边做整体 deltaY 对齐并夹在表内。
|
||||
|
||||
核心逻辑:x/高度保持签名 header_bbox;只用 primary_bbox.y0 - signature_table.y0
|
||||
平移;再把 y 夹在主表竖向范围内,避免落到明细数据行。无 header_bbox 时返回 None。
|
||||
核心逻辑:x/高度保持 header_bbox;deltaY = table.y0 - signature_table.y0。
|
||||
"""
|
||||
if not isinstance(primary_bbox, list) or len(primary_bbox) != 4:
|
||||
if not isinstance(table_bbox, list) or len(table_bbox) != 4:
|
||||
return None
|
||||
header_bbox = _signature_header_bbox(signature)
|
||||
if header_bbox is None:
|
||||
if not isinstance(header_bbox, list) or len(header_bbox) != 4:
|
||||
return None
|
||||
table_median = _signature_table_bbox_median(signature)
|
||||
try:
|
||||
hx0, hy0, hx1, hy1 = (float(header_bbox[i]) for i in range(4))
|
||||
py0, py1 = float(primary_bbox[1]), float(primary_bbox[3])
|
||||
py0, py1 = float(table_bbox[1]), float(table_bbox[3])
|
||||
except (TypeError, ValueError, IndexError):
|
||||
return None
|
||||
if hy1 <= hy0 or py1 <= py0:
|
||||
return None
|
||||
delta_y = 0.0
|
||||
if table_median is not None:
|
||||
if signature_table_y0 is not None:
|
||||
try:
|
||||
delta_y = py0 - float(table_median[1])
|
||||
except (TypeError, ValueError, IndexError):
|
||||
delta_y = py0 - float(signature_table_y0)
|
||||
except (TypeError, ValueError):
|
||||
delta_y = 0.0
|
||||
aligned_y0 = hy0 + delta_y
|
||||
aligned_y1 = hy1 + delta_y
|
||||
# [STEP] 夹在主表内;保持最小可读高度。
|
||||
height = max(0.02, aligned_y1 - aligned_y0)
|
||||
clipped_y0 = min(max(aligned_y0, py0), max(py0, py1 - height))
|
||||
clipped_y1 = min(clipped_y0 + height, py1)
|
||||
@@ -1777,51 +1796,106 @@ def _align_signature_header_bbox_to_primary(
|
||||
return [hx0, clipped_y0, hx1, clipped_y1]
|
||||
|
||||
|
||||
def _observe_primary_table_header(
|
||||
def _align_signature_header_bbox_to_primary(
|
||||
*,
|
||||
glyph_tables: dict[str, Any],
|
||||
page_glyphs: dict[str, Any],
|
||||
pages: dict[str, Any],
|
||||
primary_bbox: list[float] | None,
|
||||
signature: dict[str, Any] | None,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""
|
||||
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
|
||||
|
||||
核心逻辑:有签名 header_bbox 时按主表顶边 deltaY 对齐后只读该窗口;无签名表头框
|
||||
时才用主表顶 18% 保守带(与签名生成兜底一致)。禁止固定带失准后改走表顶多行
|
||||
宽带搜索,避免印刷括号注记污染身份原子。
|
||||
"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return [], [], []
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
|
||||
if not isinstance(glyphs, list):
|
||||
glyphs = []
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
glyphs.extend(table_glyphs)
|
||||
page = pages.get('1') or pages.get(1)
|
||||
if not isinstance(glyphs, list) or not glyphs or not isinstance(page, dict):
|
||||
return [], [], []
|
||||
aligned = _align_signature_header_bbox_to_primary(
|
||||
signature=signature, primary_bbox=primary_bbox,
|
||||
primary_bbox: list[float],
|
||||
) -> list[float] | None:
|
||||
"""兼容入口:用签名首个 header_bbox / table median 对齐到主表。"""
|
||||
header_bbox = _signature_header_bbox(signature)
|
||||
if header_bbox is None:
|
||||
return None
|
||||
table_median = _signature_table_bbox_median(signature)
|
||||
signature_table_y0 = float(table_median[1]) if table_median is not None else None
|
||||
return _align_header_bbox_to_table(
|
||||
header_bbox=header_bbox,
|
||||
signature_table_y0=signature_table_y0,
|
||||
table_bbox=primary_bbox,
|
||||
)
|
||||
if aligned is not None:
|
||||
region = {
|
||||
'x0': float(aligned[0]), 'y0': float(aligned[1]),
|
||||
'x1': float(aligned[2]), 'y1': float(aligned[3]),
|
||||
}
|
||||
else:
|
||||
region = {
|
||||
'x0': float(primary_bbox[0]),
|
||||
'y0': float(primary_bbox[1]),
|
||||
'x1': float(primary_bbox[2]),
|
||||
'y1': float(primary_bbox[1]) + max(
|
||||
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _normalized_layout_tables(
|
||||
*,
|
||||
tables: list[dict[str, Any]],
|
||||
pages: dict[str, Any],
|
||||
) -> list[tuple[list[float], Any, dict[str, Any]]]:
|
||||
"""将 layout.tables 规范为 (归一化 bbox, page_no, page)。"""
|
||||
normalized: list[tuple[list[float], Any, dict[str, Any]]] = []
|
||||
for table in tables:
|
||||
page_no = table.get('page_no') or 1
|
||||
page = pages.get(str(page_no)) or pages.get(page_no)
|
||||
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
|
||||
if not isinstance(page, dict) or not isinstance(bbox, dict):
|
||||
continue
|
||||
try:
|
||||
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
|
||||
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
|
||||
except (KeyError, TypeError, ValueError):
|
||||
continue
|
||||
if raw[2] <= raw[0] or raw[3] <= raw[1] or width <= 0 or height <= 0:
|
||||
continue
|
||||
norm = raw if max(raw) <= 1 else [
|
||||
raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height,
|
||||
]
|
||||
normalized.append((norm, page_no, page))
|
||||
return normalized
|
||||
|
||||
|
||||
def _best_table_for_pattern_bbox(
|
||||
*,
|
||||
pattern_bbox: list[float] | None,
|
||||
normalized_tables: list[tuple[list[float], Any, dict[str, Any]]],
|
||||
fallback: list[float] | None,
|
||||
) -> tuple[list[float], Any, dict[str, Any]] | None:
|
||||
"""按与 pattern.bbox.median 的 IoU 选运行时表;无重叠时回退 fallback 及其最近页。"""
|
||||
if pattern_bbox is not None and normalized_tables:
|
||||
best: tuple[float, list[float], Any, dict[str, Any]] | None = None
|
||||
for bbox, page_no, page in normalized_tables:
|
||||
overlap = _bbox_overlap(pattern_bbox, bbox)
|
||||
if best is None or overlap > best[0]:
|
||||
best = (overlap, bbox, page_no, page)
|
||||
if best is not None and best[0] > 0:
|
||||
return best[1], best[2], best[3]
|
||||
if fallback is None or len(fallback) != 4 or not normalized_tables:
|
||||
return None
|
||||
nearest = max(
|
||||
normalized_tables,
|
||||
key=lambda item: _bbox_overlap(fallback, item[0]),
|
||||
)
|
||||
return fallback, nearest[1], nearest[2]
|
||||
|
||||
|
||||
def _glyphs_for_page(
|
||||
*,
|
||||
page_no: Any,
|
||||
page_glyphs: dict[str, Any],
|
||||
glyph_tables: dict[str, Any],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""按页取 glyphs;缺页时回退全部 table glyphs。"""
|
||||
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no)
|
||||
if isinstance(glyphs, list) and glyphs:
|
||||
return glyphs
|
||||
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
|
||||
if isinstance(glyphs, list) and glyphs:
|
||||
return glyphs
|
||||
merged: list[dict[str, Any]] = []
|
||||
for table_glyphs in glyph_tables.values():
|
||||
if isinstance(table_glyphs, list):
|
||||
merged.extend(table_glyphs)
|
||||
return merged
|
||||
|
||||
|
||||
def _observe_header_region(
|
||||
*,
|
||||
region: dict[str, float],
|
||||
page: dict[str, Any],
|
||||
glyphs: list[dict[str, Any]],
|
||||
table_bbox: list[float],
|
||||
merge_wrap: bool,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""在指定页的相对区域内读取表头 token/列中心/宽度比。"""
|
||||
width = float(page.get('width') or 0)
|
||||
if width <= 0:
|
||||
if width <= 0 or not glyphs:
|
||||
return [], [], []
|
||||
header_glyphs = _glyphs_in_relative_region(glyphs, page=page, region=region)
|
||||
spans = [
|
||||
@@ -1830,11 +1904,11 @@ def _observe_primary_table_header(
|
||||
][:32]
|
||||
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
|
||||
band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
|
||||
table_span = max(float(primary_bbox[2]) - float(primary_bbox[0]), 0.0001)
|
||||
table_span = max(float(table_bbox[2]) - float(table_bbox[0]), 0.0001)
|
||||
band_widths = [
|
||||
round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans
|
||||
]
|
||||
if _signature_single_logical_header(signature):
|
||||
if merge_wrap:
|
||||
merged_tokens, merged_centers, merged_widths = merge_header_identity_wrap_tokens(
|
||||
band_tokens, band_centers, band_widths,
|
||||
)
|
||||
@@ -1846,6 +1920,97 @@ def _observe_primary_table_header(
|
||||
return band_tokens, band_centers, band_widths
|
||||
|
||||
|
||||
def _observe_primary_table_header(
|
||||
*,
|
||||
tables: list[dict[str, Any]],
|
||||
glyph_tables: dict[str, Any],
|
||||
page_glyphs: dict[str, Any],
|
||||
pages: dict[str, Any],
|
||||
primary_bbox: list[float] | None,
|
||||
signature: dict[str, Any] | None,
|
||||
) -> tuple[list[str], list[float], list[float]]:
|
||||
"""
|
||||
从对齐身份窗口观测表头,与签名生成保持同一证据口径。
|
||||
|
||||
核心逻辑:对每个带 header_bbox 的 table_pattern,选 IoU 最大的运行时表,按该表
|
||||
所在页做 deltaY 对齐后只读窗口;多 pattern 的 token 并集对应签名身份并集。无
|
||||
header_bbox 时才用主表顶 18% 保守带。禁止表顶多行宽带搜索。
|
||||
"""
|
||||
if not primary_bbox or len(primary_bbox) != 4:
|
||||
return [], [], []
|
||||
|
||||
patterns = [
|
||||
item for item in (signature or {}).get('table_patterns') or []
|
||||
if isinstance(item, dict) and _pattern_header_bbox(item) is not None
|
||||
]
|
||||
normalized_tables = _normalized_layout_tables(tables=tables, pages=pages)
|
||||
observed_tokens: list[str] = []
|
||||
observed_centers: list[float] = []
|
||||
observed_widths: list[float] = []
|
||||
|
||||
if patterns:
|
||||
for pattern in patterns:
|
||||
header_bbox = _pattern_header_bbox(pattern)
|
||||
if header_bbox is None:
|
||||
continue
|
||||
pattern_median = _pattern_table_bbox_median(pattern)
|
||||
matched = _best_table_for_pattern_bbox(
|
||||
pattern_bbox=pattern_median,
|
||||
normalized_tables=normalized_tables,
|
||||
fallback=primary_bbox,
|
||||
)
|
||||
if matched is None:
|
||||
continue
|
||||
table_bbox, page_no, page = matched
|
||||
aligned = _align_header_bbox_to_table(
|
||||
header_bbox=header_bbox,
|
||||
signature_table_y0=(
|
||||
float(pattern_median[1]) if pattern_median is not None else None
|
||||
),
|
||||
table_bbox=table_bbox,
|
||||
)
|
||||
if aligned is None:
|
||||
continue
|
||||
region = {
|
||||
'x0': float(aligned[0]), 'y0': float(aligned[1]),
|
||||
'x1': float(aligned[2]), 'y1': float(aligned[3]),
|
||||
}
|
||||
glyphs = _glyphs_for_page(
|
||||
page_no=page_no, page_glyphs=page_glyphs, glyph_tables=glyph_tables,
|
||||
)
|
||||
tokens, centers, widths = _observe_header_region(
|
||||
region=region, page=page, glyphs=glyphs, table_bbox=table_bbox,
|
||||
merge_wrap=int(pattern.get('header_row_count') or 1) <= 1,
|
||||
)
|
||||
observed_tokens.extend(tokens)
|
||||
observed_centers.extend(centers)
|
||||
observed_widths.extend(widths)
|
||||
if observed_tokens:
|
||||
return observed_tokens, observed_centers, observed_widths
|
||||
|
||||
# 无签名表头框或 pattern 均未读到:主表顶 18% 保守带(与签名生成兜底一致)。
|
||||
page_no, page = _page_for_primary_table_bbox(
|
||||
primary_bbox, tables=tables, pages=pages,
|
||||
)
|
||||
if not isinstance(page, dict):
|
||||
return [], [], []
|
||||
glyphs = _glyphs_for_page(
|
||||
page_no=page_no, page_glyphs=page_glyphs, glyph_tables=glyph_tables,
|
||||
)
|
||||
region = {
|
||||
'x0': float(primary_bbox[0]),
|
||||
'y0': float(primary_bbox[1]),
|
||||
'x1': float(primary_bbox[2]),
|
||||
'y1': float(primary_bbox[1]) + max(
|
||||
0.06, (float(primary_bbox[3]) - float(primary_bbox[1])) * 0.18,
|
||||
),
|
||||
}
|
||||
return _observe_header_region(
|
||||
region=region, page=page, glyphs=glyphs, table_bbox=primary_bbox,
|
||||
merge_wrap=_signature_single_logical_header(signature),
|
||||
)
|
||||
|
||||
|
||||
def _merge_following_wrap_candidate(
|
||||
*,
|
||||
header: dict[str, Any],
|
||||
|
||||
@@ -602,6 +602,7 @@ def rebuild_tree_dto_from_analysis(
|
||||
pdf_bytes: bytes,
|
||||
*,
|
||||
include_values: bool = False,
|
||||
include_full_values: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按需从 PDF 重建字段树 DTO(管理员 API 用,不持久化 XML)。
|
||||
@@ -610,6 +611,7 @@ def rebuild_tree_dto_from_analysis(
|
||||
analysis: 已有结构分析记录。
|
||||
pdf_bytes: 原始 PDF 字节。
|
||||
include_values: 是否包含脱敏值。
|
||||
include_full_values: 是否写入完整 sample_value_display(需上游权限门禁)。
|
||||
|
||||
Returns:
|
||||
字段树 DTO。
|
||||
@@ -618,7 +620,15 @@ def rebuild_tree_dto_from_analysis(
|
||||
if outcome.dataset_analysis is None:
|
||||
return project_field_tree(analysis, include_values=include_values)
|
||||
root = outcome.dataset_analysis.nodes[0] if outcome.dataset_analysis.nodes else None
|
||||
tree = serialize_tree_node(root, include_values=include_values) if root else {}
|
||||
tree = (
|
||||
serialize_tree_node(
|
||||
root,
|
||||
include_values=include_values,
|
||||
include_full_values=include_full_values,
|
||||
)
|
||||
if root
|
||||
else {}
|
||||
)
|
||||
return sanitize_xfa_dto({
|
||||
'analysis_id': analysis.id,
|
||||
'document_kind': analysis.document_kind,
|
||||
@@ -626,4 +636,5 @@ def rebuild_tree_dto_from_analysis(
|
||||
'tree': tree,
|
||||
'header_candidates': outcome.dataset_analysis.header_candidates,
|
||||
'stats': outcome.dataset_analysis.stats,
|
||||
'full_values_revealed': bool(include_full_values),
|
||||
})
|
||||
@@ -679,8 +679,8 @@ class OrderXfaDatasetProfile(XfaContractModel):
|
||||
raise ValueError('field_layout_id must reference an order_field_layouts entry')
|
||||
layout_field_code = str(layout.get('field_code') or '')
|
||||
if layout_field_code != binding.field_code:
|
||||
# 一个多行源值(MATNR)可以通过已确认拆分规则产出多个行字段。
|
||||
# 每个目标仍指向同一个真实 MATNR 框,避免伪造重叠视觉框。
|
||||
# 同一 datasets 源字段经已确认拆分规则可产出多个行字段。
|
||||
# 每个目标仍指向同一个真实视觉框,避免伪造重叠框。
|
||||
split_ref = binding.split_rule_ref
|
||||
segment = split_segments.get(str(split_ref.segment_id)) if split_ref else None
|
||||
is_split_target_visual_reuse = bool(
|
||||
|
||||
@@ -559,13 +559,20 @@ def read_collection_rows(
|
||||
return rows
|
||||
|
||||
|
||||
def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -> dict[str, Any]:
|
||||
def serialize_tree_node(
|
||||
node: XfaDatasetNode,
|
||||
*,
|
||||
include_values: bool = False,
|
||||
include_full_values: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
序列化单个树节点供 API 返回。
|
||||
|
||||
Args:
|
||||
node: 数据集树节点。
|
||||
include_values: 是否包含受控的样本展示值;不得暴露 raw_value。
|
||||
include_values: 是否包含受控的样本展示值;默认不得暴露 raw_value。
|
||||
include_full_values: 为 True 时把内存 raw_value 写入 sample_value_display
|
||||
(仅供已鉴权的映射台 reveal 路径;仍不输出 raw_value 键)。
|
||||
|
||||
Returns:
|
||||
安全 DTO 字典。
|
||||
@@ -580,16 +587,30 @@ def serialize_tree_node(node: XfaDatasetNode, *, include_values: bool = False) -
|
||||
'is_leaf': node.is_leaf,
|
||||
'is_header_candidate': node.is_header_candidate,
|
||||
'is_collection_candidate': node.is_collection_candidate,
|
||||
'children': [serialize_tree_node(child, include_values=include_values) for child in node.children],
|
||||
'children': [
|
||||
serialize_tree_node(
|
||||
child,
|
||||
include_values=include_values,
|
||||
include_full_values=include_full_values,
|
||||
)
|
||||
for child in node.children
|
||||
],
|
||||
}
|
||||
if include_values and node.is_leaf:
|
||||
# 字段树是批量 DTO:即使管理端需要映射辅助,也绝不能把 datasets
|
||||
# 原文放入可缓存/可下载的树响应。完整值只能经单值受控读取与审计接口取得。
|
||||
# 默认批量树只给脱敏/分级展示;完整值须经 reveal + 敏感读权限,且不输出 raw_value 键。
|
||||
payload['sample_value_masked'] = str(node.sample_value_masked or '')
|
||||
payload['sample_value_display'] = str(node.sample_value_display or '')
|
||||
payload['display_policy'] = str(node.display_policy or 'empty')
|
||||
payload['can_reveal'] = bool(node.can_reveal)
|
||||
payload['line_count'] = len(node.lines or [])
|
||||
raw = str(node.raw_value or '')
|
||||
if include_full_values and raw:
|
||||
payload['sample_value_display'] = raw
|
||||
payload['display_policy'] = 'full'
|
||||
payload['can_reveal'] = False
|
||||
payload['full_value_revealed'] = True
|
||||
else:
|
||||
payload['sample_value_display'] = str(node.sample_value_display or '')
|
||||
payload['display_policy'] = str(node.display_policy or 'empty')
|
||||
payload['can_reveal'] = bool(node.can_reveal)
|
||||
payload['full_value_revealed'] = False
|
||||
return payload
|
||||
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ backend/app/services/shipping_notice/document_layout/xfa_profile_extraction.py
|
||||
order_profile_extractors。
|
||||
逻辑:由 order_extraction_workflow XFA 分支在精确命中后调用;正式提取仅读 bindings[],
|
||||
无 bindings 或仍含 header_mappings/line_mapping.fields 时 fail-closed;
|
||||
header 带 split_rule_ref 的目标跳过 STEP1 直读,仅由拆分规则产出(与 line 对齐);
|
||||
类型/normalizer/validator 取自 schema_fields;失败由上层回退坐标/OCR/通用。
|
||||
"""
|
||||
|
||||
@@ -574,10 +575,12 @@ def extract_xfa_profile(
|
||||
header_bindings = _bindings_for_scope(profile, 'header')
|
||||
line_bindings = _bindings_for_scope(profile, 'line')
|
||||
|
||||
# [STEP 1] Header bindings
|
||||
# [STEP 1] Header bindings:带 split_rule_ref 的目标由后续拆分产出,禁止再读源全文。
|
||||
header_fields: list[XfaExtractedField] = []
|
||||
header_issues: list[str] = []
|
||||
for binding in header_bindings:
|
||||
if binding.split_rule_ref is not None:
|
||||
continue
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
value_type, normalizer_key, validator_key = _schema_metadata_for_field(
|
||||
schema_fields=schema_fields,
|
||||
|
||||
@@ -8,6 +8,7 @@ services/shipping_notice/document_layout/xfa_split_rule_contract.py
|
||||
BaseSplitSegment / BaseSplitRule / BaseSplitRuleSet)。
|
||||
逻辑:仅声明式校验,不执行规则、不读 PDF、不接网络;非法契约以 ValidationError
|
||||
或 ValueError 拒绝;匹配优先级由引擎固定 prefix > regex > position > unmatched;
|
||||
position 支持 line_end + join_with 合并连续多行;
|
||||
XfaSplit* 系列继承共享核心 BaseSplit*,但保留 XFA 专属字段(source_path_id /
|
||||
source_data_path 等)和 XFA 前缀的环境变量读取,保持对外行为零漂移。
|
||||
"""
|
||||
@@ -195,14 +196,17 @@ class XfaSplitPostProcessor(XfaContractModel):
|
||||
|
||||
class XfaSplitMatcher(BaseSplitMatcher):
|
||||
"""
|
||||
单行匹配器:position / prefix / regex。
|
||||
匹配器:position(可连续多行)/ prefix / regex。
|
||||
|
||||
优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。
|
||||
继承共享核心 BaseSplitMatcher;保留 XFA 自己的校验器与 XFA_ 前缀长度常量。
|
||||
position 可通过 line_end(含)与 join_with 合并连续多行。
|
||||
"""
|
||||
|
||||
type: XfaSplitMatcherType
|
||||
line_index: int | None = Field(default=None, ge=1, le=1000)
|
||||
line_end: int | None = Field(default=None, ge=1, le=1000)
|
||||
join_with: Literal['newline', 'space', 'comma'] | None = None
|
||||
value: str | None = Field(default=None, max_length=XFA_SPLIT_MAX_PREFIX_LENGTH)
|
||||
separators: list[str] = Field(default_factory=lambda: [':', ':'])
|
||||
case_sensitive: bool = False
|
||||
@@ -220,6 +224,19 @@ class XfaSplitMatcher(BaseSplitMatcher):
|
||||
if self.type == 'position':
|
||||
if self.line_index is None:
|
||||
raise ValueError('position matcher requires line_index (1-based)')
|
||||
# 单行保持 line_end=None,避免历史确认指纹漂移;连续多行才写入 line_end。
|
||||
if self.line_end is not None:
|
||||
if int(self.line_end) < int(self.line_index):
|
||||
raise ValueError('position matcher line_end must be >= line_index')
|
||||
if int(self.line_end) == int(self.line_index):
|
||||
object.__setattr__(self, 'line_end', None)
|
||||
object.__setattr__(self, 'join_with', None)
|
||||
elif self.join_with is None:
|
||||
object.__setattr__(self, 'join_with', 'newline')
|
||||
elif self.join_with not in {'newline', 'space', 'comma'}:
|
||||
raise ValueError('position matcher join_with must be newline/space/comma')
|
||||
else:
|
||||
object.__setattr__(self, 'join_with', None)
|
||||
elif self.type == 'prefix':
|
||||
label = str(self.value or '').strip()
|
||||
if not label:
|
||||
@@ -374,6 +391,7 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -
|
||||
|
||||
核心逻辑:只冻结 matcher 与 normalization;segment 的 Schema 映射字段不属于拆分逻辑,
|
||||
后续绑定或解绑目标字段不得取消已确认状态。
|
||||
单行 position 的空 line_end/join_with 不进入指纹,避免新增可选字段导致历史令牌失效。
|
||||
|
||||
【重要】:XFA 版指纹实现独立保留,不直接调用共享核心 base_split_content_fingerprint。
|
||||
原因:未来若共享核心为 Vendor Comments 增加 relation_capture 字段纳入指纹计算,
|
||||
@@ -399,7 +417,15 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -
|
||||
# 将同一规则对象交给 normalize/save,原地 pop 会使已确认草稿不可再次编辑。
|
||||
payload = json.loads(json.dumps(payload))
|
||||
for rule in payload.get('rules') or []:
|
||||
segment = rule.get('segment') if isinstance(rule, dict) else None
|
||||
if not isinstance(rule, dict):
|
||||
continue
|
||||
matcher = rule.get('matcher')
|
||||
if isinstance(matcher, dict):
|
||||
if matcher.get('line_end') in (None, matcher.get('line_index')):
|
||||
matcher.pop('line_end', None)
|
||||
if not matcher.get('join_with'):
|
||||
matcher.pop('join_with', None)
|
||||
segment = rule.get('segment')
|
||||
if not isinstance(segment, dict):
|
||||
continue
|
||||
segment.pop('handling', None)
|
||||
|
||||
@@ -385,6 +385,7 @@ def _validate_acroform(
|
||||
核心逻辑:
|
||||
- 允许展示格式不同,标准化后必须相同;
|
||||
- 明细按 AcroForm 同名多实例下标与提取行一一对应,禁止“全行扫到首个 field_code”;
|
||||
- 带 split_rule_ref 的 binding(表头/明细)跳过源 Widget 全文对账,正式值由拆分产出;
|
||||
- 无 Fields / 无重叠字段 → unavailable;仅部分字段可对 → partial;冲突 → mismatched。
|
||||
|
||||
Returns:
|
||||
@@ -405,10 +406,12 @@ def _validate_acroform(
|
||||
missing_counterpart = 0
|
||||
mismatches: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 1] Header:每个 binding 对应短名的首个 AcroForm 实例。
|
||||
# [STEP 1] Header:每个 binding 对应短名的首个 AcroForm 实例;拆分目标跳过源全文对账。
|
||||
for binding in profile.bindings:
|
||||
if binding.scope != 'header':
|
||||
continue
|
||||
if binding.split_rule_ref is not None:
|
||||
continue
|
||||
data_path = str(binding.value_binding.data_path or '')
|
||||
local = data_path.rsplit('/', 1)[-1].upper()
|
||||
acro_values = by_name.get(local) or []
|
||||
|
||||
@@ -7,7 +7,10 @@ services/shipping_notice/document_profile_quality_service.py
|
||||
共同坐标回放完成视觉证据,末端值源 adapter 再补充正式字段和结构校验;
|
||||
策略需复核时仍展示最佳努力明细供人工核对,正式自动建单仍要求策略 selected;
|
||||
盲测主明细仅 business_lines,随后按 LN 合并 line_field_supplement 料号;
|
||||
盲测执行附加 visual/split/evidence 指标,XFA 任一指标 < 1.0 即失败;样本通过并批准后才放行自动建单。
|
||||
盲测执行附加 visual/split/evidence 指标供展示;XFA 硬失败只认 datasets 抽取与真值比对;
|
||||
OCR↔datasets / 视觉覆盖不足写入 soft_diagnostics,不计入硬失败;
|
||||
XFA 确认真值:bindings 表头必须齐全,允许候选额外含仅有视觉框的表头(如 bill_to);
|
||||
样本通过并批准后才放行自动建单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -272,9 +275,13 @@ def _expected_rows(raw: Any) -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def _expected_order_fields(raw: Any, *, parser: Any) -> dict[str, Any]:
|
||||
"""校验订单字段盲测真值;按共同字段契约读取,不判断值源实现。"""
|
||||
"""校验订单字段盲测真值;按共同字段契约读取,不判断值源实现。
|
||||
|
||||
核心逻辑:XFA bindings 表头必须齐全;候选还可含视觉框/拆分产出的额外表头
|
||||
(如 bill_to_* 仅有 order_field_layouts、尚无 path binding),不得因多出来的键拒绝确认。
|
||||
"""
|
||||
# [STEP 1] bindings-only XFA 已禁止 legacy header_mappings;盲测 Header
|
||||
# 真值必须由共同 bindings[] 推导,不能因迁移字段为空而静默保存为 {}。
|
||||
# 真值必须覆盖共同 bindings[],不能因迁移字段为空而静默保存为 {}。
|
||||
binding_headers = [
|
||||
item for item in (getattr(parser, 'bindings', None) or [])
|
||||
if str(getattr(item, 'scope', '') or '') == 'header'
|
||||
@@ -289,11 +296,25 @@ def _expected_order_fields(raw: Any, *, parser: Any) -> dict[str, Any]:
|
||||
}
|
||||
if not expected_keys:
|
||||
return {}
|
||||
if not isinstance(raw, dict) or set(raw) != expected_keys or any(value in (None, '') for value in raw.values()):
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError(
|
||||
'expected_order_fields must contain every bound header field',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID',
|
||||
)
|
||||
missing = sorted(key for key in expected_keys if key not in raw)
|
||||
empty_bound = sorted(
|
||||
key for key in expected_keys
|
||||
if key in raw and raw.get(key) in (None, '')
|
||||
)
|
||||
if missing or empty_bound or any(value in (None, '') for value in raw.values()):
|
||||
raise ValidationError(
|
||||
'expected_order_fields must contain every bound header field',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID',
|
||||
details={
|
||||
'missing_keys': missing[:20],
|
||||
'empty_bound_keys': empty_bound[:20],
|
||||
},
|
||||
)
|
||||
return dict(raw)
|
||||
header_mappings = getattr(parser, 'header_mappings', [])
|
||||
if header_mappings:
|
||||
@@ -675,7 +696,7 @@ def _compare_blind_candidate(
|
||||
"""比较任意 value adapter 的盲测候选与人工冻结真值。
|
||||
|
||||
核心逻辑:adapter 已统一返回 order_fields 与 rows;本函数只做共同的字段确认、
|
||||
标准化值和行值对照。XFA 的视觉/镜像/证据完整性在调用前另行作为 adapter 门禁。
|
||||
标准化值和行值对照。XFA 视觉/镜像/证据指标仅作展示与 soft 诊断,不在此硬拦。
|
||||
|
||||
Args:
|
||||
candidate: coordinate 或 XFA adapter 产生的脱敏候选。
|
||||
@@ -1052,7 +1073,13 @@ def remove_sample(*, suite_id: int, sample_id: int, actor_id: int) -> dict[str,
|
||||
|
||||
|
||||
def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
"""用与候选预览相同的当前 Profile 路径执行盲测;任何差异都不得批准。"""
|
||||
"""
|
||||
用与候选预览相同的当前 Profile 路径执行盲测;任何差异都不得批准。
|
||||
|
||||
核心逻辑:公共流程拉候选 → 真值比对 → 汇总 Run。XFA adapter 的
|
||||
visual/mirror/evidence 与 OCR↔datasets 对照写入 soft_diagnostics,不计入硬失败;
|
||||
硬失败仅来自 datasets 抽取失败或与人工真值不一致。
|
||||
"""
|
||||
suite = db.session.get(ShippingDocumentProfileTestSuite, int(suite_id))
|
||||
if suite is None:
|
||||
raise NotFoundError('Order document profile test suite not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_NOT_FOUND')
|
||||
@@ -1076,12 +1103,35 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
'key_field_accuracy_rate': 1.0,
|
||||
}
|
||||
metrics_samples = 0
|
||||
soft_diagnostics: list[dict[str, Any]] = []
|
||||
for sample in suite.samples:
|
||||
try:
|
||||
candidate = _adapter_blind_candidate(profile=profile, sample=sample)
|
||||
except (NotFoundError, ValidationError):
|
||||
failures.append(f'sample:{sample.id}:{_adapter_evidence_missing_code(adapter)}_evidence_missing')
|
||||
continue
|
||||
# XFA OCR↔datasets 不一致:保留字段级诊断,不计入硬失败。
|
||||
ocr_check = candidate.get('ocr_datasets_cross_check') if isinstance(candidate, dict) else None
|
||||
if isinstance(ocr_check, dict) and ocr_check.get('status') == 'mismatched':
|
||||
mismatches = [
|
||||
item for item in (ocr_check.get('mismatches') or [])
|
||||
if isinstance(item, dict) and str(item.get('field_code') or '').strip()
|
||||
]
|
||||
soft_diagnostics.append({
|
||||
'sample_id': int(sample.id),
|
||||
'code': 'ocr_datasets_mismatch',
|
||||
'mismatch_count': int(ocr_check.get('mismatch_count') or len(mismatches)),
|
||||
'fields': [
|
||||
{
|
||||
'scope': str(item.get('scope') or ''),
|
||||
'field_code': str(item.get('field_code') or ''),
|
||||
'row_index': item.get('row_index'),
|
||||
'ocr_value': str(item.get('ocr_value') or ''),
|
||||
'datasets_value': str(item.get('datasets_value') or ''),
|
||||
}
|
||||
for item in mismatches[:20]
|
||||
],
|
||||
})
|
||||
adapter_failures, adapter_metrics = _adapter_blind_gate_failures(
|
||||
adapter=adapter, candidate=candidate, sample_id=sample.id,
|
||||
)
|
||||
@@ -1090,6 +1140,24 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
for key, value in adapter_metrics.items():
|
||||
metrics_agg[key] = min(metrics_agg[key], value)
|
||||
metrics_samples += 1
|
||||
# [STEP] XFA 视觉/镜像/留痕不足:仅 soft 诊断,不否决样本。
|
||||
soft_metric_codes = [
|
||||
(key, code)
|
||||
for key, code in (
|
||||
('visual_coverage_rate', 'visual_coverage_soft'),
|
||||
('mirror_consistency_rate', 'mirror_consistency_soft'),
|
||||
('evidence_retention_rate', 'evidence_retention_soft'),
|
||||
)
|
||||
if float(adapter_metrics.get(key) or 1.0) < 1.0
|
||||
]
|
||||
for _key, code in soft_metric_codes:
|
||||
soft_diagnostics.append({
|
||||
'sample_id': int(sample.id),
|
||||
'code': code,
|
||||
'mismatch_count': 0,
|
||||
'fields': [],
|
||||
'rate': float(adapter_metrics.get(_key) or 0.0),
|
||||
})
|
||||
line_schema_by_code = _adapter_line_schema_by_code(parser, schema_fields)
|
||||
comparison_failures, key_total, key_matched = _compare_blind_candidate(
|
||||
candidate=candidate,
|
||||
@@ -1114,6 +1182,7 @@ def execute_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
'value_adapter': adapter.key,
|
||||
'metrics': metrics_agg,
|
||||
'adapter_metrics_available': metrics_samples > 0,
|
||||
'soft_diagnostics': soft_diagnostics,
|
||||
},
|
||||
executed_by_id=actor_id,
|
||||
)
|
||||
@@ -1489,6 +1558,7 @@ def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]:
|
||||
latest = suite.runs[-1] if suite.runs else None
|
||||
evidence = dict(getattr(latest, 'evidence_json', {}) or {}) if latest is not None else {}
|
||||
metrics = evidence.get('metrics') if isinstance(evidence.get('metrics'), dict) else None
|
||||
soft_diagnostics = evidence.get('soft_diagnostics') if isinstance(evidence.get('soft_diagnostics'), list) else []
|
||||
failure_codes = [str(code or '') for code in list(latest.failure_codes_json or [])] if latest is not None else []
|
||||
return {
|
||||
'id': suite.id, 'profile_id': suite.profile_id, 'profile_checksum': suite.profile_checksum,
|
||||
@@ -1500,5 +1570,7 @@ def serialize_suite(suite: ShippingDocumentProfileTestSuite) -> dict[str, Any]:
|
||||
'passed_sample_count': latest.passed_sample_count,
|
||||
'failure_codes': failure_codes,
|
||||
'metrics': metrics,
|
||||
# 字段级 OCR↔datasets 对照诊断(含两侧截断值),供管理端标明差异。
|
||||
'soft_diagnostics': soft_diagnostics,
|
||||
},
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_document_profile_service.py
|
||||
|
||||
Profile Run
|
||||
ShippingOrderDocumentProfile Schema document_layout.order_profile
|
||||
field_code field_id Schema
|
||||
CASCADE 500?
|
||||
用途:订单文档 Profile 的保存、发布、预览授权与共同视觉契约还原。
|
||||
依赖:OrderCoordinateProfile、Schema 模型、preview_grant_store、value adapter 注册表。
|
||||
逻辑:管理 API / 盲测质量服务调用本模块;`_definition_contract` 供候选预览与样本回放
|
||||
构造坐标契约,并回填 XFA 草稿中空的 order_field field_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -727,9 +727,10 @@ def _normalize_visual_definition_for_preview(
|
||||
"""将任意值源草稿投影为共同视觉定义,供画布样本值预览使用。
|
||||
|
||||
核心逻辑:PDFium/OCR 视觉取值只依赖文档匹配、表区和视觉字段布局,不能因为 XFA
|
||||
datasets 终值映射尚未完成而拒绝预览。该函数刻意丢弃 template_mode、bindings、path_id
|
||||
与 datasets 契约;保存、发布和正式提取仍必须走 ``_normalize_definition`` 的完整 adapter
|
||||
校验,绝不在此放宽正式值源规则。
|
||||
datasets 终值映射尚未完成、或草稿存在重复 Schema 绑定而拒绝预览。该函数刻意丢弃
|
||||
template_mode、bindings、path_id 与 datasets 契约,并对重复 field_code 仅保留首个
|
||||
布局;保存、发布和正式提取仍必须走 ``_normalize_definition`` 的完整校验,绝不在
|
||||
此放宽正式值源规则。
|
||||
|
||||
Args:
|
||||
raw: 编辑器当前草稿,可能包含 coordinate 或 XFA datasets 的末端值配置。
|
||||
@@ -743,7 +744,20 @@ def _normalize_visual_definition_for_preview(
|
||||
'Order profile definition must be an object',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
)
|
||||
order_field_layouts = raw.get('order_field_layouts') or []
|
||||
# [STEP] 预览只读:草稿可能已存在重复订单字段绑定;保留每个 field_code 的首个布局,
|
||||
# 让进入编辑页即可读取样本值。保存路径仍走完整 _normalize_definition 硬阻断。
|
||||
seen_order_field_codes: set[str] = set()
|
||||
order_field_layouts: list[Any] = []
|
||||
for item in raw.get('order_field_layouts') or []:
|
||||
if not isinstance(item, dict):
|
||||
order_field_layouts.append(item)
|
||||
continue
|
||||
code = str(item.get('field_code') or '').strip()
|
||||
if code and code in seen_order_field_codes:
|
||||
continue
|
||||
if code:
|
||||
seen_order_field_codes.add(code)
|
||||
order_field_layouts.append(item)
|
||||
bound_layout_ids = {
|
||||
str(item.get('layout_id') or '').strip()
|
||||
for item in order_field_layouts
|
||||
@@ -798,19 +812,135 @@ def _normalize_visual_definition_for_preview(
|
||||
return _normalize_definition(visual, schema_version=schema_version, preferred_template_mode='coordinate')
|
||||
|
||||
|
||||
def _hydrate_coordinate_layout_field_ids(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
schema_version: ShippingOrderSchemaVersion | None,
|
||||
) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
||||
"""
|
||||
为共同视觉坐标契约回填空 field_id,避免盲测/候选预览直接校验已保存草稿时 500。
|
||||
|
||||
核心逻辑:XFA 画布保存时常把 order_field_layouts.field_id 写成空串,正式 field_id
|
||||
在 Schema 或 bindings 上。按 (scope, field_code) 取 Schema,再按 field_layout_id
|
||||
回退 binding.field_id;表内 field_regions 同样处理。不改写 profile.definition_json。
|
||||
|
||||
Args:
|
||||
definition: Profile.definition_json 字典。
|
||||
schema_version: Profile 绑定的 Schema 版本;缺失时仅尝试 bindings。
|
||||
|
||||
Returns:
|
||||
(order_field_layouts, table_regions) 的浅拷贝列表,已尽量补齐 field_id。
|
||||
"""
|
||||
profile_fields = _schema_profile_fields(schema_version) if schema_version is not None else {}
|
||||
bindings_by_layout = {
|
||||
str(item.get('field_layout_id') or '').strip(): item
|
||||
for item in (definition.get('bindings') or [])
|
||||
if isinstance(item, dict) and str(item.get('field_layout_id') or '').strip()
|
||||
}
|
||||
|
||||
def resolve_field_id(*, field_id: Any, field_code: Any, scope: Any, layout_id: Any) -> str:
|
||||
current = str(field_id or '').strip()
|
||||
if current:
|
||||
return current
|
||||
code = str(field_code or '').strip()
|
||||
field_scope = str(scope or 'header').strip() or 'header'
|
||||
schema_field = profile_fields.get((field_scope, code)) if code else None
|
||||
if isinstance(schema_field, dict) and str(schema_field.get('field_id') or '').strip():
|
||||
return str(schema_field['field_id']).strip()
|
||||
binding = bindings_by_layout.get(str(layout_id or '').strip())
|
||||
if isinstance(binding, dict) and str(binding.get('field_id') or '').strip():
|
||||
return str(binding['field_id']).strip()
|
||||
return current
|
||||
|
||||
order_field_layouts: list[dict[str, Any]] = []
|
||||
for item in definition.get('order_field_layouts') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
layout = dict(item)
|
||||
layout['field_id'] = resolve_field_id(
|
||||
field_id=layout.get('field_id'),
|
||||
field_code=layout.get('field_code'),
|
||||
scope=layout.get('scope') or 'header',
|
||||
layout_id=layout.get('layout_id'),
|
||||
)
|
||||
order_field_layouts.append(layout)
|
||||
|
||||
table_regions: list[dict[str, Any]] = []
|
||||
for raw_table in definition.get('table_regions') or []:
|
||||
if not isinstance(raw_table, dict):
|
||||
continue
|
||||
table = dict(raw_table)
|
||||
|
||||
def hydrate_layout_fields(raw_layout: Any) -> dict[str, Any] | None:
|
||||
if not isinstance(raw_layout, dict):
|
||||
return None
|
||||
layout = dict(raw_layout)
|
||||
parent_id = str(layout.get('layout_id') or '').strip()
|
||||
hydrated_fields: list[dict[str, Any]] = []
|
||||
for raw_field in layout.get('field_regions') or []:
|
||||
if not isinstance(raw_field, dict):
|
||||
continue
|
||||
field = dict(raw_field)
|
||||
region_id = str(field.get('region_id') or '').strip()
|
||||
layout_key = region_id or (
|
||||
f'{parent_id}:{str(field.get("field_code") or "").strip()}'.strip(':')
|
||||
)
|
||||
field['field_id'] = resolve_field_id(
|
||||
field_id=field.get('field_id'),
|
||||
field_code=field.get('field_code'),
|
||||
scope=field.get('scope') or 'line',
|
||||
layout_id=layout_key,
|
||||
)
|
||||
hydrated_fields.append(field)
|
||||
layout['field_regions'] = hydrated_fields
|
||||
return layout
|
||||
|
||||
table['header_layouts'] = [
|
||||
hydrated
|
||||
for item in (table.get('header_layouts') or [])
|
||||
if (hydrated := hydrate_layout_fields(item)) is not None
|
||||
]
|
||||
table['line_layouts'] = [
|
||||
hydrated
|
||||
for item in (table.get('line_layouts') or [])
|
||||
if (hydrated := hydrate_layout_fields(item)) is not None
|
||||
]
|
||||
table_regions.append(table)
|
||||
|
||||
return order_field_layouts, table_regions
|
||||
|
||||
|
||||
def _definition_contract(profile: ShippingOrderDocumentProfile) -> OrderCoordinateProfile:
|
||||
""" v1 Profile v2?"""
|
||||
"""
|
||||
把已保存 Profile 还原为共同视觉坐标契约,供盲测/样本候选抽取使用。
|
||||
|
||||
核心逻辑:先回填空 field_id(XFA 草稿常见),再构造 OrderCoordinateProfile;
|
||||
契约非法时转为业务 ValidationError,禁止冒泡成 SYSTEM.INTERNAL_ERROR 500。
|
||||
"""
|
||||
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
|
||||
return OrderCoordinateProfile(
|
||||
profile_code=profile.profile_code,
|
||||
version=profile.version,
|
||||
document_match=definition.get('document_match'),
|
||||
table_regions=definition.get('table_regions'),
|
||||
order_field_layouts=definition.get('order_field_layouts') or [],
|
||||
draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [],
|
||||
coordinate_model=definition.get('coordinate_model') or {},
|
||||
reference_page_frames=definition.get('reference_page_frames') or {},
|
||||
order_field_layouts, table_regions = _hydrate_coordinate_layout_field_ids(
|
||||
definition=definition,
|
||||
schema_version=profile.schema_version,
|
||||
)
|
||||
try:
|
||||
return OrderCoordinateProfile(
|
||||
profile_code=profile.profile_code,
|
||||
version=profile.version,
|
||||
document_match=definition.get('document_match'),
|
||||
table_regions=table_regions,
|
||||
order_field_layouts=order_field_layouts,
|
||||
draft_unbound_order_field_layouts=definition.get('draft_unbound_order_field_layouts') or [],
|
||||
coordinate_model=definition.get('coordinate_model') or {},
|
||||
reference_page_frames=definition.get('reference_page_frames') or {},
|
||||
)
|
||||
except (TypeError, ValueError) as exc:
|
||||
validation_errors = getattr(exc, 'errors', lambda: [])()
|
||||
location = validation_errors[0].get('loc', ()) if validation_errors else ()
|
||||
raise ValidationError(
|
||||
'Order profile definition is invalid',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
details={'reason': 'coordinate_contract_invalid', 'location': list(location)},
|
||||
) from exc
|
||||
|
||||
|
||||
def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
|
||||
@@ -176,27 +176,27 @@ def _require_xfa_draft(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
return dict(profile.definition_json or {})
|
||||
|
||||
|
||||
def _resolve_matnr_path_id(
|
||||
def _resolve_split_source_path_id(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
path_context: dict[str, Any],
|
||||
path_id: str | None,
|
||||
) -> tuple[str, str]:
|
||||
"""
|
||||
解析 MATNR 类拆分源 path_id 与 data_path。
|
||||
解析拆分规则建议的源 path_id 与 data_path(通用,不绑死字段名)。
|
||||
|
||||
核心逻辑:显式 path_id 优先;否则在权威行集合下查找 local_name=MATNR 的路径。
|
||||
核心逻辑:显式 path_id 优先;未传时仅作兼容回退,在权威行集合下查找常见料号叶子名。
|
||||
|
||||
Args:
|
||||
definition: 当前 Profile definition。
|
||||
path_context: 当前末端值源 adapter 的冻结路径上下文。
|
||||
path_id: 可选显式 path_id。
|
||||
path_id: 可选显式 path_id(UI 选中源字段时应必传)。
|
||||
|
||||
Returns:
|
||||
(path_id, data_path) 元组。
|
||||
|
||||
Raises:
|
||||
ValidationError: 无法定位 MATNR 路径。
|
||||
ValidationError: 无法定位源路径。
|
||||
"""
|
||||
path_map: dict[str, str] = dict(path_context.get('path_map') or {})
|
||||
if path_id:
|
||||
@@ -209,24 +209,31 @@ def _resolve_matnr_path_id(
|
||||
)
|
||||
return str(path_id), resolved
|
||||
|
||||
# 兼容旧调用:未传 path_id 时按常见料号叶子名回退,不是运行时拆分引擎的字段硬编码。
|
||||
source = definition.get('source_contract') if isinstance(definition.get('source_contract'), dict) else {}
|
||||
auth_path = str(source.get('authoritative_line_collection_path') or '').rstrip('/')
|
||||
fallback_leaf_names = ('MATNR', 'PARTS', 'PART_NO', 'MATERIAL')
|
||||
candidates = [
|
||||
(pid, data_path)
|
||||
for pid, data_path in path_map.items()
|
||||
if data_path.endswith('/MATNR') or data_path == f'{auth_path}/MATNR'
|
||||
for leaf in fallback_leaf_names
|
||||
if data_path.endswith(f'/{leaf}') or data_path == f'{auth_path}/{leaf}'
|
||||
]
|
||||
if not candidates:
|
||||
raise ValidationError(
|
||||
'MATNR source path is not available for split rule suggestion',
|
||||
'Split source path_id is required when no common material leaf can be inferred',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
details={'reason': 'matnr_path_missing'},
|
||||
details={'reason': 'split_source_path_missing'},
|
||||
)
|
||||
if len(candidates) > 1:
|
||||
candidates.sort(key=lambda item: item[1])
|
||||
return candidates[0]
|
||||
|
||||
|
||||
# 兼容旧名:历史测试/调用仍可能引用 MATNR 命名;实现已改为通用源路径解析。
|
||||
_resolve_matnr_path_id = _resolve_split_source_path_id
|
||||
|
||||
|
||||
def _schema_field_ids(profile_id: int) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
读取 Profile 绑定 Schema 的 field_code → 字段定义。
|
||||
@@ -241,21 +248,36 @@ def _schema_field_ids(profile_id: int) -> dict[str, dict[str, Any]]:
|
||||
return get_value_adapter(dict(profile.definition_json or {})).mapping_schema_fields(profile_id=profile_id)
|
||||
|
||||
|
||||
def build_matnr_split_rule_suggestion(
|
||||
def _source_field_code_from_data_path(data_path: str) -> str:
|
||||
"""
|
||||
从 data_path 取叶子名作为 source_field_code(通用,不写死 MATNR)。
|
||||
|
||||
Args:
|
||||
data_path: datasets 绝对路径。
|
||||
|
||||
Returns:
|
||||
路径最后一段;空路径时返回空串。
|
||||
"""
|
||||
parts = [part for part in str(data_path or '').split('/') if part]
|
||||
return parts[-1] if parts else ''
|
||||
|
||||
|
||||
def build_multiline_part_split_rule_suggestion(
|
||||
*,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
生成 MATNR 类五行样本的拆分规则建议(matcher 模型)。
|
||||
生成「多行料号描述」类拆分规则建议(matcher 模型,仅建议草稿)。
|
||||
|
||||
核心逻辑:position:1→customer_part_number;prefix MPN→part_number;
|
||||
核心逻辑:这是可选的系统建议模板,不是运行时拆分引擎;运行时只认用户确认后的
|
||||
split_rules。position:1→customer_part_number;prefix MPN→part_number;
|
||||
其余 unmatched→evidence_only;status=draft、source=system_suggestion。
|
||||
|
||||
Args:
|
||||
path_id: 源 datasets path_id。
|
||||
data_path: 源 data_path(写入 source_data_path)。
|
||||
path_id: 源 datasets path_id(任意叶子,不限 MATNR)。
|
||||
data_path: 源 data_path(写入 source_data_path / source_field_code)。
|
||||
schema_fields: Schema field_code 索引。
|
||||
|
||||
Returns:
|
||||
@@ -266,12 +288,13 @@ def build_matnr_split_rule_suggestion(
|
||||
rule_set_id = f'rs-{secrets.token_hex(8)}'
|
||||
segment_cpn = new_segment_id()
|
||||
segment_mpn = new_segment_id()
|
||||
source_field_code = _source_field_code_from_data_path(data_path) or 'SOURCE'
|
||||
rule_set = XfaSplitRuleSet(
|
||||
rule_set_id=rule_set_id,
|
||||
rule_version=1,
|
||||
source_path_id=str(path_id),
|
||||
source_scope='line',
|
||||
source_field_code='MATNR',
|
||||
source_field_code=source_field_code,
|
||||
source_data_path=str(data_path),
|
||||
rules=[
|
||||
XfaSplitRule(
|
||||
@@ -319,6 +342,10 @@ def build_matnr_split_rule_suggestion(
|
||||
return dumped
|
||||
|
||||
|
||||
# 兼容旧名:历史 MATNR 样本建议入口;实现已改为任意源字段。
|
||||
build_matnr_split_rule_suggestion = build_multiline_part_split_rule_suggestion
|
||||
|
||||
|
||||
def suggest_xfa_split_rules(
|
||||
profile_id: int,
|
||||
*,
|
||||
@@ -328,12 +355,14 @@ def suggest_xfa_split_rules(
|
||||
write_audit: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
为 MATNR 类字段生成拆分规则建议(不写 Draft、不 commit)。
|
||||
为指定 datasets 源字段生成拆分规则建议(不写 Draft、不 commit)。
|
||||
|
||||
核心逻辑:建议模板仅辅助配置;运行时拆分只执行用户已确认的通用 split_rules。
|
||||
|
||||
Args:
|
||||
profile_id: 模板 ID。
|
||||
document_id: 绑定样本 document ID。
|
||||
path_id: 可选显式源 path_id;省略时自动定位 MATNR。
|
||||
path_id: 源 path_id;省略时仅兼容回退常见料号叶子。
|
||||
actor_id: 管理员 ID。
|
||||
write_audit: 为 True 时写只读建议审计(默认 False,零写库)。
|
||||
|
||||
@@ -354,13 +383,13 @@ def suggest_xfa_split_rules(
|
||||
profile_service._bound_sample_document(int(profile_id), int(document_id))
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
path_context = get_value_adapter(definition).prepare_context(document)
|
||||
resolved_path_id, data_path = _resolve_matnr_path_id(
|
||||
resolved_path_id, data_path = _resolve_split_source_path_id(
|
||||
definition=definition,
|
||||
path_context=path_context,
|
||||
path_id=str(path_id).strip() if path_id else None,
|
||||
)
|
||||
schema_fields = _schema_field_ids(profile.id)
|
||||
rule_set = build_matnr_split_rule_suggestion(
|
||||
rule_set = build_multiline_part_split_rule_suggestion(
|
||||
path_id=resolved_path_id,
|
||||
data_path=data_path,
|
||||
schema_fields=schema_fields,
|
||||
|
||||
@@ -1165,12 +1165,28 @@ def order_extraction_layout_prerequisite_issues(run: ShippingOrderProcessingRun)
|
||||
)
|
||||
version = active_versions[0] if active_versions else document.current_layout_version
|
||||
if version is None:
|
||||
issues[int(document.id)] = 'layout_missing'
|
||||
# 有原件但尚未排到版面(配额延后或历史 budget unsupported 未绑 current):
|
||||
# 记 pending 等待后续 schedule,禁止当成 layout_missing 永久 failed。
|
||||
if document.asset_id:
|
||||
issues[int(document.id)] = 'layout_pending'
|
||||
else:
|
||||
issues[int(document.id)] = 'layout_missing'
|
||||
continue
|
||||
if str(version.status or '') in {'queued', 'running'}:
|
||||
issues[int(document.id)] = 'layout_pending'
|
||||
continue
|
||||
if str(version.status or '') != 'ready':
|
||||
issues_list = [
|
||||
str(item) for item in (version.issues_json or []) if str(item or '').strip()
|
||||
]
|
||||
# 历史预算跳过审计:视为延后排程,不进硬失败。
|
||||
if (
|
||||
str(version.status or '') == 'unsupported'
|
||||
and 'mineru_intake_document_budget_exceeded' in issues_list
|
||||
and bool(document.asset_id)
|
||||
):
|
||||
issues[int(document.id)] = 'layout_pending'
|
||||
continue
|
||||
payload = version.payload_json if isinstance(version.payload_json, dict) else {}
|
||||
# PDF 坐标证据可从原始附件按需恢复;压缩导致的 failed/不完整版本不应
|
||||
# 在正式模板匹配前提前阻断,workflow 会在内存中恢复并继续做确定性匹配。
|
||||
@@ -1204,11 +1220,48 @@ def order_extraction_layouts_pending(run: ShippingOrderProcessingRun) -> bool:
|
||||
_EXTRACT_DONE_UNIT_STATUSES = frozenset({
|
||||
'candidate_ready', 'review_required', 'failed', 'cancelled',
|
||||
})
|
||||
_LAYOUT_PREREQUISITE_FAILED_CODE = 'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PREREQUISITE_FAILED'
|
||||
# layout 与 extraction 共 shipping 队列且默认 priority=0;resume 抬高后才能插队,
|
||||
# 否则「单文件版式完成」的 extraction 仍排在剩余 layout FIFO 之后。
|
||||
_ORDER_EXTRACTION_READY_PRIORITY = 10
|
||||
|
||||
|
||||
def revive_layout_prerequisite_failed_units(run: ShippingOrderProcessingRun) -> int:
|
||||
"""
|
||||
版面已就绪时,将 layout 前置失败的 Unit 重置为 pending 以便重抽。
|
||||
|
||||
核心逻辑:仅复活 error_code=LAYOUT_PREREQUISITE_FAILED 且 document 现已 ready 的 Unit;
|
||||
同步清掉 Document 上对应的 failed 投影,避免首屏仍显示解析失败。
|
||||
|
||||
Returns:
|
||||
复活的 Unit 数量。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
ready_ids = order_extraction_ready_document_ids(run)
|
||||
if not ready_ids:
|
||||
return 0
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
if plan is None:
|
||||
return 0
|
||||
revived = 0
|
||||
for unit in ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all():
|
||||
if str(unit.status or '') != 'failed':
|
||||
continue
|
||||
if str(unit.error_code or '') != _LAYOUT_PREREQUISITE_FAILED_CODE:
|
||||
continue
|
||||
if int(unit.document_id or 0) not in ready_ids:
|
||||
continue
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
document = db.session.get(ShippingOrderDocument, int(unit.document_id))
|
||||
if document is not None and str(document.order_extraction_status or '') == 'failed':
|
||||
document.order_extraction_status = 'not_started'
|
||||
document.order_extraction_error_code = None
|
||||
document.order_extraction_error_message = None
|
||||
revived += 1
|
||||
return revived
|
||||
|
||||
|
||||
def _enqueue_ready_order_extraction_job(
|
||||
run: ShippingOrderProcessingRun, *, message: str,
|
||||
) -> int:
|
||||
@@ -1265,9 +1318,10 @@ def order_extraction_has_extractable_ready_work(run: ShippingOrderProcessingRun)
|
||||
"""
|
||||
判断是否存在「版式已就绪、Unit 尚未收口」的可抽取工作。
|
||||
|
||||
核心逻辑:有 ready PDF 且(尚无 Plan / Plan 为空 → 需要建计划抽取;或存在对应
|
||||
Unit 未到 candidate_ready/review_required/failed/cancelled)。
|
||||
核心逻辑:先尝试复活 layout 前置失败 Unit;有 ready PDF 且(尚无 Plan / Plan 为空 →
|
||||
需要建计划抽取;或存在对应 Unit 未到 candidate_ready/review_required/failed/cancelled)。
|
||||
"""
|
||||
revive_layout_prerequisite_failed_units(run)
|
||||
ready_ids = order_extraction_ready_document_ids(run)
|
||||
if not ready_ids:
|
||||
return False
|
||||
@@ -1334,13 +1388,11 @@ def schedule_order_extraction_layouts(
|
||||
"""
|
||||
发送后为本 Run 已选附件创建版面任务,并返回是否需要等待其完成。
|
||||
|
||||
核心逻辑:调用 schedule_document_layouts;用返回值与库查询确认每份 PDF 已有布局版本,
|
||||
避免 ORM 关系未刷新导致误报「未创建版面 Job」。
|
||||
核心逻辑:调用 schedule_document_layouts;配额延后的 PDF 本轮可不排程,返回 True 继续等待;
|
||||
已有 queued/running/ready 的不重复占用配额。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_document_layouts
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
documents = _run_layout_documents(run)
|
||||
scheduled = schedule_document_layouts(documents, created_by_id=created_by_id)
|
||||
# [STEP] 以本轮排程结果与库内版本为准,禁止依赖可能未 refresh 的 layout_versions 关系。
|
||||
@@ -1374,7 +1426,7 @@ def schedule_order_extraction_layouts(
|
||||
for document in documents
|
||||
if document.current_layout_version_id is not None
|
||||
}
|
||||
# 排程函数不能再静默跳过订单 PDF;否则后续路由只能看到空表格并误判业务失败。
|
||||
# 配额延后的 PDF 本轮可不排程;保留 pending,禁止当成排程失败抬 ValidationError。
|
||||
missing = [
|
||||
document_id for document_id in pdf_document_ids
|
||||
if (
|
||||
@@ -1384,11 +1436,7 @@ def schedule_order_extraction_layouts(
|
||||
)
|
||||
]
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
'Order PDF layout job was not created',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_SCHEDULING_FAILED',
|
||||
details={'document_ids': missing},
|
||||
)
|
||||
return True
|
||||
return order_extraction_layouts_pending(run)
|
||||
|
||||
|
||||
@@ -1460,6 +1508,44 @@ def resume_runs_waiting_for_layout(*, document_id: int) -> int:
|
||||
reason_code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_FAILED', commit=False,
|
||||
)
|
||||
resumed += 1
|
||||
continue
|
||||
# 无版面 pending、无可抽/可复活工作:收口卡住的 waiting_layout,避免永久 processing。
|
||||
plan = ShippingOrderProcessingPlan.query.filter_by(run_id=int(run.id)).first()
|
||||
units = (
|
||||
ShippingOrderProcessingUnit.query.filter_by(plan_id=int(plan.id)).all()
|
||||
if plan is not None else []
|
||||
)
|
||||
if not units or any(
|
||||
str(unit.status or '') not in _EXTRACT_DONE_UNIT_STATUSES for unit in units
|
||||
):
|
||||
continue
|
||||
deterministic = sum(1 for unit in units if str(unit.status or '') == 'candidate_ready')
|
||||
failed = sum(1 for unit in units if str(unit.status or '') == 'failed')
|
||||
review = sum(1 for unit in units if str(unit.status or '') == 'review_required')
|
||||
if deterministic == 0 and failed > 0 and review == 0:
|
||||
final_status = 'failed'
|
||||
elif deterministic == 0 and review > 0 and failed == 0:
|
||||
final_status = 'review_required'
|
||||
elif review > 0 or failed > 0 or deterministic < len(units):
|
||||
final_status = 'partially_completed'
|
||||
else:
|
||||
final_status = 'completed'
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='processing', phase=final_status)
|
||||
transition_order_extraction_run(run, target_status=final_status, phase=final_status)
|
||||
record_run_progress(
|
||||
run=run,
|
||||
event_code='run_completed',
|
||||
summary={
|
||||
'document_id': int(document_id),
|
||||
'handoff_status': 'waiting_layout_closed',
|
||||
'deterministic_unit_count': deterministic,
|
||||
'failed_unit_count': failed,
|
||||
'review_required_unit_count': review,
|
||||
},
|
||||
commit=False,
|
||||
)
|
||||
resumed += 1
|
||||
if resumed:
|
||||
db.session.commit()
|
||||
return resumed
|
||||
|
||||
@@ -5,6 +5,7 @@ backend/app/services/shipping_notice/order_extraction_workflow.py
|
||||
依赖:MinerU 紧凑快照、订单 Profile(coordinate / xfa_dataset)、Schema 校验、
|
||||
order_extraction_route_contract、xfa_profile_*、line_field_supplement_merge、统一错误类型。
|
||||
逻辑:Worker 先调用本模块裁决;所有 PDF 先走共同视觉路径,datasets 仅在末端取正式值;
|
||||
XFA(xfa_dataset)正式值只认 datasets;OCR/坐标 confirmed 仅供点击定位,不得否决或覆盖;
|
||||
datasets 缺失或冲突时共同 OCR 仅作复核/兜底证据并强制 needs_review;
|
||||
唯一 PO 提升到 Header 后从明细剥离,避免 persist 因 scope 不匹配失败;
|
||||
路由产出 Candidate 后由 Candidate Qualification 统一评估自动建单资格;
|
||||
@@ -1691,8 +1692,63 @@ def _validate_locked_layout_fields(document: dict[str, Any], *, orders: list[dic
|
||||
)
|
||||
|
||||
|
||||
def _orders_use_xfa_dataset_formal_values(orders: list[dict[str, Any]]) -> bool:
|
||||
"""
|
||||
判断订单列表是否已携带 XFA datasets 正式值。
|
||||
|
||||
核心逻辑:任一 observation / evidence_ref / value_source 标明 xfa_dataset 即视为正式值源,
|
||||
此时坐标 confirmed 锁仅作定位参考,不得参与合并或冲突否决。
|
||||
|
||||
Args:
|
||||
orders: 单 Unit 订单列表。
|
||||
|
||||
Returns:
|
||||
True 表示应以 datasets 为准,跳过坐标 confirmed 字段合并。
|
||||
"""
|
||||
for order in orders or []:
|
||||
if not isinstance(order, dict):
|
||||
continue
|
||||
groups: list[Any] = [order.get('header_fields') or []]
|
||||
groups.extend(
|
||||
line.get('fields') or []
|
||||
for line in (order.get('lines') or [])
|
||||
if isinstance(line, dict)
|
||||
)
|
||||
for fields in groups:
|
||||
if not isinstance(fields, list):
|
||||
continue
|
||||
for field in fields:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
if str(field.get('value_source') or '') == 'xfa_dataset':
|
||||
return True
|
||||
for observation in field.get('observations') or []:
|
||||
if not isinstance(observation, dict):
|
||||
continue
|
||||
if str(observation.get('source') or observation.get('value_source') or '') == 'xfa_dataset':
|
||||
return True
|
||||
layout_evidence = observation.get('layout_evidence')
|
||||
if not isinstance(layout_evidence, dict):
|
||||
continue
|
||||
if str(layout_evidence.get('source') or '') == 'xfa_dataset':
|
||||
return True
|
||||
evidence_ref = layout_evidence.get('evidence_ref')
|
||||
if isinstance(evidence_ref, dict) and str(evidence_ref.get('source') or '') == 'xfa_dataset':
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _merge_confirmed_profile_order_fields(run: Any, *, unit: Any, orders: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""注入 confirmed 订单字段并拒绝 Provider 显式冲突;Provider 省略它们是合法的。"""
|
||||
"""
|
||||
注入 confirmed 订单字段并拒绝 Provider 显式冲突;Provider 省略它们是合法的。
|
||||
|
||||
核心逻辑:坐标模板下,confirmed 字段不可被 Provider 改写。
|
||||
XFA(datasets 正式值)订单跳过本合并——OCR/坐标 confirmed 只供点击定位,
|
||||
不得否决或覆盖 datasets(避免「b) Issue invoice to:」类标签 OCR 锁死整单)。
|
||||
"""
|
||||
# [STEP] XFA 正式值优先:坐标 confirmed 锁不得介入。
|
||||
if _orders_use_xfa_dataset_formal_values(orders):
|
||||
return orders
|
||||
locked = {
|
||||
str(item.get('field_id') or ''): item for item in _confirmed_profile_order_fields(run, unit=unit)
|
||||
if item.get('field_id')
|
||||
|
||||
@@ -5,6 +5,8 @@ services/shipping_notice/order_profile_unified_migration.py
|
||||
依赖:xfa_contract、xfa_acroform、order_document_profile_service、SQLAlchemy ORM。
|
||||
逻辑:CLI / Admin API 调用本模块;Dry Run 只产出报告与审计;Execute 生成新 Draft Revision
|
||||
并写入 before/after 审计。报告存审计 detail,不新增表字段(无 Alembic)。
|
||||
摘要 pending_visual:仅统计无 field_layout_id 且 visual_binding 未 confirmed 的 binding
|
||||
(现代 XFA 编辑器靠 order_field_layouts + field_layout_id,可不写 visual_binding)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -821,8 +823,10 @@ def summarize_unified_migration_status(
|
||||
"""
|
||||
轻量汇总模板统一 binding 迁移状态(不读 PDF / AcroForm)。
|
||||
|
||||
核心逻辑:已有 bindings[] 时统计未确认视觉框;否则对 definition 做内存转换预览
|
||||
needs_migration / pending_visual / field_diff,不写库。
|
||||
核心逻辑:已有 bindings[] 时,仅将「无 field_layout_id 且 visual_binding.status
|
||||
非 confirmed」计为待补框;已挂 field_layout_id(共享 order_field_layouts)的
|
||||
XFA 绑定视为视觉已就绪,即使缺少 visual_binding。无 bindings 时对 definition
|
||||
做内存转换预览 needs_migration / pending_visual / field_diff,不写库。
|
||||
|
||||
Args:
|
||||
definition: Profile definition_json。
|
||||
@@ -835,10 +839,12 @@ def summarize_unified_migration_status(
|
||||
mode = str(template_mode or safe_definition.get('template_mode') or 'coordinate').strip()
|
||||
bindings = [item for item in (safe_definition.get('bindings') or []) if isinstance(item, dict)]
|
||||
if bindings:
|
||||
# [STEP] 现代 XFA:field_layout_id → order_field_layouts,无需再确认 visual_binding。
|
||||
pending = sum(
|
||||
1
|
||||
for item in bindings
|
||||
if str((item.get('visual_binding') or {}).get('status') or '').strip() != 'confirmed'
|
||||
if not str(item.get('field_layout_id') or '').strip()
|
||||
and str((item.get('visual_binding') or {}).get('status') or '').strip() != 'confirmed'
|
||||
)
|
||||
status = 'ready' if pending == 0 else 'pending_visual'
|
||||
return {
|
||||
|
||||
@@ -50,7 +50,7 @@ class OrderProfileValueAdapter:
|
||||
def business_fingerprint(self, definition: dict[str, Any]) -> str | None: return self._call('business_fingerprint', definition)
|
||||
def record_mapping_audit(self, **context: Any) -> None: self._call('record_mapping_audit', **context)
|
||||
def identity_summary(self, summary: dict[str, Any], snapshot: dict[str, Any]) -> dict[str, Any]: return self._call('identity_summary', summary, snapshot)
|
||||
def mapping_field_tree(self, *, document_id: int, actor_id: int | None) -> dict[str, Any]: return self._call('mapping_field_tree', document_id=document_id, actor_id=actor_id)
|
||||
def mapping_field_tree(self, *, document_id: int, actor_id: int | None, include_full_values: bool = False) -> dict[str, Any]: return self._call('mapping_field_tree', document_id=document_id, actor_id=actor_id, include_full_values=include_full_values)
|
||||
def mapping_collections(self, *, document_id: int, actor_id: int | None) -> dict[str, Any]: return self._call('mapping_collections', document_id=document_id, actor_id=actor_id)
|
||||
def mapping_value_preview(self, *, document_id: int, path_id: str, actor_id: int | None, include_full_value: bool) -> dict[str, Any]: return self._call('mapping_value_preview', document_id=document_id, path_id=path_id, actor_id=actor_id, include_full_value=include_full_value)
|
||||
def mapping_split_preview(self, **context: Any) -> dict[str, Any]: return self._call('mapping_split_preview', **context)
|
||||
|
||||
@@ -3,6 +3,15 @@
|
||||
用途:在共同视觉/OCR 解析完成后,以 XFA datasets 作为正式字段值并提供交叉校验。
|
||||
依赖:共同 Route 的视觉匹配与 coordinate/OCR 提取,以及 document_layout 的 XFA datasets 解析。
|
||||
逻辑:本模块绝不另行选择模板或推进业务状态;先直接调用共同 OCR 提取,最后覆盖正式值。
|
||||
normalize_definition 须回填 order_field_layouts.field_id(画布常交空串),与表内 field_regions 一致。
|
||||
发布门禁 shared_layout_ids:优先 field.region_id,无则回退 parent:field_code。
|
||||
盲测 rows:剔除挂到每行的 header field_code(与 _field_preview_rows 对齐);空视觉
|
||||
reservation 不得冲掉 datasets 单头值。
|
||||
OCR↔datasets 对照仅为诊断,不得写入盲测 reason_codes / 样本验证失败 / 正式抽取 fallback。
|
||||
盲测硬门禁只认 datasets 抽取状态与 reason_codes;visual/mirror/evidence 指标仅展示。
|
||||
发布 path 覆盖:line.reservation_id 可由 header 映射或 reservation_id_region 覆盖
|
||||
(与 runtime compute_effective_reservation_id 一致),不强制再绑行级 datasets path。
|
||||
正式抽取:datasets 通过后剔除 OCR 侧 PARSE_STRATEGY_* 等 fallback,不得否决正式值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -232,7 +241,26 @@ def normalize_definition(raw: dict[str, Any], *, schema_version: Any, path_conte
|
||||
# 共同视觉布局仍须冻结 Schema field_id,即使 XFA 的正式值来自 datasets。
|
||||
# 表头文字(ITEM/QTY 等)可映射到 Line Schema 字段,因而 header_layouts 与
|
||||
# line_layouts 必须使用同一套 scope/code 规范化;否则保存后快照无法证明字段身份。
|
||||
shared_layouts = [item for item in (raw.get('order_field_layouts') or []) if isinstance(item, dict)]
|
||||
# order_field_layouts 同样回填 field_id:画布常提交空串,盲测 _definition_contract
|
||||
# 虽可临时候补,但持久化定义必须自洽,避免旧进程/旁路仍读到 '' 触发契约失败。
|
||||
order_field_layouts: list[dict[str, Any]] = []
|
||||
for item in raw.get('order_field_layouts') or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
layout = dict(item)
|
||||
scope = str(layout.get('scope') or 'header').strip() or 'header'
|
||||
field_code = str(layout.get('field_code') or '').strip()
|
||||
schema_field = profile_fields.get((scope, field_code))
|
||||
if schema_field is None:
|
||||
raise ValidationError(
|
||||
'Order field binding must target a header Schema field',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
details={'field_code': field_code or None, 'scope': scope},
|
||||
)
|
||||
layout['field_id'] = str(schema_field['field_id'])
|
||||
layout['scope'] = scope
|
||||
order_field_layouts.append(layout)
|
||||
shared_layouts = list(order_field_layouts)
|
||||
for table in raw.get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
@@ -332,7 +360,7 @@ def normalize_definition(raw: dict[str, Any], *, schema_version: Any, path_conte
|
||||
segment['target_field_id'] = str(field['field_id']); rule['segment'] = segment
|
||||
rules.append(dumped)
|
||||
cross = raw.get('cross_checks') if isinstance(raw.get('cross_checks'), dict) else {}
|
||||
payload = {'template_mode': 'xfa_dataset', 'main_table_id': str(raw.get('main_table_id') or '').strip() or None, 'document_match': raw.get('document_match'), 'table_regions': raw.get('table_regions') or [], 'order_field_layouts': raw.get('order_field_layouts') or [], 'draft_unbound_order_field_layouts': raw.get('draft_unbound_order_field_layouts') or [], 'source_contract': {'template_packet_checksum': template_checksum, 'dataset_structure_fingerprint': fingerprint, 'dataset_root_path': root_path, 'authoritative_line_collection_path': auth_path or None, 'mirror_collection_paths': mirrors}, 'header_mappings': [], 'line_mapping': {'row_path': auth_path or None, 'fields': []}, 'cross_checks': {'acroform_enabled': bool(cross.get('acroform_enabled', True)), 'mirror_collection_policy': str(cross.get('mirror_collection_policy') or 'must_match_when_present'), 'line_amount_formula': str(cross.get('line_amount_formula') or 'quantity_times_unit_price'), 'total_amount_policy': str(cross.get('total_amount_policy') or 'must_equal_line_sum')}, 'split_rules': rules, 'bindings': [rewrite_binding(item) for item in bindings_raw]}
|
||||
payload = {'template_mode': 'xfa_dataset', 'main_table_id': str(raw.get('main_table_id') or '').strip() or None, 'document_match': raw.get('document_match'), 'table_regions': raw.get('table_regions') or [], 'order_field_layouts': order_field_layouts, 'draft_unbound_order_field_layouts': raw.get('draft_unbound_order_field_layouts') or [], 'source_contract': {'template_packet_checksum': template_checksum, 'dataset_structure_fingerprint': fingerprint, 'dataset_root_path': root_path, 'authoritative_line_collection_path': auth_path or None, 'mirror_collection_paths': mirrors}, 'header_mappings': [], 'line_mapping': {'row_path': auth_path or None, 'fields': []}, 'cross_checks': {'acroform_enabled': bool(cross.get('acroform_enabled', True)), 'mirror_collection_policy': str(cross.get('mirror_collection_policy') or 'must_match_when_present'), 'line_amount_formula': str(cross.get('line_amount_formula') or 'quantity_times_unit_price'), 'total_amount_policy': str(cross.get('total_amount_policy') or 'must_equal_line_sum')}, 'split_rules': rules, 'bindings': [rewrite_binding(item) for item in bindings_raw]}
|
||||
try:
|
||||
return validate_xfa_dataset_definition(payload).model_dump(mode='json')
|
||||
except (TypeError, ValueError) as exc:
|
||||
@@ -478,8 +506,17 @@ def identity_summary(summary: dict[str, Any], _snapshot: dict[str, Any]) -> dict
|
||||
return {'adapter': 'xfa_dataset', 'template_packet_checksum': summary.get('template_packet_checksum'), 'dataset_structure_fingerprint': summary.get('dataset_structure_fingerprint'), 'parser_identity': summary.get('parser_identity'), 'analysis_count': summary.get('analysis_count')}
|
||||
|
||||
|
||||
def mapping_field_tree(*, document_id: int, actor_id: int | None) -> dict[str, Any]:
|
||||
"""返回 datasets 字段树;仅供末端映射工作区使用。"""
|
||||
def mapping_field_tree(
|
||||
*,
|
||||
document_id: int,
|
||||
actor_id: int | None,
|
||||
include_full_values: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""返回 datasets 字段树;仅供末端映射工作区使用。
|
||||
|
||||
include_full_values=True 时写入完整 sample_value_display,供管理端字段选型;
|
||||
仍不输出 raw_value 键,并由上游要求 audit_sensitive_read。
|
||||
"""
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import FileAsset, ShippingOrderDocument, ShippingOrderDocumentProfileAudit
|
||||
@@ -500,12 +537,23 @@ def mapping_field_tree(*, document_id: int, actor_id: int | None) -> dict[str, A
|
||||
asset = db.session.get(FileAsset, int(document.asset_id or 0)) if document.asset_id else None
|
||||
if asset is None:
|
||||
raise ValidationError('Value-source sample asset is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_UNAVAILABLE', details={'document_id': int(document.id), 'reason': 'asset_missing'})
|
||||
payload = rebuild_tree_dto_from_analysis(analysis, read_asset_bytes(asset), include_values=True)
|
||||
reveal = bool(include_full_values)
|
||||
payload = rebuild_tree_dto_from_analysis(
|
||||
analysis,
|
||||
read_asset_bytes(asset),
|
||||
include_values=True,
|
||||
include_full_values=reveal,
|
||||
)
|
||||
append_shipping_audit_event(
|
||||
event_type='xfa_field_tree_accessed', aggregate_type='shipping_notice_document',
|
||||
aggregate_id=str(document.id), document_id=document.id, actor_type='admin', actor_id=actor_id,
|
||||
result='success', action='mapping_field_tree', sensitivity_level='internal',
|
||||
after={'analysis_id': analysis.id, 'layout_version_id': int(layout_version.id)},
|
||||
result='success', action='mapping_field_tree',
|
||||
sensitivity_level='sensitive' if reveal else 'internal',
|
||||
after={
|
||||
'analysis_id': analysis.id,
|
||||
'layout_version_id': int(layout_version.id),
|
||||
'full_values_revealed': reveal,
|
||||
},
|
||||
)
|
||||
return sanitize_xfa_dto(payload)
|
||||
|
||||
@@ -1071,13 +1119,89 @@ def _field_preview_rows(*, extraction: Any, validation: Any) -> dict[str, Any]:
|
||||
return {'header_fields': header_fields, 'lines': lines, 'cross_checks': dict(getattr(validation, 'cross_check_summary', None) or {})}
|
||||
|
||||
|
||||
def _blind_rows_excluding_header_fields(
|
||||
*,
|
||||
extraction: Any,
|
||||
json_value,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
将提取行投影为盲测 rows;表头字段只进 order_fields,不进明细 JSON。
|
||||
|
||||
核心逻辑:正式提取会把 header 挂到每行供建单聚合,盲测复核必须与
|
||||
`_field_preview_rows` 一样剔除这些 header field_code。
|
||||
|
||||
Args:
|
||||
extraction: extract_xfa_profile 结果。
|
||||
json_value: 值序列化函数(通常 quality_service._json_value)。
|
||||
|
||||
Returns:
|
||||
仅含明细 field_code 的行字典列表。
|
||||
"""
|
||||
header_codes = {
|
||||
str(item.field_code or '')
|
||||
for item in (getattr(extraction, 'header_fields', None) or [])
|
||||
if str(getattr(item, 'field_code', '') or '')
|
||||
}
|
||||
rows: list[dict[str, Any]] = []
|
||||
for row in getattr(extraction, 'rows', None) or []:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
projected = {
|
||||
str(field['field_code']): json_value(field.get('value'))
|
||||
for field in (row.get('fields') or [])
|
||||
if isinstance(field, dict)
|
||||
and field.get('field_code')
|
||||
and str(field.get('field_code') or '') not in header_codes
|
||||
}
|
||||
if projected:
|
||||
rows.append(projected)
|
||||
return rows
|
||||
|
||||
|
||||
def _merge_visual_reservation_into_blind_candidate(
|
||||
*,
|
||||
datasets_candidate: dict[str, Any],
|
||||
visual_candidate: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
将视觉 Reservation 专区结果并入盲测候选(原地修改)。
|
||||
|
||||
核心逻辑:仅当视觉侧有非空 reservation_id 时覆盖 datasets;空视觉结果不得
|
||||
冲掉已抽取的单头值(否则复核卡显示「未识别到值」而明细 JSON 仍有值)。
|
||||
"""
|
||||
visual_reservation_headers = [
|
||||
item for item in visual_candidate.get('order_fields') or []
|
||||
if isinstance(item, dict)
|
||||
and item.get('field_code') == 'reservation_id'
|
||||
and item.get('value') not in (None, '')
|
||||
]
|
||||
if visual_reservation_headers:
|
||||
datasets_candidate['order_fields'] = [
|
||||
item for item in datasets_candidate['order_fields']
|
||||
if not (item.get('field_code') == 'reservation_id' and item.get('scope') == 'header')
|
||||
] + visual_reservation_headers
|
||||
for index, visual_row in enumerate(visual_candidate.get('rows') or []):
|
||||
if index >= len(datasets_candidate['rows']) or not isinstance(visual_row, dict):
|
||||
continue
|
||||
if visual_row.get('reservation_id') not in (None, ''):
|
||||
datasets_candidate['rows'][index]['reservation_id'] = visual_row['reservation_id']
|
||||
|
||||
|
||||
def _clip_diagnostic_value(value: Any, *, limit: int = 160) -> str:
|
||||
"""将对照诊断值截断为可展示短文本(管理端定位差异,不无限回传长原文)。"""
|
||||
text = str(value if value is not None else '').strip()
|
||||
if len(text) <= limit:
|
||||
return text
|
||||
return f'{text[: max(0, limit - 1)]}…'
|
||||
|
||||
|
||||
def _validation_evidence_cross_check(
|
||||
*, visual_evidence: dict[str, Any], datasets_evidence: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""对共同 OCR 验证证据与 datasets 正式字段做脱敏交叉裁决。
|
||||
"""对共同 OCR 验证证据与 datasets 正式字段做交叉裁决。
|
||||
|
||||
OCR 不产生正式值;这里只返回可审计的字段位置,任何同字段冲突均由调用方
|
||||
转成 Review/验证失败。没有共同 OCR 字段时明确为 unavailable,不能伪造一致。
|
||||
OCR 不产生正式值;返回字段位置及两侧截断展示值,供管理端标明「哪里不一样」。
|
||||
没有共同 OCR 字段时明确为 unavailable,不能伪造一致。
|
||||
"""
|
||||
def values(evidence: dict[str, Any]) -> dict[tuple[str, int | None, str], str]:
|
||||
result: dict[tuple[str, int | None, str], str] = {}
|
||||
@@ -1098,16 +1222,26 @@ def _validation_evidence_cross_check(
|
||||
|
||||
visual_values, dataset_values = values(visual_evidence), values(datasets_evidence)
|
||||
shared = sorted(set(visual_values).intersection(dataset_values))
|
||||
mismatches = [
|
||||
{'scope': scope, 'row_index': row_index, 'field_code': field_code}
|
||||
for scope, row_index, field_code in shared
|
||||
if visual_values[(scope, row_index, field_code)] != dataset_values[(scope, row_index, field_code)]
|
||||
]
|
||||
mismatches = []
|
||||
for scope, row_index, field_code in shared:
|
||||
left = visual_values[(scope, row_index, field_code)]
|
||||
right = dataset_values[(scope, row_index, field_code)]
|
||||
if left == right:
|
||||
continue
|
||||
mismatches.append({
|
||||
'scope': scope,
|
||||
'row_index': row_index,
|
||||
'field_code': field_code,
|
||||
'ocr_value': _clip_diagnostic_value(left),
|
||||
'datasets_value': _clip_diagnostic_value(right),
|
||||
})
|
||||
if len(mismatches) >= 20:
|
||||
break
|
||||
return {
|
||||
'status': 'mismatched' if mismatches else ('matched' if shared else 'unavailable'),
|
||||
'compared_field_count': len(shared),
|
||||
'mismatch_count': len(mismatches),
|
||||
'mismatches': mismatches[:20],
|
||||
'mismatches': mismatches,
|
||||
}
|
||||
|
||||
|
||||
@@ -1184,13 +1318,15 @@ def extract_current_sample(*, profile: Any, sample: Any, actor_id: int | None) -
|
||||
ocr_comparison = _validation_evidence_cross_check(
|
||||
visual_evidence=visual_evidence, datasets_evidence=preview,
|
||||
)
|
||||
if ocr_comparison['status'] == 'mismatched':
|
||||
failures.append('ocr_datasets_mismatch')
|
||||
summary['cross_check_failures'] = list(dict.fromkeys(
|
||||
list(summary.get('cross_check_failures') or []) + ['ocr_datasets_mismatch'],
|
||||
))
|
||||
status = 'failed'
|
||||
summary.update({'header_fields': preview['header_fields'], 'lines': preview['lines'], 'validation_evidence': preview, 'visual_validation_evidence': visual_evidence, 'visual_validation_status': visual_status, 'ocr_datasets_cross_check': ocr_comparison})
|
||||
# XFA:datasets 为正式值;OCR 仅定位/旁路对照。不一致写入诊断,不否决样本验证。
|
||||
summary.update({
|
||||
'header_fields': preview['header_fields'],
|
||||
'lines': preview['lines'],
|
||||
'validation_evidence': preview,
|
||||
'visual_validation_evidence': visual_evidence,
|
||||
'visual_validation_status': visual_status,
|
||||
'ocr_datasets_cross_check': ocr_comparison,
|
||||
})
|
||||
if status == 'passed' and extraction.status != 'parsed':
|
||||
summary['failure_code'] = (extraction.reason_codes or ['xfa_required_field_missing'])[0]
|
||||
return 'failed', summary, {}
|
||||
@@ -1339,31 +1475,21 @@ def blind_candidate(*, profile: Any, sample: Any) -> dict[str, Any]:
|
||||
field_ids = {str(item.get('field_id') or '') for item in (schema_definition.get('fields') or []) if isinstance(item, dict) and item.get('enabled', True) and item.get('field_id')}
|
||||
validation = validate_xfa_extraction(raw_profile=raw_profile, dataset_analysis=outcome.dataset_analysis, extraction=extraction, pdf_bytes=pdf_bytes, schema_field_ids=field_ids)
|
||||
metrics = build_xfa_validation_metrics(definition=definition, extraction=extraction, cross_check_summary=validation.cross_check_summary, schema_field_ids=field_ids)
|
||||
rows = [{str(field['field_code']): quality_service._json_value(field.get('value')) for field in row.get('fields') or [] if isinstance(field, dict) and field.get('field_code')} for row in extraction.rows]
|
||||
datasets_candidate = {'order_fields': [{'field_code': item.field_code, 'value': quality_service._json_value(item.normalized_value), 'status': 'confirmed' if item.normalized_value not in (None, '') and not item.issues else 'failed', 'field_id': item.field_id, 'scope': 'header', 'page_no': 1, 'issues': list(item.issues)} for item in extraction.header_fields], 'rows': [row for row in rows if row]}
|
||||
# 正式提取会把 header 挂到每行;盲测复核与验证页一致,明细 rows 剔除表头 field_code。
|
||||
rows = _blind_rows_excluding_header_fields(
|
||||
extraction=extraction, json_value=quality_service._json_value,
|
||||
)
|
||||
datasets_candidate = {'order_fields': [{'field_code': item.field_code, 'value': quality_service._json_value(item.normalized_value), 'status': 'confirmed' if item.normalized_value not in (None, '') and not item.issues else 'failed', 'field_id': item.field_id, 'scope': 'header', 'page_no': 1, 'issues': list(item.issues)} for item in extraction.header_fields], 'rows': rows}
|
||||
# Reservation 专用证据区不是 XFA 的拆分映射:它和坐标模板盲测共用同一解析器。
|
||||
# 视觉候选中的整单值与指定行覆盖值应参与最终 blind candidate,避免盲测与正式
|
||||
# 公共建单路径出现不同结果。
|
||||
visual_reservation_headers = [
|
||||
item for item in visual_candidate.get('order_fields') or []
|
||||
if isinstance(item, dict) and item.get('field_code') == 'reservation_id'
|
||||
]
|
||||
if visual_reservation_headers:
|
||||
datasets_candidate['order_fields'] = [
|
||||
item for item in datasets_candidate['order_fields']
|
||||
if not (item.get('field_code') == 'reservation_id' and item.get('scope') == 'header')
|
||||
] + visual_reservation_headers
|
||||
for index, visual_row in enumerate(visual_candidate.get('rows') or []):
|
||||
if index >= len(datasets_candidate['rows']) or not isinstance(visual_row, dict):
|
||||
continue
|
||||
if visual_row.get('reservation_id') not in (None, ''):
|
||||
datasets_candidate['rows'][index]['reservation_id'] = visual_row['reservation_id']
|
||||
# 仅非空视觉结果可覆盖 datasets,避免空视觉冲掉已抽取的单头 reservation_id。
|
||||
_merge_visual_reservation_into_blind_candidate(
|
||||
datasets_candidate=datasets_candidate, visual_candidate=visual_candidate,
|
||||
)
|
||||
ocr_comparison = _blind_candidate_cross_check(
|
||||
visual_candidate=visual_candidate, datasets_candidate=datasets_candidate,
|
||||
)
|
||||
# XFA:datasets 正式抽取失败才进 reason_codes;OCR↔datasets 不一致仅诊断,不硬拦盲测。
|
||||
reason_codes = list(extraction.reason_codes or []) + list(validation.reason_codes or [])
|
||||
if ocr_comparison['status'] == 'mismatched':
|
||||
reason_codes.append('ocr_datasets_mismatch')
|
||||
return {
|
||||
'document_id': document.id, 'table_id': visual_table_id, **datasets_candidate,
|
||||
'extraction_status': extraction.status, 'reason_codes': reason_codes,
|
||||
@@ -1380,12 +1506,32 @@ def blind_candidate(*, profile: Any, sample: Any) -> dict[str, Any]:
|
||||
|
||||
|
||||
def blind_gate_failures(*, candidate: dict[str, Any], sample_id: int) -> tuple[list[str], dict[str, float]]:
|
||||
"""校验 datasets 正式值的视觉覆盖、镜像与留痕完整性。"""
|
||||
visual, mirror, evidence = float(candidate.get('visual_coverage_rate') or 0.0), float(candidate.get('mirror_consistency_rate') or 0.0), float(candidate.get('evidence_retention_rate') or 0.0)
|
||||
failures = ([f'sample:{sample_id}:visual_coverage_insufficient'] if visual < 1.0 else []) + ([f'sample:{sample_id}:mirror_consistency_insufficient'] if mirror < 1.0 else []) + ([f'sample:{sample_id}:evidence_retention_insufficient'] if evidence < 1.0 else [])
|
||||
"""
|
||||
XFA 盲测硬门禁:只拦 datasets 正式抽取失败,不拦视觉/OCR/镜像指标。
|
||||
|
||||
核心逻辑:visual_coverage / mirror_consistency / evidence_retention 仍回传供
|
||||
管理端展示与 soft 诊断;正式对账以 datasets 抽取 status/reason_codes 为准。
|
||||
OCR↔datasets 不一致由公共 execute_suite 写入 soft_diagnostics,不经本函数。
|
||||
|
||||
Args:
|
||||
candidate: blind_candidate 产出(须含 extraction_status / reason_codes / 指标)。
|
||||
sample_id: 盲测样本主键,用于失败码前缀。
|
||||
|
||||
Returns:
|
||||
(硬失败码列表, 指标字典)。指标 < 1.0 不产生硬失败。
|
||||
"""
|
||||
visual = float(candidate.get('visual_coverage_rate') or 0.0)
|
||||
mirror = float(candidate.get('mirror_consistency_rate') or 0.0)
|
||||
evidence = float(candidate.get('evidence_retention_rate') or 0.0)
|
||||
failures: list[str] = []
|
||||
# [STEP 1] 仅 datasets 抽取失败硬拦;视觉定位/镜像/留痕不否决盲测通过。
|
||||
if candidate.get('extraction_status') != 'parsed' or candidate.get('reason_codes'):
|
||||
failures.append(f"sample:{sample_id}:extraction:{(candidate.get('reason_codes') or ['failed'])[0]}")
|
||||
return failures, {'visual_coverage_rate': visual, 'mirror_consistency_rate': mirror, 'evidence_retention_rate': evidence}
|
||||
return failures, {
|
||||
'visual_coverage_rate': visual,
|
||||
'mirror_consistency_rate': mirror,
|
||||
'evidence_retention_rate': evidence,
|
||||
}
|
||||
|
||||
|
||||
def _blocking_shared_field_labels(*, definition: dict[str, Any], schema_field_ids: set[str]) -> list[dict[str, Any]]:
|
||||
@@ -1406,9 +1552,8 @@ def _blocking_shared_field_labels(*, definition: dict[str, Any], schema_field_id
|
||||
if not bindings:
|
||||
return blocking
|
||||
formal_ids = collect_formal_schema_field_ids(definition, schema_field_ids=schema_field_ids or None)
|
||||
# 共同视觉标签既包含订单抬头值框,也包含每个明细行的字段框。XFA binding 的
|
||||
# field_layout_id 使用 `${line_layout_id}:${field_code}`,必须按相同身份验证,
|
||||
# 否则明细 datasets 映射会被错误要求创建一个无关的抬头框。
|
||||
# 共同视觉标签:优先 field.region_id(画布框稳定身份);无 region_id 时回退
|
||||
# legacy `${parent_layout_id}:{field_code}`。表头/明细 field_regions 均计入。
|
||||
shared_layout_ids = {
|
||||
str(item.get('layout_id') or '')
|
||||
for item in (definition.get('order_field_layouts') or [])
|
||||
@@ -1417,18 +1562,20 @@ def _blocking_shared_field_labels(*, definition: dict[str, Any], schema_field_id
|
||||
for table in definition.get('table_regions') or []:
|
||||
if not isinstance(table, dict):
|
||||
continue
|
||||
for line in table.get('line_layouts') or []:
|
||||
if not isinstance(line, dict):
|
||||
continue
|
||||
line_layout_id = str(line.get('layout_id') or '').strip()
|
||||
if not line_layout_id:
|
||||
continue
|
||||
for field in line.get('field_regions') or []:
|
||||
if not isinstance(field, dict):
|
||||
for layout_key in ('header_layouts', 'line_layouts'):
|
||||
for layout in table.get(layout_key) or []:
|
||||
if not isinstance(layout, dict):
|
||||
continue
|
||||
field_code = str(field.get('field_code') or '').strip()
|
||||
if field_code:
|
||||
shared_layout_ids.add(f'{line_layout_id}:{field_code}')
|
||||
parent_layout_id = str(layout.get('layout_id') or '').strip()
|
||||
for field in layout.get('field_regions') or []:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
region_id = str(field.get('region_id') or '').strip()
|
||||
field_code = str(field.get('field_code') or '').strip()
|
||||
if region_id:
|
||||
shared_layout_ids.add(region_id)
|
||||
elif parent_layout_id and field_code:
|
||||
shared_layout_ids.add(f'{parent_layout_id}:{field_code}')
|
||||
publishable: dict[str, bool] = {}
|
||||
for raw in bindings:
|
||||
if not isinstance(raw, dict):
|
||||
@@ -1463,10 +1610,57 @@ def _blocking_validation_metrics(summary: dict[str, Any]) -> list[dict[str, Any]
|
||||
]
|
||||
|
||||
|
||||
def _extend_mapped_ids_with_reservation_coverage(
|
||||
*,
|
||||
definition: dict[str, Any],
|
||||
schema_fields: dict[str, dict[str, Any]],
|
||||
mapped_ids: set[str],
|
||||
) -> set[str]:
|
||||
"""
|
||||
将 Reservation 覆盖规则并入已映射 field_id 集合。
|
||||
|
||||
核心逻辑:与 Schema Runtime ``compute_effective_reservation_id`` 对齐——
|
||||
行级 reservation_id 可回退到头字段;``reservation_id_region`` 可同时覆盖头/行。
|
||||
XFA 模板通常只绑 header datasets path(如 SHIPMENT_TEXT),不得再强制行级 path。
|
||||
|
||||
Args:
|
||||
definition: Profile definition。
|
||||
schema_fields: 启用中的 Schema field_id → 配置。
|
||||
mapped_ids: 已由 bindings/拆分覆盖的 field_id。
|
||||
|
||||
Returns:
|
||||
扩展后的 mapped_ids(新集合,不修改入参)。
|
||||
"""
|
||||
covered = set(mapped_ids)
|
||||
header_ids = {
|
||||
field_id
|
||||
for field_id, cfg in schema_fields.items()
|
||||
if str(cfg.get('field_code') or '') == 'reservation_id'
|
||||
and str(cfg.get('scope') or '') == 'header'
|
||||
}
|
||||
line_ids = {
|
||||
field_id
|
||||
for field_id, cfg in schema_fields.items()
|
||||
if str(cfg.get('field_code') or '') == 'reservation_id'
|
||||
and str(cfg.get('scope') or '') == 'line'
|
||||
}
|
||||
region = definition.get('reservation_id_region')
|
||||
has_region = isinstance(region, dict) and bool(region)
|
||||
# [STEP 1] 专区存在时:头/行 reservation 均视为已有正式取值路径(专区解析,非 OCR)。
|
||||
if has_region:
|
||||
covered |= header_ids | line_ids
|
||||
return covered
|
||||
# [STEP 2] 仅有头 datasets 映射时:行级建单键可回退头值,记入已覆盖。
|
||||
if header_ids & covered:
|
||||
covered |= line_ids
|
||||
return covered
|
||||
|
||||
|
||||
def publish_checks(profile: Any, *, validation: Any | None) -> list[dict[str, Any]]:
|
||||
"""执行 datasets 值源的既有发布门禁,不参与共同发布生命周期。
|
||||
|
||||
核心逻辑:沿用已发布的路径、集合、拆分规则、共同视觉绑定及当前样本对账门禁;
|
||||
line.reservation_id 可由 header 映射或 reservation_id_region 覆盖;
|
||||
调用方只接收稳定 blocking_items,不能在公共服务判断 XFA。
|
||||
"""
|
||||
definition = dict(profile.definition_json or {})
|
||||
@@ -1508,6 +1702,10 @@ def publish_checks(profile: Any, *, validation: Any | None) -> list[dict[str, An
|
||||
for rule in rule_set.rules:
|
||||
if rule.segment.handling == 'mapped' and rule.segment.target_field_id:
|
||||
mapped_ids.add(str(rule.segment.target_field_id))
|
||||
# [STEP] Reservation:头 path / 专区即可覆盖行级建单键,与 runtime 回退口径一致。
|
||||
mapped_ids = _extend_mapped_ids_with_reservation_coverage(
|
||||
definition=definition, schema_fields=schema_fields, mapped_ids=mapped_ids,
|
||||
)
|
||||
missing_fields = [
|
||||
{
|
||||
'field_id': field_id,
|
||||
@@ -1559,21 +1757,60 @@ def _field_values(table: dict[str, Any] | None) -> dict[tuple[int, str], str]:
|
||||
return values
|
||||
|
||||
|
||||
def _fallback_codes_after_datasets_success(codes: list[Any] | None) -> list[str]:
|
||||
"""
|
||||
datasets 正式抽取与校验已通过时,剔除仅反映 OCR/视觉侧的 fallback 码。
|
||||
|
||||
核心逻辑:共同视觉路径可能留下 PARSE_STRATEGY_* / 无表/多表/坐标证据不可用;
|
||||
这些不能否决已通过的 datasets 正式值。其它码原样保留。
|
||||
|
||||
Args:
|
||||
codes: OCR 决策上遗留的 fallback_reason_codes。
|
||||
|
||||
Returns:
|
||||
过滤后的稳定码列表(去空、保序)。
|
||||
"""
|
||||
drop = {
|
||||
'business_table_not_found',
|
||||
'multiple_business_tables',
|
||||
'ocr_datasets_mismatch',
|
||||
'coordinate_evidence_unavailable',
|
||||
}
|
||||
kept: list[str] = []
|
||||
for raw in codes or []:
|
||||
code = str(raw or '').strip()
|
||||
if not code:
|
||||
continue
|
||||
if code in drop or code.startswith('PARSE_STRATEGY_'):
|
||||
continue
|
||||
kept.append(code)
|
||||
return kept
|
||||
|
||||
|
||||
def _ocr_cross_check(*, ocr_table: dict[str, Any] | None, datasets_table: dict[str, Any]) -> dict[str, Any]:
|
||||
"""对照两种值源的重叠字段,输出数量与差异定位但不写入业务字段原文。"""
|
||||
"""对照两种值源的重叠字段;输出定位与两侧截断值,供诊断,不否决 datasets 正式结果。"""
|
||||
ocr_values = _field_values(ocr_table)
|
||||
dataset_values = _field_values(datasets_table)
|
||||
shared = sorted(set(ocr_values).intersection(dataset_values))
|
||||
mismatches = [
|
||||
{'row_index': row_index, 'field_id': field_id}
|
||||
for row_index, field_id in shared
|
||||
if ocr_values[(row_index, field_id)] != dataset_values[(row_index, field_id)]
|
||||
]
|
||||
mismatches = []
|
||||
for row_index, field_id in shared:
|
||||
left = ocr_values[(row_index, field_id)]
|
||||
right = dataset_values[(row_index, field_id)]
|
||||
if left == right:
|
||||
continue
|
||||
mismatches.append({
|
||||
'row_index': row_index,
|
||||
'field_id': field_id,
|
||||
'ocr_value': _clip_diagnostic_value(left),
|
||||
'datasets_value': _clip_diagnostic_value(right),
|
||||
})
|
||||
if len(mismatches) >= 20:
|
||||
break
|
||||
return {
|
||||
'status': 'mismatched' if mismatches else ('matched' if shared else 'unavailable'),
|
||||
'compared_field_count': len(shared),
|
||||
'mismatch_count': len(mismatches),
|
||||
'mismatches': mismatches[:20],
|
||||
'mismatches': mismatches,
|
||||
}
|
||||
|
||||
|
||||
@@ -1585,7 +1822,8 @@ def extract(
|
||||
"""从 XFA datasets 解析正式值,并直接复用共同 OCR/视觉提取作双向校验。
|
||||
|
||||
核心逻辑:共同 OCR 先产出相同视觉表与字段证据;datasets 仅在最后覆盖正式字段值。
|
||||
datasets 缺失或与 OCR 冲突时仍保留 OCR 证据,但写入 Review 原因码,不能直通。
|
||||
datasets 完整通过后剔除 OCR 侧 PARSE_STRATEGY_* / 无表等 fallback,不得否决正式值;
|
||||
datasets 缺失或业务校验失败时仍强制 Review,禁止 OCR 静默直通。
|
||||
|
||||
Args:
|
||||
run: 冻结的订单抽取运行。
|
||||
@@ -1731,15 +1969,10 @@ def extract(
|
||||
}
|
||||
comparison = _ocr_cross_check(ocr_table=ocr_result.table, datasets_table=table)
|
||||
decision['ocr_datasets_cross_check'] = comparison
|
||||
# OCR 作为共同视觉证据:若 datasets 已完整通过,它的“未找到/多表”只说明
|
||||
# 无法交叉比对,不能替代 datasets 否决最终字段。真正的 datasets 身份、映射和
|
||||
# 业务校验失败均已在上方 fail-closed。
|
||||
decision['fallback_reason_codes'] = [
|
||||
code for code in (decision.get('fallback_reason_codes') or [])
|
||||
if str(code) not in {'business_table_not_found', 'multiple_business_tables'}
|
||||
]
|
||||
if comparison['status'] == 'mismatched':
|
||||
decision['fallback_reason_codes'] = ['ocr_datasets_mismatch']
|
||||
# OCR 作为共同视觉证据:datasets 已完整通过时,视觉行重建/无表等码不得否决正式值。
|
||||
decision['fallback_reason_codes'] = _fallback_codes_after_datasets_success(
|
||||
decision.get('fallback_reason_codes'),
|
||||
)
|
||||
return workflow.ValueAdapterExtractionResult(
|
||||
decision=decision, table=table,
|
||||
evidence={'formal_evidence_summary': extraction.evidence_summary, 'value_source_identity': decision['xfa_structure']},
|
||||
|
||||
@@ -1160,9 +1160,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
|
||||
'Customer is not confirmed',
|
||||
code='SHIPPING.REVIEW_CUSTOMER_UNRESOLVED',
|
||||
)
|
||||
# Candidate normalization adds fulfillment-only derived fields such as
|
||||
# effective_reservation_id. Extraction is the frozen Schema record and
|
||||
# must receive the unmodified reviewed summary for strict field checks.
|
||||
# Candidate normalization 还会附加 fulfillment 派生字段(如 effective_reservation_id)。
|
||||
# Extraction 只物化 Schema 业务字段;行级 reservation_id 已由
|
||||
# build_confirmable_draft_summary 按表头回退写回,此处仍传 summary 而非 normalized。
|
||||
normalized = normalize_candidate_business_summary(summary)
|
||||
extraction = _materialize_extraction(case=case, intake_id=int(intake.id), summary=summary, actor_id=int(user_id))
|
||||
candidate = _create_review_candidate(
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
services/shipping_notice/order_review_draft_service.py
|
||||
|
||||
用途:建单前订单复核草稿的编辑、校验与统一审计;含库存源路由重算、采用建议与保留人工决定。
|
||||
依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则、order_build_eligibility_service、
|
||||
依赖:Review Case/Draft、Run 冻结 Schema、订单字段规则(含 compute_effective_reservation_id)、
|
||||
order_build_eligibility_service、
|
||||
candidate_qualification_service.resolve_review_case_customer_resolved、
|
||||
fulfillment_audit、order_review_progress_bridge、process_gate_bridge、
|
||||
workflow_ledger_service.assert_case_is_current_workflow_version。
|
||||
@@ -10,6 +11,8 @@ services/shipping_notice/order_review_draft_service.py
|
||||
追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流;
|
||||
Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计;
|
||||
整单校验汇总客户确认、有效 Reservation、行级库存源候选与自动建单资格;
|
||||
行级必填 reservation_id 空值时先回退表头(与建单资格 / Schema Runtime 一致),再报缺失;
|
||||
确认建单摘要同样回填行级 reservation_id,供物化 FieldValue / 冻结门禁消费;
|
||||
履约波次确认经 build_confirmable_draft_summary(draft_line_ids) 仅对选中行重算 validation;
|
||||
库存路由恢复使用最新已发布规则与库存源启停,不重新识别 PDF,不静默覆盖人工决定;
|
||||
路由恢复幂等键写入 Draft 历史集合(非仅最近一次),旧键重试可安全重放;
|
||||
@@ -47,6 +50,7 @@ from app.services.shipping_notice.order_build_eligibility_service import (
|
||||
from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref
|
||||
from app.services.shipping_notice.order_review_projection import serialize_review_case
|
||||
from app.services.shipping_notice.order_schema.field_rules import (
|
||||
compute_effective_reservation_id,
|
||||
normalize_order_field_value,
|
||||
validate_order_field_value,
|
||||
)
|
||||
@@ -429,6 +433,8 @@ def _validation(
|
||||
核心逻辑:投影 field_code 值后调用资格服务;多候选不阻断;客户确认按真实
|
||||
Bill-to / Candidate 状态评估(禁止硬编码已确认);结果写入
|
||||
validation_result_json(含 line_projections)供工作台展示。
|
||||
行级必填 reservation_id 空时先按表头回退(与 compute_effective_reservation_id /
|
||||
Schema Runtime STEP 3.5 一致),避免「表头已有预约单号、行格空」误报缺失。
|
||||
可选 raw_lines:仅对给定完整明细行重算(履约波次),禁止继承未选中行导致的整单失败。
|
||||
|
||||
Args:
|
||||
@@ -464,8 +470,22 @@ def _validation(
|
||||
if str(field.get('scope')) != 'line':
|
||||
continue
|
||||
value = _current_value(raw_line, field_id)
|
||||
line[str(field.get('field_code') or field_id)] = value
|
||||
field_code = str(field.get('field_code') or field_id)
|
||||
line[field_code] = value
|
||||
normalized = normalize_order_field_value(value, field)
|
||||
# [STEP] 行预约单号空:先回退表头,再决定是否报 Schema 必填缺失。
|
||||
if (
|
||||
field.get('required')
|
||||
and normalized in (None, '')
|
||||
and field_code == 'reservation_id'
|
||||
):
|
||||
effective = compute_effective_reservation_id(
|
||||
line_reservation_id=None,
|
||||
header_reservation_id=header.get('reservation_id'),
|
||||
)
|
||||
if effective:
|
||||
line[field_code] = effective
|
||||
continue
|
||||
if field.get('required') and normalized in (None, ''):
|
||||
issues.append({'code': 'required_field_missing', 'field_id': field_id, 'draft_line_id': raw_line.get('draft_line_id'), 'severity': 'blocking'})
|
||||
elif normalized is not None and not validate_order_field_value(normalized, field):
|
||||
@@ -564,6 +584,10 @@ def build_confirmable_draft_summary(
|
||||
"""
|
||||
从冻结 Schema 投影完整草稿并重跑确认校验,供原子建单服务使用。
|
||||
|
||||
核心逻辑:投影 header/lines 后,行级 reservation_id 空时回填表头有效值
|
||||
(与 compute_effective_reservation_id / 草稿校验一致),确保确认物化写入
|
||||
行级 FieldValue,冻结门禁不会因「仅表头有预约单号」误拦。
|
||||
|
||||
Args:
|
||||
case: 复核 Case。
|
||||
draft_line_ids: 可选;仅投影这些完整明细行(履约波次),禁止拆分数量。
|
||||
@@ -606,6 +630,15 @@ def build_confirmable_draft_summary(
|
||||
key = str(raw_line.get('draft_line_id') or '').strip()
|
||||
if key and idx < len(lines):
|
||||
lines[idx]['draft_line_id'] = key
|
||||
# [STEP] 行预约单号空:回填表头有效值,供物化 Extraction / 冻结门禁消费。
|
||||
header_reservation = header.get('reservation_id')
|
||||
for line in lines:
|
||||
effective = compute_effective_reservation_id(
|
||||
line_reservation_id=line.get('reservation_id'),
|
||||
header_reservation_id=header_reservation,
|
||||
)
|
||||
if effective:
|
||||
line['reservation_id'] = effective
|
||||
# [STEP] 履约波次必须按选中行重算 can_build/status,禁止继承未选中行的整单失败态。
|
||||
validation = _validation(case, raw_lines=raw_lines)
|
||||
return {**header, 'lines': lines}, validation
|
||||
|
||||
@@ -346,6 +346,18 @@ def _project_case_automation_status(
|
||||
or result.get('reason_code')
|
||||
or 'stp_job_failed'
|
||||
)
|
||||
# 冻结门禁每次 confirm 重算;预约单号等修复后仍须允许技术重试入队。
|
||||
blocking_code = (
|
||||
blocking_reason.get('code')
|
||||
if isinstance(blocking_reason, dict)
|
||||
else str(blocking_reason or '').strip()
|
||||
)
|
||||
if (
|
||||
blocking_code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
and can_auto
|
||||
and can_build
|
||||
):
|
||||
retryable = True
|
||||
next_action = result.get('next_action')
|
||||
details = result.get('blocking_reason_details') if isinstance(
|
||||
result.get('blocking_reason_details'), dict,
|
||||
|
||||
@@ -11,7 +11,8 @@ backend/app/services/shipping_notice/order_schema/runtime.py
|
||||
Decision.selected_observation_id 对齐最终选中 Observation,禁止固定取第一条;
|
||||
仅 required 或 auto_create_key_field 字段可进入 blocked_fields;
|
||||
可选非关键字段证据不足只生成 diagnostic Finding,不阻断建单;
|
||||
必填门禁按最终投影判定;
|
||||
必填门禁按最终投影判定;行级 reservation_id 缺失时先回退表头再判完整性
|
||||
(与 compute_effective_reservation_id / 建单资格一致);
|
||||
published_version 固定读取唯一 Schema STANDARD_SHIPPING_NOTICE(兼容历史 SHIPPING_ORDER)。
|
||||
"""
|
||||
|
||||
@@ -1295,6 +1296,16 @@ def persist_dynamic_order(
|
||||
# [STEP 3] 内部项次由系统按解析行顺序生成;不读取或执行任何派生规则。
|
||||
field_lineage: list[dict[str, Any]] = []
|
||||
|
||||
# [STEP 3.5] 行级 reservation 回退表头,再进入完整性门禁(与建单资格一致)。
|
||||
header_reservation = header.get('reservation_id')
|
||||
for projection in line_projections:
|
||||
effective = compute_effective_reservation_id(
|
||||
line_reservation_id=projection.get('reservation_id'),
|
||||
header_reservation_id=header_reservation,
|
||||
)
|
||||
if effective:
|
||||
projection['reservation_id'] = effective
|
||||
|
||||
# [STEP 4] 关键字段完整性按最终投影检查。
|
||||
for config in all_configs.values():
|
||||
if not field_may_block_process(config):
|
||||
|
||||
@@ -279,12 +279,15 @@ def find_active_stp_job(*, business_ref: str) -> Job | None:
|
||||
if not key:
|
||||
return None
|
||||
cache = db.session.info.get('shipping_conversation_projection_read_cache')
|
||||
# 缓存仅在「已加载该键」时可信;空壳缓存(仅 Gate)不得冒充无 Job。
|
||||
if isinstance(cache, dict):
|
||||
jobs = cache.get('stp_jobs_by_ref', {}).get(key, [])
|
||||
return next(
|
||||
(job for job in jobs if str(job.status or '').strip().lower() in {'queued', 'running'}),
|
||||
None,
|
||||
)
|
||||
by_ref = cache.get('stp_jobs_by_ref')
|
||||
if isinstance(by_ref, dict) and key in by_ref:
|
||||
jobs = by_ref.get(key) or []
|
||||
return next(
|
||||
(job for job in jobs if str(job.status or '').strip().lower() in {'queued', 'running'}),
|
||||
None,
|
||||
)
|
||||
return (
|
||||
Job.query
|
||||
.filter(
|
||||
@@ -312,9 +315,12 @@ def find_latest_stp_job(*, business_ref: str) -> Job | None:
|
||||
if not key:
|
||||
return None
|
||||
cache = db.session.info.get('shipping_conversation_projection_read_cache')
|
||||
# 缓存仅在「已加载该键」时可信;空壳缓存不得把失败 Job 误判为缺失。
|
||||
if isinstance(cache, dict):
|
||||
jobs = cache.get('stp_jobs_by_ref', {}).get(key, [])
|
||||
return jobs[0] if jobs else None
|
||||
by_ref = cache.get('stp_jobs_by_ref')
|
||||
if isinstance(by_ref, dict) and key in by_ref:
|
||||
jobs = by_ref.get(key) or []
|
||||
return jobs[0] if jobs else None
|
||||
return (
|
||||
Job.query
|
||||
.filter(
|
||||
|
||||
@@ -297,6 +297,19 @@ def project_case_automation_status(
|
||||
or result.get('reason_code')
|
||||
or 'stp_job_failed'
|
||||
)
|
||||
# 冻结门禁每次 confirm 重算;预约单号等修复后仍须允许技术重试入队
|
||||
#(与 order_review_projection._project_case_automation_status 同源)。
|
||||
blocking_code = (
|
||||
blocking_reason_raw.get('code')
|
||||
if isinstance(blocking_reason_raw, dict)
|
||||
else str(blocking_reason_raw or '').strip()
|
||||
)
|
||||
if (
|
||||
blocking_code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
and can_auto
|
||||
and can_build
|
||||
):
|
||||
retryable = True
|
||||
next_action = result.get('next_action')
|
||||
details = (
|
||||
result.get('blocking_reason_details')
|
||||
@@ -929,10 +942,13 @@ def _project_fine_grained_pre_stp_blocking(
|
||||
if run_no and document_id is not None and draft_version is not None:
|
||||
business_ref_prefix = f"stp-auto:{run_no}:doc-{int(document_id)}:"
|
||||
cache = db.session.info.get('shipping_conversation_projection_read_cache')
|
||||
prefix_jobs = (
|
||||
cache.get('stp_jobs_by_prefix', {}).get(business_ref_prefix, [])
|
||||
if isinstance(cache, dict) else None
|
||||
)
|
||||
# 仅当缓存已加载该前缀的 STP Job 列表时才用缓存;空壳 Gate 缓存必须回落 DB,
|
||||
# 否则会把历史 failed Job 误判为「未入队」并错误投影 retry_stp_auto_create。
|
||||
prefix_jobs = None
|
||||
if isinstance(cache, dict):
|
||||
by_prefix = cache.get('stp_jobs_by_prefix')
|
||||
if isinstance(by_prefix, dict) and business_ref_prefix in by_prefix:
|
||||
prefix_jobs = by_prefix.get(business_ref_prefix) or []
|
||||
active_job = (
|
||||
next(
|
||||
(job for job in prefix_jobs if str(job.status or '').strip().lower() in {'queued', 'running'}),
|
||||
@@ -1070,10 +1086,11 @@ def _project_fine_grained_pre_stp_blocking(
|
||||
if run_no and document_id is not None and draft_version is not None:
|
||||
business_ref_prefix = f"stp-auto:{run_no}:doc-{int(document_id)}:"
|
||||
cache = db.session.info.get('shipping_conversation_projection_read_cache')
|
||||
prefix_jobs = (
|
||||
cache.get('stp_jobs_by_prefix', {}).get(business_ref_prefix, [])
|
||||
if isinstance(cache, dict) else None
|
||||
)
|
||||
prefix_jobs = None
|
||||
if isinstance(cache, dict):
|
||||
by_prefix = cache.get('stp_jobs_by_prefix')
|
||||
if isinstance(by_prefix, dict) and business_ref_prefix in by_prefix:
|
||||
prefix_jobs = by_prefix.get(business_ref_prefix) or []
|
||||
queued_job = (
|
||||
next((job for job in prefix_jobs if str(job.status or '').strip().lower() == 'queued'), None)
|
||||
if prefix_jobs is not None else (
|
||||
|
||||
@@ -781,12 +781,17 @@ def assert_case_not_blocked_manual(*, case_no: str, case: ShippingOrderReviewCas
|
||||
# 兼容修复前已落库的技术异常:旧结果被错误写成 retryable=false,
|
||||
# 但 SHIPPING.STP_AUTO_CREATE_UNEXPECTED 本身不是业务裁决原因,普通
|
||||
# retry 应创建新的 Job,而不是强制用户走 reconcile-and-progress。
|
||||
# ORDER_FREEZE_BLOCKED:冻结门禁每次 confirm 重算(如预约单号表头回退已修复),
|
||||
# 允许技术重试再入队,避免 UI/API 死锁在「人工裁决」文案上。
|
||||
effective_error_code = error_code or (
|
||||
blocking_reason.get('code')
|
||||
if isinstance(blocking_reason, dict)
|
||||
else str(blocking_reason or '').strip()
|
||||
)
|
||||
if not retryable_flag and effective_error_code == 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED':
|
||||
if not retryable_flag and effective_error_code in {
|
||||
'SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
|
||||
'SHIPPING.ORDER_FREEZE_BLOCKED',
|
||||
}:
|
||||
return
|
||||
if should_general_retry_be_removed(retryable_flag=retryable_flag, blocking_reason=blocking_reason):
|
||||
raise ConflictError(
|
||||
|
||||
@@ -74,8 +74,11 @@ def test_blocking_xfa_definition_flags_missing_paths_and_collection():
|
||||
assert 'xfa_required_path_coverage_incomplete' in keys
|
||||
|
||||
|
||||
def test_xfa_path_coverage_reports_scope_when_same_code_exists_twice():
|
||||
"""关键断言:同名 header/line 字段缺路径时,发布诊断必须保留真实字段身份。"""
|
||||
def test_xfa_path_coverage_header_reservation_covers_line_key():
|
||||
"""
|
||||
关键断言:header.reservation_id 已绑 datasets path 时,line.reservation_id
|
||||
建单键不再因缺行级 path 阻断发布(与 runtime 头→行回退一致)。
|
||||
"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='XFA_SCOPE_DIAGNOSTIC', display_name='XFA Scope', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='c' * 64, template_mode='xfa_dataset',
|
||||
@@ -91,6 +94,36 @@ def test_xfa_path_coverage_reports_scope_when_same_code_exists_twice():
|
||||
'field_code': 'reservation_id', 'scope': 'header', 'field_layout_id': 'header-reservation',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'header-path', 'data_path': '/data/HEADER/RESERVATION'},
|
||||
}],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': 'header-reservation', 'field_code': 'reservation_id', 'scope': 'header',
|
||||
'page_no': 1, 'region': {'x0': 0.1, 'y0': 0.1, 'x1': 0.2, 'y1': 0.2},
|
||||
}],
|
||||
'header_mappings': [], 'line_mapping': {'row_path': '/data/ITEMS', 'fields': []},
|
||||
'cross_checks': {},
|
||||
},
|
||||
)
|
||||
profile.schema_version = type('SV', (), {'definition_json': {'fields': [
|
||||
{'field_id': 'reservation-header', 'field_code': 'reservation_id', 'scope': 'header', 'enabled': True, 'required': False},
|
||||
{'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line', 'enabled': True, 'required': True, 'auto_create_key_field': True},
|
||||
]}})()
|
||||
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=None)
|
||||
assert 'xfa_required_path_coverage_incomplete' not in {item['key'] for item in blocking}
|
||||
|
||||
|
||||
def test_xfa_path_coverage_reports_line_reservation_when_header_unmapped():
|
||||
"""关键断言:头/行 reservation 均未映射时,诊断须标明缺失的是 line.reservation_id。"""
|
||||
profile = ShippingOrderDocumentProfile(
|
||||
profile_code='XFA_SCOPE_MISSING', display_name='XFA Scope Missing', version=1, status='draft',
|
||||
schema_version_id=1, structure_fingerprint='d' * 64, template_mode='xfa_dataset',
|
||||
definition_json={
|
||||
'template_mode': 'xfa_dataset',
|
||||
'source_contract': {
|
||||
'template_packet_checksum': 'sha256:template', 'dataset_structure_fingerprint': 'sha256:structure',
|
||||
'dataset_root_path': '/data', 'authoritative_line_collection_path': '/data/ITEMS',
|
||||
'mirror_collection_paths': [],
|
||||
},
|
||||
'bindings': [],
|
||||
'header_mappings': [], 'line_mapping': {'row_path': '/data/ITEMS', 'fields': []},
|
||||
'cross_checks': {},
|
||||
},
|
||||
@@ -102,8 +135,6 @@ def test_xfa_path_coverage_reports_scope_when_same_code_exists_twice():
|
||||
|
||||
blocking = xfa_dataset.publish_checks(profile=profile, validation=None)
|
||||
coverage = next(item for item in blocking if item['key'] == 'xfa_required_path_coverage_incomplete')
|
||||
|
||||
# 同名显示码只是辅助信息;管理员必须能识别真正缺失的是 line 的 reservation_id。
|
||||
assert coverage['field_codes'] == ['reservation_id']
|
||||
assert coverage['missing_fields'] == [{
|
||||
'field_id': 'reservation-line', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
|
||||
@@ -783,8 +783,8 @@ def test_on_demand_evidence_leaves_coordinates_missing_when_native_and_ocr_fail(
|
||||
assert not restored['coordinate_evidence'].get('page_glyphs')
|
||||
|
||||
|
||||
def test_layout_document_budget_creates_unsupported_audit_versions(app):
|
||||
"""超过单 Intake 配额的支持附件必须有 unsupported 审计,不能静默跳过。"""
|
||||
def test_layout_document_budget_defers_unscheduled_pdfs(app):
|
||||
"""超过单 Intake 配额的 PDF 本轮不排程、不写 unsupported;后续 schedule 可继续排上。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE'] = 1
|
||||
with app.app_context():
|
||||
@@ -805,12 +805,23 @@ def test_layout_document_budget_creates_unsupported_audit_versions(app):
|
||||
versions = schedule_document_layouts([first, text, second])
|
||||
db.session.commit()
|
||||
|
||||
assert len(versions) == 2
|
||||
assert len(versions) == 1
|
||||
assert versions[0].status == 'queued'
|
||||
assert versions[1].status == 'unsupported'
|
||||
assert versions[1].issues_json == ['mineru_intake_document_budget_exceeded']
|
||||
assert versions[0].document_id == first.id
|
||||
assert ShippingDocumentLayoutVersion.query.filter_by(document_id=second.id).count() == 0
|
||||
assert ShippingDocumentLayoutVersion.query.filter_by(document_id=text.id).count() == 0
|
||||
|
||||
# 第一份进入可用终态后,第二次 schedule 应排上此前延后的 PDF。
|
||||
versions[0].status = 'ready'
|
||||
first.current_layout_version_id = versions[0].id
|
||||
db.session.commit()
|
||||
|
||||
second_wave = schedule_document_layouts([first, text, second])
|
||||
db.session.commit()
|
||||
assert len(second_wave) == 1
|
||||
assert second_wave[0].document_id == second.id
|
||||
assert second_wave[0].status == 'queued'
|
||||
|
||||
|
||||
def test_deleting_document_cascades_layout_versions(app):
|
||||
"""Document 删除必须先解除 current 引用,并级联清理其全部布局版本。"""
|
||||
|
||||
@@ -4,6 +4,7 @@ backend/tests/test_shipping_document_profile_quality.py
|
||||
用途:验证订单文档模板的独立盲测候选、批准资格和冻结 checksum 门禁。
|
||||
依赖:Profile 服务、布局快照、模板盲测服务与测试数据库。
|
||||
逻辑:管理员固化一份独立样本真值;通过且批准后才可放行确定性自动建单。
|
||||
XFA 确认真值允许候选含 bindings 以外的视觉表头(如 bill_to)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -42,6 +43,47 @@ def _memory_file_asset_storage(monkeypatch):
|
||||
monkeypatch.setattr(file_asset_storage_module.file_asset_storage, 'delete_object', lambda storage_key: objects.pop(storage_key, None))
|
||||
|
||||
|
||||
def test_expected_order_fields_allows_extra_visual_header_keys_for_xfa_bindings():
|
||||
"""XFA 确认:bindings 表头齐全即可;候选额外含 bill_to 等视觉框不得拒绝。"""
|
||||
binding = SimpleNamespace(
|
||||
scope='header',
|
||||
field_code='customer_po_number',
|
||||
value_binding=SimpleNamespace(path_id='po-path'),
|
||||
)
|
||||
parser = SimpleNamespace(bindings=[binding], header_mappings=[], order_field_layouts=[])
|
||||
raw = {
|
||||
'header:customer_po_number': '4510039229',
|
||||
'header:bill_to_customer': 'Cloud Network Technology Kft.',
|
||||
'header:bill_to_address': 'Bánki Donát u. 1',
|
||||
}
|
||||
|
||||
result = quality._expected_order_fields(raw, parser=parser)
|
||||
|
||||
# 关键断言:正式绑定键保留,额外视觉表头一并写入盲测真值。
|
||||
assert result == raw
|
||||
|
||||
|
||||
def test_expected_order_fields_still_requires_every_bound_header_for_xfa():
|
||||
"""XFA 确认:缺少 bindings 表头仍须拒绝,避免静默漏掉正式 path 字段。"""
|
||||
parser = SimpleNamespace(
|
||||
bindings=[
|
||||
SimpleNamespace(scope='header', field_code='customer_po_number'),
|
||||
SimpleNamespace(scope='header', field_code='currency'),
|
||||
],
|
||||
header_mappings=[],
|
||||
order_field_layouts=[],
|
||||
)
|
||||
|
||||
with pytest.raises(Exception) as caught:
|
||||
quality._expected_order_fields(
|
||||
{'header:customer_po_number': '4510039229', 'header:bill_to_customer': 'X'},
|
||||
parser=parser,
|
||||
)
|
||||
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID'
|
||||
assert 'header:currency' in (getattr(caught.value, 'details', {}) or {}).get('missing_keys', [])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
('actual', 'expected', 'config'),
|
||||
[
|
||||
|
||||
@@ -134,9 +134,57 @@ def test_position_matcher_line_index_1based():
|
||||
parsed_seg = [s for s in result.segments if s.rule_id == 'pos1'][0]
|
||||
assert parsed_seg.normalized_text == 'Vendor Comments:'
|
||||
assert parsed_seg.line_no == 1
|
||||
assert parsed_seg.line_end_no == 1
|
||||
assert parsed_seg.handling == 'evidence_only'
|
||||
|
||||
|
||||
def test_position_matcher_joins_consecutive_lines():
|
||||
"""连续多行 position:line_end + join_with 合并文本并认领范围内行。"""
|
||||
seg = BaseSplitSegment(
|
||||
segment_id=new_segment_id(),
|
||||
segment_code='bill_to_address',
|
||||
display_name='账款地址',
|
||||
handling='mapped',
|
||||
target_field_id='f-addr',
|
||||
target_field_code='bill_to_address',
|
||||
)
|
||||
rule_set = _base_rule_set([
|
||||
BaseSplitRule(
|
||||
rule_id='addr-range',
|
||||
matcher=BaseSplitMatcher(
|
||||
type='position',
|
||||
line_index=2,
|
||||
line_end=4,
|
||||
join_with='newline',
|
||||
),
|
||||
segment=seg,
|
||||
),
|
||||
])
|
||||
raw = (
|
||||
'Cloud Network Technology Kft.\n'
|
||||
'Bánki Donát u. 1.\n'
|
||||
'2900 Komárom\n'
|
||||
'Hungary'
|
||||
)
|
||||
result = execute_base_split_rule_set(raw_value=raw, rule_set=rule_set)
|
||||
assert result.status == 'parsed'
|
||||
assert result.mapped_fields['bill_to_address'] == (
|
||||
'Bánki Donát u. 1.\n2900 Komárom\nHungary'
|
||||
)
|
||||
parsed_seg = [s for s in result.segments if s.rule_id == 'addr-range'][0]
|
||||
assert parsed_seg.line_no == 2
|
||||
assert parsed_seg.line_end_no == 4
|
||||
unmatched = [s for s in result.segments if s.matcher_type == 'unmatched']
|
||||
assert len(unmatched) == 1
|
||||
assert unmatched[0].line_no == 1
|
||||
|
||||
|
||||
def test_position_matcher_rejects_inverted_line_range():
|
||||
"""line_end < line_index 时契约拒绝。"""
|
||||
with pytest.raises(Exception):
|
||||
BaseSplitMatcher(type='position', line_index=3, line_end=1)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# [TEST 2] 优先级仲裁——prefix > regex > position > unmatched
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -183,6 +183,51 @@ def test_reference_page_frames_read_annotation_coordinate_evidence():
|
||||
}
|
||||
|
||||
|
||||
def test_definition_contract_hydrates_empty_order_field_id_from_schema():
|
||||
"""盲测候选预览:已保存空 field_id 必须从 Schema 回填,禁止 Pydantic 500。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [
|
||||
{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'line-start', 'field_code': 'customer_po_line_no', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
{
|
||||
'field_id': 'part-field', 'field_code': 'part_number', 'scope': 'line',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
},
|
||||
]})
|
||||
definition = _coordinate_definition()
|
||||
definition['order_field_layouts'] = [{
|
||||
'layout_id': 'order_field_1_9',
|
||||
'field_id': '',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'page_scope': 'exact_page',
|
||||
'page_no': 1,
|
||||
'anchor': None,
|
||||
'fallback_value_region': {'x0': .1, 'y0': .1, 'x1': .4, 'y1': .15},
|
||||
'value_mode': 'single_line',
|
||||
'stop_anchors': [],
|
||||
'required': False,
|
||||
'minimum_evidence_level': 'coordinate',
|
||||
}]
|
||||
profile = SimpleNamespace(
|
||||
profile_code='FOX_HUNGARY',
|
||||
version=1,
|
||||
definition_json=definition,
|
||||
schema_version=schema,
|
||||
)
|
||||
|
||||
contract = service._definition_contract(profile)
|
||||
|
||||
# 关键断言:空串 field_id 已按 Schema 回填,坐标契约可构造。
|
||||
assert contract.order_field_layouts[0].field_id == 'po-field'
|
||||
assert contract.order_field_layouts[0].layout_id == 'order_field_1_9'
|
||||
|
||||
|
||||
def test_reservation_region_rejects_schema_without_header_scope():
|
||||
"""无行号 Reservation 需要稳定 Header 落点,只有 Line 字段时不得保存。"""
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
@@ -603,6 +648,54 @@ def test_visual_sample_preview_discards_duplicate_unbound_layout_for_bound_field
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
|
||||
|
||||
def test_visual_sample_preview_soft_dedupes_duplicate_order_field_codes(app, monkeypatch):
|
||||
"""进入编辑页时草稿若已重复绑定同一 Header 字段,预览须去重后继续返回样本值。"""
|
||||
glyphs = [
|
||||
{
|
||||
'text': character,
|
||||
'bbox': {'x0': 20 + index * 8, 'y0': 10, 'x1': 26 + index * 8, 'y1': 18},
|
||||
}
|
||||
for index, character in enumerate('4510039227')
|
||||
]
|
||||
schema = SimpleNamespace(definition_json={'fields': [{
|
||||
'field_id': 'po-field', 'field_code': 'customer_po_number', 'scope': 'header',
|
||||
'enabled': True, 'normalizer_key': 'trim', 'allowed_sources': ['pdf_coordinate'],
|
||||
}]})
|
||||
document = SimpleNamespace(id=101)
|
||||
layout = {
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': glyphs},
|
||||
'sources': {'pages': {'1': 'pdf_coordinate'}},
|
||||
},
|
||||
}
|
||||
monkeypatch.setattr(db.session, 'get', lambda model, object_id: document if object_id == 101 else None)
|
||||
monkeypatch.setattr(service, '_require_schema_version', lambda _value: schema)
|
||||
monkeypatch.setattr(service, '_document_layout', lambda _document: layout)
|
||||
|
||||
definition = {
|
||||
'document_match': {'required_anchors': []}, 'table_regions': [],
|
||||
'draft_unbound_order_field_layouts': [],
|
||||
'order_field_layouts': [{
|
||||
'layout_id': f'customer_po_{index}', 'field_id': '', 'field_code': 'customer_po_number',
|
||||
'scope': 'header', 'page_scope': 'exact_page', 'page_no': 1,
|
||||
'anchor': None, 'fallback_value_region': {'x0': .05, 'y0': .05, 'x1': .60, 'y1': .25},
|
||||
'value_mode': 'single_line', 'stop_anchors': [], 'normalizer_key': None,
|
||||
'required': False, 'minimum_evidence_level': 'coordinate',
|
||||
} for index in (1, 2)],
|
||||
}
|
||||
|
||||
with app.app_context():
|
||||
result = service.preview_order_field_values({
|
||||
'document_id': 101, 'schema_version_id': 7, 'page_no': 1, 'definition': definition,
|
||||
}, actor_id=None)
|
||||
|
||||
# 关键断言:预览只保留首个重复字段布局,不因 order_field_duplicate 拒绝进入编辑页。
|
||||
assert len(result['fields']) == 1
|
||||
assert result['fields'][0]['field_code'] == 'customer_po_number'
|
||||
assert result['fields'][0]['value'] == '4510039227'
|
||||
|
||||
|
||||
def test_visual_sample_preview_reads_order_field_before_table_region_is_drawn(app, monkeypatch):
|
||||
"""共同视觉预览在明细表尚未标注时,仍可读取已标注的订单级 PO 字段。"""
|
||||
glyphs = [
|
||||
|
||||
@@ -53,6 +53,7 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
reparse_order_extraction_run,
|
||||
retry_order_extraction_run,
|
||||
resume_runs_waiting_for_layout,
|
||||
revive_layout_prerequisite_failed_units,
|
||||
order_extraction_layout_prerequisite_issues,
|
||||
order_extraction_layouts_failed,
|
||||
materialize_order_extraction_run_inputs,
|
||||
@@ -706,6 +707,66 @@ def test_create_run_waits_for_active_document_layout_before_enqueuing_extraction
|
||||
assert ShippingOrderProcessingRun.query.count() == 1
|
||||
|
||||
|
||||
def test_resume_revives_layout_prerequisite_failed_unit_when_layout_ready(app):
|
||||
"""layout 前置失败的 Unit 在版面变 ready 后必须复活为 pending 并入队续抽。"""
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
user, agent, session, intake, document, run, _ = _seed_run_with_plan(suffix='REVIVE-LAYOUT')
|
||||
unit = run.extraction_plan.units[0]
|
||||
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='layout prerequisite: layout_missing',
|
||||
)
|
||||
document.order_extraction_status = 'failed'
|
||||
document.order_extraction_error_code = unit.error_code
|
||||
run.status = 'processing'
|
||||
run.phase = 'waiting_layout'
|
||||
layout = ShippingDocumentLayoutVersion.query.filter_by(document_id=document.id).order_by(
|
||||
ShippingDocumentLayoutVersion.version.desc(),
|
||||
).first()
|
||||
if layout is None:
|
||||
layout = ShippingDocumentLayoutVersion(
|
||||
document_id=document.id,
|
||||
version=1,
|
||||
status='ready',
|
||||
source_content_hash=document.content_hash,
|
||||
parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:test',
|
||||
parser_name='mineru',
|
||||
contract_version='shipping_document_table_snapshot.v1',
|
||||
issues_json=[],
|
||||
)
|
||||
db.session.add(layout)
|
||||
db.session.flush()
|
||||
layout.status = 'ready'
|
||||
layout.payload_json = {
|
||||
'status': 'ready',
|
||||
'layout_candidate': {'pages': [{'page_no': 1, 'tables': []}]},
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': [{'text': 'A'}]},
|
||||
},
|
||||
}
|
||||
layout.issues_json = []
|
||||
document.current_layout_version_id = layout.id
|
||||
db.session.commit()
|
||||
|
||||
revived = revive_layout_prerequisite_failed_units(run)
|
||||
assert revived == 1
|
||||
db.session.refresh(unit)
|
||||
db.session.refresh(document)
|
||||
assert unit.status == 'pending'
|
||||
assert unit.error_code is None
|
||||
assert document.order_extraction_status == 'not_started'
|
||||
|
||||
assert resume_runs_waiting_for_layout(document_id=document.id) == 1
|
||||
db.session.refresh(run)
|
||||
assert run.current_job_id is not None
|
||||
assert run.phase in {'queued', 'waiting_layout'}
|
||||
|
||||
|
||||
def test_create_run_accepts_a_reused_layout_from_an_identical_document(app):
|
||||
"""相同内容复用历史布局时,当前 Document 的版本绑定应视为排程成功。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -246,6 +246,128 @@ def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(mo
|
||||
assert finished['result']['waiting_layout'] is True
|
||||
|
||||
|
||||
def test_worker_runtime_budget_reenqueues_instead_of_partially_completed(monkeypatch):
|
||||
"""运行时预算耗尽且仍有 pending Unit 时,必须入队续抽,不得终态 partially_completed。"""
|
||||
import app.jobs.handlers.shipping_order_extraction as handler
|
||||
|
||||
events: list[str] = []
|
||||
finished: dict = {}
|
||||
run = SimpleNamespace(
|
||||
id=5, user_id=9, run_no='SNER-WORKER-BUDGET', status='queued', phase='queued',
|
||||
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
|
||||
input_snapshot_json={
|
||||
'attachment_selection': {'max_runtime_seconds': 1},
|
||||
'intakes': [],
|
||||
},
|
||||
execution_result_json=None, extraction_completed_at=None,
|
||||
)
|
||||
job = SimpleNamespace(id=5, attempts=1, business_ref=run.run_no, max_attempts=3)
|
||||
done_unit = SimpleNamespace(
|
||||
id=51, document_id=201, intake_id=1, status='pending', result_json=None, position=1,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
pending_unit = SimpleNamespace(
|
||||
id=52, document_id=202, intake_id=1, status='pending', result_json=None, position=2,
|
||||
cancellation_requested_at=None,
|
||||
)
|
||||
plan = SimpleNamespace(id=5, unit_count=2, units=[done_unit, pending_unit])
|
||||
|
||||
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else done_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: [done_unit, pending_unit]),
|
||||
),
|
||||
),
|
||||
))
|
||||
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
|
||||
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None)
|
||||
monkeypatch.setattr(
|
||||
handler, 'materialize_order_extraction_run_inputs',
|
||||
lambda _run, *, finalize_plan=True: 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: False)
|
||||
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
|
||||
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: {201, 202})
|
||||
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False)
|
||||
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: events.append('budget_progress'))
|
||||
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
|
||||
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [done_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: {})
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_extraction_plan.transition_order_extraction_unit',
|
||||
lambda unit, *, target_status, **_k: setattr(unit, 'status', target_status),
|
||||
)
|
||||
|
||||
# 第一轮抽完后假装时间已耗尽,禁止启动第二个 Unit。
|
||||
clock = {'now': 100.0}
|
||||
|
||||
def _perf_counter():
|
||||
return clock['now']
|
||||
|
||||
monkeypatch.setattr(handler.time, 'perf_counter', _perf_counter)
|
||||
|
||||
def _process(*, unit, **_kwargs):
|
||||
events.append(f'processed:{unit.id}')
|
||||
unit.status = 'merging_supplement'
|
||||
clock['now'] = 200.0 # 超过 max_runtime_seconds=1
|
||||
return [{'po_number': 'PO-BUDGET', '_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: {})
|
||||
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'))
|
||||
monkeypatch.setattr(
|
||||
handler, '_enqueue_ready_order_extraction_job',
|
||||
lambda _run, *, message: events.append(f'enqueue:{message}') or 999,
|
||||
)
|
||||
|
||||
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': 5})
|
||||
|
||||
assert 'processed:51' in events
|
||||
assert 'processed:52' not in events
|
||||
assert any(item.startswith('enqueue:') for item in events)
|
||||
assert 'terminalized' not in events
|
||||
assert 'persist_started' not in events
|
||||
assert run.status == 'processing'
|
||||
assert run.phase == 'waiting_layout'
|
||||
assert run.current_job_id == 999
|
||||
assert finished['result']['budget_stopped'] is True
|
||||
assert finished['result']['waiting_continue'] is True
|
||||
assert finished['result']['handoff_status'] == 'runtime_budget_continue'
|
||||
assert pending_unit.status == 'pending'
|
||||
|
||||
|
||||
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
|
||||
|
||||
@@ -873,3 +873,44 @@ def test_provider_omission_is_merged_but_override_of_confirmed_order_field_is_re
|
||||
assert error.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE'
|
||||
else:
|
||||
raise AssertionError('confirmed order field override must be rejected')
|
||||
|
||||
|
||||
def test_merge_confirmed_fields_skips_lock_when_orders_use_xfa_dataset():
|
||||
"""
|
||||
XFA:datasets 为正式值;坐标 confirmed 锁(含标签 OCR 垃圾值)不得否决或覆盖。
|
||||
关键断言:bill_to 保留 datasets 客户名,且不抛 ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE。
|
||||
"""
|
||||
from unittest.mock import patch
|
||||
|
||||
unit = type('Unit', (), {'document_id': 247})()
|
||||
xfa_orders = [{
|
||||
'header_fields': [{
|
||||
'field_id': '9a81b044-b49f-4ed3-8c09-2aec85fb1470',
|
||||
'value_source': 'xfa_dataset',
|
||||
'observations': [{
|
||||
'value': 'Cloud Network Technology Kft.',
|
||||
'source': 'xfa_dataset',
|
||||
'document_id': 247,
|
||||
'layout_evidence': {
|
||||
'source': 'xfa_dataset',
|
||||
'evidence_ref': {'source': 'xfa_dataset'},
|
||||
},
|
||||
}],
|
||||
}],
|
||||
'lines': [],
|
||||
}]
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_extraction_workflow._confirmed_profile_order_fields',
|
||||
lambda _run, unit: [{
|
||||
'field_id': '9a81b044-b49f-4ed3-8c09-2aec85fb1470',
|
||||
'value': 'b) Issue invoice to:',
|
||||
'status': 'confirmed',
|
||||
'source': 'pdf_coordinate',
|
||||
}],
|
||||
):
|
||||
merged = _merge_confirmed_profile_order_fields(object(), unit=unit, orders=xfa_orders)
|
||||
|
||||
obs = merged[0]['header_fields'][0]['observations'][0]
|
||||
assert obs['value'] == 'Cloud Network Technology Kft.'
|
||||
assert obs['source'] == 'xfa_dataset'
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
tests/test_shipping_order_profile_matcher_replay.py
|
||||
|
||||
用途:回放本地库历史 unique_match 冻结快照,验证收紧表头身份读取不回归已发布模板。
|
||||
依赖:SQLAlchemy、match_frozen_coordinate_profiles、shipping_order_route_decisions 表。
|
||||
逻辑:只读查询 Run 冻结 input_snapshot_json;无 DB/快照时 skip;失败样本按 profile 汇总。
|
||||
用途:回放本地库已发布模板样本,验证表头身份观测改动不回归任一 published profile。
|
||||
依赖:SQLAlchemy / Flask app、match_frozen_coordinate_profiles、profile samples、route decisions。
|
||||
逻辑:① 历史 unique_match 快照仍命中原 profile;② 每个 published 标注样本在全量候选中自匹配;
|
||||
③ 生产件 curated 文档重匹配。无 DB 时 skip。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -26,10 +27,11 @@ _REPLAY_DB_URL = os.environ.get(
|
||||
os.environ.get('DATABASE_URL', 'postgresql://postgres:postgres@127.0.0.1:5432/hxops_db'),
|
||||
)
|
||||
_MAX_PER_PROFILE = int(os.environ.get('HXOPS_PROFILE_REPLAY_MAX_PER_PROFILE', '20'))
|
||||
_EXTRA_DOC_IDS = {
|
||||
int(item.strip())
|
||||
for item in os.environ.get('HXOPS_PROFILE_REPLAY_DOC_IDS', '194').split(',')
|
||||
if item.strip().isdigit()
|
||||
# 生产件回归:document_id → 期望 profile_code
|
||||
_CURATED_DOC_EXPECTATIONS = {
|
||||
194: 'ODP-20260824-2C542346805B', # FOX MX / 4210012210
|
||||
199: 'ODP-20260825-BE122F0633B6', # INVENTECH TW / 4518814494_524
|
||||
197: 'ODP-20260825-BE122F0633B6', # INVENTECH TW / 4518814838
|
||||
}
|
||||
|
||||
|
||||
@@ -52,6 +54,27 @@ def replay_engine() -> Engine:
|
||||
return create_engine(_REPLAY_DB_URL)
|
||||
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def replay_app(replay_engine: Engine):
|
||||
"""
|
||||
绑定回放库的 Flask app,供标注样本 hydrate / published 快照加载。
|
||||
|
||||
核心逻辑:强制 DATABASE_URL 指向回放库后 create_app;测试结束弹出覆盖值。
|
||||
"""
|
||||
previous = os.environ.get('DATABASE_URL')
|
||||
os.environ['DATABASE_URL'] = _REPLAY_DB_URL
|
||||
from app import create_app
|
||||
|
||||
app = create_app('development')
|
||||
try:
|
||||
yield app
|
||||
finally:
|
||||
if previous is None:
|
||||
os.environ.pop('DATABASE_URL', None)
|
||||
else:
|
||||
os.environ['DATABASE_URL'] = previous
|
||||
|
||||
|
||||
def _document_from_snapshot(
|
||||
snapshot: dict[str, Any],
|
||||
*,
|
||||
@@ -95,12 +118,7 @@ def _frozen_profiles(snapshot: dict[str, Any], *, schema_version_id: int) -> lis
|
||||
|
||||
|
||||
def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]:
|
||||
"""
|
||||
拉取 unique_match 路由样本;每个 profile_code 最多保留最近 N 条。
|
||||
|
||||
Returns:
|
||||
含 route/run/unit/document/profile 期望字段的字典列表。
|
||||
"""
|
||||
"""拉取 unique_match 路由样本;每个 profile_code 最多保留最近 N 条。"""
|
||||
query = text("""
|
||||
SELECT
|
||||
r.id AS route_id,
|
||||
@@ -148,11 +166,9 @@ def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]:
|
||||
rows.append({
|
||||
'route_id': int(row['route_id']),
|
||||
'run_id': int(row['run_id']),
|
||||
'unit_id': int(row['unit_id']),
|
||||
'document_id': int(row['document_id']),
|
||||
'expected_profile_code': code,
|
||||
'expected_profile_version': int(row['selected_profile_version'] or 0),
|
||||
'expected_profile_checksum': str(row['selected_profile_checksum'] or ''),
|
||||
'profiles': profiles,
|
||||
'layout': layout,
|
||||
})
|
||||
@@ -160,57 +176,133 @@ def _load_replay_samples(engine: Engine) -> list[dict[str, Any]]:
|
||||
|
||||
|
||||
def test_replay_published_unique_match_snapshots(replay_engine: Engine) -> None:
|
||||
"""历史 unique_match 样本回放后仍应命中同一 profile(收紧表头带回归门禁)。"""
|
||||
"""历史 unique_match 样本回放后仍应命中同一 profile。"""
|
||||
samples = _load_replay_samples(replay_engine)
|
||||
if not samples:
|
||||
pytest.skip('No replayable unique_match snapshots in database')
|
||||
|
||||
failures: list[str] = []
|
||||
summary: dict[str, dict[str, int]] = defaultdict(lambda: {'pass': 0, 'fail': 0})
|
||||
|
||||
for sample in samples:
|
||||
code = sample['expected_profile_code']
|
||||
result = match_frozen_coordinate_profiles(
|
||||
profiles=sample['profiles'],
|
||||
layout=sample['layout'],
|
||||
profiles=sample['profiles'], layout=sample['layout'],
|
||||
)
|
||||
ok = (
|
||||
result.status == 'unique_match'
|
||||
and result.profile_code == sample['expected_profile_code']
|
||||
and result.profile_code == code
|
||||
and (
|
||||
not sample['expected_profile_version']
|
||||
or int(result.version or 0) == int(sample['expected_profile_version'])
|
||||
)
|
||||
)
|
||||
if ok:
|
||||
summary[code]['pass'] += 1
|
||||
else:
|
||||
summary[code]['fail'] += 1
|
||||
summary[code]['pass' if ok else 'fail'] += 1
|
||||
if not ok:
|
||||
failures.append(
|
||||
f"{code} route={sample['route_id']} run={sample['run_id']} "
|
||||
f"doc={sample['document_id']}: expected {sample['expected_profile_code']}"
|
||||
f"/v{sample['expected_profile_version']}, got {result.status}"
|
||||
f"/{result.profile_code}/v{result.version}"
|
||||
f"{code} route={sample['route_id']} doc={sample['document_id']}: "
|
||||
f"got {result.status}/{result.profile_code}"
|
||||
)
|
||||
|
||||
if failures:
|
||||
lines = [
|
||||
'Published unique_match replay failures:',
|
||||
*[f' - {item}' for item in failures[:50]],
|
||||
'Per-profile summary:',
|
||||
]
|
||||
lines = ['unique_match replay failures:', *[f' - {item}' for item in failures[:50]]]
|
||||
for profile_code, counts in sorted(summary.items()):
|
||||
lines.append(f' {profile_code}: pass={counts["pass"]} fail={counts["fail"]}')
|
||||
pytest.fail('\n'.join(lines))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('document_id', sorted(_EXTRA_DOC_IDS))
|
||||
def test_replay_specific_document_rematch_after_header_band(replay_engine: Engine, document_id: int) -> None:
|
||||
def test_replay_all_published_annotation_samples_unique_match(replay_app) -> None:
|
||||
"""
|
||||
对指定 document(默认 194 / 4210012210)用最新 Run 冻结快照重匹配。
|
||||
每个已发布模板的标注样本,在同 Schema 全量 published 候选中须 unique_match 自身。
|
||||
|
||||
历史路由可能失败;本断言验证收紧表头带后应 FOX MX unique_match。
|
||||
覆盖无历史 unique_match 路由的模板(FOX TW / QUANTA / Inventec / WIWYNN CZ 等)。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderDocumentProfile, ShippingOrderDocumentProfileSample
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.order_document_profile_service import (
|
||||
published_snapshots_for_schema,
|
||||
)
|
||||
from app.services.shipping_notice.order_document_profile_validation_service import (
|
||||
_load_sample_layout,
|
||||
)
|
||||
|
||||
with replay_app.app_context():
|
||||
published = (
|
||||
ShippingOrderDocumentProfile.query
|
||||
.filter_by(status='published')
|
||||
.order_by(ShippingOrderDocumentProfile.profile_code.asc())
|
||||
.all()
|
||||
)
|
||||
if not published:
|
||||
pytest.skip('No published profiles in replay database')
|
||||
|
||||
failures: list[str] = []
|
||||
missing: list[str] = []
|
||||
for profile in published:
|
||||
sample = (
|
||||
ShippingOrderDocumentProfileSample.query
|
||||
.filter_by(profile_id=int(profile.id), sample_role='annotation')
|
||||
.order_by(ShippingOrderDocumentProfileSample.id.asc())
|
||||
.first()
|
||||
)
|
||||
if sample is None:
|
||||
missing.append(f'{profile.display_name} ({profile.profile_code}): no annotation sample')
|
||||
continue
|
||||
try:
|
||||
layout = _load_sample_layout(sample)
|
||||
except ValidationError as exc:
|
||||
missing.append(
|
||||
f'{profile.display_name} ({profile.profile_code}): layout unavailable ({exc.code})'
|
||||
)
|
||||
continue
|
||||
if not _layout_ready(layout):
|
||||
from app.models import ShippingOrderDocument
|
||||
from app.services.shipping_notice.document_layout.on_demand_coordinate_evidence import (
|
||||
ensure_on_demand_coordinate_evidence,
|
||||
)
|
||||
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
|
||||
if document is not None:
|
||||
layout = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=dict(layout), page_nos=None,
|
||||
)
|
||||
if not _layout_ready(layout):
|
||||
missing.append(
|
||||
f'{profile.display_name} ({profile.profile_code}): layout evidence incomplete'
|
||||
)
|
||||
continue
|
||||
|
||||
candidates = published_snapshots_for_schema(int(profile.schema_version_id))
|
||||
if not candidates:
|
||||
missing.append(
|
||||
f'{profile.display_name} ({profile.profile_code}): no published snapshots'
|
||||
)
|
||||
continue
|
||||
result = match_frozen_coordinate_profiles(profiles=candidates, layout=layout)
|
||||
if not (
|
||||
result.status == 'unique_match'
|
||||
and result.profile_code == profile.profile_code
|
||||
and int(result.version or 0) == int(profile.version)
|
||||
):
|
||||
failures.append(
|
||||
f'{profile.display_name} ({profile.profile_code}): '
|
||||
f'got {result.status}/{result.profile_code}/v{result.version}'
|
||||
)
|
||||
|
||||
if missing or failures:
|
||||
lines = []
|
||||
if missing:
|
||||
lines.append('Missing fixtures / evidence:')
|
||||
lines.extend(f' - {item}' for item in missing)
|
||||
if failures:
|
||||
lines.append('Annotation self-match failures:')
|
||||
lines.extend(f' - {item}' for item in failures)
|
||||
pytest.fail('\n'.join(lines))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('document_id,expected_profile_code', sorted(_CURATED_DOC_EXPECTATIONS.items()))
|
||||
def test_replay_curated_production_documents(
|
||||
replay_engine: Engine, document_id: int, expected_profile_code: str,
|
||||
) -> None:
|
||||
"""生产回归件(FOX MX / INVENTECH TW 等)用最新 Run 快照重匹配须 unique_match。"""
|
||||
query = text("""
|
||||
SELECT
|
||||
run.id AS run_id,
|
||||
@@ -245,7 +337,4 @@ def test_replay_specific_document_rematch_after_header_band(replay_engine: Engin
|
||||
profiles = _frozen_profiles(snapshot, schema_version_id=int(row['schema_version_id'] or 0))
|
||||
result = match_frozen_coordinate_profiles(profiles=profiles, layout=layout)
|
||||
assert result.status == 'unique_match'
|
||||
if document_id == 194:
|
||||
assert result.profile_code == 'ODP-20260824-2C542346805B'
|
||||
else:
|
||||
assert result.profile_code
|
||||
assert result.profile_code == expected_profile_code
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
tests/test_shipping_order_profile_unified_migration_status.py
|
||||
|
||||
用途:锁定 summarize_unified_migration_status 的 pending_visual 计数规则。
|
||||
依赖:order_profile_unified_migration.summarize_unified_migration_status。
|
||||
逻辑:纯摘要单测;不读 PDF / 不写库。现代 XFA 绑定靠 field_layout_id,不得因缺少
|
||||
visual_binding 被计为「待补框」。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.order_profile_unified_migration import (
|
||||
summarize_unified_migration_status,
|
||||
)
|
||||
|
||||
|
||||
def test_summarize_skips_pending_when_field_layout_id_present():
|
||||
"""
|
||||
有 field_layout_id 的 XFA binding 即使无 visual_binding,也不计 pending_visual。
|
||||
"""
|
||||
summary = summarize_unified_migration_status(
|
||||
{
|
||||
'template_mode': 'xfa_dataset',
|
||||
'bindings': [
|
||||
{
|
||||
'binding_id': 'bind-po',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'field_layout_id': 'header_po_box',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'header-po'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-mat',
|
||||
'field_code': 'material_number',
|
||||
'scope': 'line',
|
||||
'field_layout_id': 'line_1:material_number',
|
||||
'value_binding': {'type': 'xfa_dataset', 'path_id': 'matnr-path'},
|
||||
# visual_binding 缺失或非 confirmed 都不应计入 pending。
|
||||
'visual_binding': {'status': 'suggested'},
|
||||
},
|
||||
],
|
||||
},
|
||||
template_mode='xfa_dataset',
|
||||
)
|
||||
|
||||
# 关键断言:库列表「待补框」不得把已挂共享布局的 XFA 绑定算进去。
|
||||
assert summary['already_unified'] is True
|
||||
assert summary['needs_migration'] is False
|
||||
assert summary['binding_count'] == 2
|
||||
assert summary['pending_visual_count'] == 0
|
||||
assert summary['unified_binding_status'] == 'ready'
|
||||
|
||||
|
||||
def test_summarize_counts_pending_without_field_layout_or_confirmed_visual():
|
||||
"""
|
||||
无 field_layout_id 且 visual 未 confirmed 的 binding 仍计为 pending_visual。
|
||||
"""
|
||||
summary = summarize_unified_migration_status(
|
||||
{
|
||||
'template_mode': 'coordinate',
|
||||
'bindings': [
|
||||
{
|
||||
'binding_id': 'bind-ready',
|
||||
'field_code': 'order_date',
|
||||
'scope': 'header',
|
||||
'field_layout_id': '',
|
||||
'visual_binding': {'status': 'confirmed'},
|
||||
'value_binding': {'type': 'ocr_region'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-pending',
|
||||
'field_code': 'customer_po_number',
|
||||
'scope': 'header',
|
||||
'visual_binding': {'status': 'suggested'},
|
||||
'value_binding': {'type': 'ocr_region'},
|
||||
},
|
||||
{
|
||||
'binding_id': 'bind-missing-visual',
|
||||
'field_code': 'ship_to',
|
||||
'scope': 'header',
|
||||
'value_binding': {'type': 'ocr_region'},
|
||||
},
|
||||
],
|
||||
},
|
||||
template_mode='coordinate',
|
||||
)
|
||||
|
||||
# 关键断言:仅无布局且未确认视觉的两条计入 pending。
|
||||
assert summary['binding_count'] == 3
|
||||
assert summary['pending_visual_count'] == 2
|
||||
assert summary['unified_binding_status'] == 'pending_visual'
|
||||
@@ -0,0 +1,281 @@
|
||||
"""
|
||||
tests/test_shipping_order_review_draft_reservation_fallback.py
|
||||
|
||||
用途:回归「表头已有预约单号、明细行格空」时草稿校验与确认摘要同一回退规则。
|
||||
依赖:order_review_draft_service._validation / build_confirmable_draft_summary、
|
||||
field_rules.compute_effective_reservation_id。
|
||||
逻辑:资格服务已算 effective_reservation_id,但确认物化/冻结只认行级 reservation_id;
|
||||
本测试锁定校验不误拦,且确认摘要必须把表头值写回行字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app.services.shipping_notice.order_review_draft_service import (
|
||||
_validation,
|
||||
build_confirmable_draft_summary,
|
||||
)
|
||||
|
||||
|
||||
def _string_field(field_id: str, field_code: str, *, scope: str, required: bool) -> dict:
|
||||
"""构造草稿校验用的最小 Schema 字段配置。"""
|
||||
return {
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
'scope': scope,
|
||||
'value_type': 'string',
|
||||
'required': required,
|
||||
'normalizer_key': 'reservation_id' if field_code == 'reservation_id' else 'trim',
|
||||
'validator_keys': ['reservation_id'] if field_code == 'reservation_id' else [],
|
||||
'display_name': field_code,
|
||||
}
|
||||
|
||||
|
||||
def test_draft_validation_accepts_required_line_reservation_from_header():
|
||||
"""
|
||||
表头预约单号有效、行格空时:不得再发 required_field_missing;
|
||||
投影行应带上表头有效值供资格服务使用。
|
||||
"""
|
||||
fields = {
|
||||
'h-res': _string_field('h-res', 'reservation_id', scope='header', required=False),
|
||||
'l-res': _string_field('l-res', 'reservation_id', scope='line', required=True),
|
||||
'part-id': {
|
||||
**_string_field('part-id', 'part_number', scope='line', required=True),
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['atomic_part_number'],
|
||||
},
|
||||
'qty-id': {
|
||||
'field_id': 'qty-id',
|
||||
'field_code': 'qty',
|
||||
'scope': 'line',
|
||||
'value_type': 'decimal',
|
||||
'required': True,
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'],
|
||||
'display_name': 'qty',
|
||||
},
|
||||
}
|
||||
draft = SimpleNamespace(
|
||||
header_values_json={
|
||||
'machine_fields': [
|
||||
{'field_id': 'h-res', 'observations': [{'value': '2000485916'}]},
|
||||
],
|
||||
'values': {},
|
||||
},
|
||||
lines_json=[{
|
||||
'draft_line_id': 'machine-1',
|
||||
'machine_fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
|
||||
# 行预约单号故意缺失:应回退表头。
|
||||
],
|
||||
'values': {},
|
||||
}],
|
||||
draft_version=1,
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
current_draft=draft,
|
||||
candidate_id=None,
|
||||
unit=None,
|
||||
unit_id=None,
|
||||
run=None,
|
||||
run_id=None,
|
||||
case_no='CASE-RES-FALLBACK',
|
||||
document_id=1,
|
||||
)
|
||||
captured_lines: list[dict] = []
|
||||
|
||||
def _fake_eligibility(*, lines, **_kwargs):
|
||||
captured_lines.extend(lines)
|
||||
return {
|
||||
'can_build': True,
|
||||
'can_auto_create': True,
|
||||
'shadow_would_auto_create': False,
|
||||
'gates': {'required_fields_complete': True},
|
||||
'failed_gates': [],
|
||||
'issues': [],
|
||||
'line_projections': [{
|
||||
'draft_line_id': 'machine-1',
|
||||
'effective_reservation_id': '2000485916',
|
||||
}],
|
||||
'qualification': {},
|
||||
'assessment': {
|
||||
'can_create_task': True,
|
||||
'missing_required_fields': [],
|
||||
'invalid_lines': [],
|
||||
},
|
||||
'enabled_inventory_source_codes': [],
|
||||
}
|
||||
|
||||
with (
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._schema_fields',
|
||||
return_value=fields,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service.assess_order_build_eligibility',
|
||||
side_effect=_fake_eligibility,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.candidate_qualification_service.resolve_review_case_customer_resolved',
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
result = _validation(case)
|
||||
|
||||
# 关键断言:表头回退后不再把行预约单号标成 Schema 必填缺失。
|
||||
assert not any(
|
||||
str(item.get('code') or '') == 'required_field_missing'
|
||||
and str(item.get('field_id') or '') == 'l-res'
|
||||
for item in (result.get('issues') or [])
|
||||
)
|
||||
assert captured_lines and captured_lines[0].get('reservation_id') == '2000485916'
|
||||
assert result['can_build'] is True
|
||||
|
||||
|
||||
def test_draft_validation_still_blocks_when_header_and_line_reservation_missing():
|
||||
"""表头与行均无有效预约单号时,行必填仍应阻断。"""
|
||||
fields = {
|
||||
'h-res': _string_field('h-res', 'reservation_id', scope='header', required=False),
|
||||
'l-res': _string_field('l-res', 'reservation_id', scope='line', required=True),
|
||||
'part-id': {
|
||||
**_string_field('part-id', 'part_number', scope='line', required=True),
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['atomic_part_number'],
|
||||
},
|
||||
'qty-id': {
|
||||
'field_id': 'qty-id',
|
||||
'field_code': 'qty',
|
||||
'scope': 'line',
|
||||
'value_type': 'decimal',
|
||||
'required': True,
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'],
|
||||
'display_name': 'qty',
|
||||
},
|
||||
}
|
||||
draft = SimpleNamespace(
|
||||
header_values_json={'machine_fields': [], 'values': {}},
|
||||
lines_json=[{
|
||||
'draft_line_id': 'machine-1',
|
||||
'machine_fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
|
||||
],
|
||||
'values': {},
|
||||
}],
|
||||
draft_version=1,
|
||||
)
|
||||
case = SimpleNamespace(
|
||||
current_draft=draft,
|
||||
candidate_id=None,
|
||||
unit=None,
|
||||
unit_id=None,
|
||||
run=None,
|
||||
run_id=None,
|
||||
case_no='CASE-RES-MISSING',
|
||||
document_id=1,
|
||||
)
|
||||
|
||||
with (
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._schema_fields',
|
||||
return_value=fields,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service.assess_order_build_eligibility',
|
||||
return_value={
|
||||
'can_build': True,
|
||||
'can_auto_create': False,
|
||||
'shadow_would_auto_create': False,
|
||||
'gates': {},
|
||||
'failed_gates': [],
|
||||
'issues': [],
|
||||
'line_projections': [],
|
||||
'qualification': {},
|
||||
'assessment': {
|
||||
'can_create_task': True,
|
||||
'missing_required_fields': [],
|
||||
'invalid_lines': [],
|
||||
},
|
||||
'enabled_inventory_source_codes': [],
|
||||
},
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.candidate_qualification_service.resolve_review_case_customer_resolved',
|
||||
return_value=True,
|
||||
),
|
||||
):
|
||||
result = _validation(case)
|
||||
|
||||
# 关键断言:双端皆空时仍报行级预约单号缺失。
|
||||
assert any(
|
||||
str(item.get('code') or '') == 'required_field_missing'
|
||||
and str(item.get('field_id') or '') == 'l-res'
|
||||
for item in (result.get('issues') or [])
|
||||
)
|
||||
assert result['can_build'] is False
|
||||
|
||||
|
||||
def test_build_confirmable_draft_summary_fills_line_reservation_from_header():
|
||||
"""
|
||||
确认建单摘要必须把表头有效预约单号写进行级 reservation_id,
|
||||
否则物化 Extraction 无行 FieldValue,冻结门禁会 ORDER_FREEZE_BLOCKED。
|
||||
"""
|
||||
fields = {
|
||||
'h-res': _string_field('h-res', 'reservation_id', scope='header', required=False),
|
||||
'l-res': _string_field('l-res', 'reservation_id', scope='line', required=True),
|
||||
'part-id': {
|
||||
**_string_field('part-id', 'part_number', scope='line', required=True),
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['atomic_part_number'],
|
||||
},
|
||||
'qty-id': {
|
||||
'field_id': 'qty-id',
|
||||
'field_code': 'qty',
|
||||
'scope': 'line',
|
||||
'value_type': 'decimal',
|
||||
'required': True,
|
||||
'normalizer_key': 'trim',
|
||||
'validator_keys': ['positive_decimal'],
|
||||
'display_name': 'qty',
|
||||
},
|
||||
}
|
||||
draft = SimpleNamespace(
|
||||
header_values_json={
|
||||
'machine_fields': [
|
||||
{'field_id': 'h-res', 'observations': [{'value': '2000485916'}]},
|
||||
],
|
||||
'values': {},
|
||||
},
|
||||
lines_json=[{
|
||||
'draft_line_id': 'machine-1',
|
||||
'machine_fields': [
|
||||
{'field_id': 'part-id', 'observations': [{'value': 'A001'}]},
|
||||
{'field_id': 'qty-id', 'observations': [{'value': '1'}]},
|
||||
],
|
||||
'values': {},
|
||||
}],
|
||||
draft_version=3,
|
||||
schema_version_id=1,
|
||||
)
|
||||
case = SimpleNamespace(current_draft=draft)
|
||||
|
||||
with (
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._schema_fields',
|
||||
return_value=fields,
|
||||
),
|
||||
patch(
|
||||
'app.services.shipping_notice.order_review_draft_service._validation',
|
||||
return_value={'status': 'ready', 'can_build': True, 'issues': []},
|
||||
),
|
||||
):
|
||||
summary, _validation_result = build_confirmable_draft_summary(case)
|
||||
|
||||
# 关键断言:确认摘要行上须带有效预约单号,供物化/冻结消费。
|
||||
assert summary.get('reservation_id') == '2000485916'
|
||||
assert summary['lines'][0].get('reservation_id') == '2000485916'
|
||||
assert summary['lines'][0].get('draft_line_id') == 'machine-1'
|
||||
@@ -681,7 +681,7 @@ def test_runtime_preserves_customer_po_line_number_without_system_line_projectio
|
||||
|
||||
|
||||
def test_runtime_projects_effective_reservation_with_line_override(app):
|
||||
"""行级 Reservation 优先,缺失时回退订单头,二者均可选不构成阶段 0 门禁。"""
|
||||
"""行级 Reservation 优先;缺失时回退订单头,且不得再因行缺值误拦完整性门禁。"""
|
||||
with app.app_context():
|
||||
service.initialize_schema({'display_name': '订单字段'}, actor_id=None)
|
||||
header_reservation = service.save_field(
|
||||
@@ -691,9 +691,11 @@ def test_runtime_projects_effective_reservation_with_line_override(app):
|
||||
{'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string'}, actor_id=None,
|
||||
)
|
||||
draft = service.create_draft({}, actor_id=None)
|
||||
line_cfg = _config(line_reservation['id'], '行预约单号', value_type='string')
|
||||
line_cfg.update({'auto_create_key_field': True, 'minimum_confidence': 0.95})
|
||||
published = _save_and_publish(draft, [
|
||||
_config(header_reservation['id'], '订单预约单号', value_type='string'),
|
||||
_config(line_reservation['id'], '行预约单号', value_type='string'),
|
||||
line_cfg,
|
||||
])
|
||||
intake_id, documents, actor_id = _seed_documents()
|
||||
document = documents[1]
|
||||
@@ -715,7 +717,13 @@ def test_runtime_projects_effective_reservation_with_line_override(app):
|
||||
intake_id=intake_id, snapshot_hash='r' * 64, documents=documents, actor_id=actor_id,
|
||||
)
|
||||
|
||||
assert [item['effective_reservation_id'] for item in result['system_line_projections']] == ['3000000001', '3000000002']
|
||||
assert [item['effective_reservation_id'] for item in result['system_line_projections']] == [
|
||||
'3000000001', '3000000002',
|
||||
]
|
||||
# 关键断言:行投影已回填表头值;完整性不得因「行格空」阻断预约单号。
|
||||
assert result['lines'][0].get('reservation_id') == '3000000001'
|
||||
assert result['lines'][1].get('reservation_id') == '3000000002'
|
||||
assert 'reservation_id' not in (result.get('blocked_fields') or [])
|
||||
|
||||
|
||||
def test_dynamic_schema_contract_and_cross_document_persistence(app):
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""
|
||||
tests/test_shipping_stp_projection_cache_shell.py
|
||||
|
||||
用途:空壳投影缓存不得把已失败的 STP Job 误判为「未入队」;
|
||||
ORDER_FREEZE_BLOCKED 在 can_auto+can_build 时须投影为可技术重试。
|
||||
依赖:order_stp_auto_create_service.find_latest_stp_job、
|
||||
reconciliation_projector.project_case_automation_status。
|
||||
逻辑:Gate 投影会写入无 stp_jobs_* 的 session 缓存;若按「缺键=空列表」处理,
|
||||
UI 会错误展示重试自动推进,而 API 又因真实 failed Job 抛 RETRY_STP_BLOCKED_MANUAL。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from app import db
|
||||
from app.services.shipping_notice.order_stp_auto_create_service import find_latest_stp_job
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_case_automation_status,
|
||||
)
|
||||
|
||||
|
||||
def test_find_latest_stp_job_falls_back_when_cache_shell_has_no_ref(app):
|
||||
"""空壳缓存有 dict 但无该 business_ref 时,必须查库而非返回 None。"""
|
||||
with app.app_context():
|
||||
db.session.info['shipping_conversation_projection_read_cache'] = {
|
||||
'gates_by_execution_id': {},
|
||||
'stp_jobs_by_ref': {},
|
||||
}
|
||||
sentinel = SimpleNamespace(id=1904, status='failed', business_ref='stp-auto:r:doc-1:v3')
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.Job'
|
||||
) as job_model:
|
||||
query = job_model.query.filter.return_value.order_by.return_value
|
||||
query.first.return_value = sentinel
|
||||
found = find_latest_stp_job(business_ref='stp-auto:r:doc-1:v3')
|
||||
assert found is sentinel
|
||||
|
||||
|
||||
def test_order_freeze_blocked_projects_retryable_when_can_auto(app):
|
||||
"""
|
||||
历史 Job 以 ORDER_FREEZE_BLOCKED + retryable=false 落库时,
|
||||
若当前仍可建单,投影必须允许技术重试(与 assert_case_not_blocked_manual 放行一致)。
|
||||
"""
|
||||
with app.app_context():
|
||||
draft = SimpleNamespace(draft_version=3)
|
||||
case = SimpleNamespace(
|
||||
case_no='SORC-TEST-FREEZE',
|
||||
status='ready',
|
||||
confirmed_task_id=None,
|
||||
document_id=246,
|
||||
current_draft=draft,
|
||||
run=SimpleNamespace(run_no='SNER-TEST'),
|
||||
candidate_id=None,
|
||||
)
|
||||
failed_job = SimpleNamespace(
|
||||
id=1904,
|
||||
status='failed',
|
||||
result_json={
|
||||
'retryable': False,
|
||||
'blocking_reason': 'SHIPPING.ORDER_FREEZE_BLOCKED',
|
||||
'error_code': 'SHIPPING.ORDER_FREEZE_BLOCKED',
|
||||
},
|
||||
)
|
||||
validation = {'status': 'ready', 'can_auto_create': True, 'can_build': True}
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.build_stp_idempotency_key',
|
||||
return_value='stp-auto:SNER-TEST:doc-246:v3',
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.find_latest_stp_job',
|
||||
return_value=failed_job,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_workbench_projection.resolve_formal_ot',
|
||||
return_value={'has_formal_ot': False, 'task_missing': False},
|
||||
):
|
||||
auto = project_case_automation_status(
|
||||
case, validation=validation, post_confirm=None,
|
||||
)
|
||||
|
||||
assert auto['status'] == 'failed'
|
||||
assert auto['retryable'] is True
|
||||
assert auto['job_id'] == 1904
|
||||
assert auto['blocking_reason'] == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
@@ -80,6 +80,34 @@ def test_tree_nodes_have_path_id_and_no_raw_paths_in_serialized_dto():
|
||||
assert payload['data_path_hash'].startswith('sha256:')
|
||||
assert 'data_path' not in payload
|
||||
assert '4510039227' not in json.dumps(payload)
|
||||
assert 'raw_value' not in json.dumps(payload)
|
||||
|
||||
|
||||
def test_tree_nodes_can_reveal_full_sample_display_without_raw_value_key():
|
||||
"""断言意图:reveal 路径可把完整样本写入 display,但仍禁止 raw_value 键。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
root = analysis.nodes[0]
|
||||
payload = serialize_tree_node(root, include_values=True, include_full_values=True)
|
||||
dumped = json.dumps(payload)
|
||||
assert 'raw_value' not in dumped
|
||||
assert '4510039227' in dumped
|
||||
assert 'data_path' not in payload
|
||||
|
||||
def find_leaf(node: dict):
|
||||
if node.get('is_leaf'):
|
||||
return node
|
||||
for child in node.get('children') or []:
|
||||
found = find_leaf(child)
|
||||
if found:
|
||||
return found
|
||||
return None
|
||||
|
||||
leaf = find_leaf(payload)
|
||||
assert leaf is not None
|
||||
assert leaf.get('full_value_revealed') is True
|
||||
assert leaf.get('display_policy') == 'full'
|
||||
assert '•' not in str(leaf.get('sample_value_display') or '')
|
||||
assert '…' not in str(leaf.get('sample_value_display') or '')
|
||||
|
||||
|
||||
def test_mask_value_for_dto():
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_formal_extraction_route.py
|
||||
|
||||
用途:阶段 3 正式 Worker 路由端到端——精确命中 published XFA Profile 后产出 golden 字段。
|
||||
用途:阶段 3 正式 Worker 路由端到端——精确命中 published XFA Profile 后产出 golden 字段;
|
||||
另锁定盲测 rows 剔除表头、空视觉 reservation 不冲掉 datasets。
|
||||
依赖:order_extraction_workflow、xfa helpers、pytest。
|
||||
逻辑:合成 hybrid PDF + 冻结 Profile 快照 → route_deterministic_unit;
|
||||
断言 A/B 字段、needs_review 失败关闭、无通用回退、snapshot 冻结 parser identity。
|
||||
@@ -36,11 +37,16 @@ def test_datasets_adapter_uses_ocr_only_as_cross_check_evidence():
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 1
|
||||
assert result['mismatch_count'] == 1
|
||||
assert result['mismatches'] == [{'row_index': 0, 'field_id': 'material'}]
|
||||
assert result['mismatches'] == [{
|
||||
'row_index': 0,
|
||||
'field_id': 'material',
|
||||
'ocr_value': 'OCR-M1',
|
||||
'datasets_value': 'DATA-M1',
|
||||
}]
|
||||
|
||||
|
||||
def test_datasets_validation_cross_check_reports_shared_ocr_mismatch():
|
||||
"""关键断言:验证/盲测阶段也必须拒绝 OCR 与 datasets 的字段冲突。"""
|
||||
"""关键断言:验证/盲测对照须标出 OCR 与 datasets 冲突字段及两侧截断值。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_validation_evidence_cross_check,
|
||||
)
|
||||
@@ -58,11 +64,17 @@ def test_datasets_validation_cross_check_reports_shared_ocr_mismatch():
|
||||
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 2
|
||||
assert result['mismatches'] == [{'scope': 'header', 'row_index': None, 'field_code': 'customer_po_no'}]
|
||||
assert result['mismatches'] == [{
|
||||
'scope': 'header',
|
||||
'row_index': None,
|
||||
'field_code': 'customer_po_no',
|
||||
'ocr_value': 'OCR-PO',
|
||||
'datasets_value': 'DATA-PO',
|
||||
}]
|
||||
|
||||
|
||||
def test_datasets_blind_cross_check_reports_shared_ocr_mismatch():
|
||||
"""关键断言:盲测也复用共同视觉候选,只把 datasets 保留为正式值。"""
|
||||
"""关键断言:盲测也复用共同视觉候选,只把 datasets 保留为正式值;对照带两侧值。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_blind_candidate_cross_check,
|
||||
)
|
||||
@@ -80,7 +92,13 @@ def test_datasets_blind_cross_check_reports_shared_ocr_mismatch():
|
||||
|
||||
assert result['status'] == 'mismatched'
|
||||
assert result['compared_field_count'] == 2
|
||||
assert result['mismatches'] == [{'scope': 'header', 'row_index': None, 'field_code': 'customer_po_no'}]
|
||||
assert result['mismatches'] == [{
|
||||
'scope': 'header',
|
||||
'row_index': None,
|
||||
'field_code': 'customer_po_no',
|
||||
'ocr_value': 'OCR-PO',
|
||||
'datasets_value': 'DATA-PO',
|
||||
}]
|
||||
|
||||
|
||||
def test_datasets_overlap_reuses_common_visual_evidence_then_appends_identity_conflict(monkeypatch):
|
||||
@@ -186,6 +204,226 @@ def test_datasets_overlap_parse_result_uses_formal_datasets_extraction(monkeypat
|
||||
assert result == {'passed': True, 'reason_codes': []}
|
||||
|
||||
|
||||
def test_blind_rows_exclude_header_fields_copied_onto_line_rows():
|
||||
"""
|
||||
正式提取会把单头挂到每行;盲测明细 JSON 必须剔除这些 header field_code。
|
||||
关键断言:currency/reservation_id 等只应出现在 order_fields,不得留在 rows。
|
||||
"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_blind_rows_excluding_header_fields,
|
||||
)
|
||||
|
||||
extraction = SimpleNamespace(
|
||||
header_fields=[
|
||||
SimpleNamespace(field_code='currency'),
|
||||
SimpleNamespace(field_code='reservation_id'),
|
||||
SimpleNamespace(field_code='bill_to_customer'),
|
||||
],
|
||||
rows=[{
|
||||
'fields': [
|
||||
{'field_code': 'currency', 'value': 'USD'},
|
||||
{'field_code': 'reservation_id', 'value': '1000144510'},
|
||||
{'field_code': 'bill_to_customer', 'value': 'Cloud Network'},
|
||||
{'field_code': 'part_number', 'value': 'D4-A08'},
|
||||
{'field_code': 'qty', 'value': 1},
|
||||
],
|
||||
}],
|
||||
)
|
||||
rows = _blind_rows_excluding_header_fields(
|
||||
extraction=extraction, json_value=lambda value: value,
|
||||
)
|
||||
assert rows == [{'part_number': 'D4-A08', 'qty': 1}]
|
||||
|
||||
|
||||
def test_empty_visual_reservation_does_not_wipe_datasets_header():
|
||||
"""空视觉 reservation 不得冲掉 datasets 已抽取的单头值。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_merge_visual_reservation_into_blind_candidate,
|
||||
)
|
||||
|
||||
datasets_candidate = {
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': '1000144510',
|
||||
'scope': 'header', 'status': 'confirmed', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
_merge_visual_reservation_into_blind_candidate(
|
||||
datasets_candidate=datasets_candidate,
|
||||
visual_candidate={
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': None,
|
||||
'scope': 'header', 'status': 'unavailable', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{}],
|
||||
},
|
||||
)
|
||||
reservation = next(
|
||||
item for item in datasets_candidate['order_fields']
|
||||
if item['field_code'] == 'reservation_id'
|
||||
)
|
||||
assert reservation['value'] == '1000144510'
|
||||
|
||||
|
||||
def test_non_empty_visual_reservation_overrides_datasets_header():
|
||||
"""非空视觉 Reservation 专区结果应覆盖 datasets 单头。"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_merge_visual_reservation_into_blind_candidate,
|
||||
)
|
||||
|
||||
datasets_candidate = {
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': 'OLD',
|
||||
'scope': 'header', 'status': 'confirmed', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
_merge_visual_reservation_into_blind_candidate(
|
||||
datasets_candidate=datasets_candidate,
|
||||
visual_candidate={
|
||||
'order_fields': [{
|
||||
'field_code': 'reservation_id', 'value': '1000144510',
|
||||
'scope': 'header', 'status': 'confirmed', 'field_id': 'f-res',
|
||||
}],
|
||||
'rows': [{'reservation_id': 'LINE-1'}],
|
||||
},
|
||||
)
|
||||
reservation = next(
|
||||
item for item in datasets_candidate['order_fields']
|
||||
if item['field_code'] == 'reservation_id'
|
||||
)
|
||||
assert reservation['value'] == '1000144510'
|
||||
assert datasets_candidate['rows'][0]['reservation_id'] == 'LINE-1'
|
||||
|
||||
|
||||
def test_datasets_success_drops_ocr_parse_strategy_fallback_codes():
|
||||
"""
|
||||
datasets 正式通过后,OCR 行重建 PARSE_STRATEGY 不得留作阻断码。
|
||||
关键断言:PARSE_STRATEGY_* / 无表/坐标证据不可用被剔除;其它码保留。
|
||||
"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_fallback_codes_after_datasets_success,
|
||||
)
|
||||
|
||||
kept = _fallback_codes_after_datasets_success([
|
||||
'PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION',
|
||||
'PARSE_STRATEGY_ROW_MODE_AMBIGUOUS',
|
||||
'business_table_not_found',
|
||||
'coordinate_evidence_unavailable',
|
||||
'reservation_region_needs_review',
|
||||
])
|
||||
assert kept == ['reservation_region_needs_review']
|
||||
|
||||
|
||||
def test_blind_gate_does_not_fail_on_ocr_or_visual_metrics():
|
||||
"""
|
||||
XFA:OCR↔datasets 与 visual/mirror/evidence 指标均不得硬拦盲测(datasets 为正式值)。
|
||||
关键断言:指标 < 1.0 且对照 mismatched 时 failures 为空;抽取失败仍硬拦。
|
||||
"""
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
_blind_candidate_cross_check,
|
||||
blind_gate_failures,
|
||||
)
|
||||
|
||||
visual = {
|
||||
'order_fields': [
|
||||
{'field_code': 'currency', 'value': 'usd', 'scope': 'header'},
|
||||
{'field_code': 'bill_to_customer', 'value': 'Full Block', 'scope': 'header'},
|
||||
],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
datasets = {
|
||||
'order_fields': [
|
||||
{'field_code': 'currency', 'value': 'USD', 'scope': 'header'},
|
||||
{'field_code': 'bill_to_customer', 'value': 'Cloud Network', 'scope': 'header'},
|
||||
],
|
||||
'rows': [{'part_number': 'P1'}],
|
||||
}
|
||||
comparison = _blind_candidate_cross_check(
|
||||
visual_candidate=visual, datasets_candidate=datasets,
|
||||
)
|
||||
assert comparison['status'] == 'mismatched'
|
||||
assert {item['field_code'] for item in comparison['mismatches']} == {
|
||||
'currency', 'bill_to_customer',
|
||||
}
|
||||
failures, metrics = blind_gate_failures(
|
||||
candidate={
|
||||
'extraction_status': 'parsed',
|
||||
'reason_codes': [],
|
||||
'visual_coverage_rate': 0.857,
|
||||
'mirror_consistency_rate': 0.5,
|
||||
'evidence_retention_rate': 0.9,
|
||||
'ocr_datasets_cross_check': comparison,
|
||||
},
|
||||
sample_id=44,
|
||||
)
|
||||
assert failures == []
|
||||
assert metrics['visual_coverage_rate'] == 0.857
|
||||
assert 'ocr_datasets_mismatch' not in failures
|
||||
|
||||
extract_failures, _ = blind_gate_failures(
|
||||
candidate={
|
||||
'extraction_status': 'failed',
|
||||
'reason_codes': ['xfa_dataset_missing'],
|
||||
'visual_coverage_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
'evidence_retention_rate': 1.0,
|
||||
},
|
||||
sample_id=45,
|
||||
)
|
||||
assert extract_failures == ['sample:45:extraction:xfa_dataset_missing']
|
||||
|
||||
|
||||
def test_serialize_suite_exposes_soft_diagnostics_without_payload_values():
|
||||
"""执行摘要应带 soft_diagnostics 字段码,且不含对照正文值。"""
|
||||
from app.services.shipping_notice.document_profile_quality_service import serialize_suite
|
||||
|
||||
suite = SimpleNamespace(
|
||||
id=1,
|
||||
profile_id=9,
|
||||
profile_checksum='abc',
|
||||
status='draft',
|
||||
samples=[],
|
||||
approved_at=None,
|
||||
runs=[
|
||||
SimpleNamespace(
|
||||
status='passed',
|
||||
sample_count=1,
|
||||
passed_sample_count=1,
|
||||
failure_codes_json=[],
|
||||
evidence_json={
|
||||
'metrics': {
|
||||
'visual_coverage_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'key_field_accuracy_rate': 1.0,
|
||||
},
|
||||
'soft_diagnostics': [{
|
||||
'sample_id': 44,
|
||||
'code': 'ocr_datasets_mismatch',
|
||||
'mismatch_count': 1,
|
||||
'fields': [{
|
||||
'scope': 'header',
|
||||
'field_code': 'bill_to_customer',
|
||||
'row_index': None,
|
||||
'ocr_value': 'Cloud Network Technology Kft. Full Block',
|
||||
'datasets_value': 'Cloud Network Technology Kft.',
|
||||
}],
|
||||
}],
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
payload = serialize_suite(suite)
|
||||
assert payload['latest_run']['status'] == 'passed'
|
||||
field = payload['latest_run']['soft_diagnostics'][0]['fields'][0]
|
||||
assert field['field_code'] == 'bill_to_customer'
|
||||
assert field['ocr_value'].startswith('Cloud Network')
|
||||
assert field['datasets_value'] == 'Cloud Network Technology Kft.'
|
||||
dumped = json.dumps(payload['latest_run']['soft_diagnostics'])
|
||||
assert 'normalized_value' not in dumped
|
||||
|
||||
|
||||
def test_xfa_unified_bindings_require_header_blind_truths():
|
||||
"""bindings-only XFA Profile 的 Header 真值不得因 legacy 映射为空而被静默丢弃。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_formal_multiline_extraction.py
|
||||
|
||||
用途:正式提取——多行 MATNR 经已确认 matcher 规则产出 customer_part_number 与 part_number。
|
||||
用途:正式提取——多行 MATNR 经已确认 matcher 规则产出 customer_part_number 与 part_number;
|
||||
Header INVOICED_TO 拆分不得因带 split_rule_ref 的目标 binding 重复读源全文。
|
||||
依赖:xfa_profile_extraction、xfa_split_rule_contract、xfa_dataset、pytest。
|
||||
逻辑:合成多行 datasets XML + 已确认规则集;断言 mapped 字段、evidence_only 与 needs_review 边界。
|
||||
"""
|
||||
@@ -127,7 +128,7 @@ def _confirmed_matnr_rule_set() -> dict:
|
||||
|
||||
|
||||
def _confirmed_header_rule_set() -> dict:
|
||||
"""构造 Header 拆分规则:第 1 行 mapped,其余行 evidence_only。"""
|
||||
"""构造 Header 拆分规则:第 1 行客户,第 2–末行地址。"""
|
||||
return XfaSplitRuleSet(
|
||||
rule_set_id='invoiced-to-v1',
|
||||
rule_version=1,
|
||||
@@ -144,6 +145,14 @@ def _confirmed_header_rule_set() -> dict:
|
||||
handling='mapped', target_field_id='f-bill-customer', target_field_code='bill_to_customer',
|
||||
),
|
||||
),
|
||||
XfaSplitRule(
|
||||
rule_id='bill-address',
|
||||
matcher=XfaSplitMatcher(type='position', line_index=2, line_end=4),
|
||||
segment=XfaSplitSegment(
|
||||
segment_id=new_segment_id(), segment_code='bill_address', display_name='账款地址',
|
||||
handling='mapped', target_field_id='f-bill-address', target_field_code='bill_to_address',
|
||||
),
|
||||
),
|
||||
],
|
||||
unmatched_line_policy='evidence_only',
|
||||
source='user', status='confirmed', requires_confirmation=False,
|
||||
@@ -158,9 +167,10 @@ def _xfa_binding(
|
||||
scope: str,
|
||||
path_id: str,
|
||||
data_path: str,
|
||||
split_rule_ref: dict | None = None,
|
||||
) -> dict:
|
||||
"""构造最小合法统一 binding。"""
|
||||
return {
|
||||
payload = {
|
||||
'binding_id': binding_id,
|
||||
'field_id': field_id,
|
||||
'field_code': field_code,
|
||||
@@ -178,6 +188,9 @@ def _xfa_binding(
|
||||
'confidence': 0.0,
|
||||
},
|
||||
}
|
||||
if split_rule_ref is not None:
|
||||
payload['split_rule_ref'] = split_rule_ref
|
||||
return payload
|
||||
|
||||
|
||||
def _raw_profile(*, split_rules: list[dict] | None = None) -> dict:
|
||||
@@ -279,7 +292,7 @@ def test_draft_split_rules_fail_closed_needs_review():
|
||||
|
||||
|
||||
def test_confirmed_header_split_rules_extract_customer_line():
|
||||
"""Header 源规则执行一次并产出第 1 行客户名;其余行保留为 evidence。"""
|
||||
"""Header 源规则执行一次并产出客户/地址;不得再附带源全文重复项。"""
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=_raw_profile(split_rules=[_confirmed_header_rule_set()]),
|
||||
@@ -290,4 +303,54 @@ def test_confirmed_header_split_rules_extract_customer_line():
|
||||
)
|
||||
header_values = {item.field_code: item.normalized_value for item in result.header_fields}
|
||||
assert header_values['bill_to_customer'] == 'Cloud Network Technology Kft.'
|
||||
assert header_values['bill_to_address'] == 'Bánki Donát u. 1,\n2900 Komárom,\nHungary'
|
||||
assert sum(item.field_code == 'bill_to_customer' for item in result.header_fields) == 1
|
||||
assert sum(item.field_code == 'bill_to_address' for item in result.header_fields) == 1
|
||||
|
||||
|
||||
def test_header_split_target_bindings_do_not_duplicate_raw_source():
|
||||
"""
|
||||
编辑器形态:账款客户/地址 binding 共享源 path 且带 split_rule_ref。
|
||||
关键断言:表头只保留拆分段,禁止 STEP1 再读源全文导致重复与错误值。
|
||||
"""
|
||||
rule_set = _confirmed_header_rule_set()
|
||||
customer_seg = rule_set['rules'][0]['segment']['segment_id']
|
||||
address_seg = rule_set['rules'][1]['segment']['segment_id']
|
||||
raw = _raw_profile(split_rules=[rule_set])
|
||||
raw['definition']['bindings'].extend([
|
||||
_xfa_binding(
|
||||
binding_id='bind-bill-customer',
|
||||
field_id='f-bill-customer',
|
||||
field_code='bill_to_customer',
|
||||
scope='header',
|
||||
path_id='path-invoiced-to',
|
||||
data_path='/data/HEADER/INVOICED_TO',
|
||||
split_rule_ref={'rule_set_id': 'invoiced-to-v1', 'segment_id': customer_seg},
|
||||
),
|
||||
_xfa_binding(
|
||||
binding_id='bind-bill-address',
|
||||
field_id='f-bill-address',
|
||||
field_code='bill_to_address',
|
||||
scope='header',
|
||||
path_id='path-invoiced-to',
|
||||
data_path='/data/HEADER/INVOICED_TO',
|
||||
split_rule_ref={'rule_set_id': 'invoiced-to-v1', 'segment_id': address_seg},
|
||||
),
|
||||
])
|
||||
analysis = parse_xfa_datasets(_multiline_datasets_xml())
|
||||
result = extract_xfa_profile(
|
||||
raw_profile=raw,
|
||||
dataset_analysis=analysis,
|
||||
schema_definition=_schema_definition(),
|
||||
document_id=1,
|
||||
packet_checksum='pkt-checksum-0123456789abcdef',
|
||||
)
|
||||
customers = [item for item in result.header_fields if item.field_code == 'bill_to_customer']
|
||||
addresses = [item for item in result.header_fields if item.field_code == 'bill_to_address']
|
||||
assert len(customers) == 1
|
||||
assert len(addresses) == 1
|
||||
assert customers[0].normalized_value == 'Cloud Network Technology Kft.'
|
||||
assert addresses[0].normalized_value == 'Bánki Donát u. 1,\n2900 Komárom,\nHungary'
|
||||
# 禁止 STEP1 把源全文挂到目标 field_code。
|
||||
assert 'Cloud Network Technology Kft.\nBánki' not in (customers[0].normalized_value or '')
|
||||
assert customers[0].normalized_value != addresses[0].normalized_value
|
||||
@@ -454,6 +454,30 @@ def test_normalize_definition_freezes_schema_identity_for_visual_header_line_fie
|
||||
assert field['target_fields'] == [{'field_id': 'f-qty', 'field_code': 'quantity', 'scope': 'line'}]
|
||||
|
||||
|
||||
def test_normalize_definition_freezes_schema_identity_for_order_field_layouts():
|
||||
"""订单头视觉框画布常提交空 field_id,XFA 保存必须按 Schema 冻结,禁止盲测读到空串。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
raw, context, _path_id_by_path = _normalization_raw_profile(analysis)
|
||||
assert raw['order_field_layouts'], 'fixture must already contain an order field layout'
|
||||
for layout in raw['order_field_layouts']:
|
||||
layout['field_id'] = ''
|
||||
|
||||
normalized = normalize_definition(
|
||||
raw, schema_version=SimpleNamespace(definition_json=_schema_definition()), path_context=context,
|
||||
)
|
||||
|
||||
# 关键断言:空 field_id 已写成 Schema 主键,持久化定义可直接构造坐标契约。
|
||||
assert all(str(item.get('field_id') or '').strip() for item in normalized['order_field_layouts'])
|
||||
assert all(
|
||||
item['field_id'] == next(
|
||||
field['field_id']
|
||||
for field in _schema_definition()['fields']
|
||||
if field['field_code'] == item['field_code'] and field['scope'] == item['scope']
|
||||
)
|
||||
for item in normalized['order_field_layouts']
|
||||
)
|
||||
|
||||
|
||||
def test_normalize_definition_allows_line_header_inheritance_to_reuse_header_visual_layout():
|
||||
"""行级正式继承可复用同名 Header 视觉框,避免伪造不存在的表格内预约号框。"""
|
||||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||||
|
||||
@@ -107,6 +107,21 @@ def test_position_matcher_accepts_restricted_prefix_post_processor():
|
||||
|
||||
assert matcher.post_processors[0].type == 'prefix'
|
||||
assert matcher.post_processors[0].value == 'MPN'
|
||||
assert matcher.line_end is None
|
||||
assert matcher.join_with is None
|
||||
|
||||
|
||||
def test_position_matcher_accepts_consecutive_line_range():
|
||||
"""连续多行 position:允许 line_end + join_with。"""
|
||||
matcher = XfaSplitMatcher(
|
||||
type='position',
|
||||
line_index=2,
|
||||
line_end=4,
|
||||
join_with='newline',
|
||||
)
|
||||
assert matcher.line_index == 2
|
||||
assert matcher.line_end == 4
|
||||
assert matcher.join_with == 'newline'
|
||||
|
||||
|
||||
def test_rule_set_accepts_rule_id_alias():
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""
|
||||
tests/test_shipping_xfa_unified_blind_test.py
|
||||
|
||||
用途:阶段 6 独立盲测指标——视觉/证据率 < 1.0 时失败;所有 adapter 共用 evidence DTO。
|
||||
依赖:document_profile_quality_service serialize / BlindTestRun evidence_json。
|
||||
逻辑:纯单元验证公共 evidence DTO 与阈值语义。
|
||||
用途:阶段 6 独立盲测指标——公共 evidence DTO 序列化;XFA 视觉指标不硬拦通过。
|
||||
依赖:document_profile_quality_service serialize / BlindTestRun evidence_json;
|
||||
xfa_dataset.blind_gate_failures。
|
||||
逻辑:纯单元验证公共 evidence DTO 与 XFA 盲测硬门禁语义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -13,6 +14,9 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_profile_quality_service import serialize_suite
|
||||
from app.services.shipping_notice.order_profile_value_adapters.xfa_dataset import (
|
||||
blind_gate_failures,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
@@ -47,11 +51,17 @@ def test_serialize_suite_reads_shared_adapter_evidence():
|
||||
assert payload['latest_run']['failure_codes'] == ['sample:1:order_field:po:mismatch']
|
||||
|
||||
|
||||
def test_blind_metrics_threshold_requires_full_coverage():
|
||||
"""关键断言:任一统一指标 < 1.0 即视为盲测不合格(契约语义)。"""
|
||||
rates = {
|
||||
'visual_coverage_rate': 0.99,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
}
|
||||
assert any(float(v) < 1.0 for v in rates.values())
|
||||
def test_xfa_blind_gate_keeps_visual_metrics_as_display_only():
|
||||
"""关键断言:XFA 视觉/镜像/留痕 < 1.0 不产生硬失败码,仅回传指标。"""
|
||||
failures, metrics = blind_gate_failures(
|
||||
candidate={
|
||||
'extraction_status': 'parsed',
|
||||
'reason_codes': [],
|
||||
'visual_coverage_rate': 0.99,
|
||||
'evidence_retention_rate': 1.0,
|
||||
'mirror_consistency_rate': 1.0,
|
||||
},
|
||||
sample_id=7,
|
||||
)
|
||||
assert failures == []
|
||||
assert metrics['visual_coverage_rate'] == 0.99
|
||||
@@ -296,6 +296,46 @@ def test_xfa_publish_gate_accepts_a_line_binding_with_its_shared_line_visual_lay
|
||||
assert not any(item['key'] == 'xfa_shared_field_label_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_xfa_publish_gate_prefers_field_region_id_over_legacy_layout_key():
|
||||
"""有 region_id 时,binding.field_layout_id 必须按 region_id 校验,而不是强制 legacy 键。"""
|
||||
definition = {
|
||||
'order_field_layouts': [],
|
||||
'header_mappings': [],
|
||||
'line_mapping': {'fields': []},
|
||||
'bindings': [{
|
||||
'binding_id': 'line-binding-region',
|
||||
'field_id': 'field-quantity',
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'field_layout_id': 'field_qty_box',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-quantity',
|
||||
'data_path': '/datasets/data/data/ITEMS/DATA/MENGE',
|
||||
},
|
||||
}],
|
||||
'table_regions': [{
|
||||
'line_layouts': [{
|
||||
'layout_id': 'line_1',
|
||||
'field_regions': [{
|
||||
'field_code': 'quantity',
|
||||
'scope': 'line',
|
||||
'region_id': 'field_qty_box',
|
||||
'region': {'x0': .2, 'y0': .3, 'x1': .4, 'y1': .4},
|
||||
}],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
|
||||
blocking = _blocking_shared_field_labels(
|
||||
definition=definition,
|
||||
schema_field_ids={'field-quantity'},
|
||||
)
|
||||
|
||||
# 关键断言:region_id 作为 shared layout 主键时,发布门禁应放行。
|
||||
assert not any(item['key'] == 'xfa_shared_field_label_incomplete' for item in blocking)
|
||||
|
||||
|
||||
def test_suggest_split_rules_service_status_draft(app, monkeypatch, _patch_xfa_io):
|
||||
"""拆分建议 service 层 status 必须为 draft/suggested。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -248,6 +248,75 @@ def test_acroform_composite_value_requires_an_explicit_split_binding(monkeypatch
|
||||
assert 'xfa_acroform_mismatch' in result.reason_codes
|
||||
|
||||
|
||||
def test_acroform_skips_header_bindings_with_split_rule_ref(monkeypatch):
|
||||
"""
|
||||
表头拆分目标不得拿源 Widget 全文对账(与明细 split_rule_ref 跳过对齐)。
|
||||
关键断言:即使 datasets 侧与 AcroForm 源全文因换行不同,也不应报 bill_to_* mismatched。
|
||||
"""
|
||||
from app.services.shipping_notice.document_layout.xfa_profile_extraction import XfaExtractedField
|
||||
|
||||
raw_profile, analysis, extraction = _extract_ok()
|
||||
raw_profile['definition']['bindings'].append({
|
||||
'binding_id': 'bind-bill-customer',
|
||||
'field_id': 'f-bill-customer',
|
||||
'field_code': 'bill_to_customer',
|
||||
'scope': 'header',
|
||||
'value_binding': {
|
||||
'type': 'xfa_dataset',
|
||||
'path_id': 'path-invoiced-to',
|
||||
'data_path': '/data/HEADER/INVOICED_TO',
|
||||
},
|
||||
'visual_binding': {
|
||||
'page_no': 1,
|
||||
'normalized_bbox': {'x0': 0.0, 'y0': 0.0, 'x1': 0.02, 'y1': 0.02},
|
||||
'source': 'suggested',
|
||||
'status': 'suggested',
|
||||
'confidence': 0.0,
|
||||
},
|
||||
'split_rule_ref': {
|
||||
'rule_set_id': 'invoiced-to-v1',
|
||||
'segment_id': 'seg-bill-customer',
|
||||
},
|
||||
})
|
||||
# 模拟 STEP1 误写的源全文(修复前会按 binding_id 参与 AcroForm 对账)。
|
||||
sample_evidence = extraction.header_fields[0].evidence if extraction.header_fields else {}
|
||||
extraction.header_fields = list(extraction.header_fields) + [
|
||||
XfaExtractedField(
|
||||
mapping_id='bind-bill-customer',
|
||||
field_id='f-bill-customer',
|
||||
field_code='bill_to_customer',
|
||||
data_path='/data/HEADER/INVOICED_TO',
|
||||
raw_value='Cloud Network Technology Kft.\nBánki Donát u.1.',
|
||||
normalized_value='Cloud Network Technology Kft.\nBánki Donát u.1.',
|
||||
quote='Cloud Network Technology Kft.\nBánki Donát u.1.',
|
||||
normalizer_key='trim',
|
||||
evidence=sample_evidence,
|
||||
issues=[],
|
||||
),
|
||||
]
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.xfa_validation.read_acroform_fields',
|
||||
lambda _pdf: [
|
||||
XfaAcroformField(
|
||||
'INVOICED_TO',
|
||||
'INVOICED_TO',
|
||||
'Cloud Network Technology Kft.\r\nBánki Donát u.1.',
|
||||
'Cloud***u.1.',
|
||||
),
|
||||
],
|
||||
)
|
||||
result = validate_xfa_extraction(
|
||||
raw_profile=raw_profile,
|
||||
dataset_analysis=analysis,
|
||||
extraction=extraction,
|
||||
pdf_bytes=b'%PDF-fake',
|
||||
)
|
||||
mismatches = result.cross_check_summary.get('acroform_mismatches') or []
|
||||
assert not any(item.get('field_code') == 'bill_to_customer' for item in mismatches)
|
||||
assert 'xfa_acroform_mismatch' not in result.reason_codes
|
||||
|
||||
|
||||
def test_acroform_english_month_date_matches_normalized_dataset_date(monkeypatch):
|
||||
"""AcroForm 的英文月名日期与 datasets ISO 日期一致时不得误判为冲突。"""
|
||||
raw_profile, analysis, extraction = _extract_ok()
|
||||
|
||||
Generated
+940
-409
File diff suppressed because it is too large.
Load diff
@@ -33,6 +33,7 @@
|
||||
"@types/pdfjs-dist": "^2.10.377",
|
||||
"@types/qrcode": "^1.5.6",
|
||||
"@vitejs/plugin-vue": "^6.0.2",
|
||||
"@vue/server-renderer": "^3.5.28",
|
||||
"@vue/test-utils": "^2.4.11",
|
||||
"@vue/tsconfig": "^0.8.1",
|
||||
"autoprefixer": "^10.4.24",
|
||||
|
||||
@@ -234,12 +234,17 @@ export const suggestOrderProfileOrderFields = (
|
||||
|
||||
/** 按当前未保存的工作台定义重读订单单头字段值;传入多页时由后端统一处理跨页冲突。 */
|
||||
export const previewOrderProfileOrderFieldValues = (
|
||||
documentId: number, schemaVersionId: number, pageNo: number, definition: ShippingOrderDocumentProfile['definition'],
|
||||
documentId: number,
|
||||
schemaVersionId: number,
|
||||
pageNo: number,
|
||||
definition: ShippingOrderDocumentProfile['definition'],
|
||||
pageNos?: number[],
|
||||
signal?: AbortSignal,
|
||||
) => requestJson<OrderFieldValuePreviewResponse>(
|
||||
'/api/admin/shipping-notice/order-document-profile-samples/order-field-values-preview', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ document_id: documentId, schema_version_id: schemaVersionId, page_no: pageNo, page_nos: pageNos, definition }),
|
||||
signal,
|
||||
...jsonAuth(),
|
||||
},
|
||||
);
|
||||
@@ -267,12 +272,17 @@ export const completeOrderDocumentProfileWizard = (payload: {
|
||||
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
|
||||
);
|
||||
|
||||
/** 读取样本文档 XFA 字段树(脱敏值,不含明文路径)。 */
|
||||
export const getOrderProfileSampleXfaFieldTree = (documentId: number) =>
|
||||
requestJson<import('../types/shipping-order-document-profile.types').XfaFieldTreeResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/field-tree`,
|
||||
/** 读取样本文档 XFA 字段树;reveal=true 时需敏感读权限并返回完整样本展示值。 */
|
||||
export const getOrderProfileSampleXfaFieldTree = (
|
||||
documentId: number,
|
||||
options?: { reveal?: boolean },
|
||||
) => {
|
||||
const qs = options?.reveal ? '?reveal=true' : '';
|
||||
return requestJson<import('../types/shipping-order-document-profile.types').XfaFieldTreeResponse>(
|
||||
`/api/admin/shipping-notice/order-document-profile-samples/${documentId}/value-adapter/field-tree${qs}`,
|
||||
auth(),
|
||||
);
|
||||
};
|
||||
|
||||
/** 读取 XFA 明细集合候选。 */
|
||||
export const getOrderProfileSampleXfaCollections = (documentId: number) =>
|
||||
|
||||
+134
-3
@@ -3,7 +3,9 @@
|
||||
用途:维护订单模板草稿的独立盲测证据,并完成执行和批准。
|
||||
依赖:盲测 API、Profile 详情、Vue Router、统一业务错误提示和四语言文案。
|
||||
逻辑:验证页进入本页;所有模板按统一视觉表候选和字段证据复核;
|
||||
末端值源差异由服务端 adapter 投影,管理员复核后写入真值,再执行并批准。
|
||||
末端值源差异由服务端 adapter 投影,管理员复核后写入真值,再执行并批准;
|
||||
XFA 以 datasets 为正式值:OCR 对照与视觉/镜像指标仅 soft 诊断,不硬拦;
|
||||
业务错误优先用扁平 errors key 翻译,并附带服务端 message 便于定位。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
|
||||
@@ -94,8 +96,101 @@ const failureDetails = computed(() => (suite.value?.latest_run?.failure_codes ||
|
||||
if (parts[2] === 'mismatch') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.rowsMismatch', { sample: sampleName }) };
|
||||
}
|
||||
if (parts[2] === 'extraction' && parts[3] === 'ocr_datasets_mismatch') {
|
||||
// 历史 Run 可能仍带此硬失败码;现已改为 soft_diagnostics,文案标明「对照诊断」语义。
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.ocrDatasetsMismatchLegacy', { sample: sampleName }) };
|
||||
}
|
||||
if (
|
||||
parts[2] === 'visual_coverage_insufficient'
|
||||
|| parts[2] === 'mirror_consistency_insufficient'
|
||||
|| parts[2] === 'evidence_retention_insufficient'
|
||||
) {
|
||||
// 历史 Run:XFA 视觉/镜像/留痕曾硬拦;现以 datasets 真值为准,请重新执行。
|
||||
return {
|
||||
code,
|
||||
message: t('admin.shippingOrderProfiles.blindTest.failure.visualMetricLegacy', {
|
||||
sample: sampleName,
|
||||
metric: parts[2],
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (parts[2] === 'extraction') {
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.extractionFailed', { sample: sampleName, reason: parts.slice(3).join(':') || 'failed' }) };
|
||||
}
|
||||
return { code, message: t('admin.shippingOrderProfiles.blindTest.failure.unknown', { sample: sampleName }) };
|
||||
}));
|
||||
|
||||
/**
|
||||
* 执行后的 soft 诊断:OCR↔datasets 与 XFA 视觉/镜像/留痕不足,不阻断批准门禁。
|
||||
*/
|
||||
const softDiagnosticDetails = computed(() => {
|
||||
const diagnostics = suite.value?.latest_run?.soft_diagnostics || [];
|
||||
return diagnostics.flatMap((item) => {
|
||||
const sample = suite.value?.samples.find((entry) => entry.id === item.sample_id);
|
||||
const sampleName = sample
|
||||
? `${sample.filename} · P${sample.page_no}`
|
||||
: t('admin.shippingOrderProfiles.blindTest.unknownSample');
|
||||
if (item.code === 'visual_coverage_soft' || item.code === 'mirror_consistency_soft' || item.code === 'evidence_retention_soft') {
|
||||
const ratePct = item.rate == null ? '—' : `${(Number(item.rate) * 100).toFixed(1)}%`;
|
||||
return [{
|
||||
key: `soft-${item.sample_id}-${item.code}`,
|
||||
message: t('admin.shippingOrderProfiles.blindTest.softDiagnostic.visualMetricSoft', {
|
||||
sample: sampleName,
|
||||
metric: t(`admin.shippingOrderProfiles.blindTest.softDiagnostic.metric.${item.code}`),
|
||||
rate: ratePct,
|
||||
}),
|
||||
}];
|
||||
}
|
||||
const fields = item.fields || [];
|
||||
if (!fields.length) {
|
||||
return [{
|
||||
key: `soft-${item.sample_id}-empty`,
|
||||
message: t('admin.shippingOrderProfiles.blindTest.softDiagnostic.ocrDatasetsMismatch', {
|
||||
sample: sampleName,
|
||||
fields: t('admin.shippingOrderProfiles.blindTest.softDiagnostic.fieldsUnknown'),
|
||||
count: item.mismatch_count || 0,
|
||||
}),
|
||||
}];
|
||||
}
|
||||
return fields.map((field, index) => {
|
||||
const code = String(field.field_code || '').trim() || t('admin.shippingOrderProfiles.blindTest.softDiagnostic.fieldsUnknown');
|
||||
const label = field.scope === 'line' && field.row_index != null
|
||||
? `${code}#${Number(field.row_index) + 1}`
|
||||
: code;
|
||||
return {
|
||||
key: `soft-${item.sample_id}-${code}-${index}`,
|
||||
message: t('admin.shippingOrderProfiles.blindTest.softDiagnostic.ocrDatasetsFieldDiff', {
|
||||
sample: sampleName,
|
||||
field: label,
|
||||
ocr: String(field.ocr_value || '').trim() || t('admin.shippingOrderProfiles.blindTest.softDiagnostic.emptyValue'),
|
||||
datasets: String(field.datasets_value || '').trim() || t('admin.shippingOrderProfiles.blindTest.softDiagnostic.emptyValue'),
|
||||
}),
|
||||
};
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 预览复核时列出当前样本 OCR 与 datasets 未对齐项(含两侧截断值)。
|
||||
*/
|
||||
const candidateOcrMismatchLines = computed(() => {
|
||||
const check = candidate.value?.ocr_datasets_cross_check;
|
||||
if (!check || check.status !== 'mismatched') return [];
|
||||
return (check.mismatches || [])
|
||||
.map((item) => {
|
||||
const code = String(item.field_code || '').trim();
|
||||
if (!code) return null;
|
||||
const label = item.scope === 'line' && item.row_index != null
|
||||
? `${code}#${Number(item.row_index) + 1}`
|
||||
: code;
|
||||
return t('admin.shippingOrderProfiles.blindTest.softDiagnostic.ocrDatasetsFieldDiffInline', {
|
||||
field: label,
|
||||
ocr: String(item.ocr_value || '').trim() || t('admin.shippingOrderProfiles.blindTest.softDiagnostic.emptyValue'),
|
||||
datasets: String(item.datasets_value || '').trim() || t('admin.shippingOrderProfiles.blindTest.softDiagnostic.emptyValue'),
|
||||
});
|
||||
})
|
||||
.filter((item): item is string => Boolean(item));
|
||||
});
|
||||
/** 读取订单字段复核状态;候选加载完成时会初始化,默认值仅用于渲染过程中的安全兜底。 */
|
||||
function orderFieldReview(fieldKey: string): { correct: boolean; value: string } {
|
||||
return orderFieldReviews.value[fieldKey] || { correct: true, value: '' };
|
||||
@@ -111,8 +206,21 @@ function orderFieldKey(field: { scope: 'header'; field_code: string }): string {
|
||||
|
||||
/** 将统一业务错误转换为安全的界面提示,不暴露盲测真值或内部布局数据。 */
|
||||
function report(error: unknown): void {
|
||||
const code = error instanceof BusinessError ? error.code : '';
|
||||
message.error(code ? t(`errors.${code}`, code) : t('admin.orderProfileValidation.failed'));
|
||||
if (!(error instanceof BusinessError)) {
|
||||
message.error(t('admin.orderProfileValidation.failed'));
|
||||
return;
|
||||
}
|
||||
// 点号 code 在 i18n 里常被当成嵌套路径;优先扁平 key,再回退原文 code。
|
||||
const flatKey = `errors.${error.code.replace(/\./g, '_')}`;
|
||||
const dottedKey = `errors.${error.code}`;
|
||||
const translated = t(flatKey);
|
||||
const label = translated !== flatKey
|
||||
? translated
|
||||
: (t(dottedKey) !== dottedKey ? t(dottedKey) : error.code);
|
||||
const detail = typeof error.message === 'string' && error.message && error.message !== error.code
|
||||
? error.message
|
||||
: '';
|
||||
message.error(detail ? `${label}(${detail})` : label);
|
||||
}
|
||||
/** 将文件物化失败转成安全提示;版面错误只允许在预览复核阶段出现。 */
|
||||
function sampleFailureMessage(): string {
|
||||
@@ -432,6 +540,16 @@ onBeforeUnmount(() => {
|
||||
<ul><li v-for="failure in failureDetails" :key="failure.code"><span>{{ failure.message }}</span><code>{{ failure.code }}</code></li></ul>
|
||||
</section>
|
||||
|
||||
<section v-if="softDiagnosticDetails.length" class="card soft-diagnostics">
|
||||
<div>
|
||||
<h2>{{ t('admin.shippingOrderProfiles.blindTest.softDiagnostic.title') }}</h2>
|
||||
<p>{{ t('admin.shippingOrderProfiles.blindTest.softDiagnostic.hint') }}</p>
|
||||
</div>
|
||||
<ul>
|
||||
<li v-for="item in softDiagnosticDetails" :key="item.key">{{ item.message }}</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section v-if="suite.status === 'draft'" class="card">
|
||||
<div class="sample-heading"><h2>{{ t('admin.shippingOrderProfiles.blindTest.selectIndependentSample') }}</h2><label class="btn-secondary upload-sample"><input type="file" accept=".pdf,.eml,application/pdf,message/rfc822" :disabled="uploadingSample" @change="uploadIndependentSample"><span>{{ uploadingSample ? t('admin.shippingOrderProfiles.wizard.uploading') : t('admin.shippingOrderProfiles.blindTest.uploadSample') }}</span></label></div>
|
||||
<p v-if="availableSamplesLoaded && !availableSamples.length">{{ t('admin.shippingOrderProfiles.blindTest.noIndependentSamples') }}</p>
|
||||
@@ -450,6 +568,14 @@ onBeforeUnmount(() => {
|
||||
reasons: (candidate.reservation_region_review_reasons || []).join(', ') || candidate.reservation_region_status,
|
||||
}) }}
|
||||
</p>
|
||||
<p v-if="candidateOcrMismatchLines.length" class="ocr-diagnostic">
|
||||
{{ t('admin.shippingOrderProfiles.blindTest.softDiagnostic.previewOcrMismatchIntro', {
|
||||
count: candidateOcrMismatchLines.length,
|
||||
}) }}
|
||||
</p>
|
||||
<ul v-if="candidateOcrMismatchLines.length" class="ocr-diagnostic-list">
|
||||
<li v-for="(line, index) in candidateOcrMismatchLines" :key="`ocr-diff-${index}`">{{ line }}</li>
|
||||
</ul>
|
||||
<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]">
|
||||
@@ -489,6 +615,11 @@ header { align-items: flex-start; margin-bottom: 24px; } h1, h2, h3, p { margin:
|
||||
.review-item { display: grid; gap: 8px; border: 1px solid var(--border-default); border-radius: 8px; padding: 12px; } code { overflow-wrap: anywhere; white-space: pre-wrap; color: var(--text-primary); font-size: 12px; } label { display: flex; gap: 6px; align-items: center; }
|
||||
ul { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; } li { border-top: 1px solid var(--border-default); padding-top: 8px; }
|
||||
.failure-details { border-color: var(--status-error-border); background: var(--status-error-bg); }.failure-details h2 { color: var(--status-error-fg); }.failure-details li { display: grid; gap: 4px; color: var(--status-error-fg); }.failure-details code { color: var(--status-error-fg); }
|
||||
.soft-diagnostics { border-color: var(--status-warning-border, #f59e0b); background: var(--status-warning-bg, #fffbeb); }
|
||||
.soft-diagnostics h2, .soft-diagnostics li, .ocr-diagnostic { color: var(--status-warning-fg) !important; }
|
||||
.ocr-diagnostic { font-weight: 600; grid-column: 1 / -1; }
|
||||
.ocr-diagnostic-list { grid-column: 1 / -1; margin: 0; padding-left: 1.2rem; color: var(--status-warning-fg); }
|
||||
.ocr-diagnostic-list li { margin: 4px 0; }
|
||||
.training-required { color: var(--status-warning-fg) !important; font-weight: 600; }
|
||||
@media (max-width: 700px) { header, .suite-summary, .execution, .sample-heading, .sample-picker { align-items: stretch; flex-direction: column; } .sample-picker .select-field { min-width: 0; width: 100%; } }
|
||||
</style>
|
||||
+364
-119
@@ -6,7 +6,15 @@
|
||||
逻辑:PDF 与 XFA 共用同一 desk DOM(main + aside.config + OrderProfileDocumentCanvas);
|
||||
XFA 仅在属性区插入读取方式/数据源/拆分/样本显示增量;OCR 建议进入普通建议区;
|
||||
未绑定订单字段框通过横幅 + 画布高亮强制展示,避免空白底图漏看导致发布失败;
|
||||
选中已有标注时退出绘制模式,避免 drawing 态吞掉缩放导致标签高度无法调整。
|
||||
选中已有标注时退出绘制模式,避免 drawing 态吞掉缩放导致标签高度无法调整;
|
||||
datasets 字段选型使用弹窗(复用 xfa-rule-dialog),避免窄侧栏内联树;
|
||||
数据源按钮有 path 时展示 selectedPathLabel,否则占位「选择数据源」;
|
||||
datasets 树「+」经 @add-rule → addSplitRuleFromTree 打开拆分弹窗;
|
||||
规则行点击即应用到当前 Schema 字段(@select-rule),铅笔才打开编辑(@edit-rule);
|
||||
删除视觉框/紫标签时同步移除 datasets binding(含级联删掉的绿框),避免重标新 ID 后保存报 formal_binding_visual_missing;
|
||||
识别结果区:OCR 表头保留,datasets header_fields/lines 作正式值增量;保存后刷新 validation runs;
|
||||
整页 order-field OCR 可中止+超时,自动保存前取消,避免占满连接池卡在「保存中」;
|
||||
保存飞行中若又选了 datasets path,applySavedDraft 后 restoreConcurrentEdits,禁止冲掉未入库绑定。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
@@ -162,6 +170,14 @@ const selectedVisualSampleValue = ref<string | null>(null);
|
||||
const selectedVisualSampleState = ref<'idle' | 'loading' | 'ready' | 'failed'>('idle');
|
||||
const visualSampleCache = new Map<string, { text: string | null; source: typeof selectedVisualSampleSource.value }>();
|
||||
const VISUAL_SAMPLE_TIMEOUT_MS = 10000;
|
||||
/** 整页 order-field OCR 预览超时;超时必须中止,否则会占满连接池拖死自动保存。 */
|
||||
const ORDER_FIELD_VALUE_TIMEOUT_MS = 12000;
|
||||
/** 连续标注时整页 OCR 防抖;须长于 autosave(800ms),避免每次画框都并发打满 preview。 */
|
||||
const ORDER_FIELD_VALUE_DEBOUNCE_MS = 1600;
|
||||
/** 自动保存成功后延迟再刷 OCR;编辑中会取消,避免保存后立刻再堵连接。 */
|
||||
const ORDER_FIELD_VALUE_POST_AUTOSAVE_DELAY_MS = 2500;
|
||||
/** region-text 附带的裁剪图 data URL 上限;超限则省略,避免大包体拖垮本地 worker / 阻塞草稿保存。 */
|
||||
const VISUAL_SAMPLE_RENDERED_IMAGE_MAX_CHARS = 1_400_000;
|
||||
/** 当前选区视觉样本的实际证据来源;仅供管理员交叉复核,不能替代 datasets 正式值。 */
|
||||
const selectedVisualSampleSource = ref<'pdf_coordinate' | 'ocr_coordinate' | 'acroform_widget' | 'xfa_rendered_ocr' | null>(null);
|
||||
const previewError = ref("");
|
||||
@@ -200,6 +216,17 @@ const documentCanvas = ref<{
|
||||
captureRegion: (region: OrderProfileRelativeRegion) => string | null;
|
||||
scrollRegionIntoView?: (regionId: string) => void;
|
||||
} | null>(null);
|
||||
/**
|
||||
* 导出画布裁剪图供 region-text 兜底 OCR;超限或 XFA datasets 模式返回 null。
|
||||
* XFA 正式值只认 datasets;视觉回读优先坐标/OCR 证据,避免大图 OCR 占满 worker 拖死保存。
|
||||
* @param region - 相对页宽高的框选区域
|
||||
*/
|
||||
const captureRegionForRegionText = (region: OrderProfileRelativeRegion): string | null => {
|
||||
if (hasValueSourceMapping.value) return null;
|
||||
const captured = documentCanvas.value?.captureRegion(region) || null;
|
||||
if (!captured || captured.length > VISUAL_SAMPLE_RENDERED_IMAGE_MAX_CHARS) return null;
|
||||
return captured;
|
||||
};
|
||||
const previewState = ref<"idle" | "updating" | "ready" | "failed">("idle");
|
||||
const canvasUnavailable = ref(false);
|
||||
const saving = ref(false);
|
||||
@@ -252,6 +279,7 @@ const valueAdapterDesk = reactive(useOrderProfileValueAdapter({
|
||||
onProfileSaved: onXfaProfileSaved,
|
||||
onValidateBlockedChange: (blocked) => { xfaValidateBlocked.value = blocked; },
|
||||
onSaveRequest: () => save(),
|
||||
onRequestAutosave: () => { scheduleAutosave(); },
|
||||
}));
|
||||
/** 共享 Editor 唯一持有 PDF 预览、翻页与渲染所需的 annotation 上下文。 */
|
||||
const deskAnnotationContext = computed(() => ({
|
||||
@@ -277,6 +305,13 @@ function assignXfaSplitDialogPanel(el: unknown): void {
|
||||
valueAdapterDesk.splitRuleDialogPanel = (el as HTMLElement | null) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定 datasets 字段选择弹窗 DOM,供焦点陷阱使用。
|
||||
*/
|
||||
function assignXfaDatasetsPickerPanel(el: unknown): void {
|
||||
valueAdapterDesk.datasetsPickerPanel = (el as HTMLElement | null) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定拆分规则面板实例,供 Header 动作调用。
|
||||
*/
|
||||
@@ -321,14 +356,17 @@ function onDeskCanvasSelect(id: string): void {
|
||||
canvasActions.value.select(id);
|
||||
const region = regions.value.find((item) => item.id === id);
|
||||
if (hasValueSourceMapping.value && region && ['order_field', 'header_field', 'field'].includes(region.kind)) {
|
||||
// 明细字段的共同布局 ID 由行布局 + field_code 稳定生成;不能另造 XFA 专属框。
|
||||
// 明细/表头字段以画布 region.id 为 field_layout_id,避免同 field_code 多框共用一个 binding。
|
||||
const fieldLayoutId = ['header_field', 'field'].includes(region.kind)
|
||||
? `${region.parentId || ''}:${region.fieldCode || ''}`.replace(/^:|:$/g, '')
|
||||
? region.id
|
||||
: (region.orderFieldId || region.id);
|
||||
valueAdapterDesk.selectSharedField(
|
||||
region.fieldCode,
|
||||
fieldLayoutId,
|
||||
['header_field', 'field'].includes(region.kind) ? 'line' : 'header',
|
||||
['header_field', 'field'].includes(region.kind)
|
||||
? `${region.parentId || ''}:${region.fieldCode || ''}`.replace(/^:|:$/g, '') || null
|
||||
: null,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -415,6 +453,8 @@ let previewTimer: number | null = null;
|
||||
/** 预览请求代次;旧的异步响应不得覆盖较新的 Profile 定义或样本选择。 */
|
||||
let previewRequest = 0;
|
||||
let orderFieldValueTimer: number | null = null;
|
||||
let orderFieldValuePostSaveTimer: number | null = null;
|
||||
let orderFieldValueAbortController: AbortController | null = null;
|
||||
let pendingGestureId: string | null = null;
|
||||
let activeGestureId: string | null = null;
|
||||
let activeGestureMoved = false;
|
||||
@@ -736,9 +776,20 @@ const deskAutoSuggestDisabled = computed(() => (
|
||||
const deskPageNo = computed(() => visualCanvas.value.pageNo);
|
||||
const deskPageCount = computed(() => visualCanvas.value.pageCount);
|
||||
const deskSaveDisabled = computed(() => visualCanvas.value.saveDisabled);
|
||||
const deskOrderFieldValues = computed(() => (
|
||||
orderFieldValues.value
|
||||
));
|
||||
const deskOrderFieldValues = computed(() => {
|
||||
const base: Record<string, string | null> = { ...orderFieldValues.value };
|
||||
// XFA:OCR 为空时用当前样本 header_fields 增量补齐画布标签,与右侧识别结果同源。
|
||||
const evidence = hasValueSourceMapping.value
|
||||
? selectCurrentDatasetsValidationEvidence(validationRuns.value, active.value?.structure_fingerprint)
|
||||
: null;
|
||||
for (const field of evidence?.header_fields || []) {
|
||||
const code = String(field.field_code || '').trim();
|
||||
const value = field.normalized_value;
|
||||
if (!code || value == null || value === '') continue;
|
||||
if (!base[code]) base[code] = value;
|
||||
}
|
||||
return base;
|
||||
});
|
||||
const deskOrderFieldValueState = computed(() => (
|
||||
orderFieldValueState.value
|
||||
));
|
||||
@@ -815,12 +866,15 @@ const selectedRegion = computed(
|
||||
watch(selectedRegion, (region) => {
|
||||
if (!hasValueSourceMapping.value || !region || !['order_field', 'header_field', 'field'].includes(region.kind)) return;
|
||||
const fieldLayoutId = ['header_field', 'field'].includes(region.kind)
|
||||
? `${region.parentId || ''}:${region.fieldCode || ''}`.replace(/^:|:$/g, '')
|
||||
? region.id
|
||||
: (region.orderFieldId || region.id);
|
||||
valueAdapterDesk.selectSharedField(
|
||||
region.fieldCode,
|
||||
fieldLayoutId,
|
||||
['header_field', 'field'].includes(region.kind) ? 'line' : 'header',
|
||||
['header_field', 'field'].includes(region.kind)
|
||||
? `${region.parentId || ''}:${region.fieldCode || ''}`.replace(/^:|:$/g, '') || null
|
||||
: null,
|
||||
);
|
||||
}, { immediate: true });
|
||||
/** 当前样本值只能来自本次按画布坐标回读的结果,禁止回退到旧的自动建议缓存。 */
|
||||
@@ -1144,8 +1198,9 @@ const beginFieldBindingEdit = () => {
|
||||
const isLine = ['header_field', 'field'].includes(target.kind);
|
||||
pendingFieldBinding = {
|
||||
fieldCode: target.fieldCode || null,
|
||||
// 明细框身份跟 region.id 走;Schema 改绑时 layout 不变,只迁 field_code。
|
||||
fieldLayoutId: isLine
|
||||
? `${target.parentId || ''}:${target.fieldCode || ''}`.replace(/^:|:$/g, '')
|
||||
? target.id
|
||||
: (target.orderFieldId || target.id),
|
||||
scope: isLine ? 'line' : 'header',
|
||||
};
|
||||
@@ -1169,15 +1224,17 @@ const finishFieldBindingEdit = () => {
|
||||
const target = selectedRegion.value;
|
||||
const previousBinding = pendingFieldBinding;
|
||||
pendingFieldBinding = null;
|
||||
if (target?.kind === 'order_field' && target.fieldCode) {
|
||||
target.label = schemaFieldLabel(target.fieldCode);
|
||||
if (target && ['order_field', 'header_field', 'field'].includes(target.kind) && target.fieldCode) {
|
||||
// 明细框标签原先不会随 Schema 下拉同步,导致画布仍显示旧 field_code。
|
||||
target.label = target.kind === 'order_field'
|
||||
? schemaFieldLabel(target.fieldCode)
|
||||
: target.fieldCode;
|
||||
}
|
||||
finishFormEdit();
|
||||
if (hasValueSourceMapping.value && target && ['order_field', 'header_field', 'field'].includes(target.kind)) {
|
||||
const fieldLayoutId = ['header_field', 'field'].includes(target.kind)
|
||||
? `${target.parentId || ''}:${target.fieldCode || ''}`.replace(/^:|:$/g, '')
|
||||
: (target.orderFieldId || target.id);
|
||||
const scope = ['header_field', 'field'].includes(target.kind) ? 'line' : 'header';
|
||||
const isLine = ['header_field', 'field'].includes(target.kind);
|
||||
const fieldLayoutId = isLine ? target.id : (target.orderFieldId || target.id);
|
||||
const scope = isLine ? 'line' : 'header';
|
||||
if (previousBinding) {
|
||||
valueAdapterDesk.migrateUniqueSharedFieldBinding(
|
||||
previousBinding.fieldCode,
|
||||
@@ -1191,6 +1248,9 @@ const finishFieldBindingEdit = () => {
|
||||
target.fieldCode,
|
||||
fieldLayoutId,
|
||||
scope,
|
||||
isLine
|
||||
? `${target.parentId || ''}:${target.fieldCode || ''}`.replace(/^:|:$/g, '') || null
|
||||
: null,
|
||||
);
|
||||
}
|
||||
};
|
||||
@@ -1332,7 +1392,7 @@ const readDocumentAnchorText = async (region: OrderProfileRelativeRegion): Promi
|
||||
try {
|
||||
const result = await readOrderProfilePreviewPageRegionText(
|
||||
active.value.id, form.documentId, pageNo.value, region, undefined, undefined,
|
||||
documentCanvas.value?.captureRegion(region),
|
||||
captureRegionForRegionText(region),
|
||||
);
|
||||
return result.text.trim() || null;
|
||||
} catch (error) {
|
||||
@@ -1484,24 +1544,45 @@ const duplicateSelected = () => {
|
||||
selectedId.value = copied.id;
|
||||
schedulePreview();
|
||||
};
|
||||
/** 删除当前选中区域并记录在撤销历史中。 */
|
||||
/**
|
||||
* 删除当前选中区域并记录在撤销历史中。
|
||||
* 核心逻辑:删紫标签会级联去掉依赖绿框;XFA 正式 binding 必须按 layout 身份一并清掉,
|
||||
* 否则重标得到新 order_field_* ID 后,旧 field_layout_id 仍占 path,保存报缺框。
|
||||
*/
|
||||
const removeSelected = () => {
|
||||
if (!selectedRegion.value) return;
|
||||
checkpoint();
|
||||
const removedId = selectedRegion.value.id;
|
||||
const removedKind = selectedRegion.value.kind;
|
||||
const removedLayoutId = selectedRegion.value.orderFieldId || selectedRegion.value.id;
|
||||
const documentAnchorId = ['document_anchor_label', 'document_anchor_value'].includes(selectedRegion.value.kind)
|
||||
? selectedRegion.value.parentId
|
||||
: null;
|
||||
// Removing a shared label removes dependent value boxes; removing one value box
|
||||
// preserves the label and any sibling customer/address field.
|
||||
const beforeIds = new Set(regions.value.map((item) => item.id));
|
||||
regions.value = filterRegionsAfterRemoval(regions.value, removedId, documentAnchorId || null);
|
||||
const removedLayoutIds = [...beforeIds]
|
||||
.filter((id) => !regions.value.some((item) => item.id === id))
|
||||
.flatMap((id) => {
|
||||
// 已删除区域的 layout 身份:order_field 优先 orderFieldId,明细框用 region.id。
|
||||
if (id === removedId) return [removedLayoutId, id];
|
||||
return [id];
|
||||
});
|
||||
// order_anchor 不在旧白名单内时,绿框已删但 binding 残留 → formal_binding_visual_missing。
|
||||
if (hasValueSourceMapping.value && ['order_field', 'order_anchor', 'header_field', 'field'].includes(removedKind)) {
|
||||
valueAdapterDesk.removeBindingsForVisualLayouts(removedLayoutIds);
|
||||
}
|
||||
if (documentAnchorId) {
|
||||
documentMatch.requiredAnchors = documentMatch.requiredAnchors.filter((item) => item.anchor_id !== documentAnchorId);
|
||||
documentMatch.optionalAnchors = documentMatch.optionalAnchors.filter((item) => item.anchor_id !== documentAnchorId);
|
||||
documentMatchDirty.value = true;
|
||||
}
|
||||
selectedId.value = null;
|
||||
markLocalChange();
|
||||
scheduleAutosave();
|
||||
schedulePreview();
|
||||
scheduleOrderFieldSuggestionValues();
|
||||
};
|
||||
/** 标记一次画布手势,只有实际产生几何变化时才创建撤销检查点。 */
|
||||
const beginRegionGesture = (id: string) => {
|
||||
@@ -1619,6 +1700,8 @@ const definition = () => {
|
||||
field_code: item.fieldCode!,
|
||||
scope: "line" as const,
|
||||
region: item.region,
|
||||
// 持久化画布框 ID,供 XFA binding.field_layout_id 精确引用。
|
||||
region_id: item.id,
|
||||
extractor_key: "direct",
|
||||
allowed_sources: ["pdf_coordinate"],
|
||||
minimum_evidence_level: "coordinate",
|
||||
@@ -1854,97 +1937,153 @@ const definition = () => {
|
||||
/**
|
||||
* 保存当前草稿或执行 800ms 自动保存。
|
||||
* 核心逻辑:自动保存复用同一租约与乐观锁契约;失败只保留本地状态并有限次重试,绝不重载画布。
|
||||
* 保存前中止 region-text 与整页 order-field OCR(真正 abort HTTP),草稿写入成功后立即释放 saving;
|
||||
* 自动保存后延迟再刷 OCR,避免连接池被 OCR 占满导致「保存中」卡住。
|
||||
* @param automatic - 为 true 时不弹成功提示,连续编辑会合并为一次 Revision。
|
||||
* @returns 保存完成后的最新草稿状态。
|
||||
* @returns 保存是否成功。
|
||||
*/
|
||||
const save = async (automatic = false) => {
|
||||
const adapter = draftSaveAdapter.value;
|
||||
if (saving.value || !adapter.canSave) return false;
|
||||
if (!automatic && adapter.skipUnchangedManualSave && !adapter.hasUnsavedChanges) return true;
|
||||
// 保存进行中又选了数据源时,不能丢请求:重新排队,等当前 PUT 结束后再写 path。
|
||||
if (saving.value) {
|
||||
if (automatic) scheduleAutosave();
|
||||
return false;
|
||||
}
|
||||
if (!adapter.canSave) return false;
|
||||
if (!automatic && adapter.skipUnchangedManualSave && !adapter.hasUnsavedChanges) {
|
||||
message.info(t('admin.shippingOrderProfiles.workbench.noUnsavedChanges'));
|
||||
return true;
|
||||
}
|
||||
// [STEP 1] 让出后端与浏览器连接池:取消进行中的视觉回读 / 整页 OCR,避免草稿 PUT 被卡住。
|
||||
selectedVisualSampleAbortController?.abort();
|
||||
selectedVisualSampleAbortController = null;
|
||||
orderFieldValueAbortController?.abort();
|
||||
orderFieldValueAbortController = null;
|
||||
if (orderFieldValueTimer) {
|
||||
window.clearTimeout(orderFieldValueTimer);
|
||||
orderFieldValueTimer = null;
|
||||
}
|
||||
if (orderFieldValuePostSaveTimer) {
|
||||
window.clearTimeout(orderFieldValuePostSaveTimer);
|
||||
orderFieldValuePostSaveTimer = null;
|
||||
}
|
||||
++selectedVisualSampleRequest;
|
||||
++orderFieldValueRequest;
|
||||
++previewRequest;
|
||||
saving.value = true;
|
||||
saveState.value = 'saving';
|
||||
const savingChangeVersion = localChangeVersion;
|
||||
const xfaEpochAtStart = hasValueSourceMapping.value ? valueAdapterDesk.editEpoch : 0;
|
||||
let saveSucceeded = false;
|
||||
let shouldRescheduleAutosave = false;
|
||||
try {
|
||||
const existingProfile = active.value;
|
||||
const adapterPayload = adapter.buildPayload(definition());
|
||||
if (!adapterPayload) {
|
||||
saveState.value = 'failed';
|
||||
return false;
|
||||
} else {
|
||||
const payload = {
|
||||
profile_code: form.profileCode.toUpperCase(),
|
||||
display_name: form.displayName,
|
||||
schema_version_id: form.schemaId,
|
||||
definition: adapterPayload.definition,
|
||||
sample_document_id: form.documentId,
|
||||
// sample_table_id 与 definition.main_table_id 是同一份冻结身份;当前页预览表不能参与保存。
|
||||
sample_table_id: resolveMainTableIdForPageChange({
|
||||
frozenMainTableId: mainTableId.value,
|
||||
pagePreviewTableId: form.tableId,
|
||||
}),
|
||||
change_note: form.changeNote,
|
||||
};
|
||||
if (!existingProfile) throw new Error('A draft must be created by the wizard before editing.');
|
||||
const savedProfile = await saveOrderDocumentProfileDraft(existingProfile.id, {
|
||||
...payload,
|
||||
expected_lock_version: existingProfile.lock_version,
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value || '',
|
||||
operation_id: createRandomUuid(),
|
||||
...(adapterPayload.splitRuleConfirmationTokens
|
||||
? { split_rule_confirmation_tokens: adapterPayload.splitRuleConfirmationTokens }
|
||||
: {}),
|
||||
...(adapterPayload.allowFormalBindingDeletions?.length
|
||||
? { allow_formal_binding_deletions: adapterPayload.allowFormalBindingDeletions }
|
||||
: {}),
|
||||
});
|
||||
active.value = savedProfile;
|
||||
// [STEP] PUT 成功即解锁「保存中」;applySavedDraft 不得继续占住保存态。
|
||||
// 若保存飞行中用户又选了数据源,先抓本地快照,避免随后被服务端旧草稿冲掉。
|
||||
const concurrentXfaEdit = hasValueSourceMapping.value
|
||||
&& valueAdapterDesk.editEpoch !== xfaEpochAtStart
|
||||
? valueAdapterDesk.captureConcurrentEditState()
|
||||
: null;
|
||||
saving.value = false;
|
||||
saveState.value = 'saved';
|
||||
autosaveFailures = 0;
|
||||
const applied = await adapter.applySavedDraft(savedProfile);
|
||||
if (!applied) {
|
||||
saveState.value = 'failed';
|
||||
} else {
|
||||
if (concurrentXfaEdit) {
|
||||
// 飞行中改的 path/bindings/拆分写回本地,保持 dirty,立刻再排一次 autosave。
|
||||
valueAdapterDesk.restoreConcurrentEdits(concurrentXfaEdit);
|
||||
shouldRescheduleAutosave = true;
|
||||
}
|
||||
if (localChangeVersion === savingChangeVersion) {
|
||||
history.value = [];
|
||||
future.value = [];
|
||||
documentMatchDirty.value = false;
|
||||
reservationIdRegionDirty.value = false;
|
||||
}
|
||||
if (!automatic) message.success(t("admin.shippingOrderProfiles.updated"));
|
||||
profiles.value = profiles.value.map((item) => item.id === savedProfile.id ? savedProfile : item);
|
||||
saveSucceeded = true;
|
||||
shouldRescheduleAutosave = shouldRescheduleAutosave
|
||||
|| localChangeVersion !== savingChangeVersion;
|
||||
}
|
||||
}
|
||||
const payload = {
|
||||
profile_code: form.profileCode.toUpperCase(),
|
||||
display_name: form.displayName,
|
||||
schema_version_id: form.schemaId,
|
||||
definition: adapterPayload.definition,
|
||||
sample_document_id: form.documentId,
|
||||
// sample_table_id 与 definition.main_table_id 是同一份冻结身份;当前页预览表不能参与保存。
|
||||
sample_table_id: resolveMainTableIdForPageChange({
|
||||
frozenMainTableId: mainTableId.value,
|
||||
pagePreviewTableId: form.tableId,
|
||||
}),
|
||||
change_note: form.changeNote,
|
||||
};
|
||||
if (!existingProfile) throw new Error('A draft must be created by the wizard before editing.');
|
||||
const savedProfile = await saveOrderDocumentProfileDraft(existingProfile.id, {
|
||||
...payload,
|
||||
expected_lock_version: existingProfile.lock_version,
|
||||
browser_session_id: editorSessionId,
|
||||
lease_token: editLeaseToken.value || '',
|
||||
operation_id: createRandomUuid(),
|
||||
...(adapterPayload.splitRuleConfirmationTokens
|
||||
? { split_rule_confirmation_tokens: adapterPayload.splitRuleConfirmationTokens }
|
||||
: {}),
|
||||
...(adapterPayload.allowFormalBindingDeletions?.length
|
||||
? { allow_formal_binding_deletions: adapterPayload.allowFormalBindingDeletions }
|
||||
: {}),
|
||||
});
|
||||
active.value = savedProfile;
|
||||
const applied = await adapter.applySavedDraft(savedProfile);
|
||||
if (!applied) {
|
||||
saveState.value = 'failed';
|
||||
return false;
|
||||
}
|
||||
if (localChangeVersion === savingChangeVersion) {
|
||||
history.value = [];
|
||||
future.value = [];
|
||||
documentMatchDirty.value = false;
|
||||
reservationIdRegionDirty.value = false;
|
||||
}
|
||||
saveState.value = 'saved';
|
||||
autosaveFailures = 0;
|
||||
if (!automatic) message.success(t("admin.shippingOrderProfiles.updated"));
|
||||
profiles.value = profiles.value.map((item) => item.id === savedProfile.id ? savedProfile : item);
|
||||
// 保存主表后后端会冻结当前 Layout 身份;立即同步门禁,避免管理员必须重开编辑页。
|
||||
await refreshAutomarkSampleReadiness();
|
||||
await refreshOrderFieldSuggestionValues();
|
||||
if (localChangeVersion !== savingChangeVersion) scheduleAutosave();
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && ['SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_REQUIRED', 'SHIPPING.ORDER_DOCUMENT_PROFILE_LEASE_CONFLICT'].includes(error.code)) {
|
||||
saveState.value = 'readonly';
|
||||
return false;
|
||||
}
|
||||
saveState.value = 'failed';
|
||||
autosaveFailures += 1;
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID' && error.details.field_path) {
|
||||
message.error(t('admin.shippingOrderProfiles.workbench.invalidDefinitionPath', { path: error.details.field_path }));
|
||||
} else {
|
||||
fail(error);
|
||||
saveState.value = 'failed';
|
||||
autosaveFailures += 1;
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID' && error.details.field_path) {
|
||||
message.error(t('admin.shippingOrderProfiles.workbench.invalidDefinitionPath', { path: error.details.field_path }));
|
||||
} else {
|
||||
fail(error);
|
||||
}
|
||||
// A definition validation error cannot recover without an administrator edit.
|
||||
// Retrying it only produces repeated toast notifications for the same canvas state.
|
||||
const retryable = !(error instanceof BusinessError && [
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
].includes(error.code));
|
||||
if (automatic && retryable && autosaveFailures < 3 && navigator.onLine) {
|
||||
if (retryTimer) window.clearTimeout(retryTimer);
|
||||
retryTimer = window.setTimeout(() => void save(true), 1500 * autosaveFailures);
|
||||
}
|
||||
}
|
||||
// A definition validation error cannot recover without an administrator edit.
|
||||
// Retrying it only produces repeated toast notifications for the same canvas state.
|
||||
const retryable = !(error instanceof BusinessError && [
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID',
|
||||
'SHIPPING.ORDER_DOCUMENT_PROFILE_FIELD_INVALID',
|
||||
].includes(error.code));
|
||||
if (automatic && retryable && autosaveFailures < 3 && navigator.onLine) {
|
||||
if (retryTimer) window.clearTimeout(retryTimer);
|
||||
retryTimer = window.setTimeout(() => void save(true), 1500 * autosaveFailures);
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
// [STEP 2] 草稿已落库并解锁按钮后再刷门禁/预览;失败不影响已保存状态。
|
||||
if (saveSucceeded) {
|
||||
void refreshAutomarkSampleReadiness();
|
||||
// 自动保存后绝不立刻打整页 OCR:标注连点时会把连接池堵死,UI 一直停在「保存中」。
|
||||
if (automatic) {
|
||||
scheduleDeferredOrderFieldSuggestionValues();
|
||||
} else {
|
||||
void refreshOrderFieldSuggestionValues();
|
||||
}
|
||||
// XFA 正式明细/表头预览绑定 definition checksum;保存后刷新 Run 列表,避免仍指向旧证据。
|
||||
if (hasValueSourceMapping.value && active.value?.id) {
|
||||
void listOrderProfileValidationRuns(active.value.id)
|
||||
.then((runs) => { validationRuns.value = runs; })
|
||||
.catch(() => { /* 列表失败不阻断已保存草稿 */ });
|
||||
}
|
||||
if (shouldRescheduleAutosave) scheduleAutosave();
|
||||
}
|
||||
return saveSucceeded;
|
||||
};
|
||||
/** 创建只含主行区域的最小草稿并自动绑定样本,之后才允许打开受控页面画布标注。 */
|
||||
/** 以启用的 Schema 字段规则和冻结坐标生成待复核标记,绝不自动发布模板。 */
|
||||
@@ -2284,35 +2423,105 @@ const clearOrderFieldValuePreview = (state: 'idle' | 'loading' | 'failed') => {
|
||||
orderFieldValueError.value = '';
|
||||
};
|
||||
/**
|
||||
* 根据当前共同画布定义读取订单字段;过期请求不得覆盖更新后的值框结果。
|
||||
* 根据当前共同画布定义读取订单字段;过期/已中止请求不得覆盖更新后的值框结果。
|
||||
* 核心逻辑:XFA 也必须先复用这份 PDFium/OCR 视觉证据;datasets 只在右侧增量显示正式值。
|
||||
* 本地已存在重复 Schema 绑定时跳过请求,避免进入编辑页即打满 400 / 拖垮续租。
|
||||
* 必须支持 AbortSignal:整页 OCR 可达数十秒,不中止会占满连接池拖死自动保存 PUT。
|
||||
*/
|
||||
const refreshOrderFieldSuggestionValues = async () => {
|
||||
orderFieldValueAbortController?.abort();
|
||||
orderFieldValueAbortController = null;
|
||||
const request = ++orderFieldValueRequest;
|
||||
if (!form.documentId || !form.schemaId || !pageRegions.value.some((item) => item.kind === "order_field")) {
|
||||
clearOrderFieldValuePreview('idle');
|
||||
return;
|
||||
}
|
||||
const orderFieldCodes = regions.value
|
||||
.filter((item) => item.kind === 'order_field' && item.fieldCode)
|
||||
.map((item) => item.fieldCode!);
|
||||
const duplicateCodes = [...new Set(orderFieldCodes.filter((code, index) => orderFieldCodes.indexOf(code) !== index))];
|
||||
if (duplicateCodes.length) {
|
||||
clearOrderFieldValuePreview('failed');
|
||||
orderFieldValueError.value = t('admin.shippingOrderProfiles.workbench.orderFieldDuplicatePreview', {
|
||||
fields: duplicateCodes.join(', '),
|
||||
});
|
||||
return;
|
||||
}
|
||||
clearOrderFieldValuePreview('loading');
|
||||
const abortController = new AbortController();
|
||||
orderFieldValueAbortController = abortController;
|
||||
let timeoutId: number | null = null;
|
||||
try {
|
||||
const result = await previewOrderProfileOrderFieldValues(
|
||||
form.documentId,
|
||||
form.schemaId,
|
||||
pageNo.value,
|
||||
definition(),
|
||||
);
|
||||
const result = await Promise.race([
|
||||
previewOrderProfileOrderFieldValues(
|
||||
form.documentId,
|
||||
form.schemaId,
|
||||
pageNo.value,
|
||||
definition(),
|
||||
undefined,
|
||||
abortController.signal,
|
||||
),
|
||||
new Promise<never>((_, reject) => {
|
||||
timeoutId = window.setTimeout(() => {
|
||||
abortController.abort();
|
||||
reject(new DOMException('order_field_value_timeout', 'AbortError'));
|
||||
}, ORDER_FIELD_VALUE_TIMEOUT_MS);
|
||||
}),
|
||||
]);
|
||||
if (request !== orderFieldValueRequest) return;
|
||||
orderFieldValuePreviews.value = result.fields;
|
||||
orderFieldValueState.value = 'ready';
|
||||
} catch (error) {
|
||||
if (error instanceof DOMException && error.name === 'AbortError') {
|
||||
// 被保存/重调度/超时中止时勿卡在「读取中」,否则标注间隙 UI 一直像在读。
|
||||
if (request === orderFieldValueRequest && orderFieldValueState.value === 'loading') {
|
||||
orderFieldValueState.value = 'idle';
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (request === orderFieldValueRequest) {
|
||||
clearOrderFieldValuePreview('failed');
|
||||
orderFieldValueError.value = error instanceof BusinessError
|
||||
? error.message
|
||||
: t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed');
|
||||
}
|
||||
} finally {
|
||||
if (timeoutId !== null) window.clearTimeout(timeoutId);
|
||||
if (orderFieldValueAbortController === abortController) {
|
||||
orderFieldValueAbortController = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
/**
|
||||
* 订单字段框或读取方式变化后延迟回读整页字符证据。
|
||||
* 核心逻辑:先中止旧 HTTP(不仅是丢弃结果),并拉长防抖,避免连点标注时并发打满 OCR。
|
||||
*/
|
||||
const scheduleOrderFieldSuggestionValues = () => {
|
||||
if (orderFieldValueTimer) window.clearTimeout(orderFieldValueTimer);
|
||||
if (orderFieldValuePostSaveTimer) {
|
||||
window.clearTimeout(orderFieldValuePostSaveTimer);
|
||||
orderFieldValuePostSaveTimer = null;
|
||||
}
|
||||
// [STEP] 几何刚变化:中止进行中的整页 OCR,腾出连接给即将到来的自动保存。
|
||||
// 防抖期间保留旧预览,真正发请求时再切 loading,避免连点标注一直「读取中」。
|
||||
orderFieldValueAbortController?.abort();
|
||||
orderFieldValueAbortController = null;
|
||||
++orderFieldValueRequest;
|
||||
orderFieldValueTimer = window.setTimeout(() => {
|
||||
void refreshOrderFieldSuggestionValues();
|
||||
}, ORDER_FIELD_VALUE_DEBOUNCE_MS);
|
||||
};
|
||||
/**
|
||||
* 自动保存成功后延迟刷新整页 OCR;若期间又有标注则取消,优先保证保存通道畅通。
|
||||
*/
|
||||
const scheduleDeferredOrderFieldSuggestionValues = () => {
|
||||
if (orderFieldValuePostSaveTimer) window.clearTimeout(orderFieldValuePostSaveTimer);
|
||||
orderFieldValuePostSaveTimer = window.setTimeout(() => {
|
||||
orderFieldValuePostSaveTimer = null;
|
||||
if (saving.value || dirty.value) return;
|
||||
void refreshOrderFieldSuggestionValues();
|
||||
}, ORDER_FIELD_VALUE_POST_AUTOSAVE_DELAY_MS);
|
||||
};
|
||||
/**
|
||||
* 读取当前选中非单头框的视觉样本值。
|
||||
*
|
||||
@@ -2354,7 +2563,7 @@ const refreshSelectedVisualSampleValue = async () => {
|
||||
active.value.id, form.documentId, region.pageNo, region.region,
|
||||
abortController.signal,
|
||||
undefined,
|
||||
documentCanvas.value?.captureRegion(region.region),
|
||||
captureRegionForRegionText(region.region),
|
||||
),
|
||||
new Promise<never>((_, reject) => {
|
||||
timeoutId = window.setTimeout(() => {
|
||||
@@ -2395,16 +2604,6 @@ watch(
|
||||
() => { void refreshSelectedVisualSampleValue(); },
|
||||
{ immediate: true },
|
||||
);
|
||||
/** 订单字段框或读取方式变化后延迟回读整页字符证据,避免地址字段停留在旧的空候选。 */
|
||||
const scheduleOrderFieldSuggestionValues = () => {
|
||||
if (orderFieldValueTimer) window.clearTimeout(orderFieldValueTimer);
|
||||
// 几何刚变化即进入读取中,任何旧结果均不再可见。
|
||||
++orderFieldValueRequest;
|
||||
clearOrderFieldValuePreview('loading');
|
||||
orderFieldValueTimer = window.setTimeout(() => {
|
||||
void refreshOrderFieldSuggestionValues();
|
||||
}, 400);
|
||||
};
|
||||
/** 在后台刷新区域预览,保留原有坐标/OCR 准备行为;结果不再占用标注画布下方空间。 */
|
||||
const schedulePreview = () => {
|
||||
if (previewTimer) window.clearTimeout(previewTimer);
|
||||
@@ -2767,7 +2966,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
return [
|
||||
...table.header_layouts.flatMap((header) =>
|
||||
header.field_regions.map((item, index) => ({
|
||||
id: `${header.layout_id}-field-${index}`,
|
||||
id: item.region_id || `${header.layout_id}-field-${index}`,
|
||||
kind: "header_field" as const,
|
||||
label: item.field_code,
|
||||
// Keep the binding as well as its visible label. Without fieldCode, a
|
||||
@@ -2788,7 +2987,7 @@ const restoreRegions = (profile: ShippingOrderDocumentProfile) => {
|
||||
})),
|
||||
...table.line_layouts.flatMap((line) =>
|
||||
line.field_regions.map((item, index) => ({
|
||||
id: `${line.layout_id}-field-${index}`,
|
||||
id: item.region_id || `${line.layout_id}-field-${index}`,
|
||||
kind: "field" as const,
|
||||
label: item.field_code,
|
||||
region: item.region,
|
||||
@@ -3180,9 +3379,14 @@ onMounted(async () => {
|
||||
onBeforeUnmount(() => {
|
||||
++previewRequest;
|
||||
++selectedVisualSampleRequest;
|
||||
++orderFieldValueRequest;
|
||||
selectedVisualSampleAbortController?.abort();
|
||||
selectedVisualSampleAbortController = null;
|
||||
orderFieldValueAbortController?.abort();
|
||||
orderFieldValueAbortController = null;
|
||||
if (previewTimer) window.clearTimeout(previewTimer);
|
||||
if (orderFieldValueTimer) window.clearTimeout(orderFieldValueTimer);
|
||||
if (orderFieldValuePostSaveTimer) window.clearTimeout(orderFieldValuePostSaveTimer);
|
||||
if (autosaveTimer) window.clearTimeout(autosaveTimer);
|
||||
if (retryTimer) window.clearTimeout(retryTimer);
|
||||
stopLeaseRenewal();
|
||||
@@ -3630,21 +3834,12 @@ onBeforeUnmount(() => {
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
:disabled="xfaConfigReadonly || valueAdapterDesk.loading || !valueAdapterDesk.tree"
|
||||
@click="valueAdapterDesk.datasetsPickerOpen = !valueAdapterDesk.datasetsPickerOpen"
|
||||
:title="valueAdapterDesk.selectedPathLabel || t('admin.shippingOrderProfiles.xfaDesk.pickDatasetsPath')"
|
||||
@click="valueAdapterDesk.openDatasetsPicker()"
|
||||
>
|
||||
{{ valueAdapterDesk.selectedPathLabel || t('admin.shippingOrderProfiles.xfaDesk.pickDatasetsPath') }}
|
||||
</button>
|
||||
</label>
|
||||
<div v-if="valueAdapterDesk.datasetsPickerOpen" class="xfa-datasets-popover xfa-incremental-popover">
|
||||
<XfaDatasetTree
|
||||
:tree="valueAdapterDesk.tree"
|
||||
:selected-path-id="valueAdapterDesk.selectedPathId"
|
||||
:selected-rule-id="valueAdapterDesk.selectedRuleId"
|
||||
:mapped-path-ids="valueAdapterDesk.mappedPathIds"
|
||||
:split-rule-sets="valueAdapterDesk.splitRuleSets"
|
||||
@select-path="(pathId, isLeaf) => valueAdapterDesk.updateSelectedDatasetsPath(pathId, isLeaf)"
|
||||
/>
|
||||
</div>
|
||||
<section class="sample-value-card">
|
||||
<span>{{ t('admin.shippingOrderProfiles.xfaDesk.datasetsSampleValue') }}</span>
|
||||
<strong :class="{ empty: !valueAdapterDesk.selectedSampleValue }">
|
||||
@@ -3670,6 +3865,7 @@ onBeforeUnmount(() => {
|
||||
{{ t('admin.shippingOrderProfiles.xfaSplit.editRules') }}
|
||||
</button>
|
||||
</label>
|
||||
<p class="xfa-header-inheritance-hint">{{ t('admin.shippingOrderProfiles.xfaSplit.splitVisualReuseHint') }}</p>
|
||||
<section class="xfa-datasource-summary">
|
||||
<strong>{{ t('admin.shippingOrderProfiles.xfaDesk.datasourceSummary') }}</strong>
|
||||
<p>{{ t('admin.shippingOrderProfiles.xfaWorkbench.collectionMeta', {
|
||||
@@ -3709,7 +3905,7 @@ onBeforeUnmount(() => {
|
||||
@click="selectDeskRecognitionRegion(item.id)"
|
||||
>
|
||||
<span :title="schemaFieldLabel(item.fieldCode)">{{ schemaFieldLabel(item.fieldCode) }}</span>
|
||||
<strong :class="{ empty: !item.value }" :title="item.value || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')">{{ item.value || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable') }}</strong>
|
||||
<strong :class="{ empty: !item.value }" :title="item.value || (item.status === 'loading' ? t('admin.shippingOrderProfiles.workbench.orderFieldValueReading') : t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable'))">{{ item.value || (item.status === 'loading' ? t('admin.shippingOrderProfiles.workbench.orderFieldValueReading') : t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')) }}</strong>
|
||||
<small :class="`evidence-status--${item.status}`">{{ t(`admin.shippingOrderProfiles.workbench.evidenceStatus.${item.status}`) }}</small>
|
||||
</button>
|
||||
<p v-if="!deskHeaderRecognitionResults.length" class="recognition-empty">{{ t('admin.shippingOrderProfiles.workbench.noRecognitionResults') }}</p>
|
||||
@@ -3742,6 +3938,40 @@ onBeforeUnmount(() => {
|
||||
</section>
|
||||
</aside>
|
||||
|
||||
<div
|
||||
v-if="hasValueSourceMapping && valueAdapterDesk.datasetsPickerOpen"
|
||||
class="xfa-rule-dialog"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaDesk.pickDatasetsPathTitle')"
|
||||
@keydown.esc.stop.prevent="valueAdapterDesk.closeDatasetsPicker()"
|
||||
>
|
||||
<div class="xfa-rule-dialog__backdrop" @click="valueAdapterDesk.closeDatasetsPicker()" />
|
||||
<section :ref="assignXfaDatasetsPickerPanel" class="xfa-rule-dialog__panel xfa-datasets-picker-panel">
|
||||
<header class="xfa-rule-dialog__header">
|
||||
<div>
|
||||
<strong>{{ t('admin.shippingOrderProfiles.xfaDesk.pickDatasetsPathTitle') }}</strong>
|
||||
<p>{{ t('admin.shippingOrderProfiles.xfaDesk.pickDatasetsPathHint') }}</p>
|
||||
</div>
|
||||
<button type="button" class="xfa-rule-dialog__close" :aria-label="t('common.close')" @click="valueAdapterDesk.closeDatasetsPicker()">×</button>
|
||||
</header>
|
||||
<div class="xfa-datasets-picker-body">
|
||||
<XfaDatasetTree
|
||||
expand-samples
|
||||
:tree="valueAdapterDesk.tree"
|
||||
:selected-path-id="valueAdapterDesk.selectedPathId"
|
||||
:selected-rule-id="valueAdapterDesk.selectedRuleId"
|
||||
:mapped-path-ids="valueAdapterDesk.mappedPathIds"
|
||||
:split-rule-sets="valueAdapterDesk.splitRuleSets"
|
||||
@select-path="(pathId, isLeaf) => valueAdapterDesk.updateSelectedDatasetsPath(pathId, isLeaf)"
|
||||
@add-rule="valueAdapterDesk.addSplitRuleFromTree"
|
||||
@edit-rule="valueAdapterDesk.editSplitRuleFromTree"
|
||||
@select-rule="valueAdapterDesk.selectSplitRuleFromTree"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="hasValueSourceMapping && valueAdapterDesk.splitRuleDialogOpen"
|
||||
class="xfa-rule-dialog"
|
||||
@@ -3929,6 +4159,21 @@ onBeforeUnmount(() => {
|
||||
background: #fff;
|
||||
padding: 8px;
|
||||
}
|
||||
.xfa-datasets-picker-panel {
|
||||
width: min(920px, 96vw);
|
||||
max-height: min(860px, 92vh);
|
||||
}
|
||||
.xfa-datasets-picker-body {
|
||||
display: flex;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
padding: 12px 16px 16px;
|
||||
}
|
||||
.xfa-datasets-picker-body :deep(.xfa-tree) {
|
||||
min-height: 420px;
|
||||
}
|
||||
.binding-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -4277,7 +4522,7 @@ onBeforeUnmount(() => {
|
||||
padding: 0.65rem;
|
||||
}
|
||||
.sample-value-card span { color: #0369a1; font-size: 0.72rem; font-weight: 700; }
|
||||
.sample-value-card strong { color: #0c4a6e; font: 700 0.82rem/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; }
|
||||
.sample-value-card strong { color: #0c4a6e; font: 700 0.82rem/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; white-space: pre-wrap; }
|
||||
.sample-value-card strong.empty { color: #64748b; font-family: inherit; font-weight: 500; }
|
||||
.sample-value-card__source { color: #64748b; font-size: 0.72rem; }
|
||||
.xfa-header-inheritance-hint { margin: 0; color: #9a3412; font-size: .76rem; line-height: 1.45; }
|
||||
|
||||
+17
-1
@@ -2,7 +2,8 @@
|
||||
features/admin/modules/shipping-order-document-profiles/OrderProfilePublishCheckPage.vue
|
||||
用途:展示版面签名、跨模板唯一性与发布阻断项,并在门禁通过后发布模板。
|
||||
依赖:发布检查 API、验证运行 API、Vue Router 和统一消息提示。
|
||||
逻辑:自动选择当前样本试读通过运行;服务端生成签名/重叠验证;阻断项不可绕过,语义差异须逐项确认。
|
||||
逻辑:自动选择当前样本试读通过运行;服务端生成签名/重叠验证;阻断项不可绕过,语义差异须逐项确认;
|
||||
XFA path 覆盖不全时展示 missing_fields 的 scope.field_code,避免同名 header/line 误判。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
@@ -158,6 +159,21 @@ async function publish(): Promise<void> {
|
||||
/** 归一化有限的已知门禁码;未知内容仍保留后端安全摘要。 */
|
||||
function itemMessage(item: Record<string, unknown>): string {
|
||||
const key = String(item.key || '');
|
||||
if (key === 'xfa_required_path_coverage_incomplete') {
|
||||
const missing = Array.isArray(item.missing_fields) ? item.missing_fields : [];
|
||||
const labels = missing
|
||||
.map((entry) => {
|
||||
if (!entry || typeof entry !== 'object') return '';
|
||||
const scope = String((entry as { scope?: string }).scope || '').trim();
|
||||
const code = String((entry as { field_code?: string }).field_code || '').trim();
|
||||
if (!code) return '';
|
||||
return scope ? `${scope}.${code}` : code;
|
||||
})
|
||||
.filter(Boolean);
|
||||
return t('admin.orderProfilePublishCheck.xfaRequiredPathCoverageIncomplete', {
|
||||
fields: labels.join(', ') || t('admin.orderProfilePublishCheck.xfaRequiredPathFieldsUnknown'),
|
||||
});
|
||||
}
|
||||
const map: Record<string, string> = {
|
||||
current_validation_required: t('admin.orderProfilePublishCheck.currentValidationRequired'),
|
||||
semantic_diff_review: t('admin.orderProfilePublishCheck.semanticDiffReview'),
|
||||
|
||||
+12
-8
@@ -8,7 +8,8 @@
|
||||
选中框用 top/right/bottom/left 定位(避免 height% 在内容撑高容器上失效);
|
||||
拖拽/缩放进行中忽略滚轮缩放,避免触控板纵向手势把高度调整抢走;
|
||||
绘制模式下仍允许操作当前选中框;整边 resize 热区便于矮标签拉高;
|
||||
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态。
|
||||
画布区域 aria-label 走四语言 i18n;可选 emptyHint/loadError 区分 XFA page_unavailable 与 PDF 缺样本空态;
|
||||
订单字段标签在已有正式/OCR 值时优先展示,loading 仅在尚无值时显示「读取中」。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
@@ -352,7 +353,7 @@ const endCreation = () => {
|
||||
};
|
||||
|
||||
const selected = computed(() => new Set([props.selectedRegionId]));
|
||||
/** 在画布徽标展示字段身份和实际识别值;编辑态订单字段继续使用工作台即时读取状态。 */
|
||||
/** 在画布徽标展示字段身份和实际识别值;已有值优先于 loading 状态文案。 */
|
||||
const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
|
||||
if (readonlyMode.value && !['line', 'exclusion'].includes(region.kind)) {
|
||||
return `${region.label} · ${region.recognizedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable')}`;
|
||||
@@ -369,12 +370,15 @@ const displayRegionLabel = (region: OrderProfileCanvasRegion): string => {
|
||||
}
|
||||
const state = props.orderFieldValueState || 'idle';
|
||||
const value = region.fieldCode ? props.orderFieldValues?.[region.fieldCode] : null;
|
||||
const suffix = state === 'loading'
|
||||
? t('admin.shippingOrderProfiles.workbench.orderFieldValueReading')
|
||||
: state === 'failed'
|
||||
? t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed')
|
||||
// 新圈选的 XFA 值框先显示同次受控视觉回读;整页 PDFium/OCR 预览完成后再覆盖。
|
||||
: value || region.suggestedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable');
|
||||
// 已有正式/OCR 值时优先展示;loading 仅在尚无值时显示「读取中」,避免与「未读取到值」叠字。
|
||||
const suffix = value
|
||||
? value
|
||||
: state === 'loading'
|
||||
? t('admin.shippingOrderProfiles.workbench.orderFieldValueReading')
|
||||
: state === 'failed'
|
||||
? t('admin.shippingOrderProfiles.workbench.orderFieldValueFailed')
|
||||
// 新圈选的 XFA 值框先显示同次受控视觉回读;整页 PDFium/OCR 预览完成后再覆盖。
|
||||
: region.suggestedValue || t('admin.shippingOrderProfiles.workbench.sampleValueUnavailable');
|
||||
return `${region.label} · ${suffix}`;
|
||||
};
|
||||
/** 以固定步进调整页面倍率;区域采用相对坐标,缩放后仍与图像精确对齐。 */
|
||||
|
||||
+20
@@ -194,4 +194,24 @@ describe('XfaDatasetTree', () => {
|
||||
await wrapper.find('[data-xfa-path-id="leaf"]').trigger('click');
|
||||
expect(wrapper.emitted('select-path')?.[0]).toEqual(['leaf', true]);
|
||||
});
|
||||
|
||||
it('expands sample display in picker mode without truncating the class layout', () => {
|
||||
const wrapper = mount(XfaDatasetTree, {
|
||||
global: { plugins: [i18n] },
|
||||
props: {
|
||||
expandSamples: true,
|
||||
tree: {
|
||||
path_id: 'root', local_name: 'data', data_path_hash: 'h', depth: 0, cardinality: 'one',
|
||||
is_leaf: false,
|
||||
children: [{
|
||||
path_id: 'leaf', local_name: 'NAME1', data_path_hash: 'h2', depth: 1, cardinality: 'one',
|
||||
is_leaf: true, sample_value_display: 'Cloud Network Technology Kft.', display_policy: 'full',
|
||||
}],
|
||||
},
|
||||
},
|
||||
});
|
||||
// 断言意图:弹窗选型模式启用 expandSamples,完整样本可出现在节点上。
|
||||
expect(wrapper.find('.xfa-tree').classes()).toContain('xfa-tree--expand-samples');
|
||||
expect(wrapper.find('.sample').text()).toBe('Cloud Network Technology Kft.');
|
||||
});
|
||||
});
|
||||
+23
-4
@@ -2,7 +2,8 @@
|
||||
features/admin/modules/shipping-order-document-profiles/components/XfaDatasetTree.vue
|
||||
用途:XFA 受控数据树;主工作台用于绑定导航,高级诊断抽屉内只读展示。
|
||||
依赖:vue-i18n、xfaProfileMapping.utils。
|
||||
逻辑:支持展开折叠、方向键导航与完整样本值展示;readonly 时隐藏增删改规则动作。
|
||||
逻辑:支持展开折叠、方向键导航与完整样本值展示;readonly 时隐藏增删改规则动作;
|
||||
expandSamples 用于弹窗选型场景,放宽样本列宽度并允许换行。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, ref } from 'vue';
|
||||
@@ -25,6 +26,8 @@ const props = defineProps<{
|
||||
splitRuleSets?: XfaSplitRuleSet[];
|
||||
/** 为 true 时隐藏新增/编辑/删除规则操作,仅保留选择与诊断。 */
|
||||
readonly?: boolean;
|
||||
/** 弹窗选型时放宽样本列展示,避免窄侧栏截断。 */
|
||||
expandSamples?: boolean;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
'select-path': [pathId: string, isLeaf: boolean];
|
||||
@@ -40,6 +43,7 @@ const flat = computed(() => flattenXfaTreeNodes(props.tree || undefined));
|
||||
const collapsed = ref(new Set<string>());
|
||||
const focusedPathId = ref('');
|
||||
const isReadonly = computed(() => Boolean(props.readonly));
|
||||
const expandSamples = computed(() => Boolean(props.expandSamples));
|
||||
const visible = computed(() => {
|
||||
const filtered = filterXfaTreeNodes(flat.value, query.value);
|
||||
if (query.value.trim()) return filtered;
|
||||
@@ -78,7 +82,9 @@ function toggle(pathId: string): void {
|
||||
* @param node 扁平树节点
|
||||
*/
|
||||
function pathTitle(node: XfaFlatTreeNode): string {
|
||||
return buildXfaPathLabel(node.pathId, flat.value);
|
||||
const path = buildXfaPathLabel(node.pathId, flat.value);
|
||||
const sample = String(node.sampleValueDisplay || '').trim();
|
||||
return sample ? `${path} · ${sample}` : path;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -151,7 +157,11 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="xfa-tree" :aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.treeTitle')">
|
||||
<section
|
||||
class="xfa-tree"
|
||||
:class="{ 'xfa-tree--expand-samples': expandSamples }"
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaWorkbench.treeTitle')"
|
||||
>
|
||||
<label class="xfa-tree__search">
|
||||
<span class="sr-only">{{ t('admin.shippingOrderProfiles.xfaWorkbench.searchPaths') }}</span>
|
||||
<input v-model="query" type="search" :placeholder="t('admin.shippingOrderProfiles.xfaWorkbench.searchPaths')" />
|
||||
@@ -198,7 +208,7 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
:aria-label="t('admin.shippingOrderProfiles.xfaSplit.addRule')"
|
||||
@click.stop="emit('add-rule', node.pathId)"
|
||||
>+</button>
|
||||
<span v-if="node.sampleValueDisplay" class="sample">
|
||||
<span v-if="node.sampleValueDisplay" class="sample" :title="node.sampleValueDisplay">
|
||||
{{ node.sampleValueDisplay }}
|
||||
</span>
|
||||
</div>
|
||||
@@ -250,6 +260,15 @@ async function onKeydown(event: KeyboardEvent, pathId: string): Promise<void> {
|
||||
.xfa-tree__node .name { min-width: 0; overflow: hidden; font-size: .82rem; line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree__node .path-hint { min-width: 0; overflow: hidden; color: var(--text-muted); font-size: .64rem; line-height: 1.2; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree__node .sample { min-width: 3.2rem; margin-left: auto; max-width: 30%; overflow: hidden; color: var(--text-muted); font-size: .68rem; text-align: right; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-tree--expand-samples .xfa-tree__node { align-items: flex-start; }
|
||||
.xfa-tree--expand-samples .xfa-tree__node .sample {
|
||||
max-width: 48%;
|
||||
white-space: normal;
|
||||
overflow-wrap: anywhere;
|
||||
word-break: break-word;
|
||||
line-height: 1.25;
|
||||
text-align: left;
|
||||
}
|
||||
.xfa-tree__node .badge { color: var(--status-warning-fg); font-size: .72rem; font-weight: 700; }
|
||||
.toggle, .toggle-spacer { display: inline-flex; width: 16px; flex: 0 0 16px; }
|
||||
.add-rule { display: none; position: relative; z-index: 1; min-width: 24px; min-height: 24px; align-items: center; justify-content: center; margin-left: 2px; border: 1px solid transparent; border-radius: 5px; background: transparent; color: var(--status-info-fg); font-size: 1rem; line-height: 1; cursor: pointer; }
|
||||
|
||||
+132
-3
@@ -2,6 +2,7 @@
|
||||
* features/admin/modules/shipping-order-document-profiles/components/XfaSplitRulePanel.spec.ts
|
||||
* 用途:验证 XfaSplitRulePanel pipeline 规则增删、确认门禁、order 重排与完整值预览。
|
||||
* 依赖:Vitest、@vue/test-utils、shipping-order-document-profile API mock。
|
||||
* 逻辑:确认门禁须忽略 line_match_candidates 等 informational 诊断,仅阻断真实冲突。
|
||||
*/
|
||||
|
||||
import { describe, expect, it, vi, beforeEach } from 'vitest';
|
||||
@@ -87,6 +88,7 @@ const xfaSplitMessages = {
|
||||
previewNoSegments: '无段',
|
||||
previewValue: '值',
|
||||
previewRuleStatus: '状态',
|
||||
fullValuesRevealed: '当前预览为完整值',
|
||||
diagnostics: '诊断',
|
||||
ruleSetSettings: '规则集',
|
||||
normalization: '归一化',
|
||||
@@ -374,6 +376,56 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(confirmed).toBeFalsy();
|
||||
});
|
||||
|
||||
it('allows confirm when only informational line_match_candidates diagnostics exist', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-info-diag',
|
||||
preview: {
|
||||
status: 'parsed',
|
||||
mapped_fields: {},
|
||||
segments: [
|
||||
{
|
||||
segment_id: 'seg-1',
|
||||
segment_code: 'customer_part_number',
|
||||
rule_id: 'rule-1',
|
||||
matcher_type: 'position',
|
||||
normalized_text: 'CPN',
|
||||
raw_text: 'CPN',
|
||||
status: 'parsed',
|
||||
line_no: 1,
|
||||
},
|
||||
{
|
||||
segment_id: 'unmatched-2',
|
||||
segment_code: 'unmatched_line_2',
|
||||
rule_id: 'unmatched',
|
||||
matcher_type: 'unmatched',
|
||||
normalized_text: 'noise',
|
||||
raw_text: 'noise',
|
||||
status: 'parsed',
|
||||
line_no: 2,
|
||||
},
|
||||
],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [
|
||||
{ code: 'line_match_candidates', message: 'All matcher hits for line recorded', line_no: 1 },
|
||||
{ code: 'line_match_candidates', message: 'All matcher hits for line recorded', line_no: 2 },
|
||||
],
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet()],
|
||||
},
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
expect(wrapper.text()).not.toContain('line_match_candidates');
|
||||
exposedActions(wrapper).confirmRules();
|
||||
expect(messageError).not.toHaveBeenCalledWith('诊断阻断');
|
||||
const confirmed = wrapper.emitted('confirmed');
|
||||
expect(confirmed?.[0]?.[1]).toMatchObject({ 'path-matnr': 'tok-info-diag' });
|
||||
});
|
||||
|
||||
it('blocks confirm when a mapped segment has no Schema target', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-mapped-empty',
|
||||
@@ -422,6 +474,13 @@ describe('XfaSplitRulePanel', () => {
|
||||
const last = emitted?.[emitted.length - 1]?.[0] as typeof baseDefinition.split_rules;
|
||||
const range = last?.[0]?.rules?.[0]?.stages?.find((stage) => stage.type === 'select_line_range');
|
||||
expect(range).toMatchObject({ line_start: 1, line_end: 2, join_with: 'newline' });
|
||||
// 断言意图:正式 matcher 须带 line_end/join_with,不能只投影成单行 line_index。
|
||||
expect(last?.[0]?.rules?.[0]?.matcher).toMatchObject({
|
||||
type: 'position',
|
||||
line_index: 1,
|
||||
line_end: 2,
|
||||
join_with: 'newline',
|
||||
});
|
||||
const rangeWrapper = mountPanel({
|
||||
definition: { ...baseDefinition, split_rules: last },
|
||||
});
|
||||
@@ -430,6 +489,63 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(rangeWrapper.text()).toContain('合并方式');
|
||||
});
|
||||
|
||||
it('previews consecutive line extraction with line_end and join_with in formal payload', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-range',
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [{
|
||||
segment_id: 'seg-addr',
|
||||
segment_code: 'bill_to_address',
|
||||
rule_id: 'rule-1',
|
||||
matcher_type: 'position',
|
||||
line_no: 2,
|
||||
line_end_no: 4,
|
||||
normalized_text: 'Bánki Donát u. 1.\n2900 Komárom\nHungary',
|
||||
raw_text: 'Bánki Donát u. 1.\n2900 Komárom\nHungary',
|
||||
status: 'parsed',
|
||||
}],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [],
|
||||
full_values_revealed: true,
|
||||
},
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
...baseDefinition,
|
||||
split_rules: [makePipelineRuleSet({
|
||||
rules: [{
|
||||
...makePipelineRuleSet().rules[0],
|
||||
matcher: { type: 'position', line_index: 2, line_end: 4, join_with: 'newline' },
|
||||
stages: [
|
||||
{ stage_id: 'split', type: 'split_lines', line_breaks: ['\\n'] },
|
||||
{ stage_id: 'range', type: 'select_line_range', line_start: 2, line_end: 4, join_with: 'newline' },
|
||||
],
|
||||
}],
|
||||
})],
|
||||
},
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({
|
||||
reveal: true,
|
||||
rule_set: expect.objectContaining({
|
||||
rules: [expect.objectContaining({
|
||||
matcher: expect.objectContaining({
|
||||
type: 'position',
|
||||
line_index: 2,
|
||||
line_end: 4,
|
||||
join_with: 'newline',
|
||||
}),
|
||||
})],
|
||||
}),
|
||||
}));
|
||||
expect(wrapper.text()).toContain('Bánki Donát u. 1.');
|
||||
expect(wrapper.text()).toContain('2900 Komárom');
|
||||
expect(wrapper.text()).toContain('Hungary');
|
||||
});
|
||||
|
||||
it('emits the final confirmed rules for parent persistence', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview_token: 'tok-preview-1',
|
||||
@@ -578,15 +694,25 @@ describe('XfaSplitRulePanel', () => {
|
||||
expect(rules?.[0]?.rules).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('previews full values without a reveal permission parameter', async () => {
|
||||
it('previews split rules with reveal so mapped values are not masked', async () => {
|
||||
previewMock.mockResolvedValue({
|
||||
preview: {
|
||||
status: 'ok',
|
||||
mapped_fields: {},
|
||||
segments: [],
|
||||
segments: [
|
||||
{
|
||||
segment_id: 's1',
|
||||
segment_code: 'bill_to_customer',
|
||||
normalized_text: 'Cloud Network Technology Kft.',
|
||||
raw_text: 'Cloud Network Technology Kft.',
|
||||
status: 'parsed',
|
||||
},
|
||||
],
|
||||
evidence_only_segments: [],
|
||||
diagnostics: [],
|
||||
full_values_revealed: true,
|
||||
},
|
||||
preview_token: 'tok-full',
|
||||
});
|
||||
const wrapper = mountPanel({
|
||||
definition: {
|
||||
@@ -596,7 +722,10 @@ describe('XfaSplitRulePanel', () => {
|
||||
});
|
||||
await exposedActions(wrapper).runPreview();
|
||||
await flushPromises();
|
||||
expect(previewMock).toHaveBeenCalledWith(85, expect.not.objectContaining({ reveal: expect.anything() }));
|
||||
// 断言意图:文档模板拆分预览与侧栏同源,必须带 reveal 以免分段值被遮蔽。
|
||||
expect(previewMock).toHaveBeenCalledWith(85, expect.objectContaining({ reveal: true }));
|
||||
expect(wrapper.text()).toContain('Cloud Network Technology Kft.');
|
||||
expect(wrapper.text()).not.toContain('Clou***');
|
||||
});
|
||||
|
||||
it('sends formal matcher post-processors instead of UI-only pipeline fields to preview', async () => {
|
||||
|
||||
+87
-16
@@ -3,7 +3,10 @@
|
||||
用途:XFA 字段拆分规则编辑——matcher 优先(prefix/regex/position),兼容历史 stages[] 投影。
|
||||
依赖:shipping-order-document-profile API、vue-i18n、Schema 字段列表。
|
||||
逻辑:编辑 definition.split_rules;新增/改提取方式同步写入 matcher;stages 仅保留编辑态;
|
||||
预览和确认统一投影为正式 matcher DTO,确认前须校验同一正式 DTO 哈希。
|
||||
预览和确认统一投影为正式 matcher DTO,确认前须校验同一正式 DTO 哈希;
|
||||
连续多行提取投影为 position.line_end + join_with,引擎合并多行文本;
|
||||
预览优先 reveal 完整分段值(与映射台侧栏/数据源弹窗一致),权限不足再回退脱敏;
|
||||
确认门禁仅阻断真正影响取值可信度的诊断(与后端 informational 白名单对齐)。
|
||||
-->
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
@@ -36,6 +39,15 @@ type XfaSplitRulePatch = Omit<Partial<XfaSplitRule>, 'segment' | 'stages' | 'mat
|
||||
|
||||
type XfaSplitStagePatch = Partial<XfaSplitStage>;
|
||||
type ExtractionMode = 'select_line' | 'select_line_range' | 'extract_prefix' | 'regex_capture' | 'substring';
|
||||
type XfaSplitPreviewDiagnostic = XfaSplitPreviewResult['diagnostics'][number];
|
||||
|
||||
/**
|
||||
* 与后端 xfa_profile_extraction._SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES 对齐。
|
||||
* line_match_candidates 仅记录命中审计,不表示歧义;未配置规则的行在 evidence_only 下也不应阻断确认。
|
||||
*/
|
||||
const SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES = new Set([
|
||||
'line_match_candidates',
|
||||
]);
|
||||
|
||||
const props = defineProps<{
|
||||
definition: OrderXfaDatasetProfileDefinition;
|
||||
@@ -75,6 +87,23 @@ const SEGMENT_CODE_RE = /^[a-z][a-z0-9_]{1,63}$/;
|
||||
|
||||
const isReadonly = computed(() => props.readonly || props.canEdit === false);
|
||||
|
||||
/**
|
||||
* 判断诊断码是否会阻断确认(排除仅审计用的 informational 码)。
|
||||
* @param code - 预览诊断 code
|
||||
* @returns true 表示须阻断确认
|
||||
*/
|
||||
function isBlockingSplitDiagnostic(code: string | null | undefined): boolean {
|
||||
if (!code) return true;
|
||||
return !SPLIT_INFORMATIONAL_DIAGNOSTIC_CODES.has(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览中真正影响确认/取值可信度的诊断列表(过滤 line_match_candidates 等审计项)。
|
||||
*/
|
||||
const blockingDiagnostics = computed((): XfaSplitPreviewDiagnostic[] => (
|
||||
(preview.value?.diagnostics || []).filter((item) => isBlockingSplitDiagnostic(item.code))
|
||||
));
|
||||
|
||||
/** 可被拆分段正式写入的字段;Schema 外字段只能作为 evidence 保留。 */
|
||||
const splitTargetFields = computed(() => (props.schemaFields || []).filter((field) => (
|
||||
field.enabled !== false && Boolean(field.field_id && field.field_code)
|
||||
@@ -228,6 +257,7 @@ function createDefaultPipelineStages(lineIndex = 1): XfaSplitStage[] {
|
||||
|
||||
/**
|
||||
* 由提取模式与阶段参数生成正式 matcher(prefix > regex > position)。
|
||||
* 连续多行写入 position.line_end + join_with,供引擎合并多行文本。
|
||||
*/
|
||||
function matcherFromExtraction(mode: ExtractionMode, stage: Partial<XfaSplitStage>, order: number): XfaSplitMatcher {
|
||||
if (mode === 'extract_prefix') {
|
||||
@@ -246,6 +276,16 @@ function matcherFromExtraction(mode: ExtractionMode, stage: Partial<XfaSplitStag
|
||||
case_sensitive: Boolean(stage.case_sensitive),
|
||||
};
|
||||
}
|
||||
if (mode === 'select_line_range') {
|
||||
const lineStart = Number(stage.line_start || order || 1);
|
||||
const lineEnd = Number(stage.line_end || lineStart);
|
||||
return {
|
||||
type: 'position',
|
||||
line_index: lineStart,
|
||||
line_end: Math.max(lineEnd, lineStart),
|
||||
join_with: (stage.join_with || 'newline') as 'newline' | 'space' | 'comma',
|
||||
};
|
||||
}
|
||||
return {
|
||||
type: 'position',
|
||||
line_index: Number(stage.line_index || stage.line_start || order || 1),
|
||||
@@ -301,18 +341,33 @@ function applyRuleSetChange(updater: (ruleSet: XfaSplitRuleSet) => XfaSplitRuleS
|
||||
}
|
||||
|
||||
/**
|
||||
* 预览当前规则集执行结果;返回脱敏预览与确认令牌(完整值需 reveal)。
|
||||
* 预览当前规则集执行结果并签发确认令牌。
|
||||
* 核心逻辑:与映射台侧栏一致,优先 reveal 完整分段值供配置辨认;无敏感读权限时回退脱敏预览。
|
||||
*/
|
||||
async function runPreview(): Promise<void> {
|
||||
if (!props.selectedPathId || !activeRuleSet.value || props.canPreview === false) return;
|
||||
loading.value = true;
|
||||
try {
|
||||
const formalRuleSet = toFormalRuleSet(activeRuleSet.value);
|
||||
const result = await previewOrderProfileSampleXfaSplitRules(props.documentId, {
|
||||
const payload = {
|
||||
path_id: props.selectedPathId,
|
||||
rule_set: formalRuleSet || {},
|
||||
profile_id: props.profileId,
|
||||
});
|
||||
};
|
||||
let result;
|
||||
try {
|
||||
// [STEP 1] 映射台配置场景优先完整值,避免 Clou***ft 类遮蔽干扰规则校验。
|
||||
result = await previewOrderProfileSampleXfaSplitRules(props.documentId, {
|
||||
...payload,
|
||||
reveal: true,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof BusinessError && error.code === 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_VALUE_FORBIDDEN') {
|
||||
result = await previewOrderProfileSampleXfaSplitRules(props.documentId, payload);
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
preview.value = result.preview;
|
||||
previewRuleSetHash.value = hashRuleSet(activeRuleSet.value);
|
||||
previewConfirmationToken.value = String(result.preview_token || '') || null;
|
||||
@@ -324,8 +379,9 @@ async function runPreview(): Promise<void> {
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员确认规则:须已预览当前 rule_set;诊断或 needs_review 时阻断。
|
||||
* 核心逻辑:确认事件携带完整规则数组与 preview_token,由父页面保存时交服务端校验。
|
||||
* 管理员确认规则:须已预览当前 rule_set;阻断性诊断或 needs_review 时阻断。
|
||||
* 核心逻辑:确认事件携带完整规则数组与 preview_token,由父页面保存时交服务端校验;
|
||||
* line_match_candidates 与未匹配行(evidence_only)不视为阻断。
|
||||
*/
|
||||
function confirmRules(): void {
|
||||
if (!activeRuleSet.value || isReadonly.value) return;
|
||||
@@ -341,13 +397,13 @@ function confirmRules(): void {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaSplit.confirmNeedsPreview'));
|
||||
return;
|
||||
}
|
||||
if (preview.value.status === 'needs_review' || (preview.value.diagnostics || []).length > 0) {
|
||||
if (preview.value.status === 'needs_review' || blockingDiagnostics.value.length > 0) {
|
||||
message.error(t('admin.shippingOrderProfiles.xfaSplit.confirmBlockedDiagnostics'));
|
||||
return;
|
||||
}
|
||||
const ruleCount = activeRuleSet.value.rules.length;
|
||||
const segmentCount = (preview.value.segments || []).length;
|
||||
const diagCount = (preview.value.diagnostics || []).length;
|
||||
const diagCount = blockingDiagnostics.value.length;
|
||||
const summary = t('admin.shippingOrderProfiles.xfaSplit.confirmDialog', {
|
||||
rules: ruleCount,
|
||||
segments: segmentCount,
|
||||
@@ -464,9 +520,19 @@ function extractionStage(rule: XfaSplitRule): XfaSplitStage {
|
||||
};
|
||||
}
|
||||
if (rule.matcher?.type === 'position') {
|
||||
const lineStart = rule.matcher.line_index ?? rule.order ?? 1;
|
||||
const lineEnd = rule.matcher.line_end ?? lineStart;
|
||||
if (Number(lineEnd) > Number(lineStart)) {
|
||||
return {
|
||||
...createDefaultStage('select_line_range'),
|
||||
line_start: lineStart,
|
||||
line_end: lineEnd,
|
||||
join_with: rule.matcher.join_with || 'newline',
|
||||
};
|
||||
}
|
||||
return {
|
||||
...createDefaultStage('select_line'),
|
||||
line_index: rule.matcher.line_index ?? rule.order ?? 1,
|
||||
line_index: lineStart,
|
||||
};
|
||||
}
|
||||
return { ...createDefaultStage('select_line'), line_index: rule.order ?? 1 };
|
||||
@@ -474,12 +540,16 @@ function extractionStage(rule: XfaSplitRule): XfaSplitStage {
|
||||
|
||||
function extractionMode(rule: XfaSplitRule): ExtractionMode {
|
||||
const stages = rule.stages || [];
|
||||
// 连续行/截取仍靠 stages 驱动 UI;正式 matcher 用 position 近似。
|
||||
// 连续行/截取仍可靠 stages 驱动 UI;正式 matcher 也可用 line_end 表达连续多行。
|
||||
if (stages.some((stage) => stage.type === 'select_line_range')) return 'select_line_range';
|
||||
if (stages.some((stage) => stage.type === 'substring')) return 'substring';
|
||||
if (rule.matcher?.type === 'prefix') return 'extract_prefix';
|
||||
if (rule.matcher?.type === 'regex') return 'regex_capture';
|
||||
if (rule.matcher?.type === 'position') return 'select_line';
|
||||
if (rule.matcher?.type === 'position') {
|
||||
const start = Number(rule.matcher.line_index || 0);
|
||||
const end = Number(rule.matcher.line_end || start);
|
||||
return end > start ? 'select_line_range' : 'select_line';
|
||||
}
|
||||
return extractionStage(rule).type as ExtractionMode;
|
||||
}
|
||||
|
||||
@@ -907,9 +977,9 @@ watch(activeRuleSet, (current, previous) => {
|
||||
</table>
|
||||
<p v-else class="hint">{{ t('admin.shippingOrderProfiles.xfaSplit.previewNoSegments') }}</p>
|
||||
|
||||
<h5 v-if="preview.diagnostics?.length">{{ t('admin.shippingOrderProfiles.xfaSplit.diagnostics') }}</h5>
|
||||
<ul v-if="preview.diagnostics?.length" class="xfa-split__diagnostics">
|
||||
<li v-for="(diag, idx) in preview.diagnostics" :key="`${diag.code}-${idx}`">
|
||||
<h5 v-if="blockingDiagnostics.length">{{ t('admin.shippingOrderProfiles.xfaSplit.diagnostics') }}</h5>
|
||||
<ul v-if="blockingDiagnostics.length" class="xfa-split__diagnostics">
|
||||
<li v-for="(diag, idx) in blockingDiagnostics" :key="`${diag.code}-${idx}`">
|
||||
<strong>{{ diag.code }}</strong>: {{ diag.message }}
|
||||
<small v-if="diag.line_no">L{{ diag.line_no }}</small>
|
||||
</li>
|
||||
@@ -1333,8 +1403,8 @@ watch(activeRuleSet, (current, previous) => {
|
||||
.xfa-split__rule-title .rule-chevron { width: 12px; color: var(--status-info-fg); font-size: 1rem; }
|
||||
.xfa-split__rule-detail { display: grid; gap: 6px; }
|
||||
.xfa-split__extraction { display: grid; grid-template-columns: minmax(180px, 1fr) minmax(160px, .7fr); gap: 8px 12px; padding: 10px; border: 1px solid var(--status-info-border); border-radius: 6px; background: var(--status-info-bg); }
|
||||
.xfa-split__inline-preview { grid-column: 1 / -1; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-top: 7px; border-top: 1px solid var(--status-info-border); color: var(--text-muted); font-size: .75rem; }
|
||||
.xfa-split__inline-preview strong { max-width: 70%; overflow: hidden; color: var(--status-success-fg); text-overflow: ellipsis; white-space: nowrap; }
|
||||
.xfa-split__inline-preview { grid-column: 1 / -1; display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; padding-top: 7px; border-top: 1px solid var(--status-info-border); color: var(--text-muted); font-size: .75rem; }
|
||||
.xfa-split__inline-preview strong { max-width: 70%; overflow: hidden; color: var(--status-success-fg); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.xfa-split__advanced-toggle { justify-self: start; padding: 3px 0; border: 0; background: transparent; color: var(--status-info-fg); cursor: pointer; font-size: .75rem; }
|
||||
.xfa-split__rule-actions { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.xfa-split__rule-actions button { padding: 2px 6px; font-size: 0.72rem; border: 1px solid var(--border-default); border-radius: 4px; background: var(--bg-page); cursor: pointer; }
|
||||
@@ -1349,6 +1419,7 @@ watch(activeRuleSet, (current, previous) => {
|
||||
.xfa-split__preview h4, .xfa-split__preview h5 { margin: 8px 0 4px; font-size: 0.85rem; }
|
||||
.xfa-split__table { width: 100%; border-collapse: collapse; font-size: 0.75rem; }
|
||||
.xfa-split__table th, .xfa-split__table td { border: 1px solid var(--border-default); padding: 4px 6px; text-align: left; vertical-align: top; }
|
||||
.xfa-split__table td:nth-child(4) { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.xfa-split__diagnostics li { font-size: 0.8rem; color: var(--status-warning-fg); }
|
||||
.xfa-split__hint-error { color: var(--status-error-fg); font-size: 0.72rem; }
|
||||
.xfa-split__invalid { border-color: var(--status-error-border); }
|
||||
|
||||
+1100
-5
File diff suppressed because it is too large.
Load diff
+932
-106
File diff suppressed because it is too large.
Load diff
+35
-1
@@ -2,7 +2,8 @@
|
||||
* features/admin/modules/shipping-order-document-profiles/orderProfileForm.utils.spec.ts
|
||||
* 用途:验证可视化订单模板表单生成受控规则、明细字段分组,并确保切换样本时配置入口不会消失。
|
||||
* 依赖:Vitest、orderProfileForm.utils。
|
||||
* 逻辑:覆盖 direct、复合解析器开关及跨列冲突,避免无效配置进入后端。
|
||||
* 逻辑:覆盖 direct、复合解析器开关及跨列冲突,避免无效配置进入后端;
|
||||
* XFA 识别结果在 OCR 空值时用 datasets header_fields 增量补齐。
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
@@ -269,6 +270,37 @@ describe('order profile form rules', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('overlays XFA datasets header_fields when OCR header values are empty', () => {
|
||||
const regions = [
|
||||
{ id: 'date-box', kind: 'order_field' as const, label: 'Date', fieldCode: 'order_date', pageNo: 1, region: { x0: .4, y0: .1, x1: .6, y1: .15 } },
|
||||
{ id: 'currency-box', kind: 'order_field' as const, label: 'Currency', fieldCode: 'currency', pageNo: 1, region: { x0: .6, y0: .1, x1: .7, y1: .15 } },
|
||||
{ id: 'po-box', kind: 'order_field' as const, label: 'PO', fieldCode: 'customer_po_number', pageNo: 1, region: { x0: .1, y0: .1, x1: .3, y1: .15 } },
|
||||
];
|
||||
|
||||
const results = buildOrderProfileRecognitionResults(
|
||||
regions,
|
||||
[{ field_id: 'po', field_code: 'customer_po_number', value: '4510039227', source: 'ocr_coordinate', status: 'confirmed', page_no: 1, issues: [] }],
|
||||
null,
|
||||
'loading',
|
||||
{
|
||||
header_fields: [
|
||||
{ field_id: 'date', field_code: 'order_date', raw_value: '2024-05-20', normalized_value: '2024-05-20', status: 'passed', issues: [] },
|
||||
{ field_id: 'currency', field_code: 'currency', raw_value: 'USD', normalized_value: 'USD', status: 'passed', issues: [] },
|
||||
{ field_id: 'po', field_code: 'customer_po_number', raw_value: 'DATASET-PO', normalized_value: 'DATASET-PO', status: 'passed', issues: [] },
|
||||
],
|
||||
lines: [],
|
||||
cross_checks: {},
|
||||
},
|
||||
);
|
||||
|
||||
// datasets 只增量补齐 OCR 空值;已有 OCR 值(PO)不得被 datasets 覆盖。
|
||||
expect(results.header).toMatchObject([
|
||||
{ id: 'date-box', fieldCode: 'order_date', value: '2024-05-20', status: 'read' },
|
||||
{ id: 'currency-box', fieldCode: 'currency', value: 'USD', status: 'read' },
|
||||
{ id: 'po-box', fieldCode: 'customer_po_number', value: '4510039227', status: 'read' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('selects only the current XFA validation evidence for the active draft checksum', () => {
|
||||
const evidence = {
|
||||
header_fields: [], lines: [{ row_index: 0, fields: [] }], cross_checks: {},
|
||||
@@ -345,11 +377,13 @@ describe('order profile form rules', () => {
|
||||
it('serializes accepted header fields with header scope', () => {
|
||||
// 表头候选接受后必须进入 header_layouts;写成 line 会被后端契约拒绝,导致表头刷新后消失。
|
||||
expect(toOrderProfileHeaderFieldRegion({
|
||||
id: 'header_field_1_1',
|
||||
fieldCode: 'delivery_date',
|
||||
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
|
||||
})).toEqual({
|
||||
field_id: '', field_code: 'delivery_date', scope: 'header',
|
||||
region: { x0: .2, y0: .1, x1: .4, y1: .16 },
|
||||
region_id: 'header_field_1_1',
|
||||
extractor_key: 'direct', allowed_sources: ['pdf_coordinate'], minimum_evidence_level: 'coordinate',
|
||||
});
|
||||
expect(toOrderProfileHeaderFieldRegion({
|
||||
|
||||
+33
-5
@@ -3,7 +3,8 @@
|
||||
* 用途:构造可视化订单模板的白名单列规则、明细字段分组,并控制样本表格配置区的安全显示。
|
||||
* 依赖:订单 Profile DTO。
|
||||
* 逻辑:页面状态只允许 direct 或已注册复合解析器;同一目标字段跨列只能出现一次;
|
||||
* 另提供「未绑定订单字段」判定,供画布强制高亮与编辑横幅共用。
|
||||
* 另提供「未绑定订单字段」判定,供画布强制高亮与编辑横幅共用;
|
||||
* 表头/明细 field_regions 可带 region_id,供 XFA binding 按画布框精确定位。
|
||||
*/
|
||||
|
||||
import type {
|
||||
@@ -60,7 +61,7 @@ export const isUnboundOrderFieldCanvasRegion = (
|
||||
* @returns 可持久化的表头字段区域;没有 fieldCode 时返回 null。
|
||||
*/
|
||||
export const toOrderProfileHeaderFieldRegion = (
|
||||
item: Pick<OrderProfileCanvasRegion, 'fieldCode' | 'region'>,
|
||||
item: Pick<OrderProfileCanvasRegion, 'id' | 'fieldCode' | 'region'>,
|
||||
scope: 'header' | 'line' = 'header',
|
||||
): OrderProfileFieldRegion | null => {
|
||||
if (!item.fieldCode) return null;
|
||||
@@ -69,6 +70,7 @@ export const toOrderProfileHeaderFieldRegion = (
|
||||
field_code: item.fieldCode,
|
||||
scope,
|
||||
region: item.region,
|
||||
region_id: item.id || null,
|
||||
extractor_key: 'direct',
|
||||
allowed_sources: ['pdf_coordinate'],
|
||||
minimum_evidence_level: 'coordinate',
|
||||
@@ -141,8 +143,14 @@ export const restoreFormalBindingFieldCodes = (
|
||||
const fieldCodeByRegionId = new Map<string, string>();
|
||||
for (const region of existingRegions) {
|
||||
if (region.kind !== 'field' || !region.parentId || !region.fieldCode) continue;
|
||||
const layoutId = `${region.parentId}:${region.fieldCode}`;
|
||||
if (formalBindingLayoutIds.has(layoutId)) fieldCodeByRegionId.set(region.id, region.fieldCode);
|
||||
// 新身份:region.id;旧身份:parent:fieldCode。任一命中正式 binding 即可恢复。
|
||||
const legacyLayoutId = `${region.parentId}:${region.fieldCode}`;
|
||||
if (
|
||||
formalBindingLayoutIds.has(region.id)
|
||||
|| formalBindingLayoutIds.has(legacyLayoutId)
|
||||
) {
|
||||
fieldCodeByRegionId.set(region.id, region.fieldCode);
|
||||
}
|
||||
}
|
||||
return suggestedRegions.map((region) => {
|
||||
if (region.kind !== 'field' || region.fieldCode) return region;
|
||||
@@ -623,9 +631,14 @@ export const buildOrderProfileCanvasLineFieldValues = (
|
||||
|
||||
/**
|
||||
* 将已有坐标预览和值读取结果变为可反向定位的结构化复核项。
|
||||
* 核心逻辑:OCR/PDFium 表头结果始终保留;若传入 datasets 当前样本证据,则用
|
||||
* header_fields 增量补齐 OCR 为空的表头(订单日期/币种等),明细仅消费 datasets.lines。
|
||||
* @param pageRegions - 当前页画布区域;未标注字段不会伪装成可定位项。
|
||||
* @param fieldValues - 订单表头字段值接口的结果。
|
||||
* @param reconstruction - 坐标重建接口的明细行结果。
|
||||
* @param fieldValueState - 表头 OCR 读取状态。
|
||||
* @param datasetsEvidence - XFA 当前样本正式证据;有则忽略 coordinate reconstruction。
|
||||
* @param reservationCandidates - Reservation 专区候选。
|
||||
* @returns 表头及明细字段结果,均保留对应画布区域 ID。
|
||||
*/
|
||||
export const buildOrderProfileRecognitionResults = (
|
||||
@@ -660,6 +673,21 @@ export const buildOrderProfileRecognitionResults = (
|
||||
// XFA datasets 是正式明细值源;共同视觉坐标只定位和交叉校验,不能把表头或
|
||||
// OCR 候选伪装成已读取的行值。传入此证据时完全忽略 coordinate reconstruction。
|
||||
if (datasetsEvidence) {
|
||||
// [STEP] OCR 为空时用 datasets header_fields 增量补齐,避免 XFA 外观页表头永久「未读取到值」。
|
||||
const formalHeaderByCode = new Map(
|
||||
datasetsEvidence.header_fields.map((field) => [field.field_code, field]),
|
||||
);
|
||||
const mergedHeader = header.map((item) => {
|
||||
if (item.value) return item;
|
||||
const formal = formalHeaderByCode.get(item.fieldCode);
|
||||
const formalValue = formal?.normalized_value || null;
|
||||
if (!formalValue) return item;
|
||||
return {
|
||||
...item,
|
||||
value: formalValue,
|
||||
status: 'read' as const,
|
||||
};
|
||||
});
|
||||
const line = datasetsEvidence.lines.flatMap((row) => (
|
||||
row.fields.map((field) => ({
|
||||
id: regionsByCode.get(field.field_code) || null,
|
||||
@@ -673,7 +701,7 @@ export const buildOrderProfileRecognitionResults = (
|
||||
}))
|
||||
));
|
||||
return applyReservationRegionRecognitionResults(
|
||||
header, line, reservationCandidates, datasetsEvidence.lines.length,
|
||||
mergedHeader, line, reservationCandidates, datasetsEvidence.lines.length,
|
||||
);
|
||||
}
|
||||
if (!reconstruction) {
|
||||
|
||||
+16
@@ -113,6 +113,22 @@ describe('xfaProfileMapping split utils', () => {
|
||||
expect(matnr?.lineCount).toBe(5);
|
||||
});
|
||||
|
||||
it('flattenXfaTreeNodes does not fall back to masked sample asterisks', () => {
|
||||
const tree: XfaFieldTreeNode = {
|
||||
path_id: 'netpr',
|
||||
local_name: 'NETPR',
|
||||
data_path_hash: 'h-netpr',
|
||||
depth: 0,
|
||||
cardinality: 'one',
|
||||
is_leaf: true,
|
||||
sample_value_masked: '***',
|
||||
};
|
||||
const flat = flattenXfaTreeNodes(tree);
|
||||
// 断言意图:与选择数据源弹窗一致,缺 display 时保持空,不展示 ***。
|
||||
expect(flat[0]?.sampleValueDisplay).toBe('');
|
||||
expect(flat[0]?.sampleValueMasked).toBe('***');
|
||||
});
|
||||
|
||||
it('selectedIsMultiline uses lineCount greater than one', () => {
|
||||
const tree: XfaFieldTreeNode = {
|
||||
path_id: 'single',
|
||||
|
||||
+5
-3
@@ -2,7 +2,8 @@
|
||||
* features/admin/modules/shipping-order-document-profiles/xfaProfileMapping.utils.ts
|
||||
* 用途:XFA 映射工作台纯函数——树投影、Schema 过滤、覆盖率、保存 payload 与脏状态检测。
|
||||
* 依赖:shipping-order-document-profile.types、订单 Schema 字段类型。
|
||||
* 逻辑:页面与组件只调用本文件;不发网络请求,不持有明文 XML 或 data_path。
|
||||
* 逻辑:页面与组件只调用本文件;不发网络请求,不持有明文 XML 或 data_path;
|
||||
* 扁平树样本展示只用 sample_value_display,与选择数据源弹窗一致,禁止回退脱敏 ***。
|
||||
*/
|
||||
|
||||
import type {
|
||||
@@ -40,7 +41,7 @@ export interface XfaMappingWorkbenchState {
|
||||
|
||||
/**
|
||||
* 将 XFA 字段树投影为可键盘导航的扁平节点列表。
|
||||
* 核心逻辑:深度优先展开;仅保留分析记录返回的节点。
|
||||
* 核心逻辑:深度优先展开;样本展示仅取 sample_value_display(与弹窗一致),不回退脱敏。
|
||||
* @param tree 字段树根节点
|
||||
* @returns 扁平节点(含 depth / leaf / collection 标记)
|
||||
*/
|
||||
@@ -57,7 +58,8 @@ export function flattenXfaTreeNodes(tree: XfaFieldTreeNode | null | undefined):
|
||||
isHeaderCandidate: Boolean(node.is_header_candidate),
|
||||
isCollectionCandidate: Boolean(node.is_collection_candidate),
|
||||
sampleValueMasked: node.sample_value_masked,
|
||||
sampleValueDisplay: node.sample_value_display || node.sample_value_masked,
|
||||
// 映射台/弹窗样本与侧栏同源:只用受控 sample_value_display,禁止回退脱敏 ***。
|
||||
sampleValueDisplay: node.sample_value_display || '',
|
||||
displayPolicy: node.display_policy || 'empty',
|
||||
canReveal: Boolean(node.can_reveal),
|
||||
lineCount: node.line_count,
|
||||
|
||||
@@ -69,7 +69,18 @@ export interface OrderProfileCoordinateModel {
|
||||
max_translate_x?: number;
|
||||
max_translate_y?: number;
|
||||
}
|
||||
export interface OrderProfileFieldRegion { field_id: string; field_code: string; scope: 'header' | 'line'; region: OrderProfileRelativeRegion; extractor_key: OrderProfileExtractorKey; allowed_sources: OrderProfileAllowedSource[]; minimum_evidence_level: OrderProfileEvidenceLevel; target_fields?: Array<{ field_id: string; field_code: string; scope: 'header' | 'line' }>; }
|
||||
export interface OrderProfileFieldRegion {
|
||||
field_id: string;
|
||||
field_code: string;
|
||||
scope: 'header' | 'line';
|
||||
region: OrderProfileRelativeRegion;
|
||||
/** 画布框稳定身份;XFA binding.field_layout_id 优先引用,避免同 field_code 多框撞绑。 */
|
||||
region_id?: string | null;
|
||||
extractor_key: OrderProfileExtractorKey;
|
||||
allowed_sources: OrderProfileAllowedSource[];
|
||||
minimum_evidence_level: OrderProfileEvidenceLevel;
|
||||
target_fields?: Array<{ field_id: string; field_code: string; scope: 'header' | 'line' }>;
|
||||
}
|
||||
export interface OrderProfileOrderFieldLayout { layout_id: string; field_id: string; field_code: string; scope: 'header'; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; normalizer_key?: string | null; required: boolean; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileDraftUnboundOrderFieldLayout { layout_id: string; label: string; page_scope: 'first_page' | 'all_pages' | 'exact_page'; page_no?: number | null; anchor?: OrderProfileAnchorRule | null; value_region?: OrderProfileAnchorRelativeRegion | null; absolute_value_region?: OrderProfileRelativeRegion | null; fallback_value_region?: OrderProfileRelativeRegion | null; value_mode: 'single_line' | 'multi_line' | 'right_of_anchor' | 'below_anchor'; stop_anchors: OrderProfileAnchorRule[]; minimum_evidence_level: OrderProfileEvidenceLevel; }
|
||||
export interface OrderProfileHeaderLayout { layout_id: string; region: OrderProfileRelativeRegion; field_regions: OrderProfileFieldRegion[]; }
|
||||
@@ -251,10 +262,14 @@ export interface XfaSplitSegment {
|
||||
note?: string | null;
|
||||
}
|
||||
|
||||
/** 单行匹配器:优先级固定 prefix > regex > position > unmatched。 */
|
||||
/** 匹配器:优先级固定 prefix > regex > position > unmatched;position 可连续多行。 */
|
||||
export interface XfaSplitMatcher {
|
||||
type: XfaSplitMatcherType;
|
||||
line_index?: number | null;
|
||||
/** position 连续多行结束行(含);缺省等于 line_index。 */
|
||||
line_end?: number | null;
|
||||
/** 连续多行合并方式;仅 line_end > line_index 时有效。 */
|
||||
join_with?: 'newline' | 'space' | 'comma' | null;
|
||||
value?: string | null;
|
||||
separators?: string[];
|
||||
case_sensitive?: boolean;
|
||||
@@ -927,6 +942,20 @@ export interface OrderProfileTestSuite {
|
||||
evidence_retention_rate?: number;
|
||||
key_field_accuracy_rate?: number;
|
||||
} | null;
|
||||
/** OCR↔datasets / XFA 视觉指标 soft 诊断;含两侧截断值或 rate,便于标明差异。 */
|
||||
soft_diagnostics?: Array<{
|
||||
sample_id: number;
|
||||
code: string;
|
||||
mismatch_count: number;
|
||||
rate?: number;
|
||||
fields: Array<{
|
||||
scope: string;
|
||||
field_code: string;
|
||||
row_index?: number | null;
|
||||
ocr_value?: string;
|
||||
datasets_value?: string;
|
||||
}>;
|
||||
}>;
|
||||
} | null;
|
||||
}
|
||||
|
||||
@@ -962,6 +991,19 @@ export interface OrderProfileBlindTestCandidate {
|
||||
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[];
|
||||
/** XFA:OCR 与 datasets 同名字段对照;mismatched 仅为诊断,不否决复核。 */
|
||||
ocr_datasets_cross_check?: {
|
||||
status: 'matched' | 'mismatched' | 'unavailable';
|
||||
compared_field_count?: number;
|
||||
mismatch_count?: number;
|
||||
mismatches?: Array<{
|
||||
scope?: string;
|
||||
field_code?: string;
|
||||
row_index?: number | null;
|
||||
ocr_value?: string;
|
||||
datasets_value?: string;
|
||||
}>;
|
||||
};
|
||||
}
|
||||
|
||||
/** 工作台的本地几何状态;保存前转为 v2 相对区域定义。 */
|
||||
|
||||
@@ -3108,6 +3108,8 @@
|
||||
"semanticDiffReview": "This version has semantic changes. Confirm that you reviewed them.",
|
||||
"unknownIssue": "The publish check found an issue that needs attention.",
|
||||
"xfaFieldMappingsRequired": "Final value mappings are incomplete.",
|
||||
"xfaRequiredPathCoverageIncomplete": "Required or auto-create-key Schema fields are missing XFA path mappings: {fields}",
|
||||
"xfaRequiredPathFieldsUnknown": "(no field details returned)",
|
||||
"xfaVisualCoverageInsufficient": "Visual binding coverage is below 100%.",
|
||||
"xfaEvidenceRetentionInsufficient": "evidence_only retention is below 100%.",
|
||||
"xfaMirrorConsistencyInsufficient": "Mirror formal-field consistency is below 100%.",
|
||||
@@ -3712,8 +3714,28 @@
|
||||
"coordinateEvidenceMissing": "{sample}: table or page coordinate evidence is missing, so the blind test cannot run.",
|
||||
"xfaEvidenceMissing": "{sample}: usable XFA structure-analysis evidence is missing, so the blind test cannot run.",
|
||||
"rowsMismatch": "{sample}: reread order lines differ from the human truth.",
|
||||
"extractionFailed": "{sample}: formal extraction failed ({reason}).",
|
||||
"ocrDatasetsMismatchLegacy": "{sample}: a legacy gate treated OCR↔datasets mismatch as a hard failure; datasets is now authoritative—rerun. See diagnostics below for fields.",
|
||||
"visualMetricLegacy": "{sample}: a legacy gate treated {metric} as a hard failure; XFA now judges by datasets truth—rerun. See metrics and soft diagnostics.",
|
||||
"unknown": "{sample}: the blind test did not pass; check the raw diagnostic code below."
|
||||
},
|
||||
"softDiagnostic": {
|
||||
"title": "Cross-check diagnostics (non-blocking)",
|
||||
"hint": "For XFA, datasets is the formal value source; OCR/visual metrics are side-by-side only. Differences below do not block a datasets-based blind-test pass.",
|
||||
"ocrDatasetsMismatch": "{sample}: OCR vs datasets mismatched fields ({count}): {fields}",
|
||||
"ocrDatasetsFieldDiff": "{sample} · {field}: OCR \"{ocr}\" ≠ datasets \"{datasets}\"",
|
||||
"ocrDatasetsFieldDiffInline": "{field}: OCR \"{ocr}\" ≠ datasets \"{datasets}\"",
|
||||
"previewOcrMismatch": "OCR vs datasets mismatch ({count}): {fields}. Formal values still follow datasets; you may continue review.",
|
||||
"previewOcrMismatchIntro": "OCR vs datasets mismatch ({count}). Formal values still follow datasets; continue review:",
|
||||
"visualMetricSoft": "{sample}: {metric} is {rate} (diagnostic only, non-blocking)",
|
||||
"metric": {
|
||||
"visual_coverage_soft": "visual positioning coverage",
|
||||
"mirror_consistency_soft": "mirror consistency",
|
||||
"evidence_retention_soft": "evidence_only retention"
|
||||
},
|
||||
"fieldsUnknown": "(no field codes returned)",
|
||||
"emptyValue": "(empty)"
|
||||
},
|
||||
"run": "Run",
|
||||
"approve": "Approve"
|
||||
},
|
||||
@@ -3737,6 +3759,7 @@
|
||||
"headerTrainingSample": "Training sample bound",
|
||||
"headerAddTrainingSample": "Bind sample",
|
||||
"headerSaveDraft": "Save",
|
||||
"noUnsavedChanges": "No unsaved changes",
|
||||
"headerValidate": "Validate",
|
||||
"headerReturnToLibrary": "Templates",
|
||||
"invalidDefinitionPath": "Template configuration is invalid: {path}",
|
||||
@@ -3751,6 +3774,7 @@
|
||||
"xfaVisualReadbackUnavailable": "XFA visual readback failed; the value box was kept. Continue binding the datasets field.",
|
||||
"orderFieldValueReading": "Reading",
|
||||
"orderFieldValueFailed": "Read failed",
|
||||
"orderFieldDuplicatePreview": "Order field {fields} is bound more than once; remove the extra box before reading sample values",
|
||||
"currentSampleValue": "Current sample value",
|
||||
"visualEvidenceSource": "Visual evidence: {source}",
|
||||
"visualEvidenceSources": {
|
||||
@@ -4187,7 +4211,9 @@
|
||||
"datasourceField": "Data source field",
|
||||
"splitRuleField": "Split rules",
|
||||
"datasetsPath": "Datasets path",
|
||||
"pickDatasetsPath": "Pick datasets path",
|
||||
"pickDatasetsPath": "Choose data source",
|
||||
"pickDatasetsPathTitle": "Choose data source field",
|
||||
"pickDatasetsPathHint": "Select a leaf path or split rule to bind the current field. Sample values are shown in full for mapping.",
|
||||
"datasetsSampleValue": "Datasets sample value",
|
||||
"lineInheritsHeaderHint": "This is a line field: the selected Header value will be inherited by every line.",
|
||||
"previewStatusTitle": "Preview & OCR status",
|
||||
@@ -4363,6 +4389,9 @@
|
||||
"validationRequired": "Required",
|
||||
"validationSegmentCode": "Must be lowercase snake_case starting with a letter",
|
||||
"validationMappedTarget": "Mapped handling requires a target field",
|
||||
"ruleAlreadyMapped": "This rule is already mapped to another Schema field; change the target in the split editor or unbind first",
|
||||
"applyNeedsSelectedField": "Select a Schema field on the canvas first, then click a split rule",
|
||||
"splitVisualReuseHint": "Multiple fields from one source share one visual box; map targets in split rules instead of drawing duplicate boxes",
|
||||
"validationPrefixValue": "Prefix label is required",
|
||||
"validationPrefixSeparators": "At least one separator is required",
|
||||
"validationRegexPattern": "Regex pattern is required",
|
||||
|
||||
@@ -221,7 +221,7 @@
|
||||
"candidate_confirmation": "Order candidates are ready — confirm each one",
|
||||
"technical_failure": "Some attachments failed — retry or view details",
|
||||
"auto_freeze_blocked": "Auto-freeze did not pass the gate — review the reasons",
|
||||
"budget_stopped": "Initial parsing budget is exhausted — check remaining attachments"
|
||||
"budget_stopped": "Initial parsing budget is exhausted — remaining attachments will continue automatically"
|
||||
},
|
||||
"reason": {
|
||||
"profile_not_auto_freeze_approved": "Profile is not approved for auto-freeze",
|
||||
@@ -306,7 +306,7 @@
|
||||
"review_required": "This PDF requires manual review.",
|
||||
"technical_retrying": "Retrying the failed attachment.",
|
||||
"technical_failed": "The system could not finish this attachment.",
|
||||
"budget_stopped": "The current attachment budget has been reached. Remaining attachments require manual review.",
|
||||
"budget_stopped": "The current attachment budget has been reached. Remaining attachments will continue automatically.",
|
||||
"run_completed": "This order parsing run is complete.",
|
||||
"generic_processing": "The system is processing the order attachment.",
|
||||
"cancellation_requested": "Cancellation requested; stopping at a safe point.",
|
||||
|
||||
@@ -48,6 +48,9 @@
|
||||
"SHIPPING_ORDER_SCHEMA_NOT_PUBLISHED": "No usable order field version has been published.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_NOT_FOUND": "The order document parsing profile was not found.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_INVALID": "The order document parsing profile is invalid.",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID": "The order document parsing profile is invalid.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_INVALID": "Blind-test configuration is invalid. Check the profile status and field boxes, then retry.",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID": "Blind-test configuration is invalid. Check the profile status and field boxes, then retry.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "The profile must bind to a published or retired order schema version.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "The profile references an unavailable order line field.",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID": "A Reservation ID evidence region requires a header Reservation ID field. A line Reservation ID field is optional and receives numbered overrides.",
|
||||
|
||||
@@ -2974,6 +2974,8 @@
|
||||
"semanticDiffReview": "รุ่นนี้มีความแตกต่างเชิงความหมาย โปรดยืนยันว่าได้ตรวจสอบแล้ว",
|
||||
"unknownIssue": "การตรวจสอบก่อนเผยแพร่พบปัญหาที่ต้องจัดการ",
|
||||
"xfaFieldMappingsRequired": "การแมปค่าฟิลด์ขั้นสุดท้ายยังไม่สมบูรณ์",
|
||||
"xfaRequiredPathCoverageIncomplete": "ฟิลด์ Schema ที่จำเป็นหรือเป็นคีย์สร้างอัตโนมัติยังไม่มี XFA path: {fields}",
|
||||
"xfaRequiredPathFieldsUnknown": "(ไม่มีรายละเอียดฟิลด์)",
|
||||
"xfaVisualCoverageInsufficient": "อัตราครอบคลุมการผูกภาพยังไม่ถึง 100%",
|
||||
"xfaEvidenceRetentionInsufficient": "อัตราการเก็บ evidence_only ยังไม่ถึง 100%",
|
||||
"xfaMirrorConsistencyInsufficient": "อัตราความสอดคล้องของฟิลด์ทางการในชุดกระจกยังไม่ถึง 100%",
|
||||
@@ -3578,8 +3580,28 @@
|
||||
"coordinateEvidenceMissing": "{sample}: ไม่มีหลักฐานพิกัดของตารางหรือหน้า จึงดำเนินการทดสอบไม่ได้",
|
||||
"xfaEvidenceMissing": "{sample}: ไม่มีหลักฐานการวิเคราะห์โครงสร้าง XFA ที่ใช้ได้ จึงดำเนินการทดสอบไม่ได้",
|
||||
"rowsMismatch": "{sample}: รายการคำสั่งซื้อที่อ่านใหม่ไม่ตรงกับข้อมูลจริงที่ยืนยันโดยคน",
|
||||
"extractionFailed": "{sample}: การสกัดอย่างเป็นทางการไม่ผ่าน ({reason})",
|
||||
"ocrDatasetsMismatchLegacy": "{sample}: เกตเวย์เดิมเคยถือว่า OCR↔datasets ไม่ตรงกันเป็นการล้มเหลวแบบแข็ง ขณะนี้ยึด datasets เป็นหลัก — โปรดรันใหม่ ดูฟิลด์ที่ต่างกันด้านล่าง",
|
||||
"visualMetricLegacy": "{sample}: เกตเวย์เดิมเคยถือว่า {metric} เป็นการล้มเหลวแบบแข็ง — XFA ขณะนี้ยึดค่าจริงจาก datasets โปรดรันใหม่ ดูตัวชี้วัดและการวินิจฉัยด้านล่าง",
|
||||
"unknown": "{sample}: การทดสอบแบบปิดบังไม่ผ่าน โปรดตรวจรหัสวินิจฉัยด้านล่าง"
|
||||
},
|
||||
"softDiagnostic": {
|
||||
"title": "การวินิจฉัยเปรียบเทียบ (ไม่บล็อก)",
|
||||
"hint": "สำหรับ XFA ค่าทางการมาจาก datasets; OCR/ตัวชี้วัดภาพใช้เพื่อเทียบเคียงเท่านั้น ความต่างด้านล่างไม่บล็อกการผ่านด้วย datasets",
|
||||
"ocrDatasetsMismatch": "{sample}: ฟิลด์ที่ OCR กับ datasets ไม่ตรงกัน ({count}): {fields}",
|
||||
"ocrDatasetsFieldDiff": "{sample} · {field}: OCR \"{ocr}\" ≠ datasets \"{datasets}\"",
|
||||
"ocrDatasetsFieldDiffInline": "{field}: OCR \"{ocr}\" ≠ datasets \"{datasets}\"",
|
||||
"previewOcrMismatch": "OCR กับ datasets ไม่ตรงกัน ({count}): {fields} ค่ายังยึด datasets เป็นหลัก สามารถตรวจทานต่อได้",
|
||||
"previewOcrMismatchIntro": "OCR กับ datasets ไม่ตรงกัน ({count} รายการ) ค่ายังยึด datasets เป็นหลัก ตรวจทานต่อได้:",
|
||||
"visualMetricSoft": "{sample}: {metric} อยู่ที่ {rate} (วินิจฉัยเท่านั้น ไม่บล็อก)",
|
||||
"metric": {
|
||||
"visual_coverage_soft": "อัตราครอบคลุมตำแหน่งภาพ",
|
||||
"mirror_consistency_soft": "อัตราความสอดคล้องกระจก",
|
||||
"evidence_retention_soft": "อัตราคงหลักฐาน evidence_only"
|
||||
},
|
||||
"fieldsUnknown": "(ไม่มีรหัสฟิลด์)",
|
||||
"emptyValue": "(ว่าง)"
|
||||
},
|
||||
"run": "ดำเนินการ",
|
||||
"approve": "อนุมัติ"
|
||||
},
|
||||
@@ -3603,6 +3625,7 @@
|
||||
"headerTrainingSample": "ผูกตัวอย่างฝึกแล้ว",
|
||||
"headerAddTrainingSample": "ผูกตัวอย่าง",
|
||||
"headerSaveDraft": "บันทึก",
|
||||
"noUnsavedChanges": "ไม่มีการเปลี่ยนแปลงที่ยังไม่ได้บันทึก",
|
||||
"headerValidate": "ตรวจสอบ",
|
||||
"headerReturnToLibrary": "เทมเพลต",
|
||||
"invalidDefinitionPath": "การตั้งค่าเทมเพลตไม่ถูกต้อง: {path}",
|
||||
@@ -3617,6 +3640,7 @@
|
||||
"xfaVisualReadbackUnavailable": "การอ่านกลับภาพ XFA ล้มเหลว แต่เก็บกรอบค่าไว้แล้ว โปรดผูกฟิลด์ datasets ต่อ",
|
||||
"orderFieldValueReading": "กำลังอ่าน",
|
||||
"orderFieldValueFailed": "อ่านไม่สำเร็จ",
|
||||
"orderFieldDuplicatePreview": "ฟิลด์คำสั่งซื้อ {fields} ผูกซ้ำ กรุณาลบกรอบส่วนเกินก่อนอ่านค่าตัวอย่าง",
|
||||
"currentSampleValue": "ค่าจากตัวอย่างปัจจุบัน",
|
||||
"visualEvidenceSource": "หลักฐานภาพ: {source}",
|
||||
"visualEvidenceSources": {
|
||||
@@ -4053,7 +4077,9 @@
|
||||
"datasourceField": "ฟิลด์แหล่งข้อมูล",
|
||||
"splitRuleField": "กฎการแยก",
|
||||
"datasetsPath": "พาธ Datasets",
|
||||
"pickDatasetsPath": "เลือกพาธ datasets",
|
||||
"pickDatasetsPath": "เลือกแหล่งข้อมูล",
|
||||
"pickDatasetsPathTitle": "เลือกฟิลด์แหล่งข้อมูล",
|
||||
"pickDatasetsPathHint": "เลือกพาธใบหรือกฎการแยกเพื่อผูกฟิลด์ปัจจุบัน ค่าตัวอย่างแสดงแบบเต็มเพื่อช่วยแมป",
|
||||
"datasetsSampleValue": "ค่าตัวอย่าง Datasets",
|
||||
"lineInheritsHeaderHint": "นี่คือฟิลด์รายการ: ค่า Header ที่เลือกจะถูกสืบทอดไปยังทุกรายการ.",
|
||||
"previewStatusTitle": "สถานะตัวอย่างและ OCR",
|
||||
@@ -4229,6 +4255,9 @@
|
||||
"validationRequired": "จำเป็น",
|
||||
"validationSegmentCode": "ต้องเป็น snake_case ตัวพิมพ์เล็ก ขึ้นต้นด้วยตัวอักษร",
|
||||
"validationMappedTarget": "การแมปต้องเลือกฟิลด์เป้าหมาย",
|
||||
"ruleAlreadyMapped": "กฎนี้ถูกแมปกับฟิลด์ Schema อื่นแล้ว โปรดเปลี่ยนเป้าหมายในตัวแก้ไขการแยกหรือยกเลิกการผูกก่อน",
|
||||
"applyNeedsSelectedField": "โปรดเลือกฟิลด์ Schema บนแคนวาสก่อน แล้วจึงคลิกกฎการแยก",
|
||||
"splitVisualReuseHint": "หลายฟิลด์จากแหล่งข้อมูลเดียวกันใช้กรอบภาพเดียวกัน กำหนดเป้าหมายในกฎการแยกแทนการวาดกรอบซ้ำ",
|
||||
"validationPrefixValue": "ป้ายคำนำหน้าต้องไม่ว่าง",
|
||||
"validationPrefixSeparators": "ต้องมีตัวคั่นอย่างน้อยหนึ่งตัว",
|
||||
"validationRegexPattern": "นิพจน์ regex ต้องไม่ว่าง",
|
||||
|
||||
@@ -221,7 +221,7 @@
|
||||
"candidate_confirmation": "สร้างรายการคำสั่งซื้อแล้ว — ยืนยันทีละรายการ",
|
||||
"technical_failure": "บางไฟล์แนบล้มเหลว — ลองใหม่หรือดูรายละเอียด",
|
||||
"auto_freeze_blocked": "การแช่แข็งอัตโนมัติไม่ผ่านเงื่อนไข — ดูสาเหตุ",
|
||||
"budget_stopped": "งบแยกวิเคราะห์รอบแรกหมดแล้ว — ตรวจไฟล์ที่ยังไม่ประมวลผล"
|
||||
"budget_stopped": "งบแยกวิเคราะห์รอบแรกหมดแล้ว — ไฟล์ที่เหลือจะถูกแยกวิเคราะห์ต่อโดยอัตโนมัติ"
|
||||
},
|
||||
"reason": {
|
||||
"profile_not_auto_freeze_approved": "เทมเพลตยังไม่ผ่านคุณสมบัติแช่แข็งอัตโนมัติ",
|
||||
@@ -306,7 +306,7 @@
|
||||
"review_required": "PDF นี้ต้องตรวจสอบด้วยตนเอง",
|
||||
"technical_retrying": "ระบบกำลังลองประมวลผลไฟล์แนบที่ล้มเหลวอีกครั้ง",
|
||||
"technical_failed": "ระบบไม่สามารถประมวลผลไฟล์แนบนี้ได้",
|
||||
"budget_stopped": "ถึงงบประมาณไฟล์แนบของรอบนี้แล้ว ไฟล์ที่เหลือต้องตรวจสอบด้วยตนเอง",
|
||||
"budget_stopped": "ถึงงบประมาณไฟล์แนบของรอบนี้แล้ว ไฟล์ที่เหลือจะถูกแยกวิเคราะห์ต่อโดยอัตโนมัติ",
|
||||
"run_completed": "การแยกวิเคราะห์คำสั่งซื้อรอบนี้เสร็จแล้ว",
|
||||
"generic_processing": "ระบบกำลังประมวลผลไฟล์แนบคำสั่งซื้อ",
|
||||
"cancellation_requested": "ได้รับคำขอยกเลิกแล้ว กำลังหยุดอย่างปลอดภัย",
|
||||
|
||||
@@ -48,6 +48,9 @@
|
||||
"SHIPPING_ORDER_SCHEMA_NOT_PUBLISHED": "ยังไม่มีเวอร์ชันฟิลด์คำสั่งซื้อที่เผยแพร่และใช้งานได้",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_NOT_FOUND": "ไม่พบโปรไฟล์การแยกข้อมูลเอกสารคำสั่งซื้อ",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_INVALID": "การตั้งค่าโปรไฟล์การแยกข้อมูลเอกสารคำสั่งซื้อไม่ถูกต้อง",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID": "การตั้งค่าโปรไฟล์การแยกข้อมูลเอกสารคำสั่งซื้อไม่ถูกต้อง",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_INVALID": "การตั้งค่าการทดสอบแบบปิดบังไม่ถูกต้อง โปรดตรวจสอบสถานะเทมเพลตและกล่องฟิลด์แล้วลองใหม่",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID": "การตั้งค่าการทดสอบแบบปิดบังไม่ถูกต้อง โปรดตรวจสอบสถานะเทมเพลตและกล่องฟิลด์แล้วลองใหม่",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "โปรไฟล์ต้องผูกกับเวอร์ชันสคีมาคำสั่งซื้อที่เผยแพร่หรือเลิกใช้งานแล้ว",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "โปรไฟล์อ้างอิงฟิลด์รายการคำสั่งซื้อที่ไม่พร้อมใช้งาน",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID": "เมื่อใช้พื้นที่หลักฐาน Reservation ID Schema ต้องเปิดใช้ Reservation ID ระดับหัวเอกสาร ส่วนระดับรายการเป็นตัวเลือกสำหรับค่าที่ระบุหมายเลขบรรทัด",
|
||||
|
||||
@@ -3220,6 +3220,8 @@
|
||||
"semanticDiffReview": "此版本包含语义差异,请确认已审核。",
|
||||
"unknownIssue": "发布检查发现需要处理的问题。",
|
||||
"xfaFieldMappingsRequired": "末端字段映射未完成,无法发布。",
|
||||
"xfaRequiredPathCoverageIncomplete": "必填或建单键 Schema 字段缺少 XFA path 映射:{fields}",
|
||||
"xfaRequiredPathFieldsUnknown": "(未返回字段明细)",
|
||||
"xfaVisualCoverageInsufficient": "视觉绑定覆盖率未达 100%。",
|
||||
"xfaEvidenceRetentionInsufficient": "evidence_only 保留率未达 100%。",
|
||||
"xfaMirrorConsistencyInsufficient": "镜像正式字段一致率未达 100%。",
|
||||
@@ -3824,8 +3826,28 @@
|
||||
"coordinateEvidenceMissing": "{sample}:缺少表格或页面坐标证据,无法完成盲测。",
|
||||
"xfaEvidenceMissing": "{sample}:缺少可用的 XFA 结构分析证据,无法完成盲测。",
|
||||
"rowsMismatch": "{sample}:重新解析的订单明细与人工真值不一致。",
|
||||
"extractionFailed": "{sample}:正式抽取未通过({reason})。",
|
||||
"ocrDatasetsMismatchLegacy": "{sample}:历史门禁曾将 OCR↔datasets 对照记为硬失败;现以 datasets 为准,请重新执行。对照字段见下方诊断。",
|
||||
"visualMetricLegacy": "{sample}:历史门禁曾将 {metric} 记为硬失败;XFA 现以 datasets 真值为准,请重新执行。指标见上方与下方诊断。",
|
||||
"unknown": "{sample}:盲测执行未通过,请检查下方原始诊断码。"
|
||||
},
|
||||
"softDiagnostic": {
|
||||
"title": "对照诊断(不阻断)",
|
||||
"hint": "XFA 正式值以 datasets 为准;OCR/视觉定位仅用于旁路对照与展示。下列差异不影响以 datasets 为准的盲测通过。",
|
||||
"ocrDatasetsMismatch": "{sample}:OCR 与 datasets 未对齐字段({count}):{fields}",
|
||||
"ocrDatasetsFieldDiff": "{sample} · {field}:OCR「{ocr}」≠ datasets「{datasets}」",
|
||||
"ocrDatasetsFieldDiffInline": "{field}:OCR「{ocr}」≠ datasets「{datasets}」",
|
||||
"previewOcrMismatch": "OCR 与 datasets 未对齐({count}):{fields}。正式值仍以 datasets 为准,可继续复核。",
|
||||
"previewOcrMismatchIntro": "OCR 与 datasets 未对齐({count} 项)。正式值仍以 datasets 为准,可继续复核:",
|
||||
"visualMetricSoft": "{sample}:{metric} 为 {rate}(仅诊断,不阻断)",
|
||||
"metric": {
|
||||
"visual_coverage_soft": "视觉定位覆盖率",
|
||||
"mirror_consistency_soft": "镜像一致率",
|
||||
"evidence_retention_soft": "evidence_only 保留率"
|
||||
},
|
||||
"fieldsUnknown": "(未返回字段码)",
|
||||
"emptyValue": "(空)"
|
||||
},
|
||||
"run": "执行",
|
||||
"approve": "批准"
|
||||
},
|
||||
@@ -3849,6 +3871,7 @@
|
||||
"headerTrainingSample": "训练样本已绑定",
|
||||
"headerAddTrainingSample": "绑定样本",
|
||||
"headerSaveDraft": "保存",
|
||||
"noUnsavedChanges": "没有未保存的更改",
|
||||
"headerValidate": "验证",
|
||||
"headerReturnToLibrary": "返回模板",
|
||||
"invalidDefinitionPath": "模板配置无效:{path}",
|
||||
@@ -3863,6 +3886,7 @@
|
||||
"xfaVisualReadbackUnavailable": "XFA 视觉回读失败,已保留值框;请继续绑定 datasets 字段",
|
||||
"orderFieldValueReading": "读取中",
|
||||
"orderFieldValueFailed": "读取失败",
|
||||
"orderFieldDuplicatePreview": "订单字段 {fields} 重复绑定,请先删除多余画框后再读取样本值",
|
||||
"currentSampleValue": "当前样本值",
|
||||
"visualEvidenceSource": "视觉证据:{source}",
|
||||
"visualEvidenceSources": {
|
||||
@@ -4299,7 +4323,9 @@
|
||||
"datasourceField": "数据源字段",
|
||||
"splitRuleField": "拆分规则",
|
||||
"datasetsPath": "Datasets 路径",
|
||||
"pickDatasetsPath": "选择 datasets 路径",
|
||||
"pickDatasetsPath": "选择数据源",
|
||||
"pickDatasetsPathTitle": "选择数据源字段",
|
||||
"pickDatasetsPathHint": "点选叶子路径或拆分规则以绑定当前字段;样本值按完整可读展示。",
|
||||
"datasetsSampleValue": "Datasets 样本值",
|
||||
"lineInheritsHeaderHint": "当前为明细字段:所选 Header 值会继承到每条明细行。",
|
||||
"previewStatusTitle": "预览与 OCR 状态",
|
||||
@@ -4476,6 +4502,9 @@
|
||||
"validationRequired": "必填",
|
||||
"validationSegmentCode": "须为小写蛇形编码(字母开头)",
|
||||
"validationMappedTarget": "映射模式须选择目标字段",
|
||||
"ruleAlreadyMapped": "该规则已映射到其它 Schema 字段,请先在拆分弹窗修改目标或解绑后再绑定",
|
||||
"applyNeedsSelectedField": "请先在画布选中要绑定的 Schema 字段,再点选拆分规则",
|
||||
"splitVisualReuseHint": "同一数据源拆出的多个字段共用一个视觉框;请用拆分规则目标字段区分,不要重复画框",
|
||||
"validationPrefixValue": "前缀标签不能为空",
|
||||
"validationPrefixSeparators": "须至少一个分隔符",
|
||||
"validationRegexPattern": "正则表达式不能为空",
|
||||
|
||||
@@ -221,7 +221,7 @@
|
||||
"candidate_confirmation": "订单候选已生成,请逐份人工确认",
|
||||
"technical_failure": "部分附件处理失败,可重试或查看详情",
|
||||
"auto_freeze_blocked": "自动冻结未通过门禁,请查看原因并处理",
|
||||
"budget_stopped": "首轮识别预算已用尽,请查看未处理附件"
|
||||
"budget_stopped": "首轮识别预算已用尽,剩余附件将自动继续识别"
|
||||
},
|
||||
"reason": {
|
||||
"profile_not_auto_freeze_approved": "模板未通过自动冻结资格审批",
|
||||
@@ -340,7 +340,7 @@
|
||||
"review_required": "该 PDF 需要人工复核。",
|
||||
"technical_retrying": "系统正在重试失败的附件。",
|
||||
"technical_failed": "系统未能完成该附件处理。",
|
||||
"budget_stopped": "已达到当前附件预算,剩余附件等待人工复核。",
|
||||
"budget_stopped": "已达到当前附件预算,剩余附件将自动继续识别。",
|
||||
"run_completed": "本次订单解析已完成。",
|
||||
"cancellation_requested": "已收到取消请求,正在安全停止。",
|
||||
"cancellation_completed": "取消已完成。",
|
||||
|
||||
@@ -48,6 +48,9 @@
|
||||
"SHIPPING_ORDER_SCHEMA_NOT_PUBLISHED": "尚未发布可用的订单字段版本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_NOT_FOUND": "未找到订单文档解析模板。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_INVALID": "订单文档解析模板配置无效。",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID": "订单文档解析模板配置无效。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_INVALID": "盲测配置无效,请检查模板状态与字段框后重试。",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID": "盲测配置无效,请检查模板状态与字段框后重试。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "订单文档解析模板必须绑定已发布或已退役的订单字段版本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "订单文档解析模板引用了不可用的订单明细字段。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID": "使用 Reservation ID 证据区域时,订单字段版本必须启用订单头 Reservation ID;明细 Reservation ID 可选,用于带行号的覆盖值。",
|
||||
|
||||
@@ -2979,6 +2979,8 @@
|
||||
"semanticDiffReview": "此版本包含語義差異,請確認已審核。",
|
||||
"unknownIssue": "發布檢查發現需要處理的問題。",
|
||||
"xfaFieldMappingsRequired": "末端欄位映射尚未完成,無法發佈。",
|
||||
"xfaRequiredPathCoverageIncomplete": "必填或建單鍵 Schema 欄位缺少 XFA path 映射:{fields}",
|
||||
"xfaRequiredPathFieldsUnknown": "(未回傳欄位明細)",
|
||||
"xfaVisualCoverageInsufficient": "視覺綁定覆蓋率未達 100%。",
|
||||
"xfaEvidenceRetentionInsufficient": "evidence_only 保留率未達 100%。",
|
||||
"xfaMirrorConsistencyInsufficient": "鏡像正式欄位一致率未達 100%。",
|
||||
@@ -3583,8 +3585,28 @@
|
||||
"coordinateEvidenceMissing": "{sample}:缺少表格或頁面座標證據,無法完成盲測。",
|
||||
"xfaEvidenceMissing": "{sample}:缺少可用的 XFA 結構分析證據,無法完成盲測。",
|
||||
"rowsMismatch": "{sample}:重新解析的訂單明細與人工真值不一致。",
|
||||
"extractionFailed": "{sample}:正式抽取未通過({reason})。",
|
||||
"ocrDatasetsMismatchLegacy": "{sample}:歷史門禁曾將 OCR↔datasets 對照記為硬失敗;現以 datasets 為準,請重新執行。對照欄位見下方診斷。",
|
||||
"visualMetricLegacy": "{sample}:歷史門禁曾將 {metric} 記為硬失敗;XFA 現以 datasets 真值為準,請重新執行。指標見上方與下方診斷。",
|
||||
"unknown": "{sample}:盲測執行未通過,請檢查下方原始診斷碼。"
|
||||
},
|
||||
"softDiagnostic": {
|
||||
"title": "對照診斷(不阻斷)",
|
||||
"hint": "XFA 正式值以 datasets 為準;OCR/視覺定位僅用於旁路對照與展示。下列差異不影響以 datasets 為準的盲測通過。",
|
||||
"ocrDatasetsMismatch": "{sample}:OCR 與 datasets 未對齊欄位({count}):{fields}",
|
||||
"ocrDatasetsFieldDiff": "{sample} · {field}:OCR「{ocr}」≠ datasets「{datasets}」",
|
||||
"ocrDatasetsFieldDiffInline": "{field}:OCR「{ocr}」≠ datasets「{datasets}」",
|
||||
"previewOcrMismatch": "OCR 與 datasets 未對齊({count}):{fields}。正式值仍以 datasets 為準,可繼續複核。",
|
||||
"previewOcrMismatchIntro": "OCR 與 datasets 未對齊({count} 項)。正式值仍以 datasets 為準,可繼續複核:",
|
||||
"visualMetricSoft": "{sample}:{metric} 為 {rate}(僅診斷,不阻斷)",
|
||||
"metric": {
|
||||
"visual_coverage_soft": "視覺定位覆蓋率",
|
||||
"mirror_consistency_soft": "鏡像一致率",
|
||||
"evidence_retention_soft": "evidence_only 保留率"
|
||||
},
|
||||
"fieldsUnknown": "(未回傳欄位碼)",
|
||||
"emptyValue": "(空)"
|
||||
},
|
||||
"run": "執行",
|
||||
"approve": "批准"
|
||||
},
|
||||
@@ -3608,6 +3630,7 @@
|
||||
"headerTrainingSample": "訓練樣本已綁定",
|
||||
"headerAddTrainingSample": "綁定樣本",
|
||||
"headerSaveDraft": "儲存",
|
||||
"noUnsavedChanges": "沒有未儲存的變更",
|
||||
"headerValidate": "驗證",
|
||||
"headerReturnToLibrary": "返回範本",
|
||||
"invalidDefinitionPath": "模板設定無效:{path}",
|
||||
@@ -3622,6 +3645,7 @@
|
||||
"xfaVisualReadbackUnavailable": "XFA 視覺回讀失敗,已保留值框;請繼續綁定 datasets 欄位",
|
||||
"orderFieldValueReading": "讀取中",
|
||||
"orderFieldValueFailed": "讀取失敗",
|
||||
"orderFieldDuplicatePreview": "訂單欄位 {fields} 重複綁定,請先刪除多餘畫框後再讀取樣本值",
|
||||
"currentSampleValue": "目前樣本值",
|
||||
"visualEvidenceSource": "視覺證據:{source}",
|
||||
"visualEvidenceSources": {
|
||||
@@ -4058,7 +4082,9 @@
|
||||
"datasourceField": "資料來源欄位",
|
||||
"splitRuleField": "拆分規則",
|
||||
"datasetsPath": "Datasets 路徑",
|
||||
"pickDatasetsPath": "選擇 datasets 路徑",
|
||||
"pickDatasetsPath": "選擇資料來源",
|
||||
"pickDatasetsPathTitle": "選擇資料來源欄位",
|
||||
"pickDatasetsPathHint": "點選葉子路徑或拆分規則以綁定目前欄位;樣本值以完整可讀展示。",
|
||||
"datasetsSampleValue": "Datasets 樣本值",
|
||||
"lineInheritsHeaderHint": "目前為明細欄位:所選 Header 值會繼承至每一筆明細行。",
|
||||
"previewStatusTitle": "預覽與 OCR 狀態",
|
||||
@@ -4234,6 +4260,9 @@
|
||||
"validationRequired": "必填",
|
||||
"validationSegmentCode": "須為小寫蛇形編碼(字母開頭)",
|
||||
"validationMappedTarget": "對應模式須選擇目標欄位",
|
||||
"ruleAlreadyMapped": "該規則已對應到其它 Schema 欄位,請先在拆分彈窗修改目標或解除綁定後再綁定",
|
||||
"applyNeedsSelectedField": "請先在畫布選中要綁定的 Schema 欄位,再點選拆分規則",
|
||||
"splitVisualReuseHint": "同一資料源拆出的多個欄位共用一個視覺框;請用拆分規則目標欄位區分,不要重複畫框",
|
||||
"validationPrefixValue": "前綴標籤不能為空",
|
||||
"validationPrefixSeparators": "須至少一個分隔符",
|
||||
"validationRegexPattern": "正則表達式不能為空",
|
||||
|
||||
@@ -221,7 +221,7 @@
|
||||
"candidate_confirmation": "訂單候選已生成,請逐份人工確認",
|
||||
"technical_failure": "部分附件處理失敗,可重試或查看詳情",
|
||||
"auto_freeze_blocked": "自動凍結未通過門禁,請查看原因並處理",
|
||||
"budget_stopped": "首輪識別預算已用盡,請查看未處理附件"
|
||||
"budget_stopped": "首輪識別預算已用盡,剩餘附件將自動繼續識別"
|
||||
},
|
||||
"reason": {
|
||||
"profile_not_auto_freeze_approved": "模板未通過自動凍結資格審批",
|
||||
@@ -306,7 +306,7 @@
|
||||
"review_required": "該 PDF 需要人工覆核。",
|
||||
"technical_retrying": "系統正在重試失敗附件。",
|
||||
"technical_failed": "系統未能完成該附件處理。",
|
||||
"budget_stopped": "已達目前附件預算,剩餘附件等待人工覆核。",
|
||||
"budget_stopped": "已達目前附件預算,剩餘附件將自動繼續識別。",
|
||||
"run_completed": "本次訂單解析已完成。",
|
||||
"generic_processing": "系統正在處理訂單附件。",
|
||||
"cancellation_requested": "已收到取消請求,正在安全停止。",
|
||||
|
||||
@@ -48,6 +48,9 @@
|
||||
"SHIPPING_ORDER_SCHEMA_NOT_PUBLISHED": "尚未發布可用的訂單欄位版本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_NOT_FOUND": "找不到訂單文件解析範本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_INVALID": "訂單文件解析範本設定無效。",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_INVALID": "訂單文件解析範本設定無效。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_TEST_INVALID": "盲測設定無效,請檢查範本狀態與欄位框後重試。",
|
||||
"SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_INVALID": "盲測設定無效,請檢查範本狀態與欄位框後重試。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_SCHEMA_INVALID": "訂單文件解析範本必須綁定已發布或已退役的訂單欄位版本。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_FIELD_INVALID": "訂單文件解析範本引用了不可用的訂單明細欄位。",
|
||||
"SHIPPING_ORDER_DOCUMENT_PROFILE_RESERVATION_SCHEMA_INVALID": "使用 Reservation ID 證據區域時,訂單欄位版本必須啟用訂單頭 Reservation ID;明細 Reservation ID 為選填,用於有行號的覆蓋值。",
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
<#
|
||||
scripts/start_local_integrated.ps1
|
||||
用途:在同一 IDE 终端内用 Start-Job 托管 backend / frontend / workers。
|
||||
依赖:backend\.venv、frontend npm、.env.shared / .env.dev / .env.local。
|
||||
逻辑:清理旧进程与端口 → 可选迁移 → Start-Job 拉起各服务。
|
||||
-NoHotReload:Start-Job 下不能用 WERKZEUG_RUN_MAIN(会 KeyError: WERKZEUG_SERVER_FD),
|
||||
改为 python -c + use_reloader=False,不修改 run.py。
|
||||
Job 内 stderr 经 2>&1 会变成 ErrorRecord;统一转成纯文本再输出,避免终端误显示为启动失败。
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$DatabaseUrl = "",
|
||||
[int]$KbConcurrency = 1,
|
||||
[int]$ShippingConcurrency = 1,
|
||||
[switch]$SkipMigrate
|
||||
[switch]$SkipMigrate,
|
||||
[switch]$NoHotReload
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
@@ -45,6 +55,16 @@ function Stop-Port {
|
||||
ForEach-Object { Stop-Process -Id $_ -Force -ErrorAction SilentlyContinue }
|
||||
}
|
||||
|
||||
# 将 Start-Job 输出压成纯文本,避免 stderr 的 ErrorRecord 被终端标成启动失败。
|
||||
function Format-JobLine {
|
||||
param([object]$Item)
|
||||
if ($null -eq $Item) { return $null }
|
||||
if ($Item -is [System.Management.Automation.ErrorRecord]) {
|
||||
return [string]$Item.Exception.Message
|
||||
}
|
||||
return [string]$Item
|
||||
}
|
||||
|
||||
Import-DotEnv (Join-Path $repoRoot ".env.shared")
|
||||
Import-DotEnv (Join-Path $repoRoot ".env.dev")
|
||||
Import-DotEnv (Join-Path $repoRoot ".env.local")
|
||||
@@ -66,54 +86,76 @@ if (-not $SkipMigrate) {
|
||||
if ($LASTEXITCODE -ne 0) { throw "Database migration failed with exit code $LASTEXITCODE" }
|
||||
}
|
||||
|
||||
# -NoHotReload 启动代码经 ArgumentList 传入;Start-Job 会吞掉内嵌双引号,故 Python 侧只用单引号。
|
||||
$backendNoReloadCode = "import os; from app import create_app; create_app('development').run(host='0.0.0.0', port=int(os.getenv('HXOPS_BACKEND_PORT', '5052')), use_reloader=False, debug=True)"
|
||||
|
||||
$jobs = @()
|
||||
$jobs += Start-Job -Name "hxops-backend" -ScriptBlock {
|
||||
param($dir, $python, $db)
|
||||
param($dir, $python, $db, $disableHotReload, $noReloadCode)
|
||||
$ErrorActionPreference = "Continue"
|
||||
if ($db) { $env:DATABASE_URL = $db }
|
||||
Set-Location $dir
|
||||
& $python .\run.py 2>&1
|
||||
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL)
|
||||
if ($disableHotReload) {
|
||||
& $python -c $noReloadCode 2>&1 | ForEach-Object { "$_" }
|
||||
} else {
|
||||
& $python .\run.py 2>&1 | ForEach-Object { "$_" }
|
||||
}
|
||||
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL, [bool]$NoHotReload, $backendNoReloadCode)
|
||||
$jobs += Start-Job -Name "hxops-frontend" -ScriptBlock {
|
||||
param($dir)
|
||||
$ErrorActionPreference = "Continue"
|
||||
Set-Location $dir
|
||||
npm run dev 2>&1
|
||||
npm run dev 2>&1 | ForEach-Object { "$_" }
|
||||
} -ArgumentList @($frontendDir)
|
||||
$jobs += Start-Job -Name "hxops-kb-worker" -ScriptBlock {
|
||||
param($dir, $python, $db, $concurrency)
|
||||
$ErrorActionPreference = "Continue"
|
||||
if ($db) { $env:DATABASE_URL = $db }
|
||||
$env:ENV_NAME = "dev"
|
||||
$env:KB_WORKER_CONCURRENCY = "$concurrency"
|
||||
Set-Location $dir
|
||||
& $python .\worker_kb.py 2>&1
|
||||
& $python .\worker_kb.py 2>&1 | ForEach-Object { "$_" }
|
||||
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL, $KbConcurrency)
|
||||
$jobs += Start-Job -Name "hxops-shipping-worker" -ScriptBlock {
|
||||
param($dir, $python, $db, $concurrency)
|
||||
$ErrorActionPreference = "Continue"
|
||||
if ($db) { $env:DATABASE_URL = $db }
|
||||
$env:ENV_NAME = "dev"
|
||||
$env:SHIPPING_NOTICE_WORKER_CONCURRENCY = "$concurrency"
|
||||
Set-Location $dir
|
||||
& $python .\worker_shipping.py 2>&1
|
||||
& $python .\worker_shipping.py 2>&1 | ForEach-Object { "$_" }
|
||||
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL, $ShippingConcurrency)
|
||||
# 排程 worker:消费 schedule 队列并执行到期 ScheduleTask(入口为 backend/workers/worker_scheduler.py,与 start_local.ps1 的 schedule-worker 对齐)
|
||||
$jobs += Start-Job -Name "hxops-schedule-worker" -ScriptBlock {
|
||||
param($dir, $python, $db)
|
||||
$ErrorActionPreference = "Continue"
|
||||
if ($db) { $env:DATABASE_URL = $db }
|
||||
$env:ENV_NAME = "dev"
|
||||
Set-Location $dir
|
||||
& $python .\workers\worker_scheduler.py 2>&1
|
||||
& $python .\workers\worker_scheduler.py 2>&1 | ForEach-Object { "$_" }
|
||||
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL)
|
||||
|
||||
Write-Host "[startup] backend, frontend, kb-worker, shipping-worker and schedule-worker are running in this IDE terminal." -ForegroundColor Green
|
||||
if ($NoHotReload) {
|
||||
Write-Host "[startup] backend hot-reload disabled (-NoHotReload / use_reloader=False)." -ForegroundColor DarkGray
|
||||
}
|
||||
Write-Host "[startup] Press Ctrl+C to stop all services." -ForegroundColor DarkGray
|
||||
|
||||
$warnedCompleted = @{}
|
||||
try {
|
||||
while ($true) {
|
||||
foreach ($job in $jobs) {
|
||||
Receive-Job -Job $job -ErrorAction SilentlyContinue | ForEach-Object {
|
||||
Write-Host "[$($job.Name)] $_"
|
||||
$line = Format-JobLine $_
|
||||
if (-not [string]::IsNullOrWhiteSpace($line)) {
|
||||
Write-Host "[$($job.Name)] $line"
|
||||
}
|
||||
}
|
||||
if ($job.State -in @("Failed", "Stopped", "Completed")) {
|
||||
Write-Warning "[$($job.Name)] state: $($job.State)"
|
||||
if (-not $warnedCompleted.ContainsKey($job.Name)) {
|
||||
$warnedCompleted[$job.Name] = $true
|
||||
Write-Warning "[$($job.Name)] state: $($job.State)"
|
||||
}
|
||||
}
|
||||
}
|
||||
Start-Sleep -Milliseconds 500
|
||||
|
||||
Reference in new issue
Block a user