Merge branch 'test' into prod

This commit is contained in:
sophie committed 2026-06-23 14:20:42 +08:00
commit 8efc526ca8
72 files changed
+6849 -1043

No files matched your search

+1 -1
View File
@@ -59,4 +59,4 @@ MINIO_SECURE=false
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
# RoHS / 货代等 Dify Tool API 基地址(默认与 PUBLIC_BASE_URL 一致)
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8891
HXOPS_TOOLS_API_BASE=http://192.168.100.230:8890
+16 -2
View File
@@ -5,11 +5,12 @@ ROOT_DIR="$(git rev-parse --show-toplevel)"
# shellcheck source=_common.sh
source "${ROOT_DIR}/.githooks/_common.sh"
if hook_should_skip; then
if [[ "${SKIP_GIT_HOOKS:-}" == "1" ]]; then
exit 0
fi
zero="0000000000000000000000000000000000000000"
need_migration_check=0
need_frontend_build=0
while read -r local_ref local_sha remote_ref remote_sha; do
@@ -33,12 +34,25 @@ while read -r local_ref local_sha remote_ref remote_sha; do
changed_files="$(git diff --name-only --diff-filter=ACMR "${remote_sha}" "${local_sha}" || true)"
fi
if echo "${changed_files}" | grep -qE '^backend/migrations/versions/.*\.py$'; then
need_migration_check=1
fi
if frontend_paths_in "${changed_files}"; then
need_frontend_build=1
break
fi
done
if [[ "${need_migration_check}" -eq 1 ]]; then
if ! run_migration_heads_check "${ROOT_DIR}"; then
exit 1
fi
fi
if [[ "${SKIP_FRONTEND_HOOKS:-}" == "1" ]]; then
exit 0
fi
if [[ "${need_frontend_build}" -eq 0 ]]; then
exit 0
fi
+15 -4
View File
@@ -1066,6 +1066,8 @@ def chat_completions():
query = data.get('query')
# 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id')
shipping_task_id = str(data.get('task_id') or '').strip()
shipping_batch_no = str(data.get('batch_no') or '').strip()
kb_type = data.get('kb_type', '企业知识库')
files = data.get('files')
request_id = uuid.uuid4().hex[:12]
@@ -1195,14 +1197,13 @@ def chat_completions():
)
from app.services.file_check_tools.dify_inputs import build_file_check_dify_inputs
from app.services.shipping_notice.dify_inputs import (
build_dify_chat_inputs as build_shipping_dify_chat_inputs,
build_dify_chat_inputs as build_shipping_notice_dify_inputs,
is_shipping_notice_chat_agent,
)
declares_file_check = agent_declares_file_check_progress(agent_proxy)
is_file_check_agent = is_file_check_chat_agent(agent_proxy)
if is_shipping_notice_chat_agent(agent_proxy):
dify_inputs = build_shipping_dify_chat_inputs()
elif declares_file_check or is_file_check_agent:
is_shipping_agent = is_shipping_notice_chat_agent(agent_proxy)
if declares_file_check or is_file_check_agent:
# [STEP 1] 先校验 task_id,避免 Dify Chatflow 缺参时长连接挂死
dify_inputs = build_file_check_dify_inputs(agent_proxy, required=True)
if is_file_check_agent:
@@ -1216,6 +1217,16 @@ def chat_completions():
agent_id=agent_proxy.id,
query=query,
)
elif is_shipping_agent:
# [STEP 2] 发货通知 Chatflow 依赖会话级 task/batch 上下文稳定定位当前任务
dify_inputs = build_shipping_notice_dify_inputs(
external_conversation_id or session.session_id,
task_id=shipping_task_id,
batch_no=shipping_batch_no,
entry_mode="user_chat",
user_message=query,
trigger_source="frontend_chat",
)
generator = DifyService.stream_chat(
query,
user_proxy.id,
+54
View File
@@ -21,8 +21,11 @@ from app.errors import AppError, ConflictError, NotFoundError, ServiceUnavailabl
from app.models import ScheduleRun, ScheduleTask
from app.services.file_check_tools.openapi_spec import build_file_check_openapi_spec
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
from app.services.schedule import _build_srm_conn_str
from app.services.schedule.query_service import get_run, serialize_run
from app.services.schedule.srm_service import _fetch_records
from app.services.schedule.scheduler_service import _generate_run_no, run_task_now
from app.services.schedule.sql_config import get_schedule_sql_config_by_task_id
file_check_bp = Blueprint("file_check_tools", __name__)
@@ -266,6 +269,44 @@ def _record_run_bind(run: ScheduleRun, data: dict) -> None:
attach_run_to_turn(turn_id, int(run.id))
def _build_no_data_response(task: ScheduleTask) -> dict:
"""无待检资料时直接返回提示,不创建批次也不绑定 run_id。"""
return {
"ok": False,
"error_code": "no_data_to_check",
"message": "目前没有资料需要检核",
"task": {
"task_id": task.id,
"task_name": task.name,
},
}
def _precheck_no_data(task: ScheduleTask) -> dict | None:
"""
启动前预检当前任务是否存在待检资料。
核心逻辑:仅在数据库型检核任务上做轻量预检;若结果为空,则直接返回 no_data_to_check,
避免创建空批次并向 ChatLog 回写 run_id。
"""
if str(getattr(task, "data_source_type", "") or "database").lower() != "database":
return None
cfg = get_schedule_sql_config_by_task_id(task.id)
if not cfg or not str(cfg.fetch_sql or "").strip():
return None
if cfg.data_source and not cfg.data_source.is_empty():
conn_str = cfg.data_source.build_connection_string()
else:
conn_str = _build_srm_conn_str()
rows = _fetch_records(conn_str, cfg.fetch_sql)
if rows:
return None
return _build_no_data_response(task)
@file_check_bp.route("/tools/tasks/run", methods=["POST"])
def run_file_check():
"""立即执行检核;任务 enabled 仅控制 cron,不限制人工或 Chatflow 触发。"""
@@ -301,6 +342,19 @@ def run_file_check():
"run": _serialize_tool_run(existing),
})
no_data_response = _precheck_no_data(task)
if no_data_response:
lock_ms = int((time.perf_counter() - lock_started) * 1000)
total_ms = int((time.perf_counter() - perf_started) * 1000)
current_app.logger.info(
"[file-check-tool-perf] run_file_check outcome=no_data resolve_ms=%s lock_ms=%s total_ms=%s task_id=%s",
resolve_ms,
lock_ms,
total_ms,
task.id,
)
return jsonify(no_data_response)
run = ScheduleRun(
run_no=_generate_run_no(),
schedule_task_id=task.id,
+8 -7
View File
@@ -36,22 +36,23 @@ def _require_tool_auth() -> None:
校验货代 Tool API 鉴权 Header。
【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。
核心逻辑:读取配置中的 `SHIPPING_NOTICE_TOOL_API_KEY`,并校验 `Authorization: Bearer <token>` 或
`X-Shipping-Tool-Key` 是否命中;未配置时报服务不可用,缺失或错误时报未授权。
核心逻辑:对齐文件检核 Tool,只接受 `Authorization: Bearer <token>` 或
`X-Integration-Key`,并统一使用 `INTEGRATION_API_KEY` 作为服务端校验值;
未配置时报服务不可用,缺失或错误时报未授权。
"""
configured = str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip()
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
if not configured:
raise ServiceUnavailableError(
"SHIPPING_NOTICE_TOOL_API_KEY is not configured",
"INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
shipping_key = str(request.headers.get("X-Shipping-Tool-Key") or "").strip()
if configured in {token, shipping_key}:
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
if configured in {token, integration_key}:
return
if not token and not shipping_key:
if not token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
+92 -10
View File
@@ -65,7 +65,7 @@ def workspace_shipping_batches():
@workspace_shipping_notice_bp.route("/shipping-batches/create-from-notices", methods=["POST"])
def workspace_create_shipping_batch_from_notices():
"""接收多份发货通知附件,创建批次并为每份附件生成任务。"""
"""接收多份发货通知附件,创建批次并交给后台编排器逐票推进。"""
user, err = _require_user()
if err:
return err
@@ -121,8 +121,36 @@ def workspace_create_shipping_batch_from_notices():
"conversation_id": conversation_id or None,
"file_count": len(notice_items),
"notice_items": notice_items,
# 上传接口先快速完成建批/建任务与 raw_text 落库,避免请求阻塞;
# 后续首轮解析与可自动推进步骤交给后台编排线程逐票执行。
"defer_parse": True,
}
return jsonify(shipping_tools.create_batch_tasks(payload))
created = shipping_tools.create_batch_tasks(payload)
data = created.get("data") if isinstance(created, dict) else None
batch_data = data.get("batch") if isinstance(data, dict) else None
tasks_data = data.get("tasks") if isinstance(data, dict) else None
batch_no = str(created.get("batch_no") or (batch_data or {}).get("batch_no") or "").strip()
orchestrator_started = False
if batch_no:
from app.services.shipping_notice.batch_orchestrator import start_batch_orchestrator
orchestrator_started = start_batch_orchestrator(batch_no)
if isinstance(data, dict) and batch_no:
focus_task = get_focus_task_for_batch(batch_no, user.id)
if focus_task:
data["focus_task"] = serialize_task_summary(focus_task)
if isinstance(tasks_data, list):
data["tasks"] = tasks_data
data["orchestrator_started"] = orchestrator_started
if isinstance(created, dict):
base_message = str(created.get("message") or "").strip()
if orchestrator_started:
created["message"] = (
f"{base_message},后台已开始逐票处理。"
if base_message
else "后台已开始逐票处理。"
)
return jsonify(created)
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>", methods=["GET"])
@@ -222,7 +250,7 @@ def workspace_create_shipping_task():
@workspace_shipping_notice_bp.route("/shipping-tasks/create-from-notice", methods=["POST"])
def workspace_create_shipping_task_from_notice():
"""接收单个发货通知附件,建单后抽取文本并立即触发解析。"""
"""接收单个发货通知附件,建单后抽取文本并保存 raw_text,再交给后台编排器。"""
user, err = _require_user()
if err:
return err
@@ -277,13 +305,32 @@ def workspace_create_shipping_task_from_notice():
task.raw_content = text
db.session.commit()
payload = {"task_id": task_id}
parsed = shipping_tools.parse_notice(payload)
data = parsed.get("data") if isinstance(parsed, dict) else None
if isinstance(data, dict):
data["notice_upload"] = {"filename": upload.filename or "", **meta}
parsed["message"] = f"已上传发货通知文件并创建任务 {task_id}。{parsed.get('message') or ''}".strip()
return jsonify(parsed)
task = ShippingTask.query.filter_by(task_no=task_id).first()
if task:
task.source_file_name = str(upload.filename or "").strip() or task.source_file_name
task.source_file_type = str(getattr(upload, "mimetype", "") or "").strip() or task.source_file_type
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
orchestrator_started = start_task_orchestrator(task_id)
return jsonify(
{
"status": "ok",
"task_id": task_id,
"message": (
f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。"
if orchestrator_started
else f"已上传发货通知文件并创建任务 {task_id}。通知原文已保存。"
),
"data": {
"task": serialize_task_summary(task) if task else {"task_no": task_id},
"notice_upload": {"filename": upload.filename or "", **meta},
"parse_status": "deferred",
"orchestrator_started": orchestrator_started,
},
}
)
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>", methods=["GET"])
@@ -310,6 +357,26 @@ def workspace_shipping_task_chat_actions(task_no: str):
return jsonify(build_chat_actions_payload(task))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/retry", methods=["POST"])
def workspace_retry_shipping_task(task_no: str):
"""重试当前任务,适用于超时、解析失败或自动推进中断后的恢复。"""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
payload = {"task_id": task.task_no}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.retry_task(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/upload-inventory", methods=["POST"])
def workspace_upload_shipping_inventory(task_no: str):
"""用户态上传库存 Excel,并在服务端完成解析。"""
@@ -598,3 +665,18 @@ def workspace_shipping_task_export(task_no: str):
download_name=download_name,
mimetype=EXPORT_MIME_TYPE,
)
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/retry-pending", methods=["POST"])
def workspace_retry_shipping_batch_pending(batch_no: str):
"""重试批次中仍可自动推进的任务,跳过终态和人工阻断任务。"""
user, err = _require_user()
if err:
return err
batch = get_batch_for_user(batch_no, user.id)
if not batch:
return jsonify({"error": "Not found"}), 404
from app.services.shipping_notice.batch_orchestrator import retry_batch_pending_tasks
return jsonify(retry_batch_pending_tasks(batch.batch_no))
+16
View File
@@ -121,6 +121,22 @@ class Config:
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
)
# 建单后是否延后 parse_notice,交由 Dify 画布 LLM + Tool 解析(默认 true,符合 Dify 优先原则)
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'
)
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
)
SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS') or '180'
)
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(
os.getenv('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', '300')
)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
+2
View File
@@ -4,3 +4,5 @@ backend/app/jobs/handlers/__init__.py
用途:导入各 handler 模块以触发 @register_handler 注册。
逻辑:Wave 2 起在 worker 启动前 import 本包。
"""
from app.jobs.handlers import file_check_run, kb_clean, kb_dify_sync, schedule_run, shipping_notice_run, wecom_directory_sync # noqa: F401
@@ -0,0 +1,19 @@
"""
backend/app/jobs/handlers/shipping_notice_run.py
用途:货代发货单票后台任务 handler。
依赖:jobs.context、jobs.registry、shipping_notice.queue_service。
逻辑:统一由 worker 消费 `shipping_notice_run` 队列任务,再委托 shipping_notice.queue_service 执行单票。
"""
from __future__ import annotations
from app.jobs.context import JobContext
from app.jobs.registry import register_handler
from app.jobs.types import JobType
from app.services.shipping_notice.queue_service import run_shipping_notice_job
@register_handler(JobType.SHIPPING_NOTICE_RUN)
def run_shipping_notice(ctx: JobContext, payload: dict) -> None:
"""消费单票发货后台任务。"""
run_shipping_notice_job(payload, logger=ctx.logger)
+1
View File
@@ -14,6 +14,7 @@ class JobType(StrEnum):
KB_CLEAN = 'kb_clean'
KB_DIFY_SYNC = 'kb_dify_sync'
SHIPPING_NOTICE_RUN = 'shipping_notice_run'
SCHEDULE_RUN = 'schedule_run'
FILE_CHECK_RUN = 'file_check_run'
WECOM_DIRECTORY_SYNC = 'wecom_directory_sync'
+81 -2
View File
@@ -8,6 +8,7 @@ It is responsible for:
1) Forwarding chat requests from this system to Dify in streaming mode.
2) Relaying Dify SSE events to the frontend.
3) Aggregating answer text and metadata (retriever resources / attribution).
Chatflow 模式下来源在 knowledge-retrieval 的 node_finished.outputs.result。
4) Enriching retriever resources with original source-file download URLs via
the integration API mapping (dataset_id + remote_document_id).
5) Persisting chat logs to the local database.
@@ -623,7 +624,9 @@ class DifyService:
app_obj = current_app._get_current_object() if current_app else None
persist_data = json.loads(json.dumps(data, ensure_ascii=False, default=str))
resources_snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
# 优先使用已 enrich 并挂到 event 上的 retriever_resources(与 SSE 下发一致)
resources_for_persist = data.get('retriever_resources') or retriever_resources
resources_snapshot = json.loads(json.dumps(resources_for_persist, ensure_ascii=False, default=str))
attribution_snapshot = list(attribution_parts)
answer_snapshot = build_final_answer_text(persist_data, event_name)
latency_snapshot = int((time.time() - start_time) * 1000)
@@ -742,7 +745,11 @@ class DifyService:
data.get('conversation_id') or normalized_conversation_id,
)
if event == 'message':
if event == 'node_finished':
# [STEP] Chatflow 知识检索结果在 node_finished.outputs.result,不在 message_end
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, data)
elif event == 'message':
message_count += 1
if data.get('answer'):
has_sent_answer = True
@@ -770,6 +777,7 @@ class DifyService:
data['replace_answer'] = True
if event in ('message_end', 'workflow_finished'):
DifyService._attach_retriever_resources_to_event(data, retriever_resources)
persist_stream_chat(data, event)
if chat_perf_enabled():
perf_summary = perf.log_summary(current_app.logger if current_app else None)
@@ -1116,6 +1124,77 @@ class DifyService:
DifyService._merge_attribution_parts(attribution_parts, event_data.get('citation'))
DifyService._merge_attribution_parts(attribution_parts, metadata.get('citation'))
@staticmethod
def _normalize_knowledge_retrieval_result(item: Any) -> dict | None:
"""
将 Chatflow 知识检索节点的单条 result 规范化为 retriever_resource 结构。
核心逻辑:合并 metadata 中的 dataset/document/segment 字段到顶层,供前后端统一解析。
"""
if not isinstance(item, dict):
return None
metadata = item.get('metadata') if isinstance(item.get('metadata'), dict) else {}
document_name = (
item.get('document_name')
or metadata.get('document_name')
or item.get('title')
or metadata.get('title')
)
resource = {
**item,
'document_name': document_name,
'content': item.get('content') or metadata.get('content') or '',
'metadata': dict(metadata),
}
for key in ('dataset_id', 'dataset_name', 'document_id', 'segment_id', 'score'):
value = metadata.get(key) if metadata.get(key) not in (None, '') else item.get(key)
if value not in (None, '') and resource.get(key) in (None, ''):
resource[key] = value
return resource
@staticmethod
def _collect_knowledge_retrieval_from_node(retriever_resources: List[Any], event_data: dict):
"""
从 knowledge-retrieval 节点的 node_finished 事件提取检索来源。
核心逻辑:读取 data.outputs.result 列表,规范化后合并进 retriever_resources accumulator。
"""
if event_data.get('event') != 'node_finished':
return
node = event_data.get('data') if isinstance(event_data.get('data'), dict) else {}
if node.get('node_type') != 'knowledge-retrieval':
return
if node.get('status') not in (None, 'succeeded'):
return
outputs = node.get('outputs') if isinstance(node.get('outputs'), dict) else {}
results = outputs.get('result')
if not isinstance(results, list):
return
normalized: List[Any] = []
for item in results:
resource = DifyService._normalize_knowledge_retrieval_result(item)
if resource:
normalized.append(resource)
DifyService._merge_retriever_resources(retriever_resources, normalized)
@staticmethod
def _attach_retriever_resources_to_event(event_data: dict, retriever_resources: List[Any]):
"""
在 message_end / workflow_finished 下发前,把检索来源挂到 SSE 事件体。
核心逻辑:深拷贝 accumulator → enrich 源文件下载链接 → 写入 retriever_resources 与 metadata。
"""
if not retriever_resources:
return
snapshot = json.loads(json.dumps(retriever_resources, ensure_ascii=False, default=str))
DifyService._enrich_retriever_resources_with_source_urls(snapshot)
event_data['retriever_resources'] = snapshot
metadata = event_data.get('metadata') if isinstance(event_data.get('metadata'), dict) else {}
metadata['retriever_resources'] = snapshot
event_data['metadata'] = metadata
@staticmethod
def _extract_dify_ids(resource: dict):
"""
+141 -7
View File
@@ -8,6 +8,14 @@ from flask import current_app
class HRLeaveSQLServerService:
"""HR 假期查询服务。
用途:为“通用入口 / 人事规章”中的假期余额、明细类问题提供 SQL Server 查询。
依赖:chat.py 在识别到假期类意图后会调用本服务,查询结果再回写 ChatLog。
逻辑:先判断是否是假期查询,再识别是否为“查询他人假期”;若是则直接返回限制提示,
否则继续按当前登录用户的工号查询 HR 假期数据。
"""
_LEAVE_KEYWORDS = ("年假", "育儿假", "假期", "休假", "请假")
_PROCESS_KEYWORDS = (
"流程",
@@ -44,24 +52,139 @@ class HRLeaveSQLServerService:
r"(?:假期|年假|育儿假|休假).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少)",
r"(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:假期|年假|育儿假|休假)",
)
_OTHER_PERSON_PRONOUN_PATTERNS = (
r"(?:他|她|他们|她们|别人|其他人|同事).{0,8}(?:假期|年假|育儿假|休假)",
r"(?:查询|查下|查一下|帮我查|帮忙查|看看|核对).{0,8}(?:他|她|他们|她们|别人|其他人|同事)",
)
_PERSON_NAME_PATTERNS = (
r"(?:查询|查下|查一下|帮我查|帮忙查|看看|核对|想知道|统计).{0,4}(?P<name>[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假)",
r"(?P<name>[\u4e00-\u9fa5]{2,4})(?:的)?(?:年假|育儿假|假期|休假).{0,8}(?:还剩|还有|剩余|可休|已休|未休|多少|情况|记录|明细|查询)",
r"(?P<name>[\u4e00-\u9fa5]{2,4}).{0,6}(?:还剩|还有|剩余|可休|已休|未休|多少).{0,6}(?:年假|育儿假|假期|休假)",
)
_PERSON_NAME_STOPWORDS = {
"我的",
"我",
"本人",
"自己",
"假期",
"年假",
"育儿",
"育儿假",
"休假",
"请假",
"多少",
"还有",
"还剩",
"剩余",
"可休",
"已休",
"未休",
"情况",
"记录",
"明细",
"查询",
"帮我",
"帮忙",
"今年",
"去年",
"本年",
"公司",
"部门",
}
_OTHER_PERSON_QUERY_MESSAGE = "暂时不支持查询其他人假期"
@staticmethod
def supports(query: str) -> bool:
@classmethod
def supports(cls, query: str) -> bool:
"""判断是否应由 HR 假期模块接管。
AI 触发时机:用户问“我还有多少假期/年假/育儿假”,或试图查询他人假期时触发。
这样即使是“查张三还有多少假期”这类问句,也会先进入本服务统一拦截,
避免落回 Dify 产生不一致回答。
"""
text = (query or "").strip()
if not text:
return False
if not any(keyword in text for keyword in HRLeaveSQLServerService._LEAVE_KEYWORDS):
if not any(keyword in text for keyword in cls._LEAVE_KEYWORDS):
return False
if any(keyword in text for keyword in HRLeaveSQLServerService._PROCESS_KEYWORDS):
if any(keyword in text for keyword in cls._PROCESS_KEYWORDS):
return False
if any(re.search(pattern, text) for pattern in HRLeaveSQLServerService._STRONG_BALANCE_PATTERNS):
if any(re.search(pattern, text) for pattern in cls._STRONG_BALANCE_PATTERNS):
return True
if not any(keyword in text for keyword in HRLeaveSQLServerService._SELF_KEYWORDS):
if cls._looks_like_other_person_leave_query(text):
return True
if not any(keyword in text for keyword in cls._SELF_KEYWORDS):
return False
if any(keyword in text for keyword in HRLeaveSQLServerService._BALANCE_KEYWORDS):
if any(keyword in text for keyword in cls._BALANCE_KEYWORDS):
return True
return bool(re.search(r"(20\d{2}|今年|去年|本年)", text))
@classmethod
def _looks_like_other_person_leave_query(cls, query: str) -> bool:
"""粗判是否在询问他人假期。
用途:让“查张三假期”“其他人假期还有多少”这类问句优先进入本服务。
约束:这里只做路由级粗判,不能依赖当前登录人身份;最终是否判定为“查他人”
仍由 `_is_querying_other_person_leave()` 基于当前用户信息做二次确认。
"""
text = (query or "").strip()
if not text:
return False
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
return False
if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS):
return True
return bool(cls._extract_candidate_person_names(text))
@classmethod
def _extract_candidate_person_names(cls, query: str) -> list[str]:
"""提取问句中疑似“被查询人姓名”的候选词。
用途:识别“张三的年假还有多少”这类显式姓名问句。
约束:只返回 2-4 位中文候选词,并过滤常见假期业务词,避免把“多少/今年”等噪音误识别成姓名。
"""
text = (query or "").strip()
candidates: list[str] = []
for pattern in cls._PERSON_NAME_PATTERNS:
for match in re.finditer(pattern, text):
name = (match.groupdict().get("name") or "").strip()
if not name or name in cls._PERSON_NAME_STOPWORDS:
continue
if any(keyword in name for keyword in cls._SELF_KEYWORDS):
continue
if any(keyword in name for keyword in cls._BALANCE_KEYWORDS):
continue
if any(keyword in name for keyword in cls._LEAVE_KEYWORDS):
continue
candidates.append(name)
# 去重并保持原有顺序,避免重复命中同一个人名。
return list(dict.fromkeys(candidates))
@classmethod
def _is_querying_other_person_leave(cls, query: str, user) -> bool:
"""判断本次假期查询是否在查询他人。
AI 触发时机:当问句已经被识别为假期查询时调用。
核心逻辑:先识别“他/她/其他人/同事”等代词,再识别显式姓名;
若候选姓名与当前登录人的姓名/工号/用户名都不一致,则视为查询他人。
"""
text = (query or "").strip()
if not text:
return False
if any(keyword in text for keyword in cls._SELF_KEYWORDS):
return False
if any(re.search(pattern, text) for pattern in cls._OTHER_PERSON_PRONOUN_PATTERNS):
return True
self_identifiers = {
str(getattr(user, "real_name", None) or "").strip(),
str(getattr(user, "username", None) or "").strip(),
str(getattr(user, "employee_id", None) or "").strip(),
}
self_identifiers = {value for value in self_identifiers if value}
for candidate in cls._extract_candidate_person_names(text):
if candidate not in self_identifiers:
return True
return False
@staticmethod
def _detect_leave_type(query: str) -> str:
text = (query or "").strip()
@@ -267,6 +390,17 @@ WHERE c002001 = ?
start_time = time.time()
final_conversation_id = conversation_id or f"hr_{int(time.time())}"
try:
if cls._is_querying_other_person_leave(query, user):
end_data = {
"event": "message_end",
"answer": cls._OTHER_PERSON_QUERY_MESSAGE,
"replace_answer": True,
"chat_log_id": None,
"conversation_id": final_conversation_id,
}
yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
return
employee_code = cls._get_employee_code(user)
leave_type = cls._detect_leave_type(query)
year = cls._extract_year(query)
@@ -0,0 +1,342 @@
"""
services/shipping_notice/batch_orchestrator.py
用途:发货通知批次/单票后台编排器。
依赖:query_service、task_workflow、dify_executor、shipping_notice.tools、tool_common。
逻辑:工作台上传后由后端主导单票调度;批次线程只做任务派发,created 票通过 Dify 完成 AI 解析,其余确定性步骤由后端 auto_progress 推进。
"""
from __future__ import annotations
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any
from flask import current_app
from app import db
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 auto_progress_enabled, cfg_bool, cfg_int, log_task_event
from app.services.shipping_notice.tools import auto_progress
_RUNNING_BATCHES: set[str] = set()
_RUNNING_TASKS: set[str] = set()
_TERMINAL_PROCESS_STATUSES = frozenset({"uploaded", "completed", "closed", "rejected"})
def batch_orchestrator_enabled() -> bool:
"""是否启用发货通知后台批次编排器。"""
return cfg_bool("SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED", True)
def batch_dispatch_concurrency() -> int:
"""单个批次最多并发派发多少张票。"""
return cfg_int("SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY", 3, min_value=1)
def _normalize_ref(value: str | None) -> str:
return str(value or "").strip().upper()
def _mark_running(bucket: set[str], key: str) -> bool:
normalized = _normalize_ref(key)
if not normalized:
return False
if normalized in bucket:
return False
bucket.add(normalized)
return True
def _unmark_running(bucket: set[str], key: str) -> None:
normalized = _normalize_ref(key)
if not normalized:
return
bucket.discard(normalized)
def _should_orchestrate_task(task: Any) -> bool:
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
if process_status in _TERMINAL_PROCESS_STATUSES:
return False
if getattr(task, "review_status", None):
return False
if getattr(task, "pending_human_reason", None):
return False
if process_status in {"waiting_inventory", "waiting_upload", "upload_failed"}:
return False
return True
def _is_retryable_task(task: Any) -> bool:
"""判断任务是否允许由批次重试入口重新派发。"""
process_status = str(getattr(task, "process_status", "") or "").strip().lower()
if process_status in _TERMINAL_PROCESS_STATUSES:
return False
if getattr(task, "review_status", None):
return False
if getattr(task, "pending_human_reason", None):
return False
return True
def _refresh_batch_focus(task_no: str) -> None:
task = get_task_by_ref(task_no)
if not task or not task.batch:
return
task.batch.current_focus_task_no = task.task_no
recompute_batch_summary(task.batch)
db.session.commit()
def _run_single_task(task_no: str) -> dict[str, str | None]:
"""
后台执行单票任务的一轮推进。
`created` 先由 Dify 做单票解析,其余状态尝试走 auto_progress;进入人工检查点时自然返回。
"""
normalized_task_no = _normalize_ref(task_no)
if not normalized_task_no:
return {"status": "missing", "message": "task_no is required"}
if not _mark_running(_RUNNING_TASKS, normalized_task_no):
return {"status": "skipped", "message": "task already running"}
try:
task = get_task_by_ref(normalized_task_no)
if not task:
return {"status": "missing", "message": "task not found"}
if not _should_orchestrate_task(task):
return {
"status": "skipped",
"message": f"skip process_status={task.process_status or ''}",
}
_refresh_batch_focus(task.task_no)
task = get_task_by_ref(normalized_task_no)
assert task is not None
log_task_event(
task,
"backend_orchestrator_task_started",
{"process_status": task.process_status, "current_step": task.current_step},
)
db.session.commit()
payload: dict[str, Any] = {"task_id": task.task_no, "conversation_id": task.conversation_id}
if str(task.process_status or "").strip().lower() == "created":
result = run_shipping_parse_via_dify(task.task_no)
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,
}
else:
payload["mode"] = "auto"
result = auto_progress(payload)
if current_app:
current_app.logger.info(
"[shipping-orchestrator] auto-progress task_no=%s status=%s process_status_before=%s current_step_before=%s message=%s",
task.task_no,
result.get("status"),
task.process_status,
task.current_step,
str(result.get("message") or "")[:300],
)
refreshed = get_task_by_ref(normalized_task_no)
if refreshed:
if refreshed.batch:
recompute_batch_summary(refreshed.batch)
log_task_event(
refreshed,
"backend_orchestrator_task_finished",
{
"result_status": str(result.get("status") or ""),
"process_status": refreshed.process_status,
"current_step": refreshed.current_step,
},
)
db.session.commit()
return {
"status": str(result.get("status") or ""),
"message": str(result.get("message") or "")[:500] or None,
}
except Exception as exc:
db.session.rollback()
task = get_task_by_ref(normalized_task_no)
if task:
task.error_message = str(exc)
log_task_event(task, "backend_orchestrator_task_failed", {"error": str(exc)[:1000]})
if task.batch:
recompute_batch_summary(task.batch)
db.session.commit()
return {"status": "failed", "message": str(exc)[:500] or "background task failed"}
finally:
db.session.remove()
_unmark_running(_RUNNING_TASKS, normalized_task_no)
def _background_task_runner(app: Any, task_no: str) -> None:
try:
with app.app_context():
_run_single_task(task_no)
finally:
_unmark_running(_RUNNING_BATCHES, f"TASK::{task_no}")
def _background_batch_runner(app: Any, batch_no: str) -> None:
normalized_batch_no = _normalize_ref(batch_no)
try:
with app.app_context():
batch = get_batch_by_no(normalized_batch_no)
if not batch:
return
recompute_batch_summary(batch)
db.session.commit()
task_nos = [task.task_no for task in list_sorted_batch_tasks(batch)]
if not task_nos:
return
max_workers = min(batch_dispatch_concurrency(), len(task_nos))
if max_workers <= 1:
for task_no in task_nos:
_refresh_batch_focus(task_no)
_run_single_task(task_no)
batch = get_batch_by_no(normalized_batch_no)
if not batch:
break
else:
app_obj = current_app._get_current_object()
with ThreadPoolExecutor(
max_workers=max_workers,
thread_name_prefix=f"shipping-batch-{normalized_batch_no}",
) as executor:
future_map = {
executor.submit(_run_task_with_app_context, app_obj, task_no): task_no
for task_no in task_nos
}
for future in as_completed(future_map):
task_no = future_map[future]
try:
future.result()
except Exception as exc:
task = get_task_by_ref(task_no)
if task:
task.error_message = str(exc)
log_task_event(
task,
"backend_orchestrator_task_failed",
{"error": str(exc)[:1000], "source": "batch_dispatcher"},
)
if task.batch:
recompute_batch_summary(task.batch)
db.session.commit()
batch = get_batch_by_no(normalized_batch_no)
if batch:
recompute_batch_summary(batch)
db.session.commit()
finally:
db.session.remove()
_unmark_running(_RUNNING_BATCHES, normalized_batch_no)
def start_task_orchestrator(task_no: str | None) -> bool:
"""将单票后台任务写入持久化队列。"""
normalized_task_no = _normalize_ref(task_no)
if not normalized_task_no or not batch_orchestrator_enabled():
return False
ok, result = enqueue_shipping_notice_job(task_no=normalized_task_no)
return ok and result in {"queued_for_worker", "already_queued", "done", "ok", "running", "needs_human", "skipped"}
def start_batch_orchestrator(batch_no: str | None) -> bool:
"""批次入口改为逐票入队,由 worker 消费,不再在 web 进程内起长线程。"""
normalized_batch_no = _normalize_ref(batch_no)
if not normalized_batch_no or not batch_orchestrator_enabled():
return False
batch = get_batch_by_no(normalized_batch_no)
if not batch:
return False
started = False
for task in list_sorted_batch_tasks(batch):
ok, _result = enqueue_shipping_notice_job(
task_no=task.task_no,
created_by_id=getattr(batch, "user_id", None),
batch_no=batch.batch_no,
)
started = started or ok
recompute_batch_summary(batch)
db.session.commit()
return started
def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]:
"""重试批次中仍可自动推进的任务,跳过已终态和人工阻断任务。"""
normalized_batch_no = _normalize_ref(batch_no)
if not normalized_batch_no:
return {"status": "failed", "message": "batch_no is required"}
batch = get_batch_by_no(normalized_batch_no)
if not batch:
return {"status": "failed", "message": "batch not found"}
started = 0
skipped = 0
for task in list_sorted_batch_tasks(batch):
if not _is_retryable_task(task):
skipped += 1
continue
if start_task_orchestrator(task.task_no):
started += 1
else:
skipped += 1
recompute_batch_summary(batch)
db.session.commit()
return {
"status": "ok",
"batch_no": batch.batch_no,
"started": started,
"skipped": skipped,
"message": f"已为批次 {batch.batch_no} 重试 {started} 个任务,跳过 {skipped} 个任务。",
}
def _run_task_with_app_context(app: Any, task_no: str) -> dict[str, str | None]:
"""批次派发时为单票补充独立 app/db 上下文,避免批次线程串行阻塞。"""
with app.app_context():
return _run_single_task(task_no)
@@ -0,0 +1,348 @@
"""
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 的单票解析指令。"""
pieces = [
"你正在处理货代发货通知任务。",
f"当前任务编号:{task_no}。",
]
if batch_no:
pieces.append(f"所属批次:{batch_no}。")
pieces.extend(
[
"只允许处理当前这一票,禁止切换任务、禁止整批循环、禁止调用 switch_focus_task。",
"先调用 get_task_status 获取当前任务状态和 raw_text。",
"如果当前任务已经不是待解析状态,或已经进入人工确认/下游阶段,请直接总结当前状态并结束。",
"如果当前任务仍待解析,请基于 raw_text 用 LLM 抽取结构化字段,并调用 parse_notice(structured=...) 落库。",
"禁止再次询问用户“是否开始解析”。",
"完成后只返回当前票的简短解析结果摘要。",
]
)
return "".join(pieces)
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 _update_chat_session_after_stream(
session: ChatSession | None,
*,
provider_conversation_id: str | None,
status: str,
) -> None:
if not session:
return
provider_id = str(provider_conversation_id or "").strip() or None
changed = False
if provider_id and session.external_conversation_id != provider_id:
session.external_conversation_id = provider_id
changed = True
if status and session.status != status:
session.status = status
changed = True
session.last_active_at = datetime.utcnow()
session.updated_at = datetime.utcnow()
changed = True
if changed:
db.session.commit()
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 解析 + parse_notice”这一步。
"""
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
)
provider_conversation_id = (
str(getattr(session, "external_conversation_id", "") or "").strip() or None
)
inputs = build_dify_chat_inputs(
local_conversation_id,
task_id=task.task_no,
batch_no=batch_no,
entry_mode="orchestrator_parse",
user_message="",
trigger_source="backend_orchestrator",
)
request_id = f"shipping-orch-{task.task_no}"
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,
)
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()
_update_chat_session_after_stream(
session,
provider_conversation_id=provider_conversation_id,
status="error",
)
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"}
_update_chat_session_after_stream(
session,
provider_conversation_id=provider_conversation_id,
status=terminal_status,
)
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,
}
@@ -1,21 +1,23 @@
"""
services/shipping_notice/dify_inputs.py
用途:构建发货通知 Dify Chatflow 需要的输入变量,如 Tool API Base URL 和 Tool API Key。
依赖:agent_resolver、tool_api_url、Flask current_app 配置。
逻辑:由聊天 Agent 入口或 Dify 调用准备逻辑引用本文件,把环境相关变量注入到 Dify 请求上下文。
用途:识别发货通知 Dify Chatflow Agent,并构建会话级 Dify inputs。
依赖:agent_resolver、models.ShippingBatch/ShippingTask。
逻辑:由 api/chat 在调用 DifyService.stream_chat 前引用;本模块按会话号解析当前批次/任务焦点,
把 Dify 画布需要的 conversation_id、current_batch_no、current_task_no 注入 Start 节点变量。
"""
from __future__ import annotations
from flask import current_app
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
# Dify Chatflow input variable names — must match canvas Start / 输入变量配置.
HXOPS_TOOLS_API_BASE_INPUT = "HXOPS_TOOLS_API_BASE"
HXOPS_TOOL_API_KEY_INPUT = "hxops_tool_api_key"
SHIPPING_CONVERSATION_ID_INPUT = "conversation_id"
SHIPPING_CURRENT_BATCH_NO_INPUT = "current_batch_no"
SHIPPING_CURRENT_TASK_NO_INPUT = "current_task_no"
SHIPPING_ENTRY_MODE_INPUT = "entry_mode"
SHIPPING_USER_MESSAGE_INPUT = "user_message"
SHIPPING_TRIGGER_SOURCE_INPUT = "trigger_source"
def is_shipping_notice_chat_agent(agent) -> bool:
@@ -23,14 +25,78 @@ def is_shipping_notice_chat_agent(agent) -> bool:
return getattr(agent, "name", None) == CHAT_AGENT_NAME
def build_dify_chat_inputs() -> dict[str, str]:
"""构建 Dify Chatflow 输入变量(Tool API Base URL 与 API Key)。"""
base = resolve_tool_api_base_url()
key = str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip()
inputs: dict[str, str] = {}
if base:
inputs[HXOPS_TOOLS_API_BASE_INPUT] = base
if key:
inputs[HXOPS_TOOL_API_KEY_INPUT] = key
return inputs
def _latest_batch_for_conversation(conversation_id: str) -> ShippingBatch | None:
"""按会话号获取最近一个发货批次,用于恢复当前批次焦点。"""
conv_id = str(conversation_id or "").strip()
if not conv_id:
return None
return (
ShippingBatch.query.filter_by(conversation_id=conv_id)
.order_by(ShippingBatch.id.desc())
.first()
)
def _latest_task_for_conversation(conversation_id: str) -> ShippingTask | None:
"""按会话号获取最近一个未拒绝任务,用于恢复当前任务焦点。"""
conv_id = str(conversation_id or "").strip()
if not conv_id:
return None
return (
ShippingTask.query.filter_by(conversation_id=conv_id)
.filter(ShippingTask.process_status.notin_(["rejected"]))
.order_by(ShippingTask.id.desc())
.first()
)
def build_dify_chat_inputs(
conversation_id: str | None = None,
*,
task_id: str | None = None,
batch_no: str | None = None,
entry_mode: str | None = None,
user_message: str | None = None,
trigger_source: str | None = None,
) -> dict[str, str]:
"""
构建发货通知 Dify Chatflow inputs。
OpenAPI 工具已在 Dify 侧配置 Server URL 与 Authorization / X-Integration-Key,
无需再注入 HXOPS_TOOLS_API_BASE;这里只补会话级上下文,供 Dify 画布稳定读取当前 task/batch。
"""
conv_id = str(conversation_id or "").strip()
if not conv_id:
return {}
explicit_task_no = str(task_id or "").strip().upper()
explicit_batch_no = str(batch_no or "").strip().upper()
batch = _latest_batch_for_conversation(conv_id)
task = _latest_task_for_conversation(conv_id)
current_task_no = explicit_task_no
if not current_task_no and batch and batch.current_focus_task_no:
current_task_no = str(batch.current_focus_task_no or "").strip().upper()
elif not current_task_no and task and task.task_no:
current_task_no = str(task.task_no or "").strip().upper()
current_batch_no = explicit_batch_no
if not current_batch_no and batch and batch.batch_no:
current_batch_no = str(batch.batch_no or "").strip().upper()
elif (
not current_batch_no
and task
and getattr(task, "batch", None) is not None
and getattr(task.batch, "batch_no", None)
):
current_batch_no = str(task.batch.batch_no or "").strip().upper()
return {
SHIPPING_ENTRY_MODE_INPUT: str(entry_mode or "").strip(),
SHIPPING_CONVERSATION_ID_INPUT: conv_id,
SHIPPING_CURRENT_BATCH_NO_INPUT: current_batch_no,
SHIPPING_CURRENT_TASK_NO_INPUT: current_task_no,
SHIPPING_USER_MESSAGE_INPUT: str(user_message or "").strip(),
SHIPPING_TRIGGER_SOURCE_INPUT: str(trigger_source or "").strip(),
}
@@ -3,7 +3,7 @@ services/shipping_notice/extract.py
用途:抽取发货通知中的单头字段与订单行,并在收尾阶段补充文档级字段和告警。
依赖:po_number、reservation_id、notice_lines 中的标准化与回填工具。
逻辑:由 task_workflow.parse_notice 调用本文件完成原始文本解析,再把结果交给 parse_summary 和状态机链路。
逻辑:由 task_workflow.parse_notice 调用;优先 Dify 传入的 structured,无则走后端启发式规则兜底。
"""
from __future__ import annotations
@@ -29,11 +29,14 @@ def _finalize_notice_parse(
base_confidence: float,
raw_text: str = "",
) -> tuple[dict[str, Any], float, list[str]]:
parse_source = parsed.get("parse_source")
lines = normalize_notice_lines(parsed.get("lines") if isinstance(parsed.get("lines"), list) else [])
parsed = enrich_notice_with_document_reservation({**parsed, "lines": lines}, raw_text=raw_text)
parsed = enrich_notice_with_document_required_date(parsed)
parsed = enrich_notice_with_document_currency(parsed)
parsed = enrich_notice_with_po_number(parsed, raw_text=raw_text)
if parse_source:
parsed["parse_source"] = parse_source
lines = parsed.get("lines") if isinstance(parsed.get("lines"), list) else []
warnings = validate_notice_lines(lines)
from app.services.shipping_notice.notice_lines import notice_parse_completeness
@@ -52,12 +55,16 @@ def extract_notice_fields(
) -> tuple[dict[str, Any], float, list[str]]:
"""
抽取发货通知单头与订单行,并计算置信度与 warnings。
【AI 触发时机】:由 parse_notice 内部调用;Agent 应调 parse_notice 而非直接调用本函数。
【AI 触发时机】:由 parse_notice Tool 调用;Dify 画布/Agent 应先用 LLM 产出 structured 再传入,勿依赖本函数做 LLM 抽取。
解析优先级:
1. structured:Dify LLM/画布已抽取并传入 parse_notice
2. 后端启发式规则(_heuristic_extract,仅作 Dify 无法实现时的兜底)
Args:
raw_text: 发货通知正文。
source_type: 来源类型(manual/pdf/email 等)。
structured: Dify/上游已结构化的解析结果(优先使用)。
structured: Dify 编排产出的结构化解析结果(最高优先级)。
notice_files: 附件元数据列表(预留)。
Returns:
@@ -66,15 +73,22 @@ def extract_notice_fields(
warnings: list[str] = []
if structured and isinstance(structured, dict):
return _finalize_notice_parse(
structured,
payload = {**structured, "parse_source": structured.get("parse_source") or "dify"}
parsed, confidence, line_warnings = _finalize_notice_parse(
payload,
base_confidence=float(structured.get("confidence") or 0.95),
raw_text=str(structured.get("raw_text") or ""),
raw_text=str(structured.get("raw_text") or raw_text),
)
warnings.extend(line_warnings)
return parsed, confidence, warnings
warnings.append("parse_fallback_heuristic")
heuristic, confidence, heuristic_warnings = _heuristic_extract(raw_text)
warnings.extend(heuristic_warnings)
return _finalize_notice_parse(heuristic, base_confidence=confidence, raw_text=raw_text)
heuristic["parse_source"] = "heuristic"
parsed, confidence, line_warnings = _finalize_notice_parse(heuristic, base_confidence=confidence, raw_text=raw_text)
warnings.extend(line_warnings)
return parsed, confidence, warnings
def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]:
@@ -29,6 +29,7 @@ from app.services.shipping_notice.match import format_match_summary, match_notic
from app.services.shipping_notice.query_service import (
resolve_task_from_payload,
serialize_task_for_tool,
task_export_error_message,
)
from app.services.shipping_notice.reservation_id import extract_reservation_id
from app.services.shipping_notice.rpa import write_upload_trigger
@@ -37,7 +38,7 @@ from app.services.shipping_notice.rpa_attempts import (
upload_rpa_attempts,
)
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import prepend_tool_message
from app.services.shipping_notice.tool_common import prepend_tool_message, set_task_step_progress
from app.services.shipping_notice.tool_response import tool_response
@@ -95,10 +96,9 @@ def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] |
def match_completed(task: ShippingTask) -> bool:
"""判断任务是否已完成可履约的库存匹配(process_status=matched 且 line_results 非空)。"""
"""判断任务是否已完成可履约的库存匹配(fulfillable 且 line_results 非空)。"""
return bool(
task.process_status == "matched"
and task.match_status
task.match_status == "fulfillable"
and isinstance(task.line_results_json, list)
and len(task.line_results_json) > 0
)
@@ -214,10 +214,23 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
if lang:
inv_payload["lang"] = lang
return ensure_inventory(inv_payload)
notice_lines = task.lines_json or []
total_notice_lines = len(notice_lines) if isinstance(notice_lines, list) else 0
set_task_step_progress(
task,
step_key="step5_match_inventory",
step_title="匹配库存",
status="running",
message="正在执行库存匹配",
progress_percent=10,
current=0,
total=total_notice_lines or None,
detail="按 SKU + Reservation ID 逐行比对需求与库存",
)
db.session.flush()
# [STEP 2] 校验 Reservation ID 前置条件。
# 当前匹配规则要求订单侧必须具备 Reservation ID,缺失时要先打回上游解析而不是继续匹配。
notice_lines = task.lines_json or []
order_missing = [
{"sku": str(line.get("sku") or "").strip(), "reservation_id": str(line.get("reservation_id") or "").strip()}
for line in (notice_lines if isinstance(notice_lines, list) else [])
@@ -254,15 +267,47 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
# [STEP 3] 执行匹配并按结果分流。
# fulfillable 时继续走自动串联;shortage/异常时停在人审确认,避免误生成 Excel 或误上传。
def _on_match_progress(processed: int, total: int) -> None:
percent = 10 if total <= 0 else min(95, max(10, int(processed * 100 / total)))
set_task_step_progress(
task,
step_key="step5_match_inventory",
step_title="匹配库存",
status="running",
message="正在执行库存匹配",
progress_percent=percent,
current=processed,
total=total,
detail=f"已匹配 {processed}/{total} 行",
)
if processed == total or processed % 50 == 0:
db.session.flush()
match_status, line_results, shortage = match_notice_lines(
notice_lines,
task.inventory_lines_json or [],
progress_callback=_on_match_progress,
)
if inv_missing_count and isinstance(shortage, dict):
shortage.pop("warnings", None)
task.match_status = match_status
task.line_results_json = line_results
task.shortage_json = shortage
set_task_step_progress(
task,
step_key="step5_match_inventory",
step_title="匹配库存",
status="needs_human" if match_status != "fulfillable" else "completed",
message="库存匹配已完成",
progress_percent=100,
current=len(line_results),
total=len(line_results),
detail=(
f"已匹配 {len(line_results)}/{len(line_results)} 行,全部订单行库存满足"
if match_status == "fulfillable"
else f"已匹配 {len(line_results)}/{len(line_results)} 行,存在缺口,需人工处理"
),
)
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() or None
match_summary = format_match_summary(
@@ -300,7 +345,7 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
基于已匹配任务生成货代发货 Excel 并推进至 waiting_upload。
【AI 触发时机】:match_inventory 返回 fulfillable 且用户需下载/上传 Excel 时调用;未匹配前禁止调用。
核心逻辑:excel_gate_error 门禁 → generate_shipment_excel → 写 export_file_path → WAITING_UPLOAD。
核心逻辑:已有导出文件时直接返回成功;否则走 excel_gate_error 门禁 → generate_shipment_excel → 写 export_file_path → WAITING_UPLOAD。
Args:
payload: 须含 task_id 或 conversation_id。
@@ -312,8 +357,18 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
if not task:
return tool_response(status="failed", message="未找到任务编号")
# [STEP 1] 先校验是否满足导出门禁。
# 只有库存匹配完成后才允许生成货代 Excel,避免基于未确认数据导出。
# [STEP 1] 若任务已有可下载的导出文件,则直接返回成功,保证重复点击“生成 Excel”幂等。
# 这里不重复生成文件,避免任务已进入 waiting_upload 后再次点击却被旧门禁误判为“未完成匹配”。
if task.export_file_path and not task_export_error_message(task):
return tool_response(
status="ok",
task_id=task.task_no,
message=f"发货 Excel 已生成:{task.export_file_name or task.export_file_path}",
data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"},
)
# [STEP 2] 先校验是否满足导出门禁。
# 只有库存匹配完成后才允许生成货代 Excel;但 waiting_upload/uploaded 仍应视为“已完成匹配”。
gate_error = excel_gate_error(task)
if gate_error:
return tool_response(
@@ -324,13 +379,31 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
forbidden_next_tools=["upload_to_freight"],
next_required_action="match_inventory(须先完成库存上传与字段对齐确认)",
)
set_task_step_progress(
task,
step_key="step6_generate_file",
step_title="生成发货文件",
status="running",
message="正在生成发货 Excel",
progress_percent=60,
detail="正在按货代模板填充全部应发行",
)
# [STEP 2] 生成文件并把任务推进到等待上传阶段。
# [STEP 3] 生成文件并把任务推进到等待上传阶段。
# 导出文件路径会成为后续 RPA 上传或人工下载的唯一输入。
path, filename = generate_shipment_excel(task)
task.export_file_path = path
task.export_file_name = filename
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
set_task_step_progress(
task,
step_key="step6_generate_file",
step_title="生成发货文件",
status="completed",
message="发货 Excel 已生成",
progress_percent=100,
detail=filename,
)
log_task_event(task, "export_generated", {"file_name": filename})
db.session.commit()
return tool_response(
@@ -380,6 +453,21 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
human_options=[],
)
apply_task_transition(task, TaskTransition.UPLOADED)
task.upload_finished_at = datetime.utcnow()
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="completed",
message="已确认手工上传货代完成",
progress_percent=100,
detail="任务已完成",
)
# [STEP 2.1] 手工上传确认属于任务终态写路径,需要同步刷新批次汇总,
# 否则聊天顶部批次卡片仍会读取旧的 process_summary_json,显示成未完成。
from app.services.shipping_notice.task_workflow import sync_batch_after_task_change
sync_batch_after_task_change(task)
ref = str(payload.get("freight_ref_no") or "").strip()
if ref:
task.freight_ref_no = ref
@@ -461,6 +549,17 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
if queued and trigger:
apply_task_transition(task, TaskTransition.UPLOAD_RPA_PENDING)
attempt_no = attempts + 1
task.upload_started_at = datetime.utcnow()
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="running",
message="已触发 RPA 上传货代,等待回执",
current=attempt_no,
total=max_attempts,
detail=f"第 {attempt_no}/{max_attempts} 次上传尝试",
)
log_task_event(
task,
"upload_rpa_triggered",
@@ -488,6 +587,15 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
)
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="needs_human",
message="RPA 自动上传失败,请人工接管",
progress_percent=100,
detail="请下载 Excel 手工上传后确认完成",
)
task.error_message = "RPA 上传目录未配置或触发失败"
log_task_event(task, "upload_rpa_pending", {})
db.session.commit()
@@ -519,6 +627,16 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
success = bool(payload.get("success", True))
if success:
apply_task_transition(task, TaskTransition.UPLOADED)
task.upload_finished_at = datetime.utcnow()
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="completed",
message="RPA 已成功上传货代系统",
progress_percent=100,
detail="任务已完成",
)
task.freight_ref_no = str(payload.get("freight_ref_no") or "").strip() or None
log_task_event(task, "upload_rpa_success", {"freight_ref_no": task.freight_ref_no})
db.session.commit()
@@ -533,6 +651,16 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
)
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
task.upload_finished_at = datetime.utcnow()
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="needs_human",
message="货代上传失败,等待人工处理",
progress_percent=100,
detail="可重试上传或改为手工上传",
)
task.error_message = str(payload.get("error_message") or "RPA upload failed")[:500]
log_task_event(task, "upload_rpa_failed", {"error": task.error_message})
db.session.flush()
@@ -27,6 +27,7 @@ from app.services.shipping_notice.tool_common import (
auto_progress_enabled,
log_task_event,
payload_wants_auto_chain_fallback,
set_task_step_progress,
)
from app.services.shipping_notice.tool_response import tool_response
from app.services.shipping_notice.constants import RS_ALIGN_REVIEW
@@ -143,6 +144,19 @@ def inventory_mapping_checkpoint_response(
"field_alignment": field_alignment,
**extra,
}
set_task_step_progress(
task,
step_key="step4_align_confirm",
step_title="确认字段对齐",
status="needs_human",
message="请确认库存字段对齐后再继续匹配",
progress_percent=100,
current=3,
total=3,
detail="系统已识别必填列映射,请先人工确认",
extra={"field_alignment": field_alignment},
)
db.session.flush()
# [STEP 2] 明确停在人审检查点。
# 返回值必须阻止同轮继续调用 match_inventory,确保用户先确认字段对齐。
return tool_response(
@@ -253,6 +267,17 @@ def inventory_loaded_response(
# 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。
task.inventory_lines_json = inventory_lines
field_alignment = field_alignment_for_task(task, column_meta)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running" if require_mapping_review else "completed",
message=f"已载入库存 {len(inventory_lines)} 行",
progress_percent=100,
current=len(inventory_lines),
total=len(inventory_lines),
detail="库存快照已就绪,正在进入字段对齐阶段" if require_mapping_review else "库存快照已就绪,可进入匹配阶段",
)
# [STEP 2] 如果当前策略要求映射复核,则先进入对齐确认检查点。
# 同时尝试自动串联;只有自动串联没有吃掉结果时,才真正返回给用户确认映射。
@@ -30,7 +30,11 @@ from app.services.shipping_notice.rpa_attempts import (
max_rpa_inventory_attempts,
)
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import log_task_event, rpa_inventory_timeout_seconds
from app.services.shipping_notice.tool_common import (
log_task_event,
rpa_inventory_timeout_seconds,
set_task_step_progress,
)
from app.services.shipping_notice.tool_response import tool_response
@@ -136,6 +140,17 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]
trigger = write_inventory_export_trigger(task.task_no, {"mode": mode, "attempt": attempt_no})
if trigger:
apply_task_transition(task, TaskTransition.RPA_PENDING)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running",
message="已触发 RPA 库存导出,等待结果",
progress_percent=60,
current=attempt_no,
total=max_attempts,
detail=f"第 {attempt_no}/{max_attempts} 次尝试",
)
log_task_event(task, "inventory_rpa_triggered", {"trigger": trigger, "attempt": attempt_no})
if attempt_no >= max_attempts and not task.inventory_lines_json:
@@ -225,6 +240,15 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
processed = inventory_processed_dir()
lines, column_meta = ingest_inventory_file(path, move_to=processed)
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running",
message="RPA 库存文件已返回,正在读取库存快照",
progress_percent=85,
detail=f"正在读取 {path.name}",
)
return inventory_loaded_response(
task,
lines,
@@ -49,7 +49,7 @@ from app.services.shipping_notice.query_service import (
serialize_task_for_tool,
)
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_common import log_task_event
from app.services.shipping_notice.tool_common import log_task_event, set_task_step_progress
from app.services.shipping_notice.tool_response import tool_response
@@ -385,6 +385,16 @@ def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
)
try:
set_task_step_progress(
task,
step_key="step3_inventory_prepare",
step_title="获取库存",
status="running",
message="正在上传并解析库存文件",
progress_percent=35,
detail=f"正在处理库存文件 {filename}",
)
db.session.flush()
save_task_inventory_upload(task.task_no, upload)
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
@@ -8,7 +8,7 @@ services/shipping_notice/match.py
from __future__ import annotations
from typing import Any
from typing import Any, Callable
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.reservation_id import extract_reservation_id
@@ -60,6 +60,8 @@ def _available_for_notice_line(
def match_notice_lines(
notice_lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
*,
progress_callback: Callable[[int, int], None] | None = None,
) -> tuple[str, list[dict[str, Any]], dict[str, Any]]:
"""
将订单行与库存行按 (sku, reservation_id) 匹配,计算 fulfillable/partial/unfulfillable。
@@ -78,7 +80,8 @@ def match_notice_lines(
has_shortage = False
# [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。
for line in notice_lines:
total_lines = len(notice_lines)
for index, line in enumerate(notice_lines, start=1):
sku = _norm(line.get("sku"))
reservation_id = _norm_reservation(line.get("reservation_id")) or None
try:
@@ -110,6 +113,8 @@ def match_notice_lines(
line_results.append(result)
if shortage > 0:
shortages.append(result)
if progress_callback is not None:
progress_callback(index, total_lines)
# [STEP 3] 汇总整体 match_status(fulfillable / partial / unfulfillable)。
if not notice_lines:
@@ -79,7 +79,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"info": {
"title": "Hxops Shipping Notice Tools",
"version": "1.0.0",
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。",
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。鉴权:Authorization Bearer 或 X-Integration-Key。",
},
"servers": [{"url": server}],
"paths": {
@@ -115,6 +115,12 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
{
"task_id": task_id,
"raw_text": _str_prop("待解析的发货通知全文"),
"structured": {
"type": "object",
"description": "Dify LLM 解析后的结构化结果对象。若提供,后端优先使用该对象中的 lines/confidence/reservation_id 等字段落库。",
"additionalProperties": True,
},
"lang": _str_prop("可选语言代码:zh|en|th"),
},
required=["task_id"],
),
@@ -127,11 +127,22 @@ def compute_batch_process_summary(tasks: list[ShippingTask]) -> dict[str, int]:
completed = sum(1 for item in tasks if item.process_status in {"uploaded", "completed", "closed"})
failed = sum(1 for item in tasks if item.process_status in {"rejected"} or item.upload_status == "failed")
running = sum(1 for item in tasks if item.process_status not in {"uploaded", "completed", "closed", "rejected"})
pending = sum(1 for item in tasks if item.process_status in {"created", "pending_review"} or not item.current_step)
focus = next(
(
item for item in sort_batch_tasks(tasks)
if item.process_status not in {"uploaded", "completed", "closed", "rejected"}
),
None,
)
return {
"total": total,
"completed": completed,
"failed": failed,
"running": running,
"pending": pending,
"current_index": int(focus.batch_index or 0) if focus else (total if total else 0),
"current_task_no": focus.task_no if focus else None,
}
@@ -171,9 +182,12 @@ def resolve_task_from_payload(payload: dict[str, Any]) -> ShippingTask | None:
def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
"""Tool data 基础字段(裁剪前)。"""
return {
from app.services.shipping_notice.notice_upload import max_notice_chars
payload: dict[str, Any] = {
"task_no": task.task_no,
"process_status": task.process_status,
"current_step": task.current_step,
"review_status": task.review_status,
"match_status": task.match_status,
"pending_human_reason": task.pending_human_reason,
@@ -189,7 +203,17 @@ def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
"freight_ref_no": task.freight_ref_no,
"error_message": task.error_message,
"conversation_id": task.conversation_id,
"step_payload": task.step_payload_json or {},
}
raw_content = str(task.raw_content or "").strip()
lines = task.lines_json or []
# Dify 画布 LLM 字段抽取需要正文;已落库订单行后不再重复下发全文。
if raw_content and (not lines or str(task.process_status or "").strip().lower() == "created"):
limit = max_notice_chars()
payload["raw_text"] = raw_content[:limit] if len(raw_content) > limit else raw_content
if len(raw_content) > limit:
payload["raw_text_truncated"] = True
return payload
def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, Any]:
@@ -0,0 +1,173 @@
"""
services/shipping_notice/queue_service.py
用途:货代发货后台任务最小队列实现(基于 KbJob 持久化表)。
依赖:models.KbJob、jobs.types、shipping_notice.batch_orchestrator。
逻辑:Web 侧负责 enqueue;worker 侧通过 claim/process 消费单票任务,避免使用进程内 threading。
"""
from __future__ import annotations
from datetime import datetime, timedelta
from typing import Any
import logging
from flask import current_app
from sqlalchemy.exc import OperationalError
from app import db
from app.jobs.types import JobType
from app.models import KbJob
logger = logging.getLogger('shipping-worker')
def shipping_task_execution_mode() -> str:
return str(current_app.config.get('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker') or 'worker').strip().lower()
def enqueue_shipping_notice_job(*, task_no: str, created_by_id: int | None = None, batch_no: str | None = None) -> tuple[bool, str]:
"""持久化一条单票发货后台任务;sync 模式下直接执行。"""
normalized_task_no = str(task_no or '').strip().upper()
if not normalized_task_no:
return False, 'task_no is required'
existing = (
db.session.query(KbJob)
.filter(
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
KbJob.status.in_(('queued', 'running')),
)
.all()
)
for job in existing:
payload = job.payload_json or {}
if str(payload.get('task_no') or '').strip().upper() == normalized_task_no:
return True, 'already_queued'
job = KbJob(
job_type=JobType.SHIPPING_NOTICE_RUN.value,
status='queued',
progress=0,
message='等待后台处理发货任务',
payload_json={
'task_no': normalized_task_no,
'batch_no': str(batch_no or '').strip().upper() or None,
},
created_by_id=created_by_id,
)
db.session.add(job)
db.session.commit()
if shipping_task_execution_mode() == 'sync':
ok, result = run_shipping_notice_job({'job_id': job.id})
return ok, result
if shipping_task_execution_mode() in ('worker', 'rq'):
return True, 'queued_for_worker'
return True, 'queued_manual'
def recover_stale_shipping_notice_jobs() -> tuple[int, str]:
"""回收长时间 running 的发货后台任务,避免 worker 被卡死任务阻塞。"""
timeout_sec = float(current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 300))
cutoff = datetime.utcnow() - timedelta(seconds=timeout_sec)
stale_jobs = (
db.session.query(KbJob)
.filter(
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
KbJob.status == 'running',
KbJob.started_at.isnot(None),
KbJob.started_at < cutoff,
)
.order_by(KbJob.started_at.asc(), KbJob.id.asc())
.all()
)
if not stale_jobs:
return 0, 'no_stale_jobs'
now = datetime.utcnow()
message = f'发货任务执行超时(超过 {int(timeout_sec)}s),已自动回收'
for job in stale_jobs:
job.status = 'failed'
job.error_message = message
job.message = message
job.finished_at = now
job.progress = 100
db.session.commit()
logger.warning('recovered %s stale shipping_notice job(s)', len(stale_jobs))
return len(stale_jobs), f'recovered_{len(stale_jobs)}'
def claim_next_shipping_notice_job() -> KbJob | None:
"""原子领取下一条 queued 的发货后台任务。"""
now = datetime.utcnow()
try:
job = (
db.session.query(KbJob)
.filter(
KbJob.job_type == JobType.SHIPPING_NOTICE_RUN.value,
KbJob.status == 'queued',
)
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
.with_for_update(skip_locked=True)
.first()
)
except OperationalError:
db.session.rollback()
logger.exception('failed to claim next shipping notice job')
return None
if not job:
db.session.rollback()
return None
job.status = 'running'
job.started_at = job.started_at or now
job.progress = max(int(job.progress or 0), 1)
job.message = 'worker 已领取发货任务'
db.session.commit()
return job
def run_shipping_notice_job(payload: dict[str, Any], logger: logging.Logger | None = None) -> tuple[bool, str]:
"""执行单票发货任务;既可被 worker 调用,也可被 sync enqueue 直调。"""
from app.services.shipping_notice.batch_orchestrator import _run_single_task
job_id = payload.get('job_id')
job = db.session.get(KbJob, int(job_id)) if job_id else None
if job is None:
task_no = str(payload.get('task_no') or '').strip().upper()
else:
task_no = str((job.payload_json or {}).get('task_no') or '').strip().upper()
if not task_no:
return False, 'missing_task_no'
result = _run_single_task(task_no)
status = str(result.get('status') or '').strip().lower()
success = status in {'ok', 'running', 'needs_human', 'skipped'}
if job is not None:
job.progress = 100
job.finished_at = datetime.utcnow()
job.result_json = dict(result)
job.message = str(result.get('message') or '')[:500] or '发货任务处理完成'
if success:
job.status = 'success'
job.error_message = None
else:
job.status = 'failed'
job.error_message = str(result.get('message') or 'shipping notice job failed')[:1000]
db.session.commit()
if logger:
logger.info('shipping_notice job task_no=%s status=%s', task_no, status or 'unknown')
return success, status or 'done'
def process_next_shipping_notice_job() -> tuple[bool, str]:
"""worker 消费发货后台队列的单步入口。"""
recover_stale_shipping_notice_jobs()
job = claim_next_shipping_notice_job()
if not job:
return False, 'no_job'
return run_shipping_notice_job({'job_id': job.id})
@@ -12,8 +12,11 @@ import uuid
from datetime import datetime
from typing import Any
from flask import current_app
from app import db
from app.models import ShippingBatch, ShippingTask
from app.models import ChatLog, ShippingBatch, ShippingTask
from app.services.shipping_notice.agent_resolver import resolve_chat_agent
from app.services.shipping_notice.constants import (
CP_PARSE_OK,
CP_TASK_EXISTS,
@@ -41,14 +44,88 @@ from app.services.shipping_notice.user_facing_status import user_facing_task_sta
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.tool_common import (
auto_progress_enabled,
defer_parse_to_dify_enabled,
generate_task_no,
log_task_event,
set_task_step_progress,
)
EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", "po_number", "required_date"})
EDITABLE_NOTICE_LINE_FIELDS = frozenset({"sku", "reservation_id", "qty", "quantity", "required_date", "uom"})
def _build_parse_review_chat_payload(task: ShippingTask) -> dict[str, Any]:
return {
"taskId": task.task_no,
"checkpoint": "parse_review",
"header": {
"customer_name": task.customer_name,
"customer_code": task.customer_code,
"ship_to": task.ship_to,
"po_number": task.po_number,
"required_date": task.required_date,
},
"lines": task.lines_json or [],
"saving": False,
}
def _upsert_parse_review_chat_message(task: ShippingTask) -> None:
"""
将 parse_review 结果直接回填到当前聊天会话。
设计意图:
- 不再依赖“前端再次发一轮消息”去索取解析结果;
- 同任务只保留一条 shipping-parse-review 消息,重复解析时直接更新。
"""
session_id = str(task.conversation_id or "").strip()
if not session_id or not task.user_id:
return
agent = resolve_chat_agent()
if not agent or not getattr(agent, "id", None):
return
payload = _build_parse_review_chat_payload(task)
content = f"请确认或修订以下解析结果。\n任务编号:{task.task_no}"
chat_logs = (
db.session.query(ChatLog)
.filter_by(
user_id=task.user_id,
agent_id=agent.id,
session_id=session_id,
message_type="shipping-parse-review",
)
.order_by(ChatLog.created_at.desc(), ChatLog.id.desc())
.all()
)
existing = None
for item in chat_logs:
item_payload = item.payload if isinstance(item.payload, dict) else {}
if str(item_payload.get("taskId") or "").strip().upper() == str(task.task_no or "").strip().upper():
existing = item
break
if existing:
existing.answer = content
existing.payload = payload
return
db.session.add(
ChatLog(
user_id=task.user_id,
agent_id=agent.id,
conversation_id=session_id,
session_id=session_id,
query="",
answer=content,
message_type="shipping-parse-review",
payload=payload,
)
)
def recompute_batch_summary(batch: ShippingBatch | None) -> None:
"""写路径:重算批次汇总并校正 current_focus_task_no。"""
if not batch:
@@ -57,6 +134,17 @@ def recompute_batch_summary(batch: ShippingBatch | None) -> None:
tasks = list_sorted_batch_tasks(batch)
batch.file_count = max(int(batch.file_count or 0), len(tasks) or 0)
batch.process_summary_json = compute_batch_process_summary(tasks)
next_focus = next(
(
item.task_no
for item in tasks
if str(item.process_status or "").strip() not in {"uploaded", "completed", "closed", "rejected"}
),
None,
)
if next_focus:
batch.current_focus_task_no = next_focus
return
if not batch.current_focus_task_no:
batch.current_focus_task_no = tasks[0].task_no if tasks else None
return
@@ -105,12 +193,23 @@ def create_batch(payload: dict[str, Any]) -> ShippingBatch:
return batch
def _should_defer_notice_parse(payload: dict[str, Any], item: dict[str, Any]) -> bool:
"""判断是否将 parse_notice 延后到 Dify 画布(有 structured 或显式 auto_parse 时不延后)。"""
if isinstance(item.get("structured"), dict) and item.get("structured"):
return False
if payload.get("auto_parse") is True:
return False
if payload.get("defer_parse") is False:
return False
return defer_parse_to_dify_enabled()
def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
"""
一次创建批次,并为每个 notice_item 创建任务后立即触发解析。
一次创建批次,并为每个 notice_item 创建任务;默认将字段解析延后到 Dify 画布。
【AI 触发时机】:当用户批量上传多份发货通知附件,希望系统自动拆成多个任务时调用。
核心逻辑:先创建批次,再逐个创建任务、透传 notice 原文到 `parse_notice`,最后回写批次汇总。
核心逻辑:先创建批次,再逐个创建任务;若 notice_item 已带 structured 或 auto_parse=true 则立即 parse_notice,否则仅保存 raw_text 待 Dify 续办。
Args:
payload: 包含 user_id、conversation_id、notice_items、file_count 等批量建单数据。
@@ -164,6 +263,20 @@ def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
warnings = item.get("warnings")
if isinstance(warnings, list):
parse_payload["warnings"] = warnings
if _should_defer_notice_parse(payload, item):
log_task_event(
task,
"parse_deferred_to_dify",
{"batch_no": batch.batch_no, "reason": "SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY"},
)
created_tasks.append(
{
"task_id": task.task_no,
"batch_index": idx,
"parse_status": "deferred",
}
)
continue
parse_result = parse_notice(parse_payload)
created_tasks.append(
{
@@ -312,6 +425,17 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
if conv_id and not task.conversation_id:
task.conversation_id = conv_id
set_task_step_progress(
task,
step_key="step1_notice_submit",
step_title="提交通知",
status="running",
message="正在解析发货通知",
progress_percent=20,
detail="正在抽取单头、订单行与关键字段",
)
db.session.flush()
# [STEP 2] 提取单头、订单行与置信度,回写任务字段。
raw_text = str(payload.get("raw_text") or task.raw_content or "").strip()
structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None
@@ -342,6 +466,18 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
task.required_date = required_date or None
task.lines_json = lines
task.parse_confidence = confidence
set_task_step_progress(
task,
step_key="step2_parse_confirm",
step_title="确认解析",
status="needs_human" if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7) else "completed",
message="发货通知解析已完成",
progress_percent=100,
current=len(lines),
total=len(lines),
detail=f"已识别 {len(lines)} 行订单,解析置信度 {confidence:.2f}",
extra={"warnings": warnings},
)
summary_kwargs = {
"task_no": task.task_no,
@@ -357,6 +493,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7):
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
log_task_event(task, "parse_needs_review", {"confidence": confidence, "warnings": warnings})
_upsert_parse_review_chat_message(task)
db.session.commit()
return tool_response(
status="needs_human",
@@ -668,6 +805,68 @@ def remove_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
)
def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
"""
重置单个任务到可重新自动推进的状态,并重新交给后台编排器。
【AI 触发时机】:当用户要求“重试当前票”“重新跑这张单据”时调用。
核心逻辑:保留解析/库存/匹配等业务真相字段,仅清理错误与人工阻断,再恢复到当前数据所对应的最近可续跑状态。
Args:
payload: 必须能定位 task;可选 comment 记录重试原因。
Returns:
dict[str, Any]: Tool 标准响应,返回重置后的任务状态与是否成功触发后台编排。
"""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
comment = str(payload.get("comment") or "").strip()
task.review_status = None
task.pending_human_reason = None
task.error_message = None
if not task.raw_content and not task.lines_json:
task.process_status = "created"
elif task.lines_json:
if task.export_file_path:
task.process_status = "matched"
elif task.inventory_lines_json:
task.process_status = "inventory_ready"
else:
task.process_status = "parsed"
else:
task.process_status = "created"
log_task_event(
task,
"task_retry_requested",
{
"comment": comment,
"restored_process_status": task.process_status,
},
)
sync_batch_after_task_change(task)
db.session.commit()
from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator
started = start_task_orchestrator(task.task_no)
return tool_response(
status="ok",
task=task,
message=(
f"已重试任务 {task.task_no},后台已重新开始处理。"
if started
else f"已重置任务 {task.task_no},请稍后再试。"
),
data={
**serialize_task_for_tool(task),
"orchestrator_started": started,
},
)
def get_task_status(payload: dict[str, Any]) -> dict[str, Any]:
"""
查询任务当前进度(Tool / 工作台共用)。
@@ -64,6 +64,11 @@ def auto_mapping_allow_llm() -> bool:
return cfg_bool("SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM", False)
def defer_parse_to_dify_enabled() -> bool:
"""建单后是否延后 parse_notice,交由 Dify 画布完成 LLM 抽取与落库。"""
return cfg_bool("SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY", True)
def auto_match_enabled() -> bool:
"""auto_progress 是否自动调用 match_inventory。"""
return cfg_bool("SHIPPING_NOTICE_AUTO_MATCH_ENABLED", True)
@@ -123,6 +128,49 @@ def prepend_tool_message(result: dict[str, Any], prefix: str) -> dict[str, Any]:
return {**result, "message": f"{note}\n\n{body}" if body else note}
def set_task_step_progress(
task: ShippingTask,
*,
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: ShippingTask) -> None:
"""清空任务步骤内进度,保留其他 step_payload_json 字段。"""
payload = dict(task.step_payload_json or {})
payload.pop("current_step_progress", None)
task.step_payload_json = payload or None
@@ -18,6 +18,7 @@ parse_notice = task_workflow.parse_notice
auto_progress = task_workflow.auto_progress
submit_decision = task_workflow.submit_decision
get_task_status = task_workflow.get_task_status
retry_task = task_workflow.retry_task
update_notice_fields = task_workflow.update_notice_fields
update_notice_line = task_workflow.update_notice_line
add_notice_line = task_workflow.add_notice_line
@@ -0,0 +1,112 @@
"""align shipping_tasks schema drift
Revision ID: e2f4a6b8c0d1
Revises: c5d6e7f8a9b0
Create Date: 2026-06-22 09:10:00.000000
用途:一次性修复 shipping_tasks 在部分 PostgreSQL 环境里的 schema 漂移,使其与当前 ShippingTask 模型保持一致。
依赖:Alembic op / SQLAlchemy inspect;与 ShippingTask 模型、既有建单/编辑逻辑保持一致。
逻辑:upgrade 恢复 upload_status/upload_mode 的可空语义,并对齐 source_file_type 长度、export_version 默认值;downgrade 提供对称回滚。
"""
from alembic import op
import sqlalchemy as sa
revision = "e2f4a6b8c0d1"
down_revision = "c5d6e7f8a9b0"
branch_labels = None
depends_on = None
def _table_columns(insp, table_name: str) -> set[str]:
if table_name not in set(insp.get_table_names()):
return set()
return {col["name"] for col in insp.get_columns(table_name)}
def upgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
columns = _table_columns(insp, "shipping_tasks")
if not columns:
return
# [STEP 1] 恢复上传相关字段的可空语义,与模型/状态机现状保持一致。
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "upload_status" in columns:
batch_op.alter_column(
"upload_status",
existing_type=sa.String(length=32),
nullable=True,
)
if "upload_mode" in columns:
batch_op.alter_column(
"upload_mode",
existing_type=sa.String(length=32),
nullable=True,
)
# [STEP 2] 对齐字段长度与默认值,避免模型/数据库继续出现隐性分叉。
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "source_file_type" in columns:
batch_op.alter_column(
"source_file_type",
existing_type=sa.String(length=32),
type_=sa.String(length=64),
existing_nullable=True,
)
if "export_version" in columns:
batch_op.alter_column(
"export_version",
existing_type=sa.Integer(),
server_default="1",
existing_nullable=False,
)
def downgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
columns = _table_columns(insp, "shipping_tasks")
if not columns:
return
# [STEP 1] 先回滚长度与默认值,恢复升级前的库侧行为。
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "source_file_type" in columns:
batch_op.alter_column(
"source_file_type",
existing_type=sa.String(length=64),
type_=sa.String(length=32),
existing_nullable=True,
)
if "export_version" in columns:
batch_op.alter_column(
"export_version",
existing_type=sa.Integer(),
server_default="0",
existing_nullable=False,
)
# [STEP 2] 回滚为 NOT NULL 前先补齐现存 NULL,避免约束恢复时失败。
if "upload_status" in columns:
op.execute("UPDATE shipping_tasks SET upload_status = '' WHERE upload_status IS NULL")
if "upload_mode" in columns:
op.execute("UPDATE shipping_tasks SET upload_mode = '' WHERE upload_mode IS NULL")
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "upload_status" in columns:
batch_op.alter_column(
"upload_status",
existing_type=sa.String(length=32),
nullable=False,
)
if "upload_mode" in columns:
batch_op.alter_column(
"upload_mode",
existing_type=sa.String(length=32),
nullable=False,
)
@@ -0,0 +1,108 @@
"""apply shipping_tasks schema alignment
Revision ID: f1e2d3c4b5a6
Revises: e2f4a6b8c0d1
Create Date: 2026-06-22 09:45:00.000000
用途:将已处于 e2f4a6b8c0d1 版本、但未实际应用 shipping_tasks 字段对齐的数据库补齐到目标结构。
依赖:Alembic op / SQLAlchemy inspect;用于修复已执行 revision 文件被后改导致的实际库结构未变问题。
逻辑:upgrade 真正落地 upload_mode/upload_status/source_file_type/export_version 的对齐;downgrade 回退到当前本地库观测到的旧结构。
"""
from alembic import op
import sqlalchemy as sa
revision = "f1e2d3c4b5a6"
down_revision = "e2f4a6b8c0d1"
branch_labels = None
depends_on = None
def _table_columns(insp, table_name: str) -> set[str]:
if table_name not in set(insp.get_table_names()):
return set()
return {col["name"] for col in insp.get_columns(table_name)}
def upgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
columns = _table_columns(insp, "shipping_tasks")
if not columns:
return
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "upload_status" in columns:
batch_op.alter_column(
"upload_status",
existing_type=sa.String(length=32),
nullable=True,
server_default=None,
)
if "upload_mode" in columns:
batch_op.alter_column(
"upload_mode",
existing_type=sa.String(length=32),
nullable=True,
server_default=None,
)
if "source_file_type" in columns:
batch_op.alter_column(
"source_file_type",
existing_type=sa.String(length=32),
type_=sa.String(length=64),
existing_nullable=True,
)
if "export_version" in columns:
batch_op.alter_column(
"export_version",
existing_type=sa.Integer(),
server_default="1",
existing_nullable=False,
)
def downgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
columns = _table_columns(insp, "shipping_tasks")
if not columns:
return
if "upload_mode" in columns:
op.execute("UPDATE shipping_tasks SET upload_mode = 'auto' WHERE upload_mode IS NULL")
if "upload_status" in columns:
op.execute("UPDATE shipping_tasks SET upload_status = 'not_started' WHERE upload_status IS NULL")
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "upload_status" in columns:
batch_op.alter_column(
"upload_status",
existing_type=sa.String(length=32),
nullable=True,
server_default="not_started",
)
if "upload_mode" in columns:
batch_op.alter_column(
"upload_mode",
existing_type=sa.String(length=32),
nullable=False,
server_default="auto",
)
if "source_file_type" in columns:
batch_op.alter_column(
"source_file_type",
existing_type=sa.String(length=64),
type_=sa.String(length=32),
existing_nullable=True,
)
if "export_version" in columns:
batch_op.alter_column(
"export_version",
existing_type=sa.Integer(),
server_default="0",
existing_nullable=False,
)
@@ -0,0 +1,30 @@
"""Merge FAQ stale fields and shipping schema alignment migration heads.
Purpose:
Keep Alembic's revision graph linear after two independent backend schema
fixes were added from different migration branches.
Dependencies:
Alembic revision metadata for c6d7e8f9a0b1 and f1e2d3c4b5a6.
Flow:
The deployment command ``flask db upgrade`` targets ``head``; this
merge-only revision gives Alembic a single head without executing DDL.
Revision ID: f9a0b1c2d3e4
Revises: c6d7e8f9a0b1, f1e2d3c4b5a6
Create Date: 2026-06-23 12:20:00.000000
"""
revision = "f9a0b1c2d3e4"
down_revision = ("c6d7e8f9a0b1", "f1e2d3c4b5a6")
branch_labels = None
depends_on = None
def upgrade():
"""Unify the two migration heads; no database changes are required."""
pass
def downgrade():
"""Keep downgrade as a no-op because this revision only changes topology."""
pass
+2
View File
@@ -23,9 +23,11 @@ def _shipping_notice_stable_auto_config(app, request):
if request.node.get_closest_marker("auto_rpa"):
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
def pytest_configure(config):
+92 -1
View File
@@ -127,5 +127,96 @@ def test_update_chat_log_tokens_backfills_after_message_end(app):
assert updated is True
assert db.session.get(ChatLog, chat_log_id).tokens_used == 3068
# 不应被更小的值覆盖
def test_collect_knowledge_retrieval_from_node_finished():
"""Chatflow:知识检索来源应从 node_finished.outputs.result 提取。"""
retriever_resources: list = []
event_data = {
'event': 'node_finished',
'data': {
'node_type': 'knowledge-retrieval',
'status': 'succeeded',
'outputs': {
'result': [
{
'metadata': {
'dataset_id': 'ac0cf595-ca91-4f48-a0d1-0d31544c4136',
'dataset_name': '4.人事规章',
'document_id': '94b7246a-4daa-4dff-bdef-01510848f985',
'document_name': '员工入职须4',
'segment_id': '9d10e131-bf02-4add-8ef1-d3098a2ab7a4',
'score': 0.8577696681022644,
},
'title': '员工入职须4',
'files': None,
'content': '员工入职须知4\n2.上班时间',
},
{
'metadata': {
'dataset_id': 'ac0cf595-ca91-4f48-a0d1-0d31544c4136',
'document_id': '97eab330-d658-4f9e-aa7f-a24423234ee5',
'document_name': '考勤-公司班次信息',
},
'title': '考勤-公司班次信息',
'content': '考勤-公司班次信息',
},
],
},
},
}
DifyService._collect_knowledge_retrieval_from_node(retriever_resources, event_data)
assert len(retriever_resources) == 2
assert retriever_resources[0]['document_id'] == '94b7246a-4daa-4dff-bdef-01510848f985'
assert retriever_resources[0]['document_name'] == '员工入职须4'
assert retriever_resources[0]['dataset_id'] == 'ac0cf595-ca91-4f48-a0d1-0d31544c4136'
assert retriever_resources[1]['document_id'] == '97eab330-d658-4f9e-aa7f-a24423234ee5'
def test_attach_retriever_resources_to_workflow_finished_event():
"""workflow_finished 下发前应携带 retriever_resources 供前端展示源文件。"""
resources = [
{
'dataset_id': 'ds-1',
'document_id': 'doc-1',
'document_name': '员工入职须知.pdf',
'content': '上班时间 8:00',
},
]
event_data = {'event': 'workflow_finished', 'metadata': {}}
DifyService._attach_retriever_resources_to_event(event_data, resources)
assert len(event_data['retriever_resources']) == 1
assert event_data['retriever_resources'][0]['document_name'] == '员工入职须知.pdf'
assert event_data['metadata']['retriever_resources'][0]['document_id'] == 'doc-1'
def test_update_chat_log_tokens_does_not_decrease(app):
"""已写入更大 token 后,不应被更小的值覆盖。"""
with app.app_context():
user = User(username='u3', role='user', email='u3@example.com')
agent = Agent(name='wf_agent3', dify_app_id='wf-3')
db.session.add_all([user, agent])
db.session.commit()
first = DifyService._persist_stream_chat_record(
data={'event': 'message_end', 'conversation_id': 'conv-wf-3', 'metadata': {}},
event_name='message_end',
request_id='req-wf-3',
user_id=user.id,
agent=agent,
session_id='sess-wf-3',
hxops_turn_id=None,
normalized_conversation_id='conv-wf-3',
query='test',
answer_text='answer',
latency=1000,
retriever_resources=[],
attribution_parts=[],
)
chat_log_id = first['chat_log_id']
DifyService._update_chat_log_tokens(chat_log_id, 500)
assert DifyService._update_chat_log_tokens(chat_log_id, 100) is False
+75
View File
@@ -389,6 +389,81 @@ def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkey
assert resolve_run_id_for_chat_log(session_id='bind-on-start', query='执行 RoHS 检核') == run_id
def test_file_check_tool_no_data_does_not_create_run_or_bind_context(app, client, monkeypatch):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
task_id = task.id
before_count = ScheduleRun.query.filter_by(schedule_task_id=task_id).count()
monkeypatch.setattr('app.api.file_check_tools._precheck_no_data', lambda _task: {
'ok': False,
'error_code': 'no_data_to_check',
'message': '目前没有资料需要检核',
'task': {'task_id': _task.id, 'task_name': _task.name},
})
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={
'task_id': task_id,
'hxops_session_id': 'no-data-session',
'hxops_turn_id': 'no-data-turn',
'user_message': '立即执行检核',
},
)
assert res.status_code == 200
data = res.get_json()
assert data['ok'] is False
assert data['error_code'] == 'no_data_to_check'
assert 'run' not in data
with app.app_context():
after_count = ScheduleRun.query.filter_by(schedule_task_id=task_id).count()
assert after_count == before_count
from app.services.file_check_tools.chat_log_run_binding import resolve_run_id_for_chat_log
assert resolve_run_id_for_chat_log(turn_id='no-data-turn') is None
assert resolve_run_id_for_chat_log(session_id='no-data-session', query='立即执行检核') is None
def test_file_check_tool_no_data_keeps_existing_running_conflict_priority(app, client, monkeypatch):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
admin = _mk_admin()
db.session.commit()
task = _mk_check_task(admin.id)
run = ScheduleRun(
run_no='RUN-ROHS-NO-DATA-CONFLICT',
schedule_task_id=task.id,
status='running',
trigger_type='manual',
)
db.session.add(run)
db.session.commit()
task_id = task.id
monkeypatch.setattr('app.api.file_check_tools._precheck_no_data', lambda _task: {
'ok': False,
'error_code': 'no_data_to_check',
'message': '目前没有资料需要检核',
'task': {'task_id': _task.id, 'task_name': _task.name},
})
res = client.post(
'/api/file-check/tools/tasks/run',
headers={'X-Integration-Key': 'secret', 'Content-Type': 'application/json'},
json={'task_id': task_id},
)
assert res.status_code == 200
data = res.get_json()
assert data['error_code'] == 'check_running'
assert data.get('run', {}).get('run_id')
def test_file_check_tool_requires_task_id(app, client):
with app.app_context():
app.config['INTEGRATION_API_KEY'] = 'secret'
@@ -1,4 +1,5 @@
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
from types import SimpleNamespace
def test_supports_strong_leave_balance_intent_without_self_pronoun():
@@ -6,8 +7,27 @@ def test_supports_strong_leave_balance_intent_without_self_pronoun():
assert HRLeaveSQLServerService.supports("还有多少假期")
assert HRLeaveSQLServerService.supports("年假还有多少天")
assert HRLeaveSQLServerService.supports("还有多少年假")
assert HRLeaveSQLServerService.supports("我还有多少假期")
assert HRLeaveSQLServerService.supports("自己还有多少假期")
def test_supports_rejects_leave_process_questions():
assert not HRLeaveSQLServerService.supports("假期怎么申请")
assert not HRLeaveSQLServerService.supports("年假制度是什么")
def test_supports_other_person_leave_queries_for_guardrail():
assert HRLeaveSQLServerService.supports("张三还有多少假期")
assert HRLeaveSQLServerService.supports("曹惠鹏还有多少假期")
assert HRLeaveSQLServerService.supports("帮我查一下其他人的年假情况")
def test_is_querying_other_person_leave_distinguishes_self_and_others():
user = SimpleNamespace(real_name="李四", username="lisi", employee_id="E1001")
assert HRLeaveSQLServerService._is_querying_other_person_leave("张三还有多少假期", user)
assert HRLeaveSQLServerService._is_querying_other_person_leave("曹惠鹏还有多少假期", user)
assert HRLeaveSQLServerService._is_querying_other_person_leave("帮我查一下其他人的年假情况", user)
assert not HRLeaveSQLServerService._is_querying_other_person_leave("我还有多少假期", user)
assert not HRLeaveSQLServerService._is_querying_other_person_leave("自己还有多少假期", user)
assert not HRLeaveSQLServerService._is_querying_other_person_leave("还有多少假期", user)
assert not HRLeaveSQLServerService._is_querying_other_person_leave("李四的年假还有多少", user)
+286 -4
View File
@@ -4,20 +4,45 @@
1. 单/多通知可通过 create_batch 一次建批并生成多 task。
2. get_batch_status 返回 focus task 与任务列表。
3. switch_focus_task 可在同批次内切换当前任务。
4. 工作台批量上传通知时仅保存 raw_text,首轮解析延后到 Dify。
"""
from app.models import ShippingBatch, ShippingTask
from io import BytesIO
from app import db
from app.models import Agent, ChatSession, ShippingBatch, ShippingTask, User
from app.auth_jwt import issue_local_access_token
from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs
def _tool_headers():
def _tool_headers(app):
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
return {
"Content-Type": "application/json",
"X-Integration-Key": "test-integration-key",
}
def _workspace_headers(app):
with app.app_context():
user = User(
username="shipping_workspace_user",
email="shipping_workspace_user@example.com",
role="user",
status="active",
)
user.set_password("password")
db.session.add(user)
db.session.commit()
token = issue_local_access_token(user)
return {
"Authorization": f"Bearer {token}",
}
def test_create_batch_tasks_and_switch_focus(app, client):
"""验证 batch 建单、状态查询、focus task 切换主流程。"""
headers = _tool_headers()
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_batch",
@@ -93,9 +118,266 @@ def test_create_batch_tasks_and_switch_focus(app, client):
assert task_rows[1].batch_total == 2
def test_create_batch_defers_parse_without_structured(app, client):
"""默认将 parse_notice 延后到 Dify,仅保存 raw_text。"""
headers = _tool_headers(app)
res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={
"notice_items": [
{
"source_file_name": "notice-a.txt",
"raw_text": "客户:ACME 料号A001 x 10",
},
],
},
)
assert res.status_code == 200
data = res.get_json()
assert data["data"]["tasks"][0]["parse_status"] == "deferred"
with app.app_context():
task = ShippingTask.query.filter_by(task_no=data["data"]["tasks"][0]["task_id"]).first()
assert task is not None
assert task.raw_content
assert not (task.lines_json or [])
def test_workspace_create_batch_from_notices_defers_parse_to_dify(app, client):
"""聊天/工作台批量上传通知时应仅落 raw_text,首轮解析延后到 Dify。"""
headers = _workspace_headers(app)
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
"conversation_id": "conv-workspace-batch-001",
},
content_type="multipart/form-data",
)
assert res.status_code == 200
data = res.get_json()
assert data["status"] == "ok"
assert data["batch_no"].startswith("SB-")
assert data["data"]["batch"]["batch_no"] == data["batch_no"]
assert data["data"]["tasks"][0]["parse_status"] == "deferred"
assert data["data"]["focus_task"]["task_no"] == data["data"]["tasks"][0]["task_id"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=data["data"]["tasks"][0]["task_id"]).first()
assert task is not None
assert task.raw_content
assert task.process_status == "created"
assert len(task.lines_json or []) == 0
def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(app, client, monkeypatch):
"""开启编排器时,工作台上传接口应返回 orchestrator_started。"""
headers = _workspace_headers(app)
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = True
app.config["SHIPPING_NOTICE_DEFER_PARSE_TO_DIFY"] = True
started: list[str] = []
def fake_start(batch_no: str | None) -> bool:
if batch_no:
started.append(batch_no)
return True
monkeypatch.setattr(batch_orchestrator, "start_batch_orchestrator", fake_start)
res = client.post(
"/api/workspace/shipping-batches/create-from-notices",
headers=headers,
data={
"files": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "notice-a.txt"),
"conversation_id": "conv-workspace-batch-002",
},
content_type="multipart/form-data",
)
assert res.status_code == 200
data = res.get_json()
assert data["status"] == "ok"
assert data["data"]["orchestrator_started"] is True
assert started == [data["batch_no"]]
def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch):
"""编排器遇到 created 任务时应调用后台 Dify 执行器。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-ORCH-PARSE", file_count=1)
task = ShippingTask(
task_no="SN-20260622-AAAA0001",
batch=batch,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
called: dict[str, object] = {}
def fake_dify(task_ref: str):
called["dify"] = task_ref
return {"status": "ok", "message": "parsed-by-dify"}
def fake_auto_progress(payload):
raise AssertionError("created task should not call auto_progress when auto_progress is disabled")
monkeypatch.setattr(batch_orchestrator, "run_shipping_parse_via_dify", fake_dify)
monkeypatch.setattr(batch_orchestrator, "auto_progress", fake_auto_progress)
result = batch_orchestrator._run_single_task(task.task_no)
assert result["status"] == "ok"
assert called.get("dify") == task_no
def test_run_single_task_routes_non_created_task_to_auto_progress(app, monkeypatch):
"""编排器遇到非 created 且无人工阻塞的任务时应调用 auto_progress。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-ORCH-AUTO", file_count=1)
task = ShippingTask(
task_no="SN-20260622-BBBB0002",
batch=batch,
source_type="manual",
process_status="parsed",
)
db.session.add_all([batch, task])
db.session.commit()
task_no = task.task_no
called: dict[str, object] = {}
def fake_dify(task_ref: str):
raise AssertionError(f"parsed task should not call dify parse executor: {task_ref}")
def fake_auto_progress(payload):
called["auto_progress"] = payload
return {"status": "ok", "message": "advanced"}
monkeypatch.setattr(batch_orchestrator, "run_shipping_parse_via_dify", fake_dify)
monkeypatch.setattr(batch_orchestrator, "auto_progress", fake_auto_progress)
result = batch_orchestrator._run_single_task(task.task_no)
assert result["status"] == "ok"
assert isinstance(called.get("auto_progress"), dict)
assert called["auto_progress"]["task_id"] == task_no
def test_run_shipping_parse_via_dify_passes_task_context_and_updates_session(app, monkeypatch):
"""后台 Dify 执行器应带上当前任务上下文,并回写 provider conversation id。"""
with app.app_context():
user = User(
username="shipping_dify_user",
email="shipping_dify_user@example.com",
role="user",
status="active",
)
user.set_password("password")
db.session.add(user)
db.session.flush()
agent = Agent(
name="货代发货通知 Agent",
dify_api_key="test-dify-key",
is_active=True,
)
db.session.add(agent)
db.session.flush()
session = ChatSession(
session_id="conv-shipping-dify-001",
user_id=user.id,
agent_id=agent.id,
title="shipping parse",
status="running",
)
batch = ShippingBatch(
batch_no="SB-DIFY-EXEC",
user_id=user.id,
conversation_id=session.session_id,
file_count=1,
)
task = ShippingTask(
task_no="SN-20260622-CCCC0003",
batch=batch,
user_id=user.id,
conversation_id=session.session_id,
source_type="manual",
raw_content="客户:ACME\nA001 x 10",
process_status="created",
)
db.session.add_all([session, batch, task])
db.session.commit()
captured: dict[str, object] = {}
def fake_stream_chat(query, user_id, agent_obj, conversation_id=None, **kwargs):
captured["query"] = query
captured["user_id"] = user_id
captured["agent_id"] = agent_obj.id
captured["conversation_id"] = conversation_id
captured["session_id"] = kwargs.get("session_id")
captured["inputs"] = kwargs.get("inputs")
yield 'data: {"event":"message_end","conversation_id":"11111111-1111-1111-1111-111111111111","answer":"parsed"}\n\n'
monkeypatch.setattr(dify_executor.DifyService, "stream_chat", staticmethod(fake_stream_chat))
result = dify_executor.run_shipping_parse_via_dify(task.task_no)
assert result["status"] == "ok"
assert captured["user_id"] == user.id
assert captured["agent_id"] == agent.id
assert captured["session_id"] == session.session_id
assert isinstance(captured["inputs"], dict)
assert captured["inputs"]["entry_mode"] == "orchestrator_parse"
assert captured["inputs"]["trigger_source"] == "backend_orchestrator"
assert captured["inputs"]["user_message"] == ""
assert captured["inputs"]["current_task_no"] == task.task_no
assert captured["inputs"]["current_batch_no"] == batch.batch_no
refreshed_session = ChatSession.query.filter_by(session_id=session.session_id).first()
assert refreshed_session is not None
assert refreshed_session.external_conversation_id == "11111111-1111-1111-1111-111111111111"
def test_build_dify_chat_inputs_supports_unified_frontend_fields(app):
"""统一版 Dify inputs 应同时包含 entry_mode/user_message/trigger_source。"""
with app.app_context():
batch = ShippingBatch(
batch_no="SB-DIFY-INPUTS",
conversation_id="conv-shipping-inputs-001",
current_focus_task_no="SN-20260622-DDDD0004",
file_count=1,
)
task = ShippingTask(
task_no="SN-20260622-DDDD0004",
batch=batch,
conversation_id="conv-shipping-inputs-001",
source_type="manual",
process_status="created",
)
db.session.add_all([batch, task])
db.session.commit()
inputs = dify_inputs.build_dify_chat_inputs(
"conv-shipping-inputs-001",
entry_mode="user_chat",
user_message="这票现在什么状态?",
trigger_source="frontend_chat",
)
assert inputs["entry_mode"] == "user_chat"
assert inputs["conversation_id"] == "conv-shipping-inputs-001"
assert inputs["current_batch_no"] == "SB-DIFY-INPUTS"
assert inputs["current_task_no"] == "SN-20260622-DDDD0004"
assert inputs["user_message"] == "这票现在什么状态?"
assert inputs["trigger_source"] == "frontend_chat"
def test_create_empty_batch_returns_batch_shell(app, client):
"""验证无 notice_items 时仍可创建批次壳,供后续续办。"""
headers = _tool_headers()
headers = _tool_headers(app)
res = client.post(
"/api/shipping-notice/tools/create_batch",
+27 -1
View File
@@ -1,4 +1,4 @@
from app.services.shipping_notice.extract import extract_notice_fields
from app.services.shipping_notice.extract import extract_notice_fields, _heuristic_extract
from app.services.shipping_notice.notice_lines import (
normalize_notice_line,
parse_notice_table_rows,
@@ -179,3 +179,29 @@ AWS Sku\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
assert parsed["lines"][0]["unit_price"] == 5
assert parsed["lines"][0]["amount"] == 20
assert confidence >= 0.5
def test_extract_notice_fields_structured_over_heuristic():
"""Dify 传入 structured 时应直接使用,不走启发式。"""
structured = {
"customer_name": "ACME",
"lines": [{"sku": "SKU-DIFY", "qty": 3, "uom": "EA"}],
"confidence": 0.95,
}
parsed, confidence, warnings = extract_notice_fields(
raw_text="ignored SKU x 99",
structured=structured,
)
assert parsed["parse_source"] == "dify"
assert parsed["lines"][0]["sku"] == "SKU-DIFY"
assert confidence > 0.8
assert "parse_fallback_heuristic" not in warnings
def test_extract_notice_fields_heuristic_fallback():
"""无 structured 时走后端启发式兜底。"""
text = "AWS Sku\tReservation Order\tOrder Qty\n10-40594-001\tORD-3002\t4"
parsed, _, warnings = extract_notice_fields(raw_text=text)
assert parsed["parse_source"] == "heuristic"
assert parsed["lines"][0]["sku"] == "10-40594-001"
assert "parse_fallback_heuristic" in warnings
@@ -2,14 +2,38 @@ import pytest
from app import db
from app.models import ShippingInventoryMapping, ShippingTask
from app.services.shipping_notice.match import match_notice_lines
def _tool_headers(app):
app.config["INTEGRATION_API_KEY"] = "test-integration-key"
return {
"Content-Type": "application/json",
"X-Integration-Key": "test-integration-key",
}
def test_match_notice_lines_reports_progress():
seen: list[tuple[int, int]] = []
status, line_results, shortage = match_notice_lines(
[
{"sku": "A001", "reservation_id": "R-1", "qty": 1},
{"sku": "A002", "reservation_id": "R-2", "qty": 2},
],
[
{"sku": "A001", "reservation_id": "R-1", "available_qty": 1},
{"sku": "A002", "reservation_id": "R-2", "available_qty": 2},
],
progress_callback=lambda current, total: seen.append((current, total)),
)
assert status == "fulfillable"
assert len(line_results) == 2
assert shortage["lines"] == []
assert seen == [(1, 2), (2, 2)]
def test_shipping_notice_tool_flow(app, client):
headers = _tool_headers(app)
+35 -4
View File
@@ -13,7 +13,6 @@ import sys
from app import create_app
from app.jobs.context import JobContext
from app.jobs.runner import run_forever
_LOG_FORMAT = '%(asctime)s %(levelname)s [worker] %(message)s'
@@ -28,6 +27,18 @@ def _configure_logging() -> logging.Logger:
return logger
def _resolve_processor(queue_name: str):
if queue_name == 'kb':
from app.services.knowledge_cleaning.queue_service import process_next_kb_job
return process_next_kb_job
if queue_name == 'shipping':
from app.services.shipping_notice.queue_service import process_next_shipping_notice_job
return process_next_shipping_notice_job
raise ValueError(f'Unsupported queue: {queue_name}')
def main(*, queues: list[str] | None = None, config_name: str = 'default') -> None:
"""
启动 worker 主循环。
@@ -38,14 +49,34 @@ def main(*, queues: list[str] | None = None, config_name: str = 'default') -> No
logger = _configure_logging()
app = create_app(config_name)
with app.app_context():
import app.jobs.handlers # noqa: F401
ctx = JobContext(
config=dict(app.config),
logger=logger,
extras={'queues': queues or ['kb']},
)
logger.info('Worker starting queues=%s (skeleton — Wave 2 enables job processing)', ctx.extras['queues'])
# Wave 2: import app.jobs.handlers # noqa: F401 — register handlers
run_forever(ctx)
queue_names = ctx.extras['queues']
poll_seconds = 2.0
if 'shipping' in queue_names:
poll_seconds = float(app.config.get('SHIPPING_NOTICE_WORKER_POLL_SECONDS', poll_seconds))
elif 'kb' in queue_names:
poll_seconds = float(app.config.get('KB_WORKER_POLL_SECONDS', poll_seconds))
logger.info('Worker starting queues=%s poll_seconds=%s', queue_names, poll_seconds)
processors = [_resolve_processor(name) for name in queue_names]
import time
while True:
handled = False
for processor in processors:
processed, message = processor()
if processed:
handled = True
logger.info('processed job: %s', message)
if not handled:
time.sleep(poll_seconds)
if __name__ == '__main__':
+19
View File
@@ -0,0 +1,19 @@
"""
backend/workers/worker_shipping_notice.py
用途:货代发货 worker Supervisor / Compose 兼容启动脚本。
逻辑:转调 backend/worker.py,默认只消费 shipping 队列。
"""
from __future__ import annotations
import sys
from pathlib import Path
_backend_root = Path(__file__).resolve().parents[1]
if str(_backend_root) not in sys.path:
sys.path.insert(0, str(_backend_root))
from worker import main
if __name__ == '__main__':
main(queues=['shipping'])
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+7 -6
View File
@@ -16,7 +16,7 @@
|------|------|--------|----------|
| **pre-commit** | `git commit` | 已安装 Hook 的本机 | models 须带 migration;migration 须单 head;暂存 `frontend/` 时跑 `vue-tsc` |
| **commit-msg** | `git commit` | 已安装 Hook 的本机 | 提交信息须符合 [COMMIT_CONVENTION](./convention/COMMIT_CONVENTION.md)(commitlint) |
| **pre-push** | `git push` | 已安装 Hook 的本机 | 本次推送含 `frontend/` 变更时跑 `npm run build` |
| **pre-push** | `git push` | 已安装 Hook 的本机 | 本次推送含 migration 变更时校验单 head;含 `frontend/` 变更时跑 `npm run build` |
| **Jenkins CI** | push 触发流水线 | 全员(不装 Hook 也跑) | `npm ci && npm run build`(`scripts/ci_frontend_build.sh`) |
- Hook **不会**随 `git clone` 自动启用,需每人配置 `core.hooksPath=.githooks`。
@@ -74,7 +74,7 @@ chmod +x scripts/install_git_hooks.sh
[hook-install] Installed Git hooks successfully.
[hook-install] pre-commit: models 变更需带 migration;migration 须单 head;frontend 暂存时跑 vue-tsc
[hook-install] commit-msg: 校验提交信息格式(Conventional Commits)
[hook-install] pre-push: 推送含 frontend 变更时跑 npm run build
[hook-install] pre-push: 推送含 migration 变更时校验单 head;推送含 frontend 变更时跑 npm run build
[hook-install] core.hooksPath=.githooks
```
@@ -160,8 +160,9 @@ echo "feat(auth): add SMS login support" | npx commitlint
| 条件 | 行为 |
|------|------|
| 本次 push 的提交 diff 含 `backend/migrations/versions/*.py` | 运行 `scripts/check_migration_heads.py`,Alembic **必须仅 1 个 head** |
| 本次 push 的提交 diff 含 `frontend/` | 运行 `npm run build`(`vue-tsc -b && vite build`) |
| 无 `frontend/` 变更 | 直接通过 |
| 无 migration / `frontend/` 变更 | 直接通过 |
### 5.4 Jenkins CI
@@ -183,7 +184,7 @@ echo "feat(auth): add SMS login support" | npx commitlint
### 7.1 只跳过前端检查
migration 规则在 pre-commit 中仍会执行。
migration 规则在 pre-commit / pre-push 中仍会执行。
**Git Bash:**
@@ -213,7 +214,7 @@ git push --no-verify
| 变量 | 默认值 | 生效条件 |
|------|--------|----------|
| `SKIP_FRONTEND_HOOKS` | 未设置 | 设为 `1` 时跳过前端 vue-tsc / build |
| `SKIP_FRONTEND_HOOKS` | 未设置 | 设为 `1` 时仅跳过前端 vue-tsc / build;若本次 push 含 migration,仍会检查 migration |
| `SKIP_GIT_HOOKS` | 未设置 | 设为 `1` 时跳过前端检查(与上一项在前端逻辑等价) |
仓库内**没有**预置这些变量的配置文件,仅在单次命令前临时设置。
@@ -246,7 +247,7 @@ git push --no-verify
| `package.json` | 根目录 tooling 依赖(commitlint) |
| `scripts/install_git_hooks.sh` | 一键安装 |
| `scripts/ci_frontend_build.sh` | Jenkins / 本地 CI 同款 build |
| `scripts/check_migration_heads.py` | 离线校验 Alembic 仅 1 个 head(pre-commit 调用) |
| `scripts/check_migration_heads.py` | 离线校验 Alembic 仅 1 个 head(pre-commit / pre-push 调用) |
| `Jenkinsfile` | `Frontend Build (CI)` 阶段 |
| `docs/新人环境搭建与配置文档.md` | 新人环境 §4.2 简要说明 |
+17 -17
View File
@@ -6,7 +6,7 @@
- 一个提交只做一件事(或同一类紧密相关的事)。
- 提交信息要让不了解上下文的人也能快速理解“改了什么、为什么改”。
- **`type` 与 `scope` 使用英文**;**`subject` 与 `body` 使用中文**,便于团队阅读且 scope 与代码模块一一对应。
- **`type`** **与** **`scope`** **使用英文**;**`subject`** **与** **`body`** **使用中文**,便于团队阅读且 scope 与代码模块一一对应。
- 所有人遵循同一格式,减少代码评审和回溯成本。
## 2. 标准格式(必须)
@@ -79,20 +79,20 @@ Scope 应对齐代码模块,便于从提交信息定位到目录。选取规
2. 目录名转 kebab-case:`shipping_notice` → `shipping-notice`,`rohs_check` → `rohs-check`。
3. 跨模块改动选影响最大的模块;纯基建用 `jenkins`、`migration`、`deps`、`ci` 等。
| scope | 典型目录/模块 |
| --- | --- |
| `schedule` | `services/schedule/`、`api/schedule_admin`、前端 `features/admin/modules/schedules/` |
| `shipping-notice` | `services/shipping_notice/`、`api/workspace_shipping_notice` |
| `file-check` | `services/file_check*`、`api/file_check_tools` |
| `rohs-check` | RoHS 实例(历史 scope,新改动请用 `file-check`) |
| `knowledge-base` | `api/knowledge_base`、`services/knowledge_cleaning/` |
| `chat` | `api/chat`、前端 chat 相关 |
| `auth` | 登录认证 |
| `admin` | 管理后台通用 |
| `agents` | Agent 管理 |
| `api` | 跨模块 API 层重构 |
| `migration` | Alembic 迁移 |
| `jenkins` / `ci` / `deps` | 工程与依赖 |
| scope | 典型目录/模块 |
| ------------------------- | -------------------------------------------------------------------------------- |
| `schedule` | `services/schedule/`、`api/schedule_admin`、前端 `features/admin/modules/schedules/` |
| `shipping-notice` | `services/shipping_notice/`、`api/workspace_shipping_notice` |
| `file-check` | `services/file_check*`、`api/file_check_tools` |
| `rohs-check` | RoHS 实例(历史 scope,新改动请用 `file-check`) |
| `knowledge-base` | `api/knowledge_base`、`services/knowledge_cleaning/` |
| `chat` | `api/chat`、前端 chat 相关 |
| `auth` | 登录认证 |
| `admin` | 管理后台通用 |
| `agents` | Agent 管理 |
| `api` | 跨模块 API 层重构 |
| `migration` | Alembic 迁移 |
| `jenkins` / `ci` / `deps` | 工程与依赖 |
示例:
@@ -203,8 +203,8 @@ revert: feat(shipping-notice): 支持微信扫码结账
可选工具(尚未配置,可按需引入):
- `commitizen` 或 `cz-git`:交互式提交,降低学习成本。
- 参考链接:https://www.conventionalcommits.org/en/v1.0.0/
- 参考链接:<https://www.conventionalcommits.org/en/v1.0.0/>
---
***
维护建议:本规范由团队共同维护,若新增 `type` 或调整规则,请在评审通过后更新本文档并同步工具配置。
+136 -16
View File
@@ -1457,18 +1457,53 @@ LLM 节点不像 Code 节点一样通过函数参数声明入参;它的“输
| 输出名 | Dify 类型 | 说明 |
| --- | --- | --- |
| `ok` | Boolean | API `ok` 字段 |
| `error_code` | String | 如 `check_running` / `task_not_found` |
| `error_code` | String | 如 `check_running` / `no_data_to_check` / `task_not_found` |
| `message` | String | 提示或错误文案 |
| `run_id` | String | 检核批次 ID |
| `run_no` | String | 检核批次编号 |
| `run_status` | String | `running` / `success` / `failed` 等 |
| `run_status_label` | String | 批次状态中文文案 |
| `task_name` | String | 检核任务名称 |
| `started_at` | String | ISO 时间字符串 |
| `started_at_display` | String | 按北京时间格式化的启动时间 |
| `scene` | String | `started` / `already_running` / `no_data` / `failed` |
| `has_run_id` | Boolean | 是否拿到了有效批次 ID |
**完整 Python 代码**
```python
import json
from datetime import datetime, timezone, timedelta
_CN_TZ = timezone(timedelta(hours=8))
_STATUS_LABEL = {
"queued": "排队中",
"running": "进行中",
"success": "已完成",
"partial_failed": "部分失败",
"failed": "失败",
"cancelled": "已取消",
}
_DEFAULT_TASK_NAME = "RoHS 文件检核"
def _empty_result(message: str = "") -> dict:
return {
"ok": False,
"error_code": "invalid_response",
"message": message,
"run_id": "",
"run_no": "",
"run_status": "",
"run_status_label": "",
"task_name": "",
"started_at": "",
"started_at_display": "",
"scene": "failed",
"has_run_id": False,
}
def _load_tool_json(tool_json, tool_text):
if isinstance(tool_json, list) and tool_json:
@@ -1487,25 +1522,91 @@ def _load_tool_json(tool_json, tool_text):
return {}
return {}
def main(tool_json, tool_text) -> dict:
empty = {
"ok": False, "error_code": "invalid_response", "message": "",
"run_id": "", "run_no": "", "run_status": "", "task_name": "", "started_at": "",
}
def _format_started_at(iso_str) -> str:
if not iso_str:
return ""
s = str(iso_str).strip()
if not s:
return ""
if s.endswith("Z"):
s = s[:-1] + "+00:00"
try:
dt = datetime.fromisoformat(s)
except ValueError:
return str(iso_str)
if dt.tzinfo is None:
dt = dt.replace(tzinfo=timezone.utc)
local = dt.astimezone(_CN_TZ)
return f"{local.year}年{local.month}月{local.day}日 {local.hour:02d}:{local.minute:02d}"
def _status_label(status: str) -> str:
key = str(status or "").strip().lower()
if not key:
return ""
return _STATUS_LABEL.get(key, status)
def _resolve_scene(ok: bool, error_code: str) -> str:
code = str(error_code or "").strip()
if ok:
return "started"
if code == "check_running":
return "already_running"
if code == "no_data_to_check":
return "no_data"
return "failed"
def _safe_str(value) -> str:
if value is None:
return ""
return str(value).strip()
def main(tool_json, tool_text: str = "") -> dict:
data = _load_tool_json(tool_json, tool_text)
if not data:
empty["message"] = "无 Tool 响应"
empty = _empty_result("目前没有资料需要检核。")
empty["error_code"] = "no_data_to_check"
empty["scene"] = "no_data"
return empty
run = data.get("run") or {}
if not isinstance(run, dict):
run = {}
ok = bool(data.get("ok"))
error_code = _safe_str(data.get("error_code"))
message = _safe_str(data.get("message"))
run_id = _safe_str(run.get("run_id"))
run_no = _safe_str(run.get("run_no"))
run_status = _safe_str(run.get("status"))
task_name = _safe_str(
run.get("task_name") or run.get("schedule_name") or _DEFAULT_TASK_NAME
)
started_at = _safe_str(run.get("started_at"))
return {
"ok": bool(data.get("ok")),
"error_code": str(data.get("error_code") or ""),
"message": str(data.get("message") or ""),
"run_id": str(run.get("run_id") or ""),
"run_no": str(run.get("run_no") or ""),
"run_status": str(run.get("status") or ""),
"task_name": str(run.get("task_name") or run.get("schedule_name") or ""),
"started_at": str(run.get("started_at") or ""),
"ok": ok,
"error_code": error_code,
"message": message,
"run_id": run_id,
"run_no": run_no,
"run_status": run_status,
"run_status_label": _status_label(run_status),
"task_name": task_name,
"started_at": started_at,
"started_at_display": _format_started_at(started_at),
"scene": _resolve_scene(ok, error_code),
"has_run_id": bool(run_id),
}
```
@@ -1525,6 +1626,7 @@ def main(tool_json, tool_text) -> dict:
| --- | --- |
| `解析启动检核响应.ok == true` | [§3.11 Answer:检核已启动](#311-answer检核已启动) |
| `解析启动检核响应.error_code == "check_running"` | [§3.12 Answer:检核进行中](#312-answer检核进行中) |
| `解析启动检核响应.error_code == "no_data_to_check"` | [§3.13 Answer:没有资料需要检核](#313-answer没有资料需要检核) |
| 默认 | [§3.24 Answer:错误兜底(启动检核 body)](#324-answer错误兜底启动检核) |
---
@@ -1572,6 +1674,24 @@ def main(tool_json, tool_text) -> dict:
---
### 3.13 Answer:没有资料需要检核
**上游**:IF 启动业务分支(`error_code == "no_data_to_check"`)
**引用变量**:`解析启动检核响应.message` · **String**
**回复模板**
```text
目前没有资料需要检核,暂时不用启动本次检核。
{{#解析启动检核响应.message#}}
如果后续有新的资料进入检核范围,再发起一次即可。
```
---
### 3.14 Code:提取查询参数
**上游**:IF 意图分类(`check_status` 分支)
@@ -2031,7 +2151,7 @@ def main(tool_json, tool_text) -> dict:
### 3.24 Answer:错误兜底(启动检核 body)
**上游**:IF 启动业务分支(Tool **成功出口** 后,body 中 `ok=false` 且非 `check_running`;如 `invalid_response`)
**上游**:IF 启动业务分支(Tool **成功出口** 后,body 中 `ok=false` 且非 `check_running`、`no_data_to_check`;如 `invalid_response`)
**引用变量**:`解析启动检核响应.message` · **String**;`解析启动检核响应.error_code` · **String**
+11 -2
View File
@@ -3,7 +3,7 @@
"info": {
"title": "Hxops Shipping Notice Tools",
"version": "1.0.0",
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。"
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。鉴权:Authorization Bearer 或 X-Integration-Key。"
},
"servers": [
{
@@ -157,6 +157,15 @@
"raw_text": {
"type": "string",
"description": "待解析的发货通知全文"
},
"structured": {
"type": "object",
"description": "Dify LLM 解析后的结构化结果对象。若提供,后端优先使用该对象中的 lines/confidence/reservation_id 等字段落库。",
"additionalProperties": true
},
"lang": {
"type": "string",
"description": "可选语言代码:zh|en|th"
}
},
"required": [
@@ -935,4 +944,4 @@
}
}
}
}
}
+61
View File
@@ -0,0 +1,61 @@
版本周期: 2026-06-09 ~ 2026-06-22
tag: V26.6.2
起始 commit: ff7c227(feat(环境配置): 添加企业微信通知和货代发货Agent环境配置)
本周更新亮点:
1. 前端架构重构(V3)
a. 按 Feature-Module 垂直切分(auth / workspace / chat / admin / kb),统一 composables + Pinia 状态管理
b. Chat 与 Workspace 子路由懒加载,减少首屏体积与重复请求
c. 统一异常处理与错误提示,流式对话错误映射为面向用户的友好文案
d. Admin 应用管理布局优化,新建/编辑弹框抽离为独立子组件
2. 文件检核(原 RoHS 检核升级)
a. 新增文件检核工具 API,逐步替换原 RoHS 检核能力
b. 支持检核进度实时展示、判定统计与当前步骤信息
c. 检核执行过程中可下载 Excel 结果;支持历史检核报告检索
d. 对话轮次与检核批次绑定;排程管理 cron 支持图形化配置
e. 更新 Chatflow 编排与 API 文档,完善 API Key 配置说明
3. FAQ 高频问答缓存
a. 缓存高频问题及预置答案,命中后直接返回,跳过 Dify 调用以提升响应速度
b. 知识库关联文档更新时,自动标记关联问题为「待复审」并暂停缓存命中
c. 排程管理支持触发热点问题离线聚合
4. 固定资产(固资)Agent 增强
a. 查询结果去重、分页加载优化,修复查询状态中文显示问题
b. 扩展 HXJM / HTT / HTE 等查询维度;支持供应商模糊查询
c. 本人明细资产查询优化;表单字段过多时滑动体验改进
d. 本地化固资快照:优先查本地缓存,可降级 ERP 直查;定期同步 ERP 全量资产信息
5. 货代发货通知(Shipping Notice)
a. 环境变量与接口增强,完善企业微信通知及 Agent 参数配置
b. 新增发货批次与任务管理,支持批次创建与任务处理
6. 排程管理
a. 界面交互优化,新增弹窗控制逻辑
b. 新增调度时区转换功能
7. 管理控制台(Admin)
a. 用户管理改为服务端分页,避免拉取全量用户;修复删除用户未级联清理等问题
b. 用户字段唯一性校验;新增/修改用户同步 Casdoor(仅密码变更时同步密码)
c. 企业微信管理支持从 OA 一键同步企业微信 ID
d. 聊天日志报表优化;公告布局调整并在首页滚动展示
e. 支持企业微信重置密码
8. 聊天与对话链路
a. 新增对话流性能监控及相关日志输出
b. 修复 Dify 返回 token 但 chat_logs 记录 tokens_used 为 0 的问题
9. 知识库
a. 修复 PPT 图片解析同步 Dify 时携带 base64 数据的问题
b. Excel 上传预处理优化:由 markdown 改为 key=value 格式,改善 Dify 切块命中效果
10. 构建与运维
a. Jenkins 构建保留最近 10 组镜像,超出自动清除旧镜像
b. 测试环境 Oracle Client 替换为 ARM 版本;加速后端镜像构建并修复 Debian 12 ODBC 配置
c. 修复 Alembic migration 多 head 问题
11. Bug 修复与体验优化
a. 检核任务禁用状态处理及错误信息修复
b. Admin 若干样式与布局微调
+2804 -599
View File
File diff suppressed because it is too large. Load diff
@@ -214,6 +214,49 @@ export async function switchWorkspaceShippingBatchFocusTask(batchNo: string, tas
return body;
}
/**
* 重试当前发货任务。
* @param taskNo - 发货任务编号
* @param comment - 可选重试备注
* @returns 重试结果
*/
export async function retryWorkspaceShippingTask(taskNo: string, comment?: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/retry`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(comment ? { comment } : {}),
},
);
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
/**
* 重试批次中仍可自动推进的任务。
* @param batchNo - 批次编号
* @returns 批次重试结果
*/
export async function retryWorkspaceShippingBatchPending(batchNo: string) {
const res = await fetch(
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/retry-pending`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({}),
},
);
const body = (await res.json().catch(() => ({}))) as { status?: string; message?: string; error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
/**
* 提交人工决策。
* @param taskNo - 发货任务编号
@@ -390,6 +433,28 @@ export async function autoProgressWorkspaceShippingTask(taskNo: string, lang?: s
return body;
}
/**
* 以用户态触发通知解析,供批量上传后逐任务补齐首轮解析。
* @param taskNo - 发货任务编号
* @param lang - 可选语言代码
* @returns 解析与可能的自动推进结果
*/
export async function parseWorkspaceShippingNotice(taskNo: string, lang?: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/parse-notice`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(lang ? { lang } : {}),
},
);
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
/**
* 标记货代系统已人工上传完成。
* @param taskNo - 发货任务编号
@@ -439,6 +504,7 @@ export type {
ShippingBatchSummary,
ShippingChatAction,
ShippingChatActionsResponse,
ShippingCurrentStepProgress,
ShippingDecisionResponse,
ShippingInventoryUploadResponse,
ShippingMatchLineResult,
@@ -1,10 +1,10 @@
/**
* features/chat/components/ChatViewContent.vue
* 对话页主区域:侧栏、消息列表、输入栏与内置浏览器。
* 用途:对话页主区域,组合侧栏、发货批次进度区、消息列表、输入栏与内置浏览器。
* 依赖:ChatSidebar、ChatMessageList、ChatInputBar、ShippingBatchProgressPanel、chat.context。
* 逻辑:本文件只做页面结构编排;发货批次进度样式与任务续办交互下沉到独立面板组件。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { Loader2 } from 'lucide-vue-next';
import ChatShell from '@/shared/layouts/ChatShell.vue';
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
@@ -12,68 +12,10 @@ import ChatInputBar from '@/features/chat/components/ChatInputBar.vue';
import ChatMessageList from '@/features/chat/components/ChatMessageList.vue';
import ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
import ShippingWorkflowStepper from '@/features/chat/components/ShippingWorkflowStepper.vue';
import ShippingBatchProgressPanel from '@/features/chat/components/ShippingBatchProgressPanel.vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { buildShippingWorkflowSteps } from '@/features/chat/shipping';
import type { ShippingTaskSummary } from '@/features/chat/types/shipping.api.types';
const page = useChatPageContext();
const { t } = useI18n();
const statusMeta = (status?: string | null) => {
const map: Record<string, { label: string; chip: string }> = {
created: { label: t('chat.shippingNoticeUi.status.created'), chip: 'bg-slate-100 text-slate-700' },
waiting_inventory: { label: t('chat.shippingNoticeUi.status.waitingInventory'), chip: 'bg-amber-100 text-amber-700' },
inventory_ready: { label: t('chat.shippingNoticeUi.status.inventoryReady'), chip: 'bg-sky-100 text-sky-700' },
matched: { label: t('chat.shippingNoticeUi.status.matched'), chip: 'bg-emerald-100 text-emerald-700' },
waiting_upload: { label: t('chat.shippingNoticeUi.status.waitingUpload'), chip: 'bg-orange-100 text-orange-700' },
uploaded: { label: t('chat.shippingNoticeUi.status.uploaded'), chip: 'bg-emerald-100 text-emerald-700' },
upload_failed: { label: t('chat.shippingNoticeUi.status.uploadFailed'), chip: 'bg-rose-100 text-rose-700' },
rejected: { label: t('chat.shippingNoticeUi.status.rejected'), chip: 'bg-rose-100 text-rose-700' },
closed: { label: t('chat.shippingNoticeUi.status.closed'), chip: 'bg-slate-100 text-slate-700' },
};
return map[String(status || '').trim()] || { label: String(status || t('chat.shippingNoticeUi.processing')), chip: 'bg-slate-100 text-slate-700' };
};
const stepLabel = (step?: string | null) => {
const map: Record<string, string> = {
step1_notice_submit: t('chat.shippingNoticeUi.currentStep.noticeParse'),
step2_inventory_prepare: t('chat.shippingNoticeUi.currentStep.inventoryPrepare'),
step3_inventory_match: t('chat.shippingNoticeUi.currentStep.inventoryMatch'),
step4_shortage_review: t('chat.shippingNoticeUi.currentStep.shortageHandle'),
step5_export_excel: t('chat.shippingNoticeUi.currentStep.generateExcel'),
step6_upload_freight: t('chat.shippingNoticeUi.currentStep.uploadFreight'),
step7_finish: t('chat.shippingNoticeUi.currentStep.finishArchive'),
};
return map[String(step || '').trim()] || t('chat.shippingNoticeUi.processing');
};
const currentShippingTask = computed<ShippingTaskSummary | null>(() => {
const focusTaskNo = String(page.shippingBatchSummary?.current_focus_task_no || '').trim();
if (!focusTaskNo || !Array.isArray(page.shippingBatchTasks)) return null;
return page.shippingBatchTasks.find((task: ShippingTaskSummary) => task.task_no === focusTaskNo) || null;
});
const currentShippingTaskSource = computed(() => currentShippingTask.value || page.activeShippingTaskDetail || null);
const currentShippingSteps = computed(() => buildShippingWorkflowSteps(currentShippingTaskSource.value));
const currentShippingBatchProgress = computed(() => {
const task = currentShippingTask.value;
if (!task?.batch_index || !task?.batch_total) return '';
return t('chat.shippingNoticeUi.batchProgress', { index: task.batch_index, total: task.batch_total });
});
const batchCompletedCount = computed(() =>
Number(page.shippingBatchSummary?.process_summary?.completed || 0),
);
const batchRunningCount = computed(() =>
Number(page.shippingBatchSummary?.process_summary?.running || 0),
);
const batchFileCount = computed(() =>
Number(page.shippingBatchSummary?.file_count || 0),
);
const batchCompletionPercent = computed(() => {
if (!batchFileCount.value) return 0;
return Math.min(100, Math.max(0, Math.round((batchCompletedCount.value / batchFileCount.value) * 100)));
});
</script>
<template>
@@ -141,186 +83,17 @@ const batchCompletionPercent = computed(() => {
<template v-else>
<div class="flex min-h-0 flex-1">
<div class="flex min-h-0 flex-1 flex-col">
<div
v-if="page.isShippingNoticeAgent && (page.shippingBatchSummary || currentShippingTaskSource)"
class="mx-4 mt-4 rounded-3xl border border-default/80 bg-[linear-gradient(135deg,rgba(255,255,255,0.96),rgba(246,248,251,0.92))] px-4 py-3 shadow-sm"
>
<div class="flex flex-wrap items-start justify-between gap-3">
<div class="space-y-1">
<div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">
{{ page.shippingBatchSummary ? t('chat.shippingNoticeUi.batchTitle') : t('chat.shippingNoticeUi.taskTitle') }}
</div>
<div class="flex flex-wrap items-center gap-2">
<span
v-if="page.shippingBatchSummary"
class="font-mono text-sm font-semibold text-primary"
>
{{ page.shippingBatchSummary.batch_no }}
</span>
<span
v-else-if="currentShippingTaskSource"
class="font-mono text-sm font-semibold text-primary"
>
{{ currentShippingTaskSource.task_no }}
</span>
<span
v-if="page.shippingBatchSummary?.current_focus_task_no"
class="rounded-full bg-brand-50 px-2.5 py-1 text-xs font-medium text-brand-700"
>
{{ t('chat.shippingNoticeUi.currentTask', { taskId: page.shippingBatchSummary.current_focus_task_no }) }}
</span>
<span
v-if="currentShippingBatchProgress"
class="rounded-full bg-sky-50 px-2.5 py-1 text-xs font-medium text-sky-700"
>
{{ currentShippingBatchProgress }}
</span>
</div>
<div v-if="currentShippingTaskSource" class="flex flex-wrap items-center gap-2 text-xs text-secondary">
<span class="truncate font-medium text-primary">
{{ currentShippingTaskSource.customer_name || currentShippingTaskSource.source_file_name || t('chat.shippingNoticeUi.currentNotice') }}
</span>
<span
class="rounded-full px-2 py-0.5 font-medium"
:class="statusMeta(currentShippingTaskSource.process_status).chip"
>
{{ statusMeta(currentShippingTaskSource.process_status).label }}
</span>
<span class="text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}:{{ stepLabel(currentShippingTaskSource.current_step) }}</span>
</div>
<ShippingWorkflowStepper
v-if="currentShippingTaskSource"
:steps="currentShippingSteps"
compact
class="pt-2"
/>
<div class="flex flex-wrap gap-2 pt-1 text-xs">
<button
v-if="page.shippingBatchSummary"
type="button"
class="rounded-full border border-default px-2.5 py-1 text-secondary transition hover:bg-surface-soft"
@click="page.input = '上一票'"
>
{{ t('chat.shippingNoticeUi.prevTask') }}
</button>
<button
v-if="page.shippingBatchSummary"
type="button"
class="rounded-full border border-default px-2.5 py-1 text-secondary transition hover:bg-surface-soft"
@click="page.input = '下一票'"
>
{{ t('chat.shippingNoticeUi.nextTask') }}
</button>
<button
v-if="page.shippingBatchTasks?.length > 1"
type="button"
class="rounded-full border border-default px-2.5 py-1 text-secondary transition hover:bg-surface-soft"
@click="page.shippingBatchTasksExpanded = !page.shippingBatchTasksExpanded"
>
{{ page.shippingBatchTasksExpanded ? t('chat.shippingNoticeUi.collapseTasks') : t('chat.shippingNoticeUi.viewTasks') }}
</button>
</div>
</div>
<div v-if="page.shippingBatchSummary" class="grid grid-cols-3 gap-2 text-right text-xs">
<div class="rounded-2xl bg-surface px-3 py-2">
<div class="text-muted">{{ t('chat.shippingNoticeUi.fileCount') }}</div>
<div class="mt-1 text-sm font-semibold text-primary">{{ batchFileCount }}</div>
</div>
<div class="rounded-2xl bg-surface px-3 py-2">
<div class="text-muted">{{ t('chat.shippingNoticeUi.runningCount') }}</div>
<div class="mt-1 text-sm font-semibold text-primary">{{ batchRunningCount }}</div>
</div>
<div class="rounded-2xl bg-surface px-3 py-2">
<div class="text-muted">{{ t('chat.shippingNoticeUi.completedCount') }}</div>
<div class="mt-1 text-sm font-semibold text-primary">{{ batchCompletedCount }}</div>
</div>
</div>
</div>
<div
v-if="page.shippingBatchSummary"
class="mt-3 space-y-1 border-t border-default/70 pt-3"
>
<div class="flex items-center justify-between text-[11px] text-muted">
<span>{{ t('chat.shippingNoticeUi.batchProgressTitle') }}</span>
<span>{{ batchCompletedCount }}/{{ batchFileCount }} · {{ batchCompletionPercent }}%</span>
</div>
<div class="h-2 overflow-hidden rounded-full bg-slate-200">
<div
class="h-full rounded-full bg-brand-500 transition-all"
:style="{ width: `${batchCompletionPercent}%` }"
/>
</div>
</div>
<div
v-if="page.shippingInventorySelectionActive && page.shippingBatchTasks?.length > 1"
class="mt-3 flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-amber-200 bg-amber-50/90 px-3 py-3 text-sm text-amber-900"
>
<div class="space-y-1">
<div class="font-semibold">{{ t('chat.shippingNoticeUi.inventoryTaskPickTitle') }}</div>
<div class="text-xs text-amber-800">
{{ t('chat.shippingNoticeUi.inventoryTaskPickHint') }}
</div>
</div>
<button
type="button"
class="rounded-full border border-amber-300 px-3 py-1 text-xs font-medium text-amber-800 transition hover:bg-amber-100"
@click="page.cancelShippingInventoryTaskSelection()"
>
{{ t('chat.shippingNoticeUi.cancelInventoryTaskPick') }}
</button>
</div>
<div
v-if="page.shippingBatchTasksExpanded && page.shippingBatchTasks?.length"
class="mt-3 grid gap-2 border-t border-default/70 pt-3 sm:grid-cols-2 xl:grid-cols-3"
>
<button
v-for="task in page.shippingBatchTasks"
:key="task.task_no"
type="button"
class="rounded-2xl border px-3 py-3 text-left transition"
:class="task.task_no === page.shippingBatchSummary?.current_focus_task_no ? 'border-brand-300 bg-brand-50/80 shadow-sm' : 'border-default bg-surface hover:bg-surface-soft'"
@click="page.switchShippingFocusTask(task.task_no)"
>
<div class="flex items-start justify-between gap-2">
<div class="font-mono text-xs font-semibold text-primary">{{ task.task_no }}</div>
<span
class="rounded-full px-2 py-0.5 text-[11px] font-medium"
:class="statusMeta(task.process_status).chip"
>
{{ statusMeta(task.process_status).label }}
</span>
</div>
<div class="mt-2 truncate text-sm font-medium text-secondary">{{ task.customer_name || task.source_file_name || '未命名通知' }}</div>
<div class="mt-1 text-[11px] text-muted">
{{ stepLabel(task.current_step) }}
<span v-if="task.batch_index && task.batch_total">
· {{ t('chat.shippingNoticeUi.batchProgress', { index: task.batch_index, total: task.batch_total }) }}
</span>
</div>
<div
v-if="page.shippingInventorySelectionActive"
class="mt-3 flex items-center justify-between gap-2"
>
<span
v-if="page.shippingInventorySelectionTaskId === task.task_no"
class="rounded-full bg-brand-50 px-2 py-1 text-[11px] font-medium text-brand-700"
>
{{ t('chat.shippingNoticeUi.inventoryTargetTask', { taskId: task.task_no }) }}
</span>
<span v-else class="text-[11px] text-muted">
{{ t('chat.shippingNoticeUi.inventoryTargetIdle') }}
</span>
<button
type="button"
class="rounded-full border border-brand-200 px-2.5 py-1 text-[11px] font-medium text-brand-700 transition hover:bg-brand-50"
@click.stop="page.selectShippingInventoryUploadTask(task.task_no)"
>
{{ t('chat.shippingNoticeUi.uploadInventoryToTask') }}
</button>
</div>
</button>
</div>
</div>
<ShippingBatchProgressPanel
v-if="page.isShippingNoticeAgent && (page.shippingBatchSummary || page.activeShippingTaskDetail)"
:batch-summary="page.shippingBatchSummary"
:batch-tasks="page.shippingBatchTasks"
:active-task-detail="page.activeShippingTaskDetail"
:tasks-expanded="page.shippingBatchTasksExpanded"
:inventory-selection-active="page.shippingInventorySelectionActive && page.shippingBatchTasks?.length > 1"
@update:tasks-expanded="page.shippingBatchTasksExpanded = $event"
@focus-task="page.switchShippingFocusTask"
@resume-task="page.resumeShippingTask"
/>
<ChatMessageList
:messages="page.messages"
@@ -0,0 +1,443 @@
<script setup lang="ts">
/**
* features/chat/components/ShippingBatchProgressPanel.vue
* 用途:发货通知聊天顶部批次进度卡片,按原型方案 C 展示批次概览、任务切换列表、七步进度与续办弹层。
* 依赖:shippingStepper、shipping.api.types、vue-i18n、lucide-vue-next。
* 逻辑:上游由 ChatViewContent 传入批次/任务状态;本组件只负责展示与抛出 focus/resume 事件,不直接请求后端。
*/
import { computed, ref } from 'vue';
import { List, PlayCircle, X } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { buildShippingWorkflowSteps, type ShippingWorkflowStepItem } from '@/features/chat/shipping';
import { retryWorkspaceShippingBatchPending } from '@/features/chat/api/shipping.api';
import { useMessage } from '@/shared/composables/useMessage';
import type {
ShippingBatchSummary,
ShippingTaskDetail,
ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
const props = defineProps<{
batchSummary: ShippingBatchSummary | null;
batchTasks: ShippingTaskSummary[];
activeTaskDetail: ShippingTaskDetail | null;
tasksExpanded: boolean;
inventorySelectionActive: boolean;
}>();
const emit = defineEmits<{
'update:tasksExpanded': [value: boolean];
'focus-task': [taskNo: string];
'resume-task': [taskNo: string];
}>();
const { t } = useI18n();
const msg = useMessage();
const showTaskDialog = ref(false);
const retryingPending = ref(false);
const COMPLETED_PROCESS_STATUSES = new Set(['uploaded', 'closed']);
const CIRCLED_NUMBERS = ['①', '②', '③', '④', '⑤', '⑥', '⑦', '⑧', '⑨'];
const processSummary = computed(() => {
const summary = props.batchSummary?.process_summary || null;
const total = Number(summary?.total || props.batchSummary?.file_count || props.batchTasks.length || 0);
const completed = Number(
summary?.completed
|| props.batchTasks.filter((task) => COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())).length
|| 0,
);
const runningFallback = props.batchTasks.some(
(task) => !COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim()),
) ? 1 : 0;
const running = Number(summary?.running || runningFallback || 0);
const pending = Math.max(0, Number(summary?.pending ?? (total - completed - running)));
return { total, completed, running, pending };
});
const currentTask = computed<ShippingTaskSummary | ShippingTaskDetail | null>(() => {
const focusTaskNo = String(props.batchSummary?.current_focus_task_no || '').trim().toUpperCase();
if (focusTaskNo) {
return props.batchTasks.find((task) => String(task.task_no || '').trim().toUpperCase() === focusTaskNo)
|| props.activeTaskDetail
|| null;
}
return props.activeTaskDetail || props.batchTasks[0] || null;
});
const currentTaskNo = computed(() => String(currentTask.value?.task_no || '').trim().toUpperCase());
const currentTaskName = computed(() =>
String(
currentTask.value?.source_file_name
|| currentTask.value?.customer_name
|| t('chat.shippingNoticeUi.currentNotice'),
).trim(),
);
const currentTaskIndex = computed(() =>
Number(
currentTask.value?.batch_index
|| props.batchSummary?.process_summary?.current_index
|| 0,
),
);
const currentTaskTotal = computed(() =>
Number(
currentTask.value?.batch_total
|| props.batchSummary?.file_count
|| processSummary.value.total
|| 0,
),
);
const currentSteps = computed(() => buildShippingWorkflowSteps(currentTask.value));
const resolveActiveStep = (steps: ShippingWorkflowStepItem[]) =>
steps.findIndex((step) => step.status === 'current' || step.status === 'blocked');
const currentStepMeta = computed(() => {
const steps = currentSteps.value;
if (!steps.length) return { index: 0, label: t('chat.shippingNoticeUi.processing') };
const activeIndex = resolveActiveStep(steps);
const safeIndex = activeIndex >= 0 ? activeIndex : steps.length - 1;
return {
index: safeIndex + 1,
label: t(steps[safeIndex]?.label || 'chat.shippingNoticeUi.processing'),
};
});
const summaryLine = computed(() => t('chat.shippingNoticeUi.batchSummaryLine', {
total: processSummary.value.total,
completed: processSummary.value.completed,
running: processSummary.value.running,
pending: processSummary.value.pending,
}));
/**
* 将任务状态映射为原型中列表右侧的紧凑状态文案。
*
* 核心逻辑:完成态显示“已完成”,阻塞态显示“步骤 X 待确认”,运行态显示“步骤 X/Y”,
* 其余回退到“排队中”,以匹配原型中批次队列的短标签风格。
* @param task - 任务摘要或详情
* @returns 原型列表使用的短文案与颜色类
*/
const resolveTaskStateMeta = (task: ShippingTaskSummary | ShippingTaskDetail | null) => {
if (!task) {
return { text: t('chat.shippingNoticeUi.queuedState'), tone: 'text-muted' };
}
if (COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())) {
return { text: t('chat.shippingNoticeUi.completedState'), tone: 'text-emerald-700' };
}
const steps = buildShippingWorkflowSteps(task);
const blockedIndex = steps.findIndex((step) => step.status === 'blocked');
if (blockedIndex >= 0) {
return {
text: t('chat.shippingNoticeUi.stepNeedsConfirm', { step: blockedIndex + 1 }),
tone: 'text-amber-700',
};
}
const activeIndex = resolveActiveStep(steps);
if (activeIndex >= 0) {
return {
text: t('chat.shippingNoticeUi.stepFraction', { current: activeIndex + 1, total: steps.length }),
tone: 'text-brand-600',
};
}
return { text: t('chat.shippingNoticeUi.queuedState'), tone: 'text-muted' };
};
const shortTaskNo = (taskNo?: string | null) => {
const value = String(taskNo || '').trim();
if (value.length <= 10) return value || '--';
return `${value.slice(0, 5)}...${value.slice(-3)}`;
};
const isCurrentTask = (taskNo?: string | null) =>
String(taskNo || '').trim().toUpperCase() === currentTaskNo.value;
const openTaskDialog = () => {
if (!props.batchTasks.length) return;
showTaskDialog.value = true;
};
const handleFocusTask = (taskNo: string) => {
emit('focus-task', taskNo);
};
const handleResumeTask = (taskNo: string) => {
showTaskDialog.value = false;
emit('resume-task', taskNo);
};
const handleRetryPending = async () => {
const batchNo = String(props.batchSummary?.batch_no || '').trim();
if (!batchNo || retryingPending.value) return;
retryingPending.value = true;
try {
const result = await retryWorkspaceShippingBatchPending(batchNo);
msg.success(result.message || t('chat.shippingNoticeUi.retryPendingDone'));
} catch (error) {
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
} finally {
retryingPending.value = false;
}
};
</script>
<template>
<section
class="mx-auto mt-4 w-full max-w-4xl overflow-hidden rounded-2xl border border-sky-100 bg-gradient-to-br from-sky-50 via-white to-emerald-50 shadow-sm"
>
<div class="border-b border-sky-100/80 px-4 py-3">
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="text-xs text-slate-500">
{{ summaryLine }}
</div>
<div class="flex items-center gap-2">
<button
v-if="batchSummary?.batch_no"
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white/80 px-2.5 py-1 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="retryingPending"
@click="handleRetryPending"
>
{{ retryingPending ? t('chat.shippingNoticeUi.retrying') : t('chat.shippingNoticeUi.retryPendingTasks') }}
</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-default bg-white/80 px-2.5 py-1 text-xs font-medium text-secondary transition hover:border-brand-300 hover:bg-brand-50 hover:text-brand-700"
@click="openTaskDialog"
>
<List class="h-3.5 w-3.5" />
{{ t('chat.shippingNoticeUi.taskListResume') }}
</button>
<button
v-if="batchTasks.length > 1"
type="button"
class="text-xs font-medium text-brand-600 transition hover:text-brand-700"
@click="emit('update:tasksExpanded', !tasksExpanded)"
>
{{ tasksExpanded ? `${t('chat.shippingNoticeUi.collapseTaskList')} ▲` : `${t('chat.shippingNoticeUi.expandTaskList')} ▼` }}
</button>
</div>
</div>
<div
v-if="tasksExpanded && batchTasks.length"
class="mt-2 space-y-1 border-t border-dashed border-sky-100 pt-2"
>
<button
v-for="(task, index) in batchTasks"
:key="task.task_no"
type="button"
class="flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-xs transition hover:bg-white/70"
:class="isCurrentTask(task.task_no) ? 'bg-white/80 ring-1 ring-brand-200' : ''"
@click="handleFocusTask(task.task_no)"
>
<span class="text-muted">{{ CIRCLED_NUMBERS[index] || `${index + 1}` }}</span>
<span class="flex-1 truncate" :class="isCurrentTask(task.task_no) ? 'font-medium text-secondary' : ''">
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
</span>
<span class="font-mono text-brand-600">{{ shortTaskNo(task.task_no) }}</span>
<span
class="rounded-full px-1.5 py-0.5"
:class="isCurrentTask(task.task_no) ? 'text-brand-600' : resolveTaskStateMeta(task).tone"
>
{{ resolveTaskStateMeta(task).text }}
</span>
</button>
</div>
</div>
<div class="space-y-3 px-4 py-4">
<div class="flex flex-wrap items-baseline justify-between gap-2">
<div>
<div class="font-mono text-sm font-semibold text-brand-700">
{{ currentTaskNo || batchSummary?.batch_no || '--' }}
</div>
<div class="mt-0.5 text-xs text-muted">
当前 · 第 {{ currentTaskIndex || 0 }}/{{ currentTaskTotal || 0 }} 笔 ·
<em class="not-italic text-secondary">{{ currentTaskName }}</em>
</div>
</div>
<div class="text-xs text-muted">
步骤 <strong class="text-secondary">{{ currentStepMeta.index }}</strong>/{{ currentSteps.length || 7 }} · {{ currentStepMeta.label }}
</div>
</div>
<div class="scheme-stepper">
<template v-for="(step, index) in currentSteps" :key="step.id">
<div
class="scheme-step-node"
:class="{
done: step.status === 'completed',
active: step.status === 'current' || step.status === 'blocked',
}"
>
<div class="scheme-step-dot">
{{ step.status === 'completed' ? '✓' : index + 1 }}
</div>
<div class="scheme-step-label">{{ t(step.label) }}</div>
</div>
</template>
</div>
<div
v-if="inventorySelectionActive"
class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800"
>
{{ t('chat.shippingNoticeUi.inventoryTaskPickHint') }}
</div>
</div>
<Teleport to="body">
<div
v-if="showTaskDialog"
class="fixed inset-0 z-[120] flex items-center justify-center bg-slate-900/30 px-4"
@click.self="showTaskDialog = false"
>
<div class="w-full max-w-[620px] rounded-[28px] bg-white p-5 shadow-[0_24px_80px_rgba(15,23,42,0.22)]">
<div class="flex items-start justify-between gap-4">
<div>
<div class="text-[32px] font-semibold tracking-tight text-slate-800">
{{ t('chat.shippingNoticeUi.taskListTitle') }}
</div>
<div class="mt-1 text-sm text-slate-500">
{{ t('chat.shippingNoticeUi.taskListHint') }}
</div>
</div>
<button
type="button"
class="rounded-full p-2 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600"
@click="showTaskDialog = false"
>
<X class="h-5 w-5" />
</button>
</div>
<div class="mt-5 space-y-3">
<button
v-for="task in batchTasks"
:key="task.task_no"
type="button"
class="w-full rounded-3xl border px-4 py-4 text-left transition hover:border-[#8bc8f5] hover:bg-[#f8fbff]"
:class="isCurrentTask(task.task_no) ? 'border-[#8bc8f5] bg-[#f5fbff]' : 'border-[#e5edf5] bg-white'"
@click="handleResumeTask(task.task_no)"
>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<div class="font-mono text-lg font-semibold text-[#1277c8]">
{{ task.task_no }}
</div>
<div class="mt-1 truncate text-[15px] text-slate-700">
{{ task.source_file_name || task.customer_name || t('chat.shippingNoticeUi.currentNotice') }}
</div>
<div class="mt-1 text-sm text-slate-500">
{{ resolveTaskStateMeta(task).text }}
</div>
<div
v-if="isCurrentTask(task.task_no)"
class="mt-2 inline-flex items-center gap-1 text-sm font-medium text-[#1277c8]"
>
{{ t('chat.shippingNoticeUi.currentFocus') }}
</div>
</div>
<div class="flex shrink-0 items-center gap-2">
<span
class="rounded-full px-3 py-1 text-sm font-medium"
:class="COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())
? 'bg-emerald-100 text-emerald-700'
: isCurrentTask(task.task_no)
? 'bg-sky-100 text-sky-700'
: 'bg-amber-100 text-amber-700'"
>
{{ COMPLETED_PROCESS_STATUSES.has(String(task.process_status || '').trim())
? t('chat.shippingNoticeUi.completedState')
: isCurrentTask(task.task_no)
? t('chat.shippingNoticeUi.runningState')
: t('chat.shippingNoticeUi.pendingState') }}
</span>
<PlayCircle class="h-5 w-5 text-[#1492df]" />
</div>
</div>
</button>
</div>
</div>
</div>
</Teleport>
</section>
</template>
<style scoped>
.scheme-stepper {
display: flex;
overflow-x: auto;
padding-bottom: 0.25rem;
}
.scheme-step-node {
position: relative;
flex: 1;
min-width: 52px;
text-align: center;
}
.scheme-step-node:not(:last-child)::after {
content: '';
position: absolute;
top: 10px;
left: calc(50% + 11px);
width: calc(100% - 22px);
height: 2px;
background: #e2e8f0;
z-index: 0;
}
.scheme-step-node.done:not(:last-child)::after {
background: #0284c7;
}
.scheme-step-node.active:not(:last-child)::after {
background: linear-gradient(90deg, #0284c7 50%, #e2e8f0 50%);
}
.scheme-step-dot {
position: relative;
z-index: 1;
display: grid;
place-items: center;
width: 20px;
height: 20px;
margin: 0 auto 0.25rem;
border: 2px solid #e2e8f0;
border-radius: 9999px;
background: #fff;
color: #64748b;
font-size: 0.55rem;
font-weight: 700;
}
.scheme-step-node.done .scheme-step-dot {
border-color: #0284c7;
background: #0284c7;
color: #fff;
}
.scheme-step-node.active .scheme-step-dot {
border-color: #0284c7;
box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.18);
color: #0284c7;
}
.scheme-step-label {
color: #64748b;
font-size: 0.58rem;
line-height: 1.2;
}
.scheme-step-node.active .scheme-step-label {
color: #0284c7;
font-weight: 600;
}
</style>
@@ -85,6 +85,10 @@ const applyEventMetadata = (msg: ChatMessage, data: Record<string, unknown>) =>
if (Number.isInteger(data.chat_log_id)) {
msg.chat_log_id = Number(data.chat_log_id);
}
const runId = Number(data.run_id);
if (Number.isFinite(runId) && runId > 0) {
msg.run_id = runId;
}
if (typeof data.type === 'string' && data.type.trim()) {
msg.type = data.type as ChatMessage['type'];
}
@@ -187,6 +191,7 @@ export function useChat() {
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'local_file'; upload_file_id: string }
| { type: 'image' | 'document' | 'audio' | 'video' | 'custom'; transfer_method: 'remote_url'; url: string }
>,
context?: { task_id?: string; batch_no?: string },
) => {
const runViewId = viewId.value;
const runMessages = messages.value;
@@ -205,17 +210,20 @@ export function useChat() {
activeRunId.value = run.runId;
runMessages.push({ role: 'user', content: query });
let botMsgIndex: number | null = null;
let botMsgRef: ChatMessage | null = null;
let hasAssistantContent = false;
let hasTerminalEvent = false;
const ensureBotMessage = () => {
if (botMsgIndex === null) {
botMsgIndex = runMessages.push({
if (!botMsgRef) {
botMsgRef = {
role: 'assistant',
content: '',
retriever_resources: [],
attribution_parts: [],
}) - 1;
};
runMessages.push(botMsgRef);
}
return runMessages[botMsgIndex] || null;
return botMsgRef;
};
isThinking.value = true;
@@ -230,6 +238,8 @@ export function useChat() {
conversation_id: conversationId.value,
kb_type: kbType,
files: files && files.length > 0 ? files : undefined,
task_id: context?.task_id || undefined,
batch_no: context?.batch_no || undefined,
}),
});
@@ -263,6 +273,16 @@ export function useChat() {
if (!payload) continue;
try {
const eventMatch = payload.match(/"event"\s*:\s*"([^"]+)"/);
const fastEventName = eventMatch?.[1] || '';
if (
fastEventName === 'workflow_started'
|| fastEventName === 'node_started'
|| fastEventName === 'node_finished'
|| fastEventName === 'chat_perf'
) {
continue;
}
const data = JSON.parse(payload) as Record<string, unknown>;
if (data?.conversation_id) {
@@ -277,40 +297,13 @@ export function useChat() {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
hasAssistantContent = true;
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
if (botMsgRef) {
applyEventMetadata(botMsgRef, data);
}
} else if (eventName === 'chat_perf') {
const perf = (data.perf || {}) as Record<string, unknown>;
const nodes = Array.isArray(perf.nodes) ? perf.nodes : [];
// eslint-disable-next-line no-console
console.groupCollapsed(
`[chat-perf] request=${String(perf.request_id || '')} total=${String(perf.total_ms ?? '')}ms ttft=${String(perf.ttft_ms ?? '')}ms`,
);
if (nodes.length > 0) {
// eslint-disable-next-line no-console
console.table(
nodes.map((node) => {
const item = node as Record<string, unknown>;
return {
index: item.index,
title: item.title,
type: item.node_type,
elapsed_ms: item.elapsed_ms,
at_ms: item.at_ms,
status: item.status,
};
}),
);
} else {
// eslint-disable-next-line no-console
console.log(perf);
}
// eslint-disable-next-line no-console
console.groupEnd();
} else if (eventName === 'message_end' || eventName === 'workflow_finished') {
hasTerminalEvent = true;
const relay = (data.hxops_relay || {}) as Record<string, unknown>;
if (relay.total_relay_ms != null) {
// eslint-disable-next-line no-console
@@ -320,30 +313,19 @@ export function useChat() {
}
run.status = 'done';
if (messages.value === runMessages) isThinking.value = false;
if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) currentBotMsg.chat_log_id = Number(data.chat_log_id);
}
if (botMsgIndex !== null) {
const runId = Number(data.run_id);
if (Number.isFinite(runId) && runId > 0) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) currentBotMsg.run_id = runId;
}
}
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
const normalizedAnswer = normalizeStreamText(data.answer);
hasAssistantContent = true;
if (data.replace_answer) {
botMsg.content = normalizedAnswer;
} else {
botMsg.content += normalizedAnswer;
}
}
if (botMsgIndex !== null) {
const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) applyEventMetadata(currentBotMsg, data);
if (botMsgRef) {
applyEventMetadata(botMsgRef, data);
}
} else if (eventName === 'error') {
const botMsg = ensureBotMessage();
@@ -355,12 +337,16 @@ export function useChat() {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
hasAssistantContent = true;
}
} catch {
// ignore malformed SSE frames
}
}
}
if (!hasTerminalEvent && hasAssistantContent && run.status === 'running') {
run.status = 'done';
}
} catch (e: unknown) {
run.status = 'error';
const botMsg = ensureBotMessage();
@@ -87,9 +87,12 @@ export function useChatPage() {
const scroll = useChatScroll({ container: chatScrollContainer, messages });
scroll.setupThinkingScrollWatch(isThinking, conversationId);
let resetShippingConversationState = () => {};
const resetPeripheralState = () => {
browser.close();
queryPreview.close();
resetShippingConversationState();
};
const disposePeripherals = () => {
@@ -204,6 +207,7 @@ export function useChatPage() {
loadConversation: (id, opts) => loadConversation(id, opts),
createNewChatView,
});
resetShippingConversationState = shipping.resetShippingConversationState;
const conversationApi = createChatPageConversationApi({
deps,
@@ -284,6 +288,7 @@ export function useChatPage() {
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
clearAttachments: attachmentApi.clearAttachments,
sendMessage,
getChatContext: shipping.isShippingNoticeAgent ? shipping.getCurrentShippingChatContext : undefined,
refreshHistoryAfterSend,
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
tryHandleLeaveSend: leave.tryHandleLeaveSend,
@@ -415,6 +420,7 @@ export function useChatPage() {
shippingInventorySelectionActive: shipping.shippingInventorySelectionActive,
shippingInventorySelectionTaskId: shipping.shippingInventorySelectionTaskId,
switchShippingFocusTask: shipping.switchShippingFocusTask,
resumeShippingTask: shipping.resumeShippingTask,
selectShippingInventoryUploadTask: shipping.selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection: shipping.cancelShippingInventoryTaskSelection,
shippingSuggestedPrompt: shipping.shippingSuggestedPrompt,
@@ -7,6 +7,7 @@
import {
computed,
onBeforeUnmount,
ref,
watch,
type ComputedRef,
@@ -48,6 +49,7 @@ import {
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
import type { ChatDeps } from './chat.deps';
import { listChatMessages } from '../api/chat.api';
export interface UseChatShippingOptions {
deps: ChatDeps;
@@ -152,6 +154,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
const lastConversationSyncKey = ref('');
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
const syncShippingBatchSummary = async (batchNo: string) => {
const normalized = String(batchNo || '').trim();
@@ -174,8 +178,14 @@ export function useChatShipping(options: UseChatShippingOptions) {
created_at: detail.created_at,
updated_at: detail.updated_at,
};
if (detail.focus_task?.task_no) {
resolvedShippingTaskId.value = String(detail.focus_task.task_no).trim();
const preferredTaskNo = String(
detail.focus_task?.task_no
|| detail.process_summary?.current_task_no
|| detail.current_focus_task_no
|| '',
).trim();
if (preferredTaskNo) {
resolvedShippingTaskId.value = preferredTaskNo;
}
} catch {
// ignore summary refresh failure in chat flow
@@ -195,9 +205,34 @@ export function useChatShipping(options: UseChatShippingOptions) {
};
}
await syncShippingBatchSummary(batchNo);
await syncActiveShippingTaskDetail(normalizedTaskNo);
await refreshShippingActions();
return true;
};
/**
* 清空当前聊天页绑定的发货任务上下文。
*
* 核心逻辑:在新建对话、切换 Agent 或离开发货任务场景时,主动清掉批次/任务/上传缓存,
* 避免顶部 Stepper、列表展开态和待上传库存文件残留到下一次新会话。
*/
const resetShippingConversationState = () => {
shippingAutoFlowRequested.value = false;
pendingShippingUploadTaskId.value = '';
pendingShippingInventoryFile.value = null;
shippingInventorySelectionActive.value = false;
shippingInventorySelectionTaskId.value = '';
resolvedShippingTaskId.value = '';
resolvedShippingBatchNo.value = '';
shippingBatchSummary.value = null;
shippingBatchTasks.value = [];
shippingBatchTasksExpanded.value = false;
activeShippingTaskDetail.value = null;
shippingConversationTaskIdCache.value = {};
shippingInventorySchemaPreviewCache.value = {};
lastConversationSyncKey.value = '';
};
const getActiveShippingTaskId = () =>
findLatestShippingTaskId(messages.value)
|| resolvedShippingTaskId.value
@@ -210,6 +245,22 @@ export function useChatShipping(options: UseChatShippingOptions) {
|| String(shippingBatchSummary.value?.batch_no || '').trim()
|| '';
const getCurrentShippingChatContext = () => ({
task_id: getActiveShippingTaskId(),
batch_no: getActiveShippingBatchNo(),
});
const hasRunningShippingBatchTasks = () =>
shippingBatchTasks.value.some(
(task) => !['uploaded', 'completed', 'closed', 'rejected'].includes(String(task.process_status || '').trim()),
);
/**
* 同步当前焦点任务详情,并在仅恢复 `task_no` 的场景下补齐 `batch_no` 上下文。
*
* 核心逻辑:先拉取任务详情,再把详情里的批次号回填到聊天状态,确保会话恢复后仍能继续按批次模式加载 2 票/多票摘要。
* @param taskId - 可选任务编号;未传时回退到当前激活任务
*/
const syncActiveShippingTaskDetail = async (taskId?: string) => {
const normalized = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
if (!normalized) {
@@ -217,12 +268,43 @@ export function useChatShipping(options: UseChatShippingOptions) {
return;
}
try {
activeShippingTaskDetail.value = await getWorkspaceShippingTask(normalized);
const detail = await getWorkspaceShippingTask(normalized);
activeShippingTaskDetail.value = detail;
const batchNo = String(detail.batch_no || '').trim();
if (batchNo && resolvedShippingBatchNo.value !== batchNo) {
resolvedShippingBatchNo.value = batchNo;
}
} catch {
activeShippingTaskDetail.value = null;
}
};
const syncConversationMessagesIfNeeded = async (taskId?: string) => {
const conversationKey = String(conversationId.value || '').trim();
const normalizedTaskId = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
if (!conversationKey || !normalizedTaskId || !isShippingNoticeAgent.value || isThinking.value) return;
const detail = activeShippingTaskDetail.value;
// 任务详情接口当前不返回顶层 checkpoint,parse_review 需从详情状态字段回推。
const checkpoint = String(
(detail?.step_payload as Record<string, unknown> | undefined)?.checkpoint
|| detail?.review_status
|| '',
).trim();
if (checkpoint !== 'parse_review') return;
const exists = messages.value.some((msg) => {
if (msg.type !== 'shipping-parse-review' || !msg.payload || typeof msg.payload !== 'object') return false;
return String((msg.payload as { taskId?: string }).taskId || '').trim().toUpperCase() === normalizedTaskId;
});
if (exists) return;
const syncKey = `${conversationKey}|${normalizedTaskId}|parse_review`;
if (lastConversationSyncKey.value === syncKey) return;
const loaded = await listChatMessages(conversationKey, currentAgentId.value);
if (Array.isArray(loaded) && loaded.length > 0) {
messages.value = loaded;
lastConversationSyncKey.value = syncKey;
}
};
const lastAssistantMessageContent = () => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const item = messages.value[i];
@@ -417,9 +499,32 @@ export function useChatShipping(options: UseChatShippingOptions) {
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
if (prevId !== nextId) {
resolvedShippingTaskId.value = '';
if (!shippingBatchNoFromQuery.value) {
resolvedShippingBatchNo.value = '';
shippingBatchSummary.value = null;
shippingBatchTasks.value = [];
}
}
};
/**
* 续办指定任务,并把聊天上下文切到该任务继续推进。
*
* 核心逻辑:先切换批次焦点任务,再复用既有“请继续处理发货任务”提示词触发一次发送,
* 让 Agent 基于最新 task_id/batch_no 返回下一步动作。
* @param taskNo - 需要续办的任务编号
* @returns 是否已成功触发续办
*/
const resumeShippingTask = async (taskNo: string) => {
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
if (!normalizedTaskNo || !isShippingNoticeAgent.value || isThinking.value) return false;
const switched = await switchShippingFocusTask(normalizedTaskNo);
if (!switched) return false;
input.value = t('chat.shippingNoticeContinue', { taskId: normalizedTaskNo });
await invokeHandleSend?.();
return true;
};
const onConversationLoadedEmpty = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
@@ -437,6 +542,42 @@ export function useChatShipping(options: UseChatShippingOptions) {
await invokeHandleSend?.();
};
/**
* 启停发货批次状态短轮询。
*
* 核心逻辑:聊天流当前没有 shipping 专属 SSE;因此在存在任务/批次上下文时每 3 秒补拉一次,
* 让顶部 Stepper、批次统计和动作按钮能在后端异步状态变化后自动更新。
*/
const restartShippingStatusPolling = () => {
if (shippingStatusPollTimer) {
clearInterval(shippingStatusPollTimer);
shippingStatusPollTimer = null;
}
if (!isShippingNoticeAgent.value) return;
const batchNo = getActiveShippingBatchNo();
const taskId = getActiveShippingTaskId();
if (!batchNo && !taskId) return;
shippingStatusPollTimer = setInterval(() => {
if (!isShippingNoticeAgent.value) return;
const nextBatchNo = getActiveShippingBatchNo();
const nextTaskId = getActiveShippingTaskId();
if (!nextBatchNo && !nextTaskId) return;
void (async () => {
if (nextBatchNo) await syncShippingBatchSummary(nextBatchNo);
if (nextTaskId) {
await syncActiveShippingTaskDetail(nextTaskId);
await syncConversationMessagesIfNeeded(nextTaskId);
}
await refreshShippingActions();
if (!hasRunningShippingBatchTasks() && !isThinking.value && shippingStatusPollTimer) {
clearInterval(shippingStatusPollTimer);
shippingStatusPollTimer = null;
}
})();
}, 3000);
};
// ── 动作按钮 watch ────────────────────────────────────────
const shippingActionsWatchKey = computed(() => {
const msgs = messages.value;
@@ -455,6 +596,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
syncShippingParseReviewCard(taskId),
syncActiveShippingTaskDetail(taskId),
]);
await syncConversationMessagesIfNeeded(taskId);
});
});
watch([resolvedShippingBatchNo, shippingBatchNoFromQuery], ([batchNo, queryBatchNo]) => {
@@ -465,6 +607,19 @@ export function useChatShipping(options: UseChatShippingOptions) {
}
void syncShippingBatchSummary(nextBatchNo);
}, { immediate: true });
watch(
[isShippingNoticeAgent, conversationId, resolvedShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
() => {
restartShippingStatusPolling();
},
{ immediate: true },
);
onBeforeUnmount(() => {
if (shippingStatusPollTimer) {
clearInterval(shippingStatusPollTimer);
shippingStatusPollTimer = null;
}
});
return {
shippingBindSend,
@@ -483,8 +638,11 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingBatchTasks,
shippingBatchTasksExpanded,
activeShippingTaskDetail,
getCurrentShippingChatContext,
getActiveShippingBatchNo,
switchShippingFocusTask,
resumeShippingTask,
resetShippingConversationState,
resumeShippingTaskFromQuery,
normalizeShippingHeaderForDisplay,
getShippingInventoryMappingPayload,
@@ -62,6 +62,28 @@ const looksLikeFileName = (name: string) => {
return /\.[A-Za-z0-9]{2,8}$/.test(n);
};
/**
* 判断源文件名是否为知识库上传链路生成的兜底名。
* AI 触发时机:当 Dify 文档名与 HXOPS 源文件名不一致时,用它识别 `uploaded_file.*`
* 这类无业务含义的占位名,避免聊天源文件按钮展示错误名称。
*/
const isFallbackUploadedFileName = (name: string) => {
const base = String(name || '').trim().split(/[\\/]/).pop() || '';
return /^uploaded_file(?:\.[A-Za-z0-9]{1,8})?$/i.test(base);
};
/**
* 选择聊天源文件按钮/预览弹窗的展示名称。
* AI 触发时机:构建 source file link 时调用;若本地源文件名是兜底名,
* 优先使用 Dify 检索返回的 document_name/title,下载链接仍沿用后端解析结果。
*/
const pickSourceDisplayName = (item: Record<string, unknown>, fallback = '') => {
const sourceFilename = String(item?.source_filename || '').trim();
const documentName = String(item?.document_name || item?.title || '').trim();
if (sourceFilename && !isFallbackUploadedFileName(sourceFilename)) return sourceFilename;
return documentName || sourceFilename || fallback;
};
const findFirstByKeys = (payload: unknown, keyCandidates: string[]): string => {
if (payload == null) return '';
if (Array.isArray(payload)) {
@@ -234,7 +256,7 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
].filter(Boolean) as string[];
const content = getSourceContent(item);
const forceName = String(item?.source_filename || item?.document_name || item?.title || '');
const forceName = pickSourceDisplayName(item);
const forceUrl = normalizeUrl(String(item?.source_download_url || item?.url || ''));
if (forceName && (forceUrl || (datasetId && remoteDocumentId))) {
@@ -263,7 +285,7 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
for (const url of discovered) {
if (isChunkLikeLink(url)) continue;
const name = String(item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file'));
const name = pickSourceDisplayName(item, safeDecode(url.split('/').pop() || 'source-file'));
if (isNoisySourceName(name)) continue;
if (isMarkdownFileName(name) || isMarkdownByUrl(url)) continue;
const key = buildSourceLinkKey(name, datasetId, remoteDocumentId, url);
@@ -316,7 +338,7 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
const getDisplayRetrieverResources = (message: Record<string, unknown>): Record<string, unknown>[] => {
const list = Array.isArray(message?.retriever_resources) ? message.retriever_resources as Record<string, unknown>[] : [];
return list.filter((doc) => {
const name = String(doc?.source_filename || doc?.document_name || doc?.title || '');
const name = pickSourceDisplayName(doc);
const url = String(doc?.source_download_url || doc?.url || doc?.file_url || doc?.document_url || '');
return !(isMarkdownFileName(name) || isMarkdownByUrl(url));
});
@@ -358,7 +380,9 @@ export function useChatSourceFiles({ agentId, t, msg, isMobile }: UseChatSourceF
return {
...file,
url: resolvedUrl,
name: data?.source_filename || file.name,
name: data?.source_filename && !isFallbackUploadedFileName(data.source_filename)
? data.source_filename
: file.name,
actualExt: String(data?.source_ext || '').trim().toLowerCase() || undefined,
};
}
@@ -0,0 +1,22 @@
/**
* 用途:覆盖请假强/弱意图边界,避免“咨询规则”被误判成“立即发起请假”。
* 依赖:与 leaveIntent.ts 中的 isStrongLeaveIntent 保持一致。
* 逻辑:弱咨询句应继续走 Dify;强请假句才触发表单流程。
*/
import { describe, expect, it } from 'vitest';
import { isStrongLeaveIntent } from './leaveIntent';
describe('isStrongLeaveIntent', () => {
it('将非强请假咨询句判定为弱意图', () => {
// 断言:规则咨询不应触发本地请假表单,应继续走 Dify 问答。
expect(isStrongLeaveIntent('年假可以按照小时请假吗?')).toBe(false);
expect(isStrongLeaveIntent('怎么请年假?年假可以按照小时请假吗?')).toBe(false);
});
it('保留强请假意图触发表单', () => {
// 断言:明确申请/发起请假的表达仍应保留原有请假流程。
expect(isStrongLeaveIntent('我要请假')).toBe(true);
expect(isStrongLeaveIntent('帮我请年假')).toBe(true);
});
});
@@ -141,8 +141,10 @@ export function getLeaveIntentNormalized(content: string): string {
export function isStrongLeaveIntent(content: string): boolean {
const normalized = getLeaveIntentNormalized(content);
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定|请假管理办法|请假制度)/;
const weakLeaveQuestionIntent = /((怎么|如何).{0,8}(请假|请年假|休假|休年假|年假)|(请假|年假|休假).{0,12}(可以|可否|能否|是否|支持).{0,8}(按小时|按照小时|小时请|小时休))/;
const materialConsultationIntent = /(提交哪些|提交什么|需要哪些|需要什么|要提交哪些|要提交什么|哪些资料|哪些材料|什么资料|什么材料|申请材料|所需资料|所需材料)/;
if (weakConsultationIntent.test(normalized)) return false;
if (weakLeaveQuestionIntent.test(normalized)) return false;
if (materialConsultationIntent.test(normalized)) return false;
if (/^(请假|休假|年假|事假|病假|调休|休年假|请事假|请病假|请年假)$/.test(normalized)) return true;
return /(我要请|申请请|发起请|请假申请|我要休|申请休|想请|帮我请|代我请|提交请|帮我申请|我要申请|想申请|申请.*假|请.*假|休.*假)/.test(normalized);
@@ -65,6 +65,12 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
const startNewChat = () => {
ctx.createNewChatView();
ctx.clearAttachments();
ctx.input.value = '';
ctx.copiedIndex.value = null;
ctx.resetPeripheralState();
ctx.filePreviewVisible.value = false;
ctx.previewFile.value = null;
void ctx.router.replace({ path: ctx.route.path, query: {} });
};
@@ -25,6 +25,7 @@ export interface ChatPageSendContext {
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string },
) => Promise<void>;
refreshHistoryAfterSend: () => Promise<void>;
tryHandleShippingAttachmentAutoFlow: (
@@ -43,6 +44,7 @@ export interface ChatPageSendContext {
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string) => string;
copiedIndex: Ref<number | null>;
getChatContext?: () => { task_id?: string; batch_no?: string };
}
export function createChatPageSendApi(ctx: ChatPageSendContext) {
@@ -90,7 +92,13 @@ export function createChatPageSendApi(ctx: ChatPageSendContext) {
ctx.clearAttachments();
await ctx.prepareToolRunProgressBeforeSend();
await ctx.sendMessage(content, ctx.currentAgentId.value, ctx.selectedKb.value, files);
await ctx.sendMessage(
content,
ctx.currentAgentId.value,
ctx.selectedKb.value,
files,
ctx.getChatContext?.(),
);
await ctx.refreshHistoryAfterSend();
await ctx.refreshToolRunProgressAfterSend();
};
@@ -29,14 +29,40 @@ export const SHIPPING_WORKFLOW_STEP_LABELS = [
'chat.shippingNoticeUi.stepper.uploadFreight',
] as const;
const CURRENT_STEP_INDEX_MAP: Record<string, number> = {
step1_notice_submit: 0,
step2_parse_confirm: 1,
step3_inventory_prepare: 2,
step2_inventory_prepare: 2,
step4_align_confirm: 3,
step5_match_inventory: 4,
step3_inventory_match: 4,
step4_shortage_review: 4,
step6_generate_file: 5,
step5_export_excel: 5,
step7_upload_freight: 6,
step6_upload_freight: 6,
step7_finish: 6,
};
const TERMINAL_PROCESS_STATUSES = new Set(['uploaded', 'closed']);
function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): number {
const currentStep = String(task?.current_step || '').trim();
const processStatus = String(task?.process_status || '').trim();
const reviewStatus = String(task?.review_status || '').trim();
const pendingReason = String(task?.pending_human_reason || '').trim();
const matchStatus = String(task?.match_status || '').trim();
const hasExport = !!String(task?.export_file_name || '').trim();
if (processStatus === 'uploaded' || processStatus === 'closed') return 6;
if (currentStep) {
const currentStepIndex = CURRENT_STEP_INDEX_MAP[currentStep];
if (currentStepIndex !== undefined) {
return currentStepIndex;
}
}
if (TERMINAL_PROCESS_STATUSES.has(processStatus)) return 6;
if (processStatus === 'waiting_upload' || processStatus === 'upload_failed' || hasExport) return 5;
if (processStatus === 'matched') return 4;
if (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage') return 4;
@@ -78,7 +104,10 @@ export function buildShippingWorkflowSteps(
return SHIPPING_WORKFLOW_STEP_LABELS.map((label, index) => {
let status: ShippingWorkflowStepItem['status'] = 'pending';
if (index < currentIndex) {
// [STEP 1] uploaded/closed 是整票已完成的终态,不能再被 current_step 渲染成“第 7 步进行中”。
if (TERMINAL_PROCESS_STATUSES.has(processStatus)) {
status = 'completed';
} else if (index < currentIndex) {
status = 'completed';
} else if (index === currentIndex) {
status = 'current';
@@ -1,8 +1,8 @@
/**
* features/chat/shipping/shippingUploadPrompt.ts
* 用途:库存上传后发给 Dify 的提示语构建与附件类型分类。
* 用途:库存/通知上传后发给 Dify 的提示语构建与附件类型分类。
* 依赖:无;useChatShippingUploadHandler 在上传成功后调用。
* 逻辑:按 checkpoint 生成不同 follow-up 提示;classifyShippingUploadFile 区分库存/通知附件。
* 逻辑:按 checkpoint 生成不同 follow-up 提示;通知建批后触发 Dify LLM 解析续办。
*/
/**
* 根据上传 API 响应 checkpoint 生成发给 Agent 的 follow-up 提示语。
@@ -29,6 +29,43 @@ export function buildShippingInventoryUploadPrompt(
return `${prefix}。请继续处理库存导入,并告诉我下一步。`;
}
/**
* 根据通知建批 API 响应生成发给 Dify 的 follow-up 提示语(触发画布 LLM 抽取 + parse_notice)。
*/
export function buildShippingNoticeUploadPrompt(
result: Record<string, unknown> | null | undefined,
options?: { fileCount?: number; fileName?: string },
): string {
const batchNo = String(
(result?.batch_no as string | undefined)
|| ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|| '',
).trim();
const taskId = String(
((result?.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|| (result?.task_id as string | undefined)
|| ((result?.data as { tasks?: Array<{ task_id?: string }> } | undefined)?.tasks?.[0]?.task_id)
|| '',
).trim();
const taskIds = Array.isArray((result?.data as { tasks?: unknown[] } | undefined)?.tasks)
? ((result?.data as { tasks?: Array<{ task_id?: string }> }).tasks || [])
.map((task) => String(task?.task_id || '').trim())
.filter(Boolean)
: [];
const fileCount = Number(options?.fileCount || 0);
const fileLabel = options?.fileName
? `《${options.fileName}》`
: (fileCount > 1 ? `${fileCount} 份发货通知` : '发货通知');
const parts = [`我已上传${fileLabel}`];
if (batchNo) parts.push(`批次 ${batchNo}`);
if (taskId) parts.push(`当前任务 ${taskId}`);
if (fileCount > 1 || taskIds.length > 1) {
const taskListText = taskIds.length ? `任务列表:${taskIds.join('、')}。` : '';
return `${parts.join(',')}。${taskListText}请立即开始整批处理,不要只处理当前任务。先调用 get_batch_status 查看整批状态,再按批次顺序逐票处理:必要时调用 switch_focus_task 切到对应任务,然后读取该任务 raw_text,用 LLM 抽取结构化字段并调用 parse_notice(structured=...) 落库;若抽取失败可仅传 task_id 让后端用 raw_text 兜底。每处理完一票,都继续切到下一票,直到本批每一票都进入各自下一阶段(待确认、待上传库存、自动推进中的任一状态)。禁止再次询问我“是否开始解析”或只停在第一票。`;
}
return `${parts.join(',')}。请立即读取任务 raw_text,用 LLM 抽取结构化字段后直接调用 parse_notice(structured=...) 落库;若抽取失败可仅传 raw_text 走后端规则兜底。禁止再次询问我“是否开始解析”或“是否现在开始解析”。解析完成后,请直接展示解析结果供我确认。`;
}
/**
* 按扩展名判断附件是库存 Excel 还是发货通知文件。
*/
@@ -107,12 +107,11 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
};
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'shipping-match-result',
type: 'text',
content: [
String(result.message || '').trim(),
`任务编号:${taskId}`,
].filter(Boolean).join('\n'),
payload: buildMatchResultPayload(taskId, result),
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
};
@@ -158,11 +157,9 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
};
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: [
String(result.message || '').trim(),
`任务编号:${taskId}`,
].filter(Boolean).join('\n'),
type: 'shipping-match-result',
content: String(result.message || '').trim(),
payload: buildMatchResultPayload(taskId, result),
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
};
@@ -60,10 +60,14 @@ export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContex
const removeParseReviewMessageForTask = (taskId: string) => {
const normalized = String(taskId || '').trim().toUpperCase();
if (!normalized) return;
ctx.messages.value = ctx.messages.value.filter((msg) => {
for (let i = ctx.messages.value.length - 1; i >= 0; i -= 1) {
const msg = ctx.messages.value[i];
if (!msg) continue;
const payload = getShippingParseReviewPayload(msg);
return payload?.taskId?.trim().toUpperCase() !== normalized;
});
if (payload?.taskId?.trim().toUpperCase() === normalized) {
ctx.messages.value.splice(i, 1);
}
}
};
const upsertParseReviewMessage = async (payload: ShippingParseReviewPayload) => {
@@ -184,12 +184,16 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
).trim();
const hint = String(result.message || '').trim();
const status = String((result as { status?: string }).status || '').trim();
const orchestratorStarted = Boolean(
(result.data as { orchestrator_started?: boolean } | undefined)?.orchestrator_started,
);
const tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
await ctx.pushShippingLocalAssistantMessage(
[
hint || `已处理发货通知附件:${file.name}`,
batchNo ? `批次编号:${batchNo}` : '',
taskId ? `任务编号:${taskId}` : '',
orchestratorStarted ? '后台已开始按票处理,请稍后查看进度自动刷新。' : '',
tail,
].filter(Boolean).join('\n'),
);
@@ -228,6 +232,9 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
const fileCount = Number(batch?.file_count || noticeFiles.length || 0);
const hint = String(result.message || '').trim();
const status = String((result as { status?: string }).status || '').trim();
const orchestratorStarted = Boolean(
(result.data as { orchestrator_started?: boolean } | undefined)?.orchestrator_started,
);
const tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
await ctx.pushShippingLocalAssistantMessage(
[
@@ -235,6 +242,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
batchNo ? `批次编号:${batchNo}` : '',
taskId ? `当前任务:${taskId}` : '',
focusProgress,
orchestratorStarted ? `后台已开始按票拆分处理,本批 ${fileCount} 票会逐步更新状态。` : '',
tail,
].filter(Boolean).join('\n'),
);
@@ -25,6 +25,9 @@ export interface ShippingTaskSummary {
conversation_id?: string | null;
export_file_name?: string | null;
freight_ref_no?: string | null;
step_payload?: Record<string, unknown> & {
current_step_progress?: ShippingCurrentStepProgress;
};
created_at?: string | null;
updated_at?: string | null;
}
@@ -35,6 +38,18 @@ export interface ShippingTaskEvent {
created_at?: string | null;
}
export interface ShippingCurrentStepProgress {
step_key?: string;
step_title?: string;
status?: 'running' | 'completed' | 'needs_human' | 'pending' | string;
message?: string;
progress_percent?: number;
current?: number;
total?: number;
detail?: string;
extra?: Record<string, unknown>;
}
export interface ShippingNoticeHeader {
customer_name?: string | null;
customer_code?: string | null;
@@ -70,7 +85,6 @@ export interface ShippingTaskDetail extends ShippingTaskSummary {
ship_to?: string | null;
po_number?: string | null;
required_date?: string | null;
step_payload?: Record<string, unknown>;
upload_receipt?: Record<string, unknown>;
export_version?: number | null;
idempotency_key?: string | null;
@@ -104,7 +118,15 @@ export interface ShippingBatchSummary {
conversation_id?: string | null;
current_focus_task_no?: string | null;
file_count?: number | null;
process_summary?: Record<string, unknown> | null;
process_summary?: Record<string, unknown> & {
total?: number;
completed?: number;
failed?: number;
running?: number;
pending?: number;
current_index?: number;
current_task_no?: string | null;
} | null;
created_at?: string | null;
updated_at?: string | null;
}
@@ -135,6 +157,7 @@ export interface ShippingNoticeUploadResponse {
batch?: ShippingBatchSummary;
focus_task?: ShippingTaskSummary | null;
tasks?: Array<Record<string, unknown>>;
orchestrator_started?: boolean;
};
human_options?: string[];
}
@@ -24,12 +24,14 @@ import {
markWorkspaceShippingManualUploaded,
matchWorkspaceShippingInventory,
removeWorkspaceShippingNoticeLine,
retryWorkspaceShippingTask,
SHIPPING_NOTICE_AGENT_NAME,
submitWorkspaceShippingDecision,
updateWorkspaceShippingNoticeFields,
updateWorkspaceShippingNoticeLine,
workspaceShippingExportUrl,
type ShippingChatAction,
type ShippingCurrentStepProgress,
type ShippingNoticeHeader,
type ShippingNoticeLine,
type ShippingTaskDetail,
@@ -38,6 +40,7 @@ import {
import type { ChatMessage } from '@/features/chat/types/chat.types';
import type { ShippingParseReviewPayload } from '@/features/chat/types/shipping.types';
import { getAuthHeaders } from '@/shared/utils/auth';
import { useMessage } from '@/shared/composables/useMessage';
import { buildShippingWorkflowSteps, shippingActionButtonClass } from '@/features/chat/shipping';
const props = defineProps<{
@@ -46,6 +49,7 @@ const props = defineProps<{
const router = useRouter();
const { t } = useI18n();
const msg = useMessage();
const loading = ref(false);
const detailLoading = ref(false);
@@ -54,6 +58,7 @@ const selectedTaskNo = ref<string | null>(null);
const detail = ref<ShippingTaskDetail | null>(null);
const detailSaving = ref(false);
const detailActionBusy = ref(false);
const detailRetrying = ref(false);
const detailActionButtons = ref<ShippingChatAction[]>([]);
const statusFilter = ref('all');
const chatAgentId = ref<number | null>(null);
@@ -90,6 +95,15 @@ const statusBadge = (status: string) => {
};
const detailWorkflowSteps = computed(() => buildShippingWorkflowSteps(detail.value));
const detailStepProgress = computed<ShippingCurrentStepProgress | null>(() => {
const payload = detail.value?.step_payload;
if (!payload || typeof payload !== 'object') return null;
const progress = (payload as Record<string, unknown>).current_step_progress;
return progress && typeof progress === 'object' ? progress as ShippingCurrentStepProgress : null;
});
const detailStepHasPercent = computed(() =>
typeof detailStepProgress.value?.progress_percent === 'number',
);
const loadCases = async () => {
loading.value = true;
@@ -283,6 +297,20 @@ const handleWorkspaceAction = async (action: ShippingChatAction) => {
}
};
const handleRetryCurrentTask = async () => {
if (!detail.value || detailRetrying.value) return;
detailRetrying.value = true;
try {
const result = await retryWorkspaceShippingTask(detail.value.task_no, '工作台重试当前票');
msg.success(result.message || t('workspace.shippingNotice.retryCurrentDone'));
await Promise.all([loadDetail(detail.value.task_no), loadCases()]);
} catch (error) {
msg.error(error instanceof Error ? error.message : t('workspace.shippingNotice.retryFailed'));
} finally {
detailRetrying.value = false;
}
};
watch(selectedTaskNo, (val) => {
if (val) loadDetail(val);
else detail.value = null;
@@ -390,6 +418,15 @@ onMounted(async () => {
</div>
</div>
<div class="flex flex-wrap gap-2">
<button
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
:disabled="detailRetrying"
@click="handleRetryCurrentTask"
>
<RefreshCw class="h-3.5 w-3.5" />
{{ detailRetrying ? $t('workspace.shippingNotice.retrying') : $t('workspace.shippingNotice.retryCurrentTask') }}
</button>
<button
v-if="chatAgentId"
type="button"
@@ -413,6 +450,41 @@ onMounted(async () => {
<ShippingWorkflowStepper :steps="detailWorkflowSteps" />
<div
v-if="detailStepProgress"
class="rounded-2xl border border-default/80 bg-surface px-4 py-3"
>
<div class="flex items-center justify-between gap-3 text-xs">
<div class="font-medium text-primary">
{{ detailStepProgress.step_title || t('chat.shippingNoticeUi.stepDetail.title') }}
</div>
<div v-if="detailStepHasPercent" class="text-muted">
{{ detailStepProgress.progress_percent }}%
</div>
</div>
<div class="mt-1 text-sm text-secondary">
{{ detailStepProgress.message || t('chat.shippingNoticeUi.processing') }}
</div>
<div v-if="detailStepProgress.detail" class="mt-1 text-xs text-muted">
{{ detailStepProgress.detail }}
</div>
<div
v-if="detailStepProgress.current && detailStepProgress.total"
class="mt-1 text-xs text-muted"
>
{{ t('chat.shippingNoticeUi.stepDetail.counter', { current: detailStepProgress.current, total: detailStepProgress.total }) }}
</div>
<div
v-if="detailStepHasPercent"
class="mt-2 h-2 overflow-hidden rounded-full bg-slate-200"
>
<div
class="h-full rounded-full bg-sky-500 transition-all"
:style="{ width: `${detailStepProgress.progress_percent}%` }"
/>
</div>
</div>
<dl class="grid gap-3 sm:grid-cols-2 text-sm">
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.status') }}</dt><dd>{{ detail.process_status }}</dd></div>
<div><dt class="text-muted">{{ $t('workspace.shippingNotice.fields.match') }}</dt><dd>{{ detail.match_status || '—' }}</dd></div>
+23
View File
@@ -79,7 +79,23 @@
"taskTitle": "Shipping task",
"currentTask": "Current task {taskId}",
"batchProgress": "Item {index}/{total}",
"batchCurrentIndex": "Currently processing item {index}/{total}",
"batchSummaryLine": "Batch {total} items · Completed {completed} · In progress {running} · Pending {pending}",
"currentNotice": "Current notice",
"currentStepLabel": "Current",
"stepHeadline": "Step {current}/{total} · {label}",
"stepFraction": "Step {current}/{total}",
"stepNeedsConfirm": "Step {step} needs confirmation",
"taskListResume": "Task List / Resume",
"taskListTitle": "Task List",
"taskListHint": "Switching tasks also updates the top Stepper and available actions",
"expandTaskList": "Expand list",
"collapseTaskList": "Collapse list",
"currentFocus": "Current focus →",
"runningState": "In progress",
"pendingState": "Pending",
"completedState": "Completed",
"queuedState": "Queued",
"prevTask": "Previous",
"nextTask": "Next",
"collapseTasks": "Hide tasks",
@@ -94,6 +110,7 @@
"fileCount": "Files",
"runningCount": "Running",
"completedCount": "Completed",
"pendingCount": "Pending",
"batchProgressTitle": "Batch progress",
"processing": "Processing",
"status": {
@@ -109,13 +126,19 @@
},
"currentStep": {
"noticeParse": "Notice parsing",
"parseConfirm": "Confirm parsing",
"inventoryPrepare": "Inventory prep",
"alignConfirm": "Confirm mapping",
"inventoryMatch": "Inventory match",
"shortageHandle": "Shortage handling",
"generateExcel": "Generate Excel",
"uploadFreight": "Upload to freight",
"finishArchive": "Archive"
},
"stepDetail": {
"title": "Step progress",
"counter": "{current}/{total}"
},
"matchStatus": {
"fulfillable": "Fully fulfillable",
"partial": "Partially fulfillable",
+23
View File
@@ -79,7 +79,23 @@
"taskTitle": "งานจัดส่ง",
"currentTask": "งานปัจจุบัน {taskId}",
"batchProgress": "รายการ {index}/{total}",
"batchCurrentIndex": "กำลังประมวลผลรายการที่ {index}/{total}",
"batchSummaryLine": "ชุดนี้ {total} รายการ · เสร็จแล้ว {completed} · กำลังดำเนินการ {running} · รอดำเนินการ {pending}",
"currentNotice": "ใบแจ้งปัจจุบัน",
"currentStepLabel": "ปัจจุบัน",
"stepHeadline": "ขั้นตอน {current}/{total} · {label}",
"stepFraction": "ขั้นตอน {current}/{total}",
"stepNeedsConfirm": "ขั้นตอน {step} รอยืนยัน",
"taskListResume": "รายการงาน / ดำเนินการต่อ",
"taskListTitle": "รายการงาน",
"taskListHint": "เมื่อสลับงาน Stepper ด้านบนและการดำเนินการจะอัปเดตพร้อมกัน",
"expandTaskList": "ขยายรายการ",
"collapseTaskList": "ย่อรายการ",
"currentFocus": "โฟกัสปัจจุบัน →",
"runningState": "กำลังดำเนินการ",
"pendingState": "รอยืนยัน",
"completedState": "เสร็จแล้ว",
"queuedState": "อยู่ในคิว",
"prevTask": "ก่อนหน้า",
"nextTask": "ถัดไป",
"collapseTasks": "ซ่อนงาน",
@@ -94,6 +110,7 @@
"fileCount": "จำนวนไฟล์",
"runningCount": "กำลังดำเนินการ",
"completedCount": "เสร็จแล้ว",
"pendingCount": "รอดำเนินการ",
"batchProgressTitle": "ความคืบหน้าของชุดงาน",
"processing": "กำลังดำเนินการ",
"status": {
@@ -109,13 +126,19 @@
},
"currentStep": {
"noticeParse": "แยกใบแจ้ง",
"parseConfirm": "ยืนยันผลแยก",
"inventoryPrepare": "เตรียมสต็อก",
"alignConfirm": "ยืนยันการจับคู่คอลัมน์",
"inventoryMatch": "จับคู่สต็อก",
"shortageHandle": "จัดการส่วนขาด",
"generateExcel": "สร้าง Excel",
"uploadFreight": "อัปโหลดผู้ให้บริการขนส่ง",
"finishArchive": "เก็บงาน"
},
"stepDetail": {
"title": "ความคืบหน้าภายในขั้นตอน",
"counter": "{current}/{total}"
},
"matchStatus": {
"fulfillable": "จัดส่งได้ครบ",
"partial": "จัดส่งได้บางส่วน",
+27
View File
@@ -79,7 +79,27 @@
"taskTitle": "发货任务",
"currentTask": "当前任务 {taskId}",
"batchProgress": "第 {index}/{total} 票",
"batchCurrentIndex": "当前处理第 {index}/{total} 票",
"batchSummaryLine": "本批 {total} 笔 · 已完成 {completed} · 进行中 {running} · 待处理 {pending}",
"currentNotice": "当前通知",
"currentStepLabel": "当前",
"stepHeadline": "步骤 {current}/{total} · {label}",
"stepFraction": "步骤 {current}/{total}",
"stepNeedsConfirm": "步骤 {step} 待确认",
"taskListResume": "任务列表 / 续办",
"retryPendingTasks": "重试未完成票",
"retryPendingDone": "已重新提交未完成票",
"retryFailed": "重试失败",
"retrying": "重试中...",
"taskListTitle": "任务列表",
"taskListHint": "切换任务后,对话顶部 Stepper 与操作同步更新",
"expandTaskList": "展开列表",
"collapseTaskList": "收起列表",
"currentFocus": "当前聚焦 →",
"runningState": "进行中",
"pendingState": "待确认",
"completedState": "已完成",
"queuedState": "排队中",
"prevTask": "上一票",
"nextTask": "下一票",
"collapseTasks": "收起任务",
@@ -94,6 +114,7 @@
"fileCount": "文件数",
"runningCount": "处理中",
"completedCount": "已完成",
"pendingCount": "待处理",
"batchProgressTitle": "批次进度",
"processing": "处理中",
"status": {
@@ -109,13 +130,19 @@
},
"currentStep": {
"noticeParse": "通知解析",
"parseConfirm": "确认解析",
"inventoryPrepare": "库存准备",
"alignConfirm": "确认字段对齐",
"inventoryMatch": "库存匹配",
"shortageHandle": "缺口处理",
"generateExcel": "生成 Excel",
"uploadFreight": "上传货代",
"finishArchive": "完成归档"
},
"stepDetail": {
"title": "步骤内进度",
"counter": "{current}/{total}"
},
"matchStatus": {
"fulfillable": "可全部发货",
"partial": "部分满足",
@@ -160,6 +160,10 @@
"loadFailed": "加载失败",
"openChat": "在 Chat 中继续",
"download": "下载 Excel",
"retryCurrentTask": "重试当前票",
"retryCurrentDone": "已重新提交当前票",
"retryFailed": "重试失败",
"retrying": "重试中...",
"lines": "发货明细",
"qty": "数量",
"columns": {
+23
View File
@@ -79,7 +79,23 @@
"taskTitle": "發貨任務",
"currentTask": "當前任務 {taskId}",
"batchProgress": "第 {index}/{total} 票",
"batchCurrentIndex": "當前處理第 {index}/{total} 票",
"batchSummaryLine": "本批 {total} 筆 · 已完成 {completed} · 進行中 {running} · 待處理 {pending}",
"currentNotice": "當前通知",
"currentStepLabel": "目前",
"stepHeadline": "步驟 {current}/{total} · {label}",
"stepFraction": "步驟 {current}/{total}",
"stepNeedsConfirm": "步驟 {step} 待確認",
"taskListResume": "任務列表 / 續辦",
"taskListTitle": "任務列表",
"taskListHint": "切換任務後,對話頂部 Stepper 與操作會同步更新",
"expandTaskList": "展開列表",
"collapseTaskList": "收起列表",
"currentFocus": "目前聚焦 →",
"runningState": "進行中",
"pendingState": "待確認",
"completedState": "已完成",
"queuedState": "排隊中",
"prevTask": "上一票",
"nextTask": "下一票",
"collapseTasks": "收起任務",
@@ -94,6 +110,7 @@
"fileCount": "檔案數",
"runningCount": "處理中",
"completedCount": "已完成",
"pendingCount": "待處理",
"batchProgressTitle": "批次進度",
"processing": "處理中",
"status": {
@@ -109,13 +126,19 @@
},
"currentStep": {
"noticeParse": "通知解析",
"parseConfirm": "確認解析",
"inventoryPrepare": "庫存準備",
"alignConfirm": "確認欄位對齊",
"inventoryMatch": "庫存匹配",
"shortageHandle": "缺口處理",
"generateExcel": "生成 Excel",
"uploadFreight": "上傳貨代",
"finishArchive": "完成歸檔"
},
"stepDetail": {
"title": "步驟內進度",
"counter": "{current}/{total}"
},
"matchStatus": {
"fulfillable": "可全部發貨",
"partial": "部分滿足",