diff --git a/.env.dev b/.env.dev index d639cbc1..e50a296b 100644 --- a/.env.dev +++ b/.env.dev @@ -89,10 +89,10 @@ SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx # RPA 目录(相对 backend/ 根目录) -FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop -FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers -FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue -FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers +FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop +FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers +FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue +FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers # 发货 Excel 模板(可选) FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx diff --git a/.env.test b/.env.test index 0f6e28a5..4c790c0e 100644 --- a/.env.test +++ b/.env.test @@ -93,10 +93,10 @@ SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 SHIPPING_NOTICE_EXPORT_FILENAME_PATTERN={task_no}-{date}.xlsx # RPA 目录(相对 backend/ 根目录) -FREIGHT_INVENTORY_DROP_DIR=data/freight_rpa/inventory_drop -FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/freight_rpa/inventory_triggers -FREIGHT_UPLOAD_QUEUE_DIR=data/freight_rpa/upload_queue -FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/freight_rpa/upload_triggers +FREIGHT_INVENTORY_DROP_DIR=data/shipping_notice/freight_rpa/inventory_drop +FREIGHT_RPA_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rpa/inventory_triggers +FREIGHT_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue +FREIGHT_RPA_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers # 发货 Excel 模板(可选) FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx diff --git a/backend/app/api/workspace_shipping_notice.py b/backend/app/api/workspace_shipping_notice.py index e67be0a3..86def172 100644 --- a/backend/app/api/workspace_shipping_notice.py +++ b/backend/app/api/workspace_shipping_notice.py @@ -52,6 +52,28 @@ def _require_user(): raise UnauthorizedError() return user + +def _maybe_recheck_inventory_rpa_wait(task: ShippingTask | None) -> None: + """ + 工作台查询兜底复查库存 RPA 等待态。 + + 常规超时/重试由 shipping worker 执行;这里仅在用户查询时发现已超时仍未推进的任务,补偿触发一次幂等复查。 + """ + if not task: + return + from app.services.shipping_notice.inventory_rpa_workflow import maybe_recheck_inventory_rpa_wait + + maybe_recheck_inventory_rpa_wait(task, source="workspace_query") + + +def _maybe_recheck_batch_inventory_rpa_wait(batch: ShippingBatch | None) -> None: + """对批次下任务执行工作台查询兜底复查,避免 worker 异常时页面长期停在等待结果。""" + if not batch: + return + for task in batch.tasks or []: + _maybe_recheck_inventory_rpa_wait(task) + + @workspace_shipping_notice_bp.route('/shipping-tasks', methods=['GET']) def workspace_shipping_tasks(): """列出当前用户可见的发货任务,可按批次与处理状态过滤。""" @@ -72,6 +94,11 @@ def workspace_shipping_batches(): def workspace_shipping_conversation_batch_workspace(conversation_id: str): """返回一个 Agent 会话下的多批次执行工作台快照。""" user = _require_user() + batches = ShippingBatch.query.filter(ShippingBatch.conversation_id == str(conversation_id or "").strip()).filter( + (ShippingBatch.user_id == user.id) | (ShippingBatch.user_id.is_(None)) + ).all() + for batch in batches: + _maybe_recheck_batch_inventory_rpa_wait(batch) return jsonify(get_conversation_batch_workspace(conversation_id, user.id)) @workspace_shipping_notice_bp.route('/shipping-batches/create-from-notices', methods=['POST']) @@ -138,6 +165,7 @@ def workspace_shipping_batch_detail(batch_no: str): batch = get_batch_for_user(batch_no, user.id) if not batch: raise NotFoundError('Not found') + _maybe_recheck_batch_inventory_rpa_wait(batch) focus_task = get_focus_task_for_batch(batch_no, user.id) return jsonify({**serialize_batch_summary(batch), 'tasks': list_tasks_for_batch(batch_no, user.id), 'focus_task': serialize_task_summary(focus_task) if focus_task else None}) @@ -148,6 +176,7 @@ def workspace_shipping_batch_tasks(batch_no: str): batch = get_batch_for_user(batch_no, user.id) if not batch: raise NotFoundError('Not found') + _maybe_recheck_batch_inventory_rpa_wait(batch) return jsonify(list_tasks_for_batch(batch_no, user.id)) @workspace_shipping_notice_bp.route('/shipping-batches//focus-task', methods=['GET']) @@ -157,6 +186,7 @@ def workspace_shipping_batch_focus_task(batch_no: str): batch = get_batch_for_user(batch_no, user.id) if not batch: raise NotFoundError('Not found') + _maybe_recheck_batch_inventory_rpa_wait(batch) focus_task = get_focus_task_for_batch(batch_no, user.id) if not focus_task: raise NotFoundError('Focus task not found') @@ -240,6 +270,41 @@ def workspace_create_shipping_task_from_notice(): orchestrator_started = start_task_orchestrator(task_id) return jsonify({'status': 'ok', 'task_id': task_id, 'message': f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存,后台已开始处理。' if orchestrator_started else f'已上传发货通知文件并创建任务 {task_id}。通知原文已保存。', 'data': {'task': serialize_task_summary(task) if task else {'task_no': task_id}, 'notice_upload': {'filename': upload.filename or '', **meta}, 'parse_status': 'deferred', 'orchestrator_started': orchestrator_started}}) +@workspace_shipping_notice_bp.route('/shipping-tasks//replace-notice', methods=['POST']) +def workspace_replace_shipping_task_notice(task_no: str): + """重新上传发货通知并覆盖当前任务,不新建批次/任务。""" + user = _require_user() + task = get_task_for_user(task_no, user.id) + if not task: + raise NotFoundError('Not found') + upload = request.files.get('file') + if not upload: + raise ValidationError('file is required') + from app.services.shipping_notice import task_workflow + from app.services.shipping_notice.notice_upload import extract_notice_text, guess_source_type, max_notice_chars, save_task_notice_upload + raw = upload.read() or b'' + filename = upload.filename or 'notice' + saved_path = save_task_notice_upload(task.task_no, filename, raw) + text, meta = extract_notice_text(saved_path) + warnings = list(meta.get('warnings') or []) if isinstance(meta, dict) else [] + if text: + limit = max_notice_chars() + if len(text) > limit: + text = text[:limit] + warnings.append(f'notice_text_truncated:{limit}') + task.source_type = guess_source_type(filename) or task.source_type + result = task_workflow.replace_task_notice( + task, + raw_text=text, + source_file_name=filename, + source_file_type=str(getattr(upload, 'mimetype', '') or '').strip(), + warnings=warnings, + ) + data = result.setdefault('data', {}) + if isinstance(data, dict): + data['notice_upload'] = {'filename': filename, **(meta if isinstance(meta, dict) else {})} + return jsonify(result) + @workspace_shipping_notice_bp.route('/shipping-tasks/', methods=['GET']) def workspace_shipping_task_detail(task_no: str): """返回指定任务的详情快照。""" @@ -247,6 +312,7 @@ def workspace_shipping_task_detail(task_no: str): task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') + _maybe_recheck_inventory_rpa_wait(task) return jsonify(serialize_task_detail(task)) @workspace_shipping_notice_bp.route('/shipping-tasks//chat-actions', methods=['GET']) diff --git a/backend/app/services/shipping_notice/constants.py b/backend/app/services/shipping_notice/constants.py index 3910a556..29b584c5 100644 --- a/backend/app/services/shipping_notice/constants.py +++ b/backend/app/services/shipping_notice/constants.py @@ -59,6 +59,7 @@ PH_SHORTAGE = "shortage" PH_RPA_EXHAUSTED = "rpa_exhausted" PH_RPA_PENDING = "rpa_pending" PH_INV_UNAVAIL = "inv_unavail" +PH_NOTICE_TEXT_EXTRACTION_FAILED = CP_NOTICE_TEXT_EXTRACTION_FAILED PH_UPLOAD_RPA_FAILED = "upload_rpa_failed" PH_UPLOAD_RPA_PENDING = "upload_rpa_pending" diff --git a/backend/app/services/shipping_notice/decision_workflow.py b/backend/app/services/shipping_notice/decision_workflow.py index e8c1d786..0b72b28a 100644 --- a/backend/app/services/shipping_notice/decision_workflow.py +++ b/backend/app/services/shipping_notice/decision_workflow.py @@ -3,7 +3,7 @@ services/shipping_notice/decision_workflow.py 用途:承接发货通知任务的人工作业决策流转,包括确认、驳回、重匹配、重解析和映射修正。 依赖:state_machine、tool_response、query_service、inventory_mapping_workflow、inventory_upload、fulfillment_workflow。 -逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调后端 orchestrator 或 parse_notice。 +逻辑:由 task_workflow 对外转调本文件;本文件在当前任务上下文内执行决策分支,并在必要时回调后端 orchestrator。 """ from __future__ import annotations @@ -373,11 +373,28 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: ) # [STEP 4] 最后处理整单重新解析。 - # 该分支会复用已有任务号和原始文本,避免产生重复任务。 + # 整单重解析必须回到 created 并交给后台 Dify 编排,避免启发式兜底直接覆盖 AI 解析。 if decision == "reparse": - from app.services.shipping_notice.task_workflow import parse_notice - - return parse_notice({"task_id": task.task_no, "raw_text": task.raw_content or ""}) + task.process_status = "created" + task.review_status = None + task.pending_human_reason = None + task.lines_json = [] + task.parse_confidence = None + task.match_status = None + task.shortage_json = None + task.line_results_json = None + task.inventory_lines_json = None + task.error_message = None + log_task_event(task, "notice_reparse_requested", {"comment": comment, "source": "dify_required"}) + db.session.commit() + orchestrator_started = start_task_orchestrator(task.task_no) + return tool_response( + status="running" if orchestrator_started else "ok", + task=task, + message=f"已提交重新解析任务 {task.task_no},后台将通过 Dify 重新抽取发货通知。", + data=serialize_task_for_tool(task), + forbidden_next_tools=["match_inventory", "generate_shipment_excel", "upload_to_freight"], + ) return tool_response( status="failed", diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index 9676d063..00e00f8f 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -8,7 +8,7 @@ services/shipping_notice/inventory_rpa_workflow.py from __future__ import annotations -from datetime import datetime +from datetime import datetime, timedelta from pathlib import Path from typing import Any @@ -49,6 +49,70 @@ def latest_task_event(task: ShippingTask, event_type: str) -> ShippingTaskEvent ) +def inventory_rpa_wait_seconds(task: ShippingTask) -> tuple[int | None, int | None, int | None]: + """ + 返回库存 RPA 当前等待耗时、超时时间和剩余秒数。 + 【AI 触发时机】:需要判断库存 RPA 是否还应等待、是否该调度复查或兜底推进时调用。 + + Args: + task: 当前发货通知任务,必须已经进入 RPA 库存等待态。 + + Returns: + tuple[int | None, int | None, int | None]: (elapsed_seconds, timeout_seconds, remaining_seconds)。 + """ + if ( + task.pending_human_reason != PH_RPA_PENDING + or task.process_status != "waiting_inventory" + or task.inventory_lines_json + ): + return None, None, None + last_trigger = latest_task_event(task, "inventory_rpa_triggered") + if not last_trigger or not isinstance(last_trigger.created_at, datetime): + return None, None, None + timeout_seconds = rpa_inventory_timeout_seconds() + elapsed = max(int((datetime.utcnow() - last_trigger.created_at).total_seconds()), 0) + remaining = max(timeout_seconds - elapsed, 0) + return elapsed, timeout_seconds, remaining + + +def next_inventory_rpa_recheck_at(task: ShippingTask) -> datetime | None: + """ + 计算库存 RPA 下一次复查时间点。 + 【AI 触发时机】:worker 给等待外部 RPA 回执的任务创建延迟复查 job 时调用。 + """ + elapsed, timeout_seconds, remaining = inventory_rpa_wait_seconds(task) + if elapsed is None or timeout_seconds is None or remaining is None: + return None + return datetime.utcnow() + timedelta(seconds=max(remaining, 1)) + + +def maybe_recheck_inventory_rpa_wait(task: ShippingTask, *, source: str = "workspace_fallback") -> dict[str, Any] | None: + """ + 对已超时的库存 RPA 等待态做一次幂等复查。 + 【AI 触发时机】:工作台查询发现任务仍卡在 RPA 等待且已超过超时时间时调用;常规链路仍由 worker 调度。 + + 核心逻辑:未超时立即返回 None;已超时则复用 ensure_inventory_via_rpa,让既有状态机负责失败事件、自动重试和耗尽转人工。 + Args: + task: 当前发货通知任务。 + source: 复查来源,用于审计排障。 + + Returns: + dict | None: 实际触发复查时返回 Tool 响应;未触发时返回 None。 + """ + elapsed, timeout_seconds, remaining = inventory_rpa_wait_seconds(task) + if elapsed is None or timeout_seconds is None or remaining is None: + return None + if remaining > 0: + return None + log_task_event( + task, + "inventory_rpa_wait_rechecked", + {"source": source, "elapsed_seconds": elapsed, "timeout_seconds": timeout_seconds}, + ) + db.session.flush() + return ensure_inventory_via_rpa(task, mode="auto") + + 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 @@ -202,7 +266,20 @@ def ensure_inventory_via_rpa(task: ShippingTask, *, mode: str) -> dict[str, Any] }, ) - log_task_event(task, "inventory_rpa_retry_requested", {}) + apply_task_transition(task, TaskTransition.INV_UNAVAIL) + task.error_message = "RPA 库存目录未配置或触发失败" + set_task_step_progress( + task, + step_key="step3_inventory_prepare", + step_title="获取库存", + status="needs_human", + message="RPA 库存触发失败", + progress_percent=100, + current=0, + total=max_attempts, + detail="请重试 RPA 自动导出,或手动上传货代库存 Excel。", + ) + log_task_event(task, "inventory_rpa_retry_requested", {"reason": "trigger_failed"}) db.session.commit() return tool_response( status="needs_human", diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index 0e8ad30e..2a2e5cf6 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -13,6 +13,7 @@ from typing import Any from flask import current_app from app.services.shipping_notice import fulfillment_workflow +from app import db from app.services.shipping_notice.constants import CP_UPLOAD_REQ, PH_LOW_CONF, RS_PARSE_REVIEW from app.services.shipping_notice.inventory_mapping_workflow import ( awaiting_inventory_mapping_confirm, @@ -21,8 +22,8 @@ from app.services.shipping_notice.inventory_mapping_workflow import ( ) from app.services.shipping_notice.inventory_workflow import ensure_inventory from app.services.shipping_notice.query_service import resolve_task_from_payload, serialize_task_for_tool -from app.services.shipping_notice.state_machine import resolve_task_ui_state -from app.services.shipping_notice.tool_common import auto_progress_enabled, auto_rpa_inventory_enabled +from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition, resolve_task_ui_state +from app.services.shipping_notice.tool_common import auto_progress_enabled, auto_rpa_inventory_enabled, set_task_step_progress from app.services.shipping_notice.tool_response import tool_response @@ -87,6 +88,19 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: # 若库存还没导入,则根据配置决定触发 RPA 拉取,或明确提示人工上传 Excel。 if not task.inventory_lines_json: if not auto_rpa_inventory_enabled(): + apply_task_transition(task, TaskTransition.INV_UNAVAIL) + set_task_step_progress( + task, + step_key="step3_inventory_prepare", + step_title="获取库存", + status="needs_human", + message="未开启自动 RPA 获取库存", + progress_percent=100, + current=0, + total=1, + detail="请手动上传货代库存 Excel,或开启自动 RPA 后重试。", + ) + db.session.commit() return tool_response( status="needs_human", task=task, diff --git a/backend/app/services/shipping_notice/queue_service.py b/backend/app/services/shipping_notice/queue_service.py index ac6eea3c..b3aba22c 100644 --- a/backend/app/services/shipping_notice/queue_service.py +++ b/backend/app/services/shipping_notice/queue_service.py @@ -79,10 +79,20 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None: """把等待 RPA 回调的任务重新放回队列,供 worker 下一轮做超时/重试判断。""" if not _should_requeue_waiting_external_result(task_no): return - recheck_seconds = max( - float(current_app.config.get('SHIPPING_NOTICE_RPA_WAIT_RECHECK_SECONDS', 10) or 10), - 1, - ) + scheduled_at = None + from app.services.shipping_notice.query_service import get_task_by_ref + + task = get_task_by_ref(task_no) + if task and str(task.pending_human_reason or '').strip() == PH_RPA_PENDING: + from app.services.shipping_notice.inventory_rpa_workflow import next_inventory_rpa_recheck_at + + scheduled_at = next_inventory_rpa_recheck_at(task) + if scheduled_at is None: + recheck_seconds = max( + float(current_app.config.get('SHIPPING_NOTICE_RPA_WAIT_RECHECK_SECONDS', 10) or 10), + 1, + ) + scheduled_at = datetime.utcnow() + timedelta(seconds=recheck_seconds) enqueue( JobType.SHIPPING_NOTICE_RUN, { @@ -95,7 +105,7 @@ def _requeue_external_wait_job(task_no: str, *, job: Job | None = None) -> None: message='等待 RPA 回传,稍后自动复查', max_attempts=int(current_app.config.get('SHIPPING_NOTICE_JOB_MAX_ATTEMPTS', 3) or 3), dedupe_active=False, - scheduled_at=datetime.utcnow() + timedelta(seconds=recheck_seconds), + scheduled_at=scheduled_at, ) diff --git a/backend/app/services/shipping_notice/state_machine.py b/backend/app/services/shipping_notice/state_machine.py index 72973e57..305f1dae 100644 --- a/backend/app/services/shipping_notice/state_machine.py +++ b/backend/app/services/shipping_notice/state_machine.py @@ -40,6 +40,7 @@ from app.services.shipping_notice.constants import ( PH_INV_UNAVAIL, PH_LOW_CONF, PH_MAP_INFER, + PH_NOTICE_TEXT_EXTRACTION_FAILED, PH_RPA_EXHAUSTED, PH_RPA_PENDING, PH_RSV_REQ, @@ -66,6 +67,7 @@ ACTION_SPECS: dict[str, dict[str, str]] = { "confirm": {"label": "确认", "message": "确认", "variant": "primary"}, "reject": {"label": "驳回", "message": "驳回", "variant": "danger"}, "reparse": {"label": "重新解析", "message": "重新解析", "variant": "secondary"}, + "replace_notice_file": {"label": "重新上传", "message": "重新上传发货通知", "variant": "primary"}, "confirm_inventory_mapping": {"label": "确认", "message": "确认", "variant": "primary"}, "correct_inventory_mapping": {"label": "更正映射", "message": "更正映射", "variant": "secondary"}, "reparse_inventory": {"label": "重新上传", "message": "重新上传库存", "variant": "secondary"}, @@ -121,7 +123,7 @@ CHECKPOINT_REGISTRY: dict[str, tuple[str, ...]] = { CP_INVENTORY_PENDING: ("upload_inventory_file", "retry_rpa", "paste_inventory_json"), CP_RSV_REQ: ("reparse", "edit_inventory_mapping", "upload_inventory_file", "reject"), RS_SHORTAGE_REVIEW: ("reparse_inventory", "correct_inventory_mapping", "rematch", "reject"), - CP_NOTICE_TEXT_EXTRACTION_FAILED: ("reparse", "reject"), + CP_NOTICE_TEXT_EXTRACTION_FAILED: ("replace_notice_file", "reparse", "reject"), CP_UPLOAD_FAILED: ("retry_upload", "download_excel", "mark_manual_uploaded"), CP_WAITING_UPLOAD: ("refresh", "retry_upload", "download_excel", "mark_manual_uploaded"), CP_READY_MATCH: ("match_inventory",), @@ -312,6 +314,11 @@ def resolve_task_ui_state(task: ShippingTask) -> TaskUiState: checkpoint=CP_PARSE_REVIEW, human_options=list(CHECKPOINT_REGISTRY[CP_PARSE_REVIEW]), ) + if reason == PH_NOTICE_TEXT_EXTRACTION_FAILED: + return TaskUiState( + checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED, + human_options=list(CHECKPOINT_REGISTRY[CP_NOTICE_TEXT_EXTRACTION_FAILED]), + ) if reason == PH_UPLOAD_RPA_FAILED or task.process_status == "upload_failed": return TaskUiState( checkpoint=CP_UPLOAD_FAILED, @@ -429,6 +436,7 @@ class TaskTransition(StrEnum): CORRECT_MAPPING = "correct_mapping" REPARSE_INVENTORY = "reparse_inventory" REPARSE_INVENTORY_DEMOTE = "reparse_inventory_demote" + NOTICE_TEXT_EXTRACTION_FAILED = "notice_text_extraction_failed" REMATCH_REQUESTED = "rematch_requested" WAITING_UPLOAD = "waiting_upload" UPLOAD_RPA_PENDING = "upload_rpa_pending" @@ -536,6 +544,11 @@ TASK_TRANSITIONS: dict[TaskTransition, _TransitionSpec] = { review_status=None, pending_human_reason=None, ), + TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED: _TransitionSpec( + process_status="pending_review", + review_status=None, + pending_human_reason=PH_NOTICE_TEXT_EXTRACTION_FAILED, + ), TaskTransition.REMATCH_REQUESTED: _TransitionSpec( process_status="inventory_ready", review_status=None, diff --git a/backend/app/services/shipping_notice/task_workflow.py b/backend/app/services/shipping_notice/task_workflow.py index 6af46eaf..f0e187ee 100644 --- a/backend/app/services/shipping_notice/task_workflow.py +++ b/backend/app/services/shipping_notice/task_workflow.py @@ -18,6 +18,7 @@ from app import db from app.models import ChatLog, ShippingBatch, ShippingTask from app.services.shipping_notice.agent_resolver import resolve_chat_agent from app.services.shipping_notice.constants import ( + CP_NOTICE_TEXT_EXTRACTION_FAILED, CP_PARSE_OK, CP_TASK_EXISTS, RS_PARSE_REVIEW, @@ -56,6 +57,22 @@ EDITABLE_NOTICE_FIELDS = frozenset({"customer_name", "customer_code", "ship_to", EDITABLE_NOTICE_LINE_FIELDS = frozenset({"sku", "reservation_id", "qty", "quantity", "required_date", "uom"}) +def _has_parse_review_content(task: ShippingTask, lines: list[Any]) -> bool: + """判断解析结果是否有足够内容进入人工复核卡片。""" + if any(isinstance(line, dict) for line in lines): + return True + return any( + str(value or "").strip() + for value in ( + task.customer_name, + task.customer_code, + task.ship_to, + task.po_number, + task.required_date, + ) + ) + + def start_task_orchestrator(task_no: str | None) -> bool: """延迟导入 orchestrator,既打断循环依赖,也保留单测 monkeypatch 入口。""" from app.services.shipping_notice.batch_orchestrator import start_task_orchestrator as _start @@ -521,6 +538,21 @@ def parse_notice(payload: dict[str, Any]) -> dict[str, Any]: # [STEP 3] 低置信度停待人审;否则标记 parsed 并准备后续库存链路。 if confidence < float(current_app.config.get("SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD") or 0.7): + if not _has_parse_review_content(task, lines): + apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED) + log_task_event(task, "notice_text_extraction_failed", {"confidence": confidence, "warnings": warnings}) + db.session.commit() + message = ( + "未能从发货通知中解析到可审核内容,请重新上传清晰版 PDF/文本," + "或复制粘贴通知正文后重新解析。" + ) + return tool_response( + status="needs_human", + task=task, + message=message, + data={**serialize_task_for_tool(task), "warnings": warnings}, + checkpoint=CP_NOTICE_TEXT_EXTRACTION_FAILED, + ) apply_task_transition(task, TaskTransition.PARSE_NEEDS_REVIEW) log_task_event(task, "parse_needs_review", {"confidence": confidence, "warnings": warnings}) _upsert_parse_review_chat_message(task) @@ -601,6 +633,119 @@ def _reset_notice_edit_downstream(task: ShippingTask) -> None: task.idempotency_key = None +def replace_task_notice( + task: ShippingTask, + *, + raw_text: str, + source_file_name: str = "", + source_file_type: str = "", + warnings: list[Any] | None = None, +) -> dict[str, Any]: + """ + 覆盖当前任务的发货通知正文,并重置解析/匹配/导出链路后重新编排。 + + 核心逻辑:保留 task_no、batch_id、batch_index 等任务身份字段,只替换原始通知内容与文件元信息; + 清空旧解析结果和下游匹配/导出/上传状态,避免重新上传清晰文件时误新建批次。 + Args: + task: 当前用户拥有的 ShippingTask。 + raw_text: 经 notice_upload.extract_notice_text 清洗后的通知正文。 + source_file_name: 新上传文件名。 + source_file_type: 新上传文件 MIME 类型。 + warnings: 文件清洗阶段产生的告警。 + + Returns: + dict[str, Any]: Tool 风格响应,包含原 task_no 与后台编排启动状态。 + """ + cleaned_text = str(raw_text or "").strip() + cleaned_warnings = [str(item).strip() for item in (warnings or []) if str(item).strip()] + if not cleaned_text: + apply_task_transition(task, TaskTransition.NOTICE_TEXT_EXTRACTION_FAILED) + task.error_message = "未能从重新上传的发货通知中抽取到可解析文本" + task.raw_content = "" + if source_file_name: + task.source_file_name = source_file_name + if source_file_type: + task.source_file_type = source_file_type + set_task_step_progress( + task, + step_key="step2_parse_confirm", + step_title="确认解析", + status="needs_human", + message="发货通知文本抽取失败", + progress_percent=100, + current=0, + total=0, + detail="未能从文件中抽取到可审核内容,请重新上传清晰版 PDF/文本。", + extra={"warnings": cleaned_warnings}, + ) + log_task_event(task, "notice_replace_extract_failed", {"warnings": cleaned_warnings}) + sync_batch_after_task_change(task) + db.session.commit() + return tool_response( + status="needs_human", + task=task, + message="未能从重新上传的发货通知中抽取到可解析文本,请上传清晰版 PDF/文本或粘贴通知正文。", + data={**serialize_task_for_tool(task), "warnings": cleaned_warnings}, + ) + + task.raw_content = cleaned_text + if source_file_name: + task.source_file_name = source_file_name + if source_file_type: + task.source_file_type = source_file_type + task.customer_name = None + task.customer_code = None + task.ship_to = None + task.po_number = None + task.required_date = None + task.lines_json = [] + task.parse_confidence = None + task.review_status = None + task.pending_human_reason = None + task.error_message = None + task.process_status = "created" + _reset_notice_edit_downstream(task) + set_task_step_progress( + task, + step_key="step1_notice_submit", + step_title="提交通知", + status="completed", + message="已重新上传发货通知并覆盖当前任务", + progress_percent=100, + current=1, + total=1, + detail="已保存新的通知正文,准备重新解析当前任务。", + extra={"warnings": cleaned_warnings}, + ) + log_task_event( + task, + "notice_replaced", + { + "source_file_name": source_file_name, + "source_file_type": source_file_type, + "warnings": cleaned_warnings, + }, + ) + sync_batch_after_task_change(task) + db.session.commit() + orchestrator_started = start_task_orchestrator(task.task_no) + return tool_response( + status="running" if orchestrator_started else "ok", + task=task, + message=( + f"已重新上传发货通知并覆盖当前任务 {task.task_no},后台已开始重新解析。" + if orchestrator_started + else f"已重新上传发货通知并覆盖当前任务 {task.task_no}。" + ), + data={ + **serialize_task_for_tool(task), + "warnings": cleaned_warnings, + "parse_status": "deferred", + "orchestrator_started": orchestrator_started, + }, + ) + + def _commit_notice_edit( task: ShippingTask, *, diff --git a/backend/tests/test_shipping_notice_batches.py b/backend/tests/test_shipping_notice_batches.py index b221fbe6..4126b9f8 100644 --- a/backend/tests/test_shipping_notice_batches.py +++ b/backend/tests/test_shipping_notice_batches.py @@ -7,15 +7,17 @@ 4. 工作台批量上传通知时仅保存 raw_text,首轮解析延后到 Dify。 """ +from datetime import datetime, timedelta from io import BytesIO from app import db -from app.models import Agent, ChatSession, Job, KbJob, ShippingBatch, ShippingTask, User +from app.models import Agent, ChatSession, Job, KbJob, ShippingBatch, ShippingTask, ShippingTaskEvent, User from app.auth_jwt import issue_local_access_token from app.jobs.context import JobContext from app.jobs.queue import process_next_job from app.jobs.types import JobType -from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs +from app.services.shipping_notice import batch_orchestrator, dify_executor, dify_inputs, tools as shipping_tools +from app.services.shipping_notice.progress_workflow import auto_progress def _tool_headers(app): @@ -205,6 +207,184 @@ def test_workspace_create_batch_from_notices_starts_orchestrator_when_enabled(ap assert started == [data["batch_no"]] +def test_parse_notice_empty_result_requires_reupload_instead_of_review(app): + """无订单行且无单头字段时,不应生成空审核卡片,应停在重新上传/清洗节点。""" + with app.app_context(): + user = User(username="shipping_empty_parse_user", email="shipping_empty_parse_user@example.com") + db.session.add(user) + db.session.flush() + task = ShippingTask( + task_no="SN-EMPTY-PARSE-001", + user_id=user.id, + source_type="pdf", + process_status="created", + raw_content="This PDF extraction contains no order table.", + ) + db.session.add(task) + db.session.commit() + + result = shipping_tools.parse_notice({"task_id": task.task_no}) + + db.session.refresh(task) + assert result["status"] == "needs_human" + assert result["checkpoint"] == "notice_text_extraction_failed" + assert [button["id"] for button in result["action_buttons"]] == [ + "replace_notice_file", + "reparse", + "reject", + ] + assert task.pending_human_reason == "notice_text_extraction_failed" + assert task.review_status is None + assert task.lines_json == [] + assert "重新上传" in result["message"] + + +def test_workspace_replace_notice_overwrites_current_task_without_new_batch(app, client): + """重新上传当前任务通知应保留 task_no/batch_no,只覆盖正文并清理旧解析结果。""" + headers = _workspace_headers(app) + with app.app_context(): + user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first() + assert user is not None + batch = ShippingBatch( + batch_no="SB-REPLACE-NOTICE-001", + user_id=user.id, + conversation_id="conv-replace-notice", + current_focus_task_no="SN-REPLACE-NOTICE-001", + file_count=1, + ) + db.session.add(batch) + db.session.flush() + task = ShippingTask( + task_no="SN-REPLACE-NOTICE-001", + batch_id=batch.id, + user_id=user.id, + conversation_id="conv-replace-notice", + source_type="pdf", + process_status="pending_review", + review_status="parse_review", + pending_human_reason="low_confidence", + raw_content="old text", + source_file_name="old.pdf", + lines_json=[{"sku": "OLD", "qty": 1}], + match_status="shortage", + shortage_json={"OLD": 1}, + export_file_name="old.xlsx", + ) + db.session.add(task) + db.session.commit() + original_batch_count = ShippingBatch.query.count() + original_task_count = ShippingTask.query.count() + + res = client.post( + "/api/workspace/shipping-tasks/SN-REPLACE-NOTICE-001/replace-notice", + headers=headers, + data={"file": (BytesIO("客户:ACME\nA001 x 10".encode("utf-8")), "new-notice.txt")}, + content_type="multipart/form-data", + ) + + assert res.status_code == 200 + data = res.get_json() + assert data["status"] in {"ok", "running"} + assert data["data"]["task_no"] == "SN-REPLACE-NOTICE-001" + with app.app_context(): + task = ShippingTask.query.filter_by(task_no="SN-REPLACE-NOTICE-001").one() + assert ShippingBatch.query.count() == original_batch_count + assert ShippingTask.query.count() == original_task_count + assert task.batch.batch_no == "SB-REPLACE-NOTICE-001" + assert task.raw_content == "客户:ACME\nA001 x 10" + assert task.source_file_name == "new-notice.txt" + assert task.lines_json == [] + assert task.review_status is None + assert task.pending_human_reason is None + assert task.match_status is None + assert task.shortage_json is None + assert task.export_file_name is None + + +def test_auto_progress_inventory_trigger_failure_marks_step3(app): + """库存自动获取失败时应进入第 3 步库存准备,而不是继续显示解析确认。""" + app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True + app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True + app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = "" + with app.app_context(): + user = User(username="shipping_inventory_step_user", email="shipping_inventory_step_user@example.com") + db.session.add(user) + db.session.flush() + task = ShippingTask( + task_no="SN-INVENTORY-STEP-001", + user_id=user.id, + source_type="pdf", + process_status="parsed", + parse_confidence=0.95, + raw_content="客户:ACME\nA001 x 10", + lines_json=[{"sku": "A001", "qty": 10}], + current_step="step2_parse_confirm", + ) + db.session.add(task) + db.session.commit() + + result = auto_progress({"task_id": task.task_no, "mode": "auto"}) + + db.session.refresh(task) + assert result["status"] == "needs_human" + assert result["checkpoint"] == "upload_req" + assert task.process_status == "waiting_inventory" + assert task.pending_human_reason == "inv_unavail" + assert task.current_step == "step3_inventory_prepare" + assert task.step_payload_json["current_step_progress"]["status"] == "needs_human" + + +def test_workspace_task_detail_rechecks_timed_out_inventory_rpa(app, client, tmp_path): + """工作台查询遇到已超时 RPA 等待态时,应兜底复查并自动触发下一次库存导出。""" + headers = _workspace_headers(app) + app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True + app.config["SHIPPING_NOTICE_AUTO_RPA_INVENTORY_ENABLED"] = True + app.config["SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS"] = 5 + app.config["FREIGHT_RPA_INVENTORY_TRIGGER_DIR"] = str(tmp_path / "inventory_triggers") + with app.app_context(): + user = User.query.filter_by(username="shipping_workspace_user").order_by(User.id.desc()).first() + assert user is not None + task = ShippingTask( + task_no="SN-RPA-RECHECK-001", + user_id=user.id, + source_type="pdf", + process_status="waiting_inventory", + pending_human_reason="rpa_pending", + parse_confidence=0.95, + raw_content="客户:ACME\nA001 x 10", + lines_json=[{"sku": "A001", "qty": 10}], + ) + db.session.add(task) + db.session.flush() + db.session.add( + ShippingTaskEvent( + task_id=task.id, + event_type="inventory_rpa_triggered", + detail_json={"attempt": 1}, + created_at=datetime.utcnow() - timedelta(seconds=10), + ) + ) + db.session.commit() + + res = client.get("/api/workspace/shipping-tasks/SN-RPA-RECHECK-001", headers=headers) + + assert res.status_code == 200 + data = res.get_json() + assert data["process_status"] == "waiting_inventory" + assert data["pending_human_reason"] == "rpa_pending" + with app.app_context(): + task = ShippingTask.query.filter_by(task_no="SN-RPA-RECHECK-001").one() + events = ShippingTaskEvent.query.filter_by(task_id=task.id).order_by(ShippingTaskEvent.id.asc()).all() + triggered = [event for event in events if event.event_type == "inventory_rpa_triggered"] + failed = [event for event in events if event.event_type == "inventory_rpa_failed"] + rechecked = [event for event in events if event.event_type == "inventory_rpa_wait_rechecked"] + assert len(triggered) == 2 + assert len(failed) == 1 + assert len(rechecked) == 1 + assert triggered[-1].detail_json["attempt"] == 2 + assert task.step_payload_json["current_step_progress"]["current"] == 2 + + def test_workspace_conversation_batch_workspace_aggregates_multiple_batches(app, client): """同一 Agent 会话下多个批次应聚合为一个会话级工作台快照。""" headers = _workspace_headers(app) @@ -469,6 +649,61 @@ def test_run_single_task_routes_created_task_to_dify_executor(app, monkeypatch): assert called.get("dify") == task_no +def test_submit_reparse_resets_task_and_starts_dify_orchestrator(app, monkeypatch): + """重新解析必须回退到 created 并交给后台 Dify,不允许同步启发式解析。""" + with app.app_context(): + batch = ShippingBatch(batch_no="SB-REPARSE-DIFY", file_count=1) + task = ShippingTask( + task_no="SN-20260629-REPARSE1", + batch=batch, + source_type="manual", + raw_content="客户:ACME\nA001 x 10", + process_status="pending_review", + review_status="parse_review", + pending_human_reason="low_confidence", + lines_json=[{"sku": "OLD", "qty": 1}], + parse_confidence=0.42, + match_status="shortage", + shortage_json={"OLD": 1}, + line_results_json=[{"sku": "OLD", "status": "shortage"}], + inventory_lines_json=[{"sku": "OLD", "available_qty": 0}], + error_message="old error", + ) + db.session.add_all([batch, task]) + db.session.commit() + task_no = task.task_no + + started: list[str] = [] + + def fake_start(task_ref: str | None) -> bool: + if task_ref: + started.append(task_ref) + return True + + monkeypatch.setattr( + "app.services.shipping_notice.decision_workflow.start_task_orchestrator", + fake_start, + ) + + result = shipping_tools.submit_decision({"task_id": task_no, "decision": "reparse"}) + + db.session.refresh(task) + assert result["status"] == "running" + assert started == [task_no] + assert task.process_status == "created" + assert task.review_status is None + assert task.pending_human_reason is None + assert task.lines_json == [] + assert task.parse_confidence is None + assert task.match_status is None + assert task.shortage_json is None + assert task.line_results_json is None + assert task.inventory_lines_json is None + assert task.error_message is None + assert "Dify" in result["message"] + assert "【发货通知解析确认】" not in result["message"] + + def test_run_single_task_refreshes_after_dify_parse_before_auto_progress(app, monkeypatch): """Dify Tool 提交解析结果后,编排器应刷新 session 并继续触发自动推进。""" app.config["SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED"] = True diff --git a/docs/shipping_notice.md b/docs/shipping_notice.md index 8b85472a..85dc840f 100644 --- a/docs/shipping_notice.md +++ b/docs/shipping_notice.md @@ -1974,6 +1974,7 @@ Agent 禁用 Tool: - `retry_upload` - `mark_manual_uploaded` - `refresh` +- `replace_notice_file` 说明: @@ -1998,6 +1999,13 @@ Agent 禁用 Tool: 首层附件分流由 Chatflow 的 Code 节点完成(通知/库存附件 → 引导回 **当前对话** 上传)。你负责第二层业务理解与 Tool 调用,**不要接管首层分流职责**。 +#### 重新解析与重新上传边界 + +- `reparse` 只表示:基于当前任务已保存的 `raw_text` 重新执行 Dify 结构化抽取与 `parse_notice`,**不会重新读取原 PDF,也不会重跑 `loader_pdf`**。 +- 当后端返回 `notice_text_extraction_failed`,说明当前任务没有可审核内容;用户应在宿主系统上传清晰版 PDF/文本,宿主系统调用 `/api/workspace/shipping-tasks//replace-notice` 覆盖当前任务通知文件。 +- `replace-notice` 保留原 `task_no / batch_no / batch_index`,重新执行 `save_task_notice_upload → extract_notice_text(loader_pdf/OCR) → 覆盖 raw_content → 重置旧解析/匹配/导出状态 → 重新编排当前票`。 +- 用户主动上传多份新通知时才新建批次;当前任务失败上下文里的单文件重新上传必须修复当前票,禁止误建新批次。 + #### 主流程 【宿主系统已完成】建 task + raw_text 落库 diff --git a/frontend/src/constants/shippingNoticeActions.ts b/frontend/src/constants/shippingNoticeActions.ts index 2dc2bc3c..c1829e8d 100644 --- a/frontend/src/constants/shippingNoticeActions.ts +++ b/frontend/src/constants/shippingNoticeActions.ts @@ -7,6 +7,7 @@ export const SHIPPING_ACTION_IDS = [ 'confirm', 'reject', 'reparse', + 'replace_notice_file', 'confirm_inventory_mapping', 'correct_inventory_mapping', 'reparse_inventory', diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index 87ec7842..f6ac137a 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -167,6 +167,28 @@ export async function createWorkspaceShippingTaskFromNotice(file: File, conversa return body; } +/** + * 重新上传发货通知并覆盖当前任务。 + * @param taskNo - 需要覆盖的发货任务编号 + * @param file - 新的发货通知文件 + * @returns 覆盖后的任务状态与后台编排结果 + */ +export async function replaceWorkspaceShippingTaskNotice(taskNo: string, file: File) { + const form = new FormData(); + form.append('file', file); + const headers = getAuthHeaders(); + delete (headers as Record)['Content-Type']; + const res = await fetch( + `/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/replace-notice`, + { method: 'POST', headers, body: form }, + ); + const body = (await res.json().catch(() => ({}))) as ShippingNoticeUploadResponse & { error?: string }; + if (!res.ok || body.status === 'failed') { + throw new Error(body.error || body.message || res.statusText); + } + return body; +} + /** * 批量上传多份发货通知并创建批次。 * @param files - 发货通知附件列表 diff --git a/frontend/src/features/chat/components/ChatInputBar.vue b/frontend/src/features/chat/components/ChatInputBar.vue index 60d50579..5fabde40 100644 --- a/frontend/src/features/chat/components/ChatInputBar.vue +++ b/frontend/src/features/chat/components/ChatInputBar.vue @@ -44,6 +44,7 @@ const props = defineProps<{ shippingFocusReason?: string; /** 用对象包裹 Ref,避免 template 自动解包 */ shippingPickerRefHolder: { pickerRef: Ref }; + shippingNoticePickerRefHolder: { pickerRef: Ref }; getKbLabel: (kb: string) => string; }>(); @@ -121,6 +122,15 @@ const bindShippingPickerRef = (el: unknown) => { props.shippingPickerRefHolder.pickerRef.value = (el as HTMLInputElement | null) ?? null; }; +const bindShippingNoticePickerRef = (el: unknown) => { + props.shippingNoticePickerRefHolder.pickerRef.value = (el as HTMLInputElement | null) ?? null; +}; + +const bindAttachmentPickerRef = (el: unknown) => { + filePickerRef.value = (el as HTMLInputElement | null) ?? null; + bindShippingNoticePickerRef(el); +}; + const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => { const target = event.target as Node | null; if (!target) return; @@ -185,7 +195,7 @@ onBeforeUnmount(() => { /> (null); + const shippingNoticePickerRef = ref(null); const pendingShippingUploadTaskId = ref(''); const pendingShippingInventoryFile = ref(null); const shippingInventorySelectionActive = ref(false); @@ -609,6 +610,10 @@ export function useChatShipping(options: UseChatShippingOptions) { sendShippingMenuMessage, openShippingInventoryMappingFormForTask, openShippingInventoryPicker, + openShippingNoticePicker: () => { + shippingNoticePickerRef.value?.click(); + return true; + }, executeShippingDecision, executeShippingManualUpload, refreshShippingActions, @@ -855,6 +860,7 @@ export function useChatShipping(options: UseChatShippingOptions) { prepareMarkdownDisplayText, shippingAutoFlowRequested, shippingInventoryPickerRef, + shippingNoticePickerRef, pendingShippingUploadTaskId, shippingInventorySelectionActive, shippingInventorySelectionTaskId, diff --git a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts index 3f55a8d3..6c353694 100644 --- a/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts +++ b/frontend/src/features/chat/shipping/useChatShippingMenuHandler.ts @@ -26,6 +26,7 @@ export interface ShippingMenuHandlerContext { sendShippingMenuMessage: (message: string) => Promise; openShippingInventoryMappingFormForTask: (taskId: string) => Promise; openShippingInventoryPicker: () => boolean; + openShippingNoticePicker: () => boolean; executeShippingDecision: (decision: string, displayText?: string) => Promise; executeShippingManualUpload: (taskId: string, displayText?: string) => Promise; refreshShippingActions: () => Promise; @@ -175,6 +176,10 @@ export function createShippingMenuHandlers(ctx: ShippingMenuHandlerContext) { ctx.openShippingInventoryPicker(); return; } + if (action.id === 'replace_notice_file') { + ctx.openShippingNoticePicker(); + return; + } if (action.id === 'match_inventory') { if (chatMsg?.shipping_actions_used) return; if (chatMsg) chatMsg.shipping_actions_used = true; diff --git a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts index 83c24fb2..f510dee2 100644 --- a/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts +++ b/frontend/src/features/chat/shipping/useChatShippingUploadHandler.ts @@ -8,6 +8,7 @@ import { computed } from 'vue'; import { createWorkspaceShippingBatchFromNotices, createWorkspaceShippingTask, + replaceWorkspaceShippingTaskNotice, uploadWorkspaceShippingInventory, type ShippingTaskSummary, } from '@/features/chat/api/shipping.api'; @@ -133,6 +134,26 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) } }; + const handleReplaceNoticeForCurrentTask = async (taskId: string, file: File) => { + const result = await replaceWorkspaceShippingTaskNotice(taskId, file); + syncBatchContextFromNoticeResponse(result as unknown as Record); + ctx.resolvedShippingTaskId.value = taskId; + const hint = String(result.message || '').trim(); + const status = String((result as { status?: string }).status || '').trim(); + const orchestratorStarted = Boolean( + (result.data as { orchestrator_started?: boolean } | undefined)?.orchestrator_started, + ); + await ctx.pushShippingLocalAssistantMessage( + [ + hint || `已重新上传发货通知并覆盖当前任务 ${taskId}`, + `任务编号:${taskId}`, + orchestratorStarted ? '后台已开始重新解析当前任务,请稍后查看进度自动刷新。' : '', + status === 'needs_human' ? '请根据提示重新上传清晰文件,或粘贴通知正文。' : '', + ].filter(Boolean).join('\n'), + ); + void ctx.refreshShippingActions(); + }; + const handleShippingAutoUploadFile = async (file: File) => { const kind = classifyShippingUploadFile(file, extractExt); if (kind === 'inventory') { @@ -152,6 +173,11 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) await uploadInventoryForTask(taskId, file); return; } + const activeTaskId = String(ctx.getActiveShippingTaskId() || '').trim().toUpperCase(); + if (activeTaskId) { + await handleReplaceNoticeForCurrentTask(activeTaskId, file); + return; + } const result = await createWorkspaceShippingBatchFromNotices( [file], String(ctx.conversationId.value || '').trim() || undefined, @@ -188,6 +214,12 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext) const handleShippingAutoUploadNoticeBatch = async (files: File[]) => { const noticeFiles = files.filter(Boolean); if (!noticeFiles.length) return; + const activeTaskId = String(ctx.getActiveShippingTaskId() || '').trim().toUpperCase(); + const singleNoticeFile = noticeFiles[0]; + if (noticeFiles.length === 1 && activeTaskId && singleNoticeFile) { + await handleReplaceNoticeForCurrentTask(activeTaskId, singleNoticeFile); + return; + } const result = await createWorkspaceShippingBatchFromNotices( noticeFiles, String(ctx.conversationId.value || '').trim() || undefined,