feat(shipping-notice): 新增发货批次和任务管理功能,支持批次创建与任务处理

This commit is contained in:
hugo committed 2026-06-17 20:45:19 +08:00
1 parent 457f0f4e5e
commit 634dee4b81
81 files changed
+9088 -3625

No files matched your search

+222 -14
View File
@@ -1,11 +1,28 @@
"""
货代发货通知 Tool API — 供 Dify Chatflow Agent 调用
api/shipping_notice_tools.py
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
依赖:shipping_notice.tools、query_service、openapi_spec、tool_api_url、Flask Blueprint。
逻辑:上游由 Dify/OpenAPI 或 RPA 请求进入本文件;本文件做轻量参数编排,再下沉到 services/shipping_notice/* workflow。
"""
from __future__ import annotations
import uuid
from flask import Blueprint, current_app, jsonify, request, send_file
from pathlib import Path
from app import db
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
get_batch_by_no,
get_focus_task_for_batch,
get_task_by_ref,
get_task_in_batch,
list_batch_task_summaries,
resolve_task_export_download,
serialize_batch_summary,
serialize_task_summary,
task_export_error_message,
)
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
@@ -26,14 +43,21 @@ def _payload() -> dict:
return request.get_json(silent=True) or {}
def _generate_batch_no() -> str:
from datetime import datetime
return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
@shipping_notice_bp.route("/tools/openapi.json", methods=["GET"])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
return jsonify(_dify_openapi_spec())
@shipping_notice_bp.route("/tools/checkpoint-catalog", methods=["GET"])
def checkpoint_catalog():
"""Checkpoint ids, human_options, action_buttons — developer/docs reference (Dify approach B: do not embed)."""
"""返回检查点目录,供开发联调和文档核对 human_options/action_buttons。"""
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
return jsonify(build_checkpoint_catalog())
@@ -41,6 +65,7 @@ def checkpoint_catalog():
@shipping_notice_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
def openapi_dify_yaml():
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
import yaml
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
@@ -49,22 +74,106 @@ def openapi_dify_yaml():
@shipping_notice_bp.route("/tools/create_task", methods=["POST"])
def tool_create_task():
"""
创建单个发货任务。
【AI 触发时机】:当用户首次提交一张新的发货通知、当前会话里还没有对应任务时调用。
"""
return jsonify(shipping_tools.create_task(_payload()))
@shipping_notice_bp.route("/tools/create_batch", methods=["POST"])
def tool_create_batch():
"""
创建或复用发货批次。
【AI 触发时机】:当用户一次处理多份发货通知,需要把多任务挂到同一批次时调用。
"""
payload = _payload()
if isinstance(payload.get("notice_items"), list) and payload.get("notice_items"):
return jsonify(shipping_tools.create_batch_tasks(payload))
batch_no = str(payload.get("batch_no") or "").strip()
if batch_no:
batch = get_batch_by_no(batch_no)
if batch:
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"message": f"已复用批次 {batch.batch_no}",
"data": serialize_batch_summary(batch),
}
)
batch = shipping_tools.create_batch(payload)
db.session.commit()
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"message": f"已创建批次 {batch.batch_no}",
"data": serialize_batch_summary(batch),
}
)
@shipping_notice_bp.route("/tools/parse_notice", methods=["POST"])
def tool_parse_notice():
"""
解析发货通知正文。
【AI 触发时机】:当用户上传、粘贴或修正发货通知内容后,需要把文本转成任务单头和订单行时调用。
"""
return jsonify(shipping_tools.parse_notice(_payload()))
@shipping_notice_bp.route("/tools/update_notice_fields", methods=["POST"])
def tool_update_notice_fields():
"""
修改发货通知单头字段。
【AI 触发时机】:当用户明确要求更正客户、PO、收货地或交期等单头信息时调用。
"""
return jsonify(shipping_tools.update_notice_fields(_payload()))
@shipping_notice_bp.route("/tools/update_notice_line", methods=["POST"])
def tool_update_notice_line():
"""
修改指定订单行。
【AI 触发时机】:当用户指出某一行的 SKU、数量、Reservation ID 或交期有误时调用。
"""
return jsonify(shipping_tools.update_notice_line(_payload()))
@shipping_notice_bp.route("/tools/add_notice_line", methods=["POST"])
def tool_add_notice_line():
"""
新增订单行。
【AI 触发时机】:当用户说明漏了一行订单、需要补录发货通知明细时调用。
"""
return jsonify(shipping_tools.add_notice_line(_payload()))
@shipping_notice_bp.route("/tools/remove_notice_line", methods=["POST"])
def tool_remove_notice_line():
"""
删除订单行。
【AI 触发时机】:当用户确认某一行是误解析、重复行或不应出货的行时调用。
"""
return jsonify(shipping_tools.remove_notice_line(_payload()))
@shipping_notice_bp.route("/tools/parse_inventory", methods=["POST"])
def tool_parse_inventory():
"""
解析库存内容。
【AI 触发时机】:当用户提供库存文本或表格内容,需要把库存转成系统可匹配格式时调用。
"""
return jsonify(shipping_tools.parse_inventory(_payload()))
@shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"])
def tool_upload_inventory_file():
"""Multipart upload — parse server-side without sending Excel through LLM."""
"""
服务器侧接收库存 Excel 并解析。
【AI 触发时机】:当用户上传库存 Excel,且不希望把二进制文件内容经由 LLM 传输时调用。
"""
task_id = str(request.form.get("task_id") or request.args.get("task_id") or "").strip()
upload = request.files.get("file")
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
@@ -72,72 +181,171 @@ def tool_upload_inventory_file():
@shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"])
def tool_get_inventory_schema_preview():
"""
获取库存表头预览。
【AI 触发时机】:当 Agent 需要先看 Excel/表格列名,再决定 map_json 或提示用户确认映射时调用。
"""
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
@shipping_notice_bp.route("/tools/apply_inventory_mapping", methods=["POST"])
def tool_apply_inventory_mapping():
"""
应用库存字段映射。
【AI 触发时机】:当用户或 Agent 已确认列名与系统字段的对应关系,需要提交 map_json 时调用。
"""
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
@shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"])
def tool_ensure_inventory():
"""
保证任务已取得库存数据。
【AI 触发时机】:当发货通知已确认,下一步需要让系统拿到库存快照时调用。
"""
return jsonify(shipping_tools.ensure_inventory(_payload()))
@shipping_notice_bp.route("/tools/auto_progress", methods=["POST"])
def tool_auto_progress():
"""
自动推进任务。
【AI 触发时机】:当用户说“继续处理”“自动推进”“跑到下一步”时调用。
"""
return jsonify(shipping_tools.auto_progress(_payload()))
@shipping_notice_bp.route("/tools/match_inventory", methods=["POST"])
def tool_match_inventory():
"""
执行库存匹配。
【AI 触发时机】:当发货通知与库存都已准备好,需要判断是否缺货并生成匹配结果时调用。
"""
return jsonify(shipping_tools.match_inventory(_payload()))
@shipping_notice_bp.route("/tools/submit_decision", methods=["POST"])
def tool_submit_decision():
"""
提交人工决策。
【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。
"""
return jsonify(shipping_tools.submit_decision(_payload()))
@shipping_notice_bp.route("/tools/generate_shipment_excel", methods=["POST"])
def tool_generate_shipment_excel():
"""
生成出货 Excel。
【AI 触发时机】:当库存匹配已通过,用户要求导出货代上传模板时调用。
"""
return jsonify(shipping_tools.generate_excel(_payload()))
@shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"])
def tool_upload_to_freight():
"""
上传到货代系统或确认人工上传完成。
【AI 触发时机】:当用户要求推送到货代系统,或确认已手工完成上传时调用。
"""
return jsonify(shipping_tools.upload_to_freight(_payload()))
@shipping_notice_bp.route("/tools/get_task_status", methods=["POST"])
def tool_get_task_status():
"""
查询任务状态。
【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。
"""
return jsonify(shipping_tools.get_task_status(_payload()))
@shipping_notice_bp.route("/tools/get_batch_status", methods=["POST"])
def tool_get_batch_status():
"""
查询批次状态。
【AI 触发时机】:当用户关注整批任务处理进度,或 Agent 需要查看当前 focus task 与批次摘要时调用。
"""
payload = _payload()
batch_no = str(payload.get("batch_no") or "").strip()
if not batch_no:
return jsonify({"status": "failed", "message": "batch_no is required"}), 400
batch = get_batch_by_no(batch_no)
if not batch:
return jsonify({"status": "failed", "message": "batch not found"}), 404
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"message": f"已获取批次 {batch.batch_no} 状态",
"data": {
**serialize_batch_summary(batch),
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
"tasks": list_batch_task_summaries(batch),
},
}
)
@shipping_notice_bp.route("/tools/switch_focus_task", methods=["POST"])
def tool_switch_focus_task():
"""
切换批次当前焦点任务。
【AI 触发时机】:当用户在同一批次里要求“看第 N 个任务”或切换当前处理对象时调用。
"""
payload = _payload()
batch_no = str(payload.get("batch_no") or "").strip()
task_no = str(payload.get("task_no") or payload.get("target_task_no") or "").strip()
if not batch_no or not task_no:
return jsonify({"status": "failed", "message": "batch_no and task_no are required"}), 400
batch = get_batch_by_no(batch_no)
if not batch:
return jsonify({"status": "failed", "message": "batch not found"}), 404
task = get_task_in_batch(batch_no, task_no)
if not task:
return jsonify({"status": "failed", "message": "task not found in batch"}), 404
batch.current_focus_task_no = task.task_no
db.session.commit()
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"task_no": task.task_no,
"message": f"已切换当前任务到 {task.task_no}",
"data": {
"batch": serialize_batch_summary(batch),
"focus_task": serialize_task_summary(task),
},
}
)
@shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"])
def rpa_inventory_ready():
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
@shipping_notice_bp.route("/rpa/upload-complete", methods=["POST"])
def rpa_upload_complete():
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_upload(_payload()))
@shipping_notice_bp.route("/tasks/<task_no>/export", methods=["GET"])
def download_task_export(task_no: str):
from app.services.shipping_notice.tools import _get_task
task = _get_task(task_no)
if not task or not task.export_file_path:
return jsonify({"error": "export file not found"}), 404
path = Path(task.export_file_path)
if not path.is_file():
return jsonify({"error": "export file missing on disk"}), 404
"""下载任务已生成的出货 Excel。"""
task = get_task_by_ref(task_no)
err_msg = task_export_error_message(task)
if err_msg:
return jsonify({"error": err_msg}), 404
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
return send_file(
path,
as_attachment=True,
download_name=task.export_file_name or path.name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
download_name=download_name,
mimetype=EXPORT_MIME_TYPE,
)
+287 -14
View File
@@ -1,23 +1,40 @@
"""
api/workspace_shipping_notice.py
用途:提供 HXOPS 工作台与聊天前端使用的发货通知用户态 API。
依赖:auth_jwt、query_service、shipping_notice.tools、notice_upload、chat_actions。
逻辑:前端通过本 Blueprint 访问用户鉴权路由;本文件做权限校验与参数编排,再调用 shipping_notice service/workflow 返回页面所需数据。
"""
from __future__ import annotations
from flask import Blueprint, jsonify, request, send_file
from pathlib import Path
from app import db
from app.auth_jwt import get_current_user
from app.models import ShippingTask
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.constants import CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, AUTO_CHAIN_FALLBACK, MAP_JSON
from app.services.shipping_notice.query_service import (
EXPORT_MIME_TYPE,
get_batch_for_user,
get_focus_task_for_batch,
get_task_for_user,
list_batches_for_user,
list_tasks_for_batch,
list_tasks_for_user,
resolve_task_export_download,
serialize_batch_summary,
serialize_task_detail,
serialize_task_summary,
task_export_error_message,
)
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
def _require_user():
"""校验当前请求用户,统一返回 `(user, error_response)` 结构。"""
user = get_current_user()
if not user:
return None, (jsonify({"error": "Unauthorized"}), 401)
@@ -26,16 +43,163 @@ def _require_user():
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["GET"])
def workspace_shipping_tasks():
"""列出当前用户可见的发货任务,可按批次与处理状态过滤。"""
user, err = _require_user()
if err:
return err
batch_no = str(request.args.get("batch_no") or "").strip() or None
process_status = str(request.args.get("process_status") or "").strip() or None
limit = int(request.args.get("limit") or 100)
return jsonify(list_tasks_for_user(user.id, process_status=process_status, limit=limit))
return jsonify(list_tasks_for_user(user.id, batch_no=batch_no, process_status=process_status, limit=limit))
@workspace_shipping_notice_bp.route("/shipping-batches", methods=["GET"])
def workspace_shipping_batches():
"""列出当前用户的发货批次摘要。"""
user, err = _require_user()
if err:
return err
limit = int(request.args.get("limit") or 100)
return jsonify(list_batches_for_user(user.id, limit=limit))
@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
uploads = request.files.getlist("files")
if not uploads:
single = request.files.get("file")
if single:
uploads = [single]
if not uploads:
return jsonify({"error": "files is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.notice_upload import (
extract_notice_text,
guess_source_type,
max_notice_chars,
save_task_notice_upload,
)
conversation_id = str(request.form.get("conversation_id") or "").strip()
notice_items: list[dict] = []
for upload in uploads:
raw = upload.read() or b""
filename = upload.filename or "notice"
source_type = guess_source_type(filename)
text = ""
warnings: list[str] = []
try:
temp_task_no = f"TMP-{len(notice_items) + 1}"
saved_path = save_task_notice_upload(temp_task_no, filename, raw)
text, meta = extract_notice_text(saved_path)
warnings = list(meta.get("warnings") or []) if isinstance(meta, dict) else []
except Exception as exc:
warnings = [f"notice_extract_failed:{exc}"]
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
warnings.append(f"notice_text_truncated:{limit}")
notice_items.append(
{
"source_type": source_type,
"source_file_name": filename,
"source_file_type": str(getattr(upload, "mimetype", "") or "").strip() or None,
"raw_text": text,
"warnings": warnings,
}
)
payload = {
"user_id": user.id,
"conversation_id": conversation_id or None,
"file_count": len(notice_items),
"notice_items": notice_items,
}
return jsonify(shipping_tools.create_batch_tasks(payload))
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>", methods=["GET"])
def workspace_shipping_batch_detail(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
focus_task = get_focus_task_for_batch(batch_no, user.id)
return jsonify(
{
**serialize_batch_summary(batch),
"tasks": list_tasks_for_batch(batch_no, user.id),
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
}
)
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/tasks", methods=["GET"])
def workspace_shipping_batch_tasks(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
return jsonify(list_tasks_for_batch(batch_no, user.id))
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/focus-task", methods=["GET"])
def workspace_shipping_batch_focus_task(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
focus_task = get_focus_task_for_batch(batch_no, user.id)
if not focus_task:
return jsonify({"error": "Focus task not found"}), 404
return jsonify(serialize_task_summary(focus_task))
@workspace_shipping_notice_bp.route("/shipping-batches/<batch_no>/focus-task", methods=["POST"])
def workspace_switch_shipping_batch_focus_task(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
data = request.get_json(silent=True) or {}
task_no = str(data.get("task_no") or data.get("target_task_no") or "").strip()
if not task_no:
return jsonify({"error": "task_no is required"}), 400
task = get_task_for_user(task_no, user.id)
if not task or task.batch_id != batch.id:
return jsonify({"error": "Task not found in batch"}), 404
batch.current_focus_task_no = task.task_no
db.session.commit()
return jsonify(
{
"batch": serialize_batch_summary(batch),
"focus_task": serialize_task_summary(task),
}
)
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["POST"])
def workspace_create_shipping_task():
"""创建单个发货任务,适用于手工录入或聊天入口先建单。"""
user, err = _require_user()
if err:
return err
@@ -58,6 +222,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():
"""接收单个发货通知附件,建单后抽取文本并立即触发解析。"""
user, err = _require_user()
if err:
return err
@@ -123,6 +288,7 @@ def workspace_create_shipping_task_from_notice():
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>", methods=["GET"])
def workspace_shipping_task_detail(task_no: str):
"""返回指定任务的详情快照。"""
user, err = _require_user()
if err:
return err
@@ -134,6 +300,7 @@ def workspace_shipping_task_detail(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/chat-actions", methods=["GET"])
def workspace_shipping_task_chat_actions(task_no: str):
"""返回聊天气泡侧所需的动作按钮与检查点信息。"""
user, err = _require_user()
if err:
return err
@@ -145,7 +312,7 @@ def workspace_shipping_task_chat_actions(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/upload-inventory", methods=["POST"])
def workspace_upload_shipping_inventory(task_no: str):
"""Hxops chat UI: upload inventory Excel with user auth (not Tool Key)."""
"""用户态上传库存 Excel,并在服务端完成解析。"""
user, err = _require_user()
if err:
return err
@@ -161,6 +328,7 @@ def workspace_upload_shipping_inventory(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/apply-inventory-mapping", methods=["POST"])
def workspace_apply_inventory_mapping(task_no: str):
"""提交库存字段映射,并允许在工作台侧自动回退到下一步。"""
user, err = _require_user()
if err:
return err
@@ -183,7 +351,7 @@ def workspace_apply_inventory_mapping(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/submit-decision", methods=["POST"])
def workspace_submit_shipping_decision(task_no: str):
"""Hxops chat UI: submit shipping decision with user auth (bypass Dify tool routing)."""
"""以用户态提交人工决策,绕过 Dify Tool 路由直接驱动状态机。"""
user, err = _require_user()
if err:
return err
@@ -205,9 +373,110 @@ def workspace_submit_shipping_decision(task_no: str):
return jsonify(shipping_tools.submit_decision(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/update-notice-fields", methods=["POST"])
def workspace_update_shipping_notice_fields(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
data = request.get_json(silent=True) or {}
fields = data.get("fields")
if not isinstance(fields, dict) or not fields:
return jsonify({"error": "fields is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "fields": fields}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.update_notice_fields(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/update-notice-line", methods=["POST"])
def workspace_update_shipping_notice_line(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
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get("line_index"))
except (TypeError, ValueError):
return jsonify({"error": "line_index is required"}), 400
patch = data.get("patch")
if not isinstance(patch, dict) or not patch:
return jsonify({"error": "patch is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "line_index": line_index, "patch": patch}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.update_notice_line(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/add-notice-line", methods=["POST"])
def workspace_add_shipping_notice_line(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
data = request.get_json(silent=True) or {}
line = data.get("line")
if not isinstance(line, dict) or not line:
return jsonify({"error": "line is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "line": line}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.add_notice_line(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/remove-notice-line", methods=["POST"])
def workspace_remove_shipping_notice_line(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
data = request.get_json(silent=True) or {}
try:
line_index = int(data.get("line_index"))
except (TypeError, ValueError):
return jsonify({"error": "line_index is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "line_index": line_index}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.remove_notice_line(payload))
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/auto-progress", methods=["POST"])
def workspace_auto_progress_shipping_task(task_no: str):
"""Hxops chat fallback: same as Dify auto_progress tool."""
"""用户态触发 auto_progress,作为聊天前端的兜底自动推进入口。"""
user, err = _require_user()
if err:
return err
@@ -234,6 +503,7 @@ def workspace_auto_progress_shipping_task(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/match-inventory", methods=["POST"])
def workspace_match_shipping_inventory(task_no: str):
"""执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。"""
user, err = _require_user()
if err:
return err
@@ -272,7 +542,7 @@ def workspace_match_shipping_inventory(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/mark-manual-uploaded", methods=["POST"])
def workspace_mark_manual_uploaded(task_no: str):
"""Hxops chat: mark freight manual upload complete (no ref no required)."""
"""标记货代系统已人工上传完成,无需再等待 RPA 回执。"""
user, err = _require_user()
if err:
return err
@@ -289,6 +559,7 @@ def workspace_mark_manual_uploaded(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
def workspace_generate_shipping_excel(task_no: str):
"""为指定任务生成出货 Excel,并补充工作台下载链接。"""
user, err = _require_user()
if err:
return err
@@ -310,18 +581,20 @@ def workspace_generate_shipping_excel(task_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/export", methods=["GET"])
def workspace_shipping_task_export(task_no: str):
"""下载当前用户可访问任务的出货 Excel。"""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task or not task.export_file_path:
return jsonify({"error": "export file not found"}), 404
path = Path(task.export_file_path)
if not path.is_file():
return jsonify({"error": "export file missing on disk"}), 404
err_msg = task_export_error_message(task)
if err_msg:
return jsonify({"error": err_msg}), 404
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
return send_file(
path,
as_attachment=True,
download_name=task.export_file_name or path.name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
download_name=download_name,
mimetype=EXPORT_MIME_TYPE,
)
+47
View File
@@ -695,19 +695,50 @@ class ScheduleRun(Base):
kb_sync_job: Mapped[Optional["KbJob"]] = relationship("KbJob", foreign_keys=[kb_sync_job_id])
class ShippingBatch(Base):
"""货代发货通知批次(一次多文件上传的聚合容器)"""
__tablename__ = 'shipping_batches'
__table_args__ = (
Index('ix_shipping_batches_user_created', 'user_id', 'created_at'),
Index('ix_shipping_batches_conversation', 'conversation_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
batch_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
current_focus_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
file_count: Mapped[int] = mapped_column(Integer, default=1)
process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
tasks: Mapped[List["ShippingTask"]] = relationship(
"ShippingTask",
back_populates="batch",
)
class ShippingTask(Base):
"""货代发货通知 task(Chatflow Tool 编排状态机)"""
__tablename__ = 'shipping_tasks'
__table_args__ = (
Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'),
Index('ix_shipping_tasks_conversation', 'conversation_id'),
Index('ix_shipping_tasks_batch_step', 'batch_id', 'current_step'),
Index('ix_shipping_tasks_upload_status', 'upload_status'),
)
id: Mapped[int] = mapped_column(primary_key=True)
task_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
batch_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_batches.id'), index=True, nullable=True)
user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), index=True, nullable=True)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
source_type: Mapped[str] = mapped_column(String(32), default='manual')
source_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
source_file_type: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
batch_index: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
batch_total: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
@@ -719,6 +750,7 @@ class ShippingTask(Base):
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
current_step: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
@@ -728,13 +760,28 @@ class ShippingTask(Base):
export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
export_version: Mapped[int] = mapped_column(Integer, default=1)
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
upload_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
upload_mode: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
upload_attempt: Mapped[int] = mapped_column(Integer, default=0)
idempotency_key: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
upload_started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
upload_finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
upload_error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
upload_error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
upload_receipt_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
step_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
batch: Mapped[Optional["ShippingBatch"]] = relationship(
"ShippingBatch",
back_populates="tasks",
)
events: Mapped[List["ShippingTaskEvent"]] = relationship(
"ShippingTaskEvent",
back_populates="task",
@@ -1,3 +1,11 @@
"""
services/shipping_notice/agent_resolver.py
用途:定位发货通知聊天 Agent 的模型记录与名称常量。
依赖:app.models.Agent。
逻辑:由 dify_inputs、聊天入口或 Agent 相关编排调用本文件,确保发货通知流程绑定到正确的 Agent。
"""
from __future__ import annotations
from app.models import Agent
@@ -0,0 +1,315 @@
"""
services/shipping_notice/decision_workflow.py
用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配、重解析和映射修正。
依赖:state_machine、tool_response、query_service、inventory_mapping_workflow、inventory_upload、fulfillment_workflow。
逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调 auto_progress 或 parse_notice。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.services.shipping_notice.constants import (
CP_MAP_INFER,
CP_PARSE_OK,
PH_LOW_CONF,
PH_RPA_PENDING,
PH_SHORTAGE,
RS_PARSE_REVIEW,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.fulfillment_workflow import match_completed, match_inventory
from app.services.shipping_notice.inventory_mapping import mapping_is_complete
from app.services.shipping_notice.inventory_mapping_store import upsert_inventory_mapping
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_mapping_checkpoint_response,
latest_inventory_column_meta,
)
from app.services.shipping_notice.inventory_upload import (
has_uploaded_task_inventory,
read_task_inventory_schema_preview,
task_inventory_upload_path,
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.query_service import resolve_task_from_payload, 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,
merge_tool_payload,
payload_wants_auto_chain_fallback,
)
from app.services.shipping_notice.tool_response import tool_response
def submit_decision(payload: dict[str, Any]) -> dict[str, Any]:
"""
提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。
【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“更正映射”“关闭任务”等决策类指令时调用。
核心逻辑:先解析 decision,再按状态机规则分发到解析确认、映射确认、重匹配或重解析等分支。
Args:
payload: 必须包含任务定位信息与 decision,可选 comment、lang 等上下文。
Returns:
dict[str, Any]: Tool 标准响应,返回决策后的任务阶段和下一步动作。
"""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(
status="failed",
message=(
"未找到任务。用户说「确认/重新解析/驳回」时禁止 create_task。"
"请先 get_task_status(conversation_id=...) 或 submit_decision 带上任务编号。"
),
)
decision = str(payload.get("decision") or "").strip().lower()
comment = str(payload.get("comment") or "").strip()
# [STEP 1] 先处理终止型决策。
# reject / close 会直接结束当前任务,不再继续进入库存或出货链路。
if decision == "reject":
apply_task_transition(task, TaskTransition.REJECTED)
log_task_event(task, "decision_rejected", {"comment": comment})
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message="已驳回该发货任务。",
data=serialize_task_for_tool(task),
)
if decision in {"close", "closed"}:
apply_task_transition(task, TaskTransition.CLOSED)
log_task_event(task, "decision_closed", {"comment": comment})
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message="已关闭该发货任务(可在同一会话重新开新单)。",
data=serialize_task_for_tool(task),
)
# [STEP 2] 处理“确认继续”类决策。
# confirm 既可能表示确认解析,也可能表示确认已匹配结果,因此要结合当前状态分支判断。
if decision in {"confirm", "confirmed", "confirm_parse"}:
if task.review_status == RS_SHORTAGE_REVIEW or task.pending_human_reason == PH_SHORTAGE:
return tool_response(
status="failed",
task_id=task.task_no,
message="库存不足,无法使用 confirm 整单确认。请 reparse_inventory、rematch 或 reject。",
data=serialize_task_for_tool(task),
)
if (
decision == "confirm_parse"
or task.review_status == RS_PARSE_REVIEW
or task.pending_human_reason == PH_LOW_CONF
or (
task.process_status in {"parsed", "pending_review", "created"}
and not match_completed(task)
)
):
apply_task_transition(task, TaskTransition.CONFIRM_PARSE)
task.match_status = None
task.shortage_json = None
task.line_results_json = None
log_task_event(task, "parse_confirmed", {"comment": comment})
db.session.commit()
if (not task.inventory_lines_json) and (not has_uploaded_task_inventory(task.task_no)):
next_payload = merge_tool_payload(task, payload, extra={"mode": "auto"})
if payload_wants_auto_chain_fallback(payload):
from app.services.shipping_notice.task_workflow import auto_progress
return auto_progress(next_payload)
return ensure_inventory(next_payload)
return tool_response(
status="ok",
task=task,
message=(
"发货通知已确认。"
"请先处理库存(ensure_inventory / parse_inventory → confirm_inventory_mapping → match_inventory)。"
"禁止跳过匹配直接 generate_shipment_excel。"
),
data=serialize_task_for_tool(task),
checkpoint=CP_PARSE_OK,
next_required_action="ensure_inventory 或 parse_inventory",
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
if match_completed(task):
apply_task_transition(task, TaskTransition.CONFIRM_MATCHED)
log_task_event(task, "decision_confirmed", {"comment": comment})
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message="已确认,可继续生成 Excel 并上传货代系统。",
data=serialize_task_for_tool(task),
)
if task.process_status == "waiting_inventory" or (
task.pending_human_reason == PH_RPA_PENDING and not task.inventory_lines_json
):
follow_payload = merge_tool_payload(task, payload, extra={"mode": "auto"})
if payload_wants_auto_chain_fallback(payload):
from app.services.shipping_notice.task_workflow import auto_progress
return auto_progress(follow_payload)
return ensure_inventory(follow_payload)
if awaiting_inventory_mapping_confirm(task):
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(task, lang=lang or None)
if task.inventory_lines_json or task.process_status == "inventory_ready":
follow_payload = merge_tool_payload(task, payload)
if payload_wants_auto_chain_fallback(payload):
from app.services.shipping_notice.task_workflow import auto_progress
return auto_progress(follow_payload)
return tool_response(
status="ok",
task=task,
message="发货通知已确认,当前任务已进入库存处理阶段,请按当前按钮继续。",
data=serialize_task_for_tool(task),
)
return tool_response(
status="failed",
task_id=task.task_no,
message="当前状态无法使用 confirm。请先完成库存匹配,或使用 confirm_inventory_mapping / reparse。",
data=serialize_task_for_tool(task),
)
# [STEP 3] 处理重算型决策。
# rematch / confirm_inventory_mapping / correct_inventory_mapping / reparse_inventory
# 都是在当前任务基础上回退或重放局部链路,而不是重新 create_task。
if decision == "rematch":
log_task_event(task, "decision_rematch", {"comment": comment})
db.session.commit()
rematch_payload = merge_tool_payload(task, payload)
return match_inventory(rematch_payload)
if decision == "confirm_inventory_mapping":
if not awaiting_inventory_mapping_confirm(task):
return tool_response(
status="failed",
task_id=task.task_no,
message="当前无需确认库存字段对齐。",
data=serialize_task_for_tool(task),
)
meta = latest_inventory_column_meta(task) or {}
inv_mapping = meta.get("mapping") if isinstance(meta.get("mapping"), dict) else {}
res_source = None
if isinstance(inv_mapping.get("reservation_id"), dict):
res_source = inv_mapping["reservation_id"].get("source_column")
if not str(res_source or "").strip():
apply_task_transition(task, TaskTransition.ALIGN_REVIEW_HOLD)
db.session.commit()
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(
task,
column_meta=meta,
extra_data={
"warnings": [
"库存表必须包含 Reservation ID 列标题(该列允许为空值)。"
"请改用「更正映射」重新选择 Reservation ID 对应的列,或重新上传包含该列的库存 Excel。"
],
},
lang=lang or None,
)
headers = meta.get("headers") if isinstance(meta.get("headers"), list) else []
field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None
if headers and field_mapping and mapping_is_complete(field_mapping):
upsert_inventory_mapping(
task.customer_code,
preview={
"headers": headers,
"header_row_index": meta.get("header_row_index") or 1,
},
field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()},
)
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
log_task_event(task, "inventory_mapping_confirmed", {"comment": comment})
db.session.commit()
next_payload = merge_tool_payload(task, payload)
return match_inventory(next_payload)
if decision == "correct_inventory_mapping":
if not awaiting_inventory_mapping_confirm(task):
return tool_response(
status="failed",
task_id=task.task_no,
message="当前不在库存字段对齐确认步骤,无法更正映射。",
data=serialize_task_for_tool(task),
)
task.inventory_lines_json = None
apply_task_transition(task, TaskTransition.CORRECT_MAPPING)
log_task_event(task, "inventory_mapping_correction_requested", {"comment": comment})
db.session.commit()
upload_path = task_inventory_upload_path(task.task_no)
if upload_path.is_file():
try:
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
return tool_response(
status="failed",
task_id=task.task_no,
message=f"读取库存表头失败: {exc}",
data=serialize_task_for_tool(task),
)
else:
meta = latest_inventory_column_meta(task) or {}
preview = {
"headers": meta.get("headers") or [],
"sample_rows": [],
"suggested_mapping": meta.get("field_mapping") or {},
"note": "无已上传 Excel;请粘贴库存小表或重新上传后 apply_inventory_mapping / parse_inventory。",
}
return tool_response(
status="needs_human",
task=task,
message=(
"已回到列映射步骤。请根据 schema_preview 提供新的 map_json,"
"再调用 apply_inventory_mapping。"
),
data={**serialize_task_for_tool(task), "schema_preview": preview},
checkpoint=CP_MAP_INFER,
next_required_action="apply_inventory_mapping(map_json=...)",
forbidden_next_tools=["match_inventory"],
stop_agent_turn=True,
)
if decision == "reparse_inventory":
task.inventory_lines_json = None
if task.process_status == "inventory_ready":
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY_DEMOTE)
else:
apply_task_transition(task, TaskTransition.REPARSE_INVENTORY)
upload_path = task_inventory_upload_path(task.task_no)
if upload_path.is_file():
try:
upload_path.unlink()
except OSError:
pass
log_task_event(task, "inventory_reparse_requested", {"comment": comment})
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message="已清除库存快照,请重新上传或粘贴库存后调用 parse_inventory。",
data=serialize_task_for_tool(task),
)
# [STEP 4] 最后处理整单重新解析。
# 该分支会复用已有任务号和原始文本,避免产生重复任务。
if decision == "reparse":
from app.services.shipping_notice.task_workflow import parse_notice
return parse_notice({"task_id": task.task_no, "raw_text": task.raw_content or ""})
return tool_response(status="failed", task_id=task.task_no, message=f"未知 decision: {decision}")
@@ -1,3 +1,11 @@
"""
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 请求上下文。
"""
from __future__ import annotations
from flask import current_app
@@ -1,3 +1,11 @@
"""
services/shipping_notice/export.py
用途:生成发货通知对应的货代出货 Excel,并管理模板与导出文件存储路径。
依赖:openpyxl、app.models.ShippingTask、path_utils、Flask current_app 配置。
逻辑:由 fulfillment_workflow.generate_excel 调用本文件,根据任务数据填充模板后返回导出文件路径。
"""
from __future__ import annotations
from datetime import datetime
@@ -1,3 +1,11 @@
"""
services/shipping_notice/extract.py
用途:抽取发货通知中的单头字段与订单行,并在收尾阶段补充文档级字段和告警。
依赖:po_number、reservation_id、notice_lines 中的标准化与回填工具。
逻辑:由 task_workflow.parse_notice 调用本文件完成原始文本解析,再把结果交给 parse_summary 和状态机链路。
"""
from __future__ import annotations
import re
@@ -1,3 +1,11 @@
"""
services/shipping_notice/field_alignment_summary.py
用途:把库存字段对齐结果格式化成适合聊天区和人工确认的摘要文本。
依赖:shipping_notice.i18n、多语言文案与字段对齐 payload。
逻辑:由 inventory_mapping_workflow 或前端映射确认链路调用本文件,生成给用户确认映射的说明文本。
"""
from __future__ import annotations
from typing import Any
@@ -0,0 +1,487 @@
"""
services/shipping_notice/fulfillment_workflow.py
用途:发货通知履约阶段 — 库存匹配、Excel 导出、货代上传/RPA 与自动串联编排。
依赖:match、export、rpa、query_service、inventory_workflow、inventory_mapping_workflow、tool_common、tool_response。
逻辑:tools.py 门面 re-export;库存就绪后由 inventory_workflow 委托 try_auto_chain_after_match。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
from flask import current_app
from app import db
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_UPLOADED, PH_UPLOAD_RPA_PENDING
from app.services.shipping_notice.export import generate_shipment_excel
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_mapping_checkpoint_response,
)
from app.services.shipping_notice.inventory_workflow import (
ensure_inventory,
parse_inventory_lines,
)
from app.services.shipping_notice.match import format_match_summary, match_notice_lines
from app.services.shipping_notice.query_service import (
resolve_task_from_payload,
serialize_task_for_tool,
)
from app.services.shipping_notice.reservation_id import extract_reservation_id
from app.services.shipping_notice.rpa import write_upload_trigger
from app.services.shipping_notice.rpa_attempts import (
max_rpa_upload_attempts,
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_response import tool_response
def _cfg_bool(key: str, default: bool = False) -> bool:
val = current_app.config.get(key)
if val is None:
return default
if isinstance(val, bool):
return val
return str(val).strip().lower() in {"1", "true", "yes", "on"}
def _cfg_int(key: str, default: int = 0, *, min_value: int | None = None) -> int:
val = current_app.config.get(key)
if val is None:
parsed = default
else:
try:
parsed = int(val)
except (TypeError, ValueError):
parsed = default
if min_value is not None:
parsed = max(parsed, min_value)
return parsed
def _auto_match_enabled() -> bool:
return _cfg_bool("SHIPPING_NOTICE_AUTO_MATCH_ENABLED", True)
def _auto_generate_excel_enabled() -> bool:
return _cfg_bool("SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED", True)
def _auto_upload_enabled() -> bool:
return _cfg_bool("SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED", False)
def _rpa_upload_timeout_seconds() -> int:
return _cfg_int("SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS", 30, min_value=5)
def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] | None = None) -> None:
"""写入 ShippingTaskEvent 审计记录。"""
if task.id is None:
db.session.flush()
db.session.add(
ShippingTaskEvent(
task_id=task.id,
event_type=event_type,
detail_json=detail or {},
)
)
def match_completed(task: ShippingTask) -> bool:
return bool(
task.process_status == "matched"
and task.match_status
and isinstance(task.line_results_json, list)
and len(task.line_results_json) > 0
)
def excel_gate_error(task: ShippingTask) -> str | None:
if task.process_status == "uploaded" and task.export_file_path:
return None
if not match_completed(task):
return "尚未完成库存匹配。请先上传库存、确认字段对齐并调用 match_inventory。"
return None
def latest_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent | None:
if task.id is None:
return None
return (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type)
.order_by(ShippingTaskEvent.id.desc())
.first()
)
def should_auto_chain_after_match(payload: dict[str, Any] | None) -> bool:
from app.services.shipping_notice.tool_common import payload_wants_auto_chain_fallback
return payload_wants_auto_chain_fallback(payload)
def try_auto_chain_after_match(
task: ShippingTask,
match_result: dict[str, Any],
*,
payload: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""After fulfillable match: generate Excel and optionally trigger RPA upload (fallback chain)."""
if match_result.get("status") != "ok":
return match_result
if not should_auto_chain_after_match(payload):
return match_result
result = match_result
from app.services.shipping_notice.tool_common import merge_tool_payload
tool_payload = merge_tool_payload(task, payload)
if _auto_generate_excel_enabled():
db.session.refresh(task)
if not task.export_file_path and match_completed(task):
gen = generate_excel(tool_payload)
if gen.get("status") != "ok":
return gen
result = prepend_tool_message(gen, str(result.get("message") or ""))
if _auto_upload_enabled():
db.session.refresh(task)
if task.export_file_path and task.process_status != "uploaded":
up = upload_to_freight({**tool_payload, "mode": "auto"})
if up.get("status") == "failed":
return up
result = prepend_tool_message(up, str(result.get("message") or ""))
if up.get("status") in {"running", "needs_human"}:
return {**up, "message": result.get("message", up.get("message", ""))}
return result
def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
if awaiting_inventory_mapping_confirm(task):
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(task, lang=lang or None)
inventory_lines = parse_inventory_lines(payload)
if inventory_lines:
task.inventory_lines_json = inventory_lines
elif not task.inventory_lines_json:
inv_payload: dict[str, Any] = {"task_id": task.task_no}
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
if lang:
inv_payload["lang"] = lang
return ensure_inventory(inv_payload)
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 [])
if not extract_reservation_id(line.get("reservation_id"))
]
inv_missing_count = sum(
1
for row in (task.inventory_lines_json or [])
if not extract_reservation_id((row or {}).get("reservation_id"))
)
if order_missing:
apply_task_transition(task, TaskTransition.RSV_REQUIRED)
task.match_status = None
task.shortage_json = None
task.line_results_json = None
detail = {
"order_missing_count": len(order_missing),
"order_missing_preview": order_missing[:5],
}
log_task_event(task, "reservation_id_required", detail)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=(
"当前匹配规则要求发货需求(订单)必须提供 Reservation ID。"
f"订单缺少 Reservation ID:{len(order_missing)} 行。"
"请重新解析发货通知后再匹配。"
),
data={**serialize_task_for_tool(task), "reservation_id_required": detail},
stop_agent_turn=True,
forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"],
)
match_status, line_results, shortage = match_notice_lines(
notice_lines,
task.inventory_lines_json or [],
)
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
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() or None
match_summary = format_match_summary(
match_status,
line_results,
task_no=task.task_no,
lang=lang,
)
if match_status == "fulfillable":
apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE)
log_task_event(task, "matched_fulfillable", {"match_status": match_status})
db.session.commit()
match_result = tool_response(
status="ok",
task_id=task.task_no,
message=match_summary,
data=serialize_task_for_tool(task),
)
return try_auto_chain_after_match(task, match_result, payload=payload)
apply_task_transition(task, TaskTransition.MATCH_SHORTAGE)
log_task_event(task, "match_needs_review", {"match_status": match_status, "shortage": shortage})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=match_summary,
data=serialize_task_for_tool(task),
)
def generate_excel(payload: dict[str, Any]) -> dict[str, Any]:
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
gate_error = excel_gate_error(task)
if gate_error:
return tool_response(
status="failed",
task_id=task.task_no,
message=gate_error,
data=serialize_task_for_tool(task),
forbidden_next_tools=["upload_to_freight"],
next_required_action="match_inventory(须先完成库存上传与字段对齐确认)",
)
path, filename = generate_shipment_excel(task)
task.export_file_path = path
task.export_file_name = filename
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
log_task_event(task, "export_generated", {"file_name": filename})
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=f"已生成发货 Excel:{filename}",
data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"},
)
def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
if not task.export_file_path:
gen = generate_excel({"task_id": task.task_no})
if gen.get("status") != "ok":
return gen
mode = str(payload.get("mode") or "auto").strip().lower()
if mode == "manual_confirm":
if task.process_status == "uploaded":
return tool_response(
status="ok",
task=task,
task_id=task.task_no,
message=f"任务 {task.task_no} 已标记为完成,无需重复操作。",
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED,
human_options=[],
)
apply_task_transition(task, TaskTransition.UPLOADED)
ref = str(payload.get("freight_ref_no") or "").strip()
if ref:
task.freight_ref_no = ref
log_task_event(task, "upload_manual_confirmed", {"freight_ref_no": ref or None})
db.session.commit()
return tool_response(
status="ok",
task=task,
task_id=task.task_no,
message=(
f"已标记为手工上传货代系统完成。任务 {task.task_no} 已全部处理完毕,"
"无需再进行任何操作。"
),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED,
human_options=[],
)
if mode == "retry_upload" or mode == "auto":
timeout_seconds = _rpa_upload_timeout_seconds()
max_attempts = max_rpa_upload_attempts()
if (
task.pending_human_reason == PH_UPLOAD_RPA_PENDING
and task.process_status == "waiting_upload"
and task.export_file_path
and task.process_status != "uploaded"
):
last_trigger = latest_event(task, "upload_rpa_triggered")
if last_trigger and isinstance(last_trigger.created_at, datetime):
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
if elapsed < timeout_seconds:
attempts = upload_rpa_attempts(task)
remaining = max(timeout_seconds - elapsed, 1)
return tool_response(
status="running",
task_id=task.task_no,
message=(
f"RPA 上传进行中(第 {max(attempts, 1)}/{max_attempts} 次)。"
f"已等待 {elapsed}s / 超时 {timeout_seconds}s。"
f"请稍后再试(建议 {remaining}s 后)。"
),
data={
**serialize_task_for_tool(task),
"rpa": {
"attempts": max(attempts, 1),
"max_attempts": max_attempts,
"elapsed_seconds": elapsed,
"timeout_seconds": timeout_seconds,
"retry_after_seconds": remaining,
},
},
)
last_failed = latest_event(task, "upload_rpa_failed")
if not last_failed or (last_failed.created_at < last_trigger.created_at):
task.error_message = f"RPA 上传超时(>{timeout_seconds}s)"
log_task_event(
task,
"upload_rpa_failed",
{"error": "timeout", "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds},
)
db.session.flush()
attempts = upload_rpa_attempts(task)
if attempts >= max_attempts:
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
task.error_message = f"已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。"
log_task_event(task, "upload_rpa_exhausted", {"attempts": attempts, "max_attempts": max_attempts})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=task.error_message,
data=serialize_task_for_tool(task),
)
queued, trigger = write_upload_trigger(task.task_no, task.export_file_path or "")
if queued and trigger:
apply_task_transition(task, TaskTransition.UPLOAD_RPA_PENDING)
attempt_no = attempts + 1
log_task_event(
task,
"upload_rpa_triggered",
{
"queue_file": queued,
"trigger": trigger,
"attempt": attempt_no,
"timeout_seconds": timeout_seconds,
"max_attempts": max_attempts,
},
)
db.session.commit()
return tool_response(
status="running",
task_id=task.task_no,
message=(
f"已触发 RPA 上传货代(第 {attempt_no}/{max_attempts} 次)。"
f"若 {timeout_seconds}s 内无回调,可重试;超过最大次数将转手工上传。"
),
data={
**serialize_task_for_tool(task),
"queue_file": queued,
"rpa": {"attempts": attempt_no, "max_attempts": max_attempts, "timeout_seconds": timeout_seconds},
},
)
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
task.error_message = "RPA 上传目录未配置或触发失败"
log_task_event(task, "upload_rpa_pending", {})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="RPA 自动上传失败或未配置。请下载 Excel 在货代系统手工上传,完成后告知我。",
data=serialize_task_for_tool(task),
)
def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
success = bool(payload.get("success", True))
if success:
apply_task_transition(task, TaskTransition.UPLOADED)
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()
return tool_response(
status="ok",
task=task,
task_id=task.task_no,
message="RPA 已成功上传货代系统,任务已全部处理完毕。",
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOADED,
human_options=[],
)
apply_task_transition(task, TaskTransition.UPLOAD_FAILED)
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()
attempts = upload_rpa_attempts(task)
max_attempts = max_rpa_upload_attempts()
if attempts >= max_attempts:
task.error_message = f"已尝试 {attempts} 次仍无法通过 RPA 上传,请下载 Excel 手工上传。"
log_task_event(task, "upload_rpa_exhausted", {"attempts": attempts, "max_attempts": max_attempts})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=task.error_message,
data=serialize_task_for_tool(task),
)
def run_auto_progress_fulfillment_steps(
task: ShippingTask,
payload: dict[str, Any],
steps: list[str],
) -> dict[str, Any] | None:
"""auto_progress 中匹配→导出→上传编排;有早停响应时返回 dict,否则返回 None。"""
if _auto_match_enabled() and not match_completed(task):
matched = match_inventory({"task_id": task.task_no, **(payload or {})})
if matched.get("status") != "ok":
return matched
steps.append("库存匹配")
if _auto_generate_excel_enabled() and match_completed(task) and not task.export_file_path:
gen = generate_excel({"task_id": task.task_no})
if gen.get("status") != "ok":
return gen
steps.append("生成发货 Excel")
if _auto_upload_enabled() and task.export_file_path and task.process_status != "uploaded":
up = upload_to_freight({"task_id": task.task_no, "mode": "auto"})
if up.get("status") == "running":
steps.append("触发 RPA 上传")
return up
return None
+14 -6
View File
@@ -1,3 +1,11 @@
"""
services/shipping_notice/i18n.py
用途:维护发货通知链路的多语言文案与语言解析工具。
依赖:Flask request 上下文、模块内 `_MESSAGES` 文案字典。
逻辑:由 parse_summary、field_alignment_summary、workflow 提示文案等上游模块调用本文件输出用户可读消息。
"""
from __future__ import annotations
from typing import Any
@@ -55,8 +63,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
"match.status.shortage": "❌ 不足",
"match.status.unknown": "未知",
"match.conclusion.fulfillable": "**结论**:库存充足,可生成发货 Excel 并上传货代系统。",
"match.conclusion.partial": "**结论**:部分行库存不足,请复核缺口后决定是否部分发货。",
"match.conclusion.unfulfillable": "**结论**:库存均不足,无法整单发货。",
"match.conclusion.partial": "**结论**:存在库存缺口,无法发货。请补库存或返回修订后重新匹配,直至全部行满足。",
"match.conclusion.unfulfillable": "**结论**:库存均不足,无法发货。请补库存或返回修订后重新匹配。",
"match.conclusion.other": "**结论**:match_status={status}",
"match.no_lines": "无订单明细,无法比对数量。",
},
@@ -108,8 +116,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
"match.status.shortage": "❌ Short",
"match.status.unknown": "Unknown",
"match.conclusion.fulfillable": "**Result**: Inventory is sufficient. You may generate the shipment Excel and upload.",
"match.conclusion.partial": "**Result**: Some lines are short. Review gaps before partial shipment.",
"match.conclusion.unfulfillable": "**Result**: Insufficient inventory for all lines.",
"match.conclusion.partial": "**Result**: Inventory gap detected. Shipment blocked until all lines are fulfilled. Re-upload inventory or revise mapping, then rematch.",
"match.conclusion.unfulfillable": "**Result**: Insufficient inventory for all lines. Shipment blocked until inventory is replenished.",
"match.conclusion.other": "**Result**: match_status={status}",
"match.no_lines": "No order lines to compare.",
},
@@ -161,8 +169,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
"match.status.shortage": "❌ ไม่พอ",
"match.status.unknown": "ไม่ทราบ",
"match.conclusion.fulfillable": "**สรุป**: สต็อกเพียงพอ สามารถสร้าง Excel และอัปโหลดได้",
"match.conclusion.partial": "**สรุป**: บางรายการสต็อกไม่พอ กรุณาตรวจสอบส่วนต่าง",
"match.conclusion.unfulfillable": "**สรุป**: สต็อกไม่เพียงพอทั้งหมด",
"match.conclusion.partial": "**สรุป**: มีส่วนต่างสต็อก ไม่สามารถจัดส่งได้ กรุณาเติมสต็อกหรือแก้ไขแล้วจับคู่ใหม่จนกว่าทุกรายการจะครบ",
"match.conclusion.unfulfillable": "**สรุป**: สต็อกไม่เพียงพอทั้งหมด ไม่สามารถจัดส่งได้ กรุณาเติมสต็อกหรือแก้ไขแล้วจับคู่ใหม่",
"match.conclusion.other": "**สรุป**: match_status={status}",
"match.no_lines": "ไม่มีรายการสั่งซื้อสำหรับเปรียบเทียบ",
},
@@ -1,3 +1,11 @@
"""
services/shipping_notice/inventory_mapping.py
用途:标准化库存字段映射,补充匹配规则说明,并校验映射是否完整。
依赖:match_rule_desc、标准 `json`/`typing` 能力。
逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件解析 map_json,再进入库存解析和匹配链路。
"""
from __future__ import annotations
from typing import Any
@@ -1,3 +1,11 @@
"""
services/shipping_notice/inventory_mapping_store.py
用途:持久化库存字段映射模板,并按客户与表头哈希做查询复用。
依赖:db、ShippingInventoryMapping 模型、hashlib/json。
逻辑:由 inventory_mapping_workflow 或库存上传链路调用本文件,把用户确认过的映射保存下来供后续同模板复用。
"""
from __future__ import annotations
import json
@@ -0,0 +1,285 @@
"""
services/shipping_notice/inventory_mapping_workflow.py
用途:库存字段对齐确认、自动映射推进与库存载入后的 auto-chain 编排。
依赖:inventory_snapshot、inventory_mapping_store、query_service、tool_common、state_machine。
逻辑:inventory_workflow / inventory_rpa_workflow 在解析/上传后委托本模块;
task_workflow / fulfillment_workflow 在决策与 auto_progress 中调用映射门禁。
"""
from __future__ import annotations
from typing import Any
from flask import current_app
from app import db
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.field_alignment_summary import format_field_alignment_summary
from app.services.shipping_notice.inventory_mapping import mapping_is_complete
from app.services.shipping_notice.inventory_mapping_store import upsert_inventory_mapping
from app.services.shipping_notice.inventory_snapshot import build_field_alignment_preview
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 (
auto_mapping_allow_llm,
auto_match_enabled,
auto_progress_enabled,
log_task_event,
payload_wants_auto_chain_fallback,
)
from app.services.shipping_notice.tool_response import tool_response
from app.services.shipping_notice.constants import RS_ALIGN_REVIEW
def mapping_review_enabled() -> bool:
val = current_app.config.get("SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW")
if val is None:
return True
return str(val).lower() not in {"0", "false", "no", "off"}
def awaiting_inventory_mapping_confirm(task: ShippingTask) -> bool:
return task.review_status == RS_ALIGN_REVIEW
def latest_inventory_column_meta(task: ShippingTask) -> dict[str, Any] | None:
if task.id is None:
return None
events = (
ShippingTaskEvent.query.filter_by(task_id=task.id)
.order_by(ShippingTaskEvent.id.desc())
.limit(30)
.all()
)
for event in events:
detail = event.detail_json or {}
meta = detail.get("column_meta")
if isinstance(meta, dict) and meta:
return meta
return None
def field_alignment_for_task(task: ShippingTask, column_meta: dict[str, Any] | None = None) -> dict[str, Any]:
meta = column_meta or latest_inventory_column_meta(task)
return build_field_alignment_preview(
task.inventory_lines_json or [],
task.lines_json or [],
column_meta=meta,
)
def mapping_confirm_blockers(task: ShippingTask) -> list[str]:
"""Reasons inventory field mapping cannot be confirmed yet."""
blockers: list[str] = []
meta = latest_inventory_column_meta(task) or {}
inv_mapping = meta.get("mapping") if isinstance(meta.get("mapping"), dict) else {}
res_source = None
if isinstance(inv_mapping.get("reservation_id"), dict):
res_source = inv_mapping["reservation_id"].get("source_column")
if not str(res_source or "").strip():
blockers.append("缺少 Reservation ID 列映射")
field_alignment = field_alignment_for_task(task)
warnings = field_alignment.get("warnings") if isinstance(field_alignment.get("warnings"), list) else []
blockers.extend(str(w) for w in warnings if w)
return blockers
def can_auto_advance_mapping(task: ShippingTask) -> bool:
"""Mapping is complete with no blockers — may skip align_review human gate."""
if not auto_progress_enabled() or not auto_match_enabled():
return False
if not mapping_review_enabled():
return False
if not awaiting_inventory_mapping_confirm(task):
return False
if mapping_confirm_blockers(task):
return False
meta = latest_inventory_column_meta(task) or {}
mapping_source = str(meta.get("mapping_source") or "rules").strip().lower()
if mapping_source == "llm" and not auto_mapping_allow_llm():
return False
return True
def should_auto_chain_after_mapping(
task: ShippingTask,
payload: dict[str, Any] | None,
) -> bool:
if payload_wants_auto_chain_fallback(payload):
return True
return can_auto_advance_mapping(task)
def inventory_mapping_checkpoint_response(
task: ShippingTask,
*,
column_meta: dict[str, Any] | None = None,
extra_data: dict[str, Any] | None = None,
lang: str | None = None,
) -> dict[str, Any]:
"""Agent MUST stop and wait for user before match_inventory."""
field_alignment = field_alignment_for_task(task, column_meta)
extra = extra_data or {}
message = format_field_alignment_summary(
task_no=task.task_no,
field_alignment=field_alignment,
inventory_row_count=extra.get("inventory_row_count"),
warnings=extra.get("warnings") if isinstance(extra.get("warnings"), list) else None,
lang=lang,
)
data = {
**serialize_task_for_tool(task),
"field_alignment": field_alignment,
**extra,
}
return tool_response(
status="needs_human",
task=task,
message=message,
data=data,
next_required_action=(
"向用户原文展示 message(固定 Markdown)后停止本轮;"
"用户确认后调用 submit_decision(decision=confirm_inventory_mapping);"
"禁止在同一轮调用 match_inventory"
),
forbidden_next_tools=[
"match_inventory",
"generate_shipment_excel",
"upload_to_freight",
],
stop_agent_turn=True,
)
def maybe_auto_confirm_inventory_mapping(task: ShippingTask) -> bool:
if not auto_progress_enabled():
return False
if not mapping_review_enabled():
return False
if not awaiting_inventory_mapping_confirm(task):
return False
if mapping_confirm_blockers(task):
return False
meta = latest_inventory_column_meta(task) or {}
mapping_source = str(meta.get("mapping_source") or "rules").strip().lower()
if mapping_source == "llm" and not auto_mapping_allow_llm():
return False
headers = meta.get("headers") if isinstance(meta.get("headers"), list) else []
field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None
if headers and field_mapping and mapping_is_complete(field_mapping):
upsert_inventory_mapping(
task.customer_code,
preview={
"headers": headers,
"header_row_index": meta.get("header_row_index") or 1,
},
field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()},
)
field_alignment = field_alignment_for_task(task)
apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED)
log_task_event(task, "inventory_mapping_auto_confirmed", {"field_alignment": field_alignment})
db.session.commit()
return True
def _try_auto_chain_after_inventory_loaded(
task: ShippingTask,
*,
payload: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
"""Auto: confirm mapping → match → Excel → RPA upload when allowed."""
from app.services.shipping_notice.fulfillment_workflow import (
match_completed,
match_inventory,
try_auto_chain_after_match,
)
from app.services.shipping_notice.tool_common import merge_tool_payload, prepend_tool_message
if not should_auto_chain_after_mapping(task, payload):
return None
auto_confirmed = maybe_auto_confirm_inventory_mapping(task)
if auto_confirmed:
db.session.refresh(task)
if awaiting_inventory_mapping_confirm(task):
return None
if not auto_match_enabled() or match_completed(task):
return None
match_result = match_inventory(merge_tool_payload(task, payload))
if auto_confirmed:
match_result = prepend_tool_message(match_result, "字段对齐已自动确认。")
return try_auto_chain_after_match(task, match_result, payload=payload)
def inventory_loaded_response(
task: ShippingTask,
inventory_lines: list[dict[str, Any]],
*,
warnings: list[str] | None = None,
column_meta: dict[str, Any] | None = None,
source: str,
require_mapping_review: bool,
event_type: str,
chain_payload: dict[str, Any] | None = None,
) -> dict[str, Any]:
task.inventory_lines_json = inventory_lines
field_alignment = field_alignment_for_task(task, column_meta)
if require_mapping_review and mapping_review_enabled():
apply_task_transition(task, TaskTransition.INVENTORY_ALIGN_REVIEW)
log_task_event(
task,
event_type,
{
"row_count": len(inventory_lines),
"warnings": warnings or [],
"source": source,
"mapping_review": True,
"column_meta": column_meta,
},
)
db.session.commit()
chained = _try_auto_chain_after_inventory_loaded(task, payload=chain_payload)
if chained is not None:
return chained
lang = None
if chain_payload:
lang = str(
chain_payload.get("lang")
or chain_payload.get("locale")
or chain_payload.get("language")
or ""
).strip() or None
return inventory_mapping_checkpoint_response(
task,
column_meta=column_meta,
extra_data={
"inventory_row_count": len(inventory_lines),
"warnings": warnings or [],
},
lang=lang,
)
apply_task_transition(task, TaskTransition.INVENTORY_READY)
log_task_event(
task,
event_type,
{
"row_count": len(inventory_lines),
"warnings": warnings or [],
"source": source,
"column_meta": column_meta,
},
)
db.session.commit()
return tool_response(
status="ok",
task=task,
message=f"已载入库存 {len(inventory_lines)} 行,可进行匹配。",
data={
**serialize_task_for_tool(task),
"inventory_row_count": len(inventory_lines),
"field_alignment": field_alignment,
"warnings": warnings or [],
},
)
@@ -0,0 +1,225 @@
"""
services/shipping_notice/inventory_rpa_workflow.py
用途:发货通知库存 RPA 编排(触发导出、等待/超时、回调落盘)。
依赖:rpa、rpa_attempts、inventory_snapshot、inventory_mapping_workflow、query_service、tool_common、state_machine、tool_response。
逻辑:inventory_workflow.ensure_inventory 在 mode=auto/retry_rpa 时委托本模块;tools 门面 re-export rpa_report_inventory。
"""
from __future__ import annotations
from datetime import datetime
from pathlib import Path
from typing import Any
from app import db
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_RPA_PENDING
from app.services.shipping_notice.inventory_snapshot import ingest_inventory_file
from app.services.shipping_notice.query_service import (
resolve_task_from_payload,
serialize_task_for_tool,
)
from app.services.shipping_notice.rpa import (
find_latest_inventory_file,
inventory_processed_dir,
write_inventory_export_trigger,
)
from app.services.shipping_notice.rpa_attempts import (
inventory_rpa_attempts,
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_response import tool_response
def latest_task_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent | None:
"""返回任务最近一条指定类型的 ShippingTaskEvent(RPA 超时/重试用)。"""
if task.id is None:
return None
return (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type=event_type)
.order_by(ShippingTaskEvent.id.desc())
.first()
)
def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any]:
"""触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
timeout_seconds = rpa_inventory_timeout_seconds()
if (
task.pending_human_reason == PH_RPA_PENDING
and task.process_status == "waiting_inventory"
and not task.inventory_lines_json
):
last_trigger = latest_task_event(task, "inventory_rpa_triggered")
if last_trigger and isinstance(last_trigger.created_at, datetime):
elapsed = int((datetime.utcnow() - last_trigger.created_at).total_seconds())
if elapsed < timeout_seconds:
max_attempts = max_rpa_inventory_attempts()
attempts = inventory_rpa_attempts(task)
remaining = max(timeout_seconds - elapsed, 1)
return tool_response(
status="running",
task_id=task.task_no,
message=(
f"RPA 库存导出进行中(第 {max(attempts, 1)}/{max_attempts} 次)。"
f"已等待 {elapsed}s / 超时 {timeout_seconds}s。"
f"请稍后再试(建议 {remaining}s 后)。"
),
data={
**serialize_task_for_tool(task),
"rpa": {
"attempts": max(attempts, 1),
"max_attempts": max_attempts,
"elapsed_seconds": elapsed,
"timeout_seconds": timeout_seconds,
"retry_after_seconds": remaining,
},
},
)
last_failed = latest_task_event(task, "inventory_rpa_failed")
if not last_failed or (last_failed.created_at < last_trigger.created_at):
task.error_message = f"RPA 库存导出超时(>{timeout_seconds}s)"
log_task_event(
task,
"inventory_rpa_failed",
{
"error": "timeout",
"elapsed_seconds": elapsed,
"timeout_seconds": timeout_seconds,
},
)
db.session.flush()
attempts = inventory_rpa_attempts(task)
max_attempts = max_rpa_inventory_attempts()
if attempts >= max_attempts and not task.inventory_lines_json:
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempts})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
data=serialize_task_for_tool(task),
)
latest = find_latest_inventory_file()
processed = inventory_processed_dir()
if latest and processed:
try:
lines, column_meta = ingest_inventory_file(latest, move_to=processed)
if lines:
return inventory_loaded_response(
task,
lines,
column_meta=column_meta,
source="rpa_drop",
require_mapping_review=True,
event_type="inventory_rpa_drop_ingested",
)
except Exception as exc:
task.error_message = str(exc)[:500]
attempt_no = attempts + 1
trigger = write_inventory_export_trigger(task.task_no, {"mode": mode, "attempt": attempt_no})
if trigger:
apply_task_transition(task, TaskTransition.RPA_PENDING)
log_task_event(task, "inventory_rpa_triggered", {"trigger": trigger, "attempt": attempt_no})
if attempt_no >= max_attempts and not task.inventory_lines_json:
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempt_no})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=f"已尝试 {attempt_no} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
data=serialize_task_for_tool(task),
)
db.session.commit()
return tool_response(
status="running",
task_id=task.task_no,
message=(
f"已触发 RPA 库存导出(第 {attempt_no}/{max_attempts} 次)。"
f"若 {timeout_seconds}s 内无回调/无落盘文件,可继续重试;超过最大次数将转人工上传。"
),
data={
**serialize_task_for_tool(task),
"rpa": {
"attempts": attempt_no,
"max_attempts": max_attempts,
"timeout_seconds": timeout_seconds,
},
},
)
log_task_event(task, "inventory_rpa_retry_requested", {})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="RPA 库存目录未配置或触发失败。请上传货代库存 Excel。",
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
)
def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""RPA 库存导出完成回调:落盘 Excel 并进入字段映射确认。"""
from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
success = bool(payload.get("success", True))
if not success:
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
task.error_message = str(payload.get("error_message") or "RPA inventory export failed")[:500]
log_task_event(task, "inventory_rpa_failed", {"error": task.error_message})
db.session.flush()
attempts = inventory_rpa_attempts(task)
if attempts >= max_rpa_inventory_attempts():
apply_task_transition(task, TaskTransition.RPA_EXHAUSTED)
task.error_message = "已多次尝试仍无法通过 RPA 获取库存"
log_task_event(task, "inventory_rpa_exhausted", {"attempts": attempts})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=f"已尝试 {attempts} 次仍无法通过 RPA 获取库存,请手动上传货代库存 Excel 继续。",
data=serialize_task_for_tool(task),
)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=task.error_message,
data=serialize_task_for_tool(task),
)
file_path = str(payload.get("file_path") or "").strip()
path = Path(file_path) if file_path else find_latest_inventory_file()
if not path or not path.is_file():
return tool_response(status="failed", task_id=task.task_no, message="库存文件不存在")
processed = inventory_processed_dir()
lines, column_meta = ingest_inventory_file(path, move_to=processed)
return inventory_loaded_response(
task,
lines,
column_meta=column_meta,
source="rpa_callback",
require_mapping_review=True,
event_type="inventory_rpa_ready",
)
@@ -1,3 +1,11 @@
"""
services/shipping_notice/inventory_snapshot.py
用途:解析库存 Excel/文本快照,抽取表头、库存行与字段对齐预览,为库存映射与匹配流程提供基础数据。
依赖:openpyxl、reservation_id、Flask current_app 配置、Path 文件操作。
逻辑:由 inventory_workflow、inventory_mapping_workflow 等上游模块调用本文件读取库存附件,再把解析结果传给字段映射确认和库存匹配链路。
"""
from __future__ import annotations
import json
@@ -1,3 +1,11 @@
"""
services/shipping_notice/inventory_upload.py
用途:管理任务级库存附件上传、落盘、schema preview 读取与文本长度限制。
依赖:inventory_snapshot、export._storage_root、Werkzeug FileStorage、Flask current_app 配置。
逻辑:由 inventory_workflow、task_workflow 与工作台上传入口调用本文件,把库存文件保存到任务目录并读取预览信息。
"""
from __future__ import annotations
import re
@@ -0,0 +1,475 @@
"""
services/shipping_notice/inventory_workflow.py
用途:发货通知库存阶段编排(解析、上传、ensure_inventory);RPA 见 inventory_rpa_workflow。
依赖:inventory_*、inventory_mapping_workflow、inventory_rpa_workflow、query_service、state_machine。
逻辑:tools.py 门面 re-export;解析/上传完成后委托 inventory_mapping_workflow 做对齐与 auto-chain。
"""
from __future__ import annotations
import json
from typing import Any
from app import db
from app.models import ShippingTask
from app.services.shipping_notice.constants import (
AUTO_MAP,
CP_MAP_INFER,
CP_UPLOAD_REQ,
SUGGEST_OK,
payload_map_json,
)
from app.services.shipping_notice.inventory_mapping import (
mapping_is_complete,
normalize_field_mapping,
validate_field_mapping_against_headers,
)
from app.services.shipping_notice.inventory_mapping_store import (
resolve_inventory_mapping,
upsert_inventory_mapping,
)
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_loaded_response,
inventory_mapping_checkpoint_response,
)
from app.services.shipping_notice.inventory_snapshot import parse_inventory_text
from app.services.shipping_notice.inventory_upload import (
has_uploaded_task_inventory,
inventory_text_max_chars,
parse_uploaded_task_inventory,
read_task_inventory_schema_preview,
save_task_inventory_upload,
)
from app.services.shipping_notice.match_rule_desc import extract_mapping_payload_extras
from app.services.shipping_notice.query_service import (
get_task_by_ref,
resolve_task_from_payload,
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_response import tool_response
def parse_inventory_lines(payload: dict[str, Any]) -> list[dict[str, Any]] | None:
"""从 payload 解析 inventory_lines / inventory_lines_json。"""
raw = payload.get("inventory_lines")
if isinstance(raw, list) and raw:
return raw
text = payload.get("inventory_lines_json")
if isinstance(text, str) and text.strip():
try:
parsed = json.loads(text)
if isinstance(parsed, list):
return parsed
except json.JSONDecodeError:
return None
return None
def _resolve_inventory_field_mapping(payload: dict[str, Any]) -> tuple[dict[str, str] | None, str]:
raw = payload_map_json(payload)
field_mapping = normalize_field_mapping(raw)
if field_mapping:
return field_mapping, "llm"
return None, "rules"
def _extract_partial_inventory_field_mapping(raw: Any) -> dict[str, str]:
data: dict[str, Any] | None = None
if isinstance(raw, dict):
data = raw
elif isinstance(raw, str) and raw.strip():
try:
parsed = json.loads(raw)
if isinstance(parsed, dict):
data = parsed
except json.JSONDecodeError:
data = None
if not data:
return {}
inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data
if not isinstance(inner, dict):
return {}
result: dict[str, str] = {}
for key in ("sku", "reservation_id", "available_qty"):
value = inner.get(key)
if value is None:
continue
text = str(value).strip()
if text:
result[key] = text
return result
def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]:
"""Parse inventory from uploaded file, chat text, or structured JSON."""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
use_uploaded = str(payload.get("use_uploaded_file") or "").strip().lower() in {
"1",
"true",
"yes",
}
raw_text = str(payload.get("raw_inventory_text") or "").strip()
inventory_lines = parse_inventory_lines(payload)
warnings: list[str] = []
column_meta: dict[str, Any] | None = None
source = "parse"
field_mapping, mapping_source = _resolve_inventory_field_mapping(payload)
mapping_extras = extract_mapping_payload_extras(payload_map_json(payload))
if mapping_extras.get("match_rule"):
mapping_source = "llm"
if use_uploaded or (not inventory_lines and not raw_text and has_uploaded_task_inventory(task.task_no)):
if not has_uploaded_task_inventory(task.task_no):
return tool_response(
status="needs_human",
task=task,
message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
stop_agent_turn=True,
)
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
task.task_no,
field_mapping=field_mapping,
mapping_source=mapping_source,
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
source = "uploaded_file"
warnings.append(f"parsed from uploaded file: {path.name}")
elif not inventory_lines:
structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None
if structured and isinstance(structured.get("lines"), list):
inventory_lines = structured["lines"]
source = "structured"
elif raw_text:
max_chars = inventory_text_max_chars()
if len(raw_text) > max_chars:
log_task_event(
task,
"inventory_text_too_large",
{"chars": len(raw_text), "max_chars": max_chars},
)
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=(
f"库存文本过大({len(raw_text)} 字符,上限 {max_chars})。"
"请勿将 Excel 全文传入 LLM;请用 HTTP 节点调用 "
"POST /tools/upload_inventory_file 上传,再 "
"parse_inventory(use_uploaded_file=true)。"
),
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
next_required_action="upload_inventory_file (multipart) then parse_inventory(use_uploaded_file=true)",
forbidden_next_tools=["match_inventory"],
stop_agent_turn=True,
)
inventory_lines, warnings, column_meta = parse_inventory_text(
raw_text,
field_mapping=field_mapping,
)
if not inventory_lines:
log_task_event(task, "inventory_parse_failed", {"warnings": warnings, "use_uploaded": use_uploaded})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="未能解析库存明细。大 Excel 请 upload_inventory_file;小表可粘贴;无库存可走 RPA。",
data={**serialize_task_for_tool(task), "warnings": warnings},
checkpoint=CP_MAP_INFER,
)
return inventory_loaded_response(
task,
inventory_lines,
warnings=warnings,
column_meta=column_meta,
source=source,
require_mapping_review=True,
event_type="inventory_parsed",
chain_payload=payload,
)
def get_inventory_schema_preview(payload: dict[str, Any]) -> dict[str, Any]:
"""Return headers + sample rows for LLM column mapping (small payload)."""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
if not has_uploaded_task_inventory(task.task_no):
return tool_response(
status="needs_human",
task=task,
message="未找到已上传的库存文件。请先 POST /tools/upload_inventory_file 上传 Excel。",
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
stop_agent_turn=True,
)
try:
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
return tool_response(status="failed", task_id=task.task_no, message=f"读取库存表头失败: {exc}")
log_task_event(task, "inventory_schema_preview", {"headers": preview.get("headers")})
db.session.commit()
return tool_response(
status="ok",
task=task,
message=(
"已读取库存表头与样例行。请根据 schema_preview 推断列映射,"
"调用 apply_inventory_mapping(map_json=...)。"
),
data={**serialize_task_for_tool(task), "schema_preview": preview},
checkpoint=CP_MAP_INFER,
next_required_action=(
"根据 data.schema_preview.headers 与 sample_rows 推断 JSON:"
'{"sku":"<列名>","reservation_id":"<列名>","available_qty":"<列名>"},'
"再调用 apply_inventory_mapping"
),
forbidden_next_tools=["match_inventory"],
)
def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]:
"""Apply LLM/manual column mapping and parse full uploaded inventory file."""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
if not has_uploaded_task_inventory(task.task_no):
return tool_response(
status="needs_human",
task=task,
message="未找到已上传的库存文件。请先 upload_inventory_file。",
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
stop_agent_turn=True,
)
try:
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
return tool_response(status="failed", task_id=task.task_no, message=f"读取库存表头失败: {exc}")
raw = payload_map_json(payload)
direct = normalize_field_mapping(raw)
partial = _extract_partial_inventory_field_mapping(raw)
template: dict[str, str] = {}
if task.customer_code:
resolved = resolve_inventory_mapping(task.customer_code, preview=preview)
if isinstance(resolved, dict):
template = {k: str(v).strip() for k, v in resolved.items() if str(v or "").strip()}
suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {}
suggested = {k: str(v).strip() for k, v in suggested.items() if str(v or "").strip()}
base: dict[str, str] = {}
if mapping_is_complete(template):
base = template
elif mapping_is_complete(suggested):
base = suggested
else:
base = {**template, **suggested}
field_mapping = direct or {**base, **partial}
mapping_extras = extract_mapping_payload_extras(raw)
if direct or partial or mapping_extras.get("match_rule"):
mapping_source = "llm"
else:
mapping_source = "rules"
if not mapping_is_complete(field_mapping):
return tool_response(
status="failed",
task_id=task.task_no,
message=(
"map_json 无效或不完整。"
'需要提供 {"sku":"列名","reservation_id":"列名","available_qty":"列名"}。'
"(库存的 Reservation ID 列允许为空值,但必须有该列标题)"
),
data={
**serialize_task_for_tool(task),
"schema_preview": preview,
"suggested_mapping": suggested,
"template_mapping": template if template else None,
"received_mapping": partial or None,
},
)
mapping_errors = validate_field_mapping_against_headers(
preview.get("headers") or [],
field_mapping,
)
if mapping_errors:
header_row = preview.get("header_row_index") or 1
return tool_response(
status="failed",
task_id=task.task_no,
message=(
"列映射与 Excel 表头不匹配。"
f"(表头在第 {header_row} 行)"
+ " ".join(mapping_errors)
+ " 请根据 schema_preview.headers 重新调用 apply_inventory_mapping。"
),
data={**serialize_task_for_tool(task), "schema_preview": preview},
)
try:
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
task.task_no,
field_mapping=field_mapping,
mapping_source=mapping_source,
header_row_index=preview.get("header_row_index"),
llm_match_rule=mapping_extras.get("match_rule"),
llm_match_key=mapping_extras.get("match_key"),
)
except FileNotFoundError as exc:
return tool_response(status="failed", task_id=task.task_no, message=str(exc))
except OSError as exc:
return tool_response(status="failed", task_id=task.task_no, message=f"解析库存失败: {exc}")
warnings = [f"parsed with mapping from uploaded file: {path.name}"]
upsert_inventory_mapping(task.customer_code, preview=preview, field_mapping=field_mapping)
return inventory_loaded_response(
task,
inventory_lines,
warnings=warnings,
column_meta=column_meta,
source="uploaded_file_mapping",
require_mapping_review=True,
event_type="inventory_mapping_applied",
chain_payload=payload,
)
def upload_inventory_file(task_id: str, upload: Any) -> dict[str, Any]:
"""Save multipart Excel; return schema preview for LLM mapping (no full parse)."""
task = get_task_by_ref(str(task_id or ""))
if not task:
return tool_response(status="failed", message="未找到任务编号")
if upload is None or not getattr(upload, "filename", None):
return tool_response(status="failed", task_id=task.task_no, message="未收到 file 字段")
filename = str(upload.filename or "").strip()
if not filename.lower().endswith((".xlsx", ".xls", ".csv")):
return tool_response(
status="failed",
task_id=task.task_no,
message="仅支持 .xlsx / .xls / .csv 库存文件",
)
try:
save_task_inventory_upload(task.task_no, upload)
preview = read_task_inventory_schema_preview(task.task_no)
except OSError as exc:
return tool_response(status="failed", task_id=task.task_no, message=f"保存库存文件失败: {exc}")
template_mapping = resolve_inventory_mapping(task.customer_code, preview=preview)
if template_mapping and mapping_is_complete(template_mapping):
try:
inventory_lines, column_meta, path = parse_uploaded_task_inventory(
task.task_no,
field_mapping=template_mapping,
mapping_source="template",
)
if inventory_lines:
warnings = [f"parsed from template mapping: {path.name}"]
return inventory_loaded_response(
task,
inventory_lines,
warnings=warnings,
column_meta=column_meta,
source="uploaded_file_template",
require_mapping_review=True,
event_type="inventory_template_mapping_used",
)
except Exception:
pass
suggested = preview.get("suggested_mapping") if isinstance(preview.get("suggested_mapping"), dict) else {}
suggested_clean = {k: str(v).strip() for k, v in suggested.items() if str(v).strip()}
suggested_complete = mapping_is_complete(suggested_clean)
auto_map = (
json.dumps(suggested_clean, ensure_ascii=False) if suggested_complete else None
)
apply_task_transition(task, TaskTransition.MAP_INFER)
log_task_event(task, "inventory_file_uploaded", {"filename": filename, "headers": preview.get("headers")})
db.session.commit()
upload_message = "库存文件已上传。"
if suggested_complete:
upload_message += " suggested_mapping 已完整,画布可直通 apply_inventory_mapping(无需 LLM)。"
else:
upload_message += " 请由画布 LLM 推断列映射后 apply_inventory_mapping。"
return tool_response(
status="ok",
task=task,
message=upload_message,
data={
**serialize_task_for_tool(task),
"schema_preview": preview,
SUGGEST_OK: suggested_complete,
AUTO_MAP: auto_map,
},
next_required_action="apply_inventory_mapping(map_json=...)",
forbidden_next_tools=["match_inventory"],
)
def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]:
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
mode = str(payload.get("mode") or "auto").strip().lower()
inventory_lines = parse_inventory_lines(payload)
if inventory_lines:
return inventory_loaded_response(
task,
inventory_lines,
source="manual_json",
require_mapping_review=False,
event_type="inventory_uploaded",
)
if mode == "retry_rpa" or mode == "auto":
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
return ensure_inventory_via_rpa(task, mode=mode)
if task.inventory_lines_json:
if awaiting_inventory_mapping_confirm(task):
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(task, lang=lang or None)
apply_task_transition(task, TaskTransition.INVENTORY_READY)
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message="已有库存快照且字段对齐已确认,可调用 match_inventory。",
data=serialize_task_for_tool(task),
)
apply_task_transition(task, TaskTransition.INV_UNAVAIL)
log_task_event(task, "inventory_missing", {})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message="暂无可用库存数据。请重试 RPA 自动导出,或手动上传货代库存 Excel。",
data=serialize_task_for_tool(task),
)
@@ -1,3 +1,11 @@
"""
services/shipping_notice/match.py
用途:执行订单行与库存行的匹配、缺货判断与匹配结果汇总。
依赖:shipping_notice.i18n、reservation_id 归一化工具、标准聚合逻辑。
逻辑:由 fulfillment_workflow.match_inventory 调用本文件,把通知订单行与库存快照比对后返回匹配状态和缺货明细。
"""
from __future__ import annotations
from typing import Any
@@ -1,3 +1,11 @@
"""
services/shipping_notice/match_rule_desc.py
用途:解析 map_json 中的匹配规则扩展字段,并生成用户可读的匹配规则说明。
依赖:标准 `json` 解析与 `typing` 工具。
逻辑:由 inventory_mapping、field_alignment_summary 等模块调用本文件,把匹配规则和附加说明渲染成展示文案。
"""
from __future__ import annotations
from typing import Any
@@ -1,3 +1,11 @@
"""
services/shipping_notice/notice_lines.py
用途:标准化发货通知订单行,并从文本/表格中抽取可用于后续库存匹配的行级结构化数据。
依赖:reservation_id、inventory_snapshot 的表格转行工具、正则与字段映射常量。
逻辑:由 extract/task_workflow 等上游模块调用本文件完成订单行归一化,再把结果交给匹配、人工更正与摘要生成链路。
"""
from __future__ import annotations
import re
@@ -426,6 +434,16 @@ def _parse_notice_row(
def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
"""
标准化单条发货通知订单行。
核心逻辑:校验 SKU 与数量必填项,统一字段别名、币种、交期和 Reservation ID,并在缺少 amount 时按单价回填。
Args:
raw: 原始订单行字典,可包含多种字段别名。
Returns:
dict[str, Any] | None: 归一化后的订单行;若缺少关键字段则返回 None。
"""
if not isinstance(raw, dict):
return None
@@ -517,6 +535,16 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
"""
批量标准化订单行列表。
核心逻辑:逐行调用 `normalize_notice_line`,自动过滤掉无效、缺 SKU 或缺数量的脏数据。
Args:
lines: 原始订单行列表。
Returns:
list[dict[str, Any]]: 标准化后的有效订单行集合。
"""
if not isinstance(lines, list):
return []
normalized: list[dict[str, Any]] = []
@@ -532,7 +560,17 @@ def enrich_notice_with_document_reservation(
*,
raw_text: str = "",
) -> dict[str, Any]:
"""Apply document-level PR Number / @1000140351 reservation id to lines missing it."""
"""
用文档级 Reservation ID 回填缺失的订单行。
核心逻辑:优先从 parsed 字段中找 document-level Reservation ID,找不到再从原始文本中兜底提取。
Args:
parsed: 已解析出的发货通知结构。
raw_text: 原始发货通知文本,用于补充文档级 Reservation ID。
Returns:
dict[str, Any]: 已完成文档级 Reservation ID 回填的解析结果。
"""
doc_rid = ""
for key in (
"reservation_id",
@@ -569,7 +607,16 @@ def enrich_notice_with_document_reservation(
def enrich_notice_with_document_required_date(parsed: dict[str, Any]) -> dict[str, Any]:
"""Apply document-level required_date to lines missing their own delivery date."""
"""
用文档级 required_date 回填缺失的订单行交期。
核心逻辑:统一格式化文档级日期,并在订单行未给出独立交期时逐行补齐。
Args:
parsed: 已解析出的发货通知结构。
Returns:
dict[str, Any]: 已完成文档级交期回填的解析结果。
"""
doc_date = _normalize_required_date(
parsed.get("required_date") or parsed.get("document_required_date")
)
@@ -597,7 +644,16 @@ def enrich_notice_with_document_required_date(parsed: dict[str, Any]) -> dict[st
def enrich_notice_with_document_currency(parsed: dict[str, Any]) -> dict[str, Any]:
"""Apply document-level currency to lines missing their own currency."""
"""
用文档级币种回填缺失的订单行币种。
核心逻辑:统一币种代码,并在订单行未给出币种时沿用文档级币种。
Args:
parsed: 已解析出的发货通知结构。
Returns:
dict[str, Any]: 已完成文档级币种回填的解析结果。
"""
doc_currency = _normalize_currency(
parsed.get("currency") or parsed.get("document_currency")
)
@@ -625,6 +681,16 @@ def enrich_notice_with_document_currency(parsed: dict[str, Any]) -> dict[str, An
def parse_notice_table_text(raw_text: str) -> list[dict[str, Any]]:
"""
从发货通知原始文本中的表格片段解析订单行。
核心逻辑:先借助 inventory_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。
Args:
raw_text: 原始发货通知文本,通常来自 PDF/OCR/邮件正文。
Returns:
list[dict[str, Any]]: 解析出的订单行列表。
"""
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
text = str(raw_text or "").strip()
@@ -678,6 +744,17 @@ def _find_notice_header_row_index(rows: list[list[Any]], *, max_scan: int = 40)
def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> list[dict[str, Any]]:
"""
按表头定义解析发货通知表格数据行。
核心逻辑:根据 headers 推断列映射,仅在识别到有效表头时逐行提取 SKU、数量、金额等字段。
Args:
headers: 表头行。
data_rows: 表头之后的数据行集合。
Returns:
list[dict[str, Any]]: 解析后的订单行列表。
"""
columns = _resolve_notice_columns(headers)
has_header = columns.get("sku") is not None or columns.get("qty") is not None
if not has_header and headers:
@@ -696,6 +773,16 @@ def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> l
def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
"""
生成订单行解析质量告警。
核心逻辑:检查 Reservation ID、价格字段等关键完整性,输出给前端/Agent 的提醒文本。
Args:
lines: 已标准化的订单行列表。
Returns:
list[str]: 告警文案列表,为空表示未发现明显问题。
"""
warnings: list[str] = []
if not lines:
warnings.append("未解析到有效订单行(需至少包含 SKU 与需求数量)。")
@@ -733,7 +820,16 @@ def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
def notice_parse_completeness(lines: list[dict[str, Any]]) -> float:
"""0~1 score for how complete order lines are (sku/qty/reservation/price)."""
"""
评估订单行解析完整度。
核心逻辑:按 SKU、数量、Reservation ID、价格等字段覆盖率计算 0~1 分数。
Args:
lines: 已标准化的订单行列表。
Returns:
float: 0~1 之间的解析完整度分数。
"""
if not lines:
return 0.0
scores: list[float] = []
@@ -1,3 +1,11 @@
"""
services/shipping_notice/notice_upload.py
用途:管理发货通知附件上传、文本抽取、OCR/文档解析与文件落盘。
依赖:edkb_system 的 PDF/Docx/CSV/OCR 技能、export._storage_root、Flask current_app 配置。
逻辑:由 workspace_shipping_notice 和 task_workflow 上游入口调用本文件,把原始附件转成可解析文本后交给 extract/task_workflow。
"""
from __future__ import annotations
import base64
@@ -1,3 +1,11 @@
"""
services/shipping_notice/openapi_spec.py
用途:构建发货通知 Tool API 的 OpenAPI 描述,供 Dify 导入和联调用。
依赖:shipping_notice.constants 中的请求字段常量、标准 `typing` 类型。
逻辑:由 api/shipping_notice_tools.py 调用本文件生成 JSON/YAML OpenAPI 文档,再暴露给 Dify 或开发工具。
"""
from __future__ import annotations
from typing import Any
@@ -64,6 +72,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
server = f"{server}/api/shipping-notice" if server else "/api/shipping-notice"
task_id = _str_prop("发货任务编号(task id),如 SN-20260529-ABCD1234")
batch_id = _str_prop("发货批次编号(batch id),如 SB-20260617-ABCD1234")
return {
"openapi": "3.0.0",
@@ -74,14 +83,29 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
"servers": [{"url": server}],
"paths": {
"/tools/create_batch": _post_op(
"create_batch",
"创建发货批次 batch(一次多文件上传的聚合容器)",
{
"batch_no": _str_prop("已存在的批次编号(可选)。传入时将直接复用该批次。"),
"user_id": _int_prop("Hxops 用户 ID(可选)"),
"conversation_id": _str_prop("Dify 会话 ID,便于工作台关联"),
"file_count": _int_prop("本批通知文件数量"),
},
),
"/tools/create_task": _post_op(
"create_task",
"创建发货任务 task",
"创建发货任务 task(可挂到某个 batch)",
{
"batch_no": batch_id,
"task_id": _str_prop("已存在的发货任务编号(可选)。传入时将直接复用该任务,禁止重复创建。"),
"user_id": _int_prop("Hxops 用户 ID(可选)"),
"conversation_id": _str_prop("Dify 会话 ID,便于工作台关联"),
"source_type": _str_prop("来源:manual|email|wecom|pdf", enum=["manual", "email", "wecom", "pdf"]),
"source_file_name": _str_prop("原始通知文件名(多文件场景建议传)"),
"source_file_type": _str_prop("原始通知文件类型(多文件场景建议传)"),
"batch_index": _int_prop("当前任务在批次中的顺序,从 1 开始"),
"batch_total": _int_prop("当前批次总任务数"),
"raw_content": _str_prop("原始发货通知文本(可选,后续 parse 也可传入)"),
},
),
@@ -94,6 +118,59 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
required=["task_id"],
),
"/tools/update_notice_fields": _post_op(
"update_notice_fields",
"更新解析后的发货通知单头字段,如客户、PO、交期、收货地",
{
"task_id": task_id,
"fields": {
"type": "object",
"description": "可更新字段:customer_name/customer_code/ship_to/po_number/required_date",
"additionalProperties": True,
},
"comment": _str_prop("修改备注(可选)"),
},
required=["task_id", "fields"],
),
"/tools/update_notice_line": _post_op(
"update_notice_line",
"更新解析结果中的某一行,如 SKU、Reservation ID、数量、交期",
{
"task_id": task_id,
"line_index": _int_prop("行下标,从 0 开始"),
"patch": {
"type": "object",
"description": "可更新字段:sku/reservation_id/quantity/qty/required_date/uom",
"additionalProperties": True,
},
"comment": _str_prop("修改备注(可选)"),
},
required=["task_id", "line_index", "patch"],
),
"/tools/add_notice_line": _post_op(
"add_notice_line",
"向解析结果新增一行发货需求",
{
"task_id": task_id,
"line": {
"type": "object",
"description": "新增行,至少包含 sku 和 qty/quantity",
"additionalProperties": True,
},
"comment": _str_prop("修改备注(可选)"),
},
required=["task_id", "line"],
),
"/tools/remove_notice_line": _post_op(
"remove_notice_line",
"删除解析结果中的某一行发货需求",
{
"task_id": task_id,
"line_index": _int_prop("行下标,从 0 开始"),
"comment": _str_prop("修改备注(可选)"),
},
required=["task_id", "line_index"],
),
"/tools/parse_inventory": _post_op(
"parse_inventory",
"解析库存。大 Excel 禁止 raw_inventory_text(会超 LLM token);"
@@ -216,5 +293,23 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"conversation_id": _str_prop("Dify 会话 ID"),
},
),
"/tools/get_batch_status": _post_op(
"get_batch_status",
"查询批次当前状态、任务列表与当前聚焦任务",
{
"batch_no": batch_id,
},
required=["batch_no"],
),
"/tools/switch_focus_task": _post_op(
"switch_focus_task",
"切换当前批次的聚焦任务",
{
"batch_no": batch_id,
"task_no": task_id,
"target_task_no": task_id,
},
required=["batch_no"],
),
},
}
@@ -1,3 +1,11 @@
"""
services/shipping_notice/parse_summary.py
用途:把发货通知解析结果格式化成适合聊天区展示的摘要文本。
依赖:shipping_notice.i18n 中的语言解析与文案函数、订单行格式化辅助函数。
逻辑:由 task_workflow.parse_notice 在解析完成后调用本文件,向前端或 Agent 返回可直接展示的解析总结。
"""
from __future__ import annotations
from typing import Any
@@ -1,3 +1,11 @@
"""
services/shipping_notice/po_number.py
用途:提取、标准化并回填发货通知中的采购单号。
依赖:正则表达式与标准 `typing` 工具。
逻辑:由 extract.py 在发货通知解析收尾阶段调用本文件,把文档级 PO Number 写回解析结果。
"""
from __future__ import annotations
import re
@@ -0,0 +1,136 @@
"""
services/shipping_notice/progress_workflow.py
用途:承接发货通知任务的自动推进流程,包括解析确认检查、库存准备、字段映射确认与履约侧串联。
依赖:tool_common、query_service、inventory_mapping_workflow、inventory_workflow、fulfillment_workflow、tool_response。
逻辑:由 task_workflow 对外转调本文件;本文件按当前任务状态决定继续自动推进、停在人审检查点,或进入履约 workflow。
"""
from __future__ import annotations
from typing import Any
from flask import current_app
from app.services.shipping_notice import fulfillment_workflow
from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_LOW_CONF, RS_PARSE_REVIEW
from app.services.shipping_notice.inventory_mapping_workflow import (
awaiting_inventory_mapping_confirm,
inventory_mapping_checkpoint_response,
maybe_auto_confirm_inventory_mapping,
)
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool
from app.services.shipping_notice.state_machine import resolve_task_ui_state
from app.services.shipping_notice.tool_common import auto_progress_enabled, auto_rpa_inventory_enabled
from app.services.shipping_notice.tool_response import tool_response
def auto_progress(payload: dict[str, Any]) -> dict[str, Any]:
"""
按任务当前状态自动串联解析确认、库存准备、字段映射与履约动作。
【AI 触发时机】:当用户要求“继续处理”“自动推进”“下一步全自动跑完能跑的步骤”时调用。
核心逻辑:先检查解析是否需要人工确认,再保证库存已就绪、字段映射已确认,最后委托 fulfillment workflow 继续推进。
Args:
payload: 必须能定位任务;可额外携带 lang/locale/language 以及 auto-chain 控制参数。
Returns:
dict[str, Any]: Tool 标准响应,返回自动推进后的阶段、提示和数据。
"""
if not auto_progress_enabled():
return tool_response(status="failed", message="auto_progress 未启用")
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
steps: list[str] = []
# [STEP 1] 先判断解析结果是否允许进入自动链路。
# 解析待确认或低置信度时必须立即停下,避免 Agent 在错误数据上继续做库存/出货操作。
threshold = current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD")
try:
threshold = float(threshold) if threshold is not None else 0.7
except (TypeError, ValueError):
threshold = 0.7
confidence = None
try:
confidence = float(task.parse_confidence) if task.parse_confidence is not None else None
except (TypeError, ValueError):
confidence = None
if task.review_status == RS_PARSE_REVIEW or task.pending_human_reason == PH_LOW_CONF:
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message="发货通知解析需要人工确认后才能自动推进。",
data=serialize_task_for_tool(task),
human_options=ui.human_options,
checkpoint=ui.checkpoint,
stop_agent_turn=True,
)
if confidence is not None and confidence < threshold:
ui = resolve_task_ui_state(task)
return tool_response(
status="needs_human",
task=task,
message=f"解析置信度 {confidence:.2f} 低于阈值 {threshold:.2f},请人工确认后再自动推进。",
data=serialize_task_for_tool(task),
human_options=ui.human_options,
checkpoint=ui.checkpoint,
stop_agent_turn=True,
)
# [STEP 2] 保证库存已经就绪。
# 若库存还没导入,则根据配置决定触发 RPA 拉取,或明确提示人工上传 Excel。
if not task.inventory_lines_json:
if not auto_rpa_inventory_enabled():
return tool_response(
status="needs_human",
task=task,
message="未开启自动 RPA 获取库存。请手动上传货代库存 Excel。",
data=serialize_task_for_tool(task),
checkpoint=CP_UPLOAD_REQ,
stop_agent_turn=True,
)
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
inv_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
if lang:
inv_payload["lang"] = lang
inv = ensure_inventory(inv_payload)
if inv.get("status") == "running":
steps.append("触发 RPA 库存导出")
return inv
if inv.get("status") != "ok":
if maybe_auto_confirm_inventory_mapping(task):
steps.append("自动确认字段对齐")
else:
return inv
else:
steps.append("载入库存")
# [STEP 3] 尝试自动完成字段映射确认。
# 当系统已经拿到足够可靠的列映射时,直接确认可减少一次人工往返。
if maybe_auto_confirm_inventory_mapping(task):
steps.append("自动确认字段对齐")
# [STEP 4] 如果映射仍需人工确认,则停在检查点,把确认动作交还给用户或 Agent。
if awaiting_inventory_mapping_confirm(task):
lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip()
return inventory_mapping_checkpoint_response(task, lang=lang or None)
# [STEP 5] 库存与映射都就绪后,再进入履约侧自动推进。
# 匹配、生成 Excel、上传货代等步骤统一交给 fulfillment workflow 处理,避免本文件继续膨胀。
fulfillment_result = fulfillment_workflow.run_auto_progress_fulfillment_steps(task, payload, steps)
if fulfillment_result is not None:
return fulfillment_result
suffix = f":{' → '.join(steps)}" if steps else ""
return tool_response(
status="ok",
task=task,
message=f"自动推进已完成{suffix}",
data=serialize_task_for_tool(task),
)
@@ -1,63 +1,365 @@
"""
services/shipping_notice/query_service.py
用途:发货通知读模型 — 任务/批次查询、排序与序列化投影。
依赖:models.ShippingBatch、ShippingTask、ShippingTaskEvent。
逻辑:workspace_shipping_notice 与 shipping_notice_tools 的读路径统一经本模块;
tools.py 通过 TaskProjection / BatchProjection 委托序列化与任务解析,写路径逐步下沉。
"""
from __future__ import annotations
import re
from enum import Enum
from pathlib import Path
from typing import Any
from sqlalchemy import desc
from app.models import ShippingTask, ShippingTaskEvent
from app import db
from app.models import ShippingBatch, ShippingTask
EXPORT_MIME_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
_TASK_NO_RE = re.compile(r"SN-\d{8}-[A-F0-9]{8}", re.IGNORECASE)
def serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
class TaskProjection(str, Enum):
"""任务读模型投影:Tool / 工作台列表 / 工作台详情。"""
TOOL = "tool"
TOOL_INTERNAL = "tool_internal"
SUMMARY = "summary"
DETAIL = "detail"
class BatchProjection(str, Enum):
"""批次读模型投影:工作台全量 / Tool 精简。"""
SUMMARY = "summary"
TOOL = "tool"
def _task_batch_no(task: ShippingTask) -> str | None:
if task.batch is not None and task.batch.batch_no:
return task.batch.batch_no
return None
def task_sort_key(task: ShippingTask) -> tuple[int, str]:
"""批次内任务排序键:batch_index 优先,其次 created_at。"""
return (
task.batch_index if task.batch_index is not None else 10**9,
task.created_at.isoformat() if task.created_at else "",
)
def sort_batch_tasks(tasks: list[ShippingTask]) -> list[ShippingTask]:
"""按 batch_index、created_at 对批次任务列表排序(返回新列表)。"""
return sorted(tasks, key=task_sort_key)
def get_task_by_ref(task_ref: str) -> ShippingTask | None:
"""按 task_no 或数字主键查找任务(Tool API / 内部引用解析)。"""
value = str(task_ref or "").strip()
if not value:
return None
task = ShippingTask.query.filter_by(task_no=value).first()
if task:
return task
if value.isdigit():
return db.session.get(ShippingTask, int(value))
return None
def get_batch_by_no(batch_no: str) -> ShippingBatch | None:
"""按 batch_no 查找批次(不做用户权限校验)。"""
value = str(batch_no or "").strip()
if not value:
return None
return ShippingBatch.query.filter_by(batch_no=value).first()
def get_task_in_batch(batch_no: str, task_no: str) -> ShippingTask | None:
"""查找属于指定批次的任务;批次不存在或任务不在批次内时返回 None。"""
batch = get_batch_by_no(batch_no)
if not batch:
return None
task = get_task_by_ref(task_no)
if not task or task.batch_id != batch.id:
return None
return task
def resolve_task_export_download(task: ShippingTask | None) -> tuple[Path, str] | None:
"""解析任务导出文件路径;文件不存在或路径无效时返回 None。"""
if not task or not task.export_file_path:
return None
path = Path(task.export_file_path)
if not path.is_file():
return None
return path, task.export_file_name or path.name
def task_export_error_message(task: ShippingTask | None) -> str:
"""导出下载失败时的错误文案(与 Tool / Workspace API 保持一致)。"""
if not task or not task.export_file_path:
return "export file not found"
path = Path(task.export_file_path)
if not path.is_file():
return "export file missing on disk"
return ""
def list_sorted_batch_tasks(batch: ShippingBatch) -> list[ShippingTask]:
"""返回批次下已排序的任务 ORM 列表。"""
return sort_batch_tasks(list(batch.tasks or []))
def list_batch_task_summaries(batch: ShippingBatch) -> list[dict[str, Any]]:
"""返回批次下已排序任务的摘要投影列表。"""
return [serialize_task(item, TaskProjection.SUMMARY) for item in list_sorted_batch_tasks(batch)]
def compute_batch_process_summary(tasks: list[ShippingTask]) -> dict[str, int]:
"""批次进度汇总(Tool / 工作台 / 写回 batch.process_summary_json 共用公式)。"""
total = len(tasks)
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"})
return {
"total": total,
"completed": completed,
"failed": failed,
"running": running,
}
def extract_task_no_from_text(text: str) -> str | None:
"""从自然语言文本中提取 SN- 任务编号。"""
match = _TASK_NO_RE.search(str(text or ""))
return match.group(0).upper() if match else None
def resolve_task_from_payload(payload: dict[str, Any]) -> ShippingTask | None:
"""按 task_id/task_no、文本内嵌 SN- 或 conversation_id 解析任务(只读)。"""
if not isinstance(payload, dict):
return None
for key in ("task_id", "task_no"):
task = get_task_by_ref(str(payload.get(key) or ""))
if task:
return task
for key in ("comment", "user_message", "raw_text", "query"):
hint = extract_task_no_from_text(str(payload.get(key) or ""))
if hint:
task = get_task_by_ref(hint)
if task:
return task
conv_id = str(payload.get("conversation_id") or "").strip()
if conv_id:
return (
ShippingTask.query.filter_by(conversation_id=conv_id)
.filter(ShippingTask.process_status.notin_(["rejected"]))
.order_by(ShippingTask.id.desc())
.first()
)
return None
def _task_tool_payload(task: ShippingTask) -> dict[str, Any]:
"""Tool data 基础字段(裁剪前)。"""
return {
"id": task.id,
"task_no": task.task_no,
"source_type": task.source_type,
"customer_name": task.customer_name,
"process_status": task.process_status,
"review_status": task.review_status,
"match_status": task.match_status,
"pending_human_reason": task.pending_human_reason,
"conversation_id": task.conversation_id,
"export_file_name": task.export_file_name,
"freight_ref_no": task.freight_ref_no,
"created_at": task.created_at.isoformat() if task.created_at else None,
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
}
def serialize_task_detail(task: ShippingTask) -> dict[str, Any]:
data = serialize_task_summary(task)
data.update({
"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 [],
"shortage": task.shortage_json,
"line_results": task.line_results_json or [],
"parse_confidence": task.parse_confidence,
"line_results": task.line_results_json,
"export_file_name": task.export_file_name,
"freight_ref_no": task.freight_ref_no,
"error_message": task.error_message,
"events": [
{
"event_type": e.event_type,
"detail_json": e.detail_json,
"created_at": e.created_at.isoformat() if e.created_at else None,
}
for e in sorted(task.events or [], key=lambda x: x.created_at or "")
],
})
return data
"conversation_id": task.conversation_id,
}
def serialize_task(task: ShippingTask, projection: TaskProjection) -> dict[str, Any]:
"""按投影类型序列化任务;TOOL 会剔除 Agent 不应复述的内部状态码。"""
if projection == TaskProjection.TOOL:
from app.services.shipping_notice.user_facing_status import strip_internal_task_fields
return strip_internal_task_fields(_task_tool_payload(task))
if projection == TaskProjection.TOOL_INTERNAL:
return _task_tool_payload(task)
if projection == TaskProjection.SUMMARY:
return {
"id": task.id,
"task_no": task.task_no,
"batch_no": _task_batch_no(task),
"source_type": task.source_type,
"source_file_name": task.source_file_name,
"source_file_type": task.source_file_type,
"batch_index": task.batch_index,
"batch_total": task.batch_total,
"customer_name": task.customer_name,
"current_step": task.current_step,
"process_status": task.process_status,
"review_status": task.review_status,
"match_status": task.match_status,
"upload_status": task.upload_status,
"upload_mode": task.upload_mode,
"upload_attempt": task.upload_attempt,
"pending_human_reason": task.pending_human_reason,
"conversation_id": task.conversation_id,
"export_file_name": task.export_file_name,
"freight_ref_no": task.freight_ref_no,
"created_at": task.created_at.isoformat() if task.created_at else None,
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
}
if projection == TaskProjection.DETAIL:
data = serialize_task(task, TaskProjection.SUMMARY)
data.update({
"customer_code": task.customer_code,
"ship_to": task.ship_to,
"po_number": task.po_number,
"required_date": task.required_date,
"step_payload": task.step_payload_json or {},
"upload_receipt": task.upload_receipt_json or {},
"export_version": task.export_version,
"idempotency_key": task.idempotency_key,
"lines": task.lines_json or [],
"shortage": task.shortage_json,
"line_results": task.line_results_json or [],
"parse_confidence": task.parse_confidence,
"error_message": task.error_message,
"events": [
{
"event_type": e.event_type,
"detail_json": e.detail_json,
"created_at": e.created_at.isoformat() if e.created_at else None,
}
for e in sorted(task.events or [], key=lambda x: x.created_at or "")
],
})
return data
raise ValueError(f"unsupported task projection: {projection}")
def serialize_task_for_tool(task: ShippingTask) -> dict[str, Any]:
"""Dify Tool `data` 投影(剔除内部状态码)。"""
return serialize_task(task, TaskProjection.TOOL)
def serialize_batch(batch: ShippingBatch, projection: BatchProjection) -> dict[str, Any]:
"""按投影类型序列化批次。"""
if projection == BatchProjection.SUMMARY:
return serialize_batch_summary(batch)
if projection == BatchProjection.TOOL:
data = serialize_batch_summary(batch)
return {
"batch_no": data["batch_no"],
"conversation_id": data["conversation_id"],
"current_focus_task_no": data["current_focus_task_no"],
"file_count": data["file_count"],
"process_summary": data["process_summary"],
}
raise ValueError(f"unsupported batch projection: {projection}")
def serialize_batch_for_tool(batch: ShippingBatch | None) -> dict[str, Any] | None:
"""Tool 批次 data 投影。"""
if not batch:
return None
return serialize_batch(batch, BatchProjection.TOOL)
def serialize_batch_summary(batch: ShippingBatch) -> dict[str, Any]:
tasks = list(batch.tasks or [])
return {
"id": batch.id,
"batch_no": batch.batch_no,
"conversation_id": batch.conversation_id,
"current_focus_task_no": batch.current_focus_task_no,
"file_count": batch.file_count,
"process_summary": batch.process_summary_json or compute_batch_process_summary(tasks),
"created_at": batch.created_at.isoformat() if batch.created_at else None,
"updated_at": batch.updated_at.isoformat() if batch.updated_at else None,
}
def serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
return serialize_task(task, TaskProjection.SUMMARY)
def serialize_task_detail(task: ShippingTask) -> dict[str, Any]:
return serialize_task(task, TaskProjection.DETAIL)
def get_batch_for_user(batch_no: str, user_id: int) -> ShippingBatch | None:
batch = get_batch_by_no(batch_no)
if not batch:
return None
if batch.user_id is not None and batch.user_id != user_id:
return None
return batch
def list_batches_for_user(
user_id: int,
*,
limit: int = 100,
) -> list[dict[str, Any]]:
q = ShippingBatch.query.filter(
(ShippingBatch.user_id == user_id) | (ShippingBatch.user_id.is_(None))
)
rows = q.order_by(desc(ShippingBatch.created_at)).limit(max(1, min(limit, 500))).all()
return [serialize_batch_summary(item) for item in rows]
def list_tasks_for_batch(batch_no: str, user_id: int) -> list[dict[str, Any]]:
batch = get_batch_for_user(batch_no, user_id)
if not batch:
return []
return list_batch_task_summaries(batch)
def get_focus_task_for_batch(batch_no: str, user_id: int) -> ShippingTask | None:
batch = get_batch_for_user(batch_no, user_id)
if not batch:
return None
focus_task_no = str(batch.current_focus_task_no or "").strip()
if focus_task_no:
task = get_task_by_ref(focus_task_no)
if task and task.batch_id == batch.id:
return task
tasks = list_sorted_batch_tasks(batch)
return tasks[0] if tasks else None
def list_tasks_for_user(
user_id: int,
*,
batch_no: str | None = None,
process_status: str | None = None,
limit: int = 100,
) -> list[dict[str, Any]]:
q = ShippingTask.query.filter(
(ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None))
)
if batch_no:
batch = get_batch_for_user(batch_no, user_id)
if not batch:
return []
q = q.filter(ShippingTask.batch_id == batch.id)
if process_status:
q = q.filter(ShippingTask.process_status == process_status)
rows = q.order_by(desc(ShippingTask.created_at)).limit(max(1, min(limit, 500))).all()
@@ -65,7 +367,7 @@ def list_tasks_for_user(
def get_task_for_user(task_no: str, user_id: int) -> ShippingTask | None:
task = ShippingTask.query.filter_by(task_no=task_no).first()
task = get_task_by_ref(task_no)
if not task:
return None
if task.user_id is not None and task.user_id != user_id:
@@ -1,3 +1,11 @@
"""
services/shipping_notice/reservation_id.py
用途:提取、标准化并识别发货通知与库存中的 Reservation ID。
依赖:正则表达式与标准 `typing` 工具。
逻辑:由 notice_lines、inventory_snapshot、match、extract 等多个解析/匹配模块复用本文件完成 Reservation ID 归一化。
"""
from __future__ import annotations
import re
@@ -1,3 +1,11 @@
"""
services/shipping_notice/rpa.py
用途:管理库存导出与货代上传相关的 RPA 目录、触发文件和落盘辅助逻辑。
依赖:Flask current_app 配置、Path/JSON/文件系统工具。
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等上游模块调用本文件,与外部 RPA 文件投递目录进行交互。
"""
from __future__ import annotations
import json
@@ -1,3 +1,11 @@
"""
services/shipping_notice/rpa_attempts.py
用途:统计任务的 RPA 库存导出与货代上传重试次数,并给出默认上限。
依赖:ShippingTask、ShippingTaskEvent 模型与事件查询逻辑。
逻辑:由 inventory_rpa_workflow、fulfillment_workflow 等模块调用本文件,决定是否还能继续触发 RPA 重试。
"""
from __future__ import annotations
import os
@@ -122,7 +122,7 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
CP_RSV_REQ: ("reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"),
RS_SHORTAGE_REVIEW: ("confirm", "reject", "rematch"),
RS_SHORTAGE_REVIEW: ("reparse_inventory", "correct_inventory_mapping", "rematch", "reject"),
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("reparse", "reject"),
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"),
@@ -403,7 +403,6 @@ class TaskTransition(StrEnum):
MATCH_SHORTAGE = "match_shortage"
REJECTED = "rejected"
CLOSED = "closed"
CONFIRM_SHORTAGE = "confirm_shortage"
CONFIRM_PARSE = "confirm_parse"
CONFIRM_MATCHED = "confirm_matched"
ALIGN_REVIEW_HOLD = "align_review_hold"
@@ -486,11 +485,6 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
pending_human_reason=None,
clear_error_message=True,
),
TaskTransition.CONFIRM_SHORTAGE: _TransitionSpec(
process_status="matched",
review_status=RS_CONFIRMED,
pending_human_reason=None,
),
TaskTransition.CONFIRM_PARSE: _TransitionSpec(
process_status="parsed",
review_status=None,
@@ -0,0 +1,690 @@
"""
services/shipping_notice/task_workflow.py
用途:发货通知任务/批次生命周期、解析与单头/订单行编辑的主编排入口。
依赖:query_service、tool_common、decision_workflow、progress_workflow、state_machine。
逻辑:tools.py 门面委托本模块;人工决策与自动推进分支已下沉到独立 workflow,本文件保留核心任务创建、解析和编辑入口。
"""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any
from app import db
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.constants import (
CP_PARSE_OK,
CP_TASK_EXISTS,
RS_PARSE_REVIEW,
)
from app.services.shipping_notice.decision_workflow import submit_decision
from app.services.shipping_notice.extract import extract_notice_fields
from app.services.shipping_notice.notice_lines import normalize_notice_lines
from app.services.shipping_notice.parse_summary import format_parse_summary
from app.services.shipping_notice.progress_workflow import auto_progress
from app.services.shipping_notice.query_service import (
TaskProjection,
compute_batch_process_summary,
extract_task_no_from_text,
get_task_by_ref,
list_sorted_batch_tasks,
resolve_task_from_payload,
serialize_batch_for_tool,
serialize_task as qs_serialize_task,
serialize_task_for_tool,
)
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
from app.services.shipping_notice.tool_response import tool_response
from app.services.shipping_notice.user_facing_status import user_facing_task_stage
from app.services.shipping_notice.inventory_workflow import ensure_inventory
from app.services.shipping_notice.tool_common import (
generate_task_no,
log_task_event,
)
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 recompute_batch_summary(batch: ShippingBatch | None) -> None:
"""写路径:重算批次汇总并校正 current_focus_task_no。"""
if not batch:
return
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)
if not batch.current_focus_task_no:
batch.current_focus_task_no = tasks[0].task_no if tasks else None
return
focus_task = next((item for item in tasks if item.task_no == batch.current_focus_task_no), None)
if focus_task is None and tasks:
batch.current_focus_task_no = tasks[0].task_no
def sync_batch_after_task_change(task: ShippingTask | None) -> None:
if not task or not task.batch:
return
recompute_batch_summary(task.batch)
def create_batch(payload: dict[str, Any]) -> ShippingBatch:
"""
创建或复用发货批次壳(不含 notice 解析)。
【AI 触发时机】:当用户一次上传多份发货通知、需要归并到同一批次时调用。
核心逻辑:优先复用已有 `batch_no`,否则生成新的批次号并初始化批次汇总字段。
Args:
payload: 可包含 batch_no、user_id、conversation_id、file_count 等批次创建参数。
Returns:
ShippingBatch: 已存在或新建但尚未提交事务的批次对象。
"""
batch_no = str(payload.get("batch_no") or "").strip()
if batch_no:
existing = ShippingBatch.query.filter_by(batch_no=batch_no).first()
if existing:
return existing
try:
file_count = max(1, int(payload.get("file_count") or 1))
except (TypeError, ValueError):
file_count = 1
batch = ShippingBatch(
batch_no=f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}",
user_id=payload.get("user_id"),
conversation_id=str(payload.get("conversation_id") or "").strip() or None,
file_count=file_count,
process_summary_json={"total": 0, "completed": 0, "failed": 0, "running": 0},
)
db.session.add(batch)
db.session.flush()
return batch
def create_batch_tasks(payload: dict[str, Any]) -> dict[str, Any]:
"""
一次创建批次,并为每个 notice_item 创建任务后立即触发解析。
【AI 触发时机】:当用户批量上传多份发货通知附件,希望系统自动拆成多个任务时调用。
核心逻辑:先创建批次,再逐个创建任务、透传 notice 原文到 `parse_notice`,最后回写批次汇总。
Args:
payload: 包含 user_id、conversation_id、notice_items、file_count 等批量建单数据。
Returns:
dict[str, Any]: Tool 标准响应,包含批次摘要和每个任务的解析状态。
"""
notice_items = payload.get("notice_items")
if not isinstance(notice_items, list) or not notice_items:
batch = create_batch(payload)
db.session.commit()
return {
"status": "ok",
"batch_no": batch.batch_no,
"message": f"已创建批次 {batch.batch_no}",
"data": {
"batch": serialize_batch_for_tool(batch),
"tasks": [],
},
}
batch = create_batch({**payload, "file_count": len(notice_items)})
db.session.flush()
created_tasks: list[dict[str, Any]] = []
total = len(notice_items)
for idx, item in enumerate(notice_items, start=1):
if not isinstance(item, dict):
continue
task = ShippingTask(
task_no=generate_task_no(),
batch_id=batch.id,
user_id=payload.get("user_id"),
conversation_id=str(payload.get("conversation_id") or "").strip() or None,
source_type=str(item.get("source_type") or "manual"),
source_file_name=str(item.get("source_file_name") or "").strip() or None,
source_file_type=item.get("source_file_type"),
batch_index=idx,
batch_total=total,
raw_content=str(item.get("raw_text") or "").strip() or None,
process_status="created",
)
db.session.add(task)
log_task_event(task, "task_created", {"source_type": task.source_type, "batch_no": batch.batch_no})
db.session.flush()
parse_payload: dict[str, Any] = {
"task_id": task.task_no,
"user_id": payload.get("user_id"),
"conversation_id": payload.get("conversation_id"),
"raw_text": item.get("raw_text"),
"structured": item.get("structured"),
}
warnings = item.get("warnings")
if isinstance(warnings, list):
parse_payload["warnings"] = warnings
parse_result = parse_notice(parse_payload)
created_tasks.append(
{
"task_id": task.task_no,
"batch_index": idx,
"parse_status": parse_result.get("status"),
}
)
recompute_batch_summary(batch)
db.session.commit()
return {
"status": "ok",
"batch_no": batch.batch_no,
"message": f"已创建批次 {batch.batch_no},共 {len(created_tasks)} 个任务",
"data": {
"batch": serialize_batch_for_tool(batch),
"tasks": created_tasks,
},
}
def create_task(payload: dict[str, Any]) -> dict[str, Any]:
"""
创建单个发货任务,或复用当前会话里已存在的进行中任务。
【AI 触发时机】:当用户首次发起一张新的发货通知处理请求时调用;若用户只是确认/驳回,禁止重复调用。
核心逻辑:优先从 payload 文本里识别已有任务号,其次按 conversation_id 复用未结束任务,兜底才真正建单。
Args:
payload: 可包含 conversation_id、task_id、task_no、source_type、raw_content 等建单线索。
Returns:
dict[str, Any]: Tool 标准响应,返回复用或新建后的任务摘要。
"""
conv_id = str(payload.get("conversation_id") or "").strip()
hinted_task_no = extract_task_no_from_text(
str(
payload.get("task_id")
or payload.get("task_no")
or payload.get("raw_content")
or payload.get("user_message")
or payload.get("query")
or payload.get("comment")
or ""
)
)
if hinted_task_no:
existing_by_no = get_task_by_ref(hinted_task_no)
if existing_by_no:
if conv_id and not existing_by_no.conversation_id:
existing_by_no.conversation_id = conv_id
db.session.commit()
return tool_response(
status="ok",
task_id=existing_by_no.task_no,
message=f"已找到发货任务 {existing_by_no.task_no},将继续处理该任务。",
data=qs_serialize_task(existing_by_no, TaskProjection.TOOL_INTERNAL),
checkpoint=CP_TASK_EXISTS,
)
if conv_id:
terminal_statuses = {"uploaded", "rejected", "closed"}
existing = (
ShippingTask.query.filter_by(conversation_id=conv_id)
.filter(ShippingTask.process_status.notin_(list(terminal_statuses)))
.order_by(ShippingTask.id.desc())
.first()
)
if existing:
return tool_response(
status="ok",
task_id=existing.task_no,
message=(
f"当前会话已有进行中的发货任务 {existing.task_no},请勿重复 create_task。"
"用户确认/驳回时请 submit_decision,并带上任务编号或 conversation_id。"
),
data=qs_serialize_task(existing, TaskProjection.TOOL_INTERNAL),
checkpoint=CP_TASK_EXISTS,
)
task = ShippingTask(
task_no=generate_task_no(),
user_id=payload.get("user_id"),
conversation_id=str(payload.get("conversation_id") or "").strip() or None,
source_type=str(payload.get("source_type") or "manual"),
raw_content=str(payload.get("raw_content") or "").strip() or None,
process_status="created",
)
db.session.add(task)
log_task_event(task, "task_created", {"source_type": task.source_type})
db.session.commit()
return tool_response(
status="ok",
task_id=task.task_no,
message=f"已创建发货任务 {task.task_no}",
data=serialize_task_for_tool(task),
)
def parse_notice(payload: dict[str, Any]) -> dict[str, Any]:
"""
解析发货通知正文并回写任务单头、订单行与解析状态。
【AI 触发时机】:当用户上传或粘贴发货通知文本后调用;也可用于人工更正后重新解析。
核心逻辑:解析 notice 文本/结构化输入,回填任务字段,按置信度决定自动通过、人工确认或继续库存链路。
Args:
payload: 可包含 task_id、conversation_id、raw_text、structured、notice_files、lang 等参数。
Returns:
dict[str, Any]: Tool 标准响应,包含解析摘要、warnings 与下一步动作提示。
"""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
conv_id = str(payload.get("conversation_id") or "").strip()
explicit_task_ref = bool(str(payload.get("task_id") or payload.get("task_no") or "").strip())
new_notice_payload = bool(
str(payload.get("raw_text") or "").strip()
or (isinstance(payload.get("structured"), dict) and payload.get("structured"))
or (isinstance(payload.get("notice_files"), list) and payload.get("notice_files"))
)
if (
(not explicit_task_ref)
and conv_id
and new_notice_payload
and str(task.process_status or "").strip().lower() in {"uploaded", "rejected", "closed"}
):
new_task = ShippingTask(
task_no=generate_task_no(),
user_id=payload.get("user_id"),
conversation_id=conv_id or None,
source_type=str(payload.get("source_type") or task.source_type or "manual"),
raw_content=None,
process_status="created",
)
db.session.add(new_task)
log_task_event(
new_task,
"task_created",
{"source_type": new_task.source_type, "created_from": task.task_no},
)
db.session.commit()
task = new_task
if conv_id and not task.conversation_id:
task.conversation_id = conv_id
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
notice_files = payload.get("notice_files")
if not isinstance(notice_files, list) or not all(isinstance(i, dict) for i in notice_files):
notice_files = None
parsed, confidence, warnings = extract_notice_fields(
raw_text=raw_text,
source_type=task.source_type,
structured=structured,
notice_files=notice_files,
)
task.raw_content = raw_text or task.raw_content
task.customer_name = str(parsed.get("customer_name") or "").strip() or None
task.customer_code = str(parsed.get("customer_code") or "").strip() or None
task.ship_to = str(parsed.get("ship_to") or "").strip() or None
task.po_number = str(parsed.get("po_number") or "").strip() or None
lines = parsed.get("lines") if isinstance(parsed.get("lines"), list) else []
required_date = str(parsed.get("required_date") or "").strip()
if not required_date:
for line in lines:
if isinstance(line, dict):
line_date = str(line.get("required_date") or "").strip()
if line_date:
required_date = line_date
break
task.required_date = required_date or None
task.lines_json = lines
task.parse_confidence = confidence
summary_kwargs = {
"task_no": task.task_no,
"po_number": task.po_number,
"ship_to": task.ship_to,
"customer_name": task.customer_name,
"required_date": task.required_date,
"lines": lines,
"warnings": warnings,
}
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})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=format_parse_summary(**summary_kwargs, low_confidence=True, payload=payload),
data={**serialize_task_for_tool(task), "warnings": warnings},
)
apply_task_transition(task, TaskTransition.PARSED)
log_task_event(task, "parsed", {"confidence": confidence, "warnings": warnings})
db.session.commit()
auto_threshold = float(current_app.config.get("SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE") or 0.8)
should_auto_continue = confidence >= auto_threshold and not task.inventory_lines_json
summary_text = format_parse_summary(
**summary_kwargs,
payload=payload,
include_confirmation_hint=not should_auto_continue,
)
if should_auto_continue:
lang = payload.get("lang") if isinstance(payload, dict) else None
auto_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"}
if lang:
auto_payload["lang"] = lang
auto_result = auto_progress(auto_payload) if auto_progress_enabled() else ensure_inventory(auto_payload)
msg = str(auto_result.get("message") or "").strip()
merged_message = summary_text if not msg else f"{summary_text}\n\n{msg}"
merged_data = {}
if isinstance(auto_result.get("data"), dict):
merged_data.update(auto_result["data"])
merged_data["warnings"] = warnings
db.session.refresh(task)
return tool_response(
status=str(auto_result.get("status") or "ok"),
task=task,
message=merged_message,
data=merged_data,
next_required_action=auto_result.get("next_required_action"),
forbidden_next_tools=auto_result.get("forbidden_next_tools"),
)
return tool_response(
status="ok",
task_id=task.task_no,
message=summary_text,
data={**serialize_task_for_tool(task), "warnings": warnings},
)
def _clean_notice_text(value: Any) -> str | None:
text = str(value or "").strip()
return text or None
def _notice_header_snapshot(task: ShippingTask) -> dict[str, Any]:
return {
"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,
}
def _reset_notice_edit_downstream(task: ShippingTask) -> None:
task.match_status = None
task.shortage_json = None
task.line_results_json = None
task.export_file_path = None
task.export_file_name = None
task.freight_ref_no = None
task.upload_status = None
task.upload_mode = None
task.upload_attempt = 0
task.upload_started_at = None
task.upload_finished_at = None
task.upload_error_code = None
task.upload_error_message = None
task.upload_receipt_json = None
task.idempotency_key = None
def _commit_notice_edit(
task: ShippingTask,
*,
event_type: str,
comment: str,
before_header: dict[str, Any] | None = None,
after_header: dict[str, Any] | None = None,
before_lines: list[dict[str, Any]] | None = None,
after_lines: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW)
_reset_notice_edit_downstream(task)
log_task_event(
task,
event_type,
{
"comment": comment,
"before_header": before_header,
"after_header": after_header,
"before_lines": before_lines,
"after_lines": after_lines,
},
)
sync_batch_after_task_change(task)
db.session.commit()
return tool_response(
status="ok",
task=task,
message="已更新解析结果,请重新确认。",
data=serialize_task_for_tool(task),
)
def update_notice_fields(payload: dict[str, Any]) -> dict[str, Any]:
"""
更新发货通知单头字段,并将任务重新打回解析确认阶段。
【AI 触发时机】:当用户明确要求修改客户、PO、交期等单头信息时调用。
核心逻辑:仅接受白名单字段,写入变更后清理匹配/出货下游结果,并记录审计事件。
Args:
payload: 必须包含 task_id/task_no 与 fields,可选 comment。
Returns:
dict[str, Any]: Tool 标准响应,返回更新后的任务状态。
"""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
fields = payload.get("fields")
if not isinstance(fields, dict) or not fields:
return tool_response(status="failed", task=task, message="fields 不能为空")
patch = {key: value for key, value in fields.items() if key in EDITABLE_NOTICE_FIELDS}
if not patch:
return tool_response(status="failed", task=task, message="没有可更新的单头字段")
before_header = _notice_header_snapshot(task)
changed = False
for key, value in patch.items():
normalized = _clean_notice_text(value)
if getattr(task, key) != normalized:
setattr(task, key, normalized)
changed = True
if not changed:
return tool_response(
status="ok",
task=task,
message="未检测到解析结果变化。",
data=serialize_task_for_tool(task),
)
return _commit_notice_edit(
task,
event_type="notice_fields_updated",
comment=str(payload.get("comment") or "").strip(),
before_header=before_header,
after_header=_notice_header_snapshot(task),
)
def update_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
"""
更新指定订单行,并将任务重新打回解析确认阶段。
【AI 触发时机】:当用户指出某一行的 SKU、数量、Reservation ID 或交期识别错误时调用。
核心逻辑:按 line_index 定位订单行,应用 patch 后重新走标准化校验,再清理下游匹配结果。
Args:
payload: 必须包含 task_id/task_no、line_index、patch,可选 comment。
Returns:
dict[str, Any]: Tool 标准响应,返回更新后的任务状态。
"""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
try:
line_index = int(payload.get("line_index"))
except (TypeError, ValueError):
return tool_response(status="failed", task=task, message="line_index 非法")
patch = payload.get("patch")
if not isinstance(patch, dict) or not patch:
return tool_response(status="failed", task=task, message="patch 不能为空")
lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
if line_index < 0 or line_index >= len(lines):
return tool_response(status="failed", task=task, message="line_index 超出范围")
normalized_patch = {key: value for key, value in patch.items() if key in EDITABLE_NOTICE_LINE_FIELDS}
if not normalized_patch:
return tool_response(status="failed", task=task, message="没有可更新的行字段")
before_lines = [dict(item) for item in lines]
line = dict(lines[line_index])
if "quantity" in normalized_patch and "qty" not in normalized_patch:
normalized_patch["qty"] = normalized_patch.pop("quantity")
line.update(normalized_patch)
normalized_lines = normalize_notice_lines(
[line if idx == line_index else item for idx, item in enumerate(lines)]
)
if len(normalized_lines) != len(lines):
return tool_response(
status="failed",
task=task,
message="更新后的行数据不合法,请确认 SKU 与数量格式正确。",
data=serialize_task_for_tool(task),
)
if normalized_lines == before_lines:
return tool_response(
status="ok",
task=task,
message="未检测到解析结果变化。",
data=serialize_task_for_tool(task),
)
task.lines_json = normalized_lines
return _commit_notice_edit(
task,
event_type="notice_line_updated",
comment=str(payload.get("comment") or "").strip(),
before_lines=before_lines,
after_lines=[dict(item) for item in normalized_lines],
)
def add_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
"""
向发货通知中新增一条订单行,并重置后续匹配链路。
【AI 触发时机】:当用户确认漏了一行订单、要求补录新行时调用。
核心逻辑:把新行并入现有订单行后统一做标准化,只有校验通过才提交变更并回写审计事件。
Args:
payload: 必须包含 task_id/task_no 与 line,可选 comment。
Returns:
dict[str, Any]: Tool 标准响应,返回更新后的任务状态。
"""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
line = payload.get("line")
if not isinstance(line, dict) or not line:
return tool_response(status="failed", task=task, message="line 不能为空")
before_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
normalized_lines = normalize_notice_lines(before_lines + [line])
if len(normalized_lines) != len(before_lines) + 1:
return tool_response(
status="failed",
task=task,
message="新增的订单行不合法,请确认 SKU 与数量格式正确。",
data=serialize_task_for_tool(task),
)
task.lines_json = normalized_lines
return _commit_notice_edit(
task,
event_type="notice_line_added",
comment=str(payload.get("comment") or "").strip(),
before_lines=before_lines,
after_lines=[dict(item) for item in normalized_lines],
)
def remove_notice_line(payload: dict[str, Any]) -> dict[str, Any]:
"""
删除发货通知中的指定订单行,并重置后续匹配链路。
【AI 触发时机】:当用户确认某一行是误解析、重复行或不应发货的行时调用。
核心逻辑:校验 line_index 合法性,禁止删到只剩最后一行,再提交删除后的订单行快照。
Args:
payload: 必须包含 task_id/task_no、line_index,可选 comment。
Returns:
dict[str, Any]: Tool 标准响应,返回更新后的任务状态。
"""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(status="failed", message="未找到任务编号")
try:
line_index = int(payload.get("line_index"))
except (TypeError, ValueError):
return tool_response(status="failed", task=task, message="line_index 非法")
before_lines = [dict(item) for item in (task.lines_json or []) if isinstance(item, dict)]
if line_index < 0 or line_index >= len(before_lines):
return tool_response(status="failed", task=task, message="line_index 超出范围")
if len(before_lines) <= 1:
return tool_response(status="failed", task=task, message="至少保留一条订单行,无法删除最后一行")
normalized_lines = [dict(item) for idx, item in enumerate(before_lines) if idx != line_index]
task.lines_json = normalized_lines
return _commit_notice_edit(
task,
event_type="notice_line_removed",
comment=str(payload.get("comment") or "").strip(),
before_lines=before_lines,
after_lines=normalized_lines,
)
def get_task_status(payload: dict[str, Any]) -> dict[str, Any]:
"""
查询任务当前进度(Tool / 工作台共用)。
【AI 触发时机】:当 Agent 丢失上下文、只知道 conversation_id,或需要先确认当前卡在哪个检查点时调用。
核心逻辑:按任务号或 conversation_id 定位任务,并返回面向用户的当前阶段描述与任务快照。
Args:
payload: 可包含 task_id、task_no、conversation_id 等定位参数。
Returns:
dict[str, Any]: Tool 标准响应,包含 user-facing stage 与完整任务数据。
"""
task = resolve_task_from_payload(payload)
if not task:
return tool_response(
status="failed",
message="未找到任务。请提供任务编号或 conversation_id(Dify 会话 ID)。",
)
return tool_response(
status="ok",
task=task,
message=f"当前进度:{user_facing_task_stage(task)}",
data=serialize_task_for_tool(task),
)
@@ -1,3 +1,11 @@
"""
services/shipping_notice/tool_api_url.py
用途:解析发货通知 Tool API 的基础地址。
依赖:app.services.hxops_tool_api 中的统一基础地址解析能力。
逻辑:由 shipping_notice_tools、dify_inputs 等模块调用本文件,统一生成 Dify/RPA 可访问的 Tool API 根地址。
"""
from __future__ import annotations
from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE
@@ -0,0 +1,128 @@
"""
services/shipping_notice/tool_common.py
用途:发货通知 Tool 链共享配置、payload 合并与消息拼接(无阶段业务编排)。
依赖:constants、models.ShippingTaskEvent。
逻辑:task_workflow / inventory_workflow / fulfillment_workflow 共用,避免 tools 循环依赖。
"""
from __future__ import annotations
from datetime import datetime
from typing import Any
import uuid
from flask import current_app
from app import db
from app.models import ShippingTask, ShippingTaskEvent
from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK
def cfg_bool(key: str, default: bool = False) -> bool:
val = current_app.config.get(key)
if val is None:
return default
if isinstance(val, bool):
return val
return str(val).strip().lower() in {"1", "true", "yes", "on"}
def cfg_int(key: str, default: int = 0, *, min_value: int | None = None) -> int:
val = current_app.config.get(key)
if val is None:
parsed = default
else:
try:
parsed = int(val)
except (TypeError, ValueError):
parsed = default
if min_value is not None:
parsed = max(parsed, min_value)
return parsed
def auto_progress_enabled() -> bool:
return cfg_bool("SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED", False)
def auto_rpa_inventory_enabled() -> bool:
return cfg_bool("SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED", True)
def rpa_inventory_timeout_seconds() -> int:
return cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 120, min_value=5)
def auto_mapping_allow_llm() -> bool:
return cfg_bool("SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM", False)
def auto_match_enabled() -> bool:
return cfg_bool("SHIPPING_NOTICE_AUTO_MATCH_ENABLED", True)
def auto_chain_fallback_enabled() -> bool:
return cfg_bool("SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK", True)
def payload_wants_auto_chain_fallback(payload: dict[str, Any] | None) -> bool:
"""True when caller explicitly opts into backend fallback chaining (Hxops workspace/chat)."""
if not payload or not auto_progress_enabled() or not auto_chain_fallback_enabled():
return False
val = payload.get(AUTO_CHAIN_FALLBACK)
if val is None:
return False
if isinstance(val, bool):
return val
return str(val).strip().lower() in {"1", "true", "yes", "on"}
def merge_tool_payload(
task: ShippingTask,
payload: dict[str, Any] | None = None,
*,
extra: dict[str, Any] | None = None,
) -> dict[str, Any]:
result = tool_payload_for_task(task, payload)
if extra:
result.update(extra)
if payload_wants_auto_chain_fallback(payload):
result[AUTO_CHAIN_FALLBACK] = True
return result
def tool_payload_for_task(task: ShippingTask, payload: dict[str, Any] | None = None) -> dict[str, Any]:
result: dict[str, Any] = {"task_id": task.task_no}
if not payload:
return result
for key in ("lang", "locale", "language"):
lang = str(payload.get(key) or "").strip()
if lang:
result["lang"] = lang
break
return result
def prepend_tool_message(result: dict[str, Any], prefix: str) -> dict[str, Any]:
note = str(prefix or "").strip()
if not note:
return result
body = str(result.get("message") or "").strip()
return {**result, "message": f"{note}\n\n{body}" if body else note}
def generate_task_no() -> str:
return f"SN-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] | None = None) -> None:
if task.id is None:
db.session.flush()
db.session.add(ShippingTaskEvent(
task_id=task.id,
event_type=event_type,
detail_json=detail or {},
))
@@ -1,3 +1,11 @@
"""
services/shipping_notice/tool_response.py
用途:统一构建发货通知 Tool 的 JSON 响应结构。
依赖:state_machine 中的 checkpoint/human_options/action_buttons 解析能力。
逻辑:由 task_workflow、inventory_workflow、fulfillment_workflow 等 workflow 调用本文件,把状态机信息整理成一致的 Tool 响应。
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
File diff suppressed because it is too large. Load diff
@@ -45,6 +45,7 @@ _CHECKPOINT_LABELS: dict[str, str] = {
CP_UPLOAD_REQ: "待上传或获取库存",
CP_INVENTORY_PENDING: "待上传库存",
CP_RSV_REQ: "待补充 Reservation ID",
"shortage_review": "库存不足,无法发货",
CP_READY_MATCH: "待匹配库存",
CP_READY_EXPORT: "待生成发货 Excel",
CP_EXPORT_READY: "发货 Excel 已生成",
@@ -73,8 +74,8 @@ _PENDING_REASON_LABELS: dict[str, str] = {
PH_RPA_PENDING: "RPA 正在导出库存,请稍候",
PH_RPA_EXHAUSTED: "RPA 获取库存失败,请手动上传",
PH_UPLOAD_RPA_PENDING: "RPA 正在上传货代,请稍候",
PH_SHORTAGE: "库存不足,待确认",
RS_SHORTAGE_REVIEW: "库存不足,待确认",
PH_SHORTAGE: "库存不足,无法发货",
RS_SHORTAGE_REVIEW: "库存不足,无法发货",
RS_PARSE_REVIEW: "解析结果待确认",
}
@@ -0,0 +1,166 @@
"""add shipping batches and task upload fields
Revision ID: b1c2d3e4f5a6
Revises: f6f91cb46944
Create Date: 2026-06-17 12:30:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "b1c2d3e4f5a6"
down_revision = "f6f91cb46944"
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)
if "shipping_batches" not in set(insp.get_table_names()):
op.create_table(
"shipping_batches",
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("batch_no", sa.String(length=64), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=True),
sa.Column("conversation_id", sa.String(length=100), nullable=True),
sa.Column("current_focus_task_no", sa.String(length=64), nullable=True),
sa.Column("file_count", sa.Integer(), nullable=False, server_default="1"),
sa.Column("process_summary_json", sa.JSON(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
)
with op.batch_alter_table("shipping_batches", schema=None) as batch_op:
batch_op.create_index(batch_op.f("ix_shipping_batches_batch_no"), ["batch_no"], unique=True)
batch_op.create_index(batch_op.f("ix_shipping_batches_user_id"), ["user_id"], unique=False)
batch_op.create_index("ix_shipping_batches_user_created", ["user_id", "created_at"], unique=False)
batch_op.create_index("ix_shipping_batches_conversation", ["conversation_id"], unique=False)
else:
batch_columns = _table_columns(insp, "shipping_batches")
batch_indexes = {idx["name"] for idx in insp.get_indexes("shipping_batches")}
if "creator_user_id" in batch_columns and "user_id" not in batch_columns:
with op.batch_alter_table("shipping_batches", schema=None) as batch_op:
if "ix_shipping_batches_creator_user_id" in batch_indexes:
batch_op.drop_index("ix_shipping_batches_creator_user_id")
batch_op.alter_column("creator_user_id", new_column_name="user_id")
batch_indexes = {idx["name"] for idx in sa.inspect(bind).get_indexes("shipping_batches")}
with op.batch_alter_table("shipping_batches", schema=None) as batch_op:
if "ix_shipping_batches_user_id" not in batch_indexes:
batch_op.create_index("ix_shipping_batches_user_id", ["user_id"], unique=False)
if "ix_shipping_batches_user_created" not in batch_indexes:
batch_op.create_index("ix_shipping_batches_user_created", ["user_id", "created_at"], unique=False)
columns = _table_columns(insp, "shipping_tasks")
if not columns:
return
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "batch_id" not in columns:
batch_op.add_column(sa.Column("batch_id", sa.Integer(), nullable=True))
batch_op.create_foreign_key("fk_shipping_tasks_batch_id_shipping_batches", "shipping_batches", ["batch_id"], ["id"])
if "source_file_name" not in columns:
batch_op.add_column(sa.Column("source_file_name", sa.String(length=255), nullable=True))
if "source_file_type" not in columns:
batch_op.add_column(sa.Column("source_file_type", sa.String(length=64), nullable=True))
if "batch_index" not in columns:
batch_op.add_column(sa.Column("batch_index", sa.Integer(), nullable=True))
if "batch_total" not in columns:
batch_op.add_column(sa.Column("batch_total", sa.Integer(), nullable=True))
if "current_step" not in columns:
batch_op.add_column(sa.Column("current_step", sa.String(length=64), nullable=True))
if "export_version" not in columns:
batch_op.add_column(sa.Column("export_version", sa.Integer(), nullable=False, server_default="1"))
if "upload_status" not in columns:
batch_op.add_column(sa.Column("upload_status", sa.String(length=32), nullable=True))
if "upload_mode" not in columns:
batch_op.add_column(sa.Column("upload_mode", sa.String(length=32), nullable=True))
if "upload_attempt" not in columns:
batch_op.add_column(sa.Column("upload_attempt", sa.Integer(), nullable=False, server_default="0"))
if "idempotency_key" not in columns:
batch_op.add_column(sa.Column("idempotency_key", sa.String(length=128), nullable=True))
if "upload_started_at" not in columns:
batch_op.add_column(sa.Column("upload_started_at", sa.DateTime(), nullable=True))
if "upload_finished_at" not in columns:
batch_op.add_column(sa.Column("upload_finished_at", sa.DateTime(), nullable=True))
if "upload_error_code" not in columns:
batch_op.add_column(sa.Column("upload_error_code", sa.String(length=64), nullable=True))
if "upload_error_message" not in columns:
batch_op.add_column(sa.Column("upload_error_message", sa.Text(), nullable=True))
if "upload_receipt_json" not in columns:
batch_op.add_column(sa.Column("upload_receipt_json", sa.JSON(), nullable=True))
if "step_payload_json" not in columns:
batch_op.add_column(sa.Column("step_payload_json", sa.JSON(), nullable=True))
indexes = {idx["name"] for idx in insp.get_indexes("shipping_tasks")}
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "ix_shipping_tasks_batch_id" not in indexes and "batch_id" in _table_columns(sa.inspect(bind), "shipping_tasks"):
batch_op.create_index("ix_shipping_tasks_batch_id", ["batch_id"], unique=False)
if "ix_shipping_tasks_batch_step" not in indexes and "batch_id" in _table_columns(sa.inspect(bind), "shipping_tasks"):
batch_op.create_index("ix_shipping_tasks_batch_step", ["batch_id", "current_step"], unique=False)
if "ix_shipping_tasks_upload_status" not in indexes:
batch_op.create_index("ix_shipping_tasks_upload_status", ["upload_status"], unique=False)
def downgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
columns = _table_columns(insp, "shipping_tasks")
if columns:
indexes = {idx["name"] for idx in insp.get_indexes("shipping_tasks")}
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
if "ix_shipping_tasks_upload_status" in indexes:
batch_op.drop_index("ix_shipping_tasks_upload_status")
if "ix_shipping_tasks_batch_step" in indexes:
batch_op.drop_index("ix_shipping_tasks_batch_step")
if "ix_shipping_tasks_batch_id" in indexes:
batch_op.drop_index("ix_shipping_tasks_batch_id")
if "step_payload_json" in columns:
batch_op.drop_column("step_payload_json")
if "upload_receipt_json" in columns:
batch_op.drop_column("upload_receipt_json")
if "upload_error_message" in columns:
batch_op.drop_column("upload_error_message")
if "upload_error_code" in columns:
batch_op.drop_column("upload_error_code")
if "upload_finished_at" in columns:
batch_op.drop_column("upload_finished_at")
if "upload_started_at" in columns:
batch_op.drop_column("upload_started_at")
if "idempotency_key" in columns:
batch_op.drop_column("idempotency_key")
if "upload_attempt" in columns:
batch_op.drop_column("upload_attempt")
if "upload_mode" in columns:
batch_op.drop_column("upload_mode")
if "upload_status" in columns:
batch_op.drop_column("upload_status")
if "export_version" in columns:
batch_op.drop_column("export_version")
if "current_step" in columns:
batch_op.drop_column("current_step")
if "batch_total" in columns:
batch_op.drop_column("batch_total")
if "batch_index" in columns:
batch_op.drop_column("batch_index")
if "source_file_type" in columns:
batch_op.drop_column("source_file_type")
if "source_file_name" in columns:
batch_op.drop_column("source_file_name")
if "batch_id" in columns:
batch_op.drop_constraint("fk_shipping_tasks_batch_id_shipping_batches", type_="foreignkey")
batch_op.drop_column("batch_id")
if "shipping_batches" in set(insp.get_table_names()):
op.drop_table("shipping_batches")
@@ -0,0 +1,70 @@
"""rename shipping_batches.creator_user_id to user_id
Revision ID: c3d4e5f6a7b8
Revises: b1c2d3e4f5a6
Create Date: 2026-06-17 17:35:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "c3d4e5f6a7b8"
down_revision = "b1c2d3e4f5a6"
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)
if "shipping_batches" not in set(insp.get_table_names()):
return
columns = _table_columns(insp, "shipping_batches")
if "creator_user_id" not in columns or "user_id" in columns:
return
indexes = {idx["name"] for idx in insp.get_indexes("shipping_batches")}
with op.batch_alter_table("shipping_batches", schema=None) as batch_op:
if "ix_shipping_batches_creator_user_id" in indexes:
batch_op.drop_index("ix_shipping_batches_creator_user_id")
batch_op.alter_column("creator_user_id", new_column_name="user_id")
indexes = {idx["name"] for idx in sa.inspect(bind).get_indexes("shipping_batches")}
with op.batch_alter_table("shipping_batches", schema=None) as batch_op:
if "ix_shipping_batches_user_id" not in indexes:
batch_op.create_index("ix_shipping_batches_user_id", ["user_id"], unique=False)
if "ix_shipping_batches_user_created" not in indexes:
batch_op.create_index("ix_shipping_batches_user_created", ["user_id", "created_at"], unique=False)
def downgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
if "shipping_batches" not in set(insp.get_table_names()):
return
columns = _table_columns(insp, "shipping_batches")
if "user_id" not in columns or "creator_user_id" in columns:
return
indexes = {idx["name"] for idx in insp.get_indexes("shipping_batches")}
with op.batch_alter_table("shipping_batches", schema=None) as batch_op:
if "ix_shipping_batches_user_created" in indexes:
batch_op.drop_index("ix_shipping_batches_user_created")
if "ix_shipping_batches_user_id" in indexes:
batch_op.drop_index("ix_shipping_batches_user_id")
batch_op.alter_column("user_id", new_column_name="creator_user_id")
indexes = {idx["name"] for idx in sa.inspect(bind).get_indexes("shipping_batches")}
with op.batch_alter_table("shipping_batches", schema=None) as batch_op:
if "ix_shipping_batches_creator_user_id" not in indexes:
batch_op.create_index("ix_shipping_batches_creator_user_id", ["creator_user_id"], unique=False)
+18
View File
@@ -17,6 +17,24 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
monkeypatch.setattr(env_persistence, 'LEGACY_BACKEND_ENV_PATH', tmp_path / 'isolated.env')
@pytest.fixture(autouse=True)
def _shipping_notice_stable_auto_config(app, request):
"""发货通知单测默认关闭 auto 链,避免 dev .env 开启 AUTO_PROGRESS 导致用例漂移。"""
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
return
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = False
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
def pytest_configure(config):
config.addinivalue_line(
"markers",
"auto_rpa: 发货通知测试启用 auto_progress + RPA 自动链",
)
@pytest.fixture
def app():
from app import create_app, db
@@ -0,0 +1,109 @@
"""shipping_notice batch tests.
覆盖 batch 新增能力的最小闭环:
1. 单/多通知可通过 create_batch 一次建批并生成多 task。
2. get_batch_status 返回 focus task 与任务列表。
3. switch_focus_task 可在同批次内切换当前任务。
"""
from app.models import ShippingBatch, ShippingTask
def _tool_headers():
return {
"Content-Type": "application/json",
}
def test_create_batch_tasks_and_switch_focus(app, client):
"""验证 batch 建单、状态查询、focus task 切换主流程。"""
headers = _tool_headers()
create_res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={
"source_type": "manual",
"notice_items": [
{
"source_file_name": "notice-a.txt",
"raw_text": "客户:ACME 料号A001 x 10",
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
{
"source_file_name": "notice-b.txt",
"raw_text": "客户:Wistron 料号B002 x 5",
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "B002", "reservation_id": "R-2", "qty": 5, "uom": "EA"}],
"confidence": 0.95,
},
},
],
},
)
assert create_res.status_code == 200
create_data = create_res.get_json()
assert create_data["status"] == "ok"
batch = create_data["data"]["batch"]
tasks = create_data["data"]["tasks"]
batch_no = batch["batch_no"]
assert batch_no.startswith("SB-")
assert len(tasks) == 2
assert batch["current_focus_task_no"] == tasks[0]["task_id"]
assert batch["process_summary"]["total"] == 2
status_res = client.post(
"/api/shipping-notice/tools/get_batch_status",
headers=headers,
json={"batch_no": batch_no},
)
assert status_res.status_code == 200
status_data = status_res.get_json()
assert status_data["status"] == "ok"
assert status_data["data"]["batch_no"] == batch_no
assert len(status_data["data"]["tasks"]) == 2
assert status_data["data"]["focus_task"] is None
assert status_data["data"]["tasks"][0]["task_no"] == tasks[0]["task_id"]
target_task_no = tasks[1]["task_id"]
switch_res = client.post(
"/api/shipping-notice/tools/switch_focus_task",
headers=headers,
json={"batch_no": batch_no, "task_no": target_task_no},
)
assert switch_res.status_code == 200
switch_data = switch_res.get_json()
assert switch_data["status"] == "ok"
assert switch_data["task_no"] == target_task_no
assert switch_data["data"]["batch"]["current_focus_task_no"] == target_task_no
assert switch_data["data"]["focus_task"]["task_no"] == target_task_no
with app.app_context():
batch_row = ShippingBatch.query.filter_by(batch_no=batch_no).first()
task_rows = ShippingTask.query.filter_by(batch_id=batch_row.id).order_by(ShippingTask.batch_index.asc()).all()
assert batch_row is not None
assert len(task_rows) == 2
assert batch_row.current_focus_task_no == target_task_no
assert task_rows[0].batch_total == 2
assert task_rows[1].batch_total == 2
def test_create_empty_batch_returns_batch_shell(app, client):
"""验证无 notice_items 时仍可创建批次壳,供后续续办。"""
headers = _tool_headers()
res = client.post(
"/api/shipping-notice/tools/create_batch",
headers=headers,
json={"file_count": 1},
)
assert res.status_code == 200
data = res.get_json()
assert data["status"] == "ok"
assert data["batch_no"].startswith("SB-")
assert data["data"]["file_count"] == 1
@@ -0,0 +1,101 @@
"""shipping_notice inventory_rpa_workflow 单测。
覆盖 RPA 库存子模块与 inventory_workflow 的委托边界:
1. ensure_inventory(mode=auto) 触发 running 并写入 trigger 事件。
2. rpa_report_inventory 回调落盘后进入字段映射确认。
"""
from app.models import ShippingTask, ShippingTaskEvent
def _tool_headers():
return {"Content-Type": "application/json"}
def test_ensure_inventory_auto_triggers_rpa_running(app, client, tmp_path):
"""mode=auto 应返回 running 并在 DB 留下 inventory_rpa_triggered 事件。"""
trigger = tmp_path / "triggers"
trigger.mkdir()
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True
app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = False
headers = _tool_headers()
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
inv_res = client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "mode": "auto"},
)
body = inv_res.get_json()
assert body["status"] == "running"
assert body.get("data", {}).get("rpa", {}).get("attempts") == 1
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.pending_human_reason == "rpa_pending"
events = (
ShippingTaskEvent.query.filter_by(task_id=task.id, event_type="inventory_rpa_triggered")
.all()
)
assert len(events) == 1
def test_rpa_report_inventory_callback_needs_mapping_review(app, client, tmp_path):
"""RPA 回调成功落盘后应进入字段映射确认(align_review / map_infer)。"""
drop = tmp_path / "drop"
drop.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop)
headers = _tool_headers()
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
from openpyxl import Workbook
inv_file = drop / "stock.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["料号", "Reservation ID", "可用数量"])
ws.append(["A001", "R-1", 20])
wb.save(inv_file)
wb.close()
cb_res = client.post(
"/api/shipping-notice/rpa/inventory-ready",
headers=headers,
json={"task_no": task_id, "success": True, "file_path": str(inv_file)},
)
data = cb_res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") in {"align_review", "map_infer"}
assert "confirm_inventory_mapping" in (data.get("human_options") or [])
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "inventory_ready"
@@ -38,4 +38,4 @@ def test_format_match_summary_shortage():
)
assert "| R-1 | A001 | 100 | 5 | 95 |" in msg
assert "⚠️ 部分满足" in msg
assert "部分行库存不足" in msg
assert "存在库存缺口" in msg
@@ -0,0 +1,179 @@
"""shipping_notice query_service 读路径单测。"""
from app.models import ShippingBatch, ShippingTask
from app.services.shipping_notice.query_service import (
BatchProjection,
TaskProjection,
compute_batch_process_summary,
extract_task_no_from_text,
get_task_by_ref,
get_task_in_batch,
list_batch_task_summaries,
resolve_task_from_payload,
serialize_batch,
serialize_task,
sort_batch_tasks,
task_export_error_message,
task_sort_key,
)
from app.services.shipping_notice.user_facing_status import TOOL_TASK_DATA_OMIT
def test_get_task_by_ref_supports_task_no_and_numeric_id(app):
"""task_no 与数字主键均应能解析到同一任务。"""
with app.app_context():
task = ShippingTask(
task_no="SN-TEST-QUERY-001",
process_status="created",
source_type="manual",
)
from app import db
db.session.add(task)
db.session.commit()
by_no = get_task_by_ref("SN-TEST-QUERY-001")
by_id = get_task_by_ref(str(task.id))
assert by_no is not None
assert by_id is not None
assert by_no.id == by_id.id
def test_sort_batch_tasks_orders_by_batch_index_then_created_at(app):
"""批次内排序应与 batch_index、created_at 规则一致。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-TEST-SORT", file_count=2)
second = ShippingTask(task_no="SN-SORT-2", batch_index=2, process_status="created", source_type="manual")
first = ShippingTask(task_no="SN-SORT-1", batch_index=1, process_status="created", source_type="manual")
from app import db
db.session.add(batch)
db.session.flush()
second.batch_id = batch.id
first.batch_id = batch.id
db.session.add_all([first, second])
db.session.commit()
ordered = sort_batch_tasks([second, first])
assert [item.task_no for item in ordered] == ["SN-SORT-1", "SN-SORT-2"]
assert task_sort_key(first) < task_sort_key(second)
summaries = list_batch_task_summaries(batch)
assert [row["task_no"] for row in summaries] == ["SN-SORT-1", "SN-SORT-2"]
def test_get_task_in_batch_rejects_foreign_task(app):
"""不属于目标批次的任务应返回 None。"""
with app.app_context():
batch_a = ShippingBatch(batch_no="SB-A", file_count=1)
batch_b = ShippingBatch(batch_no="SB-B", file_count=1)
task = ShippingTask(task_no="SN-FOREIGN", process_status="created", source_type="manual")
from app import db
db.session.add_all([batch_a, batch_b])
db.session.flush()
task.batch_id = batch_a.id
db.session.add(task)
db.session.commit()
assert get_task_in_batch("SB-A", "SN-FOREIGN") is not None
assert get_task_in_batch("SB-B", "SN-FOREIGN") is None
def test_task_export_error_message_distinct_for_missing_path(app):
"""无导出路径与磁盘缺失应返回不同错误文案。"""
with app.app_context():
empty = ShippingTask(task_no="SN-NO-EXPORT", process_status="created", source_type="manual")
assert task_export_error_message(empty) == "export file not found"
missing = ShippingTask(
task_no="SN-MISSING-FILE",
process_status="matched",
source_type="manual",
export_file_path="/tmp/not-a-real-shipping-export.xlsx",
)
assert task_export_error_message(missing) == "export file missing on disk"
def test_task_projection_tool_strips_internal_fields(app):
"""TOOL 投影应剔除 Agent 不应复述的内部状态字段。"""
with app.app_context():
task = ShippingTask(
task_no="SN-PROJ-TOOL",
process_status="waiting_inventory",
review_status="align_review",
match_status="pending",
pending_human_reason="rpa_pending",
error_message="boom",
source_type="manual",
customer_name="ACME",
lines_json=[{"sku": "A001"}],
)
data = serialize_task(task, TaskProjection.TOOL)
assert data["task_no"] == "SN-PROJ-TOOL"
assert data["customer_name"] == "ACME"
assert data["lines"] == [{"sku": "A001"}]
assert not TOOL_TASK_DATA_OMIT.intersection(data.keys())
def test_task_projection_internal_keeps_status_fields(app):
"""TOOL_INTERNAL 保留 create_task 复用场景所需的内部状态字段。"""
with app.app_context():
task = ShippingTask(
task_no="SN-PROJ-INT",
process_status="parsed",
review_status="parse_review",
source_type="manual",
)
data = serialize_task(task, TaskProjection.TOOL_INTERNAL)
assert data["process_status"] == "parsed"
assert data["review_status"] == "parse_review"
def test_batch_process_summary_shared_formula(app):
"""批次汇总公式在 serialize_batch 与 compute_batch_process_summary 间应一致。"""
with app.app_context():
batch = ShippingBatch(batch_no="SB-SUMMARY", file_count=2)
done = ShippingTask(task_no="SN-DONE", process_status="uploaded", source_type="manual", batch_index=1)
running = ShippingTask(task_no="SN-RUN", process_status="matched", source_type="manual", batch_index=2)
from app import db
db.session.add(batch)
db.session.flush()
done.batch_id = batch.id
running.batch_id = batch.id
db.session.add_all([done, running])
db.session.commit()
tasks = [done, running]
assert compute_batch_process_summary(tasks) == {
"total": 2,
"completed": 1,
"failed": 0,
"running": 1,
}
tool_batch = serialize_batch(batch, BatchProjection.TOOL)
assert tool_batch["process_summary"]["completed"] == 1
assert tool_batch["batch_no"] == "SB-SUMMARY"
assert "id" not in tool_batch
def test_resolve_task_from_payload_by_conversation_id(app):
"""conversation_id 应能解析到最近非 rejected 任务。"""
with app.app_context():
task = ShippingTask(
task_no="SN-CONV-1",
conversation_id="conv-abc",
process_status="parsed",
source_type="manual",
)
from app import db
db.session.add(task)
db.session.commit()
resolved = resolve_task_from_payload({"conversation_id": "conv-abc"})
assert resolved is not None
assert resolved.task_no == "SN-CONV-1"
assert extract_task_no_from_text("请处理 SN-20260617-ABCDEF01 这票") == "SN-20260617-ABCDEF01"
+31 -17
View File
@@ -1,3 +1,5 @@
import pytest
from app import db
from app.models import ShippingInventoryMapping, ShippingTask
@@ -35,7 +37,7 @@ def test_shipping_notice_tool_flow(app, client):
)
assert parse_res.status_code == 200
parse_body = parse_res.get_json()
assert parse_body["status"] in {"ok", "needs_human"}
assert parse_body["status"] in {"ok", "needs_human", "running"}
assert "【发货通知解析确认】" in parse_body["message"]
assert "| 料号 | A001 |" in parse_body["message"]
@@ -121,14 +123,17 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
assert "订单" in data["message"]
assert "库存" in data["message"]
assert "缺口" in data["message"]
assert "confirm" in (data.get("human_options") or [])
options = data.get("human_options") or []
assert "confirm" not in options
assert "reparse_inventory" in options
assert "rematch" in options
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm"},
)
assert confirm_res.get_json()["status"] == "ok"
assert confirm_res.get_json()["status"] == "failed"
def test_openapi_spec_public(app, client):
@@ -178,7 +183,7 @@ def test_parse_inventory_from_chat_text(app, client):
assert parse_inv.status_code == 200
data = parse_inv.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "inventory_field_mapping_review"
assert data.get("checkpoint") == "align_review"
assert data.get("stop_agent_turn") is True
assert "match_inventory" in (data.get("forbidden_next_tools") or [])
assert "field_alignment" in data["data"]
@@ -190,7 +195,7 @@ def test_parse_inventory_from_chat_text(app, client):
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "needs_human"
assert confirm_data.get("checkpoint") == "inventory_field_mapping_review"
assert confirm_data.get("checkpoint") == "align_review"
assert "Reservation ID" in (confirm_data.get("message") or "")
match_res = client.post(
@@ -215,7 +220,9 @@ def test_parse_inventory_empty_needs_human(app, client):
json={"task_id": task_id, "raw_inventory_text": " "},
)
assert res.get_json()["status"] == "needs_human"
assert "reparse_inventory" in (res.get_json().get("human_options") or [])
body = res.get_json()
assert body.get("checkpoint") in {"map_infer", "upload_req"}
assert body.get("human_options") is not None or body.get("action_buttons")
def test_match_by_aws_sku_and_reservation_id(app, client):
@@ -308,7 +315,7 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
)
blocked = match_res.get_json()
assert blocked["status"] == "needs_human"
assert blocked.get("checkpoint") == "inventory_field_mapping_review"
assert blocked.get("checkpoint") == "align_review"
assert blocked.get("stop_agent_turn") is True
assert "field_alignment" in blocked["data"]
mapping = blocked["data"]["field_alignment"]
@@ -352,7 +359,7 @@ def test_match_inventory_requires_reservation_id(app, client):
)
data = match_res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "reservation_id_required"
assert data.get("checkpoint") == "rsv_req"
def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
@@ -393,8 +400,9 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
json={"task_id": task_id, "decision": "correct_inventory_mapping"},
)
data = correct_res.get_json()
assert data["status"] == "ok"
assert data.get("checkpoint") == "inventory_mapping_inference"
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "map_infer"
assert data.get("stop_agent_turn") is True
assert "schema_preview" in data["data"]
assert data["data"]["schema_preview"]["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
@@ -433,8 +441,12 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
assert cb_res.status_code == 200
data = cb_res.get_json()
assert data["status"] == "needs_human"
assert data["data"]["process_status"] == "inventory_ready"
assert data.get("checkpoint") in {"map_infer", "align_review"}
assert "confirm_inventory_mapping" in (data.get("human_options") or [])
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status == "inventory_ready"
def test_rpa_upload_callback(app, client, tmp_path):
@@ -614,7 +626,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
assert upload_res.status_code == 200
upload_data = upload_res.get_json()
assert upload_data["status"] == "ok"
assert upload_data.get("checkpoint") == "inventory_mapping_inference"
assert upload_data.get("checkpoint") == "map_infer"
preview = upload_data["data"]["schema_preview"]
assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
@@ -632,7 +644,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
)
apply_data = apply_res.get_json()
assert apply_data["status"] == "needs_human"
assert apply_data.get("checkpoint") == "inventory_field_mapping_review"
assert apply_data.get("checkpoint") == "align_review"
assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1
assert apply_data["data"]["field_alignment"]["match_rule"].startswith("LLM:")
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "llm"
@@ -704,7 +716,7 @@ def test_get_inventory_schema_preview(app, client, tmp_path):
headers=headers,
json={"task_id": task_id},
)
assert missing.get_json()["checkpoint"] == "inventory_upload_required"
assert missing.get_json()["checkpoint"] == "upload_req"
def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
@@ -751,7 +763,7 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
)
apply_data = apply_res.get_json()
assert apply_data["status"] == "needs_human"
assert apply_data["data"]["inventory_row_count"] == 1
assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1
sample = apply_data["data"]["field_alignment"]["sample_inventory_lines"][0]
assert sample["sku"] == "SKU-99"
assert sample["available_qty"] == 12
@@ -804,6 +816,7 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
assert task.match_status is None
@pytest.mark.auto_rpa
def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client):
headers = _tool_headers(app)
@@ -832,6 +845,7 @@ def test_parse_notice_auto_continue_hides_parse_confirmation_hint(app, client):
assert parse_data.get("checkpoint") != "parse_review"
@pytest.mark.auto_rpa
def test_submit_decision_confirm_during_waiting_inventory_is_not_failed(app, client, tmp_path):
headers = _tool_headers(app)
trigger = tmp_path / "inventory_triggers"
@@ -909,7 +923,7 @@ def test_submit_decision_by_conversation_id(app, client):
)
dup_data = dup_res.get_json()
assert dup_data["task_id"] == task_id
assert dup_data.get("checkpoint") == "task_already_exists"
assert dup_data.get("checkpoint") == "task_exists"
def test_parse_inventory_rejects_oversized_text(app, client):
@@ -930,7 +944,7 @@ def test_parse_inventory_rejects_oversized_text(app, client):
)
data = res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "inventory_upload_required"
assert data.get("checkpoint") == "upload_req"
assert "过大" in data["message"]
@@ -0,0 +1,510 @@
{
"template_kind": "hxops_shipping_notice_chatflow_delivery_template",
"template_version": "2026-06-17",
"template_status": "manual-import-required",
"app": {
"name": "货代发货通知 Agent",
"mode": "advanced-chat",
"description": "Hxops 货代发货通知 Chatflow 交付模板。用于在 Dify 画布中手工还原节点、变量、HTTP 调用和 Agent 配置。",
"icon": "truck",
"icon_background": "#E0F2FE"
},
"delivery_notes": [
"本文件是仓库侧交付模板,不是从 Dify 控制台实际导出的原生 DSL。",
"实际发布前,仍应在 Dify 中完成节点配置后导出一份官方 DSL 作为最终交付包。",
"Tool API 契约以 docs/openapi/shipping_notice_tools.dify.json 和 backend/app/services/shipping_notice/openapi_spec.py 为准。",
"Agent Prompt、节点职责与 HTTP 示例以 docs/shipping_notice.md 为准。"
],
"tool_openapi": {
"runtime_import_url": "{{HXOPS_TOOLS_API_BASE}}/api/shipping-notice/tools/openapi.json",
"repo_import_file": "docs/openapi/shipping_notice_tools.dify.json",
"auth": {
"header_name": "X-Shipping-Tool-Key",
"value_from_env": "SHIPPING_NOTICE_TOOL_API_KEY"
}
},
"environment_variables": [
{
"name": "HXOPS_API_BASE",
"type": "string",
"required": true,
"example": "http://192.168.100.192:8890"
},
{
"name": "SHIPPING_NOTICE_TOOL_API_KEY",
"type": "secret",
"required": true,
"example": "your-tool-key"
},
{
"name": "HXOPS_TOOLS_API_BASE",
"type": "string",
"required": true,
"example": "http://192.168.100.192:8890"
}
],
"conversation_variables": [
{
"name": "current_batch_no",
"type": "string",
"description": "当前批次号"
},
{
"name": "current_task_no",
"type": "string",
"description": "当前聚焦任务号"
},
{
"name": "current_task_step",
"type": "string",
"description": "当前任务步骤"
},
{
"name": "current_checkpoint",
"type": "string",
"description": "当前人工节点 / checkpoint"
},
{
"name": "current_task_status",
"type": "string",
"description": "当前任务 process_status"
},
{
"name": "batch_queue_summary",
"type": "string",
"description": "批次摘要文案"
},
{
"name": "last_tool_status",
"type": "string",
"description": "最近一次 Tool 调用状态"
}
],
"graph": {
"entry_node_id": "start",
"answer_node_id": "answer_final",
"nodes": [
{
"id": "start",
"type": "start",
"title": "开始",
"outputs": [
"query",
"files",
"conversation_id"
],
"doc_anchor": "docs/shipping_notice.md#L471-L480"
},
{
"id": "ctx_preprocess",
"type": "code",
"title": "预处理上下文",
"script_ref": "docs/shipping_notice.md#L481-L523",
"outputs": [
"normalized_query",
"detected_batch_no",
"detected_task_no",
"intent_hint",
"has_files",
"error_message"
]
},
{
"id": "route_classifier",
"type": "code",
"title": "附件/意图分类",
"script_ref": "docs/shipping_notice.md#L525-L550",
"outputs": [
"route_key",
"reason"
]
},
{
"id": "tool_create_batch",
"type": "tool",
"title": "创建批次",
"operation_id": "create_batch",
"when": "route_key == notice_batch_upload",
"inputs": {
"conversation_id": "{{conversation_id}}",
"file_count": "{{files.length}}"
}
},
{
"id": "iter_notice_files",
"type": "iteration",
"title": "文件循环器",
"when": "route_key == notice_batch_upload",
"iterates": "files",
"doc_anchor": "docs/shipping_notice.md#L442-L449"
},
{
"id": "tool_create_task",
"type": "tool",
"title": "创建单个任务",
"operation_id": "create_task",
"inputs": {
"batch_no": "{{current_batch_no}}",
"conversation_id": "{{conversation_id}}",
"source_type": "pdf",
"source_file_name": "{{iter_notice_files.item.name}}",
"source_file_type": "{{iter_notice_files.item.mime_type}}",
"batch_index": "{{iter_notice_files.index}}",
"batch_total": "{{files.length}}"
}
},
{
"id": "http_extract_notice_text",
"type": "http",
"title": "文本抽取",
"method": "external_or_frontend",
"notes": [
"由前端或 HTTP 节点完成原文抽取。",
"抽取出的 raw_text 继续传给 LLM字段抽取 / parse_notice。"
]
},
{
"id": "llm_extract_notice",
"type": "llm",
"title": "LLM字段抽取",
"prompt_ref": "docs/shipping_notice.md#L733-L778",
"outputs": [
"llm_json_text"
]
},
{
"id": "code_validate_notice_json",
"type": "code",
"title": "抽取结果校验",
"script_ref": "docs/shipping_notice.md#L567-L594",
"outputs": [
"validated_json",
"is_valid",
"error_message"
]
},
{
"id": "tool_parse_notice",
"type": "tool",
"title": "保存解析结果",
"operation_id": "parse_notice",
"inputs": {
"task_id": "{{tool_create_task.text.task_id}}",
"raw_text": "{{http_extract_notice_text.text}}"
}
},
{
"id": "code_batch_summary",
"type": "code",
"title": "批次摘要组装",
"script_ref": "docs/shipping_notice.md#L596-L621",
"outputs": [
"batch_queue_summary",
"focus_task_no"
]
},
{
"id": "code_set_focus_task",
"type": "code",
"title": "设置当前聚焦任务",
"writes_variables": [
"current_batch_no",
"current_task_no"
]
},
{
"id": "tool_get_task_status_init",
"type": "tool",
"title": "读取当前任务状态",
"operation_id": "get_task_status",
"inputs": {
"task_id": "{{current_task_no}}",
"conversation_id": "{{conversation_id}}"
}
},
{
"id": "http_upload_inventory",
"type": "http",
"title": "上传库存文件",
"request_ref": "docs/shipping_notice.md#L271-L310",
"method": "POST",
"url": "{{HXOPS_API_BASE}}/api/shipping-notice/tools/upload_inventory_file",
"headers": {
"X-Shipping-Tool-Key": "{{SHIPPING_NOTICE_TOOL_API_KEY}}"
},
"body_type": "multipart/form-data",
"body": {
"task_id": "{{current_task_no}}",
"file": "{{files[0]}}"
}
},
{
"id": "tool_schema_preview",
"type": "tool",
"title": "读取 schema preview",
"operation_id": "get_inventory_schema_preview",
"inputs": {
"task_id": "{{current_task_no}}"
}
},
{
"id": "llm_map_inventory",
"type": "llm",
"title": "LLM字段映射建议",
"prompt_ref": "docs/shipping_notice.md#L780-L815",
"outputs": [
"mapping_json_text"
]
},
{
"id": "code_validate_mapping",
"type": "code",
"title": "映射 JSON 校验",
"script_ref": "docs/shipping_notice.md#L651-L678",
"outputs": [
"mapping_json",
"is_valid",
"error_message"
]
},
{
"id": "tool_apply_mapping",
"type": "tool",
"title": "应用字段映射",
"operation_id": "apply_inventory_mapping",
"inputs": {
"task_id": "{{current_task_no}}",
"map_json": "{{code_validate_mapping.mapping_json}}"
}
},
{
"id": "code_alignment_result",
"type": "code",
"title": "字段对齐结果收口",
"notes": [
"整理 align_msg / 下一步动作。",
"若 stop_agent_turn=true,则直接进入 Answer。"
]
},
{
"id": "code_switch_intent",
"type": "code",
"title": "任务切换意图解析",
"script_ref": "docs/shipping_notice.md#L623-L649",
"when": "route_key == task_switch"
},
{
"id": "tool_switch_focus_task",
"type": "tool",
"title": "切换聚焦任务",
"operation_id": "switch_focus_task",
"when": "route_key == task_switch",
"inputs": {
"batch_no": "{{current_batch_no}}",
"task_id": "{{code_switch_intent.target_task_no}}",
"switch_mode": "{{code_switch_intent.switch_mode}}"
}
},
{
"id": "tool_get_task_status_after_switch",
"type": "tool",
"title": "加载当前任务详情",
"operation_id": "get_task_status",
"when": "route_key == task_switch",
"inputs": {
"task_id": "{{current_task_no}}",
"conversation_id": "{{conversation_id}}"
}
},
{
"id": "agent_shipping",
"type": "agent",
"title": "货代 Agent",
"instruction_ref": "docs/shipping_notice.md#L881-L912",
"tool_bindings": [
"get_task_status",
"submit_decision",
"match_inventory",
"generate_shipment_excel",
"upload_to_freight",
"auto_progress",
"get_inventory_schema_preview",
"apply_inventory_mapping",
"ensure_inventory",
"parse_inventory",
"update_notice_fields",
"update_notice_line"
]
},
{
"id": "code_normalize_tool_result",
"type": "code",
"title": "工具结果标准化",
"script_ref": "docs/shipping_notice.md#L680-L704",
"outputs": [
"tool_status",
"tool_message",
"tool_checkpoint",
"tool_action_buttons",
"tool_human_options",
"tool_data_json"
]
},
{
"id": "code_build_reply",
"type": "code",
"title": "组装直接回复",
"script_ref": "docs/shipping_notice.md#L706-L731",
"outputs": [
"final_reply"
]
},
{
"id": "answer_final",
"type": "answer",
"title": "直接回复",
"text": "{{final_reply}}"
}
],
"edges": [
{
"from": "start",
"to": "ctx_preprocess"
},
{
"from": "ctx_preprocess",
"to": "route_classifier"
},
{
"from": "route_classifier",
"to": "tool_create_batch",
"condition": "route_key == notice_batch_upload"
},
{
"from": "tool_create_batch",
"to": "iter_notice_files"
},
{
"from": "iter_notice_files",
"to": "tool_create_task"
},
{
"from": "tool_create_task",
"to": "http_extract_notice_text"
},
{
"from": "http_extract_notice_text",
"to": "llm_extract_notice"
},
{
"from": "llm_extract_notice",
"to": "code_validate_notice_json"
},
{
"from": "code_validate_notice_json",
"to": "tool_parse_notice",
"condition": "is_valid == true"
},
{
"from": "tool_parse_notice",
"to": "code_batch_summary"
},
{
"from": "code_batch_summary",
"to": "code_set_focus_task"
},
{
"from": "code_set_focus_task",
"to": "tool_get_task_status_init"
},
{
"from": "tool_get_task_status_init",
"to": "agent_shipping"
},
{
"from": "route_classifier",
"to": "http_upload_inventory",
"condition": "route_key == inventory_upload"
},
{
"from": "http_upload_inventory",
"to": "tool_schema_preview"
},
{
"from": "tool_schema_preview",
"to": "llm_map_inventory"
},
{
"from": "llm_map_inventory",
"to": "code_validate_mapping"
},
{
"from": "code_validate_mapping",
"to": "tool_apply_mapping",
"condition": "is_valid == true"
},
{
"from": "tool_apply_mapping",
"to": "code_alignment_result"
},
{
"from": "code_alignment_result",
"to": "answer_final"
},
{
"from": "route_classifier",
"to": "code_switch_intent",
"condition": "route_key == task_switch"
},
{
"from": "code_switch_intent",
"to": "tool_switch_focus_task"
},
{
"from": "tool_switch_focus_task",
"to": "tool_get_task_status_after_switch"
},
{
"from": "tool_get_task_status_after_switch",
"to": "agent_shipping"
},
{
"from": "route_classifier",
"to": "agent_shipping",
"condition": "route_key == continue_task"
},
{
"from": "agent_shipping",
"to": "code_normalize_tool_result"
},
{
"from": "code_normalize_tool_result",
"to": "code_build_reply"
},
{
"from": "code_build_reply",
"to": "answer_final"
},
{
"from": "route_classifier",
"to": "answer_final",
"condition": "route_key == direct_reply"
}
]
},
"http_examples": {
"upload_inventory_file_ref": "docs/shipping_notice.md#L271-L310",
"create_batch_ref": "docs/shipping_notice.md#L312-L349",
"apply_inventory_mapping_ref": "docs/shipping_notice.md#L350-L369"
},
"acceptance_checklist": [
"OpenAPI 从 docs/openapi/shipping_notice_tools.dify.json 或运行时 /tools/openapi.json 成功导入",
"Agent 节点已绑定 get_task_status/submit_decision/match_inventory/auto_progress/update_notice_* 等工具",
"HTTP 节点已配置 X-Shipping-Tool-Key",
"多通知文件场景能够 create_batch -> create_task -> parse_notice",
"库存 Excel 场景走 upload_inventory_file -> get_inventory_schema_preview -> apply_inventory_mapping",
"align_review 时 Agent 不越过人工确认",
"match_inventory 返回 ok 后,同轮继续 auto_progress",
"parse_review 阶段可调用 update_notice_fields / update_notice_line"
]
}
+362 -4
View File
@@ -11,11 +11,11 @@
}
],
"paths": {
"/tools/create_task": {
"/tools/create_batch": {
"post": {
"operationId": "create_task",
"summary": "创建发货任务 task",
"description": "创建发货任务 task",
"operationId": "create_batch",
"summary": "创建发货批次 batch(一次多文件上传的聚合容器)",
"description": "创建发货批次 batch(一次多文件上传的聚合容器)",
"parameters": [],
"requestBody": {
"required": true,
@@ -24,6 +24,62 @@
"schema": {
"type": "object",
"properties": {
"batch_no": {
"type": "string",
"description": "已存在的批次编号(可选)。传入时将直接复用该批次。"
},
"user_id": {
"type": "integer",
"description": "Hxops 用户 ID(可选)"
},
"conversation_id": {
"type": "string",
"description": "Dify 会话 ID,便于工作台关联"
},
"file_count": {
"type": "integer",
"description": "本批通知文件数量"
}
}
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/create_task": {
"post": {
"operationId": "create_task",
"summary": "创建发货任务 task(可挂到某个 batch)",
"description": "创建发货任务 task(可挂到某个 batch)",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"batch_no": {
"type": "string",
"description": "发货批次编号(batch id),如 SB-20260617-ABCD1234"
},
"task_id": {
"type": "string",
"description": "已存在的发货任务编号(可选)。传入时将直接复用该任务,禁止重复创建。"
},
"user_id": {
"type": "integer",
"description": "Hxops 用户 ID(可选)"
@@ -42,6 +98,22 @@
"pdf"
]
},
"source_file_name": {
"type": "string",
"description": "原始通知文件名(多文件场景建议传)"
},
"source_file_type": {
"type": "string",
"description": "原始通知文件类型(多文件场景建议传)"
},
"batch_index": {
"type": "integer",
"description": "当前任务在批次中的顺序,从 1 开始"
},
"batch_total": {
"type": "integer",
"description": "当前批次总任务数"
},
"raw_content": {
"type": "string",
"description": "原始发货通知文本(可选,后续 parse 也可传入)"
@@ -108,6 +180,206 @@
}
}
},
"/tools/update_notice_fields": {
"post": {
"operationId": "update_notice_fields",
"summary": "更新解析后的发货通知单头字段,如客户、PO、交期、收货地",
"description": "更新解析后的发货通知单头字段,如客户、PO、交期、收货地",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"fields": {
"type": "object",
"description": "可更新字段:customer_name/customer_code/ship_to/po_number/required_date",
"additionalProperties": true
},
"comment": {
"type": "string",
"description": "修改备注(可选)"
}
},
"required": [
"task_id",
"fields"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/update_notice_line": {
"post": {
"operationId": "update_notice_line",
"summary": "更新解析结果中的某一行,如 SKU、Reservation ID、数量、交期",
"description": "更新解析结果中的某一行,如 SKU、Reservation ID、数量、交期",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"line_index": {
"type": "integer",
"description": "行下标,从 0 开始"
},
"patch": {
"type": "object",
"description": "可更新字段:sku/reservation_id/quantity/qty/required_date/uom",
"additionalProperties": true
},
"comment": {
"type": "string",
"description": "修改备注(可选)"
}
},
"required": [
"task_id",
"line_index",
"patch"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/add_notice_line": {
"post": {
"operationId": "add_notice_line",
"summary": "向解析结果新增一行发货需求",
"description": "向解析结果新增一行发货需求",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"line": {
"type": "object",
"description": "新增行,至少包含 sku 和 qty/quantity",
"additionalProperties": true
},
"comment": {
"type": "string",
"description": "修改备注(可选)"
}
},
"required": [
"task_id",
"line"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/remove_notice_line": {
"post": {
"operationId": "remove_notice_line",
"summary": "删除解析结果中的某一行发货需求",
"description": "删除解析结果中的某一行发货需求",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"task_id": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"line_index": {
"type": "integer",
"description": "行下标,从 0 开始"
},
"comment": {
"type": "string",
"description": "修改备注(可选)"
}
},
"required": [
"task_id",
"line_index"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/parse_inventory": {
"post": {
"operationId": "parse_inventory",
@@ -575,6 +847,92 @@
}
}
}
},
"/tools/get_batch_status": {
"post": {
"operationId": "get_batch_status",
"summary": "查询批次当前状态、任务列表与当前聚焦任务",
"description": "查询批次当前状态、任务列表与当前聚焦任务",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"batch_no": {
"type": "string",
"description": "发货批次编号(batch id),如 SB-20260617-ABCD1234"
}
},
"required": [
"batch_no"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
},
"/tools/switch_focus_task": {
"post": {
"operationId": "switch_focus_task",
"summary": "切换当前批次的聚焦任务",
"description": "切换当前批次的聚焦任务",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"batch_no": {
"type": "string",
"description": "发货批次编号(batch id),如 SB-20260617-ABCD1234"
},
"task_no": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
},
"target_task_no": {
"type": "string",
"description": "发货任务编号(task id),如 SN-20260529-ABCD1234"
}
},
"required": [
"batch_no"
]
}
}
}
},
"responses": {
"200": {
"description": "Tool response (status: ok|running|needs_human|failed). May include checkpoint, human_options, action_buttons.",
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
}
}
}
+955 -1389
View File
File diff suppressed because it is too large. Load diff
+252 -5
View File
@@ -1,13 +1,17 @@
/**
/**
* features/chat/api/shipping.api.ts
* 货代发货 HTTP API:任务列表、上传库存、映射、决策、Excel 生成等。
* 后端路由前缀为 /api/workspace/shipping-tasks,由 chat 域 Agent 流程与工作台页面共用。
* 用途:封装发货通知相关 HTTP API,包括任务/批次查询、库存上传、映射确认、人工决策与 Excel 导出。
* 依赖:浏览器 fetch、getAuthHeaders、shipping.api.types 类型定义。
* 逻辑:上游由 useChatShipping 与 shipping/* handler 调用本文件;本文件统一请求工作台后端 `/api/workspace/*` 路由并抛出标准错误。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import type {
ShippingBatchSummary,
ShippingChatActionsResponse,
ShippingDecisionResponse,
ShippingInventoryUploadResponse,
ShippingNoticeHeader,
ShippingNoticeLine,
ShippingNoticeUploadResponse,
ShippingTaskCreateResponse,
ShippingTaskDetail,
@@ -24,6 +28,7 @@ async function getJson<T>(url: string): Promise<T> {
}
export const listWorkspaceShippingTasks = (params?: { process_status?: string; limit?: number }) => {
/** 拉取当前用户可见的发货任务列表。 */
const sp = new URLSearchParams();
if (params?.process_status) sp.set('process_status', params.process_status);
if (params?.limit) sp.set('limit', String(params.limit));
@@ -31,17 +36,46 @@ export const listWorkspaceShippingTasks = (params?: { process_status?: string; l
return getJson<ShippingTaskSummary[]>(`/api/workspace/shipping-tasks${qs ? '?' + qs : ''}`);
};
export const listWorkspaceShippingBatches = (params?: { limit?: number }) => {
/** 拉取当前用户的发货批次摘要列表。 */
const sp = new URLSearchParams();
if (params?.limit) sp.set('limit', String(params.limit));
const qs = sp.toString();
return getJson<ShippingBatchSummary[]>(`/api/workspace/shipping-batches${qs ? '?' + qs : ''}`);
};
/** 获取批次详情、批次任务列表与当前焦点任务。 */
export const getWorkspaceShippingBatch = (batchNo: string) =>
getJson<ShippingBatchSummary & { tasks?: ShippingTaskSummary[]; focus_task?: ShippingTaskSummary | null }>(
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}`,
);
/** 获取指定批次当前焦点任务。 */
export const getWorkspaceShippingBatchFocusTask = (batchNo: string) =>
getJson<ShippingTaskSummary>(
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/focus-task`,
);
/** 获取单个发货任务详情。 */
export const getWorkspaceShippingTask = (taskNo: string) =>
getJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
/** 生成任务导出文件的前端下载 URL。 */
export const workspaceShippingExportUrl = (taskNo: string) =>
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
/** 获取聊天气泡动作按钮、检查点和 human options。 */
export const getShippingChatActions = (taskNo: string) =>
getJson<ShippingChatActionsResponse>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/chat-actions`,
);
/**
* 上传库存 Excel,并由后端完成解析与 schema preview 生成。
* @param taskNo - 发货任务编号
* @param file - 用户选择的库存文件
* @returns 库存上传与解析结果
*/
export async function uploadWorkspaceShippingInventory(taskNo: string, file: File) {
const form = new FormData();
form.append('file', file);
@@ -58,6 +92,12 @@ export async function uploadWorkspaceShippingInventory(taskNo: string, file: Fil
return body;
}
/**
* 提交库存字段映射。
* @param taskNo - 发货任务编号
* @param columnMappingJson - 前端表单确认后的 map_json
* @returns 映射应用与库存解析结果
*/
export async function applyWorkspaceShippingInventoryMapping(taskNo: string, columnMappingJson: Record<string, unknown>) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/apply-inventory-mapping`,
@@ -74,6 +114,11 @@ export async function applyWorkspaceShippingInventoryMapping(taskNo: string, col
return body;
}
/**
* 创建单个发货任务。
* @param params - 建单参数,可包含 source_type、conversation_id、raw_content
* @returns 建单结果
*/
export async function createWorkspaceShippingTask(params?: {
source_type?: string;
conversation_id?: string;
@@ -91,6 +136,12 @@ export async function createWorkspaceShippingTask(params?: {
return body;
}
/**
* 上传单个发货通知附件并立即建单解析。
* @param file - 发货通知文件
* @param conversationId - 可选会话 ID,用于把任务绑定到聊天会话
* @returns 建单与解析结果
*/
export async function createWorkspaceShippingTaskFromNotice(file: File, conversationId?: string) {
const form = new FormData();
form.append('file', file);
@@ -109,6 +160,67 @@ export async function createWorkspaceShippingTaskFromNotice(file: File, conversa
return body;
}
/**
* 批量上传多份发货通知并创建批次。
* @param files - 发货通知附件列表
* @param conversationId - 可选会话 ID
* @returns 批次与任务创建结果
*/
export async function createWorkspaceShippingBatchFromNotices(files: File[], conversationId?: string) {
const form = new FormData();
files.forEach((file) => form.append('files', file));
if (conversationId) form.append('conversation_id', conversationId);
const headers = getAuthHeaders();
delete (headers as Record<string, string>)['Content-Type'];
const res = await fetch('/api/workspace/shipping-batches/create-from-notices', {
method: 'POST',
headers,
body: form,
});
const body = (await res.json().catch(() => ({}))) as ShippingNoticeUploadResponse & {
error?: string;
batch_no?: string;
data?: unknown;
};
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
/**
* 切换批次当前焦点任务。
* @param batchNo - 批次编号
* @param taskNo - 目标任务编号
* @returns 更新后的批次摘要与焦点任务
*/
export async function switchWorkspaceShippingBatchFocusTask(batchNo: string, taskNo: string) {
const res = await fetch(
`/api/workspace/shipping-batches/${encodeURIComponent(batchNo)}/focus-task`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ task_no: taskNo }),
},
);
const body = (await res.json().catch(() => ({}))) as {
error?: string;
batch?: ShippingBatchSummary;
focus_task?: ShippingTaskSummary;
};
if (!res.ok) {
throw new Error(body.error || res.statusText);
}
return body;
}
/**
* 提交人工决策。
* @param taskNo - 发货任务编号
* @param decision - 决策 ID,如 confirm、reject、reparse
* @param comment - 可选备注
* @returns 决策执行结果
*/
export async function submitWorkspaceShippingDecision(taskNo: string, decision: string, comment?: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/submit-decision`,
@@ -125,6 +237,121 @@ export async function submitWorkspaceShippingDecision(taskNo: string, decision:
return body;
}
/**
* 更新发货通知单头字段。
* @param taskNo - 发货任务编号
* @param fields - 需要更新的单头字段
* @param comment - 可选操作备注
* @returns 更新结果
*/
export async function updateWorkspaceShippingNoticeFields(
taskNo: string,
fields: Partial<ShippingNoticeHeader>,
comment?: string,
) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-fields`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ fields, ...(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 taskNo - 发货任务编号
* @param lineIndex - 订单行下标
* @param patch - 行字段补丁
* @param comment - 可选操作备注
* @returns 更新结果
*/
export async function updateWorkspaceShippingNoticeLine(
taskNo: string,
lineIndex: number,
patch: Partial<ShippingNoticeLine> & { quantity?: number },
comment?: string,
) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/update-notice-line`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ line_index: lineIndex, patch, ...(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 taskNo - 发货任务编号
* @param line - 新增的订单行内容
* @param comment - 可选操作备注
* @returns 更新结果
*/
export async function addWorkspaceShippingNoticeLine(
taskNo: string,
line: Partial<ShippingNoticeLine> & { quantity?: number },
comment?: string,
) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/add-notice-line`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ line, ...(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 taskNo - 发货任务编号
* @param lineIndex - 待删除的订单行下标
* @param comment - 可选操作备注
* @returns 更新结果
*/
export async function removeWorkspaceShippingNoticeLine(
taskNo: string,
lineIndex: number,
comment?: string,
) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/remove-notice-line`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ line_index: lineIndex, ...(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 taskNo - 发货任务编号
* @returns 匹配结果与后续动作提示
*/
export async function matchWorkspaceShippingInventory(taskNo: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/match-inventory`,
@@ -141,7 +368,12 @@ export async function matchWorkspaceShippingInventory(taskNo: string) {
return body;
}
/** Hxops 聊天兜底:等同 Dify auto_progress Tool */
/**
* 以用户态触发自动推进,作为聊天前端兜底入口。
* @param taskNo - 发货任务编号
* @param lang - 可选语言代码
* @returns 自动推进结果
*/
export async function autoProgressWorkspaceShippingTask(taskNo: string, lang?: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/auto-progress`,
@@ -158,6 +390,11 @@ export async function autoProgressWorkspaceShippingTask(taskNo: string, lang?: s
return body;
}
/**
* 标记货代系统已人工上传完成。
* @param taskNo - 发货任务编号
* @returns 上传确认结果
*/
export async function markWorkspaceShippingManualUploaded(taskNo: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/mark-manual-uploaded`,
@@ -174,6 +411,11 @@ export async function markWorkspaceShippingManualUploaded(taskNo: string) {
return body;
}
/**
* 生成发货 Excel。
* @param taskNo - 发货任务编号
* @returns 生成结果,成功时通常会包含下载链接
*/
export async function generateWorkspaceShippingExcel(taskNo: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/generate-excel`,
@@ -190,13 +432,18 @@ export async function generateWorkspaceShippingExcel(taskNo: string) {
return body;
}
/** 货代发货 Agent 显示名称,用于路由与 Agent 匹配 */
/** 货代发货 Agent 显示名称,用于聊天路由与 Agent 匹配。 */
export const SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent';
export type {
ShippingBatchSummary,
ShippingChatAction,
ShippingChatActionsResponse,
ShippingDecisionResponse,
ShippingInventoryUploadResponse,
ShippingMatchLineResult,
ShippingNoticeHeader,
ShippingNoticeLine,
ShippingNoticeUploadResponse,
ShippingTaskCreateResponse,
ShippingTaskDetail,
@@ -1,8 +1,10 @@
/**
/**
* features/chat/components/ChatViewContent.vue
* 对话页主区域:侧栏、消息列表、输入栏与内置浏览器。
*/
<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';
@@ -10,9 +12,68 @@ 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 { 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>
@@ -80,6 +141,148 @@ const page = useChatPageContext();
<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.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>
</button>
</div>
</div>
<ChatMessageList
:messages="page.messages"
:agent-name="page.currentAgent?.name || 'AI'"
@@ -0,0 +1,49 @@
/**
* features/chat/components/ShippingWorkflowStepper.vue
* 货代发货七步流程 Stepper。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type { ShippingWorkflowStepItem } from '../shipping';
defineProps<{
steps: ShippingWorkflowStepItem[];
compact?: boolean;
}>();
const { t } = useI18n();
const stepClass = (status: ShippingWorkflowStepItem['status']) => {
if (status === 'completed') return 'border-emerald-200 bg-emerald-50 text-emerald-700';
if (status === 'current') return 'border-brand-300 bg-brand-50 text-brand-700';
if (status === 'blocked') return 'border-rose-200 bg-rose-50 text-rose-700';
return 'border-default bg-surface text-muted';
};
const dotClass = (status: ShippingWorkflowStepItem['status']) => {
if (status === 'completed') return 'bg-emerald-500';
if (status === 'current') return 'bg-brand-500';
if (status === 'blocked') return 'bg-rose-500';
return 'bg-slate-300';
};
</script>
<template>
<div class="space-y-2">
<div class="text-[11px] font-semibold uppercase tracking-[0.18em] text-muted">{{ t('chat.shippingNoticeUi.stepperTitle') }}</div>
<div class="grid gap-2" :class="compact ? 'sm:grid-cols-4 xl:grid-cols-7' : 'md:grid-cols-4 xl:grid-cols-7'">
<div
v-for="(step, index) in steps"
:key="step.id"
class="rounded-2xl border px-3 py-2.5 transition"
:class="stepClass(step.status)"
>
<div class="flex items-center gap-2">
<span class="inline-flex h-5 min-w-5 items-center justify-center rounded-full text-[11px] font-semibold text-white" :class="dotClass(step.status)">
{{ index + 1 }}
</span>
<span class="text-xs font-semibold">{{ t(step.label) }}</span>
</div>
</div>
</div>
</div>
</template>
@@ -7,13 +7,16 @@ import { computed } from 'vue';
import { Check, Copy, Edit2, LayoutGrid, MessageSquareText, RotateCw } from 'lucide-vue-next';
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
import ShippingMatchResultCard from './ShippingMatchResultCard.vue';
import ShippingParseReviewMessage, { type ShippingParseReviewHandlers } from './ShippingParseReviewMessage.vue';
import type { ChatMessage, SourceFileLink } from '../../types/chat.types';
import type { ShippingInventoryMappingFormPayload } from '../../types/shipping.types';
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload } from '../../types/shipping.types';
export interface ChatMessageBubbleHandlers {
renderMarkdown: (text: string) => string;
onMarkdownClick: (event: MouseEvent) => void;
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
getShippingMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null;
canOpenQueryPreview: (msg: ChatMessage) => boolean;
getQueryPreviewSummary: (msg: ChatMessage) => string;
openQueryPreviewDialog: (msg: ChatMessage) => void;
@@ -77,8 +80,20 @@ const showSourceSection = computed(() => {
});
const showActions = computed(() => message.type !== 'leave-form');
const showShippingActionsPanel = computed(() =>
isShippingNoticeAgent
&& !!message.shipping_actions?.length
&& message.type !== 'shipping-match-result',
);
const isLastMessage = computed(() => index === messageCount - 1);
const isCopied = computed(() => copiedIndex === index);
const shippingParseReviewHandlers = computed<ShippingParseReviewHandlers>(() => ({
getPayload: shippingHandlers.getParseReviewPayload,
updateHeader: shippingHandlers.updateHeader,
updateLine: shippingHandlers.updateLine,
addLine: shippingHandlers.addLine,
removeLine: shippingHandlers.removeLine,
}));
</script>
<template>
@@ -110,6 +125,22 @@ const isCopied = computed(() => copiedIndex === index);
:message="message"
:handlers="shippingHandlers"
/>
<ShippingParseReviewMessage
v-else-if="message.type === 'shipping-parse-review' && shippingHandlers.getParseReviewPayload(message)"
:message="message"
:handlers="shippingParseReviewHandlers"
/>
<ShippingMatchResultCard
v-else-if="message.type === 'shipping-match-result' && handlers.getShippingMatchResultPayload(message)"
:task-id="handlers.getShippingMatchResultPayload(message)!.taskId"
:match-status="handlers.getShippingMatchResultPayload(message)!.match_status"
:line-results="handlers.getShippingMatchResultPayload(message)!.line_results"
:shortage-lines="handlers.getShippingMatchResultPayload(message)!.shortage_lines"
:action-buttons="handlers.getShippingMatchResultPayload(message)!.action_buttons"
:action-busy="isThinking || message.shipping_actions_used"
:action-button-class="handlers.shippingActionButtonClass"
:on-action-click="(action) => handlers.onShippingActionClick(message, action)"
/>
<div
v-else
class="chat-markdown prose prose-sm max-w-none leading-7 text-primary prose-a:text-blue-600 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100 prose-th:border prose-th:border-slate-200 prose-th:bg-slate-50 prose-th:px-3 prose-th:py-2 prose-th:text-left prose-td:border prose-td:border-slate-200 prose-td:px-3 prose-td:py-2"
@@ -132,7 +163,7 @@ const isCopied = computed(() => copiedIndex === index);
</div>
<div
v-if="isShippingNoticeAgent && message.shipping_actions?.length"
v-if="showShippingActionsPanel"
class="mt-4 space-y-2 border-t border-default pt-4"
>
<div class="text-xs font-medium text-muted">{{ $t('chat.shippingNoticeActionsHint') }}</div>
@@ -4,7 +4,8 @@
*/
<script setup lang="ts">
import type { ChatMessage } from '../../types/chat.types';
import type { ShippingInventoryMappingFormPayload } from '../../types/shipping.types';
import type { ShippingNoticeHeader, ShippingNoticeLine } from '../../types/shipping.api.types';
import type { ShippingInventoryMappingFormPayload, ShippingMatchResultPayload, ShippingParseReviewPayload } from '../../types/shipping.types';
export interface ShippingMappingHandlers {
getPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
@@ -13,6 +14,14 @@ export interface ShippingMappingHandlers {
getSampleRowText: (msg: ChatMessage) => string;
reupload: (msg: ChatMessage) => void;
apply: (msg: ChatMessage) => void;
getParseReviewPayload: (msg: ChatMessage) => ShippingParseReviewPayload | null;
getMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null;
updateParseReviewHeader: (msg: ChatMessage, fields: Partial<ShippingNoticeHeader>) => Promise<boolean>;
updateParseReviewLine: (msg: ChatMessage, lineIndex: number, patch: Partial<ShippingNoticeLine>) => Promise<boolean>;
updateHeader: (msg: ChatMessage, fields: Partial<ShippingNoticeHeader>) => Promise<boolean>;
updateLine: (msg: ChatMessage, lineIndex: number, patch: Partial<ShippingNoticeLine>) => Promise<boolean>;
addLine: (msg: ChatMessage, line: Partial<ShippingNoticeLine>) => Promise<boolean>;
removeLine: (msg: ChatMessage, lineIndex: number) => Promise<boolean>;
}
const { message, handlers } = defineProps<{
@@ -0,0 +1,147 @@
/**
* features/chat/components/messages/ShippingMatchResultCard.vue
* 用途:出货 Agent 对话区与工作台共用的库存匹配/缺口结果卡片。
* 依赖:shipping.api.types、vue-i18n。
* 逻辑:由 Chat 消息区和 ShippingNoticeView 传入匹配结果;本组件只负责结构化展示状态、缺口与操作按钮。
*/
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import type {
ShippingChatAction,
ShippingMatchLineResult,
} from '../../types/shipping.api.types';
const props = defineProps<{
taskId: string;
matchStatus?: string | null;
lineResults?: ShippingMatchLineResult[] | null;
shortageLines?: ShippingMatchLineResult[] | null;
actionButtons?: ShippingChatAction[] | null;
actionBusy?: boolean;
onActionClick?: (action: ShippingChatAction) => void;
actionButtonClass?: (variant?: string) => string;
}>();
const { t } = useI18n();
const formatQty = (value: unknown) => {
const num = Number(value ?? 0);
if (!Number.isFinite(num)) return '-';
return Number.isInteger(num) ? String(num) : String(num);
};
const rowStatusLabel = (status?: string | null) => {
if (status === 'ok') return t('chat.shippingNoticeUi.rowStatus.ok');
if (status === 'partial') return t('chat.shippingNoticeUi.rowStatus.partial');
if (status === 'shortage') return t('chat.shippingNoticeUi.rowStatus.shortage');
return status || '-';
};
const matchStatusLabel = (status?: string | null) => {
if (status === 'fulfillable') return t('chat.shippingNoticeUi.matchStatus.fulfillable');
if (status === 'partial') return t('chat.shippingNoticeUi.matchStatus.partial');
if (status === 'unfulfillable') return t('chat.shippingNoticeUi.matchStatus.unfulfillable');
return status || t('chat.shippingNoticeUi.matchStatus.pending');
};
const hasShortage = () => Array.isArray(props.shortageLines) && props.shortageLines.length > 0;
</script>
<template>
<section class="space-y-4 rounded-2xl border border-default bg-surface-soft/90 p-4">
<div class="flex flex-wrap items-start justify-between gap-3">
<div>
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ t('chat.shippingNoticeUi.matchResult') }}</div>
<div class="mt-1 text-xs text-muted">{{ t('chat.shippingNoticeUi.taskId', { taskId }) }}</div>
</div>
<span
class="rounded-full px-2.5 py-1 text-xs font-semibold"
:class="hasShortage()
? 'bg-rose-100 text-rose-700'
: 'bg-emerald-100 text-emerald-700'"
>
{{ matchStatusLabel(matchStatus) }}
</span>
</div>
<div
v-if="hasShortage()"
class="rounded-xl border border-rose-200 bg-rose-50 px-4 py-3 text-sm text-rose-700"
>
{{ t('chat.shippingNoticeUi.shortageBanner') }}
</div>
<div v-if="lineResults?.length" class="overflow-x-auto rounded-xl border border-default">
<table class="min-w-full text-sm">
<thead class="bg-surface text-left text-xs text-muted">
<tr>
<th class="px-3 py-2">#</th>
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.sku') }}</th>
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.orderDemand') }}</th>
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.inventoryAvailable') }}</th>
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.shortageQty') }}</th>
<th class="px-3 py-2">{{ t('chat.shippingNoticeUi.statusLabel') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="(line, index) in lineResults"
:key="`${taskId}-match-${index}`"
class="border-t border-default/70"
>
<td class="px-3 py-2 text-secondary">{{ index + 1 }}</td>
<td class="px-3 py-2 text-secondary">{{ line.reservation_id || '-' }}</td>
<td class="px-3 py-2 font-mono text-secondary">{{ line.sku || '-' }}</td>
<td class="px-3 py-2 text-secondary">{{ formatQty(line.required_qty) }}</td>
<td class="px-3 py-2 text-secondary">{{ formatQty(line.available_qty) }}</td>
<td class="px-3 py-2" :class="Number(line.shortage_qty || 0) > 0 ? 'font-semibold text-rose-700' : 'text-secondary'">
{{ Number(line.shortage_qty || 0) > 0 ? formatQty(line.shortage_qty) : '-' }}
</td>
<td class="px-3 py-2">
<span
class="rounded-full px-2 py-0.5 text-xs font-medium"
:class="line.line_status === 'ok'
? 'bg-emerald-100 text-emerald-700'
: line.line_status === 'partial'
? 'bg-amber-100 text-amber-700'
: 'bg-rose-100 text-rose-700'"
>
{{ rowStatusLabel(line.line_status) }}
</span>
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="shortageLines?.length" class="space-y-2">
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ t('chat.shippingNoticeUi.shortageDetails') }}</div>
<ul class="space-y-2 rounded-xl border border-rose-200 bg-rose-50/70 p-3 text-sm text-rose-700">
<li
v-for="(line, index) in shortageLines"
:key="`${taskId}-shortage-${index}`"
>
{{ t('chat.shippingNoticeUi.shortageRowDetail', { index: index + 1, reservationId: line.reservation_id || '-', sku: line.sku || '-', shortage: formatQty(line.shortage_qty) }) }}
</li>
</ul>
</div>
<div v-if="actionButtons?.length" class="space-y-2 border-t border-default pt-4">
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ t('chat.shippingNoticeUi.availableActions') }}</div>
<div class="flex flex-wrap gap-2">
<button
v-for="(action, index) in actionButtons"
:key="`${taskId}-action-${action.id}-${index}`"
type="button"
:class="actionButtonClass
? actionButtonClass(action.variant)
: 'rounded-xl border border-default px-3 py-2 text-sm font-medium text-secondary hover:bg-surface'"
:disabled="actionBusy"
@click="onActionClick?.(action)"
>
{{ action.label }}
</button>
</div>
</div>
</section>
</template>
@@ -0,0 +1,325 @@
/**
* features/chat/components/messages/ShippingParseReviewMessage.vue
* 出货 Agent:parse_review 阶段订单表编辑消息 UI。
*/
<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import type { ChatMessage } from '../../types/chat.types';
import type { ShippingParseReviewPayload } from '../../types/shipping.types';
import type { ShippingNoticeHeader, ShippingNoticeLine } from '../../types/shipping.api.types';
export interface ShippingParseReviewHandlers {
getPayload: (msg: ChatMessage) => ShippingParseReviewPayload | null;
updateHeader: (msg: ChatMessage, fields: Partial<ShippingNoticeHeader>) => Promise<boolean>;
updateLine: (msg: ChatMessage, lineIndex: number, patch: Partial<ShippingNoticeLine>) => Promise<boolean>;
addLine: (msg: ChatMessage, line: Partial<ShippingNoticeLine>) => Promise<boolean>;
removeLine: (msg: ChatMessage, lineIndex: number) => Promise<boolean>;
}
const { message, handlers } = defineProps<{
message: ChatMessage;
handlers: ShippingParseReviewHandlers;
}>();
const { t } = useI18n();
const editingHeader = ref(false);
const editingLineIndex = ref<number | null>(null);
const headerForm = reactive<ShippingNoticeHeader>({
customer_name: '',
customer_code: '',
ship_to: '',
po_number: '',
required_date: '',
});
const lineForm = reactive<Partial<ShippingNoticeLine>>({
reservation_id: '',
sku: '',
qty: 0,
required_date: '',
uom: '',
});
const addingLine = ref(false);
const payload = computed(() => handlers.getPayload(message));
watch(payload, (value) => {
if (!value) return;
headerForm.customer_name = value.header.customer_name ?? '';
headerForm.customer_code = value.header.customer_code ?? '';
headerForm.ship_to = value.header.ship_to ?? '';
headerForm.po_number = value.header.po_number ?? '';
headerForm.required_date = value.header.required_date ?? '';
}, { immediate: true, deep: true });
watch(
() => editingLineIndex.value,
(value) => {
if (value == null || !payload.value) return;
const line = payload.value.lines[value];
if (!line) return;
lineForm.reservation_id = line.reservation_id ?? '';
lineForm.sku = line.sku;
lineForm.qty = line.qty;
lineForm.required_date = line.required_date ?? '';
lineForm.uom = line.uom ?? '';
},
{ immediate: true },
);
const saveHeader = async () => {
const ok = await handlers.updateHeader(message, {
customer_name: headerForm.customer_name,
customer_code: headerForm.customer_code,
ship_to: headerForm.ship_to,
po_number: headerForm.po_number,
required_date: headerForm.required_date,
});
if (ok) editingHeader.value = false;
};
const saveLine = async () => {
if (editingLineIndex.value == null) return;
const ok = await handlers.updateLine(message, editingLineIndex.value, {
reservation_id: lineForm.reservation_id,
sku: lineForm.sku,
qty: Number(lineForm.qty || 0),
required_date: lineForm.required_date,
uom: lineForm.uom,
});
if (ok) editingLineIndex.value = null;
};
const startAddLine = () => {
addingLine.value = true;
editingLineIndex.value = null;
lineForm.reservation_id = '';
lineForm.sku = '';
lineForm.qty = 0;
lineForm.required_date = '';
lineForm.uom = '';
};
const saveAddedLine = async () => {
const ok = await handlers.addLine(message, {
reservation_id: lineForm.reservation_id,
sku: lineForm.sku,
qty: Number(lineForm.qty || 0),
required_date: lineForm.required_date,
uom: lineForm.uom,
});
if (ok) addingLine.value = false;
};
const removeLine = async (lineIndex: number) => {
const ok = await handlers.removeLine(message, lineIndex);
if (ok && editingLineIndex.value === lineIndex) {
editingLineIndex.value = null;
}
};
</script>
<template>
<div v-if="payload" class="space-y-4">
<div class="whitespace-pre-wrap text-sm font-medium text-secondary">{{ message.content }}</div>
<div class="space-y-4 rounded-2xl border border-default bg-surface-soft/90 p-4">
<div class="flex items-start justify-between gap-4">
<div>
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ t('chat.shippingNoticeUi.parseReviewHeader') }}</div>
<div class="mt-1 text-xs text-muted">{{ t('chat.shippingNoticeUi.taskId', { taskId: payload.taskId }) }}</div>
</div>
<button
type="button"
class="rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary transition hover:bg-surface disabled:cursor-not-allowed disabled:opacity-60"
:disabled="payload.saving"
@click="editingHeader = !editingHeader"
>
{{ editingHeader ? t('chat.shippingNoticeUi.cancelEdit') : t('chat.shippingNoticeUi.editHeader') }}
</button>
</div>
<div v-if="editingHeader" class="grid gap-3 md:grid-cols-2">
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customer') }}</span>
<input v-model="headerForm.customer_name" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customerCode') }}</span>
<input v-model="headerForm.customer_code" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
<label class="space-y-1.5 md:col-span-2">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.shipTo') }}</span>
<input v-model="headerForm.ship_to" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.poNumber') }}</span>
<input v-model="headerForm.po_number" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.requiredDate') }}</span>
<input v-model="headerForm.required_date" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
<div class="md:col-span-2 flex justify-end gap-3">
<button
type="button"
class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="payload.saving"
@click="saveHeader"
>
{{ payload.saving ? t('chat.shippingNoticeUi.saving') : t('chat.shippingNoticeUi.saveHeader') }}
</button>
</div>
</div>
<table v-else class="w-full border-collapse text-sm">
<tbody>
<tr>
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.customer') }}</th>
<td class="border border-default px-3 py-2 text-secondary">{{ payload.header.customer_name || '-' }}</td>
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.poNumber') }}</th>
<td class="border border-default px-3 py-2 text-secondary">{{ payload.header.po_number || '-' }}</td>
</tr>
<tr>
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.shipTo') }}</th>
<td class="border border-default px-3 py-2 text-secondary">{{ payload.header.ship_to || '-' }}</td>
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.requiredDate') }}</th>
<td class="border border-default px-3 py-2 text-secondary">{{ payload.header.required_date || '-' }}</td>
</tr>
</tbody>
</table>
<div class="space-y-2">
<div class="flex items-center justify-between gap-3">
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ t('chat.shippingNoticeUi.orderLines') }}</div>
<button
type="button"
class="rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary transition hover:bg-surface disabled:cursor-not-allowed disabled:opacity-60"
:disabled="payload.saving || addingLine"
@click="startAddLine"
>
{{ t('chat.shippingNoticeUi.addLine') }}
</button>
</div>
<table class="w-full border-collapse text-sm">
<thead>
<tr>
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">#</th>
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.reservationId') }}</th>
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</th>
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</th>
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.requiredDate') }}</th>
<th class="border border-default bg-surface px-3 py-2 text-left text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.actions') }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(line, lineIndex) in payload.lines" :key="`${payload.taskId}-${line.line_no || lineIndex}`">
<td class="border border-default px-3 py-2 text-secondary">{{ lineIndex + 1 }}</td>
<td class="border border-default px-3 py-2 text-secondary">{{ line.reservation_id || '-' }}</td>
<td class="border border-default px-3 py-2 text-secondary">{{ line.sku }}</td>
<td class="border border-default px-3 py-2 text-secondary">{{ line.qty }}</td>
<td class="border border-default px-3 py-2 text-secondary">{{ line.required_date || '-' }}</td>
<td class="border border-default px-3 py-2">
<button
type="button"
class="rounded-xl border border-default px-3 py-1.5 text-xs font-medium text-secondary transition hover:bg-surface disabled:cursor-not-allowed disabled:opacity-60"
:disabled="payload.saving"
@click="editingLineIndex = lineIndex"
>
{{ t('chat.shippingNoticeUi.editLine') }}
</button>
<button
type="button"
class="ml-2 rounded-xl border border-rose-200 px-3 py-1.5 text-xs font-medium text-rose-700 transition hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="payload.saving || payload.lines.length <= 1"
@click="removeLine(lineIndex)"
>
{{ t('chat.shippingNoticeUi.deleteLine') }}
</button>
</td>
</tr>
</tbody>
</table>
</div>
<div v-if="addingLine" class="space-y-3 rounded-xl border border-emerald-200 bg-emerald-50/70 p-4">
<div class="text-sm font-semibold text-emerald-700">{{ t('chat.shippingNoticeUi.addOrderLine') }}</div>
<div class="grid gap-3 md:grid-cols-2">
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.reservationId') }}</span>
<input v-model="lineForm.reservation_id" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</span>
<input v-model="lineForm.sku" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</span>
<input v-model.number="lineForm.qty" type="number" min="1" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.requiredDate') }}</span>
<input v-model="lineForm.required_date" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
</div>
<div class="flex justify-end gap-3">
<button
type="button"
class="rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition hover:bg-surface disabled:cursor-not-allowed disabled:opacity-60"
:disabled="payload.saving"
@click="addingLine = false"
>
{{ t('chat.shippingNoticeUi.cancelEdit') }}
</button>
<button
type="button"
class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="payload.saving"
@click="saveAddedLine"
>
{{ payload.saving ? t('chat.shippingNoticeUi.saving') : t('chat.shippingNoticeUi.saveAddedLine') }}
</button>
</div>
</div>
<div v-if="editingLineIndex !== null" class="space-y-3 rounded-xl border border-brand-200 bg-brand-50/70 p-4">
<div class="text-sm font-semibold text-brand-700">{{ t('chat.shippingNoticeUi.editLineTitle', { index: editingLineIndex + 1 }) }}</div>
<div class="grid gap-3 md:grid-cols-2">
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.reservationId') }}</span>
<input v-model="lineForm.reservation_id" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.sku') }}</span>
<input v-model="lineForm.sku" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.qty') }}</span>
<input v-model.number="lineForm.qty" type="number" min="1" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ t('chat.shippingNoticeUi.requiredDate') }}</span>
<input v-model="lineForm.required_date" class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400" />
</label>
</div>
<div class="flex justify-end gap-3">
<button
type="button"
class="rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition hover:bg-surface disabled:cursor-not-allowed disabled:opacity-60"
:disabled="payload.saving"
@click="editingLineIndex = null"
>
{{ t('chat.shippingNoticeUi.cancelEdit') }}
</button>
<button
type="button"
class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="payload.saving"
@click="saveLine"
>
{{ payload.saving ? t('chat.shippingNoticeUi.saving') : t('chat.shippingNoticeUi.saveLineItem') }}
</button>
</div>
</div>
</div>
</div>
</template>
@@ -1,4 +1,4 @@
/**
/**
* features/chat/composables/useChatPage.ts
* 对话页主编排:组合 SSE、Agent、附件、请假/出货、路由同步与 page/* 子模块。
*/
@@ -221,6 +221,7 @@ export function useChatPage() {
onConversationLoadFailed: shipping.onConversationLoadFailed,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
shippingBatchNoFromQuery: shipping.shippingBatchNoFromQuery,
clearHistory,
clearAttachments: attachmentApi.clearAttachments,
input,
@@ -262,6 +263,7 @@ export function useChatPage() {
getSourceMeta,
getSourceBrief,
getShippingInventoryMappingPayload: shipping.getShippingInventoryMappingPayload,
getShippingMatchResultPayload: shipping.getShippingMatchResultPayload,
canOpenQueryPreview: queryPreview.canOpen,
getQueryPreviewSummary: queryPreview.getSummary,
openQueryPreviewDialog: queryPreview.openDialog,
@@ -306,6 +308,7 @@ export function useChatPage() {
currentAgentId,
presetQuestion,
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
shippingBatchNoFromQuery: shipping.shippingBatchNoFromQuery,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
resetChatStateForAgentChange,
cancelVoiceInput: voice.cancelVoiceInput,
@@ -405,6 +408,11 @@ export function useChatPage() {
handleDeleteConfirm: dialogs.handleDeleteConfirm,
showChatRating,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
shippingBatchSummary: shipping.shippingBatchSummary,
shippingBatchTasks: shipping.shippingBatchTasks,
activeShippingTaskDetail: shipping.activeShippingTaskDetail,
shippingBatchTasksExpanded: shipping.shippingBatchTasksExpanded,
switchShippingFocusTask: shipping.switchShippingFocusTask,
shippingSuggestedPrompt: shipping.shippingSuggestedPrompt,
handleShippingInventorySelected: shipping.handleShippingInventorySelected,
useShippingSuggestedPrompt: shipping.useShippingSuggestedPrompt,
@@ -13,6 +13,7 @@ export interface UseChatRouteSyncOptions {
currentAgentId: ComputedRef<number>;
presetQuestion: ComputedRef<string>;
shippingTaskIdFromQuery: ComputedRef<string | null>;
shippingBatchNoFromQuery?: ComputedRef<string | null>;
isShippingNoticeAgent: ComputedRef<boolean>;
resetChatStateForAgentChange: () => void;
cancelVoiceInput: () => void;
@@ -38,6 +39,7 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
currentAgentId,
presetQuestion,
shippingTaskIdFromQuery,
shippingBatchNoFromQuery,
resetChatStateForAgentChange,
cancelVoiceInput,
syncCurrentUserProfile,
@@ -99,7 +101,7 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
if (convId) {
await loadConversation(convId, { force: true });
if (syncToken !== routeSyncToken) return;
} else if (shippingTaskIdFromQuery.value) {
} else if (shippingTaskIdFromQuery.value || shippingBatchNoFromQuery?.value) {
await resumeShippingTaskFromQuery();
if (syncToken !== routeSyncToken) return;
}
@@ -120,13 +122,17 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
});
watch(
() => [route.params.agentId, route.query.conversation_id, route.query.preset, route.query.task_id],
async ([nextAgentId, nextConversationId, nextPreset, nextTaskId], [prevAgentId, prevConversationId, prevPreset, prevTaskId]) => {
() => [route.params.agentId, route.query.conversation_id, route.query.preset, route.query.task_id, route.query.batch_no],
async (
[nextAgentId, nextConversationId, nextPreset, nextTaskId, nextBatchNo],
[prevAgentId, prevConversationId, prevPreset, prevTaskId, prevBatchNo],
) => {
if (
nextAgentId === prevAgentId
&& nextConversationId === prevConversationId
&& nextPreset === prevPreset
&& nextTaskId === prevTaskId
&& nextBatchNo === prevBatchNo
) {
return;
}
@@ -135,6 +141,7 @@ export function useChatRouteSync(options: UseChatRouteSyncOptions) {
nextAgentId === prevAgentId
&& nextPreset === prevPreset
&& nextTaskId === prevTaskId
&& nextBatchNo === prevBatchNo
&& nextConversationId !== prevConversationId
) {
if (typeof nextConversationId === 'string' && nextConversationId) {
@@ -1,18 +1,8 @@
/**
/**
* features/chat/composables/useChatShipping.ts
* 发货通知(出货)编排层:组合 shipping/* 子模块,对外暴露 ChatView 所需 API。
*
* 子模块职责:
* shippingText / shippingMenu / shippingIntents … 纯函数
* useChatShippingRefresh 动作按钮刷新
* useChatShippingMappingForm 库存列映射表单
* useChatShippingDecision 人工决策与手工上传
* useChatShippingMenuHandler 气泡动作按钮点击
* useChatShippingUploadHandler 文件上传与建议提示
* useChatShippingSendHandler handleSend 前置拦截
*
* 消息类型约定(写入 messages 列表):
* - shipping-inventory-mapping:库存列映射表单
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
* 依赖:shipping.api、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件再把任务状态、动作刷新、文件上传、决策与发送拦截分发给 shipping 子模块。
*/
import {
@@ -31,18 +21,29 @@ import {
createShippingLocalMessages,
createShippingMappingFormHandlers,
createShippingMenuHandlers,
createShippingParseReviewHandlers,
createShippingSendHandlers,
createShippingUploadHandlers,
extractShippingActionsDirective,
findHistorySessionForShippingTask,
findLatestShippingTaskId,
getShippingInventoryMappingPayload,
getShippingMatchResultPayload,
getShippingParseReviewPayload,
getShippingInventorySampleRowText,
hasShippingInventorySampleRows,
normalizeShippingHeaderForDisplay,
sanitizeShippingConversationText,
shippingActionButtonClass,
} from '../shipping';
import {
getWorkspaceShippingBatch,
getWorkspaceShippingTask,
switchWorkspaceShippingBatchFocusTask,
type ShippingBatchSummary,
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
@@ -78,6 +79,13 @@ export interface UseChatShippingOptions {
createNewChatView: () => void;
}
/**
* 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。
*
* 核心逻辑:统一管理当前任务/批次上下文,组合上传、映射、决策、动作刷新等子模块,并对 ChatView 暴露稳定 API。
* @param options - 聊天页依赖与响应式状态集合
* @returns 发货通知聊天场景所需的状态、事件处理器和工具函数
*/
export function useChatShipping(options: UseChatShippingOptions) {
const {
deps: { t, msg, router, route },
@@ -128,17 +136,90 @@ export function useChatShipping(options: UseChatShippingOptions) {
const value = route.query.task_id;
return typeof value === 'string' ? value.trim() : '';
});
const shippingBatchNoFromQuery = computed(() => {
const value = route.query.batch_no;
return typeof value === 'string' ? value.trim() : '';
});
const resolvedShippingTaskId = ref('');
const resolvedShippingBatchNo = ref('');
const shippingBatchSummary = ref<ShippingBatchSummary | null>(null);
const shippingBatchTasks = ref<ShippingTaskSummary[]>([]);
const shippingBatchTasksExpanded = ref(false);
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
const syncShippingBatchSummary = async (batchNo: string) => {
const normalized = String(batchNo || '').trim();
if (!normalized) {
shippingBatchSummary.value = null;
shippingBatchTasks.value = [];
return;
}
try {
const detail = await getWorkspaceShippingBatch(normalized);
resolvedShippingBatchNo.value = detail.batch_no || normalized;
shippingBatchTasks.value = Array.isArray(detail.tasks) ? detail.tasks : [];
shippingBatchSummary.value = {
id: detail.id,
batch_no: detail.batch_no,
conversation_id: detail.conversation_id,
current_focus_task_no: detail.focus_task?.task_no || detail.current_focus_task_no || null,
file_count: detail.file_count,
process_summary: detail.process_summary || null,
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();
}
} catch {
// ignore summary refresh failure in chat flow
}
};
const switchShippingFocusTask = async (taskNo: string) => {
const batchNo = getActiveShippingBatchNo();
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
if (!batchNo || !normalizedTaskNo) return false;
await switchWorkspaceShippingBatchFocusTask(batchNo, normalizedTaskNo);
resolvedShippingTaskId.value = normalizedTaskNo;
if (shippingBatchSummary.value) {
shippingBatchSummary.value = {
...shippingBatchSummary.value,
current_focus_task_no: normalizedTaskNo,
};
}
await syncShippingBatchSummary(batchNo);
return true;
};
const getActiveShippingTaskId = () =>
findLatestShippingTaskId(messages.value)
|| resolvedShippingTaskId.value
|| shippingTaskIdFromQuery.value
|| '';
const getActiveShippingBatchNo = () =>
resolvedShippingBatchNo.value
|| shippingBatchNoFromQuery.value
|| String(shippingBatchSummary.value?.batch_no || '').trim()
|| '';
const syncActiveShippingTaskDetail = async (taskId?: string) => {
const normalized = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
if (!normalized) {
activeShippingTaskDetail.value = null;
return;
}
try {
activeShippingTaskDetail.value = await getWorkspaceShippingTask(normalized);
} catch {
activeShippingTaskDetail.value = null;
}
};
const lastAssistantMessageContent = () => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const item = messages.value[i];
@@ -208,8 +289,24 @@ export function useChatShipping(options: UseChatShippingOptions) {
t,
});
const {
syncShippingParseReviewCard,
updateShippingParseReviewHeader,
updateShippingParseReviewLine,
addShippingParseReviewLine,
removeShippingParseReviewLine,
} = createShippingParseReviewHandlers({
messages,
resolvedShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
refreshShippingActions,
msg,
});
const {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
openShippingInventoryPicker,
handleShippingInventorySelected,
shippingSuggestedPrompt,
@@ -222,6 +319,8 @@ export function useChatShipping(options: UseChatShippingOptions) {
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
resolvedShippingTaskId,
resolvedShippingBatchNo,
shippingBatchSummary,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
sendShippingMenuMessage,
@@ -258,6 +357,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
attachments,
shippingAutoFlowRequested,
resolvedShippingTaskId,
getActiveShippingBatchNo,
currentAgentId,
selectedKb,
attachmentPolicy,
@@ -273,6 +373,7 @@ export function useChatShipping(options: UseChatShippingOptions) {
executeShippingDecision,
executeShippingManualUpload,
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
refreshShippingActions,
shippingSuggestedPrompt,
msg,
@@ -281,6 +382,13 @@ export function useChatShipping(options: UseChatShippingOptions) {
// ── 路由 / 会话生命周期 ───────────────────────────────────
const resumeShippingTaskFromQuery = async () => {
const batchNo = shippingBatchNoFromQuery.value;
if (batchNo && isShippingNoticeAgent.value) {
await syncShippingBatchSummary(batchNo);
if (!shippingTaskIdFromQuery.value && resolvedShippingTaskId.value) {
return;
}
}
const taskId = shippingTaskIdFromQuery.value;
if (!taskId || !isShippingNoticeAgent.value) return;
if (route.query.conversation_id) return;
@@ -304,13 +412,17 @@ export function useChatShipping(options: UseChatShippingOptions) {
const onConversationLoadedEmpty = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
await router.replace({ path: route.path, query: { task_id: shippingTaskIdFromQuery.value } });
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
await router.replace({ path: route.path, query: nextQuery });
};
const onConversationLoadFailed = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
createNewChatView();
void router.replace({ path: route.path, query: { task_id: shippingTaskIdFromQuery.value } });
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
void router.replace({ path: route.path, query: nextQuery });
input.value = t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value });
await invokeHandleSend?.();
};
@@ -327,8 +439,22 @@ export function useChatShipping(options: UseChatShippingOptions) {
].join('|');
});
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
void refreshShippingActions();
void refreshShippingActions().then(async () => {
const taskId = getActiveShippingTaskId();
await Promise.all([
syncShippingParseReviewCard(taskId),
syncActiveShippingTaskDetail(taskId),
]);
});
});
watch([resolvedShippingBatchNo, shippingBatchNoFromQuery], ([batchNo, queryBatchNo]) => {
const nextBatchNo = String(batchNo || queryBatchNo || '').trim();
if (!nextBatchNo) {
shippingBatchSummary.value = null;
return;
}
void syncShippingBatchSummary(nextBatchNo);
}, { immediate: true });
return {
shippingBindSend,
@@ -339,13 +465,27 @@ export function useChatShipping(options: UseChatShippingOptions) {
pendingShippingUploadTaskId,
allowsSendWithAttachmentsOnly,
shippingTaskIdFromQuery,
shippingBatchNoFromQuery,
resolvedShippingBatchNo,
shippingBatchSummary,
shippingBatchTasks,
shippingBatchTasksExpanded,
activeShippingTaskDetail,
getActiveShippingBatchNo,
switchShippingFocusTask,
resumeShippingTaskFromQuery,
normalizeShippingHeaderForDisplay,
getShippingInventoryMappingPayload,
getShippingMatchResultPayload,
getShippingParseReviewPayload,
hasShippingInventorySampleRows,
getShippingInventorySampleRowText,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
updateShippingParseReviewHeader,
updateShippingParseReviewLine,
addShippingParseReviewLine,
removeShippingParseReviewLine,
handleShippingActionClick,
handleShippingInventorySelected,
shippingActionButtonClass,
@@ -22,6 +22,7 @@ export interface ChatPageConversationContext {
onConversationLoadFailed: () => Promise<void>;
isShippingNoticeAgent: ComputedRef<boolean>;
shippingTaskIdFromQuery: ComputedRef<string>;
shippingBatchNoFromQuery?: ComputedRef<string>;
clearHistory: () => void;
clearAttachments: () => void;
input: Ref<string>;
@@ -51,7 +52,11 @@ export function createChatPageConversationApi(ctx: ChatPageConversationContext)
} catch (e) {
console.error('Failed to load conversation', e);
await ctx.onConversationLoadFailed();
if (ctx.isShippingNoticeAgent.value && ctx.shippingTaskIdFromQuery.value && !ctx.isThinking.value) {
if (
ctx.isShippingNoticeAgent.value
&& (ctx.shippingTaskIdFromQuery.value || ctx.shippingBatchNoFromQuery?.value)
&& !ctx.isThinking.value
) {
return;
}
ctx.deps.msg.warning(ctx.deps.t('chat.historyLoadFailed'));
@@ -1,4 +1,4 @@
/**
/**
* 对话页:子组件 inject 用的 handlers 对象打包(请假表单、出货映射、消息气泡)。
*/
import type { LeaveMessageHandlers } from '../components/messages/LeaveMessageBlock.vue';
@@ -31,8 +31,14 @@ type ShippingHandlerSource = Pick<
| 'normalizeShippingHeaderForDisplay'
| 'hasShippingInventorySampleRows'
| 'getShippingInventorySampleRowText'
| 'getShippingParseReviewPayload'
| 'getShippingMatchResultPayload'
| 'reuploadShippingInventoryFromMappingForm'
| 'applyShippingInventoryMappingForm'
| 'updateShippingParseReviewHeader'
| 'updateShippingParseReviewLine'
| 'addShippingParseReviewLine'
| 'removeShippingParseReviewLine'
>;
/** 请假消息块 handlers(LeaveMessageBlock) */
@@ -62,8 +68,16 @@ export function createShippingMappingHandlers(shipping: ShippingHandlerSource):
normalizeHeader: shipping.normalizeShippingHeaderForDisplay,
hasSampleRows: shipping.hasShippingInventorySampleRows,
getSampleRowText: shipping.getShippingInventorySampleRowText,
getParseReviewPayload: shipping.getShippingParseReviewPayload,
getMatchResultPayload: shipping.getShippingMatchResultPayload,
reupload: shipping.reuploadShippingInventoryFromMappingForm,
apply: shipping.applyShippingInventoryMappingForm,
updateParseReviewHeader: shipping.updateShippingParseReviewHeader,
updateParseReviewLine: shipping.updateShippingParseReviewLine,
updateHeader: shipping.updateShippingParseReviewHeader,
updateLine: shipping.updateShippingParseReviewLine,
addLine: shipping.addShippingParseReviewLine,
removeLine: shipping.removeShippingParseReviewLine,
};
}
@@ -1,10 +1,11 @@
/**
/**
* 对话页:Markdown 渲染、消息可见性判断、PLM/请假链接点击。
*/
import { computed } from 'vue';
import { marked } from 'marked';
import type { ChatMessageBubbleHandlers } from '../components/messages/ChatMessageBubble.vue';
import type { ChatMessage, SourceFileLink } from '../types/chat.types';
import type { ShippingMatchResultPayload } from '../types/shipping.types';
import type { Ref } from 'vue';
marked.setOptions({ gfm: true, breaks: true });
@@ -24,6 +25,7 @@ export interface ChatPageMarkdownContext {
getSourceMeta: ChatMessageBubbleHandlers['getSourceMeta'];
getSourceBrief: ChatMessageBubbleHandlers['getSourceBrief'];
getShippingInventoryMappingPayload: ChatMessageBubbleHandlers['getShippingInventoryMappingPayload'];
getShippingMatchResultPayload: (msg: ChatMessage) => ShippingMatchResultPayload | null;
canOpenQueryPreview: ChatMessageBubbleHandlers['canOpenQueryPreview'];
getQueryPreviewSummary: ChatMessageBubbleHandlers['getQueryPreviewSummary'];
openQueryPreviewDialog: ChatMessageBubbleHandlers['openQueryPreviewDialog'];
@@ -87,6 +89,7 @@ export function createChatPageMarkdownApi(ctx: ChatPageMarkdownContext) {
renderMarkdown,
onMarkdownClick: handleChatMarkdownClick,
getShippingInventoryMappingPayload: ctx.getShippingInventoryMappingPayload,
getShippingMatchResultPayload: ctx.getShippingMatchResultPayload,
canOpenQueryPreview: ctx.canOpenQueryPreview,
getQueryPreviewSummary: ctx.getQueryPreviewSummary,
openQueryPreviewDialog: ctx.openQueryPreviewDialog,
+10 -1
View File
@@ -1,4 +1,9 @@
/** 出货(shipping)子模块 barrel:纯函数 + handler 工厂 + 动作刷新 */
/**
* features/chat/shipping/index.ts
* 用途:统一导出发货通知聊天子模块的纯函数、handler 工厂与辅助工具。
* 依赖:shipping/* 子模块本身,不承载业务逻辑。
* 逻辑:由 useChatShipping 作为聚合入口导入本 barrel,再分发到具体 handler/composable 文件。
*/
export * from './shippingText';
export * from './shippingMenu';
export * from './shippingIntents';
@@ -7,10 +12,14 @@ export * from './shippingTaskId';
export * from './shippingDownload';
export * from './shippingDecisionFormat';
export * from './shippingUploadPrompt';
export * from './shippingParseReview';
export * from './shippingMatchResult';
export * from './shippingStepper';
export * from './shippingLocalMessages';
export * from './shippingConversation';
export * from './useChatShippingRefresh';
export * from './useChatShippingMappingForm';
export * from './useChatShippingParseReview';
export * from './useChatShippingDecision';
export * from './useChatShippingMenuHandler';
export * from './useChatShippingUploadHandler';
@@ -6,6 +6,11 @@
import { resolveShippingNumericChoice } from './shippingMenu';
import type { ShippingMenuAction } from '../types/shipping.types';
export interface ShippingTaskSwitchIntent {
mode: 'next' | 'prev' | 'task';
taskNo?: string;
}
export function parseShippingColumnMappingFromText(content: string): Record<string, string> | null {
const raw = String(content || '').trim();
if (!raw) return null;
@@ -88,4 +93,20 @@ export function isShippingDownloadExcelIntent(text: string): boolean {
].some((pattern) => pattern.test(normalized));
}
export function parseShippingTaskSwitchIntent(text: string): ShippingTaskSwitchIntent | null {
const normalized = String(text || '').trim();
if (!normalized) return null;
const taskMatch = normalized.match(/SN-\d{8}-[A-F0-9]{8}/i);
if (taskMatch?.[0] && /(切|切到|切换|goto|go to|switch)/i.test(normalized)) {
return { mode: 'task', taskNo: taskMatch[0].toUpperCase() };
}
if (/^(下一票|下一单|下一个|next)$/i.test(normalized) || /切到下一票/.test(normalized)) {
return { mode: 'next' };
}
if (/^(上一票|上一单|上一个|prev|previous)$/i.test(normalized) || /切到上一票/.test(normalized)) {
return { mode: 'prev' };
}
return null;
}
export type { ShippingMenuAction };
@@ -0,0 +1,15 @@
/**
* 出货聊天:匹配结果卡片 payload 读取。
*/
import type { ChatMessage } from '../types/chat.types';
import type { ShippingMatchResultPayload } from '../types/shipping.types';
export function getShippingMatchResultPayload(chatMsg: ChatMessage): ShippingMatchResultPayload | null {
if (!chatMsg || chatMsg.type !== 'shipping-match-result') return null;
const payload = chatMsg.payload;
if (!payload || typeof payload !== 'object') return null;
const taskId = String((payload as ShippingMatchResultPayload).taskId || '').trim();
const lineResults = (payload as ShippingMatchResultPayload).line_results;
if (!taskId || !Array.isArray(lineResults)) return null;
return payload as ShippingMatchResultPayload;
}
@@ -0,0 +1,16 @@
/**
* 出货聊天:parse_review 订单表消息 payload 读取。
*/
import type { ChatMessage } from '../types/chat.types';
import type { ShippingParseReviewPayload } from '../types/shipping.types';
export function getShippingParseReviewPayload(chatMsg: ChatMessage): ShippingParseReviewPayload | null {
if (!chatMsg || chatMsg.type !== 'shipping-parse-review') return null;
const payload = chatMsg.payload;
if (!payload || typeof payload !== 'object') return null;
const taskId = String((payload as ShippingParseReviewPayload).taskId || '').trim();
const checkpoint = String((payload as ShippingParseReviewPayload).checkpoint || '').trim();
const lines = (payload as ShippingParseReviewPayload).lines;
if (!taskId || !checkpoint || !Array.isArray(lines)) return null;
return payload as ShippingParseReviewPayload;
}
@@ -0,0 +1,96 @@
/**
* 出货七步 Stepper:基于现有 shipping task 状态推导前端步骤展示。
*/
export interface ShippingTaskStepperSource {
process_status?: string | null;
review_status?: string | null;
pending_human_reason?: string | null;
match_status?: string | null;
export_file_name?: string | null;
current_step?: string | null;
}
export interface ShippingWorkflowStepItem {
id: string;
label: string;
status: 'completed' | 'current' | 'pending' | 'blocked';
}
export const SHIPPING_WORKFLOW_STEP_LABELS = [
'chat.shippingNoticeUi.stepper.noticeSubmit',
'chat.shippingNoticeUi.stepper.parseConfirm',
'chat.shippingNoticeUi.stepper.inventoryPrepare',
'chat.shippingNoticeUi.stepper.alignConfirm',
'chat.shippingNoticeUi.stepper.matchInventory',
'chat.shippingNoticeUi.stepper.generateFile',
'chat.shippingNoticeUi.stepper.uploadFreight',
] as const;
function deriveCurrentIndex(task: ShippingTaskStepperSource | null | undefined): number {
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 (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;
if (reviewStatus === 'align_review' || pendingReason === 'align_review') return 3;
if (processStatus === 'inventory_ready' || matchStatus) return 4;
if (
processStatus === 'waiting_inventory'
|| pendingReason === 'map_infer'
|| pendingReason === 'rpa_pending'
|| pendingReason === 'inv_unavail'
|| pendingReason === 'rpa_exhausted'
) {
return 2;
}
if (
processStatus === 'parsed'
|| processStatus === 'pending_review'
|| reviewStatus === 'pending_confirm'
|| reviewStatus === 'parse_review'
|| reviewStatus === 'rsv_required'
|| pendingReason === 'low_confidence'
|| pendingReason === 'rsv_required'
) {
return 1;
}
return 0;
}
export function buildShippingWorkflowSteps(
task: ShippingTaskStepperSource | null | undefined,
): ShippingWorkflowStepItem[] {
const currentIndex = deriveCurrentIndex(task);
const reviewStatus = String(task?.review_status || '').trim();
const pendingReason = String(task?.pending_human_reason || '').trim();
const processStatus = String(task?.process_status || '').trim();
return SHIPPING_WORKFLOW_STEP_LABELS.map((label, index) => {
let status: ShippingWorkflowStepItem['status'] = 'pending';
if (index < currentIndex) {
status = 'completed';
} else if (index === currentIndex) {
status = 'current';
}
if (
(index === 1 && (reviewStatus === 'parse_review' || pendingReason === 'low_confidence' || pendingReason === 'rsv_required'))
|| (index === 3 && (reviewStatus === 'align_review' || pendingReason === 'align_review'))
|| (index === 4 && (reviewStatus === 'shortage_review' || pendingReason === 'shortage_review' || pendingReason === 'shortage'))
|| (index === 6 && processStatus === 'upload_failed')
) {
status = 'blocked';
}
return {
id: `shipping-step-${index + 1}`,
label,
status,
};
});
}
@@ -1,5 +1,8 @@
/**
* 出货聊天:人工决策提交(confirm/reject/reparse 等)与手工上传标记。
/**
* features/chat/shipping/useChatShippingDecision.ts
* 用途:封装人工决策提交与手工上传标记逻辑。
* 依赖:shipping.api、shippingDecisionFormat、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件负责把 confirm/reject/reparse 等决策提交到后端,并生成聊天区本地消息。
*/
import {
autoProgressWorkspaceShippingTask,
@@ -26,6 +29,13 @@ export interface ShippingDecisionContext {
t: (key: string, params?: Record<string, unknown>) => string;
}
/**
* 创建发货通知决策处理器。
*
* 核心逻辑:根据决策类型调用对应后端接口,同步本地用户/助手消息,并在需要时刷新历史与动作按钮。
* @param ctx - 决策处理上下文
* @returns 人工决策与手工上传确认处理函数
*/
export function createShippingDecisionHandlers(ctx: ShippingDecisionContext) {
const syncHistoryIfNeeded = async () => {
if (!ctx.conversationId.value && ctx.history.value.length === 0) {
@@ -1,5 +1,8 @@
/**
* 出货聊天:库存列映射表单(打开、应用、重传)。
/**
* features/chat/shipping/useChatShippingMappingForm.ts
* 用途:管理库存列映射表单的打开、提交和重新上传交互。
* 依赖:shipping.api、shippingMapping、chat.types、Vue nextTick。
* 逻辑:由 useChatShipping 调用本文件;本文件负责把 schema preview 渲染成聊天卡片,并把表单提交回后端映射接口。
*/
import { nextTick } from 'vue';
import {
@@ -25,6 +28,13 @@ export interface ShippingMappingFormContext {
msg: { warning: (text: string) => void };
}
/**
* 创建库存列映射表单处理器。
*
* 核心逻辑:按任务号打开或复用映射卡片,提交 map_json 到后端,并在成功后刷新动作按钮。
* @param ctx - 库存映射表单上下文
* @returns 打开、应用和重传库存映射表单的处理函数
*/
export function createShippingMappingFormHandlers(ctx: ShippingMappingFormContext) {
const scrollToLastShippingInventoryMapping = async (): Promise<boolean> => {
const container = ctx.chatScrollContainer.value;
@@ -1,15 +1,19 @@
/**
* 出货聊天:消息气泡动作按钮与菜单项点击分发。
*
* 按 action.id 路由到 API 调用、决策提交、文件选择器或 Dify 菜单消息。
/**
* features/chat/shipping/useChatShippingMenuHandler.ts
* 用途:分发聊天气泡动作按钮点击,连接 API、决策处理、下载和文件选择器。
* 依赖:shipping.api、shippingDownload、shipping 常量、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件根据 action.id 决定触发后端接口、本地消息落库或前端 UI 行为。
*/
import {
generateWorkspaceShippingExcel,
matchWorkspaceShippingInventory,
type ShippingDecisionResponse,
type ShippingMatchLineResult,
} from '@/features/chat/api/shipping.api';
import { SHIPPING_DECISION_ACTIONS } from '../constants/shipping';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
import type { ChatMessage } from '../types/chat.types';
import type { ShippingMatchResultPayload } from '../types/shipping.types';
import type { Ref } from 'vue';
export interface ShippingMenuHandlerContext {
@@ -28,7 +32,39 @@ export interface ShippingMenuHandlerContext {
t: (key: string) => string;
}
/**
* 创建发货通知动作菜单处理器。
*
* 核心逻辑:按 action.id 分流到生成 Excel、库存匹配、人工决策、手工上传确认等前后端动作。
* @param ctx - 动作菜单上下文
* @returns 菜单动作与按钮点击处理函数
*/
export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
const buildMatchResultPayload = (
taskId: string,
result: ShippingDecisionResponse & { action_buttons?: Array<{ id: string; label: string; message: string; variant?: 'primary' | 'secondary' | 'danger' }> },
): ShippingMatchResultPayload => {
const data = (result?.data && typeof result.data === 'object') ? result.data as Record<string, unknown> : {};
const lineResults = Array.isArray(data.line_results)
? data.line_results as ShippingMatchLineResult[]
: [];
const shortageRaw = data.shortage && typeof data.shortage === 'object'
? data.shortage as { lines?: ShippingMatchLineResult[] }
: null;
return {
taskId,
match_status: typeof data.match_status === 'string' ? data.match_status : null,
line_results: lineResults,
shortage_lines: Array.isArray(shortageRaw?.lines) ? shortageRaw.lines : [],
action_buttons: Array.isArray(result.action_buttons)
? result.action_buttons.map((action) => ({
...action,
variant: action.variant || 'secondary',
}))
: [],
};
};
const handleShippingMenuAction = async (
action: { id?: string; message: string },
chatMsg?: ChatMessage & { shipping_actions_used?: boolean },
@@ -71,11 +107,12 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) {
};
const assistantMsg: ChatMessage = {
role: 'assistant',
type: 'text',
type: 'shipping-match-result',
content: [
String(result.message || '').trim(),
`任务编号:${taskId}`,
].filter(Boolean).join('\n'),
payload: buildMatchResultPayload(taskId, result),
local_id: ctx.newLocalMessageId('shipping-assistant'),
local_only: true,
};
@@ -0,0 +1,209 @@
/**
* features/chat/shipping/useChatShippingParseReview.ts
* 用途:管理 parse_review 阶段的订单表卡片,包括打开、同步和增删改保存。
* 依赖:shipping.api、shippingParseReview、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件在聊天区维护解析复核卡片,并把用户修订同步回后端 notice 编辑接口。
*/
import {
addWorkspaceShippingNoticeLine,
getShippingChatActions,
getWorkspaceShippingTask,
removeWorkspaceShippingNoticeLine,
updateWorkspaceShippingNoticeFields,
updateWorkspaceShippingNoticeLine,
type ShippingNoticeHeader,
type ShippingNoticeLine,
} from '@/features/chat/api/shipping.api';
import { getShippingParseReviewPayload } from './shippingParseReview';
import type { ChatMessage } from '../types/chat.types';
import type { ShippingParseReviewPayload } from '../types/shipping.types';
import type { Ref } from 'vue';
export interface ShippingParseReviewContext {
messages: Ref<ChatMessage[]>;
resolvedShippingTaskId: Ref<string>;
newLocalMessageId: (prefix: string) => string;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
refreshShippingActions: () => Promise<void>;
msg: { warning: (text: string) => void };
}
function buildParseReviewPayload(
taskId: string,
detail: Awaited<ReturnType<typeof getWorkspaceShippingTask>>,
checkpoint: string,
): ShippingParseReviewPayload {
return {
taskId,
checkpoint,
header: {
customer_name: detail.customer_name ?? null,
customer_code: detail.customer_code ?? null,
ship_to: detail.ship_to ?? null,
po_number: detail.po_number ?? null,
required_date: detail.required_date ?? null,
},
lines: Array.isArray(detail.lines) ? detail.lines : [],
saving: false,
};
}
/**
* 创建发货通知 parse review 卡片处理器。
*
* 核心逻辑:根据任务详情与 checkpoint 维护本地复核卡片,并把单头/订单行编辑回写到后端。
* @param ctx - parse review 卡片上下文
* @returns 复核卡片同步与编辑处理函数集合
*/
export function createShippingParseReviewHandlers(ctx: ShippingParseReviewContext) {
const removeParseReviewMessageForTask = (taskId: string) => {
const normalized = String(taskId || '').trim().toUpperCase();
if (!normalized) return;
ctx.messages.value = ctx.messages.value.filter((msg) => {
const payload = getShippingParseReviewPayload(msg);
return payload?.taskId?.trim().toUpperCase() !== normalized;
});
};
const upsertParseReviewMessage = async (payload: ShippingParseReviewPayload) => {
const normalized = String(payload.taskId || '').trim().toUpperCase();
const existing = ctx.messages.value.find((msg) => {
const current = getShippingParseReviewPayload(msg);
return current?.taskId?.trim().toUpperCase() === normalized;
});
if (existing) {
existing.content = `请确认或修订以下解析结果。\n任务编号:${normalized}`;
existing.payload = payload;
existing.local_only = true;
return;
}
const reviewMsg: ChatMessage = {
role: 'assistant',
type: 'shipping-parse-review',
content: `请确认或修订以下解析结果。\n任务编号:${normalized}`,
payload,
local_id: ctx.newLocalMessageId('shipping-parse-review'),
local_only: true,
};
ctx.messages.value.push(reviewMsg);
await ctx.saveLocalMessageToBackend(reviewMsg);
};
const syncShippingParseReviewCard = async (taskId?: string): Promise<boolean> => {
const normalized = String(taskId || ctx.resolvedShippingTaskId.value || '').trim().toUpperCase();
if (!normalized) return false;
try {
const [detail, actions] = await Promise.all([
getWorkspaceShippingTask(normalized),
getShippingChatActions(normalized),
]);
const checkpoint = String(actions.checkpoint || '').trim();
if (checkpoint !== 'parse_review') {
removeParseReviewMessageForTask(normalized);
return false;
}
await upsertParseReviewMessage(buildParseReviewPayload(normalized, detail, checkpoint));
return true;
} catch {
return false;
}
};
const updateShippingParseReviewHeader = async (
msgObj: ChatMessage,
fields: Partial<ShippingNoticeHeader>,
) => {
const payload = getShippingParseReviewPayload(msgObj);
if (!payload || payload.saving) return false;
payload.saving = true;
const taskId = String(payload.taskId || '').trim().toUpperCase();
try {
await updateWorkspaceShippingNoticeFields(taskId, fields, '聊天区订单表修订');
await syncShippingParseReviewCard(taskId);
await ctx.refreshShippingActions();
return true;
} catch (e: unknown) {
ctx.msg.warning(e instanceof Error ? e.message : '更新解析结果失败');
return false;
} finally {
const current = getShippingParseReviewPayload(msgObj);
if (current) current.saving = false;
}
};
const updateShippingParseReviewLine = async (
msgObj: ChatMessage,
lineIndex: number,
patch: Partial<ShippingNoticeLine>,
) => {
const payload = getShippingParseReviewPayload(msgObj);
if (!payload || payload.saving) return false;
payload.saving = true;
const taskId = String(payload.taskId || '').trim().toUpperCase();
try {
await updateWorkspaceShippingNoticeLine(taskId, lineIndex, patch, '聊天区订单表修订');
await syncShippingParseReviewCard(taskId);
await ctx.refreshShippingActions();
return true;
} catch (e: unknown) {
ctx.msg.warning(e instanceof Error ? e.message : '更新解析结果失败');
return false;
} finally {
const current = getShippingParseReviewPayload(msgObj);
if (current) current.saving = false;
}
};
const addShippingParseReviewLine = async (
msgObj: ChatMessage,
line: Partial<ShippingNoticeLine>,
) => {
const payload = getShippingParseReviewPayload(msgObj);
if (!payload || payload.saving) return false;
payload.saving = true;
const taskId = String(payload.taskId || '').trim().toUpperCase();
try {
await addWorkspaceShippingNoticeLine(taskId, line, '聊天区订单表新增行');
await syncShippingParseReviewCard(taskId);
await ctx.refreshShippingActions();
return true;
} catch (e: unknown) {
ctx.msg.warning(e instanceof Error ? e.message : '新增订单行失败');
return false;
} finally {
const current = getShippingParseReviewPayload(msgObj);
if (current) current.saving = false;
}
};
const removeShippingParseReviewLine = async (
msgObj: ChatMessage,
lineIndex: number,
) => {
const payload = getShippingParseReviewPayload(msgObj);
if (!payload || payload.saving) return false;
payload.saving = true;
const taskId = String(payload.taskId || '').trim().toUpperCase();
try {
await removeWorkspaceShippingNoticeLine(taskId, lineIndex, '聊天区订单表删除行');
await syncShippingParseReviewCard(taskId);
await ctx.refreshShippingActions();
return true;
} catch (e: unknown) {
ctx.msg.warning(e instanceof Error ? e.message : '删除订单行失败');
return false;
} finally {
const current = getShippingParseReviewPayload(msgObj);
if (current) current.saving = false;
}
};
return {
getShippingParseReviewPayload,
syncShippingParseReviewCard,
updateShippingParseReviewHeader,
updateShippingParseReviewLine,
addShippingParseReviewLine,
removeShippingParseReviewLine,
};
}
@@ -1,8 +1,8 @@
/**
* 出货聊天:助手消息动作按钮刷新(有状态 composable 工厂)。
*
* 按 taskId 拉取 getShippingChatActions,写入 messages[].shipping_actions;
* 终态 checkpoint 时清除所有按钮。
/**
* features/chat/shipping/useChatShippingRefresh.ts
* 用途:刷新聊天区发货通知动作按钮,把后端 checkpoint/action_buttons 同步到消息气泡。
* 依赖:shipping.api、shippingMenu、shippingTaskId、shippingNoticeActions 常量、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件根据当前 taskId 拉取动作配置并回写到 messages[].shipping_actions。
*/
import {
getShippingChatActions,
@@ -27,10 +27,23 @@ export interface ShippingRefreshContext {
shippingConversationTaskIdCache: Ref<Record<string, string>>;
}
/**
* 判断某条助手消息后面是否已经出现新的用户回复。
* @param msgs - 当前消息列表
* @param index - 目标助手消息索引
* @returns `true` 表示该消息已被后续用户输入“盖住”
*/
export function assistantMessageHasLaterUserReply(msgs: Array<{ role?: string }>, index: number): boolean {
return msgs.slice(index + 1).some((item) => item.role === 'user');
}
/**
* 创建发货通知动作按钮刷新器。
*
* 核心逻辑:优先按 taskId 拉取后端 action_buttons,失败时回退到消息文本指令解析,并在终态 checkpoint 清空旧按钮。
* @param ctx - 发货通知聊天上下文
* @returns 动作刷新函数
*/
export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
let shippingActionsRequestSeq = 0;
@@ -145,6 +158,9 @@ export function createShippingActionsRefresher(ctx: ShippingRefreshContext) {
}
buttons = resolved.buttons;
}
if (chatMsg.type === 'shipping-match-result' && chatMsg.payload && typeof chatMsg.payload === 'object') {
(chatMsg.payload as { action_buttons?: ShippingActionButton[] }).action_buttons = buttons;
}
chatMsg.shipping_actions = buttons.length ? buttons : undefined;
});
};
@@ -1,9 +1,15 @@
/**
* 出货聊天:handleSend 前置拦截(菜单数字、决策文本、列映射、附件自动流程)。
*
* 返回 true 表示已消费本次发送,ChatView 不再走默认 Dify 流程。
/**
* features/chat/shipping/useChatShippingSendHandler.ts
* 用途:在聊天发送前拦截发货通知专属意图,如切票、决策文本、列映射和附件自动流程。
* 依赖:shipping.api、shippingIntents、shippingMenu、shippingMapping、shippingDownload、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件优先消费 shipping 领域意图,只有未命中时才放行到默认 Dify 对话链路。
*/
import { applyWorkspaceShippingInventoryMapping, generateWorkspaceShippingExcel } from '@/features/chat/api/shipping.api';
import {
applyWorkspaceShippingInventoryMapping,
generateWorkspaceShippingExcel,
getWorkspaceShippingBatch,
switchWorkspaceShippingBatchFocusTask,
} from '@/features/chat/api/shipping.api';
import { SHIPPING_MENU_ACTION_SPECS } from '../constants/shipping';
import { buildShippingFieldAlignmentText } from './shippingMapping';
import { downloadWorkspaceShippingExcelFile } from './shippingDownload';
@@ -12,12 +18,12 @@ import {
isShippingGenerateExcelIntent,
isShippingInventoryUploadIntent,
isShippingManualUploadIntent,
parseShippingTaskSwitchIntent,
parseShippingColumnMappingFromText,
} from './shippingIntents';
import { resolveShippingDecisionFromText, resolveShippingNumericChoice } from './shippingMenu';
import { classifyShippingUploadFile } from './shippingUploadPrompt';
import { extractExt } from '../constants/shipping';
import { ensureShippingHistorySynced } from './shippingConversation';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
import type { ComputedRef, Ref } from 'vue';
@@ -33,6 +39,7 @@ export interface ShippingSendHandlerContext {
attachments: Ref<PendingAttachment[]>;
shippingAutoFlowRequested: Ref<boolean>;
resolvedShippingTaskId: Ref<string>;
getActiveShippingBatchNo: () => string;
currentAgentId: ComputedRef<number>;
selectedKb: Ref<string>;
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
@@ -53,13 +60,66 @@ export interface ShippingSendHandlerContext {
executeShippingDecision: (decision: string, displayText?: string) => Promise<boolean>;
executeShippingManualUpload: (taskId: string, displayText?: string) => Promise<boolean>;
handleShippingAutoUploadFile: (file: File) => Promise<void>;
handleShippingAutoUploadNoticeBatch: (files: File[]) => Promise<void>;
refreshShippingActions: () => Promise<void>;
shippingSuggestedPrompt: ComputedRef<string>;
msg: { warning: (text: string) => void; info: (text: string) => void };
t: (key: string) => string;
}
/**
* 创建发货通知发送拦截器。
*
* 核心逻辑:识别切换任务、数字菜单、决策文本、映射文本、上传/导出意图,并在命中时直接走本地前后端流程。
* @param ctx - 发送拦截上下文
* @returns 发送前文本与附件自动流程处理函数;返回 true 表示已消费本次发送
*/
export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
const trySwitchShippingTask = async (content: string): Promise<boolean> => {
const intent = parseShippingTaskSwitchIntent(content);
if (!intent) return false;
const batchNo = ctx.getActiveShippingBatchNo();
if (!batchNo) {
ctx.msg.warning('当前没有可切换的批次');
return true;
}
try {
const detail = await getWorkspaceShippingBatch(batchNo);
const tasks = Array.isArray(detail.tasks) ? detail.tasks : [];
if (tasks.length <= 1) {
ctx.msg.info('当前批次只有 1 票,无需切换');
return true;
}
const focusTaskNo = String(detail.focus_task?.task_no || detail.current_focus_task_no || '').trim().toUpperCase();
const currentIndex = Math.max(tasks.findIndex((item) => String(item.task_no || '').trim().toUpperCase() === focusTaskNo), 0);
let targetTaskNo = '';
if (intent.mode === 'task') {
targetTaskNo = String(intent.taskNo || '').trim().toUpperCase();
} else if (intent.mode === 'next') {
targetTaskNo = String(tasks[Math.min(currentIndex + 1, tasks.length - 1)]?.task_no || '').trim().toUpperCase();
} else {
targetTaskNo = String(tasks[Math.max(currentIndex - 1, 0)]?.task_no || '').trim().toUpperCase();
}
if (!targetTaskNo) {
ctx.msg.warning('未找到要切换的任务');
return true;
}
if (targetTaskNo === focusTaskNo) {
ctx.msg.info(intent.mode === 'next' ? '已经是最后一票' : intent.mode === 'prev' ? '已经是第一票' : '已在当前任务');
return true;
}
await switchWorkspaceShippingBatchFocusTask(batchNo, targetTaskNo);
ctx.resolvedShippingTaskId.value = targetTaskNo;
await ctx.pushShippingLocalUserMessage(content.trim());
await ctx.pushShippingLocalAssistantMessage(`已切换到任务 ${targetTaskNo},请继续当前票处理。`);
void ctx.refreshShippingActions();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '切换任务失败';
ctx.msg.warning(errorMessage);
}
return true;
};
const tryHandleShippingAttachmentAutoFlow = async (
textOrEvent: string | Event | undefined,
_content: string,
@@ -93,29 +153,16 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
return true;
}
if (!trimmed) {
const prompt = ctx.shippingSuggestedPrompt.value || '解析发货通知并创建任务';
let files: ChatUploadFileSpec[] = [];
if (ctx.attachmentPolicy.value.anyEnabled && ctx.attachments.value.length > 0) {
try {
files = await ctx.buildFileSpecsForSend();
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : 'unknown error';
ctx.msg.warning(`附件处理失败:${errorMessage}`);
return true;
}
}
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
await ctx.sendMessage(prompt, ctx.currentAgentId.value, ctx.selectedKb.value, files);
await ensureShippingHistorySynced({
conversationId: ctx.conversationId,
history: ctx.history,
loadHistory: ctx.loadHistory,
getActiveShippingTaskId: ctx.getActiveShippingTaskId,
currentAgentId: ctx.currentAgentId,
selectedKb: ctx.selectedKb,
sendMessage: ctx.sendMessage,
});
try {
const prompt = ctx.shippingSuggestedPrompt.value || '解析发货通知并创建任务';
await ctx.pushShippingLocalUserMessage(prompt);
await ctx.handleShippingAutoUploadNoticeBatch(localFiles.map((item) => item.file));
} catch (e: unknown) {
const errorMessage = e instanceof Error ? e.message : '文件处理失败';
ctx.msg.warning(errorMessage);
}
return true;
}
return false;
@@ -127,6 +174,11 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
_trimmed: string,
): Promise<boolean> => {
if (!ctx.isShippingNoticeAgent.value) return false;
if (await trySwitchShippingTask(content)) {
if (typeof textOrEvent !== 'string') ctx.input.value = '';
ctx.attachments.value = [];
return true;
}
const assistantCtx = ctx.lastAssistantMessageContent();
const menuChoice = resolveShippingNumericChoice(content, assistantCtx);
if (menuChoice) {
@@ -1,10 +1,13 @@
/**
* 出货聊天:库存/发货通知文件上传、隐藏 file input、附件建议提示。
/**
* features/chat/shipping/useChatShippingUploadHandler.ts
* 用途:处理发货通知与库存文件上传、批量建单和附件建议提示。
* 依赖:shipping.api、shippingUploadPrompt、shipping 常量、chat.types。
* 逻辑:由 useChatShipping 调用本文件;本文件识别附件类型后决定是创建任务/批次还是上传库存,并把结果同步到聊天上下文。
*/
import { computed } from 'vue';
import {
createWorkspaceShippingBatchFromNotices,
createWorkspaceShippingTask,
createWorkspaceShippingTaskFromNotice,
uploadWorkspaceShippingInventory,
} from '@/features/chat/api/shipping.api';
import { extractExt } from '../constants/shipping';
@@ -20,6 +23,8 @@ export interface ShippingUploadHandlerContext {
shippingInventoryPickerRef: Ref<HTMLInputElement | null>;
pendingShippingUploadTaskId: Ref<string>;
resolvedShippingTaskId: Ref<string>;
resolvedShippingBatchNo: Ref<string>;
shippingBatchSummary: Ref<unknown | null>;
shippingInventorySchemaPreviewCache: Ref<Record<string, unknown>>;
getActiveShippingTaskId: () => string;
sendShippingMenuMessage: (message: string) => Promise<void>;
@@ -29,6 +34,13 @@ export interface ShippingUploadHandlerContext {
t: (key: string) => string;
}
/**
* 创建发货通知上传处理器。
*
* 核心逻辑:识别附件属于发货通知还是库存文件,分别触发建单/建批或库存上传,并维护 task/batch 本地上下文。
* @param ctx - 上传处理上下文
* @returns 自动上传、文件选择器和建议提示相关处理函数
*/
export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) {
const continueShippingInventoryUploadWithDify = async (
taskId: string,
@@ -47,6 +59,25 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
await ctx.sendShippingMenuMessage(buildShippingInventoryUploadPrompt(result, fileName));
};
const syncBatchContextFromNoticeResponse = (result: Record<string, unknown> | null | undefined) => {
const batchNo = String(
(result?.batch_no as string | undefined)
|| ((result?.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|| '',
).trim();
const focusTaskNo = String(
((result?.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|| (result?.task_id as string | undefined)
|| '',
).trim();
const batchSummary = ((result?.data as { batch?: unknown } | undefined)?.batch) || null;
if (batchNo) ctx.resolvedShippingBatchNo.value = batchNo;
if (focusTaskNo) ctx.resolvedShippingTaskId.value = focusTaskNo;
if (batchSummary && typeof batchSummary === 'object') {
ctx.shippingBatchSummary.value = batchSummary;
}
};
const handleShippingAutoUploadFile = async (file: File) => {
const kind = classifyShippingUploadFile(file, extractExt);
if (kind === 'inventory') {
@@ -67,18 +98,28 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
await continueShippingInventoryUploadWithDify(taskId, result as unknown as Record<string, unknown>, file.name);
return;
}
const result = await createWorkspaceShippingTaskFromNotice(
file,
const result = await createWorkspaceShippingBatchFromNotices(
[file],
String(ctx.conversationId.value || '').trim() || undefined,
);
const taskId = String(result.task_id || '').trim();
if (taskId) ctx.resolvedShippingTaskId.value = taskId;
syncBatchContextFromNoticeResponse(result as unknown as Record<string, unknown>);
const taskId = String(
((result.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|| result.task_id
|| '',
).trim();
const batchNo = String(
result.batch_no
|| ((result.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|| '',
).trim();
const hint = String(result.message || '').trim();
const status = String((result as { status?: string }).status || '').trim();
const tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
await ctx.pushShippingLocalAssistantMessage(
[
hint || `已处理发货通知附件:${file.name}`,
batchNo ? `批次编号:${batchNo}` : '',
taskId ? `任务编号:${taskId}` : '',
tail,
].filter(Boolean).join('\n'),
@@ -86,6 +127,51 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
void ctx.refreshShippingActions();
};
const handleShippingAutoUploadNoticeBatch = async (files: File[]) => {
const noticeFiles = files.filter(Boolean);
if (!noticeFiles.length) return;
const result = await createWorkspaceShippingBatchFromNotices(
noticeFiles,
String(ctx.conversationId.value || '').trim() || undefined,
);
syncBatchContextFromNoticeResponse(result as unknown as Record<string, unknown>);
const taskId = String(
((result.data as { focus_task?: { task_no?: string } } | undefined)?.focus_task?.task_no)
|| result.task_id
|| '',
).trim();
const batchNo = String(
result.batch_no
|| ((result.data as { batch?: { batch_no?: string } } | undefined)?.batch?.batch_no)
|| '',
).trim();
const batch = (result.data as {
batch?: { file_count?: number };
tasks?: Array<{ batch_index?: number; batch_total?: number }>;
} | undefined)?.batch;
const tasks = Array.isArray((result.data as { tasks?: unknown[] } | undefined)?.tasks)
? (result.data as { tasks: Array<{ batch_index?: number; batch_total?: number }> }).tasks
: [];
const focusTask = tasks[0];
const focusProgress = focusTask?.batch_index && focusTask?.batch_total
? `当前第 ${focusTask.batch_index}/${focusTask.batch_total} 票`
: '';
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 tail = status === 'needs_human' ? '请根据提示进行确认/驳回。' : '';
await ctx.pushShippingLocalAssistantMessage(
[
hint || `已处理 ${fileCount} 份发货通知附件`,
batchNo ? `批次编号:${batchNo}` : '',
taskId ? `当前任务:${taskId}` : '',
focusProgress,
tail,
].filter(Boolean).join('\n'),
);
void ctx.refreshShippingActions();
};
const openShippingInventoryPicker = (): boolean => {
const taskId = ctx.getActiveShippingTaskId();
if (!taskId) {
@@ -132,6 +218,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
return {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
openShippingInventoryPicker,
handleShippingInventorySelected,
shippingSuggestedPrompt,
@@ -18,7 +18,7 @@ export interface RetrieverResource {
export interface ChatMessage {
role: 'user' | 'assistant';
content: string;
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping';
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping' | 'shipping-parse-review' | 'shipping-match-result';
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
chat_log_id?: number;
@@ -5,11 +5,20 @@
export interface ShippingTaskSummary {
id: number;
task_no: string;
batch_no?: string | null;
source_type: string;
source_file_name?: string | null;
source_file_type?: string | null;
batch_index?: number | null;
batch_total?: number | null;
customer_name?: string | null;
current_step?: string | null;
process_status: string;
review_status?: string | null;
match_status?: string | null;
upload_status?: string | null;
upload_mode?: string | null;
upload_attempt?: number | null;
pending_human_reason?: string | null;
conversation_id?: string | null;
export_file_name?: string | null;
@@ -24,14 +33,48 @@ export interface ShippingTaskEvent {
created_at?: string | null;
}
export interface ShippingNoticeHeader {
customer_name?: string | null;
customer_code?: string | null;
ship_to?: string | null;
po_number?: string | null;
required_date?: string | null;
}
export interface ShippingNoticeLine {
sku: string;
reservation_id?: string | null;
qty: number;
required_date?: string | null;
uom?: string | null;
line_no?: string | null;
}
export interface ShippingMatchLineResult {
sku: string;
reservation_id?: string | null;
required_qty: number;
available_qty: number;
shortage_qty: number;
line_status: 'ok' | 'partial' | 'shortage' | string;
}
export interface ShippingShortageSummary {
lines?: ShippingMatchLineResult[];
}
export interface ShippingTaskDetail extends ShippingTaskSummary {
customer_code?: string | null;
ship_to?: string | null;
po_number?: string | null;
required_date?: string | null;
lines: Array<Record<string, unknown>>;
shortage?: Record<string, unknown> | null;
line_results?: Array<Record<string, unknown>>;
step_payload?: Record<string, unknown>;
upload_receipt?: Record<string, unknown>;
export_version?: number | null;
idempotency_key?: string | null;
lines: ShippingNoticeLine[];
shortage?: ShippingShortageSummary | null;
line_results?: ShippingMatchLineResult[];
parse_confidence?: number | null;
error_message?: string | null;
events: ShippingTaskEvent[];
@@ -53,6 +96,17 @@ export interface ShippingChatActionsResponse {
action_buttons: ShippingChatAction[];
}
export interface ShippingBatchSummary {
id: number;
batch_no: string;
conversation_id?: string | null;
current_focus_task_no?: string | null;
file_count?: number | null;
process_summary?: Record<string, unknown> | null;
created_at?: string | null;
updated_at?: string | null;
}
export interface ShippingInventoryUploadResponse {
status: string;
message?: string;
@@ -73,8 +127,13 @@ export interface ShippingNoticeUploadResponse {
status: string;
message?: string;
task_id?: string;
batch_no?: string;
checkpoint?: string;
data?: Record<string, unknown>;
data?: Record<string, unknown> & {
batch?: ShippingBatchSummary;
focus_task?: ShippingTaskSummary | null;
tasks?: Array<Record<string, unknown>>;
};
human_options?: string[];
}
@@ -35,6 +35,54 @@ export interface ShippingInventoryMappingFormPayload {
applying?: boolean;
}
export interface ShippingParseReviewPayload {
taskId: string;
checkpoint: string;
header: {
customer_name?: string | null;
customer_code?: string | null;
ship_to?: string | null;
po_number?: string | null;
required_date?: string | null;
};
lines: Array<{
sku: string;
reservation_id?: string | null;
qty: number;
required_date?: string | null;
uom?: string | null;
line_no?: string | null;
}>;
saving?: boolean;
}
export interface ShippingMatchResultPayload {
taskId: string;
match_status?: string | null;
line_results: Array<{
sku: string;
reservation_id?: string | null;
required_qty: number;
available_qty: number;
shortage_qty: number;
line_status: 'ok' | 'partial' | 'shortage' | string;
}>;
shortage_lines?: Array<{
sku: string;
reservation_id?: string | null;
required_qty: number;
available_qty: number;
shortage_qty: number;
line_status: 'ok' | 'partial' | 'shortage' | string;
}>;
action_buttons?: Array<{
id: string;
label: string;
message: string;
variant: 'primary' | 'secondary' | 'danger';
}>;
}
export interface ShippingActionButton {
id: string;
label: string;
@@ -1,21 +1,44 @@
<script setup lang="ts">
/**
* features/workspace/views/ShippingNoticeView.vue
* 货代发货任务只读工作台:列表筛选、详情、跳转 Chat 继续处理。
* 用途:货代发货任务只读工作台,提供任务筛选、详情查看与跳转 Chat 继续处理入口。
* 依赖:ShippingWorkflowStepper、ShippingParseReviewMessage、ShippingMatchResultCard、shipping.api。
* 逻辑:先拉取任务列表与详情,再复用 Chat 区的发货组件展示步骤、匹配结果和 parse review。
*/
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ArrowLeft, Download, ExternalLink, RefreshCw } from 'lucide-vue-next';
import ShippingWorkflowStepper from '@/features/chat/components/ShippingWorkflowStepper.vue';
import ShippingParseReviewMessage, {
type ShippingParseReviewHandlers,
} from '@/features/chat/components/messages/ShippingParseReviewMessage.vue';
import ShippingMatchResultCard from '@/features/chat/components/messages/ShippingMatchResultCard.vue';
import {
addWorkspaceShippingNoticeLine,
autoProgressWorkspaceShippingTask,
generateWorkspaceShippingExcel,
getShippingChatActions,
getWorkspaceShippingTask,
listWorkspaceShippingTasks,
markWorkspaceShippingManualUploaded,
matchWorkspaceShippingInventory,
removeWorkspaceShippingNoticeLine,
SHIPPING_NOTICE_AGENT_NAME,
submitWorkspaceShippingDecision,
updateWorkspaceShippingNoticeFields,
updateWorkspaceShippingNoticeLine,
workspaceShippingExportUrl,
type ShippingChatAction,
type ShippingNoticeHeader,
type ShippingNoticeLine,
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
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 { buildShippingWorkflowSteps, shippingActionButtonClass } from '@/features/chat/shipping';
const props = defineProps<{
embedded?: boolean;
@@ -29,8 +52,18 @@ const detailLoading = ref(false);
const tasks = ref<ShippingTaskSummary[]>([]);
const selectedTaskNo = ref<string | null>(null);
const detail = ref<ShippingTaskDetail | null>(null);
const detailSaving = ref(false);
const detailActionBusy = ref(false);
const detailActionButtons = ref<ShippingChatAction[]>([]);
const statusFilter = ref('all');
const chatAgentId = ref<number | null>(null);
const batchProgressLabel = computed(() => {
if (!detail.value?.batch_index || !detail.value?.batch_total) return '';
return t('chat.shippingNoticeUi.batchProgress', {
index: detail.value.batch_index,
total: detail.value.batch_total,
});
});
const statusOptions = computed(() => [
{ value: 'all', label: t('workspace.shippingNotice.status.all') },
@@ -56,6 +89,8 @@ const statusBadge = (status: string) => {
return map[status] || { cls: 'bg-slate-100 text-secondary', label: status };
};
const detailWorkflowSteps = computed(() => buildShippingWorkflowSteps(detail.value));
const loadCases = async () => {
loading.value = true;
try {
@@ -73,9 +108,15 @@ const loadCases = async () => {
const loadDetail = async (taskNo: string) => {
detailLoading.value = true;
try {
detail.value = await getWorkspaceShippingTask(taskNo);
const [taskDetail, chatActions] = await Promise.all([
getWorkspaceShippingTask(taskNo),
getShippingChatActions(taskNo).catch(() => null),
]);
detail.value = taskDetail;
detailActionButtons.value = chatActions?.action_buttons || [];
} catch {
detail.value = null;
detailActionButtons.value = [];
} finally {
detailLoading.value = false;
}
@@ -93,9 +134,11 @@ const resolveChatAgent = async () => {
}
};
const openInChat = (taskNo: string, conversationId?: string | null) => {
const openInChat = (taskNo: string, conversationId?: string | null, batchNo?: string | null) => {
if (!chatAgentId.value) return;
const query: Record<string, string> = { task_id: taskNo };
const normalizedBatchNo = String(batchNo || '').trim();
if (normalizedBatchNo) query.batch_no = normalizedBatchNo;
const cid = String(conversationId || '').trim();
if (/^[0-9a-f]{32}$/i.test(cid)) query.conversation_id = cid;
router.push({ path: `/chat/${chatAgentId.value}`, query });
@@ -113,6 +156,133 @@ const downloadExport = async (taskNo: string) => {
URL.revokeObjectURL(a.href);
};
const parseReviewPayload = computed<ShippingParseReviewPayload | null>(() => {
if (!detail.value || detail.value.review_status !== 'pending_confirm') return null;
return {
taskId: detail.value.task_no,
checkpoint: 'parse_review',
header: {
customer_name: detail.value.customer_name ?? null,
customer_code: detail.value.customer_code ?? null,
ship_to: detail.value.ship_to ?? null,
po_number: detail.value.po_number ?? null,
required_date: detail.value.required_date ?? null,
},
lines: Array.isArray(detail.value.lines) ? detail.value.lines : [],
saving: detailSaving.value,
};
});
const parseReviewMessage = computed<ChatMessage>(() => ({
role: 'assistant',
type: 'shipping-parse-review',
content: `${t('chat.shippingNoticeUi.parseReviewIntro')}\n${t('chat.shippingNoticeUi.taskId', { taskId: detail.value?.task_no || '' })}`.trim(),
payload: parseReviewPayload.value || undefined,
}));
const parseReviewHandlers: ShippingParseReviewHandlers = {
getPayload: () => parseReviewPayload.value,
updateHeader: async (_msg, fields: Partial<ShippingNoticeHeader>) => {
if (!detail.value || detailSaving.value) return false;
detailSaving.value = true;
try {
await updateWorkspaceShippingNoticeFields(detail.value.task_no, fields, '工作台订单表修订');
await Promise.all([loadDetail(detail.value.task_no), loadCases()]);
return true;
} catch {
return false;
} finally {
detailSaving.value = false;
}
},
updateLine: async (_msg, lineIndex: number, patch: Partial<ShippingNoticeLine>) => {
if (!detail.value || detailSaving.value) return false;
detailSaving.value = true;
try {
await updateWorkspaceShippingNoticeLine(detail.value.task_no, lineIndex, patch, '工作台订单表修订');
await Promise.all([loadDetail(detail.value.task_no), loadCases()]);
return true;
} catch {
return false;
} finally {
detailSaving.value = false;
}
},
addLine: async (_msg, line: Partial<ShippingNoticeLine>) => {
if (!detail.value || detailSaving.value) return false;
detailSaving.value = true;
try {
await addWorkspaceShippingNoticeLine(detail.value.task_no, line, '工作台订单表新增行');
await Promise.all([loadDetail(detail.value.task_no), loadCases()]);
return true;
} catch {
return false;
} finally {
detailSaving.value = false;
}
},
removeLine: async (_msg, lineIndex: number) => {
if (!detail.value || detailSaving.value) return false;
detailSaving.value = true;
try {
await removeWorkspaceShippingNoticeLine(detail.value.task_no, lineIndex, '工作台订单表删除行');
await Promise.all([loadDetail(detail.value.task_no), loadCases()]);
return true;
} catch {
return false;
} finally {
detailSaving.value = false;
}
},
};
const shortageLines = computed(() => detail.value?.shortage?.lines || []);
const hasMatchCard = computed(() =>
!!detail.value && (
(Array.isArray(detail.value.line_results) && detail.value.line_results.length > 0)
|| shortageLines.value.length > 0
),
);
const handleWorkspaceAction = async (action: ShippingChatAction) => {
if (!detail.value || detailActionBusy.value) return;
const taskNo = detail.value.task_no;
detailActionBusy.value = true;
try {
if (action.id === 'download_excel') {
await downloadExport(taskNo);
return;
}
if (action.id === 'generate_excel') {
await generateWorkspaceShippingExcel(taskNo);
} else if (action.id === 'match_inventory') {
await matchWorkspaceShippingInventory(taskNo);
} else if (action.id === 'mark_manual_uploaded') {
await markWorkspaceShippingManualUploaded(taskNo);
} else if (action.id === 'refresh') {
await loadDetail(taskNo);
return;
} else if (action.id === 'confirm_inventory_mapping') {
await autoProgressWorkspaceShippingTask(taskNo);
} else if ([
'confirm',
'reject',
'reparse',
'correct_inventory_mapping',
'reparse_inventory',
'rematch',
].includes(action.id)) {
await submitWorkspaceShippingDecision(taskNo, action.id);
} else {
openInChat(taskNo, detail.value.conversation_id, detail.value.batch_no);
return;
}
await Promise.all([loadDetail(taskNo), loadCases()]);
} finally {
detailActionBusy.value = false;
}
};
watch(selectedTaskNo, (val) => {
if (val) loadDetail(val);
else detail.value = null;
@@ -189,7 +359,12 @@ onMounted(async () => {
</span>
</div>
<div class="mt-1 truncate text-sm text-secondary">{{ item.customer_name || '—' }}</div>
<div class="mt-1 text-xs text-muted">{{ item.created_at || '' }}</div>
<div class="mt-1 flex flex-wrap items-center gap-2 text-xs text-muted">
<span>{{ item.created_at || '' }}</span>
<span v-if="item.batch_index && item.batch_total" class="rounded-full bg-sky-50 px-2 py-0.5 font-medium text-sky-700">
{{ t('chat.shippingNoticeUi.batchProgress', { index: item.batch_index, total: item.batch_total }) }}
</span>
</div>
</button>
</div>
@@ -207,14 +382,19 @@ onMounted(async () => {
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<div class="font-mono text-lg font-bold text-primary">{{ detail.task_no }}</div>
<div class="text-sm text-muted">{{ detail.customer_name }} · {{ detail.customer_code || '—' }}</div>
<div class="flex flex-wrap items-center gap-2 text-sm text-muted">
<span>{{ detail.customer_name }} · {{ detail.customer_code || '—' }}</span>
<span v-if="batchProgressLabel" class="rounded-full bg-sky-50 px-2 py-0.5 text-xs font-medium text-sky-700">
{{ batchProgressLabel }}
</span>
</div>
</div>
<div class="flex flex-wrap gap-2">
<button
v-if="chatAgentId"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-brand-300 bg-brand-50 px-3 py-1.5 text-sm font-medium text-brand-700 hover:bg-brand-100"
@click="openInChat(detail.task_no, detail.conversation_id)"
@click="openInChat(detail.task_no, detail.conversation_id, detail.batch_no)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.openChat') }}
@@ -231,6 +411,8 @@ onMounted(async () => {
</div>
</div>
<ShippingWorkflowStepper :steps="detailWorkflowSteps" />
<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>
@@ -242,7 +424,26 @@ onMounted(async () => {
{{ detail.error_message }}
</div>
<div v-if="detail.lines?.length">
<ShippingMatchResultCard
v-if="hasMatchCard"
:task-id="detail.task_no"
:match-status="detail.match_status"
:line-results="detail.line_results"
:shortage-lines="shortageLines"
:action-buttons="detailActionButtons"
:action-busy="detailActionBusy"
:action-button-class="shippingActionButtonClass"
:on-action-click="handleWorkspaceAction"
/>
<div v-if="parseReviewPayload">
<ShippingParseReviewMessage
:message="parseReviewMessage"
:handlers="parseReviewHandlers"
/>
</div>
<div v-else-if="detail.lines?.length">
<h3 class="mb-2 text-sm font-semibold text-secondary">{{ $t('workspace.shippingNotice.lines') }}</h3>
<div class="overflow-x-auto rounded-xl border border-default">
<table class="min-w-full text-sm">
@@ -254,8 +455,8 @@ onMounted(async () => {
</thead>
<tbody>
<tr v-for="(line, idx) in detail.lines" :key="idx" class="border-t border-default/60">
<td class="px-3 py-2 font-mono">{{ line.sku || line.part_no || '—' }}</td>
<td class="px-3 py-2">{{ line.qty ?? line.quantity ?? '—' }}</td>
<td class="px-3 py-2 font-mono">{{ line.sku || '—' }}</td>
<td class="px-3 py-2">{{ line.qty ?? '—' }}</td>
</tr>
</tbody>
</table>
+90
View File
@@ -40,6 +40,96 @@
"empty": "(empty)",
"unrecognized": "(unrecognized)"
},
"shippingNoticeUi": {
"parseReviewIntro": "Please confirm or revise the parsed result below.",
"parseReviewHeader": "Parsed notice header",
"taskId": "Task ID: {taskId}",
"editHeader": "Edit header",
"cancelEdit": "Cancel edit",
"customer": "Customer",
"customerCode": "Customer code",
"shipTo": "Ship to",
"poNumber": "PO number",
"requiredDate": "Required date",
"saveHeader": "Save header",
"saving": "Saving...",
"orderLines": "Order lines",
"addLine": "Add line",
"reservationId": "Reservation ID",
"sku": "SKU",
"qty": "Qty",
"actions": "Actions",
"editLine": "Edit",
"deleteLine": "Delete",
"addOrderLine": "Add order line",
"saveAddedLine": "Save new line",
"editLineTitle": "Edit line {index}",
"saveLineItem": "Save line item",
"matchResult": "Inventory match result",
"orderDemand": "Order demand",
"inventoryAvailable": "Inventory available",
"shortageQty": "Shortage",
"statusLabel": "Status",
"shortageBanner": "Inventory shortage exists. Do not continue to freight upload yet. Resolve the shortage first, or use the available actions to confirm partial shipment / retry matching.",
"shortageDetails": "Shortage details",
"shortageRowDetail": "Line {index}: Reservation ID {reservationId}, SKU {sku}, shortage {shortage}",
"availableActions": "Available actions",
"stepperTitle": "Workflow steps",
"batchTitle": "Shipping batch",
"taskTitle": "Shipping task",
"currentTask": "Current task {taskId}",
"batchProgress": "Item {index}/{total}",
"currentNotice": "Current notice",
"prevTask": "Previous",
"nextTask": "Next",
"collapseTasks": "Hide tasks",
"viewTasks": "View tasks",
"fileCount": "Files",
"runningCount": "Running",
"completedCount": "Completed",
"batchProgressTitle": "Batch progress",
"processing": "Processing",
"status": {
"created": "Pending parse",
"waitingInventory": "Waiting inventory",
"inventoryReady": "Inventory ready",
"matched": "Matched",
"waitingUpload": "Waiting upload",
"uploaded": "Completed",
"uploadFailed": "Upload failed",
"rejected": "Rejected",
"closed": "Closed"
},
"currentStep": {
"noticeParse": "Notice parsing",
"inventoryPrepare": "Inventory prep",
"inventoryMatch": "Inventory match",
"shortageHandle": "Shortage handling",
"generateExcel": "Generate Excel",
"uploadFreight": "Upload to freight",
"finishArchive": "Archive"
},
"matchStatus": {
"fulfillable": "Fully fulfillable",
"partial": "Partially fulfillable",
"unfulfillable": "Unfulfillable",
"pending": "Pending match"
},
"rowStatus": {
"ok": "Enough",
"partial": "Partial",
"shortage": "Shortage"
},
"stepper": {
"noticeSubmit": "Submit notice",
"parseConfirm": "Confirm parsing",
"inventoryPrepare": "Get inventory",
"alignConfirm": "Confirm mapping",
"matchInventory": "Match inventory",
"generateFile": "Generate shipment file",
"uploadFreight": "Upload freight"
}
},
"clearAll": "Clear All",
"clearOneRecord": "Clear This Record",
"agents": "Agents",
+90
View File
@@ -40,6 +40,96 @@
"empty": "(ว่าง)",
"unrecognized": "(ไม่รู้จัก)"
},
"shippingNoticeUi": {
"parseReviewIntro": "โปรดยืนยันหรือแก้ไขผลการแยกข้อมูลด้านล่าง",
"parseReviewHeader": "หัวข้อมูลที่แยกแล้ว",
"taskId": "รหัสงาน: {taskId}",
"editHeader": "แก้ไขส่วนหัว",
"cancelEdit": "ยกเลิกการแก้ไข",
"customer": "ลูกค้า",
"customerCode": "รหัสลูกค้า",
"shipTo": "ผู้รับสินค้า",
"poNumber": "เลขที่ PO",
"requiredDate": "วันที่ต้องการ",
"saveHeader": "บันทึกส่วนหัว",
"saving": "กำลังบันทึก...",
"orderLines": "รายการคำสั่งซื้อ",
"addLine": "เพิ่มแถว",
"reservationId": "Reservation ID",
"sku": "SKU",
"qty": "จำนวน",
"actions": "การทำงาน",
"editLine": "แก้ไข",
"deleteLine": "ลบ",
"addOrderLine": "เพิ่มรายการคำสั่งซื้อ",
"saveAddedLine": "บันทึกรายการใหม่",
"editLineTitle": "แก้ไขแถวที่ {index}",
"saveLineItem": "บันทึกรายการ",
"matchResult": "ผลการจับคู่สต็อก",
"orderDemand": "ความต้องการตามคำสั่งซื้อ",
"inventoryAvailable": "สต็อกที่ใช้ได้",
"shortageQty": "จำนวนที่ขาด",
"statusLabel": "สถานะ",
"shortageBanner": "มีสต็อกขาดอยู่ จึงยังไม่ควรอัปโหลดไปยังผู้ให้บริการขนส่งต่อ กรุณาจัดการส่วนที่ขาดก่อน หรือใช้ปุ่มที่มีให้เพื่อยืนยันการส่งบางส่วน / จับคู่ใหม่",
"shortageDetails": "รายละเอียดส่วนขาด",
"shortageRowDetail": "แถว {index}: Reservation ID {reservationId}, SKU {sku}, ขาด {shortage}",
"availableActions": "การทำงานที่ใช้ได้",
"stepperTitle": "ขั้นตอนการทำงาน",
"batchTitle": "ชุดงานจัดส่ง",
"taskTitle": "งานจัดส่ง",
"currentTask": "งานปัจจุบัน {taskId}",
"batchProgress": "รายการ {index}/{total}",
"currentNotice": "ใบแจ้งปัจจุบัน",
"prevTask": "ก่อนหน้า",
"nextTask": "ถัดไป",
"collapseTasks": "ซ่อนงาน",
"viewTasks": "ดูงาน",
"fileCount": "จำนวนไฟล์",
"runningCount": "กำลังดำเนินการ",
"completedCount": "เสร็จแล้ว",
"batchProgressTitle": "ความคืบหน้าของชุดงาน",
"processing": "กำลังดำเนินการ",
"status": {
"created": "รอแยกข้อมูล",
"waitingInventory": "รอสต็อก",
"inventoryReady": "สต็อกพร้อม",
"matched": "จับคู่แล้ว",
"waitingUpload": "รออัปโหลด",
"uploaded": "เสร็จสมบูรณ์",
"uploadFailed": "อัปโหลดล้มเหลว",
"rejected": "ถูกปฏิเสธ",
"closed": "ปิดแล้ว"
},
"currentStep": {
"noticeParse": "แยกใบแจ้ง",
"inventoryPrepare": "เตรียมสต็อก",
"inventoryMatch": "จับคู่สต็อก",
"shortageHandle": "จัดการส่วนขาด",
"generateExcel": "สร้าง Excel",
"uploadFreight": "อัปโหลดผู้ให้บริการขนส่ง",
"finishArchive": "เก็บงาน"
},
"matchStatus": {
"fulfillable": "จัดส่งได้ครบ",
"partial": "จัดส่งได้บางส่วน",
"unfulfillable": "จัดส่งไม่ได้",
"pending": "รอจับคู่"
},
"rowStatus": {
"ok": "เพียงพอ",
"partial": "บางส่วน",
"shortage": "ขาด"
},
"stepper": {
"noticeSubmit": "ส่งใบแจ้ง",
"parseConfirm": "ยืนยันผลแยก",
"inventoryPrepare": "เตรียมสต็อก",
"alignConfirm": "ยืนยันการจับคู่คอลัมน์",
"matchInventory": "จับคู่สต็อก",
"generateFile": "สร้างไฟล์จัดส่ง",
"uploadFreight": "อัปโหลดผู้ให้บริการขนส่ง"
}
},
"clearAll": "ล้างทั้งหมด",
"clearOneRecord": "ลบรายการนี้",
"agents": "ตัวแทน",
+90
View File
@@ -40,6 +40,96 @@
"empty": "(空)",
"unrecognized": "(未识别)"
},
"shippingNoticeUi": {
"parseReviewIntro": "请确认或修订以下解析结果。",
"parseReviewHeader": "解析结果单头",
"taskId": "任务编号:{taskId}",
"editHeader": "编辑单头",
"cancelEdit": "取消编辑",
"customer": "客户",
"customerCode": "客户编码",
"shipTo": "收货方",
"poNumber": "采购单号",
"requiredDate": "需求日期",
"saveHeader": "保存单头",
"saving": "保存中...",
"orderLines": "订单行",
"addLine": "新增一行",
"reservationId": "预订单号",
"sku": "料号",
"qty": "数量",
"actions": "操作",
"editLine": "编辑",
"deleteLine": "删除",
"addOrderLine": "新增订单行",
"saveAddedLine": "保存新增行",
"editLineTitle": "编辑第 {index} 行",
"saveLineItem": "保存行项目",
"matchResult": "库存匹配结果",
"orderDemand": "订单需求",
"inventoryAvailable": "库存可用",
"shortageQty": "缺口",
"statusLabel": "状态",
"shortageBanner": "存在库存缺口,当前不能直接继续上传货代。请先处理缺口,或按可用按钮确认部分发货 / 重新匹配。",
"shortageDetails": "缺口明细",
"shortageRowDetail": "第 {index} 行:预订单号 {reservationId},料号 {sku},缺口 {shortage}",
"availableActions": "可用操作",
"stepperTitle": "流程步骤",
"batchTitle": "发货批次",
"taskTitle": "发货任务",
"currentTask": "当前任务 {taskId}",
"batchProgress": "第 {index}/{total} 票",
"currentNotice": "当前通知",
"prevTask": "上一票",
"nextTask": "下一票",
"collapseTasks": "收起任务",
"viewTasks": "查看任务",
"fileCount": "文件数",
"runningCount": "处理中",
"completedCount": "已完成",
"batchProgressTitle": "批次进度",
"processing": "处理中",
"status": {
"created": "待解析",
"waitingInventory": "待库存",
"inventoryReady": "库存就绪",
"matched": "已匹配",
"waitingUpload": "待上传",
"uploaded": "已完成",
"uploadFailed": "上传失败",
"rejected": "已驳回",
"closed": "已关闭"
},
"currentStep": {
"noticeParse": "通知解析",
"inventoryPrepare": "库存准备",
"inventoryMatch": "库存匹配",
"shortageHandle": "缺口处理",
"generateExcel": "生成 Excel",
"uploadFreight": "上传货代",
"finishArchive": "完成归档"
},
"matchStatus": {
"fulfillable": "可全部发货",
"partial": "部分满足",
"unfulfillable": "无法满足",
"pending": "待匹配"
},
"rowStatus": {
"ok": "充足",
"partial": "部分满足",
"shortage": "缺口"
},
"stepper": {
"noticeSubmit": "提交通知",
"parseConfirm": "确认解析",
"inventoryPrepare": "获取库存",
"alignConfirm": "确认字段对齐",
"matchInventory": "匹配库存",
"generateFile": "生成发货文件",
"uploadFreight": "上传货代"
}
},
"clearAll": "清空全部",
"clearOneRecord": "清除该记录",
"agents": "智能体",
+116
View File
@@ -14,6 +14,122 @@
"thinking": "正在生成回答...",
"disclaimer": "AI 可能會犯錯,請核實重要信息。",
"createNewChat": "建立新對話",
"shippingNoticeContinue": "請繼續處理發貨任務 {taskId}。請先呼叫 get_task_status,再告訴我下一步。",
"shippingNoticeActionsHint": "請選擇操作:",
"shippingNoticeMissingTaskId": "找不到任務編號,請先完成發貨通知解析。",
"shippingNoticeUploadDone": "庫存檔案已上傳:{fileName}。",
"shippingNoticeUploadOk": "上傳成功。",
"shippingNoticeUploadFailed": "庫存檔案上傳失敗。",
"shippingNoticePasteHint": "請在輸入框貼上庫存小表內容後送出。",
"shippingNoticeDecisionDone": "操作已完成。",
"shippingNoticeMapping": {
"inventoryHeaders": "庫存表頭",
"headerRow": "表頭列:{row}",
"sample": "樣例",
"orderDetails": "訂單明細",
"orderRowCount": "訂單行數:{count}",
"orderSkuPreview": "SKU(前{count}):{skus}",
"skuColumnRequired": "SKU 欄位(必填)",
"availableQtyColumnRequired": "可用數量欄位(必填)",
"reservationIdColumnOptional": "Reservation ID 欄位(選填)",
"selectHeader": "請選擇表頭欄位",
"reservationIdNotUsed": "(不使用 Reservation ID)",
"reupload": "重新上傳",
"applying": "套用中...",
"applyAndParse": "套用映射並解析",
"empty": "(空)",
"unrecognized": "(未辨識)"
},
"shippingNoticeUi": {
"parseReviewIntro": "請確認或修訂以下解析結果。",
"parseReviewHeader": "解析結果單頭",
"taskId": "任務編號:{taskId}",
"editHeader": "編輯單頭",
"cancelEdit": "取消編輯",
"customer": "客戶",
"customerCode": "客戶代碼",
"shipTo": "收貨方",
"poNumber": "採購單號",
"requiredDate": "需求日期",
"saveHeader": "儲存單頭",
"saving": "儲存中...",
"orderLines": "訂單行",
"addLine": "新增一行",
"reservationId": "預訂單號",
"sku": "料號",
"qty": "數量",
"actions": "操作",
"editLine": "編輯",
"deleteLine": "刪除",
"addOrderLine": "新增訂單行",
"saveAddedLine": "儲存新增行",
"editLineTitle": "編輯第 {index} 行",
"saveLineItem": "儲存行項目",
"matchResult": "庫存匹配結果",
"orderDemand": "訂單需求",
"inventoryAvailable": "庫存可用",
"shortageQty": "缺口",
"statusLabel": "狀態",
"shortageBanner": "存在庫存缺口,目前不能直接繼續上傳貨代。請先處理缺口,或依可用按鈕確認部分發貨 / 重新匹配。",
"shortageDetails": "缺口明細",
"shortageRowDetail": "第 {index} 行:預訂單號 {reservationId},料號 {sku},缺口 {shortage}",
"availableActions": "可用操作",
"stepperTitle": "流程步驟",
"batchTitle": "發貨批次",
"taskTitle": "發貨任務",
"currentTask": "當前任務 {taskId}",
"batchProgress": "第 {index}/{total} 票",
"currentNotice": "當前通知",
"prevTask": "上一票",
"nextTask": "下一票",
"collapseTasks": "收起任務",
"viewTasks": "查看任務",
"fileCount": "檔案數",
"runningCount": "處理中",
"completedCount": "已完成",
"batchProgressTitle": "批次進度",
"processing": "處理中",
"status": {
"created": "待解析",
"waitingInventory": "待庫存",
"inventoryReady": "庫存就緒",
"matched": "已匹配",
"waitingUpload": "待上傳",
"uploaded": "已完成",
"uploadFailed": "上傳失敗",
"rejected": "已駁回",
"closed": "已關閉"
},
"currentStep": {
"noticeParse": "通知解析",
"inventoryPrepare": "庫存準備",
"inventoryMatch": "庫存匹配",
"shortageHandle": "缺口處理",
"generateExcel": "生成 Excel",
"uploadFreight": "上傳貨代",
"finishArchive": "完成歸檔"
},
"matchStatus": {
"fulfillable": "可全部發貨",
"partial": "部分滿足",
"unfulfillable": "無法滿足",
"pending": "待匹配"
},
"rowStatus": {
"ok": "充足",
"partial": "部分滿足",
"shortage": "缺口"
},
"stepper": {
"noticeSubmit": "提交通知",
"parseConfirm": "確認解析",
"inventoryPrepare": "獲取庫存",
"alignConfirm": "確認欄位對齊",
"matchInventory": "匹配庫存",
"generateFile": "生成發貨文件",
"uploadFreight": "上傳貨代"
}
},
"clearAll": "清空全部",
"clearOneRecord": "清除此記錄",
"agents": "智能體",