Merge branch 'dev' into runny827

feat(training): 新增精益培训视频与周任务管理

# Conflicts:
#	backend/app/models/__init__.py
This commit is contained in:
runny committed 2026-09-08 18:30:09 +08:00
1 parent 85d27e9ffa
commit 91b7233872
812 files changed
+73763 -18908

No files matched your search

@@ -2,9 +2,11 @@
services/shipping_notice/auto_progress_controller.py
用途:P0-3 发货任务 AutoProgress 的正式 Task 级串行控制器。
依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务。
依赖:Job transactional outbox、ShippingProcessExecution/Gate、CandidateSet、现有库存/RPA、匹配和 Excel 服务;
process_gate_job_service.cancel_inventory_external_wait_polls(显式 retry_rpa 终止轮询)。
逻辑:入口只创建或复用一个 Task 活动 Job;Worker 每次仅评估一个正式 Gate,Gate passed 与后继 Job
在同一数据库事务落库。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
在同一数据库事务落库。显式 inventory_mode=retry_rpa 时覆盖 waiting_external 残留 poll,
强制入队 retry_inventory_preparation。库存源 RPA Attempt 仍由既有 per_source_rpa_service 独立并行执行。
"""
from __future__ import annotations
@@ -18,18 +20,18 @@ from flask import current_app
from app import db
from app.jobs.queue import enqueue
from app.jobs.types import JobType
from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.models import Job, ShippingOrderTask, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
from app.services.shipping_notice.process_gate_contract import action_belongs_to_gate
from app.services.shipping_notice.tool_common import log_task_event
_ACTIVE_JOB_STATUSES = ('queued', 'running')
_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled', 'canceled'})
_CANCELLED_LIFECYCLE_STATUSES = frozenset({'voided', 'archived', 'deleted', 'cancelled'})
def audit_legacy_forwarded_entrypoint(
*, task: ShippingNotice, action_code: str, actor_id: int | None = None,
*, task: ShippingOrderTask, action_code: str, actor_id: int | None = None,
request_id: str | None = None,
) -> None:
"""记录旧工作台入口已转发至正式 Gate Orchestrator 的审计事实。"""
@@ -51,9 +53,9 @@ def _utc_now() -> datetime:
return datetime.utcnow()
def _task_is_cancelled(task: ShippingNotice) -> bool:
def _task_is_cancelled(task: ShippingOrderTask) -> bool:
"""根据生命周期事实判断任务是否不可再推进,旧 Job 不得将其复活。"""
return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES
return str(getattr(task, 'lifecycle_status', '') or '').strip().lower() in _CANCELLED_LIFECYCLE_STATUSES or str(getattr(task, 'status', '') or '').strip().lower() == 'cancelled'
def _recover_stale_active_job(job: Job) -> bool:
@@ -90,6 +92,17 @@ def _recover_stale_active_job(job: Job) -> bool:
gate.status = 'blocked_manual'
gate.blocking_reason_code = 'technical_failure_present'
gate.updated_at = now
# [FIX] 同一事务内重算 Execution 指针并回写 OT.stage,避免 Gate 已被判为
# blocked_manual 而 execution.status / OT.stage 仍停在上一机械阶段(如 automating)。
execution_id = getattr(gate, 'execution_id', None)
execution = (
db.session.get(ShippingProcessExecution, int(execution_id))
if execution_id is not None else None
)
if execution is not None:
from app.services.shipping_notice.process_gate_service import _refresh_execution_pointers
_refresh_execution_pointers(execution)
db.session.flush()
return True
@@ -111,7 +124,7 @@ def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool:
def determine_formal_start_gate(
task: ShippingNotice,
task: ShippingOrderTask,
*,
candidate_set: Any | None = None,
) -> str:
@@ -126,7 +139,8 @@ def determine_formal_start_gate(
return 'order_freeze_readiness'
# 仅当服务端已明确记录 pending/failed 时阻断客户确认;None 保留给历史
# Task-only 兼容构造,不能把缺失的可选字段误当成失败事实。
customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower()
from app.services.shipping_notice.customer_identity_gate import customer_confirmation_facts
customer_status = str((customer_confirmation_facts(task) or {}).get('status') or '').strip().lower()
if customer_status in {'pending', 'needs_review', 'failed', 'unresolved'}:
return 'customer_resolution'
# 字段冲突是独立的正式 Gate,必须先于候选冻结和库存准备处理。
@@ -139,7 +153,7 @@ def determine_formal_start_gate(
def _create_formal_execution_for_task(
task: ShippingNotice,
task: ShippingOrderTask,
*,
candidate_set_id: int | None,
) -> ShippingProcessExecution:
@@ -178,7 +192,7 @@ def _supersede_duplicate_execution(
)
def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution:
def _active_execution_for_task(task: ShippingOrderTask, *, candidate_set_id: int | None) -> ShippingProcessExecution:
"""
锁定并取得当前唯一活动 Execution。
@@ -235,7 +249,7 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int |
return _create_formal_execution_for_task(task, candidate_set_id=candidate_set_id)
def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None:
def supersede_auto_progress_for_candidate_refreeze(task: ShippingOrderTask) -> None:
"""
在 CandidateSet 指针切换后取消旧 Job/未完成 Gate,防止旧版本副作用污染新链。
@@ -309,9 +323,37 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi
return None, None
def _auto_retry_blocked(
trigger: str | None,
has_failed_worker_attempt: bool,
resume_gate_code: str | None = None,
) -> bool:
"""[禁止自动重试] 裁决:已存在失败 Worker Attempt 时是否拒绝再入队。
核心逻辑:防止自动/后台 trigger 在外部依赖持续故障时无人值守空转重试;
但用户显式重试(user_retry / user_manual)或带 resume_gate_code 的显式定向推进
(如匹配工具调 run_task_auto_progress,其 trigger 为 tool_api_match_inventory_line
而非 user_retry)应放行,否则点"重新匹配库存"会因 has_failed_worker_attempt
被误拦、报"自动推进已无待处理 Gate"。
Args:
trigger: 触发类型(auto / user_retry / user_manual / worker_takeover / ...)。
has_failed_worker_attempt: 当前 Gate 是否已有带 job_id 的失败 Attempt。
resume_gate_code: 显式定向推进的目标 Gate;有值即视为用户/工具主动恢复,不拦。
Returns:
True 表示应禁止自动再入队;False 表示放行。
"""
user_initiated = str(trigger or '').strip() in {'user_retry', 'user_manual'}
explicit_resume = bool(str(resume_gate_code or '').strip())
return bool(has_failed_worker_attempt) and not user_initiated and not explicit_resume
def submit_auto_progress(
*, task: ShippingNotice, trigger: str, operator_id: int | None = None,
*, task: ShippingOrderTask, trigger: str, operator_id: int | None = None,
resume_gate_code: str | None = None, commit: bool = True,
inventory_mode: str = 'auto',
line_scope_key: str | None = None,
recovery_plan_id: int | None = None,
recovery_attempt_id: int | None = None,
resume_after_gate: str | None = None,
@@ -319,14 +361,12 @@ def submit_auto_progress(
"""
接收任何自动/用户触发并安全入队当前 Gate。
普通调用不会信任 resume_gate_code;即使管理员提供诊断 Gate,仍由最早未通过 Gate 决定实际工作。
入口只接受 ShippingOrderTask;Execution 与 Gate 始终按 OT 任务身份推进。
"""
# ShippingNotice.shipping_case 使用 joined eager load,会产生 LEFT OUTER JOIN;
# PostgreSQL 禁止对外连接可空侧执行无目标 FOR UPDATE,因此仅锁主表。
locked_task = (
ShippingNotice.query
ShippingOrderTask.query
.filter_by(id=int(task.id))
.with_for_update(of=ShippingNotice)
.with_for_update(of=ShippingOrderTask)
.first()
)
if locked_task is None:
@@ -373,14 +413,23 @@ def submit_auto_progress(
from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
actor_id=operator_id,
explicit_inventory_retry = (
str(inventory_mode or '').strip() == 'retry_rpa'
and str(resume_gate_code or '').strip() == 'inventory_preparation'
)
db.session.flush()
if not explicit_inventory_retry:
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
actor_id=operator_id,
)
db.session.flush()
execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one()
current_gate = str(execution.current_gate_code or '').strip() or None
current_gate = (
'inventory_preparation'
if explicit_inventory_retry
else str(execution.current_gate_code or '').strip() or None
)
gate = (
ShippingProcessGate.query
.filter_by(execution_id=int(execution.id), gate_code=current_gate)
@@ -388,6 +437,53 @@ def submit_auto_progress(
.first()
if current_gate else None
)
if explicit_inventory_retry and gate is not None:
# [ROOT CAUSE] 显式 retry_rpa(含行级改源后重抓)必须覆盖残留的
# poll_inventory_preparation / waiting_external。否则只会再入队只读 poll:
# poll 遇到失败 Preparation 会直接收口,既不建新 RPA Attempt 也不写 trigger。
# passed / waiting_external / failed_terminal 一律放开为 blocked_retryable。
from app.services.shipping_notice.process_gate_job_service import (
cancel_inventory_external_wait_polls,
)
cancel_inventory_external_wait_polls(
gate_id=int(gate.id),
reason='显式库存重抓:终止外部等待轮询',
)
# 活动 Attempt 不得被复用;否则 queue_gate_attempt 会因 BUSY 失败,
# 或 active_attempt 早退把「强制重抓」吞成「继续轮询」。
for stale in (
ShippingProcessGateAttempt.query
.filter(
ShippingProcessGateAttempt.gate_id == int(gate.id),
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
)
.all()
):
stale.status = 'failed'
stale.error_code = 'superseded_by_explicit_retry'
stale.error_summary = '被显式库存重抓取代'
stale.finished_at = _utc_now()
if stale.job_id:
stale_job = db.session.get(Job, int(stale.job_id))
if stale_job is not None and str(stale_job.status or '') in _ACTIVE_JOB_STATUSES:
stale_job.status = 'cancelled'
stale_job.finished_at = _utc_now()
stale_job.message = '显式库存重抓:取消残留活动 Job'
gate.status = 'blocked_retryable'
gate.passed_at = None
gate.blocking_reason_code = 'inventory_rpa_retry_requested'
gate.next_action_code = 'retry_inventory_preparation'
gate.evaluation_version = int(gate.evaluation_version) + 1
gate.lock_version = int(gate.lock_version) + 1
gate.updated_at = _utc_now()
execution.current_gate_code = 'inventory_preparation'
# 阶段能力回退同时切换责任方;保留旧 Gate 的 owner 会使技术 Gate
# 被 submit_auto_progress 误判为人工节点,从而跳过 Attempt/RPA 入队。
execution.responsible_party = 'worker'
execution.primary_next_action_code = 'retry_inventory_preparation'
execution.updated_at = _utc_now()
db.session.flush()
active_attempt = (
ShippingProcessGateAttempt.query
.filter(
@@ -398,7 +494,7 @@ def submit_auto_progress(
.first()
if gate is not None else None
)
if active_attempt is not None and active_attempt.job_id:
if active_attempt is not None and active_attempt.job_id and not explicit_inventory_retry:
if commit:
db.session.commit()
return {
@@ -410,6 +506,22 @@ def submit_auto_progress(
'reused': True,
}
action_code = str(getattr(gate, 'next_action_code', '') or '').strip()
# [禁止自动重试] 门禁一旦存在“Worker 真实执行失败”的 Attempt(failed 且 job_id 非空),
# 本次自动投递即属重试:任何 trigger(回调/聊天/批处理)都不得再入队,重试必须由
# 用户在当前 Gate 显式发起;否则外部依赖持续故障时,回调/轮询会形成无人值守的
# “失败→重试→再失败”空转环。仅存量内联投影 Attempt(job_id 为空)或无 Attempt
# 的首次投递不受影响,编排初始触发保持不变。
has_failed_worker_attempt = (
gate is not None
and db.session.query(ShippingProcessGateAttempt.id)
.filter(
ShippingProcessGateAttempt.gate_id == int(gate.id),
ShippingProcessGateAttempt.status == 'failed',
ShippingProcessGateAttempt.job_id.isnot(None),
)
.first()
is not None
)
# 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的
# system/worker Gate 才可自动创建 Attempt 并入队。
# 责任方只描述 Gate 的默认归属,不代表当前动作可由 Worker 执行。
@@ -418,6 +530,7 @@ def submit_auto_progress(
if (
gate is not None
and action_code
and not _auto_retry_blocked(trigger, has_failed_worker_attempt, resume_gate_code)
and action_belongs_to_gate(gate_code=str(gate.gate_code), action_code=action_code)
and not is_navigation_action(action_code)
and is_technical_gate_party(execution.responsible_party)
@@ -439,6 +552,8 @@ def submit_auto_progress(
'candidate_set_id': candidate_set_id,
'fencing_token': uuid.uuid4().hex,
'trigger': trigger,
'inventory_mode': inventory_mode,
'line_scope_key': line_scope_key,
'recovery_plan_id': recovery_plan_id,
'recovery_attempt_id': recovery_attempt_id,
'resume_after_gate': resume_after_gate,
@@ -3,7 +3,7 @@ services/shipping_notice/batch_create_idempotency.py
用途:发货通知跨请求文件内容重复校验。
依赖:models.ShippingNotice。
逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingNotice.idempotency_key(货代上传幂等)语义分离。
逻辑:订单复核确认服务使用本模块串行化同用户的建单与重复校验;与 ShippingUploadAttempt.idempotency_key(货代上传幂等)语义分离。
"""
from __future__ import annotations
@@ -83,10 +83,17 @@ def assert_no_exact_duplicate_notices(
return
for content_hash, _filename in hashes:
query = ShippingNotice.query.filter(
ShippingNotice.user_id == user_id,
ShippingNotice.source_content_hash == content_hash,
ShippingNotice.lifecycle_status == 'active',
from app.models import ShippingOrderTask, ShippingOrderIntake, FileAsset
query = (
ShippingNotice.query
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id)
.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
.filter(
ShippingOrderTask.user_id == user_id,
FileAsset.content_hash == content_hash,
ShippingOrderTask.lifecycle_status == 'active',
)
)
if skipped_ids:
query = query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -14,7 +14,9 @@ from typing import Any
from flask import current_app
from app import db
from app.models import ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.constants import PH_RPA_PENDING
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
from app.services.shipping_notice.query_service import get_task_by_ref
from app.services.shipping_notice.tool_common import (
@@ -55,22 +57,25 @@ def _unmark_running(bucket: set[str], key: str) -> None:
def _should_orchestrate_task(task: Any) -> bool:
from app.services.shipping_notice.task_disposition_service import task_is_active
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
if not task_is_active(task):
return False
pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower()
if str(getattr(task, "upload_status", "") or "").strip().lower() in {"uploaded", "succeeded", "success"}:
pending_reason = str(task_blocking_reason(task) or '').strip().lower()
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success, latest_upload_attempt
if has_verified_upload_success(task):
return False
if getattr(task, "review_status", None):
return False
if (
not getattr(task, "inventory_lines_json", None)
not has_ready_inventory_file_for_task(task)
and pending_reason in {"", PH_RPA_PENDING}
):
return True
if getattr(task, "pending_human_reason", None):
if task_blocking_reason(task):
return False
if getattr(task, "upload_status", None) in {"pending", "uploading", "failed"}:
latest_attempt = latest_upload_attempt(task) if hasattr(task, 'id') else None
if latest_attempt is not None and str(latest_attempt.status or '').strip().lower() in {"pending", "running", "failed", "unknown", "timed_out"}:
return False
return True
@@ -95,6 +100,8 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
return {"status": "skipped", "message": "task already running"}
try:
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
task = get_task_by_ref(normalized_task_no)
if not task:
return {"status": "missing", "message": "task not found"}
@@ -102,30 +109,38 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
return {
"status": "skipped",
"message": (
f"skip stage={getattr(task, 'current_step', '') or ''}"
f" pending_human_reason={task.pending_human_reason or ''}"
f" review_status={task.review_status or ''}"
f"skip stage={getattr(task, 'stage', '') or ''}"
f" pending_human_reason={task_blocking_reason(task) or ''}"
f" review_status={getattr(task, 'review_status', '') or ''}"
),
}
log_task_event(
task,
"backend_orchestrator_task_started",
{"current_step": task.current_step, "lifecycle_status": task.lifecycle_status},
{"stage": task.stage, "lifecycle_status": task.lifecycle_status},
)
db.session.commit()
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id}
pending_reason = str(task.pending_human_reason or "").strip().lower()
pending_reason = str(task_blocking_reason(task) or '').strip().lower()
if (
not getattr(task, "inventory_lines_json", None)
not has_ready_inventory_file_for_task(task)
and pending_reason == PH_RPA_PENDING
):
# Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询
# PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
# [STEP] 先做一次同步超时复查:单次 RPA 触发已过期且无成功回执时直接落
# rpa_exhausted(needs_human),避免仅依赖异步 Gate 轮询导致单票卡在 running。
from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
recheck = maybe_recheck_inventory_rpa_wait(task, source='batch_orchestrator')
if recheck is not None:
result = recheck
else:
# Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询
# PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator')
if current_app:
current_app.logger.info(
"[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s",
@@ -134,7 +149,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
str(result.get("message") or "")[:300],
)
elif (
not getattr(task, "inventory_lines_json", None)
not has_ready_inventory_file_for_task(task)
and pending_reason == ""
):
payload["mode"] = "auto"
@@ -166,7 +181,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
"[shipping-orchestrator] auto-progress task_no=%s status=%s current_step_before=%s message=%s",
task.task_no,
result.get("status"),
task.current_step,
task.stage,
str(result.get("message") or "")[:300],
)
@@ -178,7 +193,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
{
"result_status": str(result.get("status") or ""),
"lifecycle_status": refreshed.lifecycle_status,
"current_step": refreshed.current_step,
"stage": refreshed.stage,
},
)
db.session.commit()
@@ -190,7 +205,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
db.session.rollback()
task = get_task_by_ref(normalized_task_no)
if task:
task.error_message = str(exc)
owner = task
if isinstance(task, ShippingNotice) and getattr(task, 'order_task_id', None):
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
if hasattr(owner, 'error_message'):
owner.error_message = str(exc)
log_task_event(task, "backend_orchestrator_task_failed", {"error": str(exc)[:1000]})
db.session.commit()
return {"status": "failed", "message": str(exc)[:500] or "background task failed"}
@@ -15,7 +15,7 @@ from sqlalchemy import update
from app import db
from app.core.errors import ConflictError
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.customer_normalization import SHORT_CODE_RE
BUSINESS_TYPE = "shipping_notice"
@@ -121,13 +121,19 @@ def _next_sequence_value(customer_id: int, business_date: date) -> int:
return int(value)
def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime | None = None) -> str:
def assign_notice_business_number(
notice: ShippingNotice,
*,
moment: datetime | None = None,
customer_id_override: int | None = None,
) -> str:
"""
为单个发货通知分配不可变业务编号;同一 PO 的不同通知单不会复用编号。
Args:
notice: 已绑定客户的 ShippingNotice;客户事实只读取 Notice 本身。
moment: 可选时刻,测试时用于固定上海业务日期。
customer_id_override: 纠错替代单使用的新客户;仅用于编号,不修改原 OT 的历史匹配事实。
Returns:
分配或已存在的 business_no。
@@ -137,12 +143,18 @@ def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime |
"""
if notice.business_no:
return str(notice.business_no)
if notice.customer_id is None:
owner = db.session.get(ShippingOrderTask, notice.order_task_id) if notice.order_task_id else None
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
resolution = customer_resolution_facts(owner) if owner is not None else {'customer_id': None}
customer_id = int(customer_id_override) if customer_id_override is not None else (
int(resolution['customer_id']) if resolution['customer_id'] is not None else None
)
if customer_id is None:
raise ConflictError(
'Shipping notice customer must be confirmed before numbering',
code='SHIPPING.BUSINESS_NUMBER_CUSTOMER_REQUIRED',
)
customer = db.session.get(ShippingCustomer, int(notice.customer_id))
customer = db.session.get(ShippingCustomer, customer_id)
if customer is None or customer.status != 'active':
raise ConflictError(
'Active customer is required before numbering',
@@ -160,7 +172,5 @@ def assign_notice_business_number(notice: ShippingNotice, *, moment: datetime |
notice.business_date = business_date
notice.business_sequence_value = sequence_value
notice.business_numbering_rule_version = NUMBERING_RULE_VERSION
notice.customer_name_snapshot = customer.standard_name
notice.customer_short_code_snapshot = short_code
db.session.flush()
return str(notice.business_no)
@@ -27,7 +27,6 @@ from app.models import (
ShippingOrderCandidate,
ShippingOrderCandidateQualification,
ShippingOrderExtraction,
ShippingOrderCustomerMatch,
)
from app.services.shipping_notice.candidate_qualification_contract import (
CANDIDATE_QUALIFICATION_EVALUATOR_VERSION,
@@ -71,7 +70,6 @@ _CONFIDENCE_SOURCE_DEFAULT_FALLBACK = 'default_fallback_0_85'
# 文档表格坐标不足只影响证据高亮质量,不代表订单字段值存在冲突。
# 保留在抽取诊断中供排查,但不得阻断人工建单或自动建单。
_NON_BLOCKING_CONFLICT_REASONS = frozenset({'layout_table_needs_review'})
_OPTIONAL_INTERNAL_FIELD_CODES = frozenset({'line_no'})
_EVIDENCE_GAP_REASONS = frozenset({'evidence_missing', 'pdf_evidence_missing'})
@@ -79,9 +77,8 @@ def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) ->
"""按冻结字段配置判断证据缺失是否只是可选字段诊断。
核心逻辑:优先读取 Candidate 关联 Extraction 的冻结 Schema;只有
``required`` 或 ``auto_create_key_field`` 才能阻断。历史 Candidate 无法
追溯 Schema 时,仅兼容已明确属于内部可派生字段的 ``line_no``,其余未知
字段继续 fail-closed。
``required`` 或 ``auto_create_key_field`` 才能阻断。无法追溯 Schema
时继续 fail-closed;系统项次由写路径生成,不构成证据缺失例外。
"""
reason = str(item.get('reason') or item.get('code') or '').strip()
if reason not in _EVIDENCE_GAP_REASONS:
@@ -111,7 +108,7 @@ def field_evidence_gap_is_non_blocking(candidate: Any, item: dict[str, Any]) ->
config = None
if config is not None:
return not bool(config.get('required')) and not bool(config.get('auto_create_key_field'))
return field_code in _OPTIONAL_INTERNAL_FIELD_CODES
return False
def blocking_candidate_conflicts(candidate: Any) -> list[Any]:
@@ -173,8 +170,7 @@ def resolve_candidate_customer_resolved(
"""
判定 Candidate/Extraction 的 Bill-to 客户是否已确认。
核心逻辑:优先读 ShippingOrderCustomerMatch(bill_to)=confirmed;
其次读 Candidate.structured_result_json.customer.resolution_status。
核心逻辑:只读 Candidate 的正式客户识别结果;不读取 bill_to 或解析摘要兜底。
Args:
candidate: 可选 Candidate。
@@ -183,56 +179,35 @@ def resolve_candidate_customer_resolved(
Returns:
True 表示客户已确认,可用于建单资格评估。
"""
ext_id = extraction_id
if ext_id is None and candidate is not None:
raw = getattr(candidate, 'order_extraction_id', None)
if raw is not None:
try:
ext_id = int(raw)
except (TypeError, ValueError):
ext_id = None
if ext_id is not None:
row = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(ext_id),
role='bill_to',
status='confirmed',
).first()
if row is not None and row.customer_id is not None:
return True
from app.services.shipping_notice.customer_resolution_service import resolution_for_extraction, resolution_for_task
if candidate is None:
return False
ok, _reason = _customer_ok(candidate, customer_resolved=None)
return bool(ok)
resolution = resolution_for_task(candidate) if candidate is not None else resolution_for_extraction(extraction_id)
if resolution is not None:
return bool(resolution.status == 'confirmed' and resolution.confirmed_customer_id is not None)
# review_case 人工确认新建的 Candidate 只在 structured_result_json['customer'] 写入确认事实
# (review_case 权威确认,见 order_review_confirmation_service._create_review_candidate),并不落 resolution 表;
# 在建单资格判断时兜底认可,避免"已确认客户却无法建单"。
structured = getattr(candidate, 'structured_result_json', None) if candidate is not None else None
if isinstance(structured, dict):
customer = structured.get('customer') if isinstance(structured.get('customer'), dict) else {}
return str(customer.get('resolution_status') or '').strip().lower() == 'confirmed'
return False
def resolve_confirmed_bill_to_customer_id(
def resolve_confirmed_customer_id(
*,
candidate: Any | None = None,
extraction_id: int | None = None,
) -> int | None:
"""
返回已确认 Bill-to 标准客户主键;未确认时为 None。
核心逻辑:与 resolve_candidate_customer_resolved 同源,额外取出 customer_id 供建单绑定。
返回正式识别结果中已确认的标准客户主键;未确认时为 None。
"""
ext_id = extraction_id
if ext_id is None and candidate is not None:
raw = getattr(candidate, 'order_extraction_id', None)
if raw is not None:
try:
ext_id = int(raw)
except (TypeError, ValueError):
ext_id = None
if ext_id is not None:
row = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(ext_id),
role='bill_to',
status='confirmed',
).first()
if row is not None and row.customer_id is not None:
return int(row.customer_id)
return None
from app.services.shipping_notice.customer_resolution_service import resolution_for_extraction, resolution_for_task
resolution = resolution_for_task(candidate) if candidate is not None else resolution_for_extraction(extraction_id)
return int(resolution.confirmed_customer_id) if (
resolution is not None and resolution.status == 'confirmed' and resolution.confirmed_customer_id is not None
) else None
def assert_customer_confirmed_before_task_create(
@@ -2,11 +2,17 @@
services/shipping_notice/chat_actions.py
用途:发货通知聊天只读状态适配。
依赖:state_machine(checkpoint 与内部状态迁移)、ui_state。
依赖:state_machine(位置/用户模式与内部状态迁移)、ui_state。
逻辑:Chat 不再拥有动作目录或写入口;仅输出 Gate 已裁决的只读 UI State。
"""
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, checkpoint_for_task, resolve_task_ui_state, validate_registry
from app.services.shipping_notice.state_machine import (
TaskTransition,
apply_task_transition,
position_for_task,
resolve_task_ui_state,
validate_registry,
)
from app.services.shipping_notice.ui_state import build_task_ui_state
@@ -14,19 +20,20 @@ def build_chat_actions_payload(task) -> dict:
"""
构建聊天气泡侧动作按钮兼容 payload。
核心逻辑:复用统一 UI State 读模型,抽取聊天侧 checkpoint/summary/process_gate;
核心逻辑:复用统一 UI State 读模型,抽取聊天侧 position/user_mode/summary/process_gate;
业务动作只从 ui_state.actions 返回,Chat 不再暴露旧 action_buttons。
Args:
task: ShippingNotice 模型实例。
Returns:
包含 task_no、checkpoint、process_gate、actions 与摘要的字典。
包含 task_no、position、user_mode、process_gate、actions 与摘要的字典。
"""
state = build_task_ui_state(task)
return {
"task_no": state.get("task_no"),
"checkpoint": state.get("checkpoint"),
"position": state.get("position"),
"user_mode": state.get("user_mode"),
"stage": state.get("stage"),
"todo": state.get("todo"),
"actions": state.get("actions"),
@@ -41,7 +48,7 @@ __all__ = [
"TaskTransition",
"apply_task_transition",
"build_chat_actions_payload",
"checkpoint_for_task",
"position_for_task",
"resolve_task_ui_state",
"validate_registry",
]
@@ -13,7 +13,7 @@ from typing import Any
from flask import current_app
from app.core.errors import ForbiddenError
from app.models import ChatSession, ShippingNotice
from app.models import ChatSession, ShippingOrderTask
READ_SCOPES = frozenset({'get_shipping_status'})
@@ -50,7 +50,7 @@ def require_chat_capability(*, token: Any, scope: str, task_no: str | None = Non
if session is None:
raise ForbiddenError('Chat capability session is invalid', code='SHIPPING.CHAT_CAPABILITY_DENIED')
if task_no:
task = ShippingNotice.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none()
task = ShippingOrderTask.query.filter_by(task_no=str(task_no).upper(), user_id=session.user_id).one_or_none()
if task is None or str(body.get('task') or '').upper() != task.task_no:
raise ForbiddenError('Task is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED')
return body
@@ -1,10 +1,10 @@
"""
services/shipping_notice/constants.py
用途:发货通知 API 字段名、checkpoint / review_status / pending_human_reason 的规范常量;
用途:发货通知 API 字段名、位置标签 POSITION_* / review_status / pending_human_reason 的规范常量;
并再导出错误可解释性分层原因码集合,供 Tool/Workspace 与门禁投影对齐。
依赖:error_explainability_contract(分层原因码冻结集);state_machine.py 引用 CP_*/PH_*/RS_*。
逻辑:tools.py、tool_response、workspace API 统一读本模块,避免 checkpoint id 漂移;
依赖:error_explainability_contract(分层原因码冻结集);state_machine / ui_state 引用 POSITION_*/PH_*/RS_*。
逻辑:tools.py、tool_response、workspace API 统一读本模块,避免位置标签漂移;
细粒度 reason_code 以 error_explainability_contract 为准,本文件仅再导出。
"""
@@ -36,28 +36,27 @@ from app.services.shipping_notice.error_explainability_contract import (
# Workspace / Hxops chat fallback only — Dify 正式路径不直接调用主推进 Tool;人工确认后由后端 worker 续跑
AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
# Checkpoints (tool_response.checkpoint; canonical ids — register buttons in state_machine.py)
CP_UPLOAD_REQ = "upload_req"
CP_PARSE_OK = "parse_ok"
CP_PARSE_REVIEW = "parse_review"
CP_CUSTOMER_REVIEW = "customer_review"
CP_TASK_EXISTS = "task_exists"
CP_RSV_REQ = "rsv_req"
CP_UPLOAD_FAILED = "upload_failed"
CP_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
CP_WAITING_UPLOAD = "waiting_upload"
CP_REJECTED = "rejected"
# Derived UI checkpoints (no separate pending_human_reason; from domain facts)
CP_INVENTORY_PENDING = "inventory_pending"
CP_READY_MATCH = "ready_to_match"
CP_READY_EXPORT = "ready_to_export"
CP_EXPORT_READY = "export_ready"
CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
CP_INVENTORY_SOURCE_REVIEW = "inventory_source_review"
CP_ORDER_FREEZE = "order_freeze"
CP_EXPORT_GENERATED = "export_generated"
CP_UPLOADED = "uploaded"
CP_COMPLETED = "completed"
# 位置标签(原 CheckPoint 字面量;非状态机。derive_position / 文案表共用)
POSITION_UPLOAD_REQ = "upload_req"
POSITION_PARSE_OK = "parse_ok" # 转瞬态;新逻辑勿依赖
POSITION_PARSE_REVIEW = "parse_review"
POSITION_CUSTOMER_REVIEW = "customer_review"
POSITION_TASK_EXISTS = "task_exists" # 信息态;新逻辑勿依赖
POSITION_RSV_REQ = "rsv_req"
POSITION_UPLOAD_FAILED = "upload_failed"
POSITION_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
POSITION_WAITING_UPLOAD = "waiting_upload"
POSITION_REJECTED = "rejected"
POSITION_INVENTORY_PENDING = "inventory_pending"
POSITION_READY_MATCH = "ready_to_match"
POSITION_READY_EXPORT = "ready_to_export"
POSITION_EXPORT_READY = "export_ready"
POSITION_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
POSITION_INVENTORY_SOURCE_REVIEW = "inventory_source_review"
POSITION_ORDER_FREEZE = "order_freeze"
POSITION_EXPORT_GENERATED = "export_generated"
POSITION_UPLOADED = "uploaded"
POSITION_COMPLETED = "completed"
# review_status
RS_PARSE_REVIEW = "parse_review"
@@ -68,13 +67,13 @@ RS_CONFIRMED = "confirmed"
# pending_human_reason (internal; shortened)
PH_LOW_CONF = "low_confidence"
PH_RSV_REQ = CP_RSV_REQ
PH_RSV_REQ = POSITION_RSV_REQ
PH_SHORTAGE = "shortage"
PH_RPA_EXHAUSTED = "rpa_exhausted"
PH_RPA_PENDING = "rpa_pending"
PH_INV_UNAVAIL = "inv_unavail"
PH_INVENTORY_SOURCE_UNRESOLVED = "inventory_source_unresolved"
PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED
PH_NOTICE_TEXT_EXTRACTION_FAILED = POSITION_NOTICE_TEXT_EXTRACTION_FAILED
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
@@ -82,26 +81,26 @@ PH_UPLOAD_RESULT_UNKNOWN = "upload_result_unknown"
# 错误可解释性契约再导出(阶段 0 冻结;接线见 error_explainability_contract / 契约文档)
__all__ = (
'AUTO_CHAIN_FALLBACK',
'CP_UPLOAD_REQ',
'CP_PARSE_OK',
'CP_PARSE_REVIEW',
'CP_CUSTOMER_REVIEW',
'CP_TASK_EXISTS',
'CP_RSV_REQ',
'CP_UPLOAD_FAILED',
'CP_UPLOAD_RESULT_UNKNOWN',
'CP_WAITING_UPLOAD',
'CP_REJECTED',
'CP_INVENTORY_PENDING',
'CP_READY_MATCH',
'CP_READY_EXPORT',
'CP_EXPORT_READY',
'CP_NOTICE_TEXT_EXTRACTION_FAILED',
'CP_INVENTORY_SOURCE_REVIEW',
'CP_ORDER_FREEZE',
'CP_EXPORT_GENERATED',
'CP_UPLOADED',
'CP_COMPLETED',
'POSITION_UPLOAD_REQ',
'POSITION_PARSE_OK',
'POSITION_PARSE_REVIEW',
'POSITION_CUSTOMER_REVIEW',
'POSITION_TASK_EXISTS',
'POSITION_RSV_REQ',
'POSITION_UPLOAD_FAILED',
'POSITION_UPLOAD_RESULT_UNKNOWN',
'POSITION_WAITING_UPLOAD',
'POSITION_REJECTED',
'POSITION_INVENTORY_PENDING',
'POSITION_READY_MATCH',
'POSITION_READY_EXPORT',
'POSITION_EXPORT_READY',
'POSITION_NOTICE_TEXT_EXTRACTION_FAILED',
'POSITION_INVENTORY_SOURCE_REVIEW',
'POSITION_ORDER_FREEZE',
'POSITION_EXPORT_GENERATED',
'POSITION_UPLOADED',
'POSITION_COMPLETED',
'RS_PARSE_REVIEW',
'RS_SHORTAGE_REVIEW',
'RS_RSV_REQ',
@@ -1,19 +1,16 @@
"""
services/shipping_notice/customer_auto_resolution.py
用途:基于管理员审核的强证据受控自动确认客户,并支持历史回填与编号后客户纠错。
依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、business_numbering_service、Flask 配置。
逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;管理员纠错时保留原号作废并创建替代业务单。
用途:基于管理员审核的强证据受控自动确认 OT 客户。
依赖:ShippingIdentityEvidence/ShadowResolution/Task、customer_identity_gate、Flask 配置。
逻辑:Candidate 建单后只按影子快照中的已审核授权证据自动确认;不创建 Notice 或分配业务编号。
"""
from __future__ import annotations
import hashlib
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import (
ShippingCustomer,
ShippingCustomerShadowResolution,
@@ -24,24 +21,25 @@ from app.models import (
ShippingOrderFieldDecision,
ShippingOrderFieldValue,
ShippingOrderSchemaVersion,
ShippingNotice,
ShippingOrderTask,
ShippingTaskEvent,
)
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
from app.services.shipping_notice.customer_identity_gate import (
confirm_task_customer,
customer_confirmation_facts,
)
from app.services.shipping_notice.customer_normalization import (
is_public_email_domain,
normalize_customer_name,
normalize_domain,
normalize_email,
)
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, generate_task_no
from app.services.shipping_notice.business_numbering_service import assign_notice_business_number
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int, task_event_task_id
AUTO_RESOLUTION_VERSION = "customer-auto-v2"
CUSTOMER_AUDIT_EVENT_TYPES = (
"customer_auto_resolution_evaluated",
"customer_auto_confirmed",
"customer_correction_applied",
)
@@ -92,6 +90,52 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]:
}
def _ruleset_definitions_semantically_compatible(
snapshot: dict[str, Any], schema_version: ShippingOrderSchemaVersion,
) -> bool:
"""
校验规则集冻结定义在解析所用 Schema 版本中语义契约仍成立(允许 Schema 常规重发布造成的版本错位)。
语义键集合:field_code / scope('header') / value_type / normalizer_key / available_for_customer_identity。
允许 display_name、aliases、extraction_instruction、evidence_policy 等非语义字段变化;
任一语义键不一致或字段被停用则 fail-closed,防止按过期配置标准化产生误绑客户。
Args:
snapshot: 影子 rule_set 快照(含 definitions)。
schema_version: 解析实际使用的 Schema 版本。
Returns:
True 表示所有带 field_code 的定义在新 Schema 中语义兼容。
"""
fields = ((schema_version.definition_json or {}).get('fields') or []) if schema_version else []
fields_by_code = {
str(item.get('field_code') or ''): item
for item in fields if isinstance(item, dict) and str(item.get('field_code') or '')
}
definitions = snapshot.get('definitions') if isinstance(snapshot, dict) else []
for raw in definitions if isinstance(definitions, list) else []:
if not isinstance(raw, dict):
continue
config = raw.get('field_config') if isinstance(raw.get('field_config'), dict) else {}
field_code = str(config.get('field_code') or '').strip()
if not field_code:
# 旧快照未保存 field_code:无法做语义校验,交由 UUID 直配路径(继续,不判定失败)。
continue
actual = fields_by_code.get(field_code)
if actual is None or not actual.get('enabled', True):
return False
if str(actual.get('scope') or '') != 'header' or str(config.get('scope') or '') != 'header':
return False
if str(actual.get('value_type') or '') != str(config.get('value_type') or ''):
return False
if not actual.get('available_for_customer_identity'):
return False
frozen_normalizer = str(config.get('normalizer_key') or '').strip()
if frozen_normalizer and frozen_normalizer != str(actual.get('normalizer_key') or '').strip():
return False
return True
def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] | None:
"""校验规则集及其订单 Schema/Extraction 锚点;任一链路缺失都安全降级。"""
context = shadow.resolution_context_json if isinstance(shadow.resolution_context_json, dict) else {}
@@ -118,16 +162,12 @@ def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] |
or snapshot.get('order_schema') != frozen_definition.get('order_schema')
):
return None
schema = snapshot.get('order_schema') if isinstance(snapshot.get('order_schema'), dict) else None
if not schema or schema.get('id') != shadow.order_schema_version_id:
return None
# Schema 锚点放宽:规则集冻结的版本 id 可与解析实际使用的版本错位(Schema 常规重发布),
# 但解析所用 Schema 版本必须真实存在(published/retired),且规则集定义在新 Schema 中语义兼容。
schema_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
if (
schema_version is None
or schema_version.status not in {'published', 'retired'}
or schema_version.version != schema.get('version')
or schema_version.checksum != schema.get('checksum')
):
if schema_version is None or schema_version.status not in {'published', 'retired'}:
return None
if not _ruleset_definitions_semantically_compatible(snapshot, schema_version):
return None
extraction_id = context.get('order_extraction_id')
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id)) if str(extraction_id or '').isdigit() else None
@@ -286,7 +326,7 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
return result
def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
def resolve_auto_customer_from_shadow(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
"""
使用任务来源 Candidate 的影子证据执行受控自动裁决。
@@ -307,13 +347,14 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
'is_eligible': False,
},
}
if task.source_candidate_id is None:
candidate_id = getattr(task, 'candidate_id', None)
if candidate_id is None:
return {"status": "no_candidate", "rule_version": AUTO_RESOLUTION_VERSION, "customer_id": None, "evidence": []}
shadow = db.session.query(ShippingCustomerShadowResolution).filter_by(
candidate_id=int(task.source_candidate_id),
candidate_id=int(candidate_id),
).first()
if shadow is None:
candidate = db.session.get(ShippingOrderCandidate, int(task.source_candidate_id))
candidate = db.session.get(ShippingOrderCandidate, int(candidate_id))
if candidate is not None:
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
@@ -333,20 +374,23 @@ def resolve_auto_customer_from_shadow(task: ShippingNotice) -> dict[str, Any]:
return {**decision, 'quality_gate': quality_gate}
def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
def try_auto_confirm_task_customer(task: ShippingOrderTask) -> dict[str, Any]:
"""
尝试自动确认并生成业务编号;未达门槛时保持 customer_review。
尝试自动确认 OT 客户;未达门槛时保持 customer_review。
核心逻辑:先写自动裁决审计,再复用人工确认的锁与编号事务;成功后将确认方法改为 auto_rule。
核心逻辑:先写自动裁决审计,再复用人工确认事务;成功后将确认方法改为 auto_rule。
"""
if task.customer_resolution_status == "confirmed":
return {"status": "already_confirmed", "customer_id": task.customer_id}
facts = customer_confirmation_facts(task)
if facts['status'] == 'confirmed':
return {"status": "already_confirmed", "customer_id": facts['customer_id']}
decision = resolve_auto_customer_from_shadow(task)
db.session.add(ShippingTaskEvent(
task_id=task.id,
event_type="customer_auto_resolution_evaluated",
detail_json=decision,
))
event_task_id = task_event_task_id(task)
if event_task_id is not None:
db.session.add(ShippingTaskEvent(
task_id=event_task_id,
event_type="customer_auto_resolution_evaluated",
detail_json=decision,
))
if decision.get("customer_id") is None:
db.session.flush()
return decision
@@ -358,165 +402,32 @@ def try_auto_confirm_task_customer(task: ShippingNotice) -> dict[str, Any]:
resolution_method="auto_rule",
commit=False,
)
db.session.add(ShippingTaskEvent(
task_id=updated.id,
event_type="customer_auto_confirmed",
detail_json={
**decision,
"business_no": updated.business_no,
},
))
updated_event_task_id = task_event_task_id(updated)
if updated_event_task_id is not None:
db.session.add(ShippingTaskEvent(
task_id=updated_event_task_id,
event_type="customer_auto_confirmed",
detail_json={
**decision,
"business_no": getattr(updated, 'business_no', None),
},
))
db.session.flush()
return {**decision, "status": "auto_confirmed", "business_no": updated.business_no}
def correct_numbered_task_customer(
task: ShippingNotice,
*,
customer_id: int,
reason: str,
actor_id: int | None,
) -> dict[str, Any]:
"""
更正已编号 Notice 的标准客户,同时保留原号作废与替代关系。
核心逻辑:锁定原 Notice 并校验未上传 → 创建替代 Notice 和新号 → 作废原 Notice →
清理新 Notice 的客户相关下游派生结果 → 写入新旧编号纠错审计;原业务号永不修改。
Args:
task: 原业务号或技术号定位到的当前任务版本。
customer_id: 管理员确认的正确启用客户 ID。
reason: 必填纠错原因,写入审计事件。
actor_id: 管理员审计 ID。
Returns:
原号、新号、替代业务单和受影响任务信息。
Raises:
ValidationError: 缺少原因、客户无效或客户未变化。
ConflictError: 业务单未编号、已上传或已被替代。
"""
correction_reason = str(reason or "").strip()
if not correction_reason:
raise ValidationError(
"Customer correction reason is required",
code="SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED",
)
original = (
db.session.query(ShippingNotice)
.filter(ShippingNotice.id == int(task.id))
.with_for_update()
.one_or_none()
)
if original is None or not original.business_no:
raise ConflictError(
"Numbered shipping notice is required for customer correction",
code="SHIPPING.CUSTOMER_CORRECTION_NUMBER_REQUIRED",
)
existing_replacement = db.session.query(ShippingNotice.id).filter_by(
supersedes_task_id=original.id,
).first()
if existing_replacement is not None or str(original.lifecycle_status or '') == 'voided':
raise ConflictError(
"Shipping notice has already been replaced",
code="SHIPPING.CUSTOMER_CORRECTION_ALREADY_REPLACED",
)
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError("Customer not found", code="SHIPPING.CUSTOMER_NOT_FOUND")
if customer.status == "merged":
raise ConflictError("Merged customer cannot be used", code="SHIPPING.CUSTOMER_MERGED_LOCKED")
if customer.status != "active":
raise ValidationError("Inactive customer cannot be used", code="SHIPPING.CUSTOMER_INACTIVE")
if original.customer_id == customer.id:
raise ValidationError(
"Corrected customer must differ from the current customer",
code="SHIPPING.CUSTOMER_CORRECTION_UNCHANGED",
)
if str(getattr(original, "upload_status", None) or "").strip().lower() in {"uploaded", "succeeded", "success"}:
raise ConflictError(
"Uploaded shipping notices require an external cancellation workflow before correction",
code="SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED",
)
old_business_no = str(original.business_no)
now = datetime.utcnow()
customer_fingerprint = hashlib.sha256(f"customer:{customer.id}".encode("ascii")).hexdigest()
replacement = ShippingNotice(
task_no=generate_task_no(),
user_id=original.user_id,
conversation_id=original.conversation_id,
source_type=original.source_type,
source_file_name=original.source_file_name,
source_file_type=original.source_file_type,
source_content_hash=original.source_content_hash,
source_asset_id=original.source_asset_id,
source_intake_id=original.source_intake_id,
source_candidate_id=original.source_candidate_id,
order_task_id=original.order_task_id,
business_fingerprint=original.business_fingerprint,
fingerprint_version=original.fingerprint_version,
content_fingerprint=original.content_fingerprint,
content_fingerprint_version=original.content_fingerprint_version,
document_version=int(original.document_version or 1) + 1,
supersedes_task_id=original.id,
raw_content=original.raw_content,
customer_id=customer.id,
customer_name_snapshot=customer.standard_name,
customer_short_code_snapshot=customer.short_code,
customer_resolution_status="confirmed",
customer_resolution_method="admin_correction",
customer_identity_fingerprint=customer_fingerprint,
customer_confirmed_by=actor_id,
customer_confirmed_at=now,
)
db.session.add(replacement)
db.session.flush()
new_business_no = assign_notice_business_number(replacement)
original.lifecycle_status = 'voided'
original.voided_at = now
original.voided_by_id = actor_id
original.void_reason = f'customer_correction:{correction_reason}'
correction_detail = {
"old_notice_id": original.id,
"new_notice_id": replacement.id,
"old_business_no": old_business_no,
"new_business_no": new_business_no,
"old_customer_id": original.customer_id,
"new_customer_id": customer.id,
"reason": correction_reason,
"actor_id": actor_id,
}
db.session.add(ShippingTaskEvent(task_id=original.id, event_type="customer_correction_applied", detail_json=correction_detail))
db.session.add(ShippingTaskEvent(task_id=replacement.id, event_type="customer_correction_applied", detail_json=correction_detail))
# 客户变化会使库存路由、匹配和导出失效;只重置当前版本,旧版本状态通过事件保留审计语义。
db.session.commit()
return {
"task_no": replacement.task_no,
"old_notice_id": original.id,
"new_notice_id": replacement.id,
"old_business_no": old_business_no,
"new_business_no": new_business_no,
"customer_id": customer.id,
"affected_task_count": 1,
}
# OT 阶段只确认客户;业务编号属于正式 Notice 的 Excel 生成事务。
return {**decision, "status": "auto_confirmed", "business_no": None}
def get_auto_resolution_metrics() -> dict[str, Any]:
"""汇总自动裁决和纠错事件,供管理员监控、查询与降级判断。"""
"""汇总自动裁决事件,供管理员监控、查询与降级判断。"""
evaluated = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_auto_resolution_evaluated",
).distinct().count()
confirmed = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_auto_confirmed",
).distinct().count()
corrected = db.session.query(ShippingTaskEvent.task_id).filter_by(
event_type="customer_correction_applied",
).distinct().count()
recent_events = (
db.session.query(ShippingTaskEvent, ShippingNotice.task_no)
.join(ShippingNotice, ShippingNotice.id == ShippingTaskEvent.task_id)
db.session.query(ShippingTaskEvent, ShippingOrderTask.task_no)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingTaskEvent.task_id)
.filter(ShippingTaskEvent.event_type.in_(CUSTOMER_AUDIT_EVENT_TYPES))
.order_by(ShippingTaskEvent.id.desc())
.limit(100)
@@ -528,7 +439,6 @@ def get_auto_resolution_metrics() -> dict[str, Any]:
'quality_gate': _auto_confirmation_quality_gate(),
"evaluated_count": evaluated,
"auto_confirmed_count": confirmed,
"corrected_task_count": corrected,
"auto_confirmation_rate": (confirmed / evaluated) if evaluated else None,
"recent_events": [
{
@@ -8,7 +8,6 @@ backend/app/services/shipping_notice/customer_identity_gate.py
from __future__ import annotations
import hashlib
from datetime import datetime
from typing import Any
@@ -16,18 +15,44 @@ from sqlalchemy import or_
from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent
from app.models import (
ShippingCustomer,
ShippingNotice,
ShippingOrderTask,
)
from app.services.shipping_notice.customer_normalization import clean_text
from app.services.shipping_notice.customer_resolution_service import (
confirm_customer_resolution,
customer_resolution_facts,
)
CUSTOMER_GATE_ERROR_CODE = 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
def customer_identity_is_confirmed(task: ShippingNotice) -> bool:
"""判断 Notice 自身是否已通过标准客户确认。"""
if task.customer_id is None:
def customer_confirmation_facts(task: ShippingNotice | ShippingOrderTask) -> dict[str, Any]:
"""读取唯一客户识别结果;bill_to 等订单字段仅可出现在识别证据中。"""
facts = customer_resolution_facts(task)
resolution = facts['resolution']
customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None
return {
'customer_id': facts['customer_id'],
'status': facts['status'],
'resolution_method': getattr(resolution, 'confirmation_method', None),
'identity_fingerprint': getattr(resolution, 'identity_rule_set_checksum', None),
'confirmed_by_id': getattr(resolution, 'confirmed_by_id', None),
'confirmed_at': getattr(resolution, 'confirmed_at', None),
'customer_name_snapshot': getattr(customer, 'standard_name', None),
'customer_short_code_snapshot': getattr(customer, 'short_code', None),
}
def customer_identity_is_confirmed(task: ShippingNotice | ShippingOrderTask) -> bool:
"""判断 OT 或正式 Notice 是否已通过标准客户确认。"""
facts = customer_confirmation_facts(task)
if facts['customer_id'] is None or facts['status'] != 'confirmed':
return False
customer = db.session.get(ShippingCustomer, int(task.customer_id))
return bool(customer and customer.status == 'active' and task.customer_resolution_status == 'confirmed')
customer = db.session.get(ShippingCustomer, int(facts['customer_id']))
return bool(customer and customer.status == 'active')
def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'continue') -> None:
@@ -42,6 +67,9 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con
"""
if customer_identity_is_confirmed(task):
return
facts = customer_confirmation_facts(task)
customer_id = facts['customer_id']
status = facts['status'] or 'pending'
raise AppError(
code=CUSTOMER_GATE_ERROR_CODE,
message='标准客户尚未确认,无法继续后续流程',
@@ -49,8 +77,8 @@ def assert_customer_identity_gate(task: ShippingNotice, *, operation: str = 'con
details={
'operation': operation,
'task_no': task.task_no,
'customer_resolution_status': task.customer_resolution_status or 'pending',
'customer_id': task.customer_id,
'customer_resolution_status': status,
'customer_id': customer_id,
},
)
@@ -71,15 +99,15 @@ def list_customer_options(*, query: str = '', limit: int = 100) -> list[dict[str
def confirm_task_customer(
task: ShippingNotice,
task: ShippingNotice | ShippingOrderTask,
*,
customer_id: int,
actor_id: int | None,
resolution_method: str = 'manual',
commit: bool = True,
) -> ShippingNotice:
) -> ShippingNotice | ShippingOrderTask:
"""
人工确认 Notice 所属标准客户;业务编号留待首次 Excel 生成时分配。
人工确认 OT/Notice 所属标准客户;业务编号仅由正式 Notice 的 Excel 阶段分配。
核心逻辑:锁定客户归属 → 校验启用客户 → 固化 Notice 客户快照。
客户确认与客户快照同事务提交;业务编号由 Excel 生成事务独占写入。
@@ -91,12 +119,11 @@ def confirm_task_customer(
resolution_method: manual/auto_rule 等审计方法。
commit: 是否提交事务;批次编排传 False 由外层统一提交。
"""
model = ShippingOrderTask if isinstance(task, ShippingOrderTask) else ShippingNotice
task = (
db.session.query(ShippingNotice)
.filter(ShippingNotice.id == int(task.id))
# ShippingNotice.customer 使用 joined eager load,会形成 LEFT OUTER JOIN;
# PostgreSQL 不允许锁定该连接的可空侧,故只锁当前 Notice 行。
.with_for_update(of=ShippingNotice)
db.session.query(model)
.filter(model.id == int(task.id))
.with_for_update(of=model)
.one()
)
customer = db.session.get(ShippingCustomer, int(customer_id))
@@ -106,38 +133,28 @@ def confirm_task_customer(
raise ConflictError('Merged customer cannot be confirmed', code='SHIPPING.CUSTOMER_MERGED_LOCKED')
if customer.status != 'active':
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
if task.business_no and task.customer_id not in {None, customer.id}:
facts = customer_confirmation_facts(task)
if getattr(task, 'business_no', None) and facts['customer_id'] not in {None, customer.id}:
raise ConflictError(
'Numbered shipping notice customer cannot be changed silently',
code='SHIPPING.CUSTOMER_NUMBERED_NOTICE_LOCKED',
)
now = datetime.utcnow()
previous_customer_id = task.customer_id
task.customer_id = customer.id
task.customer_name_snapshot = customer.standard_name
task.customer_short_code_snapshot = customer.short_code
fingerprint = hashlib.sha256(f'customer:{customer.id}'.encode('ascii')).hexdigest()
task.customer_resolution_status = 'confirmed'
task.customer_resolution_method = resolution_method
task.customer_identity_fingerprint = fingerprint
task.customer_confirmed_by = actor_id
task.customer_confirmed_at = now
db.session.add(ShippingTaskEvent(
task_id=task.id,
event_type='customer_confirmed',
detail_json={
'customer_id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'previous_customer_id': previous_customer_id,
'method': resolution_method,
'business_no': task.business_no,
},
))
owner = task
if not isinstance(task, ShippingOrderTask):
order_task_id = getattr(task, 'order_task_id', None)
owner = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else None
if owner is None:
raise ConflictError('Shipping notice is not linked to an order task', code='SHIPPING.ORDER_TASK_REQUIRED')
confirm_customer_resolution(
owner,
customer_id=int(customer.id),
actor_id=actor_id,
method=resolution_method,
)
if commit:
db.session.commit()
return db.session.get(ShippingNotice, int(task.id))
return db.session.get(model, int(task.id))
db.session.flush()
return task
@@ -154,7 +171,7 @@ def customer_gate_tool_response(task: ShippingNotice, *, operation: str) -> dict
task=task,
message='标准客户尚未确认,请先选择正式客户后再继续。',
data=serialize_task_for_tool(task),
checkpoint='customer_review',
position='customer_review',
stop_agent_turn=True,
forbidden_next_tools=[
'ensure_inventory', 'parse_inventory', 'match_inventory',
@@ -187,7 +204,7 @@ def confirm_customer(payload: dict[str, Any]) -> dict[str, Any]:
task=task,
message='请选择标准客户。',
data=serialize_task_for_tool(task),
checkpoint='customer_review',
position='customer_review',
stop_agent_turn=True,
)
updated = confirm_task_customer(
@@ -0,0 +1,76 @@
"""
services/shipping_notice/customer_resolution_service.py
用途:提供订单任务的唯一客户识别结果读取与确认入口。
依赖:ShippingCustomerShadowResolution、ShippingOrderTask、ShippingOrderCandidate、ShippingCustomer。
逻辑:客户身份来自已发布规则生成的证据快照;订单字段(包括 bill_to)只能作为证据,
不能承担客户角色或流程门禁真相。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingCustomer, ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderTask
def resolution_for_task(task: Any) -> ShippingCustomerShadowResolution | None:
"""按 OT、Notice 或 Candidate 读取正式客户识别结果,不回读 bill_to 或解析摘要。"""
candidate_id = getattr(task, 'id', None) if isinstance(task, ShippingOrderCandidate) else getattr(task, 'candidate_id', None)
if candidate_id is None:
order_task_id = getattr(task, 'order_task_id', None)
order_task = db.session.get(ShippingOrderTask, int(order_task_id)) if order_task_id else None
candidate_id = getattr(order_task, 'candidate_id', None)
if candidate_id is None:
return None
return ShippingCustomerShadowResolution.query.filter_by(candidate_id=int(candidate_id)).one_or_none()
def resolution_for_extraction(extraction_id: int | None) -> ShippingCustomerShadowResolution | None:
"""按当前 Extraction 找到关联 Candidate 的唯一客户识别结果。"""
if extraction_id is None:
return None
candidate = ShippingOrderCandidate.query.filter_by(order_extraction_id=int(extraction_id)).one_or_none()
return resolution_for_task(candidate) if candidate is not None else None
def customer_resolution_facts(task: Any) -> dict[str, Any]:
"""返回流程 Gate 所需的最小客户确认事实,缺失时 fail-closed。"""
resolution = resolution_for_task(task)
if resolution is None:
return {'customer_id': None, 'status': None, 'resolution': None}
return {
'customer_id': resolution.confirmed_customer_id,
'status': resolution.status,
'resolution': resolution,
}
def confirm_customer_resolution(
task: Any,
*,
customer_id: int,
actor_id: int | None,
method: str,
reason: str | None = None,
) -> ShippingCustomerShadowResolution:
"""确认当前识别结果的客户;人工或自动确认均保留原始证据、规则和候选快照。"""
resolution = resolution_for_task(task)
if resolution is None:
raise ConflictError('Customer resolution is required before confirmation', code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED')
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if customer.status != 'active':
raise ValidationError('Inactive customer cannot be confirmed', code='SHIPPING.CUSTOMER_INACTIVE')
resolution.confirmed_customer_id = int(customer.id)
resolution.confirmation_method = str(method)
resolution.confirmation_reason = str(reason or '').strip() or None
resolution.confirmed_by_id = actor_id
resolution.confirmed_at = datetime.utcnow()
resolution.status = 'confirmed'
db.session.flush()
return resolution
@@ -1,517 +0,0 @@
"""
services/shipping_notice/decision_workflow.py
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配和重解析。
依赖:state_machine、tool_response、query_service、库存源 Gate、fulfillment_workflow、
tool_common(操作人/生命周期快照)、fulfillment_audit。
逻辑:由 task_workflow / workspace API 转调;决策事件必须带操作人与前后快照,
reject/close/confirm 同步写入 ShippingAuditEvent。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import ShippingOrderCandidate, ShippingOrderProcessingRun, ShippingTaskInventoryLink
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
CP_PARSE_OK,
PH_INVENTORY_SOURCE_UNRESOLVED,
PH_LOW_CONF,
PH_RPA_PENDING,
PH_SHORTAGE,
RS_PARSE_REVIEW,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.fulfillment_workflow import match_completed
from app.services.shipping_notice.task_order_field_editor import retire_current_order_extraction
from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
adjudicate_and_apply_inventory_source,
ensure_inventory_source_review_state,
)
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state
from app.services.shipping_notice.tool_common import (
log_task_action_event,
log_task_event,
merge_tool_payload,
payload_wants_auto_chain_fallback,
resolve_workspace_actor_id,
task_lifecycle_audit_snapshot,
prepend_tool_message,
)
from app.services.shipping_notice.tool_response import tool_response
def start_task_orchestrator(task_no: str | None) -> bool:
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
return _start(task_no)
def _reset_inventory_state_for_forced_rpa(task) -> None:
"""
清理旧库存派生结果,让 retry_rpa 成为真正的“重新获取库存”。
【AI 触发时机】:用户明确要求重新获取库存时由 submit_decision 内部调用。
"""
task.inventory_lines_json = None
task.match_status = None
task.shortage_json = None
task.line_results_json = None
task.export_file_path = None
task.export_file_name = None
task.freight_ref_no = None
task.upload_status = None
task.upload_mode = None
def _request_formal_gate_action(**kwargs):
"""决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。
核心逻辑:请求正式 Gate 恢复前先清除任务级解析/复核阻断残留
(review_status / pending_human_reason / error_message / upload 错误),
避免旧阻断事实污染重启后的 Gate 投影。写入由被调用方的事务统一提交。
"""
task = kwargs.get('task')
if task is not None:
task.upload_error_message = None
task.upload_receipt_json = None
task.review_status = None
task.pending_human_reason = None
task.error_message = None
from app.services.shipping_notice.task_retry_decision_service import _request_formal_gate_action as _request
return _request(**kwargs)
def _prepare_task_for_inventory_reupload(task) -> None:
"""
解除任务当前库存快照并清理派生结果,等待用户重新选择正式库存文件。
【AI 触发时机】:用户明确选择“重新上传库存”时由 submit_decision 内部调用。
历史库存快照与 link 保留审计,但当前 active link 会停用,且不会进入字段推断链路。
"""
if task.id is not None:
for link in ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True).all():
link.is_active = False
_reset_inventory_state_for_forced_rpa(task)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
"""
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、正式 Gate
Recovery 或重解析等分支;工作台入口须注入 operator_id 以保证审计非匿名。
Args:
payload: 必须包含任务定位信息与 decision;可选 comment、lang、operator_id/actor_id。
Returns:
dict[str, Any]: Tool 标准响应,返回决策后的任务阶段和下一步动作。
"""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(
status="failed",
message=t("workflow.decision.task_not_found", lang="zh"),
)
decision = str(payload.get("decision") or "").strip().lower()
comment = str(payload.get("comment") or "").strip()
lang = resolve_lang(payload)
event_source = str(payload.get("event_source") or "").strip() or "decision_workflow"
actor_id = resolve_workspace_actor_id(payload)
before_snapshot = task_lifecycle_audit_snapshot(task)
# Published parsing profiles are the only production mapping contract.
# Reject legacy task-level mapping decisions instead of reopening a manual
# mapping path that could override the source's configured profile.
if decision in {"confirm_inventory_mapping", "correct_inventory_mapping"}:
return tool_response(
status="failed",
task_id=task.task_no,
message="库存字段映射已由库存站点的已发布解析方案管理;请在库存映射中调整方案后重新获取库存。",
data=serialize_task_for_tool(task),
)
if decision == "reparse_inventory":
_prepare_task_for_inventory_reupload(task)
log_task_action_event(
task,
"inventory_reupload_requested",
action="reparse_inventory",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="当前库存已解除关联,请重新选择库存文件。系统将按库存站点已发布的解析方案校验并解析。",
data=serialize_task_for_tool(task),
checkpoint="upload_req",
stop_agent_turn=True,
)
# [STEP 1] 先处理终止型决策。
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
if decision == "reject":
apply_task_transition(task, TaskTransition.REJECTED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"decision_rejected",
action="reject",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='reject',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot or {'status': 'active'},
after=after_snapshot or {'status': 'rejected'},
metadata={'decision': 'reject'},
source=event_source,
)
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=t("workflow.decision.rejected", lang=lang),
data=serialize_task_for_tool(task),
)
if decision in {"close", "closed"}:
apply_task_transition(task, TaskTransition.CLOSED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"decision_closed",
action="close",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='close',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot or {'status': 'active'},
after=after_snapshot or {'status': 'closed'},
metadata={'decision': 'close'},
source=event_source,
)
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=t("workflow.decision.closed", lang=lang),
data=serialize_task_for_tool(task),
)
# [STEP 2] 处理“确认继续”类决策。
# confirm 既可能表示确认解析,也可能表示确认已匹配结果,因此要结合当前状态分支判断。
if decision in {"confirm", "confirmed", "confirm_parse"}:
if task.review_status == RS_SHORTAGE_REVIEW or task.pending_human_reason == PH_SHORTAGE:
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.shortage_confirm_blocked", lang=lang),
data=serialize_task_for_tool(task),
)
if (
decision == "confirm_parse"
or task.review_status == RS_PARSE_REVIEW
or task.pending_human_reason == PH_LOW_CONF
or not match_completed(task)
):
parse_validation = (
(task.step_payload_json or {}).get("parse_validation")
if isinstance(task.step_payload_json, dict)
else None
)
blocking_issues = [
item
for item in (parse_validation.get("issues") if isinstance(parse_validation, dict) else []) or []
if isinstance(item, dict) and item.get("severity") == "blocking"
]
if blocking_issues:
return tool_response(
status="needs_human",
task=task,
message="解析结果仍包含不合法的关键字段,请修正后再确认。",
data={**serialize_task_for_tool(task), "parse_validation": parse_validation},
checkpoint=task.review_status or "parse_review",
stop_agent_turn=True,
forbidden_next_tools=["ensure_inventory", "parse_inventory", "match_inventory", "generate_shipment_excel"],
)
is_low_confidence_parse_confirm = task.pending_human_reason == PH_LOW_CONF
# 已在库存源确认节点时禁止用 confirm 跳过;低置信度解析复核可先 confirm,确认后再进库存源。
if (
not is_low_confidence_parse_confirm
and (
task.pending_human_reason == PH_INVENTORY_SOURCE_UNRESOLVED
or not is_inventory_source_stable(task)
)
):
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message="库存源尚未确定,请先完成库存源确认。",
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
apply_task_transition(task, TaskTransition.CONFIRM_PARSE)
task.match_status = None
task.shortage_json = None
task.line_results_json = None
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"parse_confirmed",
action="confirm",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='confirm_parse',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot,
after=after_snapshot,
metadata={'decision': decision},
source=event_source,
)
db.session.commit()
if not is_inventory_source_stable(task):
adjudication = ensure_inventory_source_review_state(task)
db.session.commit()
return tool_response(
status="ok",
task=task,
message="解析内容已确认,请继续选择正式库存源。",
data={
**serialize_task_for_tool(task),
"inventory_source_candidates": adjudication.candidates,
"inventory_source_status": adjudication.status,
"inventory_source_reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
},
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
if not task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.parse_confirmed_running", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_OK,
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
return tool_response(
status="ok",
task=task,
message=t("workflow.decision.parse_confirmed_next", lang=lang),
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_OK,
next_required_action=t("workflow.decision.parse_confirmed_wait", lang=lang),
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
if match_completed(task):
apply_task_transition(task, TaskTransition.CONFIRM_MATCHED)
after_snapshot = task_lifecycle_audit_snapshot(task)
log_task_action_event(
task,
"decision_confirmed",
action="confirm",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=after_snapshot,
)
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
record_fulfillment_audit(
event_type='task_decision',
aggregate_type='shipping_task',
aggregate_id=task.task_no,
action='confirm_matched',
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=task.task_no,
conversation_id=task.conversation_id,
before=before_snapshot,
after=after_snapshot,
metadata={'decision': decision},
source=event_source,
)
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=t("workflow.decision.matched_confirmed", lang=lang),
data=serialize_task_for_tool(task),
)
if task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.inventory_preparing", lang=lang),
data=serialize_task_for_tool(task),
)
if task.inventory_lines_json:
orchestrator_started = start_task_orchestrator(task.task_no)
return tool_response(
status="running" if orchestrator_started else "ok",
task=task,
message=t("workflow.decision.fulfillment_running", lang=lang),
data=serialize_task_for_tool(task),
)
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.confirm_invalid_state", lang=lang),
data=serialize_task_for_tool(task),
)
# [STEP 3] 处理重算型决策。
# retry_rpa / rematch 都是在当前任务基础上回退或重放局部链路,
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
if decision == "retry_rpa":
_reset_inventory_state_for_forced_rpa(task)
log_task_event(
task,
"decision_retry_rpa",
{"comment": comment, "force_refresh": True},
actor_id=actor_id,
source=event_source,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
db.session.flush()
return _request_formal_gate_action(
task=task,
action_code='retry_inventory_preparation',
user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0),
idempotency_key=str(payload.get('idempotency_key') or f'decision-retry-rpa:{task.task_no}:{task.order_data_version}'),
trigger=event_source,
)
if decision == "rematch":
apply_task_transition(task, TaskTransition.REMATCH_REQUESTED)
task.match_status = None
task.shortage_json = None
task.line_results_json = None
log_task_action_event(
task,
"decision_rematch",
action="rematch",
source=event_source,
comment=comment,
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
# flush 即可:状态清理与正式 Gate Action 入队同属一次连续写入,避免中间态落库。
db.session.flush()
return _request_formal_gate_action(
task=task,
action_code='retry_inventory_from_matching',
user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0),
idempotency_key=str(payload.get('idempotency_key') or f'decision-rematch:{task.task_no}:{task.order_data_version}'),
trigger=event_source,
)
# [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。
if decision == "reparse":
candidate = (
db.session.get(ShippingOrderCandidate, int(task.source_candidate_id))
if task.source_candidate_id else None
)
source_run_id = candidate.order_extraction_run_id if candidate is not None else None
if source_run_id:
from app.services.shipping_notice.order_extraction_run_service import reparse_order_extraction_run
run = db.session.get(ShippingOrderProcessingRun, source_run_id)
if run is not None:
replacement, reused = reparse_order_extraction_run(
user_id=int(task.user_id), run_no=run.run_no, reason="other", comment=comment or None,
)
log_task_action_event(
task, "notice_reparse_requested", action="reparse", source=event_source, comment=comment,
extra={"source_run_no": run.run_no, "replacement_run_no": replacement.run_no, "reused": reused},
actor_id=actor_id,
before=before_snapshot,
after=task_lifecycle_audit_snapshot(task),
)
db.session.commit()
return tool_response(
status="needs_human", task=task,
message="已使用当前发布规则重新识别原始发货通知,请等待新版结果后审核。",
data={**serialize_task_for_tool(task), "order_extraction_run_no": replacement.run_no},
checkpoint=task.review_status or "parse_review", stop_agent_turn=True,
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
)
return tool_response(
status="needs_human",
task=task,
message="当前任务无法追溯到可重新识别的原始 Run,请重新上传发货通知。",
data=serialize_task_for_tool(task),
checkpoint=task.review_status or "parse_review",
stop_agent_turn=True,
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
)
return tool_response(
status="failed",
task_id=task.task_no,
message=t("workflow.decision.unknown", lang=lang).format(decision=decision),
)
@@ -13,18 +13,18 @@ from __future__ import annotations
from datetime import datetime
from typing import Any
from app.models import ShippingNotice, ShippingTemporaryInventorySession
from app.models import ShippingOrderTask, ShippingTemporaryInventorySession
from app.services.agent_runtime_context.builder import serialize_for_dify
from app.services.agent_runtime_context.schema import AGENT_RUNTIME_CONTEXT_INPUT
from app.services.shipping_notice.runtime_context import build_shipping_runtime_context
def _task_by_task_no(task_id: str) -> ShippingNotice | None:
def _task_by_task_no(task_id: str) -> ShippingOrderTask | None:
"""按显式 task_id 获取任务;禁止按会话号猜测当前任务。"""
normalized = str(task_id or "").strip().upper()
if not normalized:
return None
return ShippingNotice.query.filter_by(task_no=normalized).first()
return ShippingOrderTask.query.filter_by(task_no=normalized).first()
def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | None:
@@ -56,7 +56,7 @@ def _latest_pending_temporary_inventory_session(conversation_id: str) -> str | N
return str(item.session_no or '').strip().upper() or None if item else None
def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -> ShippingNotice | None:
def _focus_task_row(focus_task: str, explicit_task_row: ShippingOrderTask | None) -> ShippingOrderTask | None:
"""
解析当前显式焦点任务行。
@@ -74,7 +74,7 @@ def _focus_task_row(focus_task: str, explicit_task_row: ShippingNotice | None) -
return None
if explicit_task_row and str(explicit_task_row.task_no or "").strip().upper() == normalized:
return explicit_task_row
return ShippingNotice.query.filter_by(task_no=normalized).first()
return ShippingOrderTask.query.filter_by(task_no=normalized).first()
def build_dify_chat_inputs(
@@ -177,6 +177,7 @@ def reconstruct_coordinate_profile_rows_with_strategy(
dynamic_rows = reconstruct_coordinate_profile_rows(
characters=characters, table_bbox=table_bbox, line_layouts=line_layouts,
table_region=table_region, termination_rules=termination_rules,
# dynamic 不执行普通排除过滤,但其专用排除区仍授权删除标记。
exclusion_regions=dynamic_exclusion_regions or [], line_start_field_code=line_start_field_code,
include_deleted=include_deleted, row_reconstruction_mode='dynamic_x_columns',
schema_field_metadata=schema_field_metadata, initial_fields=initial_fields,
@@ -567,6 +568,7 @@ def reconstruct_coordinate_profile_rows(
_absolute_relative_region(bbox, item)
for item in (exclusion_regions or []) if isinstance(item, dict)
]
marker_authorization_exclusions = exclusions
# 直接调用动态候选时,传入的旧式排除区无法区分表头/普通排除;为兼容其
# “表头可移动”语义不应用它。统一入口则显式传入 dynamic_exclusion_regions,
# 从而保留管理员配置的普通排除区。
@@ -583,10 +585,10 @@ def reconstruct_coordinate_profile_rows(
continue
band_indices = {glyph_index for glyph_index, _glyph in band}
marker_indices.update(band_indices)
if exclusions and any(
if marker_authorization_exclusions and any(
_inside_region(glyph.bbox, region)
for _glyph_index, glyph in band
for region in exclusions
for region in marker_authorization_exclusions
):
authorized_marker_indices.update(band_indices)
# [STEP 2] 普通排除区内容与未授权删除文字都不参与字段重建;已授权删除标记保留到行状态判定。
@@ -604,7 +606,8 @@ def reconstruct_coordinate_profile_rows(
# This mode is opt-in per table region. It supports documents whose stable
# columns stay put while optional descriptions move values across visual rows.
if row_reconstruction_mode == 'dynamic_x_columns':
return _reconstruct_dynamic_x_columns_profile_rows(
return _resolve_shifted_part_number_candidates(
rows=_reconstruct_dynamic_x_columns_profile_rows(
glyphs=glyphs,
table_bbox=bbox,
ordered_layouts=ordered_layouts,
@@ -612,9 +615,13 @@ def reconstruct_coordinate_profile_rows(
include_deleted=include_deleted,
line_start_field_code=start_field_code,
schema_fields=schema_fields,
),
glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
if row_reconstruction_mode == 'adaptive_record_columns':
return _reconstruct_adaptive_record_columns_profile_rows(
return _resolve_shifted_part_number_candidates(
rows=_reconstruct_adaptive_record_columns_profile_rows(
glyphs=glyphs,
table_bbox=bbox,
ordered_layouts=ordered_layouts,
@@ -622,6 +629,9 @@ def reconstruct_coordinate_profile_rows(
include_deleted=include_deleted,
line_start_field_code=start_field_code,
schema_fields=schema_fields,
),
glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
relative_y_rows = _reconstruct_relative_y_profile_rows(
@@ -636,7 +646,10 @@ def reconstruct_coordinate_profile_rows(
schema_fields=schema_fields,
)
if relative_y_rows is not None:
return relative_y_rows
return _resolve_shifted_part_number_candidates(
rows=relative_y_rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
def values_for(
band: list[tuple[int, PositionedCharacter]], layout: dict[str, Any],
@@ -730,7 +743,11 @@ def reconstruct_coordinate_profile_rows(
current_issues.extend(continuation_issues)
next_offset += 1
flush()
return results if include_deleted else [row for row in results if row.role != 'deleted']
rows = results if include_deleted else [row for row in results if row.role != 'deleted']
return _resolve_shifted_part_number_candidates(
rows=rows, glyphs=glyphs, ordered_layouts=ordered_layouts, table_bbox=bbox,
line_start_field_code=start_field_code,
)
def _project_coordinate_profile_regions(
@@ -960,12 +977,23 @@ def _reconstruct_dynamic_x_columns_profile_rows(
delta_y = (anchor_box.y0 + anchor_box.y1) / 2 - expected_anchor_center
values: dict[str, str] = {}
issues: list[str] = []
deleted = any(
_DELETED_PATTERN.fullmatch(re.sub(
r'\s+', '', ''.join(
glyph.text for _, glyph in sorted(band, key=lambda item: item[1].bbox.x0)
),
))
for _row_index, band in record
)
for field in fields:
code = str(field['field_code'])
saved = _absolute_relative_region(table_bbox, field['region'])
# [STEP 3] 整体上移可把宽字段框推过页面顶端;截断页外部分,
# 保持 LayoutBBox 的非负原点和正面积契约。
shifted_y0 = max(0.0, saved.y0 + delta_y)
region = LayoutBBox(
x0=saved.x0, y0=saved.y0 + delta_y,
x1=saved.x1, y1=saved.y1 + delta_y,
x0=saved.x0, y0=shifted_y0,
x1=saved.x1, y1=max(shifted_y0 + 1e-6, saved.y1 + delta_y),
)
selected_bands = [
band for _row_index, band in record
@@ -990,7 +1018,7 @@ def _reconstruct_dynamic_x_columns_profile_rows(
results.append(CoordinateProfileLogicalRow(
fields=values,
source_row_indices=[row_index for row_index, _band in record],
role='data', issues=issues,
role='deleted' if deleted else 'data', issues=issues,
))
return results if include_deleted else [row for row in results if row.role != 'deleted']
@@ -1157,6 +1185,19 @@ def _reconstruct_relative_y_profile_rows(
start_region = _absolute_relative_region(table_bbox, start_field['region'])
expected_anchor_center = (start_region.y0 + start_region.y1) / 2
results: list[CoordinateProfileLogicalRow] = []
sample_record = usable_bands[anchors[0]:anchors[1] if len(anchors) > 1 else len(usable_bands)]
expected_indices = _calibrate_field_band_indices(
fields=fields, sample_record=sample_record, table_bbox=table_bbox,
)
multiline_fields = {
id(field) for field in fields
if sum(
_regions_overlap_vertically(
_absolute_relative_region(table_bbox, field['region']), _band_bbox(band),
)
for _row_index, band in sample_record
) > 1
}
for anchor_index, start in enumerate(anchors):
end = anchors[anchor_index + 1] if anchor_index + 1 < len(anchors) else len(usable_bands)
record = usable_bands[start:end]
@@ -1176,23 +1217,56 @@ def _reconstruct_relative_y_profile_rows(
x0=saved.x0, y0=saved.y0 + delta_y,
x1=saved.x1, y1=saved.y1 + delta_y,
)
# A visual field box may intentionally span multiple PDF text lines
# (for example a wrapped customer part number). The previous
# one-band assignment treated that as an ambiguity and dropped the
# field, which caused two vertically stacked part-number fields to
# become empty or reuse the same prefix. When the configured field
# region intersects multiple bands, read all of its own glyphs;
# single-band fields retain the calibrated matching behavior.
intersecting = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
if not intersecting:
continue
raw = _text_in_multiline_region(
intersecting, region,
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
)
if id(field) not in multiline_fields:
intersecting = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
raw = _text_in_horizontal_region(intersecting[0], region) if intersecting else ''
if code == 'part_number':
expected_index = expected_indices.get(id(field), 0)
candidates: list[tuple[float, int, str]] = []
for candidate_index in range(expected_index, len(record)):
candidate_raw = _text_in_horizontal_region(record[candidate_index][1], region)
if _is_structured_part_identifier(candidate_raw):
compact_candidate = re.sub(r'\s+', '', candidate_raw)
candidates.append((
_profile_field_band_score(
raw=candidate_raw, field_code=code,
extractor_key=str(field.get('extractor_key') or 'direct'),
),
candidate_index, candidate_raw,
))
if re.search(r'\d', compact_candidate):
candidates[-1] = (candidates[-1][0] + .5, *candidates[-1][1:])
candidates.sort(key=lambda item: (-item[0], item[1]))
if len(candidates) == 1:
raw = candidates[0][2]
elif len(candidates) > 1:
best = candidates[0]
if best[0] > candidates[1][0] + .25:
raw = best[2]
else:
issues.append(f'coordinate_profile_field_band_ambiguous:{code}')
raw = ''
else:
# A visual field box may intentionally span multiple PDF text lines
# (for example a wrapped customer part number). The previous
# one-band assignment treated that as an ambiguity and dropped the
# field, which caused two vertically stacked part-number fields to
# become empty or reuse the same prefix. When the configured field
# region intersects multiple bands, read all of its own glyphs;
# single-band fields retain the calibrated matching behavior.
intersecting = [
band for _row_index, band in record
if _regions_overlap_vertically(region, _band_bbox(band))
]
if not intersecting:
continue
raw = _text_in_multiline_region(
intersecting, region,
compact=code in {'part_number', 'customer_part_number', 'aws_part_number'},
)
if not raw:
continue
extracted = extract_profile_field_value(
@@ -1890,6 +1964,137 @@ def _profile_field_band_score(*, raw: str, field_code: str, extractor_key: str)
return score
def _is_structured_part_identifier(raw: str) -> bool:
"""
判断文本是否可作为内部料号纠偏证据。
核心逻辑:去首尾空白后仍须是无空格的紧凑标识(字母数字 + ._:/-),且含数字或
连接符;含空格的贸易条款/描述串一律拒绝,避免去空格后误匹配。
Args:
raw: 候选原文。
Returns:
True 表示可作为 structured 料号证据。
"""
value = str(raw or '').strip()
if not value or re.search(r'\s', value):
return False
return bool(
not re.match(r'^(?:revision|rev):', value, re.IGNORECASE)
and re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._:/-]{2,}', value)
and re.search(r'\d|[._:/-]', value)
)
def _resolve_shifted_part_number_candidates(
*, rows: list[CoordinateProfileLogicalRow],
glyphs: list[tuple[int, PositionedCharacter]],
ordered_layouts: list[dict[str, Any]],
table_bbox: LayoutBBox,
line_start_field_code: str,
) -> list[CoordinateProfileLogicalRow]:
"""
在多子行模板中跳过描述折行,裁决后续唯一结构化内部料号。
核心逻辑:仅当当前位置读到的值不是 structured 料号(多为描述折行)时,才扫描
后续视觉行;唯一高置信候选可替换,多候选则 Review。当前位置已是 structured
时保持原值,禁止被后续条款行无条件覆盖。
Args:
rows: 三种重建模式产出的逻辑明细。
glyphs: 表区内带索引的字符。
ordered_layouts: 按 row_offset 排序的子行布局。
table_bbox: 重建坐标系下的表/页框。
line_start_field_code: 起行锚点字段编码。
Returns:
纠偏后的逻辑明细列表(原地更新 fields/issues)。
"""
part_fields = [
field for layout in ordered_layouts
for field in (layout.get('field_regions') or [])
if isinstance(field, dict) and str(field.get('field_code') or '') == 'part_number'
and isinstance(field.get('region'), dict)
]
if not part_fields:
return rows
part_start_offset = min(
offset for offset, layout in enumerate(ordered_layouts)
if any(field in (layout.get('field_regions') or []) for field in part_fields)
)
# 主行内的料号没有“预期下一子行”这一语义。只纠正被标在后续子行的字段,
# 避免跨到价格、日期或表尾文本中寻找候选,保持已有单行模板的解析边界。
if part_start_offset == 0:
return rows
bands = _group_visual_rows(glyphs)
main_fields = ordered_layouts[0].get('field_regions') or []
start_field = next(
(
field for field in main_fields
if isinstance(field, dict)
and str(field.get('field_code') or '') == line_start_field_code
and isinstance(field.get('region'), dict)
),
None,
)
start_region = (
_absolute_relative_region(table_bbox, start_field['region'])
if start_field is not None else None
)
for row_position, row in enumerate(rows):
current = str(row.fields.get('part_number') or '').strip()
if not current or not row.source_row_indices:
continue
# 当前位置已是结构化料号:纠偏只服务描述折行,不得再扫后续条款行覆盖。
if _is_structured_part_identifier(current):
continue
record_start = min(row.source_row_indices)
record_end = (
min(min(next_row.source_row_indices) for next_row in rows[row_position + 1:])
if row_position + 1 < len(rows) else len(bands)
)
candidates: list[tuple[float, int, str]] = []
# 从该记录中 part_number 的预期子行开始重扫;当前值本身若只是折行描述,
# 会被跳过,后续唯一结构化候选才可替换。不能按 source_row_indices 末端起步,
# 因为自适应重建可能已把后续候选 band 一并吸收到当前行。
expected_index = record_start + part_start_offset
scan_start = expected_index
for index in range(scan_start, record_end):
# 末条记录也必须以视觉上的下一起行锚点截断;后续解析策略可能因
# 表尾规则不产出该行,但不能让它泄漏进当前记录的料号候选池。
if index > record_start and start_region is not None:
start_raw = _text_in_horizontal_region(bands[index], start_region)
if is_valid_line_start_value(start_raw):
break
for field in part_fields:
region = _absolute_relative_region(table_bbox, field['region'])
raw = _text_in_horizontal_region(bands[index], region)
if raw.strip() == current:
continue
if not _is_structured_part_identifier(raw):
continue
score = _profile_field_band_score(
raw=raw, field_code='part_number',
extractor_key=str(field.get('extractor_key') or 'direct'),
)
score -= abs(index - expected_index) * .5
if re.search(r'\d', re.sub(r'\s+', '', raw)):
score += .5
candidates.append((score, index, raw))
candidates.sort(key=lambda item: (-item[0], item[1]))
if len(candidates) == 1:
row.fields['part_number'] = candidates[0][2]
elif len(candidates) > 1:
if candidates[0][0] > candidates[1][0] + .25:
row.fields['part_number'] = candidates[0][2]
else:
row.fields.pop('part_number', None)
row.issues.append('coordinate_profile_field_band_ambiguous:part_number')
return rows
def _text_in_region(
band: list[tuple[int, PositionedCharacter]], region: LayoutBBox,
) -> str:
@@ -380,6 +380,8 @@ def base_split_content_fingerprint(rule_set: BaseSplitRuleSet | dict[str, Any])
segment.pop('handling', None)
segment.pop('target_field_id', None)
segment.pop('target_field_code', None)
# segment_id 是段记录标识而非拆分逻辑(matcher/normalization/relation),不得进入内容指纹。
segment.pop('segment_id', None)
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
@@ -464,10 +464,13 @@ def _map_data_row(
if _is_repeated_header(grid, row_index=row_index, columns=columns, contract=contract):
return HtmlMappedRow(row_index=row_index, role='repeated_header')
joined = ' '.join(normalized)
if 'item deleted' in joined or 'deleted item' in joined or '项目已删除' in joined or '項目已刪除' in joined:
# 删除标记是业务内容关键词,不区分大小写;normalize_table_header 保留表头大小写。
marker_joined = joined.lower()
if 'item deleted' in marker_joined or 'deleted item' in marker_joined or '项目已删除' in joined or '項目已刪除' in joined:
return HtmlMappedRow(row_index=row_index, role='deleted')
first = next((item for item in normalized if item), '')
if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first):
# 合计标记同样是业务内容关键词,按小写匹配 'Total'/'TOTAL'/'Subtotal' 等常见大小写。
if re.fullmatch(r'(grand )?(sub ?)?total|合计|合計|总计|總計', first.lower()):
return HtmlMappedRow(row_index=row_index, role='summary')
if _has_explicit_zero_quantity(row, columns=columns):
return HtmlMappedRow(row_index=row_index, role='deleted')
@@ -581,7 +584,8 @@ def _is_exclusive_deletion_marker_row(grid: HtmlGrid, row_index: int) -> bool:
if not texts:
return False
markers = {'item deleted', 'deleted item', '项目已删除', '項目已刪除'}
return all(text in markers for text in texts)
# 删除标记占整行的内容为业务关键词,按小写匹配,避免大小写差异漏判。
return all(text.lower() in markers for text in texts)
def _header_candidates(grid: HtmlGrid, *, row_index: int, column_index: int) -> list[str]:
@@ -5,7 +5,7 @@ backend/app/services/shipping_notice/document_layout/order_profile.py
依赖:Pydantic、坐标 bbox 契约、订单字段规则和已注册解析器。
逻辑:管理员保存稳定锚点、相对区域和 field_code 绑定;order_profile_matcher 消费
DocumentMatchProfile 分项权重与 negative_anchors;order_profile_signature 生成
matching_signature 供运行时硬门禁与维度比对。
matching_signature 供运行时硬门禁与维度比对。自动决胜 critical 仅 header+column。
"""
from __future__ import annotations
@@ -329,10 +329,10 @@ SCORING_DIMENSION_KEYS = (
'optional_static_text',
'trusted_business_context',
)
# table_geometry 保留为软分;MinerU 脏高度不得作为自动决胜硬门禁。
CRITICAL_STRUCTURE_DIMENSION_KEYS = (
'header_semantic_position',
'column_topology',
'table_geometry',
)
# 历史 v1 权重键 → v2 键;供 model_validator 迁移旧模板配置。
_LEGACY_SCORING_WEIGHT_KEYS: dict[str, str] = {
@@ -32,6 +32,10 @@ def extract_profile_field_value(*, extractor_key: str, field_code: str, raw: str
if field_code == 'reservation_id':
value = validated_reservation_id(text)
return {field_code: value} if value else {}
if field_code == 'uom':
# 单位剔除数字(如 '0 PCS' → 'PCS'),避免相邻数量字段数字串入单位。
stripped = re.sub(r'\d+', '', text).strip()
return {field_code: stripped} if stripped else {}
return {field_code: text}
if extractor_key == 'temp_internal_parts':
resolved = resolve_composite_part_numbers(text)
@@ -4,7 +4,9 @@ services/shipping_notice/document_layout/order_profile_matcher.py
用途:以冻结版面签名与坐标证据唯一匹配订单坐标模板,按统一七维权重做确定性综合评分。
依赖:OrderCoordinateProfile、order_profile_signature.MATCHER_POLICY_ID、coordinate_region_text。
逻辑:硬门禁(签名/必选锚点/排除锚点)→ 三态维度比对 → evidence_coverage 与相似度决胜;
页存在≠page_structure 命中;line_layout 存在≠结构匹配;缺失锚点/客户提示不得满分。
table_geometry 只比顶边/宽度(忽略 MinerU 脏 y1);critical 仅 header+column;
主表业务行裁剪只消费模板 termination_rules/exclusion_regions,无硬编码结束词表;
无必选锚点的近亲模板才用表头原子硬互斥;已配置 required_anchors 时身份交给锚点门禁。
"""
from __future__ import annotations
@@ -34,6 +36,7 @@ from app.services.shipping_notice.document_layout.order_profile import (
)
from app.services.shipping_notice.document_layout.order_profile_signature import (
MATCHER_POLICY_ID,
clip_table_bbox_to_business_rows,
signature_checksum,
)
@@ -167,6 +170,8 @@ def match_frozen_coordinate_profiles(
observed = _observe_layout_features(
layout=layout, tables=tables, pages=pages, glyph_tables=glyph_tables,
page_glyphs=page_glyphs, signature=observed_signature,
termination_rules=_profile_termination_rules(profile),
exclusion_regions=_profile_exclusion_regions(profile),
)
if signature_body is None:
reason_codes.append('profile_signature_missing')
@@ -882,11 +887,20 @@ def _compute_dimension_results(
results: dict[str, MatchDimensionResult] = {}
# [STEP 1] header_semantic_position:表头语义和位置必须独立于锚点硬门禁。
# 有 required_anchors 时不做表头原子硬互斥——唯一身份由锚点承担,避免噪声表头误杀。
enforce_header_atoms = _should_enforce_header_atom_discriminator(required_hits)
header_result = _score_header_semantic_position(
signature=signature, observed=observed, required_hits=required_hits,
enforce_atom_discriminator=enforce_header_atoms,
)
results['header_semantic_position'] = header_result
if (
enforce_header_atoms
and header_result.state == 'mismatched'
and _header_discriminator_atoms_conflict(signature=signature, observed=observed)
):
hard_conflicts.append('profile_header_discriminator_conflict')
elif (
header_result.state == 'mismatched'
and signature
and signature.get('table_patterns')
@@ -926,13 +940,27 @@ def _compute_dimension_results(
return results, hard_conflicts
def _should_enforce_header_atom_discriminator(required_hits: list[bool]) -> bool:
"""
判断是否启用表头原子硬互斥。
核心逻辑:模板若已配置必选锚点,身份由锚点门禁承担,不再用表头原子硬杀;
仅「无必选锚点」的近亲模板才启用原子互斥。
"""
return not required_hits
def _score_header_semantic_position(
*,
signature: dict[str, Any] | None,
observed: dict[str, Any],
required_hits: list[bool],
enforce_atom_discriminator: bool = True,
) -> MatchDimensionResult:
"""比对真实表头 token、横向顺序和位置;锚点命中不替代表头结构证据。"""
"""比对真实表头 token、横向顺序和位置。
核心逻辑:无必选锚点时先做表头原子硬互斥;有必选锚点则只走软评分。
"""
if signature is None:
return MatchDimensionResult(state='unavailable', score=0.0)
expected_tokens: list[str] = []
@@ -951,6 +979,11 @@ def _score_header_semantic_position(
)
if not observed_tokens:
return MatchDimensionResult(state='unavailable', score=0.0)
if (
enforce_atom_discriminator
and _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens)
):
return MatchDimensionResult(state='mismatched', score=0.0)
matched = sum(1 for token in expected_tokens if token in observed_tokens)
token_ratio = matched / len(expected_tokens)
expected_order = [str(item).casefold() for table in signature.get('table_patterns') or [] if isinstance(table, dict) for item in table.get('header_order') or []]
@@ -971,6 +1004,43 @@ def _score_header_semantic_position(
)
_HEADER_ATOM_STOPWORDS = frozenset({'and', 'the', 'of', 'or', 'to', 'for', 'with', 'by'})
_HEADER_ATOM_MIN_LEN = 3
def _header_token_atoms(tokens: list[str]) -> frozenset[str]:
"""
将表头 token 拆成稳定原子,供无锚点近亲模板互斥。
核心逻辑:去撇号后按非字母数字切分;过滤过短词与虚词,避免 Q'TY/No. 噪声。
"""
atoms: set[str] = set()
for token in tokens:
normalized = re.sub(r"['’]", '', str(token).casefold())
for part in re.split(r'[^a-z0-9]+', normalized):
if len(part) >= _HEADER_ATOM_MIN_LEN and part not in _HEADER_ATOM_STOPWORDS:
atoms.add(part)
return frozenset(atoms)
def _header_discriminator_atoms_conflict(
*,
signature: dict[str, Any] | None,
observed: dict[str, Any],
) -> bool:
"""签名与观测表头原子集合不一致时视为互斥冲突(仅无必选锚点路径调用)。"""
if signature is None or not signature.get('table_patterns'):
return False
expected_tokens: list[str] = []
for table in signature.get('table_patterns') or []:
if isinstance(table, dict):
expected_tokens.extend(str(item) for item in table.get('header_tokens') or [])
observed_tokens = [str(item) for item in observed.get('header_tokens') or []]
if not expected_tokens or not observed_tokens:
return False
return _header_token_atoms(expected_tokens) != _header_token_atoms(observed_tokens)
def _score_column_topology(
*,
signature: dict[str, Any] | None,
@@ -1025,7 +1095,8 @@ def _score_table_geometry(
observed: dict[str, Any],
profile: OrderCoordinateProfile,
) -> MatchDimensionResult:
"""比对表区 bbox 中位数与容差。"""
"""比对主表身份几何:顶边与左右宽度;忽略底边高度(MinerU 粘连备注会拉高 y1)。"""
_ = profile
if signature is None:
return MatchDimensionResult(state='unavailable', score=0.0)
patterns = [item for item in signature.get('table_patterns') or [] if isinstance(item, dict)]
@@ -1045,11 +1116,30 @@ def _score_table_geometry(
if isinstance(tolerance, list) and len(tolerance) == 4
else [float(tolerance[0]) if isinstance(tolerance, list) and tolerance else 0.05] * 4
)
best = max(best, _bbox_similarity(median, reference_bbox, tolerances=tolerances))
best = max(
best,
_identity_table_geometry_similarity(
median, reference_bbox, tolerances=tolerances,
),
)
score = round(best, 6)
return MatchDimensionResult(state='matched' if score >= 0.65 else 'mismatched', score=score)
def _identity_table_geometry_similarity(
expected: list[float], observed: list[float], *, tolerances: list[float],
) -> float:
"""只比较 x0/y0/x1(顶边+宽度);y1 不参与身份分,避免脏表高绑架模板匹配。"""
# indices: 0=x0, 1=y0, 2=x1, 3=y1(忽略)
identity_indices = (0, 1, 2)
hits = 0
for index in identity_indices:
tolerance = float(tolerances[index]) if index < len(tolerances) else 0.05
if abs(float(expected[index]) - float(observed[index])) <= tolerance:
hits += 1
return round(hits / len(identity_indices), 6)
def _score_page_structure(
*,
signature: dict[str, Any] | None,
@@ -1140,15 +1230,6 @@ def _score_trusted_business_context(
)
def _bbox_similarity(expected: list[float], observed: list[float], *, tolerances: list[float]) -> float:
"""分别使用 x0/y0/x1/y1 容差评估表区几何。"""
deltas = [abs(float(a) - float(b)) for a, b in zip(expected, observed)]
if not deltas:
return 0.0
within = sum(1 for delta, tolerance in zip(deltas, tolerances) if delta <= tolerance)
return round(within / len(deltas), 6)
def _observe_layout_features(
*,
layout: dict[str, Any],
@@ -1157,6 +1238,8 @@ def _observe_layout_features(
glyph_tables: dict[str, Any],
page_glyphs: dict[str, Any],
signature: dict[str, Any] | None,
termination_rules: list[dict[str, Any]] | None = None,
exclusion_regions: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
"""从冻结 layout 聚合非敏感结构特征供维度比对。"""
persisted = layout.get('matching_features')
@@ -1183,6 +1266,16 @@ def _observe_layout_features(
primary_bbox = _select_signature_primary_table_bbox(
tables=tables, pages=pages, signature=signature,
)
# [STEP 1b] 业务行裁剪:仅按模板 termination/exclusion 截断粘连高度。
primary_bbox = _clip_observed_primary_table_bbox(
primary_bbox,
tables=tables,
pages=pages,
page_glyphs=page_glyphs,
signature=signature,
termination_rules=termination_rules,
exclusion_regions=exclusion_regions,
)
header_tokens, column_centers, column_width_ratios = _observe_primary_table_header(
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
@@ -1371,6 +1464,96 @@ def _select_signature_primary_table_bbox(
return best_bbox
def _clip_observed_primary_table_bbox(
primary_bbox: list[float] | None,
*,
tables: list[dict[str, Any]],
pages: dict[str, Any],
page_glyphs: dict[str, Any],
signature: dict[str, Any] | None,
termination_rules: list[dict[str, Any]] | None = None,
exclusion_regions: list[dict[str, Any]] | None = None,
) -> list[float] | None:
"""对运行时主表框做业务行裁剪;无模板终止声明或定位失败时 fail-open。"""
if not isinstance(primary_bbox, list) or len(primary_bbox) != 4:
return primary_bbox
page_no, page = _page_for_primary_table_bbox(
primary_bbox, tables=tables, pages=pages,
)
if not isinstance(page, dict):
return primary_bbox
glyphs = page_glyphs.get(str(page_no)) or page_glyphs.get(page_no) or []
header_y1 = None
for pattern in (signature or {}).get('table_patterns') or []:
if not isinstance(pattern, dict):
continue
header_bbox = pattern.get('header_bbox')
if isinstance(header_bbox, list) and len(header_bbox) == 4:
try:
header_y1 = float(header_bbox[3])
except (TypeError, ValueError):
header_y1 = None
break
clipped = clip_table_bbox_to_business_rows(
primary_bbox,
page=page,
glyphs=glyphs if isinstance(glyphs, list) else None,
header_y1=header_y1,
termination_rules=termination_rules,
exclusion_regions=exclusion_regions,
)
return clipped if isinstance(clipped, list) else primary_bbox
def _profile_termination_rules(profile: OrderCoordinateProfile) -> list[dict[str, Any]]:
"""汇总模板全部表区的终止规则,供主表几何裁剪复用抽取侧契约。"""
return [
rule.model_dump()
for table in profile.table_regions
for rule in table.termination_rules
]
def _profile_exclusion_regions(profile: OrderCoordinateProfile) -> list[dict[str, Any]]:
"""汇总模板全部表区的排除框。"""
return [
region.model_dump()
for table in profile.table_regions
for region in table.exclusion_regions
]
def _page_for_primary_table_bbox(
primary_bbox: list[float],
*,
tables: list[dict[str, Any]],
pages: dict[str, Any],
) -> tuple[Any, dict[str, Any] | None]:
"""按与主表框重叠最大的 layout 表定位页对象。"""
best: tuple[float, Any, dict[str, Any]] | None = None
for table in tables:
page_no = table.get('page_no') or 1
page = pages.get(str(page_no)) or pages.get(page_no)
bbox = table.get('bbox') if isinstance(table.get('bbox'), dict) else None
if not isinstance(page, dict) or not isinstance(bbox, dict):
continue
try:
raw = [float(bbox[key]) for key in ('x0', 'y0', 'x1', 'y1')]
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
except (KeyError, TypeError, ValueError):
continue
if width <= 0 or height <= 0 or raw[2] <= raw[0] or raw[3] <= raw[1]:
continue
normalized = raw if max(raw) <= 1 else [raw[0] / width, raw[1] / height, raw[2] / width, raw[3] / height]
overlap = _bbox_overlap(primary_bbox, normalized)
if best is None or overlap > best[0]:
best = (overlap, page_no, page)
if best is None:
fallback = pages.get('1') or pages.get(1)
return 1, fallback if isinstance(fallback, dict) else None
return best[1], best[2]
def _bbox_overlap(left: list[float], right: list[float]) -> float:
"""计算两个归一化矩形的 IoU,供签名表区与实际表选择使用。"""
x0, y0 = max(left[0], right[0]), max(left[1], right[1])
@@ -1383,6 +1566,28 @@ def _bbox_overlap(left: list[float], right: list[float]) -> float:
_HEADER_TOKEN_SPLIT = re.compile(r'[\s|/]+')
def _band_headers_match_signature(
*, band_tokens: list[str], signature: dict[str, Any] | None,
) -> bool:
"""判断冻结表头带读到的 token 是否足以代表签名表头。
只有当固定带读到的表头 token 与签名 header_tokens 覆盖达到阈值时才视为“带仍有效”,
直接沿用;否则(表体因上方内容折行/加行而上移或下移,固定带读空或读到错误行)
需要回退到表体顶部的结构搜索。
"""
expected = [
str(token).casefold()
for pattern in (signature or {}).get('table_patterns') or []
if isinstance(pattern, dict)
for token in pattern.get('header_tokens') or []
]
if not expected or not band_tokens:
return False
observed = [str(token).casefold() for token in band_tokens]
matched = sum(1 for token in expected if token in observed)
return matched / len(expected) >= 0.5
def _observe_primary_table_header(
*,
glyph_tables: dict[str, Any],
@@ -1391,7 +1596,13 @@ def _observe_primary_table_header(
primary_bbox: list[float] | None,
signature: dict[str, Any] | None,
) -> tuple[list[str], list[float], list[float]]:
"""仅从实际主表 bbox 顶部观测表头,与签名生成保持同一证据口径。"""
"""从实际主表顶部观测表头,与签名生成保持同一证据口径。
先读模板冻结的表头带;若该带仍能读出与签名一致的表头 token,则直接沿用(保持既有行为,
不影响正常模板)。若固定带失准(表体因上方内容折行/加行而上移或下移,带读空或读到
错误行),则基于已定位表体顶部做表头行搜索(与压缩快照路径一致的候选行选择逻辑),
从而对上移/下移/任意行数位移都健壮,且不依赖上方可变内容。
"""
if not primary_bbox or len(primary_bbox) != 4:
return [], [], []
glyphs = page_glyphs.get('1') or page_glyphs.get(1)
@@ -1419,11 +1630,28 @@ def _observe_primary_table_header(
item for item in positioned_token_spans(header_glyphs, respect_explicit_spaces=False)
if _usable_observed_header_token(str(item.get('text') or ''))
][:32]
tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
band_tokens = [' '.join(str(item['text']).split())[:80].casefold() for item in spans]
band_centers = [round((float(item['x0']) + float(item['x1'])) / 2 / width, 4) for item in spans]
table_span = max(primary_bbox[2] - primary_bbox[0], 0.0001)
widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
return tokens, centers, widths
band_widths = [round((float(item['x1']) - float(item['x0'])) / width / table_span, 4) for item in spans]
# 固定带有效 → 直接沿用(对正常模板零影响)。
if _band_headers_match_signature(band_tokens=band_tokens, signature=signature):
return band_tokens, band_centers, band_widths
# 固定带失准(位移场景)→ 基于已定位表体顶部做表头行搜索,选与签名最匹配的一行。
candidates = [{
'bbox': primary_bbox,
'header_candidates': _observe_header_candidates(
glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages, primary_bbox=primary_bbox,
),
}]
selected = _select_persisted_header_candidate(candidates=candidates, signature=signature)
if selected is not None:
header, _ = selected
return (
[str(token).casefold() for token in header['header_tokens']],
header['column_centers'], header['column_width_ratios'],
)
return band_tokens, band_centers, band_widths
def _signature_header_bbox(signature: dict[str, Any] | None) -> list[float] | None:
@@ -14,6 +14,15 @@ from typing import Any
from app.services.shipping_notice.document_layout.coordinate_region_text import read_coordinate_region_text
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile
from app.services.shipping_notice.document_layout.coordinate_table_reconstruction import (
LayoutBBox,
_absolute_relative_region,
_group_visual_rows,
_inside_horizontal_region,
_table_glyphs,
_text_in_horizontal_region,
coordinate_profile_character_candidates,
)
_NUMERIC_PATTERN = re.compile(r'^-?\d+([.,]\d+)?$')
@@ -84,12 +93,14 @@ def validate_profile_parse_candidate(
fields=header_bound, glyphs=glyphs, page=page,
)
# [STEP 2] Line 字段覆盖
# [STEP 2] Line 字段覆盖(位移容忍:与行重建同源,避免 legacy 绝对坐标位移误报)
line_fields = [
field for table in profile.table_regions for layout in table.line_layouts
for field in layout.field_regions if field.scope == 'line'
]
line_coverage = _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page)
line_coverage = _line_region_coverage_shift_tolerant(
profile=profile, glyphs=glyphs, page=page, layout=layout,
)
# [STEP 3] 明细行数启发式
line_count = _estimate_line_count(profile=profile, glyphs=glyphs, page=page)
@@ -207,6 +218,176 @@ def _field_validation_region(field: Any) -> dict[str, Any] | None:
return None
def _line_region_coverage_shift_tolerant(
*,
profile: OrderCoordinateProfile,
glyphs: list[dict[str, Any]],
page: dict[str, Any],
layout: dict[str, Any],
) -> dict[str, Any]:
"""按行重建同源的位移容忍字符窗口与视觉行横向重叠,统计 line 字段覆盖率。
核心逻辑:legacy 模板把字段区冻结在标注样本的绝对页坐标,但实际物理表可能整体
纵向位移;若沿用冻结区域做严格中心包含读取,位移后的字段会读空,导致
``profile_parse_line_coverage_insufficient`` 误报。行重建 ``values_for`` 是把字段
区域按横向边界投影到所在视觉行(只做 x 重叠、y 来自真实行带),与是否位移无关。
此处对齐同一套语义:先按当前表区定位物理表,构造位移容忍的字符窗口,再按视觉行
做横向重叠覆盖;定位不到物理表时回退到冻结区域严格读取。
Args:
profile: 当前候选 Profile(含 table_regions)。
glyphs: 当前页冻结坐标字符。
page: 当前页尺寸。
layout: 冻结 layout,含 coordinate_evidence 的 tables/page_glyphs。
Returns:
{coverage_ratio, empty_region_count, total_region_count}。
"""
if not profile.table_regions:
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
line_fields = [
field for table in profile.table_regions for layout_item in table.line_layouts
for field in layout_item.field_regions if field.scope == 'line'
]
if not line_fields:
return {'coverage_ratio': 1.0, 'empty_region_count': 0, 'total_region_count': 0}
evidence = layout.get('coordinate_evidence') if isinstance(layout.get('coordinate_evidence'), dict) else {}
page_glyph_tables = evidence.get('tables') if isinstance(evidence.get('tables'), dict) else {}
# 定位与主表区(首个含 line_layouts 的表区)重叠且在 page 上的物理表;取重叠面积最大者。
primary_region = next(
(table for table in profile.table_regions if table.line_layouts), None,
)
raw_table = _locate_overlapping_raw_table(
primary_region=primary_region, layout=layout, page=page, profile=profile,
)
width, height = float(page['width']), float(page['height'])
table_region = primary_region.region.model_dump() if primary_region is not None else None
reference_page_frame = _reference_page_frame_mapping(profile, page)
reconstruction_page_bbox = {
'x0': 0.0, 'y0': 0.0,
'x1': float(reference_page_frame['width']) if reference_page_frame is not None else width,
'y1': float(reference_page_frame['height']) if reference_page_frame is not None else height,
}
# 位移容忍字符窗口:表区横向始终有效,纵向扩展至定位到的物理表框。
characters, _ = coordinate_profile_character_candidates(
table_region=table_region or {},
page_size=page, reference_page_frame=reference_page_frame,
page_characters=glyphs if isinstance(glyphs, list) else None,
table_characters=(
page_glyph_tables.get(raw_table.get('table_id'))
if raw_table is not None and isinstance(page_glyph_tables.get(raw_table.get('table_id')), list)
else None
),
raw_table_bbox=(raw_table.get('bbox') if raw_table is not None else None),
table_id=(raw_table.get('table_id') if raw_table is not None else None),
page_no=1, coordinate_transform=None, allow_table_fallback=True,
)
if not isinstance(characters, list) or not characters:
return _field_region_coverage(fields=line_fields, glyphs=glyphs, page=page)
page_bbox = _LayoutBBox_from_dict(reconstruction_page_bbox)
glyphs_in_table = _table_glyphs(characters, page_bbox)
visual_rows = _group_visual_rows(glyphs_in_table)
non_empty = 0
measurable = 0
for field in line_fields:
relative = field.region.model_dump() if hasattr(field.region, 'model_dump') else field.region
if not isinstance(relative, dict):
continue
measurable += 1
absolute = _absolute_relative_region(page_bbox, relative)
if _region_is_covered(visual_rows=visual_rows, region=absolute):
non_empty += 1
total = measurable
return {
'coverage_ratio': non_empty / total if total else 1.0,
'empty_region_count': total - non_empty,
'total_region_count': total,
}
def _reference_page_frame_mapping(profile: OrderCoordinateProfile, page: dict[str, Any]) -> dict[str, Any] | None:
"""读取 Profile 冻结的首页参考页框;缺失时返回 None(由调用方回退到页面尺寸)。"""
reference = profile.reference_page_frames.get(1)
if reference is None:
return None
return reference.model_dump() if hasattr(reference, 'model_dump') else reference
def _LayoutBBox_from_dict(value: dict[str, Any]) -> Any:
"""将页面框 dict 包装为 LayoutBBox,供重建辅助函数读取绝对坐标。"""
if isinstance(value, LayoutBBox):
return value
return LayoutBBox.model_validate(value)
def _locate_overlapping_raw_table(
*,
primary_region: Any,
layout: dict[str, Any],
page: dict[str, Any],
profile: OrderCoordinateProfile,
) -> dict[str, Any] | None:
"""在 layout.tables 中找出与主表区纵向交叠且位于当前页、重叠面积最大的物理表。
命中不到物理表(例如整页字符回退、虚拟页)时返回 None,由调用方维持冻结严格读取,
避免把无物理表的场景误判为已定位到明细表。
"""
if primary_region is None:
return None
reference_page_frame = _reference_page_frame_mapping(profile, page)
width, height = float(page['width']), float(page['height'])
projection_width = float(reference_page_frame['width']) if reference_page_frame is not None else width
projection_height = float(reference_page_frame['height']) if reference_page_frame is not None else height
if projection_width <= 0 or projection_height <= 0:
return None
relative = primary_region.region.model_dump() if hasattr(primary_region.region, 'model_dump') else primary_region.region
if not isinstance(relative, dict):
return None
try:
absolute_region = {
'x0': float(relative['x0']) * projection_width,
'y0': float(relative['y0']) * projection_height,
'x1': float(relative['x1']) * projection_width,
'y1': float(relative['y1']) * projection_height,
}
except (KeyError, TypeError, ValueError):
return None
best: dict[str, Any] | None = None
best_overlap = 0.0
for raw_table in layout.get('tables') or []:
if not isinstance(raw_table, dict) or int(raw_table.get('page_no') or 1) != 1:
continue
bbox = raw_table.get('bbox')
if not isinstance(bbox, dict):
continue
overlap_x = (
min(float(bbox.get('x1', 0)), absolute_region['x1'])
- max(float(bbox.get('x0', 0)), absolute_region['x0'])
)
overlap_y = (
min(float(bbox.get('y1', 0)), absolute_region['y1'])
- max(float(bbox.get('y0', 0)), absolute_region['y0'])
)
if overlap_x <= 0 or overlap_y <= 0:
continue
overlap_area = overlap_x * overlap_y
if overlap_area > best_overlap:
best_overlap = overlap_area
best = raw_table
return best
def _region_is_covered(visual_rows: list[list[tuple[int, Any]]], region: Any) -> bool:
"""判断任一视觉行在字段横向边界内是否出现非空文字,忽略冻结纵向位置。"""
for band in visual_rows:
selected = [item for item in band if _inside_horizontal_region(item[1].bbox, region)]
if _text_in_horizontal_region(selected, region).strip():
return True
return False
def _estimate_line_count(
*,
profile: OrderCoordinateProfile,
@@ -4,6 +4,7 @@ services/shipping_notice/document_layout/order_profile_signature.py
用途:从模板定义与冻结样本坐标证据生成不可变版面签名(统计摘要,不含正文/URL)。
依赖:order_profile 契约、coordinate_region_text、标准库 hashlib/json/statistics。
逻辑:由 validation_service 在发布检查前调用;本模块不负责数据库提交或 Profile 引用更新。
另提供 clip_table_bbox_to_business_rows,供签名观测与运行时 matcher 共用。
"""
from __future__ import annotations
@@ -17,6 +18,7 @@ from typing import Any
from app.services.shipping_notice.document_layout.coordinate_region_text import (
positioned_token_spans,
read_coordinate_region_text,
visual_glyph_rows,
)
from app.services.shipping_notice.document_layout.order_profile import OrderCoordinateProfile, RelativeRegion
from app.services.shipping_notice.order_extraction_route_contract import PROFILE_SCORING_POLICY_ID
@@ -27,15 +29,162 @@ LAYOUT_SIGNATURE_ID = 'order-profile-layout-signature'
MATCHER_POLICY_ID = PROFILE_SCORING_POLICY_ID
# 动态业务值不得进入表头签名;仅保留多样本稳定出现的固定文字。
# 最后一条只匹配「标签 + 显式分隔符/空白数字」的粘连值(如 Qty: 24、Qty 24),
# 不得误杀 Qty.Req / Qty Req 这类列名(点号或纯字母后缀不是业务值)。
_DYNAMIC_TOKEN_PATTERNS = (
re.compile(r'^\d{4}[-/\.]\d{1,2}[-/\.]\d{1,2}$'),
re.compile(r'^\d{1,2}[-/\.]\d{1,2}[-/\.]\d{2,4}$'),
re.compile(r'^[A-Z]{0,4}\d{5,}[A-Z0-9\-]*$', re.IGNORECASE),
re.compile(r'^\d+([.,]\d+)?$'),
re.compile(r'^(po|p\.?o\.?|qty|quantity|amount|price|date|no\.?|#)\s*[:#-]?\s*\S+', re.IGNORECASE),
re.compile(
r'^(po|p\.?o\.?|qty|quantity|amount|price|date|no\.?|#)'
r'(?:\s*[:#=\-]\s*\S+|\s+\d)',
re.IGNORECASE,
),
)
def clip_table_bbox_to_business_rows(
bbox: list[float] | None,
*,
page: dict[str, Any],
glyphs: list[dict[str, Any]] | None,
header_y1: float | None = None,
termination_rules: list[dict[str, Any]] | None = None,
exclusion_regions: list[dict[str, Any]] | None = None,
) -> list[float] | None:
"""
将主表 bbox 底边裁到业务明细结束处,去掉 MinerU 粘连的表外备注区。
核心逻辑:只使用模板声明的 termination_rules 锚点文案与 exclusion_regions;
在表框内、表头下方命中最早终止点则裁 y1。无模板声明或未命中时 fail-open。
Args:
bbox: 归一化 [x0, y0, x1, y1]。
page: 含 width/height 的页对象。
glyphs: 该页 page_glyphs。
header_y1: 可选表头下沿(归一化)。
termination_rules: 表区 termination_rules 的 dict 列表(含 anchor.text/match_mode/region)。
exclusion_regions: 表区 exclusion_regions 的相对框 dict 列表。
Returns:
裁剪后的 bbox,或无法裁剪时的原 bbox。
"""
if not isinstance(bbox, list) or len(bbox) != 4:
return bbox
try:
x0, y0, x1, y1 = (float(bbox[0]), float(bbox[1]), float(bbox[2]), float(bbox[3]))
width, height = float(page.get('width') or 0), float(page.get('height') or 0)
except (TypeError, ValueError):
return bbox
if width <= 0 or height <= 0 or x1 <= x0 or y1 <= y0:
return bbox
floor = float(header_y1) if header_y1 is not None else (y0 + max(0.02, (y1 - y0) * 0.08))
floor = min(max(floor, y0), y1)
stop_ys: list[float] = []
for region in exclusion_regions or []:
if not isinstance(region, dict):
continue
try:
ey0 = float(region['y0'])
ex0, ex1 = float(region['x0']), float(region['x1'])
except (KeyError, TypeError, ValueError):
continue
if ey0 <= floor or ey0 >= y1:
continue
if ex1 < x0 or ex0 > x1:
continue
stop_ys.append(ey0)
rules = [item for item in (termination_rules or []) if isinstance(item, dict)]
if rules and isinstance(glyphs, list) and glyphs:
for row in visual_glyph_rows(glyphs):
row_meta = _normalized_glyph_row(row, width=width, height=height)
if row_meta is None:
continue
row_y, row_x0, row_x1, text = row_meta
if row_y <= floor or row_y >= y1:
continue
if row_x1 < x0 or row_x0 > x1:
continue
if _row_matches_termination_rules(
text=text, row_y=row_y, table_bbox=[x0, y0, x1, y1], rules=rules,
):
stop_ys.append(row_y)
if not stop_ys:
return bbox
clipped_y1 = max(floor + 1e-3, min(stop_ys) - 0.008)
if clipped_y1 >= y1 - 1e-3:
return bbox
return [x0, y0, x1, round(clipped_y1, 6)]
def _normalized_glyph_row(
row: list[dict[str, Any]], *, width: float, height: float,
) -> tuple[float, float, float, str] | None:
"""将视觉行折叠为归一化 y/x 范围与拼接文本。"""
xs: list[float] = []
ys: list[float] = []
texts: list[str] = []
for glyph in row:
box = glyph.get('bbox') if isinstance(glyph.get('bbox'), dict) else None
if not box:
continue
try:
gx0, gy0, gx1, gy1 = float(box['x0']), float(box['y0']), float(box['x1']), float(box['y1'])
except (KeyError, TypeError, ValueError):
continue
xs.extend((gx0 / width, gx1 / width))
ys.append(((gy0 + gy1) / 2) / height)
texts.append(str(glyph.get('text') or ''))
if not xs or not ys:
return None
return sum(ys) / len(ys), min(xs), max(xs), ''.join(texts)
def _row_matches_termination_rules(
*,
text: str,
row_y: float,
table_bbox: list[float],
rules: list[dict[str, Any]],
) -> bool:
"""按模板 termination_rules 判断视觉行是否为业务表结束锚点。"""
compact = ' '.join(text.split())
if not compact:
return False
compact_key = compact.casefold().replace(' ', '')
x0, y0, x1, y1 = table_bbox
for rule in rules:
anchor = rule.get('anchor') if isinstance(rule.get('anchor'), dict) else None
if not isinstance(anchor, dict):
continue
expected = str(anchor.get('text') or '').strip()
if not expected:
continue
region = anchor.get('region')
if isinstance(region, dict):
try:
# region 相对表区;换算到页面归一化 y 再约束命中带。
ry0 = y0 + (y1 - y0) * float(region['y0'])
ry1 = y0 + (y1 - y0) * float(region['y1'])
except (KeyError, TypeError, ValueError):
continue
if not ry0 <= row_y <= ry1:
continue
mode = str(anchor.get('match_mode') or 'contains')
expected_key = expected.casefold().replace(' ', '')
if mode == 'exact':
if compact == expected or compact_key == expected_key:
return True
elif expected in compact or (expected_key and expected_key in compact_key):
return True
return False
def build_layout_signature(
*,
definition: dict[str, Any],
@@ -206,7 +355,10 @@ def _build_table_pattern(*, table: Any, sample_layouts: list[dict[str, Any]]) ->
for layout in sample_layouts:
observed = _observe_sample_table(
layout, target_region=region, header_region=header_region,
layout,
target_region=region,
header_region=header_region,
table_region=table,
)
if observed is None:
continue
@@ -280,6 +432,7 @@ def _build_field_relation_graph(
def _observe_sample_table(
layout: dict[str, Any], *, target_region: RelativeRegion,
header_region: RelativeRegion | None,
table_region: Any | None = None,
) -> dict[str, Any] | None:
"""读取样本中与标注区域重叠最高的真实表格及其页级字符几何。"""
tables = [item for item in layout.get('tables') or [] if isinstance(item, dict)]
@@ -318,8 +471,25 @@ def _observe_sample_table(
header_tokens, centers, widths = _header_observation(
header_glyphs, page=page, bbox=bbox,
)
header_y1 = header_bbox[3] if isinstance(header_bbox, list) and len(header_bbox) == 4 else None
termination_rules = [
rule.model_dump() if hasattr(rule, 'model_dump') else rule
for rule in (getattr(table_region, 'termination_rules', None) or [])
]
exclusion_regions = [
region.model_dump() if hasattr(region, 'model_dump') else region
for region in (getattr(table_region, 'exclusion_regions', None) or [])
]
clipped = clip_table_bbox_to_business_rows(
bbox,
page=page,
glyphs=glyphs if isinstance(glyphs, list) else None,
header_y1=header_y1,
termination_rules=termination_rules or None,
exclusion_regions=exclusion_regions or None,
)
return {
'bbox': bbox,
'bbox': clipped if isinstance(clipped, list) else bbox,
'header_tokens': header_tokens,
'column_centers': centers,
'column_width_ratios': widths,
@@ -528,7 +698,12 @@ def _split_header_tokens(text: str) -> list[str]:
def _is_dynamic_token(token: str) -> bool:
"""判断 token 是否像 PO/日期/数量等动态值。"""
"""
判断 token 是否像 PO/日期/数量等动态值。
核心逻辑:日期、料号型编码、纯数字,以及「Qty:/PO: + 值」粘连串视为动态;
Qty.Req 等列名不含显式分隔后的值或空白数字,不得判动态。
"""
compact = token.strip()
if not compact or len(compact) <= 1:
return True
@@ -1339,8 +1339,31 @@ def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None:
raise ConflictError('A cross-page blind test sample is required', code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_CROSS_PAGE')
def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str) -> None:
"""将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。"""
def promote_approved_suite_for_publish(
*, profile: ShippingOrderDocumentProfile, draft_checksum: str, published_checksum: str,
actor_id: int | None = None,
) -> None:
"""将已批准草稿盲测凭证原子冻结为正式 Profile checksum,供历史 Run 精确引用。
核心逻辑:
[STEP 1] 定位当前草稿 checksum 下已批准的盲测集;缺失时直接返回(生产调用方
已通过 assert_profile_publishable 门禁,此守卫仅防御测试夹具伪造凭证)。
[STEP 2] 同一 Profile 行重复发布相同内容时(如人工将已发布模板重置为草稿后
再次发布),发布 checksum 由规范化负载确定性复现,历史提升套件仍占用
(profile_id, profile_checksum) 唯一键。若占用者仍是有效发布凭证(approved 且
最近一次 Run 通过且 checksum 一致),则直接复用历史凭证:新草稿集转为
superseded 以保留其运行历史供审计,不再重写 checksum,避免唯一键冲突。
[STEP 3] 常规路径:重写套件与其 Run 的 checksum 为发布 checksum。
Args:
profile: 即将发布的 Profile ORM 记录(发布事务内调用,不自行提交)。
draft_checksum: 发布前草稿定义的规范化 checksum。
published_checksum: 本次发布冻结的正式 checksum。
actor_id: 触发发布的管理员主键,用于审计;允许为空。
Returns:
无返回值;套件状态变更随发布事务一并提交。
"""
suite = ShippingDocumentProfileTestSuite.query.filter_by(
profile_id=profile.id, profile_checksum=draft_checksum, status='approved',
).one_or_none()
@@ -1348,6 +1371,31 @@ def promote_approved_suite_for_publish(*, profile: ShippingOrderDocumentProfile,
# isolated lifecycle tests from fabricating a quality credential by monkeypatch.
if suite is None:
return
# [STEP 2] 唯一键占用检查:发布 checksum 相同意味着定义、Schema 与 adapter 证据
# 完全一致,历史凭证对本次发布同样有效,无需也不允许重写第二个套件。
occupant = ShippingDocumentProfileTestSuite.query.filter_by(
profile_id=profile.id, profile_checksum=published_checksum,
).one_or_none()
if occupant is not None and occupant.id != suite.id:
occupant_last_run = occupant.runs[-1] if occupant.runs else None
if (
occupant.status == 'approved' and occupant_last_run is not None
and occupant_last_run.status == 'passed'
and occupant_last_run.profile_checksum == published_checksum
):
suite.status = 'superseded'
_audit(profile_id=profile.id, event_type='blind_test_suite_superseded', actor_id=actor_id, detail={
'suite_id': suite.id, 'reused_suite_id': occupant.id,
'reason_code': 'republish_identical_content',
})
return
# 占用者不是有效凭证(人工改动等异常数据):拒绝发布并给出可定位的错误码,
# 禁止静默覆盖或删除历史盲测证据。
raise ConflictError(
'Published checksum is already occupied by another test suite',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SUITE_CHECKSUM_CONFLICT',
details={'suite_id': occupant.id},
)
suite.profile_checksum = published_checksum
for run in suite.runs:
if run.profile_checksum == draft_checksum:
@@ -23,6 +23,7 @@ from app.models import (
ShippingOrderIntake,
ShippingOrderSnapshot,
ShippingNotice,
ShippingOrderTask,
)
from app.services.shipping_notice.business_fingerprint import (
CONTENT_FINGERPRINT_VERSION,
@@ -40,19 +41,35 @@ def classify_task_lifecycle(task: ShippingNotice | dict[str, Any] | None) -> str
lifecycle = str(get('lifecycle_status', '') or '').strip().lower()
if lifecycle in {'voided', 'archived', 'deleted', 'cancelled', 'canceled'}:
return 'closed'
upload = str(get('upload_status', '') or '').strip().lower()
if upload in {'uploaded', 'succeeded', 'success'} or get('freight_ref_no'):
upload = None
try:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
if not isinstance(task, dict) and has_verified_upload_success(task):
upload = 'uploaded'
except Exception:
upload = None
if upload == 'uploaded':
return 'completed'
return 'active'
def is_irreversible_task(task: ShippingNotice) -> bool:
"""已 uploaded 或终态任务不可原地覆盖源文件。"""
upload_status = str(task.upload_status or '').strip().lower()
return upload_status in {'uploaded', 'succeeded', 'success'}
try:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
return has_verified_upload_success(task)
except Exception:
return False
def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: list[str]) -> dict[str, Any]:
candidate = (
db.session.query(ShippingOrderCandidate)
.filter(ShippingOrderCandidate.consumed_task_id == task.order_task_id)
.order_by(ShippingOrderCandidate.id.desc())
.first()
if getattr(task, 'order_task_id', None) else None
)
return {
'task_no': task.task_no,
'document_version': int(task.document_version or 1),
@@ -60,14 +77,29 @@ def _match_payload(task: ShippingNotice, *, match_type: str, matched_fields: lis
'matched_fields': list(matched_fields),
'lifecycle': classify_task_lifecycle(task),
'created_at': utc_iso(task.created_at),
'content_fingerprint': task.content_fingerprint,
'content_fingerprint_version': task.content_fingerprint_version,
'content_fingerprint': getattr(candidate, 'content_fingerprint', None),
'content_fingerprint_version': getattr(candidate, 'content_fingerprint_version', None),
}
def _task_content_fingerprint(task: ShippingNotice) -> tuple[str | None, str | None]:
"""从建单来源 Candidate 读取内容指纹;正式 Notice 不再保存该投影。"""
if not getattr(task, 'order_task_id', None):
return None, None
candidate = (
db.session.query(ShippingOrderCandidate.content_fingerprint, ShippingOrderCandidate.content_fingerprint_version)
.filter(ShippingOrderCandidate.consumed_task_id == task.order_task_id)
.order_by(ShippingOrderCandidate.id.desc())
.first()
)
return (candidate[0], candidate[1]) if candidate else (None, None)
def _reservation_differences(task: ShippingNotice, summary: dict[str, Any]) -> list[dict[str, Any]]:
"""比较候选与目标冻结订单的同 Reservation 行,供人工修订确认前展示。"""
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None:
return []
proposed = {
@@ -158,10 +190,13 @@ def detect_duplicates_for_intake(
if content_hash:
hash_tasks = (
db.session.query(ShippingNotice)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id)
.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.source_content_hash == content_hash,
ShippingNotice.lifecycle_status == 'active',
ShippingOrderTask.user_id == int(intake.user_id),
FileAsset.content_hash == content_hash,
ShippingOrderTask.lifecycle_status == 'active',
)
.order_by(ShippingNotice.id.desc())
.limit(10)
@@ -182,10 +217,12 @@ def detect_duplicates_for_intake(
if fingerprint and strength in {'strong', 'medium'}:
fp_tasks = (
db.session.query(ShippingNotice)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
ShippingOrderTask.user_id == int(intake.user_id),
ShippingOrderCandidate.business_fingerprint == fingerprint,
ShippingOrderCandidate.fingerprint_version == version,
)
.order_by(ShippingNotice.id.desc())
.limit(20)
@@ -206,12 +243,13 @@ def detect_duplicates_for_intake(
if matches and status == 'none':
comparable = [
task for task in fp_tasks
if task.content_fingerprint and task.content_fingerprint_version == content_version
if _task_content_fingerprint(task)[0]
and _task_content_fingerprint(task)[1] == content_version
]
if content_fingerprint and comparable:
status = (
'same_business_content'
if any(task.content_fingerprint == content_fingerprint for task in comparable)
if any(_task_content_fingerprint(task)[0] == content_fingerprint for task in comparable)
else 'possible_revision'
)
else:
@@ -229,11 +267,13 @@ def detect_duplicates_for_intake(
# 弱指纹:仅标记疑似,不按 active 强阻断
fp_tasks = (
db.session.query(ShippingNotice)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
ShippingNotice.lifecycle_status == 'active',
ShippingOrderTask.user_id == int(intake.user_id),
ShippingOrderCandidate.business_fingerprint == fingerprint,
ShippingOrderCandidate.fingerprint_version == version,
ShippingOrderTask.lifecycle_status == 'active',
)
.order_by(ShippingNotice.id.desc())
.limit(5)
@@ -498,11 +538,10 @@ def detect_duplicates_for_candidate(
if content_hash:
hash_query = (
db.session.query(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.source_content_hash == content_hash,
ShippingNotice.lifecycle_status == 'active',
)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderIntake, ShippingOrderIntake.consumed_task_id == ShippingOrderTask.id)
.join(FileAsset, FileAsset.id == ShippingOrderIntake.asset_id)
.filter(ShippingOrderTask.user_id == int(intake.user_id), FileAsset.content_hash == content_hash, ShippingOrderTask.lifecycle_status == 'active')
)
if skipped_ids:
hash_query = hash_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -522,11 +561,9 @@ def detect_duplicates_for_candidate(
if fingerprint and strength in {'strong', 'medium'}:
fp_query = (
db.session.query(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(ShippingOrderTask.user_id == int(intake.user_id), ShippingOrderCandidate.business_fingerprint == fingerprint, ShippingOrderCandidate.fingerprint_version == version)
)
if skipped_ids:
fp_query = fp_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -545,12 +582,13 @@ def detect_duplicates_for_candidate(
if matches and status == 'none':
comparable = [
task for task in fp_tasks
if task.content_fingerprint and task.content_fingerprint_version == content_version
if _task_content_fingerprint(task)[0]
and _task_content_fingerprint(task)[1] == content_version
]
if content_fingerprint and comparable:
status = (
'same_business_content'
if any(task.content_fingerprint == content_fingerprint for task in comparable)
if any(_task_content_fingerprint(task)[0] == content_fingerprint for task in comparable)
else 'possible_revision'
)
else:
@@ -564,12 +602,9 @@ def detect_duplicates_for_candidate(
elif fingerprint and strength == 'weak' and status == 'none':
weak_query = (
db.session.query(ShippingNotice)
.filter(
ShippingNotice.user_id == int(intake.user_id),
ShippingNotice.business_fingerprint == fingerprint,
ShippingNotice.fingerprint_version == version,
ShippingNotice.lifecycle_status == 'active',
)
.join(ShippingOrderTask, ShippingOrderTask.id == ShippingNotice.order_task_id)
.join(ShippingOrderCandidate, ShippingOrderCandidate.consumed_task_id == ShippingOrderTask.id)
.filter(ShippingOrderTask.user_id == int(intake.user_id), ShippingOrderCandidate.business_fingerprint == fingerprint, ShippingOrderCandidate.fingerprint_version == version, ShippingOrderTask.lifecycle_status == 'active')
)
if skipped_ids:
weak_query = weak_query.filter(ShippingNotice.id.notin_(list(skipped_ids)))
@@ -3,6 +3,8 @@
依赖:受控 HTML 网格解析、冻结订单 Schema 表头契约、PO/Reservation 标准化。
逻辑:订单字段表头只复用 Run/当前发布 Schema 的显式别名;邮件专属的分配事实
仍使用受控固定列。表格歧义或缺 PO 保留原因,不将正文直接转成订单。
非法非 PO 字段跳过本列并记 issue,避免可选列拖垮 Reservation/库存源线索。
多表按文档顺序叠行:靠前为新,同行身份键先到为准;旧表仅补全新表未覆盖的行。
"""
from __future__ import annotations
@@ -31,10 +33,46 @@ def _schema_configs(schema_definition: dict[str, Any]) -> dict[str, dict[str, An
}
def _supplement_row_identity(row: dict[str, Any]) -> tuple[str, str, str] | None:
"""返回补充行跨表去重键;无次级身份时返回 None(不可安全覆盖,原样保留)。
核心逻辑:PO 必选;次级键按 reservation_id → allocation_id → part_number →
customer_part_number 择一,避免把同 PO 不同明细误合成一行。
Args:
row: 已规范化的补充行(含 PO 与可选明细身份字段)。
Returns:
``(po, field_code, value)``;缺 PO 或无可覆盖次级键时为 None。
"""
po_number = normalize_po_number(row.get('customer_po_number') or row.get('po_number'))
if not po_number:
return None
po_key = po_number.upper()
for field_code in ('reservation_id', 'allocation_id', 'part_number', 'customer_part_number'):
value = str(row.get(field_code) or '').strip().upper()
if value:
return (po_key, field_code, value)
return None
def _normalize_schema_row(
values: dict[str, str], *, schema_definition: dict[str, Any], issues: list[str],
) -> dict[str, Any] | None:
"""按冻结 Schema 规范化并校验 EML 单元格;非法字段不参与任何补充裁决。"""
"""按冻结 Schema 规范化并校验 EML 单元格;非法非 PO 字段跳过,不拖垮整行。
核心逻辑:PO 仍是行身份门槛;其余字段解析/校验失败只记
``email_supplement_field_invalid`` 并省略该字段,避免可选列(如 PO Date)
非法时把 Reservation / 库存源线索一并丢掉。
Args:
values: 表头映射后的 field_code → 原始单元格文本。
schema_definition: Run 冻结 Schema。
issues: 可追加的问题码列表(调用方持有,本函数原地写入)。
Returns:
规范化后的补充行;缺有效 PO 时返回 None。
"""
configs = _schema_configs(schema_definition)
normalized: dict[str, Any] = {}
for field_code, raw_value in values.items():
@@ -42,14 +80,15 @@ def _normalize_schema_row(
if config is None:
normalized[field_code] = raw_value
continue
# [STEP] 非 PO 字段失败只跳过本列;PO 失败则稍后由 po 门槛统一拒行。
try:
value = normalize_order_field_value(raw_value, config)
except Exception:
issues.append('email_supplement_field_invalid')
return None
continue
if value is None or not validate_order_field_value(value, config):
issues.append('email_supplement_field_invalid')
return None
continue
normalized[field_code] = value
po_code = 'customer_po_number' if 'customer_po_number' in normalized else 'po_number'
po_number = normalize_po_number(normalized.get(po_code))
@@ -128,10 +167,23 @@ def _schema_headers(schema_definition: dict[str, Any]) -> dict[str, str | None]:
def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str, schema_definition: dict[str, Any]) -> dict[str, Any]:
"""输出正文补充行和 DOM 单元格证据;订单字段别名必须来自冻结 Schema。"""
"""输出正文补充行和 DOM 单元格证据;订单字段别名必须来自冻结 Schema。
核心逻辑:按 HTML 出现顺序扫描全部可映射分配表;同行身份键以先到(更新)为准,
旧表仅补全新表未覆盖的行,避免局部修订丢行或与旧单价假冲突。
Args:
html_tables: Intake 清洗后的顶层 HTML table 片段列表(文档顺序)。
content_hash: 正文 Document 内容哈希,用于稳定 cell_id。
schema_definition: Run 冻结 Schema。
Returns:
email-supplement.v1 结果(rows / issues / version)。
"""
result = empty_email_supplement_result()
rows: list[dict[str, Any]] = []
issues: list[str] = []
seen_identities: set[tuple[str, str, str]] = set()
for table_index, html in enumerate(html_tables):
try:
grid = parse_html_grid(str(html or ''), table_id=f'email-supplement:{content_hash}:{table_index}')
@@ -161,10 +213,18 @@ def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str,
)
if normalized is None:
continue
rows.append({
row = {
**normalized, 'evidence': evidence, 'table_index': table_index,
'row_index': row_index,
})
}
# [STEP] 有身份键则先到为准;无次级键无法跨表覆盖,整行保留。
identity = _supplement_row_identity(row)
if identity is not None:
if identity in seen_identities:
issues.append('email_supplement_older_row_superseded')
continue
seen_identities.add(identity)
rows.append(row)
result.update({'rows': rows, 'issues': sorted(set(issues))})
return result
@@ -570,7 +570,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'inventory_rpa_login_failed': _meta('admin', 'retry_inventory_preparation', '库存平台登录失败'),
'inventory_rpa_export_failed': _meta('worker', 'retry_inventory_preparation', '库存报表导出失败'),
'inventory_rpa_exhausted': _meta('owner', 'reload_inventory_result', '库存源重试次数已耗尽'),
'inventory_file_missing': _meta('owner', 'upload_inventory_file', '未生成库存文件'),
'inventory_file_missing': _meta('owner', 'retry_inventory_preparation', '未生成库存文件'),
'inventory_candidates_missing': _meta('system', 'retry_with_latest_rules', '正式库存候选版本缺失'),
'inventory_candidate_data_incomplete': _meta('system', 'retry_with_latest_rules', '库存候选事实不完整'),
'inventory_candidate_version_stale': _meta('system', 'retry_with_latest_rules', '库存候选版本已切换'),
@@ -613,7 +613,7 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = {
'inventory_reservation_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 Reservation'),
'inventory_warehouse_mismatch': _meta('owner', 'open_inventory_match_review', '仓库与订单要求不一致'),
'inventory_uom_conversion_failed': _meta('owner', 'open_inventory_match_review', '单位换算失败'),
'inventory_multi_file_conflict': _meta('owner', 'open_inventory_match_review', '多库存文件结果冲突'),
'inventory_multi_file_conflict': _meta('owner', 'override_line_inventory_source', '多库存文件结果冲突'),
}
@@ -36,7 +36,7 @@ ALLOWED_SOURCE_KINDS = {'order_field', 'inventory_field', 'system_fact', 'consta
ALLOWED_ROW_MODES = {'header', 'line'}
ALLOWED_FORMATTERS = {'text', 'upper', 'lower', 'date_mmddyyyy', 'integer', 'decimal'}
ALLOWED_SYSTEM_FACTS = {
'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date', 'export_sequence',
'task_no', 'business_no', 'warehouse_id', 'inventory_source_code', 'export_date', 'notice_line_no',
}
+212 -59
View File
@@ -4,7 +4,9 @@ services/shipping_notice/export.py
用途:按库存源绑定的已发布模板版本生成发货 Excel,并记录不可变导出产物。
依赖:ShippingExcelTemplate/ShippingExportArtifact、冻结 ShippingOrderSnapshot、库存快照与 openpyxl。
逻辑:锁定 Source、模板、冻结订单快照、库存解析 Profile 和库存快照,按白名单映射写入模板;
在最终导出行集上注入 `__export_sequence=1..N`,仅供 system_fact:export_sequence 消费;
导出前按本单 match_keys(通常 reservation+part)裁剪库存候选再匹配,避免全量快照进匹配;
Header 的 system_fact:warehouse_id 取本 Notice 唯一行库位(PVMI 契约);多库位冲突失败;
在最终导出行集上按通知明细项次写入模板;内部遍历序号不属于业务字段。
订单内部项次 line_no 只能通过 order_field 映射,不得再作为系统事实。
"""
@@ -29,16 +31,55 @@ from app.models import (
ShippingExcelTemplate,
ShippingExportArtifact,
ShippingNoticeLine,
ShippingNoticeLineInventoryMatch,
ShippingInventoryField,
ShippingInventorySource,
ShippingOrderSnapshot,
ShippingOrderField,
ShippingNotice,
ShippingOrderTask,
ShippingCustomer,
)
from app.path_utils import resolve_backend_relative_path
from app.services.file_assets.storage import file_asset_storage
def _notice_source_code(task: ShippingNotice) -> str | None:
"""返回正式 Notice 行级匹配中唯一使用的库存源;多源导出必须显式拒绝。"""
task_id = getattr(task, 'order_task_id', None)
if task_id is None:
return None
task_id = int(task_id)
codes = [
str(row[0]).strip().upper()
for row in 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),
).distinct().all()
if row[0]
]
return codes[0] if len(codes) == 1 else None
def _notice_inventory_file_id(task: ShippingNotice) -> int | None:
"""从 Notice 行级匹配读取本次导出的唯一库存文件。"""
task_id = getattr(task, 'order_task_id', None)
if task_id is None:
return None
task_id = int(task_id)
ids = [
int(row[0]) for row in db.session.query(ShippingNoticeLineInventoryMatch.inventory_snapshot_id).filter(
ShippingNoticeLineInventoryMatch.task_id == task_id,
ShippingNoticeLineInventoryMatch.is_current.is_(True),
ShippingNoticeLineInventoryMatch.match_result == 'matched',
ShippingNoticeLineInventoryMatch.inventory_snapshot_id.isnot(None),
).distinct().all()
]
return ids[0] if len(ids) == 1 else None
def assert_notice_has_no_export_artifact(task: ShippingNotice) -> None:
"""
确保发货通知尚未生成 Excel,保证一个 business_no 只对应一个 Artifact。
@@ -73,16 +114,7 @@ def _storage_root() -> Path:
def _source_notice_for_order_facts(notice: ShippingNotice) -> ShippingNotice:
"""后续分批 Notice 回读同一 OT 的首个冻结 Notice,订单事实不复制。"""
if notice.order_snapshot_id:
return notice
if notice.order_task_id:
source = ShippingNotice.query.filter(
ShippingNotice.order_task_id == int(notice.order_task_id),
ShippingNotice.order_snapshot_id.isnot(None),
).order_by(ShippingNotice.id.asc()).first()
if source is not None:
return source
"""返回当前 Notice;订单事实统一由其关联 OT/Snapshot 提供。"""
return notice
@@ -90,7 +122,9 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di
"""从 OT 冻结订单事实按稳定 field_id 返回 Header/Line 值。"""
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
assert_task_not_supersession_blocked(task)
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于库存匹配的冻结订单快照')
fields = (snapshot.schema_version.definition_json or {}).get('fields') or []
@@ -122,9 +156,10 @@ def _system_fact(
task: ShippingNotice,
key: str,
*,
export_sequence: int | None = None,
excel_business_no: str | None = None,
notice_no: str | None = None,
notice_line_no: str | None = None,
notice_line_warehouse_id: str | None = None,
export_date: date | None = None,
) -> Any:
"""
@@ -133,18 +168,16 @@ def _system_fact(
Args:
task: 发货任务。
key: 系统事实键;仅允许白名单内键。
export_sequence: 本次最终导出行集上的连续序号(1..N);仅 export_sequence 键使用。
Returns:
对应系统事实值;未知键返回 None。
"""
values = {
'task_no': notice_no or task.task_no,
'business_no': notice_no or excel_business_no or task.business_no,
'warehouse_id': task.inventory_warehouse_id,
'inventory_source_code': task.inventory_source_code,
'warehouse_id': notice_line_warehouse_id,
'inventory_source_code': _notice_source_code(task),
'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(),
'export_sequence': export_sequence,
'notice_line_no': notice_line_no,
}
return values.get(key)
@@ -164,6 +197,34 @@ def _template_requires_system_warehouse_id(mappings: list[dict[str, Any]]) -> bo
)
def _unique_notice_warehouse_id(notice_lines: list[Any]) -> str | None:
"""
从表头可写的 Notice 行推导唯一 Warehouse ID。
核心逻辑:PVMI 等模板把 Warehouse ID 写在 Header;多行须同库位才可写入表头,
多库位冲突时失败,避免把某一行的库位误写到整单表头。
Args:
notice_lines: 本 Notice 的 ``ShippingNoticeLine`` 列表。
Returns:
唯一非空库位码;全部为空时返回 None。
Raises:
ValueError: 多行存在多个不同库位。
"""
warehouses = {
str(getattr(line, 'inventory_warehouse_id', None) or '').strip().upper()
for line in (notice_lines or [])
if str(getattr(line, 'inventory_warehouse_id', None) or '').strip()
}
if len(warehouses) > 1:
raise ValueError('多库位发货通知不能把 Warehouse ID 映射为表头')
if len(warehouses) == 1:
return next(iter(warehouses))
return None
def _format_value(value: Any, formatter: str) -> Any:
"""应用发布契约允许的确定性格式化器。"""
if value is None:
@@ -191,9 +252,11 @@ def _format_value(value: Any, formatter: str) -> Any:
def _mapping_value(
mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any],
header_values: dict[str, Any] | None = None, export_sequence: int | None = None,
header_values: dict[str, Any] | None = None,
excel_business_no: str | None = None,
notice_no: str | None = None,
notice_line_no: str | None = None,
notice_line_warehouse_id: str | None = None,
export_date: date | None = None,
field_id_by_code: dict[str, str] | None = None,
) -> Any:
@@ -201,9 +264,7 @@ def _mapping_value(
按映射来源类型读取值;未知来源已在模板发布时被拒绝。
核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实;
export_sequence 优先用调用方传入值,缺失时回退行上注入的 ``__export_sequence``。
项次缺失时经 order_line_no_resolver 统一解析(line_no 字段 → 客户 PO 行号 →
导出行序号),与 UI 展示同一口径,禁止此处另造回退链。
通知项次只读取 ``ShippingNoticeLine.line_no``;订单字段映射不再使用导出序号兜底。
Args:
mapping: 已发布模板映射项。
@@ -211,7 +272,6 @@ def _mapping_value(
order_values: 当前行或表头订单字段值(field_id 为键)。
inventory_values: 当前行库存字段值。
header_values: 明细行模式下可回退的表头字段。
export_sequence: 本次导出行序号(1..N)。
field_id_by_code: field_code → field_id 映射(快照 Schema);缺失时按 code 键兼容。
Returns:
@@ -224,13 +284,7 @@ def _mapping_value(
field = db.session.get(ShippingOrderField, key) if key else None
field_code = str(field.field_code or '') if field else ''
if value in (None, '') and field_code == 'line_no':
from app.services.shipping_notice.order_line_no_resolver import resolve_order_line_no
value = resolve_order_line_no(
field_values=order_values,
field_id_by_code=field_id_by_code,
fallback_sequence=export_sequence,
)['value']
value = notice_line_no
if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
value = header_values.get(key)
elif kind == 'inventory_field':
@@ -238,13 +292,12 @@ def _mapping_value(
elif kind == 'system_fact':
value = _system_fact(
task, key,
export_sequence=export_sequence if key == 'export_sequence' else None,
excel_business_no=excel_business_no,
notice_no=notice_no,
notice_line_no=notice_line_no,
notice_line_warehouse_id=notice_line_warehouse_id,
export_date=export_date,
)
if key == 'export_sequence' and value is None:
value = order_values.get('__export_sequence')
else:
value = key
# 订单 Schema 的缺失值是业务事实缺失,不能被 Excel 格式化器改写成空字符串;
@@ -263,6 +316,50 @@ def _match_text(value: Any) -> str:
return str(value).strip().casefold()
def _narrow_inventory_lines_by_wanted_match_keys(
inventory_lines: list[dict[str, Any]],
*,
inventory_field_keys: list[str],
wanted_keys: set[tuple[str, ...]],
) -> list[dict[str, Any]]:
"""
仅保留与本单导出行 match_keys 命中的库存行。
核心逻辑:导出前按 reservation/part 等键裁剪候选,避免上万行全量快照进入
逐行模板匹配;键集合为空时返回空列表(由后续匹配/放行逻辑裁决)。
Args:
inventory_lines: 活动库存快照行。
inventory_field_keys: 与 match_keys 对齐的库存字段键(通常为字段目录 ID)。
wanted_keys: 本单导出行规范化后的键元组集合。
Returns:
子集库存行;无候选时为空列表。
"""
if not inventory_lines or not inventory_field_keys or not wanted_keys:
return []
return [
row for row in inventory_lines
if tuple(_match_text(row.get(field)) for field in inventory_field_keys) in wanted_keys
]
def _wanted_order_match_keys(
order_lines: list[dict[str, Any]],
*,
order_field_ids: list[str],
) -> set[tuple[str, ...]]:
"""从本单导出行收集完整 match_keys 元组(缺任一键的行跳过)。"""
wanted: set[tuple[str, ...]] = set()
if not order_lines or not order_field_ids:
return wanted
for order_line in order_lines:
key = tuple(_match_text(order_line.get(field_id)) for field_id in order_field_ids)
if all(key):
wanted.add(key)
return wanted
def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> set[str]:
"""返回模板直接引用的库存字段 ID,用于多命中一致性验证。"""
raw_ids = {
@@ -447,13 +544,20 @@ def _filename(
if not pattern:
raise ValueError('发货 Excel 文件名规则未配置')
now = datetime.now(ZoneInfo('Asia/Shanghai')).strftime('%Y%m%d%H%M%S')
owner = db.session.get(ShippingOrderTask, task.order_task_id) if getattr(task, 'order_task_id', None) else task
customer_short_code = ''
if isinstance(owner, ShippingOrderTask):
from app.services.shipping_notice.customer_resolution_service import customer_resolution_facts
facts = customer_resolution_facts(owner)
customer = db.session.get(ShippingCustomer, int(facts['customer_id'])) if facts['customer_id'] else None
customer_short_code = str(getattr(customer, 'short_code', None) or '')
values = {
'task_no': notice_no or task.task_no,
'business_no': notice_no or excel_business_no or task.business_no or task.task_no,
'source_code': task.inventory_source_code or '',
'source_code': _notice_source_code(task) or '',
'ts': now,
'date': now[:8],
'customer_short_code': task.customer_short_code_snapshot or '',
'customer_short_code': customer_short_code,
'business_date': task.business_date.strftime('%y%m%d') if task.business_date else '',
'sequence': f'{int(task.business_sequence_value):02d}' if task.business_sequence_value else '',
}
@@ -474,7 +578,7 @@ def _input_checksum(
'task_id': task.id, 'source_id': source.id, 'template_id': template.id,
'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum,
'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id,
'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': _notice_inventory_file_id(task),
'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines,
'notice_id': notice_id,
}
@@ -499,24 +603,22 @@ def generate_shipment_excel(
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
# OT 在库存门禁通过后才物化为正式 Notice;之后导出链路只接受 Notice。
from app.models import ShippingOrderTask
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.shipping_notice_creation_service import (
create_shipping_notice_after_inventory_gate,
)
task = create_shipping_notice_after_inventory_gate(task)
if not task_is_active(task):
raise ValueError('已作废或归档的任务不能生成发货 Excel')
assert_task_not_supersession_blocked(task)
assert_notice_has_no_export_artifact(task)
# [T6 E2] 滚动履约只导出当前可用行;短缺/冲突行由下方 Reservation 资格筛选排除。
source_code = str(task.inventory_source_code or '').strip().upper()
source_code = str(_notice_source_code(task) 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
source = None
if source is None:
raise ValueError('库存源不存在或已停用,不能生成发货 Excel')
template = source.excel_template
@@ -528,13 +630,10 @@ def generate_shipment_excel(
mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else []
if not mappings:
raise ValueError('发货 Excel 模板没有已发布的字段映射')
# Fixed Sources receive task Warehouse ID from configuration; dynamic Sources
# resolve it only after Reservation ID + Part Number matches. This requirement
# applies only when the published template actually consumes that system fact.
if _template_requires_system_warehouse_id(mappings) and not str(task.inventory_warehouse_id or '').strip():
raise ValueError('缺少已解析的 Warehouse ID,不能生成发货 Excel')
source_notice = _source_notice_for_order_facts(task)
snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None
owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于导出的冻结订单快照')
header_values, all_line_values = order_field_id_values(task)
@@ -590,7 +689,7 @@ def generate_shipment_excel(
)
except ConflictError:
raise
# [STEP 2] 先筛出最终可导出行,再按该集合生成连续 export_sequence(1..N)。
# [STEP 2] 先筛出最终可导出行;通知项次来自已持久化的 ShippingNoticeLine.line_no。
line_values = []
for source_index, (line, values) in enumerate(zip(snapshot.lines, all_line_values, strict=True)):
if line.id not in available_line_ids:
@@ -598,12 +697,40 @@ def generate_shipment_excel(
row = dict(values)
row['__order_line_index'] = source_index
line_values.append(row)
for index, row in enumerate(line_values, start=1):
row['__export_sequence'] = index
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
# [STEP 3] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。
# [STEP 3] 活动库存 Link 为事实源;先按本单 match_keys(通常 reservation+part)
# 裁成候选子集,再做模板字段匹配——禁止上万行全量快照进入逐行匹配。
inventory_lines = resolve_inventory_lines_for_execution(source_notice)
if (line_inventory_fields or header_inventory_fields) and match_keys and line_values:
from app.models import ShippingInventoryField
match_field_ids = {
int(item.get('inventory_field_id'))
for item in match_keys
if isinstance(item, dict) and str(item.get('inventory_field_id') or '').isdigit()
}
catalog = {
str(item.id): str(item.id)
for item in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(match_field_ids)).all()
} if match_field_ids else {}
order_field_ids: list[str] = []
inventory_field_keys: list[str] = []
for item in match_keys:
if not isinstance(item, dict):
continue
inv_key = catalog.get(str(item.get('inventory_field_id') or '').strip())
if not inv_key:
continue
order_field_ids.append(str(item.get('order_field_id') or ''))
inventory_field_keys.append(inv_key)
if order_field_ids and inventory_field_keys:
wanted_keys = _wanted_order_match_keys(line_values, order_field_ids=order_field_ids)
inventory_lines = _narrow_inventory_lines_by_wanted_match_keys(
inventory_lines,
inventory_field_keys=inventory_field_keys,
wanted_keys=wanted_keys,
)
release_overrides_by_line = _release_overrides_for_export_lines(
line_values=line_values,
release_overrides_by_source_line=release_overrides_by_source_line,
@@ -656,15 +783,32 @@ def generate_shipment_excel(
}
for sheet, start_row in data_start_rows.items():
_clear_template_data_rows(wb[sheet], start_row)
# [STEP] Notice 行一次加载:明细写各行库位;Header warehouse 仅在模板需要时解析。
notice_lines = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
).all()
header_warehouse_id: str | None = None
header_warehouse_resolved = False
for mapping in mappings:
ws = wb[mapping['sheet']]
start_row = int(mapping['start_row'])
column = int(mapping['target_column'])
if mapping['row_mode'] == 'header':
# PVMI Header 允许 system_fact:warehouse_id;值取本 Notice 唯一库位。
mapping_warehouse_id = None
if _template_requires_system_warehouse_id([mapping]):
if not header_warehouse_resolved:
header_warehouse_id = _unique_notice_warehouse_id(notice_lines)
header_warehouse_resolved = True
if not header_warehouse_id:
raise ValueError('缺少 Warehouse ID,无法写入发货 Excel 表头')
mapping_warehouse_id = header_warehouse_id
ws.cell(start_row, column).value = _mapping_value(
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
excel_business_no=excel_business_no,
export_date=export_date,
notice_line_no=None,
notice_line_warehouse_id=mapping_warehouse_id,
field_id_by_code=field_id_by_code,
)
continue
@@ -675,7 +819,16 @@ def generate_shipment_excel(
ws.cell(start_row + index, column).value = _mapping_value(
mapping, task=task, order_values=order_line, inventory_values=inventory_line,
header_values=header_values,
export_sequence=int(order_line.get('__export_sequence') or (index + 1)),
notice_line_no=(
int(notice_lines[index].line_no)
if index < len(notice_lines) and notice_lines[index].line_no is not None
else None
),
notice_line_warehouse_id=(
notice_lines[index].inventory_warehouse_id
if index < len(notice_lines)
else None
),
excel_business_no=excel_business_no,
export_date=export_date,
field_id_by_code=field_id_by_code,
@@ -691,7 +844,7 @@ def generate_shipment_excel(
artifact_no=artifact_no, task_id=task.id,
template_id=template.id,
order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id,
inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=_notice_inventory_file_id(task),
input_checksum=_input_checksum(
task, source, template, snapshot, header_values, line_values, inventory_lines,
notice_id=int(task.id),
@@ -37,7 +37,8 @@ def _select_tasks(
tasks = []
for task_no in normalized_tasks:
task = get_task_for_user(task_no, user_id)
if task is None or (
# 导出归档是正式 Notice 边界;OT 尚未生成正式单据时不可进入 Artifact 查询。
if not isinstance(task, ShippingNotice) or (
require_business_no and str(getattr(task, 'business_no', '') or '').strip().upper() != task_no.upper()
):
raise NotFoundError('Shipping task not found', code='SHIPPING.EXPORT_ARCHIVE_NOT_FOUND')
@@ -61,7 +62,6 @@ def _ready_artifacts(tasks: list[ShippingNotice]) -> dict[int, list[ShippingExpo
artifact = ShippingExportArtifact.query.filter(
ShippingExportArtifact.task_id == task.id,
ShippingExportArtifact.status.in_({'ready', 'uploaded'}),
ShippingExportArtifact.file_path == task.export_file_path,
).order_by(ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc()).first()
if artifact is not None:
result[int(task.id)] = [artifact]
@@ -317,3 +317,60 @@ def analyze_unadopt_impact(*, previous_field_ids: set[str], next_field_ids: set[
'warnings': warnings,
'can_publish': not blocked,
}
def _definition_field_code_map(definition: dict[str, Any] | None) -> dict[str, str]:
"""提取版本定义中 field_id → field_code 映射,用于字段语义键跨版本一致性校验。"""
if not isinstance(definition, dict):
return {}
result: dict[str, str] = {}
for item in (definition.get('fields') or []):
if not isinstance(item, dict):
continue
field_id = str(item.get('field_id') or '').strip()
field_code = str(item.get('field_code') or '').strip()
if field_id and field_code:
result[field_id] = field_code
return result
def analyze_published_field_code_changes(
previous_definition: dict[str, Any] | None,
next_definition: dict[str, Any] | None,
) -> dict[str, Any]:
"""
已发布 field_code 不可变门禁:同一 field_id 不应在下一发布版本中更换 field_code。
核心逻辑:只比较上一已发布版本与当前草稿「同一 field_id」的 field_code 是否变化;
同一 field_code 漂移到新 field_id(废弃旧字段 + 新建)属于合法路径,不阻断。
仅在语义键被重命名时阻断,要求走「退役 + 新建」而非原地改名,保证 field_code 是
跨版本稳定引用锚点(供身份识别 resolver 等按语义键匹配)。
Args:
previous_definition: 上一已发布版本 definition;无则视为首次发布,不校验。
next_definition: 即将发布的草稿 definition。
Returns:
含 blocked、changed(field_id / previous_field_code / next_field_code)与
changed_field_ids 的字典;changed 为空时 can_publish=True。
"""
if previous_definition is None:
return {'blocked': False, 'changed': [], 'changed_field_ids': [], 'can_publish': True}
previous_map = _definition_field_code_map(previous_definition)
next_map = _definition_field_code_map(next_definition)
changed: list[dict[str, Any]] = []
for field_id in sorted(set(previous_map) & set(next_map)):
previous_code = previous_map[field_id]
next_code = next_map[field_id]
if previous_code != next_code:
changed.append({
'field_id': field_id,
'previous_field_code': previous_code,
'next_field_code': next_code,
})
return {
'blocked': bool(changed),
'changed': changed,
'changed_field_ids': [item['field_id'] for item in changed],
'can_publish': not changed,
}
@@ -16,8 +16,9 @@ from typing import Any
from app import db
from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.models import ShippingFreightCancellation, ShippingNotice, ShippingTaskEvent
from app.models import ShippingFreightCancellation, ShippingNotice, ShippingOrderTask, ShippingTaskEvent
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
from app.services.shipping_notice.tool_common import task_event_task_id
def complete_freight_cancellation(
@@ -59,11 +60,16 @@ def complete_freight_cancellation(
old.voided_at = datetime.utcnow()
old.voided_by_id = int(actor_id)
old.void_reason = 'freight_cancellation_completed'
if new.lifecycle_status == 'blocked' and new.pending_human_reason == 'freight_cancellation_required':
new.lifecycle_status = 'active'
new.pending_human_reason = None
# Notice 不再承载旧工作流阻断字段;解除修订阻断时更新其 OT 生命周期,
# 由 OT 的 Gate/状态投影重新计算当前工作面。
new_owner = (
db.session.get(ShippingOrderTask, int(new.order_task_id))
if new.order_task_id is not None else None
)
if new_owner is not None and new_owner.status == 'blocked':
new_owner.status = 'processing'
db.session.add(ShippingTaskEvent(
task_id=old.id,
task_id=task_event_task_id(old),
event_type='freight_cancellation_completed',
actor_id=actor_id,
detail_json={
@@ -74,7 +80,7 @@ def complete_freight_cancellation(
},
))
db.session.add(ShippingTaskEvent(
task_id=new.id,
task_id=task_event_task_id(new),
event_type='supersession_unblocked',
actor_id=actor_id,
detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no},
@@ -109,12 +115,19 @@ def complete_freight_cancellation(
def _task_cancel_snapshot(task: ShippingNotice) -> dict[str, Any]:
"""构造取消处置前后快照(白名单字段)。"""
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
artifact = latest_export_artifact(task)
owner = (
db.session.get(ShippingOrderTask, int(task.order_task_id))
if task.order_task_id is not None else None
)
return {
'task_no': str(task.task_no),
'lifecycle_status': str(task.lifecycle_status or ''),
'export_file_name': task.export_file_name,
'export_file_name': getattr(artifact, 'file_name', None),
'void_reason': task.void_reason,
'pending_human_reason': task.pending_human_reason,
'owner_lifecycle_status': getattr(owner, 'lifecycle_status', None),
'owner_void_reason': getattr(owner, 'void_reason', None),
}
@@ -150,11 +163,10 @@ def mark_cancelled_task_readonly(
if str(task.lifecycle_status or '').strip().lower() not in {'voided', 'pending_void'}:
task.lifecycle_status = 'pending_void'
task.void_reason = reason_text
task.pending_human_reason = 'pending_void'
# co8:Workflow Version 已 DROP;只读语义改由 Task.lifecycle_status=pending_void 表达。
after = _task_cancel_snapshot(task)
db.session.add(ShippingTaskEvent(
task_id=int(task.id),
task_id=task_event_task_id(task),
event_type='task_pending_void',
actor_id=int(actor_id),
detail_json={
File diff suppressed because it is too large. Load diff
@@ -113,6 +113,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.reservation_required": "当前匹配规则要求发货需求(订单)必须提供 Reservation ID。订单缺少 Reservation ID:{count} 行。请重新解析发货通知后再匹配。",
"workflow.gate.field_conflict_blocked": "存在 {count} 条未解决的订单字段冲突,请先复核并解决后再继续库存/匹配/导出。",
"workflow.fulfillment.excel_gate_unmatched": "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。",
"workflow.fulfillment.inventory_preparation_failed": "库存准备失败。请人工重试或上传库存文件后再继续。",
"workflow.fulfillment.excel_exists": "发货 Excel 已生成:{file}",
"workflow.fulfillment.match_first": "match_inventory(须先完成库存上传与字段对齐确认)",
"workflow.fulfillment.generate_running": "正在生成发货 Excel",
@@ -238,6 +239,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.reservation_required": "The current matching rule requires Reservation ID on the order side. {count} order lines are missing Reservation ID. Please re-parse the shipping notice before matching again.",
"workflow.gate.field_conflict_blocked": "There are {count} unresolved order field conflicts. Resolve them before inventory, matching, or export.",
"workflow.fulfillment.excel_gate_unmatched": "Inventory matching is not complete yet. Please upload inventory, confirm field alignment, and call match_inventory first.",
"workflow.fulfillment.inventory_preparation_failed": "Inventory preparation failed. Retry manually or upload an inventory file before continuing.",
"workflow.fulfillment.excel_exists": "Shipment Excel already exists: {file}",
"workflow.fulfillment.match_first": "match_inventory (inventory upload and field alignment confirmation are required first)",
"workflow.fulfillment.generate_running": "Generating shipment Excel.",
@@ -363,6 +365,7 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.reservation_required": "กฎการจับคู่ปัจจุบันกำหนดให้ฝั่งคำสั่งซื้อมี Reservation ID ขณะนี้มี {count} รายการที่ขาด Reservation ID โปรดแยกใบแจ้งส่งสินค้าใหม่ก่อนแล้วค่อยจับคู่",
"workflow.gate.field_conflict_blocked": "มีข้อขัดแย้งของฟิลด์คำสั่งซื้อที่ยังไม่แก้ {count} รายการ กรุณาตรวจสอบก่อนดำเนินการสต็อก/จับคู่/ส่งออก",
"workflow.fulfillment.excel_gate_unmatched": "ยังจับคู่สต็อกไม่เสร็จ โปรดอัปโหลดสต็อก ยืนยันการจับคู่คอลัมน์ แล้วเรียก match_inventory ก่อน",
"workflow.fulfillment.inventory_preparation_failed": "การเตรียมสต็อกล้มเหลว โปรดลองด้วยตนเองหรืออัปโหลดไฟล์สต็อกก่อนดำเนินการต่อ",
"workflow.fulfillment.excel_exists": "สร้างไฟล์ Shipment Excel แล้ว: {file}",
"workflow.fulfillment.match_first": "match_inventory (ต้องอัปโหลดสต็อกและยืนยันการจับคู่คอลัมน์ก่อน)",
"workflow.fulfillment.generate_running": "กำลังสร้าง Shipment Excel",
@@ -86,7 +86,7 @@ def _accepted_header_values(candidate: ShippingOrderCandidate) -> tuple[Shipping
def definition_context_field_is_compatible(
definition: dict[str, Any], extraction: ShippingOrderExtraction, actual_field_id: str,
) -> bool:
"""校验新版 Schema 字段能否承接旧规则快照,防止字段 UUID 漂移误伤稳定业务语义。"""
"""字段绑定主谓词:先认定同一 UUID 即同字段;否则按 field_code + scope + value_type 判断语义兼容承接规则快照。"""
expected_id = str(definition.get('context_field_id') or '')
if actual_field_id == expected_id:
return True
@@ -111,15 +111,19 @@ def definition_context_field_is_compatible(
def _resolved_context_field_id(
definition: dict[str, Any], extraction: ShippingOrderExtraction | None, header_values: dict[str, dict[str, Any]],
) -> str | None:
"""优先使用快照 UUID;Schema 升级仅在字段业务语义未变化时按 field_code 映射到新 UUID。"""
"""按 field_config.field_code 语义键定位当前字段;UUID 直配仅保留为同字段快速命中。
规则定义以 field_code(不随 Schema 版本重建而漂移)作为跨版本稳定引用锚点;
UUID 直接命中只作为无漂移时的快捷路径,避免 Schema 重发布打断识别链路。
旧快照若缺少 field_code,则回退到 UUID 直配路径,保证向后兼容。
"""
if extraction is not None:
for field_id in header_values:
if definition_context_field_is_compatible(definition, extraction, field_id):
return field_id
expected_id = str(definition.get('context_field_id') or '')
if expected_id in header_values:
return expected_id
if extraction is None:
return None
for field_id in header_values:
if definition_context_field_is_compatible(definition, extraction, field_id):
return field_id
return None
@@ -12,8 +12,6 @@ import hashlib
import json
import re
import uuid
from pathlib import Path
import urllib.request
from datetime import datetime
from typing import Any
@@ -112,19 +110,6 @@ def _published_schema_version() -> ShippingOrderSchemaVersion | None:
def _published_field_config(field_id: str) -> dict[str, Any] | None:
"""读取当前发布版本中的字段配置;识别定义和证据标准化均使用同一快照。"""
# #region debug-point A/B/C/E:published-schema-state
try:
debug_env = Path(__file__).resolve().parents[5] / '.dbg' / 'shipping-customer-fingerprint-500.env'
debug_values = {
line.split('=', 1)[0]: line.split('=', 1)[1].strip()
for line in debug_env.read_text(encoding='utf-8').splitlines()
if '=' in line
}
published_rows = ShippingOrderSchemaVersion.query.filter_by(status='published').all()
urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'shipping-customer-fingerprint-500'), 'runId': 'post-fix', 'hypothesisId': 'A/B/C/E', 'location': 'identity_rules/service.py:114', 'msg': '[DEBUG] published schema rows before serializer lookup', 'data': {'field_id': field_id, 'count': len(published_rows), 'rows': [{'id': row.id, 'schema_id': row.schema_id, 'version': row.version, 'status': row.status} for row in published_rows]}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read()
except Exception:
pass
# #endregion
published = _published_schema_version()
return next((
item for item in ((published.definition_json if published else {}) or {}).get('fields', [])
@@ -193,7 +193,7 @@ def _collect_order_line_candidates(
line_codes = list(task_level_source_codes_ordered)
line_projections.append({
'line_key': f'{task.id}:{line_no}',
# 该阶段只产生候选投影;冻结档建立后由 snapshot_line_id 作为唯一行身份。
'line_index': idx,
'line_no': line_no,
'source_line_no': source_line_no,
@@ -276,19 +276,13 @@ def _invalidate_task_candidate_outputs(
ShippingUploadAttempt,
)
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
if task.__class__.__name__ != 'ShippingOrderTask':
task.step_payload_json = payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in payload.items() if key in {'current_step_progress', 'parse_validation'}}
(
session.query(ShippingNoticeLineInventoryMatch)
@@ -306,12 +300,18 @@ def _invalidate_task_candidate_outputs(
)
.update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False)
)
artifact_ids = [
row[0] for row in session.query(ShippingExportArtifact.id).filter(
ShippingExportArtifact.task_id == int(task.id),
ShippingExportArtifact.status.in_(('ready', 'uploading')),
notice_ids = [
int(row.id)
for row in session.query(ShippingNotice.id).filter(
ShippingNotice.order_task_id == int(task.id),
).all()
]
artifact_ids = [
row[0] for row in session.query(ShippingExportArtifact.id).filter(
ShippingExportArtifact.task_id.in_(notice_ids),
ShippingExportArtifact.status.in_(('ready', 'uploading')),
).all()
] if notice_ids else []
if artifact_ids:
session.query(ShippingExportArtifact).filter(
ShippingExportArtifact.id.in_(artifact_ids),
@@ -358,6 +358,7 @@ def freeze_candidates_for_task(
execution_id: int | None = None,
frozen_by_id: int | None = None,
line_projections: list[dict[str, Any]] | None = None,
preserve_empty_line_candidates: bool = False,
session: Session | None = None,
) -> CandidateFreezeResult:
"""
@@ -370,7 +371,6 @@ def freeze_candidates_for_task(
[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 字段)。
@@ -380,6 +380,8 @@ def freeze_candidates_for_task(
execution_id: 可选的 ProcessExecution 绑定 ID。
frozen_by_id: 人工覆盖冻结时的操作人 ID。
line_projections: STP 阶段已算出的行级候选投影(缺省时逐行 evaluate_inventory_source_rules)。
preserve_empty_line_candidates: 仅人工逐项选源时为 True;保留尚未选择源的
Snapshot 行为空列表,使 Gate 能继续阻断而不会误触发整单库存准备。
session: 可选的 SQLAlchemy Session(缺省用 db.session)。
Returns:
@@ -421,18 +423,14 @@ def freeze_candidates_for_task(
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:
if not codes and not preserve_empty_line_candidates:
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
raise ValueError('候选行缺少持久化 line_no,禁止从 line_index 派生项次')
signatures.append((
line_no,
str(item.get('source_line_no') or '').strip() or None,
@@ -599,22 +597,22 @@ def freeze_candidates_for_task(
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,
)
# 人工逐项选源正由当前 GateAttempt 执行时,不能把它自己 supersede,
# 否则选源已落库但 Attempt 无法完成。该 Execution 只更新候选版本,仍停在
# routing Gate;所有项次选完后才进入库存准备。其他重冻结仍取消旧链。
current_execution_id = getattr(task, 'active_process_execution_id', None)
if execution_id is not None and int(current_execution_id or 0) == int(execution_id):
from app.models import ShippingProcessExecution
supersede_auto_progress_for_candidate_refreeze(task)
current_execution = session.get(ShippingProcessExecution, int(execution_id))
if current_execution is not None:
current_execution.candidate_set_id = int(new_set.id)
else:
from app.services.shipping_notice.auto_progress_controller import (
supersede_auto_progress_for_candidate_refreeze,
)
# [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,调用方可追加细节
supersede_auto_progress_for_candidate_refreeze(task)
return CandidateFreezeResult(
candidate_set_id=new_set.id,
@@ -624,3 +622,204 @@ def freeze_candidates_for_task(
manifest_snapshot_sha256=manifest_sha256,
set_version=set_version,
)
def freeze_manual_line_source_selection(
task: ShippingNotice,
*,
line_no: int,
source_code: str,
actor_id: int | None,
reason: str | None,
execution_id: int | None,
session: Session | None = None,
) -> tuple[CandidateFreezeResult, bool]:
"""
将通知准备的人工选源冻结为新的 CandidateSet 版本。
核心逻辑:以冻结 Snapshot 的全量 line_no 为骨架,继承当前候选行的选择后仅替换目标项次。
没有自动候选时也会先创建全量 CandidateLine;未选源项保持空数组,只有每一项都有源时才返回
``all_lines_selected=True``,调用方据此允许进入库存准备/RPA。
Args:
task: 已冻结订单对应的 OT。
line_no: 用户选择库存源的 Snapshot 项次,必须存在。
source_code: 已启用库存源编码。
actor_id: 操作人,用于候选源与候选行审计。
reason: 人工选择原因。
execution_id: 当前流程 Execution,用于绑定候选版本。
session: 可选数据库会话。
Returns:
(CandidateFreezeResult, all_lines_selected)。
Raises:
ValueError: OT 未冻结 Snapshot 或项次不存在。
"""
session = session or db.session
snapshot = (
session.query(ShippingOrderSnapshot)
.filter(ShippingOrderSnapshot.task_id == int(task.id))
.one_or_none()
)
if snapshot is None:
raise ValueError('人工选源前必须先冻结订单 Snapshot')
snapshot_lines = sorted(list(snapshot.lines or []), key=lambda row: int(row.line_no))
wanted_line = int(line_no)
if not any(int(row.line_no) == wanted_line for row in snapshot_lines):
raise ValueError('未找到该订单项次')
active_set = (
session.get(ShippingInventoryCandidateSet, int(task.active_inventory_candidate_set_id))
if task.active_inventory_candidate_set_id is not None else None
)
existing_codes = {
int(row.line_no): [str(code).strip().upper() for code in (row.source_codes_json or []) if str(code).strip()]
for row in (active_set.lines if active_set is not None else [])
}
line_projections: list[dict[str, Any]] = []
for row in snapshot_lines:
current_line_no = int(row.line_no)
codes = [source_code] if current_line_no == wanted_line else existing_codes.get(current_line_no, [])
line_projections.append({
'line_no': current_line_no,
'source_line_no': str(row.line_no),
'part_number': row.part_number,
'reservation_id': row.reservation_id,
'candidate_inventory_source_codes': codes,
})
source_codes = []
for projection in line_projections:
for code in projection['candidate_inventory_source_codes']:
if code not in source_codes:
source_codes.append(code)
adjudication = InventorySourceAdjudication(
status='manual',
method='manual_line_selection',
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(extract_routing_context(task)),
candidates=[{'source_code': code} for code in source_codes],
evidence=[{'line_no': wanted_line, 'source_code': source_code, 'reason': reason or '人工指定库存源'}],
reason='manual_line_selection',
)
result = freeze_candidates_for_task(
task,
adjudication=adjudication,
execution_id=execution_id,
frozen_by_id=actor_id,
line_projections=line_projections,
preserve_empty_line_candidates=True,
session=session,
)
return result, all(bool(item['candidate_inventory_source_codes']) for item in line_projections)
def freeze_wave_notice_routing(
notice: ShippingNotice,
*,
source_notice: ShippingNotice | None = None,
) -> CandidateFreezeResult | None:
"""
按波次自身行重跑库存源路由并冻结候选集(设计 D8:波次不再继承首通知源)。
【AI 触发时机】建波次通知(post_ot_fulfillment_wave)且在写入波次 ShippingNoticeLine 后调用;
仅当波次行需要独立路由(不同行可能不同仓)时使用。
核心逻辑:以订单级 header(field_id 值)+ 波次行 ShippingNoticeLine.field_values_json
逐行调用 ``evaluate_inventory_source_rules_for_field_values(scope='line')`` 得到行级候选;
以全波次行候选并集作为任务级候选集,调用 ``freeze_candidates_for_task`` 冻结 Set/Source/Line
(候选快照已在本地,后续匹配不重复 RPA)。
Args:
notice: 已 flush 且已写入波次行的波次通知。
source_notice: 订单首个冻结通知(提供订单级 header 事实);缺省用 notice。
Returns:
CandidateFreezeResult;无任何波次行候选时返回 None(交由无候选阻断,不冻结)。
"""
from app.models.shipping_notice_line import ShippingNoticeLine
from app.services.shipping_notice.export import order_field_id_values
from app.services.shipping_notice.inventory_routing_engine import (
evaluate_inventory_source_rules_for_field_values,
)
src = source_notice or notice
try:
header, _full_lines = order_field_id_values(src)
except ValueError:
header = {}
wave_lines = (
ShippingNoticeLine.query.filter_by(notice_id=int(notice.id)).order_by(ShippingNoticeLine.position).all()
if getattr(notice, 'id', None) is not None
else []
)
# [回退] 与首单路径一致(_collect_order_line_candidates):行级无规则命中时回退到订单级 task 候选集,
# 避免波次行「一条规则都不命中」时被算成无候选而卡死。
task_result = evaluate_inventory_source_rules_for_field_values(
header_field_values=header, scope='task',
)
task_source_codes = [str(c or '').strip().upper() for c in (getattr(task_result, 'source_codes', None) or []) if str(c or '').strip()]
line_projections: list[dict[str, Any]] = []
task_codes: list[str] = []
seen: set[str] = set()
for idx, line in enumerate(wave_lines):
line_values = dict(getattr(line, 'field_values_json', None) or {})
line_result = evaluate_inventory_source_rules_for_field_values(
header_field_values=header,
line_field_values=line_values,
scope='line',
)
resolved = str(getattr(line_result, 'status', '') or '') == 'resolved' and bool(getattr(line_result, 'source_codes', None))
if resolved:
codes = [str(c or '').strip().upper() for c in (getattr(line_result, 'source_codes', None) or []) if str(c or '').strip()]
else:
codes = list(task_source_codes)
if not codes:
codes = list(task_source_codes)
for code in codes:
if code not in seen:
seen.add(code)
task_codes.append(code)
line_projections.append({
'line_index': idx,
'line_no': idx + 1,
'source_line_no': str(getattr(line, 'line_no', None) or '').strip() or None,
'part_number': str(getattr(line, 'part_number', None) or '').strip() or None,
'reservation_id': str(getattr(line, 'reservation_id', None) or '').strip() or None,
'candidate_inventory_source_codes': codes,
'selection_mode': 'line_rule' if resolved else 'task_fallback',
'routing_status': str(getattr(line_result, 'status', '') or ''),
'matched_rule_ids': list(getattr(line_result, 'matched_rules', ()) or ()),
})
if not task_codes:
return None
from app.services.shipping_notice.inventory_source_rules import (
InventorySourceAdjudication,
_candidate,
compute_routing_fingerprint,
extract_routing_context,
)
candidates = []
for code in task_codes:
src_cfg = get_database_inventory_source(code)
if src_cfg:
candidates.append(_candidate(src_cfg))
adjudication = InventorySourceAdjudication(
status='candidates_frozen',
method='wave_line_routing',
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(extract_routing_context(notice)),
candidates=candidates,
)
return freeze_candidates_for_task(
notice,
adjudication=adjudication,
line_projections=line_projections,
)
@@ -2,9 +2,9 @@
services/shipping_notice/inventory_candidate_projection.py
用途:统一读取正式 CandidateSet 真相,并投影为任务/工作台/聊天共用的候选事实 DTO。
依赖:ShippingNotice、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、
依赖:ShippingOrderTask、ShippingInventoryCandidateSet/Source/Line、ShippingNoticeLineInventoryMatch、
ShippingTaskInventoryRpaAttempt。
逻辑:正式 Task 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、
逻辑:正式 OT 一律通过 active_inventory_candidate_set_id 读取当前 frozen Set;缺失、
坏链、旧版本匹配引用或越界匹配统一产出 fail-closed 诊断,供 Gate / Projection / API 复用。
"""
@@ -21,7 +21,7 @@ from app.models import (
ShippingInventoryCandidateSet,
ShippingInventoryCandidateSource,
ShippingInventoryFile,
ShippingNotice,
ShippingOrderTask,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
)
@@ -55,7 +55,7 @@ def _normalized_codes(codes: list[Any] | None) -> list[str]:
def _candidate_set_filter(
task: ShippingNotice,
task: ShippingOrderTask,
*,
include_drafts: bool = False,
session: Session | None = None,
@@ -83,14 +83,14 @@ def _candidate_set_filter(
def get_active_candidate_set(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> ShippingInventoryCandidateSet | None:
"""
读取正式 Task 当前 frozen CandidateSet。
核心逻辑:严格依赖 ShippingNotice.active_inventory_candidate_set_id;
核心逻辑:严格依赖 ShippingOrderTask.active_inventory_candidate_set_id;
指针为空、坏链、跨 Task、非 frozen 均返回 None,由上层映射阻断。
"""
candidate_set_id = getattr(task, 'active_inventory_candidate_set_id', None)
@@ -107,7 +107,7 @@ def get_active_candidate_set(
def get_active_candidate_sources(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateSource]:
@@ -129,7 +129,7 @@ def get_active_candidate_sources(
def get_active_candidate_lines(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> list[ShippingInventoryCandidateLine]:
@@ -150,8 +150,51 @@ def get_active_candidate_lines(
return list(rows)
def active_inventory_runtime_facts(
task: ShippingOrderTask,
*,
session: Session | None = None,
) -> dict[str, Any]:
"""
读取通知准备的当前运行事实,替代 OT 上的库存路由和快照投影列。
核心逻辑:库存源只读当前 CandidateSet/Source;库存文件只读 active Link;配置版本
取 CandidateSource 的冻结版本,不能回读 Task 的可变历史字段。
Args:
task: 当前订单任务。
session: 可选数据库会话。
Returns:
source_codes、source_config_version、inventory_file_id 与 active_link 等当前事实。
"""
from app.models import ShippingTaskInventoryLink
sess = _session(session)
candidate_set = get_active_candidate_set(task, session=sess)
sources = get_active_candidate_sources(task, session=sess)
source_codes = [str(row.source_code or '').strip().upper() for row in sources if str(row.source_code or '').strip()]
versions = [str(row.source_config_version or '').strip() for row in sources if str(row.source_config_version or '').strip()]
link = (
sess.query(ShippingTaskInventoryLink)
.filter(ShippingTaskInventoryLink.task_id == int(task.id), ShippingTaskInventoryLink.is_active.is_(True))
.order_by(ShippingTaskInventoryLink.id.desc())
.first()
if getattr(task, 'id', None) is not None else None
)
return {
'candidate_set': candidate_set,
'candidate_set_id': getattr(candidate_set, 'id', None),
'source_codes': source_codes,
'source_config_version': versions[0] if len(set(versions)) == 1 and versions else None,
'active_link': link,
'inventory_file_id': getattr(link, 'inventory_file_id', None),
'inventory_file': getattr(link, 'inventory_file', None),
}
def get_candidate_set_by_version(
task: ShippingNotice,
task: ShippingOrderTask,
version: int,
*,
include_drafts: bool = False,
@@ -271,7 +314,7 @@ def _candidate_lines_for_set(
def build_inventory_candidate_blocking_reason(
code: str,
*,
task: ShippingNotice,
task: ShippingOrderTask,
details: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""构造统一 blocking_reason DTO。"""
@@ -293,7 +336,7 @@ def build_inventory_candidate_primary_action(code: str = 'retry_with_latest_rule
}
def _latest_attempts_by_source(task: ShippingNotice, source_codes: list[str], *, session: Session | None = None) -> dict[str, dict[str, Any]]:
def _latest_attempts_by_source(task: ShippingOrderTask, 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:
@@ -346,7 +389,7 @@ def _classify_sources(source_codes: list[str], attempt_map: dict[str, dict[str,
return prepared, pending, failed
def _current_match_rows(task: ShippingNotice, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]:
def _current_match_rows(task: ShippingOrderTask, *, session: Session | None = None) -> list[ShippingNoticeLineInventoryMatch]:
"""读取任务当前生效的行级匹配事实。"""
if getattr(task, 'id', None) is None:
return []
@@ -367,7 +410,7 @@ def _current_match_rows(task: ShippingNotice, *, session: Session | None = None)
def project_inventory_candidate_detail(
task: ShippingNotice,
task: ShippingOrderTask,
*,
version: str | int = 'current',
session: Session | None = None,
@@ -426,7 +469,7 @@ def project_inventory_candidate_detail(
def project_inventory_candidate_facts(
task: ShippingNotice,
task: ShippingOrderTask,
*,
session: Session | None = None,
include_history: bool = False,
@@ -493,14 +536,20 @@ def project_inventory_candidate_facts(
allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None))
serialized = {
'id': int(row.id),
'line_key': str(row.line_key or ''),
'snapshot_line_id': int(row.snapshot_line_id),
'line_no': int(row.line_no),
'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),
# [Approach 1] 行匹配记录未回填源、但行允许源为单一源时(如 shortages 匹配、覆写单源),
# 用该单一源回填 resolved_inventory_source_code,保证行级源诚实展示(D7 Excel 前可改)。
'resolved_inventory_source_code': (
getattr(row, 'inventory_source_code', None)
or (allowed_codes[0] if len(allowed_codes) == 1 else 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')),
@@ -3,7 +3,9 @@ services/shipping_notice/inventory_file_store.py
用途:管理货代发货任务库存快照文件、任务 link 与解析结果投影。
依赖:models.ShippingInventoryFile/ShippingTaskInventoryLink、inventory_snapshot、export._storage_root。
逻辑:inventory_workflow 上传或解析库存时写入库存快照;fulfillment_workflow 匹配前从 link 解析当前任务库存。
逻辑:inventory_workflow 上传或解析库存时写入库存快照(Link 挂在正式 OT);
fulfillment_workflow / Excel 导出经 resolve_inventory_lines_for_execution:
冻结候选 OT 读 prepare 合并行,单源读 active Link 文件;禁止用 Notice.id 漏读 OT Link。
"""
from __future__ import annotations
@@ -19,7 +21,15 @@ from werkzeug.datastructures import FileStorage
from app import db
from app.core.errors import AppError
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
from app.models import (
ShippingInventoryFile,
ShippingNotice,
ShippingNoticeLineInventoryMatch,
ShippingOrderSnapshot,
ShippingTaskEvent,
ShippingTaskInventoryLink,
)
from app.services.shipping_notice.tool_common import task_event_task_id
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
@@ -29,10 +39,14 @@ from app.services.shipping_notice.inventory_source_gate import (
is_inventory_source_stable,
task_inventory_identity,
)
from app.services.shipping_notice.inventory_source_repository import inventory_sources_runtime_version
from app.services.shipping_notice.inventory_source_repository import (
get_database_inventory_source,
inventory_sources_runtime_version,
)
def _can_relink_inventory(task: ShippingNotice) -> bool:
"""判断任务是否允许被新的批次库存快照影响;终态任务不能回退。"""
return str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} \
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
return not has_verified_upload_success(task) \
and str(getattr(task, 'lifecycle_status', None) or '').strip().lower() not in {'voided', 'archived', 'deleted'}
@@ -129,11 +143,28 @@ def delete_inventory_storage_path(storage_path: str | Path | None) -> None:
def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFile | None:
"""读取任务当前 active link 指向的库存快照。"""
if task.id is None:
"""
读取任务当前 active link 指向的库存快照。
核心逻辑:``ShippingTaskInventoryLink.task_id`` 挂在正式 OT 上;传入
``ShippingNotice`` 时使用 ``order_task_id``,OT 自身使用 ``id``。
Args:
task: OT 或已绑定 ``order_task_id`` 的正式 Notice。
Returns:
当前有效库存文件;无 active Link 时返回 None。
"""
# [STEP] Link 归属 OT:Notice.id 与 OT.id 不同,禁止误用 Notice 主键查 Link。
task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
if task_id is None:
return None
link = (
ShippingTaskInventoryLink.query.filter_by(task_id=task.id, is_active=True)
ShippingTaskInventoryLink.query.filter_by(
task_id=int(task_id),
is_active=True,
invalidated_at=None,
)
.order_by(ShippingTaskInventoryLink.id.desc())
.first()
)
@@ -162,24 +193,33 @@ def resolve_task_inventory_download(task: ShippingNotice) -> tuple[Path, str] |
return path, filename
def read_inventory_file_lines(inv_file: ShippingInventoryFile) -> tuple[list[dict[str, Any]], dict[str, Any]]:
"""读取库存文件的唯一行事实;缓存为空时按已发布解析方案解析并固化到文件层。"""
cached_rows = [
row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)
]
if cached_rows:
return cached_rows, {'source': 'inventory_file_cache'}
rows, column_meta = parse_inventory_snapshot_file(inv_file)
rows = [row for row in rows if isinstance(row, dict)]
if rows:
inv_file.inventory_lines_json = rows
inv_file.line_count = len(rows)
db.session.flush()
return rows, column_meta
def active_inventory_lines_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
"""读取任务活动库存快照;已有 JSON 是快照事实,禁止读取时被物理文件静默覆盖。"""
"""读取任务活动库存文件的行事实;解析失败由调用方 Gate 转为可解释状态。"""
inv_file = active_inventory_file_for_task(task)
if inv_file and isinstance(inv_file.inventory_lines_json, list):
rows = [row for row in inv_file.inventory_lines_json if isinstance(row, dict)]
if not rows and Path(inv_file.storage_path).is_file():
try:
reparsed, _meta = parse_inventory_snapshot_file(inv_file)
if reparsed:
inv_file.inventory_lines_json = reparsed
inv_file.line_count = len(reparsed)
db.session.flush()
rows = reparsed
except Exception: # noqa: BLE001
# 解析失败时保留原快照,交由上层 Gate 报告可解释错误。
pass
if inv_file is None:
return []
try:
rows, _column_meta = read_inventory_file_lines(inv_file)
return rows
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
except (OSError, ValueError, AppError):
return []
def resolve_inventory_lines_for_execution(
@@ -188,22 +228,42 @@ def resolve_inventory_lines_for_execution(
legacy_payload_lines: list[dict[str, Any]] | None = None,
) -> list[dict[str, Any]]:
"""
解析库存匹配与导出的统一运行输入,活动库存 Link 为唯一事实源。
解析库存匹配与导出的统一运行输入。
核心逻辑:已冻结候选源时优先 ``prepare_candidate_inventory_lines`` 合并各源
ready 快照(带 ``__source_code``),避免依赖把合并行写进单份共享 File;
否则读当前 active Link 文件行;无 Link 时才允许 legacy payload。
Args:
task: 当前正式发货通知。
task: 当前正式发货通知 / OT。
legacy_payload_lines: 旧 Tool 请求携带的库存行;仅无活动 Link 的历史任务允许使用。
Returns:
本次执行使用的库存行;不会回写 ``ShippingNotice.inventory_lines_json``。
本次执行使用的库存行;不会回写任务或通知单的库存行缓存。
"""
# [STEP 1] STP 冻结候选:匹配输入来自各源快照合并,不读被污染的单文件缓存。
from app.services.shipping_notice.stp_inventory_freeze import (
task_frozen_inventory_source_codes,
)
from app.services.shipping_notice.stp_line_inventory_match import (
prepare_candidate_inventory_lines,
)
if len(task_frozen_inventory_source_codes(task)) >= 1:
prep = prepare_candidate_inventory_lines(task)
if prep.get('status') == 'ready':
rows = [row for row in list(prep.get('lines') or []) if isinstance(row, dict)]
if rows:
return rows
# [STEP 2] 单源 / 无冻结:活动 Link 文件是行事实。
if active_inventory_file_for_task(task) is not None:
return active_inventory_lines_for_task(task)
if isinstance(legacy_payload_lines, list):
rows = [row for row in legacy_payload_lines if isinstance(row, dict)]
if rows:
return rows
return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
return []
def has_uploaded_inventory_file(task: ShippingNotice) -> bool:
@@ -214,6 +274,60 @@ def has_uploaded_inventory_file(task: ShippingNotice) -> bool:
return False
def has_ready_inventory_file_for_task(task: ShippingNotice) -> bool:
"""判断 OT 是否已绑定一份有效且已解析的库存文件。"""
inv_file = active_inventory_file_for_task(task)
return bool(
inv_file is not None
and str(inv_file.snapshot_status or '').strip().lower() == 'ready'
and inv_file.invalidated_at is None
and int(inv_file.line_count or 0) > 0
)
def current_inventory_matches_for_task(task: ShippingNotice) -> list[ShippingNoticeLineInventoryMatch]:
"""读取 OT 当前有效的行级库存匹配事实。"""
task_id = getattr(task, 'id', None)
if task_id is None:
return []
return ShippingNoticeLineInventoryMatch.query.filter_by(
task_id=int(task_id), is_current=True,
).all()
def inventory_matches_complete_for_task(task: ShippingNotice) -> bool:
"""判断当前 Match 是否已覆盖冻结订单全部项次且不在准备中。"""
task_id = getattr(task, 'id', None)
snapshot_id = getattr(task, 'order_snapshot_id', None)
if task_id is None or not snapshot_id:
return False
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id))
if snapshot is None or not snapshot.lines:
return False
matches = {
int(row.snapshot_line_id): row
for row in current_inventory_matches_for_task(task)
if row.snapshot_line_id is not None
}
expected = {int(line.id) for line in snapshot.lines}
return set(matches) == expected and all(
str(row.match_result or '').strip().lower() != 'preparing'
for row in matches.values()
)
def current_inventory_matches_have_shortage(task: ShippingNotice) -> bool:
"""判断当前行级匹配中是否存在尚未满足的缺口或匹配失败。"""
for row in current_inventory_matches_for_task(task):
try:
shortage = float(row.shortage_qty or 0)
except (TypeError, ValueError):
shortage = 0.0
if str(row.match_result or '').strip().lower() != 'matched' or shortage > 0:
return True
return False
def _same_stable_inventory_identity(lhs: ShippingNotice, rhs: ShippingNotice) -> bool:
"""判断两票任务是否具备相同且稳定的库存源身份,供批次库存快照共用。"""
if not is_inventory_source_stable(lhs) or not is_inventory_source_stable(rhs):
@@ -314,9 +428,11 @@ def save_task_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Shi
mapping_source='parsing_profile',
mapping_confirmed=True,
source_code=source_code,
source_type=str(task.inventory_connector_type or "").strip() or None,
source_type=str(
(get_database_inventory_source(source_code) or {}).get('connector_type') or ''
).strip() or None,
warehouse_id=warehouse_id,
source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(),
source_config_version=inventory_sources_runtime_version(),
source_query_json={'trigger_type': 'manual_upload'},
identity_status="pending",
snapshot_status="ready",
@@ -442,7 +558,7 @@ def replace_task_inventory_link(
db.session.add(new_link)
db.session.add(
ShippingTaskEvent(
task_id=task.id,
task_id=task_event_task_id(task),
event_type="inventory_file_linked",
detail_json={
"inventory_file_no": inv_file.inventory_file_no,
@@ -524,8 +640,6 @@ def apply_inventory_parse_result_to_linked_tasks(
continue
if not _can_relink_inventory(link.task):
continue
link.task.inventory_snapshot_id = inv_file.id
link.task.inventory_lines_json = inventory_lines
linked_tasks.append(link.task)
return linked_tasks
@@ -569,7 +683,8 @@ def start_inventory_file_linked_tasks(inv_file: ShippingInventoryFile | None) ->
task = link.task
if not link.is_active or not task:
continue
if task.task_no in task_nos and not task.match_status and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'}:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
if task.task_no in task_nos and not current_inventory_matches_for_task(task) and not has_verified_upload_success(task):
set_task_step_progress(
task,
step_key="step5_match_inventory",
@@ -3,7 +3,8 @@ services/shipping_notice/inventory_mapping_workflow.py
用途:将已按 published Profile 解析完成的正式库存写回任务并推进到待匹配状态。
依赖:inventory_file_store、inventory_snapshot、query_service、state_machine、tool_common。
逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析。
逻辑:正式库存不存在任务级字段推断或映射确认;调用方必须先完成结构校验和确定性解析;
快照复用路径可传 persist_lines=False,只推进状态、不覆盖共享 File 的 inventory_lines_json。
"""
from __future__ import annotations
@@ -13,6 +14,7 @@ from typing import Any
from app import db
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_file_store import (
_can_relink_inventory,
active_inventory_file_for_task,
apply_inventory_parse_result_to_linked_tasks,
start_inventory_file_linked_tasks,
@@ -36,9 +38,14 @@ def inventory_loaded_response(
field_mapping: dict[str, str] | None = None,
mapping_source: str | None = None,
commit: bool = True,
persist_lines: bool = True,
) -> dict[str, Any]:
"""
写入已经确定性解析的正式库存,并将关联任务推进到待匹配状态。
将正式库存推进到待匹配状态;可选把解析行写入当前绑定的库存文件。
核心逻辑:必须已有 active Link。``persist_lines=True``(上传/RPA 首次落库)
写回 ``inventory_lines_json``;``False``(快照复用)只收集关联任务并推进状态,
禁止覆盖共享 File 上已有行缓存。
Args:
task: 当前正式发货任务。
@@ -50,13 +57,18 @@ def inventory_loaded_response(
field_mapping: published Profile 的字段映射快照。
mapping_source: 必须由调用方标明的映射来源,正式文件通常为 parsing_profile。
commit: False 时仅 flush,供批量回调维持外层事务边界。
persist_lines: False 时不写 File.inventory_lines_json(复用路径)。
Returns:
Tool 标准响应;成功后任务可直接进入库存匹配。
"""
inv_file = active_inventory_file_for_task(task)
if inv_file is None:
raise ValueError('OT 库存解析结果必须先绑定到有效库存文件')
# [STEP] 首次落库写 File;复用只推进状态,避免共享快照被 OT 私有/合并行覆盖。
linked_tasks: list[ShippingNotice] = []
if inv_file:
if persist_lines:
linked_tasks = apply_inventory_parse_result_to_linked_tasks(
inv_file,
inventory_lines,
@@ -65,7 +77,11 @@ def inventory_loaded_response(
mapping_confirmed=True,
)
else:
task.inventory_lines_json = inventory_lines
linked_tasks = [
link.task
for link in (inv_file.links or [])
if link.is_active and link.task and _can_relink_inventory(link.task)
]
# [BE-放行-恢复] 库存内容已重新载入/复用,旧匹配结果必然失效:清空任务级派生状态,
# 强制 Gate 链路在下一轮重新匹配,避免复用旧快照的短缺/匹配结果而造成"库存已刷新
@@ -73,9 +89,6 @@ def inventory_loaded_response(
for affected in [task, *linked_tasks]:
if affected is None:
continue
affected.match_status = None
affected.line_results_json = None
affected.shortage_json = None
try:
order_lines = task_line_purpose_values(task)
@@ -127,6 +140,7 @@ def inventory_loaded_response(
"column_meta": column_meta,
"inventory_file_no": inv_file.inventory_file_no if inv_file else None,
"linked_task_nos": [item.task_no for item in linked_tasks],
"persist_lines": bool(persist_lines),
},
)
if commit:
@@ -144,5 +158,6 @@ def inventory_loaded_response(
"inventory_row_count": len(inventory_lines),
"field_alignment": field_alignment,
"warnings": warnings or [],
"persist_lines": bool(persist_lines),
},
)
@@ -56,8 +56,37 @@ def _required_catalog_field_ids(fields: dict[str, ShippingInventoryField]) -> se
return match_ids | quantity_ids
def _validate_definition(raw: Any) -> dict[str, Any]:
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。"""
# 异动(movement)用途的定死字段端点与必需字段集(领域定死,不依赖库存字段目录)。
def _required_movement_field_ids(definition: dict[str, Any]) -> set[str]:
"""校验 movement 用途的解析定义只引用定死领域字段,且必需字段齐全。"""
from app.services.in_transit_transfer.movement_contract import MOVEMENT_FIELDS
movement_codes = {field.code for field in MOVEMENT_FIELDS}
mapping = definition.get('field_mapping') or {}
mapped_codes = {str(code) for code in mapping.keys() if str(code).strip()}
unknown = mapped_codes - movement_codes
if unknown:
raise ValidationError(
f'Movement parsing profile references unknown field: {sorted(unknown)}',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
missing = {code for code in ('doc_no', 'material_code', 'quantity', 'movement_date') if code not in mapped_codes}
if missing:
raise ValidationError(
f'Movement parsing profile requires doc_no/material_code/quantity/movement_date: {sorted(missing)}',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
return mapped_codes
def _validate_definition(raw: Any, *, purpose: str = 'inventory') -> dict[str, Any]:
"""校验字段目录 ID 到来源表头的映射及订单明细匹配键,禁止自由脚本。
Args:
raw: 解析定义对象。
purpose: 'inventory'(沿用库存字段目录与 match_keys)或
'movement'(端点用定死 MOVEMENT_FIELDS,无 match_keys)。
"""
if not isinstance(raw, dict):
raise ValidationError('Parsing profile definition must be an object', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
field_mapping = raw.get('field_mapping')
@@ -65,6 +94,19 @@ def _validate_definition(raw: Any) -> dict[str, Any]:
raise ValidationError('Parsing profile requires complete field mapping', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if any(not str(value or '').strip() for value in field_mapping.values()):
raise ValidationError('Parsing profile field mapping is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
header_row_index = raw.get('header_row_index')
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if purpose == 'movement':
_required_movement_field_ids(raw)
return {
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
'header_row_index': header_row_index,
'field_mapping': {str(key).strip(): str(value).strip() for key, value in field_mapping.items()},
'match_keys': [],
}
catalog_fields = _catalog_fields(field_mapping)
_required_catalog_field_ids(catalog_fields)
match_keys = raw.get('match_keys')
@@ -87,9 +129,6 @@ def _validate_definition(raw: Any) -> dict[str, Any]:
seen_order_fields.add(field.id)
seen_inventory_fields.add(inventory_field)
normalized_keys.append({'order_field_id': field.id, 'inventory_field_id': inventory_field})
header_row_index = raw.get('header_row_index')
if header_row_index is not None and (not isinstance(header_row_index, int) or header_row_index < 1):
raise ValidationError('header_row_index is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
return {
'sheet_name': str(raw.get('sheet_name') or '').strip() or None,
'header_row_index': header_row_index,
@@ -151,7 +190,7 @@ def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
sample_analysis = profile.sample_analysis
return {
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'status': profile.status, 'file_format': profile.file_format,
'purpose': profile.purpose, 'version': profile.version, 'status': profile.status, 'file_format': profile.file_format,
'definition': profile.definition_json or {}, 'checksum': profile.checksum,
'published_at': profile.published_at.isoformat() if profile.published_at else None,
'source_count': len(profile.sources),
@@ -193,6 +232,15 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
next_version = int(db.session.query(func.max(ShippingInventoryParsingProfile.version)).filter_by(profile_code=code).scalar() or 0) + 1
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
db.session.add(profile)
purpose = str(data.get('purpose') or profile.purpose or 'inventory').strip().lower()
if purpose not in {'inventory', 'movement'}:
raise ValidationError('purpose is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if profile_id and purpose != profile.purpose:
raise ValidationError(
'Draft parsing profile purpose is immutable',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
profile.purpose = purpose
profile.display_name = str(data.get('display_name') or code).strip()
requested_file_format = str(data.get('file_format') or 'xlsx').lower()
if requested_file_format not in {'xls', 'xlsx', 'csv'}:
@@ -203,7 +251,7 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
profile.file_format = requested_file_format
definition = _validate_definition(data.get('definition'))
definition = _validate_definition(data.get('definition'), purpose=purpose)
if profile.file_format == 'csv' and definition.get('sheet_name'):
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
sample_analysis = _require_sample_evidence(
@@ -16,16 +16,19 @@ from app.models import (
ShippingInventoryFile,
ShippingInventoryPreparationAttempt,
ShippingInventoryPreparationSourceAttempt,
ShippingNotice,
ShippingOrderTask,
ShippingOrderCandidate,
ShippingTaskInventoryLink,
)
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint
from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
def create_inventory_preparation_round(
*, task: ShippingNotice, execution_id: int | None, recovery_plan_id: int | None,
*, task: ShippingOrderTask, execution_id: int | None, recovery_plan_id: int | None,
action_code: str, source_codes: list[str] | None = None, operation_id: str | None = None,
gate_attempt_id: int | None = None,
) -> ShippingInventoryPreparationAttempt:
@@ -50,8 +53,7 @@ def create_inventory_preparation_round(
db.session.flush()
codes = [str(code).strip().upper() for code in (source_codes or []) if str(code).strip()]
if not codes:
codes = [str(getattr(task, 'inventory_source_code', '') or '').strip().upper()]
codes = [code for code in codes if code]
codes = task_frozen_inventory_source_codes(task)
active_file = active_inventory_file_for_task(task)
for source_code in codes:
reusable, _reuse_reasons = check_inventory_snapshot_reusable(
@@ -76,8 +78,14 @@ def create_inventory_preparation_round(
)
db.session.add(source)
db.session.flush()
source_candidate = (
db.session.query(ShippingOrderCandidate)
.filter(ShippingOrderCandidate.consumed_task_id == int(task.id))
.order_by(ShippingOrderCandidate.id.desc())
.first()
)
round_row.combination_input_fingerprint = build_inventory_combination_fingerprint(
task_snapshot_fingerprint=str(getattr(task, 'content_fingerprint', '') or ''),
task_snapshot_fingerprint=str(getattr(source_candidate, 'content_fingerprint', '') or ''),
candidate_freeze_fingerprint=str(getattr(getattr(task, 'active_inventory_candidate_set', None), 'input_fingerprint', '') or ''),
sources=[
{
@@ -99,7 +107,7 @@ def create_inventory_preparation_round(
for item in round_row.source_attempts
],
reservation_version=str(getattr(task, 'order_data_version', '') or ''),
matching_rule_version=str(getattr(task, 'inventory_source_config_version', '') or ''),
matching_rule_version=str(active_inventory_runtime_facts(task).get('source_config_version') or ''),
)
db.session.flush()
return round_row
@@ -20,8 +20,8 @@ from typing import Any
from app import db
from app.core.errors import AppError, ServiceUnavailableError
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_RPA_PENDING
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask, ShippingTaskEvent
from app.services.shipping_notice.constants import POSITION_UPLOAD_REQ, PH_RPA_PENDING
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
from app.services.shipping_notice.inventory_snapshot_store import (
find_latest_ready_snapshot,
@@ -78,6 +78,30 @@ from app.services.shipping_notice.tool_response import tool_response
from app.services.shipping_notice.task_disposition_service import task_execution_block_reason
def _workflow_owner(task: ShippingNotice | ShippingOrderTask) -> ShippingNotice | ShippingOrderTask:
"""将正式 Notice 输入解析为 OT owner;库存运行事实统一写入 OT。"""
if isinstance(task, ShippingOrderTask):
return task
order_task_id = getattr(task, 'order_task_id', None)
if order_task_id:
owner = db.session.get(ShippingOrderTask, int(order_task_id))
if owner is not None:
return owner
return task
def _set_workflow_error(task: ShippingNotice | ShippingOrderTask, message: str | None) -> None:
"""写入库存流程错误;正式 Notice 通过关联 OT 承接。"""
owner = _workflow_owner(task)
if hasattr(owner, 'error_message'):
owner.error_message = message
def _workflow_error(task: ShippingNotice | ShippingOrderTask) -> str | None:
"""读取库存流程错误;正式 Notice 通过关联 OT 承接。"""
return getattr(_workflow_owner(task), 'error_message', None)
def latest_task_event(task: ShippingNotice, event_type: str) -> ShippingTaskEvent | None:
"""返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试用)。"""
if task.id is None:
@@ -160,34 +184,22 @@ def _try_reuse_inventory_snapshot(
)
db.session.flush()
cached_lines = [
row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)
]
if cached_lines:
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
try:
lines, column_meta = read_inventory_file_lines(snapshot)
except (OSError, ValueError, AppError):
lines, column_meta = [], {}
if lines:
# 复用:行缓存已由 read_inventory_file_lines 保证;只 Link + 推进,不覆盖 File。
return inventory_loaded_response(
task,
cached_lines,
column_meta={"source": "snapshot_reuse"},
lines,
column_meta=column_meta,
source="snapshot_reuse",
event_type="inventory_snapshot_reused",
persist_lines=False,
)
path = Path(snapshot.storage_path)
if path.is_file():
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
lines, column_meta = parse_inventory_snapshot_file(snapshot)
if lines:
snapshot.inventory_lines_json = lines
snapshot.line_count = len(lines)
return inventory_loaded_response(
task,
lines,
column_meta=column_meta,
source="snapshot_reuse",
event_type="inventory_snapshot_reused",
)
db.session.commit()
return tool_response(
status="running",
@@ -209,9 +221,11 @@ def _save_last_inventory_rpa_runtime(task: ShippingNotice, payload: dict[str, An
source_code = str(payload.get("source_code") or "").strip()
if source_code:
runtime["source_code"] = source_code
step_payload = dict(task.step_payload_json or {})
step_payload["last_inventory_rpa_runtime"] = runtime
task.step_payload_json = step_payload
owner = _workflow_owner(task)
if hasattr(owner, 'step_payload_json'):
step_payload = dict(owner.step_payload_json or {})
step_payload["last_inventory_rpa_runtime"] = runtime
owner.step_payload_json = step_payload
return runtime
@@ -252,10 +266,10 @@ def inventory_rpa_wait_seconds(task: ShippingNotice) -> tuple[int | None, int |
Returns:
tuple[int | None, int | None, int | None]: (elapsed_seconds, timeout_seconds, remaining_seconds)。
"""
if (
task.pending_human_reason != PH_RPA_PENDING
or task.inventory_lines_json
):
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
if task_blocking_reason(task) != PH_RPA_PENDING or has_ready_inventory_file_for_task(task):
return None, None, None
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
if not last_trigger or not isinstance(last_trigger.created_at, datetime):
@@ -301,24 +315,43 @@ def maybe_recheck_inventory_rpa_wait(task: ShippingNotice, *, source: str = "wor
"inventory_rpa_wait_rechecked",
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
)
# [STEP] 单次 RPA 触发已超时且无更晚成功回执:不做自动重试,记录超时失败并落
# rpa_exhausted 人工接管;两个事件供审计/前端识别“等待超时 → 重试耗尽”。
log_task_event(
task,
"inventory_rpa_failed",
{
"error": "timeout",
"elapsed_seconds": elapsed,
"timeout_seconds": timeout_seconds,
},
)
log_task_event(
task,
"inventory_rpa_exhausted",
{"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
)
db.session.flush()
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
task.error_message = "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel"
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
_set_workflow_error(task, "RPA 库存导出等待超时,已停止自动重试,请选择重新获取库存或上传库存 Excel")
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=task.error_message,
message=_workflow_error(task),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
position=POSITION_UPLOAD_REQ,
)
def _expected_snapshot_identity_from_task(task: ShippingNotice) -> tuple[str, str]:
"""从任务正式库存身份推导快照预期二元组。"""
from app.services.shipping_notice.inventory_source_gate import task_inventory_identity
identity = task_inventory_identity(task)
return (
str(task.inventory_source_code or "").strip().upper(),
str(task.inventory_warehouse_id or "").strip().upper(),
str(identity['inventory_source_code'] or "").strip().upper(),
str(identity['inventory_warehouse_id'] or "").strip().upper(),
)
@@ -627,23 +660,29 @@ def _resolve_effective_callback_run_no(task: ShippingNotice, payload: dict[str,
return _expected_rpa_callback_run_no(task)
def _lock_task_for_rpa_callback(task: ShippingNotice) -> ShippingNotice:
"""对任务行加悲观锁,防止并发回调重复消费同一轮次。"""
def _lock_task_for_rpa_callback(task: ShippingOrderTask) -> ShippingOrderTask:
"""对订单任务行加悲观锁,防止并发回调重复消费同一轮次。"""
if task.id is None:
return task
# ShippingNotice 默认关系加载会带 shipping_case 外连接;PostgreSQL 不允许
# 对外连接空值端执行 FOR UPDATE。回调只需锁任务主表,避免成功文件回调在入库前失败。
return (
db.session.query(ShippingNotice)
db.session.query(ShippingOrderTask)
.filter_by(id=task.id)
.with_for_update(of=ShippingNotice)
.with_for_update(of=ShippingOrderTask)
.one()
)
def _get_consumed_inventory_rpa_run_no(task: ShippingNotice) -> str:
"""读取已消费(处理完成)的 RPA 轮次 run_no。"""
return str(task.inventory_rpa_consumed_run_no or "").strip()
from app.models import ShippingTaskInventoryRpaAttempt
attempt = (
ShippingTaskInventoryRpaAttempt.query
.filter_by(task_no=str(task.task_no or ''), status='consumed')
.order_by(ShippingTaskInventoryRpaAttempt.consumed_at.desc(), ShippingTaskInventoryRpaAttempt.id.desc())
.first()
)
return str(getattr(attempt, 'source_run_no', '') or '').strip()
def _mark_inventory_rpa_run_no_consumed(task: ShippingNotice, run_no: str) -> None:
@@ -651,7 +690,16 @@ def _mark_inventory_rpa_run_no_consumed(task: ShippingNotice, run_no: str) -> No
effective = str(run_no or "").strip()
if not effective:
return
task.inventory_rpa_consumed_run_no = effective
from app.models import ShippingTaskInventoryRpaAttempt
attempt = (
ShippingTaskInventoryRpaAttempt.query
.filter_by(task_no=str(task.task_no or ''), source_run_no=effective)
.one_or_none()
)
if attempt is not None:
attempt.status = 'consumed'
attempt.consumed_at = datetime.utcnow()
def _validate_rpa_callback_not_replayed(task: ShippingNotice, run_no: str) -> str | None:
@@ -789,7 +837,7 @@ def _validate_rpa_callback_gate(task: ShippingNotice) -> dict[str, Any] | None:
"order_missing_preview": reservation_issues[:5],
},
},
checkpoint="rsv_req",
position="rsv_req",
stop_agent_turn=True,
)
@@ -811,7 +859,9 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
核心逻辑:动态 Source 的 Warehouse 由库存行按 Reservation + PN 解析,回调不预先裁决。
"""
callback_source = str(payload.get("source_code") or "").strip().upper()
task_source = str(task.inventory_source_code or "").strip().upper()
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
task_sources = set(task_frozen_inventory_source_codes(task))
if not callback_source:
return tool_response(
status="failed",
@@ -819,7 +869,7 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
message="RPA 成功回调缺少 source_code,已拒绝入库",
data=serialize_task_for_tool(task),
)
if not task_source or callback_source != task_source:
if callback_source not in task_sources:
return tool_response(
status="failed",
task=task,
@@ -829,10 +879,12 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_database_inventory_source(task_source)
source = get_database_inventory_source(callback_source)
is_fixed = source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed'
callback_wh = str(payload.get("warehouse_id") or "").strip().upper()
task_wh = str(task.inventory_warehouse_id or "").strip().upper()
from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id
task_wh = resolve_inventory_source_warehouse_id(task, source=source) or ''
if is_fixed and (not callback_wh or callback_wh != task_wh):
return tool_response(
status="failed",
@@ -1026,7 +1078,9 @@ def _batch_snapshot_verify_warehouse_id(
if str(source.get('warehouse_resolution_mode') or '').lower() == 'inventory_match':
return None
if task:
warehouse_id = str(task.inventory_warehouse_id or "").strip().upper()
from app.services.shipping_notice.inventory_source_gate import resolve_inventory_source_warehouse_id
warehouse_id = resolve_inventory_source_warehouse_id(task, source=source) or ''
return warehouse_id or None
if item is not None:
warehouse_id = str(item.get("warehouse_id") or "").strip().upper()
@@ -1062,8 +1116,20 @@ def _validate_batch_callback_worker_identity(item: dict[str, Any], source: dict[
return None
def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, Any]:
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。"""
def ensure_inventory_via_rpa(
task: ShippingNotice,
*,
mode: str,
allow_auto_retry: bool = True,
source_codes: list[str] | None = None,
) -> dict[str, Any]:
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。
Args:
allow_auto_retry: 只读轮询开关,透传 ensure_all_required_sources_prepared。
poll_inventory_preparation 查询路径必须传 False,禁止轮询自动新建 RPA Attempt。
source_codes: 可选行级库存源;有值时只为这些源准备/触发 RPA,不跑整单冻结源。
"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
manual_retry_round = mode == "retry_rpa"
@@ -1101,7 +1167,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
"order_missing_preview": reservation_issues[:5],
},
},
checkpoint="rsv_req",
position="rsv_req",
stop_agent_turn=True,
)
@@ -1110,31 +1176,38 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
assert_inventory_source_gate(task, operation="ensure_inventory_via_rpa")
except AppError:
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
task.current_step = "step2_parse_confirm"
task.error_message = "库存源尚未确定,无法启动 RPA"
# OT 在正式 Notice 创建前只保存阶段;不得写 Notice 专属 current_step。
task.stage = "inventory_source_resolving"
_set_workflow_error(task, "库存源尚未确定,无法启动 RPA")
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
data=serialize_task_for_tool(task),
checkpoint=CP_INVENTORY_SOURCE_REVIEW,
position=POSITION_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
rpa_source = task_rpa_inventory_source(task) or {}
# 首次自动与人工重试都必须创建逐源 Attempt。只有该路径会冻结
# 首次自动与人工显式重试才可能创建逐源 Attempt;自动路径读到失败事实时
# 必须收口,不能重试。只有该路径会冻结
# source_run_no/lease_token/candidate_set/execution/gate 身份,Worker 回调才可精确收口。
# 下方保留的旧单票逻辑仅用于历史代码阅读,所有受支持 mode 均在这里返回。
if mode in {'auto', 'retry_rpa'}:
from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared
prepared = ensure_all_required_sources_prepared(task, mode=mode)
prepared = ensure_all_required_sources_prepared(
task,
mode=mode,
allow_auto_retry=allow_auto_retry,
source_codes=source_codes,
)
db.session.flush()
if prepared.pending_source_codes:
apply_task_transition(task, TaskTransition.RPA_PENDING)
task.error_message = None
_set_workflow_error(task, None)
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
@@ -1158,6 +1231,11 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
)
if prepared.all_prepared:
return tool_response(status='completed', task=task, message='库存快照已准备完成。')
# [只读轮询失败语义] poll(allow_auto_retry=False)查询到源失败事实时返回
# status='failed'(executor 的 _tool_outcome 映射为 blocked_retryable):
# 失败是可重试的技术结果,不是需要用户决策的人工阻断;重试由用户显式动作发起。
# 显式重试/首次投递路径(allow_auto_retry=True)维持 needs_human 人工兑底。
poll_read_only = not allow_auto_retry
set_task_step_progress(
task,
step_key='step3_inventory_prepare',
@@ -1172,11 +1250,12 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
)
db.session.commit()
return tool_response(
status='needs_human', task=task,
status='failed' if poll_read_only else 'needs_human', task=task,
message='库存 RPA 未能为全部库存源生成结果。',
data={**serialize_task_for_tool(task), 'rpa': {
'failed_source_codes': prepared.failed_source_codes,
'source_attempts': prepared.source_attempts,
'poll_read_only': poll_read_only,
}},
)
@@ -1188,10 +1267,10 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
# [STEP 1] 先检查当前是否已有进行中的 RPA 导出。
# 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。
timeout_seconds = rpa_inventory_timeout_seconds()
if (
task.pending_human_reason == PH_RPA_PENDING
and not task.inventory_lines_json
):
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
if task_blocking_reason(task) == PH_RPA_PENDING and not has_ready_inventory_file_for_task(task):
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
if last_trigger and isinstance(last_trigger.created_at, datetime):
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
@@ -1215,7 +1294,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
)
last_failed = latest_task_event(task, "inventory_rpa_failed")
if not last_failed or (last_failed.created_at < last_trigger.created_at):
task.error_message = "RPA 库存导出等待超时"
_set_workflow_error(task, "RPA 库存导出等待超时")
log_task_event(
task,
"inventory_rpa_failed",
@@ -1227,14 +1306,14 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
)
db.session.flush( )
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
task.error_message = "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel"
_set_workflow_error(task, "RPA 库存导出等待超时,请选择重新获取库存或上传库存 Excel")
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=task.error_message,
message=_workflow_error(task),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
position=POSITION_UPLOAD_REQ,
)
# [STEP 2] 仅本次用户或系统明确触发可创建一次 RPA 尝试。
@@ -1256,10 +1335,10 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
except ServiceUnavailableError as exc:
trigger = None
detail_message = str((exc.details or {}).get("detail_message") or exc.message or RPA_WORKER_OFFLINE_MESSAGE)
task.error_message = detail_message[:500]
_set_workflow_error(task, detail_message[:500])
if trigger:
apply_task_transition(task, TaskTransition.RPA_PENDING)
task.error_message = None
_set_workflow_error(task, None)
progress_message = (
"已重新触发库存获取,等待结果"
if manual_retry_round
@@ -1312,14 +1391,14 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
offline_message = (task.error_message or "").strip()
offline_message = (_workflow_error(task) or "").strip()
if offline_message == RPA_WORKER_OFFLINE_MESSAGE:
human_message = RPA_WORKER_OFFLINE_MESSAGE
detail = "请启动 Windows RPA 服务后重试,或手动上传货代库存 Excel。"
else:
human_message = "RPA 库存目录未配置或触发失败"
detail = "请重新获取库存,或手动上传货代库存 Excel。"
task.error_message = human_message[:500]
_set_workflow_error(task, human_message[:500])
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
@@ -1338,7 +1417,7 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An
task=task,
message=f"{human_message}。请上传货代库存 Excel。" if human_message != RPA_WORKER_OFFLINE_MESSAGE else human_message,
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
position=POSITION_UPLOAD_REQ,
)
@@ -1469,15 +1548,7 @@ def _handle_rpa_inventory_skipped(
detail = str(payload.get("message") or payload.get("error_message") or "").strip()
message = _inventory_rpa_skipped_message(skip_reason=skip_reason, detail=detail)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
task.error_message = None
step_payload = dict(task.step_payload_json or {})
step_payload["inventory_rpa_skipped"] = {
"skip_reason": skip_reason,
"message": detail or message,
"reported_at": datetime.utcnow().isoformat(),
"rpa_runtime": runtime,
}
task.step_payload_json = step_payload
_set_workflow_error(task, None)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
@@ -1506,7 +1577,7 @@ def _handle_rpa_inventory_skipped(
task=task,
message=message,
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
position=POSITION_UPLOAD_REQ,
)
@@ -1519,9 +1590,9 @@ def _handle_rpa_inventory_failed(
) -> dict[str, Any]:
"""处理 failed 回调:记录失败事实并保留用户可重试/上传的恢复入口。"""
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500]
_set_workflow_error(task, str(payload.get("error_message") or "RPA inventory export failed")[:500])
log_task_event(task, "inventory_rpa_failed", {
"error": task.error_message,
"error": _workflow_error(task),
"error_code": str(payload.get("error_code") or "rpa_export_failed"),
"rpa_runtime": runtime,
})
@@ -1530,7 +1601,7 @@ def _handle_rpa_inventory_failed(
step_key='step3_inventory_prepare',
step_title='获取库存',
status='needs_human',
message=task.error_message,
message=_workflow_error(task),
progress_percent=100,
detail='请重新获取库存或上传库存 Excel。',
extra={'error_code': str(payload.get('error_code') or 'rpa_export_failed')},
@@ -1544,11 +1615,51 @@ def _handle_rpa_inventory_failed(
return tool_response(
status="needs_human",
task=task,
message=task.error_message,
message=_workflow_error(task),
data=serialize_task_for_tool(task),
)
def settle_failed_inventory_callback(payload: dict[str, Any], *, error: str) -> None:
"""收口回调处理失败,避免 RPA Attempt 与 Gate 留在外部等待。"""
from app.models import ShippingProcessExecution
from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
for item in payload.get('results') or []:
if not isinstance(item, dict):
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()
task = resolve_task_from_payload({'task_no': task_no}, allow_conversation_fallback=False)
if not isinstance(task, ShippingOrderTask) or not source_code or not source_run_no:
continue
task = _lock_task_for_rpa_callback(task)
per_source_callback_handler(
task,
source_code=source_code,
run_no=source_run_no,
callback_payload={
**dict(item),
'schema_version': str(payload.get('schema_version') or item.get('schema_version') or ''),
'error_code': 'callback_processing_failed',
'error_message': error,
},
)
_handle_rpa_inventory_failed(
task,
{'error_code': 'callback_processing_failed', 'error_message': error},
_save_last_inventory_rpa_runtime(task, payload),
commit=False,
)
if task.active_process_execution_id:
execution = db.session.get(ShippingProcessExecution, int(task.active_process_execution_id))
if execution is not None and str(execution.status or '').lower() != 'superseded':
sync_fulfillment_gates_from_task(execution=execution, actor_type='system')
db.session.commit()
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
@@ -1756,7 +1867,9 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
trigger_type="on_demand",
success=True,
user_id=task.user_id,
verify_warehouse_id=task_wh if (task_wh := str(task.inventory_warehouse_id or "").strip().upper()) else None,
verify_warehouse_id=(
_expected_snapshot_identity_from_task(task)[1] or None
),
)
if not created_new:
reuse_error = _validate_reused_snapshot_callback_file(inv_file, path)
@@ -2044,6 +2157,43 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
)
def _resolve_shared_inventory_drop_file(raw_path: str, *, allowed_root: Path) -> Path | None:
"""将 Worker 回调中的 file_path 解析为 Linux 侧共享 drop 内的真实文件。
Windows Worker 上报 ``C:\\HxopsRpaTest\\data\\inventory_drop\\file.xlsx``,
Ubuntu 后端通过 ``/mnt/hxops-rpa-*-data/inventory_drop/file.xlsx`` 读同一 SMB 文件。
安全约束:仅允许 ``allowed_root`` 下按文件名映射,拒绝路径穿越。
"""
text = str(raw_path or '').strip()
if not text:
return None
try:
root = allowed_root.resolve()
except OSError:
return None
candidate = Path(text)
try:
resolved = candidate.resolve()
if resolved.is_file():
resolved.relative_to(root)
return resolved
except (OSError, ValueError, RuntimeError):
pass
name = Path(text.replace('\\', '/')).name.strip()
if not name or name in {'.', '..'} or '/' in name or '\\' in name:
return None
mapped = (root / name).resolve()
try:
mapped.relative_to(root)
except ValueError:
return None
if mapped.is_file():
return mapped
return None
def _persist_batch_callback_receipt(
payload: dict[str, Any],
*,
@@ -2084,12 +2234,8 @@ def _persist_batch_callback_receipt(
continue
raw_path = str(item.get('file_path') or '').strip()
source_path = Path(raw_path).resolve() if raw_path else None
if source_path is None or not source_path.is_file():
return None
try:
source_path.relative_to(allowed_root)
except ValueError:
source_path = _resolve_shared_inventory_drop_file(raw_path, allowed_root=allowed_root)
if source_path is None:
return None
suffix = source_path.suffix.lower()
@@ -2120,27 +2266,34 @@ def _received_batch_callback_file_path(
callback_id: str,
) -> Path | None:
"""验证 batch 处理可读取的文件仅来自 RPA drop 或本回调受控收件区。"""
candidate = Path(file_path).resolve() if file_path else None
if candidate is None or not candidate.is_file():
return None
allowed_roots: list[Path] = []
drop_dir = inventory_drop_dir()
if drop_dir is not None:
allowed_roots.append(drop_dir.resolve())
from app.services.shipping_notice.export import _storage_root
safe_callback_id = ''.join(
char if char.isalnum() or char in {'-', '_'} else '_'
for char in callback_id
).strip('_') or 'unknown'
allowed_roots.append((_storage_root() / 'rpa_callback_receipts' / safe_callback_id).resolve())
for allowed_root in allowed_roots:
try:
candidate.relative_to(allowed_root)
return candidate
except ValueError:
continue
return None
receipt_root = (_storage_root() / 'rpa_callback_receipts' / safe_callback_id).resolve()
drop_dir = inventory_drop_dir()
if drop_dir is not None:
mapped = _resolve_shared_inventory_drop_file(file_path, allowed_root=drop_dir)
if mapped is not None:
return mapped
text = str(file_path or '').strip()
if not text:
return None
try:
candidate = Path(text).resolve()
except (OSError, RuntimeError):
return None
if not candidate.is_file():
return None
try:
candidate.relative_to(receipt_root)
return candidate
except ValueError:
return None
def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
@@ -2577,7 +2730,8 @@ def process_rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any
**(inv_file.schema_preview_json or {}),
'structure_validation': column_meta['structure_validation'],
}
if lines and str(getattr(task, 'upload_status', None) or '').strip().lower() not in {'uploaded', 'succeeded', 'success'} and str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower() == 'active':
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
if lines and not has_verified_upload_success(task) and str(getattr(task, 'lifecycle_status', 'active') or 'active').strip().lower() == 'active':
inventory_loaded_response(
task,
lines,
@@ -2805,7 +2959,7 @@ def _validate_repair_inventory_snapshot(
return "inventory_source_unstable"
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_database_inventory_source(task.inventory_source_code)
source = get_database_inventory_source(inv_file.source_code)
if source and str(source.get('warehouse_resolution_mode') or '').lower() == 'fixed':
if not inventory_identities_match(
task,
@@ -18,7 +18,9 @@ from sqlalchemy import event as _sa_event
from sqlalchemy.orm import Session
from app import db
from app.core.errors import AppError
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
from app.services.shipping_notice.tool_common import task_event_task_id
from app.services.shipping_notice.inventory_file_store import (
_can_relink_inventory,
generate_inventory_file_no,
@@ -468,24 +470,24 @@ def link_snapshot_to_task(
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_database_inventory_source(task.inventory_source_code)
source = get_database_inventory_source(inv_file.source_code)
if source is None:
return None
resolved_warehouse_id = inv_file.warehouse_id
if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'inventory_match':
from app.services.shipping_notice.inventory_warehouse_resolution import resolve_dynamic_warehouse
lines = [row for row in (inv_file.inventory_lines_json or []) if isinstance(row, dict)]
if not lines and Path(inv_file.storage_path).is_file():
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
lines, _column_meta = parse_inventory_snapshot_file(inv_file)
inv_file.inventory_lines_json = lines
inv_file.line_count = len(lines)
try:
lines, _column_meta = read_inventory_file_lines(inv_file)
except (OSError, ValueError, AppError):
lines = []
resolution = resolve_dynamic_warehouse(
task=task,
inventory_lines=lines,
fallback_warehouse_id=inv_file.warehouse_id,
source_code=inv_file.source_code,
)
if not resolution.warehouse_id:
# identity_status 受数据库枚举约束,仅保存状态;具体动态仓解析原因
@@ -513,10 +515,6 @@ def link_snapshot_to_task(
if not identity_ok:
return None
# 动态 Source 不预维护 Warehouse;以已校验库存文件的 Warehouse 固化本任务身份。
if not task.inventory_warehouse_id:
task.inventory_warehouse_id = resolved_warehouse_id
link = replace_task_inventory_link(task, inv_file, role=role)
link.link_reason = reason
link.matched_warehouse_id = resolved_warehouse_id
@@ -533,10 +531,9 @@ def link_snapshot_to_task(
"inventory_file_no": inv_file.inventory_file_no,
"trigger_type": (inv_file.source_query_json or {}).get("trigger_type"),
}
task.inventory_snapshot_id = inv_file.id
db.session.add(
ShippingTaskEvent(
task_id=task.id,
task_id=task_event_task_id(task),
event_type="inventory_snapshot_linked",
detail_json={
"inventory_file_no": inv_file.inventory_file_no,
@@ -574,7 +571,7 @@ def link_snapshot_to_task_for_preparation(
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
source = get_database_inventory_source(task.inventory_source_code)
source = get_database_inventory_source(inv_file.source_code)
if (
source is None
or str(source.get('warehouse_resolution_mode') or '').strip().lower() != 'inventory_match'
@@ -595,7 +592,6 @@ def link_snapshot_to_task_for_preparation(
'inventory_file_no': inv_file.inventory_file_no,
'identity_status': inv_file.identity_status,
}
task.inventory_snapshot_id = inv_file.id
return link
@@ -1,9 +1,10 @@
"""
services/shipping_notice/inventory_source_gate.py
用途:库存源稳定性门禁、独立字段写入与路由指纹管理。
依赖:inventory_source_rules、inventory_source_repository、models.ShippingNotice、core.errors。
用途:库存源稳定性门禁;路由真相由 CandidateSet 承接,库存文件由 Link 承接。
依赖:inventory_source_rules、inventory_source_repository、models.ShippingOrderTask、core.errors。
逻辑:动态订单抽取先裁决线索;STP 建单可冻结单/多候选(candidates_frozen 视为可进入库存准备);
apply 仅冻结 resolved/ambiguous/candidates_frozen;unresolved 不得写入全源 CandidateSet;
解析确认通过后未稳定才进入 inventory_source_review;RPA/库存/匹配/导出统一经本模块硬门禁。
"""
@@ -12,7 +13,7 @@ from __future__ import annotations
from typing import Any
from app.core.errors import AppError
from app.models import ShippingNotice
from app.models import ShippingOrderTask
from app.services.shipping_notice.inventory_source_rules import (
InventorySourceAdjudication,
adjudicate_inventory_source,
@@ -29,8 +30,6 @@ from app.services.shipping_notice.inventory_source_repository import (
)
STABLE_INVENTORY_SOURCE_STATUSES = frozenset({"resolved", "candidates_frozen"})
INVENTORY_SOURCE_ERROR_CODES = {
"unresolved": "SHIPPING.INVENTORY_SOURCE_UNRESOLVED",
"ambiguous": "SHIPPING.INVENTORY_SOURCE_AMBIGUOUS",
@@ -42,7 +41,7 @@ INVENTORY_SOURCE_ERROR_CODES = {
}
def is_inventory_source_stable(task: ShippingNotice) -> bool:
def is_inventory_source_stable(task: ShippingOrderTask) -> bool:
"""
判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
@@ -50,135 +49,87 @@ def is_inventory_source_stable(task: ShippingNotice) -> bool:
STP 多候选冻结(candidates_frozen)在候选非空且各候选源存在时视为稳定。
不比对全局配置版本 hash 或路由指纹——无关库存源的改动不使本任务失效。
"""
status = str(task.inventory_source_status or "").strip()
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
return False
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_lines
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
if status == "candidates_frozen":
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
codes = task_frozen_inventory_source_codes(task)
return bool(codes) and all(get_database_inventory_source(code) for code in codes)
code = str(task.inventory_source_code or "").strip().upper()
if not code:
codes = task_frozen_inventory_source_codes(task)
lines = get_active_candidate_lines(task)
if not codes or not lines or any(not list(row.source_codes_json or []) for row in lines):
return False
connector_type = str(task.inventory_connector_type or "").strip()
if not connector_type:
return False
source = get_database_inventory_source(code)
if not source:
return False
if connector_type != str(source.get("connector_type") or "").strip():
return False
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
fixed_warehouse = str(source.get('fixed_warehouse_id') or '').strip().upper()
task_warehouse = str(task.inventory_warehouse_id or '').strip().upper()
if mode == 'fixed' and task_warehouse != fixed_warehouse:
return False
for code in codes:
source = get_database_inventory_source(code)
if not source:
return False
if str(source.get('warehouse_resolution_mode') or '').strip().lower() == 'fixed' and not str(source.get('fixed_warehouse_id') or '').strip():
return False
return True
def routing_fingerprint_changed(task: ShippingNotice, context: dict[str, Any]) -> bool:
def routing_fingerprint_changed(task: ShippingOrderTask, context: dict[str, Any]) -> bool:
"""比较当前路由上下文与任务已存指纹,判断库存源裁决是否因事实变化失效。"""
previous = str(task.inventory_routing_fingerprint or "").strip()
from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set
current = get_active_candidate_set(task)
previous = str((getattr(current, 'routing_rule_version_json', None) or {}).get('routing_fingerprint') or '').strip()
if not previous:
return False
return previous != compute_routing_fingerprint(context)
def inventory_source_config_changed(task: ShippingNotice) -> bool:
def inventory_source_config_changed(task: ShippingOrderTask) -> bool:
"""
配置变更判定(档位一收窄):仅当任务实际选中的库存源自身不再可用时才算配置已变。
核心逻辑:不再比对全局配置版本 hash——无关库存源的改动不影响本任务;
只检查任务冻结时选中的源(或冻结候选集)当前是否仍可用(存在且启用、驱动一致)。
"""
status = str(task.inventory_source_status or "").strip()
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
# 未稳定任务沿用旧语义:已有裁决状态即视为需要重新裁决。
return bool(status)
return not is_inventory_source_stable(task)
def apply_destination_fields(task: ShippingNotice, context: dict[str, Any]) -> None:
"""将标准化目的地线索写入任务独立字段。"""
task.destination_code = str(context.get("destination_code") or "").strip().upper() or None
task.destination_city = str(context.get("destination_city") or "").strip() or None
task.destination_country = str(context.get("destination_country") or "").strip().upper() or None
task.warehouse_hint = str(context.get("warehouse_hint") or "").strip() or None
def clear_inventory_source_confirmation(task: ShippingNotice) -> None:
def clear_inventory_source_confirmation(task: ShippingOrderTask) -> None:
"""路由指纹或配置版本变化时清除历史人工确认信息及过期 RPA 参数。"""
task.inventory_source_confirmed_by = None
task.inventory_source_confirmed_at = None
if str(task.inventory_source_status or "").strip() == "user_confirmed":
task.inventory_source_status = "unresolved"
task.inventory_source_method = None
payload = dict(task.step_payload_json or {})
payload = dict(getattr(task, 'step_payload_json', None) or {})
payload.pop("rpa_inventory_source", None)
task.step_payload_json = payload
def apply_inventory_source_adjudication(
task: ShippingNotice,
task: ShippingOrderTask,
adjudication: InventorySourceAdjudication,
*,
execution_id: int | None = None,
) -> None:
"""
将裁决结果写入任务独立字段,并同步候选/证据到 step_payload_json。
核心逻辑:正式身份以独立字段为准;JSON 仅承载展示与审计辅助信息。
将裁决结果冻结为 CandidateSet;无候选时由 Gate 保存阻断事实。
核心逻辑:仅 resolved / ambiguous / candidates_frozen 且候选非空时冻结;
unresolved/conflicted/invalid 即使误带候选也不得冻结(防全源兜底污染)。
Args:
execution_id: 可选;传给 ``freeze_candidates_for_task``,使重冻结不撤销当前
正在执行的门禁链(否则会误 supersede 活动 Execution)。
"""
context = extract_routing_context(task)
fingerprint = adjudication.routing_fingerprint or compute_routing_fingerprint(context)
task.inventory_routing_fingerprint = fingerprint
apply_destination_fields(task, context)
task.inventory_source_status = adjudication.status
task.inventory_source_method = adjudication.method or None
task.inventory_source_config_version = adjudication.config_version or inventory_sources_runtime_version()
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
task.inventory_source_code = adjudication.source_code
task.inventory_connector_type = adjudication.connector_type
task.inventory_warehouse_id = adjudication.warehouse_id or None
elif adjudication.status not in STABLE_INVENTORY_SOURCE_STATUSES:
task.inventory_source_code = None
task.inventory_connector_type = None
task.inventory_warehouse_id = None
payload = dict(task.step_payload_json or {})
payload.pop("rpa_inventory_source", None)
task.step_payload_json = payload
payload = dict(task.step_payload_json or {})
payload["inventory_source_resolution"] = {
"status": adjudication.status,
"method": adjudication.method,
"reason": adjudication.reason,
"destination_candidates": adjudication.destination_candidates,
"candidates": adjudication.candidates,
"evidence": adjudication.evidence,
"conflicts": adjudication.conflicts,
"config_version": adjudication.config_version,
"routing_fingerprint": fingerprint,
}
if adjudication.status in STABLE_INVENTORY_SOURCE_STATUSES and adjudication.source_code:
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
rpa_source = task_rpa_inventory_source(task)
if rpa_source:
payload["rpa_inventory_source"] = rpa_source
else:
payload.pop("rpa_inventory_source", None)
task.step_payload_json = payload
status = str(adjudication.status or '').strip().lower()
if status not in {'resolved', 'ambiguous', 'candidates_frozen'}:
return
if any(str(item.get('source_code') or '').strip() for item in (adjudication.candidates or []) if isinstance(item, dict)):
freeze_candidates_for_task(
task, adjudication=adjudication, execution_id=execution_id,
)
def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication:
def adjudicate_and_apply_inventory_source(
task: ShippingOrderTask,
*,
execution_id: int | None = None,
) -> InventorySourceAdjudication:
"""
对任务执行库存源裁决并写入独立字段。
【AI 触发时机】:订单抽取提交完成后由后端编排调用;重解析时同样调用以刷新裁决。
【AI 触发时机】:订单抽取提交完成后由后端编排调用;重解析时同样调用以刷新裁决;
库存准备 Gate 在任务尚无冻结候选源时补裁决(传入当前 execution_id 以避免撤销活动链)。
Args:
execution_id: 可选;透传给冻结服务,使重冻结不撤销当前正在执行的门禁链。
"""
context = extract_routing_context(task)
if inventory_source_config_changed(task) or routing_fingerprint_changed(task, context):
@@ -201,7 +152,9 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour
)
):
try:
freeze_result = freeze_candidates_for_task(task, adjudication=adjudication)
freeze_result = freeze_candidates_for_task(
task, adjudication=adjudication, execution_id=execution_id,
)
# 冻结成功后升级裁决为 candidates_frozen;apply_inventory_source_adjudication 会再写一次字段,
# 但冻结服务已写好 task.status=method=config=fingerprint,结果一致。
evidence_merged = list(adjudication.evidence or [])
@@ -232,12 +185,12 @@ def adjudicate_and_apply_inventory_source(task: ShippingNotice) -> InventorySour
# 保留原 ambiguous 让下游 is_inventory_source_stable 正确进入规则重算阻断。
pass
apply_inventory_source_adjudication(task, adjudication)
apply_inventory_source_adjudication(task, adjudication, execution_id=execution_id)
return adjudication
def transition_task_to_inventory_source_review(
task: ShippingNotice,
task: ShippingOrderTask,
adjudication: InventorySourceAdjudication,
*,
error_message: str | None = None,
@@ -245,15 +198,17 @@ def transition_task_to_inventory_source_review(
"""
将任务持久化到库存源规则重算检查点,并写入候选裁决信息。
核心逻辑:保留 checkpoint 作为内部恢复事实,但不产生人工选源按钮;
解析复核必须在进入本检查点前完成,不保存延后复核标记。
核心逻辑:写入 INVENTORY_SOURCE_REVIEW 过渡与 stage,但不产生人工选源按钮;
解析复核必须在进入本阶段前完成,不保存延后复核标记。
"""
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
apply_task_transition(task, TaskTransition.INVENTORY_SOURCE_REVIEW)
task.current_step = "step2_parse_confirm"
# OT 的流程阶段字段是 stage;current_step 属于已创建 Notice 的历史工作流,
# 不能在通知准备前写入 OT。
task.stage = "inventory_source_resolving"
task.error_message = error_message or "无法根据发货通知唯一确定库存查询来源"
payload = dict(task.step_payload_json or {})
payload = dict(getattr(task, 'step_payload_json', None) or {})
payload["inventory_source_resolution"] = {
"status": adjudication.status,
"method": adjudication.method,
@@ -268,7 +223,7 @@ def transition_task_to_inventory_source_review(
task.step_payload_json = payload
def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourceAdjudication:
def ensure_inventory_source_review_state(task: ShippingOrderTask) -> InventorySourceAdjudication:
"""
对已通过解析确认但库存源仍不稳定的任务,补做规则裁决并落库到内部恢复检查点。
@@ -282,7 +237,7 @@ def ensure_inventory_source_review_state(task: ShippingNotice) -> InventorySourc
def assert_inventory_source_gate(
task: ShippingNotice,
task: ShippingOrderTask,
*,
operation: str = "continue",
) -> None:
@@ -307,36 +262,67 @@ def assert_inventory_source_gate(
)
if is_inventory_source_stable(task):
return
status = str(task.inventory_source_status or "unresolved").strip()
code = INVENTORY_SOURCE_ERROR_CODES.get(status, INVENTORY_SOURCE_ERROR_CODES["gate_blocked"])
reason_by_status = {
"conflicted": "inventory_source_conflicted",
"changed": "inventory_source_changed",
"identity_mismatch": "inventory_source_identity_mismatch",
}
code = INVENTORY_SOURCE_ERROR_CODES['unresolved']
raise AppError(
code=code,
message="库存源尚未确定,无法继续后续流程",
http_status=409,
details={
"operation": operation,
"inventory_source_status": status,
"inventory_source_status": 'unresolved',
"task_no": task.task_no,
"reason_code": reason_by_status.get(status, "require_manual_review"),
"reason_code": "require_manual_review",
},
)
def task_inventory_identity(task: ShippingNotice) -> dict[str, str | None]:
"""返回任务当前正式库存身份;多候选冻结时 source 摘要可为空。"""
def task_inventory_identity(task: ShippingOrderTask) -> dict[str, str | None]:
"""返回库存执行身份;固定仓来自配置,动态仓仅来自已验证库存 Link。"""
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
source_codes = task_frozen_inventory_source_codes(task)
source_code = source_codes[0] if len(source_codes) == 1 else None
source = get_database_inventory_source(source_code) if source_code else None
return {
"inventory_source_code": str(task.inventory_source_code or "").strip().upper() or None,
"inventory_warehouse_id": str(task.inventory_warehouse_id or "").strip().upper() or None,
"inventory_source_code": source_code,
"inventory_warehouse_id": resolve_inventory_source_warehouse_id(task, source=source),
}
def resolve_inventory_source_warehouse_id(
task: ShippingOrderTask,
*,
source: dict[str, Any] | None,
) -> str | None:
"""解析库存执行仓库:固定仓读 Source 配置,动态仓只读有效库存 Link。"""
if not source:
return None
mode = str(source.get('warehouse_resolution_mode') or '').strip().lower()
if mode == 'fixed':
return str(source.get('fixed_warehouse_id') or '').strip().upper() or None
task_id = getattr(task, 'id', None)
source_code = str(source.get('source_code') or '').strip().upper()
if not task_id or not source_code:
return None
from app.models import ShippingTaskInventoryLink
link = ShippingTaskInventoryLink.query.filter_by(
task_id=int(task_id),
matched_source_code=source_code,
is_active=True,
).order_by(ShippingTaskInventoryLink.id.desc()).first()
if link is None:
return None
return (
str(link.matched_warehouse_id or '').strip().upper()
or str(getattr(link.inventory_file, 'warehouse_id', '') or '').strip().upper()
or None
)
def inventory_identities_match(
task: ShippingNotice,
task: ShippingOrderTask,
*,
source_code: str | None,
warehouse_id: str | None,
@@ -344,8 +330,7 @@ def inventory_identities_match(
"""
校验库存文件 Source;固定仓严格匹配,动态仓允许从库存文件中解析。
核心逻辑:单源任务要求与 task.inventory_source_code 一致;
candidates_frozen 时允许文件源属于冻结候选集合。
核心逻辑:单源任务要求与唯一 CandidateSource 一致;多源允许文件源属于当前 CandidateSet。
"""
if not is_inventory_source_stable(task):
return False
@@ -4,7 +4,8 @@ services/shipping_notice/inventory_source_rules.py
用途:将通用路由规则的 Source 候选转为任务可持久化的裁决结果。
依赖:inventory_routing_engine、inventory_source_repository、order_field_purposes。
逻辑:规则只决定 Source;建单前多候选由资格服务按 can_build 放行;
本模块仍负责任务级裁决与快照消歧(履约阶段);Warehouse 由 Source/匹配决定。
行级一致的 ambiguous/resolved/conflicted 可上收为任务裁决;unresolved 禁止兜底全部启用源;
Warehouse 由 Source/匹配决定。
"""
from __future__ import annotations
@@ -15,7 +16,8 @@ from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any
from app.models import ShippingNotice
from app import db
from app.models import ShippingNotice, ShippingOrderSnapshot
from app.services.shipping_notice.inventory_routing_engine import evaluate_inventory_source_rules
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
from app.services.shipping_notice.inventory_source_repository import (
@@ -49,17 +51,26 @@ InventorySourceResolution = InventorySourceAdjudication
def extract_routing_context(task: ShippingNotice) -> dict[str, Any]:
"""投影任务字段为路由审计上下文,不依赖 YAML 目的地别名。"""
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
"""从冻结订单(冻结前为当前 Extraction)读取路由审计上下文。"""
header = current_header_field_values_or_empty(task)
snapshot_id = getattr(task, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id)) if snapshot_id else None
if snapshot is not None:
fields = list((getattr(snapshot.schema_version, 'definition_json', None) or {}).get('fields') or [])
frozen_values = dict(snapshot.header_values_json or {})
header = {
str(field.get('field_code') or ''): frozen_values.get(str(field.get('field_id') or ''))
for field in fields
if field.get('scope') == 'header' and str(field.get('field_code') or '')
}
return {
'destination_code': task.destination_code,
'destination_city': task.destination_city,
'destination_country': task.destination_country,
'warehouse_hint': task.warehouse_hint,
'destination_code': header.get('destination_code'),
'destination_city': header.get('destination_city'),
'destination_country': header.get('destination_country'),
'warehouse_hint': header.get('warehouse_hint'),
'customer_code': header.get('customer_code'),
'customer_name': header.get('customer_name') or header.get('bill_to_customer'),
'order_type': payload.get('order_type'),
'customer_name': header.get('customer_name'),
'order_type': header.get('order_type'),
'destination_candidates': [],
}
@@ -101,7 +112,12 @@ def _from_source(*, status: str, source: dict[str, Any], method: str, context: d
def _result_to_adjudication(result: Any, context: dict[str, Any]) -> InventorySourceAdjudication:
"""将规则引擎候选集转换为可执行或待人工确认的裁决。"""
"""
将规则引擎候选集转换为可执行或待人工确认的裁决。
核心逻辑:只保留规则给出且当前仍可用的 Source;unresolved/空候选时 candidates
必须为空,禁止回退到全部启用库存源(否则会错误触发全源 RPA)。
"""
sources = [item for code in result.source_codes if (item := get_database_inventory_source(code))]
evidence = [{'rule_ids': list(result.matched_rule_ids), **result.evidence}]
if result.status == 'resolved' and len(sources) == 1:
@@ -110,7 +126,7 @@ def _result_to_adjudication(result: Any, context: dict[str, Any]) -> InventorySo
status=result.status,
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[_candidate(item) for item in (sources or list_database_inventory_sources())],
candidates=[_candidate(item) for item in sources],
evidence=evidence,
reason='routing_rule_' + result.status,
)
@@ -165,7 +181,7 @@ def resolve_ambiguous_source_from_ready_snapshots(
if len(order_keys) != len(order_lines):
return adjudication
from app.services.shipping_notice.inventory_file_store import parse_inventory_snapshot_file
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
from app.services.shipping_notice.inventory_snapshot_store import find_latest_ready_snapshot
matched: list[tuple[dict[str, Any], Any]] = []
@@ -179,12 +195,10 @@ def resolve_ambiguous_source_from_ready_snapshots(
if snapshot is None:
checked.append({'source_code': source_code, 'snapshot': 'missing'})
continue
lines = [row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict)]
if not lines:
try:
lines, _column_meta = parse_inventory_snapshot_file(snapshot)
except (OSError, ValueError):
lines = []
try:
lines, _column_meta = read_inventory_file_lines(snapshot)
except (OSError, ValueError):
lines = []
inventory_keys = {
key for row in lines
if isinstance(row, dict) and (key := _snapshot_match_key(row))
@@ -227,19 +241,41 @@ def resolve_ambiguous_source_from_ready_snapshots(
def adjudicate_inventory_source(task: ShippingNotice) -> InventorySourceAdjudication:
"""先评估任务级规则,再在所有订单行一致时接受行级规则结果。"""
"""
先评估任务级规则,再在订单行一致时接受行级规则结果。
核心逻辑:任务级有结论直接用;否则要求各行非 unresolved 且
(status, source_codes) 一致(含 ambiguous 多候选)才采纳行级结果。
仅「各行 resolved 到不同单源」时合并为 ambiguous;不得把 unresolved 扩成全源。
"""
context = extract_routing_context(task)
task_result = evaluate_inventory_source_rules(task=task)
if task_result.status != 'unresolved':
return _result_to_adjudication(task_result, context)
line_results = [evaluate_inventory_source_rules(task=task, line=line) for line in _task_routing_lines(task)]
resolved_codes = {item.source_codes[0] for item in line_results if item.status == 'resolved' and len(item.source_codes) == 1}
if len(resolved_codes) == 1 and all(item.status == 'resolved' for item in line_results):
return _result_to_adjudication(next(item for item in line_results if item.status == 'resolved'), context)
if len(resolved_codes) > 1:
# [STEP] 各行一致的非 unresolved(含 ambiguous)直接采纳,修复 PREFIX 多候选被丢弃。
if line_results and all(item.status != 'unresolved' for item in line_results):
first = line_results[0]
if all(
item.status == first.status and item.source_codes == first.source_codes
for item in line_results
):
return _result_to_adjudication(first, context)
resolved_codes = {
item.source_codes[0]
for item in line_results
if item.status == 'resolved' and len(item.source_codes) == 1
}
if len(resolved_codes) > 1 and all(item.status == 'resolved' for item in line_results):
return InventorySourceAdjudication(
'ambiguous', config_version=inventory_sources_runtime_version(), routing_fingerprint=compute_routing_fingerprint(context),
candidates=[_candidate(item) for item in list_database_inventory_sources() if item['source_code'] in resolved_codes],
'ambiguous',
config_version=inventory_sources_runtime_version(),
routing_fingerprint=compute_routing_fingerprint(context),
candidates=[
_candidate(item)
for item in list_database_inventory_sources()
if item['source_code'] in resolved_codes
],
reason='line_rules_resolve_different_sources',
)
return _result_to_adjudication(task_result, context)
@@ -251,10 +287,7 @@ def resolve_inventory_source(task: ShippingNotice) -> InventorySourceAdjudicatio
def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
"""按任务 Source 或冻结多候选中的首个可用源读取 RPA/快照配置。"""
primary = get_database_inventory_source(task.inventory_source_code)
if primary is not None:
return primary
"""按当前冻结 CandidateSet 的首个可用源读取 RPA/快照配置。"""
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
for code in task_frozen_inventory_source_codes(task):
@@ -265,7 +298,7 @@ def task_rpa_inventory_source(task: ShippingNotice) -> dict[str, Any] | None:
def save_task_rpa_inventory_source(task: ShippingNotice, source: dict[str, Any], *, resolution: InventorySourceAdjudication | None = None) -> None:
"""持久化规则裁决结果;禁止根据调用方传入 source_code 人工覆盖。"""
"""持久化规则裁决结果到 CandidateSet;禁止调用方直接写 OT。"""
from app.services.shipping_notice.inventory_source_gate import apply_inventory_source_adjudication
del source
@@ -19,7 +19,7 @@ from typing import Any
from flask import current_app
from werkzeug.datastructures import FileStorage
from app.models import ShippingInventoryFile, ShippingNotice
from app.models import ShippingInventoryFile, ShippingNotice, ShippingOrderTask
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_file_store import inventory_storage_suffix_for_path
_TASK_INVENTORY_SUFFIXES = (".xls", ".xlsx", ".csv")
@@ -163,7 +163,7 @@ def install_task_inventory_attachment_from_file(
def rebuild_task_inventory_attachment_from_snapshot(
task: ShippingNotice | str,
task: ShippingOrderTask | ShippingNotice | str,
inv_file: ShippingInventoryFile,
) -> Path:
"""
@@ -177,7 +177,7 @@ def rebuild_task_inventory_attachment_from_snapshot(
Returns:
重建后的任务正式附件路径。
"""
task_no = task.task_no if isinstance(task, ShippingNotice) else str(task or "").strip()
task_no = str(getattr(task, "task_no", task) or "").strip()
if not task_no:
raise ValueError("task_no is required")
storage_path = Path(str(inv_file.storage_path or ""))
@@ -29,9 +29,9 @@ def _key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
return values if values and all(values) else None
def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None) -> WarehouseResolution:
def resolve_dynamic_warehouse(*, task: Any, inventory_lines: list[dict[str, Any]], fallback_warehouse_id: str | None = None, source_code: str | None = None) -> WarehouseResolution:
"""按站点已发布解析方案为全部订单行寻找唯一 Warehouse。"""
source = ShippingInventorySource.query.filter_by(source_code=task.inventory_source_code).first()
source = ShippingInventorySource.query.filter_by(source_code=source_code).first()
definition = source.parsing_profile.definition_json if source and source.parsing_profile else {}
match_keys = definition.get('match_keys') if isinstance(definition, dict) else []
order_fields = [str(item.get('order_field_id') or '') for item in match_keys if isinstance(item, dict)]
@@ -2,8 +2,11 @@
services/shipping_notice/inventory_workflow.py
用途:发货通知正式库存阶段编排(上传、复用已解析库存文件);RPA 见 inventory_rpa_workflow。
依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、query_service、state_machine、动态订单字段。
逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除。
依赖:customer_identity_gate、reservation_gate、inventory_file_store、inventory_mapping_workflow、
inventory_snapshot_store、query_service、state_machine、动态订单字段、per_source_rpa_service。
逻辑:正式库存仅按库存站点 published Profile 确定性解析;任务级列推断和映射确认入口已移除;
payload.source_codes 可收窄 ensure_inventory / RPA 作用源(行级重抓);
STP 冻结源 ready 复用必须先 link 快照再推进状态(persist_lines=False),禁止未绑定或覆盖共享 File。
"""
from __future__ import annotations
@@ -13,9 +16,9 @@ from typing import Any
from app import db
from app.core.errors import AppError
from app.models import ShippingNotice
from app.models import ShippingOrderTask
from app.services.shipping_notice.constants import (
CP_INVENTORY_SOURCE_REVIEW,
POSITION_INVENTORY_SOURCE_REVIEW,
)
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
from app.services.shipping_notice.inventory_file_store import save_task_inventory_upload
@@ -52,7 +55,108 @@ def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | Non
return None
def _reservation_gate_response(task: ShippingNotice, *, lang: str) -> dict[str, Any] | None:
def _link_ready_candidate_prep_or_block(
task: ShippingOrderTask,
prep: dict[str, Any],
*,
lang: str,
) -> dict[str, Any] | None:
"""
STP 候选库存 ready 后,确保 OT 已绑定有效库存文件再允许写回解析结果。
核心逻辑:已有 active link 直接放行;否则取 evidence(或行标签)中首个 loaded
快照并 ``link_snapshot_to_task``(与单源 reuse 对齐)。绑定失败返回 needs_human,
禁止抛出「未绑定库存文件」ValueError 把 Gate Job 打成 technical_failure。
Args:
task: 已冻结候选源的订单任务。
prep: ``prepare_candidate_inventory_lines`` 的 ready 结果。
lang: 文案语言。
Returns:
None 表示可继续 ``inventory_loaded_response(persist_lines=False)``;dict 为 tool_response 阻断结果。
"""
from app.models import ShippingInventoryFile
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
from app.services.shipping_notice.inventory_snapshot_store import link_snapshot_to_task
# [STEP 1] 已绑定则无需重复 link。
if active_inventory_file_for_task(task) is not None:
return None
# [STEP 2] 从候选准备证据解析待绑定快照编号。
file_no = ''
for item in list(prep.get('evidence') or []):
if not isinstance(item, dict):
continue
if str(item.get('status') or '').strip().lower() != 'loaded':
continue
file_no = str(item.get('inventory_file_no') or '').strip()
if file_no:
break
if not file_no:
for row in list(prep.get('lines') or []):
if not isinstance(row, dict):
continue
file_no = str(row.get('__inventory_file_no') or '').strip()
if file_no:
break
inv_file = (
ShippingInventoryFile.query.filter_by(inventory_file_no=file_no).first()
if file_no
else None
)
link = None
if inv_file is not None:
link = link_snapshot_to_task(
task,
inv_file,
reason='stp_candidate_prep',
role='owner',
audit_payload={
'candidate_set_id': prep.get('candidate_set_id'),
'loaded_source_codes': list(prep.get('loaded_source_codes') or []),
},
)
if link is not None:
db.session.flush()
return None
# [STEP 3] 无法绑定:软阻断,留给人工重试/上传,勿让 Gate Job 因 ValueError 失败。
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_link_failed',
{
'inventory_file_no': file_no or None,
'loaded_source_codes': list(prep.get('loaded_source_codes') or []),
'candidate_set_id': prep.get('candidate_set_id'),
},
)
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': 'inventory_file_missing'},
'inventory_file_no': file_no or None,
},
)
def _reservation_gate_response(task: ShippingOrderTask, *, lang: str) -> dict[str, Any] | None:
"""
库存入口统一检查订单侧 Reservation ID。
@@ -74,7 +178,7 @@ def _reservation_gate_response(task: ShippingNotice, *, lang: str) -> dict[str,
"order_missing_preview": reservation_issues[:5],
},
},
checkpoint="rsv_req",
position="rsv_req",
stop_agent_turn=True,
forbidden_next_tools=[
"ensure_inventory",
@@ -86,7 +190,7 @@ def _reservation_gate_response(task: ShippingNotice, *, lang: str) -> dict[str,
)
def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lang: str) -> dict[str, Any] | None:
def _inventory_source_gate_response(task: ShippingOrderTask, *, operation: str, lang: str) -> dict[str, Any] | None:
"""
库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。
核心逻辑:先拦客户与 Reservation,再检查库存源稳定性;仅捕获预期 AppError。
@@ -102,7 +206,7 @@ def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lan
task=task,
message='订单解析已确认后必须先冻结订单快照,才能进入库存链路。',
data={**serialize_task_for_tool(task), 'error_code': 'SHIPPING.ORDER_SNAPSHOT_REQUIRED'},
checkpoint='order_freeze',
position='order_freeze',
stop_agent_turn=True,
forbidden_next_tools=['ensure_inventory', 'parse_inventory', 'match_inventory', 'generate_shipment_excel'],
)
@@ -112,6 +216,43 @@ def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lan
reservation_gate = _reservation_gate_response(task, lang=lang)
if reservation_gate is not None:
return reservation_gate
if operation == "ensure_inventory":
# [STEP 0A] 库存准备只能消费已经冻结的路由事实;不得在本阶段补做裁决或
# 触发 RPA。CandidateSet、Source、Line 任一缺失都必须停留在 routing Gate。
from app.services.shipping_notice.inventory_candidate_projection import (
get_active_candidate_lines,
get_active_candidate_set,
get_active_candidate_sources,
)
candidate_set = get_active_candidate_set(task)
sources = get_active_candidate_sources(task)
lines = get_active_candidate_lines(task)
invalid_lines = [
line for line in lines
if not list(getattr(line, "source_codes_json", None) or [])
]
if (
not task.order_snapshot_id
or candidate_set is None
or str(getattr(candidate_set, "lifecycle_status", "") or "").lower() != "frozen"
or not sources
or not lines
or invalid_lines
):
return tool_response(
status="needs_human",
task=task,
message="库存源候选集尚未冻结完成,暂不能准备库存。",
data={
**serialize_task_for_tool(task),
"error_code": "SHIPPING.INVENTORY_SOURCE_ROUTING_REQUIRED",
"position": POSITION_INVENTORY_SOURCE_REVIEW,
},
position=POSITION_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
forbidden_next_tools=["ensure_inventory", "match_inventory", "generate_shipment_excel"],
)
if is_inventory_source_stable(task):
return None
try:
@@ -123,7 +264,7 @@ def _inventory_source_gate_response(task: ShippingNotice, *, operation: str, lan
task=task,
message="库存源尚未确定,请先完成订单解析阶段的库存源确认。",
data=serialize_task_for_tool(task),
checkpoint=ui.checkpoint or CP_INVENTORY_SOURCE_REVIEW,
position=ui.position or POSITION_INVENTORY_SOURCE_REVIEW,
stop_agent_turn=True,
)
return None
@@ -138,7 +279,8 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
gate_resp = _inventory_source_gate_response(task, operation="upload_inventory_file", lang=lang)
if gate_resp is not None:
return gate_resp
if str(getattr(task, 'upload_status', None) or '').strip().lower() in {'uploaded', 'succeeded', 'success'} or str(getattr(task, 'lifecycle_status', None) or '').strip().lower() in {'voided', 'archived', 'deleted'}:
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
if has_verified_upload_success(task) or str(getattr(task, 'lifecycle_status', None) or '').strip().lower() in {'voided', 'archived', 'deleted'}:
return tool_response(
status="failed",
task=task,
@@ -253,6 +395,14 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
resume_gate_code='inventory_preparation',
operator_id=operator_id,
inventory_mode=str(payload.get('mode') or 'auto').strip().lower() or 'auto',
line_scope_key=(
str(
payload.get('line_scope_key')
if payload.get('line_scope_key') is not None
else payload.get('snapshot_line_id')
or ''
).strip() or None
),
)
lang = resolve_lang(payload)
task = resolve_task_from_payload(payload)
@@ -267,6 +417,14 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# [STEP 1] 优先接受当前请求直接携带的库存明细。
# 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。
mode = str(payload.get("mode") or "auto").strip().lower()
# 只读轮询开关:poll_inventory_preparation 查询路径传 False——轮询只消费 RPA Attempt 事实,
# 禁止在查询中自动新建 Attempt;重试必须由用户显式动作(mode='retry_rpa')发起。
allow_auto_retry = bool(payload.get('allow_auto_retry', True))
scoped_source_codes = [
str(code).strip().upper()
for code in (payload.get('source_codes') or [])
if str(code).strip()
] or None
inventory_lines = parse_inventory_lines(payload)
if inventory_lines:
return inventory_loaded_response(
@@ -280,7 +438,9 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if mode == "retry_rpa":
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
return ensure_inventory_via_rpa(task, mode=mode)
return ensure_inventory_via_rpa(
task, mode=mode, source_codes=scoped_source_codes,
)
if mode == "auto":
from app.services.shipping_notice.inventory_rpa_workflow import _try_reuse_inventory_snapshot
@@ -290,7 +450,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# [STEP] STP 多候选:准备全部冻结源快照;缺文件则停在库存等待,不隐式触发 RPA。
frozen_codes = task_frozen_inventory_source_codes(task)
if len(frozen_codes) > 1 or str(task.inventory_source_status or '').strip() == 'candidates_frozen':
if len(frozen_codes) >= 1:
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)
@@ -319,7 +479,75 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
},
},
)
if prep.get('status') == 'missing_files':
if prep.get('status') in {'missing_files', 'partial_missing'}:
# [STEP] 缺失源自动批次探测(设计 D3/D4):不再停在 needs_human;
# 已有 ready 快照的源由 ensure_all_required_sources_prepared 复用,
# 仅缺失源进入单批次 trigger;回调后由下一轮 ensure 继续推进匹配。
from app.services.shipping_notice.per_source_rpa_service import (
ensure_all_required_sources_prepared,
)
probe = ensure_all_required_sources_prepared(
task,
mode=mode,
allow_auto_retry=allow_auto_retry,
source_codes=scoped_source_codes,
)
if probe.pending_source_codes:
apply_task_transition(task, TaskTransition.RPA_PENDING)
task.error_message = None
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running",
message="已触发库存获取,等待各库存源回调。",
progress_percent=60,
detail="等待库存 RPA 回调",
)
db.session.commit()
return tool_response(
status="running",
task=task,
message="已触发库存获取,等待各库存源回调。",
data={
**serialize_task_for_tool(task),
'rpa': {'pending_source_codes': list(probe.pending_source_codes)},
},
)
if probe.all_prepared:
# 探测期间快照已就绪(竞态收敛):重载一次候选行后走正常加载。
prep = prepare_candidate_inventory_lines(task)
else:
# 探测无 pending(trigger 写入失败/无可用源):明确 needs_human 兜底。
log_task_event(task, "inventory_probe_failed", {
'failed_source_codes': list(probe.failed_source_codes or []),
})
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="needs_human",
message="库存 RPA 未能为全部库存源生成结果。",
progress_percent=100,
detail="请重新获取库存或上传库存 Excel。",
)
db.session.commit()
return tool_response(
# [只读轮询失败语义] poll(allow_auto_retry=False)查询到源失败事实时
# 返回 status='failed'(executor 映射为 blocked_retryable),
# 不伪装成人工阻断;显式路径维持 needs_human。
status="failed" if not allow_auto_retry else "needs_human",
task=task,
message="库存 RPA 未能为全部库存源生成结果。",
data={
**serialize_task_for_tool(task),
'blocking_reason': {'code': 'inventory_preparation_failed'},
'poll_read_only': not allow_auto_retry,
},
)
if prep.get('status') in {'missing_files', 'partial_missing'}:
# 防御:探测后仍缺失(如快照在探测窗口内失效),不得带着残缺数据进入匹配。
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
set_task_step_progress(
task,
@@ -343,40 +571,17 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
'missing_source_codes': prep.get('missing_source_codes') or [],
},
)
if prep.get('status') == 'partial_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_files_partial", {
'missing_source_codes': prep.get('missing_source_codes') or [],
'loaded_source_codes': prep.get('loaded_source_codes') or [],
})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=t("workflow.inventory.unavailable", lang=lang),
data={
**serialize_task_for_tool(task),
'missing_source_codes': prep.get('missing_source_codes') or [],
'loaded_source_codes': prep.get('loaded_source_codes') or [],
},
)
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
# [STEP] ready 快照复用:先 Link,再只推进状态;不把合并行写进共享 File。
link_block = _link_ready_candidate_prep_or_block(task, prep, lang=lang)
if link_block is not None:
return link_block
return inventory_loaded_response(
task,
list(prep.get('lines') or []),
column_meta={'source': 'stp_candidate_prep'},
source='stp_candidate_prep',
event_type='inventory_candidates_prepared',
persist_lines=False,
)
reused = _try_reuse_inventory_snapshot(
@@ -391,11 +596,18 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# 否则任务会错误停在人审且没有可执行的恢复动作。
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
return ensure_inventory_via_rpa(task, mode=mode)
return ensure_inventory_via_rpa(
task,
mode=mode,
allow_auto_retry=allow_auto_retry,
source_codes=scoped_source_codes,
)
# [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。
# 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。
if task.inventory_lines_json:
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
if has_ready_inventory_file_for_task(task):
apply_task_transition(task, TaskTransition.INVENTORY_READY)
db.session.commit()
return tool_response(
@@ -3,8 +3,10 @@ services/shipping_notice/lifecycle_projection.py
用途:为批次进度、任务详情与订单生命周期工作台裁决同一份五阶段业务生命周期。
依赖:process_gate_contract 的阻断原因归属;调用方提供正式 Gate、Case/Candidate 或已核验成功事实。
逻辑:正式 Process Gate 优先,其次是可解释阻断原因;无正式事实时保持未分类。
本模块只做只读业务投影,不授权任何写操作;阶段入口与实际动作权限必须分开。
逻辑:已核验上传成功 → 已持久化处理阶段 → 正式 Process Gate → 可解释阻断原因;
[B''] 处理阶段是阶段唯一权威,正式 Gate 不再覆盖/升降阶段,仅在处理阶段缺失时
兜底;无正式事实时保持未分类。本模块只做只读业务投影,不授权任何写操作;
阶段入口与实际动作权限必须分开。
"""
from __future__ import annotations
@@ -36,6 +38,9 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
'duplicate_detection': 'order_review',
'field_conflict_resolution': 'order_review',
'order_freeze_readiness': 'order_review',
# 建单前已存在当前有效 Candidate 的未确认 Review Case 仍属「订单复核」工作面:
# 用户在复核并决定标记非订单/修订草稿之前,订单尚未正式创建。
'order_review_build': 'order_review',
'task_creation': 'order_review',
'inventory_source_routing': 'fulfillment_prep',
'inventory_preparation': 'fulfillment_prep',
@@ -49,8 +54,8 @@ LIFECYCLE_STAGE_BY_GATE: dict[str, str] = {
}
# 已持久化的 Processing 技术阶段到五阶段业务工作面的唯一映射。它只用于
# 读模型展示,不推进订单、不创建任务,也不授予任何动作。正式 Gate 仍在
# 技术阶段缺失时提供兜底,避免历史数据被无条件覆盖。
# 读模型展示,不推进订单、不创建任务,也不授予任何动作。[B''] 它是阶段的唯一
# 权威;正式 Gate 仅在技术阶段缺失时提供兜底,不能覆盖有效处理阶段。
LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
'upload_received': 'intake_parse',
'email_parsing': 'intake_parse',
@@ -60,7 +65,7 @@ LIFECYCLE_STAGE_BY_PROCESSING_STAGE: dict[str, str] = {
'waiting_review': 'order_review',
'customer_resolving': 'order_review',
'duplicate_checking': 'order_review',
'inventory_source_resolving': 'order_review',
'inventory_source_resolving': 'fulfillment_prep',
'order_creating': 'fulfillment_prep',
'inventory_fetching': 'fulfillment_prep',
'inventory_preparation': 'fulfillment_prep',
@@ -114,11 +119,12 @@ def project_lifecycle(
verified_upload_success: bool = False,
processing_stage: str | None = None,
) -> dict[str, Any]:
"""按成功事实 → Gate → 已持久化阶段 → 阻断归属的固定优先级裁决生命周期。
"""按成功事实 → 已持久化阶段 → 正式 Gate → 阻断归属的固定优先级裁决生命周期。
``processing_stage`` 是订单处理流程已写入的事实,仅映射展示工作面;它不能
授权动作或推进流程。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算
阶段或放开按钮。
[B''] 阶段唯一权威:只要 ``processing_stage``(OT.stage / Run.processing_stage)是合法
15 阶成员,就直接映射五阶段,正式 Gate 不能覆盖或升降它。``gate_code`` 只在处理
阶段缺失时兜底(如任务详情无 OT.stage 上下文),且仅用于「订单检查」面板诊断;
它不再能改变阶段。``authority`` 仅用于诊断/迁移观测;前端不得据此再计算阶段或放开按钮。
"""
gate = current_gate if isinstance(current_gate, dict) else {}
gate_code = str(gate.get('gate_code') or gate.get('code') or '').strip().lower()
@@ -127,14 +133,16 @@ def project_lifecycle(
if verified_upload_success:
lifecycle_stage = 'upload_complete'
authority = 'verified_upload_success'
elif gate_code in LIFECYCLE_STAGE_BY_GATE:
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
authority = 'process_gate'
# [B''] 处理阶段是阶段唯一权威。合法 15 阶直接映射五阶段;Gate 不再覆盖它。
elif str(processing_stage or '').strip().lower() in LIFECYCLE_STAGE_BY_PROCESSING_STAGE:
lifecycle_stage = LIFECYCLE_STAGE_BY_PROCESSING_STAGE[
str(processing_stage or '').strip().lower()
]
authority = 'processing_stage'
# [B''] 正式 Gate 仅在处理阶段缺失时兜底,用于「订单检查」面板,不改变阶段。
elif gate_code in LIFECYCLE_STAGE_BY_GATE:
lifecycle_stage = LIFECYCLE_STAGE_BY_GATE[gate_code]
authority = 'process_gate'
else:
reason = blocking_reason if isinstance(blocking_reason, dict) else {}
reason_code = str(reason.get('code') or reason.get('blocking_reason_code') or '').strip()
@@ -24,7 +24,7 @@ from app.services.shipping_notice.line_inventory_match_persistence import resolv
from app.services.shipping_notice.line_inventory_match_projection import line_auto_fulfill_enabled
from app.services.shipping_notice.post_ot_fulfillment_wave_service import (
create_post_ot_fulfillment_wave,
list_eligible_post_ot_line_keys,
list_eligible_post_ot_snapshot_line_ids,
)
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
project_review_case_line_decisions,
@@ -35,7 +35,7 @@ from app.services.shipping_notice.post_ot_wave_progress_service import schedule_
def _mark_auto_fulfill_failed(
case: ShippingOrderReviewCase,
*,
line_keys: list[str],
snapshot_line_ids: list[str],
error_code: str,
message: str,
) -> None:
@@ -46,12 +46,18 @@ def _mark_auto_fulfill_failed(
"""
now = datetime.utcnow()
formal_task_id = getattr(case, 'confirmed_task_id', None)
for key in line_keys:
projection = project_review_case_line_decisions(case)
draft_id_by_snapshot_id = {
str(item.get('snapshot_line_id')): str(item.get('draft_line_id') or '').strip()
for item in list(projection.get('lines') or [])
if isinstance(item, dict) and item.get('snapshot_line_id') is not None
}
for key in snapshot_line_ids:
key_s = str(key)
if formal_task_id is not None:
fact = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(formal_task_id), line_key=key_s, is_current=True)
.filter_by(task_id=int(formal_task_id), snapshot_line_id=int(key_s), is_current=True)
.first()
)
if fact is not None:
@@ -67,9 +73,12 @@ def _mark_auto_fulfill_failed(
fact.detail_json = detail
fact.updated_at = now
draft_line_id = draft_id_by_snapshot_id.get(key_s)
if not draft_line_id:
continue
row = (
ShippingOrderReviewLineDecision.query
.filter_by(review_case_id=int(case.id), line_key=key_s, is_active=True)
.filter_by(review_case_id=int(case.id), draft_line_id=draft_line_id, is_active=True)
.first()
)
if row is None:
@@ -116,10 +125,10 @@ def coordinate_post_ot_auto_fulfill(
'case_no': case.case_no,
}
eligible = list_eligible_post_ot_line_keys(case)
eligible = list_eligible_post_ot_snapshot_line_ids(case)
projection = project_review_case_line_decisions(case)
unassigned = [
str(item.get('line_key') or '')
str(item.get('snapshot_line_id') or '')
for item in list(projection.get('lines') or [])
if str(item.get('line_status') or '') not in {'task_created', 'fulfilled', 'closed_unfulfillable'}
]
@@ -129,7 +138,7 @@ def coordinate_post_ot_auto_fulfill(
'reason': 'no_eligible_lines',
'trigger': trigger,
'case_no': case.case_no,
'accepted_line_keys': [],
'accepted_snapshot_line_ids': [],
}
# [STEP] 自动制单只处理唯一开放明细。多条明细必须由用户勾选后合并,
# 绝不静默替用户决定 Notice 的合并范围。
@@ -139,7 +148,7 @@ def coordinate_post_ot_auto_fulfill(
'reason': 'manual_wave_selection_required',
'trigger': trigger,
'case_no': case.case_no,
'accepted_line_keys': [],
'accepted_snapshot_line_ids': [],
}
idem_key = f'auto-fulfill:{case.case_no}:{trigger}:{",".join(sorted(eligible))}'
@@ -147,7 +156,7 @@ def coordinate_post_ot_auto_fulfill(
# [STEP 1] 整波创建(失败则整波回滚)
result = create_post_ot_fulfillment_wave(
case_no=str(case.case_no),
line_keys=eligible,
snapshot_line_ids=[int(item) for item in eligible],
decision_source='system',
actor_user_id=None,
reason=f'auto_fulfill:{trigger}',
@@ -157,7 +166,7 @@ def coordinate_post_ot_auto_fulfill(
progress = schedule_post_ot_wave_progress(
task_no=str(result.get('task_no') or ''),
wave_no=result.get('wave_no'),
line_keys=list(result.get('accepted_line_keys') or eligible),
snapshot_line_ids=[int(item) for item in (result.get('accepted_snapshot_line_ids') or eligible)],
review_case_id=int(result.get('review_case_id') or case.id),
idempotency_row_id=result.get('idempotency_row_id'),
request_idempotency_key=str(result.get('idempotency_key') or idem_key),
@@ -170,7 +179,7 @@ def coordinate_post_ot_auto_fulfill(
'case_no': case.case_no,
'wave_progress': progress,
**{k: result.get(k) for k in (
'task_no', 'wave_no', 'accepted_line_keys', 'skipped_line_keys',
'task_no', 'wave_no', 'accepted_snapshot_line_ids', 'skipped_snapshot_line_ids',
'idempotency_row_id', 'idempotent_replay',
)},
}
@@ -185,7 +194,7 @@ def coordinate_post_ot_auto_fulfill(
if refreshed is not None:
_mark_auto_fulfill_failed(
refreshed,
line_keys=eligible,
snapshot_line_ids=eligible,
error_code=getattr(exc, 'code', None) or 'SHIPPING.AUTO_FULFILL_FAILED',
message=str(exc)[:1000],
)
@@ -195,7 +204,7 @@ def coordinate_post_ot_auto_fulfill(
'trigger': trigger,
'case_no': case_no_hint,
'error': str(exc)[:500],
'eligible_line_keys': eligible,
'eligible_snapshot_line_ids': eligible,
}
@@ -3,7 +3,7 @@ services/shipping_notice/line_inventory_match_persistence.py
用途:inventory_matching 完成后把逐行结果写入 OT 行库存匹配事实表(Slice 1)。
依赖:ShippingNoticeLineInventoryMatch、ShippingOrderReviewCase、normalize 投影语义。
逻辑:由 fulfillment_workflow.match_inventory 调用;按 draft line_key(行序)落库;
逻辑:由 fulfillment_workflow.match_inventory 调用;按冻结订单行 snapshot_line_id 落库;
新快照新增行并切换 is_current;不覆盖历史快照事实。
"""
@@ -26,19 +26,6 @@ from app.services.shipping_notice.inventory_candidate_projection import (
)
def _draft_line_keys_by_index(case: ShippingOrderReviewCase | None) -> dict[int, str]:
"""Case 草稿行序 → line_key。"""
if case is None or case.current_draft is None:
return {}
out: dict[int, str] = {}
for idx, line in enumerate(list(case.current_draft.lines_json or [])):
if not isinstance(line, dict):
continue
key = str(line.get('line_key') or '').strip() or f'line-{idx + 1}'
out[idx] = key
return out
def resolve_review_case_for_task(task: ShippingNotice) -> ShippingOrderReviewCase | None:
"""
反查确认到该 OT 的 Review Case。
@@ -85,6 +72,24 @@ def map_disposition_to_match_codes(
return 'result_missing', 'unavailable'
def _line_resolved_source_code(task: ShippingNotice, result: dict[str, Any]) -> str | None:
"""
行级已定源:优先取匹配结果,缺失时回退到任务级已定源(Approach 1)。
核心逻辑:匹配未回填源时,只有当前 CandidateSet 恰有一个源才回填;
不从 OT 读取任务级库存源投影。
"""
src = str(result.get('resolved_inventory_source_code') or '')[:64] or None
if src:
return src
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
source_codes = task_frozen_inventory_source_codes(task)
if len(source_codes) == 1:
return source_codes[0][:64]
return None
def persist_line_inventory_match_facts(
*,
task: ShippingNotice,
@@ -95,14 +100,15 @@ def persist_line_inventory_match_facts(
"""
将 match_order_lines_across_candidates 结果持久化为当前事实。
核心逻辑:按 line_index 解析 draft line_key;同快照幂等更新;否则新增并切换 is_current;
核心逻辑:按冻结订单行项次解析 snapshot_line_id;同快照幂等更新;否则新增并切换 is_current;
无 inventory_snapshot_id 时禁止写入 ready/not_found;单位写入事实列。
"""
case = resolve_review_case_for_task(task)
keys_by_index = _draft_line_keys_by_index(case)
snap_id = inventory_snapshot_id
if snap_id is None and getattr(task, 'inventory_snapshot_id', None) is not None:
snap_id = int(task.inventory_snapshot_id)
if snap_id is None:
from app.services.shipping_notice.inventory_candidate_projection import active_inventory_runtime_facts
snap_id = active_inventory_runtime_facts(task).get('inventory_file_id')
# 匹配器结果可能未回填 inventory_file_no,但当前快照本身已是行匹配的
# 正式文件身份。持久化必须补齐,避免“有快照却无行级下载证据”。
snapshot_file_no = None
@@ -129,6 +135,12 @@ def persist_line_inventory_match_facts(
int(row.line_no): row
for row in get_active_candidate_lines(task)
}
from app.models import ShippingOrderSnapshot
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id)) if task.order_snapshot_id else None
snapshot_lines_by_no = {
int(line.line_no): line for line in (snapshot.lines if snapshot is not None else [])
if str(getattr(line, 'line_no', '') or '').isdigit()
}
for result in line_results:
try:
@@ -136,15 +148,11 @@ def persist_line_inventory_match_facts(
except (TypeError, ValueError):
continue
res = res_by_index.get(index) or {}
# Case 草稿 line_key 是订单明细的正式身份;匹配器临时 line-1 只能兜底,
# 禁止覆盖 machine-1 等正式键,否则事实已落库但工作台无法关联显示。
line_key = str(
keys_by_index.get(index)
or res.get('line_key')
or f'line-{index + 1}'
).strip()
if not line_key:
line_no = index + 1
snapshot_line = snapshot_lines_by_no.get(line_no)
if snapshot_line is None:
continue
snapshot_line_id = int(snapshot_line.id)
match_result, inventory_status = map_disposition_to_match_codes(
disposition=str(result.get('disposition') or res.get('disposition') or ''),
@@ -192,7 +200,8 @@ def persist_line_inventory_match_facts(
ShippingNoticeLineInventoryMatch.query
.filter_by(
task_id=int(task.id),
line_key=line_key,
snapshot_line_id=snapshot_line_id,
line_no=line_no,
inventory_snapshot_id=int(snap_id),
)
.first()
@@ -200,7 +209,7 @@ def persist_line_inventory_match_facts(
if existing is None and snap_id is None:
existing = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
.filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True)
.filter(ShippingNoticeLineInventoryMatch.inventory_snapshot_id.is_(None))
.first()
)
@@ -208,18 +217,17 @@ def persist_line_inventory_match_facts(
if existing is None:
(
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_key=line_key, is_current=True)
.filter_by(task_id=int(task.id), snapshot_line_id=snapshot_line_id, is_current=True)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
# Draft line_key 发生过版本切换时,按稳定 line_index 关闭旧键事实,
# 避免同一订单行同时存在两个 current 投影。
# 同一订单行按稳定 line_index 关闭旧事实,避免多个 current 投影。
(
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_index=index, 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
src_code = _line_resolved_source_code(task, result)
file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
try:
@@ -249,7 +257,8 @@ def persist_line_inventory_match_facts(
row = ShippingNoticeLineInventoryMatch(
task_id=int(task.id),
review_case_id=int(case.id) if case is not None else None,
line_key=line_key,
snapshot_line_id=snapshot_line_id,
line_no=line_no,
line_index=index,
candidate_set_id=(
int(current_candidate_set.id)
@@ -301,7 +310,7 @@ def persist_line_inventory_match_facts(
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
src_code = _line_resolved_source_code(task, result)
file_no = str(result.get('inventory_file_no') or snapshot_file_no or '')[:128] or None
row_index_raw = result.get('inventory_row_index') or result.get('inventory_row_ref')
try:
@@ -374,14 +383,13 @@ def persist_line_inventory_match_facts(
ShippingNoticeLineInventoryMatch.query
.filter(
ShippingNoticeLineInventoryMatch.task_id == int(task.id),
ShippingNoticeLineInventoryMatch.line_key == line_key,
ShippingNoticeLineInventoryMatch.snapshot_line_id == snapshot_line_id,
ShippingNoticeLineInventoryMatch.id != int(existing.id),
ShippingNoticeLineInventoryMatch.is_current.is_(True),
)
.update({'is_current': False, 'updated_at': now}, synchronize_session=False)
)
# Draft line_key 发生过版本切换时,更新已有新键也必须关闭旧键;
# 否则旧 key 会与新 key 同时进入 current 投影,导致订单明细不确定。
# 同一订单行更新时关闭旧事实,保证 current 投影唯一。
(
ShippingNoticeLineInventoryMatch.query
.filter(
@@ -2,11 +2,13 @@
services/shipping_notice/line_inventory_match_projection.py
用途:将 OT 行库存匹配事实规范为复核明细可消费的库存/履约投影。
依赖:ShippingNoticeLineInventoryMatch、Config 自动履约开关。
逻辑:由 order_review_fulfillment_decision_service.project_review_case_line_decisions 调用;
依赖:ShippingNoticeLineInventoryMatch、ShippingTaskInventoryRpaAttempt、Config 自动履约开关。
逻辑:由 order_review_fulfillment_decision_service / ui_state._build_stage_context 调用;
ready+not_found→available=0;result_missing 不得转 0;
inventory_allowed_actions / line_allowed_actions 分域下发(禁止前端自推按钮);
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail。
line_allowed_actions 仅 close_unfulfillable,不再下发 view_fulfillment_detail;
load_current_match_facts_by_task / inventory_rpa_is_running 在同一 HTTP 请求内 memo,
禁止按行重复查库。
"""
from __future__ import annotations
@@ -14,7 +16,11 @@ from __future__ import annotations
from decimal import Decimal, InvalidOperation
from typing import Any
from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch
from app.models import (
ShippingInventoryFile,
ShippingNoticeLineInventoryMatch,
ShippingTaskInventoryRpaAttempt,
)
MATCH_NOT_FOUND = 'not_found'
@@ -414,24 +420,107 @@ def resolve_allowed_actions(
return [*inv, *line]
def load_current_match_facts_by_task(task_id: int | None) -> dict[str, dict[str, Any]]:
"""加载 OT 当前行匹配事实,键为 line_key。"""
def inventory_rpa_is_running(task: Any) -> bool:
"""
仅依据正式 OT 的库存 RPA Attempt 判断库存获取是否运行中。
核心逻辑:查 (task_no, status in queued|running) 是否存在;阶段推进 Job 的
queued/running 不得冒充本结果。同一 HTTP 请求内按 task_no memo,供 Case 投影
与工作台 stage_context 共享,禁止逐行或重复入口各查一次。
Args:
task: 含 task_no 的正式 OT(或等价命名空间);无 task_no 时返回 False。
Returns:
True 表示存在活动库存 RPA Attempt。
"""
task_no = str(getattr(task, 'task_no', None) or '').strip()
if not task_no:
return False
try:
from flask import g, has_app_context, has_request_context
if has_app_context() and has_request_context():
cache = getattr(g, '_shipping_inventory_rpa_running_by_task_no', None)
if cache is None:
cache = {}
g._shipping_inventory_rpa_running_by_task_no = cache
if task_no in cache:
return bool(cache[task_no])
else:
cache = None
except Exception:
cache = None
try:
running = (
ShippingTaskInventoryRpaAttempt.query
.filter(
ShippingTaskInventoryRpaAttempt.task_no == task_no,
ShippingTaskInventoryRpaAttempt.status.in_(('queued', 'running')),
)
.first()
is not None
)
except Exception: # noqa: BLE001
# 纯投影/无数据库测试对象不得把未知状态误判为运行中。
running = False
if cache is not None:
cache[task_no] = running
return running
def load_current_match_facts_by_task(task_id: int | None) -> dict[int, dict[str, Any]]:
"""
加载 OT 当前行匹配事实,键为冻结订单行 ID。
同一 HTTP 请求内按 task_id memo,避免 SUMMARY / ui_state / stage_context 重复查库。
"""
if task_id is None:
return {}
key = int(task_id)
try:
from flask import g, has_app_context, has_request_context
if has_app_context() and has_request_context():
cache = getattr(g, '_shipping_match_facts_by_task', None)
if cache is None:
cache = {}
g._shipping_match_facts_by_task = cache
cached = cache.get(key)
if cached is not None:
return cached
else:
cache = None
except Exception:
cache = None
rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task_id), is_current=True)
.filter_by(task_id=key, is_current=True)
.all()
)
out: dict[str, dict[str, Any]] = {}
out: dict[int, dict[str, Any]] = {}
for row in rows:
key = str(row.line_key or '').strip()
if not key:
if row.snapshot_line_id is None:
continue
out[key] = serialize_match_fact(row)
out[int(row.snapshot_line_id)] = serialize_match_fact(row)
if cache is not None:
cache[key] = out
return out
def aggregate_match_status_for_task(task_id: int | None) -> str | None:
"""根据当前行级 Match 聚合任务匹配状态,禁止读取 OT/Notice 缓存字段。"""
facts = list(load_current_match_facts_by_task(task_id).values())
if not facts:
return None
blocked = any(
str(row.get('match_result') or '').strip().lower() != 'matched'
or str(row.get('shortage_qty') or '').strip() not in {'', '0', '0.0', '0.00'}
for row in facts
)
return 'unfulfillable' if blocked else 'fulfillable'
def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]:
"""将 ORM 行序列化为投影输入。"""
snapshot = (
@@ -442,7 +531,8 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
'id': int(row.id),
'task_id': int(row.task_id),
'review_case_id': int(row.review_case_id) if row.review_case_id is not None else None,
'line_key': str(row.line_key),
'snapshot_line_id': int(row.snapshot_line_id),
'line_no': int(row.line_no),
'line_index': row.line_index,
'inventory_snapshot_id': (
int(row.inventory_snapshot_id) if row.inventory_snapshot_id is not None else None
@@ -457,6 +547,7 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any
'unit': row.unit,
'matching_rule_version': row.matching_rule_version,
'inventory_source_code': row.inventory_source_code,
'allowed_source_codes_snapshot': list(getattr(row, 'allowed_source_codes_snapshot', None) or []),
'inventory_file_no': getattr(row, 'matched_file_no', None),
'inventory_file_sha256': (
dict(row.detail_json or {}).get('file_sha256')
@@ -15,7 +15,7 @@ def _norm(value: Any) -> str:
return str(value or "").strip()
def _line_key(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
def _match_identity(row: dict[str, Any], fields: list[str]) -> tuple[str, ...] | None:
"""按配置字段列表构造确定性匹配键;任一字段为空时该行不可匹配。"""
values = tuple(_norm(row.get(field)).casefold() for field in fields)
return values if values and all(values) else None
@@ -27,7 +27,7 @@ def _aggregate_inventory(
"""按用户配置的库存匹配字段组合汇总唯一数量字段。"""
totals: dict[tuple[str, ...], float] = {}
for row in inventory_lines:
key = _line_key(row, match_fields)
key = _match_identity(row, match_fields)
if key is None:
continue
try:
@@ -70,7 +70,7 @@ def match_notice_lines(
# [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。
total_lines = len(notice_lines)
for index, line in enumerate(notice_lines, start=1):
order_key = _line_key(line, order_fields)
order_key = _match_identity(line, order_fields)
try:
required = float(line.get("__required_qty") or 0)
except (TypeError, ValueError):
@@ -9,36 +9,26 @@ services/shipping_notice/notice_line_constants.py
from __future__ import annotations
NOTICE_LINE_FIELDS = (
"line_no",
"part_number",
"qty",
"unit_price",
"amount",
"currency",
"line_amount_with_tax",
"reservation_id",
"required_date",
"customer_part_number",
"aws_part_number",
"uom",
"line_remark",
"po_number",
"allocation_id",
"inventory_source_hint",
)
NOTICE_FIELD_LABELS = {
"line_no": "项次 / Item / Line No",
"part_number": "内部料号 / Part Number",
"qty": "需求数量",
"unit_price": "单价",
"amount": "金额",
"currency": "币种",
"line_amount_with_tax": "含税金额 / Amount",
"reservation_id": "Reservation ID(常见纯数字,如 1000140351)",
"required_date": "要求交期 / 交货日期",
"customer_part_number": "客户料号 / Customer Part Number",
"aws_part_number": "AWS 料号 / AWS Part Number",
"po_number": "PO Number",
"allocation_id": "Allocation ID",
"inventory_source_hint": "库存来源提示 / Hub Code",
"line_remark": "行备注",
}
@@ -9,6 +9,7 @@ backend/app/services/shipping_notice/notice_line_service.py
from __future__ import annotations
from datetime import datetime
from typing import Any
from app import db
from app.models import ShippingNoticeLine, ShippingOrderSnapshot
@@ -19,6 +20,7 @@ def replace_notice_lines_from_snapshot(
notice_id: int,
snapshot: ShippingOrderSnapshot,
snapshot_line_ids: set[int] | None = None,
inventory_facts_by_snapshot_line_id: dict[int, dict[str, Any]] | None = None,
) -> int:
"""
用 Snapshot 行替换指定 Notice 的 shipping_notice_lines。
@@ -35,18 +37,26 @@ def replace_notice_lines_from_snapshot(
now = datetime.utcnow()
rows: list[ShippingNoticeLine] = []
selected_ids = {int(item) for item in (snapshot_line_ids or set())}
inventory_facts_by_snapshot_line_id = inventory_facts_by_snapshot_line_id or {}
notice_position = 0
for line in list(snapshot.lines or []):
if selected_ids and int(line.id) not in selected_ids:
continue
notice_position += 1
inventory_facts = dict(inventory_facts_by_snapshot_line_id.get(int(line.id)) or {})
rows.append(
ShippingNoticeLine(
notice_id=int(notice_id),
snapshot_line_id=int(line.id) if getattr(line, 'id', None) else None,
position=int(line.position),
line_key=str(getattr(line, 'line_no', None) or '').strip() or None,
position=notice_position - 1,
# 发货通知项次按当前通知单重新从 1 编排。
line_no=notice_position,
part_number=getattr(line, 'part_number', None),
reservation_id=getattr(line, 'reservation_id', None),
required_qty=getattr(line, 'qty', None),
inventory_source_code=inventory_facts.get('inventory_source_code'),
inventory_file_id=inventory_facts.get('inventory_file_id'),
inventory_warehouse_id=inventory_facts.get('inventory_warehouse_id'),
field_values_json=dict(getattr(line, 'field_values_json', None) or {}),
created_at=now,
)
@@ -86,14 +86,6 @@ def parse_notice_row(
if idx_qty is not None:
skip_indices.add(idx_qty)
idx_line_no = columns.get("line_no")
if idx_line_no is not None:
config = contract.fields_by_code.get('line_no')
line_no = _normalized_cell(row, idx_line_no, config)
skip_indices.add(idx_line_no)
if line_no is not None:
parsed["line_no"] = str(line_no)
idx_res = columns.get("reservation_id")
reservation_id = ""
if idx_res is not None:
@@ -119,18 +111,22 @@ def parse_notice_row(
if value is not None:
parsed["unit_price"] = float(value)
idx_amount = columns.get("amount")
# 冻结契约的表头字段码已从旧版 `amount` 迁移为 `line_amount_with_tax`(见
# table_contract.TABLE_FIELD_CODES / order_freeze_service.LINE_FIELD_PROJECTIONS)。
# 表格列以 `line_amount_with_tax` 识别,但订单行输出沿用通知层的 `amount` 表示键,
# 供 normalize_notice_line / validate_notice_lines 等下游统一消费。
idx_amount = columns.get("line_amount_with_tax")
amount_cell = None
if idx_amount is not None:
amount_cell = cell(row, idx_amount)
config = contract.fields_by_code.get('amount')
config = contract.fields_by_code.get('line_amount_with_tax')
value = _normalized_cell(row, idx_amount, config, numeric=True)
if value is not None:
parsed["amount"] = float(value)
for field in (
'currency', 'uom', 'required_date', 'po_number', 'inventory_source_hint',
'customer_part_number', 'aws_part_number', 'line_remark',
'customer_part_number', 'line_remark',
):
idx = columns.get(field)
if idx is None:
@@ -145,7 +141,7 @@ def parse_notice_row(
if currency:
parsed['currency'] = currency
amount_config = contract.fields_by_code.get('amount')
amount_config = contract.fields_by_code.get('line_amount_with_tax')
if amount_config is not None and "amount" not in parsed and "unit_price" in parsed:
computed = round(parsed["unit_price"] * float(qty), 4)
normalized = _normalized_cell([computed], 0, amount_config, numeric=True)
@@ -170,7 +166,7 @@ def score_notice_header_row(cells: list[Any], contract: TableHeaderContract | No
score += 30
if "reservation_id" in mapped:
score += 10
if "unit_price" in mapped or "amount" in mapped:
if "unit_price" in mapped or "line_amount_with_tax" in mapped or "amount" in mapped:
score += 5
return score
@@ -20,7 +20,6 @@ from app.services.shipping_notice.notice_line_values import (
map_notice_header,
norm_header,
normalize_currency,
normalize_line_no,
normalize_required_date,
parse_number,
)
@@ -201,10 +200,6 @@ def normalize_notice_line(
if raw_uom and field_enabled("uom"):
line["uom"] = raw_uom
line_no = normalize_line_no(raw.get("line_no"))
if line_no and field_enabled("line_no"):
line["line_no"] = line_no
reservation_id = extract_reservation_id(raw.get("reservation_id"))
if reservation_id and field_enabled("reservation_id"):
line["reservation_id"] = reservation_id
@@ -217,9 +212,10 @@ def normalize_notice_line(
line["unit_price"] = unit_price
amount = parse_number(raw.get("amount"))
if amount is not None and field_enabled("amount"):
# Schema 使用 canonical line_amount_with_tax;内部通知行仍保留 amount 键供下游消费。
if amount is not None and field_enabled("line_amount_with_tax"):
line["amount"] = amount
elif unit_price is not None and field_enabled("amount"):
elif unit_price is not None and field_enabled("line_amount_with_tax"):
line["amount"] = round(unit_price * qty, 4)
currency = normalize_currency(raw.get("currency"))
@@ -51,7 +51,7 @@ def _post_op(
"200": {
"description": (
"Tool response (status: ok|running|needs_human|failed). "
"May include checkpoint; business buttons are exposed only by ui_state.actions."
"May include position; business buttons are exposed only by ui_state.actions."
),
"content": {
"application/json": {
@@ -86,7 +86,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"paths": {
"/tools/get_task_status": _post_op(
"get_task_status",
"查询任务当前状态;响应含库存连接器独立字段与候选结构",
"查询任务当前状态;响应含库存源状态与候选结构",
{
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID"),
@@ -94,8 +94,8 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["task_id", "shipping_chat_capability_token"],
description=(
"返回 inventory_source_code、inventory_connector_type、"
"inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|"
"返回 inventory_source_code、inventory_warehouse_id、"
"inventory_source_status(unresolved|ambiguous|resolved|"
"candidates_frozen|invalid|conflicted)、inventory_source_method、"
"inventory_source_config_version、inventory_routing_fingerprint、"
"以及 step_payload.inventory_source_resolution.candidates。"
@@ -17,7 +17,8 @@ from typing import Any
from app.models import (
ShippingDocumentProfileAutoFreezeQualification,
ShippingOrderCustomerMatch,
ShippingCustomerShadowResolution,
ShippingOrderCandidate,
ShippingOrderExtraction,
ShippingOrderExtractionProgressEvent,
ShippingOrderRouteDecision,
@@ -321,19 +322,19 @@ def _qualification_for_route(
def _confirmed_customer_ids(run: ShippingOrderProcessingRun) -> list[int]:
"""读取本轮已确认的 Bill-to 客户;跨订单多客户时必须维持 fail-closed。"""
"""读取本轮正式识别结果中的已确认客户;跨订单多客户时维持 fail-closed。"""
rows = (
ShippingOrderCustomerMatch.query
.join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCustomerMatch.extraction_id)
ShippingCustomerShadowResolution.query
.join(ShippingOrderCandidate, ShippingOrderCandidate.id == ShippingCustomerShadowResolution.candidate_id)
.join(ShippingOrderExtraction, ShippingOrderExtraction.id == ShippingOrderCandidate.order_extraction_id)
.filter(
ShippingOrderExtraction.run_id == int(run.id),
ShippingOrderCustomerMatch.role == 'bill_to',
ShippingOrderCustomerMatch.status == 'confirmed',
ShippingOrderCustomerMatch.customer_id.isnot(None),
ShippingCustomerShadowResolution.status == 'confirmed',
ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None),
)
.all()
)
return sorted({int(row.customer_id) for row in rows if row.customer_id is not None})
return sorted({int(row.confirmed_customer_id) for row in rows if row.confirmed_customer_id is not None})
def _evaluate_customer_scope(
@@ -7,7 +7,7 @@ services/shipping_notice/order_build_eligibility_service.py
inventory_routing_engine、inventory_source_repository、
ShippingOrderCandidate / ShippingOrderProcessingUnit / ShippingOrderProcessingRun、
ShippingInventorySource、process_gate_contract(原因唯一归属)。
逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核阻断;
逻辑:由 Draft 校验与确认建单调用;多候选不阻断;零候选或强制人工复核不阻断正式 OT 创建(库存路由属可人工修正事实,行级仍记录 block_reason 供自动建单/复核门禁消费);
人工已选候选(含原因)可覆盖规则零候选且优先于自动建议;规则原始候选与当前有效候选分离;
停用 / Profile 未启用 / 无已发布解析 Profile / Excel 模板未发布的 Source 不进入有效候选,
并写入稳定 unavailable_reasons(码表见 error_explainability_contract);
@@ -473,7 +473,7 @@ def assess_order_build_eligibility(
fields: Schema field_id → 配置。
header_by_code: Header field_code → 值。
lines: 行 field_code → 值列表(与 line_metas 对齐)。
line_metas: Draft 行原始对象(含 line_key / inventory_routing)。
line_metas: Draft 行原始对象(含 draft_line_id / inventory_routing)。
customer_resolved: 客户是否已唯一命中或人工确认;缺省 True 由调用方保证。
candidate / unit / run: 可选门禁上下文(自动建单检查)。
@@ -515,7 +515,7 @@ def assess_order_build_eligibility(
line_meta=meta,
)
projection = {
'line_key': meta.get('line_key'),
'draft_line_id': meta.get('draft_line_id'),
'line_index': index,
'effective_reservation_id': effective,
'inventory_source_hint': raw_line.get('inventory_source_hint'),
@@ -526,7 +526,7 @@ def assess_order_build_eligibility(
if not effective:
issues.append({
'code': 'effective_reservation_missing',
'line_key': meta.get('line_key'),
'draft_line_id': meta.get('draft_line_id'),
'line_index': index,
'severity': 'blocking',
'owning_gate_code': 'reservation_validation',
@@ -534,7 +534,7 @@ def assess_order_build_eligibility(
if not routing.get('can_build'):
issues.append({
'code': str(routing.get('block_reason') or 'inventory_source_unresolved'),
'line_key': meta.get('line_key'),
'draft_line_id': meta.get('draft_line_id'),
'line_index': index,
'severity': 'blocking',
'owning_gate_code': 'inventory_source_routing',
@@ -573,11 +573,16 @@ def assess_order_build_eligibility(
'owning_gate_code': 'reservation_validation',
})
# 库存源路由属于通知准备阶段可人工修正的事实,不阻断正式 OT 创建。
build_blocking_issues = [
item for item in issues
if str(item.get('owning_gate_code') or '') != 'inventory_source_routing'
]
can_build = (
bool(customer_resolved)
and bool(assessment.get('can_create_task'))
and not issues
and all(item.get('can_build') and item.get('effective_reservation_id') for item in line_projections)
and not build_blocking_issues
and all(item.get('effective_reservation_id') for item in line_projections)
and bool(line_projections)
)
fields_complete = (
@@ -12,8 +12,17 @@ import re
from decimal import Decimal, InvalidOperation
from typing import Any
from app.services.shipping_notice.notice_line_table import parse_notice_table_text
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
from app.services.shipping_notice.notice_line_table import (
find_notice_header_row_index,
parse_notice_row,
parse_notice_table_text,
)
from app.services.shipping_notice.notice_line_values import resolve_notice_columns
from app.services.shipping_notice.order_schema.table_contract import (
compile_table_header_contract,
normalize_table_header,
)
from app.services.shipping_notice.po_number import normalize_po_number
from app.services.shipping_notice.reservation_id import validated_reservation_id
@@ -33,11 +42,49 @@ def _comparable_value(field: str, value: Any) -> str:
return str(value or "").strip().upper()
def _scan_email_po_aws_header(
header: list[str], schema_definition: dict[str, Any],
) -> tuple[int | None, int | None]:
"""
定位邮件正文表头中 PO 与 AWS SKU 的列索引。
背景:`po_number` 为 header 作用域、`aws_part_number` 不在 TABLE_FIELD_CODES 内,两者都不会被
compile_table_header_contract 编入契约,故 `parse_notice_row` 永远不会产出这两个字段。正文订单索引行
需要额外保留它们,才能在按 PO 融合附件时回填正文分配字段(如 inventory_source_hint / customer_part_number
等)。为不移除共享表头契约(守约严格性),这里只做独立的表头列扫描。
Returns:
返回 (po_idx, aws_idx);对应列不在表头时结果为 None。
"""
# 仅从本次预处理选择的 Schema 定义派生候选表头(field_code + display_name + aliases),避免硬编码漂移。
aliases: dict[str, set[str]] = {"po_number": set(), "aws_part_number": set()}
for raw in schema_definition.get("fields") or []:
code = str(raw.get("field_code") or "").strip()
if code not in aliases:
continue
for candidate in (code, raw.get("display_name"), *(raw.get("aliases") or [])):
normalized = normalize_table_header(candidate)
if normalized:
aliases[code].add(normalized)
po_idx = None
aws_idx = None
for i, cell_text in enumerate(header):
normalized = normalize_table_header(cell_text)
if normalized and normalized in aliases["po_number"]:
po_idx = i
if normalized and normalized in aliases["aws_part_number"]:
aws_idx = i
return po_idx, aws_idx
def build_email_order_index(body_text: str, *, schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
"""
从邮件正文表格提取订单索引行。
核心逻辑:复用统一订单表格解析器,并只保留具备 PO 或 Reservation 的有效订单行。
核心逻辑:复用统一订单表格解析器抽标准明细字段,并额外按正文原始表头回填 `po_number` 与
`aws_part_number`(两者因作用域/字段表不在共享契约中,parse_notice_row 不产出),供按 PO 融合
附件时补正文分配字段。最后只保留具备 PO 或 Reservation 的有效订单行。
Args:
body_text: 邮件正文纯文本。
schema_definition: 本次预处理明确选择的订单 Schema 定义。
@@ -45,7 +92,44 @@ def build_email_order_index(body_text: str, *, schema_definition: dict[str, Any]
正文订单索引列表。
"""
contract = compile_table_header_contract(schema_definition)
rows = parse_notice_table_text(str(body_text or ""), contract=contract)
text = str(body_text or "")
# 先用共享解析器判空;无有效行时直接退化为共享结果,避免空文本重复自建解析。
if not parse_notice_table_text(text, contract=contract):
return []
raw_rows = _rows_from_table_text(text)
if not raw_rows:
return []
header_idx = find_notice_header_row_index(raw_rows, contract=contract)
header = [str(c or "").strip() for c in raw_rows[header_idx]]
po_idx, aws_idx = _scan_email_po_aws_header(header, schema_definition)
columns = resolve_notice_columns(header, contract)
if columns.get("_ambiguous_fields"):
return []
idx_res = columns.get("reservation_id")
if idx_res is not None and idx_res < len(header):
columns["_reservation_id_header"] = str(header[idx_res] or "").strip()
rows: list[dict[str, Any]] = []
for raw_row in raw_rows[header_idx + 1:]:
if not raw_row:
continue
parsed = parse_notice_row(list(raw_row), columns, contract=contract)
if parsed is None:
continue
# 回填共享解析器不产出的 PO / AWS SKU,保证正文行与原始表列强对齐。
if po_idx is not None and po_idx < len(raw_row):
po_number = str(raw_row[po_idx] or "").strip()
if po_number:
parsed["po_number"] = po_number
if aws_idx is not None and aws_idx < len(raw_row):
aws_part_number = str(raw_row[aws_idx] or "").strip()
if aws_part_number:
parsed["aws_part_number"] = aws_part_number
rows.append(parsed)
return [
row for row in rows
if normalize_po_number(row.get("po_number"))
@@ -1,289 +0,0 @@
"""
backend/app/services/shipping_notice/order_customer_matching.py
用途:将订单解析出的 Bill-to / Ship-to 名称和外部编码匹配到客户及送货站点主数据。
依赖:ShippingCustomer、外部编码、客户站点/标识、ShippingOrderCustomerMatch、客户名称规范化。
逻辑:外部编码优先于名称;Bill-to 匹配标准客户,Ship-to 匹配客户站点,唯一命中保存简称快照。
"""
from __future__ import annotations
import hashlib
import json
from datetime import datetime
from typing import Any
from app import db
from app.core.errors import NotFoundError, ValidationError
from app.models import (
ShippingCustomer,
ShippingCustomerExternalRef,
ShippingCustomerIdentifier,
ShippingCustomerSite,
ShippingCustomerSiteIdentifier,
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
)
from app.services.shipping_notice.customer_normalization import normalize_customer_name
ROLE_FIELDS = {
'bill_to': {'name': 'bill_to_customer', 'code': 'bill_to_customer_code', 'source': 'bill_to_source_system'},
'ship_to': {'name': 'ship_to_customer', 'code': 'ship_to_code', 'source': 'ship_to_source_system'},
}
IDENTITY_RULE_VERSION = 'order-customer-fingerprint.v1'
def _normalized_code(value: Any) -> str:
"""规范外部客户/站点编码,保留业务符号并统一大小写。"""
return str(value or '').strip().upper()
def _identity_fingerprint(*, role: str, raw_name: str, external_code: str, source_system: str) -> tuple[str, dict[str, str]]:
"""用订单原文标准化值和固定规则版本生成稳定身份指纹,不写回或替换原始字段。"""
components = {
'role': role,
'normalized_name': normalize_customer_name(raw_name) if raw_name else '',
'external_code': _normalized_code(external_code),
'source_system': _normalized_code(source_system),
}
encoded = json.dumps(
{'rule_version': IDENTITY_RULE_VERSION, 'components': components},
ensure_ascii=True, sort_keys=True, separators=(',', ':'),
).encode('utf-8')
return hashlib.sha256(encoded).hexdigest(), components
def _customer_candidates(raw_name: str) -> list[dict[str, Any]]:
"""按标准名称和 approved 名称别名返回稳定去重的启用客户候选。"""
normalized = normalize_customer_name(raw_name)
if not normalized:
return []
customers = db.session.query(ShippingCustomer).filter_by(status='active').all()
matched: dict[int, dict[str, Any]] = {}
for customer in customers:
if normalize_customer_name(customer.standard_name) == normalized:
matched[customer.id] = {
'customer_id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'matched_by': ['standard_name'],
}
aliases = db.session.query(ShippingCustomerIdentifier).filter_by(
identifier_type='name_alias', normalized_value=normalized, status='approved',
).all()
active_by_id = {customer.id: customer for customer in customers}
for alias in aliases:
customer = active_by_id.get(int(alias.customer_id))
if customer is None:
continue
candidate = matched.setdefault(customer.id, {
'customer_id': customer.id,
'standard_name': customer.standard_name,
'short_code': customer.short_code,
'matched_by': [],
})
if 'name_alias' not in candidate['matched_by']:
candidate['matched_by'].append('name_alias')
return sorted(matched.values(), key=lambda item: (item['standard_name'], item['customer_id']))
def _bill_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]:
"""优先按来源系统和外部客户编码匹配 Bill-to,再回退名称匹配。"""
code = _normalized_code(external_code)
source = _normalized_code(source_system)
if code and source:
refs = db.session.query(ShippingCustomerExternalRef).filter_by(
source_system=source, legacy_customer_key=code,
).all()
candidates = []
for ref in refs:
customer = db.session.get(ShippingCustomer, int(ref.customer_id))
if customer and customer.status == 'active':
candidates.append({
'customer_id': customer.id, 'standard_name': customer.standard_name,
'short_code': customer.short_code, 'site_id': None, 'site_name': None,
'site_code': None, 'matched_by': ['external_customer_code'],
})
if candidates:
return candidates
return [{**item, 'site_id': None, 'site_name': None, 'site_code': None} for item in _customer_candidates(raw_name)]
def _ship_to_candidates(raw_name: str, external_code: str, source_system: str) -> list[dict[str, Any]]:
"""优先按 Ship-to Code 匹配启用站点,再按站点名称或已审核别名匹配。"""
code = _normalized_code(external_code)
source = _normalized_code(source_system)
sites = db.session.query(ShippingCustomerSite).filter_by(status='active').all()
matched: dict[int, dict[str, Any]] = {}
matched_site_ids: dict[int, str] = {}
if code:
identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by(
identifier_type='external_code', source_system=source, normalized_value=code, status='approved',
).all()
for identifier in identifiers:
matched_site_ids[int(identifier.site_id)] = 'external_site_code'
for site in sites:
if _normalized_code(site.site_code) == code:
matched_site_ids[site.id] = 'site_code'
if not matched_site_ids:
normalized = normalize_customer_name(raw_name) if raw_name else ''
for site in sites:
if normalized and normalize_customer_name(site.site_name) == normalized:
matched_site_ids[site.id] = 'site_name'
if normalized:
identifiers = db.session.query(ShippingCustomerSiteIdentifier).filter_by(
identifier_type='name_alias', source_system='', normalized_value=normalized, status='approved',
).all()
for identifier in identifiers:
matched_site_ids[int(identifier.site_id)] = 'site_name_alias'
by_id = {site.id: site for site in sites}
for site_id, matched_by in matched_site_ids.items():
site = by_id.get(site_id)
customer = db.session.get(ShippingCustomer, int(site.customer_id)) if site else None
if site is None or customer is None or customer.status != 'active':
continue
matched[site.id] = {
'customer_id': customer.id, 'standard_name': customer.standard_name,
'short_code': customer.short_code, 'site_id': site.id, 'site_name': site.site_name,
'site_code': site.site_code, 'matched_by': [matched_by],
}
return sorted(matched.values(), key=lambda item: (item['standard_name'], item['site_name'], item['site_id']))
def refresh_order_customer_matches(
extraction: ShippingOrderExtraction,
header: dict[str, Any],
) -> list[dict[str, Any]]:
"""
根据订单头原文幂等刷新 Bill-to / Ship-to 客户匹配结果。
Args:
extraction: 已持久化的动态订单解析记录。
header: 已通过证据裁决的订单头字段投影。
Returns:
两种角色的匹配摘要;客户简称只来自客户主数据快照。
"""
results: list[dict[str, Any]] = []
for role, fields in ROLE_FIELDS.items():
raw_name = str(header.get(fields['name']) or '').strip()
external_code = _normalized_code(header.get(fields['code']))
source_system = _normalized_code(header.get(fields['source']))
fingerprint, components = _identity_fingerprint(
role=role, raw_name=raw_name, external_code=external_code, source_system=source_system,
)
candidates = (
_bill_to_candidates(raw_name, external_code, source_system)
if role == 'bill_to'
else _ship_to_candidates(raw_name, external_code, source_system)
)
row = db.session.query(ShippingOrderCustomerMatch).filter_by(
extraction_id=extraction.id, role=role,
).one_or_none()
if row is None:
row = ShippingOrderCustomerMatch(extraction_id=extraction.id, role=role)
db.session.add(row)
row.raw_name = raw_name or None
row.normalized_name = normalize_customer_name(raw_name) if raw_name else None
row.source_system = source_system or None
row.external_code = external_code or None
row.identity_fingerprint = fingerprint
row.identity_rule_version = IDENTITY_RULE_VERSION
row.identity_components_json = components
row.candidates_json = candidates
if len(candidates) == 1:
candidate = candidates[0]
row.status = 'unique_candidate'
row.customer_id = int(candidate['customer_id'])
row.site_id = int(candidate['site_id']) if candidate.get('site_id') else None
row.customer_name_snapshot = str(candidate['standard_name'])
row.customer_short_code_snapshot = str(candidate['short_code'])
row.resolution_method = str(candidate['matched_by'][0])
else:
row.status = 'ambiguous' if candidates else 'unmatched'
row.customer_id = None
row.site_id = None
row.customer_name_snapshot = None
row.customer_short_code_snapshot = None
row.resolution_method = None
row.confirmed_by_id = None
row.confirmed_at = None
row.confirmation_reason = None
row.updated_at = datetime.utcnow()
db.session.flush()
results.append(serialize_order_customer_match(row))
return results
def confirm_order_customer_match(
extraction_id: int,
*,
role: str,
customer_id: int,
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(
extraction_id=extraction_id, role=role,
).one_or_none()
if row is None:
raise NotFoundError('Order customer match not found', code='SHIPPING.ORDER_CUSTOMER_MATCH_NOT_FOUND')
reason_value = str(reason or '').strip()
if not reason_value:
raise ValidationError('Customer confirmation reason is required', code='SHIPPING.ORDER_CUSTOMER_CONFIRM_REASON_REQUIRED')
customer = db.session.get(ShippingCustomer, int(customer_id))
if customer is None:
raise NotFoundError('Customer not found', code='SHIPPING.CUSTOMER_NOT_FOUND')
if customer.status != 'active':
raise ValidationError('Inactive customer cannot be used', code='SHIPPING.CUSTOMER_INACTIVE')
selected_site = None
if role == 'ship_to':
selected_site = db.session.get(ShippingCustomerSite, int(site_id)) if site_id is not None else None
if selected_site is None or selected_site.customer_id != customer.id or selected_site.status != 'active':
raise ValidationError('Active Ship-to site is required', code='SHIPPING.ORDER_CUSTOMER_SITE_INVALID')
row.status = 'confirmed'
row.customer_id = customer.id
row.site_id = selected_site.id if selected_site else None
row.customer_name_snapshot = customer.standard_name
row.customer_short_code_snapshot = customer.short_code
row.resolution_method = 'manual'
row.confirmation_reason = reason_value
row.confirmed_by_id = actor_id
row.confirmed_at = datetime.utcnow()
if commit:
db.session.commit()
else:
db.session.flush()
return serialize_order_customer_match(row)
def serialize_order_customer_match(row: ShippingOrderCustomerMatch) -> dict[str, Any]:
"""输出前端可直接展示的角色匹配摘要,不暴露内部 ORM 状态。"""
return {
'id': row.id,
'extraction_id': row.extraction_id,
'role': row.role,
'raw_name': row.raw_name,
'status': row.status,
'customer_id': row.customer_id,
'site_id': row.site_id,
'source_system': row.source_system,
'external_code': row.external_code,
'identity_fingerprint': row.identity_fingerprint,
'identity_rule_version': row.identity_rule_version,
'standard_name': row.customer_name_snapshot,
'short_code': row.customer_short_code_snapshot,
'candidates': list(row.candidates_json or []),
'resolution_method': row.resolution_method,
'confirmation_reason': row.confirmation_reason,
}
@@ -178,6 +178,8 @@ def complete_wizard(data: dict[str, Any], *, actor_id: int | None) -> dict[str,
sample_role=sample_role, created_by_id=actor_id,
))
db.session.flush()
if document.asset_id:
profile_service._retain_profile_sample_assets(profile_id, asset_ids={int(document.asset_id)})
profile_service._refresh_training_sample_count(db.session.get(ShippingOrderDocumentProfile, profile_id))
revision_no = int(saved['draft_revision']['revision_no'])
profile_service._audit(
@@ -153,6 +153,7 @@ def _frozen_sample_context(
'Frozen sample file is unavailable',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
)
profile_service._repair_bound_sample_asset(document)
asset = db.session.get(FileAsset, int(document.asset_id))
if asset is None:
raise ValidationError(
@@ -239,6 +240,39 @@ def _render_pdf_pages(asset: FileAsset) -> list[Any]:
) from exc
def _frozen_physical_page_count(
*, layout_version: ShippingDocumentLayoutVersion, document: ShippingOrderDocument,
) -> int | None:
"""
从冻结 Layout 的完整页证据读取原 PDF 物理页数,供历史错误快照的只读兼容校验。
核心逻辑:持久化 Layout 可把坐标证据外置到受控 FileAsset,本函数只加载该冻结引用;
仅页面元数据可证明物理页数,绝不以业务表格页数作为回退。
Args:
layout_version: 已通过冻结 checksum 校验的 Layout 版本。
document: 与 Layout 绑定且已通过内容 hash 校验的样本文档。
Returns:
完整页证据可用时返回物理页数;证据缺失或结构无效时返回 None。
"""
from app.services.shipping_notice.document_layout.lifecycle import _hydrate_coordinate_evidence
payload = _hydrate_coordinate_evidence(
payload=dict(layout_version.payload_json or {}), document=document,
)
pages = payload.get('pages')
if isinstance(pages, list):
count = len([item for item in pages if isinstance(item, dict)])
if count:
return count
evidence = payload.get('coordinate_evidence')
evidence_pages = evidence.get('pages') if isinstance(evidence, dict) else None
if isinstance(evidence_pages, dict) and evidence_pages:
return len(evidence_pages)
return None
def authorize_frozen_sample_preview_pages(
profile_id: int,
*,
@@ -258,15 +292,18 @@ def authorize_frozen_sample_preview_pages(
profile = db.session.get(ShippingOrderDocumentProfile, int(profile_id))
if profile is None:
raise NotFoundError('Order document profile not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_NOT_FOUND')
_, sample, document, _layout_version, asset = _frozen_sample_context(
_, sample, document, layout_version, asset = _frozen_sample_context(
profile_id=int(profile_id), sample_binding_id=int(sample_binding_id),
)
pages = _render_pdf_pages(asset)
if sample.page_count_snapshot is not None and len(pages) != int(sample.page_count_snapshot):
raise ValidationError(
'Frozen page count no longer matches the published evidence',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
)
# [STEP 1] 兼容修复上线前把外置证据退化为表格页数的历史冻结记录;
# 只有同一冻结 Layout 的完整页证据与当前原 PDF 一致时才允许预览。
if _frozen_physical_page_count(layout_version=layout_version, document=document) != len(pages):
raise ValidationError(
'Frozen page count no longer matches the published evidence',
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_UNAVAILABLE',
)
store = _preview_grant_store()
preview_pages: list[dict[str, Any]] = []
for page in pages:
File diff suppressed because it is too large. Load diff
@@ -1136,6 +1136,20 @@ def _published_representative_samples(profile_id: int) -> list[ShippingOrderDocu
).all()
def published_rival_snapshots_for_overlap(profile: ShippingOrderDocumentProfile) -> list[dict[str, Any]]:
"""
跨模板唯一性候选:同 Schema 已发布快照,但排除本模板族。
发布时同 profile_code 的旧 published 会被 retire,新草稿不必与自家旧版比唯一性;
否则 clone 出的 v2 几乎必然与 v1 冲突。
"""
code = str(profile.profile_code or '')
return [
item for item in profile_service.published_snapshots_for_schema(profile.schema_version_id)
if str(item.get('profile_code') or '') != code
]
def _build_coordinate_overlap_evidence(
*,
profile: ShippingOrderDocumentProfile,
@@ -1152,11 +1166,7 @@ def _build_coordinate_overlap_evidence(
definition = dict(profile.definition_json or {})
thresholds = _match_thresholds(definition)
schema_definition = profile.schema_version.definition_json if profile.schema_version is not None else {}
published = [
item for item in profile_service.published_snapshots_for_schema(profile.schema_version_id)
if str(item.get('profile_code') or '') != profile.profile_code
or int(item.get('version') or 0) != int(profile.version)
]
published = published_rival_snapshots_for_overlap(profile)
candidates = [draft_snapshot, *published]
sample_role_pollution = _detect_sample_role_pollution(profile)
@@ -0,0 +1,182 @@
"""
services/shipping_notice/order_edit_window_service.py
用途:确认后、Excel 生成前的订单编辑窗谓词(设计 D10 / §3.1)。集中判定哪些头字段/行字段允许编辑,
前端 fail-closed 渲染,后端保存守卫复用同一谓词。
依赖:ShippingNotice / ShippingExportArtifact / ShippingOrderReviewWaveLine / progress_workflow。
逻辑(§3.1 矩阵):
header = 该订单**任一通知**无 Export Artifact 且无活动 Gate Attempt;
lines = 逐行:行已入某波次 → 该波次通知无 Export Artifact 且无活动 Attempt;
行未入波次 → 无活动 Attempt(不受首单 Excel 限制,D10)。
编辑窗谓词收敛在单一服务,避免「用户不修改原始订单」原则被扩大解释(D12)。
"""
from __future__ import annotations
from typing import Any
from app.models import ShippingNotice, ShippingOrderTask
from app.models.shipping_excel_template import ShippingExportArtifact
# 导出产物一旦落库即视为 Excel 已生成(锁定边界 D7);上传中/已上传同属生成后。
_ARTIFACT_LOCK_STATUSES = frozenset({'ready', 'uploading', 'uploaded', 'succeeded', 'success'})
def _notice_has_export_artifact(notice: ShippingNotice) -> bool:
"""该通知是否已生成导出产物(Excel)。"""
if getattr(notice, 'id', None) is None:
return False
row = (
ShippingExportArtifact.query
.filter(ShippingExportArtifact.task_id == int(notice.id))
.order_by(ShippingExportArtifact.id.desc())
.first()
)
return bool(row is not None and str(row.status or '') in _ARTIFACT_LOCK_STATUSES)
def _notice_has_active_attempt(notice: ShippingNotice) -> bool:
"""该通知是否有活动 Gate Attempt(库存 RPA / 匹配 queued|running)。"""
from app.services.shipping_notice.progress_workflow import _has_active_gate_attempts
task = db_session_get(ShippingOrderTask, int(notice.order_task_id)) if getattr(notice, 'order_task_id', None) else None
return bool(_has_active_gate_attempts(task)) if task is not None else False
def _order_notices(notice: ShippingNotice) -> list[ShippingNotice]:
"""同一订单(同 order_task_id)下的全部通知(含波次);无 OT 指针时退回本通知。"""
order_task_id = getattr(notice, 'order_task_id', None)
if not order_task_id:
return [notice]
rows = list(
ShippingNotice.query
.filter(ShippingNotice.order_task_id == int(order_task_id))
.order_by(ShippingNotice.id.asc())
.all()
)
return rows or [notice]
def order_has_active_attempt(order_task: ShippingNotice) -> bool:
"""订单级活动 Attempt 判定:该订单**任一通知**有活动 Gate Attempt(§3.1 header 谓词)。"""
return any(_notice_has_active_attempt(n) for n in _order_notices(order_task))
def _review_case_id_for_notice(notice: ShippingNotice) -> int | None:
"""回读该通知所属复核 Case(经 ConfirmedRevision);无则 None。"""
from app.models import ShippingOrderReviewConfirmedRevision, ShippingOrderTask
task_id = getattr(notice, 'order_task_id', None)
if task_id is None:
return None
row = (
ShippingOrderReviewConfirmedRevision.query
.filter(ShippingOrderReviewConfirmedRevision.task_id == int(task_id))
.order_by(ShippingOrderReviewConfirmedRevision.id.desc())
.first()
)
return int(row.case_id) if row is not None else None
def _wave_line_to_notice_map(review_case_id: int | None) -> dict[str, int]:
"""复核 Case 下的 snapshot_line_id -> 波次通知 task_id 映射。"""
if review_case_id is None:
return {}
from app.models import ShippingOrderReviewWaveLine
rows = ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(review_case_id)).all()
return {
str(row.snapshot_line_id): int(row.task_id)
for row in rows
if row.snapshot_line_id is not None
}
def _order_snapshot_line_ids(notice: ShippingNotice) -> list[str]:
"""该订单可编辑范围内的全部冻结行身份(以 Snapshot 行为准,波次行并入)。"""
from app.models.shipping_notice_line import ShippingNoticeLine
notice_id = getattr(notice, 'id', None)
if notice_id is None:
return []
keys: list[str] = []
for item in (
ShippingNoticeLine.query
.filter(ShippingNoticeLine.notice_id == int(notice_id))
.order_by(ShippingNoticeLine.position.asc())
.all()
):
key = str(getattr(item, 'snapshot_line_id', '') or '').strip()
if key:
keys.append(key)
review_case_id = _review_case_id_for_notice(notice)
if review_case_id is not None:
for key in _wave_line_to_notice_map(review_case_id):
if key not in keys:
keys.append(key)
return sorted(set(keys), key=lambda value: int(value))
def editable_scope(order_task: ShippingNotice) -> dict[str, Any]:
"""
计算确认后订单的编辑窗矩阵(D10 / §3.1)。
header = 该订单全部通知(含波次)无 Export Artifact 且无活动 Gate Attempt。
lines = 逐行:行已入某波次 → 该波次通知无 Export Artifact 且无活动 Attempt;
行未入波次 → 无活动 Attempt(不受首单 Excel 限制)。
Args:
order_task: 正式订单的主 ShippingNotice(含 order_task_id 可回读同订单全部通知)。
Returns:
dict: {'header': bool, 'lines': {snapshot_line_id: bool}},同构供 ui_state.edit_window 下发。
"""
notices = _order_notices(order_task)
order_busy = any(_notice_has_active_attempt(n) for n in notices)
header_has_excel = any(_notice_has_export_artifact(n) for n in notices)
header = (not header_has_excel) and (not order_busy)
wave_notice_map = _wave_line_to_notice_map(_review_case_id_for_notice(order_task))
lines: dict[str, bool] = {}
for snapshot_line_id in _order_snapshot_line_ids(order_task):
wave_task_id = wave_notice_map.get(snapshot_line_id)
if wave_task_id is None:
# 未入波次行:不受首单 Excel 限制,仅受活动 Attempt 影响。
lines[snapshot_line_id] = not order_busy
continue
wave_notice = next((n for n in notices if int(getattr(n, 'id', 0)) == int(wave_task_id)), None)
wave_notice = wave_notice or db_session_get(ShippingNotice, int(wave_task_id))
lines[snapshot_line_id] = (
(not _notice_has_export_artifact(wave_notice)) and (not order_busy)
if wave_notice is not None else False
)
return {'header': header, 'lines': lines}
def db_session_get(model: Any, pk: int) -> Any:
"""最小 Session get 封装,避免模块顶部导入 db 形成循环。"""
from app import db
return db.session.get(model, int(pk))
def assert_field_editable(scope: dict[str, Any], *, field: dict[str, Any], snapshot_line_id: str | None = None) -> bool:
"""
保存守卫辅助:按谓词判断单个头字段/行字段是否可编辑。
Args:
scope: editable_scope 结果。
field: 目标字段描述(含 scope='header' 或 scope='line')。
snapshot_line_id: line 作用域时必填;None 视为 header。
Returns:
bool:可编辑返回 True;应被 SHIPPING.EDIT_WINDOW_FIELD_LOCKED 拒绝时返回 False。
"""
if str((field or {}).get('scope') or '').strip() == 'line':
if not snapshot_line_id:
return False
return bool(scope.get('lines', {}).get(snapshot_line_id))
return bool(scope.get('header'))
@@ -49,7 +49,6 @@ from app.models import (
ShippingOrderDocument,
ShippingOrderIntake,
ShippingOrderTask,
ShippingNotice,
ShippingOrderExtraction,
)
from app.services.shipping_notice.business_fingerprint import (
@@ -503,9 +502,7 @@ def persist_order_extraction_result(
if str(item.get('reason') or '') != 'layout_table_needs_review'
])
summary = {**dynamic['header'], 'lines': dynamic['lines']}
# Bill-to 是业务归属客户原文;简称只保存在 customer_matches 主数据快照中。
if summary.get('bill_to_customer'):
summary['customer_name'] = summary['bill_to_customer']
# Bill-to 仅保留为订单原文/识别证据,不复制为通用客户名称。
if dynamic['blocked_fields']:
blocked_set = {
str(code).strip()
@@ -659,7 +656,6 @@ def persist_order_extraction_result(
'findings': list(dynamic.get('findings') or []),
'diagnostic_findings': diagnostic_findings,
},
'customer_matches': dynamic['customer_matches'],
'missing_required_fields': assessment['missing_required_fields'],
'missing_process_fields': assessment['missing_process_fields'],
'process_issues': assessment['process_issues'],
@@ -933,7 +929,7 @@ def persist_order_extraction_result(
if not target_no:
continue
target = (
db.session.query(ShippingNotice)
db.session.query(ShippingOrderTask)
.filter_by(task_no=target_no, user_id=int(session.user_id))
.with_for_update()
.first()
@@ -1107,7 +1103,7 @@ def submit_order_extraction_run_result(
}
task_nos = sorted({
str(task.task_no)
for task in ShippingNotice.query.filter(ShippingNotice.id.in_(consumed_task_ids)).all()
for task in ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(consumed_task_ids)).all()
}) if consumed_task_ids else []
pending = [candidate for candidate in run_candidates if candidate.consumed_task_id is None]
result = {
@@ -1348,8 +1344,8 @@ def submit_order_extraction_unit_result(
if consumed:
task_nos = sorted({
str(task.task_no)
for task in ShippingNotice.query.filter(
ShippingNotice.id.in_([int(row.consumed_task_id) for row in consumed])
for task in ShippingOrderTask.query.filter(
ShippingOrderTask.id.in_([int(row.consumed_task_id) for row in consumed])
).all()
})
result = {
@@ -4,7 +4,7 @@ services/shipping_notice/order_extraction_merge.py
用途:在 HXOPS 内按稳定业务身份合并文档单元订单,并保留全部字段证据供后续裁决。
依赖:Run 冻结动态 Schema field_id/field_code 映射。
逻辑:同 Intake 下仅 PO 一致或 Line 的 part_number+reservation_id 一致时合并;
跨文档 Reservation 补全优先使用 part_number / customer_po_line_no(兼容历史 line_no)。
跨文档 Reservation 补全优先使用 part_number / customer_po_line_no。
阶段 2:默认 keep_primary_documents_separate=True,不同 primary_document_id
(多 PDF)不得合并为同一 Candidate;EML 内补充仍走 order_supplement_merge。
"""
@@ -52,7 +52,7 @@ def _single_valid_reservation(line: dict[str, Any], codes: dict[str, str]) -> st
def _completion_anchor_values(line: dict[str, Any], codes: dict[str, str]) -> dict[str, str]:
"""读取可用于 PDF/邮件行补全的强锚点;只接受单一原子值。"""
anchors: dict[str, str] = {}
for field_code in ('part_number', 'customer_po_line_no', 'line_no'):
for field_code in ('part_number', 'customer_po_line_no'):
values = _field_values(line.get('fields'), field_code, codes)
if len(values) == 1:
anchors[field_code] = next(iter(values))
@@ -104,11 +104,11 @@ def _order_identity(order: dict[str, Any], codes: dict[str, str]) -> tuple[set[s
for value in _field_values(order.get('header_fields'), field_code, codes)
if (normalized := normalize_atomic_po_number(value).upper())
}
line_keys = {
line_identities = {
identity for line in order.get('lines') or []
if isinstance(line, dict) and (identity := _line_identity(line, codes)) is not None
}
return po_numbers, line_keys
return po_numbers, line_identities
def _merge_fields(target: list[dict[str, Any]], incoming: Any) -> None:
@@ -196,7 +196,7 @@ def merge_unit_orders(
order = copy.deepcopy(raw)
intake_no = str(order.get('source_intake_no') or '').strip().upper()
primary_document_id = order.get('primary_document_id')
po_numbers, line_keys = _order_identity(order, codes)
po_numbers, line_identities = _order_identity(order, codes)
match = None
matched_by_po = False
for candidate in merged:
@@ -212,7 +212,7 @@ def merge_unit_orders(
continue
candidate_pos, candidate_lines = _order_identity(candidate, codes)
matched_by_po = len(po_numbers) == 1 and po_numbers == candidate_pos
if matched_by_po or bool(line_keys & candidate_lines):
if matched_by_po or bool(line_identities & candidate_lines):
match = candidate
break
if match is None:
@@ -3306,6 +3306,8 @@ def list_order_extraction_run_summaries(
核心逻辑:列表端只需定位最新 Run 与展示摘要,故用标量列投影直接绕过 ORM 实体;
`input_snapshot_json` / `request_snapshot_json` 只能由单 Run 详情路径按需读取。
会话短列表(非分页)优先返回带 client_submission_id 的 submission primary,
避免一次多 Intake 拆出的 sibling 因 created_at 更新被误选为恢复锚点。
Args:
user_id: 当前用户主键。
@@ -3341,8 +3343,19 @@ def list_order_extraction_run_summaries(
ShippingOrderProcessingRun.last_activity_at,
ShippingOrderProcessingRun.created_at,
ShippingOrderProcessingRun.updated_at,
ShippingOrderProcessingRun.client_submission_id,
)
statement = select(*columns).where(*filters).order_by(ShippingOrderProcessingRun.created_at.desc())
# [STEP] 会话恢复短列表:primary(有 client_submission_id)排前,再按创建时间倒序。
# 分页任务中心仍按纯时间序,避免 sibling 被隐藏。
if conversation_id and page is None and page_size is None:
statement = select(*columns).where(*filters).order_by(
ShippingOrderProcessingRun.client_submission_id.isnot(None).desc(),
ShippingOrderProcessingRun.created_at.desc(),
)
else:
statement = select(*columns).where(*filters).order_by(
ShippingOrderProcessingRun.created_at.desc(),
)
if page is None and page_size is None:
return list(db.session.execute(
statement.limit(min(max(int(limit or 50), 1), 100)),
@@ -3613,6 +3626,8 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str,
if isinstance(run.input_snapshot_json, dict)
else None
),
# 仅 submission primary 有值;sibling Run 为空。聊天恢复必须锚定 primary,禁止用 sibling 再建卡。
'client_submission_id': str(run.client_submission_id or '').strip() or None,
'schema_version_id': run.schema_version_id,
'schema_version': schema_snapshot.get('version'),
'schema_checksum': schema_snapshot.get('checksum'),
@@ -3662,6 +3677,9 @@ def serialize_order_extraction_run_list_item(run: Any) -> dict[str, Any]:
'conversation_id': row['conversation_id'],
'status': str(row['status'] or 'queued'),
'phase': str(row['phase'] or row['status'] or 'queued'),
'client_submission_id': (
str(row.get('client_submission_id') or '').strip() or None
),
'summary': {
'total_documents': int(progress_summary.get('total_documents') or 0),
'pending_documents': int(progress_summary.get('pending_documents') or 0),
@@ -4506,12 +4524,18 @@ def sync_order_extraction_run_after_job_recovery(job: Any) -> None:
Args:
job: 已由 `recover_stale_jobs` 条件更新成功并刷新的 Job。
"""
from app.services.shipping_notice.order_review_workbench_projection import (
project_job_status_outcome,
)
run = ShippingOrderProcessingRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
if run is None or run.status in {'completed', 'partially_completed', 'review_required', 'cancelled'}:
return
if job.status == 'queued' and run.status == 'processing':
transition_order_extraction_run(run, target_status='queued', phase='timeout_retry_queued')
elif job.status in {'failed', 'dead', 'cancelled'} and run.status in {'queued', 'processing'}:
elif (
project_job_status_outcome(getattr(job, 'status', None)) == 'failed'
or str(getattr(job, 'status', None) or '').strip().lower() == 'cancelled'
) and run.status in {'queued', 'processing'}:
if run.status == 'queued':
transition_order_extraction_run(run, target_status='processing', phase='timeout_failing')
transition_order_extraction_run(
@@ -372,7 +372,7 @@ def _coordinate_profile_rows(
return None
rows: list[dict[str, Any]] = []
runtime_region_ids = set(select_runtime_region_ids(
table_regions=[region.model_dump() for region in profile.table_regions], page_no=page_no,
table_regions=[_coordinate_object_mapping(region) for region in profile.table_regions], page_no=page_no,
))
for region in profile.table_regions:
# 标注页优先;续页仅回退到稳定的基础表区。是否真正属于明细页仍由当前页
@@ -385,7 +385,11 @@ def _coordinate_profile_rows(
relative_region = _coordinate_region_mapping(region.region)
if relative_region is None:
return None
reference_page_frame = profile.reference_page_frames.get(page_no)
reference_page_frames = getattr(profile, 'reference_page_frames', {})
reference_page_frame = (
reference_page_frames.get(page_no)
if isinstance(reference_page_frames, dict) else None
)
reconstruction_page_bbox = (
{
'x0': 0, 'y0': 0,
@@ -395,9 +399,10 @@ def _coordinate_profile_rows(
)
raw_bbox = raw_table.get('bbox') if isinstance(raw_table.get('bbox'), dict) else None
characters, _candidate_page_bbox = coordinate_profile_character_candidates(
table_region=region.region.model_dump(), page_size=page_size,
table_region=_coordinate_object_mapping(region.region), page_size=page_size,
reference_page_frame=(
reference_page_frame.model_dump() if reference_page_frame is not None else None
_coordinate_object_mapping(reference_page_frame)
if reference_page_frame is not None else None
),
page_characters=page_characters if isinstance(page_characters, list) else None,
table_characters=tables.get(table_id) if isinstance(tables.get(table_id), list) else None,
@@ -410,11 +415,11 @@ def _coordinate_profile_rows(
carry = initial_carry if isinstance(initial_carry, dict) and initial_carry.get('region_id') == region.region_id else {}
for reconstructed in reconstruct_coordinate_profile_rows(
characters=[item for item in characters if isinstance(item, dict)], table_bbox=reconstruction_page_bbox,
line_layouts=[item.model_dump() for item in region.line_layouts],
line_layouts=[_coordinate_object_mapping(item) for item in region.line_layouts],
table_region=relative_region,
termination_rules=[item.model_dump() for item in region.termination_rules],
termination_rules=[_coordinate_object_mapping(item) for item in region.termination_rules],
exclusion_regions=reconstruction_exclusion_regions(
region.model_dump(),
_coordinate_object_mapping(region),
),
initial_fields=carry.get('fields'), initial_next_offset=int(carry.get('next_offset') or 0),
line_start_field_code=region.line_start_field_code,
@@ -514,12 +519,7 @@ def _coordinate_region_mapping(value: Any) -> dict[str, float] | None:
Returns:
包含 x0/y0/x1/y1 的合法浮点坐标;缺字段、非数值或区域退化时返回 None。
"""
if isinstance(value, dict):
raw = value
elif callable(getattr(value, 'model_dump', None)):
raw = value.model_dump()
else:
raw = {key: getattr(value, key, None) for key in ('x0', 'y0', 'x1', 'y1')}
raw = _coordinate_object_mapping(value)
if not isinstance(raw, dict):
return None
try:
@@ -531,6 +531,22 @@ def _coordinate_region_mapping(value: Any) -> dict[str, float] | None:
return region
def _coordinate_object_mapping(value: Any) -> dict[str, Any]:
"""将冻结坐标契约对象转换为字典,兼容 Pydantic 与测试使用的轻量对象。
生产 Profile 使用 Pydantic ``model_dump``;运行时和回归测试也允许同字段的
轻量对象。转换失败返回空字典,后续既有坐标校验按证据不足处理,不扩大匹配范围。
"""
if isinstance(value, dict):
return value
dump = getattr(value, 'model_dump', None)
if callable(dump):
raw = dump()
return raw if isinstance(raw, dict) else {}
raw = getattr(value, '__dict__', None)
return dict(raw) if isinstance(raw, dict) else {}
def _coordinate_regions_overlap(left: dict[str, Any], right: dict[str, Any]) -> bool:
"""判断两个 PDF 绝对坐标区域是否有面积交集;无效坐标按不相交处理。"""
try:
@@ -549,11 +565,23 @@ def _physical_table_targets_profile_region(
reference_page_frame: dict[str, Any] | None = None,
coordinate_transform: dict[str, Any] | None = None,
) -> bool:
"""判断物理表是否属于当前页模板的明细区域;未知几何保守保留为候选。
"""
判断物理表是否属于当前页模板的明细区域;未知几何保守保留为候选。
同页的页脚汇总、签章等 MinerU 物理表不属于订单明细模板,不能因其无法重建
而阻断已成功的目标表。虚拟页、缺失 bbox 或页尺寸异常时维持既有整页坐标回退,
避免表检测遗漏被错误跳过。
核心逻辑:同页页脚/签章等非目标 MinerU 表不得因重建失败阻断已成功目标表。
当前页已配置专属表区但全部没有 ``line_layouts``(仅表头壳)时明确跳过,
避免空重建产出 ``PARSE_STRATEGY_NO_VALID_ROW_RECONSTRUCTION`` 污染整单。
虚拟页、缺失 bbox 或页尺寸异常时仍 fail-open,避免表检测遗漏被错误跳过。
Args:
raw_table: 物理表身份、页码与 bbox。
table_regions: 冻结 Profile 的表区列表(含 page_scope / line_layouts)。
page_size: 当前页宽高;缺失时保守保留候选。
reference_page_frame: 可选参考页框,用于相对坐标投影。
coordinate_transform: matcher 已确认的平移;可为 None。
Returns:
True 表示应进入坐标行重建;False 表示跳过该物理表。
"""
page_no = int(raw_table.get('page_no') or 1)
if str(raw_table.get('table_id') or '') == f'page-{page_no}':
@@ -572,15 +600,23 @@ def _physical_table_targets_profile_region(
active_region_ids = set(select_runtime_region_ids(
table_regions=table_regions, page_no=page_no,
))
active_regions = [
# [STEP 1] 当前页被选中的表区(不论是否含明细子行)
page_regions = [
region for region in table_regions
if isinstance(region, dict)
and str(region.get('region_id') or '') in active_region_ids
and isinstance(region.get('region'), dict)
and region.get('line_layouts')
]
if not page_regions:
# 本页无模板表区配置:保守保留,供虚拟页/漏检回退。
return True
# [STEP 2] 仅含 line_layouts 的明细区才是重建目标;纯表头壳直接跳过。
active_regions = [
region for region in page_regions
if region.get('line_layouts')
]
if not active_regions:
return True
return False
for region in active_regions:
projected = apply_coordinate_transform_to_region(
region['region'], coordinate_transform=coordinate_transform,
@@ -881,20 +917,24 @@ def _profile_table_candidates(
profile_match=profile_match, raw_profile=raw_profile,
)
profile_table_regions = [
item.model_dump() for item in profile.table_regions
if callable(getattr(item, 'model_dump', None))
_coordinate_object_mapping(item) for item in profile.table_regions
]
evidence_pages = (
(layout.get('coordinate_evidence') or {}).get('pages') or {}
)
page_size = evidence_pages.get(str(raw_table.get('page_no') or 1))
reference_page_frame = profile.reference_page_frames.get(int(raw_table.get('page_no') or 1))
reference_page_frames = getattr(profile, 'reference_page_frames', {})
reference_page_frame = (
reference_page_frames.get(int(raw_table.get('page_no') or 1))
if isinstance(reference_page_frames, dict) else None
)
if not _physical_table_targets_profile_region(
raw_table=raw_table,
table_regions=profile_table_regions,
page_size=page_size if isinstance(page_size, dict) else None,
reference_page_frame=(
reference_page_frame.model_dump() if reference_page_frame is not None else None
_coordinate_object_mapping(reference_page_frame)
if reference_page_frame is not None else None
),
coordinate_transform=coordinate_transform,
):
@@ -934,14 +974,17 @@ def _profile_table_candidates(
except (TypeError, ValueError):
issues.append('order_profile_snapshot_invalid')
continue
if fixed_rows is None or adaptive_rows is None or dynamic_rows is None:
issues.append('order_profile_coordinate_reconstruction_unavailable')
continue
# 虚拟空页(无业务表)不能把已成功的目标表覆盖成失败;None 与空列表
# 同样视为“无行”,且必须在该判断之前处理,否则空虚拟页会被
# is None 分支误判为行重建失败而整单阻断。
if _virtual_page_without_rows_is_nonblocking(
raw_table=raw_table, fixed_rows=fixed_rows, adaptive_rows=adaptive_rows,
dynamic_rows=dynamic_rows,
):
continue
if fixed_rows is None or adaptive_rows is None or dynamic_rows is None:
issues.append('order_profile_coordinate_reconstruction_unavailable')
continue
strategy = resolve_runtime_parse_strategy(
page_glyphs=(layout.get('coordinate_evidence') or {}).get('page_glyphs') or {},
fixed_rows=fixed_rows, adaptive_rows=adaptive_rows,
@@ -1317,7 +1317,13 @@ def _unresolved_review_document_count(
def _current_non_terminal_review_cases(run: ShippingOrderProcessingRun) -> list[ShippingOrderReviewCase]:
"""返回该 Run 产出的文件 Stream 当前非终态 Case;Run 的历史 Case 不参与工作台统计。"""
"""返回该 Run 产出的文件 Stream 当前非终态 Case;Run 的历史 Case 不参与工作台统计。
转瞬/未持久化 Run(id=None,如纯单元投影)不存在落库 Case,按空集处理,
与 _duplicate_projection_by_document / _pending_order_facts 的 run.id 防空一致。
"""
if getattr(run, 'id', None) is None:
return []
return (
db.session.query(ShippingOrderReviewCase)
.join(
@@ -26,7 +26,10 @@ _PURPOSE_BY_CAPABILITY = {
def task_line_purpose_field_ids(task: ShippingNotice, *, required: set[str] | None = None) -> dict[str, str]:
"""读取冻结策略能力与字段 ID,防止 Schema 或策略后续发布重解释任务。"""
source_notice = _source_notice_for_order_facts(task)
snapshot = db.session.get(ShippingOrderSnapshot, source_notice.order_snapshot_id) if source_notice.order_snapshot_id else None
from app.models import ShippingOrderTask
owner = db.session.get(ShippingOrderTask, source_notice.order_task_id) if getattr(source_notice, 'order_task_id', None) else source_notice
snapshot_id = getattr(owner, 'order_snapshot_id', None)
snapshot = db.session.get(ShippingOrderSnapshot, snapshot_id) if snapshot_id else None
if snapshot is None:
raise ValueError('任务没有可用于履约的冻结订单快照')
rule = (snapshot.rule_versions_json or {}).get('fulfillment_rule')
@@ -2,10 +2,10 @@
services/shipping_notice/order_freeze_service.py
用途:将已复核的动态订单解析冻结为强类型履约快照。
依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingNotice、
依赖:ShippingOrderExtraction/FieldValue/Observation、ShippingOrderSnapshot、ShippingOrderTask、
standard_field_registry(投影列)、audit_service、统一 AppError。
逻辑:Candidate/Extraction 阶段可继续保留动态证据;本服务通过门禁后一次写入按 field_id 冻结的 Snapshot;
冻结时固化 derivation_rules 快照与 field_lineage;库存、导出和上传后续阶段只读取该快照。
冻结时固化字段血缘;库存、导出和上传后续阶段只读取该快照。
"""
from __future__ import annotations
@@ -22,11 +22,10 @@ from app.models import (
ShippingOrderFieldObservation,
ShippingOrderFieldValue,
ShippingOrderLine,
ShippingOrderCustomerMatch,
ShippingOrderReviewEvent,
ShippingOrderSnapshot,
ShippingOrderSnapshotLine,
ShippingNotice,
ShippingOrderTask,
ShippingOrderDocument,
)
from app.services.shipping_notice.audit_service import append_shipping_audit_event
@@ -56,7 +55,7 @@ DATE_FIELDS = frozenset({'order_date', 'required_date', 'requested_receipt_date'
def freeze_order_snapshot(
task: ShippingNotice,
task: ShippingOrderTask,
*,
actor_id: int | None,
expected_order_data_version: int,
@@ -88,9 +87,9 @@ def freeze_order_snapshot(
# query 默认带 shipping_case 的 joinedload;PostgreSQL 不允许对外连接的空值端
# 执行 FOR UPDATE。仅锁定正式任务主表,避免冻结在已确认但关联 Case 可为空时失败。
locked_task = (
ShippingNotice.query
ShippingOrderTask.query
.filter_by(id=task.id)
.with_for_update(of=ShippingNotice)
.with_for_update(of=ShippingOrderTask)
.one()
)
if locked_task.order_snapshot_id:
@@ -110,7 +109,7 @@ def freeze_order_snapshot(
)
extraction = _accepted_extraction(task)
policy, configs = _policy_configs(extraction)
customer_match = _confirmed_ordering_customer(extraction)
customer_resolution = _confirmed_ordering_customer(task)
from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness
assert_freeze_readiness(
task=task,
@@ -127,23 +126,11 @@ def freeze_order_snapshot(
task_id=task.id,
extraction_id=extraction.id,
schema_version_id=extraction.schema_version_id,
customer_id=customer_match.customer_id,
customer_short_code_snapshot=customer_match.customer_short_code_snapshot,
customer_id=customer_resolution.confirmed_customer_id,
customer_short_code_snapshot=_confirmed_customer_short_code(customer_resolution),
order_data_version=actual_version,
rule_versions_json={
**dict(rule_versions or {}),
'derivation_rules_snapshot': list(
((extraction.schema_version.definition_json or {}) if extraction.schema_version else {}).get('derivation_rules')
or []
),
'derivation_rules_checksum': (
((extraction.normalized_result_json or {}) if isinstance(extraction.normalized_result_json, dict) else {}).get(
'derivation_rules_checksum'
)
or ((extraction.schema_version.definition_json or {}) if extraction.schema_version else {}).get(
'derivation_rules_checksum'
)
),
'fulfillment_rule': {
'code': policy['rule_code'],
'checksum': _fixed_rule_checksum(),
@@ -151,12 +138,12 @@ def freeze_order_snapshot(
'required_field_ids': {code: config['field_id'] for code, config in configs.items()},
},
'ordering_customer': {
'match_id': customer_match.id,
'identity_fingerprint': customer_match.identity_fingerprint,
'identity_rule_version': customer_match.identity_rule_version,
'resolution_method': customer_match.resolution_method,
'confirmed_by_id': customer_match.confirmed_by_id,
'confirmed_at': customer_match.confirmed_at.isoformat() if customer_match.confirmed_at else None,
'resolution_id': customer_resolution.id,
'identity_rule_set_checksum': customer_resolution.identity_rule_set_checksum,
'identity_rule_set_version': customer_resolution.identity_rule_set_version,
'confirmation_method': customer_resolution.confirmation_method,
'confirmed_by_id': customer_resolution.confirmed_by_id,
'confirmed_at': customer_resolution.confirmed_at.isoformat() if customer_resolution.confirmed_at else None,
},
},
source_manifest_json={
@@ -174,17 +161,19 @@ def freeze_order_snapshot(
)
db.session.add(snapshot)
db.session.flush()
for position, source in enumerate(line_values):
for position, source in enumerate(line_values, start=1):
# 订单项次是系统项次,不采信客户 PO 行号或解析派生值;冻结后按本订单固定为 1..N。
source = dict(source)
source['line_no'] = position
db.session.add(ShippingOrderSnapshotLine(
snapshot_id=snapshot.id,
position=position,
position=position - 1,
field_values_json=_field_id_values(source, configs),
**_project_values(source, LINE_FIELD_PROJECTIONS),
))
db.session.flush()
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
replace_notice_lines_from_snapshot(notice_id=int(task.id), snapshot=snapshot)
# Snapshot 只是冻结订单事实;ShippingNoticeLine 属于正式发货通知,
# 必须在库存确认通过或人工放行后创建,不能在冻结阶段提前生成。
task.order_snapshot_id = snapshot.id
ShippingOrderReviewEvent.query.filter_by(
task_id=task.id,
@@ -202,13 +191,11 @@ def freeze_order_snapshot(
result='success',
metadata={
'snapshot_id': snapshot.id,
'derivation_rules_checksum': (snapshot.rule_versions_json or {}).get('derivation_rules_checksum'),
'schema_version_id': extraction.schema_version_id,
},
after={
'task_no': task.task_no,
'schema_version_id': extraction.schema_version_id,
'derivation_rules_checksum': (snapshot.rule_versions_json or {}).get('derivation_rules_checksum'),
},
)
db.session.flush()
@@ -270,13 +257,13 @@ def _source_manifest(*, extraction: ShippingOrderExtraction, policy: Any) -> dic
}
def assert_task_order_is_editable(task: ShippingNotice) -> None:
def assert_task_order_is_editable(task: ShippingOrderTask) -> None:
"""拒绝冻结后对 Candidate/Extraction 的任何直接编辑,防止快照与解析事实漂移。"""
if task.order_snapshot_id:
raise ConflictError('Frozen order snapshot cannot be edited', code='SHIPPING.ORDER_SNAPSHOT_FROZEN')
def _accepted_extraction(task: ShippingNotice) -> ShippingOrderExtraction:
def _accepted_extraction(task: ShippingOrderTask) -> ShippingOrderExtraction:
"""读取当前已接受 Extraction;冻结绝不回读旧版本或 Task JSON 投影。"""
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) if task.current_order_extraction_id else None
if extraction is None or extraction.status != 'accepted':
@@ -284,12 +271,14 @@ def _accepted_extraction(task: ShippingNotice) -> ShippingOrderExtraction:
return extraction
def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> ShippingOrderCustomerMatch:
"""只接受已人工确认的 Bill-to 订购客户,禁止由冻结请求自由指定 customer_id。"""
row = ShippingOrderCustomerMatch.query.filter_by(extraction_id=extraction.id, role='bill_to').one_or_none()
def _confirmed_ordering_customer(task: ShippingOrderTask) -> Any:
"""只接受正式客户识别结果,禁止由任一订单字段或冻结请求指定客户。"""
from app.services.shipping_notice.customer_resolution_service import resolution_for_task
row = resolution_for_task(task)
if (
row is None or row.status != 'confirmed' or row.customer_id is None
or not row.customer_short_code_snapshot or not row.identity_fingerprint or not row.identity_rule_version
row is None or row.status != 'confirmed' or row.confirmed_customer_id is None
or not row.evidence_json or not row.identity_rule_set_checksum
):
raise ValidationError(
'Ordering customer must be confirmed before freezing',
@@ -298,6 +287,14 @@ def _confirmed_ordering_customer(extraction: ShippingOrderExtraction) -> Shippin
return row
def _confirmed_customer_short_code(resolution: Any) -> str:
"""从已确认标准客户读取简称;订单原文和 bill_to 不得提供业务简称。"""
from app.models import ShippingCustomer
customer = db.session.get(ShippingCustomer, int(resolution.confirmed_customer_id))
return str(getattr(customer, 'short_code', None) or '')
def _policy_configs(extraction: ShippingOrderExtraction) -> tuple[dict[str, Any], dict[str, dict[str, Any]]]:
"""按固定履约契约验证冻结字段,Schema 仅承担字段目录职责。"""
from app.services.shipping_notice.fulfillment_policy_registry import (
@@ -1,12 +1,9 @@
"""
backend/app/services/shipping_notice/order_line_no_resolver.py
用途:内部项次(line_no)展示/导出值的唯一解析器——冻结字段真实值 → 客户 PO 行号 →
行展示序号,并输出来源标注(field / customer_po_line_no / sequence / None)。
用途:读取已经持久化的订单项次(line_no)。
依赖:app.models(ShippingNotice/Snapshot/Extraction)、order_schema.field_rules(格式门禁)。
逻辑:Excel 导出(export._mapping_value)与 UI 投影(query_service / ui_state)统一调用
本模块,禁止各调用方自行兜底,避免同一数据出现两套口径;缺失事实必须显式标注来源,
不得把内部行号伪装成业务项次。
逻辑:line_no 由冻结/正式通知写路径按单据内顺序生成;本模块不执行派生、回退或来源推断。
"""
from __future__ import annotations
@@ -15,11 +12,6 @@ from typing import Any
from app import db
from app.models import ShippingNotice, ShippingOrderExtraction, ShippingOrderSnapshot
from app.services.shipping_notice.order_schema.field_rules import is_valid_line_no_value
LINE_NO_SOURCE_FIELD = 'field'
LINE_NO_SOURCE_CUSTOMER_PO_LINE = 'customer_po_line_no'
LINE_NO_SOURCE_SEQUENCE = 'sequence'
def field_id_by_code_from_definition(
@@ -67,87 +59,67 @@ def notice_line_field_id_map(task: ShippingNotice) -> dict[str, str]:
return {}
def _read_field(
def _read_persisted_line_no(field_values: dict[str, Any] | None) -> str | None:
"""读取冻结行中按 ``line_no`` 规范持久化的项次值。
核心逻辑:项次不是 Schema 字段值,也不是外部单据行号;写路径生成后直接
持久化到行事实中,读取层不得按 field_code、客户行号或展示位置猜测。
"""
values = field_values if isinstance(field_values, dict) else {}
raw = values.get('line_no')
if raw in (None, ''):
return None
text = str(raw).strip()
return text or None
def read_field_by_id(
field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None,
code: str,
) -> str | None:
"""按 field_id 优先、field_code 兼容的稳定顺序读取行字段值。
核心逻辑:冻结 JSON 以 field_id(UUID)为键;历史/测试数据可能仍按 field_code 存储。
任一键命中且非空即返回规范化字符串,避免把 0/False 等合法值误判为空。
"""
"""按 Schema field_id 读取普通业务字段;不参与系统项次解析。"""
values = field_values if isinstance(field_values, dict) else {}
field_id = str(field_id_by_code.get(code) or '') if field_id_by_code else ''
if field_id and field_id in values:
raw = values[field_id]
if raw not in (None, ''):
text = str(raw).strip()
return text or None
if code in values:
raw = values[code]
if raw not in (None, ''):
text = str(raw).strip()
return text or None
return None
field_id = str((field_id_by_code or {}).get(code) or '').strip()
raw = values.get(field_id) if field_id else None
if raw in (None, ''):
return None
text = str(raw).strip()
return text or None
def resolve_order_line_no(
*,
field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None,
fallback_sequence: int | None = None,
field_id_by_code: dict[str, str] | None = None,
) -> dict[str, Any]:
"""解析一行内部项次展示值(唯一权威入口)。
【AI 触发时机】需要展示或导出某订单行的项次时统一调用;禁止在展示层自行回退。
核心逻辑:
[STEP 1] line_no 字段真实值(须通过 is_valid_line_no_value 格式门禁)→ source=field;
[STEP 2] customer_po_line_no 字段真实值(同格式门禁)→ source=customer_po_line_no;
[STEP 3] 调用方提供的 1..N 行序号 → source=sequence(明确标注为展示序号);
[STEP 4] 全部缺失 → {'value': None, 'source': None}。
与派生规则同门禁:非法项次格式(非 1–6 位数字)一律跳过,不得以序号冒充业务值。
核心逻辑:只读取 field_values 中已经持久化的 line_no;customer_po_line_no 和
展示序号都不能作为内部项次的替代来源。
Args:
field_values: 行字段值 JSON(field_id 或 field_code 键均可)。
field_id_by_code: field_code → field_id 映射;为空时仅按 field_code 键兼容读取。
fallback_sequence: 1 基展示序号;None 表示无序号兜底。
field_id_by_code: 已废弃参数,仅为调用方签名稳定保留;不会参与读取。
Returns:
{'value': 规范化字符串或 None, 'source': 'field'|'customer_po_line_no'|'sequence'|None}。
{'value': 规范化字符串或 None, 'source': 'persisted'|None}。
"""
line_no = _read_field(field_values, field_id_by_code, 'line_no')
if line_no is not None and is_valid_line_no_value(line_no):
return {'value': line_no, 'source': LINE_NO_SOURCE_FIELD}
customer_line_no = _read_field(field_values, field_id_by_code, 'customer_po_line_no')
if customer_line_no is not None and is_valid_line_no_value(customer_line_no):
return {'value': customer_line_no, 'source': LINE_NO_SOURCE_CUSTOMER_PO_LINE}
if fallback_sequence is not None and int(fallback_sequence) >= 1:
return {'value': str(int(fallback_sequence)), 'source': LINE_NO_SOURCE_SEQUENCE}
return {'value': None, 'source': None}
del field_id_by_code
line_no = _read_persisted_line_no(field_values)
return {'value': line_no, 'source': 'persisted' if line_no is not None else None}
def resolve_order_line_no_projection(
*,
field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None,
fallback_sequence: int | None = None,
field_id_by_code: dict[str, str] | None = None,
) -> dict[str, Any]:
"""与 resolve_order_line_no 同源的 UI/导出投影形(line_no / line_no_source 键)。
核心逻辑:仅供展示层消费;把语义结果映射为前端契约键,避免各处手写
{'line_no': result['value'], 'line_no_source': result['source']} 产生分叉。
Returns:
{'line_no': str|None, 'line_no_source': 'field'|'customer_po_line_no'|'sequence'|None}。
"""
"""读取不可变订单项次投影。"""
resolved = resolve_order_line_no(
field_values=field_values,
field_id_by_code=field_id_by_code,
fallback_sequence=fallback_sequence,
)
return {'line_no': resolved['value'], 'line_no_source': resolved['source']}
return {'line_no': resolved['value']}
@@ -1252,7 +1252,6 @@ def build_identity_snapshot(*, profile: Any, revision: Any, samples: list[Any])
def build_overlap_evidence(*, profile: Any, signature_run: Any, training_samples: list[Any], blind_samples: list[Any]) -> tuple[str, dict[str, Any], dict[str, Any]]:
"""复用共同视觉 overlap,并仅追加 datasets 值源身份冲突证据。"""
from app.services.shipping_notice import order_document_profile_validation_service as validation_service
from app.services.shipping_notice import order_document_profile_service as profile_service
# [STEP 1] 共同 matcher 负责样本、阈值、正反向命中和污染判定;datasets 不得重建该流程。
status, summary, snapshot = validation_service._build_coordinate_overlap_evidence(
@@ -1266,12 +1265,11 @@ def build_overlap_evidence(*, profile: Any, signature_run: Any, training_samples
snapshot = dict(snapshot or {})
# [STEP 2] datasets 仅在共同视觉结论后追加正式值源身份的 fail-closed 冲突。
# 同 profile_code 旧版会在发布时 retire,不与自家模板比身份冲突。
source = (profile.definition_json or {}).get('source_contract') if isinstance((profile.definition_json or {}).get('source_contract'), dict) else {}
template, fingerprint = str(source.get('template_packet_checksum') or '').strip(), str(source.get('dataset_structure_fingerprint') or '').strip()
conflicts: list[dict[str, Any]] = []
for item in profile_service.published_snapshots_for_schema(profile.schema_version_id):
if str(item.get('profile_code') or '') == profile.profile_code and int(item.get('version') or 0) == int(profile.version):
continue
for item in validation_service.published_rival_snapshots_for_overlap(profile):
other = item.get('definition') if isinstance(item.get('definition'), dict) else {}
other_source = other.get('source_contract') if isinstance(other.get('source_contract'), dict) else {}
if template and fingerprint and str(other_source.get('template_packet_checksum') or '') == template and str(other_source.get('dataset_structure_fingerprint') or '') == fingerprint:
@@ -5,10 +5,10 @@ services/shipping_notice/order_review_auto_progress_coordinator.py
依赖:order_review_customer_service、order_review_draft_service(延迟)、
order_stp_auto_create_service(延迟)、candidate_qualification_service、
fulfillment_audit、ShippingCustomerShadowResolution /
ShippingOrderCustomerMatch / ShippingOrderReviewCase / ShippingOrderProcessingRun。
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 本模块)。
@@ -23,19 +23,15 @@ from app import db
from app.models import (
ShippingCustomerShadowResolution,
ShippingOrderCandidate,
ShippingOrderCustomerMatch,
ShippingOrderProcessingRun,
ShippingOrderReviewCase,
ShippingOrderReviewStream,
)
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.customer_resolution_service import confirm_customer_resolution
from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref
# 注意:validate_draft 与 ensure_stp_auto_create_for_case 均不在顶层 import,
@@ -73,7 +69,7 @@ def _customer_step_for_case(
trigger: str,
) -> tuple[str, dict[str, Any] | None]:
"""
单 Case 客户协调内部步骤:shadow 唯一命中时自动确认 bill_to。
单 Case 客户协调内部步骤:识别结果唯一命中时自动确认客户。
Args:
case: 复核 Case。
@@ -105,45 +101,20 @@ def _customer_step_for_case(
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
# [STEP 1-3] 将唯一指纹候选确认到正式识别结果;不创建或读取订单角色投影。
top_customer_id = int(shadow.top_customer_id)
confirm_reason = '抽取协调器-客户指纹唯一命中自动确认'
try:
confirm_order_customer_match(
int(extraction.id),
role='bill_to',
confirm_customer_resolution(
candidate,
customer_id=top_customer_id,
site_id=None,
actor_id=None,
method='auto_rule',
reason=confirm_reason,
# 保存校验入口需将客户确认、Draft 校验与后续 Gate/STP 写入作为同一事务提交。
commit=False,
)
except Exception as exc: # noqa: BLE001
_LOGGER.warning(
'confirm_order_customer_match failed case_no=%s err=%s',
'confirm_customer_resolution failed case_no=%s err=%s',
case.case_no, str(exc)[:200],
)
return 'failed', {'reason': 'confirm_match_failed', 'error': str(exc)[:200]}
@@ -165,7 +136,7 @@ def _customer_step_for_case(
'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),
'extraction_id': getattr(candidate, 'order_extraction_id', None),
'trigger': str(trigger)[:64],
'reason': confirm_reason,
},
@@ -177,7 +148,7 @@ def _customer_step_for_case(
return 'auto_confirmed', {
'customer_id': top_customer_id,
'extraction_id': int(extraction.id),
'extraction_id': getattr(candidate, 'order_extraction_id', None),
}
@@ -397,7 +368,7 @@ def reconcile_run_review_cases_for_auto_progress(
})
continue
# [STEP 1 客户协调] shadow unique_candidate 且未 resolve → 自动确认 bill_to
# [STEP 1 客户协调] shadow unique_candidate 且未 resolve → 自动确认标准客户
customer_status, customer_meta = _customer_step_for_case(
case=case, trigger='run_reconcile',
)
@@ -3,21 +3,20 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py
用途:按 PDF 确认复核草稿并独立创建发货任务,确认后复用同一 auto_progress 链。
依赖:Review Case/Draft、动态订单 Extraction、Candidate、Task、order_task_service、
stp_inventory_freeze、progress_audit_contract.ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE、
candidate_qualification_service、customer_auto_resolution、fulfillment_audit、
order_review_progress_bridge、workflow_ledger_service、
queue_service.enqueue_shipping_notice_job、process_gate_bridge。
逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,冻结行级库存源候选与
可自动确认的客户;库存源未唯一确定时按硬门禁拒绝建单并回写 OT stage=
inventory_source_resolving;物化人工 Candidate 时先写入客户已确认事实再执行履约门禁;
逻辑:确认在单事务内分别锁定 Case 与 Draft,重跑资格门禁,固化可自动确认的客户;
物化人工 Candidate 时先写入客户已确认事实再执行履约门禁;
确认建单前锁定 case.candidate_id 对应 OT:未消费 OT 受控换绑人工 Candidate;
已消费 OT 保留历史并为后续波次创建稳定子 OT;同步 Case 当前 Candidate;
缺 OT 则 fail-closed 回滚;禁止 upsert 到 Run 根号串单;
物化 accepted Extraction(保留派生 field_lineage);建单前再次校验客户确认并
物化 accepted Extraction(保留字段 field_lineage);建单前再次校验客户确认并
持久化 Candidate Qualification 快照;客户未确认拒绝建单;同 Case 既有波次 Task
豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束;
新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照
Task 推入库存/RPA;
Task 推入库存/RPA。库存源候选的裁决/冻结不在确认流程内,由确认后 OT 进入的
正式 inventory_source_routing Gate 负责;
成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至
building_order(不关闭);同步 Process Execution 推进至 task_creation 通过,
避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox),
@@ -50,8 +49,7 @@ from app.models import (
ShippingOrderReviewConfirmedRevision,
ShippingOrderReviewDraft,
ShippingOrderReviewWaveLine,
ShippingOrderCustomerMatch,
ShippingNotice,
ShippingOrderTask,
)
from app.services.shipping_notice.batch_create_idempotency import (
acquire_notice_create_locks,
@@ -68,9 +66,6 @@ from app.services.shipping_notice.order_review_draft_service import (
build_confirmable_draft_summary,
draft_has_unaccepted_llm_suggestions,
)
from app.services.shipping_notice.progress_audit_contract import (
ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE,
)
from app.services.shipping_notice.order_review_projection import serialize_review_case
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
@@ -221,13 +216,12 @@ def _json_value(value: Any) -> Any:
def _source_extraction_lineage(case: ShippingOrderReviewCase) -> tuple[list[dict[str, Any]], str | None]:
"""
读取机器解析 Extraction / Unit 上的派生血缘与规则校验和。
读取机器解析 Extraction / Unit 上的字段血缘。
核心逻辑:优先 Candidate.order_extraction_id → normalized_result_json;
否则回退 Unit.result_json。供确认物化 Extraction 写入冻结可追溯快照。
"""
rows: list[dict[str, Any]] = []
checksum: str | None = None
candidate = db.session.get(ShippingOrderCandidate, case.candidate_id) if case.candidate_id else None
extraction_id = getattr(candidate, 'order_extraction_id', None) if candidate is not None else None
if extraction_id:
@@ -236,17 +230,9 @@ def _source_extraction_lineage(case: ShippingOrderReviewCase) -> tuple[list[dict
extraction.normalized_result_json, dict,
) else {}
rows = [item for item in (normalized.get('field_lineage') or []) if isinstance(item, dict)]
raw_checksum = normalized.get('derivation_rules_checksum')
checksum = str(raw_checksum) if raw_checksum else None
if not checksum and extraction is not None and extraction.schema_version is not None:
definition = extraction.schema_version.definition_json or {}
if isinstance(definition, dict) and definition.get('derivation_rules_checksum'):
checksum = str(definition.get('derivation_rules_checksum'))
if not rows and case.unit is not None and isinstance(case.unit.result_json, dict):
rows = [item for item in (case.unit.result_json.get('field_lineage') or []) if isinstance(item, dict)]
if not checksum and case.unit.result_json.get('derivation_rules_checksum'):
checksum = str(case.unit.result_json.get('derivation_rules_checksum'))
return rows, checksum
return rows, None
def _confirmation_field_lineage(
@@ -255,64 +241,38 @@ def _confirmation_field_lineage(
summary_lines: list[dict[str, Any]],
) -> tuple[list[dict[str, Any]], str | None]:
"""
将源解析血缘按行位映射到确认后 Extraction 的 review-* line_key。
将源解析血缘按行位映射到确认后 Extraction 的 draft_line_id。
核心逻辑:按草稿行顺序对齐;若该行 line_no 已被人工覆盖,则改写为 manual_override 血缘。
核心逻辑:按草稿行顺序对齐字段血缘;系统项次不参与人工覆盖。
"""
source_rows, checksum = _source_extraction_lineage(case)
draft_lines = [
item for item in (case.current_draft.lines_json or [])
if isinstance(item, dict)
]
line_no_field_id = None
run = case.run
definition = (
(run.input_snapshot_json or {}).get('schema', {}).get('definition', {})
if run is not None and isinstance(run.input_snapshot_json, dict) else {}
)
for item in definition.get('fields') or []:
if (
isinstance(item, dict)
and str(item.get('field_code') or '') == 'line_no'
and str(item.get('scope') or '') == 'line'
):
line_no_field_id = str(item.get('field_id') or '') or None
break
by_key: dict[str, list[dict[str, Any]]] = {}
for item in source_rows:
key = str(item.get('line_key') or '').strip()
key = str(item.get('draft_line_id') or '').strip()
if key:
by_key.setdefault(key, []).append(item)
ordered_keys: list[str] = []
for item in source_rows:
key = str(item.get('line_key') or '').strip()
key = str(item.get('draft_line_id') or '').strip()
if key and key not in ordered_keys:
ordered_keys.append(key)
remapped: list[dict[str, Any]] = []
for position, draft_line in enumerate(draft_lines):
new_key = f'review-{position + 1}'
old_key = str(draft_line.get('line_key') or '').strip()
old_key = str(draft_line.get('draft_line_id') or '').strip()
source_items = list(by_key.get(old_key) or [])
if not source_items and position < len(ordered_keys):
source_items = list(by_key.get(ordered_keys[position]) or [])
values = draft_line.get('values') if isinstance(draft_line.get('values'), dict) else {}
override_entry = values.get(line_no_field_id) if line_no_field_id else None
line_no_overridden = (
isinstance(override_entry, dict)
and str(override_entry.get('source') or '') == 'manual_override'
)
summary_line = summary_lines[position] if position < len(summary_lines) else {}
for item in source_items:
row = dict(item)
row['line_key'] = new_key
if str(row.get('field_code') or '') == 'line_no' and line_no_overridden:
row['value_source'] = 'manual_override'
row['after_value'] = summary_line.get('line_no')
row['skip_reason'] = None
row['draft_line_id'] = new_key
remapped.append(row)
return remapped, checksum
@@ -325,23 +285,16 @@ def _build_confirmation_normalized_result(
"""
组装确认后 Extraction.normalized_result_json。
核心逻辑:保留确认摘要的 header/lines,并附加源解析 field_lineage 与派生规则校验和,
供冻结快照写入可追溯项次派生来源。
核心逻辑:保留确认摘要的 header/lines,并附加源解析 field_lineage,
供冻结快照写入可追溯字段来源。
"""
header_values = {key: value for key, value in summary.items() if key != 'lines'}
lines = [dict(item) for item in (summary.get('lines') or []) if isinstance(item, dict)]
lineage, checksum = _confirmation_field_lineage(case, summary_lines=lines)
if not checksum and case.current_draft is not None:
from app.models import ShippingOrderSchemaVersion
version = db.session.get(ShippingOrderSchemaVersion, int(case.current_draft.schema_version_id))
definition = (version.definition_json or {}) if version is not None else {}
if isinstance(definition, dict) and definition.get('derivation_rules_checksum'):
checksum = str(definition.get('derivation_rules_checksum'))
lineage, _checksum = _confirmation_field_lineage(case, summary_lines=lines)
return {
'header': header_values,
'lines': lines,
'field_lineage': lineage,
'derivation_rules_checksum': checksum,
}
@@ -363,9 +316,9 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
for item in configs
if str(item.get('scope') or '') == 'line' and item.get('field_code')
}
# `line_key` is Draft-only identity used by wave selection and lineage remapping.
# `draft_line_id` is Draft-only identity used by wave selection and lineage remapping.
# It is not a Schema business field and must never be materialized as one.
internal_line_fields = {'line_key'}
internal_line_fields = {'draft_line_id'}
unknown_line_fields = sorted({
str(key)
for line in summary.get('lines') or []
@@ -413,7 +366,12 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
**_field_value_columns(value, str(config.get('value_type') or 'string')),
))
for position, values in enumerate(summary.get('lines') or []):
line = ShippingOrderLine(extraction_id=int(extraction.id), position=position, line_key=f'review-{position + 1}')
line = ShippingOrderLine(
extraction_id=int(extraction.id),
position=position,
line_no=position + 1,
draft_line_id=f'review-{position + 1}',
)
db.session.add(line)
db.session.flush()
for config in configs:
@@ -433,59 +391,33 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
extraction_id=int(extraction.id), line_id=int(line.id), field_id=field_id, decision_id=int(decision.id),
**_field_value_columns(value, str(config.get('value_type') or 'string')),
))
_inherit_confirmed_customer_match(case=case, extraction=extraction)
_inherit_confirmed_customer_resolution(case=case, extraction=extraction)
return extraction
def _inherit_confirmed_customer_match(
def _inherit_confirmed_customer_resolution(
*,
case: ShippingOrderReviewCase,
extraction: ShippingOrderExtraction,
) -> None:
"""
把当前 Case 原 Extraction 已确认的 Bill-to 客户复制到人工确认 Extraction。
人工确认产生新 Extraction 时保留同一 Candidate 的正式客户识别确认事实。
核心逻辑:仅复制当前 PDF Candidate 的 confirmed Bill-to 行;没有确认事实时保持空,
后续建单前客户门禁仍会 fail-closed。
核心逻辑:客户识别结果通过 Candidate 稳定关联,不复制或伪造 bill_to 角色行;
新 Extraction 只改变订单字段版本,后续 Gate 继续读取该 Candidate 的确认结果。
Args:
case: 当前复核 Case。
extraction: 新建的人工确认 Extraction。
"""
del extraction
if not case.candidate_id:
return
source_candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
source_extraction_id = getattr(source_candidate, 'order_extraction_id', None) if source_candidate else None
if source_extraction_id is None:
from app.services.shipping_notice.customer_resolution_service import resolution_for_task
resolution = resolution_for_task(db.session.get(ShippingOrderCandidate, int(case.candidate_id)))
if resolution is not None and resolution.status == 'confirmed':
return
source = ShippingOrderCustomerMatch.query.filter_by(
extraction_id=int(source_extraction_id),
role='bill_to',
status='confirmed',
).first()
if source is None or source.customer_id is None:
return
db.session.add(ShippingOrderCustomerMatch(
extraction_id=int(extraction.id),
role='bill_to',
raw_name=source.raw_name,
normalized_name=source.normalized_name,
source_system=source.source_system,
external_code=source.external_code,
identity_fingerprint=source.identity_fingerprint,
identity_rule_version=source.identity_rule_version,
identity_components_json=copy.deepcopy(source.identity_components_json or {}),
status='confirmed',
customer_id=int(source.customer_id),
site_id=int(source.site_id) if source.site_id is not None else None,
customer_name_snapshot=source.customer_name_snapshot,
customer_short_code_snapshot=source.customer_short_code_snapshot,
candidates_json=copy.deepcopy(source.candidates_json or []),
resolution_method=source.resolution_method or 'review_case_inherited',
confirmation_reason=source.confirmation_reason,
confirmed_by_id=source.confirmed_by_id,
confirmed_at=source.confirmed_at or datetime.utcnow(),
))
def _workflow_refs_for_case(case: ShippingOrderReviewCase) -> dict[str, str | None]:
@@ -729,6 +661,59 @@ def _audit_idempotent_confirmation_replay(
)
def _inherit_confirmed_customer_resolution_onto_candidate(
candidate: ShippingOrderCandidate,
case: ShippingOrderReviewCase,
) -> None:
"""review_case 人工确认时,把源机器 Candidate 的正式客户确认事实挂到新确认候选上。
review_case 确认会新建独立 ShippingOrderCandidate(candidate_key=review-confirm-*),
但客户识别结果按 Candidate 关联稳定存放;新候选若不继承源候选的 confirmed resolution,
后续 assert_customer_confirmed_before_task_create / resolve_confirmed_customer_id 按
新 candidate_id 查表为空,会误拒"已确认客户"无法建单。
"""
if not case.candidate_id:
return
source = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
from app.services.shipping_notice.customer_resolution_service import resolution_for_task
source_resolution = resolution_for_task(source) if source is not None else None
if (
source_resolution is None
or source_resolution.status != 'confirmed'
or source_resolution.confirmed_customer_id is None
):
return
from app.models import ShippingCustomerShadowResolution
row = db.session.query(ShippingCustomerShadowResolution).filter_by(
candidate_id=int(candidate.id),
).one_or_none()
if row is None:
row = ShippingCustomerShadowResolution(
candidate_id=int(candidate.id), intake_id=int(candidate.intake_id),
)
db.session.add(row)
row.identity_rule_set_id = source_resolution.identity_rule_set_id
row.identity_rule_set_version = source_resolution.identity_rule_set_version
row.identity_rule_set_checksum = source_resolution.identity_rule_set_checksum
row.order_schema_version_id = source_resolution.order_schema_version_id
row.resolution_version = source_resolution.resolution_version
row.status = 'confirmed'
# [STEP] 完整复制源候选的正式识别证据与候选匹配快照:review_case 确认的新候选
# 必须携带可审计的客户识别事实,否则 freeze(_confirmed_ordering_customer 要求
# evidence_json 非空)会把"已确认客户"误判为未确认而冻结失败。
row.evidence_json = list(source_resolution.evidence_json or [])
row.candidate_matches_json = list(source_resolution.candidate_matches_json or [])
row.resolution_context_json = dict(source_resolution.resolution_context_json or {})
row.confirmed_customer_id = source_resolution.confirmed_customer_id
row.confirmation_method = source_resolution.confirmation_method or 'review_case_confirmed'
row.confirmed_by_id = int(candidate.accepted_by_id) if candidate.accepted_by_id is not None else None
row.confirmed_at = datetime.utcnow()
row.top_customer_id = source_resolution.top_customer_id
row.top_score = source_resolution.top_score
def _create_review_candidate(
*,
case: ShippingOrderReviewCase,
@@ -786,6 +771,11 @@ def _create_review_candidate(
)
db.session.add(candidate)
db.session.flush()
# [STEP] review_case 人工确认:把继承的正式客户确认事实落到 resolution 表,
# 否则按新 candidate_id 查表为空,assert_customer_confirmed_before_task_create /
# resolve_confirmed_customer_id 会误拒"已确认客户"无法建单。
if customer_confirmed:
_inherit_confirmed_customer_resolution_onto_candidate(candidate, case)
asset = db.session.get(FileAsset, int(document.asset_id)) if document.asset_id else None
# [STEP] 同 Case 既有波次不参与 Candidate 级 exact_file / 指纹阻断。
prior_wave_task_ids = _prior_wave_task_ids_for_case(case)
@@ -872,8 +862,8 @@ def _prior_wave_task_ids_for_case(case: ShippingOrderReviewCase) -> set[int]:
def _persist_wave_lines_for_task(
*,
case: ShippingOrderReviewCase,
task: ShippingNotice,
line_keys: list[str],
task: ShippingOrderTask,
snapshot_line_ids: list[int],
wave_no: int,
revision_id: int | None,
) -> None:
@@ -882,8 +872,8 @@ def _persist_wave_lines_for_task(
Args:
case: 复核 Case。
task: 本波次新建的 Notice。
line_keys: 本波次完整行键。
task: 本波次复核确认生成的 OT。
snapshot_line_ids: 本波次冻结订单行 ID。
wave_no: 波次序号(从 1 起)。
revision_id: 可选确认修订 ID。
@@ -892,10 +882,10 @@ def _persist_wave_lines_for_task(
"""
from sqlalchemy.exc import IntegrityError
for key in line_keys:
for snapshot_line_id in snapshot_line_ids:
db.session.add(ShippingOrderReviewWaveLine(
review_case_id=int(case.id),
line_key=str(key),
snapshot_line_id=int(snapshot_line_id),
task_id=int(task.id),
wave_no=int(wave_no),
confirmed_revision_id=int(revision_id) if revision_id is not None else None,
@@ -906,31 +896,20 @@ def _persist_wave_lines_for_task(
raise ConflictError(
'Line already belongs to another fulfillment wave',
code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK',
details={'line_keys': list(line_keys)},
details={'snapshot_line_ids': [int(item) for item in snapshot_line_ids]},
) from exc
def _order_task_no_for_notice(notice: ShippingNotice | None) -> str | None:
"""
从已建 Notice 解析挂接的 OT 编号(幂等回放用)。
def _order_task_no_for_notice(notice: ShippingOrderTask | None) -> str | None:
"""返回 OT 自身编号(保留函数名仅用于本模块内部整理)。
Args:
notice: 发货 Notice;None 时返回 None。
notice: OT;None 时返回 None。
Returns:
order_task.task_no;未挂接时 None。
"""
if notice is None:
return None
order_task_id = getattr(notice, 'order_task_id', None)
if order_task_id is None:
return None
from app.models import ShippingOrderTask
order_task = db.session.get(ShippingOrderTask, int(order_task_id))
if order_task is None:
return None
return str(order_task.task_no or '').strip() or None
return str(getattr(notice, 'task_no', None) or '').strip() or None if notice is not None else None
def _confirmation_result_payload(
@@ -958,7 +937,7 @@ def _confirmation_result_payload(
"""
payload: dict[str, Any] = {
'task_no': task_no,
'shipping_notice_no': task_no,
'shipping_notice_no': None,
'order_task_no': order_task_no,
'idempotent_replay': idempotent_replay,
'case': serialize_review_case(case),
@@ -969,7 +948,7 @@ def _confirmation_result_payload(
return payload
def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: Any, idempotency_key: str | None, warning_acknowledgements: Any = None, confirm_note: str | None = None, line_keys: list[str] | None = None) -> dict[str, Any]:
def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: Any, idempotency_key: str | None, warning_acknowledgements: Any = None, confirm_note: str | None = None) -> dict[str, Any]:
"""
确认一个 PDF 草稿并建一张无 Batch 的 Task;门禁拒绝写统一审计后抛错。
@@ -979,7 +958,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
幂等回放(同键或已确认 Case)同样写审计(result=ignored),追溯重复提交。
版本冲突/校验失败/文档不可用/重复订单等拒绝写 result=rejected,并在 raise 前独立 commit。
锁定 Case 之前的边界拒绝(缺幂等键、警告格式非法、幂等键跨 Case 占用)在 Case 可定位时同样写拒绝审计。
可选 line_keys:仅冻结选中的完整明细行(履约波次);若 Case 仍有开放行则保持 ready 不终态确认。
确认订单恒为整单确认(业务规则:确认订单不可分行;仅“产生发货通知”可分波次)。
Args:
user_id: Case 属主用户 ID。
@@ -988,7 +967,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
idempotency_key: 建单幂等键。
warning_acknowledgements: 警告确认列表。
confirm_note: 可选确认备注,写入审计 metadata。
line_keys: 可选履约波次行键;None 表示整单草稿行。
Returns:
含 shipping_notice_no / task_no / order_task_no / case / workflow_id / trigger_auto_progress 的确认结果。
@@ -1028,7 +1006,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
),
idempotency_key=key,
)
task = db.session.get(ShippingNotice, int(replay.task_id))
task = db.session.get(ShippingOrderTask, int(replay.task_id))
task_no = task.task_no if task else None
_audit_idempotent_confirmation_replay(
user_id=user_id,
@@ -1044,9 +1022,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
idempotent_replay=True,
)
case = _locked_case(user_id=user_id, case_no=case_no, idempotency_key=key)
# 整单已终态确认时幂等回放;履约波次在 Case 仍为 ready 时可继续建后续 Task。
if case.status == 'confirmed' and case.confirmed_task_id and not line_keys:
task = db.session.get(ShippingNotice, int(case.confirmed_task_id))
# 整单已终态确认时幂等回放(确认订单恒为整单,不存在按行波次的中间态)。
if case.status == 'confirmed' and case.confirmed_task_id:
task = db.session.get(ShippingOrderTask, int(case.confirmed_task_id))
task_no = task.task_no if task else None
_audit_idempotent_confirmation_replay(
user_id=user_id,
@@ -1073,76 +1051,12 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
idempotency_key=key,
metadata={'expected_draft_version': expected},
)
wave_keys = [str(k).strip() for k in (line_keys or []) if str(k).strip()] or None
# [STEP] 波次行唯一归属:在建 Task 前 fail-closed,避免 IntegrityError 半成品。
if wave_keys is not None:
already = (
ShippingOrderReviewWaveLine.query
.filter(
ShippingOrderReviewWaveLine.review_case_id == int(case.id),
ShippingOrderReviewWaveLine.line_key.in_(list(wave_keys)),
)
.all()
)
if already:
_reject_confirmation(
case,
actor_id=int(user_id),
error=ConflictError(
'Line already belongs to another fulfillment wave',
code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK',
details={'line_keys': [str(row.line_key) for row in already]},
),
idempotency_key=key,
case_no=str(case_no),
owner_user_id=int(user_id),
)
summary, validation = build_confirmable_draft_summary(case, line_keys=wave_keys)
# [STEP] 建单硬门禁:库存源未唯一确定时禁止创建正式订单,并回写 OT stage。
if ORDER_CREATE_REQUIRES_RESOLVED_INVENTORY_SOURCE:
inventory_issues = [
item
for item in (validation.get('issues') or [])
if isinstance(item, dict)
and str(item.get('owning_gate_code') or '') == 'inventory_source_routing'
and str(item.get('severity') or '') == 'blocking'
]
if inventory_issues:
from app.services.shipping_notice.order_task_service import (
resolve_order_task_for_candidate,
sync_order_task_processing_state,
)
blocked_ot = resolve_order_task_for_candidate(
int(case.candidate_id) if case.candidate_id else None
)
if blocked_ot is not None:
sync_order_task_processing_state(
blocked_ot,
stage='inventory_source_resolving',
status='blocked',
)
primary = inventory_issues[0]
_reject_confirmation(
case,
actor_id=int(user_id),
error=ConflictError(
'Inventory source must be uniquely resolved before creating a formal order',
code='SHIPPING.REVIEW_INVENTORY_SOURCE_UNRESOLVED',
details={
'issues': inventory_issues,
'blocking_reason_code': str(
primary.get('code') or 'no_inventory_source_candidates'
),
'owning_gate_code': 'inventory_source_routing',
},
),
idempotency_key=key,
metadata={
'validation_status': str(validation.get('status') or '')[:32] or None,
'gate_code': 'inventory_source_routing',
},
)
# [STEP] 确认订单恒为整单:build_confirmable_draft_summary 不接受 draft_line_ids,
# 确认时要求整单全部行通过校验(业务规则:确认订单不可分行)。
summary, validation = build_confirmable_draft_summary(case)
# [STEP] 硬门禁已移除:确认流程只确认订单信息(订单字段/客户/订单快照)。
# 库存源候选的裁决/冻结由确认后 OT 进入的正式 inventory_source_routing Gate 负责,
# 不再要求确认时库存源已唯一确定。
if draft_has_unaccepted_llm_suggestions(case):
_reject_confirmation(
case,
@@ -1204,7 +1118,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
before_snap = {'status': previous_status, 'disposition': previous_disposition}
# [BE-01/BE-02] 人工 Candidate 物化前锁定 Case 原 Candidate 对应 OT,禁止事后落到 Run 根号。
from app.services.shipping_notice.order_task_service import (
link_notice_to_order_task,
replace_order_task_candidate_after_review,
resolve_order_task_for_candidate,
upsert_order_task_from_run,
@@ -1230,17 +1143,19 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
)
try:
assert_case_is_current_workflow_version(case=case)
# [STEP] 建单前再次校验客户确认(相对 Draft 校验时刻防并发回退)。
# [STEP] 建单前解析唯一客户(读机器候选 resolution,一次完成门户校验 + 取主键)。
# 机器候选是客户识别事实的权威来源:没有唯一已确认主键即拒绝建单。
from app.services.shipping_notice.candidate_qualification_service import (
recalculate_candidate_qualification,
resolve_review_case_customer_resolved,
resolve_confirmed_customer_id,
)
pre_candidate = (
db.session.get(ShippingOrderCandidate, int(case.candidate_id))
if case.candidate_id
else None
)
if not resolve_review_case_customer_resolved(case=case, candidate=pre_candidate):
bind_customer_id = resolve_confirmed_customer_id(candidate=pre_candidate)
if bind_customer_id is None:
raise ConflictError(
'Customer is not confirmed',
code='SHIPPING.REVIEW_CUSTOMER_UNRESOLVED',
@@ -1287,7 +1202,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
)
# [BE-01/BE-02] 复用锁定 OT;无原 Candidate 时才按人工 Candidate 新建 OT。
try:
if locked_order_task is not None and locked_order_task.shipping_notice_id is None:
if locked_order_task is not None:
order_task = replace_order_task_candidate_after_review(
order_task=locked_order_task,
previous_candidate_id=source_candidate_id,
@@ -1356,69 +1271,34 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
)
# [BE-06] Notice 创建及挂接后的消费/客户绑定失败须 fail-closed 回滚。
try:
task = ShippingNotice(
task_no=generate_task_no(), user_id=int(user_id),
conversation_id=case.run.conversation_id, source_type='review_confirmation', source_file_name=document.filename,
source_file_type=asset.mime_type if asset else None, source_content_hash=document.content_hash,
source_asset_id=document.asset_id, source_intake_id=int(intake.id), source_candidate_id=int(candidate.id),
business_fingerprint=candidate.business_fingerprint, fingerprint_version=candidate.fingerprint_version,
content_fingerprint=candidate.content_fingerprint, content_fingerprint_version=candidate.content_fingerprint_version,
document_version=1, duplicate_resolution_type='normal', raw_content=document.extracted_text,
customer_resolution_status='pending', current_order_extraction_id=int(extraction.id),
)
task = order_task
task.current_order_extraction_id = int(extraction.id)
task.order_data_version = int(getattr(task, 'order_data_version', None) or 1)
db.session.add(task)
db.session.flush()
link_notice_to_order_task(
order_task_no=order_task_no,
notice_id=int(task.id),
)
extraction.task_id = int(task.id)
candidate.consumed_task_id = int(task.id)
candidate.updated_at = datetime.utcnow()
# The review Case is the explicit human confirmation for this PDF. Do not
# recreate a low-confidence parse checkpoint on the newly materialized Task.
apply_task_transition(task, TaskTransition.CONFIRM_PARSE)
# [STEP] 冻结建单资格中的行级库存源候选;单源 resolved,多源 candidates_frozen。
from app.services.shipping_notice.stp_inventory_freeze import freeze_stp_inventory_candidates_on_task
freeze_stp_inventory_candidates_on_task(
task,
line_projections=list(validation.get('line_projections') or []),
)
# [STEP] 候选库存源已在建单前冻结;正式 OT 创建完成后立即进入获取库存,
# 不再让统一进度停留在“创建正式订单”。最终行级实际库存源仍由后续匹配决定。
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
sync_order_task_processing_state(
order_task,
stage='inventory_fetching',
status='processing',
reason_code='inventory_candidates_frozen_after_confirm',
)
# [STEP] 建单前已校验客户确认:立即绑定标准客户,禁止落入 customer_review。
from app.services.shipping_notice.candidate_qualification_service import (
resolve_confirmed_bill_to_customer_id,
)
from app.services.shipping_notice.customer_auto_resolution import try_auto_confirm_task_customer
# recreate a low-confidence parse_review disposition on the newly materialized Task.
# [STEP] 确认只固化订单信息(订单字段/客户/订单快照)。库存源候选的裁决/冻结
# 退到确认后 OT 进入的正式 inventory_source_routing Gate 处理,不在确认流程内
# 提前冻结库存候选,因此也不再在确认处设置 OT 的 notification_preparation 阶段。
# [STEP] 建单前已从机器候选解析唯一客户主键(bind_customer_id,见上方门禁)。
# 此处直接用该主键绑定标准客户,禁止落入 customer_review,不再二次查表。
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
bind_customer_id = resolve_confirmed_bill_to_customer_id(
candidate=candidate,
extraction_id=int(extraction.id),
confirm_task_customer(
task,
customer_id=int(bind_customer_id),
actor_id=int(user_id),
resolution_method='review_case_confirmed',
commit=False,
)
if bind_customer_id is not None:
confirm_task_customer(
task,
customer_id=int(bind_customer_id),
actor_id=int(user_id),
resolution_method='review_case_confirmed',
commit=False,
)
else:
try_auto_confirm_task_customer(task)
# [STEP] Review 确认建单与自动建单必须共享订单快照前置条件。
# 冻结失败由外层 AppError 回滚,不能留下已建单但库存链路无法启动的半成品。
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
from app.models import ShippingOrderSnapshot
freeze_order_snapshot(
task,
@@ -1426,6 +1306,12 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
expected_order_data_version=int(task.order_data_version or 1),
freeze_mode='manual',
)
snapshot = db.session.get(ShippingOrderSnapshot, int(task.order_snapshot_id))
if snapshot is None:
raise ConflictError(
'Confirmed order snapshot is required for wave assignment',
code='SHIPPING.REVIEW_LINE_SNAPSHOT_MAPPING_MISSING',
)
except AppError as err:
_reject_confirmation(
case,
@@ -1435,14 +1321,9 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
before=before_snap,
needs_rollback=True,
)
# [STEP] 确认订单只做整单确认(业务规则:确认订单不可分行;仅“产生发货通知”可分波次)。
# 因此 revision 记录整单草稿行,不按 draft_line_ids 过滤。
revision_lines = copy.deepcopy(case.current_draft.lines_json or [])
if wave_keys is not None:
wanted = set(wave_keys)
revision_lines = [
item for idx, item in enumerate(revision_lines)
if isinstance(item, dict)
and (str(item.get('line_key') or '').strip() or f'line-{idx + 1}') in wanted
]
revision = ShippingOrderReviewConfirmedRevision(
case_id=int(case.id), task_id=int(task.id), draft_version=int(case.current_draft.draft_version),
schema_version_id=int(case.current_draft.schema_version_id), header_values_json=copy.deepcopy(case.current_draft.header_values_json or {}),
@@ -1451,12 +1332,8 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
)
db.session.add(revision)
db.session.flush()
# [STEP] 行级唯一归属:本波次(或整单)行写入不可变 wave_lines,防并发重复入波次。
wave_line_keys = list(wave_keys) if wave_keys is not None else [
(str(item.get('line_key') or '').strip() or f'line-{idx + 1}')
for idx, item in enumerate(case.current_draft.lines_json or [])
if isinstance(item, dict)
]
# [STEP] 行级归属记录:确认订单整单写入 snapshot 全部行(防并发重复入波次)。
wave_line_ids = [int(line.id) for line in snapshot.lines]
from sqlalchemy import func
max_wave = (
@@ -1469,7 +1346,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
_persist_wave_lines_for_task(
case=case,
task=task,
line_keys=wave_line_keys,
snapshot_line_ids=wave_line_ids,
wave_no=next_wave_no,
revision_id=int(revision.id),
)
@@ -1484,47 +1361,14 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
case_no=str(case_no),
owner_user_id=int(user_id),
)
# [STEP] 履约波次:若仍有未入 Task/未关闭的草稿行,Case 保持 ready 以支持后续波次。
has_remaining_open = False
if wave_keys is not None:
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
project_review_case_line_decisions,
)
terminal = {'task_created', 'fulfilled', 'closed_unfulfillable'}
projected = project_review_case_line_decisions(case)
draft_all_keys = {
(str(item.get('line_key') or '').strip() or f'line-{idx + 1}')
for idx, item in enumerate(case.current_draft.lines_json or [])
if isinstance(item, dict)
}
assigned = {
str(row.line_key)
for row in ShippingOrderReviewWaveLine.query.filter_by(review_case_id=int(case.id)).all()
}
for key in draft_all_keys:
if key in assigned:
continue
matched = next(
(item for item in (projected.get('lines') or []) if str(item.get('line_key') or '') == key),
None,
)
# 未入波次且未关闭的行保留 Case 可继续确认。
if matched is None or matched.get('line_status') not in terminal:
has_remaining_open = True
break
if has_remaining_open:
case.status = 'ready'
case.confirmed_task_id = int(task.id)
# 保留首次确认时间;首波未终态时写入当前时间供追溯。
if case.confirmed_at is None:
case.confirmed_at = datetime.utcnow()
else:
case.status = 'confirmed'
case.confirmed_task_id = int(task.id)
case.confirmed_at = datetime.utcnow()
# [STEP] 文件主线锁定已确认版本;后完成的并行重解析不得覆盖正式履约事实。
from app.services.shipping_notice.review_stream_service import mark_review_stream_confirmed
mark_review_stream_confirmed(case=case)
# [STEP] 确认订单恒为整单终态确认(业务规则:确认订单不可分行,整单全过才确认)。
# 不再有“仍有开放行则保持 ready 支持后续波次”的中间态。
case.status = 'confirmed'
case.confirmed_task_id = int(task.id)
case.confirmed_at = datetime.utcnow()
# [STEP] 文件主线锁定已确认版本;后完成的并行重解析不得覆盖正式履约事实。
from app.services.shipping_notice.review_stream_service import mark_review_stream_confirmed
mark_review_stream_confirmed(case=case)
db.session.add(ShippingOrderReviewCaseEvent(
case_id=int(case.id), event_type='case_confirmed', draft_version=int(case.current_draft.draft_version),
actor_user_id=int(user_id), operation_json={
@@ -1532,8 +1376,6 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
'idempotency_key': key,
'warning_acknowledgements': acknowledgements,
'confirm_note': str(confirm_note or '').strip()[:1024] or None,
'line_keys': wave_keys,
'partial_wave': bool(has_remaining_open),
},
))
# Case 级统一审计必须先写:即使工作项尚未绑定,审计中心仍可按 Case 追溯确认事实。
@@ -1576,7 +1418,7 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
)
def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
def _task_needs_post_confirm_auto_progress(task: ShippingOrderTask | None) -> bool:
"""
判断确认建单后的任务是否仍需自动推进。
@@ -1593,16 +1435,18 @@ def _task_needs_post_confirm_auto_progress(task: ShippingNotice | None) -> bool:
return False
if not getattr(task, 'current_order_extraction_id', None):
return False
inventory_snapshot_id = getattr(task, 'inventory_snapshot_id', None)
inventory_lines = getattr(task, 'inventory_lines_json', None)
match_status = getattr(task, 'match_status', None)
export_file_path = getattr(task, 'export_file_path', None)
upload_status = getattr(task, 'upload_status', None)
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt
export_file_path = getattr(latest_export_artifact(task), 'file_path', None)
upload_status = getattr(latest_upload_attempt(task), 'status', None)
# 仅已定义且已持久化的业务事实才能阻止自动推进。禁止把 ORM mock、关系代理等
# 任意 Python 真值误判为已进入后续阶段,避免 confirmed OT 停在 created。
has_inventory = isinstance(inventory_snapshot_id, int) and not isinstance(inventory_snapshot_id, bool)
has_inventory = has_inventory or isinstance(inventory_lines, (list, dict)) and bool(inventory_lines)
has_match = isinstance(match_status, str) and bool(match_status.strip())
from app.services.shipping_notice.inventory_file_store import (
current_inventory_matches_for_task,
has_ready_inventory_file_for_task,
)
has_inventory = has_ready_inventory_file_for_task(task)
has_match = bool(current_inventory_matches_for_task(task))
has_export = isinstance(export_file_path, str) and bool(export_file_path.strip())
has_upload = isinstance(upload_status, str) and bool(upload_status.strip())
return not (has_inventory or has_match or has_export or has_upload)
@@ -1661,7 +1505,7 @@ def schedule_auto_progress_after_review_confirm(
if not normalized:
return None
task = db.session.query(ShippingNotice).filter(ShippingNotice.task_no == normalized).first()
task = db.session.query(ShippingOrderTask).filter(ShippingOrderTask.task_no == normalized).first()
# [STEP] 首轮与幂等回放共用:仅当仍停在 created+已抽取时入队,避免无条件跳过导致悬挂。
if not _task_needs_post_confirm_auto_progress(task):
return None
@@ -2,8 +2,8 @@
services/shipping_notice/order_review_customer_service.py
用途:建单前复核工作台的客户识别结果查询、重新匹配与人工确认。
依赖:order_review_draft_service、order_customer_matching、candidate_qualification_service、
ShippingOrderReviewCase / ShippingOrderCustomerMatch。
依赖:order_review_draft_service、candidate_qualification_service、客户识别结果服务、
ShippingOrderReviewCase / ShippingCustomerShadowResolution。
逻辑:由 workspace order-review-cases 客户路由调用;确认后重跑 Draft 校验以刷新建单资格;
不创建 Task、不重新解析 PDF。
"""
@@ -17,18 +17,13 @@ from app.core.errors import ConflictError, NotFoundError
from app.models import (
ShippingOrderCandidate,
ShippingCustomerShadowResolution,
ShippingOrderCustomerMatch,
ShippingOrderExtraction,
ShippingOrderReviewCase,
)
from app.services.shipping_notice.candidate_qualification_service import (
resolve_review_case_customer_resolved,
)
from app.services.shipping_notice.order_customer_matching import (
confirm_order_customer_match,
refresh_order_customer_matches,
serialize_order_customer_match,
)
from app.services.shipping_notice.customer_resolution_service import confirm_customer_resolution
from app.services.shipping_notice.workflow_ledger_service import (
assert_case_is_current_workflow_version,
)
@@ -78,42 +73,6 @@ def _resolve_extraction_for_case(case: ShippingOrderReviewCase) -> ShippingOrder
)
def _header_from_case(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""从 Draft / Candidate 业务摘要投影客户匹配所需的头字段。"""
header: dict[str, Any] = {}
draft = case.current_draft
if draft is not None and isinstance(draft.header_values_json, dict):
# Draft 以 field_id 存值;客户匹配需要 bill_to_* 业务码,尽量从 Candidate 摘要补齐。
for key, value in draft.header_values_json.items():
if isinstance(key, str) and value is not None:
header[str(key)] = value
candidate = (
db.session.get(ShippingOrderCandidate, int(case.candidate_id))
if case.candidate_id
else None
)
structured = candidate.structured_result_json if candidate is not None else None
summary = (
structured.get('business_summary')
if isinstance(structured, dict) and isinstance(structured.get('business_summary'), dict)
else {}
)
for key in (
'bill_to_customer',
'bill_to_customer_code',
'bill_to_source_system',
'ship_to_customer',
'ship_to_code',
'ship_to_source_system',
'customer_name',
):
if key not in header and summary.get(key) is not None:
header[key] = summary.get(key)
if 'bill_to_customer' not in header and header.get('customer_name'):
header['bill_to_customer'] = header.get('customer_name')
return header
def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""
投影复核 Case 的建单前客户识别状态,供工作台固定客户区展示。
@@ -138,25 +97,16 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di
if candidate is not None
else None
)
match = None
if extraction is not None:
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 None
shadow_matches = list(shadow.candidate_matches_json or []) if shadow is not None else []
top_shadow = shadow_matches[0] if shadow_matches else {}
status = 'confirmed' if resolved else str(
(shadow.status if shadow is not None else None)
or (match_payload or {}).get('status')
or 'unmatched'
)
# [STEP 1] 客户识别展示以已发布规则集生成的指纹候选为准;旧 CustomerMatch 仅作为确认状态兼容投影。
display_match = match_payload or {}
# [STEP 1] 客户识别展示和确认均以已发布规则集生成的证据快照为准。
display_match: dict[str, Any] = {}
if top_shadow:
display_match = {
**display_match,
'customer_id': top_shadow.get('customer_id'),
'standard_name': top_shadow.get('standard_name'),
'short_code': top_shadow.get('short_code'),
@@ -216,7 +166,7 @@ def project_review_case_customer_resolution(case: ShippingOrderReviewCase) -> di
'role': 'customer',
'extraction_id': int(extraction.id) if extraction is not None else None,
'raw_name': None,
'customer_id': display_match.get('customer_id'),
'customer_id': getattr(shadow, 'confirmed_customer_id', None) or display_match.get('customer_id'),
'standard_name': display_match.get('standard_name'),
'short_code': display_match.get('short_code'),
'candidates': list(display_match.get('candidates') or []),
@@ -236,7 +186,7 @@ def confirm_review_case_customer(
"""
在复核工作台确认标准客户,并刷新建单资格。
核心逻辑:写入 Bill-to CustomerMatch=confirmed → 统一协调器推进 → 返回最新 Case。
核心逻辑:确认正式客户识别结果 → 统一协调器推进 → 返回最新 Case。
"""
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress,
@@ -244,25 +194,15 @@ def confirm_review_case_customer(
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:
raise ConflictError(
'Order extraction is required before confirming customer',
code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND',
)
# [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',
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id)) if case.candidate_id else None
if candidate is None:
raise ConflictError('Candidate is required before confirming customer', code='SHIPPING.CUSTOMER_RESOLUTION_REQUIRED')
confirm_customer_resolution(
candidate,
customer_id=int(customer_id),
site_id=None,
actor_id=int(user_id),
method='manual',
reason=str(reason or '复核工作台人工确认标准客户').strip(),
commit=False,
)
# [STEP P1-8] 客户人工确认后走统一协调器:终态门禁 + 客户协调(已人工确认会跳过)+
# Draft 校验 + STP 入队;trigger=customer_confirmed 对应人工确认语义。
@@ -306,7 +246,7 @@ def retry_review_case_customer_resolution(
case_no: str,
) -> dict[str, Any]:
"""
重新识别客户(不重解析 PDF):按当前 Draft/摘要刷新 CustomerMatch。
重新识别客户(不重解析 PDF):刷新规则驱动的客户识别快照。
【AI 触发时机】:用户在复核工作台点击「重新识别客户」时调用。
"""
@@ -316,13 +256,7 @@ def retry_review_case_customer_resolution(
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:
raise ConflictError(
'Order extraction is required before retrying customer resolution',
code='SHIPPING.ORDER_EXTRACTION_NOT_FOUND',
)
matches = refresh_order_customer_matches(extraction, _header_from_case(case))
matches: list[dict[str, Any]] = []
if case.candidate_id:
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
candidate = db.session.get(ShippingOrderCandidate, int(case.candidate_id))
@@ -334,16 +268,14 @@ 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',
confirm_customer_resolution(
candidate,
customer_id=int(shadow.top_customer_id),
site_id=None,
actor_id=None,
method='auto_rule',
reason='客户识别指纹唯一命中自动确认',
commit=False,
)
matches = list(shadow.candidate_matches_json or [])
# [STEP P1-8] 客户 shadow 重新识别后走统一协调器;trigger=customer_shadow_reconfirmed
# 标识为「影子指纹再确认 + 唯一命中自动确认」路径,与 PATCH 异步 Job、人工确认按钮路径互补不冲突。
reconcile_result = reconcile_single_case_for_auto_progress(
@@ -1074,6 +1074,11 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo
因此只在 ``activate_review_case`` 已确认切换成功后调用单 Case 协调器。这样复用
客户确认、Draft 校验、Gate 与 STP 幂等链路,且不会让晚到分支覆盖已确认版本。
终态闭环不变式:后继 Run 收口时业务必须二选一 —— 新版 Case 已上位 Stream,
或旧版 Case 已恢复为可编辑状态。绝不允许旧 Case 停留在 ``reparse_pending``
而新版被孤儿化:该状态下工作台会永久卡在历史版本,且任何 API 都无法再次
触达新版或重新发起重识别。
Args:
run: 已到终态的重解析后继 Run。
succeeded: 新版 Run 是否成功到达可复核终态。
@@ -1095,21 +1100,24 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo
).with_for_update().first()
)
if source_case is None or source_case.status != 'reparse_pending':
# 并发分支已裁决(被另一失败后继恢复、或已确认走另一分支):
# Stream 现状即权威,此处回改只会制造第二真相源。
return
if succeeded:
replacement_case = ShippingOrderReviewCase.query.filter_by(
replacement_case = (
ShippingOrderReviewCase.query.filter_by(
run_id=int(run.id), document_id=document_id,
).with_for_update().first()
if replacement_case is None:
# Run 已到终态但没有可复核新版本时,不可废弃旧草稿。
return
if succeeded
else None
)
if replacement_case is not None:
from app.services.shipping_notice.review_stream_service import activate_review_case
stream = activate_review_case(
case=replacement_case,
trigger='batch_reparse_succeeded' if marker.get('batch_reparse_id') else 'document_reparse_succeeded',
)
# [STEP] 只有 Stream 已原子指向新版 Case 才补偿自动推进。激活被并发确认或
# 晚到分支拒绝时,保持该草稿只读,不得错误建单或进入库存准备。
# [STEP] 只有 Stream 已原子指向新版 Case 才补偿自动推进并宣告成功;
# 激活被并发确认或晚到分支拒绝时,禁止记录 succeeded 审计(与事实不符)。
if int(stream.current_case_id or 0) == int(replacement_case.id):
from app.services.shipping_notice.order_review_auto_progress_coordinator import (
reconcile_single_case_for_auto_progress,
@@ -1119,11 +1127,17 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo
trigger='document_reparse_succeeded',
refresh_validation=True,
)
_append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={
'successor_run_no': run.run_no,
'replacement_case_no': replacement_case.case_no,
})
return
_append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_succeeded', operation={
'successor_run_no': run.run_no,
'replacement_case_no': replacement_case.case_no,
})
return
finalize_failure_reason = 'stream_activation_rejected'
else:
finalize_failure_reason = 'replacement_case_missing'
# [C1] 终态闭环:成功终态但新版 Case 缺失、或激活被拒绝时,禁止静默返回 ——
# 否则旧 Case 永久停留在 reparse_pending(编辑/确认全被禁且无法再触发重识别),
# 工作台只能卡在历史版本。转入既有失败恢复链把旧 Case 恢复为可编辑状态。
previous = 'quality_issue'
event = ShippingOrderReviewCaseEvent.query.filter(
ShippingOrderReviewCaseEvent.case_id == int(source_case.id),
@@ -1136,6 +1150,7 @@ def finalize_document_reparse(*, run: ShippingOrderProcessingRun, succeeded: boo
source_case.status = previous
_append_event(source_case, actor_id=int(run.user_id), event_type='document_reparse_failed', operation={
'successor_run_no': run.run_no, 'restored_status': previous,
'failure_reason': finalize_failure_reason,
})
from app.services.shipping_notice.workflow_ledger_service import mark_reparse_failed_and_restore
mark_reparse_failed_and_restore(
@@ -10,7 +10,7 @@ services/shipping_notice/order_review_draft_service.py
追加 CaseEvent + ShippingAuditEvent,并镜像 review_field_changed 到订单抽取进度流;
Item 已关闭/重识别中的冲突经 `_reject_draft_operation` 落 rejected 审计;
整单校验汇总客户确认、有效 Reservation、行级库存源候选与自动建单资格;
履约波次确认经 build_confirmable_draft_summary(line_keys) 仅对选中行重算 validation;
履约波次确认经 build_confirmable_draft_summary(draft_line_ids) 仅对选中行重算 validation;
库存路由恢复使用最新已发布规则与库存源启停,不重新识别 PDF,不静默覆盖人工决定;
路由恢复幂等键写入 Draft 历史集合(非仅最近一次),旧键重试可安全重放;
显式校验后同步字段完整性、字段冲突、客户/Reservation/重复订单/库存路由 Gate(findings.details)。
@@ -47,7 +47,6 @@ from app.services.shipping_notice.order_build_eligibility_service import (
from app.services.shipping_notice.recovery_contract import build_review_revalidate_job_ref
from app.services.shipping_notice.order_review_projection import serialize_review_case
from app.services.shipping_notice.order_schema.field_rules import (
is_valid_line_no_value,
normalize_order_field_value,
validate_order_field_value,
)
@@ -335,21 +334,21 @@ def _machine_value(machine_fields: list[Any], field_id: str) -> Any:
def _find_line(
case: ShippingOrderReviewCase,
lines: list[dict[str, Any]],
line_key: str,
draft_line_id: str,
*,
actor_id: int,
action: str,
) -> dict[str, Any]:
"""按稳定 line_key 获取草稿行;不存在时写拒绝审计。"""
"""按稳定 draft_line_id 获取草稿行;不存在时写拒绝审计。"""
for item in lines:
if isinstance(item, dict) and str(item.get('line_key') or '') == str(line_key or ''):
if isinstance(item, dict) and str(item.get('draft_line_id') or '') == str(draft_line_id or ''):
return item
_reject_draft_operation(
case,
actor_id=actor_id,
action=action,
error=ValidationError('Review line is unavailable', code='SHIPPING.REVIEW_LINE_NOT_FOUND'),
metadata={'line_key': str(line_key or '')[:64] or None},
metadata={'draft_line_id': str(draft_line_id or '')[:128] or None},
)
@@ -400,14 +399,6 @@ def draft_has_unaccepted_llm_suggestions(case: ShippingOrderReviewCase) -> bool:
return False
LINE_NO_OVERRIDE_REASON_CODES = frozenset({
'recognition_error',
'customer_line_exception',
'business_correction',
'other',
})
def _set_value(container: dict[str, Any], field: dict[str, Any], value: Any, *, restore_machine: bool) -> dict[str, Any]:
"""写入单字段人工值或移除人工覆盖层;类型规范化始终按冻结字段规则执行。"""
values = dict(container.get('values') or {})
@@ -476,9 +467,9 @@ def _validation(
line[str(field.get('field_code') or field_id)] = value
normalized = normalize_order_field_value(value, field)
if field.get('required') and normalized in (None, ''):
issues.append({'code': 'required_field_missing', 'field_id': field_id, 'line_key': raw_line.get('line_key'), 'severity': 'blocking'})
issues.append({'code': 'required_field_missing', 'field_id': field_id, 'draft_line_id': raw_line.get('draft_line_id'), 'severity': 'blocking'})
elif normalized is not None and not validate_order_field_value(normalized, field):
issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'line_key': raw_line.get('line_key'), 'severity': 'blocking'})
issues.append({'code': 'field_value_invalid', 'field_id': field_id, 'draft_line_id': raw_line.get('draft_line_id'), 'severity': 'blocking'})
lines.append(line)
line_metas.append(raw_line)
@@ -512,8 +503,13 @@ def _validation(
if isinstance(item, dict):
issues.append(dict(item))
# 人工确认只看 blocking;五门禁 severity=auto_create_blocking 不阻断 can_build。
# 库存源路由属于确认后由正式 inventory_source_routing Gate 处理的事实,
# 这里不得把 inventory_source_routing 的 blocking 项重新纳入(eligibility.can_build 已排除),
# 否则"仅库存源未定"的订单会再次被判 needs_review,与"确认只确认订单信息"冲突。
can_build = bool(eligibility.get('can_build')) and not any(
str(item.get('severity') or '') == 'blocking' for item in issues
str(item.get('severity') or '') == 'blocking'
and str(item.get('owning_gate_code') or '') != 'inventory_source_routing'
for item in issues
)
# [STEP 2] 为缺失/无效字段补齐 field_code + display_name,禁止只返回裸 code。
enriched_issues: list[dict[str, Any]] = []
@@ -563,14 +559,14 @@ def _validation(
def build_confirmable_draft_summary(
case: ShippingOrderReviewCase,
*,
line_keys: list[str] | None = None,
draft_line_ids: list[str] | None = None,
) -> tuple[dict[str, Any], dict[str, Any]]:
"""
从冻结 Schema 投影完整草稿并重跑确认校验,供原子建单服务使用。
Args:
case: 复核 Case。
line_keys: 可选;仅投影这些完整明细行(履约波次),禁止拆分数量。
draft_line_ids: 可选;仅投影这些完整明细行(履约波次),禁止拆分数量。
Returns:
(summary, validation) 元组。
@@ -583,17 +579,17 @@ def build_confirmable_draft_summary(
if str(field.get('scope') or '') == 'header'
}
raw_lines = [item for item in (case.current_draft.lines_json or []) if isinstance(item, dict)]
if line_keys is not None:
wanted = {str(k).strip() for k in line_keys if str(k).strip()}
if draft_line_ids is not None:
wanted = {str(k).strip() for k in draft_line_ids if str(k).strip()}
filtered: list[dict[str, Any]] = []
for idx, raw_line in enumerate(raw_lines):
key = str(raw_line.get('line_key') or '').strip() or f'line-{idx + 1}'
key = str(raw_line.get('draft_line_id') or '').strip()
if key in wanted:
filtered.append(raw_line)
if len(filtered) != len(wanted):
from app.core.errors import ValidationError
raise ValidationError(
'One or more line_keys not found in draft',
'One or more draft_line_ids not found in draft',
code='SHIPPING.REVIEW_LINE_NOT_FOUND',
)
raw_lines = filtered
@@ -605,11 +601,11 @@ def build_confirmable_draft_summary(
}
for raw_line in raw_lines
]
# 波次建单时保留草稿行键,供血缘与决定回写对齐。
# 波次建单时保留草稿行身份,供血缘与决定回写对齐。
for idx, raw_line in enumerate(raw_lines):
key = str(raw_line.get('line_key') or '').strip()
key = str(raw_line.get('draft_line_id') or '').strip()
if key and idx < len(lines):
lines[idx]['line_key'] = key
lines[idx]['draft_line_id'] = key
# [STEP] 履约波次必须按选中行重算 can_build/status,禁止继承未选中行的整单失败态。
validation = _validation(case, raw_lines=raw_lines)
return {**header, 'lines': lines}, validation
@@ -719,11 +715,11 @@ def _record_change(
operation_json=operation,
))
changed_paths = [
key for key in ('field_id', 'line_key', 'action')
key for key in ('field_id', 'draft_line_id', 'action')
if key in operation and operation.get(key) is not None
]
field_id = operation.get('field_id')
line_key = operation.get('line_key')
draft_line_id = operation.get('draft_line_id')
previous_value = _audit_scalar(operation.get('previous_value'))
new_value = _audit_scalar(operation.get('value') if 'value' in operation else operation.get('new_value'))
value_source = str(operation.get('source') or '')[:32] or None
@@ -751,9 +747,9 @@ def _record_change(
after_snapshot['new_value'] = new_value
if value_source:
after_snapshot['value_source'] = value_source
if line_key is not None:
before_snapshot['line_key'] = str(line_key)[:64]
after_snapshot['line_key'] = str(line_key)[:64]
if draft_line_id is not None:
before_snapshot['draft_line_id'] = str(draft_line_id)[:128]
after_snapshot['draft_line_id'] = str(draft_line_id)[:128]
# [STEP] 库存路由恢复:把候选与规则版本写入前后快照,供审计中心展示。
if str(event_type or '').startswith('inventory_routing_'):
before_raw = operation.get('previous_value')
@@ -797,8 +793,8 @@ def _record_change(
after_snapshot['action_semantics'] = str(operation.get('action_semantics'))[:64]
if operation.get('idempotency_key'):
after_snapshot['idempotency_key'] = str(operation.get('idempotency_key'))[:128]
if operation.get('line_keys') is not None:
after_snapshot['line_keys'] = [str(item)[:64] for item in list(operation.get('line_keys') or [])[:50]]
if operation.get('draft_line_ids') is not None:
after_snapshot['draft_line_ids'] = [str(item)[:128] for item in list(operation.get('draft_line_ids') or [])[:50]]
# 恢复机器值使用独立事件类型,便于坐标/字段证据反查(阶段 5)。
audit_event_type = (
'review_field_restored_machine'
@@ -887,139 +883,31 @@ def patch_line_field(
*,
user_id: int,
case_no: str,
line_key: str,
draft_line_id: str,
field_id: str,
value: Any,
expected_draft_version: Any,
restore_machine: bool = False,
override_reason_code: str | None = None,
override_reason_text: str | None = None,
) -> dict[str, Any]:
"""
编辑或恢复一条明细字段;行由不可变 line_key 定位并受同一草稿版本锁保护。
编辑或恢复一条明细字段;行由不可变 draft_line_id 定位并受同一草稿版本锁保护。
核心逻辑:一般字段沿用 manual 覆盖;内部项次 line_no 覆盖须原因分类并锁定;
恢复时清除 override,回退到草稿 machine_fields 中的识别/派生投影(不重新跑派生引擎),
并写 LINE_NO_RESTORED。
核心逻辑:一般字段沿用 manual 覆盖;内部项次 line_no 是系统项次,禁止覆盖或恢复。
"""
action = 'line_field_changed'
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)
field = _require_field(case, field_id, 'line', actor_id=user_id, action=action)
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target = _find_line(case, lines, line_key, actor_id=user_id, action=action)
target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action)
previous_value = _current_value(target, field_id)
field_code = str(field.get('field_code') or '')
if field_code == 'line_no' and restore_machine:
prior_entry = (target.get('values') or {}).get(field_id) if isinstance(target.get('values'), dict) else None
prior_source = str((prior_entry or {}).get('source') or 'manual_override')
change = _set_value(target, field, value, restore_machine=True)
# 恢复后的展示值来自 machine_fields:初始化草稿时已含识别/派生投影,非二次派生。
restored_source = 'machine_or_derived_projection'
case.current_draft.lines_json = lines
result = _record_change(
case,
actor_id=user_id,
event_type=action,
operation={
'line_key': line_key,
'field_id': field_id,
'field_code': field_code,
'previous_value': previous_value,
'restored_source': restored_source,
'prior_value_source': prior_source,
**change,
},
if field_code == 'line_no':
raise ValidationError(
'line_no is system-generated and cannot be edited or restored',
code='SHIPPING.REVIEW_LINE_NO_IMMUTABLE',
)
append_shipping_audit_event(
event_type='LINE_NO_RESTORED',
aggregate_type='shipping_order_review_case',
aggregate_id=str(case.case_no),
actor_type='user',
actor_id=user_id,
review_case_no=str(case.case_no),
action='restore_line_no',
result='success',
metadata={
'line_key': line_key,
'field_code': 'line_no',
'restored_source': restored_source,
'prior_value_source': prior_source,
},
before={'previous_value': previous_value, 'value_source': prior_source},
after={'new_value': change.get('value'), 'value_source': restored_source},
)
return result
if field_code == 'line_no' and not restore_machine:
reason_code = str(override_reason_code or '').strip()
reason_text = str(override_reason_text or '').strip()
if reason_code not in LINE_NO_OVERRIDE_REASON_CODES:
raise ValidationError(
'line_no override requires a valid reason code',
code='SHIPPING.REVIEW_LINE_NO_OVERRIDE_REASON_REQUIRED',
)
if reason_code == 'other' and not reason_text:
raise ValidationError(
'line_no override reason text is required for other',
code='SHIPPING.REVIEW_LINE_NO_OVERRIDE_TEXT_REQUIRED',
)
if not is_valid_line_no_value(value):
raise ValidationError(
'line_no must be 1-6 digits',
code='SHIPPING.REVIEW_LINE_NO_FORMAT_INVALID',
)
change = _set_value(target, field, value, restore_machine=False)
values = dict(target.get('values') or {})
values[str(field['field_id'])] = {
'value': change['value'],
'source': 'manual_override',
'locked': True,
'override_reason_code': reason_code,
'override_reason_text': reason_text or None,
}
target['values'] = values
change = {
**change,
'source': 'manual_override',
'override_reason_code': reason_code,
'override_reason_text': reason_text or None,
'locked': True,
}
case.current_draft.lines_json = lines
result = _record_change(
case,
actor_id=user_id,
event_type=action,
operation={
'line_key': line_key,
'field_id': field_id,
'field_code': field_code,
'previous_value': previous_value,
**change,
},
)
append_shipping_audit_event(
event_type='LINE_NO_OVERRIDDEN',
aggregate_type='shipping_order_review_case',
aggregate_id=str(case.case_no),
actor_type='user',
actor_id=user_id,
review_case_no=str(case.case_no),
action='override_line_no',
result='success',
reason_code=reason_code,
reason=reason_text or None,
metadata={
'line_key': line_key,
'field_code': 'line_no',
'override_reason_code': reason_code,
},
before={'previous_value': previous_value, 'value_source': 'prior'},
after={'new_value': change['value'], 'value_source': 'manual_override'},
)
return result
change = _set_value(target, field, value, restore_machine=restore_machine)
case.current_draft.lines_json = lines
@@ -1028,7 +916,7 @@ def patch_line_field(
actor_id=user_id,
event_type=action,
operation={
'line_key': line_key,
'draft_line_id': draft_line_id,
'field_id': field_id,
'previous_value': previous_value,
**change,
@@ -1042,34 +930,34 @@ def add_line(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict
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)
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
line_key = f'manual-{uuid.uuid4().hex[:16]}'
lines.append({'line_key': line_key, 'machine_fields': [], 'values': {}})
draft_line_id = str(uuid.uuid4())
lines.append({'draft_line_id': draft_line_id, 'machine_fields': [], 'values': {}})
case.current_draft.lines_json = lines
return _record_change(case, actor_id=user_id, event_type=action, operation={'line_key': line_key})
return _record_change(case, actor_id=user_id, event_type=action, operation={'draft_line_id': draft_line_id})
def copy_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]:
"""复制明细为新 line_key;复制后的 Reservation 重复会由全量校验显式阻断。"""
def copy_line(*, user_id: int, case_no: str, draft_line_id: str, expected_draft_version: Any) -> dict[str, Any]:
"""复制明细为新 draft_line_id;复制后的 Reservation 重复会由全量校验显式阻断。"""
action = 'line_copied'
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)
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
copied = copy.deepcopy(_find_line(case, lines, line_key, actor_id=user_id, action=action))
copied['line_key'] = f'manual-{uuid.uuid4().hex[:16]}'
copied = copy.deepcopy(_find_line(case, lines, draft_line_id, actor_id=user_id, action=action))
copied['draft_line_id'] = str(uuid.uuid4())
lines.append(copied)
case.current_draft.lines_json = lines
return _record_change(case, actor_id=user_id, event_type=action, operation={'source_line_key': line_key, 'line_key': copied['line_key']})
return _record_change(case, actor_id=user_id, event_type=action, operation={'source_draft_line_id': draft_line_id, 'draft_line_id': copied['draft_line_id']})
def delete_line(*, user_id: int, case_no: str, line_key: str, expected_draft_version: Any) -> dict[str, Any]:
def delete_line(*, user_id: int, case_no: str, draft_line_id: str, expected_draft_version: Any) -> dict[str, Any]:
"""删除单条草稿行并写审计;删除最后有效行会保留为阻断校验结果。"""
action = 'line_deleted'
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)
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
_find_line(case, lines, line_key, actor_id=user_id, action=action)
case.current_draft.lines_json = [item for item in lines if str(item.get('line_key') or '') != str(line_key)]
return _record_change(case, actor_id=user_id, event_type=action, operation={'line_key': line_key})
_find_line(case, lines, draft_line_id, actor_id=user_id, action=action)
case.current_draft.lines_json = [item for item in lines if str(item.get('draft_line_id') or '') != str(draft_line_id)]
return _record_change(case, actor_id=user_id, event_type=action, operation={'draft_line_id': draft_line_id})
def validate_draft(*, user_id: int, case_no: str, expected_draft_version: Any) -> dict[str, Any]:
@@ -1102,7 +990,7 @@ def _routing_idempotency_entry_key(*, action: str, idempotency_key: str) -> str:
生成幂等历史条目键(动作 + 幂等键)。
Args:
action: 路由恢复动作(可含 line_key 后缀)。
action: 路由恢复动作(可含 draft_line_id 后缀)。
idempotency_key: 已规范化的幂等键。
Returns:
@@ -1166,7 +1054,7 @@ def _store_routing_recovery_idempotency(
*,
action: str,
idempotency_key: str,
line_keys: list[str],
draft_line_ids: list[str],
) -> None:
"""
将成功的路由恢复幂等键追加写入 Draft 历史集合(非整对象覆盖)。
@@ -1184,7 +1072,7 @@ def _store_routing_recovery_idempotency(
record = {
'idempotency_key': key,
'action': action,
'line_keys': [str(item)[:64] for item in line_keys[:50]],
'draft_line_ids': [str(item)[:128] for item in draft_line_ids[:50]],
'draft_version_after': int(draft.draft_version) + 1,
}
entries[entry_key] = record
@@ -1214,7 +1102,7 @@ def _line_routing_snapshot(line: dict[str, Any], fields: dict[str, dict[str, Any
line_meta=line,
)
return {
'line_key': str(line.get('line_key') or '')[:64],
'draft_line_id': str(line.get('draft_line_id') or '')[:128],
'selection_mode': projection.get('selection_mode'),
'candidate_inventory_source_codes': list(projection.get('candidate_inventory_source_codes') or []),
'raw_rule_source_codes': list(projection.get('raw_rule_source_codes') or []),
@@ -1243,7 +1131,7 @@ def reroute_inventory_routing(
case_no: str,
expected_draft_version: Any,
idempotency_key: str | None = None,
line_key: str | None = None,
draft_line_id: str | None = None,
) -> dict[str, Any]:
"""
按最新已发布规则与库存源启停重算库存路由;不重新识别 PDF。
@@ -1256,7 +1144,7 @@ def reroute_inventory_routing(
case_no: 复核 Case 编号。
expected_draft_version: 乐观锁版本。
idempotency_key: 可选幂等键。
line_key: 可选,仅重算指定行;缺省整单。
draft_line_id: 可选,仅重算指定行;缺省整单。
Returns:
序列化后的 Case 详情。
@@ -1271,7 +1159,7 @@ def reroute_inventory_routing(
fields = _schema_fields(case)
header_by_code = _header_by_code_for_case(case, fields)
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target_key = str(line_key or '').strip()
target_key = str(draft_line_id or '').strip()
before_rows: list[dict[str, Any]] = []
after_rows: list[dict[str, Any]] = []
touched_keys: list[str] = []
@@ -1279,7 +1167,7 @@ def reroute_inventory_routing(
for raw in lines:
if not isinstance(raw, dict):
continue
current_key = str(raw.get('line_key') or '').strip()
current_key = str(raw.get('draft_line_id') or '').strip()
if target_key and current_key != target_key:
continue
if not current_key:
@@ -1305,7 +1193,7 @@ def reroute_inventory_routing(
actor_id=user_id,
action=action,
error=NotFoundError('Order review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND'),
metadata={'line_key': target_key[:64]},
metadata={'draft_line_id': target_key[:128]},
)
case.current_draft.lines_json = lines
@@ -1313,15 +1201,15 @@ def reroute_inventory_routing(
case,
action=action,
idempotency_key=str(idempotency_key or ''),
line_keys=touched_keys,
draft_line_ids=touched_keys,
)
return _record_change(
case,
actor_id=user_id,
event_type=action,
operation={
'line_key': target_key or None,
'line_keys': touched_keys,
'draft_line_id': target_key or None,
'draft_line_ids': touched_keys,
'idempotency_key': _normalize_routing_idempotency_key(idempotency_key) or None,
'previous_value': before_rows[:20],
'new_value': after_rows[:20],
@@ -1386,7 +1274,7 @@ def _candidate_conflict_locator(case: ShippingOrderReviewCase) -> dict[str, Any]
return {
'field_code': field_code,
'line_index': conflict.get('line_index'),
'line_key': conflict.get('line_key'),
'draft_line_id': conflict.get('draft_line_id'),
}
return {}
@@ -1462,7 +1350,7 @@ def _sync_review_gates_safe(
default_reason_code='field_conflict',
details={
**base_details,
'line_key': primary_conflict.get('line_key') or conflict_locator.get('line_key'),
'draft_line_id': primary_conflict.get('draft_line_id') or conflict_locator.get('draft_line_id'),
'line_index': primary_conflict.get('line_index')
if primary_conflict.get('line_index') is not None else conflict_locator.get('line_index'),
'field_code': primary_conflict.get('field_code') or conflict_locator.get('field_code'),
@@ -1496,7 +1384,7 @@ def _sync_review_gates_safe(
) or default_reason
sync_details = {
**base_details,
'line_key': primary.get('line_key'),
'draft_line_id': primary.get('draft_line_id'),
'line_index': primary.get('line_index'),
'field_code': primary.get('field_code'),
'issue_codes': [
@@ -1517,12 +1405,8 @@ def _sync_review_gates_safe(
inventory_issues = _blocking_issues_for_gate(result, 'inventory_source_routing')
if not inventory_issues:
sync_inventory_routing_gate_for_case(
case=case,
passed=True,
actor_id=int(user_id),
details=base_details,
)
# 复核草稿阶段只能评估路由结果,正式 CandidateSet 需绑定确认后的 Task;
# 因此不得在 draft_validated 时提前通过正式 inventory_source_routing Gate。
return
primary = inventory_issues[0]
@@ -1558,7 +1442,7 @@ def _sync_review_gates_safe(
'unavailable_source_codes': list(dict.fromkeys(unavailable_codes)),
'raw_rule_source_codes': list(dict.fromkeys(raw_codes)),
'matched_rule_codes': list(dict.fromkeys(matched_rule_codes)),
'line_key': primary.get('line_key'),
'draft_line_id': primary.get('draft_line_id'),
'line_index': primary.get('line_index'),
'candidate_inventory_source_codes': list(primary.get('candidate_inventory_source_codes') or []),
},
@@ -1599,7 +1483,7 @@ def apply_llm_suggestion_prefill(
user_id: int,
case_no: str,
field_id: str,
line_key: str | None,
draft_line_id: str | None,
value: Any,
suggestion_no: str,
expected_draft_version: Any,
@@ -1613,7 +1497,7 @@ def apply_llm_suggestion_prefill(
user_id: 操作人。
case_no: Case 编号。
field_id: 字段 ID。
line_key: 行键;表头为 None。
draft_line_id: 草稿行身份;表头为 None。
value: 建议值。
suggestion_no: 关联建议编号。
expected_draft_version: 乐观锁版本。
@@ -1627,13 +1511,13 @@ def apply_llm_suggestion_prefill(
field = _require_field(
case,
field_id,
'line' if line_key else 'header',
'line' if draft_line_id else 'header',
actor_id=user_id,
action=action,
)
if line_key:
if draft_line_id:
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target = _find_line(case, lines, line_key, actor_id=user_id, action=action)
target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action)
previous_value = _current_value(target, field_id)
change = _set_llm_suggested_value(target, field, value, suggestion_no=suggestion_no)
case.current_draft.lines_json = lines
@@ -1641,7 +1525,7 @@ def apply_llm_suggestion_prefill(
case,
actor_id=user_id,
event_type=action,
operation={'line_key': line_key, 'field_id': field_id, 'previous_value': previous_value, **change},
operation={'draft_line_id': draft_line_id, 'field_id': field_id, 'previous_value': previous_value, **change},
)
header = dict(case.current_draft.header_values_json or {})
previous_value = _current_value(header, field_id)
@@ -1692,10 +1576,10 @@ def adjudicate_llm_suggestion_on_draft(
actor_id=user_id,
action=action,
)
line_key = suggestion.line_key
if line_key:
draft_line_id = suggestion.draft_line_id
if draft_line_id:
lines = copy.deepcopy(list(case.current_draft.lines_json or []))
target = _find_line(case, lines, line_key, actor_id=user_id, action=action)
target = _find_line(case, lines, draft_line_id, actor_id=user_id, action=action)
previous_value = _current_value(target, suggestion.field_id)
if decision == 'reject':
values = dict(target.get('values') or {})
@@ -1731,7 +1615,7 @@ def adjudicate_llm_suggestion_on_draft(
actor_id=user_id,
event_type=action,
operation={
'line_key': line_key,
'draft_line_id': draft_line_id,
'field_id': suggestion.field_id,
'suggestion_no': suggestion.suggestion_no,
'previous_value': previous_value,
@@ -3,7 +3,7 @@ services/shipping_notice/order_review_evidence_selector.py
用途:为订单复核 AI 建议选择最小证据包(字段→单元格→表格→页面)。
依赖:Run 冻结 layout_snapshot / layout_schema_candidates。
逻辑:默认不超过 L3;明细必须绑定 line_key/行号;禁止写入 secret、临时签名 URL、完整请求头。
逻辑:默认不超过 L3;明细必须绑定 draft_line_id/行号;禁止写入 secret、临时签名 URL、完整请求头。
"""
from __future__ import annotations
@@ -42,7 +42,7 @@ def select_review_evidence_pack(
Args:
document: 冻结 Document 快照。
target_fields: 待建议字段定位信息(须含 field_id;明细须含 line_key)。
target_fields: 待建议字段定位信息(须含 field_id;明细须含 draft_line_id)。
evidence_level: L1–L4。
allow_full_pdf: 仅管理员显式 True 时允许 L4。
@@ -84,16 +84,16 @@ def select_review_evidence_pack(
hit_table_ids: set[str] = set()
hit_page_nos: set[int] = set()
# [STEP 1] L1:目标字段相邻 cell 文本;明细必须按 line_key 过滤。
# [STEP 1] L1:目标字段相邻 cell 文本;明细必须按 draft_line_id 过滤。
for target in target_fields:
if not isinstance(target, dict):
continue
field_id = str(target.get('field_id') or '')
line_key = str(target.get('line_key') or '').strip() or None
draft_line_id = str(target.get('draft_line_id') or '').strip() or None
snippets = _field_snippets(
candidates,
field_id=field_id,
line_key=line_key,
draft_line_id=draft_line_id,
line_number=target.get('line_number'),
)
for snippet in snippets:
@@ -107,7 +107,7 @@ def select_review_evidence_pack(
'field_id': field_id,
'field_code': target.get('field_code'),
'scope': target.get('scope'),
'line_key': line_key,
'draft_line_id': draft_line_id,
'line_number': target.get('line_number'),
'snippets': snippets[:8],
})
@@ -157,11 +157,11 @@ def _field_snippets(
candidates: list[dict[str, Any]],
*,
field_id: str,
line_key: str | None = None,
draft_line_id: str | None = None,
line_number: Any = None,
) -> list[dict[str, Any]]:
"""
收集目标 field_id 的短引文;明细行必须绑定 line_key / 行号。
收集目标 field_id 的短引文;明细行必须绑定 draft_line_id / 行号。
核心逻辑:header 字段可跨行收集;line 字段仅保留匹配目标行的 cell,禁止串行。
"""
@@ -170,7 +170,7 @@ def _field_snippets(
for row in candidate.get('rows') or []:
if not isinstance(row, dict):
continue
if not _row_matches_line(row, line_key=line_key, line_number=line_number):
if not _row_matches_line(row, draft_line_id=draft_line_id, line_number=line_number):
continue
for field in row.get('fields') or []:
if not isinstance(field, dict) or str(field.get('field_id') or '') != field_id:
@@ -181,7 +181,7 @@ def _field_snippets(
'page_no': int(candidate.get('page_no') or field.get('page_no') or 1),
'table_id': str(candidate.get('table_id') or field.get('table_id') or ''),
'row_index': int(row.get('row_index') or 0),
'line_key': str(row.get('line_key') or line_key or '') or None,
'draft_line_id': str(row.get('draft_line_id') or draft_line_id or '') or None,
'cell_id': str(field.get('cell_id') or '') or None,
'quote': quote[:500],
})
@@ -191,17 +191,17 @@ def _field_snippets(
def _row_matches_line(
row: dict[str, Any],
*,
line_key: str | None,
draft_line_id: str | None,
line_number: Any,
) -> bool:
"""判断布局行是否对应目标明细;无 line_key 时视为表头字段(允许任意行)。"""
if not line_key and line_number is None:
"""判断布局行是否对应目标明细;无 draft_line_id 时视为表头字段(允许任意行)。"""
if not draft_line_id and line_number is None:
return True
row_line_key = str(row.get('line_key') or '').strip()
# [STEP] 行上已有 line_key 时只做精确匹配,禁止再按 row_index 宽松回退。
if line_key and row_line_key:
return row_line_key == line_key
target_index = _line_key_to_index(line_key)
row_draft_line_id = str(row.get('draft_line_id') or '').strip()
# [STEP] 行上已有 draft_line_id 时只做精确匹配,禁止再按 row_index 宽松回退。
if draft_line_id and row_draft_line_id:
return row_draft_line_id == draft_line_id
target_index = _draft_line_id_to_index(draft_line_id)
if target_index is None and line_number is not None:
try:
target_index = int(line_number)
@@ -216,16 +216,16 @@ def _row_matches_line(
return int(data_position) == target_index
except (TypeError, ValueError):
return False
# 兼容仅有 1-based row_index 的布局行(无 line_key)。
# 布局行没有草稿身份时,仅按显式行号定位。
row_index = int(row.get('row_index') or -1)
return row_index == target_index + 1
def _line_key_to_index(line_key: str | None) -> int | None:
"""将 machine-N 行键转换为 0-based 行序号。"""
if not line_key:
def _draft_line_id_to_index(draft_line_id: str | None) -> int | None:
"""将 machine-N 草稿行身份转换为 0-based 行序号。"""
if not draft_line_id:
return None
matched = _MACHINE_LINE_KEY.match(str(line_key).strip())
matched = _MACHINE_LINE_KEY.match(str(draft_line_id).strip())
if not matched:
return None
return max(int(matched.group(1)) - 1, 0)
@@ -275,7 +275,7 @@ def _strip_forbidden(value: Any) -> Any:
_FIELD_CORE_PRIORITY = (
'field_id', 'value', 'quote', 'evidence_ref', 'field_code',
'scope', 'line_key', 'llm_context_policy', 'mask_rule', 'value_source',
'scope', 'draft_line_id', 'llm_context_policy', 'mask_rule', 'value_source',
)
@@ -322,8 +322,8 @@ def _serialize_field_view(
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')
if fv.get('draft_line_id'):
out['draft_line_id'] = fv.get('draft_line_id')
out['value'] = sent_value
out['value_source'] = fv.get('value_source') or 'missing_both'
if masked.get('policy') == 'masked':
@@ -457,20 +457,20 @@ def _build_v2_field_entry(
) -> 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[] +
field_entry 包含:field_id/field_code/scope/draft_line_id + 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)
draft_line_id = str(target.get('draft_line_id') or '').strip() or None
target_fv = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id)
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,
'draft_line_id': draft_line_id,
'llm_context_policy': 'allowed',
'value_source': 'missing_both',
'field_evidences': [],
@@ -481,7 +481,7 @@ def _build_v2_field_entry(
'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,
'draft_line_id': draft_line_id,
'snippets': [],
}
# snippets:摊平所有 field_evidences 的 quote/value/evidence_ref
@@ -511,11 +511,11 @@ def _build_v2_field_entry(
# [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 {}
line_fields_map = evidence_view.get('line_fields') or {} if draft_line_id else {}
line_map = (line_fields_map.get(draft_line_id) 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):
if draft_line_id and isinstance(line_map, dict):
for fid, fv in line_map.items():
if not isinstance(fv, dict):
continue
@@ -580,9 +580,9 @@ def _build_v2_field_entry(
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 反查
# 没找到 row_index:用 draft_line_id 反查
for ri, r in enumerate(rows):
if isinstance(r, dict) and str(r.get('line_key') or '') == str(line_key or ''):
if isinstance(r, dict) and str(r.get('draft_line_id') or '') == str(draft_line_id or ''):
ridx = ri
break
if ridx is not None:
@@ -607,15 +607,15 @@ def _build_v2_field_entry(
})
neighbor_rows.append({
'row_index': pos,
'line_key': r.get('line_key'),
'draft_line_id': r.get('draft_line_id'),
'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 {}
line_fields_map = (evidence_view.get('line_fields') or {}) if draft_line_id else {}
line_map = (line_fields_map.get(draft_line_id) 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):
if draft_line_id and isinstance(line_map, dict):
for fid, fv in line_map.items():
if not isinstance(fv, dict):
continue
@@ -674,10 +674,10 @@ def _build_v2_field_entry(
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 {}
line_fields_map = (evidence_view.get('line_fields') or {}) if draft_line_id else {}
line_map = (line_fields_map.get(draft_line_id) if isinstance(line_fields_map, dict) else {}) or {}
row_field_items: list[dict[str, Any]] = []
if line_key and isinstance(line_map, dict):
if draft_line_id and isinstance(line_map, dict):
for fid, fv in line_map.items():
if not isinstance(fv, dict):
continue
@@ -529,7 +529,7 @@ def build_minimal_evidence_pack_for_field(
case: ShippingOrderReviewCase,
*,
field_id: str,
line_key: str | None = None,
draft_line_id: str | None = None,
evidence_level: str = 'L1_field',
allow_full_pdf: bool = False,
) -> dict[str, Any]:
@@ -541,7 +541,7 @@ def build_minimal_evidence_pack_for_field(
Args:
case: 已加载 run 的 Review Case。
field_id: 目标 field_id。
line_key: 明细行键。
draft_line_id: 草稿明细行身份。
evidence_level: L1_field–L4_pdf。
allow_full_pdf: 管理员显式 L4。
@@ -559,7 +559,7 @@ def build_minimal_evidence_pack_for_field(
if isinstance(item, dict) and int(item.get('document_id') or 0) == int(case.document_id):
document = dict(item)
break
field_meta = {'field_id': str(field_id), 'scope': 'line' if line_key else 'header', 'line_key': line_key}
field_meta = {'field_id': str(field_id), 'scope': 'line' if draft_line_id else 'header', 'draft_line_id': draft_line_id}
return select_review_evidence_pack(
document=document,
target_fields=[field_meta],
@@ -83,7 +83,7 @@ def _normalize_observation(
case_document_id: int,
case_id: int,
field_code: str | None = None,
line_key: str | None = None,
draft_line_id: str | None = None,
derived_row_index: int | None = None,
) -> dict[str, Any]:
"""
@@ -118,7 +118,7 @@ def _normalize_observation(
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 '',
case_id=case_id, draft_line_id=draft_line_id, field_code=field_code or '',
)
confidence_raw = raw.get('confidence')
@@ -221,23 +221,22 @@ def _iter_unit_header_fields(order_result: dict[str, Any]) -> list[tuple[str, di
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)]"""
"""返回 [(draft_line_id, 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}'
draft_line_id = _safe_str(line.get('draft_line_id'))
if not draft_line_id:
draft_line_id = 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))
out.append((draft_line_id, pos, fid, field_obj))
return out
@@ -254,9 +253,9 @@ def _draft_line_list(draft) -> list[dict[str, Any]]:
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:
def _find_draft_line(lines: list[dict[str, Any]], draft_line_id: str) -> dict[str, Any] | None:
for ln in lines:
if _safe_str(ln.get('line_key')) == line_key:
if _safe_str(ln.get('draft_line_id')) == draft_line_id:
return ln
return None
@@ -301,8 +300,8 @@ def _frozen_document_snapshot(case) -> dict[str, Any]:
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。
返回 [(draft_line_id_or_header, field_id, row_index, table_id, raw_field_obj)]。
header scope 行 draft_line_id=None。
"""
out: list[tuple[str, str, int | None, str, dict[str, Any]]] = []
candidates = [
@@ -315,7 +314,7 @@ def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, st
for row_idx, row in enumerate(rows):
if not isinstance(row, dict):
continue
line_key = _safe_str(row.get('line_key'))
draft_line_id = _safe_str(row.get('draft_line_id'))
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):
@@ -323,9 +322,9 @@ def _iter_frozen_layout_fields(frozen_doc: dict[str, Any]) -> list[tuple[str, st
fid = _safe_str(raw_field.get('field_id'))
if not fid:
continue
effective_line_key = line_key
effective_draft_line_id = draft_line_id
out.append((
effective_line_key,
effective_draft_line_id,
fid,
data_row_idx,
table_id,
@@ -358,7 +357,7 @@ def _schema_fields_map(case) -> dict[str, dict[str, Any]]:
_FIELD_VIEW_KEYS = (
'field_id', 'field_code', 'display_name', 'scope',
'data_type', 'llm_context_policy',
'line_key',
'draft_line_id',
'machine_value', 'current_draft_value', 'value_source',
'primary_evidence', 'field_evidences',
)
@@ -375,7 +374,7 @@ def _build_field_view(
field_id: str,
field_metadata: dict[str, Any] | None,
scope: Literal['header', 'line'],
line_key: str | None,
draft_line_id: str | None,
case_id: int,
case_document_id: int,
) -> dict[str, Any]:
@@ -387,7 +386,7 @@ def _build_field_view(
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
view['draft_line_id'] = draft_line_id
policy = resolve_llm_context_policy(
field_metadata=md,
field_code=code,
@@ -457,9 +456,9 @@ def build_review_evidence_view(case) -> dict[str, Any]:
"diagnostics": { "unit_orders_ambiguous": bool, "context_ambiguous_reasons": [] },
"header_fields": { [field_id]: field_view },
"line_fields": {
[line_key]: { [field_id]: field_view }
[draft_line_id]: { [field_id]: field_view }
},
"lines_order": [line_key...],
"lines_order": [draft_line_id...],
"layout_schema_candidates": [frozen_candidate...], // 直接引用,不 clone
"frozen_document_snapshot": dict, // 只读
}
@@ -481,7 +480,7 @@ def build_review_evidence_view(case) -> dict[str, Any]:
def _ensure_field(
fid: str,
scope: Literal['header', 'line'],
line_key: str | None = None,
draft_line_id: str | None = None,
) -> dict[str, Any]:
if scope == 'header':
if fid not in header_fields:
@@ -489,22 +488,22 @@ def build_review_evidence_view(case) -> dict[str, Any]:
field_id=fid,
field_metadata=schema_fields.get(fid),
scope='header',
line_key=None,
draft_line_id=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]
assert draft_line_id
if draft_line_id not in line_fields:
line_fields[draft_line_id] = {}
lines_order.append(draft_line_id)
line_map = line_fields[draft_line_id]
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,
draft_line_id=draft_line_id,
case_id=case_id,
case_document_id=case_document_id,
)
@@ -540,8 +539,8 @@ def build_review_evidence_view(case) -> dict[str, Any]:
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)
for draft_line_id, _pos, fid, raw_field in _iter_unit_line_fields(order):
fv = _ensure_field(fid, 'line', draft_line_id=draft_line_id)
observations = raw_field.get('observations') or []
fc = _safe_str(raw_field.get('field_code')) or fv['field_code']
for raw_obs in observations:
@@ -553,7 +552,7 @@ def build_review_evidence_view(case) -> dict[str, Any]:
case_document_id=case_document_id,
case_id=case_id,
field_code=fc,
line_key=line_key,
draft_line_id=draft_line_id,
)
fv['field_evidences'].append(norm)
if fv['machine_value'] is None:
@@ -597,17 +596,17 @@ def build_review_evidence_view(case) -> dict[str, Any]:
# Lines
draft_lines = _draft_line_list(draft)
for line in draft_lines:
line_key = _safe_str(line.get('line_key'))
if not line_key:
draft_line_id = _safe_str(line.get('draft_line_id'))
if not draft_line_id:
continue
line_map = line_fields.setdefault(line_key, {})
if line_key not in lines_order:
lines_order.append(line_key)
line_map = line_fields.setdefault(draft_line_id, {})
if draft_line_id not in lines_order:
lines_order.append(draft_line_id)
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)
fv = _ensure_field(fid, 'line', draft_line_id=draft_line_id)
obj = _machine_field_value(line, fid)
if isinstance(obj, dict):
for raw_obs in (obj.get('observations') or []):
@@ -619,7 +618,7 @@ def build_review_evidence_view(case) -> dict[str, Any]:
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,
draft_line_id=draft_line_id,
)
fv['field_evidences'].append(norm)
if fv['machine_value'] is None and obj.get('value') is not None:
@@ -630,7 +629,7 @@ def build_review_evidence_view(case) -> dict[str, Any]:
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)
fv = _ensure_field(fid, scope=scope, draft_line_id=lk or None)
wrapped = {
'value': raw_field.get('value') or raw_field.get('quote'),
'quote': raw_field.get('quote') or raw_field.get('value'),
@@ -651,7 +650,7 @@ def build_review_evidence_view(case) -> dict[str, Any]:
case_document_id=case_document_id,
case_id=case_id,
field_code=fv['field_code'],
line_key=lk or None,
draft_line_id=lk or None,
derived_row_index=ridx,
)
fv['field_evidences'].append(norm)
@@ -683,25 +682,25 @@ def get_field_view(
view: dict[str, Any],
*,
field_id: str,
line_key: str | None,
draft_line_id: 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()
if draft_line_id:
lk = str(draft_line_id).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:
def count_valid_row_fields(view: dict[str, Any], draft_line_id: str) -> int:
"""
同行中“有值且可发送”的字段数量(evidence 有值或 machine_value/draft_value 非空)。
用于门禁:同行字段数 >= 2 才允许 L2_row。
"""
lk = str(line_key or '').strip()
lk = str(draft_line_id or '').strip()
line_map = (view.get('line_fields') or {}).get(lk) or {}
count = 0
for fv in line_map.values():
@@ -194,7 +194,7 @@ def _finding_source_options(item: dict[str, Any]) -> list[dict[str, Any]]:
return options
def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None:
def _draft_line_id_for_index(case: ShippingOrderReviewCase, line_index: int) -> str | None:
"""按 line_index 定位 Draft 行键;优先显式 line_index,否则按顺序。"""
draft = case.current_draft
if draft is None:
@@ -206,12 +206,12 @@ def _line_key_for_index(case: ShippingOrderReviewCase, line_index: int) -> str |
raw_idx = raw.get('line_index')
try:
if raw_idx is not None and int(raw_idx) == int(line_index):
key = str(raw.get('line_key') or '').strip()
key = str(raw.get('draft_line_id') or '').strip()
return key or None
except (TypeError, ValueError):
pass
if idx == int(line_index):
key = str(raw.get('line_key') or '').strip()
key = str(raw.get('draft_line_id') or '').strip()
return key or None
return None
@@ -322,12 +322,12 @@ def _project_review_case_candidate_findings(case: ShippingOrderReviewCase) -> tu
)
for key in value_keys
]
line_key = _line_key_for_index(case, line_index) if line_index >= 0 else None
draft_line_id = _draft_line_id_for_index(case, line_index) if line_index >= 0 else None
finding = {
'conflict_key': _stored_conflict_key(item),
'field_code': field,
'line_index': line_index if line_index >= 0 else None,
'line_key': line_key,
'draft_line_id': draft_line_id,
'scope': str(item.get('scope') or _finding_scope(case, field_code=field, line_index=line_index)),
'severity': str(item.get('severity') or 'blocking'),
'reason': reason,
@@ -473,10 +473,10 @@ def resolve_review_case_field_conflict(
header = dict(case.current_draft.header_values_json or {})
change = _set_value(header, field, chosen_display, restore_machine=False)
case.current_draft.header_values_json = header
line_key = None
draft_line_id = None
else:
line_key = _line_key_for_index(case, line_index)
if not line_key:
draft_line_id = _draft_line_id_for_index(case, line_index)
if not draft_line_id:
raise ConflictError(
'Conflict line is missing from draft',
code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING',
@@ -486,14 +486,14 @@ def resolve_review_case_field_conflict(
lines = list(case.current_draft.lines_json or [])
target_line = None
for raw in lines:
if isinstance(raw, dict) and str(raw.get('line_key') or '') == line_key:
if isinstance(raw, dict) and str(raw.get('draft_line_id') or '') == draft_line_id:
target_line = raw
break
if target_line is None:
raise ConflictError(
'Conflict line is missing from draft',
code='SHIPPING.REVIEW_FIELD_CONFLICT_LINE_MISSING',
details={'line_key': line_key},
details={'draft_line_id': draft_line_id},
)
change = _set_value(target_line, field, chosen_display, restore_machine=False)
case.current_draft.lines_json = lines
@@ -514,7 +514,7 @@ def resolve_review_case_field_conflict(
operation={
'conflict_key': conflict_key,
'field_code': field_code,
'line_key': line_key,
'draft_line_id': draft_line_id,
'resolution': mode,
'option_index': option_index,
'chosen_value': chosen_display,
@@ -27,6 +27,7 @@ from app.models import (
ShippingOrderReviewLineDecision,
ShippingOrderReviewWaveLine,
ShippingNotice,
ShippingOrderTask,
ShippingTaskInventoryRpaAttempt,
)
from app.services.shipping_notice.workflow_ledger_service import (
@@ -236,15 +237,16 @@ def _release_fact_identity(fact: dict[str, Any] | None) -> tuple[int | None, int
def _resolve_shortage_release_inventory_source(
*,
fact_source_code: Any,
task_source_code: Any,
snapshot_source_code: Any,
candidate_source_codes: set[str] | None = None,
) -> str | None:
"""按行事实、OT、快照顺序恢复短缺放行所需的库存源。"""
for value in (fact_source_code, task_source_code, snapshot_source_code):
"""按行事实、库存文件、唯一冻结候选源顺序恢复短缺放行所需的库存源。"""
for value in (fact_source_code, snapshot_source_code):
normalized = str(value or '').strip().upper()
if normalized:
return normalized
return None
codes = candidate_source_codes or set()
return next(iter(codes)) if len(codes) == 1 else None
def _is_shortage_match_fact(fact: Any) -> bool:
@@ -285,9 +287,6 @@ def _has_terminal_inventory_rpa_failure(
source_codes = {str(item or '').strip().upper() for item in task_frozen_inventory_source_codes(task)}
except Exception: # noqa: BLE001 - 放行资格宁可拒绝,不能因冻结读取异常绕过。
source_codes = set()
source_code = str(getattr(task, 'inventory_source_code', '') or '').strip().upper()
if source_code:
source_codes.add(source_code)
rows = attempts if attempts is not None else (
ShippingTaskInventoryRpaAttempt.query
.filter_by(task_no=task_no)
@@ -326,15 +325,21 @@ def _shortage_release_required_fields(
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
)
snapshot = db.session.get(ShippingInventoryFile, int(inventory_snapshot_id)) if inventory_snapshot_id is not None else None
if inventory_snapshot_id is not None and (snapshot is None or not isinstance(snapshot.inventory_lines_json, list)):
if inventory_snapshot_id is not None and snapshot is None:
raise ConflictError(
'Current inventory snapshot is unavailable',
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
)
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
resolved_source_code = _resolve_shortage_release_inventory_source(
fact_source_code=inventory_source_code,
task_source_code=getattr(task, 'inventory_source_code', None),
snapshot_source_code=getattr(snapshot, 'source_code', None) if snapshot is not None else None,
candidate_source_codes={
str(code or '').strip().upper()
for code in task_frozen_inventory_source_codes(task)
if str(code or '').strip()
},
)
if not resolved_source_code:
raise ConflictError(
@@ -366,7 +371,7 @@ def _shortage_release_required_fields(
and str(item.get('source_key') or '').strip().isdigit()
}
labels = {str(row.id): str(row.display_name or '').strip() for row in ShippingInventoryField.query.filter(ShippingInventoryField.id.in_(field_ids)).all()} if field_ids else {}
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels) + _release_template_system_fields(mappings=mappings, warehouse_id=getattr(task, 'inventory_warehouse_id', None))
return _release_template_inventory_fields(mappings=mappings, candidates=[], field_labels=labels)
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
match_keys = definition.get('match_keys') if isinstance(definition.get('match_keys'), list) else []
expected = [
@@ -378,9 +383,17 @@ def _shortage_release_required_fields(
'Inventory matching keys are unavailable',
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
)
from app.services.shipping_notice.inventory_file_store import read_inventory_file_lines
try:
inventory_lines, _column_meta = read_inventory_file_lines(snapshot)
except (OSError, ValueError, AppError) as exc:
raise ConflictError(
'Current inventory snapshot is unavailable',
code='SHIPPING.REVIEW_LINE_RELEASE_EVIDENCE_REQUIRED',
) from exc
candidates = [
dict(row) for row in snapshot.inventory_lines_json if isinstance(row, dict)
and all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
dict(row) for row in inventory_lines
if all(_match_text(row.get(inventory_field)) == value for inventory_field, value in expected)
]
field_ids = {
int(str(item.get('source_key') or '').strip())
@@ -398,9 +411,6 @@ def _shortage_release_required_fields(
mappings=mappings,
candidates=candidates,
field_labels=labels,
) + _release_template_system_fields(
mappings=mappings,
warehouse_id=getattr(task, 'inventory_warehouse_id', None),
)
@@ -426,7 +436,7 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
task_id = getattr(case, 'confirmed_task_id', None)
if task_id is None:
return
task = db.session.get(ShippingNotice, int(task_id))
task = db.session.get(ShippingOrderTask, int(task_id))
if task is None:
return
# [BE-释放-重算] 放行是库存充分性 Gate 的受控业务事实:必须先把任务级履约态
@@ -556,7 +566,7 @@ def _assess_line_fulfill_complete(
def _assert_line_can_fulfill_complete(
*,
line_key: str,
draft_line_id: str,
draft_line: dict[str, Any],
proj: dict[str, Any],
schema_fields: dict[str, dict[str, Any]] | None = None,
@@ -576,13 +586,13 @@ def _assert_line_can_fulfill_complete(
raise ConflictError(
'Line cannot fulfill complete quantity with current inventory',
code=str(code or 'SHIPPING.REVIEW_LINE_INSUFFICIENT_INVENTORY'),
details={'line_key': line_key},
details={'draft_line_id': draft_line_id},
)
return req, avail
def _draft_line_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
"""line_key → 草稿行。"""
"""draft_line_id → 草稿行。"""
draft = case.current_draft
if draft is None:
return {}
@@ -590,16 +600,16 @@ def _draft_line_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
for idx, line in enumerate(list(draft.lines_json or [])):
if not isinstance(line, dict):
continue
key = str(line.get('line_key') or '').strip() or f'line-{idx + 1}'
key = str(line.get('draft_line_id') or '').strip() or f'line-{idx + 1}'
row = dict(line)
row['_line_index'] = idx
row['_line_key'] = key
row['_draft_line_id'] = key
out[key] = row
return out
def _line_projection_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, Any]]:
"""line_key → eligibility line projection。"""
"""draft_line_id → eligibility line projection。"""
draft = case.current_draft
if draft is None:
return {}
@@ -608,29 +618,29 @@ def _line_projection_map(case: ShippingOrderReviewCase) -> dict[str, dict[str, A
for idx, item in enumerate(list(validation.get('line_projections') or [])):
if not isinstance(item, dict):
continue
key = str(item.get('line_key') or '').strip() or f'line-{idx + 1}'
key = str(item.get('draft_line_id') or '').strip() or f'line-{idx + 1}'
out[key] = dict(item)
return out
def _active_decision(
case: ShippingOrderReviewCase,
line_key: str,
draft_line_id: str,
) -> ShippingOrderReviewLineDecision | None:
"""取某行当前活动决定。"""
return (
ShippingOrderReviewLineDecision.query
.filter_by(review_case_id=int(case.id), line_key=str(line_key), is_active=True)
.filter_by(review_case_id=int(case.id), draft_line_id=str(draft_line_id), is_active=True)
.order_by(ShippingOrderReviewLineDecision.decision_version.desc())
.first()
)
def _next_version(case: ShippingOrderReviewCase, line_key: str) -> int:
def _next_version(case: ShippingOrderReviewCase, draft_line_id: str) -> int:
"""下一决定版本号。"""
latest = (
ShippingOrderReviewLineDecision.query
.filter_by(review_case_id=int(case.id), line_key=str(line_key))
.filter_by(review_case_id=int(case.id), draft_line_id=str(draft_line_id))
.order_by(ShippingOrderReviewLineDecision.decision_version.desc())
.first()
)
@@ -641,7 +651,7 @@ def _serialize_decision(row: ShippingOrderReviewLineDecision) -> dict[str, Any]:
"""用户态决定投影。"""
return {
'id': int(row.id),
'line_key': row.line_key,
'draft_line_id': row.draft_line_id,
'line_index': row.line_index,
'decision_version': int(row.decision_version),
'decision_code': row.decision_code,
@@ -766,44 +776,33 @@ 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
task = formal_ot.get('task') if isinstance(formal_ot.get('task'), ShippingOrderTask) else None
if task is None and getattr(case, 'confirmed_task_id', None) is not None:
task = db.session.get(ShippingNotice, int(case.confirmed_task_id))
task = db.session.get(ShippingOrderTask, int(case.confirmed_task_id))
rpa_failure_release_allowed = bool(task is not None and _has_terminal_inventory_rpa_failure(task))
# [STEP] 构造 Task 级库存源回退事实(行级匹配缺失时兜底,仅影响展示)
# 优先级:行级 inventory_source_code > Task resolved 正式源 > candidates_frozen > resolving
# [STEP] 构造 CandidateSet 回退事实(行级匹配缺失时仅影响展示)。
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 == 'resolved':
frozen_codes = task_frozen_inventory_source_codes(task)
if len(frozen_codes) == 1:
fallback_inventory_source = {
'code': task_source_code,
'code': frozen_codes[0],
'label': None,
'status': 'resolved',
'source': 'task_inventory_source',
'source': 'frozen_inventory_candidates',
}
elif frozen_codes:
fallback_inventory_source = {
'code': None,
'label': None,
'status': 'candidates_frozen',
'candidates': list(frozen_codes),
'source': 'frozen_inventory_candidates',
}
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,
@@ -825,10 +824,10 @@ def project_review_case_line_decisions(
active_rows = (
ShippingOrderReviewLineDecision.query
.filter_by(review_case_id=int(case.id), is_active=True)
.order_by(ShippingOrderReviewLineDecision.line_key.asc())
.order_by(ShippingOrderReviewLineDecision.draft_line_id.asc())
.all()
)
by_key = {str(row.line_key): row for row in active_rows}
by_key = {str(row.draft_line_id): row for row in active_rows}
lines_out: list[dict[str, Any]] = []
for key, draft_line in draft_lines.items():
@@ -909,8 +908,6 @@ def project_review_case_line_decisions(
release_line_index, release_snapshot_id, release_source_code = _release_fact_identity(fact)
if release_line_index is None:
release_line_index = draft_line.get('_line_index')
if not release_source_code:
release_source_code = getattr(task, 'inventory_source_code', None)
release_template_fields = _shortage_release_required_fields(
task=task,
line_index=release_line_index,
@@ -925,7 +922,7 @@ def project_review_case_line_decisions(
available = inv_view.get('available_qty')
shortage = inv_view.get('shortage_qty')
lines_out.append({
'line_key': key,
'draft_line_id': key,
'line_index': draft_line.get('_line_index'),
'reservation_id': _line_reservation_id(draft_line, proj),
'part_number': _line_part_number(
@@ -1067,7 +1064,7 @@ def decide_review_line_fulfillment(
*,
user_id: int,
case_no: str,
line_key: str,
draft_line_id: str,
decision_code: str,
reason: str | None = None,
release_field_values: dict[str, Any] | None = None,
@@ -1084,7 +1081,7 @@ def decide_review_line_fulfillment(
Args:
user_id: 操作人。
case_no: Case 编号。
line_key: 草稿行键。
draft_line_id: 草稿行键。
decision_code: 决定码。
reason: 关闭/重开/短缺放行必填原因。
release_field_values: 短缺放行时模板行级库存字段的人工补录值。
@@ -1118,7 +1115,7 @@ def decide_review_line_fulfillment(
)
lines = _draft_line_map(case)
key = str(line_key or '').strip()
key = str(draft_line_id or '').strip()
if key not in lines:
raise NotFoundError('Review line not found', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
@@ -1128,20 +1125,20 @@ def decide_review_line_fulfillment(
raise ConflictError(
'Line already fulfilled in a task wave',
code='SHIPPING.REVIEW_LINE_ALREADY_IN_TASK',
details={'line_key': key, 'line_status': current.line_status},
details={'draft_line_id': key, 'line_status': current.line_status},
)
if code == DECISION_REOPEN:
if current is None or current.line_status != 'closed_unfulfillable':
raise ConflictError(
'Only closed_unfulfillable lines can be reopened',
code='SHIPPING.REVIEW_LINE_REOPEN_NOT_ALLOWED',
details={'line_key': key},
details={'draft_line_id': key},
)
if not actor_is_admin:
raise ConflictError(
'Reopen requires admin',
code='SHIPPING.REVIEW_LINE_REOPEN_FORBIDDEN',
details={'line_key': key},
details={'draft_line_id': key},
)
elif current is not None and current.line_status == 'closed_unfulfillable':
raise ConflictError(
@@ -1161,7 +1158,7 @@ def decide_review_line_fulfillment(
avail_qty = _parse_qty(proj.get('available_qty'))
if code == DECISION_FULFILL:
req_qty, avail_qty = _assert_line_can_fulfill_complete(
line_key=key,
draft_line_id=key,
draft_line=draft_line,
proj=proj,
schema_fields=schema_fields,
@@ -1170,10 +1167,10 @@ def decide_review_line_fulfillment(
from app.models import ShippingNoticeLineInventoryMatch
task_id = getattr(case, 'confirmed_task_id', None)
task = db.session.get(ShippingNotice, int(task_id)) if task_id is not None else None
task = db.session.get(ShippingOrderTask, int(task_id)) if task_id is not None else None
fact = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), line_key=key, is_current=True)
.filter_by(task_id=int(task.id), line_index=int(draft_line.get('_line_index')), is_current=True)
.first()
if task is not None else None
)
@@ -1182,25 +1179,20 @@ def decide_review_line_fulfillment(
raise ConflictError(
'Only shortage lines can be released',
code='SHIPPING.REVIEW_LINE_RELEASE_NOT_ALLOWED',
details={'line_key': key},
details={'draft_line_id': key},
)
release_line_index = getattr(fact, 'line_index', None) if fact is not None else draft_line.get('_line_index')
release_template_fields = _shortage_release_required_fields(
task=task,
line_index=release_line_index,
inventory_snapshot_id=getattr(fact, 'inventory_snapshot_id', None) if fact is not None else None,
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else getattr(task, 'inventory_source_code', None),
inventory_source_code=getattr(fact, 'inventory_source_code', None) if fact is not None else None,
) if task is not None else []
release_required_fields = _manual_required_release_fields(release_template_fields)
release_values = _validate_inventory_shortage_release_fields(
required_fields=release_required_fields,
supplied_values=release_field_values or {},
)
supplied_warehouse_id = str(release_values.get('system_fact:warehouse_id') or '').strip().upper()
if supplied_warehouse_id:
# Header Warehouse ID 是动态库存源导出的任务级系统事实;人工放行时必须
# 显式固化,供后续 Excel 生成消费,并同时保留在决定快照中审计。
task.inventory_warehouse_id = supplied_warehouse_id
else:
release_required_fields = []
release_values = {}
@@ -1213,7 +1205,7 @@ def decide_review_line_fulfillment(
status = _STATUS_BY_DECISION.get(code, 'pending_decision')
row = ShippingOrderReviewLineDecision(
review_case_id=int(case.id),
line_key=key,
draft_line_id=key,
line_index=draft_line.get('_line_index'),
decision_version=_next_version(case, key),
decision_code=code,
@@ -1237,7 +1229,7 @@ def decide_review_line_fulfillment(
'decision_source': 'user',
'required_qty': str(req_qty) if req_qty is not None else None,
'available_qty': str(avail_qty) if avail_qty is not None else None,
'line_key': key,
'draft_line_id': key,
'release_field_values': release_values,
'release_required_fields': release_required_fields,
},
@@ -1262,7 +1254,7 @@ def decide_review_line_fulfillment(
review_case_no=str(case.case_no),
run_no=str(case.run.run_no) if case.run is not None else None,
metadata={
'line_key': key,
'draft_line_id': key,
'decision_code': code,
'decision_version': int(row.decision_version),
'line_status': status,
@@ -1301,7 +1293,7 @@ def close_remaining_fulfillment(
user_id: int,
case_no: str,
reason: str,
line_keys: list[str] | None = None,
draft_line_ids: list[str] | None = None,
expected_draft_version: Any = None,
actor_is_admin: bool = False,
) -> dict[str, Any]:
@@ -1312,7 +1304,7 @@ def close_remaining_fulfillment(
user_id: 操作人。
case_no: Case 编号。
reason: 强制原因。
line_keys: 指定行;为空则关闭全部开放行。
draft_line_ids: 指定行;为空则关闭全部开放行。
expected_draft_version: 可选草稿版本。
actor_is_admin: 透传给 decide(关闭本身不要求管理员)。
@@ -1326,10 +1318,10 @@ def close_remaining_fulfillment(
)
case = _load_writable_case(user_id=user_id, case_no=case_no)
projection = project_review_case_line_decisions(case)
targets = list(line_keys or [])
targets = list(draft_line_ids or [])
if not targets:
targets = [
str(item['line_key'])
str(item['draft_line_id'])
for item in projection.get('lines') or []
if item.get('line_status') not in _TERMINAL_ACTIVE
]
@@ -1338,7 +1330,7 @@ def close_remaining_fulfillment(
last = decide_review_line_fulfillment(
user_id=user_id,
case_no=case_no,
line_key=key,
draft_line_id=key,
decision_code=DECISION_CLOSE,
reason=reason,
expected_draft_version=expected_draft_version,
@@ -145,14 +145,14 @@ def _check_table_duplicate_value(
evidence_view: dict[str, Any],
*,
field_id: str,
line_key: str | None,
draft_line_id: str | None,
field_view_obj: dict[str, Any],
) -> bool:
"""
[Priority 4] Line scope:同一 table 中多个行存在与目标字段相同的 value。
Header scope:此检测跳过(不适用)。目标 value 为空时跳过。
"""
if not line_key:
if not draft_line_id:
return False
if not isinstance(evidence_view, dict):
return False
@@ -169,7 +169,7 @@ def _check_table_duplicate_value(
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):
if lk == str(draft_line_id) or not isinstance(lf_map, dict):
continue
fv = lf_map.get(str(field_id))
if not isinstance(fv, dict):
@@ -206,16 +206,16 @@ def _check_manual_conflict(field_view: dict[str, Any]) -> bool:
def _check_context_borderline(
evidence_view: dict[str, Any],
*,
line_key: str | None,
draft_line_id: str | None,
) -> bool:
"""
[Priority 6] Line scope 同行有效字段数正好 = 门禁最低阈值(2)。
处于门禁临界线,证据不稳,升级到表格更安全。Header scope 跳过。
"""
if not line_key:
if not draft_line_id:
return False
try:
siblings = count_valid_row_fields(evidence_view, str(line_key))
siblings = count_valid_row_fields(evidence_view, str(draft_line_id))
except Exception:
return False
return siblings == _BORDERLINE_SIBLING_COUNT
@@ -224,20 +224,20 @@ def _check_context_borderline(
def _check_context_identity_insufficient(
evidence_view: dict[str, Any],
*,
line_key: str | None,
draft_line_id: str | None,
field_view_obj: dict[str, Any],
) -> bool:
"""
[Priority 7] Line scope:同行缺少明确身份标识字段(如 part_number / line_no),
或目标字段 primary_evidence.confidence 低于阈值。
"""
if not line_key:
if not draft_line_id:
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
lf = line_fields.get(str(draft_line_id)) if isinstance(line_fields, dict) else None
has_identity = False
if isinstance(lf, dict):
for fid, fv in lf.items():
@@ -276,7 +276,7 @@ def resolve_auto_upgrade_level(
*,
evidence_view: dict[str, Any],
field_id: str,
line_key: str | None,
draft_line_id: str | None,
requested_level: EvidenceLevelV2,
schema_field_meta: dict[str, Any] | None = None,
issue_code: str | None = None,
@@ -287,7 +287,7 @@ def resolve_auto_upgrade_level(
Args:
evidence_view: build_review_evidence_view() 的返回。
field_id: 目标字段 ID。
line_key: 目标行键;None 表示 header scope。
draft_line_id: 目标草稿行身份;None 表示 header scope。
requested_level: 用户/前端请求的等级(默认 L2_row)。
schema_field_meta: schema.definition_json.fields[] 中的原始元数据。
issue_code: 前端透传的冲突 issue_code(触发 P1)。
@@ -301,7 +301,7 @@ def resolve_auto_upgrade_level(
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)
field_view = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id)
if field_view is None:
return requested_level, None, []
@@ -313,7 +313,7 @@ def resolve_auto_upgrade_level(
if str(requested_level) not in {'L1_field', 'L2_row'}:
return requested_level, None, []
scope_is_line = bool(line_key)
scope_is_line = bool(draft_line_id)
reasons_hit: list[str] = []
# [STEP 1] 按优先级顺序跑 7 项检测,命中即追加
@@ -326,17 +326,17 @@ def resolve_auto_upgrade_level(
if _check_table_duplicate_value(
evidence_view,
field_id=field_id,
line_key=line_key,
draft_line_id=draft_line_id,
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):
if _check_context_borderline(evidence_view, draft_line_id=draft_line_id):
reasons_hit.append('context_borderline')
if _check_context_identity_insufficient(
evidence_view,
line_key=line_key,
draft_line_id=draft_line_id,
field_view_obj=field_view,
):
reasons_hit.append('context_identity_insufficient')
@@ -180,9 +180,9 @@ def is_valid_provenance_ref(value: Any) -> bool:
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:
def build_provenance_ref(*, case_id: int, draft_line_id: str | None, field_code: str) -> str:
"""生成 Draft 回退专用的 provenance_ref(不伪装成 evidence_ref)。"""
line = str(line_key or 'header').strip() or 'header'
line = str(draft_line_id or 'header').strip() or 'header'
return f'draft:case-{int(case_id)}:line-{line}:field-{str(field_code).strip()}'
# ---------------------------------------------------------------------------
@@ -231,10 +231,10 @@ class V2Target(TypedDict, total=False):
field_id: str
field_code: str
scope: Literal['header', 'line']
line_key: str | None
draft_line_id: str | None
class V2RowContext(TypedDict, total=False):
line_key: str
draft_line_id: 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):
@@ -243,7 +243,7 @@ class V2TableContext(TypedDict, total=False):
target_row_index: int | None
class V2NeighborRow(TypedDict, total=False):
line_key: str
draft_line_id: str
row_index: int
fields: list[dict[str, Any]]
position: Literal['preceding', 'following']
@@ -347,7 +347,7 @@ def build_suggestion_request_envelope(
return envelope
# ---------------------------------------------------------------------------
# 响应解析(v1/v2 统一出口,line_key/scope/needs_review v2 新增)
# 响应解析(v1/v2 统一出口,draft_line_id/scope/needs_review v2 新增)
# ---------------------------------------------------------------------------
def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]]:
"""
@@ -371,10 +371,10 @@ def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]
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
draft_line_id_raw = item.get('draft_line_id')
draft_line_id = str(draft_line_id_raw).strip() if draft_line_id_raw is not None else None
if not draft_line_id:
draft_line_id = None
scope = str(item.get('scope') or '').strip().lower()
if scope not in {'header', 'line'}:
scope = 'line'
@@ -387,7 +387,7 @@ def parse_suggestion_response(raw: dict[str, Any] | None) -> list[dict[str, Any]
'field_id': field_id,
'field_code': str(item.get('field_code') or '').strip() or None,
'scope': scope,
'line_key': line_key,
'draft_line_id': draft_line_id,
'suggested_value': item.get('suggested_value'),
'quote': str(item.get('quote') or item.get('suggested_value') or '')[:1000],
'confidence': confidence,
@@ -9,7 +9,7 @@ services/shipping_notice/order_review_llm_gate.py
- order_review_llm_policy_registry.resolve_llm_context_policy
逻辑:
[1] field_not_found 目标 field_id 在 schema 中不存在
[2] line_not_found 目标 line_key 在视图中行找不到
[2] line_not_found 目标 draft_line_id 在视图中行找不到
[3] field_value_missing 目标字段 machine/draft/primary_evidence 三者全空
[4] evidence_unavailable 目标字段无任何 field_evidences[](三源都没有事实)
[5] context_ambiguous unit orders >1 且无法按 primary_document_id 唯一确定
@@ -57,7 +57,7 @@ def run_preflight_gate(
evidence_view: dict[str, Any],
*,
field_id: str,
line_key: str | None,
draft_line_id: str | None,
requested_level: EvidenceLevelV2 | None,
schema_field_meta: dict[str, Any] | None = None,
) -> GateResult:
@@ -77,15 +77,15 @@ def run_preflight_gate(
return False, 'context_ambiguous', \
'; '.join(str(r) for r in ambiguous_reasons)
# [2] line scope 需要 line_key 存在
scope_is_line = bool(line_key)
# [2] line scope 需要 draft_line_id 存在
scope_is_line = bool(draft_line_id)
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}'
if str(draft_line_id) not in line_fields:
return False, 'line_not_found', f'draft_line_id={draft_line_id}'
# [1] field_id 找不到(header/line 都没命中)
field_view = get_field_view(evidence_view, field_id=field_id, line_key=line_key)
field_view = get_field_view(evidence_view, field_id=field_id, draft_line_id=draft_line_id)
if field_view is None:
return False, 'field_not_found', f'field_id={field_id}'
@@ -127,10 +127,10 @@ def run_preflight_gate(
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))
siblings = count_valid_row_fields(evidence_view, str(draft_line_id))
if siblings < _MIN_LINE_SIBLINGS:
return False, 'context_insufficient', \
f'line_key={line_key} valid siblings={siblings} required>={_MIN_LINE_SIBLINGS}'
f'draft_line_id={draft_line_id} valid siblings={siblings} required>={_MIN_LINE_SIBLINGS}'
return True, None, None
@@ -117,7 +117,7 @@ def _audit_llm_suggestion(
"""
after_payload = {
'field_id': suggestion.field_id,
'line_key': suggestion.line_key,
'draft_line_id': suggestion.draft_line_id,
'status': suggestion.status,
'decision': suggestion.decision,
**(after or {}),
@@ -242,7 +242,7 @@ def serialize_suggestion(
base: dict[str, Any] = {
'suggestion_no': row.suggestion_no,
'field_id': row.field_id,
'line_key': row.line_key,
'draft_line_id': row.draft_line_id,
'scope': row.scope,
'evidence_level': row.evidence_level,
'contract_version': row.contract_version,
@@ -289,7 +289,7 @@ def serialize_suggestion(
'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),
'draft_line_id': (i.get('draft_line_id') if isinstance(i, dict) else None),
}
for i in tf if isinstance(i, dict)
][:50]
@@ -368,7 +368,7 @@ def request_field_suggestion(
user_id: int,
case_no: str,
field_id: str,
line_key: str | None = None,
draft_line_id: str | None = None,
evidence_level: str | None = None,
issue_code: str | None = None,
allow_full_pdf: bool = False,
@@ -381,7 +381,7 @@ def request_field_suggestion(
user_id: Case 属主。
case_no: 复核 Case 编号。
field_id: 目标 field_id。
line_key: 明细行键。
draft_line_id: 草稿行身份。
evidence_level: L1_field–L4_pdf。
issue_code: 关联 issue。
allow_full_pdf: 管理员显式 L4。
@@ -396,8 +396,8 @@ def request_field_suggestion(
field = _schema_field(case, field_id)
scope = str(field.get('scope') or 'header')
if scope == 'line' and not line_key:
raise ValidationError('line_key is required for line scope', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
if scope == 'line' and not draft_line_id:
raise ValidationError('draft_line_id is required for line scope', code='SHIPPING.REVIEW_LINE_NOT_FOUND')
level_raw = _normalize_level(evidence_level or 'L1_field')
if level_raw == 'L4_pdf' and not (is_admin and allow_full_pdf):
@@ -409,7 +409,7 @@ def request_field_suggestion(
'field_id': str(field_id),
'field_code': str(field.get('field_code') or field_id),
'scope': scope,
'line_key': line_key,
'draft_line_id': draft_line_id,
'line_number': None,
}]
row = ShippingOrderReviewSuggestion(
@@ -418,7 +418,7 @@ def request_field_suggestion(
document_id=int(case.document_id),
run_id=int(case.run_id) if case.run_id else None,
field_id=str(field_id),
line_key=str(line_key) if line_key else None,
draft_line_id=str(draft_line_id) if draft_line_id else None,
scope=scope,
evidence_level=level,
status='pending',
@@ -454,7 +454,7 @@ def request_field_suggestion(
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,
draft_line_id=str(draft_line_id) if draft_line_id else None,
requested_level=level, # type: ignore[arg-type]
schema_field_meta=field,
issue_code=issue_code,
@@ -488,15 +488,15 @@ def request_field_suggestion(
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,
draft_line_id=str(draft_line_id) if draft_line_id else None,
requested_level=level, # type: ignore[arg-type]
schema_field_meta=field,
)
# 填充观测列(gated 或未 gated 都写,便于对账 context_hash)
_evidence_view_count = 0
if line_key:
if draft_line_id:
line_map = (evidence_view or {}).get('line_fields') or {}
row_map = line_map.get(str(line_key)) or {}
row_map = line_map.get(str(draft_line_id)) or {}
target_view = row_map.get(str(field_id))
else:
header_map = (evidence_view or {}).get('header_fields') or {}
@@ -617,7 +617,7 @@ def request_field_suggestion(
'field_id': str(field_id),
'field_code': str(field.get('field_code') or field_id),
'scope': scope,
'line_key': line_key,
'draft_line_id': draft_line_id,
},
expected_target_field_id=str(field_id),
auto_upgrade_reason=_auto_upgrade_reason,
@@ -631,7 +631,7 @@ def request_field_suggestion(
'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,
'draft_line_id': draft_line_id,
'contract_version': LLM_REVIEW_CONTRACT_VERSION,
'evidence_level': level,
'target_fields': target_fields,
@@ -781,7 +781,7 @@ def request_field_suggestion(
evidence_pack=evidence_pack,
envelope=request_payload,
expected_target_field_id=str(field_id),
expected_line_key=line_key,
expected_draft_line_id=draft_line_id,
expected_scope=scope,
)
row.validated_suggestions_json = validated
@@ -827,7 +827,7 @@ def request_field_suggestion(
user_id=user_id,
case_no=case_no,
field_id=str(field_id),
line_key=line_key,
draft_line_id=draft_line_id,
value=value,
suggestion_no=row.suggestion_no,
expected_draft_version=int(case.current_draft.draft_version),
@@ -914,7 +914,7 @@ def decide_suggestion(
before_status = {
'status': suggestion.status,
'field_id': suggestion.field_id,
'line_key': suggestion.line_key,
'draft_line_id': suggestion.draft_line_id,
}
case_payload = adjudicate_llm_suggestion_on_draft(
user_id=user_id,
@@ -5,15 +5,15 @@ services/shipping_notice/order_review_llm_validation.py
任何一项未通过 → 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}]
- request_payload.envelope:target / expected_target_field_id / evidence[] / draft_line_id 定位
- 响应解析层:parse_suggestion_response 输出 [{field_id, draft_line_id, 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(头部不能带行键)
2. header_scope_has_draft_line_id scope=header 时 draft_line_id 不为 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(精确相等)
5. draft_line_id_mismatch scope=line 时响应 draft_line_id != 请求值(精确相等)
6. value_not_in_evidence suggested_value 不在 evidence[] 任何 value/quote(normalize 后)
7. quote_consistency 响应 quote normalize 后与 suggested_value quote 不构成 substring 或
完整相等;即使值存在也视为伪造
@@ -38,10 +38,10 @@ from app.services.shipping_notice.order_review_llm_contract import (
# ---------------------------------------------------------------------------
_VALIDATION_CHECKS_ORDER: Final[tuple[str, ...]] = (
'json_schema_invalid',
'header_scope_has_line_key',
'header_scope_has_draft_line_id',
'non_target_field',
'field_id_mismatch',
'line_key_mismatch',
'draft_line_id_mismatch',
'value_not_in_evidence',
'quote_consistency',
'guess_without_evidence',
@@ -55,7 +55,7 @@ def _collect_evidence_values(
"""
从 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}
每项返回 {value_norm, quote_norm, value_raw, quote_raw, field_id, draft_line_id, evidence_ref}
"""
pool: list[dict[str, Any]] = []
env = envelope if isinstance(envelope, dict) else {}
@@ -72,7 +72,7 @@ def _collect_evidence_values(
'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,
'draft_line_id': str(ev.get('draft_line_id') or '').strip() or None,
'evidence_ref': ev.get('evidence_ref'),
})
return pool
@@ -82,7 +82,7 @@ def _collect_evidence_values(
if not isinstance(f, dict):
continue
fid = str(f.get('field_id') or '')
lk = str(f.get('line_key') or '').strip() or None
draft_line_id = str(f.get('draft_line_id') or '').strip() or None
for sn in (f.get('snippets') or []):
if not isinstance(sn, dict):
continue
@@ -94,44 +94,56 @@ def _collect_evidence_values(
'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,
'draft_line_id': draft_line_id,
'evidence_ref': sn.get('evidence_ref'),
})
return pool
def _is_pure_numeric(value: str) -> bool:
"""判定某值是否为纯数字(可含正负号/小数点)。纯数字的子串匹配无意义(如 '10' 命中 '100'),
会放行数量失真/幻觉,因此纯数字值只允许精确匹配,禁用子串匹配。"""
if not value:
return False
stripped = value.strip().lstrip('+-')
if not stripped:
return False
return stripped.replace('.', '', 1).isdigit() and any(ch.isdigit() for ch in stripped)
def _find_value_match(
pool: list[dict[str, Any]],
*,
value_norm: str,
quote_norm_provided: str,
field_id: str,
line_key: str | None,
draft_line_id: 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;最后全局任意项。
同池内优先匹配 field_id + draft_line_id 双重身份的项;其次 field_id;最后全局任意项。
"""
if not value_norm and not quote_norm_provided:
return '', None
# 身份过滤:先 field_id + line_key
# 身份过滤:先 field_id + draft_line_id
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'))
and (str(p.get('draft_line_id') or '') == str(draft_line_id or '')
if draft_line_id else not p.get('draft_line_id'))
]
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:
# 字段隔离:只允许用同 field_id 的证据验证当前字段建议,
# 禁止用其它字段(others)的证据兜底,避免跨字段误判(fail-closed)。
for p in same_identity + same_field:
yield p
# 1. exact:raw 完全相等
@@ -142,12 +154,12 @@ def _find_value_match(
if (vr and vr == needle) or (qr and qr == needle):
return 'exact', p
# 2. exact_substring:raw 内 substring
# 2. exact_substring:raw 内 substring(纯数字禁用子串,防止 '10' 误命中 '100')
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:
if not needle or _is_pure_numeric(needle):
continue
if (vr and needle in vr) or (qr and needle in qr):
return 'exact_substring', p
@@ -159,11 +171,11 @@ def _find_value_match(
if (vn and vn == value_norm) or (qn and qn == value_norm):
return 'normalized', p
# 4. normalized_substring:norm 内 substring
# 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:
if not value_norm or _is_pure_numeric(value_norm):
continue
if (vn and value_norm in vn) or (qn and value_norm in qn):
return 'normalized_substring', p
@@ -225,7 +237,7 @@ def validate_suggestions_against_evidence(
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_draft_line_id: str | None = None,
expected_scope: str | None = None,
) -> list[dict[str, Any]]:
"""
@@ -236,7 +248,7 @@ def validate_suggestions_against_evidence(
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_draft_line_id: 期望草稿行身份(行 scope 用;header scope 传 None)。
expected_scope: 'header' / 'line'(从 schema_field_meta.scope 兜底)。
Returns:
@@ -258,9 +270,9 @@ def validate_suggestions_against_evidence(
or str(target.get('field_id') or '').strip()
or ''
)
_exp_lk_raw = expected_line_key
_exp_lk_raw = expected_draft_line_id
if _exp_lk_raw is None:
_exp_lk_from_env = target.get('line_key')
_exp_lk_from_env = target.get('draft_line_id')
_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':
@@ -296,18 +308,18 @@ def validate_suggestions_against_evidence(
result.append(payload)
continue
# ---- [Check 2] header_scope_has_line_key ----
checks_ran.append('header_scope_has_line_key')
# ---- [Check 2] header_scope_has_draft_line_id ----
checks_ran.append('header_scope_has_draft_line_id')
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_raw = raw_item.get('draft_line_id')
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'
rejection_reason = 'header_scope_has_draft_line_id'
if rejection_reason:
payload['valid'] = False
payload['rejection_reason'] = rejection_reason
@@ -338,11 +350,11 @@ def validate_suggestions_against_evidence(
result.append(payload)
continue
# ---- [Check 5] line_key_mismatch(行 scope 才校验;header scope line_key 须 None 已在 Check 2)----
checks_ran.append('line_key_mismatch')
# ---- [Check 5] draft_line_id_mismatch ----
checks_ran.append('draft_line_id_mismatch')
if effective_scope == 'line':
if _exp_lk and resp_lk != _exp_lk:
rejection_reason = 'line_key_mismatch'
rejection_reason = 'draft_line_id_mismatch'
if rejection_reason:
payload['valid'] = False
payload['rejection_reason'] = rejection_reason
@@ -368,7 +380,7 @@ def validate_suggestions_against_evidence(
value_norm=sv_norm,
quote_norm_provided=quote_norm,
field_id=resp_fid,
line_key=resp_lk,
draft_line_id=resp_lk,
)
if not _matched_mode:
rejection_reason = 'value_not_in_evidence'
@@ -12,6 +12,7 @@ backend/app/services/shipping_notice/order_review_projection.py
order_review_fulfillment_decision_service.project_review_case_line_decisions /
build_inventory_issue_fallback、
order_review_workbench_projection(正式 OT / completed_checks / field_completeness)、
lifecycle_projection.project_lifecycle(队列摘要五阶段;禁止 build_task_ui_state)、
order_task_service.resolve_order_task_for_candidate、
schema_edit_policy.list_editable_formal_field_ids、
workflow_ledger_service.find_item_by_current_case、ShippingNotice(确认后推进态)。
@@ -33,6 +34,7 @@ backend/app/services/shipping_notice/order_review_projection.py
普通路径不再投影 confirm(自动建单走 STP;无 manual_create_fallback);
不返回会话级批量恢复动作;失败由当前 Gate 的具体动作恢复。
WorkflowItem 已关闭时 available_actions 仅保留 view;
会话队列摘要对正式 OT 仅用 project_lifecycle(OT.stage),禁止逐条 build_task_ui_state;
不返回全文、对象存储定位、模型原始响应、Prompt 或其他内部执行载荷。
"""
@@ -53,10 +55,14 @@ from app.models import (
ShippingOrderReviewStream,
ShippingOrderIntake,
ShippingNotice,
ShippingOrderTask,
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
)
from app.services.shipping_notice.line_inventory_match_projection import (
inventory_rpa_is_running as _inventory_rpa_is_running,
)
def _safe_filename(value: Any) -> str | None:
@@ -272,6 +278,9 @@ def _project_case_automation_status(
}
# [STEP 2] 建单前:查当前有效 STP Job;无有效 Job 时再看最新历史(failed → 可重试)。
from app.services.shipping_notice.order_review_workbench_projection import (
project_job_status_outcome,
)
job = None
latest = None
draft = getattr(case, 'current_draft', None)
@@ -324,7 +333,7 @@ def _project_case_automation_status(
'can_build': can_build,
'job_id': int(job.id),
}
if latest is not None and str(latest.status or '').strip().lower() in {'failed', 'dead'}:
if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'failed':
# 旧 Job(改造前写入)可能没有 retryable;缺失时按失败即停止处理。
result = latest.result_json if isinstance(latest.result_json, dict) else {}
raw_retryable = result.get('retryable')
@@ -355,7 +364,7 @@ def _project_case_automation_status(
'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'}:
if latest is not None and project_job_status_outcome(getattr(latest, 'status', None)) == 'succeeded':
return {
'status': 'completed',
'retryable': False,
@@ -428,53 +437,14 @@ def _schema_fields(run: ShippingOrderProcessingRun) -> list[dict[str, Any]]:
return fields
def _field_lineage_index(case: ShippingOrderReviewCase) -> dict[tuple[str, str], dict[str, Any]]:
"""
从关联 Extraction 或 Unit 结果索引派生血缘,键为 (line_key, field_code)。
核心逻辑:优先 Candidate.order_extraction_id → normalized_result_json.field_lineage;
否则回退 Unit.result_json.field_lineage。仅保留脱敏后的来源元数据。
"""
rows: list[Any] = []
candidate = db.session.get(ShippingOrderCandidate, case.candidate_id) if case.candidate_id else None
extraction_id = getattr(candidate, 'order_extraction_id', None) if candidate is not None else None
if extraction_id:
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id))
normalized = extraction.normalized_result_json if extraction is not None and isinstance(
extraction.normalized_result_json, dict,
) else {}
rows = list(normalized.get('field_lineage') or [])
if not rows and case.unit is not None and isinstance(case.unit.result_json, dict):
rows = list(case.unit.result_json.get('field_lineage') or [])
index: dict[tuple[str, str], dict[str, Any]] = {}
for item in rows:
if not isinstance(item, dict):
continue
line_key = str(item.get('line_key') or '').strip()
field_code = str(item.get('field_code') or '').strip()
if not field_code:
continue
index[(line_key, field_code)] = {
'value_source': str(item.get('value_source') or 'derived'),
'rule_id': item.get('rule_id'),
'skip_reason': item.get('skip_reason'),
'source_field_code': item.get('source_field_code'),
}
return index
def _resolve_field_meta(
*,
container: dict[str, Any],
field_id: str,
field_code: str,
lineage_index: dict[tuple[str, str], dict[str, Any]],
line_key: str | None = None,
) -> dict[str, Any]:
"""
合并草稿 values 与派生血缘,投影字段值来源元数据。
优先级:manual_override / manual(含 locked、覆盖原因)→ derived/skipped 血缘 → machine。
投影草稿 values 的来源元数据;项次由系统生成,不投影派生规则血缘。
"""
values = container.get('values') if isinstance(container.get('values'), dict) else {}
entry = values.get(field_id) if isinstance(values.get(field_id), dict) else None
@@ -492,17 +462,6 @@ def _resolve_field_meta(
if entry.get('override_reason_text'):
meta['override_reason_text'] = str(entry.get('override_reason_text'))
return meta
lineage = lineage_index.get((str(line_key or ''), field_code))
if lineage is not None:
return {
'value_source': str(lineage.get('value_source') or 'derived'),
'locked': False,
'derivation': {
'rule_id': lineage.get('rule_id'),
'skip_reason': lineage.get('skip_reason'),
'source_field_code': lineage.get('source_field_code'),
},
}
return {'value_source': 'machine', 'locked': False}
@@ -510,8 +469,6 @@ def _project_draft_container(
container: dict[str, Any] | None,
*,
scope_fields: list[dict[str, Any]],
lineage_index: dict[tuple[str, str], dict[str, Any]],
line_key: str | None = None,
) -> dict[str, Any]:
"""在保留原草稿结构基础上附加 field_meta,供复核 UI 展示来源徽章。"""
payload = dict(container or {})
@@ -525,8 +482,6 @@ def _project_draft_container(
container=payload,
field_id=field_id,
field_code=field_code,
lineage_index=lineage_index,
line_key=line_key,
)
payload['field_meta'] = field_meta
return payload
@@ -710,7 +665,6 @@ def serialize_review_case(
schema_fields = _schema_fields(run)
header_fields = [item for item in schema_fields if item.get('scope') == 'header']
line_fields = [item for item in schema_fields if item.get('scope') == 'line']
lineage_index = _field_lineage_index(case) if draft is not None else {}
projected_draft = None
llm_suggestions: list[dict[str, Any]] = []
if draft is not None:
@@ -720,14 +674,11 @@ def serialize_review_case(
'header_values': _project_draft_container(
dict(draft.header_values_json or {}),
scope_fields=header_fields,
lineage_index=lineage_index,
),
'lines': [
_project_draft_container(
dict(line) if isinstance(line, dict) else {},
scope_fields=line_fields,
lineage_index=lineage_index,
line_key=str((line or {}).get('line_key') or '') if isinstance(line, dict) else None,
)
for line in raw_lines
],
@@ -956,9 +907,9 @@ def serialize_review_case(
)
order_data_version = None
confirmed_notice = formal_ot.get('task') if formal_ot.get('has_formal_ot') else None
if confirmed_notice is not None:
order_data_version = int(confirmed_notice.order_data_version or 1)
confirmed_order_task = formal_ot.get('task') if formal_ot.get('has_formal_ot') else None
if confirmed_order_task is not None:
order_data_version = int(getattr(confirmed_order_task, 'order_data_version', None) or 1)
if is_admin and formal_ot.get('task_missing'):
technical_progress = {
@@ -990,10 +941,8 @@ def serialize_review_case(
# [STEP] 行履约投影依赖 automation / labels;Case 兜底仅无行投影且系统失败。
# waiting_to_start / waiting = 尚未真正跑库存 RPA,禁止当成 running 清空行动作。
auto_status = str((automation or {}).get('status') or '').strip().lower()
inventory_rpa_running = auto_status in {
'processing', 'queued', 'automating', 'running',
}
# 库存 RPA 运行态必须来自逐源 Attempt;阶段自动推进 Job 与库存 RPA 解耦。
inventory_rpa_running = _inventory_rpa_is_running(formal_ot.get('task'))
source_labels: dict[str, str] = {}
if isinstance(validation_snapshot, dict):
raw_labels = validation_snapshot.get('inventory_source_labels') or {}
@@ -1052,7 +1001,11 @@ def serialize_review_case(
'formal_editable_field_ids': (
list_editable_formal_field_ids(
schema_fields,
excel_ready=is_excel_ready_for_task(confirmed_notice) if confirmed_notice is not None else False,
excel_ready=(
is_excel_ready_for_task(confirmed_order_task)
if confirmed_order_task is not None
else False
),
)
if str(case.status or '') == 'confirmed'
else []
@@ -1068,6 +1021,38 @@ def serialize_review_case(
}
def _queue_current_gate_hint(case: ShippingOrderReviewCase) -> dict[str, Any] | None:
"""
从会话级批量缓存取当前 Gate 码,供队列 lifecycle 在 OT.stage 为旧 step 码时兜底。
Args:
case: 当前复核 Case。
Returns:
``{'gate_code': ...}`` 或 None(无 Execution / 缓存未就绪时)。
"""
cache = db.session.info.get('shipping_conversation_projection_read_cache')
if not isinstance(cache, dict) or getattr(case, 'id', None) is None:
return None
execution = (cache.get('execution_by_case_id') or {}).get(int(case.id))
if execution is None:
return None
gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower()
if gate_code:
return {'gate_code': gate_code}
gates = (cache.get('gates_by_execution_id') or {}).get(int(execution.id), []) or []
for gate in gates:
status = str(getattr(gate, 'status', '') or '').strip().lower()
if status not in {
'blocked_manual', 'blocked_retryable', 'waiting_external', 'running', 'pending',
}:
continue
code = str(getattr(gate, 'gate_code', '') or '').strip().lower()
if code:
return {'gate_code': code}
return None
def _serialize_review_case_summary(
case: ShippingOrderReviewCase,
*,
@@ -1076,7 +1061,11 @@ def _serialize_review_case_summary(
intakes_by_no: dict[str, ShippingOrderIntake] | None = None,
drafts_by_id: dict[int, ShippingOrderReviewDraft] | None = None,
) -> dict[str, Any]:
"""为工作台文件队列投影单 Case 的只读识别与生命周期摘要。"""
"""为工作台文件队列投影单 Case 的只读识别与生命周期摘要。
正式 OT 的五阶段:优先 OT.stage → project_lifecycle;旧 step* stage 不在映射表时
用批量缓存的 current Gate 兜底。禁止调用 build_task_ui_state。
"""
draft = (
drafts_by_id.get(int(case.current_draft_id))
if drafts_by_id is not None and case.current_draft_id
@@ -1103,19 +1092,34 @@ def _serialize_review_case_summary(
# 只有当前有效 Candidate 或正式任务事实存在时,才进入订单生命周期。
lifecycle_stage = 'intake_parse'
lifecycle_entries: list[dict[str, str]] = []
# 正式任务身份:与左侧文件导航共用同一份来源(选法 2),供前端在正式任务下游阶段
# 解耦对「复核 Case 全量快照」的依赖,按阶段懒加载复核编辑器数据。
confirmed_task_no = None
has_formal_ot = False
# 接收解析是无 Candidate Case 的独立处置面,不属于订单生命周期入口;
# 前端只能以此显式授权读取当前 Case 的解析上下文,不能据此开放订单复核。
intake_parse_authorized = False
candidate_is_reviewable = False
if case.confirmed_task_id:
from app.services.shipping_notice.lifecycle_projection import project_lifecycle
from app.services.shipping_notice.order_review_workbench_projection import resolve_formal_ot
from app.services.shipping_notice.ui_state import build_task_ui_state
# 队列摘要只需五阶段 lifecycle;禁止走 build_task_ui_state(会拉 Gate/summary/
# 动作全量,会话多 OT 时 N 倍放大到数秒)。正式 OT 已存在即开放候选上下文入口。
# OT.stage 若仍是历史 step* 码,project_lifecycle 会忽略它并改用 current_gate 兜底。
formal_ot = resolve_formal_ot(case)
if formal_ot.get('has_formal_ot'):
task_ui_state = build_task_ui_state(formal_ot['task'])
lifecycle_stage = str(task_ui_state.get('lifecycle_stage') or lifecycle_stage)
lifecycle_entries = list(task_ui_state.get('lifecycle_entries') or [])
task = formal_ot['task']
confirmed_task_no = str(getattr(task, 'task_no', None) or '').strip() or None
has_formal_ot = True
lifecycle = project_lifecycle(
current_gate=_queue_current_gate_hint(case),
blocking_reason=None,
has_candidate_context=True,
processing_stage=getattr(task, 'stage', None),
)
lifecycle_stage = str(lifecycle.get('lifecycle_stage') or lifecycle_stage)
lifecycle_entries = list(lifecycle.get('lifecycle_entries') or [])
else:
from app.services.shipping_notice.candidate_service import is_current_reviewable_candidate
@@ -1162,6 +1166,9 @@ def _serialize_review_case_summary(
# 与批次中心 / 任务中心同义;前端不得再根据 Case status 或 stage 推断入口。
'lifecycle_entries': lifecycle_entries,
'intake_parse_authorized': intake_parse_authorized,
# 正式任务身份(选法 2):供工作台在此阶段懒加载复核编辑器,不再反推复核 Case。
'confirmed_task_no': confirmed_task_no,
'has_formal_ot': has_formal_ot,
}
@@ -1259,7 +1266,7 @@ def _load_review_case_summary_batch(
for draft in ShippingOrderReviewDraft.query.filter(ShippingOrderReviewDraft.id.in_(draft_ids)).all()
} if draft_ids else {}
if task_ids:
ShippingNotice.query.filter(ShippingNotice.id.in_(task_ids)).all()
ShippingOrderTask.query.filter(ShippingOrderTask.id.in_(task_ids)).all()
intake_nos = {
str(intake_snapshot.get('intake_no') or '').strip().upper()
for case, run in rows
@@ -112,7 +112,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
if not isinstance(proj, dict):
continue
effective = str(proj.get('effective_reservation_id') or '').strip() or None
line_key = str(proj.get('line_key') or '').strip() or None
draft_line_id = str(proj.get('draft_line_id') or '').strip() or None
block_reason = str(proj.get('block_reason') or '').strip() or None
line_reservation_issue = next(
(
@@ -133,7 +133,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
)
lines_out.append({
'line_index': idx,
'line_key': line_key,
'draft_line_id': draft_line_id,
'effective_reservation_id': effective,
'can_build': bool(proj.get('can_build', True)),
# Reservation 面板只展示自身 Gate 原因,不能泄漏库存路由 block_reason。
@@ -150,7 +150,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
rid = _current_line_reservation_id(line, reservation_field_id)
lines_out.append({
'line_index': idx,
'line_key': str(line.get('line_key') or '').strip() or None,
'draft_line_id': str(line.get('draft_line_id') or '').strip() or None,
'effective_reservation_id': rid,
'can_build': True,
'block_reason': None,
@@ -170,7 +170,7 @@ def project_review_case_reservation(case: ShippingOrderReviewCase) -> dict[str,
'severity': str(item.get('severity') or 'blocking')[:32],
'message': str(item.get('message') or '')[:240] or None,
'line_index': item.get('line_index'),
'line_key': item.get('line_key'),
'draft_line_id': item.get('draft_line_id'),
'field_code': item.get('field_code') or 'reservation_id',
}
for item in issues[:20]
@@ -202,7 +202,7 @@ def _initial_draft_payload(
order = orders[0]
header = {'machine_fields': list(order.get('header_fields') or [])}
lines = [
{'line_key': f'machine-{index + 1}', 'machine_fields': list(line.get('fields') or [])}
{'draft_line_id': f'machine-{index + 1}', 'machine_fields': list(line.get('fields') or [])}
for index, line in enumerate(order.get('lines') or []) if isinstance(line, dict)
]
_restore_machine_source_case(header, lines)
@@ -499,7 +499,7 @@ def build_llm_suggestion_request_context(
user_id: int,
case_no: str,
field_id: str,
line_key: str | None = None,
draft_line_id: str | None = None,
) -> dict[str, Any]:
"""
为 LLM 建议请求绑定 Case、Document 与冻结 Schema 字段上下文。
@@ -510,7 +510,7 @@ def build_llm_suggestion_request_context(
user_id: Case 属主。
case_no: 复核 Case 编号。
field_id: 目标 field_id。
line_key: 明细行键。
draft_line_id: 明细行键。
Returns:
含 case_no、document_id、draft_version、field 的上下文 dict。
@@ -536,6 +536,6 @@ def build_llm_suggestion_request_context(
'field_id': str(field_id),
'field_code': str(field.get('field_code') or field_id),
'scope': str(field.get('scope') or ''),
'line_key': line_key,
'draft_line_id': draft_line_id,
'schema_version_id': int(case.run.schema_version_id),
}
@@ -3,13 +3,14 @@ backend/app/services/shipping_notice/order_review_workbench_projection.py
用途:复核工作台 Case 投影的阶段分层辅助——正式 OT 判定、用户态 profile_match、
field_completeness、completed_checks、OT 当前阶段与 automation 责任方;
以及草稿行 field_code(如 part_number/qty)解析,供履约表与订单明细对齐。
以及草稿行 field_code(如 part_number/qty)解析,供履约表与订单明细对齐;
另提供 Job.status → 单一 outcome 投影(project_job_status_outcome)。
依赖:ShippingNotice、ShippingOrderReviewCase、Job、order_review_draft_service._current_value、
process_gate_contract、processing_projection_invariants、queue_service 域常量。
逻辑:由 order_review_projection.serialize_review_case / shipping_processing_projection /
order_review_fulfillment_decision_service 调用;不新建状态模型;
project_stage_for_task 与 project_post_ot_automation_from_job 为 Case/Progress 同源;
禁止前端自行拼接里程碑。
Job 成功/失败同义词只在本模块翻译,调用方只判 succeeded/failed。
"""
from __future__ import annotations
@@ -18,7 +19,38 @@ from datetime import datetime
from typing import Any
from app import db
from app.models import ShippingNotice, ShippingOrderReviewCase
from app.models import ShippingNotice, ShippingOrderReviewCase, ShippingOrderTask
# Job 库内成功/失败词 → 单一 outcome;仅本模块持有 synonym 袋,禁止外溢。
JOB_FAILURE_STATUS_TOKENS: frozenset[str] = frozenset({'failed', 'dead'})
JOB_SUCCESS_STATUS_TOKENS: frozenset[str] = frozenset({'succeeded', 'success', 'completed'})
def project_job_status_outcome(raw_status: str | None) -> str:
"""将 Job.status 库内词投影为单一 outcome。
核心逻辑:failed/dead → failed;succeeded/success/completed → succeeded;
queued / running|processing 原样归类。调用方只允许 ``== 'failed'`` / ``== 'succeeded'``。
Args:
raw_status: Job.status 原值。
Returns:
failed | succeeded | queued | running | 其它小写透传 | 空串。
"""
status = str(raw_status or '').strip().lower()
if not status:
return ''
if status in JOB_FAILURE_STATUS_TOKENS:
return 'failed'
if status in JOB_SUCCESS_STATUS_TOKENS:
return 'succeeded'
if status == 'queued':
return 'queued'
if status in {'running', 'processing'}:
return 'running'
return status
# 正式 OT 创建后不得再作为「当前人工阻断」的建单前 Gate。
_PRE_OT_BLOCKING_GATE_CODES: frozenset[str] = frozenset({
@@ -65,7 +97,7 @@ def resolve_formal_ot(case: ShippingOrderReviewCase) -> dict[str, Any]:
"""
判定 Case 是否已绑定可读的正式 OT。
核心逻辑:唯一判据为 confirmed_task_id 指向存在且 task_no 有效的 ShippingNotice;
核心逻辑:唯一判据为 confirmed_task_id 指向存在且 task_no 有效的 ShippingOrderTask;
Case.status=confirmed 不能单独证明 OT 存在。
Args:
@@ -75,7 +107,7 @@ def resolve_formal_ot(case: ShippingOrderReviewCase) -> dict[str, Any]:
{
has_formal_ot: bool,
task_missing: bool,
task: ShippingNotice | None,
task: ShippingOrderTask | None,
task_no: str | None,
task_id: int | None,
}
@@ -89,7 +121,7 @@ def resolve_formal_ot(case: ShippingOrderReviewCase) -> dict[str, Any]:
'task_no': None,
'task_id': None,
}
task = db.session.get(ShippingNotice, int(task_id))
task = db.session.get(ShippingOrderTask, int(task_id))
if task is None:
return {
'has_formal_ot': False,
@@ -441,17 +473,33 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
}
task_no = str(getattr(task, 'task_no', None) or '').strip().upper() or None
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
from app.services.shipping_notice.upload_attempt_service import (
has_verified_upload_success,
latest_export_artifact,
latest_upload_attempt,
)
verified_upload_success = has_verified_upload_success(task)
upload_status = getattr(task, 'upload_status', None)
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
upload_status = getattr(latest_upload_attempt(task), 'status', None)
upload_status = upload_status.strip().lower() if isinstance(upload_status, str) else ''
export_file_path = getattr(task, 'export_file_path', None)
match_status = getattr(task, 'match_status', None)
inventory_lines = getattr(task, 'inventory_lines_json', None)
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
export_file_path = getattr(latest_export_artifact(task), 'file_path', None)
if isinstance(task, ShippingOrderTask):
from app.services.shipping_notice.inventory_file_store import (
current_inventory_matches_for_task,
has_ready_inventory_file_for_task,
)
has_match = bool(current_inventory_matches_for_task(task))
has_inventory = has_ready_inventory_file_for_task(task)
else:
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
match_status = aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None))
has_match = bool(match_status)
has_inventory = has_ready_inventory_file_for_task(task)
has_export = isinstance(export_file_path, str) and bool(export_file_path.strip())
has_match = isinstance(match_status, str) and bool(match_status.strip())
has_inventory = isinstance(inventory_lines, (list, dict)) and bool(inventory_lines)
progress_state = (
'uploaded' if verified_upload_success
else 'export_ready' if has_export
@@ -531,11 +579,11 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
**_job_fields(active),
}
# [STEP 2] 最近 Job:failed/dead,或 success 但 OT 未推进。
# [STEP 2] 最近 Job:failed,或 succeeded 但 OT 未推进。
if latest is not None:
latest_status = str(latest.status or '').strip().lower()
latest_outcome = project_job_status_outcome(getattr(latest, 'status', None))
fields = _job_fields(latest)
if latest_status in {'failed', 'dead'}:
if latest_outcome == 'failed':
exhausted = _attempts_exhausted(latest)
return {
'status': 'manual_fallback' if exhausted else 'failed',
@@ -546,7 +594,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str
'reason_code': fields.get('error_code') or 'auto_progress_job_failed',
**fields,
}
if latest_status in {'succeeded', 'success', 'completed'}:
if latest_outcome == 'succeeded':
# Job 标成功但 OT 仍 created:业务故障,不得伪装 waiting / 抹掉 job_id。
if progress_state in {'', 'not_started'}:
exhausted = _attempts_exhausted(latest)
@@ -642,21 +690,35 @@ def project_stage_for_task(
from app.services.shipping_notice.processing_projection_invariants import (
map_notice_to_processing_status_stage,
)
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
from app.services.shipping_notice.upload_attempt_service import (
has_verified_upload_success,
latest_export_artifact,
)
# 业务完成不能仅信任 Notice 的历史聚合字段。复核工作台必须与批次投影
# 复用同一成功谓词,否则同一任务会在不同入口出现“已完成/待上传”分叉。
owner = task
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None):
owner = db.session.get(ShippingOrderTask, int(task.order_task_id)) or task
verified_upload_success = has_verified_upload_success(task)
raw_upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
if isinstance(owner, ShippingOrderTask):
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
match_facts = list(load_current_match_facts_by_task(getattr(owner, 'id', None)).values())
has_task_match = bool(match_facts)
else:
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
has_task_match = bool(aggregate_match_status_for_task(getattr(task, 'order_task_id', None) or getattr(task, 'id', None)))
progress_state = (
'uploaded' if verified_upload_success
else 'export_ready' if getattr(task, 'export_file_path', None)
else 'matched' if getattr(task, 'match_status', None)
else 'inventory_ready' if getattr(task, 'inventory_lines_json', None)
else 'export_ready' if getattr(latest_export_artifact(task), 'file_path', None)
else 'matched' if has_task_match
else 'inventory_ready' if has_ready_inventory_file_for_task(task)
else 'not_started'
)
current_step = str(getattr(task, 'current_step', None) or '').strip() or None
current_step = str(getattr(owner, 'current_step', None) or '').strip() or None
def _with_label(code: str, *, source: str) -> dict[str, Any]:
# order_creating 技术阶段码保留;用户可见文案键固定 waiting_system_start。
@@ -675,7 +737,8 @@ def project_stage_for_task(
# freight_uploading,只有三层成功事实齐备时才能覆盖为 completed。
if progress_state == 'uploaded':
return _with_label('completed', source='notice_terminal')
if raw_upload_status in {'uploaded', 'succeeded', 'success'}:
from app.services.shipping_notice.upload_attempt_service import project_notice_upload_status
if project_notice_upload_status(task) == 'uploaded':
return _with_label('freight_uploading', source='upload_success_unverified')
# [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。
@@ -685,12 +748,6 @@ def project_stage_for_task(
if has_app_context():
if getattr(task, 'order_task_id', None):
order_task = db.session.get(ShippingOrderTask, int(task.order_task_id))
if order_task is None and getattr(task, 'id', None):
order_task = (
ShippingOrderTask.query.filter_by(shipping_notice_id=int(task.id))
.order_by(ShippingOrderTask.id.desc())
.first()
)
except Exception: # noqa: BLE001 — 单元测试无 Flask 上下文时跳过 OT 查询
order_task = None
ot_stage = str(getattr(order_task, 'stage', None) or '').strip().lower() if order_task else ''
@@ -1,105 +0,0 @@
"""
services/shipping_notice/order_schema/derivation_engine.py
用途:执行 Schema 级字段派生规则(首期 copy_if_empty),供模拟与运行时共用。
依赖:field_rules(规则归一化与 line_no 格式)、统一 ValidationError。
逻辑:仅处理启用中的 line→line 规则;目标非空/来源空/格式非法时记录跳过原因;
不写库;调用方负责持久化与审计。
"""
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.order_schema.field_rules import (
derivation_rules_checksum,
is_valid_line_no_value,
normalize_derivation_rules,
)
def apply_derivation_rules_to_lines(
lines: list[dict[str, Any]],
rules: list[dict[str, Any]] | None,
*,
locked_targets: set[tuple[int, str]] | None = None,
) -> dict[str, Any]:
"""
对明细行集合执行派生规则,返回派生后行与逐行结果摘要。
核心逻辑:仅启用规则生效;copy_if_empty 仅在目标为空时复制来源;
目标已锁定(人工覆盖)时跳过;来源缺失或目标格式非法时跳过。
Args:
lines: 明细字段字典列表(按行可变副本由本函数新建)。
rules: Schema definition_json.derivation_rules 或草稿规则。
locked_targets: 可选 ``{(line_index, field_code)}`` 人工锁定集合。
Returns:
``{lines, results, rules_checksum, derived_count, skipped_count}``;
``results`` 每项含 line_index、rule_id、status(derived|skipped)、skip_reason、
source/target 前后值。
"""
normalized = normalize_derivation_rules(rules, adopted_line_field_codes=None)
checksum = derivation_rules_checksum(normalized)
enabled = [rule for rule in normalized if rule.get('enabled')]
output_lines = [dict(line) for line in lines]
results: list[dict[str, Any]] = []
locks = locked_targets or set()
for line_index, line in enumerate(output_lines):
for rule in enabled:
source_code = str(rule['source_field_code'])
target_code = str(rule['target_field_code'])
rule_id = str(rule['rule_id'])
before_target = line.get(target_code)
before_source = line.get(source_code)
entry: dict[str, Any] = {
'line_index': line_index,
'rule_id': rule_id,
'source_field_code': source_code,
'target_field_code': target_code,
'strategy': rule['strategy'],
'before_source': before_source,
'before_target': before_target,
'after_target': before_target,
'status': 'skipped',
'skip_reason': None,
}
if (line_index, target_code) in locks:
entry['skip_reason'] = 'manual_override_locked'
results.append(entry)
continue
if before_target not in (None, ''):
entry['skip_reason'] = 'target_not_empty'
results.append(entry)
continue
if before_source in (None, ''):
entry['skip_reason'] = 'source_empty'
results.append(entry)
continue
source_text = str(before_source).strip()
if target_code == 'line_no' and not is_valid_line_no_value(source_text):
entry['skip_reason'] = 'source_format_invalid'
results.append(entry)
continue
if rule['strategy'] != 'copy_if_empty':
entry['skip_reason'] = 'unsupported_strategy'
results.append(entry)
continue
line[target_code] = source_text
entry['after_target'] = source_text
entry['status'] = 'derived'
entry['skip_reason'] = None
results.append(entry)
derived_count = sum(1 for item in results if item['status'] == 'derived')
skipped_count = sum(1 for item in results if item['status'] == 'skipped')
return {
'lines': output_lines,
'results': results,
'rules': normalized,
'rules_checksum': checksum,
'derived_count': derived_count,
'skipped_count': skipped_count,
}
@@ -1,18 +1,15 @@
"""
backend/app/services/shipping_notice/order_schema/field_rules.py
用途:执行冻结订单 Schema 的通用字段归一化、validator,以及 Schema 级字段派生规则契约校验。
用途:执行冻结订单 Schema 的通用字段归一化和 validator。
依赖:标准库 Decimal/date、reservation_id 安全校验、统一 ValidationError。
逻辑:运行时传入完整字段配置;本模块不查询数据库,也不允许配置绕过 Reservation ID 安全规则;
Header/Line Reservation 均可选,有效值由行优先回退头计算;
单价等字段必须已经由显式视觉框或拆分规则提供单值;derivation_rules 仅允许 line→line。
单价等字段必须已经由显式视觉框或拆分规则提供单值;订单项次由系统按单据内顺序生成。
"""
from __future__ import annotations
import hashlib
import json
import re
from datetime import date, datetime
from decimal import Decimal, InvalidOperation
from typing import Any
@@ -20,11 +17,7 @@ from typing import Any
from app.core.errors import ValidationError
from app.services.shipping_notice.reservation_id import validated_reservation_id
# Phase 0/1 派生规则契约常量。
DERIVATION_STRATEGIES = frozenset({'copy_if_empty'})
DERIVATION_ALLOWED_TARGETS = frozenset({'line_no'})
DERIVATION_LINE_NO_PATTERN = re.compile(r'^\d{1,6}$')
DEFAULT_DERIVATION_RULE_ID = 'R-LINE-NO-FROM-CUSTOMER-PO'
# 硬切换后不再提供 Schema 派生规则;订单项次由系统按单据顺序生成。
def compute_effective_reservation_id(
@@ -52,160 +45,21 @@ def compute_effective_reservation_id(
)
def default_derivation_rules() -> list[dict[str, Any]]:
"""
返回新草稿默认派生规则(关闭状态)。
核心逻辑:预置 customer_po_line_no → line_no 的 copy_if_empty 规则,enabled=False,
避免未评审规则自动改写内部项次。
Returns:
可写入 definition_json.derivation_rules 的规则列表。
"""
return [{
'rule_id': DEFAULT_DERIVATION_RULE_ID,
'enabled': False,
'source_field_code': 'customer_po_line_no',
'target_field_code': 'line_no',
'strategy': 'copy_if_empty',
'scope': 'line',
}]
def derivation_rules_checksum(rules: list[dict[str, Any]]) -> str:
"""
计算派生规则稳定校验和,供发布冻结与审计引用。
Args:
rules: 已归一化的派生规则列表。
Returns:
SHA-256 hex 摘要。
"""
payload = json.dumps(rules, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
return hashlib.sha256(payload.encode('utf-8')).hexdigest()
def normalize_derivation_rules(
value: Any,
*,
adopted_line_field_codes: set[str] | None = None,
) -> list[dict[str, Any]]:
"""
归一化并校验 Schema definition_json.derivation_rules。
核心逻辑:仅允许 line→line;首期策略仅 copy_if_empty;目标仅 line_no;
禁止自引用;同一启用目标只允许一条规则;来源/目标须属于已采用明细字段(若提供)。
Args:
value: 原始 derivation_rules(None 时返回默认关闭预置)。
adopted_line_field_codes: 当前草稿已采用的明细 field_code 集合;None 表示跳过采用检查。
Returns:
归一化后的规则列表。
Raises:
ValidationError: 结构、策略、循环或竞争冲突。
"""
if value is None:
return default_derivation_rules()
if not isinstance(value, list):
raise ValidationError(
'derivation_rules must be a list',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
)
normalized: list[dict[str, Any]] = []
enabled_targets: set[str] = set()
for index, raw in enumerate(value):
if not isinstance(raw, dict):
raise ValidationError(
'derivation rule must be an object',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'index': index},
)
rule_id = str(raw.get('rule_id') or '').strip() or f'R-DERIVE-{index + 1}'
enabled = raw.get('enabled', False)
if not isinstance(enabled, bool):
raise ValidationError(
'derivation rule enabled must be boolean',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id},
)
source = str(raw.get('source_field_code') or '').strip()
target = str(raw.get('target_field_code') or '').strip()
strategy = str(raw.get('strategy') or '').strip()
scope = str(raw.get('scope') or 'line').strip()
if scope != 'line':
raise ValidationError(
'derivation rules only allow line scope',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id},
)
if strategy not in DERIVATION_STRATEGIES:
raise ValidationError(
'unsupported derivation strategy',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id, 'strategy': strategy},
)
if target not in DERIVATION_ALLOWED_TARGETS:
raise ValidationError(
'derivation target is not allowed in this phase',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id, 'target_field_code': target},
)
if not source or source == target:
raise ValidationError(
'derivation source/target must differ and be non-empty',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id},
)
if adopted_line_field_codes is not None:
missing = {code for code in (source, target) if code not in adopted_line_field_codes}
if missing:
raise ValidationError(
'derivation fields must be adopted line fields',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'rule_id': rule_id, 'missing_field_codes': sorted(missing)},
)
if enabled and target in enabled_targets:
raise ValidationError(
'only one enabled derivation rule is allowed per target',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_INVALID',
details={'target_field_code': target},
)
if enabled:
enabled_targets.add(target)
normalized.append({
'rule_id': rule_id,
'enabled': enabled,
'source_field_code': source,
'target_field_code': target,
'strategy': strategy,
'scope': scope,
})
return normalized
def is_valid_line_no_value(value: Any) -> bool:
"""
校验内部项次格式:1–6 位数字,保留前导零。
Args:
value: 候选内部项次。
Returns:
是否符合契约。
"""
if value in (None, ''):
return False
return bool(DERIVATION_LINE_NO_PATTERN.fullmatch(str(value).strip()))
def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
"""按冻结字段类型解析候选值,同时保留原始文本大小写。
`uppercase_trim` / `lowercase_trim` 仅可用于比较、索引和规则匹配,不能改写
PDF/邮件证据对应的业务展示值;否则料号、客户名称、地址和币种会偏离原文件。
核心逻辑:按 value_type 做确定性解析;文本类 normalizer 不得改写展示值。
日期仅接受显式布局,禁止把自由文本猜成日期。
Args:
value: 原始候选值(PDF/邮件单元格或 Observation)。
config: 冻结 Schema 字段配置(须含 value_type;可选 normalizer_key)。
Returns:
规范化后的业务值;空输入返回 None。
Raises:
ValidationError: 类型无法按显式规则解析时失败。
"""
if value in (None, ''):
return None
@@ -231,6 +85,9 @@ def normalize_order_field_value(value: Any, config: dict[str, Any]) -> Any:
# ISO date, so downstream validators receive one type.
'%m/%d/%y', '%m-%d-%y', '%m.%d.%y',
'%d-%b-%Y', '%d-%B-%Y',
# [PARAM_TUNING] 2026-09-08: EML 分配表 PO Date 常见 ``12-Jun-26``;
# 仅有四位年 ``%d-%b-%Y`` 时整行补充被 fail-closed 丢弃,库存源线索/预约号一并落空。
'%d-%b-%y', '%d-%B-%y',
):
try:
return datetime.strptime(text, pattern).date()
@@ -267,8 +124,6 @@ def validate_order_field_value(value: Any, config: dict[str, Any]) -> bool:
field_code = str(config.get('field_code') or '')
if field_code == 'reservation_id' and value not in (None, '') and not validated_reservation_id(value):
return False
if field_code == 'line_no' and value not in (None, '') and not is_valid_line_no_value(value):
return False
for key in config.get('validator_keys') or []:
if key == 'non_empty' and value in (None, ''):
return False
@@ -3,15 +3,15 @@ backend/app/services/shipping_notice/order_schema/runtime.py
用途:编译已发布订单 Schema,并裁决 Dify 返回的动态字段 Observation。
依赖:订单 Schema 动态模型、standard_field_registry、ShippingOrderDocument、registry、
derivation_engine、audit_service、订单客户匹配服务、process_gate_contract(字段阻断资格)、
audit_service、订单客户匹配服务、process_gate_contract(字段阻断资格)、
pdf_priority_adjudication(阶段 2 PDF 优先冲突裁决)。
逻辑:提交时先验证原文证据和字段规则并投影;再执行 Schema 派生并落库 FieldValue;
逻辑:提交时先验证原文证据和字段规则并投影;内部项次由系统按行顺序生成;
Observation.source_type 按主 PDF / 其他 PDF / Excel / Word / 正文区分;
跨来源冲突时先尝试 PDF_PRIORITY_FIELD_POLICIES,未命中再回退 prefer_attachment/email;
Decision.selected_observation_id 对齐最终选中 Observation,禁止固定取第一条;
仅 required 或 auto_create_key_field 字段可进入 blocked_fields;
可选非关键字段证据不足只生成 diagnostic Finding,不阻断建单;
必填门禁仅在派生后按最终投影判定;
必填门禁按最终投影判定;
published_version 固定读取唯一 Schema STANDARD_SHIPPING_NOTICE(兼容历史 SHIPPING_ORDER)。
"""
@@ -43,13 +43,11 @@ from app.services.shipping_notice.context_fields.runtime import (
canonical_mail_context,
persist_deterministic_context_fields,
)
from app.services.shipping_notice.order_customer_matching import refresh_order_customer_matches
from app.services.shipping_notice.order_schema.field_rules import (
compute_effective_reservation_id,
normalize_order_field_value,
validate_order_field_value,
)
from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.pdf_priority_adjudication import choose_pdf_priority_value
@@ -413,11 +411,19 @@ def _verified_email_supplement_observation(
def _valid_coordinate_evidence(raw: dict[str, Any]) -> bool:
"""只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。"""
"""
只接受后端确认的最小页级坐标证据,缺页号、来源或字符索引时不提升为已验证。
anchor_bbox 仅锚点定位字段携带;模板固定值区字段(无锚点标签)由解析器合法返回
None,其冻结 value_bbox + 字符索引已是完整取值证据,不得因缺锚点丢弃观测,
否则账款客户/地址等固定区头字段永远无法落库,下游客户识别将空转。
"""
anchor_bbox = raw.get('anchor_bbox')
return (
str(raw.get('source') or '') == 'pdf_coordinate'
and isinstance(raw.get('page_no'), int) and raw['page_no'] >= 1
and isinstance(raw.get('anchor_bbox'), dict) and isinstance(raw.get('value_bbox'), dict)
and (anchor_bbox is None or isinstance(anchor_bbox, dict))
and isinstance(raw.get('value_bbox'), dict)
and isinstance(raw.get('glyph_indices'), list) and bool(raw['glyph_indices'])
)
@@ -946,7 +952,7 @@ def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) -
return result
def _persist_derived_line_field(
'''# Disabled legacy derivation helpers intentionally retained as inert source text.
*,
extraction: ShippingOrderExtraction,
line: ShippingOrderLine,
@@ -1034,7 +1040,6 @@ def _persist_derived_line_field(
'value': payload,
'reason_code': 'derived',
'rule_id': rule_id,
'derivation_rules_checksum': rules_checksum,
'observation_ids': [],
'confidence': 1.0,
}
@@ -1104,6 +1109,7 @@ def _derivation_evidence_refs(
return refs
'''
def persist_dynamic_order(
*,
raw_order: dict[str, Any],
@@ -1132,9 +1138,12 @@ def persist_dynamic_order(
str(item['field_id']): item for item in (version.definition_json or {}).get('fields') or []
if item.get('enabled', True)
}
# line_no 是系统生成且只读的订单项次,不是解析出来的业务字段:不进 llm 字段裁决,
# 不落 FieldValue/Decision,只在 ShippingOrderLine.line_no 与 system_line_projections 体现。
configs = {
field_id: item for field_id, item in all_configs.items()
if item.get('collection_mode', 'llm_extraction') == 'llm_extraction'
and str(item.get('field_code') or '').strip() != 'line_no'
}
context_configs = [
item for item in all_configs.values()
@@ -1196,7 +1205,8 @@ def persist_dynamic_order(
line = ShippingOrderLine(
extraction_id=extraction.id,
position=position,
line_key=str(uuid.uuid4()),
line_no=position + 1,
draft_line_id=str(uuid.uuid4()),
)
db.session.add(line)
db.session.flush()
@@ -1282,79 +1292,19 @@ def persist_dynamic_order(
owning_gate_code='order_field_extraction',
))
# [STEP 3] Schema 派生规则:仅补齐空目标;成功后落库 FieldValue,供冻结/Excel 读取。
derivation_outcome = apply_derivation_rules_to_lines(
line_projections,
(version.definition_json or {}).get('derivation_rules'),
)
line_projections = derivation_outcome['lines']
# [STEP 3] 内部项次由系统按解析行顺序生成;不读取或执行任何派生规则。
field_lineage: list[dict[str, Any]] = []
for item in derivation_outcome['results']:
line_index = int(item['line_index'])
line_obj = extraction.lines[line_index] if line_index < len(extraction.lines) else None
lineage_row = {
'line_key': line_obj.line_key if line_obj is not None else None,
'field_code': item['target_field_code'],
'value_source': 'derived' if item['status'] == 'derived' else 'skipped',
'rule_id': item['rule_id'],
'rule_checksum': derivation_outcome['rules_checksum'],
'skip_reason': item.get('skip_reason'),
'before_value': item.get('before_target'),
'after_value': item.get('after_target'),
'source_field_code': item.get('source_field_code'),
'source_value': item.get('before_source'),
}
field_lineage.append(lineage_row)
if item['status'] == 'derived' and line_obj is not None:
target_config = _config_by_line_field_code(all_configs, str(item['target_field_code']))
if target_config is not None and item.get('after_target') not in (None, ''):
decisions.append(_persist_derived_line_field(
extraction=extraction,
line=line_obj,
config=target_config,
value=item.get('after_target'),
rule_id=str(item['rule_id']),
rules_checksum=str(derivation_outcome['rules_checksum']),
))
event_type = 'FIELD_DERIVED' if item['status'] == 'derived' else 'FIELD_DERIVATION_SKIPPED'
evidence_refs = _derivation_evidence_refs(
extraction_id=int(extraction.id),
line_id=int(line_obj.id) if line_obj is not None else None,
source_field_code=str(item.get('source_field_code') or '') or None,
all_configs=all_configs,
)
append_shipping_audit_event(
event_type=event_type,
aggregate_type='shipping_order_extraction',
aggregate_id=str(extraction.id),
intake_no=getattr(intake, 'intake_no', None),
actor_type='system',
actor_id='derivation_engine',
action='derive_line_field',
result='success' if item['status'] == 'derived' else 'ignored',
reason_code=item.get('skip_reason'),
evidence_refs=evidence_refs or None,
metadata={
'rule_id': item['rule_id'],
'derivation_rules_checksum': derivation_outcome['rules_checksum'],
'field_code': item['target_field_code'],
'line_key': lineage_row['line_key'],
'source_field_code': item.get('source_field_code'),
'skip_reason': item.get('skip_reason'),
'schema_version_id': version.id,
},
before={'previous_value': item.get('before_target'), 'value_source': 'machine'},
after={
'new_value': item.get('after_target'),
'value_source': 'derived' if item['status'] == 'derived' else 'skipped',
},
)
# [STEP 4] 关键字段完整性仅在派生之后按最终投影检查,避免派生刚补齐的必填项仍被误拦。
# [STEP 4] 关键字段完整性按最终投影检查。
for config in all_configs.values():
if not field_may_block_process(config):
continue
code = str(config['field_code'])
# line_no 是系统生成且只读的订单项次(写入 ShippingOrderLine.line_no,并经
# system_line_projections 输出);业务行投影不重复携带它,因此不得用“required
# 但业务投影缺失”把这一系统字段误判为缺失阻断。
if code == 'line_no':
continue
missing = False
if config['scope'] == 'header' and code not in header:
missing = True
@@ -1405,11 +1355,12 @@ def persist_dynamic_order(
'blocks_current_action': str(code) in blocking_codes,
})
# 行级辅助投影:仅输出 line_key 与有效 Reservation;line_no 为可识别/可派生内部项次。
# 行级辅助投影:输出草稿身份、系统项次与有效 Reservation。
system_line_projections: list[dict[str, Any]] = []
for line, projection in zip(extraction.lines, line_projections):
system_line_projections.append({
'line_key': line.line_key,
'draft_line_id': line.draft_line_id,
'line_no': int(line.line_no),
'effective_reservation_id': compute_effective_reservation_id(
line_reservation_id=projection.get('reservation_id'),
header_reservation_id=header.get('reservation_id'),
@@ -1437,7 +1388,6 @@ def persist_dynamic_order(
'header': header,
'lines': line_projections,
'field_lineage': field_lineage,
'derivation_rules_checksum': derivation_outcome['rules_checksum'],
}
extraction.validation_result_json = {
'blocked_fields': blocked_unique,
@@ -1447,19 +1397,16 @@ def persist_dynamic_order(
extraction.status = 'needs_review' if blocked_unique else 'accepted'
extraction.updated_at = datetime.utcnow()
db.session.flush()
customer_matches = refresh_order_customer_matches(extraction, header)
return {
'extraction': extraction,
'header': header,
'lines': line_projections,
'system_line_projections': system_line_projections,
'field_lineage': field_lineage,
'derivation_rules_checksum': derivation_outcome['rules_checksum'],
'blocked_fields': blocked_unique,
'findings': deduped_findings,
'observations': observations,
'decisions': decisions,
'customer_matches': customer_matches,
'auto_create_key_field_thresholds': {
str(item['field_code']): float(item['minimum_confidence'])
for item in all_configs.values()
@@ -3,8 +3,8 @@ backend/app/services/shipping_notice/order_schema/service.py
用途:管理唯一发货订单 Schema 的版本采用/发布与追加式配置审计;字段资产生命周期委托 field_asset_service。
依赖:db、订单 Schema 模型、standard_field_registry、field_asset_service、field_rules、registry、统一 AppError。
逻辑:草稿与发布版本统一读写 definition_json(含 auto_creation_policy、derivation_rules、
task_edit_policy);乐观锁阻止覆盖;发布冻结快照并追加审计事件。
逻辑:草稿与发布版本统一读写 definition_json(含 auto_creation_policy、task_edit_policy);
乐观锁阻止覆盖;发布冻结快照并追加审计事件。
"""
from __future__ import annotations
@@ -68,12 +68,6 @@ from app.services.shipping_notice.order_schema.registry import (
from app.services.shipping_notice.order_schema.compatibility import compare_profile_schema
from app.services.shipping_notice.order_schema.table_contract import compile_table_header_contract
from app.services.shipping_notice.order_schema.diff import compare_definitions
from app.services.shipping_notice.order_schema.field_rules import (
default_derivation_rules,
derivation_rules_checksum,
normalize_derivation_rules,
)
from app.services.shipping_notice.order_schema.derivation_engine import apply_derivation_rules_to_lines
from app.services.shipping_notice.audit_service import append_shipping_audit_event
SCHEMA_CODE = DEFAULT_SCHEMA_FAMILY_CODE
@@ -836,7 +830,7 @@ def get_extraction_audit(extraction_id: int) -> dict[str, Any]:
'raw_llm_output': _copy_json(extraction.raw_llm_output_json),
'normalized_result': _copy_json(extraction.normalized_result_json),
'validation_result': _copy_json(extraction.validation_result_json),
'lines': [{'id': row.id, 'position': row.position, 'line_key': row.line_key} for row in lines],
'lines': [{'id': row.id, 'position': row.position, 'draft_line_id': row.draft_line_id} for row in lines],
'observations': [
identity(row.field_id) | {
'id': row.id, 'line_id': row.line_id, 'source_document_id': row.source_document_id,
@@ -1018,12 +1012,6 @@ def create_draft(
definition if source else None,
fallback=schema.auto_creation_policy_json,
)
# [STEP] 派生规则:复制来源时归一化;全新草稿预置关闭状态的默认规则。
definition['derivation_rules'] = normalize_derivation_rules(
definition.get('derivation_rules') if source else None,
adopted_line_field_codes=None,
)
definition['derivation_rules_checksum'] = derivation_rules_checksum(definition['derivation_rules'])
version = ShippingOrderSchemaVersion(
schema_id=schema.id,
version=next_version,
@@ -1123,6 +1111,23 @@ def save_draft(
raise ValidationError('fields must be a list', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
before = _definition(version)
ensure_standard_assets_seeded(actor_id=actor_id)
# line_no 是系统项次字段:调用方无需提交配置,服务端始终将其纳入 Schema。
line_no_asset = ShippingOrderField.query.filter_by(
field_code='line_no', scope='line', asset_kind='system_standard', status='active',
).one()
if not any(
isinstance(item, dict) and str(item.get('field_id') or '') == str(line_no_asset.id)
for item in configs
):
configs = [*configs, {
'field_id': str(line_no_asset.id),
'enabled': True,
'display_name': line_no_asset.display_name_default or '内部项次',
'required': True,
'normalizer_key': 'integer',
'comparator_key': 'integer',
'validator_keys': ['positive_integer'],
}]
seen: set[str] = set()
enabled_purposes: set[str] = set()
normalized_fields: list[dict[str, Any]] = []
@@ -1241,34 +1246,36 @@ def save_draft(
'on_revalidation_failure': sanitized['on_revalidation_failure'],
}
normalized_fields.append(field_entry)
# line_no 是订单项次系统字段:Schema 必须包含且启用为必填,但不得开放人工编辑或派生配置。
line_no_entries = [item for item in normalized_fields if item.get('field_code') == 'line_no' and item.get('scope') == 'line']
if len(line_no_entries) != 1:
raise ValidationError(
'line_no is required exactly once in schema fields',
code='SHIPPING.ORDER_SCHEMA_LINE_NO_REQUIRED',
)
line_no_entry = line_no_entries[0]
line_no_entry['enabled'] = True
line_no_entry['required'] = True
line_no_entry['auto_create_key_field'] = False
line_no_entry['aliases'] = []
line_no_entry['extraction_instruction'] = None
line_no_entry['task_edit_policy'] = {
'editable': False,
'editable_until': None,
'change_effect': 'none',
'on_revalidation_failure': 'block',
}
if 'auto_creation_policy' in data:
auto_creation_policy = _auto_creation_policy(data.get('auto_creation_policy'))
else:
auto_creation_policy = _resolve_auto_creation_policy_for_definition(
before, fallback=version.schema.auto_creation_policy_json,
)
adopted_line_codes = {
str(item.get('field_code'))
for item in normalized_fields
if isinstance(item, dict) and item.get('enabled', True) and item.get('scope') == 'line'
}
# 保存时未传 derivation_rules 则保留草稿既有规则;缺省时回退关闭预置。
raw_derivation_rules = data['derivation_rules'] if 'derivation_rules' in data else before.get('derivation_rules')
derivation_rules = normalize_derivation_rules(
raw_derivation_rules if raw_derivation_rules is not None else default_derivation_rules(),
adopted_line_field_codes=adopted_line_codes if any(
rule.get('enabled') for rule in (
raw_derivation_rules if isinstance(raw_derivation_rules, list) else default_derivation_rules()
)
) else None,
)
after = {
'schema_code': version.schema.schema_code,
'version': version.version,
'fields': normalized_fields,
'auto_creation_policy': auto_creation_policy,
'derivation_rules': derivation_rules,
'derivation_rules_checksum': derivation_rules_checksum(derivation_rules),
}
compile_table_header_contract(after)
version.definition_json = after
@@ -1334,21 +1341,6 @@ def publish(
enabled_configs = _enabled_fields(definition)
if not enabled_configs:
raise ValidationError('Schema version requires at least one field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
# [STEP] 发布前再次归一化派生规则;启用中的规则要求来源/目标已采用。
adopted_line_codes = {
str(item.get('field_code'))
for item in enabled_configs
if item.get('scope') == 'line' and item.get('field_code')
}
derivation_rules = normalize_derivation_rules(
definition.get('derivation_rules'),
adopted_line_field_codes=adopted_line_codes if any(
isinstance(rule, dict) and rule.get('enabled')
for rule in (definition.get('derivation_rules') or [])
) else None,
)
definition['derivation_rules'] = derivation_rules
definition['derivation_rules_checksum'] = derivation_rules_checksum(derivation_rules)
version.definition_json = definition
included_field_ids = {str(config.get('field_id')) for config in enabled_configs}
previous = ShippingOrderSchemaVersion.query.filter_by(schema_id=version.schema_id, status='published').first()
@@ -1470,134 +1462,11 @@ def simulate_derivation(
actor_id: int | None,
request_id: str | None = None,
) -> dict[str, Any]:
"""
对草稿或已发布 Schema 版本的派生规则做只读样本模拟。
核心逻辑:优先使用请求体 derivation_rules,否则读版本 definition;
lines 可直接提交,或通过 sample_ref=`extraction:<id>` 从历史 Extraction 加载明细投影;
模拟前仅对历史 Extraction 样本剔除规则目标字段,避免已派生结果恒跳过;
手工 JSON 保留目标字段以真实评估 copy_if_empty;
写入 DERIVATION_SIMULATED 审计(不 commit),不改订单。
Args:
version_id: Schema 版本 ID。
data: 含 lines 或 sample_ref(extraction:<id>)、可选 derivation_rules。
actor_id: 管理员 ID。
request_id: 请求追踪 ID。
Returns:
模拟结果摘要与逐行结果。
Raises:
ValidationError: lines / sample_ref 非法。
NotFoundError: 版本或 Extraction 不存在。
"""
from app.models import ShippingOrderExtraction
_, version = _resolve_schema_for_version(version_id)
sample_ref = str(data.get('sample_ref') or '').strip() or None
raw_lines = data.get('lines')
sample_source: dict[str, Any] | None = None
# [STEP] 支持可追溯样本:extraction:<id> → normalized_result_json.lines
# 历史样本可能已含派生后的目标字段;模拟前剔除规则目标,避免 copy_if_empty 恒跳过。
if sample_ref and sample_ref.startswith('extraction:'):
try:
extraction_id = int(sample_ref.split(':', 1)[1])
except (TypeError, ValueError) as exc:
raise ValidationError(
'sample_ref extraction id is invalid',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_INVALID',
) from exc
extraction = db.session.get(ShippingOrderExtraction, extraction_id)
if extraction is None:
raise NotFoundError(
'Derivation sample extraction not found',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_NOT_FOUND',
)
normalized = extraction.normalized_result_json if isinstance(extraction.normalized_result_json, dict) else {}
loaded = list(normalized.get('lines') or [])
if not loaded or any(not isinstance(item, dict) for item in loaded):
raise ValidationError(
'extraction sample has no usable line projections',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SAMPLE_EMPTY',
)
raw_lines = loaded
sample_source = {
'kind': 'extraction',
'extraction_id': int(extraction.id),
'schema_version_id': int(extraction.schema_version_id),
'intake_id': int(extraction.intake_id),
'status': extraction.status,
'targets_stripped_for_simulate': True,
}
if not isinstance(raw_lines, list) or any(not isinstance(item, dict) for item in raw_lines):
raise ValidationError(
'lines must be a list of objects (or provide sample_ref=extraction:<id>)',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_SIMULATE_INVALID',
)
definition = _definition(version)
rules = data.get('derivation_rules') if 'derivation_rules' in data else definition.get('derivation_rules')
normalized_rules = normalize_derivation_rules(rules if isinstance(rules, list) else None)
# 仅历史 Extraction 样本剔除目标字段;手工 JSON 保留原值以真实评估 copy_if_empty。
strip_targets = bool(sample_source and sample_source.get('targets_stripped_for_simulate'))
if strip_targets:
target_codes = {
str(rule.get('target_field_code') or '')
for rule in normalized_rules
if rule.get('target_field_code')
}
simulate_lines = []
for line in raw_lines:
cleaned = dict(line)
for code in target_codes:
cleaned.pop(code, None)
simulate_lines.append(cleaned)
else:
simulate_lines = [dict(line) for line in raw_lines]
outcome = apply_derivation_rules_to_lines(simulate_lines, normalized_rules)
append_shipping_audit_event(
event_type='DERIVATION_SIMULATED',
aggregate_type='shipping_order_schema_version',
aggregate_id=str(version.id),
actor_type='admin',
actor_id=actor_id,
request_id=request_id,
action='simulate_derivation',
result='success',
metadata={
'schema_version': version.version,
'schema_version_status': version.status,
'derivation_rules_checksum': outcome['rules_checksum'],
'derived_count': outcome['derived_count'],
'skipped_count': outcome['skipped_count'],
'sample_ref': sample_ref,
'sample_source': sample_source,
'line_count': len(raw_lines),
},
after={
'derivation_rules_checksum': outcome['rules_checksum'],
'derived_count': outcome['derived_count'],
'skipped_count': outcome['skipped_count'],
'sample_ref': sample_ref,
},
"""派生规则已硬切换下线;项次由系统生成,接口统一返回业务错误。"""
raise ValidationError(
'Schema derivation is disabled; line_no is system-generated',
code='SHIPPING.ORDER_SCHEMA_DERIVATION_DISABLED',
)
# 不在此 commit:由路由层统一提交,便于与样本读取等审计同事务。
return {
'schema_version_id': version.id,
'schema_version': version.version,
'schema_version_status': version.status,
'rules_checksum': outcome['rules_checksum'],
'rules': outcome['rules'],
'derived_count': outcome['derived_count'],
'skipped_count': outcome['skipped_count'],
'results': outcome['results'],
'lines_after': outcome['lines'],
'sample_ref': sample_ref,
'sample_source': sample_source,
'mutates_orders': False,
}
def list_derivation_simulate_samples(*, limit: int = 20) -> dict[str, Any]:
@@ -1637,4 +1506,4 @@ def list_derivation_simulate_samples(*, limit: int = 20) -> dict[str, Any]:
})
if len(items) >= capped:
break
return {'items': items}
return {'items': items}
@@ -18,7 +18,7 @@ from app.core.errors import ValidationError
TABLE_FIELD_CODES = frozenset({
'line_no', 'reservation_id', 'part_number', 'product_revision', 'customer_part_number',
'reservation_id', 'part_number', 'product_revision', 'customer_part_number',
'customer_po_line_no', 'product_feature', 'qty', 'uom', 'reference_qty', 'reference_uom',
'pricing_qty', 'pricing_uom', 'required_date', 'requested_receipt_date', 'unit_price',
'line_amount_before_tax', 'line_tax_amount', 'line_amount_with_tax', 'tax_category', 'tax_rate',
@@ -36,10 +36,16 @@ class TableHeaderContract:
def normalize_table_header(value: Any) -> str:
"""以 NFKC 和标点空白折叠生成严格大小写的 Schema v1 表头键。"""
# Schema v1 treats case as business data: ``Part No`` and ``PART NO`` are
# distinct configured labels, so a permissive match cannot silently bind a column.
"""以 NFKC 和标点空白折叠生成严格大小写的 Schema v1 表头键。
Schema v1 treats case as business data: ``Part No`` and ``PART NO`` are
distinct configured labels, so a permissive match cannot silently bind a column.
额外把 camelCase 相邻词拆出空格(``manufacturerPN`` -> ``manufacturer PN``),
使真实邮件/PDF 表头 ``manufacturerPN`` 能命中 Schema 的 ``Manufacturer PN`` 别名。
"""
text = unicodedata.normalize('NFKC', str(value or '')).strip()
# 在「小写/数字 后紧接大写」的边界插入空格,处理无分隔符的驼峰表头。
text = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", ' ', text)
text = re.sub(r"[^\w\u4e00-\u9fff]+", ' ', text, flags=re.UNICODE)
return re.sub(r'[_\s]+', ' ', text).strip()
@@ -474,10 +474,16 @@ def ensure_stp_auto_create_for_case(
),
}
# [STEP] failed/dead 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。
# [STEP] failed 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。
from app.services.shipping_notice.order_review_workbench_projection import (
project_job_status_outcome,
)
latest = find_latest_stp_job(business_ref=idempotency_key)
retry_of_job_id = None
if latest is not None and str(latest.status or '') in {'failed', 'dead', 'cancelled'}:
latest_status = str(getattr(latest, 'status', None) or '').strip().lower() if latest is not None else ''
if latest is not None and (
project_job_status_outcome(latest_status) == 'failed' or latest_status == 'cancelled'
):
retry_of_job_id = int(latest.id)
elif force_retry and latest is not None:
retry_of_job_id = int(latest.id)
Loaded 100 of 812 files, more files were not shown because too many files have changed in this diff. Show more