feat(shipping-notice): 完成货代发货通知全流程开发与代码重构
- 新增PO号提取、预约ID解析(支持`PR@xxx`格式)工具,完善库存匹配逻辑 - 新增库存映射缓存、匹配/解析结果格式化摘要,优化用户提示 - 修复数据库迁移脚本未检查表存在的问题,避免全新部署失败 - 新增路径工具类统一管理相对路径,优化配置文件处理逻辑 - 归档旧文档,将部署、Dify配置合并到`shipping_notice.md` - 新增完整单元测试与集成测试覆盖核心流程 - 更新前端国际化与会话管理逻辑,优化界面交互
This commit is contained in:
1 parent
b62082758b
commit
8deae3146b
65 files changed
+6477
-1937
No files matched your search
+16
-16
@@ -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
@@ -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}')
|
||||
|
||||
@@ -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",
|
||||
)
|
||||
@@ -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
@@ -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
@@ -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)
|
||||
|
||||
@@ -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())
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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()
|
||||
@@ -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))
|
||||
@@ -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
Reference in new issue
Block a user