feat(shipping, admin, workspace, docs): 迭代货代模块、补充文档并处理合并冲突问题

This commit is contained in:
hugo committed 2026-08-12 09:27:33 +08:00
1 parent 4587b56900
commit 3c0e08377c
94 files changed
+29222 -1218

No files matched your search

+140 -10
View File
@@ -135,21 +135,36 @@ class DifyService:
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试。"
@staticmethod
def _friendly_stream_request_failure_message(error: requests.exceptions.RequestException) -> str:
"""
将对话连接异常转换成可安全展示的业务提示。
def _friendly_upstream_error_message(status_code: int, raw_body: str, agent_name: str | None = None) -> str:
"""将 Dify HTTP 错误转换为可执行的用户提示。
AI 触发时机:Dify 在建立 SSE 流前直接返回非 2xx 响应时调用。
核心逻辑:优先识别知识检索常用的 rerank 插件授权失败,避免把上游 403 误报为网络超时;
其余状态码则给出不泄露密钥和内部地址的通用排查方向。
Args:
error: requests 抛出的上游连接异常;原始内容只用于服务端日志。
status_code: Dify HTTP 响应状态码。
raw_body: 已截断的 Dify 错误正文,仅用于分类,不向用户原样透传。
agent_name: 当前智能体名称。
Returns:
不包含服务名称、地址、密钥或异常正文的用户提示。
面向最终用户的安全错误提示。
"""
if isinstance(error, requests.exceptions.ReadTimeout):
return "回答生成时间较长,本次请求未能完成,请稍后重试。"
if isinstance(error, requests.exceptions.ConnectTimeout):
return "当前服务连接超时,请稍后重试。"
return "当前服务暂时无法完成回答,请稍后重试。"
text = str(raw_body or "")
lower = text.lower()
resolved_agent_name = str(agent_name or "").strip() or "当前智能体"
if "rerank" in lower and ("403" in lower or "forbidden" in lower):
return (
f"{resolved_agent_name}的知识检索重排服务授权失败。"
"请联系管理员在 Dify 中更新 Rerank 模型供应商的 API Key 后重新发布应用。"
)
if status_code in (401, 403):
return f"{resolved_agent_name}暂时无法访问 Dify 服务,请联系管理员检查该应用的 API Key 与服务授权。"
if status_code == 404:
return f"{resolved_agent_name}的 Dify 应用地址或应用类型配置错误,请联系管理员检查 API Base URL。"
if status_code in (429, 502, 503, 504):
return f"{resolved_agent_name}的 Dify 服务暂时不可用或繁忙,请稍后重试。"
return f"{resolved_agent_name}暂时无法完成查询,请稍后重试;如持续失败请联系管理员检查 Dify 工作流。"
@staticmethod
def _merge_stream_answer_text(
@@ -1086,6 +1101,23 @@ class DifyService:
if retryable and attempt < max_retries:
time.sleep(attempt * 2)
continue
if not response.ok:
message = DifyService._friendly_upstream_error_message(
response.status_code,
response.text[:2000],
getattr(agent, 'name', None),
)
persist_stream_chat(
{
'event': 'error',
'conversation_id': normalized_conversation_id,
'answer': f"[Error: {message}]",
'metadata': {},
},
'error',
)
yield f"data: {json.dumps({'event': 'error', 'message': message}, ensure_ascii=False)}\n\n"
return
response.raise_for_status()
yield f"data: {json.dumps({'event': 'upstream_connected', 'message': 'Dify 已连接'}, ensure_ascii=False)}\n\n"
@@ -1216,6 +1248,104 @@ class DifyService:
persist_stream_chat(error_event, 'error')
yield f"data: {json.dumps(error_event, ensure_ascii=False)}\n\n"
@staticmethod
def run_chatflow_once(
*,
agent,
query: str,
inputs: dict[str, Any] | None = None,
user: str = "system",
timeout: tuple[int, int] = (5, 120),
) -> dict[str, Any]:
"""
以单次、无持久会话方式调用 Dify Chatflow 并收集最终回答。
核心逻辑:复用 Chatflow 的 `/v1/chat-messages` 和 SSE 协议,但不写 chat_logs、
不传 conversation_id;适用于合同审核等后台结构化任务,返回 message_end 的 answer。
Args:
agent: 含 Dify API Key 的 Chatflow Agent。
query: 传给 Chatflow 的一次性任务提示。
inputs: Dify Start 节点声明的变量。
user: Dify 用户标识,不应使用真实业务用户 ID。
timeout: `(connect_seconds, read_seconds)`。
Returns:
包含 `answer`、`conversation_id`、`message_id` 的字典。
Raises:
RuntimeError: Dify 返回错误事件或未产出最终回答。
requests.RequestException: HTTP 连接、超时或状态码错误。
"""
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
url = DifyService._build_chat_messages_url(base_url)
headers = {
"Authorization": f"Bearer {agent.dify_api_key}",
"Content-Type": "application/json",
}
payload = {
"inputs": DifyService._stringify_inputs(inputs),
"query": str(query or "").strip(),
"response_mode": "streaming",
"user": str(user or "system"),
}
if current_app:
current_app.logger.info(
"[chatflow-once] start agent_id=%s url=%s query_len=%s",
getattr(agent, "id", None),
url,
len(payload["query"]),
)
answer_parts: list[str] = []
final_data: dict[str, Any] = {}
with requests.post(url, headers=headers, json=payload, stream=True, timeout=timeout) as response:
if not response.ok and current_app:
current_app.logger.error(
"[chatflow-once] bad response status=%s url=%s body=%s",
response.status_code,
url,
response.text[:2000],
)
response.raise_for_status()
for line in response.iter_lines():
if not line:
continue
decoded = line.decode("utf-8", errors="replace")
if not decoded.startswith("data: "):
continue
try:
data = json.loads(decoded[6:])
except json.JSONDecodeError:
continue
event = str(data.get("event") or "")
if event == "error":
raise RuntimeError(str(data.get("message") or data))
if event == "message" and data.get("answer"):
answer_parts.append(str(data["answer"]))
if event in {"message_end", "workflow_finished"}:
final_data = data
workflow_data = data.get("data") if isinstance(data.get("data"), dict) else {}
if event == "workflow_finished" and workflow_data.get("status") == "failed":
# Chatflow also emits workflow events; expose the canvas-node error to the review task.
error_text = str(workflow_data.get("error") or "Dify Chatflow workflow failed")
raise RuntimeError(error_text)
final_answer = str(data.get("answer") or "").strip()
if final_answer:
answer_parts = [final_answer]
if event == "message_end":
break
answer = "".join(answer_parts).strip()
if not answer:
raise RuntimeError("Dify Chatflow returned no final answer")
return {
"answer": answer,
"conversation_id": final_data.get("conversation_id"),
"message_id": final_data.get("message_id") or final_data.get("id"),
"event": final_data.get("event") or "message_end",
}
@staticmethod
def _log_chat(
user_id,
+74 -1
View File
@@ -2,7 +2,7 @@
backend/app/services/schedule/job_registry.py
用途:平台内置排程 Job Registry(任务契约中心:key → handler + 展示信息 + params_schema + defaults)。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、job_params(执行前校验)。
依赖:shipping_inventory_rpa_job、faq_hot_aggregate_job、fixed_assets_snapshot_job、voucher_check_job、job_params。
逻辑:internal_jobs API 与 platform_job 排程通过 platform_api_path 引用已注册 key;
api/schedule/platform_tasks.py 下发 params_schema 供前端 DynamicTaskParamsForm 通用渲染。
"""
@@ -137,6 +137,8 @@ def _register_builtin_platform_jobs() -> None:
from app.services.schedule.shipping_post_ot_auto_fulfill_compensation_job import (
run_shipping_post_ot_auto_fulfill_compensation_schedule,
)
from app.services.schedule.voucher_check_job import run_voucher_check_schedule
from app.services.voucher_check.config import DEFAULT_JOB_PARAMS, DEFAULT_REQUIRED_FILES
register_platform_job(PlatformJobDefinition(
key="shipping-order-extraction-progress-cleanup",
@@ -272,6 +274,77 @@ def _register_builtin_platform_jobs() -> None:
description="按 TTL 清理未建单、未引用的临时 FileAsset 与关联 intake,并删除私有 MinIO 对象。",
category="files",
))
register_platform_job(PlatformJobDefinition(
key="accounting-voucher-check",
label="立账凭证检核",
label_key="admin.schedule.form.platformJobAccountingVoucherCheck",
handler=run_voucher_check_schedule,
description="按当前自然月拉取 ERP 发票清单,扫描共享盘必检材料是否存在(不读文件内容)。",
description_key="admin.schedule.form.accountingVoucherCheckHint",
category="finance",
params_schema=(
{
"key": "scope_code",
"type": "select",
"label": "账套",
"label_key": "admin.schedule.form.voucherCheckScope",
"required": True,
"default": "HXJM",
"options": [{"value": "HXJM", "label": "HXJM"}],
},
{
"key": "directory_template",
"type": "text",
"label": "目录模板",
"label_key": "admin.schedule.form.voucherCheckDirTemplate",
"required": True,
"default": "{root}/{YYYY}/{MM}/{invoice_no}",
"help": "仅允许 {root}/{YYYY}/{MM}/{invoice_no}",
"help_key": "admin.schedule.form.voucherCheckDirTemplateHelp",
},
{
"key": "required_files",
"type": "json",
"label": "必检材料",
"label_key": "admin.schedule.form.voucherCheckRequiredFiles",
"required": True,
"default": DEFAULT_REQUIRED_FILES,
},
{
"key": "filename_case_sensitive",
"type": "boolean",
"label": "文件名区分大小写",
"label_key": "admin.schedule.form.voucherCheckCaseSensitive",
"required": True,
"default": True,
},
{
"key": "notify_missing_enabled",
"type": "boolean",
"label": "缺资料通知",
"label_key": "admin.schedule.form.voucherCheckNotifyMissing",
"required": False,
"default": True,
},
{
"key": "notify_failure_enabled",
"type": "boolean",
"label": "失败告警",
"label_key": "admin.schedule.form.voucherCheckNotifyFailure",
"required": False,
"default": True,
},
{
"key": "same_day_dedup_enabled",
"type": "boolean",
"label": "同票同日去重",
"label_key": "admin.schedule.form.voucherCheckSameDayDedup",
"required": False,
"default": True,
},
),
defaults=dict(DEFAULT_JOB_PARAMS),
))
_register_builtin_platform_jobs()
@@ -576,6 +576,14 @@ def _resolve_task_actions(run: ShippingOrderProcessingRun) -> tuple[str | None,
if code == 'retry_failed_attachments' and 'retry_failed_documents' not in actions:
actions.append('retry_failed_documents')
# 当前 Run 已有可见 Review Case 时,任务卡不能再提供“打开订单复核”导航;
# 用户已经位于该工作台,继续动作必须由 Case/当前 Gate 投影提供。
review_cases = list(getattr(run, 'review_cases', None) or [])
if any(str(getattr(case, 'status', '') or '') not in {'superseded', 'non_order'} for case in review_cases):
actions = [action for action in actions if action not in {
'open_review', 'enter_manual_review', 'open_order_review',
}]
if 'view_details' not in actions:
actions.append('view_details')
@@ -12,6 +12,8 @@ import hashlib
import json
import re
import uuid
from pathlib import Path
import urllib.request
from datetime import datetime
from typing import Any
@@ -37,6 +39,7 @@ from app.services.shipping_notice.customer_normalization import (
normalize_domain,
normalize_email,
)
from app.services.shipping_notice.order_schema.runtime import published_version
DEFINITION_CODE_RE = re.compile(r'^[a-z][a-z0-9_]{1,63}$')
TARGET_TYPES = frozenset({'customer', 'site'})
@@ -99,9 +102,30 @@ def _write_audit(
))
def _published_schema_version() -> ShippingOrderSchemaVersion | None:
"""读取当前订单 Schema 族的已发布版本,隔离其他 Schema 族的同状态版本。"""
try:
return published_version()
except ConflictError:
return None
def _published_field_config(field_id: str) -> dict[str, Any] | None:
"""读取当前发布版本中的字段配置;识别定义和证据标准化均使用同一快照。"""
published = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
# #region debug-point A/B/C/E:published-schema-state
try:
debug_env = Path(__file__).resolve().parents[5] / '.dbg' / 'shipping-customer-fingerprint-500.env'
debug_values = {
line.split('=', 1)[0]: line.split('=', 1)[1].strip()
for line in debug_env.read_text(encoding='utf-8').splitlines()
if '=' in line
}
published_rows = ShippingOrderSchemaVersion.query.filter_by(status='published').all()
urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'shipping-customer-fingerprint-500'), 'runId': 'post-fix', 'hypothesisId': 'A/B/C/E', 'location': 'identity_rules/service.py:114', 'msg': '[DEBUG] published schema rows before serializer lookup', 'data': {'field_id': field_id, 'count': len(published_rows), 'rows': [{'id': row.id, 'schema_id': row.schema_id, 'version': row.version, 'status': row.status} for row in published_rows]}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read()
except Exception:
pass
# #endregion
published = _published_schema_version()
return next((
item for item in ((published.definition_json if published else {}) or {}).get('fields', [])
if str(item.get('field_id') or '') == field_id and item.get('enabled', True)
@@ -110,7 +134,7 @@ def _published_field_config(field_id: str) -> dict[str, Any] | None:
def _published_schema_snapshot() -> dict[str, Any]:
"""返回识别规则发布所绑定的唯一订单 Schema 版本锚点。"""
published = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
published = _published_schema_version()
if published is None or not published.checksum:
raise ConflictError(
'Published order schema is required for identity rules',
@@ -166,7 +190,7 @@ def list_published_evidence_definitions(*, target_type: str | None = None) -> di
def _published_header_fields() -> list[ShippingOrderField]:
"""读取当前发布版本实际纳入契约的 Header 文本字段。"""
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
version = _published_schema_version()
if version is None:
return []
ids = [str(item.get('field_id')) for item in (version.definition_json or {}).get('fields', [])
@@ -177,7 +201,7 @@ def _published_header_fields() -> list[ShippingOrderField]:
def _field_catalog_item(field: ShippingOrderField) -> dict[str, Any]:
"""返回可供业务人员选择的已发布订单字段,稳定编码仅作回退展示。"""
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
version = _published_schema_version()
snapshot = next((item for item in ((version.definition_json if version else {}) or {}).get('fields', [])
if str(item.get('field_id')) == field.id), {})
display_name = clean_text(snapshot.get('display_name')) or field.field_code
@@ -15,6 +15,8 @@ from __future__ import annotations
import hashlib
import json
from pathlib import Path
import urllib.request
from dataclasses import dataclass
from datetime import datetime
from typing import Any
@@ -507,7 +509,7 @@ def freeze_candidates_for_task(
for idx, code in enumerate(task_source_codes_ordered):
src_cfg = get_database_inventory_source(code)
rule_id: int | None = None
rule_version: str | None = None
rule_version: int | None = None
if isinstance(adjudication.evidence, list) and adjudication.evidence:
first_evidence = adjudication.evidence[0]
matched_rule_ids = first_evidence.get('rule_ids')
@@ -525,7 +527,7 @@ def freeze_candidates_for_task(
)
if rule_row is not None:
rule_id = rule_row.id
rule_version = str(rule_row.version)
rule_version = int(rule_row.version) if rule_row.version is not None else None
except (TypeError, ValueError):
rule_id = None
rule_version = None
@@ -535,13 +537,25 @@ def freeze_candidates_for_task(
candidate_order=idx + 1,
candidate_origin='manual_override' if frozen_by_id is not None else 'rule',
routing_rule_id=rule_id,
routing_rule_version=rule_version or config_version,
routing_rule_version=rule_version,
source_config_version=(
str(src_cfg.get('config_version')).strip() if isinstance(src_cfg, dict) and src_cfg.get('config_version') else None
),
override_by_id=frozen_by_id,
override_reason=None,
)
# #region debug-point A/C/E:source-version-contract
try:
debug_env = Path(__file__).resolve().parents[4] / '.dbg' / 'integer-routing-version.env'
debug_values = {
line.split('=', 1)[0]: line.split('=', 1)[1].strip()
for line in debug_env.read_text(encoding='utf-8').splitlines()
if '=' in line
}
urllib.request.urlopen(urllib.request.Request(debug_values.get('DEBUG_SERVER_URL', 'http://127.0.0.1:7777/event'), data=json.dumps({'sessionId': debug_values.get('DEBUG_SESSION_ID', 'integer-routing-version'), 'runId': 'post-fix', 'hypothesisId': 'A/C/E', 'location': 'inventory_candidate_freeze_service.py:545', 'msg': '[DEBUG] candidate source version before flush', 'data': {'routing_rule_id': rule_id, 'routing_rule_version': rule_version, 'config_version': config_version, 'persisted_routing_rule_version': source.routing_rule_version, 'source_code': code}}).encode(), headers={'Content-Type': 'application/json'}), timeout=1).read()
except Exception:
pass
# #endregion
session.add(source)
created_sources.append(source)
session.flush(created_sources)
@@ -244,8 +244,8 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
from app.services.shipping_notice.progress_workflow import run_task_auto_progress
task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip()
if not task_no and isinstance(payload, dict):
t = resolve_task_from_payload(payload)
task_no = str(getattr(t, 'task_no', '') or '').strip()
resolved_task = resolve_task_from_payload(payload)
task_no = str(getattr(resolved_task, 'task_no', '') or '').strip()
trigger = str(payload.get('source') or payload.get('trigger') or 'tool_api_ensure_inventory').strip()
actor_raw = payload.get("operator_id") or payload.get("actor_id") or payload.get("_trusted_user_id")
try:
@@ -282,8 +282,7 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
event_type="inventory_uploaded",
)
# [STEP 2] 正常流程只复用已完成的库存快照,绝不隐式触发 RPA。
# 库存导出由独立排程生产;用户明确选择 retry_rpa 才允许本任务发起刷新。
# [STEP 2] 正常流程优先复用已完成的库存快照;缺少快照时自动进入库存 RPA。
if mode == "retry_rpa":
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
@@ -394,6 +393,12 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if reused is not None:
return reused
# 库存源已确定但没有可复用快照时,自动推进必须启动一次 RPA,
# 否则任务会错误停在人审且没有可执行的恢复动作。
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
return ensure_inventory_via_rpa(task, mode=mode)
# [STEP 3] 最后处理已有任务库存与彻底缺库存两种兜底分支。
# 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。
if task.inventory_lines_json:
@@ -290,6 +290,23 @@ def _project_case_automation_status(
'job_id': int(job.id),
}
if job_status == 'running':
started_at = getattr(job, 'started_at', None) or getattr(job, 'updated_at', None)
if started_at is not None:
if getattr(started_at, 'tzinfo', None) is None:
started_at = started_at.replace(tzinfo=timezone.utc)
age = (datetime.now(timezone.utc) - started_at).total_seconds()
if age >= _stp_waiting_timeout_seconds():
return {
'status': 'failed',
'retryable': True,
'task_no': None,
'can_auto_create': can_auto,
'can_build': can_build,
'job_id': int(job.id),
'reason_code': 'stp_job_stale',
'error_code': 'SHIPPING.STP_AUTO_CREATE_TIMEOUT',
'next_action': 'retry_stp_auto_create',
}
return {
'status': 'running',
'retryable': False,
@@ -865,8 +882,14 @@ def serialize_review_case(
elif formal_ot.get('has_formal_ot'):
current_stage = project_stage_for_task(formal_ot.get('task'))
else:
# 建单前:固定 order_review;STP 入队态只走 automation,不冒充库存阶段。
current_stage = project_stage_for_task(None, default_code='order_review')
# 建单前一旦进入 STP,始终停留在自动建单节点;失败不得回退到订单复核前置节点。
auto_status = str((automation or {}).get('status') or '').strip().lower()
current_stage = project_stage_for_task(
None,
default_code='order_creating' if auto_status in {
'queued', 'running', 'failed', 'manual_fallback', 'completed',
} else 'order_review',
)
# [UI-03] Case 级暴露 Candidate 绑定的 OT,禁止前端回退 Run 根号。
linked_order_task = resolve_order_task_for_candidate(
@@ -276,6 +276,13 @@ def sync_order_task_stage_for_candidate(
)
if ot is None:
return None
# 正式建单后的 Candidate 仍可能因恢复/对账再次触发资格重算;
# 此时建单前资格阶段不再是权威事实,禁止覆盖 OT 当前履约阶段。
if (
getattr(candidate, 'consumed_task_id', None) is not None
or getattr(ot, 'shipping_notice_id', None) is not None
):
return ot
stage, status = resolve_pre_confirm_stage(
candidate=candidate,
evaluation=evaluation,
@@ -256,6 +256,22 @@ def project_case_automation_status(
'job_id': int(job.id),
}
if job_status == 'running':
started_at = getattr(job, 'started_at', None) or getattr(job, 'updated_at', None)
if started_at is not None:
if getattr(started_at, 'tzinfo', None) is None:
started_at = started_at.replace(tzinfo=timezone.utc)
if (datetime.now(timezone.utc) - started_at).total_seconds() >= _stp_waiting_timeout_seconds():
return {
'status': 'failed',
'retryable': True,
'task_no': None,
'can_auto_create': can_auto,
'can_build': can_build,
'job_id': int(job.id),
'reason_code': 'stp_job_stale',
'error_code': 'SHIPPING.STP_AUTO_CREATE_TIMEOUT',
'next_action': 'retry_stp_auto_create',
}
return {
'status': 'running',
'retryable': False,
@@ -469,6 +485,8 @@ def project_case_allowed_actions(
llm_enabled = False
if llm_enabled and 'edit_draft' in actions:
actions.append('request_llm_suggestion')
# 当前 Case 已由本工作台打开;该导航动作只适用于列表页入口,不能在复核页重复展示。
actions = [action for action in actions if action != 'open_order_review']
return actions