feat(shipping-notice): 添加订单抽取功能,支持异步运行和管理,优化相关数据模型和处理逻辑
This commit is contained in:
1 parent
34d489a2d1
commit
ce26d6d0c4
144 files changed
+12241
-4233
No files matched your search
@@ -18,6 +18,7 @@ import app.api.admin.database # noqa: F401
|
||||
import app.api.admin.permissions # noqa: F401
|
||||
import app.api.admin.users # noqa: F401
|
||||
import app.api.admin.wecom # noqa: F401
|
||||
import app.api.admin.shipping_order_extraction # noqa: F401
|
||||
import app.api.admin.announcements # noqa: F401
|
||||
import app.api.admin.shipping_customers # noqa: F401
|
||||
import app.api.admin.shipping_identity_rules # noqa: F401
|
||||
|
||||
@@ -9,6 +9,7 @@ from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.admin import agent_service
|
||||
|
||||
@@ -106,6 +107,38 @@ def test_agent(id: int):
|
||||
return ok(payload, request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/runtime-bindings', methods=['GET'])
|
||||
@require_admin
|
||||
def list_agent_runtime_bindings(id: int):
|
||||
"""列出入口 Agent 的显式运行能力绑定。"""
|
||||
from app.services.agent_runtime_binding_service import list_runtime_bindings
|
||||
|
||||
return ok(list_runtime_bindings(id), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/runtime-bindings/<path:capability_code>', methods=['PUT'])
|
||||
@require_admin
|
||||
def save_agent_runtime_binding(id: int, capability_code: str):
|
||||
"""保存单个能力 Provider;API Key 仍由 Provider Agent 自身配置管理。"""
|
||||
body = request.get_json(silent=True)
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
try:
|
||||
provider_agent_id = int(body.get('provider_agent_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('provider_agent_id is required') from exc
|
||||
from app.services.agent_runtime_binding_service import save_runtime_binding, serialize_runtime_binding
|
||||
|
||||
binding = save_runtime_binding(
|
||||
owner_agent_id=id,
|
||||
capability_code=capability_code,
|
||||
provider_agent_id=provider_agent_id,
|
||||
enabled=body.get('enabled') is not False,
|
||||
config=body.get('config'),
|
||||
)
|
||||
return ok(serialize_runtime_binding(binding), request_id=_request_id())
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
def update_agent_permissions(id: int):
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"""
|
||||
backend/app/api/admin/shipping_order_extraction.py
|
||||
|
||||
用途:提供订单抽取异步 Run 的管理员运维健康视图。
|
||||
依赖:admin Blueprint、require_admin、order_extraction_run_service。
|
||||
逻辑:路由校验监控窗口与阈值后返回安全聚合指标,不暴露文档、Provider 配置或错误正文。
|
||||
"""
|
||||
|
||||
from flask import g, request
|
||||
|
||||
from app.api.admin.blueprint import admin_bp
|
||||
from app.core.decorators import require_admin
|
||||
from app.core.errors import ValidationError
|
||||
from app.core.response import ok
|
||||
from app.services.shipping_notice.order_extraction_run_service import get_order_extraction_run_health
|
||||
|
||||
|
||||
def _query_int(name: str, default: int) -> int:
|
||||
"""读取可选整数查询参数;非整数抛出统一参数错误。"""
|
||||
raw = request.args.get(name)
|
||||
if raw in (None, ''):
|
||||
return default
|
||||
try:
|
||||
return int(raw)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(f'{name} must be an integer') from exc
|
||||
|
||||
|
||||
@admin_bp.route('/shipping-notice/order-extraction-runs/health', methods=['GET'])
|
||||
@require_admin
|
||||
def get_shipping_order_extraction_health():
|
||||
"""返回 Run 积压、失败率、阶段分布和分段时延的管理员安全视图。"""
|
||||
payload = get_order_extraction_run_health(
|
||||
window_hours=_query_int('window_hours', 24),
|
||||
queued_stale_seconds=_query_int('queued_stale_seconds', 300),
|
||||
running_stale_seconds=_query_int('running_stale_seconds', 1800),
|
||||
)
|
||||
return ok(payload, request_id=getattr(g, 'request_id', None))
|
||||
@@ -38,11 +38,11 @@ def _list_active_agents_for_user(user: User) -> list[Agent]:
|
||||
if user.role == 'admin':
|
||||
return (
|
||||
db.session.query(Agent)
|
||||
.filter(Agent.is_active.is_(True))
|
||||
.filter(Agent.is_active.is_(True), Agent.exposure_mode == 'workspace')
|
||||
.order_by(Agent.id.asc())
|
||||
.all()
|
||||
)
|
||||
return [agent for agent in user.agents if agent.is_active]
|
||||
return [agent for agent in user.agents if agent.is_active and agent.exposure_mode == 'workspace']
|
||||
|
||||
|
||||
@agents_bp.route('', methods=['GET'])
|
||||
@@ -70,7 +70,7 @@ def list_agent_guides(agent_id):
|
||||
if agent_id == 0:
|
||||
generic_agent = (
|
||||
db.session.query(Agent)
|
||||
.filter_by(agent_code='generic', is_active=True)
|
||||
.filter_by(agent_code='generic', is_active=True, exposure_mode='workspace')
|
||||
.order_by(Agent.sort_order.asc(), Agent.id.asc())
|
||||
.first()
|
||||
)
|
||||
|
||||
+4
-17
@@ -141,7 +141,6 @@ def _build_chat_adapter_hints(
|
||||
*,
|
||||
shipping_task_id: str | None = None,
|
||||
shipping_batch_no: str | None = None,
|
||||
shipping_intake_nos: list[str] | None = None,
|
||||
shipping_temporary_inventory_asset_no: str | None = None,
|
||||
shipping_temporary_inventory_session_no: str | None = None,
|
||||
) -> dict | None:
|
||||
@@ -153,17 +152,15 @@ def _build_chat_adapter_hints(
|
||||
"""
|
||||
task_id = str(shipping_task_id or '').strip()
|
||||
batch_no = str(shipping_batch_no or '').strip()
|
||||
intake_nos = sorted({str(item or '').strip().upper() for item in (shipping_intake_nos or []) if str(item 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 intake_nos and not temporary_asset_no and not temporary_session_no:
|
||||
if not task_id and not batch_no and not temporary_asset_no and not temporary_session_no:
|
||||
return None
|
||||
return {
|
||||
'shipping_notice': {
|
||||
'task_id': task_id or None,
|
||||
'batch_no': batch_no or None,
|
||||
'intake_nos': intake_nos,
|
||||
'capability': 'temporary_inventory' if temporary_asset_no else ('order_extraction' if intake_nos else 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,
|
||||
}
|
||||
@@ -207,7 +204,7 @@ 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 or 'submit_order_extraction' in value:
|
||||
if 'create_task' in value or 'get_task_status' in value:
|
||||
return f'继续处理当前发货任务 {task_no}'.strip()
|
||||
return value
|
||||
|
||||
@@ -1393,14 +1390,6 @@ def chat_completions():
|
||||
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())
|
||||
@@ -1539,7 +1528,6 @@ def chat_completions():
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no,
|
||||
shipping_temporary_inventory_session_no=shipping_temporary_inventory_session_no,
|
||||
),
|
||||
@@ -1584,8 +1572,7 @@ def chat_completions():
|
||||
adapter_hints=_build_chat_adapter_hints(
|
||||
shipping_task_id=shipping_task_id,
|
||||
shipping_batch_no=shipping_batch_no,
|
||||
shipping_intake_nos=shipping_intake_nos,
|
||||
shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no,
|
||||
shipping_temporary_inventory_asset_no=shipping_temporary_inventory_asset_no,
|
||||
shipping_temporary_inventory_session_no=shipping_temporary_inventory_session_no,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -139,23 +139,6 @@ def tool_create_task():
|
||||
return jsonify(shipping_tools.create_task(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/get_order_extraction_context', methods=['POST'])
|
||||
def tool_get_order_extraction_context():
|
||||
"""
|
||||
返回当前会话待解析邮件及附件文本。
|
||||
【AI 触发时机】:仅当 agent_runtime_context.refs.capability=order_extraction 时,
|
||||
在完整订单抽取 LLM 节点之前调用一次。
|
||||
"""
|
||||
return jsonify(shipping_tools.get_order_extraction_context(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/submit_order_extraction', methods=['POST'])
|
||||
def tool_submit_order_extraction():
|
||||
"""
|
||||
提交 LLM 完整订单抽取结果并由 HXOPS 校验、判重和自动建单。
|
||||
【AI 触发时机】:订单抽取 LLM 与 JSON 标准化节点成功后调用;禁止绕过此 Tool 直接建单。
|
||||
"""
|
||||
return jsonify(shipping_tools.submit_order_extraction(_payload()))
|
||||
|
||||
|
||||
@shipping_notice_bp.route('/tools/create_temporary_inventory_session', methods=['POST'])
|
||||
|
||||
@@ -1342,9 +1342,14 @@ def home():
|
||||
|
||||
def _load_home_payload():
|
||||
if user.role == 'admin':
|
||||
agent_rows = Agent.query.filter(Agent.is_active.is_(True)).all()
|
||||
agent_rows = Agent.query.filter(
|
||||
Agent.is_active.is_(True), Agent.exposure_mode == 'workspace',
|
||||
).all()
|
||||
else:
|
||||
agent_rows = [agent for agent in user.agents if agent.is_active]
|
||||
agent_rows = [
|
||||
agent for agent in user.agents
|
||||
if agent.is_active and agent.exposure_mode == 'workspace'
|
||||
]
|
||||
agent_rows = sort_agent_rows(agent_rows)
|
||||
favorites = db.session.query(UserFavoriteAgent).filter_by(user_id=user.id).all()
|
||||
favorite_ids = [f.agent_id for f in favorites]
|
||||
|
||||
@@ -864,6 +864,78 @@ def workspace_list_shipping_notice_intakes():
|
||||
return _ok({'items': items})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['POST'])
|
||||
def workspace_create_shipping_order_extraction_run():
|
||||
"""冻结当前会话的已解析 Intake 并创建异步订单抽取领域 Run。"""
|
||||
user = _require_user()
|
||||
body = request.get_json(silent=True)
|
||||
if body is None:
|
||||
body = {}
|
||||
if not isinstance(body, dict):
|
||||
raise ValidationError('JSON body must be an object')
|
||||
try:
|
||||
agent_id = int(body.get('agent_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'agent_id is required',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_INVALID',
|
||||
) from exc
|
||||
conversation_id = str(body.get('conversation_id') or '').strip()
|
||||
intake_nos = body.get('intake_nos')
|
||||
if not isinstance(intake_nos, list):
|
||||
raise ValidationError(
|
||||
'intake_nos must be a list',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_INTAKES_INVALID',
|
||||
)
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
create_order_extraction_run,
|
||||
serialize_order_extraction_run,
|
||||
)
|
||||
|
||||
run, reused = create_order_extraction_run(
|
||||
user=user,
|
||||
agent_id=agent_id,
|
||||
conversation_id=conversation_id,
|
||||
intake_nos=intake_nos,
|
||||
)
|
||||
db.session.commit()
|
||||
return ok(
|
||||
{'run': serialize_order_extraction_run(run), 'reused': reused},
|
||||
request_id=getattr(g, 'request_id', None),
|
||||
status=202,
|
||||
)
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs/<run_no>', methods=['GET'])
|
||||
def workspace_get_shipping_order_extraction_run(run_no: str):
|
||||
"""查询当前用户的一次订单抽取 Run;正文快照不会暴露给前端。"""
|
||||
user = _require_user()
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
get_order_extraction_run,
|
||||
serialize_order_extraction_run,
|
||||
)
|
||||
|
||||
return _ok(serialize_order_extraction_run(get_order_extraction_run(user_id=user.id, run_no=run_no)))
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/order-extraction-runs', methods=['GET'])
|
||||
def workspace_list_shipping_order_extraction_runs():
|
||||
"""列出当前用户订单抽取 Run,可按 HXOPS 会话过滤。"""
|
||||
user = _require_user()
|
||||
conversation_id = str(request.args.get('conversation_id') or '').strip() or None
|
||||
try:
|
||||
limit = int(request.args.get('limit') or 50)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('limit must be an integer') from exc
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
list_order_extraction_runs,
|
||||
serialize_order_extraction_run,
|
||||
)
|
||||
|
||||
rows = list_order_extraction_runs(user_id=user.id, conversation_id=conversation_id, limit=limit)
|
||||
return _ok({'items': [serialize_order_extraction_run(row) for row in rows]})
|
||||
|
||||
|
||||
@workspace_shipping_notice_bp.route('/shipping-notice/intakes', methods=['POST'])
|
||||
def workspace_create_shipping_notice_intake():
|
||||
"""基于 FileAsset 创建发货通知接入记录并投递预解析任务。"""
|
||||
|
||||
@@ -208,7 +208,7 @@ class Config:
|
||||
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
|
||||
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
|
||||
)
|
||||
# 建单后是否延后订单抽取,交由 Dify 画布 LLM + submit_order_extraction 完成(默认 true)。
|
||||
# 建单后是否延后订单抽取,由后台 Run/Worker 和专用 Workflow 完成(默认 true)。
|
||||
SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY = os.getenv('SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY', 'true').lower() == 'true'
|
||||
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
|
||||
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
|
||||
@@ -219,9 +219,6 @@ class Config:
|
||||
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
|
||||
)
|
||||
SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS = int(
|
||||
os.getenv('SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS') or '300'
|
||||
)
|
||||
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
|
||||
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
|
||||
SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS = float(
|
||||
|
||||
@@ -5,4 +5,4 @@ backend/app/jobs/handlers/__init__.py
|
||||
逻辑:Wave 2 起在 worker 启动前 import 本包。
|
||||
"""
|
||||
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, wecom_directory_sync # noqa: F401
|
||||
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_parse, shipping_notice_run, shipping_order_extraction, wecom_directory_sync # noqa: F401
|
||||
@@ -0,0 +1,196 @@
|
||||
"""
|
||||
backend/app/jobs/handlers/shipping_order_extraction.py
|
||||
|
||||
用途:消费订单抽取领域 Run,调用显式绑定的 Dify Workflow 并持久化订单结果。
|
||||
依赖:Job queue、AgentRuntimeBinding、order_extraction_workflow、Run 状态机。
|
||||
逻辑:Job 只承载执行尝试;Run 是业务真相。结果先完整落库并进入 result_persisted,再收口 completed/needs_review。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.jobs.context import JobContext
|
||||
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, ShippingOrderExtractionRun
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction_run_result
|
||||
from app.services.shipping_notice.order_extraction_run_service import transition_order_extraction_run
|
||||
from app.services.shipping_notice.order_extraction_workflow import execute_order_extraction_workflow
|
||||
|
||||
|
||||
@register_handler(JobType.SHIPPING_ORDER_EXTRACTION)
|
||||
def run_shipping_order_extraction(ctx: JobContext, payload: dict) -> None:
|
||||
"""
|
||||
执行一次订单抽取 Job。
|
||||
|
||||
Args:
|
||||
ctx: Worker 上下文,仅用于安全日志。
|
||||
payload: 须含 job_id;业务身份只从 Job.business_ref 对应 Run 读取。
|
||||
"""
|
||||
raw_job_id = payload.get('job_id')
|
||||
job = db.session.get(Job, int(raw_job_id)) if raw_job_id else None
|
||||
if job is None:
|
||||
return
|
||||
owned_attempt = int(job.attempts or 0)
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
if run is 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,
|
||||
)
|
||||
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)
|
||||
db.session.commit()
|
||||
finish_job(job.id, result={'run_no': run.run_no, 'status': run.status}, owned_attempt=owned_attempt)
|
||||
return
|
||||
if run.status not in {'queued', 'running'}:
|
||||
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()
|
||||
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')
|
||||
run.current_job_id = job.id
|
||||
run.attempt_count = owned_attempt
|
||||
db.session.commit()
|
||||
|
||||
timeout_seconds = int((run.provider_config_json or {}).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:
|
||||
orders, workflow_meta = execute_order_extraction_workflow(
|
||||
run=run,
|
||||
provider=provider,
|
||||
timeout_seconds=timeout_seconds,
|
||||
)
|
||||
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_id'):
|
||||
run.dify_workflow_run_id = str(workflow_meta['workflow_run_id'])[:128]
|
||||
# [STEP 1] Provider 成功即建立独立提交边界,HXOPS 后续落库重试不得再次调用 Dify。
|
||||
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),
|
||||
)
|
||||
result = submit_order_extraction_run_result(run=run, orders=orders)
|
||||
|
||||
summary = {
|
||||
'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,
|
||||
}
|
||||
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'] 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'}:
|
||||
if retryable and owned_attempt < int(job.max_attempts or 1):
|
||||
if run.status == 'running':
|
||||
transition_order_extraction_run(run, target_status='queued', phase='retry_queued')
|
||||
elif run.status in {'queued', 'running'}:
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='running', phase='failing')
|
||||
transition_order_extraction_run(
|
||||
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,
|
||||
)
|
||||
if retryable:
|
||||
raise
|
||||
@@ -977,6 +977,12 @@ def process_next_job(
|
||||
)
|
||||
|
||||
on_recovered = sync_intake_after_parse_job_recovery
|
||||
elif normalized_type == JobType.SHIPPING_ORDER_EXTRACTION.value:
|
||||
from app.services.shipping_notice.order_extraction_run_service import (
|
||||
sync_order_extraction_run_after_job_recovery,
|
||||
)
|
||||
|
||||
on_recovered = sync_order_extraction_run_after_job_recovery
|
||||
recover_stale_jobs(
|
||||
domain=domain,
|
||||
timeout_seconds=timeout_seconds,
|
||||
|
||||
@@ -16,6 +16,7 @@ class JobType(StrEnum):
|
||||
KB_DIFY_SYNC = 'kb_dify_sync'
|
||||
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
|
||||
SHIPPING_NOTICE_PARSE = 'shipping_notice_parse'
|
||||
SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction'
|
||||
SCHEDULE_RUN = 'schedule_run'
|
||||
FILE_CHECK_RUN = 'file_check_run'
|
||||
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
|
||||
@@ -49,7 +50,7 @@ _HANDLER_TO_KB_JOB_TYPE: dict[JobType, str] = {
|
||||
# worker --queues 参数 → 可消费的 KbJob.job_type 集合
|
||||
QUEUE_KB_JOB_TYPES: dict[str, frozenset[str]] = {
|
||||
'kb': frozenset({'clean', 'path_upload', 'sync_dify'}),
|
||||
'shipping': frozenset({'shipping_notice_run', 'shipping_notice_parse'}),
|
||||
'shipping': frozenset({'shipping_notice_run', 'shipping_notice_parse', 'shipping_order_extraction'}),
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ backend/app/models/__init__.py
|
||||
"""
|
||||
|
||||
from app.models.agent import Agent, AgentDirectoryMember, AgentGuide, PermissionRequest
|
||||
from app.models.agent_runtime_binding import AgentRuntimeBinding
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
from app.models.chat import ChatLog, ChatSession, ChatToolRun, Feedback, GeneralFeedback
|
||||
from app.models.content import Announcement, FaqHotCandidate, QuickQuestion, ZlLanguage
|
||||
@@ -29,6 +30,7 @@ from app.models.shipping import (
|
||||
ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.models.shipping_task_line import ShippingTaskFieldConflict
|
||||
from app.models.shipping_context_provider import ShippingContextProvider, ShippingContextProviderOption
|
||||
from app.models.shipping_excel_template import ShippingExcelTemplate, ShippingExportArtifact
|
||||
from app.models.shipping_order_schema import (
|
||||
ShippingOrderExtraction,
|
||||
@@ -42,6 +44,10 @@ from app.models.shipping_order_schema import (
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.models.shipping_order_customer_match import ShippingOrderCustomerMatch
|
||||
from app.models.shipping_order_extraction_run import (
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRunIntake,
|
||||
)
|
||||
from app.models.shipping_inventory_config import (
|
||||
ShippingInventoryField,
|
||||
ShippingInventoryExternalMapping,
|
||||
@@ -90,6 +96,7 @@ __all__ = [
|
||||
'UserDefaultAgent',
|
||||
'User',
|
||||
'Agent',
|
||||
'AgentRuntimeBinding',
|
||||
'ChatSession',
|
||||
'ChatLog',
|
||||
'ChatToolRun',
|
||||
@@ -115,6 +122,8 @@ __all__ = [
|
||||
'ShippingBatch',
|
||||
'ShippingTask',
|
||||
'ShippingTaskFieldConflict',
|
||||
'ShippingContextProvider',
|
||||
'ShippingContextProviderOption',
|
||||
'ShippingOrderSchema',
|
||||
'ShippingOrderSchemaVersion',
|
||||
'ShippingOrderSchemaAuditEvent',
|
||||
@@ -125,6 +134,8 @@ __all__ = [
|
||||
'ShippingOrderFieldDecision',
|
||||
'ShippingOrderFieldValue',
|
||||
'ShippingOrderCustomerMatch',
|
||||
'ShippingOrderExtractionRun',
|
||||
'ShippingOrderExtractionRunIntake',
|
||||
'ShippingCustomer',
|
||||
'ShippingCustomerIdentifier',
|
||||
'ShippingCustomerExternalRef',
|
||||
|
||||
@@ -11,7 +11,7 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy import Boolean, CheckConstraint, DateTime, ForeignKey, Integer, JSON, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base, user_agent_permissions
|
||||
@@ -25,6 +25,12 @@ class Agent(Base):
|
||||
"""
|
||||
|
||||
__tablename__ = 'agents'
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"exposure_mode IN ('workspace', 'internal')",
|
||||
name='ck_agents_exposure_mode',
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
name: Mapped[str] = mapped_column(String(100))
|
||||
@@ -44,6 +50,7 @@ class Agent(Base):
|
||||
runtime_provider: Mapped[str] = mapped_column(String(32), default='dify', nullable=False)
|
||||
conversation_mode: Mapped[str] = mapped_column(String(32), default='chat', nullable=False)
|
||||
dify_app_type: Mapped[str] = mapped_column(String(20), default='chatflow', nullable=False)
|
||||
exposure_mode: Mapped[str] = mapped_column(String(20), default='workspace', nullable=False)
|
||||
iframe_url: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
|
||||
category: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
sub_category: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
backend/app/models/agent_runtime_binding.py
|
||||
|
||||
用途:定义用户入口 Agent 到内部运行能力 Provider 的显式绑定。
|
||||
依赖:agents 表。
|
||||
逻辑:业务代码只按 owner_agent_id + capability_code 解析 Provider;Dify App ID、Key 和 URL 继续由 Provider Agent 保存。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import Boolean, ForeignKey, JSON, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class AgentRuntimeBinding(Base):
|
||||
"""一个 Agent 的命名运行能力绑定;同一能力只允许一个当前 Provider。"""
|
||||
|
||||
__tablename__ = 'agent_runtime_bindings'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('owner_agent_id', 'capability_code', name='uq_agent_runtime_binding_capability'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
owner_agent_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('agents.id', ondelete='CASCADE'), nullable=False, index=True,
|
||||
)
|
||||
capability_code: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
||||
provider_agent_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('agents.id'), nullable=False, index=True,
|
||||
)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default='1', nullable=False)
|
||||
config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
owner_agent: Mapped['Agent'] = relationship('Agent', foreign_keys=[owner_agent_id])
|
||||
provider_agent: Mapped['Agent'] = relationship('Agent', foreign_keys=[provider_agent_id])
|
||||
@@ -48,6 +48,23 @@ class Job(Base):
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
),
|
||||
Index(
|
||||
'uq_jobs_shipping_order_extraction_active_ref',
|
||||
'domain',
|
||||
'job_type',
|
||||
'business_ref',
|
||||
unique=True,
|
||||
postgresql_where=text(
|
||||
"job_type = 'shipping_order_extraction' "
|
||||
"AND status IN ('queued', 'running') "
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
sqlite_where=text(
|
||||
"job_type = 'shipping_order_extraction' "
|
||||
"AND status IN ('queued', 'running') "
|
||||
"AND business_ref IS NOT NULL"
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
|
||||
@@ -563,6 +563,9 @@ class ShippingNoticeCandidate(Base):
|
||||
order_extraction_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extractions.id'), nullable=True, index=True,
|
||||
)
|
||||
order_extraction_run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
extraction_source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
|
||||
classification_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
|
||||
field_confidence_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
backend/app/models/shipping_context_provider.py
|
||||
|
||||
用途:定义订单通用上下文字段可选择的确定性来源目录及受控选项。
|
||||
依赖:models.base.Base、SQLAlchemy。
|
||||
逻辑:数据库维护来源展示与启停状态;代码注册表校验 provider_key/option_key 是否具有真实采集实现。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, ForeignKey, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingContextProvider(Base):
|
||||
"""确定性上下文来源族;只允许绑定代码注册的 provider_key。"""
|
||||
|
||||
__tablename__ = 'shipping_context_providers'
|
||||
__table_args__ = (
|
||||
CheckConstraint("status IN ('active', 'disabled')", name='ck_shipping_context_providers_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
provider_key: Mapped[str] = mapped_column(String(64), nullable=False, unique=True)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
options: Mapped[list['ShippingContextProviderOption']] = relationship(
|
||||
back_populates='provider', cascade='all, delete-orphan', order_by='ShippingContextProviderOption.id'
|
||||
)
|
||||
|
||||
|
||||
class ShippingContextProviderOption(Base):
|
||||
"""来源族下的受控值选项;option_key 必须与代码注册表中的能力一致。"""
|
||||
|
||||
__tablename__ = 'shipping_context_provider_options'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('provider_id', 'option_key', name='uq_shipping_context_provider_options_key'),
|
||||
CheckConstraint("value_type IN ('string')", name='ck_shipping_context_provider_options_value_type'),
|
||||
CheckConstraint(
|
||||
"sensitivity_level IN ('low', 'personal', 'confidential')",
|
||||
name='ck_shipping_context_provider_options_sensitivity',
|
||||
),
|
||||
CheckConstraint(
|
||||
"default_dify_exposure_policy IN ('never', 'redacted', 'confirmed_readonly')",
|
||||
name='ck_shipping_context_provider_options_dify_policy',
|
||||
),
|
||||
CheckConstraint("status IN ('active', 'disabled')", name='ck_shipping_context_provider_options_status'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
provider_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_context_providers.id', ondelete='CASCADE'), nullable=False
|
||||
)
|
||||
option_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
display_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
value_type: Mapped[str] = mapped_column(String(16), nullable=False, default='string', server_default='string')
|
||||
sensitivity_level: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
default_dify_exposure_policy: Mapped[str] = mapped_column(
|
||||
String(32), nullable=False, default='never', server_default='never'
|
||||
)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
|
||||
provider: Mapped[ShippingContextProvider] = relationship(back_populates='options')
|
||||
@@ -3,7 +3,7 @@ backend/app/models/shipping_identity_rule.py
|
||||
|
||||
用途:定义货代客户/送货站点的可配置识别定义、发布规则集和追加式审计。
|
||||
依赖:订单字段目录、客户/站点主数据、users。
|
||||
逻辑:定义引用稳定订单 field_id;规则集冻结定义快照;证据值绑定定义而不再依赖代码枚举。
|
||||
逻辑:定义只引用已发布订单上下文字段;规则集冻结字段配置;证据值绑定定义。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -24,20 +24,16 @@ def _uuid() -> str:
|
||||
|
||||
|
||||
class ShippingIdentityDefinition(Base):
|
||||
"""管理员维护的稳定识别定义;平台只校验其受控来源适配器及参数。"""
|
||||
"""管理员维护的稳定识别定义;取值规则唯一来自已发布订单 Schema 字段。"""
|
||||
|
||||
__tablename__ = 'shipping_identity_definitions'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('definition_code', name='uq_shipping_identity_definitions_code'),
|
||||
CheckConstraint("target_type IN ('customer', 'site')", name='ck_shipping_identity_definitions_target'),
|
||||
CheckConstraint(
|
||||
"source_adapter_key IN ('email_metadata', 'document_template', 'order_field')",
|
||||
name='ck_shipping_identity_definitions_source_adapter',
|
||||
),
|
||||
CheckConstraint("max_automation IN ('none', 'conditional')", name='ck_shipping_identity_definitions_automation'),
|
||||
CheckConstraint("status IN ('active', 'retired')", name='ck_shipping_identity_definitions_status'),
|
||||
Index('ix_shipping_identity_definitions_target_status', 'target_type', 'status'),
|
||||
Index('ix_shipping_identity_definitions_order_field', 'order_field_id'),
|
||||
Index('ix_shipping_identity_definitions_context_field', 'context_field_id'),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
|
||||
@@ -46,12 +42,7 @@ class ShippingIdentityDefinition(Base):
|
||||
description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
evidence_label: Mapped[str] = mapped_column(String(128), nullable=False, default='', server_default='')
|
||||
target_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
source_adapter_key: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
source_selector_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
|
||||
attribute_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
order_field_id: Mapped[Optional[str]] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=True)
|
||||
normalizer_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
comparator_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
context_field_id: Mapped[str] = mapped_column(ForeignKey('shipping_order_fields.id'), nullable=False)
|
||||
default_weight: Mapped[int] = mapped_column(Integer, nullable=False, default=0, server_default='0')
|
||||
max_automation: Mapped[str] = mapped_column(String(16), nullable=False, default='none', server_default='none')
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
backend/app/models/shipping_order_extraction_run.py
|
||||
|
||||
用途:定义建单前订单抽取的领域运行记录及其冻结 Intake 集合。
|
||||
依赖:agents、users、jobs、shipping_notice_intakes、shipping_order_schema_versions。
|
||||
逻辑:Run 保存用户可见生命周期和不可变输入快照;通用 Job 只承担执行尝试,Candidate/Extraction 通过 run_id 回溯本次运行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Any, Optional
|
||||
|
||||
from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from app.models.base import Base
|
||||
|
||||
|
||||
class ShippingOrderExtractionRun(Base):
|
||||
"""一次建单前订单抽取业务运行;状态只允许按领域状态机单调推进。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_runs'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('run_no', name='uq_shipping_order_extraction_runs_no'),
|
||||
UniqueConstraint('idempotency_key', name='uq_shipping_order_extraction_runs_idempotency'),
|
||||
CheckConstraint(
|
||||
"status IN ('queued', 'running', 'result_persisted', 'completed', "
|
||||
"'needs_review', 'failed', 'cancelled')",
|
||||
name='ck_shipping_order_extraction_runs_status',
|
||||
),
|
||||
Index('ix_shipping_order_extraction_runs_user_created', 'user_id', 'created_at'),
|
||||
Index('ix_shipping_order_extraction_runs_conversation_created', 'conversation_id', 'created_at'),
|
||||
Index('ix_shipping_order_extraction_runs_status_created', 'status', 'created_at'),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
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,
|
||||
)
|
||||
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)
|
||||
conversation_id: Mapped[str] = mapped_column(String(100), nullable=False, index=True)
|
||||
schema_version_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_schema_versions.id'), nullable=False,
|
||||
)
|
||||
input_snapshot_hash: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False)
|
||||
idempotency_key: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
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)
|
||||
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)
|
||||
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
|
||||
lock_version: Mapped[int] = mapped_column(Integer, default=1, server_default='1', nullable=False)
|
||||
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,
|
||||
)
|
||||
started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
result_persisted_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
|
||||
intakes: Mapped[list['ShippingOrderExtractionRunIntake']] = relationship(
|
||||
back_populates='run', cascade='all, delete-orphan', order_by='ShippingOrderExtractionRunIntake.position',
|
||||
)
|
||||
|
||||
|
||||
class ShippingOrderExtractionRunIntake(Base):
|
||||
"""Run 冻结的 Intake 成员;position 保证输入集合顺序稳定且可审计。"""
|
||||
|
||||
__tablename__ = 'shipping_order_extraction_run_intakes'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('run_id', 'intake_id', name='uq_shipping_order_extraction_run_intake'),
|
||||
UniqueConstraint('run_id', 'position', name='uq_shipping_order_extraction_run_position'),
|
||||
Index('ix_shipping_order_extraction_run_intakes_intake', 'intake_id'),
|
||||
Index(
|
||||
'uq_shipping_order_extraction_run_intakes_active_intake',
|
||||
'intake_id',
|
||||
unique=True,
|
||||
postgresql_where=text('released_at IS NULL'),
|
||||
sqlite_where=text('released_at IS NULL'),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_id: Mapped[int] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id', ondelete='CASCADE'), nullable=False,
|
||||
)
|
||||
intake_id: Mapped[int] = mapped_column(ForeignKey('shipping_notice_intakes.id'), nullable=False)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
released_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
|
||||
run: Mapped['ShippingOrderExtractionRun'] = relationship(back_populates='intakes')
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/models/shipping_order_schema.py
|
||||
|
||||
用途:定义货代订单唯一 Schema、不可变版本、配置审计及动态订单解析结果。
|
||||
依赖:models.base.Base、shipping_tasks、shipping_notice_intakes、users。
|
||||
依赖:models.base.Base、shipping_tasks、shipping_notice_intakes、shipping_context_providers、users。
|
||||
逻辑:草稿和发布版本统一保存完整 JSON 定义;写操作追加审计事件;解析链锁定发布版本并保存裁决结果。
|
||||
"""
|
||||
|
||||
@@ -38,6 +38,11 @@ def _uuid() -> str:
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
def _default_field_category(context: Any) -> str:
|
||||
"""为未显式分类的既有 ORM 创建路径按 scope 生成订单字段分类。"""
|
||||
return 'order_line' if context.get_current_parameters().get('scope') == 'line' else 'order_header'
|
||||
|
||||
|
||||
class ShippingOrderSchema(Base):
|
||||
"""全局唯一货代订单 Schema;当前业务只允许一个逻辑 Schema。"""
|
||||
|
||||
@@ -71,6 +76,14 @@ class ShippingOrderField(Base):
|
||||
__table_args__ = (
|
||||
UniqueConstraint('schema_id', 'field_code', name='uq_shipping_order_fields_schema_code'),
|
||||
CheckConstraint("scope IN ('header', 'line')", name='ck_shipping_order_fields_scope'),
|
||||
CheckConstraint(
|
||||
"field_category IN ('general_context', 'order_header', 'order_line')",
|
||||
name='ck_shipping_order_fields_category',
|
||||
),
|
||||
CheckConstraint(
|
||||
"collection_mode IN ('deterministic_context', 'llm_extraction')",
|
||||
name='ck_shipping_order_fields_collection_mode',
|
||||
),
|
||||
CheckConstraint(
|
||||
"value_type IN ('string', 'decimal', 'integer', 'date', 'boolean', 'enum')",
|
||||
name='ck_shipping_order_fields_value_type',
|
||||
@@ -84,6 +97,8 @@ class ShippingOrderField(Base):
|
||||
field_code: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
scope: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
value_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
field_category: Mapped[str] = mapped_column(String(32), nullable=False, default=_default_field_category)
|
||||
collection_mode: Mapped[str] = mapped_column(String(32), nullable=False, default='llm_extraction')
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False, default='active', server_default='active')
|
||||
published_once: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False, server_default=text('false'))
|
||||
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
|
||||
@@ -177,6 +192,9 @@ class ShippingOrderExtraction(Base):
|
||||
)
|
||||
|
||||
id: Mapped[int] = mapped_column(primary_key=True)
|
||||
run_id: Mapped[Optional[int]] = mapped_column(
|
||||
ForeignKey('shipping_order_extraction_runs.id'), nullable=True, index=True,
|
||||
)
|
||||
task_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_tasks.id'), nullable=True)
|
||||
intake_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_intakes.id'), nullable=True)
|
||||
schema_version_id: Mapped[int] = mapped_column(ForeignKey('shipping_order_schema_versions.id'), nullable=False)
|
||||
|
||||
@@ -14,8 +14,8 @@ import requests
|
||||
|
||||
from app import db
|
||||
from app.core.config.settings import Config
|
||||
from app.core.errors import NotFoundError, ValidationError
|
||||
from app.models import Agent, User
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Agent, AgentRuntimeBinding, ShippingOrderExtractionRun, User
|
||||
from app.services.agent_directory import normalize_directory_member_ids, replace_directory_members
|
||||
from app.services.admin.training_exam_pdf_service import parse_training_question_bank_from_guide
|
||||
from app.services.agent_registry.admin_payload import apply_agent_payload, validate_agent_payload
|
||||
@@ -60,6 +60,24 @@ def create_agent(data: dict[str, Any]) -> dict:
|
||||
db.session.flush()
|
||||
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
|
||||
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
|
||||
runtime_binding = data.get('order_extraction_runtime_binding')
|
||||
if runtime_binding is not None:
|
||||
if not isinstance(runtime_binding, dict):
|
||||
raise ValidationError('order_extraction_runtime_binding 必须为 JSON 对象')
|
||||
try:
|
||||
provider_agent_id = int(runtime_binding.get('provider_agent_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('provider_agent_id is required') from exc
|
||||
from app.services.agent_runtime_binding_service import save_runtime_binding
|
||||
|
||||
save_runtime_binding(
|
||||
owner_agent_id=agent.id,
|
||||
capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider_agent_id,
|
||||
enabled=runtime_binding.get('enabled') is not False,
|
||||
config=runtime_binding.get('config'),
|
||||
commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
return {'id': agent.id}
|
||||
|
||||
@@ -86,6 +104,7 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None:
|
||||
'runtime_provider': data.get('runtime_provider', agent.runtime_provider),
|
||||
'conversation_mode': data.get('conversation_mode', agent.conversation_mode),
|
||||
'dify_app_type': data.get('dify_app_type', agent.dify_app_type),
|
||||
'exposure_mode': data.get('exposure_mode', agent.exposure_mode),
|
||||
'iframe_url': data.get('iframe_url', agent.iframe_url),
|
||||
'category': data.get('category', agent.category),
|
||||
'sub_category': data.get('sub_category', agent.sub_category),
|
||||
@@ -108,13 +127,45 @@ def update_agent(agent_id: int, data: dict[str, Any]) -> None:
|
||||
if 'directory_member_ids' in data or 'is_aggregate' in data:
|
||||
member_ids = data.get('directory_member_ids') if agent.is_aggregate else []
|
||||
replace_directory_members(agent, normalize_directory_member_ids(member_ids, directory_agent_id=agent.id))
|
||||
runtime_binding = data.get('order_extraction_runtime_binding')
|
||||
if runtime_binding is not None:
|
||||
if not isinstance(runtime_binding, dict):
|
||||
raise ValidationError('order_extraction_runtime_binding 必须为 JSON 对象')
|
||||
try:
|
||||
provider_agent_id = int(runtime_binding.get('provider_agent_id'))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError('provider_agent_id is required') from exc
|
||||
from app.services.agent_runtime_binding_service import save_runtime_binding
|
||||
|
||||
save_runtime_binding(
|
||||
owner_agent_id=agent.id,
|
||||
capability_code='shipping.order_extraction',
|
||||
provider_agent_id=provider_agent_id,
|
||||
enabled=runtime_binding.get('enabled') is not False,
|
||||
config=runtime_binding.get('config'),
|
||||
commit=False,
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def delete_agent(agent_id: int) -> None:
|
||||
"""删除 Agent(不存在时静默成功)。"""
|
||||
"""删除 Agent;被能力绑定或历史订单抽取 Run 引用时明确阻断。"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if agent:
|
||||
binding_count = AgentRuntimeBinding.query.filter(
|
||||
(AgentRuntimeBinding.owner_agent_id == agent.id)
|
||||
| (AgentRuntimeBinding.provider_agent_id == agent.id)
|
||||
).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(
|
||||
'Agent is referenced by runtime capability history',
|
||||
code='AGENT.RUNTIME_PROVIDER_DELETE_BLOCKED',
|
||||
details={'binding_count': binding_count, 'run_count': run_count},
|
||||
)
|
||||
db.session.delete(agent)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ MIGRATED_EXTRA_REGISTRY_KEYS = frozenset({
|
||||
'runtime_provider',
|
||||
'conversation_mode',
|
||||
'dify_app_type',
|
||||
'exposure_mode',
|
||||
'iframe_url',
|
||||
'category',
|
||||
'sub_category',
|
||||
@@ -150,6 +151,7 @@ def validate_agent_payload(
|
||||
valid_runtime_providers = get_platform_enum_set('runtime_providers')
|
||||
valid_conversation_modes = get_platform_enum_set('conversation_modes')
|
||||
valid_dify_app_types = get_platform_enum_set('dify_app_types')
|
||||
valid_exposure_modes = get_platform_enum_set('exposure_modes')
|
||||
valid_suggested_styles = get_platform_enum_set('suggested_questions_styles')
|
||||
dify_required_providers = get_dify_required_providers()
|
||||
|
||||
@@ -175,6 +177,12 @@ def validate_agent_payload(
|
||||
if dify_app_type not in valid_dify_app_types:
|
||||
dify_app_type = 'chatflow'
|
||||
|
||||
exposure_mode = _strip(data.get('exposure_mode')) or (
|
||||
getattr(agent, 'exposure_mode', None) if agent else 'workspace'
|
||||
) or 'workspace'
|
||||
if exposure_mode not in valid_exposure_modes:
|
||||
raise ValidationError(f'无效的 exposure_mode: {exposure_mode}')
|
||||
|
||||
dify_app_id = _strip(data.get('dify_app_id')) or (agent.dify_app_id if agent else '')
|
||||
if runtime_provider in dify_required_providers and not dify_app_id:
|
||||
raise ValidationError('runtime_provider 含 dify 时 dify_app_id 必填')
|
||||
@@ -260,6 +268,7 @@ def validate_agent_payload(
|
||||
'runtime_provider': runtime_provider,
|
||||
'conversation_mode': conversation_mode,
|
||||
'dify_app_type': dify_app_type,
|
||||
'exposure_mode': exposure_mode,
|
||||
'iframe_url': iframe_url or None,
|
||||
'category': _strip(data.get('category')) or None,
|
||||
'sub_category': _strip(data.get('sub_category')) or None,
|
||||
@@ -285,7 +294,7 @@ def apply_agent_payload(agent: Agent, normalized: dict[str, Any]) -> None:
|
||||
"""
|
||||
column_fields = (
|
||||
'name', 'description', 'icon_url', 'is_active', 'is_aggregate', 'dify_app_id', 'api_base_url', 'type',
|
||||
'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'iframe_url',
|
||||
'agent_code', 'runtime_provider', 'conversation_mode', 'dify_app_type', 'exposure_mode', 'iframe_url',
|
||||
'category', 'sub_category', 'sort_order', 'welcome_message', 'suggested_questions_style',
|
||||
'suggested_questions', 'capabilities', 'file_upload_policy', 'bound_schedule_task_id',
|
||||
'handler_config',
|
||||
|
||||
@@ -46,6 +46,7 @@ def build_agent_registry_schema() -> dict[str, Any]:
|
||||
'forced_capabilities': dict(entry.get('forced_capabilities') or {}),
|
||||
'progress_contract': deepcopy_schema(entry.get('progress_contract')),
|
||||
'default_intent_routes': list(entry.get('default_intent_routes') or []),
|
||||
'required_runtime_capabilities': deepcopy_schema(entry.get('required_runtime_capabilities')),
|
||||
})
|
||||
|
||||
return {
|
||||
@@ -53,6 +54,7 @@ def build_agent_registry_schema() -> dict[str, Any]:
|
||||
'runtime_providers': list(platform.get('runtime_providers') or []),
|
||||
'conversation_modes': list(platform.get('conversation_modes') or []),
|
||||
'dify_app_types': list(platform.get('dify_app_types') or []),
|
||||
'exposure_modes': list(platform.get('exposure_modes') or []),
|
||||
'suggested_questions_styles': list(platform.get('suggested_questions_styles') or []),
|
||||
'default_capabilities': get_default_capabilities(),
|
||||
'tool_run_progress_defaults': get_tool_run_progress_defaults(),
|
||||
|
||||
@@ -14,6 +14,9 @@ platform:
|
||||
dify_app_types:
|
||||
- chatflow
|
||||
- workflow
|
||||
exposure_modes:
|
||||
- workspace
|
||||
- internal
|
||||
suggested_questions_styles:
|
||||
- plain
|
||||
- styled
|
||||
@@ -83,6 +86,13 @@ 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]
|
||||
file_check:
|
||||
label: 文件检核
|
||||
conversation_mode_default: task_chat
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
"""
|
||||
backend/app/services/agent_registry/handlers/shipping_notice.py
|
||||
|
||||
用途:货代发货通知 Hybrid Handler — 聊天流订单抽取生命周期、UI State 与上下文准备。
|
||||
依赖:shipping_notice.order_extraction/query_service、chat.log_service、ui_state、agent_registry.handlers.registry。
|
||||
逻辑:Dify 请求前登记并推送订单抽取状态,terminal/error 后收口、持久化结果并补发 Batch UI State;
|
||||
不替代 Dify 正文生成。
|
||||
用途:货代发货通知 Hybrid Handler,负责普通聊天中的任务/批次 UI State。
|
||||
依赖:shipping_notice.query_service/ui_state、agent_registry.handlers.registry。
|
||||
逻辑:根据显式 task/batch 上下文构造并推送 UI State;订单抽取由后台 Run/Worker 独立执行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -39,10 +36,8 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
"""
|
||||
货代发货通知业务 Handler。
|
||||
|
||||
核心逻辑:订单抽取请求进入 Dify 前登记 request/intakes 并推送 extracting;终态时先落失败、
|
||||
推送并持久化抽取结果,再按 adapter_hints / task_id / batch_no 构造 shipping_ui_state。
|
||||
阶段约束:`open_existing` 终态必须能为前端提供恢复锚点;最小字段是 `task_no`,若已知批次则补
|
||||
`batch_no`,若已构造快照则补 `ui_state / batch_ui_state`,供实时消息与历史回放共用。
|
||||
核心逻辑:按 adapter_hints / task_id / batch_no 构造 shipping_ui_state,供实时消息使用。
|
||||
订单抽取状态卡由 Run API 和本地消息持久化恢复,不进入普通 Dify Chatflow 生命周期。
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
@@ -52,128 +47,30 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
shipping_hints = hints.get('shipping_notice')
|
||||
return shipping_hints if isinstance(shipping_hints, dict) else {}
|
||||
|
||||
@classmethod
|
||||
def _order_extraction_intake_nos(cls, ctx: ChatStreamContext) -> list[str]:
|
||||
"""仅在订单抽取能力匹配时返回本轮 Intake 集合,避免普通续办误触抽取收口。"""
|
||||
hints = cls._shipping_hints(ctx)
|
||||
if (
|
||||
str(hints.get('capability') or '') != 'order_extraction'
|
||||
or not isinstance(hints.get('intake_nos'), list)
|
||||
):
|
||||
return []
|
||||
return sorted({
|
||||
str(item or '').strip().upper()
|
||||
for item in hints.get('intake_nos') or []
|
||||
if str(item or '').strip()
|
||||
})
|
||||
|
||||
@staticmethod
|
||||
def _workflow_failure_message(event_data: dict[str, Any]) -> str:
|
||||
"""从 Dify terminal/error 事件提取已友好化的错误文本,缺失时返回空字符串。"""
|
||||
event_name = str(event_data.get('event') or '').strip()
|
||||
data = event_data.get('data') if isinstance(event_data.get('data'), dict) else {}
|
||||
failed = event_name == 'error' or (
|
||||
event_name == 'workflow_finished'
|
||||
and str(data.get('status') or '').strip().lower() == 'failed'
|
||||
)
|
||||
if not failed:
|
||||
return ''
|
||||
for value in (
|
||||
event_data.get('message'),
|
||||
event_data.get('error'),
|
||||
event_data.get('description'),
|
||||
data.get('message'),
|
||||
data.get('error'),
|
||||
data.get('description'),
|
||||
):
|
||||
text = str(value or '').strip()
|
||||
if text:
|
||||
return text
|
||||
return '订单识别失败,请重新发送当前邮件。'
|
||||
|
||||
def prepare_stream(self, ctx: ChatStreamContext) -> ChatStreamContext:
|
||||
"""
|
||||
在订单抽取请求进入 Dify 前登记权威 extracting 状态。
|
||||
|
||||
核心逻辑:仅消费平台 adapter_hints 中的固定能力契约,并把 HXOPS request_id 绑定到完整 Intake 集合;
|
||||
失败直接阻止上游调用,避免前端显示本地 extracting 而后端仍为 not_started。
|
||||
"""
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if not intake_nos:
|
||||
return ctx
|
||||
from app.services.shipping_notice.order_extraction import start_order_extraction
|
||||
|
||||
start_order_extraction(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
request_id=ctx.request_id,
|
||||
)
|
||||
return ctx
|
||||
|
||||
def build_ui_state_event(
|
||||
self,
|
||||
ctx: ChatStreamContext,
|
||||
*,
|
||||
resolve_order_extraction: bool = False,
|
||||
) -> dict[str, Any] | None:
|
||||
def build_ui_state_event(self, ctx: ChatStreamContext) -> dict[str, Any] | None:
|
||||
"""
|
||||
构造 shipping_ui_state SSE 事件。
|
||||
|
||||
用途:为聊天页当前消息与历史回放提供任务/批次恢复锚点。
|
||||
核心逻辑:优先显式 task_id,其次 batch 焦点任务;订单抽取终态可按 intake 反查新建批次或
|
||||
`open_existing` 命中的既有任务。`open_existing` 场景下即使没有新建批次,也必须至少返回
|
||||
`task_no`;失败时记录日志并返回 None。
|
||||
核心逻辑:优先显式 task_id,其次 batch 焦点任务;失败时记录日志并返回 None。
|
||||
"""
|
||||
if not _uses_shipping_ui_state_progress(ctx.agent):
|
||||
return None
|
||||
|
||||
task_id = str(ctx.shipping_task_id or '').strip()
|
||||
batch_no = str(ctx.shipping_batch_no or '').strip()
|
||||
shipping_hints = self._shipping_hints(ctx)
|
||||
if not task_id and not batch_no:
|
||||
task_id = str(shipping_hints.get('task_id') or '').strip()
|
||||
batch_no = str(shipping_hints.get('batch_no') or '').strip()
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if not task_id and not batch_no and not (resolve_order_extraction and intake_nos):
|
||||
if not task_id and not batch_no:
|
||||
return None
|
||||
|
||||
try:
|
||||
from app.services.shipping_notice.query_service import (
|
||||
get_batch_by_no,
|
||||
get_task_by_ref,
|
||||
resolve_order_extraction_ui_target,
|
||||
)
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref
|
||||
from app.services.shipping_notice.ui_state import build_batch_ui_state, build_task_ui_state
|
||||
|
||||
task = get_task_by_ref(task_id) if task_id else None
|
||||
batch = get_batch_by_no(batch_no) if batch_no else None
|
||||
resolved_from_order_extraction = False
|
||||
if task is None and batch is None and resolve_order_extraction and intake_nos:
|
||||
batch, task = resolve_order_extraction_ui_target(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
conversation_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
)
|
||||
resolved_from_order_extraction = batch is not None or task is not None
|
||||
session_id = str(getattr(ctx.session, 'session_id', '') or '')
|
||||
if resolved_from_order_extraction and batch is not None:
|
||||
batch_ui_state = build_batch_ui_state(batch)
|
||||
focus_task = batch_ui_state.get('focus_task') if isinstance(batch_ui_state.get('focus_task'), dict) else {}
|
||||
focus_ui_state = (
|
||||
batch_ui_state.get('focus_task_ui_state')
|
||||
if isinstance(batch_ui_state.get('focus_task_ui_state'), dict)
|
||||
else None
|
||||
)
|
||||
return {
|
||||
'event': 'shipping_ui_state',
|
||||
'conversation_id': session_id,
|
||||
'batch_no': batch.batch_no,
|
||||
'task_no': focus_task.get('task_no'),
|
||||
'batch_ui_state': batch_ui_state,
|
||||
**({'ui_state': focus_ui_state} if focus_ui_state is not None else {}),
|
||||
'source': 'order_extraction',
|
||||
}
|
||||
if task is None and batch is not None:
|
||||
focus_task_no = str(batch.current_focus_task_no or '').strip()
|
||||
if focus_task_no:
|
||||
@@ -187,7 +84,6 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
'task_no': task.task_no,
|
||||
'batch_no': task.batch.batch_no if task.batch is not None else None,
|
||||
'ui_state': build_task_ui_state(task),
|
||||
**({'source': 'order_extraction'} if resolved_from_order_extraction else {}),
|
||||
}
|
||||
if batch is not None:
|
||||
batch_ui_state = build_batch_ui_state(batch)
|
||||
@@ -215,125 +111,6 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
)
|
||||
return None
|
||||
|
||||
def build_order_extraction_state_event(
|
||||
self,
|
||||
ctx: ChatStreamContext,
|
||||
) -> dict[str, Any] | None:
|
||||
"""
|
||||
构造当前请求的 shipping_order_extraction_state SSE 事件。
|
||||
|
||||
核心逻辑:只为固定订单抽取能力契约读取权威 Intake 状态;身份围栏失败时记录日志并跳过,
|
||||
避免把旧请求或其他会话结果推送到当前消息。
|
||||
|
||||
Args:
|
||||
ctx: 当前聊天流上下文,必须包含用户、会话、request_id 与 Intake 集合。
|
||||
|
||||
Returns:
|
||||
可直接格式化为 SSE 的事件字典;非订单抽取回合或读取失败时返回 None。
|
||||
"""
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if not intake_nos:
|
||||
return None
|
||||
try:
|
||||
from app.services.shipping_notice.order_extraction import get_order_extraction_state
|
||||
|
||||
state = get_order_extraction_state(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
request_id=ctx.request_id,
|
||||
)
|
||||
return {
|
||||
'event': 'shipping_order_extraction_state',
|
||||
'conversation_id': str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
**state,
|
||||
}
|
||||
except Exception:
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
'[shipping-handler] build order extraction state failed request_id=%s intakes=%s',
|
||||
ctx.request_id,
|
||||
intake_nos,
|
||||
)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _build_history_recovery_payload_patch(
|
||||
*,
|
||||
state_event: dict[str, Any] | None,
|
||||
ui_event: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
提取历史回放所需的最小恢复载荷。
|
||||
|
||||
核心逻辑:抽取终态负责统计摘要,UI State 负责任务/批次锚点;两者都存在时合并为同一条
|
||||
ChatLog.payload patch,保证历史消息可直接恢复工作台。
|
||||
"""
|
||||
payload_patch: dict[str, Any] = {}
|
||||
if isinstance(state_event, dict) and state_event.get('terminal') is True:
|
||||
payload_patch['shipping_order_extraction_state'] = {
|
||||
key: value
|
||||
for key, value in state_event.items()
|
||||
if key not in {'event', 'conversation_id'}
|
||||
}
|
||||
if isinstance(ui_event, dict) and str(ui_event.get('event') or '') == 'shipping_ui_state':
|
||||
task_no = str(ui_event.get('task_no') or '').strip()
|
||||
if task_no:
|
||||
payload_patch['task_no'] = task_no
|
||||
if 'batch_no' in ui_event:
|
||||
batch_no = str(ui_event.get('batch_no') or '').strip()
|
||||
payload_patch['batch_no'] = batch_no or None
|
||||
ui_state = ui_event.get('ui_state')
|
||||
if isinstance(ui_state, dict):
|
||||
payload_patch['shipping_ui_state'] = ui_state
|
||||
batch_ui_state = ui_event.get('batch_ui_state')
|
||||
if isinstance(batch_ui_state, dict):
|
||||
payload_patch['shipping_batch_ui_state'] = batch_ui_state
|
||||
return payload_patch
|
||||
|
||||
def _persist_history_recovery_payload(
|
||||
self,
|
||||
ctx: ChatStreamContext,
|
||||
event_data: dict[str, Any],
|
||||
*,
|
||||
state_event: dict[str, Any] | None = None,
|
||||
ui_event: dict[str, Any] | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
把订单抽取终态与 UI 锚点合并到本轮已落库 ChatLog,供历史消息恢复。
|
||||
|
||||
核心逻辑:使用上游终态附带的 chat_log_id 与当前身份做归属校验;缺少日志主键时保留实时 SSE,
|
||||
不创建额外聊天记录。阶段 1 要求 `open_existing` 至少补齐 `task_no`,有批次或快照时继续补齐
|
||||
`batch_no / shipping_ui_state / shipping_batch_ui_state`。
|
||||
|
||||
Args:
|
||||
ctx: 当前聊天流上下文。
|
||||
event_data: Dify terminal/error 原始事件。
|
||||
state_event: 已构造的订单抽取状态事件。
|
||||
ui_event: 已构造的 shipping_ui_state 事件。
|
||||
"""
|
||||
payload_patch = self._build_history_recovery_payload_patch(
|
||||
state_event=state_event,
|
||||
ui_event=ui_event,
|
||||
)
|
||||
if not payload_patch:
|
||||
return
|
||||
try:
|
||||
chat_log_id = int(event_data.get('chat_log_id') or 0)
|
||||
except (TypeError, ValueError):
|
||||
chat_log_id = 0
|
||||
if chat_log_id <= 0:
|
||||
return
|
||||
from app.services.chat.log_service import merge_chat_log_payload
|
||||
|
||||
merge_chat_log_payload(
|
||||
chat_log_id=chat_log_id,
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
agent_id=int(getattr(ctx.agent, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
payload_patch=payload_patch,
|
||||
)
|
||||
|
||||
def iter_ui_state_dedupe_key(self, event: dict[str, Any]) -> str | None:
|
||||
"""仅为 shipping_ui_state 构造去重键,其他领域事件保持独立生命周期。"""
|
||||
if str(event.get('event') or '') != 'shipping_ui_state':
|
||||
@@ -353,15 +130,13 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
'updated_at': ui_state.get('updated_at') or batch_ui_state.get('updated_at'),
|
||||
}, ensure_ascii=False, sort_keys=True)
|
||||
|
||||
def _format_sse(self, event: dict[str, Any]) -> str:
|
||||
@staticmethod
|
||||
def _format_sse(event: dict[str, Any]) -> str:
|
||||
"""把领域事件编码为单条 SSE data frame。"""
|
||||
return f"data: {json.dumps(event, ensure_ascii=False)}\n\n"
|
||||
|
||||
def iter_preface_sse_lines(self, ctx: ChatStreamContext) -> Iterator[str]:
|
||||
"""上游调用前先推送订单抽取进行态,再补充已有任务 UI State。"""
|
||||
extraction_event = self.build_order_extraction_state_event(ctx)
|
||||
if extraction_event:
|
||||
yield self._format_sse(extraction_event)
|
||||
"""上游调用前补充已有任务 UI State。"""
|
||||
event = self.build_ui_state_event(ctx)
|
||||
if event:
|
||||
yield self._format_sse(event)
|
||||
@@ -371,62 +146,10 @@ class ShippingNoticeHandler(AgentHandler):
|
||||
ctx: ChatStreamContext,
|
||||
event_data: dict[str, Any],
|
||||
) -> Iterator[str]:
|
||||
"""上游终态后收口抽取状态,依次推送抽取事实和任务 UI State。"""
|
||||
"""上游终态后刷新显式任务或批次的 UI State。"""
|
||||
event_name = str(event_data.get('event') or '').strip()
|
||||
if event_name not in {'error', 'message_end', 'workflow_finished'}:
|
||||
return iter(())
|
||||
intake_nos = self._order_extraction_intake_nos(ctx)
|
||||
if intake_nos:
|
||||
from app.services.shipping_notice.order_extraction import (
|
||||
ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
|
||||
finalize_order_extraction_failure,
|
||||
)
|
||||
|
||||
failure_message = self._workflow_failure_message(event_data)
|
||||
try:
|
||||
finalize_order_extraction_failure(
|
||||
user_id=int(getattr(ctx.user, 'id', 0) or 0),
|
||||
session_id=str(getattr(ctx.session, 'session_id', '') or ''),
|
||||
intake_nos=intake_nos,
|
||||
request_id=ctx.request_id,
|
||||
error_message=failure_message or ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
|
||||
)
|
||||
except Exception:
|
||||
from app import db
|
||||
|
||||
db.session.rollback()
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
'[shipping-handler] finalize order extraction failed request_id=%s intakes=%s',
|
||||
ctx.request_id,
|
||||
intake_nos,
|
||||
)
|
||||
extraction_event = self.build_order_extraction_state_event(ctx)
|
||||
event = self.build_ui_state_event(ctx, resolve_order_extraction=True)
|
||||
if extraction_event or event:
|
||||
self._persist_history_recovery_payload(
|
||||
ctx,
|
||||
event_data,
|
||||
state_event=extraction_event,
|
||||
ui_event=event,
|
||||
)
|
||||
if extraction_event:
|
||||
yield self._format_sse(extraction_event)
|
||||
event = self.build_ui_state_event(ctx)
|
||||
if event:
|
||||
yield self._format_sse(event)
|
||||
|
||||
def should_recover_upstream_error(self, ctx: ChatStreamContext, event_data: dict[str, Any]) -> bool:
|
||||
"""
|
||||
判断 Dify 流错误能否按已持久化的订单抽取结果正常收口。
|
||||
|
||||
核心逻辑:仅处理当前订单抽取请求;Tool 已写入 completed/partially_completed 时,
|
||||
网络断流不应覆盖订单事实或向前端显示失败。仍为 extracting/failed 的请求维持原错误语义。
|
||||
"""
|
||||
if str(event_data.get('event') or '').strip() != 'error':
|
||||
return False
|
||||
state_event = self.build_order_extraction_state_event(ctx)
|
||||
return bool(
|
||||
state_event
|
||||
and state_event.get('terminal') is True
|
||||
and state_event.get('status') in {'completed', 'partially_completed'}
|
||||
)
|
||||
@@ -49,6 +49,7 @@ def serialize_registry_fields(agent: Agent | Any) -> dict[str, Any]:
|
||||
'runtime_provider': resolve_runtime_provider(agent),
|
||||
'conversation_mode': resolve_conversation_mode(agent),
|
||||
'dify_app_type': getattr(agent, 'dify_app_type', None) or 'chatflow',
|
||||
'exposure_mode': getattr(agent, 'exposure_mode', None) or 'workspace',
|
||||
'iframe_url': getattr(agent, 'iframe_url', None),
|
||||
'category': getattr(agent, 'category', None) or None,
|
||||
'sub_category': getattr(agent, 'sub_category', None) or None,
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
"""
|
||||
backend/app/services/agent_runtime_binding_service.py
|
||||
|
||||
用途:解析、校验和管理 Agent 的命名运行能力 Provider 绑定。
|
||||
依赖:Agent/AgentRuntimeBinding、Agent Catalog、统一 AppError。
|
||||
逻辑:Catalog 声明 owner 需要的能力和 Provider 约束;管理员只保存 Agent 外键,运行时禁止名称或环境变量回退。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import Agent, AgentRuntimeBinding
|
||||
from app.services.agent_registry.catalog import get_catalog_entry
|
||||
|
||||
|
||||
def _capability_definition(owner: Agent, capability_code: str) -> dict[str, Any]:
|
||||
"""读取 owner Agent Catalog 中声明的能力定义;未声明能力不可由管理员任意绑定。"""
|
||||
entry = get_catalog_entry(owner.agent_code) or {}
|
||||
definitions = entry.get('required_runtime_capabilities')
|
||||
definitions = definitions if isinstance(definitions, dict) else {}
|
||||
definition = definitions.get(capability_code)
|
||||
if not isinstance(definition, dict):
|
||||
raise ValidationError(
|
||||
'Runtime capability is not declared by the Agent Catalog',
|
||||
code='AGENT.RUNTIME_CAPABILITY_NOT_DECLARED',
|
||||
)
|
||||
return definition
|
||||
|
||||
|
||||
def _normalize_config(raw: Any) -> dict[str, Any]:
|
||||
"""限制通用超时/重试配置,避免任意 JSON 成为隐式业务配置后门。"""
|
||||
if raw is None:
|
||||
raw = {}
|
||||
if not isinstance(raw, dict):
|
||||
raise ValidationError('config must be an object', code='AGENT.RUNTIME_BINDING_CONFIG_INVALID')
|
||||
unknown = set(raw) - {'timeout_seconds', 'max_attempts'}
|
||||
if unknown:
|
||||
raise ValidationError(
|
||||
'Unsupported runtime binding config keys',
|
||||
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
|
||||
details={'keys': sorted(unknown)},
|
||||
)
|
||||
try:
|
||||
timeout_seconds = int(raw.get('timeout_seconds', 900))
|
||||
max_attempts = int(raw.get('max_attempts', 3))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise ValidationError(
|
||||
'Runtime binding timeout/max_attempts must be integers',
|
||||
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
|
||||
) from exc
|
||||
if not 30 <= timeout_seconds <= 3600 or not 1 <= max_attempts <= 10:
|
||||
raise ValidationError(
|
||||
'Runtime binding config is outside allowed limits',
|
||||
code='AGENT.RUNTIME_BINDING_CONFIG_INVALID',
|
||||
)
|
||||
return {'timeout_seconds': timeout_seconds, 'max_attempts': max_attempts}
|
||||
|
||||
|
||||
def _validate_provider(provider: Agent, definition: dict[str, Any]) -> None:
|
||||
"""按 Catalog 校验 Provider 类型、可见性和 Dify 配置完整性。"""
|
||||
allowed_providers = set(definition.get('allowed_runtime_providers') or [])
|
||||
allowed_app_types = set(definition.get('allowed_dify_app_types') or [])
|
||||
allowed_exposure = set(definition.get('allowed_exposure_modes') or [])
|
||||
if not provider.is_active:
|
||||
raise ConflictError('Runtime provider is disabled', code='AGENT.RUNTIME_PROVIDER_DISABLED')
|
||||
if allowed_providers and provider.runtime_provider not in allowed_providers:
|
||||
raise ValidationError('Runtime provider type is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID')
|
||||
if allowed_app_types and provider.dify_app_type not in allowed_app_types:
|
||||
raise ValidationError('Dify application type is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID')
|
||||
if allowed_exposure and provider.exposure_mode not in allowed_exposure:
|
||||
raise ValidationError('Runtime provider exposure mode is invalid', code='AGENT.RUNTIME_PROVIDER_INVALID')
|
||||
if provider.runtime_provider in {'dify', 'hybrid'} and (
|
||||
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 ConflictError(
|
||||
'Runtime provider Dify configuration is incomplete',
|
||||
code='AGENT.RUNTIME_PROVIDER_CONFIG_INCOMPLETE',
|
||||
)
|
||||
|
||||
|
||||
def serialize_runtime_binding(binding: AgentRuntimeBinding) -> dict[str, Any]:
|
||||
"""输出管理端安全视图;不返回 Provider API Key。"""
|
||||
provider = binding.provider_agent
|
||||
return {
|
||||
'id': binding.id,
|
||||
'owner_agent_id': binding.owner_agent_id,
|
||||
'capability_code': binding.capability_code,
|
||||
'provider_agent_id': binding.provider_agent_id,
|
||||
'provider': {
|
||||
'id': provider.id,
|
||||
'name': provider.name,
|
||||
'runtime_provider': provider.runtime_provider,
|
||||
'dify_app_type': provider.dify_app_type,
|
||||
'exposure_mode': provider.exposure_mode,
|
||||
'is_active': provider.is_active,
|
||||
} if provider else None,
|
||||
'enabled': bool(binding.enabled),
|
||||
'config': dict(binding.config_json or {}),
|
||||
}
|
||||
|
||||
|
||||
def list_runtime_bindings(owner_agent_id: int) -> list[dict[str, Any]]:
|
||||
"""列出指定 owner Agent 的全部显式运行能力绑定。"""
|
||||
owner = db.session.get(Agent, owner_agent_id)
|
||||
if owner is None:
|
||||
raise NotFoundError('Agent not found')
|
||||
rows = AgentRuntimeBinding.query.filter_by(owner_agent_id=owner.id).order_by(
|
||||
AgentRuntimeBinding.capability_code.asc(),
|
||||
).all()
|
||||
return [serialize_runtime_binding(row) for row in rows]
|
||||
|
||||
|
||||
def save_runtime_binding(
|
||||
*,
|
||||
owner_agent_id: int,
|
||||
capability_code: str,
|
||||
provider_agent_id: int,
|
||||
enabled: bool,
|
||||
config: Any,
|
||||
commit: bool = True,
|
||||
) -> AgentRuntimeBinding:
|
||||
"""创建或更新能力绑定;owner/provider 必须是不同 Agent 且满足 Catalog 约束。"""
|
||||
owner = db.session.get(Agent, owner_agent_id)
|
||||
provider = db.session.get(Agent, provider_agent_id)
|
||||
if owner is None or provider is None:
|
||||
raise NotFoundError('Agent not found')
|
||||
code = str(capability_code or '').strip()
|
||||
if owner.id == provider.id:
|
||||
raise ValidationError('Owner and provider must be different Agents', code='AGENT.RUNTIME_PROVIDER_INVALID')
|
||||
definition = _capability_definition(owner, code)
|
||||
if enabled:
|
||||
_validate_provider(provider, definition)
|
||||
normalized_config = _normalize_config(config)
|
||||
binding = AgentRuntimeBinding.query.filter_by(
|
||||
owner_agent_id=owner.id, capability_code=code,
|
||||
).first()
|
||||
if binding is None:
|
||||
binding = AgentRuntimeBinding(owner_agent_id=owner.id, capability_code=code)
|
||||
db.session.add(binding)
|
||||
binding.provider_agent_id = provider.id
|
||||
binding.enabled = bool(enabled)
|
||||
binding.config_json = normalized_config
|
||||
if commit:
|
||||
db.session.commit()
|
||||
else:
|
||||
db.session.flush()
|
||||
return binding
|
||||
|
||||
|
||||
def resolve_runtime_binding(*, owner_agent_id: int, capability_code: str) -> AgentRuntimeBinding:
|
||||
"""运行时解析启用绑定并复检 Provider;未配置时明确阻断,禁止任何隐式回退。"""
|
||||
binding = AgentRuntimeBinding.query.filter_by(
|
||||
owner_agent_id=owner_agent_id,
|
||||
capability_code=capability_code,
|
||||
enabled=True,
|
||||
).first()
|
||||
if binding is None:
|
||||
raise ConflictError(
|
||||
'Runtime capability provider is not configured',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_NOT_CONFIGURED',
|
||||
)
|
||||
definition = _capability_definition(binding.owner_agent, capability_code)
|
||||
_validate_provider(binding.provider_agent, definition)
|
||||
return binding
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/agent_resolver.py
|
||||
|
||||
用途:定位发货通知聊天 Agent 的模型记录。
|
||||
依赖:app.models.Agent、agent_registry.resolver(agent_code 列)。
|
||||
逻辑:由 dify_executor、聊天入口或 Agent 相关编排调用本文件,确保发货通知流程绑定到正确的 Agent。
|
||||
逻辑:由聊天入口或 Agent 相关编排调用本文件,确保发货通知会话绑定到正确的聊天 Agent。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
services/shipping_notice/batch_orchestrator.py
|
||||
|
||||
用途:发货通知批次/单票后台编排器。
|
||||
依赖:query_service、task_workflow、dify_executor、shipping_notice.tools、tool_common。
|
||||
逻辑:工作台上传后由后端主导单票调度;批次线程只做任务派发,created 票通过 Dify 完成单票 AI 解析,其余确定性步骤由后端 auto_progress 推进。
|
||||
依赖:query_service、task_workflow、shipping_notice.tools、tool_common。
|
||||
逻辑:批次线程只推进已由订单抽取 Run 建立的正式 Task;created 旧壳任务安全停止,不再进入普通 Dify Chatflow。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,7 +16,6 @@ from flask import current_app
|
||||
from app import db
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
|
||||
from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job
|
||||
from app.services.shipping_notice.dify_executor import run_shipping_parse_via_dify
|
||||
from app.services.shipping_notice.query_service import get_batch_by_no, get_task_by_ref, list_sorted_batch_tasks
|
||||
from app.services.shipping_notice.task_workflow import recompute_batch_summary
|
||||
from app.services.shipping_notice.tool_common import (
|
||||
@@ -126,7 +125,7 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
"""
|
||||
后台执行单票任务的一轮推进。
|
||||
|
||||
`created` 先由 Dify 做单票解析;解析完成后和其他可续跑状态统一交给后端 auto_progress。
|
||||
仅推进已完成订单抽取的正式 Task;created 表示历史未抽取壳任务,必须重新上传创建 Intake/Run。
|
||||
一旦进入人工检查点或等待外部回执状态,本轮自动停止,等待用户或外部系统回写。
|
||||
"""
|
||||
normalized_task_no = _normalize_ref(task_no)
|
||||
@@ -194,46 +193,10 @@ def _run_single_task(task_no: str) -> dict[str, str | None]:
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
elif process_status == "created":
|
||||
result = run_shipping_parse_via_dify(task.task_no)
|
||||
# Dify 会通过 Tool API 在独立请求中提交动态订单抽取;当前 worker session
|
||||
# 可能仍缓存 created 旧对象,必须重新读库后才能决定是否继续 auto_progress。
|
||||
db.session.expire_all()
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] dify-parse result task_no=%s status=%s process_status_before=%s provider_conversation_id=%s message=%s",
|
||||
task.task_no,
|
||||
result.get("status"),
|
||||
task.process_status,
|
||||
result.get("provider_conversation_id"),
|
||||
str(result.get("message") or "")[:300],
|
||||
)
|
||||
refreshed_after_dify = get_task_by_ref(normalized_task_no)
|
||||
if (
|
||||
refreshed_after_dify
|
||||
and auto_progress_enabled()
|
||||
and _should_orchestrate_task(refreshed_after_dify)
|
||||
and str(refreshed_after_dify.process_status or "").strip().lower() != "created"
|
||||
):
|
||||
payload["mode"] = "auto"
|
||||
follow_up = auto_progress(payload)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-orchestrator] auto-progress follow-up task_no=%s status=%s process_status_after_dify=%s current_step=%s message=%s",
|
||||
task.task_no,
|
||||
follow_up.get("status"),
|
||||
getattr(refreshed_after_dify, "process_status", None),
|
||||
getattr(refreshed_after_dify, "current_step", None),
|
||||
str(follow_up.get("message") or "")[:300],
|
||||
)
|
||||
result = {
|
||||
"status": str(follow_up.get("status") or result.get("status") or ""),
|
||||
"message": "\n".join(
|
||||
part for part in [
|
||||
str(result.get("message") or "").strip(),
|
||||
str(follow_up.get("message") or "").strip(),
|
||||
] if part
|
||||
)[:500] or None,
|
||||
}
|
||||
result = {
|
||||
"status": "needs_human",
|
||||
"message": "任务尚未完成订单抽取,请重新上传原始发货通知创建后台识别 Run。",
|
||||
}
|
||||
else:
|
||||
payload["mode"] = "auto"
|
||||
result = auto_progress(payload)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/context_fields/__init__.py
|
||||
|
||||
用途:提供订单通用上下文字段确定性采集能力的包入口。
|
||||
依赖:context_fields.provider_registry。
|
||||
逻辑:Schema 管理与后续运行时采集器从本包共享同一受控来源注册表。
|
||||
"""
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/context_fields/dify_exposure.py
|
||||
|
||||
用途:把 Run 冻结的确定性上下文字段编译为 Dify 只读输入。
|
||||
依赖:context_fields.provider_registry。
|
||||
逻辑:只读取冻结 Schema 定义与 Intake 上下文;按发布策略排除、脱敏或只读暴露,绝不生成可回传字段契约。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from app.services.shipping_notice.context_fields.provider_registry import (
|
||||
redact_context_value,
|
||||
registered_option,
|
||||
supports_dify_exposure,
|
||||
)
|
||||
|
||||
|
||||
def _exposed_value(*, value: Any, policy: str, redactor_key: str | None) -> str | None:
|
||||
"""按已发布策略生成只读值;未知策略或脱敏器采取 fail-closed,不向 Dify 输出。"""
|
||||
if value in (None, '') or policy == 'never':
|
||||
return None
|
||||
normalized = str(value)
|
||||
if policy == 'confirmed_readonly':
|
||||
return normalized
|
||||
if policy == 'redacted':
|
||||
return redact_context_value(redactor_key, normalized)
|
||||
return None
|
||||
|
||||
|
||||
def compile_readonly_context(snapshot: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""
|
||||
从 Run 不可变快照编译按 Intake 隔离的 Dify 只读上下文。
|
||||
|
||||
Args:
|
||||
snapshot: Run 的 input_snapshot_json;必须包含冻结 schema.definition 与 intakes。
|
||||
Returns:
|
||||
仅包含实际暴露字段的 Intake 分组;`never`、缺值和失效能力完全不输出。
|
||||
"""
|
||||
schema = snapshot.get('schema') if isinstance(snapshot.get('schema'), dict) else {}
|
||||
definition = schema.get('definition') if isinstance(schema.get('definition'), dict) else {}
|
||||
fields = definition.get('fields') if isinstance(definition.get('fields'), list) else []
|
||||
exposed_fields: list[tuple[dict[str, Any], dict[str, Any]]] = []
|
||||
for field in fields:
|
||||
if not isinstance(field, dict) or field.get('enabled') is not True:
|
||||
continue
|
||||
if field.get('collection_mode') != 'deterministic_context' or field.get('scope') != 'header':
|
||||
continue
|
||||
source = field.get('context_source') if isinstance(field.get('context_source'), dict) else {}
|
||||
capability = registered_option(str(source.get('provider_key') or ''), str(source.get('option_key') or ''))
|
||||
policy = str(field.get('dify_exposure_policy') or 'never')
|
||||
if supports_dify_exposure(capability, policy) and policy != 'never':
|
||||
exposed_fields.append((field, capability))
|
||||
|
||||
groups: list[dict[str, Any]] = []
|
||||
intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
for intake in intakes:
|
||||
if not isinstance(intake, dict):
|
||||
continue
|
||||
values = intake.get('deterministic_context') if isinstance(intake.get('deterministic_context'), dict) else {}
|
||||
items: list[dict[str, Any]] = []
|
||||
for field, capability in exposed_fields:
|
||||
source = field['context_source']
|
||||
policy = str(field['dify_exposure_policy'])
|
||||
value = _exposed_value(
|
||||
value=values.get(str(source.get('option_key') or '')),
|
||||
policy=policy,
|
||||
redactor_key=capability.get('redactor_key'),
|
||||
)
|
||||
if value is None:
|
||||
continue
|
||||
items.append({
|
||||
'field_id': str(field.get('field_id') or ''),
|
||||
'field_code': str(field.get('field_code') or ''),
|
||||
'display_name': str(field.get('display_name') or field.get('field_code') or ''),
|
||||
'value': value,
|
||||
'exposure_policy': policy,
|
||||
'readonly': True,
|
||||
})
|
||||
if items:
|
||||
groups.append({
|
||||
'intake_id': intake.get('intake_id'),
|
||||
'intake_no': intake.get('intake_no'),
|
||||
'fields': items,
|
||||
})
|
||||
return groups
|
||||
@@ -0,0 +1,75 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/context_fields/provider_registry.py
|
||||
|
||||
用途:声明订单通用上下文字段可执行的确定性来源及 Dify 只读暴露能力。
|
||||
依赖:无。
|
||||
逻辑:数据库仅维护展示与启停;Schema 保存/发布及 Workflow 输入编译必须命中本注册表白名单。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
|
||||
|
||||
def _email_mask(_value: str) -> str:
|
||||
"""返回不可还原的邮箱占位符;不保留用户名、域名、长度或字符模式。"""
|
||||
return '***@***'
|
||||
|
||||
|
||||
def _domain_mask(_value: str) -> str:
|
||||
"""返回不可还原的域名占位符;不保留组织名、后缀或字符模式。"""
|
||||
return '***.***'
|
||||
|
||||
|
||||
REGISTERED_REDACTORS: dict[str, Callable[[str], str]] = {
|
||||
'email_mask': _email_mask,
|
||||
'domain_mask': _domain_mask,
|
||||
}
|
||||
|
||||
|
||||
REGISTERED_CONTEXT_PROVIDERS: dict[str, dict[str, Any]] = {
|
||||
'mail_header': {
|
||||
'options': {
|
||||
'from_email': {
|
||||
'source_key': 'mail.from.email',
|
||||
'value_type': 'string',
|
||||
'canonical_source': 'eml.header.from',
|
||||
'allowed_dify_exposure_policies': ('never', 'redacted', 'confirmed_readonly'),
|
||||
'redactor_key': 'email_mask',
|
||||
},
|
||||
'from_domain': {
|
||||
'source_key': 'mail.from.domain',
|
||||
'value_type': 'string',
|
||||
'canonical_source': 'eml.header.from',
|
||||
'allowed_dify_exposure_policies': ('never', 'redacted', 'confirmed_readonly'),
|
||||
'redactor_key': 'domain_mask',
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def registered_option(provider_key: str, option_key: str) -> dict[str, Any] | None:
|
||||
"""按稳定键读取来源能力;未注册时返回 None,禁止数据库自行扩展可执行路径。"""
|
||||
provider = REGISTERED_CONTEXT_PROVIDERS.get(provider_key)
|
||||
if provider is None:
|
||||
return None
|
||||
option = provider['options'].get(option_key)
|
||||
return dict(option) if option else None
|
||||
|
||||
|
||||
def supports_dify_exposure(capability: dict[str, Any] | None, policy: str) -> bool:
|
||||
"""判断来源能力能否安全执行指定策略;redacted 必须同时命中受控脱敏器注册表。"""
|
||||
if capability is None:
|
||||
return False
|
||||
if policy == 'never':
|
||||
return True
|
||||
if policy not in set(capability.get('allowed_dify_exposure_policies', ())):
|
||||
return False
|
||||
return policy != 'redacted' or capability.get('redactor_key') in REGISTERED_REDACTORS
|
||||
|
||||
|
||||
def redact_context_value(redactor_key: str | None, value: str) -> str | None:
|
||||
"""调用受控脱敏器;未知键返回 None,确保运行时与 Schema 校验共享同一能力来源。"""
|
||||
redactor = REGISTERED_REDACTORS.get(str(redactor_key or ''))
|
||||
return redactor(value) if redactor else None
|
||||
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/context_fields/runtime.py
|
||||
|
||||
用途:从 Intake 冻结邮件元数据采集通用上下文字段,并写入统一 Observation/Decision/FieldValue 链路。
|
||||
依赖:ShippingNoticeIntake、订单动态字段模型、customer_normalization。
|
||||
逻辑:只读取原始 EML From;按发布快照 option_key 投影邮箱/域名,缺失或非法时形成 missing Decision。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from email.utils import getaddresses
|
||||
from typing import Any
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
ShippingOrderFieldValue,
|
||||
)
|
||||
from app.services.shipping_notice.customer_normalization import normalize_domain, normalize_email
|
||||
|
||||
|
||||
def canonical_mail_context(intake: ShippingNoticeIntake) -> dict[str, str]:
|
||||
"""从 Intake 的 EML From 解析唯一规范邮箱及域名,供快照和裁决共用。"""
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
email_meta = structured.get('email') if isinstance(structured.get('email'), dict) else {}
|
||||
raw_from = str(email_meta.get('from') or '').strip()
|
||||
addresses = [address.strip() for _name, address in getaddresses([raw_from]) if address.strip()]
|
||||
if len(addresses) != 1:
|
||||
return {}
|
||||
try:
|
||||
email = normalize_email(addresses[0])
|
||||
return {'from_email': email, 'from_domain': normalize_domain(email)}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _existing_value(extraction_id: int, field_id: str) -> tuple[ShippingOrderFieldDecision, Any] | None:
|
||||
"""读取已存在的 Header 决定和值,供同一 Extraction 重入时保持幂等。"""
|
||||
decision = ShippingOrderFieldDecision.query.filter_by(
|
||||
extraction_id=extraction_id, line_id=None, field_id=field_id,
|
||||
).one_or_none()
|
||||
if decision is None:
|
||||
return None
|
||||
value = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=extraction_id, line_id=None, field_id=field_id,
|
||||
).one_or_none()
|
||||
return decision, value.value_json if value is not None else decision.resolved_value_json
|
||||
|
||||
|
||||
def persist_deterministic_context_fields(
|
||||
*, extraction: ShippingOrderExtraction, intake: ShippingNoticeIntake,
|
||||
configs: list[dict[str, Any]], frozen_values: dict[str, Any] | None = None,
|
||||
) -> tuple[dict[str, Any], list[dict[str, Any]], list[dict[str, Any]], list[str]]:
|
||||
"""
|
||||
将发布版本中的确定性 Header 字段写入统一字段链路。
|
||||
|
||||
Args:
|
||||
extraction: 当前订单解析记录;必须已 flush 获得主键。
|
||||
intake: Extraction 对应接入记录,只读取其冻结 `email.from` 元数据。
|
||||
configs: 已启用且 collection_mode=deterministic_context 的版本字段快照。
|
||||
frozen_values: Run/Extraction 已冻结的规范值;未提供时才从当前 Intake 生成。
|
||||
Returns:
|
||||
`(header_projection, observations, decisions, blocked_fields)`;required 缺失字段进入 blocked。
|
||||
"""
|
||||
values = (
|
||||
{str(key): str(value) for key, value in frozen_values.items() if value not in (None, '')}
|
||||
if isinstance(frozen_values, dict)
|
||||
else canonical_mail_context(intake)
|
||||
)
|
||||
header: dict[str, Any] = {}
|
||||
observations: list[dict[str, Any]] = []
|
||||
decisions: list[dict[str, Any]] = []
|
||||
blocked: list[str] = []
|
||||
for config in configs:
|
||||
field_id = str(config['field_id'])
|
||||
field_code = str(config['field_code'])
|
||||
existing = _existing_value(extraction.id, field_id)
|
||||
if existing is not None:
|
||||
decision, value = existing
|
||||
if value is not None and decision.decision_status in {'accepted', 'corroborated'}:
|
||||
header[field_code] = value
|
||||
decisions.append({
|
||||
'id': decision.id, 'field_id': field_id, 'field_code': field_code, 'line_id': None,
|
||||
'status': decision.decision_status, 'value': value, 'reason_code': decision.reason_code,
|
||||
'observation_ids': list(decision.supporting_observation_ids_json or []),
|
||||
})
|
||||
continue
|
||||
|
||||
source = config.get('context_source') if isinstance(config.get('context_source'), dict) else {}
|
||||
option_key = str(source.get('option_key') or '')
|
||||
value = values.get(option_key)
|
||||
observation = None
|
||||
if value is not None:
|
||||
observation = ShippingOrderFieldObservation(
|
||||
extraction_id=extraction.id, line_id=None, field_id=field_id,
|
||||
source_document_id=None, source_type='mail_header', extractor='deterministic_context',
|
||||
raw_value_json=value, normalized_value_json=value, evidence_quote=None,
|
||||
confidence=Decimal('1.0000'), evidence_verified=True,
|
||||
)
|
||||
db.session.add(observation)
|
||||
db.session.flush()
|
||||
status = 'accepted' if observation is not None else 'missing'
|
||||
reason = 'deterministic_context' if observation is not None else 'mail_from_missing_or_invalid'
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=None, field_id=field_id,
|
||||
decision_status=status, selected_observation_id=observation.id if observation else None,
|
||||
supporting_observation_ids_json=[observation.id] if observation else [],
|
||||
resolved_value_json=value, reason_code=reason,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
if value is not None:
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=None, field_id=field_id, decision_id=decision.id,
|
||||
value_text=value, value_json=value,
|
||||
))
|
||||
header[field_code] = value
|
||||
observations.append({
|
||||
'id': observation.id, 'field_id': field_id, 'line_id': None,
|
||||
'source_type': 'mail_header', 'document_id': None,
|
||||
'value': value, 'evidence_verified': True,
|
||||
})
|
||||
elif config.get('required'):
|
||||
blocked.append(field_code)
|
||||
decisions.append({
|
||||
'id': decision.id, 'field_id': field_id, 'field_code': field_code, 'line_id': None,
|
||||
'status': status, 'value': value, 'reason_code': reason,
|
||||
'observation_ids': list(decision.supporting_observation_ids_json or []),
|
||||
})
|
||||
return header, observations, decisions, blocked
|
||||
@@ -19,12 +19,22 @@ from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingTask,
|
||||
ShippingTaskEvent,
|
||||
)
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
from app.services.shipping_notice.customer_normalization import is_public_email_domain
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
is_public_email_domain,
|
||||
normalize_customer_name,
|
||||
normalize_domain,
|
||||
normalize_email,
|
||||
)
|
||||
from app.services.shipping_notice.tool_common import cfg_bool, cfg_float, cfg_int
|
||||
from app.services.shipping_notice.business_case_service import generate_shipping_case_no
|
||||
from app.services.shipping_notice.business_numbering_service import assign_business_number
|
||||
@@ -85,7 +95,7 @@ def _auto_confirmation_quality_gate() -> dict[str, Any]:
|
||||
|
||||
|
||||
def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] | None:
|
||||
"""读取并校验影子记录冻结的规则集;缺失或不一致时宁可降级,不能回读当前配置。"""
|
||||
"""校验规则集及其订单 Schema/Extraction 锚点;任一链路缺失都安全降级。"""
|
||||
context = shadow.resolution_context_json if isinstance(shadow.resolution_context_json, dict) else {}
|
||||
snapshot = context.get('rule_set') if isinstance(context.get('rule_set'), dict) else None
|
||||
if not snapshot or not isinstance(snapshot.get('definitions'), list):
|
||||
@@ -96,6 +106,35 @@ def _rule_snapshot(shadow: ShippingCustomerShadowResolution) -> dict[str, Any] |
|
||||
return None
|
||||
if snapshot.get('checksum') != shadow.identity_rule_set_checksum:
|
||||
return None
|
||||
rule_set = db.session.get(ShippingIdentityRuleSet, shadow.identity_rule_set_id)
|
||||
if (
|
||||
rule_set is None
|
||||
or rule_set.status not in {'published', 'retired'}
|
||||
or rule_set.version != shadow.identity_rule_set_version
|
||||
or rule_set.checksum != shadow.identity_rule_set_checksum
|
||||
):
|
||||
return None
|
||||
frozen_definition = rule_set.definition_json if isinstance(rule_set.definition_json, dict) else {}
|
||||
if (
|
||||
snapshot.get('definitions') != frozen_definition.get('definitions')
|
||||
or snapshot.get('order_schema') != frozen_definition.get('order_schema')
|
||||
):
|
||||
return None
|
||||
schema = snapshot.get('order_schema') if isinstance(snapshot.get('order_schema'), dict) else None
|
||||
if not schema or schema.get('id') != shadow.order_schema_version_id:
|
||||
return None
|
||||
schema_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
|
||||
if (
|
||||
schema_version is None
|
||||
or schema_version.status not in {'published', 'retired'}
|
||||
or schema_version.version != schema.get('version')
|
||||
or schema_version.checksum != schema.get('checksum')
|
||||
):
|
||||
return None
|
||||
extraction_id = context.get('order_extraction_id')
|
||||
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id)) if str(extraction_id or '').isdigit() else None
|
||||
if extraction is None or extraction.schema_version_id != shadow.order_schema_version_id:
|
||||
return None
|
||||
return snapshot
|
||||
|
||||
|
||||
@@ -112,9 +151,57 @@ def _decision_base(shadow: ShippingCustomerShadowResolution, *, status: str) ->
|
||||
'version': shadow.identity_rule_set_version,
|
||||
'checksum': shadow.identity_rule_set_checksum,
|
||||
},
|
||||
'order_schema_version_id': shadow.order_schema_version_id,
|
||||
'order_extraction_id': (
|
||||
shadow.resolution_context_json.get('order_extraction_id')
|
||||
if isinstance(shadow.resolution_context_json, dict)
|
||||
else None
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def _verified_shadow_value(
|
||||
shadow: ShippingCustomerShadowResolution, definition: dict[str, Any], evidence: dict[str, Any],
|
||||
) -> str | None:
|
||||
"""复核影子证据所引用的数据库 FieldValue/Decision,并按规则快照重新标准化。"""
|
||||
source = evidence.get('source') if isinstance(evidence.get('source'), dict) else {}
|
||||
if source.get('kind') != 'field_value':
|
||||
return None
|
||||
field_id = str(definition.get('context_field_id') or '')
|
||||
if (
|
||||
str(source.get('context_field_id') or '') != field_id
|
||||
or source.get('order_schema_version_id') != shadow.order_schema_version_id
|
||||
):
|
||||
return None
|
||||
field_value = db.session.get(ShippingOrderFieldValue, source.get('field_value_id'))
|
||||
decision = db.session.get(ShippingOrderFieldDecision, source.get('decision_id'))
|
||||
extraction = db.session.get(ShippingOrderExtraction, source.get('extraction_id'))
|
||||
if (
|
||||
field_value is None or decision is None or extraction is None
|
||||
or field_value.extraction_id != extraction.id
|
||||
or field_value.decision_id != decision.id
|
||||
or decision.extraction_id != extraction.id
|
||||
or field_value.field_id != field_id
|
||||
or decision.field_id != field_id
|
||||
or decision.decision_status not in {'accepted', 'corroborated'}
|
||||
or extraction.schema_version_id != shadow.order_schema_version_id
|
||||
):
|
||||
return None
|
||||
value = field_value.value_text if field_value.value_text not in (None, '') else field_value.value_json
|
||||
config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
context_source = config.get('context_source') if isinstance(config.get('context_source'), dict) else {}
|
||||
try:
|
||||
if context_source.get('option_key') == 'from_email':
|
||||
return normalize_email(value)
|
||||
if context_source.get('option_key') == 'from_domain':
|
||||
return normalize_domain(value)
|
||||
if config.get('normalizer_key') == 'name':
|
||||
return normalize_customer_name(value) or None
|
||||
return str(value or '').strip().upper() or None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadowResolution) -> dict[str, Any]:
|
||||
"""
|
||||
按影子记录的冻结定义和当前已审核授权证据求唯一自动确认客户。
|
||||
@@ -139,14 +226,20 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
|
||||
normalized = str(evidence.get('normalized_value') or '').strip()
|
||||
if not definition or not normalized:
|
||||
continue
|
||||
verified_normalized = _verified_shadow_value(shadow, definition, evidence)
|
||||
if verified_normalized is None or verified_normalized != normalized:
|
||||
continue
|
||||
field_value_source = evidence['source']
|
||||
if (
|
||||
definition.get('target_type') != 'customer'
|
||||
or definition.get('max_automation') != 'conditional'
|
||||
or definition.get('source_adapter_key') not in {'email_metadata', 'document_template'}
|
||||
or not definition.get('context_field_id')
|
||||
):
|
||||
continue
|
||||
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
context_source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
|
||||
email_domain = normalized.rsplit('@', 1)[-1] if '@' in normalized else normalized
|
||||
if definition.get('attribute_key') in {'email', 'domain'} and is_public_email_domain(email_domain):
|
||||
if context_source.get('option_key') in {'from_email', 'from_domain'} and is_public_email_domain(email_domain):
|
||||
continue
|
||||
records = db.session.query(ShippingIdentityEvidence).filter_by(
|
||||
definition_id=definition_id,
|
||||
@@ -165,7 +258,8 @@ def _resolve_auto_customer_from_shadow_resolution(shadow: ShippingCustomerShadow
|
||||
'definition_id': definition_id,
|
||||
'definition_code': definition.get('definition_code'),
|
||||
'normalized_value': normalized,
|
||||
'source': evidence.get('source'),
|
||||
'source': field_value_source,
|
||||
'context_source': context_source,
|
||||
})
|
||||
if len(matched) != 1:
|
||||
result = _decision_base(shadow, status='ambiguous' if matched else 'unmatched')
|
||||
|
||||
@@ -371,34 +371,15 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
)
|
||||
return match_result
|
||||
|
||||
# [STEP 4] 最后处理整单重新解析。
|
||||
# 整单重解析必须回到 created 并交给后台 Dify 编排,避免启发式兜底直接覆盖 AI 解析。
|
||||
# [STEP 4] Task 不再回退到旧 Chatflow 重新抽取;只有 Intake Run 可以执行订单识别。
|
||||
if decision == "reparse":
|
||||
task.process_status = "created"
|
||||
task.review_status = None
|
||||
task.pending_human_reason = None
|
||||
retire_current_order_extraction(task)
|
||||
task.parse_confidence = None
|
||||
task.match_status = None
|
||||
task.shortage_json = None
|
||||
task.line_results_json = None
|
||||
task.inventory_lines_json = None
|
||||
task.error_message = None
|
||||
log_task_action_event(
|
||||
task,
|
||||
"notice_reparse_requested",
|
||||
action="reparse",
|
||||
source=event_source,
|
||||
comment=comment,
|
||||
extra={"reparse_mode": "dify_required"},
|
||||
)
|
||||
db.session.commit()
|
||||
orchestrator_started = start_task_orchestrator(task.task_no)
|
||||
return tool_response(
|
||||
status="running" if orchestrator_started else "ok",
|
||||
status="needs_human",
|
||||
task=task,
|
||||
message=f"已提交重新解析任务 {task.task_no},后台将通过 Dify 重新抽取发货通知。",
|
||||
message="订单重新识别必须从原始发货通知重新上传并创建后台识别任务。",
|
||||
data=serialize_task_for_tool(task),
|
||||
checkpoint=task.review_status or "parse_review",
|
||||
stop_agent_turn=True,
|
||||
forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"],
|
||||
)
|
||||
|
||||
|
||||
@@ -1,303 +0,0 @@
|
||||
"""
|
||||
services/shipping_notice/dify_executor.py
|
||||
|
||||
用途:发货通知后台编排器内部调用 Dify Chatflow,完成单票 AI 解析。
|
||||
依赖:models.ChatSession、services.dify、agent_resolver、dify_inputs、query_service。
|
||||
逻辑:后台调度器逐票执行时,created 任务在这里触发 Dify;Dify 只负责当前票解析,不承担整批调度。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
|
||||
from app import db
|
||||
from app.models import ChatSession
|
||||
from app.services.dify import DifyService
|
||||
from app.services.shipping_notice.agent_resolver import resolve_chat_agent
|
||||
from app.services.shipping_notice.dify_inputs import build_dify_chat_inputs
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
from app.services.shipping_notice.tool_common import cfg_int
|
||||
|
||||
|
||||
def build_single_task_parse_prompt(task_no: str, *, batch_no: str | None = None) -> str:
|
||||
"""
|
||||
构造后台排程器发给 Dify 的用户意图短句。
|
||||
|
||||
后台任务号与批次号通过 agent_runtime_context.refs 注入,不能拼入 query,
|
||||
避免 Dify 预处理把 SB-/流程指令误判为切换任务。
|
||||
"""
|
||||
return "解析当前发货通知任务"
|
||||
|
||||
|
||||
def _ensure_chat_session_for_task(task: Any, agent_id: int, title: str) -> ChatSession | None:
|
||||
"""尽量复用聊天会话;若任务带本地会话号但会话未建,则补建一条 ChatSession。"""
|
||||
session_id = str(getattr(task, "conversation_id", "") or "").strip()
|
||||
user_id = getattr(task, "user_id", None)
|
||||
if not session_id or not user_id:
|
||||
return None
|
||||
session = ChatSession.query.filter_by(
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
session_id=session_id,
|
||||
).first()
|
||||
if session:
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] reuse chat_session task_no=%s session_id=%s external_conversation_id=%s",
|
||||
getattr(task, "task_no", None),
|
||||
session.session_id,
|
||||
session.external_conversation_id,
|
||||
)
|
||||
return session
|
||||
session = ChatSession(
|
||||
session_id=session_id,
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
title=(str(title or "").strip()[:255]),
|
||||
status="running",
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
last_active_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(session)
|
||||
db.session.commit()
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] create chat_session task_no=%s session_id=%s",
|
||||
getattr(task, "task_no", None),
|
||||
session.session_id,
|
||||
)
|
||||
return session
|
||||
|
||||
|
||||
def _log_executor_context(
|
||||
*,
|
||||
task: Any,
|
||||
batch_no: str | None,
|
||||
local_conversation_id: str,
|
||||
provider_conversation_id: str | None,
|
||||
inputs: dict[str, Any],
|
||||
request_id: str,
|
||||
) -> None:
|
||||
if not current_app:
|
||||
return
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] context request_id=%s task_no=%s batch_no=%s session_id=%s provider_conversation_id=%s inputs=%s",
|
||||
request_id,
|
||||
getattr(task, "task_no", None),
|
||||
batch_no,
|
||||
local_conversation_id,
|
||||
provider_conversation_id,
|
||||
json.dumps(inputs, ensure_ascii=False, default=str),
|
||||
)
|
||||
|
||||
|
||||
def _parse_total_timeout_seconds() -> int:
|
||||
"""单票 Dify 解析总超时,避免长时间无终态事件把工作线程一直占住。"""
|
||||
return cfg_int("SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS", 180, min_value=15)
|
||||
|
||||
|
||||
def run_shipping_parse_via_dify(task_no: str) -> dict[str, Any]:
|
||||
"""
|
||||
由后台排程器触发 Dify 处理单票发货通知解析。
|
||||
|
||||
这里不做批次循环,只让 Dify 完成“当前票 AI 订单抽取 + submit_order_extraction”这一步。
|
||||
"""
|
||||
task = get_task_by_ref(task_no)
|
||||
if not task:
|
||||
return {"status": "failed", "message": "task not found"}
|
||||
if not getattr(task, "user_id", None):
|
||||
return {"status": "failed", "message": "task user_id is missing"}
|
||||
|
||||
agent = resolve_chat_agent()
|
||||
if not agent or not getattr(agent, "dify_api_key", None):
|
||||
return {"status": "failed", "message": "shipping dify agent is not available"}
|
||||
|
||||
batch_no = str(getattr(getattr(task, "batch", None), "batch_no", "") or "").strip() or None
|
||||
query = build_single_task_parse_prompt(task.task_no, batch_no=batch_no)
|
||||
session = _ensure_chat_session_for_task(task, agent.id, query)
|
||||
local_conversation_id = (
|
||||
str(getattr(session, "session_id", "") or "").strip()
|
||||
or str(getattr(task, "conversation_id", "") or "").strip()
|
||||
or task.task_no
|
||||
)
|
||||
# 后台编排每票都从新的 Dify provider conversation 开始,避免多票复用前端会话导致上下文串单。
|
||||
provider_conversation_id = None
|
||||
request_id = f"shipping-orch-{task.task_no}"
|
||||
inputs = build_dify_chat_inputs(
|
||||
local_conversation_id,
|
||||
task_id=task.task_no,
|
||||
batch_no=batch_no,
|
||||
trigger_source="backend_orchestrator",
|
||||
request_id=request_id,
|
||||
)
|
||||
started_at = time.perf_counter()
|
||||
total_timeout_seconds = _parse_total_timeout_seconds()
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] start request_id=%s task_no=%s batch_no=%s session_id=%s provider_conversation_id=%s",
|
||||
request_id,
|
||||
task.task_no,
|
||||
batch_no,
|
||||
local_conversation_id,
|
||||
provider_conversation_id,
|
||||
)
|
||||
_log_executor_context(
|
||||
task=task,
|
||||
batch_no=batch_no,
|
||||
local_conversation_id=local_conversation_id,
|
||||
provider_conversation_id=provider_conversation_id,
|
||||
inputs=inputs,
|
||||
request_id=request_id,
|
||||
)
|
||||
|
||||
final_event: dict[str, Any] | None = None
|
||||
final_answer = ""
|
||||
terminal_status = "done"
|
||||
event_count = 0
|
||||
message_event_count = 0
|
||||
message_char_count = 0
|
||||
terminal_event_name = ""
|
||||
|
||||
try:
|
||||
stream = DifyService.stream_chat(
|
||||
query,
|
||||
int(task.user_id),
|
||||
agent,
|
||||
provider_conversation_id,
|
||||
request_id=request_id,
|
||||
session_id=local_conversation_id,
|
||||
inputs=inputs,
|
||||
persist_chat_log=False,
|
||||
)
|
||||
for chunk in stream:
|
||||
if time.perf_counter() - started_at > total_timeout_seconds:
|
||||
raise TimeoutError(f"dify parse timed out after {total_timeout_seconds}s")
|
||||
if not isinstance(chunk, str) or not chunk.startswith("data: "):
|
||||
continue
|
||||
payload = chunk[6:].strip()
|
||||
if not payload:
|
||||
continue
|
||||
try:
|
||||
data = json.loads(payload)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
event_name = str(data.get("event") or "").strip()
|
||||
if not event_name:
|
||||
continue
|
||||
event_count += 1
|
||||
provider_id = str(data.get("conversation_id") or "").strip() or None
|
||||
if provider_id:
|
||||
provider_conversation_id = provider_id
|
||||
answer = str(data.get("answer") or "")
|
||||
if answer:
|
||||
if event_name in {"message", "agent_message", "message_end", "workflow_finished"}:
|
||||
message_event_count += 1
|
||||
message_char_count += len(answer)
|
||||
if data.get("replace_answer"):
|
||||
final_answer = answer
|
||||
else:
|
||||
final_answer += answer
|
||||
if current_app and event_name in {"error", "message_end", "workflow_finished"}:
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] terminal-candidate request_id=%s event=%s task_no=%s provider_conversation_id=%s answer_len=%s",
|
||||
request_id,
|
||||
event_name,
|
||||
task.task_no,
|
||||
provider_conversation_id,
|
||||
len(answer),
|
||||
)
|
||||
if event_name == "error":
|
||||
terminal_status = "error"
|
||||
terminal_event_name = event_name
|
||||
final_event = data
|
||||
break
|
||||
if event_name in {"message_end", "workflow_finished"}:
|
||||
terminal_event_name = event_name
|
||||
final_event = data
|
||||
break
|
||||
except Exception as exc:
|
||||
db.session.rollback()
|
||||
if current_app:
|
||||
current_app.logger.exception(
|
||||
"[shipping-dify-executor] exception request_id=%s task_no=%s provider_conversation_id=%s",
|
||||
request_id,
|
||||
task.task_no,
|
||||
provider_conversation_id,
|
||||
)
|
||||
return {"status": "failed", "message": str(exc)[:500] or "dify execution failed"}
|
||||
|
||||
refreshed = get_task_by_ref(task.task_no)
|
||||
process_status = str(getattr(refreshed, "process_status", "") or "").strip() if refreshed else ""
|
||||
review_status = str(getattr(refreshed, "review_status", "") or "").strip() if refreshed else ""
|
||||
elapsed_ms = int((time.perf_counter() - started_at) * 1000)
|
||||
|
||||
if final_event and str(final_event.get("event") or "").strip() == "error":
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[shipping-dify-executor] failed request_id=%s task_no=%s event=%s provider_conversation_id=%s elapsed_ms=%s events=%s message_events=%s answer_chars=%s process_status=%s review_status=%s error=%s",
|
||||
request_id,
|
||||
task.task_no,
|
||||
terminal_event_name or "error",
|
||||
provider_conversation_id,
|
||||
elapsed_ms,
|
||||
event_count,
|
||||
message_event_count,
|
||||
message_char_count,
|
||||
process_status,
|
||||
review_status,
|
||||
str(final_event.get("message") or "")[:300],
|
||||
)
|
||||
return {
|
||||
"status": "failed",
|
||||
"message": str(final_event.get("message") or "dify returned error")[:500],
|
||||
"provider_conversation_id": provider_conversation_id,
|
||||
}
|
||||
|
||||
if not final_event:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[shipping-dify-executor] missing-terminal-event request_id=%s task_no=%s provider_conversation_id=%s elapsed_ms=%s events=%s process_status=%s review_status=%s",
|
||||
request_id,
|
||||
task.task_no,
|
||||
provider_conversation_id,
|
||||
elapsed_ms,
|
||||
event_count,
|
||||
process_status,
|
||||
review_status,
|
||||
)
|
||||
return {
|
||||
"status": "failed",
|
||||
"message": "dify stream finished without terminal event",
|
||||
"provider_conversation_id": provider_conversation_id,
|
||||
}
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[shipping-dify-executor] finished request_id=%s task_no=%s event=%s provider_conversation_id=%s elapsed_ms=%s events=%s message_events=%s answer_chars=%s process_status=%s review_status=%s",
|
||||
request_id,
|
||||
task.task_no,
|
||||
terminal_event_name or str(final_event.get("event") or ""),
|
||||
provider_conversation_id,
|
||||
elapsed_ms,
|
||||
event_count,
|
||||
message_event_count,
|
||||
message_char_count,
|
||||
process_status,
|
||||
review_status,
|
||||
)
|
||||
|
||||
return {
|
||||
"status": "ok",
|
||||
"message": final_answer[:500] or "dify parse finished",
|
||||
"task_process_status": process_status or None,
|
||||
"task_review_status": review_status or None,
|
||||
"provider_conversation_id": provider_conversation_id,
|
||||
}
|
||||
@@ -152,9 +152,8 @@ def build_dify_chat_inputs(
|
||||
locale=locale,
|
||||
scope="task_run" if trigger_source == "backend_orchestrator" else "chat_turn",
|
||||
run_purpose=(
|
||||
"order_extraction"
|
||||
if trigger_source == "backend_orchestrator"
|
||||
else ("temporary_inventory" if temporary_inventory_asset_no else ("order_extraction" if intake_nos else "chat_turn"))
|
||||
"chat_turn" if trigger_source == "backend_orchestrator"
|
||||
else ("temporary_inventory" if temporary_inventory_asset_no else "chat_turn")
|
||||
),
|
||||
intake_nos=intake_nos,
|
||||
capability=capability or ("temporary_inventory" if temporary_inventory_asset_no else None),
|
||||
|
||||
@@ -3,7 +3,7 @@ services/shipping_notice/extract.py
|
||||
|
||||
用途:抽取发货通知中的单头字段与订单行,并在收尾阶段补充文档级字段和告警。
|
||||
依赖:po_number、reservation_id、notice_lines 中的标准化与回填工具。
|
||||
逻辑:保留历史启发式文本工具;正式订单抽取已统一由 Dify 调用 get_order_extraction_context / submit_order_extraction。
|
||||
逻辑:保留历史启发式文本工具;正式订单抽取已统一由后台 Run/Worker 调用专用 Workflow。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/field_adjudication.py
|
||||
|
||||
用途:把后端表格解析与 Dify LLM 输出转换为不可变字段 Observation,并生成规范订单行裁决结果。
|
||||
依赖:ShippingNoticeDocument、notice_lines、标准库 hashlib/json/re。
|
||||
逻辑:submit_order_extraction 在 Candidate 校验前调用;原始 Observation 只追加不互相覆盖,裁决结果另行投影。
|
||||
逻辑:后台 Run 结果持久化在 Candidate 校验前调用;原始 Observation 只追加不互相覆盖,裁决结果另行投影。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
"""
|
||||
用途:基于已发布身份规则集产生客户主体与送货站点的可解释影子候选。
|
||||
依赖:身份规则快照、受控订单字段裁决值、客户/站点证据主数据和邮件接入元数据。
|
||||
逻辑:只读取邮件元数据及 accepted/corroborated Header FieldValue;站点候选独立保存,绝不反向确认客户主体。
|
||||
依赖:身份规则快照、受控订单字段裁决值、客户/站点证据主数据。
|
||||
逻辑:只读取 Candidate 所属 Extraction 的 accepted/corroborated Header FieldValue;站点候选不反向确认客户主体。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import defaultdict
|
||||
from email.utils import parseaddr
|
||||
import hashlib
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from app import db
|
||||
@@ -19,7 +16,6 @@ from app.models import (
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
@@ -36,14 +32,15 @@ ACCEPTED_DECISION_STATUSES = frozenset({'accepted', 'corroborated'})
|
||||
|
||||
|
||||
def _normalize(definition: dict[str, Any], value: object) -> str | None:
|
||||
"""按发布定义快照生成稳定匹配键;无效输入仅跳过当前证据而不影响其余取证。"""
|
||||
"""按定义冻结的 Schema 字段配置生成匹配键;无效输入只跳过当前证据。"""
|
||||
try:
|
||||
normalizer = str(definition.get('normalizer_key') or '')
|
||||
if normalizer == 'email':
|
||||
field_config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
|
||||
if source.get('option_key') == 'from_email':
|
||||
return normalize_email(value)
|
||||
if normalizer == 'domain':
|
||||
if source.get('option_key') == 'from_domain':
|
||||
return normalize_domain(value)
|
||||
if normalizer == 'name':
|
||||
if field_config.get('normalizer_key') == 'name':
|
||||
return normalize_customer_name(value) or None
|
||||
normalized = str(value or '').strip().upper()
|
||||
return normalized or None
|
||||
@@ -56,40 +53,8 @@ def _published_rule_set() -> ShippingIdentityRuleSet | None:
|
||||
return ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none()
|
||||
|
||||
|
||||
def _mail_values(intake: ShippingNoticeIntake) -> dict[str, str]:
|
||||
"""从接入邮件元数据取邮箱和域名投影,不读取订单解析或 LLM 摘要。"""
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
email_meta = structured.get('email') if isinstance(structured.get('email'), dict) else {}
|
||||
sender = parseaddr(str(email_meta.get('from') or ''))[1].strip()
|
||||
if not sender:
|
||||
return {}
|
||||
try:
|
||||
email = normalize_email(sender)
|
||||
domain = normalize_domain(email)
|
||||
except Exception:
|
||||
return {}
|
||||
return {'email': email, 'domain': domain}
|
||||
|
||||
|
||||
def _template_fingerprint(candidate: ShippingNoticeCandidate) -> str | None:
|
||||
"""由主文档文本生成脱敏模板指纹;只保留哈希,不将正文或个人信息写入识别快照。"""
|
||||
document = db.session.get(ShippingNoticeDocument, int(candidate.primary_document_id))
|
||||
if document is None or int(document.intake_id) != int(candidate.intake_id):
|
||||
return None
|
||||
text = str(document.extracted_text or '').upper().strip()
|
||||
if not text:
|
||||
return None
|
||||
# 订单编号、日期、金额等可变字面量不参与模板身份,减少同模板不同订单的误分裂。
|
||||
template_shape = re.sub(r'\b[A-Z0-9][A-Z0-9_\-/]{2,}\b', '<TOKEN>', text)
|
||||
template_shape = re.sub(r'\d+', '<NUMBER>', template_shape)
|
||||
template_shape = re.sub(r'\s+', ' ', template_shape).strip()
|
||||
if not template_shape:
|
||||
return None
|
||||
return hashlib.sha256(template_shape.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _accepted_header_values(candidate: ShippingNoticeCandidate) -> tuple[ShippingOrderExtraction | None, dict[str, str]]:
|
||||
"""仅从 Candidate 外键关联的已裁决 Header FieldValue 读取业务证据,拒绝原始 JSON 和 Line 字段。"""
|
||||
def _accepted_header_values(candidate: ShippingNoticeCandidate) -> tuple[ShippingOrderExtraction | None, dict[str, dict[str, Any]]]:
|
||||
"""读取已裁决 Header FieldValue 及其决定主键,保留自动确认所需完整追溯链。"""
|
||||
if candidate.order_extraction_id is None:
|
||||
return None, {}
|
||||
extraction = db.session.get(ShippingOrderExtraction, int(candidate.order_extraction_id))
|
||||
@@ -107,8 +72,12 @@ def _accepted_header_values(candidate: ShippingNoticeCandidate) -> tuple[Shippin
|
||||
.all()
|
||||
)
|
||||
return extraction, {
|
||||
str(value.field_id): str(value.value_text or value.value_json or '').strip()
|
||||
for value, _decision in rows
|
||||
str(value.field_id): {
|
||||
'value': str(value.value_text or value.value_json or '').strip(),
|
||||
'field_value_id': value.id,
|
||||
'decision_id': decision.id,
|
||||
}
|
||||
for value, decision in rows
|
||||
if str(value.value_text or value.value_json or '').strip()
|
||||
}
|
||||
|
||||
@@ -116,42 +85,33 @@ def _accepted_header_values(candidate: ShippingNoticeCandidate) -> tuple[Shippin
|
||||
def _source_evidence(
|
||||
definitions: list[dict[str, Any]], *, candidate: ShippingNoticeCandidate, intake: ShippingNoticeIntake,
|
||||
) -> tuple[list[dict[str, Any]], ShippingOrderExtraction | None]:
|
||||
"""按规则快照的受控来源适配器编译证据输入,拒绝按定义编码决定取值。"""
|
||||
"""按规则快照的 context_field_id 编译证据,只消费统一已裁决字段值。"""
|
||||
extraction, header_values = _accepted_header_values(candidate)
|
||||
mail_values = _mail_values(intake)
|
||||
template_fingerprint = _template_fingerprint(candidate)
|
||||
evidence: list[dict[str, Any]] = []
|
||||
for definition in definitions:
|
||||
definition_id = str(definition.get('id') or '')
|
||||
code = str(definition.get('definition_code') or '')
|
||||
adapter_key = str(definition.get('source_adapter_key') or '')
|
||||
selector = definition.get('source_selector') if isinstance(definition.get('source_selector'), dict) else {}
|
||||
value: str | None = None
|
||||
source: dict[str, Any] = {'kind': 'unsupported_source_adapter'}
|
||||
if adapter_key == 'order_field':
|
||||
field_id = str(selector.get('order_field_id') or definition.get('order_field_id') or '')
|
||||
value = header_values.get(field_id)
|
||||
source = {'kind': 'order_field_value', 'order_field_id': field_id, 'extraction_id': extraction.id if extraction else None}
|
||||
elif adapter_key == 'email_metadata':
|
||||
projection = str(selector.get('projection') or '')
|
||||
if selector.get('attribute') == 'email.from' and projection in {'email', 'domain'}:
|
||||
value = mail_values.get(projection)
|
||||
source = {'kind': 'mail_metadata', 'attribute': 'email.from', 'projection': projection}
|
||||
elif adapter_key == 'document_template' and selector == {'document': 'primary'}:
|
||||
value = template_fingerprint
|
||||
source = {'kind': 'document_template_fingerprint', 'document_id': candidate.primary_document_id}
|
||||
if not value:
|
||||
field_id = str(definition.get('context_field_id') or '')
|
||||
accepted = header_values.get(field_id)
|
||||
if not accepted:
|
||||
continue
|
||||
value = accepted['value']
|
||||
source = {
|
||||
'kind': 'field_value',
|
||||
'context_field_id': field_id,
|
||||
'field_value_id': accepted['field_value_id'],
|
||||
'decision_id': accepted['decision_id'],
|
||||
'extraction_id': extraction.id if extraction else None,
|
||||
'order_schema_version_id': extraction.schema_version_id if extraction else None,
|
||||
}
|
||||
normalized = _normalize(definition, value)
|
||||
if not normalized:
|
||||
continue
|
||||
evidence.append({
|
||||
'definition_id': definition_id,
|
||||
'definition_code': code,
|
||||
'source_adapter_key': adapter_key,
|
||||
'source_selector': selector,
|
||||
'context_field_id': field_id,
|
||||
'target_type': definition.get('target_type'),
|
||||
'attribute_key': definition.get('attribute_key'),
|
||||
'raw_value': value,
|
||||
'normalized_value': normalized,
|
||||
'weight': int(definition.get('default_weight') or 0),
|
||||
@@ -237,6 +197,11 @@ def resolve_candidate_identity(candidate: ShippingNoticeCandidate, intake: Shipp
|
||||
"""
|
||||
rule_set = _published_rule_set()
|
||||
definitions = list((rule_set.definition_json or {}).get('definitions') or []) if rule_set else []
|
||||
schema_snapshot = (
|
||||
(rule_set.definition_json or {}).get('order_schema')
|
||||
if rule_set and isinstance((rule_set.definition_json or {}).get('order_schema'), dict)
|
||||
else None
|
||||
)
|
||||
evidence, extraction = _source_evidence(definitions, candidate=candidate, intake=intake)
|
||||
customer_matches = _rank_customer_matches(evidence)
|
||||
site_matches = _rank_site_matches(evidence)
|
||||
@@ -252,6 +217,7 @@ def resolve_candidate_identity(candidate: ShippingNoticeCandidate, intake: Shipp
|
||||
'id': rule_set.id if rule_set else None,
|
||||
'version': rule_set.version if rule_set else None,
|
||||
'checksum': rule_set.checksum if rule_set else None,
|
||||
'order_schema': schema_snapshot,
|
||||
'definitions': definitions,
|
||||
},
|
||||
'order_schema_version_id': extraction.schema_version_id if extraction else None,
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/app/services/shipping_notice/identity_rules/service.py
|
||||
|
||||
用途:管理货代客户识别定义、规则集版本和新证据值。
|
||||
依赖:订单 Schema 字段目录、客户/站点主数据、customer_normalization、统一异常。
|
||||
逻辑:平台只提供受控来源适配器;所有定义由管理员创建,发布规则集冻结全量快照。
|
||||
逻辑:管理员只选择已发布且允许客户识别的 Header 字段;规则集冻结字段配置快照。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -40,32 +40,6 @@ from app.services.shipping_notice.customer_normalization import (
|
||||
|
||||
DEFINITION_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
|
||||
TARGET_TYPES = frozenset({'customer', 'site'})
|
||||
SOURCE_ADAPTERS = {
|
||||
'email_metadata': {
|
||||
'display_name': '邮件发件人',
|
||||
'description': '从来件的发件人读取完整邮箱或企业域名。',
|
||||
'selectors': {'attribute': 'email.from', 'projections': {'email', 'domain'}},
|
||||
'options': {
|
||||
'email': {'display_name': '发件人邮箱', 'normalizer_key': 'email', 'max_automation': 'conditional'},
|
||||
'domain': {'display_name': '企业域名', 'normalizer_key': 'domain', 'max_automation': 'conditional'},
|
||||
},
|
||||
},
|
||||
'document_template': {
|
||||
'display_name': '单据版式',
|
||||
'description': '根据主单据的固定版式特征识别。',
|
||||
'selectors': {'document': 'primary'},
|
||||
'options': {
|
||||
'template': {'display_name': '当前单据版式', 'normalizer_key': 'text_upper', 'max_automation': 'conditional'},
|
||||
},
|
||||
},
|
||||
'order_field': {
|
||||
'display_name': '已解析订单字段',
|
||||
'description': '读取已发布订单字段中已经确认的内容,仅供人工复核使用。',
|
||||
'options': {},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _copy(value: Any) -> Any:
|
||||
"""复制目录或快照值,并将集合规范化为稳定 JSON 数组避免 API 序列化失败。"""
|
||||
def _json_default(item: Any) -> list[Any]:
|
||||
@@ -82,8 +56,9 @@ def _iso(value: datetime | None) -> str | None:
|
||||
|
||||
|
||||
def _definition_payload(row: ShippingIdentityDefinition, *, field: ShippingOrderField | None = None) -> dict[str, Any]:
|
||||
"""序列化识别定义及其稳定订单字段引用,不依赖前端自行判定权限。"""
|
||||
field = field or (db.session.get(ShippingOrderField, row.order_field_id) if row.order_field_id else None)
|
||||
"""序列化识别定义及其已发布上下文字段引用。"""
|
||||
field = field or db.session.get(ShippingOrderField, row.context_field_id)
|
||||
field_config = _published_field_config(row.context_field_id)
|
||||
return {
|
||||
'id': row.id,
|
||||
'definition_code': row.definition_code,
|
||||
@@ -91,16 +66,13 @@ def _definition_payload(row: ShippingIdentityDefinition, *, field: ShippingOrder
|
||||
'description': row.description,
|
||||
'evidence_label': row.evidence_label or '识别证据',
|
||||
'target_type': row.target_type,
|
||||
'source_adapter_key': row.source_adapter_key,
|
||||
'source_selector': _copy(row.source_selector_json or {}),
|
||||
'attribute_key': row.attribute_key,
|
||||
'order_field_id': row.order_field_id,
|
||||
'order_field': ({
|
||||
'context_field_id': row.context_field_id,
|
||||
'context_field': ({
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': _field_catalog_item(field)['display_name'],
|
||||
'scope': field.scope, 'value_type': field.value_type, 'status': field.status,
|
||||
'field_category': field.field_category, 'collection_mode': field.collection_mode,
|
||||
} if field else None),
|
||||
'normalizer_key': row.normalizer_key,
|
||||
'comparator_key': row.comparator_key,
|
||||
'field_config': _copy(field_config) if field_config else None,
|
||||
'default_weight': row.default_weight,
|
||||
'max_automation': row.max_automation,
|
||||
'status': row.status,
|
||||
@@ -127,64 +99,35 @@ def _write_audit(
|
||||
))
|
||||
|
||||
|
||||
def _source_adapter_catalog() -> list[dict[str, Any]]:
|
||||
"""返回只读来源适配器目录;客户端只能选择受控参数,不能提交任意取值路径。"""
|
||||
return [
|
||||
{
|
||||
'key': key,
|
||||
'display_name': value['display_name'],
|
||||
'description': value['description'],
|
||||
'selectors': _copy(value.get('selectors') or {}),
|
||||
'options': _copy(value.get('options') or {}),
|
||||
}
|
||||
for key, value in SOURCE_ADAPTERS.items()
|
||||
]
|
||||
def _published_field_config(field_id: str) -> dict[str, Any] | None:
|
||||
"""读取当前发布版本中的字段配置;识别定义和证据标准化均使用同一快照。"""
|
||||
published = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
return next((
|
||||
item for item in ((published.definition_json if published else {}) or {}).get('fields', [])
|
||||
if str(item.get('field_id') or '') == field_id and item.get('enabled', True)
|
||||
), None)
|
||||
|
||||
|
||||
def _validate_source(
|
||||
*, adapter_key: str, selector: object, field_id: str, target_type: str,
|
||||
) -> tuple[dict[str, Any], ShippingOrderField | None, str, str, str]:
|
||||
"""校验受控来源并推导内部执行参数,业务端不能提交属性或自动化等级。"""
|
||||
adapter = SOURCE_ADAPTERS.get(adapter_key)
|
||||
if adapter is None or not isinstance(selector, dict):
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
if adapter_key == 'order_field':
|
||||
field = _published_header_field(field_id)
|
||||
expected = {'order_field_id': field.id}
|
||||
if selector != expected:
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
return expected, field, 'text_upper', 'order_field_value', 'none'
|
||||
if field_id:
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
if adapter_key == 'email_metadata':
|
||||
if target_type != 'customer':
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
projection = clean_text(selector.get('projection')).lower()
|
||||
if selector != {'attribute': 'email.from', 'projection': projection} or projection not in {'email', 'domain'}:
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
option = adapter['options'][projection]
|
||||
return {'attribute': 'email.from', 'projection': projection}, None, option['normalizer_key'], projection, option['max_automation']
|
||||
if adapter_key == 'document_template':
|
||||
if target_type != 'customer' or selector != {'document': 'primary'}:
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
option = adapter['options']['template']
|
||||
return {'document': 'primary'}, None, option['normalizer_key'], 'template', option['max_automation']
|
||||
raise ValidationError('Identity definition source is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
def _published_schema_snapshot() -> dict[str, Any]:
|
||||
"""返回识别规则发布所绑定的唯一订单 Schema 版本锚点。"""
|
||||
published = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if published is None or not published.checksum:
|
||||
raise ConflictError(
|
||||
'Published order schema is required for identity rules',
|
||||
code='SHIPPING.IDENTITY_RULE_SET_CONFLICT',
|
||||
)
|
||||
return {'id': published.id, 'version': published.version, 'checksum': published.checksum}
|
||||
|
||||
|
||||
def _published_header_field(field_id: str) -> ShippingOrderField:
|
||||
"""验证业务来源字段已发布、启用且为可识别的 Header 文本字段。"""
|
||||
def _published_context_field(field_id: str) -> tuple[ShippingOrderField, dict[str, Any]]:
|
||||
"""验证字段已发布、启用、位于 Header 且明确允许用于客户识别。"""
|
||||
field = db.session.get(ShippingOrderField, field_id)
|
||||
if field is None or field.status != 'active' or field.scope != 'header' or field.value_type not in {'string', 'enum'}:
|
||||
raise ValidationError('Identity order field is invalid', code='SHIPPING.IDENTITY_ORDER_FIELD_INVALID')
|
||||
published = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
enabled_ids = {
|
||||
str(item.get('field_id')) for item in ((published.definition_json if published else {}) or {}).get('fields', [])
|
||||
if item.get('enabled', True)
|
||||
}
|
||||
if field.id not in enabled_ids:
|
||||
config = _published_field_config(field.id)
|
||||
if config is None or not config.get('available_for_customer_identity'):
|
||||
raise ValidationError('Identity order field is not published', code='SHIPPING.IDENTITY_ORDER_FIELD_INVALID')
|
||||
return field
|
||||
return field, config
|
||||
|
||||
|
||||
def list_definitions(*, target_type: str | None = None, active_only: bool = False) -> dict[str, Any]:
|
||||
@@ -199,11 +142,8 @@ def list_definitions(*, target_type: str | None = None, active_only: bool = Fals
|
||||
rows = query.order_by(ShippingIdentityDefinition.definition_code).all()
|
||||
return {
|
||||
'definitions': [_definition_payload(row) for row in rows],
|
||||
'order_fields': [_field_catalog_item(row) for row in _published_header_fields()],
|
||||
'catalog': {
|
||||
'target_types': sorted(TARGET_TYPES),
|
||||
'source_adapters': _source_adapter_catalog(),
|
||||
},
|
||||
'context_fields': [_field_catalog_item(row) for row in _published_header_fields()],
|
||||
'catalog': {'target_types': sorted(TARGET_TYPES)},
|
||||
}
|
||||
|
||||
|
||||
@@ -230,7 +170,8 @@ def _published_header_fields() -> list[ShippingOrderField]:
|
||||
if version is None:
|
||||
return []
|
||||
ids = [str(item.get('field_id')) for item in (version.definition_json or {}).get('fields', [])
|
||||
if item.get('enabled', True) and item.get('scope') == 'header' and item.get('value_type') in {'string', 'enum'}]
|
||||
if item.get('enabled', True) and item.get('scope') == 'header'
|
||||
and item.get('value_type') in {'string', 'enum'} and item.get('available_for_customer_identity')]
|
||||
return ShippingOrderField.query.filter(ShippingOrderField.id.in_(ids), ShippingOrderField.status == 'active').all() if ids else []
|
||||
|
||||
|
||||
@@ -243,6 +184,7 @@ def _field_catalog_item(field: ShippingOrderField) -> dict[str, Any]:
|
||||
return {
|
||||
'field_id': field.id, 'field_code': field.field_code, 'display_name': display_name,
|
||||
'scope': field.scope, 'value_type': field.value_type,
|
||||
'field_category': field.field_category, 'collection_mode': field.collection_mode,
|
||||
}
|
||||
|
||||
|
||||
@@ -257,18 +199,27 @@ def save_definition(data: dict[str, Any], *, actor_id: int | None, request_id: s
|
||||
evidence_label = clean_text(data.get('evidence_label'))
|
||||
code = clean_text(data.get('definition_code')).lower() or f'identity_rule_{uuid.uuid4().hex[:12]}'
|
||||
target = clean_text(data.get('target_type')).lower()
|
||||
field_id = clean_text(data.get('order_field_id'))
|
||||
adapter_key = clean_text(data.get('source_adapter_key')).lower()
|
||||
selector = data.get('source_selector')
|
||||
field_id = clean_text(data.get('context_field_id'))
|
||||
if not DEFINITION_CODE_RE.fullmatch(code) or target not in TARGET_TYPES:
|
||||
raise ValidationError('Identity definition is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
# 兼容服务层既有调用;管理端新建规则始终提交业务名称与证据名称。
|
||||
display_name = display_name or code
|
||||
evidence_label = evidence_label or display_name
|
||||
selector, field, normalizer, attribute, automation = _validate_source(
|
||||
adapter_key=adapter_key, selector=selector, field_id=field_id, target_type=target,
|
||||
)
|
||||
comparator = 'normalized_exact'
|
||||
field, field_config = _published_context_field(field_id)
|
||||
if row and (row.definition_code, row.target_type, row.context_field_id) != (code, target, field.id):
|
||||
referenced = ShippingIdentityEvidence.query.filter_by(definition_id=row.id).count() > 0 or any(
|
||||
any(str(item.get('id') or '') == row.id for item in (rule_set.definition_json or {}).get('definitions', []))
|
||||
for rule_set in ShippingIdentityRuleSet.query.filter(
|
||||
ShippingIdentityRuleSet.status.in_(['draft', 'published'])
|
||||
).all()
|
||||
)
|
||||
if referenced:
|
||||
raise ConflictError(
|
||||
'Referenced identity definition binding is immutable',
|
||||
code='SHIPPING.IDENTITY_DEFINITION_CONFLICT',
|
||||
)
|
||||
source = field_config.get('context_source') if isinstance(field_config.get('context_source'), dict) else {}
|
||||
automation = 'conditional' if source.get('option_key') in {'from_email', 'from_domain'} and target == 'customer' else 'none'
|
||||
requested_automation = clean_text(data.get('max_automation')).lower() if 'max_automation' in data else automation
|
||||
if requested_automation not in {'none', automation}:
|
||||
raise ValidationError('Identity definition automation is invalid', code='SHIPPING.IDENTITY_AUTOMATION_FORBIDDEN')
|
||||
@@ -281,8 +232,7 @@ def save_definition(data: dict[str, Any], *, actor_id: int | None, request_id: s
|
||||
raise ValidationError('Identity definition weight is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
row = row or ShippingIdentityDefinition(
|
||||
definition_code=code, display_name=display_name, description=description, evidence_label=evidence_label,
|
||||
target_type=target, source_adapter_key=adapter_key, source_selector_json=selector,
|
||||
attribute_key=attribute, order_field_id=field.id if field else None, normalizer_key=normalizer, comparator_key=comparator,
|
||||
target_type=target, context_field_id=field.id,
|
||||
default_weight=weight, max_automation=automation,
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
@@ -291,12 +241,7 @@ def save_definition(data: dict[str, Any], *, actor_id: int | None, request_id: s
|
||||
row.description = description
|
||||
row.evidence_label = evidence_label
|
||||
row.target_type = target
|
||||
row.source_adapter_key = adapter_key
|
||||
row.source_selector_json = selector
|
||||
row.attribute_key = attribute
|
||||
row.order_field_id = field.id if field else None
|
||||
row.normalizer_key = normalizer
|
||||
row.comparator_key = comparator
|
||||
row.context_field_id = field.id
|
||||
row.default_weight = weight
|
||||
row.max_automation = automation
|
||||
row.updated_by_id = actor_id
|
||||
@@ -396,7 +341,7 @@ def save_rule_set(rule_set_id: int, data: dict[str, Any], *, actor_id: int | Non
|
||||
|
||||
def publish_rule_set(rule_set_id: int, *, expected_lock_version: int | None, actor_id: int | None,
|
||||
request_id: str | None = None) -> dict[str, Any]:
|
||||
"""发布规则集并退役前一版本;发布快照 checksum 是运行期审计锚点。"""
|
||||
"""发布规则集并冻结订单 Schema 版本;双重 checksum 构成运行期审计锚点。"""
|
||||
row = db.session.get(ShippingIdentityRuleSet, rule_set_id)
|
||||
if row is None:
|
||||
raise NotFoundError('Identity rule set not found', code='SHIPPING.IDENTITY_RULE_SET_NOT_FOUND')
|
||||
@@ -405,9 +350,28 @@ def publish_rule_set(rule_set_id: int, *, expected_lock_version: int | None, act
|
||||
definitions = (row.definition_json or {}).get('definitions') or []
|
||||
if not definitions:
|
||||
raise ValidationError('Identity rule definitions are required', code='SHIPPING.IDENTITY_RULE_SET_INVALID')
|
||||
active_ids = {item.id for item in ShippingIdentityDefinition.query.filter_by(status='active').all()}
|
||||
if any(str(item.get('id') or '') not in active_ids for item in definitions):
|
||||
active_rows = {
|
||||
item.id: item for item in ShippingIdentityDefinition.query.filter_by(status='active').all()
|
||||
}
|
||||
definition_ids = [str(item.get('id') or '') for item in definitions]
|
||||
if any(definition_id not in active_rows for definition_id in definition_ids):
|
||||
raise ConflictError('Identity rule set references retired definitions', code='SHIPPING.IDENTITY_RULE_SET_CONFLICT')
|
||||
for definition_id in definition_ids:
|
||||
try:
|
||||
_published_context_field(active_rows[definition_id].context_field_id)
|
||||
except ValidationError as exc:
|
||||
raise ConflictError(
|
||||
'Identity rule set references an unavailable published field',
|
||||
code='SHIPPING.IDENTITY_RULE_SET_CONFLICT',
|
||||
) from exc
|
||||
# 发布边界必须重新编译当前 Schema 字段配置,禁止草稿携带陈旧 field_config 投产。
|
||||
row.definition_json = {
|
||||
'order_schema': _published_schema_snapshot(),
|
||||
'definitions': [
|
||||
_definition_snapshot(active_rows[definition_id])
|
||||
for definition_id in sorted(definition_ids, key=lambda item: active_rows[item].definition_code)
|
||||
],
|
||||
}
|
||||
current = ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none()
|
||||
now = datetime.utcnow()
|
||||
if current:
|
||||
@@ -425,13 +389,18 @@ def list_rule_sets() -> dict[str, Any]:
|
||||
return {'items': [_rule_set_payload(row) for row in ShippingIdentityRuleSet.query.order_by(ShippingIdentityRuleSet.version.desc()).all()]}
|
||||
|
||||
|
||||
def _normalize_for_definition(definition: ShippingIdentityDefinition, value: object) -> str:
|
||||
"""按定义受控 normalizer 生成证据匹配键,禁止前端传入任意处理方式。"""
|
||||
if definition.normalizer_key == 'email':
|
||||
def _normalize_for_snapshot(definition: dict[str, Any], value: object) -> str:
|
||||
"""按已发布规则集冻结的字段配置生成证据匹配键。"""
|
||||
config = definition.get('field_config') if isinstance(definition.get('field_config'), dict) else {}
|
||||
if not config:
|
||||
raise ValidationError('Identity definition snapshot is invalid', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
source = config.get('context_source') if isinstance(config.get('context_source'), dict) else {}
|
||||
option_key = str(source.get('option_key') or '')
|
||||
if option_key == 'from_email':
|
||||
return normalize_email(value)
|
||||
if definition.normalizer_key == 'domain':
|
||||
if option_key == 'from_domain':
|
||||
return normalize_domain(value)
|
||||
if definition.normalizer_key == 'name':
|
||||
if config.get('normalizer_key') == 'name':
|
||||
return normalize_customer_name(value)
|
||||
result = clean_text(value).upper()
|
||||
if not result:
|
||||
@@ -458,15 +427,21 @@ def create_evidence(*, target_type: str, target_id: int, data: dict[str, Any], a
|
||||
customer = db.session.get(ShippingCustomer, int(target.customer_id))
|
||||
if customer is None or customer.status != 'active':
|
||||
raise ValidationError('Identity evidence target is invalid', code='SHIPPING.IDENTITY_TARGET_INVALID')
|
||||
published_definition = next(
|
||||
item for item in (published.definition_json or {}).get('definitions', [])
|
||||
if str(item.get('id') or '') == definition.id
|
||||
)
|
||||
raw = clean_text(data.get('raw_value') or data.get('identifier_value'))
|
||||
normalized = _normalize_for_definition(definition, raw)
|
||||
normalized = _normalize_for_snapshot(published_definition, raw)
|
||||
status = clean_text(data.get('status') or 'pending').lower()
|
||||
allowed = data.get('auto_match_allowed', False)
|
||||
if status not in {'pending', 'approved', 'disabled'} or not isinstance(allowed, bool):
|
||||
raise ValidationError('Identity evidence status is invalid', code='SHIPPING.IDENTITY_EVIDENCE_INVALID')
|
||||
if allowed and (status != 'approved' or definition.max_automation != 'conditional'):
|
||||
if allowed and (status != 'approved' or published_definition.get('max_automation') != 'conditional'):
|
||||
raise ValidationError('Identity evidence cannot auto confirm', code='SHIPPING.IDENTITY_AUTOMATION_FORBIDDEN')
|
||||
if allowed and definition.attribute_key == 'domain' and is_public_email_domain(normalized):
|
||||
config = published_definition.get('field_config') if isinstance(published_definition.get('field_config'), dict) else {}
|
||||
source = config.get('context_source') if isinstance(config.get('context_source'), dict) else {}
|
||||
if allowed and source.get('option_key') == 'from_domain' and is_public_email_domain(normalized):
|
||||
raise ValidationError('Public email domain cannot auto confirm', code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN')
|
||||
row = ShippingIdentityEvidence(
|
||||
definition_id=definition.id, customer_id=target_id if target_type == 'customer' else None,
|
||||
@@ -513,9 +488,18 @@ def update_evidence(evidence_id: int, data: dict[str, Any], *, actor_id: int | N
|
||||
raise ValidationError('Identity evidence status is invalid', code='SHIPPING.IDENTITY_EVIDENCE_INVALID')
|
||||
if next_status != 'approved':
|
||||
next_allowed = False
|
||||
if next_allowed and definition.max_automation != 'conditional':
|
||||
published = ShippingIdentityRuleSet.query.filter_by(status='published').one_or_none()
|
||||
published_definition = next((
|
||||
item for item in ((published.definition_json if published else {}) or {}).get('definitions', [])
|
||||
if str(item.get('id') or '') == definition.id
|
||||
), None)
|
||||
if published_definition is None:
|
||||
raise ValidationError('Identity definition is not published', code='SHIPPING.IDENTITY_DEFINITION_INVALID')
|
||||
if next_allowed and published_definition.get('max_automation') != 'conditional':
|
||||
raise ValidationError('Identity evidence cannot auto confirm', code='SHIPPING.IDENTITY_AUTOMATION_FORBIDDEN')
|
||||
if next_allowed and definition.attribute_key == 'domain' and is_public_email_domain(row.normalized_value):
|
||||
config = published_definition.get('field_config') if isinstance(published_definition.get('field_config'), dict) else {}
|
||||
source = config.get('context_source') if isinstance(config.get('context_source'), dict) else {}
|
||||
if next_allowed and source.get('option_key') == 'from_domain' and is_public_email_domain(row.normalized_value):
|
||||
raise ValidationError('Public email domain cannot auto confirm', code='SHIPPING.CUSTOMER_PUBLIC_DOMAIN_AUTO_MATCH_FORBIDDEN')
|
||||
next_remark = clean_text(data.get('remark')) or None if 'remark' in data else row.remark
|
||||
changed = (next_status, bool(next_allowed), next_remark) != (row.status, bool(row.auto_match_allowed), row.remark)
|
||||
@@ -560,12 +544,10 @@ def serialize_evidence(row: ShippingIdentityEvidence) -> dict[str, Any]:
|
||||
def active_definition_field_references(field_id: str) -> list[str]:
|
||||
"""供订单 Schema 退役/发布门禁查询仍被启用业务定义引用的稳定字段。"""
|
||||
references: list[str] = []
|
||||
if ShippingIdentityDefinition.query.filter_by(
|
||||
source_adapter_key='order_field', order_field_id=field_id, status='active',
|
||||
).count():
|
||||
if ShippingIdentityDefinition.query.filter_by(context_field_id=field_id, status='active').count():
|
||||
references.append('identity_definition')
|
||||
if any(
|
||||
any(str(item.get('order_field_id') or '') == field_id for item in (rule_set.definition_json or {}).get('definitions', []))
|
||||
any(str(item.get('context_field_id') or '') == field_id for item in (rule_set.definition_json or {}).get('definitions', []))
|
||||
for rule_set in ShippingIdentityRuleSet.query.filter(ShippingIdentityRuleSet.status.in_(['draft', 'published'])).all()
|
||||
):
|
||||
references.append('identity_rule_set')
|
||||
|
||||
@@ -54,30 +54,6 @@ def _intake_ttl_hours() -> int:
|
||||
return max(int(current_app.config.get('SHIPPING_NOTICE_INTAKE_TTL_HOURS', 72) or 72), 1)
|
||||
|
||||
|
||||
def _expire_order_extractions_for_read(
|
||||
*,
|
||||
user_id: int,
|
||||
intake_nos: list[str] | None = None,
|
||||
conversation_id: str | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
在 Intake 读取入口惰性回收订单识别超时状态。
|
||||
|
||||
核心逻辑:委托 order_extraction 使用数据库快照和配置超时值完成带锁收口;
|
||||
读取接口无需依赖进程内定时器,服务重启后仍可恢复失败终态。
|
||||
|
||||
Returns:
|
||||
本次由 extracting 收口为 failed 的 Intake 数量。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction import expire_stale_order_extractions
|
||||
|
||||
return expire_stale_order_extractions(
|
||||
user_id=user_id,
|
||||
intake_nos=intake_nos,
|
||||
conversation_id=conversation_id,
|
||||
)
|
||||
|
||||
|
||||
def generate_intake_no() -> str:
|
||||
"""生成 SNI-YYYYMMDD-XXXXXXXX 格式接入编号。"""
|
||||
return f"SNI-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
@@ -253,7 +229,6 @@ def get_intake_for_user(intake_no: str, user_id: int) -> ShippingNoticeIntake:
|
||||
|
||||
def get_intake_detail(*, user_id: int, intake_no: str) -> dict[str, Any]:
|
||||
"""查询单个接入记录详情(含资产摘要与附件全文)。"""
|
||||
_expire_order_extractions_for_read(user_id=user_id, intake_nos=[intake_no])
|
||||
intake = get_intake_for_user(intake_no, user_id)
|
||||
asset = db.session.get(FileAsset, intake.asset_id)
|
||||
if not asset:
|
||||
@@ -412,7 +387,6 @@ def create_shipping_notice_intake(
|
||||
def list_active_intakes_for_conversation(*, user_id: int, conversation_id: str | None) -> list[dict[str, Any]]:
|
||||
"""列出会话下未消费的活跃接入记录,供页面恢复。"""
|
||||
conv = str(conversation_id or '').strip()
|
||||
_expire_order_extractions_for_read(user_id=user_id, conversation_id=conv or None)
|
||||
query = db.session.query(ShippingNoticeIntake, FileAsset).join(
|
||||
FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id
|
||||
).filter(
|
||||
@@ -431,7 +405,6 @@ def get_intake_statuses(*, user_id: int, intake_nos: list[str]) -> list[dict[str
|
||||
normalized = [str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()]
|
||||
if not normalized:
|
||||
return []
|
||||
_expire_order_extractions_for_read(user_id=user_id, intake_nos=normalized)
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeIntake, FileAsset)
|
||||
.join(FileAsset, FileAsset.id == ShippingNoticeIntake.asset_id)
|
||||
|
||||
@@ -74,31 +74,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
runtime_context = _str_prop(
|
||||
"HXOPS 注入的完整 agent_runtime_context JSON 字符串;必须原样透传,禁止由 LLM 构造或修改"
|
||||
)
|
||||
observation_schema = {
|
||||
"type": "object",
|
||||
"required": ["value", "document_id", "quote"],
|
||||
"properties": {
|
||||
"value": {"description": "从证据原文提取的字段值,类型必须符合动态字段契约"},
|
||||
"document_id": _int_prop("证据来源 Document ID,必须来自抽取上下文"),
|
||||
"quote": _str_prop("证据原文中的逐字引用,HXOPS 将验证其确实存在"),
|
||||
"confidence": {"type": "number", "minimum": 0, "maximum": 1},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
}
|
||||
extracted_field_schema = {
|
||||
"type": "object",
|
||||
"required": ["field_id", "observations"],
|
||||
"properties": {
|
||||
"field_id": _str_prop("动态字段契约中的稳定 field_id,禁止传 field_code 或显示名称"),
|
||||
"observations": {
|
||||
"type": "array",
|
||||
"minItems": 1,
|
||||
"items": observation_schema,
|
||||
},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
}
|
||||
|
||||
return {
|
||||
"openapi": "3.0.0",
|
||||
"info": {
|
||||
@@ -121,84 +96,6 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
|
||||
},
|
||||
"servers": [{"url": server}],
|
||||
"paths": {
|
||||
"/tools/get_order_extraction_context": _post_op(
|
||||
"get_order_extraction_context",
|
||||
"读取点击发送后完整订单抽取所需的邮件正文与附件文本",
|
||||
{"agent_runtime_context": runtime_context},
|
||||
required=["agent_runtime_context"],
|
||||
description=(
|
||||
"仅在 refs.capability=order_extraction 分支调用。Tool 从 platform.session_id 反查当前用户,"
|
||||
"并返回 input_snapshot_hash、documents 与当前 published 动态 Schema 契约;禁止让 LLM 传 user_id。"
|
||||
),
|
||||
),
|
||||
"/tools/submit_order_extraction": _post_op(
|
||||
"submit_order_extraction",
|
||||
"提交完整订单抽取结果,由 HXOPS 执行证据校验、订单级判重与自动建单",
|
||||
{
|
||||
"agent_runtime_context": runtime_context,
|
||||
"input_snapshot_hash": _str_prop("get_order_extraction_context 返回的不可变输入快照 SHA-256"),
|
||||
"orders": {
|
||||
"type": "array",
|
||||
"description": "LLM 从一封或多封邮件中识别出的订单数组;一个附件可产生多个订单,非发货邮件可为空数组",
|
||||
"maxItems": 50,
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"schema_version_id",
|
||||
"schema_checksum",
|
||||
"source_intake_no",
|
||||
"primary_document_id",
|
||||
"classification",
|
||||
"classification_confidence",
|
||||
"header_fields",
|
||||
"lines",
|
||||
],
|
||||
"properties": {
|
||||
"source_intake_no": _str_prop("来源 Intake 编号,必须来自上下文"),
|
||||
"schema_version_id": _int_prop("context.contract.schema_version_id,必须原样回传"),
|
||||
"schema_checksum": _str_prop("context.contract.checksum,必须原样回传"),
|
||||
"primary_document_id": _int_prop("主来源 Document ID,必须来自上下文"),
|
||||
"candidate_key_hint": _str_prop("可选稳定订单标识,如 PO/订单号;不得使用随机值"),
|
||||
"classification": _str_prop("仅 shipping_request 可自动建单", enum=["shipping_request", "non_shipping_request", "uncertain"]),
|
||||
"classification_confidence": {"type": "number", "minimum": 0, "maximum": 1},
|
||||
"header_fields": {
|
||||
"type": "array",
|
||||
"description": "Header scope 动态字段;仅可使用 context.contract.fields 中的稳定 field_id",
|
||||
"items": extracted_field_schema,
|
||||
},
|
||||
"lines": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": ["fields"],
|
||||
"properties": {
|
||||
"fields": {
|
||||
"type": "array",
|
||||
"description": "Line scope 动态字段;每项含 field_id 与 observations[]",
|
||||
"items": extracted_field_schema,
|
||||
},
|
||||
},
|
||||
"additionalProperties": False,
|
||||
},
|
||||
},
|
||||
"conflicts": {
|
||||
"type": "array",
|
||||
"items": {"type": "object", "additionalProperties": True},
|
||||
},
|
||||
},
|
||||
"additionalProperties": True,
|
||||
},
|
||||
},
|
||||
},
|
||||
required=["agent_runtime_context", "input_snapshot_hash", "orders"],
|
||||
description=(
|
||||
"只接受同一快照和同一 Schema checksum。Dify 必须逐字段返回稳定 field_id 与 observations[];"
|
||||
"每个 Observation 包含 value、document_id、逐字 quote 和可选 confidence。"
|
||||
"HXOPS 验证原文、执行类型/validator/证据策略与跨 Document 裁决后,才按 field_code 投影给下游。"
|
||||
"响应以持久化结果分别返回 created_count、opened_existing_count、pending_count、"
|
||||
"non_shipping_count;auto_created_count 仅为兼容字段且等于 created_count。"
|
||||
),
|
||||
),
|
||||
"/tools/create_temporary_inventory_session": _post_op(
|
||||
"create_temporary_inventory_session",
|
||||
"创建对话上传库存文件的临时分析会话",
|
||||
|
||||
@@ -1,18 +1,17 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_extraction.py
|
||||
|
||||
用途:为现有货代 Chatflow 提供建单前订单抽取上下文,并接收 LLM orders[] 完成校验、判重、自动建单与失败收口。
|
||||
依赖:agent_runtime_context、ChatSession、ShippingNoticeIntake/Document/Candidate、batch_from_intakes。
|
||||
逻辑:聊天请求进入 Dify 前先登记本轮抽取身份,Dify 再读取不可变输入快照并提交结构化订单;
|
||||
HXOPS 逐订单落 Candidate,高置信度内部料号/Qty 订单自动消费建 Task,其余保留供自然对话修订;
|
||||
Dify 终态或状态读取负责把未提交和超时请求收口为失败。
|
||||
用途:持久化后台订单抽取 Run 的结构化结果,完成校验、判重、自动建单与审计。
|
||||
依赖:ChatSession、ShippingNoticeIntake/Document/Candidate、动态 Schema 与 batch_from_intakes。
|
||||
逻辑:Worker 校验 Run 冻结快照后提交 orders[];HXOPS 逐订单落 Candidate,高置信度订单自动建 Task,
|
||||
其余保留供自然对话修订;Provider 成功结果可在 HXOPS 持久化失败时安全重放。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from flask import current_app
|
||||
@@ -21,15 +20,14 @@ from sqlalchemy.orm.attributes import flag_modified
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
Agent,
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingNoticeCandidate,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingTask,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
from app.services.agent_runtime_context.parser import parse_agent_runtime_context
|
||||
from app.services.shipping_notice.batch_from_intakes import create_shipping_batch_from_candidates
|
||||
from app.services.shipping_notice.business_fingerprint import (
|
||||
build_business_fingerprint,
|
||||
@@ -43,53 +41,8 @@ from app.services.shipping_notice.duplicate_detection import (
|
||||
detect_duplicates_for_candidate,
|
||||
)
|
||||
from app.services.shipping_notice.document_candidate_persist import generate_candidate_no
|
||||
from app.services.shipping_notice.order_schema.runtime import dify_contract, persist_dynamic_order, published_version
|
||||
|
||||
_CONTEXT_PATHS = [
|
||||
'agent_code',
|
||||
'platform.session_id',
|
||||
'platform.request_id',
|
||||
'refs.capability',
|
||||
'refs.intake_nos',
|
||||
]
|
||||
ORDER_EXTRACTION_FAILED_CODE = 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED'
|
||||
ORDER_EXTRACTION_INCOMPLETE_MESSAGE = '订单识别流程未提交有效结果,请重新发送当前邮件。'
|
||||
ORDER_EXTRACTION_TIMEOUT_MESSAGE = '订单识别超时,请重新发送当前邮件。'
|
||||
|
||||
|
||||
def _runtime_identity(raw_context: str | dict[str, Any]) -> tuple[ChatSession, list[str], str]:
|
||||
"""从统一运行态上下文解析会话用户、Intake集合与请求号。"""
|
||||
parsed = parse_agent_runtime_context(raw_context, _CONTEXT_PATHS)
|
||||
values = parsed.get('data') if isinstance(parsed.get('data'), dict) else {}
|
||||
if str(values.get('agent_code') or '') != 'shipping_notice':
|
||||
raise ForbiddenError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='当前上下文不属于货代发货应用')
|
||||
if str(values.get('refs.capability') or '') != 'order_extraction':
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='当前上下文不是订单抽取请求')
|
||||
session_id = str(values.get('platform.session_id') or '').strip()
|
||||
request_id = str(values.get('platform.request_id') or '').strip()
|
||||
if not session_id or not request_id:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='订单抽取请求缺少会话或请求标识')
|
||||
session = (
|
||||
db.session.query(ChatSession)
|
||||
.join(Agent, Agent.id == ChatSession.agent_id)
|
||||
.filter(
|
||||
ChatSession.session_id == session_id,
|
||||
Agent.agent_code == 'shipping_notice',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if session is None:
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='聊天会话不存在')
|
||||
try:
|
||||
raw_nos = json.loads(str(values.get('refs.intake_nos') or '[]'))
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='Intake 上下文格式无效') from exc
|
||||
if not isinstance(raw_nos, list):
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='Intake 上下文必须为数组')
|
||||
intake_nos = sorted({str(item or '').strip().upper() for item in raw_nos if str(item or '').strip()})
|
||||
if not intake_nos:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='未提供待解析 Intake')
|
||||
return session, intake_nos, request_id
|
||||
from app.services.shipping_notice.order_schema.runtime import persist_dynamic_order
|
||||
from app.services.shipping_notice.context_fields.runtime import canonical_mail_context
|
||||
|
||||
|
||||
def _load_intakes(
|
||||
@@ -138,560 +91,11 @@ def _load_documents(intakes: list[ShippingNoticeIntake], *, lock: bool) -> list[
|
||||
return query.order_by(ShippingNoticeDocument.intake_id.asc(), ShippingNoticeDocument.id.asc()).all()
|
||||
|
||||
|
||||
def _snapshot_hash(intakes: list[ShippingNoticeIntake], documents: list[ShippingNoticeDocument]) -> str:
|
||||
"""对输入集合及正文内容生成稳定 SHA-256,拒绝旧 LLM 结果覆盖新附件。"""
|
||||
payload = {
|
||||
'intakes': [
|
||||
{
|
||||
'id': row.id,
|
||||
'no': row.intake_no,
|
||||
'asset_id': row.asset_id,
|
||||
}
|
||||
for row in intakes
|
||||
],
|
||||
'documents': [
|
||||
{
|
||||
'id': row.id,
|
||||
'intake_id': row.intake_id,
|
||||
'content_hash': row.content_hash,
|
||||
'parse_status': row.parse_status,
|
||||
'text_hash': hashlib.sha256(str(row.extracted_text or '').encode('utf-8')).hexdigest(),
|
||||
}
|
||||
for row in documents
|
||||
],
|
||||
}
|
||||
raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'))
|
||||
return hashlib.sha256(raw.encode('utf-8')).hexdigest()
|
||||
|
||||
|
||||
def _normalized_intake_nos(intake_nos: list[str]) -> list[str]:
|
||||
"""规范化并稳定排序 Intake 编号,供请求登记、失败收口和超时回收复用。"""
|
||||
return sorted({str(item or '').strip().upper() for item in intake_nos if str(item or '').strip()})
|
||||
|
||||
|
||||
def _order_extraction_snapshot(intake: ShippingNoticeIntake) -> dict[str, Any]:
|
||||
"""读取 Intake 当前抽取快照;旧数据或非法结构统一视为空快照。"""
|
||||
def _order_extraction_submission(intake: ShippingNoticeIntake) -> dict[str, Any]:
|
||||
"""读取已持久化的订单抽取提交事实;非法结构统一视为空。"""
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
snapshot = structured.get('order_extraction_snapshot')
|
||||
return snapshot if isinstance(snapshot, dict) else {}
|
||||
|
||||
|
||||
def _parse_snapshot_time(value: Any) -> datetime | None:
|
||||
"""将抽取快照时间转换为无时区 UTC,兼容 ISO `Z` 与带时区格式。"""
|
||||
text = str(value or '').strip()
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
parsed = datetime.fromisoformat(text.replace('Z', '+00:00'))
|
||||
except ValueError:
|
||||
return None
|
||||
if parsed.tzinfo is not None:
|
||||
parsed = parsed.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
return parsed
|
||||
|
||||
|
||||
def _set_documents_extraction_state(
|
||||
*,
|
||||
intake_ids: list[int],
|
||||
status: str,
|
||||
error_code: str | None,
|
||||
error_message: str | None,
|
||||
now: datetime,
|
||||
only_extracting: bool,
|
||||
) -> None:
|
||||
"""
|
||||
同步本轮 Intake 下 Document 的订单抽取状态。
|
||||
|
||||
Args:
|
||||
intake_ids: 已通过用户、会话与请求身份校验的 Intake 主键。
|
||||
status: 目标状态。
|
||||
error_code: 失败错误码;开始抽取时传 None。
|
||||
error_message: 用户可见错误说明;开始抽取时传 None。
|
||||
now: 本次状态更新时间。
|
||||
only_extracting: True 时只收口仍在 extracting 的 Document,禁止覆盖成功终态。
|
||||
"""
|
||||
if not intake_ids:
|
||||
return
|
||||
query = db.session.query(ShippingNoticeDocument).filter(
|
||||
ShippingNoticeDocument.intake_id.in_(intake_ids)
|
||||
)
|
||||
if only_extracting:
|
||||
query = query.filter(ShippingNoticeDocument.order_extraction_status == 'extracting')
|
||||
for document in query.with_for_update().all():
|
||||
document.order_extraction_status = status
|
||||
document.order_extraction_source = 'dify_chatflow'
|
||||
document.order_extraction_error_code = error_code
|
||||
document.order_extraction_error_message = error_message
|
||||
document.updated_at = now
|
||||
|
||||
|
||||
def start_order_extraction(
|
||||
*,
|
||||
user_id: int,
|
||||
session_id: str,
|
||||
intake_nos: list[str],
|
||||
request_id: str,
|
||||
) -> int:
|
||||
"""
|
||||
在请求进入 Dify 前登记权威订单抽取状态。
|
||||
|
||||
核心逻辑:锁定当前用户和会话的完整 Intake 集合;同一 request 重入不刷新超时起点,
|
||||
新 request 则覆盖旧快照身份,使旧 terminal 无法把新一轮抽取收口为失败。
|
||||
|
||||
Args:
|
||||
user_id: 当前聊天用户主键。
|
||||
session_id: HXOPS 本地会话号,必须与 Intake 绑定会话一致。
|
||||
intake_nos: 本轮完整 Intake 编号集合。
|
||||
request_id: 本轮 HXOPS 请求号,不得为空。
|
||||
|
||||
Returns:
|
||||
本轮进入 extracting 的 Intake 数量;同一请求重复登记仍返回完整数量。
|
||||
|
||||
Raises:
|
||||
ValidationError: 请求身份或 Intake 集合为空。
|
||||
NotFoundError: Intake 集合不完整。
|
||||
ConflictError: Intake 尚未预处理完成、已消费或绑定其他会话。
|
||||
"""
|
||||
normalized = _normalized_intake_nos(intake_nos)
|
||||
session_value = str(session_id or '').strip()
|
||||
request_value = str(request_id or '').strip()
|
||||
if not normalized or not session_value or not request_value:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='订单识别请求上下文不完整')
|
||||
|
||||
intakes = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.order_by(ShippingNoticeIntake.id.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
if {row.intake_no for row in intakes} != set(normalized):
|
||||
db.session.rollback()
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='部分发货通知接入记录不存在')
|
||||
now = datetime.utcnow()
|
||||
intake_ids: list[int] = []
|
||||
for intake in intakes:
|
||||
if intake.parse_status == 'consumed' or intake.consumed_at is not None:
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_ALREADY_CONSUMED',
|
||||
message='该邮件或附件的订单抽取已完成,请查看已有任务或订单抽取结果',
|
||||
)
|
||||
if intake.parse_status != 'parsed':
|
||||
db.session.rollback()
|
||||
raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING', message='邮件或附件尚未完成预处理')
|
||||
if intake.conversation_id and intake.conversation_id != session_value:
|
||||
db.session.rollback()
|
||||
raise ConflictError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID', message='发货通知已绑定其他会话')
|
||||
intake.conversation_id = session_value
|
||||
previous = _order_extraction_snapshot(intake)
|
||||
same_request = (
|
||||
intake.order_extraction_status == 'extracting'
|
||||
and str(previous.get('request_id') or '') == request_value
|
||||
and str(previous.get('session_id') or '') == session_value
|
||||
)
|
||||
structured = dict(intake.structured_result_json or {})
|
||||
next_snapshot = dict(previous) if same_request else {}
|
||||
structured['order_extraction_snapshot'] = {
|
||||
**next_snapshot,
|
||||
'request_id': request_value,
|
||||
'session_id': session_value,
|
||||
'created_at': previous.get('created_at') if same_request and previous.get('created_at') else now.isoformat(),
|
||||
}
|
||||
intake.structured_result_json = structured
|
||||
flag_modified(intake, 'structured_result_json')
|
||||
intake.order_extraction_status = 'extracting'
|
||||
intake.order_extraction_error_code = None
|
||||
intake.order_extraction_error_message = None
|
||||
intake.updated_at = now
|
||||
intake_ids.append(int(intake.id))
|
||||
_set_documents_extraction_state(
|
||||
intake_ids=intake_ids,
|
||||
status='extracting',
|
||||
error_code=None,
|
||||
error_message=None,
|
||||
now=now,
|
||||
only_extracting=False,
|
||||
)
|
||||
db.session.commit()
|
||||
return len(intakes)
|
||||
|
||||
|
||||
def finalize_order_extraction_failure(
|
||||
*,
|
||||
user_id: int,
|
||||
session_id: str,
|
||||
intake_nos: list[str],
|
||||
request_id: str,
|
||||
error_code: str = ORDER_EXTRACTION_FAILED_CODE,
|
||||
error_message: str = ORDER_EXTRACTION_INCOMPLETE_MESSAGE,
|
||||
) -> int:
|
||||
"""
|
||||
将当前请求仍未提交的订单抽取幂等收口为失败。
|
||||
|
||||
核心逻辑:先验证用户、会话与完整 Intake 集合,再逐条匹配快照 request/session;
|
||||
只允许 extracting 转 failed,因此成功结果、部分完成结果和新请求均不会被旧 terminal 覆盖。
|
||||
|
||||
Args:
|
||||
user_id: 当前聊天用户主键。
|
||||
session_id: 当前 HXOPS 会话号。
|
||||
intake_nos: 当前请求携带的完整 Intake 集合。
|
||||
request_id: 当前 HXOPS 请求号。
|
||||
error_code: 稳定业务错误码,最长 64 字符。
|
||||
error_message: 用户可见错误说明,不得包含密钥或堆栈。
|
||||
|
||||
Returns:
|
||||
实际由 extracting 更新为 failed 的 Intake 数量;重复调用或旧请求返回 0。
|
||||
"""
|
||||
normalized = _normalized_intake_nos(intake_nos)
|
||||
session_value = str(session_id or '').strip()
|
||||
request_value = str(request_id or '').strip()
|
||||
if not normalized or not session_value or not request_value:
|
||||
return 0
|
||||
intakes = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.order_by(ShippingNoticeIntake.id.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
if {row.intake_no for row in intakes} != set(normalized):
|
||||
db.session.rollback()
|
||||
return 0
|
||||
now = datetime.utcnow()
|
||||
code = str(error_code or ORDER_EXTRACTION_FAILED_CODE).strip()[:64]
|
||||
message = str(error_message or ORDER_EXTRACTION_INCOMPLETE_MESSAGE).strip()[:2000]
|
||||
failed_ids: list[int] = []
|
||||
for intake in intakes:
|
||||
snapshot = _order_extraction_snapshot(intake)
|
||||
if (
|
||||
intake.order_extraction_status != 'extracting'
|
||||
or intake.conversation_id != session_value
|
||||
or str(snapshot.get('request_id') or '') != request_value
|
||||
or str(snapshot.get('session_id') or '') != session_value
|
||||
):
|
||||
continue
|
||||
intake.order_extraction_status = 'failed'
|
||||
intake.order_extraction_error_code = code
|
||||
intake.order_extraction_error_message = message
|
||||
intake.updated_at = now
|
||||
failed_ids.append(int(intake.id))
|
||||
_set_documents_extraction_state(
|
||||
intake_ids=failed_ids,
|
||||
status='failed',
|
||||
error_code=code,
|
||||
error_message=message,
|
||||
now=now,
|
||||
only_extracting=True,
|
||||
)
|
||||
db.session.commit()
|
||||
return len(failed_ids)
|
||||
|
||||
|
||||
def expire_stale_order_extractions(
|
||||
*,
|
||||
user_id: int,
|
||||
intake_nos: list[str] | None = None,
|
||||
conversation_id: str | None = None,
|
||||
timeout_seconds: int | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> int:
|
||||
"""
|
||||
在 Intake 状态读取时惰性回收超时订单抽取。
|
||||
|
||||
核心逻辑:锁定当前用户仍为 extracting 的记录,优先使用快照 created_at,旧数据回退 updated_at;
|
||||
只更新超时记录及其仍在 extracting 的 Documents,不依赖进程内定时器。
|
||||
|
||||
Args:
|
||||
user_id: 当前用户主键。
|
||||
intake_nos: 可选 Intake 范围;批量状态接口应传入请求集合。
|
||||
conversation_id: 可选会话范围;会话恢复接口应传入当前会话。
|
||||
timeout_seconds: 可选覆盖值,默认读取应用配置,最小为 1 秒。
|
||||
now: 测试使用的 UTC 当前时间;生产不传。
|
||||
|
||||
Returns:
|
||||
实际回收为 failed 的 Intake 数量。
|
||||
"""
|
||||
configured = timeout_seconds
|
||||
if configured is None:
|
||||
configured = int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS') or 300)
|
||||
timeout = max(int(configured), 1)
|
||||
current_time = now or datetime.utcnow()
|
||||
if current_time.tzinfo is not None:
|
||||
current_time = current_time.astimezone(timezone.utc).replace(tzinfo=None)
|
||||
query = db.session.query(ShippingNoticeIntake).filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.order_extraction_status == 'extracting',
|
||||
)
|
||||
normalized = _normalized_intake_nos(intake_nos or [])
|
||||
if intake_nos is not None:
|
||||
if not normalized:
|
||||
return 0
|
||||
query = query.filter(ShippingNoticeIntake.intake_no.in_(normalized))
|
||||
conversation_value = str(conversation_id or '').strip()
|
||||
if conversation_value:
|
||||
query = query.filter(ShippingNoticeIntake.conversation_id == conversation_value)
|
||||
|
||||
expired_ids: list[int] = []
|
||||
for intake in query.order_by(ShippingNoticeIntake.id.asc()).with_for_update().all():
|
||||
snapshot = _order_extraction_snapshot(intake)
|
||||
started_at = _parse_snapshot_time(snapshot.get('created_at')) or intake.updated_at
|
||||
if started_at is None or current_time - started_at < timedelta(seconds=timeout):
|
||||
continue
|
||||
intake.order_extraction_status = 'failed'
|
||||
intake.order_extraction_error_code = ORDER_EXTRACTION_FAILED_CODE
|
||||
intake.order_extraction_error_message = ORDER_EXTRACTION_TIMEOUT_MESSAGE
|
||||
intake.updated_at = current_time
|
||||
expired_ids.append(int(intake.id))
|
||||
_set_documents_extraction_state(
|
||||
intake_ids=expired_ids,
|
||||
status='failed',
|
||||
error_code=ORDER_EXTRACTION_FAILED_CODE,
|
||||
error_message=ORDER_EXTRACTION_TIMEOUT_MESSAGE,
|
||||
now=current_time,
|
||||
only_extracting=True,
|
||||
)
|
||||
# 查询使用 FOR UPDATE;即使没有超时记录也提交只读事务,避免状态接口序列化期间继续持锁。
|
||||
db.session.commit()
|
||||
return len(expired_ids)
|
||||
|
||||
|
||||
def get_order_extraction_state(
|
||||
*,
|
||||
user_id: int,
|
||||
session_id: str,
|
||||
intake_nos: list[str],
|
||||
request_id: str,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
读取当前订单抽取请求可用于聊天展示的权威聚合状态。
|
||||
|
||||
核心逻辑:按用户、会话、完整 Intake 集合和 snapshot request_id 做四重围栏;
|
||||
处理中只返回不确定进度,终态从已持久化的 submission.result 读取真实建单计数。
|
||||
|
||||
Args:
|
||||
user_id: 当前聊天用户主键。
|
||||
session_id: HXOPS 本地会话号。
|
||||
intake_nos: 本轮完整 Intake 编号集合。
|
||||
request_id: 本轮 HXOPS 请求号。
|
||||
|
||||
Returns:
|
||||
包含 status、phase、message、真实结果计数、batch_no 与 terminal 的状态字典。
|
||||
|
||||
Raises:
|
||||
ValidationError: 请求身份不完整。
|
||||
NotFoundError: Intake 集合不存在或不完整。
|
||||
ConflictError: Intake 不属于当前会话或已被更新请求取代。
|
||||
"""
|
||||
normalized = _normalized_intake_nos(intake_nos)
|
||||
session_value = str(session_id or '').strip()
|
||||
request_value = str(request_id or '').strip()
|
||||
if int(user_id or 0) <= 0 or not normalized or not session_value or not request_value:
|
||||
raise ValidationError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID',
|
||||
message='订单识别请求上下文不完整',
|
||||
)
|
||||
|
||||
intakes = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(
|
||||
ShippingNoticeIntake.user_id == int(user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(normalized),
|
||||
)
|
||||
.order_by(ShippingNoticeIntake.id.asc())
|
||||
.all()
|
||||
)
|
||||
if {row.intake_no for row in intakes} != set(normalized):
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='部分发货通知接入记录不存在')
|
||||
|
||||
for intake in intakes:
|
||||
snapshot = _order_extraction_snapshot(intake)
|
||||
if (
|
||||
intake.conversation_id != session_value
|
||||
or str(snapshot.get('session_id') or '') != session_value
|
||||
or str(snapshot.get('request_id') or '') != request_value
|
||||
):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING',
|
||||
message='订单识别请求已失效或已被更新请求取代',
|
||||
)
|
||||
|
||||
statuses = {str(row.order_extraction_status or '').strip() for row in intakes}
|
||||
if 'extracting' in statuses:
|
||||
status = 'extracting'
|
||||
elif statuses == {'failed'}:
|
||||
status = 'failed'
|
||||
elif 'partially_completed' in statuses or 'failed' in statuses:
|
||||
status = 'partially_completed'
|
||||
elif statuses == {'completed'}:
|
||||
status = 'completed'
|
||||
else:
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING',
|
||||
message='订单识别尚未进入可展示状态',
|
||||
)
|
||||
|
||||
result: dict[str, Any] = {}
|
||||
for intake in intakes:
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
submission = structured.get('order_extraction_submission')
|
||||
if not isinstance(submission, dict) or str(submission.get('request_id') or '') != request_value:
|
||||
continue
|
||||
candidate = submission.get('result')
|
||||
if isinstance(candidate, dict):
|
||||
result = candidate
|
||||
break
|
||||
|
||||
if status == 'extracting':
|
||||
message = '正在识别邮件及附件中的订单'
|
||||
phase = 'llm_extraction'
|
||||
elif status == 'failed':
|
||||
message = next(
|
||||
(
|
||||
str(row.order_extraction_error_message or '').strip()
|
||||
for row in intakes
|
||||
if str(row.order_extraction_error_message or '').strip()
|
||||
),
|
||||
'订单识别失败,请重新发送当前邮件。',
|
||||
)
|
||||
phase = 'failed'
|
||||
else:
|
||||
message = str(result.get('message') or '').strip()
|
||||
if not message:
|
||||
message = '部分订单已处理,仍需补充或确认。' if status == 'partially_completed' else '订单识别完成。'
|
||||
phase = 'result_persisted'
|
||||
|
||||
def _count(key: str) -> int:
|
||||
"""将 Tool 结果计数约束为非负整数,异常值按 0 展示。"""
|
||||
try:
|
||||
return max(int(result.get(key) or 0), 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
return {
|
||||
'status': status,
|
||||
'phase': phase,
|
||||
'message': message,
|
||||
'created_count': _count('created_count'),
|
||||
'opened_existing_count': _count('opened_existing_count'),
|
||||
'pending_count': _count('pending_count'),
|
||||
'non_shipping_count': _count('non_shipping_count'),
|
||||
'created_with_missing_fields_count': _count('created_with_missing_fields_count'),
|
||||
'batch_no': str(result.get('batch_no') or '').strip() or None,
|
||||
'terminal': status != 'extracting',
|
||||
}
|
||||
|
||||
|
||||
def get_order_extraction_context(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"""
|
||||
返回现有 Chatflow 完整理解邮件所需的 Intake/Document 上下文。
|
||||
|
||||
【AI 触发时机】:当 agent_runtime_context.refs.capability=order_extraction 时,
|
||||
在订单抽取 LLM 节点之前调用一次;禁止用于已创建 Task 的普通续办。
|
||||
|
||||
Args:
|
||||
payload: 必须包含 agent_runtime_context。
|
||||
|
||||
Returns:
|
||||
邮件正文、附件文本、规则提示、输入快照 hash 与输出契约。
|
||||
"""
|
||||
session, intake_nos, request_id = _runtime_identity(payload.get('agent_runtime_context'))
|
||||
intakes = _load_intakes(session=session, intake_nos=intake_nos, lock=True)
|
||||
for intake in intakes:
|
||||
previous_snapshot = _order_extraction_snapshot(intake)
|
||||
if (
|
||||
intake.order_extraction_status == 'extracting'
|
||||
and previous_snapshot.get('request_id')
|
||||
and (
|
||||
str(previous_snapshot.get('request_id') or '') != request_id
|
||||
or str(previous_snapshot.get('session_id') or '') != session.session_id
|
||||
)
|
||||
):
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING',
|
||||
message='已有更新的订单识别请求正在处理,当前旧请求已失效',
|
||||
)
|
||||
documents = _load_documents(intakes, lock=False)
|
||||
if not documents:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE', message='未找到可供订单抽取的邮件正文或附件')
|
||||
|
||||
max_total = int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_CONTEXT_CHARS') or 500000)
|
||||
used = 0
|
||||
document_rows: list[dict[str, Any]] = []
|
||||
intake_by_id = {int(row.id): row for row in intakes}
|
||||
for document in documents:
|
||||
text = str(document.extracted_text or '')
|
||||
remaining = max(max_total - used, 0)
|
||||
clipped = text[:remaining]
|
||||
used += len(clipped)
|
||||
document_rows.append({
|
||||
'document_id': int(document.id),
|
||||
'source_intake_no': intake_by_id[int(document.intake_id)].intake_no,
|
||||
'document_type': document.document_type,
|
||||
'filename': document.filename,
|
||||
'mime_type': (
|
||||
db.session.get(FileAsset, int(document.asset_id)).mime_type
|
||||
if document.asset_id and db.session.get(FileAsset, int(document.asset_id)) is not None
|
||||
else None
|
||||
),
|
||||
'classification_hint': document.classification,
|
||||
'parse_status': document.parse_status,
|
||||
'text': clipped,
|
||||
'text_truncated': len(clipped) < len(text),
|
||||
'warnings': list(document.parse_warnings_json or []),
|
||||
})
|
||||
snapshot = _snapshot_hash(intakes, documents)
|
||||
now = datetime.utcnow()
|
||||
for intake in intakes:
|
||||
structured = dict(intake.structured_result_json or {})
|
||||
previous_snapshot = _order_extraction_snapshot(intake)
|
||||
structured['order_extraction_snapshot'] = {
|
||||
**previous_snapshot,
|
||||
'hash': snapshot,
|
||||
'request_id': request_id,
|
||||
'session_id': session.session_id,
|
||||
'created_at': (
|
||||
previous_snapshot.get('created_at')
|
||||
if str(previous_snapshot.get('request_id') or '') == request_id
|
||||
and str(previous_snapshot.get('session_id') or '') == session.session_id
|
||||
and previous_snapshot.get('created_at')
|
||||
else now.isoformat()
|
||||
),
|
||||
}
|
||||
intake.structured_result_json = structured
|
||||
flag_modified(intake, 'structured_result_json')
|
||||
intake.order_extraction_status = 'extracting'
|
||||
intake.order_extraction_error_code = None
|
||||
intake.order_extraction_error_message = None
|
||||
intake.updated_at = now
|
||||
_set_documents_extraction_state(
|
||||
intake_ids=[int(row.id) for row in intakes],
|
||||
status='extracting',
|
||||
error_code=None,
|
||||
error_message=None,
|
||||
now=now,
|
||||
only_extracting=False,
|
||||
)
|
||||
db.session.commit()
|
||||
return {
|
||||
'status': 'ok',
|
||||
'request_id': request_id,
|
||||
'input_snapshot_hash': snapshot,
|
||||
'intake_nos': intake_nos,
|
||||
'documents': document_rows,
|
||||
'rule_hints': {
|
||||
row.intake_no: dict(row.structured_result_json or {}).get('rule_hints') or {}
|
||||
for row in intakes
|
||||
},
|
||||
'contract': dify_contract(published_version()),
|
||||
}
|
||||
submission = structured.get('order_extraction_submission')
|
||||
return submission if isinstance(submission, dict) else {}
|
||||
|
||||
|
||||
def _float(value: Any, default: float = 0.0) -> float:
|
||||
@@ -768,45 +172,43 @@ def _build_submission_message(
|
||||
return message
|
||||
|
||||
|
||||
def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
def persist_order_extraction_result(
|
||||
*,
|
||||
session: ChatSession,
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
documents: list[ShippingNoticeDocument],
|
||||
current_snapshot: str,
|
||||
request_id: str,
|
||||
orders: list[dict[str, Any]],
|
||||
run_id: int | None,
|
||||
schema_version_id: int,
|
||||
extraction_source: str = 'dify_workflow',
|
||||
frozen_context_by_intake: dict[int, dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
提交 Chatflow 的 orders[],执行后端强校验、订单级判重与自动建单。
|
||||
|
||||
【AI 触发时机】:订单抽取 LLM + JSON 标准化节点成功后调用;每轮只调用一次。
|
||||
低置信度、缺内部料号/Qty、证据不足或可能修订的订单会保留为待处理 Candidate,
|
||||
不得由画布自行绕过后端门禁。
|
||||
持久化后台订单抽取 Run 的结构化结果,并执行后端裁决、判重与自动建单。
|
||||
|
||||
Args:
|
||||
payload: agent_runtime_context、input_snapshot_hash、orders。
|
||||
|
||||
session: Run 已授权且与入口 Agent 匹配的本地会话。
|
||||
intakes: 按 Run 冻结集合加载并锁定的 Intake;允许终态幂等回放。
|
||||
documents: 上述 Intake 的当前锁定 Document,用于证据归属和漂移校验。
|
||||
current_snapshot: 已与 Run 冻结输入核对一致的内容摘要。
|
||||
request_id: Run 编号,作为 Candidate/Submission 的服务端幂等围栏。
|
||||
orders: 专用 Workflow 输出的结构化订单数组。
|
||||
run_id: ShippingOrderExtractionRun 主键;生产 Run 必须提供,领域单测可为空。
|
||||
schema_version_id: Run 冻结的 published Schema 版本。
|
||||
extraction_source: 固定为后台 Workflow 来源,不接受用户输入。
|
||||
frozen_context_by_intake: Run 按 Intake 冻结的确定性上下文;后台 Run 必须提供。
|
||||
Returns:
|
||||
自动创建/打开的任务、待处理订单及缺失流程字段摘要。
|
||||
"""
|
||||
session, intake_nos, request_id = _runtime_identity(payload.get('agent_runtime_context'))
|
||||
orders = payload.get('orders')
|
||||
if not isinstance(orders, list):
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT', message='orders 必须为数组')
|
||||
max_orders = int(current_app.config.get('SHIPPING_NOTICE_ORDER_EXTRACTION_MAX_ORDERS') or 50)
|
||||
if len(orders) > max_orders:
|
||||
raise ValidationError(code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT', message='订单数量超过限制')
|
||||
|
||||
intakes = _load_intakes(session=session, intake_nos=intake_nos, lock=True, allow_consumed=True)
|
||||
if any(
|
||||
str(_order_extraction_snapshot(intake).get('request_id') or '') != request_id
|
||||
or str(_order_extraction_snapshot(intake).get('session_id') or '') != session.session_id
|
||||
for intake in intakes
|
||||
):
|
||||
db.session.rollback()
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONTEXT_INVALID',
|
||||
message='订单识别请求已被更新请求替代,请重新读取上下文',
|
||||
)
|
||||
documents = _load_documents(intakes, lock=True)
|
||||
current_snapshot = _snapshot_hash(intakes, documents)
|
||||
supplied_snapshot = str(payload.get('input_snapshot_hash') or '').strip().lower()
|
||||
if not supplied_snapshot or supplied_snapshot != current_snapshot:
|
||||
raise ConflictError(code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED', message='邮件或附件内容已变化,请重新解析')
|
||||
replay_results = []
|
||||
intake_nos = [row.intake_no for row in intakes]
|
||||
replay_results: list[dict[str, Any]] = []
|
||||
for intake in intakes:
|
||||
structured = intake.structured_result_json if isinstance(intake.structured_result_json, dict) else {}
|
||||
submission = structured.get('order_extraction_submission')
|
||||
@@ -904,7 +306,11 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
snapshot_hash=current_snapshot,
|
||||
documents=owned_docs,
|
||||
actor_id=int(session.user_id),
|
||||
schema_version_id=schema_version_id,
|
||||
frozen_mail_context=(frozen_context_by_intake or {}).get(int(intake.id)),
|
||||
)
|
||||
if run_id is not None:
|
||||
dynamic['extraction'].run_id = int(run_id)
|
||||
summary = {**dynamic['header'], 'lines': dynamic['lines']}
|
||||
# Bill-to 是业务归属客户原文;简称只保存在 customer_matches 主数据快照中。
|
||||
if summary.get('bill_to_customer'):
|
||||
@@ -957,7 +363,8 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
candidate.primary_document_id = int(document.id)
|
||||
candidate.source_order_index = index
|
||||
candidate.order_extraction_id = int(dynamic['extraction'].id)
|
||||
candidate.extraction_source = 'dify_chatflow'
|
||||
candidate.order_extraction_run_id = int(run_id) if run_id is not None else None
|
||||
candidate.extraction_source = extraction_source
|
||||
candidate.classification_confidence = classification_confidence
|
||||
candidate.field_confidence_json = {}
|
||||
candidate.missing_fields_json = list(assessment['missing_required_fields']) + list(assessment['missing_process_fields'])
|
||||
@@ -1068,7 +475,7 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
if document_has_pending[int(document.id)] or has_unassigned_pending
|
||||
else 'completed'
|
||||
)
|
||||
document.order_extraction_source = 'dify_chatflow'
|
||||
document.order_extraction_source = extraction_source
|
||||
document.order_extraction_result_json = {
|
||||
'request_id': request_id,
|
||||
'candidate_keys': keys,
|
||||
@@ -1083,7 +490,7 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
stale = db.session.query(ShippingNoticeCandidate).filter(
|
||||
ShippingNoticeCandidate.intake_id == int(intake.id),
|
||||
ShippingNoticeCandidate.consumed_task_id.is_(None),
|
||||
ShippingNoticeCandidate.extraction_source == 'dify_chatflow',
|
||||
ShippingNoticeCandidate.extraction_source == extraction_source,
|
||||
)
|
||||
if active_keys:
|
||||
stale = stale.filter(ShippingNoticeCandidate.candidate_key.notin_(tuple(active_keys)))
|
||||
@@ -1173,8 +580,6 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
'pending_count': len(pending),
|
||||
'non_shipping_count': len(non_shipping),
|
||||
'created_with_missing_fields_count': created_with_missing_fields_count,
|
||||
# 兼容旧 Dify 节点;新节点应改读 created_count。
|
||||
'auto_created_count': created_count,
|
||||
'message': _build_submission_message(
|
||||
created_count=created_count,
|
||||
opened_existing_count=opened_existing_count,
|
||||
@@ -1183,7 +588,7 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
created_with_missing_fields_count=created_with_missing_fields_count,
|
||||
),
|
||||
}
|
||||
# [STEP 5] 保存 Tool 级幂等回放结果,防止 Dify 网络重试重复建单。
|
||||
# [STEP 5] 保存 Run 级幂等回放结果,防止 Worker 重试重复建单。
|
||||
for intake in intakes:
|
||||
structured = dict(intake.structured_result_json or {})
|
||||
structured['order_extraction_submission'] = {
|
||||
@@ -1196,3 +601,170 @@ def submit_order_extraction(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
flag_modified(intake, 'structured_result_json')
|
||||
db.session.commit()
|
||||
return result
|
||||
|
||||
|
||||
def submit_order_extraction_run_result(
|
||||
*,
|
||||
run: Any,
|
||||
orders: list[dict[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
将后台 Workflow 输出提交到既有 HXOPS 裁决与持久化核心。
|
||||
|
||||
Args:
|
||||
run: `ShippingOrderExtractionRun`;必须包含冻结用户、会话、Intake 和 Schema。
|
||||
orders: Workflow 输出的结构化订单数组;禁止包含 Provider 选择或用户身份。
|
||||
Returns:
|
||||
不含 Provider 配置或输入文档的安全业务摘要。
|
||||
|
||||
核心逻辑:先逐 Document 对照 Run 冻结正文,拒绝排队期间源数据变化;再使用 run_no
|
||||
作为服务端幂等请求号,最后按 Run 锁定 Schema 调用领域持久化核心。
|
||||
"""
|
||||
snapshot = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
|
||||
snapshot_intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
frozen_context_by_intake = {
|
||||
int(item['intake_id']): dict(item.get('deterministic_context') or {})
|
||||
for item in snapshot_intakes
|
||||
if isinstance(item, dict) and str(item.get('intake_id') or '').isdigit()
|
||||
}
|
||||
intake_nos = [str(item.get('intake_no') or '').strip().upper() for item in snapshot_intakes]
|
||||
intake_nos = [item for item in intake_nos if item]
|
||||
intakes = db.session.query(ShippingNoticeIntake).filter(
|
||||
ShippingNoticeIntake.user_id == int(run.user_id),
|
||||
ShippingNoticeIntake.intake_no.in_(intake_nos),
|
||||
).order_by(ShippingNoticeIntake.intake_no.asc()).all()
|
||||
if len(intakes) != len(intake_nos):
|
||||
raise NotFoundError(code='SHIPPING_NOTICE.INTAKE_NOT_FOUND', message='Run 输入 Intake 不完整')
|
||||
run_extractions = ShippingOrderExtraction.query.filter_by(run_id=int(run.id)).all()
|
||||
if run_extractions and all(
|
||||
extraction.status in {'accepted', 'needs_review'}
|
||||
for extraction in run_extractions
|
||||
):
|
||||
candidates = ShippingNoticeCandidate.query.filter_by(order_extraction_run_id=int(run.id)).all()
|
||||
consumed_task_ids = {
|
||||
int(candidate.consumed_task_id)
|
||||
for candidate in candidates
|
||||
if candidate.consumed_task_id is not None
|
||||
}
|
||||
task_nos = sorted({
|
||||
str(task.task_no)
|
||||
for task in ShippingTask.query.filter(ShippingTask.id.in_(consumed_task_ids)).all()
|
||||
}) if consumed_task_ids else []
|
||||
pending = [candidate for candidate in candidates if candidate.consumed_task_id is None]
|
||||
result = {
|
||||
'status': 'ok',
|
||||
'request_id': str(run.run_no),
|
||||
'batch_no': None,
|
||||
'created': [{'task_no': task_no} for task_no in task_nos],
|
||||
'opened_existing': [],
|
||||
'pending_orders': [{'candidate_no': item.candidate_no} for item in pending],
|
||||
'non_shipping_orders': [],
|
||||
'created_count': len(task_nos),
|
||||
'opened_existing_count': 0,
|
||||
'pending_count': len(pending),
|
||||
'non_shipping_count': 0,
|
||||
'created_with_missing_fields_count': 0,
|
||||
'idempotent_replay': True,
|
||||
'recovered_from_run_facts': True,
|
||||
}
|
||||
for intake in intakes:
|
||||
structured = dict(intake.structured_result_json or {})
|
||||
structured['order_extraction_submission'] = {
|
||||
'input_snapshot_hash': run.input_snapshot_hash,
|
||||
'request_id': str(run.run_no),
|
||||
'result': result,
|
||||
'submitted_at': datetime.utcnow().isoformat(),
|
||||
}
|
||||
intake.structured_result_json = structured
|
||||
flag_modified(intake, 'structured_result_json')
|
||||
db.session.commit()
|
||||
return result
|
||||
cached_orders = (
|
||||
run.provider_result_json.get('orders')
|
||||
if isinstance(run.provider_result_json, dict)
|
||||
else None
|
||||
)
|
||||
if (
|
||||
not run_extractions
|
||||
and isinstance(cached_orders, list)
|
||||
and not cached_orders
|
||||
and all(intake.parse_status == 'consumed' for intake in intakes)
|
||||
):
|
||||
result = {
|
||||
'status': 'ok',
|
||||
'request_id': str(run.run_no),
|
||||
'batch_no': None,
|
||||
'created': [],
|
||||
'opened_existing': [],
|
||||
'pending_orders': [],
|
||||
'non_shipping_orders': [],
|
||||
'created_count': 0,
|
||||
'opened_existing_count': 0,
|
||||
'pending_count': 0,
|
||||
'non_shipping_count': 0,
|
||||
'created_with_missing_fields_count': 0,
|
||||
'idempotent_replay': True,
|
||||
'recovered_from_consumed_empty_result': True,
|
||||
}
|
||||
for intake in intakes:
|
||||
structured = dict(intake.structured_result_json or {})
|
||||
structured['order_extraction_submission'] = {
|
||||
'input_snapshot_hash': run.input_snapshot_hash,
|
||||
'request_id': str(run.run_no),
|
||||
'result': result,
|
||||
'submitted_at': datetime.utcnow().isoformat(),
|
||||
}
|
||||
intake.structured_result_json = structured
|
||||
flag_modified(intake, 'structured_result_json')
|
||||
db.session.commit()
|
||||
return result
|
||||
is_replay = all(
|
||||
str(_order_extraction_submission(intake).get('request_id') or '') == str(run.run_no)
|
||||
for intake in intakes
|
||||
)
|
||||
session = db.session.query(ChatSession).filter_by(session_id=run.conversation_id).one()
|
||||
current_intakes = _load_intakes(
|
||||
session=session,
|
||||
intake_nos=intake_nos,
|
||||
lock=True,
|
||||
allow_consumed=is_replay,
|
||||
)
|
||||
current_documents = _load_documents(current_intakes, lock=True)
|
||||
current_intake_by_id = {int(item.id): item for item in current_intakes}
|
||||
current_document_by_id = {int(item.id): item for item in current_documents}
|
||||
for intake_snapshot in snapshot_intakes:
|
||||
if not isinstance(intake_snapshot, dict):
|
||||
continue
|
||||
intake = current_intake_by_id.get(int(intake_snapshot.get('intake_id') or 0))
|
||||
frozen_context = dict(intake_snapshot.get('deterministic_context') or {})
|
||||
if intake is None or canonical_mail_context(intake) != frozen_context:
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED',
|
||||
message='Run 冻结后的邮件上下文已变化',
|
||||
)
|
||||
for frozen in intake_snapshot.get('documents') or []:
|
||||
if not isinstance(frozen, dict):
|
||||
continue
|
||||
document = current_document_by_id.get(int(frozen.get('document_id') or 0))
|
||||
if (
|
||||
document is None
|
||||
or int(document.intake_id) != int(intake.id)
|
||||
or str(document.content_hash or '') != str(frozen.get('content_hash') or '')
|
||||
or str(document.extracted_text or '') != str(frozen.get('extracted_text') or '')
|
||||
):
|
||||
raise ConflictError(
|
||||
code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED',
|
||||
message='Run 冻结后的邮件或附件内容已变化',
|
||||
)
|
||||
return persist_order_extraction_result(
|
||||
session=session,
|
||||
intakes=current_intakes,
|
||||
documents=current_documents,
|
||||
current_snapshot=str(run.input_snapshot_hash),
|
||||
request_id=str(run.run_no),
|
||||
orders=orders,
|
||||
run_id=int(run.id),
|
||||
schema_version_id=int(run.schema_version_id),
|
||||
extraction_source='dify_workflow',
|
||||
frozen_context_by_intake=frozen_context_by_intake,
|
||||
)
|
||||
@@ -0,0 +1,677 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_extraction_run_service.py
|
||||
|
||||
用途:创建、查询和序列化建单前订单抽取领域 Run。
|
||||
依赖:Agent/ChatSession、ShippingNoticeIntake/Document、已发布订单 Schema、SQLAlchemy 事务。
|
||||
逻辑:服务端校验用户与会话权限,冻结 Intake/Document/Schema 输入,并以数据库唯一约束保证幂等与单 Intake 单活跃 Run。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ForbiddenError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
Agent,
|
||||
ChatSession,
|
||||
FileAsset,
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtractionRun,
|
||||
ShippingOrderExtractionRunIntake,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema.runtime import dify_contract, published_version
|
||||
|
||||
RUN_TRANSITIONS: dict[str, set[str]] = {
|
||||
'queued': {'running', 'cancelled'},
|
||||
'running': {'queued', 'result_persisted', 'failed', 'cancelled'},
|
||||
'result_persisted': {'completed', 'needs_review'},
|
||||
'completed': set(),
|
||||
'needs_review': set(),
|
||||
'failed': {'queued', 'cancelled'},
|
||||
'cancelled': set(),
|
||||
}
|
||||
|
||||
|
||||
def _canonical_json(payload: Any) -> str:
|
||||
"""生成稳定 JSON,用于快照哈希和幂等键;禁止依赖浏览器随机请求标识。"""
|
||||
return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(',', ':'), default=str)
|
||||
|
||||
|
||||
def _sha256(payload: Any) -> str:
|
||||
"""返回业务输入的 SHA-256;输入必须先经过稳定 JSON 编码。"""
|
||||
return hashlib.sha256(_canonical_json(payload).encode('ascii')).hexdigest()
|
||||
|
||||
|
||||
def _run_no() -> str:
|
||||
"""生成用户可见 Run 编号;数据库唯一约束负责极小概率碰撞兜底。"""
|
||||
return f"SNER-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
|
||||
|
||||
|
||||
def _require_owner_agent(*, user: User, agent_id: int) -> Agent:
|
||||
"""校验订单抽取归属的货代入口 Agent,并阻断无权限或停用应用。"""
|
||||
agent = db.session.get(Agent, agent_id)
|
||||
if agent is None:
|
||||
raise NotFoundError('Agent not found', code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_NOT_FOUND')
|
||||
if agent.agent_code != 'shipping_notice' or not agent.is_active:
|
||||
raise ValidationError(
|
||||
'agent_id must reference an active shipping notice agent',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_INVALID',
|
||||
)
|
||||
if str(user.role or '').lower() != 'admin' and agent not in user.agents:
|
||||
raise ForbiddenError(
|
||||
'Permission denied for this agent',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_AGENT_FORBIDDEN',
|
||||
)
|
||||
return agent
|
||||
|
||||
|
||||
def _require_conversation(*, user_id: int, agent_id: int, conversation_id: str) -> ChatSession:
|
||||
"""确认会话属于当前用户和货代入口 Agent,防止跨会话冻结附件。"""
|
||||
session = db.session.query(ChatSession).filter_by(
|
||||
session_id=conversation_id,
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
).first()
|
||||
if session is None:
|
||||
raise NotFoundError(
|
||||
'Shipping notice conversation not found',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONVERSATION_NOT_FOUND',
|
||||
)
|
||||
return session
|
||||
|
||||
|
||||
def _load_intakes(*, user_id: int, intake_nos: list[str]) -> list[ShippingNoticeIntake]:
|
||||
"""按稳定编号加载并锁定 Intake;先校验业务资格,会话归属由后续事务步骤统一处理。"""
|
||||
normalized = sorted({str(value or '').strip().upper() for value in intake_nos if str(value or '').strip()})
|
||||
if not normalized or len(normalized) > 50:
|
||||
raise ValidationError(
|
||||
'intake_nos must contain 1 to 50 values',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_INTAKES_INVALID',
|
||||
)
|
||||
rows = (
|
||||
db.session.query(ShippingNoticeIntake)
|
||||
.filter(ShippingNoticeIntake.intake_no.in_(normalized), ShippingNoticeIntake.user_id == user_id)
|
||||
.order_by(ShippingNoticeIntake.intake_no.asc())
|
||||
.with_for_update()
|
||||
.all()
|
||||
)
|
||||
if len(rows) != len(normalized):
|
||||
raise NotFoundError('Shipping notice intake not found', code='SHIPPING_NOTICE.INTAKE_NOT_FOUND')
|
||||
now = datetime.utcnow()
|
||||
for intake in rows:
|
||||
if intake.consumed_at is not None or intake.consumed_batch_id is not None or intake.consumed_task_id is not None:
|
||||
raise ConflictError('Shipping notice intake was consumed', code='SHIPPING_NOTICE.INTAKE_ALREADY_CONSUMED')
|
||||
if intake.parse_status == 'cancelled':
|
||||
raise ConflictError('Shipping notice intake was cancelled', code='SHIPPING_NOTICE.INTAKE_INVALID_STATUS')
|
||||
if intake.expires_at is not None and intake.expires_at <= now:
|
||||
raise ConflictError('Shipping notice intake expired', code='SHIPPING_NOTICE.INTAKE_EXPIRED')
|
||||
if intake.parse_status != 'parsed':
|
||||
raise ConflictError(
|
||||
'Shipping notice intake is not parsed',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PENDING',
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def _resolve_conversation(
|
||||
*,
|
||||
user_id: int,
|
||||
agent_id: int,
|
||||
conversation_id: str,
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
) -> ChatSession:
|
||||
"""
|
||||
解析或创建订单抽取所属本地会话,并把未绑定的 Intake 原子归属到该会话。
|
||||
|
||||
Args:
|
||||
user_id/agent_id: 当前用户和货代入口 Agent;用于隔离会话。
|
||||
conversation_id: 前端已知的本地 session_id;空值表示首次后台 Run 可创建会话。
|
||||
intakes: 已按用户锁定且通过业务资格校验的 Intake。
|
||||
Returns:
|
||||
已存在或本事务新建的 ChatSession;调用方负责最终提交。
|
||||
Raises:
|
||||
ConflictError: 所选 Intake 已分属不同会话,或与显式会话不一致。
|
||||
"""
|
||||
requested = str(conversation_id or '').strip()
|
||||
bound_ids = {str(row.conversation_id or '').strip() for row in intakes if str(row.conversation_id or '').strip()}
|
||||
if len(bound_ids) > 1:
|
||||
raise ConflictError(
|
||||
'Selected shipping notice intakes belong to different conversations',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONVERSATION_MISMATCH',
|
||||
)
|
||||
if requested and bound_ids and bound_ids != {requested}:
|
||||
raise ConflictError(
|
||||
'Shipping notice intake belongs to another conversation',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONVERSATION_MISMATCH',
|
||||
)
|
||||
|
||||
resolved = requested or next(iter(bound_ids), '')
|
||||
if resolved:
|
||||
session = _require_conversation(user_id=user_id, agent_id=agent_id, conversation_id=resolved)
|
||||
else:
|
||||
session = ChatSession(
|
||||
session_id=uuid.uuid4().hex,
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
title='订单抽取',
|
||||
status='running',
|
||||
created_at=datetime.utcnow(),
|
||||
updated_at=datetime.utcnow(),
|
||||
last_active_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(session)
|
||||
db.session.flush()
|
||||
resolved = session.session_id
|
||||
|
||||
for intake in intakes:
|
||||
current = str(intake.conversation_id or '').strip()
|
||||
if current and current != resolved:
|
||||
raise ConflictError(
|
||||
'Shipping notice intake belongs to another conversation',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_CONVERSATION_MISMATCH',
|
||||
)
|
||||
if not current:
|
||||
intake.conversation_id = resolved
|
||||
return session
|
||||
|
||||
|
||||
def _build_snapshot(
|
||||
*,
|
||||
user_id: int,
|
||||
owner_agent_id: int,
|
||||
conversation_id: str,
|
||||
intakes: list[ShippingNoticeIntake],
|
||||
schema_version: ShippingOrderSchemaVersion,
|
||||
) -> dict[str, Any]:
|
||||
"""冻结 Worker 所需的完整输入;保存文档正文,后续执行不再回读可变 Document。"""
|
||||
intake_ids = [intake.id for intake in intakes]
|
||||
documents = (
|
||||
db.session.query(ShippingNoticeDocument)
|
||||
.filter(ShippingNoticeDocument.intake_id.in_(intake_ids))
|
||||
.order_by(ShippingNoticeDocument.intake_id.asc(), ShippingNoticeDocument.id.asc())
|
||||
.all()
|
||||
)
|
||||
asset_ids = {intake.asset_id for intake in intakes}
|
||||
asset_ids.update(document.asset_id for document in documents if document.asset_id is not None)
|
||||
assets = {
|
||||
asset.id: asset
|
||||
for asset in db.session.query(FileAsset).filter(FileAsset.id.in_(asset_ids)).all()
|
||||
} if asset_ids else {}
|
||||
documents_by_intake: dict[int, list[dict[str, Any]]] = {intake.id: [] for intake in intakes}
|
||||
for document in documents:
|
||||
asset = assets.get(document.asset_id) if document.asset_id is not None else None
|
||||
documents_by_intake[document.intake_id].append({
|
||||
'document_id': document.id,
|
||||
'document_type': document.document_type,
|
||||
'attachment_key': document.attachment_key,
|
||||
'filename': document.filename,
|
||||
'content_hash': document.content_hash,
|
||||
'asset_no': asset.asset_no if asset else None,
|
||||
'asset_content_hash': asset.content_hash if asset else None,
|
||||
'classification': document.classification,
|
||||
'parse_status': document.parse_status,
|
||||
'extracted_text': document.extracted_text or '',
|
||||
'parse_warnings': document.parse_warnings_json or [],
|
||||
})
|
||||
incomplete = [
|
||||
intake.intake_no
|
||||
for intake in intakes
|
||||
if not any(
|
||||
item['parse_status'] == 'parsed' and bool(str(item['extracted_text'] or '').strip())
|
||||
for item in documents_by_intake[intake.id]
|
||||
)
|
||||
]
|
||||
if incomplete:
|
||||
raise ConflictError(
|
||||
'Shipping notice documents are incomplete',
|
||||
code='SHIPPING_NOTICE.INTAKE_ATTACHMENTS_INCOMPLETE',
|
||||
details={'intake_nos': incomplete},
|
||||
)
|
||||
return {
|
||||
'snapshot_version': 1,
|
||||
'user_id': user_id,
|
||||
'owner_agent_id': owner_agent_id,
|
||||
'conversation_id': conversation_id,
|
||||
'schema': {
|
||||
'schema_version_id': schema_version.id,
|
||||
'version': schema_version.version,
|
||||
'checksum': schema_version.checksum,
|
||||
'extraction_contract': dify_contract(schema_version),
|
||||
'definition': schema_version.definition_json,
|
||||
},
|
||||
'intakes': [
|
||||
{
|
||||
'intake_id': intake.id,
|
||||
'intake_no': intake.intake_no,
|
||||
'asset_no': assets[intake.asset_id].asset_no if intake.asset_id in assets else None,
|
||||
'asset_content_hash': assets[intake.asset_id].content_hash if intake.asset_id in assets else None,
|
||||
'parser_version': intake.parser_version,
|
||||
'extracted_text': intake.extracted_text or '',
|
||||
'documents': documents_by_intake[intake.id],
|
||||
}
|
||||
for intake in intakes
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _active_run_for_intakes(intake_ids: list[int]) -> ShippingOrderExtractionRun | None:
|
||||
"""读取占用任一 Intake 的未释放 Run,供并发唯一约束冲突后返回明确业务结果。"""
|
||||
return (
|
||||
db.session.query(ShippingOrderExtractionRun)
|
||||
.join(ShippingOrderExtractionRunIntake)
|
||||
.filter(
|
||||
ShippingOrderExtractionRunIntake.intake_id.in_(intake_ids),
|
||||
ShippingOrderExtractionRunIntake.released_at.is_(None),
|
||||
)
|
||||
.order_by(ShippingOrderExtractionRun.created_at.desc())
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _run_by_idempotency_key(idempotency_key: str) -> ShippingOrderExtractionRun | None:
|
||||
"""按服务端幂等键读取赢家 Run;独立函数便于验证并发唯一约束回落路径。"""
|
||||
return ShippingOrderExtractionRun.query.filter_by(idempotency_key=idempotency_key).first()
|
||||
|
||||
|
||||
def create_order_extraction_run(
|
||||
*,
|
||||
user: User,
|
||||
agent_id: int,
|
||||
conversation_id: str,
|
||||
intake_nos: list[str],
|
||||
) -> tuple[ShippingOrderExtractionRun, bool]:
|
||||
"""
|
||||
创建订单抽取 Run;相同服务器快照幂等复用,不同输入抢占同一 Intake 时返回冲突。
|
||||
|
||||
Args:
|
||||
user: 当前认证用户;管理员可使用任意启用货代 Agent,普通用户必须拥有 Agent 权限。
|
||||
agent_id: 用户入口货代 Agent 主键,不是后台 Provider ID。
|
||||
conversation_id: HXOPS ChatSession.session_id;首次后台 Run 可为空,由服务端创建并绑定 Intake。
|
||||
intake_nos: 1-50 个已解析且未消费的 Intake 编号。
|
||||
Returns:
|
||||
`(run, reused)`;Run 与通用 Job 在同一事务创建。
|
||||
"""
|
||||
owner_agent = _require_owner_agent(user=user, agent_id=agent_id)
|
||||
intakes = _load_intakes(user_id=user.id, intake_nos=intake_nos)
|
||||
from app.services.agent_runtime_binding_service import resolve_runtime_binding
|
||||
|
||||
binding = resolve_runtime_binding(
|
||||
owner_agent_id=owner_agent.id,
|
||||
capability_code='shipping.order_extraction',
|
||||
)
|
||||
schema_version = published_version()
|
||||
session = _resolve_conversation(
|
||||
user_id=user.id,
|
||||
agent_id=owner_agent.id,
|
||||
conversation_id=conversation_id,
|
||||
intakes=intakes,
|
||||
)
|
||||
conversation_id = session.session_id
|
||||
snapshot = _build_snapshot(
|
||||
user_id=user.id,
|
||||
owner_agent_id=owner_agent.id,
|
||||
conversation_id=conversation_id,
|
||||
intakes=intakes,
|
||||
schema_version=schema_version,
|
||||
)
|
||||
snapshot_hash = _sha256(snapshot)
|
||||
idempotency_key = _sha256({
|
||||
'user_id': user.id,
|
||||
'owner_agent_id': owner_agent.id,
|
||||
'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_json or {},
|
||||
})
|
||||
existing = _run_by_idempotency_key(idempotency_key)
|
||||
if existing is not None:
|
||||
return existing, True
|
||||
active = _active_run_for_intakes([intake.id for intake in intakes])
|
||||
if active is not None:
|
||||
raise ConflictError(
|
||||
'A selected intake already belongs to another active extraction run',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_ACTIVE',
|
||||
details={'run_no': active.run_no},
|
||||
)
|
||||
|
||||
run = ShippingOrderExtractionRun(
|
||||
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,
|
||||
provider_config_json=dict(binding.config_json or {}),
|
||||
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,
|
||||
},
|
||||
conversation_id=conversation_id,
|
||||
schema_version_id=schema_version.id,
|
||||
input_snapshot_hash=snapshot_hash,
|
||||
input_snapshot_json=snapshot,
|
||||
idempotency_key=idempotency_key,
|
||||
status='queued',
|
||||
phase='queued',
|
||||
)
|
||||
try:
|
||||
with db.session.begin_nested():
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingOrderExtractionRunIntake(run_id=run.id, intake_id=intake.id, position=index)
|
||||
for index, intake in enumerate(intakes)
|
||||
])
|
||||
db.session.flush()
|
||||
from app.jobs.queue import enqueue
|
||||
from app.jobs.types import JobType
|
||||
|
||||
job_id = enqueue(
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
{'run_no': run.run_no},
|
||||
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),
|
||||
message='订单抽取等待后台处理',
|
||||
commit=False,
|
||||
)
|
||||
run.current_job_id = job_id
|
||||
for intake in intakes:
|
||||
intake.order_extraction_status = 'extracting'
|
||||
intake.order_extraction_error_code = None
|
||||
intake.order_extraction_error_message = None
|
||||
db.session.flush()
|
||||
except IntegrityError:
|
||||
existing = _run_by_idempotency_key(idempotency_key)
|
||||
if existing is not None:
|
||||
return existing, True
|
||||
active = _active_run_for_intakes([intake.id for intake in intakes])
|
||||
if active is not None:
|
||||
raise ConflictError(
|
||||
'A selected intake already belongs to another active extraction run',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_ACTIVE',
|
||||
details={'run_no': active.run_no},
|
||||
)
|
||||
raise
|
||||
return run, False
|
||||
|
||||
|
||||
def get_order_extraction_run(*, user_id: int, run_no: str) -> ShippingOrderExtractionRun:
|
||||
"""按用户与 Run 编号查询;跨用户访问统一表现为不存在。"""
|
||||
run = ShippingOrderExtractionRun.query.filter_by(user_id=user_id, run_no=run_no).first()
|
||||
if run is None:
|
||||
raise NotFoundError(
|
||||
'Shipping order extraction run not found',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_NOT_FOUND',
|
||||
)
|
||||
return run
|
||||
|
||||
|
||||
def list_order_extraction_runs(
|
||||
*, user_id: int, conversation_id: str | None = None, limit: int = 50,
|
||||
) -> list[ShippingOrderExtractionRun]:
|
||||
"""列出当前用户 Run;可按会话过滤,最多返回 100 条。"""
|
||||
query = ShippingOrderExtractionRun.query.filter_by(user_id=user_id)
|
||||
if conversation_id:
|
||||
query = query.filter_by(conversation_id=conversation_id)
|
||||
return query.order_by(ShippingOrderExtractionRun.created_at.desc()).limit(min(max(limit, 1), 100)).all()
|
||||
|
||||
|
||||
def serialize_order_extraction_run(run: ShippingOrderExtractionRun) -> dict[str, Any]:
|
||||
"""输出用户态 Run 摘要;不返回冻结正文、幂等键或未来 Provider 凭据。"""
|
||||
intake_snapshot = run.input_snapshot_json.get('intakes', []) if isinstance(run.input_snapshot_json, dict) else []
|
||||
schema_snapshot = run.input_snapshot_json.get('schema', {}) if isinstance(run.input_snapshot_json, dict) else {}
|
||||
return {
|
||||
'run_no': run.run_no,
|
||||
'agent_id': run.owner_agent_id,
|
||||
'conversation_id': run.conversation_id,
|
||||
'status': run.status,
|
||||
'phase': run.phase,
|
||||
'intake_nos': [item.get('intake_no') for item in intake_snapshot if item.get('intake_no')],
|
||||
'schema_version_id': run.schema_version_id,
|
||||
'schema_version': schema_snapshot.get('version'),
|
||||
'schema_checksum': schema_snapshot.get('checksum'),
|
||||
'attempt_count': int(run.attempt_count or 0),
|
||||
'result': run.result_json,
|
||||
'error': (
|
||||
{'code': run.error_code, 'message': run.error_message}
|
||||
if run.error_code or run.error_message else None
|
||||
),
|
||||
'created_at': run.created_at.isoformat() + 'Z' if run.created_at else None,
|
||||
'updated_at': run.updated_at.isoformat() + 'Z' if run.updated_at else None,
|
||||
'started_at': run.started_at.isoformat() + 'Z' if run.started_at else None,
|
||||
'finished_at': run.finished_at.isoformat() + 'Z' if run.finished_at else None,
|
||||
}
|
||||
|
||||
|
||||
def transition_order_extraction_run(
|
||||
run: ShippingOrderExtractionRun,
|
||||
*,
|
||||
target_status: str,
|
||||
phase: str | None = None,
|
||||
result: dict[str, Any] | None = None,
|
||||
error_code: str | None = None,
|
||||
error_message: str | None = None,
|
||||
) -> ShippingOrderExtractionRun:
|
||||
"""
|
||||
单调推进 Run 业务状态,供阶段 2 Worker 唯一调用。
|
||||
|
||||
Args:
|
||||
run: 已加载且由调用方持有事务锁的 Run。
|
||||
target_status: 必须是当前状态允许的下一状态;`result_persisted` 后禁止回退失败或取消。
|
||||
phase: 可选细分阶段;不改变领域状态机语义。
|
||||
result: 仅 `result_persisted/completed/needs_review` 可写的安全业务摘要。
|
||||
error_code/error_message: 仅 failed 状态可写;不得包含凭据或文档全文。
|
||||
Returns:
|
||||
已更新但尚未提交的 Run。
|
||||
"""
|
||||
current_status = str(run.status or '')
|
||||
if target_status not in RUN_TRANSITIONS.get(current_status, set()):
|
||||
raise ConflictError(
|
||||
f'Invalid order extraction run transition: {current_status} -> {target_status}',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_RUN_TRANSITION_INVALID',
|
||||
)
|
||||
now = datetime.utcnow()
|
||||
run.status = target_status
|
||||
run.phase = phase or target_status
|
||||
run.lock_version = int(run.lock_version or 0) + 1
|
||||
if target_status == 'running' and run.started_at is None:
|
||||
run.started_at = now
|
||||
intake_ids = [member.intake_id for member in run.intakes]
|
||||
intake_rows = (
|
||||
db.session.query(ShippingNoticeIntake).filter(ShippingNoticeIntake.id.in_(intake_ids)).all()
|
||||
if intake_ids else []
|
||||
)
|
||||
if target_status == 'queued':
|
||||
run.finished_at = None
|
||||
run.error_code = None
|
||||
run.error_message = None
|
||||
for member in run.intakes:
|
||||
member.released_at = None
|
||||
for intake in intake_rows:
|
||||
intake.order_extraction_status = 'extracting'
|
||||
intake.order_extraction_error_code = None
|
||||
intake.order_extraction_error_message = None
|
||||
elif target_status == 'running':
|
||||
for intake in intake_rows:
|
||||
intake.order_extraction_status = 'extracting'
|
||||
intake.order_extraction_error_code = None
|
||||
intake.order_extraction_error_message = None
|
||||
if target_status == 'result_persisted':
|
||||
run.result_persisted_at = now
|
||||
run.result_json = result or {}
|
||||
run.error_code = None
|
||||
run.error_message = None
|
||||
elif target_status in {'completed', 'needs_review'}:
|
||||
if result is not None:
|
||||
run.result_json = result
|
||||
run.finished_at = now
|
||||
elif target_status == 'failed':
|
||||
run.error_code = str(error_code or 'SHIPPING_NOTICE.ORDER_EXTRACTION_FAILED')[:64]
|
||||
run.error_message = str(error_message or 'Order extraction failed')[:2000]
|
||||
run.finished_at = now
|
||||
for intake in intake_rows:
|
||||
if str(intake.order_extraction_status or '') not in {'completed', 'partially_completed'}:
|
||||
intake.order_extraction_status = 'failed'
|
||||
intake.order_extraction_error_code = run.error_code
|
||||
intake.order_extraction_error_message = run.error_message
|
||||
elif target_status == 'cancelled':
|
||||
run.finished_at = now
|
||||
for intake in intake_rows:
|
||||
if str(intake.order_extraction_status or '') not in {'completed', 'partially_completed'}:
|
||||
intake.order_extraction_status = 'failed'
|
||||
intake.order_extraction_error_code = 'SHIPPING_NOTICE.ORDER_EXTRACTION_CANCELLED'
|
||||
intake.order_extraction_error_message = 'Order extraction was cancelled'
|
||||
if target_status in {'completed', 'needs_review', 'failed', 'cancelled'}:
|
||||
for member in run.intakes:
|
||||
member.released_at = now
|
||||
return run
|
||||
|
||||
|
||||
def sync_order_extraction_run_after_job_recovery(job: Any) -> None:
|
||||
"""
|
||||
通用 Job 超时回收后同步领域 Run,避免 Job 已 queued/failed 而 Run 永久 running。
|
||||
|
||||
Args:
|
||||
job: 已由 `recover_stale_jobs` 条件更新成功并刷新的 Job。
|
||||
"""
|
||||
run = ShippingOrderExtractionRun.query.filter_by(run_no=str(job.business_ref or '')).with_for_update().first()
|
||||
if run is None or run.status in {'result_persisted', 'completed', 'needs_review', 'cancelled'}:
|
||||
return
|
||||
if job.status == 'queued' and run.status == 'running':
|
||||
transition_order_extraction_run(run, target_status='queued', phase='timeout_retry_queued')
|
||||
elif job.status in {'failed', 'dead', 'cancelled'} and run.status in {'queued', 'running'}:
|
||||
if run.status == 'queued':
|
||||
transition_order_extraction_run(run, target_status='running', phase='timeout_failing')
|
||||
transition_order_extraction_run(
|
||||
run,
|
||||
target_status='failed',
|
||||
error_code='SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT',
|
||||
error_message=str(job.error_message or '订单抽取后台任务执行超时'),
|
||||
)
|
||||
|
||||
def _latency_summary(values: list[int]) -> dict[str, int | None]:
|
||||
"""汇总毫秒耗时样本;空集合返回空指标,避免监控端猜测零耗时。"""
|
||||
if not values:
|
||||
return {'count': 0, 'avg_ms': None, 'p95_ms': None, 'max_ms': None}
|
||||
ordered = sorted(max(0, int(value)) for value in values)
|
||||
p95_index = max(0, min(len(ordered) - 1, ((len(ordered) * 95 + 99) // 100) - 1))
|
||||
return {
|
||||
'count': len(ordered),
|
||||
'avg_ms': int(sum(ordered) / len(ordered)),
|
||||
'p95_ms': ordered[p95_index],
|
||||
'max_ms': ordered[-1],
|
||||
}
|
||||
|
||||
|
||||
def get_order_extraction_run_health(
|
||||
*,
|
||||
window_hours: int = 24,
|
||||
queued_stale_seconds: int = 300,
|
||||
running_stale_seconds: int = 1800,
|
||||
now: datetime | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
汇总订单抽取 Run 的积压、失败和分段时延,供管理员运维查询。
|
||||
|
||||
Args:
|
||||
window_hours: 终态统计窗口,限制为 1-168 小时;活动 Run 不受窗口过滤。
|
||||
queued_stale_seconds: queued 超过该秒数记为积压,限制为 30-86400。
|
||||
running_stale_seconds: running/result_persisted 超过该秒数记为卡住,限制为 60-86400。
|
||||
now: 测试可注入的 UTC 当前时间;生产调用留空。
|
||||
Returns:
|
||||
仅含聚合指标和最多 20 个异常 Run 编号的安全视图,不含输入、Provider 或错误正文。
|
||||
"""
|
||||
current = now or datetime.utcnow()
|
||||
hours = min(max(int(window_hours or 24), 1), 168)
|
||||
queued_threshold = min(max(int(queued_stale_seconds or 300), 30), 86400)
|
||||
running_threshold = min(max(int(running_stale_seconds or 1800), 60), 86400)
|
||||
since = current - timedelta(hours=hours)
|
||||
active_statuses = {'queued', 'running', 'result_persisted'}
|
||||
rows = (
|
||||
ShippingOrderExtractionRun.query
|
||||
.filter(
|
||||
or_(
|
||||
ShippingOrderExtractionRun.status.in_(active_statuses),
|
||||
ShippingOrderExtractionRun.created_at >= since,
|
||||
)
|
||||
)
|
||||
.order_by(ShippingOrderExtractionRun.created_at.asc())
|
||||
.all()
|
||||
)
|
||||
status_counts = Counter(str(row.status or 'unknown') for row in rows)
|
||||
phase_counts = Counter(str(row.phase or 'unknown') for row in rows)
|
||||
terminal_rows = [row for row in rows if row.status not in active_statuses and row.finished_at]
|
||||
failed_rows = [row for row in terminal_rows if row.status in {'failed', 'cancelled'}]
|
||||
stale_rows: list[ShippingOrderExtractionRun] = []
|
||||
for row in rows:
|
||||
age_seconds = max(0, int((current - (row.started_at or row.created_at)).total_seconds()))
|
||||
if row.status == 'queued' and age_seconds >= queued_threshold:
|
||||
stale_rows.append(row)
|
||||
elif row.status in {'running', 'result_persisted'} and age_seconds >= running_threshold:
|
||||
stale_rows.append(row)
|
||||
|
||||
def elapsed_ms(start: datetime | None, end: datetime | None) -> int | None:
|
||||
if start is None or end is None or end < start:
|
||||
return None
|
||||
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]
|
||||
persistence_ms = [
|
||||
value for row in rows
|
||||
if (value := elapsed_ms(row.provider_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)
|
||||
failure_rate = round(len(failed_rows) / terminal_count, 4) if terminal_count else 0.0
|
||||
health_status = 'degraded' if stale_rows or (terminal_count >= 5 and failure_rate >= 0.2) else 'healthy'
|
||||
return {
|
||||
'generated_at': current.isoformat() + 'Z',
|
||||
'health_status': health_status,
|
||||
'window_hours': hours,
|
||||
'thresholds': {
|
||||
'queued_stale_seconds': queued_threshold,
|
||||
'running_stale_seconds': running_threshold,
|
||||
'failure_rate_degraded': 0.2,
|
||||
'failure_rate_min_terminal_runs': 5,
|
||||
},
|
||||
'counts': {
|
||||
'total_observed': len(rows),
|
||||
'active': sum(status_counts.get(item, 0) for item in active_statuses),
|
||||
'terminal': terminal_count,
|
||||
'failed': len(failed_rows),
|
||||
'retried': sum(1 for row in rows if int(row.attempt_count or 0) > 1),
|
||||
'stale': len(stale_rows),
|
||||
},
|
||||
'status_counts': dict(sorted(status_counts.items())),
|
||||
'phase_counts': dict(sorted(phase_counts.items())),
|
||||
'error_code_counts': dict(sorted(Counter(str(row.error_code or 'UNKNOWN') for row in failed_rows).items())),
|
||||
'failure_rate': failure_rate,
|
||||
'latency': {
|
||||
'queue': _latency_summary(queue_ms),
|
||||
'provider': _latency_summary(provider_ms),
|
||||
'hxops_persistence': _latency_summary(persistence_ms),
|
||||
'total': _latency_summary(total_ms),
|
||||
},
|
||||
# 仅暴露异常 Run 编号,最多 20 条,避免泄露输入/Provider/错误正文。
|
||||
'stale_run_nos': [str(row.run_no) for row in stale_rows[:20]],
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_extraction_workflow.py
|
||||
|
||||
用途:把订单抽取 Run 冻结快照编译为 Dify Workflow inputs,并校验结构化 outputs。
|
||||
依赖:DifyService、context_fields.dify_exposure、ShippingOrderExtractionRun、统一错误类型。
|
||||
逻辑:Provider 只接收字符串化抽取契约、文档及受控只读上下文;输出必须是成功 Workflow 中的 orders 数组。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
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
|
||||
|
||||
|
||||
def build_order_extraction_workflow_inputs(run: Any) -> dict[str, str]:
|
||||
"""从 Run 不可变快照构建 Dify Start 输入;确定性字段只能进入独立只读上下文。"""
|
||||
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 {}
|
||||
)
|
||||
intakes = snapshot.get('intakes') if isinstance(snapshot.get('intakes'), list) else []
|
||||
# 确定性上下文必须从 documents 剥离,避免绕过版本级暴露策略。
|
||||
dify_intakes = [
|
||||
{key: value for key, value in intake.items() if key != 'deterministic_context'}
|
||||
for intake in intakes if isinstance(intake, dict)
|
||||
]
|
||||
return {
|
||||
'run_no': str(run.run_no),
|
||||
'input_snapshot_hash': str(run.input_snapshot_hash),
|
||||
'schema_contract': json.dumps(schema, ensure_ascii=False, separators=(',', ':')),
|
||||
'documents': json.dumps(dify_intakes, ensure_ascii=False, separators=(',', ':')),
|
||||
'readonly_context': json.dumps(
|
||||
compile_readonly_context(snapshot), ensure_ascii=False, separators=(',', ':'),
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def parse_order_extraction_workflow_result(result: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"""校验 Dify Workflow 终态与 orders 输出;禁止从自由文本猜测 JSON。"""
|
||||
if not isinstance(result, dict):
|
||||
raise ServiceUnavailableError(
|
||||
'Dify Workflow returned no structured result',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
status = str(result.get('status') or '').strip().lower()
|
||||
if status not in {'succeeded', 'success'}:
|
||||
raise ServiceUnavailableError(
|
||||
str(result.get('error') or 'Dify Workflow failed')[:1000],
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_FAILED',
|
||||
)
|
||||
outputs = result.get('outputs') if isinstance(result.get('outputs'), dict) else {}
|
||||
raw = outputs.get('orders')
|
||||
if raw is None:
|
||||
raw = outputs.get('order_extraction_result')
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
raw = json.loads(raw)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValidationError(
|
||||
'Workflow orders output must be valid JSON',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
) from exc
|
||||
if isinstance(raw, dict) and isinstance(raw.get('orders'), list):
|
||||
raw = raw['orders']
|
||||
if not isinstance(raw, list) or any(not isinstance(item, dict) for item in raw):
|
||||
raise ValidationError(
|
||||
'Workflow must output an orders array',
|
||||
code='SHIPPING_NOTICE.ORDER_EXTRACTION_PROVIDER_INVALID_RESPONSE',
|
||||
)
|
||||
return raw
|
||||
|
||||
|
||||
def execute_order_extraction_workflow(*, run: Any, provider: Any, timeout_seconds: int) -> 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),
|
||||
user=f'shipping-order-extraction:{run.user_id}',
|
||||
timeout=(5, timeout_seconds),
|
||||
)
|
||||
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 = parse_order_extraction_workflow_result(result)
|
||||
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
|
||||
@@ -12,9 +12,10 @@ from typing import Any
|
||||
|
||||
|
||||
_SCALAR_KEYS = (
|
||||
'field_code', 'scope', 'value_type', 'enabled', 'display_name', 'description',
|
||||
'required', 'normalizer_key', 'relation_role', 'comparator_key',
|
||||
'extraction_instruction', 'sequence',
|
||||
'field_code', 'scope', 'value_type', 'field_category', 'collection_mode', 'enabled',
|
||||
'display_name', 'description', 'business_purpose', 'required', 'normalizer_key',
|
||||
'relation_role', 'comparator_key', 'extraction_instruction', 'context_source',
|
||||
'sensitivity_level', 'dify_exposure_policy', 'available_for_customer_identity', 'sequence',
|
||||
)
|
||||
_SET_KEYS = ('aliases', 'validator_keys', 'enum_options')
|
||||
_EVIDENCE_POLICY_KEYS = ('required', 'source_precedence', 'conflict_policy', 'allow_single_source')
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
backend/app/services/shipping_notice/order_schema/registry.py
|
||||
|
||||
用途:维护订单字段类型、规范化器、校验器、比较器和证据策略白名单。
|
||||
用途:维护订单字段分类、采集模式、类型、规范化器、校验器、比较器和证据策略白名单。
|
||||
依赖:无。
|
||||
逻辑:管理员配置只能引用本模块声明的安全能力;运行期解析器在后续阶段复用同一目录。
|
||||
"""
|
||||
@@ -10,6 +10,8 @@ from __future__ import annotations
|
||||
|
||||
FIELD_TYPES = {'string', 'decimal', 'integer', 'date', 'boolean', 'enum'}
|
||||
FIELD_SCOPES = {'header', 'line'}
|
||||
FIELD_CATEGORIES = {'general_context', 'order_header', 'order_line'}
|
||||
COLLECTION_MODES = {'deterministic_context', 'llm_extraction'}
|
||||
NORMALIZERS = {
|
||||
'trim', 'uppercase_trim', 'lowercase_trim', 'decimal', 'integer', 'iso_date',
|
||||
'boolean', 'reservation_id',
|
||||
@@ -62,6 +64,8 @@ def catalog() -> dict[str, list[str] | dict[str, list[str]]]:
|
||||
return {
|
||||
'field_types': sorted(FIELD_TYPES),
|
||||
'field_scopes': sorted(FIELD_SCOPES),
|
||||
'field_categories': sorted(FIELD_CATEGORIES),
|
||||
'collection_modes': sorted(COLLECTION_MODES),
|
||||
'normalizers': _admin_rules(NORMALIZERS),
|
||||
'validators': _admin_rules(VALIDATORS),
|
||||
'comparators': _admin_rules(COMPARATORS),
|
||||
|
||||
@@ -8,6 +8,7 @@ backend/app/services/shipping_notice/order_schema/runtime.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
@@ -16,6 +17,7 @@ from app.core.errors import ConflictError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingNoticeDocument,
|
||||
ShippingNoticeIntake,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
@@ -24,6 +26,10 @@ from app.models import (
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.notice_lines import parse_notice_table_text
|
||||
from app.services.shipping_notice.context_fields.runtime import (
|
||||
canonical_mail_context,
|
||||
persist_deterministic_context_fields,
|
||||
)
|
||||
from app.services.shipping_notice.order_customer_matching import refresh_order_customer_matches
|
||||
from app.services.shipping_notice.reservation_id import validated_reservation_id
|
||||
|
||||
@@ -37,10 +43,10 @@ def published_version() -> ShippingOrderSchemaVersion:
|
||||
|
||||
|
||||
def dify_contract(version: ShippingOrderSchemaVersion) -> dict[str, Any]:
|
||||
"""编译 Dify 动态抽取契约;仅输出发布快照中 enabled 的字段。"""
|
||||
"""编译 Dify 动态抽取契约;仅输出已启用的 LLM 字段,隔离确定性上下文字段。"""
|
||||
fields = [
|
||||
dict(item) for item in (version.definition_json or {}).get('fields') or []
|
||||
if item.get('enabled', True)
|
||||
if item.get('enabled', True) and item.get('collection_mode', 'llm_extraction') == 'llm_extraction'
|
||||
]
|
||||
return {
|
||||
'schema_version_id': int(version.id),
|
||||
@@ -56,6 +62,7 @@ def dify_contract(version: ShippingOrderSchemaVersion) -> dict[str, Any]:
|
||||
'confidence': '<optional 0..1>',
|
||||
},
|
||||
'order': {'header_fields': '<field[]>', 'lines': [{'fields': '<field[]>'}]},
|
||||
'restriction': 'Only field_id values listed in fields[] may be returned; deterministic context fields are forbidden.',
|
||||
},
|
||||
}
|
||||
|
||||
@@ -69,11 +76,15 @@ def _json_value(value: Any) -> Any:
|
||||
return value
|
||||
|
||||
|
||||
def _input_snapshot(*, intake_id: int, snapshot_hash: str, documents: list[ShippingNoticeDocument]) -> dict[str, Any]:
|
||||
"""冻结本次裁决使用的文档文本和指纹,供管理员重建输入证据而不回读可变 Document。"""
|
||||
def _input_snapshot(
|
||||
*, intake_id: int, snapshot_hash: str, documents: list[ShippingNoticeDocument],
|
||||
mail_context: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""冻结本次裁决使用的文档与邮件上下文,供管理员完整重建输入证据。"""
|
||||
return {
|
||||
'intake_id': intake_id,
|
||||
'snapshot_hash': snapshot_hash,
|
||||
'mail_context': dict(mail_context),
|
||||
'documents': [
|
||||
{
|
||||
'id': int(document.id),
|
||||
@@ -148,9 +159,53 @@ def _source_type(document: ShippingNoticeDocument) -> str:
|
||||
return 'email_body_text' if document.document_type == 'body' else 'attachment_text'
|
||||
|
||||
|
||||
def _quote_supports_value(value: Any, config: dict[str, Any], quote: str) -> bool:
|
||||
"""
|
||||
按字段数据类型确认原文引文确实支持已标准化的候选值。
|
||||
|
||||
核心逻辑:文本保留规范化后的包含校验;数值从引文提取数值 token 后以 Decimal 等价比较,
|
||||
日期则接受常见原文格式并转换为 date 比较,避免 30 EA、28,252.80、06/29/2026 被格式差异误拒。
|
||||
|
||||
Args:
|
||||
value: 已通过 `_normalize` 的字段候选值。
|
||||
config: 已发布字段配置,必须包含 value_type。
|
||||
quote: 已确认存在于来源文档的逐字原文引文。
|
||||
|
||||
Returns:
|
||||
候选值可由 quote 直接支持时返回 True;否则返回 False。
|
||||
"""
|
||||
value_type = str(config.get('value_type') or '')
|
||||
if value_type in {'decimal', 'integer'}:
|
||||
try:
|
||||
expected = Decimal(str(value).replace(',', '').strip())
|
||||
except (InvalidOperation, ValueError, TypeError):
|
||||
return False
|
||||
for token in re.findall(r'[-+]?\d[\d,]*(?:\.\d+)?', quote):
|
||||
try:
|
||||
if Decimal(token.replace(',', '')) == expected:
|
||||
return True
|
||||
except InvalidOperation:
|
||||
continue
|
||||
return False
|
||||
|
||||
if value_type == 'date' and isinstance(value, date):
|
||||
for token in re.findall(r'\d{4}-\d{1,2}-\d{1,2}|\d{1,2}[/-]\d{1,2}[/-]\d{2,4}', quote):
|
||||
for pattern in ('%Y-%m-%d', '%m/%d/%Y', '%m-%d-%Y', '%m/%d/%y', '%m-%d-%y'):
|
||||
try:
|
||||
if datetime.strptime(token, pattern).date() == value:
|
||||
return True
|
||||
except ValueError:
|
||||
continue
|
||||
return False
|
||||
|
||||
normalized_quote = ' '.join(quote.upper().split())
|
||||
normalized_value = ' '.join(str(_json_value(value)).upper().split())
|
||||
return bool(normalized_value) and normalized_value in normalized_quote
|
||||
|
||||
|
||||
def _verified_observations(raw: dict[str, Any], config: dict[str, Any],
|
||||
documents: dict[int, ShippingNoticeDocument]) -> list[dict[str, Any]]:
|
||||
"""验证动态 Observation 的字段值、Document 归属、逐字 quote 与值包含关系。"""
|
||||
"""验证动态 Observation 的字段值、Document 归属、逐字 quote 与类型化值支持关系。"""
|
||||
items = raw.get('observations') if isinstance(raw.get('observations'), list) else []
|
||||
verified: list[dict[str, Any]] = []
|
||||
for item in items:
|
||||
@@ -163,7 +218,7 @@ def _verified_observations(raw: dict[str, Any], config: dict[str, Any],
|
||||
continue
|
||||
if not quote or quote not in str(document.extracted_text or ''):
|
||||
continue
|
||||
if str(_json_value(value)).upper() not in quote.upper():
|
||||
if not _quote_supports_value(value, config, quote):
|
||||
continue
|
||||
try:
|
||||
confidence = max(0.0, min(float(item.get('confidence')), 1.0))
|
||||
@@ -317,22 +372,53 @@ def _backend_candidates(config: dict[str, Any], *, rows: list[dict[str, Any]]) -
|
||||
return result
|
||||
|
||||
|
||||
def persist_dynamic_order(*, raw_order: dict[str, Any], intake_id: int, snapshot_hash: str,
|
||||
documents: list[ShippingNoticeDocument], actor_id: int | None) -> dict[str, Any]:
|
||||
"""裁决并保存一个动态订单,返回 field_code 下游投影与阻断字段。"""
|
||||
version = published_version()
|
||||
def persist_dynamic_order(
|
||||
*,
|
||||
raw_order: dict[str, Any],
|
||||
intake_id: int,
|
||||
snapshot_hash: str,
|
||||
documents: list[ShippingNoticeDocument],
|
||||
actor_id: int | None,
|
||||
schema_version_id: int | None = None,
|
||||
frozen_mail_context: dict[str, Any] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""按当前 published 或 Run 锁定版本裁决订单,返回下游投影与阻断字段。"""
|
||||
version = (
|
||||
db.session.get(ShippingOrderSchemaVersion, int(schema_version_id))
|
||||
if schema_version_id is not None
|
||||
else published_version()
|
||||
)
|
||||
if version is None or version.status not in {'published', 'retired'}:
|
||||
raise ConflictError('Order schema version is unavailable', code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED')
|
||||
supplied_version = raw_order.get('schema_version_id')
|
||||
supplied_checksum = str(raw_order.get('schema_checksum') or '')
|
||||
if supplied_version != int(version.id) or supplied_checksum != str(version.checksum or ''):
|
||||
raise ConflictError('Order schema changed', code='SHIPPING_NOTICE.CANDIDATE_SOURCE_CHANGED')
|
||||
configs = {
|
||||
all_configs = {
|
||||
str(item['field_id']): item for item in (version.definition_json or {}).get('fields') or []
|
||||
if item.get('enabled', True)
|
||||
}
|
||||
configs = {
|
||||
field_id: item for field_id, item in all_configs.items()
|
||||
if item.get('collection_mode', 'llm_extraction') == 'llm_extraction'
|
||||
}
|
||||
context_configs = [
|
||||
item for item in all_configs.values()
|
||||
if item.get('collection_mode') == 'deterministic_context' and item.get('scope') == 'header'
|
||||
]
|
||||
intake = db.session.get(ShippingNoticeIntake, intake_id)
|
||||
if intake is None:
|
||||
raise ValidationError('Shipping notice intake not found', code='SHIPPING_NOTICE.ORDER_EXTRACTION_INVALID_RESULT')
|
||||
mail_context = (
|
||||
dict(frozen_mail_context)
|
||||
if isinstance(frozen_mail_context, dict)
|
||||
else canonical_mail_context(intake)
|
||||
)
|
||||
extraction = ShippingOrderExtraction(
|
||||
intake_id=intake_id, schema_version_id=version.id, input_snapshot_hash=snapshot_hash,
|
||||
input_snapshot_json=_input_snapshot(
|
||||
intake_id=intake_id, snapshot_hash=snapshot_hash, documents=documents,
|
||||
mail_context=mail_context,
|
||||
),
|
||||
status='extracting', raw_llm_output_json=raw_order, created_by_id=actor_id,
|
||||
)
|
||||
@@ -344,6 +430,13 @@ def persist_dynamic_order(*, raw_order: dict[str, Any], intake_id: int, snapshot
|
||||
blocked: list[str] = []
|
||||
observations: list[dict[str, Any]] = []
|
||||
decisions: list[dict[str, Any]] = []
|
||||
context_header, context_observations, context_decisions, context_blocked = persist_deterministic_context_fields(
|
||||
extraction=extraction, intake=intake, configs=context_configs, frozen_values=mail_context,
|
||||
)
|
||||
header.update(context_header)
|
||||
observations.extend(context_observations)
|
||||
decisions.extend(context_decisions)
|
||||
blocked.extend(context_blocked)
|
||||
backend_rows = _backend_rows(documents)
|
||||
groups: list[tuple[int | None, int | None, str, list[Any], dict[str, Any]]] = [
|
||||
(None, None, 'header', raw_order.get('header_fields') or [], header)
|
||||
@@ -398,7 +491,7 @@ def persist_dynamic_order(*, raw_order: dict[str, Any], intake_id: int, snapshot
|
||||
blocked.append(str(config['field_code']))
|
||||
|
||||
# [STEP 3] Required 按 Header/每一 Line 检查,缺值和冲突都阻断自动建单。
|
||||
for config in configs.values():
|
||||
for config in all_configs.values():
|
||||
if not config.get('required'):
|
||||
continue
|
||||
code = str(config['field_code'])
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
backend/app/services/shipping_notice/order_schema/service.py
|
||||
|
||||
用途:管理唯一订单 Schema、稳定字段目录、不可变版本和追加式配置审计。
|
||||
依赖:db、订单 Schema 模型、registry、统一 AppError。
|
||||
依赖:db、订单 Schema/上下文来源模型、provider_registry、registry、统一 AppError。
|
||||
逻辑:草稿与发布版本统一读写 definition_json;乐观锁阻止覆盖;发布冻结快照并追加审计事件。
|
||||
"""
|
||||
|
||||
@@ -19,6 +19,8 @@ from sqlalchemy import func
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
ShippingContextProvider,
|
||||
ShippingContextProviderOption,
|
||||
ShippingOrderField,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldObservation,
|
||||
@@ -33,10 +35,13 @@ from app.models import (
|
||||
ShippingOrderLine,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.context_fields.provider_registry import registered_option, supports_dify_exposure
|
||||
from app.services.shipping_notice.order_schema.registry import (
|
||||
COLLECTION_MODES,
|
||||
COMPARATORS,
|
||||
CONFLICT_POLICIES,
|
||||
FIELD_SCOPES,
|
||||
FIELD_CATEGORIES,
|
||||
FIELD_TYPES,
|
||||
NORMALIZERS,
|
||||
RELATION_ROLES,
|
||||
@@ -56,6 +61,9 @@ BUSINESS_PURPOSES = frozenset({
|
||||
'general', 'part_number', 'quantity', 'reservation_id', 'inventory_source_hint',
|
||||
})
|
||||
_LINE_STRING_PURPOSES = frozenset({'part_number', 'reservation_id', 'inventory_source_hint'})
|
||||
DIFY_EXPOSURE_POLICY_ORDER = ('never', 'redacted', 'confirmed_readonly')
|
||||
DIFY_EXPOSURE_POLICIES = frozenset(DIFY_EXPOSURE_POLICY_ORDER)
|
||||
SENSITIVITY_LEVELS = frozenset({'low', 'personal', 'confidential'})
|
||||
|
||||
|
||||
def _iso(value: datetime | None) -> str | None:
|
||||
@@ -83,6 +91,8 @@ def _field_payload(field: ShippingOrderField) -> dict[str, Any]:
|
||||
'field_code': field.field_code,
|
||||
'scope': field.scope,
|
||||
'value_type': field.value_type,
|
||||
'field_category': field.field_category,
|
||||
'collection_mode': field.collection_mode,
|
||||
'status': field.status,
|
||||
'published_once': bool(field.published_once),
|
||||
'created_at': _iso(field.created_at),
|
||||
@@ -121,6 +131,98 @@ def _business_purpose(raw: Any, *, field: ShippingOrderField) -> str:
|
||||
return purpose
|
||||
|
||||
|
||||
def _context_source_snapshot(raw: dict[str, Any], *, field: ShippingOrderField) -> dict[str, Any] | None:
|
||||
"""校验确定性来源并生成版本快照;禁止自由选择器和未注册/已停用能力进入 Schema。"""
|
||||
option_id = raw.get('context_provider_option_id')
|
||||
if field.collection_mode != 'deterministic_context':
|
||||
if option_id not in (None, ''):
|
||||
raise ValidationError(
|
||||
'LLM extraction field cannot select a context provider',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
)
|
||||
return None
|
||||
if not isinstance(option_id, int):
|
||||
raise ValidationError(
|
||||
'deterministic context field requires context_provider_option_id',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
)
|
||||
option = db.session.get(ShippingContextProviderOption, option_id)
|
||||
provider = option.provider if option else None
|
||||
capability = registered_option(provider.provider_key, option.option_key) if provider and option else None
|
||||
if option is None or provider is None or option.status != 'active' or provider.status != 'active' or capability is None:
|
||||
raise ValidationError(
|
||||
'context provider option is disabled or unregistered',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
)
|
||||
if option.value_type != field.value_type or capability.get('value_type') != field.value_type:
|
||||
raise ValidationError(
|
||||
'context provider value type is incompatible with field type',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
)
|
||||
return {
|
||||
'provider_id': provider.id,
|
||||
'provider_key': provider.provider_key,
|
||||
'provider_option_id': option.id,
|
||||
'option_key': option.option_key,
|
||||
'source_key': capability['source_key'],
|
||||
'sensitivity_level': option.sensitivity_level,
|
||||
'default_dify_exposure_policy': option.default_dify_exposure_policy,
|
||||
}
|
||||
|
||||
|
||||
def _version_context_policy(raw: dict[str, Any], *, source: dict[str, Any] | None) -> tuple[str, bool]:
|
||||
"""规范化版本级 Dify 暴露策略;仅允许代码注册能力声明的受控策略。"""
|
||||
policy = str(raw.get('dify_exposure_policy') or 'never').strip()
|
||||
if policy not in DIFY_EXPOSURE_POLICIES:
|
||||
raise ValidationError('dify exposure policy is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
if source is None and policy != 'never':
|
||||
raise ValidationError(
|
||||
'LLM extraction fields cannot be exposed as deterministic read-only context',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
)
|
||||
if source is not None:
|
||||
capability = registered_option(source['provider_key'], source['option_key'])
|
||||
if not supports_dify_exposure(capability, policy):
|
||||
raise ValidationError(
|
||||
'context field Dify exposure policy is not supported by the registered provider',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
)
|
||||
identity_enabled = raw.get('available_for_customer_identity', False)
|
||||
if not isinstance(identity_enabled, bool):
|
||||
raise ValidationError(
|
||||
'available_for_customer_identity must be boolean', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID'
|
||||
)
|
||||
return policy, identity_enabled
|
||||
|
||||
|
||||
def _sensitivity_level(raw: dict[str, Any], *, source: dict[str, Any] | None) -> str:
|
||||
"""冻结字段敏感等级;确定性来源继承受控目录,LLM 字段由管理员在白名单内配置。"""
|
||||
level = source['sensitivity_level'] if source else str(raw.get('sensitivity_level') or 'confidential').strip()
|
||||
if level not in SENSITIVITY_LEVELS:
|
||||
raise ValidationError('sensitivity level is invalid', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
return level
|
||||
|
||||
|
||||
def _validate_published_context_sources(definition: dict[str, Any]) -> None:
|
||||
"""发布前重验确定性来源与暴露能力,防止草稿保存后注册白名单发生变化。"""
|
||||
for config in _enabled_fields(definition):
|
||||
if config.get('collection_mode') != 'deterministic_context':
|
||||
continue
|
||||
field = db.session.get(ShippingOrderField, str(config.get('field_id') or ''))
|
||||
if field is None:
|
||||
raise ValidationError('context field no longer exists', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
current_source = _context_source_snapshot(
|
||||
{'context_provider_option_id': config.get('context_source', {}).get('provider_option_id')},
|
||||
field=field,
|
||||
)
|
||||
if current_source != config.get('context_source'):
|
||||
raise ValidationError(
|
||||
'context provider metadata changed; save the draft again before publishing',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
)
|
||||
_version_context_policy(config, source=current_source)
|
||||
|
||||
|
||||
def _audit_summary(before: dict[str, Any] | None, after: dict[str, Any] | None) -> dict[str, Any]:
|
||||
"""生成阶段一审计摘要;阶段三在此基础上提供完整字段级语义差异。"""
|
||||
before_fields = {str(item.get('field_id')): item for item in (before or {}).get('fields', [])}
|
||||
@@ -193,7 +295,10 @@ def get_state() -> dict[str, Any]:
|
||||
"""返回编辑工作区所需当前草稿/发布版本,历史版本由分页接口按需读取。"""
|
||||
schema = _schema()
|
||||
if schema is None:
|
||||
return {'schema': None, 'fields': [], 'versions': [], 'catalog': catalog()}
|
||||
return {
|
||||
'schema': None, 'fields': [], 'versions': [], 'catalog': catalog(),
|
||||
'context_providers': _context_provider_catalog(),
|
||||
}
|
||||
return {
|
||||
'schema': {
|
||||
'id': schema.id,
|
||||
@@ -212,9 +317,45 @@ def get_state() -> dict[str, Any]:
|
||||
if item.status in {'draft', 'published'}
|
||||
],
|
||||
'catalog': catalog(),
|
||||
'context_providers': _context_provider_catalog(),
|
||||
}
|
||||
|
||||
|
||||
def _context_provider_catalog() -> list[dict[str, Any]]:
|
||||
"""返回数据库来源目录,并标记代码注册状态,供管理端只展示真实可执行选项。"""
|
||||
providers = ShippingContextProvider.query.order_by(ShippingContextProvider.id).all()
|
||||
return [
|
||||
{
|
||||
'id': provider.id,
|
||||
'provider_key': provider.provider_key,
|
||||
'display_name': provider.display_name,
|
||||
'description': provider.description,
|
||||
'status': provider.status,
|
||||
'options': [
|
||||
{
|
||||
'id': option.id,
|
||||
'option_key': option.option_key,
|
||||
'display_name': option.display_name,
|
||||
'description': option.description,
|
||||
'value_type': option.value_type,
|
||||
'sensitivity_level': option.sensitivity_level,
|
||||
'default_dify_exposure_policy': option.default_dify_exposure_policy,
|
||||
'allowed_dify_exposure_policies': list(
|
||||
policy for policy in DIFY_EXPOSURE_POLICY_ORDER
|
||||
if supports_dify_exposure(
|
||||
registered_option(provider.provider_key, option.option_key), policy,
|
||||
)
|
||||
),
|
||||
'status': option.status,
|
||||
'registered': registered_option(provider.provider_key, option.option_key) is not None,
|
||||
}
|
||||
for option in provider.options
|
||||
],
|
||||
}
|
||||
for provider in providers
|
||||
]
|
||||
|
||||
|
||||
def list_versions(
|
||||
*, page: int = 1, page_size: int = 20, version_number: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
@@ -474,7 +615,7 @@ def save_field(
|
||||
data: dict[str, Any], *, actor_id: int | None, field_id: str | None = None,
|
||||
request_id: str | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""创建或更新稳定字段;系统标识可重命名,首次发布后仍锁定 scope 和 type。"""
|
||||
"""创建或更新稳定字段;首次发布后锁定作用域、类型、字段分类和采集模式。"""
|
||||
schema = _require_schema()
|
||||
field = db.session.get(ShippingOrderField, field_id) if field_id else None
|
||||
if field_id and (field is None or field.schema_id != schema.id):
|
||||
@@ -482,23 +623,41 @@ def save_field(
|
||||
code = str(data.get('field_code') or '').strip().lower()
|
||||
scope = str(data.get('scope') or '').strip().lower()
|
||||
value_type = str(data.get('value_type') or '').strip().lower()
|
||||
field_category = str(data.get('field_category') or ('order_line' if scope == 'line' else 'order_header')).strip()
|
||||
collection_mode = str(data.get('collection_mode') or 'llm_extraction').strip()
|
||||
if not FIELD_CODE_RE.fullmatch(code):
|
||||
raise ValidationError('field_code must use lower snake_case', code='SHIPPING.ORDER_FIELD_INVALID')
|
||||
if scope not in FIELD_SCOPES or value_type not in FIELD_TYPES:
|
||||
raise ValidationError('scope or value_type is invalid', code='SHIPPING.ORDER_FIELD_INVALID')
|
||||
if field and field.published_once and (field.scope, field.value_type) != (scope, value_type):
|
||||
raise ConflictError('Published field scope and type are immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE')
|
||||
if field_category not in FIELD_CATEGORIES or collection_mode not in COLLECTION_MODES:
|
||||
raise ValidationError('field category or collection mode is invalid', code='SHIPPING.ORDER_FIELD_INVALID')
|
||||
expected_shape = {
|
||||
'general_context': ('header', 'deterministic_context'),
|
||||
'order_header': ('header', 'llm_extraction'),
|
||||
'order_line': ('line', 'llm_extraction'),
|
||||
}[field_category]
|
||||
if (scope, collection_mode) != expected_shape:
|
||||
raise ValidationError('field category is incompatible with scope or collection mode', code='SHIPPING.ORDER_FIELD_INVALID')
|
||||
immutable_shape = (scope, value_type, field_category, collection_mode)
|
||||
if field and field.published_once and (
|
||||
field.scope, field.value_type, field.field_category, field.collection_mode,
|
||||
) != immutable_shape:
|
||||
raise ConflictError('Published field identity shape is immutable', code='SHIPPING.ORDER_FIELD_IMMUTABLE')
|
||||
previous_code = field.field_code if field else None
|
||||
field = field or ShippingOrderField(
|
||||
schema_id=schema.id,
|
||||
field_code=code,
|
||||
scope=scope,
|
||||
value_type=value_type,
|
||||
field_category=field_category,
|
||||
collection_mode=collection_mode,
|
||||
created_by_id=actor_id,
|
||||
)
|
||||
field.field_code = code
|
||||
field.scope = scope
|
||||
field.value_type = value_type
|
||||
field.field_category = field_category
|
||||
field.collection_mode = collection_mode
|
||||
if not field_id:
|
||||
db.session.add(field)
|
||||
try:
|
||||
@@ -777,6 +936,16 @@ def save_draft(
|
||||
if field.value_type != 'enum' and enum_options:
|
||||
raise ValidationError('enum_options only applies to enum fields', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
business_purpose = _business_purpose(raw.get('business_purpose'), field=field)
|
||||
context_source = _context_source_snapshot(raw, field=field)
|
||||
dify_exposure_policy, available_for_customer_identity = _version_context_policy(
|
||||
raw, source=context_source,
|
||||
)
|
||||
sensitivity_level = _sensitivity_level(raw, source=context_source)
|
||||
if context_source is not None and (aliases or raw.get('extraction_instruction')):
|
||||
raise ValidationError(
|
||||
'deterministic context field cannot configure LLM extraction rules',
|
||||
code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID',
|
||||
)
|
||||
if enabled and business_purpose != 'general':
|
||||
if business_purpose in enabled_purposes:
|
||||
raise ValidationError(
|
||||
@@ -789,6 +958,8 @@ def save_draft(
|
||||
'field_code': field.field_code,
|
||||
'scope': field.scope,
|
||||
'value_type': field.value_type,
|
||||
'field_category': field.field_category,
|
||||
'collection_mode': field.collection_mode,
|
||||
'enabled': enabled,
|
||||
'display_name': display_name,
|
||||
'description': str(raw.get('description') or '').strip() or None,
|
||||
@@ -802,6 +973,10 @@ def save_draft(
|
||||
'relation_role': relation_role,
|
||||
'comparator_key': comparator,
|
||||
'extraction_instruction': str(raw.get('extraction_instruction') or '').strip() or None,
|
||||
'context_source': context_source,
|
||||
'sensitivity_level': sensitivity_level,
|
||||
'dify_exposure_policy': dify_exposure_policy,
|
||||
'available_for_customer_identity': available_for_customer_identity,
|
||||
'sequence': sequence,
|
||||
})
|
||||
after = {'schema_code': version.schema.schema_code, 'version': version.version, 'fields': normalized_fields}
|
||||
@@ -837,6 +1012,7 @@ def publish(
|
||||
details={'expected_lock_version': expected_lock_version, 'current_lock_version': version.lock_version},
|
||||
)
|
||||
definition = _definition(version)
|
||||
_validate_published_context_sources(definition)
|
||||
enabled_configs = _enabled_fields(definition)
|
||||
if not enabled_configs:
|
||||
raise ValidationError('Schema version requires at least one field', code='SHIPPING.ORDER_SCHEMA_VERSION_INVALID')
|
||||
|
||||
@@ -174,7 +174,11 @@ def claim_next_shipping_notice_job() -> Job | None:
|
||||
|
||||
return claim_next_job(
|
||||
domain=SHIPPING_NOTICE_JOB_DOMAIN,
|
||||
job_types=[JobType.SHIPPING_NOTICE_RUN, JobType.SHIPPING_NOTICE_PARSE],
|
||||
job_types=[
|
||||
JobType.SHIPPING_NOTICE_RUN,
|
||||
JobType.SHIPPING_NOTICE_PARSE,
|
||||
JobType.SHIPPING_ORDER_EXTRACTION,
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -85,7 +85,7 @@ def auto_mapping_allow_llm() -> bool:
|
||||
|
||||
|
||||
def defer_parse_to_dify_enabled() -> bool:
|
||||
"""建单后是否延后订单抽取,交由 Dify 画布完成并通过 submit_order_extraction 落库。"""
|
||||
"""建单后是否延后订单抽取,交由后台 Run/Worker 与专用 Workflow 完成。"""
|
||||
return cfg_bool("SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY", True)
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
services/shipping_notice/tools.py
|
||||
|
||||
用途:发货通知 Agent Tool 统一门面(API 唯一业务入口,无编排实现)。
|
||||
依赖:customer_identity_gate、task_workflow、inventory_workflow、inventory_rpa_workflow、fulfillment_workflow;order_extraction 延迟导入以避免建批循环依赖。
|
||||
依赖:customer_identity_gate、task_workflow、inventory_workflow、inventory_rpa_workflow、fulfillment_workflow。
|
||||
逻辑:shipping_notice_tools / workspace_shipping_notice 仅 import 本模块公开符号。
|
||||
"""
|
||||
|
||||
@@ -17,37 +17,6 @@ from app.services.shipping_notice import (
|
||||
from app.services.shipping_notice import customer_identity_gate
|
||||
|
||||
|
||||
def get_order_extraction_context(payload: dict):
|
||||
"""
|
||||
返回点击发送后的完整订单抽取上下文。
|
||||
【AI 触发时机】:仅在 Dify 订单抽取固定分支的 LLM 节点之前调用。
|
||||
|
||||
核心逻辑:延迟导入实现,避免 batch_from_intakes 与 Tool 门面形成模块初始化环。
|
||||
Args:
|
||||
payload: 必须包含完整 agent_runtime_context。
|
||||
Returns:
|
||||
邮件/附件文本、输入快照与抽取契约。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction import get_order_extraction_context as _get
|
||||
|
||||
return _get(payload)
|
||||
|
||||
|
||||
def submit_order_extraction(payload: dict):
|
||||
"""
|
||||
提交 LLM 完整订单结果并执行自动建单。
|
||||
【AI 触发时机】:订单抽取 LLM 与 JSON 标准化节点成功后调用。
|
||||
|
||||
核心逻辑:延迟导入实现,保留 Tool 门面为唯一 API 业务入口且不引入建批循环依赖。
|
||||
Args:
|
||||
payload: 完整运行态上下文、输入快照、契约版本与 orders[]。
|
||||
Returns:
|
||||
自动建单、打开已有任务和待处理订单摘要。
|
||||
"""
|
||||
from app.services.shipping_notice.order_extraction import submit_order_extraction as _submit
|
||||
|
||||
return _submit(payload)
|
||||
|
||||
# 任务 / 批次 / 决策
|
||||
create_batch = task_workflow.create_batch
|
||||
create_batch_tasks = task_workflow.create_batch_tasks
|
||||
|
||||
Reference in new issue
Block a user