feat(shipping-notice): 新增发货批次和任务管理功能,支持批次创建与任务处理
This commit is contained in:
1 parent
457f0f4e5e
commit
634dee4b81
81 files changed
+9088
-3625
No files matched your search
@@ -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,
|
||||
)
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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
|
||||
|
||||
@@ -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: "解析结果待确认",
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user