feat(shipping_notice): 新增货代订单全流程业务模块及配套基建
本次提交新增货代订单处理全流程的完整业务能力、数据库迁移与测试用例: 1. 统一追加式审计事件体系,支持全链路不可篡改的业务追溯 2. 货代任务撤销、版本替代管控逻辑,规范已上传订单的合规版本更替 3. 订单抽取路由审计、模板自动冻结资格、路由计数等核心业务基建 4. EML订单补充表解析契约与合并逻辑,完善订单补全能力 5. Chatflow只读能力令牌校验机制,保障工具调用安全 6. 人工复核证据校验服务,规范人工审核的证据留存 所有变更均配套完整的单元测试与迁移契约测试,支持受控回退
This commit is contained in:
1 parent
90f77634d6
commit
1f3ecb87b7
128 files changed
+3635
-2074
No files matched your search
@@ -169,7 +169,6 @@ def delete_agent(agent_id: int) -> None:
|
||||
).count()
|
||||
run_count = ShippingOrderExtractionRun.query.filter(
|
||||
(ShippingOrderExtractionRun.owner_agent_id == agent.id)
|
||||
| (ShippingOrderExtractionRun.provider_agent_id == agent.id)
|
||||
).count()
|
||||
if binding_count or run_count:
|
||||
raise ConflictError(
|
||||
|
||||
@@ -85,14 +85,6 @@ agent_types:
|
||||
layout: workspace
|
||||
visualization: stepper
|
||||
handler_config_schema: {}
|
||||
required_runtime_capabilities:
|
||||
shipping.order_extraction:
|
||||
label: 订单抽取
|
||||
required: true
|
||||
allowed_runtime_providers: [dify]
|
||||
allowed_dify_app_types: [workflow]
|
||||
allowed_exposure_modes: [internal]
|
||||
allowed_effective_roles: [internal_executor]
|
||||
file_check:
|
||||
label: 文件检核
|
||||
conversation_mode_default: task_chat
|
||||
|
||||
@@ -16,8 +16,9 @@ CHAT_AGENT_NAME = "货代发货通知 Agent"
|
||||
|
||||
def resolve_chat_agent() -> Agent | None:
|
||||
"""按 agent_code=shipping_notice 查找当前启用的发货通知聊天 Agent 记录。"""
|
||||
return (
|
||||
agents = (
|
||||
Agent.query.filter_by(agent_code='shipping_notice', is_active=True)
|
||||
.order_by(Agent.id.asc())
|
||||
.first()
|
||||
.all()
|
||||
)
|
||||
return agents[0] if len(agents) == 1 else None
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/audit_service.py
|
||||
|
||||
用途:集中追加货代领域审计事件并拒绝含敏感业务载荷的元数据。
|
||||
依赖:ShippingAuditEvent、SQLAlchemy 会话。
|
||||
逻辑:Run、Task、库存和 Chatflow 服务调用本模块写入状态与决策事实;本服务不提交事务,由调用方保证业务与审计原子性。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
|
||||
|
||||
_FORBIDDEN_METADATA_KEYS = frozenset({
|
||||
'api_key', 'api_base_url', 'authorization', 'body', 'content', 'document_text', 'email_body',
|
||||
'password', 'prompt', 'provider_config', 'quote', 'token',
|
||||
})
|
||||
|
||||
|
||||
def _stable_hash(value: Any) -> str:
|
||||
"""对受控状态投影生成 SHA-256,避免审计表重复保存原始业务值。"""
|
||||
encoded = json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
|
||||
return hashlib.sha256(encoded.encode('ascii')).hexdigest()
|
||||
|
||||
|
||||
def _sanitize_metadata(metadata: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""验证元数据仅含脱敏诊断事实,阻断正文、凭据和字段值进入统一审计。"""
|
||||
safe = dict(metadata or {})
|
||||
forbidden = sorted(key for key in safe if str(key).lower() in _FORBIDDEN_METADATA_KEYS)
|
||||
if forbidden:
|
||||
raise ValidationError(
|
||||
'Shipping audit metadata contains forbidden keys',
|
||||
code='SHIPPING_NOTICE.AUDIT_METADATA_FORBIDDEN',
|
||||
)
|
||||
return safe
|
||||
|
||||
|
||||
def append_shipping_audit_event(
|
||||
*, event_type: str, aggregate_type: str, aggregate_id: str, run_no: str | None = None,
|
||||
task_no: str | None = None, intake_no: str | None = None, actor_type: str = 'system',
|
||||
actor_id: str | int | None = None, request_id: str | None = None,
|
||||
correlation_id: str | None = None, reason_code: str | None = None,
|
||||
before: Any = None, after: Any = None, metadata: dict[str, Any] | None = None,
|
||||
) -> ShippingAuditEvent:
|
||||
"""
|
||||
追加一条货代审计事实。
|
||||
|
||||
Args:
|
||||
event_type: 稳定业务事件名,例如 ``run_status_changed``;禁止传入用户自由文本。
|
||||
aggregate_type/aggregate_id: 业务聚合类型与稳定编号,不使用可删除记录的外键。
|
||||
before/after: 可复现的受控状态投影;只持久化其哈希。
|
||||
metadata: 仅允许原因码、计数、版本等脱敏诊断事实。
|
||||
|
||||
Returns:
|
||||
尚未提交的审计事件,由调用方与业务写入在同一事务提交。
|
||||
|
||||
Raises:
|
||||
ValidationError: actor 类型或元数据包含正文、凭据等敏感字段。
|
||||
"""
|
||||
allowed_actor_types = {'user', 'system', 'rpa', 'chatflow', 'admin'}
|
||||
if actor_type not in allowed_actor_types:
|
||||
raise ValidationError('Invalid shipping audit actor type', code='SHIPPING_NOTICE.AUDIT_ACTOR_INVALID')
|
||||
event = ShippingAuditEvent(
|
||||
event_type=str(event_type)[:64],
|
||||
aggregate_type=str(aggregate_type)[:64],
|
||||
aggregate_id=str(aggregate_id)[:128],
|
||||
run_no=str(run_no)[:64] if run_no else None,
|
||||
task_no=str(task_no)[:64] if task_no else None,
|
||||
intake_no=str(intake_no)[:64] if intake_no else None,
|
||||
actor_type=actor_type,
|
||||
actor_id=str(actor_id)[:128] if actor_id is not None else None,
|
||||
request_id=str(request_id)[:64] if request_id else None,
|
||||
correlation_id=str(correlation_id)[:64] if correlation_id else None,
|
||||
reason_code=str(reason_code)[:128] if reason_code else None,
|
||||
before_hash=_stable_hash(before) if before is not None else None,
|
||||
after_hash=_stable_hash(after) if after is not None else None,
|
||||
metadata_json=_sanitize_metadata(metadata),
|
||||
)
|
||||
db.session.add(event)
|
||||
return event
|
||||
|
||||
@@ -1183,6 +1183,11 @@ def create_shipping_batch_from_intakes(
|
||||
'operator_user_id': int(user_id),
|
||||
},
|
||||
)
|
||||
from app.services.shipping_notice.task_supersession_service import establish_task_supersession
|
||||
establish_task_supersession(
|
||||
old_task=prev, new_task=task, actor_id=int(user_id),
|
||||
reason=str(intake.duplicate_resolution_reason or 'customer resend revision'),
|
||||
)
|
||||
elif resolution_type == 'force_create':
|
||||
log_task_event(
|
||||
task,
|
||||
|
||||
@@ -4,7 +4,7 @@ backend/app/services/shipping_notice/business_fingerprint.py
|
||||
用途:基于业务摘要生成稳定业务指纹与强度判定(货代域,不含文件哈希)。
|
||||
依赖:po_number / reservation_id 标准化函数。
|
||||
逻辑:intake_parse_workflow / Candidate 级 duplicate_detection / 建单门闩共用;
|
||||
身份算法版本 shipping-v1,内容算法版本 shipping-content-v4。
|
||||
身份算法版本 shipping-v2,内容算法版本 shipping-content-v4。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,7 +17,7 @@ from typing import Any
|
||||
from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
FINGERPRINT_VERSION = 'shipping-v1'
|
||||
FINGERPRINT_VERSION = 'shipping-v2'
|
||||
CONTENT_FINGERPRINT_VERSION = 'shipping-content-v4'
|
||||
|
||||
|
||||
@@ -71,9 +71,8 @@ def build_business_fingerprint(business_summary: dict[str, Any] | None) -> dict[
|
||||
"""
|
||||
由业务摘要生成指纹、强度与组成依据。
|
||||
|
||||
核心逻辑(shipping-v1):
|
||||
- strong:客户身份(code 或 name)+ (PO 或 reservation 集合)
|
||||
或:PO + reservation 集合(稳定业务编号,无需客户码)
|
||||
核心逻辑(shipping-v2):
|
||||
- strong:客户身份(code 或 name)+ PO;Reservation、料号与数量只属于内容版本。
|
||||
- medium:客户身份 + 目的地 + required_date + 行 digest
|
||||
- weak:ship_to 或 仅行 digest(SKU+qty)
|
||||
- unavailable:不足以可靠去重
|
||||
@@ -87,14 +86,6 @@ def build_business_fingerprint(business_summary: dict[str, Any] | None) -> dict[
|
||||
summary = business_summary if isinstance(business_summary, dict) else {}
|
||||
customer_id, customer_field = _customer_identity(summary)
|
||||
po_number = normalize_po_number(str(summary.get('po_number') or '')) or ''
|
||||
reservation_ids = sorted(
|
||||
{
|
||||
validated_reservation_id(str(item)) or ''
|
||||
for item in (summary.get('reservation_ids') or [])
|
||||
if str(item or '').strip()
|
||||
}
|
||||
- {''}
|
||||
)
|
||||
dest = summary.get('destination') if isinstance(summary.get('destination'), dict) else {}
|
||||
destination_key = '|'.join(
|
||||
[
|
||||
@@ -111,19 +102,12 @@ def build_business_fingerprint(business_summary: dict[str, Any] | None) -> dict[
|
||||
strength = 'unavailable'
|
||||
components: dict[str, Any] = {}
|
||||
|
||||
# [STEP 1] 强指纹:客户身份 + 稳定单号;或仅 PO+Reservation(编号本身足够强)
|
||||
if customer_id and (po_number or reservation_ids):
|
||||
# [STEP 1] 订单身份只由客户 + PO 决定;可变订单内容必须转入 content_fingerprint。
|
||||
if customer_id and po_number:
|
||||
strength = 'strong'
|
||||
components = {
|
||||
customer_field: customer_id,
|
||||
'po_number': po_number or None,
|
||||
'reservation_ids': reservation_ids,
|
||||
}
|
||||
elif po_number and reservation_ids:
|
||||
strength = 'strong'
|
||||
components = {
|
||||
'po_number': po_number,
|
||||
'reservation_ids': reservation_ids,
|
||||
}
|
||||
elif customer_id and destination_key and required_date and line_digest:
|
||||
strength = 'medium'
|
||||
@@ -139,7 +123,7 @@ def build_business_fingerprint(business_summary: dict[str, Any] | None) -> dict[
|
||||
'ship_to': ship_to,
|
||||
'line_digest': hashlib.sha256(line_digest.encode('utf-8')).hexdigest()[:16],
|
||||
}
|
||||
elif line_digest and (reservation_ids or po_number or customer_id):
|
||||
elif line_digest and (po_number or customer_id):
|
||||
# 有行 digest 且至少一项单头标识:弱指纹,可标记 possible
|
||||
strength = 'weak'
|
||||
components = {
|
||||
@@ -149,8 +133,6 @@ def build_business_fingerprint(business_summary: dict[str, Any] | None) -> dict[
|
||||
components[customer_field] = customer_id
|
||||
if po_number:
|
||||
components['po_number'] = po_number
|
||||
if reservation_ids:
|
||||
components['reservation_ids'] = reservation_ids
|
||||
else:
|
||||
return {
|
||||
'fingerprint': None,
|
||||
|
||||
@@ -12,7 +12,7 @@ from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.notice_lines import non_atomic_part_number_field, normalize_notice_line
|
||||
from app.services.shipping_notice.po_number import normalize_po_number
|
||||
from app.services.shipping_notice.po_number import normalize_atomic_po_number
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
BUILD_REQUIRED_FIELDS = ('part_number', 'qty')
|
||||
@@ -59,7 +59,10 @@ def assess_candidate_business_summary(summary: dict[str, Any] | None) -> dict[st
|
||||
|
||||
normalized_summary = dict(raw)
|
||||
normalized_summary['lines'] = normalized_lines
|
||||
normalized_summary['po_number'] = normalize_po_number(raw.get('po_number')) or None
|
||||
# customer_po_number 是动态 Schema 的正式字段;po_number 保留为 Candidate/履约链路的兼容投影。
|
||||
normalized_summary['po_number'] = normalize_atomic_po_number(
|
||||
raw.get('customer_po_number') or raw.get('po_number')
|
||||
) or None
|
||||
normalized_summary['reservation_ids'] = sorted({
|
||||
normalized
|
||||
for line in normalized_lines
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Dify Chatflow 只读工具的短效能力令牌。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app.core.errors import ForbiddenError
|
||||
from app.models import ChatSession, ShippingTask
|
||||
|
||||
|
||||
READ_SCOPES = frozenset({'get_shipping_status', 'get_batch_status'})
|
||||
|
||||
|
||||
def _secret() -> bytes:
|
||||
value = str(current_app.config.get('SHIPPING_CHAT_CAPABILITY_SECRET') or current_app.config.get('SECRET_KEY') or '').strip()
|
||||
if not value:
|
||||
raise ForbiddenError('Chat capability service is unavailable', code='SHIPPING.CHAT_CAPABILITY_UNAVAILABLE')
|
||||
return value.encode('utf-8')
|
||||
|
||||
|
||||
def issue_chat_capability(*, user_id: int, session_id: str, agent_id: int, task_no: str | None, batch_no: str | None) -> str:
|
||||
"""为单次 Chatflow 注入签名、短效且绑定会话/对象的只读令牌。"""
|
||||
body = {'uid': int(user_id), 'sid': str(session_id), 'aid': int(agent_id), 'task': str(task_no or '').upper(), 'batch': str(batch_no or '').upper(), 'scopes': sorted(READ_SCOPES), 'exp': int(time.time()) + 300, 'nonce': uuid.uuid4().hex}
|
||||
raw = json.dumps(body, ensure_ascii=True, sort_keys=True, separators=(',', ':')).encode()
|
||||
signature = hmac.new(_secret(), raw, hashlib.sha256).digest()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip('=') + '.' + base64.urlsafe_b64encode(signature).decode().rstrip('=')
|
||||
|
||||
|
||||
def require_chat_capability(*, token: Any, scope: str, task_no: str | None = None, batch_no: str | None = None) -> dict[str, Any]:
|
||||
"""验证令牌签名、时效、scope、会话归属及请求对象,拒绝猜测他人编号。"""
|
||||
try:
|
||||
encoded, signed = str(token or '').split('.', 1)
|
||||
raw = base64.urlsafe_b64decode(encoded + '=' * (-len(encoded) % 4))
|
||||
signature = base64.urlsafe_b64decode(signed + '=' * (-len(signed) % 4))
|
||||
if not hmac.compare_digest(hmac.new(_secret(), raw, hashlib.sha256).digest(), signature): raise ValueError
|
||||
body = json.loads(raw)
|
||||
except Exception as exc:
|
||||
raise ForbiddenError('Invalid chat capability', code='SHIPPING.CHAT_CAPABILITY_INVALID') from exc
|
||||
if int(body.get('exp') or 0) < int(time.time()) or scope not in set(body.get('scopes') or []):
|
||||
raise ForbiddenError('Expired or unauthorized chat capability', code='SHIPPING.CHAT_CAPABILITY_DENIED')
|
||||
session = ChatSession.query.filter_by(session_id=str(body.get('sid') or ''), user_id=int(body.get('uid') or 0), agent_id=int(body.get('aid') or 0)).one_or_none()
|
||||
if session is None:
|
||||
raise ForbiddenError('Chat capability session is invalid', code='SHIPPING.CHAT_CAPABILITY_DENIED')
|
||||
if task_no:
|
||||
task = ShippingTask.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')
|
||||
if batch_no and str(body.get('batch') or '').upper() != str(batch_no).upper():
|
||||
raise ForbiddenError('Batch is outside chat capability scope', code='SHIPPING.CHAT_CAPABILITY_DENIED')
|
||||
return body
|
||||
@@ -162,6 +162,14 @@ def build_dify_chat_inputs(
|
||||
)
|
||||
if not runtime_context:
|
||||
return {}
|
||||
from app.models import ChatSession
|
||||
from app.services.shipping_notice.chat_tool_capability import issue_chat_capability
|
||||
session = ChatSession.query.filter_by(session_id=conv_id).one_or_none()
|
||||
capability_token = issue_chat_capability(
|
||||
user_id=session.user_id, session_id=conv_id, agent_id=session.agent_id,
|
||||
task_no=focus_task, batch_no=focus_batch,
|
||||
) if session is not None else None
|
||||
return {
|
||||
AGENT_RUNTIME_CONTEXT_INPUT: serialize_for_dify(runtime_context),
|
||||
**({'shipping_chat_capability_token': capability_token} if capability_token else {}),
|
||||
}
|
||||
@@ -35,6 +35,7 @@ from app.services.shipping_notice.business_fingerprint import (
|
||||
build_content_fingerprint,
|
||||
)
|
||||
from app.services.shipping_notice.eml_parse import pop_attachment_payload, strip_attachment_payloads
|
||||
from app.services.shipping_notice.email_allocation_table_parser import parse_email_allocation_tables
|
||||
from app.services.shipping_notice.intake_business_parser import parse_intake_business_summary
|
||||
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
|
||||
from app.services.shipping_notice.order_candidate_builder import (
|
||||
@@ -533,6 +534,27 @@ def persist_documents_and_candidates(
|
||||
},
|
||||
parser_key='eml-html-dom:shipping_document_layout.v1:v1',
|
||||
)
|
||||
# 正文表是 PO 级补充事实,永不作为订单 Candidate 或独立抽取 Unit。
|
||||
supplement = parse_email_allocation_tables(
|
||||
html_tables=canonical_html_tables,
|
||||
content_hash=str(body_doc.content_hash or ''),
|
||||
)
|
||||
supplement['document_id'] = int(body_doc.id)
|
||||
body_doc.order_extraction_result_json = {'email_supplement': supplement}
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
append_shipping_audit_event(
|
||||
event_type='email_supplement_parsed',
|
||||
aggregate_type='shipping_notice_intake',
|
||||
aggregate_id=intake.intake_no,
|
||||
intake_no=intake.intake_no,
|
||||
actor_type='system',
|
||||
metadata={
|
||||
'document_id': int(body_doc.id),
|
||||
'row_count': len(supplement.get('rows') or []),
|
||||
'issue_codes': list(supplement.get('issues') or []),
|
||||
'parser_version': supplement.get('version'),
|
||||
},
|
||||
)
|
||||
active_keys.add(BODY_ATTACHMENT_KEY)
|
||||
documents.append(body_doc)
|
||||
|
||||
|
||||
@@ -24,7 +24,9 @@ class ProfileMatchCandidate(BaseModel):
|
||||
version: int = Field(ge=1)
|
||||
score: float = Field(ge=0, le=1)
|
||||
hard_match: bool
|
||||
reasons: list[str] = Field(default_factory=list)
|
||||
reason_codes: list[str] = Field(default_factory=list)
|
||||
# Anchor IDs are template configuration identifiers, never document text.
|
||||
missing_required_anchor_ids: list[str] = Field(default_factory=list)
|
||||
|
||||
|
||||
class ProfileMatchResult(BaseModel):
|
||||
@@ -62,25 +64,29 @@ def match_frozen_coordinate_profiles(*, profiles: list[dict[str, Any]], layout:
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
reasons: list[str] = []
|
||||
reason_codes: list[str] = []
|
||||
if len(tables) < len(profile.table_regions):
|
||||
reasons.append('table_region_count_insufficient')
|
||||
reason_codes.append('table_region_count_insufficient')
|
||||
required = profile.document_match.required_anchors
|
||||
required_hits = [_anchor_present(
|
||||
anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
) for anchor in required]
|
||||
if not all(required_hits):
|
||||
reasons.append('required_anchor_missing')
|
||||
missing_required_anchor_ids = [
|
||||
anchor.anchor_id for anchor, present in zip(required, required_hits) if not present
|
||||
]
|
||||
if missing_required_anchor_ids:
|
||||
reason_codes.append('required_anchor_missing')
|
||||
optional = profile.document_match.optional_anchors
|
||||
optional_hits = sum(_anchor_present(
|
||||
anchor.model_dump(), tables=tables, glyph_tables=glyph_tables, page_glyphs=page_glyphs, pages=pages,
|
||||
) for anchor in optional)
|
||||
hard_match = not reasons
|
||||
hard_match = not reason_codes
|
||||
# Required evidence is mandatory rather than a soft score. Optional evidence only separates already valid templates.
|
||||
score = 1.0 if not optional else 0.8 + 0.2 * optional_hits / len(optional)
|
||||
candidates.append((raw, profile, ProfileMatchCandidate(
|
||||
profile_code=profile.profile_code, version=profile.version, score=score if hard_match else 0.0,
|
||||
hard_match=hard_match, reasons=reasons,
|
||||
hard_match=hard_match, reason_codes=reason_codes,
|
||||
missing_required_anchor_ids=missing_required_anchor_ids,
|
||||
)))
|
||||
rendered = sorted((item[2] for item in candidates), key=lambda item: (-item.score, item.profile_code, item.version))
|
||||
valid = sorted((item for item in candidates if item[2].hard_match), key=lambda item: (-item[2].score, item[1].profile_code, item[1].version))
|
||||
|
||||
@@ -18,6 +18,7 @@ from app.models import (
|
||||
ShippingDocumentProfileTestRun,
|
||||
ShippingDocumentProfileTestSample,
|
||||
ShippingDocumentProfileTestSuite,
|
||||
ShippingDocumentProfileAutoFreezeQualification,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderDocumentProfile,
|
||||
@@ -578,11 +579,82 @@ def approve_suite(*, suite_id: int, actor_id: int) -> dict[str, Any]:
|
||||
|
||||
|
||||
def profile_is_auto_create_approved(*, profile_id: int, checksum: str) -> bool:
|
||||
"""为 Run 冻结快照判断模板是否有当前 checksum 的已批准盲测凭证。"""
|
||||
suite = ShippingDocumentProfileTestSuite.query.filter_by(
|
||||
profile_id=int(profile_id), profile_checksum=str(checksum), status='approved',
|
||||
"""判断冻结模板版本是否已有独立的自动冻结批准资格。"""
|
||||
qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
|
||||
profile_id=int(profile_id), profile_checksum=str(checksum), status='auto_freeze_approved',
|
||||
).first()
|
||||
return suite is not None
|
||||
return qualification is not None
|
||||
|
||||
|
||||
def ensure_manual_confirmation_qualification(profile: ShippingOrderDocumentProfile) -> ShippingDocumentProfileAutoFreezeQualification:
|
||||
"""为新发布模板版本建立首版人工确认资格,不因盲测通过而自动升级。"""
|
||||
qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
|
||||
profile_id=profile.id, profile_version=profile.version, profile_checksum=str(profile.checksum or ''),
|
||||
).one_or_none()
|
||||
if qualification is None:
|
||||
qualification = ShippingDocumentProfileAutoFreezeQualification(
|
||||
profile_id=profile.id,
|
||||
profile_version=profile.version,
|
||||
profile_checksum=str(profile.checksum or ''),
|
||||
schema_version_id=profile.schema_version_id,
|
||||
parser_version='deterministic-order-parser.v1',
|
||||
status='manual_confirmation',
|
||||
)
|
||||
db.session.add(qualification)
|
||||
db.session.flush()
|
||||
_audit(profile_id=profile.id, event_type='auto_freeze_qualification_created', actor_id=None, detail={
|
||||
'qualification_id': qualification.id,
|
||||
'status': qualification.status,
|
||||
'profile_checksum': qualification.profile_checksum,
|
||||
})
|
||||
return qualification
|
||||
|
||||
|
||||
def qualification_summary(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
"""返回模板版本资格摘要;旧发布版本没有记录时安全降级为人工确认。"""
|
||||
qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
|
||||
profile_id=profile.id, profile_version=profile.version, profile_checksum=str(profile.checksum or ''),
|
||||
).one_or_none()
|
||||
if qualification is None:
|
||||
return {'status': 'manual_confirmation', 'auto_freeze_enabled': False, 'qualification_id': None}
|
||||
return {
|
||||
'status': qualification.status,
|
||||
'auto_freeze_enabled': qualification.status == 'auto_freeze_approved',
|
||||
'qualification_id': qualification.id,
|
||||
'parser_version': qualification.parser_version,
|
||||
'quality_suite_id': qualification.quality_suite_id,
|
||||
}
|
||||
|
||||
|
||||
def serialize_qualification(qualification: ShippingDocumentProfileAutoFreezeQualification) -> dict[str, Any]:
|
||||
"""以与 Profile DTO 相同的脱敏形状返回资格状态。"""
|
||||
return {
|
||||
'status': qualification.status,
|
||||
'auto_freeze_enabled': qualification.status == 'auto_freeze_approved',
|
||||
'qualification_id': qualification.id,
|
||||
'parser_version': qualification.parser_version,
|
||||
'quality_suite_id': qualification.quality_suite_id,
|
||||
}
|
||||
|
||||
|
||||
def suspend_auto_freeze_qualification(*, profile_id: int, actor_id: int, reason: str) -> ShippingDocumentProfileAutoFreezeQualification:
|
||||
"""单独暂停一个模板版本资格;即使未来已批准也立即阻断新的自动冻结。"""
|
||||
profile = _profile(profile_id)
|
||||
qualification = ShippingDocumentProfileAutoFreezeQualification.query.filter_by(
|
||||
profile_id=profile.id, profile_version=profile.version, profile_checksum=str(profile.checksum or ''),
|
||||
).one_or_none()
|
||||
if qualification is None:
|
||||
raise ConflictError('Profile qualification is unavailable', code='SHIPPING.ORDER_DOCUMENT_PROFILE_QUALIFICATION_NOT_FOUND')
|
||||
if qualification.status != 'auto_freeze_suspended':
|
||||
qualification.status = 'auto_freeze_suspended'
|
||||
qualification.suspended_by_id = actor_id
|
||||
qualification.suspended_at = datetime.utcnow()
|
||||
qualification.suspension_reason = str(reason or '').strip()[:2000] or 'manual_suspension'
|
||||
_audit(profile_id=profile.id, event_type='auto_freeze_qualification_suspended', actor_id=actor_id, detail={
|
||||
'qualification_id': qualification.id, 'reason_code': qualification.suspension_reason,
|
||||
})
|
||||
db.session.commit()
|
||||
return qualification
|
||||
|
||||
|
||||
def assert_profile_publishable(profile: ShippingOrderDocumentProfile) -> None:
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""解析 EML 正文 HTML 补充表并保留每格可追溯证据。
|
||||
|
||||
依赖:受控 HTML 网格解析、PO/Reservation 标准化。
|
||||
逻辑:只接受明确表头;表格歧义或缺 PO 保留原因,不将正文直接转成订单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.email_supplement_contract import (
|
||||
EMAIL_SUPPLEMENT_VERSION,
|
||||
empty_email_supplement_result,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.table_contract import 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
|
||||
|
||||
|
||||
_HEADERS = {
|
||||
'po_number': {'po', 'po number', 'po no', 'po #', 'purchase order', 'purchase order number'},
|
||||
'mpn': {'mpn', 'manufacturer part number', 'manufacturer pn', 'part number', 'mfr part number'},
|
||||
'reservation_id': {'reservation id', 'reservation', 'reservation no', 'reservation number'},
|
||||
'allocation_id': {'allocation id', 'allocation'},
|
||||
'source_type': {'source type', 'source', 'hub code', 'hub'},
|
||||
'source_from_party': {'source from party', 'source from', 'from party', 'supplier'},
|
||||
'allocated_entity': {'allocated entity', 'allocation entity'},
|
||||
'allocated_qty': {'allocated qty', 'allocated quantity', 'allocation qty', 'allocation quantity'},
|
||||
}
|
||||
_NORMALIZED_HEADERS = {
|
||||
field: {normalize_table_header(item) for item in aliases}
|
||||
for field, aliases in _HEADERS.items()
|
||||
}
|
||||
|
||||
|
||||
def _field_map(grid: Any) -> tuple[dict[int, str], list[str]]:
|
||||
"""只选择唯一映射的首行表头;重复字段映射直接标为复核。"""
|
||||
mapped: dict[int, str] = {}
|
||||
issues: list[str] = []
|
||||
for column, slot in enumerate(grid.rows[0]):
|
||||
normalized = normalize_table_header(slot.text if slot is not None else '')
|
||||
hits = [field for field, aliases in _NORMALIZED_HEADERS.items() if normalized in aliases]
|
||||
if len(hits) == 1:
|
||||
if hits[0] in mapped.values():
|
||||
issues.append('email_supplement_duplicate_header')
|
||||
else:
|
||||
mapped[column] = hits[0]
|
||||
elif len(hits) > 1:
|
||||
issues.append('email_supplement_header_ambiguous')
|
||||
if 'po_number' not in mapped.values():
|
||||
issues.append('email_supplement_po_header_missing')
|
||||
return mapped, sorted(set(issues))
|
||||
|
||||
|
||||
def parse_email_allocation_tables(*, html_tables: list[str], content_hash: str) -> dict[str, Any]:
|
||||
"""输出正文补充行和 DOM 单元格证据,不处理 PDF 合并或数量覆盖。"""
|
||||
result = empty_email_supplement_result()
|
||||
rows: list[dict[str, Any]] = []
|
||||
issues: list[str] = []
|
||||
for table_index, html in enumerate(html_tables):
|
||||
try:
|
||||
grid = parse_html_grid(str(html or ''), table_id=f'email-supplement:{content_hash}:{table_index}')
|
||||
except Exception:
|
||||
issues.append('email_supplement_table_invalid')
|
||||
continue
|
||||
mapping, table_issues = _field_map(grid)
|
||||
issues.extend(table_issues)
|
||||
if table_issues:
|
||||
continue
|
||||
for row_index in range(1, grid.row_count):
|
||||
values: dict[str, str] = {}
|
||||
evidence: dict[str, dict[str, Any]] = {}
|
||||
for column, field in mapping.items():
|
||||
slot = grid.rows[row_index][column]
|
||||
if slot is None or not str(slot.text or '').strip():
|
||||
continue
|
||||
value = str(slot.text).strip()
|
||||
values[field] = value
|
||||
evidence[field] = {
|
||||
'table_index': table_index, 'row_index': row_index,
|
||||
'column_index': column, 'cell_id': slot.cell_id,
|
||||
'raw_value': value,
|
||||
}
|
||||
po_number = normalize_po_number(values.get('po_number'))
|
||||
if not po_number:
|
||||
issues.append('email_supplement_row_po_missing')
|
||||
continue
|
||||
values['po_number'] = po_number
|
||||
if values.get('reservation_id'):
|
||||
normalized = validated_reservation_id(values['reservation_id'])
|
||||
if normalized:
|
||||
values['reservation_id'] = normalized
|
||||
else:
|
||||
issues.append('email_supplement_reservation_invalid')
|
||||
rows.append({
|
||||
**values, 'evidence': evidence, 'table_index': table_index,
|
||||
'row_index': row_index,
|
||||
})
|
||||
result.update({'rows': rows, 'issues': sorted(set(issues))})
|
||||
return result
|
||||
@@ -0,0 +1,21 @@
|
||||
"""定义 EML 正文订单补充表的稳定字段和可追溯数据契约。
|
||||
|
||||
依赖:仅标准库,供正文表解析、Run 冻结和订单合并共同使用。
|
||||
逻辑:正文是 PO 级补充事实而非订单 Unit;每个字段必须带表格/行/列证据。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
EMAIL_SUPPLEMENT_VERSION = 'email-supplement.v1'
|
||||
SUPPLEMENT_FIELDS = (
|
||||
'po_number', 'mpn', 'reservation_id', 'allocation_id', 'source_type',
|
||||
'source_from_party', 'allocated_entity', 'allocated_qty',
|
||||
)
|
||||
|
||||
|
||||
def empty_email_supplement_result() -> dict[str, Any]:
|
||||
"""返回无正文表时的稳定空结果,避免调用方以缺键猜测处理状态。"""
|
||||
return {'version': EMAIL_SUPPLEMENT_VERSION, 'rows': [], 'issues': []}
|
||||
@@ -42,6 +42,8 @@ def _storage_root() -> Path:
|
||||
|
||||
def order_field_id_values(task: ShippingTask) -> tuple[dict[str, Any], list[dict[str, Any]]]:
|
||||
"""从冻结 Snapshot 按稳定 field_id 返回 Header/Line 值,禁止履约阶段读取 FieldValue。"""
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
assert_task_not_supersession_blocked(task)
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, task.order_snapshot_id) if task.order_snapshot_id else None
|
||||
if snapshot is None:
|
||||
raise ValueError('任务没有可用于库存匹配的冻结订单快照')
|
||||
@@ -267,6 +269,11 @@ def generate_shipment_excel(task: ShippingTask) -> tuple[str, str, ShippingExpor
|
||||
Raises:
|
||||
ValueError: 库存源、模板、订单 Extraction 或解析 Profile 未形成完整发布链。
|
||||
"""
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
if not task_is_active(task):
|
||||
raise ValueError('已作废或归档的任务不能生成发货 Excel')
|
||||
assert_task_not_supersession_blocked(task)
|
||||
source_code = str(task.inventory_source_code or '').strip().upper()
|
||||
source = ShippingInventorySource.query.filter_by(source_code=source_code, enabled=True).first()
|
||||
if source is None:
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""
|
||||
冻结前履约就绪门禁。
|
||||
|
||||
用途:集中检查订单解析、字段裁决、客户、冲突与库存源状态,阻止不完整订单进入不可编辑快照。
|
||||
依赖:订单 Extraction、字段裁决、冲突门禁、库存源门禁及已发布履约策略。
|
||||
逻辑:order_freeze_service 在创建 Snapshot 前调用;失败统一返回结构化 blocking issues。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingTask
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import required_field_configs
|
||||
from app.services.shipping_notice.task_field_gate import open_field_conflict_issues
|
||||
|
||||
|
||||
def assert_freeze_readiness(*, task: ShippingTask, extraction: ShippingOrderExtraction, policy: Any, configs: dict[str, dict[str, Any]]) -> None:
|
||||
"""校验当前任务是否可冻结;任何问题均 fail closed,附带可展示的 issues。"""
|
||||
issues: list[dict[str, Any]] = []
|
||||
if extraction.status != 'accepted':
|
||||
issues.append({'reason': 'extraction_not_accepted'})
|
||||
issues.extend(open_field_conflict_issues(task))
|
||||
|
||||
required = required_field_configs(extraction.schema_version.definition_json or {}, policy)
|
||||
required_codes = {'reservation_id', 'part_number', 'qty'}
|
||||
values = ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id).all()
|
||||
decisions = ShippingOrderFieldDecision.query.filter_by(extraction_id=extraction.id).all()
|
||||
accepted = {(item.line_id, str(item.field_id)): item for item in decisions if item.decision_status in {'accepted', 'corroborated'}}
|
||||
value_map = {(item.line_id, str(item.field_id)): item.value_json for item in values}
|
||||
lines = ShippingOrderLine.query.filter_by(extraction_id=extraction.id).order_by(ShippingOrderLine.position).all()
|
||||
if not lines:
|
||||
issues.append({'reason': 'missing_order_lines'})
|
||||
for line in lines:
|
||||
for code in required_codes:
|
||||
config = required[code]
|
||||
key = (line.id, str(config['field_id']))
|
||||
value = value_map.get(key)
|
||||
if value in (None, ''):
|
||||
issues.append({'reason': 'required_field_missing_or_unreviewed', 'field': code, 'line_index': line.position})
|
||||
continue
|
||||
if code == 'qty':
|
||||
try:
|
||||
if Decimal(str(value)) <= 0:
|
||||
raise InvalidOperation
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
issues.append({'reason': 'quantity_not_positive', 'field': code, 'line_index': line.position})
|
||||
# Header PO is the version identity and cannot be empty or unresolved.
|
||||
po_config = configs.get('customer_po_number')
|
||||
if po_config:
|
||||
po_key = (None, str(po_config['field_id']))
|
||||
if value_map.get(po_key) in (None, ''):
|
||||
issues.append({'reason': 'customer_po_missing_or_unreviewed', 'field': 'customer_po_number'})
|
||||
if issues:
|
||||
raise ValidationError('Order is not ready to freeze', code='SHIPPING.ORDER_FREEZE_BLOCKED', details={'issues': issues})
|
||||
@@ -0,0 +1,41 @@
|
||||
"""货代撤销完成后的版本链解除服务。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import ShippingFreightCancellation, ShippingTask, ShippingTaskEvent
|
||||
|
||||
|
||||
def complete_freight_cancellation(*, cancellation_id: int, actor_id: int, freight_receipt_no: str, receipt_asset_id: int, note: str | None = None) -> ShippingFreightCancellation:
|
||||
"""登记可追溯的货代撤销回执,随后作废旧任务并解除新版本的履约阻断。"""
|
||||
row = ShippingFreightCancellation.query.filter_by(id=int(cancellation_id)).with_for_update().one_or_none()
|
||||
if row is None:
|
||||
raise NotFoundError('Freight cancellation not found', code='SHIPPING.FREIGHT_CANCELLATION_NOT_FOUND')
|
||||
if row.status == 'cancelled':
|
||||
return row
|
||||
receipt = str(freight_receipt_no or '').strip()
|
||||
if not receipt or not receipt_asset_id:
|
||||
raise ValidationError('Cancellation receipt number and file are required', code='SHIPPING.FREIGHT_CANCELLATION_RECEIPT_REQUIRED')
|
||||
old = ShippingTask.query.filter_by(id=row.old_task_id).with_for_update().one()
|
||||
new = ShippingTask.query.filter_by(id=row.new_task_id).with_for_update().one()
|
||||
if new.supersedes_task_id != old.id:
|
||||
raise ConflictError('Cancellation task relationship is invalid', code='SHIPPING.FREIGHT_CANCELLATION_INVALID')
|
||||
row.status = 'cancelled'
|
||||
row.completed_by_id = int(actor_id)
|
||||
row.completed_at = datetime.utcnow()
|
||||
row.freight_receipt_no = receipt
|
||||
row.receipt_asset_id = int(receipt_asset_id)
|
||||
row.failure_reason = str(note or '').strip() or None
|
||||
old.lifecycle_status = 'voided'
|
||||
old.voided_at = datetime.utcnow()
|
||||
old.voided_by_id = int(actor_id)
|
||||
old.void_reason = 'freight_cancellation_completed'
|
||||
if new.lifecycle_status == 'blocked' and new.pending_human_reason == 'freight_cancellation_required':
|
||||
new.lifecycle_status = 'active'
|
||||
new.pending_human_reason = None
|
||||
db.session.add(ShippingTaskEvent(task_id=old.id, event_type='freight_cancellation_completed', actor_id=actor_id, detail_json={'cancellation_id': row.id, 'receipt_no': receipt, 'new_task_no': new.task_no}))
|
||||
db.session.add(ShippingTaskEvent(task_id=new.id, event_type='supersession_unblocked', actor_id=actor_id, detail_json={'cancellation_id': row.id, 'old_task_no': old.task_no}))
|
||||
return row
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/intake_service.py
|
||||
|
||||
用途:发货通知接入记录(ShippingNoticeIntake)业务编排(含重复决策投影与权限)。
|
||||
依赖:file_assets.service、intake_parse_workflow、order_extraction、jobs.queue、models、
|
||||
duplicate_detection、attachment_integrity。
|
||||
duplicate_detection、attachment_integrity、document_layout 生命周期模型。
|
||||
逻辑:由 workspace API 与 chat action 调用;解析 Job 由 intake_parse_workflow 执行;
|
||||
创建 Intake:SAVEPOINT 插入 + IntegrityError 回落,mutate/enqueue 前 FOR UPDATE;
|
||||
cancelled/expired 拒绝复活;重投仅复用 queued Job(与 retry 同口径);
|
||||
@@ -24,7 +24,14 @@ from app.core.errors import ConflictError, ForbiddenError, NotFoundError, Valida
|
||||
from app.core.response import utc_iso
|
||||
from app.jobs.queue import QUEUED_ONLY_STATUSES, enqueue
|
||||
from app.jobs.types import JobType
|
||||
from app.models import FileAsset, ShippingNoticeIntake, ShippingTask, User
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
User,
|
||||
)
|
||||
from app.services.file_assets.service import get_asset_for_user, mark_asset_referenced
|
||||
from app.services.shipping_notice.attachment_integrity import is_attachment_parse_incomplete
|
||||
|
||||
@@ -180,6 +187,7 @@ def serialize_intake(
|
||||
parse_summary = structured if include_parse_texts else _lean_parse_summary(structured)
|
||||
documents = list_intake_documents(int(intake.id), include_text=include_parse_texts)
|
||||
candidates = list_intake_candidates(int(intake.id))
|
||||
layout_summary = _serialize_intake_layout_summary(int(intake.id))
|
||||
payload: dict[str, Any] = {
|
||||
'intake_no': intake.intake_no,
|
||||
'asset_no': asset.asset_no if asset else None,
|
||||
@@ -200,6 +208,8 @@ def serialize_intake(
|
||||
'candidates': candidates,
|
||||
'document_count': len(documents),
|
||||
'candidate_count': len(candidates),
|
||||
'layout_status': layout_summary['status'],
|
||||
'layout_summary': layout_summary,
|
||||
'warnings': list(intake.parse_warnings_json or []),
|
||||
'error_code': intake.error_code,
|
||||
'error_message': intake.error_message,
|
||||
@@ -215,6 +225,48 @@ def serialize_intake(
|
||||
return payload
|
||||
|
||||
|
||||
def _serialize_intake_layout_summary(intake_id: int) -> dict[str, Any]:
|
||||
"""
|
||||
汇总 Intake 下已调度的文档版面任务,供聊天页判断订单识别是否可启动。
|
||||
|
||||
Args:
|
||||
intake_id: ShippingNoticeIntake 主键;只统计其派生 Document 的布局版本。
|
||||
|
||||
Returns:
|
||||
脱敏状态与数量。processing 表示仍有 queued/running;completed 表示所有任务已终结;
|
||||
not_required 表示没有独立布局任务,不阻断文本或 Dify 兜底。
|
||||
"""
|
||||
rows = (
|
||||
db.session.query(ShippingDocumentLayoutVersion.status)
|
||||
.join(
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeDocument.id == ShippingDocumentLayoutVersion.document_id,
|
||||
)
|
||||
.filter(ShippingNoticeDocument.intake_id == int(intake_id))
|
||||
.all()
|
||||
)
|
||||
counts = {
|
||||
'queued': 0,
|
||||
'running': 0,
|
||||
'ready': 0,
|
||||
'needs_review': 0,
|
||||
'failed': 0,
|
||||
'unsupported': 0,
|
||||
}
|
||||
for (raw_status,) in rows:
|
||||
status = str(raw_status or '')
|
||||
if status in counts:
|
||||
counts[status] += 1
|
||||
total = sum(counts.values())
|
||||
if counts['queued'] or counts['running']:
|
||||
status = 'processing'
|
||||
elif total:
|
||||
status = 'completed'
|
||||
else:
|
||||
status = 'not_required'
|
||||
return {'status': status, 'total': total, **counts}
|
||||
|
||||
|
||||
def get_intake_for_user(intake_no: str, user_id: int) -> ShippingNoticeIntake:
|
||||
"""按编号查询当前用户的接入记录。"""
|
||||
normalized = str(intake_no or '').strip().upper()
|
||||
|
||||
@@ -95,6 +95,8 @@ def _inventory_source_gate_response(task: ShippingTask, *, operation: str, lang:
|
||||
库存相关 Tool 入口统一门禁;未稳定时返回 needs_human 响应。
|
||||
核心逻辑:先拦客户与 Reservation,再检查库存源稳定性;仅捕获预期 AppError。
|
||||
"""
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
assert_task_not_supersession_blocked(task)
|
||||
customer_gate = customer_gate_tool_response(task, operation=operation)
|
||||
if customer_gate is not None:
|
||||
return customer_gate
|
||||
|
||||
@@ -74,210 +74,28 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
runtime_context = _str_prop(
|
||||
"HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
|
||||
)
|
||||
capability_token = _str_prop("HXOPS 每轮注入的短效只读能力令牌;必须原样透传")
|
||||
return {
|
||||
"openapi": "3.0.0",
|
||||
"info": {
|
||||
"title": "Shipping Notice Tools",
|
||||
"version": "1.0.0",
|
||||
"description": (
|
||||
"货代发货通知 Agent Tool API。仅导出适合 Dify AI 编排层使用的工具:"
|
||||
"通知理解、字段修订、库存映射建议、人工确认收口与状态查询;"
|
||||
"不包含由后台任务统一续跑的主推进工具,也不包含 RPA 回调。"
|
||||
"推进类 Tool 的统一约束如下:必须依赖 HXOPS 状态机校验,必须基于唯一 task_id 推进;"
|
||||
"模糊指代不能直接推进,必须先通过 reference_context、get_task_status 或其他 HXOPS Tool 解析到唯一任务。"
|
||||
"submit_decision、match_inventory、generate_shipment_excel、upload_to_freight、retry_task、confirm_inventory_source、confirm_customer"
|
||||
" 这类推进动作都必须根据 HXOPS Tool 返回结果解释,不能脱离 Tool 返回自行编造状态。"
|
||||
"若 Tool 返回 needs_human 或 failed,不得自行改写成完成、成功上传或已处理完毕。"
|
||||
"如果响应包含 action_buttons,Dify 只解释当前状态、业务原因和影响,"
|
||||
"不要在自然语言正文列出按钮清单或“推荐下一步”动作列表;"
|
||||
"可点击按钮由宿主系统根据 action_buttons 统一渲染。"
|
||||
"鉴权:Authorization Bearer 或 X-Integration-Key。"
|
||||
"货代 Chatflow 仅作自然语言只读解释。所有写操作必须由 HXOPS 确认卡和后端状态机执行;"
|
||||
"本 OpenAPI 不包含改单、确认、冻结、库存、Excel 或上传接口。"
|
||||
),
|
||||
},
|
||||
"servers": [{"url": server}],
|
||||
"paths": {
|
||||
"/tools/create_temporary_inventory_session": _post_op(
|
||||
"create_temporary_inventory_session",
|
||||
"创建对话上传库存文件的临时分析会话",
|
||||
{
|
||||
"agent_runtime_context": runtime_context,
|
||||
"asset_no": _str_prop("当前用户上传的 FileAsset 编号;必须是 xls、xlsx 或 csv"),
|
||||
},
|
||||
required=["agent_runtime_context", "asset_no"],
|
||||
description=(
|
||||
"仅在用户明确说明附件为库存文件的 temporary_inventory 分支调用。"
|
||||
"后端按会话用户校验资产归属并执行结构初检;不会创建生产库存快照、"
|
||||
"不会绑定库存站点、不会执行库存匹配。"
|
||||
),
|
||||
),
|
||||
"/tools/get_temporary_inventory_session": _post_op(
|
||||
"get_temporary_inventory_session",
|
||||
"读取临时库存文件的脱敏结构分析和方案候选",
|
||||
{
|
||||
"agent_runtime_context": runtime_context,
|
||||
"temporary_session_no": _str_prop("create_temporary_inventory_session 返回的临时会话编号"),
|
||||
},
|
||||
required=["agent_runtime_context", "temporary_session_no"],
|
||||
description=(
|
||||
"返回后端已分析的工作表、表头、字段目录和已发布方案候选,不返回样例库存值。"
|
||||
"Dify 不得读取文件路径、全量库存行,也不得据此直接宣称库存已可用于订单匹配。"
|
||||
),
|
||||
),
|
||||
"/tools/submit_temporary_inventory_mapping_suggestion": _post_op(
|
||||
"submit_temporary_inventory_mapping_suggestion",
|
||||
"保存对话临时库存的候选字段映射",
|
||||
{
|
||||
"agent_runtime_context": runtime_context,
|
||||
"temporary_session_no": _str_prop("临时库存会话编号"),
|
||||
"field_mapping": {
|
||||
"type": "object",
|
||||
"description": "库存字段目录 ID 到真实来源表头的映射;只能使用 get_temporary_inventory_session 返回的字段 ID 和表头",
|
||||
"additionalProperties": {"type": "string"},
|
||||
},
|
||||
},
|
||||
required=["agent_runtime_context", "temporary_session_no", "field_mapping"],
|
||||
description=(
|
||||
"仅在没有 exact 已发布方案可复用时调用。HXOPS 校验字段目录、真实表头、重复列和核心字段完整性,"
|
||||
"只保存待用户确认的候选;不会发布方案、绑定库存站点、创建库存快照或执行订单匹配。"
|
||||
),
|
||||
),
|
||||
"/tools/confirm_temporary_inventory_use": _post_op(
|
||||
"confirm_temporary_inventory_use",
|
||||
"确认当前对话临时库存文件使用",
|
||||
{
|
||||
"agent_runtime_context": runtime_context,
|
||||
"temporary_session_no": _str_prop("临时库存会话编号"),
|
||||
"selected_profile_id": _int_prop("仅 exact 已发布方案候选时由用户选择的方案 ID"),
|
||||
},
|
||||
required=["agent_runtime_context", "temporary_session_no"],
|
||||
description=(
|
||||
"仅在用户明确确认本次使用后调用。HXOPS 重新确定性解析文件并校验料号、预约号、库存数量;"
|
||||
"只锁定当前对话的临时会话审计,不接受任务编号,绝不创建生产库存快照、绑定库存站点、"
|
||||
"写入任务库存行或执行库存匹配。"
|
||||
),
|
||||
),
|
||||
"/tools/update_notice_fields": _post_op(
|
||||
"update_notice_fields",
|
||||
"更新解析后的发货通知单头字段,如客户、PO、交期、收货地",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"description": "可更新字段:customer_name/customer_code/ship_to/po_number/required_date",
|
||||
"additionalProperties": True,
|
||||
},
|
||||
"comment": _str_prop("修改备注(可选)"),
|
||||
},
|
||||
required=["task_id", "fields"],
|
||||
),
|
||||
"/tools/update_notice_line": _post_op(
|
||||
"update_notice_line",
|
||||
"更新解析结果中的某一行,如内部料号、Reservation ID、数量、交期",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"line_index": _int_prop("行下标,从 0 开始"),
|
||||
"patch": {
|
||||
"type": "object",
|
||||
"description": (
|
||||
"可更新字段:part_number/reservation_id/quantity/qty/required_date/uom/"
|
||||
"inventory_source_hint;inventory_source_hint 为可选订单路由线索"
|
||||
),
|
||||
"additionalProperties": True,
|
||||
},
|
||||
"comment": _str_prop("修改备注(可选)"),
|
||||
},
|
||||
required=["task_id", "line_index", "patch"],
|
||||
),
|
||||
"/tools/add_notice_line": _post_op(
|
||||
"add_notice_line",
|
||||
"向解析结果新增一行发货需求",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"line": {
|
||||
"type": "object",
|
||||
"description": "新增行,至少包含 part_number 和 qty/quantity",
|
||||
"additionalProperties": True,
|
||||
},
|
||||
"comment": _str_prop("修改备注(可选)"),
|
||||
},
|
||||
required=["task_id", "line"],
|
||||
),
|
||||
"/tools/remove_notice_line": _post_op(
|
||||
"remove_notice_line",
|
||||
"删除解析结果中的某一行发货需求",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"line_index": _int_prop("行下标,从 0 开始"),
|
||||
"comment": _str_prop("修改备注(可选)"),
|
||||
},
|
||||
required=["task_id", "line_index"],
|
||||
),
|
||||
"/tools/confirm_inventory_source": _post_op(
|
||||
"confirm_inventory_source",
|
||||
"在库存源人工检查点确认正式库存查询来源(仅提交 source_code)",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"source_code": _str_prop(
|
||||
"启用配置中的库存源编码;Warehouse 由 fixed Source 配置或库存行匹配解析,禁止前端直传"
|
||||
),
|
||||
},
|
||||
required=["task_id", "source_code"],
|
||||
description=(
|
||||
"库存连接器门禁:稳定身份须具备 source_code、connector_type;fixed Source 同时具备 warehouse_id,"
|
||||
"且 routing_fingerprint 与当前配置版本一致。"
|
||||
"Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。"
|
||||
"若返回 needs_human,说明身份未完整解析或需先完成解析确认。"
|
||||
),
|
||||
),
|
||||
"/tools/confirm_customer": _post_op(
|
||||
"confirm_customer",
|
||||
"在客户人工检查点确认标准客户(仅提交 customer_id)",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"customer_id": _int_prop("用户从 HXOPS 标准客户列表中明确选择的客户 ID"),
|
||||
},
|
||||
required=["task_id", "customer_id"],
|
||||
description=(
|
||||
"仅在 customer_review 检查点且用户已经明确选择标准客户后调用。"
|
||||
"禁止根据邮件中的不稳定客户名称自行猜测 customer_id;客户确认成功后由 HXOPS 决定后续流程。"
|
||||
),
|
||||
),
|
||||
"/tools/submit_decision": _post_op(
|
||||
"submit_decision",
|
||||
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"),
|
||||
"decision": _str_prop(
|
||||
"confirm=确认继续;reject=驳回;retry_rpa=按已发布解析方案重新获取库存;rematch=重新匹配;reparse=重新解析",
|
||||
enum=[
|
||||
"confirm",
|
||||
"confirm_parse",
|
||||
"reject",
|
||||
"retry_rpa",
|
||||
"rematch",
|
||||
"reparse",
|
||||
],
|
||||
),
|
||||
"comment": _str_prop("备注(可选)"),
|
||||
},
|
||||
required=["decision"],
|
||||
description=(
|
||||
"人工复核决策入口。必须先定位到唯一 task_id 才能推进;若 conversation_id 对应多个任务,必须先追问或调用状态查询工具确认,"
|
||||
"禁止用模糊指代直接推进。"
|
||||
"本 Tool 的返回结果以 HXOPS 状态机为准,Dify 必须根据实际返回的 status、checkpoint、forbidden_next_tools、"
|
||||
"human_options 或 action_buttons 解释当前现场。"
|
||||
"若返回 needs_human 或 failed,不得自行宣布完成、不得改写为成功,也不要在正文列出按钮清单;"
|
||||
"按钮由 HXOPS 前端渲染。"
|
||||
),
|
||||
),
|
||||
"/tools/get_task_status": _post_op(
|
||||
"get_task_status",
|
||||
"查询任务当前状态与 human_options;响应含库存连接器独立字段与候选结构",
|
||||
{
|
||||
"task_id": task_id,
|
||||
"conversation_id": _str_prop("Dify 会话 ID"),
|
||||
"shipping_chat_capability_token": capability_token,
|
||||
},
|
||||
required=["task_id", "shipping_chat_capability_token"],
|
||||
description=(
|
||||
"返回 inventory_source_code、inventory_connector_type、"
|
||||
"inventory_warehouse_id、inventory_source_status(unresolved|ambiguous|resolved|"
|
||||
@@ -292,8 +110,9 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
"查询批次当前状态、任务列表与当前聚焦任务",
|
||||
{
|
||||
"batch_no": batch_id,
|
||||
"shipping_chat_capability_token": capability_token,
|
||||
},
|
||||
required=["batch_no"],
|
||||
required=["batch_no", "shipping_chat_capability_token"],
|
||||
),
|
||||
},
|
||||
}
|
||||
@@ -368,6 +368,7 @@ def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
except Exception:
|
||||
# DTO listing must remain available even when the current Schema is temporarily unavailable.
|
||||
compatibility = None
|
||||
from app.services.shipping_notice.document_profile_quality_service import qualification_summary
|
||||
return {
|
||||
'id': profile.id,
|
||||
'profile_code': profile.profile_code,
|
||||
@@ -398,6 +399,7 @@ def payload(profile: ShippingOrderDocumentProfile) -> dict[str, Any]:
|
||||
)
|
||||
else 'normal'
|
||||
),
|
||||
'auto_freeze_qualification': qualification_summary(profile),
|
||||
}
|
||||
|
||||
|
||||
@@ -2090,14 +2092,11 @@ def publish(
|
||||
'All draft order field layouts must be bound before publish',
|
||||
code='SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_INVALID',
|
||||
)
|
||||
# 发布前先以草稿定义 checksum 执行训练/盲测门禁;不能先发布再补测。
|
||||
# 发布只校验模板定义;自动冻结资格由独立的质量发布流程维护。
|
||||
from app.services.shipping_notice.document_profile_quality_service import (
|
||||
assert_profile_publishable,
|
||||
promote_approved_suite_for_publish,
|
||||
ensure_manual_confirmation_qualification,
|
||||
)
|
||||
|
||||
draft_checksum = str(profile.structure_fingerprint or '')
|
||||
assert_profile_publishable(profile)
|
||||
schema_version = _require_schema_version(profile.schema_version_id)
|
||||
normalized = _normalize_definition(profile.definition_json, schema_version=schema_version)
|
||||
profile.definition_json = normalized
|
||||
@@ -2122,9 +2121,7 @@ def publish(
|
||||
profile.status = 'published'
|
||||
profile.published_by_id = actor_id
|
||||
profile.published_at = now
|
||||
promote_approved_suite_for_publish(
|
||||
profile=profile, draft_checksum=draft_checksum, published_checksum=profile.checksum,
|
||||
)
|
||||
ensure_manual_confirmation_qualification(profile)
|
||||
_audit(profile_id=profile.id, event_type='published', actor_id=actor_id, detail={
|
||||
'checksum': profile.checksum, 'version': profile.version,
|
||||
})
|
||||
|
||||
@@ -43,7 +43,7 @@ from app.services.shipping_notice.duplicate_detection import (
|
||||
from app.services.shipping_notice.document_candidate_persist import generate_candidate_no
|
||||
from app.services.shipping_notice.order_schema.runtime import persist_dynamic_order
|
||||
from app.services.shipping_notice.context_fields.runtime import canonical_mail_context
|
||||
from app.services.shipping_notice.order_extraction_workflow import frozen_document_text_for_dify
|
||||
from app.services.shipping_notice.order_extraction_workflow import frozen_document_text_for_parser
|
||||
|
||||
|
||||
def _load_intakes(
|
||||
@@ -183,7 +183,7 @@ def persist_order_extraction_result(
|
||||
orders: list[dict[str, Any]],
|
||||
run_id: int | None,
|
||||
schema_version_id: int,
|
||||
extraction_source: str = 'dify_workflow',
|
||||
extraction_source: str = 'deterministic_order_parser',
|
||||
frozen_context_by_intake: dict[int, dict[str, Any]] | None = None,
|
||||
frozen_layout_candidates_by_document: dict[int, list[dict[str, Any]]] | None = None,
|
||||
frozen_evidence_text_by_document: dict[int, str] | None = None,
|
||||
@@ -198,13 +198,13 @@ def persist_order_extraction_result(
|
||||
documents: 上述 Intake 的当前锁定 Document,用于证据归属和漂移校验。
|
||||
current_snapshot: 已与 Run 冻结输入核对一致的内容摘要。
|
||||
request_id: Run 编号,作为 Candidate/Submission 的服务端幂等围栏。
|
||||
orders: 专用 Workflow 输出的结构化订单数组。
|
||||
orders: 固定模板解析器输出的结构化订单数组。
|
||||
run_id: ShippingOrderExtractionRun 主键;生产 Run 必须提供,领域单测可为空。
|
||||
schema_version_id: Run 冻结的 published Schema 版本。
|
||||
extraction_source: 固定为后台 Workflow 来源,不接受用户输入。
|
||||
extraction_source: 固定为确定性解析来源,不接受用户输入。
|
||||
frozen_context_by_intake: Run 按 Intake 冻结的确定性上下文;后台 Run 必须提供。
|
||||
frozen_layout_candidates_by_document: Run 按 Document 冻结的 L4 字段候选;只接受 accepted cell 证据。
|
||||
frozen_evidence_text_by_document: Run 实际发送给 Dify 的冻结文本;用于同源 quote 核验。
|
||||
frozen_evidence_text_by_document: Run 冻结的证据文本;用于同源 quote 核验。
|
||||
auto_create_enabled: 冻结发布门禁;关闭时只落 Candidate,不自动创建/打开 Task。
|
||||
Returns:
|
||||
自动创建/打开的任务、待处理订单及缺失流程字段摘要。
|
||||
@@ -741,7 +741,7 @@ def submit_order_extraction_run_result(
|
||||
}
|
||||
frozen_evidence_text_by_document = {
|
||||
int(document['document_id']): (
|
||||
frozen_document_text_for_dify(document) or str(document.get('extracted_text') or '')
|
||||
frozen_document_text_for_parser(document) or str(document.get('extracted_text') or '')
|
||||
)
|
||||
for intake in snapshot_intakes if isinstance(intake, dict)
|
||||
for document in intake.get('documents') or []
|
||||
@@ -800,8 +800,8 @@ def submit_order_extraction_run_result(
|
||||
db.session.commit()
|
||||
return result
|
||||
cached_orders = (
|
||||
run.provider_result_json.get('orders')
|
||||
if isinstance(run.provider_result_json, dict)
|
||||
run.execution_result_json.get('orders')
|
||||
if isinstance(run.execution_result_json, dict)
|
||||
else None
|
||||
)
|
||||
if (
|
||||
@@ -885,11 +885,11 @@ def submit_order_extraction_run_result(
|
||||
orders=orders,
|
||||
run_id=int(run.id),
|
||||
schema_version_id=int(run.schema_version_id),
|
||||
extraction_source='dify_workflow',
|
||||
extraction_source='deterministic_order_parser',
|
||||
frozen_context_by_intake=frozen_context_by_intake,
|
||||
frozen_layout_candidates_by_document=frozen_layout_candidates_by_document,
|
||||
frozen_evidence_text_by_document=frozen_evidence_text_by_document,
|
||||
auto_create_enabled=bool(
|
||||
((run.input_snapshot_json or {}).get('auto_creation_policy') or {}).get('enabled', False)
|
||||
((run.auto_freeze_policy_json or {}).get('enabled', False))
|
||||
),
|
||||
)
|
||||
@@ -12,6 +12,7 @@ import copy
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.reservation_id import is_valid_reservation_id
|
||||
from app.services.shipping_notice.po_number import normalize_atomic_po_number
|
||||
|
||||
|
||||
def _field_values(fields: Any, field_code: str, codes: dict[str, str]) -> set[str]:
|
||||
@@ -92,7 +93,14 @@ def _find_unique_reservation_completion_line(
|
||||
|
||||
def _order_identity(order: dict[str, Any], codes: dict[str, str]) -> tuple[set[str], set[tuple[str, str]]]:
|
||||
"""返回可用于保守合并的 PO 集合和强行身份集合。"""
|
||||
po_numbers = _field_values(order.get('header_fields'), 'po_number', codes)
|
||||
# customer_po_number 是当前 Schema 正式字段;旧 Schema 的 po_number 只保留兼容。
|
||||
# 多 PO 自由文本不能形成订单身份,避免把邮件摘要错误并入附件订单。
|
||||
po_numbers = {
|
||||
normalized
|
||||
for field_code in ('customer_po_number', 'po_number')
|
||||
for value in _field_values(order.get('header_fields'), field_code, codes)
|
||||
if (normalized := normalize_atomic_po_number(value).upper())
|
||||
}
|
||||
line_keys = {
|
||||
identity for line in order.get('lines') or []
|
||||
if isinstance(line, dict) and (identity := _line_identity(line, codes)) is not None
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/order_extraction_plan.py
|
||||
|
||||
用途:把 Run 冻结快照编译为可恢复、可审计的文档级抽取计划。
|
||||
依赖:ShippingOrderExtractionRun、Plan/Unit ORM、统一校验错误。
|
||||
逻辑:创建 Run 和 Worker 恢复时复用同一幂等入口;正文与附件各自形成独立单元,不复制正文。
|
||||
逻辑:创建 Run 和 Worker 恢复时复用同一幂等入口;仅附件形成执行单元,正文补充事实不复制正文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,7 +23,7 @@ from app.models import (
|
||||
PLAN_VERSION = 'shipping_order_extraction.plan.v1'
|
||||
UNIT_TRANSITIONS = {
|
||||
'pending': {'running', 'skipped'},
|
||||
'running': {'succeeded', 'failed'},
|
||||
'running': {'succeeded', 'failed', 'skipped'},
|
||||
'failed': {'pending'},
|
||||
'succeeded': set(),
|
||||
'skipped': set(),
|
||||
@@ -88,7 +88,12 @@ def ensure_order_extraction_plan(run: ShippingOrderExtractionRun) -> ShippingOrd
|
||||
)
|
||||
return existing
|
||||
|
||||
documents = _snapshot_documents(run)
|
||||
documents = [item for item in _snapshot_documents(run) if item['document_type'] != 'email_body']
|
||||
if not documents:
|
||||
raise ValidationError(
|
||||
'Frozen extraction run contains no attachment units',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_SNAPSHOT_OBSOLETE',
|
||||
)
|
||||
plan = ShippingOrderExtractionPlan(
|
||||
run_id=run.id,
|
||||
plan_version=PLAN_VERSION,
|
||||
@@ -105,7 +110,7 @@ def ensure_order_extraction_plan(run: ShippingOrderExtractionRun) -> ShippingOrd
|
||||
intake_id=document['intake_id'],
|
||||
document_id=document['document_id'],
|
||||
position=position,
|
||||
unit_type='email_relation' if document_type == 'email_body' else 'document_extraction',
|
||||
unit_type='document_extraction',
|
||||
document_type=document_type,
|
||||
content_hash=document['content_hash'],
|
||||
status='pending',
|
||||
@@ -142,7 +147,7 @@ def transition_order_extraction_unit(
|
||||
|
||||
Args:
|
||||
unit: 已加载且由调用方在事务内持有的计划单元。
|
||||
target_status: 当前状态允许的下一状态;失败重试必须先回到 pending。
|
||||
target_status: 当前状态允许的下一状态;`skipped` 表示业务复核,失败重试必须先回到 pending。
|
||||
result: 仅 succeeded 可写的结构化局部结果,不得包含正文或凭据。
|
||||
error_code/error_message: 仅 failed 可写的安全诊断摘要。
|
||||
Returns:
|
||||
@@ -154,6 +159,9 @@ def transition_order_extraction_unit(
|
||||
f'Invalid order extraction unit transition: {current} -> {target_status}',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_TRANSITION_INVALID',
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
before_projection = {'status': current, 'attempt_count': int(unit.attempt_count or 0)}
|
||||
now = datetime.utcnow()
|
||||
unit.status = target_status
|
||||
if target_status == 'running':
|
||||
@@ -178,6 +186,22 @@ def transition_order_extraction_unit(
|
||||
unit.error_code = None
|
||||
unit.error_message = None
|
||||
elif target_status == 'skipped':
|
||||
unit.result_json = None
|
||||
unit.error_code = str(error_code or 'SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED')[:64]
|
||||
unit.error_message = str(error_message or 'Order extraction requires review')[:2000]
|
||||
unit.finished_at = now
|
||||
plan_run = getattr(unit.plan, 'run', None)
|
||||
if plan_run is not None and getattr(plan_run, 'run_no', None):
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_unit_status_changed',
|
||||
aggregate_type='order_extraction_unit',
|
||||
aggregate_id=str(unit.id),
|
||||
run_no=str(plan_run.run_no),
|
||||
actor_type='system',
|
||||
reason_code=unit.error_code if target_status in {'failed', 'skipped'} else None,
|
||||
before=before_projection,
|
||||
after={'status': target_status, 'attempt_count': int(unit.attempt_count or 0)},
|
||||
metadata={'target_status': target_status},
|
||||
)
|
||||
_refresh_plan_status(unit.plan)
|
||||
return unit
|
||||
@@ -123,8 +123,6 @@ def _apply_projection(run: ShippingOrderExtractionRun, event: dict[str, Any], st
|
||||
elif event_type == 'recovered':
|
||||
active.discard('auto_recovering')
|
||||
|
||||
if event.get('workflow_run_id'):
|
||||
run.dify_workflow_run_id = _safe_text(event.get('workflow_run_id'), 128)
|
||||
run.active_stage_codes_json = sorted(active)
|
||||
run.completed_stage_codes_json = sorted(completed)
|
||||
run.current_stage_code = _main_stage(active, completed, run.current_stage_code)
|
||||
|
||||
@@ -170,7 +170,7 @@ def save_quality_label(*, batch_id: int, run_no: str, actor_id: int, payload: An
|
||||
or int(run.schema_version_id) != int(batch.schema_version_id)
|
||||
or run.status not in {'completed', 'needs_review'}
|
||||
# 自动建单 Run 属于生产执行,不能反向作为影子质量验收样本。
|
||||
or bool((run.provider_config_json or {}).get('auto_create_enabled'))
|
||||
or bool((run.auto_freeze_policy_json or {}).get('enabled'))
|
||||
):
|
||||
raise ValidationError(
|
||||
'Run is not eligible for this quality batch',
|
||||
|
||||
@@ -30,6 +30,7 @@ from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRunIntake,
|
||||
ShippingOrderSchemaVersion,
|
||||
@@ -260,6 +261,12 @@ def _build_snapshot(
|
||||
'parse_warnings': document.parse_warnings_json or [],
|
||||
'layout_snapshot': layout_snapshot,
|
||||
'layout_schema_candidates': layout_schema_candidates,
|
||||
'email_supplement': (
|
||||
(document.order_extraction_result_json or {}).get('email_supplement')
|
||||
if document.document_type == 'email_body'
|
||||
and isinstance(document.order_extraction_result_json, dict)
|
||||
else None
|
||||
),
|
||||
})
|
||||
incomplete = [
|
||||
intake.intake_no
|
||||
@@ -299,12 +306,43 @@ def _build_snapshot(
|
||||
'deterministic_context': canonical_mail_context(intake),
|
||||
'extracted_text': intake.extracted_text or '',
|
||||
'documents': documents_by_intake[intake.id],
|
||||
'email_supplements': [
|
||||
item['email_supplement'] for item in documents_by_intake[intake.id]
|
||||
if isinstance(item.get('email_supplement'), dict)
|
||||
],
|
||||
}
|
||||
for intake in intakes
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _require_layouts_terminal_before_snapshot(*, intakes: list[ShippingNoticeIntake]) -> None:
|
||||
"""阻断仍在解析版面的附件,避免 Run 冻结空 Layout 后永久错过确定性模板路由。"""
|
||||
document_ids = [
|
||||
int(document_id)
|
||||
for (document_id,) in db.session.query(ShippingNoticeDocument.id)
|
||||
.filter(ShippingNoticeDocument.intake_id.in_([intake.id for intake in intakes]))
|
||||
.all()
|
||||
]
|
||||
if not document_ids:
|
||||
return
|
||||
pending = (
|
||||
db.session.query(ShippingDocumentLayoutVersion)
|
||||
.filter(
|
||||
ShippingDocumentLayoutVersion.document_id.in_(document_ids),
|
||||
ShippingDocumentLayoutVersion.status.in_({'queued', 'running'}),
|
||||
)
|
||||
.order_by(ShippingDocumentLayoutVersion.document_id.asc())
|
||||
.all()
|
||||
)
|
||||
if pending:
|
||||
raise ConflictError(
|
||||
'Shipping notice document layout is still processing',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PENDING',
|
||||
details={'document_ids': [int(item.document_id) for item in pending]},
|
||||
)
|
||||
|
||||
|
||||
def _active_run_for_intakes(intake_ids: list[int]) -> ShippingOrderExtractionRun | None:
|
||||
"""读取占用任一 Intake 的未释放 Run,供并发唯一约束冲突后返回明确业务结果。"""
|
||||
return (
|
||||
@@ -373,38 +411,15 @@ def create_order_extraction_run(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_REPARSABLE',
|
||||
)
|
||||
intakes = _load_intakes(user_id=user.id, intake_nos=intake_nos)
|
||||
from app.services.agent_runtime_binding_service import resolve_executor_governance, resolve_runtime_binding
|
||||
|
||||
binding = resolve_runtime_binding(
|
||||
owner_agent_id=owner_agent.id,
|
||||
capability_code='shipping.order_extraction',
|
||||
)
|
||||
schema_version = published_version()
|
||||
binding_auto_create_enabled = bool((binding.config_json or {}).get('auto_create_enabled'))
|
||||
from app.services.shipping_notice.order_schema.service import get_auto_creation_policy
|
||||
|
||||
schema_auto_creation_policy = get_auto_creation_policy()
|
||||
effective_auto_create_enabled = bool(
|
||||
schema_auto_creation_policy.get('enabled') and binding_auto_create_enabled
|
||||
)
|
||||
quality_batch_id = binding.quality_batch_id
|
||||
if effective_auto_create_enabled:
|
||||
from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch
|
||||
|
||||
require_approved_quality_batch(
|
||||
batch_id=quality_batch_id,
|
||||
owner_agent_id=owner_agent.id,
|
||||
schema_version_id=int(schema_version.id),
|
||||
)
|
||||
# 绑定决定本业务如何执行;执行器决定所有调用方共享的容量与熔断保护,两者一起冻结到 Run。
|
||||
binding_config = {
|
||||
**dict(binding.config_json or {}),
|
||||
# 单元执行参数属于实现细节,使用统一保守默认值而不在应用管理形成配置分支。
|
||||
'unit_concurrency': 2,
|
||||
'unit_max_attempts': 2,
|
||||
'unit_retry_backoff_ms': 500,
|
||||
'max_model_units': 20,
|
||||
**resolve_executor_governance(binding.provider_agent),
|
||||
# 第一版统一人工确认;Schema 的历史自动建单开关不再驱动订单解析执行器。
|
||||
auto_freeze_policy = {
|
||||
'mode': 'manual_confirmation',
|
||||
'enabled': False,
|
||||
'schema_policy_version': schema_auto_creation_policy.get('version'),
|
||||
}
|
||||
session = _resolve_conversation(
|
||||
user_id=user.id,
|
||||
@@ -413,6 +428,7 @@ def create_order_extraction_run(
|
||||
intakes=intakes,
|
||||
)
|
||||
conversation_id = session.session_id
|
||||
_require_layouts_terminal_before_snapshot(intakes=intakes)
|
||||
snapshot = _build_snapshot(
|
||||
user_id=user.id,
|
||||
owner_agent_id=owner_agent.id,
|
||||
@@ -420,14 +436,7 @@ def create_order_extraction_run(
|
||||
intakes=intakes,
|
||||
schema_version=schema_version,
|
||||
)
|
||||
# 自动建单必须同时通过 Schema 总开关、运行能力绑定和质量批次;任何一层关闭
|
||||
# 都冻结为影子模式,避免仅改 Schema 意外恢复自动履约。
|
||||
snapshot['auto_creation_policy'] = {
|
||||
**schema_auto_creation_policy,
|
||||
'enabled': effective_auto_create_enabled,
|
||||
'schema_enabled': bool(schema_auto_creation_policy.get('enabled')),
|
||||
'runtime_binding_enabled': binding_auto_create_enabled,
|
||||
}
|
||||
snapshot['auto_freeze_policy'] = auto_freeze_policy
|
||||
snapshot_hash = _sha256(snapshot)
|
||||
idempotency_key = _sha256({
|
||||
'user_id': user.id,
|
||||
@@ -435,10 +444,9 @@ def create_order_extraction_run(
|
||||
'conversation_id': conversation_id,
|
||||
'intake_ids': [intake.id for intake in intakes],
|
||||
'input_snapshot_hash': snapshot_hash,
|
||||
'runtime_binding_id': binding.id,
|
||||
'provider_agent_id': binding.provider_agent_id,
|
||||
'provider_config': binding_config,
|
||||
'quality_batch_id': quality_batch_id,
|
||||
'parser_engine_version': 'deterministic-order-parser.v1',
|
||||
'parser_policy_version': 'deterministic-order-policy.v1',
|
||||
'auto_freeze_policy': auto_freeze_policy,
|
||||
'reparse_of_run_id': reparse_of_run.id if reparse_of_run is not None else None,
|
||||
})
|
||||
existing = _run_by_idempotency_key(idempotency_key)
|
||||
@@ -467,18 +475,9 @@ def create_order_extraction_run(
|
||||
run_no=_run_no(),
|
||||
user_id=user.id,
|
||||
owner_agent_id=owner_agent.id,
|
||||
runtime_binding_id=binding.id,
|
||||
provider_agent_id=binding.provider_agent_id,
|
||||
quality_batch_id=quality_batch_id,
|
||||
provider_config_json={**binding_config, 'auto_create_enabled': effective_auto_create_enabled},
|
||||
provider_snapshot_json={
|
||||
'provider_agent_id': binding.provider_agent_id,
|
||||
'runtime_provider': binding.provider_agent.runtime_provider,
|
||||
'dify_app_type': binding.provider_agent.dify_app_type,
|
||||
'exposure_mode': binding.provider_agent.exposure_mode,
|
||||
'dify_app_id': binding.provider_agent.dify_app_id,
|
||||
'api_base_url': binding.provider_agent.api_base_url,
|
||||
},
|
||||
parser_engine_version='deterministic-order-parser.v1',
|
||||
parser_policy_version='deterministic-order-policy.v1',
|
||||
auto_freeze_policy_json=auto_freeze_policy,
|
||||
reparse_of_run_id=reparse_of_run.id if reparse_of_run is not None else None,
|
||||
reparse_reason=str(reparse_reason or '').strip()[:64] or None,
|
||||
reparse_comment=str(reparse_comment or '').strip()[:2000] or None,
|
||||
@@ -511,7 +510,7 @@ def create_order_extraction_run(
|
||||
domain='shipping_notice',
|
||||
business_ref=run.run_no,
|
||||
created_by_id=user.id,
|
||||
max_attempts=int((binding.config_json or {}).get('max_attempts') or 3),
|
||||
max_attempts=3,
|
||||
message='订单抽取等待后台处理',
|
||||
commit=False,
|
||||
)
|
||||
@@ -660,7 +659,7 @@ def retry_order_extraction_run(*, user_id: int, run_no: str) -> tuple[ShippingOr
|
||||
current_job = db.session.get(Job, run.current_job_id) if run.current_job_id else None
|
||||
if (
|
||||
run.status in {'queued', 'running'}
|
||||
and run.phase in {'manual_retry_queued', 'calling_provider'}
|
||||
and run.phase in {'manual_retry_queued', 'deterministic_parsing'}
|
||||
and current_job is not None
|
||||
and current_job.status in {'queued', 'running'}
|
||||
):
|
||||
@@ -673,13 +672,6 @@ def retry_order_extraction_run(*, user_id: int, run_no: str) -> tuple[ShippingOr
|
||||
)
|
||||
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
config = run.provider_config_json if isinstance(run.provider_config_json, dict) else {}
|
||||
if config.get('retired_protocol') is True:
|
||||
raise ConflictError(
|
||||
'The failed run uses a retired order extraction protocol. Create a new extraction instead.',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_PROTOCOL_RETIRED',
|
||||
details={'run_no': run.run_no},
|
||||
)
|
||||
snapshot_intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
if not snapshot_intakes or any(
|
||||
not isinstance(item, dict) or not isinstance(item.get('deterministic_context'), dict)
|
||||
@@ -723,7 +715,7 @@ def retry_order_extraction_run(*, user_id: int, run_no: str) -> tuple[ShippingOr
|
||||
domain='shipping_notice',
|
||||
business_ref=run.run_no,
|
||||
created_by_id=user_id,
|
||||
max_attempts=int((run.provider_config_json or {}).get('max_attempts') or 3),
|
||||
max_attempts=3,
|
||||
message='订单抽取等待重新识别',
|
||||
dedupe_statuses=('queued',),
|
||||
commit=False,
|
||||
@@ -777,7 +769,7 @@ def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str,
|
||||
now = datetime.utcnow()
|
||||
activity_at = run.last_activity_at or run.started_at or run.created_at
|
||||
idle_seconds = max(0, int((now - activity_at).total_seconds())) if activity_at else 0
|
||||
slow_threshold_seconds = get_order_extraction_user_slow_threshold_seconds(provider_agent_id=run.provider_agent_id)
|
||||
slow_threshold_seconds = get_order_extraction_user_slow_threshold_seconds()
|
||||
health = 'slow' if run.status in {'queued', 'running', 'result_persisted'} and idle_seconds >= slow_threshold_seconds else (
|
||||
'idle' if run.status in {'queued', 'running', 'result_persisted'} and idle_seconds >= 60 else 'normal'
|
||||
)
|
||||
@@ -827,7 +819,7 @@ def serialize_order_extraction_message_state(run: ShippingOrderExtractionRun) ->
|
||||
completed = run.status == 'completed'
|
||||
return {
|
||||
'status': 'failed' if failed else 'partially_completed' if partial else 'completed' if completed else 'extracting',
|
||||
'phase': 'failed' if failed else 'result_persisted' if run.status == 'result_persisted' else 'llm_extraction',
|
||||
'phase': 'failed' if failed else 'result_persisted' if run.status == 'result_persisted' else 'deterministic_parsing',
|
||||
# The chat log is user-visible on history replay. It must follow the same redaction
|
||||
# boundary as the workspace Run API and never persist upstream error text.
|
||||
'message': '',
|
||||
@@ -865,15 +857,13 @@ def _sync_order_extraction_chat_log(run: ShippingOrderExtractionRun) -> None:
|
||||
break
|
||||
|
||||
|
||||
def get_order_extraction_user_slow_threshold_seconds(*, provider_agent_id: int | None = None, min_samples: int = 20) -> int:
|
||||
"""按同Provider近30天终态总耗时P95计算慢响应阈值;样本不足回退180秒且不超过300秒。"""
|
||||
def get_order_extraction_user_slow_threshold_seconds(*, min_samples: int = 20) -> int:
|
||||
"""按近30天确定性订单抽取终态总耗时P95计算慢响应阈值;样本不足回退180秒且不超过300秒。"""
|
||||
query = ShippingOrderExtractionRun.query.filter(
|
||||
ShippingOrderExtractionRun.finished_at.isnot(None),
|
||||
ShippingOrderExtractionRun.created_at.isnot(None),
|
||||
ShippingOrderExtractionRun.finished_at >= datetime.utcnow() - timedelta(days=30),
|
||||
)
|
||||
if provider_agent_id is not None:
|
||||
query = query.filter(ShippingOrderExtractionRun.provider_agent_id == provider_agent_id)
|
||||
rows = query.order_by(ShippingOrderExtractionRun.finished_at.desc()).limit(200).all()
|
||||
seconds = [max(0, int((row.finished_at - row.created_at).total_seconds())) for row in rows if row.finished_at and row.created_at]
|
||||
if len(seconds) < min_samples:
|
||||
@@ -985,21 +975,22 @@ def _serialize_order_extraction_diagnostic_run(run: ShippingOrderExtractionRun)
|
||||
'status': run.status,
|
||||
'phase': run.phase,
|
||||
'conversation_id': run.conversation_id,
|
||||
'workflow_run_id': run.dify_workflow_run_id,
|
||||
'parser_engine_version': run.parser_engine_version,
|
||||
'parser_policy_version': run.parser_policy_version,
|
||||
'attempt_count': int(run.attempt_count or 0),
|
||||
'current_stage_code': run.current_stage_code,
|
||||
'active_stage_codes': list(run.active_stage_codes_json or []),
|
||||
'completed_stage_codes': list(run.completed_stage_codes_json or []),
|
||||
'created_at': _diagnostic_iso(run.created_at),
|
||||
'started_at': _diagnostic_iso(run.started_at),
|
||||
'provider_completed_at': _diagnostic_iso(run.provider_completed_at),
|
||||
'extraction_completed_at': _diagnostic_iso(run.extraction_completed_at),
|
||||
'result_persisted_at': _diagnostic_iso(run.result_persisted_at),
|
||||
'finished_at': _diagnostic_iso(run.finished_at),
|
||||
'last_activity_at': _diagnostic_iso(run.last_activity_at),
|
||||
'durations_ms': {
|
||||
'queue': _diagnostic_elapsed_ms(run.created_at, run.started_at),
|
||||
'provider': _diagnostic_elapsed_ms(run.started_at, run.provider_completed_at),
|
||||
'hxops_persistence': _diagnostic_elapsed_ms(run.provider_completed_at, run.result_persisted_at),
|
||||
'deterministic_parsing': _diagnostic_elapsed_ms(run.started_at, run.extraction_completed_at),
|
||||
'hxops_persistence': _diagnostic_elapsed_ms(run.extraction_completed_at, run.result_persisted_at),
|
||||
'total': _diagnostic_elapsed_ms(run.created_at, run.finished_at),
|
||||
},
|
||||
'result_counts': {
|
||||
@@ -1066,7 +1057,10 @@ def list_order_extraction_diagnostic_runs(
|
||||
|
||||
def get_order_extraction_diagnostic_run(*, admin_user_id: int, request_id: str | None, run_no: str) -> dict[str, Any]:
|
||||
"""读取 Run 的脱敏诊断、单元状态和证据门禁原因;不返回值、引文或版面内部 ID。"""
|
||||
from app.models import Job, ShippingOrderExtraction, ShippingOrderExtractionProgressEvent, ShippingOrderExtractionUnit
|
||||
from app.models import (
|
||||
Job, ShippingOrderExtraction, ShippingOrderExtractionProgressEvent,
|
||||
ShippingOrderExtractionRouteDecision, ShippingOrderExtractionUnit,
|
||||
)
|
||||
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=run_no).first()
|
||||
if run is None:
|
||||
@@ -1084,6 +1078,34 @@ def get_order_extraction_diagnostic_run(*, admin_user_id: int, request_id: str |
|
||||
.order_by(ShippingOrderExtractionUnit.position.asc()).all()
|
||||
if run.extraction_plan else []
|
||||
)
|
||||
route_decisions = ShippingOrderExtractionRouteDecision.query.filter_by(run_id=run.id).order_by(
|
||||
ShippingOrderExtractionRouteDecision.unit_id.asc(), ShippingOrderExtractionRouteDecision.id.asc(),
|
||||
).all()
|
||||
decisions_by_unit: dict[int, list[dict[str, Any]]] = {}
|
||||
for route in route_decisions:
|
||||
decisions_by_unit.setdefault(int(route.unit_id), []).append({
|
||||
'attempt_no': int(route.attempt_no),
|
||||
'execution_mode': route.decision,
|
||||
'match_status': route.match_status,
|
||||
'selected_profile_code': route.selected_profile_code,
|
||||
'selected_profile_version': route.selected_profile_version,
|
||||
'selected_profile_checksum': route.selected_profile_checksum,
|
||||
'auto_create_approved': route.auto_create_approved,
|
||||
'candidate_count': int(route.candidate_count or 0),
|
||||
'table_count': int(route.table_count or 0),
|
||||
'approved_table_count': int(route.approved_table_count or 0),
|
||||
# Defend the read boundary too: even a legacy/corrupt JSON row cannot disclose values or layout data.
|
||||
'candidates': [{
|
||||
'profile_code': str(item.get('profile_code') or ''),
|
||||
'version': int(item.get('version') or 0),
|
||||
'score': float(item.get('score') or 0),
|
||||
'hard_match': bool(item.get('hard_match')),
|
||||
'reason_codes': [str(code) for code in item.get('reason_codes') or []],
|
||||
'missing_required_anchor_ids': [str(anchor_id) for anchor_id in item.get('missing_required_anchor_ids') or []],
|
||||
} for item in route.candidate_summary_json if isinstance(item, dict)] if isinstance(route.candidate_summary_json, list) else [],
|
||||
'fallback_reason_codes': route.fallback_reason_codes_json if isinstance(route.fallback_reason_codes_json, list) else [],
|
||||
'created_at': _diagnostic_iso(route.created_at),
|
||||
})
|
||||
extractions = ShippingOrderExtraction.query.filter_by(run_id=run.id).order_by(
|
||||
ShippingOrderExtraction.id.asc(),
|
||||
).all()
|
||||
@@ -1135,6 +1157,7 @@ def get_order_extraction_diagnostic_run(*, admin_user_id: int, request_id: str |
|
||||
'attempt_count': int(unit.attempt_count or 0),
|
||||
'duration_ms': _diagnostic_elapsed_ms(unit.started_at, unit.finished_at),
|
||||
'error_code': unit.error_code,
|
||||
'route_decisions': decisions_by_unit.get(int(unit.id), []),
|
||||
} for unit in units],
|
||||
'evidence_gate': {
|
||||
'accepted_observation_count': accepted_observation_count,
|
||||
@@ -1184,10 +1207,28 @@ def transition_order_extraction_run(
|
||||
f'Invalid order extraction run transition: {current_status} -> {target_status}',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_TRANSITION_INVALID',
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
before_projection = {
|
||||
'status': current_status,
|
||||
'phase': run.phase,
|
||||
'lock_version': int(run.lock_version or 0),
|
||||
}
|
||||
now = datetime.utcnow()
|
||||
run.status = target_status
|
||||
run.phase = phase or target_status
|
||||
run.lock_version = int(run.lock_version or 0) + 1
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_run_status_changed',
|
||||
aggregate_type='order_extraction_run',
|
||||
aggregate_id=run.run_no,
|
||||
run_no=run.run_no,
|
||||
actor_type='system',
|
||||
reason_code=error_code if target_status == 'failed' else None,
|
||||
before=before_projection,
|
||||
after={'status': target_status, 'phase': phase or target_status, 'lock_version': int(run.lock_version or 0)},
|
||||
metadata={'target_status': target_status},
|
||||
)
|
||||
if target_status == 'running' and run.started_at is None:
|
||||
run.started_at = now
|
||||
intake_ids = [member.intake_id for member in run.intakes]
|
||||
@@ -1278,7 +1319,7 @@ def mark_order_extraction_persistence_started(run: ShippingOrderExtractionRun) -
|
||||
return
|
||||
run.active_stage_codes_json = ['hxops_persistence']
|
||||
completed = {str(item) for item in (run.completed_stage_codes_json or []) if str(item)}
|
||||
completed.add('provider_result_ready')
|
||||
completed.add('deterministic_result_ready')
|
||||
run.completed_stage_codes_json = sorted(completed)
|
||||
run.current_stage_code = 'hxops_persistence'
|
||||
run.progress_message_code = 'shipping.order_extraction.hxops_persistence'
|
||||
@@ -1378,10 +1419,10 @@ def get_order_extraction_run_health(
|
||||
return int((end - start).total_seconds() * 1000)
|
||||
|
||||
queue_ms = [value for row in rows if (value := elapsed_ms(row.created_at, row.started_at)) is not None]
|
||||
provider_ms = [value for row in rows if (value := elapsed_ms(row.started_at, row.provider_completed_at)) is not None]
|
||||
parsing_ms = [value for row in rows if (value := elapsed_ms(row.started_at, row.extraction_completed_at)) is not None]
|
||||
persistence_ms = [
|
||||
value for row in rows
|
||||
if (value := elapsed_ms(row.provider_completed_at, row.result_persisted_at)) is not None
|
||||
if (value := elapsed_ms(row.extraction_completed_at, row.result_persisted_at)) is not None
|
||||
]
|
||||
total_ms = [value for row in terminal_rows if (value := elapsed_ms(row.created_at, row.finished_at)) is not None]
|
||||
terminal_count = len(terminal_rows)
|
||||
@@ -1412,7 +1453,7 @@ def get_order_extraction_run_health(
|
||||
'failure_rate': failure_rate,
|
||||
'latency': {
|
||||
'queue': _latency_summary(queue_ms),
|
||||
'provider': _latency_summary(provider_ms),
|
||||
'deterministic_parsing': _latency_summary(parsing_ms),
|
||||
'hxops_persistence': _latency_summary(persistence_ms),
|
||||
'total': _latency_summary(total_ms),
|
||||
},
|
||||
|
||||
@@ -1,21 +1,18 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_extraction_workflow.py
|
||||
|
||||
用途:把订单抽取 Run 冻结快照编译为 Dify Workflow inputs,并校验结构化 outputs。
|
||||
依赖:DifyService、MinerU 紧凑快照、context_fields.dify_exposure、统一错误类型。
|
||||
逻辑:PDF 优先使用 MinerU 分页文本和表格网格,Provider 只接收剥离布局内部载荷后的文档及受控上下文。
|
||||
用途:提供冻结订单抽取快照的确定性模板路由及旧 Workflow 输入兼容函数。
|
||||
依赖:MinerU 紧凑快照、订单 Profile、Schema 校验、统一错误类型。
|
||||
逻辑:Worker 先调用本模块裁决确定性解析或人工复核;旧 Workflow 函数将在阶段 1 移除,不参与新订单主链。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal
|
||||
|
||||
import requests
|
||||
|
||||
from app.core.errors import ServiceUnavailableError, ValidationError
|
||||
from app.services.dify import DifyService
|
||||
from app.services.shipping_notice.context_fields.dify_exposure import compile_readonly_context
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.document_layout.html_table import parse_html_grid
|
||||
from app.services.shipping_notice.document_layout.order_profile import (
|
||||
OrderDocumentProfile,
|
||||
@@ -31,6 +28,19 @@ from app.services.shipping_notice.document_layout.order_profile_matcher import m
|
||||
from app.services.shipping_notice.order_schema.field_rules import normalize_order_field_value, validate_order_field_value
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeterministicRouteResult:
|
||||
"""一次 Unit 路由的脱敏事实;Worker 必须先持久化 decision 再执行该路径。
|
||||
|
||||
AI 触发时机:无需调用。此对象仅在 HXOPS Worker 判断已批准模板能否确定性解析
|
||||
时创建,禁止包含文档正文、字段值、坐标、Prompt 或 Provider 凭据。
|
||||
"""
|
||||
|
||||
execution_mode: Literal['deterministic', 'review_required', 'skipped']
|
||||
orders: list[dict[str, Any]]
|
||||
decision: dict[str, Any]
|
||||
|
||||
|
||||
def _unit_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]]:
|
||||
"""从 Run 冻结快照定位一个单元的 Intake 与 Document,禁止回读可变正文。"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
@@ -46,9 +56,9 @@ def _unit_snapshot(run: Any, unit: Any) -> tuple[dict[str, Any], dict[str, Any]]
|
||||
)
|
||||
|
||||
|
||||
def build_order_extraction_workflow_inputs(run: Any, *, unit: Any) -> dict[str, str]:
|
||||
def build_order_extraction_execution_snapshot(run: Any, *, unit: Any) -> dict[str, str]:
|
||||
"""
|
||||
从 Run 不可变快照构建唯一的 Dify 执行清单。
|
||||
从 Run 不可变快照构建确定性解析调试清单。
|
||||
|
||||
核心逻辑:将 Run 标识、完整性哈希、LLM 抽取契约、冻结文档和受控只读提示
|
||||
收敛为唯一 Start 输入,防止 Workflow 变量随契约演进而漂移。
|
||||
@@ -57,9 +67,9 @@ def build_order_extraction_workflow_inputs(run: Any, *, unit: Any) -> dict[str,
|
||||
run: 已冻结输入快照的 ShippingOrderExtractionRun。
|
||||
|
||||
Returns:
|
||||
dict[str, str]: 仅含 execution_manifest JSON 字符串的 Dify inputs。
|
||||
dict[str, str]: 仅含脱敏 execution_manifest JSON 字符串。
|
||||
"""
|
||||
return _build_unique_workflow_inputs(run, unit=unit)
|
||||
return _build_execution_snapshot(run, unit=unit)
|
||||
|
||||
|
||||
def _compact_layout_schema_candidates(document: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
@@ -107,9 +117,9 @@ def _compact_layout_schema_candidates(document: dict[str, Any]) -> list[dict[str
|
||||
return result
|
||||
|
||||
|
||||
def frozen_document_text_for_dify(document: dict[str, Any]) -> str:
|
||||
def frozen_document_text_for_parser(document: dict[str, Any]) -> str:
|
||||
"""
|
||||
将冻结 MinerU 文本块和 HTML 表格转换为 LLM 可读的分页纯文本。
|
||||
将冻结 MinerU 文本块和 HTML 表格转换为确定性校验可读的分页纯文本。
|
||||
|
||||
核心逻辑:按页和页面坐标恢复阅读顺序;表格展开为 TSV 以保留行列关系。
|
||||
HTML、bbox、cell_id 和 Provider 原始响应不得出现在返回文本中。
|
||||
@@ -168,9 +178,9 @@ def frozen_document_text_for_dify(document: dict[str, Any]) -> str:
|
||||
return '\n'.join(pages).strip()
|
||||
|
||||
|
||||
def _build_unique_workflow_inputs(run: Any, *, unit: Any) -> dict[str, str]:
|
||||
def _build_execution_snapshot(run: Any, *, unit: Any) -> dict[str, str]:
|
||||
"""
|
||||
构建唯一清单,给 LLM 发送紧凑表格候选而非版面原始数据。
|
||||
构建唯一清单,供确定性解析诊断使用,不包含版面原始数据。
|
||||
|
||||
核心逻辑:PDF 优先使用 MinerU 分页文本与 TSV 表格,失败时保留旧文本;Document
|
||||
删除所有布局载荷,字段候选独立放入 structured_table_candidates。
|
||||
@@ -180,23 +190,23 @@ def _build_unique_workflow_inputs(run: Any, *, unit: Any) -> dict[str, str]:
|
||||
unit: 当前抽取计划单元。
|
||||
|
||||
Returns:
|
||||
dict[str, str]: 仅含 execution_manifest 的 Dify Start 输入。
|
||||
dict[str, str]: 仅含 execution_manifest 的脱敏快照。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
schema = schema_snapshot.get('extraction_contract') if isinstance(schema_snapshot.get('extraction_contract'), dict) else {}
|
||||
intake, document = _unit_snapshot(run, unit)
|
||||
readonly_snapshot = {**snapshot, 'intakes': [intake]}
|
||||
document_for_dify = dict(document)
|
||||
candidates = _compact_layout_schema_candidates(document_for_dify)
|
||||
mineru_text = frozen_document_text_for_dify(document_for_dify)
|
||||
document_for_parser = dict(document)
|
||||
candidates = _compact_layout_schema_candidates(document_for_parser)
|
||||
mineru_text = frozen_document_text_for_parser(document_for_parser)
|
||||
if mineru_text:
|
||||
document_for_dify['extracted_text'] = mineru_text
|
||||
document_for_dify['text_source'] = 'mineru'
|
||||
document_for_parser['extracted_text'] = mineru_text
|
||||
document_for_parser['text_source'] = 'mineru'
|
||||
else:
|
||||
document_for_dify['text_source'] = 'legacy'
|
||||
document_for_parser['text_source'] = 'legacy'
|
||||
for key in ('layout_snapshot', 'layout_schema_candidates', 'layout_candidate', 'deterministic_table_candidates'):
|
||||
document_for_dify.pop(key, None)
|
||||
document_for_parser.pop(key, None)
|
||||
manifest = {
|
||||
'run': {'run_no': str(run.run_no)},
|
||||
'unit': {
|
||||
@@ -206,9 +216,9 @@ def _build_unique_workflow_inputs(run: Any, *, unit: Any) -> dict[str, str]:
|
||||
},
|
||||
'integrity': {'input_snapshot_hash': str(run.input_snapshot_hash)},
|
||||
'extraction_contract': schema,
|
||||
'document': document_for_dify,
|
||||
'document': document_for_parser,
|
||||
'structured_table_candidates': candidates,
|
||||
'readonly_hints': compile_readonly_context(readonly_snapshot),
|
||||
'readonly_hints': readonly_snapshot.get('deterministic_context', {}),
|
||||
}
|
||||
return {'execution_manifest': json.dumps(manifest, ensure_ascii=False, separators=(',', ':'))}
|
||||
|
||||
@@ -290,7 +300,7 @@ def _reconstructed_profile_html(*, layout: dict[str, Any], raw_table: dict[str,
|
||||
return None
|
||||
|
||||
|
||||
def _dify_profile_candidates(tables: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
def _profile_candidate_summary(tables: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""剥离内部 field_code,只向 Dify 暴露稳定 field_id、值和短逐字证据。"""
|
||||
result: list[dict[str, Any]] = []
|
||||
for table in tables:
|
||||
@@ -584,6 +594,7 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
raw_profile, parsed = matches[0]
|
||||
if isinstance(parsed, list):
|
||||
result_tables.append({
|
||||
'profile_id': raw_profile.get('profile_id') or raw_profile.get('id'),
|
||||
'profile_code': str(raw_profile.get('profile_code') or ''), 'profile_version': int(raw_profile.get('version') or 0),
|
||||
'profile_checksum': str(raw_profile.get('checksum') or ''), 'table_id': table_id, 'page_no': int(raw_table.get('page_no') or 1),
|
||||
'auto_create_approved': bool(raw_profile.get('auto_create_approved')), 'rows': parsed,
|
||||
@@ -625,6 +636,7 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
'issues': row.issues,
|
||||
})
|
||||
result_tables.append({
|
||||
'profile_id': raw_profile.get('profile_id') or raw_profile.get('id'),
|
||||
'profile_code': str(raw_profile.get('profile_code') or ''),
|
||||
'profile_version': int(raw_profile.get('version') or 0),
|
||||
'profile_checksum': str(raw_profile.get('checksum') or ''),
|
||||
@@ -641,7 +653,7 @@ def _profile_table_candidates(run: Any, *, unit: Any) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
def parse_order_extraction_workflow_result(result: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
def parse_order_extraction_execution_result(result: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
校验 Dify Workflow 终态与 orders 输出,并兼容 End 节点的有限 JSON 字符串包装。
|
||||
|
||||
@@ -714,7 +726,7 @@ def validate_unit_orders(
|
||||
str(item.get('field_id') or '')
|
||||
for item in contract.get('fields') or [] if isinstance(item, dict) and item.get('field_id')
|
||||
}
|
||||
evidence_text = frozen_document_text_for_dify(document) or str(document.get('extracted_text') or '')
|
||||
evidence_text = frozen_document_text_for_parser(document) or str(document.get('extracted_text') or '')
|
||||
for order in orders:
|
||||
if strict_provider_evidence and any(str(key).startswith('_hxops_') for key in order):
|
||||
raise ValidationError(
|
||||
@@ -877,8 +889,12 @@ def _merge_confirmed_profile_order_fields(run: Any, *, unit: Any, orders: list[d
|
||||
return orders
|
||||
|
||||
|
||||
def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None:
|
||||
"""仅由盲测批准的唯一 Profile 实测行生成零 Provider 订单;其余交给模型补充。"""
|
||||
def route_deterministic_unit(run: Any, *, unit: Any) -> DeterministicRouteResult:
|
||||
"""计算单元的模板路由并返回仅含脱敏诊断的结构化结果。
|
||||
|
||||
AI 触发时机:无需调用。Worker 在每个 Unit 执行前调用;只有唯一、已批准、
|
||||
完整且符合冻结 Schema 的模板解析可走 deterministic,其余均明确进入人工复核。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
schema_snapshot = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
schema = (
|
||||
@@ -889,26 +905,85 @@ def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, An
|
||||
definition = schema_snapshot.get('definition') if isinstance(schema_snapshot.get('definition'), dict) else {}
|
||||
intake, _document = _unit_snapshot(run, unit)
|
||||
profile_result = _profile_table_candidates(run, unit=unit)
|
||||
match = profile_result.get('match') if isinstance(profile_result.get('match'), dict) else {}
|
||||
tables = profile_result.get('tables') if isinstance(profile_result.get('tables'), list) else []
|
||||
candidates = match.get('candidates') if isinstance(match.get('candidates'), list) else []
|
||||
decision: dict[str, Any] = {
|
||||
'match_status': match.get('status') if match else ('unique_match' if profile_result.get('matched') else 'no_match'),
|
||||
'selected_profile_code': match.get('profile_code'),
|
||||
'selected_profile_version': match.get('version'),
|
||||
'selected_profile_checksum': match.get('checksum'),
|
||||
'selected_profile_id': None,
|
||||
'candidate_count': len(candidates),
|
||||
'table_count': len(tables),
|
||||
'document_table_count': len(tables),
|
||||
'business_table_count': 0,
|
||||
'matched_table_count': 0,
|
||||
'parsed_table_count': 0,
|
||||
'approved_table_count': sum(1 for item in tables if isinstance(item, dict) and item.get('auto_create_approved')),
|
||||
'candidate_summary': candidates,
|
||||
'fallback_reason_codes': [],
|
||||
}
|
||||
if profile_result.get('blocking'):
|
||||
return None
|
||||
issues = profile_result.get('issues') if isinstance(profile_result.get('issues'), list) else []
|
||||
decision['fallback_reason_codes'] = [_route_reason_for_issue(str(issue)) for issue in issues]
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
approved_tables = [
|
||||
item for item in profile_result.get('tables') or []
|
||||
item for item in tables
|
||||
if bool(item.get('auto_create_approved'))
|
||||
]
|
||||
# 文档出现多个模板表时不猜测其业务关系,即使其中一个模板已批准也回退 Dify/人工。
|
||||
if len(profile_result.get('tables') or []) != 1 or len(approved_tables) != 1:
|
||||
return None
|
||||
# 文档出现多个模板表时不猜测其业务关系,即使其中一个模板已批准也必须人工复核。
|
||||
if not tables:
|
||||
decision['fallback_reason_codes'] = ['no_layout_table']
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
if len(tables) != 1:
|
||||
decision['fallback_reason_codes'] = ['multiple_tables_detected']
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
if len(approved_tables) != 1:
|
||||
decision['fallback_reason_codes'] = ['profile_not_auto_create_approved']
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
selected = approved_tables[0]
|
||||
decision.update({
|
||||
'selected_profile_code': selected.get('profile_code'),
|
||||
'selected_profile_id': selected.get('profile_id'),
|
||||
'selected_profile_version': selected.get('profile_version'),
|
||||
'selected_profile_checksum': selected.get('profile_checksum'),
|
||||
'auto_create_approved': True,
|
||||
'business_table_count': 1,
|
||||
'matched_table_count': 1,
|
||||
})
|
||||
confirmed_order_fields = _confirmed_profile_order_fields(run, unit=unit)
|
||||
order = _build_approved_profile_order(
|
||||
orders, reason_code = _build_approved_profile_order_result(
|
||||
unit=unit, intake=intake, schema=schema, definition=definition, table=approved_tables[0],
|
||||
confirmed_order_fields=confirmed_order_fields,
|
||||
)
|
||||
if order is None:
|
||||
return None
|
||||
if confirmed_order_fields:
|
||||
# `_build_approved_profile_order` has already merged and validated these fields.
|
||||
pass
|
||||
return [order]
|
||||
if orders is None:
|
||||
decision['fallback_reason_codes'] = [reason_code or 'no_parsed_lines']
|
||||
return DeterministicRouteResult(execution_mode='review_required', orders=[], decision=decision)
|
||||
decision['parsed_table_count'] = 1
|
||||
decision['business_table_count'] = 1
|
||||
decision['matched_table_count'] = 1
|
||||
decision['document_table_count'] = len(tables)
|
||||
return DeterministicRouteResult(execution_mode='deterministic', orders=orders, decision=decision)
|
||||
|
||||
|
||||
def build_deterministic_unit_orders(run: Any, *, unit: Any) -> list[dict[str, Any]] | None:
|
||||
"""兼容旧调用方:仅在结构化路由允许确定性解析时返回订单数组。"""
|
||||
result = route_deterministic_unit(run, unit=unit)
|
||||
return result.orders if result.execution_mode == 'deterministic' else None
|
||||
|
||||
|
||||
def _route_reason_for_issue(issue: str) -> str:
|
||||
"""把内部解析问题收敛为管理员可长期依赖的稳定路由原因码。"""
|
||||
mapping = {
|
||||
'order_profile_evidence_insufficient': 'profile_evidence_insufficient',
|
||||
'order_profile_no_match': 'profile_no_match',
|
||||
'order_profile_ambiguous': 'profile_ambiguous',
|
||||
'order_profile_layout_drift': 'profile_layout_drift',
|
||||
'order_profile_snapshot_field_mismatch': 'profile_schema_field_mismatch',
|
||||
'order_profile_multiple_matches': 'profile_ambiguous',
|
||||
}
|
||||
return mapping.get(issue, 'profile_layout_drift')
|
||||
|
||||
|
||||
def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2:
|
||||
@@ -921,10 +996,10 @@ def _frozen_coordinate_profile(raw: dict[str, Any]) -> OrderCoordinateProfileV2:
|
||||
)
|
||||
|
||||
|
||||
def _build_approved_profile_order(
|
||||
def _build_approved_profile_order_result(
|
||||
*, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any],
|
||||
table: dict[str, Any], confirmed_order_fields: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
) -> tuple[list[dict[str, Any]] | None, str | None]:
|
||||
"""
|
||||
把已批准 Profile 本次实际解析的唯一完整表格转换为零 Provider 订单。
|
||||
|
||||
@@ -937,7 +1012,7 @@ def _build_approved_profile_order(
|
||||
confirmed_order_fields: 同一冻结模板产生的 confirmed 订单字段,作为独立 Header 证据合并。
|
||||
|
||||
Returns:
|
||||
完整确定性订单;候选非唯一、含问题或缺必填字段时返回 None。
|
||||
``(订单, 原因码)``;失败时订单为 None,原因码只表达路由事实。
|
||||
"""
|
||||
fields = [
|
||||
item for item in definition.get('fields') or []
|
||||
@@ -945,6 +1020,10 @@ def _build_approved_profile_order(
|
||||
and item.get('collection_mode', 'llm_extraction') == 'llm_extraction'
|
||||
]
|
||||
by_id = {str(item.get('field_id') or ''): item for item in fields}
|
||||
po_field_ids = {
|
||||
str(item.get('field_id') or '') for item in fields
|
||||
if str(item.get('field_code') or '') in {'customer_po_number', 'po_number'}
|
||||
}
|
||||
line_groups: list[dict[str, Any]] = []
|
||||
header_values: dict[str, list[dict[str, Any]]] = {}
|
||||
for row in table.get('rows') or []:
|
||||
@@ -952,7 +1031,7 @@ def _build_approved_profile_order(
|
||||
if not isinstance(row, dict) or row.get('status') == 'deleted':
|
||||
continue
|
||||
if row.get('status') != 'parsed' or row.get('issues'):
|
||||
return None
|
||||
return None, 'row_needs_review'
|
||||
line_fields: list[dict[str, Any]] = []
|
||||
for raw in row.get('fields') or []:
|
||||
if not isinstance(raw, dict):
|
||||
@@ -965,7 +1044,9 @@ def _build_approved_profile_order(
|
||||
'value': raw.get('value'), 'document_id': int(unit.document_id),
|
||||
'quote': str(raw.get('quote') or raw.get('value') or '')[:1000], 'confidence': 1.0,
|
||||
}
|
||||
if config.get('scope') == 'header':
|
||||
# PO can be configured as a Header field yet appear once per table row. Keep it
|
||||
# with the row until PO partitioning proves the association is unambiguous.
|
||||
if config.get('scope') == 'header' and field_id not in po_field_ids:
|
||||
header_values.setdefault(field_id, []).append(observation)
|
||||
else:
|
||||
line_fields.append({'field_id': field_id, 'observations': [observation]})
|
||||
@@ -975,7 +1056,10 @@ def _build_approved_profile_order(
|
||||
for field_id, observations in header_values.items():
|
||||
unique = {json.dumps(item['value'], ensure_ascii=False, sort_keys=True) for item in observations}
|
||||
if len(unique) != 1:
|
||||
return None
|
||||
# Multiple document-level PO values cannot be attributed to individual lines.
|
||||
if field_id in po_field_ids:
|
||||
return None, 'multiple_business_tables_ambiguous'
|
||||
return None, 'header_value_conflict'
|
||||
header_fields.append({'field_id': field_id, 'observations': [observations[0]]})
|
||||
present_header = {item['field_id'] for item in header_fields}
|
||||
for candidate in confirmed_order_fields or []:
|
||||
@@ -984,7 +1068,7 @@ def _build_approved_profile_order(
|
||||
continue
|
||||
if field_id in present_header:
|
||||
# Header table evidence and independent order-field evidence must never silently compete.
|
||||
return None
|
||||
return None, 'header_value_conflict'
|
||||
header_fields.append({'field_id': field_id, '_hxops_order_field_evidence': True, 'observations': [{
|
||||
'value': candidate.get('value'), 'document_id': int(unit.document_id),
|
||||
'quote': str(candidate.get('value') or '')[:1000], 'confidence': 1.0,
|
||||
@@ -998,18 +1082,18 @@ def _build_approved_profile_order(
|
||||
}]})
|
||||
present_header.add(field_id)
|
||||
if not line_groups:
|
||||
return None
|
||||
return None, 'no_parsed_lines'
|
||||
for config in fields:
|
||||
if not config.get('required'):
|
||||
continue
|
||||
field_id = str(config.get('field_id') or '')
|
||||
if config.get('scope') == 'header' and field_id not in present_header:
|
||||
return None
|
||||
if config.get('scope') == 'header' and field_id not in present_header and field_id not in po_field_ids:
|
||||
return None, 'required_header_missing'
|
||||
if config.get('scope') == 'line' and any(
|
||||
field_id not in {item['field_id'] for item in group['fields']} for group in line_groups
|
||||
):
|
||||
return None
|
||||
return {
|
||||
return None, 'required_line_field_missing'
|
||||
base_order = {
|
||||
'schema_version_id': schema.get('schema_version_id'), 'schema_checksum': schema.get('checksum'),
|
||||
'classification': 'shipping_request', 'classification_confidence': 1.0,
|
||||
'source_intake_no': str(intake.get('intake_no') or ''),
|
||||
@@ -1018,6 +1102,62 @@ def _build_approved_profile_order(
|
||||
# Only this frozen approved-profile builder may add this internal marker.
|
||||
'_hxops_acceptance': 'approved_deterministic_profile_v1',
|
||||
}
|
||||
# A PDF can yield multiple Tasks only when every parsed line carries one explicit PO.
|
||||
line_pos = []
|
||||
for group in line_groups:
|
||||
matches = [field for field in group['fields'] if field.get('field_id') in po_field_ids]
|
||||
values = {
|
||||
json.dumps(observation.get('value'), ensure_ascii=False, sort_keys=True)
|
||||
for field in matches for observation in field.get('observations') or [] if isinstance(observation, dict)
|
||||
}
|
||||
if len(values) != 1:
|
||||
line_pos = []
|
||||
break
|
||||
line_pos.append((next(iter(values)), group, matches[0]))
|
||||
distinct_pos = {item[0] for item in line_pos}
|
||||
if len(distinct_pos) <= 1:
|
||||
if line_pos:
|
||||
_value, _group, po_field = line_pos[0]
|
||||
base_order['header_fields'].append({
|
||||
'field_id': str(po_field.get('field_id') or ''),
|
||||
'observations': [po_field.get('observations', [None])[0]],
|
||||
})
|
||||
return [base_order], None
|
||||
if len(line_pos) != len(line_groups):
|
||||
return None, 'multiple_business_tables_ambiguous'
|
||||
orders: list[dict[str, Any]] = []
|
||||
for value in sorted(distinct_pos):
|
||||
po_lines = []
|
||||
po_field_id = None
|
||||
po_observation = None
|
||||
for line_value, group, po_field in line_pos:
|
||||
if line_value != value:
|
||||
continue
|
||||
cloned = json.loads(json.dumps(group))
|
||||
cloned['fields'] = [field for field in cloned['fields'] if field.get('field_id') not in po_field_ids]
|
||||
po_lines.append(cloned)
|
||||
po_field_id = str(po_field.get('field_id') or '')
|
||||
po_observation = po_field.get('observations', [None])[0]
|
||||
if not po_field_id or not isinstance(po_observation, dict):
|
||||
return None, 'required_header_missing'
|
||||
order = json.loads(json.dumps(base_order))
|
||||
order['lines'] = po_lines
|
||||
order['header_fields'] = [field for field in order['header_fields'] if field.get('field_id') not in po_field_ids]
|
||||
order['header_fields'].append({'field_id': po_field_id, 'observations': [po_observation]})
|
||||
orders.append(order)
|
||||
return orders, None
|
||||
|
||||
|
||||
def _build_approved_profile_order(
|
||||
*, unit: Any, intake: dict[str, Any], schema: dict[str, Any], definition: dict[str, Any],
|
||||
table: dict[str, Any], confirmed_order_fields: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any] | None:
|
||||
"""兼容既有内部测试与调用方,仅返回确定性订单而不暴露诊断元组。"""
|
||||
orders, _reason_code = _build_approved_profile_order_result(
|
||||
unit=unit, intake=intake, schema=schema, definition=definition, table=table,
|
||||
confirmed_order_fields=confirmed_order_fields,
|
||||
)
|
||||
return orders[0] if orders and len(orders) == 1 else None
|
||||
|
||||
|
||||
def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, Any]]:
|
||||
@@ -1054,35 +1194,3 @@ def _confirmed_profile_order_fields(run: Any, *, unit: Any) -> list[dict[str, An
|
||||
coordinate_evidence=layout.get('coordinate_evidence') or {},
|
||||
)
|
||||
return [item.model_dump(mode='json') for item in candidates if item.status == 'confirmed']
|
||||
|
||||
|
||||
def execute_order_extraction_workflow(*, run: Any, unit: Any, provider: Any, timeout_seconds: int, event_observer=None) -> tuple[list[dict[str, Any]], dict[str, Any]]:
|
||||
"""调用绑定 Provider 的 Workflow,并把网络异常归类为可重试业务错误。"""
|
||||
try:
|
||||
result = DifyService.run_workflow_streaming(
|
||||
agent=provider,
|
||||
inputs=build_order_extraction_workflow_inputs(run, unit=unit),
|
||||
user=f'shipping-order-extraction:{run.user_id}',
|
||||
timeout=(5, timeout_seconds),
|
||||
event_observer=event_observer,
|
||||
)
|
||||
except (requests.exceptions.ConnectTimeout, requests.exceptions.ReadTimeout) as exc:
|
||||
raise ServiceUnavailableError(
|
||||
'Dify order extraction workflow timed out',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
) from exc
|
||||
except requests.exceptions.RequestException as exc:
|
||||
raise ServiceUnavailableError(
|
||||
'Dify order extraction workflow request failed',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED',
|
||||
) from exc
|
||||
orders = validate_unit_orders(
|
||||
run, unit=unit, orders=parse_order_extraction_workflow_result(result), strict_provider_evidence=True,
|
||||
)
|
||||
metadata = {
|
||||
'workflow_run_id': result.get('workflow_run_id'),
|
||||
'poll_used': bool(result.get('_workflow_poll_used')),
|
||||
'retry_count': int(result.get('_workflow_retry_count') or 0),
|
||||
'provider_status': result.get('status'),
|
||||
}
|
||||
return orders, metadata
|
||||
@@ -25,6 +25,7 @@ from app.models import (
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingTask,
|
||||
ShippingNoticeDocument,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_policy_registry import (
|
||||
published_policy,
|
||||
@@ -79,8 +80,14 @@ def freeze_order_snapshot(
|
||||
ConflictError: 快照已存在、版本冲突或存在未确认 LLM 关键字段。
|
||||
ValidationError: 当前 Extraction 不完整或核心字段契约不匹配。
|
||||
"""
|
||||
if task.order_snapshot_id:
|
||||
raise ConflictError('Order snapshot is already frozen', code='SHIPPING.ORDER_SNAPSHOT_FROZEN')
|
||||
# [STEP 1] 锁定数据库中的 Task,令并发确认串行化;同一 Task 的重复点击复用既有快照。
|
||||
locked_task = ShippingTask.query.filter_by(id=task.id).with_for_update().one()
|
||||
if locked_task.order_snapshot_id:
|
||||
snapshot = db.session.get(ShippingOrderSnapshot, locked_task.order_snapshot_id)
|
||||
if snapshot is not None:
|
||||
return snapshot
|
||||
raise ConflictError('Order snapshot reference is invalid', code='SHIPPING.ORDER_SNAPSHOT_FROZEN')
|
||||
task = locked_task
|
||||
if not actor_id:
|
||||
raise ValidationError('Snapshot freeze requires an operator', code='SHIPPING.ORDER_FREEZE_BLOCKED')
|
||||
actual_version = int(task.order_data_version or 1)
|
||||
@@ -92,9 +99,11 @@ def freeze_order_snapshot(
|
||||
)
|
||||
extraction = _accepted_extraction(task)
|
||||
policy, configs = _policy_configs(extraction)
|
||||
customer_match = _confirmed_ordering_customer(extraction)
|
||||
from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness
|
||||
assert_freeze_readiness(task=task, extraction=extraction, policy=policy, configs=configs)
|
||||
_assert_llm_review_gate(extraction, configs)
|
||||
header_values, line_values = _extraction_values(extraction, configs)
|
||||
customer_match = _confirmed_ordering_customer(extraction)
|
||||
|
||||
# [STEP 1] 所有已发布字段均按 field_id 冻结;核心字段同步为强类型列,供既有履约能力兼容读取。
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
@@ -123,6 +132,7 @@ def freeze_order_snapshot(
|
||||
'confirmed_at': customer_match.confirmed_at.isoformat() if customer_match.confirmed_at else None,
|
||||
},
|
||||
},
|
||||
source_manifest_json=_source_manifest(extraction=extraction, policy=policy),
|
||||
frozen_by_id=actor_id,
|
||||
header_values_json=_field_id_values(header_values, configs),
|
||||
**_project_values(header_values, HEADER_FIELD_PROJECTIONS),
|
||||
@@ -146,6 +156,48 @@ def freeze_order_snapshot(
|
||||
return snapshot
|
||||
|
||||
|
||||
def _source_manifest(*, extraction: ShippingOrderExtraction, policy: Any) -> dict[str, Any]:
|
||||
"""固化字段裁决来源、文档哈希与人工复核记录,禁止下游从可变表重建证据。"""
|
||||
observations = {
|
||||
item.id: item for item in ShippingOrderFieldObservation.query.filter_by(extraction_id=extraction.id).all()
|
||||
}
|
||||
documents = {
|
||||
item.id: item.content_hash for item in ShippingNoticeDocument.query.filter(
|
||||
ShippingNoticeDocument.id.in_({item.source_document_id for item in observations.values() if item.source_document_id})
|
||||
).all()
|
||||
} if observations else {}
|
||||
fields: list[dict[str, Any]] = []
|
||||
for decision in ShippingOrderFieldDecision.query.filter_by(extraction_id=extraction.id).all():
|
||||
observation = observations.get(decision.selected_observation_id)
|
||||
fields.append({
|
||||
'field_id': str(decision.field_id), 'line_id': decision.line_id,
|
||||
'decision_status': decision.decision_status,
|
||||
'selected_observation_id': decision.selected_observation_id,
|
||||
'supporting_observation_ids': list(decision.supporting_observation_ids_json or []),
|
||||
'document_id': observation.source_document_id if observation else None,
|
||||
'document_hash': documents.get(observation.source_document_id) if observation else None,
|
||||
'evidence_quote': observation.evidence_quote if observation else None,
|
||||
'evidence_ref': observation.evidence_ref if observation else None,
|
||||
'evidence_metadata': dict(observation.evidence_metadata_json or {}) if observation else {},
|
||||
})
|
||||
reviews = [
|
||||
{
|
||||
'id': item.id, 'scope': item.scope, 'line_position': item.line_position,
|
||||
'field_code': item.field_code, 'old_value': item.old_value_json, 'new_value': item.new_value_json,
|
||||
'evidence': item.evidence_ref, 'reason': item.reason, 'reviewed_by_id': item.reviewed_by_id,
|
||||
'created_at': item.created_at.isoformat() if item.created_at else None,
|
||||
}
|
||||
for item in ShippingOrderReviewEvent.query.filter_by(extraction_id=extraction.id, snapshot_id=None).all()
|
||||
]
|
||||
return {
|
||||
'schema_version_id': extraction.schema_version_id,
|
||||
'schema_checksum': extraction.schema_version.checksum,
|
||||
'fulfillment_policy': {'id': policy.id, 'version': policy.version, 'checksum': policy.checksum},
|
||||
'fields': fields,
|
||||
'manual_reviews': reviews,
|
||||
}
|
||||
|
||||
|
||||
def assert_task_order_is_editable(task: ShippingTask) -> None:
|
||||
"""拒绝冻结后对 Candidate/Extraction 的任何直接编辑,防止快照与解析事实漂移。"""
|
||||
if task.order_snapshot_id:
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""把冻结 EML 正文补充事实保守合并到 PDF 确定性订单。
|
||||
|
||||
依赖:Run 冻结 Schema、正文补充表契约和 PO 标准化。
|
||||
逻辑:优先 PO+MPN;仅唯一 Reservation 的 PO 可降级广播,歧义只写复核原因。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.po_number import normalize_atomic_po_number
|
||||
|
||||
|
||||
def _values(fields: Any, code: str, codes: dict[str, str]) -> set[str]:
|
||||
"""读取订单字段的唯一非空值集合,避免从多 Observation 中挑一个猜测值。"""
|
||||
if not isinstance(fields, list):
|
||||
return set()
|
||||
return {
|
||||
str(observation.get('value') or '').strip().upper()
|
||||
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 str(observation.get('value') or '').strip()
|
||||
}
|
||||
|
||||
|
||||
def _inject(fields: list[dict[str, Any]], field_id: str, value: str, evidence: dict[str, Any], document_id: int) -> None:
|
||||
"""以正文权威值替换目标字段 Observation;数量字段永不调用本函数。"""
|
||||
target = next((item for item in fields if isinstance(item, dict) and item.get('field_id') == field_id), None)
|
||||
observation = {
|
||||
'value': value, 'document_id': document_id, 'quote': str(evidence.get('raw_value') or value),
|
||||
'confidence': 1.0, 'email_supplement_evidence': {
|
||||
'table_index': evidence.get('table_index'), 'row_index': evidence.get('row_index'),
|
||||
'column_index': evidence.get('column_index'), 'cell_id': evidence.get('cell_id'),
|
||||
},
|
||||
}
|
||||
if target is None:
|
||||
fields.append({'field_id': field_id, 'observations': [observation]})
|
||||
else:
|
||||
target['observations'] = [observation]
|
||||
|
||||
|
||||
def merge_email_supplements(*, orders: list[dict[str, Any]], supplements_by_intake: dict[int, dict[str, Any]], schema_definition: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""合并正文的 Reservation/Allocation/Source 字段,并对歧义订单附加复核冲突。"""
|
||||
codes = {str(item.get('field_id') or ''): str(item.get('field_code') or '') for item in schema_definition.get('fields') or [] if isinstance(item, dict)}
|
||||
ids = {code: field_id for field_id, code in codes.items()}
|
||||
merged: list[dict[str, Any]] = []
|
||||
for raw in orders:
|
||||
order = copy.deepcopy(raw)
|
||||
intake_id = int(order.get('_hxops_intake_id') or 0)
|
||||
supplement = supplements_by_intake.get(intake_id) or {}
|
||||
rows = supplement.get('rows') if isinstance(supplement.get('rows'), list) else []
|
||||
po_values = {normalize_atomic_po_number(value).upper() for value in _values(order.get('header_fields'), 'customer_po_number', codes) | _values(order.get('header_fields'), 'po_number', codes) if normalize_atomic_po_number(value)}
|
||||
mpn_values = _values(order.get('header_fields'), 'part_number', codes)
|
||||
for line in order.get('lines') or []:
|
||||
if isinstance(line, dict):
|
||||
mpn_values.update(_values(line.get('fields'), 'part_number', codes))
|
||||
candidates = [row for row in rows if normalize_atomic_po_number(row.get('po_number')).upper() in po_values]
|
||||
exact = [row for row in candidates if row.get('mpn') and str(row['mpn']).strip().upper() in mpn_values]
|
||||
selected = exact
|
||||
relation = 'po_mpn'
|
||||
if not selected and candidates:
|
||||
reservations = {str(row.get('reservation_id') or '').strip() for row in candidates if str(row.get('reservation_id') or '').strip()}
|
||||
if len(candidates) == 1 or len(reservations) == 1:
|
||||
selected = candidates
|
||||
relation = 'po_fallback'
|
||||
if not selected:
|
||||
if candidates:
|
||||
order.setdefault('conflicts', []).append({'severity': 'blocking', 'reason': 'supplement_relation_ambiguous'})
|
||||
merged.append(order)
|
||||
continue
|
||||
for source_row in selected:
|
||||
row_mpn = str(source_row.get('mpn') or '').strip().upper()
|
||||
target_lines = [
|
||||
line for line in order.get('lines') or [] if isinstance(line, dict)
|
||||
and (not row_mpn or row_mpn in _values(line.get('fields'), 'part_number', codes))
|
||||
]
|
||||
if not target_lines:
|
||||
order.setdefault('conflicts', []).append({'severity': 'blocking', 'reason': 'supplement_relation_ambiguous'})
|
||||
continue
|
||||
for field, target_code in (
|
||||
('reservation_id', 'reservation_id'),
|
||||
('allocation_id', 'allocation_id'),
|
||||
('source_type', 'inventory_source_hint'),
|
||||
):
|
||||
value = str(source_row.get(field) or '').strip()
|
||||
field_id = ids.get(target_code)
|
||||
if value and field_id:
|
||||
for line in target_lines:
|
||||
_inject(line.setdefault('fields', []), field_id, value, source_row.get('evidence', {}).get(field, {}), int(supplement.get('document_id') or 0))
|
||||
# 来源方和分配实体是证据字段;没有对应 Schema 字段时仍写入内部订单元数据。
|
||||
order.setdefault('_hxops_email_supplement_evidence', []).append({
|
||||
'source_from_party': source_row.get('source_from_party'),
|
||||
'allocated_entity': source_row.get('allocated_entity'),
|
||||
'allocated_qty': source_row.get('allocated_qty'),
|
||||
'table_index': source_row.get('table_index'), 'row_index': source_row.get('row_index'),
|
||||
})
|
||||
order['_hxops_email_supplement_relation'] = relation
|
||||
merged.append(order)
|
||||
return merged
|
||||
@@ -16,6 +16,7 @@ _PO_NUMBER_PATTERNS = (
|
||||
r"(?i)Purchase\s+Order\s*(?:Number|No\.?|#)?\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/]*)",
|
||||
r"(?:采购订单号|采购单号|订单号|PO号)\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/]*)",
|
||||
)
|
||||
_ATOMIC_PO_NUMBER_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9\-_/]*")
|
||||
|
||||
|
||||
def normalize_po_number(value: Any) -> str:
|
||||
@@ -35,6 +36,12 @@ def normalize_po_number(value: Any) -> str:
|
||||
return text
|
||||
|
||||
|
||||
def normalize_atomic_po_number(value: Any) -> str:
|
||||
"""标准化单一 PO;含多个 PO 或自由文本的值不能作为合并、建单身份。"""
|
||||
normalized = normalize_po_number(value)
|
||||
return normalized if _ATOMIC_PO_NUMBER_PATTERN.fullmatch(normalized) else ""
|
||||
|
||||
|
||||
def find_po_number_in_document(text: str) -> str:
|
||||
"""从发货通知全文中按正则模式提取 PO Number。"""
|
||||
raw = str(text or "")
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""
|
||||
人工订单复核的结构化证据校验与审计序列化。
|
||||
|
||||
用途:拒绝任意字符串证据,确保人工修订只引用当前任务的文档观察或具名人工输入。
|
||||
依赖:ShippingTask、ShippingOrderExtraction、ShippingOrderFieldObservation 和 JSON 标准库。
|
||||
逻辑:document_cell 必须属于当前 Extraction 与 Document;manual_input 必须带业务原因,返回稳定 JSON 审计载荷。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingOrderFieldObservation, ShippingTask
|
||||
|
||||
|
||||
def validate_review_evidence(*, task: ShippingTask, evidence: Any, reason: str) -> str:
|
||||
"""校验并规范化一次人工复核证据,禁止跨任务、跨 Extraction 或伪造观察。"""
|
||||
if not isinstance(evidence, dict):
|
||||
raise ValidationError('Structured review evidence is required', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED')
|
||||
evidence_type = str(evidence.get('evidence_type') or '').strip()
|
||||
if evidence_type == 'manual_input':
|
||||
manual_reason = str(evidence.get('reason') or reason or '').strip()
|
||||
if not manual_reason:
|
||||
raise ValidationError('Manual input evidence requires a reason', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED')
|
||||
normalized = {'evidence_type': 'manual_input', 'reason': manual_reason[:2000]}
|
||||
elif evidence_type == 'document_cell':
|
||||
extraction_id = int(task.current_order_extraction_id or 0)
|
||||
try:
|
||||
document_id = int(evidence.get('document_id'))
|
||||
observation_id = int(evidence.get('observation_id'))
|
||||
page_no = int(evidence.get('page_no'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('Document evidence is invalid', code='SHIPPING.ORDER_REVIEW_EVIDENCE_INVALID') from exc
|
||||
table_id = str(evidence.get('table_id') or '').strip()
|
||||
cell_id = str(evidence.get('cell_id') or '').strip()
|
||||
observation = ShippingOrderFieldObservation.query.filter_by(
|
||||
id=observation_id, extraction_id=extraction_id, source_document_id=document_id,
|
||||
).first()
|
||||
if observation is None or not table_id or not cell_id or page_no < 1:
|
||||
raise ValidationError('Document evidence does not belong to this order', code='SHIPPING.ORDER_REVIEW_EVIDENCE_INVALID')
|
||||
normalized = {
|
||||
'evidence_type': 'document_cell', 'document_id': document_id,
|
||||
'observation_id': observation_id, 'page_no': page_no,
|
||||
'table_id': table_id[:128], 'cell_id': cell_id[:128],
|
||||
}
|
||||
else:
|
||||
raise ValidationError('Unsupported review evidence type', code='SHIPPING.ORDER_REVIEW_EVIDENCE_INVALID')
|
||||
return json.dumps(normalized, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
|
||||
@@ -121,7 +121,7 @@ def resolve_field_conflict(
|
||||
expected_conflict_version: int | None = None,
|
||||
expected_order_data_version: int | None = None,
|
||||
resolved_by_id: int | None = None,
|
||||
evidence_ref: str | None = None,
|
||||
evidence: dict[str, Any] | None = None,
|
||||
reason: str | None = None,
|
||||
idempotency_key: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
@@ -134,7 +134,7 @@ def resolve_field_conflict(
|
||||
Args:
|
||||
resolution: keep_existing | take_incoming | custom
|
||||
expected_conflict_version / expected_order_data_version: 乐观锁;不匹配抛 409。
|
||||
resolved_by_id / evidence_ref / reason: 人工纠错审计必填,禁止无证据回写。
|
||||
resolved_by_id / evidence / reason: 人工纠错审计必填,禁止无证据回写。
|
||||
"""
|
||||
from app.services.shipping_notice.order_freeze_service import assert_task_order_is_editable
|
||||
|
||||
@@ -200,17 +200,18 @@ def resolve_field_conflict(
|
||||
code='SHIPPING.INVALID_CONFLICT_RESOLUTION',
|
||||
)
|
||||
|
||||
# [STEP 2] 行级冲突回写当前 FieldValue;旧任务行投影不再参与业务真相。
|
||||
clean_reason = str(reason or '').strip()
|
||||
if not resolved_by_id or not clean_reason:
|
||||
raise ValidationError('Field conflict resolution requires operator, evidence and reason', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED')
|
||||
from app.services.shipping_notice.review_evidence_service import validate_review_evidence
|
||||
clean_evidence_ref = validate_review_evidence(task=task, evidence=evidence, reason=clean_reason)
|
||||
|
||||
# [STEP 2] 先验证证据再写业务值,避免伪造证据被拒后留下半次更新。
|
||||
if conflict.position is not None:
|
||||
replace_current_line_field_value(
|
||||
task=task, position=int(conflict.position), field_code=conflict.field_name, value=value,
|
||||
)
|
||||
|
||||
clean_evidence_ref = str(evidence_ref or '').strip()
|
||||
clean_reason = str(reason or '').strip()
|
||||
if not resolved_by_id or not clean_evidence_ref or not clean_reason:
|
||||
raise ValidationError('Field conflict resolution requires operator, evidence and reason', code='SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED')
|
||||
|
||||
conflict.status = 'resolved'
|
||||
conflict.resolved_value = value
|
||||
conflict.resolved_by_id = resolved_by_id
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""订单重发后的任务替代门禁。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingFreightCancellation, ShippingTask, ShippingTaskEvent
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
|
||||
|
||||
def establish_task_supersession(*, old_task: ShippingTask, new_task: ShippingTask, actor_id: int, reason: str) -> None:
|
||||
"""锁定并替代旧版本;上传过的旧任务先进入撤销等待,新版本保持阻断。"""
|
||||
old = ShippingTask.query.filter_by(id=old_task.id).with_for_update().one()
|
||||
new = ShippingTask.query.filter_by(id=new_task.id).with_for_update().one()
|
||||
if new.supersedes_task_id != old.id:
|
||||
raise ConflictError('Revision parent mismatch', code='SHIPPING.TASK_SUPERSESSION_INVALID')
|
||||
if not task_is_active(old):
|
||||
return
|
||||
external = bool(old.freight_ref_no or old.upload_receipt_json or str(old.upload_status or '').lower() in {'uploaded', 'succeeded', 'success'} or old.process_status == 'uploaded')
|
||||
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}))
|
||||
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()}))
|
||||
|
||||
|
||||
def assert_task_not_supersession_blocked(task: ShippingTask) -> None:
|
||||
"""库存、导出和上传入口调用,阻止撤销未完成的新版本继续履约。"""
|
||||
if str(task.lifecycle_status or '').lower() == 'blocked' and task.pending_human_reason == 'freight_cancellation_required':
|
||||
raise ConflictError('Freight cancellation is required before this revision can continue', code='SHIPPING.FREIGHT_CANCELLATION_REQUIRED')
|
||||
@@ -15,7 +15,7 @@ from typing import Any
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingBatch, ShippingTask
|
||||
from app.services.shipping_notice.constants import CP_TASK_EXISTS
|
||||
from app.services.shipping_notice.decision_workflow import submit_decision
|
||||
@@ -598,7 +598,9 @@ def _assert_order_data_version(task: ShippingTask, payload: dict[str, Any]) -> d
|
||||
"""
|
||||
raw = payload.get('expected_order_data_version')
|
||||
if raw is None or raw == '':
|
||||
return None
|
||||
return tool_response(status='failed', task=task, message='expected_order_data_version 必填', data={
|
||||
'error_code': 'SHIPPING.ORDER_DATA_VERSION_REQUIRED',
|
||||
})
|
||||
try:
|
||||
expected = int(raw)
|
||||
except (TypeError, ValueError):
|
||||
@@ -772,10 +774,14 @@ def _prepare_review_context(task: ShippingTask, payload: dict[str, Any]) -> tupl
|
||||
actor_id = int(payload.get('reviewed_by_id'))
|
||||
except (TypeError, ValueError):
|
||||
return None, tool_response(status='failed', task=task, message='缺少复核人员', data={'error_code': 'SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED'})
|
||||
evidence_ref = str(payload.get('evidence_ref') or '').strip()
|
||||
reason = str(payload.get('reason') or payload.get('comment') or '').strip()
|
||||
if not evidence_ref or not reason:
|
||||
if not reason:
|
||||
return None, tool_response(status='failed', task=task, message='人工纠错必须提供证据和原因', data={'error_code': 'SHIPPING.ORDER_REVIEW_EVIDENCE_REQUIRED'})
|
||||
from app.services.shipping_notice.review_evidence_service import validate_review_evidence
|
||||
try:
|
||||
evidence_ref = validate_review_evidence(task=task, evidence=payload.get('evidence'), reason=reason)
|
||||
except ValidationError as exc:
|
||||
return None, tool_response(status='failed', task=task, message='人工纠错证据无效', data={'error_code': exc.code})
|
||||
return {'reviewed_by_id': actor_id, 'evidence_ref': evidence_ref, 'reason': reason}, None
|
||||
|
||||
|
||||
|
||||
@@ -152,8 +152,14 @@ def mark_attempt_result_unknown(attempt: ShippingUploadAttempt) -> ShippingUploa
|
||||
def record_manual_upload(task: ShippingTask, *, artifact_id: int | None, evidence_asset_no: str, operator_id: int, freight_ref_no: str | None = None) -> ShippingUploadAttempt:
|
||||
"""登记人工上传成功;必须持有当前用户已上传的私有截图或回执资产。"""
|
||||
asset_no = str(evidence_asset_no or '').strip()
|
||||
if not asset_no:
|
||||
raise ValidationError('Manual upload evidence is required', code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED')
|
||||
receipt_no = str(freight_ref_no or '').strip()
|
||||
if not asset_no or not receipt_no:
|
||||
raise ValidationError('Manual upload receipt number and evidence are required', code='SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED')
|
||||
from app.services.shipping_notice.task_disposition_service import task_is_active
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked
|
||||
if not task_is_active(task):
|
||||
raise ConflictError('Inactive task cannot be manually uploaded', code='SHIPPING.TASK_LIFECYCLE_CONFLICT')
|
||||
assert_task_not_supersession_blocked(task)
|
||||
artifact = current_upload_artifact(task, artifact_id)
|
||||
asset = get_asset_for_user(asset_no, operator_id)
|
||||
if asset.upload_status != 'ready' or asset.deleted_at is not None:
|
||||
@@ -168,7 +174,7 @@ def record_manual_upload(task: ShippingTask, *, artifact_id: int | None, evidenc
|
||||
db.session.flush()
|
||||
mark_asset_referenced(asset)
|
||||
return complete_attempt(
|
||||
attempt, success=True, callback_id=f'manual:{attempt.id}', freight_ref_no=freight_ref_no,
|
||||
attempt, success=True, callback_id=f'manual:{attempt.id}', freight_ref_no=receipt_no,
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user