test(shipping): 更新订单复核库存与通知流程测试
This commit is contained in:
1 parent
8ec028e6a3
commit
265a6e179a
168 files changed
+9420
-4613
No files matched your search
@@ -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(
|
||||
|
||||
@@ -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,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
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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 in {'uploaded', 'succeeded', 'success'}:
|
||||
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)))
|
||||
|
||||
@@ -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', '多库存文件结果冲突'),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -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', [])
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -309,9 +309,58 @@ def _bound_sample_document(profile_id: int, document_id: int) -> ShippingOrderDo
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if document is None:
|
||||
raise NotFoundError('Order profile sample not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
_repair_bound_sample_asset(document)
|
||||
return document
|
||||
|
||||
|
||||
def _repair_bound_sample_asset(document: ShippingOrderDocument) -> None:
|
||||
"""补偿历史样本资产引用,避免已绑定的标注样本按临时 TTL 过期。"""
|
||||
if not document.asset_id:
|
||||
return
|
||||
asset = db.session.get(FileAsset, int(document.asset_id))
|
||||
if asset is None:
|
||||
return
|
||||
if str(asset.lifecycle_status or '') == 'temporary' and int(asset.reference_count or 0) == 0:
|
||||
from app.services.file_assets.service import mark_asset_referenced
|
||||
|
||||
mark_asset_referenced(asset)
|
||||
|
||||
|
||||
def _retain_profile_sample_assets(profile_id: int, *, asset_ids: set[int] | None = None) -> int:
|
||||
"""为新增 Profile 样本引用的每个唯一文件资产建立一份引用。"""
|
||||
from app.services.file_assets.service import mark_asset_referenced
|
||||
|
||||
ids = set(asset_ids or ())
|
||||
for asset_id in sorted(ids):
|
||||
asset = db.session.get(FileAsset, asset_id)
|
||||
if asset is not None:
|
||||
mark_asset_referenced(asset)
|
||||
return len(ids)
|
||||
|
||||
|
||||
def _release_profile_sample_asset_if_unreferenced(profile_id: int, document_id: int) -> None:
|
||||
"""删除样本绑定后,仅当该 Profile 不再引用文件时释放资产引用。"""
|
||||
document = db.session.get(ShippingOrderDocument, int(document_id))
|
||||
if document is None or not document.asset_id:
|
||||
return
|
||||
still_bound = (
|
||||
db.session.query(ShippingOrderDocumentProfileSample)
|
||||
.join(ShippingOrderDocument, ShippingOrderDocument.id == ShippingOrderDocumentProfileSample.document_id)
|
||||
.filter(
|
||||
ShippingOrderDocumentProfileSample.profile_id == int(profile_id),
|
||||
ShippingOrderDocument.asset_id == int(document.asset_id),
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if still_bound is not None:
|
||||
return
|
||||
asset = db.session.get(FileAsset, int(document.asset_id))
|
||||
if asset is not None and int(asset.reference_count or 0) > 0:
|
||||
from app.services.file_assets.service import release_asset_reference
|
||||
|
||||
release_asset_reference(asset)
|
||||
|
||||
|
||||
def _preview_grant_store() -> Any:
|
||||
"""?????????????? Redis????????????????"""
|
||||
return preview_grant_store()
|
||||
@@ -1461,6 +1510,11 @@ def add_profile_sample(
|
||||
if document is None:
|
||||
raise NotFoundError('Order profile sample document not found', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_NOT_FOUND')
|
||||
_document_layout(document)
|
||||
existing_asset_ids = {
|
||||
int(existing_document.asset_id)
|
||||
for existing in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all()
|
||||
if (existing_document := db.session.get(ShippingOrderDocument, int(existing.document_id))) is not None and existing_document.asset_id
|
||||
}
|
||||
sample = ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id, document_id=document.id,
|
||||
table_id=str(table_id).strip() or None, sample_role=role, created_by_id=actor_id,
|
||||
@@ -1472,6 +1526,8 @@ def add_profile_sample(
|
||||
db.session.rollback()
|
||||
raise ConflictError('Profile sample already exists', code='SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_CONFLICT') from exc
|
||||
_refresh_training_sample_count(profile)
|
||||
if document.asset_id and int(document.asset_id) not in existing_asset_ids:
|
||||
_retain_profile_sample_assets(profile.id, asset_ids={int(document.asset_id)})
|
||||
clear_matching_signature_refs(profile, actor_id=actor_id, reason='sample_added')
|
||||
_audit(profile_id=profile.id, document_id=document.id, event_type='profile_sample_added', actor_id=actor_id, detail={
|
||||
'sample_role': role, 'has_table_binding': sample.table_id is not None,
|
||||
@@ -1494,6 +1550,7 @@ def remove_profile_sample(profile_id: int, sample_id: int, *, actor_id: int | No
|
||||
sample_role = sample.sample_role
|
||||
db.session.delete(sample)
|
||||
db.session.flush()
|
||||
_release_profile_sample_asset_if_unreferenced(profile.id, document_id)
|
||||
_refresh_training_sample_count(profile)
|
||||
clear_matching_signature_refs(profile, actor_id=actor_id, reason='sample_removed')
|
||||
_audit(profile_id=profile.id, document_id=document_id, event_type='profile_sample_removed', actor_id=actor_id, detail={
|
||||
@@ -1668,7 +1725,9 @@ def refresh_profile_sample_readiness(
|
||||
# not merely a repeated read of the same frozen sample.
|
||||
sample.evidence_frozen_at = datetime.utcnow() if changed else sample.evidence_frozen_at
|
||||
sample.source_filename_snapshot = str(document.filename or '').strip() or None
|
||||
sample.page_count_snapshot = _layout_page_count(version.payload_json or {})
|
||||
# [STEP 1] 页数必须来自已加载的完整坐标证据;持久化 payload 可能仅保留外置证据引用,
|
||||
# 不能退化为“有业务表格的页数”。
|
||||
sample.page_count_snapshot = _layout_page_count(layout)
|
||||
sample.table_identity_snapshot = _layout_table_identity_snapshot(version.payload_json or {}, table_id)
|
||||
if changed:
|
||||
_audit(
|
||||
@@ -1860,7 +1919,8 @@ def _freeze_profile_sample_evidence(profile: ShippingOrderDocumentProfile, *, fr
|
||||
sample.parser_version = str(layout_version.parser_version or '').strip() or None
|
||||
sample.evidence_frozen_at = frozen_at
|
||||
sample.source_filename_snapshot = str(document.filename or '').strip() or None
|
||||
sample.page_count_snapshot = _layout_page_count(layout_version.payload_json or {})
|
||||
# [STEP 1] 发布冻结使用已加载的外置坐标证据,保证页数与原 PDF 物理页一致。
|
||||
sample.page_count_snapshot = _layout_page_count(hydrated_layout)
|
||||
sample.table_identity_snapshot = _layout_table_identity_snapshot(
|
||||
layout_version.payload_json or {}, sample.table_id,
|
||||
)
|
||||
@@ -1914,7 +1974,8 @@ def _retain_frozen_sample_assets(profile: ShippingOrderDocumentProfile) -> int:
|
||||
'Profile sample file asset is unavailable',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
mark_asset_referenced(asset)
|
||||
if str(asset.lifecycle_status or '') == 'temporary' and int(asset.reference_count or 0) == 0:
|
||||
mark_asset_referenced(asset)
|
||||
retained_asset_ids.add(asset_id)
|
||||
return len(retained_asset_ids)
|
||||
|
||||
@@ -3217,9 +3278,12 @@ def create_draft_from_sample(
|
||||
profile_id=saved['id'], document_id=document.id, table_id=None,
|
||||
sample_role='annotation', created_by_id=actor_id,
|
||||
))
|
||||
db.session.flush()
|
||||
_audit(profile_id=saved['id'], document_id=document.id, event_type='profile_sample_added', actor_id=actor_id, detail={
|
||||
'sample_role': 'annotation', 'has_table_binding': False,
|
||||
})
|
||||
if document.asset_id:
|
||||
_retain_profile_sample_assets(saved['id'], asset_ids={int(document.asset_id)})
|
||||
db.session.commit()
|
||||
return saved
|
||||
|
||||
@@ -3505,6 +3569,8 @@ def save_draft(
|
||||
# readiness audit records sample_id; assign it within this outer save transaction
|
||||
# before the shared evidence-freeze service is invoked.
|
||||
db.session.flush()
|
||||
if annotation_document.asset_id:
|
||||
_retain_profile_sample_assets(profile.id, asset_ids={int(annotation_document.asset_id)})
|
||||
layout = _document_layout(annotation_document)
|
||||
if not any(
|
||||
isinstance(item, dict) and str(item.get('table_id') or '') == visual_main_table_id
|
||||
@@ -3945,6 +4011,9 @@ def create_schema_migration_draft(
|
||||
)
|
||||
db.session.add(clone)
|
||||
db.session.flush()
|
||||
# 迁移草稿会随源 Profile 拷贝标注/训练样本;新样本引用同一批文档资产,
|
||||
# 必须为这些资产建立引用,避免它们被临时清理回收。
|
||||
copied_asset_ids: set[int] = set()
|
||||
for sample in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=source.id).all():
|
||||
if sample.sample_role not in {'annotation', 'training'}:
|
||||
continue
|
||||
@@ -3955,6 +4024,11 @@ def create_schema_migration_draft(
|
||||
sample_role=sample.sample_role,
|
||||
created_by_id=actor_id,
|
||||
))
|
||||
document = db.session.get(ShippingOrderDocument, int(sample.document_id))
|
||||
if document is not None and document.asset_id:
|
||||
copied_asset_ids.add(int(document.asset_id))
|
||||
db.session.flush()
|
||||
_retain_profile_sample_assets(clone.id, asset_ids=copied_asset_ids)
|
||||
_refresh_training_sample_count(clone)
|
||||
# A migration is a new editable baseline, not a continuation of the source's revisions.
|
||||
# This keeps restore and publish-check workflows scoped to the target Schema snapshot.
|
||||
@@ -4095,6 +4169,7 @@ def publish(
|
||||
profile=profile,
|
||||
draft_checksum=draft_checksum,
|
||||
published_checksum=str(profile.checksum or ''),
|
||||
actor_id=actor_id,
|
||||
)
|
||||
profile.status = 'published'
|
||||
profile.published_by_id = actor_id
|
||||
@@ -4161,7 +4236,19 @@ def delete_draft(profile_id: int) -> None:
|
||||
db.session.delete(suite)
|
||||
if suites:
|
||||
db.session.flush()
|
||||
# [STEP 3] ???? Profile ????????? DB CASCADE?
|
||||
# [STEP 3] 删除 Profile 前释放其样本资产引用;同一资产在本 Profile 内只释放一次。
|
||||
asset_ids = {
|
||||
int(document.asset_id)
|
||||
for sample in ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).all()
|
||||
if (document := db.session.get(ShippingOrderDocument, int(sample.document_id))) is not None and document.asset_id
|
||||
}
|
||||
for asset_id in asset_ids:
|
||||
asset = db.session.get(FileAsset, asset_id)
|
||||
if asset is not None and int(asset.reference_count or 0) > 0:
|
||||
from app.services.file_assets.service import release_asset_reference
|
||||
|
||||
release_asset_reference(asset)
|
||||
# [STEP 4] ???? Profile ????????? DB CASCADE?
|
||||
db.session.delete(profile)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
@@ -881,20 +897,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 +954,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 (
|
||||
|
||||
@@ -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
|
||||
# [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,
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -80,6 +80,68 @@ def _canonical_values(fields: Any, code: str, codes: dict[str, str], config: dic
|
||||
}
|
||||
|
||||
|
||||
def _canonical_values_span(
|
||||
fields: Any, span_codes: set[str], ids: dict[str, str], configs: dict[str, dict[str, Any]],
|
||||
) -> set[Any]:
|
||||
"""收集字段跨多个同订单料号身份 code 的规范值集合(件号/客户件号交叉)。
|
||||
|
||||
与匹配层 `part_number ∪ customer_part_number` 的裁决保持一致:邮件补充的 PN 列
|
||||
值可能实为客户件号(MPN),只要命中 PDF 的任一料号身份就视为同一料号,
|
||||
禁止把「邮件 PN = PDF 客户件号」判成 `part_number` 字段冲突。
|
||||
|
||||
Args:
|
||||
fields: 目标字段 Observation 列表(header 或 line)。
|
||||
span_codes: 视作同一身份的字段 code 集合(如 {'part_number','customer_part_number'})。
|
||||
ids: {field_code: field_id} 映射。
|
||||
configs: {field_code: 冻结 Schema 配置} 映射,用于各字段独立标准化。
|
||||
|
||||
Returns:
|
||||
跨这些 code 收集到的规范值集合。
|
||||
"""
|
||||
if not isinstance(fields, list):
|
||||
return set()
|
||||
code_by_id = {str(field_id): code for code, field_id in ids.items()}
|
||||
out: set[Any] = set()
|
||||
for field in fields:
|
||||
if not isinstance(field, dict):
|
||||
continue
|
||||
code = code_by_id.get(str(field.get('field_id') or ''))
|
||||
if code not in span_codes:
|
||||
continue
|
||||
config = configs.get(code)
|
||||
if config is None:
|
||||
continue
|
||||
for observation in field.get('observations') or []:
|
||||
if isinstance(observation, dict) and observation.get('value') not in (None, ''):
|
||||
out.add(_canonical_field_value(observation.get('value'), config))
|
||||
return out
|
||||
|
||||
|
||||
# 采购单号类字段:跨来源比较须与匹配层一致,用 PO 专用标准化(含前导零归一),
|
||||
# 否则 0060208010 与 60208010 会被 Schema「lowercase_trim」误判为不同 PO 而制造冲突。
|
||||
_PO_CODES = {'customer_po_number', 'po_number'}
|
||||
|
||||
|
||||
def _conflict_canonical(value: Any, field_code: str, config: dict[str, Any]) -> Any:
|
||||
"""返回冲突比较用的字段规范值;PO 类字段复用 PO 标准化,其余走 Schema 正常化。"""
|
||||
if field_code in _PO_CODES:
|
||||
return normalize_atomic_po_number(value).upper()
|
||||
return _canonical_field_value(value, config)
|
||||
|
||||
|
||||
def _conflict_canonical_values(fields: Any, code: str, codes: dict[str, str], config: dict[str, Any]) -> set[Any]:
|
||||
"""收集字段冲突比较用的规范值集合;PO 类字段使用 _conflict_canonical。"""
|
||||
if not isinstance(fields, list):
|
||||
return set()
|
||||
return {
|
||||
_conflict_canonical(observation.get('value'), code, config)
|
||||
for field in fields if isinstance(field, dict)
|
||||
if codes.get(str(field.get('field_id') or '')) == code
|
||||
for observation in field.get('observations') or [] if isinstance(observation, dict)
|
||||
if observation.get('value') not in (None, '')
|
||||
}
|
||||
|
||||
|
||||
def _field_observations(fields: Any, code: str, codes: dict[str, str]) -> list[dict[str, Any]]:
|
||||
"""返回字段的原始 Observation,供冲突 Finding 保留 PDF 侧可追溯证据。"""
|
||||
if not isinstance(fields, list):
|
||||
@@ -125,14 +187,21 @@ def _supplement_field_conflict(
|
||||
{
|
||||
'source_type': 'pdf',
|
||||
'raw_value': str(pdf_raw),
|
||||
'canonical_value': str(_canonical_field_value(pdf_raw, config)),
|
||||
'canonical_value': str(_conflict_canonical(pdf_raw, field_code, config)),
|
||||
'document_id': pdf.get('document_id'),
|
||||
'evidence_ref': dict(pdf.get('evidence_ref') or {}),
|
||||
# evidence_ref 必须保持 dict 契约(review/evidence 消费方按 dict 处理)。
|
||||
# 坐标 observation 的 evidence_ref 是字符串、layout_evidence 才是证据 dict;
|
||||
# 直接用 dict(<字符串>) 会把字符串按字符拆成长度1序列而崩(dictionary update length 1)。
|
||||
'evidence_ref': (
|
||||
pdf.get('layout_evidence')
|
||||
if isinstance(pdf.get('layout_evidence'), dict)
|
||||
else (pdf.get('evidence_ref') if isinstance(pdf.get('evidence_ref'), dict) else {})
|
||||
),
|
||||
},
|
||||
{
|
||||
'source_type': 'email_body',
|
||||
'raw_value': str(email_raw),
|
||||
'canonical_value': str(_canonical_field_value(email_raw, config)),
|
||||
'canonical_value': str(_conflict_canonical(email_raw, field_code, config)),
|
||||
'document_id': email_document_id or None,
|
||||
'evidence_ref': dict(email_evidence or {}),
|
||||
},
|
||||
@@ -162,7 +231,7 @@ def _supplement_multi_value_conflict(
|
||||
sources.append({
|
||||
'source_type': 'email_body',
|
||||
'raw_value': raw_value,
|
||||
'canonical_value': str(_canonical_field_value(raw_value, config)),
|
||||
'canonical_value': str(_conflict_canonical(raw_value, field_code, config)),
|
||||
'document_id': email_document_id or None,
|
||||
'evidence_ref': dict(evidence or {}),
|
||||
})
|
||||
@@ -271,7 +340,7 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
raw_value = str(item.get(target_code) or '').strip()
|
||||
if raw_value:
|
||||
value_by_canonical.setdefault(
|
||||
_canonical_field_value(raw_value, config),
|
||||
_conflict_canonical(raw_value, target_code, config),
|
||||
(raw_value, item),
|
||||
)
|
||||
values = {raw_value for raw_value, _ in value_by_canonical.values()}
|
||||
@@ -292,13 +361,23 @@ def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_inta
|
||||
field_id = ids.get(target_code)
|
||||
if not value or not field_id:
|
||||
continue
|
||||
existing_values = _canonical_values(
|
||||
same_code_values = _conflict_canonical_values(
|
||||
fields, target_code, {v: k for k, v in ids.items()}, config,
|
||||
)
|
||||
if existing_values:
|
||||
if same_code_values:
|
||||
# PDF 是主证据,但正文给出不同的唯一 Schema 值也不能被静默忽略:
|
||||
# 保留 PDF 值,强制进入 Review 由人工裁决。
|
||||
if existing_values != {_canonical_field_value(value, config)}:
|
||||
email_canonical = _conflict_canonical(value, target_code, config)
|
||||
if target_code in part_codes:
|
||||
# 件号/客户件号属同一料号身份:邮件值命中任一 PDF 料号即视为一致,
|
||||
# 不因「邮件 PN 实为客户件号(MPN)」制造误判 `part_number` 冲突。
|
||||
conflicts_with_pdf = (
|
||||
email_canonical
|
||||
not in _canonical_values_span(fields, part_codes, ids, configs)
|
||||
)
|
||||
else:
|
||||
conflicts_with_pdf = same_code_values != {email_canonical}
|
||||
if conflicts_with_pdf:
|
||||
conflict = _supplement_field_conflict(
|
||||
field_code=target_code,
|
||||
config=config,
|
||||
|
||||
@@ -9,7 +9,7 @@ backend/app/services/shipping_notice/order_task_service.py
|
||||
局部重识别走 replace_order_task_candidate_after_reparse(专用审计);
|
||||
sync_order_task_processing_state 统一写入 stage/status、递增 progress_version,
|
||||
并强制写 order_task_progress_changed 审计;
|
||||
建单成功后按 candidate_id 定位 OT 再挂 shipping_notice_id(禁止误用 Run 根号串单);
|
||||
正式 ShippingNotice 通过 order_task_id 关联 OT;OT 不反向保存通知单指针。
|
||||
GET 投影只读本表,禁止读路径创建。
|
||||
"""
|
||||
|
||||
@@ -146,7 +146,6 @@ def sync_order_task_processing_state(
|
||||
},
|
||||
metadata={
|
||||
'extraction_run_id': getattr(order_task, 'extraction_run_id', None),
|
||||
'shipping_notice_id': getattr(order_task, 'shipping_notice_id', None),
|
||||
'candidate_id': getattr(order_task, 'candidate_id', None),
|
||||
},
|
||||
source=str(source or 'order_task_service'),
|
||||
@@ -442,11 +441,6 @@ def replace_order_task_candidate_after_review(
|
||||
'order task candidate binding changed concurrently',
|
||||
code='SHIPPING_NOTICE.ORDER_TASK_CANDIDATE_MISMATCH',
|
||||
)
|
||||
if order_task.shipping_notice_id is not None:
|
||||
raise ConflictError(
|
||||
'order task already linked to a shipping notice',
|
||||
code='SHIPPING_NOTICE.ORDER_TASK_ALREADY_LINKED',
|
||||
)
|
||||
|
||||
case_document_id = int(case.document_id) if getattr(case, 'document_id', None) else None
|
||||
new_document_id = (
|
||||
@@ -938,7 +932,7 @@ def resolve_order_task_for_candidate(candidate_id: int | None) -> Optional[Shipp
|
||||
|
||||
def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional[ShippingOrderTask]:
|
||||
"""
|
||||
建单成功后双向挂接 OT ↔ Notice。
|
||||
将正式 Notice 单向挂接到 OT。
|
||||
|
||||
Args:
|
||||
order_task_no: OT 编号(须为该 Candidate 自己的 OT,禁止误用 Run 根号)。
|
||||
@@ -957,15 +951,7 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
before = {
|
||||
'shipping_notice_id': row.shipping_notice_id,
|
||||
'candidate_id': row.candidate_id,
|
||||
}
|
||||
# 兼容字段只在首张 Notice 尚未建立时回填,后续分批 Notice 以
|
||||
# ShippingNotice.order_task_id 的多对一关系为权威,禁止覆盖首条指针。
|
||||
if row.shipping_notice_id is None:
|
||||
row.shipping_notice_id = int(notice_id)
|
||||
row.updated_at = datetime.utcnow()
|
||||
before = {'candidate_id': row.candidate_id}
|
||||
from app.models import ShippingNotice
|
||||
|
||||
notice = db.session.get(ShippingNotice, int(notice_id))
|
||||
@@ -985,7 +971,6 @@ def link_notice_to_order_task(*, order_task_no: str, notice_id: int) -> Optional
|
||||
reason_code='notice_created',
|
||||
before=before,
|
||||
after={
|
||||
'shipping_notice_id': row.shipping_notice_id,
|
||||
'candidate_id': row.candidate_id,
|
||||
'notice_task_no': str(getattr(notice, 'task_no', None) or '') or None,
|
||||
},
|
||||
|
||||
@@ -292,11 +292,19 @@ def sync_order_task_stage_for_candidate(
|
||||
return None
|
||||
# 正式建单后的 Candidate 仍可能因恢复/对账再次触发资格重算;
|
||||
# 此时建单前资格阶段不再是权威事实,禁止覆盖 OT 当前履约阶段。
|
||||
if (
|
||||
getattr(candidate, 'consumed_task_id', None) is not None
|
||||
or getattr(ot, 'shipping_notice_id', None) is not None
|
||||
):
|
||||
if getattr(candidate, 'consumed_task_id', None) is not None:
|
||||
return ot
|
||||
# 已挂正式通知单:以 Notice→OT(ShippingNotice.order_task_id)反向关联为准,
|
||||
# OT 本身不保存通知单指针。只要已有任意 Notice 指向该 OT,即说明 OT 已进入
|
||||
# 履约阶段,建单前资格阶段不再是权威事实:原样返回,禁止回退到确认前 stage。
|
||||
if getattr(ot, 'id', None) is not None:
|
||||
bound_notice = (
|
||||
ShippingNotice.query
|
||||
.filter(ShippingNotice.order_task_id == int(ot.id))
|
||||
.first()
|
||||
)
|
||||
if bound_notice is not None:
|
||||
return ot
|
||||
stage, status = resolve_pre_confirm_stage(
|
||||
candidate=candidate,
|
||||
evaluation=evaluation,
|
||||
@@ -328,7 +336,7 @@ def sync_order_task_stage_for_notice(
|
||||
|
||||
Args:
|
||||
notice: 正式发货通知。
|
||||
order_task: 可选;缺省按 notice.order_task_id / ShippingOrderTask.shipping_notice_id。
|
||||
order_task: 可选;缺省按 notice.order_task_id 反查 OT。
|
||||
|
||||
Returns:
|
||||
更新后的 OT;找不到时 None。
|
||||
@@ -340,18 +348,13 @@ def sync_order_task_stage_for_notice(
|
||||
ot = order_task
|
||||
if ot is None and getattr(notice, 'order_task_id', None):
|
||||
ot = db.session.get(ShippingOrderTask, int(notice.order_task_id))
|
||||
if ot is None and getattr(notice, 'id', None):
|
||||
ot = (
|
||||
ShippingOrderTask.query.filter_by(shipping_notice_id=int(notice.id))
|
||||
.order_by(ShippingOrderTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
if ot is None:
|
||||
return None
|
||||
status, stage = map_notice_to_processing_status_stage(notice)
|
||||
# [STEP] Execution.current_gate_code 是正式履约事实,优先于尚未来得及写入 Notice
|
||||
# 领域字段的默认映射;只接受 active/waiting_external/blocked 执行,避免旧 Execution 回退 OT。
|
||||
active_execution_id = getattr(notice, 'active_process_execution_id', None)
|
||||
# ProcessExecution 属于 OT;正式 Notice 不保存执行指针。
|
||||
active_execution_id = getattr(ot, 'active_process_execution_id', None)
|
||||
if active_execution_id is not None:
|
||||
from app.models import ShippingProcessExecution
|
||||
|
||||
@@ -359,9 +362,16 @@ def sync_order_task_stage_for_notice(
|
||||
execution_status = str(getattr(execution, 'status', None) or '').strip().lower()
|
||||
gate_code = str(getattr(execution, 'current_gate_code', None) or '').strip().lower()
|
||||
gate_stage = _PROCESS_GATE_TO_PROCESSING_STAGE.get(gate_code)
|
||||
if execution_status in {'active', 'waiting_external', 'blocked'} and gate_stage:
|
||||
# [FIX] current_gate_code 是正式履约事实。即使 execution.status 仍为 completed
|
||||
# (历史遗留旧值或 Gate 状态在 `_refresh_execution_pointers` 刷新前被旁路写成
|
||||
# blocked),只要 current_gate_code 仍指向一个未通过 Gate,就不能让 OT.stage 滞留
|
||||
# completed 而与实际卡住环节矛盾:据此把该 Gate 阶段回写,并落 blocked。
|
||||
if gate_stage and execution_status in {'active', 'waiting_external', 'blocked'}:
|
||||
stage = gate_stage
|
||||
status = 'automating' if execution_status in {'active', 'waiting_external'} else 'blocked'
|
||||
elif gate_stage and execution_status == 'completed':
|
||||
stage = gate_stage
|
||||
status = 'blocked'
|
||||
if stage not in SHIPPING_PROCESSING_STAGES:
|
||||
stage = 'inventory_matching'
|
||||
return sync_order_task_processing_state(
|
||||
|
||||
@@ -22,6 +22,7 @@ _ATOMIC_PO_NUMBER_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9\-_/]*")
|
||||
def normalize_po_number(value: Any) -> str:
|
||||
"""
|
||||
标准化采购单号;Wistron 等客户原文常带 ZNB 前缀(如 ZNB16754796 / ZNB-16754796),输出为纯数字段。
|
||||
纯数字 PO 前导零视为格式差异(0060208010 与 60208010 是同一张 PO),统一剥除,避免跨来源误判冲突。
|
||||
"""
|
||||
text = str(value or "").strip()
|
||||
if not text:
|
||||
@@ -32,8 +33,8 @@ def normalize_po_number(value: Any) -> str:
|
||||
if upper.startswith("ZNB") and len(text) > 3:
|
||||
tail = text[3:].strip().lstrip("-_/ ")
|
||||
if tail.isdigit():
|
||||
return tail
|
||||
return text
|
||||
return tail.lstrip("0") or "0"
|
||||
return text.lstrip("0") or "0"
|
||||
|
||||
|
||||
def normalize_atomic_po_number(value: Any) -> str:
|
||||
|
||||
@@ -89,11 +89,17 @@ def _target_is_safe(task: ShippingNotice) -> bool:
|
||||
|
||||
核心逻辑:与历史 open_existing Reservation 回填安全边界保持一致,避免已推进任务被静默改写。
|
||||
"""
|
||||
if str(task.pending_human_reason or '').strip().lower() != PH_RSV_REQ:
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
|
||||
if str(task_blocking_reason(task) or '').strip().lower() != PH_RSV_REQ:
|
||||
return False
|
||||
if task.inventory_lines_json or task.line_results_json or task.export_file_path or task.freight_ref_no:
|
||||
return False
|
||||
if task.match_status or task.upload_status:
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
current_inventory_matches_for_task,
|
||||
has_ready_inventory_file_for_task,
|
||||
)
|
||||
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt
|
||||
if has_ready_inventory_file_for_task(task) or current_inventory_matches_for_task(task) or latest_export_artifact(task) is not None or latest_upload_attempt(task) is not None:
|
||||
return False
|
||||
return True
|
||||
|
||||
@@ -334,7 +340,7 @@ def apply_candidate_reconciliation_plan(
|
||||
],
|
||||
}
|
||||
step_payload['field_conflicts'] = {'open_count': len(open_rows)}
|
||||
task.step_payload_json = step_payload
|
||||
task.step_payload_json = (step_payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'}})
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
return {
|
||||
'status': 'conflicted',
|
||||
@@ -385,7 +391,7 @@ def apply_candidate_reconciliation_plan(
|
||||
step_payload.pop('process_field_gate', None)
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
task.error_message = None
|
||||
task.step_payload_json = step_payload
|
||||
task.step_payload_json = (step_payload if task.__class__.__name__ != 'ShippingOrderTask' else {key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'}})
|
||||
return {
|
||||
'status': 'applied',
|
||||
'reason': 'fields_backfilled',
|
||||
|
||||
@@ -19,12 +19,17 @@ from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingExportArtifact,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderTask,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNotice,
|
||||
ShippingTaskEvent,
|
||||
ShippingTaskInventoryLink,
|
||||
ShippingTaskPurgeAudit,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
)
|
||||
from app.models.shipping_task_line import ShippingTaskFieldConflict
|
||||
|
||||
TaskDispositionAction = Literal['delete', 'void', 'archive', 'restore']
|
||||
|
||||
@@ -43,7 +48,7 @@ class TaskDispositionCapability:
|
||||
reason: str | None = None
|
||||
|
||||
|
||||
def task_is_active(task: ShippingNotice) -> bool:
|
||||
def task_is_active(task: ShippingNotice | ShippingOrderTask) -> bool:
|
||||
"""
|
||||
判断任务是否仍可触发履约副作用。
|
||||
|
||||
@@ -61,7 +66,7 @@ def task_is_active(task: ShippingNotice) -> bool:
|
||||
)
|
||||
|
||||
|
||||
def task_execution_block_reason(task: ShippingNotice) -> str | None:
|
||||
def task_execution_block_reason(task: ShippingNotice | ShippingOrderTask) -> str | None:
|
||||
"""
|
||||
为异步编排和外部回调提供统一的副作用熔断原因。
|
||||
|
||||
@@ -79,7 +84,7 @@ def task_execution_block_reason(task: ShippingNotice) -> str | None:
|
||||
return f'task_lifecycle_{lifecycle or "inactive"}'
|
||||
|
||||
|
||||
def load_task_for_disposition(task_no: str) -> ShippingNotice:
|
||||
def load_task_for_disposition(task_no: str) -> ShippingNotice | ShippingOrderTask:
|
||||
"""
|
||||
以行锁加载任务,供同一事务内重新判定并写入处置结果。
|
||||
|
||||
@@ -97,27 +102,29 @@ def load_task_for_disposition(task_no: str) -> ShippingNotice:
|
||||
if not normalized_task_no:
|
||||
raise ValidationError('task_no is required', code='SHIPPING.TASK_NO_REQUIRED')
|
||||
task = (
|
||||
ShippingNotice.query
|
||||
.filter(ShippingNotice.task_no == normalized_task_no)
|
||||
.with_for_update()
|
||||
.first()
|
||||
ShippingOrderTask.query.filter(ShippingOrderTask.task_no == normalized_task_no)
|
||||
.with_for_update().first()
|
||||
)
|
||||
if task is None:
|
||||
task = ShippingOrderTask.query.filter(ShippingOrderTask.task_no == normalized_task_no).with_for_update().first()
|
||||
if task is None:
|
||||
raise NotFoundError('Shipping task not found', code='SHIPPING.TASK_NOT_FOUND')
|
||||
return task
|
||||
|
||||
|
||||
def _has_external_fulfillment(task: ShippingNotice) -> bool:
|
||||
def _has_external_fulfillment(task: ShippingNotice | ShippingOrderTask) -> bool:
|
||||
"""识别已提交、正在提交或已有外部上传参考的任务;这些任务不可在平台单方作废。"""
|
||||
upload_status = str(task.upload_status or '').strip().lower()
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
|
||||
upload_status = str(getattr(latest_upload_attempt(task), 'status', None) or '').strip().lower()
|
||||
return bool(
|
||||
task.freight_ref_no
|
||||
or upload_status in _EXTERNAL_UPLOAD_STATUSES
|
||||
upload_status in _EXTERNAL_UPLOAD_STATUSES
|
||||
)
|
||||
|
||||
|
||||
def _has_successor(task: ShippingNotice) -> bool:
|
||||
def _has_successor(task: ShippingNotice | ShippingOrderTask) -> bool:
|
||||
"""修订链存在后继时禁止作废旧任务,避免破坏版本追溯。"""
|
||||
if not isinstance(task, ShippingNotice):
|
||||
return False
|
||||
return (
|
||||
db.session.query(ShippingNotice.id)
|
||||
.filter(ShippingNotice.supersedes_task_id == int(task.id))
|
||||
@@ -127,7 +134,7 @@ def _has_successor(task: ShippingNotice) -> bool:
|
||||
|
||||
|
||||
def task_disposition_capability(
|
||||
task: ShippingNotice,
|
||||
task: ShippingNotice | ShippingOrderTask,
|
||||
action: TaskDispositionAction,
|
||||
) -> TaskDispositionCapability:
|
||||
"""
|
||||
@@ -200,7 +207,7 @@ def _disposition_reason_code(event_type: str, detail: dict[str, Any]) -> str | N
|
||||
|
||||
|
||||
def _write_disposition_event(
|
||||
task: ShippingNotice,
|
||||
task: ShippingNotice | ShippingOrderTask,
|
||||
*,
|
||||
event_type: str,
|
||||
actor_id: int | None,
|
||||
@@ -216,13 +223,15 @@ def _write_disposition_event(
|
||||
reason_code = _disposition_reason_code(event_type, payload)
|
||||
if reason_code:
|
||||
payload.setdefault('reason_code', reason_code)
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=int(task.id),
|
||||
event_type=event_type,
|
||||
actor_id=actor_id,
|
||||
request_id=str(request_id or '').strip()[:64] or None,
|
||||
detail_json=payload,
|
||||
))
|
||||
from app.services.shipping_notice.tool_common import task_event_task_id
|
||||
if isinstance(task, ShippingNotice):
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=task_event_task_id(task),
|
||||
event_type=event_type,
|
||||
actor_id=actor_id,
|
||||
request_id=str(request_id or '').strip()[:64] or None,
|
||||
detail_json=payload,
|
||||
))
|
||||
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
|
||||
|
||||
record_fulfillment_audit(
|
||||
@@ -237,7 +246,12 @@ def _write_disposition_event(
|
||||
result='success',
|
||||
after={
|
||||
'lifecycle_status': getattr(task, 'lifecycle_status', None),
|
||||
'upload_status': getattr(task, 'upload_status', None),
|
||||
'upload_status': getattr(
|
||||
__import__('app.services.shipping_notice.upload_attempt_service', fromlist=['latest_upload_attempt'])
|
||||
.latest_upload_attempt(task),
|
||||
'status',
|
||||
None,
|
||||
),
|
||||
},
|
||||
metadata={
|
||||
'dual_write': 'shipping_task_event',
|
||||
@@ -281,15 +295,25 @@ def move_task_to_recycle_bin(
|
||||
raise ConflictError(capability.reason or 'Task delete is blocked', code=capability.code or 'SHIPPING.TASK_DELETE_BLOCKED')
|
||||
|
||||
# [STEP 1] 已解析或已产生内部引用的任务先作废,再进入回收站;纯 created 误建仅隐藏。
|
||||
owner_task = (
|
||||
db.session.get(ShippingOrderTask, int(task.order_task_id))
|
||||
if isinstance(task, ShippingNotice) and task.order_task_id else task
|
||||
)
|
||||
has_internal_business_record = bool(
|
||||
task.business_no
|
||||
or task.customer_id
|
||||
or task.source_candidate_id
|
||||
or task.match_status
|
||||
or task.export_file_path
|
||||
or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).first()
|
||||
or db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).first()
|
||||
or db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).first()
|
||||
getattr(task, 'business_no', None)
|
||||
or (
|
||||
db.session.query(ShippingCustomerShadowResolution.id).filter_by(
|
||||
candidate_id=getattr(owner_task, 'candidate_id', None), status='confirmed',
|
||||
).filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)).first()
|
||||
)
|
||||
or getattr(owner_task, 'candidate_id', None)
|
||||
or bool(db.session.query(ShippingNoticeLineInventoryMatch.id).filter_by(task_id=int(owner_task.id), is_current=True).first())
|
||||
or db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(owner_task.id)).first()
|
||||
or db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(owner_task.id)).first()
|
||||
or (
|
||||
isinstance(task, ShippingNotice)
|
||||
and db.session.query(ShippingExportArtifact.id).filter_by(task_id=int(task.id)).first()
|
||||
)
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
task.deleted_at = now
|
||||
@@ -318,7 +342,7 @@ def move_task_to_recycle_bin(
|
||||
|
||||
|
||||
def void_task(
|
||||
task: ShippingNotice,
|
||||
task: ShippingNotice | ShippingOrderTask,
|
||||
*,
|
||||
actor_id: int,
|
||||
reason: str,
|
||||
@@ -346,7 +370,7 @@ def void_task(
|
||||
|
||||
|
||||
def archive_task(
|
||||
task: ShippingNotice,
|
||||
task: ShippingNotice | ShippingOrderTask,
|
||||
*,
|
||||
actor_id: int,
|
||||
request_id: str | None = None,
|
||||
@@ -368,7 +392,7 @@ def archive_task(
|
||||
|
||||
|
||||
def restore_task_from_recycle_bin(
|
||||
task: ShippingNotice,
|
||||
task: ShippingNotice | ShippingOrderTask,
|
||||
*,
|
||||
actor_id: int,
|
||||
request_id: str | None = None,
|
||||
@@ -390,7 +414,7 @@ def restore_task_from_recycle_bin(
|
||||
|
||||
|
||||
def purge_task_permanently(
|
||||
task: ShippingNotice,
|
||||
task: ShippingNotice | ShippingOrderTask,
|
||||
*,
|
||||
actor_id: int,
|
||||
reason: str,
|
||||
@@ -414,18 +438,50 @@ def purge_task_permanently(
|
||||
if task.deleted_at is None or str(task.lifecycle_status or 'active') != 'active':
|
||||
raise ConflictError('Only deleted pure draft task can be purged', code='SHIPPING.TASK_PURGE_BLOCKED')
|
||||
|
||||
from app.models import ShippingOrderExtraction, ShippingTemporaryInventorySession
|
||||
from app.models.shipping_task_line import ShippingTaskFieldConflict
|
||||
# OT 尚未生成 Notice 时只检查其自身的解析/库存/审计引用,禁止访问 Notice 专属字段。
|
||||
if isinstance(task, ShippingOrderTask):
|
||||
blocking_counts = {
|
||||
'current_order_extraction': int(bool(task.current_order_extraction_id)),
|
||||
'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'candidate_consumed': db.session.query(ShippingOrderCandidate.id).filter_by(consumed_task_id=int(task.id)).count(),
|
||||
'intake_consumed': db.session.query(ShippingOrderIntake.id).filter_by(consumed_task_id=int(task.id)).count(),
|
||||
'order_extraction': db.session.query(ShippingOrderExtraction.id).filter_by(task_id=int(task.id)).count(),
|
||||
'inventory_link': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'field_conflict': db.session.query(ShippingTaskFieldConflict.id).filter_by(task_id=int(task.id)).count(),
|
||||
}
|
||||
blocking = {key: value for key, value in blocking_counts.items() if value}
|
||||
if blocking:
|
||||
raise ConflictError(
|
||||
'Order task has business or audit references and cannot be purged',
|
||||
code='SHIPPING.TASK_PURGE_BLOCKED',
|
||||
details={'blocking': blocking},
|
||||
)
|
||||
db.session.delete(task)
|
||||
db.session.add(ShippingTaskPurgeAudit(
|
||||
task_no_snapshot=task.task_no,
|
||||
actor_id=actor_id,
|
||||
reason=normalized_reason,
|
||||
snapshot_json={'task_no': task.task_no, 'lifecycle_status': task.lifecycle_status},
|
||||
))
|
||||
return
|
||||
|
||||
from app.models import ShippingTemporaryInventorySession
|
||||
|
||||
# [STEP 1] 不依赖前端预检,事务内重新统计全部会破坏可追溯性的引用。
|
||||
owner = task if hasattr(task, 'current_order_extraction_id') else None
|
||||
customer_confirmed = False
|
||||
if owner is not None and owner.current_order_extraction_id:
|
||||
customer_confirmed = db.session.query(ShippingCustomerShadowResolution.id).filter_by(
|
||||
candidate_id=owner.candidate_id, status='confirmed',
|
||||
).filter(ShippingCustomerShadowResolution.confirmed_customer_id.isnot(None)).first() is not None
|
||||
blocking_counts = {
|
||||
'business_number': int(bool(task.business_no)),
|
||||
'customer': int(bool(task.customer_id)),
|
||||
'customer': int(customer_confirmed),
|
||||
'source_asset': int(bool(task.source_asset_id)),
|
||||
'source_intake': int(bool(task.source_intake_id)),
|
||||
'source_candidate': int(bool(task.source_candidate_id)),
|
||||
'current_order_extraction': int(bool(task.current_order_extraction_id)),
|
||||
'inventory_snapshot': int(bool(task.inventory_snapshot_id)),
|
||||
'inventory_snapshot': db.session.query(ShippingTaskInventoryLink.id).filter_by(task_id=int(task.id)).count(),
|
||||
'successor': int(_has_successor(task)),
|
||||
'duplicate_link': int(bool(task.duplicate_source_task_id)),
|
||||
'duplicate_source_for_other_task': db.session.query(ShippingNotice.id).filter(
|
||||
|
||||
@@ -235,34 +235,37 @@ def resolve_field_conflict(
|
||||
remaining = list_open_field_conflicts(task)
|
||||
issues = task_reservation_gate_issues(task)
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
step_payload['field_conflicts'] = {
|
||||
'open_count': len(remaining),
|
||||
'last_resolved_id': conflict.id,
|
||||
}
|
||||
if idempotency_key:
|
||||
step_payload['last_conflict_resolve_idempotency_key'] = str(idempotency_key).strip()
|
||||
if remaining:
|
||||
step_payload['process_field_gate'] = {
|
||||
'status': 'needs_enrichment',
|
||||
'missing_fields': sorted({row.field_name for row in remaining}),
|
||||
'issues': [
|
||||
{
|
||||
'severity': 'blocking',
|
||||
'field': row.field_name,
|
||||
'line_index': row.position,
|
||||
'reason': 'field_conflict',
|
||||
'conflict_id': row.id,
|
||||
}
|
||||
for row in remaining
|
||||
],
|
||||
if task.__class__.__name__ != 'ShippingOrderTask':
|
||||
step_payload['field_conflicts'] = {
|
||||
'open_count': len(remaining),
|
||||
'last_resolved_id': conflict.id,
|
||||
}
|
||||
if idempotency_key:
|
||||
step_payload['last_conflict_resolve_idempotency_key'] = str(idempotency_key).strip()
|
||||
if remaining:
|
||||
if task.__class__.__name__ != 'ShippingOrderTask':
|
||||
step_payload['process_field_gate'] = {
|
||||
'status': 'needs_enrichment',
|
||||
'missing_fields': sorted({row.field_name for row in remaining}),
|
||||
'issues': [
|
||||
{
|
||||
'severity': 'blocking',
|
||||
'field': row.field_name,
|
||||
'line_index': row.position,
|
||||
'reason': 'field_conflict',
|
||||
'conflict_id': row.id,
|
||||
}
|
||||
for row in remaining
|
||||
],
|
||||
}
|
||||
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
|
||||
elif issues:
|
||||
step_payload['process_field_gate'] = {
|
||||
'status': 'needs_enrichment',
|
||||
'missing_fields': ['reservation_id'],
|
||||
'issues': issues,
|
||||
}
|
||||
if task.__class__.__name__ != 'ShippingOrderTask':
|
||||
step_payload['process_field_gate'] = {
|
||||
'status': 'needs_enrichment',
|
||||
'missing_fields': ['reservation_id'],
|
||||
'issues': issues,
|
||||
}
|
||||
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
|
||||
else:
|
||||
step_payload.pop('process_field_gate', None)
|
||||
@@ -273,7 +276,9 @@ def resolve_field_conflict(
|
||||
'issues': issues,
|
||||
'resolution_source': 'field_conflict_resolve',
|
||||
}
|
||||
task.step_payload_json = step_payload
|
||||
task.step_payload_json = step_payload if task.__class__.__name__ != 'ShippingOrderTask' else {
|
||||
key: value for key, value in step_payload.items() if key in {'current_step_progress', 'parse_validation'}
|
||||
}
|
||||
|
||||
log_task_event(
|
||||
task,
|
||||
|
||||
@@ -152,9 +152,10 @@ def current_line_field_configs(task: ShippingNotice) -> dict[str, dict[str, Any]
|
||||
|
||||
def _current_extraction(task: ShippingNotice) -> ShippingOrderExtraction:
|
||||
"""读取任务当前已接受 Extraction;人工编辑绝不回退旧任务行投影。"""
|
||||
extraction_id = getattr(task, 'current_order_extraction_id', None)
|
||||
extraction = (
|
||||
db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
if task.current_order_extraction_id is not None else None
|
||||
db.session.get(ShippingOrderExtraction, extraction_id)
|
||||
if extraction_id is not None else None
|
||||
)
|
||||
if extraction is None or extraction.status != 'accepted':
|
||||
raise ConflictError('Task has no accepted order extraction', code='SHIPPING.ORDER_FIELD_EDIT_BLOCKED')
|
||||
@@ -338,7 +339,7 @@ def replace_current_line_fields(*, task: ShippingNotice, lines: list[dict[str, A
|
||||
value_json=previous_value.value_json,
|
||||
))
|
||||
for position, values in enumerate(lines):
|
||||
line = ShippingOrderLine(extraction_id=replacement.id, position=position)
|
||||
line = ShippingOrderLine(extraction_id=replacement.id, position=position, line_no=position + 1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for config in configs:
|
||||
|
||||
@@ -6,8 +6,9 @@ from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingFreightCancellation, ShippingNotice, ShippingTaskEvent
|
||||
from app.models import ShippingFreightCancellation, ShippingNotice, ShippingOrderTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
from app.services.shipping_notice.tool_common import task_event_task_id
|
||||
|
||||
|
||||
def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingNotice, actor_id: int, reason: str) -> None:
|
||||
@@ -18,24 +19,48 @@ def establish_task_supersession(*, old_task: ShippingNotice, new_task: ShippingN
|
||||
raise ConflictError('Revision parent mismatch', code='SHIPPING.TASK_SUPERSESSION_INVALID')
|
||||
if not task_is_active(old):
|
||||
return
|
||||
external = bool(old.freight_ref_no or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'})
|
||||
from app.services.shipping_notice.upload_attempt_service import has_verified_upload_success
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_upload_attempt
|
||||
latest_attempt = latest_upload_attempt(old)
|
||||
external = bool(
|
||||
has_verified_upload_success(old)
|
||||
or str(getattr(latest_attempt, 'freight_ref_no', '') or '').strip()
|
||||
)
|
||||
if external:
|
||||
existing = ShippingFreightCancellation.query.filter_by(old_task_id=old.id, new_task_id=new.id).one_or_none()
|
||||
if existing is None:
|
||||
db.session.add(ShippingFreightCancellation(old_task_id=old.id, new_task_id=new.id, requested_by_id=actor_id, reason=reason))
|
||||
new.lifecycle_status = 'blocked'
|
||||
new.pending_human_reason = 'freight_cancellation_required'
|
||||
db.session.add(ShippingTaskEvent(task_id=new.id, event_type='supersession_cancellation_required', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason}))
|
||||
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:
|
||||
# lifecycle_status 仅表达 active/voided/archived;流程阻断属于 status。
|
||||
new_owner.status = 'blocked'
|
||||
new_owner.pending_human_reason = 'freight_cancellation_required'
|
||||
db.session.add(ShippingTaskEvent(task_id=task_event_task_id(new), event_type='supersession_cancellation_required', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason}))
|
||||
return
|
||||
old.lifecycle_status = 'voided'
|
||||
old.voided_at = datetime.utcnow()
|
||||
old.voided_by_id = actor_id
|
||||
old.void_reason = reason
|
||||
db.session.add(ShippingTaskEvent(task_id=old.id, event_type='task_superseded', actor_id=actor_id, detail_json={'new_task_no': new.task_no, 'reason': reason}))
|
||||
db.session.add(ShippingTaskEvent(task_id=new.id, event_type='task_supersession_established', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason, 'at': datetime.utcnow().isoformat()}))
|
||||
db.session.add(ShippingTaskEvent(task_id=task_event_task_id(old), event_type='task_superseded', actor_id=actor_id, detail_json={'new_task_no': new.task_no, 'reason': reason}))
|
||||
db.session.add(ShippingTaskEvent(task_id=task_event_task_id(new), event_type='task_supersession_established', actor_id=actor_id, detail_json={'old_task_no': old.task_no, 'reason': reason, 'at': datetime.utcnow().isoformat()}))
|
||||
|
||||
|
||||
def assert_task_not_supersession_blocked(task: ShippingNotice) -> None:
|
||||
"""库存、导出和上传入口调用,阻止撤销未完成的新版本继续履约。"""
|
||||
if str(task.lifecycle_status or '').lower() == 'blocked' and task.pending_human_reason == 'freight_cancellation_required':
|
||||
if isinstance(task, ShippingOrderTask):
|
||||
lifecycle = str(getattr(task, 'lifecycle_status', '') or '').lower()
|
||||
reason = str(getattr(task, 'pending_human_reason', '') or '').lower()
|
||||
if str(getattr(task, 'status', '') or '').lower() == 'blocked' and reason == 'freight_cancellation_required':
|
||||
raise ConflictError('Freight cancellation is required before this revision can continue', code='SHIPPING.FREIGHT_CANCELLATION_REQUIRED')
|
||||
return
|
||||
owner = (
|
||||
db.session.get(ShippingOrderTask, int(task.order_task_id))
|
||||
if task.order_task_id is not None else None
|
||||
)
|
||||
lifecycle = str(getattr(owner, 'status', None) or '').lower()
|
||||
reason = str(getattr(owner, 'pending_human_reason', None) or '').lower()
|
||||
if lifecycle == 'blocked' and reason == 'freight_cancellation_required':
|
||||
raise ConflictError('Freight cancellation is required before this revision can continue', code='SHIPPING.FREIGHT_CANCELLATION_REQUIRED')
|
||||
@@ -2,9 +2,9 @@
|
||||
services/shipping_notice/task_workflow.py
|
||||
|
||||
用途:发货通知任务/批次生命周期、解析与单头/订单行编辑的主编排入口。
|
||||
依赖:query_service、tool_common、decision_workflow、progress_workflow、state_machine、
|
||||
依赖:query_service、tool_common、progress_workflow、state_machine、
|
||||
fulfillment_audit、schema_edit_policy、动态订单字段编辑器、candidate_qualification_service。
|
||||
逻辑:tools.py 门面委托本模块;创建 Task 前强制客户已确认(禁止先建单再 customer_review);
|
||||
逻辑:tools.py 门面委托本模块;创建 OT 不强制客户已确认(先建单,客户确认交由订单复核/客户门禁处理);
|
||||
正式字段编辑经 Schema 策略门禁后落库,并按 change_effect 失效下游;
|
||||
成功/拒绝编辑与库存/Excel 失效同事务写入 ShippingAuditEvent;
|
||||
retry_task 写入操作人与前后快照审计。
|
||||
@@ -20,9 +20,8 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingNotice, ShippingOrderTask, ShippingOrderIntake
|
||||
from app.services.shipping_notice.constants import CP_TASK_EXISTS
|
||||
from app.services.shipping_notice.decision_workflow import submit_decision
|
||||
from app.services.shipping_notice.task_order_field_editor import (
|
||||
current_header_field_values,
|
||||
retire_current_order_extraction,
|
||||
@@ -52,8 +51,7 @@ from app.services.shipping_notice.batch_create_idempotency import (
|
||||
assert_no_exact_duplicate_notices,
|
||||
)
|
||||
from app.services.shipping_notice.candidate_qualification_service import (
|
||||
assert_customer_confirmed_before_task_create,
|
||||
resolve_confirmed_bill_to_customer_id,
|
||||
resolve_confirmed_customer_id,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
generate_task_no,
|
||||
@@ -64,6 +62,13 @@ from app.services.shipping_notice.tool_common import (
|
||||
)
|
||||
from app.models import ShippingOrderCandidate, ShippingOrderReviewEvent
|
||||
|
||||
|
||||
def _has_ready_inventory_file(task: ShippingNotice | ShippingOrderTask) -> bool:
|
||||
"""读取活动 Link 指向的 ready 文件,作为重试审计中的库存事实。"""
|
||||
from app.services.shipping_notice.inventory_file_store import has_ready_inventory_file_for_task
|
||||
|
||||
return has_ready_inventory_file_for_task(task)
|
||||
|
||||
EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"})
|
||||
EDITABLE_NOTICE_LINE_FIELDS = frozenset({
|
||||
"part_number",
|
||||
@@ -76,6 +81,12 @@ EDITABLE_NOTICE_LINE_FIELDS = frozenset({
|
||||
})
|
||||
|
||||
|
||||
def _task_intake(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderIntake | None:
|
||||
"""返回 OT 关联的 Intake,原始正文与来源元数据统一由 Intake 承载。"""
|
||||
intake_id = getattr(task, 'intake_id', None)
|
||||
return db.session.get(ShippingOrderIntake, int(intake_id)) if intake_id else None
|
||||
|
||||
|
||||
def start_task_orchestrator(task_no: str | None) -> bool:
|
||||
"""延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。"""
|
||||
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start
|
||||
@@ -122,9 +133,9 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
if conv_id:
|
||||
existing = (
|
||||
ShippingNotice.query.filter_by(conversation_id=conv_id)
|
||||
.filter(ShippingNotice.lifecycle_status == 'active')
|
||||
.order_by(ShippingNotice.id.desc())
|
||||
ShippingOrderTask.query.filter_by(conversation_id=conv_id)
|
||||
.filter(ShippingOrderTask.status.notin_({'completed', 'failed', 'cancelled'}))
|
||||
.order_by(ShippingOrderTask.id.desc())
|
||||
.first()
|
||||
)
|
||||
if existing:
|
||||
@@ -133,37 +144,35 @@ def create_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task_id=existing.task_no,
|
||||
message=(
|
||||
f"当前会话已有进行中的发货任务 {existing.task_no},请勿重复 create_task。"
|
||||
"用户确认/驳回时请 submit_decision,并带上任务编号或 conversation_id。"
|
||||
),
|
||||
data=qs_serialize_task(existing, TaskProjection.TOOL_INTERNAL),
|
||||
checkpoint=CP_TASK_EXISTS,
|
||||
)
|
||||
|
||||
# [STEP] 单票建单同样要求客户已确认,禁止创建后进入 customer_review。
|
||||
# [STEP] 接收解析阶段只创建 OT;客户确认由订单复核/客户门禁处理,不能阻止 OT 落库。
|
||||
customer_id = _parse_optional_customer_id(payload.get("customer_id"))
|
||||
assert_customer_confirmed_before_task_create(
|
||||
customer_id=customer_id,
|
||||
)
|
||||
task = ShippingNotice(
|
||||
user_id = payload.get("user_id")
|
||||
if user_id is None:
|
||||
raise ValidationError('user_id is required', code='SHIPPING.USER_REQUIRED')
|
||||
task = ShippingOrderTask(
|
||||
task_no=generate_task_no(),
|
||||
customer_id=customer_id,
|
||||
user_id=payload.get("user_id"),
|
||||
user_id=int(user_id),
|
||||
conversation_id=str(payload.get("conversation_id") or "").strip() or None,
|
||||
source_type=str(payload.get("source_type") or "manual"),
|
||||
batch_index=1,
|
||||
batch_total=1,
|
||||
raw_content=str(payload.get("raw_content") or "").strip() or None,
|
||||
customer_resolution_status='pending',
|
||||
# OT 仅接受 intake 层定义的来源类型;未知/手工入口保持 NULL,避免违反模型约束。
|
||||
source_type=(str(payload.get("source_type") or "").strip() or None),
|
||||
status='processing',
|
||||
stage='document_parsing',
|
||||
)
|
||||
db.session.add(task)
|
||||
log_task_event(task, "task_created", {"source_type": task.source_type})
|
||||
db.session.flush()
|
||||
_bind_confirmed_customer_after_task_create(
|
||||
task,
|
||||
customer_id=customer_id,
|
||||
candidate=None,
|
||||
actor_id=payload.get("user_id"),
|
||||
)
|
||||
if customer_id is not None:
|
||||
_bind_confirmed_customer_after_task_create(
|
||||
task,
|
||||
customer_id=customer_id,
|
||||
candidate=None,
|
||||
actor_id=payload.get("user_id"),
|
||||
)
|
||||
db.session.commit()
|
||||
return tool_response(
|
||||
status="ok",
|
||||
@@ -190,7 +199,7 @@ def _parse_optional_customer_id(raw: Any) -> int | None:
|
||||
|
||||
|
||||
def _bind_confirmed_customer_after_task_create(
|
||||
task: ShippingNotice,
|
||||
task: ShippingOrderTask,
|
||||
*,
|
||||
customer_id: int | None,
|
||||
candidate: ShippingOrderCandidate | None,
|
||||
@@ -199,9 +208,9 @@ def _bind_confirmed_customer_after_task_create(
|
||||
"""
|
||||
创建 Task 后立即绑定已确认客户,避免以 pending 进入 customer_review。
|
||||
|
||||
核心逻辑:用显式 customer_id 或候选 Bill-to 直接确认当前 Notice。
|
||||
核心逻辑:用显式 customer_id 或已确认识别结果直接确认当前 OT。
|
||||
"""
|
||||
bind_id = customer_id or resolve_confirmed_bill_to_customer_id(candidate=candidate)
|
||||
bind_id = customer_id or resolve_confirmed_customer_id(candidate=candidate)
|
||||
if bind_id is None:
|
||||
raise ConflictError(
|
||||
'Customer must be confirmed before creating a shipping task',
|
||||
@@ -229,69 +238,43 @@ def _notice_header_snapshot(task: ShippingNotice) -> dict[str, Any]:
|
||||
|
||||
def _reset_notice_edit_downstream(task: ShippingNotice) -> None:
|
||||
"""清空匹配/导出/上传等派生结果,供 require_revision / 库存重算类 change_effect 使用。"""
|
||||
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
|
||||
task.upload_attempt = 0
|
||||
task.upload_started_at = None
|
||||
task.upload_finished_at = None
|
||||
task.upload_error_code = None
|
||||
task.upload_error_message = None
|
||||
task.upload_receipt_json = None
|
||||
task.idempotency_key = None
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
order_task = _resolve_order_task_for_notice(task)
|
||||
if order_task is None:
|
||||
return
|
||||
step_payload = dict(order_task.step_payload_json or {})
|
||||
step_payload.pop('export_meta', None)
|
||||
task.step_payload_json = step_payload
|
||||
order_task.step_payload_json = step_payload
|
||||
|
||||
|
||||
def _reset_notice_export_downstream(task: ShippingNotice) -> None:
|
||||
"""仅使 Excel 导出派生结果失效,保留库存匹配真相。"""
|
||||
task.export_file_path = None
|
||||
task.export_file_name = None
|
||||
task.freight_ref_no = None
|
||||
task.upload_status = None
|
||||
task.upload_mode = None
|
||||
task.upload_attempt = 0
|
||||
task.upload_started_at = None
|
||||
task.upload_finished_at = None
|
||||
task.upload_error_code = None
|
||||
task.upload_error_message = None
|
||||
task.upload_receipt_json = None
|
||||
task.idempotency_key = None
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
order_task = _resolve_order_task_for_notice(task)
|
||||
if order_task is None:
|
||||
return
|
||||
step_payload = dict(order_task.step_payload_json or {})
|
||||
step_payload.pop('export_meta', None)
|
||||
task.step_payload_json = step_payload
|
||||
order_task.step_payload_json = step_payload
|
||||
|
||||
|
||||
def _resolve_order_task_for_notice(task: ShippingNotice):
|
||||
"""按 Notice 反查 OT;供 change_effect 同步统一进度 stage。"""
|
||||
from app.models import ShippingOrderTask
|
||||
|
||||
def _resolve_order_task_for_notice(task: ShippingNotice | ShippingOrderTask) -> ShippingOrderTask | None:
|
||||
"""按 Notice 反查 OT;若入参本身即 OT 则直接返回,供 change_effect 同步统一进度 stage。"""
|
||||
if isinstance(task, ShippingOrderTask):
|
||||
return task
|
||||
order_task_id = getattr(task, 'order_task_id', None)
|
||||
if order_task_id is not None:
|
||||
return db.session.get(ShippingOrderTask, int(order_task_id))
|
||||
return (
|
||||
db.session.query(ShippingOrderTask)
|
||||
.filter(ShippingOrderTask.shipping_notice_id == int(task.id))
|
||||
.order_by(ShippingOrderTask.id.asc())
|
||||
.first()
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _set_notice_invalidated_from_stage(task: ShippingNotice, stage: str) -> None:
|
||||
"""
|
||||
将改单失效起点写入 Notice.step_payload_json,供投影 stage_nodes 消费。
|
||||
将改单失效起点写入 OT.step_payload_json,供投影 stage_nodes 消费。
|
||||
|
||||
[BE-08] 写入时追加 invalidated_from_stage_history,降低无历史可追溯风险;
|
||||
完整列级约束与乐观锁仍待显式字段迁移。
|
||||
|
||||
Args:
|
||||
task: 被编辑的正式任务。
|
||||
task: 被编辑的正式任务(ShippingNotice)。
|
||||
stage: 失效起点统一 stage。
|
||||
"""
|
||||
from datetime import datetime
|
||||
@@ -301,33 +284,42 @@ def _set_notice_invalidated_from_stage(task: ShippingNotice, stage: str) -> None
|
||||
code = str(stage or '').strip().lower()
|
||||
if code not in SHIPPING_PROCESSING_STAGES:
|
||||
return
|
||||
payload = dict(task.step_payload_json or {}) if isinstance(task.step_payload_json, dict) else {}
|
||||
order_task = _resolve_order_task_for_notice(task)
|
||||
if order_task is None:
|
||||
return
|
||||
payload = (
|
||||
dict(order_task.step_payload_json or {})
|
||||
if isinstance(order_task.step_payload_json, dict) else {}
|
||||
)
|
||||
history = payload.get('invalidated_from_stage_history')
|
||||
if not isinstance(history, list):
|
||||
history = []
|
||||
history.append({
|
||||
'stage': code,
|
||||
'at': datetime.utcnow().isoformat(timespec='seconds') + 'Z',
|
||||
'progress_version': int(getattr(task, 'progress_version', None) or 0),
|
||||
'progress_version': int(getattr(order_task, 'progress_version', None) or 0),
|
||||
})
|
||||
payload['invalidated_from_stage'] = code
|
||||
payload['invalidated_from_stage_history'] = history[-20:]
|
||||
task.step_payload_json = payload
|
||||
order_task.step_payload_json = payload
|
||||
|
||||
|
||||
def _clear_notice_invalidated_from_stage(task: ShippingNotice) -> None:
|
||||
"""
|
||||
清除 Notice 上的改单失效起点(下游已成功重跑后)。
|
||||
清除 OT 上的改单失效起点(下游已成功重跑后)。
|
||||
|
||||
[BE-08] 清除仅移除当前起点;历史列表保留供审计追溯。
|
||||
"""
|
||||
if not isinstance(task.step_payload_json, dict):
|
||||
order_task = _resolve_order_task_for_notice(task)
|
||||
if order_task is None:
|
||||
return
|
||||
if 'invalidated_from_stage' not in task.step_payload_json:
|
||||
if not isinstance(order_task.step_payload_json, dict):
|
||||
return
|
||||
payload = dict(task.step_payload_json)
|
||||
if 'invalidated_from_stage' not in order_task.step_payload_json:
|
||||
return
|
||||
payload = dict(order_task.step_payload_json)
|
||||
payload.pop('invalidated_from_stage', None)
|
||||
task.step_payload_json = payload
|
||||
order_task.step_payload_json = payload
|
||||
|
||||
|
||||
def read_notice_invalidated_from_stage(task: ShippingNotice | None) -> str | None:
|
||||
@@ -344,7 +336,10 @@ def read_notice_invalidated_from_stage(task: ShippingNotice | None) -> str | Non
|
||||
|
||||
if task is None:
|
||||
return None
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
order_task = _resolve_order_task_for_notice(task)
|
||||
if order_task is None:
|
||||
return None
|
||||
payload = order_task.step_payload_json if isinstance(order_task.step_payload_json, dict) else {}
|
||||
code = str(payload.get('invalidated_from_stage') or '').strip().lower()
|
||||
return code if code in SHIPPING_PROCESSING_STAGES else None
|
||||
|
||||
@@ -374,7 +369,6 @@ def _apply_notice_edit_change_effects(
|
||||
from app.services.shipping_notice.schema_edit_policy import collect_change_effects_for_fields
|
||||
from app.services.shipping_notice.order_task_service import sync_order_task_processing_state
|
||||
from app.services.shipping_notice.inventory_source_gate import (
|
||||
STABLE_INVENTORY_SOURCE_STATUSES,
|
||||
adjudicate_and_apply_inventory_source,
|
||||
clear_inventory_source_confirmation,
|
||||
)
|
||||
@@ -399,18 +393,12 @@ def _apply_notice_edit_change_effects(
|
||||
# [STEP] 库存源重算优先于匹配重算:不得跳过 inventory_source_resolving。
|
||||
if 'rerun_inventory_source_resolution' in effects:
|
||||
clear_inventory_source_confirmation(task)
|
||||
task.inventory_source_status = 'unresolved'
|
||||
task.inventory_source_code = None
|
||||
task.inventory_connector_type = None
|
||||
task.inventory_warehouse_id = None
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
task.inventory_lines_json = None
|
||||
_reset_notice_export_downstream(task)
|
||||
_set_notice_invalidated_from_stage(task, 'inventory_source_resolving')
|
||||
adjudication = adjudicate_and_apply_inventory_source(task)
|
||||
stable = str(adjudication.status or '').strip() in STABLE_INVENTORY_SOURCE_STATUSES
|
||||
from app.services.shipping_notice.inventory_source_gate import is_inventory_source_stable
|
||||
|
||||
stable = is_inventory_source_stable(task)
|
||||
if order_task is not None:
|
||||
if stable:
|
||||
sync_order_task_processing_state(
|
||||
@@ -429,10 +417,6 @@ def _apply_notice_edit_change_effects(
|
||||
return applied
|
||||
|
||||
if 'rerun_inventory_matching' in effects:
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
task.inventory_lines_json = None
|
||||
_reset_notice_export_downstream(task)
|
||||
_set_notice_invalidated_from_stage(task, 'inventory_matching')
|
||||
if order_task is not None:
|
||||
@@ -553,9 +537,11 @@ def _record_formal_task_edit_audits(
|
||||
'export_file_name': before_export_file_name,
|
||||
'order_data_version': before_order_data_version,
|
||||
}
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
after_artifact = latest_export_artifact(task)
|
||||
after_summary = {
|
||||
'match_status': task.match_status,
|
||||
'export_file_name': task.export_file_name,
|
||||
'match_status': None,
|
||||
'export_file_name': getattr(after_artifact, 'file_name', None),
|
||||
'order_data_version': task.order_data_version,
|
||||
}
|
||||
field_changes = _formal_edit_field_diff_summary(
|
||||
@@ -605,7 +591,7 @@ def _record_formal_task_edit_audits(
|
||||
reason_code='inventory_match_invalidated',
|
||||
result='success',
|
||||
before={'match_status': before_match_status},
|
||||
after={'match_status': task.match_status},
|
||||
after={'match_status': None},
|
||||
metadata={'applied_effects': sorted(applied_effects), 'evidence_ref': evidence_ref},
|
||||
source='workspace_api',
|
||||
)
|
||||
@@ -627,7 +613,7 @@ def _record_formal_task_edit_audits(
|
||||
reason_code='excel_export_invalidated',
|
||||
result='success',
|
||||
before={'export_file_name': before_export_file_name},
|
||||
after={'export_file_name': task.export_file_name},
|
||||
after={'export_file_name': getattr(after_artifact, 'file_name', None)},
|
||||
metadata={'applied_effects': sorted(applied_effects), 'evidence_ref': evidence_ref},
|
||||
source='workspace_api',
|
||||
)
|
||||
@@ -707,14 +693,14 @@ def replace_task_notice(
|
||||
"""
|
||||
cleaned_text = str(raw_text or "").strip()
|
||||
cleaned_warnings = [str(item).strip() for item in (warnings or []) if str(item).strip()]
|
||||
intake = _task_intake(task)
|
||||
if not cleaned_text:
|
||||
apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED)
|
||||
task.error_message = "未能从重新上传的发货通知中抽取到可解析文本"
|
||||
task.raw_content = ""
|
||||
if source_file_name:
|
||||
task.source_file_name = source_file_name
|
||||
if source_file_type:
|
||||
task.source_file_type = source_file_type
|
||||
if intake is not None:
|
||||
intake.extracted_text = ""
|
||||
intake.error_message = task.error_message
|
||||
intake.parse_warnings_json = cleaned_warnings
|
||||
set_task_step_progress(
|
||||
task,
|
||||
step_key="step2_parse_confirm",
|
||||
@@ -736,13 +722,10 @@ def replace_task_notice(
|
||||
data={**serialize_task_for_tool(task), "warnings": cleaned_warnings},
|
||||
)
|
||||
|
||||
task.raw_content = cleaned_text
|
||||
if source_file_name:
|
||||
task.source_file_name = source_file_name
|
||||
if source_file_type:
|
||||
task.source_file_type = source_file_type
|
||||
if intake is not None:
|
||||
intake.extracted_text = cleaned_text
|
||||
intake.parse_warnings_json = cleaned_warnings
|
||||
retire_current_order_extraction(task)
|
||||
task.parse_confidence = None
|
||||
task.review_status = None
|
||||
task.pending_human_reason = None
|
||||
task.error_message = None
|
||||
@@ -821,6 +804,30 @@ def _assert_order_data_version(task: ShippingNotice, payload: dict[str, Any]) ->
|
||||
return None
|
||||
|
||||
|
||||
def _edit_window_busy_error(task: ShippingNotice) -> dict[str, Any] | None:
|
||||
"""
|
||||
二期编辑窗守卫(D10/§3.3):订单任一通知存在活动 Gate Attempt(库存 RPA / 匹配 queued|running)
|
||||
时拒绝保存,返回 SYSTEM_BUSY 的 failed Tool 响应;否则 None。
|
||||
|
||||
Args:
|
||||
task: 被编辑的 ShippingNotice。
|
||||
|
||||
Returns:
|
||||
活动 Attempt 时的 tool_response(status='failed', error_code=SHIPPING.EDIT_WINDOW_SYSTEM_BUSY);
|
||||
通过则 None。
|
||||
"""
|
||||
from app.services.shipping_notice.order_edit_window_service import order_has_active_attempt
|
||||
|
||||
if order_has_active_attempt(task):
|
||||
return tool_response(
|
||||
status='failed',
|
||||
task=task,
|
||||
message='系统处理中,请稍后再修改。',
|
||||
data={'error_code': 'SHIPPING.EDIT_WINDOW_SYSTEM_BUSY'},
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def _notice_edit_idempotency_replay(
|
||||
task: ShippingNotice,
|
||||
payload: dict[str, Any],
|
||||
@@ -829,7 +836,10 @@ def _notice_edit_idempotency_replay(
|
||||
key = str(payload.get('idempotency_key') or '').strip()
|
||||
if not key:
|
||||
return None
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
order_task = _resolve_order_task_for_notice(task)
|
||||
if order_task is None:
|
||||
return None
|
||||
step_payload = dict(order_task.step_payload_json or {})
|
||||
last = step_payload.get('last_notice_edit_idempotency')
|
||||
if not isinstance(last, dict):
|
||||
return None
|
||||
@@ -853,9 +863,35 @@ def _remember_notice_edit_idempotency(
|
||||
text = str(key or '').strip()
|
||||
if not text:
|
||||
return
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
order_task = _resolve_order_task_for_notice(task)
|
||||
if order_task is None:
|
||||
return
|
||||
step_payload = dict(order_task.step_payload_json or {})
|
||||
step_payload['last_notice_edit_idempotency'] = {'key': text, 'message': message}
|
||||
task.step_payload_json = step_payload
|
||||
order_task.step_payload_json = step_payload
|
||||
|
||||
|
||||
def _order_task_match_status_for_audit(order_task: ShippingOrderTask | None) -> str | None:
|
||||
"""
|
||||
读取 OT 当前行级库存匹配状态(matched / shortage / None),
|
||||
供正式编辑审计 before 快照记录失效前的真实 match_status。
|
||||
|
||||
核心逻辑:以行级 Match 事实为准(禁止读取 OT 缓存字段),
|
||||
all 行匹配且无短缺为 matched,否则有行时视为 shortage;无行返回 None。
|
||||
"""
|
||||
if order_task is None:
|
||||
return None
|
||||
from app.services.shipping_notice.line_inventory_match_projection import load_current_match_facts_by_task
|
||||
|
||||
facts = list(load_current_match_facts_by_task(order_task.id).values())
|
||||
if not facts:
|
||||
return None
|
||||
matched = all(
|
||||
str(row.get('match_result') or '').strip().lower() == 'matched'
|
||||
and str(row.get('shortage_qty') or '').strip() in {'', '0', '0.0', '0.00'}
|
||||
for row in facts
|
||||
)
|
||||
return 'matched' if matched else 'shortage'
|
||||
|
||||
|
||||
def _commit_notice_edit(
|
||||
@@ -887,7 +923,10 @@ def _commit_notice_edit(
|
||||
if not reviewed_by_id or not evidence_ref or not reason:
|
||||
raise ConflictError('Review evidence is required', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED')
|
||||
# [STEP 1] 人工编辑后的业务值拥有最终优先级,但仍必须通过同一流程字段契约。
|
||||
step_payload = dict(task.step_payload_json or {})
|
||||
order_task = _resolve_order_task_for_notice(task)
|
||||
if order_task is None:
|
||||
raise ConflictError('Formal task edit requires a linked order task', code='SHIPPING.ORDER_TASK_REQUIRED')
|
||||
step_payload = dict(order_task.step_payload_json or {})
|
||||
validation_issues = task_reservation_gate_issues(task)
|
||||
step_payload["parse_validation"] = {
|
||||
"status": "needs_review" if validation_issues else "ready",
|
||||
@@ -903,11 +942,12 @@ def _commit_notice_edit(
|
||||
}
|
||||
else:
|
||||
step_payload.pop('process_field_gate', None)
|
||||
task.step_payload_json = step_payload
|
||||
order_task.step_payload_json = step_payload
|
||||
|
||||
# [STEP 2] 先按 change_effect 失效下游;仅缺字段或 require_revision 才回旧复核态。
|
||||
before_match_status = task.match_status
|
||||
before_export_file_name = task.export_file_name
|
||||
before_match_status = _order_task_match_status_for_audit(order_task)
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact
|
||||
before_export_file_name = getattr(latest_export_artifact(task), 'file_name', None)
|
||||
before_order_data_version = task.order_data_version
|
||||
applied_effects = _apply_notice_edit_change_effects(task, edited_field_scopes or [])
|
||||
if validation_issues:
|
||||
@@ -1046,6 +1086,10 @@ def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
version_error = _assert_order_data_version(task, payload)
|
||||
if version_error is not None:
|
||||
return version_error
|
||||
# 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。
|
||||
busy_error = _edit_window_busy_error(task)
|
||||
if busy_error is not None:
|
||||
return busy_error
|
||||
|
||||
fields = payload.get("fields")
|
||||
if not isinstance(fields, dict) or not fields:
|
||||
@@ -1137,6 +1181,10 @@ def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
version_error = _assert_order_data_version(task, payload)
|
||||
if version_error is not None:
|
||||
return version_error
|
||||
# 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。
|
||||
busy_error = _edit_window_busy_error(task)
|
||||
if busy_error is not None:
|
||||
return busy_error
|
||||
|
||||
try:
|
||||
line_index = int(payload.get("line_index"))
|
||||
@@ -1244,6 +1292,10 @@ def add_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
version_error = _assert_order_data_version(task, payload)
|
||||
if version_error is not None:
|
||||
return version_error
|
||||
# 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。
|
||||
busy_error = _edit_window_busy_error(task)
|
||||
if busy_error is not None:
|
||||
return busy_error
|
||||
|
||||
line = payload.get("line")
|
||||
if not isinstance(line, dict) or not line:
|
||||
@@ -1288,6 +1340,10 @@ def remove_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
version_error = _assert_order_data_version(task, payload)
|
||||
if version_error is not None:
|
||||
return version_error
|
||||
# 编辑窗守卫(D10):活动 Gate Attempt 期间拒绝保存。
|
||||
busy_error = _edit_window_busy_error(task)
|
||||
if busy_error is not None:
|
||||
return busy_error
|
||||
|
||||
try:
|
||||
line_index = int(payload.get("line_index"))
|
||||
@@ -1347,10 +1403,6 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
task.error_message = None
|
||||
# [BE-放行-重试] 重试应重新评估当前库存事实:清空旧匹配结果,强制 orchest 在下一轮
|
||||
# 重新匹配,而不是带着旧的 unfulfillable/shortage 直接跳到步骤(避免旧缺货残留)。
|
||||
task.match_status = None
|
||||
task.line_results_json = None
|
||||
task.shortage_json = None
|
||||
|
||||
try:
|
||||
order_lines = current_line_field_values(task)
|
||||
except ConflictError:
|
||||
@@ -1384,7 +1436,10 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
reason=comment or None,
|
||||
before=before,
|
||||
after=after,
|
||||
metadata={'has_order_lines': bool(order_lines), 'has_inventory_lines': bool(task.inventory_lines_json)},
|
||||
metadata={
|
||||
'has_order_lines': bool(order_lines),
|
||||
'has_inventory_lines': _has_ready_inventory_file(task),
|
||||
},
|
||||
source=event_source,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
@@ -18,7 +18,7 @@ import uuid
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskEvent
|
||||
from app.models import ShippingNotice, ShippingOrderTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
|
||||
|
||||
|
||||
@@ -221,8 +221,11 @@ def set_task_step_progress(
|
||||
detail: str | None = None,
|
||||
extra: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""写入任务当前步骤与步骤内细粒度进度,统一落到 current_step + step_payload_json。"""
|
||||
payload = dict(task.step_payload_json or {})
|
||||
"""写入任务当前步骤与步骤内细粒度进度,统一落到 OT 的流程字段。"""
|
||||
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
|
||||
payload = dict(getattr(owner, 'step_payload_json', None) or {})
|
||||
progress: dict[str, Any] = {
|
||||
"step_key": step_key,
|
||||
"step_title": step_title,
|
||||
@@ -240,15 +243,23 @@ def set_task_step_progress(
|
||||
if extra:
|
||||
progress["extra"] = extra
|
||||
payload["current_step_progress"] = progress
|
||||
task.current_step = step_key
|
||||
task.step_payload_json = payload
|
||||
if hasattr(owner, 'current_step'):
|
||||
owner.current_step = step_key
|
||||
if hasattr(owner, 'stage'):
|
||||
owner.stage = step_key
|
||||
if hasattr(owner, 'step_payload_json'):
|
||||
owner.step_payload_json = payload
|
||||
|
||||
|
||||
def clear_task_step_progress(task: ShippingNotice) -> None:
|
||||
"""清空任务步骤内进度,保留其他 step_payload_json 字段。"""
|
||||
payload = dict(task.step_payload_json or {})
|
||||
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
|
||||
payload = dict(getattr(owner, 'step_payload_json', None) or {})
|
||||
payload.pop("current_step_progress", None)
|
||||
task.step_payload_json = payload or None
|
||||
if hasattr(owner, 'step_payload_json'):
|
||||
owner.step_payload_json = payload or None
|
||||
|
||||
|
||||
|
||||
@@ -307,7 +318,7 @@ def build_task_action_event_detail(
|
||||
|
||||
|
||||
def log_task_event(
|
||||
task: ShippingNotice,
|
||||
task: ShippingNotice | ShippingOrderTask,
|
||||
event_type: str,
|
||||
detail: dict[str, Any] | None = None,
|
||||
*,
|
||||
@@ -333,10 +344,14 @@ def log_task_event(
|
||||
before: 操作前业务快照。
|
||||
after: 操作后业务快照。
|
||||
"""
|
||||
if task.id is None:
|
||||
event_task_id = task_event_task_id(task)
|
||||
if event_task_id is None:
|
||||
db.session.flush()
|
||||
event_task_id = task_event_task_id(task)
|
||||
if event_task_id is None:
|
||||
raise ValueError('shipping task event requires an order task id')
|
||||
db.session.add(ShippingTaskEvent(
|
||||
task_id=task.id,
|
||||
task_id=event_task_id,
|
||||
event_type=event_type,
|
||||
detail_json=detail or {},
|
||||
actor_id=actor_id,
|
||||
@@ -436,6 +451,14 @@ def log_task_event(
|
||||
)
|
||||
|
||||
|
||||
def task_event_task_id(task: ShippingNotice | ShippingOrderTask) -> int | None:
|
||||
"""将 Notice/OT 输入统一解析为 ShippingTaskEvent 使用的 OT 主键。"""
|
||||
if isinstance(task, ShippingOrderTask):
|
||||
return int(task.id) if task.id is not None else None
|
||||
order_task_id = getattr(task, 'order_task_id', None)
|
||||
return int(order_task_id) if order_task_id is not None else None
|
||||
|
||||
|
||||
def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) -> str | None:
|
||||
"""
|
||||
将任务事件类型映射为可解释性稳定 reason_code,供审计中心筛选。
|
||||
@@ -505,7 +528,7 @@ def task_lifecycle_audit_snapshot(task: ShippingNotice) -> dict[str, Any]:
|
||||
snapshot = {
|
||||
'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None),
|
||||
'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None),
|
||||
'reason_code': getattr(task, 'pending_human_reason', None),
|
||||
'reason_code': __import__('app.services.shipping_notice.process_gate_projection', fromlist=['task_blocking_reason']).task_blocking_reason(task),
|
||||
}
|
||||
return {key: value for key, value in snapshot.items() if value is not None}
|
||||
|
||||
|
||||
@@ -12,10 +12,10 @@ from __future__ import annotations
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from app.models import ShippingNotice
|
||||
from app.models import ShippingNotice, ShippingOrderTask
|
||||
|
||||
|
||||
def _task_has_process_execution(task: ShippingNotice | None) -> bool:
|
||||
def _task_has_process_execution(task: ShippingOrderTask | ShippingNotice | None) -> bool:
|
||||
"""
|
||||
判断任务是否已绑定 ProcessExecution(Gate 为恢复真相源)。
|
||||
|
||||
@@ -27,11 +27,17 @@ def _task_has_process_execution(task: ShippingNotice | None) -> bool:
|
||||
"""
|
||||
if task is None or getattr(task, 'id', None) is None:
|
||||
return False
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.models import ShippingNotice, ShippingProcessExecution
|
||||
|
||||
if isinstance(task, ShippingNotice):
|
||||
task_id = int(task.order_task_id) if task.order_task_id is not None else None
|
||||
else:
|
||||
task_id = int(task.id) if getattr(task, 'id', None) is not None else None
|
||||
if task_id is None:
|
||||
return False
|
||||
return (
|
||||
ShippingProcessExecution.query
|
||||
.filter_by(task_id=int(task.id))
|
||||
.filter_by(task_id=task_id)
|
||||
.filter(ShippingProcessExecution.status != 'superseded')
|
||||
.first()
|
||||
is not None
|
||||
|
||||
@@ -20,7 +20,6 @@ from app.services.shipping_notice import customer_identity_gate
|
||||
# 任务 / 决策
|
||||
create_task = task_workflow.create_task
|
||||
auto_progress = task_workflow.auto_progress
|
||||
submit_decision = task_workflow.submit_decision
|
||||
get_task_status = task_workflow.get_task_status
|
||||
retry_task = task_workflow.retry_task
|
||||
update_notice_fields = task_workflow.update_notice_fields
|
||||
|
||||
@@ -8,7 +8,8 @@ services/shipping_notice/user_facing_status.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.models import ShippingNotice
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
CP_EXPORT_READY,
|
||||
CP_INVENTORY_PENDING,
|
||||
@@ -86,16 +87,24 @@ def user_facing_task_stage(task: ShippingNotice) -> str:
|
||||
这类细粒度状态被通用 checkpoint(如“待上传或获取库存”)覆盖;
|
||||
STP 多源 Excel 阻断覆盖通用 shortage 文案。
|
||||
"""
|
||||
payload = task.step_payload_json if isinstance(task.step_payload_json, dict) else {}
|
||||
# Notice 只承载正式单据;流程/UI 状态归属关联 OT。
|
||||
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
|
||||
payload = getattr(owner, 'step_payload_json', None)
|
||||
payload = payload if isinstance(payload, dict) else {}
|
||||
if payload.get('multi_source_excel_block'):
|
||||
return '多库存源冲突,待人工处理'
|
||||
reason = str(task.pending_human_reason or "").strip()
|
||||
from app.services.shipping_notice.process_gate_projection import task_blocking_reason
|
||||
|
||||
reason = str(task_blocking_reason(owner) or '').strip()
|
||||
if reason in _PENDING_REASON_LABELS:
|
||||
return _PENDING_REASON_LABELS[reason]
|
||||
ui = resolve_task_ui_state(task)
|
||||
ui = resolve_task_ui_state(owner)
|
||||
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
|
||||
return _CHECKPOINT_LABELS[ui.checkpoint]
|
||||
return str(getattr(task, "lifecycle_status", None) or "active") == "active" and "处理中" or "已结束"
|
||||
lifecycle = str(getattr(owner, "lifecycle_status", None) or getattr(owner, 'status', None) or "active")
|
||||
return lifecycle == "active" and "处理中" or "已结束"
|
||||
|
||||
|
||||
def strip_internal_task_fields(data: dict) -> dict:
|
||||
|
||||
@@ -336,11 +336,15 @@ def task_has_entered_inventory_match(task: ShippingNotice) -> bool:
|
||||
Returns:
|
||||
True 表示已进入 matched 或更后阶段。
|
||||
"""
|
||||
match_status = str(getattr(task, 'match_status', None) or '').strip().lower()
|
||||
from app.services.shipping_notice.line_inventory_match_projection import aggregate_match_status_for_task
|
||||
match_task_id = getattr(task, 'order_task_id', None) or getattr(task, 'id', None)
|
||||
match_status = aggregate_match_status_for_task(match_task_id) or ''
|
||||
from app.services.shipping_notice.upload_attempt_service import latest_export_artifact, latest_upload_attempt
|
||||
artifact = latest_export_artifact(task)
|
||||
attempt = latest_upload_attempt(task)
|
||||
return match_status in {'fulfillable', 'partial', 'unfulfillable', 'matched'} or bool(
|
||||
str(getattr(task, 'export_file_path', None) or '').strip()
|
||||
or str(getattr(task, 'freight_ref_no', None) or '').strip()
|
||||
or str(getattr(task, 'upload_status', None) or '').strip()
|
||||
str(getattr(artifact, 'file_path', None) or '').strip()
|
||||
or str(getattr(attempt, 'status', None) or '').strip()
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user