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
@@ -210,6 +210,19 @@ def retire_order_document_profile(profile_id: int):
|
||||
return _ok(service.retire(profile_id, actor_id=_actor_id()))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>/auto-freeze-qualification/suspend', methods=['POST'])
|
||||
@require_admin
|
||||
def suspend_order_document_profile_auto_freeze_qualification(profile_id: int):
|
||||
"""暂停单个发布模板版本的自动冻结资格,不影响模板解析可用性。"""
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
|
||||
data = request.get_json(silent=True) or {}
|
||||
qualification = quality.suspend_auto_freeze_qualification(
|
||||
profile_id=profile_id, actor_id=int(_actor_id() or 0), reason=str(data.get('reason') or ''),
|
||||
)
|
||||
return _ok(quality.serialize_qualification(qualification))
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-document-profiles/<int:profile_id>', methods=['DELETE'])
|
||||
@require_admin
|
||||
def delete_order_document_profile(profile_id: int):
|
||||
|
||||
+32
-52
@@ -82,9 +82,6 @@ def _normalize_user_attachments(value) -> list[dict]:
|
||||
'type': attachment_type,
|
||||
'source': source,
|
||||
}
|
||||
attachment_id = re.sub(r'[\x00-\x1f\x7f]', '', str(item.get('id') or '')).strip()[:128]
|
||||
if attachment_id:
|
||||
snapshot['id'] = attachment_id
|
||||
extension = str(item.get('extension') or '').strip().lower()
|
||||
if re.fullmatch(r'[a-z0-9]{1,16}', extension):
|
||||
snapshot['extension'] = extension
|
||||
@@ -141,8 +138,7 @@ def _build_chat_adapter_hints(
|
||||
*,
|
||||
shipping_task_id: str | None = None,
|
||||
shipping_batch_no: str | None = None,
|
||||
shipping_temporary_inventory_asset_no: str | None = None,
|
||||
shipping_temporary_inventory_session_no: str | None = None,
|
||||
shipping_intake_nos: list[str] | None = None,
|
||||
) -> dict | None:
|
||||
"""
|
||||
构建聊天入口分发给领域 adapter 的提示字典。
|
||||
@@ -152,17 +148,16 @@ def _build_chat_adapter_hints(
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
temporary_asset_no = str(shipping_temporary_inventory_asset_no or '').strip().upper()
|
||||
temporary_session_no = str(shipping_temporary_inventory_session_no or '').strip().upper()
|
||||
if not task_id and not batch_no and not temporary_asset_no and not temporary_session_no:
|
||||
intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item or '').strip()})
|
||||
if not task_id and not batch_no and not intake_nos:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
'capability': 'temporary_inventory' if temporary_asset_no else None,
|
||||
'temporary_inventory_asset_no': temporary_asset_no or None,
|
||||
'temporary_inventory_session_no': temporary_session_no or None,
|
||||
'intake_nos': intake_nos,
|
||||
'capability': 'order_extraction' if intake_nos else None,
|
||||
'contract_version': 'shipping-order-extraction-v1' if intake_nos else None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -204,18 +199,17 @@ def _user_facing_chat_query(text: str, *, agent_code: str | None = None) -> str:
|
||||
|
||||
task_match = re.search(r'(SN-\d{8}-[A-Z0-9]+)', value, re.I)
|
||||
task_no = task_match.group(1).upper() if task_match else ''
|
||||
if 'create_task' in value or 'get_task_status' in value:
|
||||
if 'create_task' in value or 'get_task_status' in value or 'parse_notice' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
|
||||
def _serialize_session(
|
||||
session: ChatSession,
|
||||
*,
|
||||
unseen_order_extraction_count: int = 0,
|
||||
*, unseen_order_extraction_count: int = 0,
|
||||
unseen_order_extraction_severity: str | None = None,
|
||||
) -> dict:
|
||||
"""输出会话摘要及订单识别待查看聚合,不返回 Run 内容或错误正文。"""
|
||||
"""输出会话摘要及订单抽取待查看聚合,不返回 Run 内容或错误正文。"""
|
||||
last_active = session.last_active_at or session.created_at
|
||||
return {
|
||||
'id': session.id,
|
||||
@@ -228,8 +222,10 @@ def _serialize_session(
|
||||
}
|
||||
|
||||
|
||||
def _order_extraction_attention_by_conversation(*, user_id: int, agent_id: int, conversation_ids: set[str]) -> dict[str, tuple[int, str]]:
|
||||
"""聚合阶段4之后生成、且当前用户尚未确认的终态订单识别提醒。"""
|
||||
def _order_extraction_attention_by_conversation(
|
||||
*, user_id: int, agent_id: int, conversation_ids: set[str],
|
||||
) -> dict[str, tuple[int, str]]:
|
||||
"""聚合同用户同 Agent 尚未确认的终态订单抽取提醒,防止跨会话泄露。"""
|
||||
if not conversation_ids:
|
||||
return {}
|
||||
severity_rank = {'info': 1, 'warning': 2, 'error': 3}
|
||||
@@ -247,10 +243,10 @@ def _order_extraction_attention_by_conversation(*, user_id: int, agent_id: int,
|
||||
aggregate: dict[str, tuple[int, str]] = {}
|
||||
for conversation_id, status in rows:
|
||||
severity = status_severity.get(str(status or ''), 'info')
|
||||
current_count, current_severity = aggregate.get(conversation_id, (0, severity))
|
||||
count, existing = aggregate.get(conversation_id, (0, severity))
|
||||
aggregate[conversation_id] = (
|
||||
current_count + 1,
|
||||
severity if severity_rank[severity] >= severity_rank[current_severity] else current_severity,
|
||||
count + 1,
|
||||
severity if severity_rank[severity] >= severity_rank[existing] else existing,
|
||||
)
|
||||
return aggregate
|
||||
|
||||
@@ -1162,9 +1158,9 @@ def get_chat_messages():
|
||||
ChatLog.agent_id == g.current_agent.id,
|
||||
ChatLog.conversation_id == conversation_id,
|
||||
).order_by(ChatLog.created_at.asc()).all()
|
||||
|
||||
|
||||
def _is_order_extraction_state_card(payload):
|
||||
"""仅识别正式 Run 状态卡,避免用户上传记录在历史回放中被投影成重复助手卡。"""
|
||||
"""只识别正式 Run 状态卡;用户上传锚点不得回放为重复的助手卡。"""
|
||||
if not isinstance(payload, dict):
|
||||
return False
|
||||
run_no = str(payload.get('order_extraction_run_no') or '').strip()
|
||||
@@ -1172,8 +1168,7 @@ def get_chat_messages():
|
||||
|
||||
run_nos = {
|
||||
str(log.payload.get('order_extraction_run_no') or '').strip()
|
||||
for log in logs
|
||||
if _is_order_extraction_state_card(log.payload)
|
||||
for log in logs if _is_order_extraction_state_card(log.payload)
|
||||
}
|
||||
order_extraction_runs = {}
|
||||
if run_nos:
|
||||
@@ -1186,6 +1181,7 @@ def get_chat_messages():
|
||||
ShippingOrderExtractionRun.run_no.in_(run_nos),
|
||||
).all()
|
||||
}
|
||||
|
||||
messages = []
|
||||
agent_code = str(getattr(g.current_agent, 'agent_code', '') or '').strip() or 'generic'
|
||||
for log in logs:
|
||||
@@ -1197,8 +1193,7 @@ def get_chat_messages():
|
||||
if key != 'user_attachments'
|
||||
}
|
||||
run_no = str(assistant_payload.get('order_extraction_run_no') or '').strip()
|
||||
is_order_extraction_state_card = _is_order_extraction_state_card(raw_payload)
|
||||
if is_order_extraction_state_card and run_no in order_extraction_runs:
|
||||
if _is_order_extraction_state_card(raw_payload) and run_no in order_extraction_runs:
|
||||
from app.services.shipping_notice.order_extraction_run_service import serialize_order_extraction_message_state
|
||||
|
||||
assistant_payload['shipping_order_extraction_state'] = serialize_order_extraction_message_state(
|
||||
@@ -1209,11 +1204,7 @@ def get_chat_messages():
|
||||
if user_attachments:
|
||||
user_msg['attachments'] = user_attachments
|
||||
messages.append(user_msg)
|
||||
if (
|
||||
str(raw_payload.get('formId') or '').strip()
|
||||
== f'shipping-order-extraction-user:{run_no}'
|
||||
):
|
||||
# 用户上传记录携带 Run 锚点只用于关联,不能再回放为一张助手状态卡。
|
||||
if str(raw_payload.get('formId') or '').strip() == f'shipping-order-extraction-user:{run_no}':
|
||||
continue
|
||||
if (
|
||||
not log.answer
|
||||
@@ -1469,8 +1460,14 @@ def chat_completions():
|
||||
conversation_id = data.get('conversation_id')
|
||||
shipping_task_id = str(data.get('task_id') or '').strip()
|
||||
shipping_batch_no = str(data.get('batch_no') or '').strip()
|
||||
shipping_temporary_inventory_asset_no = str(data.get('shipping_temporary_inventory_asset_no') or '').strip().upper()
|
||||
shipping_temporary_inventory_session_no = str(data.get('shipping_temporary_inventory_session_no') or '').strip().upper()
|
||||
raw_shipping_intakes = data.get('shipping_intake_nos')
|
||||
if raw_shipping_intakes is not None and not isinstance(raw_shipping_intakes, list):
|
||||
raise ValidationError('shipping_intake_nos must be a list')
|
||||
shipping_intake_nos = sorted({
|
||||
str(item or '').strip().upper()
|
||||
for item in (raw_shipping_intakes or [])
|
||||
if str(item or '').strip()
|
||||
})
|
||||
kb_type = data.get('kb_type', '企业知识库')
|
||||
user_attachments = _normalize_user_attachments(data.get('user_attachments'))
|
||||
session_title = display_query or (user_attachments[0]['name'] if user_attachments else str(query or '').strip())
|
||||
@@ -1609,8 +1606,7 @@ def chat_completions():
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no,
|
||||
shipping_temporary_inventory_session_no=shipping_temporary_inventory_session_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
),
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
@@ -1653,8 +1649,7 @@ def chat_completions():
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no,
|
||||
shipping_temporary_inventory_session_no=shipping_temporary_inventory_session_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
),
|
||||
),
|
||||
)
|
||||
@@ -1683,7 +1678,6 @@ def chat_completions():
|
||||
from app.services.chat.stream_relay import (
|
||||
iter_handler_preface_sse,
|
||||
iter_handler_terminal_sse,
|
||||
should_recover_upstream_error,
|
||||
)
|
||||
|
||||
for preface_line in iter_handler_preface_sse(relay_stream_ctx, emitted_keys=emitted_handler_state_keys):
|
||||
@@ -1707,20 +1701,6 @@ def chat_completions():
|
||||
|
||||
provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None
|
||||
event_name = event_data.get('event')
|
||||
if event_name == 'error' and should_recover_upstream_error(relay_stream_ctx, event_data):
|
||||
current_app.logger.warning(
|
||||
'[chat-api] recover upstream error from persisted shipping extraction request_id=%s session_id=%s',
|
||||
request_id,
|
||||
local_session_id,
|
||||
)
|
||||
event_data = {
|
||||
**event_data,
|
||||
'event': 'message_end',
|
||||
'answer': '',
|
||||
'replace_answer': False,
|
||||
'recovered_upstream_error': True,
|
||||
}
|
||||
event_name = 'message_end'
|
||||
if event_name in ('error', 'message_end', 'workflow_finished') and user_attachments:
|
||||
try:
|
||||
attachment_chat_log_id = int(event_data.get('chat_log_id') or 0)
|
||||
|
||||
@@ -108,6 +108,19 @@ def _dify_openapi_spec() -> dict:
|
||||
def _payload() -> dict:
|
||||
return request.get_json(silent=True) or {}
|
||||
|
||||
|
||||
def _require_read_capability(payload: dict, *, scope: str, task_no: str | None = None, batch_no: str | None = None) -> None:
|
||||
"""Chatflow 只读查询必须携带短效会话能力令牌,不能仅依赖全局集成密钥。"""
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.chat_tool_capability import require_chat_capability
|
||||
claims = require_chat_capability(token=payload.get('shipping_chat_capability_token'), scope=scope, task_no=task_no, batch_no=batch_no)
|
||||
db.session.add(ShippingAuditEvent(
|
||||
event_type='chatflow_tool_read', aggregate_type='chat_session', aggregate_id=str(claims['sid']),
|
||||
task_no=task_no, actor_type='chatflow', actor_id=str(claims['uid']),
|
||||
request_id=str(request.headers.get('X-Request-ID') or '')[:64] or None,
|
||||
metadata_json={'tool': scope, 'token_nonce': str(claims['nonce'])[:16], 'success': True},
|
||||
))
|
||||
|
||||
def _generate_batch_no() -> str:
|
||||
from datetime import datetime
|
||||
return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
@@ -299,7 +312,10 @@ def tool_get_task_status():
|
||||
查询任务状态。
|
||||
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_task_status(_payload()))
|
||||
payload = _payload()
|
||||
task_no = str(payload.get('task_id') or payload.get('task_no') or '').strip().upper()
|
||||
_require_read_capability(payload, scope='get_shipping_status', task_no=task_no or None)
|
||||
return jsonify(shipping_tools.get_task_status(payload))
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST'])
|
||||
def tool_get_batch_status():
|
||||
@@ -311,6 +327,7 @@ def tool_get_batch_status():
|
||||
batch_no = str(payload.get('batch_no') or '').strip()
|
||||
if not batch_no:
|
||||
raise ValidationError("batch_no is required")
|
||||
_require_read_capability(payload, scope='get_batch_status', batch_no=batch_no)
|
||||
batch = get_batch_by_no(batch_no)
|
||||
if not batch:
|
||||
raise NotFoundError("batch not found")
|
||||
|
||||
@@ -620,13 +620,12 @@ def workspace_update_shipping_notice_fields(task_no: str):
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'fields': fields, 'event_source': 'workspace_api'}
|
||||
payload['reviewed_by_id'] = int(user.id)
|
||||
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
|
||||
payload['evidence'] = data.get('evidence')
|
||||
payload['reason'] = str(data.get('reason') or '').strip()
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
if data.get('expected_order_data_version') is not None:
|
||||
payload['expected_order_data_version'] = data.get('expected_order_data_version')
|
||||
payload['expected_order_data_version'] = data.get('expected_order_data_version')
|
||||
idem = str(data.get('idempotency_key') or '').strip()
|
||||
if idem:
|
||||
payload['idempotency_key'] = idem
|
||||
@@ -659,6 +658,28 @@ def workspace_freeze_shipping_order(task_no: str):
|
||||
'frozen_at': snapshot.frozen_at.isoformat(),
|
||||
})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-freight-cancellations/<int:cancellation_id>/complete', methods=['POST'])
|
||||
def workspace_complete_shipping_freight_cancellation(cancellation_id: int):
|
||||
"""登记货代撤销回执并解除合法后继版本的履约阻断。"""
|
||||
user = _require_user()
|
||||
data = request.get_json(silent=True) or {}
|
||||
from app.models import ShippingFreightCancellation
|
||||
cancellation = ShippingFreightCancellation.query.filter_by(id=cancellation_id).one_or_none()
|
||||
if cancellation is None:
|
||||
raise NotFoundError('Not found')
|
||||
old_task = db.session.get(ShippingTask, cancellation.old_task_id)
|
||||
if old_task is None or int(old_task.user_id or 0) != int(user.id):
|
||||
raise NotFoundError('Not found')
|
||||
from app.services.shipping_notice.freight_cancellation_service import complete_freight_cancellation
|
||||
row = complete_freight_cancellation(
|
||||
cancellation_id=cancellation.id, actor_id=int(user.id),
|
||||
freight_receipt_no=str(data.get('freight_receipt_no') or ''),
|
||||
receipt_asset_id=data.get('receipt_asset_id'), note=str(data.get('note') or ''),
|
||||
)
|
||||
db.session.commit()
|
||||
return _ok({'id': row.id, 'status': row.status, 'old_task_id': row.old_task_id, 'new_task_id': row.new_task_id})
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/update-notice-line', methods=['POST'])
|
||||
def workspace_update_shipping_notice_line(task_no: str):
|
||||
"""更新发货通知中的指定订单行。"""
|
||||
@@ -677,13 +698,12 @@ def workspace_update_shipping_notice_line(task_no: str):
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line_index': line_index, 'patch': patch, 'event_source': 'workspace_api'}
|
||||
payload['reviewed_by_id'] = int(user.id)
|
||||
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
|
||||
payload['evidence'] = data.get('evidence')
|
||||
payload['reason'] = str(data.get('reason') or '').strip()
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
if data.get('expected_order_data_version') is not None:
|
||||
payload['expected_order_data_version'] = data.get('expected_order_data_version')
|
||||
payload['expected_order_data_version'] = data.get('expected_order_data_version')
|
||||
idem = str(data.get('idempotency_key') or '').strip()
|
||||
if idem:
|
||||
payload['idempotency_key'] = idem
|
||||
@@ -742,7 +762,7 @@ def workspace_resolve_shipping_field_conflict(task_no: str, conflict_id: int):
|
||||
expected_conflict_version=_optional_int('expected_conflict_version'),
|
||||
expected_order_data_version=_optional_int('expected_order_data_version'),
|
||||
resolved_by_id=int(user.id),
|
||||
evidence_ref=str(data.get('evidence_ref') or '').strip() or None,
|
||||
evidence=data.get('evidence') if isinstance(data.get('evidence'), dict) else None,
|
||||
reason=str(data.get('reason') or '').strip() or None,
|
||||
idempotency_key=str(data.get('idempotency_key') or '').strip() or None,
|
||||
)
|
||||
@@ -762,13 +782,12 @@ def workspace_add_shipping_notice_line(task_no: str):
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line': line, 'event_source': 'workspace_api'}
|
||||
payload['reviewed_by_id'] = int(user.id)
|
||||
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
|
||||
payload['evidence'] = data.get('evidence')
|
||||
payload['reason'] = str(data.get('reason') or '').strip()
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
if data.get('expected_order_data_version') is not None:
|
||||
payload['expected_order_data_version'] = data.get('expected_order_data_version')
|
||||
payload['expected_order_data_version'] = data.get('expected_order_data_version')
|
||||
idem = str(data.get('idempotency_key') or '').strip()
|
||||
if idem:
|
||||
payload['idempotency_key'] = idem
|
||||
@@ -789,13 +808,12 @@ def workspace_remove_shipping_notice_line(task_no: str):
|
||||
from app.services.shipping_notice import tools as shipping_tools
|
||||
payload = {'task_id': task.task_no, 'line_index': line_index, 'event_source': 'workspace_api'}
|
||||
payload['reviewed_by_id'] = int(user.id)
|
||||
payload['evidence_ref'] = str(data.get('evidence_ref') or '').strip()
|
||||
payload['evidence'] = data.get('evidence')
|
||||
payload['reason'] = str(data.get('reason') or '').strip()
|
||||
comment = str(data.get('comment') or '').strip()
|
||||
if comment:
|
||||
payload['comment'] = comment
|
||||
if data.get('expected_order_data_version') is not None:
|
||||
payload['expected_order_data_version'] = data.get('expected_order_data_version')
|
||||
payload['expected_order_data_version'] = data.get('expected_order_data_version')
|
||||
idem = str(data.get('idempotency_key') or '').strip()
|
||||
if idem:
|
||||
payload['idempotency_key'] = idem
|
||||
|
||||
@@ -1,20 +1,15 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
用途:消费订单抽取领域 Run,调用显式绑定的 Dify Workflow 并持久化订单结果。
|
||||
依赖:Job queue、AgentRuntimeBinding、order_extraction_workflow、Run 状态机、provider_guard。
|
||||
逻辑:Job 只承载执行尝试;Run 是业务真相。线程快照须含 provider_config_json/schema_version_id;
|
||||
仅 Dify 传输类失败累计熔断。结果先完整落库并进入 result_persisted,再收口 completed/needs_review。
|
||||
用途:消费订单抽取 Run,使用固定模板确定性解析并持久化可复核结果。
|
||||
依赖:Job queue、冻结 Run/Plan、确定性路由和解析、统一审计服务。
|
||||
逻辑:每个 Unit 先持久化脱敏路由,再确定性解析或标记人工复核;不调用 Dify、Provider 或 Runtime Binding。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from types import SimpleNamespace
|
||||
|
||||
from flask import current_app
|
||||
from datetime import datetime
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
@@ -23,100 +18,92 @@ from app.jobs.queue import fail_job, finish_job
|
||||
from app.jobs.registry import register_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent,
|
||||
Job,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
mark_order_extraction_persistence_started,
|
||||
transition_order_extraction_run,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_workflow import (
|
||||
build_deterministic_unit_orders,
|
||||
execute_order_extraction_workflow,
|
||||
route_deterministic_unit,
|
||||
validate_unit_orders,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_progress import (
|
||||
record_order_extraction_progress_event,
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
from app.services.shipping_notice.order_extraction_provider_guard import (
|
||||
assert_circuit_closed,
|
||||
provider_slot,
|
||||
record_provider_failure,
|
||||
record_provider_success,
|
||||
)
|
||||
|
||||
|
||||
# 仅 Dify 传输类失败累计熔断;本地编程错误与 CIRCUIT_OPEN 自身不得拉长冷却窗。
|
||||
_PROVIDER_CIRCUIT_FAILURE_CODES = frozenset({
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
'SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED',
|
||||
})
|
||||
def _append_route_decision(*, run, unit, job, attempt_no: int, route_result) -> None:
|
||||
"""追加 Unit 脱敏路由投影及统一审计,禁止保存订单值、正文或布局载荷。"""
|
||||
decision = route_result.decision if isinstance(route_result.decision, dict) else {}
|
||||
candidates = decision.get('candidate_summary') if isinstance(decision.get('candidate_summary'), list) else []
|
||||
safe_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 candidates if isinstance(item, dict)]
|
||||
db.session.add(ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id, unit_id=unit.id, job_id=job.id, attempt_no=attempt_no,
|
||||
decision=route_result.execution_mode,
|
||||
match_status=str(decision.get('match_status') or 'no_match'),
|
||||
selected_profile_id=decision.get('selected_profile_id'),
|
||||
selected_profile_code=decision.get('selected_profile_code'),
|
||||
selected_profile_version=decision.get('selected_profile_version'),
|
||||
selected_profile_checksum=decision.get('selected_profile_checksum'),
|
||||
auto_create_approved=decision.get('auto_create_approved'),
|
||||
candidate_count=int(decision.get('candidate_count') or 0),
|
||||
table_count=int(decision.get('table_count') or 0),
|
||||
document_table_count=int(decision.get('document_table_count') or decision.get('table_count') or 0),
|
||||
business_table_count=int(decision.get('business_table_count') or 0),
|
||||
matched_table_count=int(decision.get('matched_table_count') or 0),
|
||||
parsed_table_count=int(decision.get('parsed_table_count') or 0),
|
||||
approved_table_count=int(decision.get('approved_table_count') or 0),
|
||||
candidate_summary_json=safe_candidates,
|
||||
fallback_reason_codes_json=[str(code) for code in decision.get('fallback_reason_codes') or []],
|
||||
))
|
||||
append_shipping_audit_event(
|
||||
event_type='order_extraction_route_decided', aggregate_type='order_extraction_unit',
|
||||
aggregate_id=str(unit.id), run_no=run.run_no, actor_type='system',
|
||||
reason_code=(decision.get('fallback_reason_codes') or [None])[0],
|
||||
before={'unit_status': unit.status}, after={'route': route_result.execution_mode},
|
||||
metadata={
|
||||
'attempt_no': int(attempt_no),
|
||||
'candidate_count': int(decision.get('candidate_count') or 0),
|
||||
'document_table_count': int(decision.get('document_table_count') or decision.get('table_count') or 0),
|
||||
'business_table_count': int(decision.get('business_table_count') or 0),
|
||||
'matched_table_count': int(decision.get('matched_table_count') or 0),
|
||||
'parsed_table_count': int(decision.get('parsed_table_count') or 0),
|
||||
'match_status': str(decision.get('match_status') or 'no_match'),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _execute_dify_unit_with_retry(
|
||||
*, app, run_snapshot: dict, unit_snapshot: dict, provider_snapshot: dict, timeout_seconds: int,
|
||||
max_attempts: int, backoff_ms: int, job_id: int, job_attempt: int,
|
||||
provider_max_concurrency: int, circuit_failure_threshold: int, circuit_cooldown_seconds: int,
|
||||
) -> dict:
|
||||
"""在线程独立应用上下文中用纯快照执行网络调用,并做有限指数退避重试。
|
||||
|
||||
核心逻辑:熔断仅统计 Dify 超时/请求失败;本地异常与 CIRCUIT_OPEN 不拉长冷却。
|
||||
"""
|
||||
last_error: Exception | None = None
|
||||
started = time.perf_counter()
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
with app.app_context():
|
||||
local_run = SimpleNamespace(**run_snapshot)
|
||||
local_unit = SimpleNamespace(**unit_snapshot)
|
||||
local_provider = SimpleNamespace(**provider_snapshot)
|
||||
|
||||
def observe(event):
|
||||
event['job_id'] = job_id
|
||||
event['attempt_count'] = job_attempt
|
||||
record_order_extraction_progress_event(run_no=local_run.run_no, event=event)
|
||||
|
||||
assert_circuit_closed(local_provider.id)
|
||||
with provider_slot(local_provider.id, max_concurrency=provider_max_concurrency):
|
||||
orders, meta = execute_order_extraction_workflow(
|
||||
run=local_run, unit=local_unit, provider=local_provider,
|
||||
timeout_seconds=timeout_seconds, event_observer=observe,
|
||||
)
|
||||
record_provider_success(local_provider.id)
|
||||
return {
|
||||
'unit_id': local_unit.id, 'orders': orders, 'meta': {**meta, 'execution_mode': 'dify'},
|
||||
'attempts': attempt, 'latency_ms': int((time.perf_counter() - started) * 1000),
|
||||
}
|
||||
except Exception as exc:
|
||||
last_error = exc
|
||||
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
|
||||
# [STEP] 仅传输类 Provider 失败累计熔断,避免本地异常或开路自身延长冷却。
|
||||
if isinstance(exc, AppError) and getattr(exc, 'code', None) in _PROVIDER_CIRCUIT_FAILURE_CODES:
|
||||
record_provider_failure(
|
||||
int(provider_snapshot['id']), threshold=circuit_failure_threshold,
|
||||
cooldown_seconds=circuit_cooldown_seconds,
|
||||
)
|
||||
if not retryable or attempt >= max_attempts:
|
||||
break
|
||||
delay = (backoff_ms / 1000) * (2 ** (attempt - 1))
|
||||
time.sleep(delay + random.uniform(0, min(delay * 0.25, 0.5)))
|
||||
assert last_error is not None
|
||||
raise last_error
|
||||
def _result_requires_review(*, units: list[ShippingOrderExtractionUnit], result: dict) -> bool:
|
||||
"""汇总人工复核、未接受候选和技术局部失败,确保不把不完整订单标记完成。"""
|
||||
return bool(
|
||||
result.get('pending_count')
|
||||
or any(unit.status in {'skipped', 'failed'} for unit in units)
|
||||
)
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
|
||||
def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行一次订单抽取 Job。
|
||||
执行一次纯确定性订单抽取 Job。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文,仅用于安全日志。
|
||||
payload: 须含 job_id;业务身份只从 Job.business_ref 对应 Run 读取。
|
||||
payload: 必须包含 job_id;Run 身份只从 Job.business_ref 读取。
|
||||
|
||||
Raises:
|
||||
Exception: 技术故障交给 Job 队列重试;模板、证据和业务歧义不抛出为技术失败。
|
||||
"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
@@ -128,15 +115,11 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
fail_job(job.id, error='order extraction run not found', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
if run.status in {'completed', 'needs_review'}:
|
||||
finish_job(
|
||||
job.id,
|
||||
result={'run_no': run.run_no, 'status': run.status, 'idempotent_replay': True},
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'status': run.status, 'idempotent_replay': True}, owned_attempt=owned_attempt)
|
||||
return
|
||||
if run.status == 'result_persisted':
|
||||
final_status = 'needs_review' if (run.result_json or {}).get('pending_count') else 'completed'
|
||||
transition_order_extraction_run(run, target_status=final_status)
|
||||
target = 'needs_review' if (run.result_json or {}).get('requires_review') else 'completed'
|
||||
transition_order_extraction_run(run, target_status=target)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'status': run.status}, owned_attempt=owned_attempt)
|
||||
return
|
||||
@@ -144,275 +127,110 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
fail_job(job.id, error=f'run status is not executable: {run.status}', retryable=False, owned_attempt=owned_attempt)
|
||||
return
|
||||
|
||||
ctx.logger.info(
|
||||
'shipping_order_extraction_started run_no=%s job_id=%s attempt=%s phase=%s',
|
||||
run.run_no,
|
||||
job.id,
|
||||
owned_attempt,
|
||||
run.phase,
|
||||
)
|
||||
handler_started = time.perf_counter()
|
||||
started = time.perf_counter()
|
||||
try:
|
||||
provider = db.session.get(Agent, int(run.provider_agent_id))
|
||||
if provider is None or not provider.is_active:
|
||||
raise AppError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_NOT_CONFIGURED',
|
||||
message='订单抽取 Provider 不存在或已停用',
|
||||
http_status=409,
|
||||
)
|
||||
if (
|
||||
provider.runtime_provider != 'dify'
|
||||
or provider.dify_app_type != 'workflow'
|
||||
or provider.exposure_mode != 'internal'
|
||||
or not str(provider.dify_app_id or '').strip()
|
||||
or not str(provider.dify_api_key or '').strip()
|
||||
or not str(provider.api_base_url or '').strip()
|
||||
):
|
||||
raise AppError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_CHANGED',
|
||||
message='订单抽取 Provider 配置已不符合 Run 的执行约束',
|
||||
http_status=409,
|
||||
)
|
||||
provider_snapshot = run.provider_snapshot_json if isinstance(run.provider_snapshot_json, dict) else {}
|
||||
if (
|
||||
str(provider.dify_app_id or '') != str(provider_snapshot.get('dify_app_id') or '')
|
||||
or str(provider.api_base_url or '').rstrip('/') != str(provider_snapshot.get('api_base_url') or '').rstrip('/')
|
||||
):
|
||||
raise AppError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_CHANGED',
|
||||
message='订单抽取 Provider 的 Dify 应用或地址已变化,请创建新的 Run',
|
||||
http_status=409,
|
||||
)
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan
|
||||
transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing')
|
||||
from app.services.shipping_notice.order_extraction_plan import ensure_order_extraction_plan, transition_order_extraction_unit
|
||||
|
||||
ensure_order_extraction_plan(run)
|
||||
plan = ensure_order_extraction_plan(run)
|
||||
run.current_job_id = job.id
|
||||
run.attempt_count = owned_attempt
|
||||
db.session.commit()
|
||||
units = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).order_by(ShippingOrderExtractionUnit.position.asc()).all()
|
||||
orders: list[dict] = []
|
||||
|
||||
run_config = run.provider_config_json if isinstance(run.provider_config_json, dict) else {}
|
||||
if bool(run_config.get('auto_create_enabled')):
|
||||
from app.services.shipping_notice.order_extraction_quality_service import require_approved_quality_batch
|
||||
|
||||
require_approved_quality_batch(
|
||||
batch_id=run.quality_batch_id,
|
||||
owner_agent_id=int(run.owner_agent_id),
|
||||
schema_version_id=int(run.schema_version_id),
|
||||
)
|
||||
timeout_seconds = int(run_config.get('timeout_seconds') or 900)
|
||||
saved_provider_result = run.provider_result_json if isinstance(run.provider_result_json, dict) else {}
|
||||
saved_orders = saved_provider_result.get('orders')
|
||||
if isinstance(saved_orders, list) and all(isinstance(item, dict) for item in saved_orders):
|
||||
orders = saved_orders
|
||||
workflow_meta = saved_provider_result.get('workflow')
|
||||
workflow_meta = workflow_meta if isinstance(workflow_meta, dict) else {}
|
||||
else:
|
||||
plan = run.extraction_plan
|
||||
units = (
|
||||
ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id)
|
||||
.order_by(ShippingOrderExtractionUnit.position.asc())
|
||||
.all()
|
||||
)
|
||||
orders = []
|
||||
unit_workflows = []
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
dify_units = []
|
||||
for unit in units:
|
||||
if unit.status == 'succeeded' and isinstance(unit.result_json, dict):
|
||||
unit_orders = unit.result_json.get('orders')
|
||||
if isinstance(unit_orders, list):
|
||||
orders.extend(item for item in unit_orders if isinstance(item, dict))
|
||||
unit_workflows.append(dict(unit.result_json.get('workflow') or {}))
|
||||
continue
|
||||
if unit.status == 'failed':
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
transition_order_extraction_unit(unit, target_status='running')
|
||||
db.session.commit()
|
||||
deterministic_orders = build_deterministic_unit_orders(run, unit=unit)
|
||||
if deterministic_orders is not None:
|
||||
unit_orders = validate_unit_orders(run, unit=unit, orders=deterministic_orders)
|
||||
unit_meta = {'execution_mode': 'deterministic', 'workflow_run_id': None}
|
||||
transition_order_extraction_unit(
|
||||
unit, target_status='succeeded',
|
||||
result={'orders': unit_orders, 'workflow': unit_meta},
|
||||
)
|
||||
db.session.commit()
|
||||
orders.extend(unit_orders)
|
||||
unit_workflows.append(unit_meta)
|
||||
else:
|
||||
dify_units.append(unit)
|
||||
|
||||
config = run.provider_config_json or {}
|
||||
concurrency = int(config.get('unit_concurrency') or 2)
|
||||
unit_max_attempts = int(config.get('unit_max_attempts') or 2)
|
||||
backoff_ms = int(config.get('unit_retry_backoff_ms') or 500)
|
||||
max_model_units = int(config.get('max_model_units') or 20)
|
||||
if len(dify_units) > max_model_units:
|
||||
raise AppError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_MODEL_BUDGET_EXCEEDED',
|
||||
message='订单抽取模型单元数量超过冻结预算', http_status=409,
|
||||
)
|
||||
provider_max_concurrency = int(config.get('provider_max_concurrency') or 4)
|
||||
circuit_failure_threshold = int(config.get('circuit_failure_threshold') or 5)
|
||||
circuit_cooldown_seconds = int(config.get('circuit_cooldown_seconds') or 60)
|
||||
app = current_app._get_current_object()
|
||||
failures: list[tuple[ShippingOrderExtractionUnit, Exception]] = []
|
||||
completed_by_unit: dict[int, dict] = {}
|
||||
with ThreadPoolExecutor(max_workers=min(concurrency, len(dify_units) or 1)) as pool:
|
||||
run_snapshot = {
|
||||
'id': run.id, 'run_no': run.run_no, 'user_id': run.user_id,
|
||||
'schema_version_id': run.schema_version_id,
|
||||
'input_snapshot_hash': run.input_snapshot_hash,
|
||||
'input_snapshot_json': run.input_snapshot_json,
|
||||
'provider_config_json': run.provider_config_json,
|
||||
}
|
||||
provider_snapshot = {
|
||||
'id': provider.id, 'api_base_url': provider.api_base_url,
|
||||
'dify_api_key': provider.dify_api_key,
|
||||
}
|
||||
futures = {
|
||||
pool.submit(
|
||||
_execute_dify_unit_with_retry,
|
||||
app=app, run_snapshot=run_snapshot,
|
||||
unit_snapshot={
|
||||
'id': unit.id, 'intake_id': unit.intake_id,
|
||||
'document_id': unit.document_id, 'document_type': unit.document_type,
|
||||
'unit_type': unit.unit_type,
|
||||
},
|
||||
provider_snapshot=provider_snapshot,
|
||||
timeout_seconds=timeout_seconds, max_attempts=unit_max_attempts,
|
||||
backoff_ms=backoff_ms, job_id=job.id, job_attempt=owned_attempt,
|
||||
provider_max_concurrency=provider_max_concurrency,
|
||||
circuit_failure_threshold=circuit_failure_threshold,
|
||||
circuit_cooldown_seconds=circuit_cooldown_seconds,
|
||||
): unit for unit in dify_units
|
||||
}
|
||||
for future in as_completed(futures):
|
||||
unit = futures[future]
|
||||
try:
|
||||
item = future.result()
|
||||
unit.attempt_count = max(int(unit.attempt_count or 0), int(item['attempts']))
|
||||
meta = {**item['meta'], 'latency_ms': item['latency_ms'], 'attempts': item['attempts']}
|
||||
transition_order_extraction_unit(
|
||||
unit, target_status='succeeded',
|
||||
result={'orders': item['orders'], 'workflow': meta},
|
||||
)
|
||||
completed_by_unit[unit.id] = {'orders': item['orders'], 'meta': meta}
|
||||
except Exception as exc:
|
||||
transition_order_extraction_unit(
|
||||
unit, target_status='failed',
|
||||
error_code=str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'),
|
||||
error_message=str(exc),
|
||||
)
|
||||
failures.append((unit, exc))
|
||||
db.session.commit()
|
||||
if failures and not orders and not completed_by_unit:
|
||||
raise failures[0][1]
|
||||
for unit in dify_units:
|
||||
item = completed_by_unit.get(unit.id)
|
||||
if item is None:
|
||||
# [STEP 1] 每个文档独立路由,单个歧义不得阻断其他 PDF/PO 的确定性结果。
|
||||
for unit in units:
|
||||
if unit.status == 'succeeded' and isinstance(unit.result_json, dict):
|
||||
saved_orders = unit.result_json.get('orders')
|
||||
if isinstance(saved_orders, list):
|
||||
orders.extend(item for item in saved_orders if isinstance(item, dict))
|
||||
continue
|
||||
orders.extend(item['orders'])
|
||||
unit_workflows.append(item['meta'])
|
||||
schema_snapshot = run.input_snapshot_json.get('schema') or {}
|
||||
orders = merge_unit_orders(
|
||||
orders=orders,
|
||||
schema_definition=schema_snapshot.get('definition') or {},
|
||||
)
|
||||
workflow_meta = {
|
||||
'execution_mode': 'unit_parallel',
|
||||
'unit_count': len(units),
|
||||
'unit_concurrency': concurrency,
|
||||
'dify_unit_count': sum(
|
||||
1 for item in unit_workflows if item.get('execution_mode') == 'dify'
|
||||
),
|
||||
'deterministic_unit_count': sum(
|
||||
1 for item in unit_workflows if item.get('execution_mode') == 'deterministic'
|
||||
),
|
||||
'failed_unit_count': len(failures),
|
||||
'workflow_run_ids': [
|
||||
str(item['workflow_run_id']) for item in unit_workflows if item.get('workflow_run_id')
|
||||
],
|
||||
}
|
||||
# Dify 观察器以独立事务更新进度投影,返回后刷新主Session避免旧对象覆盖投影。
|
||||
db.session.refresh(run)
|
||||
run.provider_result_json = {'orders': orders, 'workflow': workflow_meta}
|
||||
from datetime import datetime
|
||||
|
||||
run.provider_completed_at = datetime.utcnow()
|
||||
if workflow_meta.get('workflow_run_ids'):
|
||||
run.dify_workflow_run_id = str(workflow_meta['workflow_run_ids'][-1])[:128]
|
||||
# [STEP 1] Provider 成功即建立独立提交边界,HXOPS 后续落库重试不得再次调用 Dify。
|
||||
if unit.status == 'failed':
|
||||
transition_order_extraction_unit(unit, target_status='pending')
|
||||
if unit.status == 'skipped':
|
||||
continue
|
||||
transition_order_extraction_unit(unit, target_status='running')
|
||||
db.session.commit()
|
||||
ctx.logger.info(
|
||||
'shipping_order_extraction_provider_completed run_no=%s job_id=%s attempt=%s elapsed_ms=%s',
|
||||
run.run_no,
|
||||
job.id,
|
||||
owned_attempt,
|
||||
int((time.perf_counter() - handler_started) * 1000),
|
||||
route_result = route_deterministic_unit(run, unit=unit)
|
||||
_append_route_decision(run=run, unit=unit, job=job, attempt_no=owned_attempt, route_result=route_result)
|
||||
db.session.commit()
|
||||
if route_result.execution_mode != 'deterministic':
|
||||
transition_order_extraction_unit(
|
||||
unit, target_status='skipped',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED',
|
||||
error_message='订单模板路由要求人工处理',
|
||||
)
|
||||
db.session.commit()
|
||||
continue
|
||||
unit_orders = validate_unit_orders(run, unit=unit, orders=route_result.orders)
|
||||
for order in unit_orders:
|
||||
order['_hxops_intake_id'] = int(unit.intake_id)
|
||||
transition_order_extraction_unit(
|
||||
unit, target_status='succeeded',
|
||||
result={'orders': unit_orders, 'execution': {'mode': 'deterministic'}},
|
||||
)
|
||||
db.session.commit()
|
||||
orders.extend(unit_orders)
|
||||
|
||||
schema_snapshot = run.input_snapshot_json.get('schema') or {}
|
||||
orders = merge_unit_orders(orders=orders, schema_definition=schema_snapshot.get('definition') or {})
|
||||
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
|
||||
supplements_by_intake = {
|
||||
int(intake.get('intake_id') or 0): supplement
|
||||
for intake in run.input_snapshot_json.get('intakes') or [] if isinstance(intake, dict)
|
||||
for supplement in intake.get('email_supplements') or [] if isinstance(supplement, dict)
|
||||
}
|
||||
orders = merge_email_supplements(
|
||||
orders=orders,
|
||||
supplements_by_intake=supplements_by_intake,
|
||||
schema_definition=schema_snapshot.get('definition') or {},
|
||||
)
|
||||
execution = {
|
||||
'mode': 'deterministic',
|
||||
'unit_count': len(units),
|
||||
'deterministic_unit_count': sum(1 for unit in units if unit.status == 'succeeded'),
|
||||
'review_required_unit_count': sum(1 for unit in units if unit.status == 'skipped'),
|
||||
'failed_unit_count': sum(1 for unit in units if unit.status == 'failed'),
|
||||
'duration_ms': int((time.perf_counter() - started) * 1000),
|
||||
}
|
||||
run.execution_result_json = {'orders': orders, 'execution': execution}
|
||||
run.extraction_completed_at = datetime.utcnow()
|
||||
db.session.commit()
|
||||
|
||||
# [STEP 2] Candidate 写入与解析执行分离;落库失败可重试,已完成 Unit 不重复解析。
|
||||
mark_order_extraction_persistence_started(run)
|
||||
result = submit_order_extraction_run_result(run=run, orders=orders)
|
||||
|
||||
requires_review = _result_requires_review(units=units, result=result)
|
||||
summary = {
|
||||
'run_no': run.run_no,
|
||||
'batch_no': result.get('batch_no'),
|
||||
'run_no': run.run_no, 'batch_no': result.get('batch_no'),
|
||||
'created_count': int(result.get('created_count') or 0),
|
||||
'opened_existing_count': int(result.get('opened_existing_count') or 0),
|
||||
'pending_count': int(result.get('pending_count') or 0),
|
||||
'non_shipping_count': int(result.get('non_shipping_count') or 0),
|
||||
'workflow': workflow_meta,
|
||||
'failed_unit_count': int(workflow_meta.get('failed_unit_count') or 0),
|
||||
'execution': execution, 'requires_review': requires_review,
|
||||
}
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='result_persisted',
|
||||
phase='result_persisted',
|
||||
result=summary,
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='result_persisted', phase='result_persisted', result=summary)
|
||||
db.session.commit()
|
||||
final_status = 'needs_review' if summary['pending_count'] or summary['failed_unit_count'] else 'completed'
|
||||
final_status = 'needs_review' if requires_review else 'completed'
|
||||
transition_order_extraction_run(run, target_status=final_status, result=summary)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result=summary, message='订单抽取完成', owned_attempt=owned_attempt)
|
||||
ctx.logger.info(
|
||||
'shipping_order_extraction_completed run_no=%s job_id=%s attempt=%s status=%s elapsed_ms=%s',
|
||||
run.run_no,
|
||||
job.id,
|
||||
owned_attempt,
|
||||
final_status,
|
||||
int((time.perf_counter() - handler_started) * 1000),
|
||||
)
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
retryable = not isinstance(exc, AppError) or bool(getattr(exc, 'retryable', False))
|
||||
ctx.logger.warning(
|
||||
'shipping_order_extraction_attempt_failed run_no=%s job_id=%s attempt=%s retryable=%s error_code=%s',
|
||||
str(job.business_ref or ''),
|
||||
job.id,
|
||||
owned_attempt,
|
||||
retryable,
|
||||
str(getattr(exc, 'code', None) or 'UNCLASSIFIED'),
|
||||
)
|
||||
if run is not None and run.status in {'queued', 'running', 'failed'}:
|
||||
running_unit = (
|
||||
ShippingOrderExtractionUnit.query.join(ShippingOrderExtractionPlan)
|
||||
.filter(
|
||||
ShippingOrderExtractionPlan.run_id == run.id,
|
||||
ShippingOrderExtractionUnit.status == 'running',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
running_unit = ShippingOrderExtractionUnit.query.join(ShippingOrderExtractionPlan).filter(
|
||||
ShippingOrderExtractionPlan.run_id == run.id,
|
||||
ShippingOrderExtractionUnit.status == 'running',
|
||||
).first()
|
||||
if running_unit is not None:
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
transition_order_extraction_unit(
|
||||
running_unit,
|
||||
target_status='failed',
|
||||
running_unit, target_status='failed',
|
||||
error_code=str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_UNIT_FAILED'),
|
||||
error_message=str(exc),
|
||||
)
|
||||
@@ -423,17 +241,11 @@ def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='running', phase='failing')
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='failed',
|
||||
run, target_status='failed',
|
||||
error_code=str(getattr(exc, 'code', None) or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED'),
|
||||
error_message=str(exc),
|
||||
)
|
||||
db.session.commit()
|
||||
fail_job(
|
||||
job.id,
|
||||
error=str(exc),
|
||||
retryable=retryable,
|
||||
owned_attempt=owned_attempt,
|
||||
)
|
||||
fail_job(job.id, error=str(exc), retryable=retryable, owned_attempt=owned_attempt)
|
||||
if retryable:
|
||||
raise
|
||||
@@ -63,8 +63,10 @@ from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRunIntake,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionUnit,
|
||||
)
|
||||
from app.models.shipping_audit_event import ShippingAuditEvent
|
||||
from app.models.shipping_order_document_profile import (
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
@@ -75,6 +77,8 @@ from app.models.shipping_document_profile_quality import (
|
||||
ShippingDocumentProfileTestSample,
|
||||
ShippingDocumentProfileTestSuite,
|
||||
)
|
||||
from app.models.shipping_document_profile_auto_freeze import ShippingDocumentProfileAutoFreezeQualification
|
||||
from app.models.shipping_freight_cancellation import ShippingFreightCancellation
|
||||
from app.models.shipping_document_layout import ShippingDocumentLayoutVersion
|
||||
from app.models.shipping_inventory_config import (
|
||||
ShippingInventoryField,
|
||||
@@ -172,9 +176,11 @@ __all__ = [
|
||||
'ShippingOrderExtractionRun',
|
||||
'ShippingOrderExtractionRunIntake',
|
||||
'ShippingOrderExtractionPlan',
|
||||
'ShippingOrderExtractionRouteDecision',
|
||||
'ShippingOrderExtractionUnit',
|
||||
'ShippingOrderExtractionProgressEvent',
|
||||
'ShippingOrderExtractionDiagnosticAudit',
|
||||
'ShippingAuditEvent',
|
||||
'ShippingOrderExtractionQualityBatch',
|
||||
'ShippingOrderExtractionQualityLabel',
|
||||
'ShippingOrderDocumentProfile',
|
||||
@@ -183,6 +189,8 @@ __all__ = [
|
||||
'ShippingDocumentProfileTestSuite',
|
||||
'ShippingDocumentProfileTestSample',
|
||||
'ShippingDocumentProfileTestRun',
|
||||
'ShippingDocumentProfileAutoFreezeQualification',
|
||||
'ShippingFreightCancellation',
|
||||
'ShippingDocumentLayoutVersion',
|
||||
'ShippingCustomer',
|
||||
'ShippingCustomerIdentifier',
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Integer, Index, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
@@ -30,6 +30,9 @@ class Agent(Base):
|
||||
"exposure_mode IN ('workspace', 'internal')",
|
||||
name='ck_agents_exposure_mode',
|
||||
),
|
||||
Index('uq_agents_one_active_shipping_notice', 'agent_code', unique=True,
|
||||
postgresql_where=text("agent_code = 'shipping_notice' AND is_active = true"),
|
||||
sqlite_where=text("agent_code = 'shipping_notice' AND is_active = 1")),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
"""
|
||||
backend/app/models/shipping_audit_event.py
|
||||
|
||||
用途:定义货代领域统一、仅追加的审计事件。
|
||||
依赖:SQLAlchemy Base、货代 Run/Task/Intake 的稳定业务编号。
|
||||
逻辑:各业务服务通过 audit_service 追加事件;事件不依赖可级联删除的业务外键,保留跨生命周期追溯事实。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, Index, Integer, JSON, String, event
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
class ShippingAuditEvent(Base):
|
||||
"""货代领域的不可变审计事件;禁止业务代码更新或删除既有记录。"""
|
||||
|
||||
__tablename__ = 'shipping_audit_events'
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin')",
|
||||
name='ck_shipping_audit_events_actor_type',
|
||||
),
|
||||
Index('ix_shipping_audit_events_aggregate_created', 'aggregate_type', 'aggregate_id', 'created_at'),
|
||||
Index('ix_shipping_audit_events_run_created', 'run_no', 'created_at'),
|
||||
Index('ix_shipping_audit_events_task_created', 'task_no', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
event_type: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
aggregate_type: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
aggregate_id: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
run_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
task_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
intake_no: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system')
|
||||
actor_id: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
request_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
correlation_id: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
reason_code: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
before_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
after_hash: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
metadata_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
|
||||
@event.listens_for(ShippingAuditEvent, 'before_update')
|
||||
def _reject_shipping_audit_update(_mapper, _connection, _target) -> None:
|
||||
"""拒绝 ORM 更新,确保即使未调用审计服务也不能改写历史事件。"""
|
||||
raise ValidationError('Shipping audit event is append-only', code='SHIPPING_NOTICE.AUDIT_IMMUTABLE')
|
||||
|
||||
|
||||
@event.listens_for(ShippingAuditEvent, 'before_delete')
|
||||
def _reject_shipping_audit_delete(_mapper, _connection, _target) -> None:
|
||||
"""拒绝 ORM 删除,避免业务清理或级联关系抹除审计事实。"""
|
||||
raise ValidationError('Shipping audit event is append-only', code='SHIPPING_NOTICE.AUDIT_IMMUTABLE')
|
||||
@@ -0,0 +1,59 @@
|
||||
"""
|
||||
订单模板自动冻结资格的版本化发布凭证。
|
||||
|
||||
用途:把模板可发布状态与自动冻结资格分离,并冻结 Profile、Schema、解析器和质量凭证身份。
|
||||
依赖:订单 Profile、Schema 版本、盲测套件、用户和 SQLAlchemy Base。
|
||||
逻辑:每个已发布模板版本独立持有一条资格记录;首版只能是人工确认,后续自动冻结须显式批准。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingDocumentProfileAutoFreezeQualification(Base):
|
||||
"""模板版本的自动冻结资格;发布、暂停和撤销均保留独立审计身份。"""
|
||||
|
||||
__tablename__ = 'shipping_document_profile_auto_freeze_qualifications'
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
'profile_id', 'profile_version', 'profile_checksum',
|
||||
name='uq_shipping_document_profile_auto_freeze_qualification_version',
|
||||
),
|
||||
CheckConstraint(
|
||||
"status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')",
|
||||
name='ck_shipping_document_profile_auto_freeze_qualification_status',
|
||||
),
|
||||
Index(
|
||||
'ix_shipping_document_profile_auto_freeze_qualification_profile_status',
|
||||
'profile_id', 'status',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
profile_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_document_profiles.id'), nullable=False)
|
||||
profile_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
profile_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
parser_version: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
quality_suite_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_document_profile_test_suites.id'), nullable=True,
|
||||
)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='manual_confirmation', server_default='manual_confirmation',
|
||||
)
|
||||
approved_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
approved_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
suspended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
suspended_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
suspension_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False,
|
||||
)
|
||||
@@ -0,0 +1,34 @@
|
||||
"""货代上传后版本替代的外部撤销审计事实。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import DateTime, ForeignKey, Index, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingFreightCancellation(Base):
|
||||
"""已上传旧任务的撤销申请与货代回执;成功前新版本不得履约。"""
|
||||
|
||||
__tablename__ = 'shipping_freight_cancellations'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('old_task_id', 'new_task_id', name='uq_shipping_freight_cancellations_version_pair'),
|
||||
Index('ix_shipping_freight_cancellations_old_status', 'old_task_id', 'status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
old_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
|
||||
new_task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='cancellation_required')
|
||||
requested_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
requested_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
completed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
freight_receipt_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
receipt_asset_id: Mapped[Optional[int]] = mapped_column(ForeignKey('file_assets.id'), nullable=True)
|
||||
reason: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
failure_reason: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
@@ -59,17 +59,9 @@ class ShippingOrderExtractionRun(Base):
|
||||
run_no: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), nullable=False, index=True)
|
||||
owner_agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), nullable=False, index=True)
|
||||
runtime_binding_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('agent_runtime_bindings.id'), nullable=True, index=True,
|
||||
)
|
||||
provider_agent_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('agents.id'), nullable=True, index=True,
|
||||
)
|
||||
quality_batch_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_quality_batches.id'), nullable=True, index=True,
|
||||
)
|
||||
provider_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
provider_snapshot_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
parser_engine_version: Mapped[str] = mapped_column(String(64), nullable=False, default='deterministic-order-parser.v1')
|
||||
parser_policy_version: Mapped[str] = mapped_column(String(64), nullable=False, default='deterministic-order-policy.v1')
|
||||
auto_freeze_policy_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
# 重新识别创建新 Run;谱系字段保留旧结果,禁止用原地覆盖破坏审计事实。
|
||||
reparse_of_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
@@ -90,9 +82,8 @@ class ShippingOrderExtractionRun(Base):
|
||||
status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued')
|
||||
phase: Mapped[str] = mapped_column(String(64), nullable=False, default='queued', server_default='queued')
|
||||
current_job_id: Mapped[Optional[int]] = mapped_column(ForeignKey('jobs.id'), nullable=True, index=True)
|
||||
dify_workflow_run_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True, index=True)
|
||||
provider_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
provider_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
execution_result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
extraction_completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
attempt_count: Mapped[int] = mapped_column(Integer, default=0, server_default='0', nullable=False)
|
||||
result_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
@@ -130,6 +121,9 @@ class ShippingOrderExtractionRun(Base):
|
||||
extraction_plan: Mapped[Optional['ShippingOrderExtractionPlan']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', uselist=False,
|
||||
)
|
||||
route_decisions: Mapped[list['ShippingOrderExtractionRouteDecision']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderExtractionRouteDecision.id',
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderExtractionRunIntake(Base):
|
||||
@@ -241,6 +235,54 @@ class ShippingOrderExtractionUnit(Base):
|
||||
)
|
||||
|
||||
plan: Mapped['ShippingOrderExtractionPlan'] = relationship(back_populates='units')
|
||||
route_decisions: Mapped[list['ShippingOrderExtractionRouteDecision']] = relationship(
|
||||
back_populates='unit', cascade='all, delete-orphan', order_by='ShippingOrderExtractionRouteDecision.id',
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderExtractionRouteDecision(Base):
|
||||
"""Unit 每次模板分流的不可变脱敏审计;禁止存储文档、字段值和 Provider 输入。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_route_decisions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('unit_id', 'job_id', 'attempt_no', name='uq_shipping_order_extraction_route_decision_attempt'),
|
||||
CheckConstraint(
|
||||
"decision IN ('deterministic', 'review_required', 'skipped')",
|
||||
name='ck_shipping_order_extraction_route_decision',
|
||||
),
|
||||
CheckConstraint(
|
||||
"match_status IN ('unique_match', 'no_match', 'ambiguous', 'layout_drift', 'evidence_insufficient')",
|
||||
name='ck_shipping_order_extraction_route_match_status',
|
||||
),
|
||||
Index('ix_shipping_order_extraction_route_decisions_run_unit', 'run_id', 'unit_id', 'id'),
|
||||
Index('ix_shipping_order_extraction_route_decisions_unit_created', 'unit_id', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False)
|
||||
unit_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_extraction_units.id', ondelete='CASCADE'), nullable=False)
|
||||
job_id: Mapped[int] = mapped_column(ForeignKey('jobs.id'), nullable=False)
|
||||
attempt_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
decision: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
match_status: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
selected_profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_order_document_profiles.id'), nullable=True)
|
||||
selected_profile_code: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
|
||||
selected_profile_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
|
||||
selected_profile_checksum: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
auto_create_approved: Mapped[Optional[bool]] = mapped_column(nullable=True)
|
||||
candidate_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
document_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
business_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
matched_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
parsed_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
approved_table_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
candidate_summary_json: Mapped[list[dict[str, Any]]] = mapped_column(JSON, nullable=False, default=list)
|
||||
fallback_reason_codes_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
run: Mapped['ShippingOrderExtractionRun'] = relationship(back_populates='route_decisions')
|
||||
unit: Mapped['ShippingOrderExtractionUnit'] = relationship(back_populates='route_decisions')
|
||||
|
||||
|
||||
class ShippingOrderExtractionProgressEvent(Base):
|
||||
|
||||
@@ -23,6 +23,7 @@ class ShippingOrderSnapshot(Base):
|
||||
|
||||
__tablename__ = 'shipping_order_snapshots'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('task_id', name='uq_shipping_order_snapshots_task'),
|
||||
UniqueConstraint('extraction_id', name='uq_shipping_order_snapshots_extraction'),
|
||||
Index('ix_shipping_order_snapshots_customer_created', 'customer_id', 'created_at'),
|
||||
)
|
||||
@@ -35,6 +36,8 @@ class ShippingOrderSnapshot(Base):
|
||||
customer_short_code_snapshot: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
order_data_version: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
rule_versions_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
# 冻结时固化字段裁决、文档哈希、页码坐标及人工复核,避免下游回读可变解析事实。
|
||||
source_manifest_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
# 保留所有已发布 Header 字段;核心字段同时写入下方强类型列,扩展字段由业务配置按 field_id 消费。
|
||||
header_values_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""add order extraction route decisions
|
||||
|
||||
Revision ID: 06ef1a2b3c4d
|
||||
Revises: 05df1e2f3a4b
|
||||
Create Date: 2026-07-27 21:10:00.000000
|
||||
|
||||
用途:为订单抽取 Unit 的每一次模板分流保留不可变、脱敏的审计事实。
|
||||
依赖:shipping_order_extraction_runs、shipping_order_extraction_units、jobs、Profile。
|
||||
逻辑:决策在 Worker 分流前追加;重试以 unit/job/attempt 唯一。统一长期审计由后继 shipping_audit_events 保存。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '06ef1a2b3c4d'
|
||||
down_revision = '05df1e2f3a4b'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建 Unit 路由决策审计表及按 Run/Unit 查询的索引。"""
|
||||
op.create_table(
|
||||
'shipping_order_extraction_route_decisions',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('run_id', sa.Integer(), nullable=False),
|
||||
sa.Column('unit_id', sa.Integer(), nullable=False),
|
||||
sa.Column('job_id', sa.Integer(), nullable=False),
|
||||
sa.Column('attempt_no', sa.Integer(), nullable=False),
|
||||
sa.Column('decision', sa.String(length=16), nullable=False),
|
||||
sa.Column('match_status', sa.String(length=32), nullable=False),
|
||||
sa.Column('selected_profile_id', sa.Integer(), nullable=True),
|
||||
sa.Column('selected_profile_code', sa.String(length=128), nullable=True),
|
||||
sa.Column('selected_profile_version', sa.Integer(), nullable=True),
|
||||
sa.Column('selected_profile_checksum', sa.String(length=64), nullable=True),
|
||||
sa.Column('auto_create_approved', sa.Boolean(), nullable=True),
|
||||
sa.Column('candidate_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('table_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('approved_table_count', sa.Integer(), nullable=False, server_default='0'),
|
||||
sa.Column('candidate_summary_json', sa.JSON(), nullable=False),
|
||||
sa.Column('fallback_reason_codes_json', sa.JSON(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"decision IN ('deterministic', 'review_required', 'skipped')",
|
||||
name='ck_shipping_order_extraction_route_decision',
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"match_status IN ('unique_match', 'no_match', 'ambiguous', 'layout_drift', 'evidence_insufficient')",
|
||||
name='ck_shipping_order_extraction_route_match_status',
|
||||
),
|
||||
sa.ForeignKeyConstraint(['job_id'], ['jobs.id']),
|
||||
sa.ForeignKeyConstraint(['run_id'], ['shipping_order_extraction_runs.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['selected_profile_id'], ['shipping_order_document_profiles.id']),
|
||||
sa.ForeignKeyConstraint(['unit_id'], ['shipping_order_extraction_units.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('unit_id', 'job_id', 'attempt_no', name='uq_shipping_order_extraction_route_decision_attempt'),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_extraction_route_decisions_run_unit',
|
||||
'shipping_order_extraction_route_decisions', ['run_id', 'unit_id', 'id'],
|
||||
)
|
||||
op.create_index(
|
||||
'ix_shipping_order_extraction_route_decisions_unit_created',
|
||||
'shipping_order_extraction_route_decisions', ['unit_id', 'created_at'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除路由决策审计表及其索引。"""
|
||||
op.drop_index('ix_shipping_order_extraction_route_decisions_unit_created', table_name='shipping_order_extraction_route_decisions')
|
||||
op.drop_index('ix_shipping_order_extraction_route_decisions_run_unit', table_name='shipping_order_extraction_route_decisions')
|
||||
op.drop_table('shipping_order_extraction_route_decisions')
|
||||
@@ -0,0 +1,58 @@
|
||||
"""add shipping audit events
|
||||
|
||||
Revision ID: 07f01a2b3c4d
|
||||
Revises: 06ef1a2b3c4d
|
||||
Create Date: 2026-07-27 23:15:00.000000
|
||||
|
||||
用途:建立不依赖业务外键的货代统一追加式审计表。
|
||||
依赖:订单抽取 Run/Unit 的稳定业务编号;不级联删除任何审计事实。
|
||||
逻辑:状态变化、模板路由与后续履约动作统一写入该表;仅保存哈希和脱敏元数据。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '07f01a2b3c4d'
|
||||
down_revision = '06ef1a2b3c4d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建统一审计表和按聚合、Run、Task 查询的索引。"""
|
||||
op.create_table(
|
||||
'shipping_audit_events',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('event_type', sa.String(length=64), nullable=False),
|
||||
sa.Column('aggregate_type', sa.String(length=64), nullable=False),
|
||||
sa.Column('aggregate_id', sa.String(length=128), nullable=False),
|
||||
sa.Column('run_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('task_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('intake_no', sa.String(length=64), nullable=True),
|
||||
sa.Column('actor_type', sa.String(length=16), nullable=False, server_default='system'),
|
||||
sa.Column('actor_id', sa.String(length=128), nullable=True),
|
||||
sa.Column('request_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('correlation_id', sa.String(length=64), nullable=True),
|
||||
sa.Column('reason_code', sa.String(length=128), nullable=True),
|
||||
sa.Column('before_hash', sa.String(length=64), nullable=True),
|
||||
sa.Column('after_hash', sa.String(length=64), nullable=True),
|
||||
sa.Column('metadata_json', sa.JSON(), nullable=False),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"actor_type IN ('user', 'system', 'rpa', 'chatflow', 'admin')",
|
||||
name='ck_shipping_audit_events_actor_type',
|
||||
),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
)
|
||||
op.create_index('ix_shipping_audit_events_aggregate_created', 'shipping_audit_events', ['aggregate_type', 'aggregate_id', 'created_at'])
|
||||
op.create_index('ix_shipping_audit_events_run_created', 'shipping_audit_events', ['run_no', 'created_at'])
|
||||
op.create_index('ix_shipping_audit_events_task_created', 'shipping_audit_events', ['task_no', 'created_at'])
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除审计表;仅用于受控回滚,业务运行不得删除已有审计记录。"""
|
||||
op.drop_index('ix_shipping_audit_events_task_created', table_name='shipping_audit_events')
|
||||
op.drop_index('ix_shipping_audit_events_run_created', table_name='shipping_audit_events')
|
||||
op.drop_index('ix_shipping_audit_events_aggregate_created', table_name='shipping_audit_events')
|
||||
op.drop_table('shipping_audit_events')
|
||||
@@ -0,0 +1,70 @@
|
||||
"""remove order extraction provider fields
|
||||
|
||||
Revision ID: 08f12a3b4c5d
|
||||
Revises: 07f01a2b3c4d
|
||||
Create Date: 2026-07-27 23:40:00.000000
|
||||
|
||||
用途:移除订单解析的 Runtime Binding/Provider 持久化依赖,冻结确定性解析版本和结果。
|
||||
依赖:shipping_order_extraction_runs、订单抽取阶段 0 审计契约。
|
||||
逻辑:破坏性迁移不保留历史 Provider 快照;新 Run 不需要 Dify 或内部 Workflow 配置。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '08f12a3b4c5d'
|
||||
down_revision = '07f01a2b3c4d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""替换 Provider 字段为确定性解析器版本、执行结果和人工冻结策略。"""
|
||||
inspector = sa.inspect(op.get_bind())
|
||||
existing_columns = {
|
||||
column['name']
|
||||
for column in inspector.get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
existing_indexes = {
|
||||
index['name']
|
||||
for index in inspector.get_indexes('shipping_order_extraction_runs')
|
||||
}
|
||||
existing_foreign_keys = {
|
||||
foreign_key['name']
|
||||
for foreign_key in inspector.get_foreign_keys('shipping_order_extraction_runs')
|
||||
if foreign_key.get('name')
|
||||
}
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch:
|
||||
for index in ('ix_shipping_order_extraction_runs_runtime_binding_id', 'ix_shipping_order_extraction_runs_provider_agent_id'):
|
||||
if index in existing_indexes:
|
||||
batch.drop_index(index)
|
||||
for constraint in ('fk_shipping_order_extraction_runs_runtime_binding_id', 'fk_shipping_order_extraction_runs_provider_agent_id'):
|
||||
if constraint in existing_foreign_keys:
|
||||
batch.drop_constraint(constraint, type_='foreignkey')
|
||||
for column in (
|
||||
'runtime_binding_id', 'provider_agent_id', 'quality_batch_id', 'provider_config_json',
|
||||
'provider_snapshot_json', 'dify_workflow_run_id', 'provider_result_json', 'provider_completed_at',
|
||||
):
|
||||
if column in existing_columns:
|
||||
batch.drop_column(column)
|
||||
batch.add_column(sa.Column('parser_engine_version', sa.String(length=64), nullable=False, server_default='deterministic-order-parser.v1'))
|
||||
batch.add_column(sa.Column('parser_policy_version', sa.String(length=64), nullable=False, server_default='deterministic-order-policy.v1'))
|
||||
batch.add_column(sa.Column('auto_freeze_policy_json', sa.JSON(), nullable=False, server_default=sa.text("'{}'")))
|
||||
batch.add_column(sa.Column('execution_result_json', sa.JSON(), nullable=True))
|
||||
batch.add_column(sa.Column('extraction_completed_at', sa.DateTime(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""恢复旧列结构,仅用于受控回滚;不会恢复已删除 Provider 内容。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_runs') as batch:
|
||||
for column in ('parser_engine_version', 'parser_policy_version', 'auto_freeze_policy_json', 'execution_result_json', 'extraction_completed_at'):
|
||||
batch.drop_column(column)
|
||||
batch.add_column(sa.Column('runtime_binding_id', sa.Integer(), nullable=True))
|
||||
batch.add_column(sa.Column('provider_agent_id', sa.Integer(), nullable=True))
|
||||
batch.add_column(sa.Column('quality_batch_id', sa.Integer(), nullable=True))
|
||||
batch.add_column(sa.Column('provider_config_json', sa.JSON(), nullable=True))
|
||||
batch.add_column(sa.Column('provider_snapshot_json', sa.JSON(), nullable=True))
|
||||
batch.add_column(sa.Column('dify_workflow_run_id', sa.String(length=128), nullable=True))
|
||||
batch.add_column(sa.Column('provider_result_json', sa.JSON(), nullable=True))
|
||||
batch.add_column(sa.Column('provider_completed_at', sa.DateTime(), nullable=True))
|
||||
@@ -0,0 +1,33 @@
|
||||
"""add order route table counters
|
||||
|
||||
Revision ID: 09a23b4c5d6e
|
||||
Revises: 08f12a3b4c5d
|
||||
Create Date: 2026-07-27 23:55:00.000000
|
||||
|
||||
用途:细分订单模板路由的文档、业务、匹配与解析表计数。
|
||||
依赖:shipping_order_extraction_route_decisions 阶段 0 路由审计表。
|
||||
逻辑:只保存计数,不保存订单值、正文或坐标载荷。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '09a23b4c5d6e'
|
||||
down_revision = '08f12a3b4c5d'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为 Route Decision 增加四类不可逆业务计数。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_route_decisions') as batch:
|
||||
for column in ('document_table_count', 'business_table_count', 'matched_table_count', 'parsed_table_count'):
|
||||
batch.add_column(sa.Column(column, sa.Integer(), nullable=False, server_default='0'))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回退阶段 3 路由计数列。"""
|
||||
with op.batch_alter_table('shipping_order_extraction_route_decisions') as batch:
|
||||
for column in ('parsed_table_count', 'matched_table_count', 'business_table_count', 'document_table_count'):
|
||||
batch.drop_column(column)
|
||||
@@ -0,0 +1,53 @@
|
||||
"""add independent order profile auto-freeze qualifications
|
||||
|
||||
Revision ID: 0aa34b5c6d7e
|
||||
Revises: 09a23b4c5d6e
|
||||
Create Date: 2026-07-28 00:20:00.000000
|
||||
|
||||
用途:将订单模板发布生命周期与自动冻结资格分离。
|
||||
依赖:订单 Profile、Schema、盲测套件和用户表。
|
||||
逻辑:资格按 Profile 版本/checksum 冻结,首版仅写 manual_confirmation,不会反向打开自动建单。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '0aa34b5c6d7e'
|
||||
down_revision = '09a23b4c5d6e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""创建模板版本级自动冻结资格表。"""
|
||||
op.create_table(
|
||||
'shipping_document_profile_auto_freeze_qualifications',
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('profile_id', sa.Integer(), sa.ForeignKey('shipping_order_document_profiles.id'), nullable=False),
|
||||
sa.Column('profile_version', sa.Integer(), nullable=False),
|
||||
sa.Column('profile_checksum', sa.String(64), nullable=False),
|
||||
sa.Column('schema_version_id', sa.Integer(), sa.ForeignKey('shipping_order_schema_versions.id'), nullable=False),
|
||||
sa.Column('parser_version', sa.String(64), nullable=False),
|
||||
sa.Column('quality_suite_id', sa.Integer(), sa.ForeignKey('shipping_document_profile_test_suites.id'), nullable=True),
|
||||
sa.Column('status', sa.String(32), nullable=False, server_default='manual_confirmation'),
|
||||
sa.Column('approved_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||
sa.Column('approved_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('suspended_by_id', sa.Integer(), sa.ForeignKey('users.id'), nullable=True),
|
||||
sa.Column('suspended_at', sa.DateTime(), nullable=True),
|
||||
sa.Column('suspension_reason', sa.Text(), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(), nullable=False),
|
||||
sa.UniqueConstraint('profile_id', 'profile_version', 'profile_checksum', name='uq_shipping_document_profile_auto_freeze_qualification_version'),
|
||||
sa.CheckConstraint("status IN ('manual_confirmation', 'auto_freeze_approved', 'auto_freeze_suspended')", name='ck_shipping_document_profile_auto_freeze_qualification_status'),
|
||||
)
|
||||
op.create_index(
|
||||
'ix_ship_doc_prof_auto_freeze_profile_status',
|
||||
'shipping_document_profile_auto_freeze_qualifications', ['profile_id', 'status'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""删除独立资格表,不修改模板发布记录。"""
|
||||
op.drop_index('ix_ship_doc_prof_auto_freeze_profile_status', table_name='shipping_document_profile_auto_freeze_qualifications')
|
||||
op.drop_table('shipping_document_profile_auto_freeze_qualifications')
|
||||
@@ -0,0 +1,33 @@
|
||||
"""add snapshot task uniqueness and freeze source manifest
|
||||
|
||||
Revision ID: 1bb45c6d7e8f
|
||||
Revises: 0aa34b5c6d7e
|
||||
Create Date: 2026-07-28 00:30:00.000000
|
||||
|
||||
用途:冻结并发时保证一个 Task 只有一个 Snapshot,并固化冻结字段来源清单。
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '1bb45c6d7e8f'
|
||||
down_revision = '0aa34b5c6d7e'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
"""为冻结快照增加并发唯一约束和来源 JSON。"""
|
||||
with op.batch_alter_table('shipping_order_snapshots') as batch_op:
|
||||
batch_op.add_column(sa.Column('source_manifest_json', sa.JSON(), nullable=False, server_default=sa.text("'{}'")))
|
||||
batch_op.create_unique_constraint('uq_shipping_order_snapshots_task', ['task_id'])
|
||||
with op.batch_alter_table('shipping_order_snapshots') as batch_op:
|
||||
batch_op.alter_column('source_manifest_json', server_default=None)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
"""回滚阶段六快照字段与任务唯一约束。"""
|
||||
with op.batch_alter_table('shipping_order_snapshots') as batch_op:
|
||||
batch_op.drop_constraint('uq_shipping_order_snapshots_task', type_='unique')
|
||||
batch_op.drop_column('source_manifest_json')
|
||||
@@ -0,0 +1,21 @@
|
||||
"""add freight cancellation records for task supersession
|
||||
|
||||
Revision ID: 2cc56d7e8f9a
|
||||
Revises: 1bb45c6d7e8f
|
||||
Create Date: 2026-07-28 00:40:00.000000
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = '2cc56d7e8f9a'
|
||||
down_revision = '1bb45c6d7e8f'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table('shipping_freight_cancellations', sa.Column('id', sa.Integer(), primary_key=True), sa.Column('old_task_id', sa.Integer(), sa.ForeignKey('shipping_tasks.id'), nullable=False), sa.Column('new_task_id', sa.Integer(), sa.ForeignKey('shipping_tasks.id'), nullable=False), sa.Column('status', sa.String(32), nullable=False), sa.Column('requested_by_id', sa.Integer(), sa.ForeignKey('users.id')), sa.Column('requested_at', sa.DateTime(), nullable=False), sa.Column('completed_by_id', sa.Integer(), sa.ForeignKey('users.id')), sa.Column('completed_at', sa.DateTime()), sa.Column('freight_receipt_no', sa.String(128)), sa.Column('receipt_asset_id', sa.Integer(), sa.ForeignKey('file_assets.id')), sa.Column('reason', sa.Text(), nullable=False), sa.Column('failure_reason', sa.Text()), sa.UniqueConstraint('old_task_id', 'new_task_id', name='uq_shipping_freight_cancellations_version_pair'))
|
||||
op.create_index('ix_shipping_freight_cancellations_old_status', 'shipping_freight_cancellations', ['old_task_id', 'status'])
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index('ix_shipping_freight_cancellations_old_status', table_name='shipping_freight_cancellations')
|
||||
op.drop_table('shipping_freight_cancellations')
|
||||
@@ -0,0 +1,18 @@
|
||||
"""enforce one active shipping notice chatflow
|
||||
|
||||
Revision ID: 3dd67e8f9a0b
|
||||
Revises: 2cc56d7e8f9a
|
||||
Create Date: 2026-07-28 01:00:00.000000
|
||||
"""
|
||||
from alembic import op
|
||||
|
||||
revision = '3dd67e8f9a0b'
|
||||
down_revision = '2cc56d7e8f9a'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_index('uq_agents_one_active_shipping_notice', 'agents', ['agent_code'], unique=True, postgresql_where="agent_code = 'shipping_notice' AND is_active = true", sqlite_where="agent_code = 'shipping_notice' AND is_active = 1")
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index('uq_agents_one_active_shipping_notice', table_name='agents')
|
||||
@@ -21,6 +21,7 @@ from app.models import (
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingTaskFieldConflict,
|
||||
ShippingFulfillmentPolicy,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
@@ -154,6 +155,9 @@ def test_freeze_creates_strong_snapshot_and_preserves_identifiers(app):
|
||||
assert snapshot.lines[0].part_number == '000123'
|
||||
assert snapshot.lines[0].reservation_id == '0012345678'
|
||||
assert snapshot.lines[0].qty == Decimal('12.50000000')
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
assert extraction is not None
|
||||
assert snapshot.source_manifest_json['schema_version_id'] == extraction.schema_version_id
|
||||
|
||||
|
||||
def test_freeze_rejects_unverified_llm_critical_field(app):
|
||||
@@ -252,3 +256,35 @@ def test_freeze_rejects_unconfirmed_or_caller_supplied_customer(app):
|
||||
with pytest.raises(ValidationError) as error:
|
||||
freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
assert error.value.code == 'SHIPPING.ORDER_CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
|
||||
|
||||
def test_freeze_rejects_open_conflict_and_missing_fulfillment_value(app):
|
||||
"""关键断言:开放冲突、缺失料号/预约号/正数数量均不能形成不可编辑快照。"""
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order(suffix='freeze-gates')
|
||||
db.session.add(ShippingTaskFieldConflict(
|
||||
task_id=task.id, field_name='part_number', position=0, status='open', conflict_version=1,
|
||||
existing_value='000123', incoming_value='999999',
|
||||
))
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError) as conflict_error:
|
||||
freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
assert conflict_error.value.code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
|
||||
ShippingTaskFieldConflict.query.filter_by(task_id=task.id).update({'status': 'resolved'})
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
part_field = next(item for item in extraction.schema_version.definition_json['fields'] if item['field_code'] == 'part_number')
|
||||
ShippingOrderFieldValue.query.filter_by(extraction_id=extraction.id, field_id=part_field['field_id']).delete()
|
||||
with pytest.raises(ValidationError) as missing_error:
|
||||
freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
assert missing_error.value.code == 'SHIPPING.ORDER_FREEZE_BLOCKED'
|
||||
|
||||
|
||||
def test_freeze_is_idempotent_for_repeated_confirmation(app):
|
||||
"""关键断言:用户重复确认冻结只返回同一 Snapshot,不产生第二份履约事实。"""
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order(suffix='freeze-idempotent')
|
||||
first = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
db.session.commit()
|
||||
second = freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
assert second.id == first.id
|
||||
@@ -31,7 +31,7 @@ from app.jobs.queue import claim_next_job, recover_stale_jobs
|
||||
from app.jobs.types import JobType
|
||||
from app.models import (
|
||||
Agent, AgentRuntimeBinding, Job, ShippingNoticeCandidate, ShippingNoticeDocument,
|
||||
ShippingOrderDocumentProfile, ShippingOrderExtraction, ShippingOrderExtractionRun,
|
||||
ShippingOrderDocumentProfile, ShippingOrderExtraction, ShippingOrderExtractionRouteDecision, ShippingOrderExtractionRun,
|
||||
ShippingOrderSchemaVersion, User,
|
||||
)
|
||||
from app.services.agent_runtime_binding_service import resolve_runtime_binding, save_runtime_binding
|
||||
@@ -1065,6 +1065,11 @@ def test_profile_template_candidate_uses_provider_after_l7_cleanup(app):
|
||||
run_shipping_order_extraction(JobContext(config={}, logger=app.logger), {'job_id': job.id})
|
||||
|
||||
execute.assert_called_once()
|
||||
route_decision = ShippingOrderExtractionRouteDecision.query.filter_by(unit_id=run.extraction_plan.units[0].id).one()
|
||||
# 关键断言:即使 Provider 成功或失败,进入 Dify 前的匹配与审批事实已经独立持久化。
|
||||
assert route_decision.decision == 'dify'
|
||||
assert route_decision.match_status == 'unique_match'
|
||||
assert route_decision.fallback_reason_codes_json == ['profile_not_auto_create_approved']
|
||||
manifest = json.loads(execute.call_args.kwargs['run'].input_snapshot_json and build_order_extraction_workflow_inputs(
|
||||
run, unit=run.extraction_plan.units[0],
|
||||
)['execution_manifest'])
|
||||
|
||||
@@ -15,7 +15,6 @@ from app.api.chat import (
|
||||
|
||||
def test_normalize_user_attachments_keeps_only_display_whitelist():
|
||||
items = [{
|
||||
'id': 'attachment-1',
|
||||
'name': 'C:\\temp\\purchase-order.pdf\x00',
|
||||
'size': '144456',
|
||||
'extension': 'PDF',
|
||||
@@ -27,7 +26,6 @@ def test_normalize_user_attachments_keeps_only_display_whitelist():
|
||||
}]
|
||||
|
||||
assert _normalize_user_attachments(items) == [{
|
||||
'id': 'attachment-1',
|
||||
'name': 'purchase-order.pdf',
|
||||
'size': 144456,
|
||||
'extension': 'pdf',
|
||||
@@ -38,7 +36,6 @@ def test_normalize_user_attachments_keeps_only_display_whitelist():
|
||||
|
||||
def test_normalize_user_attachments_limits_items_and_drops_invalid_values():
|
||||
valid = {
|
||||
'id': 'attachment-1',
|
||||
'name': 'file.pdf',
|
||||
'size': 1,
|
||||
'extension': 'pdf',
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""验证 EML 正文补充表的确定性解析、关联和数量保护。
|
||||
|
||||
依赖:正文补充解析器与合并服务。
|
||||
逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威,歧义稳定进入复核。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.email_allocation_table_parser import parse_email_allocation_tables
|
||||
from app.services.shipping_notice.order_supplement_merge import merge_email_supplements
|
||||
|
||||
|
||||
SCHEMA = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number'},
|
||||
{'field_id': 'part', 'field_code': 'part_number'},
|
||||
{'field_id': 'qty', 'field_code': 'qty'},
|
||||
{'field_id': 'reservation', 'field_code': 'reservation_id'},
|
||||
{'field_id': 'allocation', 'field_code': 'allocation_id'},
|
||||
{'field_id': 'source', 'field_code': 'inventory_source_hint'},
|
||||
]}
|
||||
|
||||
|
||||
def _order() -> dict:
|
||||
return {
|
||||
'_hxops_intake_id': 1,
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': '4518738152'}]}],
|
||||
'lines': [{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000002'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 30}]},
|
||||
]}],
|
||||
'conflicts': [],
|
||||
}
|
||||
|
||||
|
||||
def _value(fields: list[dict], field_id: str):
|
||||
"""读取测试订单中唯一字段值,断言前由调用方确保该字段存在。"""
|
||||
field = next(item for item in fields if item['field_id'] == field_id)
|
||||
return field['observations'][0]['value']
|
||||
|
||||
|
||||
def test_email_supplement_html_grid_merges_by_po_and_mpn_without_overwriting_pdf_qty():
|
||||
"""正文表可补齐 Reservation/来源,PDF 的数量不被 allocated qty 覆盖。"""
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='a' * 64,
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>Reservation ID</th><th>Source Type</th><th>Allocated Qty</th></tr><tr><td>4518738152</td><td>D4-A08AR12000002</td><td>2000484577</td><td>DSB CMH</td><td>99</td></tr></table>'''],
|
||||
)
|
||||
supplement['document_id'] = 44
|
||||
assert supplement['rows'][0]['evidence']['reservation_id'] == {
|
||||
'table_index': 0, 'row_index': 1, 'column_index': 2,
|
||||
'cell_id': f"email-supplement:{'a' * 64}:0:r1:c2", 'raw_value': '2000484577',
|
||||
}
|
||||
merged = merge_email_supplements(
|
||||
orders=[_order()], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)
|
||||
fields = merged[0]['lines'][0]['fields']
|
||||
assert _value(fields, 'reservation') == '2000484577'
|
||||
assert _value(fields, 'source') == 'DSB CMH'
|
||||
assert _value(fields, 'qty') == 30
|
||||
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
def test_email_supplement_po_fallback_requires_one_reservation():
|
||||
"""缺 MPN 时只有唯一 Reservation 的 PO 可广播;多 Reservation 必须复核。"""
|
||||
one = {'document_id': 44, 'rows': [{'po_number': '4518738152', 'reservation_id': '2000484577', 'evidence': {}}]}
|
||||
assert merge_email_supplements(orders=[_order()], supplements_by_intake={1: one}, schema_definition=SCHEMA)[0]['_hxops_email_supplement_relation'] == 'po_fallback'
|
||||
ambiguous = {'document_id': 44, 'rows': [
|
||||
{'po_number': '4518738152', 'reservation_id': '2000484577', 'evidence': {}},
|
||||
{'po_number': '4518738152', 'reservation_id': '2000484578', 'evidence': {}},
|
||||
]}
|
||||
result = merge_email_supplements(orders=[_order()], supplements_by_intake={1: ambiguous}, schema_definition=SCHEMA)[0]
|
||||
assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in result['conflicts'])
|
||||
@@ -38,12 +38,10 @@ def test_shipping_notice_snapshot_matches_builder_output():
|
||||
generated = build_dify_openapi_spec(DEFAULT_BASE_URL)
|
||||
|
||||
assert snapshot == generated
|
||||
assert snapshot["paths"]["/tools/submit_decision"]["post"]["operationId"] == "submit_decision"
|
||||
assert snapshot["paths"]["/tools/get_task_status"]["post"]["operationId"] == "get_task_status"
|
||||
snapshot_text = json.dumps(snapshot, ensure_ascii=False)
|
||||
assert "reference_context" in snapshot_text
|
||||
assert "状态机" in snapshot_text
|
||||
assert "唯一 task_id" in snapshot_text
|
||||
assert "不得自行宣布完成" in snapshot_text
|
||||
assert "只读解释" in snapshot_text
|
||||
assert "/tools/submit_decision" not in snapshot["paths"]
|
||||
|
||||
|
||||
def test_agent_runtime_context_snapshot_matches_builder_output():
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""验证订单抽取去 Provider 迁移的字段替换和受控回退。
|
||||
|
||||
依赖:Alembic Operations、SQLite 内存数据库和 08f12a3b4c5d 迁移。
|
||||
逻辑:建立迁移前最小 Run 表,执行升级/回退并断言旧 Provider 字段不会残留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_extraction_deterministic_migration_replaces_provider_columns():
|
||||
"""升级后只保留确定性解析字段;回退仅恢复结构,不能恢复已删除数据。"""
|
||||
migration = importlib.import_module(
|
||||
'migrations.versions.08f12a3b4c5d_remove_order_extraction_provider_fields'
|
||||
)
|
||||
engine = sa.create_engine('sqlite://')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'shipping_order_extraction_runs',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer, primary_key=True),
|
||||
sa.Column('runtime_binding_id', sa.Integer),
|
||||
sa.Column('provider_agent_id', sa.Integer),
|
||||
sa.Column('quality_batch_id', sa.Integer),
|
||||
sa.Column('provider_config_json', sa.JSON),
|
||||
sa.Column('provider_snapshot_json', sa.JSON),
|
||||
sa.Column('dify_workflow_run_id', sa.String(length=128)),
|
||||
sa.Column('provider_result_json', sa.JSON),
|
||||
sa.Column('provider_completed_at', sa.DateTime),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
migration.upgrade()
|
||||
columns = {
|
||||
column['name']
|
||||
for column in sa.inspect(connection).get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
assert {
|
||||
'parser_engine_version', 'parser_policy_version', 'auto_freeze_policy_json',
|
||||
'execution_result_json', 'extraction_completed_at',
|
||||
} <= columns
|
||||
assert not {
|
||||
'runtime_binding_id', 'provider_agent_id', 'quality_batch_id', 'provider_config_json',
|
||||
'provider_snapshot_json', 'dify_workflow_run_id', 'provider_result_json',
|
||||
'provider_completed_at',
|
||||
} & columns
|
||||
|
||||
migration.downgrade()
|
||||
rollback_columns = {
|
||||
column['name']
|
||||
for column in sa.inspect(connection).get_columns('shipping_order_extraction_runs')
|
||||
}
|
||||
assert 'parser_engine_version' not in rollback_columns
|
||||
assert {'runtime_binding_id', 'provider_agent_id', 'provider_result_json'} <= rollback_columns
|
||||
@@ -0,0 +1,50 @@
|
||||
"""验证已批准 PDF 模板的多 PO 拆分与严格拒识边界。
|
||||
|
||||
依赖:确定性 Profile 订单构建器。
|
||||
逻辑:只有每行携带唯一 PO 证据时拆分;文档级多 PO 绝不猜测行归属。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app.services.shipping_notice.order_extraction_workflow import _build_approved_profile_order_result
|
||||
|
||||
|
||||
SCHEMA = {'schema_version_id': 1, 'checksum': 'schema'}
|
||||
DEFINITION = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number', 'scope': 'header', 'required': True},
|
||||
{'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'required': True},
|
||||
{'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'required': True},
|
||||
]}
|
||||
|
||||
|
||||
def _row(po: str, part: str) -> dict:
|
||||
return {'status': 'parsed', 'issues': [], 'fields': [
|
||||
{'field_id': 'po', 'value': po, 'quote': po},
|
||||
{'field_id': 'part', 'value': part, 'quote': part},
|
||||
{'field_id': 'qty', 'value': 1, 'quote': '1'},
|
||||
]}
|
||||
|
||||
|
||||
def test_approved_pdf_splits_explicit_line_pos_into_independent_orders():
|
||||
"""同一 PDF 的两条明细各有 PO 时,必须生成两份独立订单。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=DEFINITION, table={'rows': [_row('PO-1', 'P-1'), _row('PO-2', 'P-2')]},
|
||||
)
|
||||
assert reason is None
|
||||
assert len(orders or []) == 2
|
||||
assert [item['header_fields'][0]['observations'][0]['value'] for item in orders or []] == ['PO-1', 'PO-2']
|
||||
|
||||
|
||||
def test_approved_pdf_keeps_one_order_when_only_one_po_is_proven():
|
||||
"""未证明第二个 PO 时不得臆造拆分,保守保留为同一订单。"""
|
||||
missing = _row('PO-2', 'P-2')
|
||||
missing['fields'] = [item for item in missing['fields'] if item['field_id'] != 'po']
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=DEFINITION, table={'rows': [_row('PO-1', 'P-1'), missing]},
|
||||
)
|
||||
assert reason is None
|
||||
assert len(orders or []) == 1
|
||||
@@ -0,0 +1,26 @@
|
||||
"""验证阶段 3 路由表计数迁移的升级与回退契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_order_route_table_counter_migration_contract():
|
||||
"""四类表计数必须可建、可查且能受控回退。"""
|
||||
migration = importlib.import_module('migrations.versions.09a23b4c5d6e_add_order_route_table_counters')
|
||||
engine = sa.create_engine('sqlite://')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('shipping_order_extraction_route_decisions', metadata, sa.Column('id', sa.Integer, primary_key=True))
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
migration.upgrade()
|
||||
columns = {item['name'] for item in sa.inspect(connection).get_columns('shipping_order_extraction_route_decisions')}
|
||||
assert {'document_table_count', 'business_table_count', 'matched_table_count', 'parsed_table_count'} <= columns
|
||||
migration.downgrade()
|
||||
columns = {item['name'] for item in sa.inspect(connection).get_columns('shipping_order_extraction_route_decisions')}
|
||||
assert 'document_table_count' not in columns
|
||||
@@ -0,0 +1,26 @@
|
||||
"""验证阶段 4 模板自动冻结资格迁移的升级与回退契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_profile_auto_freeze_qualification_migration_contract():
|
||||
"""资格必须按模板版本冻结,且迁移可受控回退。"""
|
||||
migration = importlib.import_module('migrations.versions.0aa34b5c6d7e_add_profile_auto_freeze_qualifications')
|
||||
engine = sa.create_engine('sqlite://')
|
||||
metadata = sa.MetaData()
|
||||
for name in ('shipping_order_document_profiles', 'shipping_order_schema_versions', 'shipping_document_profile_test_suites', 'users'):
|
||||
sa.Table(name, metadata, sa.Column('id', sa.Integer, primary_key=True))
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
migration.upgrade()
|
||||
columns = {item['name'] for item in sa.inspect(connection).get_columns('shipping_document_profile_auto_freeze_qualifications')}
|
||||
assert {'profile_id', 'profile_version', 'profile_checksum', 'schema_version_id', 'parser_version', 'status'} <= columns
|
||||
migration.downgrade()
|
||||
assert 'shipping_document_profile_auto_freeze_qualifications' not in sa.inspect(connection).get_table_names()
|
||||
@@ -0,0 +1,52 @@
|
||||
"""验证货代统一审计事件的脱敏和 append-only 契约。
|
||||
|
||||
依赖:ShippingAuditEvent、audit_service、SQLAlchemy 内存会话。
|
||||
逻辑:审计写入只保存状态哈希和受控元数据;更新、删除或敏感内容均必须被拒绝。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.audit_service import append_shipping_audit_event
|
||||
|
||||
|
||||
def test_append_shipping_audit_event_hashes_state_and_rejects_sensitive_metadata(app):
|
||||
"""状态审计仅保存前后哈希,正文或凭据类元数据必须在入库前拒绝。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(
|
||||
event_type='order_extraction_run_status_changed', aggregate_type='order_extraction_run',
|
||||
aggregate_id='SNER-1', run_no='SNER-1', before={'status': 'queued'},
|
||||
after={'status': 'running'}, metadata={'target_status': 'running'},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:可追溯性来自哈希而不是把订单、邮件正文写进审计表。
|
||||
assert event.before_hash and event.after_hash
|
||||
assert event.metadata_json == {'target_status': 'running'}
|
||||
with pytest.raises(ValidationError, match='forbidden'):
|
||||
append_shipping_audit_event(
|
||||
event_type='invalid', aggregate_type='run', aggregate_id='1', metadata={'email_body': 'secret'},
|
||||
)
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_shipping_audit_event_rejects_orm_update_and_delete(app):
|
||||
"""已经提交的统一审计事件必须拒绝更新和删除,避免业务清理破坏追溯事实。"""
|
||||
with app.app_context():
|
||||
event = append_shipping_audit_event(event_type='created', aggregate_type='run', aggregate_id='SNER-2')
|
||||
db.session.commit()
|
||||
|
||||
event.reason_code = 'changed'
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
persisted = db.session.get(ShippingAuditEvent, event.id)
|
||||
db.session.delete(persisted)
|
||||
with pytest.raises(ValidationError, match='append-only'):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
@@ -0,0 +1,34 @@
|
||||
"""验证货代统一审计迁移的建表、索引与回退契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_shipping_audit_event_migration_contract():
|
||||
"""迁移必须具备所需追溯字段、actor 枚举约束及查询索引。"""
|
||||
migration = importlib.import_module('migrations.versions.07f01a2b3c4d_add_shipping_audit_events')
|
||||
engine = sa.create_engine('sqlite://')
|
||||
with engine.begin() as connection:
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
columns = {item['name'] for item in inspector.get_columns('shipping_audit_events')}
|
||||
indexes = {item['name'] for item in inspector.get_indexes('shipping_audit_events')}
|
||||
checks = {item['name'] for item in inspector.get_check_constraints('shipping_audit_events')}
|
||||
assert {
|
||||
'event_type', 'aggregate_type', 'aggregate_id', 'run_no', 'task_no', 'intake_no',
|
||||
'actor_type', 'actor_id', 'request_id', 'correlation_id', 'reason_code',
|
||||
'before_hash', 'after_hash', 'metadata_json', 'created_at',
|
||||
} <= columns
|
||||
assert 'ck_shipping_audit_events_actor_type' in checks
|
||||
assert {
|
||||
'ix_shipping_audit_events_aggregate_created', 'ix_shipping_audit_events_run_created',
|
||||
'ix_shipping_audit_events_task_created',
|
||||
} <= indexes
|
||||
migration.downgrade()
|
||||
assert 'shipping_audit_events' not in sa.inspect(connection).get_table_names()
|
||||
@@ -0,0 +1,38 @@
|
||||
"""阶段九 Chatflow 只读能力令牌与唯一应用约束。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ForbiddenError
|
||||
from app.models import Agent, ChatSession, ShippingTask, User
|
||||
from app.services.shipping_notice.chat_tool_capability import issue_chat_capability, require_chat_capability
|
||||
|
||||
|
||||
def test_chat_capability_rejects_cross_task_and_expired_scope(app):
|
||||
"""关键断言:令牌不能读取他人任务,且 scope/对象必须与本轮上下文完全一致。"""
|
||||
with app.app_context():
|
||||
user = User(username='cap-user', email='cap-user@example.test', password_hash='x')
|
||||
agent = Agent(name='cap-agent', agent_code='shipping_notice', is_active=True)
|
||||
db.session.add_all([user, agent]); db.session.flush()
|
||||
session = ChatSession(session_id='cap-session', user_id=user.id, agent_id=agent.id)
|
||||
own = ShippingTask(task_no='SN-CAP-OWN', user_id=user.id, source_type='test')
|
||||
other = ShippingTask(task_no='SN-CAP-OTHER', source_type='test')
|
||||
db.session.add_all([session, own, other]); db.session.commit()
|
||||
token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no, batch_no=None)
|
||||
assert require_chat_capability(token=token, scope='get_shipping_status', task_no=own.task_no)['uid'] == user.id
|
||||
with pytest.raises(ForbiddenError):
|
||||
require_chat_capability(token=token, scope='get_shipping_status', task_no=other.task_no)
|
||||
|
||||
|
||||
def test_second_active_shipping_chatflow_is_rejected(app):
|
||||
"""关键断言:数据库部分唯一索引阻止第二个启用的 shipping_notice Chatflow。"""
|
||||
with app.app_context():
|
||||
db.session.add(Agent(name='shipping-one', agent_code='shipping_notice', is_active=True))
|
||||
db.session.commit()
|
||||
db.session.add(Agent(name='shipping-two', agent_code='shipping_notice', is_active=True))
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
@@ -111,8 +111,33 @@ def _published_profile_with_samples() -> tuple[ShippingOrderDocumentProfile, Use
|
||||
return profile, user, documents
|
||||
|
||||
|
||||
def test_profile_auto_create_requires_one_passing_blind_sample_and_approval(app):
|
||||
"""关键断言:一份独立样本通过并经批准后才能放行,批准后样本不可篡改。"""
|
||||
def _publishable_v2_draft(profile: ShippingOrderDocumentProfile) -> None:
|
||||
"""将质量夹具改为最小 v2 草稿,使发布测试只覆盖阶段 4 边界。"""
|
||||
profile.status = 'draft'
|
||||
profile.checksum = None
|
||||
profile.published_at = None
|
||||
profile.definition_json = {
|
||||
'contract_version': 'order_coordinate_profile.v2',
|
||||
'document_match': {'required_anchors': []},
|
||||
'table_regions': [{
|
||||
'region_id': 'lines', 'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'header_layouts': [], 'termination_rules': [], 'exclusion_regions': [],
|
||||
'continuation_rule': {'allow_cross_page': False, 'required_anchor_ids': []},
|
||||
'line_layouts': [{
|
||||
'layout_id': 'main', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': 0, 'x1': 1, 'y1': 1},
|
||||
'field_regions': [
|
||||
{'field_id': 'part-id', 'field_code': 'part_number', 'region': {'x0': 0, 'y0': 0, 'x1': .6, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
{'field_id': 'qty-id', 'field_code': 'qty', 'region': {'x0': .6, 'y0': 0, 'x1': 1, 'y1': 1}, 'allowed_sources': ['pdf_coordinate']},
|
||||
],
|
||||
'continuation_conditions': [], 'required_fields': ['part_number', 'qty'], 'allowed_empty_fields': [],
|
||||
}],
|
||||
}],
|
||||
}
|
||||
|
||||
|
||||
def test_profile_blind_test_approval_does_not_enable_auto_freeze(app):
|
||||
"""关键断言:盲测批准与自动冻结资格独立,首版仍只能人工确认。"""
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
@@ -131,7 +156,7 @@ def test_profile_auto_create_requires_one_passing_blind_sample_and_approval(app)
|
||||
assert executed['latest_run']['status'] == 'passed'
|
||||
approved = quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert approved['status'] == 'approved'
|
||||
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
with pytest.raises(Exception) as immutable:
|
||||
quality.add_sample(
|
||||
suite_id=suite['id'], document_id=documents[0].id, table_id='other',
|
||||
@@ -266,6 +291,23 @@ def test_profile_checksum_change_invalidates_approved_quality_credential(app):
|
||||
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.checksum)
|
||||
|
||||
|
||||
def test_profile_auto_freeze_qualification_can_be_suspended_independently(app):
|
||||
"""关键断言:暂停资格不退役模板,且只影响当前版本。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
with app.app_context():
|
||||
profile, user, _documents = _published_profile_with_samples()
|
||||
_publishable_v2_draft(profile)
|
||||
db.session.commit()
|
||||
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
qualification = quality.suspend_auto_freeze_qualification(
|
||||
profile_id=profile.id, actor_id=user.id, reason='manual_review',
|
||||
)
|
||||
assert qualification.status == 'auto_freeze_suspended'
|
||||
assert db.session.get(ShippingOrderDocumentProfile, profile.id).status == 'published'
|
||||
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
||||
|
||||
|
||||
def test_profile_change_supersedes_stale_draft_suite_and_creates_current_suite(app):
|
||||
"""保存模板后必须建立新 checksum 的盲测集,旧草稿真值不得继续阻断或背书。"""
|
||||
with app.app_context():
|
||||
@@ -319,36 +361,22 @@ def test_blind_test_sample_removal_is_audited_and_approved_suite_is_immutable(ap
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_IMMUTABLE'
|
||||
|
||||
|
||||
def test_draft_publish_requires_independent_training_and_multiline_blind_gate(app):
|
||||
"""关键断言:发布前必须已有训练样本、独立多明细盲测与审批,不能发布后补门禁。"""
|
||||
def test_draft_publish_is_independent_from_blind_test_and_starts_manual_confirmation(app):
|
||||
"""关键断言:模板可先发布供人工确认使用,缺样本绝不反向启用自动冻结。"""
|
||||
from app.services.shipping_notice import order_document_profile_service as profiles
|
||||
|
||||
with app.app_context():
|
||||
profile, user, documents = _published_profile_with_samples()
|
||||
profile.status = 'draft'
|
||||
profile.checksum = None
|
||||
_publishable_v2_draft(profile)
|
||||
db.session.add(ShippingOrderDocumentProfileSample(
|
||||
profile_id=profile.id, document_id=documents[0].id, table_id='table-1', sample_role='training', created_by_id=user.id,
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(Exception) as missing_suite:
|
||||
profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
assert getattr(missing_suite.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_BLIND_TEST'
|
||||
|
||||
suite = quality.create_suite(profile_id=profile.id, actor_id=user.id)
|
||||
# One independent sample is enough, but it must still be genuine multi-line evidence.
|
||||
record_inline_layout_snapshot(documents[1], {
|
||||
'snapshot_version': 'shipping_document_table_snapshot.v1', 'status': 'ready',
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'html': '<table><tr><th>Part</th><th>Qty</th></tr><tr><td>PN-1</td><td>3</td></tr><tr><td>PN-2</td><td>4</td></tr></table>'}],
|
||||
})
|
||||
quality.add_sample(suite_id=suite['id'], document_id=documents[1].id, table_id='table-1', expected_rows=[
|
||||
{'part_number': 'PN-1', 'qty': 3}, {'part_number': 'PN-2', 'qty': 4},
|
||||
], actor_id=user.id)
|
||||
executed = quality.execute_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert executed['latest_run']['status'] == 'passed', executed['latest_run']['failure_codes']
|
||||
quality.approve_suite(suite_id=suite['id'], actor_id=user.id)
|
||||
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=profile.structure_fingerprint)
|
||||
published_without_suite = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
assert published_without_suite['status'] == 'published'
|
||||
assert published_without_suite['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
||||
assert not published_without_suite['auto_freeze_qualification']['auto_freeze_enabled']
|
||||
|
||||
|
||||
def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
@@ -428,4 +456,5 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
|
||||
published = profiles.publish(profile.id, actor_id=user.id, expected_lock_version=profile.lock_version)
|
||||
assert published['status'] == 'published'
|
||||
assert quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=published['checksum'])
|
||||
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
||||
assert not quality.profile_is_auto_create_approved(profile_id=profile.id, checksum=published['checksum'])
|
||||
@@ -0,0 +1,12 @@
|
||||
"""阶段七货代撤销记录迁移契约。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
|
||||
def test_freight_cancellation_migration_contract():
|
||||
"""关键断言:迁移声明新旧任务唯一版本对与回执字段。"""
|
||||
migration = importlib.import_module('migrations.versions.2cc56d7e8f9a_add_shipping_freight_cancellations')
|
||||
assert migration.down_revision == '1bb45c6d7e8f'
|
||||
assert migration.revision == '2cc56d7e8f9a'
|
||||
@@ -0,0 +1,31 @@
|
||||
"""阶段八:库存、Excel 与人工上传的底层入口门禁。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import ShippingTask
|
||||
from app.services.shipping_notice.export import generate_shipment_excel
|
||||
from app.services.shipping_notice.upload_attempt_service import record_manual_upload
|
||||
|
||||
|
||||
def test_export_rejects_voided_task_before_reading_template(app):
|
||||
"""关键断言:被替代/作废任务即使持有旧字段也不能从底层导出。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(task_no='SN-ENTRY-VOID', source_type='test', lifecycle_status='voided')
|
||||
from app import db
|
||||
db.session.add(task); db.session.commit()
|
||||
with pytest.raises(ValueError, match='作废'):
|
||||
generate_shipment_excel(task)
|
||||
|
||||
|
||||
def test_manual_upload_requires_receipt_number_and_evidence(app):
|
||||
"""关键断言:截图/附件和货代回执号缺一不可,不能仅凭客户端声明完成上传。"""
|
||||
with app.app_context():
|
||||
task = ShippingTask(task_no='SN-ENTRY-UPLOAD', source_type='test')
|
||||
from app import db
|
||||
db.session.add(task); db.session.commit()
|
||||
with pytest.raises(ValidationError) as error:
|
||||
record_manual_upload(task, artifact_id=None, evidence_asset_no='asset', operator_id=1, freight_ref_no='')
|
||||
assert error.value.code == 'SHIPPING.MANUAL_UPLOAD_EVIDENCE_REQUIRED'
|
||||
@@ -392,6 +392,14 @@ def test_fingerprint_strong_with_customer_name_po_reservation():
|
||||
assert fp['components'].get('customer_name') == 'ACME'
|
||||
|
||||
|
||||
def test_fingerprint_keeps_same_customer_po_when_reservation_changes():
|
||||
"""关键断言:Reservation/数量变化是同一 PO 的内容修订,不能改变版本链身份。"""
|
||||
base = {'customer_code': 'C1', 'po_number': 'PO-VERSION', 'reservation_ids': ['10000001'], 'lines': [{'reservation_id': '10000001', 'part_number': 'A', 'qty': 1}]}
|
||||
resend = {'customer_code': 'C1', 'po_number': 'PO-VERSION', 'reservation_ids': ['10000002'], 'lines': [{'reservation_id': '10000002', 'part_number': 'A', 'qty': 2}]}
|
||||
assert build_business_fingerprint(base)['fingerprint'] == build_business_fingerprint(resend)['fingerprint']
|
||||
assert build_content_fingerprint(base)['fingerprint'] != build_content_fingerprint(resend)['fingerprint']
|
||||
|
||||
|
||||
def test_pending_review_hit_is_same_active_blocking(app, dedup_user):
|
||||
"""pending_review 属活跃态:业务指纹命中应为 same_active_task 且 blocking。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -20,6 +20,7 @@ from app.core.errors import ConflictError, ForbiddenError, NotFoundError, Valida
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingBatch,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
@@ -51,6 +52,62 @@ def _make_upload(content: bytes = b'customer order line', filename: str = 'notic
|
||||
return FileStorage(stream=BytesIO(content), filename=filename, content_type='text/plain')
|
||||
|
||||
|
||||
def test_intake_status_exposes_layout_lifecycle_without_blocking_terminal_fallback(app, shipping_user):
|
||||
"""
|
||||
Intake 状态须区分附件预解析与版面任务;只有 queued/running 阻断发送。
|
||||
|
||||
关键断言:无任务为 not_required;活动任务为 processing;ready/failed 等终态统一为 completed,
|
||||
使前端继续轮询活动任务但保留文本/Dify 兜底能力。
|
||||
"""
|
||||
from app.services.shipping_notice.intake_service import serialize_intake
|
||||
|
||||
with app.app_context():
|
||||
asset = FileAsset(
|
||||
asset_no='FA-LAYOUT-STATUS-001', owner_user_id=shipping_user.id,
|
||||
original_filename='layout-status.eml', storage_provider='minio',
|
||||
storage_bucket='hxops-file-assets', storage_key='temporary/layout-status.eml',
|
||||
content_hash='a' * 64, file_size=100, mime_type='message/rfc822',
|
||||
upload_status='ready', lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingNoticeIntake(
|
||||
intake_no='SNI-LAYOUT-STATUS-001', asset_id=asset.id, user_id=shipping_user.id,
|
||||
purpose='shipping_notice', parse_status='parsed', parser_version='v6',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingNoticeDocument(
|
||||
intake_id=intake.id, document_type='attachment', attachment_key='order.pdf',
|
||||
filename='order.pdf', classification='order_notice', parse_status='parsed',
|
||||
content_hash='b' * 64,
|
||||
)
|
||||
db.session.add(document)
|
||||
db.session.flush()
|
||||
|
||||
# 没有独立版面任务时不阻断普通文本附件。
|
||||
assert serialize_intake(intake, asset=asset)['layout_status'] == 'not_required'
|
||||
|
||||
version = ShippingDocumentLayoutVersion(
|
||||
document_id=document.id, version=1, status='queued', source_content_hash='b' * 64,
|
||||
parser_key='mineru:test', parser_name='mineru', contract_version='shipping_document_layout.v1',
|
||||
issues_json=[],
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
processing = serialize_intake(intake, asset=asset)
|
||||
assert processing['layout_status'] == 'processing'
|
||||
assert processing['layout_summary']['queued'] == 1
|
||||
|
||||
# 失败也是终态;订单抽取可以继续使用文本或 Dify 兜底。
|
||||
version.status = 'failed'
|
||||
version.finished_at = datetime.utcnow()
|
||||
db.session.flush()
|
||||
completed = serialize_intake(intake, asset=asset)
|
||||
assert completed['layout_status'] == 'completed'
|
||||
assert completed['layout_summary']['failed'] == 1
|
||||
|
||||
|
||||
def test_candidate_review_duplicate_api_and_access_guards(app, client):
|
||||
"""Candidate API 应支持修订、刷新和决策,并阻止越权或已消费候选修改。"""
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
|
||||
@@ -34,9 +34,7 @@ def _assert_connector_contract(spec: dict[str, Any]) -> None:
|
||||
assert "inventory_connector_type" in status_description
|
||||
assert "inventory_source_type" not in status_description
|
||||
|
||||
confirm_description = spec["paths"]["/tools/confirm_inventory_source"]["post"]["description"]
|
||||
assert "connector_type" in confirm_description
|
||||
assert "source_code、source_type" not in confirm_description
|
||||
assert set(paths) == {"/tools/get_task_status", "/tools/get_batch_status"}
|
||||
|
||||
|
||||
def test_dynamic_openapi_uses_connector_contract(app, client) -> None:
|
||||
|
||||
@@ -38,7 +38,8 @@ from app.models import (
|
||||
from app.services.chat.log_service import merge_chat_log_payload
|
||||
from app.services.shipping_notice.candidate_validation import assess_candidate_business_summary
|
||||
from app.services.shipping_notice.order_extraction import persist_order_extraction_result
|
||||
from app.services.shipping_notice.order_extraction_workflow import parse_order_extraction_workflow_result
|
||||
from app.services.shipping_notice.order_extraction_merge import merge_unit_orders
|
||||
from app.services.shipping_notice.order_extraction_workflow import parse_order_extraction_execution_result
|
||||
from app.services.shipping_notice.open_existing_reservation_backfill import (
|
||||
backfill_exact_file_open_existing_reservations,
|
||||
)
|
||||
@@ -111,6 +112,50 @@ def test_candidate_validation_marks_reservation_missing_when_any_line_lacks_it()
|
||||
assert assessment['missing_process_fields'] == ['reservation_id']
|
||||
|
||||
|
||||
def test_candidate_validation_projects_customer_po_number_to_legacy_candidate_field():
|
||||
"""当前动态 Schema 的客户 PO 必须投影到 Candidate 兼容字段,供履约链路读取。"""
|
||||
assessment = assess_candidate_business_summary({
|
||||
'customer_po_number': '4518838152',
|
||||
'lines': [{'part_number': 'SKU-A', 'qty': 1, 'reservation_id': '1000140351'}],
|
||||
})
|
||||
|
||||
assert assessment['normalized_summary']['po_number'] == '4518838152'
|
||||
|
||||
|
||||
def test_merge_unit_orders_uses_atomic_customer_po_number_only():
|
||||
"""同一原子客户 PO 可补全 Reservation;多 PO 邮件文本绝不能误合并。"""
|
||||
schema = {'fields': [
|
||||
{'field_id': 'po', 'field_code': 'customer_po_number'},
|
||||
{'field_id': 'part', 'field_code': 'part_number'},
|
||||
{'field_id': 'reservation', 'field_code': 'reservation_id'},
|
||||
]}
|
||||
|
||||
def field(field_id, value):
|
||||
return {'field_id': field_id, 'observations': [{'value': value}]}
|
||||
|
||||
def order(po, reservation):
|
||||
line = [field('part', 'SKU-A')]
|
||||
if reservation:
|
||||
line.append(field('reservation', reservation))
|
||||
return {
|
||||
'source_intake_no': 'SNI-1', 'primary_document_id': po,
|
||||
'header_fields': [field('po', po)], 'lines': [{'fields': line}],
|
||||
}
|
||||
|
||||
merged = merge_unit_orders(
|
||||
orders=[order('4518838152', '1000140351'), order('4518838152', None)],
|
||||
schema_definition=schema,
|
||||
)
|
||||
assert len(merged) == 1
|
||||
assert len(merged[0]['lines']) == 1
|
||||
|
||||
split = merge_unit_orders(
|
||||
orders=[order('4518738152 & 4518838154', '1000140351'), order('4518838152', None)],
|
||||
schema_definition=schema,
|
||||
)
|
||||
assert len(split) == 2
|
||||
|
||||
|
||||
@pytest.mark.parametrize('field', ['customer_part_number', 'aws_part_number'])
|
||||
def test_candidate_validation_blocks_non_atomic_optional_part_numbers(field):
|
||||
"""可选料号包含分隔符时必须在 Candidate 门禁阻断,不能延迟到规范表写入失败。"""
|
||||
@@ -641,7 +686,7 @@ def test_approved_deterministic_marker_is_the_only_automatic_acceptance_source(a
|
||||
|
||||
def test_workflow_result_accepts_only_documented_data_orders_wrapper():
|
||||
"""Dify End 允许 data.orders 包装,但不把内部接受字段当作可信输入。"""
|
||||
assert parse_order_extraction_workflow_result({
|
||||
assert parse_order_extraction_execution_result({
|
||||
'status': 'succeeded', 'outputs': {'orders': {'data': {'orders': [{'id': 'one'}]}}},
|
||||
}) == [{'id': 'one'}]
|
||||
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
from app.services.shipping_notice.po_number import find_po_number_in_document, normalize_po_number
|
||||
from app.services.shipping_notice.po_number import (
|
||||
find_po_number_in_document,
|
||||
normalize_atomic_po_number,
|
||||
normalize_po_number,
|
||||
)
|
||||
from app.services.shipping_notice.extract import extract_notice_fields
|
||||
|
||||
|
||||
@@ -22,6 +26,12 @@ def test_normalize_po_number():
|
||||
assert normalize_po_number("") == ""
|
||||
|
||||
|
||||
def test_normalize_atomic_po_number_rejects_multi_value_text():
|
||||
"""多个 PO 的邮件摘要不能充当跨文档合并的单一订单身份。"""
|
||||
assert normalize_atomic_po_number('4518738152 & 4518838154') == ''
|
||||
assert normalize_atomic_po_number('ZNB-16754796') == '16754796'
|
||||
|
||||
|
||||
def test_extract_notice_fields_includes_po_number():
|
||||
structured = {
|
||||
"po_number": "PO-2026-001",
|
||||
|
||||
@@ -258,31 +258,10 @@ def test_openapi_spec_public(app, client):
|
||||
assert "/tools/generate_shipment_excel" not in spec["paths"]
|
||||
assert "/tools/upload_to_freight" not in spec["paths"]
|
||||
assert "/tools/switch_focus_task" not in spec["paths"]
|
||||
# 正式库存站点只能走已发布解析方案,Dify 不得恢复任务级临时映射入口。
|
||||
assert "/tools/get_inventory_schema_preview" not in spec["paths"]
|
||||
assert "/tools/apply_inventory_mapping" not in spec["paths"]
|
||||
assert "/tools/upload_inventory_file" not in spec["paths"]
|
||||
assert "/tools/submit_temporary_inventory_mapping_suggestion" in spec["paths"]
|
||||
assert "/tools/confirm_inventory_source" in spec["paths"]
|
||||
submit_decision = spec["paths"]["/tools/submit_decision"]["post"]["requestBody"]["content"]["application/json"]["schema"]
|
||||
assert "retry_rpa" in submit_decision["properties"]["decision"]["enum"]
|
||||
assert set(spec["paths"]) == {"/tools/get_task_status", "/tools/get_batch_status"}
|
||||
spec_text = str(spec)
|
||||
assert "submit_decision" in spec_text
|
||||
assert "match_inventory" in spec_text
|
||||
assert "generate_shipment_excel" in spec_text
|
||||
assert "upload_to_freight" in spec_text
|
||||
assert "retry_task" in spec_text
|
||||
assert "confirm_inventory_source" in spec_text
|
||||
assert "唯一 task_id" in spec_text
|
||||
assert "模糊指代不能直接推进" in spec_text
|
||||
assert "状态机" in spec_text
|
||||
assert "不得自行宣布完成" in spec_text
|
||||
assert "不要在自然语言正文列出按钮清单" in spec_text
|
||||
submit_desc = spec["paths"]["/tools/submit_decision"]["post"]["description"]
|
||||
assert "唯一 task_id" in submit_desc
|
||||
assert "模糊指代" in submit_desc
|
||||
assert "needs_human 或 failed" in submit_desc
|
||||
assert "按钮由 HXOPS 前端渲染" in submit_desc
|
||||
assert "只读解释" in spec_text
|
||||
assert "submit_decision" not in spec_text
|
||||
|
||||
|
||||
def test_confirm_inventory_source_route_returns_json(app, client):
|
||||
@@ -315,20 +294,11 @@ def test_static_openapi_snapshot_contains_shipping_contract_keywords():
|
||||
spec = json.loads(spec_path.read_text(encoding="utf-8"))
|
||||
|
||||
assert spec["openapi"] == "3.0.0"
|
||||
assert "/tools/submit_decision" in spec["paths"]
|
||||
assert "/tools/submit_decision" not in spec["paths"]
|
||||
assert "/tools/parse_notice" not in spec["paths"]
|
||||
spec_text = str(spec)
|
||||
assert "reference_context" in spec_text
|
||||
assert "状态机" in spec_text
|
||||
assert "不得自行改写成完成" in spec_text
|
||||
assert "不要在自然语言正文列出按钮清单" in spec_text
|
||||
assert "match_inventory" in spec_text
|
||||
assert "generate_shipment_excel" in spec_text
|
||||
assert "upload_to_freight" in spec_text
|
||||
submit_desc = spec["paths"]["/tools/submit_decision"]["post"]["description"]
|
||||
assert "唯一 task_id" in submit_desc
|
||||
assert "模糊指代" in submit_desc
|
||||
assert "按钮由 HXOPS 前端渲染" in submit_desc
|
||||
assert "只读解释" in spec_text
|
||||
assert "match_inventory" not in spec_text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("decision", ["confirm_inventory_mapping", "correct_inventory_mapping"])
|
||||
|
||||
@@ -457,14 +457,16 @@ def test_profile_samples_are_governed_and_audited(app):
|
||||
assert db.session.get(ShippingOrderDocumentProfile, profile.id).training_sample_count == 0
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile.id).count() == 0
|
||||
|
||||
with pytest.raises(Exception) as gate:
|
||||
service.publish(profile.id, actor_id=None, expected_lock_version=profile.lock_version)
|
||||
assert getattr(gate.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PUBLISH_GATE_TRAINING'
|
||||
published = service.publish(profile.id, actor_id=None, expected_lock_version=profile.lock_version)
|
||||
# 关键断言:样本不足不阻断模板人工确认发布,也绝不能开启自动冻结。
|
||||
assert published['status'] == 'published'
|
||||
assert published['auto_freeze_qualification']['status'] == 'manual_confirmation'
|
||||
assert not published['auto_freeze_qualification']['auto_freeze_enabled']
|
||||
with pytest.raises(Exception) as caught:
|
||||
service.add_profile_sample(
|
||||
profile.id, document_id=document.id, table_id='sample-table', sample_role='blind_test', actor_id=None,
|
||||
)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_SAMPLE_INVALID'
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_IMMUTABLE'
|
||||
|
||||
|
||||
def test_profile_publish_freezes_field_ids_and_retires_previous_version(app, monkeypatch):
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""验证订单抽取模板路由审计迁移的建表、约束、索引和回退。
|
||||
|
||||
依赖:Alembic Operations、SQLite 内存数据库、06ef1a2b3c4d 增量迁移。
|
||||
逻辑:先建立迁移引用的最小父表,再执行 upgrade/downgrade 并检查结构性契约。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_route_decision_migration_upgrade_and_downgrade_contract():
|
||||
"""迁移必须创建审计表、唯一/检查约束和索引,并可干净回退。"""
|
||||
migration = importlib.import_module('migrations.versions.06ef1a2b3c4d_add_order_extraction_route_decisions')
|
||||
engine = sa.create_engine('sqlite://')
|
||||
metadata = sa.MetaData()
|
||||
# [STEP 1] 仅建立新增表外键所需的父表,不把目标表预先纳入 metadata。
|
||||
for table_name in (
|
||||
'shipping_order_extraction_runs', 'shipping_order_extraction_units', 'jobs',
|
||||
'shipping_order_document_profiles',
|
||||
):
|
||||
sa.Table(table_name, metadata, sa.Column('id', sa.Integer, primary_key=True))
|
||||
metadata.create_all(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
migration.op = Operations(MigrationContext.configure(connection))
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
columns = {column['name'] for column in inspector.get_columns('shipping_order_extraction_route_decisions')}
|
||||
indexes = {index['name'] for index in inspector.get_indexes('shipping_order_extraction_route_decisions')}
|
||||
unique = {item['name'] for item in inspector.get_unique_constraints('shipping_order_extraction_route_decisions')}
|
||||
checks = {item['name'] for item in inspector.get_check_constraints('shipping_order_extraction_route_decisions')}
|
||||
|
||||
# 关键断言:路由投影能表达重试事实,但长期不可删除审计由统一事件表承载。
|
||||
assert {'run_id', 'unit_id', 'job_id', 'attempt_no', 'candidate_summary_json', 'fallback_reason_codes_json'} <= columns
|
||||
assert 'uq_shipping_order_extraction_route_decision_attempt' in unique
|
||||
assert {'ix_shipping_order_extraction_route_decisions_run_unit', 'ix_shipping_order_extraction_route_decisions_unit_created'} <= indexes
|
||||
assert {'ck_shipping_order_extraction_route_decision', 'ck_shipping_order_extraction_route_match_status'} <= checks
|
||||
|
||||
migration.downgrade()
|
||||
assert 'shipping_order_extraction_route_decisions' not in sa.inspect(connection).get_table_names()
|
||||
@@ -18,18 +18,19 @@ from app.core.auth.jwt import issue_local_access_token
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
Agent,
|
||||
AgentRuntimeBinding,
|
||||
ChatLog,
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingDocumentLayoutVersion,
|
||||
Job,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderExtractionDiagnosticAudit,
|
||||
ShippingOrderExtractionPlan,
|
||||
ShippingOrderExtractionRouteDecision,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionUnit,
|
||||
ShippingOrderDocumentProfile,
|
||||
@@ -39,6 +40,7 @@ from app.models import (
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
get_order_extraction_diagnostic_run,
|
||||
mark_order_extraction_run_seen,
|
||||
reparse_order_extraction_run,
|
||||
retry_order_extraction_run,
|
||||
@@ -48,6 +50,74 @@ from app.services.shipping_notice.order_extraction_run_service import (
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
from app.services.shipping_notice.order_extraction_workflow import route_deterministic_unit
|
||||
|
||||
|
||||
def test_route_decision_is_immutable_per_unit_job_attempt_and_cascades_with_run(app):
|
||||
"""路由审计按尝试追加;同一尝试不可覆盖,删除 Run 时随其级联删除。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='ROUTE-AUDIT')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
assert job is not None
|
||||
db.session.add(ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id, unit_id=unit.id, job_id=job.id, attempt_no=1,
|
||||
decision='review_required', match_status='ambiguous', candidate_count=2,
|
||||
table_count=1, approved_table_count=0,
|
||||
candidate_summary_json=[{'profile_code': 'PO_A', 'version': 1, 'score': 1.0, 'hard_match': True, 'reason_codes': []}],
|
||||
fallback_reason_codes_json=['profile_ambiguous'],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
# 关键断言:同一 Unit/Job/尝试只能有一条决策,不能被 retry 覆盖。
|
||||
duplicate = ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id, unit_id=unit.id, job_id=job.id, attempt_no=1,
|
||||
decision='review_required', match_status='no_match', candidate_count=0,
|
||||
table_count=0, approved_table_count=0, candidate_summary_json=[], fallback_reason_codes_json=['profile_no_match'],
|
||||
)
|
||||
db.session.add(duplicate)
|
||||
with pytest.raises(Exception):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
assert ShippingOrderExtractionRouteDecision.query.filter_by(unit_id=unit.id).count() == 1
|
||||
|
||||
db.session.delete(run)
|
||||
db.session.commit()
|
||||
assert ShippingOrderExtractionRouteDecision.query.count() == 0
|
||||
|
||||
|
||||
def test_diagnostic_run_exposes_redacted_route_decisions_only(app):
|
||||
"""管理员 DTO 返回模板路由事实,但绝不返回订单值、引文、坐标或 Provider 输入。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='ROUTE-DTO')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
unit = run.extraction_plan.units[0]
|
||||
job = db.session.get(Job, run.current_job_id)
|
||||
db.session.add(ShippingOrderExtractionRouteDecision(
|
||||
run_id=run.id, unit_id=unit.id, job_id=job.id, attempt_no=1,
|
||||
decision='review_required', match_status='ambiguous', candidate_count=2, table_count=1,
|
||||
approved_table_count=0,
|
||||
candidate_summary_json=[{
|
||||
'profile_code': 'PO_A', 'version': 3, 'score': 1.0, 'hard_match': True,
|
||||
'reason_codes': [], 'missing_required_anchor_ids': ['title'], 'value': 'must-not-leak',
|
||||
}],
|
||||
fallback_reason_codes_json=['profile_ambiguous'],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
payload = get_order_extraction_diagnostic_run(
|
||||
admin_user_id=user.id, request_id='route-dto', run_no=run.run_no,
|
||||
)
|
||||
|
||||
route = payload['units'][0]['route_decisions'][0]
|
||||
assert route['execution_mode'] == 'review_required'
|
||||
assert route['candidates'][0]['missing_required_anchor_ids'] == ['title']
|
||||
assert 'must-not-leak' not in str(route)
|
||||
|
||||
|
||||
def _seed_run_input(
|
||||
@@ -79,29 +149,10 @@ def _seed_run_input(
|
||||
dify_api_key='test-key',
|
||||
is_active=True,
|
||||
)
|
||||
provider = Agent(
|
||||
name=f'Order Extraction Provider {suffix}',
|
||||
agent_code='generic',
|
||||
runtime_provider='dify',
|
||||
conversation_mode='task_chat',
|
||||
dify_app_type='workflow',
|
||||
exposure_mode='internal',
|
||||
dify_app_id=f'run-provider-{suffix}',
|
||||
dify_api_key='provider-key',
|
||||
api_base_url='http://dify.example/v1',
|
||||
is_active=True,
|
||||
)
|
||||
if grant_permission:
|
||||
user.agents.append(agent)
|
||||
db.session.add_all([user, agent, provider])
|
||||
db.session.add_all([user, agent])
|
||||
db.session.flush()
|
||||
db.session.add(AgentRuntimeBinding(
|
||||
owner_agent_id=agent.id,
|
||||
capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider.id,
|
||||
enabled=True,
|
||||
config_json={'timeout_seconds': 900, 'max_attempts': 3},
|
||||
))
|
||||
session = ChatSession(
|
||||
session_id=f'run-session-{suffix}',
|
||||
user_id=user.id,
|
||||
@@ -181,7 +232,6 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app):
|
||||
plan = ShippingOrderExtractionPlan.query.filter_by(run_id=run.id).one()
|
||||
assert plan.plan_version == 'shipping_order_extraction.plan.v1'
|
||||
assert len(plan.plan_version) == 33
|
||||
|
||||
assert plan.input_snapshot_hash == run.input_snapshot_hash
|
||||
assert plan.status == 'planned'
|
||||
assert plan.unit_count == 1
|
||||
@@ -192,9 +242,7 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app):
|
||||
assert unit.status == 'pending'
|
||||
|
||||
replay, replayed = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent.id,
|
||||
conversation_id=session.session_id,
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
db.session.commit()
|
||||
@@ -206,8 +254,50 @@ def test_create_run_freezes_document_and_schema_and_is_idempotent(app):
|
||||
assert ShippingOrderExtractionUnit.query.count() == 1
|
||||
|
||||
|
||||
def test_schema_auto_create_switch_cannot_bypass_disabled_runtime_binding(app):
|
||||
"""Schema 总开关开启时,未显式启用 Runtime Binding 的 Run 仍必须保持影子模式。"""
|
||||
@pytest.mark.parametrize('layout_status', ['queued', 'running'])
|
||||
def test_create_run_waits_for_active_document_layout_before_freezing_snapshot(app, layout_status):
|
||||
"""未终态 Layout 必须先完成,避免新 Run 永久冻结空快照而错过确定性模板。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix=f'LAYOUT-{layout_status.upper()}')
|
||||
db.session.add(ShippingDocumentLayoutVersion(
|
||||
document_id=document.id,
|
||||
version=1,
|
||||
status=layout_status,
|
||||
source_content_hash=document.content_hash,
|
||||
parser_key='mineru:pipeline:shipping_document_table_snapshot.v1:test',
|
||||
parser_name='mineru',
|
||||
contract_version='shipping_document_table_snapshot.v1',
|
||||
issues_json=[],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no.upper()],
|
||||
)
|
||||
|
||||
assert exc_info.value.code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_LAYOUT_PENDING'
|
||||
assert ShippingOrderExtractionRun.query.count() == 0
|
||||
|
||||
|
||||
def test_deterministic_route_reports_no_layout_table_not_multiple_tables(app):
|
||||
"""没有可用 Layout 表格时必须给出准确回退原因,不能误报为多表。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='NO-LAYOUT-TABLE')
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
intake_nos=[intake.intake_no],
|
||||
)
|
||||
|
||||
route = route_deterministic_unit(run, unit=run.extraction_plan.units[0])
|
||||
|
||||
assert route.execution_mode == 'review_required'
|
||||
assert route.decision['fallback_reason_codes'] == ['no_layout_table']
|
||||
|
||||
|
||||
def test_run_freezes_manual_auto_freeze_policy(app):
|
||||
"""第一版无论 Schema 历史开关如何都冻结为人工确认,不能自动履约。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='AUTO-CREATE-GATE')
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one()
|
||||
@@ -220,20 +310,20 @@ def test_schema_auto_create_switch_cannot_bypass_disabled_runtime_binding(app):
|
||||
)
|
||||
|
||||
assert reused is False
|
||||
assert run.provider_config_json['auto_create_enabled'] is False
|
||||
policy = run.input_snapshot_json['auto_creation_policy']
|
||||
assert run.auto_freeze_policy_json['enabled'] is False
|
||||
policy = run.input_snapshot_json['auto_freeze_policy']
|
||||
assert policy == {
|
||||
'mode': 'manual_confirmation',
|
||||
'enabled': False,
|
||||
'schema_enabled': True,
|
||||
'runtime_binding_enabled': False,
|
||||
'schema_policy_version': None,
|
||||
}
|
||||
|
||||
|
||||
def test_run_v3_freezes_layout_schema_candidate_without_exposing_it_to_dify(app):
|
||||
"""Run v3 应冻结真实 layout cell 映射,但 Workflow Manifest 必须完全剥离内部证据。"""
|
||||
def test_run_v3_freezes_layout_schema_candidate_without_exposing_internal_evidence(app):
|
||||
"""Run v3 冻结真实 layout cell 映射,确定性诊断快照必须剥离内部证据。"""
|
||||
from app.services.shipping_notice.document_layout.html_layout import build_html_layout_candidate
|
||||
from app.services.shipping_notice.document_layout.lifecycle import record_inline_layout_snapshot
|
||||
from app.services.shipping_notice.order_extraction_workflow import build_order_extraction_workflow_inputs
|
||||
from app.services.shipping_notice.order_extraction_workflow import build_order_extraction_execution_snapshot
|
||||
|
||||
with app.app_context():
|
||||
user, agent, session, intake, document = _seed_run_input(suffix='B')
|
||||
@@ -267,7 +357,7 @@ def test_run_v3_freezes_layout_schema_candidate_without_exposing_it_to_dify(app)
|
||||
assert candidates[0]['rows'][0]['fields'][0]['cell_id']
|
||||
assert 'layout_table_not_accepted' in candidates[0]['issues']
|
||||
|
||||
manifest = build_order_extraction_workflow_inputs(
|
||||
manifest = build_order_extraction_execution_snapshot(
|
||||
run, unit=run.extraction_plan.units[0],
|
||||
)['execution_manifest']
|
||||
assert 'layout_schema_candidates' not in manifest
|
||||
@@ -327,8 +417,8 @@ def test_create_run_freezes_published_order_document_profile_definition(app):
|
||||
assert run.input_snapshot_json['order_document_profiles'][0]['definition']['drop_zero_qty'] is True
|
||||
|
||||
|
||||
def test_run_plan_creates_email_relation_and_attachment_units_in_frozen_order(app):
|
||||
"""邮件正文和附件必须成为彼此隔离、顺序稳定的计划单元。"""
|
||||
def test_run_plan_creates_only_attachment_units_and_keeps_email_as_frozen_supplement(app):
|
||||
"""正文被冻结为补充事实,但不能成为执行单元或独立订单。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, attachment = _seed_run_input(suffix='PLAN')
|
||||
body = ShippingNoticeDocument(
|
||||
@@ -356,27 +446,29 @@ def test_run_plan_creates_email_relation_and_attachment_units_in_frozen_order(ap
|
||||
units = ShippingOrderExtractionUnit.query.filter_by(plan_id=plan.id).order_by(
|
||||
ShippingOrderExtractionUnit.position.asc()
|
||||
).all()
|
||||
assert [unit.document_id for unit in units] == sorted([attachment.id, body.id])
|
||||
assert [unit.document_id for unit in units] == [attachment.id]
|
||||
assert {unit.document_id: unit.unit_type for unit in units} == {
|
||||
attachment.id: 'document_extraction',
|
||||
body.id: 'email_relation',
|
||||
}
|
||||
assert plan.unit_count == 1
|
||||
assert any(item['document_id'] == body.id for item in run.input_snapshot_json['intakes'][0]['documents'])
|
||||
assert all(unit.result_json is None and unit.error_code is None for unit in units)
|
||||
|
||||
|
||||
def test_plan_unit_state_machine_is_local_and_rolls_up_partial_failure(app):
|
||||
"""一个单元失败不得清除其他成功结果,计划仅在全部单元终态后汇总部分失败。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _attachment = _seed_run_input(suffix='STATE')
|
||||
db.session.add(ShippingNoticeDocument(
|
||||
user, agent, session, intake, attachment = _seed_run_input(suffix='STATE')
|
||||
second_attachment = ShippingNoticeDocument(
|
||||
intake_id=intake.id,
|
||||
document_type='email_body',
|
||||
attachment_key='email-body',
|
||||
document_type='attachment',
|
||||
attachment_key='second-pdf',
|
||||
content_hash='c' * 64,
|
||||
classification='order_notice',
|
||||
parse_status='parsed',
|
||||
extracted_text='Body relationship facts',
|
||||
))
|
||||
extracted_text='Second PDF order facts',
|
||||
)
|
||||
db.session.add(second_attachment)
|
||||
db.session.commit()
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id,
|
||||
@@ -847,8 +939,8 @@ def test_chat_sessions_aggregate_only_new_unseen_order_extraction_attention(app)
|
||||
assert aggregate == {session.session_id: (1, 'error')}
|
||||
|
||||
|
||||
def test_failed_run_retry_reuses_snapshot_and_provider_result(app):
|
||||
"""手工重试复用同一 Run/快照/Provider 缓存,只创建新的执行 Job。"""
|
||||
def test_failed_run_retry_reuses_snapshot_and_execution_result(app):
|
||||
"""手工重试复用同一 Run/快照/确定性结果,只创建新的执行 Job。"""
|
||||
with app.app_context():
|
||||
user, agent, session, intake, _document = _seed_run_input(suffix='RETRY')
|
||||
run, _ = create_order_extraction_run(
|
||||
@@ -856,8 +948,8 @@ def test_failed_run_retry_reuses_snapshot_and_provider_result(app):
|
||||
)
|
||||
original_job_id = run.current_job_id
|
||||
frozen_snapshot = run.input_snapshot_json
|
||||
run.provider_result_json = {'orders': [], 'workflow': {'workflow_run_id': 'wf-cached'}}
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
run.execution_result_json = {'orders': [], 'execution': {'mode': 'deterministic'}}
|
||||
transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', error_code='TEST.FAILED', error_message='failed once',
|
||||
)
|
||||
@@ -874,7 +966,7 @@ def test_failed_run_retry_reuses_snapshot_and_provider_result(app):
|
||||
assert retried.phase == 'manual_retry_queued'
|
||||
assert retried.current_job_id != original_job_id
|
||||
assert retried.input_snapshot_json == frozen_snapshot
|
||||
assert retried.provider_result_json == {'orders': [], 'workflow': {'workflow_run_id': 'wf-cached'}}
|
||||
assert retried.execution_result_json == {'orders': [], 'execution': {'mode': 'deterministic'}}
|
||||
assert retried.error_code is None
|
||||
assert intake.order_extraction_status == 'extracting'
|
||||
assert ShippingOrderExtractionRun.query.count() == 1
|
||||
@@ -918,7 +1010,7 @@ def test_run_retry_rejects_obsolete_frozen_snapshot(app):
|
||||
snapshot['intakes'] = [dict(item) for item in snapshot['intakes']]
|
||||
snapshot['intakes'][0].pop('deterministic_context')
|
||||
run.input_snapshot_json = snapshot
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='legacy snapshot')
|
||||
original_job_count = Job.query.filter_by(business_ref=run.run_no).count()
|
||||
db.session.commit()
|
||||
@@ -953,7 +1045,7 @@ def test_terminal_transition_updates_persisted_chat_state(app):
|
||||
},
|
||||
)
|
||||
db.session.add(log)
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing')
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='failed',
|
||||
@@ -976,7 +1068,7 @@ def test_chat_history_overrides_late_stale_run_card_with_terminal_fact(app, clie
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing')
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='failed',
|
||||
@@ -1022,7 +1114,7 @@ def test_chat_history_does_not_project_user_run_anchor_as_duplicate_state_card(a
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='failed once')
|
||||
db.session.add_all([
|
||||
ChatLog(
|
||||
@@ -1082,7 +1174,7 @@ def test_failed_run_retry_api_returns_queued_run(app, client):
|
||||
run, _ = create_order_extraction_run(
|
||||
user=user, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
transition_order_extraction_run(run, target_status='running', phase='calling_provider')
|
||||
transition_order_extraction_run(run, target_status='running', phase='deterministic_parsing')
|
||||
transition_order_extraction_run(run, target_status='failed', error_message='workflow failed')
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
@@ -1332,7 +1424,7 @@ def test_reparse_creates_new_run_with_lineage_and_current_snapshot(app):
|
||||
assert replacement.reparse_comment == 'column shifted'
|
||||
assert source.superseded_by_run_id == replacement.id
|
||||
assert source.superseded_at is not None
|
||||
assert replacement.provider_result_json is None
|
||||
assert replacement.execution_result_json is None
|
||||
serialized = serialize_order_extraction_run(replacement)
|
||||
assert serialized['reparse']['difference_summary'] == {
|
||||
'schema_changed': False, 'profile_changed': False, 'layout_changed': False,
|
||||
@@ -1373,7 +1465,7 @@ def test_reparse_freezes_current_document_schema_and_layout_without_reprocessing
|
||||
assert replacement.input_snapshot_hash != source.input_snapshot_hash
|
||||
assert replacement.input_snapshot_json['intakes'][0]['documents'][0]['extracted_text'].endswith('42 EA')
|
||||
assert replacement.input_snapshot_json['schema']['definition']['reparse_marker'] == 'current-published-rule'
|
||||
assert replacement.provider_result_json is None
|
||||
assert replacement.execution_result_json is None
|
||||
|
||||
|
||||
def test_reparse_rejects_non_terminal_run_and_invalid_reason(app):
|
||||
@@ -1488,7 +1580,7 @@ def test_order_extraction_health_calculates_segments_and_failure_rate(app):
|
||||
base = datetime.utcnow() - timedelta(minutes=5)
|
||||
run.created_at = base
|
||||
run.started_at = base + timedelta(seconds=1)
|
||||
run.provider_completed_at = base + timedelta(seconds=4)
|
||||
run.extraction_completed_at = base + timedelta(seconds=4)
|
||||
run.result_persisted_at = base + timedelta(seconds=6)
|
||||
run.finished_at = base + timedelta(seconds=7)
|
||||
run.status = 'failed'
|
||||
@@ -1500,7 +1592,7 @@ def test_order_extraction_health_calculates_segments_and_failure_rate(app):
|
||||
|
||||
assert report['failure_rate'] == 1.0
|
||||
assert report['latency']['queue']['avg_ms'] == 1000
|
||||
assert report['latency']['provider']['avg_ms'] == 3000
|
||||
assert report['latency']['deterministic_parsing']['avg_ms'] == 3000
|
||||
assert report['latency']['hxops_persistence']['avg_ms'] == 2000
|
||||
assert report['latency']['total']['avg_ms'] == 7000
|
||||
assert report['error_code_counts'] == {'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT': 1}
|
||||
@@ -1533,9 +1625,7 @@ def test_order_extraction_diagnostic_apis_are_admin_only_audited_and_redacted(ap
|
||||
run, _ = create_order_extraction_run(
|
||||
user=owner, agent_id=agent.id, conversation_id=session.session_id, intake_nos=[intake.intake_no],
|
||||
)
|
||||
run.dify_workflow_run_id = 'wf-diagnostic'
|
||||
run.provider_snapshot_json = {'prompt': 'must not leak'}
|
||||
run.provider_result_json = {'raw_output': 'must not leak'}
|
||||
run.execution_result_json = {'raw_output': 'must not leak'}
|
||||
transition_order_extraction_run(run, target_status='running')
|
||||
transition_order_extraction_run(
|
||||
run, target_status='failed', error_code='UPSTREAM.TIMEOUT', error_message='secret provider stack trace',
|
||||
@@ -1586,7 +1676,7 @@ def test_order_extraction_diagnostic_apis_are_admin_only_audited_and_redacted(ap
|
||||
assert listed.status_code == 200
|
||||
listing = listed.get_json()['data']
|
||||
summary = next(item for item in listing['items'] if item['run_no'] == run_no)
|
||||
assert summary['workflow_run_id'] == 'wf-diagnostic'
|
||||
assert summary['parser_engine_version'] == 'deterministic-order-parser.v1'
|
||||
serialized_listing = str(listing).lower()
|
||||
for forbidden_text in ('must not leak', 'secret provider', 'secret job', 'documents', 'prompt', 'raw_output'):
|
||||
assert forbidden_text not in serialized_listing
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""验证阶段 0 的订单抽取状态收敛。
|
||||
|
||||
依赖:Order Extraction Run/Plan 状态机、确定性路由结果。
|
||||
逻辑:业务拒识必须停在人工复核,不得作为技术失败或静默完成流入下一阶段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingAuditEvent
|
||||
from app.services.shipping_notice.order_extraction_plan import transition_order_extraction_unit
|
||||
|
||||
|
||||
def test_business_review_route_transitions_unit_to_skipped_not_failed(app):
|
||||
"""模板未匹配等业务拒识使用 skipped,计划完成后由 Run 汇总为 needs_review。"""
|
||||
with app.app_context():
|
||||
plan = SimpleNamespace(units=[])
|
||||
unit = SimpleNamespace(
|
||||
status='running', attempt_count=1, started_at=None, finished_at=None,
|
||||
result_json={'stale': True}, error_code=None, error_message=None, plan=plan,
|
||||
)
|
||||
plan.units = [unit]
|
||||
|
||||
transition_order_extraction_unit(
|
||||
unit,
|
||||
target_status='skipped',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED',
|
||||
error_message='Template requires review',
|
||||
)
|
||||
|
||||
# 关键断言:业务不确定性是可复核的完成态,不能污染技术失败率。
|
||||
assert unit.status == 'skipped'
|
||||
assert unit.error_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED'
|
||||
assert plan.status == 'completed'
|
||||
|
||||
|
||||
def test_unit_transition_appends_auditable_status_event(app):
|
||||
"""真实 Unit 状态改变必须带 Run 编号写入统一审计账本。"""
|
||||
with app.app_context():
|
||||
run = SimpleNamespace(run_no='SNER-STAGE0')
|
||||
plan = SimpleNamespace(units=[], run=run)
|
||||
unit = SimpleNamespace(
|
||||
id=37, status='running', attempt_count=1, started_at=None, finished_at=None,
|
||||
result_json=None, error_code=None, error_message=None, plan=plan,
|
||||
)
|
||||
plan.units = [unit]
|
||||
|
||||
transition_order_extraction_unit(unit, target_status='skipped')
|
||||
db.session.commit()
|
||||
|
||||
event = ShippingAuditEvent.query.filter_by(aggregate_id='37').one()
|
||||
# 关键断言:单元业务复核状态能和 Run 关联,但不复制订单内容。
|
||||
assert event.event_type == 'order_extraction_unit_status_changed'
|
||||
assert event.run_no == 'SNER-STAGE0'
|
||||
assert event.reason_code == 'SHIPPING_NOTICE.ORDER_EXTRACTION_REVIEW_REQUIRED'
|
||||
@@ -48,6 +48,23 @@ def test_profile_matcher_enforces_required_anchor_and_evidence_availability():
|
||||
assert match_frozen_coordinate_profiles(profiles=[_profile('PO_A')], layout={'tables': []}).status == 'evidence_insufficient'
|
||||
|
||||
|
||||
def test_profile_matcher_reports_only_missing_anchor_identifiers():
|
||||
"""缺失锚点诊断只能保存模板 anchor_id,绝不保存当前文档文本或坐标。"""
|
||||
profile = _profile('PO_A')
|
||||
profile['definition']['document_match']['required_anchors'].append({
|
||||
'anchor_id': 'customer_logo', 'text': 'ACME LOGO',
|
||||
})
|
||||
|
||||
result = match_frozen_coordinate_profiles(profiles=[profile], layout=_layout('PURCHASE ORDER PO-12345'))
|
||||
|
||||
# 关键断言:管理员能定位配置缺项,而诊断不泄露订单业务值。
|
||||
assert result.status == 'layout_drift'
|
||||
candidate = result.candidates[0]
|
||||
assert candidate.reason_codes == ['required_anchor_missing']
|
||||
assert candidate.missing_required_anchor_ids == ['customer_logo']
|
||||
assert 'PO-12345' not in candidate.model_dump_json()
|
||||
|
||||
|
||||
def test_profile_matcher_requires_optional_score_threshold():
|
||||
"""可选锚点未命中导致得分低于模板阈值时不得自动匹配。"""
|
||||
result = match_frozen_coordinate_profiles(profiles=[_profile('PO_A', optional=['SUPPLIER A'], score=.95)], layout=_layout())
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
"""阶段六冻结快照迁移契约测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
|
||||
def test_snapshot_readiness_migration_contract(monkeypatch):
|
||||
"""关键断言:迁移增加来源清单和 Task 级唯一约束,防止并发产生双 Snapshot。"""
|
||||
migration = importlib.import_module('migrations.versions.1bb45c6d7e8f_add_snapshot_freeze_readiness_manifest')
|
||||
engine = sa.create_engine('sqlite://')
|
||||
metadata = sa.MetaData()
|
||||
sa.Table('shipping_tasks', metadata, sa.Column('id', sa.Integer, primary_key=True))
|
||||
sa.Table(
|
||||
'shipping_order_snapshots', metadata,
|
||||
sa.Column('id', sa.Integer, primary_key=True),
|
||||
sa.Column('task_id', sa.Integer, sa.ForeignKey('shipping_tasks.id'), nullable=False),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
monkeypatch.setattr(migration.op, 'get_bind', lambda: connection)
|
||||
monkeypatch.setattr(migration.op, 'batch_alter_table', Operations(context).batch_alter_table)
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
columns = {item['name'] for item in inspector.get_columns('shipping_order_snapshots')}
|
||||
unique_sets = {tuple(item['column_names']) for item in inspector.get_unique_constraints('shipping_order_snapshots')}
|
||||
assert 'source_manifest_json' in columns
|
||||
assert ('task_id',) in unique_sets
|
||||
@@ -26,13 +26,14 @@ from app.services.shipping_notice.task_field_gate import field_conflict_gate_res
|
||||
from app.services.shipping_notice.task_workflow import add_notice_line, update_notice_line
|
||||
|
||||
|
||||
def _review_payload() -> dict[str, str | int]:
|
||||
def _review_payload() -> dict[str, object]:
|
||||
"""提供工作台人工纠错的最小审计上下文,避免测试绕过生产门禁。"""
|
||||
return {
|
||||
'event_source': 'workspace_api',
|
||||
'reviewed_by_id': 1,
|
||||
'evidence_ref': 'asset://review/order.png',
|
||||
'evidence': {'evidence_type': 'manual_input', 'reason': '客户电话确认'},
|
||||
'reason': '原始订单附件已复核',
|
||||
'expected_order_data_version': 1,
|
||||
}
|
||||
|
||||
|
||||
@@ -207,7 +208,7 @@ def test_resolve_conflict_writes_current_field_value_and_is_idempotent(app):
|
||||
expected_conflict_version=conflict.conflict_version,
|
||||
expected_order_data_version=task.order_data_version,
|
||||
resolved_by_id=1,
|
||||
evidence_ref='asset://review/conflict-1.png',
|
||||
evidence={'evidence_type': 'manual_input', 'reason': '客户电话确认'},
|
||||
reason='原始订单附件已复核',
|
||||
idempotency_key='resolve-1',
|
||||
)
|
||||
@@ -219,14 +220,14 @@ def test_resolve_conflict_writes_current_field_value_and_is_idempotent(app):
|
||||
assert value.value_json == '3000092917'
|
||||
assert ShippingTaskFieldConflict.query.filter_by(task_id=task.id, status='open').count() == 0
|
||||
event = ShippingOrderReviewEvent.query.filter_by(task_id=task.id, field_code='reservation_id').one()
|
||||
assert event.evidence_ref == 'asset://review/conflict-1.png'
|
||||
assert '"evidence_type":"manual_input"' in event.evidence_ref
|
||||
assert event.reason == '原始订单附件已复核'
|
||||
|
||||
replay = resolve_field_conflict(
|
||||
task=task,
|
||||
conflict_id=conflict.id,
|
||||
resolution='take_incoming',
|
||||
evidence_ref='asset://review/conflict-1.png',
|
||||
evidence={'evidence_type': 'manual_input', 'reason': '客户电话确认'},
|
||||
reason='原始订单附件已复核',
|
||||
idempotency_key='resolve-1',
|
||||
)
|
||||
@@ -243,26 +244,48 @@ def test_update_notice_line_version_mismatch(app):
|
||||
)
|
||||
db.session.commit()
|
||||
resp = update_notice_line({
|
||||
**_review_payload(),
|
||||
'task_id': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'inventory_source_hint': 'H9'},
|
||||
'expected_order_data_version': 1,
|
||||
**_review_payload(),
|
||||
})
|
||||
# replace 已 bump version,再带 1 应失败;先读当前版本再测过期。
|
||||
task = db.session.get(ShippingTask, task.id)
|
||||
stale = int(task.order_data_version) - 1
|
||||
resp = update_notice_line({
|
||||
**_review_payload(),
|
||||
'task_id': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'inventory_source_hint': 'H8'},
|
||||
'expected_order_data_version': stale,
|
||||
**_review_payload(),
|
||||
})
|
||||
assert resp['status'] == 'failed'
|
||||
assert resp['data']['error_code'] == 'SHIPPING.ORDER_DATA_VERSION_MISMATCH'
|
||||
|
||||
|
||||
def test_update_notice_line_rejects_forged_structured_evidence(app):
|
||||
"""伪造或跨订单 document_cell 证据必须在写入前被拒绝。"""
|
||||
with app.app_context():
|
||||
task = _task(lines_json=[{'part_number': 'A001', 'qty': 10, 'reservation_id': '3000000001'}])
|
||||
db.session.commit()
|
||||
response = update_notice_line({
|
||||
'task_id': task.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'reservation_id': '3000000002'},
|
||||
'event_source': 'workspace_api', 'reviewed_by_id': 1,
|
||||
'expected_order_data_version': task.order_data_version,
|
||||
'reason': '核对附件',
|
||||
'evidence': {
|
||||
'evidence_type': 'document_cell', 'document_id': 99999,
|
||||
'observation_id': 99999, 'page_no': 1, 'table_id': 'forged', 'cell_id': 'forged',
|
||||
},
|
||||
})
|
||||
assert response['status'] == 'failed'
|
||||
assert response['data']['error_code'] == 'SHIPPING.ORDER_REVIEW_EVIDENCE_INVALID'
|
||||
assert int(db.session.get(ShippingTask, task.id).order_data_version) == 1
|
||||
|
||||
|
||||
def test_add_notice_line_creates_new_extraction_and_preserves_header_values(app):
|
||||
"""新增行必须生成新 Extraction,且复制已有单头值,避免行编辑破坏锁定订单真相。"""
|
||||
with app.app_context():
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
"""阶段七:重发版本替代与上传后撤销门禁。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingFreightCancellation, ShippingTask, User
|
||||
from app.services.shipping_notice.freight_cancellation_service import complete_freight_cancellation
|
||||
from app.services.shipping_notice.task_supersession_service import assert_task_not_supersession_blocked, establish_task_supersession
|
||||
|
||||
|
||||
def _tasks(*, uploaded: bool) -> tuple[ShippingTask, ShippingTask, User]:
|
||||
user = User(username=f'supersession-{uploaded}', email=f'supersession-{uploaded}@example.test', password_hash='x')
|
||||
old = ShippingTask(task_no=f'SN-SUP-OLD-{uploaded}', user_id=None, process_status='uploaded' if uploaded else 'parsed', upload_status='uploaded' if uploaded else None, freight_ref_no='F-1' if uploaded else None)
|
||||
db.session.add_all([user, old]); db.session.flush()
|
||||
old.user_id = user.id
|
||||
new = ShippingTask(task_no=f'SN-SUP-NEW-{uploaded}', user_id=user.id, supersedes_task_id=old.id, process_status='created')
|
||||
db.session.add(new); db.session.commit()
|
||||
return old, new, user
|
||||
|
||||
|
||||
def test_unuploaded_resend_voids_old_task_and_keeps_new_active(app):
|
||||
"""关键断言:未上传重发立即使旧版失效,库存入口不能继续消费旧版本。"""
|
||||
with app.app_context():
|
||||
old, new, user = _tasks(uploaded=False)
|
||||
establish_task_supersession(old_task=old, new_task=new, actor_id=user.id, reason='customer resend')
|
||||
assert old.lifecycle_status == 'voided'
|
||||
assert new.lifecycle_status == 'active'
|
||||
|
||||
|
||||
def test_uploaded_resend_requires_cancellation_receipt_before_new_can_continue(app):
|
||||
"""关键断言:已上传旧版必须先有撤销回执,后继版才恢复活动状态。"""
|
||||
with app.app_context():
|
||||
old, new, user = _tasks(uploaded=True)
|
||||
establish_task_supersession(old_task=old, new_task=new, actor_id=user.id, reason='customer resend')
|
||||
row = ShippingFreightCancellation.query.one()
|
||||
assert new.lifecycle_status == 'blocked'
|
||||
with pytest.raises(ConflictError):
|
||||
assert_task_not_supersession_blocked(new)
|
||||
complete_freight_cancellation(cancellation_id=row.id, actor_id=user.id, freight_receipt_no='CANCEL-1', receipt_asset_id=1)
|
||||
assert row.status == 'cancelled'
|
||||
assert old.lifecycle_status == 'voided'
|
||||
assert new.lifecycle_status == 'active'
|
||||
@@ -101,7 +101,6 @@ def test_chat_messages_restore_user_attachments_without_leaking_into_assistant_p
|
||||
payload={
|
||||
'existing_key': 'kept',
|
||||
'user_attachments': [{
|
||||
'id': 'attachment-1',
|
||||
'name': 'purchase-order.pdf',
|
||||
'size': 144456,
|
||||
'extension': 'pdf',
|
||||
@@ -121,7 +120,6 @@ def test_chat_messages_restore_user_attachments_without_leaking_into_assistant_p
|
||||
'role': 'user',
|
||||
'content': '总结附件',
|
||||
'attachments': [{
|
||||
'id': 'attachment-1',
|
||||
'name': 'purchase-order.pdf',
|
||||
'size': 144456,
|
||||
'extension': 'pdf',
|
||||
@@ -145,7 +143,6 @@ def test_chat_messages_do_not_create_empty_assistant_for_attachment_only_payload
|
||||
query='',
|
||||
answer='',
|
||||
payload={'user_attachments': [{
|
||||
'id': 'attachment-only-1',
|
||||
'name': 'notice.eml',
|
||||
'type': 'document',
|
||||
'source': 'shipping_notice',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
# 订单抽取服务 Dify Workflow 配置手册
|
||||
# 订单抽取服务 Dify Workflow 历史退役说明
|
||||
|
||||
> 适用范围:HXOPS 货代订单抽取内部 Workflow。本文是当前唯一有效的 Dify 画布契约。
|
||||
> 自 2026-07-27 阶段 1 起,HXOPS 订单抽取主链已完全退役 Dify Workflow、Provider 和 Runtime Binding。本文保留旧画布资料供历史 Run 与审计溯源,**不是有效配置手册,禁止按本文新建、发布或修改订单抽取 Dify 画布**。
|
||||
|
||||
> 当前有效边界:订单 Run 仅执行本地确定性模板解析;无法确定的文档进入人工复核。状态卡、重试、重新识别和审计均由 HXOPS 管理,Dify 无需任何订单抽取配置。
|
||||
|
||||
## 唯一 Manifest 配置(2026-07-22,优先执行)
|
||||
|
||||
@@ -18,6 +20,10 @@
|
||||
|
||||
人工真值暂缓时,Dify 只能把 needs_review 候选作为补充上下文。Dify 结果无论置信度多高一律为 provisional,必须由用户在 HXOPS 人工采纳后才能进入履约;不得在 Code 节点输出 `_hxops_*` 内部字段、自行把候选提升为 accepted、开启自动建单或宣称达到 95% 准确率。唯一已发布且盲测批准的确定性模板由 HXOPS 后端标记为自动采纳,Dify 不能模拟该标记。
|
||||
|
||||
### 模板路由审计(无需修改 Dify)
|
||||
|
||||
HXOPS 在每个 Unit 进入分流前追加一条不可变、脱敏的模板路由决策;该动作不新增 Start 输入、变量、节点、Tool 或 Prompt。管理员只需保持本手册的既有画布契约:当 HXOPS 因模板歧义、布局漂移、证据不足、模板未获盲测批准或行/字段门禁回退时,Workflow 照常接收原有 `execution_manifest` 并仅处理该 Unit。路由原因、候选 Profile、缺失锚点 ID 和执行路径由 HXOPS 管理端诊断展示;Dify 不读取、不回传或修改它们。
|
||||
|
||||
### 单文档证据与跨文档订单的边界(必须遵守)
|
||||
|
||||
一个 Unit 只代表 EML 正文或一份附件,不代表完整订单。EML 通常提供 PO、收货/账款信息、Reservation 或沟通上下文;PDF 通常提供订单行、料号和数量。Dify 必须分别返回当前 Document 能逐字证明的字段,**不得**要求 EML 或任一 PDF 单独具有 PO、所有必填 Header、完整订单行、Reservation 或完整订单才能通过校验。
|
||||
|
||||
@@ -75,6 +75,8 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
|
||||
|
||||
**阶段 3 当前结论(2026-07-21)**:Worker 当前按计划顺序处理单元。每个单元先使用 Run 冻结 Schema 执行确定性表格解析;只有所有 required Header/Line 字段均可由明确列关系形成逐字证据时,才直接生成动态订单并以 `execution_mode=deterministic` 成功收口,Dify 调用为零。无法完整确定的单元才调用 Dify;唯一 `execution_manifest` 只含当前 `unit`、当前 Intake 的受控只读提示和一个冻结 Document。兄弟附件、整封邮件拼接和完整 Schema definition 均不进入模型输入。模型输出的 `source_intake_no`、`primary_document_id` 和每条 Observation `document_id` 必须全部等于当前单元,否则在局部结果落库前拒绝。所有单元结果按计划顺序汇总后,仍进入 HXOPS 现有严格 Schema、逐字证据、Reservation 安全和 Candidate/Task 门禁。
|
||||
|
||||
**上传与布局准备状态(2026-07-27)**:`parse_status=parsed` 仅代表 EML/附件文本预处理完成,不代表独立文档布局任务已经终结。Intake 状态响应额外返回 `layout_status=processing/completed/not_required` 与脱敏数量汇总;聊天页在任一布局版本仍为 `queued/running` 时持续轮询、显示“正在解析订单版面”并禁止创建 Run。所有已调度布局版本进入 `ready/needs_review/failed/unsupported` 后统一视为 `completed`,其中失败或不支持不永久阻断用户,后续仍可使用已抽取文本和 Dify 兜底。后端 `ORDER_EXTRACTION_LAYOUT_PENDING` 门禁保留,防止绕过前端冻结空布局快照。
|
||||
|
||||
**阶段 3 Dify 手工配置(必须由管理员执行)**:Start 节点只保留一个 String 输入 `execution_manifest`。模型节点只读取 `document`,并把 `unit.intake_no` 写入每个订单的 `source_intake_no`、`unit.document_id` 写入 `primary_document_id` 和所有 Observation 的 `document_id`。不得遍历或期待多个 Intake/Document,不得从外部回读兄弟附件。End 仍只输出 `orders`。确定性完整表格不会进入 Dify,因此 Workflow 必须允许单个非表格/不完整文档返回零个或多个订单。
|
||||
|
||||
**阶段 4 当前结论(2026-07-21)**:非确定性单元以 Run 冻结的 `unit_concurrency=2..4` 受控并行调用 Dify;线程只持有冻结 Run/Unit 和 Provider 网络字段的纯快照,不共享 ORM Session。每个单元按 `unit_max_attempts=1..3` 独立重试,并使用 `unit_retry_backoff_ms=100..5000` 指数退避加抖动;已成功和确定性单元不重跑。主线程串行写入单元状态、结果、attempt 和 latency,并按冻结 position 汇总,完成顺序不改变业务顺序。任一单元耗尽局部重试后保留其他成功结果,再由 Job 重试恢复失败单元;全局 Provider 治理与熔断在阶段 6 完成。
|
||||
@@ -2178,6 +2180,83 @@ API 层
|
||||
- Reservation ID 使用普通文本规则;Dify 仍须按字段识别说明排除 Allocation ID、UUID 和内部主键,后端安全校验作为兜底。
|
||||
### 订单文档模板坐标标注工作台
|
||||
|
||||
#### 阶段 0:统一状态与审计契约(2026-07-27)
|
||||
|
||||
订单抽取的执行结果只使用 `deterministic`、`review_required` 和 `skipped`:前者表示固定模板已产生可验证结果;后两者表示业务处理完成但需人工处理或无需解析,均不得计入技术失败。Run 终态固定为 `completed`、`needs_review`、`failed` 和 `cancelled`;只有解析器、数据库、对象存储或 Job 等技术故障可以进入 `failed`。
|
||||
|
||||
`shipping_audit_events` 是货代域统一的 append-only 审计账本。每条记录包含 `event_type`、聚合类型/编号、Run/Task/Intake 编号、操作者、请求与关联编号、原因码、前后状态哈希、脱敏元数据和时间。它不对可删除业务对象设置外键;ORM 更新或删除会被拒绝。审计元数据严禁包含邮件/PDF 正文、订单字段值、quote、坐标、Prompt、Token、API Key 或 Provider 配置。
|
||||
|
||||
#### 阶段 1:确定性订单解析与 Dify 退役(2026-07-27)
|
||||
|
||||
订单抽取主链不再调用 Dify、Provider 或 Runtime Binding。Run 创建仅冻结文档、Schema、模板 Profile、`parser_engine_version`、`parser_policy_version` 和人工冻结策略;Worker 仅执行本地确定性模板解析。`deterministic` Unit 可写入候选结果,`review_required` 与 `skipped` 进入人工复核;只有解析器、数据库、对象存储或 Job 技术异常才使 Run 失败。
|
||||
|
||||
迁移 `08f12a3b4c5d` 已破坏性删除订单解析专属的 Runtime Binding、Provider、质量批次、Workflow 运行号及结果快照列,替换为确定性解析版本、`execution_result_json` 和 `extraction_completed_at`。通用 Agent Runtime Binding 能力仍可服务其他 Agent,但不得重新接入订单抽取。
|
||||
|
||||
订单抽取状态卡由 HXOPS 的 Run 投影恢复和更新:会话侧栏聚合未查看终态提醒,进入对应会话并成功投影状态卡后才确认已查看;用户上传锚点不重复渲染为助手卡。Dify 无需、也不应为订单抽取配置画布、变量、Prompt、Tool 或 SSE。
|
||||
|
||||
#### 阶段 2:EML 正文补充表确定性解析(2026-07-27)
|
||||
|
||||
邮件正文保持 `email_context`,但其受控 HTML 表会被确定性解析为 PO 级补充事实,而不是订单 Candidate 或订单抽取 Unit。每个补充值冻结 EML Intake、正文 Document、表格/行/列、DOM `cell_id`、原始值与规范化值;Run 仅冻结这项事实,Worker 不会对正文单独执行订单解析。
|
||||
|
||||
合并优先使用 `PO + MPN`;只有同一 PO 的正文行唯一或唯一对应一个 Reservation 时,才能以 `po_fallback` 补齐。正文可覆盖/补齐 Reservation、Allocation 与库存来源提示,但绝不覆盖 PDF 的 PO、料号或数量;`allocated_qty` 仅作审计参考。多 Reservation、多来源、行无法唯一关联和无效表头均添加 `supplement_relation_ambiguous` 或稳定解析原因,并转入人工复核。
|
||||
|
||||
#### 阶段 3:PDF 模板解析、PO 拆分与严格拒识(2026-07-27)
|
||||
|
||||
单 PDF 只有在同一个已批准模板表中、每条明细均带唯一且可验证的 PO 时,才按 PO 拆为独立订单/候选/后续任务;每个结果保留同一源 PDF 的字段证据。未证明第二个 PO 时不得臆造拆分;表级多 PO 而没有逐行归属、模板歧义、版式漂移、缺锚点或字段证据不足时,统一 `review_required`。
|
||||
|
||||
Route Decision 现在分别记录 `document_table_count`、`business_table_count`、`matched_table_count` 和 `parsed_table_count`,不得再以成功匹配数冒充文档真实表数;这些仅为脱敏计数,不保存订单值、正文或坐标。
|
||||
|
||||
#### 阶段 4:模板发布与自动冻结资格分离(2026-07-28)
|
||||
|
||||
模板版本生命周期仍为 `draft / published / retired`,仅决定模板能否参与确定性解析;它不授予自动冻结能力。每个发布 Profile 版本会单独建立 `shipping_document_profile_auto_freeze_qualifications` 记录,冻结 Profile ID/版本/checksum、Schema 版本、解析器版本和可选质量套件,状态只能是 `manual_confirmation`、`auto_freeze_approved` 或 `auto_freeze_suspended`。新版本绝不继承旧版本资格,checksum 改变即不匹配,管理员可单独暂停某一版本。
|
||||
|
||||
当前样本不足,首版发布一律写入 `manual_confirmation`,Run 的 `auto_freeze_policy.mode` 固定为 `manual_confirmation` 且 `enabled=false`。盲测、质量批次或模板发布本身均不能打开自动冻结;用户仍须完成人工确认和后续冻结门禁。
|
||||
|
||||
#### 阶段 5:人工复核与字段证据闭环(2026-07-28)
|
||||
|
||||
人工改单、增删行和字段冲突解决不再接受任意 `evidence_ref` 字符串。工作台请求必须同时带 `expected_order_data_version`、原因和结构化 `evidence`:`document_cell` 必须引用当前 Task 的当前 Extraction 中同一 Document 的 Observation,并包含页码、表格和单元格标识;`manual_input` 必须带人工确认原因。伪造、跨订单、跨 Extraction 或缺少原因的证据在写入 FieldValue 前被拒绝。
|
||||
|
||||
每项变更仍追加 `shipping_order_review_events`,保存前后值、字段/行、操作者、原因、结构化证据、当前 Extraction 和时间;编辑导致的 `order_data_version` 变化使并发旧请求失败。任务详情证据面板显示文档、页码、表格/单元格和原文 quote(存在时);未匹配模板不能通过人工整单录入绕过模板建设。
|
||||
|
||||
#### 阶段 6:统一冻结就绪门禁(2026-07-28)
|
||||
|
||||
`freeze_order_snapshot` 在同一事务以 `SELECT FOR UPDATE` 锁定 Task,并由 `freeze_readiness_service` 聚合检查当前已接受 Extraction、已确认 Bill-to、开放字段冲突、订单行、履约策略绑定的 `part_number` / `reservation_id` / 正数 `qty`,以及客户端给出的 `order_data_version`。任意失败均以 `SHIPPING.ORDER_FREEZE_BLOCKED`(或更具体的既有门禁码)拒绝,绝不写入半成品 Snapshot。
|
||||
|
||||
`shipping_order_snapshots.task_id` 现在具有数据库唯一约束。重复点击冻结返回该 Task 已有的同一 Snapshot;冻结后的所有编辑入口继续由 `assert_task_order_is_editable` 统一阻断。每个 Snapshot 新增 `source_manifest_json`,冻结 Schema/策略版本、字段裁决的 Observation、文档 hash、quote、页码/表格/单元格等 evidence metadata,以及冻结前的人工复核审计,后续履约不得回读可变 Extraction 事实重建来源。
|
||||
|
||||
首版仍只允许用户明确确认后冻结;Run 的 `auto_freeze_policy.enabled` 固定为 `false`。库存源必须在冻结后的快照上裁决,随后才允许库存/RPA 副作用,因此不以冻结前的可变路由状态作为替代条件。
|
||||
|
||||
#### 阶段 7:客户重发、版本替代与货代撤销(2026-07-28)
|
||||
|
||||
订单身份算法升级为 `shipping-v2`:强身份只使用“客户身份 + PO”,Reservation、料号、数量和库存线索进入 `shipping-content-v4` 内容指纹。因此 Reservation 改动能被识别为同一 PO 的新版本,不会误建为独立订单。
|
||||
|
||||
客户选择 `create_revision` 时,新 Intake/Task 保留为新的审计事实并建立线性 `supersedes_task_id`。未上传旧任务会立即标记 `voided`;已上传旧任务创建 `shipping_freight_cancellations`,后继任务进入 `blocked / freight_cancellation_required`,库存与导出入口会拒绝继续。必须由原任务所属用户提交货代撤销回执号和回执文件后,系统才作废旧任务并解除后继阻断。旧 Excel、上传事实和回执均不删除。
|
||||
|
||||
#### 阶段 8:库存、Excel 与上传入口门禁(2026-07-28)
|
||||
|
||||
库存匹配、Excel 生成和上传均只消费冻结 Snapshot。除工作流的生命周期检查外,`generate_shipment_excel` 与 `record_manual_upload` 也在底层复核 Task 是否 active、是否受版本撤销阻断,防止后台调用绕过。库存不足不能生成正式 Artifact;已占用 Reservation 继续通过事务内 reservation 状态控制并发。
|
||||
|
||||
人工上传不能相信客户端用户 ID:操作人来自服务端会话,并必须同时提供货代回执号及所属用户可访问、状态为 ready 的回执文件;任一缺失均拒绝标记上传完成。重复生成仍由有效 Artifact/Reservation 状态返回既有结果或阻断重复占用。
|
||||
|
||||
#### 阶段 9:安全 Chatflow(2026-07-28)
|
||||
|
||||
数据库以部分唯一索引限制只能有一个启用的 `agent_code=shipping_notice` Chatflow。Dify 导入的 OpenAPI 已缩减为 `get_task_status` 与 `get_batch_status` 两个只读接口;订单修改、冻结、库存确认、Excel、上传和目标状态推进均不再提供给 Chatflow,只能由 HXOPS 确认卡/工作台的服务端动作执行。
|
||||
|
||||
每轮输入附带 `shipping_chat_capability_token`:HMAC 签名、五分钟有效期,并绑定用户、HXOPS 会话、Agent、Task/Batch、只读 scope 和 nonce。服务端同时确认 ChatSession 所有权和请求对象,跨任务、跨用户、篡改或过期令牌一律拒绝;成功读取写入脱敏 `shipping_audit_events`,不保存 Prompt、正文或密钥。Dify 停机不会阻断解析、冻结、库存、导出与上传主链,固定错误解释仍由 HXOPS 返回。
|
||||
|
||||
##### 阶段 9 Dify 手工配置(必须由管理员执行)
|
||||
|
||||
1. 在唯一的 `shipping_notice` Chatflow 的 Start 节点声明并保留两个 HXOPS 输入变量:`agent_runtime_context` 与 `shipping_chat_capability_token`;二者由 HXOPS 每轮注入,禁止 Dify 拼接、缓存、改写或让用户输入。
|
||||
2. 删除现有货代 OpenAPI Tool,重新导入 `docs/openapi/shipping_notice_tools.dify.json`。导入后只能看到 `get_task_status` 和 `get_batch_status`;如果仍显示改单、确认、库存、Excel 或上传 Tool,停止上线并重新导入。
|
||||
3. OpenAPI 的鉴权 Header 仍使用部署环境已托管的集成 Key;禁止把该 Key 写入 Prompt、节点文本、变量默认值、知识库或对话回复。短效能力令牌必须作为每次只读请求 JSON body 的 `shipping_chat_capability_token` 原样传递。
|
||||
4. Chatflow 只能解释查询结果、固定错误和 HXOPS 渲染的确认卡;不得调用任何写接口、不得输出或假设 `status=completed`、不得把用户自然语言“确认”视为业务确认。实际修改、冻结和履约均由用户点击 HXOPS 确认卡后执行。
|
||||
|
||||
#### 模板路由决策审计(2026-07-27)
|
||||
|
||||
`shipping_order_extraction_route_decisions` 是 Unit 级、按尝试追加的路由投影。Worker 先从 Run 冻结 Profile 和布局快照计算结构化路由结果,再写入并提交投影,最后才进入后端确定性解析或人工复核。唯一键为 `(unit_id, job_id, attempt_no)`;它随 Run/Unit 清理,而长期可追溯事实写入不级联删除的 `shipping_audit_events`。
|
||||
|
||||
路由投影仅允许保存执行路径、匹配状态、Profile 编码/版本/checksum、盲测批准、候选数量、表格数量、脱敏候选摘要、稳定复核原因和缺失 `anchor_id`。严禁保存 PDF/EML 正文、订单字段值、quote、bbox/glyph、Dify Prompt/输入、API Key 或 Provider 配置。历史 Run 不补写伪造记录;如未来提供冻结快照重新评估,必须标记为 `recomputed=true` 和“非原始运行决策”。管理员诊断 API 复用既有管理员权限与访问审计,前端只读展示每个 Unit 的决策历史。
|
||||
|
||||
- PDF 工具栏采用左侧编辑操作、中间上一页/页码/下一页、右侧缩放操作的固定布局;页码输入支持大页数文档直接跳转,页面标记只按精确页码渲染。
|
||||
- 历史 `all_pages` 草稿缺少原始页码时按第 1 页恢复,重新保存后统一写入 `exact_page + page_no`,避免第 1 页标记泄漏到第 2 页。
|
||||
- 自动标记优先从 PDF 原生文字层补齐字符坐标与页面尺寸,仅在原生文字层为空时调用 OCR;补证结果仍属于待人工复核证据。
|
||||
|
||||
+20
-132
@@ -1,61 +1,5 @@
|
||||
# 2026-07-21 应用管理补充
|
||||
|
||||
- 支持独立注册 Dify Workflow 内部执行器,并隐藏对话形态等聊天专属配置。
|
||||
- 货代发货通知订单抽取只需指定内部执行器、超时与重试参数,不再重复勾选启用。
|
||||
- 内部执行器禁止用户授权,Provider 绑定、删除和历史 Run 保持生命周期门禁。
|
||||
- 用户授权、公开列表、工作台、收藏、默认应用、FAQ、指南、详情和普通 Chat 已全局排除内部执行器,并提供历史用户关系清理迁移。
|
||||
- 订单识别失败卡片支持“重试”:复用原 Run、冻结附件和 Provider 成功缓存,不要求用户重新上传文件。
|
||||
- 订单审核结果支持“按当前规则重新识别”:创建新的版本化 Run,重新冻结当前 Schema/Binding/Profile/ready 布局;旧候选只读保留,新版失败自动恢复旧版,只有当前版本可建单。
|
||||
- 订单识别可观测进度已完成:Dify Workflow 事件采集、Run 脱敏阶段投影、用户时间线、服务端健康提示、终态会话待查看、管理员只读诊断审计和90天事件每日清理均已实现;自定义节点标题不持久化,用户端不暴露 Workflow/节点/Job/Provider。当前不要求手工修改 Dify Workflow。
|
||||
- 文档级订单抽取优化:按 0–7 阶段实施。目标为确定性优先、一附件一抽取单元、邮件关系单元、受控并行 Dify、HXOPS 跨文档合并和影子验收,最终删除旧整单/全内容单次 LLM 模式;每阶段必须通过 Review 门禁后再进入下一阶段。
|
||||
- 文档级订单抽取优化阶段 1 已完成:Run 冻结动态 Schema 驱动确定性表头映射、字段规范化和校验;别名碰撞/Reservation 禁用表头阻断保存发布,重复列进入复核;无契约不猜列,且不再广播文档 Reservation 或补默认 UOM。Dify 画布无需修改。
|
||||
- 文档级订单抽取优化阶段 2 已完成:新 Run 同事务创建唯一抽取计划,邮件正文和每个附件形成独立、可恢复的持久化单元;单元具备局部状态机、尝试/结果/错误隔离和计划汇总,复合外键阻止跨 Intake 文档引用。Dify 画布暂不修改。
|
||||
- 文档级订单抽取优化阶段 3 已完成:完整确定性表格直接形成带逐字证据的动态订单并跳过 Dify;无法完整确定的单元使用唯一单文档 Manifest,禁止看到兄弟附件或跨单元引用证据。Dify 需按技术手册手工更新输入解析。
|
||||
- 文档级订单抽取优化阶段 4 已完成:单元以 2–4 并发调用 Dify,失败仅在该单元内指数退避重试;成功单元不重跑,attempt/latency 持久化,结果按冻结顺序汇总。管理端可配置并发、单元尝试次数和退避。
|
||||
- 文档级订单抽取优化阶段 5 已完成:HXOPS 按唯一 PO 或 `(part_number, reservation_id)` 强身份跨文档合并,保留所有 Observation 并将值冲突交动态 Schema 裁决;弱身份不误合并。单元部分失败时成功结果继续提交,Run 转 needs_review。
|
||||
- 文档级订单抽取优化阶段 6 已完成:支持模型单元预算、Provider 进程并发上限和短期熔断;管理员诊断可查看脱敏单元状态/尝试/耗时/错误码并保留访问审计,用户端不泄露内部信息。
|
||||
- 文档级订单抽取优化阶段 7 已完成工程门禁、但质量验收延期:自动建单默认关闭,影子模式完整落 Candidate/证据但零 Task;只有当前 Schema 的达标质量批次和不同账号双角色批准全部满足后才可开启。人工真值、100 个影子 Run、20 个测试环境 Run 与 Dify 实配尚未验收,因此不得宣称阶段完成或达到 95%。
|
||||
- 订单坐标 Profile v2 阶段 1 已完成并通过工程 Review:模板定义由静态锚点、相对表区、独立表头/明细物理行、字段区域、受控解析器、排除/终止和跨页规则组成;字段绑定冻结 `field_id + field_code`,并必须获得 Schema 对 PDF/OCR 坐标来源的显式授权。Profile 保存模板模式、训练样本计数和无正文匹配摘要;训练/标注样本、盲测样本、区域/字段绑定、草稿、执行、批准、发布/退役均追加无敏感审计。旧 HTML 网格行号/固定列定义不再允许保存,历史冻结 v1 仅保持只读回放;运行期唯一匹配、坐标解析和质量门禁将在后续阶段接入。
|
||||
- 订单坐标 Profile v2 阶段 2 已完成受控预览接口:PDF 按页低清 PNG 使用 Redis 短时单用途授权并禁止缓存;页面文本候选、OCR 触发和局部重建均要求 Profile 已绑定样本,且不返回对象存储 URL、永久 Token、原始 HTML 或整份坐标 JSON。EML 继续只使用既有白名单清洗后的文本/表格候选。
|
||||
- 订单坐标 Profile v2 阶段 3 已完成并通过工程 Review:管理端已替换为画布与配置同屏的桌面工作台,PDF 按页按需加载,区域支持选择、拖动、右下角缩放、撤销/重做和未保存离开保护;多个物理行按 `main + continuation` 连续保存,字段明确归属到行,版本历史收进右侧抽屉。页面与局部候选均不接触存储地址、HTML 或原始坐标。
|
||||
- 订单坐标 Profile v2 阶段 4 已完成并通过工程 Review:表头物理行独立于明细布局,表头字段区域可以绑定当前 Schema 字段。后端仅以 Schema 的唯一精确别名提供待确认建议;歧义、位置接近和缺失字段均保持未映射,建议永不自动覆盖人工绑定。
|
||||
- 订单坐标 Profile v2 阶段 9 已完成工程 Review:草稿可建立盲测集并显式添加训练样本;盲测样本在写入时即拒绝复用 annotation/training 文档。发布前强制训练样本、独立样本数量、至少一份多明细真值及跨页续页覆盖;批准套件随发布事务从草稿定义 hash 提升为正式 checksum,Run 仅认正式凭证。工作台提供人工真值 JSON、训练样本、执行和批准入口,四语言文案齐全;Dify 不参与此配置。
|
||||
- 订单 Schema/Profile 兼容治理已实现:稳定 `field_id` 支撑 `compatible / review_required / breaking` 三等级影响评估;Schema 发布前展示 published/draft 模板影响,published breaking 需显式确认。兼容模板运行时按当前 Schema 自动更新字段名称;破坏性字段使用受控候选或解除绑定保留坐标创建局部迁移草稿,复制训练/标注样本但不继承盲测批准,重新盲测后方可发布。历史 Run 保留原版本,Dify 无需修改。
|
||||
- PDF 模型输入优先使用 MinerU 分页文本块与表格 TSV,保留表头和行列关系;MinerU 不可用时回退原 `extracted_text`。Dify Manifest 仅携带紧凑纯文本,不包含 HTML、bbox、task 原响应或内部证据标识。
|
||||
- 订单文档 Profile 可视化治理已实现:管理员从 ready MinerU 样本文档选择表格、表头结束行/数据起始行和受控列映射;多行表头按逻辑列合并为虚拟列头后统一映射,并与明细多物理行版式独立配置。切换样本会清理旧坐标状态,避免配置区消失。结构指纹仅由后端计算;支持草稿更新、发布、删除、新版本复制和退役,重复目标字段在前后端阻断;业务管理员无需编辑 JSON、HTML、正则或脚本。
|
||||
- 坐标订单模板的逻辑明细重建已实现:数据页表头不完整时使用稳定虚拟表头;管理员确认相对列边界和固定字段映射后,系统按 x/y、字段格式和同行顺序辅助归列,合并多条物理续行,回写 `Item deleted`,在合计/说明区终止,并在模板页显示有效/删除明细及来源物理行。结果继续保持人工审核和盲测门禁,不直接提升为 accepted 履约证据。
|
||||
- 多行明细版式支持动态 N 行:模板页可增加或删除第 2..N 行,每行独立设置边界和字段,允许跨行横坐标重叠;第 1 行以 `line_no` 开始明细,后续所有行按相对顺序合并。没有固定为主行/补充行/属性行三种角色。
|
||||
- 模板页支持基于 PDF/OCR 冻结字符坐标自动识别动态行版式:既可首次自动识别全部物理行,也可只重新识别当前选中行而不覆盖其他行。工作台左侧纵向选择物理行,右侧横向编辑当前行列配置;边界尺可拖动,每个列卡片可明确在本列后新增或删除列,列卡片同步变化。实时候选全宽显示在编辑区下方。样本上传/删除与样本选择组成同一控件组,基础字段按内容宽度紧凑排列,低频参数收进高级设置。
|
||||
- L0 人工真值辅助继续保持非生产隔离:新增 PDF 原生字符坐标严格对齐候选,仅接受唯一、同视觉行、连续且非重叠文本;30 份真实 PDF 复评仍不足以自动生成完整 cell 真值,因此未开放 LayoutCell 自动接受、自动建单或 95% 准确率声明。
|
||||
- L1 文档布局生命周期已实现:Document 使用独立递增布局版本和当前成功引用;布局任务支持幂等调度、parser revision 防漂移、lease 防旧 Worker 回写、超时恢复、尝试耗尽、payload 大小门禁、级联删除、管理员脱敏诊断和显式重解析。人工真值延期不阻塞该生命周期,但继续阻断 cell 自动接受与准确率声明;Dify 无需修改。
|
||||
- L2 原生 PDF 工程能力已实现:PDFium 提取真实字符 bbox,MinerU HTML cell 通过唯一文本对齐或严格有框表 OpenCV+全文本门禁生成可追溯 token/cell 候选;只保存表格区域 token,失败逐表隔离,revision 升至 v2。候选固定 needs_review;人工真值、准确率和性能验收延期,因此未进入 OCR 自动接受,Dify 无需修改。
|
||||
- L3 OCR/HTML 工程能力已实现:RapidOCR 多边形坐标经页面缩放后,仅在 OpenCV 网格与全部 cell 文本一致时生成 OCR token/cell;EML HTML table 经主动内容白名单清理并按 DOM 合并格生成逻辑布局。email_body hash 覆盖清洗表格,HTML 不进入摘要/Dify,revision 升至 v3。候选固定 needs_review;真实扫描质量/P95 验收延期。
|
||||
- L4 Schema 证据映射已实现:layout.v1 Table 复用冻结 Schema 精确表头规则,字段保留真实 cell_id/token_ids/evidence_ref;支持后置表头、重复列阻断、零 Qty 和显式跨页 continuation。Run snapshot 升至 v3并冻结内部 candidate,Manifest 全部剥离;无 accepted 自动消费,真实映射准确率待人工真值。
|
||||
|
||||
# 智能HR请假管理功能清单
|
||||
|
||||
## 订单级字段标注与确定性提取
|
||||
|
||||
- 已实现独立订单字段标注域(订单字段标签、值区、单行/多行模式、停止标签),与明细表头和物理行完全分离。
|
||||
- 已实现页级 PDF/OCR 字符证据的锚点定位与相对区域读取;仅唯一原生坐标、格式校验通过的结果可标记 `confirmed`,其余进入 `needs_review` 或 `unavailable`。
|
||||
- 已实现盲测订单字段真值、发布门禁与运行时合并;Dify 不得覆盖 `confirmed` 字段,配置说明见 `docs/features/shipping-notice/order-extraction-workflow-dify-guide.md`。
|
||||
|
||||
## 货代订单抽取异步 Run(阶段 0–5 已完成)
|
||||
|
||||
- 已实现 `ShippingOrderExtractionRun` 领域生命周期、不可变 Intake/Document/Schema 输入快照和服务端幂等键。
|
||||
- 已实现工作台 Run 创建、单条查询和按会话列表 API;权限同时校验用户、货代入口 Agent、ChatSession 和 Intake 归属。
|
||||
- 已实现同一 Intake 单活跃 Run 数据库约束及 `result_persisted` 不可回退状态门禁。
|
||||
- 已实现 `shipping.order_extraction` 能力声明、`agent_runtime_bindings` 显式绑定、内部 Workflow Provider 可见性隔离,以及 Agent/绑定原子保存;业务代码不写死 Provider ID 或 App ID。
|
||||
- 已实现 Run 与 Job 同事务创建、后台 Worker 调用专用 Dify Workflow、结构化 `orders` 校验、Provider 成功结果独立提交、超时重试和事实恢复;API Key 可轮换,App ID/Base URL 漂移会阻断旧 Run。
|
||||
- 已完成阶段 0 模型—迁移一致性 Review:Provider 配置/身份快照使用独立增量迁移,数据库、SQLAlchemy 模型、外键和索引可完整核对,Candidate/Extraction/Run 查询不再因缺列失败。
|
||||
- 已完成聊天前端 Run 驱动切流:订单附件发送不再调用普通 Chatflow,支持服务端新建会话、状态卡原位更新、刷新恢复与活动 Run 续轮询。
|
||||
- 已实现轮询生命周期隔离、网络失败退避和状态签名持久化,避免切会话后旧响应污染及每两秒重复写 ChatLog。
|
||||
- 已实现 Run 失败映射 Intake 可重试状态,已提交附件从输入栏移除但保留用户消息安全附件快照。
|
||||
- 普通无附件聊天仍使用 `/api/chat/completions`;旧 Chatflow 抽取分支、后台 Task Chatflow 执行器和专属 SSE 已删除。
|
||||
- 已实现阶段 4 管理员 Run 健康汇总:积压、失败率、重试、状态/阶段/错误码和四段耗时可查询,返回安全聚合数据。
|
||||
- 已实现 Worker 安全关键节点日志,支持按 `run_no + job_id + attempt` 追踪 Provider 与 HXOPS 落库边界。
|
||||
- 已实现前端 Run GET 10 秒超时与切会话取消;取消查询不取消后台 Run,不伪造业务失败。
|
||||
|
||||
## 设备维保助手
|
||||
|
||||
| 功能项 | 状态 | 说明 |
|
||||
@@ -83,12 +27,11 @@
|
||||
| --- | --- | --- |
|
||||
| Chat 内培训工作区 | 前端已实现 | 在培训 Agent 聊天页顶部提供视频学习、知识点复盘、逐题考试、成绩结算的一体化工作区 |
|
||||
| Chat 内 HR 管理面板 | 已实现 | 仅具备培训 HR 管理权限的用户可在同一聊天页查看真实培训统计、筛选记录并导出 Excel;权限支持角色默认值与前端用户配置共同控制 |
|
||||
| Chat 附件发送前预览与已发送回放 | 已实现 | 附件列表在发送前显示于输入框上方,展示文件类型、名称、真实大小和逐文件处理状态;发送成功后转为用户消息气泡上方的只读附件快照,并可随历史会话刷新恢复;支持输入区删除、上传中保护删除,发货通知保留解析重试与重复处理入口 |
|
||||
| Chat 附件发送前预览 | 已实现 | 附件列表显示在输入框上方,展示文件类型、名称、真实大小和逐文件处理状态;支持右上角删除,上传中保护删除,发货通知保留解析重试与重复处理入口 |
|
||||
| 培训题库后台配置 | 已实现 | Agent 管理表单支持维护及格线、复盘要点、考前清单与题库;员工培训页优先读取 `extra_config.training_config`,未配置时才回退前端默认题库 |
|
||||
| 培训聊天常见问题分角色配置 | 已实现 | Agent 管理表单支持分别维护普通员工与 HR 管理员进入“员工培训”聊天页时看到的常见问题;聊天欢迎区会按 `training_hr_manage` 权限自动切换对应问题集 |
|
||||
| 培训 HR 统计问答兜底 | 已实现 | “员工培训”聊天页中,HR 管理员提问参训人数、通过率、未完成名单、本月成绩统计及考试明细等固定统计问题时,优先走后端本地统计兜底;明细列表会把培训阶段映射为中文(观看视频/知识点复盘/逐题考试/结束),并统一把考试时间、完成时间格式化为年月日,避免当前 Dify 工作流 SQL 改写异常导致问答失败 |
|
||||
| 管理端培训模式配置 | 已实现 | Agent 管理表单支持显式开启培训工作区;平台应用说明页支持上传并标记“员工培训视频 / 员工培训试题 PDF”,并可直接把试题 PDF 解析导入题库表单;扫描件 PDF 在 OCR 依赖齐备时也可回退识别 |
|
||||
| 培训视频 iOS 兼容播放 | 已实现 | 培训视频统一通过 HTTPS 站点同源接口访问 MinIO 文件,支持 Range/206 分段响应与 iOS 企业微信内联播放,避免生产 HTTPS 页面直连 HTTP MinIO 导致视频被拦截 |
|
||||
| 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 |
|
||||
| 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 |
|
||||
| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案;培训 Agent 对接 Dify 时会额外透传后台账号 `role`,便于区分学员/HR 问答分支,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) |
|
||||
@@ -119,79 +62,37 @@
|
||||
| 业务去重与任务版本(Phase 3) | 已实现 | Intake 业务指纹/重复决策、修订版本链、强制新建权限与审计;见技术手册第三节摘要 |
|
||||
| EML 附件提取(阶段一) | 已实现 | 结构化解析主题/发件人/正文与真实附件;`message/rfc822`/附件型 multipart 独立登记;完整性门禁与容器计费;见技术手册「EML 附件提取」 |
|
||||
| EML/附件上传预处理 | 已实现 | 上传后自动创建 Intake,解析邮件正文/真实附件并派生 FileAsset/Document;上传阶段不调用 LLM、不生成 Candidate、不判订单重复;解析失败、超时、取消和资产引用补偿保持幂等 |
|
||||
| 点击发送完整订单抽取 | 已实现(Run 驱动) | parsed Intake 直接创建后台 Run;状态卡支持刷新恢复、活动轮询、失败重试;订单抽取只调用显式绑定的内部 Workflow,旧 Chatflow 分支已删除 |
|
||||
| 订单识别生命周期反馈 | 已实现 | 独立 Run API 返回 queued/running/result_persisted/终态;前端 Run 状态卡轮询并持久化恢复,普通聊天 Handler/SSE 不再承载订单抽取状态 |
|
||||
| 订单识别断流与重复执行保护 | 已实现 | 同一 Intake 仅允许一个未释放 Run;Provider 结果先独立提交,HXOPS 持久化重试不重复调用 Dify;浏览器断流或切会话不取消后台作业 |
|
||||
| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 使用 `shipping-v1` 身份指纹与 `shipping-content-v4` 内容指纹;高置信 `part_number`+Qty 订单可自动建 Task;缺失/非法 Reservation、未解决字段冲突继续阻断下游,库存源线索统一为 `inventory_source_hint` |
|
||||
| 订单解析结果持久只读展示 | 已实现 | Task Detail 顶层投影 `order_header` / `order_header_fields` / `order_line_fields` / `lines` / `parse_validation` / `process_field_gate` / `source_candidate`;右侧工作台按任务锁定 Schema 的显示名称和 `sequence` 展示订单信息与动态明细列,避免前端写死字段顺序;Candidate 审核非编辑态同步展示关键行 |
|
||||
| 动态订单解析真相 | 已实现 | Task 通过 `current_order_extraction_id` 追溯 `ShippingOrderExtraction/Line/Decision/FieldValue`;它们只承载解析结果。订单冻结后由 `order_snapshot_id` 供库存、RPA、匹配和导出读取,旧 `shipping_task_lines`、`lines_json` 和兼容投影不恢复。 |
|
||||
| 货代字段分层与冻结策略(阶段 1) | 已实现,Review 通过 | 平台系统事实与 57 个订单标准字段目录分离;字段可按版本启用而非全量必填。`customer_po_number` 是客户 PO;固定 `SHIP_AVAILABLE_ROLLING_V1` 仅校验 `reservation_id + part_number + qty>0 + 已确认客户`,自定义字段仍可随 Snapshot 冻结;`inventory_source_hint` 保持可选 Line 路由线索。 |
|
||||
| 字段能力绑定与版本化履约策略(阶段 2) | 已实现,Review 通过 | 独立策略版本按稳定 `field_id` 绑定受控货代能力;冻结策略定义避免新发布版本重解释历史订单。 |
|
||||
| 履约策略管理闭环(阶段 3) | 已实现,Review 通过 | 管理端仅列出四项注册能力与当前 published Schema 中 scope/type 相符的字段;创建草稿、乐观锁发布和旧版本退役均由后端裁决,API 不能绕过 Schema 纳入门禁。 |
|
||||
| Schema-策略反向依赖门禁(阶段 4) | 已实现,Review 通过 | Schema 发布反查当前 published 策略绑定,不能移除仍会被冻结、库存、制单与上传使用的字段;与路由/Profile/模板引用统一阻断。 |
|
||||
| 迁移后管理员重建顺序(阶段 5) | 已实现,Review 通过 | 明确按 Schema → 策略 → 文档/库存 Profile、路由、模板 → 停用源测试 → 启用源重建;库存测试与订单履约状态独立,不能绕过策略冻结门禁。 |
|
||||
| 冻结入口策略发布门禁(阶段 6) | 已实现,Review 通过 | 即使 Schema、字段值与订购客户均有效,未发布履约策略仍会以 `SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED` 阻断冻结且不写入 Snapshot。 |
|
||||
| 履约策略管理 API 验收(阶段 7) | 已实现,Review 通过 | 普通用户不能发布策略;管理员只能在当前 Schema 已发布并包含绑定字段时发布策略,前端与服务端门禁一致。 |
|
||||
| PostgreSQL 完整迁移链(阶段 8) | 已实现,Review 通过 | 隔离 PostgreSQL 空库从初始 revision 升级至 `027d8e9f0a1b`;修复历史迁移的空库分支假设后,57 字段目录与快照物理结构均通过核验。 |
|
||||
| 管理员重建演练(阶段 9) | 已实现,Review 通过 | 隔离库实际发布最小四字段 Schema 与 `SHIP_AVAILABLE_ROLLING_V1`,验证目录可选与策略显式发布路径;Profile/路由/模板/RPA 仍按上线清单手工重建。 |
|
||||
| Reservation 全局唯一与修订门禁(阶段 1) | 已实现,待阶段 Review | 单列 Reservation 唯一约束绑定标准化 PO;不同 PO 或同一快照内重复一律阻断,同 PO 内容变更返回人工差异确认,已有有效 Artifact/上传时禁止直接修订。 |
|
||||
| 订单字段对账与冲突复核 | 已实现 | Candidate→Task 字段级自动补空/冲突落库;未解决冲突阻断库存/匹配/导出;workspace 冲突查询与解决 API;改单支持 `expected_order_data_version` 与幂等键;工作台解析卡可解决冲突 |
|
||||
| 库存源/RPA Profile 数据库主数据 | 已实现 | 以 Inventory Source 为业务主键;Source 持久化 DBS 报表路径与查询参数;订单到站点的选择统一由路由规则维护;RPA Profile 仅保存登录、密文凭据与连接级登录配置;YAML 不再作为运行时真相源 |
|
||||
| 货代管理工作台 | 在建(导航补齐) | 管理端“货代管理”按“订单识别、库存管理”组织业务入口:订单识别依次提供订单字段规则、订单文档模板、客户识别规则和识别任务;库存管理工作台依次维护库存字段与解析、系统连接、库存站点、仓库映射、路由规则和发货模板,并将库存快照、导出记录归入运行与审计。各页面复用货代管理权限,现有深链保持兼容。 |
|
||||
| 发货模板可读配置 | 已实现 | 模板上传后读取工作表与首行表头供选择目标列;映射逐项展示字段说明和来源分组;文件名规则显式展示可用业务变量,默认推荐 `{business_no}.xlsx` |
|
||||
| 通用库存源路由规则 | 已实现 | 可配置、版本化规则从订单事实产生 `source_code` 候选;Reservation ID 仅为首批兜底事实字段 |
|
||||
| 库存文件优先匹配 | 已实现 | 正常货代流程按 `source_code` 匹配最新有效库存文件,不自动触发 RPA;RPA 仅由排程或用户手动刷新执行 |
|
||||
| 上传与订单版面准备状态一致性 | 已实现 | Intake 状态接口独立汇总文档布局任务;聊天附件在 `queued/running` 时显示“正在解析订单版面”、持续轮询并禁止过早发送,所有布局任务终结后才允许创建订单识别 Run;布局失败或不支持进入人工复核,不调用 Dify 兜底 |
|
||||
| 点击发送完整订单抽取 | 已实现 | Run 冻结文档、Schema、模板 Profile 和确定性解析器版本;Worker 只执行本地模板解析,支持一附件多订单、证据门禁、幂等重放及人工复核,不依赖 Dify、Provider 或 Runtime Binding |
|
||||
| 订单识别生命周期反馈 | 已实现 | Run 状态卡按真实确定性解析进度和终态计数更新并持久化到 `ChatLog.payload`;聊天历史可恢复,侧栏显示未查看终态提醒,处理中不伪造百分比 |
|
||||
| EML 正文补充表合并(阶段 2) | 已实现 | 正文 HTML 表解析为带 DOM 单元格证据的 PO 级补充事实,不创建独立订单或执行 Unit;按 `PO + MPN`、受限 PO 降级补 Reservation/Allocation/库存来源提示,PDF 数量保持权威,歧义统一进入人工复核 |
|
||||
| PDF 模板 PO 拆分与严格拒识(阶段 3) | 已实现 | 已批准模板中每条明细均有唯一 PO 证据时,单 PDF 自动拆为多个独立订单;表级多 PO 未能归属明细、模板歧义、漂移和证据不足统一转人工复核,Route Decision 分别审计四类表计数 |
|
||||
| 模板发布与自动冻结资格分离(阶段 4) | 已实现 | Profile 的发布仅允许确定性解析;每个发布版本独立冻结人工确认资格,首版强制 `manual_confirmation` 且自动冻结关闭,盲测批准、旧版本资格或 checksum 变化均不能越过该门禁 |
|
||||
| 人工复核与字段证据闭环(阶段 5) | 已实现 | 单头、订单行、冲突解决均要求乐观锁、原因和结构化 `document_cell`/`manual_input` 证据;跨订单或伪造证据在写值前拒绝,复核审计保存结构化证据且详情页展示页码、表格、单元格与原文 |
|
||||
| 多订单 Candidate 判重与自动建批 | 已实现 | Candidate 身份/内容双指纹;高置信 SKU+Qty 订单自动建 Task,低置信/冲突/修订保留待处理;部分消费 Intake 不丢剩余订单;缺 Reservation/Source Type/Hub Code 的 Task 停在自然对话补字段门禁 |
|
||||
| 库存 RPA 源 YAML 配置 | 已实现 | `backend/config/shipping_inventory_sources.yaml`,新增 Warehouse 只改 YAML |
|
||||
| 订单解析阶段库存源判定 | 已实现 | `parse_notice` 内 adjudicate 写线索;低置信度先 `parse_review`,解析通过后再 `inventory_source_review`;稳定态 `resolved`/`user_confirmed` |
|
||||
| 文件解析阶段问题清单 | 已实现 | 步骤 2 工作台/`ui_state.summary.issues` 一次列出解析复核、RSV、库存源门禁与 parse warnings |
|
||||
| 发货通知关键字段真值校验 | 已实现 | LLM 出候选、后端裁决;支持多模板 Reservation 别名,拒绝 32 位 hex/UUID;仅按 TSV 列关系与唯一 SKU/APN/MPN 证据纠错;`parse_validation` 留痕,blocking issue 在解析确认和库存匹配前双重阻断 |
|
||||
| 唯一订单 Schema 与动态字段基础 | 已实现 | 管理员以固定高度字段字典维护系统标识、版本显示名称、位置、格式和识别规则;两个名称不受“纳入当前版本”开关限制,未纳入字段配置可保存但不进入发布契约;系统标识可重命名且历史快照保留旧值,位置/类型与已发布版本保持安全门禁;管理端提供分页版本历史、严格只读快照、任意版本间服务端字段级差异、追加式配置审计时间线、版本实际使用统计和单次解析证据链;历史发布/退役版本可复制为新草稿,URL 可按业务版本号恢复;新版本移除下游引用字段时阻断发布 |
|
||||
| 通用上下文字段目录与运行时 | 已实现(阶段 3、5) | 复用订单解析字段目录,按通用上下文字段/订单信息/货品明细分组;迁移自动在当前草稿补齐发件人邮箱/企业域名两个完整字段配置,管理员审核后发布。首批受控来源为 EML From 邮箱/域名。Run 按 Intake 冻结规范值,Extraction 独立写入 Observation→Decision→FieldValue 与审计快照;缺失/非法/多地址不做其他来源兜底,公共域名保留真实值。Dify 契约和 documents 输入隔离确定性上下文;Schema 发布可审计地控制 `never`、受控不可逆 `redacted`、Run 冻结值 `confirmed_readonly`,并通过独立 `readonly_context` 只读输入按 Intake 传递。 |
|
||||
| Schema 驱动 Dify 订单解析 | 已实现 | Worker 向专用 Workflow 传入冻结 published Schema 与 Document;Workflow 按稳定 field_id 返回 Observation,后端完成类型校验、原文核验、跨文档裁决和类型化值持久化 |
|
||||
| 订单文档解析 Profile | 已实现 | 版本化草稿/发布/退役、Schema/field_id 绑定、服务端结构指纹、固定注册解析器、Run 快照和 Worker 精确匹配已完成;管理端可从 MinerU 样本维护表头结束行、数据起始行和列映射,多行表头会合并为虚拟列头且与明细多物理行版式独立配置,无自由 JSON/脚本入口 |
|
||||
| 文档布局版本与任务生命周期 | 已实现(L1) | 独立布局版本/Job、当前成功引用、parser revision、checksum/大小门禁、lease/超时恢复、重试耗尽、管理员诊断和显式重解析已完成;人工 cell 真值延期,不开放自动 accepted 或 95% 声明 |
|
||||
| 原生 PDF 结构候选 | 工程已实现(L2 质量待验收) | PDFium 字符 bbox、稳定 token/cell、唯一文本对齐、OpenCV 有框表双门禁、逐表故障隔离和 revision v2 已完成;候选固定 needs_review,人工真值/准确率/P95 未验收 |
|
||||
| 扫描 PDF OCR 与 EML HTML 布局 | 工程已实现(L3 质量待验收) | RapidOCR 坐标/置信度、OCR+网格+全文本门禁、HTML 主动内容清理、DOM rowspan/colspan、hash/摘要隐私和 revision v3 已完成;候选固定 needs_review,真实扫描质量/P95 未验收 |
|
||||
| 冻结 Schema 与 cell 证据映射 | 工程已实现(L4 质量待验收) | layout.v1→Grid→冻结 Schema、真实 cell/token evidence、后置表头、重复列、零 Qty、显式 continuation、Run snapshot v3 和 Dify 隔离完成;candidate 不自动接受,真实准确率未验收 |
|
||||
| 订单字段全局显示顺序 | 已实现 | 字段目录独立保存 `display_sequence`,同分类拖拽后静默持久化且刷新保持;当前字段页、已发布/历史版本详情和对话订单信息均按全局顺序展示,历史已删除字段回退版本快照顺序 |
|
||||
| 动态订单字段驱动库存源路由 | 已实现 | 路由条件选择 published 订单稳定 field_id;运行时从 Task 当前 Extraction 的类型化 FieldValue 读取;系统事实仅保留受控枚举 |
|
||||
| 可复用库存解析 Profile | 已实现 | 管理端通过订单字段和库存标准字段结构化选择器版本化维护表头、列映射和 match_keys;多个 published 版本可并存,库存源显式迁移版本;引用中版本不可退役,正常库存源解析无需 LLM |
|
||||
| 库存字段目录 | 已实现 | 作为“库存映射”的子功能以空目录启动,字段名称、说明、格式、用途和顺序完全由用户维护;程序只控制匹配、数量、仓库识别和一般信息四种用途。解析方案、库存行、匹配键和发货模板全程使用库存字段目录 ID;未引用字段可物理删除,当前配置引用字段禁止删除、退役或改变能力用途 |
|
||||
| 库存样本结构识别与方案复用 | 在建 | 管理员上传 `.xls/.xlsx/.csv` 后由后端分析工作表、候选表头、真实栏位、类型和空值率;样本原件即时分析后清理,草稿/发布版本绑定并保留文件校验值、结构指纹、完整表头和最多五行脱敏样例。再次打开草稿会恢复已保存样本结构、表头下拉和脱敏预览,无需重传原文件;替换样本先展示结构/映射差异,平台确认后才切换,并保留旧/新样本审计链;后续阶段补齐运行闭环;Dify 仅可提供陌生表头候选,不自动生效。 |
|
||||
| 库存站点测试导出 | 已实现 | 停用库存站点可发起单站点或批量异步 RPA 测试导出;批量按相同 RPA Profile 分组复用一次登录,逐站点保持独立运行、状态与错误,部分失败可定向重试。当前绑定的已发布解析方案验证通过(含无库存的查询成功)且正式门禁齐全时,后端自动启用站点;无需人工确认解析或点击启用。测试文件不进入正式库存快照、订单匹配或发货导出;站点或连接配置变更后旧测试自动失效。 |
|
||||
| 零库存验证与空快照 | 已实现 | RPA 查询成功但无库存记录为 `completed_empty`,不再误报测试失败;固定仓保留“首次非空文件待数据行验证”提示,动态仓仍要求非空样本验证仓库识别;调度空结果写 `empty` 审计快照且永不参与库存匹配或发货 |
|
||||
| 库存站点启用验证与仓库映射门禁 | 已实现 | 启用前按用户字段用途复核至少一个匹配字段、唯一数量字段及动态仓唯一仓库识别字段,验证发货模板库存字段可由解析方案提供;固定仓要求精确或默认仓库映射,动态仓要求覆盖样例仓库;后端以结构化 `activation.checks` 返回状态、阻断、推荐动作与脱敏证据,配置变更后旧测试明确为 `stale`;只提示缺失映射,绝不自动臆造 |
|
||||
| 正式库存文件结构漂移门禁 | 已实现 | 每次 RPA 正式导出及缓存快照重读均用已绑定库存文件解析方案复核/解析格式、工作表、表头和核心栏位;完全一致放行,非关键栏位变化记录差异后放行,关键变化阻断快照和库存匹配;正式库存站点运行期不再自动猜列或接收 LLM 映射覆盖 |
|
||||
| 陌生表头 LLM 候选解释(Dify 手工配置) | 已文档化 | 默认关闭;用户明确声明对话附件为库存文件且后端无精确方案时,可对脱敏真实表头给出本次临时候选;管理员也可在库存文件解析方案草稿中主动请求候选。Dify 不能发布方案、绑定库存站点、创建仓库映射、调用旧库存映射 Tool 或放行结构漂移 |
|
||||
| 对话临时库存文件受控解析 | 已实现 | 用户上传 `.xls/.xlsx/.csv` 表格时必须先明确声明为库存文件,系统不会按后缀猜测用途;后端创建当前用户和当前聊天会话隔离的临时文件并确定性检查结构与库存最低特征。跨回合时由 HXOPS 数据库恢复最新待确认会话号,不依赖 Dify 隐式记忆;普通消息不会因此自动进入确认。无完全匹配方案时 Dify 只能基于真实表头、类型/空值率和字段目录提交受控候选映射,用户明确确认后仅锁定本次临时质量审计;不创建正式库存快照、不修改库存站点、不执行订单匹配。管理员可将确认会话沉淀为解析方案草稿,仍需走既有发布门禁 |
|
||||
| 版本化发货 Excel 模板 | 已实现 | xlsx 存私有 MinIO,管理端通过后端白名单结构化配置稳定订单字段/库存字段/系统事实映射并发布;支持从已保存模板创建新草稿版本,无需重复上传,只有 Excel 结构变化时才替换文件;已回写 AWS PVMI V1 草稿,支持上海业务时区导出日期及订单信息字段重复写入每条货品明细;订单与库存按 Profile match_keys 关联,多库存源共享模板,生成时保存不可变 Artifact 与版本/checksum 审计 |
|
||||
| 发货 Excel 批次 ZIP 下载 | 已实现 | 工作台支持按批次或显式勾选当前页任务下载每票当前有效 Artifact;显式选择最多 100 票并在刷新、筛选或切页后清空,服务端重新执行权限校验、同名消歧、checksum 校验并附 manifest,纠错失效或损坏票据不静默混入 |
|
||||
| 发货任务列表分页 | 已实现 | 工作台每页 10 条,后端按用户和筛选条件执行分页计数;返回当前页与总数,筛选/刷新重置第一页,任务选择仅限当前页 |
|
||||
| 发货任务处置生命周期基础 | 已实现 | 独立 `active/voided/archived` 生命周期与回收站字段;删除/作废/归档写任务审计。上传中、已上传或已有外部回执的任务仅允许归档,禁止平台单方作废 |
|
||||
| 发货任务批量处置与回收站 | 已实现 | 工作台按当前页批量删除、归档、恢复;服务端逐票行锁鉴权及资格复核,返回部分成功明细;管理员可永久清除无引用纯误建任务并保留独立快照审计;Dify 无需调整 |
|
||||
| 订单料号领域模型升级 | 已实现 | 主字段为内部料号 `part_number`;可选 `customer_part_number` / `aws_part_number`;三种料号必须原子化且禁止 `/`;当前字段模型不接受旧 `sku / vendor_part_number / customer_sku` |
|
||||
| 后端与 Dify 字段级交叉裁决 | 已实现 | 两侧输出不可变 Observation;后端统一验证 evidence、评分并生成规范投影;一致标记 consensus,高可信冲突或分差不足写 Candidate 阻断冲突;Observation 历史只追加不覆盖 |
|
||||
| Bill-to/Ship-to 客户角色匹配 | 已实现 | 订单模板解析账款客户、送货对象、外部编码、来源系统和地址原文;后端优先按外部编码匹配标准客户/送货站点,名称与审核别名回退;客户简称仅由 Bill-to 主数据派生,Candidate 展示角色匹配状态并提供权限受控确认接口 |
|
||||
| 内部料号库存匹配 | 已实现 | 主匹配键为 `(part_number, reservation_id)`;库存 `Supplier Sku` 对应内部料号,`AWS Sku` 仅作为可选 `aws_part_number`,AWS-only 库存表不能形成有效主匹配行 |
|
||||
| 库存源人工确认与 Gate | 已实现 | `confirm_inventory_source`;RPA/匹配/Excel/上传硬阻断;独立 DB 字段持久化 |
|
||||
| Warehouse 统一解析与 Excel 真相源 | 已实现 | 固定 Source 取配置 Warehouse;Crane 从 `reservation_id + part_number` 命中库存行取 Warehouse;未解析时禁止生成 Excel |
|
||||
| 库存快照 TTL 复用 | 已实现 | 按 `source_code` 复用最新有效文件,不再使用 `site_id`;动态多仓按 `run_no + source_code` 幂等 |
|
||||
| 库存 RPA 批量导出(DBS/Crane) | 已实现 | 排程以 `source_codes` 为目标,按 RPA Profile 分组登录且每个结果独立归档 Source |
|
||||
| 库存每日定时导出排程 | 已实现 | 排程生产库存文件;正常任务仅消费文件,手动刷新才执行按需导出 |
|
||||
| 库存快照身份校验 | 已实现 | link 时校验 `source_code`/`site_id`/`warehouse_id` 与任务一致 |
|
||||
| 库存快照 TTL 复用 | 已实现 | `inventory_snapshot_store`,按需任务优先复用未过期快照 |
|
||||
| 库存 RPA 批量导出(DSV/Crane 一次登录) | 已实现 | `inventory_export_batch` trigger + worker + `/rpa/inventory-batch-ready` |
|
||||
| 库存每日定时导出排程 | 已实现 | `schedule_type=platform_job` + `platform_api_path=shipping-inventory-rpa`,cron 建议 `0 3 * * *` |
|
||||
| 库存源至外部系统仓库映射 | 已实现 | 维护精确与 Source 默认映射;当前仅后台维护和后端内部 Service,不开发 Tool API 或调拨逻辑 |
|
||||
| 建单防重复(第一阶段) | 已实现 | 批次 `create_idempotency_key`、任务 `source_content_hash`、同请求去重、幂等重放 |
|
||||
| 客户身份与业务编号规则 | 已文档化 | 内部 `SN-...` 与业务号分离;业务号固定为 `客户简码 + YYMMDD + 两位流水`,例如 `WYC26071501`,日期口径 `Asia/Shanghai` |
|
||||
| 客户主数据与识别证据 | 已实现 | 工作台「货代发货 → 客户主数据」二级目录(仅管理员可见);维护标准客户、唯一简码、名称别名、邮箱/域名、模板指纹、审核与停用管理 |
|
||||
| 客户可配置识别规则 | 已实现(阶段 4) | 识别定义只引用当前 published Schema 中 `available_for_customer_identity=true` 的 Header `context_field_id`;来源适配器下拉、邮件元数据旁路、模板指纹和重复 normalizer 配置已删除。运行时只消费 Candidate Extraction 的 accepted/corroborated FieldValue;规则发布重校字段可用性,字段退役受定义及规则快照阻断。旧规则、证据与影子快照按不兼容迁移清理。 |
|
||||
| 客户删除资格预检 | 已实现 | 管理员可查询业务单、业务流水、外部来源、导入与影子识别审计引用;仅识别证据允许作为未来永久删除的级联数据,前端不得以业务单数自行判断 |
|
||||
| 客户受控永久删除 | 已实现 | 管理员在预检无阻断时输入当前简码和删除原因;后端锁定客户并重算引用,任一新增或既有引用均返回冲突,成功后保留快照审计并级联删除识别证据 |
|
||||
| 客户受控合并 | 已实现 | 管理员预览历史保留与未来配置迁移后,输入源简码和原因归并至启用目标客户;历史业务/编号/审计不改写,识别证据和来源键迁移,源客户标记为 merged 并不可再用于新任务 |
|
||||
| 期初客户导入与对账 | 已实现 | 标准 Excel 模板、上传暂存、预检查重、冲突决策、单事务发布、来源键幂等重导和 CSV 对账 |
|
||||
| 客户影子识别 | 已实现 | Candidate 抽取后记录客户候选、证据和版本;支持人工真值标签与准确率报告,不绑定、不编号、不阻断现有货代流程 |
|
||||
| 客户人工确认与 Gate | 已实现 | `customer_review`;业务用户从标准客户主数据中确认,客户未稳定时阻断库存源、RPA、匹配、Excel 和上传 |
|
||||
| 货代业务编号 | 已实现 | 客户确认后按 `Asia/Shanghai` 原子生成 `WYC26071501` 类业务号;每客户每日 `01-99`,修订继承、强制新建重新编号 |
|
||||
| 受控自动客户识别 | 已实现 | 自动确认消费字段驱动的冻结规则快照,交叉校验历史订单 Schema、Extraction、Decision、FieldValue、审核授权证据、active 客户、唯一命中、公共域名与质量阈值;任务事件保存完整追溯主键,任一快照漂移或链路不一致均转人工复核。 |
|
||||
| 受控自动客户识别 | 已实现 | 仅对 approved 且允许自动匹配的邮箱/非公共域名/模板指纹开放;唯一命中才自动确认,默认关闭;管理端可查询自动裁决、自动确认、历史回填和“原号作废 + 新号替代”纠错审计 |
|
||||
| 客户治理闭环 | 已实现 | 客户与识别证据关键变更记录快照时间线;简码、状态、自动匹配授权必须填写原因。自动确认在总开关外再受有效人工标注样本量(默认 20)与准确率(默认 98%)门禁约束,未达标保持 `customer_review`;客户主数据页展示时间线和降级原因 |
|
||||
| 产品原型 | 已文档化 | 见 [docs/prototype/shipping_notice_agent_prototype.md](prototype/shipping_notice_agent_prototype.md) |
|
||||
| 滚动履约领域契约(阶段 0) | 实施中 | 冻结 `SHIP_AVAILABLE_ROLLING`、预置核心字段与可配置扩展字段、Snapshot 正式真相、预约单全局注册、Artifact/Attempt 拆分、LLM 人工复核门禁;扩展字段是否进入库存/Excel/RPA 由已发布业务配置决定;Excel 命名由已发布模板规则优先、环境变量受控回退,最终规则在 Artifact 审计冻结。 |
|
||||
| 订单冻结就绪门禁(阶段 6) | 已完成 | 冻结前聚合校验已接受抽取、客户确认、字段冲突、最小履约字段、正数数量和版本;Task 行锁与 Snapshot 的 `task_id` 唯一约束保证重复确认只返回同一快照;来源清单冻结字段裁决、文档 hash、证据定位和人工复核历史。 |
|
||||
| 重发版本替代与货代撤销(阶段 7) | 已完成 | 身份固定为客户+PO、内容变化单独版本化;未上传旧版立即作废,已上传旧版必须登记撤销回执后才能解除新版本履约阻断;新旧任务关系和撤销审计永久保留。 |
|
||||
| 库存、Excel 与上传入口门禁(阶段 8) | 已完成 | 履约入口及其底层服务均要求活动的冻结订单,替代/作废/撤销待处理版本无法匹配或导出;人工上传强制货代回执号、私有回执文件和服务端当前用户。 |
|
||||
| 安全 Chatflow(阶段 9) | 已完成 | 仅允许一个启用货代 Chatflow;Dify OpenAPI 只保留短效能力令牌保护的任务/批次状态查询,所有写操作改由 HXOPS 确认卡与服务端状态机执行。 |
|
||||
|
||||
### 排程平台任务契约中心(schedule)
|
||||
|
||||
@@ -654,17 +555,4 @@
|
||||
| 目录 Agent 可点击问答 | 已实现 | 目录本身仍是普通 Agent,用户点击后进入聊天页并走现有 SSE 链路。 |
|
||||
| 目录展开/折叠与子应用点击 | 已实现 | Chat 侧边栏/移动端 Agent 切换器将目录渲染为树形节点;目录可点击,展开后成员应用也可点击并进入各自 Dify 问答。 |
|
||||
| 聚合 Chatflow 上下文注入 | 已实现 | 聊天时向 Dify inputs 注入成员应用 ID、名称、Dify App ID 与分类等元数据。 |
|
||||
| 多子 Agent 并行召回与答案融合 | 未纳入本期 | 当前由目录 Agent 对应的 Dify Chatflow 基于注入元数据完成聚合问答。 |
|
||||
| 订单抽取紧凑结构化候选 | 已实现 / 质量验收延期 | 唯一 Manifest、Run 冻结、无 HTML/bbox/token 泄漏、accepted 字段锁与完整表零 Provider;人工真值及 95% 指标暂缓。 |
|
||||
| 订单抽取 L6 证据裁决与诊断 | 已实现 / 质量验收延期 | Observation 证据引用、纯文本无 cell 转复核、同 Document 强身份关联、冲突阻断、Candidate/UI 原因码和脱敏管理员追溯率诊断。 |
|
||||
| 订单抽取 L7 启用准备 | 工程完成 / 阶段未验收 | 删除 Profile/纯文本零 Provider;自动建单要求当前 Schema 的已批准质量批次,并冻结到 Run、Worker 再核验。人工真值延期时无批准批次可选,自动建单保持关闭;影子 Run 和实际 Dify 验收尚缺。 |
|
||||
| 订单文档 Profile 独立盲测资格 | 已实现 / 待真实样本验收 | 发布前必须存在训练样本;盲测与 annotation/training 完全独立,所有模板仅需 1 份样本,仍须包含多明细及所需跨页续页证据;通过、批准并原子提升到正式 checksum 后,唯一命中 Profile 才可零 Provider 建单;未批准、多模板或异常行回退 Dify/人工。 |
|
||||
| 订单客户指纹与 Snapshot 绑定 | 已实现 | Bill-to/Ship-to 原文与正式客户分层保存;Bill-to 人工确认须有理由并生成规则版本化指纹,冻结只采纳该确认结果并固化客户简码。 |
|
||||
- 订单文档模板支持大页数 PDF 的上一页/页码跳转/下一页导航、顶部撤销/重做/复制/删除/保存/缩放工具栏、可折叠紧凑标注工具轨,以及按页隔离的区域标记;复制支持 `Ctrl/Cmd+D`,删除支持 `Delete/Backspace`,配置侧栏不再重复放置操作入口。
|
||||
- 订单文档模板自动标记支持原生 PDF 坐标优先补证、扫描件 OCR 兜底、页面尺寸修复和可重复多物理行版式候选重算。
|
||||
- 订单文档模板自动标记只展示独立 `header_field` 表头字段,不再产生可见、可编辑的整行表头框;同一视觉行由内部布局 ID 分组,保存时按字段坐标并集自动生成后端表头区域。
|
||||
- 订单文档模板草稿允许字段区域暂不绑定 Schema,不把正常标注中间态当成保存错误;发布门禁仍要求完整有效绑定。自动标记同时从首条明细前的独立视觉行生成待复核表头框,并兼容 PDF 字符层将 `ITEM NO`、`UNIT PRICE` 合并为紧凑文本;表头与业务值真正混行时仍保持人工复核。
|
||||
- 订单文档模板局部候选支持多明细分组展示,并按绑定 Schema 字段顺序逐项核对识别值与来源物理行。
|
||||
- 订单文档模板支持表头到 Schema 的显式确认绑定,并以已确认表头为跨页字段列提供不自动覆盖的语义建议;字段区域保持最终数据提取真相。
|
||||
- 订单文档模板支持父物理行内视觉 band 校准:运行时按 `line_no` 切分重复明细,以首条样例真实字符将字段框校准到实际 band,并将纵向字段组单调对齐到后续明细;未标注描述行和可变换行不会压缩字段序号,歧义候选留空复核。表头即使位于后续页面也可提供与页序无关的 X 列语义建议,但不传播绝对 Y、不自动覆盖人工绑定,旧整高字段和多物理行模板保持兼容。
|
||||
- 订单文档模板样本下拉仅显示模板页专用上传样本;普通发货历史附件不再混入模板维护入口。
|
||||
@@ -3,7 +3,7 @@
|
||||
"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。"
|
||||
"description": "货代 Chatflow 仅作自然语言只读解释。所有写操作必须由 HXOPS 确认卡和后端状态机执行;本 OpenAPI 不包含改单、确认、冻结、库存、Excel 或上传接口。"
|
||||
},
|
||||
"servers": [
|
||||
{
|
||||
@@ -11,541 +11,6 @@
|
||||
}
|
||||
],
|
||||
"paths": {
|
||||
"/tools/create_temporary_inventory_session": {
|
||||
"post": {
|
||||
"operationId": "create_temporary_inventory_session",
|
||||
"summary": "创建对话上传库存文件的临时分析会话",
|
||||
"description": "仅在用户明确说明附件为库存文件的 temporary_inventory 分支调用。后端按会话用户校验资产归属并执行结构初检;不会创建生产库存快照、不会绑定库存站点、不会执行库存匹配。",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"agent_runtime_context": {
|
||||
"type": "string",
|
||||
"description": "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
|
||||
},
|
||||
"asset_no": {
|
||||
"type": "string",
|
||||
"description": "当前用户上传的 FileAsset 编号;必须是 xls、xlsx 或 csv"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"agent_runtime_context",
|
||||
"asset_no"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/tools/get_temporary_inventory_session": {
|
||||
"post": {
|
||||
"operationId": "get_temporary_inventory_session",
|
||||
"summary": "读取临时库存文件的脱敏结构分析和方案候选",
|
||||
"description": "返回后端已分析的工作表、表头、字段目录和已发布方案候选,不返回样例库存值。Dify 不得读取文件路径、全量库存行,也不得据此直接宣称库存已可用于订单匹配。",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"agent_runtime_context": {
|
||||
"type": "string",
|
||||
"description": "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
|
||||
},
|
||||
"temporary_session_no": {
|
||||
"type": "string",
|
||||
"description": "create_temporary_inventory_session 返回的临时会话编号"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"agent_runtime_context",
|
||||
"temporary_session_no"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/tools/submit_temporary_inventory_mapping_suggestion": {
|
||||
"post": {
|
||||
"operationId": "submit_temporary_inventory_mapping_suggestion",
|
||||
"summary": "保存对话临时库存的候选字段映射",
|
||||
"description": "仅在没有 exact 已发布方案可复用时调用。HXOPS 校验字段目录、真实表头、重复列和核心字段完整性,只保存待用户确认的候选;不会发布方案、绑定库存站点、创建库存快照或执行订单匹配。",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"agent_runtime_context": {
|
||||
"type": "string",
|
||||
"description": "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
|
||||
},
|
||||
"temporary_session_no": {
|
||||
"type": "string",
|
||||
"description": "临时库存会话编号"
|
||||
},
|
||||
"field_mapping": {
|
||||
"type": "object",
|
||||
"description": "库存字段目录 ID 到真实来源表头的映射;只能使用 get_temporary_inventory_session 返回的字段 ID 和表头",
|
||||
"additionalProperties": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"agent_runtime_context",
|
||||
"temporary_session_no",
|
||||
"field_mapping"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/tools/confirm_temporary_inventory_use": {
|
||||
"post": {
|
||||
"operationId": "confirm_temporary_inventory_use",
|
||||
"summary": "确认当前对话临时库存文件使用",
|
||||
"description": "仅在用户明确确认本次使用后调用。HXOPS 重新确定性解析文件并校验料号、预约号、库存数量;只锁定当前对话的临时会话审计,不接受任务编号,绝不创建生产库存快照、绑定库存站点、写入任务库存行或执行库存匹配。",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"agent_runtime_context": {
|
||||
"type": "string",
|
||||
"description": "HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
|
||||
},
|
||||
"temporary_session_no": {
|
||||
"type": "string",
|
||||
"description": "临时库存会话编号"
|
||||
},
|
||||
"selected_profile_id": {
|
||||
"type": "integer",
|
||||
"description": "仅 exact 已发布方案候选时由用户选择的方案 ID"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"agent_runtime_context",
|
||||
"temporary_session_no"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/tools/update_notice_fields": {
|
||||
"post": {
|
||||
"operationId": "update_notice_fields",
|
||||
"summary": "更新解析后的发货通知单头字段,如客户、PO、交期、收货地",
|
||||
"description": "更新解析后的发货通知单头字段,如客户、PO、交期、收货地",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "string",
|
||||
"description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501"
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"description": "可更新字段:customer_name/customer_code/ship_to/po_number/required_date",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"comment": {
|
||||
"type": "string",
|
||||
"description": "修改备注(可选)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"task_id",
|
||||
"fields"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/tools/update_notice_line": {
|
||||
"post": {
|
||||
"operationId": "update_notice_line",
|
||||
"summary": "更新解析结果中的某一行,如内部料号、Reservation ID、数量、交期",
|
||||
"description": "更新解析结果中的某一行,如内部料号、Reservation ID、数量、交期",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "string",
|
||||
"description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501"
|
||||
},
|
||||
"line_index": {
|
||||
"type": "integer",
|
||||
"description": "行下标,从 0 开始"
|
||||
},
|
||||
"patch": {
|
||||
"type": "object",
|
||||
"description": "可更新字段:part_number/reservation_id/quantity/qty/required_date/uom/inventory_source_hint;inventory_source_hint 为可选订单路由线索",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"comment": {
|
||||
"type": "string",
|
||||
"description": "修改备注(可选)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"task_id",
|
||||
"line_index",
|
||||
"patch"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/tools/add_notice_line": {
|
||||
"post": {
|
||||
"operationId": "add_notice_line",
|
||||
"summary": "向解析结果新增一行发货需求",
|
||||
"description": "向解析结果新增一行发货需求",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "string",
|
||||
"description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501"
|
||||
},
|
||||
"line": {
|
||||
"type": "object",
|
||||
"description": "新增行,至少包含 part_number 和 qty/quantity",
|
||||
"additionalProperties": true
|
||||
},
|
||||
"comment": {
|
||||
"type": "string",
|
||||
"description": "修改备注(可选)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"task_id",
|
||||
"line"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/tools/remove_notice_line": {
|
||||
"post": {
|
||||
"operationId": "remove_notice_line",
|
||||
"summary": "删除解析结果中的某一行发货需求",
|
||||
"description": "删除解析结果中的某一行发货需求",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "string",
|
||||
"description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501"
|
||||
},
|
||||
"line_index": {
|
||||
"type": "integer",
|
||||
"description": "行下标,从 0 开始"
|
||||
},
|
||||
"comment": {
|
||||
"type": "string",
|
||||
"description": "修改备注(可选)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"task_id",
|
||||
"line_index"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/tools/confirm_inventory_source": {
|
||||
"post": {
|
||||
"operationId": "confirm_inventory_source",
|
||||
"summary": "在库存源人工检查点确认正式库存查询来源(仅提交 source_code)",
|
||||
"description": "库存连接器门禁:稳定身份须具备 source_code、connector_type;fixed Source 同时具备 warehouse_id,且 routing_fingerprint 与当前配置版本一致。Tool API 使用集成密钥鉴权,确认人审计由宿主会话内部链路写入,不接受外部 user_id。若返回 needs_human,说明身份未完整解析或需先完成解析确认。",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "string",
|
||||
"description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501"
|
||||
},
|
||||
"source_code": {
|
||||
"type": "string",
|
||||
"description": "启用配置中的库存源编码;Warehouse 由 fixed Source 配置或库存行匹配解析,禁止前端直传"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"task_id",
|
||||
"source_code"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/tools/confirm_customer": {
|
||||
"post": {
|
||||
"operationId": "confirm_customer",
|
||||
"summary": "在客户人工检查点确认标准客户(仅提交 customer_id)",
|
||||
"description": "仅在 customer_review 检查点且用户已经明确选择标准客户后调用。禁止根据邮件中的不稳定客户名称自行猜测 customer_id;客户确认成功后由 HXOPS 决定后续流程。",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "string",
|
||||
"description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501"
|
||||
},
|
||||
"customer_id": {
|
||||
"type": "integer",
|
||||
"description": "用户从 HXOPS 标准客户列表中明确选择的客户 ID"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"task_id",
|
||||
"customer_id"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/tools/submit_decision": {
|
||||
"post": {
|
||||
"operationId": "submit_decision",
|
||||
"summary": "人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task。决策提交后由后台任务统一续跑。",
|
||||
"description": "人工复核决策入口。必须先定位到唯一 task_id 才能推进;若 conversation_id 对应多个任务,必须先追问或调用状态查询工具确认,禁止用模糊指代直接推进。本 Tool 的返回结果以 HXOPS 状态机为准,Dify 必须根据实际返回的 status、checkpoint、forbidden_next_tools、human_options 或 action_buttons 解释当前现场。若返回 needs_human 或 failed,不得自行宣布完成、不得改写为成功,也不要在正文列出按钮清单;按钮由 HXOPS 前端渲染。",
|
||||
"parameters": [],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"task_id": {
|
||||
"type": "string",
|
||||
"description": "发货任务引用:技术任务号 SN-20260529-ABCD1234 或业务号 WYC26071501"
|
||||
},
|
||||
"conversation_id": {
|
||||
"type": "string",
|
||||
"description": "Dify 会话 ID;用户仅回复「确认」时用于定位任务"
|
||||
},
|
||||
"decision": {
|
||||
"type": "string",
|
||||
"description": "confirm=确认继续;reject=驳回;retry_rpa=按已发布解析方案重新获取库存;rematch=重新匹配;reparse=重新解析",
|
||||
"enum": [
|
||||
"confirm",
|
||||
"confirm_parse",
|
||||
"reject",
|
||||
"retry_rpa",
|
||||
"rematch",
|
||||
"reparse"
|
||||
]
|
||||
},
|
||||
"comment": {
|
||||
"type": "string",
|
||||
"description": "备注(可选)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"decision"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/tools/get_task_status": {
|
||||
"post": {
|
||||
"operationId": "get_task_status",
|
||||
@@ -566,8 +31,16 @@
|
||||
"conversation_id": {
|
||||
"type": "string",
|
||||
"description": "Dify 会话 ID"
|
||||
},
|
||||
"shipping_chat_capability_token": {
|
||||
"type": "string",
|
||||
"description": "HXOPS 每轮注入的短效只读能力令牌;必须原样透传"
|
||||
}
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"task_id",
|
||||
"shipping_chat_capability_token"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -602,10 +75,15 @@
|
||||
"batch_no": {
|
||||
"type": "string",
|
||||
"description": "发货批次编号(batch id),如 SB-20260617-ABCD1234"
|
||||
},
|
||||
"shipping_chat_capability_token": {
|
||||
"type": "string",
|
||||
"description": "HXOPS 每轮注入的短效只读能力令牌;必须原样透传"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"batch_no"
|
||||
"batch_no",
|
||||
"shipping_chat_capability_token"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,6 +60,8 @@
|
||||
| **发货通知** | **文档版面结构化 L4 冻结 Schema 证据映射** | layout.v1 Table 直接按 Run 冻结 Schema 映射,字段证据必须引用真实 cell/token;跨页只接受显式 continuation。 | `test_shipping_document_layout_schema_mapping.py`、`test_shipping_document_layout_html_table.py`、`test_shipping_order_extraction_runs.py`、`test_agent_runtime_bindings.py` | 后置表头、重复目标列、Qty=0、真实 cell/token/evidence_ref、显式/缺失 continuation、Run 后 Schema 漂移、Manifest 泄漏 | 映射复用既有安全规则;重复列全 ambiguous;零 Qty 删除;Run v3冻结候选不漂移;needs_review 只标 candidate且不进 Dify/确定性执行。人工真值延期时不判真实字段映射准确率,但错误自动接受数必须为 0。 |
|
||||
| **发货通知** | **订单文档模板 Profile 纯契约** | 以表头网格精确结构指纹选择固定列规则,允许模板级字段语义覆盖全局 Schema;只运行注册解析器。 | `test_shipping_order_document_profile.py` | `Part Number -> customer_part_number`、`Vendor Item# -> part_number`、复合料号 cell、零 Qty、结构漂移、MinerU 行关系丢失、自由解析器注入 | 精确命中时模板映射原样生效;零 Qty 行删除;结构变化不做相似匹配;行关系丢失显式阻断;未知解析器或非法目标字段拒绝保存。 |
|
||||
| **发货通知** | **订单文档 Profile 发布与运行锁定** | Profile 绑定不可变 Schema/稳定 field_id,版本化发布;Run 冻结完整 Profile 与 MinerU 紧凑布局,Worker 只执行唯一精确匹配。 | `test_shipping_order_document_profile_service.py`、`test_order_document_profile_migration.py`、`test_shipping_document_layout_runtime.py`、`test_agent_runtime_bindings.py`、`test_shipping_order_extraction_runs.py` | 并发草稿覆盖、新版发布、字段退役、Provider 失败、多附件预算、多表/多 Profile、零 Qty、Decimal JSON、布局 HTML 泄漏 Dify、Run 后配置变化 | 乐观锁与单 published 唯一索引生效;字段引用阻断退役;Run 快照不漂移;Provider 失败安全回退;唯一完整表跳过 Dify;多表不自动合并;HTML/bbox/field_code 不进入 Dify;零 Qty 删除。 |
|
||||
| **发货通知** | **阶段 4 模板资格独立门禁** | 模板发布和自动冻结资格分别治理;首版只能人工确认。 | `test_shipping_document_profile_quality.py`、`test_profile_auto_freeze_qualification_migration.py` | 未盲测发布、盲测批准、模板新版本、checksum 变化、单模板暂停 | 发布模板可供解析但只生成 `manual_confirmation`;盲测不会自动开启冻结;资格按 Profile 版本/checksum 独立;暂停一个模板不影响其他模板;样本不足时 `auto_freeze_enabled=false`。 |
|
||||
| **发货通知** | **阶段 5 人工复核证据闭环** | 所有人工改单/冲突解决都提交结构化证据和订单版本。 | `test_shipping_task_field_reconciliation.py`、前端生产构建 | 手工输入、伪造 document_cell、跨订单 Observation、过期版本、行增删改、冲突解决 | 仅当前 Task/Extraction/Document 的 Observation 可用;手工输入须有原因;证据校验在写值前执行;审计保存前后值、字段/行、操作者与结构化证据;过期版本拒绝覆盖。 |
|
||||
| **发货通知** | **订单坐标 Profile v2 契约治理** | 模板以文档静态锚点、相对表区、独立表头/明细物理行、字段区域、受控解析器、排除/终止/跨页规则表达;字段绑定必须冻结 Schema field_id 且获坐标来源授权。 | `test_shipping_order_document_profile.py`、`test_shipping_order_document_profile_service.py`、前端生产构建 | 坐标越界/重叠、重复字段、物理行错序、未注册解析器、浏览器伪造 field_id、未授权 PDF/OCR 来源、旧网格行/列定义、过期 lock | 后端拒绝非法几何与歧义定义;表头布局和明细布局相互独立;字段 ID 后端重写;Schema 未授权来源阻断;新 Profile 不接收 HTML 网格、行号或固定列规则;乐观锁与不可变发布版本生效。 |
|
||||
| **发货通知** | **文档版面坐标重建候选** | 在可信 PDF/OCR 字符坐标存在时自动建议动态行数、列边界和列示例;管理员确认字段后,按 x 列归属、y 视觉行、字段内容适配及同行顺序重建错误 MinerU 网格,再按动态 N 行版式合并为可审核逻辑明细。 | `test_shipping_coordinate_table_reconstruction.py`、`test_shipping_order_document_profile_service.py` | `00010/00020` 行号、料号/数量/单位边界、2/3/4/N 行版式、每行不同列数、单内容块续行、跨行重叠边界、`** Item deleted **`、TOTAL 终止、残缺/后置表头、纯表头页、列归属并列 | 建议与候选固定 `needs_review`;自动建议排除表头/合计、自动标出首行 `line_no` 并只返回相对边界/少量示例;坐标虚拟表头不依赖数据页完整表头;第 2..N 行按独立边界合并;无坐标/歧义绝不自动接受、发布 Profile 或进入履约。 |
|
||||
| **发货通知** | **坐标修复模板闭环** | 结构污染 PDF 由管理员确认列边界后重建,确认结果随 Profile 与 Run 冻结。 | `test_shipping_coordinate_table_reconstruction.py`、`test_shipping_order_document_profile_service.py`、前端生产构建 | 表头混入首条明细、无文本层 PDF、非法边界、未确认候选、盲测与 Run 证据缺失 | 浏览器只看到候选网格;边界必须从 0 到 1 严格递增;重建固定待审核且须显式确认;Profile/Run/盲测只用冻结坐标证据,任何缺失均阻断,不回退原始错误网格或 Dify。 |
|
||||
@@ -79,6 +81,10 @@
|
||||
| **发货通知** | **Schema-策略反向依赖门禁(阶段 4)** | 已发布履约策略所绑定字段成为 Schema 发布依赖,和路由/Profile/模板引用同级处理。 | `test_shipping_fulfillment_policy.py`、`test_shipping_order_schema.py` | 先发布策略再移除绑定字段、替换字段、并存库存 Profile 引用 | 新 Schema 在发布前返回依赖阻断;当前发布 Schema、策略与库存配置保持可冻结、可匹配、可制单的一致状态。 |
|
||||
| **发货通知** | **迁移后管理员重建顺序(阶段 5)** | Schema/策略决定订单履约就绪;库存源配置测试独立于订单冻结和上传。 | `test_shipping_fulfillment_policy.py`、`test_shipping_excel_template.py`、`test_shipping_order_schema.py` | 初始策略草稿、未发布策略、Schema 后策略发布、Profile/模板重建、停用源测试 | 未发布策略时冻结 fail closed;策略仅绑定当前 Schema 字段;库存测试不生成订单履约副作用,启用源不等于绕过订单策略门禁。 |
|
||||
| **发货通知** | **冻结策略发布门禁(阶段 6)** | 冻结入口必须取得当前 published 策略,不能由已发布 Schema 或前端状态替代。 | `test_shipping_order_snapshot.py`、`test_shipping_fulfillment_policy.py` | Schema/字段/已确认客户完整但无 published 策略 | 返回 `SHIPPING.FULFILLMENT_POLICY_NOT_PUBLISHED`,不产生 Snapshot 或后续库存履约事实。 |
|
||||
| **发货通知** | **统一冻结就绪门禁(阶段 6)** | 在单事务内锁定 Task,验证可冻结性并固化来源清单。 | `test_shipping_order_snapshot.py`、`test_shipping_order_snapshot_readiness_migration.py` | 开放冲突、料号/预约号/数量缺失或非正、旧版本、重复确认、冻结后编辑、来源清单 | 阻断不完整订单;重复确认返回同一 Snapshot;数据库保证每 Task 一份 Snapshot;快照保留裁决、文档 hash、证据 metadata 与人工审计。 |
|
||||
| **发货通知** | **重发版本替代与货代撤销(阶段 7)** | 用客户+PO 稳定识别订单版本,并约束旧版停止与外部撤销。 | `test_shipping_notice_business_dedup.py`、`test_shipping_task_supersession.py`、`test_shipping_freight_cancellation_migration.py` | Reservation/数量变化、未上传旧版、已上传旧版、缺少撤销回执、重复撤销 | 内容变化仍进入同一 PO 版本链;旧版不会与新版同时履约;撤销成功前新版被阻断;回执与历史 Artifact 永久保留。 |
|
||||
| **发货通知** | **库存、Excel 与回执门禁(阶段 8)** | 所有履约入口只能处理活动冻结版本,人工上传需可验证回执。 | `test_shipping_fulfillment_entry_gates.py`、`test_shipping_rolling_fulfillment.py` | 作废/替代/撤销待处理任务、未冻结、库存不足、缺回执号或文件、重复制单 | 不会触发库存/RPA 或生成 Excel;库存不足整单阻断;人工上传不能完成;Artifact/Reservation 幂等避免重复占用。 |
|
||||
| **发货通知** | **安全 Chatflow(阶段 9)** | Dify 仅做自然语言只读解释,短效令牌绑定 HXOPS 会话和对象。 | `test_shipping_chat_tool_capability.py`、`test_openapi_snapshots.py`、`test_shipping_notice_openapi_contract.py` | 第二个启用 Agent、跨任务/跨用户、篡改/过期令牌、OpenAPI 写工具 | 只保留状态查询;越权读取失败并留审计;未点击 HXOPS 确认卡不改变业务状态;Dify 不可直接推进履约。 |
|
||||
| **发货通知** | **履约策略管理 API(阶段 7)** | 管理员 API 与页面字段过滤共同形成发布闭环。 | `test_shipping_order_schema.py`、`test_shipping_fulfillment_policy.py`、前端 build | 普通用户发布、Schema 已发布后发布策略、字段纳入校验 | 非管理员返回 `AUTH.FORBIDDEN`;管理员发布的策略只绑定当前 published Schema 的兼容字段。 |
|
||||
| **发货通知** | **完整 PostgreSQL 迁移链(阶段 8)** | 空库必须从初始 revision 无人工补表地升级到当前货代 head;历史兼容回填不能假设 sibling 分支字段/表存在。 | `test_shipping_inventory_source_gate_migration.py`、字段目录/Reservation 迁移测试、隔离 PostgreSQL `flask db upgrade` | 缺 `step_payload_json`、缺任务状态列、缺旧 ERP 表、无旧路由配置、PostgreSQL 索引名长度 | 升级抵达唯一 head `027d8e9f0a1b`;57 个 active 标准字段、`customer_po_number` 和移除 `aws_part_number` 的快照结构均经数据库核验。 |
|
||||
| **发货通知** | **管理员重建演练(阶段 9)** | 57 字段目录可发布为满足当前履约最低要求的 Schema,策略必须随后显式发布。 | 隔离 PostgreSQL 重建演练、`test_shipping_order_schema.py`、`test_shipping_fulfillment_policy.py` | 仅四字段发布、策略草稿、策略发布 | Schema 发布 4 项字段成功;`SHIP_AVAILABLE_ROLLING_V1` 成功发布;未发布策略时冻结仍 fail closed。 |
|
||||
@@ -118,7 +124,12 @@
|
||||
| **发货通知** | **订单 Schema 迁移往返** | 阶段一新增表和 Task 当前解析引用可独立 upgrade/downgrade。 | `test_shipping_order_schema_migration.py` | SQLite 最小上一版本基线 | 核心表和列完整新增并完整移除。 |
|
||||
| **发货通知** | **动态 Schema 订单解析** | published 契约驱动 EML/PDF 同字段 Observation 与后端裁决。 | `test_shipping_order_schema_runtime.py`、`test_shipping_notice_order_extraction.py` | 跨 Document 一致、冲突、缺证据、Schema checksum 漂移 | 一致值 corroborated;冲突/缺证据阻断;accepted 值生成类型化投影。 |
|
||||
| **发货通知** | **订单抽取异步 Run 阶段 1 历史门禁** | 独立 API 创建/查询领域 Run,冻结入口 Agent、会话、Intake/Document 正文和 published Schema;阶段 1 验收时不创建 Job。 | `test_shipping_order_extraction_runs.py`、`test_shipping_order_extraction_run_migration.py` | 正常创建、重复请求、活跃 Intake 冲突、无权限/跨用户、未解析/消费/过期、空 Document、迁移往返、结果落库后超时回退 | 阶段 2 扩展后 POST 仍返回 202 queued 且同步持有 Job;其余快照、幂等、双活跃、隐私与状态机门禁持续成立。 |
|
||||
| **发货通知** | **Run 模型与迁移一致性** | 已执行 revision 不再追加字段;Provider 配置/身份快照由独立增量迁移提供,实际数据库与模型保持一致。 | `test_agent_runtime_binding_migration.py`、`test_order_extraction_provider_snapshot_migration.py`、数据库 inspector 冒烟检查 | 从前一 revision upgrade/downgrade;查询 Candidate/Extraction/Run | 迁移往返通过;Alembic 为唯一 head;模型声明列、数据库实际列、外键与索引一致;完整 ORM 查询无 `UndefinedColumn`。 |
|
||||
| **发货通知** | **上传与订单版面准备状态一致性** | 文本预解析完成后继续汇总并轮询独立布局任务,活动布局不得过早创建订单识别 Run。 | `test_shipping_notice_intakes.py::test_intake_status_exposes_layout_lifecycle_without_blocking_terminal_fallback`、`useShippingNoticeIntakes.spec.ts`、`attachmentCard.utils.spec.ts` | 无布局任务、queued/running、ready、failed/unsupported、刷新恢复、直接点击发送、四语言错误码 | `not_required` 与终态允许发送;`processing` 持续轮询并显示版面处理中;后端仍返回稳定门禁;失败布局可走文本/Dify 兜底且不永久卡住。 |
|
||||
| **发货通知** | **订单模板路由决策审计** | 每个 Unit 在后端确定性解析或人工复核前持久化脱敏路由事实;重试只追加不覆盖。 | `test_shipping_order_profile_matcher.py`、`test_shipping_order_extraction_stage0.py`、迁移 upgrade/downgrade 测试 | 缺失锚点、分差歧义、证据不足、未批准模板、多表、无有效行、Job 重试、Run 删除、管理员详情与普通用户访问 | 缺失项仅输出 `anchor_id`;稳定原因码完整;`unit_id + job_id + attempt_no` 唯一;审计先于结果写入;业务拒识为 `skipped/needs_review`;DTO/页面无正文、字段值、quote、坐标、Prompt 或凭据。 |
|
||||
| **发货通知** | **阶段 0 统一状态与追加式审计** | 路由结果统一为 `deterministic/review_required/skipped`;业务拒识不计技术失败;Run 状态变化与路由结果追加至统一审计账本。 | `test_shipping_audit_event.py`、`test_shipping_audit_event_migration.py`、路由/Run 状态测试 | 未命中模板、模板歧义、技术异常、状态变化、敏感元数据、ORM 更新/删除、迁移升级回退 | 业务拒识进入 `needs_review`;技术故障才进入 `failed`;审计含 actor/request/correlation/状态哈希,且拒绝正文、凭据、更新和删除。 |
|
||||
| **发货通知** | **确定性订单 Run 与迁移一致性(阶段 1)** | 订单 Run 不再保存或依赖 Provider、Dify Workflow、质量批次或 Runtime Binding;版本、结果和人工冻结策略是新的冻结事实。 | `test_order_extraction_deterministic_migration.py`、`test_shipping_order_extraction_runs.py`、数据库 inspector 冒烟检查 | 从阶段 0 revision upgrade/downgrade;无 Runtime Binding 创建/重试/重新识别 Run;Dify 不可用 | 迁移往返通过;Alembic 为唯一 head;旧 Provider 列不存在;创建和 Worker 均不触发 Dify 网络调用;模型和数据库一致。 |
|
||||
| **发货通知** | **EML 正文补充表(阶段 2)** | 正文 HTML 表是 PO 级补充事实,不创建订单 Unit;只可按安全关联补 Reservation/Allocation/来源字段。 | `test_email_supplement_merge.py`、`test_shipping_order_extraction_runs.py` | `PO + MPN`、唯一 Reservation 的 PO 降级、多 Reservation、HTML 单元格证据、正文数量与 PDF 数量冲突 | 正文不生成独立订单;PDF 数量不被覆盖;每个补充值可追溯到正文表格/行/列/DOM cell;任何歧义稳定进入 `needs_review`。 |
|
||||
| **发货通知** | **PDF 模板 PO 拆分与拒识(阶段 3)** | 单 PDF 仅在逐行 PO 证据完整时拆分;四类表计数由 Route Decision 审计。 | `test_order_extraction_pdf_po_split.py`、`test_order_route_table_counter_migration.py` | 两个逐行 PO、未证明第二 PO、表级多 PO、多个业务表、模板歧义/漂移 | 逐行 PO 自动拆为独立订单;无可证明归属不猜测;真实表数不被匹配数替代;审核投影不泄露订单值或坐标。 |
|
||||
| **发货通知** | **动态字段库存路由** | 路由规则引用稳定订单 field_id,并从当前 Extraction 读取类型化值。 | `test_shipping_inventory_routing_engine.py`、`test_shipping_inventory_service.py` | Header/Line scope、系统事实、动态行值、非法字段 | 动态字段可命中 Source;作用域错误/退役字段被拒;无任意 fact path。 |
|
||||
| **发货通知** | **库存站点停用保存与启用门禁** | 首次保存保持停用,普通保存不可直接启用;独立启用接口返回系统连接、库存文件解析方案、发货模板和测试导出等未完成项。 | `test_shipping_inventory_service.py::test_activation_is_a_separate_gate_and_reports_unfinished_steps` | 新建站点请求携带 `enabled=true`;缺解析方案、发货模板和测试证据 | 站点仍为停用;启用被阻断且返回准确缺失项;后续测试导出阶段补齐证据后才可放行。 |
|
||||
| **发货通知** | **已发布解析方案直接/批量绑定(一期)** | 停用站点可直接或批量选择已发布方案;服务端全量预检、递增配置版本并写追加式审计,不触发 RPA 或启用。 | `tests/services/admin/test_shipping_inventory_service.py::test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit`、`::test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled` | 草稿/退役方案、启用站点、模板库存字段不兼容、重复站点 ID、空补充说明、批量混合合法与非法站点 | 仅兼容停用站点绑定成功;任一项失败整批零写入;审计自动记录操作者、系统动作、前后方案与配置版本;旧测试因配置版本变更失效。 |
|
||||
|
||||
@@ -77,7 +77,7 @@ export type ShippingOrderExtractionDiagnosticRun = {
|
||||
export type ShippingOrderExtractionDiagnosticDetail = {
|
||||
run: ShippingOrderExtractionDiagnosticRun;
|
||||
job_attempts: Array<{ job_id: number; status: string; attempts: number; max_attempts: number; created_at?: string | null; started_at?: string | null; finished_at?: string | null; duration_ms?: number | null }>;
|
||||
units: Array<{ unit_id: number; position: number; unit_type: string; document_type: string; status: string; attempt_count: number; duration_ms?: number | null; error_code?: string | null }>;
|
||||
units: Array<{ unit_id: number; position: number; unit_type: string; document_type: string; status: string; attempt_count: number; duration_ms?: number | null; error_code?: string | null; route_decisions: Array<{ attempt_no: number; execution_mode: 'deterministic' | 'dify' | 'blocked'; match_status: string; selected_profile_code?: string | null; selected_profile_version?: number | null; auto_create_approved?: boolean | null; candidate_count: number; table_count: number; approved_table_count: number; candidates: Array<{ profile_code: string; version: number; score: number; hard_match: boolean; reason_codes: string[]; missing_required_anchor_ids?: string[] }>; fallback_reason_codes: string[] }> }>;
|
||||
progress_events: Array<{ event_type: string; node_type?: string | null; stage_code?: string | null; status?: string | null; workflow_run_id?: string | null; node_execution_id?: string | null; occurred_at?: string | null }>;
|
||||
};
|
||||
export const listShippingOrderExtractionDiagnosticRuns = (page = 1, pageSize = 25, status = '') => {
|
||||
|
||||
@@ -76,16 +76,6 @@ const dialogTitle = computed(() => {
|
||||
const dialogSubtitle = computed(() => (
|
||||
isInternalExecutor.value ? t('admin.agent.executor.formSubtitle') : t('admin.agent.subtitle')
|
||||
));
|
||||
const orderExtractionCapability = computed(() => (
|
||||
currentCatalogEntry.value?.required_runtime_capabilities?.['shipping.order_extraction']
|
||||
));
|
||||
const orderExtractionProviderOptions = computed(() => props.agentOptions.filter((agent) => (
|
||||
agent.id !== props.form.id
|
||||
&& agent.is_active
|
||||
&& agent.runtime_provider === 'dify'
|
||||
&& agent.dify_app_type === 'workflow'
|
||||
&& agent.exposure_mode === 'internal'
|
||||
)));
|
||||
const showToolRunProgress = computed(() => (
|
||||
showDifyFields.value
|
||||
&& props.form.dify_app_type !== 'workflow'
|
||||
@@ -366,28 +356,6 @@ const handleTrainingQuestionTypeChange = (form: AgentFormState, index: number) =
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-if="orderExtractionCapability" class="col-span-1 md:col-span-2 rounded-xl border border-default bg-surface-soft p-4">
|
||||
<div class="mb-4">
|
||||
<h4 class="text-sm font-semibold text-primary">{{ t('admin.agent.runtimeBinding.title') }}</h4>
|
||||
<p class="mt-1 text-xs text-muted">{{ t('admin.agent.runtimeBinding.subtitle') }}</p>
|
||||
</div>
|
||||
<div class="overflow-x-auto rounded-lg border border-default">
|
||||
<table class="min-w-full text-sm">
|
||||
<thead class="bg-surface-soft text-left text-xs font-bold uppercase tracking-wider text-muted">
|
||||
<tr><th class="px-3 py-2">{{ t('admin.agent.runtimeBinding.capability') }}</th><th class="px-3 py-2">{{ t('admin.agent.runtimeBinding.provider') }}</th><th class="px-3 py-2">{{ t('admin.agent.runtimeBinding.timeout') }}</th><th class="px-3 py-2">{{ t('admin.agent.runtimeBinding.maxAttempts') }}</th></tr>
|
||||
</thead>
|
||||
<tbody><tr class="border-t border-default">
|
||||
<td class="px-3 py-3 font-medium text-primary">{{ t('admin.agent.runtimeBinding.orderExtraction') }}</td>
|
||||
<td class="px-3 py-3"><select v-model="form.order_extraction_provider_agent_id" class="w-full input-field text-sm"><option :value="null">{{ t('admin.agent.runtimeBinding.selectProvider') }}</option><option v-for="agent in orderExtractionProviderOptions" :key="agent.id" :value="agent.id">{{ agent.name }} (Workflow #{{ agent.id }})</option></select></td>
|
||||
<td class="px-3 py-3"><input v-model.number="form.order_extraction_timeout_seconds" type="number" min="30" max="3600" class="w-28 input-field text-sm" /></td>
|
||||
<td class="px-3 py-3"><input v-model.number="form.order_extraction_max_attempts" type="number" min="1" max="10" class="w-20 input-field text-sm" /></td>
|
||||
</tr></tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p v-if="!orderExtractionProviderOptions.length" class="mt-3 text-xs text-amber-700">
|
||||
{{ t('admin.agent.runtimeBinding.noProvider') }}
|
||||
</p>
|
||||
</div>
|
||||
<div v-if="isInternalExecutor" class="col-span-1 md:col-span-2 rounded-xl border border-default bg-surface-soft p-4">
|
||||
<div class="mb-4"><h4 class="text-sm font-semibold text-primary">{{ t('admin.agent.runtimeBinding.executorGovernance') }}</h4></div>
|
||||
<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
listAdminContentProfiles,
|
||||
listAdminIntentRoutes,
|
||||
listAdminAgents,
|
||||
listAdminAgentRuntimeBindings,
|
||||
listAdminUsers,
|
||||
saveAdminAgentPermissions,
|
||||
testAdminAgent,
|
||||
@@ -404,18 +403,6 @@ export function useAgentsAdmin() {
|
||||
}
|
||||
isEditing.value = true;
|
||||
void loadTrainingExamPdfGuides(agent.id);
|
||||
if (catalogEntry?.required_runtime_capabilities?.['shipping.order_extraction']) {
|
||||
void listAdminAgentRuntimeBindings(agent.id).then((bindings) => {
|
||||
if (selectedAgentId.value !== agent.id) return;
|
||||
const binding = bindings.find((item) => item.capability_code === 'shipping.order_extraction');
|
||||
form.value.order_extraction_binding_enabled = binding?.enabled !== false;
|
||||
form.value.order_extraction_provider_agent_id = binding?.provider_agent_id ?? null;
|
||||
form.value.order_extraction_timeout_seconds = Number(binding?.config?.timeout_seconds || 900);
|
||||
form.value.order_extraction_max_attempts = Number(binding?.config?.max_attempts || 3);
|
||||
}).catch((error) => {
|
||||
console.error('Error loading Agent runtime bindings:', error);
|
||||
});
|
||||
}
|
||||
const governance = asRecord(extra.order_extraction_governance);
|
||||
form.value.executor_provider_max_concurrency = Number(governance.provider_max_concurrency || 4);
|
||||
form.value.executor_circuit_failure_threshold = Number(governance.circuit_failure_threshold || 5);
|
||||
@@ -521,22 +508,6 @@ export function useAgentsAdmin() {
|
||||
typeCatalog: typeCatalog.value,
|
||||
});
|
||||
registryPayload.exposure_mode = form.value.exposure_mode;
|
||||
if (catalogEntry?.required_runtime_capabilities?.['shipping.order_extraction']) {
|
||||
if (!form.value.order_extraction_provider_agent_id) {
|
||||
msg.warning(t('admin.agent.runtimeBinding.providerRequired'));
|
||||
isSaving.value = false;
|
||||
return false;
|
||||
}
|
||||
registryPayload.order_extraction_runtime_binding = {
|
||||
provider_agent_id: form.value.order_extraction_provider_agent_id,
|
||||
// 新 UI 不再暴露启用勾选;绑定存在即启用,旧 API 仍兼容显式 enabled=false。
|
||||
enabled: true,
|
||||
config: {
|
||||
timeout_seconds: form.value.order_extraction_timeout_seconds,
|
||||
max_attempts: form.value.order_extraction_max_attempts,
|
||||
},
|
||||
};
|
||||
}
|
||||
if (form.value.exposure_mode === 'internal') {
|
||||
extra_config.order_extraction_governance = {
|
||||
provider_max_concurrency: form.value.executor_provider_max_concurrency,
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ defineEmits<{ close: []; edit: [profile: ShippingOrderDocumentProfile]; publish:
|
||||
<aside v-if="open" class="drawer" :aria-label="t('admin.shippingOrderProfiles.versions')">
|
||||
<header><strong>{{ t('admin.shippingOrderProfiles.versions') }}</strong><button type="button" @click="$emit('close')">{{ t('common.close') }}</button></header>
|
||||
<article v-for="profile in profiles" :key="profile.id">
|
||||
<div><b>{{ profile.display_name }} · v{{ profile.version }}</b><small>{{ profile.profile_code }} · {{ profile.status }}</small><small v-if="profile.migration_status === 'needs_revalidation'" class="migration-status">{{ t('admin.shippingOrderProfiles.migrationNeedsReview') }}</small></div>
|
||||
<div><b>{{ profile.display_name }} · v{{ profile.version }}</b><small>{{ profile.profile_code }} · {{ profile.status }}</small><small v-if="profile.auto_freeze_qualification">{{ t(`admin.shippingOrderProfiles.autoFreezeQualification.${profile.auto_freeze_qualification.status}`) }}</small><small v-if="profile.migration_status === 'needs_revalidation'" class="migration-status">{{ t('admin.shippingOrderProfiles.migrationNeedsReview') }}</small></div>
|
||||
<div class="actions">
|
||||
<button v-if="profile.status === 'draft'" type="button" @click="$emit('edit', profile)">{{ t('common.edit') }}</button>
|
||||
<button v-if="profile.status === 'draft'" type="button" @click="$emit('test', profile)">{{ t('admin.shippingOrderProfiles.blindTest.title') }}</button>
|
||||
|
||||
+3
-1
@@ -110,7 +110,9 @@ onMounted(() => { void load(); });
|
||||
<p v-if="detailLoading" class="mt-6 text-muted">{{ t('admin.shippingOrderExtractionRuns.loading') }}</p>
|
||||
<template v-else-if="detail"><dl class="mt-5 grid grid-cols-2 gap-3 text-sm"><dt>{{ t('admin.shippingOrderExtractionRuns.runNo') }}</dt><dd class="font-mono text-xs">{{ detail.run.run_no }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.workflowRunId') }}</dt><dd class="font-mono text-xs">{{ detail.run.workflow_run_id || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.errorCode') }}</dt><dd>{{ detail.run.error_code || '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.totalDuration') }}</dt><dd>{{ formatDuration(detail.run.durations_ms.total) }}</dd></dl>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.jobAttempts') }}</h3><div class="mt-2 space-y-2"><div v-for="job in detail.job_attempts" :key="job.job_id" class="rounded-lg border border-default p-3 text-sm"><b>#{{ job.job_id }}</b> · {{ job.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ job.attempts }}/{{ job.max_attempts }} · {{ formatDuration(job.duration_ms) }}</div><p v-if="!detail.job_attempts.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.units') }}</h3><div class="mt-2 space-y-2"><div v-for="unit in detail.units" :key="unit.unit_id" class="rounded-lg border border-default p-3 text-sm"><b>#{{ unit.position + 1 }} {{ unit.unit_type }}</b> · {{ unit.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ unit.attempt_count }} · {{ formatDuration(unit.duration_ms) }}<span v-if="unit.error_code" class="ml-2 font-mono text-xs text-danger">{{ unit.error_code }}</span></div><p v-if="!detail.units.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.units') }}</h3><div class="mt-2 space-y-2"><div v-for="unit in detail.units" :key="unit.unit_id" class="rounded-lg border border-default p-3 text-sm"><b>#{{ unit.position + 1 }} {{ unit.unit_type }}</b> · {{ unit.status }} · {{ t('admin.shippingOrderExtractionRuns.attempts') }} {{ unit.attempt_count }} · {{ formatDuration(unit.duration_ms) }}<span v-if="unit.error_code" class="ml-2 font-mono text-xs text-danger">{{ unit.error_code }}</span>
|
||||
<section v-for="route in unit.route_decisions" :key="`${unit.unit_id}:${route.attempt_no}`" class="mt-3 rounded border border-default bg-slate-50 p-3 text-xs dark:bg-slate-900/40"><h4 class="font-semibold text-primary">{{ t('admin.shippingOrderExtractionRuns.routeDecision') }} #{{ route.attempt_no }}</h4><dl class="mt-2 grid grid-cols-2 gap-x-3 gap-y-1"><dt>{{ t('admin.shippingOrderExtractionRuns.executionMode') }}</dt><dd>{{ t(`admin.shippingOrderExtractionRuns.executionModes.${route.execution_mode}`) }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.matchStatus') }}</dt><dd>{{ t(`admin.shippingOrderExtractionRuns.matchStatuses.${route.match_status}`) }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.selectedProfile') }}</dt><dd>{{ route.selected_profile_code ? `${route.selected_profile_code} V${route.selected_profile_version}` : '-' }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.autoCreateApproved') }}</dt><dd>{{ route.auto_create_approved == null ? '-' : t(route.auto_create_approved ? 'admin.shippingOrderExtractionRuns.yes' : 'admin.shippingOrderExtractionRuns.no') }}</dd><dt>{{ t('admin.shippingOrderExtractionRuns.fallbackReasons') }}</dt><dd>{{ route.fallback_reason_codes.length ? route.fallback_reason_codes.map(code => t(`admin.shippingOrderExtractionRuns.reasonCodes.${code}`)).join(';') : '-' }}</dd></dl><div v-if="route.candidates.length" class="mt-3"><p class="font-medium">{{ t('admin.shippingOrderExtractionRuns.candidates') }}</p><div v-for="candidate in route.candidates" :key="`${candidate.profile_code}:${candidate.version}`" class="mt-1 flex flex-wrap gap-x-2 text-muted"><span>{{ candidate.profile_code }} V{{ candidate.version }}</span><span>{{ candidate.score.toFixed(2) }}</span><span>{{ candidate.hard_match ? t('admin.shippingOrderExtractionRuns.hardMatch') : t('admin.shippingOrderExtractionRuns.hardMismatch') }}</span><span v-if="candidate.missing_required_anchor_ids?.length">{{ t('admin.shippingOrderExtractionRuns.missingAnchors', { ids: candidate.missing_required_anchor_ids.join(', ') }) }}</span></div></div></section>
|
||||
</div><p v-if="!detail.units.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
|
||||
<h3 class="mt-7 font-semibold">{{ t('admin.shippingOrderExtractionRuns.lifecycle') }}</h3><div class="mt-2 space-y-2"><div v-for="event in detail.progress_events" :key="`${event.node_execution_id}:${event.event_type}:${event.occurred_at}`" class="rounded-lg border border-default p-3 text-sm"><b>{{ event.stage_code || event.event_type }}</b><span class="ml-2 text-secondary">{{ event.status || '-' }}</span><span class="ml-2 font-mono text-xs text-muted">{{ event.node_type || '-' }}</span><time class="ml-2 text-xs text-muted">{{ formatTime(event.occurred_at) }}</time></div><p v-if="!detail.progress_events.length" class="text-sm text-muted">{{ t('admin.shippingOrderExtractionRuns.empty') }}</p></div>
|
||||
</template>
|
||||
</aside>
|
||||
|
||||
@@ -132,10 +132,6 @@ export interface AgentFormState {
|
||||
training_hr_chat_questions_text: string;
|
||||
training_question_bank: AgentTrainingQuestionFormItem[];
|
||||
directory_member_ids: number[];
|
||||
order_extraction_binding_enabled: boolean;
|
||||
order_extraction_provider_agent_id: number | null;
|
||||
order_extraction_timeout_seconds: number;
|
||||
order_extraction_max_attempts: number;
|
||||
executor_provider_max_concurrency: number;
|
||||
executor_circuit_failure_threshold: number;
|
||||
executor_circuit_cooldown_seconds: number;
|
||||
@@ -198,10 +194,6 @@ export const createEmptyAgentForm = (
|
||||
training_hr_chat_questions_text: '',
|
||||
training_question_bank: [],
|
||||
directory_member_ids: [],
|
||||
order_extraction_binding_enabled: true,
|
||||
order_extraction_provider_agent_id: null,
|
||||
order_extraction_timeout_seconds: 900,
|
||||
order_extraction_max_attempts: 3,
|
||||
executor_provider_max_concurrency: 4,
|
||||
executor_circuit_failure_threshold: 5,
|
||||
executor_circuit_cooldown_seconds: 60,
|
||||
|
||||
@@ -59,6 +59,13 @@ export interface ShippingOrderDocumentProfile {
|
||||
review_changes?: Array<{ field_id: string; reason: string; before?: unknown; after?: unknown }>;
|
||||
} | null;
|
||||
migration_status?: 'normal' | 'needs_revalidation' | 'blocked';
|
||||
auto_freeze_qualification?: {
|
||||
status: 'manual_confirmation' | 'auto_freeze_approved' | 'auto_freeze_suspended';
|
||||
auto_freeze_enabled: boolean;
|
||||
qualification_id: number | null;
|
||||
parser_version?: string;
|
||||
quality_suite_id?: number | null;
|
||||
};
|
||||
}
|
||||
|
||||
/** 受控预览授权只对单页生效,令牌不得持久化或复用。 */
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
/**
|
||||
* features/chat/api/chat.api.spec.ts
|
||||
* 用途:验证聊天历史接口适配层不会在 hydrate 过程中丢失用户附件快照。
|
||||
* 依赖:Vitest、mock 后的 shared/api/client 与 auth、chat.api。
|
||||
* 逻辑:覆盖历史消息过滤 shipping-parse-review、恢复订单识别状态时仍保留 attachments。
|
||||
*/
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { listChatMessages } from './chat.api';
|
||||
|
||||
vi.mock('@/shared/utils/auth', () => ({
|
||||
getAuthHeaders: vi.fn(() => ({ Authorization: 'Bearer test-token' })),
|
||||
}));
|
||||
|
||||
vi.mock('@/shared/api/client', () => ({
|
||||
requestJson: vi.fn(),
|
||||
}));
|
||||
|
||||
import { requestJson } from '@/shared/api/client';
|
||||
|
||||
const requestJsonMock = vi.mocked(requestJson);
|
||||
|
||||
describe('chat.api history hydration', () => {
|
||||
beforeEach(() => {
|
||||
requestJsonMock.mockReset();
|
||||
});
|
||||
|
||||
it('keeps user attachment snapshots while hydrating persisted assistant payload', async () => {
|
||||
requestJsonMock.mockResolvedValue([
|
||||
{
|
||||
role: 'user',
|
||||
content: '',
|
||||
attachments: [{
|
||||
id: 'attachment-only-1',
|
||||
name: 'notice.eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '中间态消息',
|
||||
type: 'shipping-parse-review',
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: '订单识别完成',
|
||||
payload: {
|
||||
shipping_order_extraction_state: {
|
||||
status: 'completed',
|
||||
phase: 'result_persisted',
|
||||
message: '已创建 1 个任务',
|
||||
created_count: 1,
|
||||
opened_existing_count: 0,
|
||||
pending_count: 0,
|
||||
non_shipping_count: 0,
|
||||
created_with_missing_fields_count: 0,
|
||||
batch_no: 'SB-HISTORY-001',
|
||||
terminal: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const messages = await listChatMessages('conv-history-1', 24);
|
||||
|
||||
expect(requestJsonMock).toHaveBeenCalledWith(
|
||||
'/api/chat/messages?conversation_id=conv-history-1&agent_id=24',
|
||||
{ headers: { Authorization: 'Bearer test-token' } },
|
||||
);
|
||||
expect(messages).toHaveLength(2);
|
||||
expect(messages[0]).toEqual({
|
||||
role: 'user',
|
||||
content: '',
|
||||
attachments: [{
|
||||
id: 'attachment-only-1',
|
||||
name: 'notice.eml',
|
||||
type: 'document',
|
||||
source: 'shipping_notice',
|
||||
}],
|
||||
});
|
||||
expect(messages[1]?.shipping_order_extraction_state).toMatchObject({
|
||||
status: 'completed',
|
||||
batch_no: 'SB-HISTORY-001',
|
||||
terminal: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -422,6 +422,11 @@ export async function submitWorkspaceShippingDecision(taskNo: string, decision:
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
/** 人工复核证据只允许已绑定文档单元格或具名人工输入。 */
|
||||
export type ShippingReviewEvidence =
|
||||
| { evidence_type: 'document_cell'; document_id: number; observation_id: number; page_no: number; table_id: string; cell_id: string }
|
||||
| { evidence_type: 'manual_input'; reason: string };
|
||||
|
||||
/**
|
||||
* 更新发货通知单头字段。
|
||||
* @param taskNo - 发货任务编号
|
||||
@@ -432,18 +437,18 @@ export async function submitWorkspaceShippingDecision(taskNo: string, decision:
|
||||
export async function updateWorkspaceShippingNoticeFields(
|
||||
taskNo: string,
|
||||
fields: Partial<ShippingNoticeHeader>,
|
||||
comment?: string,
|
||||
options?: { expectedOrderDataVersion?: number; idempotencyKey?: string },
|
||||
comment: string | undefined,
|
||||
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-fields`,
|
||||
jsonPost({
|
||||
fields,
|
||||
...(comment ? { comment } : {}),
|
||||
...(options?.expectedOrderDataVersion != null
|
||||
? { expected_order_data_version: options.expectedOrderDataVersion }
|
||||
: {}),
|
||||
...(options?.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
|
||||
expected_order_data_version: options.expectedOrderDataVersion,
|
||||
evidence: options.evidence,
|
||||
reason: options.reason,
|
||||
...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
|
||||
}),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
@@ -479,8 +484,8 @@ export async function updateWorkspaceShippingNoticeLine(
|
||||
taskNo: string,
|
||||
lineIndex: number,
|
||||
patch: Partial<ShippingNoticeLine> & { quantity?: number },
|
||||
comment?: string,
|
||||
options?: { expectedOrderDataVersion?: number; idempotencyKey?: string },
|
||||
comment: string | undefined,
|
||||
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-line`,
|
||||
@@ -488,10 +493,10 @@ export async function updateWorkspaceShippingNoticeLine(
|
||||
line_index: lineIndex,
|
||||
patch,
|
||||
...(comment ? { comment } : {}),
|
||||
...(options?.expectedOrderDataVersion != null
|
||||
? { expected_order_data_version: options.expectedOrderDataVersion }
|
||||
: {}),
|
||||
...(options?.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
|
||||
expected_order_data_version: options.expectedOrderDataVersion,
|
||||
evidence: options.evidence,
|
||||
reason: options.reason,
|
||||
...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}),
|
||||
}),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
@@ -522,6 +527,7 @@ export async function resolveWorkspaceShippingFieldConflict(
|
||||
expectedConflictVersion?: number;
|
||||
expectedOrderDataVersion?: number;
|
||||
reason?: string;
|
||||
evidence: ShippingReviewEvidence;
|
||||
idempotencyKey?: string;
|
||||
},
|
||||
) {
|
||||
@@ -542,6 +548,7 @@ export async function resolveWorkspaceShippingFieldConflict(
|
||||
? { expected_order_data_version: payload.expectedOrderDataVersion }
|
||||
: {}),
|
||||
...(payload.reason ? { reason: payload.reason } : {}),
|
||||
evidence: payload.evidence,
|
||||
...(payload.idempotencyKey ? { idempotency_key: payload.idempotencyKey } : {}),
|
||||
}),
|
||||
);
|
||||
@@ -557,11 +564,12 @@ export async function resolveWorkspaceShippingFieldConflict(
|
||||
export async function addWorkspaceShippingNoticeLine(
|
||||
taskNo: string,
|
||||
line: Partial<ShippingNoticeLine> & { quantity?: number },
|
||||
comment?: string,
|
||||
comment: string | undefined,
|
||||
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/add-notice-line`,
|
||||
jsonPost({ line, ...(comment ? { comment } : {}) }),
|
||||
jsonPost({ line, ...(comment ? { comment } : {}), expected_order_data_version: options.expectedOrderDataVersion, evidence: options.evidence, reason: options.reason, ...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}) }),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
@@ -576,11 +584,12 @@ export async function addWorkspaceShippingNoticeLine(
|
||||
export async function removeWorkspaceShippingNoticeLine(
|
||||
taskNo: string,
|
||||
lineIndex: number,
|
||||
comment?: string,
|
||||
comment: string | undefined,
|
||||
options: { expectedOrderDataVersion: number; idempotencyKey?: string; evidence: ShippingReviewEvidence; reason: string },
|
||||
) {
|
||||
const body = await requestJson<ShippingDecisionResponse & ShippingApiStatusPayload>(
|
||||
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/remove-notice-line`,
|
||||
jsonPost({ line_index: lineIndex, ...(comment ? { comment } : {}) }),
|
||||
jsonPost({ line_index: lineIndex, ...(comment ? { comment } : {}), expected_order_data_version: options.expectedOrderDataVersion, evidence: options.evidence, reason: options.reason, ...(options.idempotencyKey ? { idempotency_key: options.idempotencyKey } : {}) }),
|
||||
);
|
||||
return assertShippingOk(body);
|
||||
}
|
||||
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user