refactor(backend): 迁移基础设施,core,拆分models

This commit is contained in:
sophie committed 2026-06-25 14:01:52 +08:00
1 parent b89d93d738
commit 053ea392f2
61 files changed
+3329 -3268

No files matched your search

+73 -151
View File
@@ -2,16 +2,25 @@
api/shipping_notice_tools.py
用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。
依赖:shipping_notice.tools、query_service、openapi_spec、tool_api_url、Flask Blueprint。
逻辑:上游由 Dify/OpenAPI 或 RPA 请求进入本文件;本文件做轻量参数编排,再下沉到 services/shipping_notice/* workflow。
依赖:app.core.errors、shipping_notice.tools、query_service、openapi_spec、tool_api_url。
逻辑:Tool 成功响应仍用 status: ok/failed 业务 envelope;HTTP 级参数/资源错误统一 raise AppError。
"""
from __future__ import annotations
import uuid
from flask import Blueprint, current_app, jsonify, request, send_file
from app import db
from app.errors import AppError, ServiceUnavailableError, UnauthorizedError
from app.core.errors import (
AppError,
NotFoundError,
ServiceUnavailableError,
UnauthorizedError,
ValidationError,
)
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.query_service import (
EXPORT_MIME_TYPE,
get_batch_by_no,
@@ -24,8 +33,6 @@ from app.services.shipping_notice.query_service import (
serialize_task_summary,
task_export_error_message,
)
from app.services.shipping_notice import tools as shipping_tools
from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec
from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url
shipping_notice_bp = Blueprint("shipping_notice", __name__)
@@ -40,44 +47,33 @@ def _require_tool_auth() -> None:
`X-Integration-Key`,并统一使用 `INTEGRATION_API_KEY` 作为服务端校验值;
未配置时报服务不可用,缺失或错误时报未授权。
"""
configured = str(current_app.config.get("INTEGRATION_API_KEY") or "").strip()
configured = str(current_app.config.get('INTEGRATION_API_KEY') or '').strip()
if not configured:
raise ServiceUnavailableError(
"INTEGRATION_API_KEY is not configured",
code="missing_auth",
)
bearer = str(request.headers.get("Authorization") or "").strip()
token = bearer[7:].strip() if bearer.lower().startswith("bearer ") else ""
integration_key = str(request.headers.get("X-Integration-Key") or "").strip()
raise ServiceUnavailableError('INTEGRATION_API_KEY is not configured', code='missing_auth')
bearer = str(request.headers.get('Authorization') or '').strip()
token = bearer[7:].strip() if bearer.lower().startswith('bearer ') else ''
integration_key = str(request.headers.get('X-Integration-Key') or '').strip()
if configured in {token, integration_key}:
return
if not token and not integration_key:
raise UnauthorizedError("missing_auth")
raise UnauthorizedError("invalid_auth")
if not token and (not integration_key):
raise UnauthorizedError('missing_auth')
raise UnauthorizedError('invalid_auth')
def _tool_error_code(exc: AppError) -> str:
"""统一归一化 Tool API 的错误码,保持与文件检核 Tool 返回风格一致。"""
message = str(exc.message or "").strip()
if message in {"missing_auth", "invalid_auth"}:
message = str(exc.message or '').strip()
if message in {'missing_auth', 'invalid_auth'}:
return message
if exc.code == "AUTH.UNAUTHORIZED":
return "invalid_auth"
if exc.code == "SYSTEM.SERVICE_UNAVAILABLE" and "not configured" in message.lower():
return "missing_auth"
if exc.code == 'AUTH.UNAUTHORIZED':
return 'invalid_auth'
if exc.code == 'SYSTEM.SERVICE_UNAVAILABLE' and 'not configured' in message.lower():
return 'missing_auth'
return exc.code
@shipping_notice_bp.errorhandler(AppError)
def _handle_tool_app_error(exc: AppError):
"""把业务异常统一转成 Tool 侧约定的 JSON 结构。"""
return jsonify({
"ok": False,
"error_code": _tool_error_code(exc),
"message": exc.message,
}), exc.http_status
return (jsonify({'ok': False, 'error_code': _tool_error_code(exc), 'message': exc.message}), exc.http_status)
@shipping_notice_bp.before_request
def _verify_tool_access():
@@ -85,55 +81,44 @@ def _verify_tool_access():
对货代 Tool / RPA / 导出接口做统一 Header 鉴权。
核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。
"""
if request.path.endswith("/openapi.json") or request.path.endswith("/openapi.dify.yaml"):
if request.path.endswith('/openapi.json') or request.path.endswith('/openapi.dify.yaml'):
return None
_require_tool_auth()
return None
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 {}
def _generate_batch_no() -> str:
from datetime import datetime
return f"SB-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}"
@shipping_notice_bp.route("/tools/openapi.json", methods=["GET"])
@shipping_notice_bp.route('/tools/openapi.json', methods=['GET'])
def openapi_spec():
"""返回 Dify 导入用的 OpenAPI JSON 文档。"""
return jsonify(_dify_openapi_spec())
@shipping_notice_bp.route("/tools/checkpoint-catalog", methods=["GET"])
@shipping_notice_bp.route('/tools/checkpoint-catalog', methods=['GET'])
def checkpoint_catalog():
"""返回检查点目录,供开发联调和文档核对 human_options/action_buttons。"""
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"])
@shipping_notice_bp.route('/tools/openapi.dify.yaml', methods=['GET'])
def openapi_dify_yaml():
"""返回 Dify 导入用的 OpenAPI YAML 文档。"""
import yaml
body = yaml.safe_dump(_dify_openapi_spec(), allow_unicode=True, sort_keys=False)
return current_app.response_class(body, mimetype="text/yaml; charset=utf-8")
return current_app.response_class(body, mimetype='text/yaml; charset=utf-8')
@shipping_notice_bp.route("/tools/create_task", methods=["POST"])
@shipping_notice_bp.route('/tools/create_task', methods=['POST'])
def tool_create_task():
"""
创建单个发货任务。
@@ -141,41 +126,25 @@ def tool_create_task():
"""
return jsonify(shipping_tools.create_task(_payload()))
@shipping_notice_bp.route("/tools/create_batch", methods=["POST"])
@shipping_notice_bp.route('/tools/create_batch', methods=['POST'])
def tool_create_batch():
"""
创建或复用发货批次。
【AI 触发时机】:当用户一次处理多份发货通知,需要把多任务挂到同一批次时调用。
"""
payload = _payload()
if isinstance(payload.get("notice_items"), list) and payload.get("notice_items"):
if isinstance(payload.get('notice_items'), list) and payload.get('notice_items'):
return jsonify(shipping_tools.create_batch_tasks(payload))
batch_no = str(payload.get("batch_no") or "").strip()
batch_no = str(payload.get('batch_no') or '').strip()
if batch_no:
batch = get_batch_by_no(batch_no)
if batch:
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"message": f"已复用批次 {batch.batch_no}",
"data": serialize_batch_summary(batch),
}
)
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已复用批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
batch = shipping_tools.create_batch(payload)
db.session.commit()
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"message": f"已创建批次 {batch.batch_no}",
"data": serialize_batch_summary(batch),
}
)
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已创建批次 {batch.batch_no}', 'data': serialize_batch_summary(batch)})
@shipping_notice_bp.route("/tools/parse_notice", methods=["POST"])
@shipping_notice_bp.route('/tools/parse_notice', methods=['POST'])
def tool_parse_notice():
"""
解析发货通知正文。
@@ -183,8 +152,7 @@ def tool_parse_notice():
"""
return jsonify(shipping_tools.parse_notice(_payload()))
@shipping_notice_bp.route("/tools/update_notice_fields", methods=["POST"])
@shipping_notice_bp.route('/tools/update_notice_fields', methods=['POST'])
def tool_update_notice_fields():
"""
修改发货通知单头字段。
@@ -192,8 +160,7 @@ def tool_update_notice_fields():
"""
return jsonify(shipping_tools.update_notice_fields(_payload()))
@shipping_notice_bp.route("/tools/update_notice_line", methods=["POST"])
@shipping_notice_bp.route('/tools/update_notice_line', methods=['POST'])
def tool_update_notice_line():
"""
修改指定订单行。
@@ -201,8 +168,7 @@ def tool_update_notice_line():
"""
return jsonify(shipping_tools.update_notice_line(_payload()))
@shipping_notice_bp.route("/tools/add_notice_line", methods=["POST"])
@shipping_notice_bp.route('/tools/add_notice_line', methods=['POST'])
def tool_add_notice_line():
"""
新增订单行。
@@ -210,8 +176,7 @@ def tool_add_notice_line():
"""
return jsonify(shipping_tools.add_notice_line(_payload()))
@shipping_notice_bp.route("/tools/remove_notice_line", methods=["POST"])
@shipping_notice_bp.route('/tools/remove_notice_line', methods=['POST'])
def tool_remove_notice_line():
"""
删除订单行。
@@ -219,8 +184,7 @@ def tool_remove_notice_line():
"""
return jsonify(shipping_tools.remove_notice_line(_payload()))
@shipping_notice_bp.route("/tools/parse_inventory", methods=["POST"])
@shipping_notice_bp.route('/tools/parse_inventory', methods=['POST'])
def tool_parse_inventory():
"""
解析库存内容。
@@ -228,19 +192,17 @@ def tool_parse_inventory():
"""
return jsonify(shipping_tools.parse_inventory(_payload()))
@shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"])
@shipping_notice_bp.route('/tools/upload_inventory_file', methods=['POST'])
def tool_upload_inventory_file():
"""
服务器侧接收库存 Excel 并解析。
【AI 触发时机】:当用户上传库存 Excel,且不希望把二进制文件内容经由 LLM 传输时调用。
"""
task_id = str(request.form.get("task_id") or request.args.get("task_id") or "").strip()
upload = request.files.get("file")
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"])
@shipping_notice_bp.route('/tools/get_inventory_schema_preview', methods=['POST'])
def tool_get_inventory_schema_preview():
"""
获取库存表头预览。
@@ -248,8 +210,7 @@ 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"])
@shipping_notice_bp.route('/tools/apply_inventory_mapping', methods=['POST'])
def tool_apply_inventory_mapping():
"""
应用库存字段映射。
@@ -257,8 +218,7 @@ def tool_apply_inventory_mapping():
"""
return jsonify(shipping_tools.apply_inventory_mapping(_payload()))
@shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"])
@shipping_notice_bp.route('/tools/ensure_inventory', methods=['POST'])
def tool_ensure_inventory():
"""
保证任务已取得库存数据。
@@ -266,8 +226,7 @@ def tool_ensure_inventory():
"""
return jsonify(shipping_tools.ensure_inventory(_payload()))
@shipping_notice_bp.route("/tools/auto_progress", methods=["POST"])
@shipping_notice_bp.route('/tools/auto_progress', methods=['POST'])
def tool_auto_progress():
"""
自动推进任务。
@@ -275,8 +234,7 @@ def tool_auto_progress():
"""
return jsonify(shipping_tools.auto_progress(_payload()))
@shipping_notice_bp.route("/tools/match_inventory", methods=["POST"])
@shipping_notice_bp.route('/tools/match_inventory', methods=['POST'])
def tool_match_inventory():
"""
执行库存匹配。
@@ -284,8 +242,7 @@ def tool_match_inventory():
"""
return jsonify(shipping_tools.match_inventory(_payload()))
@shipping_notice_bp.route("/tools/submit_decision", methods=["POST"])
@shipping_notice_bp.route('/tools/submit_decision', methods=['POST'])
def tool_submit_decision():
"""
提交人工决策。
@@ -293,8 +250,7 @@ def tool_submit_decision():
"""
return jsonify(shipping_tools.submit_decision(_payload()))
@shipping_notice_bp.route("/tools/generate_shipment_excel", methods=["POST"])
@shipping_notice_bp.route('/tools/generate_shipment_excel', methods=['POST'])
def tool_generate_shipment_excel():
"""
生成出货 Excel。
@@ -302,8 +258,7 @@ def tool_generate_shipment_excel():
"""
return jsonify(shipping_tools.generate_excel(_payload()))
@shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"])
@shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST'])
def tool_upload_to_freight():
"""
上传到货代系统或确认人工上传完成。
@@ -311,8 +266,7 @@ def tool_upload_to_freight():
"""
return jsonify(shipping_tools.upload_to_freight(_payload()))
@shipping_notice_bp.route("/tools/get_task_status", methods=["POST"])
@shipping_notice_bp.route('/tools/get_task_status', methods=['POST'])
def tool_get_task_status():
"""
查询任务状态。
@@ -320,93 +274,61 @@ def tool_get_task_status():
"""
return jsonify(shipping_tools.get_task_status(_payload()))
@shipping_notice_bp.route("/tools/get_batch_status", methods=["POST"])
@shipping_notice_bp.route('/tools/get_batch_status', methods=['POST'])
def tool_get_batch_status():
"""
查询批次状态。
【AI 触发时机】:当用户关注整批任务处理进度,或 Agent 需要查看当前 focus task 与批次摘要时调用。
"""
payload = _payload()
batch_no = str(payload.get("batch_no") or "").strip()
batch_no = str(payload.get('batch_no') or '').strip()
if not batch_no:
return jsonify({"status": "failed", "message": "batch_no is required"}), 400
raise ValidationError("batch_no is required")
batch = get_batch_by_no(batch_no)
if not batch:
return jsonify({"status": "failed", "message": "batch not found"}), 404
raise NotFoundError("batch not found")
focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"message": f"已获取批次 {batch.batch_no} 状态",
"data": {
**serialize_batch_summary(batch),
"focus_task": serialize_task_summary(focus_task) if focus_task else None,
"tasks": list_batch_task_summaries(batch),
},
}
)
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'message': f'已获取批次 {batch.batch_no} 状态', 'data': {**serialize_batch_summary(batch), 'focus_task': serialize_task_summary(focus_task) if focus_task else None, 'tasks': list_batch_task_summaries(batch)}})
@shipping_notice_bp.route("/tools/switch_focus_task", methods=["POST"])
@shipping_notice_bp.route('/tools/switch_focus_task', methods=['POST'])
def tool_switch_focus_task():
"""
切换批次当前焦点任务。
【AI 触发时机】:当用户在同一批次里要求“看第 N 个任务”或切换当前处理对象时调用。
"""
payload = _payload()
batch_no = str(payload.get("batch_no") or "").strip()
task_no = str(payload.get("task_no") or payload.get("target_task_no") or "").strip()
batch_no = str(payload.get('batch_no') or '').strip()
task_no = str(payload.get('task_no') or payload.get('target_task_no') or '').strip()
if not batch_no or not task_no:
return jsonify({"status": "failed", "message": "batch_no and task_no are required"}), 400
raise ValidationError("batch_no and task_no are required")
batch = get_batch_by_no(batch_no)
if not batch:
return jsonify({"status": "failed", "message": "batch not found"}), 404
raise NotFoundError("batch not found")
task = get_task_in_batch(batch_no, task_no)
if not task:
return jsonify({"status": "failed", "message": "task not found in batch"}), 404
raise NotFoundError("task not found in batch")
batch.current_focus_task_no = task.task_no
db.session.commit()
return jsonify(
{
"status": "ok",
"batch_no": batch.batch_no,
"task_no": task.task_no,
"message": f"已切换当前任务到 {task.task_no}",
"data": {
"batch": serialize_batch_summary(batch),
"focus_task": serialize_task_summary(task),
},
}
)
return jsonify({'status': 'ok', 'batch_no': batch.batch_no, 'task_no': task.task_no, 'message': f'已切换当前任务到 {task.task_no}', 'data': {'batch': serialize_batch_summary(batch), 'focus_task': serialize_task_summary(task)}})
@shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"])
@shipping_notice_bp.route('/rpa/inventory-ready', methods=['POST'])
def rpa_inventory_ready():
"""RPA 回调入口:上报库存导出结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_inventory(_payload()))
@shipping_notice_bp.route("/rpa/upload-complete", methods=["POST"])
@shipping_notice_bp.route('/rpa/upload-complete', methods=['POST'])
def rpa_upload_complete():
"""RPA 回调入口:上报货代上传结果并回写任务状态。"""
return jsonify(shipping_tools.rpa_report_upload(_payload()))
@shipping_notice_bp.route("/tasks/<task_no>/export", methods=["GET"])
@shipping_notice_bp.route('/tasks/<task_no>/export', methods=['GET'])
def download_task_export(task_no: str):
"""下载任务已生成的出货 Excel。"""
task = get_task_by_ref(task_no)
err_msg = task_export_error_message(task)
if err_msg:
return jsonify({"error": err_msg}), 404
raise NotFoundError(err_msg)
resolved = resolve_task_export_download(task)
assert resolved is not None
path, download_name = resolved
return send_file(
path,
as_attachment=True,
download_name=download_name,
mimetype=EXPORT_MIME_TYPE,
)
return send_file(path, as_attachment=True, download_name=download_name, mimetype=EXPORT_MIME_TYPE)