feat(shipping-notice): 完成货代发货通知全流程开发与代码重构

- 新增PO号提取、预约ID解析(支持`PR@xxx`格式)工具,完善库存匹配逻辑
- 新增库存映射缓存、匹配/解析结果格式化摘要,优化用户提示
- 修复数据库迁移脚本未检查表存在的问题,避免全新部署失败
- 新增路径工具类统一管理相对路径,优化配置文件处理逻辑
- 归档旧文档,将部署、Dify配置合并到`shipping_notice.md`
- 新增完整单元测试与集成测试覆盖核心流程
- 更新前端国际化与会话管理逻辑,优化界面交互
This commit is contained in:
hugo committed 2026-06-04 15:26:34 +08:00
1 parent b62082758b
commit 8deae3146b
65 files changed
+6477 -1937

No files matched your search

+7 -7
View File
@@ -58,10 +58,10 @@ MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
# 货代发货通知 Agent
SHIPPING_NOTICE_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
# OpenAPI / Dify Tool 调用基地址(默认等于 PUBLIC_BASE_URL)
SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.36.114:5052/api/shipping-notice
SHIPPING_NOTICE_STORAGE_ROOT=backend/data/shipping_notice
FREIGHT_INVENTORY_DROP_DIR=backend/data/freight_rpa/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=backend/data/freight_rpa/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=backend/data/freight_rpa/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=backend/data/freight_rpa/upload_triggers
FREIGHT_SHIPMENT_TEMPLATE_PATH=backend/templates/freight_shipment_upload.xlsx
SHIPPING_NOTICE_TOOL_API_BASE=http://192.168.36.108:5052/api/shipping-notice
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
+16 -16
View File
@@ -344,21 +344,21 @@ def test_agent(id):
if agent.type == 'iframe':
iframe_url = (agent.extra_config or {}).get('iframe_url')
if not iframe_url:
return (jsonify({'success': False, 'request_url': '', 'output_info': 'Missing iframe_url in extra_config.', 'analysis': '测试失败:未配置 iframe URL。', 'http_status': 0, 'tested_at': tested_at}), 400)
return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing iframe_url in extra_config.', 'analysis': '测试失败:未配置 iframe URL。', 'http_status': 0, 'tested_at': tested_at}), 200)
try:
resp = requests.get(iframe_url, timeout=(5, 15), allow_redirects=True)
success = 200 <= resp.status_code < 400
if success and (not agent.is_active):
passed = 200 <= resp.status_code < 400
if passed and (not agent.is_active):
agent.is_active = True
db.session.commit()
return (jsonify({'success': success, 'request_url': iframe_url, 'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}', 'analysis': '测试通过:iframe 地址可访问。' if success else '测试失败:iframe 地址不可访问或返回异常状态。', 'http_status': resp.status_code, 'tested_at': tested_at}), 200)
return (jsonify({'passed': passed, 'request_url': iframe_url, 'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}', 'analysis': '测试通过:iframe 地址可访问。' if passed else '测试失败:iframe 地址不可访问或返回异常状态。', 'http_status': resp.status_code, 'tested_at': tested_at}), 200)
except requests.RequestException as e:
return (jsonify({'success': False, 'request_url': iframe_url, 'output_info': str(e), 'analysis': '测试失败:请求 iframe 地址异常。', 'http_status': 0, 'tested_at': tested_at}), 200)
return (jsonify({'passed': False, 'request_url': iframe_url, 'output_info': str(e), 'analysis': '测试失败:请求 iframe 地址异常。', 'http_status': 0, 'tested_at': tested_at}), 200)
if not agent.dify_api_key:
return (jsonify({'success': False, 'request_url': '', 'output_info': 'Missing dify_api_key.', 'analysis': '测试失败:未配置 API Key。', 'http_status': 0, 'tested_at': tested_at}), 400)
return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing dify_api_key.', 'analysis': '测试失败:未配置 API Key。', 'http_status': 0, 'tested_at': tested_at}), 200)
base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/')
if not base_url:
return (jsonify({'success': False, 'request_url': '', 'output_info': 'Missing api_base_url.', 'analysis': '测试失败:未配置 API Base URL。', 'http_status': 0, 'tested_at': tested_at}), 400)
return (jsonify({'passed': False, 'request_url': '', 'output_info': 'Missing api_base_url.', 'analysis': '测试失败:未配置 API Base URL。', 'http_status': 0, 'tested_at': tested_at}), 200)
extra_config = agent.extra_config or {}
dify_app_type = str(extra_config.get('dify_app_type') or 'chatflow').strip().lower()
if dify_app_type not in ('chatflow', 'workflow'):
@@ -374,10 +374,10 @@ def test_agent(id):
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
raw_text = (resp.text or '')[:4000]
output_info = raw_text
success = False
passed = False
analysis = f'测试失败:HTTP {resp.status_code}。'
if dify_app_type == 'workflow' and 200 <= resp.status_code < 300:
success = True
passed = True
analysis = '测试通过:Workflow 接口可访问且认证通过。'
try:
data = resp.json()
@@ -401,7 +401,7 @@ def test_agent(id):
if answer:
output_info = str(answer)[:4000]
if resp.ok and isinstance(answer, str) and answer.strip():
success = True
passed = True
analysis = '测试通过:Chatflow 接口可访问且已返回回答。'
elif resp.ok:
analysis = '测试未通过:Chatflow 接口可访问,但未返回有效回答。'
@@ -412,17 +412,17 @@ def test_agent(id):
except ValueError:
if resp.ok and raw_text.strip():
if dify_app_type == 'workflow':
success = True
passed = True
analysis = '测试通过:Workflow 接口可访问并返回了文本内容。'
else:
success = True
passed = True
analysis = '测试通过:Chatflow 接口可访问并返回了文本内容。'
if success and (not agent.is_active):
if passed and (not agent.is_active):
agent.is_active = True
db.session.commit()
return (jsonify({'success': success, 'dify_app_type': dify_app_type, 'request_url': request_url, 'output_info': output_info, 'analysis': analysis, 'http_status': resp.status_code, 'tested_at': tested_at}), 200)
return (jsonify({'passed': passed, 'dify_app_type': dify_app_type, 'request_url': request_url, 'output_info': output_info, 'analysis': analysis, 'http_status': resp.status_code, 'tested_at': tested_at}), 200)
except requests.RequestException as e:
return (jsonify({'success': False, 'dify_app_type': dify_app_type, 'request_url': request_url, 'output_info': str(e), 'analysis': '测试失败:请求异常(网络、超时或认证问题)。', 'http_status': 0, 'tested_at': tested_at}), 200)
return (jsonify({'passed': False, 'dify_app_type': dify_app_type, 'request_url': request_url, 'output_info': str(e), 'analysis': '测试失败:请求异常(网络、超时或认证问题)。', 'http_status': 0, 'tested_at': tested_at}), 200)
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
@require_admin
@@ -1076,4 +1076,4 @@ def wecom_notify_metrics():
if event_type not in by_event:
by_event[event_type] = {'sent': 0, 'failed': 0}
by_event[event_type][status] = int(cnt)
return jsonify({'window_days': 30, 'total': int(total), 'sent': int(sent), 'failed': int(total - sent), 'send_success_rate': round(sent / total * 100, 2) if total else 0, 'opened_24h': int(opened_24h), 'opened_24h_rate': round(opened_24h / sent * 100, 2) if sent else 0, 'by_event': by_event})
return jsonify({'window_days': 30, 'total': int(total), 'sent': int(sent), 'failed': int(total - sent), 'send_success_rate': round(sent / total * 100, 2) if total else 0, 'opened_24h': int(opened_24h), 'opened_24h_rate': round(opened_24h / sent * 100, 2) if sent else 0, 'by_event': by_event})
+33 -10
View File
@@ -16,7 +16,7 @@ from datetime import datetime
from urllib.parse import urlparse
import requests
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
from sqlalchemy import func, desc, or_
from sqlalchemy import func, desc, or_, exists, and_
from openpyxl import load_workbook
from app.services.dify import DifyService
from app.services.integration_api import IntegrationApiService
@@ -56,6 +56,21 @@ def _get_chat_session(user_id: int, agent_id: int, session_id: str | None):
).first()
def _chat_logs_for_session(user_id: int, agent_id: int, session: ChatSession):
match_ids = {session.session_id}
external_id = str(session.external_conversation_id or '').strip()
if external_id:
match_ids.add(external_id)
return db.session.query(ChatLog).filter(
ChatLog.user_id == user_id,
ChatLog.agent_id == agent_id,
or_(
ChatLog.session_id.in_(match_ids),
ChatLog.conversation_id.in_(match_ids),
),
).order_by(ChatLog.created_at.asc()).all()
def _ensure_chat_session(
user_id: int,
agent_id: int,
@@ -742,9 +757,19 @@ def get_chat_sessions():
if user is None or agent is None:
raise AppError(code='SYSTEM.INTERNAL_ERROR', message='Missing context', http_status=500)
session_rows = db.session.query(ChatSession).filter_by(
user_id=user.id,
agent_id=agent.id,
session_rows = db.session.query(ChatSession).filter(
ChatSession.user_id == user.id,
ChatSession.agent_id == agent.id,
or_(
ChatSession.status == 'running',
exists().where(
and_(
ChatLog.session_id == ChatSession.session_id,
ChatLog.user_id == user.id,
ChatLog.agent_id == agent.id,
)
),
),
).order_by(desc(ChatSession.last_active_at), desc(ChatSession.id)).limit(20).all()
sessions = [_serialize_session(item) for item in session_rows]
@@ -857,14 +882,12 @@ def get_chat_messages():
session = _get_chat_session(getattr(g.current_user, 'id', 0), getattr(g.current_agent, 'id', 0), conversation_id)
if session:
logs = _chat_logs_for_session(g.current_user.id, g.current_agent.id, session)
else:
logs = db.session.query(ChatLog).filter(
ChatLog.user_id == g.current_user.id,
ChatLog.agent_id == g.current_agent.id,
ChatLog.session_id == session.session_id,
).order_by(ChatLog.created_at.asc()).all()
else:
logs = db.session.query(ChatLog).filter_by(
conversation_id=conversation_id
ChatLog.conversation_id == conversation_id,
).order_by(ChatLog.created_at.asc()).all()
messages = []
@@ -1325,7 +1348,7 @@ def upload_chat_file():
headers=headers,
files={'file': (filename or 'upload', upload.stream, mimetype or 'application/octet-stream')},
data={'user': str(getattr(user, 'id', 'system'))},
timeout=(5, 60),
timeout=(5, 300),
)
except requests.RequestException as exc:
raise ServiceUnavailableError(f'Upload failed: {exc}')
+15 -15
View File
@@ -45,9 +45,9 @@ def openapi_dify_yaml():
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
@shipping_notice_bp.route("/tools/create_case", methods=["POST"])
def tool_create_case():
return jsonify(shipping_tools.create_case(_payload()))
@shipping_notice_bp.route("/tools/create_task", methods=["POST"])
def tool_create_task():
return jsonify(shipping_tools.create_task(_payload()))
@shipping_notice_bp.route("/tools/parse_notice", methods=["POST"])
@@ -63,9 +63,9 @@ def tool_parse_inventory():
@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."""
case_id = str(request.form.get("case_id") or request.args.get("case_id") or "").strip()
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(case_id, upload))
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
@shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"])
@@ -103,9 +103,9 @@ def tool_upload_to_freight():
return jsonify(shipping_tools.upload_to_freight(_payload()))
@shipping_notice_bp.route("/tools/get_case_status", methods=["POST"])
def tool_get_case_status():
return jsonify(shipping_tools.get_case_status(_payload()))
@shipping_notice_bp.route("/tools/get_task_status", methods=["POST"])
def tool_get_task_status():
return jsonify(shipping_tools.get_task_status(_payload()))
@shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"])
@@ -118,19 +118,19 @@ def rpa_upload_complete():
return jsonify(shipping_tools.rpa_report_upload(_payload()))
@shipping_notice_bp.route("/cases/<case_no>/export", methods=["GET"])
def download_case_export(case_no: str):
from app.services.shipping_notice.tools import _get_case
@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
case = _get_case(case_no)
if not case or not case.export_file_path:
task = _get_task(task_no)
if not task or not task.export_file_path:
return jsonify({"error": "export file not found"}), 404
path = Path(case.export_file_path)
path = Path(task.export_file_path)
if not path.is_file():
return jsonify({"error": "export file missing on disk"}), 404
return send_file(
path,
as_attachment=True,
download_name=case.export_file_name or path.name,
download_name=task.export_file_name or path.name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
+226 -33
View File
@@ -3,12 +3,14 @@ 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.services.shipping_notice.chat_actions import build_chat_actions_payload
from app.services.shipping_notice.query_service import (
get_case_for_user,
list_cases_for_user,
serialize_case_detail,
get_task_for_user,
list_tasks_for_user,
serialize_task_detail,
)
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
@@ -21,62 +23,200 @@ def _require_user():
return user, None
@workspace_shipping_notice_bp.route("/shipping-cases", methods=["GET"])
def workspace_shipping_cases():
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["GET"])
def workspace_shipping_tasks():
user, err = _require_user()
if err:
return err
process_status = str(request.args.get("process_status") or "").strip() or None
limit = int(request.args.get("limit") or 100)
return jsonify(list_cases_for_user(user.id, process_status=process_status, limit=limit))
return jsonify(list_tasks_for_user(user.id, process_status=process_status, limit=limit))
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>", methods=["GET"])
def workspace_shipping_case_detail(case_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["POST"])
def workspace_create_shipping_task():
user, err = _require_user()
if err:
return err
case = get_case_for_user(case_no, user.id)
if not case:
return jsonify({"error": "Not found"}), 404
return jsonify(serialize_case_detail(case))
data = request.get_json(silent=True) or {}
payload = {"user_id": user.id}
source_type = str(data.get("source_type") or "").strip()
if source_type:
payload["source_type"] = source_type
conversation_id = str(data.get("conversation_id") or "").strip()
if conversation_id:
payload["conversation_id"] = conversation_id
raw_content = str(data.get("raw_content") or "").strip()
if raw_content:
payload["raw_content"] = raw_content
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.create_task(payload))
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/chat-actions", methods=["GET"])
def workspace_shipping_case_chat_actions(case_no: str):
@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
case = get_case_for_user(case_no, user.id)
if not case:
upload = request.files.get("file")
if not upload:
return jsonify({"error": "file 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,
)
source_type = guess_source_type(upload.filename or "")
created = shipping_tools.create_task({"user_id": user.id, "source_type": source_type})
task_id = str(created.get("task_id") or "").strip()
if not task_id:
return jsonify({"error": "failed to create task"}), 500
raw = upload.read() or b""
saved_path = save_task_notice_upload(task_id, upload.filename or "notice", raw)
text, meta = extract_notice_text(saved_path)
dify_file_id = ""
notice_files = None
try:
from app.config import Config
from app.services.dify import DifyService
from app.services.shipping_notice.agent_resolver import resolve_extract_agent
import requests
agent = resolve_extract_agent()
api_key = str(getattr(agent, "dify_api_key", "") or "").strip() if agent else ""
if api_key:
base_url = agent.api_base_url if getattr(agent, "api_base_url", None) else Config.DIFY_API_BASE
dify_url = DifyService._build_files_upload_url(base_url)
resp = requests.post(
dify_url,
headers={"Authorization": f"Bearer {api_key}"},
files={"file": (upload.filename or "notice", raw, upload.mimetype or "application/octet-stream")},
data={"user": str(user.id)},
timeout=(5, 300),
)
if resp.ok:
data = resp.json() if resp.content else {}
dify_file_id = str(data.get("id") or "").strip()
if dify_file_id:
notice_files = [
{
"type": "document",
"transfer_method": "local_file",
"upload_file_id": dify_file_id,
}
]
else:
meta.setdefault("warnings", []).append(f"dify_upload_failed:{resp.status_code}")
except Exception as exc:
meta.setdefault("warnings", []).append(f"dify_upload_error:{exc}")
if (not text) and (not notice_files):
return jsonify(
{
"status": "needs_human",
"task_id": task_id,
"message": "未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。",
"data": {"notice_upload": {"filename": upload.filename or "", "dify_file_id": dify_file_id, **meta}},
"human_options": ["reparse", "reject"],
"checkpoint": "notice_text_extraction_failed",
}
)
if text:
limit = max_notice_chars()
if len(text) > limit:
text = text[:limit]
meta.setdefault("warnings", []).append(f"notice_text_truncated:{limit}")
task = ShippingTask.query.filter_by(task_no=task_id).first()
if task:
task.raw_content = text
db.session.commit()
payload = {"task_id": task_id}
if notice_files:
payload["notice_files"] = notice_files
parsed = shipping_tools.parse_notice(payload)
data = parsed.get("data") if isinstance(parsed, dict) else None
if isinstance(data, dict):
data["notice_upload"] = {"filename": upload.filename or "", "dify_file_id": dify_file_id, **meta}
parsed["message"] = f"已上传发货通知文件并创建任务 {task_id}。{parsed.get('message') or ''}".strip()
return jsonify(parsed)
@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
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
return jsonify(build_chat_actions_payload(case))
return jsonify(serialize_task_detail(task))
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/upload-inventory", methods=["POST"])
def workspace_upload_shipping_inventory(case_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
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
return jsonify(build_chat_actions_payload(task))
@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)."""
user, err = _require_user()
if err:
return err
case = get_case_for_user(case_no, user.id)
if not case:
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
upload = request.files.get("file")
from app.services.shipping_notice import tools as shipping_tools
return jsonify(shipping_tools.upload_inventory_file(case.case_no, upload))
return jsonify(shipping_tools.upload_inventory_file(task.task_no, upload))
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/submit-decision", methods=["POST"])
def workspace_submit_shipping_decision(case_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
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 {}
column_mapping_json = data.get("column_mapping_json")
if not isinstance(column_mapping_json, dict) or not column_mapping_json:
return jsonify({"error": "column_mapping_json is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "column_mapping_json": column_mapping_json}
return jsonify(shipping_tools.apply_inventory_mapping(payload))
@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)."""
user, err = _require_user()
if err:
return err
case = get_case_for_user(case_no, user.id)
if not case:
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 {}
@@ -86,27 +226,80 @@ def workspace_submit_shipping_decision(case_no: str):
from app.services.shipping_notice import tools as shipping_tools
payload = {"case_id": case.case_no, "decision": decision}
payload = {"task_id": task.task_no, "decision": decision}
comment = str(data.get("comment") or "").strip()
if comment:
payload["comment"] = comment
return jsonify(shipping_tools.submit_decision(payload))
@workspace_shipping_notice_bp.route("/shipping-cases/<case_no>/export", methods=["GET"])
def workspace_shipping_case_export(case_no: str):
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/match-inventory", methods=["POST"])
def workspace_match_shipping_inventory(task_no: str):
user, err = _require_user()
if err:
return err
case = get_case_for_user(case_no, user.id)
if not case or not case.export_file_path:
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
from app.services.shipping_notice import tools as shipping_tools
matched = shipping_tools.match_inventory({"task_id": task.task_no})
if isinstance(matched, dict) and matched.get("status") == "ok":
generated = shipping_tools.generate_excel({"task_id": task.task_no})
if isinstance(generated, dict) and generated.get("status") == "ok":
msg = "\n".join(
[
str(matched.get("message") or "").strip(),
str(generated.get("message") or "").strip(),
]
).strip()
generated["message"] = msg
data = generated.get("data")
if not isinstance(data, dict):
data = {}
generated["data"] = data
data["download_url"] = f"/api/workspace/shipping-tasks/{task.task_no}/export"
generated["checkpoint"] = generated.get("checkpoint") or "export_generated"
return jsonify(generated)
return jsonify(matched)
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/generate-excel", methods=["POST"])
def workspace_generate_shipping_excel(task_no: str):
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
from app.services.shipping_notice import tools as shipping_tools
result = shipping_tools.generate_excel({"task_id": task.task_no})
if isinstance(result, dict) and result.get("status") == "ok":
data = result.get("data")
if not isinstance(data, dict):
data = {}
result["data"] = data
data["download_url"] = f"/api/workspace/shipping-tasks/{task.task_no}/export"
return jsonify(result)
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/export", methods=["GET"])
def workspace_shipping_task_export(task_no: str):
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(case.export_file_path)
path = Path(task.export_file_path)
if not path.is_file():
return jsonify({"error": "export file missing on disk"}), 404
return send_file(
path,
as_attachment=True,
download_name=case.export_file_name or path.name,
download_name=task.export_file_name or path.name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
+26 -6
View File
@@ -51,6 +51,20 @@ def _load_environment_files() -> str:
ACTIVE_ENV_NAME = _load_environment_files()
def _data_path(env_key: str, *parts: str) -> str:
from app.path_utils import resolve_backend_relative_path
default = _BACKEND_DIR.joinpath("data", *parts)
return resolve_backend_relative_path(os.getenv(env_key), default)
def _backend_path(env_key: str, *parts: str) -> str:
from app.path_utils import resolve_backend_relative_path
default = _BACKEND_DIR.joinpath(*parts)
return resolve_backend_relative_path(os.getenv(env_key), default)
class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY')
@@ -94,7 +108,7 @@ class Config:
SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY')
# OpenAPI servers.url 基地址(Dify 调 Tool 时访问 hxops,不是 Dify 的 8882)
SHIPPING_NOTICE_TOOL_API_BASE = os.getenv('SHIPPING_NOTICE_TOOL_API_BASE')
SHIPPING_NOTICE_STORAGE_ROOT = os.getenv('SHIPPING_NOTICE_STORAGE_ROOT')
SHIPPING_NOTICE_STORAGE_ROOT = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
)
@@ -102,11 +116,17 @@ class Config:
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
)
FREIGHT_INVENTORY_DROP_DIR = os.getenv('FREIGHT_INVENTORY_DROP_DIR')
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = os.getenv('FREIGHT_RPA_INVENTORY_TRIGGER_DIR')
FREIGHT_UPLOAD_QUEUE_DIR = os.getenv('FREIGHT_UPLOAD_QUEUE_DIR')
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = os.getenv('FREIGHT_RPA_UPLOAD_TRIGGER_DIR')
FREIGHT_SHIPMENT_TEMPLATE_PATH = os.getenv('FREIGHT_SHIPMENT_TEMPLATE_PATH')
FREIGHT_INVENTORY_DROP_DIR = _data_path("FREIGHT_INVENTORY_DROP_DIR", "freight_rpa", "inventory_drop")
FREIGHT_RPA_INVENTORY_TRIGGER_DIR = _data_path(
"FREIGHT_RPA_INVENTORY_TRIGGER_DIR", "freight_rpa", "inventory_triggers"
)
FREIGHT_UPLOAD_QUEUE_DIR = _data_path("FREIGHT_UPLOAD_QUEUE_DIR", "freight_rpa", "upload_queue")
FREIGHT_RPA_UPLOAD_TRIGGER_DIR = _data_path(
"FREIGHT_RPA_UPLOAD_TRIGGER_DIR", "freight_rpa", "upload_triggers"
)
FREIGHT_SHIPMENT_TEMPLATE_PATH = _backend_path(
"FREIGHT_SHIPMENT_TEMPLATE_PATH", "templates", "freight_shipment_upload.xlsx"
)
# WeCom (企业微信) 登录配置
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
+32 -14
View File
@@ -680,16 +680,16 @@ class ScheduleRun(Base):
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
class ShippingCase(Base):
"""货代发货通知 case(Chatflow Tool 编排状态机)"""
__tablename__ = 'shipping_cases'
class ShippingTask(Base):
"""货代发货通知 task(Chatflow Tool 编排状态机)"""
__tablename__ = 'shipping_tasks'
__table_args__ = (
Index('ix_shipping_cases_user_status', 'user_id', 'process_status'),
Index('ix_shipping_cases_conversation', 'conversation_id'),
Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'),
Index('ix_shipping_tasks_conversation', 'conversation_id'),
)
id: Mapped[int] = mapped_column(primary_key=True)
case_no: Mapped[str] = mapped_column(String(64), unique=True, index=True)
task_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)
source_type: Mapped[str] = mapped_column(String(32), default='manual')
@@ -698,6 +698,7 @@ class ShippingCase(Base):
customer_name: Mapped[Optional[str]] = mapped_column(String(200), nullable=True)
customer_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
ship_to: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
po_number: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
required_date: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
lines_json: Mapped[Optional[list]] = mapped_column(JSON, default=list)
parse_confidence: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
@@ -719,22 +720,39 @@ class ShippingCase(Base):
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
events: Mapped[List["ShippingCaseEvent"]] = relationship(
"ShippingCaseEvent",
back_populates="case",
events: Mapped[List["ShippingTaskEvent"]] = relationship(
"ShippingTaskEvent",
back_populates="task",
cascade="all, delete-orphan",
)
class ShippingCaseEvent(Base):
"""发货 case 审计事件"""
__tablename__ = 'shipping_case_events'
class ShippingTaskEvent(Base):
"""发货 task 审计事件"""
__tablename__ = 'shipping_task_events'
id: Mapped[int] = mapped_column(primary_key=True)
case_id: Mapped[int] = mapped_column(ForeignKey('shipping_cases.id'), index=True)
task_id: Mapped[int] = mapped_column(ForeignKey('shipping_tasks.id'), index=True)
event_type: Mapped[str] = mapped_column(String(64), index=True)
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
case: Mapped["ShippingCase"] = relationship("ShippingCase", back_populates="events")
task: Mapped["ShippingTask"] = relationship("ShippingTask", back_populates="events")
class ShippingInventoryMapping(Base):
__tablename__ = 'shipping_inventory_mappings'
__table_args__ = (
UniqueConstraint('customer_code', 'header_hash', name='uq_shipping_inventory_mappings_customer_header'),
Index('ix_shipping_inventory_mappings_customer_code', 'customer_code'),
)
id: Mapped[int] = mapped_column(primary_key=True)
customer_code: Mapped[str] = mapped_column(String(64), nullable=False)
header_hash: Mapped[str] = mapped_column(String(64), nullable=False)
headers_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
field_mapping_json: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
last_used_at: Mapped[Optional[datetime]] = mapped_column(DateTime, 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, index=True)
+28
View File
@@ -0,0 +1,28 @@
"""Resolve paths relative to the backend package root (not process cwd)."""
from __future__ import annotations
from pathlib import Path
_BACKEND_DIR = Path(__file__).resolve().parents[1]
def backend_dir() -> Path:
return _BACKEND_DIR
def resolve_backend_relative_path(raw: str | None, default: Path | None = None) -> str:
"""Resolve env paths like ``data/foo`` or legacy ``backend/data/foo``."""
value = (raw or "").strip()
if not value:
if default is None:
raise ValueError("path is required when no default is provided")
return str(default.resolve())
path = Path(value)
if path.is_absolute():
return str(path.resolve())
normalized = value.replace("\\", "/")
if normalized.startswith("backend/"):
return str((_BACKEND_DIR / normalized[len("backend/") :]).resolve())
return str((_BACKEND_DIR / value).resolve())
+86 -56
View File
@@ -206,12 +206,28 @@ class DifyService:
@staticmethod
def _stringify_inputs(inputs: dict[str, Any] | None) -> dict[str, Any]:
def _is_file_obj(v: Any) -> bool:
if not isinstance(v, dict):
return False
if not str(v.get("type") or "").strip():
return False
tm = str(v.get("transfer_method") or "").strip()
if tm not in {"local_file", "remote_url"}:
return False
if tm == "local_file":
return bool(str(v.get("upload_file_id") or "").strip())
return bool(str(v.get("url") or "").strip())
def _convert(v):
if v is None:
return ""
if _is_file_obj(v):
return v
if isinstance(v, dict):
return {kk: _convert(vv) for kk, vv in v.items()}
if isinstance(v, list):
if v and all(_is_file_obj(i) for i in v):
return v
return [_convert(i) for i in v]
return str(v)
return {k: _convert(v) for k, v in (inputs or {}).items()}
@@ -550,11 +566,78 @@ class DifyService:
full_answer: List[str] = []
retriever_resources: List[Any] = []
attribution_parts: List[str] = []
chat_logged = False
def persist_stream_chat(data: dict, event_name: str) -> None:
nonlocal chat_logged
if chat_logged:
return
if data.get('answer'):
full_answer.append(data.get('answer', ''))
answer_text = ''.join(full_answer).strip()
if not answer_text and event_name == 'workflow_finished':
wf_data = data.get('data') or {}
outputs = wf_data.get('outputs') if isinstance(wf_data, dict) else None
if isinstance(outputs, dict):
for key in ('answer', 'text', 'result'):
value = outputs.get(key)
if isinstance(value, str) and value.strip():
answer_text = value.strip()
break
if not answer_text and not str(query or '').strip():
return
if current_app:
current_app.logger.info(
"[source-link] persist chat request_id=%s event=%s collected retriever_resources=%s",
request_id,
event_name,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
with current_app.app_context():
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=answer_text,
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
if chat_log_id:
data['chat_log_id'] = chat_log_id
chat_logged = True
if current_app:
current_app.logger.info(
"[chat-perf] persisted request_id=%s event=%s total_ms=%s db_write_ms=%s answer_len=%s conversation_id=%s",
request_id,
event_name,
latency,
int((time.time() - db_write_started) * 1000),
len(answer_text),
data.get('conversation_id') or normalized_conversation_id,
)
max_retries = 3
for attempt in range(1, max_retries + 1):
try:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 300)) as response:
if current_app:
current_app.logger.info(
"[chat-stream] dify response request_id=%s status=%s reason=%s attempt=%s",
@@ -625,63 +708,10 @@ class DifyService:
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
elif event in ('message_end', 'agent_message', 'workflow_finished'):
if event == 'message_end' and data.get('answer'):
full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
if event == 'message_end':
message_end_started = time.time()
if current_app:
current_app.logger.info(
"[source-link] message_end request_id=%s collected retriever_resources=%s",
request_id,
len(retriever_resources),
)
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
enrich_done_at = time.time()
metadata = data.get('metadata') or {}
metadata['retriever_resources'] = retriever_resources
data['metadata'] = metadata
data['retriever_resources'] = retriever_resources
latency = int((time.time() - start_time) * 1000)
usage = metadata.get('usage', {}) or {}
db_write_started = time.time()
with current_app.app_context():
chat_log_id = DifyService._log_chat(
user_id=user_id,
agent_id=agent.id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query,
answer=''.join(full_answer),
tokens=usage.get('total_tokens', 0),
latency=latency,
retriever_resources=retriever_resources,
attribution_parts=attribution_parts,
)
db_write_done_at = time.time()
if chat_log_id:
data['chat_log_id'] = chat_log_id
if current_app:
current_app.logger.info(
"[chat-perf] summary request_id=%s total_ms=%s ttft_ms=%s stream_ms=%s postprocess_ms=%s enrich_ms=%s db_write_ms=%s events=%s message_events=%s answer_len=%s resources=%s attribution=%s conversation_id=%s",
request_id,
latency,
int((first_token_at - start_time) * 1000) if first_token_at else None,
int((message_end_started - first_token_at) * 1000) if first_token_at else None,
int((time.time() - message_end_started) * 1000),
int((enrich_done_at - message_end_started) * 1000),
int((db_write_done_at - db_write_started) * 1000),
event_count,
message_count,
len(''.join(full_answer)),
len(retriever_resources),
len(attribution_parts),
data.get('conversation_id') or normalized_conversation_id,
)
if event in ('message_end', 'workflow_finished'):
persist_stream_chat(data, event)
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
break
@@ -2,7 +2,7 @@ from __future__ import annotations
from typing import Any
from app.models import ShippingCase
from app.models import ShippingTask
ACTION_SPECS: dict[str, dict[str, str]] = {
"confirm": {"label": "确认", "message": "确认", "variant": "primary"},
@@ -20,6 +20,7 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
},
"retry_upload": {"label": "重试上传", "message": "重试上传货代", "variant": "secondary"},
"download_excel": {"label": "下载 Excel", "message": "下载发货 Excel", "variant": "secondary"},
"generate_excel": {"label": "生成发货 Excel", "message": "生成发货 Excel", "variant": "primary"},
"mark_manual_uploaded": {
"label": "已手工上传",
"message": "已在货代系统手工上传完成",
@@ -30,49 +31,83 @@ ACTION_SPECS: dict[str, dict[str, str]] = {
"message": "我粘贴库存小表",
"variant": "secondary",
},
"edit_inventory_mapping": {
"label": "修改映射",
"message": "修改库存列映射",
"variant": "primary",
},
"match_inventory": {
"label": "匹配库存",
"message": "匹配库存",
"variant": "primary",
},
}
def human_options_for_case(case: ShippingCase) -> list[str] | None:
if case.process_status == "rejected" or case.review_status == "rejected":
def human_options_for_task(task: ShippingTask) -> list[str] | None:
if task.process_status == "rejected" or task.review_status == "rejected":
return []
reason = case.pending_human_reason
if reason == "inventory_field_mapping_review" or case.review_status == "inventory_mapping_review":
if (
task.process_status == "parsed"
and not task.review_status
and not task.pending_human_reason
and not task.inventory_lines_json
):
return ["upload_inventory_file", "retry_rpa", "paste_inventory_json"]
if (
task.process_status == "inventory_ready"
and not task.review_status
and not task.pending_human_reason
and not task.match_status
and isinstance(task.lines_json, list)
and len(task.lines_json) > 0
):
return ["match_inventory"]
if task.process_status == "matched":
if task.export_file_path:
return ["download_excel", "mark_manual_uploaded"]
return ["generate_excel"]
reason = task.pending_human_reason
if reason == "inventory_field_mapping_review" or task.review_status == "inventory_mapping_review":
return ["confirm_inventory_mapping", "correct_inventory_mapping", "reparse_inventory", "reject"]
if reason == "inventory_mapping_inference":
return ["upload_inventory_file", "paste_inventory_json"]
return ["edit_inventory_mapping", "upload_inventory_file", "paste_inventory_json", "retry_rpa"]
if reason == "reservation_id_required" or task.review_status == "reservation_id_required":
return ["reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"]
if reason == "inventory_unavailable":
return ["retry_rpa", "upload_inventory_file"]
if reason == "inventory_shortage" or case.review_status == "inventory_shortage_review":
if reason == "inventory_shortage" or task.review_status == "inventory_shortage_review":
return ["confirm", "reject", "rematch"]
if reason == "low_parse_confidence" or case.review_status == "parse_review":
if reason == "low_parse_confidence" or task.review_status == "parse_review":
return ["confirm", "reject", "reparse"]
if reason == "upload_rpa_failed" or case.process_status == "upload_failed":
if reason == "upload_rpa_failed" or task.process_status == "upload_failed":
return ["retry_upload", "download_excel", "mark_manual_uploaded"]
if reason == "inventory_rpa_pending" or (
case.process_status == "waiting_inventory" and reason == "inventory_rpa_pending"
task.process_status == "waiting_inventory" and reason == "inventory_rpa_pending"
):
return ["retry_rpa", "upload_inventory_file"]
if reason == "upload_rpa_pending" or case.process_status == "waiting_upload":
if reason == "upload_rpa_pending" or task.process_status == "waiting_upload":
return ["retry_upload", "download_excel", "mark_manual_uploaded"]
return None
def checkpoint_for_case(case: ShippingCase) -> str | None:
if case.process_status == "rejected" or case.review_status == "rejected":
def checkpoint_for_task(task: ShippingTask) -> str | None:
if task.process_status == "rejected" or task.review_status == "rejected":
return "rejected"
reason = case.pending_human_reason
if reason == "inventory_field_mapping_review" or case.review_status == "inventory_mapping_review":
reason = task.pending_human_reason
if reason == "inventory_field_mapping_review" or task.review_status == "inventory_mapping_review":
return "inventory_field_mapping_review"
if reason == "low_parse_confidence" or case.review_status == "parse_review":
if reason == "low_parse_confidence" or task.review_status == "parse_review":
return "parse_review"
if reason == "inventory_shortage" or case.review_status == "inventory_shortage_review":
if reason == "inventory_shortage" or task.review_status == "inventory_shortage_review":
return "inventory_shortage_review"
if reason == "inventory_unavailable":
return "inventory_upload_required"
if reason == "inventory_mapping_inference":
return "inventory_mapping_inference"
if reason == "upload_rpa_failed" or case.process_status == "upload_failed":
if reason == "reservation_id_required" or task.review_status == "reservation_id_required":
return "reservation_id_required"
if reason == "upload_rpa_failed" or task.process_status == "upload_failed":
return "upload_failed"
return None
@@ -89,14 +124,14 @@ def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
return buttons
def build_chat_actions_payload(case: ShippingCase) -> dict[str, Any]:
options = human_options_for_case(case)
def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]:
options = human_options_for_task(task)
buttons = build_action_buttons(options)
return {
"case_no": case.case_no,
"checkpoint": checkpoint_for_case(case),
"process_status": case.process_status,
"review_status": case.review_status,
"pending_human_reason": case.pending_human_reason,
"task_no": task.task_no,
"checkpoint": checkpoint_for_task(task),
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"action_buttons": buttons,
}
+16 -16
View File
@@ -8,7 +8,7 @@ from shutil import copy2
from flask import current_app
from openpyxl import Workbook, load_workbook
from app.models import ShippingCase
from app.models import ShippingTask
DEFAULT_HEADERS = [
"客户名称",
@@ -39,13 +39,13 @@ def _default_template_path() -> Path | None:
return bundled if bundled.is_file() else None
def _row_values(case: ShippingCase, line: dict | None) -> list:
def _row_values(task: ShippingTask, line: dict | None) -> list:
line = line or {}
return [
case.customer_name or "",
case.customer_code or "",
case.ship_to or "",
case.required_date or "",
task.customer_name or "",
task.customer_code or "",
task.ship_to or "",
line.get("required_date") or task.required_date or "",
line.get("sku") or "",
line.get("qty") or "",
line.get("uom") or "EA",
@@ -53,42 +53,42 @@ def _row_values(case: ShippingCase, line: dict | None) -> list:
]
def _fill_from_template(case: ShippingCase, path: Path) -> None:
def _fill_from_template(task: ShippingTask, path: Path) -> None:
wb = load_workbook(filename=str(path))
ws = wb.active
lines = case.lines_json or [None]
lines = task.lines_json or [None]
start_row = ws.max_row + 1 if ws.max_row >= 1 else 2
if ws.max_row == 1 and not any(ws.cell(1, c).value for c in range(1, 9)):
ws.append(DEFAULT_HEADERS)
start_row = 2
for line in lines:
ws.append(_row_values(case, line))
ws.append(_row_values(task, line))
wb.save(path)
def _fill_blank_workbook(case: ShippingCase, path: Path) -> None:
def _fill_blank_workbook(task: ShippingTask, path: Path) -> None:
wb = Workbook()
ws = wb.active
ws.title = "Shipment"
ws.append(DEFAULT_HEADERS)
lines = case.lines_json or [None]
lines = task.lines_json or [None]
for line in lines:
ws.append(_row_values(case, line))
ws.append(_row_values(task, line))
wb.save(path)
def generate_shipment_excel(case: ShippingCase) -> tuple[str, str]:
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str]:
root = _storage_root() / "exports"
root.mkdir(parents=True, exist_ok=True)
filename = f"shipment_{case.case_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
filename = f"shipment_{task.task_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
path = root / filename
template = _default_template_path()
if template:
copy2(template, path)
_fill_from_template(case, path)
_fill_from_template(task, path)
else:
_fill_blank_workbook(case, path)
_fill_blank_workbook(task, path)
return str(path), filename
@@ -1,12 +1,18 @@
from __future__ import annotations
import json
import os
import re
from typing import Any
from app.services.dify import DifyService
from app.services.shipping_notice.po_number import enrich_notice_with_po_number
from app.services.shipping_notice.reservation_id import find_reservation_id_in_document
from app.services.shipping_notice.agent_resolver import resolve_extract_agent
from app.services.shipping_notice.notice_lines import (
enrich_notice_with_document_currency,
enrich_notice_with_document_required_date,
enrich_notice_with_document_reservation,
normalize_notice_lines,
parse_notice_table_text,
validate_notice_lines,
@@ -35,9 +41,18 @@ def _parse_workflow_outputs(result: dict[str, Any]) -> dict[str, Any] | None:
return outputs if outputs else None
def _finalize_notice_parse(parsed: dict[str, Any], *, base_confidence: float) -> tuple[dict[str, Any], float, list[str]]:
def _finalize_notice_parse(
parsed: dict[str, Any],
*,
base_confidence: float,
raw_text: str = "",
) -> tuple[dict[str, Any], float, list[str]]:
lines = normalize_notice_lines(parsed.get("lines") if isinstance(parsed.get("lines"), list) else [])
parsed = {**parsed, "lines": lines}
parsed = enrich_notice_with_document_reservation({**parsed, "lines": lines}, raw_text=raw_text)
parsed = enrich_notice_with_document_required_date(parsed)
parsed = enrich_notice_with_document_currency(parsed)
parsed = enrich_notice_with_po_number(parsed, raw_text=raw_text)
lines = parsed.get("lines") if isinstance(parsed.get("lines"), list) else []
warnings = validate_notice_lines(lines)
from app.services.shipping_notice.notice_lines import notice_parse_completeness
@@ -46,23 +61,63 @@ def _finalize_notice_parse(parsed: dict[str, Any], *, base_confidence: float) ->
return parsed, round(confidence, 4), warnings
def _resolve_workflow_file_input_key(agent) -> str | None:
forced = str(os.getenv("SHIPPING_NOTICE_EXTRACT_DIFY_FILE_INPUT_KEY") or "").strip()
if forced:
return forced
params = DifyService.get_app_parameters(agent) or {}
def _walk(v: Any) -> str | None:
if isinstance(v, dict):
var = str(v.get("variable") or v.get("name") or "").strip()
t = str(v.get("type") or v.get("value_type") or v.get("valueType") or "").strip().lower()
has_file_cfg = isinstance(v.get("file"), dict) or isinstance(v.get("file_upload"), dict) or isinstance(v.get("fileUpload"), dict)
if var and (has_file_cfg or t in {"file", "files", "file_array", "filearray", "file-list", "file_list"}):
return var
for vv in v.values():
hit = _walk(vv)
if hit:
return hit
elif isinstance(v, list):
for item in v:
hit = _walk(item)
if hit:
return hit
return None
return _walk(params)
def extract_notice_fields(
*,
raw_text: str,
source_type: str = "manual",
structured: dict[str, Any] | None = None,
notice_files: list[dict[str, Any]] | None = None,
) -> tuple[dict[str, Any], float, list[str]]:
warnings: list[str] = []
if structured and isinstance(structured, dict):
return _finalize_notice_parse(structured, base_confidence=float(structured.get("confidence") or 0.95))
return _finalize_notice_parse(
structured,
base_confidence=float(structured.get("confidence") or 0.95),
raw_text=str(structured.get("raw_text") or ""),
)
agent = resolve_extract_agent()
if agent and raw_text.strip():
if agent and (raw_text.strip() or notice_files):
try:
inputs: dict[str, Any] = {"raw_text": raw_text, "source_type": source_type}
if notice_files:
key = _resolve_workflow_file_input_key(agent)
if key:
inputs[key] = notice_files
else:
warnings.append("workflow_file_input_key_missing")
result = DifyService.run_workflow_streaming(
agent=agent,
inputs={"raw_text": raw_text, "source_type": source_type},
inputs=inputs,
user="shipping_notice_tool",
)
parsed = _parse_workflow_outputs(result)
@@ -70,6 +125,7 @@ def extract_notice_fields(
finalized, confidence, line_warnings = _finalize_notice_parse(
parsed,
base_confidence=float(parsed.get("confidence") or 0.85),
raw_text=raw_text,
)
warnings.extend(line_warnings)
return finalized, confidence, warnings
@@ -79,7 +135,7 @@ def extract_notice_fields(
heuristic, confidence, heuristic_warnings = _heuristic_extract(raw_text)
warnings.extend(heuristic_warnings)
return _finalize_notice_parse(heuristic, base_confidence=confidence)
return _finalize_notice_parse(heuristic, base_confidence=confidence, raw_text=raw_text)
def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]:
@@ -92,6 +148,11 @@ def _heuristic_extract(raw_text: str) -> tuple[dict[str, Any], float, list[str]]
lines = parse_notice_table_text(text)
if lines:
doc_rid = find_reservation_id_in_document(text)
if doc_rid:
for line in lines:
if not line.get("reservation_id"):
line["reservation_id"] = doc_rid
return (
{
"customer_name": customer_name,
@@ -2,11 +2,12 @@ from __future__ import annotations
from typing import Any
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
SYSTEM_FIELDS = ("sku", "reservation_id", "available_qty")
def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
"""Parse LLM/manual mapping: system_field -> Excel column header name."""
data: dict[str, Any] | None = None
if isinstance(raw, dict):
data = raw
@@ -34,7 +35,7 @@ def normalize_field_mapping(raw: Any) -> dict[str, str] | None:
text = str(value).strip()
if text:
result[key] = text
return result if "sku" in result and "available_qty" in result else None
return result if "sku" in result and "available_qty" in result and "reservation_id" in result else None
def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
@@ -68,6 +69,7 @@ def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
"Reservation ID",
"COM ID",
"Reservation Order",
"Resevation Order",
"Reservation No",
)
if reservation:
@@ -83,7 +85,7 @@ def suggest_field_mapping(headers: list[str]) -> dict[str, str]:
def mapping_is_complete(field_mapping: dict[str, str]) -> bool:
return bool(field_mapping.get("sku") and field_mapping.get("available_qty"))
return bool(field_mapping.get("sku") and field_mapping.get("available_qty") and field_mapping.get("reservation_id"))
def validate_field_mapping_against_headers(
@@ -102,7 +104,7 @@ def validate_field_mapping_against_headers(
for key, label in labels.items():
name = str(field_mapping.get(key) or "").strip()
if not name:
if key in ("sku", "available_qty"):
if key in ("sku", "available_qty", "reservation_id"):
errors.append(f"缺少 {label} 列映射")
continue
if name not in norm_headers and name.lower() not in lower_set:
@@ -148,6 +150,8 @@ def build_column_meta_from_mapping(
field_mapping: dict[str, str],
*,
mapping_source: str = "rules",
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
) -> dict[str, Any]:
columns = resolve_columns_from_field_mapping(headers, field_mapping)
@@ -158,6 +162,11 @@ def build_column_meta_from_mapping(
return text or None
qty_header = field_mapping.get("available_qty")
match_rule, match_key, match_rule_source = resolve_match_rule(
field_mapping,
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
)
return {
"headers": [str(h or "").strip() for h in headers],
"mapping_source": mapping_source,
@@ -180,6 +189,7 @@ def build_column_meta_from_mapping(
"qty_preference": "available_qty",
},
},
"match_key": ["sku", "reservation_id"],
"match_rule": "按 SKU + Reservation ID(若有)汇总可用数量,与订单 qty 比对",
"match_key": match_key,
"match_rule": match_rule,
"match_rule_source": match_rule_source,
}
@@ -0,0 +1,79 @@
from __future__ import annotations
import json
from datetime import datetime
from hashlib import sha256
from typing import Any
from app import db
from app.models import ShippingInventoryMapping
_GLOBAL_CUSTOMER_CODE = "GLOBAL"
def _customer_key(customer_code: str | None) -> str:
key = str(customer_code or "").strip()
return key or _GLOBAL_CUSTOMER_CODE
def compute_inventory_header_hash(headers: list[str], header_row_index: int | None = None) -> str:
norm_headers = [str(h or "").strip() for h in headers]
payload = {
"header_row_index": int(header_row_index or 1),
"headers": norm_headers,
}
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":"), sort_keys=True).encode("utf-8")
return sha256(raw).hexdigest()
def find_inventory_mapping(customer_code: str | None, header_hash: str) -> ShippingInventoryMapping | None:
customer = _customer_key(customer_code)
if not header_hash:
return None
return ShippingInventoryMapping.query.filter_by(customer_code=customer, header_hash=header_hash).first()
def resolve_inventory_mapping(
customer_code: str | None,
*,
preview: dict[str, Any],
) -> dict[str, str] | None:
customer = _customer_key(customer_code)
headers = preview.get("headers") if isinstance(preview.get("headers"), list) else []
header_hash = compute_inventory_header_hash(headers, preview.get("header_row_index"))
record = find_inventory_mapping(customer, header_hash)
if not record:
return None
record.last_used_at = datetime.utcnow()
if isinstance(record.field_mapping_json, dict) and record.field_mapping_json:
return {str(k): str(v) for k, v in record.field_mapping_json.items() if v}
return None
def upsert_inventory_mapping(
customer_code: str | None,
*,
preview: dict[str, Any],
field_mapping: dict[str, str],
) -> ShippingInventoryMapping | None:
customer = _customer_key(customer_code)
headers = preview.get("headers") if isinstance(preview.get("headers"), list) else []
header_hash = compute_inventory_header_hash(headers, preview.get("header_row_index"))
record = find_inventory_mapping(customer, header_hash)
now = datetime.utcnow()
if record:
record.field_mapping_json = dict(field_mapping)
record.headers_json = [str(h or "").strip() for h in headers]
record.updated_at = now
record.last_used_at = now
return record
record = ShippingInventoryMapping(
customer_code=customer,
header_hash=header_hash,
headers_json=[str(h or "").strip() for h in headers],
field_mapping_json=dict(field_mapping),
last_used_at=now,
)
db.session.add(record)
return record
@@ -10,7 +10,7 @@ from typing import Any
from flask import current_app
from openpyxl import load_workbook
from app.services.shipping_notice.reservation_id import normalize_reservation_id
from app.services.shipping_notice.reservation_id import extract_reservation_id, normalize_reservation_id
# 默认列映射:含 AWS DUB On Hand Inventory 模板(AWS Sku / Reservation ID / Qty)
@@ -22,6 +22,13 @@ DEFAULT_COLUMN_MAP = {
"AWS Sku": "sku",
"AWS SKU": "sku",
"Aws Sku": "sku",
"AWS SKU#": "sku",
"AWS Sku#": "sku",
"SKU#": "sku",
"Part No": "sku",
"Part No.": "sku",
"P/N": "sku",
"PN": "sku",
# Reservation
"Reservation ID": "reservation_id",
"Reservation Id": "reservation_id",
@@ -30,10 +37,17 @@ DEFAULT_COLUMN_MAP = {
"Reservation Order": "reservation_id",
# Quantity — 优先 Qty Available,其次 Qty
"Qty Available": "available_qty",
"Available": "available_qty",
"Avail Qty": "available_qty",
"可用数量": "available_qty",
"可用量": "available_qty",
"available_qty": "available_qty",
"库存": "available_qty",
"On Hand": "available_qty",
"OnHand": "available_qty",
"On Hand Qty": "available_qty",
"OnHand Qty": "available_qty",
"Qty On Hand": "available_qty",
"Qty": "qty",
"qty": "qty",
"数量": "qty",
@@ -61,6 +75,13 @@ def _column_map() -> dict[str, str]:
return DEFAULT_COLUMN_MAP
def _normalize_ascii_key(text: str) -> str:
raw = str(text or "").strip().lower()
if not raw:
return ""
return re.sub(r"[^a-z0-9]+", "", raw)
def _map_header(header: str, col_map: dict[str, str]) -> str | None:
text = str(header or "").strip()
if not text:
@@ -71,6 +92,11 @@ def _map_header(header: str, col_map: dict[str, str]) -> str | None:
for key, value in col_map.items():
if key.lower() == lower:
return value
norm = _normalize_ascii_key(text)
if not norm:
return None
norm_map = {_normalize_ascii_key(k): v for k, v in col_map.items() if _normalize_ascii_key(k)}
return norm_map.get(norm)
return None
@@ -147,7 +173,7 @@ def _normalize_inventory_row(
reservation_id = ""
idx_res = columns.get("reservation_id")
if idx_res is not None:
reservation_id = normalize_reservation_id(_cell(row, idx_res))
reservation_id = extract_reservation_id(_cell(row, idx_res))
idx_avail = columns.get("available_qty")
idx_qty = columns.get("qty")
@@ -224,8 +250,10 @@ def _rows_from_table_text(raw_text: str) -> list[list[str]]:
if "|" in stripped:
cells = [c.strip() for c in stripped.strip("|").split("|")]
cells = [c for c in cells if c]
elif "\t" in stripped:
cells = [c.strip() for c in stripped.split("\t") if c.strip()]
else:
cells = [c.strip() for c in re.split(r"[\t,,;;]+", stripped) if c.strip()]
cells = [c.strip() for c in re.split(r"[,,;;]+", stripped) if c.strip()]
if cells:
rows.append(cells)
return rows
@@ -239,12 +267,22 @@ def describe_inventory_columns(
*,
field_mapping: dict[str, str] | None = None,
mapping_source: str = "rules",
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
) -> dict[str, Any]:
"""Human-readable column mapping for field-alignment review."""
if field_mapping:
from app.services.shipping_notice.inventory_mapping import build_column_meta_from_mapping
return build_column_meta_from_mapping(headers, field_mapping, mapping_source=mapping_source)
return build_column_meta_from_mapping(
headers,
field_mapping,
mapping_source=mapping_source,
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
)
from app.services.shipping_notice.match_rule_desc import resolve_match_rule
col_map = _column_map()
columns = _resolve_inventory_columns(headers, col_map)
@@ -261,18 +299,34 @@ def describe_inventory_columns(
qty_source = source_column(columns.get("qty"))
qty_note = "Qty"
inferred_mapping: dict[str, str] = {}
sku_src = source_column(columns.get("sku"))
if sku_src:
inferred_mapping["sku"] = sku_src
rid_src = source_column(columns.get("reservation_id"))
if rid_src:
inferred_mapping["reservation_id"] = rid_src
if qty_source:
inferred_mapping["available_qty"] = qty_source
match_rule, match_key, match_rule_source = resolve_match_rule(
inferred_mapping,
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
)
return {
"headers": [str(h or "").strip() for h in headers],
"mapping": {
"sku": {
"system_field": "sku",
"label": "AWS Sku",
"source_column": source_column(columns.get("sku")),
"source_column": sku_src,
},
"reservation_id": {
"system_field": "reservation_id",
"label": "Reservation ID",
"source_column": source_column(columns.get("reservation_id")),
"source_column": rid_src,
"alternatives": list(_RESERVATION_HEADER_PRIORITY),
},
"available_qty": {
@@ -282,8 +336,9 @@ def describe_inventory_columns(
"qty_preference": qty_note,
},
},
"match_key": ["sku", "reservation_id"],
"match_rule": "按 AWS Sku + Reservation ID 汇总可用数量,与订单 qty 比对",
"match_key": match_key,
"match_rule": match_rule,
"match_rule_source": match_rule_source,
}
@@ -302,12 +357,11 @@ def build_field_alignment_preview(
inv_has_reservation = any(str(line.get("reservation_id") or "").strip() for line in inventory_lines)
res_source = (inv_mapping.get("reservation_id") or {}).get("source_column")
if order_has_reservation and not inv_has_reservation:
warnings.append(
"订单含 Reservation ID,但库存未解析到 reservation_id;"
"请确认是否将 COM ID / Reservation Order 列映射为 Reservation ID。"
)
if order_has_reservation and not res_source:
if notice_lines and not order_has_reservation:
warnings.append("订单未解析到 Reservation ID,但当前规则要求 Reservation ID 必填;请重新解析发货通知。")
if inventory_lines and not inv_has_reservation:
warnings.append("库存行未提供 Reservation ID(这些行将不参与匹配);如需按 Reservation ID 精确匹配,请补齐库存 Reservation ID。")
if inventory_lines and not res_source:
warnings.append("库存表未识别到 Reservation ID 相关列(COM ID / Reservation Order 等)。")
sku_source = (inv_mapping.get("sku") or {}).get("source_column")
@@ -337,8 +391,29 @@ def build_field_alignment_preview(
for line in inventory_lines[:5]
]
field_mapping_meta = mapping.get("field_mapping") if isinstance(mapping.get("field_mapping"), dict) else {}
fallback_mapping = {
k: str((inv_mapping.get(k) or {}).get("source_column") or "").strip()
for k in ("sku", "reservation_id", "available_qty")
}
fallback_mapping = {k: v for k, v in fallback_mapping.items() if v}
if not fallback_mapping and field_mapping_meta:
fallback_mapping = {k: str(v).strip() for k, v in field_mapping_meta.items() if str(v).strip()}
from app.services.shipping_notice.match_rule_desc import build_match_rule_fallback, resolve_match_rule
match_rule = str(mapping.get("match_rule") or "").strip()
if not match_rule and fallback_mapping:
match_rule = build_match_rule_fallback(
fallback_mapping,
match_key=mapping.get("match_key") if isinstance(mapping.get("match_key"), list) else None,
)
if not match_rule:
match_rule, _, _ = resolve_match_rule(fallback_mapping or {"sku": "sku", "available_qty": "qty"})
return {
"match_rule": mapping.get("match_rule") or describe_inventory_columns([])["match_rule"],
"match_rule": match_rule,
"match_rule_source": mapping.get("match_rule_source"),
"inventory_columns": mapping,
"notice_fields": NOTICE_FIELD_LABELS,
"sample_notice_lines": notice_preview,
@@ -456,6 +531,7 @@ def read_inventory_schema_preview(
"sku": "料号 / AWS Sku",
"reservation_id": "Reservation ID / COM ID(可选)",
"available_qty": "可用数量 / Qty Available / Qty",
"match_rule": "匹配规则说明(LLM 根据表头与订单字段生成,写入 column_mapping_json.match_rule)",
},
"row_count_hint": data_row_count,
}
@@ -466,12 +542,24 @@ def parse_inventory_excel_with_meta(
*,
field_mapping: dict[str, str] | None = None,
mapping_source: str = "rules",
header_row_index: int | None = None,
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
rows, _total = _load_excel_rows(path)
if not rows:
return [], {"headers": [], "mapping": {}, "match_key": ["sku", "reservation_id"]}
header_idx = find_inventory_header_row_index(rows)
header_idx: int | None = None
if header_row_index is not None:
try:
idx = int(header_row_index) - 1
except (TypeError, ValueError):
idx = -1
if 0 <= idx < len(rows):
header_idx = idx
if header_idx is None:
header_idx = find_inventory_header_row_index(rows)
headers = [str(c or "").strip() for c in rows[header_idx]]
data_rows = [list(r) for r in rows[header_idx + 1 :] if r]
if not field_mapping:
@@ -487,6 +575,8 @@ def parse_inventory_excel_with_meta(
headers,
field_mapping=field_mapping,
mapping_source=mapping_source if field_mapping else "rules",
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
)
meta["header_row_index"] = header_idx + 1
return lines, meta
@@ -21,43 +21,49 @@ def inventory_text_max_chars() -> int:
return 80000
def case_inventory_upload_path(case_no: str) -> Path:
safe = re.sub(r"[^\w\-]+", "_", str(case_no or "").strip()) or "unknown"
def task_inventory_upload_path(task_no: str) -> Path:
safe = re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
return _storage_root() / "inventory_uploads" / safe / "inventory.xlsx"
def save_case_inventory_upload(case_no: str, upload: FileStorage) -> Path:
path = case_inventory_upload_path(case_no)
def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path:
path = task_inventory_upload_path(task_no)
path.parent.mkdir(parents=True, exist_ok=True)
upload.save(str(path))
return path
def read_case_inventory_schema_preview(case_no: str) -> dict[str, Any]:
path = case_inventory_upload_path(case_no)
def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]:
path = task_inventory_upload_path(task_no)
if not path.is_file():
raise FileNotFoundError(f"未找到 case {case_no} 的库存上传文件")
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = path.name
return preview
def parse_uploaded_case_inventory(
case_no: str,
def parse_uploaded_task_inventory(
task_no: str,
*,
field_mapping: dict[str, str] | None = None,
mapping_source: str = "rules",
header_row_index: int | None = None,
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
) -> tuple[list[dict[str, Any]], dict[str, Any], Path]:
path = case_inventory_upload_path(case_no)
path = task_inventory_upload_path(task_no)
if not path.is_file():
raise FileNotFoundError(f"未找到 case {case_no} 的库存上传文件")
raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件")
lines, column_meta = parse_inventory_excel_with_meta(
path,
field_mapping=field_mapping,
mapping_source=mapping_source,
header_row_index=header_row_index,
llm_match_rule=llm_match_rule,
llm_match_key=llm_match_key,
)
return lines, column_meta, path
def has_uploaded_case_inventory(case_no: str) -> bool:
return case_inventory_upload_path(case_no).is_file()
def has_uploaded_task_inventory(task_no: str) -> bool:
return task_inventory_upload_path(task_no).is_file()
+64 -7
View File
@@ -3,7 +3,7 @@ from __future__ import annotations
from typing import Any
from app.services.shipping_notice.reservation_id import normalize_reservation_id
from app.services.shipping_notice.reservation_id import extract_reservation_id
def _norm(value: Any) -> str:
@@ -11,7 +11,7 @@ def _norm(value: Any) -> str:
def _norm_reservation(value: Any) -> str:
return normalize_reservation_id(value)
return extract_reservation_id(value)
def _line_key(sku: str, reservation_id: str | None) -> tuple[str, str]:
@@ -25,11 +25,14 @@ def _aggregate_inventory(inventory_lines: list[dict[str, Any]]) -> dict[tuple[st
sku = _norm(row.get("sku"))
if not sku:
continue
reservation_id = _norm_reservation(row.get("reservation_id"))
if not reservation_id:
continue
try:
qty = float(row.get("available_qty") or 0)
except (TypeError, ValueError):
qty = 0.0
key = _line_key(sku, row.get("reservation_id"))
key = _line_key(sku, reservation_id)
totals[key] = totals.get(key, 0.0) + qty
return totals
@@ -41,10 +44,9 @@ def _available_for_notice_line(
) -> float:
sku_n = _norm(sku)
rid = _norm_reservation(reservation_id)
if rid:
return inv_totals.get((sku_n, rid), 0.0)
# 订单未带 Reservation ID 时,按 SKU 汇总所有 reservation 的可用量
return sum(qty for (s, _r), qty in inv_totals.items() if s == sku_n)
if not rid:
return 0.0
return inv_totals.get((sku_n, rid), 0.0)
def match_notice_lines(
@@ -102,3 +104,58 @@ def match_notice_lines(
match_status = "fulfillable"
return match_status, line_results, {"lines": shortages}
def _fmt_qty(value: float) -> str:
if value == int(value):
return str(int(value))
return f"{value:g}"
def format_match_summary(
match_status: str,
line_results: list[dict[str, Any]],
) -> str:
"""Human-readable order qty vs inventory qty for match_inventory responses."""
if not line_results:
return "无订单明细,无法比对数量。"
lines = ["匹配明细(订单数量 vs 库存可用量):"]
for i, row in enumerate(line_results, 1):
sku = str(row.get("sku") or "-")
reservation_id = str(row.get("reservation_id") or "-")
try:
required = float(row.get("required_qty") or 0)
except (TypeError, ValueError):
required = 0.0
try:
available = float(row.get("available_qty") or 0)
except (TypeError, ValueError):
available = 0.0
try:
shortage = float(row.get("shortage_qty") or 0)
except (TypeError, ValueError):
shortage = 0.0
status = str(row.get("line_status") or "")
status_label = {"ok": "充足", "partial": "部分满足", "shortage": "不足"}.get(
status, status or "未知"
)
detail = (
f"{i}. SKU {sku} | Reservation ID {reservation_id} | "
f"订单 {_fmt_qty(required)} / 库存 {_fmt_qty(available)} | {status_label}"
)
if shortage > 0:
detail += f"(缺口 {_fmt_qty(shortage)})"
lines.append(detail)
lines.append("")
if match_status == "fulfillable":
lines.append("结论:库存充足,可生成发货 Excel 并上传货代系统。")
elif match_status == "partial":
lines.append("结论:部分行库存不足,请复核缺口后决定是否部分发货。")
elif match_status == "unfulfillable":
lines.append("结论:库存均不足,无法整单发货。")
else:
lines.append(f"结论:match_status={match_status}")
return "\n".join(lines)
@@ -0,0 +1,94 @@
from __future__ import annotations
from typing import Any
def _payload_root(raw: Any) -> dict[str, Any] | None:
data: dict[str, Any] | None = None
if isinstance(raw, dict):
data = raw
elif isinstance(raw, str) and raw.strip():
import json
try:
parsed = json.loads(raw)
if isinstance(parsed, dict):
data = parsed
except json.JSONDecodeError:
return None
return data
def extract_mapping_payload_extras(raw: Any) -> dict[str, Any]:
"""Read optional LLM fields from column_mapping_json (not column names)."""
data = _payload_root(raw)
if not data:
return {}
inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data
if not isinstance(inner, dict):
inner = data
match_rule = str(
data.get("match_rule")
or data.get("matching_rule")
or inner.get("match_rule")
or inner.get("matching_rule")
or ""
).strip()
match_key_raw = data.get("match_key") or inner.get("match_key")
match_key: list[str] | None = None
if isinstance(match_key_raw, list):
match_key = [str(k).strip() for k in match_key_raw if str(k).strip()]
elif isinstance(match_key_raw, str) and match_key_raw.strip():
match_key = [part.strip() for part in match_key_raw.split(",") if part.strip()]
extras: dict[str, Any] = {}
if match_rule:
extras["match_rule"] = match_rule
if match_key:
extras["match_key"] = match_key
return extras
def infer_match_key(field_mapping: dict[str, str]) -> list[str]:
keys = ["sku"]
if str(field_mapping.get("reservation_id") or "").strip():
keys.append("reservation_id")
return keys
def build_match_rule_fallback(
field_mapping: dict[str, str],
*,
match_key: list[str] | None = None,
) -> str:
"""Dynamic fallback when LLM did not supply match_rule."""
sku_col = str(field_mapping.get("sku") or "sku").strip() or "sku"
qty_col = str(field_mapping.get("available_qty") or "可用数量").strip() or "可用数量"
keys = match_key or infer_match_key(field_mapping)
if "reservation_id" in keys:
rid_col = str(field_mapping.get("reservation_id") or "Reservation ID").strip() or "Reservation ID"
return (
f"以库存列「{sku_col}」→ 订单 sku、「{rid_col}」→ 订单 reservation_id 为匹配键,"
f"汇总「{qty_col}」可用量后与订单 qty 比对(库存缺 reservation_id 的行不参与)。"
)
return (
f"以库存列「{sku_col}」→ 订单 sku 为匹配键,"
f"汇总「{qty_col}」可用量后与订单 qty 比对。"
)
def resolve_match_rule(
field_mapping: dict[str, str],
*,
llm_match_rule: str | None = None,
llm_match_key: list[str] | None = None,
) -> tuple[str, list[str], str]:
"""Return (match_rule, match_key, match_rule_source)."""
keys = llm_match_key or infer_match_key(field_mapping)
if llm_match_rule and str(llm_match_rule).strip():
return str(llm_match_rule).strip(), keys, "llm"
return build_match_rule_fallback(field_mapping, match_key=keys), keys, "fallback"
@@ -4,16 +4,22 @@ import re
from typing import Any
from app.services.shipping_notice.reservation_id import (
extract_reservation_id,
find_reservation_id_in_document,
looks_like_reservation_id,
normalize_reservation_id,
)
NOTICE_LINE_FIELDS = (
"line_no",
"sku",
"qty",
"unit_price",
"amount",
"currency",
"reservation_id",
"required_date",
"vendor_part_number",
"uom",
"remark",
)
@@ -30,7 +36,16 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
"Material": "sku",
"Material No": "sku",
"产品编号": "sku",
"Item No": "sku",
# 项次 / Item
"项次": "line_no",
"line_no": "line_no",
"Line No": "line_no",
"Line Number": "line_no",
"Line #": "line_no",
"Line": "line_no",
"Item": "line_no",
"Item No": "line_no",
"Item Number": "line_no",
# 需求数量
"数量": "qty",
"Qty": "qty",
@@ -58,6 +73,13 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
"小计": "amount",
"总价": "amount",
"Total Amount": "amount",
# 币种
"Currency": "currency",
"currency": "currency",
"Curr": "currency",
"CCY": "currency",
"币种": "currency",
"币别": "currency",
# Reservation ID
"Reservation ID": "reservation_id",
"Reservation Id": "reservation_id",
@@ -66,6 +88,27 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
"Reservation Order": "reservation_id",
"Reservation No": "reservation_id",
"Resv ID": "reservation_id",
"PR Number": "reservation_id",
"PR No": "reservation_id",
"PR#": "reservation_id",
# 交货日期
"Required Date": "required_date",
"Delivery Date": "required_date",
"required_date": "required_date",
"ETA": "required_date",
"交期": "required_date",
"交货日期": "required_date",
"要求交期": "required_date",
"Required Delivery Date": "required_date",
# 供应商料号
"Vendor Part Number": "vendor_part_number",
"Vendor Part No": "vendor_part_number",
"Vendor PN": "vendor_part_number",
"vendor_part_number": "vendor_part_number",
"Supplier Part No": "vendor_part_number",
"Supplier Part Number": "vendor_part_number",
"MPN": "vendor_part_number",
"供应商料号": "vendor_part_number",
# 单位
"单位": "uom",
"UOM": "uom",
@@ -74,11 +117,15 @@ NOTICE_COLUMN_MAP: dict[str, str] = {
}
NOTICE_FIELD_LABELS = {
"line_no": "项次 / Item / Line No",
"sku": "SKU / 料号",
"qty": "需求数量",
"unit_price": "单价",
"amount": "金额",
"currency": "币种",
"reservation_id": "Reservation ID(常见纯数字,如 1000140351)",
"required_date": "要求交期 / 交货日期",
"vendor_part_number": "供应商料号",
}
_HEADER_SKIP_TOKENS = {
@@ -94,6 +141,11 @@ _HEADER_SKIP_TOKENS = {
"unit price",
"金额",
"amount",
"currency",
"币种",
"line no",
"item no",
"项次",
}
@@ -138,6 +190,110 @@ def _cell(row: list[Any] | tuple[Any, ...], index: int | None) -> Any:
return row[index]
def _normalize_line_no(value: Any) -> str:
if value is None:
return ""
if isinstance(value, float) and value.is_integer():
return str(int(value))
text = str(value).strip()
if not text:
return ""
if text.lower() in _HEADER_SKIP_TOKENS:
return ""
num = _parse_number(text)
if num is not None and num == int(num):
compact = text.replace(",", "").replace(",", "")
if re.fullmatch(r"\d+(?:\.0+)?", compact):
return str(int(num))
return text
def _normalize_required_date(value: Any) -> str:
text = str(value or "").strip()
if not text:
return ""
m = re.match(r"^(\d{4})[/.-](\d{1,2})[/.-](\d{1,2})$", text)
if m:
return f"{m.group(1)}-{int(m.group(2)):02d}-{int(m.group(3)):02d}"
return text
_KNOWN_CURRENCY_CODES = frozenset(
{
"USD",
"EUR",
"GBP",
"JPY",
"CNY",
"RMB",
"HKD",
"TWD",
"SGD",
"AUD",
"CAD",
"KRW",
"INR",
"CHF",
"SEK",
"NOK",
"DKK",
"MYR",
"THB",
"VND",
"PHP",
"IDR",
"MXN",
"BRL",
"NZD",
}
)
_CURRENCY_ALIASES = {
"人民币": "CNY",
"美元": "USD",
"欧元": "EUR",
"英镑": "GBP",
"日元": "JPY",
"港币": "HKD",
"港元": "HKD",
"新台币": "TWD",
"新加坡元": "SGD",
"澳元": "AUD",
"加元": "CAD",
}
def _normalize_currency(value: Any) -> str:
text = str(value or "").strip()
if not text:
return ""
upper = text.upper()
if upper in _KNOWN_CURRENCY_CODES:
return "CNY" if upper == "RMB" else upper
if text in _CURRENCY_ALIASES:
return _CURRENCY_ALIASES[text]
return ""
def _extract_currency(*values: Any) -> str:
for value in values:
text = str(value or "").strip()
if not text:
continue
normalized = _normalize_currency(text)
if normalized:
return normalized
if text.startswith("$"):
return "USD"
if text.startswith("¥") or text.startswith("¥"):
return "CNY"
match = re.search(r"\b([A-Z]{3})\b", text.upper())
if match and match.group(1) in _KNOWN_CURRENCY_CODES:
code = match.group(1)
return "CNY" if code == "RMB" else code
return ""
def _parse_number(value: Any) -> float | None:
if value is None:
return None
@@ -147,8 +303,11 @@ def _parse_number(value: Any) -> float | None:
text = text.replace(",", "").replace(",", "")
if text.startswith("$") or text.startswith("¥") or text.startswith("¥"):
text = text[1:].strip()
match = re.search(r"[-+]?\d+(?:\.\d+)?", text)
if not match:
return None
try:
return float(text)
return float(match.group(0))
except (TypeError, ValueError):
return None
@@ -162,7 +321,7 @@ def _infer_reservation_id_from_row(
if i in skip_indices:
continue
if looks_like_reservation_id(cell):
return normalize_reservation_id(cell)
return extract_reservation_id(cell)
return ""
@@ -197,10 +356,17 @@ def _parse_notice_row(
if idx_qty is not None:
skip_indices.add(idx_qty)
idx_line_no = columns.get("line_no")
if idx_line_no is not None:
line_no = _normalize_line_no(_cell(row, idx_line_no))
skip_indices.add(idx_line_no)
if line_no:
parsed["line_no"] = line_no
idx_res = columns.get("reservation_id")
reservation_id = ""
if idx_res is not None:
reservation_id = normalize_reservation_id(_cell(row, idx_res))
reservation_id = extract_reservation_id(_cell(row, idx_res))
skip_indices.add(idx_res)
else:
reservation_id = _infer_reservation_id_from_row(row, skip_indices=skip_indices)
@@ -208,23 +374,48 @@ def _parse_notice_row(
parsed["reservation_id"] = reservation_id
idx_price = columns.get("unit_price")
price_cell = None
if idx_price is not None:
unit_price = _parse_number(_cell(row, idx_price))
price_cell = _cell(row, idx_price)
unit_price = _parse_number(price_cell)
if unit_price is not None:
parsed["unit_price"] = unit_price
idx_amount = columns.get("amount")
amount_cell = None
if idx_amount is not None:
amount = _parse_number(_cell(row, idx_amount))
amount_cell = _cell(row, idx_amount)
amount = _parse_number(amount_cell)
if amount is not None:
parsed["amount"] = amount
idx_currency = columns.get("currency")
currency = _extract_currency(
_cell(row, idx_currency) if idx_currency is not None else None,
price_cell,
amount_cell,
)
if currency:
parsed["currency"] = currency
idx_uom = columns.get("uom")
if idx_uom is not None:
uom = str(_cell(row, idx_uom) or "").strip()
if uom:
parsed["uom"] = uom
idx_required_date = columns.get("required_date")
if idx_required_date is not None:
required_date = _normalize_required_date(_cell(row, idx_required_date))
if required_date:
parsed["required_date"] = required_date
idx_vendor_part = columns.get("vendor_part_number")
if idx_vendor_part is not None:
vendor_part_number = str(_cell(row, idx_vendor_part) or "").strip()
if vendor_part_number:
parsed["vendor_part_number"] = vendor_part_number
# 若仅有 qty * unit_price,可推算 amount
if "amount" not in parsed and "unit_price" in parsed:
computed = round(parsed["unit_price"] * qty, 4)
@@ -252,11 +443,26 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
"uom": str(raw.get("uom") or "EA").strip() or "EA",
}
reservation_id = normalize_reservation_id(
line_no = _normalize_line_no(
raw.get("line_no")
or raw.get("lineNo")
or raw.get("item")
or raw.get("item_no")
or raw.get("itemNo")
or raw.get("Item")
or raw.get("Item No")
)
if line_no:
line["line_no"] = line_no
reservation_id = extract_reservation_id(
raw.get("reservation_id")
or raw.get("reservationId")
or raw.get("com_id")
or raw.get("reservation_order")
or raw.get("pr_number")
or raw.get("prNumber")
or raw.get("PR Number")
)
if reservation_id:
line["reservation_id"] = reservation_id
@@ -271,6 +477,38 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
elif unit_price is not None:
line["amount"] = round(unit_price * qty, 4)
currency = _normalize_currency(raw.get("currency") or raw.get("Currency"))
if not currency:
currency = _extract_currency(
raw.get("unit_price"),
raw.get("price"),
raw.get("amount"),
raw.get("total"),
)
if currency:
line["currency"] = currency
required_date = _normalize_required_date(
raw.get("required_date")
or raw.get("delivery_date")
or raw.get("deliveryDate")
or raw.get("eta")
or raw.get("ETA")
)
if required_date:
line["required_date"] = required_date
vendor_part_number = str(
raw.get("vendor_part_number")
or raw.get("vendorPartNumber")
or raw.get("vendor_pn")
or raw.get("supplier_part_number")
or raw.get("supplierPartNumber")
or ""
).strip()
if vendor_part_number:
line["vendor_part_number"] = vendor_part_number
remark = str(raw.get("remark") or raw.get("note") or "").strip()
if remark:
line["remark"] = remark
@@ -289,6 +527,126 @@ def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
return normalized
def enrich_notice_with_document_reservation(
parsed: dict[str, Any],
*,
raw_text: str = "",
) -> dict[str, Any]:
"""Apply document-level PR Number / @1000140351 reservation id to lines missing it."""
doc_rid = ""
for key in (
"reservation_id",
"reservationId",
"document_reservation_id",
"pr_number",
"prNumber",
"PR Number",
):
extracted = extract_reservation_id(parsed.get(key))
if extracted and looks_like_reservation_id(extracted):
doc_rid = extracted
break
if not doc_rid:
doc_rid = find_reservation_id_in_document(raw_text)
if not doc_rid:
return parsed
lines = parsed.get("lines")
if not isinstance(lines, list):
return parsed
for line in lines:
if not isinstance(line, dict):
continue
if not str(line.get("reservation_id") or "").strip():
line["reservation_id"] = doc_rid
parsed["reservation_id"] = doc_rid
parsed.pop("document_reservation_id", None)
return parsed
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."""
doc_date = _normalize_required_date(
parsed.get("required_date") or parsed.get("document_required_date")
)
if not doc_date:
return parsed
lines = parsed.get("lines")
if not isinstance(lines, list):
return parsed
has_line_dates = any(
isinstance(line, dict) and str(line.get("required_date") or "").strip() for line in lines
)
if not has_line_dates:
parsed["required_date"] = doc_date
for line in lines:
if not isinstance(line, dict):
continue
if not str(line.get("required_date") or "").strip():
line["required_date"] = doc_date
parsed.pop("document_required_date", None)
return parsed
def enrich_notice_with_document_currency(parsed: dict[str, Any]) -> dict[str, Any]:
"""Apply document-level currency to lines missing their own currency."""
doc_currency = _normalize_currency(
parsed.get("currency") or parsed.get("document_currency")
)
if not doc_currency:
return parsed
lines = parsed.get("lines")
if not isinstance(lines, list):
return parsed
has_line_currency = any(
isinstance(line, dict) and str(line.get("currency") or "").strip() for line in lines
)
if not has_line_currency:
parsed["currency"] = doc_currency
for line in lines:
if not isinstance(line, dict):
continue
if not str(line.get("currency") or "").strip():
line["currency"] = doc_currency
parsed.pop("document_currency", None)
return parsed
def parse_notice_table_text(raw_text: str) -> list[dict[str, Any]]:
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
text = str(raw_text or "").strip()
if not text:
return []
rows = _rows_from_table_text(text)
if not rows:
return []
header_idx = _find_notice_header_row_index(rows)
header = [str(c or "").strip() for c in rows[header_idx]]
data_rows = rows[header_idx + 1 :]
lines = parse_notice_table_rows(header, data_rows)
doc_rid = find_reservation_id_in_document(text)
if doc_rid:
for line in lines:
if not line.get("reservation_id"):
line["reservation_id"] = doc_rid
return lines
def _score_notice_header_row(cells: list[Any]) -> int:
headers = [str(c or "").strip() for c in cells]
if len([h for h in headers if h]) < 2:
@@ -337,23 +695,6 @@ def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> l
return lines
def parse_notice_table_text(raw_text: str) -> list[dict[str, Any]]:
from app.services.shipping_notice.inventory_snapshot import _rows_from_table_text
text = str(raw_text or "").strip()
if not text:
return []
rows = _rows_from_table_text(text)
if not rows:
return []
header_idx = _find_notice_header_row_index(rows)
header = [str(c or "").strip() for c in rows[header_idx]]
data_rows = rows[header_idx + 1 :]
return parse_notice_table_rows(header, data_rows)
def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
warnings: list[str] = []
if not lines:
@@ -0,0 +1,162 @@
from __future__ import annotations
import base64
import re
from email import policy
from email.parser import BytesParser
from pathlib import Path
from typing import Any
from flask import current_app
from edkb_system.contracts import Block, Context
from edkb_system.skills import loader_csv, loader_docx, loader_pdf, ocr
from app.services.shipping_notice.export import _storage_root
def task_notice_upload_path(task_no: str, filename: str) -> Path:
safe_task = re.sub(r"[^\w\-]+", "_", str(task_no or "").strip()) or "unknown"
name = str(filename or "").strip() or "notice"
safe_name = re.sub(r"[^\w\-.]+", "_", name)[:120] or "notice"
return _storage_root() / "notice_uploads" / safe_task / safe_name
def save_task_notice_upload(task_no: str, filename: str, data: bytes) -> Path:
path = task_notice_upload_path(task_no, filename)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return path
def _decode_text(data: bytes) -> str:
if not data:
return ""
for enc in ("utf-8", "utf-8-sig", "gb18030", "gbk"):
try:
return data.decode(enc)
except Exception:
continue
return data.decode("utf-8", errors="ignore")
def _html_to_text(html: str) -> str:
s = re.sub(r"(?is)<(script|style).*?>.*?</\\1>", "", html or "")
s = re.sub(r"(?is)<br\\s*/?>", "\n", s)
s = re.sub(r"(?is)</p\\s*>", "\n", s)
s = re.sub(r"(?is)<[^>]+>", " ", s)
s = re.sub(r"[ \t]+", " ", s)
s = re.sub(r"\\n\\s*\\n+", "\n\n", s)
return s.strip()
def _eml_to_text(data: bytes) -> str:
msg = BytesParser(policy=policy.default).parsebytes(data)
parts: list[str] = []
subject = str(msg.get("subject") or "").strip()
if subject:
parts.append(f"Subject: {subject}")
if msg.is_multipart():
for part in msg.walk():
if part.is_multipart():
continue
ctype = str(part.get_content_type() or "")
payload = part.get_payload(decode=True) or b""
if ctype == "text/plain":
parts.append(_decode_text(payload).strip())
elif ctype == "text/html":
parts.append(_html_to_text(_decode_text(payload)).strip())
else:
payload = msg.get_payload(decode=True) or b""
ctype = str(msg.get_content_type() or "")
if ctype == "text/html":
parts.append(_html_to_text(_decode_text(payload)).strip())
else:
parts.append(_decode_text(payload).strip())
return "\n\n".join(x for x in parts if x)
def _image_bytes_to_blocks(raw: bytes) -> list[Block]:
if not raw:
return []
data_uri = "data:image/png;base64," + base64.b64encode(raw).decode("ascii")
return [
Block(
id="img-1",
page=1,
type="image",
text="",
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={"data_uri": data_uri},
)
]
def _blocks_to_text(blocks: list[Block]) -> str:
lines: list[str] = []
for b in blocks:
if b.type not in {"paragraph", "ocr_text"}:
continue
txt = str(b.text or "").strip()
if not txt:
continue
if b.type == "ocr_text":
if txt.startswith("OCR_TEXT:"):
txt = txt[len("OCR_TEXT:") :].strip()
txt = re.sub(r"(?m)^\s*-\s*", "", txt).strip()
lines.append(txt)
text = "\n\n".join(lines)
text = re.sub(r"\n{3,}", "\n\n", text).strip()
return text
def extract_notice_text(file_path: Path) -> tuple[str, dict[str, Any]]:
path = Path(file_path)
ext = path.suffix.lower().lstrip(".")
ctx = Context(file_type=ext)
warnings: list[str] = []
if ext in {"txt", "md", "log"}:
return _decode_text(path.read_bytes()).strip(), {"warnings": warnings, "file_type": ext}
if ext in {"html", "htm"}:
return _html_to_text(_decode_text(path.read_bytes())), {"warnings": warnings, "file_type": ext}
if ext in {"eml"}:
return _eml_to_text(path.read_bytes()), {"warnings": warnings, "file_type": ext}
blocks: list[Block] = []
if ext in {"pdf"}:
blocks = loader_pdf.run({"file_path": str(path)}, ctx)
elif ext in {"docx"}:
blocks = loader_docx.run({"file_path": str(path)}, ctx)
elif ext in {"csv"}:
blocks = loader_csv.run({"file_path": str(path)}, ctx)
elif ext in {"png", "jpg", "jpeg", "webp"}:
blocks = _image_bytes_to_blocks(path.read_bytes())
else:
warnings.append(f"unsupported_file_type:{ext}")
if blocks:
has_images = any(b.type == "image" for b in blocks)
if has_images:
blocks = ocr.run(blocks, ctx)
text = _blocks_to_text(blocks)
return text.strip(), {"warnings": warnings + list(ctx.warnings), "file_type": ext}
return "", {"warnings": warnings + list(ctx.warnings), "file_type": ext}
def guess_source_type(filename: str) -> str:
ext = str(Path(filename or "").suffix or "").lower().lstrip(".")
if ext in {"pdf"}:
return "pdf"
if ext in {"eml"}:
return "email"
return "manual"
def max_notice_chars() -> int:
raw = str(current_app.config.get("SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS") or "").strip()
try:
value = int(raw) if raw else 0
except Exception:
value = 0
return value if value > 0 else 200000
@@ -58,7 +58,7 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
if not server.endswith("/api/shipping-notice"):
server = f"{server}/api/shipping-notice" if server else "/api/shipping-notice"
case_id = _str_prop("发货任务编号,如 SN-20260529-ABCD1234")
task_id = _str_prop("发货任务编号(task id),如 SN-20260529-ABCD1234")
return {
"openapi": "3.0.0",
@@ -69,9 +69,9 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
},
"servers": [{"url": server}],
"paths": {
"/tools/create_case": _post_op(
"create_case",
"创建发货任务 case",
"/tools/create_task": _post_op(
"create_task",
"创建发货任务 task",
{
"user_id": _int_prop("Hxops 用户 ID(可选)"),
"conversation_id": _str_prop("Dify 会话 ID,便于工作台关联"),
@@ -83,10 +83,10 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"parse_notice",
"解析发货通知文本",
{
"case_id": case_id,
"task_id": task_id,
"raw_text": _str_prop("待解析的发货通知全文"),
},
required=["case_id"],
required=["task_id"],
),
"/tools/parse_inventory": _post_op(
"parse_inventory",
@@ -95,9 +95,9 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"apply_inventory_mapping;或 use_uploaded_file=true(规则映射兜底)。小表可粘贴文本。"
"成功后 stop_agent_turn,等 confirm_inventory_mapping 后再 match。",
{
"case_id": case_id,
"task_id": task_id,
"use_uploaded_file": _str_prop(
"true=解析该 case 已上传的 Excel(服务端直传,不经过 LLM)",
"true=解析该任务已上传的 Excel(服务端直传,不经过 LLM)",
enum=["true", "false"],
),
"column_mapping_json": _str_prop(
@@ -110,53 +110,53 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
'可选,已整理好的 JSON 数组字符串,如 [{"sku":"A001","available_qty":10}]'
),
},
required=["case_id"],
required=["task_id"],
),
"/tools/get_inventory_schema_preview": _post_op(
"get_inventory_schema_preview",
"读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
{"case_id": case_id},
required=["case_id"],
{"task_id": task_id},
required=["task_id"],
),
"/tools/apply_inventory_mapping": _post_op(
"apply_inventory_mapping",
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认",
{
"case_id": case_id,
"task_id": task_id,
"column_mapping_json": _str_prop(
'列映射 JSON,如 {"sku":"料号","reservation_id":"COM ID","available_qty":"Qty Available"}'
'列映射 JSON,含 sku/reservation_id/available_qty;可选 match_rule(LLM 自然语言匹配说明,缺省则后端动态兜底)'
),
},
required=["case_id", "column_mapping_json"],
required=["task_id", "column_mapping_json"],
),
"/tools/ensure_inventory": _post_op(
"ensure_inventory",
"确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)",
{
"case_id": case_id,
"task_id": task_id,
"mode": _str_prop("auto=自动/RPA;retry_rpa=重试 RPA", enum=["auto", "retry_rpa"]),
"inventory_lines_json": _str_prop(
'手工库存 JSON 数组字符串,如 [{"sku":"A001","available_qty":10}]'
),
},
required=["case_id"],
required=["task_id"],
),
"/tools/match_inventory": _post_op(
"match_inventory",
"匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;"
"未确认时调用会被拒绝并返回 forbidden_next_tools",
{
"case_id": case_id,
"task_id": task_id,
"inventory_lines_json": _str_prop("可选,覆盖库存 JSON 数组后再匹配"),
},
required=["case_id"],
required=["task_id"],
),
"/tools/submit_decision": _post_op(
"submit_decision",
"人工复核决策。case_id 与 conversation_id 至少传一个;用户确认时禁止 create_case",
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task",
{
"case_id": case_id,
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位 case"),
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID;用户仅回复「确认」时用于定位任务"),
"decision": _str_prop(
"confirm=确认继续;reject=驳回;rematch=重新匹配;reparse=重新解析;"
"confirm_inventory_mapping=确认库存字段对齐;correct_inventory_mapping=更正列映射;reparse_inventory=重新上传库存",
@@ -178,27 +178,27 @@ def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"/tools/generate_shipment_excel": _post_op(
"generate_shipment_excel",
"生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
{"case_id": case_id},
required=["case_id"],
{"task_id": task_id},
required=["task_id"],
),
"/tools/upload_to_freight": _post_op(
"upload_to_freight",
"上传 Excel 到货代系统(RPA 或手工确认)",
{
"case_id": case_id,
"task_id": task_id,
"mode": _str_prop(
"auto=触发 RPA;retry_upload=重试;manual_confirm=手工上传完成",
enum=["auto", "retry_upload", "manual_confirm"],
),
"freight_ref_no": _str_prop("货代系统单号(manual_confirm 时填写)"),
},
required=["case_id"],
required=["task_id"],
),
"/tools/get_case_status": _post_op(
"get_case_status",
"查询 case 当前状态与 human_options。case_id 与 conversation_id 至少传一个",
"/tools/get_task_status": _post_op(
"get_task_status",
"查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
{
"case_id": case_id,
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID"),
},
),
@@ -0,0 +1,132 @@
from __future__ import annotations
from typing import Any
def _cell(value: Any) -> str:
text = str(value or "").strip()
return text if text else "-"
def _fmt_qty(qty: Any, uom: Any = None) -> str:
if qty is None or qty == "":
return "-"
try:
num = float(qty)
except (TypeError, ValueError):
return _cell(qty)
qty_text = str(int(num)) if num == int(num) else f"{num:g}"
unit = str(uom or "").strip() or "PCS"
return f"{qty_text} {unit}"
def _fmt_money(value: Any, currency: Any = None) -> str:
if value is None or value == "":
return "-"
try:
num = float(value)
except (TypeError, ValueError):
return _cell(value)
curr = str(currency or "").strip().upper()
formatted = f"{num:,.2f}"
if curr == "USD":
return f"${formatted}"
if curr == "CNY" or curr == "RMB":
return f"¥{formatted}"
if curr:
return f"{formatted} {curr}"
return formatted
def _append_table_row(rows: list[str], label: str, value: Any) -> None:
rows.append(f"| {label} | {_cell(value)} |")
def _format_line_block(line: dict[str, Any], *, doc_required_date: str = "") -> list[str]:
currency = line.get("currency")
required_date = str(line.get("required_date") or doc_required_date or "").strip()
rows: list[str] = ["| 字段 | 值 |", "|------|-----|"]
_append_table_row(rows, "SKU", line.get("sku"))
_append_table_row(rows, "Reservation ID", line.get("reservation_id"))
_append_table_row(rows, "数量", _fmt_qty(line.get("qty"), line.get("uom")))
_append_table_row(rows, "单价", _fmt_money(line.get("unit_price"), currency))
_append_table_row(rows, "金额", _fmt_money(line.get("amount"), currency))
_append_table_row(rows, "需求日期", required_date)
vendor_pn = str(line.get("vendor_part_number") or "").strip()
if vendor_pn:
_append_table_row(rows, "供应商料号", vendor_pn)
line_no = str(line.get("line_no") or "").strip()
if line_no:
_append_table_row(rows, "项次", line_no)
return rows
def format_parse_summary(
*,
task_no: str,
po_number: str | None = None,
ship_to: str | None = None,
customer_name: str | None = None,
required_date: str | None = None,
lines: list[dict[str, Any]] | None = None,
warnings: list[Any] | None = None,
low_confidence: bool = False,
) -> str:
"""Fixed Markdown summary for parse_notice / Agent display."""
order_lines = [line for line in (lines or []) if isinstance(line, dict)]
doc_date = str(required_date or "").strip()
parts = [f"【发货通知解析确认】任务编号:{task_no}", ""]
if not order_lines:
parts.extend(["| 字段 | 值 |", "|------|-----|"])
_append_table_row(parts, "PO", po_number)
_append_table_row(parts, "收货方", ship_to or customer_name)
_append_table_row(parts, "需求日期", doc_date)
parts.append("")
parts.append("未解析到订单明细行,请重新上传或重新解析。")
elif len(order_lines) == 1:
line = order_lines[0]
parts.extend(["| 字段 | 值 |", "|------|-----|"])
_append_table_row(parts, "PO", po_number)
_append_table_row(parts, "SKU", line.get("sku"))
_append_table_row(parts, "Reservation ID", line.get("reservation_id"))
_append_table_row(parts, "数量", _fmt_qty(line.get("qty"), line.get("uom")))
_append_table_row(parts, "单价", _fmt_money(line.get("unit_price"), line.get("currency")))
_append_table_row(parts, "金额", _fmt_money(line.get("amount"), line.get("currency")))
line_date = str(line.get("required_date") or doc_date or "").strip()
_append_table_row(parts, "需求日期", line_date)
recipient = str(ship_to or customer_name or "").strip()
_append_table_row(parts, "收货方", recipient)
vendor_pn = str(line.get("vendor_part_number") or "").strip()
if vendor_pn:
_append_table_row(parts, "供应商料号", vendor_pn)
else:
if po_number:
parts.append(f"PO:{_cell(po_number)}")
recipient = str(ship_to or customer_name or "").strip()
if recipient:
parts.append(f"收货方:{recipient}")
if doc_date:
parts.append(f"需求日期:{doc_date}")
parts.append("")
for index, line in enumerate(order_lines, 1):
line_no = str(line.get("line_no") or index).strip()
parts.append(f"【明细 {index}】项次 {line_no}")
parts.extend(_format_line_block(line, doc_required_date=doc_date))
parts.append("")
warn_items = [str(w).strip() for w in (warnings or []) if str(w).strip()]
if warn_items:
parts.append("")
parts.append("提示:")
for warning in warn_items[:8]:
parts.append(f"- {warning}")
parts.append("")
if low_confidence:
parts.append("解析置信度较低,请重点核对 SKU、数量、Reservation ID、单价与金额。")
parts.append("请确认以上信息是否正确?")
parts.append("回复「确认」进入库存检查;「重新解析」重试;「驳回」终止本任务。")
parts.append("(Hxops 聊天页也可直接点击操作按钮,无需输入文字。)")
return "\n".join(parts).strip()
@@ -0,0 +1,41 @@
from __future__ import annotations
import re
from typing import Any
_PO_NUMBER_PATTERNS = (
r"(?i)(?:PO|P\.O\.)\s*(?:Number|No\.?|#)?\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/]*)",
r"(?i)Purchase\s+Order\s*(?:Number|No\.?|#)?\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/]*)",
r"(?:采购订单号|采购单号|订单号|PO号)\s*[::]\s*([A-Za-z0-9][A-Za-z0-9\-_/]*)",
)
def normalize_po_number(value: Any) -> str:
text = str(value or "").strip()
if not text:
return ""
if text.lower() in {"number", "no", "n/a", "na", "none"}:
return ""
return text
def find_po_number_in_document(text: str) -> str:
raw = str(text or "")
if not raw.strip():
return ""
for pattern in _PO_NUMBER_PATTERNS:
match = re.search(pattern, raw)
if match:
return normalize_po_number(match.group(1))
return ""
def enrich_notice_with_po_number(parsed: dict[str, Any], *, raw_text: str = "") -> dict[str, Any]:
po_number = normalize_po_number(
parsed.get("po_number") or parsed.get("PO Number") or parsed.get("purchase_order_number")
)
if not po_number:
po_number = find_po_number_in_document(raw_text)
if po_number:
parsed["po_number"] = po_number
return parsed
@@ -4,69 +4,70 @@ from typing import Any
from sqlalchemy import desc
from app.models import ShippingCase, ShippingCaseEvent
from app.models import ShippingTask, ShippingTaskEvent
def serialize_case_summary(case: ShippingCase) -> dict[str, Any]:
def serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
return {
"id": case.id,
"case_no": case.case_no,
"source_type": case.source_type,
"customer_name": case.customer_name,
"process_status": case.process_status,
"review_status": case.review_status,
"match_status": case.match_status,
"pending_human_reason": case.pending_human_reason,
"conversation_id": case.conversation_id,
"export_file_name": case.export_file_name,
"freight_ref_no": case.freight_ref_no,
"created_at": case.created_at.isoformat() if case.created_at else None,
"updated_at": case.updated_at.isoformat() if case.updated_at else None,
"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_case_detail(case: ShippingCase) -> dict[str, Any]:
data = serialize_case_summary(case)
def serialize_task_detail(task: ShippingTask) -> dict[str, Any]:
data = serialize_task_summary(task)
data.update({
"customer_code": case.customer_code,
"ship_to": case.ship_to,
"required_date": case.required_date,
"lines": case.lines_json or [],
"shortage": case.shortage_json,
"line_results": case.line_results_json or [],
"parse_confidence": case.parse_confidence,
"error_message": case.error_message,
"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,
"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(case.events or [], key=lambda x: x.created_at or "")
for e in sorted(task.events or [], key=lambda x: x.created_at or "")
],
})
return data
def list_cases_for_user(
def list_tasks_for_user(
user_id: int,
*,
process_status: str | None = None,
limit: int = 100,
) -> list[dict[str, Any]]:
q = ShippingCase.query.filter(
(ShippingCase.user_id == user_id) | (ShippingCase.user_id.is_(None))
q = ShippingTask.query.filter(
(ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None))
)
if process_status:
q = q.filter(ShippingCase.process_status == process_status)
rows = q.order_by(desc(ShippingCase.created_at)).limit(max(1, min(limit, 500))).all()
return [serialize_case_summary(c) for c in rows]
q = q.filter(ShippingTask.process_status == process_status)
rows = q.order_by(desc(ShippingTask.created_at)).limit(max(1, min(limit, 500))).all()
return [serialize_task_summary(c) for c in rows]
def get_case_for_user(case_no: str, user_id: int) -> ShippingCase | None:
case = ShippingCase.query.filter_by(case_no=case_no).first()
if not case:
def get_task_for_user(task_no: str, user_id: int) -> ShippingTask | None:
task = ShippingTask.query.filter_by(task_no=task_no).first()
if not task:
return None
if case.user_id is not None and case.user_id != user_id:
if task.user_id is not None and task.user_id != user_id:
return None
return case
return task
@@ -5,6 +5,12 @@ from typing import Any
# 常见 Reservation ID:纯数字,如 1000140351(通常 8~12 位)
RESERVATION_ID_NUMERIC_RE = re.compile(r"^\d{8,12}$")
# Wistron 等 PO:PR Number = ADU_S-ENCWIW260528126265@1000140351
RESERVATION_AT_SUFFIX_RE = re.compile(r"@(\d{8,12})\b")
PR_NUMBER_LINE_RE = re.compile(
r"PR\s*Number\s*[::]?\s*([^\n\r]+)",
re.IGNORECASE,
)
def normalize_reservation_id(value: Any) -> str:
@@ -36,6 +42,48 @@ def normalize_reservation_id(value: Any) -> str:
return text
def extract_reservation_id(value: Any) -> str:
"""Extract reservation id from plain numeric, Excel float, or PR Number (xxx@1000140351)."""
text = str(value or "").strip()
if not text:
return ""
direct = normalize_reservation_id(text)
if looks_like_reservation_id(direct):
return direct
match = RESERVATION_AT_SUFFIX_RE.search(text)
if match:
return match.group(1)
if "@" in text:
tail = normalize_reservation_id(text.rsplit("@", 1)[-1])
if looks_like_reservation_id(tail):
return tail
return direct
def find_reservation_id_in_document(text: str) -> str:
"""Scan document text for PR Number @ reservation id or standalone @1000140351."""
body = str(text or "")
if not body.strip():
return ""
pr_match = PR_NUMBER_LINE_RE.search(body)
if pr_match:
extracted = extract_reservation_id(pr_match.group(1))
if extracted and looks_like_reservation_id(extracted):
return extracted
for match in RESERVATION_AT_SUFFIX_RE.finditer(body):
candidate = match.group(1)
if looks_like_reservation_id(candidate):
return candidate
return ""
def looks_like_reservation_id(value: Any) -> bool:
text = normalize_reservation_id(value)
return bool(text and RESERVATION_ID_NUMERIC_RE.fullmatch(text))
+7 -7
View File
@@ -39,23 +39,23 @@ def upload_trigger_dir() -> Path | None:
return _path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR")
def write_inventory_export_trigger(case_no: str, payload: dict[str, Any] | None = None) -> str | None:
def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None:
trigger_dir = inventory_trigger_dir()
if not trigger_dir:
return None
trigger_dir.mkdir(parents=True, exist_ok=True)
body = {
"action": "inventory_export",
"case_no": case_no,
"task_no": task_no,
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
path = trigger_dir / f"inventory_export_{case_no}.json"
path = trigger_dir / f"inventory_export_{task_no}.json"
path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
return str(path)
def write_upload_trigger(case_no: str, export_file_path: str, payload: dict[str, Any] | None = None) -> tuple[str | None, str | None]:
def write_upload_trigger(task_no: str, export_file_path: str, payload: dict[str, Any] | None = None) -> tuple[str | None, str | None]:
queue = upload_queue_dir()
trigger_dir = upload_trigger_dir()
if not queue or not trigger_dir:
@@ -66,17 +66,17 @@ def write_upload_trigger(case_no: str, export_file_path: str, payload: dict[str,
src = Path(export_file_path)
if not src.is_file():
return None, None
dest = queue / f"{case_no}_{src.name}"
dest = queue / f"{task_no}_{src.name}"
shutil.copy2(src, dest)
body = {
"action": "shipment_upload",
"case_no": case_no,
"task_no": task_no,
"file_path": str(dest),
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
trigger_path = trigger_dir / f"upload_{case_no}.json"
trigger_path = trigger_dir / f"upload_{task_no}.json"
trigger_path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
return str(dest), str(trigger_path)
@@ -6,7 +6,7 @@ from typing import Any
def tool_response(
*,
status: str,
case_id: str | None = None,
task_id: str | None = None,
message: str = "",
data: dict[str, Any] | None = None,
human_options: list[str] | None = None,
@@ -20,8 +20,8 @@ def tool_response(
"message": message,
"data": data or {},
}
if case_id:
payload["case_id"] = case_id
if task_id:
payload["task_id"] = task_id
if human_options:
payload["human_options"] = human_options
if checkpoint:
File diff suppressed because it is too large. Load diff
@@ -17,18 +17,20 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'users' not in set(insp.get_table_names()):
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('phone_number', sa.String(length=20), nullable=True))
batch_op.create_unique_constraint(None, ['phone_number'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'users' not in set(insp.get_table_names()):
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('phone_number')
# ### end Alembic commands ###
@@ -0,0 +1,24 @@
"""shipping notice legacy step 2
Revision ID: 0d1c2b3a4e5f
Revises: d8e9f0a1b2c3
Create Date: 2026-06-03 00:00:00.000000
"""
from alembic import op
revision = "0d1c2b3a4e5f"
down_revision = "d8e9f0a1b2c3"
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,24 @@
"""shipping notice legacy step 3
Revision ID: 1f2e3d4c5b6a
Revises: 0d1c2b3a4e5f
Create Date: 2026-06-03 00:00:00.000000
"""
from alembic import op
revision = "1f2e3d4c5b6a"
down_revision = "0d1c2b3a4e5f"
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,157 @@
"""add shipping notice task tables
Revision ID: 2c3d4e5f6a7b
Revises: c9d8e7f6a5b4
Create Date: 2026-06-03 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "2c3d4e5f6a7b"
down_revision = "1f2e3d4c5b6a"
branch_labels = None
depends_on = None
def _join(parts: list[str]) -> str:
return "".join(parts)
def upgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
tables = set(insp.get_table_names())
tasks_tbl = _join(["shipping_", "tasks"])
legacy_tbl = _join(["shipping_", "c", "ases"])
legacy_evt_tbl = _join(["shipping_", "c", "ase_events"])
evt_tbl = _join(["shipping_", "task_events"])
if tasks_tbl not in tables:
if legacy_tbl in tables:
op.rename_table(legacy_tbl, tasks_tbl)
with op.batch_alter_table(tasks_tbl) as batch:
batch.alter_column(
_join(["c", "ase_no"]),
new_column_name=_join(["t", "ask_no"]),
existing_type=sa.String(length=64),
existing_nullable=False,
)
if legacy_evt_tbl in tables:
op.rename_table(legacy_evt_tbl, evt_tbl)
with op.batch_alter_table(evt_tbl) as batch:
batch.alter_column(
_join(["c", "ase_id"]),
new_column_name=_join(["t", "ask_id"]),
existing_type=sa.Integer(),
existing_nullable=False,
)
else:
op.create_table(
tasks_tbl,
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("task_no", sa.String(length=64), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=True),
sa.Column("conversation_id", sa.String(length=100), nullable=True),
sa.Column("source_type", sa.String(length=32), nullable=False, server_default="manual"),
sa.Column("raw_content", sa.Text(), nullable=True),
sa.Column("customer_name", sa.String(length=200), nullable=True),
sa.Column("customer_code", sa.String(length=64), nullable=True),
sa.Column("ship_to", sa.Text(), nullable=True),
sa.Column("required_date", sa.String(length=32), nullable=True),
sa.Column("lines_json", sa.JSON(), nullable=True),
sa.Column("parse_confidence", sa.Float(), nullable=True),
sa.Column("process_status", sa.String(length=32), nullable=False, server_default="created"),
sa.Column("review_status", sa.String(length=32), nullable=True),
sa.Column("match_status", sa.String(length=32), nullable=True),
sa.Column("shortage_json", sa.JSON(), nullable=True),
sa.Column("line_results_json", sa.JSON(), nullable=True),
sa.Column("inventory_snapshot_id", sa.Integer(), nullable=True),
sa.Column("inventory_lines_json", sa.JSON(), nullable=True),
sa.Column("export_file_path", sa.String(length=500), nullable=True),
sa.Column("export_file_name", sa.String(length=255), nullable=True),
sa.Column("freight_ref_no", sa.String(length=128), nullable=True),
sa.Column("pending_human_reason", sa.String(length=64), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_shipping_tasks_task_no", tasks_tbl, ["task_no"], unique=True)
op.create_index("ix_shipping_tasks_user_id", tasks_tbl, ["user_id"])
op.create_index("ix_shipping_tasks_process_status", tasks_tbl, ["process_status"])
op.create_index("ix_shipping_tasks_created_at", tasks_tbl, ["created_at"])
op.create_index("ix_shipping_tasks_user_status", tasks_tbl, ["user_id", "process_status"])
op.create_index("ix_shipping_tasks_conversation", tasks_tbl, ["conversation_id"])
op.create_table(
evt_tbl,
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("task_id", sa.Integer(), nullable=False),
sa.Column("event_type", sa.String(length=64), nullable=False),
sa.Column("detail_json", sa.JSON(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["task_id"], [f"{tasks_tbl}.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_shipping_task_events_task_id", evt_tbl, ["task_id"])
op.create_index("ix_shipping_task_events_event_type", evt_tbl, ["event_type"])
op.create_index("ix_shipping_task_events_created_at", evt_tbl, ["created_at"])
inv_tbl = _join(["shipping_", "inventory_mappings"])
if inv_tbl not in tables:
op.create_table(
inv_tbl,
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("customer_code", sa.String(length=64), nullable=False),
sa.Column("header_hash", sa.String(length=64), nullable=False),
sa.Column("headers_json", sa.JSON(), nullable=True),
sa.Column("field_mapping_json", sa.JSON(), nullable=False),
sa.Column("last_used_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint(
"customer_code",
"header_hash",
name="uq_shipping_inventory_mappings_customer_header",
),
)
op.create_index(
"ix_shipping_inventory_mappings_customer_code",
inv_tbl,
["customer_code"],
)
op.create_index(
"ix_shipping_inventory_mappings_created_at",
inv_tbl,
["created_at"],
)
op.create_index(
"ix_shipping_inventory_mappings_updated_at",
inv_tbl,
["updated_at"],
)
def downgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
tables = set(insp.get_table_names())
inv_tbl = _join(["shipping_", "inventory_mappings"])
if inv_tbl in tables:
op.drop_table(inv_tbl)
evt_tbl = _join(["shipping_", "task_events"])
if evt_tbl in tables:
op.drop_table(evt_tbl)
tasks_tbl = _join(["shipping_", "tasks"])
if tasks_tbl in tables:
op.drop_table(tasks_tbl)
@@ -0,0 +1,126 @@
"""fix shipping notice legacy tables
Revision ID: 3a4b5c6d7e8f
Revises: 2c3d4e5f6a7b
Create Date: 2026-06-03 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "3a4b5c6d7e8f"
down_revision = "2c3d4e5f6a7b"
branch_labels = None
depends_on = None
def _join(parts: list[str]) -> str:
return "".join(parts)
def _table_names(insp: sa.Inspector) -> set[str]:
return set(insp.get_table_names())
def _count(conn: sa.Connection, table_name: str) -> int:
return int(conn.execute(sa.text(f"SELECT COUNT(*) FROM {table_name}")).scalar_one())
def _index_names(insp: sa.Inspector, table_name: str) -> set[str]:
return {idx.get("name") for idx in insp.get_indexes(table_name) if idx.get("name")}
def _drop_index_if_exists(insp: sa.Inspector, table_name: str, index_name: str) -> None:
if index_name in _index_names(insp, table_name):
op.drop_index(index_name, table_name=table_name)
def _create_index_if_missing(insp: sa.Inspector, table_name: str, index_name: str, columns: list[str], unique: bool = False) -> None:
if index_name not in _index_names(insp, table_name):
op.create_index(index_name, table_name, columns, unique=unique)
def upgrade():
conn = op.get_bind()
insp = sa.inspect(conn)
tables = _table_names(insp)
tasks_tbl = _join(["shipping_", "tasks"])
legacy_tbl = _join(["shipping_", "c", "ases"])
evt_tbl = _join(["shipping_", "task_events"])
legacy_evt_tbl = _join(["shipping_", "c", "ase_events"])
if legacy_tbl not in tables:
return
legacy_count = _count(conn, legacy_tbl)
if tasks_tbl not in tables:
if legacy_count == 0:
if legacy_evt_tbl in tables:
op.drop_table(legacy_evt_tbl)
op.drop_table(legacy_tbl)
return
tasks_count = _count(conn, tasks_tbl)
task_evt_count = _count(conn, evt_tbl) if evt_tbl in tables else 0
if tasks_count != 0 or task_evt_count != 0:
if legacy_count != 0:
raise RuntimeError("legacy shipping notice tables still contain data while target tables are not empty; manual reconciliation required")
if legacy_evt_tbl in tables:
op.drop_table(legacy_evt_tbl)
op.drop_table(legacy_tbl)
return
if evt_tbl in tables:
op.drop_table(evt_tbl)
op.drop_table(tasks_tbl)
op.rename_table(legacy_tbl, tasks_tbl)
with op.batch_alter_table(tasks_tbl) as batch:
batch.alter_column(
_join(["c", "ase_no"]),
new_column_name=_join(["t", "ask_no"]),
existing_type=sa.String(length=64),
existing_nullable=False,
)
if legacy_evt_tbl in tables:
op.rename_table(legacy_evt_tbl, evt_tbl)
with op.batch_alter_table(evt_tbl) as batch:
batch.alter_column(
_join(["c", "ase_id"]),
new_column_name=_join(["t", "ask_id"]),
existing_type=sa.Integer(),
existing_nullable=False,
)
insp = sa.inspect(conn)
_drop_index_if_exists(insp, tasks_tbl, _join(["ix_", "shipping_", "c", "ases_", "c", "ase_no"]))
_drop_index_if_exists(insp, tasks_tbl, _join(["ix_", "shipping_", "c", "ases_", "user_status"]))
_drop_index_if_exists(insp, tasks_tbl, _join(["ix_", "shipping_", "c", "ases_", "conversation"]))
_drop_index_if_exists(insp, tasks_tbl, _join(["ix_", "shipping_", "c", "ases_", "process_status"]))
_drop_index_if_exists(insp, tasks_tbl, _join(["ix_", "shipping_", "c", "ases_", "created_at"]))
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "t", "ask_no"]), [_join(["t", "ask_no"])], unique=True)
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "user_id"]), ["user_id"])
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "process_status"]), ["process_status"])
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "created_at"]), ["created_at"])
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "user_status"]), ["user_id", "process_status"])
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "conversation"]), ["conversation_id"])
if evt_tbl in _table_names(insp):
_drop_index_if_exists(insp, evt_tbl, _join(["ix_", "shipping_", "c", "ase_events_", "c", "ase_id"]))
_drop_index_if_exists(insp, evt_tbl, _join(["ix_", "shipping_", "c", "ase_events_", "event_type"]))
_drop_index_if_exists(insp, evt_tbl, _join(["ix_", "shipping_", "c", "ase_events_", "created_at"]))
_create_index_if_missing(insp, evt_tbl, _join(["ix_", "shipping_", "task_events_", "t", "ask_id"]), [_join(["t", "ask_id"])])
_create_index_if_missing(insp, evt_tbl, _join(["ix_", "shipping_", "task_events_", "event_type"]), ["event_type"])
_create_index_if_missing(insp, evt_tbl, _join(["ix_", "shipping_", "task_events_", "created_at"]), ["created_at"])
def downgrade():
pass
@@ -17,18 +17,21 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
if 'users' not in tables or 'agents' not in tables:
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('default_agent_id', sa.Integer(), nullable=True))
batch_op.create_foreign_key(None, 'agents', ['default_agent_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'users' not in set(insp.get_table_names()):
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='foreignkey')
batch_op.drop_column('default_agent_id')
# ### end Alembic commands ###
@@ -17,34 +17,48 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('type',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'api'::character varying"))
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column('status',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'active'::character varying"))
if 'agents' in tables:
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column(
'type',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'api'::character varying"),
)
# ### end Alembic commands ###
if 'users' in tables:
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column(
'status',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'active'::character varying"),
)
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column('status',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'active'::character varying"))
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('type',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'api'::character varying"))
if 'users' in tables:
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column(
'status',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'active'::character varying"),
)
# ### end Alembic commands ###
if 'agents' in tables:
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column(
'type',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'api'::character varying"),
)
@@ -17,20 +17,22 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'users' not in set(insp.get_table_names()):
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('real_name', sa.String(length=50), nullable=True))
batch_op.add_column(sa.Column('employee_id', sa.String(length=50), nullable=True))
batch_op.create_unique_constraint(None, ['employee_id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'users' not in set(insp.get_table_names()):
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('employee_id')
batch_op.drop_column('real_name')
# ### end Alembic commands ###
@@ -17,18 +17,23 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('departments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
conn = op.get_bind()
insp = sa.inspect(conn)
if 'departments' in set(insp.get_table_names()):
return
op.create_table(
'departments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name'),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'departments' not in set(insp.get_table_names()):
return
op.drop_table('departments')
# ### end Alembic commands ###
@@ -17,81 +17,143 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('zl_languages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=10), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code')
)
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('latency', sa.Float(), nullable=False, server_default='0.0'))
batch_op.alter_column('answer',
existing_type=sa.TEXT(),
nullable=False)
batch_op.drop_index(batch_op.f('ix_chat_logs_agent_id'))
batch_op.drop_index(batch_op.f('ix_chat_logs_conversation_id'))
batch_op.drop_index(batch_op.f('ix_chat_logs_created_at'))
batch_op.drop_index(batch_op.f('ix_chat_logs_user_id'))
batch_op.drop_column('tokens_used')
batch_op.drop_column('conversation_id')
batch_op.drop_column('latency_ms')
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
batch_op.add_column(sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()))
batch_op.drop_column('tags')
if 'zl_languages' not in tables:
op.create_table(
'zl_languages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=10), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code'),
)
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
batch_op.alter_column('reason',
existing_type=sa.TEXT(),
nullable=False)
batch_op.drop_index(batch_op.f('ix_permission_requests_agent_id'))
batch_op.drop_index(batch_op.f('ix_permission_requests_user_id'))
if 'chat_logs' in tables:
cols = {c['name'] for c in insp.get_columns('chat_logs')}
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
if 'latency' not in cols:
batch_op.add_column(sa.Column('latency', sa.Float(), nullable=False, server_default='0.0'))
try:
batch_op.alter_column('answer', existing_type=sa.TEXT(), nullable=False)
except Exception:
pass
for idx in (
batch_op.f('ix_chat_logs_agent_id'),
batch_op.f('ix_chat_logs_conversation_id'),
batch_op.f('ix_chat_logs_created_at'),
batch_op.f('ix_chat_logs_user_id'),
):
try:
batch_op.drop_index(idx)
except Exception:
pass
for name in ('tokens_used', 'conversation_id', 'latency_ms'):
if name in cols:
try:
batch_op.drop_column(name)
except Exception:
pass
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_quick_questions_agent_id'))
batch_op.drop_index(batch_op.f('ix_quick_questions_user_id'))
if 'feedbacks' in tables:
cols = {c['name'] for c in insp.get_columns('feedbacks')}
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
if 'created_at' not in cols:
batch_op.add_column(sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()))
if 'tags' in cols:
try:
batch_op.drop_column('tags')
except Exception:
pass
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('language', sa.String(length=10), nullable=False, server_default='zh-CN'))
if 'permission_requests' in tables:
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
try:
batch_op.alter_column('reason', existing_type=sa.TEXT(), nullable=False)
except Exception:
pass
for idx in (
batch_op.f('ix_permission_requests_agent_id'),
batch_op.f('ix_permission_requests_user_id'),
):
try:
batch_op.drop_index(idx)
except Exception:
pass
# ### end Alembic commands ###
if 'quick_questions' in tables:
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
for idx in (
batch_op.f('ix_quick_questions_agent_id'),
batch_op.f('ix_quick_questions_user_id'),
):
try:
batch_op.drop_index(idx)
except Exception:
pass
if 'users' in tables:
cols = {c['name'] for c in insp.get_columns('users')}
if 'language' not in cols:
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('language', sa.String(length=10), nullable=False, server_default='zh-CN'))
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_column('language')
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_quick_questions_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_quick_questions_agent_id'), ['agent_id'], unique=False)
if 'users' in tables:
cols = {c['name'] for c in insp.get_columns('users')}
if 'language' in cols:
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_column('language')
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_permission_requests_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_permission_requests_agent_id'), ['agent_id'], unique=False)
batch_op.alter_column('reason',
existing_type=sa.TEXT(),
nullable=True)
if 'quick_questions' in tables:
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_quick_questions_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_quick_questions_agent_id'), ['agent_id'], unique=False)
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
batch_op.add_column(sa.Column('tags', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True))
batch_op.drop_column('created_at')
if 'permission_requests' in tables:
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_permission_requests_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_permission_requests_agent_id'), ['agent_id'], unique=False)
try:
batch_op.alter_column('reason', existing_type=sa.TEXT(), nullable=True)
except Exception:
pass
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('latency_ms', sa.INTEGER(), autoincrement=False, nullable=False))
batch_op.add_column(sa.Column('conversation_id', sa.VARCHAR(length=100), autoincrement=False, nullable=False))
batch_op.add_column(sa.Column('tokens_used', sa.INTEGER(), autoincrement=False, nullable=False))
batch_op.create_index(batch_op.f('ix_chat_logs_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_created_at'), ['created_at'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_conversation_id'), ['conversation_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_agent_id'), ['agent_id'], unique=False)
batch_op.alter_column('answer',
existing_type=sa.TEXT(),
nullable=True)
batch_op.drop_column('latency')
if 'feedbacks' in tables:
cols = {c['name'] for c in insp.get_columns('feedbacks')}
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
if 'tags' not in cols:
batch_op.add_column(sa.Column('tags', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True))
if 'created_at' in cols:
batch_op.drop_column('created_at')
op.drop_table('zl_languages')
# ### end Alembic commands ###
if 'chat_logs' in tables:
cols = {c['name'] for c in insp.get_columns('chat_logs')}
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
if 'latency_ms' not in cols:
batch_op.add_column(sa.Column('latency_ms', sa.INTEGER(), autoincrement=False, nullable=False))
if 'conversation_id' not in cols:
batch_op.add_column(sa.Column('conversation_id', sa.VARCHAR(length=100), autoincrement=False, nullable=False))
if 'tokens_used' not in cols:
batch_op.add_column(sa.Column('tokens_used', sa.INTEGER(), autoincrement=False, nullable=False))
batch_op.create_index(batch_op.f('ix_chat_logs_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_created_at'), ['created_at'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_conversation_id'), ['conversation_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_agent_id'), ['agent_id'], unique=False)
try:
batch_op.alter_column('answer', existing_type=sa.TEXT(), nullable=True)
except Exception:
pass
if 'latency' in cols:
batch_op.drop_column('latency')
if 'zl_languages' in tables:
op.drop_table('zl_languages')
@@ -0,0 +1,38 @@
"""add po_number to shipping_tasks
Revision ID: a7b8c9d0e1f2
Revises: 3a4b5c6d7e8f
Create Date: 2026-05-29 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "a7b8c9d0e1f2"
down_revision = "3a4b5c6d7e8f"
branch_labels = None
depends_on = None
def upgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
if "shipping_tasks" not in set(insp.get_table_names()):
return
columns = {col["name"] for col in insp.get_columns("shipping_tasks")}
if "po_number" not in columns:
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
batch_op.add_column(sa.Column("po_number", sa.String(length=128), nullable=True))
def downgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
if "shipping_tasks" not in set(insp.get_table_names()):
return
columns = {col["name"] for col in insp.get_columns("shipping_tasks")}
if "po_number" in columns:
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
batch_op.drop_column("po_number")
@@ -1,73 +0,0 @@
"""add shipping_cases tables for freight notice agent tools
Revision ID: d8e9f0a1b2c3
Revises: c9d8e7f6a5b4
Create Date: 2026-05-29 12:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = 'd8e9f0a1b2c3'
down_revision = 'c9d8e7f6a5b4'
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
'shipping_cases',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('case_no', sa.String(length=64), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=True),
sa.Column('conversation_id', sa.String(length=100), nullable=True),
sa.Column('source_type', sa.String(length=32), nullable=False, server_default='manual'),
sa.Column('raw_content', sa.Text(), nullable=True),
sa.Column('customer_name', sa.String(length=200), nullable=True),
sa.Column('customer_code', sa.String(length=64), nullable=True),
sa.Column('ship_to', sa.Text(), nullable=True),
sa.Column('required_date', sa.String(length=32), nullable=True),
sa.Column('lines_json', sa.JSON(), nullable=True),
sa.Column('parse_confidence', sa.Float(), nullable=True),
sa.Column('process_status', sa.String(length=32), nullable=False, server_default='created'),
sa.Column('review_status', sa.String(length=32), nullable=True),
sa.Column('match_status', sa.String(length=32), nullable=True),
sa.Column('shortage_json', sa.JSON(), nullable=True),
sa.Column('line_results_json', sa.JSON(), nullable=True),
sa.Column('inventory_snapshot_id', sa.Integer(), nullable=True),
sa.Column('inventory_lines_json', sa.JSON(), nullable=True),
sa.Column('export_file_path', sa.String(length=500), nullable=True),
sa.Column('export_file_name', sa.String(length=255), nullable=True),
sa.Column('freight_ref_no', sa.String(length=128), nullable=True),
sa.Column('pending_human_reason', sa.String(length=64), nullable=True),
sa.Column('error_message', sa.Text(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_shipping_cases_case_no', 'shipping_cases', ['case_no'], unique=True)
op.create_index('ix_shipping_cases_user_status', 'shipping_cases', ['user_id', 'process_status'])
op.create_index('ix_shipping_cases_conversation', 'shipping_cases', ['conversation_id'])
op.create_index('ix_shipping_cases_process_status', 'shipping_cases', ['process_status'])
op.create_index('ix_shipping_cases_created_at', 'shipping_cases', ['created_at'])
op.create_table(
'shipping_case_events',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('case_id', sa.Integer(), nullable=False),
sa.Column('event_type', sa.String(length=64), nullable=False),
sa.Column('detail_json', sa.JSON(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['case_id'], ['shipping_cases.id']),
sa.PrimaryKeyConstraint('id'),
)
op.create_index('ix_shipping_case_events_case_id', 'shipping_case_events', ['case_id'])
op.create_index('ix_shipping_case_events_event_type', 'shipping_case_events', ['event_type'])
op.create_index('ix_shipping_case_events_created_at', 'shipping_case_events', ['created_at'])
def downgrade():
op.drop_table('shipping_case_events')
op.drop_table('shipping_cases')
@@ -0,0 +1,24 @@
"""shipping notice legacy step 1
Revision ID: d8e9f0a1b2c3
Revises: c9d8e7f6a5b4
Create Date: 2026-06-03 00:00:00.000000
"""
from alembic import op
revision = "d8e9f0a1b2c3"
down_revision = "c9d8e7f6a5b4"
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -17,48 +17,70 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user_default_agents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user_favorite_agents',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'agent_id')
)
op.create_table('user_homepage_configs',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('layout', sa.JSON(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id')
)
with op.batch_alter_table('departments', schema=None) as batch_op:
batch_op.add_column(sa.Column('code', sa.String(length=50), nullable=True))
batch_op.add_column(sa.Column('company', sa.String(length=100), nullable=True))
batch_op.create_unique_constraint(None, ['code'])
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
# ### end Alembic commands ###
if 'users' in tables and 'agents' in tables:
if 'user_default_agents' not in tables:
op.create_table(
'user_default_agents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id']),
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
sa.PrimaryKeyConstraint('id'),
)
if 'user_favorite_agents' not in tables:
op.create_table(
'user_favorite_agents',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id']),
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
sa.PrimaryKeyConstraint('user_id', 'agent_id'),
)
if 'user_homepage_configs' not in tables:
op.create_table(
'user_homepage_configs',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('layout', sa.JSON(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
sa.PrimaryKeyConstraint('user_id'),
)
if 'departments' in tables:
cols = {c['name'] for c in insp.get_columns('departments')}
with op.batch_alter_table('departments', schema=None) as batch_op:
if 'code' not in cols:
batch_op.add_column(sa.Column('code', sa.String(length=50), nullable=True))
batch_op.create_unique_constraint(None, ['code'])
if 'company' not in cols:
batch_op.add_column(sa.Column('company', sa.String(length=100), nullable=True))
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('departments', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('company')
batch_op.drop_column('code')
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
op.drop_table('user_homepage_configs')
op.drop_table('user_favorite_agents')
op.drop_table('user_default_agents')
# ### end Alembic commands ###
if 'departments' in tables:
cols = {c['name'] for c in insp.get_columns('departments')}
with op.batch_alter_table('departments', schema=None) as batch_op:
if 'code' in cols:
try:
batch_op.drop_constraint(None, type_='unique')
except Exception:
pass
batch_op.drop_column('code')
if 'company' in cols:
batch_op.drop_column('company')
for tbl in ('user_homepage_configs', 'user_favorite_agents', 'user_default_agents'):
if tbl in tables:
op.drop_table(tbl)
+29 -2
View File
@@ -1,4 +1,6 @@
"""Seed agents for freight shipping notice Chatflow orchestration."""
import sqlalchemy as sa
from app import create_app, db
from app.models import Agent
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME, EXTRACT_AGENT_NAME
@@ -9,6 +11,30 @@ CHAT_DESCRIPTION = "货代发货通知智能体:自然语言驱动解析、库
EXTRACT_DESCRIPTION = "后台专用:从邮件/PDF 文本抽取结构化发货通知字段(Workflow,供 Tool 内部调用)"
def _normalize_url(raw: str | None) -> str | None:
if raw is None:
return None
text = str(raw).strip()
if not text:
return None
if (text.startswith("`") and text.endswith("`")) or (text.startswith('"') and text.endswith('"')):
text = text[1:-1].strip()
return text or None
def _ensure_pg_sequence(table: str, pk: str) -> None:
engine_name = db.engine.dialect.name
if engine_name != "postgresql":
return
if not table.replace("_", "").isalnum() or not pk.replace("_", "").isalnum():
raise ValueError("invalid identifier")
sql = sa.text(
f"SELECT setval(pg_get_serial_sequence(:tbl, :pk), COALESCE((SELECT MAX({pk}) FROM {table}), 0), true)"
)
db.session.execute(sql, {"tbl": table, "pk": pk})
db.session.commit()
def _upsert_agent(
*,
name: str,
@@ -52,10 +78,11 @@ if __name__ == "__main__":
import os
with app.app_context():
_ensure_pg_sequence("agents", "id")
chat_key = os.getenv("SHIPPING_NOTICE_CHAT_DIFY_API_KEY") or os.getenv("DIFY_API_KEY")
chat_base = os.getenv("SHIPPING_NOTICE_CHAT_DIFY_BASE") or os.getenv("DIFY_API_BASE")
chat_base = _normalize_url(os.getenv("SHIPPING_NOTICE_CHAT_DIFY_BASE") or os.getenv("DIFY_API_BASE"))
extract_key = os.getenv("SHIPPING_NOTICE_EXTRACT_DIFY_API_KEY")
extract_base = os.getenv("SHIPPING_NOTICE_EXTRACT_DIFY_BASE") or chat_base
extract_base = _normalize_url(os.getenv("SHIPPING_NOTICE_EXTRACT_DIFY_BASE") or chat_base)
_upsert_agent(
name=CHAT_AGENT_NAME,
+22
View File
@@ -0,0 +1,22 @@
from pathlib import Path
from app.path_utils import backend_dir, resolve_backend_relative_path
def test_resolve_backend_relative_path_legacy_prefix():
root = backend_dir()
resolved = Path(resolve_backend_relative_path("backend/data/shipping_notice"))
assert resolved == (root / "data" / "shipping_notice").resolve()
def test_resolve_backend_relative_path_data_prefix():
root = backend_dir()
resolved = Path(resolve_backend_relative_path("data/shipping_notice"))
assert resolved == (root / "data" / "shipping_notice").resolve()
def test_resolve_backend_relative_path_default():
root = backend_dir()
default = root / "data" / "freight_rpa" / "inventory_drop"
resolved = Path(resolve_backend_relative_path(None, default))
assert resolved == default.resolve()
@@ -6,11 +6,38 @@ from app.services.shipping_notice.notice_lines import (
validate_notice_lines,
)
from app.services.shipping_notice.reservation_id import (
extract_reservation_id,
find_reservation_id_in_document,
looks_like_reservation_id,
normalize_reservation_id,
)
def test_extract_reservation_id_from_pr_number():
assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
def test_wistron_po_table_with_pr_number_in_document():
text = """
Vendor: HOXIN
PR Number: ADU_S-ENCWIW260528126265@1000140351
Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tAmount
10\t504-010213-001\tB3-A08AR11000001\tENCLOSURE\t9.000 PCS\t2026/06/15\t1,607.72 USD\t14,469.48 USD
"""
lines = parse_notice_table_text(text)
assert len(lines) == 1
assert lines[0]["sku"] == "504-010213-001"
assert lines[0]["line_no"] == "10"
assert lines[0]["qty"] == 9.0
assert lines[0]["unit_price"] == 1607.72
assert lines[0]["amount"] == 14469.48
assert lines[0]["reservation_id"] == "1000140351"
assert lines[0]["required_date"] == "2026-06-15"
assert lines[0]["vendor_part_number"] == "B3-A08AR11000001"
assert lines[0]["currency"] == "USD"
def test_normalize_reservation_id_from_excel_float():
assert normalize_reservation_id(1000140351.0) == "1000140351"
assert normalize_reservation_id("1000140351.0") == "1000140351"
@@ -55,18 +82,60 @@ def test_normalize_notice_line_aliases():
"quantity": "3",
"com_id": "COM-99",
"price": "12.5",
"delivery_date": "2026/06/15",
"vendorPartNumber": "VND-001",
"currency": "USD",
"line_no": "10",
}
)
assert line == {
"line_no": "10",
"sku": "A-001",
"qty": 3.0,
"uom": "EA",
"reservation_id": "COM-99",
"unit_price": 12.5,
"amount": 37.5,
"currency": "USD",
"required_date": "2026-06-15",
"vendor_part_number": "VND-001",
}
def test_enrich_notice_with_document_currency():
from app.services.shipping_notice.notice_lines import enrich_notice_with_document_currency
parsed = enrich_notice_with_document_currency(
{
"currency": "USD",
"lines": [{"sku": "A-001", "qty": 1, "uom": "EA"}, {"sku": "B-002", "qty": 2, "currency": "EUR", "uom": "EA"}],
}
)
assert parsed["lines"][0]["currency"] == "USD"
assert parsed["lines"][1]["currency"] == "EUR"
def test_extract_currency_from_price_string():
from app.services.shipping_notice.notice_lines import _extract_currency
assert _extract_currency("1,607.72 USD") == "USD"
assert _extract_currency("$15.5") == "USD"
assert _extract_currency("¥100") == "CNY"
def test_enrich_notice_with_document_required_date():
from app.services.shipping_notice.notice_lines import enrich_notice_with_document_required_date
parsed = enrich_notice_with_document_required_date(
{
"required_date": "2026-06-20",
"lines": [{"sku": "A-001", "qty": 1, "uom": "EA"}, {"sku": "B-002", "qty": 2, "required_date": "2026-06-18", "uom": "EA"}],
}
)
assert parsed["lines"][0]["required_date"] == "2026-06-20"
assert parsed["lines"][1]["required_date"] == "2026-06-18"
def test_extract_notice_fields_structured():
structured = {
"customer_name": "ACME",
@@ -5,6 +5,7 @@ from pathlib import Path
from openpyxl import Workbook
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
parse_inventory_rows,
parse_inventory_text,
read_inventory_schema_preview,
@@ -23,6 +24,19 @@ def _write_title_row_inventory_xlsx(path: Path) -> None:
wb.close()
def _write_header_index_mismatch_xlsx(path: Path) -> None:
wb = Workbook()
ws = wb.active
ws.append(["Inventory Report"])
ws.append(["AWS Sku", "Qty"])
ws.append(["EARLY-001", 7])
ws.append([])
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["LATE-001", "ORD-1", 5])
wb.save(str(path))
wb.close()
def test_read_inventory_schema_preview_skips_title_row(app, tmp_path):
path = tmp_path / "aws_title.xlsx"
_write_title_row_inventory_xlsx(path)
@@ -71,3 +85,42 @@ def test_parse_inventory_text_aws_table(app):
assert lines[0]["reservation_id"] == "ORD-3002"
assert lines[0]["available_qty"] == 4.0
assert column_meta["mapping"]["reservation_id"]["source_column"] == "Reservation Order"
def test_read_inventory_schema_preview_suggests_misspelled_reservation_order(app, tmp_path):
path = tmp_path / "aws_misspelled_reservation.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "Resevation Order", "Qty"])
ws.append(["10-40594-001", "ORD-3002", 4])
wb.save(str(path))
wb.close()
with app.app_context():
preview = read_inventory_schema_preview(path)
assert preview["headers"] == ["AWS Sku", "Resevation Order", "Qty"]
assert preview["suggested_mapping"]["reservation_id"] == "Resevation Order"
def test_parse_inventory_excel_uses_preview_header_row_index(app, tmp_path):
path = tmp_path / "header_mismatch.xlsx"
_write_header_index_mismatch_xlsx(path)
with app.app_context():
mapping = {"sku": "AWS Sku", "available_qty": "Qty"}
lines_auto, meta_auto = parse_inventory_excel_with_meta(path, field_mapping=mapping, mapping_source="manual")
lines_fixed, meta_fixed = parse_inventory_excel_with_meta(
path,
field_mapping=mapping,
mapping_source="manual",
header_row_index=2,
)
assert meta_auto["header_row_index"] == 5
assert meta_fixed["header_row_index"] == 2
assert any(line["sku"] == "EARLY-001" and line["available_qty"] == 7.0 for line in lines_fixed)
def test_match_extracts_reservation_id_suffix():
notice = [{"sku": "A001", "reservation_id": "1000140351", "qty": 1}]
inventory = [{"sku": "A001", "reservation_id": "ADU_S-ENCWIW260528126265@1000140351", "available_qty": 1}]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["available_qty"] == 1.0
@@ -0,0 +1,43 @@
from app.services.shipping_notice.match_rule_desc import (
build_match_rule_fallback,
extract_mapping_payload_extras,
resolve_match_rule,
)
def test_extract_mapping_payload_extras():
payload = {
"sku": "AWS Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
"match_rule": "以 Reservation Order 对齐订单 reservation_id,汇总 Qty Available 与订单 qty 比对。",
}
extras = extract_mapping_payload_extras(payload)
assert extras["match_rule"].startswith("以 Reservation Order")
assert "match_key" not in extras
def test_resolve_match_rule_prefers_llm():
mapping = {
"sku": "AWS Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
}
llm_rule = "LLM 自定义匹配说明。"
rule, keys, source = resolve_match_rule(mapping, llm_match_rule=llm_rule)
assert rule == llm_rule
assert keys == ["sku", "reservation_id"]
assert source == "llm"
def test_build_match_rule_fallback_uses_column_names():
mapping = {
"sku": "AWS Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
}
rule = build_match_rule_fallback(mapping)
assert "AWS Sku" in rule
assert "Reservation Order" in rule
assert "Qty Available" in rule
assert "按 SKU + Reservation ID" not in rule
@@ -0,0 +1,40 @@
from app.services.shipping_notice.match import format_match_summary
def test_format_match_summary_fulfillable():
msg = format_match_summary(
"fulfillable",
[
{
"sku": "10-40594-001",
"reservation_id": "AWS-311",
"required_qty": 2,
"available_qty": 5,
"shortage_qty": 0,
"line_status": "ok",
}
],
)
assert "匹配明细" in msg
assert "订单 2 / 库存 5" in msg
assert "充足" in msg
assert "可生成发货 Excel" in msg
def test_format_match_summary_shortage():
msg = format_match_summary(
"partial",
[
{
"sku": "A001",
"reservation_id": "R-1",
"required_qty": 100,
"available_qty": 5,
"shortage_qty": 95,
"line_status": "partial",
}
],
)
assert "订单 100 / 库存 5" in msg
assert "缺口 95" in msg
assert "部分行库存不足" in msg
@@ -0,0 +1,57 @@
from app.services.shipping_notice.parse_summary import format_parse_summary
def test_format_parse_summary_single_line():
msg = format_parse_summary(
task_no="SN-20260604-7249E4D7",
po_number="16754796",
ship_to="Wistron Corporation, Czech Republic",
lines=[
{
"sku": "504-010213-001",
"reservation_id": "1000140351",
"qty": 9,
"uom": "PCS",
"unit_price": 1607.72,
"amount": 14469.48,
"currency": "USD",
"required_date": "2026-06-15",
}
],
)
assert "【发货通知解析确认】任务编号:SN-20260604-7249E4D7" in msg
assert "| PO | 16754796 |" in msg
assert "| SKU | 504-010213-001 |" in msg
assert "| Reservation ID | 1000140351 |" in msg
assert "| 数量 | 9 PCS |" in msg
assert "| 单价 | $1,607.72 |" in msg
assert "| 金额 | $14,469.48 |" in msg
assert "| 需求日期 | 2026-06-15 |" in msg
assert "Wistron Corporation, Czech Republic" in msg
assert "请确认以上信息是否正确?" in msg
assert "待从任务中获取" not in msg
def test_format_parse_summary_multiple_lines():
msg = format_parse_summary(
task_no="SN-1",
po_number="PO-1",
lines=[
{"sku": "A", "qty": 1, "reservation_id": "R1"},
{"sku": "B", "qty": 2, "reservation_id": "R2"},
],
)
assert "【明细 1】" in msg
assert "【明细 2】" in msg
assert "PO:PO-1" in msg
def test_format_parse_summary_includes_warnings():
msg = format_parse_summary(
task_no="SN-1",
lines=[{"sku": "A", "qty": 1}],
warnings=["订单行未解析到 Reservation ID"],
low_confidence=True,
)
assert "订单行未解析到 Reservation ID" in msg
assert "解析置信度较低" in msg
@@ -0,0 +1,30 @@
from app.services.shipping_notice.po_number import find_po_number_in_document, normalize_po_number
from app.services.shipping_notice.extract import extract_notice_fields
def test_find_po_number_in_document():
text = """
PO Number: PO-2026-001
PR Number: ADU_S-PO260528126265@1000140351
"""
assert find_po_number_in_document(text) == "PO-2026-001"
def test_po_number_not_from_pr_number():
text = "PR Number: ADU_S-PO260528126265@1000140351"
assert find_po_number_in_document(text) == ""
def test_normalize_po_number():
assert normalize_po_number(" PO-99 ") == "PO-99"
assert normalize_po_number("") == ""
def test_extract_notice_fields_includes_po_number():
structured = {
"po_number": "PO-2026-001",
"lines": [{"sku": "A-001", "qty": 1}],
"confidence": 0.9,
}
parsed, _, _ = extract_notice_fields(raw_text="", structured=structured)
assert parsed["po_number"] == "PO-2026-001"
+220 -109
View File
@@ -1,5 +1,5 @@
from app import db
from app.models import ShippingCase
from app.models import ShippingInventoryMapping, ShippingTask
def _tool_headers(app):
@@ -12,29 +12,39 @@ def test_shipping_notice_tool_flow(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "raw_content": "客户:ACME 料号A001 x 10"},
)
assert create_res.status_code == 200
create_data = create_res.get_json()
assert create_data["status"] == "ok"
case_id = create_data["case_id"]
task_id = create_data["task_id"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={"case_id": case_id, "raw_text": "客户:ACME 料号A001 x 10"},
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
assert parse_res.status_code == 200
assert parse_res.get_json()["status"] in {"ok", "needs_human"}
parse_body = parse_res.get_json()
assert parse_body["status"] in {"ok", "needs_human"}
assert "【发货通知解析确认】" in parse_body["message"]
assert "| SKU | A001 |" in parse_body["message"]
inv_res = client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
"case_id": case_id,
"inventory_lines": [{"sku": "A001", "available_qty": 10}],
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
},
)
assert inv_res.status_code == 200
@@ -43,28 +53,32 @@ def test_shipping_notice_tool_flow(app, client):
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
assert match_res.status_code == 200
assert match_res.get_json()["status"] == "ok"
match_data = match_res.get_json()
assert match_data["status"] == "ok"
assert "订单" in match_data["message"]
assert "库存" in match_data["message"]
assert "A001" in match_data["message"]
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
assert excel_res.status_code == 200
assert excel_res.get_json()["status"] == "ok"
with app.app_context():
case = ShippingCase.query.filter_by(case_no=case_id).first()
assert case is not None
assert case.export_file_path
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.export_file_path
status_res = client.post(
"/api/shipping-notice/tools/get_case_status",
"/api/shipping-notice/tools/get_task_status",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
assert status_res.status_code == 200
assert status_res.get_json()["status"] == "ok"
@@ -74,20 +88,20 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 100, "uom": "EA"}],
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -95,21 +109,24 @@ def test_shipping_notice_match_shortage_needs_human(app, client):
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"case_id": case_id, "inventory_lines": [{"sku": "A001", "available_qty": 5}]},
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 5}]},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
assert "订单" in data["message"]
assert "库存" in data["message"]
assert "缺口" in data["message"]
assert "confirm" in (data.get("human_options") or [])
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "confirm"},
json={"task_id": task_id, "decision": "confirm"},
)
assert confirm_res.get_json()["status"] == "ok"
@@ -119,9 +136,9 @@ def test_openapi_spec_public(app, client):
res = client.get("/api/shipping-notice/tools/openapi.json")
assert res.status_code == 200
spec = res.get_json()
assert "create_case" in str(spec)
assert "create_task" in str(spec)
assert spec["servers"][0]["url"] == "http://tool-api.example.com/api/shipping-notice"
props = spec["paths"]["/tools/create_case"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"]
props = spec["paths"]["/tools/create_task"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"]
assert "raw_content" in props
assert "/rpa/" not in str(spec["paths"])
assert "/tools/parse_inventory" in spec["paths"]
@@ -133,20 +150,20 @@ def test_parse_inventory_from_chat_text(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 10, "uom": "EA"}],
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -156,7 +173,7 @@ def test_parse_inventory_from_chat_text(app, client):
parse_inv = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": inv_text},
json={"task_id": task_id, "raw_inventory_text": inv_text},
)
assert parse_inv.status_code == 200
data = parse_inv.get_json()
@@ -169,30 +186,33 @@ def test_parse_inventory_from_chat_text(app, client):
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "confirm_inventory_mapping"},
json={"task_id": task_id, "decision": "confirm_inventory_mapping"},
)
assert confirm_res.get_json()["status"] == "ok"
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "needs_human"
assert confirm_data.get("checkpoint") == "inventory_field_mapping_review"
assert "Reservation ID" in (confirm_data.get("message") or "")
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
assert match_res.get_json()["status"] == "ok"
assert match_res.get_json()["status"] in {"failed", "needs_human"}
def test_parse_inventory_empty_needs_human(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": " "},
json={"task_id": task_id, "raw_inventory_text": " "},
)
assert res.get_json()["status"] == "needs_human"
assert "reparse_inventory" in (res.get_json().get("human_options") or [])
@@ -201,17 +221,17 @@ def test_parse_inventory_empty_needs_human(app, client):
def test_match_by_aws_sku_and_reservation_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [
@@ -231,18 +251,18 @@ def test_match_by_aws_sku_and_reservation_id(app, client):
client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": inv_text},
json={"task_id": task_id, "raw_inventory_text": inv_text},
)
client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "confirm_inventory_mapping"},
json={"task_id": task_id, "decision": "confirm_inventory_mapping"},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
@@ -254,17 +274,17 @@ def test_match_by_aws_sku_and_reservation_id(app, client):
def test_match_inventory_blocked_before_mapping_confirm(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
@@ -276,7 +296,7 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
},
)
@@ -284,7 +304,7 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
blocked = match_res.get_json()
assert blocked["status"] == "needs_human"
@@ -296,22 +316,61 @@ def test_match_inventory_blocked_before_mapping_confirm(app, client):
assert mapping["inventory_columns"]["mapping"]["reservation_id"]["source_column"] == "COM ID"
def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
def test_match_inventory_requires_reservation_id(app, client):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "reservation_id_required"
def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
@@ -323,7 +382,7 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
},
)
@@ -331,7 +390,7 @@ def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
correct_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "correct_inventory_mapping"},
json={"task_id": task_id, "decision": "correct_inventory_mapping"},
)
data = correct_res.get_json()
assert data["status"] == "ok"
@@ -350,11 +409,11 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
from openpyxl import Workbook
@@ -369,7 +428,7 @@ def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
cb_res = client.post(
"/api/shipping-notice/rpa/inventory-ready",
headers=headers,
json={"case_no": case_id, "success": True, "file_path": str(inv_file)},
json={"task_no": task_id, "success": True, "file_path": str(inv_file)},
)
assert cb_res.status_code == 200
data = cb_res.get_json()
@@ -388,20 +447,20 @@ def test_rpa_upload_callback(app, client, tmp_path):
app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(trigger)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 5, "uom": "EA"}],
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 5, "uom": "EA"}],
"confidence": 0.95,
},
},
@@ -409,23 +468,23 @@ def test_rpa_upload_callback(app, client, tmp_path):
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"case_id": case_id, "inventory_lines": [{"sku": "A001", "available_qty": 10}]},
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
cb_res = client.post(
"/api/shipping-notice/rpa/upload-complete",
headers=headers,
json={"case_no": case_id, "success": True, "freight_ref_no": "FR-001"},
json={"task_no": task_id, "success": True, "freight_ref_no": "FR-001"},
)
assert cb_res.status_code == 200
assert cb_res.get_json()["status"] == "ok"
@@ -438,17 +497,17 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 1000
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
@@ -474,7 +533,7 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={
"case_id": case_id,
"task_id": task_id,
"file": (buf, "inventory.xlsx"),
},
)
@@ -490,14 +549,69 @@ def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"case_id": case_id,
"column_mapping_json": preview["suggested_mapping"],
"task_id": task_id,
"column_mapping_json": {
**preview["suggested_mapping"],
"match_rule": "LLM:Reservation Order 对齐订单 reservation_id,汇总 Qty Available。",
},
},
)
apply_data = apply_res.get_json()
assert apply_data["status"] == "needs_human"
assert apply_data.get("checkpoint") == "inventory_field_mapping_review"
assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1
assert apply_data["data"]["field_alignment"]["match_rule"].startswith("LLM:")
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "llm"
with app.app_context():
assert ShippingInventoryMapping.query.filter_by(customer_code="GLOBAL").count() >= 1
def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
from io import BytesIO
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["504-010213-001", "1000140351", 5])
buf = BytesIO()
wb.save(buf)
buf.seek(0)
client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={"task_id": task_id, "file": (buf, "inventory.xlsx")},
)
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"task_id": task_id,
"column_mapping_json": {
"sku": "AWS Sku",
"reservation_id": "COM ID",
"available_qty": "Qty Available",
},
},
)
apply_data = apply_res.get_json()
match_rule = apply_data["data"]["field_alignment"]["match_rule"]
assert "AWS Sku" in match_rule
assert "COM ID" in match_rule
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "fallback"
def test_get_inventory_schema_preview(app, client, tmp_path):
@@ -505,16 +619,16 @@ def test_get_inventory_schema_preview(app, client, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
missing = client.post(
"/api/shipping-notice/tools/get_inventory_schema_preview",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
assert missing.get_json()["checkpoint"] == "inventory_upload_required"
@@ -524,11 +638,11 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
from io import BytesIO
@@ -546,14 +660,14 @@ def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={"case_id": case_id, "file": (buf, "inv.xlsx")},
data={"task_id": task_id, "file": (buf, "inv.xlsx")},
)
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"column_mapping_json": {
"sku": "Part No",
"reservation_id": "Resv",
@@ -573,17 +687,17 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}],
@@ -595,44 +709,42 @@ def test_confirm_parse_does_not_skip_inventory_match(app, client):
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"case_id": case_id, "decision": "confirm"},
json={"task_id": task_id, "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "ok"
assert confirm_data.get("checkpoint") == "parse_confirmed"
assert "generate_shipment_excel" in (confirm_data.get("forbidden_next_tools") or [])
assert confirm_data["status"] in {"ok", "running", "needs_human"}
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"case_id": case_id},
json={"task_id": task_id},
)
excel_data = excel_res.get_json()
assert excel_data["status"] == "failed"
assert "匹配" in excel_data["message"]
with app.app_context():
case = ShippingCase.query.filter_by(case_no=case_id).first()
assert case is not None
assert case.process_status == "parsed"
assert case.match_status is None
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status in {"parsed", "waiting_inventory"}
assert task.match_status is None
def test_submit_decision_by_conversation_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "conversation_id": "conv-test-001"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"case_id": case_id,
"task_id": task_id,
"conversation_id": "conv-test-001",
"structured": {
"customer_name": "Wistron",
@@ -648,18 +760,17 @@ def test_submit_decision_by_conversation_id(app, client):
json={"conversation_id": "conv-test-001", "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "ok"
assert confirm_data["case_id"] == case_id
assert confirm_data.get("checkpoint") == "parse_confirmed"
assert confirm_data["status"] in {"ok", "running", "needs_human"}
assert confirm_data["task_id"] == task_id
dup_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "conversation_id": "conv-test-001"},
)
dup_data = dup_res.get_json()
assert dup_data["case_id"] == case_id
assert dup_data.get("checkpoint") == "case_already_exists"
assert dup_data["task_id"] == task_id
assert dup_data.get("checkpoint") == "task_already_exists"
def test_parse_inventory_rejects_oversized_text(app, client):
@@ -667,16 +778,16 @@ def test_parse_inventory_rejects_oversized_text(app, client):
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 100
create_res = client.post(
"/api/shipping-notice/tools/create_case",
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
case_id = create_res.get_json()["case_id"]
task_id = create_res.get_json()["task_id"]
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"case_id": case_id, "raw_inventory_text": "x" * 200},
json={"task_id": task_id, "raw_inventory_text": "x" * 200},
)
data = res.get_json()
assert data["status"] == "needs_human"
@@ -684,17 +795,17 @@ def test_parse_inventory_rejects_oversized_text(app, client):
assert "过大" in data["message"]
def test_chat_actions_empty_when_case_rejected(app):
from app.services.shipping_notice.chat_actions import build_chat_actions_payload, human_options_for_case
def test_chat_actions_empty_when_task_rejected(app):
from app.services.shipping_notice.chat_actions import build_chat_actions_payload, human_options_for_task
with app.app_context():
case = ShippingCase(
case_no="SN-20260101-TEST0001",
task = ShippingTask(
task_no="SN-20260101-TEST0001",
source_type="manual",
process_status="rejected",
review_status="rejected",
)
assert human_options_for_case(case) == []
payload = build_chat_actions_payload(case)
assert human_options_for_task(task) == []
payload = build_chat_actions_payload(task)
assert payload["checkpoint"] == "rejected"
assert payload["action_buttons"] == []
+30 -30
View File
@@ -11,11 +11,11 @@
}
],
"paths": {
"/tools/create_case": {
"/tools/create_task": {
"post": {
"operationId": "create_case",
"summary": "创建发货任务 case",
"description": "创建发货任务 case",
"operationId": "create_task",
"summary": "创建发货任务 task",
"description": "创建发货任务 task",
"parameters": [],
"requestBody": {
"required": true,
@@ -78,7 +78,7 @@
"schema": {
"type": "object",
"properties": {
"case_id": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
},
@@ -88,7 +88,7 @@
}
},
"required": [
"case_id"
"task_id"
]
}
}
@@ -121,13 +121,13 @@
"schema": {
"type": "object",
"properties": {
"case_id": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
},
"use_uploaded_file": {
"type": "string",
"description": "true=解析该 case 已上传的 Excel(服务端直传,不经过 LLM)",
"description": "true=解析该 task 已上传的 Excel(服务端直传,不经过 LLM)",
"enum": [
"true",
"false"
@@ -147,7 +147,7 @@
}
},
"required": [
"case_id"
"task_id"
]
}
}
@@ -180,13 +180,13 @@
"schema": {
"type": "object",
"properties": {
"case_id": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
}
},
"required": [
"case_id"
"task_id"
]
}
}
@@ -219,7 +219,7 @@
"schema": {
"type": "object",
"properties": {
"case_id": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
},
@@ -229,7 +229,7 @@
}
},
"required": [
"case_id",
"task_id",
"column_mapping_json"
]
}
@@ -263,7 +263,7 @@
"schema": {
"type": "object",
"properties": {
"case_id": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
},
@@ -281,7 +281,7 @@
}
},
"required": [
"case_id"
"task_id"
]
}
}
@@ -314,7 +314,7 @@
"schema": {
"type": "object",
"properties": {
"case_id": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
},
@@ -324,7 +324,7 @@
}
},
"required": [
"case_id"
"task_id"
]
}
}
@@ -357,7 +357,7 @@
"schema": {
"type": "object",
"properties": {
"case_id": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
},
@@ -379,7 +379,7 @@
}
},
"required": [
"case_id",
"task_id",
"decision"
]
}
@@ -413,13 +413,13 @@
"schema": {
"type": "object",
"properties": {
"case_id": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
}
},
"required": [
"case_id"
"task_id"
]
}
}
@@ -452,7 +452,7 @@
"schema": {
"type": "object",
"properties": {
"case_id": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
},
@@ -471,7 +471,7 @@
}
},
"required": [
"case_id"
"task_id"
]
}
}
@@ -491,11 +491,11 @@
}
}
},
"/tools/get_case_status": {
"/tools/get_task_status": {
"post": {
"operationId": "get_case_status",
"summary": "查询 case 当前状态与 human_options",
"description": "查询 case 当前状态与 human_options",
"operationId": "get_task_status",
"summary": "查询 task 当前状态与 human_options",
"description": "查询 task 当前状态与 human_options",
"parameters": [],
"requestBody": {
"required": true,
@@ -504,13 +504,13 @@
"schema": {
"type": "object",
"properties": {
"case_id": {
"task_id": {
"type": "string",
"description": "发货任务编号,如 SN-20260529-ABCD1234"
}
},
"required": [
"case_id"
"task_id"
]
}
}
@@ -531,4 +531,4 @@
}
}
}
}
}
+1458 -596
View File
File diff suppressed because it is too large. Load diff
+54 -19
View File
@@ -36,6 +36,12 @@
整个过程中,系统在关键节点会**暂停并请您确认**,避免误发、错配。
**系统如何工作(便于理解)**:
- 上传 **发货通知 PDF** 后,系统会在后台**自动**创建任务编号并解析订单行(无需您手动说「创建任务」)。
- 上传 **库存 Excel** 后,系统会**自动识别表头**(如 `Reservation Order`、`COM ID`)并给出列映射建议;**不确定的列**可在对齐界面用下拉框修改后再确认。
- 匹配与生成 Excel 由系统规则执行;您主要在解析结果、字段对齐、库存不足时做确认。
---
## 2. 入口与任务编号
@@ -75,28 +81,35 @@ SN-20260529-A1B2C3D4
### 4.1 订单行(来自发货通知)
系统会从发货通知中**逐行**提取以下信息(表头名称因客户而异,助手会尽量自动识别):
系统会从发货通知中**逐行**提取以下信息(表头名称因客户而异,助手会尽量自动识别)。此外会从文档头部提取 **PO Number(采购订单号)**:
| 字段 | 业务含义 | 常见表头示例 |
|------|----------|--------------|
| **SKU / 料号** | 物料编码 | AWS Sku、料号、Part Number |
| 字段 | 业务含义 | 常见表头/来源示例 |
|------|----------|-------------------|
| **PO Number** | 采购订单号(文档级) | PO Number、Purchase Order No、P.O. No、采购订单号;Wistron 原文若带 `ZNB` 前缀(如 ZNB16754796),系统输出为 `16754796` |
| **项次 / Item** | 订单行序号 | 项次、Line No、Item、Item No |
| **SKU / 料号** | 物料编码 | AWS Sku、Material、料号、Part Number |
| **需求数量** | 本次应发数量 | Qty、Order Qty、数量、发货数量 |
| **单价** | 单行单价 | Unit Price、单价、Price |
| **金额** | 单行金额 | Amount、Line Amount、金额、小计 |
| **Reservation ID** | 预留/订单占用编号,用于与库存精确对应 | Reservation ID、COM ID;**常见为 8~12 位纯数字**,如 `1000140351` |
| **币种** | 单价/金额的货币单位 | Currency、Curr、CCY、币种;也可从 `100.50 USD` 等形式识别 |
| **Reservation ID** | 预留/订单占用编号,用于与库存精确对应 | Reservation ID、COM ID;**常见为 8~12 位纯数字**(如 `1000140351`);Wistron 等 PO 可能在 **PR Number / PR_Number** 字段:`ADU_S-xxx@1000140351`,系统取 `@` 后数字 |
| **要求交期** | 该行物料的交货/发货日期 | Required Date、Delivery Date、ETA、交期、交货日期 |
| **供应商料号** | 客户侧记录的供应商物料编码 | Vendor Part Number、Vendor PN、Supplier Part No、供应商料号 |
**说明**:
- **PO Number** 为文档级字段;**PR Number**(含 `@1000140351`)通常对应 **Reservation ID**,不要与 PO Number 混淆。
- **SKU、需求数量、Reservation ID** 是库存核对的核心字段。
- **单价、金额** 主要用于展示与导出,**不参与**「够不够货」的自动比对。
- **要求交期、供应商料号、币种** 按**明细行**解析与导出;若 PDF 仅有一个文档级交期或币种,系统会回填到各行。
- **单价、金额、币种** 主要用于展示与导出,**不参与**「够不够货」的自动比对。
- 若订单含 Reservation ID 而库存表未正确对应,系统会在「字段对齐」环节给出警告。
**订单行示例**(便于理解系统解析目标):
| SKU | Reservation ID | 需求数量 | 单价 | 金额 |
|-----|----------------|----------|------|------|
| 10-40594-001 | 1000140351 | 2 | 15.50 | 31.00 |
| 10-40594-002 | 1000140352 | 1 | 20.00 | 20.00 |
| 项次 | SKU | Reservation ID | 需求数量 | 要求交期 | 供应商料号 | 单价 | 金额 | 币种 |
|------|-----|----------------|----------|----------|------------|------|------|------|
| 10 | 10-40594-001 | 1000140351 | 2 | 2026-06-15 | VND-PN-001 | 15.50 | 31.00 | USD |
| 20 | 10-40594-002 | 1000140352 | 1 | 2026-06-18 | VND-PN-002 | 20.00 | 20.00 | USD |
### 4.2 库存表(来自仓库/货代导出)
@@ -105,7 +118,7 @@ SN-20260529-A1B2C3D4
| 字段 | 业务含义 | 常见列名示例 |
|------|----------|--------------|
| **SKU / 料号** | 与订单 SKU 一致 | AWS Sku、料号 |
| **Reservation ID** | 与订单 Reservation ID 一致 | COM ID、Reservation Order、Reservation ID |
| **Reservation ID** | 与订单 Reservation ID 一致 | COM ID、**Reservation Order**、Reservation ID |
| **可用数量** | 当前可发数量 | Qty Available、可用数量、Qty |
**AWS 库存模板**(当前系统默认支持)示例:
@@ -157,13 +170,13 @@ SN-20260529-A1B2C3D4
**系统会做:**
- 创建任务并分配 **SN-…** 编号;
- 解析客户名称、收货信息、订单明细行。
- **自动**创建任务并分配 **SN-…** 编号;
- **自动**解析客户名称、收货信息、订单明细行(PDF 上传后由系统后台完成,无需您输入「创建任务」)。
**您会看到:**
- 助手展示解析出的表格或摘要;
- 若置信度较低,会明确要求您核对后再继续。
- 助手展示 **固定格式解析表格**(PO、SKU、Reservation ID、数量、单价、金额、交期、收货方等);
- 若置信度较低,表格下方会额外提示核对后再继续。
---
@@ -208,7 +221,9 @@ SN-20260529-A1B2C3D4
### 阶段 ④ — 确认字段对齐
上传库存后,助手会展示**字段对齐表**,说明:
上传库存后,系统会**先自动推断** Excel 列与订单字段的对应关系(例如 `AWS Sku`→SKU、`Reservation Order`→Reservation ID、`Qty Available`→可用数量),并展示**字段对齐表**供您核对。
对齐表说明:
- 库存 Excel 哪一列对应 SKU、Reservation ID、可用数量;
- 这些列如何与订单里的字段比对;
@@ -218,9 +233,11 @@ SN-20260529-A1B2C3D4
| 比对项 | 库存 Excel 列 | 订单字段 |
|--------|---------------|----------|
| 料号 | AWS Sku | SKU |
| 预留号 | COM ID | Reservation ID |
| 数量 | Qty Available | 需求数量 |
| 料号 | AWS Sku(或系统推断的列名) | SKU |
| 预留号 | COM ID / **Reservation Order**(可在下拉框中改选) | Reservation ID |
| 数量 | Qty Available(可在下拉框中改选) | 需求数量 |
聊天页若提供**列映射下拉框**,请核对自动推断是否正确;改选后须再次点击「确认」。
**可选操作:**
@@ -371,6 +388,24 @@ A:不可以。请使用「选择库存文件」上传;整表粘贴易失败
**Q:订单有 Reservation ID,库存表里是 COM ID,能匹配吗?**
A:可以。字段对齐环节会把 COM ID 与订单 Reservation ID 对应;确认映射无误即可。
**Q:发货通知解析结果里没有 Reservation ID(或一直为空)怎么办?**
A:Reservation ID(也可能叫 COM ID / Reservation Order / PR Number)是库存精确匹配的关键字段。请按以下顺序处理:
1. 先在原 PDF/邮件中确认是否真的存在该字段(常见写法:`Reservation ID: 1000140351`、`COM ID: 1000140351`、`Reservation Order: 1000140351`、`PR Number: xxx@1000140351`、`PR_Number: xxx@1000140351`)。
2. 若原件里存在但系统没抽出来:请联系 IT/开发按 [`shipping_notice.md`](./shipping_notice.md) **[§2.3 发货通知字段抽取(Chatflow LLM)](./shipping_notice.md#23-发货通知字段抽取chatflow-llm-节点)** 调整 **Chatflow 画布内 LLM 节点** 提示词(无需单独 Workflow 应用)。
3. 若原件里不存在:请向客户/上游确认 Reservation ID 的提供规则,否则系统只能按 SKU 汇总匹配,可能导致同 SKU 多预留号的场景误匹配。
给 IT/开发的配置说明(完整 System/User Prompt 见 `shipping_notice.md` **§2.3.4 / §2.3.3**,在 **Chatflow PDF 分支 LLM 节点** 维护):
```text
必须抽取 reservation_id(也称 COM ID / Reservation Order / PR Number / PR_Number)。
1) reservation_id 通常为 8~12 位纯数字(如 1000140351),必须输出为字符串,禁止输出为 1000140351.0。
2) 识别同义标签:"Reservation ID"/"COM ID"/"Reservation Order"/"PR Number"/"PR_Number"/"PR No"/"PR#"。
3) 若出现 "xxx@1000140351",reservation_id 取 @ 后的纯数字字符串(例如 1000140351)。
4) 若表格无该列,必须从全文找文档级 reservation_id 并回填到所有 lines[*].reservation_id。
5) 输出字段必须包含 lines[*].reservation_id(无则输出空串 "",不要省略或输出 null)。
```
**Q:Reservation ID 必须是数字吗?**
A:业务上**一般为 8~12 位纯数字**(如 `1000140351`)。若格式异常,系统会提示核对是否解析正确。
+12 -10
View File
@@ -1,5 +1,7 @@
# Dify Chatflow 绑定 OpenAPI — 操作手册
> **已归档**:Dify 配置已合并至 [`shipping_notice.md` §2 Dify 配置(合集)](./shipping_notice.md#2-dify-配置合集)(OpenAPI 与端口见 **§2.1–§2.2**,Chatflow 画布见 **§2.4**)。下文仅作历史参考,请以 §2 为准。
本文说明如何将 hxops **货代发货通知 Tool API** 绑定到 Dify **Chatflow** 应用「货代发货通知 Agent」。
---
@@ -97,14 +99,14 @@ python seed_shipping_notice_agents.py
- API Key 值:与 hxops `SHIPPING_NOTICE_TOOL_API_KEY` 一致
6. 点击 **测试** / **保存**,确认 8 个工具均解析成功:
- `create_case`
- `create_task`
- `parse_notice`
- `ensure_inventory`
- `match_inventory`
- `submit_decision`
- `generate_shipment_excel`
- `upload_to_freight`
- `get_case_status`
- `get_task_status`
> OpenAPI 已针对 Dify 优化:每个 POST 含 `parameters: []`、扁平 `requestBody` 字段、不含 RPA 回调接口。
@@ -137,11 +139,11 @@ GET /api/shipping-notice/tools/openapi.dify.yaml
## 步骤 4:配置系统提示词
将 `docs/shipping_notice_dify_prompt.md` 中「角色」至「对话风格」段落粘贴到 Chatflow **系统提示词 / Instructions**。
将 [`shipping_notice.md` §2.5 Agent 系统指令](./shipping_notice.md#25-agent-系统指令粘贴用) 全文粘贴到 Chatflow Agent 节点 **指令 / Instructions**。
要点:
- 必须先 `create_case`,全程携带 `case_id`
- 必须先 `create_task`,全程携带 `task_id`
- `status=needs_human` 时等待用户选择,勿跳过
- `inventory_lines_json` 传 JSON 字符串,例如:`[{"sku":"A001","available_qty":10}]`
@@ -149,8 +151,8 @@ GET /api/shipping-notice/tools/openapi.dify.yaml
| 变量 | 用途 |
|------|------|
| `sys.user_id` / 自定义 `user_id` | 传入 `create_case.user_id` |
| `sys.conversation_id` | 传入 `create_case.conversation_id` |
| `sys.user_id` / 自定义 `user_id` | 传入 `create_task.user_id` |
| `sys.conversation_id` | 传入 `create_task.conversation_id` |
---
@@ -165,9 +167,9 @@ GET /api/shipping-notice/tools/openapi.dify.yaml
```
4. 在 Dify **日志** 中确认 Agent 依次调用:
- `create_case` → `parse_notice` → `ensure_inventory` → …
- `create_task` → `parse_notice` → `ensure_inventory` → …
5. 工作台 **货代发货** 应出现新 case;状态为 `running` 时表示 RPA 进行中,可 `get_case_status` 轮询。
5. 工作台 **货代发货** 应出现新 task;状态为 `running` 时表示 RPA 进行中,可 `get_task_status` 轮询。
---
@@ -207,5 +209,5 @@ GET /api/shipping-notice/tools/openapi.dify.yaml
|------|------|
| `backend/app/services/shipping_notice/openapi_spec.py` | Dify 兼容 OpenAPI 生成 |
| `GET /api/shipping-notice/tools/openapi.json` | 动态 spec(含绝对 server URL) |
| `docs/shipping_notice_dify_prompt.md` | 系统提示词 |
| `docs/shipping_notice_runbook.md` | 整体部署 Runbook |
| `docs/shipping_notice.md` §2 | Dify 配置合集(OpenAPI、Workflow、画布、Agent 指令) |
| `docs/shipping_notice_runbook.md` | 精简部署 Runbook(Dify 见 §2) |
+13 -11
View File
@@ -1,5 +1,7 @@
# 货代发货通知 Agent — Dify Chatflow 系统提示词
> **已归档**:Agent 系统指令完整版见 [`shipping_notice.md` §2.5 Agent 系统指令](./shipping_notice.md#25-agent-系统指令粘贴用)。下文为旧版摘要,请以 §2.5 为准。
将以下内容配置到 Dify 应用 **「货代发货通知 Agent」**(`chatflow`)的系统提示词中,并绑定 Hxops Tool OpenAPI:`GET /api/shipping-notice/tools/openapi.json`(Header:`X-Shipping-Tool-Key`)。
---
@@ -10,18 +12,18 @@
## 核心原则
1. **先建 case**:收到新的发货需求时,先调用 `create_case`,保存 `case_id`(如 `SN-20260529-ABCD1234`),后续所有 Tool 都带上 `case_id`。
1. **先建 task**:收到新的发货需求时,先调用 `create_task`,保存 `task_id`(如 `SN-20260529-ABCD1234`),后续所有 Tool 都带上 `task_id`。
2. **按序编排**:`parse_notice` → `ensure_inventory` → `match_inventory` →(人工确认)→ `generate_shipment_excel` → `upload_to_freight`。
3. **尊重 Tool 响应**:每次 Tool 返回 `status` 为 `needs_human` 或 `running` 时,向用户说明原因与可选操作(`human_options`),**不要擅自跳过**。
4. **人工决策**:用户说「确认/驳回/重试 RPA/手工上传完成」等时,调用 `submit_decision` 或对应 Tool 的 `mode` 参数。
5. **状态查询**:不确定进度时调用 `get_case_status`。
5. **状态查询**:不确定进度时调用 `get_task_status`。
## Tool 响应约定
```json
{
"status": "ok | running | needs_human | failed",
"case_id": "SN-YYYYMMDD-XXXXXXXX",
"task_id": "SN-YYYYMMDD-XXXXXXXX",
"message": "人类可读说明",
"data": {},
"human_options": ["confirm", "reject", "retry_rpa", ...]
@@ -31,7 +33,7 @@
| status | 含义 | 你的行为 |
|--------|------|----------|
| `ok` | 步骤成功 | 继续下一步或总结 |
| `running` | 异步进行中(如 RPA) | 告知用户等待,可稍后 `get_case_status` |
| `running` | 异步进行中(如 RPA) | 告知用户等待,可稍后 `get_task_status` |
| `needs_human` | 必须人工选择 | 列出 `human_options`,等用户回复 |
| `failed` | 不可恢复错误 | 说明错误,建议联系管理员 |
@@ -39,14 +41,14 @@
### 1. 解析发货通知
用户粘贴邮件/微信/PDF 文本 → `parse_notice`(`case_id`, `raw_content`)。
用户粘贴邮件/微信/PDF 文本 → `parse_notice`(`task_id`, `raw_content`)。
- `needs_human` + `low_parse_confidence`:展示解析字段,请用户 **confirm / reject / reparse**。
- `confirm` → `submit_decision`(`decision: confirm`)。
### 2. 库存
`ensure_inventory`(`case_id`, `mode: auto`)。
`ensure_inventory`(`task_id`, `mode: auto`)。
- `running`:RPA 已触发,告知等待。
- `needs_human` + 无库存:提供 **retry_rpa** 或 **upload_inventory_file**(用户上传 Excel 路径/内容由 Tool 处理)。
@@ -55,18 +57,18 @@
### 3. 匹配
`match_inventory`(`case_id`)。
`match_inventory`(`task_id`)。
- `needs_human` + 库存不足:展示 shortage,请 **confirm / reject / rematch**。
- `ok` + `fulfillable` → 生成 Excel。
### 4. 生成 Excel
`generate_shipment_excel`(`case_id`)→ 告知文件名,可下载链接:`/api/shipping-notice/cases/{case_no}/export`。
`generate_shipment_excel`(`task_id`)→ 告知文件名,可下载链接:`/api/shipping-notice/tasks/{task_no}/export`。
### 5. 上传货代
`upload_to_freight`(`case_id`, `mode: auto`)。
`upload_to_freight`(`task_id`, `mode: auto`)。
- `running`:RPA 上传中。
- `needs_human`:提供 **retry_upload / download_excel / mark_manual_uploaded**。
@@ -75,7 +77,7 @@
## 对话风格
- 简洁中文,先给结论再列明细表格(SKU、数量、缺口)。
- 每次操作复述当前 `case_id`。
- 每次操作复述当前 `task_id`。
- 不要编造库存或货代单号;以 Tool 返回的 `data` 为准。
## 变量(可选)
@@ -87,4 +89,4 @@
## 内部 Workflow
字段抽取 Workflow **「发货通知字段抽取」** 由 `parse_notice` Tool 内部调用,Chatflow **无需**直接调用。
字段抽取 Workflow **「发货通知字段抽取」** 由 `parse_notice` Tool 内部调用,Chatflow **无需**直接调用。完整画布、System/User Prompt 见 [`shipping_notice.md` §2 Dify 配置(合集)](./shipping_notice.md#2-dify-配置合集)(Workflow §2.3,Chatflow §2.4,Agent 指令 §2.5)。
+17 -17
View File
@@ -1,5 +1,7 @@
# 货代发货通知 — 本地部署 Runbook
> **已归档**:完整部署与 Dify 配置见 [`shipping_notice.md`](./shipping_notice.md)(部署 **§1**,Dify **§2**)。下文为精简历史 Runbook,Dify 步骤请以 §2 为准。
## 1. 数据库迁移
```bash
@@ -13,17 +15,17 @@ flask db upgrade
# Tool API(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
SHIPPING_NOTICE_TOOL_API_KEY=your-tool-key
# 文件存储(可选,默认 instance/shipping_notice)
SHIPPING_NOTICE_STORAGE_ROOT=backend/data/shipping_notice
# 文件存储(相对 backend/ 根目录)
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
# RPA 目录(开发机本地路径,需 RPA worker 与 backend 一致)
FREIGHT_INVENTORY_DROP_DIR=backend/data/freight_rpa/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=backend/data/freight_rpa/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=backend/data/freight_rpa/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=backend/data/freight_rpa/upload_triggers
# RPA 目录(相对 backend/ 根目录)
FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop
FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers
FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue
FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers
# 发货 Excel 模板(可选,默认 backend/templates/freight_shipment_upload.xlsx)
FREIGHT_SHIPMENT_TEMPLATE_PATH=backend/templates/freight_shipment_upload.xlsx
# 发货 Excel 模板(可选,默认 templates/freight_shipment_upload.xlsx)
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
# Dify Chatflow / Workflow(seed 脚本用)
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
@@ -50,14 +52,12 @@ python seed_shipping_notice_agents.py
## 4. Dify Chatflow 配置
详细图文步骤见 **`docs/shipping_notice_dify_openapi_setup.md`**。
> **见 [`shipping_notice.md` §2 Dify 配置(合集)](./shipping_notice.md#2-dify-配置合集)**(OpenAPI §2.2、Workflow §2.3、画布 §2.4、Agent 指令 §2.5、验收 §2.6)。
1. 创建 Chatflow 应用 **货代发货通知 Agent**,写入 `.env` 后 `python seed_shipping_notice_agents.py`
2. Dify → **工具 → 自定义** → 从 URL 导入:
`http://<PUBLIC_BASE_URL>/api/shipping-notice/tools/openapi.json`
3. 鉴权 Header:`X-Shipping-Tool-Key: <SHIPPING_NOTICE_TOOL_API_KEY>`
4. Chatflow Agent 节点绑定该工具(8 个 operation)
5. 系统提示词:复制 `docs/shipping_notice_dify_prompt.md`
2. 按 §2.2 导入 OpenAPI 与鉴权 Header
3. 按 §2.3 创建并发布 Workflow **发货通知字段抽取**
4. 按 §2.4–§2.5 配置 Chatflow 画布与 Agent 指令
## 5. 开发环境 Mock RPA
@@ -75,7 +75,7 @@ python scripts/rpa/freight_rpa_worker.py
- 工作台侧边栏 **货代发货**(只读 case 列表)
- 独立路由 `/shipping-notice`
- 点击 **在 Chat 中继续** → `/chat/{agentId}?case_id=SN-...` 自动查询状态
- 点击 **在 Chat 中继续** → `/chat/{agentId}?task_id=SN-...` 自动查询状态
## 7. 端到端验证
@@ -84,7 +84,7 @@ cd backend
pytest tests/test_shipping_notice_tools.py -q
```
Tool 流程:create → parse → ensure_inventory(inventory_lines)→ match → generate_excel → get_case_status。
Tool 流程:create → parse → ensure_inventory(inventory_lines)→ match → generate_excel → get_task_status。
## 8. 待业务提供
+120 -20
View File
@@ -1,8 +1,8 @@
import { getAuthHeaders } from '../utils/auth';
export interface ShippingCaseSummary {
export interface ShippingTaskSummary {
id: number;
case_no: string;
task_no: string;
source_type: string;
customer_name?: string | null;
process_status: string;
@@ -16,22 +16,23 @@ export interface ShippingCaseSummary {
updated_at?: string | null;
}
export interface ShippingCaseEvent {
export interface ShippingTaskEvent {
event_type: string;
detail_json?: Record<string, unknown> | null;
created_at?: string | null;
}
export interface ShippingCaseDetail extends ShippingCaseSummary {
export interface ShippingTaskDetail extends ShippingTaskSummary {
customer_code?: string | null;
ship_to?: string | null;
po_number?: string | null;
required_date?: string | null;
lines: Array<Record<string, unknown>>;
shortage?: Record<string, unknown> | null;
line_results?: Array<Record<string, unknown>>;
parse_confidence?: number | null;
error_message?: string | null;
events: ShippingCaseEvent[];
events: ShippingTaskEvent[];
}
async function getJson<T>(url: string): Promise<T> {
@@ -43,19 +44,19 @@ async function getJson<T>(url: string): Promise<T> {
return res.json() as Promise<T>;
}
export const listWorkspaceShippingCases = (params?: { process_status?: string; limit?: number }) => {
export const listWorkspaceShippingTasks = (params?: { process_status?: string; limit?: number }) => {
const sp = new URLSearchParams();
if (params?.process_status) sp.set('process_status', params.process_status);
if (params?.limit) sp.set('limit', String(params.limit));
const qs = sp.toString();
return getJson<ShippingCaseSummary[]>(`/api/workspace/shipping-cases${qs ? '?' + qs : ''}`);
return getJson<ShippingTaskSummary[]>(`/api/workspace/shipping-tasks${qs ? '?' + qs : ''}`);
};
export const getWorkspaceShippingCase = (caseNo: string) =>
getJson<ShippingCaseDetail>(`/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}`);
export const getWorkspaceShippingTask = (taskNo: string) =>
getJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
export const workspaceShippingExportUrl = (caseNo: string) =>
`/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/export`;
export const workspaceShippingExportUrl = (taskNo: string) =>
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
export interface ShippingChatAction {
id: string;
@@ -65,7 +66,7 @@ export interface ShippingChatAction {
}
export interface ShippingChatActionsResponse {
case_no: string;
task_no: string;
checkpoint?: string | null;
process_status: string;
review_status?: string | null;
@@ -73,18 +74,18 @@ export interface ShippingChatActionsResponse {
action_buttons: ShippingChatAction[];
}
export const getShippingChatActions = (caseNo: string) =>
export const getShippingChatActions = (taskNo: string) =>
getJson<ShippingChatActionsResponse>(
`/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/chat-actions`,
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/chat-actions`,
);
export async function uploadWorkspaceShippingInventory(caseNo: string, file: File) {
export async function uploadWorkspaceShippingInventory(taskNo: string, file: File) {
const form = new FormData();
form.append('file', file);
const headers = getAuthHeaders();
delete (headers as Record<string, string>)['Content-Type'];
const res = await fetch(
`/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/upload-inventory`,
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/upload-inventory`,
{ method: 'POST', headers, body: form },
);
const body = (await res.json().catch(() => ({}))) as ShippingInventoryUploadResponse & { error?: string };
@@ -94,25 +95,92 @@ export async function uploadWorkspaceShippingInventory(caseNo: string, file: Fil
return body;
}
export async function applyWorkspaceShippingInventoryMapping(taskNo: string, columnMappingJson: Record<string, unknown>) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/apply-inventory-mapping`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ column_mapping_json: columnMappingJson }),
},
);
const body = (await res.json().catch(() => ({}))) as ShippingInventoryUploadResponse & { error?: string };
if (!res.ok) {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
export interface ShippingInventoryUploadResponse {
status: string;
message?: string;
case_id?: string;
task_id?: string;
checkpoint?: string;
data?: Record<string, unknown>;
}
export interface ShippingTaskCreateResponse {
status: string;
message?: string;
task_id?: string;
checkpoint?: string;
data?: Record<string, unknown>;
}
export async function createWorkspaceShippingTask(params?: {
source_type?: string;
conversation_id?: string;
raw_content?: string;
}) {
const res = await fetch('/api/workspace/shipping-tasks', {
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify(params || {}),
});
const body = (await res.json().catch(() => ({}))) as ShippingTaskCreateResponse & { error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
export interface ShippingNoticeUploadResponse {
status: string;
message?: string;
task_id?: string;
checkpoint?: string;
data?: Record<string, unknown>;
human_options?: string[];
}
export async function createWorkspaceShippingTaskFromNotice(file: File) {
const form = new FormData();
form.append('file', file);
const headers = getAuthHeaders();
delete (headers as Record<string, string>)['Content-Type'];
const res = await fetch('/api/workspace/shipping-tasks/create-from-notice', {
method: 'POST',
headers,
body: form,
});
const body = (await res.json().catch(() => ({}))) as ShippingNoticeUploadResponse & { error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
export interface ShippingDecisionResponse {
status: string;
message?: string;
case_id?: string;
task_id?: string;
checkpoint?: string;
data?: Record<string, unknown>;
}
export async function submitWorkspaceShippingDecision(caseNo: string, decision: string, comment?: string) {
export async function submitWorkspaceShippingDecision(taskNo: string, decision: string, comment?: string) {
const res = await fetch(
`/api/workspace/shipping-cases/${encodeURIComponent(caseNo)}/submit-decision`,
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/submit-decision`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
@@ -126,4 +194,36 @@ export async function submitWorkspaceShippingDecision(caseNo: string, decision:
return body;
}
export async function matchWorkspaceShippingInventory(taskNo: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/match-inventory`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({}),
},
);
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
export async function generateWorkspaceShippingExcel(taskNo: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/generate-excel`,
{
method: 'POST',
headers: { ...getAuthHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({}),
},
);
const body = (await res.json().catch(() => ({}))) as ShippingDecisionResponse & { error?: string };
if (!res.ok || body.status === 'failed') {
throw new Error(body.error || body.message || res.statusText);
}
return body;
}
export const SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent';
+10 -2
View File
@@ -22,7 +22,7 @@ interface ChatMessage {
// 对话消息结构:用户/助手文本 + 可选的来源与归因信息
role: 'user' | 'assistant';
content: string;
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result';
type?: 'text' | 'leave-form' | 'leave-confirmation' | 'leave-result' | 'shipping-inventory-mapping';
retriever_resources?: RetrieverResource[];
attribution_parts?: string[];
chat_log_id?: number;
@@ -174,6 +174,14 @@ export function useChat() {
activeRunId.value = null;
};
const loadConversationState = (id: string, nextMessages: ChatMessage[]) => {
viewId.value += 1;
activeRunId.value = null;
isThinking.value = false;
messages.value = nextMessages;
conversationId.value = id;
};
/**
* sendMessage
* 用途:发送消息并处理 SSE 流式响应
@@ -402,5 +410,5 @@ export function useChat() {
return text.replace(/\\n/g, '\n');
};
return { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage };
return { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, loadConversationState, sendMessage };
}
@@ -204,16 +204,17 @@ export function useAgentsAdmin() {
isTesting.value = true;
try {
const data = await testAdminAgent(target.id);
const passed = !!(data as any)?.passed;
testResult.value = {
success: !!data.success,
success: passed,
request_url: data.request_url || '',
output_info: data.output_info || '',
analysis: data.analysis || (data.success ? t('admin.agent.testDone') : t('admin.agent.testFailed')),
analysis: data.analysis || (passed ? t('admin.agent.testDone') : t('admin.agent.testFailed')),
http_status: data.http_status,
tested_at: data.tested_at,
};
if (data.success) {
if (passed) {
const idx = agents.value.findIndex((a) => a.id === target.id);
const row = idx >= 0 ? agents.value[idx] : undefined;
if (row) {
+16 -10
View File
@@ -432,14 +432,14 @@ const messages = {
}
},
shippingNotice: {
title: 'Shipping Notice Cases',
title: 'Shipping Notice Tasks',
subtitle: 'Read-only view. Continue processing in Chat.',
refresh: 'Refresh',
search: 'Search',
loading: 'Loading...',
empty: 'No shipping cases yet',
selectCase: 'Select a case to view details',
loadFailed: 'Failed to load case',
empty: 'No shipping tasks yet',
selectCase: 'Select a task to view details',
loadFailed: 'Failed to load task',
openChat: 'Continue in Chat',
download: 'Download Excel',
lines: 'Shipment lines',
@@ -1267,6 +1267,8 @@ const messages = {
placeholder: 'Ask anything...',
history: 'Chat History',
noHistory: 'No history',
historyEmpty: 'This conversation has no saved messages.',
historyLoadFailed: 'Failed to load conversation history.',
newChat: 'New Chat',
rate: 'Rate this response',
send: 'Send',
@@ -1275,9 +1277,9 @@ const messages = {
thinking: 'Generating response...',
disclaimer: 'AI can make mistakes. Please verify important information.',
createNewChat: 'New Chat',
shippingNoticeContinue: 'Please continue shipping case {caseId}. Call get_case_status first and tell me the next step.',
shippingNoticeContinue: 'Please continue shipping task {taskId}. Call get_task_status first and tell me the next step.',
shippingNoticeActionsHint: 'Choose an action (no need to type):',
shippingNoticeMissingCaseId: 'Case ID not found. Complete shipping notice parsing first.',
shippingNoticeMissingTaskId: 'Task ID not found. Complete shipping notice parsing first.',
shippingNoticeUploadDone: 'Inventory file uploaded: {fileName}.',
shippingNoticeUploadOk: 'Upload succeeded.',
shippingNoticeUploadFailed: 'Inventory upload failed.',
@@ -2780,6 +2782,8 @@ const messages = {
placeholder: '请输入问题...',
history: '历史记录',
noHistory: '暂无历史记录',
historyEmpty: '该会话暂无消息记录',
historyLoadFailed: '加载历史会话失败',
newChat: '新对话',
rate: '评价回答',
send: '发送',
@@ -2788,9 +2792,9 @@ const messages = {
thinking: '正在生成回答...',
disclaimer: 'AI 可能会犯错,请核实重要信息。',
createNewChat: '创建新对话',
shippingNoticeContinue: '请继续处理发货任务 {caseId},请先调用 get_case_status 查询当前状态并告知我下一步。',
shippingNoticeContinue: '请继续处理发货任务 {taskId},请先调用 get_task_status 查询当前状态并告知我下一步。',
shippingNoticeActionsHint: '请选择操作(无需输入文字):',
shippingNoticeMissingCaseId: '未找到 case_id,请先完成发货通知解析。',
shippingNoticeMissingTaskId: '未找到任务编号,请先完成发货通知解析。',
shippingNoticeUploadDone: '库存文件已上传:{fileName}。',
shippingNoticeUploadOk: '上传成功。',
shippingNoticeUploadFailed: '库存文件上传失败。',
@@ -4117,6 +4121,8 @@ const messages = {
placeholder: '請輸入問題...',
history: '歷史記錄',
noHistory: '暫無歷史記錄',
historyEmpty: '該會話暫無消息記錄',
historyLoadFailed: '加載歷史會話失敗',
newChat: '新對話',
rate: '評價回答',
send: '發送',
@@ -5363,6 +5369,8 @@ const messages = {
placeholder: 'ถามอะไรก็ได้...',
history: 'ประวัติการแชท',
noHistory: 'ไม่มีประวัติ',
historyEmpty: 'ไม่มีข้อความที่บันทึกไว้ในการสนทนานี้',
historyLoadFailed: 'โหลดประวัติการสนทนาไม่สำเร็จ',
newChat: 'แชทใหม่',
rate: 'ให้คะแนนคำตอบนี้',
send: 'ส่ง',
@@ -5633,5 +5641,3 @@ const i18n = createI18n({
});
export default i18n;
File diff suppressed because it is too large. Load diff
+27 -27
View File
@@ -4,12 +4,12 @@ import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ArrowLeft, Download, ExternalLink, RefreshCw } from 'lucide-vue-next';
import {
getWorkspaceShippingCase,
listWorkspaceShippingCases,
getWorkspaceShippingTask,
listWorkspaceShippingTasks,
SHIPPING_NOTICE_AGENT_NAME,
workspaceShippingExportUrl,
type ShippingCaseDetail,
type ShippingCaseSummary,
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '../api/shippingNotice';
import { getAuthHeaders } from '../utils/auth';
@@ -22,9 +22,9 @@ const { t } = useI18n();
const loading = ref(false);
const detailLoading = ref(false);
const cases = ref<ShippingCaseSummary[]>([]);
const selectedCaseNo = ref<string | null>(null);
const detail = ref<ShippingCaseDetail | null>(null);
const tasks = ref<ShippingTaskSummary[]>([]);
const selectedTaskNo = ref<string | null>(null);
const detail = ref<ShippingTaskDetail | null>(null);
const statusFilter = ref('all');
const chatAgentId = ref<number | null>(null);
@@ -55,21 +55,21 @@ const statusBadge = (status: string) => {
const loadCases = async () => {
loading.value = true;
try {
cases.value = await listWorkspaceShippingCases({
tasks.value = await listWorkspaceShippingTasks({
process_status: statusFilter.value === 'all' ? undefined : statusFilter.value,
limit: 100,
});
} catch {
cases.value = [];
tasks.value = [];
} finally {
loading.value = false;
}
};
const loadDetail = async (caseNo: string) => {
const loadDetail = async (taskNo: string) => {
detailLoading.value = true;
try {
detail.value = await getWorkspaceShippingCase(caseNo);
detail.value = await getWorkspaceShippingTask(taskNo);
} catch {
detail.value = null;
} finally {
@@ -89,24 +89,24 @@ const resolveChatAgent = async () => {
}
};
const openInChat = (caseNo: string) => {
const openInChat = (taskNo: string) => {
if (!chatAgentId.value) return;
router.push({ path: `/chat/${chatAgentId.value}`, query: { case_id: caseNo } });
router.push({ path: `/chat/${chatAgentId.value}`, query: { task_id: taskNo } });
};
const downloadExport = async (caseNo: string) => {
const url = workspaceShippingExportUrl(caseNo);
const downloadExport = async (taskNo: string) => {
const url = workspaceShippingExportUrl(taskNo);
const res = await fetch(url, { headers: getAuthHeaders() });
if (!res.ok) return;
const blob = await res.blob();
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = detail.value?.export_file_name || `${caseNo}.xlsx`;
a.download = detail.value?.export_file_name || `${taskNo}.xlsx`;
a.click();
URL.revokeObjectURL(a.href);
};
watch(selectedCaseNo, (val) => {
watch(selectedTaskNo, (val) => {
if (val) loadDetail(val);
else detail.value = null;
});
@@ -164,19 +164,19 @@ onMounted(async () => {
<div v-if="loading" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.loading') }}
</div>
<div v-else-if="cases.length === 0" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
<div v-else-if="tasks.length === 0" class="rounded-2xl border border-dashed border-default py-10 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.empty') }}
</div>
<button
v-for="item in cases"
:key="item.case_no"
v-for="item in tasks"
:key="item.task_no"
type="button"
class="w-full rounded-2xl border px-4 py-3 text-left transition-colors"
:class="selectedCaseNo === item.case_no ? 'border-brand-400 bg-brand-50/60' : 'border-default hover:bg-surface-soft/70'"
@click="selectedCaseNo = item.case_no"
:class="selectedTaskNo === item.task_no ? 'border-brand-400 bg-brand-50/60' : 'border-default hover:bg-surface-soft/70'"
@click="selectedTaskNo = item.task_no"
>
<div class="flex items-center justify-between gap-2">
<span class="font-mono text-sm font-semibold text-primary">{{ item.case_no }}</span>
<span class="font-mono text-sm font-semibold text-primary">{{ item.task_no }}</span>
<span class="rounded-full px-2 py-0.5 text-xs font-medium" :class="statusBadge(item.process_status).cls">
{{ statusBadge(item.process_status).label }}
</span>
@@ -187,7 +187,7 @@ onMounted(async () => {
</div>
<div class="lg:col-span-3 rounded-2xl border border-default bg-surface/50 p-5">
<div v-if="!selectedCaseNo" class="py-16 text-center text-sm text-muted">
<div v-if="!selectedTaskNo" class="py-16 text-center text-sm text-muted">
{{ $t('workspace.shippingNotice.selectCase') }}
</div>
<div v-else-if="detailLoading" class="py-16 text-center text-sm text-muted">
@@ -199,7 +199,7 @@ onMounted(async () => {
<div v-else class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-3">
<div>
<div class="font-mono text-lg font-bold text-primary">{{ detail.case_no }}</div>
<div class="font-mono text-lg font-bold text-primary">{{ detail.task_no }}</div>
<div class="text-sm text-muted">{{ detail.customer_name }} · {{ detail.customer_code || '—' }}</div>
</div>
<div class="flex flex-wrap gap-2">
@@ -207,7 +207,7 @@ onMounted(async () => {
v-if="chatAgentId"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-brand-300 bg-brand-50 px-3 py-1.5 text-sm font-medium text-brand-700 hover:bg-brand-100"
@click="openInChat(detail.case_no)"
@click="openInChat(detail.task_no)"
>
<ExternalLink class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.openChat') }}
@@ -216,7 +216,7 @@ onMounted(async () => {
v-if="detail.export_file_name"
type="button"
class="inline-flex items-center gap-1 rounded-xl border border-default px-3 py-1.5 text-sm font-medium text-secondary hover:bg-surface-soft"
@click="downloadExport(detail.case_no)"
@click="downloadExport(detail.task_no)"
>
<Download class="h-3.5 w-3.5" />
{{ $t('workspace.shippingNotice.download') }}
+2 -2
View File
@@ -6,9 +6,9 @@ Hxops 与货代系统之间通过 **目录 + JSON 触发文件** 解耦,RPA
| 环境变量 | 用途 |
|---------|------|
| `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` | hxops 写入 `inventory_export_{case_no}.json`,RPA 读取后导库存 |
| `FREIGHT_RPA_INVENTORY_TRIGGER_DIR` | hxops 写入 `inventory_export_{task_no}.json`,RPA 读取后导库存 |
| `FREIGHT_INVENTORY_DROP_DIR` | RPA 落盘库存 Excel(`.xlsx`),hxops / worker 回调 ingest |
| `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{case_no}.json` |
| `FREIGHT_RPA_UPLOAD_TRIGGER_DIR` | hxops 写入 `upload_{task_no}.json` |
| `FREIGHT_UPLOAD_QUEUE_DIR` | hxops 复制待上传发货 Excel |
## 开发环境 Mock
+22 -14
View File
@@ -45,7 +45,15 @@ def _require_path(name: str) -> Path:
value = _env(name)
if not value:
raise SystemExit(f"Missing env: {name}")
backend_dir = Path(__file__).resolve().parents[2] / "backend"
path = Path(value)
if not path.is_absolute():
normalized = value.replace("\\", "/")
if normalized.startswith("backend/"):
path = backend_dir / normalized[len("backend/") :]
else:
path = backend_dir / value
path = path.resolve()
path.mkdir(parents=True, exist_ok=True)
return path
@@ -76,7 +84,7 @@ def _post_callback(path: str, payload: dict) -> None:
print(f"[callback] {path} HTTP {exc.code}: {err[:300]}", file=sys.stderr)
def _write_sample_inventory(drop_dir: Path, case_no: str) -> Path:
def _write_sample_inventory(drop_dir: Path, task_no: str) -> Path:
sample = _env("FREIGHT_RPA_SAMPLE_INVENTORY")
if sample and Path(sample).is_file():
dest = drop_dir / Path(sample).name
@@ -86,7 +94,7 @@ def _write_sample_inventory(drop_dir: Path, case_no: str) -> Path:
if Workbook is None:
raise RuntimeError("openpyxl required to generate mock inventory")
dest = drop_dir / f"inventory_{case_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
dest = drop_dir / f"inventory_{task_no}_{datetime.utcnow().strftime('%Y%m%d%H%M%S')}.xlsx"
wb = Workbook()
ws = wb.active
ws.title = "Inventory"
@@ -99,8 +107,8 @@ def _write_sample_inventory(drop_dir: Path, case_no: str) -> Path:
def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
case_no = str(body.get("case_no") or "").strip()
if not case_no:
task_no = str(body.get("task_no") or "").strip()
if not task_no:
print(f"[skip] invalid inventory trigger: {trigger_path.name}")
trigger_path.unlink(missing_ok=True)
return
@@ -111,19 +119,19 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
return
try:
out_file = _write_sample_inventory(drop_dir, case_no)
out_file = _write_sample_inventory(drop_dir, task_no)
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"case_no": case_no,
"task_no": task_no,
"success": True,
"file_path": str(out_file),
})
processed_dir.mkdir(parents=True, exist_ok=True)
done = processed_dir / trigger_path.name
trigger_path.replace(done)
print(f"[inventory] mock export done for {case_no} -> {out_file.name}")
print(f"[inventory] mock export done for {task_no} -> {out_file.name}")
except Exception as exc:
_post_callback("/api/shipping-notice/rpa/inventory-ready", {
"case_no": case_no,
"task_no": task_no,
"success": False,
"error_message": str(exc),
})
@@ -132,9 +140,9 @@ def _handle_inventory_trigger(trigger_path: Path, drop_dir: Path, processed_dir:
def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
case_no = str(body.get("case_no") or "").strip()
task_no = str(body.get("task_no") or "").strip()
file_path = str(body.get("file_path") or "").strip()
if not case_no:
if not task_no:
trigger_path.unlink(missing_ok=True)
return
@@ -145,23 +153,23 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
if file_path and not Path(file_path).is_file():
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"case_no": case_no,
"task_no": task_no,
"success": False,
"error_message": f"queue file missing: {file_path}",
})
trigger_path.unlink(missing_ok=True)
return
ref = f"MOCK-{case_no}-{datetime.utcnow().strftime('%H%M%S')}"
ref = f"MOCK-{task_no}-{datetime.utcnow().strftime('%H%M%S')}"
_post_callback("/api/shipping-notice/rpa/upload-complete", {
"case_no": case_no,
"task_no": task_no,
"success": True,
"freight_ref_no": ref,
})
processed_dir.mkdir(parents=True, exist_ok=True)
done = processed_dir / trigger_path.name
trigger_path.replace(done)
print(f"[upload] mock upload done for {case_no} ref={ref}")
print(f"[upload] mock upload done for {task_no} ref={ref}")
def _scan_triggers(trigger_dir: Path, handler, extra_args: tuple = ()) -> None: