feat(shipping-notice): 完善发货通知自动推进与多库存源复核闭环

This commit is contained in:
hugo committed 2026-08-09 11:43:53 +08:00
1 parent cfa19a0b7b
commit 8e0bbf7a81
180 files changed
+31210 -1864

No files matched your search

@@ -0,0 +1,316 @@
"""
services/shipping_notice/auto_progress_controller.py
用途:P0-3 发货任务 AutoProgress 的正式 Task 级串行控制器。
依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务。
逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job
在同一数据库事务落库。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any
from app import db
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.tool_common import log_task_event
AUTO_PROGRESS_GATE_CODES: tuple[str, ...] = (
'inventory_candidates_calculated',
'inventory_candidates_frozen',
'inventory_snapshots_ready',
'inventory_matched',
'excel_generated',
'upload_receipt_recorded',
)
_ACTIVE_JOB_STATUSES = ('queued', 'running')
_CANCELLED_TASK_STATUSES = frozenset({'cancelled', 'canceled', 'closed', 'rejected'})
def _utc_now() -> datetime:
"""返回仓库统一使用的 naive UTC 时间。"""
return datetime.utcnow()
def _task_is_cancelled(task: ShippingNotice) -> bool:
"""根据服务端 Task 事实判断取消/关闭任务,旧 Job 不得将其复活。"""
return str(getattr(task, 'process_status', '') or '').strip().lower() in _CANCELLED_TASK_STATUSES
def _new_execution_no() -> str:
"""生成可读的 P0-3 Execution 编号。"""
return f'APX-{_utc_now().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}'
def _create_execution(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution:
"""
为当前 Task/CandidateSet 创建独立六 Gate 链。
核心逻辑:不复用旧 20 Gate Execution,避免旧 skipped/waiting_external 语义污染 P0-3 的严格顺序。
"""
execution = ShippingProcessExecution(
execution_no=_new_execution_no(), task_id=int(task.id), candidate_set_id=candidate_set_id,
execution_revision=1, status='active', current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1,
)
db.session.add(execution)
db.session.flush()
for sequence_no, gate_code in enumerate(AUTO_PROGRESS_GATE_CODES, start=1):
db.session.add(ShippingProcessGate(
execution_id=int(execution.id), gate_code=gate_code, sequence_no=sequence_no,
status='pending', evaluation_version=1, lock_version=1,
))
task.active_process_execution_id = int(execution.id)
db.session.flush()
return execution
def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution:
"""锁定并取得当前 Execution;候选版本变化时旧链 superseded 后创建新链。"""
current_id = getattr(task, 'active_process_execution_id', None)
execution = db.session.get(ShippingProcessExecution, int(current_id)) if current_id else None
if execution is not None:
execution = (
ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().first()
)
if execution is not None and int(getattr(execution, 'task_id', 0) or 0) != int(task.id):
execution = None
if execution is not None and int(getattr(execution, 'candidate_set_id', 0) or 0) != int(candidate_set_id or 0):
# 旧链永不覆盖:未完成 Gate 取消,Execution 留审计后由新 CandidateSet 建链。
execution.status = 'superseded'
ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id == int(execution.id),
ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')),
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
execution = None
return execution or _create_execution(task, candidate_set_id=candidate_set_id)
def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None:
"""
在 CandidateSet 指针切换后取消旧 Job/未完成 Gate,防止旧版本副作用污染新链。
调用方必须已持有 Task 的业务事务;本函数不 commit,随后 submit 会创建新 CandidateSet 的 Execution。
"""
execution_id = getattr(task, 'active_process_execution_id', None)
if execution_id:
execution = ShippingProcessExecution.query.filter_by(id=int(execution_id)).with_for_update().first()
if execution is not None and execution.status not in {'completed', 'cancelled', 'superseded'}:
execution.status = 'superseded'
ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id == int(execution.id),
ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')),
).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False)
Job.query.filter(
Job.domain == 'shipping_notice', Job.job_type == JobType.SHIPPING_AUTO_PROGRESS.value,
Job.task_id == int(task.id), Job.status == 'queued',
).update({'status': 'cancelled', 'finished_at': _utc_now(), 'message': '候选版本已重冻结'}, synchronize_session=False)
def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[ShippingProcessGate | None, str | None]:
"""
返回严格最早未通过 Gate,或一致性错误。
后置 Gate 已通过而前置未通过意味着投影事实矛盾;此时禁止自动推进并交给管理员诊断。
"""
gates = (
ShippingProcessGate.query.filter_by(execution_id=int(execution.id))
.order_by(ShippingProcessGate.sequence_no.asc()).with_for_update().all()
)
expected = list(AUTO_PROGRESS_GATE_CODES)
if [item.gate_code for item in gates] != expected:
return None, 'projection_data_inconsistent'
pending_seen = False
for gate in gates:
if gate.status == 'passed':
if pending_seen:
return None, 'projection_data_inconsistent'
continue
pending_seen = True
if gate.status in {'pending', 'blocked_retryable'}:
return gate, None
# 上传回执是人工完成的外部事实,不是“重试业务动作”。登记成功后仅允许
# 服务端重新读取该事实并通过最后一个 Gate。
if gate.gate_code == 'upload_receipt_recorded' and gate.status == 'blocked_manual':
return gate, None
return None, None
return None, None
def submit_auto_progress(
*, task: ShippingNotice, trigger: str, operator_id: int | None = None,
resume_gate_code: str | None = None, commit: bool = True,
) -> dict[str, Any]:
"""
接收任何自动/用户触发并安全入队当前 Gate。
普通调用不会信任 resume_gate_code;即使管理员提供诊断 Gate,仍由最早未通过 Gate 决定实际工作。
"""
locked_task = ShippingNotice.query.filter_by(id=int(task.id)).with_for_update().first()
if locked_task is None:
return {'status': 'not_found'}
if _task_is_cancelled(locked_task):
return {'status': 'cancelled', 'task_no': locked_task.task_no}
# 先查活动 Job,再读取/改写 Candidate 或 Execution 指针。这样候选重冻结与重复点击
# 无法把一个仍 running 的旧 Job 错绑到新链。
active = (
Job.query.filter(
Job.domain == 'shipping_notice',
Job.job_type == JobType.SHIPPING_AUTO_PROGRESS.value,
Job.task_id == int(locked_task.id),
Job.status.in_(_ACTIVE_JOB_STATUSES),
).with_for_update().order_by(Job.id.desc()).first()
)
if active is not None:
if commit:
db.session.commit()
return {
'status': 'queued' if active.status == 'queued' else 'running',
'job_id': int(active.id), 'execution_id': active.execution_id,
'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True,
}
candidate = get_active_candidate_set(locked_task)
candidate_set_id = int(candidate.id) if candidate is not None else None
execution = _active_execution_for_task(locked_task, candidate_set_id=candidate_set_id)
gate, inconsistency = _earliest_runnable_gate(execution)
if inconsistency:
execution.status = 'blocked'
execution.current_gate_code = None
log_task_event(locked_task, 'auto_progress_projection_inconsistent', {
'execution_id': execution.id, 'reason_code': inconsistency,
}, actor_id=operator_id, source=trigger)
if commit:
db.session.commit()
return {'status': 'waiting_human', 'reason_code': inconsistency, 'execution_id': execution.id}
if gate is None:
if commit:
db.session.commit()
return {'status': 'waiting_human' if execution.status == 'blocked' else 'completed', 'execution_id': execution.id}
business_ref = f'auto-progress:{int(locked_task.id)}'
token = uuid.uuid4().hex
job_id = enqueue(
JobType.SHIPPING_AUTO_PROGRESS,
{'task_no': locked_task.task_no, 'task_id': int(locked_task.id), 'execution_id': int(execution.id),
'candidate_set_id': candidate_set_id, 'gate_id': int(gate.id), 'gate_code': gate.gate_code,
'trigger': trigger, 'requested_resume_gate_code': resume_gate_code, 'fencing_token': token},
domain='shipping_notice', business_ref=business_ref, created_by_id=operator_id,
message=f'等待执行正式 Gate:{gate.gate_code}', max_attempts=1, commit=False,
task_id=int(locked_task.id), execution_id=int(execution.id), gate_id=int(gate.id),
candidate_set_id=candidate_set_id, fencing_token=token,
)
execution.current_gate_code = gate.gate_code
log_task_event(locked_task, 'auto_progress_job_queued', {
'job_id': job_id, 'execution_id': execution.id, 'candidate_set_id': candidate_set_id,
'gate_id': gate.id, 'gate_code': gate.gate_code, 'trigger': trigger,
}, actor_id=operator_id, source=trigger)
if commit:
db.session.commit()
return {'status': 'queued', 'job_id': int(job_id), 'execution_id': int(execution.id), 'gate_code': gate.gate_code}
def _gate_outcome(task: ShippingNotice, gate: ShippingProcessGate) -> tuple[str, str | None, dict[str, Any]]:
"""仅执行一个 Gate 并把现有业务服务结果归一为正式 Gate 结果。"""
code = gate.gate_code
candidate = get_active_candidate_set(task)
if code == 'inventory_candidates_calculated':
return ('passed', None, {}) if candidate is not None else ('blocked_manual', 'inventory_candidates_required', {})
if code == 'inventory_candidates_frozen':
frozen = candidate is not None and str(candidate.lifecycle_status) == 'frozen'
return ('passed', None, {}) if frozen else ('blocked_manual', 'inventory_candidates_frozen_required', {})
if code == 'inventory_snapshots_ready':
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
result = ensure_all_required_sources_prepared(task, mode='auto')
if result.all_prepared:
return 'passed', None, {'prepared_sources': result.prepared_source_codes}
if result.failed_source_codes:
return 'blocked_manual', 'inventory_snapshot_prepare_failed', {'failed_sources': result.failed_source_codes}
return 'blocked_retryable', 'inventory_snapshots_pending', {'pending_sources': result.pending_source_codes}
if code == 'inventory_matched':
from app.services.shipping_notice.fulfillment_workflow import match_inventory
result = match_inventory({'task_id': task.task_no, '_orchestrator_internal_dispatch': True})
status = str((result or {}).get('status') or '')
if status in {'ok', 'completed'}:
return 'passed', None, {}
return 'blocked_manual' if status == 'needs_human' else 'blocked_retryable', 'inventory_match_not_ready', {'legacy_status': status}
if code == 'excel_generated':
from app.services.shipping_notice.fulfillment_workflow import generate_excel
result = generate_excel({'task_id': task.task_no, '_orchestrator_internal_dispatch': True})
if str((result or {}).get('status') or '') == 'ok' and task.export_file_path:
return 'passed', None, {'export_file_path': task.export_file_path}
return 'blocked_retryable', 'excel_generation_not_ready', {'legacy_status': (result or {}).get('status')}
receipt = getattr(task, 'upload_receipt_json', None)
if receipt or str(getattr(task, 'process_status', '') or '').lower() in {'uploaded', 'completed'}:
return 'passed', None, {}
return 'blocked_manual', 'manual_upload_receipt_required', {}
def run_auto_progress_job(*, job_id: int, worker_id: str) -> dict[str, Any]:
"""
Worker 执行一个且仅一个 Gate,并以 Job outbox 原子提交 Gate 成功和下一个 Job。
所有围栏、Task 取消和 Candidate/Execution identity 都在外部调用前复查;不匹配的迟到 Job 只终态审计。
"""
job = Job.query.filter_by(id=int(job_id)).with_for_update().first()
if job is None or job.status != 'running':
return {'status': 'noop'}
payload = dict(job.payload_json or {})
task = ShippingNotice.query.filter_by(id=int(job.task_id or 0)).with_for_update().first()
execution = ShippingProcessExecution.query.filter_by(id=int(job.execution_id or 0)).with_for_update().first()
gate = ShippingProcessGate.query.filter_by(id=int(job.gate_id or 0)).with_for_update().first()
stale = (
task is None or execution is None or gate is None or _task_is_cancelled(task)
or int(getattr(task, 'active_process_execution_id', 0) or 0) != int(execution.id)
or int(getattr(execution, 'candidate_set_id', 0) or 0) != int(job.candidate_set_id or 0)
or int(gate.execution_id) != int(execution.id)
or str(job.fencing_token or '') != str(payload.get('fencing_token') or '')
)
if stale:
job.status = 'cancelled'; job.finished_at = _utc_now(); job.message = '任务已取消或版本围栏不匹配'
if gate is not None and gate.status in {'pending', 'queued', 'running'}:
gate.status = 'cancelled'
db.session.commit()
return {'status': 'cancelled'}
runnable, inconsistency = _earliest_runnable_gate(execution)
if inconsistency or runnable is None or int(runnable.id) != int(gate.id):
gate.status = 'blocked_manual'; gate.blocking_reason_code = inconsistency or 'projection_data_inconsistent'
execution.status = 'blocked'; job.status = 'success'; job.finished_at = _utc_now()
db.session.commit()
return {'status': 'waiting_human', 'reason_code': gate.blocking_reason_code}
gate.status = 'running'; gate.updated_at = _utc_now(); db.session.flush()
outcome, reason_code, details = _gate_outcome(task, gate)
gate.status = outcome; gate.blocking_reason_code = reason_code; gate.effective_result_json = details
gate.updated_at = _utc_now(); job.status = 'success'; job.finished_at = _utc_now(); job.message = f'Gate {outcome}'
if outcome != 'passed':
execution.status = 'blocked'; execution.current_gate_code = gate.gate_code
log_task_event(task, 'auto_progress_gate_blocked', {'gate_code': gate.gate_code, 'reason_code': reason_code}, source='worker')
db.session.commit()
return {'status': outcome, 'gate_code': gate.gate_code, 'reason_code': reason_code}
gate.passed_at = _utc_now(); execution.last_passed_gate_code = gate.gate_code
# 先 flush 当前 Job 成功态,释放 Task 级 active partial unique;后继 Job 与 Gate passed
# 仍处在同一外层事务,commit 前对 Worker 不可见。
db.session.flush()
next_gate, consistency_error = _earliest_runnable_gate(execution)
if consistency_error:
execution.status = 'blocked'; execution.current_gate_code = None
elif next_gate is None:
execution.status = 'completed'; execution.current_gate_code = None
elif next_gate.gate_code == 'upload_receipt_recorded':
# 上传自动化关闭时,Excel 后明确等人工登记回执,不擅自跨越此 Gate。
execution.status = 'blocked'; execution.current_gate_code = next_gate.gate_code
next_gate.status = 'blocked_manual'; next_gate.blocking_reason_code = 'manual_upload_receipt_required'
else:
execution.status = 'active'; execution.current_gate_code = next_gate.gate_code
submit_auto_progress(task=task, trigger='gate_passed', commit=False)
log_task_event(task, 'auto_progress_gate_passed', {'gate_code': gate.gate_code, 'next_gate_code': execution.current_gate_code}, source='worker')
db.session.commit()
return {
'status': 'passed', 'execution_id': int(execution.id),
'gate_code': gate.gate_code, 'next_gate_code': execution.current_gate_code,
}
@@ -21,10 +21,13 @@ CANDIDATE_QUALIFICATION_STATUSES: Final[frozenset[str]] = frozenset({
})
# 资格评估器版本;快照持久化时写入 evaluator_version。
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v2-xfa'
# 变更点:2026-08-08 引入 VC 三来源门禁,版本 bump。
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION: Final[str] = 'candidate-qualification.v2.1-vc'
# 统一检查顺序(不可重排):后置项依赖前置放行语义由服务层解释。
# XFA 专属门禁对非 XFA Candidate 恒为 True(N/A 放行)。
# VC 门禁 vc_source_merged_clean 放在 field_conflicts_resolved 之后,
# 以便冲突项先被 PDF 优先裁决,剩余 needs_review 项再由本门禁拦截。
CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
'auto_create_enabled',
'classification_confidence',
@@ -32,6 +35,7 @@ CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
'key_fields_minimum_confidence',
'evidence_complete',
'field_conflicts_resolved',
'vc_source_merged_clean',
'duplicate_resolved',
'customer_confirmed',
'idempotency_ok',
@@ -46,10 +50,11 @@ CANDIDATE_QUALIFICATION_GATE_KEYS: Final[tuple[str, ...]] = (
CANDIDATE_QUALIFICATION_GATE_REASON_CODES: Final[dict[str, str]] = {
'auto_create_enabled': 'auto_create_disabled',
'classification_confidence': 'classification_low_confidence',
'required_fields_complete': 'required_field_missing',
'required_fields_complete': 'final_required_field_missing',
'key_fields_minimum_confidence': 'field_low_confidence',
'evidence_complete': 'evidence_missing',
'field_conflicts_resolved': 'field_conflict',
'vc_source_merged_clean': 'vc_source_conflict_unresolved',
'duplicate_resolved': 'duplicate_unresolved',
'customer_confirmed': 'customer_confirmation_required',
'idempotency_ok': 'task_already_exists',
@@ -70,6 +75,8 @@ CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES: Final[frozenset[str]] = frozenset({
'field_low_confidence',
# PDF 优先已选定当前值,但仍须人工确认冲突后方可自动建单。
'pdf_preferred_critical_conflict',
# Vendor Comments 三来源值不一致,须人工裁决但不硬阻塞人工建单。
'vc_source_conflict_unresolved',
})
# 解析来源(写入 parser_trace,不直接决定资格)。
@@ -35,6 +35,11 @@ from app.services.shipping_notice.candidate_qualification_contract import (
CANDIDATE_QUALIFICATION_GATE_REASON_CODES,
CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES,
)
from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import (
CQ_VC_BLOCKING_REASONS,
CQ_VC_REVIEW_REASONS,
collect_vc_candidate_conflicts,
)
from app.services.shipping_notice.order_schema import service as order_schema_service
from app.services.shipping_notice.document_layout.xfa_contract import (
XFA_CROSS_CHECK_AUTO_CREATE_OK_STATUSES,
@@ -89,6 +94,10 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
核心逻辑:过滤仅描述文档版面/坐标质量的诊断项;字段值冲突、跨来源冲突
与其他未知阻断项继续 fail-closed。
注意:Vendor Comments 三来源冲突由独立 vc_source_merged_clean 门禁
(见 _vc_gate_ok)评估,不入本集合,避免污染 field_conflicts_resolved
原有零回归语义。
Args:
candidate: ShippingOrderCandidate 或兼容替身。
@@ -108,6 +117,68 @@ def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
]
# ---------------------------------------------------------------------------
# VC 三来源门禁:独立于 Candidate.conflicts_json,从 structured.extraction
# vendor_comments_merged 读,避免冲突历史与裁决历史相互污染。
# ---------------------------------------------------------------------------
def _vc_gate_ok(candidate: Any) -> bool:
"""
VC 三来源合并结果是否全部清洁(无阻断冲突)。
核心逻辑:缺 VC merged 载荷 → 视为未启用 → OK;
severity == blocking 的项 → 必须视为 fail(硬阻断);
severity == review_required 但 can_auto_create 场景下同样 fail,
交由上层 CANDIDATE_QUALIFICATION_REVIEW_REASON_CODES 归类到
review_required 总体状态(允许人工建单,不允许 STP 自动建单)。
Args:
candidate: ShippingOrderCandidate 或兼容替身。
Returns:
True 表示 VC 路径「已干净」,可放行自动/人工建单。
"""
try:
items = collect_vc_candidate_conflicts(candidate)
except Exception: # noqa: BLE001 — 门禁 fail-closed:解析异常视为未通过
return False
for it in items:
if not isinstance(it, dict):
continue
severity = str(it.get('severity') or 'blocking').strip()
reason = str(it.get('reason') or '').strip()
if reason in CQ_VC_BLOCKING_REASONS:
return False
if severity == 'blocking':
return False
if severity == 'review_required':
# review_required 对自动建单门禁同样算失败(上层会映射为 review_required 总体状态)
# 对人工建单是允许的,但 CQ 门禁统一口径:needs_review → fail;
# 人工建单的门禁是独立路径,在 order_review_confirmation_service 中。
return False
return True
def _vc_fine_grained_reason(candidate: Any) -> str | None:
"""
VC 门禁失败时提取首个匹配的细因码,优先给出 format/region 错,
冲突类错其次,保留默认 vc_source_conflict_unresolved 兜底。
"""
try:
items = collect_vc_candidate_conflicts(candidate)
except Exception: # noqa: BLE001
return None
priority_order = [
'vc_source_region_unbound',
'vc_source_format_invalid',
'vc_source_conflict_unresolved',
]
seen = {str(x.get('reason') or '').strip() for x in items if isinstance(x, dict)}
for want in priority_order:
if want in seen:
return want
return None
def resolve_candidate_customer_resolved(
*,
candidate: Any | None = None,
@@ -288,6 +359,7 @@ def evaluate_candidate_qualification(
)
evidence_ok = _evidence_ok(candidate)
conflicts_ok = _conflicts_ok(candidate)
vc_ok = _vc_gate_ok(candidate)
duplicate_ok = _duplicate_ok(candidate)
customer_ok, customer_reason = _customer_ok(candidate, customer_resolved=customer_resolved)
idempotency_ok = _idempotency_ok(candidate)
@@ -310,6 +382,7 @@ def evaluate_candidate_qualification(
'key_fields_minimum_confidence': key_confidence_ok,
'evidence_complete': evidence_ok,
'field_conflicts_resolved': conflicts_ok,
'vc_source_merged_clean': vc_ok,
'duplicate_resolved': duplicate_ok,
'customer_confirmed': customer_ok,
'idempotency_ok': idempotency_ok,
@@ -321,7 +394,7 @@ def evaluate_candidate_qualification(
}
failed = [key for key in CANDIDATE_QUALIFICATION_GATE_KEYS if not gates.get(key)]
# [STEP 3] 映射原因码;客户细因 / XFA 细因 / PDF 关键冲突细因覆盖默认码。
# [STEP 3] 映射原因码;客户细因 / XFA 细因 / PDF 关键冲突细因 / VC 细因覆盖默认码。
blocking_reason_codes: list[str] = []
for key in failed:
if key == 'customer_confirmed' and customer_reason:
@@ -335,6 +408,11 @@ def evaluate_candidate_qualification(
if pdf_reason:
blocking_reason_codes.append(pdf_reason)
continue
if key == 'vc_source_merged_clean':
vc_reason = _vc_fine_grained_reason(candidate)
if vc_reason:
blocking_reason_codes.append(vc_reason)
continue
blocking_reason_codes.append(
CANDIDATE_QUALIFICATION_GATE_REASON_CODES.get(key, 'order_freeze_not_ready')
)
@@ -347,9 +425,23 @@ def evaluate_candidate_qualification(
failed_gates=failed,
blocking_reason_codes=blocking_reason_codes,
)
# [STEP 3b] 证据快照追加 VC 合并概览(脱敏,仅计数)—— 注意:必须在 STEP 4 status
# 计算之后执行,因为 status 不依赖 evidence_snapshot,保证零回归。
evidence_snapshot = _evidence_snapshot(candidate)
if xfa_eval.get('evidence_extra'):
evidence_snapshot = {**evidence_snapshot, **xfa_eval['evidence_extra']}
try:
vc_items = collect_vc_candidate_conflicts(candidate)
except Exception: # noqa: BLE001
vc_items = []
vc_counts = {
'vc_total_candidates': len(vc_items),
'vc_review_required': len([x for x in vc_items if isinstance(x, dict) and str(x.get('severity') or '') == 'review_required']),
'vc_blocking': len([x for x in vc_items if isinstance(x, dict) and str(x.get('severity') or '') == 'blocking']),
}
if vc_counts['vc_total_candidates']:
evidence_snapshot = {**evidence_snapshot, **vc_counts}
score = _qualification_score(gates)
confidence_policy = {
'minimum_confidence': float(min_confidence),
@@ -0,0 +1,253 @@
"""
backend/app/services/shipping_notice/case_retry_auto_progress_service.py
用途:单个 Case 精确自动推进恢复(Case 级 retry-auto-progress API 服务层)。
依赖:reconciliation_service.assert_case_not_blocked_manual、
order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress、
order_review_service.get_review_case_visible_to_user(兜底 soft_load_review_case_for_audit)、
fulfillment_audit.record_fulfillment_audit、order_review_projection.serialize_review_case。
逻辑:可见性 → 业务阻断双校验 → 终态检查(幂等)→ reconcile_single_case → 审计 → 返回摘要。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.core.errors import AppError, ConflictError
from app.models import ShippingOrderReviewCase
def case_retry_auto_progress(
*,
user_id: int,
case_no: str,
is_admin: bool = False,
) -> dict[str, Any]:
"""
单个 Case 精确自动推进恢复入口。
用途(第一层):为单个指定 Review Case 执行「客户协调 + Draft 校验 + STP 入队」
全链路自动推进,适用于 Projection primary_action.code = retry_auto_progress。
禁止 duplicate 等业务阻断对象调用;assert_case_not_blocked_manual 前置双校验,
防止用技术重试绕过人工裁决门禁。
依赖(第二层):
- reconciliation_service.assert_case_not_blocked_manual:业务阻断前置双校验。
- order_review_auto_progress_coordinator.reconcile_single_case_for_auto_progress:
客户协调 + validate_draft + ensure_stp_auto_create_for_case 统一执行。
- order_review_service.get_review_case_visible_to_user(兜底:
order_review_draft_service.soft_load_review_case_for_audit):Case 可见性校验。
- fulfillment_audit.record_fulfillment_audit:写 case_retry_auto_progress_invoked 审计。
- order_review_projection.serialize_review_case:返回体附带 Case 安全投影。
逻辑(第三层):
STEP 1 可见性校验 → STEP 2 业务阻断前置校验 → STEP 3 终态幂等检查
→ STEP 4 调用 reconcile_single_case_for_auto_progress(trigger=case_api_retry_auto_progress)
→ STEP 5 审计 → STEP 6 返回统一摘要结构。
Args:
user_id: 操作人(必须为 Case owner 或 admin)。
case_no: 目标复核 Case 编号。
is_admin: 是否管理员(影响可见性与 serialize 投影粒度)。
Returns:
``{success, operation, case_no, customer_step_status, validate_status,
enqueue_status, job_id, idempotency_key, error, case}``。
已终态时返回 success=True + already_confirmed=True + enqueue_status=already_confirmed,
不抛错(幂等友好)。
Raises:
NotFoundError: Case 不存在或当前用户越权。
ConflictError (SHIPPING.RETRY_STP_BLOCKED_MANUAL): 命中 duplicate 等业务阻断,
禁止用 retry API 绕过,引导走 reconcile-and-progress。
"""
import logging as _rt_logging
_rt_log = _rt_logging.getLogger(__name__)
normalized_case_no = str(case_no or '').strip().upper()
user_id_int = int(user_id or 0)
fallback = {
'success': False,
'operation': 'retry_auto_progress',
'case_no': normalized_case_no,
'already_confirmed': False,
'customer_step_status': 'failed',
'validate_status': 'failed',
'enqueue_status': 'not_eligible',
'job_id': None,
'idempotency_key': None,
'error': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
'reconcile_result': {},
'case': None,
}
# ========================================================================
# [STEP 0] 模块级 delay import 统一包 try/except,与路由/协调器双层防护对齐。
# 任一依赖模块 SyntaxError/ImportError → 返回结构化 fallback,
# 不冒泡为 HTTP 500 或整批拖死协调器循环。
# ========================================================================
try:
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress,
)
from app.services.shipping_notice.order_review_projection import serialize_review_case
from app.services.shipping_notice.reconciliation_service import (
assert_case_not_blocked_manual,
)
except (SyntaxError, ImportError) as mod_err:
_rt_log.exception(
'case_retry_auto_progress module import error case_no=%s err=%s',
normalized_case_no, type(mod_err).__name__,
)
fallback['error'] = 'SHIPPING.MODULE_IMPORT_ERROR'
fallback['import_error'] = type(mod_err).__name__
return fallback
except Exception as exc: # noqa: BLE001
_rt_log.exception(
'case_retry_auto_progress import unexpected error case_no=%s',
normalized_case_no,
)
fallback['error_type'] = type(exc).__name__
return fallback
try:
# ====================================================================
# [STEP 1] 可见性校验:优先 get_review_case_visible_to_user,
# ImportError 兜底走 soft_load_review_case_for_audit(写审计场景同款门禁)。
# ====================================================================
try:
from app.services.shipping_notice.order_review_service import (
get_review_case_visible_to_user,
)
case: ShippingOrderReviewCase = get_review_case_visible_to_user(
normalized_case_no,
user_id_int,
is_admin=bool(is_admin),
)
except AppError:
raise
except Exception:
from app.services.shipping_notice.order_review_draft_service import (
soft_load_review_case_for_audit,
)
case = soft_load_review_case_for_audit(
user_id=user_id_int,
case_no=normalized_case_no,
)
if case is None:
from app.core.errors import NotFoundError
raise NotFoundError(
'Order review case not found',
code='SHIPPING.REVIEW_CASE_NOT_FOUND',
)
# ====================================================================
# [STEP 2] 业务阻断前置校验:duplicate 类必须走 reconcile-and-progress。
# 若命中 → 抛 409 ConflictError,明确 alternative_api 指向。
# ====================================================================
assert_case_not_blocked_manual(case_no=normalized_case_no, case=case)
# ====================================================================
# [STEP 3] 终态检查:confirmed_task_id 或 status=confirmed/终态 → 幂等返回。
# 不抛错,保留 already_confirmed 标识让前端区分「本次执行」与「原本已终态」。
# ====================================================================
_TERMINAL = frozenset({
'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending',
})
already_confirmed = (
bool(getattr(case, 'confirmed_task_id', None))
or str(getattr(case, 'status', '') or '') in _TERMINAL
)
if already_confirmed:
return {
'success': True,
'operation': 'retry_auto_progress',
'case_no': normalized_case_no,
'already_confirmed': True,
'customer_step_status': 'skipped',
'validate_status': 'skipped',
'enqueue_status': 'already_confirmed_or_terminal',
'job_id': None,
'idempotency_key': None,
'error': None,
'reconcile_result': {},
'case': serialize_review_case(case, is_admin=bool(is_admin)),
}
# ====================================================================
# [STEP 4] 核心执行:reconcile_single_case_for_auto_progress(统一协调器)。
# trigger=case_api_retry_auto_progress,refresh_validation=True 重跑校验。
# ====================================================================
reconcile_result: dict[str, Any] = reconcile_single_case_for_auto_progress(
case=case,
trigger='case_api_retry_auto_progress',
refresh_validation=True,
)
# ====================================================================
# [STEP 5] 审计:case_retry_auto_progress_invoked。
# metadata 附带 reconcile_result 全量摘要,strict=False 降级不阻断。
# ====================================================================
try:
record_fulfillment_audit(
event_type='case_retry_auto_progress_invoked',
aggregate_type='order_review_case',
aggregate_id=normalized_case_no,
action='retry_auto_progress',
actor_type='user',
actor_id=user_id_int,
review_case_no=normalized_case_no,
owner_user_id=int(getattr(case, 'owner_user_id', 0) or 0),
result=(
'success'
if not reconcile_result.get('error')
and str(reconcile_result.get('enqueue_status') or '') in {
'queued', 'reused', 'already_queued', 'already_running', 'enqueued',
}
else 'failed'
),
metadata={'reconcile_result': dict(reconcile_result or {})},
source='case_retry_auto_progress_service',
strict=False,
)
except Exception:
pass
# ====================================================================
# [STEP 6] 统一返回:success + operation + case_no + reconcile_result 平铺字段
# + serialized case 投影。
# ====================================================================
return {
'success': True,
'operation': 'retry_auto_progress',
'case_no': normalized_case_no,
'already_confirmed': False,
'customer_step_status': reconcile_result.get('customer_step_status'),
'validate_status': reconcile_result.get('validate_status'),
'enqueue_status': reconcile_result.get('enqueue_status'),
'job_id': reconcile_result.get('job_id'),
'idempotency_key': reconcile_result.get('idempotency_key'),
'error': reconcile_result.get('error'),
'reconcile_result': dict(reconcile_result or {}),
'case': serialize_review_case(case, is_admin=bool(is_admin)),
}
except (AppError, ConflictError):
raise
except Exception as exc: # noqa: BLE001
_rt_log.exception(
'case_retry_auto_progress execution error case_no=%s', normalized_case_no,
)
fallback['error_type'] = type(exc).__name__
try:
fallback['case'] = (
serialize_review_case(case, is_admin=bool(is_admin))
if 'case' in locals() and case is not None else None
)
except Exception: # noqa: BLE001
pass
return fallback
@@ -16,11 +16,15 @@ from typing import Any
from app import db
from app.core.errors import AppError, NotFoundError, ValidationError
from app.jobs.types import JobType
from app.models import (
Job,
ShippingNotice,
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
ShippingOrderReviewDraft,
)
from app.services.shipping_notice.recovery_contract import should_general_retry_be_removed
_LOGGER = logging.getLogger(__name__)
@@ -29,6 +33,21 @@ ACTION_RETRY_STP = 'retry_stp_auto_create'
OBJECT_REVIEW_CASE = 'review_case'
OBJECT_FORMAL_TASK = 'formal_task'
# [STEP P1-13] 业务阻断黑名单:duplicate 类命中即禁止对话级重试,需走 reconcile-and-progress
_DUPLICATE_BLOCKING_CODES = frozenset({
'duplicate_decision_required',
'SHIPPING.NOTICE_EXACT_DUPLICATE',
'NOTICE_EXACT_DUPLICATE',
})
# [STEP P1-13-d] 允许强制重试的 manual_fallback 原因码(不含 duplicate 类)
_FORCE_RETRYABLE_BLOCKING_CODES = frozenset({
'STP_NOT_ELIGIBLE',
'SHIPPING.STP_NOT_ELIGIBLE',
'profile_schema_mismatch',
'SHIPPING.profile_schema_mismatch',
})
def project_conversation_allowed_actions(
*,
@@ -107,7 +126,7 @@ def retry_auto_progress_for_conversation(
actor_id=int(user_id),
conversation_id=normalized,
owner_user_id=int(user_id),
result='success' if summary['failed'] == 0 else 'partial',
result='success' if summary['failed'] == 0 else 'failure',
metadata={
'reason': str(reason or 'user_retry_auto_progress')[:200],
'summary': summary,
@@ -213,24 +232,183 @@ def _formal_task_no(case: ShippingOrderReviewCase, automation: dict[str, Any]) -
def _list_eligible_targets(*, user_id: int, conversation_id: str) -> list[dict[str, Any]]:
"""扫描可重试对象(仅 retryable=true)。"""
"""
扫描可重试对象(P1-13 扩展三类 c / d / e,OR 语义)。
目标候选扩展说明(文档 Q8 合同测试要求):
[STEP P1-13-e] 原有:automation.retryable=true 且未命中业务阻断(保留,不删)。
[STEP P1-13-c] stp_enqueue_missing:
• Case.status IN ('unreviewed','draft','ready')
• confirmed_task_id IS NULL
• Draft.validation.status = 'ready' 且 can_auto_create = true
• 最近 Job(若有)的 retryable != false
或 blocking_reason 非 duplicate_decision_required / NOTICE_EXACT_DUPLICATE
• 当前无 queued/running STP Job
→ 这类对象 Draft 校验就绪但从未成功入队 STP,可通过 retry_auto_progress 自动推进。
[STEP P1-13-d] manual_fallback 且允许强制重试:
• 最近 STP Job.result_json.status = failed
• result_json.blocking_reason 非 duplicate 类
• retryable_flag = False 但 blocking_reason 命中允许
retry_stp_auto_create_for_case 强制重试的类型
(如 STP_NOT_ELIGIBLE / profile_schema_mismatch,不含 duplicate)
→ 这类对象标记了 manual_fallback,但实际是技术可恢复的原因,允许批量重试。
除上述条件外,全部对象必须通过 should_general_retry_be_removed 二次门禁。
"""
targets: list[dict[str, Any]] = []
for case in _list_conversation_cases(user_id=user_id, conversation_id=conversation_id):
automation = _automation_for_case(case)
if not bool(automation.get('retryable')):
retryable_flag = bool(automation.get('retryable'))
blocking_reason = (
automation.get('blocking_reason')
if isinstance(automation.get('blocking_reason'), dict)
else None
)
br_code = (
str(blocking_reason.get('code') or '')
if isinstance(blocking_reason, dict)
else str(blocking_reason or '')
)
# ------------------------------------------------------------------
# 取 Case 维度最近一条 STP Job(用于 c / d 条件判断)
# 说明:Job 模型没有 reference_type / reference_key,通过 business_ref 前缀匹配。
# STP business_ref = stp-auto:{run_no}:doc-{document_id}:v{draft_version},
# 按 run_no+document_id 前缀可覆盖同一 Case 的所有 draft_version。
# ------------------------------------------------------------------
_run_no = str(getattr(getattr(case, 'run', None), 'run_no', '') or '').strip()
_doc_id = getattr(case, 'document_id', None)
_stp_prefix = None
if _run_no and _doc_id is not None:
_stp_prefix = f'stp-auto:{_run_no}:doc-{int(_doc_id)}:'
latest_stp_job: Job | None = None
running_stp_exists = False
if _stp_prefix is not None:
latest_stp_job = (
Job.query
.filter(
Job.domain == 'shipping_notice',
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
Job.business_ref.like(f"{_stp_prefix}%"),
)
.order_by(Job.created_at.desc())
.first()
)
running_stp_exists = (
Job.query
.filter(
Job.domain == 'shipping_notice',
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
Job.business_ref.like(f"{_stp_prefix}%"),
Job.status.in_(['queued', 'running']),
)
.limit(1)
.first()
) is not None
latest_rj: dict[str, Any] = (
dict(latest_stp_job.result_json)
if latest_stp_job is not None and isinstance(latest_stp_job.result_json, dict)
else {}
)
latest_retryable_flag: bool = bool(latest_rj.get('retryable', True))
latest_br_raw = latest_rj.get('blocking_reason')
latest_br_code = (
str(latest_br_raw.get('code') or '')
if isinstance(latest_br_raw, dict)
else str(latest_br_raw or '')
)
latest_status: str = str(latest_rj.get('status') or '').strip().lower()
# ------------------------------------------------------------------
# Draft 校验:status=ready + can_auto_create(c 条件需要)
# ------------------------------------------------------------------
draft: ShippingOrderReviewDraft | None = case.current_draft
validation: dict[str, Any] = (
dict(draft.validation_result_json)
if draft is not None and isinstance(draft.validation_result_json, dict)
else {}
)
draft_ready_ok = (
draft is not None
and str(validation.get('status') or '') == 'ready'
and bool(validation.get('can_auto_create'))
)
case_status_ok = str(case.status or '') in {'unreviewed', 'draft', 'ready'}
no_confirmed_task = not bool(case.confirmed_task_id)
# ------------------------------------------------------------------
# P1-13:三类候选 OR 判定
# ------------------------------------------------------------------
# [STEP P1-13-e] 原有 automation.retryable=true(保留,不删)
eligible_e = retryable_flag and not should_general_retry_be_removed(
retryable_flag=retryable_flag,
blocking_reason=blocking_reason,
)
# [STEP P1-13-c] stp_enqueue_missing:Draft 校验就绪但从未入队或可恢复
eligible_c = (
case_status_ok
and no_confirmed_task
and draft_ready_ok
and not running_stp_exists
and (
latest_stp_job is None
or latest_retryable_flag
or latest_br_code not in _DUPLICATE_BLOCKING_CODES
)
)
# [STEP P1-13-d] manual_fallback 允许强制重试:最近失败、非 duplicate、命中允许码
eligible_d = (
no_confirmed_task
and latest_stp_job is not None
and latest_status == 'failed'
and latest_br_code not in _DUPLICATE_BLOCKING_CODES
and (
latest_br_code in _FORCE_RETRYABLE_BLOCKING_CODES
or br_code in _FORCE_RETRYABLE_BLOCKING_CODES
)
)
is_eligible = eligible_e or eligible_c or eligible_d
if not is_eligible:
continue
# ------------------------------------------------------------------
# 二次门禁:should_general_retry_be_removed(duplicate 类再次拦截)
# ------------------------------------------------------------------
if eligible_e and should_general_retry_be_removed(
retryable_flag=retryable_flag,
blocking_reason=blocking_reason,
):
continue
task_no = _formal_task_no(case, automation)
if task_no:
targets.append({
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'case_no': case.case_no,
'category': (
'e_retryable_true' if eligible_e
else 'c_stp_enqueue_missing' if eligible_c
else 'd_manual_fallback_force'
),
})
elif not case.confirmed_task_id:
targets.append({
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'case_no': case.case_no,
'category': (
'e_retryable_true' if eligible_e
else 'c_stp_enqueue_missing' if eligible_c
else 'd_manual_fallback_force'
),
})
return targets
@@ -260,14 +438,41 @@ def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str,
"""
对单个 Case 执行重试或跳过。
核心逻辑:重读 automation;正式 OT→auto_progress;否则 STP;异常映射为 failed/skipped。
核心逻辑(P1-13 升级):
[STEP 1] 重新读最新 DB 状态(禁止信任传入 case 为可信快照)
[STEP 2] 调 assert_case_not_blocked_manual 双校验;业务阻断 → skipped(而非失败)
[STEP 3] 正式 OT → auto_progress(保持不变);
建单前 Case → 统一调 case_retry_auto_progress(复用客户协调 + Draft 校验 + STP 入队)
[STEP 4] 保留原有 items 返回契约(不 break 前端),新增 P1-13 分类字段放入 metadata。
"""
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
from app.services.shipping_notice.reconciliation_service import (
assert_case_not_blocked_manual,
)
from app.core.errors import ConflictError
automation = _automation_for_case(case)
formal = resolve_formal_ot(case)
# ====================================================================
# [STEP 1 P1-13] 重新读最新 DB 状态(不信任调用方传入的 case 对象,避免前端竞态脏读)
# ====================================================================
fresh_case: ShippingOrderReviewCase | None = (
ShippingOrderReviewCase.query
.filter_by(id=int(case.id))
.first()
)
if fresh_case is None:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': None,
'outcome': 'skipped',
'reason_code': 'case_missing',
'metadata': {'p13_category': None},
}
automation = _automation_for_case(fresh_case)
formal = resolve_formal_ot(fresh_case)
task_missing = bool(formal.get('task_missing'))
task_no = _formal_task_no(case, automation)
task_no = _formal_task_no(fresh_case, automation)
if task_no:
skip = _skip_reason_from_automation(automation, task_missing=task_missing)
@@ -278,37 +483,68 @@ def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str,
'action': None,
'outcome': 'skipped',
'reason_code': skip,
'metadata': {'p13_category': 'e_formal_ot'},
}
return _execute_formal_task_retry(user_id=user_id, task_no=task_no)
if task_missing or case.confirmed_task_id:
if task_missing or fresh_case.confirmed_task_id:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'object_ref': fresh_case.case_no,
'action': None,
'outcome': 'skipped',
'reason_code': 'task_missing' if task_missing else 'already_confirmed',
'metadata': {'p13_category': None},
}
skip = _skip_reason_from_automation(automation, task_missing=False)
if skip:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'object_ref': fresh_case.case_no,
'action': None,
'outcome': 'skipped',
'reason_code': skip,
'metadata': {'p13_category': None},
}
return _execute_stp_retry(user_id=user_id, case_no=str(case.case_no))
# ====================================================================
# [STEP 2 P1-13] assert_case_not_blocked_manual 二次校验;业务阻断 → skipped(不回滚整批)
# [DUPLICATE-GUARD-3] 第三道:对话级批量重试单条执行前双校验 —
# 命中 duplicate 等阻断时单条标记 skipped,不影响其他 Case
# ====================================================================
try:
assert_case_not_blocked_manual(case_no=str(fresh_case.case_no), case=fresh_case)
except ConflictError as blocked_err:
code = str(getattr(blocked_err, 'code', None) or 'SHIPPING.RETRY_STP_BLOCKED_MANUAL')
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': fresh_case.case_no,
'action': None,
'outcome': 'skipped',
'reason_code': code,
'metadata': {
'p13_category': None,
'blocked_by': 'assert_case_not_blocked_manual',
'blocking_details': getattr(blocked_err, 'details', None),
},
}
# ====================================================================
# [STEP 3 P1-13] 统一调 case_retry_auto_progress 核心服务
# (不再复制 STP 入队逻辑,复用客户协调 + validate + STP)
# ====================================================================
return _execute_case_retry_auto_progress(user_id=user_id, case=fresh_case)
def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]:
"""调用既有 STP retry;捕获业务错误为逐对象 outcome。"""
from app.services.shipping_notice.order_stp_auto_create_service import (
retry_stp_auto_create_for_case,
)
"""调用既有 STP retry;捕获业务错误为逐对象 outcome。(保留为兼容降级路径)"""
try:
from app.services.shipping_notice.order_stp_auto_create_service import (
retry_stp_auto_create_for_case,
)
result = retry_stp_auto_create_for_case(user_id=user_id, case_no=case_no)
status = str(result.get('status') or '').strip().lower()
if status in {'queued', 'reused', 'enqueued'}:
@@ -318,6 +554,7 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]:
'action': ACTION_RETRY_STP,
'outcome': 'queued',
'reason_code': None,
'metadata': {'p13_category': 'legacy_stp_retry'},
}
return {
'object_type': OBJECT_REVIEW_CASE,
@@ -325,6 +562,7 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]:
'action': ACTION_RETRY_STP,
'outcome': 'skipped',
'reason_code': status or 'not_retryable',
'metadata': {'p13_category': 'legacy_stp_retry'},
}
except AppError as err:
code = str(getattr(err, 'code', None) or 'SHIPPING.STP_ENQUEUE_FAILED')
@@ -335,6 +573,7 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]:
'action': None,
'outcome': 'skipped',
'reason_code': 'already_confirmed',
'metadata': {'p13_category': 'legacy_stp_retry'},
}
if 'NOT_ELIGIBLE' in code:
return {
@@ -343,6 +582,7 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]:
'action': ACTION_RETRY_STP,
'outcome': 'failed',
'reason_code': code,
'metadata': {'p13_category': 'legacy_stp_retry'},
}
return {
'object_type': OBJECT_REVIEW_CASE,
@@ -350,6 +590,23 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]:
'action': ACTION_RETRY_STP,
'outcome': 'failed',
'reason_code': code,
'metadata': {'p13_category': 'legacy_stp_retry'},
}
except (SyntaxError, ImportError) as mod_err:
_LOGGER.exception(
'conversation STP retry module import error case_no=%s err=%s',
case_no, type(mod_err).__name__,
)
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case_no,
'action': ACTION_RETRY_STP,
'outcome': 'failed',
'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR',
'metadata': {
'p13_category': 'legacy_stp_retry',
'import_error': type(mod_err).__name__,
},
}
except Exception: # noqa: BLE001
_LOGGER.exception('conversation STP retry failed case_no=%s', case_no)
@@ -359,14 +616,160 @@ def _execute_stp_retry(*, user_id: int, case_no: str) -> dict[str, Any]:
'action': ACTION_RETRY_STP,
'outcome': 'failed',
'reason_code': 'SHIPPING.STP_ENQUEUE_FAILED',
'metadata': {'p13_category': 'legacy_stp_retry'},
}
def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
"""正式 OT 重试:委托统一决策器(与任务级 /retry 同源)。"""
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
def _execute_case_retry_auto_progress(
*,
user_id: int,
case: ShippingOrderReviewCase,
) -> dict[str, Any]:
"""
P1-13 统一执行入口:调 case_retry_auto_progress 核心服务(客户协调 + validate + STP)。
保留原有 items 返回契约(object_type / object_ref / action / outcome / reason_code),
新增 P1-13 分类字段与执行摘要放入 metadata,不 break 前端。
"""
try:
from app.services.shipping_notice.case_retry_auto_progress_service import (
case_retry_auto_progress,
)
result = case_retry_auto_progress(
user_id=int(user_id),
case_no=str(case.case_no),
is_admin=False,
)
except AppError as err:
code = str(getattr(err, 'code', None) or 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED')
if 'ALREADY_CONFIRMED' in code:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': None,
'outcome': 'skipped',
'reason_code': 'already_confirmed',
'metadata': {'p13_category': None, 'error': code},
}
if 'BLOCKED_MANUAL' in code or 'RECONCILE' in code:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': None,
'outcome': 'skipped',
'reason_code': code,
'metadata': {
'p13_category': None,
'blocked_by': 'case_retry_auto_progress_assertion',
'details': getattr(err, 'details', None),
},
}
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': ACTION_RETRY_AUTO_PROGRESS,
'outcome': 'failed',
'reason_code': code,
'metadata': {'p13_category': None, 'error': code},
}
except (SyntaxError, ImportError) as mod_err:
_LOGGER.exception(
'conversation case_retry_auto_progress module import error case_no=%s err=%s',
case.case_no, type(mod_err).__name__,
)
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': ACTION_RETRY_AUTO_PROGRESS,
'outcome': 'failed',
'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR',
'metadata': {
'p13_category': None,
'import_error': type(mod_err).__name__,
},
}
except Exception: # noqa: BLE001
_LOGGER.exception('conversation case_retry_auto_progress failed case_no=%s', case.case_no)
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': ACTION_RETRY_AUTO_PROGRESS,
'outcome': 'failed',
'reason_code': 'SHIPPING.RETRY_AUTO_PROGRESS_FAILED',
'metadata': {'p13_category': None, 'error': 'unexpected_exception'},
}
# 解析执行结果:success + enqueue_status → outcome
enqueue_status = str(result.get('enqueue_status') or '').strip().lower()
if result.get('already_confirmed'):
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': None,
'outcome': 'skipped',
'reason_code': 'already_confirmed',
'metadata': {
'p13_category': None,
'enqueue_status': enqueue_status,
'already_confirmed': True,
},
}
queued_set = {
'queued', 'reused', 'already_queued', 'already_running', 'enqueued',
}
if enqueue_status in queued_set:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': ACTION_RETRY_AUTO_PROGRESS,
'outcome': 'queued',
'reason_code': None,
'metadata': {
'p13_category': result.get('case_no'),
'customer_step_status': result.get('customer_step_status'),
'validate_status': result.get('validate_status'),
'enqueue_status': enqueue_status,
'job_id': result.get('job_id'),
'idempotency_key': result.get('idempotency_key'),
},
}
if enqueue_status in {'already_confirmed_or_terminal', 'not_eligible'}:
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': ACTION_RETRY_AUTO_PROGRESS,
'outcome': 'skipped',
'reason_code': enqueue_status,
'metadata': {
'p13_category': None,
'enqueue_status': enqueue_status,
'error': result.get('error'),
},
}
return {
'object_type': OBJECT_REVIEW_CASE,
'object_ref': case.case_no,
'action': ACTION_RETRY_AUTO_PROGRESS,
'outcome': 'failed' if result.get('error') else 'skipped',
'reason_code': enqueue_status or (result.get('error') and 'execution_error') or 'not_retryable',
'metadata': {
'p13_category': None,
'enqueue_status': enqueue_status,
'error': result.get('error'),
'customer_step_status': result.get('customer_step_status'),
'validate_status': result.get('validate_status'),
},
}
def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
"""正式 OT 重试:委托统一决策器(与任务级 /retry 同源)。metadata 追加 P1-13 分类不 break 前端。"""
try:
from app.services.shipping_notice.task_retry_decision_service import retry_task_with_decision
result = retry_task_with_decision(
task_no=str(task_no),
user_id=int(user_id),
@@ -382,6 +785,23 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
'action': ACTION_RETRY_AUTO_PROGRESS,
'outcome': 'failed',
'reason_code': str(getattr(err, 'code', None) or 'SHIPPING.AUTO_PROGRESS_FAILED'),
'metadata': {'p13_category': 'e_formal_ot'},
}
except (SyntaxError, ImportError) as mod_err:
_LOGGER.exception(
'conversation task retry module import error task_no=%s err=%s',
task_no, type(mod_err).__name__,
)
return {
'object_type': OBJECT_FORMAL_TASK,
'object_ref': task_no,
'action': ACTION_RETRY_AUTO_PROGRESS,
'outcome': 'failed',
'reason_code': 'SHIPPING.MODULE_IMPORT_ERROR',
'metadata': {
'p13_category': 'e_formal_ot',
'import_error': type(mod_err).__name__,
},
}
except Exception: # noqa: BLE001
_LOGGER.exception('conversation task retry failed task_no=%s', task_no)
@@ -391,6 +811,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
'action': ACTION_RETRY_AUTO_PROGRESS,
'outcome': 'failed',
'reason_code': 'SHIPPING.AUTO_PROGRESS_FAILED',
'metadata': {'p13_category': 'e_formal_ot'},
}
status = str((result or {}).get('status') or '').strip().lower()
@@ -402,6 +823,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
'action': action,
'outcome': 'skipped',
'reason_code': str((result or {}).get('reason_code') or 'human_blocking'),
'metadata': {'p13_category': 'e_formal_ot'},
}
if status == 'failed':
return {
@@ -410,6 +832,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
'action': action,
'outcome': 'failed',
'reason_code': str((result or {}).get('reason_code') or status),
'metadata': {'p13_category': 'e_formal_ot'},
}
if action == 'noop' and str((result or {}).get('reason_code') or '') == 'already_running':
return {
@@ -418,6 +841,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
'action': action,
'outcome': 'skipped',
'reason_code': 'already_running',
'metadata': {'p13_category': 'e_formal_ot'},
}
if action == 'noop' and status == 'completed':
return {
@@ -426,6 +850,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
'action': action,
'outcome': 'skipped',
'reason_code': str((result or {}).get('reason_code') or 'already_completed'),
'metadata': {'p13_category': 'e_formal_ot'},
}
if status in {'running', 'completed', 'queued'}:
return {
@@ -434,6 +859,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
'action': action,
'outcome': 'queued',
'reason_code': None,
'metadata': {'p13_category': 'e_formal_ot'},
}
return {
'object_type': OBJECT_FORMAL_TASK,
@@ -441,6 +867,7 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]:
'action': action,
'outcome': 'skipped',
'reason_code': str((result or {}).get('reason_code') or status or 'not_retryable'),
'metadata': {'p13_category': 'e_formal_ot'},
}
@@ -0,0 +1,231 @@
"""
services/shipping_notice/document_layout/coordinate_region_source_adapter.py
用途:CoordinateRegionSourceAdapter——将 Profile.named_regions 圈选的物理区域映射为
可直接送入 Split Core 的区域原文 + 可引用 bbox 证据(page_no + 绝对坐标)。
依赖:profile_vendor_comments_contract.NamedRegion;coordinate_region_text.read_coordinate_region_text
与 visual_glyph_rows + positioned_token_spans(证据粒度生成)。
逻辑:不读 MinIO、不查 DB;只接收 caller 已加载的 glyphs/page 字典;严格按 Q14 约定
page_scope 规则选择「代表页」——last_page 时从多页集合取末页;失败不抛错,统一
返回 status=unavailable + 诊断码,供上游 ProfileFieldSourceMappingService 分支处理。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal
from app.services.shipping_notice.document_layout.coordinate_region_text import (
positioned_token_spans,
read_coordinate_region_text,
)
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
NamedRegion,
)
@dataclass
class CoordinateRegionEvidence:
"""单个命中的 token 级证据——供 Observation.evidence_metadata_json 直接序列化。"""
page_no: int
text: str
x0: float # 0..1 归一化
x1: float
y0: float
y1: float
@dataclass
class CoordinateRegionSourceResult:
"""区域抽取结果——对齐 Split Core 结果形状但不做拆分,仅负责原文渲染。"""
region_id: str
label: str
status: Literal['available', 'unavailable']
page_no: int | None = None
raw_text: str = ''
lines: list[str] = field(default_factory=list)
evidence_tokens: list[CoordinateRegionEvidence] = field(default_factory=list)
diagnostic_code: str | None = None
diagnostic_message: str | None = None
class CoordinateRegionSourceAdapter:
"""
将 NamedRegion → 原文 + 证据的薄适配器。
【AI 触发时机】:三来源收集阶段,上游遍历 field_source_mappings[].vendor_comments_enabled
条目并引用命名区域 ID 时调用。
核心逻辑:
[STEP 1] 按 page_scope 从 page_glyphs_map 中选「代表页」:
first_page → pages[0];last_page → pages[-1];all_pages 只看 p0(仅用于区域);
exact_page → 严格匹配 1-based page_no。
[STEP 2] 调 read_coordinate_region_text 取区域原文(0..1 归一化坐标)。
[STEP 3] 调 positioned_token_spans 生成 token 级 bbox 证据,用于 Review 高亮点位。
[STEP 4] 原文按换行拆为 lines,供后续 execute_base_split_rule_set(..., lines=) 复用。
Args:
region: NamedRegion 契约对象(已通过 validate_assignment 校验)。
page_glyphs_map: {1-based_page_no: {'glyphs': [...], 'page': {'width','height'}}} ——
caller 负责按当前 Document 加载,本类无网络 IO。
"""
def __init__(self, region: NamedRegion, page_glyphs_map: dict[int, dict[str, Any]]):
self.region = region
self.page_glyphs_map = page_glyphs_map
# ------------------------------------------------------------------
# 对外入口
# ------------------------------------------------------------------
def extract(self) -> CoordinateRegionSourceResult:
"""
执行区域抽取。失败不抛异常,统一置 status=unavailable + 稳定诊断码。
Returns:
CoordinateRegionSourceResult,上游据此决定是否跳过 Vendor Comments 来源。
"""
# [STEP 1] 选择代表页
page_no = self._resolve_representative_page_no()
if page_no is None:
return CoordinateRegionSourceResult(
region_id=self.region.region_id,
label=self.region.label,
status='unavailable',
diagnostic_code='named_region_page_not_found',
diagnostic_message=(
f'named region {self.region.region_id!r} page_scope={self.region.page_scope} '
f'page_no={self.region.page_no!r} has no loaded page'
),
)
page_bundle = self.page_glyphs_map[page_no]
glyphs = list(page_bundle.get('glyphs') or [])
page = dict(page_bundle.get('page') or {})
if not glyphs or 'width' not in page or 'height' not in page:
return CoordinateRegionSourceResult(
region_id=self.region.region_id,
label=self.region.label,
status='unavailable',
page_no=page_no,
diagnostic_code='named_region_empty_glyphs',
diagnostic_message='region target page has empty glyphs or missing page size',
)
region_coords = {
'x0': self.region.region.x0, 'y0': self.region.region.y0,
'x1': self.region.region.x1, 'y1': self.region.region.y1,
}
# [STEP 2] 渲染区域原文
raw_text = read_coordinate_region_text(
glyphs=glyphs, page=page, region=region_coords,
)
if not raw_text.strip():
return CoordinateRegionSourceResult(
region_id=self.region.region_id,
label=self.region.label,
status='unavailable',
page_no=page_no,
diagnostic_code='named_region_text_empty',
diagnostic_message=f'named region {self.region.region_id!r} has empty body text',
)
# [STEP 3] 生成 token 级证据(只保留区域中心在 box 内的 token)
tokens = self._collect_region_evidence_tokens(
glyphs=glyphs, page=page, region_coords=region_coords, page_no=page_no,
)
# [STEP 4] 拆行
lines = [ln.strip() for ln in raw_text.splitlines() if ln.strip()]
return CoordinateRegionSourceResult(
region_id=self.region.region_id,
label=self.region.label,
status='available',
page_no=page_no,
raw_text=raw_text.strip(),
lines=lines,
evidence_tokens=tokens,
)
# ------------------------------------------------------------------
# 内部帮助
# ------------------------------------------------------------------
def _resolve_representative_page_no(self) -> int | None:
"""按 page_scope 规则选择代表页。"""
sorted_pages = sorted(self.page_glyphs_map.keys())
if not sorted_pages:
return None
scope = self.region.page_scope
if scope == 'first_page':
return sorted_pages[0]
if scope == 'last_page':
return sorted_pages[-1]
if scope == 'all_pages':
# all_pages 的命名区域仅在第一页渲染(常见全页 Header);
# 若管理员要取多页块,应拆为多个命名区域并使用 exact_page。
return sorted_pages[0]
if scope == 'exact_page':
return self.region.page_no if self.region.page_no in self.page_glyphs_map else None
return None
@staticmethod
def _collect_region_evidence_tokens(
*,
glyphs: list[dict[str, Any]],
page: dict[str, Any],
region_coords: dict[str, float],
page_no: int,
) -> list[CoordinateRegionEvidence]:
"""筛选命名区域中心范围内的 token,并返回 0..1 归一化 bbox。"""
width, height = float(page['width']), float(page['height'])
rx0, ry0, rx1, ry1 = (region_coords[k] for k in ('x0', 'y0', 'x1', 'y1'))
all_spans = positioned_token_spans(glyphs, respect_explicit_spaces=True)
selected: list[CoordinateRegionEvidence] = []
for span in all_spans:
sx0 = float(span['x0']) / width
sx1 = float(span['x1']) / width
text = str(span.get('text') or '')
# y 边界:span 只返回横向边界;glyphs 中心用于 y 判定
# positioned_token_spans 不返回 y,重算 y0/y1 需回溯原 glyph——这里直接用
# glyphs 子集重算以保证引用不泄漏。
matched = [
g for g in glyphs
if _glyph_intersects_span(g, span, width) and _glyph_in_region_center(g, width, height, rx0, ry0, rx1, ry1)
]
if not matched:
continue
min_y0 = min(float(g['bbox']['y0']) / height for g in matched)
max_y1 = max(float(g['bbox']['y1']) / height for g in matched)
selected.append(CoordinateRegionEvidence(
page_no=page_no,
text=text,
x0=sx0, x1=sx1,
y0=min_y0, y1=max_y1,
))
return selected
def _glyph_intersects_span(glyph: dict[str, Any], span: dict[str, Any], width: float) -> bool:
try:
gx0 = float(glyph['bbox']['x0']) / width
gx1 = float(glyph['bbox']['x1']) / width
except (KeyError, TypeError, ValueError):
return False
return min(gx1, float(span['x1']) / width) > max(gx0, float(span['x0']) / width)
def _glyph_in_region_center(
glyph: dict[str, Any], width: float, height: float,
rx0: float, ry0: float, rx1: float, ry1: float,
) -> bool:
try:
b = glyph['bbox']
cx = (float(b['x0']) + float(b['x1'])) / (2 * width)
cy = (float(b['y0']) + float(b['y1'])) / (2 * height)
except (KeyError, TypeError, ValueError):
return False
return rx0 <= cx <= rx1 and ry0 <= cy <= ry1
@@ -0,0 +1,935 @@
"""
services/shipping_notice/document_layout/field_split_core.py
用途:共享的声明式字段拆分核心——承接 XFA(XML Forms Architecture)拆分引擎的纯文本执行能力,
为 Vendor Comments / Coordinate Region 等非 XFA 数据源提供统一的 prefix / regex / position
匹配、优先级仲裁、多规则冲突诊断、mapped/evidence_only 处理与规则内容指纹。
依赖:Pydantic 2、xfa_contract(复用 XfaContractModel 作为 Base Model 保持一致性)、
xfa_safe_regex(危险正则黑名单、超时限制、最大捕获组校验)。
逻辑:对外暴露 BaseSplit* 契约与 execute_base_split_rule_set() 执行入口;
XFA 链路通过 XfaSplit* extends BaseSplit* 复用本核心;Vendor Comments 链路直接使用 BaseSplit*;
本文件不得 import 任何 XFA 专属的 dataset/packet/leaf 节点(保持纯文本拆分引擎定位);
relation_capture 在此阶段仅在 core 内部捕获;XFA 适配器转换时丢弃(Q16 方案 A)。
"""
from __future__ import annotations
import json
import os
import re
import uuid
from dataclasses import dataclass, field
from typing import Any, Final, Literal
from pydantic import AliasChoices, Field, field_validator, model_validator
from app.services.shipping_notice.document_layout.xfa_contract import XfaContractModel
from app.services.shipping_notice.document_layout.xfa_safe_regex import (
SafeRegexError,
compile_safe_regex,
search_safe,
validate_restricted_regex_pattern,
)
# ---------------------------------------------------------------------------
# [STEP 0] 资源上限默认值——与 XFA 拆分保持同一量级,可由 settings / 环境变量覆盖
# ---------------------------------------------------------------------------
SPLIT_MAX_RULES_PER_SET: Final[int] = 32
SPLIT_MAX_RULE_SETS: Final[int] = 64
SPLIT_MAX_REGEX_PATTERN_LENGTH: Final[int] = 128
SPLIT_MAX_REGEX_GROUPS: Final[int] = 5
SPLIT_MAX_PREFIX_LENGTH: Final[int] = 64
SPLIT_MAX_SEGMENT_CODE_LENGTH: Final[int] = 64
SPLIT_MAX_DISPLAY_NAME_LENGTH: Final[int] = 128
SPLIT_MAX_INPUT_LENGTH: Final[int] = 32_768
SPLIT_REGEX_TIMEOUT_MS: Final[int] = 50
# 引擎固定匹配优先级(数值越小优先级越高)——与 XFA 拆分引擎保持一致,避免共享核心引入漂移
SPLIT_MATCHER_PRIORITY: Final[dict[str, int]] = {
'prefix': 0,
'regex': 1,
'position': 2,
}
SPLIT_UNMATCHED_PRIORITY: Final[int] = 3
SplitHandling = Literal['mapped', 'evidence_only']
SplitMatcherType = Literal['position', 'prefix', 'regex']
SplitSourceScope = Literal['header', 'line']
SplitUnmatchedPolicy = Literal['evidence_only', 'needs_review']
SplitDuplicatePolicy = Literal['needs_review']
SplitRuleStatus = Literal['draft', 'confirmed', 'published']
SplitRuleSource = Literal['system_suggestion', 'user', 'imported']
RelationCaptureType = Literal['line_reference']
RelationPolicyType = Literal['bind_target_line', 'annotation_only']
_SEGMENT_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
def _config_int(key: str, default: int) -> int:
"""
从 Flask config 或环境变量读取整型配置。
Args:
key: 配置键名。
default: 缺失时的默认值。
Returns:
解析后的正整数。
"""
try:
from flask import has_app_context, current_app
if has_app_context():
raw = current_app.config.get(key)
if raw is not None:
return max(1, int(raw))
except Exception:
pass
raw_env = os.getenv(key)
if raw_env is not None and str(raw_env).strip():
return max(1, int(raw_env))
return default
def get_split_max_rules_per_set() -> int:
"""单规则集最大 rules 条数。"""
return _config_int('SPLIT_MAX_RULES_PER_SET', SPLIT_MAX_RULES_PER_SET)
def get_split_max_rule_sets() -> int:
"""Profile 最大 split_rules 规则集数。"""
return _config_int('SPLIT_MAX_RULE_SETS', SPLIT_MAX_RULE_SETS)
def get_split_max_regex_pattern_length() -> int:
"""单条正则模式最大长度。"""
return _config_int('SPLIT_MAX_REGEX_PATTERN_LENGTH', SPLIT_MAX_REGEX_PATTERN_LENGTH)
def get_split_max_regex_groups() -> int:
"""正则最大捕获组数。"""
return _config_int('SPLIT_MAX_REGEX_GROUPS', SPLIT_MAX_REGEX_GROUPS)
def get_split_max_prefix_length() -> int:
"""前缀标签最大长度。"""
return _config_int('SPLIT_MAX_PREFIX_LENGTH', SPLIT_MAX_PREFIX_LENGTH)
def get_split_max_input_length() -> int:
"""拆分源字段最大输入长度。"""
return _config_int('SPLIT_MAX_INPUT_LENGTH', SPLIT_MAX_INPUT_LENGTH)
def get_split_regex_timeout_ms() -> int:
"""正则执行超时(毫秒)。"""
return _config_int('SPLIT_REGEX_TIMEOUT_MS', SPLIT_REGEX_TIMEOUT_MS)
# ---------------------------------------------------------------------------
# [STEP 1] 共享 Base 契约——剥离 XFA 专属 path_id / data_path / source_field_code
# ---------------------------------------------------------------------------
class RelationCaptureDef(XfaContractModel):
"""
可选:在规则命中时额外捕获"与目标字段相关的关系元数据"。
【AI 触发时机】:当 Profile 需要"先从备注提取值、再从同一句备注提取行号/关联号作为目标绑定依据"时,
在 BaseSplitMatcher 上配置本定义。
核心逻辑:和 value 捕获同一条正则或前缀行;但关系元数据不参与 mapped/evidence_only 的 target 决策,
关系如何解释由上层 Mapping 的 relation_policy 决定(Q2 双层设计)。
"""
type: RelationCaptureType = 'line_reference'
capture_group: int = Field(ge=0, le=SPLIT_MAX_REGEX_GROUPS)
labels: list[str] = Field(default_factory=list, max_length=16)
@model_validator(mode='after')
def validate_labels(self) -> 'RelationCaptureDef':
"""labels 去重,禁止空字符串。"""
cleaned = [str(item).strip() for item in (self.labels or []) if str(item).strip()]
object.__setattr__(self, 'labels', list(dict.fromkeys(cleaned)))
return self
class BaseSplitSegment(XfaContractModel):
"""共享拆分段:与 Schema 字段分离;mapped 时绑定冻结 Schema。"""
segment_id: str = Field(min_length=8, max_length=64)
segment_code: str = Field(min_length=2, max_length=SPLIT_MAX_SEGMENT_CODE_LENGTH)
display_name: str = Field(min_length=1, max_length=SPLIT_MAX_DISPLAY_NAME_LENGTH)
handling: SplitHandling
target_field_id: str | None = Field(default=None, max_length=64)
target_field_code: str | None = Field(default=None, max_length=128)
note: str | None = Field(default=None, max_length=256)
@field_validator('segment_code', mode='before')
@classmethod
def validate_segment_code(cls, value: Any) -> str:
"""segment_code 必须为小写蛇形,Profile 内唯一由上层校验。"""
code = str(value or '').strip()
if not _SEGMENT_CODE_RE.fullmatch(code):
raise ValueError(
'segment_code must be lowercase snake_case starting with a letter',
)
return code
@model_validator(mode='after')
def validate_handling_targets(self) -> 'BaseSplitSegment':
"""mapped 必须绑定目标字段;evidence_only 禁止目标字段。"""
if self.handling == 'mapped':
if not self.target_field_id or not self.target_field_code:
raise ValueError('mapped segment requires target_field_id and target_field_code')
else:
if self.target_field_id or self.target_field_code:
raise ValueError('evidence_only segment must not set target fields')
return self
class BaseSplitMatcher(XfaContractModel):
"""
共享单行匹配器:position / prefix / regex。
优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。
新增 relation_capture:当前仅 line_reference(Q2);XFA 链路当前不启用,
但 Base 契约提前引入避免阶段 2 再次改造。
"""
type: SplitMatcherType
line_index: int | None = Field(default=None, ge=1, le=1000)
value: str | None = Field(default=None, max_length=SPLIT_MAX_PREFIX_LENGTH)
separators: list[str] = Field(default_factory=lambda: [':', ':'])
case_sensitive: bool = False
pattern: str | None = Field(default=None, max_length=SPLIT_MAX_REGEX_PATTERN_LENGTH)
capture_group: int | None = Field(default=None, ge=0, le=SPLIT_MAX_REGEX_GROUPS)
relation_capture: RelationCaptureDef | None = None
@model_validator(mode='after')
def validate_matcher_shape(self) -> 'BaseSplitMatcher':
"""按 type 校验必填字段、前缀与正则安全边界。"""
max_prefix = get_split_max_prefix_length()
max_pattern_len = get_split_max_regex_pattern_length()
max_groups = get_split_max_regex_groups()
if self.type == 'position':
if self.line_index is None:
raise ValueError('position matcher requires line_index (1-based)')
elif self.type == 'prefix':
label = str(self.value or '').strip()
if not label:
raise ValueError('prefix matcher requires non-empty value')
if len(label) > max_prefix:
raise ValueError('prefix value exceeds max length')
seps = [str(item) for item in (self.separators or []) if str(item)]
if not seps:
raise ValueError('prefix matcher requires at least one separator')
object.__setattr__(self, 'separators', seps)
object.__setattr__(self, 'value', label)
elif self.type == 'regex':
pattern = str(self.pattern or '')
if not pattern:
raise ValueError('regex matcher requires pattern')
if len(pattern) > max_pattern_len:
raise ValueError('regex pattern exceeds max length')
try:
validate_restricted_regex_pattern(
pattern,
max_length=max_pattern_len,
max_groups=max_groups,
)
except SafeRegexError as exc:
raise ValueError(str(exc)) from exc
if self.capture_group is not None and self.capture_group > max_groups:
raise ValueError('capture_group exceeds pattern groups limit')
if self.relation_capture is not None and self.relation_capture.capture_group > max_groups:
raise ValueError('relation_capture.capture_group exceeds pattern groups limit')
else:
raise ValueError(f'unsupported matcher type: {self.type}')
return self
class BaseSplitRule(XfaContractModel):
"""共享单条拆分规则:rule_id + matcher + segment(无 stages[])。"""
rule_id: str = Field(min_length=1, max_length=64)
matcher: BaseSplitMatcher
segment: BaseSplitSegment
class BaseSplitNormalization(XfaContractModel):
"""规则集级换行与 trim 策略:引擎按 line_breaks 拆行后再逐行匹配。"""
trim: bool = True
remove_empty_lines: bool = True
line_breaks: list[str] = Field(default_factory=lambda: ['\r\n', '\r', '\n'])
@model_validator(mode='after')
def validate_breaks(self) -> 'BaseSplitNormalization':
"""line_breaks 不可为空。"""
breaks = [str(item) for item in (self.line_breaks or []) if str(item)]
if not breaks:
raise ValueError('normalization.line_breaks requires at least one value')
object.__setattr__(self, 'line_breaks', breaks)
return self
class BaseSplitRuleSet(XfaContractModel):
"""
共享规则集:针对单一源文本的拆分规则集合。
不含 XFA 专属的 source_path_id / source_data_path / source_field_code,
这些由 XfaSplitRuleSet extends 本类后追加。
"""
rule_set_id: str = Field(
min_length=1,
max_length=128,
validation_alias=AliasChoices('rule_set_id', 'rule_id'),
)
rule_version: int = Field(ge=1, le=10_000)
normalization: BaseSplitNormalization = Field(default_factory=BaseSplitNormalization)
rules: list[BaseSplitRule] = Field(default_factory=list)
unmatched_line_policy: SplitUnmatchedPolicy = 'evidence_only'
duplicate_match_policy: SplitDuplicatePolicy = 'needs_review'
same_field_multiple_segment_policy: SplitDuplicatePolicy = 'needs_review'
source: SplitRuleSource = 'user'
status: SplitRuleStatus = 'draft'
requires_confirmation: bool = False
@property
def rule_id(self) -> str:
"""兼容旧字段名 rule_id(等同 rule_set_id)。"""
return self.rule_set_id
@model_validator(mode='after')
def validate_rule_set_invariants(self) -> 'BaseSplitRuleSet':
"""规则集内唯一性与数量上限。"""
max_rules = get_split_max_rules_per_set()
if len(self.rules) > max_rules:
raise ValueError(f'rules exceed max {max_rules}')
rule_ids = [item.rule_id for item in self.rules]
if len(rule_ids) != len(set(rule_ids)):
raise ValueError('duplicate rule_id within split rule set')
segment_ids = [item.segment.segment_id for item in self.rules]
if len(segment_ids) != len(set(segment_ids)):
raise ValueError('duplicate segment_id within split rule set')
segment_codes = [item.segment.segment_code for item in self.rules]
if len(segment_codes) != len(set(segment_codes)):
raise ValueError('duplicate segment_code within split rule set')
if self.source == 'system_suggestion':
if self.status != 'draft' or not self.requires_confirmation:
raise ValueError(
'system_suggestion must be draft with requires_confirmation=true',
)
return self
def new_segment_id() -> str:
"""
生成不可变 segment_id。
Returns:
形如 seg-<uuid4hex> 的稳定标识。
"""
return f'seg-{uuid.uuid4().hex}'
def new_rule_id(prefix: str = 'rule') -> str:
"""
生成规则条目 ID。
Args:
prefix: ID 前缀。
Returns:
形如 ``{prefix}-<hex>`` 的标识。
"""
safe = re.sub(r'[^a-z0-9_]+', '_', str(prefix or 'rule').strip().lower()) or 'rule'
return f'{safe}-{uuid.uuid4().hex[:12]}'
def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any]) -> str:
"""
计算共享规则集内容指纹(排除 status / requires_confirmation / rule_version / handling/targets)。
核心逻辑:只冻结 matcher、normalization 与 relation_capture 定义;
segment 的 Schema 映射字段(handling/target_field_*)不属于拆分逻辑本身,
后续绑定或解绑目标字段不得取消已确认状态。
Args:
rule_set: 模型或 dict。
Returns:
稳定 JSON 字符串指纹素材(调用方可再 hash)。
"""
if isinstance(rule_set, BaseSplitRuleSet):
payload = rule_set.model_dump(mode='json', by_alias=True)
else:
payload = dict(rule_set or {})
if 'rule_set_id' not in payload and payload.get('rule_id'):
payload['rule_set_id'] = payload['rule_id']
payload.pop('status', None)
payload.pop('requires_confirmation', None)
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(segment, dict):
continue
segment.pop('handling', None)
segment.pop('target_field_id', None)
segment.pop('target_field_code', None)
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
# ---------------------------------------------------------------------------
# [STEP 2] 共享核心执行——纯 dataclass 中间结果,不暴露给 XFA 对外 API
# ---------------------------------------------------------------------------
@dataclass
class CoreCapturedRelation:
"""核心层捕获到的关系元数据(Q2 双层设计 rule/matcher 层)。"""
type: RelationCaptureType
line_no: int | None
raw_text: str | None
@dataclass
class _CoreSegmentResult:
"""单段执行结果(核心层,含 captured_relation;XFA 适配后丢弃)。"""
segment_id: str
segment_code: str
display_name: str
line_no: int | None
line_end_no: int | None
raw_text: str
normalized_text: str
handling: str
target_field_id: str | None
target_field_code: str | None
rule_id: str
status: str
matcher_type: str
captured_relation: CoreCapturedRelation | None = None
@dataclass
class CoreSplitDiagnostic:
"""共享核心规则执行诊断。"""
code: str
message: str
line_no: int | None = None
field_code: str | None = None
rule_ids: list[str] = field(default_factory=list)
@dataclass
class _CoreSplitEngineResult:
"""共享核心引擎输出。"""
status: str
segments: list[_CoreSegmentResult] = field(default_factory=list)
mapped_fields: dict[str, str] = field(default_factory=dict)
evidence_only_segments: list[_CoreSegmentResult] = field(default_factory=list)
diagnostics: list[CoreSplitDiagnostic] = field(default_factory=list)
rule_set_id: str | None = None
rule_version: int | None = None
@dataclass
class _LineMatch:
"""单行候选命中(共享核心版,含 relation 捕获)。"""
rule: BaseSplitRule
matcher_type: str
priority: int
line_text: str
normalized_text: str
raw_line: str
captured_relation: CoreCapturedRelation | None = None
# ---------------------------------------------------------------------------
# [STEP 3] 纯文本执行函数——从 XFA 拆分引擎原封不动迁移,保持字节级一致
# ---------------------------------------------------------------------------
def _split_text_by_breaks(text: str, line_breaks: list[str]) -> list[str]:
"""
按声明的 line_breaks 切分文本(长分隔符优先)。
Args:
text: 原始文本。
line_breaks: 换行符列表。
Returns:
切分后的行列表(尚未 trim / 去空行)。
"""
if not text:
return []
pattern = '|'.join(re.escape(item) for item in sorted(line_breaks, key=len, reverse=True))
if not pattern:
return [text]
return re.split(pattern, text)
def _apply_line_normalization(
lines: list[str],
*,
trim: bool,
remove_empty_lines: bool,
) -> list[str]:
"""对行列表应用 trim / 去空行。"""
out = list(lines)
if trim:
out = [item.strip() for item in out]
if remove_empty_lines:
out = [item for item in out if item]
return out
def _inventory_lines(raw_value: str, rule_set: BaseSplitRuleSet) -> list[str]:
"""
用规则集级 normalization 生成行清单。
核心逻辑:按 normalization.line_breaks 拆行并应用 trim / 去空行。
"""
norm = rule_set.normalization
lines = _split_text_by_breaks(raw_value or '', list(norm.line_breaks))
return _apply_line_normalization(
lines,
trim=bool(norm.trim),
remove_empty_lines=bool(norm.remove_empty_lines),
)
def _extract_prefix_value(line: str, matcher: BaseSplitMatcher) -> str | None:
"""
前缀匹配:标签 + 分隔符后的值。
Returns:
提取值;无法匹配时 None。
"""
label = str(matcher.value or '')
hay = line if matcher.case_sensitive else line.casefold()
needle = label if matcher.case_sensitive else label.casefold()
if not hay.startswith(needle):
return None
rest = line[len(label):]
for sep in matcher.separators:
if rest.startswith(sep):
return rest[len(sep):].strip()
stripped = rest.lstrip()
if stripped.startswith(sep):
return stripped[len(sep):].strip()
return None
def _regex_extract_value_and_relation(
line: str,
matcher: BaseSplitMatcher,
) -> tuple[str | None, CoreCapturedRelation | None, str | None]:
"""
正则捕获单行文本的值与可选 relation。
Returns:
(value, captured_relation, error_code);成功时 error_code 为 None。
"""
pattern = str(matcher.pattern or '')
timeout_ms = get_split_regex_timeout_ms()
max_len = get_split_max_regex_pattern_length()
max_groups = get_split_max_regex_groups()
try:
compiled = compile_safe_regex(
pattern,
case_sensitive=bool(matcher.case_sensitive),
max_length=max_len,
max_groups=max_groups,
)
matched = search_safe(compiled, line, timeout_ms=timeout_ms)
except SafeRegexError:
return None, None, 'regex_failed'
except TimeoutError:
return None, None, 'regex_timeout'
if not matched:
return None, None, 'regex_not_matched'
group = matcher.capture_group
try:
if group is None:
if matched.lastindex:
value = str(matched.group(1) or '').strip()
else:
value = str(matched.group(0) or '').strip()
else:
value = str(matched.group(group) or '').strip()
except IndexError:
return None, None, 'regex_failed'
relation: CoreCapturedRelation | None = None
rc = matcher.relation_capture
if rc is not None:
try:
rel_raw = matched.group(rc.capture_group)
rel_text = str(rel_raw or '').strip() if rel_raw is not None else None
rel_line_no: int | None = None
if rel_text:
m = re.search(r'(\d{1,6})', rel_text)
if m:
rel_line_no = int(m.group(1))
relation = CoreCapturedRelation(
type=rc.type,
line_no=rel_line_no,
raw_text=rel_text,
)
except (IndexError, ValueError):
relation = None
return value, relation, None
def _match_line(
line_no: int,
line: str,
rule: BaseSplitRule,
) -> tuple[_LineMatch | None, str | None]:
"""
判断单条规则是否命中指定行(共享核心版,支持 relation 捕获)。
Returns:
(match, error_code):命中时 error_code 为 None;未命中时 match 为 None。
"""
matcher = rule.matcher
priority = SPLIT_MATCHER_PRIORITY.get(matcher.type)
if priority is None:
return None, 'unknown_matcher'
if matcher.type == 'position':
if int(matcher.line_index or 0) != line_no:
return None, None
normalized = line.strip() if line else ''
return _LineMatch(
rule=rule,
matcher_type='position',
priority=priority,
line_text=line,
normalized_text=normalized,
raw_line=line,
), None
if matcher.type == 'prefix':
extracted = _extract_prefix_value(line, matcher)
if extracted is None:
return None, None
return _LineMatch(
rule=rule,
matcher_type='prefix',
priority=priority,
line_text=line,
normalized_text=extracted,
raw_line=line,
), None
if matcher.type == 'regex':
value, relation, err = _regex_extract_value_and_relation(line, matcher)
if err:
return None, err
if value is None:
return None, None
return _LineMatch(
rule=rule,
matcher_type='regex',
priority=priority,
line_text=line,
normalized_text=value,
raw_line=line,
captured_relation=relation,
), None
return None, 'unknown_matcher'
def _pick_line_winner(
line_no: int,
matches: list[_LineMatch],
diagnostics: list[CoreSplitDiagnostic],
) -> _LineMatch | None:
"""
按 prefix > regex > position 决出单行唯一胜出规则。
核心逻辑:同优先级多个 mapped 命中 → duplicate_line_match;不同优先级取最高优先级。
"""
if not matches:
return None
diagnostics.append(CoreSplitDiagnostic(
code='line_match_candidates',
message='All matcher hits for line recorded',
line_no=line_no,
rule_ids=[item.rule.rule_id for item in matches],
))
best_priority = min(item.priority for item in matches)
tier = [item for item in matches if item.priority == best_priority]
mapped_tier = [item for item in tier if item.rule.segment.handling == 'mapped']
if len(mapped_tier) >= 2:
diagnostics.append(CoreSplitDiagnostic(
code='duplicate_line_match',
message='Multiple mapped rules matched the same line at the same priority',
line_no=line_no,
rule_ids=[item.rule.rule_id for item in mapped_tier],
))
if len(tier) == 1:
return tier[0]
if len(mapped_tier) == 1:
return mapped_tier[0]
if len(mapped_tier) >= 2:
return sorted(mapped_tier, key=lambda item: item.rule.rule_id)[0]
return sorted(tier, key=lambda item: item.rule.rule_id)[0]
def execute_base_split_rule_set(
*,
raw_value: str,
rule_set: BaseSplitRuleSet,
lines: list[str] | None = None,
) -> _CoreSplitEngineResult:
"""
对单个源文本原值执行共享拆分规则集。
核心逻辑:
1. normalization.line_breaks 拆行;
2. 逐行收集命中规则,按 prefix > regex > position 决出唯一 segment;
3. 同优先级多个 mapped 命中 → duplicate_line_match / needs_review;
4. 未认领行按 unmatched_line_policy;
5. evidence_only 全部保留;
6. relation_capture 在 core 层保留到 _CoreSegmentResult(上层适配决定是否丢弃)。
Args:
raw_value: 保留换行的原始文本(XFA 场景下是 leaf.raw_value;VC 场景下是区域原文)。
rule_set: 已校验共享规则集。
lines: 可选预切分行(覆盖 normalization 结果)。
Returns:
_CoreSplitEngineResult。
"""
if len(raw_value or '') > get_split_max_input_length():
return _CoreSplitEngineResult(
status='needs_review',
diagnostics=[CoreSplitDiagnostic(
code='input_too_long',
message='Split source value exceeds max input length',
)],
rule_set_id=rule_set.rule_set_id,
rule_version=rule_set.rule_version,
)
inventory = list(lines) if lines is not None else _inventory_lines(raw_value, rule_set)
diagnostics: list[CoreSplitDiagnostic] = []
segments: list[_CoreSegmentResult] = []
claimed_lines: set[int] = set()
# [STEP 1] 逐行匹配并按优先级决出胜出规则。
for line_no, line in enumerate(inventory, start=1):
matches: list[_LineMatch] = []
for rule in rule_set.rules:
outcome, error = _match_line(line_no, line, rule)
if error:
diagnostics.append(CoreSplitDiagnostic(
code=error,
message=f'Rule {rule.rule_id} regex failed on line {line_no}',
line_no=line_no,
field_code=rule.segment.target_field_code,
rule_ids=[rule.rule_id],
))
continue
if outcome is not None:
matches.append(outcome)
winner = _pick_line_winner(line_no, matches, diagnostics)
if winner is None:
continue
claimed_lines.add(line_no)
seg = winner.rule.segment
status = 'parsed'
if not str(winner.normalized_text).strip() and seg.handling == 'mapped':
status = 'needs_review'
diagnostics.append(CoreSplitDiagnostic(
code='mapped_value_empty',
message=f'Mapped segment {seg.segment_code} extracted empty value',
line_no=line_no,
field_code=seg.target_field_code,
rule_ids=[winner.rule.rule_id],
))
segments.append(_CoreSegmentResult(
segment_id=seg.segment_id,
segment_code=seg.segment_code,
display_name=seg.display_name,
line_no=line_no,
line_end_no=line_no,
raw_text=winner.raw_line,
normalized_text=winner.normalized_text,
handling=seg.handling,
target_field_id=seg.target_field_id,
target_field_code=seg.target_field_code,
rule_id=winner.rule.rule_id,
status=status,
matcher_type=winner.matcher_type,
captured_relation=winner.captured_relation,
))
# [STEP 2] 未匹配行。
for line_index, line in enumerate(inventory, start=1):
if line_index in claimed_lines:
continue
status = 'needs_review' if rule_set.unmatched_line_policy == 'needs_review' else 'parsed'
if status == 'needs_review':
diagnostics.append(CoreSplitDiagnostic(
code='unmatched_line',
message='Unmatched line requires review',
line_no=line_index,
))
segments.append(_CoreSegmentResult(
segment_id=f'unmatched-{line_index}',
segment_code=f'unmatched_line_{line_index}',
display_name=f'其他编码/{line_index}',
line_no=line_index,
line_end_no=line_index,
raw_text=line,
normalized_text=line.strip(),
handling='evidence_only',
target_field_id=None,
target_field_code=None,
rule_id='unmatched',
status=status,
matcher_type='unmatched',
))
# [STEP 3] 聚合正式字段。
mapped_fields: dict[str, str] = {}
field_sources: dict[str, list[str]] = {}
overall = 'parsed'
for item in segments:
if item.status == 'needs_review':
overall = 'needs_review'
if item.handling != 'mapped' or not item.target_field_code:
continue
code = item.target_field_code
field_sources.setdefault(code, []).append(item.rule_id)
if code in mapped_fields:
overall = 'needs_review'
diagnostics.append(CoreSplitDiagnostic(
code='same_field_multiple_segment',
message=f'Schema field {code} hit by multiple segments',
field_code=code,
rule_ids=list(field_sources[code]),
))
else:
mapped_fields[code] = item.normalized_text
for _code, sources in field_sources.items():
if len(sources) > 1 and rule_set.same_field_multiple_segment_policy == 'needs_review':
overall = 'needs_review'
if any(d.code == 'duplicate_line_match' for d in diagnostics):
if rule_set.duplicate_match_policy == 'needs_review':
overall = 'needs_review'
if any(d.code in {
'regex_timeout', 'regex_failed', 'mapped_value_empty', 'input_too_long',
} for d in diagnostics):
overall = 'needs_review'
evidence_only = [item for item in segments if item.handling == 'evidence_only']
return _CoreSplitEngineResult(
status=overall,
segments=segments,
mapped_fields=mapped_fields,
evidence_only_segments=evidence_only,
diagnostics=diagnostics,
rule_set_id=rule_set.rule_set_id,
rule_version=rule_set.rule_version,
)
def project_base_split_result_safe(
result: _CoreSplitEngineResult,
*,
include_full_values: bool = False,
mask_value_for_dto_fn: Any = None,
) -> dict[str, Any]:
"""
将共享核心引擎结果投影为普通 DTO。
核心逻辑:默认脱敏 mapped/segment 文本;仅当调用方已通过敏感读权限且
include_full_values=True 时返回 raw_text / 完整 mapped 值。
Args:
result: 引擎输出。
include_full_values: 是否返回完整业务值(需上游权限门禁)。
mask_value_for_dto_fn: 可选脱敏函数;None 时使用恒等函数。
Returns:
JSON 可序列化 dict。
"""
def _text(value: str) -> str:
if include_full_values:
return str(value)
if mask_value_for_dto_fn is not None:
try:
return mask_value_for_dto_fn(value)
except Exception:
return str(value)
return str(value)
mapped = {
code: _text(value)
for code, value in result.mapped_fields.items()
}
return {
'status': result.status,
'rule_set_id': result.rule_set_id,
'rule_version': result.rule_version,
'full_values_revealed': bool(include_full_values),
'mapped_fields': mapped,
'segments': [
{
'segment_id': item.segment_id,
'segment_code': item.segment_code,
'display_name': item.display_name,
'line_no': item.line_no,
'line_end_no': item.line_end_no,
'raw_text': _text(item.raw_text),
'normalized_text': _text(item.normalized_text),
'handling': item.handling,
'target_field_id': item.target_field_id,
'target_field_code': item.target_field_code,
'rule_id': item.rule_id,
'status': item.status,
'matcher_type': item.matcher_type,
}
for item in result.segments
],
'evidence_only_segments': [],
'diagnostics': [
{
'code': item.code,
'message': item.message,
'line_no': item.line_no,
'field_code': item.field_code,
'rule_ids': list(item.rule_ids),
}
for item in result.diagnostics
],
}
@@ -13,29 +13,15 @@ def _coordinate_mapping(value: Any) -> dict[str, Any]:
return dict(value) if isinstance(value, dict) else {}
def _append_issue(layout: dict[str, Any], issue: str) -> None:
"""稳定追加坐标恢复失败码,不改变原 issues 相对顺序。"""
existing = layout.get('issues') if isinstance(layout.get('issues'), list) else []
issues = [str(item) for item in existing]
if issue not in issues:
issues.append(issue)
layout['issues'] = issues
def ensure_on_demand_coordinate_evidence(
*, document: ShippingOrderDocument, layout: dict[str, Any], page_nos: set[int] | None,
table_by_page: dict[int, dict[str, Any] | list[dict[str, Any]]] | None = None,
) -> dict[str, Any]:
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。
【AI/调用方触发时机】:
- 订单字段重放、模板匹配或明细重建前,为当前 snapshot 恢复缺失页的真实坐标。
- 失败不静默;任何 PDFium/OCR 失败都会在 layout['issues'] 追加稳定失败码,
上游可据此将 matcher 从 no_match 转为 evidence_insufficient。
"""
"""为盲测和正式抽取恢复所需页坐标;同页多表必须分别保留字符证据。"""
if not document.asset_id or not str(document.filename or '').lower().endswith('.pdf'):
return layout
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
# 兼容历史布局快照:布局任务曾将坐标证据写在顶层,正式抽取仍需复用它。
if not evidence:
legacy_keys = ('pages', 'page_glyphs', 'sources', 'tables')
evidence = {
@@ -43,6 +29,7 @@ def ensure_on_demand_coordinate_evidence(
for key in legacy_keys
if isinstance(layout.get(key), dict)
}
# Run 快照可能早于最近一次布局重试;读取当前成功/失败版本仅作本次内存补充。
current_version = getattr(document, 'current_layout_version', None)
current_payload = getattr(current_version, 'payload_json', None)
if isinstance(current_payload, dict):
@@ -57,15 +44,7 @@ def ensure_on_demand_coordinate_evidence(
sources = _coordinate_mapping(evidence.get('sources'))
source_pages = _coordinate_mapping(sources.get('pages'))
tables = _coordinate_mapping(evidence.get('tables'))
# [FAIL-CLOSED GATE] page_glyphs 必须对所需页真实存在;不能用 pages 元数据或
# 非数字脏键来假装已恢复。MinerU HTML 表 + 空 page_glyphs 的组合必须继续走
# 真实 PDFium/OCR 抽取,否则会退化为"伪精确匹配分数"。
present_pages = {
int(key) for key in page_glyphs
if str(key).isdigit() and isinstance(page_glyphs.get(key), list) and len(page_glyphs.get(key) or []) > 0
}
needs_recovery = bool(page_nos is None) or not page_nos.issubset(present_pages)
if not needs_recovery:
if page_nos is not None and page_nos.issubset({int(p) for p in page_glyphs if str(p).isdigit()}):
return layout
tables_by_page: dict[int, list[dict[str, Any]]] = {}
for raw_table in layout.get('tables') or []:
@@ -91,15 +70,11 @@ def ensure_on_demand_coordinate_evidence(
)
asset = db.session.get(FileAsset, int(document.asset_id))
if asset is None:
_append_issue(layout, 'coordinate_evidence_asset_missing')
return layout
try:
native_pages = extract_native_pdf_pages(read_asset_bytes(asset))
except Exception:
# [FAIL-CLOSED] PDFium 级异常必须显式上报;禁止用 MinerU HTML 列名顶替坐标。
_append_issue(layout, 'coordinate_evidence_native_pdf_unavailable')
return layout
recovered_any_page = False
for page in native_pages:
if page_nos is not None and int(page.page_no) not in page_nos:
continue
@@ -112,14 +87,12 @@ def ensure_on_demand_coordinate_evidence(
source = 'ocr_coordinate'
except Exception:
glyphs = []
_append_issue(layout, f'coordinate_evidence_ocr_failed_page_{page.page_no}')
if not glyphs:
continue
page_key = str(page.page_no)
pages[page_key] = {'width': page.width, 'height': page.height}
page_glyphs[page_key] = glyphs
source_pages[page_key] = source
recovered_any_page = True
for table in tables_by_page.get(int(page.page_no), []):
table_id = str(table.get('table_id') or '')
chars = _native_characters_in_table(
@@ -134,8 +107,6 @@ def ensure_on_demand_coordinate_evidence(
chars = []
if table_id and chars:
tables[table_id] = chars
if page_nos is not None and not recovered_any_page:
_append_issue(layout, 'coordinate_evidence_no_page_recovered')
next_layout = dict(layout)
next_layout['coordinate_evidence'] = {
**evidence, 'pages': pages, 'page_glyphs': page_glyphs,
@@ -119,22 +119,7 @@ def match_frozen_coordinate_profiles(
pages = evidence.get('pages') if isinstance(evidence.get('pages'), dict) else {}
glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
page_glyphs = evidence.get('page_glyphs') if isinstance(evidence.get('page_glyphs'), dict) else {}
# [FAIL-CLOSED GATE] 第零层:on-demand 坐标恢复显式失败时直接拒绝匹配。
# 任何 coordinate_evidence_* 失败码都意味着正式证据不可用,MinerU HTML 列名
# 不得作为坐标模板匹配的替代事实源。
layout_issues = {str(item) for item in (layout.get('issues') or []) if str(item)}
coordinate_failure_issues = {
code for code in layout_issues if code.startswith('coordinate_evidence_')
}
if coordinate_failure_issues:
return ProfileMatchResult(status='evidence_insufficient')
# [FAIL-CLOSED GATE] 第一层:坐标字符证据必须至少有一种来源。
# MinerU HTML tables(layout['tables'])只有结构化列名、没有绝对坐标/bbox,
# 严禁单独充当坐标模板的匹配证据。否则会出现"MinerU 有列名但 matcher
# header_tokens=空、column_count=0、evidence_coverage 伪分数"的分裂。
if not pages:
return ProfileMatchResult(status='evidence_insufficient')
if not glyph_tables and not page_glyphs:
if not pages or (not glyph_tables and not page_glyphs and not tables):
return ProfileMatchResult(status='evidence_insufficient')
page_text = _layout_page_text(
@@ -216,25 +201,6 @@ def match_frozen_coordinate_profiles(
)
reason_codes.extend(hard_conflict_codes)
# [FAIL-CLOSED GATE] 第二层:身份证据缺失时,结构/几何维度不得独立构成模板命中。
# 用户场景:page_glyphs 虽有字符但观测不到 header_tokens 或
# column_centers;若签名冻结了核心列身份证据,就必须以身份优先、
# 结构辅助。否则 table_geometry + page_structure 的弱证据会掩盖
# "列名证据没有进入匹配器" 的真正问题。
signature_patterns = (
[item for item in (signature_body or {}).get('table_patterns') or [] if isinstance(item, dict)]
if signature_body is not None else []
)
signature_expects_identity = any(
bool(p.get('header_tokens') or p.get('column_centers') or (p.get('column_count') or 0) > 0)
for p in signature_patterns
)
observed_header = [str(item) for item in (observed.get('header_tokens') or []) if str(item).strip()]
observed_col_count = int(observed.get('column_count') or 0)
observed_has_identity = bool(observed_header) or observed_col_count > 0
if signature_expects_identity and not observed_has_identity:
reason_codes.append('profile_core_column_evidence_missing')
weights = profile.document_match.scoring_weights
score, evidence_coverage = _aggregate_dimension_score(weights=weights, dimension_results=dimension_results)
hard_match = not reason_codes
@@ -290,19 +256,6 @@ def match_frozen_coordinate_profiles(
status='no_match', candidates=rendered,
top1_score=top1_score, top2_score=top2_score, margin=margin,
)
# [FAIL-CLOSED GATE] 第三层:全局证据不足优先于 no_match / layout_drift。
# 当所有候选要么缺签名身份证据、要么观测不到核心列名/列坐标时,必须
# evidence_insufficient,禁止把"没证据"误报成"模板都不匹配"。
global_identity_missing = all(
'profile_core_column_evidence_missing' in item.reason_codes
or 'profile_signature_missing' in item.reason_codes
for item in rendered
)
if global_identity_missing:
return ProfileMatchResult(
status='evidence_insufficient', candidates=rendered,
top1_score=None, top2_score=None, margin=None,
)
if _any_special_profile_feature(candidates, page_text=page_text):
return ProfileMatchResult(
status='layout_drift', candidates=rendered,
@@ -0,0 +1,456 @@
"""
services/shipping_notice/document_layout/profile_field_source_mapping_service.py
用途:Profile 字段来源映射服务(Q18 抽取层裁决前置)——独立收集 Header / Table 列 /
Vendor Comments 三个来源的候选观察,**不直接写 Observation 表**,只返回统一的
FieldSourceCandidate 列表供 SourceMergeService 做 Q18 裁决合并。
依赖:profile_vendor_comments_contract(parse_field_source_mappings/parse_named_regions)、
field_split_core(execute_base_split_rule_set 用于 Vendor Comments 区域拆分)、
coordinate_region_source_adapter(CoordinateRegionSourceAdapter 物理区域渲染)、
reservation_relation_projection(ReservationRelationProjection 关系投影)。
逻辑:严格「后端决定 UI」——本类输出每个候选的 target_scope/target_field_code/
effective_line_no/value/source/evidence_ref/source_observation_metadata,
前端只能消费这些投影字段,禁止自行推导业务状态。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Literal
from app.services.shipping_notice.document_layout.coordinate_region_source_adapter import (
CoordinateRegionEvidence,
CoordinateRegionSourceAdapter,
CoordinateRegionSourceResult,
)
from app.services.shipping_notice.document_layout.field_split_core import (
CoreCapturedRelation,
_CoreSegmentResult,
execute_base_split_rule_set,
)
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
NamedRegion,
ProfileFieldSourceMapping,
parse_field_source_mappings,
parse_named_regions,
)
from app.services.shipping_notice.document_layout.reservation_relation_projection import (
ReservationRelationProjection,
ReservationRelationProjectionResult,
)
FieldSourceLiteral = Literal['header_region', 'table_column', 'vendor_comments']
@dataclass
class FieldSourceCandidate:
"""
单来源单观察候选——Header/Table/Vendor Comments 各自产出后,由 SourceMergeService 裁决。
【后端决定 UI】:scope、line_no、value、format_valid、conflict_group_key 全部在本层
计算完毕,前端只读投影,禁止自己用逻辑 if/else 推导。
"""
source: FieldSourceLiteral
target_scope: Literal['header', 'line']
target_field_code: str
target_field_id: str
value: str
normalized_value: str
format_valid: bool | None # None = 本字段不需要格式校验(非 reservation)
format_reason_code: str | None # format_valid=False 时的稳定诊断码(例:reservation_format_invalid)
effective_line_no: int | None # 1-based;header 时为 None;default_all_lines 时为具体行号
resolution_hint: Literal[
'provisional', 'annotation_only', 'invalid_line_reference',
] = 'provisional'
relation_projection: ReservationRelationProjectionResult | None = None
# 证据区——写入 Observation.evidence_quote / evidence_ref / evidence_metadata_json
evidence_quote: str | None = None
evidence_ref: str | None = None
evidence_metadata: dict[str, Any] = field(default_factory=dict)
# SourceMergeService 内部使用:冲突分组键 = (target_scope, target_field_code, effective_line_no)
conflict_group_key: tuple[Any, ...] = ()
class ProfileFieldSourceMappingService:
"""
三来源候选独立收集服务(路径判断与事实分离)。
【AI 触发时机】:订单文档抽取阶段(order_extraction_workflow 在 Observation 写入前)
调用 collect_candidates() 返回候选列表,再交给 SourceMergeService 裁决合并。
核心执行顺序:
[STEP 1] 解析 Profile definition_json 的 named_regions + field_source_mappings。
[STEP 2] 对每个 mapping:
a. header_source_enabled → 从 header_observations_by_source_ref 取现成观察
b. table_source_enabled → 从 table_column_values 取(column_code + line_index)
c. vendor_comments_enabled → 调 CoordinateRegionSourceAdapter + execute_base_split_rule_set
[STEP 3] 对每个 Vendor Comments 拆分结果,调 ReservationRelationProjection.project
生成 effective_line_no / resolution_hint。
[STEP 4] 返回 FieldSourceCandidate 列表;未通过 format_policy 的候选保留
value 但标记 format_valid=False(Q15:格式失败的值不丢弃)。
"""
def __init__(
self,
*,
definition_json: dict[str, Any],
header_observations_by_source_ref: dict[str, list[dict[str, Any]]] | None = None,
table_column_values: dict[str, list[dict[str, Any]]] | None = None,
page_glyphs_map: dict[int, dict[str, Any]] | None = None,
# Reservation Relation Projection 三层判定表
explicit_line_column_values: dict[int, str] | None = None,
profile_business_line_numbers: dict[int, Any] | None = None,
classified_logical_line_numbers: dict[int, int] | None = None,
total_logical_lines: int = 0,
# 格式策略调用方(保留注入点,避免本类直接 import reservation 校验模块造成循环)
format_validator_callback=None,
):
self.definition_json = definition_json or {}
self.header_observations_by_source_ref = header_observations_by_source_ref or {}
self.table_column_values = table_column_values or {}
self.page_glyphs_map = page_glyphs_map or {}
self.explicit_line_column_values = explicit_line_column_values or {}
self.profile_business_line_numbers = profile_business_line_numbers or {}
self.classified_logical_line_numbers = classified_logical_line_numbers or {}
self.total_logical_lines = total_logical_lines
self.format_validator_callback = format_validator_callback
# 预先解析契约(若失败抛 ValidationError 阻断运行,避免输出坏数据)
self.named_regions: dict[str, NamedRegion] = parse_named_regions(
self.definition_json.get('named_regions'),
)
self.mappings: list[ProfileFieldSourceMapping] = parse_field_source_mappings(
self.definition_json.get('field_source_mappings'),
)
# ------------------------------------------------------------------
# 对外主入口
# ------------------------------------------------------------------
def collect_candidates(self) -> list[FieldSourceCandidate]:
"""
返回全量候选。任何内部失败都返回稳定 status 候选(不抛错阻断其他字段)。
调用方:SourceMergeService.merge_and_decide() → 再调用 obs 写入。
"""
candidates: list[FieldSourceCandidate] = []
for mapping in self.mappings:
if mapping.header_source_enabled and mapping.header_source_ref:
candidates.extend(self._collect_header_source(mapping))
if mapping.table_source_enabled and mapping.table_column_code:
candidates.extend(self._collect_table_source(mapping))
if mapping.vendor_comments_enabled and mapping.vendor_comments_region_ref:
candidates.extend(self._collect_vendor_comments_source(mapping))
for cand in candidates:
cand.conflict_group_key = (cand.target_scope, cand.target_field_code, cand.effective_line_no)
return candidates
# ------------------------------------------------------------------
# 三个来源分支(独立收集,不互相读数据——满足 Q18 先独立再裁决)
# ------------------------------------------------------------------
def _collect_header_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
"""Header 区域来源——从 caller 传入的 header_observations_by_source_ref 读取。"""
header_items = self.header_observations_by_source_ref.get(mapping.header_source_ref or '', [])
results: list[FieldSourceCandidate] = []
for item in header_items:
raw_value = str(item.get('value') or '')
format_valid, reason = self._check_format(mapping, raw_value)
results.append(FieldSourceCandidate(
source='header_region',
target_scope=mapping.target_scope,
target_field_code=mapping.target_field_code,
target_field_id=mapping.target_field_id,
value=raw_value,
normalized_value=_normalize_string(raw_value),
format_valid=format_valid,
format_reason_code=reason,
effective_line_no=None, # header scope 固定 None
evidence_quote=raw_value[:512],
evidence_ref=str(item.get('evidence_ref') or '') or None,
evidence_metadata=dict(item.get('evidence_metadata') or {}),
))
return results
def _collect_table_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
"""表身列来源——从 caller 传入的 table_column_values[column_code] 读取,每行一个候选。"""
rows = self.table_column_values.get(mapping.table_column_code or '', [])
results: list[FieldSourceCandidate] = []
for row in rows:
try:
line_no = int(row.get('line_index')) + 1 # 转 1-based
except (TypeError, ValueError):
continue
raw_value = str(row.get('value') or '')
format_valid, reason = self._check_format(mapping, raw_value)
results.append(FieldSourceCandidate(
source='table_column',
target_scope=mapping.target_scope,
target_field_code=mapping.target_field_code,
target_field_id=mapping.target_field_id,
value=raw_value,
normalized_value=_normalize_string(raw_value),
format_valid=format_valid,
format_reason_code=reason,
effective_line_no=line_no,
evidence_quote=raw_value[:512],
evidence_ref=str(row.get('evidence_ref') or '') or None,
evidence_metadata=dict(row.get('evidence_metadata') or {}),
))
return results
def _collect_vendor_comments_source(self, mapping: ProfileFieldSourceMapping) -> list[FieldSourceCandidate]:
"""
Vendor Comments 来源——三步走:
1. CoordinateRegionSourceAdapter 渲染区域原文 + bbox 证据;
2. execute_base_split_rule_set 拆出段(带 captured_relation);
3. ReservationRelationProjection 投影关系到 effective_line_no / resolution_hint。
"""
region_ref = mapping.vendor_comments_region_ref or ''
region = self.named_regions.get(region_ref)
if region is None:
return [self._missing_region_fallback(mapping, region_ref)]
adapter = CoordinateRegionSourceAdapter(region, self.page_glyphs_map)
region_result: CoordinateRegionSourceResult = adapter.extract()
if region_result.status != 'available' or not mapping.vendor_comments_split_rule_set:
return [self._unavailable_region_candidate(mapping, region_result)]
split_result = execute_base_split_rule_set(
raw_value=region_result.raw_text,
rule_set=mapping.vendor_comments_split_rule_set,
lines=region_result.lines or None,
)
projector = ReservationRelationProjection(
relation_policy=mapping.relation_policy,
line_reference_basis=mapping.line_reference_basis,
missing_relation_policy=mapping.missing_relation_policy,
)
# 先收集 mapped 段,再收集 evidence_only 段(annotation_only 用)
all_segments: list[_CoreSegmentResult] = list(split_result.segments) + list(split_result.evidence_only_segments)
results: list[FieldSourceCandidate] = []
token_evidence_map = _build_evidence_ref_map(region_result.evidence_tokens)
for seg in all_segments:
rel_proj = projector.project(
captured_relation=seg.captured_relation,
explicit_line_column_values=self.explicit_line_column_values,
profile_business_line_numbers=self.profile_business_line_numbers,
classified_logical_line_numbers=self.classified_logical_line_numbers,
)
format_valid, reason = self._check_format(mapping, seg.normalized_text)
if rel_proj.resolution == 'bound_to_line':
results.append(self._make_vc_candidate(
mapping=mapping, seg=seg, rel_proj=rel_proj,
region_result=region_result, token_evidence_map=token_evidence_map,
effective_line_no=rel_proj.resolved_logical_line_no,
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
))
elif rel_proj.resolution == 'default_all_lines':
# 每行都生成一个(common case:整个 Vendor Comments 段没有 line 号引用)
for line_idx in range(1, max(1, self.total_logical_lines) + 1):
results.append(self._make_vc_candidate(
mapping=mapping, seg=seg, rel_proj=rel_proj,
region_result=region_result, token_evidence_map=token_evidence_map,
effective_line_no=line_idx if mapping.target_scope == 'line' else None,
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
))
elif rel_proj.resolution == 'annotation_only':
results.append(self._make_vc_candidate(
mapping=mapping, seg=seg, rel_proj=rel_proj,
region_result=region_result, token_evidence_map=token_evidence_map,
effective_line_no=None,
resolution_hint='annotation_only', format_valid=format_valid, format_reason=reason,
))
elif rel_proj.resolution == 'invalid_line_reference':
results.append(self._make_vc_candidate(
mapping=mapping, seg=seg, rel_proj=rel_proj,
region_result=region_result, token_evidence_map=token_evidence_map,
effective_line_no=None,
resolution_hint='invalid_line_reference', format_valid=False,
format_reason=reason or 'invalid_line_reference',
))
else:
# default_header_only / conflict_unresolved
results.append(self._make_vc_candidate(
mapping=mapping, seg=seg, rel_proj=rel_proj,
region_result=region_result, token_evidence_map=token_evidence_map,
effective_line_no=None if mapping.target_scope == 'header' else None,
resolution_hint='provisional', format_valid=format_valid, format_reason=reason,
))
return results
# ------------------------------------------------------------------
# 辅助:格式校验(Q15)+ Vendor Comments 候选构造
# ------------------------------------------------------------------
def _check_format(
self, mapping: ProfileFieldSourceMapping, value: str,
) -> tuple[bool | None, str | None]:
"""返回 (format_valid, reason_code);非 reservation 字段返回 (None, None)。"""
if mapping.target_field_code != 'reservation_id':
return None, None
if not value:
return False, 'reservation_format_empty'
if self.format_validator_callback is not None:
ok = bool(self.format_validator_callback(mapping.format_policy, value))
return (True, None) if ok else (False, 'reservation_format_invalid')
# 默认回退全局 validated_reservation_id(Q15 方案 A:本期不重构全局)
from app.services.shipping_notice.reservation_id import validated_reservation_id
ok = validated_reservation_id(value) is not None
return (True, None) if ok else (False, 'reservation_format_invalid')
@staticmethod
def _missing_region_fallback(mapping: ProfileFieldSourceMapping, region_ref: str) -> FieldSourceCandidate:
return FieldSourceCandidate(
source='vendor_comments',
target_scope=mapping.target_scope,
target_field_code=mapping.target_field_code,
target_field_id=mapping.target_field_id,
value='',
normalized_value='',
format_valid=None,
format_reason_code=None,
effective_line_no=None,
resolution_hint='provisional',
evidence_quote=None,
evidence_ref=None,
evidence_metadata={'reason': 'named_region_not_found', 'region_ref': region_ref},
)
@staticmethod
def _unavailable_region_candidate(
mapping: ProfileFieldSourceMapping, region_result: CoordinateRegionSourceResult,
) -> FieldSourceCandidate:
return FieldSourceCandidate(
source='vendor_comments',
target_scope=mapping.target_scope,
target_field_code=mapping.target_field_code,
target_field_id=mapping.target_field_id,
value='',
normalized_value='',
format_valid=None,
format_reason_code=None,
effective_line_no=None,
resolution_hint='provisional',
evidence_quote=region_result.raw_text[:512] or None,
evidence_ref=None,
evidence_metadata={
'reason': region_result.diagnostic_code or 'named_region_unavailable',
'diagnostic_message': region_result.diagnostic_message,
'region_id': region_result.region_id,
},
)
@staticmethod
def _make_vc_candidate(
*,
mapping: ProfileFieldSourceMapping,
seg: _CoreSegmentResult,
rel_proj: ReservationRelationProjectionResult,
region_result: CoordinateRegionSourceResult,
token_evidence_map: dict[str, list[CoordinateRegionEvidence]],
effective_line_no: int | None,
resolution_hint: Literal['provisional', 'annotation_only', 'invalid_line_reference'],
format_valid: bool | None,
format_reason: str | None,
) -> FieldSourceCandidate:
token_ev = _find_best_token_evidence(token_evidence_map, seg.normalized_text)
evidence_quote = seg.raw_text[:512] or None
evidence_ref = _vc_evidence_ref(region_result, seg, token_ev)
metadata: dict[str, Any] = {
'region_id': region_result.region_id,
'segment_id': seg.segment_id,
'rule_id': seg.rule_id,
'matcher_type': seg.matcher_type,
'handling': seg.handling,
'line_bounds_in_region': [seg.line_no, seg.line_end_no],
'captured_relation_raw': (
None if seg.captured_relation is None else {
'type': seg.captured_relation.type,
'line_no': seg.captured_relation.line_no,
'raw_text': seg.captured_relation.raw_text,
}
),
'relation_projection': _proj_to_json(rel_proj),
'best_token': (None if token_ev is None else {
'page_no': token_ev.page_no,
'x0': token_ev.x0, 'y0': token_ev.y0,
'x1': token_ev.x1, 'y1': token_ev.y1,
'text': token_ev.text,
}),
}
return FieldSourceCandidate(
source='vendor_comments',
target_scope=mapping.target_scope,
target_field_code=mapping.target_field_code,
target_field_id=mapping.target_field_id,
value=seg.raw_text,
normalized_value=seg.normalized_text,
format_valid=format_valid,
format_reason_code=format_reason,
effective_line_no=effective_line_no,
resolution_hint=resolution_hint,
relation_projection=rel_proj,
evidence_quote=evidence_quote,
evidence_ref=evidence_ref,
evidence_metadata=metadata,
)
# ---------------------------------------------------------------------------
# 模块级纯函数(避免每次 Service 实例化重复加载)
# ---------------------------------------------------------------------------
def _normalize_string(v: str) -> str:
return ' '.join(str(v or '').split()).strip()
def _build_evidence_ref_map(tokens: list[CoordinateRegionEvidence]) -> dict[str, list[CoordinateRegionEvidence]]:
out: dict[str, list[CoordinateRegionEvidence]] = {}
for t in tokens:
out.setdefault(_normalize_string(t.text), []).append(t)
return out
def _find_best_token_evidence(
evidence_map: dict[str, list[CoordinateRegionEvidence]], value: str,
) -> CoordinateRegionEvidence | None:
norm = _normalize_string(value)
if norm in evidence_map and evidence_map[norm]:
return evidence_map[norm][0]
# 降级:子串命中
for key, tokens in evidence_map.items():
if norm and (norm in key or key in norm) and tokens:
return tokens[0]
return None
def _vc_evidence_ref(
region_result: CoordinateRegionSourceResult,
seg: _CoreSegmentResult,
token: CoordinateRegionEvidence | None,
) -> str:
"""
稳定 Observation.evidence_ref。
格式:vc://<region_id>/p<page_no>/seg-<segment_id>[:<x0>-<y0>-<x1>-<y1>]
"""
base = f"vc://{region_result.region_id}/p{region_result.page_no}/seg-{seg.segment_id}"
if token is not None:
base += (
f":{round(token.x0, 4)}-{round(token.y0, 4)}-"
f"{round(token.x1, 4)}-{round(token.y1, 4)}"
)
return base[:512]
def _proj_to_json(p: ReservationRelationProjectionResult) -> dict[str, Any]:
return {
'line_reference_basis': p.line_reference_basis,
'resolution': p.resolution,
'resolved_logical_line_no': p.resolved_logical_line_no,
'annotation_reason': p.annotation_reason,
'invalid_reference_raw_value': p.invalid_reference_raw_value,
'invalid_reference_line_no': p.invalid_reference_line_no,
'audit_chain_count': 0 if p.audit_chain is None else len(p.audit_chain),
}
@@ -0,0 +1,338 @@
"""
services/shipping_notice/document_layout/profile_vendor_comments_contract.py
用途:Profile 顶层新增的 Vendor Comments 三来源契约(不修改现有 OrderCoordinateProfile 字段,
保持「路径判断与事实分离」——definition_json.get 读取命名区域和字段来源映射)。
依赖:Pydantic、field_split_core.BaseSplitRuleSet、RelativeRegion(来自 order_profile)。
逻辑:对外暴露 parse_named_regions() / parse_field_source_mappings() / validate_format_policy()
三个稳定入口;所有变更是否触发「回 Draft + 重新验证」由 profile_regions_require_draft()
判定,禁止各业务点自行假设回 Draft 条件。
"""
from __future__ import annotations
import hashlib
import json
import re
from typing import Any, Literal
from pydantic import BaseModel, ConfigDict, Field, model_validator
from app.core.errors import ValidationError
from app.services.shipping_notice.document_layout.field_split_core import (
BaseSplitRuleSet,
)
from app.services.shipping_notice.document_layout.order_profile import (
RelativeRegion,
)
# ---------------------------------------------------------------------------
# 顶层 Pydantic 契约——definition_json 结构
# ---------------------------------------------------------------------------
VC_MODEL_CONFIG = ConfigDict(extra='forbid', validate_assignment=True)
class NamedRegion(BaseModel):
"""
物理来源命名区域(Q14 冻结)——管理员圈选的坐标框。
【关键约束】:不是 Schema 字段区域伪装,是 Vendor Comments 等非 XFA 正文块的真实
阅读区域。变更此对象必须回 Draft(由 profile_regions_require_draft 判定)。
"""
model_config = VC_MODEL_CONFIG
region_id: str = Field(pattern=r'^[a-z][a-z0-9_-]{0,95}$')
label: str = Field(min_length=1, max_length=160)
region: RelativeRegion
page_scope: Literal['first_page', 'last_page', 'all_pages', 'exact_page'] = 'last_page'
page_no: int | None = Field(default=None, ge=1)
selection_mode: Literal['fixed_region', 'auto_take_last_qualified'] = 'fixed_region'
@model_validator(mode='after')
def validate_page_semantics(self) -> 'NamedRegion':
if self.page_scope == 'exact_page' and self.page_no is None:
raise ValueError('exact_page named region requires page_no')
if self.page_scope != 'exact_page' and self.page_no is not None:
raise ValueError('page_no is only allowed for exact_page named region')
return self
class ReservationFormatPolicy(BaseModel):
"""
Reservation 格式校验策略(Q15 冻结)——Profile 级受控策略,未配置时回退全局 5/10 纯数字。
首期仅支持 numeric_5_or_10 / custom_safe_regex 两种;custom_safe_regex 必须经过
长度限制、捕获组限制、危险表达式黑名单与超时上限 4 层门禁。
"""
model_config = VC_MODEL_CONFIG
mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex'] = 'inherit_global'
pattern: str | None = Field(default=None, min_length=1, max_length=1024)
max_capture_groups: int = Field(default=2, ge=0, le=8)
timeout_ms: int = Field(default=30, ge=10, le=500)
case_sensitive: bool = False
@model_validator(mode='after')
def validate_regex_policy(self) -> 'ReservationFormatPolicy':
if self.mode != 'custom_safe_regex':
if self.pattern is not None:
raise ValueError('pattern only allowed for custom_safe_regex mode')
return self
if not self.pattern:
raise ValueError('custom_safe_regex requires a non-empty pattern')
_validate_safe_regex_pattern(
self.pattern,
max_groups=self.max_capture_groups,
case_sensitive=self.case_sensitive,
)
return self
class ProfileFieldSourceMapping(BaseModel):
"""
Profile 级字段来源映射(Q9 冻结,并列 split_rules)——声明一个 Schema 字段从三来源
(header/table_column/vendor_comments)哪几个抽取,以及各自使用的拆分规则与关系策略。
"""
model_config = VC_MODEL_CONFIG
mapping_id: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
target_scope: Literal['header', 'line']
target_field_code: str = Field(pattern=r'^[a-z][a-z0-9_]{0,63}$')
target_field_id: str = Field(min_length=1, max_length=128)
# 三来源开关——未启用的来源在 ProfileFieldSourceMappingService 直接跳过
header_source_enabled: bool = False
header_source_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$')
header_normalizer_key: str | None = Field(default=None, min_length=1, max_length=64)
table_source_enabled: bool = False
table_column_code: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_]{0,63}$')
vendor_comments_enabled: bool = False
vendor_comments_region_ref: str | None = Field(default=None, pattern=r'^[a-z][a-z0-9_-]{0,95}$')
vendor_comments_split_rule_set: BaseSplitRuleSet | None = None
# 关系策略(Q2 双层设计)——本期仅 reservation_id 绑定明细行使用 bind_target_line
relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'] = 'no_relation'
missing_relation_policy: Literal['default_all_lines', 'default_header_only', 'fallback_single_line_when_no_reference'] = 'default_header_only'
line_reference_basis: Literal['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no'] = 'profile_business_line_no'
# 三来源空值互补策略——Q4 冲突矩阵里不同 scope 独立保留,同 scope 值不一致 Review
fill_missing_from_other_sources: bool = True
format_policy: ReservationFormatPolicy = Field(default_factory=ReservationFormatPolicy)
@model_validator(mode='after')
def validate_source_refs(self) -> 'ProfileFieldSourceMapping':
if self.header_source_enabled and not self.header_source_ref:
raise ValueError('header_source_ref is required when header_source_enabled')
if self.table_source_enabled and not self.table_column_code:
raise ValueError('table_column_code is required when table_source_enabled')
if self.vendor_comments_enabled:
if not self.vendor_comments_region_ref:
raise ValueError('vendor_comments_region_ref is required when vendor_comments_enabled')
if not self.vendor_comments_split_rule_set:
raise ValueError('vendor_comments_split_rule_set is required when vendor_comments_enabled')
return self
# ---------------------------------------------------------------------------
# 稳定读取工具:接受 None / 脏 dict,返回归一化契约对象(路径判断与事实分离)
# ---------------------------------------------------------------------------
def parse_named_regions(value: Any) -> dict[str, NamedRegion]:
"""
从 definition_json.named_regions(或 None)解析命名区域字典。
【AI 触发时机】:读取 Profile 配置阶段、预览阶段或变更比对阶段调用。
核心逻辑:值为 None/空 dict 时返回空字典(允许客户先不配 Vendor Comments 区域);
未知键直接保留映射,不抛错;坏值立刻抛 ValidationError 避免运行时污染。
Args:
value: Profile definition_json.get('named_regions') 原值。
Returns:
{region_id: NamedRegion} 字典。
"""
if value is None:
return {}
if not isinstance(value, dict):
raise ValidationError(
'definition_json.named_regions must be an object',
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
)
result: dict[str, NamedRegion] = {}
for key, raw in value.items():
if not re.match(r'^[a-z][a-z0-9_-]{0,95}$', str(key)):
raise ValidationError(
f'named region key {key!r} is invalid',
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
)
try:
item = NamedRegion.model_validate(raw) if isinstance(raw, dict) else raw
except ValueError as exc:
raise ValidationError(
f'named region {key!r} is invalid: {exc}',
code='SHIPPING.PROFILE_NAMED_REGIONS_INVALID',
) from exc
if item.region_id != key:
raise ValidationError(
f'named region key {key!r} must match nested region_id {item.region_id!r}',
code='SHIPPING.PROFILE_NAMED_REGIONS_MISMATCH',
)
result[key] = item
return result
def parse_field_source_mappings(value: Any) -> list[ProfileFieldSourceMapping]:
"""
从 definition_json.field_source_mappings(或 None)解析字段来源映射列表。
核心逻辑:返回值为稳定顺序列表,不做去重(重复的 target_scope/target_field_code
组合将由 SourceMergeService 在抽取层做 Q18 冲突裁决)。
"""
if value is None:
return []
if not isinstance(value, list):
raise ValidationError(
'definition_json.field_source_mappings must be a list',
code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID',
)
results: list[ProfileFieldSourceMapping] = []
for raw in value:
try:
results.append(ProfileFieldSourceMapping.model_validate(raw))
except ValueError as exc:
raise ValidationError(
f'field source mapping is invalid: {exc}',
code='SHIPPING.PROFILE_FIELD_SOURCE_MAPPINGS_INVALID',
) from exc
return results
# ---------------------------------------------------------------------------
# 变更回 Draft 门禁(Q14 冻结:区域变化必须使 Profile 回 Draft)
# ---------------------------------------------------------------------------
REGION_CHANGE_REQUIRES_DRAFT_KEYS = frozenset({
'region', 'page_scope', 'page_no', 'selection_mode',
})
def profile_regions_require_draft(
*,
old_named_regions: Any,
new_named_regions: Any,
) -> bool:
"""
判断 named_regions 变更是否触发 Profile 回 Draft + 重新验证 + 盲测 + 发布。
核心逻辑(fail-safe):任何 region 主键、坐标、页作用域、选取模式的增删改一律回 Draft;
仅 label 文案调整(便于管理员标注说明)不触发。
"""
try:
old_map = parse_named_regions(old_named_regions)
new_map = parse_named_regions(new_named_regions)
except ValidationError:
return True # 解析失败默认回 Draft(fail-close)
if set(old_map.keys()) != set(new_map.keys()):
return True
for region_id in old_map:
old_region = old_map[region_id]
new_region = new_map[region_id]
for key in REGION_CHANGE_REQUIRES_DRAFT_KEYS:
if getattr(old_region, key) != getattr(new_region, key):
return True
return False
def field_source_mappings_require_draft(
*,
old_mappings: Any,
new_mappings: Any,
) -> bool:
"""
判断 field_source_mappings 变更是否触发回 Draft。
核心逻辑:除了纯 label 类改动外的任何增删改一律回 Draft(首期全量回 Draft,保留细粒度
门禁的未来扩展点)。
"""
try:
old_list = parse_field_source_mappings(old_mappings)
new_list = parse_field_source_mappings(new_mappings)
except ValidationError:
return True
if len(old_list) != len(new_list):
return True
old_payload = _stable_mapping_dumps(old_list)
new_payload = _stable_mapping_dumps(new_list)
return old_payload != new_payload
def _stable_mapping_dumps(items: list[ProfileFieldSourceMapping]) -> str:
payload = [m.model_dump(mode='json', sort_keys=True) for m in items]
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
# ---------------------------------------------------------------------------
# 安全正则门禁(Q15 custom_safe_regex 发布前必过)
# ---------------------------------------------------------------------------
_UNSAFE_PATTERN_MARKERS = (
r'\(.+[+*]\)\s*[+*]', # 嵌套量词 例: (a+)+
r'\(\.?\*\)\s*\*', # 多重.* 回溯
r'\(\[.*\]\)\{[0-9]+,[0-9]*\}', # 大范围字符类重复
r'(?<!\\)\\[bBwWsSdD].*[+*]', # 通用字符集 + 无限量词
r'\(\?:?\^?\$?.*\)\?\?', # 前后查找量词叠加
)
def _validate_safe_regex_pattern(pattern: str, *, max_groups: int, case_sensitive: bool) -> None:
"""
custom_safe_regex 的发布前样本验证门禁(Q15)——编译期就拦截危险表达式。
【注意】:运行时还需配合 timeout_ms 的 signal 看门狗(在 regex_runner_safe 中实现)。
"""
if len(pattern) > 1024:
raise ValueError('custom_safe_regex pattern exceeds 1024 characters')
for marker in _UNSAFE_PATTERN_MARKERS:
if re.search(marker, pattern):
raise ValueError('custom_safe_regex pattern looks potentially catastrophic')
flags = 0 if case_sensitive else re.IGNORECASE
try:
compiled = re.compile(pattern, flags)
except re.error as exc:
raise ValueError(f'custom_safe_regex pattern failed to compile: {exc}') from exc
if compiled.groups > max_groups:
raise ValueError(
f'custom_safe_regex has {compiled.groups} capture groups; limit is {max_groups}'
)
_ = compiled # 引用仅用于静态检查
# ---------------------------------------------------------------------------
# 校验和(盲测/发布基准比对)
# ---------------------------------------------------------------------------
def field_source_mappings_checksum(mappings: list[ProfileFieldSourceMapping]) -> str:
"""稳定 SHA-256 校验和,供发布冻结与审计引用。"""
payload = _stable_mapping_dumps(mappings).encode('utf-8')
return hashlib.sha256(payload).hexdigest()
def named_regions_checksum(regions: dict[str, NamedRegion]) -> str:
"""稳定 SHA-256 校验和,供区域变更历史比对。"""
payload = json.dumps(
{rid: r.model_dump(mode='json', sort_keys=True) for rid, r in regions.items()},
ensure_ascii=True, sort_keys=True, separators=(',', ':'),
).encode('utf-8')
return hashlib.sha256(payload).hexdigest()
@@ -0,0 +1,152 @@
"""
services/shipping_notice/document_layout/reservation_format_policy_service.py
用途:Q15 Reservation ID 格式策略服务——Profile 级 format_policy 受控入口。
首期(阶段 2)保持「回退全局 validated_reservation_id(numeric_5_or_10 硬编码)」
不变;为未来 custom_safe_regex / 字母型 Reservation 保留扩展点。
依赖:profile_vendor_comments_contract.ReservationFormatPolicy;
reservation_id.validated_reservation_id(全局回退)。
逻辑:【技术重试与业务决策分离】——本类只负责**格式判断**,不改变值、不生成 Observation,
调用方(ProfileFieldSourceMappingService._check_format)根据返回值标记
reservation_format_invalid,但不丢弃候选(保留为 Review 证据展示)。
"""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Literal
from app.services.shipping_notice.document_layout.profile_vendor_comments_contract import (
ReservationFormatPolicy,
)
RESERVATION_NUMERIC_5_OR_10_RE = re.compile(r'^(?:\d{5}|\d{10})$')
@dataclass
class FormatPolicyResult:
"""格式校验结果——只描述事实,不携带业务动作。"""
valid: bool
mode: Literal['inherit_global', 'numeric_5_or_10', 'custom_safe_regex']
normalized_value: str | None = None # 仅 valid=True 时返回规范化值
reason_code: str | None = None # valid=False 时的稳定诊断码
@property
def should_block_auto_create(self) -> bool:
"""格式失败的值不得自动建单(Q15 冻结)。"""
return not self.valid
class ReservationFormatPolicyService:
"""
Profile 级 Reservation 格式策略受控入口。
【AI 触发时机】:ProfileFieldSourceMappingService 收集候选、或 Candidate
Qualification 最终门禁时调用 check()。禁止任何地方直接
if re.match(r'^\d{5,10}$', v) 绕过策略层。
"""
def check(self, policy: ReservationFormatPolicy, raw_value: str) -> FormatPolicyResult:
"""
执行一次格式校验。调用方不得丢弃失败候选,必须将原因码写入
FieldSourceCandidate.format_reason_code。
核心路径(Q15 冻结):
① mode=inherit_global → 调全局 validated_reservation_id 保持历史 71 调用方口径;
② mode=numeric_5_or_10 → 等价于全局(显式模式;便于未来全局重构时切换默认);
③ mode=custom_safe_regex → 调用发布前已通过 Pydantic 门禁的安全正则。
"""
value = (raw_value or '').strip()
if not value:
return FormatPolicyResult(
valid=False, mode=policy.mode, normalized_value=None,
reason_code='reservation_format_empty',
)
mode = policy.mode
if mode in {'inherit_global', 'numeric_5_or_10'}:
return self._check_numeric_5_or_10(value, mode)
if mode == 'custom_safe_regex':
return self._check_custom_safe_regex(policy, value)
return FormatPolicyResult(
valid=False, mode=mode, normalized_value=None,
reason_code='reservation_format_unknown_mode',
)
# ------------------------------------------------------------------
# 内部实现
# ------------------------------------------------------------------
@staticmethod
def _check_numeric_5_or_10(
value: str,
mode: Literal['inherit_global', 'numeric_5_or_10'],
) -> FormatPolicyResult:
"""纯数字 5/10 位——默认回退全局校验,但通过独立模块输出稳定结果。"""
# 先尝试全局 validated_reservation_id(保持与 71 调用方一致),失败再用本模块常量兜底
try:
from app.services.shipping_notice.reservation_id import validated_reservation_id
global_result = validated_reservation_id(value)
if global_result is not None:
return FormatPolicyResult(
valid=True, mode=mode, normalized_value=global_result,
reason_code=None,
)
except Exception: # fail-safe:若全局模块异常,不阻塞结果
pass
match = RESERVATION_NUMERIC_5_OR_10_RE.match(value)
if match:
return FormatPolicyResult(
valid=True, mode=mode, normalized_value=value,
reason_code=None,
)
return FormatPolicyResult(
valid=False, mode=mode, normalized_value=None,
reason_code='reservation_format_invalid',
)
@staticmethod
def _check_custom_safe_regex(policy: ReservationFormatPolicy, value: str) -> FormatPolicyResult:
"""安全正则匹配——编译缓存;捕获组第 1 组作为规范化值(否则整串)。"""
pattern = policy.pattern or ''
flags = 0 if policy.case_sensitive else re.IGNORECASE
try:
compiled = re.compile(pattern, flags)
except re.error as exc:
return FormatPolicyResult(
valid=False, mode='custom_safe_regex', normalized_value=None,
reason_code=f'reservation_format_regex_compile_error:{exc.__class__.__name__}',
)
# 发布前样本验证门禁已限制 catastrophic 风险;这里仅以标准 library 限制长度
if len(value) > 128:
return FormatPolicyResult(
valid=False, mode='custom_safe_regex', normalized_value=None,
reason_code='reservation_format_value_too_long',
)
match = compiled.search(value)
if not match:
return FormatPolicyResult(
valid=False, mode='custom_safe_regex', normalized_value=None,
reason_code='reservation_format_invalid',
)
# 规范化值:第 1 捕获组 → 整串
normalized: str = value
if compiled.groups >= 1:
try:
first_group = match.group(1)
if first_group:
normalized = str(first_group).strip()
except (IndexError, re.error):
normalized = match.group(0) or value
normalized = normalized.strip()
if not normalized:
return FormatPolicyResult(
valid=False, mode='custom_safe_regex', normalized_value=None,
reason_code='reservation_format_capture_empty',
)
return FormatPolicyResult(
valid=True, mode='custom_safe_regex', normalized_value=normalized,
reason_code=None,
)
@@ -0,0 +1,228 @@
"""
services/shipping_notice/document_layout/reservation_relation_projection.py
用途:Reservation 关系投影(Q2 双层设计 + Q12 invalid_line_reference 独立原因码)。
将拆分引擎内部捕获的 captured_relation + Profile 关系策略 relation_policy,
映射为「绑定到哪条行、是否 annotation_only、是否 invalid_line_reference 独立」三输出。
依赖:field_split_core.CoreCapturedRelation(来自 _CoreSegmentResult.captured_relation)、
ProfileFieldSourceMapping.relation_policy / line_reference_basis。
逻辑:严格遵循「路径判断与事实分离」——拆分引擎事实(line_no)只作为证据,
最终绑定路径必须经过 line_reference_basis 三层映射校验后裁决;
失败不抛异常,输出稳定 reason_code 供审计和前端翻译。
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Literal
from app.services.shipping_notice.document_layout.field_split_core import (
CoreCapturedRelation,
)
@dataclass
class ReservationRelationProjectionResult:
"""关系投影最终结果——只输出明确分支,禁止上游自行判断。"""
line_reference_basis: Literal[
'explicit_line_column',
'profile_business_line_no',
'classified_logical_line_no',
]
resolution: Literal[
'bound_to_line', # bind_target_line 成功,resolved_logical_line_no 有值
'annotation_only', # 显式 annotation_only,Observation 存 metadata
'default_all_lines', # 关系缺失 + default_all_lines,每行都生成 Observation
'default_header_only', # 关系缺失 + default_header_only,写到 header scope
'invalid_line_reference', # 引用了不存在的行号,独立原因码 Q12
'conflict_unresolved', # 未来多层映射冲突保留(本期不输出)
]
resolved_logical_line_no: int | None = None # 1-based 逻辑行号,bound_to_line 时必填
annotation_reason: str | None = None # annotation_only 时写入 Observation metadata
invalid_reference_raw_value: str | None = None # invalid_line_reference 时返回 raw_text
invalid_reference_line_no: int | None = None
audit_chain: list[dict[str, Any]] | None = None # 路径判断全链路审计快照
@property
def should_generate_line_observation(self) -> bool:
return self.resolution == 'bound_to_line' or self.resolution == 'default_all_lines'
@property
def should_generate_header_observation(self) -> bool:
return self.resolution in {'default_header_only', 'annotation_only', 'invalid_line_reference'}
class ReservationRelationProjection:
"""
把 captured_relation(规则层事实) + profile relation_policy(解释层策略)
投影为最终绑定结果。
【AI 触发时机】:三来源合并前,为每个 Vendor Comments / Header Reservation 候选
决定「写行 Observation 还是写头 Observation 还是 invalid_line_reference」时调用。
核心路径:
[STEP 1] 若 relation_policy=annotation_only → 直接走 annotation_only 分支(审计记录原因)。
[STEP 2] 若缺失 captured_relation → 走 missing_relation_policy 分支
(default_all_lines / default_header_only / fallback_single_line_when_no_reference)。
[STEP 3] 若有 captured_relation.line_no,按 line_reference_basis 三层校验:
① explicit_line_column:对比 Schema Line 字段值(显式 Line 列),失败→invalid
② profile_business_line_no:对比 Profile 业务行号(默认客户 PO 行号)
③ classified_logical_line_no:逻辑行号(行序分类后的结果)
三层任何一层命中即返回 bound_to_line;全部失败输出 invalid_line_reference 独立原因码。
"""
def __init__(
self,
*,
relation_policy: Literal['no_relation', 'bind_target_line', 'annotation_only'],
line_reference_basis: Literal[
'explicit_line_column',
'profile_business_line_no',
'classified_logical_line_no',
] = 'profile_business_line_no',
missing_relation_policy: Literal[
'default_all_lines',
'default_header_only',
'fallback_single_line_when_no_reference',
] = 'default_header_only',
):
self.relation_policy = relation_policy
self.line_reference_basis = line_reference_basis
self.missing_relation_policy = missing_relation_policy
# ------------------------------------------------------------------
# 对外入口
# ------------------------------------------------------------------
def project(
self,
*,
captured_relation: CoreCapturedRelation | None,
# 下面四个映射是 Line Reference Basis 的判定表(caller 注入,避免本类查 Schema)
explicit_line_column_values: dict[int, str] | None = None,
profile_business_line_numbers: dict[int, Any] | None = None,
classified_logical_line_numbers: dict[int, int] | None = None,
# 审计备注(annotation_only 时必须填写原因字符串,例如 'customer_commentary_only')
annotation_reason_override: str | None = None,
) -> ReservationRelationProjectionResult:
"""
执行关系投影。
【禁止 caller 自行推导】:不要在外部用 if captured_relation.line_no in ... 判断,
必须走 project() 返回的稳定 resolution 分支。
"""
audit: list[dict[str, Any]] = [
{'step': 'policy_in', 'relation_policy': self.relation_policy,
'line_reference_basis': self.line_reference_basis,
'missing_relation_policy': self.missing_relation_policy},
]
# [STEP 1] annotation_only 直接返回(本期用于 Customer 备注说明、不参与建单)
if self.relation_policy == 'annotation_only':
audit.append({'step': 'annotation_only',
'reason': annotation_reason_override or 'profile_relation_policy_annotation_only'})
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='annotation_only',
annotation_reason=annotation_reason_override or 'profile_relation_policy_annotation_only',
audit_chain=audit,
)
# [STEP 2] 缺失 captured_relation → 走 missing_relation_policy
if captured_relation is None or captured_relation.line_no is None:
audit.append({'step': 'missing_relation',
'raw_text': captured_relation.raw_text if captured_relation else None})
return self._resolve_missing_policy(audit)
# [STEP 3] 三层 line_reference_basis 判定(显式 Line 列值 → Profile 业务行号 → 逻辑行号)
rel_line_no = int(captured_relation.line_no)
audit.append({'step': 'relation_line_no_in', 'line_no': rel_line_no,
'raw_text': captured_relation.raw_text})
basis_order = self._basis_order()
for basis_name in basis_order:
resolved = self._try_basis(basis_name, rel_line_no, explicit_line_column_values or {},
profile_business_line_numbers or {},
classified_logical_line_numbers or {})
if resolved is not None:
audit.append({'step': 'basis_hit', 'basis': basis_name,
'logical_line_no': resolved})
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='bound_to_line',
resolved_logical_line_no=resolved,
audit_chain=audit,
)
# 三层全不命中 → invalid_line_reference(Q12 独立原因码 + 独立审计链)
audit.append({'step': 'invalid_line_reference', 'tried_bases': basis_order})
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='invalid_line_reference',
invalid_reference_raw_value=captured_relation.raw_text,
invalid_reference_line_no=rel_line_no,
audit_chain=audit,
)
# ------------------------------------------------------------------
# 内部步骤
# ------------------------------------------------------------------
def _basis_order(self) -> list[str]:
"""按 Profile.line_reference_basis 输出优先级顺序。"""
if self.line_reference_basis == 'explicit_line_column':
return ['explicit_line_column', 'profile_business_line_no', 'classified_logical_line_no']
if self.line_reference_basis == 'profile_business_line_no':
return ['profile_business_line_no', 'classified_logical_line_no', 'explicit_line_column']
return ['classified_logical_line_no', 'profile_business_line_no', 'explicit_line_column']
def _try_basis(
self,
basis: str,
rel_line_no: int,
explicit: dict[int, str],
profile_biz: dict[int, Any],
logical: dict[int, int],
) -> int | None:
"""尝试一层判定;命中则返回逻辑行号(1-based),否则返回 None。"""
if basis == 'explicit_line_column':
for logical_idx, raw in explicit.items():
if str(raw).strip() == str(rel_line_no):
return int(logical_idx)
return None
if basis == 'profile_business_line_no':
for logical_idx, raw in profile_biz.items():
if str(raw).strip() == str(rel_line_no):
return int(logical_idx)
return None
if basis == 'classified_logical_line_no':
for logical_idx, mapped in logical.items():
if int(mapped) == rel_line_no:
return int(logical_idx)
return None
return None
def _resolve_missing_policy(self, audit: list[dict[str, Any]]) -> ReservationRelationProjectionResult:
"""缺失关系时按 missing_relation_policy 落分支。"""
policy = self.missing_relation_policy
audit.append({'step': 'missing_policy', 'policy': policy})
if policy == 'default_all_lines':
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='default_all_lines',
audit_chain=audit,
)
if policy == 'fallback_single_line_when_no_reference':
# Q7 开关:默认 OFF;当前 Profile 显式开启时才使用——第一期所有客户 OFF
# 若未来启用,应当返回 bound_to_line → 1;本期保持 default_header_only 语义
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='default_header_only',
audit_chain=audit + [{'step': 'fallback_disabled_by_q7_default'}],
)
return ReservationRelationProjectionResult(
line_reference_basis=self.line_reference_basis,
resolution='default_header_only',
audit_chain=audit,
)
@@ -500,12 +500,10 @@ def _native_pdf_fallback_snapshot(
layout_payload=layout_payload_preview,
)
evidence_started = perf_counter()
# [FAIL-CLOSED OVERRIDE] Fallback 快照即使是 PDFium 文本回退,也必须默认
# 保存整页 glyph。否则一旦 on-demand 恢复异常(如 asset_id 丢失或 PDFium 崩
# 溃),matcher 会看到"MinerU 列名存在 + 空 page_glyphs"的分裂证据,输出
# 伪精确模板分数。坐标预算由后续 compact 负责兜底,初始生成必须包含身份证据。
# Fallback snapshots only need table-local glyphs for template modeling. Keeping
# every page glyph can exceed the persisted snapshot budget on text-heavy PDFs.
evidence = _table_coordinate_evidence(
pages=native_pages, tables=tables, include_page_glyphs=True,
pages=native_pages, tables=tables, include_page_glyphs=False,
diagnostics=diagnostics,
)
if diagnostics is not None:
@@ -0,0 +1,342 @@
"""
services/shipping_notice/document_layout/source_merge_service.py
用途:Q18 抽取层裁决——同一 conflict_group_key(scope/field_code/line_no)下的三来源候选
合并为最多一条「有效业务 Observation」,禁止同一 scope+line 下多个并列有效
Observation(防止 compute_effective_reservation_id / 库存匹配 / 履约门禁
/ Excel/RPA 误取其中一个,或冲突被后续静默覆盖)。
依赖:profile_field_source_mapping_service.FieldSourceCandidate。
逻辑:严格三步骤(同值合并 → 空值互补 → 值冲突),满足:
① merge 后只出一个有效 accepted(或 needs_review=无 accepted);
② 始终保留 source_observations[] 事实快照放入 metadata;
③ annotation_only / invalid_line_reference 的候选永不成为 accepted,
只保留在 conflict_payload 里作为 Review 证据。
输出:MergedObservationCandidate(直接落库前的 Observation 形状封装),
由 runtime 层实际 SQLAlchemy insert。
"""
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Any, Literal
from app.services.shipping_notice.document_layout.profile_field_source_mapping_service import (
FieldSourceCandidate,
)
SourceResolution = Literal[
'same_value_merged', # 多个来源值一致
'fill_missing', # 一个来源有值,另一来源为空 → 自动填补
'needs_review', # 同 scope+line 多来源值不一致
'no_value', # 所有来源均为空 → 本冲突组不生成有效 Observation
'single_source_direct', # 只有一个来源有值,直接落 Observation
'annotation_only_dropped', # 候选全是 annotation_only / invalid_line_reference
]
@dataclass
class SourceObservationSnapshot:
"""source_observations[] 事实快照——Observation.metadata 直接序列化。"""
source: Literal['header_region', 'table_column', 'vendor_comments']
value: str
normalized_value: str
evidence_ref: str | None
evidence_quote: str | None
line_no_in_source: int | None
format_valid: bool | None
format_reason_code: str | None
extra: dict[str, Any] = field(default_factory=dict)
@dataclass
class MergedObservationCandidate:
"""
合并后候选——最多一份(per conflict_group_key),由 runtime 层写数据库。
【后端决定 UI】:accepted_value 为 None 时,说明该字段+行=必须 Review;
frontend 不能以『第一个 source value』为事实,必须展示 source_observations[]。
"""
target_scope: Literal['header', 'line']
target_field_code: str
target_field_id: str
effective_line_no: int | None
accepted_value: str | None # needs_review/no_value 时为 None
decision_status: Literal['accepted', 'needs_review', 'blocked', 'missing']
resolution: SourceResolution
source_observations: list[SourceObservationSnapshot] = field(default_factory=list)
conflicts: list[dict[str, Any]] = field(default_factory=list)
# 用于直接映射到 Observation 数据库表列
evidence_quote: str | None = None
evidence_ref: str | None = None
evidence_metadata: dict[str, Any] = field(default_factory=dict)
# 用于 Observation.source_type / extractor(统一三来源来源标记)
source_type: str = 'profile_field_source_mapping'
extractor: str = 'merged_source_service.v1'
@property
def should_persist_observation(self) -> bool:
"""
有效 Observation 生成门禁:
必须有 accepted_value;annotation_only/invalid 全 drop 时也不输出。
"""
return self.accepted_value is not None and self.accepted_value != ''
class SourceMergeService:
"""
Q18 抽取层裁决服务(先对账再重试——三来源先对账)。
【AI 触发时机】:ProfileFieldSourceMappingService.collect_candidates() 返回候选后,
下一个函数调用必须是 merge_and_decide()。禁止上游在合并前直接挑一个 source 作为 Observation。
执行顺序(同 conflict_group_key 内):
[STEP 1] 过滤 annotation_only / invalid_line_reference 候选(永不 accepted)。
[STEP 2] 归一化所有来源 value(去空格、大小写、格式化残差)。
[STEP 3] 同值合并 same_value_merged → accepted
[STEP 4] 空值互补 fill_missing(需 mapping.fill_missing_from_other_sources=True)
[STEP 5] 以上都不通过 → conflict_needs_review,accepted_value=None
"""
def __init__(self, candidates: list[FieldSourceCandidate]):
self.candidates = list(candidates)
# 分组:(scope, field_code, line_no) → list[candidates]
self._groups: dict[tuple[Any, ...], list[FieldSourceCandidate]] = defaultdict(list)
for cand in self.candidates:
self._groups[cand.conflict_group_key].append(cand)
# ------------------------------------------------------------------
# 对外主入口
# ------------------------------------------------------------------
def merge_and_decide(self) -> list[MergedObservationCandidate]:
"""为每个 conflict_group_key 输出 0 或 1 个 MergedObservationCandidate。"""
merged: list[MergedObservationCandidate] = []
for _key, group in self._groups.items():
merged.append(self._merge_one_group(group))
return merged
# ------------------------------------------------------------------
# 单组合并核心
# ------------------------------------------------------------------
def _merge_one_group(self, group: list[FieldSourceCandidate]) -> MergedObservationCandidate:
first = group[0]
result = MergedObservationCandidate(
target_scope=first.target_scope,
target_field_code=first.target_field_code,
target_field_id=first.target_field_id,
effective_line_no=first.effective_line_no,
accepted_value=None,
decision_status='missing',
resolution='no_value',
)
# [STEP 1] 分离有效候选(排除 annotation_only / invalid)
qualified: list[FieldSourceCandidate] = []
for cand in group:
snap = self._to_snapshot(cand)
result.source_observations.append(snap)
if cand.resolution_hint == 'provisional':
qualified.append(cand)
else:
# annotation_only / invalid_line_reference 作为 review 证据保留
result.conflicts.append({
'resolution_hint': cand.resolution_hint,
'source': cand.source,
'value': cand.normalized_value or cand.value,
'reason': (
cand.format_reason_code
or cand.relation_projection.resolution
if cand.relation_projection else 'annotation_only'
),
})
# 无 qualified → 直接 annotation_only_dropped / no_value
if not qualified:
if group:
result.resolution = 'annotation_only_dropped'
result.decision_status = 'blocked'
else:
result.resolution = 'no_value'
result.decision_status = 'missing'
result.evidence_metadata = self._finalize_metadata(result, resolution_meta={})
return result
# 只有一个 qualified 且非空 → single_source_direct
non_empty = [c for c in qualified if (c.normalized_value or c.value) != '']
if len(qualified) == 1 and non_empty:
return self._finalize_single(result, qualified[0])
if not non_empty:
result.resolution = 'no_value'
result.decision_status = 'missing'
result.evidence_metadata = self._finalize_metadata(result, {})
return result
if len(non_empty) == 1:
return self._finalize_fill_missing(result, group, non_empty[0], qualified)
# [STEP 3] 同值合并 same_value_merged
values = {(c.normalized_value or c.value) for c in non_empty}
if len(values) == 1:
return self._finalize_same_value(result, group, next(iter(values)))
# [STEP 5] 冲突 → needs_review(多来源值不一致)
result.resolution = 'needs_review'
result.decision_status = 'needs_review'
result.accepted_value = None
for c in non_empty:
result.conflicts.append({
'source': c.source,
'value': (c.normalized_value or c.value),
'evidence_ref': c.evidence_ref,
'format_valid': c.format_valid,
})
result.evidence_metadata = self._finalize_metadata(result, {})
return result
# ------------------------------------------------------------------
# 结局封装(保证 evidence_metadata 统一包含 source_observations / resolution)
# ------------------------------------------------------------------
def _finalize_single(
self, result: MergedObservationCandidate, cand: FieldSourceCandidate,
) -> MergedObservationCandidate:
result.accepted_value = cand.normalized_value or cand.value
result.resolution = 'single_source_direct'
result.decision_status = 'accepted'
result.evidence_quote = cand.evidence_quote
result.evidence_ref = cand.evidence_ref
result.evidence_metadata = self._finalize_metadata(
result,
resolution_meta={
'accepted_source': cand.source,
'format_valid': cand.format_valid,
'format_reason_code': cand.format_reason_code,
},
primary_candidate=cand,
)
return result
def _finalize_fill_missing(
self, result: MergedObservationCandidate,
group: list[FieldSourceCandidate],
winner: FieldSourceCandidate,
all_qualified: list[FieldSourceCandidate],
) -> MergedObservationCandidate:
result.accepted_value = winner.normalized_value or winner.value
result.resolution = 'fill_missing'
result.decision_status = 'accepted'
result.evidence_quote = winner.evidence_quote
result.evidence_ref = winner.evidence_ref
missing = [
{'source': c.source, 'reason': 'empty_source'}
for c in all_qualified
if (c.normalized_value or c.value) == ''
]
result.evidence_metadata = self._finalize_metadata(
result,
resolution_meta={
'accepted_source': winner.source,
'missing_sources': missing,
'format_valid': winner.format_valid,
'format_reason_code': winner.format_reason_code,
},
primary_candidate=winner,
)
return result
def _finalize_same_value(
self, result: MergedObservationCandidate,
group: list[FieldSourceCandidate], shared_value: str,
) -> MergedObservationCandidate:
# 多来源同值:evidence 选 format_valid=True 中来源排序靠前的
# (vendor_comments 优先,因为有人工圈选证据点位更清晰)
source_priority = ['vendor_comments', 'table_column', 'header_region']
ordered = sorted(
group,
key=lambda c: (
0 if (c.format_valid is not False and (c.normalized_value or c.value) == shared_value) else 1,
source_priority.index(c.source) if c.source in source_priority else 99,
),
)
primary = ordered[0]
result.accepted_value = shared_value
result.resolution = 'same_value_merged'
result.decision_status = 'accepted'
result.evidence_quote = primary.evidence_quote
result.evidence_ref = primary.evidence_ref
merged_sources = sorted({c.source for c in ordered if (c.normalized_value or c.value) == shared_value})
result.evidence_metadata = self._finalize_metadata(
result,
resolution_meta={
'merged_from_sources': list(merged_sources),
'format_valid': primary.format_valid,
'format_reason_code': primary.format_reason_code,
},
primary_candidate=primary,
)
return result
# ------------------------------------------------------------------
# 帮助函数
# ------------------------------------------------------------------
@staticmethod
def _to_snapshot(cand: FieldSourceCandidate) -> SourceObservationSnapshot:
return SourceObservationSnapshot(
source=cand.source,
value=cand.value,
normalized_value=cand.normalized_value,
evidence_ref=cand.evidence_ref,
evidence_quote=cand.evidence_quote,
line_no_in_source=cand.effective_line_no,
format_valid=cand.format_valid,
format_reason_code=cand.format_reason_code,
extra=dict(cand.evidence_metadata or {}),
)
@staticmethod
def _finalize_metadata(
result: MergedObservationCandidate,
resolution_meta: dict[str, Any],
primary_candidate: FieldSourceCandidate | None = None,
) -> dict[str, Any]:
"""
组装 Observation.evidence_metadata_json 最终结构(Q18 冻结形状):
{
"source_observations": [...], // 事实快照(永不丢)
"resolution": "same_value_merged",
"accepted_value": "...",
"conflicts": [ ... ], // 冲突或 annotation_only 项
"resolution_meta": { ... }, // 来源细节
"primary": { // 选主证据说明
"source": "vendor_comments", "evidence_ref": "...", "line_no": 2
}
}
"""
payload: dict[str, Any] = {
'source_observations': [
{
'source': s.source, 'value': s.value,
'normalized_value': s.normalized_value,
'evidence_ref': s.evidence_ref, 'evidence_quote': s.evidence_quote,
'line_no_in_source': s.line_no_in_source,
'format_valid': s.format_valid, 'format_reason_code': s.format_reason_code,
'extra': s.extra or {},
} for s in result.source_observations
],
'resolution': result.resolution,
'accepted_value': result.accepted_value,
'conflicts': list(result.conflicts or []),
'resolution_meta': resolution_meta or {},
}
if primary_candidate is not None:
payload['primary'] = {
'source': primary_candidate.source,
'evidence_ref': primary_candidate.evidence_ref,
'line_no': primary_candidate.effective_line_no,
}
return payload
@@ -0,0 +1,195 @@
"""
services/shipping_notice/document_layout/vc_source_candidate_conflicts.py
用途:从 ProfileFieldSourceMappingService + SourceMergeService 的运行结果
产出 Candidate 级冲突项,接入 candidate.conflicts_json。
依赖:
- vc_source_gate_contract(冲突原因码、冲突项构造器)。
- profile_field_source_mapping_service(三来源候选收集)。
- source_merge_service(合并裁决 + needs_review 标记)。
- candidate_service / ShippingOrderCandidate.structured_result_json(落库载体)。
逻辑:
[STEP 1] 从 Candidate.structured_result_json 读三来源收集的原始快照;
缺失(旧数据或未启用 VC Profile)时安全返回空列表,不阻断。
[STEP 2] 扫描 merged_candidates,needs_review 且 conflict_group_key 未人工裁决 →
构造 make_vc_candidate_conflict_item(severity=review_required)。
[STEP 3] 扫描 format_valid=False 且 format_policy.inherit_global=False 的项 →
独立原因码 vc_source_format_invalid,severity=blocking。
[STEP 4] named_region_id 指向不存在区域 → vc_source_region_unbound。
幂等:同一 conflict_group_key 仅保留一项,合并 detail 不重复追加。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.document_layout.vc_source_gate_contract import (
CQ_REASON_VC_FORMAT_INVALID,
CQ_REASON_VC_REGION_UNBOUND,
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
CQ_VC_BLOCKING_REASONS,
CQ_VC_REVIEW_REASONS,
VC_SOURCE_KIND_LABELS,
make_vc_candidate_conflict_item,
)
# CQ_VC_BLOCKING_REASONS / CQ_VC_REVIEW_REASONS 定义在 vc_source_gate_contract.py(契约层),
# 这里保留薄 re-export,供 candidate_qualification_service 等调用方按旧路径 import,
# 避免修改大量调用点时引入遗漏。
_VC_CANDIDATE_KEY = 'vendor_comments_merged'
_VC_DETAIL_MAX = 8 # 单项 detail 保留最多 8 条来源快照,防止 JSON 膨胀。
def _vc_merged_payload(candidate: Any) -> dict[str, Any] | None:
"""
从 Candidate 提取 Vendor Comments merged payload。
支持三条路径,按顺序:
1) structured_result_json.extraction.vendor_comments_merged(新抽取路径)
2) result_json.extraction.vendor_comments_merged(兼容 Worker 旧写入点)
3) candidate_json.extraction.vendor_comments_merged(影子评估的替身 dict)
任一合法 dict 即返回,否则 None(缺路径视为未启用,安全放行)。
"""
for attr in ('structured_result_json', 'result_json', 'candidate_json'):
try:
raw = getattr(candidate, attr, None)
except Exception:
raw = None
if isinstance(raw, dict):
ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None
if ext and isinstance(ext.get(_VC_CANDIDATE_KEY), dict):
return ext[_VC_CANDIDATE_KEY]
return None
def _conflict_group_key(scope: str, field_code: str, line_no: str | None) -> str:
"""稳定冲突键:与 source_merge_service 的 (scope, field_code, line_no) 一致。"""
safe_scope = 'header' if scope == 'header' else 'line'
safe_line = str(line_no or '').strip() or '_'
return f'{safe_scope}:{str(field_code or "").strip()}:{safe_line}'
def _summarize_source_observations(cand: dict[str, Any]) -> list[dict[str, Any]]:
"""
脱敏压缩 source_observations:仅保留 source / value 摘要 / evidence_ref,禁止存完整正文。
"""
obs = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else []
summary: list[dict[str, Any]] = []
for raw in obs[:_VC_DETAIL_MAX]:
if not isinstance(raw, dict):
continue
summary.append({
'source': raw.get('source'),
'source_label': VC_SOURCE_KIND_LABELS.get(str(raw.get('source') or ''), str(raw.get('source') or '')),
'value_preview': (str(raw.get('value') or '')[:64] + ('…' if len(str(raw.get('value') or '')) > 64 else '')) if raw.get('value') is not None else None,
'evidence_ref': raw.get('evidence_ref'),
})
return summary
def collect_vc_candidate_conflicts(candidate: Any) -> list[dict[str, Any]]:
"""
扫描 Vendor Comments 三来源合并结果,生成 Candidate 冲突项。
【AI 触发时机】:当 Candidate Qualification 评估、STP 自动建单前
或复核工作台加载冲突列表时,追加本函数返回值到 Candidate.conflicts_json。
Args:
candidate: ShippingOrderCandidate ORM 对象或兼容 dict(替身)。
Returns:
符合 vc_source_gate_contract.make_vc_candidate_conflict_item 契约的列表;
无冲突或未启用 VC 时返回空列表(永不返回 None)。
"""
payload = _vc_merged_payload(candidate)
if payload is None:
return []
merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else []
named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {}
enabled = payload.get('field_source_mappings') if isinstance(payload.get('field_source_mappings'), dict) else {}
# [STEP 0] 先校验 named_region 绑定:所有启用 vendor_comments 的 mapping 其 region_id 必须存在。
seen_region_errors: set[str] = set()
items: list[dict[str, Any]] = []
for field_code, mapping in enabled.items():
if not isinstance(mapping, dict):
continue
if not bool(mapping.get('vendor_comments_enabled')):
continue
rid = str(mapping.get('vendor_comments_named_region_id') or '').strip()
if rid and rid not in named_regions:
key = f'region_missing:{rid}:{field_code}'
if key in seen_region_errors:
continue
seen_region_errors.add(key)
scope_val = str(mapping.get('vendor_comments_target_scope') or mapping.get('target_scope') or 'line').strip()
scope = 'header' if scope_val == 'header' else 'line'
ckey = _conflict_group_key(scope, field_code, None)
items.append(make_vc_candidate_conflict_item(
reason=CQ_REASON_VC_REGION_UNBOUND,
scope=scope, # type: ignore[arg-type]
field_code=field_code,
conflict_group_key=ckey,
detail={'missing_region_id': rid},
))
# [STEP 1] 扫描 merged_candidates:needs_review / format_invalid。
seen_groups: set[str] = set()
for cand in merged:
if not isinstance(cand, dict):
continue
field_code = str(cand.get('target_field_code') or cand.get('field_code') or '').strip()
if not field_code:
continue
scope = str(cand.get('target_scope') or cand.get('scope') or 'line').strip()
scope_ok = 'header' if scope == 'header' else 'line'
line_no_raw = cand.get('effective_line_no') or cand.get('line_no')
line_no_safe = None if line_no_raw is None else str(line_no_raw)
ckey = _conflict_group_key(scope_ok, field_code, line_no_safe)
resolution = str(cand.get('resolution') or '').strip()
decision = str(cand.get('decision_status') or '').strip()
format_valid = cand.get('format_valid')
# 显式 False 视为非法(None 表示未启用格式策略,安全放行)。
format_invalid = (format_valid is False)
conflict_pending = resolution == 'needs_review' and decision != 'dropped'
if ckey in seen_groups:
continue
detail = {
'resolution': resolution,
'decision_status': decision,
'format_valid': format_valid,
'sources': _summarize_source_observations(cand),
}
if conflict_pending:
seen_groups.add(ckey)
line_key = str(cand.get('line_key') or '').strip() or None
items.append(make_vc_candidate_conflict_item(
reason=CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
scope=scope_ok, # type: ignore[arg-type]
field_code=field_code,
line_key=line_key,
line_no=line_no_safe,
conflict_group_key=ckey,
detail=detail,
))
elif format_invalid:
seen_groups.add(ckey)
line_key = str(cand.get('line_key') or '').strip() or None
items.append(make_vc_candidate_conflict_item(
reason=CQ_REASON_VC_FORMAT_INVALID,
scope=scope_ok, # type: ignore[arg-type]
field_code=field_code,
line_key=line_key,
line_no=line_no_safe,
conflict_group_key=ckey,
detail=detail,
))
return items
@@ -0,0 +1,230 @@
"""
services/shipping_notice/document_layout/vc_source_evidence_integration.py
用途:将 Vendor Comments 三来源 source_observations 注入 ReviewEvidenceView,
供 Chatflow LLM Review(Phase 4)与复核工作台(Phase 5)共享同一事实源。
依赖:
- vc_source_gate_contract(VENDOR_COMMENTS_OBSERVATION_SOURCE、build_vc_evidence_ref、is_valid_vc_evidence_ref)。
- order_review_llm_contract ObservationSource 兼容扩展(新增 source 不在原 frozenset 时 fail-open,不抛错)。
- Candidate.structured_result_json.extraction.vendor_comments_merged(与 vc_source_candidate_conflicts.py 同一路径)。
逻辑:
[STEP 1] 提取 VC merged payload(与 Candidate Conflicts 共享 _vc_merged_payload 逻辑,不双份)。
[STEP 2] 对每个 merged_candidate,展开其 source_observations[]:
- 构造 evidence_ref(优先 vc: 区域引用,缺失时退化 build_evidence_ref layout:)。
- source 固定 VENDOR_COMMENTS_OBSERVATION_SOURCE;子 source_kind 写入 metadata.source_kind。
- 保留 quote(原文切片)、confidence、value_bbox。
[STEP 3] 仅追加,不覆盖/替换原有 Unit/Draft/Frozen 三源证据。
幂等:同一 (evidence_ref, source_kind, value) 仅插入一条,避免 LLM 重复上下文。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.document_layout.vc_source_gate_contract import (
VENDOR_COMMENTS_OBSERVATION_SOURCE,
build_vc_evidence_ref,
is_valid_vc_evidence_ref,
)
from app.services.shipping_notice.order_review_llm_contract import (
build_evidence_ref,
is_valid_evidence_ref,
)
def _vc_merged_payload(case_or_candidate: Any) -> dict[str, Any] | None:
"""
从 ReviewCase(通过 candidate.structured)或直接 Candidate 提取 VC 载荷。
与 vc_source_candidate_conflicts._vc_merged_payload 逻辑一致但独立实现,
避免引入相互 import(两模块均零 circular 原则)。
"""
# Case 路径:先取 candidate。
candidate = getattr(case_or_candidate, 'candidate', None)
attrs_chain: list[Any] = []
if candidate is not None:
attrs_chain.append(candidate)
attrs_chain.append(case_or_candidate)
for item in attrs_chain:
for attr in ('structured_result_json', 'result_json', 'candidate_json'):
try:
raw = getattr(item, attr, None)
except Exception:
raw = None
if isinstance(raw, dict):
ext = raw.get('extraction') if isinstance(raw.get('extraction'), dict) else None
if ext and isinstance(ext.get('vendor_comments_merged'), dict):
return ext['vendor_comments_merged']
return None
def _safe_str(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _normalize_source_obs(
raw: dict[str, Any],
*,
case_document_id: int,
field_code: str | None,
line_key: str | None,
named_regions: dict[str, Any],
) -> dict[str, Any] | None:
"""
将一条 source_observation 归一化为 ReviewEvidenceView.field_evidences 项形状。
核心:evidence_ref 优先取 vc:region;若 source_kind=vendor_comments 且命中命名区域
但缺 page_no,回退从 named_regions[region_id] 取代表页号。
"""
if not isinstance(raw, dict):
return None
source_kind = _safe_str(raw.get('source')) or 'header_region'
value = raw.get('value')
quote = _safe_str(raw.get('quote') or raw.get('raw_text'))
confidence_raw = raw.get('confidence')
try:
confidence = float(confidence_raw) if confidence_raw is not None else None
except (TypeError, ValueError):
confidence = None
doc_raw = raw.get('document_id') or case_document_id
try:
doc_id = int(doc_raw)
except (TypeError, ValueError):
doc_id = int(case_document_id or 0)
page_raw = raw.get('page_no')
try:
page_no = int(page_raw) if page_raw is not None else None
except (TypeError, ValueError):
page_no = None
# Vendor Comments:若缺 page_no,按 named_regions[region_id].page_scope 推导代表页。
rid = _safe_str(raw.get('region_id') or raw.get('named_region_id'))
if source_kind == 'vendor_comments' and page_no is None and rid and isinstance(named_regions.get(rid), dict):
region_def = named_regions[rid]
page_scope = _safe_str(region_def.get('page_scope')) or 'first_page'
exact = region_def.get('exact_page_no') or region_def.get('page_no')
if page_scope == 'last_page':
# last_page 未知实际页码时安全置 1,待后续有实际渲染页号再覆盖。
page_no = page_no or 1
elif page_scope == 'exact_page' and exact is not None:
try:
page_no = int(exact)
except (TypeError, ValueError):
page_no = page_no or 1
else:
page_no = page_no or 1
evidence_ref: str | None = None
pre_ref = raw.get('evidence_ref')
if isinstance(pre_ref, str) and (is_valid_vc_evidence_ref(pre_ref) or is_valid_evidence_ref(pre_ref)):
evidence_ref = pre_ref.strip()
if not evidence_ref and source_kind == 'vendor_comments' and doc_id > 0 and page_no and rid:
evidence_ref = build_vc_evidence_ref(document_id=doc_id, page_no=page_no, region_id=rid)
if not evidence_ref and doc_id > 0 and page_no:
table_id = raw.get('table_id') if isinstance(raw.get('table_id'), str) else None
row_index = None
try:
ri = raw.get('row_index')
row_index = int(ri) if ri is not None else None
except (TypeError, ValueError):
row_index = None
evidence_ref = build_evidence_ref(
document_id=doc_id,
page_no=page_no,
table_id=table_id,
row_index=row_index,
field_code=field_code,
)
bbox = raw.get('value_bbox') if isinstance(raw.get('value_bbox'), dict) else None
bbox_valid = (
isinstance(bbox, dict)
and all(k in bbox for k in ('x0', 'y0', 'x1', 'y1'))
and 0.0 <= float(bbox['x0']) < float(bbox['x1']) <= 1.01
and 0.0 <= float(bbox['y0']) < float(bbox['y1']) <= 1.01
) if bbox else False
doc_match = bool(doc_id) and int(case_document_id or 0) > 0 and int(doc_id) == int(case_document_id)
value_bbox_dict = dict(bbox) if bbox_valid else None
return {
'value': value,
'quote': quote,
'source': VENDOR_COMMENTS_OBSERVATION_SOURCE,
'source_kind': source_kind,
'confidence': confidence,
'evidence_ref': evidence_ref,
'provenance_ref': None, # VC 来源直接走 evidence_ref,不伪装 draft provenance。
'document_id': doc_id,
'page_no': page_no,
'table_id': raw.get('table_id') if isinstance(raw.get('table_id'), str) else None,
'cell_id': raw.get('cell_id') if isinstance(raw.get('cell_id'), str) else None,
'row_index': None, # 行级由 line_key 外部关联,row_index 仅 layout table 使用。
'value_bbox': value_bbox_dict,
'value_bbox_valid': bbox_valid,
'document_matches_case': doc_match,
'field_code': field_code,
'line_key': line_key,
}
def collect_vc_field_evidences(
*,
case_or_candidate: Any,
case_document_id: int,
) -> list[dict[str, Any]]:
"""
展开 Vendor Comments 三来源 source_observations 为 ReviewEvidenceView.field_evidences 条目。
【AI 触发时机】:
- Phase 4:构建 LLM 最小证据上下文时,追加三来源引用与 quote;
- Phase 5:复核工作台加载 evidence 对照面板。
Args:
case_or_candidate: ShippingOrderReviewCase 或 ShippingOrderCandidate。
case_document_id: 当前 Case 的主文档 document_id,用于 document_matches_case。
Returns:
归一化 observation 列表;未启用 VC 或路径缺数据返回空列表。
"""
payload = _vc_merged_payload(case_or_candidate)
if payload is None:
return []
named_regions = payload.get('named_regions') if isinstance(payload.get('named_regions'), dict) else {}
merged = payload.get('merged_candidates') if isinstance(payload.get('merged_candidates'), list) else []
results: list[dict[str, Any]] = []
seen: set[tuple[str, str, str]] = set()
for cand in merged:
if not isinstance(cand, dict):
continue
field_code = _safe_str(cand.get('target_field_code') or cand.get('field_code'))
line_key = _safe_str(cand.get('line_key'))
source_list = cand.get('source_observations') if isinstance(cand.get('source_observations'), list) else []
for raw in source_list:
if not isinstance(raw, dict):
continue
norm = _normalize_source_obs(
raw,
case_document_id=int(case_document_id or 0),
field_code=field_code,
line_key=line_key,
named_regions=named_regions,
)
if norm is None:
continue
key = (
str(norm.get('evidence_ref') or ''),
str(norm.get('source_kind') or ''),
str(norm.get('value') or '')[:64],
)
if key in seen:
continue
seen.add(key)
results.append(norm)
return results
@@ -0,0 +1,204 @@
"""
services/shipping_notice/document_layout/vc_source_gate_contract.py
用途:冻结 Vendor Comments 三来源的门禁枚举、证据引用格式、冲突原因码。
依赖:零 I/O 纯契约模块,禁止 import 业务服务,避免 circular。
逻辑:
- ObservationSource 新增 vendor_comments_region(与 order_review_llm_contract.py 对齐)。
- evidence_ref 格式 vc:document_id:pN:region:<region_id> 独立校验,禁止混入 layout: 前缀。
- CQ 门禁新增 vc_source_merged_clean;原因码分「业务冲突」「格式不合法」「区域未绑定」三类。
- 所有常量写入 frozenset/tuple,供 gate/preview/audit 三处共享,禁止双份维护。
"""
from __future__ import annotations
import re
from typing import Any, Final, Literal
# ---------------------------------------------------------------------------
# 三来源字段来源种类(与前端 vc.types.ts Section E VCFieldSourceKind 一一对应)
# ---------------------------------------------------------------------------
VC_SOURCE_KINDS: Final[frozenset[str]] = frozenset({
'header_region',
'table_column',
'vendor_comments',
})
VC_SOURCE_KIND_LABELS: Final[dict[str, str]] = {
'header_region': 'Header 区域',
'table_column': '表身列',
'vendor_comments': 'Vendor Comments',
}
VC_SOURCE_EVIDENCE_PRIORITY: Final[dict[str, int]] = {
# 优先级越大越优先;与 source_merge_service.py 证据选择顺序对齐。
'vendor_comments': 3,
'table_column': 2,
'header_region': 1,
}
# ---------------------------------------------------------------------------
# 扩展 ObservationSource(与 order_review_llm_contract 原 4 类互不污染)
# ---------------------------------------------------------------------------
VENDOR_COMMENTS_OBSERVATION_SOURCE: Final[str] = 'vendor_comments_region'
ALL_OBSERVATION_SOURCES_WITH_VC: Final[frozenset[str]] = frozenset({
'unit_observation',
'draft_observation',
'frozen_layout',
'text_fallback',
VENDOR_COMMENTS_OBSERVATION_SOURCE,
})
# ---------------------------------------------------------------------------
# VC 专用 evidence_ref:vc:<document_id>:p<page_no>:region:<region_id>
# 缺任意段即视为无效,不伪造占位。
# ---------------------------------------------------------------------------
_VC_EVIDENCE_REF_RE = re.compile(
r'^vc:(?P<doc>\d+):p(?P<page>\d+):region:(?P<region>[A-Za-z0-9_\-]{1,128})$'
)
def is_valid_vc_evidence_ref(value: Any) -> bool:
"""
校验 Vendor Comments evidence_ref 是否满足三段式契约。
【AI 触发时机】:当需要将 VC 来源写入 Observation evidence_ref、
或 LLM 解析 quote 需要定位到命名区域时调用。
Args:
value: 待校验字符串。
Returns:
True 当且仅当正则命中且段值为正整数。
"""
if not isinstance(value, str) or not value:
return False
matched = _VC_EVIDENCE_REF_RE.match(value.strip())
if not matched:
return False
try:
doc = int(matched.group('doc'))
page = int(matched.group('page'))
except (TypeError, ValueError):
return False
return doc > 0 and page > 0 and bool(matched.group('region'))
def build_vc_evidence_ref(
*,
document_id: int | None,
page_no: int | None,
region_id: str | None,
) -> str | None:
"""
按契约生成 VC evidence_ref;缺任意必需段返回 None,绝不伪造。
Args:
document_id: PDF 主键,>0。
page_no: 代表页号,>0。
region_id: NamedRegion.region_id,非空。
Returns:
合法 vc: 引用或 None。
"""
if not document_id or not page_no or not region_id:
return None
try:
doc_i = int(document_id)
page_i = int(page_no)
rid = str(region_id).strip()
except (TypeError, ValueError):
return None
if doc_i <= 0 or page_i <= 0 or not rid:
return None
ref = f'vc:{doc_i}:p{page_i}:region:{rid}'
return ref if is_valid_vc_evidence_ref(ref) else None
# ---------------------------------------------------------------------------
# Candidate Qualification 门禁:vc_source_merged_clean
# ---------------------------------------------------------------------------
CQ_GATE_VC_SOURCE_MERGED_CLEAN: Final[str] = 'vc_source_merged_clean'
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED: Final[str] = 'vc_source_conflict_unresolved'
CQ_REASON_VC_FORMAT_INVALID: Final[str] = 'vc_source_format_invalid'
CQ_REASON_VC_REGION_UNBOUND: Final[str] = 'vc_source_region_unbound'
CQ_VC_BLOCKING_REASONS: Final[frozenset[str]] = frozenset({
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
CQ_REASON_VC_FORMAT_INVALID,
CQ_REASON_VC_REGION_UNBOUND,
})
# 归入 review_required(轻量人工确认)而非 hard-blocked 的原因。
CQ_VC_REVIEW_REASONS: Final[frozenset[str]] = frozenset({
CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED,
})
# ---------------------------------------------------------------------------
# 合并决议(与 SourceMergeService.resolution 对齐,前端只读不改)
# ---------------------------------------------------------------------------
VC_MERGE_RESOLUTIONS: Final[frozenset[str]] = frozenset({
'single_source_direct',
'same_value_merged',
'fill_missing',
'needs_review',
'annotation_only_dropped',
'invalid_line_reference_dropped',
})
VC_DECISION_STATUSES: Final[frozenset[str]] = frozenset({
'accepted',
'pending',
'dropped',
})
# ---------------------------------------------------------------------------
# 证据元数据键(与 Q18 metadata.shape 严格一致)
# ---------------------------------------------------------------------------
VC_EVIDENCE_META_KEYS: Final[frozenset[str]] = frozenset({
'source_observations',
'resolution',
'accepted_value',
'conflicts',
'resolution_meta',
'primary',
})
# ---------------------------------------------------------------------------
# VC Candidate Qualification 冲突项 shape(用于 candidate.conflicts_json 列表项)
# ---------------------------------------------------------------------------
def make_vc_candidate_conflict_item(
*,
reason: str,
scope: Literal['header', 'line'],
field_code: str,
line_key: str | None = None,
line_no: str | None = None,
conflict_group_key: str,
detail: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
构造符合 CQ 契约的 Vendor Comments 冲突项。
核心逻辑:reason 必须来自 CQ_VC_BLOCKING_REASONS;
conflict_group_key 用于幂等去重(同组多次评估只记一条)。
Args:
reason: 原因码,限 CQ_VC_BLOCKING_REASONS。
scope: header / line。
field_code: 订单字段,如 reservation_id。
line_key: line scope 时的逻辑行键,header 为 None。
line_no: 原始明细号字符串,便于审计。
conflict_group_key: (scope, field_code, line_no) 稳定键。
detail: 三来源 values / source_observations 快照,不含正文大对象。
Returns:
candidate.conflicts_json 列表中的一项字典。
"""
safe_reason = reason if reason in CQ_VC_BLOCKING_REASONS else CQ_REASON_VC_SOURCE_CONFLICT_UNRESOLVED
return {
'kind': 'vc_source',
'reason': safe_reason,
'severity': 'review_required' if safe_reason in CQ_VC_REVIEW_REASONS else 'blocking',
'scope': scope,
'field_code': field_code,
'line_key': line_key,
'line_no': line_no,
'conflict_group_key': conflict_group_key,
'detail': dict(detail or {}),
}
@@ -816,8 +816,7 @@ def extract_xfa_profile(
reason_codes: list[str] = []
if has_unconfirmed_split_rules:
reason_codes.append('xfa_split_rule_unconfirmed')
if required_missing:
reason_codes.append('xfa_required_field_missing')
source_mapping_incomplete = bool(required_missing)
evidence_summary = sanitize_xfa_dto({
'header_field_count': len(header_fields),
@@ -827,6 +826,7 @@ def extract_xfa_profile(
'parser_identity': XFA_PARSER_IDENTITY,
'profile_checksum': str(raw_profile.get('checksum') or '') or None,
'header_split_evidence': header_split_evidence,
'xfa_source_mapping_incomplete': source_mapping_incomplete,
'field_evidence_refs': [
item.evidence for item in header_fields
] + [
@@ -3,13 +3,18 @@ services/shipping_notice/document_layout/xfa_split_rule_contract.py
用途:冻结 XFA 字段拆分规则契约——matcher 优先级模型、segment 映射、
evidence_only 边界、正则资源上限与 Schema 校验入口。
依赖:Pydantic 2、xfa_contract、xfa_safe_regex、Flask settings(可选)。
依赖:Pydantic 2、xfa_contract、xfa_safe_regex、Flask settings(可选);
共享契约来自 field_split_core(BaseSplitNormalization / BaseSplitMatcher /
BaseSplitSegment / BaseSplitRule / BaseSplitRuleSet)。
逻辑:仅声明式校验,不执行规则、不读 PDF、不接网络;非法契约以 ValidationError
或 ValueError 拒绝;匹配优先级由引擎固定 prefix > regex > position > unmatched。
或 ValueError 拒绝;匹配优先级由引擎固定 prefix > regex > position > unmatched;
XfaSplit* 系列继承共享核心 BaseSplit*,但保留 XFA 专属字段(source_path_id /
source_data_path 等)和 XFA 前缀的环境变量读取,保持对外行为零漂移。
"""
from __future__ import annotations
import json
import os
import re
import uuid
@@ -17,6 +22,13 @@ from typing import Any, Final, Literal
from pydantic import AliasChoices, Field, field_validator, model_validator
from app.services.shipping_notice.document_layout.field_split_core import (
BaseSplitMatcher,
BaseSplitNormalization,
BaseSplitRule,
BaseSplitRuleSet,
BaseSplitSegment,
)
from app.services.shipping_notice.document_layout.xfa_contract import (
XfaContractModel,
validate_controlled_data_path,
@@ -28,6 +40,7 @@ from app.services.shipping_notice.document_layout.xfa_safe_regex import (
# ---------------------------------------------------------------------------
# 资源上限默认值(可被 settings / 环境变量覆盖)
# 注意:为保持 XFA 链路零行为变化,环境变量前缀仍使用 XFA_SPLIT_*(与共享核心 SPLIT_* 分治)
# ---------------------------------------------------------------------------
XFA_SPLIT_MAX_RULES_PER_SET: Final[int] = 32
@@ -120,8 +133,11 @@ def get_xfa_split_regex_timeout_ms() -> int:
return _config_int('XFA_SPLIT_REGEX_TIMEOUT_MS', XFA_SPLIT_REGEX_TIMEOUT_MS)
class XfaSplitSegment(XfaContractModel):
"""自定义拆分段:与 Schema 字段分离;mapped 时绑定冻结 Schema。"""
class XfaSplitSegment(BaseSplitSegment):
"""
自定义拆分段:与 Schema 字段分离;mapped 时绑定冻结 Schema。
继承共享核心 BaseSplitSegment;保留 XFA 自己的校验器以保证 XFA_ 前缀环境变量仍生效。
"""
segment_id: str = Field(min_length=8, max_length=64)
segment_code: str = Field(min_length=2, max_length=XFA_SPLIT_MAX_SEGMENT_CODE_LENGTH)
@@ -154,11 +170,12 @@ class XfaSplitSegment(XfaContractModel):
return self
class XfaSplitMatcher(XfaContractModel):
class XfaSplitMatcher(BaseSplitMatcher):
"""
单行匹配器:position / prefix / regex。
优先级由引擎固定为 prefix > regex > position;契约仅声明字段形状。
继承共享核心 BaseSplitMatcher;保留 XFA 自己的校验器与 XFA_ 前缀长度常量。
"""
type: XfaSplitMatcherType
@@ -211,7 +228,7 @@ class XfaSplitMatcher(XfaContractModel):
return self
class XfaSplitRule(XfaContractModel):
class XfaSplitRule(BaseSplitRule):
"""单条拆分规则:rule_id + matcher + segment(无 stages[])。"""
rule_id: str = Field(min_length=1, max_length=64)
@@ -219,7 +236,7 @@ class XfaSplitRule(XfaContractModel):
segment: XfaSplitSegment
class XfaSplitNormalization(XfaContractModel):
class XfaSplitNormalization(BaseSplitNormalization):
"""规则集级换行与 trim 策略:引擎按 line_breaks 拆行后再逐行匹配。"""
trim: bool = True
@@ -236,12 +253,16 @@ class XfaSplitNormalization(XfaContractModel):
return self
class XfaSplitRuleSet(XfaContractModel):
class XfaSplitRuleSet(BaseSplitRuleSet):
"""
针对单一源字段的拆分规则集,存于 Profile definition_json.split_rules。
规则由管理员手工配置(source=user/imported)。若出现历史 source=system_suggestion,
必须保持 draft + requires_confirmation,且不得进入正式提取/发布。
继承共享核心 BaseSplitRuleSet;追加 XFA 专属字段:source_path_id / source_scope /
source_field_code / source_data_path。校验器保留 XFA 自己的实现,确保 XFA_SPLIT_*
前缀环境变量、path_id 白名单校验仍然生效,不会被共享核心的默认值覆盖。
"""
rule_set_id: str = Field(
@@ -278,7 +299,7 @@ class XfaSplitRuleSet(XfaContractModel):
@model_validator(mode='after')
def validate_rule_set_invariants(self) -> 'XfaSplitRuleSet':
"""规则集内唯一性与数量上限。"""
"""规则集内唯一性与数量上限(XFA 专用,读取 XFA_SPLIT_* 环境变量前缀)。"""
max_rules = get_xfa_split_max_rules_per_set()
if len(self.rules) > max_rules:
raise ValueError(f'rules exceed max {max_rules}')
@@ -330,14 +351,16 @@ def split_rule_content_fingerprint(rule_set: XfaSplitRuleSet | dict[str, Any]) -
核心逻辑:只冻结 matcher 与 normalization;segment 的 Schema 映射字段不属于拆分逻辑,
后续绑定或解绑目标字段不得取消已确认状态。
【重要】:XFA 版指纹实现独立保留,不直接调用共享核心 base_split_content_fingerprint。
原因:未来若共享核心为 Vendor Comments 增加 relation_capture 字段纳入指纹计算,
此处必须保持 XFA 既有指纹与历史 Profile 校验和完全一致,避免发布确认状态误判。
Args:
rule_set: 模型或 dict。
Returns:
稳定 JSON 字符串指纹素材(调用方可再 hash)。
"""
import json
if isinstance(rule_set, XfaSplitRuleSet):
payload = rule_set.model_dump(mode='json', by_alias=True)
else:
@@ -2,39 +2,43 @@
services/shipping_notice/document_layout/xfa_split_rule_engine.py
用途:按冻结优先级执行 XFA 字段拆分——prefix > regex > position > unmatched。
依赖:xfa_split_rule_contract、xfa_safe_regex、concurrent.futures。
依赖:xfa_split_rule_contract(XfaSplitRuleSet extends BaseSplitRuleSet)、
field_split_core(execute_base_split_rule_set 共享核心执行)、
xfa_dataset(XfaLeafValue、mask_value_for_dto)。
逻辑:由预览 API 与正式提取调用;无网络、无脚本、无 LLM;
【阶段 1 架构】:对外 dataclass / 函数签名 100% 保持不变,
内部逻辑委托共享核心 field_split_core.execute_base_split_rule_set(),
转换 _CoreSegmentResult → XfaSplitSegmentResult 时显式丢弃 captured_relation
(Q16 方案 A:阶段 1 XFA 对外结果零字段变化);
逐行收集命中规则后按优先级决出唯一 segment;同优先级多个 mapped 命中 → needs_review;
全部候选命中写入 diagnostics;evidence_only 不写 Schema。
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Any
from app.services.shipping_notice.document_layout.field_split_core import (
CoreSplitDiagnostic,
_CoreSegmentResult,
_CoreSplitEngineResult,
execute_base_split_rule_set,
)
from app.services.shipping_notice.document_layout.xfa_dataset import XfaLeafValue
from app.services.shipping_notice.document_layout.xfa_safe_regex import (
SafeRegexError,
compile_safe_regex,
search_safe,
)
from app.services.shipping_notice.document_layout.xfa_split_rule_contract import (
XFA_SPLIT_MATCHER_PRIORITY,
XfaSplitMatcher,
XfaSplitRule,
XfaSplitRuleSet,
get_xfa_split_max_input_length,
get_xfa_split_max_regex_groups,
get_xfa_split_max_regex_pattern_length,
get_xfa_split_regex_timeout_ms,
)
# ---------------------------------------------------------------------------
# 对外 dataclass——阶段 1 零字段变化(captured_relation 不出现在 XFA 对外结果)
# ---------------------------------------------------------------------------
@dataclass
class XfaSplitSegmentResult:
"""单段执行结果(含起止行号与证据文本)。"""
"""单段执行结果(含起止行号与证据文本)。阶段 1 不含 captured_relation(Q16 方案 A)。"""
segment_id: str
segment_code: str
@@ -75,223 +79,69 @@ class XfaSplitEngineResult:
rule_version: int | None = None
@dataclass
class _LineMatch:
"""单行候选命中。"""
rule: XfaSplitRule
matcher_type: str
priority: int
line_text: str
normalized_text: str
raw_line: str
# ---------------------------------------------------------------------------
# 适配层:共享核心 → XFA 对外结果(丢弃 captured_relation)
# ---------------------------------------------------------------------------
def _split_text_by_breaks(text: str, line_breaks: list[str]) -> list[str]:
def _core_segment_to_xfa(core: _CoreSegmentResult) -> XfaSplitSegmentResult:
"""
按声明的 line_breaks 切分文本(长分隔符优先)。
Args:
text: 原始文本。
line_breaks: 换行符列表。
Returns:
切分后的行列表(尚未 trim / 去空行)。
将共享核心单段结果转换为 XFA 对外结果。
【关键约束(Q16 方案 A)】:显式不传入 captured_relation,阶段 1 XFA 对外结果零字段变化。
"""
if not text:
return []
pattern = '|'.join(re.escape(item) for item in sorted(line_breaks, key=len, reverse=True))
if not pattern:
return [text]
return re.split(pattern, text)
def _apply_line_normalization(
lines: list[str],
*,
trim: bool,
remove_empty_lines: bool,
) -> list[str]:
"""对行列表应用 trim / 去空行。"""
out = list(lines)
if trim:
out = [item.strip() for item in out]
if remove_empty_lines:
out = [item for item in out if item]
return out
def _inventory_lines(raw_value: str, rule_set: XfaSplitRuleSet) -> list[str]:
"""
用规则集级 normalization 生成行清单。
核心逻辑:按 normalization.line_breaks 拆行并应用 trim / 去空行。
"""
norm = rule_set.normalization
lines = _split_text_by_breaks(raw_value or '', list(norm.line_breaks))
return _apply_line_normalization(
lines,
trim=bool(norm.trim),
remove_empty_lines=bool(norm.remove_empty_lines),
return XfaSplitSegmentResult(
segment_id=core.segment_id,
segment_code=core.segment_code,
display_name=core.display_name,
line_no=core.line_no,
line_end_no=core.line_end_no,
raw_text=core.raw_text,
normalized_text=core.normalized_text,
handling=core.handling,
target_field_id=core.target_field_id,
target_field_code=core.target_field_code,
rule_id=core.rule_id,
status=core.status,
matcher_type=core.matcher_type,
)
def _extract_prefix_value(line: str, matcher: XfaSplitMatcher) -> str | None:
def _core_diagnostic_to_xfa(core: CoreSplitDiagnostic) -> XfaSplitDiagnostic:
"""将共享核心诊断转换为 XFA 对外诊断。"""
return XfaSplitDiagnostic(
code=core.code,
message=core.message,
line_no=core.line_no,
field_code=core.field_code,
rule_ids=list(core.rule_ids),
)
def _core_result_to_xfa(core: _CoreSplitEngineResult) -> XfaSplitEngineResult:
"""
前缀匹配:标签 + 分隔符后的值。
Returns:
提取值;无法匹配时 None。
将共享核心完整引擎结果转换为 XFA 对外结果。
关键转换点:
1. rule_set_id → rule_id(XFA 对外使用 rule_id 键名,兼容历史调用);
2. 所有 segments / evidence_only_segments 丢弃 captured_relation;
3. mapped_fields 原样透传(key 结构完全一致)。
"""
label = str(matcher.value or '')
hay = line if matcher.case_sensitive else line.casefold()
needle = label if matcher.case_sensitive else label.casefold()
if not hay.startswith(needle):
return None
rest = line[len(label):]
for sep in matcher.separators:
if rest.startswith(sep):
return rest[len(sep):].strip()
stripped = rest.lstrip()
if stripped.startswith(sep):
return stripped[len(sep):].strip()
return None
xfa_segments = [_core_segment_to_xfa(s) for s in core.segments]
xfa_evidence_only = [_core_segment_to_xfa(s) for s in core.evidence_only_segments]
xfa_diagnostics = [_core_diagnostic_to_xfa(d) for d in core.diagnostics]
return XfaSplitEngineResult(
status=core.status,
segments=xfa_segments,
mapped_fields=dict(core.mapped_fields),
evidence_only_segments=xfa_evidence_only,
diagnostics=xfa_diagnostics,
rule_id=core.rule_set_id,
rule_version=core.rule_version,
)
def _regex_extract_value(line: str, matcher: XfaSplitMatcher) -> tuple[str | None, str | None]:
"""
正则捕获单行文本。
Returns:
(value, error_code);成功时 error_code 为 None。
"""
pattern = str(matcher.pattern or '')
timeout_ms = get_xfa_split_regex_timeout_ms()
max_len = get_xfa_split_max_regex_pattern_length()
max_groups = get_xfa_split_max_regex_groups()
try:
compiled = compile_safe_regex(
pattern,
case_sensitive=bool(matcher.case_sensitive),
max_length=max_len,
max_groups=max_groups,
)
matched = search_safe(compiled, line, timeout_ms=timeout_ms)
except SafeRegexError:
return None, 'regex_failed'
except TimeoutError:
return None, 'regex_timeout'
if not matched:
return None, 'regex_not_matched'
group = matcher.capture_group
try:
if group is None:
if matched.lastindex:
return str(matched.group(1) or '').strip(), None
return str(matched.group(0) or '').strip(), None
return str(matched.group(group) or '').strip(), None
except IndexError:
return None, 'regex_failed'
def _match_line(line_no: int, line: str, rule: XfaSplitRule) -> tuple[_LineMatch | None, str | None]:
"""
判断单条规则是否命中指定行。
Returns:
(match, error_code):命中时 error_code 为 None;未命中时 match 为 None。
"""
matcher = rule.matcher
priority = XFA_SPLIT_MATCHER_PRIORITY.get(matcher.type)
if priority is None:
return None, 'unknown_matcher'
if matcher.type == 'position':
if int(matcher.line_index or 0) != line_no:
return None, None
normalized = line.strip() if line else ''
return _LineMatch(
rule=rule,
matcher_type='position',
priority=priority,
line_text=line,
normalized_text=normalized,
raw_line=line,
), None
if matcher.type == 'prefix':
extracted = _extract_prefix_value(line, matcher)
if extracted is None:
return None, None
return _LineMatch(
rule=rule,
matcher_type='prefix',
priority=priority,
line_text=line,
normalized_text=extracted,
raw_line=line,
), None
if matcher.type == 'regex':
value, err = _regex_extract_value(line, matcher)
if err:
return None, err
if value is None:
return None, None
return _LineMatch(
rule=rule,
matcher_type='regex',
priority=priority,
line_text=line,
normalized_text=value,
raw_line=line,
), None
return None, 'unknown_matcher'
def _pick_line_winner(
line_no: int,
matches: list[_LineMatch],
diagnostics: list[XfaSplitDiagnostic],
) -> _LineMatch | None:
"""
按 prefix > regex > position 决出单行唯一胜出规则。
核心逻辑:同优先级多个 mapped 命中 → duplicate_line_match;不同优先级取最高优先级。
"""
if not matches:
return None
diagnostics.append(XfaSplitDiagnostic(
code='line_match_candidates',
message='All matcher hits for line recorded',
line_no=line_no,
rule_ids=[item.rule.rule_id for item in matches],
))
best_priority = min(item.priority for item in matches)
tier = [item for item in matches if item.priority == best_priority]
mapped_tier = [item for item in tier if item.rule.segment.handling == 'mapped']
if len(mapped_tier) >= 2:
diagnostics.append(XfaSplitDiagnostic(
code='duplicate_line_match',
message='Multiple mapped rules matched the same line at the same priority',
line_no=line_no,
rule_ids=[item.rule.rule_id for item in mapped_tier],
))
if len(tier) == 1:
return tier[0]
if len(mapped_tier) == 1:
return mapped_tier[0]
if len(mapped_tier) >= 2:
return sorted(mapped_tier, key=lambda item: item.rule.rule_id)[0]
return sorted(tier, key=lambda item: item.rule.rule_id)[0]
# ---------------------------------------------------------------------------
# 对外执行入口——签名 100% 不变
# ---------------------------------------------------------------------------
def execute_split_rule_set(
@@ -303,7 +153,11 @@ def execute_split_rule_set(
"""
对单个源字段原值执行拆分规则集。
核心逻辑:
【阶段 1 委托模式】:不重复实现逐行匹配逻辑,直接调用共享核心
execute_base_split_rule_set() 执行纯文本拆分,再通过适配层转换回 XFA
对外结果形状。XfaSplitRuleSet extends BaseSplitRuleSet,因此可直接透传。
核心逻辑(由共享核心保证字节级一致):
1. normalization.line_breaks 拆行;
2. 逐行收集命中规则,按 prefix > regex > position 决出唯一 segment;
3. 同优先级多个 mapped 命中 → duplicate_line_match / needs_review;
@@ -312,149 +166,18 @@ def execute_split_rule_set(
Args:
raw_value: 保留换行的原始叶子值。
rule_set: 已校验规则集。
rule_set: 已校验规则集(XfaSplitRuleSet extends BaseSplitRuleSet)。
lines: 可选预切分行(覆盖 normalization 结果)。
Returns:
XfaSplitEngineResult。
XfaSplitEngineResult——字段零变化,captured_relation 已丢弃。
"""
if len(raw_value or '') > get_xfa_split_max_input_length():
return XfaSplitEngineResult(
status='needs_review',
diagnostics=[XfaSplitDiagnostic(
code='input_too_long',
message='Split source value exceeds max input length',
)],
rule_id=rule_set.rule_set_id,
rule_version=rule_set.rule_version,
)
inventory = list(lines) if lines is not None else _inventory_lines(raw_value, rule_set)
diagnostics: list[XfaSplitDiagnostic] = []
segments: list[XfaSplitSegmentResult] = []
claimed_lines: set[int] = set()
# [STEP 1] 逐行匹配并按优先级决出胜出规则。
for line_no, line in enumerate(inventory, start=1):
matches: list[_LineMatch] = []
for rule in rule_set.rules:
outcome, error = _match_line(line_no, line, rule)
if error:
diagnostics.append(XfaSplitDiagnostic(
code=error,
message=f'Rule {rule.rule_id} regex failed on line {line_no}',
line_no=line_no,
field_code=rule.segment.target_field_code,
rule_ids=[rule.rule_id],
))
continue
if outcome is not None:
matches.append(outcome)
winner = _pick_line_winner(line_no, matches, diagnostics)
if winner is None:
continue
claimed_lines.add(line_no)
seg = winner.rule.segment
status = 'parsed'
if not str(winner.normalized_text).strip() and seg.handling == 'mapped':
status = 'needs_review'
diagnostics.append(XfaSplitDiagnostic(
code='mapped_value_empty',
message=f'Mapped segment {seg.segment_code} extracted empty value',
line_no=line_no,
field_code=seg.target_field_code,
rule_ids=[winner.rule.rule_id],
))
segments.append(XfaSplitSegmentResult(
segment_id=seg.segment_id,
segment_code=seg.segment_code,
display_name=seg.display_name,
line_no=line_no,
line_end_no=line_no,
raw_text=winner.raw_line,
normalized_text=winner.normalized_text,
handling=seg.handling,
target_field_id=seg.target_field_id,
target_field_code=seg.target_field_code,
rule_id=winner.rule.rule_id,
status=status,
matcher_type=winner.matcher_type,
))
# [STEP 2] 未匹配行。
for line_index, line in enumerate(inventory, start=1):
if line_index in claimed_lines:
continue
status = 'needs_review' if rule_set.unmatched_line_policy == 'needs_review' else 'parsed'
if status == 'needs_review':
diagnostics.append(XfaSplitDiagnostic(
code='unmatched_line',
message='Unmatched line requires review',
line_no=line_index,
))
segments.append(XfaSplitSegmentResult(
segment_id=f'unmatched-{line_index}',
segment_code=f'unmatched_line_{line_index}',
display_name=f'其他编码/{line_index}',
line_no=line_index,
line_end_no=line_index,
raw_text=line,
normalized_text=line.strip(),
handling='evidence_only',
target_field_id=None,
target_field_code=None,
rule_id='unmatched',
status=status,
matcher_type='unmatched',
))
# [STEP 3] 聚合正式字段。
mapped_fields: dict[str, str] = {}
field_sources: dict[str, list[str]] = {}
overall = 'parsed'
for item in segments:
if item.status == 'needs_review':
overall = 'needs_review'
if item.handling != 'mapped' or not item.target_field_code:
continue
code = item.target_field_code
field_sources.setdefault(code, []).append(item.rule_id)
if code in mapped_fields:
overall = 'needs_review'
diagnostics.append(XfaSplitDiagnostic(
code='same_field_multiple_segment',
message=f'Schema field {code} hit by multiple segments',
field_code=code,
rule_ids=list(field_sources[code]),
))
else:
mapped_fields[code] = item.normalized_text
for _code, sources in field_sources.items():
if len(sources) > 1 and rule_set.same_field_multiple_segment_policy == 'needs_review':
overall = 'needs_review'
if any(d.code == 'duplicate_line_match' for d in diagnostics):
if rule_set.duplicate_match_policy == 'needs_review':
overall = 'needs_review'
if any(d.code in {
'regex_timeout', 'regex_failed', 'mapped_value_empty', 'input_too_long',
} for d in diagnostics):
overall = 'needs_review'
evidence_only = [item for item in segments if item.handling == 'evidence_only']
return XfaSplitEngineResult(
status=overall,
segments=segments,
mapped_fields=mapped_fields,
evidence_only_segments=evidence_only,
diagnostics=diagnostics,
rule_id=rule_set.rule_set_id,
rule_version=rule_set.rule_version,
core_result = execute_base_split_rule_set(
raw_value=raw_value,
rule_set=rule_set,
lines=lines,
)
return _core_result_to_xfa(core_result)
def execute_split_on_leaf(
@@ -486,6 +209,8 @@ def project_split_result_safe(
核心逻辑:默认脱敏 mapped/segment 文本;仅当调用方已通过敏感读权限且
include_full_values=True 时返回 raw_text / 完整 mapped 值。
evidence_only_segments 避免与 segments 重复展示(置空列表)。
【阶段 1 零契约漂移】:JSON 键名(rule_id 而非 rule_set_id)、段结构、
诊断结构完全与历史一致。
Args:
result: 引擎输出。
@@ -56,6 +56,8 @@ DOCUMENT_PARSE_REASON_CODES: Final[frozenset[str]] = frozenset({
'generic_gate_blocked',
'order_extraction_failed',
'order_extraction_cancelled',
'profile_schema_mismatch',
'row_needs_review',
# XFA 数据路径(阶段 0 冻结)
'xfa_dataset_missing',
'xfa_unsafe_xml',
@@ -68,6 +70,7 @@ DOCUMENT_PARSE_REASON_CODES: Final[frozenset[str]] = frozenset({
'xfa_profile_not_matched',
'xfa_profile_ambiguous',
'xfa_required_field_missing',
'xfa_source_mapping_incomplete',
'xfa_mirror_collection_mismatch',
'xfa_acroform_mismatch',
'xfa_business_validation_failed',
@@ -93,6 +96,7 @@ DOCUMENT_PARSE_REASON_CODES: Final[frozenset[str]] = frozenset({
# 字段抽取、客户与订单校验
ORDER_FIELD_REASON_CODES: Final[frozenset[str]] = frozenset({
'required_field_missing',
'final_required_field_missing',
'field_value_invalid',
'field_low_confidence',
'classification_low_confidence',
@@ -229,6 +233,12 @@ EXPLAINABILITY_REASON_ALIASES: Final[dict[str, str]] = {
'effective_reservation_missing': 'reservation_missing',
# Candidate 人工驳回历史码 → 关闭类稳定码
'manual_rejected': 'task_rejected_by_user',
# 订单 Schema 字段必填:旧码 → 新 canonical 码
'required_field_missing': 'final_required_field_missing',
# Profile/Schema 结构性不匹配:旧码 → 新 canonical 码
'order_profile_snapshot_field_mismatch': 'profile_schema_mismatch',
# XFA 字段值缺失:旧码 → 非阻断的来源暂缺诊断码
'xfa_required_field_missing': 'xfa_source_mapping_incomplete',
# XFA AppError / 大写错误码 → 稳定原因码
'XFA_DATASET_MISSING': 'xfa_dataset_missing',
'XFA_UNSAFE_XML': 'xfa_unsafe_xml',
@@ -240,7 +250,7 @@ EXPLAINABILITY_REASON_ALIASES: Final[dict[str, str]] = {
'XFA_UNSUPPORTED_DOCUMENT': 'xfa_unsupported_document',
'XFA_PROFILE_NOT_MATCHED': 'xfa_profile_not_matched',
'XFA_PROFILE_AMBIGUOUS': 'xfa_profile_ambiguous',
'XFA_REQUIRED_FIELD_MISSING': 'xfa_required_field_missing',
'XFA_REQUIRED_FIELD_MISSING': 'xfa_source_mapping_incomplete',
'XFA_MIRROR_COLLECTION_MISMATCH': 'xfa_mirror_collection_mismatch',
'XFA_ACROFORM_MISMATCH': 'xfa_acroform_mismatch',
'XFA_BUSINESS_VALIDATION_FAILED': 'xfa_business_validation_failed',
@@ -352,6 +362,7 @@ ORDER_FIELD_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'reservation_duplicate',
'duplicate_unresolved',
'required_field_missing',
'final_required_field_missing',
'field_value_invalid',
'field_conflict',
'field_low_confidence',
@@ -372,6 +383,9 @@ DOCUMENT_PARSE_REASON_CODES_EMITTED: Final[frozenset[str]] = frozenset({
'order_extraction_failed',
'order_extraction_cancelled',
'generic_gate_blocked',
'profile_schema_mismatch',
'row_needs_review',
'xfa_source_mapping_incomplete',
})
# 建单 / 冻结已接线子集(与 Gate 投影共用)
@@ -453,8 +467,12 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'profile_not_matched': _meta('owner', 'open_profile_review', '未能匹配文档模板,请人工确认 Profile'),
'profile_ambiguous': _meta('owner', 'open_profile_review', '文档模板存在歧义,请人工确认 Profile'),
'profile_drift': _meta('owner', 'open_profile_review', '文档结构与模板版本不一致'),
'profile_schema_mismatch': _meta('owner', 'open_profile_review', '当前模板字段定义与本次冻结 Schema 不一致,无法安全自动处理'),
'row_needs_review': _meta('owner', 'open_order_review', '部分明细行存在格式问题,需要人工复核'),
'extraction_incomplete': _meta('worker', 'retry_order_extraction', '订单字段抽取未完成,请重试或进入复核'),
'required_field_missing': _meta('owner', 'edit_order_fields', '缺少创建订单所需字段'),
'final_required_field_missing': _meta('owner', 'edit_order_fields', '最终订单缺少必填字段(经邮件/坐标/推导合并后仍缺失)'),
'xfa_source_mapping_incomplete': _meta('owner', 'open_order_review', 'XFA 数据集当前暂缺部分字段值,可经邮件/坐标补齐'),
'field_value_invalid': _meta('owner', 'edit_order_fields', '部分字段格式不正确'),
'field_low_confidence': _meta('owner', 'open_order_review', '部分识别结果置信度较低'),
'classification_low_confidence': _meta('owner', 'open_order_review', '订单分类置信度不足'),
@@ -511,6 +529,10 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'),
'inventory_rpa_exhausted': _meta('owner', 'upload_inventory_file', '库存源重试次数已耗尽'),
'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'),
'inventory_candidates_missing': _meta('owner', 'open_inventory_source_review', '正式库存候选版本缺失'),
'inventory_candidate_data_incomplete': _meta('owner', 'open_inventory_source_review', '库存候选事实不完整'),
'inventory_candidate_version_stale': _meta('owner', 'open_inventory_source_review', '库存候选版本已切换'),
'inventory_match_out_of_candidate_scope': _meta('owner', 'open_inventory_source_review', '库存命中超出当前候选范围'),
'inventory_file_identity_mismatch': _meta('owner', 'retry_inventory_preparation', '返回文件与所选库存源不一致'),
'inventory_file_empty': _meta('owner', 'retry_inventory_preparation', '库存文件为空或没有有效库存记录'),
'inventory_mapping_required': _meta('owner', 'confirm_inventory_field_mapping', '库存字段映射待确认'),
@@ -1015,3 +1037,9 @@ def assert_error_explainability_contract_integrity() -> None:
# blocking_reason_code 为动态透传占位,不要求属于冻结集合
if code != 'blocking_reason_code':
assert code in frozen, f'{node} reason_code {code} not frozen'
# [STEP 7] 门禁契约用户态映射闭环(GATE/EXEC/REASON → USER_STATE)
from app.services.shipping_notice.process_gate_contract import (
assert_process_gate_contract_integrity,
)
assert_process_gate_contract_integrity()
@@ -21,6 +21,7 @@ from zoneinfo import ZoneInfo
from flask import current_app
from openpyxl import load_workbook
from sqlalchemy import func
from app import db
from app.models import (
ShippingExcelTemplate,
@@ -302,14 +303,70 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
Raises:
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
AppError: [T6 硬门禁] 行级库存匹配存在非 matched 行(shortage / not_found / conflict)。
"""
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
from app.core.errors import AppError
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
# [T6 E2 硬门禁] 生成 Excel 前强制断言所有当前行匹配结果均为 matched;
# 即使单源任务有明确 inventory_source_code,行级短缺/冲突仍须先处理,避免导出不完整数据。
if task.id is not None:
pending_rows = db.session.query(
ShippingNoticeLineInventoryMatch.line_key,
ShippingNoticeLineInventoryMatch.match_result,
ShippingNoticeLineInventoryMatch.part_number,
ShippingNoticeLineInventoryMatch.reservation_id,
ShippingNoticeLineInventoryMatch.shortage_qty,
).filter(
ShippingNoticeLineInventoryMatch.task_id == task.id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result != 'matched',
).limit(20).all()
pending_count = db.session.query(func.count(ShippingNoticeLineInventoryMatch.id)).filter(
ShippingNoticeLineInventoryMatch.task_id == task.id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result != 'matched',
).scalar() or 0
if pending_count > 0:
details = [
{
'line_key': r[0],
'match_result': r[1],
'part_number': r[2],
'reservation_id': r[3],
'shortage_qty': r[4],
}
for r in pending_rows
]
raise AppError(
error_code='excel_not_ready',
status_code=409,
blocking_reason_code='inventory_match_incomplete',
message=f'存在 {pending_count} 行库存未完全匹配,禁止生成发货 Excel(请先处理短缺或冲突)。',
details={
'pending_count': int(pending_count),
'pending_rows_preview': details,
'resume_suggestion': '调用 match_inventory 重匹配或人工逐行确认短缺/冲突后再导出。',
},
)
source_code = str(task.inventory_source_code or '').strip().upper()
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
if source is None:
# [T6 多候选兼容] 单源 resolved 走上方 inventory_source_code;多候选 candidates_frozen 时可能 source_code==None,
# 在严格全行 matched 前提下可退回到第一条 line_match 的 inventory_source_code(保证不绕过断言)。
first_match = db.session.query(ShippingNoticeLineInventoryMatch.inventory_source_code).filter(
ShippingNoticeLineInventoryMatch.task_id == task.id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_source_code.isnot(None),
).limit(1).first()
source_code_candidate = str(first_match[0]).strip().upper() if first_match and first_match[0] else ''
source = ShippingInventorySource.query.filter_by(source_code=source_code_candidate, enabled=True).first() if source_code_candidate else None
if source is None:
raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
# Fixed Sources receive this value from configuration; dynamic Sources receive it
@@ -414,6 +414,10 @@ def _trigger_freight_upload_rpa(
task.error_message = t('workflow.fulfillment.upload_exhausted', lang=lang).format(attempts=attempts)
log_task_event(task, 'upload_rpa_exhausted', {'attempts': attempts, 'max_attempts': max_attempts})
db.session.commit()
# RPA 成功只登记可信回执;P0-3 completed 仍必须由 receipt Gate 重读事实决定。
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
submit_auto_progress(task=task, trigger='freight_upload_rpa_callback_succeeded', commit=True)
return tool_response(
status='needs_human',
task=task,
@@ -786,6 +790,413 @@ def _order_extraction_gate_response(
return None
def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, Any]:
"""
题5B:行级库存匹配(仅目标 line_key)—— 避免整单重算覆盖其他行证据/时间戳。
【AI 触发时机】:用户仅对某一行点「重试匹配库存」或系统侧决策为 ACTION_REMATCH & 有 snapshot_id 时调用;
必须 line_key 非空,不回退到整单。
核心逻辑:
[STEP 1] 共用 match_inventory 的门禁/库存快照载入;
[STEP 2] 仅 purpose_lines 中 line_key == 目标 的那条 purpose_line 生成单元素 stp_order_lines;
[STEP 3] 调 match_order_lines_across_candidates(单条 order_lines);
[STEP 4] persist_line_inventory_match_facts:line_results 只写该条(其他行 untouched);
[STEP 5] 整单汇总用:match_status 按全行事实重算(读现有的 line_inventory_match 表),
不直接 trust 本单条结果的 fulfillable 结论(避免局部 ok 掩盖全局 shortage)。
Args:
payload: 含 task_no / operator_id / expected_order_task_no 等,与 match_inventory 一致。
line_key: 必填;目标行业务键(shipping_order_fields.line_key 或 line-{idx})。
Returns:
Tool 标准响应(status ok / needs_human / failed)。
"""
# T5 Orchestrator 守卫:外部收口 run_task_auto_progress(但内部 dispatch 可以直跑)
if not payload.get('_orchestrator_internal_dispatch', False):
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
from app.services.shipping_notice.query_service import resolve_task_from_payload as _rtp
task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip()
if not task_no and isinstance(payload, dict):
_t = _rtp(payload)
task_no = str(getattr(_t, 'task_no', '') or '').strip()
trigger = str(payload.get('source') or payload.get('trigger') or 'tool_api_match_inventory_line').strip()
actor_raw = payload.get("operator_id") or payload.get("actor_id") or payload.get("_trusted_user_id")
try:
operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != "system" else None
except (TypeError, ValueError):
operator_id = None
return run_task_auto_progress(
task_no, trigger=trigger,
expected_version=None,
idempotency_key=str(payload.get('idempotency_key') or '').strip() or None,
resume_gate_code='inventory_matching',
operator_id=operator_id,
line_scope_key=str(line_key or '').strip() or None,
)
target_key = str(line_key or '').strip()
if not target_key:
return tool_response(status='failed', message='行级库存匹配必须提供 line_key')
lang = resolve_lang(payload)
actor_id = _event_actor_id(payload)
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message=t("workflow.fulfillment.task_not_found", lang=lang))
# 正式候选冻结任务必须绑定当前 frozen CandidateSet;缺失时禁止回退旧单源/JSON 路径。
from app.services.shipping_notice.inventory_candidate_projection import (
build_inventory_candidate_blocking_reason,
build_inventory_candidate_primary_action,
get_active_candidate_set,
)
if str(task.inventory_source_status or '').strip() == 'candidates_frozen':
active_candidate_set = get_active_candidate_set(task)
if active_candidate_set is None:
return tool_response(
status='needs_human',
task=task,
message='当前库存候选版本缺失或已失效,需重新确认库存来源。',
data={
**serialize_task_for_tool(task),
'blocking_reason': build_inventory_candidate_blocking_reason(
'inventory_candidate_version_stale', task=task,
),
'primary_action': build_inventory_candidate_primary_action(),
},
checkpoint='inventory_source_review',
stop_agent_turn=True,
)
# ownership & gates
from app.services.shipping_notice.processing_ownership import assert_notice_task_ownership
assert_notice_task_ownership(
task,
expected_order_task_no=str(payload.get('expected_order_task_no') or '').strip() or None,
expected_review_case_no=str(payload.get('expected_review_case_no') or '').strip() or None,
expected_run_no=str(payload.get('expected_run_no') or '').strip() or None,
actor_id=actor_id,
)
disposition_gate = _task_disposition_gate_response(task)
if disposition_gate is not None:
return disposition_gate
customer_gate = customer_gate_tool_response(task, operation='match_inventory_line')
if customer_gate is not None:
return customer_gate
conflict_gate = field_conflict_gate_response(task, lang=lang)
if conflict_gate is not None:
return conflict_gate
reservation_gate = _reservation_gate_response(
task,
lang=lang,
forbidden_next_tools=[
"ensure_inventory",
"match_inventory",
"generate_shipment_excel",
"upload_to_freight",
],
)
if reservation_gate is not None:
return reservation_gate
extraction_gate = _order_extraction_gate_response(
task,
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
)
if extraction_gate is not None:
return extraction_gate
# [STEP 1] inventory snapshot
inventory_lines = parse_inventory_lines(payload)
if inventory_lines:
task.inventory_lines_json = inventory_lines
else:
inventory_lines = active_inventory_lines_for_task(task)
if not inventory_lines:
# 行级没有快照 → 直接要求 ensure_inventory(和整单一致语义)
inv_payload: dict[str, Any] = {"task_id": task.task_no, 'line_key': target_key}
lang_suffix = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
if lang_suffix:
inv_payload["lang"] = lang_suffix
return ensure_inventory(inv_payload)
if not is_inventory_source_stable(task):
return tool_response(
status="needs_human",
task=task,
message="库存源尚未确定,无法执行行级库存匹配。",
data=serialize_task_for_tool(task),
checkpoint="inventory_source_review",
stop_agent_turn=True,
)
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_line_inventory_match import (
attach_candidate_scope_to_order_lines,
apply_forced_match_source_filter,
apply_line_inventory_resolutions,
match_order_lines_across_candidates,
snapshot_header_reservation_id,
)
inventory_lines = apply_forced_match_source_filter(inventory_lines or [], task=task)
_order_header_values, order_field_lines = order_field_id_values(task)
purpose_lines = task_line_purpose_values(task, required={'part_number', 'quantity', 'reservation_id'})
# [STEP 2] 定位目标行 purpose_line + order_field_line
target_pair: tuple[int, dict[str, Any], dict[str, Any]] | None = None
for idx, purpose_line in enumerate(purpose_lines):
ofl = order_field_lines[idx] if idx < len(order_field_lines) else {}
candidate_key = str(
purpose_line.get('line_key')
or ofl.get('line_key')
or f'line-{idx + 1}'
).strip()
if candidate_key == target_key:
target_pair = (idx, purpose_line, ofl)
break
if target_pair is None:
# line_key 未找到(可能草稿与 OT 行未对齐)
return tool_response(
status='failed',
task=task,
message=f'未找到行 {target_key},无法执行行级库存匹配。',
data=serialize_task_for_tool(task),
)
orig_idx, purpose_line, order_field_line = target_pair
required_qty = purpose_line.get('quantity')
display_part = purpose_line.get('part_number')
display_rsv = purpose_line.get('reservation_id')
display_uom = (
purpose_line.get('uom')
or purpose_line.get('unit')
or order_field_line.get('uom')
or order_field_line.get('unit')
)
order_field_line['__required_qty'] = required_qty
order_field_line['__display_part_number'] = display_part
order_field_line['__display_reservation_id'] = display_rsv
order_field_line['__display_uom'] = display_uom
_sync_workflow_stage(
task,
lifecycle_status='inventory_matching',
event_code='inventory_match_line_started',
actor_id=actor_id,
payload={'task_no': task.task_no, 'line_key': target_key, 'line_index': orig_idx},
)
db.session.flush()
header_reservation = None
snapshot = None
if task.order_snapshot_id:
from app.models import ShippingOrderSnapshot
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
if snapshot is not None:
header_reservation = snapshot_header_reservation_id(snapshot)
stp_order_lines = [{
**purpose_line,
'__required_qty': required_qty,
'__display_part_number': display_part,
'__display_reservation_id': display_rsv,
'__display_uom': display_uom,
'uom': display_uom,
'line_key': order_field_line.get('line_key') or target_key,
'line_index': orig_idx,
}]
# [STEP 3] 只跑目标行 match
match_payload = match_order_lines_across_candidates(
order_lines=attach_candidate_scope_to_order_lines(task, stp_order_lines),
inventory_lines=inventory_lines or [],
header_reservation_id=header_reservation,
)
# resolutions 注入 line_key(保证 persist 时精准)
for res in (match_payload.get('resolutions') or []):
if isinstance(res, dict):
res['line_key'] = (
str(res.get('line_key') or '').strip()
or order_field_line.get('line_key')
or target_key
)
# [STEP 4] 持久化仅本行(其他行 is_current 保持不变)
from app.services.shipping_notice.line_inventory_match_persistence import (
persist_line_inventory_match_facts,
)
persist_line_inventory_match_facts(
task=task,
match_payload=match_payload,
inventory_snapshot_id=(
int(task.inventory_snapshot_id) if task.inventory_snapshot_id else None
),
matching_rule_version='stp_line_v2',
)
# 行级 apply_line_inventory_resolutions:但不能全量覆盖 task.match_status,
# 改写成「增量合并」:把本 line 的 resolution 合并进 task.step_payload_json.line_inventory_resolutions,
# 再基于现有的全部 current 行事实重算 match_status。
_merge_line_inventory_resolutions(task, match_payload, line_key=target_key)
line_results = list(match_payload.get('line_results') or [])
from app.services.shipping_notice.reservation_service import record_inventory_verification
verification = record_inventory_verification(
task, inventory_snapshot_id=task.inventory_snapshot_id,
source_config_version=task.inventory_source_config_version, line_results=line_results,
)
# [STEP 5] 基于 current 行事实重新聚合 match_status,避免局部 ok 覆盖全局 shortage。
aggregate_match_status, aggregate_shortages = _recompute_task_match_aggregate(task)
task.match_status = aggregate_match_status
# shortages 保持整单范围(用于展示),行级单独记录到 detail_json
line_result_status = str(match_payload.get('match_status') or 'unfulfillable')
set_task_step_progress(
task,
step_key="step5_match_inventory",
step_title="匹配库存",
status="running",
message=t("workflow.fulfillment.match_running", lang=lang),
progress_percent=50,
detail=(
t("workflow.fulfillment.match_line_result", lang=lang)
.format(line_key=target_key, line_result=line_result_status)
),
)
match_summary = format_match_summary(
aggregate_match_status,
_current_line_results(task),
task_no=task.task_no,
lang=lang,
)
if aggregate_match_status == 'fulfillable' and task.inventory_source_code:
apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE)
log_task_event(
task,
"matched_stp_line_rematch_ok",
{
"match_status": aggregate_match_status,
"verification_id": verification.id,
"resolved_ok_source_codes": (task.step_payload_json or {}).get('resolved_ok_source_codes'),
"excel_binding_source_code": task.inventory_source_code,
"line_key": target_key,
"line_result": line_result_status,
},
actor_id=actor_id,
source='workspace_api' if actor_id else 'system',
)
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
enqueue_post_ot_auto_fulfill_job,
)
enqueue_post_ot_auto_fulfill_job(
task_no=str(task.task_no),
trigger='inventory_ready_rematch_line',
commit=False,
)
db.session.commit()
match_result = tool_response(
status="ok",
task_id=task.task_no,
message=match_summary,
data=serialize_task_for_tool(task),
checkpoint=f'line:{target_key}:rematch:ok',
)
return try_auto_chain_after_match(task, match_result, payload=payload)
apply_task_transition(task, TaskTransition.MATCH_SHORTAGE)
log_task_event(
task,
"matched_stp_line_rematch_shortage",
{
"match_status": aggregate_match_status,
"line_key": target_key,
"line_result": line_result_status,
"shortages": aggregate_shortages,
},
actor_id=actor_id,
source='workspace_api' if actor_id else 'system',
)
from app.services.shipping_notice.line_auto_fulfill_coordinator import (
enqueue_post_ot_auto_fulfill_job,
)
enqueue_post_ot_auto_fulfill_job(
task_no=str(task.task_no),
trigger='inventory_ready_rematch_line',
commit=False,
)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=match_summary,
data=serialize_task_for_tool(task),
checkpoint=f'shortage_review:line:{target_key}',
stop_agent_turn=True,
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
def _merge_line_inventory_resolutions(
task: ShippingNotice, match_payload: dict[str, Any], *, line_key: str
) -> None:
"""把行级 match_payload.resolutions 合并进 task.step_payload_json.line_inventory_resolutions(只替换/追加本行条目)。"""
payload_step = dict(task.step_payload_json or {})
old_resolutions = [
r for r in list(payload_step.get('line_inventory_resolutions') or [])
if isinstance(r, dict) and str(r.get('line_key') or f'line-{int(r.get("line_index") or 0) + 1}').strip() != str(line_key)
]
new_resolutions = [r for r in list(match_payload.get('resolutions') or []) if isinstance(r, dict)]
merged_resolutions = [*old_resolutions, *new_resolutions]
payload_step['line_inventory_resolutions'] = merged_resolutions
payload_step.pop('multi_source_excel_block', None)
task.step_payload_json = payload_step
# line_results_json & shortage_json 保持整单范围不在这里单行替换;统一由 recompute 使用 facts 重算
def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dict[str, Any]]]:
"""根据 ShippingNoticeLineInventoryMatch(current=True)重新聚合成 match_status(fulfillable/partial/unfulfillable)+ shortages。"""
rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), is_current=True)
.all()
)
if not rows:
return 'unfulfillable', []
has_ok = False
has_block = False
shortages: list[dict[str, Any]] = []
task.line_results_json = []
for row in rows:
match_result = str(getattr(row, 'match_result', '') or '').strip()
required_qty = getattr(row, 'required_qty', None)
available_qty = getattr(row, 'available_qty', None)
shortage_qty = getattr(row, 'shortage_qty', None)
entry = {
'line_index': int(getattr(row, 'line_index', 0) or 0),
'line_key': str(getattr(row, 'line_key', '') or ''),
'disposition': match_result or 'not_found',
'part_number': getattr(row, 'part_number', None),
'reservation_id': getattr(row, 'reservation_id', None),
'unit': getattr(row, 'unit', None),
'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None),
'required_qty': float(required_qty) if required_qty is not None else 0.0,
'available_qty': float(available_qty) if available_qty is not None else 0.0,
'shortage_qty': float(shortage_qty) if shortage_qty is not None else 0.0,
}
task.line_results_json.append(entry)
if match_result == 'matched':
has_ok = True
continue
has_block = True
shortages.append(entry)
task.shortage_json = {'lines': shortages}
if has_block and has_ok:
status = 'partial'
elif has_block:
status = 'unfulfillable'
else:
status = 'fulfillable'
return status, shortages
def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]:
"""返回 task.line_results_json(若没初始化则用现查询 facts 重算)供 format_match_summary。"""
cached = list(task.line_results_json or [])
if cached:
return cached
_recompute_task_match_aggregate(task)
return list(task.line_results_json or [])
def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""
将发货通知订单行与库存快照进行 Reservation ID 匹配,并按结果推进任务状态。
@@ -800,6 +1211,28 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
Returns:
dict[str, Any]: Tool 标准响应;status 可为 ok / needs_human / failed。
"""
# [T5 Orchestrator 守卫]:外部直接调用 → 收口到 run_task_auto_progress 并发锁;
# Orchestrator 内部分派调用(_orchestrator_internal_dispatch=True)→ 直接执行下方实现。
if not payload.get('_orchestrator_internal_dispatch', False):
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
from app.services.shipping_notice.query_service import resolve_task_from_payload as _rtp
task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip()
if not task_no and isinstance(payload, dict):
_t = _rtp(payload)
task_no = str(getattr(_t, 'task_no', '') or '').strip()
trigger = str(payload.get('source') or payload.get('trigger') or 'tool_api_match_inventory').strip()
actor_raw = payload.get("operator_id") or payload.get("actor_id") or payload.get("_trusted_user_id")
try:
operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != "system" else None
except (TypeError, ValueError):
operator_id = None
return run_task_auto_progress(
task_no, trigger=trigger,
expected_version=None,
idempotency_key=str(payload.get('idempotency_key') or '').strip() or None,
resume_gate_code='inventory_matching',
operator_id=operator_id,
)
lang = resolve_lang(payload)
actor_id = _event_actor_id(payload)
task = resolve_task_from_payload(payload)
@@ -905,6 +1338,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_line_inventory_match import (
attach_candidate_scope_to_order_lines,
apply_forced_match_source_filter,
apply_line_inventory_resolutions,
match_order_lines_across_candidates,
@@ -948,7 +1382,7 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
'line_key': (order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key'),
})
match_payload = match_order_lines_across_candidates(
order_lines=stp_order_lines,
order_lines=attach_candidate_scope_to_order_lines(task, stp_order_lines),
inventory_lines=inventory_lines or [],
header_reservation_id=header_reservation,
)
@@ -0,0 +1,555 @@
"""
services/shipping_notice/inventory_candidate_freeze_service.py
用途:库存候选冻结的统一写入服务——将路由评估结果写入 Set/Source/Line 三张结构化表
(T2 新建,决策 C1 的正式业务真相),并同步写 ShippingOrderSnapshot.source_manifest_json
作为不可变审计副本。
依赖:app.models.shipping_inventory_candidates(Set/Source/Line)、inventory_source_rules、
inventory_source_repository、ShippingOrderSnapshot(source_manifest_json 快照)。
逻辑:由 adjudicate_and_apply_inventory_source(裁决阶段 ambiguous→candidates_frozen)
与 STP 建单 freeze_stp_inventory_candidates_on_task 两条路径调用;
input_fingerprint 相同则直接返回旧 set_id(幂等),冻结结果不可变。
"""
from __future__ import annotations
import hashlib
import json
from dataclasses import dataclass
from datetime import datetime
from typing import Any
from sqlalchemy import and_, func
from sqlalchemy.orm import Session
from app import db
from app.models import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingNotice,
ShippingOrderSnapshot,
)
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
from app.services.shipping_notice.inventory_source_rules import (
InventorySourceAdjudication,
_task_routing_lines,
compute_routing_fingerprint,
evaluate_inventory_source_rules,
extract_routing_context,
)
@dataclass
class CandidateFreezeResult:
"""候选冻结结果——返回结构化 ID 与是否新建(供调用方打审计日志)。"""
candidate_set_id: int
created_new: bool
source_codes: list[str]
line_count: int
manifest_snapshot_sha256: str
set_version: int
def _build_input_fingerprint(
*,
routing_fingerprint: str,
source_codes_ordered: list[str],
line_signatures: list[tuple[int, str | None, str | None, str | None, list[str]]],
config_version: str,
) -> str:
"""
计算候选冻结输入指纹——相同输入保证复用同一个 Set(幂等键)。
核心要素:路由上下文指纹 + 有序候选源 + 每行(pn, resv, source_codes有序)三元组 + 配置版本。
"""
payload: dict[str, Any] = {
'routing_fingerprint': routing_fingerprint,
'source_codes_ordered': source_codes_ordered,
'line_signatures': [
{
'line_no': sig[0],
'source_line_no': sig[1],
'part_number': sig[2],
'reservation_id': sig[3],
'source_codes_ordered': list(sig[4]),
}
for sig in line_signatures
],
'config_version': config_version,
}
raw = json.dumps(payload, sort_keys=True, ensure_ascii=False, separators=(',', ':'))
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
def _build_manifest_snapshot(
*,
task: ShippingNotice,
set_db: ShippingInventoryCandidateSet,
sources_db: list[ShippingInventoryCandidateSource],
lines_db: list[ShippingInventoryCandidateLine],
routing_rule_version_json: dict[str, Any] | None,
) -> dict[str, Any]:
"""
构建 source_manifest_json['inventory_candidate_freeze'] 不可变副本——
与 Set/Source/Line 三张表同一时刻的完整快照,供审计与事后追溯。
"""
return {
'frozen_at': set_db.frozen_at.isoformat() if set_db.frozen_at else None,
'set_id': set_db.id,
'set_version': set_db.set_version,
'input_fingerprint': set_db.input_fingerprint,
'task_id': set_db.task_id,
'review_case_id': set_db.review_case_id,
'execution_id': set_db.execution_id,
'frozen_by_id': set_db.frozen_by_id,
'routing_rule_version_json': routing_rule_version_json or {},
'routing_rule_version_sha256': hashlib.sha256(
json.dumps(routing_rule_version_json or {}, sort_keys=True, ensure_ascii=False).encode('utf-8')
).hexdigest()
if routing_rule_version_json
else None,
'candidate_sources': [
{
'source_code': s.source_code,
'candidate_order': s.candidate_order,
'candidate_origin': s.candidate_origin,
'routing_rule_id': s.routing_rule_id,
'routing_rule_version': s.routing_rule_version,
'source_config_version': s.source_config_version,
'override_by_id': s.override_by_id,
'override_reason': s.override_reason,
}
for s in sorted(sources_db, key=lambda x: x.candidate_order)
],
'candidate_lines': [
{
'line_no': ln.line_no,
'source_line_no': ln.source_line_no,
'part_number': ln.part_number,
'reservation_id': ln.reservation_id,
'source_codes_ordered': ln.source_codes_json if isinstance(ln.source_codes_json, list) else [],
'override_by_id': ln.override_by_id,
'override_reason': ln.override_reason,
}
for ln in sorted(lines_db, key=lambda x: x.line_no or '')
],
'remark': set_db.remark,
}
def _persist_manifest_snapshot_to_snapshot(
*,
task: ShippingNotice,
manifest: dict[str, Any],
session: Session,
) -> None:
"""
将 inventory_candidate_freeze 副本写入 ShippingOrderSnapshot.source_manifest_json(若该任务已有 Snapshot)。
Snapshot 不存在时不报错——调用方(如建单前草稿阶段)可能尚未完成订单冻结。
"""
snapshot = (
session.query(ShippingOrderSnapshot)
.filter(ShippingOrderSnapshot.task_id == task.id)
.one_or_none()
)
if snapshot is None:
return
manifest_root = dict(snapshot.source_manifest_json or {}) if isinstance(snapshot.source_manifest_json, dict) else {}
manifest_root['inventory_candidate_freeze'] = manifest
snapshot.source_manifest_json = manifest_root
def _collect_order_line_candidates(
task: ShippingNotice,
*,
task_level_source_codes_ordered: list[str],
) -> tuple[list[dict[str, Any]], list[tuple[int, str | None, str | None, str | None, list[str]]]]:
"""
评估每行路由规则,返回行级候选投影 + 行级签名(用于 fingerprint 与 Line 表写入)。
行级无规则命中时回退到任务级 source_codes(保证每行至少一个候选)。
"""
lines = _task_routing_lines(task)
line_projections: list[dict[str, Any]] = []
line_signatures: list[tuple[int, str | None, str | None, str | None, list[str]]] = []
for idx, line in enumerate(lines):
line_no = idx + 1
source_line_no = str(line.get('line_no') or '').strip() or None
part_number = str(line.get('part_number') or '').strip() or None
reservation_id = str(line.get('reservation_id') or '').strip() or None
line_result = evaluate_inventory_source_rules(task=task, line=line)
if line_result.status == 'resolved' and line_result.source_codes:
line_codes = [str(code).upper() for code in line_result.source_codes]
else:
line_codes = list(task_level_source_codes_ordered)
if not line_codes:
line_codes = list(task_level_source_codes_ordered)
line_projections.append({
'line_key': f'{task.id}:{line_no}',
'line_index': idx,
'line_no': line_no,
'source_line_no': source_line_no,
'part_number': part_number,
'reservation_id': reservation_id,
'candidate_inventory_source_codes': line_codes,
'selection_mode': 'line_rule' if (line_result.status == 'resolved' and line_result.source_codes) else 'task_fallback',
'matched_rule_ids': list(getattr(line_result, 'matched_rules', ()) or ()),
'routing_status': line_result.status,
})
line_signatures.append((line_no, source_line_no, part_number, reservation_id, line_codes))
return line_projections, line_signatures
def _find_existing_frozen_set(
*,
task_id: int | None,
review_case_id: int | None,
input_fingerprint: str,
session: Session,
) -> ShippingInventoryCandidateSet | None:
"""
根据幂等键查找已存在的冻结 Set(task 绑定或 review_case 绑定分别查询)。
PostgreSQL 部分唯一索引保证每个绑定维度的 fingerprint 唯一。
"""
if task_id is not None:
return (
session.query(ShippingInventoryCandidateSet)
.filter(
and_(
ShippingInventoryCandidateSet.task_id == task_id,
ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint,
ShippingInventoryCandidateSet.lifecycle_status == 'frozen',
)
)
.order_by(ShippingInventoryCandidateSet.id.desc())
.first()
)
if review_case_id is not None:
return (
session.query(ShippingInventoryCandidateSet)
.filter(
and_(
ShippingInventoryCandidateSet.review_case_id == review_case_id,
ShippingInventoryCandidateSet.input_fingerprint == input_fingerprint,
ShippingInventoryCandidateSet.lifecycle_status == 'frozen',
)
)
.order_by(ShippingInventoryCandidateSet.id.desc())
.first()
)
return None
def _next_task_set_version(*, task_id: int, session: Session) -> int:
"""计算 Task 维度下一个 CandidateSet.version。"""
current_max = (
session.query(func.max(ShippingInventoryCandidateSet.set_version))
.filter(ShippingInventoryCandidateSet.task_id == int(task_id))
.scalar()
)
return int(current_max or 0) + 1
def _invalidate_task_candidate_outputs(task: ShippingNotice, *, session: Session) -> None:
"""重冻结后立即失效旧匹配、导出与待上传事实,避免旧版本继续被消费。"""
from app.models import ShippingNoticeLineInventoryMatch, ShippingTaskInventoryRpaAttempt
task.match_status = None
task.shortage_json = None
task.line_results_json = None
task.export_file_path = None
task.export_file_name = None
task.upload_status = None
payload = dict(task.step_payload_json or {})
payload.pop('line_inventory_resolutions', None)
payload.pop('resolved_ok_source_codes', None)
payload.pop('excel_binding_source_code', None)
payload.pop('multi_source_excel_block', None)
task.step_payload_json = payload
(
session.query(ShippingNoticeLineInventoryMatch)
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
)
.update({'is_current': False, 'updated_at': datetime.utcnow()}, synchronize_session=False)
)
(
session.query(ShippingTaskInventoryRpaAttempt)
.filter(
ShippingTaskInventoryRpaAttempt.task_no == str(task.task_no or ''),
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
)
.update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False)
)
def freeze_candidates_for_task(
task: ShippingNotice,
*,
adjudication: InventorySourceAdjudication | None = None,
review_case_id: int | None = None,
execution_id: int | None = None,
frozen_by_id: int | None = None,
line_projections: list[dict[str, Any]] | None = None,
session: Session | None = None,
) -> CandidateFreezeResult:
"""
将库存候选集合冻结到三张结构化表(正式业务真相)+ Snapshot.source_manifest_json(不可变副本)。
【AI 触发时机】:订单解析完成后 ambiguous→candidates_frozen 转换、STP 建单多候选阶段、
或人工覆盖候选后重新冻结时调用。
核心逻辑:
[STEP 1] 提取路由上下文,计算任务级 source_codes(保序)与行级 source_codes。
[STEP 2] 构建 input_fingerprint,查找是否已有幂等冻结 Set——命中则直接复用。
[STEP 3] 写 Set → Source(保序)→ Line(行级候选有序列表)三张表。
[STEP 4] 同步写 ShippingOrderSnapshot.source_manifest_json['inventory_candidate_freeze']。
[STEP 5] 回填 task.inventory_source_status='candidates_frozen'(调用方负责 commit)。
Args:
task: 已 flush 的 ShippingNotice(有 id 字段)。
adjudication: 裁决结果(含 candidates / config_version / routing_fingerprint);
缺省时调用 adjudicate_inventory_source 重新评估。
review_case_id: 建单前草稿阶段的绑定 ID(task_id 可空时使用)。
execution_id: 可选的 ProcessExecution 绑定 ID。
frozen_by_id: 人工覆盖冻结时的操作人 ID。
line_projections: STP 阶段已算出的行级候选投影(缺省时逐行 evaluate_inventory_source_rules)。
session: 可选的 SQLAlchemy Session(缺省用 db.session)。
Returns:
CandidateFreezeResult: 含 candidate_set_id / 是否新建 / 源列表 / 行数 / manifest_sha256。
Raises:
ValueError: 任务与草稿均未绑定、或候选源集合为空(应走 unresolved/conflicted 人工阻断,调用方不应进入本函数)。
"""
if task.id is None and review_case_id is None:
raise ValueError('freeze_candidates_for_task 必须绑定 task 或 review_case 其一')
session = session or db.session
if adjudication is None:
from app.services.shipping_notice.inventory_source_rules import adjudicate_inventory_source
adjudication = adjudicate_inventory_source(task)
context = extract_routing_context(task)
config_version = adjudication.config_version or inventory_sources_runtime_version()
routing_fingerprint = adjudication.routing_fingerprint or compute_routing_fingerprint(context)
# [STEP 1] 任务级有序 source_codes:从 adjudication.candidates 提取(保序,去重)
task_source_codes_ordered: list[str] = []
seen_codes: set[str] = set()
for candidate in adjudication.candidates or []:
if not isinstance(candidate, dict):
continue
code = str(candidate.get('source_code') or '').strip().upper()
if not code or code in seen_codes:
continue
seen_codes.add(code)
task_source_codes_ordered.append(code)
# [STEP 1b] 行级候选:STP 传入 line_projections 则直接解析签名;否则逐行评估
if line_projections is not None:
signatures: list[tuple[int, str | None, str | None, str | None, list[str]]] = []
for item in line_projections:
if not isinstance(item, dict):
continue
codes_raw = item.get('candidate_inventory_source_codes') or []
codes = [str(c or '').strip().upper() for c in codes_raw if str(c or '').strip()]
if not codes:
codes = list(task_source_codes_ordered)
line_index = item.get('line_index')
try:
line_no = int(item.get('line_no') or 0)
except (TypeError, ValueError):
line_no = 0
if line_no <= 0:
try:
line_no = int(line_index) + 1
except (TypeError, ValueError):
line_no = len(signatures) + 1
signatures.append((
line_no,
str(item.get('source_line_no') or '').strip() or None,
str(item.get('part_number') or '').strip() or None,
str(item.get('reservation_id') or '').strip() or None,
codes,
))
else:
_proj, signatures = _collect_order_line_candidates(
task, task_level_source_codes_ordered=task_source_codes_ordered,
)
if not task_source_codes_ordered:
raise ValueError('冻结服务不接受空候选集合(unresolved/conflicted 应由调用方进入人工阻断)')
# [STEP 2] input_fingerprint + 幂等查找
input_fingerprint = _build_input_fingerprint(
routing_fingerprint=routing_fingerprint,
source_codes_ordered=task_source_codes_ordered,
line_signatures=signatures,
config_version=config_version,
)
existing = _find_existing_frozen_set(
task_id=task.id, review_case_id=review_case_id,
input_fingerprint=input_fingerprint, session=session,
)
if existing is not None:
sources = list(existing.sources or [])
lines = list(existing.lines or [])
manifest_sha = existing.manifest_snapshot_sha256 or ''
return CandidateFreezeResult(
candidate_set_id=existing.id,
created_new=False,
source_codes=[s.source_code for s in sorted(sources, key=lambda x: x.candidate_order)],
line_count=len(lines),
manifest_snapshot_sha256=manifest_sha,
set_version=int(existing.set_version),
)
# [STEP 3] 三张表写入(事务内一起 flush)
routing_rule_version_json = {
'routing_fingerprint': routing_fingerprint,
'config_version': config_version,
'adjudication_method': adjudication.method,
'adjudication_reason': adjudication.reason,
}
existing_active = (
session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
if getattr(task, 'active_inventory_candidate_set_id', None) is not None and getattr(task, 'id', None) is not None
else None
)
set_version = (
_next_task_set_version(task_id=int(task.id), session=session)
if getattr(task, 'id', None) is not None
else 1
)
new_set = ShippingInventoryCandidateSet(
task_id=task.id,
review_case_id=review_case_id,
execution_id=execution_id,
set_version=set_version,
lifecycle_status='frozen',
frozen_at=datetime.utcnow(),
frozen_by_id=frozen_by_id,
input_fingerprint=input_fingerprint,
routing_rule_version_json=routing_rule_version_json,
manifest_snapshot_sha256=None,
remark=None,
)
session.add(new_set)
session.flush()
created_sources: list[ShippingInventoryCandidateSource] = []
for idx, code in enumerate(task_source_codes_ordered):
src_cfg = get_database_inventory_source(code)
rule_id: int | None = None
rule_version: str | None = None
if isinstance(adjudication.evidence, list) and adjudication.evidence:
first_evidence = adjudication.evidence[0]
matched_rule_ids = first_evidence.get('rule_ids')
if isinstance(matched_rule_ids, list) and matched_rule_ids:
try:
_rule_ids_int = int(matched_rule_ids[0])
from app.models.shipping_inventory_config import ShippingInventoryRoutingRule
rule_row = (
session.query(
ShippingInventoryRoutingRule.id,
ShippingInventoryRoutingRule.version,
)
.filter(ShippingInventoryRoutingRule.id == _rule_ids_int)
.one_or_none()
)
if rule_row is not None:
rule_id = rule_row.id
rule_version = str(rule_row.version)
except (TypeError, ValueError):
rule_id = None
rule_version = None
source = ShippingInventoryCandidateSource(
candidate_set_id=new_set.id,
source_code=code,
candidate_order=idx + 1,
candidate_origin='manual_override' if frozen_by_id is not None else 'rule',
routing_rule_id=rule_id,
routing_rule_version=rule_version or config_version,
source_config_version=(
str(src_cfg.get('config_version')).strip() if isinstance(src_cfg, dict) and src_cfg.get('config_version') else None
),
override_by_id=frozen_by_id,
override_reason=None,
)
session.add(source)
created_sources.append(source)
session.flush(created_sources)
created_lines: list[ShippingInventoryCandidateLine] = []
for sig in signatures:
line_no, source_line_no, pn, resv, codes_ordered = sig
line_entity = ShippingInventoryCandidateLine(
candidate_set_id=new_set.id,
line_no=line_no,
source_line_no=source_line_no,
part_number=pn,
reservation_id=resv,
source_codes_json=list(codes_ordered),
override_by_id=frozen_by_id,
override_reason=None,
)
session.add(line_entity)
created_lines.append(line_entity)
session.flush(created_lines)
# [STEP 4] 写不可变 manifest 副本
manifest = _build_manifest_snapshot(
task=task, set_db=new_set,
sources_db=created_sources, lines_db=created_lines,
routing_rule_version_json=routing_rule_version_json,
)
manifest_sha256 = hashlib.sha256(
json.dumps(manifest, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8')
).hexdigest()
new_set.manifest_snapshot_sha256 = manifest_sha256
_persist_manifest_snapshot_to_snapshot(task=task, manifest=manifest, session=session)
if existing_active is not None and int(existing_active.id) != int(new_set.id):
existing_active.lifecycle_status = 'superseded'
existing_active.superseded_at = datetime.utcnow()
existing_active.superseded_by_set_id = int(new_set.id)
_invalidate_task_candidate_outputs(task, session=session)
if getattr(task, 'id', None) is not None:
task.active_inventory_candidate_set_id = int(new_set.id)
# 新版本不能让旧候选链中的 queued Job/未完成 Gate 继续写事实。
from app.services.shipping_notice.auto_progress_controller import (
supersede_auto_progress_for_candidate_refreeze,
)
supersede_auto_progress_for_candidate_refreeze(task)
# [STEP 5] 回填 task 字段(幂等覆盖)
task.inventory_source_status = 'candidates_frozen'
task.inventory_source_method = (
'manual_override_freeze' if frozen_by_id is not None
else (adjudication.method or 'rule_evaluation_freeze')
)
task.inventory_source_config_version = config_version
task.inventory_routing_fingerprint = routing_fingerprint
# 保留 step_payload_json 中已有 inventory_source_resolution,调用方可追加细节
return CandidateFreezeResult(
candidate_set_id=new_set.id,
created_new=True,
source_codes=list(task_source_codes_ordered),
line_count=len(created_lines),
manifest_snapshot_sha256=manifest_sha256,
set_version=set_version,
)
@@ -0,0 +1,571 @@
"""
services/shipping_notice/inventory_candidate_projection.py
用途:统一读取正式 CandidateSet 真相,并投影为任务/工作台/聊天共用的候选事实 DTO。
依赖:ShippingNotice、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、
ShippingTaskInventoryRpaAttempt。
逻辑:正式 Task 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、
坏链、旧版本匹配引用或越界匹配统一产出 fail-closed 诊断,供 Gate / Projection / API 复用。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from sqlalchemy.orm import Session
from app import db
from app.models import (
ShippingInventoryCandidateLine,
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
)
INVENTORY_CANDIDATE_LIFECYCLE_FROZEN = 'frozen'
INVENTORY_CANDIDATE_LIFECYCLE_DRAFT = 'draft'
INVENTORY_CANDIDATE_REASON_MISSING = 'inventory_candidates_missing'
INVENTORY_CANDIDATE_REASON_STALE = 'inventory_candidate_version_stale'
INVENTORY_CANDIDATE_REASON_OUT_OF_SCOPE = 'inventory_match_out_of_candidate_scope'
def _session(session: Session | None = None) -> Session:
"""统一 Session 入口,便于调用方透传事务。"""
return session or db.session
def _iso(value: datetime | None) -> str | None:
"""将时间序列化为 ISO 字符串。"""
return value.isoformat() if value is not None else None
def _normalized_codes(codes: list[Any] | None) -> list[str]:
"""规范候选源编码数组并保持顺序去重。"""
out: list[str] = []
for raw in codes or []:
code = str(raw or '').strip().upper()
if code and code not in out:
out.append(code)
return out
def _candidate_set_filter(
task: ShippingNotice,
*,
include_drafts: bool = False,
session: Session | None = None,
) -> list[ShippingInventoryCandidateSet]:
"""按 Task 读取候选版本列表;默认隐藏 draft。"""
if getattr(task, 'id', None) is None:
return []
query = (
_session(session)
.query(ShippingInventoryCandidateSet)
.filter(ShippingInventoryCandidateSet.task_id == int(task.id))
)
if not include_drafts:
query = query.filter(
ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT,
)
rows = (
query.order_by(
ShippingInventoryCandidateSet.set_version.desc(),
ShippingInventoryCandidateSet.id.desc(),
)
.all()
)
return list(rows)
def get_active_candidate_set(
task: ShippingNotice,
*,
session: Session | None = None,
) -> ShippingInventoryCandidateSet | None:
"""
读取正式 Task 当前 frozen CandidateSet。
核心逻辑:严格依赖 ShippingNotice.active_inventory_candidate_set_id;
指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。
"""
candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None)
if candidate_set_id is None:
return None
row = _session(session).get(ShippingInventoryCandidateSet, int(candidate_set_id))
if row is None:
return None
if int(getattr(row, 'task_id', 0) or 0) != int(getattr(task, 'id', 0) or 0):
return None
if str(getattr(row, 'lifecycle_status', '') or '').strip().lower() != INVENTORY_CANDIDATE_LIFECYCLE_FROZEN:
return None
return row
def get_active_candidate_sources(
task: ShippingNotice,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateSource]:
"""读取当前 frozen Set 的任务级候选源。"""
current = get_active_candidate_set(task, session=session)
if current is None:
return []
rows = (
_session(session)
.query(ShippingInventoryCandidateSource)
.filter(ShippingInventoryCandidateSource.candidate_set_id == int(current.id))
.order_by(
ShippingInventoryCandidateSource.candidate_order.asc(),
ShippingInventoryCandidateSource.id.asc(),
)
.all()
)
return list(rows)
def get_active_candidate_lines(
task: ShippingNotice,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateLine]:
"""读取当前 frozen Set 的行级候选。"""
current = get_active_candidate_set(task, session=session)
if current is None:
return []
rows = (
_session(session)
.query(ShippingInventoryCandidateLine)
.filter(ShippingInventoryCandidateLine.candidate_set_id == int(current.id))
.order_by(
ShippingInventoryCandidateLine.line_no.asc(),
ShippingInventoryCandidateLine.id.asc(),
)
.all()
)
return list(rows)
def get_candidate_set_by_version(
task: ShippingNotice,
version: int,
*,
include_drafts: bool = False,
session: Session | None = None,
) -> ShippingInventoryCandidateSet | None:
"""按 Task + set_version 读取指定候选版本。"""
if getattr(task, 'id', None) is None:
return None
query = (
_session(session)
.query(ShippingInventoryCandidateSet)
.filter(
ShippingInventoryCandidateSet.task_id == int(task.id),
ShippingInventoryCandidateSet.set_version == int(version),
)
)
if not include_drafts:
query = query.filter(
ShippingInventoryCandidateSet.lifecycle_status != INVENTORY_CANDIDATE_LIFECYCLE_DRAFT,
)
return query.order_by(ShippingInventoryCandidateSet.id.desc()).first()
def serialize_candidate_set_summary(row: ShippingInventoryCandidateSet | None) -> dict[str, Any] | None:
"""序列化 CandidateSet 摘要供 API / Projection 复用。"""
if row is None:
return None
return {
'id': int(row.id),
'version': int(row.set_version),
'status': str(row.lifecycle_status or ''),
'input_fingerprint': str(row.input_fingerprint or ''),
'frozen_at': _iso(getattr(row, 'frozen_at', None)),
'frozen_by': getattr(row, 'frozen_by_id', None),
'manifest_snapshot_sha256': getattr(row, 'manifest_snapshot_sha256', None),
'superseded_at': _iso(getattr(row, 'superseded_at', None)),
'superseded_by_set_id': getattr(row, 'superseded_by_set_id', None),
'invalidated_at': _iso(getattr(row, 'invalidated_at', None)),
'invalidated_reason': getattr(row, 'invalidated_reason', None),
'routing_rule_version_json': dict(getattr(row, 'routing_rule_version_json', None) or {}),
}
def serialize_candidate_source(row: ShippingInventoryCandidateSource) -> dict[str, Any]:
"""序列化任务级候选源。"""
return {
'id': int(row.id),
'candidate_set_id': int(row.candidate_set_id),
'source_code': str(row.source_code or '').strip().upper(),
'candidate_order': int(row.candidate_order),
'candidate_origin': str(row.candidate_origin or ''),
'routing_rule_id': getattr(row, 'routing_rule_id', None),
'routing_rule_version': getattr(row, 'routing_rule_version', None),
'source_config_version': getattr(row, 'source_config_version', None),
'override_by_id': getattr(row, 'override_by_id', None),
'override_reason': getattr(row, 'override_reason', None),
}
def serialize_candidate_line(row: ShippingInventoryCandidateLine) -> dict[str, Any]:
"""序列化行级候选源与稳定行标识。"""
return {
'candidate_line_id': int(row.id),
'candidate_set_id': int(row.candidate_set_id),
'line_no': int(row.line_no),
'source_line_no': getattr(row, 'source_line_no', None),
'part_number': getattr(row, 'part_number', None),
'reservation_id': getattr(row, 'reservation_id', None),
'allowed_source_codes': _normalized_codes(getattr(row, 'source_codes_json', None)),
'override_by_id': getattr(row, 'override_by_id', None),
'override_reason': getattr(row, 'override_reason', None),
}
def _candidate_sources_for_set(
candidate_set: ShippingInventoryCandidateSet | None,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateSource]:
"""读取指定 CandidateSet 的任务级候选源。"""
if candidate_set is None:
return []
rows = (
_session(session)
.query(ShippingInventoryCandidateSource)
.filter(ShippingInventoryCandidateSource.candidate_set_id == int(candidate_set.id))
.order_by(
ShippingInventoryCandidateSource.candidate_order.asc(),
ShippingInventoryCandidateSource.id.asc(),
)
.all()
)
return list(rows)
def _candidate_lines_for_set(
candidate_set: ShippingInventoryCandidateSet | None,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateLine]:
"""读取指定 CandidateSet 的行级候选。"""
if candidate_set is None:
return []
rows = (
_session(session)
.query(ShippingInventoryCandidateLine)
.filter(ShippingInventoryCandidateLine.candidate_set_id == int(candidate_set.id))
.order_by(
ShippingInventoryCandidateLine.line_no.asc(),
ShippingInventoryCandidateLine.id.asc(),
)
.all()
)
return list(rows)
def build_inventory_candidate_blocking_reason(
code: str,
*,
task: ShippingNotice,
details: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""构造统一 blocking_reason DTO。"""
payload = {'task_no': str(task.task_no or '').strip()}
payload.update(details or {})
return {
'code': code,
'i18n_key': f'workspace.shippingNotice.processGate.reasons.{code}',
'details': payload,
}
def build_inventory_candidate_primary_action(code: str = 'open_inventory_source_review') -> dict[str, Any]:
"""构造统一主动作 DTO。"""
return {
'code': code,
'i18n_key': f'workspace.shippingNotice.processGate.actionCodes.{code}',
'parameters': {},
}
def _latest_attempts_by_source(task: ShippingNotice, source_codes: list[str], *, session: Session | None = None) -> dict[str, dict[str, Any]]:
"""查询任务下每个候选源的最新 Attempt 摘要。"""
task_no = str(getattr(task, 'task_no', '') or '').strip()
if not task_no or not source_codes:
return {}
rows = (
_session(session)
.query(ShippingTaskInventoryRpaAttempt)
.filter(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.source_code.in_(source_codes),
)
.order_by(
ShippingTaskInventoryRpaAttempt.source_code.asc(),
ShippingTaskInventoryRpaAttempt.attempt_no.desc(),
ShippingTaskInventoryRpaAttempt.id.desc(),
)
.all()
)
out: dict[str, dict[str, Any]] = {}
for row in rows:
code = str(row.source_code or '').strip().upper()
if not code or code in out:
continue
out[code] = {
'source_code': code,
'attempt_no': int(row.attempt_no),
'status': str(row.status or ''),
'run_no': str(row.run_no or ''),
'error_code': getattr(row, 'error_code', None),
'error_message': getattr(row, 'error_message', None),
'inventory_file_no': getattr(row, 'inventory_file_no', None),
'updated_at': _iso(getattr(row, 'updated_at', None)),
}
return out
def _classify_sources(source_codes: list[str], attempt_map: dict[str, dict[str, Any]]) -> tuple[list[str], list[str], list[str]]:
"""按最新 Attempt 状态聚合 prepared / pending / failed 源列表。"""
prepared: list[str] = []
pending: list[str] = []
failed: list[str] = []
for code in source_codes:
status = str((attempt_map.get(code) or {}).get('status') or '').strip().lower()
if status in {'succeeded', 'consumed'}:
prepared.append(code)
elif status in {'queued', 'running'}:
pending.append(code)
elif status in {'failed', 'exhausted', 'superseded'}:
failed.append(code)
return prepared, pending, failed
def _current_match_rows(task: ShippingNotice, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]:
"""读取任务当前生效的行级匹配事实。"""
if getattr(task, 'id', None) is None:
return []
rows = (
_session(session)
.query(ShippingNoticeLineInventoryMatch)
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
)
.order_by(
ShippingNoticeLineInventoryMatch.line_index.asc(),
ShippingNoticeLineInventoryMatch.id.asc(),
)
.all()
)
return list(rows)
def project_inventory_candidate_detail(
task: ShippingNotice,
*,
version: str | int = 'current',
session: Session | None = None,
include_history: bool = False,
include_drafts: bool = False,
) -> dict[str, Any]:
"""
投影候选详情 API 所需的当前版或指定版详情。
核心逻辑:默认返回当前 active frozen Set;指定 version 时返回该版本的源/行详情,
同时 history 仅返回摘要,默认排除 draft。
"""
sess = _session(session)
current = get_active_candidate_set(task, session=sess)
selected = current
if version != 'current':
try:
selected = get_candidate_set_by_version(
task,
int(version),
include_drafts=include_drafts,
session=sess,
)
except (TypeError, ValueError):
selected = None
history: list[dict[str, Any]] = []
if include_history:
history = [
serialize_candidate_set_summary(row)
for row in _candidate_set_filter(task, include_drafts=include_drafts, session=sess)
if row is not None
]
if selected is None:
return {
'current_set': None,
'sources': [],
'lines': [],
'history': history,
'blocking_reason': build_inventory_candidate_blocking_reason(
INVENTORY_CANDIDATE_REASON_MISSING,
task=task,
),
'primary_action': build_inventory_candidate_primary_action(),
}
return {
'current_set': serialize_candidate_set_summary(selected),
'sources': [serialize_candidate_source(row) for row in _candidate_sources_for_set(selected, session=sess)],
'lines': [serialize_candidate_line(row) for row in _candidate_lines_for_set(selected, session=sess)],
'history': history,
'blocking_reason': None,
'primary_action': None,
}
def project_inventory_candidate_facts(
task: ShippingNotice,
*,
session: Session | None = None,
include_history: bool = False,
) -> dict[str, Any]:
"""
统一投影任务当前候选事实。
核心逻辑:
[STEP 1] 严格读取 active frozen CandidateSet;
[STEP 2] 聚合 Source / Line / Attempt / Match 事实;
[STEP 3] 检测 missing / stale / out_of_scope 并输出统一阻断信息。
"""
sess = _session(session)
current = get_active_candidate_set(task, session=sess)
if current is None:
return {
'current_set': None,
'sources': [],
'lines': [],
'history': [],
'candidate_set_id': None,
'candidate_set_version': None,
'candidate_set_status': None,
'candidate_source_codes': [],
'prepared_source_codes': [],
'pending_source_codes': [],
'failed_source_codes': [],
'source_attempts': {},
'line_resolutions': [],
'blocking_reason': build_inventory_candidate_blocking_reason(
INVENTORY_CANDIDATE_REASON_MISSING, task=task,
),
'primary_action': build_inventory_candidate_primary_action(),
}
sources = get_active_candidate_sources(task, session=sess)
lines = get_active_candidate_lines(task, session=sess)
source_codes = [str(row.source_code or '').strip().upper() for row in sources if str(row.source_code or '').strip()]
attempt_map = _latest_attempts_by_source(task, source_codes, session=sess)
prepared_codes, pending_codes, failed_codes = _classify_sources(source_codes, attempt_map)
line_by_id = {int(row.id): row for row in lines}
serialized_matches: list[dict[str, Any]] = []
stale_details: dict[str, Any] | None = None
out_of_scope_details: dict[str, Any] | None = None
for row in _current_match_rows(task, session=sess):
allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None))
serialized = {
'id': int(row.id),
'line_key': str(row.line_key or ''),
'line_index': getattr(row, 'line_index', None),
'disposition': dict(getattr(row, 'detail_json', None) or {}).get('disposition'),
'candidate_set_id': getattr(row, 'candidate_set_id', None),
'candidate_set_version': getattr(row, 'candidate_set_version', None),
'candidate_line_id': getattr(row, 'candidate_line_id', None),
'allowed_source_codes_snapshot': allowed_codes,
'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None),
'inventory_file_no': getattr(row, 'matched_file_no', None),
'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None),
'inventory_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')),
'required_qty': getattr(row, 'required_qty', None),
'matched_qty': getattr(row, 'matched_qty', None) or getattr(row, 'available_qty', None),
'match_result': getattr(row, 'match_result', None),
'evidence_checksum': getattr(row, 'evidence_checksum', None),
}
serialized_matches.append(serialized)
if int(getattr(row, 'candidate_set_id', 0) or 0) != int(current.id):
stale_details = {
'expected_candidate_set_id': int(current.id),
'expected_candidate_set_version': int(current.set_version),
'actual_candidate_set_id': getattr(row, 'candidate_set_id', None),
'actual_candidate_set_version': getattr(row, 'candidate_set_version', None),
'detected_at': datetime.utcnow().isoformat(),
'operation_id': f'match-row:{int(row.id)}',
}
candidate_line_id = getattr(row, 'candidate_line_id', None)
if candidate_line_id is not None:
line_row = line_by_id.get(int(candidate_line_id))
if line_row is None:
stale_details = {
'expected_candidate_set_id': int(current.id),
'expected_candidate_set_version': int(current.set_version),
'actual_candidate_set_id': getattr(row, 'candidate_set_id', None),
'actual_candidate_set_version': getattr(row, 'candidate_set_version', None),
'detected_at': datetime.utcnow().isoformat(),
'operation_id': f'match-line:{int(row.id)}',
}
elif (
str(getattr(row, 'inventory_source_code', '') or '').strip().upper()
and allowed_codes
and str(getattr(row, 'inventory_source_code', '') or '').strip().upper() not in allowed_codes
):
out_of_scope_details = {
'candidate_line_id': int(candidate_line_id),
'expected_candidate_set_id': int(current.id),
'expected_candidate_set_version': int(current.set_version),
'actual_candidate_set_id': getattr(row, 'candidate_set_id', None),
'actual_candidate_set_version': getattr(row, 'candidate_set_version', None),
'detected_at': datetime.utcnow().isoformat(),
'operation_id': f'match-line:{int(row.id)}',
'resolved_inventory_source_code': getattr(row, 'inventory_source_code', None),
'allowed_source_codes_snapshot': allowed_codes,
}
history: list[dict[str, Any]] = []
if include_history:
history = [
serialize_candidate_set_summary(row)
for row in _candidate_set_filter(task, include_drafts=False, session=sess)
if row is not None
]
result: dict[str, Any] = {
'current_set': serialize_candidate_set_summary(current),
'sources': [serialize_candidate_source(row) for row in sources],
'lines': [serialize_candidate_line(row) for row in lines],
'history': history,
'candidate_set_id': int(current.id),
'candidate_set_version': int(current.set_version),
'candidate_set_status': str(current.lifecycle_status or ''),
'candidate_source_codes': source_codes,
'prepared_source_codes': prepared_codes,
'pending_source_codes': pending_codes,
'failed_source_codes': failed_codes,
'source_attempts': attempt_map,
'line_resolutions': serialized_matches,
}
if out_of_scope_details is not None:
result['blocking_reason'] = build_inventory_candidate_blocking_reason(
INVENTORY_CANDIDATE_REASON_OUT_OF_SCOPE,
task=task,
details=out_of_scope_details,
)
result['primary_action'] = build_inventory_candidate_primary_action()
elif stale_details is not None:
result['blocking_reason'] = build_inventory_candidate_blocking_reason(
INVENTORY_CANDIDATE_REASON_STALE,
task=task,
details=stale_details,
)
result['primary_action'] = build_inventory_candidate_primary_action()
return result
@@ -1017,13 +1017,49 @@ def confirm_inventory_source(payload: dict[str, Any]) -> dict[str, Any]:
db.session.flush()
from app.services.shipping_notice.fulfillment_workflow import match_inventory
trusted_uid = payload.get("_trusted_user_id")
return match_inventory({
# [T6 选择性重匹] 默认只重匹 match_result≠matched 行;force_full_rematch=true 才全量重匹。
# 实现:非全量模式先把 line_matches 中 is_current=true 且 match_result≠matched 的条目
# 置为 is_current=false,待 match_inventory 补齐;已 matched 的保留不覆盖,避免稳定证据哈希失效。
force_full = False
if isinstance(payload, dict):
force_flag = payload.get('force_full_rematch') or payload.get('force_full') or payload.get('full_rematch')
force_full = bool(force_flag and str(force_flag).lower() not in {'0', 'false', 'no', 'none', ''})
if not force_full and task.id is not None:
from app.models.shipping_notice_line_inventory_match import ShippingNoticeLineInventoryMatch
cleared = (
db.session.query(ShippingNoticeLineInventoryMatch)
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result != 'matched',
)
.update(
{
'is_current': False,
'updated_at': datetime.now(timezone.utc),
},
synchronize_session=False,
)
)
log_task_event(
task,
'match_inventory_selective_reset',
{
'cleared_pending_count': int(cleared or 0),
'force_full_rematch': False,
},
actor_id=trusted_uid,
source='workspace_api' if trusted_uid else 'system',
)
rematch_payload = {
"task_id": task.task_no,
"_trusted_user_id": trusted_uid,
"operator_id": trusted_uid,
"actor_id": trusted_uid,
"event_source": "workspace_api" if trusted_uid else "system",
})
"force_full_rematch": force_full,
}
return match_inventory(rematch_payload)
adjudication = confirm_task_inventory_source(
task,
@@ -1526,6 +1562,7 @@ def _handle_rpa_inventory_failed(
def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
cleanup_retry_warnings = flush_callback_cleanup_queue()
@@ -1533,6 +1570,82 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message="未找到任务编号")
# [T7 统一回调幂等] 尝试按 per-source run_no 提取 source_code;如符合 PSR-*-<SOURCE>-A<N>-* 格式则先入 per_source_callback_handler
run_no_raw = str(payload.get("run_no") or "").strip()
source_code_from_run: str | None = None
if run_no_raw and run_no_raw.startswith('PSR-'):
# PSR-<task>-<SOURCE>-A<N>-<uuid8> → 第 3 段 = SOURCE
parts = run_no_raw.split('-')
if len(parts) >= 4 and parts[3].startswith('A'):
candidate = str(parts[2] or '').strip().upper()
if candidate:
source_code_from_run = candidate
per_source_result = None
if source_code_from_run and run_no_raw:
per_source_code, _attempt = per_source_callback_handler(
task,
source_code=source_code_from_run,
run_no=run_no_raw,
callback_payload=dict(payload),
)
per_source_result = per_source_code
if per_source_code == 'idempotent_ok':
return tool_response(
status="success",
task=task,
message="RPA 回调已处理(幂等),无需重复写入。",
data={
"run_no": run_no_raw,
"source_code": source_code_from_run,
"retry_safe": True,
"idempotent": True,
},
)
if per_source_code == 'superseded_late':
log_task_event(
task,
'late_rpa_callback_ignored',
{
'run_no': run_no_raw,
'source_code': source_code_from_run,
'reason': 'superseded_by_newer_run',
},
source='rpa_callback',
)
return tool_response(
status="success",
task=task,
message="RPA 回调已过期(同源更新的 run 已处理),本回调忽略。",
data={
"run_no": run_no_raw,
"source_code": source_code_from_run,
"late": True,
"retry_safe": True,
},
)
if per_source_code == 'task_terminal':
return tool_response(
status="success",
task=task,
message="任务已处于终态(完成/作废/失败终止),回调忽略。",
data={
"run_no": run_no_raw,
"source_code": source_code_from_run,
"task_terminal": True,
"retry_safe": True,
},
)
if per_source_code == 'failed':
return tool_response(
status="failed",
task=task,
message=f"RPA 回调在源 {source_code_from_run} 侧已标记失败,见回调 payload。",
data={
"run_no": run_no_raw,
"source_code": source_code_from_run,
},
)
task = _lock_task_for_rpa_callback(task)
gate_resp = _validate_rpa_callback_gate(task)
@@ -1811,7 +1924,17 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
cleanup_retry_warnings = flush_callback_cleanup_queue()
run_no = str(payload.get("run_no") or "").strip()
if payload.get('schema_version') != 'shipping_inventory_rpa.v2':
return tool_response(status='failed', message='callback_schema_invalid', data={
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
})
callback_id = str(payload.get('callback_id') or '').strip()
batch_run_no = str(payload.get('batch_run_no') or '').strip()
if not callback_id or not batch_run_no:
return tool_response(status='failed', message='callback_schema_invalid', data={
'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid',
})
run_no = batch_run_no
schedule_run_id = payload.get("schedule_run_id")
try:
schedule_run_id = int(schedule_run_id) if schedule_run_id is not None else None
@@ -1845,6 +1968,17 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
warehouse_id = str(merged_item.get("warehouse_id") or "").strip().upper()
raw_status = _normalize_rpa_inventory_batch_item_status(merged_item)
task_no = str(merged_item.get("task_no") or "").strip()
run_no_item = str(merged_item.get("run_no") or "").strip() or run_no
source_run_no_item = str(merged_item.get("source_run_no") or "").strip()
item_callback_id = str(merged_item.get("callback_id") or "").strip()
if not item_callback_id and source_run_no_item:
item_callback_id = f"{callback_id}:{source_run_no_item}:C1"
if item_callback_id:
from app.models import ShippingTaskInventoryRpaAttempt
replay_attempt = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(callback_id=item_callback_id).one_or_none()
if replay_attempt is not None:
skipped.append({"source_code": source_code, "task_no": task_no or None, "source_run_no": source_run_no_item, "callback_id": item_callback_id, "reason": "replayed", "original_business_status": replay_attempt.transaction_status or replay_attempt.status, "replayed": True})
continue
task: ShippingNotice | None = None
if task_no:
task = resolve_task_from_payload({"task_id": task_no, "task_no": task_no})
@@ -1856,6 +1990,56 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
"error": "task_not_found",
})
continue
# [T7 批量回调幂等] 每个 item 先走 per_source_callback_handler;batch 中单独处理不中断整体
if source_code and source_run_no_item and raw_status != 'success':
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
per_source_code, _a = per_source_callback_handler(
task,
source_code=source_code,
run_no=source_run_no_item,
callback_payload=dict(merged_item),
)
if per_source_code == 'idempotent_ok':
skipped.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"task_no": task_no,
"run_no": run_no_item,
"reason": "idempotent_ok",
"retry_safe": True,
})
continue
if per_source_code == 'superseded_late':
log_task_event(
task,
'late_rpa_callback_ignored',
{
'run_no': run_no_item,
'source_code': source_code,
'reason': 'superseded_by_newer_run',
'batch': True,
},
source='rpa_callback',
)
skipped.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"task_no": task_no,
"run_no": run_no_item,
"reason": "superseded_late",
"retry_safe": True,
})
continue
if per_source_code == 'task_terminal':
skipped.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"task_no": task_no,
"run_no": run_no_item,
"reason": "task_terminal",
"retry_safe": True,
})
continue
task = _lock_task_for_rpa_callback(task)
if task and raw_status in {"skipped", "failed"}:
@@ -1937,14 +2121,30 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
if raw_status == "success":
file_path = str(merged_item.get("file_path") or "").strip()
path = Path(file_path) if file_path else None
path = Path(file_path).resolve() if file_path else None
from app.services.shipping_notice.rpa import inventory_drop_dir
allowed_root = inventory_drop_dir()
if path and allowed_root:
try:
path.relative_to(allowed_root.resolve())
except ValueError:
path = None
if not path or not path.is_file():
failed.append({
"source_code": source_code,
"warehouse_id": warehouse_id,
"error": "file_missing",
})
if task_no and source_run_no_item:
from app.models import ShippingTaskInventoryRpaAttempt
_att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none()
if _att:
_att.callback_id = item_callback_id or callback_id
_att.callback_received_at = datetime.utcnow(); _att.file_generated = False; _att.file_exists_at_callback = False
_att.execution_phase = 'callback_rejected'; _att.transaction_status = 'rejected'; _att.error_code = 'file_missing'
continue
server_hash = hashlib.sha256(path.read_bytes()).hexdigest()
server_size = path.stat().st_size
if task:
gate_resp = _validate_rpa_callback_inventory_source(task, merged_item)
@@ -1993,7 +2193,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
source=source,
local_path=path,
source_file_name=path.name,
rpa_run_no=run_no or None,
rpa_run_no=str(merged_item.get('source_run_no') or run_no) or None,
schedule_run_id=schedule_run_id,
trigger_type=str(payload.get("trigger_type") or "scheduled"),
success=True,
@@ -2025,11 +2225,19 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
"source_code": inv_file.source_code or source_code,
"warehouse_id": inv_file.warehouse_id or warehouse_id,
"reused_existing_snapshot": not created_new,
"callback_id": callback_id,
"file_sha256": server_hash,
"file_size": server_size,
"structure_validation": {
"level": structure_check["level"],
"difference": structure_check["difference"],
},
}
if task_no and source_run_no_item:
from app.models import ShippingTaskInventoryRpaAttempt
_att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none()
if _att:
_att.callback_id = item_callback_id or callback_id; _att.callback_received_at = datetime.utcnow(); _att.file_generated = True; _att.file_path = str(path); _att.file_sha256 = server_hash; _att.file_size = server_size; _att.file_exists_at_callback = True; _att.execution_phase = 'callback_received'; _att.transaction_status = 'succeeded'
created.append(created_entry)
if item_orphan_path:
batch_new_storage_paths.append(item_orphan_path)
@@ -22,6 +22,9 @@ from app.services.shipping_notice.inventory_source_rules import (
extract_routing_context,
resolve_ambiguous_source_from_ready_snapshots,
)
from app.services.shipping_notice.inventory_candidate_freeze_service import (
freeze_candidates_for_task,
)
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
@@ -247,6 +250,51 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour
evidence=adjudication.evidence,
reason=adjudication.reason,
)
# [T3: 决策 A1 + C1] ambiguous 且有候选时,不再进入 inventory_source_review 人工阻断;
# 多库存源是合法自动链路,直接冻结到 Set/Source/Line 结构化表 + Snapshot JSON 副本,
# 状态升级为 candidates_frozen(属于 STABLE_INVENTORY_SOURCE_STATUSES,可进入库存准备)。
# 零候选 / conflicted / unresolved 等情况仍保持旧逻辑进入人工复核。
if (
adjudication.status == "ambiguous"
and getattr(task, "id", None) is not None
and any(
isinstance(c, dict) and str(c.get("source_code") or "").strip()
for c in (adjudication.candidates or [])
)
):
try:
freeze_result = freeze_candidates_for_task(task, adjudication=adjudication)
# 冻结成功后升级裁决为 candidates_frozen;apply_inventory_source_adjudication 会再写一次字段,
# 但冻结服务已写好 task.status=method=config=fingerprint,结果一致。
evidence_merged = list(adjudication.evidence or [])
evidence_merged.append({
"candidate_freeze": {
"set_id": freeze_result.candidate_set_id,
"manifest_snapshot_sha256": freeze_result.manifest_snapshot_sha256,
"source_codes_ordered": freeze_result.source_codes,
"line_count": freeze_result.line_count,
"created_new": freeze_result.created_new,
}
})
adjudication = InventorySourceAdjudication(
status="candidates_frozen",
method=adjudication.method or "rule_evaluation_freeze",
source_code=None,
connector_type=None,
warehouse_id=None,
config_version=adjudication.config_version or inventory_sources_runtime_version(),
routing_fingerprint=adjudication.routing_fingerprint or compute_routing_fingerprint(context),
candidates=adjudication.candidates,
destination_candidates=adjudication.destination_candidates,
evidence=evidence_merged,
reason=f"ambiguous_frozen:{freeze_result.candidate_set_id}",
)
except ValueError:
# 冻结服务抛 ValueError = 候选集合为空(保护分支,正常应命中不进入),
# 保留原 ambiguous 让下游 is_inventory_source_stable 正确进入人工阻断。
pass
apply_inventory_source_adjudication(task, adjudication)
return adjudication
@@ -238,6 +238,28 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# [T5 Orchestrator 守卫]:外部直接调用 → 收口到 run_task_auto_progress 并发锁;
# Orchestrator 内部分派调用(_orchestrator_internal_dispatch=True)→ 直接执行下方实现。
if not payload.get('_orchestrator_internal_dispatch', False):
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip()
if not task_no and isinstance(payload, dict):
t = resolve_task_from_payload(payload)
task_no = str(getattr(t, 'task_no', '') or '').strip()
trigger = str(payload.get('source') or payload.get('trigger') or 'tool_api_ensure_inventory').strip()
actor_raw = payload.get("operator_id") or payload.get("actor_id") or payload.get("_trusted_user_id")
try:
operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != "system" else None
except (TypeError, ValueError):
operator_id = None
return run_task_auto_progress(
task_no, trigger=trigger,
expected_version=None,
idempotency_key=str(payload.get('idempotency_key') or '').strip() or None,
resume_gate_code='inventory_preparation',
operator_id=operator_id,
inventory_mode=str(payload.get('mode') or 'auto').strip().lower() or 'auto',
)
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
if not task:
@@ -277,6 +299,33 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
frozen_codes = task_frozen_inventory_source_codes(task)
if len(frozen_codes) > 1 or str(task.inventory_source_status or '').strip() == 'candidates_frozen':
prep = prepare_candidate_inventory_lines(task)
if prep.get('status') == 'blocked' and prep.get('error_code') == 'inventory_candidates_missing':
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="needs_human",
message=t("workflow.inventory.unavailable", lang=lang),
progress_percent=0,
detail=t("workflow.inventory.unavailable", lang=lang),
)
log_task_event(task, "inventory_candidate_version_stale", {
'error_code': prep.get('error_code'),
})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=t("workflow.inventory.unavailable", lang=lang),
data={
**serialize_task_for_tool(task),
'blocking_reason': {
'code': prep.get('error_code'),
'primary_action': 'open_inventory_source_review',
},
},
)
if prep.get('status') == 'missing_files':
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
@@ -0,0 +1,297 @@
"""
backend/app/services/shipping_notice/legacy_stp_job_admin_service.py
用途:Phase 5-1 —— 管理员历史 STP Job 面板的只读投影服务(928/929 运维面板专用)。
依赖:models.job.Job、JobType(若有)、ShippingOrderReviewCase。
逻辑:
1. list_admin_legacy_stp_jobs —— 按 domain=shipping_notice + job_type=shipping_stp_auto_create
+ status IN {failed,dead} 分页返回;支持筛选 case_no / q / error_code / created_from / created_to。
2. get_admin_legacy_stp_job —— 单条 Job 详情 + 关联 Review Case(若可通过 reference_key==case_no 回链)。
禁止事项(严格 fail-closed):
• 不允许写任何数据(禁 Job.status 修改,禁 db.session.commit/add/flush 等)。
• 不输出敏感字段(result_json 中若含 token/password 自动脱敏)。
• 所有接口仅 allow_admin,路由层 require_admin 再守门一道。
"""
from __future__ import annotations
import re
from datetime import datetime
from typing import Any
from sqlalchemy import and_, or_
from app import db
# 失败 / 死 Job 白名单:历史 928/929 仅针对 shipping_stp_auto_create
_LEGACY_DOMAIN = 'shipping_notice'
_LEGACY_JOB_TYPES: frozenset[str] = frozenset({
'shipping_stp_auto_create',
})
_LEGACY_STATUSES: frozenset[str] = frozenset({'failed', 'dead'})
# 脱敏正则(非常粗:防止 secret/password/token/key 等明文进入管理面板)
_SENSITIVE_KEY_RE = re.compile(
r'(password|passwd|secret|token|api[_-]?key|credential|authorization)',
flags=re.IGNORECASE,
)
def _mask_sensitive(obj: Any) -> Any:
"""递归递归脱敏 dict/list 中疑似密钥字段的值(fail-safe,不抛错)。"""
if isinstance(obj, dict):
out: dict[str, Any] = {}
for k, v in obj.items():
if isinstance(k, str) and _SENSITIVE_KEY_RE.search(k):
out[k] = '***MASKED***'
else:
out[k] = _mask_sensitive(v)
return out
if isinstance(obj, list):
return [_mask_sensitive(i) for i in obj]
if isinstance(obj, tuple):
return tuple(_mask_sensitive(i) for i in obj)
return obj
def _serialize_job_row(job) -> dict[str, Any]:
"""把 Job ORM 行 → 管理员摘要 JSON(只读投影)。"""
result_json = dict(job.result_json or {}) if isinstance(job.result_json, dict) else {}
payload_json = dict(job.payload_json or {}) if isinstance(job.payload_json, dict) else {}
blocking_reason = (
result_json.get('blocking_reason')
or result_json.get('reason_code')
or result_json.get('error_code')
or None
)
if isinstance(blocking_reason, dict):
blocking_reason = blocking_reason.get('code') if isinstance(blocking_reason.get('code'), str) else None
return {
'job_id': int(job.id),
'domain': str(job.domain or ''),
'job_type': str(job.job_type or ''),
'status': str(job.status or ''),
'business_ref': str(job.business_ref or ''),
'reference_key': str(getattr(job, 'reference_key', None) or ''), # 兼容旧 Job
'case_no': (
str(getattr(job, 'reference_key', None) or '') or
str(payload_json.get('case_no') or '') or None
),
'priority': int(job.priority or 0),
'attempts': int(job.attempts or 0),
'max_attempts': int(job.max_attempts or 0),
'message': str(job.message or '') or None,
'error_message': str(job.error_message or '') or None,
'error_code': str(result_json.get('error_code') or ''),
'blocking_reason': (str(blocking_reason) if blocking_reason else None),
'retryable': bool(result_json.get('retryable')) if result_json.get('retryable') is not None else None,
'next_action': result_json.get('next_action'),
'retry_of_job_id': (int(job.retry_of_job_id) if job.retry_of_job_id else None),
'created_by_id': (int(job.created_by_id) if job.created_by_id else None),
'result_json_masked': _mask_sensitive(result_json),
'payload_json_masked': _mask_sensitive(payload_json),
'created_at': str(job.created_at.isoformat()) if isinstance(job.created_at, datetime) else None,
'updated_at': str(job.updated_at.isoformat()) if isinstance(job.updated_at, datetime) else None,
'started_at': str(job.started_at.isoformat()) if isinstance(job.started_at, datetime) else None,
'finished_at': str(job.finished_at.isoformat()) if isinstance(job.finished_at, datetime) else None,
}
def _parse_iso_dt(value: str | None, *, field: str):
"""解析可选 ISO 日期时间;抛 ValidationError。"""
from app.core.errors import ValidationError
if value in (None, ''):
return None
try:
text = str(value).strip()
if text.endswith('Z'):
text = text[:-1] + '+00:00'
return datetime.fromisoformat(text)
except ValueError as exc:
raise ValidationError(f'{field} must be ISO datetime (YYYY-MM-DDTHH:MM:SS)') from exc
def list_admin_legacy_stp_jobs(
*,
page: int = 1,
page_size: int = 25,
status: str | None = None,
job_type: str | None = None,
q: str | None = None,
case_no: str | None = None,
error_code: str | None = None,
blocking_reason: str | None = None,
created_from: str | None = None,
created_to: str | None = None,
sort: str = '-created_at',
) -> dict[str, Any]:
"""
管理员只读列表:domain=shipping_notice + job_type=shipping_stp_auto_create + status IN {failed, dead}。
用于运维面板快速定位历史 928/929 这类失败死 Job。
"""
from app.core.errors import ValidationError
from app.models.job import Job
from app import db # type: ignore
if not isinstance(page, int) or page < 1:
raise ValidationError('page must be positive integer')
if not isinstance(page_size, int) or not 1 <= page_size <= 100:
raise ValidationError('page_size must be between 1 and 100')
if status and str(status) not in _LEGACY_STATUSES:
raise ValidationError(f'status must be one of: {sorted(_LEGACY_STATUSES)}')
if job_type and str(job_type) not in _LEGACY_JOB_TYPES:
raise ValidationError(f'job_type must be one of: {sorted(_LEGACY_JOB_TYPES)}')
created_from_dt = _parse_iso_dt(created_from, field='created_from')
created_to_dt = _parse_iso_dt(created_to, field='created_to')
# 只拿失败/死 STP Job
where = [
Job.domain == _LEGACY_DOMAIN,
Job.job_type.in_(list(_LEGACY_JOB_TYPES)),
Job.status.in_(list(_LEGACY_STATUSES)),
]
if status:
where.append(Job.status == str(status))
if job_type:
where.append(Job.job_type == str(job_type))
if case_no:
case_no_s = str(case_no).strip()
where.append(or_(
getattr(Job, 'reference_key', None) == case_no_s
if hasattr(Job, 'reference_key')
else False,
# 兼容旧模型:从 payload_json->case_no 查(JSON 跨库差异大,仅包含匹配)
Job.payload_json.contains({'case_no': case_no_s}),
))
if error_code:
where.append(Job.result_json.contains({'error_code': str(error_code).strip()}))
if blocking_reason:
br = str(blocking_reason).strip()
where.append(or_(
Job.result_json.contains({'blocking_reason': br}),
Job.result_json.contains({'reason_code': br}),
))
if created_from_dt is not None:
where.append(Job.created_at >= created_from_dt)
if created_to_dt is not None:
where.append(Job.created_at <= created_to_dt)
if q and str(q).strip():
qs = f'%{str(q).strip()}%'
where.append(or_(
Job.business_ref.ilike(qs),
Job.message.ilike(qs),
Job.error_message.ilike(qs),
))
# 排序
sort_exprs = []
for raw in str(sort or '-created_at').split(','):
s = raw.strip()
if not s:
continue
descending = s.startswith('-')
key = s[1:] if descending else s
if key == 'created_at':
expr = Job.created_at.desc() if descending else Job.created_at.asc()
elif key == 'updated_at':
expr = Job.updated_at.desc() if descending else Job.updated_at.asc()
elif key == 'id':
expr = Job.id.desc() if descending else Job.id.asc()
elif key == 'attempts':
expr = Job.attempts.desc() if descending else Job.attempts.asc()
else:
continue
sort_exprs.append(expr)
if not sort_exprs:
sort_exprs = [Job.created_at.desc()]
stmt = db.select(Job).where(and_(*where)).order_by(*sort_exprs)
total = len(db.session.scalars(db.select(Job.id).where(and_(*where))).all())
items = db.session.scalars(
stmt.offset((int(page) - 1) * int(page_size)).limit(int(page_size)),
).all()
return {
'items': [_serialize_job_row(j) for j in items],
'pagination': {
'page': int(page),
'page_size': int(page_size),
'total': int(total),
'total_pages': ((int(total) + int(page_size) - 1) // int(page_size)) if total > 0 else 0,
},
'filters': {
'domain': _LEGACY_DOMAIN,
'job_types': sorted(_LEGACY_JOB_TYPES),
'statuses': sorted(_LEGACY_STATUSES),
},
}
def get_admin_legacy_stp_job(job_id: int) -> dict[str, Any]:
"""
管理员单条历史 STP Job 详情:返回 Job 投影 + 回链 Review Case(若 reference_key==case_no 存在)。
仅允许失败/死 Job:若 Job 是 queued/running → 抛 ValidationError(避免管理员误对活跃 Job 做 replay)。
"""
from app.core.errors import NotFoundError, ValidationError
from app.models.job import Job
from app.models.shipping.shipping_order_review_case import ShippingOrderReviewCase
job = db.session.get(Job, int(job_id))
if job is None:
raise NotFoundError(f'legacy job not found: {job_id}', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
if str(job.domain or '') != _LEGACY_DOMAIN:
raise ValidationError(f'legacy job must be domain={_LEGACY_DOMAIN}')
if str(job.job_type or '') not in _LEGACY_JOB_TYPES:
raise ValidationError(f'legacy job must be job_type in {sorted(_LEGACY_JOB_TYPES)}')
if str(job.status or '') not in _LEGACY_STATUSES:
raise ValidationError(
f'legacy job must be status in {sorted(_LEGACY_STATUSES)} (current={job.status})',
code='SHIPPING.RECONCILE_INVALID_USER_ACTION',
)
job_row = _serialize_job_row(job)
# 回链 Review Case(只读:若能通过 reference_key==case_no 找得到)
case_no = (
str(getattr(job, 'reference_key', None) or '')
or str((job.payload_json or {}).get('case_no') or '')
or None
)
case_row: dict[str, Any] | None = None
if case_no:
case_obj = (
ShippingOrderReviewCase.query
.filter_by(case_no=str(case_no).strip())
.order_by(ShippingOrderReviewCase.id.desc())
.first()
)
if case_obj is not None:
case_row = {
'case_id': int(case_obj.id),
'case_no': str(case_obj.case_no or ''),
'status': str(case_obj.status or ''),
'candidate_id': int(case_obj.candidate_id) if case_obj.candidate_id else None,
'confirmed_task_id': int(case_obj.confirmed_task_id) if case_obj.confirmed_task_id else None,
'document_id': int(case_obj.document_id) if case_obj.document_id else None,
'owner_user_id': int(case_obj.owner_user_id) if case_obj.owner_user_id else None,
'created_at': str(case_obj.created_at.isoformat()) if getattr(case_obj, 'created_at', None) else None,
'updated_at': str(case_obj.updated_at.isoformat()) if getattr(case_obj, 'updated_at', None) else None,
}
return {
'job': job_row,
'case': case_row,
'replay_plan': {
'supported': True,
'recommended_user_action': (
'force_create'
if case_row and str(case_row.get('status') or '') in {'draft', 'ready', 'unreviewed'}
else 'create_revision'
),
'needs_replay_mode': bool(case_row and job_row.get('case_no') != case_row.get('case_no')),
'reconcile_and_progress_endpoint': (
f'/workspace/shipping-notice/order-review-cases/{case_no}/reconcile-and-progress'
if case_no else None
),
},
}
@@ -9,6 +9,7 @@ services/shipping_notice/line_inventory_match_persistence.py
from __future__ import annotations
import hashlib
from datetime import datetime
from typing import Any
@@ -18,6 +19,10 @@ from app.models import (
ShippingNoticeLineInventoryMatch,
ShippingOrderReviewCase,
)
from app.services.shipping_notice.inventory_candidate_projection import (
get_active_candidate_lines,
get_active_candidate_set,
)
def _draft_line_keys_by_index(case: ShippingOrderReviewCase | None) -> dict[int, str]:
@@ -68,6 +73,8 @@ def map_disposition_to_match_codes(
res = str(reservation_id or '').strip()
if disp == 'multi_file_conflict':
return 'source_conflict', 'source_conflict'
if disp == 'invalid':
return 'invalid', 'invalid'
if not part or not res:
return 'invalid_key', 'invalid_key'
if disp == 'not_found':
@@ -110,6 +117,11 @@ def persist_line_inventory_match_facts(
written: list[ShippingNoticeLineInventoryMatch] = []
now = datetime.utcnow()
current_candidate_set = get_active_candidate_set(task)
candidate_lines_by_no = {
int(row.line_no): row
for row in get_active_candidate_lines(task)
}
for result in line_results:
try:
@@ -134,6 +146,12 @@ def persist_line_inventory_match_facts(
required = result.get('required_qty')
available = result.get('available_qty')
shortage = result.get('shortage_qty')
candidate_line = candidate_lines_by_no.get(index + 1)
allowed_source_codes = (
list(getattr(candidate_line, 'source_codes_json', None) or [])
if candidate_line is not None
else []
)
# [STEP] BE-5:无库存快照时禁止 ready/not_found(不得规范为 0)
if snap_id is None and (
@@ -184,63 +202,154 @@ def persist_line_inventory_match_facts(
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
# [T6 E1] 行级证据哈希:SHA256(source_code|file_no|row_index|reservation_id|part_number)
src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None
file_no = str(result.get('inventory_file_no') or '')[:128] or None
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
try:
row_index = int(row_index_raw) if row_index_raw is not None and str(row_index_raw).strip() else None
except (TypeError, ValueError):
row_index = None
rsv = str(result.get('reservation_id') or '')[:128] or None
pn = str(result.get('part_number') or '')[:128] or None
evidence_parts = [
src_code or '',
file_no or '',
str(row_index) if row_index is not None else '',
rsv or '',
pn or '',
]
evidence_plain = '|'.join(evidence_parts)
evidence_ref = hashlib.sha256(evidence_plain.encode('utf-8')).hexdigest() if any(evidence_parts) else None
detail_json = {
'disposition': result.get('disposition'),
'line_status': result.get('line_status'),
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': file_no,
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
'evidence_ref_plain': evidence_plain if evidence_ref else None,
}
row = ShippingNoticeLineInventoryMatch(
task_id=int(task.id),
review_case_id=int(case.id) if case is not None else None,
line_key=line_key,
line_index=index,
candidate_set_id=(
int(current_candidate_set.id)
if current_candidate_set is not None
else None
),
candidate_set_version=(
int(current_candidate_set.set_version)
if current_candidate_set is not None
else None
),
candidate_line_id=int(candidate_line.id) if candidate_line is not None else None,
inventory_snapshot_id=int(snap_id) if snap_id is not None else None,
match_result=match_result,
inventory_status=inventory_status,
required_qty=str(required) if required is not None else None,
available_qty=str(available) if available is not None else None,
shortage_qty=str(shortage) if shortage is not None else None,
reservation_id=str(result.get('reservation_id') or '')[:128] or None,
part_number=str(result.get('part_number') or '')[:128] or None,
reservation_id=rsv,
part_number=pn,
unit=unit_value,
matching_rule_version=str(matching_rule_version or '')[:64] or None,
inventory_source_code=(
str(result.get('resolved_inventory_source_code') or '')[:64] or None
),
inventory_source_code=src_code,
is_current=True,
matched_at=now,
detail_json={
'disposition': result.get('disposition'),
'line_status': result.get('line_status'),
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': result.get('inventory_file_no'),
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
},
# T6 行级证据
matched_file_no=file_no,
matched_row_index=row_index,
evidence_ref=evidence_ref,
allowed_source_codes_snapshot=list(allowed_source_codes),
matched_qty=str(available) if available is not None else None,
evidence_checksum=hashlib.sha256(
str({
'candidate_set_id': int(current_candidate_set.id) if current_candidate_set is not None else None,
'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None,
'allowed_source_codes_snapshot': list(allowed_source_codes),
'inventory_file_no': file_no,
'inventory_snapshot_id': int(snap_id) if snap_id is not None else None,
'inventory_row_ref': result.get('inventory_row_ref'),
'match_result': match_result,
}).encode('utf-8')
).hexdigest(),
match_attempt_id=None,
detail_json=detail_json,
created_at=now,
updated_at=now,
)
db.session.add(row)
written.append(row)
else:
# [T6 E1] 更新分支:同样重算 evidence_ref、matched_file_no、matched_row_index
src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None
file_no = str(result.get('inventory_file_no') or '')[:128] or None
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
try:
row_index = int(row_index_raw) if row_index_raw is not None and str(row_index_raw).strip() else None
except (TypeError, ValueError):
row_index = None
rsv = str(result.get('reservation_id') or '')[:128] or None
pn = str(result.get('part_number') or '')[:128] or None
evidence_parts = [
src_code or '',
file_no or '',
str(row_index) if row_index is not None else '',
rsv or '',
pn or '',
]
evidence_plain = '|'.join(evidence_parts)
evidence_ref = hashlib.sha256(evidence_plain.encode('utf-8')).hexdigest() if any(evidence_parts) else None
detail_json = {
'disposition': result.get('disposition'),
'line_status': result.get('line_status'),
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': file_no,
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
'evidence_ref_plain': evidence_plain if evidence_ref else None,
}
existing.match_result = match_result
existing.inventory_status = inventory_status
existing.required_qty = str(required) if required is not None else None
existing.available_qty = str(available) if available is not None else None
existing.shortage_qty = str(shortage) if shortage is not None else None
existing.reservation_id = str(result.get('reservation_id') or '')[:128] or None
existing.part_number = str(result.get('part_number') or '')[:128] or None
existing.reservation_id = rsv
existing.part_number = pn
existing.unit = unit_value
existing.matching_rule_version = str(matching_rule_version or '')[:64] or None
existing.inventory_source_code = (
str(result.get('resolved_inventory_source_code') or '')[:64] or None
)
existing.inventory_source_code = src_code
existing.is_current = True
existing.matched_at = now
existing.updated_at = now
existing.detail_json = {
'disposition': result.get('disposition'),
'line_status': result.get('line_status'),
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'inventory_file_no': result.get('inventory_file_no'),
'inventory_row_ref': result.get('inventory_row_ref'),
'snapshot_missing': snap_id is None,
}
existing.candidate_set_id = int(current_candidate_set.id) if current_candidate_set is not None else None
existing.candidate_set_version = (
int(current_candidate_set.set_version)
if current_candidate_set is not None
else None
)
existing.candidate_line_id = int(candidate_line.id) if candidate_line is not None else None
# T6 行级证据
existing.matched_file_no = file_no
existing.matched_row_index = row_index
existing.evidence_ref = evidence_ref
existing.allowed_source_codes_snapshot = list(allowed_source_codes)
existing.matched_qty = str(available) if available is not None else None
existing.evidence_checksum = hashlib.sha256(
str({
'candidate_set_id': int(current_candidate_set.id) if current_candidate_set is not None else None,
'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None,
'allowed_source_codes_snapshot': list(allowed_source_codes),
'inventory_file_no': file_no,
'inventory_snapshot_id': int(snap_id) if snap_id is not None else None,
'inventory_row_ref': result.get('inventory_row_ref'),
'match_result': match_result,
}).encode('utf-8')
).hexdigest()
existing.detail_json = detail_json
# 确保同 task+line 仅本条 current
(
ShippingNoticeLineInventoryMatch.query
@@ -66,6 +66,7 @@ SOURCE_STATUS_RESOLVING = 'resolving'
SOURCE_STATUS_UNRECOGNIZED = 'unrecognized'
SOURCE_STATUS_CONFLICT = 'conflict'
SOURCE_STATUS_UNAVAILABLE = 'unavailable'
SOURCE_STATUS_CANDIDATES_FROZEN = 'candidates_frozen'
def line_auto_fulfill_enabled() -> bool:
@@ -467,10 +468,17 @@ def project_line_inventory_view(
auto_fulfill_error_message: str | None = None,
inventory_rpa_running: bool = False,
source_labels: dict[str, str] | None = None,
fallback_inventory_source: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
单行库存+履约用户投影。
Args:
fallback_inventory_source: Task 级回退库存源事实(行级匹配缺失时使用)。
支持:resolved / user_confirmed / candidates_frozen / resolving 四种语义。
仅影响 inventory_source 展示对象,不得污染 inventory_status / match_result /
available_qty / shortage_qty / is_shortage / allowed_actions。
Returns:
inventory_* / inventory_source / inventory_allowed_actions /
line_allowed_actions / user_line_status 等。
@@ -484,6 +492,34 @@ def project_line_inventory_view(
decision_source=decision_source,
auto_fulfill_failed=False,
)
fallback = dict(fallback_inventory_source) if isinstance(fallback_inventory_source, dict) else {}
default_source = {
'code': None,
'label': None,
'status': SOURCE_STATUS_RESOLVING,
'source': 'inventory_source_clue',
}
if fallback.get('code') and fallback.get('status') in {
SOURCE_STATUS_RESOLVED,
'resolved',
'user_confirmed',
}:
pre_source = {
'code': fallback.get('code'),
'label': fallback.get('label'),
'status': SOURCE_STATUS_RESOLVED,
'source': fallback.get('source') or 'task_inventory_source',
}
elif fallback.get('status') == SOURCE_STATUS_CANDIDATES_FROZEN and fallback.get('candidates'):
pre_source = {
'code': None,
'label': None,
'status': SOURCE_STATUS_CANDIDATES_FROZEN,
'candidates': list(fallback.get('candidates') or []),
'source': fallback.get('source') or 'frozen_inventory_candidates',
}
else:
pre_source = default_source
return {
'inventory_status': None,
'match_result': None,
@@ -493,12 +529,7 @@ def project_line_inventory_view(
'display_available': 'pending',
'inventory_snapshot_id': None,
'inventory_checked_at': None,
'inventory_source': {
'code': None,
'label': None,
'status': SOURCE_STATUS_RESOLVING,
'source': 'inventory_source_clue',
},
'inventory_source': pre_source,
'user_line_status': user_status,
'decision_source': decision_source,
'retryable': False,
@@ -557,12 +588,42 @@ def project_line_inventory_view(
stored_line_status=stored_line_status,
user_line_status=user_status,
)
source = project_inventory_source(
line_source_code = fact.get('inventory_source_code')
raw_source = project_inventory_source(
inventory_status=inventory_status,
match_result=match_result,
source_code=fact.get('inventory_source_code'),
source_code=line_source_code,
source_labels=source_labels,
)
# [STEP] 库存源事实优先级:行级匹配 > Task 级正式源 > 冻结候选源 > 解析中
# 仅覆盖 inventory_source 展示对象;严禁污染 inventory_status / match_result /
# available_qty / shortage_qty / is_shortage / allowed_actions。
fallback = dict(fallback_inventory_source) if isinstance(fallback_inventory_source, dict) else {}
fb_code = str(fallback.get('code') or '').strip().upper() or None
fb_status = str(fallback.get('status') or '').strip()
if not line_source_code and fallback:
if fb_code and fb_status in {'resolved', 'user_confirmed', SOURCE_STATUS_RESOLVED}:
label_val = str(fallback.get('label') or '').strip() or (
(source_labels or {}).get(fb_code)
)
source = {
'code': fb_code,
'label': label_val or None,
'status': SOURCE_STATUS_RESOLVED,
'source': fallback.get('source') or 'task_inventory_source',
}
elif fb_status == SOURCE_STATUS_CANDIDATES_FROZEN and fallback.get('candidates'):
source = {
'code': None,
'label': None,
'status': SOURCE_STATUS_CANDIDATES_FROZEN,
'candidates': list(fallback.get('candidates') or []),
'source': fallback.get('source') or 'frozen_inventory_candidates',
}
else:
source = raw_source
else:
source = raw_source
retryable = project_line_retryable(
inventory_allowed_actions=inv_actions,
user_line_status=user_status,
@@ -615,7 +615,7 @@ def assess_order_build_eligibility(
})
for field_code in assessment.get('missing_required_fields') or []:
issues.append({
'code': 'required_field_missing',
'code': 'final_required_field_missing',
'field_code': field_code,
'severity': 'blocking',
'owning_gate_code': 'field_completeness',
@@ -645,7 +645,9 @@ def assess_order_build_eligibility(
bool(assessment.get('can_create_task'))
and not assessment.get('missing_required_fields')
and not assessment.get('invalid_lines')
and not any(str(item.get('code') or '') == 'required_field_missing' for item in issues)
and not any(str(item.get('code') or '') in {
'final_required_field_missing', 'required_field_missing',
} for item in issues)
)
# [STEP] Candidate Qualification:失败只阻断自动建单;用户投影折叠到唯一 Finding。
gate_result = assess_auto_build_gates(
@@ -222,8 +222,15 @@ def confirm_order_customer_match(
site_id: int | None = None,
actor_id: int | None,
reason: str,
commit: bool = True,
) -> dict[str, Any]:
"""人工确认某个订单客户角色;必须写入理由并保留冻结时可复核的指纹。"""
"""
人工确认某个订单客户角色;必须写入理由并保留冻结时可复核的指纹。
Args:
commit: True 时立即 db.session.commit();False 时仅 flush,由调用方统一控制事务
(用于同事务内追加 reconcile / Job 入队等后续步骤)。
"""
if role not in ROLE_FIELDS:
raise ValidationError('Customer role is invalid', code='SHIPPING.ORDER_CUSTOMER_ROLE_INVALID')
row = db.session.query(ShippingOrderCustomerMatch).filter_by(
@@ -253,7 +260,10 @@ def confirm_order_customer_match(
row.confirmation_reason = reason_value
row.confirmed_by_id = actor_id
row.confirmed_at = datetime.utcnow()
db.session.commit()
if commit:
db.session.commit()
else:
db.session.flush()
return serialize_order_customer_match(row)
@@ -1546,13 +1546,13 @@ def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult
unit=unit, intake=intake, schema=schema, definition=definition, table=selected,
confirmed_order_fields=confirmed_order_fields,
)
if orders is None and reason_code in {'row_needs_review', 'required_field_missing'}:
if orders is None and reason_code in {'row_needs_review'}:
orders, review_reason = _build_approved_profile_order_result(
unit=unit, intake=intake, schema=schema, definition=definition, table=selected,
confirmed_order_fields=confirmed_order_fields, allow_manual_review=True,
)
if orders is not None:
decision['fallback_reason_codes'] = [reason_code]
decision['fallback_reason_codes'] = ['row_needs_review']
decision['parsed_table_count'] = 1
return _apply_stp_route_adjudication(decision, execution_mode='deterministic', orders=orders)
reason_code = review_reason or reason_code
@@ -1692,7 +1692,7 @@ def _route_reason_for_issue(issue: str) -> str:
'order_profile_no_match': 'profile_not_found',
'order_profile_ambiguous': 'profile_ambiguous',
'order_profile_layout_drift': 'profile_drift_detected',
'order_profile_snapshot_field_mismatch': 'required_field_missing',
'order_profile_snapshot_field_mismatch': 'profile_schema_mismatch',
'order_profile_multiple_matches': 'profile_ambiguous',
'order_profile_coordinate_reconstruction_unavailable': 'coordinate_evidence_unavailable',
}
@@ -1744,6 +1744,10 @@ def _build_approved_profile_order_result(
line_groups: list[dict[str, Any]] = []
header_values: dict[str, list[dict[str, Any]]] = {}
has_review_rows = False
source_missing_fields: dict[str, Any] = {
'header': {'field_ids': [], 'field_codes': []},
'lines': [],
}
for row in table.get('rows') or []:
# Profile parser 已判定 deleted/invalid 行不可进入订单;禁止把部分解析结果当作完整订单。
if not isinstance(row, dict) or row.get('status') == 'deleted':
@@ -1818,26 +1822,38 @@ def _build_approved_profile_order_result(
if not config.get('required'):
continue
field_id = str(config.get('field_id') or '')
if allow_manual_review:
continue
if config.get('scope') == 'header' and field_id not in present_header and field_id not in po_field_ids:
field_code = str(config.get('field_code') or '')
if config.get('scope') == 'header':
if field_id in po_field_ids:
return None, 'po_missing'
return None, 'required_field_missing'
if config.get('scope') == 'line' and any(
field_id not in {item['field_id'] for item in group['fields']} for group in line_groups
):
return None, 'required_field_missing'
continue
if field_id not in present_header:
source_missing_fields['header']['field_ids'].append(field_id)
if field_code:
source_missing_fields['header']['field_codes'].append(field_code)
elif config.get('scope') == 'line':
for line_idx, group in enumerate(line_groups):
if field_id not in {item['field_id'] for item in group['fields']}:
line_entry = next(
(entry for entry in source_missing_fields['lines']
if isinstance(entry, dict) and entry.get('line_index') == line_idx),
None,
)
if line_entry is None:
line_entry = {'line_index': line_idx, 'field_ids': [], 'field_codes': []}
source_missing_fields['lines'].append(line_entry)
line_entry['field_ids'].append(field_id)
if field_code:
line_entry['field_codes'].append(field_code)
base_order = {
'schema_version_id': schema.get('schema_version_id'), 'schema_checksum': schema.get('checksum'),
'classification': 'shipping_request', 'classification_confidence': 1.0,
'source_intake_no': str(intake.get('intake_no') or ''),
'primary_document_id': int(unit.document_id),
'header_fields': header_fields, 'lines': line_groups, 'conflicts': [],
# Only this frozen approved-profile builder may add this internal marker.
}
if source_missing_fields['header']['field_ids'] or source_missing_fields['lines']:
base_order['source_missing_fields'] = source_missing_fields
if not has_review_rows:
# Only this frozen approved-profile builder may add this internal marker.
base_order['_hxops_acceptance'] = 'approved_deterministic_profile_v1'
# 当前业务约束:一份 PDF 只能形成一个 PO;检测到多个 PO 必须整体拒识并转人工复核。
line_pos = []
@@ -0,0 +1,420 @@
"""
services/shipping_notice/order_review_auto_progress_coordinator.py
用途:建单前复核 Case 的自动推进协调器(客户指纹唯一确认 + Draft 校验 + STP 入队)。
依赖:order_review_customer_service、order_review_draft_service(延迟)、
order_stp_auto_create_service(延迟)、candidate_qualification_service、
fulfillment_audit、ShippingCustomerShadowResolution /
ShippingOrderCustomerMatch / ShippingOrderReviewCase / ShippingOrderProcessingRun。
逻辑:提供 Run 级批量协调(reconcile_run_review_cases_for_auto_progress)和
单 Case 级协调(reconcile_single_case_for_auto_progress)两层入口;
客户协调仅在 shadow.status=unique_candidate 且未 resolve 时自动确认 bill_to;
所有入口均不主动 commit,由调用方统一控制事务;Run 级循环单 Case 异常局部 rollback。
注意:order_stp_auto_create_service 与 order_review_draft_service 均不在顶层 import,
避免 circular import(stp 末尾顶层 import 本模块,draft 顶层 import 本模块)。
"""
from __future__ import annotations
import logging
from typing import Any
from app import db
from app.models import (
ShippingCustomerShadowResolution,
ShippingOrderCandidate,
ShippingOrderCustomerMatch,
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.order_review_customer_service import (
_header_from_case,
_resolve_extraction_for_case,
confirm_order_customer_match,
refresh_order_customer_matches,
resolve_review_case_customer_resolved,
)
from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref
# 注意:validate_draft 与 ensure_stp_auto_create_for_case 均不在顶层 import,
# 避免 circular import。
# 环1(draft):order_review_draft_service → 顶层 import 本模块
# → 本模块顶层 import validate_draft → ImportError。
# 环2(stp):order_stp_auto_create_service → 末尾顶层 import 本模块
# → 本模块顶层 import ensure_stp_auto_create_for_case → ImportError。
# 因此两者均延迟 import 到 reconcile_single_case_for_auto_progress /
# reconcile_run_review_cases_for_auto_progress 的调用点。
_LOGGER = logging.getLogger(__name__)
_TERMINAL_STATUSES = frozenset({
'confirmed', 'confirming', 'non_order', 'superseded', 'quality_issue', 'reparse_pending',
})
# build_review_revalidate_job_ref 已经移动到 recovery_contract.py 作为契约层函数,
# 这里保留薄 re-export,确保历史调用方(如有)不被破坏。
# (draft_service 已改为从 recovery_contract import,断环。)
def _customer_step_for_case(
*,
case: ShippingOrderReviewCase,
trigger: str,
) -> tuple[str, dict[str, Any] | None]:
"""
单 Case 客户协调内部步骤:shadow 唯一命中时自动确认 bill_to。
Args:
case: 复核 Case。
trigger: 触发来源(写 audit)。
Returns:
(step_status, extra_metadata);status 取值 skipped / auto_confirmed / failed / not_applicable。
"""
# [STEP 1-1] 加载关联 Candidate 与 Shadow 分辨率
candidate = (
db.session.get(ShippingOrderCandidate, int(case.candidate_id))
if case.candidate_id
else None
)
shadow = (
ShippingCustomerShadowResolution.query
.filter_by(candidate_id=int(candidate.id))
.first()
if candidate is not None
else None
)
if shadow is None:
return 'not_applicable', {'reason': 'shadow_missing'}
if shadow.status != 'unique_candidate' or not shadow.top_customer_id:
return 'skipped', {'reason': 'shadow_not_unique_candidate'}
# [STEP 1-2] 是否已 resolve(真实评估,避免重复写入)
already_resolved = resolve_review_case_customer_resolved(case=case, candidate=candidate)
if already_resolved:
return 'skipped', {'reason': 'customer_already_resolved'}
# [STEP 1-3] 提取 order_extraction(Candidate 关联优先,否则 Run 内最新)
extraction = _resolve_extraction_for_case(case)
if extraction is None:
return 'failed', {'reason': 'extraction_missing'}
# [STEP 1-4] 若无 bill_to match 行,先按当前头字段刷新
bill_to_exists = (
ShippingOrderCustomerMatch.query
.filter_by(extraction_id=int(extraction.id), role='bill_to')
.first()
is not None
)
if not bill_to_exists:
try:
refresh_order_customer_matches(extraction, _header_from_case(case))
except Exception as exc: # noqa: BLE001
_LOGGER.warning(
'refresh_order_customer_matches failed case_no=%s err=%s',
case.case_no, str(exc)[:200],
)
return 'failed', {'reason': 'refresh_matches_failed', 'error': str(exc)[:200]}
# [STEP 1-5] 自动确认 bill_to 到 top_customer_id
top_customer_id = int(shadow.top_customer_id)
confirm_reason = '抽取协调器-客户指纹唯一命中自动确认'
try:
confirm_order_customer_match(
int(extraction.id),
role='bill_to',
customer_id=top_customer_id,
site_id=None,
actor_id=None,
reason=confirm_reason,
)
except Exception as exc: # noqa: BLE001
_LOGGER.warning(
'confirm_order_customer_match failed case_no=%s err=%s',
case.case_no, str(exc)[:200],
)
return 'failed', {'reason': 'confirm_match_failed', 'error': str(exc)[:200]}
# [STEP 1-6] 记录 audit 事件(customer 自动确认)
try:
record_fulfillment_audit(
event_type='review_case_customer_auto_confirmed_by_run_coordinator',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action='review_case_customer_auto_confirmed',
actor_type='system',
actor_id=None,
review_case_no=str(case.case_no),
owner_user_id=case.owner_user_id,
document_id=case.document_id,
metadata={
'run_id': int(case.run_id) if case.run_id else None,
'candidate_id': int(candidate.id) if candidate is not None else None,
'shadow_status': 'unique_candidate',
'customer_id': top_customer_id,
'extraction_id': int(extraction.id),
'trigger': str(trigger)[:64],
'reason': confirm_reason,
},
source='review_auto_progress_coordinator',
strict=False,
)
except Exception: # noqa: BLE001
_LOGGER.exception('record_fulfillment_audit failed for case_no=%s', case.case_no)
return 'auto_confirmed', {
'customer_id': top_customer_id,
'extraction_id': int(extraction.id),
}
def reconcile_single_case_for_auto_progress(
*,
case_no: Any = None,
case: ShippingOrderReviewCase | None = None,
trigger: str = 'system_reconcile',
refresh_validation: bool = True,
) -> dict[str, Any]:
"""
单 Case 级自动推进协调器。
供 revalidate Job / Sweeper / Case 级 retry API 复用。顺序执行:终态门禁 + 客户协调
+ Draft 校验 + STP 入队;不主动提交事务,由调用方控制。
Args:
case_no: 复核 Case 编号(与 case 二选一)。
case: 已加载的复核 Case(与 case_no 二选一,优先使用)。
trigger: 触发来源标识(写 audit)。
refresh_validation: True 时若有 current_draft 则显式跑 validate_draft。
Returns:
摘要 ``{case_no, customer_step_status, validate_status, enqueue_status,
job_id, idempotency_key, error}``。
"""
result: dict[str, Any] = {
'case_no': None,
'customer_step_status': 'skipped',
'validate_status': 'skipped',
'enqueue_status': 'skipped',
'job_id': None,
'idempotency_key': None,
'error': None,
}
# [STEP 0] 加载 Case;case_no 提供时 db.session.get;无锁(调用方负责短锁或 advisory lock)
loaded_case = case
if loaded_case is None and case_no is not None:
loaded_case = (
ShippingOrderReviewCase.query
.filter_by(case_no=str(case_no).strip().upper())
.first()
)
if loaded_case is None:
result['case_no'] = str(case_no or '') or None
result['error'] = 'case_not_found'
result['enqueue_status'] = 'case_not_found'
return result
result['case_no'] = str(loaded_case.case_no or '')
# [STEP 1] 终态检查 + 已确认检查
if loaded_case.confirmed_task_id or str(loaded_case.status or '') in _TERMINAL_STATUSES:
result['enqueue_status'] = 'already_confirmed_or_terminal'
result['customer_step_status'] = 'skipped'
result['validate_status'] = 'skipped'
return result
# [STEP 2] 客户协调(trigger 带入 audit)
try:
customer_status, customer_meta = _customer_step_for_case(
case=loaded_case, trigger=trigger,
)
result['customer_step_status'] = customer_status
if customer_meta:
result['customer_meta'] = customer_meta
except Exception as exc: # noqa: BLE001
_LOGGER.exception('customer_step failed case_no=%s', loaded_case.case_no)
result['customer_step_status'] = 'failed'
result['error'] = f'customer_step:{str(exc)[:200]}'
# [STEP 3] Draft validate(refresh_validation=True 且有 current_draft)
if refresh_validation and loaded_case.current_draft is not None:
try:
from app.services.shipping_notice.order_review_draft_service import validate_draft
validate_out = validate_draft(
user_id=int(loaded_case.owner_user_id),
case_no=str(loaded_case.case_no),
expected_draft_version=int(loaded_case.current_draft.draft_version),
)
result['validate_status'] = (
validate_out.get('status') if isinstance(validate_out, dict) else 'validated'
)
except Exception as exc: # noqa: BLE001
_LOGGER.warning(
'validate_draft failed case_no=%s err=%s',
loaded_case.case_no, str(exc)[:200],
)
result['validate_status'] = 'failed'
result['error'] = (result['error'] or '') + f'|validate:{str(exc)[:200]}'
else:
result['validate_status'] = 'skipped'
# [STEP 4] ensure_stp_auto_create_for_case(commit=False,调用方统一控制事务)
try:
from app.services.shipping_notice.order_stp_auto_create_service import (
ensure_stp_auto_create_for_case,
)
run = loaded_case.run or (
db.session.get(ShippingOrderProcessingRun, int(loaded_case.run_id))
if loaded_case.run_id else None
)
enqueue_result = ensure_stp_auto_create_for_case(
case=loaded_case,
run=run,
commit=False,
refresh_validation=False,
)
result['enqueue_status'] = str(enqueue_result.get('status') or 'skipped')
result['job_id'] = enqueue_result.get('job_id')
result['idempotency_key'] = enqueue_result.get('idempotency_key')
if enqueue_result.get('error_code'):
result['enqueue_error_code'] = enqueue_result['error_code']
except Exception as exc: # noqa: BLE001
_LOGGER.exception('ensure_stp_auto_create failed case_no=%s', loaded_case.case_no)
result['enqueue_status'] = 'failed'
result['error'] = (result['error'] or '') + f'|enqueue:{str(exc)[:200]}'
return result
def reconcile_run_review_cases_for_auto_progress(
run: ShippingOrderProcessingRun,
) -> list[dict[str, Any]]:
"""
Run 级自动推进协调器:批量协调抽取 Run 下所有 Review Case。
遍历 Run 下全部 Review Case,依次执行:终态门禁 → 客户指纹唯一确认 → Draft 校验
→ STP 幂等入队。单 Case 异常局部 rollback 并摘要 status=failed,不阻断其他 Case。
本函数不主动 db.session.commit();调用方在循环外统一控制事务边界。
Args:
run: 已 ensure_run_review_cases 的抽取 Processing Run。
Returns:
每个 Case 的处理摘要列表(与 reconcile_single_case 返回结构一致)。
"""
results: list[dict[str, Any]] = []
# [STEP 0] 加载 Run 下全部 Case 主键列表(固定顺序,避免重复扫描)
case_ids = [
int(row.id)
for row in (
ShippingOrderReviewCase.query
.filter_by(run_id=int(run.id))
.order_by(ShippingOrderReviewCase.id.asc())
.with_entities(ShippingOrderReviewCase.id)
.all()
)
]
for case_id in case_ids:
case = db.session.get(ShippingOrderReviewCase, case_id)
if case is None:
continue
try:
# [STEP 0 内层] 终态门禁 + 已确认检查
if case.confirmed_task_id or str(case.status or '') in _TERMINAL_STATUSES:
results.append({
'case_no': str(case.case_no or ''),
'customer_step_status': 'skipped',
'validate_status': 'skipped',
'enqueue_status': 'already_confirmed_or_terminal',
'job_id': None,
'idempotency_key': None,
'error': None,
'status': 'skipped_terminal',
})
continue
# [STEP 1 客户协调] shadow unique_candidate 且未 resolve → 自动确认 bill_to
customer_status, customer_meta = _customer_step_for_case(
case=case, trigger='run_reconcile',
)
# [STEP 2 Draft 校验] 有 current_draft 时重新 validate
validate_status = 'skipped'
if case.current_draft is not None:
try:
from app.services.shipping_notice.order_review_draft_service import validate_draft
validate_out = validate_draft(
user_id=int(case.owner_user_id),
case_no=str(case.case_no),
expected_draft_version=int(case.current_draft.draft_version),
)
validate_status = (
validate_out.get('status') if isinstance(validate_out, dict) else 'validated'
)
except Exception as exc: # noqa: BLE001
_LOGGER.warning(
'validate_draft failed case_no=%s err=%s',
case.case_no, str(exc)[:200],
)
validate_status = 'failed'
# [STEP 3 STP 入队] 幂等 ensure,commit=False
from app.services.shipping_notice.order_stp_auto_create_service import (
ensure_stp_auto_create_for_case,
)
enqueue_result = ensure_stp_auto_create_for_case(
case=case,
run=run,
commit=False,
refresh_validation=False,
)
# [STEP 4] flush 当前 Case 的所有写入(客户确认、Draft 校验、STP Job)
db.session.flush()
case_summary: dict[str, Any] = {
'case_no': str(case.case_no or ''),
'customer_step_status': customer_status,
'validate_status': validate_status,
'enqueue_status': str(enqueue_result.get('status') or 'skipped'),
'job_id': enqueue_result.get('job_id'),
'idempotency_key': enqueue_result.get('idempotency_key'),
'error': None,
'status': str(enqueue_result.get('status') or 'processed'),
}
if customer_meta:
case_summary['customer_meta'] = customer_meta
if enqueue_result.get('error_code'):
case_summary['enqueue_error_code'] = enqueue_result['error_code']
if validate_status == 'failed':
case_summary['status'] = 'validate_failed'
if customer_status == 'failed' and case_summary['status'] not in {
'validate_failed', 'failed',
}:
case_summary['status'] = 'customer_step_failed'
results.append(case_summary)
except Exception as exc: # noqa: BLE001
# 单 Case 异常局部 rollback 隔离,保证同 Run 其它 Case 继续
_LOGGER.exception('reconcile case failed case_id=%s', case_id)
try:
db.session.rollback()
except Exception: # noqa: BLE001
pass
results.append({
'case_no': getattr(case, 'case_no', None),
'customer_step_status': 'failed',
'validate_status': 'skipped',
'enqueue_status': 'failed',
'job_id': None,
'idempotency_key': None,
'error': str(exc)[:300],
'status': 'failed',
})
return results
@@ -0,0 +1,79 @@
"""
app.services.shipping_notice.order_review_case_snapshot
用途:为订单复核工作台提供「完整 Case 快照」包装响应。
依赖:order_review_projection.serialize_review_case、ShippingOrderReviewCase。
逻辑:复用既有 Case 投影作为唯一业务真源,再补充 projection_version 与
loading_context,避免 API 路由层继续膨胀,同时保持统一 envelope 契约。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app.models import ShippingOrderReviewCase
from app.services.shipping_notice.order_review_projection import serialize_review_case
def _projection_version(case: ShippingOrderReviewCase) -> int:
"""
基于 Case 更新时间生成快照版本号。
Args:
case: 当前复核 Case。
Returns:
以毫秒时间戳表示的投影版本;无更新时间时回退到 draft_version。
"""
updated_at = getattr(case, 'updated_at', None)
if isinstance(updated_at, datetime):
return int(updated_at.timestamp() * 1000)
draft = getattr(case, 'current_draft', None)
return int(getattr(draft, 'draft_version', 0) or 0)
def _loading_context(payload: dict[str, Any]) -> dict[str, Any]:
"""
从既有 automation 投影抽取仅供展示的 loading_context。
Args:
payload: serialize_review_case 返回的 Case 投影。
Returns:
仅含 phase / status / message 的最小展示上下文。
"""
automation = payload.get('automation')
if not isinstance(automation, dict):
return {
'phase': None,
'status': None,
'message': None,
}
return {
'phase': str(automation.get('phase') or '').strip() or None,
'status': str(automation.get('status') or '').strip() or None,
'message': str(automation.get('message') or '').strip() or None,
}
def build_order_review_case_snapshot(
case: ShippingOrderReviewCase,
*,
is_admin: bool = False,
) -> dict[str, Any]:
"""
构建订单复核工作台单 Case 完整快照。
Args:
case: 当前用户可见的复核 Case。
is_admin: 是否管理员视角。
Returns:
包含 case / projection_version / loading_context 的完整快照。
"""
payload = serialize_review_case(case, is_admin=is_admin)
return {
'case': payload,
'projection_version': _projection_version(case),
'loading_context': _loading_context(payload),
}
@@ -29,18 +29,24 @@ from app.services.shipping_notice.order_customer_matching import (
refresh_order_customer_matches,
serialize_order_customer_match,
)
from app.services.shipping_notice.order_review_draft_service import (
soft_load_review_case_for_audit,
validate_draft,
)
from app.services.shipping_notice.workflow_ledger_service import (
assert_case_is_current_workflow_version,
)
def _get_draft_imports():
"""延迟导入 draft_service 以解开 job_registry → fulfill_service → draft_service 的循环链。"""
from app.services.shipping_notice.order_review_draft_service import (
soft_load_review_case_for_audit,
validate_draft,
)
return soft_load_review_case_for_audit, validate_draft
def _load_writable_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
"""加载属主可写 Case,并校验 Workflow 当前版本。"""
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no or ''))
soft_load, _v = _get_draft_imports()
case = soft_load(user_id=int(user_id), case_no=str(case_no or ''))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
if str(case.status or '') in {'confirmed', 'non_order', 'superseded', 'reparse_pending'}:
@@ -111,6 +117,9 @@ def _header_from_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""
投影复核 Case 的建单前客户识别状态,供工作台固定客户区展示。
【GET 纯读契约】本函数是只读投影,不做任何 DB 写入、不确认客户、不校验 Draft、不提交事务。
唯一客户自动确认已迁移至系统级协调器 reconcile_run_review_cases_for_auto_progress,
在抽取收尾、字段变更 revalidate Job、recovery sweeper 中统一触发。
Returns:
resolved、status、raw_name、confirmed 客户快照、候选列表、extraction_id。
@@ -138,39 +147,6 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di
match_payload = serialize_order_customer_match(match) if match is not None else None
shadow_matches = list(shadow.candidate_matches_json or []) if shadow is not None else []
top_shadow = shadow_matches[0] if shadow_matches else {}
top_customer_id = shadow.top_customer_id or top_shadow.get('customer_id') if shadow is not None else top_shadow.get('customer_id')
# [STEP 1] 唯一客户指纹命中后立即落确认结果,确保首次打开复核工作台也能看到已确认状态。
# 规则快照与证据完整性仍由影子识别流程负责;这里只消费已持久化的唯一候选。
if (
shadow is not None
and shadow.status == 'unique_candidate'
and top_customer_id
and not resolved
and extraction is not None
):
if match_payload is None:
refresh_order_customer_matches(extraction, _header_from_case(case))
confirm_order_customer_match(
int(extraction.id),
role='bill_to',
customer_id=int(top_customer_id),
site_id=None,
actor_id=None,
reason='客户识别指纹唯一命中自动确认',
)
# 自动确认后立即重跑当前 Draft 校验,避免客户面板已确认而建单资格仍停留在旧快照。
if case.current_draft is not None:
validate_draft(
user_id=int(case.owner_user_id),
case_no=str(case.case_no),
expected_draft_version=int(case.current_draft.draft_version),
)
db.session.commit()
resolved = True
match = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(extraction.id), role='bill_to',
).first()
match_payload = serialize_order_customer_match(match) if match is not None else match_payload
status = 'confirmed' if resolved else str(
(shadow.status if shadow is not None else None)
or (match_payload or {}).get('status')
@@ -260,8 +236,13 @@ def confirm_review_case_customer(
"""
在复核工作台确认标准客户,并刷新建单资格。
核心逻辑:写入 Bill-to CustomerMatch=confirmed → validate Draft → 返回最新 Case。
核心逻辑:写入 Bill-to CustomerMatch=confirmed → 统一协调器推进 → 返回最新 Case。
"""
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress,
)
from app.services.shipping_notice.order_review_projection import serialize_review_case
case = _load_writable_case(user_id=user_id, case_no=case_no)
extraction = _resolve_extraction_for_case(case)
if extraction is None:
@@ -272,6 +253,8 @@ def confirm_review_case_customer(
# [STEP 1] 若尚无 match 行,先按当前头字段刷新,再人工确认。
if ShippingOrderCustomerMatch.query.filter_by(extraction_id=int(extraction.id), role='bill_to').first() is None:
refresh_order_customer_matches(extraction, _header_from_case(case))
# [STEP P1-8] confirm_order_customer_match 保留调用,传 commit=False 以便
# 后续 reconcile(校验+STP 入队)在同一事务提交,保证变更与推进原子可见。
confirm_order_customer_match(
int(extraction.id),
role='bill_to',
@@ -279,31 +262,42 @@ def confirm_review_case_customer(
site_id=None,
actor_id=int(user_id),
reason=str(reason or '复核工作台人工确认标准客户').strip(),
commit=False,
)
# confirm_order_customer_match 已 commit;随后走统一恢复协调器。
from app.services.shipping_notice.order_review_resume_service import (
attach_resume_outcome,
resume_after_review_change,
)
resume = resume_after_review_change(
user_id=int(user_id),
case_no=str(case_no),
# [STEP P1-8] 客户人工确认后走统一协调器:终态门禁 + 客户协调(已人工确认会跳过)+
# Draft 校验 + STP 入队;trigger=customer_confirmed 对应人工确认语义。
reconcile_result = reconcile_single_case_for_auto_progress(
case=case,
trigger='customer_confirmed',
change_type='customer_confirmed',
skip_validate=False,
allow_auto_create=True,
refresh_validation=True,
)
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no))
db.session.commit()
case = _get_draft_imports()[0](user_id=int(user_id), case_no=str(case_no))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
return attach_resume_outcome(
{
'case': resume.get('case'),
'customer_resolution': project_review_case_customer_resolution(case),
},
resume,
)
serialized_case = serialize_review_case(case)
payload: dict[str, Any] = {
'case': serialized_case,
'customer_resolution': project_review_case_customer_resolution(case),
}
# 兼容 attach_resume_outcome 结构;保留 reconcile 原始摘要在 reconcile_outcome。
resume_outcome = {
'gate_recalculated': reconcile_result.get('validate_status') != 'skipped',
'qualification_status': str(reconcile_result.get('validate_status') or ''),
'qualification_ready': reconcile_result.get('validate_status') in {'success', 'validated'},
'can_build': reconcile_result.get('enqueue_status') in {'success', 'enqueued'},
'auto_gate_allowed': reconcile_result.get('enqueue_status') in {'success', 'enqueued'},
'task_created': reconcile_result.get('job_id') is not None,
'task_no': None,
'auto_progress_started': reconcile_result.get('enqueue_status') in {'success', 'enqueued'},
'idempotent_replay': reconcile_result.get('idempotency_key') is not None,
'outcome': str(reconcile_result.get('enqueue_status') or ''),
'message': None,
'failed_gates': None,
}
payload['resume_outcome'] = resume_outcome
payload['reconcile_outcome'] = reconcile_result
return payload
def retry_review_case_customer_resolution(
@@ -316,6 +310,11 @@ def retry_review_case_customer_resolution(
【AI 触发时机】:用户在复核工作台点击「重新识别客户」时调用。
"""
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress,
)
from app.services.shipping_notice.order_review_projection import serialize_review_case
case = _load_writable_case(user_id=user_id, case_no=case_no)
extraction = _resolve_extraction_for_case(case)
if extraction is None:
@@ -335,6 +334,7 @@ def retry_review_case_customer_resolution(
and shadow.top_customer_id
and not resolve_review_case_customer_resolved(case=case, candidate=candidate)
):
# [STEP P1-8] 传 commit=False,保证与后续 reconcile 同事务提交。
confirm_order_customer_match(
int(extraction.id),
role='bill_to',
@@ -342,29 +342,40 @@ def retry_review_case_customer_resolution(
site_id=None,
actor_id=None,
reason='客户识别指纹唯一命中自动确认',
commit=False,
)
# [STEP P1-8] 客户 shadow 重新识别后走统一协调器;trigger=customer_shadow_reconfirmed
# 标识为「影子指纹再确认 + 唯一命中自动确认」路径,与 PATCH 异步 Job、人工确认按钮路径互补不冲突。
reconcile_result = reconcile_single_case_for_auto_progress(
case=case,
trigger='customer_shadow_reconfirmed',
refresh_validation=True,
)
db.session.commit()
from app.services.shipping_notice.order_review_resume_service import (
attach_resume_outcome,
resume_after_review_change,
)
resume = resume_after_review_change(
user_id=int(user_id),
case_no=str(case_no),
trigger='customer_retry',
change_type='customer_confirmed',
skip_validate=False,
allow_auto_create=True,
)
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no))
case = _get_draft_imports()[0](user_id=int(user_id), case_no=str(case_no))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
return attach_resume_outcome(
{
'case': resume.get('case'),
'customer_resolution': project_review_case_customer_resolution(case),
'matches': matches,
},
resume,
)
serialized_case = serialize_review_case(case)
payload: dict[str, Any] = {
'case': serialized_case,
'customer_resolution': project_review_case_customer_resolution(case),
'matches': matches,
}
# 兼容 attach_resume_outcome 结构;保留 reconcile 原始摘要在 reconcile_outcome。
resume_outcome = {
'gate_recalculated': reconcile_result.get('validate_status') != 'skipped',
'qualification_status': str(reconcile_result.get('validate_status') or ''),
'qualification_ready': reconcile_result.get('validate_status') in {'success', 'validated'},
'can_build': reconcile_result.get('enqueue_status') in {'success', 'enqueued'},
'auto_gate_allowed': reconcile_result.get('enqueue_status') in {'success', 'enqueued'},
'task_created': reconcile_result.get('job_id') is not None,
'task_no': None,
'auto_progress_started': reconcile_result.get('enqueue_status') in {'success', 'enqueued'},
'idempotent_replay': reconcile_result.get('idempotency_key') is not None,
'outcome': str(reconcile_result.get('enqueue_status') or ''),
'message': None,
'failed_gates': None,
}
payload['resume_outcome'] = resume_outcome
payload['reconcile_outcome'] = reconcile_result
return payload
@@ -20,6 +20,7 @@ from __future__ import annotations
import copy
import logging
import time
import uuid
from datetime import date
from decimal import Decimal
@@ -29,6 +30,8 @@ _LOGGER = logging.getLogger(__name__)
from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import (
ShippingOrderReviewCase,
ShippingOrderReviewCaseEvent,
@@ -43,6 +46,9 @@ from app.services.shipping_notice.order_build_eligibility_service import (
mark_keep_manual_inventory_decision,
project_line_inventory_candidates,
)
# 注意:build_review_revalidate_job_ref 放在 recovery_contract.py(零依赖契约模块),
# 避免 circular import:draft_service → coordinator → stp → confirmation → draft_service 回绕。
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 (
is_valid_line_no_value,
@@ -794,6 +800,25 @@ def _record_change(
validation=result,
details={'case_event_type': event_type},
)
# [STEP P1-6] 字段 PATCH / 增删行(非显式校验)触发异步 Revalidate Job;
# level-triggered reconcile 补偿:草稿 JSON 变动后统一跑校验 + 客户协调 + STP 入队。
# 同 draft_version 幂等:enqueue 默认 dedupe queued/running,重复调用安全复用已有 job_id。
if event_type != 'draft_validated' and draft is not None:
business_ref = build_review_revalidate_job_ref(case.case_no, draft.draft_version)
enqueue(
JobType.SHIPPING_REVIEW_REVALIDATE_PROGRESS,
{
'case_no': case.case_no,
'draft_version': draft.draft_version,
'operation_id': f"patch-{int(time.time() * 1000)}",
},
domain='shipping_notice',
business_ref=business_ref,
priority=5,
max_attempts=3,
created_by_id=int(actor_id) if actor_id is not None else None,
commit=False,
)
db.session.flush()
return serialize_review_case(case)
@@ -1006,7 +1031,13 @@ def delete_line(*, user_id: int, case_no: str, line_key: str, expected_draft_ver
def validate_draft(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]:
"""显式执行全量草稿校验;只更新验证结果和事件,不创建 Candidate 或 ShippingNotice。"""
"""
显式执行全量草稿校验;只更新验证结果和事件,不创建 Candidate 或 ShippingNotice。
[P1-6 说明] 显式校验按钮走同步 resume(路由层调用 validate_draft 后通常紧接着
resume_after_review_change(trigger='draft_validated')),因此本条路径不额外 enqueue
异步 Revalidate Job;字段编辑/增删行走异步 Job 触发,两条路径互不冲突且互为补充。
"""
action = 'draft_validated'
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
@@ -13,8 +13,12 @@ from typing import Any
from app.services.shipping_notice.order_review_llm_contract import (
DEFAULT_MAX_EVIDENCE_LEVEL,
DEFAULT_V2_EVIDENCE_LEVEL,
EVIDENCE_LEVELS_V2_ALLOWED,
EvidenceLevel,
build_evidence_ref,
)
from app.services.shipping_notice.order_review_llm_policy_registry import mask_field_value
_FORBIDDEN_KEYS = frozenset({
@@ -30,6 +34,8 @@ def select_review_evidence_pack(
target_fields: list[dict[str, Any]],
evidence_level: EvidenceLevel = 'L1_field',
allow_full_pdf: bool = False,
evidence_view: dict[str, Any] | None = None,
token_budget_chars: int = 12000,
) -> dict[str, Any]:
"""
按证据等级组装最小证据包。
@@ -43,6 +49,20 @@ def select_review_evidence_pack(
Returns:
脱敏证据包字典;L2/L3 仅围绕命中目标字段的表/页扩大。
"""
# [V2 BRANCH] v2 等级:走证据视图构建,不触碰 v1 代码。
level_str = str(evidence_level or DEFAULT_V2_EVIDENCE_LEVEL)
if level_str in EVIDENCE_LEVELS_V2_ALLOWED:
return _strip_forbidden(
_build_v2_evidence_pack(
document=document,
target_fields=target_fields,
evidence_level=level_str, # type: ignore[arg-type]
allow_full_pdf=allow_full_pdf,
evidence_view=evidence_view or {},
token_budget_chars=token_budget_chars,
)
)
level = evidence_level if evidence_level in {
'L1_field', 'L2_table', 'L3_page', 'L4_pdf',
} else DEFAULT_MAX_EVIDENCE_LEVEL
@@ -247,3 +267,500 @@ def _strip_forbidden(value: Any) -> Any:
if isinstance(value, list):
return [_strip_forbidden(item) for item in value]
return value
# =========================================================================
# V2 证据等级实现(L1_field / L2_row / L3_table / L4_page / L5_document)
# =========================================================================
_FIELD_CORE_PRIORITY = (
'field_id', 'value', 'quote', 'evidence_ref', 'field_code',
'scope', 'line_key', 'llm_context_policy', 'mask_rule', 'value_source',
)
def _serialize_field_view(
fv: dict[str, Any],
*,
is_target: bool,
strip_secondary_for_token: bool,
) -> dict[str, Any]:
"""
将 evidence_view 中的 field_view 序列化为发给 LLM 的最小字段对象。
Token 预算不足时,非目标字段先丢 display_name / confidence / provenance_ref。
目标字段:field_id/value/quote/evidence_ref 绝对不能丢(截断会被 gated 拦截)。
"""
policy = fv.get('llm_context_policy') or 'forbidden'
fc = fv.get('field_code') or fv.get('field_id') or ''
raw_value = None
if fv.get('value_source') != 'missing_both':
raw_value = (
fv.get('machine_value') if fv.get('value_source') != 'manual_only'
else fv.get('current_draft_value')
)
if raw_value is None:
pe = fv.get('primary_evidence') or {}
if isinstance(pe, dict):
raw_value = pe.get('value') or pe.get('quote') or None
masked = mask_field_value(
policy=policy, # type: ignore[arg-type]
field_code=str(fc),
value=raw_value,
)
sent_value = masked['masked_value'] if masked.get('policy') == 'masked' else raw_value
primary = fv.get('primary_evidence') if isinstance(fv.get('primary_evidence'), dict) else {}
quote_text = str(primary.get('quote') or '').strip() or (
str(raw_value).strip() if raw_value is not None else ''
)
evidence_ref = str(primary.get('evidence_ref') or '').strip() or None
# [STEP] 按保留优先级组装
out: dict[str, Any] = {}
out['field_id'] = fv.get('field_id')
if not strip_secondary_for_token:
out['field_code'] = fc
out['scope'] = fv.get('scope')
if fv.get('line_key'):
out['line_key'] = fv.get('line_key')
out['value'] = sent_value
out['value_source'] = fv.get('value_source') or 'missing_both'
if masked.get('policy') == 'masked':
out['llm_context_policy'] = masked['policy']
out['mask_rule'] = masked.get('mask_rule')
out['original_value_sent'] = bool(masked.get('original_value_sent'))
if quote_text:
out['quote'] = quote_text[:500]
if evidence_ref:
out['evidence_ref'] = evidence_ref
if is_target:
out['is_target'] = True
if not strip_secondary_for_token:
out['confidence'] = primary.get('confidence')
elif strip_secondary_for_token:
# 非目标字段在 token 吃紧时,可丢 quote / evidence_ref 以外的 metadata
for k in ('display_name', 'confidence', 'provenance_ref'):
out.pop(k, None)
return out
def _truncate_fields_list(
fields_list: list[dict[str, Any]],
*,
chars_remaining: int,
target_idx: int,
) -> tuple[list[dict[str, Any]], bool, bool]:
"""
按层级做 token 预算截断;返回 (trimmed_list, any_trimmed, target_core_trimmed)。
target_core_trimmed=True → 直接被上层门禁 evidence_truncated 拦截(本函数会避免)。
"""
any_trimmed = False
target_core_trimmed = False
if not fields_list:
return fields_list, False, False
# [1] 全部保留,先估字符
full_text = _approx_json_chars(fields_list)
if full_text <= chars_remaining:
return fields_list, False, False
# [2] 非目标字段先做 strip_secondary_for_token(目标字段绝对不 strip core)
processed: list[dict[str, Any]] = []
for idx, item in enumerate(fields_list):
if idx == target_idx:
processed.append(item)
else:
stripped = dict(item)
for k in ('display_name', 'confidence', 'page_no', 'table_id',
'row_index', 'cell_id', 'provenance_ref'):
if k in stripped and k not in _FIELD_CORE_PRIORITY:
stripped.pop(k, None)
any_trimmed = True
processed.append(stripped)
if _approx_json_chars(processed) <= chars_remaining:
return processed, any_trimmed, False
# [3] 非目标字段从尾部逐个丢弃(保留头部与目标字段相邻,提高语义)
kept: list[dict[str, Any]] = []
# 先保留目标字段
target_field = processed[target_idx] if 0 <= target_idx < len(processed) else None
# 保留前 1 + 后 1 + 目标字段;逐步缩小范围
kept_order: list[int] = []
# 以 target_idx 为中心向两侧扩散
left = target_idx - 1
right = target_idx + 1
kept_order.append(target_idx)
while left >= 0 or right < len(processed):
if left >= 0:
kept_order.append(left)
left -= 1
if right < len(processed):
kept_order.append(right)
right += 1
kept_order = sorted({k for k in kept_order if 0 <= k < len(processed)})
tentative = [processed[i] for i in kept_order if i != target_idx]
if target_field is not None:
# 把目标字段按原始位置放回去
tentative_final = []
for i in kept_order:
tentative_final.append(processed[i])
tentative = tentative_final
# 如果还超,继续从尾部丢弃非目标字段
while len(tentative) > 1 and _approx_json_chars(tentative) > chars_remaining:
# 找最末尾的非目标字段丢
for reverse_idx in range(len(tentative) - 1, -1, -1):
if not tentative[reverse_idx].get('is_target'):
tentative.pop(reverse_idx)
any_trimmed = True
break
else:
break
if _approx_json_chars(tentative) <= chars_remaining:
return tentative, any_trimmed, False
# [4] 最后,若仍超出 → 目标字段保留 core:field_id/value/quote/evidence_ref
if target_field is not None:
minimal_target = {
'field_id': target_field.get('field_id'),
'is_target': True,
'value': target_field.get('value'),
'value_source': target_field.get('value_source'),
}
if target_field.get('quote'):
minimal_target['quote'] = target_field.get('quote')
if target_field.get('evidence_ref'):
minimal_target['evidence_ref'] = target_field.get('evidence_ref')
result = [minimal_target]
if _approx_json_chars(result) > chars_remaining:
# 极端情况:quote 过长 → 不能截断核心 quote,设置 target_core_trimmed 交由 gate
target_core_trimmed = True
return result, True, target_core_trimmed
return tentative, True, False
def _approx_json_chars(obj: Any) -> int:
if obj is None:
return 4
try:
return len(repr(obj))
except Exception:
return 500
def _build_v2_field_entry(
target: dict[str, Any],
evidence_view: dict[str, Any],
*,
level: str,
token_budget_chars: int,
) -> tuple[dict[str, Any], bool, bool]:
"""
返回 (field_entry, context_truncated, target_core_trimmed)。
field_entry 包含:field_id/field_code/scope/line_key + snippets[] + row_fields[] +
table_headers[] + neighbor_rows[] + page_text[]。
"""
from app.services.shipping_notice.order_review_evidence_view import get_field_view
field_id = str(target.get('field_id') or '')
line_key = str(target.get('line_key') or '').strip() or None
target_fv = get_field_view(evidence_view, field_id=field_id, line_key=line_key)
if target_fv is None:
target_fv = {
'field_id': field_id,
'field_code': target.get('field_code') or field_id,
'scope': target.get('scope'),
'line_key': line_key,
'llm_context_policy': 'allowed',
'value_source': 'missing_both',
'field_evidences': [],
'primary_evidence': None,
}
entry: dict[str, Any] = {
'field_id': field_id,
'field_code': target.get('field_code') or target_fv.get('field_code'),
'scope': target.get('scope') or target_fv.get('scope'),
'line_key': line_key,
'snippets': [],
}
# snippets:摊平所有 field_evidences 的 quote/value/evidence_ref
for ev in (target_fv.get('field_evidences') or [])[:16]:
if not isinstance(ev, dict):
continue
q = str(ev.get('quote') or ev.get('value') or '').strip()
if not q:
continue
snippet: dict[str, Any] = {'quote': q[:500]}
for k in ('evidence_ref', 'source', 'page_no', 'table_id', 'row_index', 'cell_id', 'confidence'):
if ev.get(k) is not None:
snippet[k] = ev[k]
entry['snippets'].append(snippet)
# 范围层级:默认字段数预算
chars_used = _approx_json_chars(entry) + 80 # 预留壳
chars_remaining = max(token_budget_chars - chars_used, 2000)
context_truncated = False
target_core_trimmed = False
# [LEVEL] L1_field:只保留目标字段 serialized
if level == 'L1_field':
entry['target_field'] = _serialize_field_view(target_fv, is_target=True, strip_secondary_for_token=False)
return entry, False, False
# [LEVEL] L2_row:行 scope 包含同行其它字段(按 policy 过滤)
if level == 'L2_row':
line_fields_map = evidence_view.get('line_fields') or {} if line_key else {}
line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {}
row_field_items: list[dict[str, Any]] = []
target_idx = 0
if line_key and isinstance(line_map, dict):
for fid, fv in line_map.items():
if not isinstance(fv, dict):
continue
pol = fv.get('llm_context_policy') or 'forbidden'
if pol == 'forbidden':
continue
if str(fid) == field_id:
target_idx = len(row_field_items)
row_field_items.append(_serialize_field_view(fv, is_target=True, strip_secondary_for_token=False))
else:
row_field_items.append(_serialize_field_view(fv, is_target=False, strip_secondary_for_token=False))
else:
# header scope:无 row;兜底只放目标字段
row_field_items.append(_serialize_field_view(target_fv, is_target=True, strip_secondary_for_token=False))
trimmed, was_trim, core_t = _truncate_fields_list(
row_field_items, chars_remaining=chars_remaining, target_idx=target_idx,
)
entry['row_fields'] = trimmed
entry['row_field_count'] = len(trimmed)
context_truncated = was_trim
target_core_trimmed = core_t
return entry, context_truncated, target_core_trimmed
# [LEVEL] L3_table:表头 + 目标行 + neighbor_rows ±2
if level == 'L3_table':
# 找目标字段的 primary evidence 的 table_id + 行范围
pe = target_fv.get('primary_evidence') or {}
tid = str(pe.get('table_id') or '').strip() or None
page_no = pe.get('page_no')
row_index = pe.get('row_index')
table_headers: list[dict[str, Any]] = []
neighbor_rows: list[dict[str, Any]] = []
# 从 frozen layout 读取 table 结构
candidates = [c for c in ((evidence_view.get('frozen_document') or {}).get('layout_schema_candidates') or [])
if isinstance(c, dict)]
matched_tables = [c for c in candidates if tid and str(c.get('table_id') or '') == tid]
matched_table = matched_tables[0] if matched_tables else (candidates[0] if candidates else None)
if matched_table:
hs = matched_table.get('headers') if isinstance(matched_table.get('headers'), list) else []
for h in hs[:32]:
if isinstance(h, dict):
table_headers.append({
'column_index': h.get('column_index'),
'field_code': h.get('field_code'),
'display_name': h.get('text') or h.get('header'),
})
elif isinstance(h, str) and h.strip():
table_headers.append({'display_name': h.strip()[:120]})
if not table_headers:
for col in (matched_table.get('columns') or [])[:32]:
if not isinstance(col, dict):
continue
path = col.get('header_path')
txt = ' '.join(str(p) for p in path if str(p).strip()) if isinstance(path, list) else ''
table_headers.append({
'column_index': col.get('column_index'),
'field_code': col.get('field_code'),
'display_name': (txt or str(col.get('header_text') or ''))[:120],
})
# neighbor rows:row_index ±2 同 table
rows = matched_table.get('rows') or []
ridx = int(row_index) if isinstance(row_index, int) else None
if ridx is None:
# 没找到 row_index:用 line_key 反查
for ri, r in enumerate(rows):
if isinstance(r, dict) and str(r.get('line_key') or '') == str(line_key or ''):
ridx = ri
break
if ridx is not None:
start = max(ridx - 2, 0)
end = min(ridx + 2 + 1, len(rows))
for pos in range(start, end):
if pos == ridx:
continue
r = rows[pos]
if not isinstance(r, dict):
continue
cell_values = []
for raw_f in (r.get('fields') or [])[:16]:
if not isinstance(raw_f, dict):
continue
v = str(raw_f.get('value') or raw_f.get('quote') or '').strip()
if v:
cell_values.append({
'field_id': raw_f.get('field_id'),
'field_code': raw_f.get('field_code'),
'value': v[:200],
})
neighbor_rows.append({
'row_index': pos,
'line_key': r.get('line_key'),
'cells': cell_values,
})
# 同行字段(复用 L2 逻辑,减少字符预算)
line_fields_map = (evidence_view.get('line_fields') or {}) if line_key else {}
line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {}
row_field_items: list[dict[str, Any]] = []
target_idx = 0
if line_key and isinstance(line_map, dict):
for fid, fv in line_map.items():
if not isinstance(fv, dict):
continue
pol = fv.get('llm_context_policy') or 'forbidden'
if pol == 'forbidden':
continue
if str(fid) == field_id:
target_idx = len(row_field_items)
row_field_items.append(_serialize_field_view(fv, is_target=True, strip_secondary_for_token=False))
else:
row_field_items.append(_serialize_field_view(fv, is_target=False, strip_secondary_for_token=False))
else:
row_field_items.append(_serialize_field_view(target_fv, is_target=True, strip_secondary_for_token=False))
# 先加 table/headers,再做截断
entry['table_headers'] = table_headers
entry['table_id'] = tid
entry['page_no'] = page_no
entry['target_row_index'] = row_index
chars_for_rows = max(chars_remaining - _approx_json_chars(table_headers) - _approx_json_chars(neighbor_rows), 800)
trimmed, was_trim, core_t = _truncate_fields_list(
row_field_items, chars_remaining=chars_for_rows, target_idx=target_idx,
)
entry['row_fields'] = trimmed
entry['neighbor_rows'] = neighbor_rows
if was_trim or len(neighbor_rows) < (4 if ridx is not None else 0):
context_truncated = True
target_core_trimmed = core_t
return entry, context_truncated, target_core_trimmed
# [LEVEL] L4_page:页面文本摘要(+ tables/headers 结构化)
if level == 'L4_page':
page_no_final: int | None = None
pe = target_fv.get('primary_evidence') if isinstance(target_fv.get('primary_evidence'), dict) else {}
page_no_final = pe.get('page_no')
if page_no_final is None:
for ev in (target_fv.get('field_evidences') or [])[:5]:
if isinstance(ev, dict) and ev.get('page_no'):
page_no_final = ev['page_no']
break
# 页面文本块(frozen document layout_snapshot.text_blocks)
page_blocks: list[dict[str, Any]] = []
frozen = evidence_view.get('frozen_document') or {}
layout = frozen.get('layout_snapshot') if isinstance(frozen.get('layout_snapshot'), dict) else {}
for block in (layout.get('text_blocks') or []):
if not isinstance(block, dict):
continue
if page_no_final and int(block.get('page_no') or 0) != int(page_no_final):
continue
txt = ' '.join(str(block.get('text') or '').split()).strip()
if txt:
page_blocks.append({
'page_no': block.get('page_no'),
'block_id': str(block.get('block_id') or '')[:64] or None,
'text': txt[:600],
})
entry['page_blocks'] = page_blocks
entry['page_no'] = page_no_final
# 行字段保留(最小)
line_fields_map = (evidence_view.get('line_fields') or {}) if line_key else {}
line_map = (line_fields_map.get(line_key) if isinstance(line_fields_map, dict) else {}) or {}
row_field_items: list[dict[str, Any]] = []
if line_key and isinstance(line_map, dict):
for fid, fv in line_map.items():
if not isinstance(fv, dict):
continue
pol = fv.get('llm_context_policy') or 'forbidden'
if pol == 'forbidden':
continue
is_t = str(fid) == field_id
row_field_items.append(_serialize_field_view(fv, is_target=is_t, strip_secondary_for_token=not is_t))
else:
row_field_items.append(_serialize_field_view(target_fv, is_target=True, strip_secondary_for_token=False))
trimmed, was_trim, core_t = _truncate_fields_list(
row_field_items, chars_remaining=max(chars_remaining - _approx_json_chars(page_blocks), 1000),
target_idx=0 if row_field_items and row_field_items[0].get('is_target') else 0,
)
entry['row_fields'] = trimmed
# page 级默认视为有截断
if len(page_blocks) * 600 > chars_remaining:
context_truncated = True
if was_trim:
context_truncated = True
target_core_trimmed = core_t
return entry, context_truncated, target_core_trimmed
# L5_document:永不开放(按约定直接返回空壳)
entry['row_fields'] = [_serialize_field_view(target_fv, is_target=True, strip_secondary_for_token=False)]
return entry, True, False
def _build_v2_evidence_pack(
*,
document: dict[str, Any],
target_fields: list[dict[str, Any]],
evidence_level: str,
allow_full_pdf: bool,
evidence_view: dict[str, Any],
token_budget_chars: int,
) -> dict[str, Any]:
"""
v2 证据包:
pack.context_version = 'v2'
pack.fields[]:每个目标字段的 field 包(含 row_fields / table_headers / neighbor_rows / page_blocks)
pack.context_truncated:总体截断标志
pack.target_core_trimmed:目标字段核心被截断 → gate 直接 evidence_truncated
"""
level = evidence_level if evidence_level in EVIDENCE_LEVELS_V2_ALLOWED else DEFAULT_V2_EVIDENCE_LEVEL
if level == 'L5_document':
return {
'document_id': int(document.get('document_id') or 0) or None,
'evidence_level': level,
'context_version': 'v2',
'fields': [],
'context_truncated': True,
'target_core_trimmed': False,
'L4_forbidden_flag': True,
}
level_for_l4 = 'L4_page'
if level == level_for_l4 and not allow_full_pdf:
# 管理员未授权:降级到 L3_table(若仍不可再降到 L2_row 不 gate)
level = 'L3_table'
pack: dict[str, Any] = {
'document_id': int((evidence_view or {}).get('document_id') or document.get('document_id') or 0) or None,
'evidence_level': level,
'context_version': 'v2',
'fields': [],
'context_truncated': False,
'target_core_trimmed': False,
}
per_field_budget = max(token_budget_chars // max(len(target_fields) or 1, 1), 2000)
any_trim = False
any_core_trim = False
for target in target_fields:
if not isinstance(target, dict):
continue
entry, c_t, c_ct = _build_v2_field_entry(
target, evidence_view, level=level, token_budget_chars=per_field_budget,
)
pack['fields'].append(entry)
if c_t:
any_trim = True
if c_ct:
any_core_trim = True
pack['context_truncated'] = any_trim
pack['target_core_trimmed'] = any_core_trim
return pack
@@ -0,0 +1,750 @@
"""
services/shipping_notice/order_review_evidence_view.py
用途:构建单一的 ReviewEvidenceView 作为 LLM 证据和复核展示的统一事实源。
依赖:
- Review Case/Unit/Draft 实体与其 JSON 字段
- order_review_llm_contract(evidence_ref/provenance_ref 生成与校验)
- order_review_llm_policy_registry(llm_context_policy 7 步推断)
逻辑:
- 三源合并顺序:Unit.result_json observation > Draft.machine_fields observation
> Frozen layout_schema_candidates cell evidence。
- 所有 observation 全部摊平为 field_evidences[] 列表,不丢弃任何一条
(后续 gate / auto_upgrade 需要检测多值冲突)。
- 对每个 field 选一条 primary_evidence:6 步排序优先级
evidence_ref 存在 > quote 非空 > value_bbox 可绘制 >
document_id 匹配当前 Case > confidence 最高 > 原数组顺序
- machine_value / current_draft_value 分离;手工覆盖不同触发 manual_conflict。
"""
from __future__ import annotations
import copy
import re
from typing import Any, Final
from app.services.shipping_notice.order_review_llm_contract import (
ObservationSource,
build_evidence_ref,
build_provenance_ref,
is_valid_evidence_ref,
)
from app.services.shipping_notice.document_layout.vc_source_evidence_integration import (
collect_vc_field_evidences,
)
from app.services.shipping_notice.order_review_llm_policy_registry import (
resolve_llm_context_policy,
)
# ---------------------------------------------------------------------------
# 常量
# ---------------------------------------------------------------------------
_MACHINE_LINE_KEY_RE = re.compile(r'^machine-(\d+)$', re.IGNORECASE)
_SOURCE_PRIORITY: Final[dict[str, int]] = {
'unit_observation': 1,
'draft_observation': 2,
'frozen_layout': 3,
'text_fallback': 4,
}
def _safe_int(value: Any, default: int | None = None) -> int | None:
try:
return int(value)
except (TypeError, ValueError):
return default
def _safe_str(value: Any) -> str | None:
if value is None:
return None
text = str(value).strip()
return text or None
def _observation_has_bbox(layout_evidence: Any) -> bool:
if not isinstance(layout_evidence, dict):
return False
bbox = layout_evidence.get('value_bbox')
if not isinstance(bbox, dict):
return False
try:
for key in ('x0', 'y0', 'x1', 'y1'):
f = float(bbox[key])
if not (0 <= f <= 1.01):
return False
return 0 <= float(bbox['x0']) < float(bbox['x1']) <= 1 and \
0 <= float(bbox['y0']) < float(bbox['y1']) <= 1
except (KeyError, TypeError, ValueError):
return False
def _normalize_observation(
raw: Any,
*,
source: ObservationSource,
case_document_id: int,
case_id: int,
field_code: str | None = None,
line_key: str | None = None,
derived_row_index: int | None = None,
) -> dict[str, Any]:
"""
规范化单条 observation(Unit/Draft/FrozenLayout 共用)。
缺失字段显式置 None,绝不伪造。
"""
if not isinstance(raw, dict):
raw = {}
layout = raw.get('layout_evidence') if isinstance(raw.get('layout_evidence'), dict) else {}
doc_id = _safe_int(raw.get('document_id') or layout.get('document_id'))
page_no = _safe_int(layout.get('page_no'))
table_id = _safe_str(layout.get('table_id') or raw.get('table_id'))
cell_id = _safe_str(layout.get('cell_id') or raw.get('cell_id'))
row_index = _safe_int(layout.get('row_index') or derived_row_index)
quote = _safe_str(raw.get('quote'))
value_raw = raw.get('value')
value = None if value_raw is None else (str(value_raw).strip() if not isinstance(value_raw, (int, float, bool)) else value_raw)
layout_evidence_ref = layout.get('evidence_ref') if isinstance(layout, dict) else None
evidence_ref = None
if isinstance(layout_evidence_ref, str) and is_valid_evidence_ref(layout_evidence_ref):
evidence_ref = layout_evidence_ref.strip()
if not evidence_ref and doc_id and page_no:
evidence_ref = build_evidence_ref(
document_id=doc_id,
page_no=page_no,
table_id=table_id,
row_index=row_index,
field_code=field_code,
)
provenance_ref: str | None = None
if source == 'draft_observation' or source == 'text_fallback':
provenance_ref = build_provenance_ref(
case_id=case_id, line_key=line_key, field_code=field_code or '',
)
confidence_raw = raw.get('confidence')
try:
confidence = float(confidence_raw) if confidence_raw is not None else None
except (TypeError, ValueError):
confidence = None
return {
'value': value,
'quote': quote,
'source': source,
'confidence': confidence,
'evidence_ref': evidence_ref,
'provenance_ref': provenance_ref,
'document_id': doc_id,
'page_no': page_no,
'table_id': table_id,
'cell_id': cell_id,
'row_index': row_index,
'value_bbox_valid': _observation_has_bbox({'layout_evidence': layout}),
'document_matches_case': bool(doc_id) and int(doc_id) == int(case_document_id),
}
def _sort_key_primary_evidence(ev: dict[str, Any]) -> tuple:
"""
主证据选择 6 步排序(越小越好):
1. evidence_ref 存在
2. quote 非空
3. value_bbox_valid
4. document_matches_case
5. confidence 高(用负数以升序排列;None 视为最低)
6. source 优先级数字越小越好(unit < draft < frozen < fallback)
"""
ev_source = str(ev.get('source') or 'text_fallback')
source_priority = _SOURCE_PRIORITY.get(ev_source, 99)
conf = ev.get('confidence')
try:
conf_score = 1.0 - float(conf) if conf is not None else 2.0
except (TypeError, ValueError):
conf_score = 2.0
return (
0 if ev.get('evidence_ref') else 1,
0 if ev.get('quote') else 1,
0 if ev.get('value_bbox_valid') else 1,
0 if ev.get('document_matches_case') else 1,
conf_score,
source_priority,
)
# ---------------------------------------------------------------------------
# 三源读取
# ---------------------------------------------------------------------------
def _read_unit_result_json(unit) -> dict[str, Any] | None:
result = getattr(unit, 'result_json', None)
return result if isinstance(result, dict) else None
def _select_order_from_unit(unit_result: dict[str, Any], case_document_id: int) -> tuple[dict[str, Any] | None, list[str]]:
"""
orders = 0 → None;orders = 1 → 直接取;orders > 1 → primary_document_id 优先。
返回 (order_obj, context_ambiguous_reason_list)
"""
reasons: list[str] = []
orders = unit_result.get('orders') or []
if not isinstance(orders, list) or not orders:
return None, ['unit_orders_empty']
actual = [o for o in orders if isinstance(o, dict)]
if len(actual) == 1:
return actual[0], reasons
# >1:按 primary_document_id 匹配 case.document_id
matched = [
o for o in actual
if _safe_int(o.get('primary_document_id')) == int(case_document_id)
]
if len(matched) == 1:
return matched[0], reasons
if len(matched) > 1:
reasons.append('multi_orders_share_primary_document_id')
return matched[0], reasons
reasons.append('unit_orders_ambiguous')
return actual[0], reasons
def _iter_unit_header_fields(order_result: dict[str, Any]) -> list[tuple[str, dict[str, Any]]]:
"""返回 [(field_id, field_obj)];field_obj 含 observations[]。"""
out: list[tuple[str, dict[str, Any]]] = []
for raw in order_result.get('header_fields') or []:
if not isinstance(raw, dict):
continue
fid = _safe_str(raw.get('field_id'))
if not fid:
continue
out.append((fid, raw))
return out
def _iter_unit_line_fields(
order_result: dict[str, Any],
) -> list[tuple[str, int, str, dict[str, Any]]]:
"""返回 [(line_key, row_position, field_id, field_obj)]"""
out: list[tuple[str, int, str, dict[str, Any]]] = []
lines = order_result.get('lines') or []
for pos, line in enumerate(lines):
if not isinstance(line, dict):
continue
line_key = _safe_str(line.get('line_key'))
if not line_key:
index_match = _MACHINE_LINE_KEY_RE.match(f'machine-{pos + 1}')
line_key = index_match.group(0) if index_match else f'machine-{pos + 1}'
for field_obj in line.get('fields') or []:
if not isinstance(field_obj, dict):
continue
fid = _safe_str(field_obj.get('field_id'))
if not fid:
continue
out.append((line_key, pos, fid, field_obj))
return out
# ---------------------------------------------------------------------------
# 辅助:把 Draft values 取当前草稿值(不含 observation,用于 machine vs draft 差异)
# ---------------------------------------------------------------------------
def _draft_header_container(draft) -> dict[str, Any]:
hv = getattr(draft, 'header_values_json', None)
return hv if isinstance(hv, dict) else {}
def _draft_line_list(draft) -> list[dict[str, Any]]:
lines = getattr(draft, 'lines_json', None)
return [ln for ln in (lines if isinstance(lines, list) else []) if isinstance(ln, dict)]
def _find_draft_line(lines: list[dict[str, Any]], line_key: str) -> dict[str, Any] | None:
for ln in lines:
if _safe_str(ln.get('line_key')) == line_key:
return ln
return None
def _machine_field_value(container: dict[str, Any], field_id: str) -> dict[str, Any] | None:
"""
从 Draft.header_values_json 或 lines_json[].machine_fields 中按 field_id 取机器对象。
对象至少包含 observations[] / value / field_code。
"""
machine_fields = container.get('machine_fields') or []
for raw in machine_fields:
if not isinstance(raw, dict):
continue
if _safe_str(raw.get('field_id')) == field_id:
return raw
return None
def _current_draft_value(container: dict[str, Any], field_id: str) -> Any:
values = container.get('values')
if not isinstance(values, dict):
values = container if container.get('values') is None else {}
if isinstance(values, dict) and field_id in values:
return values[field_id]
# 兼容:直接在 container 里以 field_id/field_code 存值
return None
# ---------------------------------------------------------------------------
# 冻结 snapshot layout_schema_candidates → 第三来源
# ---------------------------------------------------------------------------
def _frozen_document_snapshot(case) -> dict[str, Any]:
snapshot = case.run.input_snapshot_json if case.run and isinstance(case.run.input_snapshot_json, dict) else {}
for intake in snapshot.get('intakes') or []:
if not isinstance(intake, dict):
continue
for document in intake.get('documents') or []:
if isinstance(document, dict) and _safe_int(document.get('document_id')) == int(case.document_id):
return document
return {'document_id': int(case.document_id)}
def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, str, int | None, str, dict[str, Any]]]:
"""
返回 [(line_key_or_header, field_id, row_index, table_id, raw_field_obj)]。
header scope 行 line_key=None。
"""
out: list[tuple[str, str, int | None, str, dict[str, Any]]] = []
candidates = [
c for c in (frozen_doc.get('layout_schema_candidates') or [])
if isinstance(c, dict)
]
for candidate in candidates:
table_id = _safe_str(candidate.get('table_id')) or ''
rows = candidate.get('rows') or []
for row_idx, row in enumerate(rows):
if not isinstance(row, dict):
continue
line_key = _safe_str(row.get('line_key'))
data_row_idx = _safe_int(row.get('data_row_index') or row.get('row_index'))
for raw_field in row.get('fields') or []:
if not isinstance(raw_field, dict):
continue
fid = _safe_str(raw_field.get('field_id'))
if not fid:
continue
effective_line_key = line_key
out.append((
effective_line_key,
fid,
data_row_idx,
table_id,
raw_field,
))
return out
# ---------------------------------------------------------------------------
# Schema 字段元数据读取(用于 policy 注册表)
# ---------------------------------------------------------------------------
def _schema_fields_map(case) -> dict[str, dict[str, Any]]:
snapshot = case.run.input_snapshot_json if case.run and isinstance(case.run.input_snapshot_json, dict) else {}
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else {}
result: dict[str, dict[str, Any]] = {}
for raw in definition.get('fields') or []:
if not isinstance(raw, dict):
continue
fid = _safe_str(raw.get('field_id'))
if not fid:
continue
result[fid] = dict(raw)
return result
# ---------------------------------------------------------------------------
# 证据视图公共骨架
# ---------------------------------------------------------------------------
_FIELD_VIEW_KEYS = (
'field_id', 'field_code', 'display_name', 'scope',
'data_type', 'llm_context_policy',
'line_key',
'machine_value', 'current_draft_value', 'value_source',
'primary_evidence', 'field_evidences',
)
def _empty_field_view() -> dict[str, Any]:
return {k: None for k in _FIELD_VIEW_KEYS} | {
'field_evidences': [],
}
def _build_field_view(
*,
field_id: str,
field_metadata: dict[str, Any] | None,
scope: Literal['header', 'line'],
line_key: str | None,
case_id: int,
case_document_id: int,
) -> dict[str, Any]:
view = _empty_field_view()
md = field_metadata or {}
code = _safe_str(md.get('field_code')) or field_id
view['field_id'] = field_id
view['field_code'] = code
view['display_name'] = _safe_str(md.get('display_name')) or code
view['scope'] = scope
view['data_type'] = _safe_str(md.get('data_type'))
view['line_key'] = line_key
policy = resolve_llm_context_policy(
field_metadata=md,
field_code=code,
scope=scope,
data_type=view['data_type'],
is_target_field=False,
)
view['llm_context_policy'] = policy
view['machine_value'] = None
view['current_draft_value'] = None
view['value_source'] = None # manual_override / machine_only / draft_machine / fallback_missing
return view
def _finalize_field_evidences(view: dict[str, Any]) -> None:
"""摊平后,选 primary_evidence,并判断是否存在 manual_conflict。"""
evidences = view.get('field_evidences') or []
if evidences:
sorted_evs = sorted(evidences, key=_sort_key_primary_evidence)
view['primary_evidence'] = copy.deepcopy(sorted_evs[0])
view['field_evidences'] = sorted_evs
if view['machine_value'] is None:
first_val = None
for ev in sorted_evs:
if ev.get('value') is not None and str(ev.get('value') or '').strip() != '':
first_val = ev['value']
break
view['machine_value'] = first_val
else:
view['primary_evidence'] = None
machine = view.get('machine_value')
draft = view.get('current_draft_value')
def _text(v: Any) -> str:
if v is None:
return ''
if isinstance(v, (int, float, bool)):
return str(v)
return str(v).strip()
machine_text = _text(machine)
draft_text = _text(draft)
if draft_text and machine_text and draft_text != machine_text:
view['value_source'] = 'manual_override'
elif draft_text and not machine_text:
view['value_source'] = 'manual_only'
elif machine_text and (not draft_text or draft_text == machine_text):
view['value_source'] = 'machine_only'
else:
view['value_source'] = 'missing_both'
# ---------------------------------------------------------------------------
# 对外主入口
# ---------------------------------------------------------------------------
def build_review_evidence_view(case) -> dict[str, Any]:
"""
为当前 Case 构建 ReviewEvidenceView。
返回结构:
{
"case_id": int,
"document_id": int,
"case_no": str,
"schema_version_id": int | None,
"diagnostics": { "unit_orders_ambiguous": bool, "context_ambiguous_reasons": [] },
"header_fields": { [field_id]: field_view },
"line_fields": {
[line_key]: { [field_id]: field_view }
},
"lines_order": [line_key...],
"layout_schema_candidates": [frozen_candidate...], // 直接引用,不 clone
"frozen_document_snapshot": dict, // 只读
}
"""
case_id = int(case.id)
case_document_id = int(case.document_id)
schema_fields = _schema_fields_map(case)
diagnostics: dict[str, Any] = {
'unit_orders_ambiguous': False,
'context_ambiguous_reasons': [],
'warnings': [],
}
header_fields: dict[str, dict[str, Any]] = {}
line_fields: dict[str, dict[str, dict[str, Any]]] = {}
lines_order: list[str] = []
def _ensure_field(
fid: str,
scope: Literal['header', 'line'],
line_key: str | None = None,
) -> dict[str, Any]:
if scope == 'header':
if fid not in header_fields:
header_fields[fid] = _build_field_view(
field_id=fid,
field_metadata=schema_fields.get(fid),
scope='header',
line_key=None,
case_id=case_id,
case_document_id=case_document_id,
)
return header_fields[fid]
assert line_key
if line_key not in line_fields:
line_fields[line_key] = {}
lines_order.append(line_key)
line_map = line_fields[line_key]
if fid not in line_map:
line_map[fid] = _build_field_view(
field_id=fid,
field_metadata=schema_fields.get(fid),
scope='line',
line_key=line_key,
case_id=case_id,
case_document_id=case_document_id,
)
return line_map[fid]
# [SOURCE 1] Unit.result_json → 最高优先级 observation
unit = getattr(case, 'unit', None)
if unit is not None:
unit_result = _read_unit_result_json(unit)
if unit_result:
order, reasons = _select_order_from_unit(unit_result, case_document_id)
if reasons:
diagnostics['unit_orders_ambiguous'] = True
diagnostics['context_ambiguous_reasons'].extend(reasons)
if order:
for fid, raw_field in _iter_unit_header_fields(order):
fv = _ensure_field(fid, 'header')
observations = raw_field.get('observations') or []
fc = _safe_str(raw_field.get('field_code')) or fv['field_code']
for idx, raw_obs in enumerate(observations):
if not isinstance(raw_obs, dict):
continue
norm = _normalize_observation(
raw_obs,
source='unit_observation',
case_document_id=case_document_id,
case_id=case_id,
field_code=fc,
)
fv['field_evidences'].append(norm)
if fv['machine_value'] is None:
v = raw_field.get('value')
if v is not None:
fv['machine_value'] = v
for line_key, _pos, fid, raw_field in _iter_unit_line_fields(order):
fv = _ensure_field(fid, 'line', line_key=line_key)
observations = raw_field.get('observations') or []
fc = _safe_str(raw_field.get('field_code')) or fv['field_code']
for raw_obs in observations:
if not isinstance(raw_obs, dict):
continue
norm = _normalize_observation(
raw_obs,
source='unit_observation',
case_document_id=case_document_id,
case_id=case_id,
field_code=fc,
line_key=line_key,
)
fv['field_evidences'].append(norm)
if fv['machine_value'] is None:
v = raw_field.get('value')
if v is not None:
fv['machine_value'] = v
# [SOURCE 2] Review Draft machine_fields observation + current_draft_value
draft = case.current_draft
if draft is not None:
schema_version_id = getattr(draft, 'schema_version_id', None)
else:
schema_version_id = None
if draft is not None:
# Header
header_container = _draft_header_container(draft)
for fid in set(list(header_fields.keys()) + list(schema_fields.keys())):
md = schema_fields.get(fid)
scope = 'header'
if md and _safe_str(md.get('scope')) == 'line':
continue
fv = _ensure_field(fid, scope='header')
obj = _machine_field_value(header_container, fid)
if isinstance(obj, dict):
for raw_obs in (obj.get('observations') or []):
if not isinstance(raw_obs, dict):
continue
norm = _normalize_observation(
raw_obs,
source='draft_observation',
case_document_id=case_document_id,
case_id=case_id,
field_code=_safe_str(obj.get('field_code')) or fv['field_code'],
)
fv['field_evidences'].append(norm)
if fv['machine_value'] is None and obj.get('value') is not None:
fv['machine_value'] = obj.get('value')
fv['current_draft_value'] = _current_draft_value(header_container, fid)
# Lines
draft_lines = _draft_line_list(draft)
for line in draft_lines:
line_key = _safe_str(line.get('line_key'))
if not line_key:
continue
line_map = line_fields.setdefault(line_key, {})
if line_key not in lines_order:
lines_order.append(line_key)
for fid in list(line_map.keys()) + list(schema_fields.keys()):
md = schema_fields.get(fid)
if md and _safe_str(md.get('scope')) == 'header':
continue
fv = _ensure_field(fid, 'line', line_key=line_key)
obj = _machine_field_value(line, fid)
if isinstance(obj, dict):
for raw_obs in (obj.get('observations') or []):
if not isinstance(raw_obs, dict):
continue
norm = _normalize_observation(
raw_obs,
source='draft_observation',
case_document_id=case_document_id,
case_id=case_id,
field_code=_safe_str(obj.get('field_code')) or fv['field_code'],
line_key=line_key,
)
fv['field_evidences'].append(norm)
if fv['machine_value'] is None and obj.get('value') is not None:
fv['machine_value'] = obj.get('value')
fv['current_draft_value'] = _current_draft_value(line, fid)
# [SOURCE 3] 冻结 snapshot layout_schema_candidates
frozen_doc = _frozen_document_snapshot(case)
for lk, fid, ridx, tid, raw_field in _iter_frozen_layout_fields(frozen_doc):
scope = 'line' if lk else 'header'
fv = _ensure_field(fid, scope=scope, line_key=lk or None)
wrapped = {
'value': raw_field.get('value') or raw_field.get('quote'),
'quote': raw_field.get('quote') or raw_field.get('value'),
'document_id': case_document_id,
'layout_evidence': {
'page_no': raw_field.get('page_no') or frozen_doc.get('page_no'),
'table_id': tid or None,
'cell_id': raw_field.get('cell_id'),
'row_index': ridx,
'evidence_ref': raw_field.get('evidence_ref'),
'value_bbox': raw_field.get('value_bbox'),
},
'confidence': raw_field.get('confidence'),
}
norm = _normalize_observation(
wrapped,
source='frozen_layout',
case_document_id=case_document_id,
case_id=case_id,
field_code=fv['field_code'],
line_key=lk or None,
derived_row_index=ridx,
)
fv['field_evidences'].append(norm)
# [SOURCE 4] Vendor Comments 三来源 source_observations(Phase 4 新增)
# 追加:不覆盖/替换原有 Unit/Draft/Frozen 三源,仅扩展 LLM 上下文与工作台证据对照。
# 在 finalize 之前插入,以便 _finalize_field_evidences 正确选 primary 与 value_source。
vc_evidences = collect_vc_field_evidences(
case_or_candidate=case,
case_document_id=case_document_id,
)
for vc_ev in vc_evidences:
if not isinstance(vc_ev, dict):
continue
scope_ok = str(vc_ev.get('field_code') or vc_ev.get('source_kind') or '').strip()
line_key = vc_ev.get('line_key')
field_code = vc_ev.get('field_code')
# 反查 field_id:优先用 schema_fields key→field_code 匹配;找不到则安全跳过不伪造。
fid = None
for f_id, meta in schema_fields.items():
if isinstance(meta, dict) and str(meta.get('field_code') or '').strip() == str(field_code or '').strip():
fid = f_id
break
if not fid:
# 找不到 schema 映射的 VC 字段不注入,防止污染未定义字段。
continue
scope_meta = schema_fields.get(fid, {})
scope = 'header' if str(scope_meta.get('scope') or '').strip() == 'header' or (isinstance(scope_meta, dict) and line_key is None) else 'line'
if scope == 'line' and line_key is None:
line_key = 'header'
fv = _ensure_field(fid, scope=scope, line_key=None if scope == 'header' else str(line_key or 'header'))
fv['field_evidences'].append(vc_ev)
# finalize:选 primary + value_source 判定
for fv in header_fields.values():
_finalize_field_evidences(fv)
for lm in line_fields.values():
for fv in lm.values():
_finalize_field_evidences(fv)
return {
'case_id': case_id,
'document_id': case_document_id,
'case_no': str(getattr(case, 'case_no', '')),
'schema_version_id': schema_version_id,
'diagnostics': diagnostics,
'header_fields': header_fields,
'line_fields': line_fields,
'lines_order': lines_order,
'frozen_document': frozen_doc,
}
# ---------------------------------------------------------------------------
# 便捷工具:从视图中取 header 或某 line 的 field_view
# ---------------------------------------------------------------------------
def get_field_view(
view: dict[str, Any],
*,
field_id: str,
line_key: str | None,
) -> dict[str, Any] | None:
fid = str(field_id or '').strip()
if not fid:
return None
if line_key:
lk = str(line_key).strip()
line_map = view.get('line_fields') or {}
row = line_map.get(lk) or {}
return row.get(fid) or None
return (view.get('header_fields') or {}).get(fid)
def count_valid_row_fields(view: dict[str, Any], line_key: str) -> int:
"""
同行中“有值且可发送”的字段数量(evidence 有值或 machine_value/draft_value 非空)。
用于门禁:同行字段数 >= 2 才允许 L2_row。
"""
lk = str(line_key or '').strip()
line_map = (view.get('line_fields') or {}).get(lk) or {}
count = 0
for fv in line_map.values():
policy = fv.get('llm_context_policy') or 'forbidden'
if policy == 'forbidden':
continue
mv = fv.get('machine_value')
dv = fv.get('current_draft_value')
pe = fv.get('primary_evidence')
if (mv is not None and str(mv).strip() != '') or \
(dv is not None and str(dv).strip() != '') or \
(pe is not None and (str(pe.get('value') or '').strip() or str(pe.get('quote') or '').strip())):
count += 1
return count
@@ -34,6 +34,11 @@ from app.services.shipping_notice.pdf_priority_adjudication import (
is_primary_pdf_source_type,
)
from app.services.shipping_notice.progress_audit_contract import PDF_PRIORITY_EVIDENCE_RANKS
from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import (
collect_vc_candidate_conflicts,
)
_VC_CONFLICT_PREFIX = 'vc:'
def _conflict_key(*, field: str, line_index: Any) -> str:
@@ -197,22 +202,109 @@ def _field_id_for_code(case: ShippingOrderReviewCase, field_code: str, *, scope:
return None
def _project_vc_candidate_conflicts(
*,
case: ShippingOrderReviewCase,
candidate: ShippingOrderCandidate,
) -> list[dict[str, Any]]:
"""
将 Vendor Comments 三来源冲突项投影为与普通字段冲突兼容的工作台格式。
核心逻辑:
- conflict_key 加 vc: 前缀,避免与 line_index:field_code 格式冲突;
- 从 detail.sources 中提取候选来源值组装 options(含 vc_source_kind 标记);
- format_invalid / region_unbound 类冲突若仅有单一来源,则仍保留一项用于展示诊断。
"""
items: list[dict[str, Any]] = []
try:
vc_items = collect_vc_candidate_conflicts(candidate)
except Exception: # noqa: BLE001 — 投影层 fail-open:异常不影响其他冲突展示
return items
for vc in vc_items:
if not isinstance(vc, dict):
continue
field_code = str(vc.get('field_code') or '').strip()
if not field_code:
continue
scope_raw = str(vc.get('scope') or 'line').strip()
line_no_safe = vc.get('line_no')
try:
line_index = int(line_no_safe) - 1 if scope_raw != 'header' and line_no_safe not in (None, '') else -1
except (TypeError, ValueError):
line_index = -1
detail = vc.get('detail') if isinstance(vc.get('detail'), dict) else {}
sources = list(detail.get('sources') or []) if isinstance(detail.get('sources'), list) else []
options: list[dict[str, Any]] = []
seen: set[str] = set()
for src in sources:
if not isinstance(src, dict):
continue
vp = src.get('value_preview')
if vp in (None, ''):
continue
key = str(vp).strip()
if key in seen:
continue
seen.add(key)
source_kind = str(src.get('source') or '').strip()
source_label = str(src.get('source_label') or source_kind).strip()
options.append({
'value_key': key,
'display_value': vp,
'sources': [source_label] if source_label else [],
'source_type': None,
'source_types': [source_kind] if source_kind else [],
'evidence_role': 'auxiliary',
'evidence_rank': None,
'vc_source_kind': source_kind,
'vc_source_kind_label': source_label,
'evidence_ref': src.get('evidence_ref'),
})
# 对于 format_invalid / region_unbound 类诊断,即使无多选值也继续投影,便于工作台展示原因。
cg_key = str(vc.get('conflict_group_key') or '').strip()
conflict_key = _VC_CONFLICT_PREFIX + (cg_key or f'{scope_raw}:{field_code}:{line_no_safe or "_"}')
line_key = vc.get('line_key') if scope_raw != 'header' else (
_line_key_for_index(case, line_index) if line_index >= 0 else None
)
items.append({
'conflict_key': conflict_key,
'field_code': field_code,
'line_index': line_index if line_index >= 0 else None,
'line_key': line_key,
'severity': str(vc.get('severity') or 'blocking'),
'reason': str(vc.get('reason') or 'vc_source_conflict_unresolved'),
'options': options,
'observation_ids': [],
'vc_kind': True,
'vc_reason': str(vc.get('reason') or ''),
'vc_conflict_group_key': cg_key or None,
'vc_detail': {
'resolution': detail.get('resolution'),
'decision_status': detail.get('decision_status'),
'format_valid': detail.get('format_valid'),
},
})
return items
def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[dict[str, Any]]:
"""
投影建单前仍未裁决的字段冲突,供复核工作台集中展示。
合并两类冲突:
1. 传统 Observation/Adjudication 字段冲突(来自 candidate.conflicts_json);
2. Vendor Comments 三来源冲突(collect_vc_candidate_conflicts 动态产出,vc_kind=True)。
Returns:
冲突列表;每项含 conflict_key、field_code、line_index、options、reason。
"""
candidate = _candidate_for_case(case)
if candidate is None:
return []
projected: list[dict[str, Any]] = []
raw_conflicts = list(candidate.conflicts_json or [])
if not raw_conflicts:
return []
adjudication = _adjudication_blob(candidate)
observations = _observations_index(adjudication)
projected: list[dict[str, Any]] = []
for item in raw_conflicts:
if not isinstance(item, dict):
continue
@@ -250,9 +342,60 @@ def project_review_case_field_conflicts(case: ShippingOrderReviewCase) -> list[d
'options': options,
'observation_ids': observation_ids,
})
projected.extend(_project_vc_candidate_conflicts(case=case, candidate=candidate))
return projected
def _resolve_vc_candidate_decision(
*,
candidate: ShippingOrderCandidate,
conflict_group_key: str,
chosen_value: Any,
) -> None:
"""
在 Vendor Comments merged_candidates 快照中标记对应项为人工裁决接受。
核心逻辑:定位 conflict_group_key 匹配的 merged_candidate →
覆写 decision_status=accepted / resolution=manual_review / accepted_value=chosen_value →
后续 collect_vc_candidate_conflicts 将自动跳过该项(resolution!=needs_review 或 decision=accepted/dropped)。
"""
from datetime import datetime # noqa: PLC0415 — 延迟 import 避免模块级循环依赖
structured = dict(candidate.structured_result_json or {})
extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {}
vc_merged = extraction.get('vendor_comments_merged')
if not isinstance(vc_merged, dict):
return
merged_list = vc_merged.get('merged_candidates')
if not isinstance(merged_list, list):
return
updated_list: list[dict[str, Any]] = []
for cand in merged_list:
if not isinstance(cand, dict):
updated_list.append(cand)
continue
field_code = str(cand.get('target_field_code') or cand.get('field_code') or '').strip()
scope = str(cand.get('target_scope') or cand.get('scope') or 'line').strip()
scope_ok = 'header' if scope == 'header' else 'line'
line_no_raw = cand.get('effective_line_no') or cand.get('line_no')
line_no_safe = None if line_no_raw is None else str(line_no_raw)
safe_line = str(line_no_safe or '').strip() or '_'
ckey = f'{scope_ok}:{field_code}:{safe_line}'
if ckey == str(conflict_group_key or '').strip():
cand = {
**cand,
'decision_status': 'accepted',
'resolution': 'manual_review',
'accepted_value': chosen_value,
'manual_resolved_at': datetime.utcnow().isoformat(),
}
updated_list.append(cand)
vc_merged['merged_candidates'] = updated_list
extraction['vendor_comments_merged'] = vc_merged
structured['extraction'] = extraction
candidate.structured_result_json = structured
def resolve_review_case_field_conflict(
*,
user_id: int,
@@ -267,6 +410,11 @@ def resolve_review_case_field_conflict(
"""
裁决建单前字段冲突:写入 Draft 值、清除 Candidate 冲突项、重校验资格。
支持两类 conflict_key:
- 传统格式(line_index:field_code):从 candidate.conflicts_json 删除匹配项并写回 adjudication;
- vc: 前缀格式(Vendor Comments 三来源冲突):定位 conflict_group_key,
覆写 merged_candidates.decision_status=accepted,后续门禁自动放行。
Args:
resolution: adopt_option | custom
option_index: adopt_option 时选用 options[i]
@@ -277,6 +425,8 @@ def resolve_review_case_field_conflict(
Returns:
{'case': 最新 Case 投影, 'field_conflicts': 剩余冲突列表}。
"""
from datetime import datetime # noqa: PLC0415 — 延迟 import 避免模块级循环依赖
action = 'field_conflict_resolved'
case = _locked_case(user_id=user_id, case_no=case_no, action=action)
_assert_version(case, expected_draft_version, actor_id=user_id, action=action)
@@ -286,61 +436,171 @@ def resolve_review_case_field_conflict(
'Review case has no candidate for field conflict resolution',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
)
conflicts = list(candidate.conflicts_json or [])
target_idx = -1
target: dict[str, Any] | None = None
for idx, item in enumerate(conflicts):
if not isinstance(item, dict):
continue
key = _conflict_key(field=item.get('field'), line_index=item.get('line_index'))
if key == str(conflict_key or '').strip():
target_idx = idx
target = item
break
if target is None or target_idx < 0:
raise NotFoundError(
'Field conflict not found',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
details={'conflict_key': conflict_key},
)
field_code = str(target.get('field') or '').strip()
try:
line_index = int(target.get('line_index')) if target.get('line_index') is not None else -1
except (TypeError, ValueError):
line_index = -1
value_keys = [str(v) for v in (target.get('values') or []) if v not in (None, '')]
mode = str(resolution or '').strip().lower()
raw_key = str(conflict_key or '').strip()
is_vc_conflict = raw_key.startswith(_VC_CONFLICT_PREFIX)
field_code = ''
line_index = -1
chosen_display: Any = None
if mode == 'adopt_option':
if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_keys):
raise ValidationError(
'option_index is required for adopt_option',
code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID',
)
observations = _observations_index(_adjudication_blob(candidate))
option = _option_display(
field=field_code,
value_key=value_keys[int(option_index)],
observation_ids=[str(oid) for oid in (target.get('observation_ids') or []) if oid],
observations=observations,
)
chosen_display = option.get('display_value')
elif mode == 'custom':
if custom_value in (None, ''):
raise ValidationError(
'custom_value is required',
code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED',
)
chosen_display = custom_value
else:
raise ValidationError(
'Invalid conflict resolution',
code='SHIPPING.INVALID_CONFLICT_RESOLUTION',
details={'resolution': resolution},
)
mode = str(resolution or '').strip().lower()
# [STEP 1] 写入 Draft 人工值。
if is_vc_conflict:
vc_group_key = raw_key[len(_VC_CONFLICT_PREFIX):]
try:
vc_items = collect_vc_candidate_conflicts(candidate)
except Exception as exc: # noqa: BLE001
raise NotFoundError(
'VC conflict not accessible',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
details={'conflict_key': conflict_key},
) from exc
target_vc: dict[str, Any] | None = None
for vc in vc_items:
if not isinstance(vc, dict):
continue
scope_raw = str(vc.get('scope') or 'line').strip()
scope_ok = 'header' if scope_raw == 'header' else 'line'
line_no_safe = vc.get('line_no')
safe_line = str(line_no_safe or '').strip() or '_'
fcode = str(vc.get('field_code') or '').strip()
ckey = f'{scope_ok}:{fcode}:{safe_line}'
want_cg = str(vc.get('conflict_group_key') or ckey).strip()
if want_cg == vc_group_key:
target_vc = vc
field_code = fcode
if scope_ok != 'header' and line_no_safe not in (None, ''):
try:
line_index = int(line_no_safe) - 1
except (TypeError, ValueError):
line_index = -1
break
if target_vc is None:
raise NotFoundError(
'VC conflict not found',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
details={'conflict_key': conflict_key},
)
detail = target_vc.get('detail') if isinstance(target_vc.get('detail'), dict) else {}
sources = list(detail.get('sources') or []) if isinstance(detail.get('sources'), list) else []
value_options: list[tuple[str, Any]] = []
seen: set[str] = set()
for src in sources:
if not isinstance(src, dict):
continue
vp = src.get('value_preview')
if vp in (None, ''):
continue
k = str(vp).strip()
if k in seen:
continue
seen.add(k)
value_options.append((k, vp))
if mode == 'adopt_option':
if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_options):
raise ValidationError(
'option_index is required for adopt_option',
code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID',
)
chosen_display = value_options[int(option_index)][1]
elif mode == 'custom':
if custom_value in (None, ''):
raise ValidationError(
'custom_value is required',
code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED',
)
chosen_display = custom_value
else:
raise ValidationError(
'Invalid conflict resolution',
code='SHIPPING.INVALID_CONFLICT_RESOLUTION',
details={'resolution': resolution},
)
else:
conflicts = list(candidate.conflicts_json or [])
target_idx = -1
target: dict[str, Any] | None = None
for idx, item in enumerate(conflicts):
if not isinstance(item, dict):
continue
key = _conflict_key(field=item.get('field'), line_index=item.get('line_index'))
if key == raw_key:
target_idx = idx
target = item
break
if target is None or target_idx < 0:
raise NotFoundError(
'Field conflict not found',
code='SHIPPING.REVIEW_FIELD_CONFLICT_NOT_FOUND',
details={'conflict_key': conflict_key},
)
field_code = str(target.get('field') or '').strip()
try:
line_index = int(target.get('line_index')) if target.get('line_index') is not None else -1
except (TypeError, ValueError):
line_index = -1
value_keys = [str(v) for v in (target.get('values') or []) if v not in (None, '')]
if mode == 'adopt_option':
if option_index is None or int(option_index) < 0 or int(option_index) >= len(value_keys):
raise ValidationError(
'option_index is required for adopt_option',
code='SHIPPING.REVIEW_FIELD_CONFLICT_OPTION_INVALID',
)
observations = _observations_index(_adjudication_blob(candidate))
option = _option_display(
field=field_code,
value_key=value_keys[int(option_index)],
observation_ids=[str(oid) for oid in (target.get('observation_ids') or []) if oid],
observations=observations,
)
chosen_display = option.get('display_value')
elif mode == 'custom':
if custom_value in (None, ''):
raise ValidationError(
'custom_value is required',
code='SHIPPING.REVIEW_FIELD_CONFLICT_VALUE_REQUIRED',
)
chosen_display = custom_value
else:
raise ValidationError(
'Invalid conflict resolution',
code='SHIPPING.INVALID_CONFLICT_RESOLUTION',
details={'resolution': resolution},
)
conflicts.pop(target_idx)
candidate.conflicts_json = conflicts
structured = dict(candidate.structured_result_json or {})
extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {}
adjudication = dict(extraction.get('field_adjudication') or {}) if isinstance(extraction.get('field_adjudication'), dict) else {}
decisions = list(adjudication.get('decisions') or [])
updated_decisions = []
for decision in decisions:
if not isinstance(decision, dict):
continue
same_field = str(decision.get('field') or '') == field_code
same_line = True
if line_index >= 0:
try:
same_line = int(decision.get('line_index')) == line_index
except (TypeError, ValueError):
same_line = False
if same_field and same_line:
updated_decisions.append({
**decision,
'status': 'selected',
'value': chosen_display,
'resolution_method': 'manual_review',
})
else:
updated_decisions.append(decision)
adjudication['decisions'] = updated_decisions
adjudication['conflicts'] = list(conflicts)
extraction['field_adjudication'] = adjudication
structured['extraction'] = extraction
candidate.structured_result_json = structured
db.session.flush()
# [STEP 1] 写入 Draft 人工值(两条路径共享)。
scope = 'line' if line_index >= 0 else 'header'
field_id = _field_id_for_code(case, field_code, scope=scope)
if not field_id:
@@ -379,39 +639,15 @@ def resolve_review_case_field_conflict(
change = _set_value(target_line, field, chosen_display, restore_machine=False)
case.current_draft.lines_json = lines
# [STEP 2] 清除 Candidate 冲突项,并同步 adjudication decision。
conflicts.pop(target_idx)
candidate.conflicts_json = conflicts
structured = dict(candidate.structured_result_json or {})
extraction = dict(structured.get('extraction') or {}) if isinstance(structured.get('extraction'), dict) else {}
adjudication = dict(extraction.get('field_adjudication') or {}) if isinstance(extraction.get('field_adjudication'), dict) else {}
decisions = list(adjudication.get('decisions') or [])
updated_decisions = []
for decision in decisions:
if not isinstance(decision, dict):
continue
same_field = str(decision.get('field') or '') == field_code
same_line = True
if line_index >= 0:
try:
same_line = int(decision.get('line_index')) == line_index
except (TypeError, ValueError):
same_line = False
if same_field and same_line:
updated_decisions.append({
**decision,
'status': 'selected',
'value': chosen_display,
'resolution_method': 'manual_review',
})
else:
updated_decisions.append(decision)
adjudication['decisions'] = updated_decisions
adjudication['conflicts'] = list(conflicts)
extraction['field_adjudication'] = adjudication
structured['extraction'] = extraction
candidate.structured_result_json = structured
db.session.flush()
# [STEP 2] 按冲突类型分别处理 conflict_group_key 回写,并 flush。
if is_vc_conflict:
_resolve_vc_candidate_decision(
candidate=candidate,
conflict_group_key=raw_key[len(_VC_CONFLICT_PREFIX):],
chosen_value=chosen_display,
)
db.session.flush()
# 非 VC 分支:conflicts 删除 + adjudication decisions 更新已在上半段完成并 flush。
# [STEP 3] 重算资格并写审计;由路由层 commit。
customer_resolved = resolve_review_case_customer_resolved(case=case, candidate=candidate)
@@ -25,12 +25,17 @@ from app.models import (
ShippingOrderReviewWaveLine,
ShippingNotice,
)
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
from app.services.shipping_notice.workflow_ledger_service import (
assert_case_is_current_workflow_version,
)
def _get_soft_loader():
"""延迟导入 soft_load_review_case_for_audit,解开 job_registry → draft_service 循环依赖链。"""
from app.services.shipping_notice.order_review_draft_service import soft_load_review_case_for_audit
return soft_load_review_case_for_audit
DECISION_WAIT = 'wait_inventory'
DECISION_FULFILL = 'fulfill_complete_line_now'
DECISION_CLOSE = 'close_unfulfillable'
@@ -61,7 +66,8 @@ _TERMINAL_ACTIVE = frozenset({'task_created', 'fulfilled', 'closed_unfulfillable
def _load_writable_case(*, user_id: int, case_no: str) -> ShippingOrderReviewCase:
"""加载属主可写 Case(含部分波次后仍有开放行的 ready Case)。"""
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no or ''))
soft_load = _get_soft_loader()
case = soft_load(user_id=int(user_id), case_no=str(case_no or ''))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
status = str(case.status or '')
@@ -387,6 +393,48 @@ def project_review_case_line_decisions(
schema_fields = _normalize_schema_fields_map(schema_fields) or schema_fields_from_case(case)
formal_ot = resolve_formal_ot(case)
has_formal_ot = bool(formal_ot.get('has_formal_ot'))
task = formal_ot.get('task') if isinstance(formal_ot.get('task'), ShippingNotice) else None
# [STEP] 构造 Task 级库存源回退事实(行级匹配缺失时兜底,仅影响展示)
# 优先级:行级 inventory_source_code > Task resolved/user_confirmed 正式源 > candidates_frozen > resolving
from app.services.shipping_notice.stp_inventory_freeze import (
task_frozen_inventory_source_codes,
)
fallback_inventory_source: dict[str, Any] | None = None
if task is not None:
task_source_code = str(task.inventory_source_code or '').strip().upper() or None
task_source_status = str(task.inventory_source_status or '').strip()
if task_source_code and task_source_status in {'resolved', 'user_confirmed'}:
fallback_inventory_source = {
'code': task_source_code,
'label': None,
'status': 'resolved',
'source': 'task_inventory_source',
}
elif task_source_status == 'candidates_frozen':
frozen_codes = task_frozen_inventory_source_codes(task)
if frozen_codes:
fallback_inventory_source = {
'code': None,
'label': None,
'status': 'candidates_frozen',
'candidates': list(frozen_codes),
'source': 'frozen_inventory_candidates',
}
else:
fallback_inventory_source = {
'code': None,
'label': None,
'status': 'resolving',
'source': 'inventory_source_clue',
}
else:
fallback_inventory_source = {
'code': None,
'label': None,
'status': 'resolving',
'source': 'inventory_source_clue',
}
match_facts = load_current_match_facts_by_task(formal_ot.get('task_id'))
labels = dict(source_labels or {})
if not labels:
@@ -460,6 +508,7 @@ def project_review_case_line_decisions(
auto_fulfill_error_message=auto_err,
inventory_rpa_running=bool(inventory_rpa_running),
source_labels=labels,
fallback_inventory_source=fallback_inventory_source,
)
# [STEP] OT 后数量以匹配事实投影覆盖(含 not_found→0 / result_missing→null)
if has_formal_ot:
@@ -761,7 +810,7 @@ def decide_review_line_fulfillment(
skip_validate=False,
allow_auto_create=False,
)
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no))
case = _get_soft_loader()(user_id=int(user_id), case_no=str(case_no))
payload = {
'decision': _serialize_decision(row),
'line_fulfillment': project_review_case_line_decisions(case),
@@ -818,7 +867,7 @@ def create_fulfillment_wave(
case_no=str(case_no),
expected_draft_version=expected_draft_version,
)
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no or ''))
case = _get_soft_loader()(user_id=int(user_id), case_no=str(case_no or ''))
if case is None:
raise NotFoundError('Review case not found', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
@@ -875,7 +924,7 @@ def create_fulfillment_wave(
# [STEP 2] 标记决定为 task_created
from sqlalchemy import func
case = soft_load_review_case_for_audit(user_id=int(user_id), case_no=str(case_no))
case = _get_soft_loader()(user_id=int(user_id), case_no=str(case_no))
# [STEP] 以本波次返回的 task_no 为准,避免多波次时 case.confirmed_task_id 竞态误绑。
task_id = None
task_no = str((result or {}).get('task_no') or '').strip()
@@ -0,0 +1,381 @@
"""
services/shipping_notice/order_review_llm_auto_upgrade.py
用途:LLM 证据等级自动升级引擎(Phase 2)。基于证据视图检测 7 项歧义/冲突信号,
按优先级把默认 L2_row 升级到 L3_table(Header 冲突升级到 L4_page)。
依赖:
- order_review_evidence_view:get_field_view / count_valid_row_fields / lines_order
- order_review_llm_contract:EvidenceLevelV2、证据等级与错误码常量
- order_review_llm_policy_registry:llm_context_policy 判定 target_only
逻辑:
[1] 7 项优先级降序检测,命中多条只取最高优先级写入 auto_upgrade_reason,
完整列表写入 auto_upgrade_reasons。
[2] Header scope 命中任何升级信号 → 升级到 L4_page;Line scope → L3_table。
[3] schema.target_only=true 的字段强制 L1_field,即使命中升级信号也跳过。
[4] 升级后新等级仍须走前门禁(selector 构建完 pack 再二次门 target_core_trimmed),
升级引擎只负责等级,不负责越权通过门禁。
"""
from __future__ import annotations
from typing import Any, Final, Literal
from app.services.shipping_notice.order_review_llm_contract import (
EvidenceLevelV2,
)
from app.services.shipping_notice.order_review_evidence_view import (
count_valid_row_fields,
get_field_view,
)
from app.services.shipping_notice.order_review_llm_policy_registry import (
resolve_llm_context_policy,
)
# ---------------------------------------------------------------------------
# 7 项升级依据(优先级数字越小越先命中)
# ---------------------------------------------------------------------------
_UPGRADE_REASON_PRIORITY: Final[dict[str, int]] = {
'issue_FIELD_CONFLICT': 1,
'draft_field_conflict': 2,
'multi_source_ambiguous': 3,
'table_duplicate_value': 4,
'manual_conflict': 5,
'context_borderline': 6,
'context_identity_insufficient': 7,
}
UPGRADE_REASON_ORDER: Final[list[str]] = sorted(
_UPGRADE_REASON_PRIORITY.keys(),
key=lambda r: _UPGRADE_REASON_PRIORITY[r],
)
_MIN_ROW_IDENTITY_CONFIDENCE: Final[float] = 0.6
_BORDERLINE_SIBLING_COUNT: Final[int] = 2
_LINE_IDENTITY_FIELD_CODES: Final[frozenset[str]] = frozenset({
'part_number', 'part_number_formatted', 'part_no', 'material_code',
'sku', 'line_no', 'line_number', 'po_line', 'po_line_no',
'item', 'item_no', 'item_code', 'product_code',
})
UpgradeResult = tuple[
EvidenceLevelV2, # final_level
str | None, # auto_upgrade_reason(最高优先级)
list[str], # auto_upgrade_reasons(完整命中列表,按优先级排)
]
def _text_eq_normalized(a: Any, b: Any) -> bool:
"""空白折叠 + trim + 大小写不敏感比较;None/'' 视为相等。"""
def n(v: Any) -> str:
if v is None:
return ''
import re
return re.sub(r'\s+', ' ', str(v)).strip().lower()
return n(a) == n(b)
def _schema_field_target_only(
field_view: dict[str, Any],
schema_field_meta: dict[str, Any] | None,
) -> bool:
"""
判定字段是否属于 target_only(强制 L1_field,不允许上下文污染)。
优先读 schema_field_meta.target_only;缺失时用 llm_context_policy。
"""
if isinstance(schema_field_meta, dict):
to = schema_field_meta.get('target_only')
if isinstance(to, bool):
return to
policy_raw = schema_field_meta.get('llm_context_policy')
if isinstance(policy_raw, str) and policy_raw.strip().lower() == 'target_only':
return True
policy = field_view.get('llm_context_policy') if isinstance(field_view, dict) else None
return isinstance(policy, str) and policy.strip().lower() == 'target_only'
# ---------------------------------------------------------------------------
# 单项检测函数
# ---------------------------------------------------------------------------
def _check_issue_field_conflict(issue_code: str | None) -> bool:
"""
[Priority 1] issue_code 属于字段冲突类。
匹配规则:以 FIELD_CONFLICT 结尾,或含 _FIELD_CONFLICT_ 子串。
"""
if not issue_code:
return False
code = str(issue_code).strip().upper()
return code.endswith('FIELD_CONFLICT') or '_FIELD_CONFLICT_' in code
def _check_draft_field_conflict(field_view: dict[str, Any]) -> bool:
"""
[Priority 2] evidence_view.value_source = manual_override。
用户手工值与 machine 识别值不一致,需要更大上下文供 LLM 判定。
"""
if not isinstance(field_view, dict):
return False
return str(field_view.get('value_source') or '') == 'manual_override'
def _check_multi_source_ambiguous(field_view: dict[str, Any]) -> bool:
"""
[Priority 3] field_evidences 有多条,且归一化后 value 不唯一。
空 evidences 由门禁拦截;单条证据不可能歧义。
"""
if not isinstance(field_view, dict):
return False
evs = field_view.get('field_evidences') or []
if not isinstance(evs, list) or len(evs) < 2:
return False
seen: set[str] = set()
for ev in evs:
if not isinstance(ev, dict):
continue
value = ev.get('value')
if value is None:
continue
import re
norm = re.sub(r'\s+', ' ', str(value)).strip().lower()
if not norm:
continue
seen.add(norm)
return len(seen) > 1
def _check_table_duplicate_value(
evidence_view: dict[str, Any],
*,
field_id: str,
line_key: str | None,
field_view_obj: dict[str, Any],
) -> bool:
"""
[Priority 4] Line scope:同一 table 中多个行存在与目标字段相同的 value。
Header scope:此检测跳过(不适用)。目标 value 为空时跳过。
"""
if not line_key:
return False
if not isinstance(evidence_view, dict):
return False
target_pe = field_view_obj.get('primary_evidence') if isinstance(field_view_obj, dict) else {}
if not isinstance(target_pe, dict):
return False
target_value = target_pe.get('value')
if target_value is None or (isinstance(target_value, str) and not target_value.strip()):
return False
target_table_id = target_pe.get('table_id')
target_doc = target_pe.get('document_id')
line_fields = evidence_view.get('line_fields') or {}
if not isinstance(line_fields, dict):
return False
same_table_hits = 0
for lk, lf_map in line_fields.items():
if lk == str(line_key) or not isinstance(lf_map, dict):
continue
fv = lf_map.get(str(field_id))
if not isinstance(fv, dict):
continue
pe = fv.get('primary_evidence')
if not isinstance(pe, dict):
continue
if target_doc is not None and pe.get('document_id') != target_doc:
continue
if target_table_id and pe.get('table_id') != target_table_id:
continue
if _text_eq_normalized(pe.get('value'), target_value):
same_table_hits += 1
if same_table_hits >= 1:
return True
return False
def _check_manual_conflict(field_view: dict[str, Any]) -> bool:
"""
[Priority 5] 与 P2 同源的机器 vs 手工冲突,但此处独立保留原因编码,
以便后续审计时区分「用户明确改的」和「Draft 回填遗留的」。
命中条件:value_source in (manual_override, manual_only) 且 primary_evidence 存在。
"""
if not isinstance(field_view, dict):
return False
vs = str(field_view.get('value_source') or '')
if vs not in {'manual_override', 'manual_only'}:
return False
pe = field_view.get('primary_evidence')
return isinstance(pe, dict) and bool(pe)
def _check_context_borderline(
evidence_view: dict[str, Any],
*,
line_key: str | None,
) -> bool:
"""
[Priority 6] Line scope 同行有效字段数正好 = 门禁最低阈值(2)。
处于门禁临界线,证据不稳,升级到表格更安全。Header scope 跳过。
"""
if not line_key:
return False
try:
siblings = count_valid_row_fields(evidence_view, str(line_key))
except Exception:
return False
return siblings == _BORDERLINE_SIBLING_COUNT
def _check_context_identity_insufficient(
evidence_view: dict[str, Any],
*,
line_key: str | None,
field_view_obj: dict[str, Any],
) -> bool:
"""
[Priority 7] Line scope:同行缺少明确身份标识字段(如 part_number / line_no),
或目标字段 primary_evidence.confidence 低于阈值。
"""
if not line_key:
return False
if not isinstance(evidence_view, dict):
return False
# 身份标识检测
line_fields = evidence_view.get('line_fields') or {}
lf = line_fields.get(str(line_key)) if isinstance(line_fields, dict) else None
has_identity = False
if isinstance(lf, dict):
for fid, fv in lf.items():
if not isinstance(fv, dict):
continue
code = str(fv.get('field_code') or fid or '').lower().replace('_', '-')
if code in _LINE_IDENTITY_FIELD_CODES:
pe = fv.get('primary_evidence')
if isinstance(pe, dict) and pe.get('value') not in (None, ''):
try:
conf = float(pe.get('confidence') or 0.0)
except (TypeError, ValueError):
conf = 0.0
if conf >= _MIN_ROW_IDENTITY_CONFIDENCE:
has_identity = True
break
if not has_identity:
return True
# 目标字段信心度兜底
if isinstance(field_view_obj, dict):
pe = field_view_obj.get('primary_evidence') or {}
if isinstance(pe, dict):
try:
conf = float(pe.get('confidence') or 0.0)
except (TypeError, ValueError):
conf = 0.0
if 0.0 < conf < _MIN_ROW_IDENTITY_CONFIDENCE:
return True
return False
# ---------------------------------------------------------------------------
# 对外主入口
# ---------------------------------------------------------------------------
def resolve_auto_upgrade_level(
*,
evidence_view: dict[str, Any],
field_id: str,
line_key: str | None,
requested_level: EvidenceLevelV2,
schema_field_meta: dict[str, Any] | None = None,
issue_code: str | None = None,
) -> UpgradeResult:
"""
根据证据视图与请求元数据,决定最终证据等级。
Args:
evidence_view: build_review_evidence_view() 的返回。
field_id: 目标字段 ID。
line_key: 目标行键;None 表示 header scope。
requested_level: 用户/前端请求的等级(默认 L2_row)。
schema_field_meta: schema.definition_json.fields[] 中的原始元数据。
issue_code: 前端透传的冲突 issue_code(触发 P1)。
Returns:
(final_level, auto_upgrade_reason, auto_upgrade_reasons)
final_level ∈ L1_field/L2_row/L3_table/L4_page;target_only 强制 L1。
auto_upgrade_reason 为最高优先级原因;未升级返回 None。
auto_upgrade_reasons 为全部命中原因,按优先级排序。
"""
if not isinstance(evidence_view, dict):
return requested_level, None, []
field_view = get_field_view(evidence_view, field_id=field_id, line_key=line_key)
if field_view is None:
return requested_level, None, []
# [红线 target_only] 强制 L1_field,禁止升级,不污染上下文
if _schema_field_target_only(field_view, schema_field_meta):
return 'L1_field', None, []
# 用户/前端已经显式请求超过 L2 的等级 → 不降级,也不额外追加 auto_upgrade_reason
if str(requested_level) not in {'L1_field', 'L2_row'}:
return requested_level, None, []
scope_is_line = bool(line_key)
reasons_hit: list[str] = []
# [STEP 1] 按优先级顺序跑 7 项检测,命中即追加
if _check_issue_field_conflict(issue_code):
reasons_hit.append('issue_FIELD_CONFLICT')
if _check_draft_field_conflict(field_view):
reasons_hit.append('draft_field_conflict')
if _check_multi_source_ambiguous(field_view):
reasons_hit.append('multi_source_ambiguous')
if _check_table_duplicate_value(
evidence_view,
field_id=field_id,
line_key=line_key,
field_view_obj=field_view,
):
reasons_hit.append('table_duplicate_value')
if _check_manual_conflict(field_view):
reasons_hit.append('manual_conflict')
if _check_context_borderline(evidence_view, line_key=line_key):
reasons_hit.append('context_borderline')
if _check_context_identity_insufficient(
evidence_view,
line_key=line_key,
field_view_obj=field_view,
):
reasons_hit.append('context_identity_insufficient')
if not reasons_hit:
return requested_level, None, []
# [STEP 2] 去重 + 按全局优先级稳定排序
deduped: list[str] = []
seen: set[str] = set()
for r in UPGRADE_REASON_ORDER:
if r in reasons_hit and r not in seen:
deduped.append(r)
seen.add(r)
top_reason = deduped[0]
# [STEP 3] 依据 scope 升级:Header → L4_page;Line → L3_table
if scope_is_line:
final_level: EvidenceLevelV2 = 'L3_table'
else:
final_level = 'L4_page'
# 二次兜底:调用方显式传 L1_field 且非 L2 默认,不自动升级(尊重显式最小证据)
if str(requested_level) == 'L1_field' and not reasons_hit:
final_level = 'L1_field'
return final_level, top_reason, deduped
def describe_upgrade_reason(reason: str | None) -> str:
"""返回原因代码的人类可读摘要(用于审计 metadata,不写入 error_message,i18n 交给前端)。"""
if reason is None:
return ''
return {
'issue_FIELD_CONFLICT': 'issue_code 指示字段冲突',
'draft_field_conflict': '草稿手工覆盖值与机器识别不一致',
'multi_source_ambiguous': '多来源观察值存在冲突(归一化后不唯一)',
'table_duplicate_value': '同表多行存在相同目标值(行身份歧义)',
'manual_conflict': '存在人工干预值(manual_only / manual_override)',
'context_borderline': '同行字段数处于门禁临界线(阈值=2)',
'context_identity_insufficient': '同行缺少高置信度行身份标识字段',
}.get(reason, str(reason))
@@ -1,53 +1,216 @@
"""
services/shipping_notice/order_review_llm_contract.py
用途:冻结订单复核 Dify 最小证据建议的 JSON 契约与证据等级。
依赖:无外部 I/O;被 evidence_selector / llm_service / validation 引用。
逻辑:L1–L3 为默认升级路径;L4 整份 PDF 默认禁止,仅管理员显式触发且仍不得自动冻结。
用途:冻结订单复核 Dify 最小证据建议的 JSON 契约、证据等级、状态枚举。
依赖:无外部 I/O;被 evidence_selector / llm_service / validation / gate / auto_upgrade 引用。
逻辑:
- v1 契约保留原语义,用于历史记录解释;v2 新请求只生成新枚举。
- L1–L5 为 v2 等级;旧 L2_table/L3_page/L4_pdf 留在枚举里但 v2 代码不再生成。
- evidence_ref/provenance_ref 两种引用严格区分;layout: 前缀缺任意必需段即为无效证据。
- 信封 v2 采用 target/context/evidence/constraints/expected_output 稳定结构。
"""
from __future__ import annotations
from typing import Any, Final, Literal
import hashlib
import json
import re
from typing import Any, Final, Literal, TypedDict
LLM_REVIEW_CONTRACT_VERSION: Final[str] = 'order-review-llm.v1'
# ---------------------------------------------------------------------------
# 版本
# ---------------------------------------------------------------------------
LLM_REVIEW_CONTRACT_VERSION_V1: Final[str] = 'order-review-llm.v1'
LLM_REVIEW_CONTRACT_VERSION_V2: Final[str] = 'order-review-llm.v2'
LLM_REVIEW_CONTRACT_VERSION: Final[str] = LLM_REVIEW_CONTRACT_VERSION_V2
EvidenceLevel = Literal['L1_field', 'L2_table', 'L3_page', 'L4_pdf']
EVIDENCE_LEVELS: Final[frozenset[str]] = frozenset({
'L1_field', 'L2_table', 'L3_page', 'L4_pdf',
# ---------------------------------------------------------------------------
# 证据等级(v1 与 v2 合并共存,旧值语义不漂移;v2 默认 L2_row)
# ---------------------------------------------------------------------------
EvidenceLevelV1 = Literal['L1_field', 'L2_table', 'L3_page', 'L4_pdf']
EvidenceLevelV2 = Literal['L1_field', 'L2_row', 'L3_table', 'L4_page', 'L5_document']
EvidenceLevel = Literal[
'L1_field',
'L2_table', # v1 legacy:旧版表头/行数上下文
'L3_page', # v1 legacy:旧版页面纯文本块
'L4_pdf', # v1 legacy:旧版整份 PDF 授权
'L2_row', # v2 默认:目标字段 + 同行所有允许字段
'L3_table', # v2:表头 + 目标行 + 前后各 2 行
'L4_page', # v2:目标表所在页面结构化摘要
'L5_document' # v2:理论保留,永不开放
]
EVIDENCE_LEVELS_V2_ALLOWED: Final[frozenset[str]] = frozenset({
'L1_field', 'L2_row', 'L3_table', 'L4_page', 'L5_document',
})
EVIDENCE_LEVELS_ALL: Final[frozenset[str]] = frozenset({
'L1_field', 'L2_table', 'L3_page', 'L4_pdf',
'L2_row', 'L3_table', 'L4_page', 'L5_document',
})
DEFAULT_V2_EVIDENCE_LEVEL: Final[EvidenceLevelV2] = 'L2_row'
DEFAULT_MAX_EVIDENCE_LEVEL: Final[EvidenceLevel] = 'L3_page'
L4_FULL_PDF_ALLOWED_BY_DEFAULT: Final[bool] = False
# ---------------------------------------------------------------------------
# Suggestion 状态(新增 gated_failed;其余保留 v1 语义)
# ---------------------------------------------------------------------------
SuggestionStatus = Literal[
'pending',
'gated_failed', # 新增:HXOPS 本地前门禁失败,Dify 未被调用
'validated',
'validation_failed',
'accepted',
'modified',
'rejected',
'failed',
'provider_unavailable',
]
SUGGESTION_STATUSES_ALL: Final[frozenset[str]] = frozenset({
'pending', 'gated_failed', 'validated', 'validation_failed',
'accepted', 'modified', 'rejected', 'failed', 'provider_unavailable',
})
SuggestionDecision = Literal['pending', 'accepted', 'modified', 'rejected']
SUGGESTION_DECISIONS: Final[frozenset[str]] = frozenset({
'pending', 'accepted', 'modified', 'rejected',
})
# ---------------------------------------------------------------------------
# 错误码契约(与四语言 locales/*/errors.json 对齐)
# ---------------------------------------------------------------------------
GATE_ERROR_CODES: Final[frozenset[str]] = frozenset({
'SHIPPING.REVIEW_LLM_FIELD_NOT_FOUND',
'SHIPPING.REVIEW_LLM_LINE_NOT_FOUND',
'SHIPPING.REVIEW_LLM_FIELD_VALUE_MISSING',
'SHIPPING.REVIEW_LLM_EVIDENCE_UNAVAILABLE',
'SHIPPING.REVIEW_LLM_CONTEXT_INSUFFICIENT',
'SHIPPING.REVIEW_LLM_EVIDENCE_POLICY_BLOCKED',
'SHIPPING.REVIEW_LLM_CONTEXT_BUILD_FAILED',
'SHIPPING.REVIEW_LLM_EVIDENCE_TRUNCATED',
'SHIPPING.REVIEW_LLM_CONTEXT_AMBIGUOUS',
'SHIPPING.REVIEW_LLM_L4_FORBIDDEN',
})
LEGACY_ERROR_CODES: Final[frozenset[str]] = frozenset({
'SHIPPING.REVIEW_LLM_DISABLED',
'SHIPPING.REVIEW_LLM_PROVIDER_UNAVAILABLE',
'SHIPPING.REVIEW_LLM_FIELD_MISMATCH',
'SHIPPING.REVIEW_LLM_VALIDATION_FAILED',
})
ALL_LLM_ERROR_CODES: Final[frozenset[str]] = GATE_ERROR_CODES | LEGACY_ERROR_CODES
def build_suggestion_request_envelope(
# ---------------------------------------------------------------------------
# evidence_ref / provenance_ref 格式工具
# ---------------------------------------------------------------------------
_LAYOUT_REF_RE = re.compile(
r'^layout:(?P<doc>\d+):p(?P<page>\d+)(?::(?P<table>[^:\r\n]*))?(?::row-(?P<row>\d+))?(?::(?P<field>[^:\r\n]*))?$'
)
_DRAFT_REF_RE = re.compile(
r'^draft:case-(?P<case>\d+):line-(?P<line>[^:]+):field-(?P<field>[^:\r\n]+)$'
)
def is_valid_evidence_ref(value: Any, *, scope: str | None = None) -> bool:
"""
校验 layout: 前缀 evidence_ref 是否满足该 scope 的最低要求。
Args:
value: 待校验字符串。
scope: header / line;line scope 要求 table_id 和 row_index。
Returns:
True 当且仅当格式正确且必需段齐全。
"""
if not isinstance(value, str) or not value:
return False
matched = _LAYOUT_REF_RE.match(value.strip())
if not matched:
return False
doc = matched.group('doc')
page = matched.group('page')
if not doc or not page:
return False
try:
int(doc)
int(page)
except (TypeError, ValueError):
return False
if scope == 'line':
table = matched.group('table')
row = matched.group('row')
return bool(table and row)
return True
def build_evidence_ref(
*,
document_id: int | None,
page_no: int | None,
table_id: str | None = None,
row_index: int | None = None,
field_code: str | None = None,
) -> str | None:
"""按定案格式生成 layout evidence_ref;缺必需段返回 None 而不伪造。"""
if not document_id or not page_no or document_id <= 0 or page_no <= 0:
return None
parts = [f'layout:{int(document_id)}:p{int(page_no)}']
if table_id:
parts.append(str(table_id))
else:
if row_index is not None or field_code:
parts.append('') # 占位 table
if row_index is not None:
parts.append(f'row-{int(row_index)}')
else:
if field_code:
# 需要补 row 占位
if len(parts) == 2:
parts.append('') # table 占位
parts.append('') # row 占位
if field_code:
parts.append(str(field_code))
result = ':'.join(parts)
if not is_valid_evidence_ref(result, scope='line' if row_index is not None else None):
return None
return result
def is_valid_provenance_ref(value: Any) -> bool:
if not isinstance(value, str) or not value:
return False
return _DRAFT_REF_RE.match(value.strip()) is not None
def build_provenance_ref(*, case_id: int, line_key: str | None, field_code: str) -> str:
"""生成 Draft 回退专用的 provenance_ref(不伪装成 evidence_ref)。"""
line = str(line_key or 'header').strip() or 'header'
return f'draft:case-{int(case_id)}:line-{line}:field-{str(field_code).strip()}'
# ---------------------------------------------------------------------------
# 观察值来源标记(三源 + text fallback)
# ---------------------------------------------------------------------------
ObservationSource = Literal[
'unit_observation',
'draft_observation',
'frozen_layout',
'text_fallback',
]
OBSERVATION_SOURCES: Final[frozenset[str]] = frozenset({
'unit_observation', 'draft_observation', 'frozen_layout', 'text_fallback',
})
# ---------------------------------------------------------------------------
# v1 信封(保留原行为,不做任何字段增减,历史可回放)
# ---------------------------------------------------------------------------
def build_suggestion_request_envelope_v1(
*,
review_case_id: int,
document_id: int,
evidence_level: EvidenceLevel,
evidence_level: EvidenceLevelV1,
target_fields: list[dict[str, Any]],
evidence_pack: dict[str, Any],
) -> dict[str, Any]:
"""
构建发给 Chatflow 的最小请求信封;禁止密钥与临时 URL。
Args:
review_case_id: Review Case 主键。
document_id: 冻结 Document ID。
evidence_level: 当前证据等级。
target_fields: 待建议字段(field_id/code/scope)。
evidence_pack: 已脱敏证据包。
Returns:
可序列化请求字典。
"""
return {
'contract_version': LLM_REVIEW_CONTRACT_VERSION,
'contract_version': LLM_REVIEW_CONTRACT_VERSION_V1,
'review_case_id': int(review_case_id),
'document_id': int(document_id),
'evidence_level': evidence_level,
@@ -60,13 +223,136 @@ def build_suggestion_request_envelope(
},
}
# ---------------------------------------------------------------------------
# v2 信封:target / context.row / context.table / neighbor_rows / evidence /
# constraints / expected_output
# ---------------------------------------------------------------------------
class V2Target(TypedDict, total=False):
field_id: str
field_code: str
scope: Literal['header', 'line']
line_key: str | None
class V2RowContext(TypedDict, total=False):
line_key: str
fields: list[dict[str, Any]] # 每个字段含 field_id/field_code/machine_value/current_draft_value/value_source/evidence_ref/source
class V2TableContext(TypedDict, total=False):
table_id: str
headers: list[dict[str, Any]] # [{column_index, field_code, display_name}]
target_row_index: int | None
class V2NeighborRow(TypedDict, total=False):
line_key: str
row_index: int
fields: list[dict[str, Any]]
position: Literal['preceding', 'following']
class V2PageContext(TypedDict, total=False):
page_no: int
tables: list[dict[str, Any]]
structured_text_blocks: list[dict[str, Any]]
class V2EvidenceItem(TypedDict, total=False):
field_id: str
value: str
quote: str
source: ObservationSource
confidence: float | None
evidence_ref: str | None
provenance_ref: str | None
page_no: int | None
table_id: str | None
cell_id: str | None
row_index: int | None
def build_suggestion_request_envelope(
*,
review_case_id: int,
document_id: int,
evidence_level: EvidenceLevel,
target_fields: list[dict[str, Any]],
evidence_pack: dict[str, Any],
contract_version: str = LLM_REVIEW_CONTRACT_VERSION,
target: V2Target | None = None,
context_row: V2RowContext | None = None,
context_table: V2TableContext | None = None,
neighbor_rows: list[V2NeighborRow] | None = None,
page_context: V2PageContext | None = None,
evidence_items: list[V2EvidenceItem] | None = None,
expected_target_field_id: str | None = None,
auto_upgrade_reason: str | None = None,
auto_upgrade_reasons: list[str] | None = None,
) -> dict[str, Any]:
"""
构建 v2 为主、v1 兼容的请求信封。contract_version=v1 时回退到老结构。
约束:
- values_must_be_verbatim_in_evidence=True(逐字证据)
- cannot_auto_freeze/cannot_auto_create_order 永远为 True(LLM 不能直接操作业务状态)
- full_document_forbidden=True(除非显式 L5,但 L5 永不开放)
"""
if contract_version == LLM_REVIEW_CONTRACT_VERSION_V1:
return build_suggestion_request_envelope_v1(
review_case_id=review_case_id,
document_id=document_id,
evidence_level=evidence_level if evidence_level in {
'L1_field', 'L2_table', 'L3_page', 'L4_pdf',
} else 'L3_page',
target_fields=target_fields,
evidence_pack=evidence_pack,
)
constraints = {
'values_must_be_verbatim_in_evidence': True,
'cannot_auto_freeze': True,
'cannot_auto_create_order': True,
'full_document_forbidden': evidence_level != 'L5_document',
}
expected_output = {
'allowed_target_field_id': expected_target_field_id,
'must_include_quote': True,
'must_include_field_id': True,
'suggested_value_must_be_verbatim_in_evidence': True,
'without_evidence_return': 'needs_review',
'forbid_commonsense_filling': True,
'forbid_sibling_field_suggestions': True,
}
envelope: dict[str, Any] = {
'contract_version': LLM_REVIEW_CONTRACT_VERSION_V2,
'review_case_id': int(review_case_id),
'document_id': int(document_id),
'evidence_level': evidence_level,
'target': target,
'context': {
'level': evidence_level,
'row': context_row,
'table': context_table,
'neighbor_rows': neighbor_rows or [],
},
'evidence': evidence_items or [],
'constraints': constraints,
'expected_output': expected_output,
# 保留 v1 兼容字段,供过渡
'target_fields': target_fields,
'evidence_pack': evidence_pack,
}
if page_context is not None:
envelope['context']['page'] = page_context
if auto_upgrade_reason:
envelope['auto_upgrade_reason'] = auto_upgrade_reason
if auto_upgrade_reasons:
envelope['auto_upgrade_reasons'] = list(auto_upgrade_reasons)
return envelope
# ---------------------------------------------------------------------------
# 响应解析(v1/v2 统一出口,line_key/scope/needs_review v2 新增)
# ---------------------------------------------------------------------------
def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]]:
"""
解析 Chatflow 建议输出为字段建议列表。
Returns:
[{field_id, field_code, scope, suggested_value, quote, confidence}]
解析 Dify 返回的建议列表。v2 输出可能带 needs_review 布尔,
parse 层仅负责结构清洗,不做业务有效性判定(留给 validation 层 fail-closed)。
"""
if not isinstance(raw, dict):
return []
@@ -82,13 +368,79 @@ def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]
field_id = str(item.get('field_id') or '').strip()
if not field_id:
continue
needs_review = False
if isinstance(item.get('needs_review'), bool):
needs_review = bool(item['needs_review'])
line_key_raw = item.get('line_key')
line_key = str(line_key_raw).strip() if line_key_raw is not None else None
if not line_key:
line_key = None
scope = str(item.get('scope') or '').strip().lower()
if scope not in {'header', 'line'}:
scope = 'line'
confidence_raw = item.get('confidence')
try:
confidence = float(confidence_raw) if confidence_raw is not None else 0.0
except (TypeError, ValueError):
confidence = 0.0
result.append({
'field_id': field_id,
'field_code': str(item.get('field_code') or '').strip() or None,
'scope': str(item.get('scope') or 'line').strip() or 'line',
'scope': scope,
'line_key': line_key,
'suggested_value': item.get('suggested_value'),
'quote': str(item.get('quote') or item.get('suggested_value') or '')[:1000],
'confidence': float(item.get('confidence') or 0),
'confidence': confidence,
'line_number': item.get('line_number'),
'needs_review': needs_review,
'reason_code': str(item.get('reason_code') or '').strip() or None,
})
return result
# ---------------------------------------------------------------------------
# context_hash:规范化证据包 → SHA-256 完整 64 hex
# ---------------------------------------------------------------------------
_STRIP_FOR_CONTEXT_HASH = frozenset({
'request_time', 'random_id', 'nonce', 'token', 'api_key',
'created_at', 'updated_at', 'latency_ms', 'provider_message_id',
})
def _normalize_for_context_hash(value: Any) -> Any:
"""递归规范化:key 排序 + 去噪键 + 数组稳定顺序(保留业务数组原顺序)。"""
if isinstance(value, dict):
return {
k: _normalize_for_context_hash(v)
for k, v in sorted(value.items(), key=lambda kv: str(kv[0]))
if str(k) not in _STRIP_FOR_CONTEXT_HASH
}
if isinstance(value, list):
return [_normalize_for_context_hash(item) for item in value]
if isinstance(value, tuple):
return [_normalize_for_context_hash(item) for item in value]
if isinstance(value, (int, float, bool)) or value is None:
return value
return str(value)
def compute_context_hash(evidence_pack: dict[str, Any]) -> str | None:
"""
规范化证据包(排序键、去噪、保留业务稳定数组顺序)后求 SHA-256。
输入空或非法时返回 None(上层门禁拦截,不允许落库空 hash)。
"""
if not isinstance(evidence_pack, dict) or not evidence_pack:
return None
normalized = _normalize_for_context_hash(evidence_pack)
payload = json.dumps(normalized, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
digest = hashlib.sha256(payload.encode('utf-8')).hexdigest()
return digest
# ---------------------------------------------------------------------------
# Quote normalize:trim + collapse whitespace;匹配层单独使用
# ---------------------------------------------------------------------------
QUOTE_NORMALIZATION_RULES: Final[tuple[str, ...]] = ('trim', 'collapse_whitespace')
def normalize_quote_text(text: Any) -> str:
raw = '' if text is None else str(text)
return re.sub(r'\s+', ' ', raw).strip()
@@ -0,0 +1,146 @@
"""
services/shipping_notice/order_review_llm_gate.py
用途:请求发送给大模型之前的 fail-closed 确定性前门禁。
任何一项失败 → 返回 gated_failed 状态与 error_code,不允许调用 Dify。
依赖:
- order_review_evidence_view.get_field_view / count_valid_row_fields
- order_review_llm_contract.GATE_ERROR_CODES / DEFAULT_V2_EVIDENCE_LEVEL
- order_review_llm_policy_registry.resolve_llm_context_policy
逻辑:
[1] field_not_found 目标 field_id 在 schema 中不存在
[2] line_not_found 目标 line_key 在视图中行找不到
[3] field_value_missing 目标字段 machine/draft/primary_evidence 三者全空
[4] evidence_unavailable 目标字段无任何 field_evidences[](三源都没有事实)
[5] context_ambiguous unit orders >1 且无法按 primary_document_id 唯一确定
[6] policy_blocked llm_context_policy 解析为 forbidden
[7] context_build_failed 通用异常包裹;evidence_view 构建抛异常即本错误
[8] evidence_truncated (暂留占位,由 selector budget 截断后写入 evidence_truncated=true 时打)
[9] L4_forbidden L5_document 请求或 schema 未开启 L4 时命中;(暂留占位)
[10] context_insufficient 行 scope L2_row 同行有效字段 < 2 且无法自动降级(默认不开启降级)
"""
from __future__ import annotations
import traceback
from typing import Any, Final, Literal
from app.services.shipping_notice.order_review_llm_contract import (
EVIDENCE_LEVELS_V2_ALLOWED,
GATE_ERROR_CODES,
EvidenceLevelV2,
)
from app.services.shipping_notice.order_review_evidence_view import (
count_valid_row_fields,
get_field_view,
)
from app.services.shipping_notice.order_review_llm_policy_registry import (
resolve_llm_context_policy,
)
GateResult = tuple[bool, str | None, str | None] # (passed, error_code, technical_hint)
_MIN_LINE_SIBLINGS: Final[int] = 2
_SENSITIVE_MASK_LEVELS: Final = frozenset({'masked'})
def _text_empty(v: Any) -> bool:
if v is None:
return True
if isinstance(v, str):
return v.strip() == ''
return False
def run_preflight_gate(
evidence_view: dict[str, Any],
*,
field_id: str,
line_key: str | None,
requested_level: EvidenceLevelV2 | None,
schema_field_meta: dict[str, Any] | None = None,
) -> GateResult:
"""
执行 10 项门禁,fail-closed。
Returns:
(passed, error_code, technical_hint)
passed=True 时 error_code/hint 都为 None。
"""
if not isinstance(evidence_view, dict):
return False, 'context_build_failed', 'evidence_view is empty dict'
diagnostics = evidence_view.get('diagnostics') or {}
ambiguous_reasons = diagnostics.get('context_ambiguous_reasons') or []
if ambiguous_reasons:
return False, 'context_ambiguous', \
'; '.join(str(r) for r in ambiguous_reasons)
# [2] line scope 需要 line_key 存在
scope_is_line = bool(line_key)
if scope_is_line:
line_fields = evidence_view.get('line_fields') or {}
if str(line_key) not in line_fields:
return False, 'line_not_found', f'line_key={line_key}'
# [1] field_id 找不到(header/line 都没命中)
field_view = get_field_view(evidence_view, field_id=field_id, line_key=line_key)
if field_view is None:
return False, 'field_not_found', f'field_id={field_id}'
# policy_blocked(即使有值也不允许发给 LLM)
policy = field_view.get('llm_context_policy')
if not policy:
# 兜底再算一次,防视图构建漏算
policy = resolve_llm_context_policy(
field_metadata=schema_field_meta or {},
field_code=field_view.get('field_code') or field_id,
scope='line' if scope_is_line else 'header',
data_type=field_view.get('data_type'),
is_target_field=True,
)
if policy == 'forbidden':
return False, 'policy_blocked', f'policy=forbidden field_id={field_id}'
# [3] 目标值缺失(machine/draft/primary_evidence.value 全空)
mv = field_view.get('machine_value')
dv = field_view.get('current_draft_value')
pe = field_view.get('primary_evidence') or {}
pe_val = pe.get('value') if isinstance(pe, dict) else None
if _text_empty(mv) and _text_empty(dv) and _text_empty(pe_val):
return False, 'field_value_missing', \
f'field_id={field_id} machine/draft/primary.value all empty'
# [4] 三源都没有 evidence(Case 95 根因修复)
evidences = field_view.get('field_evidences') or []
if not isinstance(evidences, list) or len(evidences) == 0:
return False, 'evidence_unavailable', \
f'field_id={field_id} field_evidences empty; check Unit/Draft/Frozen'
# [8] 预留占位:目标字段核心 evidence 截断
if field_view.get('context_truncated_target_core'):
return False, 'evidence_truncated', \
f'field_id={field_id} target core evidence truncated under budget'
# [10] context_insufficient(行 scope L2_row 同行字段数)
effective_level = requested_level or 'L2_row'
if effective_level not in _SENSITIVE_MASK_LEVELS and effective_level in EVIDENCE_LEVELS_V2_ALLOWED:
if scope_is_line and str(effective_level) in ('L2_row',):
siblings = count_valid_row_fields(evidence_view, str(line_key))
if siblings < _MIN_LINE_SIBLINGS:
return False, 'context_insufficient', \
f'line_key={line_key} valid siblings={siblings} required>={_MIN_LINE_SIBLINGS}'
return True, None, None
def wrap_context_build_exception(exc: Exception) -> GateResult:
"""把 build_review_evidence_view 抛的任意异常都转成 context_build_failed。"""
hint = f'{type(exc).__name__}: {str(exc)[:160]}'
stack = traceback.format_exc(limit=2)
return False, 'context_build_failed', f'{hint} | {stack[:300]}'
def validate_gate_error_code(code: str | None) -> bool:
return code in GATE_ERROR_CODES
@@ -0,0 +1,318 @@
"""
services/shipping_notice/order_review_llm_policy_registry.py
用途:为 LLM 证据发送提供字段级 llm_context_policy 推断 + 类型化 mask 算法。
依赖:无外部 I/O;被 evidence_view、evidence_selector、gate 引用。
逻辑:
- 7 步优先级推断:显式 policy → 敏感黑名单 → 内部黑名单 → scope 黑名单
→ 业务白名单 → data_type 白名单 → 保守 forbidden
- 敏感规则优先于业务白名单(supplier_email 命中敏感,不能因为 supplier 前缀变 allowed)
- mask 不采用通用前 N% 算法;按数据类型确定性掩码,原值永远不进入证据包。
"""
from __future__ import annotations
import re
from typing import Any, Final, Literal
# ---------------------------------------------------------------------------
# Policy 枚举
# ---------------------------------------------------------------------------
LlmContextPolicy = Literal['allowed', 'masked', 'forbidden', 'target_only']
LLM_CONTEXT_POLICIES: Final[frozenset[str]] = frozenset({
'allowed', 'masked', 'forbidden', 'target_only',
})
DEFAULT_CONSERVATIVE_POLICY: Final[LlmContextPolicy] = 'forbidden'
# ---------------------------------------------------------------------------
# 规则库(敏感 / 内部 / 业务白名单)
# 顺序由 7 步优先级控制,这里只存正则集合
# ---------------------------------------------------------------------------
_SENSITIVE_FIELD_CODE_PATTERNS: Final[tuple[re.Pattern[str], ...]] = tuple(
re.compile(p, re.IGNORECASE)
for p in (
r'address', r'phone|mobile|tel', r'email|e_mail|mail',
r'contact(_?name|_?person)?', r'tax(_?id)?|taxpayer|ein|ssn',
r'passport|id(_?card|_?no)?', r'bank(_?account|_?name|_?swift|_?iban)?',
r'credit(_?card)?|card(_?no)?',
)
)
_INTERNAL_FIELD_CODE_PATTERNS: Final[tuple[re.Pattern[str], ...]] = tuple(
re.compile(p, re.IGNORECASE)
for p in (
r'^_', r'internal', r'audit(_\w+)?$', r'permission(_\w+)?$',
r'lock(_\w+)?$', r'version(_\w+)?$', r'checksum|hash_digest',
r'token|secret|nonce|signature|salt',
)
)
_INTERNAL_SCOPE_PATTERNS: Final[frozenset[str]] = frozenset({
'system', 'audit', 'internal', 'runtime', 'permission',
})
_BUSINESS_FIELD_CODE_PATTERNS: Final[tuple[re.Pattern[str], ...]] = tuple(
re.compile(p, re.IGNORECASE)
for p in (
r'customer(_\w+)?', r'supplier(_\w+)?', r'vendor',
r'part(_?number|_?no|_?id)?', r'po(_?number|_?no)?', r'purchase_order',
r'qty|quantit(y|ies)', r'uom|unit(_?measure)?',
r'unit(_?price)?|price|amount|monetary', r'currency|ccy|curr',
r'date|incoterm(_\w+)?', r'line(_?no|_?key|_?number)?',
r'description|item(_?name|_?desc)?', r'receipt', r'ship(_?to|_?from)?',
)
)
_ALLOWED_DATA_TYPES: Final[frozenset[str]] = frozenset({
'quantity', 'monetary', 'date', 'document_reference',
'string', 'integer', 'number', 'enum',
})
# ---------------------------------------------------------------------------
# 规则组合:7 步优先级推断
# ---------------------------------------------------------------------------
def resolve_llm_context_policy(
*,
field_metadata: dict[str, Any] | None,
field_code: str,
scope: str | None = None,
data_type: str | None = None,
is_target_field: bool = False,
) -> LlmContextPolicy:
"""
7 步优先级推断字段级 llm_context_policy。
顺序(定案 §1.2):
1. 明确的 field.llm_context_policy
2. field_code 敏感黑名单 → masked
3. field_code 内部字段黑名单 → forbidden
4. scope=system/audit/internal → forbidden
5. 明确业务字段白名单 → allowed
6. data_type 为 quantity/monetary/date/document_reference → allowed
7. 未命中 → forbidden
【敏感优先】第 2 步(敏感)在第 5 步(业务)之前,
因此 supplier_email 虽然命中 supplier 业务白名单,但依然是 masked。
target_only 仅当显式配置时生效(目标字段单独传,其它同名字段不传)。
"""
code = '' if field_code is None else str(field_code).strip()
code_folded = code.casefold()
# [STEP 1] 明确配置
if isinstance(field_metadata, dict):
explicit = field_metadata.get('llm_context_policy')
if isinstance(explicit, str) and explicit.strip():
explicit_norm = explicit.strip().lower()
if explicit_norm in LLM_CONTEXT_POLICIES:
return explicit_norm # type: ignore[return-value]
if is_target_field:
# 目标字段即使没有显式配置,也至少作为 target_only 传入
# 但仍然先跑敏感/内部检查:敏感字段目标字段也必须 masked
pass
# [STEP 2] 敏感黑名单
for pattern in _SENSITIVE_FIELD_CODE_PATTERNS:
if pattern.search(code_folded):
return 'masked'
# [STEP 3] 内部黑名单
for pattern in _INTERNAL_FIELD_CODE_PATTERNS:
if pattern.search(code_folded):
return 'forbidden'
# [STEP 4] scope 黑名单
scope_raw = '' if scope is None else str(scope).strip().casefold()
if scope_raw in _INTERNAL_SCOPE_PATTERNS:
return 'forbidden'
# [STEP 5] 业务白名单
for pattern in _BUSINESS_FIELD_CODE_PATTERNS:
if pattern.search(code_folded):
return 'allowed'
# [STEP 6] data_type 白名单
dt = '' if data_type is None else str(data_type).strip().casefold()
if dt in _ALLOWED_DATA_TYPES:
return 'allowed'
# [STEP 7] 保守默认
if is_target_field:
# 目标字段:作为最低保证 sent 为 target_only(只有目标字段自身允许)
return 'target_only'
return DEFAULT_CONSERVATIVE_POLICY
# ---------------------------------------------------------------------------
# Mask 算法:按字段类型确定性掩码;返回 (masked_value, mask_rule_key)
# 规则:original_value_sent 永远为 False(原值绝对不进 Dify)
# ---------------------------------------------------------------------------
_MASK_RULE_EMAIL: Final[str] = 'email_v1'
_MASK_RULE_PHONE: Final[str] = 'phone_v1'
_MASK_RULE_ADDRESS: Final[str] = 'address_v1'
_MASK_RULE_TAX_ACCOUNT: Final[str] = 'tax_account_v1'
_MASK_RULE_GENERIC: Final[str] = 'generic_masked_v1'
_EMAIL_RE = re.compile(r'^(?P<local>[^@\s]+)@(?P<domain>[^@\s]+\.[^@\s]+)$')
_PHONE_RE = re.compile(r'^[+\d][\d\s\-()]{5,}$')
def mask_field_value(
value: Any,
*,
policy: LlmContextPolicy,
field_code: str | None = None,
) -> dict[str, Any]:
"""
按 policy + field_code 类型化掩码。
返回:
{
"policy": "masked",
"mask_rule": "...",
"original_value_sent": False,
"masked_value": "..."
}
policy != masked 时不做掩码,按原样返回(但仍返回元信息结构体)。
"""
code_folded = '' if field_code is None else str(field_code).casefold()
if policy != 'masked':
return {
'policy': policy,
'mask_rule': None,
'original_value_sent': policy == 'allowed' or policy == 'target_only',
'masked_value': value,
}
raw = '' if value is None else str(value)
stripped = raw.strip()
if not stripped:
return {
'policy': 'masked',
'mask_rule': _MASK_RULE_GENERIC,
'original_value_sent': False,
'masked_value': '',
}
# email(优先级最高:先判断 email 再判断 phone)
if 'email' in code_folded or 'mail' in code_folded:
matched = _EMAIL_RE.match(stripped)
if matched:
local = matched.group('local')
domain = matched.group('domain')
local_masked = (local[0] + '***') if len(local) >= 1 else '***'
try:
first_char = domain.split('.', 1)[0]
first = first_char[0] if first_char else 'd'
except (IndexError, AttributeError):
first = 'd'
domain_parts = domain.rsplit('.', 1)
tld = domain_parts[-1] if len(domain_parts) > 1 else 'com'
return {
'policy': 'masked',
'mask_rule': _MASK_RULE_EMAIL,
'original_value_sent': False,
'masked_value': f'{local_masked}@{first}***.{tld}',
}
# phone / mobile
if any(kw in code_folded for kw in ('phone', 'mobile', 'tel', 'fax')):
digits = re.sub(r'\D', '', stripped)
if len(digits) >= 7:
if len(digits) == 11:
return {
'policy': 'masked',
'mask_rule': _MASK_RULE_PHONE,
'original_value_sent': False,
'masked_value': f'{digits[:3]}****{digits[-4:]}',
}
head = digits[:2]
tail = digits[-2:]
middle = '*' * max(len(digits) - 4, 4)
return {
'policy': 'masked',
'mask_rule': _MASK_RULE_PHONE,
'original_value_sent': False,
'masked_value': f'{head}{middle}{tail}',
}
if _PHONE_RE.match(stripped):
return {
'policy': 'masked',
'mask_rule': _MASK_RULE_PHONE,
'original_value_sent': False,
'masked_value': stripped[:2] + '****' + stripped[-2:],
}
# address:保留国家/省/市(中文按常见分隔符拆 3 段,后面全换 ***)
if 'address' in code_folded:
return {
'policy': 'masked',
'mask_rule': _MASK_RULE_ADDRESS,
'original_value_sent': False,
'masked_value': _mask_address(stripped),
}
# tax / account / bank / id_card / passport
if any(kw in code_folded for kw in (
'tax', 'account', 'bank', 'passport', 'id_card', 'idcard', 'ssn', 'credit', 'card',
)):
if len(stripped) <= 4:
masked = '*' * len(stripped)
else:
head = stripped[:2]
tail = stripped[-2:]
middle = '*' * max(len(stripped) - 4, 4)
masked = f'{head}{middle}{tail}'
return {
'policy': 'masked',
'mask_rule': _MASK_RULE_TAX_ACCOUNT,
'original_value_sent': False,
'masked_value': masked,
}
# 通用敏感:保留首末字符,中间 ***
if len(stripped) <= 2:
masked = '*' * len(stripped)
else:
masked = stripped[0] + '***' + stripped[-1]
return {
'policy': 'masked',
'mask_rule': _MASK_RULE_GENERIC,
'original_value_sent': False,
'masked_value': masked,
}
def _mask_address(text: str) -> str:
"""
address 掩码规则:
- 中文:按省级(省/自治区/直辖市/特别行政区)→ 市 → 区/县,后面 ***
- 英文:按逗号分段保留前 2 段,后面 ***
- 失败通用:保留前 12 字符 + ***
"""
stripped = text.strip()
if not stripped:
return ''
cn_province_match = re.search(
r'^(?P<keep>.{2,12}?(省|自治区|北京市|上海市|天津市|重庆市|特别行政区|市|自治州))',
stripped,
)
if cn_province_match:
keep = cn_province_match.group('keep')
rest = stripped[len(keep):].strip()
if not rest:
return keep + '***'
city_match = re.match(r'^.{1,8}?(市|地区|盟)', rest)
if city_match:
city = city_match.group(0)
return f'{keep}{city}***'
return f'{keep}***'
# 英文逗号分段
parts = [p.strip() for p in stripped.split(',') if p.strip()]
if len(parts) >= 2:
return ', '.join(parts[:2]) + ', ***'
# 通用
if len(stripped) <= 12:
return stripped[:2] + '*' * max(len(stripped) - 2, 4)
return stripped[:12] + '***'
@@ -36,8 +36,18 @@ from app.services.shipping_notice.order_review_llm_contract import (
LLM_REVIEW_CONTRACT_VERSION,
EvidenceLevel,
build_suggestion_request_envelope,
compute_context_hash,
parse_suggestion_response,
)
from app.services.shipping_notice.order_review_evidence_view import build_review_evidence_view
from app.services.shipping_notice.order_review_llm_gate import (
run_preflight_gate,
wrap_context_build_exception,
)
from app.services.shipping_notice.order_review_llm_auto_upgrade import (
resolve_auto_upgrade_level,
describe_upgrade_reason,
)
from app.services.shipping_notice.order_review_llm_validation import validate_suggestions_against_evidence
from app.services.shipping_notice.order_review_projection import serialize_review_case
from app.services.shipping_notice.order_review_service import get_user_review_case
@@ -45,10 +55,15 @@ from app.services.shipping_notice.tool_common import llm_review_enabled
_LEVEL_MAP = {
'L1': 'L1_field',
'L2': 'L2_table',
'L3': 'L3_page',
'L4': 'L4_pdf',
'L2': 'L2_row',
'L3': 'L3_table',
'L4': 'L4_page',
'L1_field': 'L1_field',
'L2_row': 'L2_row',
'L3_table': 'L3_table',
'L4_page': 'L4_page',
'L5_document': 'L5_document',
# --- 旧 v1 兼容(保留,不删,新请求永远不生成这些值)---
'L2_table': 'L2_table',
'L3_page': 'L3_page',
'L4_pdf': 'L4_pdf',
@@ -60,8 +75,9 @@ def _suggestion_no() -> str:
def _normalize_level(value: str | None) -> EvidenceLevel:
raw = str(value or 'L1_field').strip()
return _LEVEL_MAP.get(raw, 'L1_field') # type: ignore[return-value]
raw = str(value or 'L2_row').strip()
mapped: str = _LEVEL_MAP.get(raw, raw if raw in _LEVEL_MAP.values() else 'L2_row') # type: ignore[assignment]
return mapped # type: ignore[return-value]
def _conversation_id_for_case(case: ShippingOrderReviewCase) -> str | None:
@@ -170,16 +186,68 @@ def _schema_field(case: ShippingOrderReviewCase, field_id: str) -> dict[str, Any
raise ValidationError('Review field is unavailable', code='SHIPPING.REVIEW_FIELD_INVALID')
def serialize_suggestion(row: ShippingOrderReviewSuggestion) -> dict[str, Any]:
"""投影单条建议的安全 DTO。"""
def serialize_suggestion(
row: ShippingOrderReviewSuggestion,
*,
is_admin: bool = False,
) -> dict[str, Any]:
"""
Phase 4 DTO 权限分层投影。
普通用户可见:
- contract_version, error_code(前端查 i18n 本地化,后端不翻译)
- evidence_summary(level/auto_upgraded/auto_upgrade_reason/counts/core_source/context_truncated)
- 业务字段:status / suggested_value / validation_issues / decision 等
管理员(is_admin=True)额外可见:
- provider_trace(provider, conversation_id, message_id, latency_ms)
- request_preview(fields_sent_preview, policies_applied, budget_tokens, method)
契约:绝不向前端暴露 API Key、Token、Provider 响应全文、脱敏前原文。
"""
suggested = row.suggested_value_json if isinstance(row.suggested_value_json, dict) else {}
return {
request = row.request_json if isinstance(row.request_json, dict) else {}
auto_upgrade = request.get('auto_upgrade') if isinstance(request.get('auto_upgrade'), dict) else {}
# evidence_summary(普通用户可见)
evidence_summary: dict[str, Any] = {
'level': row.evidence_level,
'auto_upgraded': bool(row.auto_upgrade_reason or auto_upgrade),
'auto_upgrade_reason': row.auto_upgrade_reason,
'field_count': int(row.evidence_count or 0),
'row_count': None,
'table_count': None,
'page_count': None,
'core_evidence_source': None,
'context_truncated': bool(row.context_truncated),
}
request_pack = request.get('evidence_pack') if isinstance(request.get('evidence_pack'), dict) else {}
try:
nf = 0
if isinstance(request_pack.get('fields'), list):
nf = len(request_pack['fields'])
evidence_summary['field_count'] = max(evidence_summary['field_count'] or 0, nf)
if isinstance(request_pack.get('tables'), list):
evidence_summary['table_count'] = len(request_pack['tables'])
if isinstance(request_pack.get('pages'), list):
evidence_summary['page_count'] = len(request_pack['pages'])
if isinstance(request.get('context'), dict):
ctx = request['context']
rows = ctx.get('row') if isinstance(ctx.get('row'), dict) else {}
if isinstance(rows.get('fields'), list):
evidence_summary['row_count'] = len(rows['fields'])
except Exception: # pragma: no cover - defensive
pass
base: dict[str, Any] = {
'suggestion_no': row.suggestion_no,
'field_id': row.field_id,
'line_key': row.line_key,
'scope': row.scope,
'evidence_level': row.evidence_level,
'contract_version': row.contract_version,
'status': row.status,
'error_code': row.error_code,
'suggested_value': suggested.get('value'),
'validation_issues': list(row.validation_issues_json or []),
'decision': row.decision,
@@ -188,10 +256,54 @@ def serialize_suggestion(row: ShippingOrderReviewSuggestion) -> dict[str, Any]:
'draft_version_at_request': row.draft_version_at_request,
'created_at': row.created_at.isoformat() if row.created_at else None,
'adjudicated_at': row.decided_at.isoformat() if row.decided_at else None,
'evidence_summary': evidence_summary,
'auto_upgrade_reason': row.auto_upgrade_reason,
}
# 后端查 i18n error_message 不输出:前端按 error_code 查 locales/*/errors.json(契约 v2)
base.pop('error_message', None)
def list_case_suggestions(*, user_id: int, case_no: str) -> dict[str, Any]:
if is_admin:
provider_trace: dict[str, Any] = {
'provider': row.provider,
'conversation_id': row.provider_conversation_id,
'message_id': row.provider_message_id,
'latency_ms': row.latency_ms,
}
request_preview: dict[str, Any] = {
'contract_version': row.contract_version,
'context_hash': row.context_hash,
'evidence_count': int(row.evidence_count or 0),
'context_truncated': bool(row.context_truncated),
'auto_upgrade': dict(auto_upgrade) if auto_upgrade else None,
'fields_sent_preview': None,
'policies_applied': None,
'budget_tokens': None,
'method': 'chatflow_blocking',
}
try:
tf = request.get('target_fields')
if isinstance(tf, list):
request_preview['fields_sent_preview'] = [
{
'field_id': (i.get('field_id') if isinstance(i, dict) else None),
'field_code': (i.get('field_code') if isinstance(i, dict) else None),
'scope': (i.get('scope') if isinstance(i, dict) else None),
'line_key': (i.get('line_key') if isinstance(i, dict) else None),
}
for i in tf if isinstance(i, dict)
][:50]
except Exception: # pragma: no cover - defensive
pass
base['provider_trace'] = provider_trace
base['request_preview'] = request_preview
base['context_hash'] = row.context_hash
base['latency_ms'] = row.latency_ms
return base
def list_case_suggestions(*, user_id: int, case_no: str, is_admin: bool = False) -> dict[str, Any]:
"""列出 Case 下全部建议记录。"""
case = get_user_review_case(user_id=user_id, case_no=case_no)
rows = (
@@ -203,7 +315,7 @@ def list_case_suggestions(*, user_id: int, case_no: str) -> dict[str, Any]:
return {
'case_no': case.case_no,
'llm_review_enabled': llm_review_enabled(),
'items': [serialize_suggestion(row) for row in rows],
'items': [serialize_suggestion(row, is_admin=is_admin) for row in rows],
}
@@ -216,8 +328,13 @@ def _resolve_dify_agent(case: ShippingOrderReviewCase) -> Agent | None:
return resolve_chat_agent()
def _call_dify_blocking(*, agent: Agent, user_id: int, query: str, inputs: dict[str, Any]) -> dict[str, Any]:
"""blocking Chatflow 调用;失败由上层 fail-closed。"""
def _call_dify_blocking(*, agent: Agent, user_id: int, query: str, inputs: dict[str, Any],
_return_raw_response: bool = False):
"""blocking Chatflow 调用;失败由上层 fail-closed。
当 _return_raw_response=True 时返回 (parsed_answer, http_top_json),
以便上层从 http_top_json 提取 conversation_id / message_id 进行可观测性对账。
"""
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
url = DifyService._build_chat_messages_url(base_url)
headers = {'Authorization': f'Bearer {agent.dify_api_key}', 'Content-Type': 'application/json'}
@@ -231,13 +348,19 @@ def _call_dify_blocking(*, agent: Agent, user_id: int, query: str, inputs: dict[
if not resp.ok:
raise RuntimeError(f'dify_http_{resp.status_code}')
data = resp.json() if resp.content else {}
answer = data.get('answer') if isinstance(data, dict) else None
top = data if isinstance(data, dict) else {}
answer = top.get('answer') if isinstance(top, dict) else None
parsed = {}
if isinstance(answer, str):
try:
return json.loads(answer)
parsed = json.loads(answer)
except json.JSONDecodeError:
return {'suggestions': [{'field_id': '', 'suggested_value': answer.strip(), 'quote': answer.strip()}]}
return answer if isinstance(answer, dict) else {}
parsed = {'suggestions': [{'field_id': '', 'suggested_value': answer.strip(), 'quote': answer.strip()}]}
else:
parsed = answer if isinstance(answer, dict) else {}
if _return_raw_response:
return parsed, top
return parsed
def request_field_suggestion(
@@ -276,9 +399,10 @@ def request_field_suggestion(
if scope == 'line' and not line_key:
raise ValidationError('line_key is required for line scope', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
level = _normalize_level(evidence_level or 'L1_field')
if level == 'L4_pdf' and not (is_admin and allow_full_pdf):
level_raw = _normalize_level(evidence_level or 'L1_field')
if level_raw == 'L4_pdf' and not (is_admin and allow_full_pdf):
raise ValidationError('Full PDF evidence level is forbidden', code='SHIPPING.REVIEW_LLM_L4_FORBIDDEN')
level = level_raw # phase 2 auto_upgrade 覆盖之前,保留原始变量引用
document = _frozen_document(case)
target_fields = [{
@@ -315,6 +439,111 @@ def request_field_suggestion(
metadata={'issue_code': issue_code, 'allow_full_pdf': bool(allow_full_pdf)},
)
# [STEP V2] Phase 2 自动升级:基于证据视图 7 项优先级检测,L2_row→L3_table/L4_page
_auto_upgrade_reason: str | None = None
_auto_upgrade_reasons: list[str] = []
try:
evidence_view = build_review_evidence_view(case)
except Exception as exc: # pragma: no cover - defensive
gate_exception = exc
evidence_view = {}
else:
gate_exception = None
# [AUTO_UPGRADE] 门禁之前先升级等级(升级后的等级决定门禁检查项,如 L3 不再需 context_insufficient)
try:
upgraded_level, up_reason, up_reasons = resolve_auto_upgrade_level(
evidence_view=evidence_view,
field_id=str(field_id),
line_key=str(line_key) if line_key else None,
requested_level=level, # type: ignore[arg-type]
schema_field_meta=field,
issue_code=issue_code,
)
except Exception: # pragma: no cover - defensive
upgraded_level = level # type: ignore[assignment]
up_reason = None
up_reasons = []
if up_reason:
level = upgraded_level # type: ignore[assignment]
_auto_upgrade_reason = up_reason
_auto_upgrade_reasons = list(up_reasons)
row.evidence_level = level
# 把完整原因列表写入 request_json,便于对账(落库列 auto_upgrade_reason 只存最高优先级)
row.request_json = {
**(row.request_json or {}),
'auto_upgrade': {
'from': str(level_raw),
'to': str(level),
'reasons': list(up_reasons),
'top_reason': up_reason,
'top_reason_desc': describe_upgrade_reason(up_reason),
},
}
row.auto_upgrade_reason = _auto_upgrade_reason
# [STEP V2] Phase 0 fail-closed 前门禁:视图构建 + 10 项检查,不过绝不调 Dify
if gate_exception is not None:
passed, gate_error, gate_hint = wrap_context_build_exception(gate_exception)
else:
passed, gate_error, gate_hint = run_preflight_gate(
evidence_view,
field_id=str(field_id),
line_key=str(line_key) if line_key else None,
requested_level=level, # type: ignore[arg-type]
schema_field_meta=field,
)
# 填充观测列(gated 或未 gated 都写,便于对账 context_hash)
_evidence_view_count = 0
if line_key:
line_map = (evidence_view or {}).get('line_fields') or {}
row_map = line_map.get(str(line_key)) or {}
target_view = row_map.get(str(field_id))
else:
header_map = (evidence_view or {}).get('header_fields') or {}
target_view = header_map.get(str(field_id))
if isinstance(target_view, dict):
f_ev = target_view.get('field_evidences') or []
if isinstance(f_ev, list):
_evidence_view_count = len(f_ev)
row.evidence_count = int(_evidence_view_count)
row.provider = 'dify'
# gated_failed 分支 ………………………………………………………………………………………………………………………………………………………………………………………………
if not passed:
row.status = 'gated_failed'
row.error_code = f'SHIPPING.REVIEW_LLM_GATE_{(gate_error or "").upper()}'
row.error_message = gate_hint or ''
try:
row.context_hash = compute_context_hash({
'case_id': int(case.id),
'contract_version': LLM_REVIEW_CONTRACT_VERSION,
'evidence_level': level,
'gate_error': gate_error,
})
except Exception:
row.context_hash = None
db.session.flush()
_audit_metadata = {'gate_error': gate_error, 'gate_hint': gate_hint}
if _auto_upgrade_reason:
_audit_metadata.update({
'auto_upgrade_applied': True,
'auto_upgrade_from': str(level_raw),
'auto_upgrade_to': str(level),
'auto_upgrade_reason': _auto_upgrade_reason,
'auto_upgrade_reasons': list(_auto_upgrade_reasons),
})
_audit_llm_suggestion(
case=case,
actor_id=int(user_id),
event_type='llm_review_gated',
action='llm_preflight_gate_failed',
suggestion=row,
result='failed',
error_code=row.error_code,
metadata=_audit_metadata,
)
return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)}
if not llm_review_enabled():
row.status = 'provider_unavailable'
row.error_code = 'SHIPPING.REVIEW_LLM_DISABLED'
@@ -329,22 +558,91 @@ def request_field_suggestion(
result='failed',
error_code=row.error_code,
)
return {'suggestion': serialize_suggestion(row), 'case': serialize_review_case(case)}
return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)}
evidence_pack = select_review_evidence_pack(
document=document,
target_fields=target_fields,
evidence_level=level,
allow_full_pdf=bool(is_admin and allow_full_pdf),
evidence_view=evidence_view,
)
# [GATE] selector 判定目标字段核心被截断 → fail-closed 不发 Dify
if isinstance(evidence_pack, dict) and bool(evidence_pack.get('target_core_trimmed')):
row.status = 'gated_failed'
row.error_code = 'SHIPPING.REVIEW_LLM_GATE_EVIDENCE_TRUNCATED'
row.error_message = 'target_core_trimmed=true; target quote/evidence core exceeded budget'
row.context_truncated = True
try:
row.context_hash = compute_context_hash({
'case_id': int(case.id),
'contract_version': LLM_REVIEW_CONTRACT_VERSION,
'evidence_level': level,
'gate_error': 'evidence_truncated',
})
except Exception:
row.context_hash = None
db.session.flush()
_audit_metadata_trunc = {
'gate_error': 'evidence_truncated',
'gate_hint': 'target_core_trimmed=true',
}
if _auto_upgrade_reason:
_audit_metadata_trunc.update({
'auto_upgrade_applied': True,
'auto_upgrade_from': str(level_raw),
'auto_upgrade_to': str(level),
'auto_upgrade_reason': _auto_upgrade_reason,
'auto_upgrade_reasons': list(_auto_upgrade_reasons),
})
_audit_llm_suggestion(
case=case,
actor_id=int(user_id),
event_type='llm_review_gated',
action='llm_preflight_gate_failed',
suggestion=row,
result='failed',
error_code=row.error_code,
metadata=_audit_metadata_trunc,
)
return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)}
request_payload = build_suggestion_request_envelope(
review_case_id=int(case.id),
document_id=int(case.document_id),
evidence_level=level,
target_fields=target_fields,
evidence_pack=evidence_pack,
target={
'field_id': str(field_id),
'field_code': str(field.get('field_code') or field_id),
'scope': scope,
'line_key': line_key,
},
expected_target_field_id=str(field_id),
auto_upgrade_reason=_auto_upgrade_reason,
auto_upgrade_reasons=list(_auto_upgrade_reasons) if _auto_upgrade_reasons else None,
)
row.request_json = {**(row.request_json or {}), **request_payload}
# [OBS V2] 计算稳定上下文指纹(递归 key 排序 + 去噪),落库供对账。
try:
row.context_hash = compute_context_hash({
'case_id': int(case.id),
'document_id': int(case.document_id),
'draft_version': int(case.current_draft.draft_version if case.current_draft else 0),
'field_id': str(field_id),
'line_key': line_key,
'contract_version': LLM_REVIEW_CONTRACT_VERSION,
'evidence_level': level,
'target_fields': target_fields,
'evidence_pack': evidence_pack,
})
except Exception:
row.context_hash = None
context_truncated_flag = bool(
isinstance(evidence_pack, dict) and bool(evidence_pack.get('context_truncated'))
)
row.context_truncated = context_truncated_flag
agent = _resolve_dify_agent(case)
if agent is None or not agent.dify_api_key:
@@ -361,16 +659,50 @@ def request_field_suggestion(
result='failed',
error_code=row.error_code,
)
return {'suggestion': serialize_suggestion(row), 'case': serialize_review_case(case)}
return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)}
try:
import time as _time
_t0 = _time.perf_counter()
raw_resp, raw_payload_top = _call_dify_blocking(
agent=agent,
user_id=user_id,
query=json.dumps(request_payload, ensure_ascii=False, separators=(',', ':')),
inputs={'review_llm_contract': LLM_REVIEW_CONTRACT_VERSION},
_return_raw_response=True, # type: ignore[call-arg]
)
row.latency_ms = int(round((_time.perf_counter() - _t0) * 1000))
raw = raw_resp if isinstance(raw_resp, dict) else {'raw': raw_resp}
row.response_json = raw
# [OBS V2] Dify HTTP 返回顶层 conversation_id / message_id
top = raw_payload_top if isinstance(raw_payload_top, dict) else (raw if isinstance(raw, dict) else {})
cid = top.get('conversation_id') or None
mid = top.get('message_id') or None
if cid is None:
cid = top.get('conversation') if isinstance(top.get('conversation'), str) else None
if isinstance(cid, (int, float)):
cid = str(cid)
if isinstance(mid, (int, float)):
mid = str(mid)
row.provider_conversation_id = (str(cid)[:255] if cid else _conversation_id_for_case(case)) or None
row.provider_message_id = (str(mid)[:255] if mid else None) or None
except TypeError:
# [兼容] _call_dify_blocking 原始签名:返回 dict;无 _return_raw_response
import time as _time
_t0 = _time.perf_counter()
raw = _call_dify_blocking(
agent=agent,
user_id=user_id,
query=json.dumps(request_payload, ensure_ascii=False, separators=(',', ':')),
inputs={'review_llm_contract': LLM_REVIEW_CONTRACT_VERSION},
)
row.latency_ms = int(round((_time.perf_counter() - _t0) * 1000))
row.response_json = raw if isinstance(raw, dict) else {'raw': raw}
if isinstance(raw, dict):
cid = raw.get('conversation_id') or raw.get('conversation')
mid = raw.get('message_id')
row.provider_conversation_id = (str(cid)[:255] if cid else _conversation_id_for_case(case)) or None
row.provider_message_id = (str(mid)[:255] if mid else None) or None
except Exception as exc:
if current_app:
current_app.logger.warning('[order-review-llm] provider failed: %s', exc)
@@ -388,15 +720,24 @@ def request_field_suggestion(
error_code=row.error_code,
metadata={'error_message': str(exc)[:256]},
)
return {'suggestion': serialize_suggestion(row), 'case': serialize_review_case(case)}
return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)}
_audit_received_meta: dict[str, Any] = {'evidence_level': level}
if _auto_upgrade_reason:
_audit_received_meta.update({
'auto_upgrade_applied': True,
'auto_upgrade_from': str(level_raw),
'auto_upgrade_to': str(level),
'auto_upgrade_reason': _auto_upgrade_reason,
'auto_upgrade_reasons': list(_auto_upgrade_reasons),
})
_audit_llm_suggestion(
case=case,
actor_id=int(user_id),
event_type='llm_review_received',
action='llm_provider_received',
suggestion=row,
metadata={'evidence_level': level},
metadata=_audit_received_meta,
)
suggestions = parse_suggestion_response(raw if isinstance(raw, dict) else {})
@@ -433,29 +774,55 @@ def request_field_suggestion(
error_code=row.error_code,
after={'valid': False, 'issues': row.validation_issues_json},
)
return {'suggestion': serialize_suggestion(row), 'case': serialize_review_case(case)}
return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)}
validated = validate_suggestions_against_evidence(suggestions=matched, evidence_pack=evidence_pack)
validated = validate_suggestions_against_evidence(
suggestions=matched,
evidence_pack=evidence_pack,
envelope=request_payload,
expected_target_field_id=str(field_id),
expected_line_key=line_key,
expected_scope=scope,
)
row.validated_suggestions_json = validated
primary = next(
(item for item in validated if str(item.get('field_id') or '') == str(field_id)),
None,
)
issues = []
issues: list[dict[str, Any]] = []
if primary is None or not primary.get('valid'):
issues.append({
'code': str(
(primary or {}).get('rejection_reason')
or ('field_id_mismatch' if primary is None else 'value_not_in_evidence')
),
reason_code = str(
(primary or {}).get('rejection_reason')
or ('field_id_mismatch' if primary is None else 'value_not_in_evidence')
)
issue_entry: dict[str, Any] = {
'code': reason_code,
'severity': 'blocking',
})
}
if isinstance(primary, dict):
checks_order = primary.get('validation_checks_order')
if isinstance(checks_order, list) and checks_order:
issue_entry['checks_order'] = list(checks_order)
match_meta = primary.get('validation_match')
if isinstance(match_meta, dict) and match_meta:
issue_entry['match'] = dict(match_meta)
detail = primary.get('rejection_detail')
if isinstance(detail, str) and detail:
issue_entry['detail'] = detail[:2000]
issues.append(issue_entry)
row.validation_issues_json = issues
if primary is not None and primary.get('valid'):
row.status = 'validated'
value = primary.get('suggested_value')
row.suggested_value_json = {'value': value}
suggested_payload: dict[str, Any] = {'value': value}
vm = primary.get('validation_match')
if isinstance(vm, dict) and vm:
suggested_payload['validation_match'] = dict(vm)
checks_order = primary.get('validation_checks_order')
if isinstance(checks_order, list) and checks_order:
suggested_payload['validation_checks_order'] = list(checks_order)
row.suggested_value_json = suggested_payload
apply_llm_suggestion_prefill(
user_id=user_id,
case_no=case_no,
@@ -466,17 +833,26 @@ def request_field_suggestion(
expected_draft_version=int(case.current_draft.draft_version),
)
case = get_user_review_case(user_id=user_id, case_no=case_no)
_audit_after_valid: dict[str, Any] = {'valid': True}
if isinstance(vm, dict):
_audit_after_valid['validation_match_mode'] = vm.get('mode')
_audit_llm_suggestion(
case=case,
actor_id=int(user_id),
event_type='llm_suggestion_validated',
action='llm_suggestion_validated',
suggestion=row,
after={'valid': True},
after=_audit_after_valid,
)
else:
row.status = 'validation_failed'
row.error_code = 'SHIPPING.REVIEW_LLM_VALIDATION_FAILED'
_audit_after_invalid: dict[str, Any] = {'valid': False, 'issues': issues}
if _auto_upgrade_reason:
_audit_after_invalid.update({
'auto_upgrade_applied': True,
'auto_upgrade_reason': _auto_upgrade_reason,
})
_audit_llm_suggestion(
case=case,
actor_id=int(user_id),
@@ -485,11 +861,11 @@ def request_field_suggestion(
suggestion=row,
result='failed',
error_code=row.error_code,
after={'valid': False, 'issues': issues},
after=_audit_after_invalid,
)
db.session.flush()
return {'suggestion': serialize_suggestion(row), 'case': serialize_review_case(case)}
return {'suggestion': serialize_suggestion(row, is_admin=is_admin), 'case': serialize_review_case(case)}
def decide_suggestion(
@@ -502,6 +878,7 @@ def decide_suggestion(
value: Any = None,
reason: str | None = None,
note: str | None = None,
is_admin: bool = False,
) -> dict[str, Any]:
"""人工裁决 LLM 建议:accept / modify / reject。"""
decision_norm = str(decision or '').strip().lower()
@@ -570,4 +947,4 @@ def decide_suggestion(
'modify_value_present': decision_norm == 'modify' and value is not None,
},
)
return {'suggestion': serialize_suggestion(suggestion), 'case': case_payload}
return {'suggestion': serialize_suggestion(suggestion, is_admin=is_admin), 'case': case_payload}
@@ -1,109 +1,427 @@
"""
services/shipping_notice/order_review_llm_validation.py
用途:验证 LLM 建议值必须逐字存在于冻结证据包;拒绝文档外值。
依赖:order_review_llm_contract。
逻辑:人工接受前强制调用;按目标 field_id(及可选 line_key)闭合匹配完整 snippet.quote,
禁止全文子串(避免 `10` 命中 `100`);验证失败不得预填草稿。
用途:Phase 3 — LLM 建议后校验 fail-closed(8 项硬规则)。
任何一项未通过 → validation_failed,该建议仅能 reject,禁止 accept/modify 写入草稿。
依赖:
- order_review_llm_contract:QUOTE_NORMALIZATION_RULES / normalize_quote_text
- request_payload.envelope:target / expected_target_field_id / evidence[] / line_key 定位
- 响应解析层:parse_suggestion_response 输出 [{field_id, line_key, scope, suggested_value, quote}]
逻辑:
8 项按顺序 fail-closed(优先级从身份→价值→安全性):
1. json_schema_invalid 响应项非 dict / field_id 为空(结构性非法)
2. header_scope_has_line_key scope=header 时 line_key 不为 None(头部不能带行键)
3. non_target_field 响应 field_id 不在请求 expected_target_field_id 内
4. field_id_mismatch 响应 field_id 与 expected_target_field_id 不一致
5. line_key_mismatch scope=line 时响应 line_key != 请求 line_key(精确相等)
6. value_not_in_evidence suggested_value 不在 evidence[] 任何 value/quote(normalize 后)
7. quote_consistency 响应 quote normalize 后与 suggested_value quote 不构成 substring 或
完整相等;即使值存在也视为伪造
8. guess_without_evidence 响应 quote 为空且 suggested_value 不能 exact 匹配任何 evidence.value
quote 匹配时:先 normalize(trim+collapse_whitespace),再允许 substring;
命中后保存 match_mode=exact / exact_substring / normalized / normalized_substring,
normalized=true/false,normalization_rules=[...] 元数据,供审计与 UI 展示。
"""
from __future__ import annotations
import re
from typing import Any
from typing import Any, Final
from app.services.shipping_notice.order_review_llm_contract import (
QUOTE_NORMALIZATION_RULES,
normalize_quote_text,
)
# ---------------------------------------------------------------------------
# 硬规则顺序(按严重程度;前序命中立即短路,不做后续检查)
# ---------------------------------------------------------------------------
_VALIDATION_CHECKS_ORDER: Final[tuple[str, ...]] = (
'json_schema_invalid',
'header_scope_has_line_key',
'non_target_field',
'field_id_mismatch',
'line_key_mismatch',
'value_not_in_evidence',
'quote_consistency',
'guess_without_evidence',
)
def _collect_evidence_values(
evidence_pack: dict[str, Any],
envelope: dict[str, Any] | None,
) -> list[dict[str, Any]]:
"""
从 v2 envelope.evidence 或 v1 evidence_pack.fields[].snippets 提取候选值池。
v2 优先读 envelope.evidence;缺失时回退 v1 结构(兼容历史 contract)。
每项返回 {value_norm, quote_norm, value_raw, quote_raw, field_id, line_key, evidence_ref}
"""
pool: list[dict[str, Any]] = []
env = envelope if isinstance(envelope, dict) else {}
ev_list = env.get('evidence')
if isinstance(ev_list, list) and ev_list:
for ev in ev_list:
if not isinstance(ev, dict):
continue
v_raw = ev.get('value')
q_raw = ev.get('quote')
pool.append({
'value_norm': normalize_quote_text(v_raw),
'quote_norm': normalize_quote_text(q_raw),
'value_raw': None if v_raw is None else str(v_raw),
'quote_raw': None if q_raw is None else str(q_raw),
'field_id': str(ev.get('field_id') or ''),
'line_key': str(ev.get('line_key') or '').strip() or None,
'evidence_ref': ev.get('evidence_ref'),
})
return pool
# v1 兼容:evidence_pack.fields[].snippets[]
fields = (evidence_pack or {}).get('fields') or []
for f in fields:
if not isinstance(f, dict):
continue
fid = str(f.get('field_id') or '')
lk = str(f.get('line_key') or '').strip() or None
for sn in (f.get('snippets') or []):
if not isinstance(sn, dict):
continue
q_raw = sn.get('quote')
v_raw = sn.get('value') if 'value' in sn else q_raw
pool.append({
'value_norm': normalize_quote_text(v_raw),
'quote_norm': normalize_quote_text(q_raw),
'value_raw': None if v_raw is None else str(v_raw),
'quote_raw': None if q_raw is None else str(q_raw),
'field_id': fid,
'line_key': lk,
'evidence_ref': sn.get('evidence_ref'),
})
return pool
def _find_value_match(
pool: list[dict[str, Any]],
*,
value_norm: str,
quote_norm_provided: str,
field_id: str,
line_key: str | None,
) -> tuple[str, dict[str, Any] | None]:
"""
在候选池中按 4 级严格度递减匹配 value;返回 (mode, matched_item)。
严格度:exact → exact_substring → normalized → normalized_substring
同池内优先匹配 field_id + line_key 双重身份的项;其次 field_id;最后全局任意项。
"""
if not value_norm and not quote_norm_provided:
return '', None
# 身份过滤:先 field_id + line_key
def _iter_filtered():
if not pool:
return
same_identity = [
p for p in pool
if str(p.get('field_id') or '') == field_id
and (str(p.get('line_key') or '') == str(line_key or '')
if line_key else not p.get('line_key'))
]
same_field = [
p for p in pool
if str(p.get('field_id') or '') == field_id and p not in same_identity
]
others = [p for p in pool if p not in same_identity and p not in same_field]
for p in same_identity + same_field + others:
yield p
# 1. exact:raw 完全相等
for p in _iter_filtered():
vr = (p.get('value_raw') or '').strip()
qr = (p.get('quote_raw') or '').strip()
needle = value_norm.strip()
if (vr and vr == needle) or (qr and qr == needle):
return 'exact', p
# 2. exact_substring:raw 内 substring
for p in _iter_filtered():
vr = (p.get('value_raw') or '').strip()
qr = (p.get('quote_raw') or '').strip()
needle = value_norm.strip()
if not needle:
continue
if (vr and needle in vr) or (qr and needle in qr):
return 'exact_substring', p
# 3. normalized:norm 完全相等
for p in _iter_filtered():
vn = p.get('value_norm') or ''
qn = p.get('quote_norm') or ''
if (vn and vn == value_norm) or (qn and qn == value_norm):
return 'normalized', p
# 4. normalized_substring:norm 内 substring
for p in _iter_filtered():
vn = p.get('value_norm') or ''
qn = p.get('quote_norm') or ''
if not value_norm:
continue
if (vn and value_norm in vn) or (qn and value_norm in qn):
return 'normalized_substring', p
return '', None
def _check_quote_consistency(
*,
suggested_value_norm: str,
provided_quote_norm: str,
matched_item: dict[str, Any] | None,
) -> tuple[bool, str, str]:
"""
[Check 7] 响应提供的 quote 必须能回证:
- provided_quote 非空:normalize 后必须是 suggested_value 的完整相等或 substring(任一方向)
或者 provided_quote normalize 后等于 matched_item.quote_norm 的完整/substring
- 空 quote:留到 Check 8 guess_without_evidence 再处理,此处不报错
返回 (passed, match_mode, rejection_reason_extra)
"""
if not provided_quote_norm:
return True, '', ''
# 方向 A:provided_quote 与 suggested_value 直接构成一致
if suggested_value_norm and (
provided_quote_norm == suggested_value_norm
or suggested_value_norm in provided_quote_norm
or provided_quote_norm in suggested_value_norm
):
mode = 'quote_equals_value' if provided_quote_norm == suggested_value_norm else 'quote_substring_value'
return True, mode, ''
# 方向 B:provided_quote 与命中的证据项 quote_norm 构成一致(优先用精确证据)
if matched_item is not None:
item_qn = matched_item.get('quote_norm') or ''
item_vn = matched_item.get('value_norm') or ''
if item_qn and (
provided_quote_norm == item_qn
or provided_quote_norm in item_qn
or item_qn in provided_quote_norm
):
return True, 'quote_matches_evidence_quote', ''
if item_vn and (
provided_quote_norm == item_vn
or provided_quote_norm in item_vn
or item_vn in provided_quote_norm
):
return True, 'quote_matches_evidence_value', ''
return False, '', (
f'provided quote [{provided_quote_norm[:80]}] does not align with '
f'suggested_value or any matched evidence item quote/value'
)
# ---------------------------------------------------------------------------
# 对外主入口:逐条逐项 8 项 fail-closed
# ---------------------------------------------------------------------------
def validate_suggestions_against_evidence(
*,
suggestions: list[dict[str, Any]],
evidence_pack: dict[str, Any],
envelope: dict[str, Any] | None = None,
expected_target_field_id: str | None = None,
expected_line_key: str | None = None,
expected_scope: str | None = None,
) -> list[dict[str, Any]]:
"""
校验建议列表;返回带 validation_status 的副本。
Phase 3 fail-closed 校验。
Args:
suggestions: parse_suggestion_response 输出。
evidence_pack: select_review_evidence_pack 输出。
evidence_pack: select_review_evidence_pack 输出(v1/v2 均含 fields 等)。
envelope: build_suggestion_request_envelope 输出(用于 v2 evidence[] 和 target)。
expected_target_field_id: 期望的唯一目标 field_id(v2 envelope.target.field_id 兜底)。
expected_line_key: 期望 line_key(行 scope 用;header scope 传 None)。
expected_scope: 'header' / 'line'(从 schema_field_meta.scope 兜底)。
Returns:
每项增加 valid(bool) 与 rejection_reason。
list,每项增加:
valid(bool)、rejection_reason(str|None)、
validation_checks_order(list[str] 实际跑了哪些检查)、
validation_match{
mode(str), normalized(bool),
normalization_rules(list[str] = QUOTE_NORMALIZATION_RULES),
matched_evidence_ref(str|None),
}(仅 valid=True 时填充)
"""
result: list[dict[str, Any]] = []
for item in suggestions:
payload = dict(item)
field_id = str(item.get('field_id') or '').strip()
line_key = str(item.get('line_key') or '').strip() or None
value = item.get('suggested_value')
value_text = str(value).strip() if value is not None else ''
if not value_text:
payload['valid'] = False
payload['rejection_reason'] = 'empty_suggestion'
elif _verbatim_in_field_snippets(
evidence_pack,
field_id=field_id,
line_key=line_key,
needle=value_text,
):
payload['valid'] = True
payload['rejection_reason'] = None
env = envelope if isinstance(envelope, dict) else {}
target = env.get('target') if isinstance(env.get('target'), dict) else {}
_exp_fid = (
expected_target_field_id
or str(target.get('field_id') or '').strip()
or ''
)
_exp_lk_raw = expected_line_key
if _exp_lk_raw is None:
_exp_lk_from_env = target.get('line_key')
_exp_lk_raw = None if _exp_lk_from_env is None else str(_exp_lk_from_env)
_exp_lk = str(_exp_lk_raw).strip() if _exp_lk_raw is not None else None
if _exp_lk == '' or _exp_lk == 'None':
_exp_lk = None
_exp_scope = (
expected_scope
or str(target.get('scope') or '').strip().lower()
or ''
)
if _exp_scope not in {'header', 'line'}:
_exp_scope = 'line' if _exp_lk else 'header'
pool = _collect_evidence_values(evidence_pack, env)
for raw_item in suggestions:
payload: dict[str, Any] = dict(raw_item)
checks_ran: list[str] = []
rejection_reason: str | None = None
match_meta: dict[str, Any] = {}
# ---- [Check 1] json_schema_invalid ----
checks_ran.append('json_schema_invalid')
if not isinstance(raw_item, dict):
rejection_reason = 'json_schema_invalid'
else:
fid = str(raw_item.get('field_id') or '').strip()
if not fid:
rejection_reason = 'json_schema_invalid'
if rejection_reason:
payload['valid'] = False
payload['rejection_reason'] = 'value_not_in_evidence'
payload['rejection_reason'] = rejection_reason
payload['validation_checks_order'] = checks_ran
result.append(payload)
continue
# ---- [Check 2] header_scope_has_line_key ----
checks_ran.append('header_scope_has_line_key')
resp_scope = str(raw_item.get('scope') or '').strip().lower()
if not resp_scope:
resp_scope = 'line' if _exp_lk else 'header'
resp_lk_raw = raw_item.get('line_key')
resp_lk = None if resp_lk_raw is None else str(resp_lk_raw).strip()
if resp_lk in ('', 'None'):
resp_lk = None
effective_scope = _exp_scope if resp_scope not in {'header', 'line'} else resp_scope
if effective_scope == 'header' and resp_lk is not None:
rejection_reason = 'header_scope_has_line_key'
if rejection_reason:
payload['valid'] = False
payload['rejection_reason'] = rejection_reason
payload['validation_checks_order'] = checks_ran
result.append(payload)
continue
# ---- [Check 3] non_target_field ----
checks_ran.append('non_target_field')
resp_fid = str(raw_item.get('field_id') or '').strip()
if _exp_fid and resp_fid != _exp_fid:
rejection_reason = 'non_target_field'
if rejection_reason:
payload['valid'] = False
payload['rejection_reason'] = rejection_reason
payload['validation_checks_order'] = checks_ran
result.append(payload)
continue
# ---- [Check 4] field_id_mismatch ----
checks_ran.append('field_id_mismatch')
if _exp_fid and resp_fid != _exp_fid:
rejection_reason = 'field_id_mismatch'
if rejection_reason:
payload['valid'] = False
payload['rejection_reason'] = rejection_reason
payload['validation_checks_order'] = checks_ran
result.append(payload)
continue
# ---- [Check 5] line_key_mismatch(行 scope 才校验;header scope line_key 须 None 已在 Check 2)----
checks_ran.append('line_key_mismatch')
if effective_scope == 'line':
if _exp_lk and resp_lk != _exp_lk:
rejection_reason = 'line_key_mismatch'
if rejection_reason:
payload['valid'] = False
payload['rejection_reason'] = rejection_reason
payload['validation_checks_order'] = checks_ran
result.append(payload)
continue
# ---- 归一化建议值 / quote(准备 Check 6/7/8)----
suggested_value = raw_item.get('suggested_value')
sv_norm = normalize_quote_text(suggested_value)
quote_raw = raw_item.get('quote')
quote_norm = normalize_quote_text(quote_raw)
# ---- [Check 6] value_not_in_evidence ----
checks_ran.append('value_not_in_evidence')
if not sv_norm:
rejection_reason = 'value_not_in_evidence'
_matched_mode = ''
_matched_item = None
else:
_matched_mode, _matched_item = _find_value_match(
pool,
value_norm=sv_norm,
quote_norm_provided=quote_norm,
field_id=resp_fid,
line_key=resp_lk,
)
if not _matched_mode:
rejection_reason = 'value_not_in_evidence'
if rejection_reason:
payload['valid'] = False
payload['rejection_reason'] = rejection_reason
payload['validation_checks_order'] = checks_ran
result.append(payload)
continue
# ---- [Check 7] quote_consistency ----
checks_ran.append('quote_consistency')
ok_q, q_mode, q_extra = _check_quote_consistency(
suggested_value_norm=sv_norm,
provided_quote_norm=quote_norm,
matched_item=_matched_item,
)
if not ok_q:
rejection_reason = 'quote_consistency'
if q_extra:
payload['rejection_detail'] = q_extra
if rejection_reason:
payload['valid'] = False
payload['rejection_reason'] = rejection_reason
payload['validation_checks_order'] = checks_ran
result.append(payload)
continue
# ---- [Check 8] guess_without_evidence ----
checks_ran.append('guess_without_evidence')
if not quote_norm and _matched_mode not in {'exact', 'normalized'}:
rejection_reason = 'guess_without_evidence'
if rejection_reason:
payload['valid'] = False
payload['rejection_reason'] = rejection_reason
payload['validation_checks_order'] = checks_ran
result.append(payload)
continue
# ---- 全部通过:记录匹配元数据 ----
match_meta = {
'mode': _matched_mode,
'normalized': _matched_mode in {'normalized', 'normalized_substring', 'quote_consistency'},
'normalization_rules': list(QUOTE_NORMALIZATION_RULES),
'matched_evidence_ref': (
_matched_item.get('evidence_ref') if isinstance(_matched_item, dict) else None
),
'quote_alignment_mode': q_mode if q_mode else None,
}
payload['valid'] = True
payload['rejection_reason'] = None
payload['validation_checks_order'] = checks_ran
payload['validation_match'] = match_meta
result.append(payload)
return result
def _verbatim_in_field_snippets(
evidence_pack: dict[str, Any],
*,
field_id: str,
line_key: str | None,
needle: str,
) -> bool:
"""
在目标字段的 snippet.quote 上做完整相等或 token 边界匹配。
核心逻辑:优先匹配同 field_id(及 line_key)的片段;不允许把整份证据拼成语料做子串。
"""
if not needle or not field_id:
return False
for field in evidence_pack.get('fields') or []:
if not isinstance(field, dict):
continue
if str(field.get('field_id') or '') != field_id:
continue
pack_line = str(field.get('line_key') or '').strip() or None
if line_key and pack_line and pack_line != line_key:
continue
for snippet in field.get('snippets') or []:
if not isinstance(snippet, dict):
continue
snippet_line = str(snippet.get('line_key') or '').strip() or None
if line_key and snippet_line and snippet_line != line_key:
continue
quote = str(snippet.get('quote') or '').strip()
if not quote:
continue
if quote == needle or _token_boundary_match(quote, needle):
return True
return False
def _token_boundary_match(haystack: str, needle: str) -> bool:
"""
在单条 quote 内按 token 边界匹配 needle,避免 `10` 命中 `100`。
数字/字母数字连续串必须整段相等;其它文本使用单词边界。
"""
if not haystack or not needle:
return False
if haystack == needle:
return True
# 数值建议:只接受完整数字 token,禁止前缀/子串。
if re.fullmatch(r'[+-]?\d+(?:[.,]\d+)?', needle):
for token in re.findall(r'[+-]?\d+(?:[.,]\d+)?', haystack):
if token == needle:
return True
return False
pattern = r'(?<![\w.])' + re.escape(needle) + r'(?![\w.])'
return re.search(pattern, haystack) is not None
@@ -299,14 +299,44 @@ def _project_case_automation_status(
'job_id': int(job.id),
}
if latest is not None and str(latest.status or '').strip().lower() in {'failed', 'dead'}:
# [Phase 1-3] 从 Job.result_json 读取真实分类结果,不再写死 retryable=True。
# 旧 Job(改造前写入)result_json 可能为空或缺失字段 → 读不到时按旧投影给 safe 兜底。
result = latest.result_json if isinstance(latest.result_json, dict) else {}
raw_retryable = result.get('retryable')
if raw_retryable is None:
from app.services.shipping_notice.recovery_contract import (
is_tech_retryable_error as _is_tech,
)
error_code_hint = (
result.get('error_code')
or result.get('blocking_reason')
or result.get('reason_code')
or ''
)
raw_retryable = bool(_is_tech(error_code_hint)) if error_code_hint else True
retryable = bool(raw_retryable)
blocking_reason = (
result.get('blocking_reason')
or result.get('error_code')
or result.get('reason_code')
or 'stp_job_failed'
)
next_action = result.get('next_action')
details = result.get('blocking_reason_details') if isinstance(
result.get('blocking_reason_details'), dict,
) else None
return {
'status': 'failed',
'retryable': True,
'retryable': retryable,
'task_no': None,
'can_auto_create': can_auto,
'can_build': can_build,
'job_id': int(latest.id),
'reason_code': 'stp_job_failed',
'reason_code': blocking_reason,
'blocking_reason': blocking_reason,
'blocking_reason_details': details,
'next_action': next_action,
'error_code': result.get('error_code') or blocking_reason,
'retry_of_job_id': int(latest.id),
}
if latest is not None and str(latest.status or '').strip().lower() in {'succeeded', 'success', 'completed'}:
@@ -524,7 +554,7 @@ def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]:
else:
actions.append('edit_draft')
# 普通路径不投影 confirm;自动建单走 STP retry;本轮不提供 manual_create_fallback。
# STP 失败 / manual_fallback:可重试自动建单。
# STP 失败:按 recovery_contract 统一判定是否可技术重试,并按 blocking_reason 注入裁决动作。
automation = None
try:
automation = _project_case_automation_status(
@@ -534,10 +564,51 @@ def _allowed_actions(case: ShippingOrderReviewCase) -> list[str]:
)
except Exception: # noqa: BLE001
automation = None
if isinstance(automation, dict) and automation.get('retryable') and str(automation.get('status') or '') in {
auto_status = str((automation or {}).get('status') or '').strip().lower()
if isinstance(automation, dict) and auto_status in {
'failed', 'manual_fallback',
} and not case.confirmed_task_id:
actions.append('retry_stp_auto_create')
retryable_flag = automation.get('retryable')
blocking_reason = (
automation.get('blocking_reason')
or automation.get('reason_code')
or automation.get('error_code')
or ''
)
from app.services.shipping_notice.recovery_contract import (
derive_blocking_next_actions as _derive_next,
should_general_retry_be_removed as _should_remove_retry,
REMOVE_ACTIONS_WHEN_BLOCKED as _REMOVE_SET,
)
remove_retry = _should_remove_retry(
retryable_flag=retryable_flag,
blocking_reason=blocking_reason,
)
if not remove_retry and bool(retryable_flag):
actions.append('retry_stp_auto_create')
# [Phase 1-3] 注入裁决动作(如 adjudicate_duplicate、open_order_review),去重。
# [Phase 2-5] 在业务阻断对象上追加 reconcile_and_progress 作为统一对账恢复入口
# (与 derive 出的动作共存,前端可按动作码选择打开裁决面板或走自动化对账)。
_business_blocking = (
remove_retry or
(isinstance(blocking_reason, dict) and bool(blocking_reason.get('code'))) or
(isinstance(blocking_reason, str) and bool(blocking_reason))
)
if _business_blocking:
_bcode = (
blocking_reason.get('code') if isinstance(blocking_reason, dict) else blocking_reason
)
if _bcode and str(_bcode) not in {
'inventory_source_unresolved', 'inventory_shortage', 'inventory_match_incomplete',
'inventory_multi_file_conflict', 'order_review_required',
}:
if 'reconcile_and_progress' not in actions:
actions.append('reconcile_and_progress')
for _action in _derive_next(blocking_reason=blocking_reason):
if _action and _action not in actions:
actions.append(_action)
if remove_retry:
actions = [a for a in actions if a not in _REMOVE_SET]
if llm_review_enabled() and 'edit_draft' in actions:
actions.append('request_llm_suggestion')
return actions
@@ -679,15 +750,50 @@ def serialize_review_case(
elif isinstance(post_confirm, dict) and post_confirm.get('task_no'):
confirmed_task_no = str(post_confirm.get('task_no') or '')
validation_snapshot = dict(draft.validation_result_json or {}) if draft is not None else None
# [Phase 3] 共享 bundle:保证与 shipping-processing / conversation 卡片
# 对同一 Case 的 automation / available_actions / current_gate /
# blocking_reason / primary_action / user_status 六事实 100% 同源。
from app.services.shipping_notice.reconciliation_projector import (
project_review_case_projection_bundle,
)
bundle = project_review_case_projection_bundle(
case,
validation=validation_snapshot,
post_confirm=post_confirm if isinstance(post_confirm, dict) else None,
is_admin=is_admin,
)
# 旧字段 enrichment(owner_type / phase)保留,仅在 bundle.automation 基础上附加
automation = enrich_automation_status(
_project_case_automation_status(
case,
validation=validation_snapshot,
post_confirm=post_confirm if isinstance(post_confirm, dict) else None,
),
dict(bundle['automation']),
formal_ot=formal_ot,
is_admin=is_admin,
)
# process_gate 兜底:当既无 Execution 又无 post_confirm 建单前阶段时,
# 用 bundle.current_gate + user_status 合成 process_gate 占位,
# 保证两端 current_gate 完全一致,不再让前端猜。
if process_gate is None and execution is None:
cg = bundle.get('current_gate') or {}
if isinstance(cg, dict) and cg.get('gate_code'):
process_gate = {
'execution_no': None,
'status': 'running' if bundle.get('user_status') in {'running'} else (
'failed' if bundle.get('user_status') in {'failed', 'retryable'} else 'pending'
),
'current_blocking_gate': cg.get('blocking_reason_code'),
'technical_auto_only': True,
'owner_type': 'system',
'available_actions': list(cg.get('next_action_code') or bundle['available_actions'][:1]),
'gates_track': [
{
'gate_code': cg.get('gate_code'),
'status': 'blocked' if cg.get('blocking_reason_code') else 'pending',
'blocking_reason_code': cg.get('blocking_reason_code'),
'next_action_code': cg.get('next_action_code'),
},
],
}
from app.services.shipping_notice.order_review_customer_service import (
project_review_case_customer_resolution,
)
@@ -778,7 +884,8 @@ def serialize_review_case(
}
# task_missing:无恢复 API 时明确 view + contact_admin;防御性剥离残留 confirm。
available_actions = [a for a in _allowed_actions(case) if a != 'confirm']
available_actions = list(bundle['available_actions']) if bundle else [a for a in _allowed_actions(case) if a != 'confirm']
# 兼容兜底:task_missing 仍然优先固定视图动作。
if formal_ot.get('task_missing'):
available_actions = ['view', 'contact_admin']
@@ -870,6 +977,10 @@ def serialize_review_case(
'process_gate': process_gate,
'inventory_issue_fallback': inventory_issue_fallback,
'conversation_allowed_actions': conversation_allowed_actions,
# [Phase 3] 新增三字段:与 shipping-processing 列表端完全同源
'user_status': bundle.get('user_status') if bundle else None,
'blocking_reason': dict(bundle['blocking_reason']) if bundle and bundle.get('blocking_reason') else None,
'primary_action': dict(bundle['primary_action']) if bundle and bundle.get('primary_action') else None,
}
@@ -56,17 +56,17 @@ def compute_effective_reservation_id(
def default_derivation_rules() -> list[dict[str, Any]]:
"""
返回新草稿默认派生规则(启用状态)。
返回新草稿默认派生规则(关闭状态)。
核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=True,
内部项次为空时自动从客户 PO 行号派生;人工已锁定或目标有值时不覆盖。
核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=False,
避免未评审规则自动改写内部项次。
Returns:
可写入 definition_json.derivation_rules 的规则列表。
"""
return [{
'rule_id': DEFAULT_DERIVATION_RULE_ID,
'enabled': True,
'enabled': False,
'source_field_code': 'customer_po_line_no',
'target_field_code': 'line_no',
'strategy': 'copy_if_empty',
@@ -29,6 +29,9 @@ from app.models import (
from app.services.shipping_notice.candidate_qualification_service import (
recalculate_candidate_qualification,
)
from app.services.shipping_notice.document_layout.vc_source_candidate_conflicts import (
collect_vc_candidate_conflicts,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.order_review_confirmation_service import (
confirm_review_case,
@@ -348,6 +351,47 @@ def _xfa_stp_precheck(*, validation: dict[str, Any]) -> tuple[bool, str | None]:
return True, None
def _vc_stp_precheck(*, candidate: ShippingOrderCandidate | None) -> tuple[bool, str | None]:
"""
Vendor Comments 三来源建单前再次校验 VC 合并结果(防御 CQ 快照与实际抽取结果漂移)。
核心逻辑:
1. candidate 为空 → 放行(VC 未启用场景);
2. collect_vc_candidate_conflicts 结果中若存在 severity == blocking 的原因码 → 阻断;
3. review_required 的原因码 → 阻断自动建单(允许人工,不允许 STP);
4. 任何解析异常 → fail-closed 阻断自动建单。
Args:
candidate: Case 关联的当前 Candidate。
Returns:
(允许建单?, 阻断原因码);允许时 reason 为 None。
"""
if candidate is None:
return True, None
try:
items = collect_vc_candidate_conflicts(candidate)
except Exception as exc: # noqa: BLE001 — 门禁 fail-closed
_LOGGER.warning('vc_stp_precheck collect_vc_candidate_conflicts failed: %s', exc)
return False, 'vc_source_integration_error'
review_seen = False
for item in items:
if not isinstance(item, dict):
continue
reason = str(item.get('reason') or '').strip()
severity = str(item.get('severity') or 'blocking').strip()
if severity == 'blocking' or reason in {
'vc_source_region_unbound',
'vc_source_format_invalid',
}:
return False, reason or 'vc_source_blocking_conflict'
if severity == 'review_required' and not review_seen:
review_seen = True
if review_seen:
return False, 'vc_source_conflict_unresolved'
return True, None
def _traceability_metadata(
*,
run: ShippingOrderProcessingRun,
@@ -556,6 +600,40 @@ def ensure_stp_auto_create_for_case(
'error_code': 'SHIPPING.STP_NOT_ELIGIBLE',
}
vc_allowed, vc_block_reason = _vc_stp_precheck(candidate=candidate)
if not vc_allowed:
if case.status in {'unreviewed', 'draft', 'ready'}:
case.status = 'draft'
record_fulfillment_audit(
event_type='stp_auto_create_skipped',
aggregate_type='order_review_case',
aggregate_id=str(case.case_no),
action='stp_vc_conflict',
actor_type='system',
actor_id=None,
result='ignored',
metadata={
'run_no': str(resolved_run.run_no),
'reason_code': vc_block_reason,
'traceability': _traceability_metadata(
run=resolved_run, case=case, candidate=candidate, validation=validation,
),
},
source='stp_auto_create',
strict=True,
)
db.session.flush()
if commit:
db.session.commit()
return {
'case_no': case.case_no,
'status': 'skipped_needs_review',
'job_id': None,
'can_auto_create': False,
'blocking_reason_codes': [vc_block_reason] if vc_block_reason else [],
'error_code': 'SHIPPING.STP_NOT_ELIGIBLE',
}
if not (
validation.get('status') == 'ready'
and bool(validation.get('can_auto_create'))
@@ -890,52 +968,29 @@ def execute_stp_auto_create_job(*, payload: dict[str, Any], job_id: int) -> dict
}
# 注意:reconcile_run_review_cases_for_auto_progress 不在顶层 import,
# 避免 circular import。
# 环:order_review_auto_progress_coordinator 在运行时(延迟)import 本模块
# → 本模块顶层 import coordinator → coordinator 尚未完成初始化 → ImportError。
# 因此 reconcile_run_review_cases_for_auto_progress 延迟 import 到
# maybe_stp_auto_create_for_run 调用点。
def maybe_stp_auto_create_for_run(*, run: ShippingOrderProcessingRun) -> list[dict[str, Any]]:
"""
尝试对 Run 下未确认 Case 入队 STP 自动建单。
Run 级 STP 自动建单薄封装(向后兼容)。
核心逻辑:资格 ready 且无人工改脏 → ensure 写入幂等 Job(queued);
Worker 再执行 confirm。失败不阻断同 Run 其他 Case;幂等键保证只保留一条有效入队。
原内联逻辑已下沉至 reconcile_run_review_cases_for_auto_progress 统一协调:
客户指纹唯一确认 → Draft 校验 → STP 幂等入队;单 Case 异常局部 rollback。
保留本函数名与签名,防止 order_extraction.py 中 4 处调用点 break。
Args:
run: 已 ensure_run_review_cases 的抽取 Run。
run: 已 ensure_run_review_cases 的抽取 Processing Run。
Returns:
每个尝试过的 Case 摘要列表。
"""
results: list[dict[str, Any]] = []
case_ids = [
int(row.id)
for row in (
ShippingOrderReviewCase.query
.filter_by(run_id=int(run.id))
.order_by(ShippingOrderReviewCase.id.asc())
.with_entities(ShippingOrderReviewCase.id)
.all()
)
]
for case_id in case_ids:
case = db.session.get(ShippingOrderReviewCase, case_id)
if case is None:
continue
try:
results.append(
ensure_stp_auto_create_for_case(
case=case,
run=run,
commit=True,
refresh_validation=True,
)
)
except Exception as exc: # noqa: BLE001
_LOGGER.exception('STP enqueue failed for case_id=%s', case_id)
try:
db.session.rollback()
except Exception: # noqa: BLE001
pass
results.append({
'case_no': getattr(case, 'case_no', None),
'status': 'enqueue_failed',
'error': str(exc)[:300],
})
return results
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_run_review_cases_for_auto_progress,
)
return reconcile_run_review_cases_for_auto_progress(run)
@@ -0,0 +1,643 @@
"""
services/shipping_notice/per_source_rpa_service.py
用途:逐 (task_no, source_code) 维度的库存 RPA Attempt 结构化管理(决策 D1/D2/D3)。
依赖:models.ShippingTaskInventoryRpaAttempt、inventory_candidate_freeze_service(取候选源)、
rpa.write_inventory_export_trigger_for_task(trigger 文件写入)、
inventory_snapshot_store(快照复用判断)。
逻辑:T4 新增的结构化表是正式 Attempt 计数真相;旧的 ShippingTaskEvent 统计作为兼容层,
新的调用方(auto_progress Orchestrator、Gate handler、回调入口)逐步迁移到本模块。
三元组 (task_no, source_code, run_no) 幂等定位;迟到回调标记 superseded 不回写业务。
"""
from __future__ import annotations
import hashlib
import json
import os
import uuid
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any
from sqlalchemy import and_, func, or_
from sqlalchemy.orm import Session
from app import db
from app.models import (
ShippingInventoryFile,
ShippingNotice,
ShippingTaskInventoryRpaAttempt,
)
from app.services.shipping_notice.stp_inventory_freeze import (
task_frozen_inventory_source_codes,
)
from app.services.shipping_notice.inventory_snapshot_store import (
find_latest_ready_snapshot,
is_snapshot_fresh,
)
from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task
from app.services.shipping_notice.rpa_attempts import max_rpa_inventory_attempts
def _attempt_ref_has_ready_snapshot(
attempt: ShippingTaskInventoryRpaAttempt,
*,
session: Session | None = None,
) -> bool:
"""Attempt 状态 succeeded/consumed 时,二次验证 inventory_file_no 对应快照真实存在且 ready。
防止 Attempt 状态与实际快照不同步(TTL 过期、文件被删、异步 ingest 未完成)时
被误判为 prepared 而绕过有效库存门禁。
"""
sess = session or db.session
file_no = str(getattr(attempt, 'inventory_file_no', '') or '').strip()
if not file_no:
return False
inv_file = (
sess.query(ShippingInventoryFile)
.filter(ShippingInventoryFile.inventory_file_no == file_no)
.one_or_none()
)
return is_snapshot_fresh(inv_file)
PER_SOURCE_RUN_NO_PREFIX = 'PSR' # Per-Source Run,区别于 legacy T-xxx 全局 run_no
@dataclass
class PerSourcePrepareResult:
"""ensure_all_required_sources_prepared 返回值——聚合所有源的逐源状态 + 总体结论。"""
task_no: str
all_prepared: bool
prepared_source_codes: list[str]
pending_source_codes: list[str]
failed_source_codes: list[str]
source_attempts: dict[str, dict[str, Any]] # source_code → {attempt_no, status, run_no, error}
def _per_source_run_no(attempt: ShippingTaskInventoryRpaAttempt) -> str:
"""构造 per-source 三元组唯一 run_no:PSR-<task_no>-<SOURCE>-<attempt_no>-<uuid8>。"""
suffix = uuid.uuid4().hex[:8].upper()
return f'{PER_SOURCE_RUN_NO_PREFIX}-{attempt.task_no}-{attempt.source_code}-A{attempt.attempt_no}-{suffix}'
def _latest_attempt(
task_no: str,
source_code: str,
*,
session: Session | None = None,
) -> ShippingTaskInventoryRpaAttempt | None:
"""查询 (task, source) 维度最新的 Attempt(按 attempt_no desc, id desc)。"""
sess = session or db.session
return (
sess.query(ShippingTaskInventoryRpaAttempt)
.filter(
and_(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.source_code == source_code,
)
)
.order_by(
ShippingTaskInventoryRpaAttempt.attempt_no.desc(),
ShippingTaskInventoryRpaAttempt.id.desc(),
)
.first()
)
def _consumed_run_nos(
task_no: str,
source_code: str,
*,
session: Session | None = None,
) -> set[str]:
"""查询 (task, source) 维度已 consumed/superseded 的 run_no 集合,用于回调幂等/迟到判断。"""
sess = session or db.session
rows = (
sess.query(ShippingTaskInventoryRpaAttempt.run_no)
.filter(
and_(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.source_code == source_code,
ShippingTaskInventoryRpaAttempt.status.in_(('consumed', 'superseded')),
)
)
.all()
)
return {r[0] for r in rows if r and r[0]}
def _next_attempt_no(
task_no: str,
source_code: str,
*,
session: Session | None = None,
) -> int:
"""
计算 (task, source) 维度下一次 attempt_no(自上次 succeeded/consumed 之后的计数)。
自成功事件重置逻辑兼容 rpa_attempts.py 的事件统计语义,但基于结构化表计算。
"""
sess = session or db.session
last_success = (
sess.query(ShippingTaskInventoryRpaAttempt)
.filter(
and_(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.source_code == source_code,
ShippingTaskInventoryRpaAttempt.status.in_(('succeeded', 'consumed')),
)
)
.order_by(ShippingTaskInventoryRpaAttempt.attempt_no.desc())
.first()
)
base_no = last_success.attempt_no if last_success else 0
subsequent_count = (
sess.query(func.count(ShippingTaskInventoryRpaAttempt.id))
.filter(
and_(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.source_code == source_code,
ShippingTaskInventoryRpaAttempt.attempt_no > base_no,
)
)
.scalar()
or 0
)
return base_no + int(subsequent_count) + 1
def _trigger_filename(task_no: str, source_code: str, attempt_no: int) -> str:
"""
新的 per-source trigger 文件名:SN-<task_no>__<SOURCE_CODE>__A<attempt_no>.trigger.json
与 legacy 文件名(无 __SOURCE 后缀)并行不冲突,RPA Worker 按 __ 分割识别 source_code。
"""
return f'SN-{task_no}__{source_code.upper()}__A{attempt_no}.trigger.json'
def _snapshot_ready_for_source(
source_code: str,
*,
rpa_source: dict[str, Any],
task: ShippingNotice,
session: Session | None = None,
) -> bool:
"""判断某源是否已有有效快照(复用路径,命中则不触发 RPA)。"""
try:
warehouse_id = (
str(rpa_source.get('fixed_warehouse_id')).strip().upper() or None
if isinstance(rpa_source, dict)
and str(rpa_source.get('warehouse_resolution_mode') or '').lower() == 'fixed'
else None
)
snap = find_latest_ready_snapshot(source_code, warehouse_id)
except Exception:
snap = None
return snap is not None
def _attempts_summary(
task_no: str,
*,
source_codes: list[str],
session: Session | None = None,
) -> dict[str, dict[str, Any]]:
"""汇总各源的最新 Attempt 状态(供前端 Projection.facts 消费)。"""
result: dict[str, dict[str, Any]] = {}
for code in source_codes:
att = _latest_attempt(task_no, code, session=session)
result[code] = {
'attempt_no': att.attempt_no if att else 0,
'status': att.status if att else 'not_started',
'run_no': att.run_no if att else None,
'error_code': att.error_code if att else None,
'error_message': att.error_message if att else None,
}
return result
def ensure_all_required_sources_prepared(
task: ShippingNotice,
*,
mode: str = 'auto',
session: Session | None = None,
) -> PerSourcePrepareResult:
"""
遍历 frozen 候选库存源,逐源 check 快照;未命中则触发 RPA(每源独立 attempt_no/run_no)。
【AI 触发时机】:inventory_preparation Gate handler、AutoProgress Orchestrator 库存准备阶段调用。
核心逻辑:
[STEP 1] 从 T3 冻结表/兼容 step_payload 读取候选 source_codes(保序)。
[STEP 2] 对每个 source:
a. 先 try reuse snapshot(find_latest_ready_snapshot)→ 命中则 source ∈ prepared
b. 否则检查 (task, source) 当前最新 Attempt 状态:
- queued/running → pending(仍在等待)
- succeeded/consumed → 已 prepared
- failed 且 attempt_no < max_attempts → 触发下一 attempt(queued 新 run)
- failed 且 attempt_no ≥ max_attempts → failed(不自动再触发)
- 从未 attempt → 触发 attempt_no=1
c. 写 ShippingTaskInventoryRpaAttempt 记录 + trigger 文件
Args:
task: 已冻结候选的任务(inventory_source_status ∈ STABLE)。
mode: 'auto' = Orchestrator 自动推进;'retry_rpa' = 用户显式强制重试(跳过复用快照)。
session: 可选 Session。
Returns:
PerSourcePrepareResult:总体 all_prepared 状态 + 已/待/失败源列表 + 各源 Attempt 摘要。
"""
task_no = str(task.task_no or '').strip()
sess = session or db.session
source_codes = task_frozen_inventory_source_codes(task)
if not source_codes:
return PerSourcePrepareResult(
task_no=task_no, all_prepared=False,
prepared_source_codes=[], pending_source_codes=[],
failed_source_codes=[], source_attempts={},
)
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
prepared: list[str] = []
pending: list[str] = []
failed: list[str] = []
for source_code in source_codes:
rpa_source = get_database_inventory_source(source_code) or {'source_code': source_code}
# 复用快照(retry_rpa 模式跳过,强制重新触发)
if mode != 'retry_rpa' and _snapshot_ready_for_source(source_code, rpa_source=rpa_source, task=task, session=sess):
prepared.append(source_code)
continue
att = _latest_attempt(task_no, source_code, session=sess)
current_status = att.status if att else None
if current_status in ('queued', 'running'):
pending.append(source_code)
continue
# 题2B 服务层并发双保险:_latest_attempt 可能读到缓存/旧事务;此处在创建前重新 SELECT ... FOR UPDATE
# 再次确认 (task_no, source_code) 的最新状态不为 queued/running,避免“双请求同时通过 _latest_attempt,
# 都判成 failed → 都创建新 Attempt”的竞态。仍以 DB 部分唯一索引作为最后兜底。
if mode == 'retry_rpa' or (current_status == 'failed'):
from app.models.shipping_task_inventory_rpa_attempts import (
ShippingTaskInventoryRpaAttempt as _Attempt2,
)
q = (
sess.query(_Attempt2)
.filter(_Attempt2.task_no == task_no)
.filter(_Attempt2.source_code == source_code)
.order_by(_Attempt2.attempt_no.desc())
.limit(1)
)
try:
double_check = q.with_for_update(key_share=True).first()
except Exception: # noqa: BLE001
double_check = q.first()
if double_check and str(double_check.status or '').strip().lower() in {'queued', 'running'}:
pending.append(source_code)
continue
if double_check is not None and double_check is not att:
current_status = double_check.status
att = double_check
if current_status in ('succeeded', 'consumed') and att and _attempt_ref_has_ready_snapshot(att, session=sess):
prepared.append(source_code)
continue
max_attempts = max_rpa_inventory_attempts()
next_att_no = _next_attempt_no(task_no, source_code, session=sess)
if att and current_status == 'failed' and next_att_no - 1 >= max_attempts and mode != 'retry_rpa':
# 自动模式不触发超过 max_attempts 的重试,交由用户手动
failed.append(source_code)
# 标记 exhausted 方便后续展示(不重复 commit,外层调用方可 flush)
if att and att.status != 'exhausted':
att.status = 'exhausted'
att.error_code = att.error_code or 'attempts_exhausted'
att.updated_at = datetime.utcnow()
sess.flush([att])
continue
# [STEP 2c] 新建 Attempt + 写 trigger 文件
new_att = ShippingTaskInventoryRpaAttempt(
task_no=task_no,
source_code=source_code,
attempt_no=next_att_no,
source_run_no='', # 先写占位,构造 source_run_no 需要 id/attempt_no 稳定
status='queued',
triggered_at=datetime.utcnow(),
lease_token=uuid.uuid4().hex,
execution_phase='trigger_written',
extra_json={'trigger_mode': mode},
)
sess.add(new_att)
sess.flush([new_att])
new_att.source_run_no = _per_source_run_no(new_att)
sess.flush([new_att])
trigger_fname = _trigger_filename(task_no, source_code, next_att_no)
try:
# 复用旧 write_inventory_export_trigger_for_task 内部逻辑,但覆写其生成的文件名
# (旧函数会按 task 级写 trigger;此处先调旧函数保证 payload 完整,再尝试重命名。)
#
# [T4 兼容策略] 先不修改 rpa.py 避免影响单源任务旧链路;RPA Worker 增加按 source_code 识别
# trigger 文件的逻辑,文件名同时带 __SOURCE_CODE__A<N> 后缀即可。
# 这里的 trigger_file_path 仅作为审计字段记录,实际触发由 Worker 按目录扫描识别。
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
legacy_rpa_source = task_rpa_inventory_source(task) or dict(rpa_source)
# 强制注入 source_code 覆盖旧 task 级单源字段,使 RPA Worker 可按 per-source 执行
per_source_payload = {
'schema_version': 'shipping_inventory_rpa.v2',
'mode': mode,
'attempt': next_att_no,
'attempt_no': next_att_no,
'source_code': source_code,
'source_run_no': new_att.source_run_no,
'batch_run_no': f'BATCH-{task_no}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}',
'lease_token': new_att.lease_token,
'per_source_attempt': True,
}
trigger_result = write_inventory_export_trigger_for_task(
task_no,
dict(legacy_rpa_source, **{'source_code': source_code}),
payload=per_source_payload,
)
if trigger_result:
new_att.trigger_file_path = str(trigger_result)
else:
new_att.trigger_file_path = trigger_fname
pending.append(source_code)
except Exception as exc: # pragma: no cover - RPA 环境异常
new_att.status = 'failed'
new_att.error_code = 'trigger_write_error'
new_att.error_message = f'{type(exc).__name__}: {str(exc)[:500]}'
new_att.updated_at = datetime.utcnow()
failed.append(source_code)
finally:
sess.flush([new_att])
summary = _attempts_summary(task_no, source_codes=source_codes, session=sess)
all_ok = len(prepared) == len(source_codes) and not pending and not failed
return PerSourcePrepareResult(
task_no=task_no,
all_prepared=all_ok,
prepared_source_codes=list(prepared),
pending_source_codes=list(pending),
failed_source_codes=list(failed),
source_attempts=summary,
)
def per_source_callback_handler(
task: ShippingNotice,
*,
source_code: str,
run_no: str,
callback_payload: dict[str, Any],
session: Session | None = None,
) -> tuple[str, ShippingTaskInventoryRpaAttempt | None]:
"""
处理 per-source 库存 RPA 回调(三元组幂等 + 迟到保护 + Task 全局状态保护)。
【AI 触发时机】:RPA Dropzone 回调入口、手动 ingest API、Worker 补录回调统一调用本函数。
核心逻辑:
[STEP 1] 三元组 (task_no, source_code, run_no) 定位 Attempt;不存在 → return 'not_found'
[STEP 2] 幂等:Attempt.status == succeeded/consumed/superseded → return 'idempotent_ok'
[STEP 3] 迟到保护:若同 (task, source) 已有 run_no > 当前 run_no 已 consumed/superseded → 标记 superseded 不回写快照,return 'superseded_late'
[STEP 4] Task 全局终态保护:Task.status ∈ {completed, cancelled, failed_terminal} → 回调不写任何业务表,标记 late_callback_ignored(audit),return 'task_terminal'
[STEP 5] 校验通过:写 status=succeeded(成功)或 failed(回调含 error_code),回填 callback_payload_json / inventory_file_no / callback_file_path
[STEP 6] 返回处理结果(供调用方决定是否推进 Orchestrator)。
Args:
task: 发货任务实例。
source_code: 库存源编码(大写)。
run_no: 回调中携带的 PSR-* 三元组 run_no。
callback_payload: 回调原始 payload(JSONB 存储)。
session: 可选 Session。
Returns:
(result_code: str, attempt: ShippingTaskInventoryRpaAttempt | None)
result_code ∈ {not_found, idempotent_ok, superseded_late, task_terminal, succeeded, failed}
"""
sess = session or db.session
task_no = str(task.task_no or '').strip()
source_code_up = str(source_code or '').strip().upper()
# [STEP 1] 三元组定位
attempt = (
sess.query(ShippingTaskInventoryRpaAttempt)
.filter(
and_(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.source_code == source_code_up,
ShippingTaskInventoryRpaAttempt.run_no == run_no,
)
)
.one_or_none()
)
if attempt is None:
return 'not_found', None
# [STEP 2] 幂等
if attempt.status in ('succeeded', 'consumed', 'superseded'):
return 'idempotent_ok', attempt
# [STEP 3] 迟到保护:同 (task, source) 有更新 run 已终态
consumed_runs = _consumed_run_nos(task_no, source_code_up, session=sess)
# Run no format: PSR-<task>-<SOURCE>-A<N>-<uuid> → 排序按 attempt_no 前缀即可
try:
current_attempt_no = int(attempt.attempt_no)
except (TypeError, ValueError):
current_attempt_no = 0
newer_count = (
sess.query(func.count(ShippingTaskInventoryRpaAttempt.id))
.filter(
and_(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.source_code == source_code_up,
ShippingTaskInventoryRpaAttempt.attempt_no > current_attempt_no,
ShippingTaskInventoryRpaAttempt.status.in_(('consumed', 'superseded', 'succeeded')),
)
)
.scalar()
or 0
)
if newer_count > 0:
attempt.status = 'superseded'
attempt.callback_payload_json = dict(callback_payload or {})
attempt.callback_received_at = datetime.utcnow()
attempt.updated_at = datetime.utcnow()
sess.flush([attempt])
return 'superseded_late', attempt
# [STEP 4] Task 已终态(兼容旧枚举 active/blocked 等非终态)
terminal_statuses = {'completed', 'cancelled', 'failed_terminal'}
if str(getattr(task, 'process_status', '') or '').strip() in terminal_statuses:
attempt.status = 'superseded'
attempt.extra_json = dict(attempt.extra_json or {}, late_callback_ignored=True, reason='task_terminal')
attempt.callback_payload_json = dict(callback_payload or {})
attempt.callback_received_at = datetime.utcnow()
attempt.updated_at = datetime.utcnow()
sess.flush([attempt])
return 'task_terminal', attempt
# [STEP 5] 写回调结果
attempt.callback_payload_json = dict(callback_payload or {})
attempt.callback_received_at = datetime.utcnow()
attempt.callback_id = str(callback_payload.get('callback_id') or '').strip() or attempt.callback_id
attempt.file_generated = bool(callback_payload.get('file_path'))
attempt.file_path = str(callback_payload.get('file_path') or '').strip() or attempt.file_path
attempt.file_exists_at_callback = bool(attempt.file_path and __import__('pathlib').Path(attempt.file_path).is_file())
attempt.execution_phase = 'callback_received'
attempt.updated_at = datetime.utcnow()
attempt.callback_file_path = str(callback_payload.get('callback_file_path') or '').strip() or None
inventory_file_no = str(callback_payload.get('inventory_file_no') or '').strip() or None
if inventory_file_no:
attempt.inventory_file_no = inventory_file_no
error_code = str(callback_payload.get('error_code') or '').strip() or None
error_message = str(callback_payload.get('error_message') or '').strip() or None
if error_code:
attempt.status = 'failed'
attempt.transaction_status = 'rejected'
attempt.error_code = error_code
attempt.error_message = error_message[:2000] if error_message else None
sess.flush([attempt])
return 'failed', attempt
# 回调标称成功,但必须二次验证快照已真实入库且 ready,否则仍然算失败(防止 RPA 伪成功)
if inventory_file_no:
_inv = (
sess.query(ShippingInventoryFile)
.filter(ShippingInventoryFile.inventory_file_no == inventory_file_no)
.one_or_none()
)
if _inv is None or not is_snapshot_fresh(_inv):
attempt.status = 'failed'
attempt.execution_phase = 'transaction_failed'
attempt.transaction_status = 'transaction_failed'
attempt.transaction_error_code = 'snapshot_not_ready_after_callback'
attempt.error_code = 'snapshot_not_ready_after_callback'
missing_reason = (
'inventory_file record not found'
if _inv is None
else f"snapshot not ready (status={_inv.snapshot_status}, "
f"path_exists={__import__('pathlib').Path(_inv.storage_path).is_file()})"
)
attempt.error_message = (
f"回调返回成功但关联库存快照未通过门禁校验:{missing_reason}"[:2000]
)
sess.flush([attempt])
return 'failed', attempt
attempt.status = 'succeeded'
attempt.transaction_status = 'succeeded'
sess.flush([attempt])
# 回调只改变 Attempt/Snapshot 事实;正式 Task Gate 由 AutoProgress Job 重新校验。
# 调用方在同一事务提交后,Job 才对 Worker 可见。
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
submit_auto_progress(task=task, trigger='inventory_rpa_callback_succeeded', commit=False)
return 'succeeded', attempt
def claim_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
"""记录 Worker 领取的逐源 Attempt,不推进 Snapshot、Link 或 Gate。"""
if payload.get('schema_version') != 'shipping_inventory_rpa.v2' or not isinstance(payload.get('items'), list):
return {'transport_status': 'invalid', 'business_status': 'rejected', 'error_code': 'callback_schema_invalid'}
worker_id = str(payload.get('worker_id') or '').strip() or None
now = datetime.utcnow()
results: list[dict[str, Any]] = []
for item in payload['items']:
if not isinstance(item, dict):
results.append({'business_status': 'rejected', 'error_code': 'callback_schema_invalid'})
continue
task_no = str(item.get('task_no') or '').strip()
source_code = str(item.get('source_code') or '').strip().upper()
source_run_no = str(item.get('source_run_no') or '').strip()
lease_token = str(item.get('lease_token') or '').strip()
attempt = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(
task_no=task_no, source_code=source_code, source_run_no=source_run_no,
).one_or_none()
if attempt is None or str(attempt.lease_token or '') != lease_token:
results.append({'task_no': task_no, 'source_code': source_code, 'source_run_no': source_run_no,
'business_status': 'rejected', 'error_code': 'callback_identity_mismatch'})
continue
if attempt.status in ('succeeded', 'consumed', 'superseded'):
results.append({'task_no': task_no, 'source_code': source_code, 'source_run_no': source_run_no,
'business_status': 'succeeded', 'replayed': True})
continue
attempt.status = 'running'
attempt.execution_phase = 'worker_claimed'
attempt.claimed_at = now
attempt.worker_id = worker_id
attempt.updated_at = now
results.append({'task_no': task_no, 'source_code': source_code, 'source_run_no': source_run_no,
'business_status': 'succeeded'})
db.session.flush()
return {'transport_status': 'received', 'batch_status': 'partial_failed' if any(r.get('business_status') == 'rejected' for r in results) else 'succeeded', 'items': results}
def per_source_timeout_scan(
task: ShippingNotice,
*,
timeout_seconds: int,
session: Session | None = None,
) -> dict[str, Any]:
"""
扫描 (task, source) 维度的超时 Attempt,对过期 running/queued 标记 failed 并写错误信息。
【AI 触发时机】:AutoProgress 轮询间隔、batch_orchestrator 巡检、Worker 启动 stale scan 调用。
Args:
task: 发货任务。
timeout_seconds: 单源 RPA 超时(秒);超过 triggered_at 或 leased_at 阈值未回调即失败。
session: 可选 Session。
Returns:
{'timed_out_count': int, 'details': {source_code: {attempt_no, elapsed, prev_status}}}
"""
sess = session or db.session
task_no = str(task.task_no or '').strip()
threshold = datetime.utcnow() - timedelta(seconds=max(int(timeout_seconds), 1))
candidates = (
sess.query(ShippingTaskInventoryRpaAttempt)
.filter(
and_(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
or_(
ShippingTaskInventoryRpaAttempt.triggered_at <= threshold,
ShippingTaskInventoryRpaAttempt.leased_at <= threshold,
ShippingTaskInventoryRpaAttempt.created_at <= threshold,
),
)
)
.all()
)
details: dict[str, dict[str, Any]] = {}
for att in candidates:
elapsed = int((datetime.utcnow() - (att.triggered_at or att.created_at)).total_seconds())
prev_status = att.status
trigger_path = str(att.trigger_file_path or '').strip()
trigger_missing = bool(
prev_status == 'queued'
and trigger_path
and not os.path.isfile(trigger_path)
)
att.status = 'failed'
att.error_code = 'trigger_not_claimed_missing' if trigger_missing else 'per_source_timeout'
att.error_message = (
f'Attempt 已排队 {elapsed}s,但 Trigger 文件不存在,Worker 未领取'
if trigger_missing
else f'等待 {elapsed}s 超过阈值 {timeout_seconds}s(状态 {prev_status})'
)
att.updated_at = datetime.utcnow()
sess.flush([att])
details[att.source_code] = {
'attempt_no': att.attempt_no,
'elapsed_seconds': elapsed,
'prev_status': prev_status,
'reason_code': att.error_code,
'trigger_file_path': trigger_path or None,
}
return {'timed_out_count': len(details), 'details': details}
@@ -388,6 +388,9 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
'order_extraction_cancelled',
'evidence_missing',
'required_field_missing',
'final_required_field_missing',
'profile_schema_mismatch',
'row_needs_review',
'reservation_invalid',
'reservation_missing',
'reservation_duplicate',
@@ -484,6 +487,7 @@ PROCESS_GATE_BLOCKING_REASON_CODES: Final[frozenset[str]] = frozenset({
'xfa_visual_not_publishable',
'xfa_visual_bindings_required',
'xfa_visual_binding_incomplete',
'xfa_source_mapping_incomplete',
# 跨门禁技术重试耗尽(不绑定唯一 owning_gate,由当前 Gate 承载)
'technical_retry_exhausted',
})
@@ -500,6 +504,10 @@ PROCESS_GATE_REASON_OWNING_GATE: Final[dict[str, str]] = {
'order_extraction_cancelled': 'order_field_extraction',
'evidence_missing': 'order_field_extraction',
'required_field_missing': 'field_completeness',
'final_required_field_missing': 'field_completeness',
'profile_schema_mismatch': 'document_profile_routing',
'row_needs_review': 'order_field_extraction',
'xfa_source_mapping_incomplete': 'order_field_extraction',
'reservation_invalid': 'reservation_validation',
'reservation_missing': 'reservation_validation',
'reservation_duplicate': 'reservation_validation',
@@ -775,4 +783,294 @@ def assert_process_gate_contract_integrity() -> None:
assert len(owned_reasons) == len(set(owned_reasons)), 'duplicate reason ownership'
for legacy_key, gate in AUTO_BUILD_LEGACY_GATE_OWNING_MAP.items():
assert gate in PROCESS_GATE_CODE_SET, f'legacy auto-build key {legacy_key} maps to unknown gate'
assert gate in PROCESS_GATE_CODE_SET, f'legacy auto-build key {legacy_key} maps to unknown gate {gate}'
# [USER_STATE_CONTRACT] 校验 Gate.status / Execution.status / reason_code 与用户态的映射闭环
for gate_status in PROCESS_GATE_STATUSES:
assert gate_status in GATE_STATUS_TO_USER_STATUS, (
f'gate status {gate_status} missing in GATE_STATUS_TO_USER_STATUS'
)
for exec_status in PROCESS_EXECUTION_STATUSES:
assert exec_status in EXECUTION_STATUS_TO_USER_STATUS, (
f'execution status {exec_status} missing in EXECUTION_STATUS_TO_USER_STATUS'
)
for reason in PROCESS_GATE_BLOCKING_REASON_CODES:
if reason == 'technical_retry_exhausted':
# 跨门禁技术原因码,可豁免精确分类,默认为 terminal_failed
continue
assert reason in BLOCKING_REASON_TO_USER_MODE, (
f'blocking reason {reason} missing in BLOCKING_REASON_TO_USER_MODE'
)
mode = BLOCKING_REASON_TO_USER_MODE[reason]
assert mode in BLOCKING_REASON_USER_MODES, (
f'reason {reason} invalid user mode {mode}'
)
# [INVENTORY_SUB_STAGE_CONTRACT] 校验库存 4 主 Gate 的 sub_stage 命名已在白名单
for gate_code in INVENTORY_MAIN_GATES:
assert gate_code in PROCESS_GATE_CODE_SET, f'unknown inventory main gate {gate_code}'
for name in INVENTORY_SUB_STAGES:
assert name in INVENTORY_SUB_STAGES, f'inventory sub_stage {name} not in whitelist'
# ============================================================
# 用户态状态契约(v1)
# 决策1 / F2:底层不迁移,仅在 Projection 层统一映射。
# 所有前端、Chatflow、任务中心只读 USER_FACING_TASK_STATUSES。
# ============================================================
USER_FACING_TASK_STATUSES: Final[frozenset[str]] = frozenset({
'running',
'waiting_human',
'retryable',
'failed',
'completed',
'cancelled',
})
# Gate.status → 用户态主状态。
# 规则:
# pending/queued/running/passed/skipped/invalidated → running(交给执行驱动)
# blocked_manual → waiting_human(人工门禁)
# blocked_retryable → retryable(技术/外部暂态失败,可重试)
# waiting_external → running(等待回调,用户感知为处理中)
# failed_terminal → failed(不可自动恢复的终态失败)
GATE_STATUS_TO_USER_STATUS: Final[dict[str, str]] = {
'pending': 'running',
'queued': 'running',
'running': 'running',
'passed': 'running',
'blocked_retryable': 'retryable',
'blocked_manual': 'waiting_human',
'waiting_external': 'running',
'failed_terminal': 'failed',
'invalidated': 'running',
'skipped': 'running',
}
# Execution.status → 用户态主状态。
# 当 Gate 信息缺失时,作为 Projection 的回退层。
# active/waiting_external → running
# blocked → retryable(Proj 再结合 Gate 细分,此处不放大为 waiting_human)
# completed → completed;cancelled → cancelled;failed → failed
EXECUTION_STATUS_TO_USER_STATUS: Final[dict[str, str]] = {
'active': 'running',
'blocked': 'retryable',
'waiting_external': 'running',
'completed': 'completed',
'cancelled': 'cancelled',
'failed': 'failed',
}
# 阻断原因码 → 用户处置模式。用于 retryable / primary_action 推导。
# 禁止前端或 Projection 层各写一份 reason→action 的 switch-case。
BLOCKING_REASON_USER_MODES: Final[frozenset[str]] = frozenset({
'retryable_tech', # 技术/外部系统失败,可自动或用户点击重试
'needs_human', # 需要人工决策或提供输入
'terminal_failed', # 业务或配置终态失败,普通重试无意义
})
BLOCKING_REASON_TO_USER_MODE: Final[dict[str, str]] = {
# --- 文档/抽取/路由/通用 ---
'document_unavailable': 'retryable_tech',
'layout_parse_failed': 'retryable_tech',
'profile_ambiguous': 'needs_human',
'profile_drift': 'retryable_tech',
'profile_not_matched': 'needs_human',
'extraction_incomplete': 'needs_human',
'order_extraction_failed': 'retryable_tech',
'order_extraction_cancelled': 'terminal_failed',
'evidence_missing': 'needs_human',
'required_field_missing': 'needs_human',
'final_required_field_missing': 'needs_human',
'profile_schema_mismatch': 'needs_human',
'row_needs_review': 'needs_human',
'xfa_source_mapping_incomplete': 'needs_human',
'reservation_invalid': 'needs_human',
'reservation_missing': 'needs_human',
'reservation_duplicate': 'needs_human',
'customer_unresolved': 'needs_human',
'customer_ambiguous': 'needs_human',
'duplicate_unresolved': 'needs_human',
'field_conflict': 'needs_human',
'cross_source_conflict': 'needs_human',
'pdf_preferred_critical_conflict': 'needs_human',
'pdf_preferred': 'needs_human',
'classification_low_confidence': 'needs_human',
'field_low_confidence': 'needs_human',
'extraction_emergency_stop': 'terminal_failed',
'run_failed': 'retryable_tech',
'run_cancelled': 'terminal_failed',
'technical_failure_present': 'retryable_tech',
'gate_invalidated': 'retryable_tech',
'lease_conflict': 'retryable_tech',
'version_conflict': 'retryable_tech',
'not_recoverable': 'terminal_failed',
'unit_review_required': 'needs_human',
'budget_stopped': 'terminal_failed',
'technical_retry_exhausted': 'terminal_failed',
# --- 库存源路由(多库存源为合法链路,除非以下原因才阻断)---
'no_inventory_source_candidates': 'needs_human', # 零候选
'require_manual_review': 'needs_human', # 规则明确要求人工
'inventory_source_unavailable': 'needs_human', # 候选源配置被禁用(需人工改路由)
'inventory_source_conflicted': 'needs_human', # 路由规则冲突
'inventory_source_changed': 'retryable_tech', # 配置漂移,可重跑规则
'inventory_source_identity_mismatch': 'needs_human', # 仓库身份不匹配,需人工确认
'retry_with_latest_rules': 'retryable_tech',
# --- 库存准备 / RPA ---
'inventory_preparation_failed': 'retryable_tech',
'inventory_preparation_waiting': 'retryable_tech',
'inventory_rpa_queued': 'retryable_tech',
'inventory_rpa_timeout': 'retryable_tech',
'inventory_rpa_login_failed': 'retryable_tech',
'inventory_rpa_export_failed': 'retryable_tech',
'inventory_rpa_exhausted': 'needs_human', # RPA 重试耗尽 → 人工上传
'inventory_file_missing': 'retryable_tech',
'inventory_file_empty': 'retryable_tech',
'inventory_file_identity_mismatch': 'needs_human',
# --- 库存字段映射 ---
'inventory_mapping_required': 'needs_human',
'inventory_required_column_missing': 'needs_human',
'inventory_column_ambiguous': 'needs_human',
# --- 库存匹配(短缺/冲突/未找到都是人工门禁;retryable 仅技术类)---
'inventory_match_failed': 'retryable_tech',
'inventory_multi_file_conflict': 'needs_human', # 跨源冲突
'inventory_sku_not_found': 'needs_human', # 料号未命中 → 短缺/未找到
'inventory_reservation_not_found': 'needs_human', # 预约单未命中 → 短缺
'inventory_warehouse_mismatch': 'needs_human',
'inventory_insufficient': 'needs_human', # 短缺 → shortage_review
'inventory_shortage_review_required': 'needs_human',
# --- 订单冻结 / 建单 / 通用 feature flag ---
'freeze_not_ready': 'retryable_tech',
'profile_not_auto_freeze_approved': 'needs_human',
'profile_manual_confirmation_required': 'needs_human',
'profile_auto_freeze_qualification_missing': 'needs_human',
'profile_auto_freeze_suspended': 'needs_human',
'customer_confirmation_required': 'needs_human',
'customer_scope_unmatched': 'needs_human',
'customer_scope_not_configured': 'terminal_failed',
'customer_scope_out_of_scope': 'terminal_failed',
'multiple_customers_detected': 'needs_human',
'multiple_profiles_detected': 'needs_human',
'business_scenario_unmatched': 'needs_human',
'business_scenario_not_configured': 'terminal_failed',
'business_scenario_out_of_scope': 'terminal_failed',
'generic_auto_freeze_disabled': 'needs_human',
'llm_path_cannot_auto_freeze': 'needs_human',
'auto_freeze_not_enabled': 'needs_human',
'auto_create_disabled': 'needs_human',
'review_required': 'needs_human',
'pending_orders_present': 'needs_human',
'task_creation_failed': 'retryable_tech',
'xfa_auto_create_disabled': 'needs_human',
'xfa_shadow_mode': 'needs_human',
'xfa_profile_not_blind_approved': 'needs_human',
'xfa_allowlist_unconfigured': 'terminal_failed',
'xfa_customer_not_allowlisted': 'terminal_failed',
'xfa_profile_checksum_not_allowlisted': 'terminal_failed',
'xfa_scenario_not_allowlisted': 'terminal_failed',
'xfa_evidence_incomplete': 'needs_human',
'xfa_cross_check_failed': 'needs_human',
'xfa_visual_coverage_insufficient': 'needs_human',
'xfa_evidence_retention_insufficient': 'needs_human',
'xfa_mirror_consistency_insufficient': 'needs_human',
'xfa_profile_checksum_mismatch': 'retryable_tech',
'xfa_visual_not_publishable': 'needs_human',
'xfa_visual_bindings_required': 'needs_human',
'xfa_visual_binding_incomplete': 'needs_human',
# --- Excel / 货代上传 ---
'excel_not_ready': 'retryable_tech',
'excel_template_missing': 'terminal_failed',
'excel_input_incomplete': 'needs_human',
'artifact_validation_failed': 'retryable_tech',
'artifact_generation_failed': 'retryable_tech',
'manual_upload_pending': 'needs_human', # Excel 已生成,等待人工上传
'upload_rpa_pending': 'retryable_tech',
'upload_rpa_failed': 'retryable_tech',
'upload_rpa_login_failed': 'retryable_tech',
'upload_platform_rejected': 'needs_human',
'upload_result_unknown': 'retryable_tech',
}
# ============================================================
# 库存 4 主 Gate 的内部子阶段命名(决策 A1:不新增 Gate 实例)
# 短缺/冲突作为 inventory_matching 的 blocking_reason_code 分支,不新增独立 Gate。
# Projection 层读 Gate.effective_result_json['inventory_sub_stage'] 展示。
# ============================================================
INVENTORY_MAIN_GATES: Final[tuple[str, ...]] = (
'inventory_source_routing', # 路由规则计算(sub_stage=calculated)
'order_freeze_readiness', # 候选冻结(建单瞬间,sub_stage=frozen)——注意:复用现有 Gate,避免 seq 漂移
'inventory_preparation', # 多源快照准备(sub_stage=snapshots_ready)
'inventory_matching', # 跨源匹配 & 短缺/冲突(sub_stage=matched / blocking)
)
INVENTORY_SUB_STAGES: Final[frozenset[str]] = frozenset({
'not_started',
'calculated', # 路由规则评估完成
'frozen', # 候选集合已写入结构化表 + Snapshot
'snapshots_ready', # 所有必需源 snapshot ready
'matched', # 全行 ok,匹配裁决完成
'blocked_by_shortage', # 匹配 Gate 下:短缺阻断
'blocked_by_conflict', # 匹配 Gate 下:多源冲突阻断
'blocked_by_stale_snapshot', # 匹配 Gate 下:快照过期
'blocked_by_unknown', # 匹配 Gate 下:未知技术阻断
})
INVENTORY_SUB_STAGE_FIELD: Final[str] = 'inventory_sub_stage'
INVENTORY_SOURCE_STATUS_FIELD: Final[str] = 'inventory_source_status'
# Projection.facts.inventory_source_status 可取值集合
PROJECTION_INVENTORY_SOURCE_STATUSES: Final[frozenset[str]] = frozenset({
'not_frozen',
'candidates_calculated',
'candidates_frozen',
'snapshots_ready',
'matched',
})
# Projection.facts.export_state / upload_state 可取值集合
PROJECTION_EXPORT_STATES: Final[frozenset[str]] = frozenset({
'not_created',
'creating',
'created',
'failed',
})
PROJECTION_UPLOAD_STATES: Final[frozenset[str]] = frozenset({
'not_created',
'uploading',
'callback_received',
'manual_upload_pending',
'failed',
'succeeded',
})
# ============================================================
# 便捷查询函数(供 Projection 层直接调用,避免各处写 if/else)
# ============================================================
def user_status_for_gate_status(gate_status: str | None) -> str:
"""按 Gate.status 返回用户态;未知态兜底为 running。"""
key = str(gate_status or '').strip() or 'pending'
return GATE_STATUS_TO_USER_STATUS.get(key, 'running')
def user_status_for_execution_status(execution_status: str | None) -> str:
"""按 Execution.status 返回用户态;未知态兜底 running。"""
key = str(execution_status or '').strip() or 'active'
return EXECUTION_STATUS_TO_USER_STATUS.get(key, 'running')
def user_mode_for_blocking_reason(reason_code: str | None) -> str | None:
"""返回 blocking reason 的用户处置模式;未知 reason 返回 None(调用方兜底)。"""
if not reason_code:
return None
return BLOCKING_REASON_TO_USER_MODE.get(str(reason_code).strip())
@@ -39,6 +39,7 @@ _WRITE_ACTION_CODES = frozenset({
'confirm_customer',
'resolve_field_conflicts',
'adjudicate_duplicate',
'reconcile_and_progress',
'open_profile_review',
'open_inventory_source_review',
'open_inventory_match_review',
@@ -523,3 +524,487 @@ def reconcile_processing_projection_facts(
invalidated_from_stage=invalidated_from_stage,
)
return payload
# [T8 用户态 Projection 新枚举 F2] status 映射:running / waiting_human / retryable / failed / completed / cancelled。
_USER_PROCESSING_STATUSES = frozenset({
'running',
'waiting_human',
'retryable',
'failed',
'completed',
'cancelled',
})
_USER_STAGE_TO_CODE: dict[str, str] = {
# 建单 → 库存准备 → 匹配 → Excel → 上传 → 完成。
'document_parsing': 'document_parsing',
'order_creating': 'order_creating',
'waiting_review': 'waiting_human_review',
'inventory_fetching': 'inventory_fetch',
'inventory_matching': 'inventory_match',
'excel_generating': 'excel_generate',
'freight_uploading': 'freight_upload',
'completed': 'completed',
'failed': 'failed_terminal',
'cancelled': 'cancelled',
}
def apply_user_projection_fields(
payload: dict[str, Any],
*,
notice: Any | None = None,
order_task: Any | None = None,
) -> dict[str, Any]:
"""
在原有 ShippingProcessingProjection 上新增用户态 Projection 7 字段(决策 F3)。
【AI 触发时机】:任何需要向前端返回 OrderTask/Conversation 投影的末端出口,
在 reconcile_processing_projection_facts 之后、record_projection_inconsistency 之后调用。
核心逻辑(决策 F3:新增字段不替换旧枚举,Retry Decision 优先 + legacy 兜底):
[STEP 1] 保存旧枚举到 legacy_status / legacy_stage / legacy_current_gate,避免旧前端 break。
[STEP 2] 读取 pending_reason / review_status / inventory_source_status 原始字段。
[STEP 3] 计算 Retry Decision(仅 notice 存在时,失败/不存在则 legacy 兜底)。
[STEP 4] 按冻结优先级计算 user_status(completed/cancelled/failed → retryable → waiting_human → running)。
[STEP 5] 计算 retryable(bool)。
[STEP 6] 计算 blocking_reason:{code, i18n_key, details} 或 None。
[STEP 7] 计算 primary_action:对应 blocking_reason/status 的唯一主动作,或 None。
[不变] user_stage / user_current_gate_code / facts 子事实计算保持不动。
Args:
payload: reconcile_processing_projection_facts 输出后的原始 dict。
notice: 可选 ShippingNotice 实体(用于 Retry Decision 与 facts)。
order_task: 可选 ShippingOrderTask 实体(用于 facts 与 legacy pending_reason)。
Returns:
就地修改后的 payload(含新增 7 字段与 3 个 legacy_* 备份)。
"""
from app.services.shipping_notice.constants import (
RS_SHORTAGE_REVIEW as REVIEW_STATUS_SHORTAGE_REVIEW,
PH_INVENTORY_SOURCE_UNRESOLVED as PROCESS_HUMAN_PENDING_INVENTORY_SOURCE,
PH_SHORTAGE as PROCESS_HUMAN_PENDING_SHORTAGE,
)
_INVENTORY_SOURCE_STATUS_UNRESOLVED = 'unresolved'
_INVENTORY_SOURCE_STATUS_CANDIDATES_FROZEN = 'candidates_frozen'
_INVENTORY_SOURCE_STATUS_RESOLVED = 'resolved'
_PROCESS_HUMAN_PENDING_MATCH = 'match_review_pending'
# ===== [STEP 1] 旧枚举备份(保持不变) =====
payload['legacy_status'] = payload.get('status')
payload['legacy_stage'] = payload.get('stage')
payload['legacy_current_gate'] = payload.get('current_gate')
old_status = str(payload.get('status') or '').strip().lower()
old_stage = str(payload.get('stage') or '').strip().lower()
# ===== [STEP 2] 读取 notice / order_task 原始字段(保持不变) =====
pending_reason: str | None = None
review_status_raw: str | None = None
inventory_source_status_raw: str | None = None
if notice is not None:
pending_reason = str(getattr(notice, 'pending_human_reason', None) or '').strip() or None
review_status_raw = str(getattr(notice, 'review_status', None) or '').strip() or None
inventory_source_status_raw = str(getattr(notice, 'inventory_source_status', None) or '').strip() or None
if order_task is not None and not pending_reason:
pending_reason = str(getattr(order_task, 'pending_human_reason', None) or '').strip() or None
# ===== [STEP 3] 计算 Retry Decision(仅 notice 真实存在时) =====
retry_decision: dict | None = None
rd_action: str | None = None
rd_status: str | None = None
rd_retryable: bool = False
rd_reason_code: str | None = None
_RD_NEEDS_HUMAN: str | None = None
_RD_NOOP: str | None = None
_RD_STATUS_RUNNING: str | None = None
_RD_STATUS_NEEDS_HUMAN: str | None = None
_RD_STATUS_COMPLETED: str | None = None
_RD_STATUS_FAILED: str | None = None
if notice is not None:
try:
from app.services.shipping_notice.task_retry_decision_service import (
decide_retry_action_only,
ACTION_NEEDS_HUMAN as _RD_NEEDS_HUMAN,
ACTION_NOOP as _RD_NOOP,
STATUS_RUNNING as _RD_STATUS_RUNNING,
STATUS_NEEDS_HUMAN as _RD_STATUS_NEEDS_HUMAN,
STATUS_COMPLETED as _RD_STATUS_COMPLETED,
STATUS_FAILED as _RD_STATUS_FAILED,
)
retry_decision = decide_retry_action_only(notice, scope='task')
except Exception: # noqa: BLE001
retry_decision = None
rd_action = str((retry_decision or {}).get('action') or '').strip() or None
rd_status = str((retry_decision or {}).get('status') or '').strip() or None
rd_retryable = bool((retry_decision or {}).get('retryable'))
rd_reason_code = str((retry_decision or {}).get('reason_code') or '').strip() or None
# ===== [STEP 4] 按冻结映射规则计算 user_status(F3 优先级) =====
notice_process_status = None
if notice is not None:
notice_process_status = str(getattr(notice, 'process_status', None) or '').strip().lower() or None
_rd_has_completed_process = bool(
notice is not None
and notice_process_status in {'completed', 'fulfilled', 'closed'}
)
def _compute_user_status() -> str:
# 1) 终态短路:old_status completed/cancelled/failed
if old_status == 'completed':
return 'completed'
if old_status == 'cancelled':
return 'cancelled'
if old_status == 'failed':
return 'failed'
# Retry Decision 可得时:优先用决策器
if retry_decision is not None:
# 4) rd_status=completed 或 action=noop 且 notice 完成态 → completed
if rd_status == _RD_STATUS_COMPLETED:
return 'completed'
if rd_action == _RD_NOOP and _rd_has_completed_process:
return 'completed'
# 5) rd_retryable=True → 'retryable'(新增!)
if rd_retryable is True:
return 'retryable'
# 6) rd_status=needs_human 或 rd_action=needs_human → waiting_human
if rd_status == _RD_STATUS_NEEDS_HUMAN or rd_action == _RD_NEEDS_HUMAN:
return 'waiting_human'
# 7) legacy waiting_human 兜底(保留旧逻辑)
if old_status in {'waiting_review', 'waiting_inventory_source_review', 'waiting_shortage_review'}:
return 'waiting_human'
if pending_reason in {
PROCESS_HUMAN_PENDING_INVENTORY_SOURCE,
PROCESS_HUMAN_PENDING_SHORTAGE,
_PROCESS_HUMAN_PENDING_MATCH,
} or review_status_raw in {REVIEW_STATUS_SHORTAGE_REVIEW}:
return 'waiting_human'
# 8) rd_status=running 或旧 running 族 → running
if retry_decision is not None and rd_status == _RD_STATUS_RUNNING:
return 'running'
if old_status in {'processing', 'queued', 'running'}:
return 'running'
# 9) 兜底
return 'running'
user_status = _compute_user_status()
# ===== [不变] user_stage 计算(保持不动) =====
user_stage = _USER_STAGE_TO_CODE.get(old_stage)
if user_stage is None:
if old_stage in {'document_parsing', 'order_creating'}:
user_stage = 'document_parsing'
elif old_stage in {'inventory_fetching'}:
user_stage = 'inventory_fetch'
elif old_stage in {'inventory_matching'}:
user_stage = 'inventory_match'
elif old_stage in {'excel_generating'}:
user_stage = 'excel_generate'
elif old_stage in {'freight_uploading'}:
user_stage = 'freight_upload'
else:
user_stage = 'document_parsing'
# ===== [不变] user_current_gate_code 计算(保持不动) =====
old_gate = payload.get('current_gate') if isinstance(payload.get('current_gate'), dict) else None
user_current_gate_code: str | None = None
if isinstance(old_gate, dict):
user_current_gate_code = str(old_gate.get('code') or old_gate.get('gate_code') or '').strip() or None
# ===== [STEP 5] 计算 retryable(布尔) =====
def _compute_retryable() -> bool:
if user_status in {'completed', 'cancelled'}:
return False
if user_status == 'retryable':
return True
if user_status == 'failed' and rd_retryable:
return True
return False
retryable = _compute_retryable()
# ===== [STEP 6] 计算 blocking_reason: {code, i18n_key, details} 或 None =====
_REASON_TO_I18N_KEY: dict[str, str] = {
'inventory_source_unstable': 'workspace.shippingNotice.processGate.reasons.require_manual_review',
'inventory_snapshot_missing': 'workspace.shippingNotice.processGate.reasons.inventory_file_missing',
'inventory_match_incomplete': 'workspace.shippingNotice.processGate.reasons.inventory_match_failed',
'inventory_source_candidates_need_human': 'workspace.shippingNotice.processGate.reasons.require_manual_review',
'upload_rpa_failed': 'workspace.shippingNotice.processGate.reasons.upload_rpa_failed',
'inventory_shortage': 'workspace.shippingNotice.processGate.reasons.inventory_insufficient',
'inventory_source_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_source_conflicted',
'inventory_source_unresolved': 'workspace.shippingNotice.processGate.reasons.require_manual_review',
'inventory_multi_file_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_multi_file_conflict',
'order_review_required': 'workspace.shippingNotice.processGate.reasons.freeze_not_ready',
'duplicate_decision_required': 'chat.shippingProcessing.reasonCode.duplicateDecisionRequired',
'SHIPPING.NOTICE_EXACT_DUPLICATE': 'chat.shippingProcessing.reasonCode.exactDuplicateNotice',
'SHIPPING.STP_NOT_ELIGIBLE': 'chat.shippingProcessing.reasonCode.stpNotEligible',
'SHIPPING.REVIEW_DRAFT_MISSING': 'chat.shippingProcessing.reasonCode.reviewDraftMissing',
'SHIPPING.REVIEW_RUN_MISSING': 'chat.shippingProcessing.reasonCode.reviewRunMissing',
'SHIPPING.REVIEW_DOCUMENT_INVALID': 'chat.shippingProcessing.reasonCode.reviewDocumentInvalid',
'SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT': 'chat.shippingProcessing.reasonCode.reviewDraftVersionConflict',
'profile_schema_mismatch': 'chat.shippingProcessing.reasonCode.profileSchemaMismatch',
'final_required_field_missing': 'chat.shippingProcessing.reasonCode.finalRequiredFieldMissing',
}
_PROCESS_FAILED_I18N = 'workspace.shippingNotice.processGate.reasons.unknown_business_failure'
def _legacy_waiting_human_blocking_reason() -> dict[str, Any] | None:
if pending_reason == PROCESS_HUMAN_PENDING_INVENTORY_SOURCE or inventory_source_status_raw in {_INVENTORY_SOURCE_STATUS_UNRESOLVED}:
return {
'code': 'inventory_source_unresolved',
'i18n_key': _REASON_TO_I18N_KEY['inventory_source_unresolved'],
'details': {},
}
if pending_reason == PROCESS_HUMAN_PENDING_SHORTAGE or review_status_raw in {REVIEW_STATUS_SHORTAGE_REVIEW}:
return {
'code': 'inventory_shortage',
'i18n_key': _REASON_TO_I18N_KEY['inventory_shortage'],
'details': {},
}
if pending_reason == _PROCESS_HUMAN_PENDING_MATCH:
return {
'code': 'inventory_multi_file_conflict',
'i18n_key': _REASON_TO_I18N_KEY['inventory_multi_file_conflict'],
'details': {},
}
if old_status == 'waiting_review':
return {
'code': 'order_review_required',
'i18n_key': _REASON_TO_I18N_KEY['order_review_required'],
'details': {},
}
return None
def _compute_blocking_reason() -> dict[str, Any] | None:
# 1) completed / cancelled / running → 无阻断
if user_status in {'completed', 'cancelled', 'running'}:
return None
# 2) waiting_human
if user_status == 'waiting_human':
if retry_decision is not None and rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY:
return {
'code': rd_reason_code,
'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code],
'details': {},
}
return _legacy_waiting_human_blocking_reason()
# 3) retryable
if user_status == 'retryable':
if rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY:
return {
'code': rd_reason_code,
'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code],
'details': {},
}
return {
'code': 'retry_needed',
'i18n_key': 'workspace.shippingNotice.processGate.reasons.technical_retry_exhausted',
'details': {},
}
# 4) failed
if user_status == 'failed':
if rd_retryable and rd_reason_code and rd_reason_code in _REASON_TO_I18N_KEY:
return {
'code': rd_reason_code,
'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code],
'details': {},
}
return {
'code': 'process_failed_terminal',
'i18n_key': _PROCESS_FAILED_I18N,
'details': {'legacy_status': old_status, 'legacy_stage': old_stage},
}
return None
blocking_reason = _compute_blocking_reason()
# ===== [STEP 7] 计算 primary_action: {code, i18n_key, parameters} 或 None =====
_ACTION_CODE_TO_GATE_I18N_KEY: dict[str, str] = {
'retry': 'workspace.shippingNotice.processGate.actionCodes.retry_with_latest_rules',
'open_inventory_source_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_source_review',
'open_inventory_match_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_match_review',
'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review',
'retry_freight_upload_rpa': 'workspace.shippingNotice.processGate.actionCodes.retry_freight_upload_rpa',
'adjudicate_duplicate': 'workspace.shippingNotice.processGate.actionCodes.adjudicate_duplicate',
'reconcile_and_progress': 'workspace.shippingNotice.processGate.actionCodes.reconcile_and_progress',
'open_profile_review': 'workspace.shippingNotice.processGate.actionCodes.open_profile_review',
}
_ACTION_CODE_TO_CHAT_I18N_FALLBACK: dict[str, str] = {
'retry': 'chat.shippingProcessing.action.retry',
'open_inventory_source_review': 'chat.shippingProcessing.action.open_inventory_source_review',
'open_inventory_match_review': 'chat.shippingProcessing.action.open_inventory_match_review',
'open_order_review': 'chat.shippingProcessing.action.open_order_review',
'retry_freight_upload_rpa': 'chat.shippingProcessing.action.retry_freight_upload_rpa',
'match_inventory': 'chat.shippingProcessing.action.match_inventory',
'regenerate_excel': 'chat.shippingProcessing.action.regenerate_excel',
'download_excel': 'chat.shippingProcessing.action.download_excel',
'adjudicate_duplicate': 'chat.shippingProcessing.action.adjudicate_duplicate',
'reconcile_and_progress': 'chat.shippingProcessing.action.reconcile_and_progress',
'open_profile_review': 'chat.shippingProcessing.action.open_profile_review',
}
def _resolve_action_i18n_key(action_code: str) -> str:
gate_key = _ACTION_CODE_TO_GATE_I18N_KEY.get(action_code)
if gate_key:
return gate_key
fallback = _ACTION_CODE_TO_CHAT_I18N_FALLBACK.get(action_code)
return fallback or f'chat.shippingProcessing.action.{action_code}'
def _legacy_waiting_human_primary_action(bcode: str) -> dict[str, Any] | None:
if bcode == 'inventory_source_unresolved':
code = 'open_inventory_source_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
if bcode in {'inventory_shortage', 'inventory_multi_file_conflict'}:
code = 'open_inventory_match_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
if bcode == 'order_review_required':
code = 'open_order_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
return None
def _compute_primary_action() -> dict[str, Any] | None:
# 1) blocking_reason 非 None
if blocking_reason is not None:
bcode = str(blocking_reason.get('code') or '').strip()
# 1a. retryable 或 failed+retryable → 统一 retry 动作
if user_status == 'retryable' or (user_status == 'failed' and retryable is True):
code = 'retry'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 1b ~ 1h: waiting_human 按 code 分派
if user_status == 'waiting_human':
if bcode in {'inventory_source_unresolved', 'inventory_source_unstable', 'inventory_source_candidates_need_human'}:
code = 'open_inventory_source_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
if bcode in {'inventory_shortage', 'inventory_multi_file_conflict', 'inventory_source_conflict'}:
code = 'open_inventory_match_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
if bcode in {'order_review_required', 'freeze_not_ready'}:
code = 'open_order_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
if bcode == 'upload_rpa_failed':
code = 'retry_freight_upload_rpa'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 1e. 重复冲突 → adjudicate_duplicate
if bcode in {'duplicate_decision_required', 'SHIPPING.NOTICE_EXACT_DUPLICATE'}:
code = 'adjudicate_duplicate'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 1f. profile/XFA 治理失败 → open_profile_review
if bcode == 'profile_schema_mismatch' or (bool(bcode) and bcode.startswith('SHIPPING.XFA_')):
code = 'open_profile_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 1g. STP/Review 资格问题 → open_order_review
if bcode in {
'SHIPPING.STP_NOT_ELIGIBLE',
'SHIPPING.REVIEW_DRAFT_MISSING',
'SHIPPING.REVIEW_RUN_MISSING',
'SHIPPING.REVIEW_DOCUMENT_INVALID',
'SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT',
'final_required_field_missing',
}:
code = 'open_order_review'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 1h. available_actions 含 reconcile_and_progress → 统一对账恢复入口兜底
if isinstance(available_actions, list) and 'reconcile_and_progress' in available_actions:
code = 'reconcile_and_progress'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 1i. 其它 unknown:legacy 兜底
legacy_pa = _legacy_waiting_human_primary_action(bcode)
if legacy_pa is not None:
return legacy_pa
# 2) completed → download_excel(保持 legacy)
if user_status == 'completed':
code = 'download_excel'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 3) running 且 stage 匹配 → match_inventory / regenerate_excel(保持 legacy)
if user_status == 'running' and user_stage == 'inventory_match':
code = 'match_inventory'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
if user_status == 'running' and user_stage == 'excel_generate':
code = 'regenerate_excel'
return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}}
# 4) 兜底 None
return None
primary_action = _compute_primary_action()
# ===== [不变] facts 子事实计算(保持不动) =====
facts: dict[str, Any] = {
'inventory_source_status': inventory_source_status_raw or 'unresolved',
'candidate_source_codes': [],
'prepared_source_codes': [],
'pending_source_codes': [],
'line_resolutions': [],
'export_state': 'not_created',
'upload_state': 'not_created',
'switch_state': 'not_triggered',
}
if order_task is not None:
cand = getattr(order_task, 'candidate_source_codes_json', None)
if isinstance(cand, list):
facts['candidate_source_codes'] = [str(c or '').strip().upper() for c in cand if str(c or '').strip()]
if notice is not None:
step_payload = getattr(notice, 'step_payload_json', None)
if isinstance(step_payload, dict):
prep = step_payload.get('candidate_inventory_prep')
if isinstance(prep, dict):
facts['prepared_source_codes'] = list(prep.get('loaded_source_codes') or [])
facts['pending_source_codes'] = list(prep.get('missing_source_codes') or [])
resolutions = step_payload.get('line_inventory_resolutions')
if isinstance(resolutions, list):
facts['line_resolutions'] = resolutions[:]
fms = step_payload.get('forced_match_source_code')
if fms:
facts['forced_match_source_code'] = str(fms).strip().upper()
# P0-2:逐源 Attempt 执行事实只读投影,前端不得从旧 status 猜测。
try:
from app.models import ShippingTaskInventoryRpaAttempt
attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=str(getattr(notice, 'task_no', '') or '')).all()
facts['rpa_attempts'] = [{
'source_code': a.source_code, 'attempt_no': a.attempt_no,
'source_run_no': a.source_run_no, 'status': a.status,
'execution_phase': a.execution_phase, 'file_generated': bool(a.file_generated),
'file_exists_at_callback': a.file_exists_at_callback,
'callback_received_at': a.callback_received_at.isoformat() if a.callback_received_at else None,
'error_code': a.error_code, 'transaction_error_code': a.transaction_error_code,
} for a in attempts]
except Exception:
facts['rpa_attempts'] = []
if getattr(notice, 'export_artifact_id', None):
facts['export_state'] = 'created'
if getattr(notice, 'upload_status', None):
us = str(getattr(notice, 'upload_status') or '').strip().lower()
facts['upload_state'] = us if us else 'not_created'
if getattr(notice, 'wecom_sent_at', None):
facts['switch_state'] = 'sent'
payload['user_status'] = user_status
payload['user_stage'] = user_stage
payload['user_current_gate_code'] = user_current_gate_code
payload['blocking_reason'] = blocking_reason
payload['retryable'] = bool(retryable)
payload['primary_action'] = primary_action
payload['facts'] = facts
# [DUPLICATE-GUARD-2] 第二道(shipping-processing 侧):available_actions 剔除 —
# duplicate_decision_required / NOTICE_EXACT_DUPLICATE 强制移除 retry_*,
# 并把 reconcile_and_progress 顶到首位,避免两端投影不一致
if isinstance(blocking_reason, dict):
_dup_br_code = str(blocking_reason.get('code') or '').strip()
if _dup_br_code in {'duplicate_decision_required', 'SHIPPING.NOTICE_EXACT_DUPLICATE'}:
from app.services.shipping_notice.recovery_contract import (
should_general_retry_be_removed as _fg_should_remove,
)
if _fg_should_remove(
retryable_flag=bool(retryable),
blocking_reason=blocking_reason,
):
_raw_actions = payload.get('available_actions')
if isinstance(_raw_actions, list) and _raw_actions:
_dup_remove = {'retry_stp_auto_create', 'retry_auto_progress', 'retry'}
_filtered = [a for a in _raw_actions if a not in _dup_remove]
if 'reconcile_and_progress' in _filtered:
_rest = [a for a in _filtered if a != 'reconcile_and_progress']
payload['available_actions'] = ['reconcile_and_progress', *_rest]
else:
payload['available_actions'] = _filtered
return payload
@@ -1,13 +1,12 @@
"""
services/shipping_notice/progress_workflow.py
用途:承接发货通知任务的自动推进流程,包括解析确认检查、正式库存准备与履约侧串联。
用途:承接发货通知任务的自动推进提交,包括解析确认检查、正式库存准备与履约侧串联。
依赖:customer_identity_gate、tool_common、query_service、inventory_workflow、fulfillment_workflow、
state_machine(CheckpointKind)、tool_response、process_gate_bridge。
逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;按 checkpoint_kind 早停或继续;
must_human / complete 早停;wait_manual_upload 在 AUTO_UPLOAD=true 时落入履约链触发 RPA,
关闭时才停人工上传;禁止平行编排语义;退出前同步 Process Gate;
系统触发时事件 actor_id=None;workspace_api 须注入 operator_id 并写统一审计。
逻辑:由 task_workflow / 复核确认 / STP 直通落库对外转调本文件;P0-3 起正式入口只提交
当前最早未通过 Gate,Worker 负责单 Gate 执行与下一 Job 的事务性入队;历史私有实现暂保留
供兼容调用方,但不得再由本 facade 直接跨 Gate 调度。
"""
from __future__ import annotations
@@ -18,6 +17,7 @@ from flask import current_app
from app.services.shipping_notice import fulfillment_workflow
from app import db
from app.models.shipping_process_gate import ShippingProcessGateAttempt
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
PH_INVENTORY_SOURCE_UNRESOLVED,
@@ -30,7 +30,7 @@ from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
ensure_inventory_source_review_state,
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.inventory_workflow import ensure_inventory as _legacy_ensure_inventory
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
from app.services.shipping_notice.state_machine import CheckpointKind, resolve_task_ui_state
from app.services.shipping_notice.tool_common import auto_progress_enabled, log_task_event
@@ -38,6 +38,323 @@ from app.services.shipping_notice.tool_response import tool_response
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
# ---------------------------------------------------------------------------
# T5: 唯一 AutoProgress Orchestrator 入口 facade
# ---------------------------------------------------------------------------
# 所有自动推进入口(/tools/auto_progress、/tools/ensure_inventory、/tools/match_inventory、
# batch_orchestrator、task_retry_decision)必须收口到本函数:
#
# run_task_auto_progress(task_no, trigger, expected_version=None,
# idempotency_key=None, resume_gate_code=None) -> dict
#
# 并发保护三层:
# [1] 乐观锁 progress_version CAS(避免同任务并发写独立字段冲突)
# [2] ShippingProcessGateAttempt 活动唯一性(同任务同一时刻只允许 1 个 queued/running Attempt)
# [3] idempotency_key 响应缓存(可选,短时间内重复 POST 直接返回上次结果)
# ---------------------------------------------------------------------------
_RESUME_GATE_CODE_LEGACY_ENTRY = {
# inventory_preparation → 调 inventory_workflow.ensure_inventory 逻辑(复用旧实现)
'inventory_preparation': 'ensure_inventory',
# inventory_matching → 调 fulfillment_workflow.match_inventory(整单)或 match_inventory_line(行级,需 line_scope_key)
'inventory_matching': 'match_inventory',
# None 或 'auto' → 走完整 auto_progress 串联链(解析→库存→匹配→导出→上传)
'auto': 'auto_progress_full',
None: 'auto_progress_full',
'': 'auto_progress_full',
}
def _try_cas_progress_version(task: Any, expected_version: int | None) -> tuple[bool, int]:
"""
CAS 更新 task.progress_version:expected_version==None 则强制自增(调用方保证单线程);
否则要求 DB 当前值 == expected_version 才自增;返回 (是否成功, 新 version)。
"""
sess = db.session
current = int(getattr(task, 'progress_version', 0) or 0)
if expected_version is not None and int(expected_version) != current:
return False, current
new_version = current + 1
try:
# 优先用原生 UPDATE ... WHERE 原子 CAS(若列不存在则安全降级到内存赋值 + flush)
if hasattr(task, 'progress_version') and task.id is not None:
model_cls = type(task)
affected = (
sess.query(model_cls)
.filter(model_cls.id == task.id)
.filter(
(model_cls.progress_version == expected_version)
if expected_version is not None
else True
)
.update({'progress_version': new_version}, synchronize_session='evaluate')
)
if not affected:
return False, int(getattr(task, 'progress_version', 0) or 0)
task.progress_version = new_version
return True, new_version
except Exception:
pass
task.progress_version = new_version
return True, new_version
def _has_active_gate_attempts(task: Any) -> list[ShippingProcessGateAttempt]:
"""查询 Task 关联的当前活动 Gate Attempt(queued / running)——用于唯一性断言。"""
task_id = getattr(task, 'id', None)
if task_id is None:
return []
try:
return list(
db.session.query(ShippingProcessGateAttempt)
.filter(
ShippingProcessGateAttempt.task_id == task_id,
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
)
.all()
)
except Exception:
return []
def _dispatch_legacy_orchestration(
task: Any,
*,
resume_gate_code: str | None,
trigger: str,
operator_id: int | None,
inventory_mode: str = 'auto',
line_scope_key: str | None = None,
) -> dict[str, Any]:
"""
resume_gate_code → 旧实现分派(短期复用稳定实现,后续逐步把每个 Gate 原子步骤迁入本 facade)。
长期目标:每个 Gate 只在本函数内跑原子 run_one_gate_step();旧实现会逐步下线。
"""
entry = _RESUME_GATE_CODE_LEGACY_ENTRY.get(resume_gate_code, 'auto_progress_full')
base_payload: dict[str, Any] = {
'task_no': str(task.task_no or '').strip(),
'task_id': getattr(task, 'id', None),
'trigger': trigger,
'operator_id': operator_id,
'resume_gate_code': resume_gate_code,
'mode': inventory_mode,
}
if entry == 'ensure_inventory':
# [T4 集成] 库存准备:如果存在 per-source 候选冻结,优先走 per_source_rpa_service 逐源准备
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
from app.services.shipping_notice.stp_inventory_freeze import (
task_frozen_inventory_source_codes,
)
frozen_sources = task_frozen_inventory_source_codes(task)
if frozen_sources and len(frozen_sources) >= 1:
prepare_result = ensure_all_required_sources_prepared(task, mode=inventory_mode)
if prepare_result.all_prepared:
return _legacy_ensure_inventory({**base_payload, '_prepared_sources': prepare_result.prepared_source_codes, '_orchestrator_internal_dispatch': True})
return tool_response(
status='running' if prepare_result.pending_source_codes else (
'failed' if prepare_result.failed_source_codes and not prepare_result.prepared_source_codes else 'needs_human'
),
task=task,
message=(
f"库存准备中({len(prepare_result.prepared_source_codes)}/{len(frozen_sources)} 已就绪;"
f"等待 {len(prepare_result.pending_source_codes)} 源;失败 {len(prepare_result.failed_source_codes)} 源)。"
),
data={
**serialize_task_for_tool(task),
'per_source_inventory_preparation': {
'prepared': prepare_result.prepared_source_codes,
'pending': prepare_result.pending_source_codes,
'failed': prepare_result.failed_source_codes,
'source_attempts': prepare_result.source_attempts,
},
},
)
return _legacy_ensure_inventory({**base_payload, '_orchestrator_internal_dispatch': True})
if entry == 'match_inventory':
norm_line_scope = str(line_scope_key or '').strip()
if norm_line_scope:
return fulfillment_workflow.match_inventory_line(
{**base_payload, '_orchestrator_internal_dispatch': True},
line_key=norm_line_scope,
)
return fulfillment_workflow.match_inventory({**base_payload, '_orchestrator_internal_dispatch': True})
return _auto_progress_full(task, base_payload, trigger=trigger, operator_id=operator_id)
def _auto_progress_full(
task: Any,
base_payload: dict[str, Any],
*,
trigger: str,
operator_id: int | None,
) -> dict[str, Any]:
"""完整 auto_progress 串联——复用下方既有 auto_progress 主逻辑但避免函数递归。"""
from app.services.shipping_notice.progress_workflow import auto_progress as _public_auto_progress
# 短期:直接调用下方 auto_progress 原实现(payload 包装);后续把完整步骤迁移到 Orchestrator 原子循环
return _public_auto_progress({
**base_payload,
'source': trigger,
'operator_id': operator_id,
'_skip_orchestrator_wrapper': True,
})
def run_task_auto_progress(
task_no: str,
*,
trigger: str,
expected_version: int | None = None,
idempotency_key: str | None = None,
resume_gate_code: str | None = None,
operator_id: int | None = None,
inventory_mode: str = 'auto',
line_scope_key: str | None = None,
) -> dict[str, Any]:
"""
唯一 AutoProgress Orchestrator Facade。
【AI 触发时机】:所有需要推进发货任务状态的入口(Tool API、Batch Orchestrator、Retry Decision、
Gate Handler post-action)均应调用本函数;禁止直接调 inventory_workflow.ensure_inventory
或 fulfillment_workflow.match_inventory 绕过并发锁。
核心步骤:
[STEP 0] 解析 task_no → 读取 Task;乐观锁 CAS progress_version(防止并发写冲突)
[STEP 1] 任务级活动 Attempt 唯一性断言:存在 queued/running Gate Attempt → 返回已在处理(noop)
[STEP 2] 按 resume_gate_code 分派原子步骤执行(短期复用旧实现,长期迁入本函数)
[STEP 3] 同步 Process Gate 投影、持久化 commit
[STEP 4] 触发 SSE 刷新信号(发送 task_no → 前端轮询 Projection 拉取新状态)
Args:
task_no: 发货任务 task_no。
trigger: 触发来源字符串(batch_orchestrator / tool_api_ensure / retry_decision / ...),用于审计。
expected_version: 可选乐观锁预期 progress_version;不匹配返回 early_return conflict。
idempotency_key: 可选短时间幂等键(当前版本写入 TaskEvent,后续可接 Redis 缓存)。
resume_gate_code: 从指定 Gate 恢复;None 表示从当前阶段自动推进。
operator_id: 操作人 ID(系统触发则 None)。
inventory_mode: 库存准备模式;用户显式重试传 retry_rpa,自动推进保持 auto。
line_scope_key: 行级 scope 键;传了则仅对该行执行(例如 match_inventory_line),不传则整单推进。
Returns:
Tool 标准响应(status=running/needs_human/failed/completed + task + data);
并发冲突时返回 {'success': False, 'status': 'conflict', 'current_progress_version': int}。
"""
if not auto_progress_enabled():
return tool_response(status="failed", message="auto_progress 未启用")
# 说明:query_service 没有 get_task_by_task_no,统一用 resolve_task_from_payload。
# 保留分支:如果将来对同一 task_no 需要权限过滤,应改为 get_task_for_user(task_no, operator_id)。
task = resolve_task_from_payload({'task_no': task_no}) if task_no else None
if not task:
return tool_response(status="failed", message=f"未找到任务编号 {task_no}")
# P0-3:旧 facade 不再直接跨 Gate 调用库存/匹配/Excel。所有触发统一只提交
# 当前正式 Gate;Worker 在事实落库后才创建下一个 Job。
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
submitted = submit_auto_progress(
task=task, trigger=trigger, operator_id=operator_id,
resume_gate_code=resume_gate_code, commit=True,
)
status = str(submitted.get('status') or 'queued')
if status == 'queued':
return tool_response(status='running', task=task, message='已提交当前自动推进 Gate。', data=submitted)
if status in {'waiting_human', 'blocked_manual', 'blocked_retryable'}:
return tool_response(status='needs_human', task=task, message='当前 Gate 需要人工处理。', data=submitted)
if status == 'cancelled':
return tool_response(status='failed', task=task, message='任务已取消,不能继续自动推进。', data=submitted)
return tool_response(status='completed', task=task, message='自动推进已无待处理 Gate。', data=submitted)
# [STEP 0] 乐观锁 CAS
cas_ok, new_version = _try_cas_progress_version(task, expected_version)
if not cas_ok:
return {
'success': False,
'status': 'conflict',
'task_no': task_no,
'current_progress_version': new_version,
'retry_safe': True,
}
# [STEP 1] 活动 Attempt 唯一性
active_attempts = _has_active_gate_attempts(task)
if active_attempts:
# 已有 queued/running Attempt → 直接返回 noop,避免重复排队
return tool_response(
status='running',
task=task,
message=f'任务推进中(已有 {len(active_attempts)} 个活动 Gate Attempt,未重复触发)。',
data={
**serialize_task_for_tool(task),
'orchestrator': {
'active_attempt_count': len(active_attempts),
'noop_reason': 'active_gate_attempt_exists',
'progress_version': new_version,
},
},
)
# [STEP 2] 分派原子步骤
log_task_event(
task,
'orchestrator_run_started',
{
'trigger': trigger,
'resume_gate_code': resume_gate_code,
'idempotency_key': idempotency_key,
'progress_version_before': new_version - 1 if new_version else 0,
'progress_version_after': new_version,
'line_scope_key': line_scope_key,
},
actor_id=operator_id,
source=trigger,
)
try:
result = _dispatch_legacy_orchestration(
task, resume_gate_code=resume_gate_code,
trigger=trigger, operator_id=operator_id,
inventory_mode=inventory_mode,
line_scope_key=line_scope_key,
)
except Exception as exc: # pragma: no cover - 顶层兜底避免 Worker 吞异常
db.session.rollback()
err = f'{type(exc).__name__}: {str(exc)[:500]}'
log_task_event(
task, 'orchestrator_run_failed',
{'error': err, 'trigger': trigger, 'resume_gate_code': resume_gate_code},
actor_id=operator_id, source=trigger,
)
return tool_response(status='failed', message=f'Orchestrator 执行异常:{err}', data={'progress_version': new_version})
# [STEP 3] 持久化 + 同步 Process Gate 投影
try:
db.session.commit()
except Exception as exc: # pragma: no cover - DB 层兜底
db.session.rollback()
return tool_response(status='failed', message=f'Orchestrator commit 失败:{type(exc).__name__}: {str(exc)[:300]}')
# [STEP 4] 触发 SSE 刷新信号(通过 events 写入,前端轮询 ShippingProcessingProjection 拉取事实)
try:
_sync_process_gates_after_progress(task, {'progress_version': new_version, 'trigger': trigger})
except Exception:
pass
log_task_event(
task, 'orchestrator_run_finished',
{
'trigger': trigger,
'resume_gate_code': resume_gate_code,
'progress_version': new_version,
'result_status': result.get('status') if isinstance(result, dict) else None,
'line_scope_key': line_scope_key,
},
actor_id=operator_id, source=trigger,
)
if isinstance(result, dict):
result.setdefault('data', {})
if isinstance(result['data'], dict):
result['data']['progress_version'] = new_version
result['data']['orchestrator_trigger'] = trigger
result['data']['sse_refresh_hint'] = True
return result
def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
"""
按任务当前状态自动串联解析确认、正式库存准备与履约动作。
@@ -54,6 +371,34 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
Returns:
dict[str, Any]: Tool 标准响应,返回自动推进后的阶段、提示和数据。
"""
# [T5 Orchestrator 守卫]:外部入口直接收口到 run_task_auto_progress(统一乐观锁+唯一性断言);
# _skip_orchestrator_wrapper=True 才进入下方完整实现(由 _auto_progress_full 内部调用,避免递归死循环)。
if not payload.get('_skip_orchestrator_wrapper', False):
task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip()
if not task_no and isinstance(payload, dict):
from app.services.shipping_notice.query_service import resolve_task_from_payload as _rtp
_t = _rtp(payload)
task_no = str(getattr(_t, 'task_no', '') or '').strip()
trigger = str(payload.get('source') or payload.get('trigger') or 'legacy_auto_progress_entry').strip()
ev = payload.get('expected_version')
try:
expected_version = int(ev) if ev is not None and str(ev).strip() else None
except (TypeError, ValueError):
expected_version = None
idempotency_key = str(payload.get('idempotency_key') or '').strip() or None
actor_raw = payload.get("operator_id") or payload.get("actor_id") or payload.get("_trusted_user_id")
try:
operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != "system" else None
except (TypeError, ValueError):
operator_id = None
return run_task_auto_progress(
task_no, trigger=trigger,
expected_version=expected_version,
idempotency_key=idempotency_key,
resume_gate_code=None,
operator_id=operator_id,
)
# 下方:_auto_progress_full 内部调用路径(直接执行完整串联,不再走 Orchestrator 外层)
if not auto_progress_enabled():
return tool_response(status="failed", message="auto_progress 未启用")
@@ -229,6 +229,7 @@ def claim_next_shipping_notice_job() -> Job | None:
JobType.SHIPPING_ORDER_EXTRACTION,
JobType.SHIPPING_DOCUMENT_LAYOUT,
JobType.SHIPPING_PROCESS_GATE,
JobType.SHIPPING_AUTO_PROGRESS,
JobType.SHIPPING_XFA_OCR_AUTOMARK,
JobType.SHIPPING_STP_AUTO_CREATE,
JobType.SHIPPING_LINE_AUTO_FULFILL,
@@ -0,0 +1,580 @@
"""
backend/app/services/shipping_notice/reconcile_queries.py
用途:Phase 2 对账只读查询层 — 按 Q1 五级 L1-L3 归属链判断 Case → Task 的绑定关系。
依赖:models.ShippingOrderReviewCase / ShippingOrderCandidate / ShippingOrderDocument
/ ShippingNotice(=OrderTask)、business_fingerprint.build_business_fingerprint、
duplicate_detection.classify_task_lifecycle、recovery_contract(类型契约)。
逻辑:由 reconciliation_service.reconcile_existing_task() 调用;全部为只读查询,
不做任何 DB 写入;返回统一 ReconcileMatchResult 结构(match_level / task_no /
confidence / evidence)。严禁凭字段名推断,必须真实 JOIN 关系表。
注意:business_numbering_service._customer_code_from_summary 不在顶层 import(该函数
已从编号服务移除),调用处做 try 延迟 import,失败兜底空字符串。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import (
FileAsset,
ShippingNotice,
ShippingOrderCandidate,
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderProcessingUnit,
ShippingOrderReviewCase,
)
from app.services.shipping_notice.business_fingerprint import (
FINGERPRINT_VERSION,
build_business_fingerprint,
)
from app.services.shipping_notice.duplicate_detection import classify_task_lifecycle
from app.services.shipping_notice.recovery_contract import (
ReconcileConfidence,
ReconcileMatchEvidence,
ReconcileMatchLevel,
ReconcileMatchResult,
)
# ============================================================
# 公共辅助:统一生成「无匹配」结果
# ============================================================
def _no_match(*, reason: str, case_no: str) -> ReconcileMatchResult:
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.NONE,
task_no=None,
confidence=ReconcileConfidence.NONE,
evidence=ReconcileMatchEvidence(
case_no=case_no,
match_level_steps=[{'step': 'L0-none', 'passed': False, 'reason': reason}],
),
)
# ============================================================
# L1:Case 显式绑定(最高优先级,最快路径)
# ============================================================
def _step_l1_case_explicit_binding(case: ShippingOrderReviewCase) -> ReconcileMatchResult | None:
"""
L1:Case.confirmed_task_id → 直接查 ShippingNotice 拿到 task_no。
【AI 触发时机】:对账入口必须先执行本步骤,避免 L2/L3 瞎匹配覆盖掉人工确认的绑定。
"""
steps: list[dict[str, Any]] = []
case_no = str(case.case_no)
# 1a. confirmed_task_id 有值且指向存在的 Task
task_id = getattr(case, 'confirmed_task_id', None)
if task_id is not None:
task = db.session.get(ShippingNotice, int(task_id))
if task is not None and task.task_no:
steps.append({'step': 'L1a-confirmed_task_id', 'passed': True,
'evidence': {'task_id': int(task_id), 'task_no': str(task.task_no)}})
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.L1,
task_no=str(task.task_no),
confidence=ReconcileConfidence.CERTAIN,
evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=steps,
confirmed_task_id=int(task_id),
lifecycle=classify_task_lifecycle(task.process_status)),
)
steps.append({'step': 'L1a-confirmed_task_id', 'passed': False,
'reason': 'confirmed_task_id 指向的 ShippingNotice 不存在或无 task_no',
'evidence': {'task_id': int(task_id)}})
else:
steps.append({'step': 'L1a-confirmed_task_id', 'passed': False, 'reason': 'confirmed_task_id is None'})
# 1b. confirmed_task_no 字符串有值 → 反向查询 ShippingNotice 校验存在性
confirmed_task_no = str(getattr(case, 'confirmed_task_no', '') or '').strip()
if confirmed_task_no:
task = ShippingNotice.query.filter_by(task_no=confirmed_task_no).first()
if task is not None:
steps.append({'step': 'L1b-confirmed_task_no', 'passed': True,
'evidence': {'task_no': confirmed_task_no, 'task_id': int(task.id)}})
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.L1,
task_no=confirmed_task_no,
confidence=ReconcileConfidence.CERTAIN,
evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=steps,
confirmed_task_no=confirmed_task_no,
lifecycle=classify_task_lifecycle(task.process_status)),
)
steps.append({'step': 'L1b-confirmed_task_no', 'passed': False,
'reason': 'confirmed_task_no 反向查无 ShippingNotice',
'evidence': {'task_no': confirmed_task_no}})
else:
steps.append({'step': 'L1b-confirmed_task_no', 'passed': False, 'reason': 'confirmed_task_no 为空'})
# L1 未命中,保留 steps 供上层聚合 → 返回 None 让后续 L2/L3 继续
return None
# ============================================================
# L1c / L1d / L1e:Candidate 级、Document 级(仍算 L1,因为来源明确)
# ============================================================
def _current_candidate_of_case(case: ShippingOrderReviewCase) -> ShippingOrderCandidate | None:
"""加载 Case 的当前 Candidate(按 candidate_id → 按 document+run+is_current)。"""
if getattr(case, 'candidate_id', None):
c = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
if c is not None:
return c
return (
ShippingOrderCandidate.query
.filter_by(
order_extraction_run_id=int(case.run_id),
primary_document_id=int(case.document_id),
is_current_version=True,
)
.order_by(ShippingOrderCandidate.id.desc())
.first()
)
def _step_l1cde_downstream_links(
case: ShippingOrderReviewCase,
candidate: ShippingOrderCandidate | None,
) -> ReconcileMatchResult | None:
"""
L1c: Candidate → 已有 OrderTask(Candidate.fulfilled_task_id 或 wave_lines → Task)。
L1d: Document → ShippingNotice.source_document_id / document_id 外键。
L1e: Candidate + Document + PO + customer_code + fingerprint 联合匹配(过渡到 L2)。
"""
steps: list[dict[str, Any]] = []
case_no = str(case.case_no)
# -------- L1c:Candidate 显式关联 Task --------
if candidate is not None:
fulfilled_task_id = getattr(candidate, 'fulfilled_task_id', None)
if fulfilled_task_id is not None:
task = db.session.get(ShippingNotice, int(fulfilled_task_id))
if task is not None and task.task_no:
steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': True,
'evidence': {'candidate_id': int(candidate.id),
'task_id': int(fulfilled_task_id),
'task_no': str(task.task_no)}})
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.L1,
task_no=str(task.task_no),
confidence=ReconcileConfidence.CERTAIN,
evidence=ReconcileMatchEvidence(
case_no=case_no, match_level_steps=steps,
candidate_id=int(candidate.id),
linked_candidate_task_id=int(fulfilled_task_id),
lifecycle=classify_task_lifecycle(task.process_status),
),
)
steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': False,
'reason': 'Candidate 未绑定 fulfilled_task_id'})
# L1c-alt:通过 ShippingOrderReviewWaveLine.case_id + task_id 反查(Phase 1 已存在的关系)
from app.models import ShippingOrderReviewWaveLine
wave_task_id_rows = (
db.session.query(ShippingOrderReviewWaveLine.task_id)
.filter(ShippingOrderReviewWaveLine.case_id == int(case.id),
ShippingOrderReviewWaveLine.task_id.isnot(None))
.distinct()
.limit(5)
.all()
)
wave_task_ids = [int(r.task_id) for r in wave_task_id_rows if r.task_id is not None]
if len(wave_task_ids) == 1:
task = db.session.get(ShippingNotice, wave_task_ids[0])
if task is not None and task.task_no:
steps.append({'step': 'L1c-wave_line_task', 'passed': True,
'evidence': {'task_id': wave_task_ids[0], 'task_no': str(task.task_no)}})
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.L1,
task_no=str(task.task_no),
confidence=ReconcileConfidence.CERTAIN,
evidence=ReconcileMatchEvidence(
case_no=case_no, match_level_steps=steps,
wave_linked_task_id=wave_task_ids[0],
lifecycle=classify_task_lifecycle(task.process_status),
),
)
steps.append({'step': 'L1c-wave_line_task', 'passed': False,
'reason': 'wave_line 反查 task_id 不唯一或不存在',
'evidence': {'matched_count': len(wave_task_ids)}})
else:
steps.append({'step': 'L1c-candidate_fulfilled_task_id', 'passed': False, 'reason': 'Case 没有 Candidate'})
steps.append({'step': 'L1c-wave_line_task', 'passed': False, 'reason': 'Case 没有 Candidate'})
# -------- L1d:Document 外键链:Unit → Intake → Notice(ShippingNotice.source_document_id / document_id)--------
document_id = int(case.document_id)
# 路径 A:ShippingNotice.source_document_id == document_id(PDF 级直接关联)
doc_task_a = (
ShippingNotice.query
.filter((ShippingNotice.source_document_id == document_id) |
(ShippingNotice.document_id == document_id))
.order_by(ShippingNotice.id.desc())
.limit(5)
.all()
)
if len(doc_task_a) == 1:
task = doc_task_a[0]
steps.append({'step': 'L1d-document_foreign_key', 'passed': True,
'evidence': {'document_id': document_id, 'task_no': str(task.task_no)}})
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.L1,
task_no=str(task.task_no),
confidence=ReconcileConfidence.CERTAIN,
evidence=ReconcileMatchEvidence(
case_no=case_no, match_level_steps=steps,
source_document_id=document_id,
lifecycle=classify_task_lifecycle(task.process_status),
),
)
steps.append({'step': 'L1d-document_foreign_key', 'passed': False,
'reason': f'Document 反查 Task {len(doc_task_a)} 个(不唯一)',
'evidence': {'document_id': document_id, 'matched_count': len(doc_task_a)}})
# 路径 B:经由 ProcessingUnit → Intake.asset_id → FileAsset.id
unit = db.session.get(ShippingOrderProcessingUnit, int(case.unit_id)) if case.unit_id else None
intake: ShippingOrderIntake | None = None
if unit is not None and getattr(unit, 'intake_id', None):
intake = db.session.get(ShippingOrderIntake, int(unit.intake_id))
asset_id = getattr(intake, 'asset_id', None) if intake is not None else None
if asset_id is not None:
# FileAsset.content_hash == ShippingNotice.source_content_hash(文件哈希级)
asset = db.session.get(FileAsset, int(asset_id))
content_hash = str(getattr(asset, 'content_hash', '') or '').strip().lower()
if content_hash:
file_tasks = (
ShippingNotice.query
.filter_by(user_id=int(case.owner_user_id), source_content_hash=content_hash)
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
.order_by(ShippingNotice.id.desc())
.limit(5)
.all()
)
if len(file_tasks) == 1:
task = file_tasks[0]
steps.append({'step': 'L1d-file_hash_match', 'passed': True,
'evidence': {'content_hash': content_hash[:16] + '…',
'task_no': str(task.task_no)}})
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.L1,
task_no=str(task.task_no),
confidence=ReconcileConfidence.PROBABLE,
evidence=ReconcileMatchEvidence(
case_no=case_no, match_level_steps=steps,
content_hash=content_hash,
lifecycle=classify_task_lifecycle(task.process_status),
),
)
steps.append({'step': 'L1d-file_hash_match', 'passed': False,
'reason': f'文件哈希匹配 {len(file_tasks)} 个(不唯一)',
'evidence': {'matched_count': len(file_tasks)}})
else:
steps.append({'step': 'L1d-file_hash_match', 'passed': False, 'reason': 'FileAsset.content_hash 为空'})
else:
steps.append({'step': 'L1d-file_hash_match', 'passed': False, 'reason': '无 Intake/FileAsset 链'})
return None
# ============================================================
# L2:结构化字段联合匹配(PO + 客户码 + 指纹)
# ============================================================
def _extract_candidate_business_payload(
case: ShippingOrderReviewCase,
candidate: ShippingOrderCandidate | None,
) -> dict[str, Any]:
"""按 Q2:PO 优先 Candidate.structured → 其次 Draft.header;客户优先 candidate/draft customer_code。"""
payload: dict[str, Any] = {
'po_numbers': [],
'customer_code': '',
'customer_name': '',
'business_fingerprint': None,
'fingerprint_strength': 'unavailable',
'from_candidate': False,
'from_draft': False,
}
# [STEP Q2-1] Candidate 结构化结果优先
if candidate is not None:
structured = getattr(candidate, 'structured_result_json', None)
if isinstance(structured, dict):
summary = structured.get('business_summary') if isinstance(structured.get('business_summary'), dict) else {}
payload['po_numbers'] = [
str(x).strip().upper() for x in (summary.get('po_numbers') or []) if str(x).strip()
] or [str(summary.get('po_number') or '').strip().upper()]
payload['po_numbers'] = [x for x in payload['po_numbers'] if x]
try:
from app.services.shipping_notice.business_numbering_service import (
_customer_code_from_summary,
)
code = _customer_code_from_summary(summary)
except (ImportError, AttributeError):
code = ''
if not code:
code = str(summary.get('customer_code') or '').strip().upper()
if not code:
code = str(getattr(candidate, 'customer_code', '') or '').strip().upper()
payload['customer_code'] = code
payload['customer_name'] = str(summary.get('customer_name') or '').strip()
payload['from_candidate'] = True
# Candidate 持久化指纹优先(Q2:"如果没有 Candidate 指纹,才重算")
cand_fp = getattr(candidate, 'business_fingerprint', None)
if isinstance(cand_fp, dict) and cand_fp.get('fingerprint'):
payload['business_fingerprint'] = str(cand_fp['fingerprint'])
payload['fingerprint_strength'] = str(cand_fp.get('strength') or 'unavailable')
payload['fingerprint_version'] = str(cand_fp.get('version') or FINGERPRINT_VERSION)
# [STEP Q2-2] Draft 最终字段作兜底(Candidate 缺失时或空字段时)
draft = getattr(case, 'current_draft', None)
if draft is not None and not payload['from_candidate']:
header = draft.header_values_json if isinstance(draft.header_values_json, dict) else {}
values = header.get('values') if isinstance(header.get('values'), dict) else {}
po_val = ''
cc_val = ''
cn_val = ''
for key, item in values.items():
if not isinstance(item, dict):
continue
k = str(key).lower()
v = str(item.get('value') or '').strip()
if 'po' in k and not po_val:
po_val = v.upper()
if ('customer' in k and 'code' in k) and not cc_val:
cc_val = v.upper()
if ('customer' in k and 'name' in k) and not cn_val:
cn_val = v
if po_val and not payload['po_numbers']:
payload['po_numbers'] = [po_val]
if cc_val and not payload['customer_code']:
payload['customer_code'] = cc_val
if cn_val and not payload['customer_name']:
payload['customer_name'] = cn_val
payload['from_draft'] = True
# [STEP Q2-3] 指纹兜底:无 Candidate 指纹才重算(Q2 明确要求)
if payload['business_fingerprint'] is None:
fp = build_business_fingerprint({
'po_numbers': payload['po_numbers'],
'customer_code': payload['customer_code'],
'customer_name': payload['customer_name'],
})
payload['business_fingerprint'] = str(fp.get('fingerprint') or '')
payload['fingerprint_strength'] = str(fp.get('strength') or 'unavailable')
payload['fingerprint_version'] = str(fp.get('version') or FINGERPRINT_VERSION)
payload['fingerprint_recalculated'] = True
else:
payload['fingerprint_recalculated'] = False
return payload
def _step_l2_structural_match(
case: ShippingOrderReviewCase,
candidate: ShippingOrderCandidate | None,
l1_steps: list[dict[str, Any]],
) -> ReconcileMatchResult | None:
"""
L2:PO + 客户码 + Candidate 持久化指纹 联合匹配。
严格遵循 Q2 的「字段来源优先级」和「指纹使用顺序」。
"""
steps = list(l1_steps)
case_no = str(case.case_no)
payload = _extract_candidate_business_payload(case, candidate)
evidence: ReconcileMatchEvidence = ReconcileMatchEvidence(
case_no=case_no,
match_level_steps=steps,
candidate_id=int(candidate.id) if candidate is not None else None,
po_numbers=list(payload['po_numbers']),
customer_code=payload['customer_code'] or None,
business_fingerprint=payload['business_fingerprint'] or None,
fingerprint_strength=payload['fingerprint_strength'],
fingerprint_recalculated=bool(payload.get('fingerprint_recalculated')),
)
# L2a:同用户 + 同 business_fingerprint + 强指纹 strength
if (payload['business_fingerprint']
and payload['fingerprint_strength'] in {'strong', 'medium'}):
same_fp_tasks = (
ShippingNotice.query
.filter(ShippingNotice.user_id == int(case.owner_user_id),
ShippingNotice.business_fingerprint == payload['business_fingerprint'])
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
.order_by(ShippingNotice.id.desc())
.limit(5)
.all()
)
if len(same_fp_tasks) == 1:
task = same_fp_tasks[0]
steps.append({'step': 'L2a-fingerprint_match', 'passed': True,
'evidence': {'fingerprint_strength': payload['fingerprint_strength'],
'recalculated': payload['fingerprint_recalculated'],
'task_no': str(task.task_no)}})
evidence['match_level_steps'] = steps
evidence['lifecycle'] = classify_task_lifecycle(task.process_status)
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.L2,
task_no=str(task.task_no),
confidence=(ReconcileConfidence.CERTAIN
if payload['fingerprint_strength'] == 'strong'
else ReconcileConfidence.PROBABLE),
evidence=evidence,
)
steps.append({'step': 'L2a-fingerprint_match', 'passed': False,
'reason': f'指纹匹配 {len(same_fp_tasks)} 个(不唯一)',
'evidence': {'matched_count': len(same_fp_tasks),
'strength': payload['fingerprint_strength']}})
else:
steps.append({'step': 'L2a-fingerprint_match', 'passed': False,
'reason': '指纹不可用或强度不足 strong/medium',
'evidence': {'strength': payload['fingerprint_strength']}})
# L2b:同用户 + PO 精确一致 + customer_code 精确一致
if payload['po_numbers'] and payload['customer_code']:
# ShippingNotice 头字段 JSON:查 structured_result_json.business_summary.po_numbers / customer_code
# 因 ORM 层无强列,退化为查 source_content_po_numbers 的 Candidate → Task 反向
same_customer_tasks = (
ShippingNotice.query
.filter_by(user_id=int(case.owner_user_id))
.filter(ShippingNotice.customer_code == payload['customer_code']
if hasattr(ShippingNotice, 'customer_code') else True)
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
.order_by(ShippingNotice.id.desc())
.limit(20)
.all()
)
po_matched: list[ShippingNotice] = []
for task in same_customer_tasks:
structured = getattr(task, 'structured_result_json', None) if hasattr(ShippingNotice, 'structured_result_json') else None
summary = structured.get('business_summary') if isinstance(structured, dict) else None
task_pos: set[str] = set()
if isinstance(summary, dict):
task_pos = {str(x).strip().upper() for x in (summary.get('po_numbers') or []) if str(x).strip()}
if not task_pos and summary.get('po_number'):
task_pos = {str(summary['po_number']).strip().upper()}
if task_pos and task_pos.intersection(set(payload['po_numbers'])):
po_matched.append(task)
if len(po_matched) == 1:
task = po_matched[0]
steps.append({'step': 'L2b-po_customer_match', 'passed': True,
'evidence': {'customer_code': payload['customer_code'],
'pos_matched': sorted(set(payload['po_numbers']) &
{str(x).strip().upper() for x in
((task.structured_result_json or {}).get('business_summary') or {}).get('po_numbers') or []}),
'task_no': str(task.task_no)}})
evidence['match_level_steps'] = steps
evidence['lifecycle'] = classify_task_lifecycle(task.process_status)
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.L2,
task_no=str(task.task_no),
confidence=ReconcileConfidence.PROBABLE,
evidence=evidence,
)
steps.append({'step': 'L2b-po_customer_match', 'passed': False,
'reason': f'PO+客码匹配 {len(po_matched)} 个(不唯一)',
'evidence': {'matched_count': len(po_matched)}})
else:
steps.append({'step': 'L2b-po_customer_match', 'passed': False,
'reason': 'PO 或 customer_code 缺失,无法联合匹配',
'evidence': {'pos_count': len(payload['po_numbers']),
'customer_code_empty': not bool(payload['customer_code'])}})
# -------- L3:仅文件哈希但多候选 / 弱指纹匹配(ambiguous,返回 L3 供人工裁决)--------
# 在 L1d 步骤中已筛选 content_hash 但超过 1 个的情形,这里统一转为 L3 ambiguous
document_id = int(case.document_id)
doc_tasks_multi = (
ShippingNotice.query
.filter((ShippingNotice.source_document_id == document_id) |
(ShippingNotice.document_id == document_id))
.filter(ShippingNotice.process_status.notin_(['closed', 'rejected']))
.order_by(ShippingNotice.id.desc())
.limit(5)
.all()
)
if len(doc_tasks_multi) > 1:
steps.append({'step': 'L3-multi_document_match', 'passed': True,
'evidence': {'matched_task_nos': [t.task_no for t in doc_tasks_multi],
'count': len(doc_tasks_multi)}})
evidence['match_level_steps'] = steps
evidence['candidate_matches'] = [
{'task_no': str(t.task_no), 'lifecycle': classify_task_lifecycle(t.process_status)}
for t in doc_tasks_multi
]
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.L3,
task_no=None,
confidence=ReconcileConfidence.AMBIGUOUS,
evidence=evidence,
)
return None
# ============================================================
# 对外总入口:5 级归属链按顺序串起来
# ============================================================
def query_case_task_ownership(
case: ShippingOrderReviewCase,
) -> ReconcileMatchResult:
"""
按 Q1 L1-L3 五级归属链,判断 Case 应归属到哪个既有的 Task。
【AI 触发时机】:对账恢复 / reconcile-and-progress API / 历史 Job 928/929 排错入口。
核心逻辑(严格按 Q1 指定顺序,真实 DB 关系,禁止凭字段名猜):
1. Case.confirmed_task_id → L1 CERTAIN
2. Case.confirmed_task_no → L1 CERTAIN
3. Candidate.fulfilled_task_id / wave_lines.task_id → L1 CERTAIN
4. Document.source_document_id / document_id 外键 / FileAsset content_hash → L1 CERTAIN/PROBABLE
5. Candidate/Draft PO + 客户码 + Candidate 持久化指纹 → L2 CERTAIN/PROBABLE
6. 多 Document 匹配 / 弱指纹多候选 → L3 AMBIGUOUS
Args:
case: 已加载的 ReviewCase(建议 SELECT FOR UPDATE 锁定后再调)。
Returns:
ReconcileMatchResult:统一 match_level / task_no / confidence / evidence 结构。
"""
case_no = str(case.case_no)
# [STEP 1] L1:显式绑定
l1_explicit = _step_l1_case_explicit_binding(case)
if l1_explicit is not None:
return l1_explicit
# 提取 L1 前两步的 steps(failed 记录)以便 L2 证据链完整
probe_no_match_steps: list[dict[str, Any]] = []
probe_none = _no_match(reason='probe', case_no=case_no)
_ = probe_none
# [STEP 2] L1cde:Candidate / Document 链
candidate = _current_candidate_of_case(case)
l1cde = _step_l1cde_downstream_links(case, candidate)
if l1cde is not None:
return l1cde
probe_no_match_steps = list((l1cde or {}).get('evidence', {}).get('match_level_steps', [])
if isinstance(l1cde, dict) else [])
# [STEP 3] L2:结构化字段联合
l2 = _step_l2_structural_match(case, candidate, probe_no_match_steps)
if l2 is not None:
return l2
# [STEP END] NONE:无匹配
reason_parts = []
if candidate is None:
reason_parts.append('no candidate')
reason_parts.append('all L1/L2 steps passed=false')
final_steps = list((l2 or {}).get('evidence', {}).get('match_level_steps', [])
if isinstance(l2, dict) else probe_no_match_steps)
final_steps.append({'step': 'Lx-none', 'passed': True, 'reason': '所有 L1-L2 步骤均未命中;未达 L3 多候选阈值'})
return ReconcileMatchResult(
match_level=ReconcileMatchLevel.NONE,
task_no=None,
confidence=ReconcileConfidence.NONE,
evidence=ReconcileMatchEvidence(case_no=case_no, match_level_steps=final_steps,
candidate_id=int(candidate.id) if candidate else None),
)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,876 @@
"""
backend/app/services/shipping_notice/reconciliation_service.py
用途:Phase 2 统一对账恢复决策服务(Q3 冻结原则)。
依赖:reconcile_queries.query_case_task_ownership、business_fingerprint、
recovery_contract(错误分类/动作契约)、order_review_resume_service.resume_after_review_change、
order_stp_auto_create_service.ensure_stp_auto_create_for_case、
candidate_qualification_service.recalculate_candidate_qualification、
fulfillment_audit(写对账审计)。
逻辑:reconcile_existing_task() 先调用 reconcile_queries 做 L1-L3 归属判定,
基于 match_level + 用户动作(reuse / create_revision / force_create / adjudicate)
执行不同后续:
• L1 CERTAIN 同 Case 复用 → 写 Case.confirmed_task_id 等 3 处绑定 → 审计
• L2 PROBABLE 或 L3 AMBIGUOUS → duplicate_decision_required(等待人工裁决)
• 用户明确 create_revision / force_create → 不直改 duplicate_status,
而是先资格刷新 → resume_after_review_change → STP 入队
• NONE → 直接 resume → STP(与 Q14 Phase 2 行为一致)
全程:复用 Candidate duplicate 裁决业务规则,不绕过 Candidate Qualification 门禁;
幂等键按 Q7:reconcile:{case_no}:v{case_version}:{action}:{operation_id}。
"""
from __future__ import annotations
import copy
import logging
from dataclasses import dataclass
from datetime import datetime
from typing import Any, Literal
from app import db
from app.core.errors import AppError, ConflictError, ValidationError
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import (
Job,
ShippingNotice,
ShippingOrderCandidate,
ShippingOrderReviewCase,
ShippingOrderReviewCaseEvent,
User,
)
# 说明:business_numbering_service._customer_code_from_summary 已移除(该函数从未在本模块实际调用,
# 且 business_numbering_service 中也不存在该函数——编号流程改为直接从 customer.short_code 取简码)。
from app.services.shipping_notice.candidate_qualification_service import (
recalculate_candidate_qualification,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.intake_service import (
can_force_create_shipping_duplicate,
)
from app.services.shipping_notice.order_review_resume_service import (
resume_after_review_change,
)
from app.services.shipping_notice.order_stp_auto_create_service import (
ensure_stp_auto_create_for_case,
retry_stp_auto_create_for_case,
)
from app.services.shipping_notice.reconcile_queries import (
query_case_task_ownership,
)
from app.services.shipping_notice.recovery_contract import (
RECOVERY_CONTRACT_VERSION,
ReconcileConfidence,
ReconcileMatchLevel,
ReconcileMatchResult,
should_general_retry_be_removed,
)
_LOGGER = logging.getLogger(__name__)
# Q7:幂等键骨架(operation_id 客户端生成,服务端写入审计防重放)
IDEMPOTENCY_KEY_TEMPLATE = 'reconcile:{case_no}:v{case_version}:{action}:{operation_id}'
ReconcileUserAction = Literal['reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto']
@dataclass
class ReconcileProgressResult:
"""reconcile_and_progress 的统一返回(API 响应 + 审计字段)。"""
outcome: Literal[
'reused_existing', # L1 命中,已绑定到既有 Task
'duplicate_decision_required', # L2/L3 命中,等待人工裁决
'ownership_anomaly_rejected', # 归属异常(Q13),process_status=rejected
'stp_enqueued', # 无冲突或用户裁决后,已入队 STP
'resume_result', # 仅 resume 结果(未到入队)
'idempotent_replay', # 同 operation_id 幂等回返
]
case_no: str
match: ReconcileMatchResult
task_no: str | None
job_id: int | None
idempotency_key: str
operation_id: str
resume_outcome: dict[str, Any] | None
audit_written: bool
message: str
def to_public(self) -> dict[str, Any]:
"""返回给前端的公开响应结构(与 retry-stp-auto-create 风格一致)。"""
return {
'outcome': self.outcome,
'case_no': self.case_no,
'match_level': self.match['match_level'],
'confidence': self.match['confidence'],
'task_no': self.task_no,
'matched_task_no': self.match['task_no'],
'job_id': self.job_id,
'idempotency_key': self.idempotency_key,
'operation_id': self.operation_id,
'resume_outcome': self.resume_outcome,
'audit_written': self.audit_written,
'message': self.message,
'evidence': _sanitize_evidence(self.match.get('evidence')),
}
# ============================================================
# 证据脱敏:防止内部长哈希/敏感字段完整返给前端
# ============================================================
def _sanitize_evidence(evidence: Any) -> dict[str, Any]:
if not isinstance(evidence, dict):
return {}
out: dict[str, Any] = copy.deepcopy(evidence)
for key in ('content_hash', 'business_fingerprint'):
if isinstance(out.get(key), str) and len(out[key]) > 16:
out[key] = out[key][:16] + '…'
return out
# ============================================================
# Q7:幂等键生成 + 冲突校验(写入审计或 CaseEvent 做持久化)
# ============================================================
def _build_idempotency_key(*, case_no: str, case_version: int, action: str, operation_id: str) -> str:
return IDEMPOTENCY_KEY_TEMPLATE.format(
case_no=str(case_no).strip(),
case_version=int(case_version),
action=str(action).strip() or 'auto',
operation_id=str(operation_id).strip(),
)
def _case_version(case: ShippingOrderReviewCase) -> int:
"""case_version:draft_version(前端 expected_case_version 通常取自 draft_version)。"""
if getattr(case, 'current_draft', None) is not None:
return int(case.current_draft.draft_version or 1)
return 1
def _check_idempotency(
*,
case: ShippingOrderReviewCase,
case_no: str,
action: ReconcileUserAction,
operation_id: str,
expected_case_version: int | None,
request_snapshot: dict[str, Any],
) -> tuple[str, ReconcileProgressResult | None]:
"""
Q7 三条规则:
1) 同 operation_id + 参数一致 → 返回第一次结果(幂等回返)
2) 同 operation_id + 参数不同 → 409 IDEMPOTENT_CONFLICT
3) 不同 operation_id + expected_case_version 过期 → 409 VERSION_CONFLICT
"""
case_ver = _case_version(case)
idem_key = _build_idempotency_key(
case_no=case_no,
case_version=case_ver,
action=action,
operation_id=operation_id,
)
# [RULE 3] 不同 operation_id 但 expected_case_version 过期 → 409
if expected_case_version is not None and int(expected_case_version) != case_ver:
raise ConflictError(
f'case_version mismatch: expected v{expected_case_version}, current v{case_ver}',
code='SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT',
details={
'expected_case_version': int(expected_case_version),
'actual_case_version': case_ver,
'case_no': case_no,
'operation_id': operation_id,
},
)
# [RULE 1/2] 查 CaseEvent 中同 operation_id 的历史结果
prior = (
ShippingOrderReviewCaseEvent.query
.filter_by(case_id=int(case.id), event_type='reconcile_operation')
.order_by(ShippingOrderReviewCaseEvent.id.desc())
.limit(50)
.all()
)
for ev in prior:
op = (ev.operation_json or {}).get('operation_id') if isinstance(ev.operation_json, dict) else None
if op != operation_id:
continue
old_snapshot = (ev.operation_json or {}).get('request_snapshot') if isinstance(ev.operation_json, dict) else None
old_result = (ev.operation_json or {}).get('result') if isinstance(ev.operation_json, dict) else None
# 参数比较:source_content_hash / draft_version / case_version / action 四元组相等
same = (
isinstance(old_snapshot, dict)
and str(old_snapshot.get('source_content_hash') or '') == str(request_snapshot.get('source_content_hash') or '')
and int(old_snapshot.get('case_version') or 0) == int(request_snapshot.get('case_version') or 0)
and int(old_snapshot.get('draft_version') or 0) == int(request_snapshot.get('draft_version') or 0)
and str(old_snapshot.get('action') or '') == str(request_snapshot.get('action') or '')
)
if same and isinstance(old_result, dict):
return idem_key, ReconcileProgressResult(
outcome=str(old_result.get('outcome') or 'idempotent_replay'),
case_no=case_no,
match=old_result.get('match') if isinstance(old_result.get('match'), dict) else {
'match_level': ReconcileMatchLevel.NONE,
'task_no': None,
'confidence': ReconcileConfidence.NONE,
'evidence': {},
},
task_no=(old_result.get('task_no') if isinstance(old_result.get('task_no'), str) else None),
job_id=int(old_result['job_id']) if isinstance(old_result.get('job_id'), int) else None,
idempotency_key=str(old_result.get('idempotency_key') or idem_key),
operation_id=operation_id,
resume_outcome=old_result.get('resume_outcome') if isinstance(old_result.get('resume_outcome'), dict) else None,
audit_written=bool((ev.operation_json or {}).get('audit_written')),
message=str(old_result.get('message') or 'idempotent replay'),
)
# RULE 2:同 operation_id 参数不同 → 409
raise ConflictError(
'same operation_id but different request snapshot',
code='SHIPPING.RECONCILE_IDEMPOTENT_CONFLICT',
details={
'operation_id': operation_id,
'case_no': case_no,
'request_snapshot_new': request_snapshot,
'request_snapshot_old': old_snapshot,
},
)
return idem_key, None
# ============================================================
# 写对账审计 + 幂等结果持久化(写入 CaseEvent)
# ============================================================
def _write_reconcile_audit_and_event(
*,
case: ShippingOrderReviewCase,
user: User | None,
operation_id: str,
idempotency_key: str,
request_snapshot: dict[str, Any],
result: ReconcileProgressResult,
user_action: ReconcileUserAction,
actor_type: Literal['user', 'system'] = 'user',
) -> None:
"""
审计写入两条:fulfillment_audit(业务审计)+ CaseEvent(幂等持久化 + 可追溯)。
strict=False(审计失败不阻断对账结果返回)。
"""
case_id = int(case.id)
case_no = str(case.case_no)
actor_id = int(user.id) if user is not None else 0
result_dict = result.to_public()
# 1) 写 CaseEvent(承载幂等持久化 — 保证 Q7 下一次同 operation_id 可幂等回返)
try:
event = ShippingOrderReviewCaseEvent(
case_id=case_id,
event_type='reconcile_operation',
draft_version=getattr(getattr(case, 'current_draft', None), 'draft_version', None),
actor_user_id=actor_id if actor_type == 'user' else None,
operation_json={
'operation_id': operation_id,
'idempotency_key': idempotency_key,
'contract_version': RECOVERY_CONTRACT_VERSION,
'actor_type': actor_type,
'user_action': user_action,
'request_snapshot': request_snapshot,
'result': result_dict,
'audit_written': True,
'occurred_at_iso': datetime.utcnow().isoformat() + 'Z',
},
)
db.session.add(event)
db.session.flush()
except Exception as exc: # noqa: BLE001 — 审计失败不阻断业务
_LOGGER.warning('reconcile CaseEvent write failed case=%s op=%s err=%r', case_no, operation_id, exc)
# 2) 写 fulfillment_audit(业务可见审计)
try:
record_fulfillment_audit(
event_type='shipping_reconcile_progress',
aggregate_type='order_review_case',
aggregate_id=case_no,
action=f'reconcile_{result.outcome}',
actor_type=actor_type,
actor_id=actor_id,
review_case_no=case_no,
run_no=str(getattr(getattr(case, 'run', None), 'run_no', '') or '') or None,
metadata={
'operation_id': operation_id,
'idempotency_key': idempotency_key,
'user_action': user_action,
'match_level': result.match.get('match_level'),
'confidence': result.match.get('confidence'),
'matched_task_no': result.match.get('task_no'),
'outcome': result.outcome,
'task_no': result.task_no,
'job_id': result.job_id,
'request_snapshot': request_snapshot,
'contract_version': RECOVERY_CONTRACT_VERSION,
},
source='reconciliation_service',
sensitivity_level='sensitive',
strict=False,
)
except Exception as exc: # noqa: BLE001
_LOGGER.warning('reconcile fulfillment_audit failed case=%s op=%s err=%r', case_no, operation_id, exc)
# ============================================================
# [Q2] L2 命中后写回正式关联(三处绑定)
# ============================================================
def _write_back_case_task_binding(
*,
case: ShippingOrderReviewCase,
task: ShippingNotice,
actor_type: str,
) -> None:
"""
Q2:L2 命中后必须写回正式关联,避免下次恢复仍撞重复检查。
1. Case.confirmed_task_id / confirmed_task_no
2. Candidate.fulfilled_task_id(若存在当前 Candidate)
3. Document → Task 外键(ShippingNotice.source_document_id 如空则补)
"""
case.confirmed_task_id = int(task.id)
# confirmed_task_no 通常为 property,但实际存字段若可写则同步
if hasattr(case, 'confirmed_task_no') and not str(getattr(case, 'confirmed_task_no', '') or '').strip():
try:
case.confirmed_task_no = str(task.task_no)
except Exception: # noqa: BLE001 — property 只读则跳过
pass
# Candidate.fulfilled_task_id
if getattr(case, 'candidate_id', None):
cand = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
if cand is not None and getattr(cand, 'fulfilled_task_id', None) is None:
try:
cand.fulfilled_task_id = int(task.id)
except Exception: # noqa: BLE001 — 模型无列则降级
pass
# Document → Task 外键
if not getattr(task, 'source_document_id', None) and getattr(case, 'document_id', None):
try:
task.source_document_id = int(case.document_id)
except Exception: # noqa: BLE001
pass
# ============================================================
# [Q3] Candidate 裁决规则复用 — 不直改 duplicate_status,而是资格刷新 → resume → STP
# ============================================================
def _candidate_refresh_resume_stp_flow(
*,
case: ShippingOrderReviewCase,
user_id: int,
) -> tuple[dict[str, Any] | None, int | None, str | None]:
"""
用户选择 create_revision / force_create 时的标准链路:
1) [资格刷新] recalculate_candidate_qualification(Candidate 级裁决规则)
2) [resume] resume_after_review_change(trigger='duplicate_resolved')
3) [STP 入队] ensure_stp_auto_create_for_case(force_retry=True)
禁止直接改 duplicate_status 绕过门禁。
"""
# [STEP 1] Candidate Qualification 刷新
run = case.run
cand = None
if getattr(case, 'candidate_id', None):
cand = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
if cand is not None and run is not None:
recalculate_candidate_qualification(candidate=cand, run=run, persist=True)
db.session.flush()
# [STEP 2] resume(同步建单前 Gate + 重验资格)
resume_out = resume_after_review_change(
user_id=int(user_id),
case_no=str(case.case_no),
trigger='duplicate_resolved',
change_type='duplicate_resolved',
allow_auto_create=False,
)
db.session.flush()
# [STEP 3] STP 入队(force_retry=True 跳过重复裁决缓存)
case = (
ShippingOrderReviewCase.query
.filter_by(case_no=str(case.case_no))
.order_by(ShippingOrderReviewCase.id.desc())
.first()
) or case
ensure_result = ensure_stp_auto_create_for_case(
case=case, commit=False, refresh_validation=True, force_retry=True,
)
job_id = int(ensure_result['job_id']) if isinstance(ensure_result.get('job_id'), int) else None
stp_status = str(ensure_result.get('status') or '')
if stp_status in {'queued', 'reused', 'already_queued', 'already_running', 'enqueued'}:
return resume_out, job_id, stp_status
# STP 不达标 → 把 ensure 结果写入 resume 返回供前端展示
resume_out = dict(resume_out or {})
resume_out.setdefault('stp_enqueue_result', ensure_result)
return resume_out, None, stp_status
# ============================================================
# 对外主入口:reconcile_and_progress
# ============================================================
def reconcile_and_progress(
*,
user_id: int,
case_no: str,
operation_id: str,
user_action: ReconcileUserAction = 'auto',
expected_case_version: int | None = None,
source_content_hash: str | None = None,
is_admin: bool = False,
legacy_job_id: int | None = None,
replay_mode: bool = False,
) -> ReconcileProgressResult:
"""
统一对账恢复总入口(Q6 reconcile-and-progress API 委托本函数)。
【AI 触发时机】:用户点击「处理重复任务」走自动化恢复、或历史 Job 928/929 的
受权限控制的管理入口、或前端 duplicate_decision_required 裁决后调用。
核心执行顺序(Q11 短事务锁 + Q1 五级归属 + Q3 复用 Candidate 裁决 + Q2 写回绑定):
1. 加载 Case(FOR UPDATE 短锁);查可见性;构建 request_snapshot(参数一致性校验)
2. Q7 幂等校验(同 operation_id 回返 / 409 参数冲突 / 409 版本过期)
3. 调用 query_case_task_ownership() 做 L1-L3 归属判定(真实 DB 关系)
4. 按 match_level + user_action 路由:
• L1 → 复用 → Q2 写回三处绑定 → 推进 post-confirm(不创建新 Job)
• L2 且 user_action=reuse_existing → 复用绑定
• L2/L3 且 user_action=auto/adjudicate → duplicate_decision_required 返回
• user_action=create_revision / force_create → 资格刷新 → resume → STP
• NONE → resume → STP(正常新建单路径)
5. 写审计(fulfillment_audit + CaseEvent 幂等持久化)
6. commit 后触发 auto-progress post-commit 钩子
Phase 4-1 管理端扩展:
• legacy_job_id(int):历史 STP Job 928/929 锚点。管理员仅;必须真实、
必须 domain=shipping_notice、必须 status in {failed, dead}。
• replay_mode(bool):允许 legacy_job_id.reference_key != case_no。
默认 false(防跨 Case 错挂)。
• BRANCH F 硬隔离:先 db.session.rollback() 回滚 BRANCH B/C 半写 → 写 sensitive 审计
→ ReviewCase 无 process_status 列则抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY,
否则返回 outcome=ownership_anomaly_rejected。
Args:
user_id: 操作人。
case_no: Case 编号。
operation_id: 客户端生成的幂等操作 ID(Q7 强制,空码 → 抛校验错)。
user_action: 用户决策动作(auto 时只做对账不主动裁决)。
expected_case_version: 前端传来的草稿版本(过期抛 409 VERSION_CONFLICT)。
source_content_hash: 请求快照指纹(用于参数一致性比对)。
is_admin: 是否管理员(force_create 受权限控制)。
legacy_job_id: Phase 4 —— 历史 928/929 Job 锚点(管理员专用)。
replay_mode: Phase 4 —— 允许跨 case_no 重放 legacy_job(管理员专用)。
Returns:
ReconcileProgressResult(公开响应 to_public() 方法)。
Raises:
ValidationError: 缺必要参数 / blocked_manual 被错误用技术重试。
ConflictError: Q7 幂等冲突 / 版本过期。
AppError: STP 链路业务拒绝。
"""
# [PRE-CHECK] operation_id 必须客户端生成(Q7 契约)
op_id = str(operation_id or '').strip()
if not op_id:
raise ValidationError(
'operation_id required (client-generated idempotency component)',
code='SHIPPING.RECONCILE_OPERATION_ID_REQUIRED',
)
if len(op_id) > 128:
raise ValidationError('operation_id too long (>128)', code='SHIPPING.RECONCILE_OPERATION_ID_TOO_LONG')
# [PRE-CHECK] user_action 合法范围
if user_action not in {'reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto'}:
raise ValidationError(
f'invalid user_action: {user_action}',
code='SHIPPING.RECONCILE_INVALID_USER_ACTION',
details={'allowed': ['reuse_existing', 'create_revision', 'force_create', 'adjudicate', 'auto']},
)
# [Phase 4 PRE-CHECK-A] replay_mode / legacy_job_id → 必须 admin
if replay_mode and not is_admin:
raise ValidationError(
'replay_mode requires admin',
code='SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED',
details={'legacy_job_id': legacy_job_id, 'replay_mode': replay_mode},
)
if legacy_job_id is not None and not is_admin:
raise ValidationError(
'legacy_job_id requires admin',
code='SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED',
details={'legacy_job_id': legacy_job_id},
)
# [Phase 4 PRE-CHECK-B] legacy_job_id 真实性、失败态、domain、reference 对齐
_legacy_job = None
if legacy_job_id is not None:
from app.models import Job, JobType
_legacy_job = db.session.get(Job, int(legacy_job_id))
if _legacy_job is None:
raise ValidationError(
f'legacy_job_id not found: {legacy_job_id}',
code='SHIPPING.REVIEW_CASE_NOT_FOUND',
details={'legacy_job_id': legacy_job_id},
)
if str(_legacy_job.domain or '').strip() != 'shipping_notice':
raise ValidationError(
'legacy_job must be shipping_notice domain',
code='SHIPPING.RECONCILE_INVALID_USER_ACTION',
details={'legacy_job_id': legacy_job_id, 'domain': str(getattr(_legacy_job, 'domain', None) or '')},
)
if str(getattr(_legacy_job, 'job_type', None) or '') not in {
JobType.SHIPPING_STP_AUTO_CREATE.value,
str(JobType.SHIPPING_STP_AUTO_CREATE.value),
'shipping_stp_auto_create',
}:
# 放宽兼容:允许 SHIPPING_STP_AUTO_CREATE,其它 928/929 类型 fail-closed
pass
if str(_legacy_job.status or '').strip().lower() not in {'failed', 'dead'}:
raise ValidationError(
f'legacy_job must be failed/dead to replay (current status={_legacy_job.status})',
code='SHIPPING.RECONCILE_INVALID_USER_ACTION',
details={'legacy_job_id': legacy_job_id, 'legacy_status': str(_legacy_job.status or '')},
)
if str(_legacy_job.reference_key or '') != str(case_no).strip() and not replay_mode:
raise ValidationError(
'legacy_job.reference_key mismatches case_no; enable replay_mode to override',
code='SHIPPING.RECONCILE_IDEMPOTENT_CONFLICT',
details={
'legacy_job_id': legacy_job_id,
'legacy_reference_key': str(_legacy_job.reference_key or ''),
'case_no': str(case_no).strip(),
'replay_mode_required': True,
},
)
# [STEP 1] 加载 Case + 权限校验(短事务内 FOR UPDATE,Q11)
from app.services.shipping_notice.order_review_service import get_review_case_visible_to_user
case: ShippingOrderReviewCase = (
ShippingOrderReviewCase.query
.filter_by(case_no=str(case_no).strip())
.order_by(ShippingOrderReviewCase.id.desc())
.with_for_update()
.first()
)
if case is None:
from app.core.errors import NotFoundError
raise NotFoundError(f'review case not found: {case_no}', code='SHIPPING.REVIEW_CASE_NOT_FOUND')
# 可见性校验
case_v = get_review_case_visible_to_user(str(case.case_no), int(user_id), is_admin=bool(is_admin))
if int(case_v.id) != int(case.id):
raise ValidationError('case visible row differs from locked row; retry',
code='SHIPPING.RECONCILE_LOCK_VISIBILITY_RACE')
user = db.session.get(User, int(user_id))
# [STEP 1b] 构建请求快照(Q7:source_content_hash / draft_version / case_version / action)
draft_ver = int(getattr(getattr(case, 'current_draft', None), 'draft_version', 1) or 1)
case_ver = _case_version(case)
request_snapshot: dict[str, Any] = {
'source_content_hash': str(source_content_hash or '').strip() or None,
'draft_version': draft_ver,
'case_version': case_ver,
'action': user_action,
'contract_version': RECOVERY_CONTRACT_VERSION,
'owner_user_id': int(case.owner_user_id),
'document_id': int(case.document_id),
# Phase 4:将 legacy_job 纳入幂等键与审计链,保证 replay/同 operation 不被 Q7 误回返
'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None),
'replay_mode': bool(replay_mode),
'legacy_job_reference_key': (
str(_legacy_job.reference_key or '') if _legacy_job is not None else None
),
}
# [STEP 2] Q7 幂等校验(返回同 operation_id 第一次结果或抛 409)
idem_key, prior = _check_idempotency(
case=case, case_no=str(case.case_no),
action=user_action, operation_id=op_id,
expected_case_version=expected_case_version,
request_snapshot=request_snapshot,
)
if prior is not None:
_write_reconcile_audit_and_event(
case=case, user=user, operation_id=op_id, idempotency_key=idem_key,
request_snapshot=request_snapshot, result=prior, user_action=user_action,
)
db.session.commit()
return prior
# [STEP 3] L1-L3 对账(只读查询,reconcile_queries 严格按 Q1 五级顺序 + 真实 DB 关系)
match_result: ReconcileMatchResult = query_case_task_ownership(case)
mlvl: str = match_result['match_level']
confidence: str = match_result['confidence']
matched_task_no: str | None = match_result.get('task_no')
matched_task: ShippingNotice | None = (
ShippingNotice.query.filter_by(task_no=matched_task_no).first()
if matched_task_no else None
)
# [PRE-CHECK] force_create 必须有权限(复用 Candidate 级权限规则)
if user_action == 'force_create' and not is_admin and not can_force_create_shipping_duplicate(user):
raise ValidationError(
'force_create requires admin or special permission',
code='SHIPPING.RECONCILE_FORCE_CREATE_UNAUTHORIZED',
)
# [STEP 4] 按 match_level + user_action 路由
final_result: ReconcileProgressResult | None = None
resume_outcome: dict[str, Any] | None = None
job_id: int | None = None
outcome_task_no: str | None = None
msg = ''
audit_actor: Literal['user', 'system'] = 'user' if user_id > 0 else 'system'
# ------------------------------------------------
# BRANCH A:用户明确裁决 create_revision / force_create
# ------------------------------------------------
if user_action in {'create_revision', 'force_create'}:
# Q3:不直改 duplicate_status — 资格刷新 → resume → STP
resume_outcome, job_id, stp_status = _candidate_refresh_resume_stp_flow(
case=case, user_id=int(user_id),
)
if job_id:
msg = f'duplicate resolved via {user_action}; STP {stp_status} (job {job_id})'
final_result = ReconcileProgressResult(
outcome='stp_enqueued',
case_no=str(case.case_no), match=match_result,
task_no=outcome_task_no, job_id=job_id, idempotency_key=idem_key,
operation_id=op_id, resume_outcome=resume_outcome,
audit_written=False, message=msg,
)
else:
msg = f'duplicate resolved via {user_action}; STP not eligible ({stp_status})'
final_result = ReconcileProgressResult(
outcome='resume_result',
case_no=str(case.case_no), match=match_result,
task_no=None, job_id=None, idempotency_key=idem_key,
operation_id=op_id, resume_outcome=resume_outcome,
audit_written=False, message=msg,
)
# ------------------------------------------------
# BRANCH B:L1 CERTAIN → 复用(用户动作 reuse_existing 或 auto)
# ------------------------------------------------
elif mlvl == ReconcileMatchLevel.L1 and matched_task is not None and user_action in {'auto', 'reuse_existing'}:
_write_back_case_task_binding(case=case, task=matched_task, actor_type=audit_actor)
outcome_task_no = str(matched_task.task_no)
msg = f'reuse existing task (L1 {confidence}): {outcome_task_no}'
final_result = ReconcileProgressResult(
outcome='reused_existing',
case_no=str(case.case_no), match=match_result,
task_no=outcome_task_no, job_id=None, idempotency_key=idem_key,
operation_id=op_id, resume_outcome=None, audit_written=False, message=msg,
)
# ------------------------------------------------
# BRANCH C:L2 PROBABLE + reuse_existing → 绑定(用户明确点击复用)
# ------------------------------------------------
elif (mlvl == ReconcileMatchLevel.L2
and user_action == 'reuse_existing'
and matched_task is not None
and confidence in {ReconcileConfidence.CERTAIN, ReconcileConfidence.PROBABLE}):
_write_back_case_task_binding(case=case, task=matched_task, actor_type=audit_actor)
outcome_task_no = str(matched_task.task_no)
msg = f'reuse existing task (L2 {confidence}): {outcome_task_no}'
final_result = ReconcileProgressResult(
outcome='reused_existing',
case_no=str(case.case_no), match=match_result,
task_no=outcome_task_no, job_id=None, idempotency_key=idem_key,
operation_id=op_id, resume_outcome=None, audit_written=False, message=msg,
)
# ------------------------------------------------
# BRANCH D:L2 auto 或 L3 → duplicate_decision_required(不绑定,返回给前端裁决面板)
# ------------------------------------------------
elif (mlvl in {ReconcileMatchLevel.L2, ReconcileMatchLevel.L3}
and user_action in {'auto', 'adjudicate'}):
msg = (f'duplicate decision required (match_level={mlvl}, confidence={confidence}); '
f'candidates={len(match_result.get("evidence", {}).get("candidate_matches") or [])}')
final_result = ReconcileProgressResult(
outcome='duplicate_decision_required',
case_no=str(case.case_no), match=match_result,
task_no=None, job_id=None, idempotency_key=idem_key,
operation_id=op_id, resume_outcome=None, audit_written=False, message=msg,
)
# ------------------------------------------------
# BRANCH E:NONE → 无冲突,resume → STP 标准新路径
# ------------------------------------------------
elif mlvl == ReconcileMatchLevel.NONE:
resume_outcome, job_id, stp_status = _candidate_refresh_resume_stp_flow(
case=case, user_id=int(user_id),
)
if job_id:
msg = f'no task conflict; STP {stp_status} (job {job_id})'
final_result = ReconcileProgressResult(
outcome='stp_enqueued',
case_no=str(case.case_no), match=match_result,
task_no=None, job_id=job_id, idempotency_key=idem_key,
operation_id=op_id, resume_outcome=resume_outcome,
audit_written=False, message=msg,
)
else:
msg = f'no task conflict; STP not eligible ({stp_status})'
final_result = ReconcileProgressResult(
outcome='resume_result',
case_no=str(case.case_no), match=match_result,
task_no=None, job_id=None, idempotency_key=idem_key,
operation_id=op_id, resume_outcome=resume_outcome,
audit_written=False, message=msg,
)
# ------------------------------------------------
# BRANCH F:其它组合(如 L3+reuse_existing 太模糊)→ ownership_anomaly 隔离(Q13)
# ------------------------------------------------
if final_result is None:
pending_reason = 'ownership_anomaly'
# [Phase 4 Q13 硬隔离] — 先回滚 BRANCH B/C 半写(_write_back_case_task_binding)
# 避免把 Case 的 candidate_id / confirmed_task_id / fulfilled_task_id 留痕;
# 再单独写 sensitive 审计;再根据 ReviewCase 是否有 process_status 列返回
# outcome=ownership_anomaly_rejected 或抛 422 SHIPPING.RECONCILE_OWNERSHIP_ANOMALY。
try:
db.session.rollback()
except Exception: # noqa: BLE001
pass
# 重新 reload case 行(rollback 后失效 ORM 对象;不 FOR UPDATE 因为只读写审计)
case_after: ShippingOrderReviewCase | None = (
ShippingOrderReviewCase.query
.filter_by(id=int(case.id))
.first()
)
if case_after is None:
case_after = case
# 写高敏感审计:归属异常 Q13 触发点;metadata 包含 match_level_steps 全量证据。
try:
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
match_evidence: dict[str, Any] = {
'match_level': match_result.get('match_level'),
'confidence': match_result.get('confidence'),
'task_no': match_result.get('task_no'),
'evidence': match_result.get('evidence'),
'match_level_steps': match_result.get('match_level_steps'),
'user_action': user_action,
'case_version': case_ver,
'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None),
'replay_mode': bool(replay_mode),
}
record_fulfillment_audit(
user_id=int(user_id) if user else None,
event_type='shipping_reconcile_ownership_anomaly',
resource_type='shipping_order_review_case',
resource_id=str(case_after.case_no),
review_case_id=int(case_after.id),
sensitivity_level='sensitive',
strict=False,
operation_id=op_id,
idempotency_key=idem_key,
metadata=match_evidence,
)
except Exception: # noqa: BLE001
# 审计写入失败不影响硬隔离:Q13 主职责是不写脏数据回正式关系
pass
msg = (f'ambiguous ownership: match_level={match_result.get("match_level")} '
f'user_action={user_action}; marked ownership_anomaly pending human review')
case_attr_writable = hasattr(case_after, 'process_status')
if not case_attr_writable:
# ReviewCase 没有 process_status(process_status 属于 CaseEvent/Wave 层)
# → 降级:抛 422 给前端显式提示 hard_isolation=True(让前端走裁决面板)
raise ValidationError(
msg,
code='SHIPPING.RECONCILE_OWNERSHIP_ANOMALY',
details={
'hard_isolation': True,
'match': {
k: match_result.get(k)
for k in ('match_level', 'confidence', 'task_no')
},
'user_action': user_action,
'next_suggested_actions': [
'reuse_existing', 'create_revision', 'force_create',
],
'legacy_job_id': (int(legacy_job_id) if legacy_job_id is not None else None),
'replay_mode': bool(replay_mode),
},
)
final_result = ReconcileProgressResult(
outcome='ownership_anomaly_rejected',
case_no=str(case_after.case_no), match=match_result,
task_no=None, job_id=None, idempotency_key=idem_key,
operation_id=op_id, resume_outcome=None, audit_written=False, message=msg,
)
# 用 case_after 替换引用,防止后续审计写已失效对象
case = case_after
user = db.session.get(User, int(user_id))
# [STEP 5] 写审计 + 幂等持久化(CaseEvent 保证下一次同 operation_id 可回返)
_write_reconcile_audit_and_event(
case=case, user=user, operation_id=op_id, idempotency_key=idem_key,
request_snapshot=request_snapshot, result=final_result,
user_action=user_action, actor_type=audit_actor,
)
final_result.audit_written = True
# [STEP 6] commit;commit 后 order_review_confirmation.schedule... 钩子由上层 API 触发
db.session.commit()
return final_result
# ============================================================
# 辅助:供现有 retry-stp-auto-create API 做前置 blocked_manual 拦截
# ============================================================
def assert_case_not_blocked_manual(*, case_no: str, case: ShippingOrderReviewCase) -> None:
"""
Phase 2-4:retry-stp-auto-create 前置校验(Q6 职责边界)。
blocked_manual = Projection 层 automation.retryable=false + blocking_reason 非空。
若命中 → 抛 409,要求改用 reconcile-and-progress(返回 adjudicate_duplicate)。
"""
# 读取 Case 关联的最新 failed STP Job.result_json
# 说明:Job 模型没有 reference_type / reference_key,通过 business_ref 前缀匹配。
_run_no = str(getattr(getattr(case, 'run', None), 'run_no', '') or '').strip()
_doc_id = getattr(case, 'document_id', None)
_stp_prefix = None
if _run_no and _doc_id is not None:
_stp_prefix = f'stp-auto:{_run_no}:doc-{int(_doc_id)}:'
latest: Job | None = None
if _stp_prefix is not None:
latest = (
Job.query
.filter(Job.domain == 'shipping_notice',
Job.job_type == JobType.SHIPPING_STP_AUTO_CREATE.value,
Job.business_ref.like(f"{_stp_prefix}%"))
.filter(Job.status.in_(['failed', 'dead']))
.order_by(Job.created_at.desc())
.first()
)
if latest is None:
return
rj = latest.result_json if isinstance(latest.result_json, dict) else {}
retryable_flag = bool(rj.get('retryable', True))
blocking_reason_raw = rj.get('blocking_reason')
blocking_reason = (
{'code': str(blocking_reason_raw)}
if isinstance(blocking_reason_raw, str) and blocking_reason_raw
else blocking_reason_raw if isinstance(blocking_reason_raw, dict) else None
)
if should_general_retry_be_removed(retryable_flag=retryable_flag, blocking_reason=blocking_reason):
raise ConflictError(
'Case blocked on manual adjudication; use reconcile-and-progress instead of retry-stp-auto-create',
code='SHIPPING.RETRY_STP_BLOCKED_MANUAL',
details={
'error_code': rj.get('error_code'),
'blocking_reason': blocking_reason.get('code') if isinstance(blocking_reason, dict) else blocking_reason,
'next_action': rj.get('next_action'),
'case_no': case_no,
'alternative_api': 'POST /workspace/shipping-notice/order-review-cases/<case_no>/reconcile-and-progress',
'allowed_user_actions': ['reuse_existing', 'create_revision', 'force_create', 'adjudicate'],
},
)
@@ -0,0 +1,317 @@
"""
services/shipping_notice/recovery_contract.py
用途:STP / 发货通知 恢复裁决 契约层(Phase 1)。
依赖:无外部 IO(纯函数 + 枚举 + dataclass);error_explainability_contract(顶层原因码交叉校验)、process_gate_contract。
逻辑:
T1 — 错误码 → is_tech_retryable_error(白名单制,fail-closed);
T2 — build_stp_job_blocked_manual_result / build_stp_job_failed_transient_result
输出严格结构契约的 Job.result;
T3 — should_general_retry_be_removed + derive_blocking_next_actions
决定是否删除 UI 侧的 "retry" 按钮并注入阻塞裁决动作;
T4 — reconcile_queries 所用到的 ReconcileMatchResult / ReconcileMatchLevel
/ ReconcileConfidence / ReconcileMatchEvidence 类型契约。
本文件为 Worker 启动 import 链路必经模块;任何新增导入符号须同步补齐。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import Enum
from typing import Any
# ============================================================
# 版本 & 常量(客户端、Job Result、审计日志里都要带,保证契约可回滚)
# ============================================================
RECOVERY_CONTRACT_VERSION: str = "shipping-recovery-v1-phase1"
# T1:技术重试白名单前缀(优先命中 prefix;category_hint 其次)
_TECH_RETRYABLE_PREFIXES: tuple[str, ...] = (
"SHIPPING.TRANSIENT_",
"SHIPPING.WORKER_TIMEOUT_",
)
_TECH_RETRYABLE_CATEGORY_HINTS: frozenset[str] = frozenset({
"worker_timeout",
"queue_unavailable",
"temporary_network_error",
"temporary_storage_error",
"external_service_5xx",
"lease_expired",
})
# T3:业务阻断 → 推荐 UI 动作映射;未命中时 fallback 为 "open_order_review"
BLOCKING_REASON_TO_ACTION_CODES: dict[str, str] = {
"duplicate_decision_required": "adjudicate_duplicate",
"SHIPPING.NOTICE_EXACT_DUPLICATE": "adjudicate_duplicate",
"profile_schema_mismatch": "open_profile_review",
"SHIPPING.STP_NOT_ELIGIBLE": "open_order_review",
"SHIPPING.REVIEW_DRAFT_MISSING": "open_order_review",
"final_required_field_missing": "open_order_review",
"SHIPPING.REVIEW_DOCUMENT_INVALID": "open_order_review",
"SHIPPING.REVIEW_DRAFT_VERSION_CONFLICT": "refresh_and_retry",
}
# T3:阻断后需要从 available_actions 中移除的动作集合
REMOVE_ACTIONS_WHEN_BLOCKED: frozenset[str] = frozenset({
"retry_stp_auto_create",
"retry_failed_documents",
"retry_parse",
"retry",
})
# ============================================================
# T1 — 错误重试白名单分类
# ============================================================
def is_tech_retryable_error(
error_code: str | None,
*,
category_hint: str | None = None,
) -> bool:
"""
判断错误码是否属于「技术临时失败」,允许自动/手动技术重试。
【AI 触发时机】:
- Worker 领取 Job 失败后分类 retryable 标志;
- 工作台 / 对话侧投影 available_actions 时决定是否显示 retry;
- 对账链路 error_code 分类。
核心逻辑(fail-closed):
[STEP 1] error_code 为空/None → 直接 False,禁止空码回退到可重试;
[STEP 2] 前缀 _TECH_RETRYABLE_PREFIXES 命中 → True;
[STEP 3] category_hint 在 _TECH_RETRYABLE_CATEGORY_HINTS → True;
[STEP 4] 其他全部 False(业务阻断、未知错误都不得自动重试)。
Args:
error_code: 业务/AppError.code;前缀优先。
category_hint: 上游 catch 时给出的原因分类(如 "external_service_5xx")。
Returns:
True → 技术临时失败,允许 retryable=true;False → 业务阻断或未知,必须人工接管。
"""
normalized = str(error_code or "").strip()
if not normalized:
return False
for prefix in _TECH_RETRYABLE_PREFIXES:
if normalized.startswith(prefix):
return True
hint = str(category_hint or "").strip()
if hint and hint in _TECH_RETRYABLE_CATEGORY_HINTS:
return True
return False
# ============================================================
# T2 — STP Job Result 结构契约
# ============================================================
def _build_decision_trace(
*,
contract_version: str,
stage: str,
retryable: bool,
matched_rule: str | None,
) -> dict[str, Any]:
return {
"contract_version": contract_version,
"stage": stage,
"retryable": retryable,
"matched_rule": matched_rule,
}
def build_stp_job_blocked_manual_result(
*,
error_code: str,
message: str,
next_action: str | None = None,
details: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
构建「业务阻断 → 人工接管」的 STP Job.result。
【AI 触发时机】:
Handler 收到业务拒绝 ok=False / AppError 为阻断码 / 非预期 Exception 兜底且
is_tech_retryable_error 返回 False 时,统一输出这个结构(禁止各 handler 手写散 schema)。
保证字段:status=failed / retryable=false / blocking_reason=error_code /
blocking_reason_details=details / next_action=next_action(default derive)/
contract_version / decision_trace。
"""
code = str(error_code or "").strip()
action = next_action if next_action else BLOCKING_REASON_TO_ACTION_CODES.get(
code, "open_order_review",
)
return {
"status": "failed",
"retryable": False,
"blocking_reason": code,
"blocking_reason_details": dict(details) if details else {},
"next_action": action,
"error_code": code,
"message": str(message or ""),
"contract_version": RECOVERY_CONTRACT_VERSION,
"decision_trace": _build_decision_trace(
contract_version=RECOVERY_CONTRACT_VERSION,
stage="blocked_manual",
retryable=False,
matched_rule="business_blocking",
),
}
def build_stp_job_failed_transient_result(
*,
error_code: str,
message: str,
category_hint: str | None = None,
) -> dict[str, Any]:
"""
构建「技术临时失败 → 可重试」的 STP Job.result。
【AI 触发时机】:
is_tech_retryable_error 返回 True 时调用;blocking_reason/next_action 置空,
由上游 worker 根据 retryable=true 自动重试或保留 retry 按钮。
"""
code = str(error_code or "").strip()
return {
"status": "failed",
"retryable": True,
"blocking_reason": None,
"next_action": None,
"error_code": code,
"message": str(message or ""),
"category_hint": category_hint,
"contract_version": RECOVERY_CONTRACT_VERSION,
"decision_trace": _build_decision_trace(
contract_version=RECOVERY_CONTRACT_VERSION,
stage="failed_transient",
retryable=True,
matched_rule="tech_retry_whitelist",
),
}
# ============================================================
# T3 — UI 动作注入 / 删除
# ============================================================
# 内部辅助:从 str | dict | None 的 blocking_reason 输入中归一化取出 code 字符串
def _extract_blocking_reason_code(
blocking_reason: str | dict[str, Any] | None,
) -> str:
if blocking_reason is None:
return ""
if isinstance(blocking_reason, dict):
# 兼容 order_review_projection 的 dict 格式:{'code': 'xxx', ...}
code = blocking_reason.get("code") or blocking_reason.get("error_code") or blocking_reason.get("blocking_reason") or ""
return str(code or "").strip()
return str(blocking_reason or "").strip()
def should_general_retry_be_removed(
*,
retryable_flag: bool,
blocking_reason: str | dict[str, Any] | None,
) -> bool:
"""
判定是否应该从 available_actions 中移除通用的 "retry_*" 动作。
【AI 触发时机】:order_review_projection、shipping_processing_projection 汇总 available_actions 时。
规则:retryable_flag=False 且 blocking_reason 在映射表中 → True;否则保留。
兼容 blocking_reason 入参为 dict({'code': 'xxx'})的情况,见测试 T3。
"""
if bool(retryable_flag):
return False
reason = _extract_blocking_reason_code(blocking_reason)
if not reason:
return False
if reason in BLOCKING_REASON_TO_ACTION_CODES:
return True
# 只要是业务阻断(非 retryable),默认也移除 retry,避免用户点了无意义重试
return True
def derive_blocking_next_actions(
*,
blocking_reason: str | dict[str, Any] | None,
) -> list[str]:
"""
根据阻断原因输出推荐动作列表(按优先级降序,0~N 个)。
【AI 触发时机】:
Projection 层注入 available_actions 时优先把返回的动作插到最前面;
空阻断原因返回空列表(不注入任何动作)。
兼容 dict 入参,见测试 T3。
"""
reason = _extract_blocking_reason_code(blocking_reason)
if not reason:
return []
action = BLOCKING_REASON_TO_ACTION_CODES.get(reason)
if not action:
return ["open_order_review"]
return [action]
# ============================================================
# T4-extra — 复核 Draft 重新校验 Job 的幂等键契约
# ============================================================
def build_review_revalidate_job_ref(case_no: Any, draft_version: Any) -> str:
"""
构造复核 Draft 重新校验 Job 的 business_ref 幂等键(纯字符串拼接,零依赖)。
【AI 触发时机】:
- Draft 校验失败事件(draft_validated 除外)后入队用;
- Worker 消费 handler 中按同键 dedupe queued/running;
- PATCH /cases/<case_no>/revalidate API 入队幂等键。
同 case_no + 同 draft_version 保证只保留一条有效入队,避免同一版本重复校验刷 Worker。
"""
return f'review-revalidate:{str(case_no or "").strip()}:v{int(draft_version or 0)}'
# ============================================================
# T4 — 对账链路类型契约
# ============================================================
class ReconcileMatchLevel(str, Enum):
"""对账匹配级别(从高到低,优先级顺序决定采用哪条匹配结果)。"""
NONE = "none"
L3 = "L3" # 业务指纹相似
L2 = "L2" # 文档/PO 关联
L1 = "L1" # Case.confirmed_task_id / 显式绑定
class ReconcileConfidence(str, Enum):
"""匹配置信度,用于前端彩色徽标 & 人工复核筛选。"""
NONE = "none"
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CERTAIN = "certain"
@dataclass
class ReconcileMatchEvidence:
"""匹配证据链,便于人工复核追溯判定步骤。"""
case_no: str
match_level_steps: list[dict[str, Any]] = field(default_factory=list)
document_overlap: dict[str, Any] | None = None
fingerprint_similarity: float | None = None
extra: dict[str, Any] = field(default_factory=dict)
@dataclass
class ReconcileMatchResult:
"""对账查询层统一输出结构。"""
match_level: ReconcileMatchLevel
task_no: str | None
confidence: ReconcileConfidence
evidence: ReconcileMatchEvidence
+23 -5
View File
@@ -137,7 +137,7 @@ def write_inventory_export_batch_trigger(
source = {**source, **trigger_source}
business_connector = str(source.get("connector_type") or "").strip().lower()
worker_connector = {"dbs": "dsv360", "crane": "crane_footprint"}.get(business_connector, business_connector)
inventory_sources.append({
item = {
"source_code": source.get("source_code"),
"connector_type": business_connector,
"worker_connector_type": worker_connector,
@@ -151,13 +151,20 @@ def write_inventory_export_batch_trigger(
"credential_envelope": source.get("credential_envelope") or {},
# 配置测试回调据此将批次结果精确回写到各自站点运行。
"validation_run_no": source.get("validation_run_no"),
})
}
# v2 逐源身份必须由后端显式写入,Worker 不得重新生成。
for identity_key in ("task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version", "expected_warehouse_id", "lease_token"):
if source.get(identity_key) is not None:
item[identity_key] = source[identity_key]
inventory_sources.append(item)
if not inventory_sources:
return None
body = {
"action": "inventory_export_batch",
"run_no": run_no,
"schema_version": "shipping_inventory_rpa.v2",
"batch_run_no": run_no,
"run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段
"trigger_type": "scheduled",
"requested_at": datetime.utcnow().isoformat(),
"inventory_sources": inventory_sources,
@@ -201,11 +208,22 @@ def write_inventory_export_trigger_for_task(
rpa_source.setdefault('credential_envelope', {})
body = dict(payload or {})
if inventory_rpa_batch_enabled():
run_no = f"TASK-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}"
run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}")
source_item = dict(rpa_source)
source_item.update({
"task_no": task_no,
"attempt_no": body.get("attempt_no"),
"source_run_no": body.get("source_run_no"),
"candidate_set_id": body.get("candidate_set_id"),
"candidate_set_version": body.get("candidate_set_version"),
"expected_warehouse_id": body.get("expected_warehouse_id"),
"lease_token": body.get("lease_token"),
})
return write_inventory_export_batch_trigger(
run_no,
[rpa_source],
[source_item],
payload={
"schema_version": "shipping_inventory_rpa.v2",
"trigger_type": "on_demand",
"task_no": task_no,
**body,
@@ -39,6 +39,7 @@ from app.models import (
ShippingOrderTask,
)
from app.services.shipping_notice.processing_projection_invariants import (
apply_user_projection_fields,
derivation_status_for_extraction_run,
reconcile_processing_projection_facts,
)
@@ -486,6 +487,7 @@ def project_intake_work_item(
{
'work_item_type': 'order_intake',
'work_item_no': str(intake.intake_no),
'has_formal_ot': False,
'source_type': source_type,
'root_order_task_no': None,
'shipping_notice_no': None,
@@ -850,11 +852,23 @@ def _order_task_current_gate(
or 'order_task_failed'
)
if status in {'failed', 'technical_retrying'}:
from app.services.shipping_notice.recovery_contract import (
derive_blocking_next_actions as _derive_next,
is_tech_retryable_error as _is_tech,
)
# [Phase 1-4] 以 error_code/blocking_reason_code 统一分类:
# 技术白名单 → retry_failed_documents;业务阻断 → derive_next 的第一个动作。
blocking_reason_code = error_code
if _is_tech(blocking_reason_code):
next_action = 'retry_failed_documents'
else:
actions = _derive_next(blocking_reason=blocking_reason_code)
next_action = actions[0] if actions else 'open_order_review'
return {
'gate_code': 'order_extraction',
'status': 'blocked',
'next_action_code': 'retry_failed_documents',
'blocking_reason_code': error_code,
'next_action_code': next_action,
'blocking_reason_code': blocking_reason_code,
'attempt_no': 0,
}
if status in {'review_required', 'waiting_review', 'pending_review'}:
@@ -1051,13 +1065,20 @@ def _project_order_task_work_item(
if linked_case is not None:
case_no = str(getattr(linked_case, 'case_no', None) or '').strip() or None
notice_no_for_task = _notice_no_for_order_task(order_task)
has_formal_ot = bool(
order_task is not None
and getattr(order_task, 'shipping_notice_id', None) is not None
and notice_no_for_task is not None
)
payload = reconcile_processing_projection_facts(
{
'work_item_type': 'order_task',
'work_item_no': user_task_no,
'has_formal_ot': has_formal_ot,
'source_type': source_type,
'root_order_task_no': root_task_no,
'shipping_notice_no': _notice_no_for_order_task(order_task),
'shipping_notice_no': notice_no_for_task,
'run_no': run_no,
'case_no': case_no,
'conversation_id': str(run.conversation_id or '').strip() or None,
@@ -1098,6 +1119,111 @@ def _project_order_task_work_item(
# [STEP] 投影不一致:写审计后剥离内部诊断字段,避免泄漏给前端契约。
record_projection_inconsistency_audit(payload)
payload.pop('projection_inconsistency_code', None)
# [T8 用户态 Projection 7 字段] 新增 status/stage/current_gate/blocking_reason/retryable/primary_action/facts,
# 同时保存旧枚举到 legacy_status/stage/current_gate,保证旧客户端兼容。
payload = apply_user_projection_fields(payload, notice=notice, order_task=order_task)
# [Phase 3] 当 work_item 关联真实 open_case(未确认 Case 或 candidate_id 回链 Case)→
# 用共享 bundle 权威覆盖 6 个字段,保证与 Case 详情页两端绝对同源,消除 notice/OT 侧投影漂移。
# 动作集合按 review_domain_codes 分层:notice/OT 老履约动作保留,建单前裁决动作由 bundle 权威替换。
if open_case is not None:
try:
from app.services.shipping_notice.reconciliation_projector import (
REVIEW_DOMAIN_ACTION_CODES,
project_review_case_projection_bundle,
)
validation_snapshot = None
draft = getattr(open_case, 'current_draft', None)
if draft is not None and getattr(draft, 'validation_result_json', None) is not None:
validation_snapshot = dict(draft.validation_result_json or {})
post_confirm_snapshot = None
if case_no:
from app.services.shipping_notice.order_review_projection import (
_project_post_confirm_auto_progress,
)
post_confirm_snapshot = _project_post_confirm_auto_progress(open_case)
bundle = project_review_case_projection_bundle(
open_case,
validation=validation_snapshot,
post_confirm=post_confirm_snapshot,
is_admin=False,
)
# 六字段覆盖:user_status / blocking_reason / primary_action / current_gate / available_actions / retryable
if isinstance(bundle.get('user_status'), str):
payload['user_status'] = bundle['user_status']
if isinstance(bundle.get('blocking_reason'), dict):
payload['blocking_reason'] = dict(bundle['blocking_reason'])
if isinstance(bundle.get('primary_action'), dict):
payload['primary_action'] = dict(bundle['primary_action'])
if isinstance(bundle.get('current_gate'), dict):
current_gate = dict(payload.get('current_gate') or {})
current_gate.update(bundle['current_gate'])
payload['current_gate'] = current_gate
if isinstance(bundle.get('available_actions'), list):
old_actions = list(payload.get('available_actions') or [])
keep_notice_side = [a for a in old_actions if a not in REVIEW_DOMAIN_ACTION_CODES]
bundle_actions = list(bundle['available_actions'])
# 去重合并:notice 侧老动作为基,裁决动作 bundle 权威追加并去重。
merged: list[str] = []
for a in [*bundle_actions, *keep_notice_side]:
if a and a not in merged:
merged.append(a)
payload['available_actions'] = merged
retry_flag = bool((bundle.get('automation') or {}).get('retryable'))
if retry_flag or str(payload.get('user_status') or '') == 'retryable':
payload['retryable'] = True
except Exception: # noqa: BLE001
# 只读投影失败不阻断列表输出(fail-closed 兜底 invariants 结果)
pass
# 题4A:注入 inventory_preparation 结构化字段(题7A:区分 failed/exhausted_sources);
# 仅当 inventory 阶段或更早、且已挂正式 Notice 时才填充;其他阶段填 None 避免误导。
inventory_preparation = None
if notice is not None:
try:
from app.services.shipping_notice.task_retry_decision_service import (
summarize_inventory_rpa_latest_attempts,
)
snapshot_src = summarize_inventory_rpa_latest_attempts(notice, include_gate_status=True)
required_sources = list(snapshot_src.get('required_frozen_sources') or [])
prepared_sources = list(snapshot_src.get('prepared_source_codes') or [])
pending_sources = list(snapshot_src.get('pending_source_codes') or [])
failed_sources = list(snapshot_src.get('failed_source_codes') or [])
exhausted_sources = list(snapshot_src.get('exhausted_source_codes') or [])
active_attempt_count = int(snapshot_src.get('active_attempt_count') or 0)
latest_attempts = dict(snapshot_src.get('latest_attempts') or {})
# 快照载入状态补入 prepared_sources(如果快照就绪且 inventory_lines_json 已保存但 per_source 尚未标记 prepared)
if notice.inventory_lines_json and notice.inventory_snapshot_id:
for code in required_sources:
if code and code not in prepared_sources and code not in pending_sources:
prepared_sources.append(code)
inventory_preparation = {
'required_sources': required_sources,
'prepared_sources': prepared_sources,
'pending_sources': pending_sources,
'failed_sources': failed_sources,
'exhausted_sources': exhausted_sources,
'active_attempt_count': active_attempt_count,
'latest_attempts': latest_attempts,
'gate_attempt_active': bool(snapshot_src.get('gate_attempt_active')),
}
except Exception: # noqa: BLE001
inventory_preparation = None
payload['inventory_preparation'] = inventory_preparation
# 题4A & 题7A:根据 inventory_preparation 统一折叠 retryable(仅当没有 pending/running + (failed or exhausted) 时,保证可重试为 true;
# 若 active_attempt_count > 0 说明正在执行,强制 retryable=false)。原 retryable 为 false 时不要强行改 true(人工态不改)。
inv = inventory_preparation
if isinstance(inv, dict):
active = bool(inv.get('active_attempt_count')) or bool(inv.get('gate_attempt_active'))
has_pending = bool(inv.get('pending_sources'))
has_fail = bool(inv.get('failed_sources')) or bool(inv.get('exhausted_sources'))
if active or has_pending:
payload['retryable'] = False
elif has_fail and payload.get('retryable') is not False:
payload['retryable'] = True
return payload
@@ -1176,8 +1302,15 @@ def _conversation_processing_group_for_work_item(item: dict[str, Any]) -> str:
Returns:
needs_action | processing | completed 之一。
"""
user_status = str(item.get('user_status') or '').strip().lower()
status = str(item.get('status') or '').strip().lower()
stage = str(item.get('stage') or '').strip().lower()
if user_status in {'waiting_human', 'retryable', 'failed'}:
return 'needs_action'
if user_status in {'completed', 'cancelled'}:
return 'completed'
if user_status == 'running':
return 'processing'
if status in {'failed', 'blocked'} or stage == 'waiting_review' or status == 'waiting_review':
return 'needs_action'
if status == 'completed' or stage == 'completed':
@@ -1195,8 +1328,17 @@ def _conversation_processing_status_label_for_work_item(item: dict[str, Any]) ->
Returns:
稳定展示码。
"""
user_status = str(item.get('user_status') or '').strip().lower()
status = str(item.get('status') or '').strip().lower()
stage = str(item.get('stage') or '').strip().lower()
if user_status == 'waiting_human':
return 'pending_review'
if user_status == 'retryable':
return 'failed'
if user_status in {'completed', 'cancelled', 'failed'}:
return user_status
if user_status == 'running':
return 'processing'
if status == 'failed':
return 'failed'
if status == 'waiting_review' or stage == 'waiting_review':
@@ -1232,24 +1374,52 @@ def _conversation_task_row_from_work_item(
title = filename if document_count == 1 and filename else None
display_kind = 'single_document_task' if document_count == 1 else 'multi_document_task'
group = _conversation_processing_group_for_work_item(item)
available_actions = list(item.get('available_actions') or [])
primary_action = available_actions[0] if available_actions else 'view_details'
run_no = None
workflow_no = None
resolved_primary: str | None = None
order_task = (
ShippingOrderTask.query.filter_by(task_no=user_task_no).first()
if user_task_no
else None
)
run = None
if order_task is not None and order_task.extraction_run_id:
run = db.session.get(ShippingOrderProcessingRun, int(order_task.extraction_run_id))
if run is not None:
run_no = str(run.run_no or '').strip() or None
from app.services.shipping_notice.conversation_processing_projection import (
_resolve_workflow_no,
if run is None and user_task_no:
# [ROOT-3 FIX] fallback:拿代表 Run(与旧 embedded 投影同选择规则)
run_candidate = (
ShippingOrderProcessingRun.query.filter(
ShippingOrderProcessingRun.user_task_no == user_task_no,
ShippingOrderProcessingRun.superseded_by_run_id.is_(None),
)
workflow_no = _resolve_workflow_no(run)
.order_by(
ShippingOrderProcessingRun.last_activity_at.desc().nullslast(),
ShippingOrderProcessingRun.created_at.desc(),
)
.first()
)
if run_candidate is not None:
run = run_candidate
if run is not None:
run_no = str(run.run_no or '').strip() or None
from app.services.shipping_notice.conversation_processing_projection import (
_resolve_workflow_no,
)
workflow_no = _resolve_workflow_no(run)
# 会话兼容投影必须直接复用最终 work_item 的用户态字段,
# 不能再回退旧 run 级契约,否则会把 running OT 重新投影成 pending_review。
available_actions = list(item.get('available_actions') or [])
primary_action_raw = item.get('primary_action')
if isinstance(primary_action_raw, dict):
resolved_primary = str(primary_action_raw.get('code') or '').strip() or None
elif isinstance(primary_action_raw, str):
resolved_primary = str(primary_action_raw or '').strip() or None
if resolved_primary is not None:
primary_action = resolved_primary
elif available_actions:
primary_action = available_actions[0]
else:
primary_action = 'focus_task'
return {
'user_task_no': user_task_no,
'submission_ordinal': None,
@@ -1433,7 +1603,33 @@ def project_conversation_processing_items(
)
work_items: list[dict[str, Any]] = []
# [STEP 1] OT 是统一进度聚合根;禁止为构造统一投影先执行旧 Run 级会话投影。
# [LEGACY-UNIFY ROOT-2] STEP 1a:先按旧 conversation_processing_projection 的代表 Run 选择规则
# (superseded IS NULL + 右侧可见状态白名单 + last_activity_at desc)选 latest_by_task,
# 保证 unified 与旧 embedded 选到同一条代表 Run,杜绝 status_label / run_no 漂移。
from app.services.shipping_notice.conversation_processing_projection import (
_RIGHT_PANEL_RUN_STATUSES,
)
legacy_seed_runs = (
ShippingOrderProcessingRun.query.filter(
ShippingOrderProcessingRun.user_id == int(user_id),
ShippingOrderProcessingRun.conversation_id == normalized,
ShippingOrderProcessingRun.superseded_by_run_id.is_(None),
ShippingOrderProcessingRun.user_task_no.isnot(None),
ShippingOrderProcessingRun.status.in_(sorted(_RIGHT_PANEL_RUN_STATUSES)),
)
.order_by(
ShippingOrderProcessingRun.last_activity_at.desc().nullslast(),
ShippingOrderProcessingRun.created_at.desc(),
)
.all()
)
latest_by_task: dict[str, ShippingOrderProcessingRun] = {}
for seed_run in legacy_seed_runs:
seed_task_no = str(getattr(seed_run, 'user_task_no', None) or '').strip()
if seed_task_no and seed_task_no not in latest_by_task:
latest_by_task[seed_task_no] = seed_run
# STEP 1b:会话内 OT 实体列表(保留 updated_at desc 排序,前端卡片顺序仍靠 OT 更新时间)
order_tasks = (
ShippingOrderTask.query.filter(
ShippingOrderTask.user_id == int(user_id),
@@ -1464,7 +1660,7 @@ def project_conversation_processing_items(
for task in order_tasks
if not task.extraction_run_id and str(task.task_no or '').strip()
]
latest_run_by_task: dict[str, ShippingOrderProcessingRun] = {}
fallback_run_by_task: dict[str, ShippingOrderProcessingRun] = {}
if missing_task_nos:
fallback_runs = (
ShippingOrderProcessingRun.query.filter(
@@ -1480,21 +1676,120 @@ def project_conversation_processing_items(
)
for fallback_run in fallback_runs:
task_no = str(fallback_run.user_task_no or '').strip()
if task_no and task_no not in latest_run_by_task:
latest_run_by_task[task_no] = fallback_run
if task_no and task_no not in fallback_run_by_task:
fallback_run_by_task[task_no] = fallback_run
# STEP 1c:按 OT 实体顺序投影;[LEGACY-UNIFY ROOT-1] run is None 时不 continue,用 OT 自身字段构造最小 work_item
for order_task in order_tasks:
task_no = str(order_task.task_no or '').strip()
run = (
runs_by_id.get(int(order_task.extraction_run_id))
if order_task.extraction_run_id
else latest_run_by_task.get(task_no)
)
if run is None:
if not task_no:
continue
projected = _project_order_task_work_item(run, order_task=order_task)
if projected is not None:
work_items.append(projected)
# 选 Run 优先级:A) 旧投影等价代表 → B) OT 自身 extraction_run_id → C) 原 fallback
run: ShippingOrderProcessingRun | None = latest_by_task.get(task_no)
if run is None and order_task.extraction_run_id:
run = runs_by_id.get(int(order_task.extraction_run_id))
if run is None:
run = fallback_run_by_task.get(task_no)
if run is not None:
projected = _project_order_task_work_item(run, order_task=order_task)
if projected is not None:
work_items.append(projected)
continue
# [ROOT-1 FIX] 找不到任何 Run 上下文:直接用 OT 自身字段构造最小 order_task work_item,
# 保证 work_items / conversation_processing 能输出 OT 语义,不被吞回 intake-only。
user_task_no = task_no
source_type = 'extraction_run'
stage = (
str(getattr(order_task, 'stage', None) or '').strip().lower()
or 'candidate_creating'
)
if stage not in SHIPPING_PROCESSING_STAGES:
stage = 'candidate_creating'
raw_status = str(getattr(order_task, 'status', None) or '').strip().lower()
status = raw_status if raw_status in SHIPPING_PROCESSING_STATUSES else 'processing'
if status == 'completed' and stage != 'completed':
status = 'processing'
notice_min = None
stage_label_key = None
invalidated_from_stage = None
excel_ready = False
if getattr(order_task, 'shipping_notice_id', None):
nid = int(order_task.shipping_notice_id)
notice_min = db.session.get(ShippingNotice, nid)
if notice_min is not None:
from app.services.shipping_notice.order_review_workbench_projection import (
project_stage_for_task,
)
shared = project_stage_for_task(notice_min)
shared_code = str(shared.get('code') or '').strip().lower()
if shared_code in SHIPPING_PROCESSING_STAGES:
stage = shared_code
stage_label_key = str(shared.get('label_key') or '').strip() or None
from app.services.shipping_notice.task_workflow import (
read_notice_invalidated_from_stage,
)
from app.services.shipping_notice.schema_edit_policy import (
is_excel_ready_for_task,
)
invalidated_from_stage = read_notice_invalidated_from_stage(notice_min)
excel_ready = is_excel_ready_for_task(notice_min)
if (
invalidated_from_stage
and excel_ready
and stage in {'freight_uploading', 'completed'}
):
invalidated_from_stage = None
if not stage_label_key and stage == 'order_creating':
stage_label_key = 'waiting_system_start'
legacy_actions_min: list[str] = []
notice_no_min = _notice_no_for_order_task(order_task)
has_formal_ot_min = bool(
getattr(order_task, 'shipping_notice_id', None) is not None
and notice_no_min is not None
)
payload_min = reconcile_processing_projection_facts(
{
'work_item_type': 'order_task',
'work_item_no': user_task_no,
'has_formal_ot': has_formal_ot_min,
'source_type': source_type,
'root_order_task_no': user_task_no,
'shipping_notice_no': notice_no_min,
'run_no': None,
'case_no': None,
'conversation_id': normalized,
'submission_no': None,
'intake_no': None,
'status': status,
'stage': stage,
'stage_label_key': stage_label_key or (
'waiting_system_start' if stage == 'order_creating' else stage
),
'progress_version': int(
getattr(order_task, 'progress_version', None) or 1
),
'last_activity_at': _iso(
getattr(order_task, 'updated_at', None)
) or '',
'current_gate': None,
'available_actions': legacy_actions_min,
'source_summary': {
'filename': None,
'document_count': 0,
'document_id': None,
},
'child_order_tasks': [],
},
legacy_actions=legacy_actions_min,
invalidated_from_stage=invalidated_from_stage,
excel_ready=excel_ready,
)
payload_min.pop('projection_inconsistency_code', None)
payload_min = apply_user_projection_fields(
payload_min, notice=notice_min, order_task=order_task
)
work_items.append(payload_min)
linked_intake_ids = _intake_ids_linked_to_active_ot(
user_id=int(user_id),
@@ -0,0 +1,377 @@
"""
services/shipping_notice/shipping_recovery_sweeper_service.py
用途:Shipping Recovery Sweeper 服务——补偿长时间停留在 unreviewed/draft/ready
且 STP Job 缺失的 Review Case,触发 reconcile → ensure_stp → 入队 STP Job。
依赖:
- app.db(SQLAlchemy session + text() SQL 执行)
- app.models(ShippingOrderReviewCase、Job)
- app.services.shipping_notice.order_review_auto_progress_coordinator(延迟 import)
- app.services.shipping_notice.recovery_contract(错误分类契约,供后续决策引用)
- app.services.shipping_notice.queue_service(业务 Job 定义,domain/job_type 常量对齐)
逻辑:
_fetch_sweeper_case_candidates 只读 + SKIP LOCKED 语义批量捞取候选 case_id;
shipping_recovery_tick 主入口对每个 case 开 SAVEPOINT + FOR UPDATE SKIP LOCKED
+ pg_advisory_xact_lock 后调用 reconcile_single_case_for_auto_progress。
注意:order_review_auto_progress_coordinator 不在顶层 import,避免与
order_stp_auto_create_service / order_review_draft_service 形成
circular import(coord 运行时会延迟 import stp / draft)。
"""
from __future__ import annotations
import logging
from typing import Any
from flask import current_app
from sqlalchemy import String, and_, cast, exists, func, not_, select, text
from app import db
from app.models import (
Job,
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
ShippingOrderReviewDraft,
ShippingNotice,
ShippingProcessExecution,
ShippingTaskInventoryRpaAttempt,
)
# 注意:
# 1) order_review_auto_progress_coordinator 不在顶层 import,避免 circular import。
# 2) order_stp_auto_create_service 也不在顶层 import(虽然当前仅用纯函数,但未来
# stp 可能顶层再 import sweeper / coord,统一延迟更安全)。
# 两者都延迟 import 到 shipping_recovery_tick / _stp_prefix_expr 调用点。
_LOGGER = logging.getLogger(__name__)
_STP_JOB_TYPES = ('shipping_stp_auto_create',)
_STP_JOB_DOMAIN = 'shipping_notice'
_STP_ACTIVE_STATUSES = ('queued', 'running')
_STP_FAILED_STATUS = 'failed'
_STP_PREFIX_SEGMENT_SEP = ':'
_STP_PREFIX_HEAD = 'stp-auto'
_NON_RETRYABLE_BLOCKING_REASONS = (
'duplicate_decision_required',
'SHIPPING.NOTICE_EXACT_DUPLICATE',
)
def _recover_auto_progress_jobs() -> int:
"""
补偿无活动 Job 的 P0-3 Task Execution。
核心逻辑:只扫描 active Execution,submit_auto_progress 在 Task 锁 + 部分唯一索引下二次判定,
因此多个 shipping worker tick 不会为同一 Task 创建两个决策 Job。
"""
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
rows = (
ShippingNotice.query.join(
ShippingProcessExecution,
ShippingNotice.active_process_execution_id == ShippingProcessExecution.id,
)
.filter(
ShippingProcessExecution.status == 'active',
ShippingNotice.process_status.notin_(('cancelled', 'canceled', 'closed', 'rejected')),
).limit(50).all()
)
recovered = 0
for task in rows:
result = submit_auto_progress(task=task, trigger='recovery_sweeper', commit=False)
if result.get('status') == 'queued' and not result.get('reused'):
recovered += 1
return recovered
def _json_text_expr(json_column, key: str):
"""
从 PostgreSQL JSON/JSONB 列中提取文本值。
这里统一用 ``->>`` 而不是 ``jsonb_extract_path_text``,因为本项目这些字段当前
在数据库里是 ``json`` 列而非 ``jsonb``。``->>`` 对 json/jsonb 都可工作,
可以避免 worker 启动阶段因函数签名不匹配直接报错退出。
"""
return json_column.op('->>')(key)
def _stp_business_ref_like_expr(*, run_no_expr, document_id_expr):
"""
构造 STP Job business_ref LIKE 前缀表达式(ORM 层拼,彻底避免 text() 中
`%doc%` 被 SQLAlchemy 误识别为绑定参数 `:doc` 的坑)。
LIKE 语义:``stp-auto:<run_no>:doc-<document_id>:<任意后缀>%``
Args:
run_no_expr: SQL 表达式或列(ShippingOrderProcessingRun.run_no)。
document_id_expr: SQL 表达式或列(ShippingOrderReviewCase.document_id)。
Returns:
LIKE 字符串表达式,可直接放到 ``Job.business_ref.like(...)`` 里。
"""
# CONCAT 参数顺序:stp-auto: + run_no + :doc- + document_id + : + %
# 每个片段独立传入,PostgreSQL 会自动类型统一,不引入 text() 解析歧义。
return func.CONCAT(
_STP_PREFIX_HEAD,
_STP_PREFIX_SEGMENT_SEP,
cast(run_no_expr, String),
_STP_PREFIX_SEGMENT_SEP,
'doc-',
cast(document_id_expr, String),
_STP_PREFIX_SEGMENT_SEP,
'%',
)
def _fetch_sweeper_case_candidates(*, max_age_hours: int = 72) -> list[int]:
"""
查询符合补偿条件的 ReviewCase 主键列表(只读 + SKIP LOCKED 语义)。
候选条件:
1. rc.status IN ('unreviewed','draft','ready')
2. rc.confirmed_task_id IS NULL(尚未绑定建单结果)
3. rc.updated_at >= NOW() - N 小时(最近活跃,避免扫历史堆)
4. Draft.validation_result_json.status = 'ready'(草稿校验已通过)
5. Draft.validation_result_json.can_auto_create = true(具备自动建单资格)
6. 不存在同 (run_no, document_id) 的 queued/running STP Job(避免重复入队)
7. 不存在同 (run_no, document_id) 的 retryable=false 业务阻断失败 Job
(duplicate/SHIPPING.NOTICE_EXACT_DUPLICATE)→ 尊重人工对账边界。
单批上限 LIMIT 50,按 updated_at + id 倒序优先处理最近更新。
【实现决策】:
- 全部用 SQLAlchemy ORM 表达式重写,彻底消除 text() 里 `stp-auto:%:doc-` 被
SQLAlchemy 误识别为绑定参数 `:doc` 的坑。
- run_no 来自真实 JOIN shipping_order_processing_runs,不再在 text() 里 LIKE CONCAT
走错误前缀;与 build_stp_idempotency_key(run_no, document_id, ...) 严格一致。
Args:
max_age_hours: 只扫描最近 N 小时内更新过的 Case;默认 72。
Returns:
符合条件的 case_id 列表(按 rc.updated_at DESC, rc.id DESC)。
"""
rc = ShippingOrderReviewCase.__table__.alias('rc')
d = ShippingOrderReviewDraft.__table__.alias('d')
r = ShippingOrderProcessingRun.__table__.alias('r')
j = Job.__table__.alias('j')
j2 = Job.__table__.alias('j2')
stp_prefix_like = _stp_business_ref_like_expr(
run_no_expr=r.c.run_no,
document_id_expr=rc.c.document_id,
)
# j:queued/running 匹配 → 要求不存在
active_stp_exists = exists().where(and_(
j.c.domain == _STP_JOB_DOMAIN,
j.c.job_type.in_(_STP_JOB_TYPES),
j.c.status.in_(_STP_ACTIVE_STATUSES),
j.c.business_ref.like(stp_prefix_like),
))
# j2:retryable=false 的业务阻断失败 → 要求不存在
blocking_code_expr = _json_text_expr(j2.c.result_json, 'blocking_reason')
retryable_expr = _json_text_expr(j2.c.result_json, 'retryable')
blocking_stp_exists = exists().where(and_(
j2.c.domain == _STP_JOB_DOMAIN,
j2.c.job_type.in_(_STP_JOB_TYPES),
j2.c.status == _STP_FAILED_STATUS,
retryable_expr == 'false',
blocking_code_expr.in_(_NON_RETRYABLE_BLOCKING_REASONS),
j2.c.business_ref.like(stp_prefix_like),
))
status_expr = _json_text_expr(d.c.validation_result_json, 'status')
can_auto_create_expr = _json_text_expr(d.c.validation_result_json, 'can_auto_create')
stmt = (
select(rc.c.id)
.select_from(rc.join(d, d.c.id == rc.c.current_draft_id).join(r, r.c.id == rc.c.run_id))
.where(and_(
rc.c.status.in_(('unreviewed', 'draft', 'ready')),
rc.c.confirmed_task_id.is_(None),
# [注意] 直接 text(f"INTERVAL '{N} HOURS'") 而非 TextClause * int,
# 也不用 cast(str, db.Interval)。max_age_hours 来自 int(config or 72),
# 必为纯数字字面量,不存在 SQL 注入风险;此写法与迁移脚本的
# "INTERVAL '72 hours'" 字面量完全等价,最稳妥。
rc.c.updated_at >= func.NOW() - text(
f"INTERVAL '{int(max_age_hours)} HOURS'"
),
status_expr == 'ready',
cast(can_auto_create_expr, String).cast(db.Boolean).is_(True),
not_(active_stp_exists),
not_(blocking_stp_exists),
))
.order_by(rc.c.updated_at.desc(), rc.c.id.desc())
.limit(50)
)
rows = db.session.execute(stmt).fetchall()
return [int(row[0]) for row in rows]
def shipping_recovery_tick() -> int:
"""
主入口:执行一轮 Sweeper 补偿,返回本轮成功处理(非跳过)的 Case 数量。
执行步骤:
[STEP 1] 从 Config 读取 SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS,
调用 _fetch_sweeper_case_candidates 捞取候选 case_id。
[STEP 2] 逐个 case_id 循环:
* 开 SAVEPOINT(session.begin_nested())
* SELECT ... FOR UPDATE SKIP LOCKED 按 id 取 Case(被其他 Sweeper/Worker 持有则跳过)
* pg_advisory_xact_lock(hashtext('shipping_stp_sweeper'), :case_id) 事务级咨询锁
* 调 reconcile_single_case_for_auto_progress(case=case, trigger='recovery_sweeper',
refresh_validation=True)
* commit 当前 savepoint;异常则 rollback savepoint
[STEP 3] 返回成功执行(非 FOR UPDATE SKIP LOCKED 跳过)的 Case 计数。
注意:Sweeper 不直接执行 confirm_review_case / 建单,只负责触发
reconcile → ensure_stp → 入队 STP Job,与 Q3/Q11 职责边界一致。
Returns:
本轮成功调用 reconcile(即未被 SKIP LOCKED/其它互斥跳过)的 Case 数量。
"""
max_age_hours = int(getattr(
current_app.config,
'SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS',
72,
) or 72)
# [STEP 0] 先收敛逐源库存 RPA 的陈旧 queued/running Attempt。
# shipping-worker 不消费 Windows Trigger 文件;若不在 recovery 周期调用该
# 扫描,Worker 离线或共享目录失效会让 Attempt 永久停在 queued,前端也会
# 继续显示“可重试”并造成重复点击。扫描只更新 Attempt 事实,后续投影会
# 根据最新 Attempt/Gate 状态刷新按钮与阻断原因。
inventory_timeout_seconds = max(int(getattr(
current_app.config,
'SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS',
900,
) or 900), 1)
inventory_scan_count = _scan_stale_inventory_attempts(
timeout_seconds=inventory_timeout_seconds,
)
auto_progress_recovered = _recover_auto_progress_jobs()
# [延迟 import] 放在 tick 主入口首条语句,避免 sweeper 顶层 import coord 时与
# order_stp_auto_create_service / order_review_draft_service 互导回环。
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress,
)
case_ids = _fetch_sweeper_case_candidates(max_age_hours=max_age_hours)
if not case_ids:
_LOGGER.debug(
'shipping_recovery_tick: no candidate cases inventory_scanned=%s',
inventory_scan_count,
)
try:
db.session.commit()
except Exception: # noqa: BLE001
db.session.rollback()
_LOGGER.warning('shipping_recovery_tick: inventory scan commit failed', exc_info=True)
return inventory_scan_count + auto_progress_recovered
processed_count = 0
for case_id in case_ids:
nested = db.session.begin_nested()
try:
locked_case = (
ShippingOrderReviewCase.query
.filter_by(id=int(case_id))
.with_for_update(skip_locked=True)
.first()
)
if locked_case is None:
_LOGGER.debug(
'shipping_recovery_tick: case_id=%s skipped (FOR UPDATE SKIP LOCKED)',
case_id,
)
nested.rollback()
continue
db.session.execute(text(
"SELECT pg_advisory_xact_lock(hashtext('shipping_stp_sweeper'), :case_id)"
), {"case_id": int(case_id)})
reconcile_single_case_for_auto_progress(
case=locked_case,
trigger='recovery_sweeper',
refresh_validation=True,
)
nested.commit()
processed_count += 1
except Exception as exc: # noqa: BLE001 — 单 Case 异常不阻断本轮
try:
nested.rollback()
except Exception: # noqa: BLE001
pass
_LOGGER.warning(
'shipping_recovery_tick: case_id=%s reconcile failed err=%s',
case_id,
str(exc)[:300],
exc_info=True,
)
try:
db.session.commit()
except Exception: # noqa: BLE001
db.session.rollback()
_LOGGER.warning('shipping_recovery_tick: final session commit failed', exc_info=True)
_LOGGER.info(
'shipping_recovery_tick: candidates=%s processed=%s inventory_scanned=%s max_age_hours=%s',
len(case_ids),
processed_count,
inventory_scan_count,
max_age_hours,
)
return processed_count + inventory_scan_count + auto_progress_recovered
def _scan_stale_inventory_attempts(*, timeout_seconds: int) -> int:
"""扫描所有活动逐源库存 Attempt,并收敛超时记录。
【AI 触发时机】:shipping worker recovery tick 每轮调用;不负责创建新
Attempt 或执行 RPA,只负责把无人领取/无回调的事实从 queued/running 收敛
为 failed,避免活动锁长期阻止人工重试。
Returns:
本轮收敛的 Attempt 数量。
"""
task_nos = [
str(row[0])
for row in db.session.query(ShippingTaskInventoryRpaAttempt.task_no)
.filter(ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')))
.distinct()
.all()
]
if not task_nos:
return 0
from app.services.shipping_notice.per_source_rpa_service import per_source_timeout_scan
total = 0
for task in (
ShippingNotice.query
.filter(ShippingNotice.task_no.in_(task_nos))
.all()
):
try:
result = per_source_timeout_scan(
task,
timeout_seconds=timeout_seconds,
session=db.session,
)
total += int(result.get('timed_out_count') or 0)
except Exception: # noqa: BLE001 — 单任务扫描失败不阻断其它恢复项
_LOGGER.warning(
'shipping_recovery_tick: inventory attempt scan failed task_no=%s',
task.task_no,
exc_info=True,
)
if total:
db.session.flush()
return total
@@ -13,6 +13,12 @@ from __future__ import annotations
from typing import Any
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_candidate_freeze_service import (
freeze_candidates_for_task,
)
from app.services.shipping_notice.inventory_candidate_projection import (
get_active_candidate_sources,
)
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
@@ -93,14 +99,6 @@ def freeze_stp_inventory_candidates_on_task(
],
}]
payload = dict(task.step_payload_json or {})
payload['line_inventory_candidates'] = {
'source_codes': valid_codes,
'lines': evidence[0]['line_projections'],
'frozen_at': 'build',
}
task.step_payload_json = payload
if len(valid_codes) == 1 and sources:
adjudication = InventorySourceAdjudication(
status='resolved',
@@ -142,6 +140,23 @@ def freeze_stp_inventory_candidates_on_task(
reason='no_valid_candidates_at_build',
)
freeze_result = None
if valid_codes:
freeze_result = freeze_candidates_for_task(
task,
adjudication=adjudication,
line_projections=line_projections,
)
payload = dict(task.step_payload_json or {})
payload['line_inventory_candidates'] = {
'source_codes': valid_codes,
'lines': evidence[0]['line_projections'],
'frozen_at': 'build',
'candidate_set_id': getattr(freeze_result, 'candidate_set_id', None),
}
task.step_payload_json = payload
apply_inventory_source_adjudication(task, adjudication)
# 多候选时 apply 会清空 task.inventory_source_code;保留 line_inventory_candidates。
if adjudication.status == 'candidates_frozen':
@@ -150,6 +165,7 @@ def freeze_stp_inventory_candidates_on_task(
'source_codes': valid_codes,
'lines': evidence[0]['line_projections'],
'frozen_at': 'build',
'candidate_set_id': getattr(freeze_result, 'candidate_set_id', None),
}
resolution = dict(payload.get('inventory_source_resolution') or {})
resolution['status'] = 'candidates_frozen'
@@ -188,6 +204,11 @@ def freeze_stp_inventory_candidates_on_task(
},
source='system',
)
# 候选版本冻结完成是正式 AutoProgress 触发源。仅提交当前 Gate,绝不在
# 建单事务里直接推进库存/RPA/匹配。
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
submit_auto_progress(task=task, trigger='candidate_set_frozen', commit=False)
return adjudication
@@ -201,12 +222,10 @@ def task_frozen_inventory_source_codes(task: ShippingNotice) -> list[str]:
Returns:
大写 source_code 列表。
"""
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
frozen = payload.get('line_inventory_candidates') if isinstance(payload.get('line_inventory_candidates'), dict) else {}
codes = [
str(code or '').strip().upper()
for code in (frozen.get('source_codes') or [])
if str(code or '').strip()
str(source.source_code or '').strip().upper()
for source in get_active_candidate_sources(task)
if str(source.source_code or '').strip()
]
if codes:
return list(dict.fromkeys(codes))
@@ -14,7 +14,12 @@ from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
from app import db
from app.models import ShippingOrderSnapshot, ShippingNotice
from app.services.shipping_notice.inventory_candidate_projection import (
get_active_candidate_lines,
get_active_candidate_set,
)
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
@@ -107,7 +112,9 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
"""
为任务准备全部冻结候选源的有效库存行(打上 __source_code 标签)。
核心逻辑:只查询冻结候选;任一候选无 ready 快照则记录 missing;全部缺失则不可匹配。
核心逻辑:required = 行级 InventoryCandidateLine 引用到的源;任务级未被任何行引用的源 =
optional(不阻塞 missing 统计)。任一 required 源无 ready 快照则记录 missing;
全部 required 缺失则不可匹配。
Args:
task: 已冻结候选的发货任务。
@@ -118,21 +125,46 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot
codes = task_frozen_inventory_source_codes(task)
if not codes:
single = str(task.inventory_source_code or '').strip().upper()
codes = [single] if single else []
current_set = get_active_candidate_set(task)
if current_set is None:
return {
'status': 'blocked',
'error_code': 'inventory_candidates_missing',
'candidate_set_id': None,
'required_source_codes': [],
'optional_source_codes': [],
'lines': [],
'loaded_source_codes': [],
'missing_source_codes': [],
'evidence': [],
}
candidate_lines = get_active_candidate_lines(task)
task_level_codes = list(task_frozen_inventory_source_codes(task))
required_codes: list[str] = []
for line in candidate_lines:
for raw in list(getattr(line, 'source_codes_json', None) or []):
code = str(raw or '').strip().upper()
if code and code not in required_codes:
required_codes.append(code)
optional_codes = [c for c in task_level_codes if c not in required_codes]
merged: list[dict[str, Any]] = []
missing: list[str] = []
loaded: list[str] = []
evidence: list[dict[str, Any]] = []
for code in codes:
for code in required_codes + optional_codes:
in_required = code in required_codes
source = get_database_inventory_source(code)
if source is None:
missing.append(code)
evidence.append({'source_code': code, 'status': 'source_disabled'})
if in_required:
missing.append(code)
evidence.append({
'source_code': code,
'status': 'source_disabled',
'required': in_required,
})
continue
warehouse_id = (
str(source.get('fixed_warehouse_id') or '').strip().upper() or None
@@ -141,8 +173,13 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
)
snapshot = find_latest_ready_snapshot(code, warehouse_id)
if snapshot is None:
missing.append(code)
evidence.append({'source_code': code, 'status': 'snapshot_missing'})
if in_required:
missing.append(code)
evidence.append({
'source_code': code,
'status': 'snapshot_missing',
'required': in_required,
})
continue
lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)]
if not lines:
@@ -151,11 +188,13 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
except (OSError, ValueError):
lines = []
if not lines:
missing.append(code)
if in_required:
missing.append(code)
evidence.append({
'source_code': code,
'status': 'snapshot_empty',
'inventory_file_no': snapshot.inventory_file_no,
'required': in_required,
})
continue
for row in lines:
@@ -167,43 +206,76 @@ def prepare_candidate_inventory_lines(task: ShippingNotice) -> dict[str, Any]:
evidence.append({
'source_code': code,
'status': 'loaded',
'candidate_set_id': int(current_set.id),
'inventory_file_no': snapshot.inventory_file_no,
'line_count': len(lines),
'required': in_required,
})
payload = dict(task.step_payload_json or {})
payload['candidate_inventory_prep'] = {
'candidate_set_id': int(current_set.id),
'candidate_set_version': int(current_set.set_version),
'loaded_source_codes': loaded,
'missing_source_codes': missing,
'optional_source_codes': optional_codes,
'required_source_codes': required_codes,
'evidence': evidence,
}
task.step_payload_json = payload
if not merged:
if not merged and required_codes:
return {
'status': 'missing_files',
'candidate_set_id': int(current_set.id),
'lines': [],
'missing_source_codes': missing,
'loaded_source_codes': loaded,
'evidence': evidence,
'required_source_codes': required_codes,
}
if missing:
return {
'status': 'partial_missing',
'candidate_set_id': int(current_set.id),
'lines': merged,
'missing_source_codes': missing,
'loaded_source_codes': loaded,
'evidence': evidence,
'required_source_codes': required_codes,
}
return {
'status': 'ready',
'candidate_set_id': int(current_set.id),
'lines': merged,
'missing_source_codes': [],
'loaded_source_codes': loaded,
'evidence': evidence,
'required_source_codes': required_codes,
}
def attach_candidate_scope_to_order_lines(
task: ShippingNotice,
order_lines: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""为订单行附加当前 active CandidateLine 的 allowed_source_codes 快照。"""
candidate_lines = {
int(row.line_no): row
for row in get_active_candidate_lines(task)
}
scoped_lines: list[dict[str, Any]] = []
for index, line in enumerate(order_lines):
candidate_line = candidate_lines.get(index + 1)
scoped_lines.append({
**line,
'candidate_line_id': int(candidate_line.id) if candidate_line is not None else None,
'candidate_scope_present': candidate_line is not None,
'allowed_source_codes': list(getattr(candidate_line, 'source_codes_json', None) or []),
})
return scoped_lines
def match_order_lines_across_candidates(
*,
order_lines: list[dict[str, Any]],
@@ -255,14 +327,35 @@ def match_order_lines_across_candidates(
header_reservation_id=header_reservation_id,
)
required = _qty(line.get('quantity') if line.get('quantity') is not None else line.get('__required_qty', line.get('qty')))
has_candidate_scope = (
'allowed_source_codes' in line
or 'candidate_inventory_source_codes' in line
or 'candidate_line_id' in line
or 'candidate_scope_present' in line
)
allowed_source_codes = [
str(code or '').strip().upper()
for code in (line.get('allowed_source_codes') or line.get('candidate_inventory_source_codes') or [])
if str(code or '').strip()
]
# [STEP] 订单带单位时只命中同单位库存;双方皆空则退化为料号+预约单。
source_hits = [
all_source_hits = [
buckets[key]
for key in buckets
if key[0] == (effective or '')
and key[1] == part
and key[2] == unit
] if effective and part else []
# 正式匹配必须存在结构化 CandidateLine,并严格限制在该行允许源内。
# 缺少行级范围本身就是候选事实缺失,不能退化为任务级并集匹配。
source_hits = [
item for item in all_source_hits
if (
item['source_code'] in allowed_source_codes
if has_candidate_scope
else True
)
]
if not effective or not part:
disposition = 'not_found'
@@ -279,6 +372,24 @@ def match_order_lines_across_candidates(
'resolved_inventory_source_code': None,
}
has_block = True
elif has_candidate_scope and all_source_hits and not source_hits:
disposition = 'invalid'
result = {
'line_index': index,
'part_number': part,
'reservation_id': effective,
'unit': unit or None,
'required_qty': float(required),
'available_qty': float(sum(item['available_qty'] for item in all_source_hits)),
'shortage_qty': 0.0,
'line_status': 'invalid',
'disposition': disposition,
'resolved_inventory_source_code': None,
'candidate_hit_source_codes': [item['source_code'] for item in all_source_hits],
'out_of_candidate_scope': True,
'allowed_source_codes_snapshot': list(allowed_source_codes),
}
has_block = True
elif len(source_hits) > 1:
disposition = 'multi_file_conflict'
result = {
@@ -362,11 +473,13 @@ def match_order_lines_across_candidates(
'unit': unit or None,
'resolved_inventory_source_code': result.get('resolved_inventory_source_code'),
'candidate_hit_source_codes': result.get('candidate_hit_source_codes'),
'allowed_source_codes_snapshot': list(allowed_source_codes),
'out_of_candidate_scope': bool(result.get('out_of_candidate_scope')),
'inventory_file_no': result.get('inventory_file_no'),
'inventory_row_ref': result.get('inventory_row_ref'),
})
if float(result.get('shortage_qty') or 0) > 0 or result.get('disposition') in {
'not_found', 'multi_file_conflict', 'shortage',
'not_found', 'multi_file_conflict', 'shortage', 'invalid',
}:
shortages.append(result)
@@ -87,7 +87,9 @@ def retry_task_with_decision(
raise NotFoundError('Not found')
decision_version = int(getattr(task, 'order_data_version', None) or 1)
decided = _decide(task, scope=scope_norm, line_key=line)
# 题2B:先检查最新逐源 Attempt 活跃状态(不再依赖 pending_human_reason 滞后字段),避免误判
latest_active = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
decided = _decide(task, scope=scope_norm, line_key=line, latest_active=latest_active)
action = str(decided.get('action') or ACTION_NOOP)
idempotency_key = _build_idempotency_key(
task=task,
@@ -96,29 +98,35 @@ def retry_task_with_decision(
line_key=line,
)
# [STEP] 幂等:同键活跃运行中直接回放。
if _is_inventory_rpa_active(task) and action in {ACTION_FETCH_INVENTORY, ACTION_REMATCH, ACTION_AUTO_PROGRESS}:
result = _result_payload(
task=task,
action=ACTION_NOOP,
status=STATUS_RUNNING,
retryable=False,
reason_code='already_running',
decision_version=decision_version,
idempotency_key=idempotency_key,
idempotent_replay=True,
message='已有库存处理在运行',
# [STEP] 幂等:逐源有 queued/running 且本次动作是 fetch/rematch/auto_progress → 直接回放 already_running。
# 按实际冻结源过滤(仅判断属于 required_frozen_sources 的 pending Attempt)。
need_inv_rpa = action in {ACTION_FETCH_INVENTORY, ACTION_REMATCH, ACTION_AUTO_PROGRESS}
if need_inv_rpa:
pending_required = bool(
set(latest_active['pending_source_codes']) & set(latest_active['required_frozen_sources'] or [])
)
_audit_decision(
task=task,
user_id=int(user_id),
scope=scope_norm,
line_key=line,
trigger=trigger,
reason=reason,
result=result,
)
return result
if pending_required or bool(latest_active['gate_attempt_active']):
result = _result_payload(
task=task,
action=ACTION_NOOP,
status=STATUS_RUNNING,
retryable=False,
reason_code='already_running',
decision_version=decision_version,
idempotency_key=idempotency_key,
idempotent_replay=True,
message='已有库存处理在运行',
)
_audit_decision(
task=task,
user_id=int(user_id),
scope=scope_norm,
line_key=line,
trigger=trigger,
reason=reason,
result=result,
)
return result
executed = _execute(
task=task,
@@ -128,6 +136,7 @@ def retry_task_with_decision(
decision_version=decision_version,
idempotency_key=idempotency_key,
line_key=line,
trigger=trigger,
)
_audit_decision(
task=task,
@@ -167,12 +176,22 @@ def _decide(
*,
scope: Scope,
line_key: str | None,
latest_active: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""按冻结优先级计算 RetryDecision。"""
"""按冻结优先级计算 RetryDecision。
【retryable 语义】:表示当前阻塞可通过触发 retry 操作来尝试推进。
- true:resolve_source / fetch_inventory / rematch 等系统可恢复动作
- false:running/queued(已在执行)、needs_human(需人工决策)、completed/cancelled(终态)
"""
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
process_status = str(getattr(task, 'process_status', None) or '').strip().lower()
pending = str(getattr(task, 'pending_human_reason', None) or '').strip().lower()
# 题2B:统一直接用入参 latest_active(调用方已查逐源 Attempt);无入参时回落旧实现
active = latest_active if isinstance(latest_active, dict) else (
summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
)
if process_status in {'completed', 'fulfilled', 'closed', 'cancelled'}:
return {
@@ -181,7 +200,19 @@ def _decide(
'retryable': False,
'reason_code': 'already_completed',
}
if pending in {PH_RPA_PENDING, PH_UPLOAD_PENDING} or _is_inventory_rpa_active(task):
# 库存 RPA 是否运行以逐源 Attempt 为准;pending_human_reason 可能在失败后残留。
if pending == PH_UPLOAD_PENDING:
return {
'action': ACTION_NOOP,
'status': STATUS_RUNNING,
'retryable': False,
'reason_code': 'already_running',
}
# task 整单 running(仅 scope=task 模式 & 非 line 单独 rematch 场景可通过(见题3B:line 单独决策里处理 running 不阻塞)
if scope != 'line' and (
active.get('active_attempt_count', 0) > 0
or bool(active.get('gate_attempt_active'))
):
return {
'action': ACTION_NOOP,
'status': STATUS_RUNNING,
@@ -197,9 +228,7 @@ def _decide(
}
if scope == 'line' and line_key:
return _decide_for_line(task, line_key=line_key)
# [STEP] 库存源不稳定:先解析源,不得直接写 RPA。
return _decide_for_line(task, line_key=line_key, latest_active=active)
if not is_inventory_source_stable(task):
status = str(getattr(task, 'inventory_source_status', None) or '').strip().lower()
if status in {'ambiguous', 'candidates_frozen', 'conflicted', 'unresolved', ''}:
@@ -217,20 +246,22 @@ def _decide(
'retryable': False,
'reason_code': 'inventory_source_candidates_need_human',
}
# resolve_source:单一候选或歧义已人工消除 → 可通过重试自动推进
return {
'action': ACTION_RESOLVE_SOURCE,
'status': STATUS_RUNNING,
'retryable': False,
'retryable': True,
'reason_code': 'inventory_source_unstable',
}
has_lines = bool(getattr(task, 'inventory_lines_json', None))
snapshot_id = getattr(task, 'inventory_snapshot_id', None)
if not has_lines and not snapshot_id:
# fetch_inventory:无有效快照 → 可重试复用文件或触发 RPA
return {
'action': ACTION_FETCH_INVENTORY,
'status': STATUS_RUNNING,
'retryable': False,
'retryable': True,
'reason_code': 'inventory_snapshot_missing',
}
@@ -244,10 +275,11 @@ def _decide(
'reason_code': match_hint.get('reason_code') or 'inventory_shortage',
}
if match_hint.get('needs_rematch'):
# rematch:有有效快照但匹配未完成或执行失败 → 可重试匹配
return {
'action': ACTION_REMATCH,
'status': STATUS_RUNNING,
'retryable': False,
'retryable': True,
'reason_code': 'inventory_match_incomplete',
}
@@ -260,19 +292,35 @@ def _decide(
}
def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]:
"""行级决策:只处理该行库存事实。"""
def _decide_for_line(
task: ShippingNotice,
*,
line_key: str,
latest_active: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
行级决策(题3B):仅该行需要 fetch_inventory(缺快照)时才按整单 RPA running 互斥;
若已有 inventory_snapshot_id 存在且该行未完成,直接放行 ACTION_REMATCH,
不因为其他无关源的 queued/running 阻塞(避免"行A RPA 跑时,行B 明明有快照也不能重匹配"的误判)。
题10A:行 → 依赖库存源映射优先级:
build_eligibility.line_projections[i].candidate_inventory_source_codes 优先,
为空时回退到任务级冻结源 required_frozen_sources。
"""
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
from app.services.shipping_notice.line_inventory_match_projection import (
project_line_inventory_view,
project_line_retryable,
)
active = latest_active if isinstance(latest_active, dict) else (
summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)
)
if not is_inventory_source_stable(task):
return {
'action': ACTION_RESOLVE_SOURCE,
'status': STATUS_RUNNING,
'retryable': False,
'retryable': True,
'reason_code': 'inventory_source_unstable',
}
@@ -293,6 +341,15 @@ def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]:
'matching_rule_version': getattr(row, 'matching_rule_version', None) if row else None,
'detail_json': dict(getattr(row, 'detail_json', None) or {}) if row else {},
}
# 题10A:先尝试从 build_eligibility 读行候选源(优先),缺省时用任务冻结源作为 line_dependent_codes。
line_dependent_codes = _line_dependent_inventory_source_codes(task, line_key)
if not line_dependent_codes:
line_dependent_codes = list(active.get('required_frozen_sources') or [])
# 行级 fetch running 判断:仅按 line_dependent_codes & pending_source_codes 交集非空时才算 already_running,
# 或 Gate Attempt 全局在 running。
inv_running_for_line = bool(set(line_dependent_codes) & set(active.get('pending_source_codes') or []))
line_running_flag = inv_running_for_line or bool(active.get('gate_attempt_active'))
view = project_line_inventory_view(
has_formal_ot=True,
fact=fact,
@@ -300,7 +357,7 @@ def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]:
stored_line_status=None,
decision_source=None,
can_fulfill_complete_line=False,
inventory_rpa_running=_is_inventory_rpa_active(task),
inventory_rpa_running=line_running_flag,
)
user_status = str(view.get('user_line_status') or '')
if user_status in {'shortage', 'source_conflict'}:
@@ -313,7 +370,7 @@ def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]:
if not project_line_retryable(
inventory_allowed_actions=list(view.get('inventory_allowed_actions') or []),
user_line_status=user_status,
inventory_rpa_running=_is_inventory_rpa_active(task),
inventory_rpa_running=line_running_flag,
):
return {
'action': ACTION_NOOP,
@@ -323,22 +380,69 @@ def _decide_for_line(task: ShippingNotice, *, line_key: str) -> dict[str, Any]:
}
inv_actions = set(view.get('inventory_allowed_actions') or [])
if 'retry_inventory_matching' in inv_actions and view.get('inventory_snapshot_id'):
# 题3B:快照已存在,直接放行 REMATCH,不被其他行/源的 RPA running 阻塞
return {
'action': ACTION_REMATCH,
'status': STATUS_RUNNING,
'retryable': False,
'retryable': True,
'reason_code': 'inventory_match_incomplete',
'line_key': line_key,
}
# 缺快照,需要 fetch_inventory:如果行依赖的源正好在 running,就阻塞 already_running
if inv_running_for_line or bool(active.get('gate_attempt_active')):
return {
'action': ACTION_NOOP,
'status': STATUS_RUNNING,
'retryable': False,
'reason_code': 'already_running',
'line_key': line_key,
}
return {
'action': ACTION_FETCH_INVENTORY,
'status': STATUS_RUNNING,
'retryable': False,
'retryable': True,
'reason_code': 'inventory_snapshot_missing',
'line_key': line_key,
}
def _line_dependent_inventory_source_codes(task: ShippingNotice, line_key: str) -> list[str]:
"""题10A:行依赖库存源映射(build_eligibility.line_projections[i].candidate_inventory_source_codes 优先。"""
try:
from app.services.shipping_notice.order_build_eligibility_service import (
assess_order_build_eligibility as build_fn,
)
eligibility = build_fn(task, mode='case_review')
except Exception: # noqa: BLE001
eligibility = None
out: list[str] = []
# 常见结构:{ line_projections: [ { line_key, candidate_inventory_source_codes: [] } ]
if isinstance(eligibility, dict):
projections = eligibility.get('line_projections') or eligibility.get('build_eligibility.line_projections') or []
elif eligibility and hasattr(eligibility, '__iter__'):
projections = getattr(eligibility, 'line_projections') or []
else:
projections = []
key = str(line_key or '').strip()
for p in (projections or []):
p_line = str(
p.get('line_key') if isinstance(p, dict) else getattr(p, 'line_key', None)
or ''
)
if p_line != key:
continue
codes = (
p.get('candidate_inventory_source_codes') if isinstance(p, dict)
else getattr(p, 'candidate_inventory_source_codes', None)
)
for code in (codes or []):
c = str(code or '').strip().upper()
if c and c not in out:
out.append(c)
return out
def _execute(
*,
task: ShippingNotice,
@@ -348,6 +452,7 @@ def _execute(
decision_version: int,
idempotency_key: str,
line_key: str | None,
trigger: str = 'user_retry',
) -> dict[str, Any]:
"""执行决策动作并映射统一响应。"""
from app.services.shipping_notice.inventory_source_gate import (
@@ -405,29 +510,36 @@ def _execute(
action = ACTION_FETCH_INVENTORY
if action == ACTION_FETCH_INVENTORY:
# 先尝试复用快照;仍无则显式 retry_rpa。
reused = ensure_inventory({
'task_id': task.task_no,
'mode': 'auto',
'operator_id': int(user_id),
'_trusted_user_id': int(user_id),
'event_source': 'workspace_api',
})
if str((reused or {}).get('status') or '') in {'ok', 'completed'}:
if continue_auto_progress:
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
return _map_tool_result(
reused,
action=ACTION_FETCH_INVENTORY,
base_kwargs=base_kwargs,
message='已复用库存快照',
)
# 题1C:按调用来源分流。
# user_retry / user_line_retry:直接 mode='retry_rpa',显式重试无论 auto 是否已 exhausted 都开新 Attempt。
# conversation_retry / system_auto_progress 等:先 mode='auto' 复用快照,失败再 mode='retry_rpa' 兜底。
trigger_norm = str(trigger or '').strip().lower()
user_explicit = trigger_norm in {'user_retry', 'user_line_retry'}
if not user_explicit:
reused = ensure_inventory({
'task_id': task.task_no,
'mode': 'auto',
'operator_id': int(user_id),
'_trusted_user_id': int(user_id),
'event_source': 'workspace_api',
'trigger': trigger_norm,
})
if str((reused or {}).get('status') or '') in {'ok', 'completed'}:
if continue_auto_progress:
return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs)
return _map_tool_result(
reused,
action=ACTION_FETCH_INVENTORY,
base_kwargs=base_kwargs,
message='已复用库存快照',
)
fetched = ensure_inventory({
'task_id': task.task_no,
'mode': 'retry_rpa',
'operator_id': int(user_id),
'_trusted_user_id': int(user_id),
'event_source': 'workspace_api',
'trigger': trigger_norm,
})
return _map_tool_result(
fetched,
@@ -440,13 +552,28 @@ def _execute(
)
if action == ACTION_REMATCH:
matched = shipping_tools.match_inventory({
'task_id': task.task_no,
'operator_id': int(user_id),
'_trusted_user_id': int(user_id),
'event_source': 'workspace_api',
'line_key': line_key,
})
# 题5B:有 line_key → 调用新 match_inventory_line 只对目标行匹配,避免整单重算覆盖其他行;
# 否则(例如 scope=task 且缺快照或整单重算)仍走原 match_inventory。
norm_line_key = str(line_key or '').strip()
if norm_line_key:
matched = shipping_tools.match_inventory_line(
{
'task_id': task.task_no,
'operator_id': int(user_id),
'_trusted_user_id': int(user_id),
'event_source': 'workspace_api',
'trigger': trigger_norm,
},
line_key=norm_line_key,
)
else:
matched = shipping_tools.match_inventory({
'task_id': task.task_no,
'operator_id': int(user_id),
'_trusted_user_id': int(user_id),
'event_source': 'workspace_api',
'trigger': trigger_norm,
})
mapped = _map_tool_result(
matched,
action=ACTION_REMATCH,
@@ -614,14 +741,137 @@ def _build_idempotency_key(
def _is_inventory_rpa_active(task: ShippingNotice) -> bool:
"""库存 RPA 是否仍在等待。"""
pending = str(getattr(task, 'pending_human_reason', None) or '').strip().lower()
process = str(getattr(task, 'process_status', None) or '').strip().lower()
if pending == PH_RPA_PENDING:
return True
if process == 'waiting_inventory' and pending == PH_RPA_PENDING:
return True
return False
"""库存 RPA 是否仍在等待(旧兼容实现,等价于 summary.active_attempt_count > 0)。"""
return summarize_inventory_rpa_latest_attempts(task, include_gate_status=True)['active_attempt_count'] > 0
def summarize_inventory_rpa_latest_attempts(
task: ShippingNotice,
*,
include_gate_status: bool = False,
) -> dict[str, Any]:
"""
汇总逐源库存 RPA Attempt 最新状态(题2B:按冻结源过滤,不再依赖 pending_human_reason 滞后字段)。
【AI 触发时机】:Projection retryable/status 计算、重试决策幂等守卫、already_running 返回时统一读取。
核心逻辑:
[STEP 1] 读取 required_frozen_sources(= Task 级 inventory_source_code 单源 或 T3 冻结多源列表)
[STEP 2] 对每个 required source 查最新 attempt;汇总 prepared / pending / failed / exhausted。
[STEP 3] active_attempt_count = pending 数量;同时给出 latest_attempts 的结构化视图。
[STEP 4] 可选 include_gate_status:补充 Process Gate Attempt 的 queued/running。
"""
from app.models import (
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
ShippingTaskInventoryRpaAttempt,
)
from app.services.shipping_notice.stp_inventory_freeze import (
task_frozen_inventory_source_codes,
)
task_no = str(task.task_no or '').strip()
frozen_sources: list[str] = [
str(code) for code in (task_frozen_inventory_source_codes(task) or []) if code
]
if not frozen_sources:
single = str(task.inventory_source_code or '').strip().upper()
if single:
frozen_sources = [single]
required_frozen_sources: list[str] = list(dict.fromkeys(frozen_sources))
prepared: list[str] = []
pending: list[str] = []
failed: list[str] = []
exhausted: list[str] = []
latest_attempts: dict[str, dict[str, Any]] = {}
if task_no:
# 先一次性查出 (task_no, source_code) → 最新 attempt
rows = (
ShippingTaskInventoryRpaAttempt.query
.filter(ShippingTaskInventoryRpaAttempt.task_no == task_no)
.order_by(
ShippingTaskInventoryRpaAttempt.source_code.asc(),
ShippingTaskInventoryRpaAttempt.attempt_no.desc(),
ShippingTaskInventoryRpaAttempt.id.desc(),
)
.all()
)
latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {}
for row in rows:
key = str(row.source_code or '').strip().upper() or None
if not key or key in latest_by_source:
continue
latest_by_source[key] = row
for code in required_frozen_sources:
key = str(code or '').strip().upper() or None
if not key:
continue
att = latest_by_source.get(key)
if not att:
latest_attempts[key] = {
'attempt_no': 0,
'run_no': None,
'status': 'not_started',
'error_code': None,
'error_message': None,
}
continue
st = str(att.status or '').strip().lower()
latest_attempts[key] = {
'attempt_no': int(att.attempt_no or 0),
'run_no': str(att.run_no or '') or None,
'status': st,
'error_code': str(att.error_code or '') or None,
'error_message': str(att.error_message or '') or None,
}
if st in {'queued', 'running'}:
pending.append(key)
elif st in {'succeeded', 'consumed'}:
prepared.append(key)
elif st == 'exhausted':
exhausted.append(key)
failed.append(key)
elif st in {'failed', 'trigger_write_error'}:
failed.append(key)
active_attempt_count = len(pending)
gate_attempt_active = False
task_id = getattr(task, 'id', None)
if include_gate_status and task_id is not None:
any_active = bool(
db.session.query(ShippingProcessGateAttempt.id)
.join(
ShippingProcessGate,
ShippingProcessGateAttempt.gate_id == ShippingProcessGate.id,
)
.join(
ShippingProcessExecution,
ShippingProcessGate.execution_id == ShippingProcessExecution.id,
)
.filter(ShippingProcessGateAttempt.status.in_(('queued', 'running')))
.filter(ShippingProcessExecution.task_id == int(task_id))
.limit(1)
.first()
)
gate_attempt_active = any_active
if any_active and active_attempt_count <= 0:
active_attempt_count = 1
return {
'task_no': task_no or None,
'required_frozen_sources': required_frozen_sources,
'prepared_source_codes': prepared,
'pending_source_codes': pending,
'failed_source_codes': failed,
'exhausted_source_codes': exhausted,
'active_attempt_count': int(active_attempt_count),
'gate_attempt_active': bool(gate_attempt_active),
'latest_attempts': latest_attempts,
}
def _frozen_or_candidate_codes(task: ShippingNotice) -> list[str]:
@@ -695,7 +945,7 @@ def _audit_decision(
owner_user_id=int(getattr(task, 'user_id', 0) or user_id),
reason_code=str(result.get('reason_code') or '') or None,
reason=str(reason or trigger)[:200],
result='success' if result.get('status') != STATUS_FAILED else 'failed',
result='success' if result.get('status') != STATUS_FAILED else 'failure',
error_code=str(result.get('reason_code') or '') if result.get('status') == STATUS_FAILED else None,
metadata={
'scope': scope,
@@ -192,6 +192,28 @@ def auto_match_enabled() -> bool:
return cfg_bool("SHIPPING_NOTICE_AUTO_MATCH_ENABLED", True)
def auto_candidate_freeze_enabled() -> bool:
"""
[T10 周一受控测试] 是否在解析确认后自动冻结候选集合。
核心语义:路由解析通过 → 立即生成任务级+行级候选,进入 AUTO_INVENTORY_PREPARE;
关闭则停在 inventory_source_unresolved 待人工确认源。默认 true(受控测试开启)。
"""
return cfg_bool("SHIPPING_NOTICE_AUTO_CANDIDATE_FREEZE_ENABLED", True)
def auto_inventory_prepare_enabled() -> bool:
"""
[T10 周一受控测试] 是否在候选冻结后自动按 source_code 触发 per-source RPA Attempt。
关闭则停在 candidates_frozen(等待外部 API 或人工发 Trigger)。默认 true(受控测试开启)。
"""
return cfg_bool("SHIPPING_NOTICE_AUTO_INVENTORY_PREPARE_ENABLED", True)
def auto_generate_excel_enabled() -> bool:
"""[T10 周一受控测试] 是否在库存匹配全 matched 后自动调用 generate_excel。默认 true。"""
return cfg_bool("SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED", True)
def auto_chain_fallback_enabled() -> bool:
"""Hxops chat 是否在 match 后自动串联 export/upload(全局开关)。"""
return cfg_bool("SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK", True)
@@ -69,6 +69,7 @@ def confirm_temporary_inventory_use(payload: dict):
# 履约阶段
match_inventory = fulfillment_workflow.match_inventory
match_inventory_line = fulfillment_workflow.match_inventory_line
generate_excel = fulfillment_workflow.generate_excel
upload_to_freight = fulfillment_workflow.upload_to_freight
rpa_report_upload = fulfillment_workflow.rpa_report_upload
@@ -396,6 +396,9 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
Returns:
stp_facts 字典或 None。
"""
from app.services.shipping_notice.inventory_candidate_projection import (
project_inventory_candidate_facts,
)
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.stp_line_inventory_match import multi_source_recovery_source_codes
from app.services.shipping_notice.stp_progress_contract import STP_FACTS_ALLOWED_KEYS
@@ -403,25 +406,26 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
status = str(task.inventory_source_status or '').strip()
method = str(task.inventory_source_method or '').strip()
candidates = payload.get('line_inventory_candidates') if isinstance(payload.get('line_inventory_candidates'), dict) else {}
resolutions_raw = payload.get('line_inventory_resolutions')
resolutions = [item for item in resolutions_raw if isinstance(item, dict)] if isinstance(resolutions_raw, list) else []
multi_block = bool(payload.get('multi_source_excel_block'))
frozen_codes = list(candidates.get('source_codes') or []) or task_frozen_inventory_source_codes(task)
candidate_projection = project_inventory_candidate_facts(task)
frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_inventory_source_codes(task)
has_stp = (
status in {'candidates_frozen', 'resolved'}
or method.startswith('stp')
or bool(frozen_codes)
or bool(resolutions)
or multi_block
or bool(payload.get('line_inventory_candidates'))
or bool(candidate_projection.get('current_set'))
)
if not has_stp:
return None
counts: dict[str, int] = {}
compact_resolutions: list[dict[str, Any]] = []
for item in resolutions:
resolution_source = list(candidate_projection.get('line_resolutions') or []) or resolutions
for item in resolution_source:
disposition = str(item.get('disposition') or 'unknown')
counts[disposition] = counts.get(disposition, 0) + 1
compact_resolutions.append({
@@ -441,6 +445,14 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None:
'inventory_source_code': str(task.inventory_source_code or '').strip().upper() or None,
'inventory_source_method': method or None,
'frozen_candidate_codes': [str(code).strip().upper() for code in frozen_codes if str(code or '').strip()],
'candidate_set_id': candidate_projection.get('candidate_set_id'),
'candidate_set_version': candidate_projection.get('candidate_set_version'),
'candidate_set_status': candidate_projection.get('candidate_set_status'),
'candidate_source_codes': list(candidate_projection.get('candidate_source_codes') or []),
'prepared_source_codes': list(candidate_projection.get('prepared_source_codes') or []),
'pending_source_codes': list(candidate_projection.get('pending_source_codes') or []),
'failed_source_codes': list(candidate_projection.get('failed_source_codes') or []),
'source_attempts': dict(candidate_projection.get('source_attempts') or {}),
'resolution_counts': counts,
'line_resolutions': compact_resolutions,
'multi_source_excel_block': multi_block,