""" api/shipping_notice_tools.py 用途:暴露发货通知 Tool API,供 Dify Chatflow Agent、RPA 回调和导出下载入口调用。 依赖:shipping_notice.tools、query_service、openapi_spec、tool_api_url、Flask Blueprint。 逻辑:上游由 Dify/OpenAPI 或 RPA 请求进入本文件;本文件做轻量参数编排,再下沉到 services/shipping_notice/* workflow。 """ from __future__ import annotations import uuid from flask import Blueprint, current_app, jsonify, request, send_file from app import db from app.errors import AppError, ServiceUnavailableError, UnauthorizedError from app.services.shipping_notice.query_service import ( EXPORT_MIME_TYPE, get_batch_by_no, get_focus_task_for_batch, get_task_by_ref, get_task_in_batch, list_batch_task_summaries, resolve_task_export_download, serialize_batch_summary, serialize_task_summary, task_export_error_message, ) from app.services.shipping_notice import tools as shipping_tools from app.services.shipping_notice.openapi_spec import build_dify_openapi_spec from app.services.shipping_notice.tool_api_url import resolve_tool_api_base_url shipping_notice_bp = Blueprint("shipping_notice", __name__) def _require_tool_auth() -> None: """ 校验货代 Tool API 鉴权 Header。 【AI 触发时机】:本函数不是给 Agent 直接调用的 Tool;当 Dify、RPA 或外部系统请求本蓝图时由 before_request 自动触发。 核心逻辑:对齐文件检核 Tool,只接受 `Authorization: Bearer ` 或 `X-Integration-Key`,并统一使用 `INTEGRATION_API_KEY` 作为服务端校验值; 未配置时报服务不可用,缺失或错误时报未授权。 """ 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() if configured in {token, integration_key}: return 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"}: 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" 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 @shipping_notice_bp.before_request def _verify_tool_access(): """ 对货代 Tool / RPA / 导出接口做统一 Header 鉴权。 核心逻辑:仅放行 OpenAPI 导入文档,其他请求都必须携带有效 Tool Key。 """ 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"]) def openapi_spec(): """返回 Dify 导入用的 OpenAPI JSON 文档。""" return jsonify(_dify_openapi_spec()) @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"]) 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") @shipping_notice_bp.route("/tools/create_task", methods=["POST"]) def tool_create_task(): """ 创建单个发货任务。 【AI 触发时机】:当用户首次提交一张新的发货通知、当前会话里还没有对应任务时调用。 """ return jsonify(shipping_tools.create_task(_payload())) @shipping_notice_bp.route("/tools/create_batch", methods=["POST"]) def tool_create_batch(): """ 创建或复用发货批次。 【AI 触发时机】:当用户一次处理多份发货通知,需要把多任务挂到同一批次时调用。 """ payload = _payload() if isinstance(payload.get("notice_items"), list) and payload.get("notice_items"): return jsonify(shipping_tools.create_batch_tasks(payload)) batch_no = str(payload.get("batch_no") or "").strip() if batch_no: batch = get_batch_by_no(batch_no) if batch: return jsonify( { "status": "ok", "batch_no": batch.batch_no, "message": f"已复用批次 {batch.batch_no}", "data": serialize_batch_summary(batch), } ) batch = shipping_tools.create_batch(payload) db.session.commit() return jsonify( { "status": "ok", "batch_no": batch.batch_no, "message": f"已创建批次 {batch.batch_no}", "data": serialize_batch_summary(batch), } ) @shipping_notice_bp.route("/tools/parse_notice", methods=["POST"]) def tool_parse_notice(): """ 解析发货通知正文。 【AI 触发时机】:当用户上传、粘贴或修正发货通知内容后,需要把文本转成任务单头和订单行时调用。 """ return jsonify(shipping_tools.parse_notice(_payload())) @shipping_notice_bp.route("/tools/update_notice_fields", methods=["POST"]) def tool_update_notice_fields(): """ 修改发货通知单头字段。 【AI 触发时机】:当用户明确要求更正客户、PO、收货地或交期等单头信息时调用。 """ return jsonify(shipping_tools.update_notice_fields(_payload())) @shipping_notice_bp.route("/tools/update_notice_line", methods=["POST"]) def tool_update_notice_line(): """ 修改指定订单行。 【AI 触发时机】:当用户指出某一行的 SKU、数量、Reservation ID 或交期有误时调用。 """ return jsonify(shipping_tools.update_notice_line(_payload())) @shipping_notice_bp.route("/tools/add_notice_line", methods=["POST"]) def tool_add_notice_line(): """ 新增订单行。 【AI 触发时机】:当用户说明漏了一行订单、需要补录发货通知明细时调用。 """ return jsonify(shipping_tools.add_notice_line(_payload())) @shipping_notice_bp.route("/tools/remove_notice_line", methods=["POST"]) def tool_remove_notice_line(): """ 删除订单行。 【AI 触发时机】:当用户确认某一行是误解析、重复行或不应出货的行时调用。 """ return jsonify(shipping_tools.remove_notice_line(_payload())) @shipping_notice_bp.route("/tools/parse_inventory", methods=["POST"]) def tool_parse_inventory(): """ 解析库存内容。 【AI 触发时机】:当用户提供库存文本或表格内容,需要把库存转成系统可匹配格式时调用。 """ return jsonify(shipping_tools.parse_inventory(_payload())) @shipping_notice_bp.route("/tools/upload_inventory_file", methods=["POST"]) def tool_upload_inventory_file(): """ 服务器侧接收库存 Excel 并解析。 【AI 触发时机】:当用户上传库存 Excel,且不希望把二进制文件内容经由 LLM 传输时调用。 """ task_id = str(request.form.get("task_id") or request.args.get("task_id") or "").strip() upload = request.files.get("file") return jsonify(shipping_tools.upload_inventory_file(task_id, upload)) @shipping_notice_bp.route("/tools/get_inventory_schema_preview", methods=["POST"]) def tool_get_inventory_schema_preview(): """ 获取库存表头预览。 【AI 触发时机】:当 Agent 需要先看 Excel/表格列名,再决定 map_json 或提示用户确认映射时调用。 """ return jsonify(shipping_tools.get_inventory_schema_preview(_payload())) @shipping_notice_bp.route("/tools/apply_inventory_mapping", methods=["POST"]) def tool_apply_inventory_mapping(): """ 应用库存字段映射。 【AI 触发时机】:当用户或 Agent 已确认列名与系统字段的对应关系,需要提交 map_json 时调用。 """ return jsonify(shipping_tools.apply_inventory_mapping(_payload())) @shipping_notice_bp.route("/tools/ensure_inventory", methods=["POST"]) def tool_ensure_inventory(): """ 保证任务已取得库存数据。 【AI 触发时机】:当发货通知已确认,下一步需要让系统拿到库存快照时调用。 """ return jsonify(shipping_tools.ensure_inventory(_payload())) @shipping_notice_bp.route("/tools/auto_progress", methods=["POST"]) def tool_auto_progress(): """ 自动推进任务。 【AI 触发时机】:当用户说“继续处理”“自动推进”“跑到下一步”时调用。 """ return jsonify(shipping_tools.auto_progress(_payload())) @shipping_notice_bp.route("/tools/match_inventory", methods=["POST"]) def tool_match_inventory(): """ 执行库存匹配。 【AI 触发时机】:当发货通知与库存都已准备好,需要判断是否缺货并生成匹配结果时调用。 """ return jsonify(shipping_tools.match_inventory(_payload())) @shipping_notice_bp.route("/tools/submit_decision", methods=["POST"]) def tool_submit_decision(): """ 提交人工决策。 【AI 触发时机】:当用户明确表达确认、驳回、重解析、重匹配、确认映射或关闭任务时调用。 """ return jsonify(shipping_tools.submit_decision(_payload())) @shipping_notice_bp.route("/tools/generate_shipment_excel", methods=["POST"]) def tool_generate_shipment_excel(): """ 生成出货 Excel。 【AI 触发时机】:当库存匹配已通过,用户要求导出货代上传模板时调用。 """ return jsonify(shipping_tools.generate_excel(_payload())) @shipping_notice_bp.route("/tools/upload_to_freight", methods=["POST"]) def tool_upload_to_freight(): """ 上传到货代系统或确认人工上传完成。 【AI 触发时机】:当用户要求推送到货代系统,或确认已手工完成上传时调用。 """ return jsonify(shipping_tools.upload_to_freight(_payload())) @shipping_notice_bp.route("/tools/get_task_status", methods=["POST"]) def tool_get_task_status(): """ 查询任务状态。 【AI 触发时机】:当 Agent 只拿到任务号/会话号,需要先确认当前卡点后再决定下一步时调用。 """ return jsonify(shipping_tools.get_task_status(_payload())) @shipping_notice_bp.route("/tools/get_batch_status", methods=["POST"]) def tool_get_batch_status(): """ 查询批次状态。 【AI 触发时机】:当用户关注整批任务处理进度,或 Agent 需要查看当前 focus task 与批次摘要时调用。 """ payload = _payload() batch_no = str(payload.get("batch_no") or "").strip() if not batch_no: return jsonify({"status": "failed", "message": "batch_no is required"}), 400 batch = get_batch_by_no(batch_no) if not batch: return jsonify({"status": "failed", "message": "batch not found"}), 404 focus_task = get_focus_task_for_batch(batch_no, batch.user_id or 0) if batch.user_id is not None else None return jsonify( { "status": "ok", "batch_no": batch.batch_no, "message": f"已获取批次 {batch.batch_no} 状态", "data": { **serialize_batch_summary(batch), "focus_task": serialize_task_summary(focus_task) if focus_task else None, "tasks": list_batch_task_summaries(batch), }, } ) @shipping_notice_bp.route("/tools/switch_focus_task", methods=["POST"]) def tool_switch_focus_task(): """ 切换批次当前焦点任务。 【AI 触发时机】:当用户在同一批次里要求“看第 N 个任务”或切换当前处理对象时调用。 """ payload = _payload() batch_no = str(payload.get("batch_no") or "").strip() task_no = str(payload.get("task_no") or payload.get("target_task_no") or "").strip() if not batch_no or not task_no: return jsonify({"status": "failed", "message": "batch_no and task_no are required"}), 400 batch = get_batch_by_no(batch_no) if not batch: return jsonify({"status": "failed", "message": "batch not found"}), 404 task = get_task_in_batch(batch_no, task_no) if not task: return jsonify({"status": "failed", "message": "task not found in batch"}), 404 batch.current_focus_task_no = task.task_no db.session.commit() return jsonify( { "status": "ok", "batch_no": batch.batch_no, "task_no": task.task_no, "message": f"已切换当前任务到 {task.task_no}", "data": { "batch": serialize_batch_summary(batch), "focus_task": serialize_task_summary(task), }, } ) @shipping_notice_bp.route("/rpa/inventory-ready", methods=["POST"]) def rpa_inventory_ready(): """RPA 回调入口:上报库存导出结果并回写任务状态。""" return jsonify(shipping_tools.rpa_report_inventory(_payload())) @shipping_notice_bp.route("/rpa/upload-complete", methods=["POST"]) def rpa_upload_complete(): """RPA 回调入口:上报货代上传结果并回写任务状态。""" return jsonify(shipping_tools.rpa_report_upload(_payload())) @shipping_notice_bp.route("/tasks//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 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, )