Merge branch 'test' into prod

This commit is contained in:
sophie committed 2026-06-09 11:33:13 +08:00
commit e5b65d9ed4
109 files changed
+17757 -353

No files matched your search

+4
View File
@@ -55,7 +55,9 @@ def create_app(config_name='default'):
from app.api.integration import integration_bp
from app.api.schedule_admin import schedule_admin_bp
from app.api.workspace_schedule import workspace_schedule_bp
from app.api.workspace_shipping_notice import workspace_shipping_notice_bp
from app.api.internal_jobs import internal_jobs_bp
from app.api.shipping_notice_tools import shipping_notice_bp
from app.api.speech import speech_bp
# 聊天相关接口
@@ -72,7 +74,9 @@ def create_app(config_name='default'):
app.register_blueprint(integration_bp, url_prefix='/api/integration')
app.register_blueprint(schedule_admin_bp, url_prefix='/api/admin')
app.register_blueprint(workspace_schedule_bp, url_prefix='/api/workspace')
app.register_blueprint(workspace_shipping_notice_bp, url_prefix='/api/workspace')
app.register_blueprint(internal_jobs_bp, url_prefix='/api/internal/jobs')
app.register_blueprint(shipping_notice_bp, url_prefix='/api/shipping-notice')
app.register_blueprint(speech_bp, url_prefix='/api/speech')
# Eagerly load persisted runtime settings so the very first request after
+16 -16
View File
@@ -345,21 +345,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'):
@@ -375,10 +375,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()
@@ -402,7 +402,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 接口可访问,但未返回有效回答。'
@@ -413,17 +413,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
@@ -1176,4 +1176,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})
+53 -11
View File
@@ -16,7 +16,7 @@ from datetime import datetime
from urllib.parse import urlparse
import requests
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context
from sqlalchemy import func, desc, or_
from sqlalchemy import func, desc, or_, exists, and_
from openpyxl import load_workbook
from app.services.dify import DifyService
from app.services.integration_api import IntegrationApiService
@@ -63,6 +63,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,
@@ -749,9 +764,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]
@@ -864,14 +889,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 = []
@@ -1080,7 +1103,26 @@ def chat_completions():
raise ValidationError('This route does not support attachments')
generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
if HRLeaveSQLServerService.supports(query):
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
dify_inputs = None
from app.services.shipping_notice.dify_inputs import build_dify_chat_inputs, is_shipping_notice_chat_agent
if is_shipping_notice_chat_agent(agent_proxy):
dify_inputs = build_dify_chat_inputs()
generator = DifyService.stream_chat(
query,
user_proxy.id,
agent_proxy,
external_conversation_id,
request_id=request_id,
session_id=session.session_id,
files=normalized_files,
inputs=dify_inputs,
)
def relay_stream():
created_event = {
@@ -1329,7 +1371,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}')
+143
View File
@@ -0,0 +1,143 @@
"""
货代发货通知 Tool API — 供 Dify Chatflow Agent 调用
"""
from __future__ import annotations
from flask import Blueprint, current_app, jsonify, request, send_file
from pathlib import Path
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
shipping_notice_bp = Blueprint("shipping_notice", __name__)
def _tool_api_base_url() -> str:
"""Base URL for OpenAPI servers — hxops backend, NOT Dify (8882)."""
return resolve_tool_api_base_url()
def _dify_openapi_spec() -> dict:
return build_dify_openapi_spec(_tool_api_base_url())
def _payload() -> dict:
return request.get_json(silent=True) or {}
@shipping_notice_bp.route("/tools/openapi.json", methods=["GET"])
def openapi_spec():
return jsonify(_dify_openapi_spec())
@shipping_notice_bp.route("/tools/checkpoint-catalog", methods=["GET"])
def checkpoint_catalog():
"""Checkpoint ids, human_options, action_buttons — developer/docs reference (Dify approach B: do not embed)."""
from app.services.shipping_notice.state_machine import build_checkpoint_catalog
return jsonify(build_checkpoint_catalog())
@shipping_notice_bp.route("/tools/openapi.dify.yaml", methods=["GET"])
def openapi_dify_yaml():
import yaml
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
@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"])
def tool_parse_notice():
return jsonify(shipping_tools.parse_notice(_payload()))
@shipping_notice_bp.route("/tools/parse_inventory", methods=["POST"])
def tool_parse_inventory():
return jsonify(shipping_tools.parse_inventory(_payload()))
@shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"])
def tool_upload_inventory_file():
"""Multipart upload — parse server-side without sending Excel through LLM."""
task_id = str(request.form.get("task_id") or request.args.get("task_id") or "").strip()
upload = request.files.get("file")
return jsonify(shipping_tools.upload_inventory_file(task_id, upload))
@shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"])
def tool_get_inventory_schema_preview():
return jsonify(shipping_tools.get_inventory_schema_preview(_payload()))
@shipping_notice_bp.route("/tools/apply_inventory_mapping", methods=["POST"])
def tool_apply_inventory_mapping():
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
@shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"])
def tool_ensure_inventory():
return jsonify(shipping_tools.ensure_inventory(_payload()))
@shipping_notice_bp.route("/tools/auto_progress", methods=["POST"])
def tool_auto_progress():
return jsonify(shipping_tools.auto_progress(_payload()))
@shipping_notice_bp.route("/tools/match_inventory", methods=["POST"])
def tool_match_inventory():
return jsonify(shipping_tools.match_inventory(_payload()))
@shipping_notice_bp.route("/tools/submit_decision", methods=["POST"])
def tool_submit_decision():
return jsonify(shipping_tools.submit_decision(_payload()))
@shipping_notice_bp.route("/tools/generate_shipment_excel", methods=["POST"])
def tool_generate_shipment_excel():
return jsonify(shipping_tools.generate_excel(_payload()))
@shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"])
def tool_upload_to_freight():
return jsonify(shipping_tools.upload_to_freight(_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"])
def rpa_inventory_ready():
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
@shipping_notice_bp.route("/rpa/upload-complete", methods=["POST"])
def rpa_upload_complete():
return jsonify(shipping_tools.rpa_report_upload(_payload()))
@shipping_notice_bp.route("/tasks/<task_no>/export", methods=["GET"])
def download_task_export(task_no: str):
from app.services.shipping_notice.tools import _get_task
task = _get_task(task_no)
if not task or not task.export_file_path:
return jsonify({"error": "export file not found"}), 404
path = Path(task.export_file_path)
if not path.is_file():
return jsonify({"error": "export file missing on disk"}), 404
return send_file(
path,
as_attachment=True,
download_name=task.export_file_name or path.name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
+102 -8
View File
@@ -16,6 +16,7 @@ import hmac
import base64
import json
import re
import ast
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
user_bp = Blueprint('user', __name__)
_WECOM_ACCESS_TOKEN_CACHE = {'token': None, 'expires_at': None}
@@ -185,7 +186,7 @@ def _casdoor_exchange_code(code: str, redirect_uri: str):
resp = requests.post(token_endpoint, data=payload, timeout=8)
data = resp.json() or {}
if not resp.ok or not data.get('access_token'):
raise RuntimeError(f'Casdoor token exchange failed: {data}')
_raise_casdoor_auth_error(data, context='code')
return data
def _casdoor_refresh_token(refresh_token: str):
@@ -195,7 +196,7 @@ def _casdoor_refresh_token(refresh_token: str):
resp = requests.post(token_endpoint, data=payload, timeout=8)
data = resp.json() or {}
if not resp.ok or not data.get('access_token'):
raise RuntimeError(f'Casdoor refresh failed: {data}')
_raise_casdoor_auth_error(data, context='refresh')
return data
def _casdoor_userinfo(access_token: str):
@@ -222,7 +223,7 @@ def _casdoor_password_login(username: str, password: str):
resp = requests.post(token_endpoint, data=payload, timeout=8)
data = resp.json() or {}
if not resp.ok or not data.get('access_token'):
raise RuntimeError(f'Casdoor password login failed: {data}')
_raise_casdoor_auth_error(data, context='password')
return data
def _is_casdoor_login_mode() -> bool:
@@ -258,12 +259,90 @@ def _casdoor_set_password(user_owner: str, user_name: str, old_password: str, ne
except ValueError:
raise RuntimeError(f'Casdoor set-password failed: HTTP {resp.status_code} {resp.text[:200]}')
if data.get('status') != 'ok':
raise RuntimeError(data.get('msg') or f'Casdoor set-password failed: {data}')
_raise_casdoor_set_password_error(data)
def _is_casdoor_password_error(message: str) -> bool:
lowered = (message or '').lower()
return 'invalid_grant' in lowered or 'password login failed' in lowered or 'incorrect password' in lowered
def _is_casdoor_user_missing_error(message: str) -> bool:
lowered = (message or '').lower()
return (
"doesn't exist" in lowered
or 'does not exist' in lowered
or 'user not found' in lowered
or 'no such user' in lowered
)
def _raise_casdoor_user_not_in_idp(source=None) -> None:
data = _extract_casdoor_error_payload(source)
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
raise AppError(
code='CASDOOR_USER_NOT_IN_IDP',
message='Your account has not been registered in the authentication system. Please contact the administrator.',
http_status=409,
details={'technical': msg_text or str(source or '')[:300]},
)
def _extract_casdoor_error_payload(source) -> dict:
if isinstance(source, dict):
return source
text = str(source or '')
match = re.search(r'\{.*\}', text, re.DOTALL)
if match:
try:
parsed = ast.literal_eval(match.group(0))
if isinstance(parsed, dict):
return parsed
except (SyntaxError, ValueError):
pass
try:
parsed = json.loads(text)
if isinstance(parsed, dict):
return parsed
except (json.JSONDecodeError, TypeError):
pass
return {}
def _raise_casdoor_auth_error(source, *, context: str, status_code: int = 401) -> None:
"""
Map Casdoor OAuth/API failures to stable business error codes for frontend i18n.
context: password | verify | code | refresh
"""
data = _extract_casdoor_error_payload(source)
raw = str(source or '')
oauth_error = _clean_str(data.get('error')).lower()
if not oauth_error and 'invalid_grant' in raw.lower():
oauth_error = 'invalid_grant'
if not oauth_error and 'invalid_client' in raw.lower():
oauth_error = 'invalid_client'
if oauth_error == 'invalid_grant' or _is_casdoor_password_error(raw):
if context in ('password', 'verify'):
raise AppError(code='CASDOOR_INVALID_CREDENTIALS', message='Incorrect username or password', http_status=401)
raise AppError(code='CASDOOR_CODE_EXPIRED', message='Login session expired, please sign in again', http_status=401)
if oauth_error in ('invalid_client', 'unauthorized_client'):
raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is misconfigured. Please contact the administrator.', http_status=503, details={'casdoor_error': oauth_error})
if oauth_error == 'access_denied':
raise AppError(code='CASDOOR_ACCESS_DENIED', message='Login was cancelled or denied', http_status=403)
if 'token endpoint missing' in raw.lower() or 'casdoor_base_url is not configured' in raw.lower() or 'casdoor is not configured' in raw.lower():
raise AppError(code='CASDOOR_CONFIG_ERROR', message='Authentication service is not configured. Please contact the administrator.', http_status=503)
if 'invalid or expired casdoor state' in raw.lower():
raise ValidationError('Invalid or expired Casdoor state')
current_app.logger.warning('[casdoor] unmapped auth error context=%s payload=%s raw=%s', context, data, raw[:500])
raise AppError(code='CASDOOR_AUTH_FAILED', message='Authentication failed, please try again', http_status=status_code, details={'casdoor_error': oauth_error or None, 'technical': raw[:300]})
def _raise_casdoor_set_password_error(source) -> None:
data = _extract_casdoor_error_payload(source)
msg_text = _clean_str(data.get('msg') or data.get('error_description') or data.get('message'))
lowered = (msg_text or str(source or '')).lower()
if _is_casdoor_password_error(lowered) or 'old password' in lowered or 'current password' in lowered:
_raise_incorrect_current_password()
if any(token in lowered for token in ('too short', 'too weak', 'password policy', 'at least')):
raise AppError(code='CASDOOR_PASSWORD_POLICY', message='New password does not meet security requirements', http_status=400)
if _is_casdoor_user_missing_error(lowered):
_raise_casdoor_user_not_in_idp(source)
raise AppError(code='CASDOOR_SET_PASSWORD_FAILED', message='Failed to change password. Please try again or contact the administrator.', http_status=502, details={'technical': msg_text or str(source)[:300]})
def _raise_incorrect_current_password():
raise AppError(
code='AUTH.INCORRECT_CURRENT_PASSWORD',
@@ -278,6 +357,10 @@ def _verify_current_password_for_change(user, current_password: str):
_raise_incorrect_current_password()
try:
_verify_casdoor_password(user.username, current_password)
except AppError as e:
if e.code == 'CASDOOR_INVALID_CREDENTIALS':
_raise_incorrect_current_password()
raise
except RuntimeError as e:
if _is_casdoor_password_error(str(e)):
_raise_incorrect_current_password()
@@ -289,7 +372,13 @@ def _sync_casdoor_password(username: str, current_password: str, new_password: s
user_owner = _casdoor_user_owner()
try:
_casdoor_set_password(user_owner, username, current_password, new_password)
except AppError as first_error:
if first_error.code in ('CASDOOR_INVALID_CREDENTIALS', 'AUTH.INCORRECT_CURRENT_PASSWORD'):
_raise_incorrect_current_password()
raise
except RuntimeError as first_error:
if _is_casdoor_user_missing_error(str(first_error)):
_raise_casdoor_user_not_in_idp(first_error)
if _is_casdoor_password_error(str(first_error)):
_raise_incorrect_current_password()
try:
@@ -775,9 +864,12 @@ def casdoor_password_login():
except WeComLoginError:
db.session.rollback()
raise
except AppError:
db.session.rollback()
raise
except Exception as e:
db.session.rollback()
raise UnauthorizedError(f'Casdoor password login failed: {str(e)}')
_raise_casdoor_auth_error(e, context='password')
@user_bp.route('/casdoor/authorize-url', methods=['GET'])
def casdoor_authorize_url():
@@ -903,10 +995,13 @@ def casdoor_login():
db.session.rollback()
current_app.logger.warning('[casdoor_login] business_reject')
raise
except AppError:
db.session.rollback()
raise
except Exception as e:
db.session.rollback()
current_app.logger.exception('[casdoor_login] failed state=%s redirect_uri=%s', state[:24] if state else '', redirect_uri)
raise UnauthorizedError(f'Casdoor login failed: {str(e)}')
_raise_casdoor_auth_error(e, context='code')
@user_bp.route('/casdoor/refresh', methods=['POST'])
def casdoor_refresh():
@@ -1460,8 +1555,7 @@ def change_password():
message = str(e)
if _is_casdoor_password_error(message):
_raise_incorrect_current_password()
current_app.logger.exception('[change_password] Casdoor failed user=%s', user.username)
raise AppError(code='SYSTEM.HTTP_ERROR', message=f'Failed to change password: {message}', http_status=502, details={'error_code': 'CASDOOR_SET_PASSWORD_FAILED'})
_raise_casdoor_set_password_error(e)
except Exception as e:
db.session.rollback()
raise AppError(code='SYSTEM.INTERNAL_ERROR', message=str(e), http_status=500)
@@ -0,0 +1,323 @@
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.constants import CP_EXPORT_GENERATED, CP_NOTICE_TEXT_EXTRACTION_FAILED, AUTO_CHAIN_FALLBACK, MAP_JSON
from app.services.shipping_notice.query_service import (
get_task_for_user,
list_tasks_for_user,
serialize_task_detail,
)
workspace_shipping_notice_bp = Blueprint("workspace_shipping_notice", __name__)
def _require_user():
user = get_current_user()
if not user:
return None, (jsonify({"error": "Unauthorized"}), 401)
return user, None
@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_tasks_for_user(user.id, process_status=process_status, limit=limit))
@workspace_shipping_notice_bp.route("/shipping-tasks", methods=["POST"])
def workspace_create_shipping_task():
user, err = _require_user()
if err:
return err
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-tasks/create-from-notice", methods=["POST"])
def workspace_create_shipping_task_from_notice():
user, err = _require_user()
if err:
return err
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)
if not text:
from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint
return jsonify(
{
"status": "needs_human",
"task_id": task_id,
"message": "未能从附件抽取到可解析文本(可能是扫描件/OCR 不可用)。请复制粘贴文本,或更换清晰版文件后重试。",
"data": {"notice_upload": {"filename": upload.filename or "", **meta}},
"human_options": ["reparse", "reject"],
"checkpoint": CP_NOTICE_TEXT_EXTRACTION_FAILED,
"action_buttons": action_buttons_for_checkpoint(CP_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}
parsed = shipping_tools.parse_notice(payload)
data = parsed.get("data") if isinstance(parsed, dict) else None
if isinstance(data, dict):
data["notice_upload"] = {"filename": upload.filename or "", **meta}
parsed["message"] = f"已上传发货通知文件并创建任务 {task_id}。{parsed.get('message') or ''}".strip()
return jsonify(parsed)
@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(serialize_task_detail(task))
@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
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(task.task_no, upload))
@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
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
map_json = data.get(MAP_JSON)
if not isinstance(map_json, dict) or not map_json:
return jsonify({"error": f"{MAP_JSON} is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, MAP_JSON: map_json, AUTO_CHAIN_FALLBACK: True}
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
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 {}
decision = str(data.get("decision") or "").strip()
if not decision:
return jsonify({"error": "decision is required"}), 400
from app.services.shipping_notice import tools as shipping_tools
payload = {"task_id": task.task_no, "decision": decision, AUTO_CHAIN_FALLBACK: True}
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-tasks/<task_no>/auto-progress", methods=["POST"])
def workspace_auto_progress_shipping_task(task_no: str):
"""Hxops chat fallback: same as Dify auto_progress tool."""
user, err = _require_user()
if err:
return err
task = get_task_for_user(task_no, user.id)
if not task:
return jsonify({"error": "Not found"}), 404
from app.services.shipping_notice import tools as shipping_tools
data = request.get_json(silent=True) or {}
payload: dict = {"task_id": task.task_no}
for key in ("lang", "locale", "language"):
if data.get(key):
payload[key] = data[key]
break
result = shipping_tools.auto_progress(payload)
if isinstance(result, dict) and result.get("status") == "ok":
gen_data = result.get("data")
if isinstance(gen_data, dict) and gen_data.get("export_file_path"):
gen_data = {**gen_data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"}
result = {**result, "data": gen_data}
return jsonify(result)
@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
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
from app.services.shipping_notice.state_machine import (
action_buttons_for_checkpoint,
human_options_for_checkpoint,
)
matched = shipping_tools.match_inventory({"task_id": task.task_no, AUTO_CHAIN_FALLBACK: True})
if not isinstance(matched, dict):
return jsonify(matched)
data = matched.get("data")
if isinstance(data, dict) and data.get("export_file_path"):
matched = {
**matched,
"data": {**data, "download_url": f"/api/workspace/shipping-tasks/{task.task_no}/export"},
}
checkpoint = matched.get("checkpoint") or CP_EXPORT_GENERATED
if matched.get("status") == "ok" and data and data.get("export_file_path"):
matched["checkpoint"] = checkpoint
if "human_options" not in matched:
options = human_options_for_checkpoint(checkpoint)
if options is not None:
matched["human_options"] = options
if "action_buttons" not in matched:
buttons = action_buttons_for_checkpoint(checkpoint)
if buttons:
matched["action_buttons"] = buttons
return jsonify(matched)
@workspace_shipping_notice_bp.route("/shipping-tasks/<task_no>/mark-manual-uploaded", methods=["POST"])
def workspace_mark_manual_uploaded(task_no: str):
"""Hxops chat: mark freight manual upload complete (no ref no required)."""
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
return jsonify(
shipping_tools.upload_to_freight({"task_id": task.task_no, "mode": "manual_confirm"})
)
@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(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=task.export_file_name or path.name,
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
+69
View File
@@ -51,6 +51,20 @@ def _load_environment_files() -> str:
ACTIVE_ENV_NAME = _load_environment_files()
def _data_path(env_key: str, *parts: str) -> str:
from app.path_utils import resolve_backend_relative_path
default = _BACKEND_DIR.joinpath("data", *parts)
return resolve_backend_relative_path(os.getenv(env_key), default)
def _backend_path(env_key: str, *parts: str) -> str:
from app.path_utils import resolve_backend_relative_path
default = _BACKEND_DIR.joinpath(*parts)
return resolve_backend_relative_path(os.getenv(env_key), default)
class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY')
@@ -93,6 +107,61 @@ class Config:
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE')
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
# 货代发货通知 Agent Tool API
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 = _data_path("SHIPPING_NOTICE_STORAGE_ROOT", "shipping_notice")
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD = float(
os.getenv('SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD') or '0.7'
)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS') or '3'
)
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS') or '120'
)
SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM = os.getenv('SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_MATCH_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_MATCH_ENABLED', 'true').lower() == 'true'
SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED = (
os.getenv('SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN = os.getenv(
'SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN',
'shipment_{task_no}_{ts}.xlsx',
)
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED', 'false').lower() == 'true'
# Hxops 工作台 / 聊天按钮兜底串联(Dify 主路径走 auto_progress;画布 HTTP 不传 auto_chain_fallback)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK = os.getenv('SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK', 'true').lower() == 'true'
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS = int(os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS') or '3')
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS') or '30'
)
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS = int(
os.getenv('SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS') or '80000'
)
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
)
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
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'
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
+78 -1
View File
@@ -1,6 +1,6 @@
from datetime import datetime
from typing import Optional, List
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary, text
from sqlalchemy import String, Text, Integer, ForeignKey, JSON, DateTime, Index, Boolean, UniqueConstraint, LargeBinary, Float, text
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app import db
from werkzeug.security import generate_password_hash, check_password_hash
@@ -679,6 +679,83 @@ class ScheduleRun(Base):
task: Mapped[Optional["ScheduleTask"]] = relationship("ScheduleTask", foreign_keys=[schedule_task_id])
class ShippingTask(Base):
"""货代发货通知 task(Chatflow Tool 编排状态机)"""
__tablename__ = 'shipping_tasks'
__table_args__ = (
Index('ix_shipping_tasks_user_status', 'user_id', 'process_status'),
Index('ix_shipping_tasks_conversation', 'conversation_id'),
)
id: Mapped[int] = mapped_column(primary_key=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')
raw_content: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
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)
process_status: Mapped[str] = mapped_column(String(32), default='created', index=True)
review_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
match_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
shortage_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
line_results_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(nullable=True)
inventory_lines_json: Mapped[Optional[list]] = mapped_column(JSON, nullable=True)
export_file_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
export_file_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
freight_ref_no: Mapped[Optional[str]] = mapped_column(String(128), nullable=True)
pending_human_reason: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
error_message: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow)
events: Mapped[List["ShippingTaskEvent"]] = relationship(
"ShippingTaskEvent",
back_populates="task",
cascade="all, delete-orphan",
)
class ShippingTaskEvent(Base):
"""发货 task 审计事件"""
__tablename__ = 'shipping_task_events'
id: Mapped[int] = mapped_column(primary_key=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)
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)
class AgentGuide(Base):
"""
平台应用新手指南表
+28
View File
@@ -0,0 +1,28 @@
"""Resolve paths relative to the backend package root (not process cwd)."""
from __future__ import annotations
from pathlib import Path
_BACKEND_DIR = Path(__file__).resolve().parents[1]
def backend_dir() -> Path:
return _BACKEND_DIR
def resolve_backend_relative_path(raw: str | None, default: Path | None = None) -> str:
"""Resolve env paths like ``data/foo`` or legacy ``backend/data/foo``."""
value = (raw or "").strip()
if not value:
if default is None:
raise ValueError("path is required when no default is provided")
return str(default.resolve())
path = Path(value)
if path.is_absolute():
return str(path.resolve())
normalized = value.replace("\\", "/")
if normalized.startswith("backend/"):
return str((_BACKEND_DIR / normalized[len("backend/") :]).resolve())
return str((_BACKEND_DIR / value).resolve())
+88 -57
View File
@@ -206,12 +206,28 @@ class DifyService:
@staticmethod
def _stringify_inputs(inputs: dict[str, Any] | None) -> dict[str, Any]:
def _is_file_obj(v: Any) -> bool:
if not isinstance(v, dict):
return False
if not str(v.get("type") or "").strip():
return False
tm = str(v.get("transfer_method") or "").strip()
if tm not in {"local_file", "remote_url"}:
return False
if tm == "local_file":
return bool(str(v.get("upload_file_id") or "").strip())
return bool(str(v.get("url") or "").strip())
def _convert(v):
if v is None:
return ""
if _is_file_obj(v):
return v
if isinstance(v, dict):
return {kk: _convert(vv) for kk, vv in v.items()}
if isinstance(v, list):
if v and all(_is_file_obj(i) for i in v):
return v
return [_convert(i) for i in v]
return str(v)
return {k: _convert(v) for k, v in (inputs or {}).items()}
@@ -492,6 +508,7 @@ class DifyService:
request_id: str | None = None,
session_id: str | None = None,
files: list[dict[str, Any]] | None = None,
inputs: dict[str, Any] | None = None,
):
"""
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
@@ -522,7 +539,7 @@ class DifyService:
'Content-Type': 'application/json',
}
payload = {
'inputs': {},
'inputs': dict(inputs or {}),
'query': query,
'response_mode': 'streaming',
'user': str(user_id),
@@ -550,11 +567,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 +709,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
Whitespace-only changes.
@@ -0,0 +1,9 @@
from __future__ import annotations
from app.models import Agent
CHAT_AGENT_NAME = "货代发货通知 Agent"
def resolve_chat_agent() -> Agent | None:
return Agent.query.filter_by(name=CHAT_AGENT_NAME, is_active=True).first()
@@ -0,0 +1,51 @@
"""Backward-compatible re-exports — canonical definitions live in state_machine.py."""
from app.services.shipping_notice.state_machine import (
ACTION_SPECS,
ALL_ACTION_IDS,
ALL_CHECKPOINT_IDS,
CHECKPOINT_REGISTRY,
TaskTransition,
TaskUiState,
action_buttons_for_checkpoint,
apply_task_transition,
build_action_buttons,
build_chat_actions_payload,
build_checkpoint_catalog,
checkpoint_for_task,
format_actions_directive,
human_options_for_checkpoint,
human_options_for_task,
human_options_for_task_or_checkpoint,
resolve_task_ui_state,
ui_state_for_checkpoint,
upload_req_options_for_task,
validate_registry,
)
# Legacy alias
CHECKPOINT_OPTIONS = CHECKPOINT_REGISTRY
__all__ = [
"ACTION_SPECS",
"ALL_ACTION_IDS",
"ALL_CHECKPOINT_IDS",
"CHECKPOINT_OPTIONS",
"CHECKPOINT_REGISTRY",
"TaskTransition",
"TaskUiState",
"action_buttons_for_checkpoint",
"apply_task_transition",
"build_action_buttons",
"build_chat_actions_payload",
"build_checkpoint_catalog",
"checkpoint_for_task",
"format_actions_directive",
"human_options_for_checkpoint",
"human_options_for_task",
"human_options_for_task_or_checkpoint",
"resolve_task_ui_state",
"ui_state_for_checkpoint",
"upload_req_options_for_task",
"validate_registry",
]
@@ -0,0 +1,74 @@
"""Short canonical names for shipping notice API fields and state machine.
Naming layers (avoid drift):
- CP_* — API `checkpoint` / Dify `flow_ckpt` (see state_machine.CHECKPOINT_REGISTRY)
- RS_* — DB `review_status` where used
- PH_* — DB `pending_human_reason` (may equal CP_* when aligned)
- Button ids / registry — state_machine.py only
- DB state writes — state_machine.py `TaskTransition` / `apply_task_transition` (tools.py only)
"""
from __future__ import annotations
from typing import Any
# HTTP JSON request/response fields
MAP_JSON = "map_json"
SUGGEST_OK = "suggest_ok"
AUTO_MAP = "auto_map"
# Workspace / Hxops chat fallback only — Dify Agent 主路径应调 auto_progress,勿在画布 HTTP 传此字段
AUTO_CHAIN_FALLBACK = "auto_chain_fallback"
# Legacy request field names (read-only compat)
MAP_JSON_LEGACY = "column_mapping_json"
# Checkpoints (tool_response.checkpoint; canonical ids — register buttons in state_machine.py)
CP_ALIGN_REVIEW = "align_review"
CP_MAP_INFER = "map_infer"
CP_UPLOAD_REQ = "upload_req"
CP_MAP_OK = "map_ok"
CP_PARSE_OK = "parse_ok"
CP_PARSE_REVIEW = "parse_review"
CP_TASK_EXISTS = "task_exists"
CP_RSV_REQ = "rsv_req"
CP_UPLOAD_FAILED = "upload_failed"
CP_WAITING_UPLOAD = "waiting_upload"
CP_REJECTED = "rejected"
# Derived UI checkpoints (no separate pending_human_reason; from process_status)
CP_INVENTORY_PENDING = "inventory_pending"
CP_READY_MATCH = "ready_to_match"
CP_READY_EXPORT = "ready_to_export"
CP_EXPORT_READY = "export_ready"
CP_NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed"
CP_EXPORT_GENERATED = "export_generated"
CP_UPLOADED = "uploaded"
CP_COMPLETED = "completed"
# review_status
RS_ALIGN_REVIEW = "align_review"
RS_PARSE_REVIEW = "parse_review"
RS_SHORTAGE_REVIEW = "shortage_review"
RS_RSV_REQ = "rsv_req"
RS_REJECTED = "rejected"
RS_CONFIRMED = "confirmed"
# pending_human_reason (internal; shortened)
PH_ALIGN_REVIEW = CP_ALIGN_REVIEW
PH_MAP_INFER = CP_MAP_INFER
PH_LOW_CONF = "low_confidence"
PH_RSV_REQ = CP_RSV_REQ
PH_SHORTAGE = "shortage"
PH_RPA_EXHAUSTED = "rpa_exhausted"
PH_RPA_PENDING = "rpa_pending"
PH_INV_UNAVAIL = "inv_unavail"
PH_UPLOAD_RPA_FAILED = "upload_rpa_failed"
PH_UPLOAD_RPA_PENDING = "upload_rpa_pending"
def payload_map_json(payload: dict[str, Any]) -> Any:
raw = payload.get(MAP_JSON)
if raw is None:
raw = payload.get(MAP_JSON_LEGACY)
if raw is None:
raw = payload.get("field_mapping")
return raw
@@ -0,0 +1,26 @@
from __future__ import annotations
from flask import current_app
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
# Dify Chatflow input variable names — must match canvas Start / 输入变量配置.
HXOPS_TOOL_API_BASE_INPUT = "hxops_tool_api_base"
HXOPS_TOOL_API_KEY_INPUT = "hxops_tool_api_key"
def is_shipping_notice_chat_agent(agent) -> bool:
return getattr(agent, "name", None) == CHAT_AGENT_NAME
def build_dify_chat_inputs() -> dict[str, str]:
"""Build Dify chat API inputs so HTTP nodes can reference env-specific hxops URLs."""
base = resolve_tool_api_base_url()
key = str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip()
inputs: dict[str, str] = {}
if base:
inputs[HXOPS_TOOL_API_BASE_INPUT] = base
if key:
inputs[HXOPS_TOOL_API_KEY_INPUT] = key
return inputs
@@ -0,0 +1,263 @@
from __future__ import annotations
from datetime import datetime
from pathlib import Path
from shutil import copy2
from typing import Any
from flask import current_app
from openpyxl import Workbook, load_workbook
from app.models import ShippingTask
from app.path_utils import backend_dir, resolve_backend_relative_path
DEFAULT_HEADERS = [
"客户名称",
"客户代码",
"收货地址",
"要求交期",
"料号",
"发货数量",
"单位",
"备注",
]
HEADER_SHEET = "PVMI Pull Request Header"
DETAIL_SHEET = "PVMI Pull Request Detail"
DATA_START_ROW = 4
def _storage_root() -> Path:
root = str(current_app.config.get("SHIPPING_NOTICE_STORAGE_ROOT") or "").strip()
if root:
return Path(resolve_backend_relative_path(root))
return Path(current_app.instance_path) / "shipping_notice"
def _default_template_path() -> Path | None:
configured = str(current_app.config.get("FREIGHT_SHIPMENT_TEMPLATE_PATH") or "").strip()
if configured:
path = Path(resolve_backend_relative_path(configured))
if path.is_file():
return path
bundled = backend_dir() / "templates" / "freight_shipment_upload.xlsx"
return bundled if bundled.is_file() else None
def _is_pvmi_workbook(wb) -> bool:
return HEADER_SHEET in wb.sheetnames and DETAIL_SHEET in wb.sheetnames
def _format_delivery_date(value: Any) -> str:
text = str(value or "").strip()
if not text:
return ""
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%d/%m/%Y", "%m/%d/%Y", "%Y%m%d"):
try:
parsed = datetime.strptime(text[:10], fmt)
return parsed.strftime("%m/%d/%Y")
except ValueError:
continue
if len(text) >= 10 and text[4] == "-" and text[7] == "-":
try:
parsed = datetime.strptime(text[:10], "%Y-%m-%d")
return parsed.strftime("%m/%d/%Y")
except ValueError:
pass
return text
def _delivery_date_for_task(task: ShippingTask) -> str:
if task.required_date:
formatted = _format_delivery_date(task.required_date)
if formatted:
return formatted
for line in task.lines_json or []:
if not isinstance(line, dict):
continue
formatted = _format_delivery_date(line.get("required_date"))
if formatted:
return formatted
return ""
def _resolve_odm_id(task: ShippingTask) -> str:
notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)]
inventory_lines = [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)]
if not inventory_lines:
return ""
inv_by_key: dict[tuple[str, str], dict[str, Any]] = {}
for row in inventory_lines:
key = (
str(row.get("sku") or "").strip(),
str(row.get("reservation_id") or "").strip(),
)
inv_by_key[key] = row
for line in notice_lines:
key = (
str(line.get("sku") or "").strip(),
str(line.get("reservation_id") or "").strip(),
)
matched = inv_by_key.get(key)
if matched:
odm_id = str(matched.get("odm_id") or "").strip()
if odm_id:
return odm_id
for row in inventory_lines:
odm_id = str(row.get("odm_id") or "").strip()
if odm_id:
return odm_id
return ""
def _line_po_number(task: ShippingTask, line: dict[str, Any]) -> str:
for value in (line.get("po_number"), task.po_number):
text = str(value or "").strip()
if text:
return text
return ""
def _line_currency(task: ShippingTask, line: dict[str, Any]) -> str:
for value in (line.get("currency"), getattr(task, "currency", None)):
text = str(value or "").strip().upper()
if text:
return text
return ""
def _line_vendor_part_number(line: dict[str, Any]) -> str:
return str(line.get("vendor_part_number") or "").strip()
def _clear_sheet_data_rows(ws, *, from_row: int = DATA_START_ROW) -> None:
if ws.max_row < from_row:
return
for row_idx in range(from_row, ws.max_row + 1):
for col_idx in range(1, ws.max_column + 1):
ws.cell(row_idx, col_idx).value = None
def _fill_pvmi_template(task: ShippingTask, path: Path) -> None:
wb = load_workbook(filename=str(path))
header_ws = wb[HEADER_SHEET]
detail_ws = wb[DETAIL_SHEET]
_clear_sheet_data_rows(detail_ws)
_clear_sheet_data_rows(header_ws, from_row=DATA_START_ROW)
if header_ws.cell(DATA_START_ROW, 1).value in (None, ""):
header_ws.cell(DATA_START_ROW, 1).value = "AWSDU"
if header_ws.cell(DATA_START_ROW, 2).value in (None, ""):
header_ws.cell(DATA_START_ROW, 2).value = "n"
if header_ws.cell(DATA_START_ROW, 3).value in (None, ""):
header_ws.cell(DATA_START_ROW, 3).value = "WEL"
if header_ws.cell(DATA_START_ROW, 4).value in (None, ""):
header_ws.cell(DATA_START_ROW, 4).value = "normal"
header_ws.cell(DATA_START_ROW, 5).value = _delivery_date_for_task(task)
header_ws.cell(DATA_START_ROW, 6).value = _resolve_odm_id(task)
header_ws.cell(DATA_START_ROW, 7).value = task.task_no
notice_lines = [line for line in (task.lines_json or []) if isinstance(line, dict)]
if not notice_lines:
notice_lines = [{}]
for index, line in enumerate(notice_lines, start=1):
row_idx = DATA_START_ROW + index - 1
line_no = str(line.get("line_no") or index).strip()
qty = line.get("qty")
amount = line.get("amount")
detail_ws.cell(row_idx, 1).value = task.task_no
detail_ws.cell(row_idx, 2).value = line_no
detail_ws.cell(row_idx, 4).value = _line_vendor_part_number(line)
detail_ws.cell(row_idx, 5).value = qty if qty is not None else ""
detail_ws.cell(row_idx, 7).value = _line_po_number(task, line)
detail_ws.cell(row_idx, 10).value = amount if amount is not None else ""
detail_ws.cell(row_idx, 11).value = _line_currency(task, line)
wb.save(path)
def _row_values(task: ShippingTask, line: dict | None) -> list:
line = line or {}
return [
task.customer_name or "",
task.customer_code or "",
task.ship_to or "",
task.required_date or "",
line.get("sku") or "",
line.get("qty") or "",
line.get("uom") or "EA",
line.get("remark") or "",
]
def _fill_legacy_template(task: ShippingTask, path: Path) -> None:
wb = load_workbook(filename=str(path))
ws = wb.active
lines = task.lines_json or [None]
if ws.max_row == 1 and not any(ws.cell(1, c).value for c in range(1, 9)):
ws.append(DEFAULT_HEADERS)
for line in lines:
ws.append(_row_values(task, line))
wb.save(path)
def _fill_blank_workbook(task: ShippingTask, path: Path) -> None:
wb = Workbook()
ws = wb.active
ws.title = "Shipment"
ws.append(DEFAULT_HEADERS)
lines = task.lines_json or [None]
for line in lines:
ws.append(_row_values(task, line))
wb.save(path)
def _sanitize_filename(name: str) -> str:
cleaned = "".join(ch for ch in (name or "") if ch.isalnum() or ch in {"-", "_", "."})
return cleaned or "shipment.xlsx"
def _export_filename(task: ShippingTask, ts: str) -> str:
pattern = str(current_app.config.get("SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN") or "").strip()
if not pattern:
pattern = "shipment_{task_no}_{ts}.xlsx"
try:
name = pattern.format(task_no=task.task_no, ts=ts, date=ts[:8])
except Exception:
name = f"shipment_{task.task_no}_{ts}.xlsx"
if not str(name).lower().endswith(".xlsx"):
name = f"{name}.xlsx"
return _sanitize_filename(str(name))
def generate_shipment_excel(task: ShippingTask) -> tuple[str, str]:
root = _storage_root() / "exports"
root.mkdir(parents=True, exist_ok=True)
ts = datetime.utcnow().strftime("%Y%m%d%H%M%S")
filename = _export_filename(task, ts)
path = root / filename
template = _default_template_path()
if template:
copy2(template, path)
wb = load_workbook(filename=str(path), read_only=True)
try:
is_pvmi = _is_pvmi_workbook(wb)
finally:
wb.close()
if is_pvmi:
_fill_pvmi_template(task, path)
else:
_fill_legacy_template(task, path)
else:
_fill_blank_workbook(task, path)
return str(path), filename
@@ -0,0 +1,121 @@
from __future__ import annotations
import re
from typing import Any
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.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,
)
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 = 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
completeness = notice_parse_completeness(lines)
confidence = min(base_confidence, 0.95) * (0.5 + 0.5 * completeness) if lines else base_confidence * 0.5
return parsed, round(confidence, 4), warnings
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),
raw_text=str(structured.get("raw_text") or ""),
)
heuristic, confidence, heuristic_warnings = _heuristic_extract(raw_text)
warnings.extend(heuristic_warnings)
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]]:
text = str(raw_text or "").strip()
warnings: list[str] = []
customer_name = ""
m = re.search(r"客户[::]\s*(\S+)", text)
if m:
customer_name = m.group(1)
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,
"customer_code": "",
"ship_to": "",
"required_date": "",
"lines": lines,
"confidence": 0.72,
},
0.72,
warnings,
)
lines = []
for m in re.finditer(r"([A-Za-z0-9\-_]{3,})\s*[xX×*]\s*(\d+(?:\.\d+)?)", text):
lines.append({"sku": m.group(1), "qty": float(m.group(2)), "uom": "EA"})
# 尝试纯数字 Reservation ID + SKU + Qty 的自由文本模式(如 1000140351 10-40594-001 2)
if not lines:
for m in re.finditer(
r"(?P<resv>\d{8,12})\s+([A-Za-z0-9\-_]{3,})\s+(\d+(?:\.\d+)?)",
text,
):
lines.append(
{
"reservation_id": m.group("resv"),
"sku": m.group(2),
"qty": float(m.group(3)),
"uom": "EA",
}
)
if not lines:
warnings.append("heuristic_no_lines_detected")
confidence = 0.5 if lines else 0.3
return (
{
"customer_name": customer_name,
"customer_code": "",
"ship_to": "",
"required_date": "",
"lines": lines,
"confidence": confidence,
},
confidence,
warnings,
)
@@ -0,0 +1,178 @@
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.i18n import resolve_lang, t
def _cell(value: Any) -> str:
text = str(value or "").strip()
return text if text else "-"
def _fmt_qty(qty: Any) -> str:
if qty is None or qty == "":
return "-"
try:
num = float(qty)
except (TypeError, ValueError):
return _cell(qty)
return str(int(num)) if num == int(num) else f"{num:g}"
def _mapping_source_column(field_alignment: dict[str, Any], key: str) -> str:
inv_columns = field_alignment.get("inventory_columns")
if not isinstance(inv_columns, dict):
return "-"
mapping = inv_columns.get("mapping")
if not isinstance(mapping, dict):
return "-"
entry = mapping.get(key)
if isinstance(entry, dict):
value = _cell(entry.get("source_column"))
return f"`{value}`" if value != "-" else value
return "-"
def _normalize_warning(text: str, *, lang: str) -> str:
raw = str(text or "").strip()
if not raw:
return raw
lower = raw.lower()
prefix_1 = "parsed with mapping from uploaded file:"
prefix_2 = "parsed from uploaded file:"
if lower.startswith(prefix_1):
filename = raw[len(prefix_1) :].strip()
if lang == "en":
return f"Parsed from uploaded inventory file with mapping: {filename}"
if lang == "th":
return f"แยกข้อมูลจากไฟล์สต็อกที่อัปโหลด (พร้อมการจับคู่คอลัมน์): {filename}"
return f"已按映射解析上传的库存文件:{filename}"
if lower.startswith(prefix_2):
filename = raw[len(prefix_2) :].strip()
if lang == "en":
return f"Parsed from uploaded inventory file: {filename}"
if lang == "th":
return f"แยกข้อมูลจากไฟล์สต็อกที่อัปโหลด: {filename}"
return f"已解析上传的库存文件:{filename}"
return raw
def _format_sample_lines(field_alignment: dict[str, Any], *, lang: str) -> list[str]:
parts: list[str] = []
notice_lines = field_alignment.get("sample_notice_lines") or []
inventory_lines = field_alignment.get("sample_inventory_lines") or []
if notice_lines:
parts.append(t("align.sample.notice", lang=lang))
for index, line in enumerate(notice_lines[:3], 1):
if not isinstance(line, dict):
continue
parts.append(
f"{index}. {t('field.reservation_id', lang=lang)} {_cell(line.get('reservation_id'))} | {t('field.sku', lang=lang)} {_cell(line.get('sku'))} | {t('field.qty', lang=lang)} {_fmt_qty(line.get('qty'))}"
)
if inventory_lines:
if parts:
parts.append("")
parts.append(t("align.sample.inventory", lang=lang))
for index, line in enumerate(inventory_lines[:3], 1):
if not isinstance(line, dict):
continue
parts.append(
f"{index}. {t('field.reservation_id', lang=lang)} {_cell(line.get('reservation_id'))} | {t('field.sku', lang=lang)} {_cell(line.get('sku'))} | {t('field.available_qty', lang=lang)} {_fmt_qty(line.get('available_qty'))}"
)
return parts
def format_field_alignment_summary(
*,
task_no: str,
field_alignment: dict[str, Any],
inventory_row_count: int | None = None,
notice_line_count: int | None = None,
warnings: list[Any] | None = None,
lang: str | None = None,
payload: dict[str, Any] | None = None,
) -> str:
"""Fixed Markdown summary for apply_inventory_mapping / field alignment review."""
resolved = resolve_lang(payload) if payload is not None else resolve_lang({"lang": lang} if lang else None)
inv_count = inventory_row_count
if inv_count is None:
inv_count = field_alignment.get("inventory_row_count")
notice_count = notice_line_count
if notice_count is None:
notice_count = field_alignment.get("notice_line_count")
match_rule = _cell(field_alignment.get("match_rule"))
match_rule_source = str(field_alignment.get("match_rule_source") or "").strip()
source_note = ""
if match_rule_source == "llm":
source_note = t("align.source.llm", lang=resolved)
elif match_rule_source == "fallback":
source_note = t("align.source.fallback", lang=resolved)
elif match_rule_source:
source_note = t("align.source.other", lang=resolved).format(source=match_rule_source)
parts = [
t("align.title", lang=resolved).format(task_no=task_no),
"",
t("align.match_rule", lang=resolved).format(rule=match_rule, note=source_note),
"",
f"| {t('align.table.sys_field', lang=resolved)} | {t('align.table.inv_col', lang=resolved)} | {t('align.table.notice_field', lang=resolved)} |",
"|---------|--------------|---------|",
f"| {t('field.reservation_id', lang=resolved)} | {_mapping_source_column(field_alignment, 'reservation_id')} | {t('field.reservation_id', lang=resolved)} |",
f"| {t('field.aws_sku', lang=resolved)} | {_mapping_source_column(field_alignment, 'sku')} | {t('field.sku', lang=resolved)} |",
f"| {t('field.available_qty', lang=resolved)} | {_mapping_source_column(field_alignment, 'available_qty')} | {t('field.qty', lang=resolved)} |",
f"| — | — | {t('align.table.display_only', lang=resolved)} |",
]
if inv_count is not None or notice_count is not None:
parts.append("")
stat_bits = []
if notice_count is not None:
if resolved == "en":
stat_bits.append(f"Order {notice_count} rows")
elif resolved == "th":
stat_bits.append(f"คำสั่งซื้อ {notice_count} แถว")
else:
stat_bits.append(f"订单 {notice_count} 行")
if inv_count is not None:
if resolved == "en":
stat_bits.append(f"Inventory {inv_count} rows")
elif resolved == "th":
stat_bits.append(f"สต็อก {inv_count} แถว")
else:
stat_bits.append(f"库存 {inv_count} 行")
if stat_bits:
sep = "; " if resolved == "en" else ";"
parts.append(t("align.stats", lang=resolved).format(stats=sep.join(stat_bits)))
sample_lines = _format_sample_lines(field_alignment, lang=resolved)
if sample_lines:
parts.append("")
parts.extend(sample_lines)
warn_items = [str(w).strip() for w in (warnings or []) if str(w).strip()]
for item in field_alignment.get("warnings") or []:
text = str(item).strip()
if text and text not in warn_items:
warn_items.append(text)
if warn_items:
parts.append("")
parts.append(t("common.tips", lang=resolved))
for warning in warn_items[:8]:
parts.append(f"- {_normalize_warning(warning, lang=resolved)}")
parts.extend(
[
"",
t("align.confirm", lang=resolved),
t("align.hint", lang=resolved),
]
)
hint_btn = t("align.hint_btn", lang=resolved).strip()
if hint_btn:
parts.append(hint_btn)
return "\n".join(parts).strip()
@@ -0,0 +1,208 @@
from __future__ import annotations
from typing import Any
from flask import has_request_context, request
SUPPORTED_LANGS = ("zh", "en", "th")
_MESSAGES: dict[str, dict[str, str]] = {
"zh": {
"parse.title": "【发货通知解析确认】任务编号:{task_no}",
"parse.no_lines": "未解析到订单明细行,请重新上传或重新解析。",
"parse.low_conf": "解析置信度较低,请重点核对料号、预订单号、数量、单价与金额。",
"parse.confirm": "请确认以上信息是否正确?",
"parse.hint": "回复「确认」进入库存检查;「重新解析」重试;「驳回」终止本任务。",
"parse.hint_btn": "",
"align.title": "【库存字段对齐确认 — 确认后再匹配】任务编号:{task_no}",
"align.match_rule": "匹配规则:{rule}{note}",
"align.table.sys_field": "系统字段",
"align.table.inv_col": "库存 Excel 列",
"align.table.notice_field": "订单字段",
"align.table.display_only": "unit_price / amount(展示用,不参与匹配)",
"align.sample.notice": "订单样例:",
"align.sample.inventory": "库存样例:",
"align.stats": "统计:{stats}",
"align.source.llm": "(LLM 推断)",
"align.source.fallback": "(后端动态兜底)",
"align.source.other": "({source})",
"align.confirm": "请确认以上字段对齐是否正确。",
"align.hint": "回复「确认」进入匹配;「更正映射」重选列;「重新上传」换库存文件;「驳回」终止本任务。",
"align.hint_btn": "",
"common.tips": "提示:",
"table.field": "字段",
"table.value": "值",
"field.po": "采购单号",
"field.sku": "料号",
"field.reservation_id": "预订单号",
"field.qty": "数量",
"field.unit_price": "单价",
"field.amount": "金额",
"field.required_date": "需求日期",
"field.ship_to": "收货方",
"field.vendor_part_number": "供应商料号",
"field.line_no": "项次",
"field.available_qty": "可用数量",
"field.aws_sku": "料号",
"match.title": "【库存匹配结果】任务编号:{task_no}",
"match.subtitle": "匹配明细(订单数量 vs 库存可用量)",
"match.col.order_qty": "订单需求",
"match.col.inv_qty": "库存可用",
"match.col.gap": "缺口",
"match.col.status": "状态",
"match.status.ok": "✅ 充足",
"match.status.partial": "⚠️ 部分满足",
"match.status.shortage": "❌ 不足",
"match.status.unknown": "未知",
"match.conclusion.fulfillable": "**结论**:库存充足,可生成发货 Excel 并上传货代系统。",
"match.conclusion.partial": "**结论**:部分行库存不足,请复核缺口后决定是否部分发货。",
"match.conclusion.unfulfillable": "**结论**:库存均不足,无法整单发货。",
"match.conclusion.other": "**结论**:match_status={status}",
"match.no_lines": "无订单明细,无法比对数量。",
},
"en": {
"parse.title": "[Shipping notice parsed] Task: {task_no}",
"parse.no_lines": "No order lines found. Please re-upload or re-parse.",
"parse.low_conf": "Low confidence. Please double-check SKU, Qty, Reservation ID, Unit Price and Amount.",
"parse.confirm": "Please confirm the above information.",
"parse.hint": 'Reply "Confirm" to proceed; "Re-parse" to retry; "Reject" to stop this task.',
"parse.hint_btn": "",
"align.title": "[Inventory mapping confirmation] Task: {task_no}",
"align.match_rule": "Match rule: {rule}{note}",
"align.table.sys_field": "System field",
"align.table.inv_col": "Inventory column",
"align.table.notice_field": "Order field",
"align.table.display_only": "unit_price / amount (display only)",
"align.sample.notice": "Order samples:",
"align.sample.inventory": "Inventory samples:",
"align.stats": "Stats: {stats}",
"align.source.llm": " (LLM)",
"align.source.fallback": " (backend fallback)",
"align.source.other": " ({source})",
"align.confirm": "Please confirm the field alignment above.",
"align.hint": 'Reply "Confirm" to match; "Fix mapping" to reselect columns; "Re-upload" to change the inventory file; "Reject" to stop.',
"align.hint_btn": "",
"common.tips": "Notes:",
"table.field": "Field",
"table.value": "Value",
"field.po": "PO",
"field.sku": "SKU",
"field.reservation_id": "Reservation ID",
"field.qty": "Qty",
"field.unit_price": "Unit Price",
"field.amount": "Amount",
"field.required_date": "Required date",
"field.ship_to": "Ship to",
"field.vendor_part_number": "Vendor PN",
"field.line_no": "Line",
"field.available_qty": "Available qty",
"field.aws_sku": "AWS Sku",
"match.title": "[Inventory match result] Task: {task_no}",
"match.subtitle": "Match details (order qty vs inventory available)",
"match.col.order_qty": "Order qty",
"match.col.inv_qty": "Available",
"match.col.gap": "Gap",
"match.col.status": "Status",
"match.status.ok": "✅ OK",
"match.status.partial": "⚠️ Partial",
"match.status.shortage": "❌ Short",
"match.status.unknown": "Unknown",
"match.conclusion.fulfillable": "**Result**: Inventory is sufficient. You may generate the shipment Excel and upload.",
"match.conclusion.partial": "**Result**: Some lines are short. Review gaps before partial shipment.",
"match.conclusion.unfulfillable": "**Result**: Insufficient inventory for all lines.",
"match.conclusion.other": "**Result**: match_status={status}",
"match.no_lines": "No order lines to compare.",
},
"th": {
"parse.title": "【ยืนยันการแยกใบแจ้งส่งสินค้า】งาน: {task_no}",
"parse.no_lines": "ไม่พบบรรทัดรายการสั่งซื้อ กรุณาอัปโหลดใหม่หรือแยกใหม่อีกครั้ง",
"parse.low_conf": "ความมั่นใจต่ำ กรุณาตรวจสอบ SKU, จำนวน, Reservation ID, ราคาต่อหน่วย และจำนวนเงิน",
"parse.confirm": "กรุณายืนยันว่าข้อมูลด้านบนถูกต้องหรือไม่",
"parse.hint": 'พิมพ์ "ยืนยัน" เพื่อไปต่อ; "แยกใหม่" เพื่อลองใหม่; "ปฏิเสธ" เพื่อยุติงานนี้',
"parse.hint_btn": "",
"align.title": "【ยืนยันการจับคู่คอลัมน์สต็อก】งาน: {task_no}",
"align.match_rule": "กฎการจับคู่: {rule}{note}",
"align.table.sys_field": "ฟิลด์ระบบ",
"align.table.inv_col": "คอลัมน์สต็อก",
"align.table.notice_field": "ฟิลด์คำสั่งซื้อ",
"align.table.display_only": "unit_price / amount (แสดงผลเท่านั้น)",
"align.sample.notice": "ตัวอย่างคำสั่งซื้อ:",
"align.sample.inventory": "ตัวอย่างสต็อก:",
"align.stats": "สถิติ: {stats}",
"align.source.llm": " (LLM)",
"align.source.fallback": " (สำรองโดยระบบ)",
"align.source.other": " ({source})",
"align.confirm": "กรุณายืนยันว่าการจับคู่ฟิลด์ด้านบนถูกต้อง",
"align.hint": 'พิมพ์ "ยืนยัน" เพื่อจับคู่; "แก้ไขการจับคู่" เพื่อเลือกคอลัมน์ใหม่; "อัปโหลดใหม่" เพื่อเปลี่ยนไฟล์สต็อก; "ปฏิเสธ" เพื่อยุติ',
"align.hint_btn": "",
"common.tips": "หมายเหตุ:",
"table.field": "ฟิลด์",
"table.value": "ค่า",
"field.po": "PO",
"field.sku": "SKU",
"field.reservation_id": "Reservation ID",
"field.qty": "จำนวน",
"field.unit_price": "ราคาต่อหน่วย",
"field.amount": "จำนวนเงิน",
"field.required_date": "วันที่ต้องการ",
"field.ship_to": "ผู้รับ",
"field.vendor_part_number": "หมายเลขชิ้นส่วนผู้ขาย",
"field.line_no": "รายการ",
"field.available_qty": "จำนวนคงเหลือ",
"field.aws_sku": "AWS Sku",
"match.title": "【ผลการจับคู่สต็อก】งาน: {task_no}",
"match.subtitle": "รายละเอียดการจับคู่ (จำนวนสั่งซื้อ vs สต็อกคงเหลือ)",
"match.col.order_qty": "จำนวนสั่ง",
"match.col.inv_qty": "สต็อกคงเหลือ",
"match.col.gap": "ส่วนต่าง",
"match.col.status": "สถานะ",
"match.status.ok": "✅ เพียงพอ",
"match.status.partial": "⚠️ บางส่วน",
"match.status.shortage": "❌ ไม่พอ",
"match.status.unknown": "ไม่ทราบ",
"match.conclusion.fulfillable": "**สรุป**: สต็อกเพียงพอ สามารถสร้าง Excel และอัปโหลดได้",
"match.conclusion.partial": "**สรุป**: บางรายการสต็อกไม่พอ กรุณาตรวจสอบส่วนต่าง",
"match.conclusion.unfulfillable": "**สรุป**: สต็อกไม่เพียงพอทั้งหมด",
"match.conclusion.other": "**สรุป**: match_status={status}",
"match.no_lines": "ไม่มีรายการสั่งซื้อสำหรับเปรียบเทียบ",
},
}
def normalize_lang(raw: Any) -> str:
text = str(raw or "").strip().lower()
if not text:
return "zh"
if text in {"zh-cn", "zh_hans", "zh-hans", "cn", "zh"}:
return "zh"
if text in {"en-us", "en_us", "en"}:
return "en"
if text in {"th-th", "th_th", "th"}:
return "th"
for prefix in SUPPORTED_LANGS:
if text.startswith(prefix):
return prefix
return "zh"
def resolve_lang(payload: dict[str, Any] | None = None) -> str:
if isinstance(payload, dict):
for key in ("lang", "locale", "language"):
if key in payload:
val = str(payload.get(key) or "").strip()
if val:
return normalize_lang(val)
if has_request_context():
hdr = str(request.headers.get("X-Lang") or "").strip()
if hdr:
return normalize_lang(hdr)
accept = str(request.headers.get("Accept-Language") or "").strip()
if accept:
return normalize_lang(accept.split(",")[0].strip())
return "zh"
def t(key: str, *, lang: str | None = None) -> str:
resolved = normalize_lang(lang) if lang else "zh"
return _MESSAGES.get(resolved, {}).get(key) or _MESSAGES["zh"].get(key) or key
@@ -0,0 +1,199 @@
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:
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
if not data:
return None
inner = data.get("mapping") if isinstance(data.get("mapping"), dict) else data
if not isinstance(inner, dict):
return None
result: dict[str, str] = {}
for key in SYSTEM_FIELDS:
value = inner.get(key)
if value is None:
continue
text = str(value).strip()
if text:
result[key] = text
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]:
"""Rule-based fallback mapping from header names."""
from app.services.shipping_notice.inventory_snapshot import _column_map, _map_header
col_map = _column_map()
norm_headers = [str(h or "").strip() for h in headers]
lower_index = {h.lower(): h for h in norm_headers if h}
def pick(*candidates: str) -> str | None:
for cand in candidates:
if cand in norm_headers:
return cand
hit = lower_index.get(cand.lower())
if hit:
return hit
for h in norm_headers:
mapped = _map_header(h, col_map)
if mapped in candidates:
return h
return None
mapping: dict[str, str] = {}
sku = pick("sku", "AWS Sku", "AWS SKU", "料号", "Part Number", "Material")
if sku:
mapping["sku"] = sku
reservation = pick(
"reservation_id",
"Reservation ID",
"COM ID",
"Reservation Order",
"Resevation Order",
"Reservation No",
)
if reservation:
mapping["reservation_id"] = reservation
qty = pick("available_qty", "Qty Available", "可用数量", "Available Qty", "On Hand Qty")
if not qty:
qty = pick("qty", "Qty", "数量", "Quantity")
if qty:
mapping["available_qty"] = qty
return mapping
def mapping_is_complete(field_mapping: dict[str, str]) -> bool:
return bool(field_mapping.get("sku") and field_mapping.get("available_qty") and field_mapping.get("reservation_id"))
def validate_field_mapping_against_headers(
headers: list[str],
field_mapping: dict[str, str],
) -> list[str]:
"""Return error messages when mapped column names are missing from headers."""
norm_headers = [str(h or "").strip() for h in headers]
lower_set = {h.lower() for h in norm_headers if h}
errors: list[str] = []
labels = {
"sku": "sku",
"reservation_id": "reservation_id",
"available_qty": "available_qty",
}
for key, label in labels.items():
name = str(field_mapping.get(key) or "").strip()
if not name:
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:
preview = ", ".join(norm_headers[:8])
if len(norm_headers) > 8:
preview += "..."
errors.append(f'列名 "{name}" 不在表头中(当前表头: {preview})')
return errors
def resolve_columns_from_field_mapping(
headers: list[str],
field_mapping: dict[str, str],
) -> dict[str, int | None]:
"""Map system fields to column indexes using explicit header names."""
from app.services.shipping_notice.inventory_snapshot import DEFAULT_COLUMN_MAP, _resolve_inventory_columns
norm_headers = [str(h or "").strip() for h in headers]
lower_to_idx = {h.lower(): i for i, h in enumerate(norm_headers) if h}
def idx_for(header_name: str | None) -> int | None:
if not header_name:
return None
name = str(header_name).strip()
if not name:
return None
if name in norm_headers:
return norm_headers.index(name)
return lower_to_idx.get(name.lower())
# Keep auto-detected optional columns (e.g. odm_id / qty) even when the
# required mapping is provided explicitly by LLM or user.
columns = _resolve_inventory_columns(norm_headers, DEFAULT_COLUMN_MAP)
columns.update({
"sku": idx_for(field_mapping.get("sku")),
"reservation_id": idx_for(field_mapping.get("reservation_id")),
"available_qty": None,
})
avail_header = field_mapping.get("available_qty")
if avail_header:
columns["available_qty"] = idx_for(avail_header)
return columns
def build_column_meta_from_mapping(
headers: list[str],
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)
def source_column(index: int | None) -> str | None:
if index is None or index >= len(headers):
return None
text = str(headers[index] or "").strip()
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,
"field_mapping": dict(field_mapping),
"mapping": {
"sku": {
"system_field": "sku",
"label": "AWS Sku / 料号",
"source_column": source_column(columns.get("sku")),
},
"reservation_id": {
"system_field": "reservation_id",
"label": "Reservation ID",
"source_column": source_column(columns.get("reservation_id")),
},
"available_qty": {
"system_field": "available_qty",
"label": "可用数量",
"source_column": qty_header or source_column(columns.get("available_qty")),
"qty_preference": "available_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
@@ -0,0 +1,622 @@
from __future__ import annotations
import json
import re
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
from openpyxl import load_workbook
from app.services.shipping_notice.reservation_id import extract_reservation_id, normalize_reservation_id
# 默认列映射:含 AWS DUB On Hand Inventory 模板(AWS Sku / Reservation ID / Qty)
DEFAULT_COLUMN_MAP = {
# SKU
"料号": "sku",
"SKU": "sku",
"sku": "sku",
"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",
"reservation_id": "reservation_id",
"COM ID": "reservation_id",
"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",
# ODM
"ODM ID": "odm_id",
"ODM Id": "odm_id",
"ODM Code": "odm_id",
"Ship to ODM Code": "odm_id",
"Ship To ODM Code": "odm_id",
}
_RESERVATION_HEADER_PRIORITY = (
"reservation_id",
"Reservation ID",
"COM ID",
"Reservation Order",
)
def _column_map() -> dict[str, str]:
raw = current_app.config.get("FREIGHT_INVENTORY_COLUMN_MAP")
if isinstance(raw, dict) and raw:
return {str(k): str(v) for k, v in raw.items()}
if isinstance(raw, str) and raw.strip():
try:
parsed = json.loads(raw)
if isinstance(parsed, dict):
return {str(k): str(v) for k, v in parsed.items()}
except json.JSONDecodeError:
pass
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:
return None
if text in col_map:
return col_map[text]
lower = text.lower()
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
def _resolve_inventory_columns(headers: list[str], col_map: dict[str, str]) -> dict[str, int | None]:
idx_sku = idx_reservation = idx_available = idx_qty = idx_odm = None
for i, h in enumerate(headers):
mapped = _map_header(h, col_map)
if mapped == "sku" and idx_sku is None:
idx_sku = i
elif mapped == "reservation_id" and idx_reservation is None:
idx_reservation = i
elif mapped == "available_qty" and idx_available is None:
idx_available = i
elif mapped == "qty" and idx_qty is None:
idx_qty = i
elif mapped == "odm_id" and idx_odm is None:
idx_odm = i
# 若 reservation 列未命中,按 AWS 模板常见列名再试
if idx_reservation is None:
for i, h in enumerate(headers):
norm = str(h or "").strip().lower()
if norm in {"com id", "reservation order", "reservation id"}:
idx_reservation = i
break
return {
"sku": idx_sku,
"reservation_id": idx_reservation,
"available_qty": idx_available,
"qty": idx_qty,
"odm_id": idx_odm,
}
def _cell(row: list[Any] | tuple[Any, ...], index: int | None) -> Any:
if index is None or index >= len(row):
return None
return row[index]
def _parse_qty(value: Any) -> float:
try:
return float(str(value).replace(",", "").strip())
except (TypeError, ValueError):
return 0.0
def _normalize_inventory_row(
row: list[Any] | tuple[Any, ...],
columns: dict[str, int | None],
*,
default_sku_index: int = 0,
default_qty_index: int = 1,
) -> dict[str, Any] | None:
idx_sku = columns.get("sku")
if idx_sku is None:
idx_sku = default_sku_index
sku = str(_cell(row, idx_sku) or "").strip()
if not sku:
return None
skip_tokens = {
"sku",
"料号",
"aws sku",
"qty",
"qty available",
"可用数量",
"reservation id",
"com id",
}
if sku.lower() in skip_tokens:
return None
reservation_id = ""
idx_res = columns.get("reservation_id")
if idx_res is not None:
reservation_id = extract_reservation_id(_cell(row, idx_res))
idx_avail = columns.get("available_qty")
idx_qty = columns.get("qty")
if idx_avail is not None:
available_qty = _parse_qty(_cell(row, idx_avail))
elif idx_qty is not None:
available_qty = _parse_qty(_cell(row, idx_qty))
else:
available_qty = _parse_qty(_cell(row, default_qty_index))
parsed: dict[str, Any] = {
"sku": sku,
"available_qty": available_qty,
}
if reservation_id:
parsed["reservation_id"] = reservation_id
idx_odm = columns.get("odm_id")
if idx_odm is not None:
odm_id = str(_cell(row, idx_odm) or "").strip()
if odm_id:
parsed["odm_id"] = odm_id
return parsed
def _score_header_candidate(cells: list[Any]) -> int:
"""Score how likely a row is the inventory column header (not a title row)."""
headers = [str(c or "").strip() for c in cells]
non_empty = [h for h in headers if h]
if len(non_empty) < 2:
return 0
col_map = _column_map()
mapped_fields: set[str] = set()
for h in headers:
mapped = _map_header(h, col_map)
if mapped:
mapped_fields.add(mapped)
score = len(mapped_fields) * 10
if "sku" in mapped_fields and ("available_qty" in mapped_fields or "qty" in mapped_fields):
score += 30
return score
def find_inventory_header_row_index(rows: list[list[Any]], *, max_scan: int = 40) -> int:
"""Pick the row that best matches known inventory column names (skip title rows)."""
best_idx = 0
best_score = 0
for i, row in enumerate(rows[:max_scan]):
score = _score_header_candidate(list(row))
if score > best_score:
best_score = score
best_idx = i
return best_idx if best_score > 0 else 0
def _load_excel_rows(path: Path, *, max_rows: int | None = None) -> tuple[list[list[Any]], int]:
"""Load worksheet rows; returns (rows, total_row_count_hint)."""
wb = load_workbook(filename=str(path), data_only=True, read_only=True)
try:
ws = wb.active
rows: list[list[Any]] = []
for i, row in enumerate(ws.iter_rows(values_only=True)):
if max_rows is not None and i >= max_rows:
break
rows.append(list(row))
total = ws.max_row or len(rows)
finally:
wb.close()
return rows, int(total)
def _rows_from_table_text(raw_text: str) -> list[list[str]]:
rows: list[list[str]] = []
for line in raw_text.splitlines():
stripped = line.strip()
if not stripped or re.match(r"^[\|\-\s]+$", stripped) or stripped.startswith("#"):
continue
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"[,,;;]+", stripped) if c.strip()]
if cells:
rows.append(cells)
return rows
from app.services.shipping_notice.notice_lines import NOTICE_FIELD_LABELS
def describe_inventory_columns(
headers: list[str],
*,
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,
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)
def source_column(index: int | None) -> str | None:
if index is None or index >= len(headers):
return None
text = str(headers[index] or "").strip()
return text or None
qty_source = source_column(columns.get("available_qty"))
qty_note = "Qty Available"
if not qty_source:
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": sku_src,
},
"reservation_id": {
"system_field": "reservation_id",
"label": "Reservation ID",
"source_column": rid_src,
"alternatives": list(_RESERVATION_HEADER_PRIORITY),
},
"available_qty": {
"system_field": "available_qty",
"label": "可用数量",
"source_column": qty_source,
"qty_preference": qty_note,
},
},
"match_key": match_key,
"match_rule": match_rule,
"match_rule_source": match_rule_source,
}
def build_field_alignment_preview(
inventory_lines: list[dict[str, Any]],
notice_lines: list[dict[str, Any]],
*,
column_meta: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Preview for human confirmation before match_inventory."""
warnings: list[str] = []
mapping = column_meta or {}
inv_mapping = mapping.get("mapping") if isinstance(mapping.get("mapping"), dict) else {}
order_has_reservation = any(str(line.get("reservation_id") or "").strip() for line in notice_lines)
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 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")
if notice_lines and inventory_lines and not sku_source:
warnings.append("库存表未识别到 AWS Sku 列,当前按第一列作为料号解析。")
qty_source = (inv_mapping.get("available_qty") or {}).get("source_column")
if inventory_lines and not qty_source:
warnings.append("库存表未识别 Qty Available / Qty 列,请核对数量列映射。")
notice_preview = [
{
"sku": str(line.get("sku") or "").strip(),
"reservation_id": str(line.get("reservation_id") or "").strip(),
"qty": line.get("qty"),
"unit_price": line.get("unit_price"),
"amount": line.get("amount"),
}
for line in notice_lines[:5]
]
sample_inventory = [
{
"sku": line.get("sku"),
"reservation_id": line.get("reservation_id", ""),
"available_qty": line.get("available_qty"),
}
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": match_rule,
"match_rule_source": mapping.get("match_rule_source"),
"inventory_columns": mapping,
"notice_fields": NOTICE_FIELD_LABELS,
"sample_notice_lines": notice_preview,
"sample_inventory_lines": sample_inventory,
"inventory_row_count": len(inventory_lines),
"notice_line_count": len(notice_lines),
"warnings": warnings,
}
def parse_inventory_rows(
headers: list[str],
data_rows: list[list[Any]],
*,
field_mapping: dict[str, str] | None = None,
) -> list[dict[str, Any]]:
"""Parse inventory table rows (Excel or document-extractor text)."""
if field_mapping:
from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping
columns = resolve_columns_from_field_mapping(headers, field_mapping)
else:
col_map = _column_map()
columns = _resolve_inventory_columns(headers, col_map)
has_header = columns["sku"] is not None or columns["available_qty"] is not None or columns["qty"] is not None
if not has_header and headers and not field_mapping:
has_header = any(_map_header(h, _column_map()) for h in headers)
lines: list[dict[str, Any]] = []
for row in data_rows:
if not row:
continue
parsed = _normalize_inventory_row(list(row), columns)
if parsed:
lines.append(parsed)
return lines
def parse_inventory_text(
raw_text: str,
*,
field_mapping: dict[str, str] | None = None,
) -> tuple[list[dict[str, Any]], list[str], dict[str, Any]]:
"""Parse inventory from chat text or document-extractor output (Excel/CSV tables)."""
warnings: list[str] = []
empty_meta: dict[str, Any] = {"headers": [], "mapping": {}, "match_key": ["sku", "reservation_id"]}
text = str(raw_text or "").strip()
if not text:
return [], ["empty inventory text"], empty_meta
rows = _rows_from_table_text(text)
if not rows:
return [], ["no table rows detected"], empty_meta
header = rows[0]
if field_mapping:
from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping
has_header = True
column_meta = describe_inventory_columns(
header,
field_mapping=field_mapping,
mapping_source="manual",
)
else:
col_map = _column_map()
columns = _resolve_inventory_columns(header, col_map)
has_header = columns["sku"] is not None or any(_map_header(h, col_map) for h in header)
column_meta = describe_inventory_columns(header) if has_header else empty_meta
data_rows: list[list[Any]] = rows[1:] if has_header else rows
lines = parse_inventory_rows(
header if has_header else [],
data_rows if has_header else rows,
field_mapping=field_mapping,
)
if not lines:
warnings.append("no inventory lines parsed from text")
return lines, warnings, column_meta
def read_inventory_schema_preview(
path: Path,
*,
max_sample_rows: int = 5,
) -> dict[str, Any]:
"""Read headers + sample rows only (safe for LLM context)."""
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
scan_rows, total_rows = _load_excel_rows(path, max_rows=40)
if not scan_rows:
return {
"headers": [],
"sample_rows": [],
"suggested_mapping": {},
"row_count_hint": 0,
"header_row_index": 1,
}
header_idx = find_inventory_header_row_index(scan_rows)
headers = [str(c or "").strip() for c in scan_rows[header_idx]]
sample_rows = [
[str(c) if c is not None else "" for c in r]
for r in scan_rows[header_idx + 1 : header_idx + 1 + max_sample_rows]
]
suggested = suggest_field_mapping(headers)
data_row_count = max(0, total_rows - header_idx - 1)
return {
"headers": headers,
"sample_rows": sample_rows,
"suggested_mapping": suggested,
"header_row_index": header_idx + 1,
"mapping_targets": {
"sku": "料号 / AWS Sku",
"reservation_id": "Reservation ID / COM ID(可选)",
"available_qty": "可用数量 / Qty Available / Qty",
"match_rule": "匹配规则说明(LLM 根据表头与订单字段生成,写入 map_json.match_rule)",
},
"row_count_hint": data_row_count,
}
def parse_inventory_excel_with_meta(
path: Path,
*,
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: 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:
from app.services.shipping_notice.inventory_mapping import suggest_field_mapping
suggested = suggest_field_mapping(headers)
if suggested.get("sku") and suggested.get("available_qty"):
field_mapping = suggested
mapping_source = "rules"
lines = parse_inventory_rows(headers, data_rows, field_mapping=field_mapping)
meta = describe_inventory_columns(
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
def parse_inventory_excel(path: Path) -> list[dict[str, Any]]:
lines, _meta = parse_inventory_excel_with_meta(path)
return lines
def ingest_inventory_file(
source_path: Path,
*,
move_to: Path | None = None,
field_mapping: dict[str, str] | None = None,
mapping_source: str = "rules",
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
lines, column_meta = parse_inventory_excel_with_meta(
source_path,
field_mapping=field_mapping,
mapping_source=mapping_source,
)
if move_to:
move_to.mkdir(parents=True, exist_ok=True)
target = move_to / source_path.name
if target.exists():
target = move_to / f"{source_path.stem}_{datetime.utcnow().strftime('%H%M%S')}{source_path.suffix}"
shutil.move(str(source_path), str(target))
return lines, column_meta
@@ -0,0 +1,69 @@
from __future__ import annotations
import re
from pathlib import Path
from typing import Any
from flask import current_app
from werkzeug.datastructures import FileStorage
from app.services.shipping_notice.export import _storage_root
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
read_inventory_schema_preview,
)
def inventory_text_max_chars() -> int:
try:
return int(current_app.config.get("SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS") or 80000)
except (TypeError, ValueError):
return 80000
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_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_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"未找到任务 {task_no} 的库存上传文件")
preview = read_inventory_schema_preview(path)
preview["upload_filename"] = path.name
return preview
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 = task_inventory_upload_path(task_no)
if not path.is_file():
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_task_inventory(task_no: str) -> bool:
return task_inventory_upload_path(task_no).is_file()
@@ -0,0 +1,187 @@
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.i18n import resolve_lang, t
from app.services.shipping_notice.reservation_id import extract_reservation_id
def _norm(value: Any) -> str:
return str(value or "").strip()
def _norm_reservation(value: Any) -> str:
return extract_reservation_id(value)
def _line_key(sku: str, reservation_id: str | None) -> tuple[str, str]:
return (_norm(sku), _norm_reservation(reservation_id))
def _aggregate_inventory(inventory_lines: list[dict[str, Any]]) -> dict[tuple[str, str], float]:
"""Sum available_qty by (AWS Sku, Reservation ID). Same key rows are aggregated."""
totals: dict[tuple[str, str], float] = {}
for row in inventory_lines:
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, reservation_id)
totals[key] = totals.get(key, 0.0) + qty
return totals
def _available_for_notice_line(
sku: str,
reservation_id: str | None,
inv_totals: dict[tuple[str, str], float],
) -> float:
sku_n = _norm(sku)
rid = _norm_reservation(reservation_id)
if not rid:
return 0.0
return inv_totals.get((sku_n, rid), 0.0)
def match_notice_lines(
notice_lines: list[dict[str, Any]],
inventory_lines: list[dict[str, Any]],
) -> tuple[str, list[dict[str, Any]], dict[str, Any]]:
inv_totals = _aggregate_inventory(inventory_lines)
line_results: list[dict[str, Any]] = []
shortages: list[dict[str, Any]] = []
has_partial = False
has_shortage = False
for line in notice_lines:
sku = _norm(line.get("sku"))
reservation_id = _norm_reservation(line.get("reservation_id")) or None
try:
required = float(line.get("qty") or 0)
except (TypeError, ValueError):
required = 0.0
available = _available_for_notice_line(sku, reservation_id, inv_totals)
if available >= required:
line_status = "ok"
shortage = 0.0
elif available > 0:
line_status = "partial"
shortage = required - available
has_partial = True
else:
line_status = "shortage"
shortage = required
has_shortage = True
result = {
"sku": sku,
"reservation_id": reservation_id or "",
"required_qty": required,
"available_qty": available,
"shortage_qty": shortage,
"line_status": line_status,
}
line_results.append(result)
if shortage > 0:
shortages.append(result)
if not notice_lines:
return "unfulfillable", line_results, {"lines": shortages}
if has_shortage and not has_partial and all(r["line_status"] == "shortage" for r in line_results):
match_status = "unfulfillable"
elif has_partial or has_shortage:
match_status = "partial"
else:
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 _md_cell(value: Any) -> str:
text = str(value or "").strip() or "-"
return text.replace("|", "\\|")
def format_match_summary(
match_status: str,
line_results: list[dict[str, Any]],
*,
task_no: str | None = None,
lang: str | None = None,
) -> str:
"""Fixed Markdown table for match_inventory responses (Agent must display verbatim)."""
resolved = resolve_lang({"lang": lang} if lang else None)
if not line_results:
return t("match.no_lines", lang=resolved)
lines: list[str] = []
if task_no:
lines.append(t("match.title", lang=resolved).format(task_no=task_no))
lines.append("")
lines.append(t("match.subtitle", lang=resolved))
lines.append("")
lines.append(
"| # | "
f"{t('field.reservation_id', lang=resolved)} | "
f"{t('field.sku', lang=resolved)} | "
f"{t('match.col.order_qty', lang=resolved)} | "
f"{t('match.col.inv_qty', lang=resolved)} | "
f"{t('match.col.gap', lang=resolved)} | "
f"{t('match.col.status', lang=resolved)} |"
)
lines.append("|---:|---|---|---:|---:|---:|---|")
status_keys = {
"ok": "match.status.ok",
"partial": "match.status.partial",
"shortage": "match.status.shortage",
}
for index, row in enumerate(line_results, 1):
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 = t(status_keys.get(status, "match.status.unknown"), lang=resolved)
gap_cell = "-" if shortage <= 0 else _fmt_qty(shortage)
lines.append(
"| "
f"{index} | "
f"{_md_cell(row.get('reservation_id'))} | "
f"{_md_cell(row.get('sku'))} | "
f"{_fmt_qty(required)} | "
f"{_fmt_qty(available)} | "
f"{gap_cell} | "
f"{status_label} |"
)
lines.append("")
conclusion_key = f"match.conclusion.{match_status}"
conclusion = t(conclusion_key, lang=resolved)
if conclusion == conclusion_key:
conclusion = t("match.conclusion.other", lang=resolved).format(status=match_status)
lines.append(conclusion)
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 map_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"
@@ -0,0 +1,751 @@
from __future__ import annotations
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",
)
# 订单行表头 → 系统字段(发货通知 PDF/Excel/邮件表格)
NOTICE_COLUMN_MAP: dict[str, str] = {
# SKU
"料号": "sku",
"SKU": "sku",
"sku": "sku",
"AWS Sku": "sku",
"AWS SKU": "sku",
"Part Number": "sku",
"Material": "sku",
"Material No": "sku",
"产品编号": "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",
"qty": "qty",
"Quantity": "qty",
"需求数量": "qty",
"订购数量": "qty",
"Order Qty": "qty",
"Ship Qty": "qty",
"发货数量": "qty",
# 单价
"单价": "unit_price",
"Unit Price": "unit_price",
"unit_price": "unit_price",
"Price": "unit_price",
"Unit Cost": "unit_price",
"价格": "unit_price",
# 金额
"金额": "amount",
"Amount": "amount",
"amount": "amount",
"Total": "amount",
"Line Amount": "amount",
"Line Total": "amount",
"小计": "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",
"reservation_id": "reservation_id",
"COM ID": "reservation_id",
"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",
"uom": "uom",
"Unit": "uom",
}
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 = {
"sku",
"料号",
"aws sku",
"qty",
"quantity",
"数量",
"reservation id",
"com id",
"单价",
"unit price",
"金额",
"amount",
"currency",
"币种",
"line no",
"item no",
"项次",
}
def _norm_header(value: Any) -> str:
return re.sub(r"\s+", " ", str(value or "").strip().lower())
def _map_notice_header(header: str, col_map: dict[str, str] | None = None) -> str | None:
text = str(header or "").strip()
if not text:
return None
mapping = col_map or NOTICE_COLUMN_MAP
if text in mapping:
return mapping[text]
norm = _norm_header(text)
for key, field in mapping.items():
if _norm_header(key) == norm:
return field
return None
def _resolve_notice_columns(headers: list[str]) -> dict[str, int | None]:
columns: dict[str, int | None] = {field: None for field in NOTICE_LINE_FIELDS if field not in {"uom", "remark"}}
for i, header in enumerate(headers):
mapped = _map_notice_header(header)
if mapped and columns.get(mapped) is None:
columns[mapped] = i
# Reservation 列名兜底
if columns.get("reservation_id") is None:
for i, header in enumerate(headers):
norm = _norm_header(header)
if norm in {"com id", "reservation order", "reservation id", "reservation no", "resv id"}:
columns["reservation_id"] = i
break
return columns
def _cell(row: list[Any] | tuple[Any, ...], index: int | None) -> Any:
if index is None or index >= len(row):
return None
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
text = str(value).strip()
if not text:
return 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(match.group(0))
except (TypeError, ValueError):
return None
def _infer_reservation_id_from_row(
row: list[Any] | tuple[Any, ...],
*,
skip_indices: set[int],
) -> str:
for i, cell in enumerate(row):
if i in skip_indices:
continue
if looks_like_reservation_id(cell):
return extract_reservation_id(cell)
return ""
def _parse_notice_row(
row: list[Any] | tuple[Any, ...],
columns: dict[str, int | None],
*,
default_sku_index: int = 0,
default_qty_index: int = 1,
) -> dict[str, Any] | None:
idx_sku = columns.get("sku")
if idx_sku is None:
idx_sku = default_sku_index
sku = str(_cell(row, idx_sku) or "").strip()
if not sku:
return None
if sku.lower() in _HEADER_SKIP_TOKENS:
return None
idx_qty = columns.get("qty")
if idx_qty is not None:
qty = _parse_number(_cell(row, idx_qty))
else:
qty = _parse_number(_cell(row, default_qty_index))
if qty is None or qty <= 0:
return None
parsed: dict[str, Any] = {"sku": sku, "qty": qty, "uom": "EA"}
skip_indices: set[int] = {idx_sku}
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 = 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)
if reservation_id:
parsed["reservation_id"] = reservation_id
idx_price = columns.get("unit_price")
price_cell = None
if idx_price is not None:
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_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)
if computed > 0:
parsed["amount"] = computed
return parsed
def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None:
if not isinstance(raw, dict):
return None
sku = str(raw.get("sku") or raw.get("part_number") or raw.get("material") or "").strip()
if not sku:
return None
qty = _parse_number(raw.get("qty") if raw.get("qty") is not None else raw.get("quantity"))
if qty is None or qty <= 0:
return None
line: dict[str, Any] = {
"sku": sku,
"qty": qty,
"uom": str(raw.get("uom") or "EA").strip() or "EA",
}
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
unit_price = _parse_number(raw.get("unit_price") if raw.get("unit_price") is not None else raw.get("price"))
if unit_price is not None:
line["unit_price"] = unit_price
amount = _parse_number(raw.get("amount") if raw.get("amount") is not None else raw.get("total"))
if amount is not None:
line["amount"] = amount
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
return line
def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]:
if not isinstance(lines, list):
return []
normalized: list[dict[str, Any]] = []
for item in lines:
parsed = normalize_notice_line(item if isinstance(item, dict) else None)
if parsed:
normalized.append(parsed)
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:
return 0
mapped: set[str] = set()
for h in headers:
field = _map_notice_header(h)
if field:
mapped.add(field)
score = len(mapped) * 10
if "sku" in mapped and "qty" in mapped:
score += 30
if "reservation_id" in mapped:
score += 10
if "unit_price" in mapped or "amount" in mapped:
score += 5
return score
def _find_notice_header_row_index(rows: list[list[Any]], *, max_scan: int = 40) -> int:
best_idx = 0
best_score = 0
for i, row in enumerate(rows[:max_scan]):
score = _score_notice_header_row(list(row))
if score > best_score:
best_score = score
best_idx = i
return best_idx if best_score > 0 else 0
def parse_notice_table_rows(headers: list[str], data_rows: list[list[Any]]) -> list[dict[str, Any]]:
columns = _resolve_notice_columns(headers)
has_header = columns.get("sku") is not None or columns.get("qty") is not None
if not has_header and headers:
has_header = any(_map_notice_header(h) for h in headers)
if not has_header:
return []
lines: list[dict[str, Any]] = []
for row in data_rows:
if not row:
continue
parsed = _parse_notice_row(list(row), columns)
if parsed:
lines.append(parsed)
return lines
def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]:
warnings: list[str] = []
if not lines:
warnings.append("未解析到有效订单行(需至少包含 SKU 与需求数量)。")
return warnings
missing_reservation = [line["sku"] for line in lines if not str(line.get("reservation_id") or "").strip()]
if missing_reservation and len(missing_reservation) == len(lines):
warnings.append(
"订单行未解析到 Reservation ID;后续将仅按 SKU 汇总库存比对,"
"若订单含 COM ID / Reservation Order 请核对表头。"
)
elif missing_reservation:
warnings.append(
f"部分订单行缺少 Reservation ID({len(missing_reservation)}/{len(lines)} 行),"
"这些行将按 SKU 汇总库存比对。"
)
invalid_reservation = [
line["sku"]
for line in lines
if str(line.get("reservation_id") or "").strip()
and not looks_like_reservation_id(line.get("reservation_id"))
]
if invalid_reservation:
warnings.append(
f"{len(invalid_reservation)} 行 Reservation ID 非典型纯数字格式(常见为 8~12 位,如 1000140351),"
"请核对是否解析正确。"
)
missing_price = sum(1 for line in lines if line.get("unit_price") is None and line.get("amount") is None)
if missing_price:
warnings.append(f"{missing_price} 行未解析到单价或金额(不影响库存匹配)。")
return warnings
def notice_parse_completeness(lines: list[dict[str, Any]]) -> float:
"""0~1 score for how complete order lines are (sku/qty/reservation/price)."""
if not lines:
return 0.0
scores: list[float] = []
for line in lines:
item = 0.0
if line.get("sku"):
item += 0.35
if line.get("qty"):
item += 0.35
if line.get("reservation_id"):
item += 0.15
if line.get("unit_price") is not None or line.get("amount") is not None:
item += 0.15
scores.append(item)
return round(sum(scores) / len(scores), 4)
@@ -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
@@ -0,0 +1,220 @@
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.constants import MAP_JSON
def _str_prop(description: str, *, enum: list[str] | None = None) -> dict[str, Any]:
prop: dict[str, Any] = {"type": "string", "description": description}
if enum:
prop["enum"] = enum
return prop
def _int_prop(description: str) -> dict[str, Any]:
return {"type": "integer", "description": description}
def _post_op(
operation_id: str,
summary: str,
properties: dict[str, Any],
*,
required: list[str] | None = None,
) -> dict[str, Any]:
schema: dict[str, Any] = {"type": "object", "properties": properties}
if required:
schema["required"] = required
return {
"post": {
"operationId": operation_id,
"summary": summary,
"description": summary,
"parameters": [],
"requestBody": {
"required": True,
"content": {
"application/json": {
"schema": schema,
}
},
},
"responses": {
"200": {
"description": (
"Tool response (status: ok|running|needs_human|failed). "
"May include checkpoint, human_options, action_buttons."
),
"content": {
"application/json": {
"schema": {"type": "object"},
}
},
}
},
}
}
def build_dify_openapi_spec(base_url: str) -> dict[str, Any]:
"""Build OpenAPI 3.0 spec for Dify Chatflow custom tools (agent-facing only)."""
server = str(base_url or "").strip().rstrip("/")
if not server.endswith("/api/shipping-notice"):
server = f"{server}/api/shipping-notice" if server else "/api/shipping-notice"
task_id = _str_prop("发货任务编号(task id),如 SN-20260529-ABCD1234")
return {
"openapi": "3.0.0",
"info": {
"title": "Hxops Shipping Notice Tools",
"version": "1.0.0",
"description": "货代发货通知 Agent Tool API。仅包含 Chatflow 编排工具,不含 RPA 回调。",
},
"servers": [{"url": server}],
"paths": {
"/tools/create_task": _post_op(
"create_task",
"创建发货任务 task",
{
"task_id": _str_prop("已存在的发货任务编号(可选)。传入时将直接复用该任务,禁止重复创建。"),
"user_id": _int_prop("Hxops 用户 ID(可选)"),
"conversation_id": _str_prop("Dify 会话 ID,便于工作台关联"),
"source_type": _str_prop("来源:manual|email|wecom|pdf", enum=["manual", "email", "wecom", "pdf"]),
"raw_content": _str_prop("原始发货通知文本(可选,后续 parse 也可传入)"),
},
),
"/tools/parse_notice": _post_op(
"parse_notice",
"解析发货通知文本",
{
"task_id": task_id,
"raw_text": _str_prop("待解析的发货通知全文"),
},
required=["task_id"],
),
"/tools/parse_inventory": _post_op(
"parse_inventory",
"解析库存。大 Excel 禁止 raw_inventory_text(会超 LLM token);"
"先 POST /tools/upload_inventory_file 上传,再 get_inventory_schema_preview → "
"apply_inventory_mapping;或 use_uploaded_file=true(规则映射兜底)。小表可粘贴文本。"
"成功后 stop_agent_turn,等 confirm_inventory_mapping 后再 match。",
{
"task_id": task_id,
"use_uploaded_file": _str_prop(
"true=解析该任务已上传的 Excel(服务端直传,不经过 LLM)",
enum=["true", "false"],
),
MAP_JSON: _str_prop(
'可选,列映射 JSON 字符串,如 {"sku":"AWS Sku","available_qty":"Qty Available"}'
),
"raw_inventory_text": _str_prop(
"仅小表(约 <8 万字符)。大 Excel 勿传此字段,改用 upload_inventory_file"
),
"inventory_lines_json": _str_prop(
'可选,已整理好的 JSON 数组字符串,如 [{"sku":"A001","available_qty":10}]'
),
},
required=["task_id"],
),
"/tools/get_inventory_schema_preview": _post_op(
"get_inventory_schema_preview",
"读取已上传库存 Excel 的表头与样例行(小 payload,供 LLM 推断列映射)",
{"task_id": task_id},
required=["task_id"],
),
"/tools/apply_inventory_mapping": _post_op(
"apply_inventory_mapping",
"应用 LLM/人工列映射并解析完整库存文件;返回 field_alignment 等待用户确认",
{
"task_id": task_id,
MAP_JSON: _str_prop(
'列映射 JSON,含 sku/reservation_id/available_qty;可选 match_rule(LLM 自然语言匹配说明,缺省则后端动态兜底)'
),
},
required=["task_id", MAP_JSON],
),
"/tools/ensure_inventory": _post_op(
"ensure_inventory",
"确保库存快照可用(RPA 自动导出;对话库存请优先用 parse_inventory)",
{
"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=["task_id"],
),
"/tools/auto_progress": _post_op(
"auto_progress",
"按后端全局配置自动推进:RPA 获取库存 → 字段对齐(满足条件可自动确认)→ 匹配 → 生成 Excel →(可选)上传。遇到人工节点会停住返回 action_buttons。",
{
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID(可选,用于仅知道会话时定位任务)"),
},
),
"/tools/match_inventory": _post_op(
"match_inventory",
"匹配发货需求与库存。前置条件:submit_decision(confirm_inventory_mapping) 已成功;"
"未确认时调用会被拒绝并返回 forbidden_next_tools",
{
"task_id": task_id,
"inventory_lines_json": _str_prop("可选,覆盖库存 JSON 数组后再匹配"),
},
required=["task_id"],
),
"/tools/submit_decision": _post_op(
"submit_decision",
"人工复核决策。task_id 与 conversation_id 至少传一个;用户确认时禁止 create_task",
{
"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=重新上传库存",
enum=[
"confirm",
"confirm_parse",
"reject",
"rematch",
"reparse",
"confirm_inventory_mapping",
"correct_inventory_mapping",
"reparse_inventory",
],
),
"comment": _str_prop("备注(可选)"),
},
required=["decision"],
),
"/tools/generate_shipment_excel": _post_op(
"generate_shipment_excel",
"生成固定模板发货 Excel(须 match_inventory 成功且 process_status=matched)",
{"task_id": task_id},
required=["task_id"],
),
"/tools/upload_to_freight": _post_op(
"upload_to_freight",
"上传 Excel 到货代系统(RPA 或手工确认)",
{
"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=["task_id"],
),
"/tools/get_task_status": _post_op(
"get_task_status",
"查询任务当前状态与 human_options。task_id 与 conversation_id 至少传一个",
{
"task_id": task_id,
"conversation_id": _str_prop("Dify 会话 ID"),
},
),
},
}
@@ -0,0 +1,150 @@
from __future__ import annotations
from typing import Any
from app.services.shipping_notice.i18n import resolve_lang, t
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 = "",
lang: str,
) -> list[str]:
currency = line.get("currency")
required_date = str(line.get("required_date") or doc_required_date or "").strip()
rows: list[str] = [
f"| {t('table.field', lang=lang)} | {t('table.value', lang=lang)} |",
"|------|-----|",
]
_append_table_row(rows, t("field.reservation_id", lang=lang), line.get("reservation_id"))
_append_table_row(rows, t("field.sku", lang=lang), line.get("sku"))
_append_table_row(rows, t("field.qty", lang=lang), _fmt_qty(line.get("qty"), line.get("uom")))
_append_table_row(rows, t("field.unit_price", lang=lang), _fmt_money(line.get("unit_price"), currency))
_append_table_row(rows, t("field.amount", lang=lang), _fmt_money(line.get("amount"), currency))
_append_table_row(rows, t("field.required_date", lang=lang), required_date)
vendor_pn = str(line.get("vendor_part_number") or "").strip()
if vendor_pn:
_append_table_row(rows, t("field.vendor_part_number", lang=lang), vendor_pn)
line_no = str(line.get("line_no") or "").strip()
if line_no:
_append_table_row(rows, t("field.line_no", lang=lang), 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,
lang: str | None = None,
payload: dict[str, Any] | None = None,
) -> str:
"""Fixed Markdown summary for parse_notice / Agent display."""
resolved = resolve_lang(payload) if payload is not None else resolve_lang({"lang": lang} if lang else None)
order_lines = [line for line in (lines or []) if isinstance(line, dict)]
doc_date = str(required_date or "").strip()
parts = [t("parse.title", lang=resolved).format(task_no=task_no), ""]
if not order_lines:
parts.extend([f"| {t('table.field', lang=resolved)} | {t('table.value', lang=resolved)} |", "|------|-----|"])
_append_table_row(parts, t("field.po", lang=resolved), po_number)
_append_table_row(parts, t("field.ship_to", lang=resolved), ship_to or customer_name)
_append_table_row(parts, t("field.required_date", lang=resolved), doc_date)
parts.append("")
parts.append(t("parse.no_lines", lang=resolved))
elif len(order_lines) == 1:
line = order_lines[0]
parts.extend([f"| {t('table.field', lang=resolved)} | {t('table.value', lang=resolved)} |", "|------|-----|"])
_append_table_row(parts, t("field.po", lang=resolved), po_number)
_append_table_row(parts, t("field.reservation_id", lang=resolved), line.get("reservation_id"))
_append_table_row(parts, t("field.sku", lang=resolved), line.get("sku"))
_append_table_row(parts, t("field.qty", lang=resolved), _fmt_qty(line.get("qty"), line.get("uom")))
_append_table_row(parts, t("field.unit_price", lang=resolved), _fmt_money(line.get("unit_price"), line.get("currency")))
_append_table_row(parts, t("field.amount", lang=resolved), _fmt_money(line.get("amount"), line.get("currency")))
line_date = str(line.get("required_date") or doc_date or "").strip()
_append_table_row(parts, t("field.required_date", lang=resolved), line_date)
recipient = str(ship_to or customer_name or "").strip()
_append_table_row(parts, t("field.ship_to", lang=resolved), recipient)
vendor_pn = str(line.get("vendor_part_number") or "").strip()
if vendor_pn:
_append_table_row(parts, t("field.vendor_part_number", lang=resolved), vendor_pn)
else:
if po_number:
parts.append(f"{t('field.po', lang=resolved)}:{_cell(po_number)}")
recipient = str(ship_to or customer_name or "").strip()
if recipient:
parts.append(f"{t('field.ship_to', lang=resolved)}:{recipient}")
if doc_date:
parts.append(f"{t('field.required_date', lang=resolved)}:{doc_date}")
parts.append("")
for index, line in enumerate(order_lines, 1):
line_no = str(line.get("line_no") or index).strip()
if resolved == "en":
parts.append(f"[Line {index}] {t('field.line_no', lang=resolved)} {line_no}")
else:
parts.append(f"【明细 {index}】{t('field.line_no', lang=resolved)} {line_no}")
parts.extend(_format_line_block(line, doc_required_date=doc_date, lang=resolved))
parts.append("")
warn_items = [str(w).strip() for w in (warnings or []) if str(w).strip()]
if warn_items:
parts.append("")
parts.append(t("common.tips", lang=resolved))
for warning in warn_items[:8]:
parts.append(f"- {warning}")
parts.append("")
if low_confidence:
parts.append(t("parse.low_conf", lang=resolved))
parts.append(t("parse.confirm", lang=resolved))
parts.append(t("parse.hint", lang=resolved))
hint_btn = t("parse.hint_btn", lang=resolved).strip()
if hint_btn:
parts.append(hint_btn)
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
@@ -0,0 +1,73 @@
from __future__ import annotations
from typing import Any
from sqlalchemy import desc
from app.models import ShippingTask, ShippingTaskEvent
def serialize_task_summary(task: ShippingTask) -> dict[str, Any]:
return {
"id": task.id,
"task_no": task.task_no,
"source_type": task.source_type,
"customer_name": task.customer_name,
"process_status": task.process_status,
"review_status": task.review_status,
"match_status": task.match_status,
"pending_human_reason": task.pending_human_reason,
"conversation_id": task.conversation_id,
"export_file_name": task.export_file_name,
"freight_ref_no": task.freight_ref_no,
"created_at": task.created_at.isoformat() if task.created_at else None,
"updated_at": task.updated_at.isoformat() if task.updated_at else None,
}
def serialize_task_detail(task: ShippingTask) -> dict[str, Any]:
data = serialize_task_summary(task)
data.update({
"customer_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(task.events or [], key=lambda x: x.created_at or "")
],
})
return data
def list_tasks_for_user(
user_id: int,
*,
process_status: str | None = None,
limit: int = 100,
) -> list[dict[str, Any]]:
q = ShippingTask.query.filter(
(ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None))
)
if process_status:
q = q.filter(ShippingTask.process_status == process_status)
rows = q.order_by(desc(ShippingTask.created_at)).limit(max(1, min(limit, 500))).all()
return [serialize_task_summary(c) for c in rows]
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 task.user_id is not None and task.user_id != user_id:
return None
return task
@@ -0,0 +1,89 @@
from __future__ import annotations
import re
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:
"""Normalize reservation id; Excel often stores numeric ids as float."""
if value is None:
return ""
if isinstance(value, bool):
return ""
if isinstance(value, float):
if value != value: # NaN
return ""
if value.is_integer():
return str(int(value))
text = str(value).strip()
elif isinstance(value, int):
text = str(value)
else:
text = str(value).strip()
if not text:
return ""
text = text.replace(",", "").replace(",", "").strip()
if re.fullmatch(r"\d+\.0+", text):
text = text.split(".", 1)[0]
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))
@@ -0,0 +1,94 @@
from __future__ import annotations
import json
import shutil
from datetime import datetime
from pathlib import Path
from typing import Any
from flask import current_app
def _path(key: str) -> Path | None:
value = str(current_app.config.get(key) or "").strip()
if not value:
return None
return Path(value)
def inventory_drop_dir() -> Path | None:
return _path("FREIGHT_INVENTORY_DROP_DIR")
def inventory_processed_dir() -> Path | None:
base = inventory_drop_dir()
if not base:
return None
return base / "processed"
def inventory_trigger_dir() -> Path | None:
return _path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR")
def upload_queue_dir() -> Path | None:
return _path("FREIGHT_UPLOAD_QUEUE_DIR")
def upload_trigger_dir() -> Path | None:
return _path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR")
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",
"task_no": task_no,
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
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(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:
return None, None
queue.mkdir(parents=True, exist_ok=True)
trigger_dir.mkdir(parents=True, exist_ok=True)
src = Path(export_file_path)
if not src.is_file():
return None, None
dest = queue / f"{task_no}_{src.name}"
shutil.copy2(src, dest)
body = {
"action": "shipment_upload",
"task_no": task_no,
"file_path": str(dest),
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
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)
def find_latest_inventory_file() -> Path | None:
drop = inventory_drop_dir()
if not drop or not drop.is_dir():
return None
candidates = [
p for p in drop.iterdir()
if p.is_file() and p.suffix.lower() in {".xlsx", ".xls", ".csv"}
]
if not candidates:
return None
return max(candidates, key=lambda p: p.stat().st_mtime)
@@ -0,0 +1,94 @@
from __future__ import annotations
import os
from datetime import datetime
from app.models import ShippingTask, ShippingTaskEvent
DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS = 3
DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS = 3
_INVENTORY_SUCCESS_EVENTS = {
"inventory_uploaded",
"inventory_parsed",
"inventory_rpa_drop_ingested",
"inventory_rpa_ready",
"inventory_template_mapping_used",
}
_UPLOAD_SUCCESS_EVENTS = {
"upload_rpa_success",
"upload_manual_confirmed",
}
def inventory_rpa_attempts(task: ShippingTask | None) -> int:
if not task or task.id is None:
return 0
last_success = (
ShippingTaskEvent.query.filter_by(task_id=task.id)
.filter(ShippingTaskEvent.event_type.in_(_INVENTORY_SUCCESS_EVENTS))
.order_by(ShippingTaskEvent.id.desc())
.first()
)
since: datetime | None = last_success.created_at if last_success else None
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_triggered"
)
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "inventory_rpa_failed"
)
if since:
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
failed = failed.filter(ShippingTaskEvent.created_at >= since)
return max(triggered.count(), failed.count())
def upload_rpa_attempts(task: ShippingTask | None) -> int:
if not task or task.id is None:
return 0
last_success = (
ShippingTaskEvent.query.filter_by(task_id=task.id)
.filter(ShippingTaskEvent.event_type.in_(_UPLOAD_SUCCESS_EVENTS))
.order_by(ShippingTaskEvent.id.desc())
.first()
)
since: datetime | None = last_success.created_at if last_success else None
triggered = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "upload_rpa_triggered"
)
failed = ShippingTaskEvent.query.filter_by(task_id=task.id).filter(
ShippingTaskEvent.event_type == "upload_rpa_failed"
)
if since:
triggered = triggered.filter(ShippingTaskEvent.created_at >= since)
failed = failed.filter(ShippingTaskEvent.created_at >= since)
return max(triggered.count(), failed.count())
def max_rpa_inventory_attempts() -> int:
value = os.getenv("SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS")
if value is None or not str(value).strip():
return DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS
try:
parsed = int(value)
except (TypeError, ValueError):
return DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS
return max(parsed, 1)
def max_rpa_upload_attempts() -> int:
value = os.getenv("SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS")
if value is None or not str(value).strip():
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
try:
parsed = int(value)
except (TypeError, ValueError):
return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS
return max(parsed, 1)
@@ -0,0 +1,552 @@
"""
Canonical registry for shipping-notice human nodes.
Single source of truth for:
- checkpoint ids (API `checkpoint`, Dify `flow_ckpt`)
- action button specs (`action_buttons`, HXOPS_SHIPPING_ACTIONS)
- task DB fields → checkpoint + human_options (chat-actions API)
- task DB field writes (`TaskTransition` / `apply_task_transition` — tools.py must use these)
When adding a human node, update ONLY this module (+ tests), then:
- tools.py sets task fields via `apply_task_transition(...)` and calls `tool_response(..., checkpoint=CP_*)`
- Dify `组装直接回复` embeds directive only from HTTP `act_json` (approach B); text-only rounds use Hxops `/chat-actions`
- `GET /tools/checkpoint-catalog` is for developers/docs/CI — not wired in Dify canvas
"""
from __future__ import annotations
import json
from dataclasses import dataclass
from enum import StrEnum
from typing import Any
from app.models import ShippingTask
from app.services.shipping_notice.constants import (
CP_ALIGN_REVIEW,
CP_EXPORT_READY,
CP_EXPORT_GENERATED,
CP_INVENTORY_PENDING,
CP_MAP_INFER,
CP_PARSE_REVIEW,
CP_NOTICE_TEXT_EXTRACTION_FAILED,
CP_READY_EXPORT,
CP_READY_MATCH,
CP_REJECTED,
CP_RSV_REQ,
CP_UPLOADED,
CP_COMPLETED,
CP_UPLOAD_FAILED,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_ALIGN_REVIEW,
PH_INV_UNAVAIL,
PH_LOW_CONF,
PH_MAP_INFER,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
PH_RSV_REQ,
PH_SHORTAGE,
PH_UPLOAD_RPA_FAILED,
PH_UPLOAD_RPA_PENDING,
RS_ALIGN_REVIEW,
RS_CONFIRMED,
RS_PARSE_REVIEW,
RS_REJECTED,
RS_RSV_REQ,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.rpa_attempts import (
inventory_rpa_attempts,
max_rpa_inventory_attempts,
)
# ---------------------------------------------------------------------------
# Action buttons (id → label / message / variant)
# ---------------------------------------------------------------------------
ACTION_SPECS: dict[str, dict[str, str]] = {
"confirm": {"label": "确认", "message": "确认", "variant": "primary"},
"reject": {"label": "驳回", "message": "驳回", "variant": "danger"},
"reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"},
"confirm_inventory_mapping": {"label": "确认", "message": "确认", "variant": "primary"},
"correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"},
"reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"},
"rematch": {"label": "重新匹配", "message": "重新匹配", "variant": "secondary"},
"retry_rpa": {"label": "重试 RPA", "message": "重试 RPA 导出库存", "variant": "secondary"},
"refresh": {"label": "刷新", "message": "刷新", "variant": "secondary"},
"upload_inventory_file": {
"label": "选择库存文件",
"message": "我要上传库存 Excel",
"variant": "secondary",
},
"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": "已在货代系统手工上传完成",
"variant": "primary",
},
"paste_inventory_json": {
"label": "粘贴库存",
"message": "我粘贴库存小表",
"variant": "secondary",
},
"edit_inventory_mapping": {
"label": "修改映射",
"message": "修改库存列映射",
"variant": "primary",
},
"match_inventory": {
"label": "匹配库存",
"message": "匹配库存",
"variant": "primary",
},
}
# checkpoint id → default human option ids (HTTP / Dify before task reload)
CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = {
CP_PARSE_REVIEW: ("confirm", "reject", "reparse"),
CP_ALIGN_REVIEW: (
"confirm_inventory_mapping",
"correct_inventory_mapping",
"reparse_inventory",
"reject",
),
CP_MAP_INFER: (
"edit_inventory_mapping",
"upload_inventory_file",
"paste_inventory_json",
"retry_rpa",
),
CP_UPLOAD_REQ: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"),
CP_RSV_REQ: ("reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"),
RS_SHORTAGE_REVIEW: ("confirm", "reject", "rematch"),
CP_NOTICE_TEXT_EXTRACTION_FAILED: ("reparse", "reject"),
CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"),
CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"),
CP_READY_MATCH: ("match_inventory",),
CP_READY_EXPORT: ("generate_excel",),
CP_EXPORT_READY: ("download_excel", "mark_manual_uploaded"),
CP_EXPORT_GENERATED: ("download_excel", "mark_manual_uploaded"),
CP_REJECTED: (),
CP_UPLOADED: (),
CP_COMPLETED: (),
}
ALL_CHECKPOINT_IDS: frozenset[str] = frozenset(CHECKPOINT_REGISTRY.keys())
ALL_ACTION_IDS: frozenset[str] = frozenset(ACTION_SPECS.keys())
# Dynamic subsets of upload_req (RPA attempts); default full set is CHECKPOINT_REGISTRY[CP_UPLOAD_REQ]
OPTIONS_UPLOAD_FILE_ONLY: tuple[str, ...] = ("upload_inventory_file",)
OPTIONS_RPA_OR_UPLOAD: tuple[str, ...] = ("retry_rpa", "upload_inventory_file")
@dataclass(frozen=True)
class TaskUiState:
checkpoint: str | None
human_options: list[str] | None
@property
def action_buttons(self) -> list[dict[str, str]]:
return build_action_buttons(self.human_options)
def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]:
if not option_ids:
return []
buttons: list[dict[str, str]] = []
for option_id in option_ids:
spec = ACTION_SPECS.get(option_id)
if not spec:
continue
buttons.append({"id": option_id, **spec})
return buttons
def human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None:
if not checkpoint:
return None
key = str(checkpoint).strip()
options = CHECKPOINT_REGISTRY.get(key)
if options is None:
return None
return list(options)
def action_buttons_for_checkpoint(checkpoint: str | None) -> list[dict[str, str]]:
return build_action_buttons(human_options_for_checkpoint(checkpoint))
def format_actions_directive(option_ids: list[str] | None) -> str:
buttons = build_action_buttons(option_ids)
if not buttons:
return ""
body = json.dumps(buttons, ensure_ascii=False)
return f"<!-- HXOPS_SHIPPING_ACTIONS: {body} -->"
def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState:
options = human_options_for_checkpoint(checkpoint)
cp = str(checkpoint).strip() if checkpoint else None
if cp and cp not in CHECKPOINT_REGISTRY:
cp = None
return TaskUiState(checkpoint=cp, human_options=options)
def upload_req_options_for_task(task: ShippingTask) -> list[str]:
"""upload_req checkpoint with RPA-attempt-aware button subsets."""
if task.pending_human_reason == PH_RPA_EXHAUSTED:
return list(OPTIONS_UPLOAD_FILE_ONLY)
if inventory_rpa_attempts(task) >= max_rpa_inventory_attempts():
return list(OPTIONS_UPLOAD_FILE_ONLY)
if task.pending_human_reason in {PH_INV_UNAVAIL, PH_RPA_PENDING}:
return list(OPTIONS_RPA_OR_UPLOAD)
return list(CHECKPOINT_REGISTRY[CP_UPLOAD_REQ])
def human_options_for_task_or_checkpoint(
*,
task: ShippingTask | None = None,
checkpoint: str | None = None,
) -> list[str] | None:
"""Prefer task DB state; fall back to static checkpoint registry (for tool_response)."""
if task is not None:
opts = resolve_task_ui_state(task).human_options
if opts is not None:
return opts
return human_options_for_checkpoint(checkpoint)
def resolve_task_ui_state(task: ShippingTask) -> TaskUiState:
"""Map ShippingTask DB fields → checkpoint + human_options for /chat-actions."""
if task.process_status == "uploaded":
return TaskUiState(checkpoint=CP_UPLOADED, human_options=[])
if task.process_status == "closed":
return TaskUiState(checkpoint=CP_COMPLETED, human_options=[])
if task.process_status == "rejected" or task.review_status == "rejected":
return TaskUiState(checkpoint=CP_REJECTED, human_options=[])
if task.pending_human_reason == PH_RPA_EXHAUSTED:
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
human_options=upload_req_options_for_task(task),
)
if (
task.process_status == "parsed"
and not task.review_status
and not task.pending_human_reason
and not task.inventory_lines_json
):
return TaskUiState(
checkpoint=CP_INVENTORY_PENDING,
human_options=list(CHECKPOINT_REGISTRY[CP_INVENTORY_PENDING]),
)
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 TaskUiState(
checkpoint=CP_READY_MATCH,
human_options=list(CHECKPOINT_REGISTRY[CP_READY_MATCH]),
)
if task.process_status == "matched":
if task.export_file_path:
return TaskUiState(
checkpoint=CP_EXPORT_READY,
human_options=list(CHECKPOINT_REGISTRY[CP_EXPORT_READY]),
)
return TaskUiState(
checkpoint=CP_READY_EXPORT,
human_options=list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]),
)
reason = task.pending_human_reason
if reason == PH_ALIGN_REVIEW or task.review_status == RS_ALIGN_REVIEW:
return TaskUiState(
checkpoint=CP_ALIGN_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[CP_ALIGN_REVIEW]),
)
if reason == PH_MAP_INFER:
return TaskUiState(
checkpoint=CP_MAP_INFER,
human_options=list(CHECKPOINT_REGISTRY[CP_MAP_INFER]),
)
if reason == PH_RSV_REQ or task.review_status == RS_RSV_REQ:
return TaskUiState(
checkpoint=CP_RSV_REQ,
human_options=list(CHECKPOINT_REGISTRY[CP_RSV_REQ]),
)
if reason == PH_INV_UNAVAIL:
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
human_options=upload_req_options_for_task(task),
)
if reason == PH_SHORTAGE or task.review_status == RS_SHORTAGE_REVIEW:
return TaskUiState(
checkpoint=RS_SHORTAGE_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[RS_SHORTAGE_REVIEW]),
)
if reason == PH_LOW_CONF or task.review_status == RS_PARSE_REVIEW:
return TaskUiState(
checkpoint=CP_PARSE_REVIEW,
human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]),
)
if reason == PH_UPLOAD_RPA_FAILED or task.process_status == "upload_failed":
return TaskUiState(
checkpoint=CP_UPLOAD_FAILED,
human_options=list(CHECKPOINT_REGISTRY[CP_UPLOAD_FAILED]),
)
if reason == PH_RPA_PENDING or (
task.process_status == "waiting_inventory" and reason == PH_RPA_PENDING
):
return TaskUiState(
checkpoint=CP_UPLOAD_REQ,
human_options=upload_req_options_for_task(task),
)
if reason == PH_UPLOAD_RPA_PENDING or task.process_status == "waiting_upload":
return TaskUiState(
checkpoint=CP_WAITING_UPLOAD,
human_options=list(CHECKPOINT_REGISTRY[CP_WAITING_UPLOAD]),
)
return TaskUiState(checkpoint=None, human_options=None)
def checkpoint_for_task(task: ShippingTask) -> str | None:
return resolve_task_ui_state(task).checkpoint
def human_options_for_task(task: ShippingTask) -> list[str] | None:
return resolve_task_ui_state(task).human_options
def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]:
ui = resolve_task_ui_state(task)
return {
"task_no": task.task_no,
"checkpoint": ui.checkpoint,
"process_status": task.process_status,
"review_status": task.review_status,
"pending_human_reason": task.pending_human_reason,
"action_buttons": ui.action_buttons,
}
def build_checkpoint_catalog() -> dict[str, Any]:
"""Export for docs, CI, and developer reference — not embedded in Dify (approach B)."""
checkpoints = []
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
buttons = build_action_buttons(list(option_ids))
checkpoints.append(
{
"id": checkpoint_id,
"human_options": list(option_ids),
"action_buttons": buttons,
}
)
return {
"checkpoints": checkpoints,
"action_specs": ACTION_SPECS,
"dify_fallback": {
cp: build_action_buttons(list(opts)) for cp, opts in CHECKPOINT_REGISTRY.items()
},
}
def validate_registry() -> list[str]:
"""Return list of validation errors (empty if ok). Used in tests."""
errors: list[str] = []
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
for option_id in option_ids:
if option_id not in ACTION_SPECS:
errors.append(f"checkpoint {checkpoint_id}: unknown action id {option_id!r}")
return errors
# ---------------------------------------------------------------------------
# Task DB field transitions (tools.py writes via apply_task_transition only)
# ---------------------------------------------------------------------------
_UNSET = object()
@dataclass(frozen=True)
class _TransitionSpec:
process_status: Any = _UNSET
review_status: Any = _UNSET
pending_human_reason: Any = _UNSET
clear_error_message: bool = False
class TaskTransition(StrEnum):
"""Named DB state writes used by shipping notice tools."""
PARSED = "parsed"
PARSE_NEEDS_REVIEW = "parse_needs_review"
INVENTORY_READY = "inventory_ready"
INVENTORY_ALIGN_REVIEW = "inventory_align_review"
MAP_INFER = "map_infer"
RPA_EXHAUSTED = "rpa_exhausted"
RPA_PENDING = "rpa_pending"
INV_UNAVAIL = "inv_unavail"
RSV_REQUIRED = "rsv_required"
MATCHED_FULFILLABLE = "matched_fulfillable"
MATCH_SHORTAGE = "match_shortage"
REJECTED = "rejected"
CLOSED = "closed"
CONFIRM_SHORTAGE = "confirm_shortage"
CONFIRM_PARSE = "confirm_parse"
CONFIRM_MATCHED = "confirm_matched"
ALIGN_REVIEW_HOLD = "align_review_hold"
MAPPING_CONFIRMED = "mapping_confirmed"
CORRECT_MAPPING = "correct_mapping"
REPARSE_INVENTORY = "reparse_inventory"
REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote"
WAITING_UPLOAD = "waiting_upload"
UPLOAD_RPA_PENDING = "upload_rpa_pending"
UPLOAD_FAILED = "upload_failed"
UPLOADED = "uploaded"
TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = {
TaskTransition.PARSED: _TransitionSpec(
process_status="parsed",
review_status=None,
pending_human_reason=None,
),
TaskTransition.PARSE_NEEDS_REVIEW: _TransitionSpec(
process_status="pending_review",
review_status=RS_PARSE_REVIEW,
pending_human_reason=PH_LOW_CONF,
),
TaskTransition.INVENTORY_READY: _TransitionSpec(
process_status="inventory_ready",
review_status=None,
pending_human_reason=None,
clear_error_message=True,
),
TaskTransition.INVENTORY_ALIGN_REVIEW: _TransitionSpec(
process_status="inventory_ready",
review_status=RS_ALIGN_REVIEW,
pending_human_reason=PH_ALIGN_REVIEW,
clear_error_message=True,
),
TaskTransition.MAP_INFER: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_MAP_INFER,
),
TaskTransition.RPA_EXHAUSTED: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_RPA_EXHAUSTED,
),
TaskTransition.RPA_PENDING: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_RPA_PENDING,
),
TaskTransition.INV_UNAVAIL: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_INV_UNAVAIL,
),
TaskTransition.RSV_REQUIRED: _TransitionSpec(
process_status="pending_review",
review_status=RS_RSV_REQ,
pending_human_reason=PH_RSV_REQ,
),
TaskTransition.MATCHED_FULFILLABLE: _TransitionSpec(
process_status="matched",
review_status=RS_CONFIRMED,
pending_human_reason=None,
),
TaskTransition.MATCH_SHORTAGE: _TransitionSpec(
process_status="pending_review",
review_status=RS_SHORTAGE_REVIEW,
pending_human_reason=PH_SHORTAGE,
),
TaskTransition.REJECTED: _TransitionSpec(
process_status="rejected",
review_status=RS_REJECTED,
pending_human_reason=None,
),
TaskTransition.CLOSED: _TransitionSpec(
process_status="closed",
review_status=None,
pending_human_reason=None,
clear_error_message=True,
),
TaskTransition.CONFIRM_SHORTAGE: _TransitionSpec(
process_status="matched",
review_status=RS_CONFIRMED,
pending_human_reason=None,
),
TaskTransition.CONFIRM_PARSE: _TransitionSpec(
process_status="parsed",
review_status=None,
pending_human_reason=None,
),
TaskTransition.CONFIRM_MATCHED: _TransitionSpec(
review_status=RS_CONFIRMED,
pending_human_reason=None,
),
TaskTransition.ALIGN_REVIEW_HOLD: _TransitionSpec(
review_status=RS_ALIGN_REVIEW,
pending_human_reason=PH_ALIGN_REVIEW,
),
TaskTransition.MAPPING_CONFIRMED: _TransitionSpec(
review_status=None,
pending_human_reason=None,
),
TaskTransition.CORRECT_MAPPING: _TransitionSpec(
process_status="waiting_inventory",
review_status=None,
pending_human_reason=PH_MAP_INFER,
),
TaskTransition.REPARSE_INVENTORY: _TransitionSpec(
review_status=None,
pending_human_reason=None,
),
TaskTransition.REPARSE_INVENTORY_DEMOTE: _TransitionSpec(
process_status="parsed",
review_status=None,
pending_human_reason=None,
),
TaskTransition.WAITING_UPLOAD: _TransitionSpec(process_status="waiting_upload"),
TaskTransition.UPLOAD_RPA_PENDING: _TransitionSpec(
process_status="waiting_upload",
pending_human_reason=PH_UPLOAD_RPA_PENDING,
),
TaskTransition.UPLOAD_FAILED: _TransitionSpec(
process_status="upload_failed",
pending_human_reason=PH_UPLOAD_RPA_FAILED,
),
TaskTransition.UPLOADED: _TransitionSpec(
process_status="uploaded",
pending_human_reason=None,
clear_error_message=True,
),
}
def apply_task_transition(task: ShippingTask, transition: TaskTransition) -> None:
"""Apply a named transition to task process/review/pending_human_reason fields."""
spec = TASK_TRANSITIONS[transition]
if spec.process_status is not _UNSET:
task.process_status = spec.process_status
if spec.review_status is not _UNSET:
task.review_status = spec.review_status
if spec.pending_human_reason is not _UNSET:
task.pending_human_reason = spec.pending_human_reason
if spec.clear_error_message:
task.error_message = None
@@ -0,0 +1,24 @@
from __future__ import annotations
from flask import current_app, has_request_context, request
def resolve_tool_api_base_url(*, config: dict | None = None, request_host: str | None = None) -> str:
"""Resolve hxops Tool API base URL (…/api/shipping-notice, no trailing slash)."""
cfg = config
if cfg is None and current_app:
cfg = current_app.config
cfg = cfg or {}
configured = str(cfg.get("SHIPPING_NOTICE_TOOL_API_BASE") or "").strip().rstrip("/")
if configured:
return configured
configured = str(cfg.get("PUBLIC_BASE_URL") or "").strip().rstrip("/")
if configured:
return configured
host = request_host
if host is None and has_request_context():
host = request.host_url.rstrip("/")
return host or ""
@@ -0,0 +1,75 @@
from __future__ import annotations
from typing import TYPE_CHECKING, Any
if TYPE_CHECKING:
from app.models import ShippingTask
def tool_response(
*,
status: str,
task: ShippingTask | None = None,
task_id: str | None = None,
message: str = "",
data: dict[str, Any] | None = None,
human_options: list[str] | None = None,
action_buttons: list[dict[str, str]] | None = None,
checkpoint: str | None = None,
next_required_action: str | None = None,
forbidden_next_tools: list[str] | None = None,
stop_agent_turn: bool = False,
) -> dict[str, Any]:
"""Build a shipping-notice tool JSON response.
When ``checkpoint`` is omitted and ``task`` is given, checkpoint / human_options /
action_buttons are derived from ``resolve_task_ui_state(task)`` (single read path).
Explicit ``checkpoint`` wins (e.g. ``parse_ok``, ``task_exists``).
"""
from app.services.shipping_notice.state_machine import (
action_buttons_for_checkpoint,
build_action_buttons,
resolve_task_ui_state,
)
if task is not None and not task_id:
task_id = task.task_no
resolved_checkpoint = checkpoint
resolved_human_options = human_options
resolved_action_buttons = action_buttons
if checkpoint is None and task is not None:
ui = resolve_task_ui_state(task)
resolved_checkpoint = ui.checkpoint
if human_options is None:
resolved_human_options = ui.human_options
if action_buttons is None and ui.action_buttons:
resolved_action_buttons = ui.action_buttons
payload: dict[str, Any] = {
"status": status,
"message": message,
"data": data or {},
}
if task_id:
payload["task_id"] = task_id
if resolved_human_options is not None:
payload["human_options"] = resolved_human_options
if resolved_action_buttons is not None:
payload["action_buttons"] = resolved_action_buttons
elif resolved_human_options is not None:
payload["action_buttons"] = build_action_buttons(resolved_human_options)
elif resolved_checkpoint:
buttons = action_buttons_for_checkpoint(resolved_checkpoint)
if buttons:
payload["action_buttons"] = buttons
if resolved_checkpoint:
payload["checkpoint"] = resolved_checkpoint
if next_required_action:
payload["next_required_action"] = next_required_action
if forbidden_next_tools:
payload["forbidden_next_tools"] = forbidden_next_tools
if stop_agent_turn:
payload["stop_agent_turn"] = True
return payload
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,95 @@
"""Human-readable task progress — never expose DB / state-machine codes to end users."""
from __future__ import annotations
from app.models import ShippingTask
from app.services.shipping_notice.constants import (
CP_ALIGN_REVIEW,
CP_EXPORT_READY,
CP_INVENTORY_PENDING,
CP_MAP_INFER,
CP_PARSE_REVIEW,
CP_READY_EXPORT,
CP_READY_MATCH,
CP_REJECTED,
CP_RSV_REQ,
CP_UPLOADED,
CP_COMPLETED,
CP_UPLOAD_FAILED,
CP_UPLOAD_REQ,
CP_WAITING_UPLOAD,
PH_RPA_EXHAUSTED,
PH_RPA_PENDING,
PH_SHORTAGE,
PH_UPLOAD_RPA_PENDING,
RS_PARSE_REVIEW,
RS_SHORTAGE_REVIEW,
)
from app.services.shipping_notice.state_machine import resolve_task_ui_state
# Fields omitted from Dify Tool `data` — Agent must not parrot these to users.
TOOL_TASK_DATA_OMIT: frozenset[str] = frozenset(
{
"process_status",
"review_status",
"match_status",
"pending_human_reason",
"error_message",
}
)
_CHECKPOINT_LABELS: dict[str, str] = {
CP_PARSE_REVIEW: "待确认发货通知解析",
CP_ALIGN_REVIEW: "待确认库存字段对齐",
CP_MAP_INFER: "待确认库存列映射",
CP_UPLOAD_REQ: "待上传或获取库存",
CP_INVENTORY_PENDING: "待上传库存",
CP_RSV_REQ: "待补充 Reservation ID",
CP_READY_MATCH: "待匹配库存",
CP_READY_EXPORT: "待生成发货 Excel",
CP_EXPORT_READY: "发货 Excel 已生成",
CP_WAITING_UPLOAD: "待上传货代系统",
CP_UPLOAD_FAILED: "货代上传失败,待处理",
CP_REJECTED: "任务已驳回",
CP_UPLOADED: "已完成上传",
CP_COMPLETED: "任务已完成",
}
_PROCESS_STATUS_LABELS: dict[str, str] = {
"created": "任务已创建",
"parsed": "发货通知已解析",
"pending_review": "待人工确认",
"waiting_inventory": "待获取库存",
"inventory_ready": "库存已就绪",
"matched": "库存已匹配",
"waiting_upload": "待上传货代系统",
"upload_failed": "货代上传失败",
"uploaded": "已完成上传",
"rejected": "已驳回",
"closed": "已关闭",
}
_PENDING_REASON_LABELS: dict[str, str] = {
PH_RPA_PENDING: "RPA 正在导出库存,请稍候",
PH_RPA_EXHAUSTED: "RPA 获取库存失败,请手动上传",
PH_UPLOAD_RPA_PENDING: "RPA 正在上传货代,请稍候",
PH_SHORTAGE: "库存不足,待确认",
RS_SHORTAGE_REVIEW: "库存不足,待确认",
RS_PARSE_REVIEW: "解析结果待确认",
}
def user_facing_task_stage(task: ShippingTask) -> str:
"""Short Chinese label for chat / get_task_status — no snake_case codes."""
ui = resolve_task_ui_state(task)
if ui.checkpoint and ui.checkpoint in _CHECKPOINT_LABELS:
return _CHECKPOINT_LABELS[ui.checkpoint]
reason = str(task.pending_human_reason or "").strip()
if reason in _PENDING_REASON_LABELS:
return _PENDING_REASON_LABELS[reason]
process = str(task.process_status or "").strip()
return _PROCESS_STATUS_LABELS.get(process, "处理中")
def strip_internal_task_fields(data: dict) -> dict:
return {k: v for k, v in data.items() if k not in TOOL_TASK_DATA_OMIT}
+22 -1
View File
@@ -12,6 +12,8 @@ from __future__ import annotations
import os
import subprocess
from pathlib import Path
import shutil
import tempfile
def soffice_timeout_sec() -> int:
@@ -46,6 +48,15 @@ def find_soffice() -> str | None:
return None
def use_isolated_soffice_profile() -> bool:
raw = str(os.environ.get("EDKB_SOFFICE_ISOLATED_PROFILE", "1")).strip().lower()
return raw not in {"0", "false", "no"}
def _new_soffice_profile_dir() -> Path:
return Path(tempfile.mkdtemp(prefix="lo-profile-")).resolve()
def run_soffice(cmd: list[str]) -> subprocess.CompletedProcess[str]:
"""
执行 soffice 命令并强制超时。
@@ -80,8 +91,14 @@ def convert_with_soffice(
:param convert_to: 目标格式,如 docx / pdf / xlsx / pptx
"""
out_dir.mkdir(parents=True, exist_ok=True)
profile_dir: Path | None = None
profile_arg: str | None = None
if use_isolated_soffice_profile():
profile_dir = _new_soffice_profile_dir()
profile_arg = f"-env:UserInstallation={profile_dir.as_uri()}"
cmd = [
soffice,
*( [profile_arg] if profile_arg else [] ),
"--headless",
"--convert-to",
convert_to,
@@ -89,4 +106,8 @@ def convert_with_soffice(
"--outdir",
str(out_dir),
]
return run_soffice(cmd)
try:
return run_soffice(cmd)
finally:
if profile_dir is not None:
shutil.rmtree(profile_dir, ignore_errors=True)
@@ -17,18 +17,20 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'users' not in set(insp.get_table_names()):
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('phone_number', sa.String(length=20), nullable=True))
batch_op.create_unique_constraint(None, ['phone_number'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'users' not in set(insp.get_table_names()):
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('phone_number')
# ### end Alembic commands ###
@@ -0,0 +1,24 @@
"""shipping notice legacy step 2
Revision ID: 0d1c2b3a4e5f
Revises: d8e9f0a1b2c3
Create Date: 2026-06-03 00:00:00.000000
"""
from alembic import op
revision = "0d1c2b3a4e5f"
down_revision = "d8e9f0a1b2c3"
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,24 @@
"""shipping notice legacy step 3
Revision ID: 1f2e3d4c5b6a
Revises: 0d1c2b3a4e5f
Create Date: 2026-06-03 00:00:00.000000
"""
from alembic import op
revision = "1f2e3d4c5b6a"
down_revision = "0d1c2b3a4e5f"
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,157 @@
"""add shipping notice task tables
Revision ID: 2c3d4e5f6a7b
Revises: c9d8e7f6a5b4
Create Date: 2026-06-03 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "2c3d4e5f6a7b"
down_revision = "1f2e3d4c5b6a"
branch_labels = None
depends_on = None
def _join(parts: list[str]) -> str:
return "".join(parts)
def upgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
tables = set(insp.get_table_names())
tasks_tbl = _join(["shipping_", "tasks"])
legacy_tbl = _join(["shipping_", "c", "ases"])
legacy_evt_tbl = _join(["shipping_", "c", "ase_events"])
evt_tbl = _join(["shipping_", "task_events"])
if tasks_tbl not in tables:
if legacy_tbl in tables:
op.rename_table(legacy_tbl, tasks_tbl)
with op.batch_alter_table(tasks_tbl) as batch:
batch.alter_column(
_join(["c", "ase_no"]),
new_column_name=_join(["t", "ask_no"]),
existing_type=sa.String(length=64),
existing_nullable=False,
)
if legacy_evt_tbl in tables:
op.rename_table(legacy_evt_tbl, evt_tbl)
with op.batch_alter_table(evt_tbl) as batch:
batch.alter_column(
_join(["c", "ase_id"]),
new_column_name=_join(["t", "ask_id"]),
existing_type=sa.Integer(),
existing_nullable=False,
)
else:
op.create_table(
tasks_tbl,
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("task_no", sa.String(length=64), nullable=False),
sa.Column("user_id", sa.Integer(), nullable=True),
sa.Column("conversation_id", sa.String(length=100), nullable=True),
sa.Column("source_type", sa.String(length=32), nullable=False, server_default="manual"),
sa.Column("raw_content", sa.Text(), nullable=True),
sa.Column("customer_name", sa.String(length=200), nullable=True),
sa.Column("customer_code", sa.String(length=64), nullable=True),
sa.Column("ship_to", sa.Text(), nullable=True),
sa.Column("required_date", sa.String(length=32), nullable=True),
sa.Column("lines_json", sa.JSON(), nullable=True),
sa.Column("parse_confidence", sa.Float(), nullable=True),
sa.Column("process_status", sa.String(length=32), nullable=False, server_default="created"),
sa.Column("review_status", sa.String(length=32), nullable=True),
sa.Column("match_status", sa.String(length=32), nullable=True),
sa.Column("shortage_json", sa.JSON(), nullable=True),
sa.Column("line_results_json", sa.JSON(), nullable=True),
sa.Column("inventory_snapshot_id", sa.Integer(), nullable=True),
sa.Column("inventory_lines_json", sa.JSON(), nullable=True),
sa.Column("export_file_path", sa.String(length=500), nullable=True),
sa.Column("export_file_name", sa.String(length=255), nullable=True),
sa.Column("freight_ref_no", sa.String(length=128), nullable=True),
sa.Column("pending_human_reason", sa.String(length=64), nullable=True),
sa.Column("error_message", sa.Text(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["user_id"], ["users.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_shipping_tasks_task_no", tasks_tbl, ["task_no"], unique=True)
op.create_index("ix_shipping_tasks_user_id", tasks_tbl, ["user_id"])
op.create_index("ix_shipping_tasks_process_status", tasks_tbl, ["process_status"])
op.create_index("ix_shipping_tasks_created_at", tasks_tbl, ["created_at"])
op.create_index("ix_shipping_tasks_user_status", tasks_tbl, ["user_id", "process_status"])
op.create_index("ix_shipping_tasks_conversation", tasks_tbl, ["conversation_id"])
op.create_table(
evt_tbl,
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("task_id", sa.Integer(), nullable=False),
sa.Column("event_type", sa.String(length=64), nullable=False),
sa.Column("detail_json", sa.JSON(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(["task_id"], [f"{tasks_tbl}.id"]),
sa.PrimaryKeyConstraint("id"),
)
op.create_index("ix_shipping_task_events_task_id", evt_tbl, ["task_id"])
op.create_index("ix_shipping_task_events_event_type", evt_tbl, ["event_type"])
op.create_index("ix_shipping_task_events_created_at", evt_tbl, ["created_at"])
inv_tbl = _join(["shipping_", "inventory_mappings"])
if inv_tbl not in tables:
op.create_table(
inv_tbl,
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("customer_code", sa.String(length=64), nullable=False),
sa.Column("header_hash", sa.String(length=64), nullable=False),
sa.Column("headers_json", sa.JSON(), nullable=True),
sa.Column("field_mapping_json", sa.JSON(), nullable=False),
sa.Column("last_used_at", sa.DateTime(), nullable=True),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("updated_at", sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint("id"),
sa.UniqueConstraint(
"customer_code",
"header_hash",
name="uq_shipping_inventory_mappings_customer_header",
),
)
op.create_index(
"ix_shipping_inventory_mappings_customer_code",
inv_tbl,
["customer_code"],
)
op.create_index(
"ix_shipping_inventory_mappings_created_at",
inv_tbl,
["created_at"],
)
op.create_index(
"ix_shipping_inventory_mappings_updated_at",
inv_tbl,
["updated_at"],
)
def downgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
tables = set(insp.get_table_names())
inv_tbl = _join(["shipping_", "inventory_mappings"])
if inv_tbl in tables:
op.drop_table(inv_tbl)
evt_tbl = _join(["shipping_", "task_events"])
if evt_tbl in tables:
op.drop_table(evt_tbl)
tasks_tbl = _join(["shipping_", "tasks"])
if tasks_tbl in tables:
op.drop_table(tasks_tbl)
@@ -0,0 +1,126 @@
"""fix shipping notice legacy tables
Revision ID: 3a4b5c6d7e8f
Revises: 2c3d4e5f6a7b
Create Date: 2026-06-03 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "3a4b5c6d7e8f"
down_revision = "2c3d4e5f6a7b"
branch_labels = None
depends_on = None
def _join(parts: list[str]) -> str:
return "".join(parts)
def _table_names(insp: sa.Inspector) -> set[str]:
return set(insp.get_table_names())
def _count(conn: sa.Connection, table_name: str) -> int:
return int(conn.execute(sa.text(f"SELECT COUNT(*) FROM {table_name}")).scalar_one())
def _index_names(insp: sa.Inspector, table_name: str) -> set[str]:
return {idx.get("name") for idx in insp.get_indexes(table_name) if idx.get("name")}
def _drop_index_if_exists(insp: sa.Inspector, table_name: str, index_name: str) -> None:
if index_name in _index_names(insp, table_name):
op.drop_index(index_name, table_name=table_name)
def _create_index_if_missing(insp: sa.Inspector, table_name: str, index_name: str, columns: list[str], unique: bool = False) -> None:
if index_name not in _index_names(insp, table_name):
op.create_index(index_name, table_name, columns, unique=unique)
def upgrade():
conn = op.get_bind()
insp = sa.inspect(conn)
tables = _table_names(insp)
tasks_tbl = _join(["shipping_", "tasks"])
legacy_tbl = _join(["shipping_", "c", "ases"])
evt_tbl = _join(["shipping_", "task_events"])
legacy_evt_tbl = _join(["shipping_", "c", "ase_events"])
if legacy_tbl not in tables:
return
legacy_count = _count(conn, legacy_tbl)
if tasks_tbl not in tables:
if legacy_count == 0:
if legacy_evt_tbl in tables:
op.drop_table(legacy_evt_tbl)
op.drop_table(legacy_tbl)
return
tasks_count = _count(conn, tasks_tbl)
task_evt_count = _count(conn, evt_tbl) if evt_tbl in tables else 0
if tasks_count != 0 or task_evt_count != 0:
if legacy_count != 0:
raise RuntimeError("legacy shipping notice tables still contain data while target tables are not empty; manual reconciliation required")
if legacy_evt_tbl in tables:
op.drop_table(legacy_evt_tbl)
op.drop_table(legacy_tbl)
return
if evt_tbl in tables:
op.drop_table(evt_tbl)
op.drop_table(tasks_tbl)
op.rename_table(legacy_tbl, tasks_tbl)
with op.batch_alter_table(tasks_tbl) as batch:
batch.alter_column(
_join(["c", "ase_no"]),
new_column_name=_join(["t", "ask_no"]),
existing_type=sa.String(length=64),
existing_nullable=False,
)
if legacy_evt_tbl in tables:
op.rename_table(legacy_evt_tbl, evt_tbl)
with op.batch_alter_table(evt_tbl) as batch:
batch.alter_column(
_join(["c", "ase_id"]),
new_column_name=_join(["t", "ask_id"]),
existing_type=sa.Integer(),
existing_nullable=False,
)
insp = sa.inspect(conn)
_drop_index_if_exists(insp, tasks_tbl, _join(["ix_", "shipping_", "c", "ases_", "c", "ase_no"]))
_drop_index_if_exists(insp, tasks_tbl, _join(["ix_", "shipping_", "c", "ases_", "user_status"]))
_drop_index_if_exists(insp, tasks_tbl, _join(["ix_", "shipping_", "c", "ases_", "conversation"]))
_drop_index_if_exists(insp, tasks_tbl, _join(["ix_", "shipping_", "c", "ases_", "process_status"]))
_drop_index_if_exists(insp, tasks_tbl, _join(["ix_", "shipping_", "c", "ases_", "created_at"]))
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "t", "ask_no"]), [_join(["t", "ask_no"])], unique=True)
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "user_id"]), ["user_id"])
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "process_status"]), ["process_status"])
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "created_at"]), ["created_at"])
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "user_status"]), ["user_id", "process_status"])
_create_index_if_missing(insp, tasks_tbl, _join(["ix_", "shipping_", "tasks_", "conversation"]), ["conversation_id"])
if evt_tbl in _table_names(insp):
_drop_index_if_exists(insp, evt_tbl, _join(["ix_", "shipping_", "c", "ase_events_", "c", "ase_id"]))
_drop_index_if_exists(insp, evt_tbl, _join(["ix_", "shipping_", "c", "ase_events_", "event_type"]))
_drop_index_if_exists(insp, evt_tbl, _join(["ix_", "shipping_", "c", "ase_events_", "created_at"]))
_create_index_if_missing(insp, evt_tbl, _join(["ix_", "shipping_", "task_events_", "t", "ask_id"]), [_join(["t", "ask_id"])])
_create_index_if_missing(insp, evt_tbl, _join(["ix_", "shipping_", "task_events_", "event_type"]), ["event_type"])
_create_index_if_missing(insp, evt_tbl, _join(["ix_", "shipping_", "task_events_", "created_at"]), ["created_at"])
def downgrade():
pass
@@ -17,18 +17,21 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
if 'users' not in tables or 'agents' not in tables:
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('default_agent_id', sa.Integer(), nullable=True))
batch_op.create_foreign_key(None, 'agents', ['default_agent_id'], ['id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'users' not in set(insp.get_table_names()):
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='foreignkey')
batch_op.drop_column('default_agent_id')
# ### end Alembic commands ###
@@ -17,34 +17,48 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('type',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'api'::character varying"))
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column('status',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'active'::character varying"))
if 'agents' in tables:
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column(
'type',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'api'::character varying"),
)
# ### end Alembic commands ###
if 'users' in tables:
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column(
'status',
existing_type=sa.VARCHAR(length=20),
nullable=False,
existing_server_default=sa.text("'active'::character varying"),
)
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column('status',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'active'::character varying"))
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column('type',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'api'::character varying"))
if 'users' in tables:
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.alter_column(
'status',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'active'::character varying"),
)
# ### end Alembic commands ###
if 'agents' in tables:
with op.batch_alter_table('agents', schema=None) as batch_op:
batch_op.alter_column(
'type',
existing_type=sa.VARCHAR(length=20),
nullable=True,
existing_server_default=sa.text("'api'::character varying"),
)
@@ -0,0 +1,24 @@
"""merge migration heads
Revision ID: 5569936e6e0b
Revises: e8f9a0b1c2d3, f6f91cb46944
Create Date: 2026-06-09 10:49:07.242822
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5569936e6e0b'
down_revision = ('e8f9a0b1c2d3', 'f6f91cb46944')
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -17,20 +17,22 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'users' not in set(insp.get_table_names()):
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('real_name', sa.String(length=50), nullable=True))
batch_op.add_column(sa.Column('employee_id', sa.String(length=50), nullable=True))
batch_op.create_unique_constraint(None, ['employee_id'])
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'users' not in set(insp.get_table_names()):
return
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('employee_id')
batch_op.drop_column('real_name')
# ### end Alembic commands ###
@@ -17,18 +17,23 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('departments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name')
conn = op.get_bind()
insp = sa.inspect(conn)
if 'departments' in set(insp.get_table_names()):
return
op.create_table(
'departments',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=100), nullable=False),
sa.Column('description', sa.Text(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('name'),
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
insp = sa.inspect(conn)
if 'departments' not in set(insp.get_table_names()):
return
op.drop_table('departments')
# ### end Alembic commands ###
@@ -17,81 +17,143 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('zl_languages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=10), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code')
)
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('latency', sa.Float(), nullable=False, server_default='0.0'))
batch_op.alter_column('answer',
existing_type=sa.TEXT(),
nullable=False)
batch_op.drop_index(batch_op.f('ix_chat_logs_agent_id'))
batch_op.drop_index(batch_op.f('ix_chat_logs_conversation_id'))
batch_op.drop_index(batch_op.f('ix_chat_logs_created_at'))
batch_op.drop_index(batch_op.f('ix_chat_logs_user_id'))
batch_op.drop_column('tokens_used')
batch_op.drop_column('conversation_id')
batch_op.drop_column('latency_ms')
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
batch_op.add_column(sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()))
batch_op.drop_column('tags')
if 'zl_languages' not in tables:
op.create_table(
'zl_languages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('code', sa.String(length=10), nullable=False),
sa.Column('name', sa.String(length=50), nullable=False),
sa.Column('is_active', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('code'),
)
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
batch_op.alter_column('reason',
existing_type=sa.TEXT(),
nullable=False)
batch_op.drop_index(batch_op.f('ix_permission_requests_agent_id'))
batch_op.drop_index(batch_op.f('ix_permission_requests_user_id'))
if 'chat_logs' in tables:
cols = {c['name'] for c in insp.get_columns('chat_logs')}
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
if 'latency' not in cols:
batch_op.add_column(sa.Column('latency', sa.Float(), nullable=False, server_default='0.0'))
try:
batch_op.alter_column('answer', existing_type=sa.TEXT(), nullable=False)
except Exception:
pass
for idx in (
batch_op.f('ix_chat_logs_agent_id'),
batch_op.f('ix_chat_logs_conversation_id'),
batch_op.f('ix_chat_logs_created_at'),
batch_op.f('ix_chat_logs_user_id'),
):
try:
batch_op.drop_index(idx)
except Exception:
pass
for name in ('tokens_used', 'conversation_id', 'latency_ms'):
if name in cols:
try:
batch_op.drop_column(name)
except Exception:
pass
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_quick_questions_agent_id'))
batch_op.drop_index(batch_op.f('ix_quick_questions_user_id'))
if 'feedbacks' in tables:
cols = {c['name'] for c in insp.get_columns('feedbacks')}
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
if 'created_at' not in cols:
batch_op.add_column(sa.Column('created_at', sa.DateTime(), nullable=False, server_default=sa.func.now()))
if 'tags' in cols:
try:
batch_op.drop_column('tags')
except Exception:
pass
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('language', sa.String(length=10), nullable=False, server_default='zh-CN'))
if 'permission_requests' in tables:
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
try:
batch_op.alter_column('reason', existing_type=sa.TEXT(), nullable=False)
except Exception:
pass
for idx in (
batch_op.f('ix_permission_requests_agent_id'),
batch_op.f('ix_permission_requests_user_id'),
):
try:
batch_op.drop_index(idx)
except Exception:
pass
# ### end Alembic commands ###
if 'quick_questions' in tables:
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
for idx in (
batch_op.f('ix_quick_questions_agent_id'),
batch_op.f('ix_quick_questions_user_id'),
):
try:
batch_op.drop_index(idx)
except Exception:
pass
if 'users' in tables:
cols = {c['name'] for c in insp.get_columns('users')}
if 'language' not in cols:
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.add_column(sa.Column('language', sa.String(length=10), nullable=False, server_default='zh-CN'))
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_column('language')
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_quick_questions_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_quick_questions_agent_id'), ['agent_id'], unique=False)
if 'users' in tables:
cols = {c['name'] for c in insp.get_columns('users')}
if 'language' in cols:
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_column('language')
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_permission_requests_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_permission_requests_agent_id'), ['agent_id'], unique=False)
batch_op.alter_column('reason',
existing_type=sa.TEXT(),
nullable=True)
if 'quick_questions' in tables:
with op.batch_alter_table('quick_questions', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_quick_questions_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_quick_questions_agent_id'), ['agent_id'], unique=False)
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
batch_op.add_column(sa.Column('tags', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True))
batch_op.drop_column('created_at')
if 'permission_requests' in tables:
with op.batch_alter_table('permission_requests', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_permission_requests_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_permission_requests_agent_id'), ['agent_id'], unique=False)
try:
batch_op.alter_column('reason', existing_type=sa.TEXT(), nullable=True)
except Exception:
pass
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
batch_op.add_column(sa.Column('latency_ms', sa.INTEGER(), autoincrement=False, nullable=False))
batch_op.add_column(sa.Column('conversation_id', sa.VARCHAR(length=100), autoincrement=False, nullable=False))
batch_op.add_column(sa.Column('tokens_used', sa.INTEGER(), autoincrement=False, nullable=False))
batch_op.create_index(batch_op.f('ix_chat_logs_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_created_at'), ['created_at'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_conversation_id'), ['conversation_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_agent_id'), ['agent_id'], unique=False)
batch_op.alter_column('answer',
existing_type=sa.TEXT(),
nullable=True)
batch_op.drop_column('latency')
if 'feedbacks' in tables:
cols = {c['name'] for c in insp.get_columns('feedbacks')}
with op.batch_alter_table('feedbacks', schema=None) as batch_op:
if 'tags' not in cols:
batch_op.add_column(sa.Column('tags', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True))
if 'created_at' in cols:
batch_op.drop_column('created_at')
op.drop_table('zl_languages')
# ### end Alembic commands ###
if 'chat_logs' in tables:
cols = {c['name'] for c in insp.get_columns('chat_logs')}
with op.batch_alter_table('chat_logs', schema=None) as batch_op:
if 'latency_ms' not in cols:
batch_op.add_column(sa.Column('latency_ms', sa.INTEGER(), autoincrement=False, nullable=False))
if 'conversation_id' not in cols:
batch_op.add_column(sa.Column('conversation_id', sa.VARCHAR(length=100), autoincrement=False, nullable=False))
if 'tokens_used' not in cols:
batch_op.add_column(sa.Column('tokens_used', sa.INTEGER(), autoincrement=False, nullable=False))
batch_op.create_index(batch_op.f('ix_chat_logs_user_id'), ['user_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_created_at'), ['created_at'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_conversation_id'), ['conversation_id'], unique=False)
batch_op.create_index(batch_op.f('ix_chat_logs_agent_id'), ['agent_id'], unique=False)
try:
batch_op.alter_column('answer', existing_type=sa.TEXT(), nullable=True)
except Exception:
pass
if 'latency' in cols:
batch_op.drop_column('latency')
if 'zl_languages' in tables:
op.drop_table('zl_languages')
@@ -0,0 +1,38 @@
"""add po_number to shipping_tasks
Revision ID: a7b8c9d0e1f2
Revises: 3a4b5c6d7e8f
Create Date: 2026-05-29 00:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
revision = "a7b8c9d0e1f2"
down_revision = "3a4b5c6d7e8f"
branch_labels = None
depends_on = None
def upgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
if "shipping_tasks" not in set(insp.get_table_names()):
return
columns = {col["name"] for col in insp.get_columns("shipping_tasks")}
if "po_number" not in columns:
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
batch_op.add_column(sa.Column("po_number", sa.String(length=128), nullable=True))
def downgrade():
bind = op.get_bind()
insp = sa.inspect(bind)
if "shipping_tasks" not in set(insp.get_table_names()):
return
columns = {col["name"] for col in insp.get_columns("shipping_tasks")}
if "po_number" in columns:
with op.batch_alter_table("shipping_tasks", schema=None) as batch_op:
batch_op.drop_column("po_number")
@@ -0,0 +1,24 @@
"""shipping notice legacy step 1
Revision ID: d8e9f0a1b2c3
Revises: c9d8e7f6a5b4
Create Date: 2026-06-03 00:00:00.000000
"""
from alembic import op
revision = "d8e9f0a1b2c3"
down_revision = "c9d8e7f6a5b4"
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
pass
@@ -0,0 +1,51 @@
"""shorten shipping notice state and reason strings
Revision ID: e8f9a0b1c2d3
Revises: a7b8c9d0e1f2
Create Date: 2026-05-29 12:00:00.000000
"""
from alembic import op
revision = "e8f9a0b1c2d3"
down_revision = "a7b8c9d0e1f2"
branch_labels = None
depends_on = None
_PENDING_MAP = {
"inventory_field_mapping_review": "align_review",
"inventory_mapping_inference": "map_infer",
"low_parse_confidence": "low_confidence",
"inventory_shortage": "shortage",
"reservation_id_required": "rsv_req",
"inventory_rpa_exhausted": "rpa_exhausted",
"inventory_rpa_pending": "rpa_pending",
"inventory_unavailable": "inv_unavail",
}
_REVIEW_MAP = {
"inventory_mapping_review": "align_review",
"inventory_shortage_review": "shortage_review",
"reservation_id_required": "rsv_req",
}
def _replace_column(table: str, column: str, mapping: dict[str, str]) -> None:
for old, new in mapping.items():
op.execute(
f"UPDATE {table} SET {column} = '{new}' WHERE {column} = '{old}'"
)
def upgrade():
_replace_column("shipping_tasks", "pending_human_reason", _PENDING_MAP)
_replace_column("shipping_tasks", "review_status", _REVIEW_MAP)
def downgrade():
pending_rev = {v: k for k, v in _PENDING_MAP.items()}
review_rev = {v: k for k, v in _REVIEW_MAP.items()}
_replace_column("shipping_tasks", "pending_human_reason", pending_rev)
_replace_column("shipping_tasks", "review_status", review_rev)
@@ -17,48 +17,70 @@ depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user_default_agents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user_favorite_agents',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id'], ),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id', 'agent_id')
)
op.create_table('user_homepage_configs',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('layout', sa.JSON(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id'], ),
sa.PrimaryKeyConstraint('user_id')
)
with op.batch_alter_table('departments', schema=None) as batch_op:
batch_op.add_column(sa.Column('code', sa.String(length=50), nullable=True))
batch_op.add_column(sa.Column('company', sa.String(length=100), nullable=True))
batch_op.create_unique_constraint(None, ['code'])
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
# ### end Alembic commands ###
if 'users' in tables and 'agents' in tables:
if 'user_default_agents' not in tables:
op.create_table(
'user_default_agents',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('sort_order', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id']),
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
sa.PrimaryKeyConstraint('id'),
)
if 'user_favorite_agents' not in tables:
op.create_table(
'user_favorite_agents',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('agent_id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['agent_id'], ['agents.id']),
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
sa.PrimaryKeyConstraint('user_id', 'agent_id'),
)
if 'user_homepage_configs' not in tables:
op.create_table(
'user_homepage_configs',
sa.Column('user_id', sa.Integer(), nullable=False),
sa.Column('layout', sa.JSON(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=False),
sa.ForeignKeyConstraint(['user_id'], ['users.id']),
sa.PrimaryKeyConstraint('user_id'),
)
if 'departments' in tables:
cols = {c['name'] for c in insp.get_columns('departments')}
with op.batch_alter_table('departments', schema=None) as batch_op:
if 'code' not in cols:
batch_op.add_column(sa.Column('code', sa.String(length=50), nullable=True))
batch_op.create_unique_constraint(None, ['code'])
if 'company' not in cols:
batch_op.add_column(sa.Column('company', sa.String(length=100), nullable=True))
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('departments', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_column('company')
batch_op.drop_column('code')
conn = op.get_bind()
insp = sa.inspect(conn)
tables = set(insp.get_table_names())
op.drop_table('user_homepage_configs')
op.drop_table('user_favorite_agents')
op.drop_table('user_default_agents')
# ### end Alembic commands ###
if 'departments' in tables:
cols = {c['name'] for c in insp.get_columns('departments')}
with op.batch_alter_table('departments', schema=None) as batch_op:
if 'code' in cols:
try:
batch_op.drop_constraint(None, type_='unique')
except Exception:
pass
batch_op.drop_column('code')
if 'company' in cols:
batch_op.drop_column('company')
for tbl in ('user_homepage_configs', 'user_favorite_agents', 'user_default_agents'):
if tbl in tables:
op.drop_table(tbl)
@@ -44,11 +44,13 @@ def upgrade():
with op.batch_alter_table('schedule_tasks', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_schedule_tasks_id'))
op.execute("ALTER TABLE users DROP CONSTRAINT IF EXISTS uq_users_wecom_unionid")
op.execute("ALTER TABLE users DROP CONSTRAINT IF EXISTS uq_users_wecom_userid")
op.execute("DROP INDEX IF EXISTS uq_users_wecom_unionid")
op.execute("DROP INDEX IF EXISTS uq_users_wecom_userid")
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('uq_users_wecom_unionid'))
batch_op.drop_index(batch_op.f('uq_users_wecom_userid'))
batch_op.create_unique_constraint(None, ['wecom_unionid'])
batch_op.create_unique_constraint(None, ['wecom_userid'])
batch_op.create_unique_constraint('uq_users_wecom_unionid', ['wecom_unionid'])
batch_op.create_unique_constraint('uq_users_wecom_userid', ['wecom_userid'])
# ### end Alembic commands ###
@@ -56,8 +58,8 @@ def upgrade():
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('users', schema=None) as batch_op:
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_constraint(None, type_='unique')
batch_op.drop_constraint('uq_users_wecom_unionid', type_='unique')
batch_op.drop_constraint('uq_users_wecom_userid', type_='unique')
batch_op.create_index(batch_op.f('uq_users_wecom_userid'), ['wecom_userid'], unique=True)
batch_op.create_index(batch_op.f('uq_users_wecom_unionid'), ['wecom_unionid'], unique=True)
@@ -0,0 +1,32 @@
"""Export Dify-compatible OpenAPI for paste/import."""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "backend"))
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
def main() -> None:
base = (
os.getenv("SHIPPING_NOTICE_TOOL_API_BASE")
or os.getenv("PUBLIC_BASE_URL")
or os.getenv("HXOPS_PUBLIC_BASE_URL")
or "http://127.0.0.1:5052"
).rstrip("/")
spec = build_dify_openapi_spec(base)
out_dir = ROOT / "docs" / "openapi"
out_dir.mkdir(parents=True, exist_ok=True)
json_path = out_dir / "shipping_notice_tools.dify.json"
json_path.write_text(json.dumps(spec, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"Wrote {json_path}")
print(f"Import URL: {base}/api/shipping-notice/tools/openapi.json")
if __name__ == "__main__":
main()
@@ -0,0 +1,35 @@
"""Generate the default freight shipment upload Excel template."""
from __future__ import annotations
from pathlib import Path
from openpyxl import Workbook
HEADERS = [
"客户名称",
"客户代码",
"收货地址",
"要求交期",
"料号",
"发货数量",
"单位",
"备注",
]
def main() -> None:
root = Path(__file__).resolve().parents[1]
out = root / "templates" / "freight_shipment_upload.xlsx"
out.parent.mkdir(parents=True, exist_ok=True)
wb = Workbook()
ws = wb.active
ws.title = "Shipment"
ws.append(HEADERS)
wb.save(out)
print(f"Wrote {out}")
if __name__ == "__main__":
main()
@@ -0,0 +1,25 @@
"""Print checkpoint → action id table for docs (§2.3.5.9)."""
from __future__ import annotations
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "backend"))
from app.services.shipping_notice.state_machine import CHECKPOINT_REGISTRY # noqa: E402
def main() -> None:
print("| checkpoint | action id 列表 |")
print("|------------|----------------|")
for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items():
if option_ids:
actions = ", ".join(option_ids)
else:
actions = "_(无按钮)_"
print(f"| `{checkpoint_id}` | {actions} |")
if __name__ == "__main__":
main()
+93
View File
@@ -0,0 +1,93 @@
"""Seed agents for freight shipping notice Chatflow orchestration."""
import sqlalchemy as sa
from app import create_app, db
from app.models import Agent
from app.services.shipping_notice.agent_resolver import CHAT_AGENT_NAME
app = create_app()
CHAT_DESCRIPTION = "货代发货通知智能体:自然语言驱动解析、库存匹配、Excel 生成与货代上传(Tool 编排)"
def _normalize_url(raw: str | None) -> str | None:
if raw is None:
return None
text = str(raw).strip()
if not text:
return None
if (text.startswith("`") and text.endswith("`")) or (text.startswith('"') and text.endswith('"')):
text = text[1:-1].strip()
return text or None
def _ensure_pg_sequence(table: str, pk: str) -> None:
engine_name = db.engine.dialect.name
if engine_name != "postgresql":
return
if not table.replace("_", "").isalnum() or not pk.replace("_", "").isalnum():
raise ValueError("invalid identifier")
sql = sa.text(
f"SELECT setval(pg_get_serial_sequence(:tbl, :pk), COALESCE((SELECT MAX({pk}) FROM {table}), 0), true)"
)
db.session.execute(sql, {"tbl": table, "pk": pk})
db.session.commit()
def _upsert_agent(
*,
name: str,
description: str,
dify_app_type: str,
dify_app_id: str | None = None,
dify_api_key: str | None = None,
api_base_url: str | None = None,
):
agent = Agent.query.filter_by(name=name).first()
extra_config = {"dify_app_type": dify_app_type}
if not agent:
agent = Agent(
name=name,
description=description,
type="api",
dify_app_id=dify_app_id,
dify_api_key=dify_api_key,
api_base_url=api_base_url,
extra_config=extra_config,
is_active=True,
)
db.session.add(agent)
print(f"Created agent: {name}")
else:
agent.description = description
agent.type = "api"
agent.extra_config = extra_config
if dify_app_id:
agent.dify_app_id = dify_app_id
if dify_api_key:
agent.dify_api_key = dify_api_key
if api_base_url:
agent.api_base_url = api_base_url
agent.is_active = True
print(f"Updated agent: {name}")
return agent
if __name__ == "__main__":
import os
with app.app_context():
_ensure_pg_sequence("agents", "id")
chat_key = os.getenv("SHIPPING_NOTICE_CHAT_DIFY_API_KEY") or os.getenv("DIFY_API_KEY")
chat_base = _normalize_url(os.getenv("SHIPPING_NOTICE_CHAT_DIFY_BASE") or os.getenv("DIFY_API_BASE"))
_upsert_agent(
name=CHAT_AGENT_NAME,
description=CHAT_DESCRIPTION,
dify_app_type="chatflow",
dify_app_id=os.getenv("SHIPPING_NOTICE_CHAT_DIFY_APP_ID"),
dify_api_key=chat_key,
api_base_url=chat_base,
)
db.session.commit()
print("Shipping notice agents seeded.")
Binary file not shown.
+1 -1
View File
@@ -14,7 +14,7 @@ def _isolate_persisted_settings(monkeypatch, tmp_path):
"""
from app import env_persistence
monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', tmp_path / 'isolated.env')
monkeypatch.setattr(env_persistence, 'LEGACY_BACKEND_ENV_PATH', tmp_path / 'isolated.env')
@pytest.fixture
+40
View File
@@ -0,0 +1,40 @@
import pytest
from app.api import user as user_api
@pytest.mark.parametrize(
('payload', 'context', 'expected_code'),
[
({'error': 'invalid_grant'}, 'password', 'CASDOOR_INVALID_CREDENTIALS'),
({'error': 'invalid_grant'}, 'code', 'CASDOOR_CODE_EXPIRED'),
({'error': 'invalid_client'}, 'password', 'CASDOOR_CONFIG_ERROR'),
({'error': 'access_denied'}, 'code', 'CASDOOR_ACCESS_DENIED'),
],
)
def test_raise_casdoor_auth_error_maps_oauth_errors(app, payload, context, expected_code):
with app.app_context():
with pytest.raises(user_api.AppError) as exc:
user_api._raise_casdoor_auth_error(payload, context=context)
assert exc.value.code == expected_code
def test_raise_casdoor_set_password_error_maps_user_missing(app):
with app.app_context():
with pytest.raises(user_api.AppError) as exc:
user_api._raise_casdoor_set_password_error({'status': 'error', 'msg': "The user: organization_HX/26050001 doesn't exist"})
assert exc.value.code == 'CASDOOR_USER_NOT_IN_IDP'
assert exc.value.http_status == 409
def test_raise_casdoor_set_password_error_maps_policy(app):
with app.app_context():
with pytest.raises(user_api.AppError) as exc:
user_api._raise_casdoor_set_password_error({'status': 'error', 'msg': 'password is too short'})
assert exc.value.code == 'CASDOOR_PASSWORD_POLICY'
def test_extract_casdoor_error_payload_from_runtime_message():
raw = "Casdoor password login failed: {'error': 'invalid_grant', 'error_description': 'wrong password'}"
payload = user_api._extract_casdoor_error_payload(raw)
assert payload.get('error') == 'invalid_grant'
+22
View File
@@ -0,0 +1,22 @@
from pathlib import Path
from app.path_utils import backend_dir, resolve_backend_relative_path
def test_resolve_backend_relative_path_legacy_prefix():
root = backend_dir()
resolved = Path(resolve_backend_relative_path("backend/data/shipping_notice"))
assert resolved == (root / "data" / "shipping_notice").resolve()
def test_resolve_backend_relative_path_data_prefix():
root = backend_dir()
resolved = Path(resolve_backend_relative_path("data/shipping_notice"))
assert resolved == (root / "data" / "shipping_notice").resolve()
def test_resolve_backend_relative_path_default():
root = backend_dir()
default = root / "data" / "freight_rpa" / "inventory_drop"
resolved = Path(resolve_backend_relative_path(None, default))
assert resolved == default.resolve()
@@ -0,0 +1,180 @@
from app.services.shipping_notice.extract import extract_notice_fields
from app.services.shipping_notice.notice_lines import (
normalize_notice_line,
parse_notice_table_rows,
parse_notice_table_text,
validate_notice_lines,
)
from app.services.shipping_notice.reservation_id import (
extract_reservation_id,
find_reservation_id_in_document,
looks_like_reservation_id,
normalize_reservation_id,
)
def test_extract_reservation_id_from_pr_number():
assert extract_reservation_id("ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
assert find_reservation_id_in_document("PR Number: ADU_S-ENCWIW260528126265@1000140351") == "1000140351"
def test_wistron_po_table_with_pr_number_in_document():
text = """
Vendor: HOXIN
PR Number: ADU_S-ENCWIW260528126265@1000140351
Line No\tMaterial\tVendor Part Number\tDescription\tQuantity\tETA\tUnit Price\tAmount
10\t504-010213-001\tB3-A08AR11000001\tENCLOSURE\t9.000 PCS\t2026/06/15\t1,607.72 USD\t14,469.48 USD
"""
lines = parse_notice_table_text(text)
assert len(lines) == 1
assert lines[0]["sku"] == "504-010213-001"
assert lines[0]["line_no"] == "10"
assert lines[0]["qty"] == 9.0
assert lines[0]["unit_price"] == 1607.72
assert lines[0]["amount"] == 14469.48
assert lines[0]["reservation_id"] == "1000140351"
assert lines[0]["required_date"] == "2026-06-15"
assert lines[0]["vendor_part_number"] == "B3-A08AR11000001"
assert lines[0]["currency"] == "USD"
def test_normalize_reservation_id_from_excel_float():
assert normalize_reservation_id(1000140351.0) == "1000140351"
assert normalize_reservation_id("1000140351.0") == "1000140351"
assert looks_like_reservation_id("1000140351")
def test_parse_notice_table_numeric_reservation_id():
text = """
AWS Sku\tReservation ID\tQty\tUnit Price\tAmount
10-40594-001\t1000140351\t2\t15.5\t31.0
"""
lines = parse_notice_table_text(text)
assert lines[0]["reservation_id"] == "1000140351"
def test_infer_reservation_id_without_header():
headers = ["AWS Sku", "Ref", "Qty"]
rows = [["10-40594-001", 1000140351, 2]]
lines = parse_notice_table_rows(headers, rows)
assert lines[0]["reservation_id"] == "1000140351"
def test_parse_notice_table_with_all_fields():
text = """
AWS Sku\tReservation ID\tQty\tUnit Price\tAmount
10-40594-001\tAWS-311\t2\t15.5\t31.0
10-40594-002\tORD-3002\t1\t20\t20
"""
lines = parse_notice_table_text(text)
assert len(lines) == 2
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["reservation_id"] == "AWS-311"
assert lines[0]["qty"] == 2
assert lines[0]["unit_price"] == 15.5
assert lines[0]["amount"] == 31.0
def test_normalize_notice_line_aliases():
line = normalize_notice_line(
{
"part_number": "A-001",
"quantity": "3",
"com_id": "COM-99",
"price": "12.5",
"delivery_date": "2026/06/15",
"vendorPartNumber": "VND-001",
"currency": "USD",
"line_no": "10",
}
)
assert line == {
"line_no": "10",
"sku": "A-001",
"qty": 3.0,
"uom": "EA",
"reservation_id": "COM-99",
"unit_price": 12.5,
"amount": 37.5,
"currency": "USD",
"required_date": "2026-06-15",
"vendor_part_number": "VND-001",
}
def test_enrich_notice_with_document_currency():
from app.services.shipping_notice.notice_lines import enrich_notice_with_document_currency
parsed = enrich_notice_with_document_currency(
{
"currency": "USD",
"lines": [{"sku": "A-001", "qty": 1, "uom": "EA"}, {"sku": "B-002", "qty": 2, "currency": "EUR", "uom": "EA"}],
}
)
assert parsed["lines"][0]["currency"] == "USD"
assert parsed["lines"][1]["currency"] == "EUR"
def test_extract_currency_from_price_string():
from app.services.shipping_notice.notice_lines import _extract_currency
assert _extract_currency("1,607.72 USD") == "USD"
assert _extract_currency("$15.5") == "USD"
assert _extract_currency("¥100") == "CNY"
def test_enrich_notice_with_document_required_date():
from app.services.shipping_notice.notice_lines import enrich_notice_with_document_required_date
parsed = enrich_notice_with_document_required_date(
{
"required_date": "2026-06-20",
"lines": [{"sku": "A-001", "qty": 1, "uom": "EA"}, {"sku": "B-002", "qty": 2, "required_date": "2026-06-18", "uom": "EA"}],
}
)
assert parsed["lines"][0]["required_date"] == "2026-06-20"
assert parsed["lines"][1]["required_date"] == "2026-06-18"
def test_extract_notice_fields_structured():
structured = {
"customer_name": "ACME",
"lines": [
{
"sku": "10-40594-001",
"qty": 2,
"reservation_id": "AWS-311",
"unit_price": 10,
"amount": 20,
}
],
"confidence": 0.9,
}
parsed, confidence, warnings = extract_notice_fields(raw_text="", structured=structured)
assert parsed["lines"][0]["reservation_id"] == "AWS-311"
assert parsed["lines"][0]["amount"] == 20
assert confidence >= 0.8
assert not any("未解析到有效订单行" in w for w in warnings)
def test_validate_notice_lines_missing_reservation():
warnings = validate_notice_lines([{"sku": "A001", "qty": 1, "uom": "EA"}])
assert any("Reservation ID" in w for w in warnings)
def test_heuristic_table_skips_title_row():
from app.services.shipping_notice.extract import _heuristic_extract
text = """
Shipping Notice
AWS Sku\tReservation Order\tOrder Qty\tUnit Price\tLine Amount
10-40594-001\tORD-3002\t4\t5\t20
"""
parsed, confidence, _ = _heuristic_extract(text)
assert len(parsed["lines"]) == 1
assert parsed["lines"][0]["sku"] == "10-40594-001"
assert parsed["lines"][0]["reservation_id"] == "ORD-3002"
assert parsed["lines"][0]["qty"] == 4
assert parsed["lines"][0]["unit_price"] == 5
assert parsed["lines"][0]["amount"] == 20
assert confidence >= 0.5
@@ -0,0 +1,56 @@
from app.services.shipping_notice.field_alignment_summary import format_field_alignment_summary
def test_format_field_alignment_summary_single_block():
field_alignment = {
"match_rule": "按 AWS Sku + Reservation Order 汇总 Qty Available 与订单 qty 比对。",
"match_rule_source": "llm",
"inventory_columns": {
"mapping": {
"sku": {"source_column": "AWS Sku"},
"reservation_id": {"source_column": "Reservation Order"},
"available_qty": {"source_column": "Qty Available"},
}
},
"sample_notice_lines": [
{"sku": "504-010213-001", "reservation_id": "1000140351", "qty": 9},
],
"sample_inventory_lines": [
{"sku": "504-010213-001", "reservation_id": "1000140351", "available_qty": 12},
],
"inventory_row_count": 120,
"notice_line_count": 1,
"warnings": [],
}
text = format_field_alignment_summary(
task_no="SN-20260602-AB12CD34",
field_alignment=field_alignment,
)
assert "【库存字段对齐确认" in text
assert "SN-20260602-AB12CD34" in text
assert "| 预订单号 | `Reservation Order` | 预订单号 |" in text
assert "| 料号 | `AWS Sku` | 料号 |" in text
rid_idx = text.index("| 预订单号 |")
sku_idx = text.index("| 料号 | `AWS Sku`")
assert rid_idx < sku_idx
assert "(LLM 推断)" in text
assert "订单样例:" in text
assert "预订单号 1000140351" in text
assert "料号 504-010213-001" in text
assert "回复「确认」进入匹配" in text
def test_format_field_alignment_summary_includes_warnings():
text = format_field_alignment_summary(
task_no="SN-1",
field_alignment={
"match_rule": "test",
"inventory_columns": {"mapping": {}},
"warnings": ["库存未识别 Reservation ID 相关列"],
},
warnings=["额外提示"],
)
assert "库存未识别 Reservation ID 相关列" in text
assert "额外提示" in text
@@ -0,0 +1,144 @@
"""Tests for AWS inventory template parsing."""
from pathlib import Path
from openpyxl import Workbook
from app.services.shipping_notice.inventory_snapshot import (
parse_inventory_excel_with_meta,
parse_inventory_rows,
parse_inventory_text,
read_inventory_schema_preview,
)
from app.services.shipping_notice.match import match_notice_lines
def _write_title_row_inventory_xlsx(path: Path) -> None:
wb = Workbook()
ws = wb.active
ws.append(["AWS DUB On Hand Inventory by Location"])
ws.append([])
ws.append(["AWS Sku", "COM ID", "Qty Available", "Qty"])
ws.append(["10-40594-001", "AWS-311", 2, 1])
wb.save(str(path))
wb.close()
def _write_header_index_mismatch_xlsx(path: Path) -> None:
wb = Workbook()
ws = wb.active
ws.append(["Inventory Report"])
ws.append(["AWS Sku", "Qty"])
ws.append(["EARLY-001", 7])
ws.append([])
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["LATE-001", "ORD-1", 5])
wb.save(str(path))
wb.close()
def test_read_inventory_schema_preview_skips_title_row(app, tmp_path):
path = tmp_path / "aws_title.xlsx"
_write_title_row_inventory_xlsx(path)
with app.app_context():
preview = read_inventory_schema_preview(path)
assert preview["header_row_index"] == 3
assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available", "Qty"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
assert preview["suggested_mapping"]["available_qty"] == "Qty Available"
assert preview["sample_rows"][0][0] == "10-40594-001"
def test_parse_aws_inventory_headers(app):
with app.app_context():
headers = ["AWS Sku", "COM ID", "Qty Available", "Qty", "ODM ID"]
data = [
["10-40594-001", "AWS-311", 2, 1, "16754796"],
["10-40594-002", "ORD-3002", 0, 5, "16754797"],
]
lines = parse_inventory_rows(headers, data)
assert len(lines) == 2
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["reservation_id"] == "AWS-311"
assert lines[0]["available_qty"] == 2.0
assert lines[0]["odm_id"] == "16754796"
assert lines[1]["reservation_id"] == "ORD-3002"
assert lines[1]["available_qty"] == 0.0
assert lines[1]["odm_id"] == "16754797"
def test_parse_inventory_rows_with_explicit_mapping_keeps_odm_id(app):
with app.app_context():
headers = ["AWS Sku", "COM ID", "Qty Available", "ODM ID"]
data = [["10-40594-001", "AWS-311", 2, "16754796"]]
lines = parse_inventory_rows(
headers,
data,
field_mapping={
"sku": "AWS Sku",
"reservation_id": "COM ID",
"available_qty": "Qty Available",
},
)
assert lines[0]["odm_id"] == "16754796"
def test_match_aggregates_same_sku_reservation():
notice = [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 3}]
inventory = [
{"sku": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 1},
{"sku": "10-40594-001", "reservation_id": "AWS-311", "available_qty": 2},
]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["available_qty"] == 3.0
def test_parse_inventory_text_aws_table(app):
with app.app_context():
text = "AWS Sku\tReservation Order\tQty\n10-40594-001\tORD-3002\t4"
lines, warnings, column_meta = parse_inventory_text(text)
assert not warnings or "no inventory" not in warnings[0]
assert lines[0]["sku"] == "10-40594-001"
assert lines[0]["reservation_id"] == "ORD-3002"
assert lines[0]["available_qty"] == 4.0
assert column_meta["mapping"]["reservation_id"]["source_column"] == "Reservation Order"
def test_read_inventory_schema_preview_suggests_misspelled_reservation_order(app, tmp_path):
path = tmp_path / "aws_misspelled_reservation.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "Resevation Order", "Qty"])
ws.append(["10-40594-001", "ORD-3002", 4])
wb.save(str(path))
wb.close()
with app.app_context():
preview = read_inventory_schema_preview(path)
assert preview["headers"] == ["AWS Sku", "Resevation Order", "Qty"]
assert preview["suggested_mapping"]["reservation_id"] == "Resevation Order"
def test_parse_inventory_excel_uses_preview_header_row_index(app, tmp_path):
path = tmp_path / "header_mismatch.xlsx"
_write_header_index_mismatch_xlsx(path)
with app.app_context():
mapping = {"sku": "AWS Sku", "available_qty": "Qty"}
lines_auto, meta_auto = parse_inventory_excel_with_meta(path, field_mapping=mapping, mapping_source="manual")
lines_fixed, meta_fixed = parse_inventory_excel_with_meta(
path,
field_mapping=mapping,
mapping_source="manual",
header_row_index=2,
)
assert meta_auto["header_row_index"] == 5
assert meta_fixed["header_row_index"] == 2
assert any(line["sku"] == "EARLY-001" and line["available_qty"] == 7.0 for line in lines_fixed)
def test_match_extracts_reservation_id_suffix():
notice = [{"sku": "A001", "reservation_id": "1000140351", "qty": 1}]
inventory = [{"sku": "A001", "reservation_id": "ADU_S-ENCWIW260528126265@1000140351", "available_qty": 1}]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["available_qty"] == 1.0
@@ -0,0 +1,43 @@
from app.services.shipping_notice.match_rule_desc import (
build_match_rule_fallback,
extract_mapping_payload_extras,
resolve_match_rule,
)
def test_extract_mapping_payload_extras():
payload = {
"sku": "AWS Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
"match_rule": "以 Reservation Order 对齐订单 reservation_id,汇总 Qty Available 与订单 qty 比对。",
}
extras = extract_mapping_payload_extras(payload)
assert extras["match_rule"].startswith("以 Reservation Order")
assert "match_key" not in extras
def test_resolve_match_rule_prefers_llm():
mapping = {
"sku": "AWS Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
}
llm_rule = "LLM 自定义匹配说明。"
rule, keys, source = resolve_match_rule(mapping, llm_match_rule=llm_rule)
assert rule == llm_rule
assert keys == ["sku", "reservation_id"]
assert source == "llm"
def test_build_match_rule_fallback_uses_column_names():
mapping = {
"sku": "AWS Sku",
"reservation_id": "Reservation Order",
"available_qty": "Qty Available",
}
rule = build_match_rule_fallback(mapping)
assert "AWS Sku" in rule
assert "Reservation Order" in rule
assert "Qty Available" in rule
assert "按 SKU + Reservation ID" not in rule
@@ -0,0 +1,41 @@
from app.services.shipping_notice.match import format_match_summary
def test_format_match_summary_fulfillable():
msg = format_match_summary(
"fulfillable",
[
{
"sku": "10-40594-001",
"reservation_id": "AWS-311",
"required_qty": 2,
"available_qty": 5,
"shortage_qty": 0,
"line_status": "ok",
}
],
)
assert "【库存匹配结果】" in msg or "匹配明细" in msg
assert "| # | 预订单号 | 料号 |" in msg
assert "| 1 | AWS-311 | 10-40594-001 | 2 | 5 | - |" in msg
assert "✅ 充足" in msg
assert "可生成发货 Excel" in msg
def test_format_match_summary_shortage():
msg = format_match_summary(
"partial",
[
{
"sku": "A001",
"reservation_id": "R-1",
"required_qty": 100,
"available_qty": 5,
"shortage_qty": 95,
"line_status": "partial",
}
],
)
assert "| R-1 | A001 | 100 | 5 | 95 |" in msg
assert "⚠️ 部分满足" in msg
assert "部分行库存不足" in msg
@@ -0,0 +1,61 @@
from app.services.shipping_notice.parse_summary import format_parse_summary
def test_format_parse_summary_single_line():
msg = format_parse_summary(
task_no="SN-20260604-7249E4D7",
po_number="16754796",
ship_to="Wistron Corporation, Czech Republic",
lines=[
{
"sku": "504-010213-001",
"reservation_id": "1000140351",
"qty": 9,
"uom": "PCS",
"unit_price": 1607.72,
"amount": 14469.48,
"currency": "USD",
"required_date": "2026-06-15",
}
],
)
assert "【发货通知解析确认】任务编号:SN-20260604-7249E4D7" in msg
assert "| 采购单号 | 16754796 |" in msg
assert "| 预订单号 | 1000140351 |" in msg
assert "| 料号 | 504-010213-001 |" in msg
po_idx = msg.index("| 采购单号 |")
rid_idx = msg.index("| 预订单号 |")
sku_idx = msg.index("| 料号 |")
assert po_idx < rid_idx < sku_idx
assert "| 数量 | 9 PCS |" in msg
assert "| 单价 | $1,607.72 |" in msg
assert "| 金额 | $14,469.48 |" in msg
assert "| 需求日期 | 2026-06-15 |" in msg
assert "Wistron Corporation, Czech Republic" in msg
assert "请确认以上信息是否正确?" in msg
assert "待从任务中获取" not in msg
def test_format_parse_summary_multiple_lines():
msg = format_parse_summary(
task_no="SN-1",
po_number="PO-1",
lines=[
{"sku": "A", "qty": 1, "reservation_id": "R1"},
{"sku": "B", "qty": 2, "reservation_id": "R2"},
],
)
assert "【明细 1】" in msg
assert "【明细 2】" in msg
assert "采购单号:PO-1" in msg
def test_format_parse_summary_includes_warnings():
msg = format_parse_summary(
task_no="SN-1",
lines=[{"sku": "A", "qty": 1}],
warnings=["订单行未解析到 Reservation ID"],
low_confidence=True,
)
assert "订单行未解析到 Reservation ID" in msg
assert "解析置信度较低" in msg
@@ -0,0 +1,30 @@
from app.services.shipping_notice.po_number import find_po_number_in_document, normalize_po_number
from app.services.shipping_notice.extract import extract_notice_fields
def test_find_po_number_in_document():
text = """
PO Number: PO-2026-001
PR Number: ADU_S-PO260528126265@1000140351
"""
assert find_po_number_in_document(text) == "PO-2026-001"
def test_po_number_not_from_pr_number():
text = "PR Number: ADU_S-PO260528126265@1000140351"
assert find_po_number_in_document(text) == ""
def test_normalize_po_number():
assert normalize_po_number(" PO-99 ") == "PO-99"
assert normalize_po_number("") == ""
def test_extract_notice_fields_includes_po_number():
structured = {
"po_number": "PO-2026-001",
"lines": [{"sku": "A-001", "qty": 1}],
"confidence": 0.9,
}
parsed, _, _ = extract_notice_fields(raw_text="", structured=structured)
assert parsed["po_number"] == "PO-2026-001"
@@ -0,0 +1,15 @@
from app.services.shipping_notice.match import match_notice_lines
from app.services.shipping_notice.reservation_id import normalize_reservation_id
def test_match_numeric_reservation_id():
notice = [{"sku": "10-40594-001", "reservation_id": "1000140351", "qty": 2}]
inventory = [{"sku": "10-40594-001", "reservation_id": 1000140351.0, "available_qty": 3}]
status, results, _ = match_notice_lines(notice, inventory)
assert status == "fulfillable"
assert results[0]["reservation_id"] == "1000140351"
assert results[0]["available_qty"] == 3
def test_normalize_reservation_id_string():
assert normalize_reservation_id("1000140351") == "1000140351"
+885
View File
@@ -0,0 +1,885 @@
from app import db
from app.models import ShippingInventoryMapping, ShippingTask
def _tool_headers(app):
return {
"Content-Type": "application/json",
}
def test_shipping_notice_tool_flow(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "raw_content": "客户:ACME 料号A001 x 10"},
)
assert create_res.status_code == 200
create_data = create_res.get_json()
assert create_data["status"] == "ok"
task_id = create_data["task_id"]
parse_res = client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
assert parse_res.status_code == 200
parse_body = parse_res.get_json()
assert parse_body["status"] in {"ok", "needs_human"}
assert "【发货通知解析确认】" in parse_body["message"]
assert "| 料号 | A001 |" in parse_body["message"]
inv_res = client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
},
)
assert inv_res.status_code == 200
assert inv_res.get_json()["status"] == "ok"
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
assert match_res.status_code == 200
match_data = match_res.get_json()
assert match_data["status"] == "ok"
assert "订单" in match_data["message"]
assert "库存" in match_data["message"]
assert "A001" in match_data["message"]
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"task_id": task_id},
)
assert excel_res.status_code == 200
assert excel_res.get_json()["status"] == "ok"
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.export_file_path
status_res = client.post(
"/api/shipping-notice/tools/get_task_status",
headers=headers,
json={"task_id": task_id},
)
assert status_res.status_code == 200
assert status_res.get_json()["status"] == "ok"
def test_shipping_notice_match_shortage_needs_human(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 100, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 5}]},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
assert "订单" in data["message"]
assert "库存" in data["message"]
assert "缺口" in data["message"]
assert "confirm" in (data.get("human_options") or [])
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm"},
)
assert confirm_res.get_json()["status"] == "ok"
def test_openapi_spec_public(app, client):
app.config["SHIPPING_NOTICE_TOOL_API_BASE"] = "http://tool-api.example.com"
res = client.get("/api/shipping-notice/tools/openapi.json")
assert res.status_code == 200
spec = res.get_json()
assert "create_task" in str(spec)
assert spec["servers"][0]["url"] == "http://tool-api.example.com/api/shipping-notice"
props = spec["paths"]["/tools/create_task"]["post"]["requestBody"]["content"]["application/json"]["schema"]["properties"]
assert "raw_content" in props
assert "/rpa/" not in str(spec["paths"])
assert "/tools/parse_inventory" in spec["paths"]
assert "/tools/get_inventory_schema_preview" in spec["paths"]
assert "/tools/apply_inventory_mapping" in spec["paths"]
def test_parse_inventory_from_chat_text(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 10, "uom": "EA"}],
"confidence": 0.95,
},
},
)
inv_text = "料号\t可用数量\nA001\t10\nB002\t5"
parse_inv = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"task_id": task_id, "raw_inventory_text": inv_text},
)
assert parse_inv.status_code == 200
data = parse_inv.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "inventory_field_mapping_review"
assert data.get("stop_agent_turn") is True
assert "match_inventory" in (data.get("forbidden_next_tools") or [])
assert "field_alignment" in data["data"]
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm_inventory_mapping"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] == "needs_human"
assert confirm_data.get("checkpoint") == "inventory_field_mapping_review"
assert "Reservation ID" in (confirm_data.get("message") or "")
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
assert match_res.get_json()["status"] in {"failed", "needs_human"}
def test_parse_inventory_empty_needs_human(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"task_id": task_id, "raw_inventory_text": " "},
)
assert res.get_json()["status"] == "needs_human"
assert "reparse_inventory" in (res.get_json().get("human_options") or [])
def test_match_by_aws_sku_and_reservation_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [
{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 2, "uom": "EA"},
{"sku": "10-40594-001", "reservation_id": "ORD-3002", "qty": 1, "uom": "EA"},
],
"confidence": 0.95,
},
},
)
inv_text = (
"AWS Sku\tCOM ID\tQty Available\n"
"10-40594-001\tAWS-311\t2\n"
"10-40594-001\tORD-3002\t0\n"
)
client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"task_id": task_id, "raw_inventory_text": inv_text},
)
client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm_inventory_mapping"},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
results = {r["reservation_id"]: r for r in data["data"]["line_results"]}
assert results["AWS-311"]["line_status"] == "ok"
assert results["ORD-3002"]["line_status"] == "shortage"
def test_match_inventory_blocked_before_mapping_confirm(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
blocked = match_res.get_json()
assert blocked["status"] == "needs_human"
assert blocked.get("checkpoint") == "inventory_field_mapping_review"
assert blocked.get("stop_agent_turn") is True
assert "field_alignment" in blocked["data"]
mapping = blocked["data"]["field_alignment"]
assert mapping["inventory_columns"]["mapping"]["sku"]["source_column"] == "AWS Sku"
assert mapping["inventory_columns"]["mapping"]["reservation_id"]["source_column"] == "COM ID"
def test_match_inventory_requires_reservation_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
"task_id": task_id,
"inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}],
},
)
match_res = client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
data = match_res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "reservation_id_required"
def test_correct_inventory_mapping_resets_to_inference(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={
"task_id": task_id,
"raw_inventory_text": "AWS Sku\tCOM ID\tQty Available\n10-40594-001\tAWS-311\t1\n",
},
)
correct_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "correct_inventory_mapping"},
)
data = correct_res.get_json()
assert data["status"] == "ok"
assert data.get("checkpoint") == "inventory_mapping_inference"
assert "schema_preview" in data["data"]
assert data["data"]["schema_preview"]["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
def test_rpa_inventory_callback(app, client, tmp_path, monkeypatch):
headers = _tool_headers(app)
drop = tmp_path / "drop"
trigger = tmp_path / "triggers"
drop.mkdir()
trigger.mkdir()
app.config["FREIGHT_INVENTORY_DROP_DIR"] = str(drop)
app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(trigger)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
from openpyxl import Workbook
inv_file = drop / "stock.xlsx"
wb = Workbook()
ws = wb.active
ws.append(["料号", "可用数量"])
ws.append(["A001", 20])
wb.save(inv_file)
wb.close()
cb_res = client.post(
"/api/shipping-notice/rpa/inventory-ready",
headers=headers,
json={"task_no": task_id, "success": True, "file_path": str(inv_file)},
)
assert cb_res.status_code == 200
data = cb_res.get_json()
assert data["status"] == "needs_human"
assert data["data"]["process_status"] == "inventory_ready"
assert "confirm_inventory_mapping" in (data.get("human_options") or [])
def test_rpa_upload_callback(app, client, tmp_path):
headers = _tool_headers(app)
queue = tmp_path / "queue"
trigger = tmp_path / "upload_triggers"
queue.mkdir()
trigger.mkdir()
app.config["FREIGHT_UPLOAD_QUEUE_DIR"] = str(queue)
app.config["FREIGHT_RPA_UPLOAD_TRIGGER_DIR"] = str(trigger)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "ACME",
"lines": [{"sku": "A001", "reservation_id": "R-1", "qty": 5, "uom": "EA"}],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={"task_id": task_id, "inventory_lines": [{"sku": "A001", "reservation_id": "R-1", "available_qty": 10}]},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"task_id": task_id},
)
cb_res = client.post(
"/api/shipping-notice/rpa/upload-complete",
headers=headers,
json={"task_no": task_id, "success": True, "freight_ref_no": "FR-001"},
)
assert cb_res.status_code == 200
assert cb_res.get_json()["status"] == "ok"
assert cb_res.get_json()["data"]["freight_ref_no"] == "FR-001"
def test_generate_shipment_excel_writes_vendor_part_and_odm_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "Wistron",
"po_number": "SN-20260608-7FCBFA4B",
"lines": [
{
"sku": "504-010213-001",
"vendor_part_number": "504-010213-001",
"reservation_id": "1000140351",
"qty": 9,
"uom": "EA",
}
],
"confidence": 0.95,
},
},
)
client.post(
"/api/shipping-notice/tools/ensure_inventory",
headers=headers,
json={
"task_id": task_id,
"inventory_lines": [
{
"sku": "504-010213-001",
"reservation_id": "1000140351",
"available_qty": 9,
"odm_id": "16754796",
}
],
},
)
client.post(
"/api/shipping-notice/tools/match_inventory",
headers=headers,
json={"task_id": task_id},
)
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"task_id": task_id},
)
assert excel_res.status_code == 200
assert excel_res.get_json()["status"] == "ok"
from openpyxl import load_workbook
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.export_file_path
wb = load_workbook(task.export_file_path, read_only=True)
header_ws = wb["PVMI Pull Request Header"]
detail_ws = wb["PVMI Pull Request Detail"]
assert header_ws.cell(4, 6).value == "16754796"
assert detail_ws.cell(4, 4).value == "504-010213-001"
wb.close()
def test_upload_inventory_file_parses_server_side(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 1000
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "AWS",
"lines": [{"sku": "10-40594-001", "reservation_id": "AWS-311", "qty": 1, "uom": "EA"}],
"confidence": 0.95,
},
},
)
from io import BytesIO
from openpyxl import Workbook
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["10-40594-001", "AWS-311", 5])
wb.save(buf)
wb.close()
buf.seek(0)
upload_res = client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={
"task_id": task_id,
"file": (buf, "inventory.xlsx"),
},
)
assert upload_res.status_code == 200
upload_data = upload_res.get_json()
assert upload_data["status"] == "ok"
assert upload_data.get("checkpoint") == "inventory_mapping_inference"
preview = upload_data["data"]["schema_preview"]
assert preview["headers"] == ["AWS Sku", "COM ID", "Qty Available"]
assert preview["suggested_mapping"]["sku"] == "AWS Sku"
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"task_id": task_id,
"column_mapping_json": {
**preview["suggested_mapping"],
"match_rule": "LLM:Reservation Order 对齐订单 reservation_id,汇总 Qty Available。",
},
},
)
apply_data = apply_res.get_json()
assert apply_data["status"] == "needs_human"
assert apply_data.get("checkpoint") == "inventory_field_mapping_review"
assert apply_data["data"]["field_alignment"]["inventory_row_count"] == 1
assert apply_data["data"]["field_alignment"]["match_rule"].startswith("LLM:")
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "llm"
with app.app_context():
assert ShippingInventoryMapping.query.filter_by(customer_code="GLOBAL").count() >= 1
def test_apply_inventory_mapping_fallback_match_rule(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
from io import BytesIO
from openpyxl import Workbook
wb = Workbook()
ws = wb.active
ws.append(["AWS Sku", "COM ID", "Qty Available"])
ws.append(["504-010213-001", "1000140351", 5])
buf = BytesIO()
wb.save(buf)
buf.seek(0)
client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={"task_id": task_id, "file": (buf, "inventory.xlsx")},
)
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"task_id": task_id,
"column_mapping_json": {
"sku": "AWS Sku",
"reservation_id": "COM ID",
"available_qty": "Qty Available",
},
},
)
apply_data = apply_res.get_json()
match_rule = apply_data["data"]["field_alignment"]["match_rule"]
assert "AWS Sku" in match_rule
assert "COM ID" in match_rule
assert apply_data["data"]["field_alignment"].get("match_rule_source") == "fallback"
def test_get_inventory_schema_preview(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
missing = client.post(
"/api/shipping-notice/tools/get_inventory_schema_preview",
headers=headers,
json={"task_id": task_id},
)
assert missing.get_json()["checkpoint"] == "inventory_upload_required"
def test_apply_inventory_mapping_custom_headers(app, client, tmp_path):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "shipping")
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
from io import BytesIO
from openpyxl import Workbook
buf = BytesIO()
wb = Workbook()
ws = wb.active
ws.append(["Part No", "Resv", "On Hand"])
ws.append(["SKU-99", "R-1", 12])
wb.save(buf)
wb.close()
buf.seek(0)
client.post(
"/api/shipping-notice/tools/upload_inventory_file",
headers={k: v for k, v in headers.items() if k.lower() != "content-type"},
data={"task_id": task_id, "file": (buf, "inv.xlsx")},
)
apply_res = client.post(
"/api/shipping-notice/tools/apply_inventory_mapping",
headers=headers,
json={
"task_id": task_id,
"column_mapping_json": {
"sku": "Part No",
"reservation_id": "Resv",
"available_qty": "On Hand",
},
},
)
apply_data = apply_res.get_json()
assert apply_data["status"] == "needs_human"
assert apply_data["data"]["inventory_row_count"] == 1
sample = apply_data["data"]["field_alignment"]["sample_inventory_lines"][0]
assert sample["sku"] == "SKU-99"
assert sample["available_qty"] == 12
def test_confirm_parse_does_not_skip_inventory_match(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
)
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"task_id": task_id, "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] in {"ok", "running", "needs_human"}
excel_res = client.post(
"/api/shipping-notice/tools/generate_shipment_excel",
headers=headers,
json={"task_id": task_id},
)
excel_data = excel_res.get_json()
assert excel_data["status"] == "failed"
assert "匹配" in excel_data["message"]
with app.app_context():
task = ShippingTask.query.filter_by(task_no=task_id).first()
assert task is not None
assert task.process_status in {"parsed", "waiting_inventory"}
assert task.match_status is None
def test_submit_decision_by_conversation_id(app, client):
headers = _tool_headers(app)
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "conversation_id": "conv-test-001"},
)
task_id = create_res.get_json()["task_id"]
client.post(
"/api/shipping-notice/tools/parse_notice",
headers=headers,
json={
"task_id": task_id,
"conversation_id": "conv-test-001",
"structured": {
"customer_name": "Wistron",
"lines": [{"sku": "504-010213-001", "qty": 9, "uom": "EA"}],
"confidence": 0.95,
},
},
)
confirm_res = client.post(
"/api/shipping-notice/tools/submit_decision",
headers=headers,
json={"conversation_id": "conv-test-001", "decision": "confirm"},
)
confirm_data = confirm_res.get_json()
assert confirm_data["status"] in {"ok", "running", "needs_human"}
assert confirm_data["task_id"] == task_id
dup_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual", "conversation_id": "conv-test-001"},
)
dup_data = dup_res.get_json()
assert dup_data["task_id"] == task_id
assert dup_data.get("checkpoint") == "task_already_exists"
def test_parse_inventory_rejects_oversized_text(app, client):
headers = _tool_headers(app)
app.config["SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS"] = 100
create_res = client.post(
"/api/shipping-notice/tools/create_task",
headers=headers,
json={"source_type": "manual"},
)
task_id = create_res.get_json()["task_id"]
res = client.post(
"/api/shipping-notice/tools/parse_inventory",
headers=headers,
json={"task_id": task_id, "raw_inventory_text": "x" * 200},
)
data = res.get_json()
assert data["status"] == "needs_human"
assert data.get("checkpoint") == "inventory_upload_required"
assert "过大" in data["message"]
def test_chat_actions_empty_when_task_rejected(app):
from app.services.shipping_notice.chat_actions import build_chat_actions_payload, human_options_for_task
with app.app_context():
task = ShippingTask(
task_no="SN-20260101-TEST0001",
source_type="manual",
process_status="rejected",
review_status="rejected",
)
assert human_options_for_task(task) == []
payload = build_chat_actions_payload(task)
assert payload["checkpoint"] == "rejected"
assert payload["action_buttons"] == []
@@ -0,0 +1,78 @@
from pathlib import Path
import subprocess
from edkb_system.skills import soffice_util
def test_convert_with_soffice_uses_isolated_profile_and_cleans(monkeypatch, tmp_path):
profile_dir = tmp_path / "lo-profile-fixed"
def fake_mkdtemp(prefix=""):
profile_dir.mkdir(parents=True, exist_ok=True)
return str(profile_dir)
monkeypatch.setenv("EDKB_SOFFICE_ISOLATED_PROFILE", "1")
monkeypatch.setattr(soffice_util.tempfile, "mkdtemp", fake_mkdtemp)
captured = {}
def fake_run(cmd):
captured["cmd"] = cmd
assert profile_dir.exists()
return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
monkeypatch.setattr(soffice_util, "run_soffice", fake_run)
source_path = tmp_path / "sample.doc"
source_path.write_text("dummy", encoding="utf-8")
out_dir = tmp_path / "out"
proc = soffice_util.convert_with_soffice(
"soffice",
convert_to="docx",
source_path=source_path,
out_dir=out_dir,
)
assert proc.returncode == 0
assert any(
str(item).startswith("-env:UserInstallation=") for item in captured["cmd"]
)
assert not profile_dir.exists()
def test_convert_with_soffice_can_use_shared_profile(monkeypatch, tmp_path):
called = {"mkdtemp": 0}
def fake_mkdtemp(prefix=""):
called["mkdtemp"] += 1
return str(tmp_path / "unused-profile")
monkeypatch.setenv("EDKB_SOFFICE_ISOLATED_PROFILE", "0")
monkeypatch.setattr(soffice_util.tempfile, "mkdtemp", fake_mkdtemp)
captured = {}
def fake_run(cmd):
captured["cmd"] = cmd
return subprocess.CompletedProcess(cmd, 0, stdout="", stderr="")
monkeypatch.setattr(soffice_util, "run_soffice", fake_run)
source_path = tmp_path / "sample.doc"
source_path.write_text("dummy", encoding="utf-8")
out_dir = tmp_path / "out"
proc = soffice_util.convert_with_soffice(
"soffice",
convert_to="docx",
source_path=source_path,
out_dir=out_dir,
)
assert proc.returncode == 0
assert called["mkdtemp"] == 0
assert not any(
str(item).startswith("-env:UserInstallation=") for item in captured["cmd"]
)