Files
syops/backend/app/services/shipping_notice/tool_common.py
T

668 lines
24 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
services/shipping_notice/tool_common.py
用途:发货通知 Tool 链共享配置、payload 合并、消息拼接与任务事件写入(无阶段业务编排)。
依赖:constants、models.ShippingTaskEvent、fulfillment_audit、stp_progress_contract。
逻辑:task_workflow / inventory_workflow / fulfillment_workflow / decision_workflow 共用;
log_task_event 对 inventory_rpa_/inventory_source_/export_/notice_replace/
freight_cancellation_/STP 事件同步投影到 ShippingAuditEvent;
另提供 generic/XFA/LLM 等主链灰度开关读取。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
import uuid
from flask import current_app
from app import db
from app.models import ShippingNotice, ShippingTaskEvent
from app.services.shipping_notice.batch_legacy_removed import raise_shipping_batches_removed
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
def cfg_bool(key: str, default: bool = False) -> bool:
"""读取 Flask config 布尔值,支持 1/true/yes/on 字符串形式。"""
val = current_app.config.get(key)
if val is None:
return default
if isinstance(val, bool):
return val
return str(val).strip().lower() in {"1", "true", "yes", "on"}
def cfg_int(key: str, default: int = 0, *, min_value: int | None = None) -> int:
"""读取 Flask config 整数值,可选 min_value 下限。"""
val = current_app.config.get(key)
if val is None:
parsed = default
else:
try:
parsed = int(val)
except (TypeError, ValueError):
parsed = default
if min_value is not None:
parsed = max(parsed, min_value)
return parsed
def cfg_float(
key: str,
default: float = 0.0,
*,
min_value: float | None = None,
max_value: float | None = None,
) -> float:
"""读取 Flask config 浮点值,并在异常配置时回退到安全默认值。"""
val = current_app.config.get(key)
try:
parsed = float(default if val is None else val)
except (TypeError, ValueError):
parsed = default
if min_value is not None:
parsed = max(parsed, min_value)
if max_value is not None:
parsed = min(parsed, max_value)
return parsed
def auto_progress_enabled() -> bool:
"""是否启用 auto_progress 自动推进(SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED)。"""
return cfg_bool("SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED", False)
def auto_rpa_inventory_enabled() -> bool:
"""是否允许自动触发 RPA 导出库存。"""
return cfg_bool("SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED", True)
def rpa_inventory_timeout_seconds() -> int:
"""RPA 库存导出等待超时秒数。"""
return cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 900, min_value=5)
def auto_mapping_allow_llm() -> bool:
"""字段映射推断是否允许调用 LLM。"""
return cfg_bool("SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM", False)
def generic_extraction_enabled() -> bool:
"""是否允许无异型特征时进入通用 Schema 确定性解析。"""
return cfg_bool("SHIPPING_NOTICE_GENERIC_EXTRACTION_ENABLED", False)
def generic_auto_freeze_enabled() -> bool:
"""通用确定性解析通过门禁后是否允许自动冻结。"""
return cfg_bool("SHIPPING_NOTICE_GENERIC_AUTO_FREEZE_ENABLED", False)
def profile_auto_selection_enabled() -> bool:
"""多模板候选是否允许按确定性评分自动采用。"""
return cfg_bool("SHIPPING_NOTICE_PROFILE_AUTO_SELECTION_ENABLED", True)
def profile_layout_signature_required() -> bool:
"""
新 Run 候选是否强制要求有效版面签名。
阶段四全量切换前保持 False,避免未重签模板全部 fail-closed;
全部模板重新签名并发布后置 True。
"""
return cfg_bool("SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED", False)
def xfa_enabled() -> bool:
"""是否启用 XFA 能力探测与结构分析;识别到 xfa_hybrid 后正式提取默认开启。"""
return cfg_bool("SHIPPING_NOTICE_XFA_ENABLED", True)
def xfa_shadow_mode_enabled() -> bool:
"""
XFA shadow:完整执行解析与资格评估,但必须阻断真实自动建单。
核心逻辑:开启时仍计算 shadow_would_auto_create;真实建单仍走统一 Schema/CQ
`auto_create_enabled`,本开关不再另设独立 XFA 自动建单环境变量。
"""
return cfg_bool("SHIPPING_NOTICE_XFA_SHADOW_MODE", False)
def _parse_csv_allowlist(raw: str | None) -> list[str]:
"""解析逗号/分号分隔白名单,去空并保持稳定顺序。"""
text = str(raw or '').strip()
if not text:
return []
items: list[str] = []
for part in text.replace(';', ',').split(','):
value = str(part or '').strip()
if value:
items.append(value)
return items
def xfa_customer_allowlist() -> list[int]:
"""
XFA 客户白名单(自动建单硬门禁)。
Returns:
客户主键列表;空列表表示未配置,fail-closed。
"""
raw = current_app.config.get('SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST')
result: list[int] = []
for item in _parse_csv_allowlist(str(raw or '')):
try:
result.append(int(item))
except (TypeError, ValueError):
continue
return sorted(set(result))
def xfa_profile_checksum_allowlist() -> list[str]:
"""XFA Profile checksum 白名单(自动建单硬门禁);空列表 fail-closed。"""
raw = current_app.config.get('SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST')
return sorted(set(_parse_csv_allowlist(str(raw or ''))))
def xfa_scenario_allowlist() -> list[str]:
"""XFA 业务场景白名单(自动建单硬门禁);默认 shipping_notice_order。"""
raw = current_app.config.get('SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST')
if raw is None or str(raw).strip() == '':
raw = 'shipping_notice_order'
items = [
str(item).strip().lower()
for item in _parse_csv_allowlist(str(raw))
if str(item).strip()
]
return sorted(set(items)) or ['shipping_notice_order']
def llm_review_enabled() -> bool:
"""确定性解析失败后是否允许请求 Dify 最小证据建议(不得自动冻结)。"""
return cfg_bool("SHIPPING_NOTICE_LLM_REVIEW_ENABLED", False)
def extraction_emergency_stop_enabled() -> bool:
"""全局紧急停止:开启后新 Run 禁止任何自动冻结。"""
return cfg_bool("SHIPPING_NOTICE_EXTRACTION_EMERGENCY_STOP", False)
def auto_match_enabled() -> bool:
"""auto_progress 是否自动调用 match_inventory。"""
return cfg_bool("SHIPPING_NOTICE_AUTO_MATCH_ENABLED", True)
def auto_candidate_freeze_enabled() -> bool:
"""
[T10 周一受控测试] 是否在解析确认后自动冻结候选集合。
核心语义:路由解析通过 → 立即生成任务级+行级候选,进入 AUTO_INVENTORY_PREPARE;
关闭则停在 inventory_source_unresolved 待人工确认源。默认 true(受控测试开启)。
"""
return cfg_bool("SHIPPING_NOTICE_AUTO_CANDIDATE_FREEZE_ENABLED", True)
def auto_inventory_prepare_enabled() -> bool:
"""
[T10 周一受控测试] 是否在候选冻结后自动按 source_code 触发 per-source RPA Attempt。
关闭则停在 candidates_frozen(等待外部 API 或人工发 Trigger)。默认 true(受控测试开启)。
"""
return cfg_bool("SHIPPING_NOTICE_AUTO_INVENTORY_PREPARE_ENABLED", True)
def auto_generate_excel_enabled() -> bool:
"""[T10 周一受控测试] 是否在库存匹配全 matched 后自动调用 generate_excel。默认 true。"""
return cfg_bool("SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED", True)
def auto_chain_fallback_enabled() -> bool:
"""Hxops chat 是否在 match 后自动串联 export/upload(全局开关)。"""
return cfg_bool("SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK", True)
def payload_wants_auto_chain_fallback(payload: dict[str, Any] | None) -> bool:
"""payload 是否显式请求 Hxops 后端 fallback 串联(auto_chain_fallback=true 且全局开关开启)。"""
if not payload or not auto_progress_enabled() or not auto_chain_fallback_enabled():
return False
val = payload.get(AUTO_CHAIN_FALLBACK)
if val is None:
return False
if isinstance(val, bool):
return val
return str(val).strip().lower() in {"1", "true", "yes", "on"}
def merge_tool_payload(
task: ShippingNotice,
payload: dict[str, Any] | None = None,
*,
extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""合并 task_id、lang 与 auto_chain_fallback 等字段,供 workflow 间传递。"""
result = tool_payload_for_task(task, payload)
if extra:
result.update(extra)
if payload_wants_auto_chain_fallback(payload):
result[AUTO_CHAIN_FALLBACK] = True
return result
def tool_payload_for_task(task: ShippingNotice, payload: dict[str, Any] | None = None) -> dict[str, Any]:
"""从 task 与原始 payload 提取 workflow 间传递的最小字段集(task_id + lang)。"""
result: dict[str, Any] = {"task_id": task.task_no}
if not payload:
return result
for key in ("lang", "locale", "language"):
lang = str(payload.get(key) or "").strip()
if lang:
result["lang"] = lang
break
return result
def prepend_tool_message(result: dict[str, Any], prefix: str) -> dict[str, Any]:
"""将 prefix 消息 prepend 到 Tool 响应 message 字段(自动串联时合并多步提示)。"""
note = str(prefix or "").strip()
if not note:
return result
body = str(result.get("message") or "").strip()
return {**result, "message": f"{note}\n\n{body}" if body else note}
def set_task_step_progress(
task: ShippingNotice,
*,
step_key: str,
step_title: str,
status: str,
message: str,
progress_percent: int | None = None,
current: int | None = None,
total: int | None = None,
detail: str | None = None,
extra: dict[str, Any] | None = None,
) -> None:
"""写入任务当前步骤与步骤内细粒度进度,统一落到 current_step + step_payload_json。"""
payload = dict(task.step_payload_json or {})
progress: dict[str, Any] = {
"step_key": step_key,
"step_title": step_title,
"status": status,
"message": str(message or "").strip(),
}
if progress_percent is not None:
progress["progress_percent"] = max(0, min(int(progress_percent), 100))
if current is not None:
progress["current"] = int(current)
if total is not None:
progress["total"] = int(total)
if detail:
progress["detail"] = str(detail).strip()
if extra:
progress["extra"] = extra
payload["current_step_progress"] = progress
task.current_step = step_key
task.step_payload_json = payload
def clear_task_step_progress(task: ShippingNotice) -> None:
"""清空任务步骤内进度,保留其他 step_payload_json 字段。"""
payload = dict(task.step_payload_json or {})
payload.pop("current_step_progress", None)
task.step_payload_json = payload or None
def generate_task_no() -> str:
"""生成 SN-YYYYMMDD-XXXXXXXX 格式任务编号。"""
return f"SN-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
def _clean_event_value(value: Any) -> str:
"""把事件详情值规范化为短字符串;空值返回空字符串。"""
return str(value or "").strip()
def _task_batch_no(task: ShippingNotice | None) -> str:
"""从任务关系中提取批次号。"""
batch = getattr(task, "batch", None)
return _clean_event_value(getattr(batch, "batch_no", None))
def build_task_action_event_detail(
task: ShippingNotice,
*,
action: str,
source: str,
comment: str | None = None,
extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
构建任务动作类事件详情。
核心逻辑:统一补齐 action/source/target/batch/conversation 等字段,保证 reference_context 后续可以稳定消费本地动作事件。
Args:
task: 动作作用的目标任务。
action: 规范化动作名,如 confirm/reject/rematch/reparse/switch_focus。
source: 触发来源,如 workspace_api/tool_api/backend_orchestrator。
comment: 用户附带备注。
extra: 其他扩展字段,例如 previous_focus_task_no。
Returns:
标准化的事件 detail_json。
"""
detail: dict[str, Any] = {
"action": _clean_event_value(action),
"source": _clean_event_value(source),
"target_type": "task",
"target_id": _clean_event_value(getattr(task, "task_no", None)),
"batch_no": _task_batch_no(task),
"conversation_id": _clean_event_value(getattr(task, "conversation_id", None)),
}
normalized_comment = _clean_event_value(comment)
if normalized_comment:
detail["comment"] = normalized_comment
for key, value in (extra or {}).items():
if value is None:
continue
detail[key] = value
return detail
def log_task_event(
task: ShippingNotice,
event_type: str,
detail: dict[str, Any] | None = None,
*,
actor_id: int | None = None,
request_id: str | None = None,
source: str | None = None,
before: dict[str, Any] | None = None,
after: dict[str, Any] | None = None,
) -> None:
"""
写入 ShippingTaskEvent 审计记录(task 尚未 flush 时自动 flush)。
核心逻辑:actor_id 为 None 表示系统动作(STP auto_progress / orchestrator);
人工动作传入真实用户 ID。detail 可含 source=system|workspace_api|tool_api 等。
Args:
task: 目标任务。
event_type: 事件类型码。
detail: 结构化明细;包含动作对象与原因。
actor_id: 操作者用户 ID;系统事件传 None。
request_id: 请求追踪标识。
source: 操作来源,如 workspace_api 或 system。
before: 操作前业务快照。
after: 操作后业务快照。
"""
if task.id is None:
db.session.flush()
db.session.add(ShippingTaskEvent(
task_id=task.id,
event_type=event_type,
detail_json=detail or {},
actor_id=actor_id,
request_id=request_id,
source=source,
before_json=before,
after_json=after,
))
# 库存/RPA/导出/STP 关键节点双写统一审计;失败必须阻断,保证审计中心可检索。
from app.services.shipping_notice.stp_progress_contract import STP_AUDIT_DUAL_WRITE_PREFIXES
event_name = str(event_type or '')
dual_write = event_name.startswith((
'inventory_rpa_',
'inventory_source_',
'export_',
'notice_replace',
'freight_cancellation_',
)) or any(
event_name.startswith(prefix) or event_name == prefix
for prefix in STP_AUDIT_DUAL_WRITE_PREFIXES
)
if dual_write:
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
safe_before = None
safe_after = None
if isinstance(before, dict):
safe_before = {
key: before[key]
for key in ('status', 'phase', 'reason_code', 'error_code', 'attempt_count')
if key in before
} or None
if isinstance(after, dict):
safe_after = {
key: after[key]
for key in ('status', 'phase', 'reason_code', 'error_code', 'attempt_count')
if key in after
} or None
meta: dict[str, Any] = {'dual_write': 'shipping_task_event'}
attempt_count = int((detail or {}).get('attempts') or (detail or {}).get('attempt_no') or 0) or None
if attempt_count is not None:
meta['attempt_count'] = attempt_count
# 将关键操作内容(匹配结论、候选源、原因码等)写入 metadata,供审计中心检索。
detail_obj = detail if isinstance(detail, dict) else {}
for key in (
'match_status',
'resolved_ok_source_codes',
'source_code',
'connector_type',
'warehouse_id',
'reason_code',
'error_code',
'verification_id',
'disposition',
'confirmed_by',
):
if key not in detail_obj:
continue
value = detail_obj[key]
if isinstance(value, (str, int, float, bool)) or value is None:
meta[key] = value
elif isinstance(value, list) and all(isinstance(item, (str, int, float, bool)) or item is None for item in value):
meta[key] = value[:32]
# [STEP] 顶层 reason_code:优先 detail/after,其次按事件类型映射可解释性稳定码
reason_from_detail = str(detail_obj.get('reason_code') or '').strip()
reason_from_after = ''
if isinstance(after, dict):
reason_from_after = str(after.get('reason_code') or '').strip()
reason_code = (
reason_from_detail
or reason_from_after
or _audit_reason_code_for_task_event(event_name, detail_obj)
)
if reason_code:
meta.setdefault('reason_code', reason_code)
is_failure = (
event_name.endswith('_failed')
or event_name.endswith('_exhausted')
or event_name.endswith('_extract_failed')
)
record_fulfillment_audit(
event_type=f'task_{event_type}'[:64],
aggregate_type='shipping_task',
aggregate_id=str(task.task_no),
action=str(event_type)[:64],
actor_type='user' if actor_id is not None else 'system',
actor_id=actor_id,
task_no=str(task.task_no),
reason_code=reason_code,
result='failure' if is_failure else 'success',
before=safe_before,
after=safe_after or {'status': getattr(task, 'process_status', None)},
metadata=meta,
source=str(source or 'system')[:32],
strict=True,
)
def _audit_reason_code_for_task_event(event_type: str, detail: dict[str, Any]) -> str | None:
"""
将任务事件类型映射为可解释性稳定 reason_code,供审计中心筛选。
Args:
event_type: ShippingTaskEvent.event_type。
detail: 事件明细;可含 error / error_code。
Returns:
稳定原因码;无法映射时 None。
"""
name = str(event_type or '').strip()
err_blob = f"{detail.get('error') or ''} {detail.get('error_code') or ''}".lower()
mapping = {
'inventory_rpa_queued': 'inventory_rpa_queued',
'inventory_rpa_started': 'inventory_rpa_queued',
'inventory_rpa_timeout': 'inventory_rpa_timeout',
'inventory_rpa_exhausted': 'inventory_rpa_exhausted',
'inventory_rpa_failed': 'inventory_rpa_export_failed',
'notice_replaced': 'attachment_replaced',
'notice_replace_extract_failed': 'document_text_unavailable',
'freight_cancellation_completed': 'task_voided_for_correction',
'task_pending_void': 'task_cancelled_by_user',
'matched_multi_file_conflict': 'inventory_multi_file_conflict',
'matched_shortage': 'inventory_shortage_review_required',
'rpa_callback_rejected': 'late_callback_ignored',
'late_callback_ignored': 'late_callback_ignored',
}
if name in mapping:
code = mapping[name]
if name == 'inventory_rpa_failed':
if 'timeout' in err_blob:
return 'inventory_rpa_timeout'
if 'login' in err_blob or 'auth' in err_blob:
return 'inventory_rpa_login_failed'
if 'export' in err_blob:
return 'inventory_rpa_export_failed'
return 'inventory_rpa_export_failed'
if name == 'notice_replace_extract_failed':
from app.services.shipping_notice.error_explainability_contract import (
primary_attachment_reason_from_warnings,
)
from_warnings = primary_attachment_reason_from_warnings(
list(detail.get('warnings') or []),
)
return from_warnings or code
return code
if name.startswith('inventory_rpa_') and name.endswith('_failed'):
return 'inventory_rpa_export_failed'
if name.startswith('upload_rpa') and 'fail' in name:
return 'upload_rpa_failed'
return None
def task_lifecycle_audit_snapshot(task: ShippingNotice) -> dict[str, Any]:
"""
投影任务生命周期白名单快照,供 ShippingTaskEvent / ShippingAuditEvent 前后对比。
核心逻辑:仅输出审计允许的 status/phase/reason_code;业务明细放 detail/metadata。
Args:
task: 当前 ShippingNotice。
Returns:
可写入 before/after 的受控快照 dict(可能为空)。
"""
snapshot = {
'status': getattr(task, 'process_status', None),
'phase': getattr(task, 'current_step', None) or getattr(task, 'review_status', None),
'reason_code': getattr(task, 'pending_human_reason', None),
}
return {key: value for key, value in snapshot.items() if value is not None}
def resolve_workspace_actor_id(payload: dict[str, Any] | None) -> int | None:
"""
从 Tool/工作台 payload 解析操作人用户 ID。
核心逻辑:优先 operator_id / actor_id / _trusted_user_id / user_id。
Args:
payload: 路由或 Tool 入参。
Returns:
用户主键,无法解析时 None。
"""
if not isinstance(payload, dict):
return None
for key in ('operator_id', 'actor_id', '_trusted_user_id', 'user_id'):
raw = payload.get(key)
if raw is None or raw == '':
continue
try:
return int(raw)
except (TypeError, ValueError):
continue
return None
def log_task_action_event(
task: ShippingNotice,
event_type: str,
*,
action: str,
source: str,
comment: str | None = None,
extra: dict[str, Any] | None = None,
actor_id: int | None = None,
before: dict[str, Any] | None = None,
after: dict[str, Any] | None = None,
) -> None:
"""
写入标准化任务动作事件。
核心逻辑:在原始 event_type 之外,统一补足 reference_context 所需的动作元数据,
并透传操作人与前后快照,避免各入口散落拼接。
Args:
task: 目标任务。
event_type: ShippingTaskEvent 事件码。
action: 标准化动作名(供 reference_context)。
source: 来源,如 workspace_api。
comment: 可选备注。
extra: 额外 detail 字段。
actor_id: 操作人用户 ID;系统动作可空。
before/after: 可选生命周期快照。
"""
log_task_event(
task,
event_type,
build_task_action_event_detail(
task,
action=action,
source=source,
comment=comment,
extra=extra,
),
actor_id=actor_id,
source=source,
before=before,
after=after,
)
def switch_batch_focus(
batch: Any,
task: ShippingNotice,
*,
source: str,
event_type: str = "focus_switched",
comment: str | None = None,
emit_when_unchanged: bool = True,
extra: dict[str, Any] | None = None,
) -> bool:
"""
切换批次焦点任务并写入标准事件。
Raises:
ValidationError: shipping_batches 表已物理删除(co8e9f0a1b2c)。
"""
del batch, task, source, event_type, comment, emit_when_unchanged, extra
raise_shipping_batches_removed()