From 55cf7ff7346e5f6cd3834892c5414c1bb64c21ab Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Wed, 17 Jun 2026 22:29:15 +0800 Subject: [PATCH] =?UTF-8?q?feat(file-check):=20=E6=9B=B4=E6=96=B0=E6=96=87?= =?UTF-8?q?=E4=BB=B6=E6=A3=80=E6=A0=B8=E5=B7=A5=E5=85=B7=20API=20Key=20?= =?UTF-8?q?=E9=85=8D=E7=BD=AE=E5=8F=8A=E7=9B=B8=E5=85=B3=E6=96=87=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.shared | 2 + backend/app/api/file_check_tools.py | 6 +- backend/app/api/shipping_notice_tools.py | 60 ++ backend/app/config.py | 2 +- backend/app/models.py | 13 +- .../file_check_tools/openapi_base.json | 6 +- .../shipping_notice/agent_resolver.py | 1 + .../services/shipping_notice/chat_actions.py | 8 +- .../app/services/shipping_notice/constants.py | 13 +- .../services/shipping_notice/dify_inputs.py | 3 +- .../app/services/shipping_notice/export.py | 10 + .../app/services/shipping_notice/extract.py | 13 + .../field_alignment_summary.py | 6 +- .../shipping_notice/fulfillment_workflow.py | 98 ++- backend/app/services/shipping_notice/i18n.py | 3 + .../shipping_notice/inventory_mapping.py | 9 +- .../inventory_mapping_store.py | 4 + .../inventory_mapping_workflow.py | 39 +- .../shipping_notice/inventory_rpa_workflow.py | 10 + .../shipping_notice/inventory_snapshot.py | 24 +- .../shipping_notice/inventory_upload.py | 11 + .../shipping_notice/inventory_workflow.py | 18 + backend/app/services/shipping_notice/match.py | 23 +- .../shipping_notice/match_rule_desc.py | 7 +- .../shipping_notice/notice_line_constants.py | 147 +++++ .../shipping_notice/notice_line_table.py | 214 ++++++ .../shipping_notice/notice_line_values.py | 220 +++++++ .../services/shipping_notice/notice_lines.py | 621 ++---------------- .../services/shipping_notice/notice_upload.py | 10 + .../services/shipping_notice/parse_summary.py | 8 +- .../app/services/shipping_notice/po_number.py | 10 + .../services/shipping_notice/query_service.py | 9 + .../shipping_notice/reservation_id.py | 7 +- backend/app/services/shipping_notice/rpa.py | 18 + .../services/shipping_notice/rpa_attempts.py | 4 + .../services/shipping_notice/state_machine.py | 59 +- .../services/shipping_notice/task_workflow.py | 5 + .../services/shipping_notice/tool_api_url.py | 2 +- .../services/shipping_notice/tool_common.py | 18 +- .../services/shipping_notice/tool_response.py | 12 +- .../shipping_notice/user_facing_status.py | 9 +- ...b9_add_fk_for_shipping_batch_focus_task.py | 90 +++ backend/tests/test_shipping_notice_extract.py | 1 + .../tests/test_shipping_notice_po_number.py | 2 + .../dify/shipping_notice_chatflow_export.json | 510 -------------- docs/openapi/file_check_tools_openapi.json | 8 +- .../chat/components/ChatViewContent.vue | 39 ++ .../components/ShippingWorkflowStepper.vue | 4 +- .../ShippingInventoryMappingMessage.vue | 4 +- .../messages/ShippingParseReviewMessage.vue | 4 +- .../features/chat/composables/useChatPage.ts | 4 + .../chat/composables/useChatShipping.ts | 14 + .../src/features/chat/constants/shipping.ts | 4 +- .../chat/shipping/shippingConversation.ts | 8 +- .../chat/shipping/shippingDecisionFormat.ts | 8 +- .../chat/shipping/shippingDownload.ts | 5 +- .../features/chat/shipping/shippingIntents.ts | 10 +- .../chat/shipping/shippingLocalMessages.ts | 8 +- .../features/chat/shipping/shippingMapping.ts | 13 +- .../chat/shipping/shippingMatchResult.ts | 6 +- .../features/chat/shipping/shippingMenu.ts | 17 +- .../chat/shipping/shippingParseReview.ts | 6 +- .../features/chat/shipping/shippingStepper.ts | 8 +- .../features/chat/shipping/shippingTaskId.ts | 9 +- .../features/chat/shipping/shippingText.ts | 18 +- .../chat/shipping/shippingUploadPrompt.ts | 11 +- .../shipping/useChatShippingParseReview.ts | 1 + .../shipping/useChatShippingUploadHandler.ts | 97 ++- .../features/chat/types/shipping.api.types.ts | 4 +- .../src/features/chat/types/shipping.types.ts | 4 +- frontend/src/locales/en/chat.json | 7 + frontend/src/locales/th/chat.json | 7 + frontend/src/locales/zh-CN/chat.json | 7 + frontend/src/locales/zh-TW/chat.json | 7 + 74 files changed, 1525 insertions(+), 1182 deletions(-) create mode 100644 backend/app/services/shipping_notice/notice_line_constants.py create mode 100644 backend/app/services/shipping_notice/notice_line_table.py create mode 100644 backend/app/services/shipping_notice/notice_line_values.py create mode 100644 backend/migrations/versions/d4c5e6f7a8b9_add_fk_for_shipping_batch_focus_task.py delete mode 100644 docs/dify/shipping_notice_chatflow_export.json diff --git a/.env.shared b/.env.shared index ea082182..e789e19d 100644 --- a/.env.shared +++ b/.env.shared @@ -11,6 +11,8 @@ FLASK_APP=run.py INTEGRATION_API_BASE=http://192.168.100.230:8891 # 连接文档清洗系统的API KEY INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh +# 文件检核 Tool API Key;未单独配置时建议与 INTEGRATION_API_KEY 保持一致 +FILE_CHECK_TOOL_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh SECRET_KEY=hxops-dify diff --git a/backend/app/api/file_check_tools.py b/backend/app/api/file_check_tools.py index a857ce15..f929852a 100644 --- a/backend/app/api/file_check_tools.py +++ b/backend/app/api/file_check_tools.py @@ -33,7 +33,7 @@ _TASK_LOCK_KEY_BASE = 8700000000 def _tool_token_secret() -> str: return str( - current_app.config.get("FILE_CHECK_TOOLS_API_KEY") + current_app.config.get("FILE_CHECK_TOOL_API_KEY") or current_app.config.get("INTEGRATION_API_KEY") or current_app.config.get("SECRET_KEY") or "default-secret" @@ -56,13 +56,13 @@ def _decode_download_token(token: str | None) -> dict | None: def _require_tool_auth() -> None: configured = str( - current_app.config.get("FILE_CHECK_TOOLS_API_KEY") + current_app.config.get("FILE_CHECK_TOOL_API_KEY") or current_app.config.get("INTEGRATION_API_KEY") or "" ).strip() if not configured: raise ServiceUnavailableError( - "FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured", + "FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured", code="missing_auth", ) diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index 2e4bf122..c3afe87d 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -11,6 +11,7 @@ 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, @@ -30,6 +31,65 @@ 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 自动触发。 + + 核心逻辑:读取配置中的 `SHIPPING_NOTICE_TOOL_API_KEY`,并校验 `Authorization: Bearer ` 或 + `X-Shipping-Tool-Key` 是否命中;未配置时报服务不可用,缺失或错误时报未授权。 + """ + configured = str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip() + if not configured: + raise ServiceUnavailableError( + "SHIPPING_NOTICE_TOOL_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 "" + shipping_key = str(request.headers.get("X-Shipping-Tool-Key") or "").strip() + if configured in {token, shipping_key}: + return + if not token and not shipping_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() diff --git a/backend/app/config.py b/backend/app/config.py index 9b0a5ad6..f5c93548 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -116,7 +116,7 @@ class Config: SHIPPING_NOTICE_TOOL_API_KEY = os.getenv('SHIPPING_NOTICE_TOOL_API_KEY') # 文件检核 Chatflow Tool API - FILE_CHECK_TOOLS_API_KEY = os.getenv('FILE_CHECK_TOOLS_API_KEY') + FILE_CHECK_TOOL_API_KEY = os.getenv('FILE_CHECK_TOOL_API_KEY') 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' diff --git a/backend/app/models.py b/backend/app/models.py index abd130fa..f972d5f9 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -707,7 +707,15 @@ class ShippingBatch(Base): batch_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) - current_focus_task_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + current_focus_task_no: Mapped[Optional[str]] = mapped_column( + String(64), + ForeignKey( + 'shipping_tasks.task_no', + name='fk_shipping_batches_current_focus_task_no_shipping_tasks', + use_alter=True, + ), + nullable=True, + ) file_count: Mapped[int] = mapped_column(Integer, default=1) process_summary_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) @@ -716,6 +724,7 @@ class ShippingBatch(Base): tasks: Mapped[List["ShippingTask"]] = relationship( "ShippingTask", back_populates="batch", + foreign_keys="ShippingTask.batch_id", ) @@ -781,6 +790,7 @@ class ShippingTask(Base): batch: Mapped[Optional["ShippingBatch"]] = relationship( "ShippingBatch", back_populates="tasks", + foreign_keys=[batch_id], ) events: Mapped[List["ShippingTaskEvent"]] = relationship( "ShippingTaskEvent", @@ -803,6 +813,7 @@ class ShippingTaskEvent(Base): class ShippingInventoryMapping(Base): + """客户库存 Excel 表头 → 标准字段的列映射缓存(按 customer_code + header_hash 去重)。""" __tablename__ = 'shipping_inventory_mappings' __table_args__ = ( UniqueConstraint('customer_code', 'header_hash', name='uq_shipping_inventory_mappings_customer_header'), diff --git a/backend/app/services/file_check_tools/openapi_base.json b/backend/app/services/file_check_tools/openapi_base.json index 12f7c70e..02018b8e 100644 --- a/backend/app/services/file_check_tools/openapi_base.json +++ b/backend/app/services/file_check_tools/openapi_base.json @@ -335,7 +335,7 @@ "BearerAuth": { "type": "http", "scheme": "bearer", - "description": "FILE_CHECK_TOOLS_API_KEY 或 INTEGRATION_API_KEY" + "description": "FILE_CHECK_TOOL_API_KEY 或 INTEGRATION_API_KEY" }, "IntegrationKey": { "type": "apiKey", @@ -804,7 +804,7 @@ } }, "MissingAuth": { - "description": "服务端未配置 FILE_CHECK_TOOLS_API_KEY / INTEGRATION_API_KEY", + "description": "服务端未配置 FILE_CHECK_TOOL_API_KEY / INTEGRATION_API_KEY", "content": { "application/json": { "schema": { @@ -813,7 +813,7 @@ "example": { "ok": false, "error_code": "missing_auth", - "message": "FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured" + "message": "FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured" } } } diff --git a/backend/app/services/shipping_notice/agent_resolver.py b/backend/app/services/shipping_notice/agent_resolver.py index 01d4b5d3..4c0ac530 100644 --- a/backend/app/services/shipping_notice/agent_resolver.py +++ b/backend/app/services/shipping_notice/agent_resolver.py @@ -14,4 +14,5 @@ CHAT_AGENT_NAME = "货代发货通知 Agent" def resolve_chat_agent() -> Agent | None: + """按 CHAT_AGENT_NAME 查找当前启用的发货通知聊天 Agent 记录。""" return Agent.query.filter_by(name=CHAT_AGENT_NAME, is_active=True).first() diff --git a/backend/app/services/shipping_notice/chat_actions.py b/backend/app/services/shipping_notice/chat_actions.py index 4579a06c..4cb1a6c8 100644 --- a/backend/app/services/shipping_notice/chat_actions.py +++ b/backend/app/services/shipping_notice/chat_actions.py @@ -1,4 +1,10 @@ -"""Backward-compatible re-exports — canonical definitions live in state_machine.py.""" +""" +services/shipping_notice/chat_actions.py + +用途:chat-actions 相关符号的向后兼容 re-export 入口。 +依赖:state_machine(ACTION_SPECS、CHECKPOINT_REGISTRY、apply_task_transition 等)。 +逻辑:历史代码 import chat_actions;新代码应直接引用 state_machine.py。 +""" from app.services.shipping_notice.state_machine import ( ACTION_SPECS, diff --git a/backend/app/services/shipping_notice/constants.py b/backend/app/services/shipping_notice/constants.py index 5ee5c0a2..f293169b 100644 --- a/backend/app/services/shipping_notice/constants.py +++ b/backend/app/services/shipping_notice/constants.py @@ -1,11 +1,9 @@ -"""Short canonical names for shipping notice API fields and state machine. +""" +services/shipping_notice/constants.py -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) +用途:发货通知 API 字段名、checkpoint / review_status / pending_human_reason 的规范常量。 +依赖:无(纯常量模块);state_machine.py 引用 CP_*/PH_*/RS_* 注册按钮与状态迁移。 +逻辑:tools.py、tool_response、workspace API 统一读本模块,避免 checkpoint id 漂移。 """ from __future__ import annotations @@ -66,6 +64,7 @@ PH_UPLOAD_RPA_PENDING = "upload_rpa_pending" def payload_map_json(payload: dict[str, Any]) -> Any: + """从请求体读取列映射 JSON,兼容 map_json 与 legacy column_mapping_json 字段名。""" raw = payload.get(MAP_JSON) if raw is None: raw = payload.get(MAP_JSON_LEGACY) diff --git a/backend/app/services/shipping_notice/dify_inputs.py b/backend/app/services/shipping_notice/dify_inputs.py index 37ca9bb3..83d84b5b 100644 --- a/backend/app/services/shipping_notice/dify_inputs.py +++ b/backend/app/services/shipping_notice/dify_inputs.py @@ -19,11 +19,12 @@ HXOPS_TOOL_API_KEY_INPUT = "hxops_tool_api_key" def is_shipping_notice_chat_agent(agent) -> bool: + """判断 Agent 记录是否为发货通知聊天 Agent。""" 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.""" + """构建 Dify Chatflow 输入变量(Tool API Base URL 与 API Key)。""" base = resolve_tool_api_base_url() key = str(current_app.config.get("SHIPPING_NOTICE_TOOL_API_KEY") or "").strip() inputs: dict[str, str] = {} diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index a346fe8f..6fd417ce 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -36,6 +36,7 @@ DATA_START_ROW = 4 def _storage_root() -> Path: + """发货通知文件存储根目录(exports/notice_uploads/inventory_uploads 的父路径)。""" root = str(current_app.config.get("SHIPPING_NOTICE_STORAGE_ROOT") or "").strip() if root: return Path(resolve_backend_relative_path(root)) @@ -246,6 +247,15 @@ def _export_filename(task: ShippingTask, ts: str) -> str: def generate_shipment_excel(task: ShippingTask) -> tuple[str, str]: + """ + 基于任务数据生成货代发货 Excel 并写入 exports 目录。 + 【AI 触发时机】:由 generate_excel Tool 调用;Agent 禁止直接操作文件系统。 + + 核心逻辑:复制 PVMI/legacy 模板 → 填充 Header/Detail 或 legacy 行 → 返回 (绝对路径, 文件名)。 + + Returns: + tuple[str, str]: (export_file_path, export_file_name)。 + """ root = _storage_root() / "exports" root.mkdir(parents=True, exist_ok=True) diff --git a/backend/app/services/shipping_notice/extract.py b/backend/app/services/shipping_notice/extract.py index c3bb1062..ae93d5f3 100644 --- a/backend/app/services/shipping_notice/extract.py +++ b/backend/app/services/shipping_notice/extract.py @@ -50,6 +50,19 @@ def extract_notice_fields( structured: dict[str, Any] | None = None, notice_files: list[dict[str, Any]] | None = None, ) -> tuple[dict[str, Any], float, list[str]]: + """ + 抽取发货通知单头与订单行,并计算置信度与 warnings。 + 【AI 触发时机】:由 parse_notice 内部调用;Agent 应调 parse_notice 而非直接调用本函数。 + + Args: + raw_text: 发货通知正文。 + source_type: 来源类型(manual/pdf/email 等)。 + structured: Dify/上游已结构化的解析结果(优先使用)。 + notice_files: 附件元数据列表(预留)。 + + Returns: + tuple: (parsed 字典, confidence, warnings 列表)。 + """ warnings: list[str] = [] if structured and isinstance(structured, dict): diff --git a/backend/app/services/shipping_notice/field_alignment_summary.py b/backend/app/services/shipping_notice/field_alignment_summary.py index d85beb0e..1bbed0a6 100644 --- a/backend/app/services/shipping_notice/field_alignment_summary.py +++ b/backend/app/services/shipping_notice/field_alignment_summary.py @@ -104,7 +104,11 @@ def format_field_alignment_summary( lang: str | None = None, payload: dict[str, Any] | None = None, ) -> str: - """Fixed Markdown summary for apply_inventory_mapping / field alignment review.""" + """ + 生成字段对齐确认的固定 Markdown 摘要(apply_inventory_mapping / align_review 用)。 + + Agent 须原文展示 message 给用户后再等待 confirm_inventory_mapping。 + """ 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: diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index 45390a5c..2af98185 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -95,6 +95,7 @@ def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] | def match_completed(task: ShippingTask) -> bool: + """判断任务是否已完成可履约的库存匹配(process_status=matched 且 line_results 非空)。""" return bool( task.process_status == "matched" and task.match_status @@ -104,6 +105,7 @@ def match_completed(task: ShippingTask) -> bool: def excel_gate_error(task: ShippingTask) -> str | None: + """校验 generate_excel 前置条件;不满足时返回中文错误提示,满足时返回 None。""" if task.process_status == "uploaded" and task.export_file_path: return None if not match_completed(task): @@ -113,6 +115,7 @@ def excel_gate_error(task: ShippingTask) -> str | None: def latest_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent | None: + """按 event_type 查询任务最近一条 ShippingTaskEvent(RPA 超时/重试判定用)。""" if task.id is None: return None return ( @@ -121,6 +124,7 @@ def latest_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent | Non .first() ) def should_auto_chain_after_match(payload: dict[str, Any] | None) -> bool: + """是否应在 match 成功后自动串联 generate_excel / upload_to_freight(Hxops fallback 链)。""" from app.services.shipping_notice.tool_common import payload_wants_auto_chain_fallback return payload_wants_auto_chain_fallback(payload) @@ -132,7 +136,20 @@ def try_auto_chain_after_match( *, payload: dict[str, Any] | None = None, ) -> dict[str, Any]: - """After fulfillable match: generate Excel and optionally trigger RPA upload (fallback chain).""" + """ + 匹配成功后按配置自动串联 Excel 导出与 RPA 上传(Hxops chat fallback 链)。 + + 核心逻辑:仅在 payload 含 auto_chain_fallback 且 match_result 为 ok 时触发; + 依次调用 generate_excel、upload_to_freight,并将消息 prepend 合并返回。 + + Args: + task: 当前 ShippingTask。 + match_result: match_inventory 的 Tool 响应。 + payload: 原始请求体,用于读取 auto_chain_fallback 与 lang 等字段。 + + Returns: + dict[str, Any]: 串联后的 Tool 响应;未触发串联时原样返回 match_result。 + """ if match_result.get("status") != "ok": return match_result if not should_auto_chain_after_match(payload): @@ -162,11 +179,28 @@ def try_auto_chain_after_match( return {**up, "message": result.get("message", up.get("message", ""))} return result + + def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: + """ + 将发货通知订单行与库存快照进行 Reservation ID 匹配,并按结果推进任务状态。 + 【AI 触发时机】:库存已上传且字段对齐已确认后调用;缺库存或仍待映射确认时禁止调用。 + + 核心逻辑:校验映射/库存 → 检查 Reservation ID → match_notice_lines → + fulfillable 时自动串联导出/上传;shortage 时停待人审。 + + Args: + payload: 须含 task_id 或 conversation_id;可含 inventory_lines、lang 等。 + + Returns: + dict[str, Any]: Tool 标准响应;status 可为 ok / needs_human / failed。 + """ task = resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") + # [STEP 1] 先确认字段对齐与库存快照是否已经就绪。 + # 若还停在映射确认阶段或完全没有库存,就不能直接进入匹配计算。 if awaiting_inventory_mapping_confirm(task): lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() return inventory_mapping_checkpoint_response(task, lang=lang or None) @@ -181,6 +215,8 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: inv_payload["lang"] = lang return ensure_inventory(inv_payload) + # [STEP 2] 校验 Reservation ID 前置条件。 + # 当前匹配规则要求订单侧必须具备 Reservation ID,缺失时要先打回上游解析而不是继续匹配。 notice_lines = task.lines_json or [] order_missing = [ {"sku": str(line.get("sku") or "").strip(), "reservation_id": str(line.get("reservation_id") or "").strip()} @@ -216,6 +252,8 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: forbidden_next_tools=["generate_shipment_excel", "upload_to_freight"], ) + # [STEP 3] 执行匹配并按结果分流。 + # fulfillable 时继续走自动串联;shortage/异常时停在人审确认,避免误生成 Excel 或误上传。 match_status, line_results, shortage = match_notice_lines( notice_lines, task.inventory_lines_json or [], @@ -255,11 +293,27 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: message=match_summary, data=serialize_task_for_tool(task), ) + + def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: + """ + 基于已匹配任务生成货代发货 Excel 并推进至 waiting_upload。 + 【AI 触发时机】:match_inventory 返回 fulfillable 且用户需下载/上传 Excel 时调用;未匹配前禁止调用。 + + 核心逻辑:excel_gate_error 门禁 → generate_shipment_excel → 写 export_file_path → WAITING_UPLOAD。 + + Args: + payload: 须含 task_id 或 conversation_id。 + + Returns: + dict[str, Any]: 含 download_hint 的 Tool 响应;门禁失败时 forbidden_next_tools 含 upload_to_freight。 + """ task = resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") + # [STEP 1] 先校验是否满足导出门禁。 + # 只有库存匹配完成后才允许生成货代 Excel,避免基于未确认数据导出。 gate_error = excel_gate_error(task) if gate_error: return tool_response( @@ -271,6 +325,8 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: next_required_action="match_inventory(须先完成库存上传与字段对齐确认)", ) + # [STEP 2] 生成文件并把任务推进到等待上传阶段。 + # 导出文件路径会成为后续 RPA 上传或人工下载的唯一输入。 path, filename = generate_shipment_excel(task) task.export_file_path = path task.export_file_name = filename @@ -283,16 +339,34 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: message=f"已生成发货 Excel:{filename}", data={**serialize_task_for_tool(task), "download_hint": f"/api/shipping-notice/tasks/{task.task_no}/export"}, ) + + def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: + """ + 将已生成的发货 Excel 上传至货代系统,或标记人工上传完成。 + 【AI 触发时机】:Excel 已生成且用户确认上传/重试 RPA 时调用;mode=manual_confirm 用于手工上传收口。 + + 核心逻辑:补齐 export → manual_confirm 直接 UPLOADED → auto/retry_upload 走 RPA 触发与超时重试。 + + Args: + payload: 须含 task_id;mode 可选 auto / retry_upload / manual_confirm;manual_confirm 可传 freight_ref_no。 + + Returns: + dict[str, Any]: status 可为 ok / running / needs_human / failed。 + """ task = resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") + # [STEP 1] 先确保上传所需的 Excel 已经存在。 + # 调用方可能直接请求 upload,此时需要自动补齐 generate_excel 前置步骤。 if not task.export_file_path: gen = generate_excel({"task_id": task.task_no}) if gen.get("status") != "ok": return gen + # [STEP 2] 区分人工确认与 RPA 上传两种路径。 + # manual_confirm 直接收口任务;auto/retry_upload 则走 RPA 触发、轮询和失败兜底。 mode = str(payload.get("mode") or "auto").strip().lower() if mode == "manual_confirm": if task.process_status == "uploaded": @@ -324,6 +398,8 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: human_options=[], ) + # [STEP 3] 处理 RPA 上传状态机。 + # 包括超时检测、最大重试次数限制、触发上传和最终人工兜底提示。 if mode == "retry_upload" or mode == "auto": timeout_seconds = _rpa_upload_timeout_seconds() max_attempts = max_rpa_upload_attempts() @@ -421,7 +497,21 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]: message="RPA 自动上传失败或未配置。请下载 Excel 在货代系统手工上传,完成后告知我。", data=serialize_task_for_tool(task), ) + + def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]: + """ + RPA 上传货代回调入口,报告成功或失败并更新任务终态。 + 【AI 触发时机】:仅由 RPA 回调 HTTP 调用,Agent 禁止主动调用。 + + 核心逻辑:success=True → UPLOADED + freight_ref_no;失败 → UPLOAD_FAILED,达最大重试转人工。 + + Args: + payload: 须含 task_id;success(bool,默认 True);可选 freight_ref_no、error_message。 + + Returns: + dict[str, Any]: 成功时 checkpoint=uploaded;失败时 needs_human 并附带 error_message。 + """ task = resolve_task_from_payload(payload) if not task: return tool_response(status="failed", message="未找到任务编号") @@ -465,18 +555,24 @@ def run_auto_progress_fulfillment_steps( steps: list[str], ) -> dict[str, Any] | None: """auto_progress 中匹配→导出→上传编排;有早停响应时返回 dict,否则返回 None。""" + # [STEP 1] 若允许自动匹配且当前尚未完成匹配,则先进入 match_inventory。 + # 这是履约侧串联的起点,失败或需人审时必须立即早停返回。 if _auto_match_enabled() and not match_completed(task): matched = match_inventory({"task_id": task.task_no, **(payload or {})}) if matched.get("status") != "ok": return matched steps.append("库存匹配") + # [STEP 2] 匹配完成后按配置自动生成 Excel。 + # 只在尚未生成导出文件时触发,避免重复导出覆盖人工下载链路。 if _auto_generate_excel_enabled() and match_completed(task) and not task.export_file_path: gen = generate_excel({"task_id": task.task_no}) if gen.get("status") != "ok": return gen steps.append("生成发货 Excel") + # [STEP 3] 最后根据配置尝试自动上传货代。 + # 上传会返回 running/needs_human 等早停状态,因此这里直接把结果上抛给 auto_progress。 if _auto_upload_enabled() and task.export_file_path and task.process_status != "uploaded": up = upload_to_freight({"task_id": task.task_no, "mode": "auto"}) if up.get("status") == "running": diff --git a/backend/app/services/shipping_notice/i18n.py b/backend/app/services/shipping_notice/i18n.py index e4345544..6bd7d1b8 100644 --- a/backend/app/services/shipping_notice/i18n.py +++ b/backend/app/services/shipping_notice/i18n.py @@ -178,6 +178,7 @@ _MESSAGES: dict[str, dict[str, str]] = { def normalize_lang(raw: Any) -> str: + """将 lang/locale 别名规范化为 zh / en / th。""" text = str(raw or "").strip().lower() if not text: return "zh" @@ -194,6 +195,7 @@ def normalize_lang(raw: Any) -> str: def resolve_lang(payload: dict[str, Any] | None = None) -> str: + """从 payload 或 HTTP 请求头(X-Lang / Accept-Language)解析语言,默认 zh。""" if isinstance(payload, dict): for key in ("lang", "locale", "language"): if key in payload: @@ -212,5 +214,6 @@ def resolve_lang(payload: dict[str, Any] | None = None) -> str: def t(key: str, *, lang: str | None = None) -> str: + """按语言键查找 i18n 文案;未命中时回退 zh 或原 key。""" resolved = normalize_lang(lang) if lang else "zh" return _MESSAGES.get(resolved, {}).get(key) or _MESSAGES["zh"].get(key) or key diff --git a/backend/app/services/shipping_notice/inventory_mapping.py b/backend/app/services/shipping_notice/inventory_mapping.py index 8d6deefe..e873a950 100644 --- a/backend/app/services/shipping_notice/inventory_mapping.py +++ b/backend/app/services/shipping_notice/inventory_mapping.py @@ -16,6 +16,7 @@ SYSTEM_FIELDS = ("sku", "reservation_id", "available_qty") def normalize_field_mapping(raw: Any) -> dict[str, str] | None: + """将 map_json / JSON 字符串规范化为 sku+reservation_id+available_qty 三字段映射;不完整时返回 None。""" data: dict[str, Any] | None = None if isinstance(raw, dict): data = raw @@ -47,7 +48,7 @@ def normalize_field_mapping(raw: Any) -> dict[str, str] | None: def suggest_field_mapping(headers: list[str]) -> dict[str, str]: - """Rule-based fallback mapping from header names.""" + """基于表头名称的规则推断列映射(LLM 不可用时的 fallback)。""" from app.services.shipping_notice.inventory_snapshot import _column_map, _map_header col_map = _column_map() @@ -93,6 +94,7 @@ def suggest_field_mapping(headers: list[str]) -> dict[str, str]: def mapping_is_complete(field_mapping: dict[str, str]) -> bool: + """映射是否同时包含 sku、reservation_id、available_qty 三列。""" return bool(field_mapping.get("sku") and field_mapping.get("available_qty") and field_mapping.get("reservation_id")) @@ -100,7 +102,7 @@ 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] = [] @@ -127,7 +129,7 @@ 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.""" + """将显式 field_mapping 转为系统字段 → 列索引映射(保留自动检测的可选列)。""" from app.services.shipping_notice.inventory_snapshot import DEFAULT_COLUMN_MAP, _resolve_inventory_columns norm_headers = [str(h or "").strip() for h in headers] @@ -165,6 +167,7 @@ def build_column_meta_from_mapping( llm_match_rule: str | None = None, llm_match_key: list[str] | None = None, ) -> dict[str, Any]: + """由用户/LLM 确认的 field_mapping 构建 column_meta(含 match_rule 与 source_column)。""" columns = resolve_columns_from_field_mapping(headers, field_mapping) def source_column(index: int | None) -> str | None: diff --git a/backend/app/services/shipping_notice/inventory_mapping_store.py b/backend/app/services/shipping_notice/inventory_mapping_store.py index 3ebc20fa..9b1bf2f3 100644 --- a/backend/app/services/shipping_notice/inventory_mapping_store.py +++ b/backend/app/services/shipping_notice/inventory_mapping_store.py @@ -26,6 +26,7 @@ def _customer_key(customer_code: str | None) -> str: def compute_inventory_header_hash(headers: list[str], header_row_index: int | None = None) -> str: + """对表头行与 header_row_index 计算 SHA256,用作映射模板去重键。""" norm_headers = [str(h or "").strip() for h in headers] payload = { "header_row_index": int(header_row_index or 1), @@ -36,6 +37,7 @@ def compute_inventory_header_hash(headers: list[str], header_row_index: int | No def find_inventory_mapping(customer_code: str | None, header_hash: str) -> ShippingInventoryMapping | None: + """按 customer_code + header_hash 查找已保存的列映射模板。""" customer = _customer_key(customer_code) if not header_hash: return None @@ -47,6 +49,7 @@ def resolve_inventory_mapping( *, preview: dict[str, Any], ) -> dict[str, str] | None: + """从 schema preview 匹配历史映射模板;命中时更新 last_used_at。""" 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")) @@ -65,6 +68,7 @@ def upsert_inventory_mapping( 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")) diff --git a/backend/app/services/shipping_notice/inventory_mapping_workflow.py b/backend/app/services/shipping_notice/inventory_mapping_workflow.py index c19a4d73..e58d770e 100644 --- a/backend/app/services/shipping_notice/inventory_mapping_workflow.py +++ b/backend/app/services/shipping_notice/inventory_mapping_workflow.py @@ -33,6 +33,7 @@ from app.services.shipping_notice.constants import RS_ALIGN_REVIEW def mapping_review_enabled() -> bool: + """是否启用库存字段对齐人审(SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW,默认 true)。""" val = current_app.config.get("SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW") if val is None: return True @@ -40,10 +41,12 @@ def mapping_review_enabled() -> bool: def awaiting_inventory_mapping_confirm(task: ShippingTask) -> bool: + """任务是否停在 align_review 等待用户确认库存列映射。""" return task.review_status == RS_ALIGN_REVIEW def latest_inventory_column_meta(task: ShippingTask) -> dict[str, Any] | None: + """从最近 30 条任务事件中回溯最新的 column_meta。""" if task.id is None: return None events = ( @@ -61,6 +64,7 @@ def latest_inventory_column_meta(task: ShippingTask) -> dict[str, Any] | None: def field_alignment_for_task(task: ShippingTask, column_meta: dict[str, Any] | None = None) -> dict[str, Any]: + """为当前任务生成 field_alignment 预览(订单行 vs 库存行 + warnings)。""" meta = column_meta or latest_inventory_column_meta(task) return build_field_alignment_preview( task.inventory_lines_json or [], @@ -70,7 +74,7 @@ def field_alignment_for_task(task: ShippingTask, column_meta: dict[str, Any] | N def mapping_confirm_blockers(task: ShippingTask) -> list[str]: - """Reasons inventory field mapping cannot be confirmed yet.""" + """列映射尚不能自动/人工确认的原因列表(中文)。""" blockers: list[str] = [] meta = latest_inventory_column_meta(task) or {} inv_mapping = meta.get("mapping") if isinstance(meta.get("mapping"), dict) else {} @@ -86,7 +90,7 @@ def mapping_confirm_blockers(task: ShippingTask) -> list[str]: def can_auto_advance_mapping(task: ShippingTask) -> bool: - """Mapping is complete with no blockers — may skip align_review human gate.""" + """映射完整且无 blocker 时,auto_progress 可跳过 align_review 人审门禁。""" if not auto_progress_enabled() or not auto_match_enabled(): return False if not mapping_review_enabled(): @@ -106,6 +110,7 @@ def should_auto_chain_after_mapping( task: ShippingTask, payload: dict[str, Any] | None, ) -> bool: + """库存映射完成后是否应自动串联 match_inventory(fallback 或 auto_advance)。""" if payload_wants_auto_chain_fallback(payload): return True return can_auto_advance_mapping(task) @@ -118,7 +123,12 @@ def inventory_mapping_checkpoint_response( extra_data: dict[str, Any] | None = None, lang: str | None = None, ) -> dict[str, Any]: - """Agent MUST stop and wait for user before match_inventory.""" + """ + 返回 align_review 检查点响应,强制 Agent 停等用户确认字段对齐。 + 【AI 触发时机】:match_inventory 发现仍待映射确认时由内部调用;Agent 禁止主动调用。 + """ + # [STEP 1] 先根据任务和列信息构建字段对齐视图。 + # 这里要把库存列、订单字段和额外 warning 汇总成用户能直接确认的 message/data。 field_alignment = field_alignment_for_task(task, column_meta) extra = extra_data or {} message = format_field_alignment_summary( @@ -133,6 +143,8 @@ def inventory_mapping_checkpoint_response( "field_alignment": field_alignment, **extra, } + # [STEP 2] 明确停在人审检查点。 + # 返回值必须阻止同轮继续调用 match_inventory,确保用户先确认字段对齐。 return tool_response( status="needs_human", task=task, @@ -153,6 +165,9 @@ def inventory_mapping_checkpoint_response( def maybe_auto_confirm_inventory_mapping(task: ShippingTask) -> bool: + """auto_progress 路径下自动确认映射并推进 MAPPING_CONFIRMED;成功返回 True。""" + # [STEP 1] 先检查是否满足自动确认前提。 + # 包括开关、当前检查点、阻塞项以及 LLM 映射是否被允许自动接受。 if not auto_progress_enabled(): return False if not mapping_review_enabled(): @@ -165,6 +180,9 @@ def maybe_auto_confirm_inventory_mapping(task: ShippingTask) -> bool: mapping_source = str(meta.get("mapping_source") or "rules").strip().lower() if mapping_source == "llm" and not auto_mapping_allow_llm(): return False + + # [STEP 2] 若映射完整则先落模板,再推进状态机。 + # 这样相同客户/表头的后续上传可以直接复用人工确认过的映射结果。 headers = meta.get("headers") if isinstance(meta.get("headers"), list) else [] field_mapping = meta.get("field_mapping") if isinstance(meta.get("field_mapping"), dict) else None if headers and field_mapping and mapping_is_complete(field_mapping): @@ -176,6 +194,8 @@ def maybe_auto_confirm_inventory_mapping(task: ShippingTask) -> bool: }, field_mapping={str(k): str(v).strip() for k, v in field_mapping.items() if str(v or "").strip()}, ) + + # [STEP 3] 最后把任务推进到 mapping_confirmed,并记录自动确认审计事件。 field_alignment = field_alignment_for_task(task) apply_task_transition(task, TaskTransition.MAPPING_CONFIRMED) log_task_event(task, "inventory_mapping_auto_confirmed", {"field_alignment": field_alignment}) @@ -222,9 +242,20 @@ def inventory_loaded_response( event_type: str, chain_payload: dict[str, Any] | None = None, ) -> dict[str, Any]: + """ + 库存载入后的统一响应编排:写 inventory_lines → 映射复核或 inventory_ready → 可选 auto-chain。 + + Args: + require_mapping_review: True 时进入 align_review;False 时直接 inventory_ready。 + chain_payload: 传递给 auto-chain 的原始请求体。 + """ + # [STEP 1] 先把库存快照写回任务,并计算当前字段对齐视图。 + # 后续无论走人工确认还是直接进入 inventory_ready,都需要统一复用这份 field_alignment。 task.inventory_lines_json = inventory_lines field_alignment = field_alignment_for_task(task, column_meta) + # [STEP 2] 如果当前策略要求映射复核,则先进入对齐确认检查点。 + # 同时尝试自动串联;只有自动串联没有吃掉结果时,才真正返回给用户确认映射。 if require_mapping_review and mapping_review_enabled(): apply_task_transition(task, TaskTransition.INVENTORY_ALIGN_REVIEW) log_task_event( @@ -260,6 +291,8 @@ def inventory_loaded_response( lang=lang, ) + # [STEP 3] 无需映射复核时,直接推进到 inventory_ready。 + # 这条路径主要服务于明确结构化库存输入,尽快把任务交给后续匹配阶段。 apply_task_transition(task, TaskTransition.INVENTORY_READY) log_task_event( task, diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index 0c457a10..3f9c6250 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -49,6 +49,8 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any] """触发或轮询 RPA 库存导出;成功落盘时委托 inventory_workflow.inventory_loaded_response。""" from app.services.shipping_notice.inventory_mapping_workflow import inventory_loaded_response + # [STEP 1] 先检查当前是否已有进行中的 RPA 导出。 + # 若仍在超时窗口内,则返回 running 轮询信息;超时则补记失败事件,避免重复无脑触发。 timeout_seconds = rpa_inventory_timeout_seconds() if ( task.pending_human_reason == PH_RPA_PENDING @@ -95,6 +97,8 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any] ) db.session.flush() + # [STEP 2] 处理重试上限与已落盘文件两种捷径。 + # 已达到最大次数时直接转人工;若目录里已有最新库存文件,则优先吃掉落盘结果而不是再触发一次 RPA。 attempts = inventory_rpa_attempts(task) max_attempts = max_rpa_inventory_attempts() if attempts >= max_attempts and not task.inventory_lines_json: @@ -126,6 +130,8 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any] except Exception as exc: task.error_message = str(exc)[:500] + # [STEP 3] 触发下一次 RPA 导出或给出人工兜底提示。 + # 触发成功则推进到 pending;触发失败则明确要求用户改走手工上传。 attempt_no = attempts + 1 trigger = write_inventory_export_trigger(task.task_no, {"mode": mode, "attempt": attempt_no}) if trigger: @@ -181,6 +187,8 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message="未找到任务编号") + # [STEP 1] 先处理 RPA 回调失败分支。 + # 失败时要累计尝试次数,并在耗尽后明确切换到人工上传兜底。 success = bool(payload.get("success", True)) if not success: apply_task_transition(task, TaskTransition.INV_UNAVAIL) @@ -208,6 +216,8 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: data=serialize_task_for_tool(task), ) + # [STEP 2] 成功回调后读取实际库存文件并交给统一的 inventory_loaded_response。 + # 这样回调路径与人工上传路径在后续字段对齐/自动串联上保持一致。 file_path = str(payload.get("file_path") or "").strip() path = Path(file_path) if file_path else find_latest_inventory_file() if not path or not path.is_file(): diff --git a/backend/app/services/shipping_notice/inventory_snapshot.py b/backend/app/services/shipping_notice/inventory_snapshot.py index e4f6df72..2a6f7138 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot.py +++ b/backend/app/services/shipping_notice/inventory_snapshot.py @@ -236,7 +236,7 @@ def _score_header_candidate(cells: list[Any]) -> int: 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).""" + """在前 max_scan 行中选取最像库存表头的行索引(跳过标题/空行)。""" best_idx = 0 best_score = 0 for i, row in enumerate(rows[:max_scan]): @@ -292,7 +292,7 @@ def describe_inventory_columns( 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 @@ -370,7 +370,7 @@ def build_field_alignment_preview( *, column_meta: dict[str, Any] | None = None, ) -> dict[str, Any]: - """Preview for human confirmation before match_inventory.""" + """生成 match_inventory 前的人工确认预览(样本行、warnings、match_rule)。""" warnings: list[str] = [] mapping = column_meta or {} inv_mapping = mapping.get("mapping") if isinstance(mapping.get("mapping"), dict) else {} @@ -452,7 +452,7 @@ def parse_inventory_rows( *, field_mapping: dict[str, str] | None = None, ) -> list[dict[str, Any]]: - """Parse inventory table rows (Excel or document-extractor text).""" + """按表头与数据行解析库存表格(Excel 或文档提取文本共用)。""" if field_mapping: from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping @@ -479,7 +479,7 @@ def parse_inventory_text( *, 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).""" + """从聊天文本或文档提取器输出解析库存表格(TSV/CSV 形式)。""" warnings: list[str] = [] empty_meta: dict[str, Any] = {"headers": [], "mapping": {}, "match_key": ["sku", "reservation_id"]} text = str(raw_text or "").strip() @@ -523,7 +523,7 @@ def read_inventory_schema_preview( *, max_sample_rows: int = 5, ) -> dict[str, Any]: - """Read headers + sample rows only (safe for LLM context).""" + """仅读取表头与样本行(供 LLM 推断列映射,不加载全量数据)。""" from app.services.shipping_notice.inventory_mapping import suggest_field_mapping scan_rows, total_rows = _load_excel_rows(path, max_rows=40) @@ -568,6 +568,11 @@ def parse_inventory_excel_with_meta( llm_match_rule: str | None = None, llm_match_key: list[str] | None = None, ) -> tuple[list[dict[str, Any]], dict[str, Any]]: + """ + 解析库存 Excel 并返回标准化行与 column_meta。 + + 核心逻辑:定位表头行 → describe_inventory_columns → parse_inventory_rows。 + """ rows, _total = _load_excel_rows(path) if not rows: return [], {"headers": [], "mapping": {}, "match_key": ["sku", "reservation_id"]} @@ -605,6 +610,7 @@ def parse_inventory_excel_with_meta( def parse_inventory_excel(path: Path) -> list[dict[str, Any]]: + """parse_inventory_excel_with_meta 的便捷封装,仅返回库存行列表。""" lines, _meta = parse_inventory_excel_with_meta(path) return lines @@ -616,6 +622,12 @@ def ingest_inventory_file( field_mapping: dict[str, str] | None = None, mapping_source: str = "rules", ) -> tuple[list[dict[str, Any]], dict[str, Any]]: + """ + 解析库存文件并可选择移动至 processed 目录(RPA drop 摄入用)。 + + Returns: + tuple: (inventory_lines, column_meta)。 + """ lines, column_meta = parse_inventory_excel_with_meta( source_path, field_mapping=field_mapping, diff --git a/backend/app/services/shipping_notice/inventory_upload.py b/backend/app/services/shipping_notice/inventory_upload.py index 1dd011f3..51ff479d 100644 --- a/backend/app/services/shipping_notice/inventory_upload.py +++ b/backend/app/services/shipping_notice/inventory_upload.py @@ -23,6 +23,7 @@ from app.services.shipping_notice.inventory_snapshot import ( def inventory_text_max_chars() -> int: + """库存粘贴文本最大字符数(SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS,默认 80000)。""" try: return int(current_app.config.get("SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS") or 80000) except (TypeError, ValueError): @@ -30,11 +31,13 @@ def inventory_text_max_chars() -> int: def task_inventory_upload_path(task_no: str) -> Path: + """任务级库存 Excel 标准落盘路径(inventory_uploads/{task_no}/inventory.xlsx)。""" 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: + """保存 werkzeug FileStorage 库存上传并返回落盘路径。""" path = task_inventory_upload_path(task_no) path.parent.mkdir(parents=True, exist_ok=True) upload.save(str(path)) @@ -42,6 +45,7 @@ def save_task_inventory_upload(task_no: str, upload: FileStorage) -> Path: def read_task_inventory_schema_preview(task_no: str) -> dict[str, Any]: + """读取已上传库存文件的表头与样本行 preview(供映射表单/LLM 用)。""" path = task_inventory_upload_path(task_no) if not path.is_file(): raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件") @@ -59,6 +63,12 @@ def parse_uploaded_task_inventory( llm_match_rule: str | None = None, llm_match_key: list[str] | None = None, ) -> tuple[list[dict[str, Any]], dict[str, Any], Path]: + """ + 解析已上传的任务库存 Excel。 + + Returns: + tuple: (inventory_lines, column_meta, 文件路径)。 + """ path = task_inventory_upload_path(task_no) if not path.is_file(): raise FileNotFoundError(f"未找到任务 {task_no} 的库存上传文件") @@ -74,4 +84,5 @@ def parse_uploaded_task_inventory( def has_uploaded_task_inventory(task_no: str) -> bool: + """任务是否已有落盘的库存 Excel 文件。""" return task_inventory_upload_path(task_no).is_file() diff --git a/backend/app/services/shipping_notice/inventory_workflow.py b/backend/app/services/shipping_notice/inventory_workflow.py index d503fb7e..07a24ed0 100644 --- a/backend/app/services/shipping_notice/inventory_workflow.py +++ b/backend/app/services/shipping_notice/inventory_workflow.py @@ -112,6 +112,8 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message="未找到任务编号") + # [STEP 1] 先归一化库存输入来源与映射提示。 + # 同一个入口要兼容已上传文件、聊天粘贴文本、结构化 JSON 和 LLM 传入的 map_json 扩展字段。 use_uploaded = str(payload.get("use_uploaded_file") or "").strip().lower() in { "1", "true", @@ -127,6 +129,8 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]: if mapping_extras.get("match_rule"): mapping_source = "llm" + # [STEP 2] 按来源解析库存内容。 + # 优先复用已上传文件;否则再回退到 structured 或 raw_text,避免大 Excel 直接走 LLM 文本链路。 if use_uploaded or (not inventory_lines and not raw_text and has_uploaded_task_inventory(task.task_no)): if not has_uploaded_task_inventory(task.task_no): return tool_response( @@ -180,6 +184,8 @@ def parse_inventory(payload: dict[str, Any]) -> dict[str, Any]: field_mapping=field_mapping, ) + # [STEP 3] 对解析失败和成功分别进入下一阶段。 + # 失败时停在人审检查点;成功时统一委托 inventory_loaded_response 进入字段对齐/自动串联。 if not inventory_lines: log_task_event(task, "inventory_parse_failed", {"warnings": warnings, "use_uploaded": use_uploaded}) db.session.commit() @@ -250,6 +256,8 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message="未找到任务编号") + # [STEP 1] 先校验上传文件与 schema preview 是否存在。 + # 映射应用必须基于真实上传文件的表头,不能只凭 LLM 文本猜测继续执行。 if not has_uploaded_task_inventory(task.task_no): return tool_response( status="needs_human", @@ -267,6 +275,8 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]: raw = payload_map_json(payload) + # [STEP 2] 汇总映射候选来源。 + # direct/partial 来自本次 map_json,template/suggested 来自历史模板和表头预判,按完整度决定优先级。 direct = normalize_field_mapping(raw) partial = _extract_partial_inventory_field_mapping(raw) template: dict[str, str] = {} @@ -310,6 +320,8 @@ def apply_inventory_mapping(payload: dict[str, Any]) -> dict[str, Any]: }, ) + # [STEP 3] 确认映射与真实表头一致,再解析整份上传文件。 + # 只有列名校验通过后才允许落地库存明细,避免错误映射污染后续匹配链路。 mapping_errors = validate_field_mapping_against_headers( preview.get("headers") or [], field_mapping, @@ -435,6 +447,8 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message="未找到任务编号") + # [STEP 1] 优先接受当前请求直接携带的库存明细。 + # 这条路径用于小表/结构化库存输入,能直接跳过上传与 RPA 等外围链路。 mode = str(payload.get("mode") or "auto").strip().lower() inventory_lines = parse_inventory_lines(payload) if inventory_lines: @@ -446,11 +460,15 @@ def ensure_inventory(payload: dict[str, Any]) -> dict[str, Any]: event_type="inventory_uploaded", ) + # [STEP 2] 如果允许自动模式,就优先交给 RPA 获取库存。 + # auto / retry_rpa 都属于“先尝试系统拉取库存”,避免不必要地要求用户手工上传。 if mode == "retry_rpa" or mode == "auto": from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa return ensure_inventory_via_rpa(task, mode=mode) + # [STEP 3] 最后处理已有快照与彻底缺库存两种兜底分支。 + # 已有库存则推进到 inventory_ready;仍无库存则明确停在人审提示用户补数据。 if task.inventory_lines_json: if awaiting_inventory_mapping_confirm(task): lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() diff --git a/backend/app/services/shipping_notice/match.py b/backend/app/services/shipping_notice/match.py index 18358d88..36cfa31d 100644 --- a/backend/app/services/shipping_notice/match.py +++ b/backend/app/services/shipping_notice/match.py @@ -27,7 +27,7 @@ def _line_key(sku: str, reservation_id: str | None) -> tuple[str, str]: 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.""" + """按 (sku, reservation_id) 汇总库存 available_qty。""" totals: dict[tuple[str, str], float] = {} for row in inventory_lines: sku = _norm(row.get("sku")) @@ -61,6 +61,15 @@ 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]]: + """ + 将订单行与库存行按 (sku, reservation_id) 匹配,计算 fulfillable/partial/unfulfillable。 + + 核心逻辑:聚合库存 → 逐行比对 required vs available → 汇总 match_status 与 shortages。 + + Returns: + tuple: (match_status, line_results, shortage_json)。 + """ + # [STEP 1] 按 (sku, reservation_id) 聚合库存可用量。 inv_totals = _aggregate_inventory(inventory_lines) line_results: list[dict[str, Any]] = [] @@ -68,6 +77,7 @@ def match_notice_lines( has_partial = False has_shortage = False + # [STEP 2] 逐订单行计算 ok/partial/shortage 并收集缺口明细。 for line in notice_lines: sku = _norm(line.get("sku")) reservation_id = _norm_reservation(line.get("reservation_id")) or None @@ -101,6 +111,7 @@ def match_notice_lines( if shortage > 0: shortages.append(result) + # [STEP 3] 汇总整体 match_status(fulfillable / partial / unfulfillable)。 if not notice_lines: return "unfulfillable", line_results, {"lines": shortages} @@ -132,7 +143,15 @@ def format_match_summary( task_no: str | None = None, lang: str | None = None, ) -> str: - """Fixed Markdown table for match_inventory responses (Agent must display verbatim).""" + """ + 生成 match_inventory 固定 Markdown 表格摘要(Agent 须原文展示给用户)。 + + Args: + match_status: fulfillable / partial / unfulfillable 等。 + line_results: match_notice_lines 返回的逐行结果。 + task_no: 可选任务编号,用于标题行。 + lang: 可选语言码(zh-CN/en/th 等)。 + """ resolved = resolve_lang({"lang": lang} if lang else None) if not line_results: return t("match.no_lines", lang=resolved) diff --git a/backend/app/services/shipping_notice/match_rule_desc.py b/backend/app/services/shipping_notice/match_rule_desc.py index 5573ce53..8c079531 100644 --- a/backend/app/services/shipping_notice/match_rule_desc.py +++ b/backend/app/services/shipping_notice/match_rule_desc.py @@ -28,7 +28,7 @@ def _payload_root(raw: Any) -> dict[str, Any] | None: def extract_mapping_payload_extras(raw: Any) -> dict[str, Any]: - """Read optional LLM fields from map_json (not column names).""" + """从 map_json 读取 match_rule / match_key 等 LLM 扩展字段(非列名映射)。""" data = _payload_root(raw) if not data: return {} @@ -61,6 +61,7 @@ def extract_mapping_payload_extras(raw: Any) -> dict[str, Any]: def infer_match_key(field_mapping: dict[str, str]) -> list[str]: + """根据 field_mapping 推断匹配键列表(默认 sku + reservation_id)。""" keys = ["sku"] if str(field_mapping.get("reservation_id") or "").strip(): keys.append("reservation_id") @@ -72,7 +73,7 @@ def build_match_rule_fallback( *, match_key: list[str] | None = None, ) -> str: - """Dynamic fallback when LLM did not supply match_rule.""" + """LLM 未提供 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) @@ -95,7 +96,7 @@ def resolve_match_rule( 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).""" + """返回 (match_rule, match_key, match_rule_source);优先 LLM 规则,否则 fallback。""" 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" diff --git a/backend/app/services/shipping_notice/notice_line_constants.py b/backend/app/services/shipping_notice/notice_line_constants.py new file mode 100644 index 00000000..cc2238f1 --- /dev/null +++ b/backend/app/services/shipping_notice/notice_line_constants.py @@ -0,0 +1,147 @@ +""" +services/shipping_notice/notice_line_constants.py + +用途:发货通知订单行的字段名、表头映射与展示标签常量。 +依赖:无(纯常量模块)。 +逻辑:由 notice_line_values / notice_line_table / notice_lines 引用;inventory_snapshot 等模块可单独 import 标签常量。 +""" + +from __future__ import annotations + +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", + "项次", +} diff --git a/backend/app/services/shipping_notice/notice_line_table.py b/backend/app/services/shipping_notice/notice_line_table.py new file mode 100644 index 00000000..47b37a91 --- /dev/null +++ b/backend/app/services/shipping_notice/notice_line_table.py @@ -0,0 +1,214 @@ +""" +services/shipping_notice/notice_line_table.py + +用途:从发货通知表格文本或二维行数据中解析订单行。 +依赖:notice_line_constants、notice_line_values、reservation_id、inventory_snapshot(懒加载表格拆行)。 +逻辑:由 extract / notice_lines 调用;输出结构化行供 normalize 与库存匹配链路使用。 +""" + +from __future__ import annotations + +from typing import Any + +from app.services.shipping_notice.notice_line_constants import HEADER_SKIP_TOKENS +from app.services.shipping_notice.notice_line_values import ( + cell, + extract_currency, + infer_reservation_id_from_row, + map_notice_header, + normalize_line_no, + normalize_required_date, + parse_number, + resolve_notice_columns, +) +from app.services.shipping_notice.reservation_id import ( + extract_reservation_id, + find_reservation_id_in_document, +) + + +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: + """ + 按列映射从单行表格数据提取一条订单行。 + + 核心逻辑:校验 SKU 与 qty 必填;依次填充 reservation、价格、币种、交期等可选字段。 + """ + 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 + + 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 score_notice_header_row(cells: list[Any]) -> int: + """为候选表头行打分:映射字段越多、含 sku+qty 组合时分越高。""" + 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: + """在前 max_scan 行中选取得分最高的表头行索引;无有效表头时返回 0。""" + 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]]: + """ + 按表头定义解析发货通知表格数据行。 + + 核心逻辑:根据 headers 推断列映射,仅在识别到有效表头时逐行提取 SKU、数量、金额等字段。 + """ + 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 parse_notice_table_text(raw_text: str) -> list[dict[str, Any]]: + """ + 从发货通知原始文本中的表格片段解析订单行。 + + 核心逻辑:先借助 inventory_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。 + """ + 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 diff --git a/backend/app/services/shipping_notice/notice_line_values.py b/backend/app/services/shipping_notice/notice_line_values.py new file mode 100644 index 00000000..fdb40767 --- /dev/null +++ b/backend/app/services/shipping_notice/notice_line_values.py @@ -0,0 +1,220 @@ +""" +services/shipping_notice/notice_line_values.py + +用途:订单行单字段值的解析、归一化与表头列映射推断。 +依赖:notice_line_constants、reservation_id。 +逻辑:由 notice_line_table 解析表格行、notice_lines 标准化 dict 行时调用;不直接暴露给上游业务模块。 +""" + +from __future__ import annotations + +import re +from typing import Any + +from app.services.shipping_notice.notice_line_constants import ( + HEADER_SKIP_TOKENS, + NOTICE_COLUMN_MAP, + NOTICE_LINE_FIELDS, +) +from app.services.shipping_notice.reservation_id import ( + extract_reservation_id, + looks_like_reservation_id, +) + +_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 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: + """ + 将原始表头文本映射为系统字段名。 + + 核心逻辑:先精确匹配 NOTICE_COLUMN_MAP,再按 norm_header 做大小写/空格无关匹配。 + """ + 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]: + """ + 根据表头行推断各系统字段对应的列索引。 + + 核心逻辑:逐列 map_notice_header;Reservation 列名未命中时使用常见别名兜底。 + """ + 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 + + 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: + """安全读取表格行指定列,越界或 index 为 None 时返回 None。""" + if index is None or index >= len(row): + return None + return row[index] + + +def normalize_line_no(value: Any) -> str: + """将项次/Line No 归一化为字符串;表头 token 或空值返回空串。""" + 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: + """将交期字符串统一为 YYYY-MM-DD;无法识别时原样返回。""" + 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 + + +def normalize_currency(value: Any) -> str: + """将币种文本归一化为 ISO 4217 三字码;无法识别时返回空串。""" + 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: + """ + 从多个候选单元格中推断币种。 + + 核心逻辑:依次尝试 normalize_currency、货币符号前缀、文本内 ISO 三字码匹配。 + """ + 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: + """在未映射 Reservation 列时,从行内其余单元格推断 Reservation ID。""" + for i, cell_value in enumerate(row): + if i in skip_indices: + continue + if looks_like_reservation_id(cell_value): + return extract_reservation_id(cell_value) + return "" diff --git a/backend/app/services/shipping_notice/notice_lines.py b/backend/app/services/shipping_notice/notice_lines.py index ae46b97f..8697fac4 100644 --- a/backend/app/services/shipping_notice/notice_lines.py +++ b/backend/app/services/shipping_notice/notice_lines.py @@ -1,436 +1,46 @@ """ services/shipping_notice/notice_lines.py -用途:标准化发货通知订单行,并从文本/表格中抽取可用于后续库存匹配的行级结构化数据。 -依赖:reservation_id、inventory_snapshot 的表格转行工具、正则与字段映射常量。 -逻辑:由 extract/task_workflow 等上游模块调用本文件完成订单行归一化,再把结果交给匹配、人工更正与摘要生成链路。 +用途:发货通知订单行的标准化、文档级回填、质量校验与完整度评估(对外统一入口)。 +依赖:notice_line_constants、notice_line_values、notice_line_table、reservation_id。 +逻辑:由 extract/task_workflow 等上游模块调用本文件;表格解析委托 notice_line_table,字段归一化委托 notice_line_values。 """ from __future__ import annotations -import re from typing import Any +from app.services.shipping_notice.notice_line_constants import ( + HEADER_SKIP_TOKENS, + NOTICE_COLUMN_MAP, + NOTICE_FIELD_LABELS, + NOTICE_LINE_FIELDS, +) +from app.services.shipping_notice.notice_line_table import ( + parse_notice_table_rows, + parse_notice_table_text, +) +from app.services.shipping_notice.notice_line_values import ( + extract_currency, + map_notice_header, + norm_header, + normalize_currency, + normalize_line_no, + normalize_required_date, + parse_number, +) 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 +# 向后兼容:旧代码/tests 仍可从 notice_lines 引用私有别名 +_HEADER_SKIP_TOKENS = HEADER_SKIP_TOKENS +_extract_currency = extract_currency +_norm_header = norm_header +_map_notice_header = map_notice_header +_parse_number = parse_number def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None: @@ -451,7 +61,7 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None: if not sku: return None - qty = _parse_number(raw.get("qty") if raw.get("qty") is not None else raw.get("quantity")) + 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 @@ -461,7 +71,7 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None: "uom": str(raw.get("uom") or "EA").strip() or "EA", } - line_no = _normalize_line_no( + line_no = normalize_line_no( raw.get("line_no") or raw.get("lineNo") or raw.get("item") @@ -485,19 +95,19 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None: 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")) + 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")) + 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")) + currency = normalize_currency(raw.get("currency") or raw.get("Currency")) if not currency: - currency = _extract_currency( + currency = extract_currency( raw.get("unit_price"), raw.get("price"), raw.get("amount"), @@ -506,7 +116,7 @@ def normalize_notice_line(raw: dict[str, Any] | None) -> dict[str, Any] | None: if currency: line["currency"] = currency - required_date = _normalize_required_date( + required_date = normalize_required_date( raw.get("required_date") or raw.get("delivery_date") or raw.get("deliveryDate") @@ -539,11 +149,6 @@ def normalize_notice_lines(lines: list[Any] | None) -> list[dict[str, Any]]: 批量标准化订单行列表。 核心逻辑:逐行调用 `normalize_notice_line`,自动过滤掉无效、缺 SKU 或缺数量的脏数据。 - Args: - lines: 原始订单行列表。 - - Returns: - list[dict[str, Any]]: 标准化后的有效订单行集合。 """ if not isinstance(lines, list): return [] @@ -564,12 +169,6 @@ def enrich_notice_with_document_reservation( 用文档级 Reservation ID 回填缺失的订单行。 核心逻辑:优先从 parsed 字段中找 document-level Reservation ID,找不到再从原始文本中兜底提取。 - Args: - parsed: 已解析出的发货通知结构。 - raw_text: 原始发货通知文本,用于补充文档级 Reservation ID。 - - Returns: - dict[str, Any]: 已完成文档级 Reservation ID 回填的解析结果。 """ doc_rid = "" for key in ( @@ -607,17 +206,8 @@ def enrich_notice_with_document_reservation( def enrich_notice_with_document_required_date(parsed: dict[str, Any]) -> dict[str, Any]: - """ - 用文档级 required_date 回填缺失的订单行交期。 - - 核心逻辑:统一格式化文档级日期,并在订单行未给出独立交期时逐行补齐。 - Args: - parsed: 已解析出的发货通知结构。 - - Returns: - dict[str, Any]: 已完成文档级交期回填的解析结果。 - """ - doc_date = _normalize_required_date( + """用文档级 required_date 回填缺失的订单行交期。""" + doc_date = normalize_required_date( parsed.get("required_date") or parsed.get("document_required_date") ) if not doc_date: @@ -644,17 +234,8 @@ def enrich_notice_with_document_required_date(parsed: dict[str, Any]) -> dict[st def enrich_notice_with_document_currency(parsed: dict[str, Any]) -> dict[str, Any]: - """ - 用文档级币种回填缺失的订单行币种。 - - 核心逻辑:统一币种代码,并在订单行未给出币种时沿用文档级币种。 - Args: - parsed: 已解析出的发货通知结构。 - - Returns: - dict[str, Any]: 已完成文档级币种回填的解析结果。 - """ - doc_currency = _normalize_currency( + """用文档级币种回填缺失的订单行币种。""" + doc_currency = normalize_currency( parsed.get("currency") or parsed.get("document_currency") ) if not doc_currency: @@ -680,108 +261,11 @@ def enrich_notice_with_document_currency(parsed: dict[str, Any]) -> dict[str, An return parsed -def parse_notice_table_text(raw_text: str) -> list[dict[str, Any]]: - """ - 从发货通知原始文本中的表格片段解析订单行。 - - 核心逻辑:先借助 inventory_snapshot 的通用表格拆行工具得到二维表,再识别表头并解析数据行。 - Args: - raw_text: 原始发货通知文本,通常来自 PDF/OCR/邮件正文。 - - Returns: - 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]]: - """ - 按表头定义解析发货通知表格数据行。 - - 核心逻辑:根据 headers 推断列映射,仅在识别到有效表头时逐行提取 SKU、数量、金额等字段。 - Args: - headers: 表头行。 - data_rows: 表头之后的数据行集合。 - - Returns: - 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]: """ 生成订单行解析质量告警。 核心逻辑:检查 Reservation ID、价格字段等关键完整性,输出给前端/Agent 的提醒文本。 - Args: - lines: 已标准化的订单行列表。 - - Returns: - list[str]: 告警文案列表,为空表示未发现明显问题。 """ warnings: list[str] = [] if not lines: @@ -791,13 +275,13 @@ def validate_notice_lines(lines: list[dict[str, Any]]) -> list[str]: 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 请核对表头。" + "订单行未解析到 Reservation ID;当前匹配规则会阻断后续库存匹配," + "若订单含 COM ID / Reservation Order 请返回解析阶段核对表头。" ) elif missing_reservation: warnings.append( f"部分订单行缺少 Reservation ID({len(missing_reservation)}/{len(lines)} 行)," - "这些行将按 SKU 汇总库存比对。" + "当前匹配规则会阻断后续库存匹配,请先修正解析结果。" ) invalid_reservation = [ @@ -824,11 +308,6 @@ def notice_parse_completeness(lines: list[dict[str, Any]]) -> float: 评估订单行解析完整度。 核心逻辑:按 SKU、数量、Reservation ID、价格等字段覆盖率计算 0~1 分数。 - Args: - lines: 已标准化的订单行列表。 - - Returns: - float: 0~1 之间的解析完整度分数。 """ if not lines: return 0.0 @@ -845,3 +324,19 @@ def notice_parse_completeness(lines: list[dict[str, Any]]) -> float: item += 0.15 scores.append(item) return round(sum(scores) / len(scores), 4) + + +__all__ = [ + "NOTICE_COLUMN_MAP", + "NOTICE_FIELD_LABELS", + "NOTICE_LINE_FIELDS", + "enrich_notice_with_document_currency", + "enrich_notice_with_document_required_date", + "enrich_notice_with_document_reservation", + "normalize_notice_line", + "normalize_notice_lines", + "notice_parse_completeness", + "parse_notice_table_rows", + "parse_notice_table_text", + "validate_notice_lines", +] diff --git a/backend/app/services/shipping_notice/notice_upload.py b/backend/app/services/shipping_notice/notice_upload.py index 2dfc6a23..7ab79733 100644 --- a/backend/app/services/shipping_notice/notice_upload.py +++ b/backend/app/services/shipping_notice/notice_upload.py @@ -23,6 +23,7 @@ from app.services.shipping_notice.export import _storage_root def task_notice_upload_path(task_no: str, filename: str) -> Path: + """生成任务级发货通知附件落盘路径(notice_uploads/{task_no}/{filename})。""" 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" @@ -30,6 +31,7 @@ def task_notice_upload_path(task_no: str, filename: str) -> Path: 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) @@ -118,6 +120,12 @@ def _blocks_to_text(blocks: list[Block]) -> str: def extract_notice_text(file_path: Path) -> tuple[str, dict[str, Any]]: + """ + 从发货通知附件抽取纯文本(PDF/DOCX/CSV/图片 OCR/EML/HTML 等)。 + + Returns: + tuple[str, dict]: (抽取文本, meta 含 warnings 与 file_type)。 + """ path = Path(file_path) ext = path.suffix.lower().lstrip(".") ctx = Context(file_type=ext) @@ -153,6 +161,7 @@ def extract_notice_text(file_path: Path) -> tuple[str, dict[str, Any]]: def guess_source_type(filename: str) -> str: + """按扩展名推断 source_type(pdf / email / manual)。""" ext = str(Path(filename or "").suffix or "").lower().lstrip(".") if ext in {"pdf"}: return "pdf" @@ -162,6 +171,7 @@ def guess_source_type(filename: str) -> str: def max_notice_chars() -> int: + """发货通知正文最大字符数(SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS,默认 200000)。""" raw = str(current_app.config.get("SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS") or "").strip() try: value = int(raw) if raw else 0 diff --git a/backend/app/services/shipping_notice/parse_summary.py b/backend/app/services/shipping_notice/parse_summary.py index c8cb07f1..b58b48f8 100644 --- a/backend/app/services/shipping_notice/parse_summary.py +++ b/backend/app/services/shipping_notice/parse_summary.py @@ -93,7 +93,13 @@ def format_parse_summary( lang: str | None = None, payload: dict[str, Any] | None = None, ) -> str: - """Fixed Markdown summary for parse_notice / Agent display.""" + """ + 生成 parse_notice 固定 Markdown 摘要(Agent 须原文展示给用户)。 + + Args: + low_confidence: True 时追加低置信度提示。 + include_confirmation_hint: False 时省略「请确认」引导(自动推进路径用)。 + """ 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() diff --git a/backend/app/services/shipping_notice/po_number.py b/backend/app/services/shipping_notice/po_number.py index e04a5afb..84a70eeb 100644 --- a/backend/app/services/shipping_notice/po_number.py +++ b/backend/app/services/shipping_notice/po_number.py @@ -19,15 +19,24 @@ _PO_NUMBER_PATTERNS = ( def normalize_po_number(value: Any) -> str: + """ + 标准化采购单号;Wistron 等客户原文常带 ZNB 前缀(如 ZNB16754796 / ZNB-16754796),输出为纯数字段。 + """ text = str(value or "").strip() if not text: return "" if text.lower() in {"number", "no", "n/a", "na", "none"}: return "" + upper = text.upper() + if upper.startswith("ZNB") and len(text) > 3: + tail = text[3:].strip().lstrip("-_/ ") + if tail.isdigit(): + return tail return text def find_po_number_in_document(text: str) -> str: + """从发货通知全文中按正则模式提取 PO Number。""" raw = str(text or "") if not raw.strip(): return "" @@ -39,6 +48,7 @@ def find_po_number_in_document(text: str) -> str: def enrich_notice_with_po_number(parsed: dict[str, Any], *, raw_text: str = "") -> dict[str, Any]: + """将结构化/文档级 PO Number 回填到 parsed 结果(含 ZNB 前缀标准化)。""" po_number = normalize_po_number( parsed.get("po_number") or parsed.get("PO Number") or parsed.get("purchase_order_number") ) diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index dd54ee04..2d1161bf 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -283,6 +283,7 @@ def serialize_batch_for_tool(batch: ShippingBatch | None) -> dict[str, Any] | No def serialize_batch_summary(batch: ShippingBatch) -> dict[str, Any]: + """工作台批次列表/详情用的批次摘要投影。""" tasks = list(batch.tasks or []) return { "id": batch.id, @@ -297,14 +298,17 @@ def serialize_batch_summary(batch: ShippingBatch) -> dict[str, Any]: def serialize_task_summary(task: ShippingTask) -> dict[str, Any]: + """工作台任务列表用的 SUMMARY 投影。""" return serialize_task(task, TaskProjection.SUMMARY) def serialize_task_detail(task: ShippingTask) -> dict[str, Any]: + """工作台任务详情用的 DETAIL 投影(含 lines、events 等)。""" return serialize_task(task, TaskProjection.DETAIL) def get_batch_for_user(batch_no: str, user_id: int) -> ShippingBatch | None: + """按 batch_no 查找批次并校验 user_id 归属。""" batch = get_batch_by_no(batch_no) if not batch: return None @@ -318,6 +322,7 @@ def list_batches_for_user( *, limit: int = 100, ) -> list[dict[str, Any]]: + """列出用户可见批次摘要(按 created_at 降序,limit 上限 500)。""" q = ShippingBatch.query.filter( (ShippingBatch.user_id == user_id) | (ShippingBatch.user_id.is_(None)) ) @@ -326,6 +331,7 @@ def list_batches_for_user( def list_tasks_for_batch(batch_no: str, user_id: int) -> list[dict[str, Any]]: + """列出批次下已排序任务的 SUMMARY 投影;批次不存在或无权限时返回空列表。""" batch = get_batch_for_user(batch_no, user_id) if not batch: return [] @@ -333,6 +339,7 @@ def list_tasks_for_batch(batch_no: str, user_id: int) -> list[dict[str, Any]]: def get_focus_task_for_batch(batch_no: str, user_id: int) -> ShippingTask | None: + """获取批次当前 focus 任务;未设置时返回 batch_index 最小的首票。""" batch = get_batch_for_user(batch_no, user_id) if not batch: return None @@ -352,6 +359,7 @@ def list_tasks_for_user( process_status: str | None = None, limit: int = 100, ) -> list[dict[str, Any]]: + """列出用户可见任务摘要,可按 batch_no / process_status 过滤。""" q = ShippingTask.query.filter( (ShippingTask.user_id == user_id) | (ShippingTask.user_id.is_(None)) ) @@ -367,6 +375,7 @@ def list_tasks_for_user( def get_task_for_user(task_no: str, user_id: int) -> ShippingTask | None: + """按 task_no 查找任务并校验 user_id 归属。""" task = get_task_by_ref(task_no) if not task: return None diff --git a/backend/app/services/shipping_notice/reservation_id.py b/backend/app/services/shipping_notice/reservation_id.py index 05a30c7d..ef3a417e 100644 --- a/backend/app/services/shipping_notice/reservation_id.py +++ b/backend/app/services/shipping_notice/reservation_id.py @@ -22,7 +22,7 @@ PR_NUMBER_LINE_RE = re.compile( def normalize_reservation_id(value: Any) -> str: - """Normalize reservation id; Excel often stores numeric ids as float.""" + """标准化 Reservation ID;处理 Excel 浮点、千分位与 x.0 尾缀。""" if value is None: return "" @@ -51,7 +51,7 @@ def normalize_reservation_id(value: Any) -> str: def extract_reservation_id(value: Any) -> str: - """Extract reservation id from plain numeric, Excel float, or PR Number (xxx@1000140351).""" + """从纯数字、Excel 浮点或 PR Number(xxx@1000140351)中提取 Reservation ID。""" text = str(value or "").strip() if not text: return "" @@ -73,7 +73,7 @@ def extract_reservation_id(value: Any) -> str: def find_reservation_id_in_document(text: str) -> str: - """Scan document text for PR Number @ reservation id or standalone @1000140351.""" + """扫描全文 PR Number 行或 @1000140351 后缀,提取文档级 Reservation ID。""" body = str(text or "") if not body.strip(): return "" @@ -93,5 +93,6 @@ def find_reservation_id_in_document(text: str) -> str: def looks_like_reservation_id(value: Any) -> bool: + """判断标准化后的值是否符合 8~12 位纯数字 Reservation ID 格式。""" text = normalize_reservation_id(value) return bool(text and RESERVATION_ID_NUMERIC_RE.fullmatch(text)) diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py index 9c0ca790..f4a7fe57 100644 --- a/backend/app/services/shipping_notice/rpa.py +++ b/backend/app/services/shipping_notice/rpa.py @@ -25,10 +25,12 @@ def _path(key: str) -> Path | None: def inventory_drop_dir() -> Path | None: + """RPA 库存 Excel 落盘目录(FREIGHT_INVENTORY_DROP_DIR)。""" return _path("FREIGHT_INVENTORY_DROP_DIR") def inventory_processed_dir() -> Path | None: + """已处理库存文件归档子目录(drop_dir/processed)。""" base = inventory_drop_dir() if not base: return None @@ -36,18 +38,27 @@ def inventory_processed_dir() -> Path | None: def inventory_trigger_dir() -> Path | None: + """RPA 库存导出触发 JSON 目录。""" return _path("FREIGHT_RPA_INVENTORY_TRIGGER_DIR") def upload_queue_dir() -> Path | None: + """货代上传 Excel 队列目录(RPA 从此处读取待上传文件)。""" return _path("FREIGHT_UPLOAD_QUEUE_DIR") def upload_trigger_dir() -> Path | None: + """RPA 货代上传触发 JSON 目录。""" return _path("FREIGHT_RPA_UPLOAD_TRIGGER_DIR") def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None = None) -> str | None: + """ + 写入 RPA 库存导出触发文件 inventory_export_{task_no}.json。 + + Returns: + str | None: 触发文件绝对路径;目录未配置时返回 None。 + """ trigger_dir = inventory_trigger_dir() if not trigger_dir: return None @@ -64,6 +75,12 @@ def write_inventory_export_trigger(task_no: str, payload: dict[str, Any] | None def write_upload_trigger(task_no: str, export_file_path: str, payload: dict[str, Any] | None = None) -> tuple[str | None, str | None]: + """ + 复制 Excel 至上传队列并写入 RPA 上传触发 JSON。 + + Returns: + tuple[str | None, str | None]: (queue 文件路径, trigger 文件路径);失败时 (None, None)。 + """ queue = upload_queue_dir() trigger_dir = upload_trigger_dir() if not queue or not trigger_dir: @@ -90,6 +107,7 @@ def write_upload_trigger(task_no: str, export_file_path: str, payload: dict[str, def find_latest_inventory_file() -> Path | None: + """在 drop 目录中查找最新修改的 xlsx/xls/csv 库存文件。""" drop = inventory_drop_dir() if not drop or not drop.is_dir(): return None diff --git a/backend/app/services/shipping_notice/rpa_attempts.py b/backend/app/services/shipping_notice/rpa_attempts.py index 8122cc17..258c2a41 100644 --- a/backend/app/services/shipping_notice/rpa_attempts.py +++ b/backend/app/services/shipping_notice/rpa_attempts.py @@ -31,6 +31,7 @@ _UPLOAD_SUCCESS_EVENTS = { def inventory_rpa_attempts(task: ShippingTask | None) -> int: + """统计自上次库存成功事件以来的 RPA 库存导出触发/失败次数。""" if not task or task.id is None: return 0 @@ -56,6 +57,7 @@ def inventory_rpa_attempts(task: ShippingTask | None) -> int: def upload_rpa_attempts(task: ShippingTask | None) -> int: + """统计自上次上传成功事件以来的 RPA 货代上传触发/失败次数。""" if not task or task.id is None: return 0 @@ -81,6 +83,7 @@ def upload_rpa_attempts(task: ShippingTask | None) -> int: def max_rpa_inventory_attempts() -> int: + """RPA 库存导出最大重试次数(环境变量 SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS)。""" value = os.getenv("SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS") if value is None or not str(value).strip(): return DEFAULT_RPA_INVENTORY_MAX_ATTEMPTS @@ -92,6 +95,7 @@ def max_rpa_inventory_attempts() -> int: def max_rpa_upload_attempts() -> int: + """RPA 货代上传最大重试次数(环境变量 SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS)。""" value = os.getenv("SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS") if value is None or not str(value).strip(): return DEFAULT_RPA_UPLOAD_MAX_ATTEMPTS diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index c61c577d..54babd73 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -1,16 +1,14 @@ """ -Canonical registry for shipping-notice human nodes. +services/shipping_notice/state_machine.py -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) +用途:发货通知人工节点(checkpoint)与动作按钮的单一注册表,负责任务 DB 字段与 UI 状态的映射。 +依赖:models.ShippingTask、constants(CP_*/PH_*/RS_*)、rpa_attempts。 +逻辑:tools.py 通过 apply_task_transition 写库并返回 checkpoint;chat_actions 与前端 chat-actions API 读本模块生成按钮与 ui_state;新增人工节点时仅改本文件与测试。 -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 +扩展说明(开发者): +- checkpoint id 即 API `checkpoint` / Dify `flow_ckpt` +- 动作按钮 id 定义于 ACTION_SPECS;DB 写入统一走 TaskTransition +- GET /tools/checkpoint-catalog 供文档/CI,不接入 Dify 画布 """ from __future__ import annotations @@ -154,6 +152,7 @@ class TaskUiState: def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]: + """将 human_options 动作 id 列表转为前端/Dify 可用的 action_buttons 结构。""" if not option_ids: return [] buttons: list[dict[str, str]] = [] @@ -166,6 +165,7 @@ def build_action_buttons(option_ids: list[str] | None) -> list[dict[str, str]]: def human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None: + """按静态 checkpoint id 查 CHECKPOINT_REGISTRY 中的默认 human_options。""" if not checkpoint: return None key = str(checkpoint).strip() @@ -176,10 +176,12 @@ def human_options_for_checkpoint(checkpoint: str | None) -> list[str] | None: def action_buttons_for_checkpoint(checkpoint: str | None) -> list[dict[str, str]]: + """checkpoint → action_buttons 的便捷封装(tool_response 与 Dify fallback 用)。""" return build_action_buttons(human_options_for_checkpoint(checkpoint)) def format_actions_directive(option_ids: list[str] | None) -> str: + """将 action_buttons 序列化为 HTML 注释指令,嵌入 Agent 回复供前端解析。""" buttons = build_action_buttons(option_ids) if not buttons: return "" @@ -188,6 +190,7 @@ def format_actions_directive(option_ids: list[str] | None) -> str: def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState: + """无 DB 任务时,仅按 checkpoint id 构造 TaskUiState(Tool 早停响应用)。""" options = human_options_for_checkpoint(checkpoint) cp = str(checkpoint).strip() if checkpoint else None if cp and cp not in CHECKPOINT_REGISTRY: @@ -196,7 +199,7 @@ def ui_state_for_checkpoint(checkpoint: str | None) -> TaskUiState: def upload_req_options_for_task(task: ShippingTask) -> list[str]: - """upload_req checkpoint with RPA-attempt-aware button subsets.""" + """upload_req checkpoint 的动作子集,随 RPA 重试次数动态收缩。""" if task.pending_human_reason == PH_RPA_EXHAUSTED: return list(OPTIONS_UPLOAD_FILE_ONLY) if inventory_rpa_attempts(task) >= max_rpa_inventory_attempts(): @@ -211,7 +214,7 @@ 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).""" + """优先从 task DB 状态解析 human_options;无 task 时回退静态 checkpoint 注册表。""" if task is not None: opts = resolve_task_ui_state(task).human_options if opts is not None: @@ -220,7 +223,12 @@ def human_options_for_task_or_checkpoint( def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: - """Map ShippingTask DB fields → checkpoint + human_options for /chat-actions.""" + """ + 将 ShippingTask DB 字段映射为 checkpoint + human_options(/chat-actions 核心)。 + + 核心逻辑:终态 → 正向流程节点 → pending_human_reason 分支 → 默认 None。 + """ + # [STEP 1] 终态:已上传、已关闭、已驳回 — 无可用按钮。 if task.process_status == "uploaded": return TaskUiState(checkpoint=CP_UPLOADED, human_options=[]) if task.process_status == "closed": @@ -229,6 +237,7 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: if task.process_status == "rejected" or task.review_status == "rejected": return TaskUiState(checkpoint=CP_REJECTED, human_options=[]) + # [STEP 2] RPA 库存耗尽与解析后待库存 — 正向流程中的「下一步」节点。 if task.pending_human_reason == PH_RPA_EXHAUSTED: return TaskUiState( checkpoint=CP_UPLOAD_REQ, @@ -259,6 +268,7 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: human_options=list(CHECKPOINT_REGISTRY[CP_READY_MATCH]), ) + # [STEP 3] 匹配/导出阶段 — matched 后区分待生成与已生成 Excel。 if task.process_status == "matched": if task.export_file_path: return TaskUiState( @@ -270,6 +280,7 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: human_options=list(CHECKPOINT_REGISTRY[CP_READY_EXPORT]), ) + # [STEP 4] 人审分支 — 按 pending_human_reason / review_status 映射 checkpoint。 reason = task.pending_human_reason if reason == PH_ALIGN_REVIEW or task.review_status == RS_ALIGN_REVIEW: return TaskUiState( @@ -322,14 +333,22 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: def checkpoint_for_task(task: ShippingTask) -> str | None: + """从 ShippingTask DB 字段解析当前 checkpoint id。""" return resolve_task_ui_state(task).checkpoint def human_options_for_task(task: ShippingTask) -> list[str] | None: + """从 ShippingTask DB 字段解析当前可用 human_options(含 RPA 动态子集)。""" return resolve_task_ui_state(task).human_options def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]: + """ + 组装 /chat-actions API 响应体,供前端渲染步骤条与动作按钮。 + + Returns: + dict: 含 task_no、checkpoint、process_status、action_buttons 等字段。 + """ ui = resolve_task_ui_state(task) return { "task_no": task.task_no, @@ -342,7 +361,7 @@ def build_chat_actions_payload(task: ShippingTask) -> dict[str, Any]: def build_checkpoint_catalog() -> dict[str, Any]: - """Export for docs, CI, and developer reference — not embedded in Dify (approach B).""" + """导出 checkpoint 注册表供文档/CI 校验(不接入 Dify 画布)。""" checkpoints = [] for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items(): buttons = build_action_buttons(list(option_ids)) @@ -363,7 +382,7 @@ def build_checkpoint_catalog() -> dict[str, Any]: def validate_registry() -> list[str]: - """Return list of validation errors (empty if ok). Used in tests.""" + """校验 CHECKPOINT_REGISTRY 中 action id 是否均存在于 ACTION_SPECS;测试用。""" errors: list[str] = [] for checkpoint_id, option_ids in CHECKPOINT_REGISTRY.items(): for option_id in option_ids: @@ -534,7 +553,15 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = { def apply_task_transition(task: ShippingTask, transition: TaskTransition) -> None: - """Apply a named transition to task process/review/pending_human_reason fields.""" + """ + 将命名状态迁移写入 ShippingTask 的 process_status / review_status / pending_human_reason。 + + 核心逻辑:查 TASK_TRANSITIONS 表驱动字段更新;所有 Tool 写库须经本函数,禁止散落赋值。 + + Args: + task: 待更新的 ShippingTask 实例(尚未 commit)。 + transition: TaskTransition 枚举值。 + """ spec = TASK_TRANSITIONS[transition] if spec.process_status is not _UNSET: task.process_status = spec.process_status diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index 15633677..51ddd259 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -66,6 +66,7 @@ def recompute_batch_summary(batch: ShippingBatch | None) -> None: def sync_batch_after_task_change(task: ShippingTask | None) -> None: + """任务状态变更后刷新所属批次的 process_summary 与 focus 指针。""" if not task or not task.batch: return recompute_batch_summary(task.batch) @@ -277,6 +278,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message="未找到任务编号") + # [STEP 1] 解析任务上下文:终态会话收到新通知时自动建新票,避免覆盖已完结任务。 conv_id = str(payload.get("conversation_id") or "").strip() explicit_task_ref = bool(str(payload.get("task_id") or payload.get("task_no") or "").strip()) new_notice_payload = bool( @@ -310,6 +312,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: if conv_id and not task.conversation_id: task.conversation_id = conv_id + # [STEP 2] 提取单头、订单行与置信度,回写任务字段。 raw_text = str(payload.get("raw_text") or task.raw_content or "").strip() structured = payload.get("structured") if isinstance(payload.get("structured"), dict) else None notice_files = payload.get("notice_files") @@ -350,6 +353,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: "warnings": warnings, } + # [STEP 3] 低置信度停待人审;否则标记 parsed 并准备后续库存链路。 if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7): apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) log_task_event(task, "parse_needs_review", {"confidence": confidence, "warnings": warnings}) @@ -372,6 +376,7 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: include_confirmation_hint=not should_auto_continue, ) + # [STEP 4] 高置信度且尚无库存时,自动串联 auto_progress 或 ensure_inventory。 if should_auto_continue: lang = payload.get("lang") if isinstance(payload, dict) else None auto_payload: dict[str, Any] = {"task_id": task.task_no, "mode": "auto"} diff --git a/backend/app/services/shipping_notice/tool_api_url.py b/backend/app/services/shipping_notice/tool_api_url.py index 9d182ee6..1e17cc31 100644 --- a/backend/app/services/shipping_notice/tool_api_url.py +++ b/backend/app/services/shipping_notice/tool_api_url.py @@ -12,5 +12,5 @@ from app.services.hxops_tool_api import resolve_HXOPS_TOOLS_API_BASE def resolve_tool_api_base_url(*, config: dict | None = None, request_host: str | None = None) -> str: - """Resolve hxops Tool API root URL (no trailing slash).""" + """解析 hxops Tool API 根地址(无尾部斜杠)。""" return resolve_HXOPS_TOOLS_API_BASE(config=config, request_host=request_host) diff --git a/backend/app/services/shipping_notice/tool_common.py b/backend/app/services/shipping_notice/tool_common.py index 3da808e1..d9a3ad9d 100644 --- a/backend/app/services/shipping_notice/tool_common.py +++ b/backend/app/services/shipping_notice/tool_common.py @@ -20,6 +20,7 @@ from app.services.shipping_notice.constants import AUTO_CHAIN_FALLBACK def cfg_bool(key: str, default: bool = False) -> bool: + """读取 Flask config 布尔值,支持 1/true/yes/on 字符串形式。""" val = current_app.config.get(key) if val is None: return default @@ -29,6 +30,7 @@ def cfg_bool(key: str, default: bool = False) -> bool: def cfg_int(key: str, default: int = 0, *, min_value: int | None = None) -> int: + """读取 Flask config 整数值,可选 min_value 下限。""" val = current_app.config.get(key) if val is None: parsed = default @@ -43,31 +45,37 @@ def cfg_int(key: str, default: int = 0, *, min_value: int | None = None) -> int: def auto_progress_enabled() -> bool: + """是否启用 auto_progress 自动推进(SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED)。""" return cfg_bool("SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED", False) def auto_rpa_inventory_enabled() -> bool: + """是否允许自动触发 RPA 导出库存。""" return cfg_bool("SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED", True) def rpa_inventory_timeout_seconds() -> int: + """RPA 库存导出等待超时秒数。""" return cfg_int("SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS", 120, min_value=5) def auto_mapping_allow_llm() -> bool: + """字段映射推断是否允许调用 LLM。""" return cfg_bool("SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM", False) def auto_match_enabled() -> bool: + """auto_progress 是否自动调用 match_inventory。""" return cfg_bool("SHIPPING_NOTICE_AUTO_MATCH_ENABLED", True) def auto_chain_fallback_enabled() -> bool: + """Hxops chat 是否在 match 后自动串联 export/upload(全局开关)。""" return cfg_bool("SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK", True) def payload_wants_auto_chain_fallback(payload: dict[str, Any] | None) -> bool: - """True when caller explicitly opts into backend fallback chaining (Hxops workspace/chat).""" + """payload 是否显式请求 Hxops 后端 fallback 串联(auto_chain_fallback=true 且全局开关开启)。""" if not payload or not auto_progress_enabled() or not auto_chain_fallback_enabled(): return False val = payload.get(AUTO_CHAIN_FALLBACK) @@ -84,6 +92,7 @@ def merge_tool_payload( *, extra: dict[str, Any] | None = None, ) -> dict[str, Any]: + """合并 task_id、lang 与 auto_chain_fallback 等字段,供 workflow 间传递。""" result = tool_payload_for_task(task, payload) if extra: result.update(extra) @@ -93,6 +102,7 @@ def merge_tool_payload( def tool_payload_for_task(task: ShippingTask, payload: dict[str, Any] | None = None) -> dict[str, Any]: + """从 task 与原始 payload 提取 workflow 间传递的最小字段集(task_id + lang)。""" result: dict[str, Any] = {"task_id": task.task_no} if not payload: return result @@ -102,7 +112,10 @@ def tool_payload_for_task(task: ShippingTask, payload: dict[str, Any] | None = N result["lang"] = lang break return result + + def prepend_tool_message(result: dict[str, Any], prefix: str) -> dict[str, Any]: + """将 prefix 消息 prepend 到 Tool 响应 message 字段(自动串联时合并多步提示)。""" note = str(prefix or "").strip() if not note: return result @@ -116,9 +129,12 @@ def prepend_tool_message(result: dict[str, Any], prefix: str) -> dict[str, Any]: def generate_task_no() -> str: + """生成 SN-YYYYMMDD-XXXXXXXX 格式任务编号。""" return f"SN-{datetime.utcnow().strftime('%Y%m%d')}-{uuid.uuid4().hex[:8].upper()}" + def log_task_event(task: ShippingTask, event_type: str, detail: dict[str, Any] | None = None) -> None: + """写入 ShippingTaskEvent 审计记录(task 尚未 flush 时自动 flush)。""" if task.id is None: db.session.flush() db.session.add(ShippingTaskEvent( diff --git a/backend/app/services/shipping_notice/tool_response.py b/backend/app/services/shipping_notice/tool_response.py index 40e6313e..7a32e765 100644 --- a/backend/app/services/shipping_notice/tool_response.py +++ b/backend/app/services/shipping_notice/tool_response.py @@ -28,11 +28,15 @@ def tool_response( forbidden_next_tools: list[str] | None = None, stop_agent_turn: bool = False, ) -> dict[str, Any]: - """Build a shipping-notice tool JSON response. + """ + 构建发货通知 Tool 标准 JSON 响应。 - 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``). + 核心逻辑:未显式传 checkpoint 时从 task DB 状态推导 checkpoint/human_options/action_buttons; + 显式 checkpoint 优先(如 parse_ok、task_exists)。 + + Args: + stop_agent_turn: True 时要求 Agent 本回合停止,等待用户操作。 + forbidden_next_tools: 禁止 Agent 同轮调用的 Tool 名称列表。 """ from app.services.shipping_notice.state_machine import ( action_buttons_for_checkpoint, diff --git a/backend/app/services/shipping_notice/user_facing_status.py b/backend/app/services/shipping_notice/user_facing_status.py index 198ad6b4..3a657142 100644 --- a/backend/app/services/shipping_notice/user_facing_status.py +++ b/backend/app/services/shipping_notice/user_facing_status.py @@ -1,4 +1,10 @@ -"""Human-readable task progress — never expose DB / state-machine codes to end users.""" +""" +services/shipping_notice/user_facing_status.py + +用途:将任务 DB / 状态机内部码转为面向用户的中文阶段描述,并过滤 Tool 响应中的内部字段。 +依赖:models.ShippingTask、constants、state_machine.resolve_task_ui_state。 +逻辑:get_task_status 与 tool_response 序列化时调用,防止 Agent 向用户暴露 snake_case 状态码。 +""" from __future__ import annotations @@ -93,4 +99,5 @@ def user_facing_task_stage(task: ShippingTask) -> str: def strip_internal_task_fields(data: dict) -> dict: + """从 Tool data 投影中移除 process_status 等内部字段,避免 Agent 复述给用户。""" return {k: v for k, v in data.items() if k not in TOOL_TASK_DATA_OMIT} diff --git a/backend/migrations/versions/d4c5e6f7a8b9_add_fk_for_shipping_batch_focus_task.py b/backend/migrations/versions/d4c5e6f7a8b9_add_fk_for_shipping_batch_focus_task.py new file mode 100644 index 00000000..fa0a5243 --- /dev/null +++ b/backend/migrations/versions/d4c5e6f7a8b9_add_fk_for_shipping_batch_focus_task.py @@ -0,0 +1,90 @@ +"""add fk for shipping batch focus task + +路径:backend/migrations/versions/d4c5e6f7a8b9_add_fk_for_shipping_batch_focus_task.py +用途:为 shipping_batches.current_focus_task_no 增加到 shipping_tasks.task_no 的外键约束。 +依赖:alembic.op、sqlalchemy.inspect、sqlalchemy.text。 +逻辑:升级时先清理历史 orphan task_no,再添加外键;降级时仅移除该外键约束。 + +Revision ID: d4c5e6f7a8b9 +Revises: c3d4e5f6a7b8 +Create Date: 2026-06-17 18:30:00.000000 +""" + +from alembic import op +import sqlalchemy as sa + + +revision = "d4c5e6f7a8b9" +down_revision = "c3d4e5f6a7b8" +branch_labels = None +depends_on = None + +_FK_NAME = "fk_shipping_batches_current_focus_task_no_shipping_tasks" + + +def _table_columns(insp, table_name: str) -> set[str]: + if table_name not in set(insp.get_table_names()): + return set() + return {col["name"] for col in insp.get_columns(table_name)} + + +def _fk_names(insp, table_name: str) -> set[str]: + if table_name not in set(insp.get_table_names()): + return set() + return {fk["name"] for fk in insp.get_foreign_keys(table_name) if fk.get("name")} + + +def upgrade(): + bind = op.get_bind() + insp = sa.inspect(bind) + + if "shipping_batches" not in set(insp.get_table_names()): + return + if "shipping_tasks" not in set(insp.get_table_names()): + return + + batch_columns = _table_columns(insp, "shipping_batches") + task_columns = _table_columns(insp, "shipping_tasks") + if "current_focus_task_no" not in batch_columns or "task_no" not in task_columns: + return + + # [STEP 1] 先把历史上已经失效的焦点 task 编号置空。 + # 该字段本身允许为空,因此用置空修复脏数据能避免升级时因 orphan 引用失败。 + op.execute( + sa.text( + """ + UPDATE shipping_batches AS sb + SET current_focus_task_no = NULL + WHERE current_focus_task_no IS NOT NULL + AND NOT EXISTS ( + SELECT 1 + FROM shipping_tasks AS st + WHERE st.task_no = sb.current_focus_task_no + ) + """ + ) + ) + + # [STEP 2] 为 current_focus_task_no 增加到 shipping_tasks.task_no 的外键约束。 + fk_names = _fk_names(sa.inspect(bind), "shipping_batches") + if _FK_NAME in fk_names: + return + + with op.batch_alter_table("shipping_batches", schema=None) as batch_op: + batch_op.create_foreign_key( + _FK_NAME, + "shipping_tasks", + ["current_focus_task_no"], + ["task_no"], + ) + + +def downgrade(): + bind = op.get_bind() + insp = sa.inspect(bind) + fk_names = _fk_names(insp, "shipping_batches") + if _FK_NAME not in fk_names: + return + + with op.batch_alter_table("shipping_batches", schema=None) as batch_op: + batch_op.drop_constraint(_FK_NAME, type_="foreignkey") diff --git a/backend/tests/test_shipping_notice_extract.py b/backend/tests/test_shipping_notice_extract.py index 489f4415..3654cade 100644 --- a/backend/tests/test_shipping_notice_extract.py +++ b/backend/tests/test_shipping_notice_extract.py @@ -160,6 +160,7 @@ def test_extract_notice_fields_structured(): 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) + assert any("阻断后续库存匹配" in w for w in warnings) def test_heuristic_table_skips_title_row(): diff --git a/backend/tests/test_shipping_notice_po_number.py b/backend/tests/test_shipping_notice_po_number.py index d3792924..6e22286f 100644 --- a/backend/tests/test_shipping_notice_po_number.py +++ b/backend/tests/test_shipping_notice_po_number.py @@ -17,6 +17,8 @@ def test_po_number_not_from_pr_number(): def test_normalize_po_number(): assert normalize_po_number(" PO-99 ") == "PO-99" + assert normalize_po_number("ZNB16754796") == "16754796" + assert normalize_po_number("ZNB-16754796") == "16754796" assert normalize_po_number("") == "" diff --git a/docs/dify/shipping_notice_chatflow_export.json b/docs/dify/shipping_notice_chatflow_export.json deleted file mode 100644 index 6f9d6ea1..00000000 --- a/docs/dify/shipping_notice_chatflow_export.json +++ /dev/null @@ -1,510 +0,0 @@ -{ - "template_kind": "hxops_shipping_notice_chatflow_delivery_template", - "template_version": "2026-06-17", - "template_status": "manual-import-required", - "app": { - "name": "货代发货通知 Agent", - "mode": "advanced-chat", - "description": "Hxops 货代发货通知 Chatflow 交付模板。用于在 Dify 画布中手工还原节点、变量、HTTP 调用和 Agent 配置。", - "icon": "truck", - "icon_background": "#E0F2FE" - }, - "delivery_notes": [ - "本文件是仓库侧交付模板,不是从 Dify 控制台实际导出的原生 DSL。", - "实际发布前,仍应在 Dify 中完成节点配置后导出一份官方 DSL 作为最终交付包。", - "Tool API 契约以 docs/openapi/shipping_notice_tools.dify.json 和 backend/app/services/shipping_notice/openapi_spec.py 为准。", - "Agent Prompt、节点职责与 HTTP 示例以 docs/shipping_notice.md 为准。" - ], - "tool_openapi": { - "runtime_import_url": "{{HXOPS_TOOLS_API_BASE}}/api/shipping-notice/tools/openapi.json", - "repo_import_file": "docs/openapi/shipping_notice_tools.dify.json", - "auth": { - "header_name": "X-Shipping-Tool-Key", - "value_from_env": "SHIPPING_NOTICE_TOOL_API_KEY" - } - }, - "environment_variables": [ - { - "name": "HXOPS_API_BASE", - "type": "string", - "required": true, - "example": "http://192.168.100.192:8890" - }, - { - "name": "SHIPPING_NOTICE_TOOL_API_KEY", - "type": "secret", - "required": true, - "example": "your-tool-key" - }, - { - "name": "HXOPS_TOOLS_API_BASE", - "type": "string", - "required": true, - "example": "http://192.168.100.192:8890" - } - ], - "conversation_variables": [ - { - "name": "current_batch_no", - "type": "string", - "description": "当前批次号" - }, - { - "name": "current_task_no", - "type": "string", - "description": "当前聚焦任务号" - }, - { - "name": "current_task_step", - "type": "string", - "description": "当前任务步骤" - }, - { - "name": "current_checkpoint", - "type": "string", - "description": "当前人工节点 / checkpoint" - }, - { - "name": "current_task_status", - "type": "string", - "description": "当前任务 process_status" - }, - { - "name": "batch_queue_summary", - "type": "string", - "description": "批次摘要文案" - }, - { - "name": "last_tool_status", - "type": "string", - "description": "最近一次 Tool 调用状态" - } - ], - "graph": { - "entry_node_id": "start", - "answer_node_id": "answer_final", - "nodes": [ - { - "id": "start", - "type": "start", - "title": "开始", - "outputs": [ - "query", - "files", - "conversation_id" - ], - "doc_anchor": "docs/shipping_notice.md#L471-L480" - }, - { - "id": "ctx_preprocess", - "type": "code", - "title": "预处理上下文", - "script_ref": "docs/shipping_notice.md#L481-L523", - "outputs": [ - "normalized_query", - "detected_batch_no", - "detected_task_no", - "intent_hint", - "has_files", - "error_message" - ] - }, - { - "id": "route_classifier", - "type": "code", - "title": "附件/意图分类", - "script_ref": "docs/shipping_notice.md#L525-L550", - "outputs": [ - "route_key", - "reason" - ] - }, - { - "id": "tool_create_batch", - "type": "tool", - "title": "创建批次", - "operation_id": "create_batch", - "when": "route_key == notice_batch_upload", - "inputs": { - "conversation_id": "{{conversation_id}}", - "file_count": "{{files.length}}" - } - }, - { - "id": "iter_notice_files", - "type": "iteration", - "title": "文件循环器", - "when": "route_key == notice_batch_upload", - "iterates": "files", - "doc_anchor": "docs/shipping_notice.md#L442-L449" - }, - { - "id": "tool_create_task", - "type": "tool", - "title": "创建单个任务", - "operation_id": "create_task", - "inputs": { - "batch_no": "{{current_batch_no}}", - "conversation_id": "{{conversation_id}}", - "source_type": "pdf", - "source_file_name": "{{iter_notice_files.item.name}}", - "source_file_type": "{{iter_notice_files.item.mime_type}}", - "batch_index": "{{iter_notice_files.index}}", - "batch_total": "{{files.length}}" - } - }, - { - "id": "http_extract_notice_text", - "type": "http", - "title": "文本抽取", - "method": "external_or_frontend", - "notes": [ - "由前端或 HTTP 节点完成原文抽取。", - "抽取出的 raw_text 继续传给 LLM字段抽取 / parse_notice。" - ] - }, - { - "id": "llm_extract_notice", - "type": "llm", - "title": "LLM字段抽取", - "prompt_ref": "docs/shipping_notice.md#L733-L778", - "outputs": [ - "llm_json_text" - ] - }, - { - "id": "code_validate_notice_json", - "type": "code", - "title": "抽取结果校验", - "script_ref": "docs/shipping_notice.md#L567-L594", - "outputs": [ - "validated_json", - "is_valid", - "error_message" - ] - }, - { - "id": "tool_parse_notice", - "type": "tool", - "title": "保存解析结果", - "operation_id": "parse_notice", - "inputs": { - "task_id": "{{tool_create_task.text.task_id}}", - "raw_text": "{{http_extract_notice_text.text}}" - } - }, - { - "id": "code_batch_summary", - "type": "code", - "title": "批次摘要组装", - "script_ref": "docs/shipping_notice.md#L596-L621", - "outputs": [ - "batch_queue_summary", - "focus_task_no" - ] - }, - { - "id": "code_set_focus_task", - "type": "code", - "title": "设置当前聚焦任务", - "writes_variables": [ - "current_batch_no", - "current_task_no" - ] - }, - { - "id": "tool_get_task_status_init", - "type": "tool", - "title": "读取当前任务状态", - "operation_id": "get_task_status", - "inputs": { - "task_id": "{{current_task_no}}", - "conversation_id": "{{conversation_id}}" - } - }, - { - "id": "http_upload_inventory", - "type": "http", - "title": "上传库存文件", - "request_ref": "docs/shipping_notice.md#L271-L310", - "method": "POST", - "url": "{{HXOPS_API_BASE}}/api/shipping-notice/tools/upload_inventory_file", - "headers": { - "X-Shipping-Tool-Key": "{{SHIPPING_NOTICE_TOOL_API_KEY}}" - }, - "body_type": "multipart/form-data", - "body": { - "task_id": "{{current_task_no}}", - "file": "{{files[0]}}" - } - }, - { - "id": "tool_schema_preview", - "type": "tool", - "title": "读取 schema preview", - "operation_id": "get_inventory_schema_preview", - "inputs": { - "task_id": "{{current_task_no}}" - } - }, - { - "id": "llm_map_inventory", - "type": "llm", - "title": "LLM字段映射建议", - "prompt_ref": "docs/shipping_notice.md#L780-L815", - "outputs": [ - "mapping_json_text" - ] - }, - { - "id": "code_validate_mapping", - "type": "code", - "title": "映射 JSON 校验", - "script_ref": "docs/shipping_notice.md#L651-L678", - "outputs": [ - "mapping_json", - "is_valid", - "error_message" - ] - }, - { - "id": "tool_apply_mapping", - "type": "tool", - "title": "应用字段映射", - "operation_id": "apply_inventory_mapping", - "inputs": { - "task_id": "{{current_task_no}}", - "map_json": "{{code_validate_mapping.mapping_json}}" - } - }, - { - "id": "code_alignment_result", - "type": "code", - "title": "字段对齐结果收口", - "notes": [ - "整理 align_msg / 下一步动作。", - "若 stop_agent_turn=true,则直接进入 Answer。" - ] - }, - { - "id": "code_switch_intent", - "type": "code", - "title": "任务切换意图解析", - "script_ref": "docs/shipping_notice.md#L623-L649", - "when": "route_key == task_switch" - }, - { - "id": "tool_switch_focus_task", - "type": "tool", - "title": "切换聚焦任务", - "operation_id": "switch_focus_task", - "when": "route_key == task_switch", - "inputs": { - "batch_no": "{{current_batch_no}}", - "task_id": "{{code_switch_intent.target_task_no}}", - "switch_mode": "{{code_switch_intent.switch_mode}}" - } - }, - { - "id": "tool_get_task_status_after_switch", - "type": "tool", - "title": "加载当前任务详情", - "operation_id": "get_task_status", - "when": "route_key == task_switch", - "inputs": { - "task_id": "{{current_task_no}}", - "conversation_id": "{{conversation_id}}" - } - }, - { - "id": "agent_shipping", - "type": "agent", - "title": "货代 Agent", - "instruction_ref": "docs/shipping_notice.md#L881-L912", - "tool_bindings": [ - "get_task_status", - "submit_decision", - "match_inventory", - "generate_shipment_excel", - "upload_to_freight", - "auto_progress", - "get_inventory_schema_preview", - "apply_inventory_mapping", - "ensure_inventory", - "parse_inventory", - "update_notice_fields", - "update_notice_line" - ] - }, - { - "id": "code_normalize_tool_result", - "type": "code", - "title": "工具结果标准化", - "script_ref": "docs/shipping_notice.md#L680-L704", - "outputs": [ - "tool_status", - "tool_message", - "tool_checkpoint", - "tool_action_buttons", - "tool_human_options", - "tool_data_json" - ] - }, - { - "id": "code_build_reply", - "type": "code", - "title": "组装直接回复", - "script_ref": "docs/shipping_notice.md#L706-L731", - "outputs": [ - "final_reply" - ] - }, - { - "id": "answer_final", - "type": "answer", - "title": "直接回复", - "text": "{{final_reply}}" - } - ], - "edges": [ - { - "from": "start", - "to": "ctx_preprocess" - }, - { - "from": "ctx_preprocess", - "to": "route_classifier" - }, - { - "from": "route_classifier", - "to": "tool_create_batch", - "condition": "route_key == notice_batch_upload" - }, - { - "from": "tool_create_batch", - "to": "iter_notice_files" - }, - { - "from": "iter_notice_files", - "to": "tool_create_task" - }, - { - "from": "tool_create_task", - "to": "http_extract_notice_text" - }, - { - "from": "http_extract_notice_text", - "to": "llm_extract_notice" - }, - { - "from": "llm_extract_notice", - "to": "code_validate_notice_json" - }, - { - "from": "code_validate_notice_json", - "to": "tool_parse_notice", - "condition": "is_valid == true" - }, - { - "from": "tool_parse_notice", - "to": "code_batch_summary" - }, - { - "from": "code_batch_summary", - "to": "code_set_focus_task" - }, - { - "from": "code_set_focus_task", - "to": "tool_get_task_status_init" - }, - { - "from": "tool_get_task_status_init", - "to": "agent_shipping" - }, - { - "from": "route_classifier", - "to": "http_upload_inventory", - "condition": "route_key == inventory_upload" - }, - { - "from": "http_upload_inventory", - "to": "tool_schema_preview" - }, - { - "from": "tool_schema_preview", - "to": "llm_map_inventory" - }, - { - "from": "llm_map_inventory", - "to": "code_validate_mapping" - }, - { - "from": "code_validate_mapping", - "to": "tool_apply_mapping", - "condition": "is_valid == true" - }, - { - "from": "tool_apply_mapping", - "to": "code_alignment_result" - }, - { - "from": "code_alignment_result", - "to": "answer_final" - }, - { - "from": "route_classifier", - "to": "code_switch_intent", - "condition": "route_key == task_switch" - }, - { - "from": "code_switch_intent", - "to": "tool_switch_focus_task" - }, - { - "from": "tool_switch_focus_task", - "to": "tool_get_task_status_after_switch" - }, - { - "from": "tool_get_task_status_after_switch", - "to": "agent_shipping" - }, - { - "from": "route_classifier", - "to": "agent_shipping", - "condition": "route_key == continue_task" - }, - { - "from": "agent_shipping", - "to": "code_normalize_tool_result" - }, - { - "from": "code_normalize_tool_result", - "to": "code_build_reply" - }, - { - "from": "code_build_reply", - "to": "answer_final" - }, - { - "from": "route_classifier", - "to": "answer_final", - "condition": "route_key == direct_reply" - } - ] - }, - "http_examples": { - "upload_inventory_file_ref": "docs/shipping_notice.md#L271-L310", - "create_batch_ref": "docs/shipping_notice.md#L312-L349", - "apply_inventory_mapping_ref": "docs/shipping_notice.md#L350-L369" - }, - "acceptance_checklist": [ - "OpenAPI 从 docs/openapi/shipping_notice_tools.dify.json 或运行时 /tools/openapi.json 成功导入", - "Agent 节点已绑定 get_task_status/submit_decision/match_inventory/auto_progress/update_notice_* 等工具", - "HTTP 节点已配置 X-Shipping-Tool-Key", - "多通知文件场景能够 create_batch -> create_task -> parse_notice", - "库存 Excel 场景走 upload_inventory_file -> get_inventory_schema_preview -> apply_inventory_mapping", - "align_review 时 Agent 不越过人工确认", - "match_inventory 返回 ok 后,同轮继续 auto_progress", - "parse_review 阶段可调用 update_notice_fields / update_notice_line" - ] -} diff --git a/docs/openapi/file_check_tools_openapi.json b/docs/openapi/file_check_tools_openapi.json index bcfadd88..0653ec7f 100644 --- a/docs/openapi/file_check_tools_openapi.json +++ b/docs/openapi/file_check_tools_openapi.json @@ -335,7 +335,7 @@ "BearerAuth": { "type": "http", "scheme": "bearer", - "description": "FILE_CHECK_TOOLS_API_KEY 或 INTEGRATION_API_KEY" + "description": "FILE_CHECK_TOOL_API_KEY 或 INTEGRATION_API_KEY" }, "IntegrationKey": { "type": "apiKey", @@ -804,7 +804,7 @@ } }, "MissingAuth": { - "description": "服务端未配置 FILE_CHECK_TOOLS_API_KEY / INTEGRATION_API_KEY", + "description": "服务端未配置 FILE_CHECK_TOOL_API_KEY / INTEGRATION_API_KEY", "content": { "application/json": { "schema": { @@ -813,7 +813,7 @@ "example": { "ok": false, "error_code": "missing_auth", - "message": "FILE_CHECK_TOOLS_API_KEY or INTEGRATION_API_KEY is not configured" + "message": "FILE_CHECK_TOOL_API_KEY or INTEGRATION_API_KEY is not configured" } } } @@ -880,4 +880,4 @@ } } } -} \ No newline at end of file +} diff --git a/frontend/src/features/chat/components/ChatViewContent.vue b/frontend/src/features/chat/components/ChatViewContent.vue index 3fb5a184..4033ad56 100644 --- a/frontend/src/features/chat/components/ChatViewContent.vue +++ b/frontend/src/features/chat/components/ChatViewContent.vue @@ -251,6 +251,24 @@ const batchCompletionPercent = computed(() => { /> +
+
+
{{ t('chat.shippingNoticeUi.inventoryTaskPickTitle') }}
+
+ {{ t('chat.shippingNoticeUi.inventoryTaskPickHint') }} +
+
+ +
{ · {{ t('chat.shippingNoticeUi.batchProgress', { index: task.batch_index, total: task.batch_total }) }}
+
+ + {{ t('chat.shippingNoticeUi.inventoryTargetTask', { taskId: task.task_no }) }} + + + {{ t('chat.shippingNoticeUi.inventoryTargetIdle') }} + + +
diff --git a/frontend/src/features/chat/components/ShippingWorkflowStepper.vue b/frontend/src/features/chat/components/ShippingWorkflowStepper.vue index 2e06448b..32f8a857 100644 --- a/frontend/src/features/chat/components/ShippingWorkflowStepper.vue +++ b/frontend/src/features/chat/components/ShippingWorkflowStepper.vue @@ -1,6 +1,8 @@ /** * features/chat/components/ShippingWorkflowStepper.vue - * 货代发货七步流程 Stepper。 + * 用途:货代发货七步流程 Stepper 展示组件。 + * 依赖:shipping/shippingStepper、vue-i18n。 + * 逻辑:Chat 与工作台传入 steps 数组;本组件只负责步骤高亮与标签渲染。 */