feat(shipping-freight-auto-upload): 新增货代发货Excel连接级自动上传全链路功能

为提升货代上传的自动化程度,减少人工操作,本提交实现完整的连接级自动上传功能,包含以下变更:
- 新增数据库迁移与ShippingRpaProfile模型字段,存储连接级上传配置
- 完善RPA自动上传触发、回调与状态管理逻辑,支持三态结果与人工兜底
- 优化聊天界面任务卡片加载与按钮渲染,修复无文案幽灵按钮问题
This commit is contained in:
hugo committed 2026-08-27 12:44:12 +08:00
1 parent 06c18b3c7c
commit 434c04ed2d
30 files changed
+1574 -185

No files matched your search

@@ -67,6 +67,12 @@ class ShippingRpaProfile(Base):
login_config_json: Mapped[dict[str, Any]] = mapped_column(
JSON, default=lambda: {'auth_mode': 'password'}, nullable=False,
)
# 连接级“发货 Excel 自动上传”配置。先使用 login_url 登录,再访问 upload_config_json.entry_url 进入上传页;
# 上传配置由管理端表单编辑,后端白名单校验后保存为受限 JSON。白名单字段仅
# enabled / entry_url / file_input_selector / submit_mode / submit_selector /
# result_mode / result_selector / success_texts / timeout_seconds。
# 一条连接只保存一份上传配置;该配置变更不递增 config_version(见 admin 服务)。
upload_config_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True)
enabled: Mapped[bool] = mapped_column(default=True, server_default=text('true'), nullable=False)
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default=text('1'), nullable=False)
credential_updated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
@@ -26,6 +26,7 @@ from app.models import (
from app.services.shipping_notice.audit_service import append_shipping_audit_event
from app.services.shipping_notice.credential_crypto import encrypt_credential
from app.services.shipping_notice.inventory_source_repository import validate_source_profile
from app.services.shipping_notice.upload_config_validation import validate_upload_config
from app.services.shipping_notice.routing_operators import ALLOWED_OPERATORS
from app.services.shipping_notice.inventory_routing_engine import ALLOWED_ACTIONS
from app.services.shipping_notice import inventory_parsing_profile
@@ -162,6 +163,7 @@ def _profile_payload(profile: ShippingRpaProfile) -> dict[str, Any]:
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'connector_type': profile.connector_type, 'login_url': profile.login_url,
'login_config_json': profile.login_config_json or {'auth_mode': 'password'}, 'enabled': bool(profile.enabled),
'upload_config_json': profile.upload_config_json,
'config_version': profile.config_version, 'username_masked': _mask(profile.username_ciphertext),
'password_configured': bool(profile.password_ciphertext), 'credential_updated_at': _iso(profile.credential_updated_at),
'created_at': _iso(profile.created_at), 'updated_at': _iso(profile.updated_at),
@@ -199,6 +201,13 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
if profile_id and profile is None:
raise NotFoundError('RPA Profile not found', code='SHIPPING.RPA_PROFILE_NOT_FOUND')
profile = profile or ShippingRpaProfile(profile_code='', display_name='', connector_type='', login_url='', login_config_json={})
# 记录“非 upload_config”的既有运行时配置快照:仅当这些字段变化才递增 config_version,
# upload_config_json 属于连接上传配置,变更不得误判库存 RPA 配置测试过期。
prev_non_upload = (
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
) if profile_id else None
profile.profile_code = str(_text(data, 'profile_code', required=True)).upper()
profile.display_name = str(_text(data, 'display_name', required=True))
profile.connector_type = str(_text(data, 'connector_type', required=True)).lower()
@@ -218,9 +227,18 @@ def save_profile(data: dict[str, Any], *, actor_id: int | None, profile_id: int
profile.password_ciphertext = encrypt_credential(password)
if username is not None or password is not None:
profile.credential_updated_at = datetime.utcnow()
# 连接级受控上传配置(受限 JSON);与库存 RPA 运行期配置隔离,不参与 config_version。
if 'upload_config_json' in data:
profile.upload_config_json = validate_upload_config(profile.connector_type, data.get('upload_config_json'))
profile.updated_by = actor_id
if profile_id:
profile.config_version += 1
now_non_upload = (
profile.profile_code, profile.display_name, profile.connector_type, profile.login_url,
dict(profile.login_config_json or {'auth_mode': 'password'}), bool(profile.enabled),
bool(profile.username_ciphertext), bool(profile.password_ciphertext),
)
if now_non_upload != prev_non_upload:
profile.config_version += 1
if not profile_id:
profile.created_by = actor_id
db.session.add(profile)
@@ -64,6 +64,9 @@ from app.services.shipping_notice.rpa_attempts import (
max_rpa_upload_attempts,
upload_rpa_attempts,
)
from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source
from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source
from app.services.shipping_notice.upload_config_validation import compute_upload_config_hash
from app.services.shipping_notice.inventory_source_gate import assert_inventory_source_gate, is_inventory_source_stable
from app.services.shipping_notice.customer_identity_gate import customer_gate_tool_response
from app.services.shipping_notice.state_machine import TaskTransition, apply_task_transition
@@ -439,14 +442,49 @@ def _trigger_freight_upload_rpa(
except (ConflictError, ValidationError) as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
queue_path, trigger_path = write_upload_trigger(
# [STEP] 读取该任务已确定的系统连接及其 upload_config_json;未配置/未启用则 fail-closed 转人工。
# 连接级受控上传是“外例”,只作用于货代上传,不向库存 RPA 或收料 RPA 扩散。
rpa_source = task_rpa_inventory_source(task) or {}
connector_type = str(rpa_source.get('connector_type') or '').strip().lower()
source_code = str(rpa_source.get('source_code') or '').strip().upper()
# 通过 get_rpa_trigger_inventory_source 取带登录凭据与上传配置的连接快照(供 Worker 登录后访问上传页)。
upload_source = get_rpa_trigger_inventory_source(source_code) if source_code else None
if not isinstance(upload_source, dict):
upload_source = dict(rpa_source)
upload_config = upload_source.get('upload_config_json') if isinstance(upload_source, dict) else None
if connector_type not in {'dbs', 'crane'} or not isinstance(upload_config, dict) or not upload_config.get('enabled'):
task.error_message = (
'该连接未启用“发货 Excel 自动上传”,请管理员先在“系统连接”完成上传配置并启用后再触发,'
'或人工下载 Excel 后上传并登记凭据。'
)
log_task_event(task, 'upload_rpa_config_missing', {'connector_type': connector_type or None})
db.session.commit()
return tool_response(
status='needs_human',
task=task,
message=task.error_message,
data=serialize_task_for_tool(task),
stop_agent_turn=True,
next_required_action='请在“系统连接”补齐上传配置并启用,或人工上传。',
)
callback_id = f'upload:{task.task_no}:attempt:{int(attempt.id)}'
queue_path, trigger_path, callback_id = write_upload_trigger(
task.task_no,
str(task.export_file_path),
payload={
'attempt_id': int(attempt.id),
'artifact_id': int(attempt.artifact_id),
'mode': str(body.get('mode') or 'auto'),
},
attempt_id=int(attempt.id),
artifact_id=int(attempt.artifact_id),
connector_type=connector_type,
upload_config=dict(upload_config),
upload_config_hash=compute_upload_config_hash(upload_config),
login_url=str(upload_source.get('login_url') or '').strip() or None,
credential_envelope=upload_source.get('credential_envelope'),
callback_id=callback_id,
business_no=task.business_no,
)
if not trigger_path:
attempt.status = 'failed'
@@ -2160,6 +2198,14 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
success = _rpa_callback_success(payload.get("success"))
except ValidationError as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
# 三态结果:success / failed / unknown。result 显式给定则优先,否则由 success 布尔推导。
raw_result = str(payload.get('result') or '').strip().lower()
if raw_result in {'success', 'failed', 'unknown'}:
result_status = raw_result
else:
result_status = 'success' if success else 'failed'
# 成功证据只在 success 时才要求;unknown/failed 不索取页面证据。
success = result_status == 'success'
success_evidence: dict[str, Any] | None = None
if success:
expected_filename = (
@@ -2187,6 +2233,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
completed = complete_attempt(
attempt, success=success, callback_id=str(payload.get('callback_id') or f'rpa:{attempt.id}'),
freight_ref_no=str(payload.get('freight_ref_no') or ''), error_message=str(payload.get('error_message') or ''),
result=result_status,
)
except (ConflictError, ValidationError) as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
@@ -2252,6 +2299,28 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
checkpoint=CP_UPLOADED if str(getattr(task, 'upload_status', None) or '').strip().lower() == 'uploaded' else None,
)
if completed.status == 'unknown':
# unknown 已可能提交但无法确认外部系统结果:保持待人工,禁止自动重试,避免重复上传。
task.upload_finished_at = datetime.utcnow()
set_task_step_progress(
task,
step_key="step7_upload_freight",
step_title="上传货代",
status="needs_human",
message=t("workflow.fulfillment.upload_unknown_wait_manual", lang=lang),
progress_percent=100,
detail=t("workflow.fulfillment.upload_unknown_detail", lang=lang),
)
task.error_message = completed.error_message or 'RPA upload result unknown'
log_task_event(task, "upload_rpa_unknown", {"artifact_id": completed.artifact_id, "attempt_id": completed.id, "error": task.error_message})
db.session.commit()
return tool_response(
status="needs_human",
task=task,
message=task.error_message,
data=serialize_task_for_tool(task),
)
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
task.upload_finished_at = datetime.utcnow()
set_task_step_progress(
@@ -137,6 +137,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.rpa_uploaded_done": "RPA 已成功上传货代系统,任务已全部处理完毕。",
"workflow.fulfillment.upload_failed_wait_manual": "货代上传失败,等待人工处理",
"workflow.fulfillment.upload_failed_detail": "可重试上传或改为手工上传",
"workflow.fulfillment.upload_unknown_wait_manual": "货代上传结果未知,必须人工核验后再处理",
"workflow.fulfillment.upload_unknown_detail": "文件可能已提交但未能从页面确认结果;为避免重复上传,请人工核验货代系统后处理。",
},
"en": {
"parse.title": "[Shipping notice parsed] Task: {task_no}",
@@ -260,6 +262,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.rpa_uploaded_done": "RPA uploaded to the freight system successfully. The task is fully completed.",
"workflow.fulfillment.upload_failed_wait_manual": "Freight upload failed. Waiting for manual handling.",
"workflow.fulfillment.upload_failed_detail": "You may retry the upload or switch to manual upload.",
"workflow.fulfillment.upload_unknown_wait_manual": "Freight upload result is unknown. Manual verification is required.",
"workflow.fulfillment.upload_unknown_detail": "The file may have been submitted but the result could not be confirmed from the page. To avoid a duplicate upload, please verify the freight system manually.",
},
"th": {
"parse.title": "【ยืนยันการแยกใบแจ้งส่งสินค้า】งาน: {task_no}",
@@ -383,6 +387,8 @@ _MESSAGES: dict[str, dict[str, str]] = {
"workflow.fulfillment.rpa_uploaded_done": "RPA อัปโหลดเข้าระบบขนส่งสำเร็จแล้ว และงานเสร็จสมบูรณ์",
"workflow.fulfillment.upload_failed_wait_manual": "อัปโหลดเข้าระบบขนส่งล้มเหลว กำลังรอให้คนจัดการต่อ",
"workflow.fulfillment.upload_failed_detail": "สามารถลองอัปโหลดใหม่หรือเปลี่ยนเป็นอัปโหลดด้วยตนเองได้",
"workflow.fulfillment.upload_unknown_wait_manual": "ผลการอัปโหลดขนส่งไม่ทราบแน่ชัด ต้องให้คนตรวจสอบก่อนดำเนินการ",
"workflow.fulfillment.upload_unknown_detail": "ไฟล์อาจถูกส่งไปแล้วแต่ไม่สามารถยืนยันผลจากหน้าเว็บได้ เพื่อหลีกเลี่ยงการอัปโหลดซ้ำ กรุณาตรวจสอบระบบขนส่งด้วยตนเอง",
},
}
@@ -75,6 +75,9 @@ def get_database_inventory_source(source_code: str, *, enabled_only: bool = True
'report_path_json': dict(source.report_path_json or {}),
'query_parameters_json': list(source.query_parameters_json or []),
'rpa_profile_code': profile.profile_code,
# 连接级受控上传配置(受限 JSON):Worker 用 login_url 登录后访问 upload_config.entry_url 上传页,
# 平台差异(文件选择、提交与结果判定)由 Worker 受控 Adapter 固化。
'upload_config_json': profile.upload_config_json,
# 与既有 worker 契约的适配层:不再从 Profile 取报表路径或查询参数。
'navigation': source_navigation,
'parameters': list(source.query_parameters_json or []),
@@ -1150,6 +1150,12 @@ def list_freight_notice_groups_for_task(
'business_no': business_no,
'po_number': po_number,
'upload_status': notice.upload_status,
'upload_mode': notice.upload_mode,
'upload_attempt': notice.upload_attempt,
'upload_error_code': notice.upload_error_code,
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
'upload_error_message': (notice.upload_error_message or notice.error_message or '')[:500] or None,
'pending_human_reason': notice.pending_human_reason,
'export_file_name': notice.export_file_name,
'available_actions': available_actions,
'lines': _notice_line_summary_for_task(notice),
+59 -8
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import json
import os
import shutil
import uuid
from datetime import datetime
from pathlib import Path
from typing import Any
@@ -259,36 +260,86 @@ def write_inventory_export_trigger_for_task(
)
def write_upload_trigger(task_no: str, export_file_path: str, payload: dict[str, Any] | None = None) -> tuple[str | None, str | None]:
def write_upload_trigger(
task_no: str,
export_file_path: str,
payload: dict[str, Any] | None = None,
*,
attempt_id: int | None = None,
artifact_id: int | None = None,
connector_type: str | None = None,
upload_config: dict[str, Any] | None = None,
upload_config_hash: str | None = None,
login_url: str | None = None,
credential_envelope: dict[str, Any] | None = None,
callback_id: str | None = None,
business_no: str | None = None,
) -> tuple[str | None, str | None, str | None]:
"""
复制 Excel 至上传队列并写入 RPA 上传触发 JSON。
复制发货 Excel 至共享上传队列,并以原子发布方式写入 RPA 上传触发 JSON。
【AI 触发时机】:upload_to_freight(mode=auto|retry_upload) 触发货代上传时调用。
触发文件固化本次上传契约快照,Worker 据此进入 DSV/Crane 受控流程:
schema_version / task_no / attempt_id / artifact_id / callback_id(非空)/
connector_type / upload_config(本次快照 + upload_config_hash)/ login_url / credential_envelope / file_path。
平台差异(文件选择器、提交与结果判定)由 Worker 的受控 Adapter 按 upload_config 执行。
写入复用“临时文件 + fsync + os.replace”原子方式,避免 Worker 读取半写 JSON。
Args:
task_no: 发货任务号。
export_file_path: 待上传发货 Excel 的服务端路径。
payload: 附加字段(如 mode),与下列具名参数合并。
attempt_id: 本次 Upload Attempt 主键。
artifact_id: 当前上传目标 Artifact 主键。
connector_type: 业务连接类型(dbs / crane)。
upload_config: 本次上传使用的连接级受控配置快照(enabled/entry_url/selector 等)。
upload_config_hash: 该快照的 sha256,用于审计关联。
login_url: 该连接登录地址(先登录,再访问 upload_config.entry_url 进入上传页)。
credential_envelope: 连接凭据密文信封(Worker 据此登录)。
callback_id: 回调幂等 ID;为空时自动生成,保证非空。
business_no: 发货通知对外业务编号(业务单号),用于精简上传文件名;为空时回退 task_no。
Returns:
tuple[str | None, str | None]: (queue 文件路径, trigger 文件路径);失败时 (None, None)。
tuple[str | None, str | None, str | None]: (queue 文件路径, trigger 文件路径, callback_id);
失败时 (None, None, None)。
"""
queue = upload_queue_dir()
trigger_dir = upload_trigger_dir()
if not queue or not trigger_dir:
return None, None
return None, None, None
queue.mkdir(parents=True, exist_ok=True)
trigger_dir.mkdir(parents=True, exist_ok=True)
src = Path(export_file_path)
if not src.is_file():
return None, None
dest = queue / f"{task_no}_{src.name}"
return None, None, None
# [STEP] 精简上传文件名:仅用业务编号(业务单号),避免 task_no 与导出文件名重复拼接过长;
# 业务编号为空时回退到内部任务号,扩展名沿用源文件(无扩展名时按 xlsx 兜底)。
emit_no = str(business_no or '').strip() or task_no
suffix = str(src.suffix or '.xlsx').lower()
dest = queue / f"{emit_no}{suffix}"
shutil.copy2(src, dest)
resolved_callback_id = str(callback_id or '').strip() or f'upload:{task_no}:{uuid.uuid4().hex[:12]}'
body = {
"action": "shipment_upload",
"schema_version": "shipping_notice_upload_rpa.v1",
"task_no": task_no,
"attempt_id": attempt_id,
"artifact_id": artifact_id,
"callback_id": resolved_callback_id,
"connector_type": str(connector_type or '').strip() or None,
"upload_config": upload_config,
"upload_config_hash": upload_config_hash,
"login_url": login_url,
"credential_envelope": credential_envelope,
"file_path": str(dest),
"requested_at": datetime.utcnow().isoformat(),
**(payload or {}),
}
trigger_path = trigger_dir / f"upload_{task_no}.json"
trigger_path.write_text(json.dumps(body, ensure_ascii=False, indent=2), encoding="utf-8")
return str(dest), str(trigger_path)
_write_trigger_json_atomic(trigger_path, body)
return str(dest), str(trigger_path), resolved_callback_id
def find_latest_inventory_file() -> Path | None:
@@ -112,11 +112,44 @@ def has_verified_upload_success(task: ShippingNotice) -> bool:
).first() is not None
def _normalize_callback_result(result: str | None, success: bool) -> str:
"""将回调结果归一化为三态 success / failed / unknown。
result 显式给定则按其校验;否则由 success 布尔推导(success→success,其余→failed)。
"""
if result is not None:
normalized = str(result or '').strip().lower()
if normalized not in {'success', 'failed', 'unknown'}:
raise ValidationError(
'result must be success, failed or unknown',
code='SHIPPING.UPLOAD_RESULT_INVALID',
)
return normalized
return 'success' if success else 'failed'
def complete_attempt(
attempt: ShippingUploadAttempt, *, success: bool, callback_id: str,
freight_ref_no: str | None = None, error_message: str | None = None,
result: str | None = None,
) -> ShippingUploadAttempt:
"""幂等落库 RPA 回调;失败或过期 Attempt 绝不能覆盖已经成功的 Artifact。"""
"""幂等落库 RPA 回调;失败或过期 Attempt 绝不能覆盖已经成功的 Artifact。
Args:
attempt: 本次上传尝试。
success: 兼容布尔标记;schema 迁移期仍保留,由 result 优先。
callback_id: 回调幂等键(唯一)。
freight_ref_no: 成功时货代回执号。
error_message: 失败/未知时的脱敏错误信息。
result: 三态结果 success / failed / unknown;三态与布尔推导见 _normalize_callback_result。
Returns:
ShippingUploadAttempt: 已更新状态的 Attob。
Raises:
ConflictError: 回调身份冲突、过期回调或不可接受的 Attempt 状态。
ValidationError: 缺 callback_id / artifact / 非法 result。
"""
callback = str(callback_id or '').strip()
if not callback:
raise ValidationError('callback_id is required', code='SHIPPING.UPLOAD_CALLBACK_REQUIRED')
@@ -134,10 +167,11 @@ def complete_attempt(
raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE')
if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}:
raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE')
result_status = _normalize_callback_result(result, success)
attempt.callback_id = callback
attempt.finished_at = datetime.utcnow()
task = db.session.get(ShippingNotice, artifact.task_id)
if success:
if result_status == 'success':
attempt.status = 'succeeded'
attempt.freight_ref_no = str(freight_ref_no or '').strip() or None
artifact.status = 'uploaded'
@@ -153,9 +187,20 @@ def complete_attempt(
else:
# A missing callback may conceal a completed freight submission. A late
# transport error is not enough to safely release or retry that Artifact.
if attempt.status in {'timed_out', 'unknown'} and not str(error_message or '').strip().lower().startswith('freight_rejected:'):
# unknown 结果既不允许自动重试,也不强制改 upload_status(迟到的成功回调可解除)。
already_unknown_before = attempt.status in {'timed_out', 'unknown'}
if result_status == 'unknown' or (
already_unknown_before
and not str(error_message or '').strip().lower().startswith('freight_rejected:')
):
attempt.status = 'unknown'
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
attempt.error_message = str(error_message or 'Upload result remains unknown')[:500]
# 逐单状态展示:未知结果仍须在 Notice 上保留失败原因(不强制改 upload_status,
# 因为迟到的成功回调仍可解除该未知态)。
if task is not None:
task.upload_error_code = attempt.error_code
task.upload_error_message = attempt.error_message
db.session.flush()
return attempt
attempt.status = 'failed'
@@ -165,6 +210,9 @@ def complete_attempt(
artifact.status = 'ready'
if task is not None:
task.upload_status = 'failed'
# 逐单状态展示:把失败原因落到 Notice,供「按发货通知单展示状态」读取。
task.upload_error_code = attempt.error_code
task.upload_error_message = message
db.session.flush()
return attempt
@@ -0,0 +1,212 @@
"""
services/shipping_notice/upload_config_validation.py
用途:对连接级“发货 Excel 自动上传”配置做后端严格白名单校验,产出受限 JSON。
依赖:app.core.errors.ValidationError;仅标准库,不引入第三方。
逻辑:配置由管理端表单编辑,但后端只接受本模块允许的字段、枚举与安全边界;
禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
upload_config 是“这次上传到底用了什么”的快照来源,不做版本管理(见技术文档)。
"""
from __future__ import annotations
import hashlib
import json
from typing import Any
from app.core.errors import ValidationError
# 连接类型与各平台已审核域名(主机名白名单,后缀匹配以覆盖同域子站)。
ALLOWED_CONNECTOR_TYPES = frozenset({'dbs', 'crane'})
ALLOWED_PLATFORM_DOMAINS: dict[str, tuple[str, ...]] = {
'dbs': ('dbschenker.com',),
'crane': ('craneww.com',),
}
ALLOWED_SUBMIT_MODES = frozenset({'auto_after_file', 'click_submit'})
ALLOWED_RESULT_MODES = frozenset({'page_notice', 'history_record'})
# 字段白名单:禁止把额外键(模板、Cookie、脚本)混入配置。
ALLOWED_KEYS = frozenset({
'enabled', 'entry_url', 'file_input_selector',
'submit_mode', 'submit_selector',
'result_mode', 'result_selector', 'success_texts', 'timeout_seconds',
})
MAX_ENTRY_URL_LENGTH = 500
MAX_SELECTOR_LENGTH = 200
MAX_SUCCESS_TEXTS = 10
MAX_SUCCESS_TEXT_LENGTH = 200
MIN_TIMEOUT_SECONDS = 1
MAX_TIMEOUT_SECONDS = 600
DEFAULT_TIMEOUT_SECONDS = 120
# 复用的字符黑名单:任何脚本/表达式/注入语义都拒绝。
_BLOCKED_SELECTOR_MARKERS = (
'javascript:', '<script', 'expression(', 'onclick=', 'onload=', 'onerror=',
'onmouseover=', 'onmouseout=', 'onfocus=', 'onblur=', 'onchange=', 'oninput=',
)
_BLOCKED_SELECTOR_CHARS = ('(', ')', '{', '}', ';', '<', '>', '`', '\\', '\n', '\r')
def _reject(message: str, *, field: str) -> None:
raise ValidationError(message, code='SHIPPING.UPLOAD_CONFIG_INVALID', details={'field': field})
def _normalize_text(value: Any) -> str:
return str(value or '').strip()
def _validate_entry_url(connector_type: str, value: Any, *, required: bool = True) -> str | None:
"""校验上传入口为 HTTPS 且主机名属于已审核平台域名。"""
url = _normalize_text(value)
if not url:
if required:
_reject('entry_url is required', field='entry_url')
return None
if len(url) > MAX_ENTRY_URL_LENGTH:
_reject('entry_url is too long', field='entry_url')
if not url.lower().startswith('https://'):
_reject('entry_url must be HTTPS', field='entry_url')
# 简单主机名解析:仅定位 host:port 部分,禁止 userinfo/query 进入主机判断。
scheme_rest = url[8:]
authority = scheme_rest.split('/', 1)[0].split('?', 1)[0].split('#', 1)[0]
host = authority.split('@')[-1].split(':')[0].strip().lower()
if not host:
_reject('entry_url host is invalid', field='entry_url')
allowed = ALLOWED_PLATFORM_DOMAINS.get(connector_type, ())
if not any(host == domain or host.endswith('.' + domain) for domain in allowed):
_reject(
f'entry_url host not allowed for {connector_type}',
field='entry_url',
)
return url
def _validate_css_selector(value: Any, *, field: str, required: bool) -> str | None:
"""校验普通 CSS selector:限制长度、拒绝脚本及表达式语义。"""
selector = _normalize_text(value)
if not selector:
if required:
_reject(f'{field} is required', field=field)
return None
if len(selector) > MAX_SELECTOR_LENGTH:
_reject(f'{field} is too long', field=field)
lowered = selector.lower()
for marker in _BLOCKED_SELECTOR_MARKERS:
if marker in lowered:
_reject(f'{field} contains script semantics', field=field)
for char in _BLOCKED_SELECTOR_CHARS:
if char in selector:
_reject(f'{field} contains an invalid character', field=field)
return selector
def _validate_success_texts(value: Any) -> list[str]:
if value in (None, ''):
return []
if not isinstance(value, list):
_reject('success_texts must be a list', field='success_texts')
if len(value) > MAX_SUCCESS_TEXTS:
_reject('success_texts is too long', field='success_texts')
result: list[str] = []
for item in value:
text = _normalize_text(item)
if not text or len(text) > MAX_SUCCESS_TEXT_LENGTH:
_reject('success_texts contains an invalid item', field='success_texts')
if text not in result:
result.append(text)
return result
def validate_upload_config(connector_type: str, raw: Any) -> dict[str, Any] | None:
"""白名单校验连接级上传配置,返回规范化 JSON;raw 为空/None 表示未配置(返回 None)。
Args:
connector_type: 连接类型,仅允许 dbs / crane。
raw: 管理端提交的原始上传配置对象。
Returns:
dict | None: 规范化受限 JSON;未配置时返回 None。
Raises:
ValidationError: 含未知字段/非法枚举/不安全 selector/非 HTTPS 或非法域名/
enabled=true 但缺少上传或结果判定所需字段。
"""
normalized_connector = _normalize_text(connector_type).lower()
if normalized_connector not in ALLOWED_CONNECTOR_TYPES:
_reject('connector_type must be dbs or crane', field='connector_type')
if raw in (None, ''):
return None
if not isinstance(raw, dict):
_reject('upload_config must be an object', field='upload_config_json')
unknown = set(raw) - ALLOWED_KEYS
if unknown:
_reject(f'upload_config contains unsupported fields: {sorted(unknown)}', field='upload_config_json')
enabled = raw.get('enabled') is True
config: dict[str, Any] = {
'enabled': enabled,
'entry_url': _validate_entry_url(normalized_connector, raw.get('entry_url'), required=enabled),
'file_input_selector': _validate_css_selector(
raw.get('file_input_selector'), field='file_input_selector', required=enabled,
),
'submit_mode': _normalize_text(raw.get('submit_mode')),
'submit_selector': _validate_css_selector(
raw.get('submit_selector'), field='submit_selector', required=False,
),
'result_mode': _normalize_text(raw.get('result_mode')),
'result_selector': _validate_css_selector(
raw.get('result_selector'), field='result_selector', required=False,
),
'success_texts': _validate_success_texts(raw.get('success_texts')),
'timeout_seconds': raw.get('timeout_seconds', DEFAULT_TIMEOUT_SECONDS),
}
if config['submit_mode'] not in ALLOWED_SUBMIT_MODES:
_reject('submit_mode must be auto_after_file or click_submit', field='submit_mode')
if config['result_mode'] not in ALLOWED_RESULT_MODES:
_reject('result_mode must be page_notice or history_record', field='result_mode')
if config['submit_mode'] == 'auto_after_file':
# auto_after_file 由页面在选文件后自动提交,不应同时配置提交按钮选择器。
config['submit_selector'] = None
try:
timeout = int(config['timeout_seconds'])
except (TypeError, ValueError):
_reject('timeout_seconds must be an integer', field='timeout_seconds')
if timeout < MIN_TIMEOUT_SECONDS or timeout > MAX_TIMEOUT_SECONDS:
_reject(
f'timeout_seconds must be within [{MIN_TIMEOUT_SECONDS}, {MAX_TIMEOUT_SECONDS}]',
field='timeout_seconds',
)
config['timeout_seconds'] = timeout
if enabled:
# 完成一次上传所需的公共字段由上述必填校验覆盖;此处补齐连接差异。
if not config['file_input_selector']:
_reject('enabled upload requires file_input_selector', field='file_input_selector')
if config['submit_mode'] == 'click_submit' and not config['submit_selector']:
_reject('enabled click_submit upload requires submit_selector', field='submit_selector')
# 结果判定:dbs(DSV) 使用代码内置的受控成功流(History 绿状态/页面证据),
# 不强制 admin 填写结果字段;crane 必须由 admin 补全提交/结果判定字段后才可启用。
if normalized_connector == 'crane':
if config['result_mode'] == 'page_notice':
if not config['result_selector'] or not config['success_texts']:
_reject(
'enabled crane page_notice upload requires result_selector and success_texts',
field='result_selector',
)
elif config['result_mode'] == 'history_record' and not config['result_selector']:
_reject('enabled crane history_record upload requires result_selector', field='result_selector')
# 未启用时仍保存规范化的受限 JSON,方便 admin 预填后续补全。
return config
def compute_upload_config_hash(config: dict[str, Any] | None) -> str | None:
"""对规范化上传配置计算稳定 sha256;供审计关联每次上传所用的确切快照。"""
if not config:
return None
payload = json.dumps(config, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
return hashlib.sha256(payload.encode('ascii')).hexdigest()
@@ -0,0 +1,33 @@
"""为连接级发货 Excel 自动上传增加 upload_config_json。
用途:货代发货 Excel 自动上传配置保存在 ShippingRpaProfile.upload_config_json,
一条连接只保存一份受限配置(enabled / entry_url / file_input_selector / submit_mode /
submit_selector / result_mode / result_selector / success_texts / timeout_seconds)。
依赖:shipping_rpa_profiles。
逻辑:新增可空 JSON 列;既有连接默认 NULL(未配置上传)。不新增 Upload Profile / 关联表 / 版本表,
upload_config 变更不递增 config_version。流程为“login_url 登录 → 访问 upload_config.entry_url 上传页”。
"""
from __future__ import annotations
from alembic import op
import sqlalchemy as sa
revision = 'hs1t2u3v4w5x'
down_revision = 'hq0r1s2t3u4v'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""在 shipping_rpa_profiles 增加可空的 upload_config_json 列。"""
op.add_column(
'shipping_rpa_profiles',
sa.Column('upload_config_json', sa.JSON(), nullable=True),
)
def downgrade() -> None:
"""回滚:删除 upload_config_json 列。"""
op.drop_column('shipping_rpa_profiles', 'upload_config_json')
@@ -560,3 +560,38 @@ def test_external_mapping_normalizes_freight_warehouse_identity(app):
'external_warehouse_name': 'Dublin', 'enabled': True,
}, actor_id=None)
assert mapping['freight_warehouse_id'] == 'DUB'
def test_upload_config_change_does_not_bump_rpa_profile_version(app):
"""连接级上传配置(upload_config_json)变更不递增 config_version。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
base_version = profile['config_version']
upload_cfg = {
'enabled': True, 'entry_url': 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2',
'file_input_selector': 'input#file2', 'submit_mode': 'auto_after_file', 'submit_selector': None,
'result_mode': 'page_notice', 'result_selector': None, 'success_texts': [], 'timeout_seconds': 120,
}
updated = shipping_inventory_service.save_profile(
{**_profile_data(), 'upload_config_json': upload_cfg}, actor_id=None, profile_id=profile['id'],
)
assert updated['config_version'] == base_version
assert updated['upload_config_json']['enabled'] is True
# 仅修改运行期连接配置(login_url)仍应递增 config_version。
bumped = shipping_inventory_service.save_profile(
{**_profile_data(), 'login_url': 'https://example.invalid/login-v2'},
actor_id=None, profile_id=profile['id'],
)
assert bumped['config_version'] == base_version + 1
# 非法上传配置(HTTP / 非法主机 / 脚本 selector)应拒绝。
with pytest.raises(ValidationError):
shipping_inventory_service.save_profile(
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'http://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
actor_id=None, profile_id=profile['id'],
)
with pytest.raises(ValidationError):
shipping_inventory_service.save_profile(
{**_profile_data(), 'upload_config_json': {'enabled': True, 'entry_url': 'https://evil.example/x', 'file_input_selector': '#f', 'submit_mode': 'auto_after_file', 'result_mode': 'page_notice', 'timeout_seconds': 120}},
actor_id=None, profile_id=profile['id'],
)
+61 -51
View File
@@ -921,29 +921,24 @@ def test_summarize_inventory_batch_results_empty():
}
def test_real_upload_requires_explicit_enablement(monkeypatch, tmp_path):
"""未显式开启上传浏览器自动化时,不得打开货代页面或提交文件。"""
def test_real_upload_requires_connection_config_enabled(monkeypatch, tmp_path):
"""未启用连接级上传配置时,不得打开货代页面或提交文件(fail-closed)。"""
worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "false")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
with pytest.raises(RuntimeError, match="upload RPA is disabled"):
worker._upload_shipment_with_browser(workbook)
with pytest.raises(RuntimeError, match="not enabled for this connection"):
worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={"upload_config_json": {"enabled": False}})
def test_real_upload_requires_success_evidence_and_returns_receipt(monkeypatch, tmp_path):
"""真实上传只能在页面成功标识可见后回传可选货代回执。"""
def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path):
"""DSV 上传须复用登录态打开入口、设置文件,并以 History 绿色回执作为证据返回。"""
worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL", "https://freight.example/upload")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR", "#file")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR", "#submit")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR", "#success")
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_RECEIPT_SELECTOR", "#receipt")
events: list[tuple[str, object]] = []
class _Locator:
@@ -951,23 +946,17 @@ def test_real_upload_requires_success_evidence_and_returns_receipt(monkeypatch,
self.selector = selector
self.first = self
def wait_for(self, **_kwargs) -> None:
events.append(("wait", self.selector))
def click(self, **_kwargs) -> None:
events.append(("click", self.selector))
def set_input_files(self, value: str, **_kwargs) -> None:
events.append(("file", value))
def click(self, **_kwargs) -> None:
events.append(("submit", self.selector))
def wait_for(self, **_kwargs) -> None:
events.append(("success", self.selector))
def text_content(self, **_kwargs) -> str:
return "FREIGHT-REF-001"
def evaluate(self, _script: str) -> str:
return '<div id="success">ok</div>'
class _Page:
url = "https://freight.example/upload"
url = "https://s360.dbschenker.com/main/portal/frame/WMSUpload2"
def goto(self, url: str, **_kwargs) -> None:
events.append(("goto", url))
@@ -975,11 +964,14 @@ def test_real_upload_requires_success_evidence_and_returns_receipt(monkeypatch,
def locator(self, selector: str) -> _Locator:
return _Locator(selector)
def get_by_text(self, text: str, **_kwargs) -> _Locator:
return _Locator(text)
def content(self) -> str:
return "<html><body><div id='success'>ok</div></body></html>"
return "<html><body>history</body></html>"
def screenshot(self, **_kwargs) -> bytes:
return b"PNG-BYTES"
return b"PNG"
class _Context:
def close(self) -> None:
@@ -991,29 +983,33 @@ def test_real_upload_requires_success_evidence_and_returns_receipt(monkeypatch,
runtime_profile = tmp_path / "profile"
runtime_profile.mkdir()
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
result = worker._upload_shipment_with_browser(workbook)
def fake_history(_page, filename):
return {"reference": "FREIGHT-REF-001", "success_evidence": {"kind": "dsv_history_green_dom", "selector": "em.fa.fa-circle.success-color.status-icon", "filename": filename, "reference": "FREIGHT-REF-001", "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "<em/>", "dom_sha256": "abc"}}
monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", fake_history)
result = worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={
"connector_type": "dbs",
"login_url": "https://s360.dbschenker.com/",
"credential_envelope": {},
"upload_config_json": {
"enabled": True, "entry_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2",
"file_input_selector": "input#file2", "submit_mode": "auto_after_file", "submit_selector": None,
"result_mode": "page_notice", "result_selector": None, "success_texts": [], "timeout_seconds": 120,
},
})
assert result['reference'] == 'FREIGHT-REF-001'
evidence = result['success_evidence']
assert evidence['kind'] == 'configured_success_selector'
assert evidence['selector'] == '#success'
assert evidence['filename'] == workbook.name
assert evidence['reference'] == 'FREIGHT-REF-001'
assert evidence['observed_at']
assert evidence['page_url']
assert evidence['dom_snippet']
assert evidence['dom_sha256']
assert events[:4] == [
("goto", "https://freight.example/upload"),
("file", str(workbook)),
("submit", "#submit"),
("success", "#success"),
]
assert result['success_evidence']['kind'] == 'dsv_history_green_dom'
assert events[0] == ("session", "https://s360.dbschenker.com/")
assert ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2") in events
assert ("file", str(workbook)) in events
def test_dsv_upload_navigates_from_my_applications_before_setting_file(monkeypatch, tmp_path):
"""DSV 上传必须复用登录态,并优先使用截图确认的 My Applications 入口。"""
def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
"""DSV 上传先登录(login_url),再直接访问 upload_entry_url,无需维护菜单导航。"""
worker = _load_freight_rpa_worker()
workbook = tmp_path / "shipment.xlsx"
workbook.write_bytes(b"test")
@@ -1036,6 +1032,9 @@ def test_dsv_upload_navigates_from_my_applications_before_setting_file(monkeypat
events.append(("file", self.selector))
class _Page:
def goto(self, url: str, **_kwargs) -> None:
events.append(("goto", url))
def locator(self, selector: str) -> _Locator:
return _Locator(selector)
@@ -1057,11 +1056,22 @@ def test_dsv_upload_navigates_from_my_applications_before_setting_file(monkeypat
monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", lambda _page, filename: f"REF-{filename}")
assert worker._upload_shipment_with_browser(
workbook, connector_type="dbs", dsv_entry_url="https://dsv.example/portal"
workbook, connector_type="dbs", upload_source={
"connector_type": "dbs",
"login_url": "https://s360.dbschenker.com/",
"credential_envelope": {},
"upload_config_json": {
"enabled": True, "entry_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2",
"file_input_selector": "#file2", "submit_mode": "click_submit",
"submit_selector": 'button.upload-button:has-text("Process File")',
"result_mode": "history_record", "result_selector": "em.fa.fa-circle.success-color.status-icon",
"success_texts": [], "timeout_seconds": 120,
},
}
) == "REF-shipment.xlsx"
assert events[0] == ("session", "https://dsv.example/portal")
assert any(event == ("click", ":has-text(\"My Applications\") a:has-text('Upload Tool')") for event in events)
assert events[0] == ("session", "https://s360.dbschenker.com/")
assert events[1] == ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2")
assert ("file", "#file2") in events
assert ("click", 'button.upload-button:has-text("Process File")') in events
@@ -1189,14 +1199,14 @@ def test_real_upload_failure_reports_failed_callback(monkeypatch, tmp_path):
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
monkeypatch.setattr(worker, "_upload_shipment_with_browser", lambda _path: (_ for _ in ()).throw(RuntimeError("success marker missing")))
monkeypatch.setattr(worker, "_upload_shipment_with_browser", lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("success marker missing")))
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed")
assert callbacks == [("/api/shipping-notice/rpa/upload-complete", {
"task_no": "SN-UPLOAD-FAIL", "attempt_id": 8, "callback_id": "rpa:8", "success": False,
"error_message": "success marker missing",
"task_no": "SN-UPLOAD-FAIL", "attempt_id": 8, "callback_id": "rpa:8",
"result": "failed", "success": False, "error_message": "success marker missing",
})]
assert (trigger_dir / "processed" / trigger_path.name).is_file()
@@ -378,6 +378,34 @@ def test_freight_notice_groups_split_same_po_by_business_no_and_owner(app):
assert result['items'][1]['lines'][0]['part_number'] == 'PART-B'
def test_freight_notice_groups_exposes_per_notice_upload_error(app):
"""货代上传聚合必须逐单透出上传错误码/原因/需人工原因,供「按通知单展示状态」消费。"""
with app.app_context():
from app import db
from app.models import ShippingNotice
from app.services.shipping_notice import query_service
first = ShippingNotice(task_no='SN-GROUP-ERR-1', business_no='WYC26082401', source_type='manual', user_id=11)
db.session.add(first); db.session.flush()
first.upload_status = 'failed'
first.upload_error_code = 'RPA_UPLOAD_FAILED'
first.upload_error_message = '货代平台拒绝:凭证无效'
db.session.commit()
original_header_reader = query_service.current_header_field_values_or_empty
query_service.current_header_field_values_or_empty = lambda _task: {'customer_po_number': 'PO-ERR'}
try:
result = list_freight_notice_groups_for_task(first, user_id=11)
finally:
query_service.current_header_field_values_or_empty = original_header_reader
item = result['items'][0]
assert item['business_no'] == 'WYC26082401'
assert item['upload_status'] == 'failed'
assert item['upload_error_code'] == 'RPA_UPLOAD_FAILED'
assert item['upload_error_message'] == '货代平台拒绝:凭证无效'
def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projection_is_unavailable(app):
"""当前 Extraction 不可读时,货代上传聚合仍必须以冻结快照中的客户 PO 对齐同一发货批次。"""
with app.app_context():
@@ -0,0 +1,144 @@
# 货代发货通知:对话附件延迟显示 / 解析进度不细化 / 模板匹配文案矛盾 —— 根因诊断与修复方案
> 日期:2026-08-26
> 范围:货代发货通知(shipping-notice)对话页与订单生命周期工作台
> 诉求(用户反馈):
> 1. 对话发送带附件消息后,气泡附件「刚发送时不显示,等一会儿才出现」;
> 2. 解析进度展示不明晰,始终显示「生成订单候选」,缺少更细化的阶段;
> 3. 模板匹配报错前后矛盾:同时出现「未匹配」与「命中模板(模板已命中,但字段提取仍被安全门禁阻断)」。
> 状态:**方案评审稿(未实施)**。涉及新增/调整代码时按 AGENTS.md 同步更新本文档与相关 i18n/测试。
---
## 0. 结论摘要
| 问题 | 根因(按可信度排序) | 修复优先级 |
| --- | --- | --- |
| 1. 附件延迟显示 | ① 服务端把 `user_attachments` 当作「终态后懒写」字段(SSE 落库不含附件 → 终态事件才合并),ChatLog 存在「先无后有」窗口;② 货代自动流首次点击被「解析中」拦截,无任何气泡,且解析完成后不会自动触发建单(需二次点击);③ 工作台「当前附件」为按需异步加载,加载前只显示占位 | P0(前端乐观保留+后端落库即写);P1(点击即落气泡/自动续跑;intake context 快照元数据) |
| 2. 进度一直「生成订单候选」 | ① work-item 投影只有粗粒度 15 阶 `stage`(`candidate_creating` 覆盖版面解析→模板匹配→表格重建→字段提取→邮件合并全段);② 细粒度步骤文本(`chat.shippingProcessing.progress.step.*`)只存在于 Run 级 `lifecycle_progress.current_step_i18n_key`,仅工作台顶部一行横幅消费;③ 15 节点阶段条组件(`ReviewProgressStrip`/`ReviewWorkflowProgressPanel`/`UnifiedProgressTrack`/`ChatProgressSummary`/`WorkbenchProgressGrouped`)在当前 UI **无任何挂载点**;④ 前端 `resolveShippingProcessingStageLabel` 未透传后端 `stage_label_key` | P0(后端下发细粒度步骤);P1(前端展示 + 恢复阶段条挂载) |
| 3. 未匹配 vs 命中模板矛盾 | `ReviewProfileMatchPanel` 同时渲染三段互相矛盾的文案:状态徽章「未命中/未匹配」(正确)+「命中模板:未选定模板」行(措辞矛盾)+ 无条件阻断框「模板已命中,但字段提取仍被安全门禁阻断」(与未命中事实直接冲突),并把原始内部码 `generic_extraction_disabled` 直接拼进文案(无本地化)。后端事实:模板未命中时进入通用解析判定,通用解析未启用 → `fallback_reason_codes=['generic_extraction_disabled']`,语义是「通用解析被禁」,不是「模板已命中被阻断」 | P0(前端按状态分流文案 + 原因码本地化) |
---
## 1. 问题 1:附件刚发送时不在气泡/面板中显示
### 1.1 现象
货代智能体对话中,用户选择 `.eml`/`.pdf` 附件并发送:发送瞬间气泡(或工作台「当前附件」区)不显示文件,数秒后才出现。
### 1.2 证据链
**(A)服务端:`user_attachments` 是「终态后懒写」字段(主因,≈65%)**
- SSE 路径落库:`DifyService._persist_stream_chat_record`(`backend/app/services/dify.py:1465-1526`)在终态创建 ChatLog,`payload=message_payload`(`dify.py:1524`),**不含** `user_attachments`。
- 合并时机:relay 层仅在终态事件(`error`/`message_end`/`workflow_finished`)且事件携带本地 `chat_log_id` 时,调用 `_merge_user_attachments_from_terminal_event`(`backend/app/api/chat.py:98-134`、`:1794-1825`)→ `merge_chat_log_payload`(`backend/app/services/chat/log_service.py:77-132`)把 `{user_attachments}` 补写进该 log 的 payload。
- 后果:该 ChatLog 的附件「先无后有」。窗口期内 `GET /api/chat/messages`(`chat.py:1286-1348`,读 `payload.user_attachments` 于 `:1310-1319`)返回的用户消息**无附件**;若该轮是「仅附件、display_query 为空」导致 `log.query == ''`,`chat.py:1316` 判定不成立,**用户消息整条消失**。
- 已核实不成立项:`chat_log_id` 归属正确(`persist_stream_chat` 把本地 `ChatLog.id` 回写同一终态事件,`dify.py:999-1000`;executor 路径 `executors/dify_workflow.py:14-17` 仍汇入 `DifyService.stream_chat`);默认路径下前端 `refreshConversationAfterSend` 不会抢跑 merge(前端 `useChat.ts:682-683` 等到 SSE EOF 才 resolve,服务端 `chat.py:1815-1825` 先 commit 再 yield)。
**(B)前端:多次「整体替换消息」且不比对附件(放大器,≈35%)**
- 发送成功后 `useChatPageSend.handleSend` 调用 `refreshConversationAfterSend`(`frontend/src/features/chat/page/useChatPageSend.ts:172-175`)→ `useChatPage.ts:421-442`:`listChatMessages` 后若 `shouldApplyServerConversationSnapshot`(`useChatPage.ts:69-84`,只比较消息条数与助手正文长度,**完全不比较附件**)为真则整体替换 `messages`。若服务端快照无附件 → 乐观气泡附件被抹掉。
- 「稍后出现」的来源:`useChatShipping.syncConversationMessagesIfNeeded`(`useChatShipping.ts:308-332`,`checkpoint==='parse_review'` 时整体替换,触发于 watch `:921-930` 与 3s 状态轮询 `:881-894`)、`loadConversation`(`page/useChatPageConversation.ts:80-88`、`useChatRouteSync.ts:101,151`、`useChatSessions.ts:132`)。这些重拉发生在服务端合并提交之后 → 附件补上。
**(C)货代自动流:首次点击发送被「解析中」拦截(与「刚发送时看不到文件」直接相关)**
- `useChatShippingSendHandler.tryHandleShippingAttachmentAutoFlow`(`frontend/src/features/chat/shipping/useChatShippingSendHandler.ts:104-208`):附件仍在解析(`hasBlockingNoticeIntake` = `useShippingNoticeIntakes.hasBlockingUploadOrParse`,`useChatShipping.ts:761`)时,仅 toast「发货通知正在上传或解析,请稍后再确认建单。」并 `return true` 消费发送,**不落任何气泡**(`:112-115`)。
- 输入区提示「解析完成后点发送确认建单」(`ChatInputBar.vue:678`,i18n `chat.shippingNoticeConfirmBatchHint`)。
- 解析完成后**无自动触发**:`markOrderExtractionStarted`/`allReadyForConfirmation`(`useShippingNoticeIntakes.ts:306-312,480-491`)只更新输入区状态,无 watch 自动调用 `startRun`;用户需**再次点击发送**(`:121-150`)→ `useShippingOrderExtractionRuns.startRun`(`useShippingOrderExtractionRuns.ts:459-517`)push 带附件的用户消息(`:486-501`)——附件气泡立即出现。
- 该路径用户消息经 `saveLocalMessageToBackend`(`useChatPageLocalMessage.ts:39-57`)落库时已把 `user_attachments` 写入 payload(`:51-53`),后端 `save_local_message`(`chat.py:1350-1429`)与 `get_chat_messages` 均能还原——**该路径本身不丢附件**,丢的是「第一次点击无任何上屏」。
**(D)工作台「当前附件/邮件正文」按需异步加载(与截图场景强相关)**
- `ReviewIntakeParsePanel`(`frontend/src/features/chat/components/shipping-review/ReviewIntakeParsePanel.vue:49-54`)加载中只显示「正在加载接收解析上下文…」,无附件占位。
- `ensureIntakeParseContextLoaded`(`useShippingOrderReview.ts:863-906`)仅在进入接收解析工作面(`selectLifecycleStage`,`ShippingOrderReviewView.vue:419-421`;watcher `:3700`)时按需请求 `getWorkspaceShippingOrderReviewIntakeParseContext`(`shipping.api.ts:970`)。
- 后端 `get_case_intake_parse_context`(`order_review_evidence_service.py:594-664`)首次较重:读对象存储 `read_asset_bytes` + EML 提取/HTML 消毒 + 写预览快照(`eml_preview_service.py:107-161`)+ 把整段 HTML 写 Redis 签发票据(`:77-86`)+ 同步审计写(`shipping_notice.py:2707`)。期间面板为空,用户感知「附件要等一会儿才出现」。
### 1.3 修复方案
| 优先级 | 改动 | 位置 | 影响面 |
| --- | --- | --- | --- |
| P0 | 后端落库即写:`_persist_stream_chat_record` 落库 payload 时直接带上 `user_attachments`(由 `/api/chat/completions` 传入 `persist_stream_chat`,而非仅依赖 relay 终态合并);终态合并仅作兜底幂等 | `backend/app/services/dify.py:1524`(`_persist_stream_chat_record`/`persist_stream_chat` 签名)+`backend/app/api/chat.py:1583,1794-1825` | 低:写入路径同事务;需同步单测 `test_*stream*`,注意 `message_payload` 为 None 时的纯文本请求不注入附件 |
| P0 | 前端快照覆盖保护:`shouldApplyServerConversationSnapshot`(及 `saveLocalMessageToBackend` 同源审查)增加附件维度——本地用户消息 `attachments` 非空而服务端对应消息缺失时,保留本地(不整体替换) | `frontend/src/features/chat/composables/useChatPage.ts:69-84`、`useChatPageSend.ts:172-175` 补充合并策略(仅以服务端**新增**助手消息做增量合并) | 中:需覆盖 `useChatPageSend.spec.ts`、`useChatPageConversation.spec.ts` 既有断言 |
| P1 | 货代自动流:解析完成后自动续跑「确认建单」,或首次点击即落「等待解析」占位气泡(附件快照 + 状态卡),避免「点击无反馈」 | `useChatShippingSendHandler.ts:104-156`、`useShippingNoticeIntakes.ts`(`allReadyForConfirmation` 补 watch → `startOrderExtractionRun`) | 中:涉及「点击语义」变更,需产品确认(提示文案 `chat.shippingNoticeWaitingForParse`/`ConfirmBatchHint` 同步调整) |
| P1 | 工作台接收解析面板:Case 快照 `loading_context`(`ShippingOrderReviewCaseLoadingContext`,`shipping.api.types.ts:2696-2706`)附带附件元数据(文件名/类型/大小),面板先展示附件信息,正文/PDF 预览异步加载 | `backend/app/api/workspace/shipping_notice.py`(case 投影)+`ReviewIntakeParsePanel.vue` | 中:需后端快照字段扩展 + 前端占位态 |
---
## 2. 问题 2:解析进度始终「生成订单候选」,无细化阶段
### 2.1 现象
对话框 / 工作台进度显示停留在「生成订单候选」(`chat.shippingProcessing.stage.candidate_creating`),没有任何「正在解析版面 / 正在匹配模板 / 正在提取字段」的细进度;用户反馈「之前应该有对应的阶段」。
### 2.2 证据链
- **粗粒度**:work-item 投影(`shipping_processing_projection.py:1565-1570,1737-1742`)只下发 15 阶 `stage` 与 `stage_label_key`;`candidate_creating` 在 `PROCESSING_STAGE_INDEX_MAP`(`frontend/src/features/chat/shipping/shippingStepper.ts:79-95`)与 `processing_projection_invariants.py` 中跨度 = 版面解析→模板匹配→表格重建→字段提取→邮件合并→候选生成,全过程阶段码不变。
- **细粒度已存在但无出口**:`chat.shippingProcessing.progress.step.*`(document_queued / layout_parsing_started / layout_parsing_completed / profile_matching / profile_matched / table_reconstructed / order_fields_extracted / email_supplement_merged / review_ready / review_required,四语言齐备,`zh-CN/chat.json:2800` 等)只由 Run 级 `_build_lifecycle_progress` 的 `current_step_i18n_key` 生成(`backend/app/services/shipping_notice/order_extraction_workspace_projection.py:81-175`,`_LIFECYCLE_EVENT_STEP_CODES` `:43-57`),**仅**工作台顶部横幅消费(`ShippingOrderReviewView.vue:1991-2040,3934-3946`)。
- **15 节点阶段条无挂载点**:`ReviewProgressStrip`(`shipping-progress/components/ReviewProgressStrip.vue`)、`ReviewWorkflowProgressPanel`、`UnifiedProgressTrack`、`ChatProgressSummary`、`WorkbenchProgressGrouped` 全仓库无使用方(grep 仅自引用);五阶段重构(`935bf26f`)后唯一保留的 `ReviewProcessDetailDrawer`(`ShippingOrderReviewView.vue:4926`)缺少打开入口(strip 未挂载)。
- **对话侧展示单薄**:`SidebarProgressInline.inlineLine`(`shipping-progress/components/SidebarProgressInline.vue:37-41`)仅 `● ${resolveShippingProcessingStageLabel(stage, te, t)}`——未传第 4 参 `labelKey`、未渲染 `stage_nodes`/step。
- **横幅文案兜底**:`lifecycleProgressMessage`(`ShippingOrderReviewView.vue:2001-2040`)`running` 态且 `current_step_i18n_key` 缺失时回退「系统正在自动处理,请稍候或刷新进度」(`systemProcessingNeed`)——与截图「系统正在自动处理 · 当前结果需要人工复核」组合一致;该组合在 `_build_lifecycle_progress` 单函数内不成立(review_required → `lifecycle_status='waiting'`),提示 **截图环境可能与当前分支版本不一致**(见 §5 待确认)。
### 2.3 修复方案
| 优先级 | 改动 | 位置 | 说明 |
| --- | --- | --- | --- |
| P0 | 后端:conversation/order-task 投影按 Run 计算一次细粒度步骤并挂到同 Run 全部 work item 的 `ui_state`(新增 `current_step_code` / `current_step_i18n_key` / `completed_step_codes`,复用 `_build_lifecycle_progress` 或抽出轻量 helper——按 `run_no` 缓存,禁止逐 item 重查进度事件) | `backend/app/services/shipping_notice/shipping_processing_projection.py`(`project_order_task`/`conversation_processing` 出口)+`frontend/src/features/chat/types/shipping.api.types.ts`(`ConversationProcessingUiState` `:728-738`) | 同步更新 `progress_audit_contract.py`(若字段进契约)与后端单测 |
| P1 | 前端:`SidebarProgressInline`(及 `ChatProgressSummary`/`UnifiedProgressTrack` 如有使用)展示「● 生成订单候选 · 正在匹配订单模板」;`resolveShippingProcessingStageLabel` 调用传 `stage_label_key` | `shipping-progress/components/SidebarProgressInline.vue`、`chat/shipping/shippingProcessingLabels.ts:126-149`(第 4 参已支持) | 纯展示 |
| P1 | 恢复 15 节点阶段条:挂载 `ReviewWorkflowProgressPanel`(工作台阶段导航下)与/或对话卡「查看流程详情」入口(drawer 已存在) | `ShippingOrderReviewView.vue`、`ShippingWorkflowTimeline.vue` | 复用既有组件,避免重复实现 |
| P1 | 横幅文案修正:`running` 且步骤文本缺失时显示「系统处理中 · {当前阶段名}」(用 `stage_label_key`),禁止与门禁原因同屏冲突 | `ShippingOrderReviewView.vue:2010-2040` | 与截图矛盾文案收敛 |
---
## 3. 问题 3:模板匹配「未匹配」与「命中模板」矛盾
### 3.1 现象
「文档模板匹配」面板同屏出现:`未匹配/未命中`(状态徽章)+「命中模板:未选定模板」行+「模板已命中,但字段提取仍被安全门禁阻断 / 阻断原因:generic_extraction.disabled」。
### 3.2 证据链
- 后端事实:模板未命中(`no_match`/`no_special_profile_feature`)时进入通用解析判定,通用解析开关关闭 → `fallback_reason_codes=['generic_extraction_disabled']`(`backend/app/services/shipping_notice/order_extraction_workflow.py:1553-1558`、`_should_attempt_generic_extraction` `:1575-1589`)。语义是「**通用解析被禁用**」,**不是**「模板已命中被阻断」。
- 投影:`project_review_case_profile_match`(`backend/app/services/shipping_notice/order_review_profile_match_service.py:162-232`)原样透传 `status=no_match`、`selected_profile=None`、`fallback_reason_codes=['generic_extraction_disabled']`、`needs_review=True`(`_LIFECYCLE…_NEEDS_REVIEW_STATUSES` `:22-27`、`fallback` `:208-213`);管理员视图(`order_review_projection.py:888-908`)保留完整审计字段。
- 前端渲染(`frontend/src/features/chat/components/shipping-review/ReviewProfileMatchPanel.vue`):
- 状态徽章 `statusLabel`(`:63-67`)→ 四态 i18n(`profileMatch.status.*`,`zh-CN/chat.json:2483-2494`);
- 「命中模板」行(`:108-113`):dt 固定 `profileMatch.selected`(中文「命中模板」),`selected_profile` 为空时 dd 为 `noSelected`(「未选定模板」)——一行内自相矛盾;
- 阻断框(`:115-124`):**无条件**渲染 `profileMatch.extractionBlocked`(「模板已命中,但字段提取仍被安全门禁阻断」)+ `extractionBlockedReason`(「阻断原因:{reasons}」),`reasons` 为 **raw 内部码**(`extractionBlockReasons` `:46-49` 直接 `join(', ')`,无本地化;admin 视图下正是截图状态)。
- 本地化映射已存在但未消费:`processing_projection_invariants.py:836-849`(`generic_extraction_disabled` → `chat.shippingProcessing.reasonCode.generic_extraction_disabled`「当前文件不满足自动解析条件,需要人工复核」,四语言齐备 `chat.json:2889` 等)。
- 注:截图为 `generic_extraction.disabled`(**点分**),当前分支为 `generic_extraction_disabled`(**下划线**)——疑似旧版本代码/数据,见 §5 待确认。
### 3.3 修复方案
| 优先级 | 改动 | 位置 |
| --- | --- | --- |
| P0 | 阻断框按 `status` 分流:`matched`/`unique_match`/`selected_by_score` → 保留「模板已命中,但字段提取仍被安全门禁阻断」;`unmatched`/`no_match`/`no_special_profile_feature` → 新增键(四语言)「未命中模板,通用解析被安全门禁阻断」;`ambiguous`/`layout_drift` → 「模板未唯一命中,需要人工确认」 | `ReviewProfileMatchPanel.vue` + `locales/zh-CN|zh-TW|en|th/chat.json`(`profileMatch` 节新增 2 键) |
| P0 | 原因码本地化:逐个 `chat.shippingOrderReview.profileMatch.reasons.<code>` → `chat.shippingProcessing.reasonCode.<code>`(`generic_extraction_disabled` 已有)→ 兜底「需人工处理」;**禁止输出裸码**(含点分/下划线归一化) | `ReviewProfileMatchPanel.vue:46-49,122-123` |
| P1 | 「命中模板」行语义修正:仅当 `selected_profile` 存在时渲染「命中模板:{name}」;无选中时改为「未匹配任何模板」说明行(或并入徽章态),不再出现「命中模板:未选定模板」 | `ReviewProfileMatchPanel.vue:108-113` |
| P1 | 后端(可选):`project_review_case_profile_match` 下发 `fallback_reason_i18n_keys`(复用 `processing_projection_invariants.py:836-849` 映射),前端纯消费 i18n 键 | `order_review_profile_match_service.py:208-213` |
---
## 4. i18n 变更清单(四语言)
| 位置 | 变更 |
| --- | --- |
| `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json` | `shippingOrderReview.profileMatch` 节新增:`extractionUnmatchedBlocked`(未命中模板·通用解析被禁)、`extractionAmbiguousBlocked`(模板未唯一命中·需人工确认)【按 §3.3 分流方案】;其余复用既有键(`progress.step.*`、`reasonCode.generic_extraction_disabled` 均已存在) |
| 若 §1.3 P1 调整点击语义 | `chat.shippingNoticeWaitingForParse` / `chat.shippingNoticeConfirmBatchHint` 文案补充「点击后将自动建单」等说明 |
| 若 §2.3 P1 恢复阶段条 | 复用既有 `progress.*` / `stageNode.*` / `stage.*` 键,无需新增 |
> 按 AGENTS.md 红线:新增文案必须四语言同步,禁止硬编码中文。
---
## 5. 待确认项
1. **部署版本**:截图出现 `generic_extraction.disabled`(点分)与「系统正在自动处理 · 当前结果需要人工复核」(`_build_lifecycle_progress` 单函数内不可同时产生),建议先核对测试/生产环境与当前分支(`06c18b3c`)的部署版本差异,避免按旧版现象修新版代码。
2. **产品确认**:§1.3 P1「解析完成后自动续跑建单」改变原有「二次点击确认」语义,需业务确认(影响提示文案与用户习惯)。
3. **数据**:历史会话中已落库但合并失败(`chat_log_id=0`/归属不匹配)的消息,无 `user_attachments`,是否需要一次性补偿脚本(可选,低优)。
---
## 6. 回归验证清单
- 前端:`npm run build` 通过;`npx vitest run` 覆盖 `useChatPageSend.spec.ts`、`useChatPageConversation.spec.ts`、`ReviewProfileMatchPanel.spec.ts`、`SidebarProgressInline`/`presenters.spec.ts`(若改动作)、`shippingProcessingLabels` 相关用例。
- 后端:`backend/tests` 中 `test_shipping_processing_projection_stage4.py`、`test_shipping_order_extraction_runs.py`、`test_shipping_generic_*` 相关断言;SSE 落库附件用例(`test_chat_*`,如存在)。
- 手工:发送带附件消息(附件在前/后)→ 附件立即上屏;解析中 → 进度行显示「生成订单候选 · 正在匹配订单模板」;工作台接收解析「当前附件」秒开;未命中模板+通用解析关闭 → 仅「未命中模板 / 未匹配任何模板 / 通用解析被安全门禁阻断(已本地化原因)」。
@@ -1748,6 +1748,24 @@ GET /api/admin/shipping-order-schema/published-contract
- 对话上传 `.xls/.xlsx/.csv` 且用户明确声明库存文件时,不会创建库存快照、不会自动确定库存源。后端先把它保存为当前用户和当前聊天会话隔离的“临时库存文件会话”,执行确定性结构初检;只有同时识别到料号和可用库存数量时,才作为库存候选交给后续受控映射建议流程。未知或不符合最低特征的文件明确拒绝,不能仅靠文件名或扩展名认定为库存文件。与之独立的任务级人工库存上传必须使用任务已确认库存站点绑定的 published 解析方案;结构一致后直接进入待匹配,结构漂移则完整回滚,不再产生任务级字段对齐确认。
- 临时文件“库存候选分类”只使用受控表头特征阻止明显订单/未知表格,不能作为最终字段映射;最终映射仍保存库存字段目录 ID,并在确认质量检查时按字段的匹配标识/库存数量用途解析,避免把可配置字段错误退化为固定技术编码。
### 连接级受控上传参数(upload_config_json,连接例外)
发货 Excel 自动上传的页面参数作为 `ShippingRpaProfile.upload_config_json` 直接挂在既有“系统连接”上,一条连接只保存一份上传配置。**这是连接级受控上传参数的例外**:它只作用于货代上传,不向库存 RPA 或收料 RPA 扩散,也不新建 Upload Profile、关联表、版本表或发布流。
- **配置由管理端表单编辑,后端保存为受限 JSON**。白名单字段仅 `enabled / entry_url / file_input_selector / submit_mode / submit_selector / result_mode / result_selector / success_texts / timeout_seconds`;保存时后端严格校验:
- `connector_type` 仍只能是 `dbs / crane`。
- `entry_url` 必须 HTTPS,且主机名只允许该连接已审核的平台域名(`dbschenker.com` / `craneww.com` 后缀匹配)。
- 三个 selector 只允许普通 CSS selector,限制长度(≤200)并拒绝 `javascript:`、`<script`、`expression(`、`on*=` 及 `() {} ; < >` 等脚本/表达式语义。
- `submit_mode` 只允许 `auto_after_file / click_submit`;`result_mode` 只允许 `page_notice / history_record`。
- `enabled=true` 时须具备完成一次上传与判定结果所需的全部字段:公共必填 `entry_url / file_input_selector / submit_mode / timeout_seconds`;`click_submit` 须有 `submit_selector`;crane 启用时还须补全 `result_selector` 与成功文本/记录判定字段(DSV 由代码内置的受控成功流判定,不强制管理员填写)。
- 禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作落库。
- **DSV 初始值**:`enabled=true`,`entry_url=https://s360.dbschenker.com/main/portal/frame/WMSUpload2`,`file_input_selector=input#file2`,`submit_mode=auto_after_file`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。
- **Crane 初始值**:`enabled=false`(提交按钮、成功提示或上传历史记录的稳定选择器尚未确认,仅有文件选择器不代表可安全自动提交),`entry_url=https://wms-portal.craneww.com/#/shipping-order-upload`,`file_input_selector=input[name="OrderFileUpload"]`,`submit_mode=click_submit`,`submit_selector=null`,`result_mode=page_notice`,`success_texts=[]`,`timeout_seconds=120`。管理员完成页面验证并补全提交/成功判定字段后才可 `enabled=true`。
- **不改版本号**:`upload_config_json` 变更不递增 `config_version`,避免库存 RPA 配置测试被误判过期;不维护 `upload_config_version`(无发布流、无并发编辑审批、无历史回放需求)。每个 trigger 固化本次 upload_config 快照即可保证“这次上传用了什么”;需要审计关联时对快照计算 `config_hash`(sha256)。
- **Worker 保留两个受控 Adapter**:`DsvUploadAdapter`(DSV 入口、文件选择与结果判定)与 `CraneUploadAdapter`(Crane 入口、文件选择、提交与结果判定),**不再根据环境变量拼接 DSV/Crane 页面动作**。用连接 `login_url` 登录后访问 `upload_config.entry_url` 进入上传页;`upload_config` 决定“该连接使用哪个已支持的受控流程及其页面参数”,浏览器动作与安全边界由代码负责;Worker 上传与最终提交的全局开关(`SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED` / `..._CONFIRM_SUBMIT`)仍作为部署级二次确认保留,但不再承载页面参数。
- **执行链路**:用户触发批量 RPA 上传 → 后端创建 Upload Attempt → 读取任务已确定的系统连接及 `upload_config_json` → 复制发货 Excel 到共享上传队列 → 生成非空 `callback_id` → 原子写入 trigger(复用“临时文件 + fsync + os.replace”,携带 `schema_version / task_no / attempt_id / artifact_id / callback_id / connector_type / upload_config 快照 / upload_config_hash / login_url / credential_envelope`)→ Windows Worker 取 trigger → 按 `connector_type` 进入 DSV/Crane Adapter → 登录、打开 entry_url、选择 Excel、提交 → 以页面提示或上传历史证据判定 → 回调。
- **结果三态**:`success`(取得可核验成功证据)、`failed`(明确页面失败、浏览器错误、超时或回调失败)、`unknown`(已可能提交但无法确认外部系统结果)。`unknown` 必须转人工处理,禁止自动重试以避免重复上传;成功/失败/未知、页面证据摘要与脱敏错误写入现有 Upload Attempt 与货代审计事件。
发布门禁:全局只有一个 published 版本;已发布版本不可编辑;字段首次发布后 `scope/value_type` 不可修改,`field_code` 重命名仅影响后续草稿,历史发布快照保留旧名称;证据来源、比较器、规范化器和校验器只能引用后端白名单。
# 发货 Excel 模板
@@ -98,6 +98,24 @@
<label><span>{{ t('admin.shippingInventory.username') }}</span><input v-model="profile.username" class="input-field" name="shipping-rpa-credential-user" autocomplete="one-time-code" readonly :placeholder="t('admin.shippingInventory.writeOnlyHint')" @focus="unlockCredentialField"></label>
<label><span>{{ t('admin.shippingInventory.password') }}</span><input v-model="profile.password" class="input-field" name="shipping-rpa-credential-password" type="password" autocomplete="new-password" readonly :placeholder="t('admin.shippingInventory.writeOnlyHint')" @focus="unlockCredentialField"></label>
<div class="switch-field"><span>{{ t('admin.shippingInventory.enabled') }}</span><button type="button" class="status-switch" :class="{ on: profile.enabled }" role="switch" :aria-checked="profile.enabled" @click="profile.enabled = !profile.enabled"><i></i><b>{{ profile.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
<section class="upload-config-section full">
<header class="upload-config-heading">
<b>{{ t('admin.shippingInventory.uploadConfigTitle') }}</b>
<small>{{ t('admin.shippingInventory.uploadConfigHint') }}</small>
</header>
<div class="switch-field"><span>{{ t('admin.shippingInventory.uploadAutoEnabled') }}</span><button type="button" class="status-switch" :class="{ on: profile.upload_config_json.enabled }" role="switch" :aria-checked="profile.upload_config_json.enabled" @click="profile.upload_config_json.enabled = !profile.upload_config_json.enabled"><i></i><b>{{ profile.upload_config_json.enabled ? t('admin.shippingInventory.enabledState') : t('admin.shippingInventory.disabledState') }}</b></button></div>
<label><span>{{ t('admin.shippingInventory.uploadEntryUrl') }}</span><input v-model="profile.upload_config_json.entry_url" class="input-field" type="url"></label>
<label><span>{{ t('admin.shippingInventory.uploadFileSelector') }}</span><input v-model="profile.upload_config_json.file_input_selector" class="input-field"></label>
<label><span>{{ t('admin.shippingInventory.uploadSubmitMode') }}</span><select v-model="profile.upload_config_json.submit_mode" class="select-field"><option value="auto_after_file">{{ t('admin.shippingInventory.uploadSubmitAuto') }}</option><option value="click_submit">{{ t('admin.shippingInventory.uploadSubmitClick') }}</option></select></label>
<label v-if="profile.upload_config_json.submit_mode === 'click_submit'"><span>{{ t('admin.shippingInventory.uploadSubmitSelector') }}</span><input v-model="profile.upload_config_json.submit_selector" class="input-field"></label>
<label><span>{{ t('admin.shippingInventory.uploadResultMode') }}</span><select v-model="profile.upload_config_json.result_mode" class="select-field"><option value="page_notice">{{ t('admin.shippingInventory.uploadResultPageNotice') }}</option><option value="history_record">{{ t('admin.shippingInventory.uploadResultHistory') }}</option></select></label>
<label><span>{{ t('admin.shippingInventory.uploadResultSelector') }}</span><input v-model="profile.upload_config_json.result_selector" class="input-field"></label>
<label><span>{{ t('admin.shippingInventory.uploadSuccessTexts') }}</span><textarea v-model="successTextsInput" class="input-field" rows="2" :placeholder="t('admin.shippingInventory.uploadSuccessTextsHint')"></textarea></label>
<label><span>{{ t('admin.shippingInventory.uploadTimeout') }}</span><input v-model.number="profile.upload_config_json.timeout_seconds" class="input-field" type="number" min="1"></label>
<div class="form-tip full">{{ t('admin.shippingInventory.uploadConfigBoundary') }}</div>
</section>
<div class="form-tip full">{{ t('admin.shippingInventory.connectionBoundary') }}</div>
</template>
@@ -565,7 +583,33 @@ const filenameVariableCandidates = computed(() => {
return filenameVariables.filter((item) => item.key.toLowerCase().includes(query) || t(item.labelKey).toLowerCase().includes(query));
});
const profile = reactive({ profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true });
/** 连接级“发货 Excel 自动上传”配置的受控 JSON 形状(字段与后端白名单一致)。 */
interface ProfileUploadConfig {
enabled: boolean;
entry_url: string;
file_input_selector: string;
submit_mode: 'auto_after_file' | 'click_submit';
submit_selector: string | null;
result_mode: 'page_notice' | 'history_record';
result_selector: string | null;
success_texts: string[];
timeout_seconds: number;
}
/** 连接级“发货 Excel 自动上传”默认配置:DSV 为已确认 URL+input#file2;Crane 保持未启用待管理员补全。 */
function defaultUploadConfig(connectorType: string): ProfileUploadConfig {
if (connectorType === 'crane') {
return { enabled: false, entry_url: 'https://wms-portal.craneww.com/#/shipping-order-upload', file_input_selector: 'input[name="OrderFileUpload"]', submit_mode: 'click_submit', submit_selector: null, result_mode: 'page_notice', result_selector: null, success_texts: [], timeout_seconds: 120 };
}
return { enabled: true, entry_url: 'https://s360.dbschenker.com/main/portal/frame/WMSUpload2', file_input_selector: 'input#file2', submit_mode: 'auto_after_file', submit_selector: null, result_mode: 'page_notice', result_selector: null, success_texts: [], timeout_seconds: 120 };
}
const profile = reactive({ profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true, upload_config_json: defaultUploadConfig('dbs') });
/** 成功文本以换行分隔的输入视图,写回 success_texts 数组。 */
const successTextsInput = computed<string>({
get: () => (profile.upload_config_json.success_texts || []).join('\n'),
set: (value) => { profile.upload_config_json.success_texts = String(value || '').split(/\r?\n/).map((item) => item.trim()).filter(Boolean); },
});
const parsing = reactive({ profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1, field_mappings: [] as ParsingFieldMapping[], match_keys: [] as ParsingMatchKey[] });
const inventoryField = reactive<InventoryFieldForm>({ display_name: '', description: '', value_type: 'text', usage_type: 'general', sort_order: 100, status: 'active' });
const excelTemplate = reactive({ template_code: '', display_name: '', filename_pattern: '{business_no}.xlsx', mappings: [] as TemplateMapping[], file: null as File | null });
@@ -868,6 +912,14 @@ watch(
{ immediate: true },
);
/** 新建连接时按货代类型切换上传配置默认值;编辑既有连接不覆盖已保存配置。 */
watch(
() => profile.connector_type,
(nextType) => {
if (!selectedId.value) profile.upload_config_json = defaultUploadConfig(nextType);
},
);
/** 在库存映射内切换解析方案与字段目录,保持左侧业务入口不分裂。 */
function selectInventoryMappingTab(tab: 'parsing' | 'inventoryFields'): void {
activeTab.value = tab;
@@ -877,7 +929,7 @@ function selectInventoryMappingTab(tab: 'parsing' | 'inventoryFields'): void {
/** 重置当前工作区的编辑表单,作为创建新对象的入口。 */
function createNew(): void {
selectedId.value = null;
if (activeTab.value === 'profiles') Object.assign(profile, { profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true });
if (activeTab.value === 'profiles') Object.assign(profile, { profile_code: '', display_name: '', connector_type: 'dbs', login_url: '', username: '', password: '', login_config_json: { auth_mode: 'password' }, enabled: true, upload_config_json: defaultUploadConfig('dbs') });
if (activeTab.value === 'parsing') { Object.assign(parsing, { profile_code: '', display_name: '', file_format: 'xlsx', sheet_name: '', header_row_index: 1, field_mappings: [], match_keys: [] }); structureAnalysis.value = null; pendingSampleReplacement.value = null; sampleReplacementConfirmed.value = false; selectedTemporaryInventorySession.value = ''; }
if (activeTab.value === 'inventoryFields') Object.assign(inventoryField, { display_name: '', description: '', value_type: 'text', usage_type: 'general', sort_order: 100, status: 'active' });
if (activeTab.value === 'templates') {
@@ -898,7 +950,7 @@ function createNew(): void {
/** 将列表对象复制到当前编辑表单,凭据字段永远不从列表回填。 */
function selectItem(item: Item): void {
selectedId.value = Number(item.id);
if (activeTab.value === 'profiles') Object.assign(profile, { ...item, username: '', password: '', login_config_json: item.login_config_json || { auth_mode: 'password' } });
if (activeTab.value === 'profiles') Object.assign(profile, { ...item, username: '', password: '', login_config_json: item.login_config_json || { auth_mode: 'password' }, upload_config_json: item.upload_config_json || defaultUploadConfig(item.connector_type) });
if (activeTab.value === 'parsing') Object.assign(parsing, {
profile_code: item.profile_code, display_name: item.display_name, file_format: item.file_format,
sheet_name: item.definition?.sheet_name || '', header_row_index: item.definition?.header_row_index ?? 0,
@@ -1067,7 +1119,7 @@ function closeDrawer(): void {
async function saveCurrent(): Promise<void> {
saving.value = true;
try {
if (activeTab.value === 'profiles') await saveShippingRpaProfile({ ...profile, display_name: profile.display_name || profile.profile_code }, selectedId.value || undefined);
if (activeTab.value === 'profiles') await saveShippingRpaProfile({ ...profile, display_name: profile.display_name || profile.profile_code, upload_config_json: profile.upload_config_json }, selectedId.value || undefined);
if (activeTab.value === 'parsing') {
const payload = {
profile_code: parsing.profile_code, display_name: parsing.display_name || parsing.profile_code, file_format: parsing.file_format,
@@ -1598,6 +1650,7 @@ onMounted(load);
.readiness-optional { border-top: 1px solid #e4edf2; padding-top: 10px; }.readiness-optional summary, .readiness-audit summary { display: flex; align-items: baseline; gap: 8px; color: #61798a; cursor: pointer; list-style: none; }.readiness-optional summary::-webkit-details-marker, .readiness-audit summary::-webkit-details-marker { display: none; }.readiness-optional summary::before, .readiness-audit summary::before { color: #4d849f; content: '›'; font-size: 16px; line-height: .8; transition: transform .15s; }.readiness-optional[open] summary::before, .readiness-audit[open] summary::before { transform: rotate(90deg); }.readiness-optional summary span { color: #516b7d; font-size: 12px; font-weight: 700; }.readiness-optional summary small { color: #8797a5; font-size: 11px; }.readiness-optional .readiness-steps { margin-top: 8px; }
.readiness-action { border: 0; border-radius: 5px; background: #e8f3f9; padding: 6px 8px; color: #16759f; font: inherit; font-size: 11px; font-weight: 700; cursor: pointer; }.readiness-action:hover { background: #d8edf7; }.readiness-run { margin: 0; border-left: 3px solid #74b8d8; background: #f0f8fc; padding: 8px 10px; color: #547185; font-size: 11px; line-height: 1.5; }.readiness-run.failed { border-left-color: #e06a58; background: #fff5f3; color: #9d382b; }.readiness-audit { margin: 0; border-top: 1px solid #e4edf2; padding-top: 10px; }.readiness-audit summary { color: #61798a; font-size: 11px; font-weight: 700; }.readiness-audit dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1px; margin: 9px 0 0; overflow: hidden; border: 1px solid #dce8ef; border-radius: 7px; background: #dce8ef; }.readiness-audit dl > div { min-width: 0; background: #fff; padding: 8px 9px; }.readiness-audit dt { color: #7b8998; font-size: 11px; font-weight: 700; }.readiness-audit dd { overflow: hidden; margin: 4px 0 0; color: #3d5366; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11px; font-variant-numeric: tabular-nums; text-overflow: ellipsis; white-space: nowrap; }.readiness-footer { display: flex; justify-content: flex-end; border-top: 1px solid #e6eef4; padding-top: 11px; }
.form-tip { border-radius: 8px; background: #f1f6fa; padding: 11px; color: #5d7084; font-size: 12px; line-height: 1.55; }
.upload-config-section { grid-column: 1 / -1; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; border: 1px solid #e1edf2; border-radius: 9px; background: #fff; padding: 0 12px 12px; }.upload-config-heading { display: grid; gap: 2px; grid-column: 1 / -1; padding: 11px 0 8px; }.upload-config-heading b { color: #385166; font-size: 12px; }.upload-config-heading small { color: #8192a0; font-size: 11px; }.upload-config-section .full { grid-column: 1 / -1; }.upload-config-section textarea.input-field { resize: vertical; }
.configuration-test-verified { margin: 0; border-left: 3px solid #34a56b; background: #effaf3; padding: 9px 10px; color: #256b43; font-size: 12px; font-weight: 600; line-height: 1.45; }
.sample-evidence-card { display: grid; gap: 12px; border: 1px solid #d7e3ed; border-radius: 8px; background: #f8fbfd; padding: 14px; }
.sample-evidence-card > div { display: grid; gap: 3px; }.sample-evidence-card strong { color: #334155; font-size: 13px; }.sample-evidence-card p, .sample-evidence-card > small { margin: 0; color: #6b7f91; font-size: 12px; line-height: 1.55; }
@@ -2,7 +2,8 @@
* features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts
* 用途:验证工作台右侧当前任务卡只在需要人工处理时渲染业务动作。
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewCurrentProcessingCard。
* 逻辑:库存自动处理中即使遗留 primary_action,也不得显示编辑正式任务;可重试状态仍保留重试入口。
* 逻辑:库存自动处理中即使遗留 primary_action,也不得显示编辑正式任务;可重试状态仍保留重试入口;
* loading 是「权威投影读取中」占位:已知阶段照常展示,状态/下一步给中性加载文案(非系统处理中)。
*/
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
@@ -38,9 +39,25 @@ const i18n = createI18n({
saveOrderAndValidate: '提交订单',
currentProcessing: {
waitingStart: '等待系统启动',
stageLoading: '正在获取最新状态…',
statusIdle: '待机',
status: '状态',
stages: {
excel_generating: 'Excel 生成',
},
},
currentTask: {
title: '当前任务',
labelStage: '当前门禁',
statusRunning: '系统处理中',
statusWaitingHuman: '待人工处理',
statusRetryable: '可重试',
statusFailed: '自动处理失败',
statusCompleted: '已完成',
statusCancelled: '已取消',
nextStepTitle: '下一步',
nextStepRunning: '系统正在处理,暂不需要人工操作',
nextStepUnknown: '状态待确认',
nextStepWaitingExternal: '等待外部系统回执,暂不需要人工操作',
},
},
@@ -180,6 +197,23 @@ describe('ReviewCurrentProcessingCard', () => {
expect(wrapper.text()).not.toContain('edit_draft');
});
it('hides an unlabeled primary action instead of rendering an icon-only ghost button', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'fulfillment_prep',
userStatus: 'waiting_human',
// 后端下发了动作码,但前端无受控文案(缺失 i18n 映射 / 未登记),
// 必须整体隐藏按钮,不能渲染成只有 Bot/RefreshCw 图标的“幽灵按钮”。
primaryAction: { code: 'unknown_system_action', i18nKey: 'workspace.shippingNotice.processGate.actionCodes.unknown_system_action' },
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-current-task-actions"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(wrapper.text()).not.toContain('unknown_system_action');
});
it('renders a localized reason instead of an internal blocking code in the next step', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
@@ -233,4 +267,46 @@ describe('ReviewCurrentProcessingCard', () => {
['retry_inventory_preparation', {}],
]);
});
it('keeps the known stage and status while the authoritative projection is still loading', () => {
// Case 先到、Projection 后到的过渡窗口:阶段与投影同源(project_stage_for_task),
// status 也来自后端 automation 运行态,必须照常展示,不能退回骨架/「正在更新状态」占位。
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
loading: true,
stageCode: 'excel_generating',
stageLabelKey: 'excel_generating',
userStatus: 'running',
},
global: { plugins: [i18n] },
});
expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toBe('Excel 生成');
// loading 只抑制动作,不掩盖真值:运行态照常显示「系统处理中」。
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toBe('系统处理中');
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text())
.toBe('系统正在处理,暂不需要人工操作');
});
it('shows the neutral idle value instead of a skeleton when nothing is actionable yet', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: { loading: true, stageCode: 'excel_generating', stageLabelKey: 'excel_generating' },
global: { plugins: [i18n] },
});
// 空用户态自然落到「待机 / 状态待确认」,与投影稳态一致——不做骨架→真值的二次刷新。
expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toBe('Excel 生成');
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toBe('待机');
expect(wrapper.get('[data-testid="review-current-task-next-step-text"]').text()).toBe('状态待确认');
});
it('falls back to a neutral stage placeholder only when no stage is known', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: { loading: true },
global: { plugins: [i18n] },
});
expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toBe('正在获取最新状态…');
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toBe('待机');
});
});
@@ -4,6 +4,11 @@
依赖:vue-i18n、ShippingProcessingBlockingReason/PrimaryAction 类型、resolveShippingProcessingStageLabel。
逻辑:主卡内部 section = 「当前阶段/状态/正式OT → 下一步 → 动作区」;
状态文案严格绑定 user_status;blocking_reason 只作下一步问题说明;按钮显隐由后端 retryable + primary_action.parameters 决定;
主动作按钮文案 fail-closed:后端下发动作码但无受控 i18n 文案时整体隐藏该按钮(含图标),禁止渲染无文字裸按钮;
loading 仅代表「权威投影读取中」而非系统运行态:已知阶段/状态/阻断仍照常展示
(与投影同源或后端 automation 运行态),空态自然落到「待机/状态待确认」,
禁止把读取占位误述为「系统处理中」,也不做骨架→真值的二次刷新;
loading 仅在挂载期抑制可执行动作,等权威投影到达后再放行(fail-closed);
由 ShippingOrderReviewView 在 mountCurrentProcessingCard 时挂载。
-->
<script setup lang="ts">
@@ -67,9 +72,15 @@ const { t, te } = useI18n();
/**
* 当前阶段展示文案:优先消费 stage_label_key,禁止直接展示 stage 码。
* 核心逻辑:loading 是「权威投影读取中」占位,不是业务运行态——只要已有可展示的
* 阶段(Case 快照 current_stage 与投影同源,见 currentProcessingStageDisplay),
* 照常展示真实阶段;仅在连降级阶段都没有时才回退 stageLoading 占位文案。
*/
const stageLabel = computed(() => {
if (props.loading) {
const hasKnownStage = Boolean(
String(props.stageCode || '').trim() || String(props.stageLabelKey || '').trim(),
);
if (props.loading && !hasKnownStage) {
return t('chat.shippingOrderReview.currentProcessing.stageLoading');
}
if (props.stageInconsistent) {
@@ -85,11 +96,11 @@ const stageLabel = computed(() => {
/**
* 「状态」行用户态文案:严格绑定 user_status,不再由前端推断。
* loading 只是「权威投影读取中」:只要已有后端下发的 user_status(如 Case automation
* 运行态)就照常展示真实/待机文案,禁止再退回「正在获取最新状态」骨架造成二次刷新
* (状态空时 statusIdle 即中性「待机」,与投影稳态一致)。
*/
const statusLabel = computed(() => {
if (props.loading) {
return t('chat.shippingOrderReview.currentTask.statusRunning');
}
const s = String(props.userStatus || '').trim() as ReviewCurrentUserStatus | '';
const map: Record<ReviewCurrentUserStatus, string> = {
running: t('chat.shippingOrderReview.currentTask.statusRunning'),
@@ -129,9 +140,10 @@ const nextStepText = computed(() => {
}
return raw;
};
if (props.loading) {
return safeMessage(props.automation?.message) || t('chat.shippingOrderReview.currentTask.nextStepRunning');
}
// 加载占位不等于系统运行态:只透传后端 automation.message(若有);
// 其余按 user_status/blocking_reason 照常渲染,空态自然落在「状态待确认」,不做骨架二次刷新。
const automationMessage = props.loading ? safeMessage(props.automation?.message) : '';
if (automationMessage) return automationMessage;
// 1) blocking_reason → 用后端给的 i18n_key 渲染具体阻断
const br = props.blockingReason;
if (br) {
@@ -216,6 +228,10 @@ function isNonTaskCapabilityAction(code: string): boolean {
/**
* 业务动作按钮只消费 primary_action;retryable 是状态,不是授权。
*
* 核心逻辑:除既有授权过滤外,文案必须是后端下发且经受控映射解析出的非空文案
* (businessActionLabel 已 fail-closed 为 '');无文案时整体隐藏按钮,防止
* 渲染成只有图标/空壳的“幽灵按钮”误导用户以为是开关或其他控件。
*/
const showBusinessAction = computed(() => {
if (props.loading) return false;
@@ -230,6 +246,8 @@ const showBusinessAction = computed(() => {
if (isHiddenWorkbenchNavigationAction(code)) return false;
// 无对象边界的泛化 retry 永不展示。
if (code === 'retry') return false;
// [AUTHORITY] 无受控文案的动作码 fail-closed:连图标一起隐藏,不渲染空壳按钮。
if (!businessActionLabel.value) return false;
return true;
});
@@ -1630,6 +1630,16 @@ export interface ShippingFreightNoticeGroup {
business_no: string;
po_number: string | null;
upload_status?: string | null;
/** 上传方式:rpa / manual,用于逐单状态展示。 */
upload_mode?: string | null;
/** 已发起的上传尝试次数,用于逐单状态展示。 */
upload_attempt?: number | null;
/** 最近一次上传的稳定错误码(如 RPA_UPLOAD_FAILED / FREIGHT_REJECTED / UPLOAD_RESULT_UNKNOWN)。 */
upload_error_code?: string | null;
/** 最近一次上传的用户可见失败原因;仅后端事实,禁止前端按状态猜测。 */
upload_error_message?: string | null;
/** 需人工接管的原因码(如 upload_rpa_pending / manual_upload_pending)。 */
pending_human_reason?: string | null;
export_file_name?: string | null;
available_actions?: string[];
lines: Array<{
@@ -594,6 +594,7 @@ async function mountView(query: Record<string, string> = {}) {
waiting_to_start: '等待系统启动',
order_creating: '等待系统启动',
inventory_matching: '库存匹配',
excel_generating: 'Excel 生成',
},
},
currentTask: {
@@ -680,7 +681,14 @@ async function mountView(query: Record<string, string> = {}) {
},
progress: {
step: { profile_matching: '正在匹配订单模板' },
lifecycleReason: { processing_slow: '当前步骤耗时较长,系统仍在继续。' },
lifecycleReason: {
processing_slow: '当前步骤耗时较长,系统仍在继续。',
review_required: '当前结果需要人工复核。',
failed: '当前步骤处理失败,请查看详情后重试。',
cancelled: '本次处理已取消。',
},
systemProcessingNeed: '系统正在自动处理,请稍候或刷新进度',
lifecycleWaitingNeed: '当前步骤需要人工处理',
},
},
shippingSessionWorkItem: {
@@ -873,6 +881,54 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.get('[data-testid="review-run-lifecycle-progress"]').text()).toContain('正在匹配订单模板');
});
it('does not claim automatic processing when the run is waiting at a human gate', async () => {
// 关键断言:门禁待机(waiting)时不得声称「系统正在自动处理」,也不得渲染呼吸点;
// 后端此时通常没有 current_step_i18n_key,旧逻辑会落入自动处理兜底文案。
activeCase.value = null as any;
reviewRun.value = { run_no: 'RUN-WAITING-GATE', items: [] };
extractionLifecycleProgress.value = {
lifecycle_stage: 'order_review', lifecycle_status: 'waiting',
current_step_i18n_key: null,
blocking_reason_i18n_key: 'chat.shippingProcessing.progress.lifecycleReason.review_required',
completed_step_codes: [], health_status: 'normal',
};
const wrapper = await mountView();
const banner = wrapper.get('[data-testid="review-run-lifecycle-current-step"]');
expect(banner.text()).not.toContain('系统正在自动处理');
expect(banner.text()).toContain('当前结果需要人工复核');
expect(banner.html()).not.toContain('animate-pulse');
});
it('shows a waiting fallback without the auto-processing claim when no reason is provided', async () => {
// 关键断言:waiting 且后端未给原因/步骤时,只展示「需要人工处理」,禁止回到自动处理文案。
activeCase.value = null as any;
reviewRun.value = { run_no: 'RUN-WAITING-FALLBACK', items: [] };
extractionLifecycleProgress.value = {
lifecycle_stage: 'order_review', lifecycle_status: 'waiting',
current_step_i18n_key: null,
blocking_reason_i18n_key: null,
completed_step_codes: [], health_status: 'normal',
};
const wrapper = await mountView();
const banner = wrapper.get('[data-testid="review-run-lifecycle-current-step"]');
expect(banner.text()).not.toContain('系统正在自动处理');
expect(banner.text()).toContain('当前步骤需要人工处理');
});
it('does not render the run progress banner for a completed run', async () => {
// 关键断言:Run 已完成时无待办,横幅直接隐藏,避免「已完成仍显示处理中」的矛盾。
activeCase.value = null as any;
reviewRun.value = { run_no: 'RUN-COMPLETED', items: [] };
extractionLifecycleProgress.value = {
lifecycle_stage: 'order_review', lifecycle_status: 'completed',
current_step_i18n_key: null,
blocking_reason_i18n_key: null,
completed_step_codes: ['review_ready'], health_status: 'normal',
};
const wrapper = await mountView();
expect(wrapper.find('[data-testid="review-run-lifecycle-current-step"]').exists()).toBe(false);
});
it('loads a cross-Run file once through the route watcher', async () => {
const originalQueue = reviewQueue.value;
try {
@@ -1211,6 +1267,30 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
});
it('keeps the known Case stage while the authoritative projection is still loading', async () => {
// Case 先到、Projection 后到的过渡窗口:阶段与投影同源(project_stage_for_task),
// 必须直接展示「Excel 生成」,禁止退回自动建单阶段或“正在更新状态”占位。
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
task_missing: false,
confirmed_task_id: 91,
confirmed_task_no: 'SN-STAGE-PENDING',
current_stage: { code: 'excel_generating', label_key: 'excel_generating', inconsistent: false },
automation: { status: 'running', retryable: false, can_auto_create: false, can_build: true },
};
shippingProcessingProjection.value = null;
shippingProcessingLoading.value = true;
const wrapper = await mountView();
await flushPromises();
expect(wrapper.get('[data-testid="review-current-task-stage"]').text()).toContain('Excel 生成');
// 状态列:loading 只抑制动作,不掩盖后端 automation 运行态真值(系统处理中)。
expect(wrapper.get('[data-testid="review-current-task-status"]').text()).toContain('系统处理中');
});
it('does not render legacy reparse failure stage as a separate progress source', async () => {
reviewProgressContext.value = {
item_no: 'WFI-1',
@@ -2047,6 +2127,120 @@ describe('ShippingOrderReviewView layout phase 1', () => {
expect(startWorkflowProgressPollingMock).toHaveBeenCalledTimes(2);
});
it('advances to freight upload after an accepted shortage release', async () => {
const taskApi = await import('@/features/chat/api/shipping.api');
let releaseAccepted = false;
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_id: 903, confirmed_task_no: 'SN-FROZEN', has_formal_ot: true,
line_fulfillment: {
lines: [{
line_key: 'line-frozen',
inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' },
line_allowed_actions: ['release_inventory_shortage'],
release_template_fields: [
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false },
{ field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true },
],
release_required_fields: [{ field_id: '102', display_name: '库位' }],
}],
},
};
vi.mocked(taskApi.decideWorkspaceShippingOrderReviewLineFulfillment).mockImplementation(async () => {
releaseAccepted = true;
return { status: 'ok' } as any;
});
vi.mocked(taskApi.getWorkspaceShippingTask).mockImplementation(async () => ({
task_no: 'SN-FROZEN', status: 'waiting_human', lines: [], events: [],
ui_state: {
process_gate: {
execution_no: 'EXEC-FROZEN-LINE',
current_blocking_gate: { gate_code: 'manual_upload_handoff', status: 'blocked_manual' },
},
actions: { primary: null, secondary: [] },
lifecycle_stage: releaseAccepted ? 'freight_upload' : 'fulfillment_prep',
lifecycle_entries: releaseAccepted
? [
{ code: 'fulfillment_prep', state: 'available' },
{ code: 'freight_upload', state: 'current' },
]
: [{ code: 'fulfillment_prep', state: 'current' }],
stage_context: { upload: {} },
},
} as any));
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await flushPromises();
await wrapper.get('[data-testid="review-fulfillment-line-release-line-frozen"]').trigger('click');
const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]');
await dialog.find('textarea').setValue('客户确认分批发货');
await dialog.find('input').setValue('A-01');
await dialog.get('button.bg-amber-600').trigger('click');
await new Promise<void>((resolve) => setTimeout(resolve, 0));
await nextTick();
// 放行后的首个权威刷新抵达目标阶段时,页面必须同步深链。
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
.toBe('freight_upload');
});
it('keeps notification preparation when the user navigates there while a shortage release is advancing', async () => {
const taskApi = await import('@/features/chat/api/shipping.api');
let releaseAccepted = false;
let resolvePostReleaseTask: ((detail: any) => void) | null = null;
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_id: 904, confirmed_task_no: 'SN-MANUAL', has_formal_ot: true,
line_fulfillment: {
lines: [{
line_key: 'line-manual',
inventory_source: { code: 'DBS', label: 'DBS', status: 'resolved' },
line_allowed_actions: ['release_inventory_shortage'],
release_template_fields: [
{ field_id: '101', display_name: 'ODM ID', value: 'ODM-001', value_source: 'inventory_snapshot', requires_manual: false },
{ field_id: '102', display_name: '库位', value: null, value_source: 'manual_required', requires_manual: true },
],
release_required_fields: [{ field_id: '102', display_name: '库位' }],
}],
},
};
const taskDetail = () => ({
task_no: 'SN-MANUAL', status: 'waiting_human', lines: [], events: [],
ui_state: {
process_gate: { execution_no: 'EXEC-MANUAL-LINE', current_blocking_gate: { gate_code: 'manual_upload_handoff', status: 'blocked_manual' } },
actions: { primary: null, secondary: [] },
lifecycle_stage: releaseAccepted ? 'freight_upload' : 'fulfillment_prep',
lifecycle_entries: releaseAccepted
? [{ code: 'fulfillment_prep', state: 'available' }, { code: 'freight_upload', state: 'current' }]
: [{ code: 'fulfillment_prep', state: 'current' }],
stage_context: { upload: {} },
},
});
vi.mocked(taskApi.decideWorkspaceShippingOrderReviewLineFulfillment).mockImplementation(async () => {
releaseAccepted = true;
return { status: 'ok' } as any;
});
vi.mocked(taskApi.getWorkspaceShippingTask).mockImplementation(async () => {
if (!releaseAccepted) return taskDetail() as any;
return new Promise((resolve) => { resolvePostReleaseTask = resolve; });
});
const wrapper = await mountView({ lifecycle_stage: 'fulfillment_prep' });
await wrapper.get('[data-testid="review-fulfillment-line-release-line-manual"]').trigger('click');
const dialog = wrapper.get('[data-testid="review-release-inventory-dialog"]');
await dialog.find('textarea').setValue('客户确认分批发货');
await dialog.find('input').setValue('A-01');
await dialog.get('button.bg-amber-600').trigger('click');
await wrapper.get('[data-testid="review-lifecycle-stage-fulfillment_prep"]').findAll('button')[1].trigger('click');
resolvePostReleaseTask?.(taskDetail());
await new Promise<void>((resolve) => setTimeout(resolve, 0));
await nextTick();
// 用户显式回看通知准备会消费本次自动推进许可,后端异步投影不得抢回焦点。
expect((wrapper.vm as { $route: { query: Record<string, string> } }).$route.query.lifecycle_stage)
.toBe('fulfillment_prep');
});
it('keeps the manual notice-generation entry in the main workspace for an editable formal task', async () => {
const taskApi = await import('@/features/chat/api/shipping.api');
reviewEditable.value = false;
@@ -193,7 +193,8 @@ const {
const msg = useMessage();
/**
* 右侧主卡阶段:优先 Progress 投影(与顶部同源);Case current_stage 仅降级。
* 右侧主卡阶段:优先 Progress 投影(与顶部同源);正式 OT 投影未到时用
* Case.current_stage(与投影同源 project_stage_for_task),建单前 automation 仅作降级。
* 无论哪一路都带 label_key,禁止把 code 当用户文案。
*/
const currentProcessingStageDisplay = computed(() => {
@@ -206,6 +207,19 @@ const currentProcessingStageDisplay = computed(() => {
inconsistent: false,
};
}
const caseStage = activeCase.value?.current_stage;
const caseCode = String(caseStage?.code || '').trim();
// 正式 OT 的 Case.current_stage 与统一投影同源(project_stage_for_task):
// 投影读取中(正式任务已存在、投影在途)也必须先展示真实阶段,
// 禁止被下方 automation 分支降级为“创建正式订单”自动建单阶段。
if (hasFormalOt.value && caseCode) {
return {
code: caseCode,
labelKey: caseStage?.label_key
|| (caseCode === 'order_creating' ? 'waiting_system_start' : caseCode),
inconsistent: Boolean(caseStage?.inconsistent),
};
}
// STP 建单前尚无正式 OT/processing projection;自动建单 Job 仍属于“创建正式订单”阶段。
const automationStatus = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
if (['queued', 'running', 'failed', 'manual_fallback'].includes(automationStatus)) {
@@ -215,12 +229,10 @@ const currentProcessingStageDisplay = computed(() => {
inconsistent: false,
};
}
const caseStage = activeCase.value?.current_stage;
const code = String(caseStage?.code || '').trim() || null;
return {
code,
code: caseCode || null,
labelKey: caseStage?.label_key
|| (code === 'order_creating' ? 'waiting_system_start' : code),
|| (caseCode === 'order_creating' ? 'waiting_system_start' : caseCode),
inconsistent: Boolean(caseStage?.inconsistent),
};
});
@@ -407,6 +419,34 @@ async function retryCurrentIntakeParse(): Promise<void> {
* 只切换前端工作面并同步可分享深链;禁止在导航点击中修改任何订单生命周期字段。
*/
const lifecycleStagePinnedByUserForCase = ref<string | null>(null);
/** 仅库存短缺放行可建立一次性自动推进许可,避免通用 Gate 恢复抢占用户导航。 */
const pendingReleaseAutoAdvanceCaseNo = ref<string | null>(null);
/**
* 消费库存短缺放行后的自动推进许可。
*
* 仅当同一 Case 仍停留在放行前的通知准备路由、用户未在放行后手动选阶段,且后端
* 权威投影已推进时替换深链。异步 Job 的首个投影可直接到目标阶段,不能依赖 watch
* 是否曾观察到旧阶段。
*/
async function syncPendingReleaseAutoAdvance(): Promise<boolean> {
const caseNo = String(activeCase.value?.case_no || '').trim();
if (!caseNo || pendingReleaseAutoAdvanceCaseNo.value !== caseNo) return false;
const requested = String(route.query.lifecycle_stage || '').trim();
if (
requested !== 'fulfillment_prep'
|| lifecycleStagePinnedByUserForCase.value === caseNo
) {
pendingReleaseAutoAdvanceCaseNo.value = null;
return false;
}
const current = lifecycleCurrentStageCode.value;
const currentIndex = current ? LIFECYCLE_STAGE_CODES.indexOf(current) : -1;
if (currentIndex <= LIFECYCLE_STAGE_CODES.indexOf('fulfillment_prep')) return false;
pendingReleaseAutoAdvanceCaseNo.value = null;
await selectLifecycleStage(current!, { replace: true });
return true;
}
async function selectLifecycleStage(code: ReviewLifecycleStageCode, options: { replace?: boolean } = {}) {
const target = lifecycleStageItems.value.find((item) => item.code === code);
@@ -414,7 +454,11 @@ async function selectLifecycleStage(code: ReviewLifecycleStageCode, options: { r
// 用户主动回看已完成阶段时,异步投影抵达不得将其强制带回当前阶段。
// 自动推进均使用 replace,不会写入该意图。
if (!options.replace) {
lifecycleStagePinnedByUserForCase.value = String(activeCase.value?.case_no || '').trim() || null;
const caseNo = String(activeCase.value?.case_no || '').trim() || null;
lifecycleStagePinnedByUserForCase.value = caseNo;
if (pendingReleaseAutoAdvanceCaseNo.value === caseNo) {
pendingReleaseAutoAdvanceCaseNo.value = null;
}
}
if (code === 'intake_parse' && intakeParseContextAuthorized.value && activeCase.value?.case_no) {
void ensureIntakeParseContextLoaded(activeCase.value.case_no);
@@ -472,7 +516,10 @@ watch(activeCase, (value) => {
watch(
() => String(activeCase.value?.case_no || '').trim(),
(caseNo, previousCaseNo) => {
if (caseNo !== previousCaseNo) lifecycleStagePinnedByUserForCase.value = null;
if (caseNo !== previousCaseNo) {
lifecycleStagePinnedByUserForCase.value = null;
pendingReleaseAutoAdvanceCaseNo.value = null;
}
},
);
@@ -628,7 +675,9 @@ const currentTaskPrimaryAction = computed(() => {
return null;
});
const currentTaskUserStatus = computed(() => {
if (formalTaskProjectionPending.value) return null;
// 已确认 OT 且权威投影在途时,先消费后端 automation 运行态(queued/running → running,
// failed/manual_fallback → failed),状态行即显真实值,不应退回「正在获取最新状态」骨架;
// authority 仍以右侧投影为准,投影到达后覆盖。
if (currentTaskUiState.value?.status) return currentTaskUiState.value.status;
// 建单前没有正式 OT 投影时,直接消费后端 Case automation 状态,避免页面看起来卡死。
const status = String(activeCase.value?.automation?.status || '').trim().toLowerCase();
@@ -1458,16 +1507,23 @@ async function retryFormalUploadRpa(taskNo: string) {
* 处理 Gate 恢复已被后端受理后的页面同步。
*
* 核心逻辑:恢复 Job 尚未完成时立即恢复用户交互,并重启五阶段轮询;三个只读投影
* 在后台刷新,避免把网络读取时间误表现为“恢复按钮卡住”。
* 在后台刷新,避免把网络读取时间误表现为“恢复按钮卡住”。库存短缺放行可额外建立
* 一次性自动推进许可,待后端生命周期投影确认后才更新深链。
*/
function handleGateRecoveryAccepted() {
function handleGateRecoveryAccepted(options: { releaseAutoAdvance?: boolean } = {}) {
const caseNo = String(activeCase.value?.case_no || '').trim();
if (options.releaseAutoAdvance && caseNo) {
// 放行前可能是用户手动进入通知准备;该历史意图不能阻止本次放行后的自动推进。
lifecycleStagePinnedByUserForCase.value = null;
pendingReleaseAutoAdvanceCaseNo.value = caseNo;
}
page.bumpWorkflowRefresh?.();
startWorkflowProgressPolling();
void Promise.allSettled([
loadFormalTaskDetail(),
reloadLatestDraft(),
refreshShippingProcessing(),
]);
]).then(() => { void syncPendingReleaseAutoAdvance(); });
}
/**
@@ -1998,6 +2054,48 @@ const lifecycleProgressReasonText = computed(() => {
if (!progress?.blocking_reason_i18n_key || !te(progress.blocking_reason_i18n_key)) return null;
return t(progress.blocking_reason_i18n_key);
});
/**
* Run 级进度横幅的统一展示消息。
*
* 核心逻辑:只有后端裁决 lifecycle_status == 'running' 才能声称「系统正在自动处理」;
* waiting(门禁待机)/ failed / cancelled 只展示等待/失败原因或步骤文本,禁止自动处理文案
* 与门禁状态自相矛盾;completed 时 Run 已无待办,横幅直接隐藏。
* 注意:后端仅在 running 下才有 current_step_i18n_key,因此旧逻辑在 waiting 时
* 会落入「系统正在自动处理」兜底文案,这正是本函数要消除的错误展示。
* 该横幅是「提取 Run(建单前流水线)」的运行提示,只在未有正式 OT 时展示
* (模板 v-if !hasFormalOt);正式 OT 后进度与操作指引由右栏当前任务卡承载。
*/
const lifecycleProgressMessage = computed<{
auto: boolean;
text: string;
reason: string | null;
} | null>(() => {
const progress = lifecycleProgressForView.value;
if (!progress) return null;
const status = String(progress.lifecycle_status || '').trim().toLowerCase();
const stepText = lifecycleProgressStepText.value;
const reasonText = lifecycleProgressReasonText.value;
if (status === 'running') {
return {
auto: true,
text: stepText || t('chat.shippingProcessing.progress.systemProcessingNeed'),
reason: reasonText,
};
}
if (status === 'completed') return null;
if (status === 'failed') {
return { auto: false, text: reasonText || t('chat.shippingProcessing.progress.lifecycleReason.failed'), reason: null };
}
if (status === 'cancelled') {
return { auto: false, text: reasonText || t('chat.shippingProcessing.progress.lifecycleReason.cancelled'), reason: null };
}
// waiting 或未知状态:绝不声称自动处理,优先展示后端原因,其次步骤文本。
return {
auto: false,
text: reasonText || stepText || t('chat.shippingProcessing.progress.lifecycleWaitingNeed'),
reason: null,
};
});
const lifecycleProgressActiveCode = computed<ReviewLifecycleStageCode | null>(() => {
const code = lifecycleProgressForView.value?.lifecycle_stage;
return LIFECYCLE_STAGE_CODES.includes(code as ReviewLifecycleStageCode)
@@ -2161,7 +2259,10 @@ const formalPreparationContext = computed(() => {
if (!fallbackLines.length) return preparation;
return {
...(preparation || {}),
status: preparation?.status || 'processing',
// [B1] 回退展示(任务详情未到、仅有 Case line_fulfillment)时不得伪造 status='processing':
// 那会让「processing → ready / blocked」看起来像二次刷新;真实状态由任务详情到达后显示,
// 徽章在状态为空时保持隐藏。
status: preparation?.status ?? null,
frozen_order: preparation?.frozen_order || {
task_no: confirmedNoticeTaskNo.value || null,
snapshot_id: null,
@@ -2274,7 +2375,7 @@ async function confirmReleaseInventoryShortage() {
// 放行写入成功即结束用户交互;Notice/Excel 由后端 Job 异步创建,不能让只读刷新
// 持续占用确认按钮。重启工作台轮询以立即接住新 Notice 的处理投影。
releaseInventoryBusy.value = false;
handleGateRecoveryAccepted();
handleGateRecoveryAccepted({ releaseAutoAdvance: true });
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
@@ -2356,8 +2457,11 @@ async function loadFormalTaskDetail() {
formalTaskDetailLoadFailed.value = false;
return;
}
// 请求在途期间不保留上一文件详情,生命周期导航会自然回退至当前 Case/实时 Projection。
formalTaskDetail.value = null;
// 仅任务切换时清空旧详情。同一任务的刷新若先清空,会让 lifecycle_stage 在
// freight_upload 与空值之间来回跳,进而触发工作面 watcher 的重复拉取循环。
if (formalTaskDetail.value?.task_no !== taskNo) {
formalTaskDetail.value = null;
}
formalTaskDetailLoadFailed.value = false;
formalTaskDetailLoading.value = true;
try {
@@ -2668,6 +2772,71 @@ function freightLineNoDisplay(line: { line_no?: string | number | null; line_no_
return { text: String(value), muted: false, title: '' };
}
/**
* 逐发货通知单的货代上传状态展示。
* 核心逻辑:upload_status 为后端事实;把 uploaded/uploading/failed/pending 映射为文案与色阶,
* 并携带 upload_error_code/upload_error_message 作为逐单失败原因。前端禁止按 upload_status 之外的状态猜原因,
* 未知状态一律回落 pending,避免把内部执行字段当作用户原因。
* @param group - 当前发货通知单聚合行(含 upload_status 与逐单错误字段)。
*/
function freightUploadStatusDisplay(group: ShippingFreightNoticeGroup): {
state: 'uploaded' | 'uploading' | 'failed' | 'needs_human' | 'pending';
label: string;
chipClass: string;
reason: string | null;
} {
const status = String(group.upload_status || '').trim().toLowerCase();
const pendingHuman = String(group.pending_human_reason || '').trim().toLowerCase();
const reason = group.upload_error_message || group.upload_error_code || null;
if (['uploaded', 'succeeded', 'success'].includes(status)) {
return {
state: 'uploaded',
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.uploaded'),
chipClass: 'bg-emerald-100 text-emerald-800 dark:bg-emerald-950/50 dark:text-emerald-200',
reason: null,
};
}
if (status === 'failed') {
return {
state: 'failed',
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.failed'),
chipClass: 'bg-rose-100 text-rose-700 dark:bg-rose-950/50 dark:text-rose-300',
reason: reason ? t('chat.shippingOrderReview.lifecycle.freightUpload.uploadError', { reason }) : null,
};
}
// 存在错误码但状态未置 failed(如超时/结果未知):按“需人工”展示并始终带出逐单原因。
if (reason) {
return {
state: 'needs_human',
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.needsHuman'),
chipClass: 'bg-amber-100 text-amber-800 dark:bg-amber-950/50 dark:text-amber-200',
reason: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadError', { reason }),
};
}
if (['uploading', 'upload_rpa_pending'].includes(status) || pendingHuman === 'upload_rpa_pending') {
return {
state: 'uploading',
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.uploading'),
chipClass: 'bg-blue-100 text-blue-800 dark:bg-blue-950/50 dark:text-blue-200',
reason: null,
};
}
if (pendingHuman) {
return {
state: 'needs_human',
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.needsHuman'),
chipClass: 'bg-amber-100 text-amber-800 dark:bg-amber-950/50 dark:text-amber-200',
reason: reason ? t('chat.shippingOrderReview.lifecycle.freightUpload.uploadError', { reason }) : null,
};
}
return {
state: 'pending',
label: t('chat.shippingOrderReview.lifecycle.freightUpload.uploadStatus.pending'),
chipClass: 'bg-slate-100 text-slate-600 dark:bg-slate-800/60 dark:text-slate-300',
reason: null,
};
}
async function confirmPreparationWave() {
const caseNo = String(activeCase.value?.case_no || '').trim();
const draftVersion = activeCase.value?.draft?.draft_version;
@@ -3666,6 +3835,7 @@ watch(
watch(
lifecycleCurrentStageCode,
async (current, previous) => {
if (await syncPendingReleaseAutoAdvance()) return;
if (!current || !previous || current === previous) return;
// 只响应后端 current 阶段的真实推进:用户点击已完成阶段只会改路由,
// 绝不能触发自动跳转而被带回当前阶段。
@@ -3891,15 +4061,18 @@ watch(
@retry-parse="() => void retryCurrentIntakeParse()"
/>
<p
v-if="lifecycleProgressForView"
v-if="lifecycleProgressMessage && !hasFormalOt"
class="mt-2 rounded-md border-l-2 border-brand-500 bg-surface-soft px-2.5 py-1.5 text-xs text-secondary"
data-testid="review-run-lifecycle-current-step"
aria-live="polite"
>
<span class="mr-1 inline-block h-2 w-2 animate-pulse rounded-full bg-brand-500" aria-hidden="true" />
<span v-if="lifecycleProgressStepText">{{ lifecycleProgressStepText }}</span>
<span v-else>{{ t('chat.shippingProcessing.progress.systemProcessingNeed') }}</span>
<span v-if="lifecycleProgressReasonText" class="ml-1 text-warning">· {{ lifecycleProgressReasonText }}</span>
<span
v-if="lifecycleProgressMessage.auto"
class="mr-1 inline-block h-2 w-2 animate-pulse rounded-full bg-brand-500"
aria-hidden="true"
/>
<span>{{ lifecycleProgressMessage.text }}</span>
<span v-if="lifecycleProgressMessage.reason" class="ml-1 text-warning">· {{ lifecycleProgressMessage.reason }}</span>
</p>
</section>
</div>
@@ -4038,9 +4211,10 @@ watch(
<h3 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.prepare.title') }}</h3>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.prepare.subtitle') }}</p>
</div>
<span class="rounded-full bg-brand-50 px-2.5 py-1 text-xs font-medium text-brand-700 dark:bg-brand-950/30 dark:text-brand-300">
{{ formalPreparationContext.status || '-' }}
</span>
<span
v-if="formalPreparationContext.status"
class="rounded-full bg-brand-50 px-2.5 py-1 text-xs font-medium text-brand-700 dark:bg-brand-950/30 dark:text-brand-300"
>{{ formalPreparationContext.status }}</span>
</div>
<div v-if="formalPreparationContext.has_match_result && formalPreparationLines.length" class="review-fulfillment-prep-workspace mt-4 overflow-x-auto rounded-lg border border-default" data-testid="review-fulfillment-prep-workspace">
<div class="flex items-center justify-between gap-3 border-b border-default bg-surface-muted/30 px-3 py-2">
@@ -4100,15 +4274,7 @@ watch(
<h2 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.title') }}</h2>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.subtitle') }}</p>
</div>
<span class="rounded-full bg-surface-muted px-2 py-1 text-xs text-secondary">{{ formalTaskDetail.upload_status || '-' }}</span>
</div>
<div
v-if="formalTaskDetail.ui_state?.stage_context?.upload?.latest_attempt || formalTaskDetail.ui_state?.stage_context?.upload?.latest_attempt?.error_code"
class="mt-3 rounded-lg border border-default bg-surface-muted/50 p-3 text-xs text-secondary"
data-testid="review-upload-attempt-summary"
>
<p v-if="formalTaskDetail.ui_state?.stage_context?.upload?.latest_attempt" class="mt-1">{{ t('chat.shippingOrderReview.lifecycle.upload.attempt', { status: formalTaskDetail.ui_state.stage_context.upload.latest_attempt.status || '-', mode: formalTaskDetail.ui_state.stage_context.upload.latest_attempt.mode || '-' }) }}</p>
<p v-if="formalTaskDetail.ui_state?.stage_context?.upload?.latest_attempt?.error_code" class="mt-1 text-rose-700 dark:text-rose-300">{{ formalTaskDetail.ui_state.stage_context.upload.latest_attempt.error_code }}</p>
<span class="rounded-full bg-surface-muted px-2 py-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.noticeCount', { count: freightNoticeGroups.length }) }}</span>
</div>
<div v-if="freightNoticeGroupsLoading" class="mt-3 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.loading') }}</div>
<p v-else-if="freightNoticeGroupsLoadFailed" class="mt-3 rounded-lg border border-rose-200 bg-rose-50/70 p-3 text-xs text-rose-700 dark:border-rose-900 dark:bg-rose-950/20 dark:text-rose-200">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.loadFailed') }}</p>
@@ -4120,8 +4286,9 @@ watch(
<div v-for="group in freightNoticeGroups" :key="group.business_no" class="rounded-lg border border-default" data-testid="review-freight-upload-notice">
<div class="flex flex-wrap items-center justify-between gap-3 border-b border-default bg-surface-muted/40 px-3 py-2 text-xs">
<label class="flex items-center gap-2 font-semibold text-primary"><input type="checkbox" :checked="selectedFreightBusinessNos.includes(group.business_no)" :aria-label="group.business_no" @change="toggleFreightNoticeSelection(group.business_no, ($event.target as HTMLInputElement).checked)"><span>{{ group.business_no }}</span></label>
<span class="text-secondary">PO: {{ group.po_number || '—' }} · {{ group.upload_status || '—' }} · {{ group.export_file_name || '—' }}</span>
<span class="text-secondary">PO: {{ group.po_number || '—' }} · {{ group.export_file_name || '—' }}</span>
<div class="flex items-center gap-2">
<span :class="freightUploadStatusDisplay(group).chipClass" class="rounded-full px-2 py-0.5 font-medium">{{ freightUploadStatusDisplay(group).label }}</span>
<button type="button" class="rounded border border-brand-200 px-2 py-1 font-medium text-brand-700 hover:bg-brand-50" data-testid="review-freight-upload-download" :disabled="saving" @click="void downloadFreightNotice(group.business_no)">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.download') }}</button>
<details class="relative">
<summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" aria-hidden="true" /></summary>
@@ -4133,6 +4300,7 @@ watch(
</details>
</div>
</div>
<div v-if="freightUploadStatusDisplay(group).reason" class="border-b border-default bg-rose-50/50 px-3 py-2 text-xs text-rose-700 dark:bg-rose-950/10 dark:text-rose-300" data-testid="review-freight-upload-error">{{ freightUploadStatusDisplay(group).reason }}</div>
<table class="min-w-full text-left text-xs"><thead class="border-b border-default bg-surface-muted/30"><tr><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.lineNo') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th></tr></thead><tbody><tr v-for="line in group.lines" :key="`${group.business_no}-${line.line_no}-${line.part_number}`" class="border-b border-default last:border-0" data-testid="review-freight-upload-line"><td class="px-3 py-2"><span :class="freightLineNoDisplay(line).muted ? 'text-muted' : ''" :title="freightLineNoDisplay(line).title">{{ freightLineNoDisplay(line).text }}</span></td><td class="px-3 py-2">{{ line.part_number || '—' }}</td><td class="px-3 py-2">{{ line.reservation_id || '—' }}</td><td class="px-3 py-2">{{ line.shipment_qty || '—' }}</td></tr></tbody></table>
</div>
</div>
+17
View File
@@ -992,6 +992,23 @@
"failed": "Test failed"
},
"connectionBoundary": "Enter only the login information here. The system handles the required page actions, downloads, and waiting for the selected freight platform.",
"uploadConfigTitle": "Shipping Excel Auto Upload",
"uploadConfigHint": "Edited from this System Connection and stored as a restricted JSON. No free JavaScript, scripts, URL templates, cookies, or arbitrary browser actions are allowed.",
"uploadAutoEnabled": "Enable auto-upload (admin has reviewed this connection's upload behavior)",
"uploadEntryUrl": "Upload entry URL",
"uploadFileSelector": "File input selector",
"uploadSubmitMode": "Submit mode",
"uploadSubmitAuto": "Auto submit after file",
"uploadSubmitClick": "Click submit button",
"uploadSubmitSelector": "Submit button selector",
"uploadResultMode": "Result determination mode",
"uploadResultPageNotice": "Page notice",
"uploadResultHistory": "Upload history",
"uploadResultSelector": "Result selector",
"uploadSuccessTexts": "Success texts (one per line)",
"uploadSuccessTextsHint": "Matching any success text marks success",
"uploadTimeout": "Timeout (seconds)",
"uploadConfigBoundary": "Upload config changes do not increment the inventory RPA config_version; used only for this connection's freight upload, not propagated to inventory/receipt RPA.",
"platform": {
"dbs": "DBS",
"crane": "Crane"
+3 -2
View File
@@ -1485,7 +1485,7 @@
"descriptions": {"intake_parse": "Review the email body and current attachment, then resolve intake parsing issues.", "order_review": "Verify fields and evidence, resolve conflicts, and freeze the order.", "fulfillment_prep": "Complete inventory matching and generate the notice Excel.", "freight_upload": "Download the notice, run RPA or register a manual upload, and reconcile unknown results.", "upload_complete": "Shown only after complete upload-success evidence is verified."},
"intakeParse": {"title": "Intake and parsing", "email": "Email body", "emailPreviewTitle": "Safe email body preview", "noEmail": "No email context", "attachment": "Current attachment", "fileName": "File name", "fileType": "File type", "preview": "Attachment preview", "previewLoading": "Loading attachment preview…", "loadPreview": "Load attachment preview", "previewUnsupported": "The current attachment is not a PDF and cannot be previewed here.", "loading": "Loading intake parsing context…", "loadFailed": "Failed to load intake parsing context.", "retry": "Retry"},
"prepare": {"title": "Notice preparation", "subtitle": "Handle inventory candidates, matching issues, and notice generation here.", "frozenOrder": "Frozen order", "inventorySource": "Inventory source", "excel": "Shipping Excel", "downloadInventory": "Download inventory file", "retryInventory": "Re-fetch inventory", "releaseShortage": "Release shortage", "releaseShortageHint": "Release allows shipping Excel generation. State the reason for this shortage release.", "releaseReasonPlaceholder": "Enter release reason (required)", "releaseConfirm": "Confirm release", "requiredQty": "Required quantity", "matchWorkspace": "Inventory matching", "lineCount": "{count} inventory results", "lineStatus": "Match status", "matched": "Matched", "shortage": "Inventory shortage", "matchStatus": {"not_found": "Inventory not found", "preparing": "Preparing inventory", "mapping_failed": "Inventory mapping failed", "unavailable": "Inventory unavailable", "source_conflict": "Inventory source conflict", "invalid_key": "Invalid match key", "result_missing": "Awaiting match result", "unknown": "Unknown status"}, "pending": "Inventory matching or the shipping file is not ready yet. Use the current processing card to continue.", "loadFailed": "Failed to load notice preparation details; current data could not be confirmed.", "detailUnavailable": "Notice preparation details have not returned yet, so frozen order and inventory matching data cannot be shown.", "retry": "Reload"},
"freightUpload": {"title": "Freight upload", "subtitle": "Grouped by shipping notice; each shipping notice has one Excel.", "loading": "Loading shipping notices…", "loadFailed": "Failed to load shipping notices. Refresh and try again.", "poMissing": "The current task has no recognized PO, so notices cannot be grouped yet.", "empty": "No uploadable shipping notices for this PO.", "download": "Download Excel", "lineNo": "Line", "lineNoSourceCustomerPo": "Customer PO line no.", "lineNoSourceSequence": "System sequence (internal line no. not recognized)", "selected": "{count} notices selected", "batchDownload": "Download selected", "batchRpa": "Batch RPA upload", "batchConfirm": "Confirm selected uploaded"},
"freightUpload": {"title": "Freight upload", "subtitle": "Grouped by shipping notice; each shipping notice has one Excel.", "loading": "Loading shipping notices…", "loadFailed": "Failed to load shipping notices. Refresh and try again.", "poMissing": "The current task has no recognized PO, so notices cannot be grouped yet.", "empty": "No uploadable shipping notices for this PO.", "download": "Download Excel", "lineNo": "Line", "lineNoSourceCustomerPo": "Customer PO line no.", "lineNoSourceSequence": "System sequence (internal line no. not recognized)", "selected": "{count} notices selected", "batchDownload": "Download selected", "batchRpa": "Batch RPA upload", "batchConfirm": "Confirm selected uploaded", "noticeCount": "{count} shipping notice(s)", "uploadError": "Upload error reason: {reason}", "uploadStatus": {"pending": "Pending upload", "uploading": "Uploading", "failed": "Upload failed", "uploaded": "Uploaded", "needsHuman": "Manual upload needed"}},
"uploadComplete": {"title": "Notification completion", "subtitle": "Upload-success evidence is verified. This view is read only.", "batchCount": "{count} shipping notice(s) uploaded in this batch", "batchDownload": "Download batch ZIP", "batchDownloading": "Packaging…", "uploaded": "Uploaded", "uploadedAt": "{time}", "exportFile": "File: {file}", "expand": "Show line details", "collapse": "Hide line details", "uploadMode": "Upload method: {mode}", "uploadModeManual": "Manual confirmation", "uploadModeRpa": "RPA upload", "empty": "No uploaded shipping notices in this batch."},
"upload": {"title": "Freight upload", "subtitle": "Download the notice Excel, upload it on the freight platform and confirm the manual upload, or run RPA.", "manualUpload": "Confirm manual upload", "attempt": "Latest upload attempt: {mode} · {status}"},
"stages": {
@@ -2218,7 +2218,7 @@
"adminDiagnosisStatus": "Status: task_missing",
"adminDiagnosisHint": "Use task audit / data repair. This page does not auto-recover.",
"stateInconsistent": "State syncing / inconsistent state data",
"stageLoading": "Updating status…",
"stageLoading": "Fetching latest status…",
"statusRunning": "System processing",
"statusFailedRetryable": "Failed — retry available",
"statusCompleted": "Completed",
@@ -2740,6 +2740,7 @@
"domainFulfillmentShip": "Fulfillment",
"currentNeedLabel": "Current need: ",
"systemProcessingNeed": "The system is processing automatically. Wait or refresh progress.",
"lifecycleWaitingNeed": "The current step requires manual handling",
"progressTitleWithStage": "Order processing · {stage}",
"systemProcessingWithStage": "System processing · {stage}",
"viewProcessDetails": "View process details",
+17
View File
@@ -992,6 +992,23 @@
"failed": "ทดสอบล้มเหลว"
},
"connectionBoundary": "กรอกเฉพาะข้อมูลเข้าสู่ระบบ ระบบจะดำเนินการหน้าเว็บ ดาวน์โหลด และรอตามแพลตฟอร์มผู้ให้บริการที่เลือกโดยอัตโนมัติ",
"uploadConfigTitle": "อัปโหลด Excel การจัดส่งอัตโนมัติ",
"uploadConfigHint": "แก้ไขจากหน้าการเชื่อมต่อระบบนี้และบันทึกเป็น JSON แบบจำกัด; ห้ามใช้ JavaScript/สคริปต์/URL template/Cookie หรือการกระทำเบราว์เซอร์โดยอิสระ",
"uploadAutoEnabled": "เปิดใช้งานอัปโหลดอัตโนมัติ (ผู้ดูแลตรวจสอบพฤติกรรมการอัปโหลดของการเชื่อมต่อนี้แล้ว)",
"uploadEntryUrl": "URL หน้าอัปโหลด",
"uploadFileSelector": "ตัวเลือกไฟล์ (selector)",
"uploadSubmitMode": "โหมดส่ง",
"uploadSubmitAuto": "ส่งอัตโนมัติหลังเลือกไฟล์",
"uploadSubmitClick": "คลิกปุ่มส่ง",
"uploadSubmitSelector": "ตัวเลือกปุ่มส่ง",
"uploadResultMode": "โหมดตรวจสอบผล",
"uploadResultPageNotice": "ข้อความแจ้งบนหน้า",
"uploadResultHistory": "ประวัติการอัปโหลด",
"uploadResultSelector": "ตัวเลือกผลลัพธ์",
"uploadSuccessTexts": "ข้อความสำเร็จ (หนึ่งรายการต่อบรรทัด)",
"uploadSuccessTextsHint": "หากตรงกับข้อความสำเร็จข้อใดข้อหนึ่งถือว่าสำเร็จ",
"uploadTimeout": "ระยะเวลารอ (วินาที)",
"uploadConfigBoundary": "การเปลี่ยนค่าอัปโหลดไม่เพิ่ม config_version ของ RPA คลัง; ใช้เฉพาะการอัปโหลดของสายการขนส่งนี้เท่านั้น ไม่แพร่ไปยัง RPA คลัง/รับของ",
"platform": {
"dbs": "DBS",
"crane": "Crane"
+3 -2
View File
@@ -1485,7 +1485,7 @@
"descriptions": {"intake_parse": "ตรวจสอบเนื้อหาอีเมลและไฟล์แนบปัจจุบัน แล้วจัดการปัญหาการแยกวิเคราะห์ขาเข้า", "order_review": "ตรวจสอบข้อมูลและหลักฐาน แก้ข้อขัดแย้ง และตรึงคำสั่งซื้อ", "fulfillment_prep": "จับคู่สต็อกและสร้าง Excel แจ้งงาน", "freight_upload": "ดาวน์โหลดไฟล์แจ้งงาน รัน RPA หรือลงทะเบียนการอัปโหลดด้วยตนเอง และตรวจสอบผลลัพธ์ที่ไม่ทราบ", "upload_complete": "แสดงเมื่อยืนยันหลักฐานความสำเร็จของการอัปโหลดครบถ้วนแล้วเท่านั้น"},
"intakeParse": {"title": "รับและแยกวิเคราะห์", "email": "เนื้อหาอีเมล", "emailPreviewTitle": "ตัวอย่างเนื้อหาอีเมลแบบปลอดภัย", "noEmail": "ไม่มีบริบทอีเมล", "attachment": "ไฟล์แนบปัจจุบัน", "fileName": "ชื่อไฟล์", "fileType": "ประเภทไฟล์", "preview": "ตัวอย่างไฟล์แนบ", "previewLoading": "กำลังโหลดตัวอย่างไฟล์แนบ…", "loadPreview": "โหลดตัวอย่างไฟล์แนบ", "previewUnsupported": "ไฟล์แนบปัจจุบันไม่ใช่ PDF และไม่สามารถแสดงตัวอย่างที่นี่ได้", "loading": "กำลังโหลดบริบทการแยกวิเคราะห์ขาเข้า…", "loadFailed": "โหลดบริบทการแยกวิเคราะห์ขาเข้าไม่สำเร็จ", "retry": "ลองอีกครั้ง"},
"prepare": {"title": "เตรียมการแจ้ง", "subtitle": "จัดการตัวเลือกสต็อก ปัญหาการจับคู่ และการสร้างไฟล์แจ้งงานที่นี่", "frozenOrder": "คำสั่งซื้อที่ตรึงแล้ว", "inventorySource": "แหล่งสต็อก", "excel": "Excel การจัดส่ง", "downloadInventory": "ดาวน์โหลดไฟล์สินค้าคงคลัง", "retryInventory": "ดึงข้อมูลสต็อกอีกครั้ง", "releaseShortage": "อนุมัติส่วนขาดสต็อก", "releaseShortageHint": "การอนุมัติทำให้สร้าง Excel การจัดส่งได้ โปรดระบุเหตุผลสำหรับส่วนขาดนี้", "releaseReasonPlaceholder": "กรอกเหตุผลการอนุมัติ (จำเป็น)", "releaseConfirm": "ยืนยันการอนุมัติ", "requiredQty": "จำนวนที่ต้องการ", "matchWorkspace": "การจับคู่สต็อก", "lineCount": "ผลลัพธ์สต็อก {count} รายการ", "lineStatus": "สถานะการจับคู่", "matched": "จับคู่แล้ว", "shortage": "สต็อกไม่เพียงพอ", "matchStatus": {"not_found": "ไม่พบสต็อก", "preparing": "กำลังเตรียมสต็อก", "mapping_failed": "จับคู่ฟิลด์สต็อกไม่สำเร็จ", "unavailable": "สต็อกไม่พร้อมใช้", "source_conflict": "แหล่งสต็อกขัดแย้ง", "invalid_key": "คีย์จับคู่ไม่ถูกต้อง", "result_missing": "กำลังรอผลการจับคู่", "unknown": "ไม่ทราบสถานะ"}, "pending": "การจับคู่สต็อกหรือไฟล์แจ้งการจัดส่งยังไม่พร้อม โปรดดำเนินการจากบัตรงานปัจจุบัน", "loadFailed": "โหลดรายละเอียดการเตรียมการแจ้งไม่สำเร็จ จึงยังยืนยันข้อมูลปัจจุบันไม่ได้", "detailUnavailable": "ยังไม่ได้รับรายละเอียดการเตรียมการแจ้ง จึงยังแสดงคำสั่งซื้อที่ตรึงและข้อมูลการจับคู่สต็อกไม่ได้", "retry": "โหลดอีกครั้ง"},
"freightUpload": {"title": "อัปโหลดให้ผู้ให้บริการขนส่ง", "subtitle": "จัดกลุ่มตามใบแจ้งส่งสินค้า; แต่ละใบแจ้งส่งสินค้ามี Excel หนึ่งไฟล์", "loading": "กำลังโหลดใบแจ้งส่งสินค้า…", "loadFailed": "โหลดใบแจ้งส่งสินค้าไม่สำเร็จ โปรดลองรีเฟรช", "poMissing": "งานปัจจุบันยังไม่พบ PO จึงยังจัดกลุ่มใบแจ้งส่งสินค้าไม่ได้", "empty": "ไม่มีใบแจ้งส่งสินค้าที่อัปโหลดได้สำหรับ PO นี้", "download": "ดาวน์โหลด Excel", "lineNo": "รายการ", "lineNoSourceCustomerPo": "เลขบรรทัด PO ของลูกค้า", "lineNoSourceSequence": "ลำดับระบบ (ไม่พบเลขรายการภายใน)", "selected": "เลือกแล้ว {count} ใบแจ้งส่งสินค้า", "batchDownload": "ดาวน์โหลดที่เลือก", "batchRpa": "อัปโหลด RPA แบบกลุ่ม", "batchConfirm": "ยืนยันว่าอัปโหลดแล้ว"},
"freightUpload": {"title": "อัปโหลดให้ผู้ให้บริการขนส่ง", "subtitle": "จัดกลุ่มตามใบแจ้งส่งสินค้า; แต่ละใบแจ้งส่งสินค้ามี Excel หนึ่งไฟล์", "loading": "กำลังโหลดใบแจ้งส่งสินค้า…", "loadFailed": "โหลดใบแจ้งส่งสินค้าไม่สำเร็จ โปรดลองรีเฟรช", "poMissing": "งานปัจจุบันยังไม่พบ PO จึงยังจัดกลุ่มใบแจ้งส่งสินค้าไม่ได้", "empty": "ไม่มีใบแจ้งส่งสินค้าที่อัปโหลดได้สำหรับ PO นี้", "download": "ดาวน์โหลด Excel", "lineNo": "รายการ", "lineNoSourceCustomerPo": "เลขบรรทัด PO ของลูกค้า", "lineNoSourceSequence": "ลำดับระบบ (ไม่พบเลขรายการภายใน)", "selected": "เลือกแล้ว {count} ใบแจ้งส่งสินค้า", "batchDownload": "ดาวน์โหลดที่เลือก", "batchRpa": "อัปโหลด RPA แบบกลุ่ม", "batchConfirm": "ยืนยันว่าอัปโหลดแล้ว", "noticeCount": "รวม {count} ใบแจ้งส่งสินค้า", "uploadError": "สาเหตุการอัปโหลดล้มเหลว: {reason}", "uploadStatus": {"pending": "รออัปโหลด", "uploading": "กำลังอัปโหลด", "failed": "อัปโหลดล้มเหลว", "uploaded": "อัปโหลดแล้ว", "needsHuman": "ต้องอัปโหลดด้วยตนเอง"}},
"uploadComplete": {"title": "แจ้งเสร็จสิ้น", "subtitle": "ยืนยันหลักฐานความสำเร็จของการอัปโหลดแล้ว หน้านี้อ่านได้อย่างเดียว", "batchCount": "ชุดนี้ได้อัปโหลดใบแจ้งส่งสินค้าแล้ว {count} ใบ", "batchDownload": "ดาวน์โหลด ZIP ทั้งชุด", "batchDownloading": "กำลังแพ็ก…", "uploaded": "อัปโหลดแล้ว", "uploadedAt": "{time}", "exportFile": "ไฟล์: {file}", "expand": "แสดงรายละเอียด", "collapse": "ซ่อนรายละเอียด", "uploadMode": "วิธีอัปโหลด: {mode}", "uploadModeManual": "ยืนยันด้วยตนเอง", "uploadModeRpa": "อัปโหลด RPA", "empty": "ชุดนี้ยังไม่มีใบแจ้งส่งสินค้าที่อัปโหลดแล้ว"},
"upload": {"title": "อัปโหลดให้ผู้ให้บริการขนส่ง", "subtitle": "ดาวน์โหลด Excel แจ้งงาน อัปโหลดบนแพลตฟอร์มขนส่งแล้วยืนยันการอัปโหลดด้วยตนเอง หรือรัน RPA", "manualUpload": "ยืนยันการอัปโหลดด้วยตนเอง", "attempt": "ความพยายามอัปโหลดล่าสุด: {mode} · {status}"},
"stages": {
@@ -2218,7 +2218,7 @@
"adminDiagnosisStatus": "สถานะ: task_missing",
"adminDiagnosisHint": "ใช้การตรวจสอบงาน/ซ่อมข้อมูล ไม่กู้คืนอัตโนมัติในหน้านี้",
"stateInconsistent": "กำลังซิงก์สถานะ / ข้อมูลไม่สอดคล้อง",
"stageLoading": "กำลังอัปเดตสถานะ…",
"stageLoading": "กำลังโหลดสถานะล่าสุด…",
"statusRunning": "ระบบกำลังประมวลผล",
"statusFailedRetryable": "ล้มเหลว — ลองใหม่ได้",
"statusCompleted": "เสร็จสิ้น",
@@ -2740,6 +2740,7 @@
"domainFulfillmentShip": "จัดส่ง",
"currentNeedLabel": "ความต้องการปัจจุบัน: ",
"systemProcessingNeed": "ระบบกำลังประมวลผลอัตโนมัติ รอสักครู่หรือรีเฟรชความคืบหน้า",
"lifecycleWaitingNeed": "ขั้นตอนปัจจุบันต้องดำเนินการด้วยตนเอง",
"progressTitleWithStage": "ความคืบหน้าการประมวลผลคำสั่ง · {stage}",
"systemProcessingWithStage": "ระบบกำลังประมวลผล · {stage}",
"viewProcessDetails": "ดูรายละเอียดกระบวนการ",
+17
View File
@@ -1120,6 +1120,23 @@
"failed": "测试失败"
},
"connectionBoundary": "连接配置只填写登录所需信息;系统会按货代平台自动执行页面操作、下载和等待。",
"uploadConfigTitle": "发货 Excel 自动上传",
"uploadConfigHint": "该配置由系统连接管理端编辑,后端保存为受限 JSON;禁止自由 JavaScript、脚本、URL 模板、Cookie 或任意浏览器动作。",
"uploadAutoEnabled": "启用自动上传(代表管理员已审核该连接的上传行为)",
"uploadEntryUrl": "上传入口 URL",
"uploadFileSelector": "文件选择器",
"uploadSubmitMode": "提交方式",
"uploadSubmitAuto": "选择文件后自动提交",
"uploadSubmitClick": "点击提交按钮",
"uploadSubmitSelector": "提交按钮选择器",
"uploadResultMode": "成功判定方式",
"uploadResultPageNotice": "页面提示",
"uploadResultHistory": "上传历史记录",
"uploadResultSelector": "结果选择器",
"uploadSuccessTexts": "成功文本(每行一条)",
"uploadSuccessTextsHint": "命中任一条成功文本即判定成功",
"uploadTimeout": "超时时间(秒)",
"uploadConfigBoundary": "上传配置变更不递增库存 RPA config_version;仅该连接的货代上传使用,不向库存/收料 RPA 扩散。",
"platform": {
"dbs": "DBS 平台",
"crane": "Crane 平台"
+3 -2
View File
@@ -1592,7 +1592,7 @@
"descriptions": {"intake_parse": "核对邮件正文和当前附件,处置接收解析异常。", "order_review": "核实字段和证据,处理冲突并冻结订单。", "fulfillment_prep": "完成库存匹配并生成通知 Excel。", "freight_upload": "下载通知文件、执行 RPA 或登记人工上传,并核对未知结果。", "upload_complete": "仅在上传成功证据完整时展示通知完成。"},
"intakeParse": {"title": "接收解析", "email": "邮件正文", "emailPreviewTitle": "邮件正文安全预览", "noEmail": "无邮件上下文", "attachment": "当前附件", "fileName": "文件名", "fileType": "文件类型", "preview": "附件预览", "previewLoading": "正在加载附件预览…", "loadPreview": "加载附件预览", "previewUnsupported": "当前附件不是 PDF,不能在此预览。", "loading": "正在加载接收解析上下文…", "loadFailed": "接收解析上下文加载失败。", "retry": "重试"},
"prepare": {"title": "通知准备", "subtitle": "库存候选、匹配异常和通知文件生成均在此阶段处理。", "frozenOrder": "冻结订单", "inventorySource": "库存源", "excel": "通知 Excel", "downloadInventory": "下载库存文件", "retryInventory": "重新获取库存", "releaseShortage": "库存缺口放行", "releaseShortageHint": "放行后可生成发货 Excel;请填写本次缺口放行原因。", "releaseReasonPlaceholder": "请输入放行原因(必填)", "releaseConfirm": "确认放行", "requiredQty": "需求数量", "matchWorkspace": "库存匹配", "lineCount": "{count} 行库存结果", "lineStatus": "匹配状态", "matched": "已匹配", "shortage": "库存不足", "matchStatus": {"not_found": "未匹配到库存", "preparing": "库存准备中", "mapping_failed": "库存映射失败", "unavailable": "库存不可用", "source_conflict": "库存源冲突", "invalid_key": "匹配键无效", "result_missing": "等待匹配结果", "unknown": "状态未知"}, "pending": "库存匹配或通知文件尚未生成。请查看右侧当前处理,按当前门禁继续。", "loadFailed": "通知准备任务详情加载失败,当前数据未能确认。", "detailUnavailable": "通知准备任务详情尚未返回,暂时无法展示冻结订单和库存匹配数据。", "retry": "重新加载"},
"freightUpload": {"title": "货代上传", "subtitle": "按发货通知单聚合展示;每张发货通知单对应一张 Excel。", "loading": "正在加载发货通知…", "loadFailed": "发货通知加载失败,请刷新后重试。", "poMissing": "当前任务尚未识别到 PO,暂时无法聚合发货通知。", "empty": "当前 PO 暂无可上传的发货通知。", "download": "下载 Excel", "lineNo": "项次", "lineNoSourceCustomerPo": "客户 PO 行号", "lineNoSourceSequence": "系统行序(未识别到内部项次)", "selected": "已选 {count} 个发货通知", "batchDownload": "批量下载", "batchRpa": "批量 RPA 上传", "batchConfirm": "批量确认已上传"},
"freightUpload": {"title": "货代上传", "subtitle": "按发货通知单聚合展示;每张发货通知单对应一张 Excel。", "loading": "正在加载发货通知…", "loadFailed": "发货通知加载失败,请刷新后重试。", "poMissing": "当前任务尚未识别到 PO,暂时无法聚合发货通知。", "empty": "当前 PO 暂无可上传的发货通知。", "download": "下载 Excel", "lineNo": "项次", "lineNoSourceCustomerPo": "客户 PO 行号", "lineNoSourceSequence": "系统行序(未识别到内部项次)", "selected": "已选 {count} 个发货通知", "batchDownload": "批量下载", "batchRpa": "批量 RPA 上传", "batchConfirm": "批量确认已上传", "noticeCount": "共 {count} 张发货通知", "uploadError": "上传失败原因:{reason}", "uploadStatus": {"pending": "待上传", "uploading": "上传中", "failed": "上传失败", "uploaded": "已上传", "needsHuman": "需人工上传"}},
"uploadComplete": {"title": "通知完成", "subtitle": "上传成功证据已核验,以下内容仅供查看。", "batchCount": "本批已上传 {count} 张发货通知", "batchDownload": "下载本批 ZIP", "batchDownloading": "正在打包…", "uploaded": "已上传", "uploadedAt": "{time}", "exportFile": "文件:{file}", "expand": "展开明细", "collapse": "收起明细", "uploadMode": "上传方式:{mode}", "uploadModeManual": "人工确认", "uploadModeRpa": "RPA 上传", "empty": "本批暂无已上传的发货通知。"},
"upload": {"title": "货代上传", "subtitle": "下载已生成的通知 Excel,上传至货代平台后确认人工上传,或执行 RPA。", "manualUpload": "确认人工上传", "attempt": "最近上传尝试:{mode} · {status}"},
"stages": {
@@ -2337,7 +2337,7 @@
"adminDiagnosisStatus": "状态:task_missing",
"adminDiagnosisHint": "请通过任务审计/数据修复流程处理;本页不提供自动恢复。",
"stateInconsistent": "状态同步中 / 状态数据不一致",
"stageLoading": "正在更新状态…",
"stageLoading": "正在获取最新状态…",
"statusRunning": "系统处理中",
"statusFailedRetryable": "失败可重试",
"statusCompleted": "已完成",
@@ -2814,6 +2814,7 @@
"domainFulfillmentShip": "发货履约",
"currentNeedLabel": "当前需要:",
"systemProcessingNeed": "系统正在自动处理,请稍候或刷新进度",
"lifecycleWaitingNeed": "当前步骤需要人工处理",
"progressTitleWithStage": "订单处理进度 · {stage}",
"systemProcessingWithStage": "系统处理中 · {stage}",
"viewProcessDetails": "查看流程详情",
+17
View File
@@ -992,6 +992,23 @@
"failed": "測試失敗"
},
"connectionBoundary": "連線設定只填寫登入所需資訊;系統會依貨代平台自動執行頁面操作、下載與等待。",
"uploadConfigTitle": "發貨 Excel 自動上傳",
"uploadConfigHint": "本設定由系統連線管理端編輯,後端儲存為受限 JSON;禁止自由 JavaScript、腳本、URL 範本、Cookie 或任意瀏覽器動作。",
"uploadAutoEnabled": "啟用自動上傳(代表管理員已審核該連線的上傳行為)",
"uploadEntryUrl": "上傳入口 URL",
"uploadFileSelector": "檔案選擇器",
"uploadSubmitMode": "提交方式",
"uploadSubmitAuto": "選擇檔案後自動提交",
"uploadSubmitClick": "點擊提交按鈕",
"uploadSubmitSelector": "提交按鈕選擇器",
"uploadResultMode": "成功判定方式",
"uploadResultPageNotice": "頁面提示",
"uploadResultHistory": "上傳歷史記錄",
"uploadResultSelector": "結果選擇器",
"uploadSuccessTexts": "成功文字(每行一條)",
"uploadSuccessTextsHint": "命中任一條成功文字即判定成功",
"uploadTimeout": "逾時時間(秒)",
"uploadConfigBoundary": "上傳設定變更不遞增庫存 RPA config_version;僅該連線的貨代上傳使用,不擴散至庫存/收料 RPA。",
"platform": {
"dbs": "DBS 平台",
"crane": "Crane 平台"
+3 -2
View File
@@ -1485,7 +1485,7 @@
"descriptions": {"intake_parse": "核對郵件正文和目前附件,處理接收解析異常。", "order_review": "核實欄位與證據、處理衝突並凍結訂單。", "fulfillment_prep": "完成庫存匹配並產生通知 Excel。", "freight_upload": "下載通知檔案、執行 RPA 或登記人工上傳,並核對未知結果。", "upload_complete": "僅在上傳成功證據完整時顯示通知完成。"},
"intakeParse": {"title": "接收解析", "email": "郵件正文", "emailPreviewTitle": "郵件正文安全預覽", "noEmail": "無郵件上下文", "attachment": "目前附件", "fileName": "檔案名稱", "fileType": "檔案類型", "preview": "附件預覽", "previewLoading": "正在載入附件預覽…", "loadPreview": "載入附件預覽", "previewUnsupported": "目前附件不是 PDF,無法在此預覽。", "loading": "正在載入接收解析上下文…", "loadFailed": "接收解析上下文載入失敗。", "retry": "重試"},
"prepare": {"title": "通知準備", "subtitle": "在此處處理庫存候選、匹配異常與通知檔產生。", "frozenOrder": "凍結訂單", "inventorySource": "庫存來源", "excel": "發貨 Excel", "downloadInventory": "下載庫存檔案", "retryInventory": "重新取得庫存", "releaseShortage": "放行庫存缺口", "releaseShortageHint": "放行後可產生發貨 Excel;請填寫本次缺口放行原因。", "releaseReasonPlaceholder": "請輸入放行原因(必填)", "releaseConfirm": "確認放行", "requiredQty": "需求數量", "matchWorkspace": "庫存匹配", "lineCount": "{count} 行庫存結果", "lineStatus": "匹配狀態", "matched": "已匹配", "shortage": "庫存不足", "matchStatus": {"not_found": "未匹配到庫存", "preparing": "庫存準備中", "mapping_failed": "庫存對應失敗", "unavailable": "庫存不可用", "source_conflict": "庫存來源衝突", "invalid_key": "匹配鍵無效", "result_missing": "等待匹配結果", "unknown": "狀態未知"}, "pending": "庫存匹配或通知檔案尚未產生。請查看右側目前處理,依目前門禁繼續。", "loadFailed": "通知準備任務詳情載入失敗,目前資料無法確認。", "detailUnavailable": "通知準備任務詳情尚未返回,暫時無法展示凍結訂單和庫存匹配資料。", "retry": "重新載入"},
"freightUpload": {"title": "貨代上傳", "subtitle": "按發貨通知單聚合展示;每張發貨通知單對應一張 Excel。", "loading": "正在載入發貨通知…", "loadFailed": "發貨通知載入失敗,請重新整理後重試。", "poMissing": "目前任務尚未識別到 PO,暫時無法聚合發貨通知。", "empty": "目前 PO 沒有可上傳的發貨通知。", "download": "下載 Excel", "lineNo": "項次", "lineNoSourceCustomerPo": "客戶 PO 行號", "lineNoSourceSequence": "系統行序(未識別到內部項次)", "selected": "已選 {count} 個發貨通知", "batchDownload": "批量下載", "batchRpa": "批量 RPA 上傳", "batchConfirm": "批量確認已上傳"},
"freightUpload": {"title": "貨代上傳", "subtitle": "按發貨通知單聚合展示;每張發貨通知單對應一張 Excel。", "loading": "正在載入發貨通知…", "loadFailed": "發貨通知載入失敗,請重新整理後重試。", "poMissing": "目前任務尚未識別到 PO,暫時無法聚合發貨通知。", "empty": "目前 PO 沒有可上傳的發貨通知。", "download": "下載 Excel", "lineNo": "項次", "lineNoSourceCustomerPo": "客戶 PO 行號", "lineNoSourceSequence": "系統行序(未識別到內部項次)", "selected": "已選 {count} 個發貨通知", "batchDownload": "批量下載", "batchRpa": "批量 RPA 上傳", "batchConfirm": "批量確認已上傳", "noticeCount": "共 {count} 張發貨通知", "uploadError": "上傳失敗原因:{reason}", "uploadStatus": {"pending": "待上傳", "uploading": "上傳中", "failed": "上傳失敗", "uploaded": "已上傳", "needsHuman": "需人工上傳"}},
"uploadComplete": {"title": "通知完成", "subtitle": "上傳成功證據已核驗,以下內容僅供查看。", "batchCount": "本批已上傳 {count} 張發貨通知", "batchDownload": "下載本批 ZIP", "batchDownloading": "正在打包…", "uploaded": "已上傳", "uploadedAt": "{time}", "exportFile": "檔案:{file}", "expand": "展開明細", "collapse": "收合明細", "uploadMode": "上傳方式:{mode}", "uploadModeManual": "人工確認", "uploadModeRpa": "RPA 上傳", "empty": "本批暫無已上傳的發貨通知。"},
"upload": {"title": "貨代上傳", "subtitle": "下載通知 Excel、上傳至貨代平台後確認人工上傳,或執行 RPA。", "manualUpload": "確認人工上傳", "attempt": "最近上傳嘗試:{mode} · {status}"},
"stages": {
@@ -2218,7 +2218,7 @@
"adminDiagnosisStatus": "狀態:task_missing",
"adminDiagnosisHint": "請透過任務審計/資料修復流程處理;本頁不提供自動恢復。",
"stateInconsistent": "狀態同步中 / 狀態資料不一致",
"stageLoading": "正在更新狀態…",
"stageLoading": "正在取得最新狀態…",
"statusRunning": "系統處理中",
"statusFailedRetryable": "失敗可重試",
"statusCompleted": "已完成",
@@ -2740,6 +2740,7 @@
"domainFulfillmentShip": "發貨履約",
"currentNeedLabel": "目前需要:",
"systemProcessingNeed": "系統正在自動處理,請稍候或重新整理進度",
"lifecycleWaitingNeed": "目前步驟需要人工處理",
"progressTitleWithStage": "訂單處理進度 · {stage}",
"systemProcessingWithStage": "系統處理中 · {stage}",
"viewProcessDetails": "查看流程詳情",
+176 -65
View File
@@ -30,9 +30,8 @@ Optional:
SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME / SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=false
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=false
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL / SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR
SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL
SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR / SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR
# 上传采用“用连接 login_url 登录 → 直接访问 upload_entry_url 上传页”;文件选择、提交动作与
# 结果判定由受控 DsvUploadAdapter / CraneUploadAdapter 固化,禁止后端注入任意脚本或 selector。
"""
from __future__ import annotations
@@ -1690,77 +1689,186 @@ def _wait_for_dsv_upload_history_receipt(page: Any, filename: str) -> dict[str,
)
class _UploadResultUnknownError(RuntimeError):
"""上传动作已发生但结果无法确认(未能取得可核验成功证据);必须转人工,禁止自动重试。"""
class _BaseUploadAdapter:
"""受控上传适配器基类:由连接级 upload_config 提供页面参数,代码负责浏览器动作与安全边界。
设计约束:禁止把任意脚本/URL 模板/Cookie/任意浏览器动作开放到后台配置;config 只决定
“该连接使用哪个已支持的受控流程及其页面参数”。Adapter 负责登录、打开 entry 页、选择 Excel、
提交与结果判定。Worker 不再根据环境变量拼接 DSV/Crane 页面动作。
"""
def __init__(self, *, file_path: Path, upload_config: dict[str, Any]):
self.file_path = file_path
self.config = upload_config or {}
def _timeout_ms(self) -> int:
try:
seconds = int(self.config.get('timeout_seconds') or 120)
except (TypeError, ValueError):
seconds = 120
return max(1, seconds) * 1000
def _require(self, *fields: str) -> None:
missing = [field for field in fields if not str(self.config.get(field) or '').strip()]
if missing:
raise RuntimeError(f"upload config missing required field(s): {', '.join(missing)}")
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
raise NotImplementedError
class DsvUploadAdapter(_BaseUploadAdapter):
"""DSV 受控上传流程:login_url 登录 → 访问 upload_config.entry_url → 选文件 → 提交 → History 绿色判定。"""
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
self._require('entry_url', 'file_input_selector')
_ensure_dsv_session(page, login_url)
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
file_selector = str(self.config.get('file_input_selector') or '#file2').strip()
page.locator(file_selector).first.set_input_files(str(self.file_path), timeout=self._timeout_ms())
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
submit_selector = str(self.config.get('submit_selector') or '').strip()
if not submit_selector:
raise RuntimeError('DSV click_submit upload requires submit_selector')
page.locator(submit_selector).first.click(timeout=self._timeout_ms())
try:
return _wait_for_dsv_upload_history_receipt(page, self.file_path.name)
except RuntimeError as exc:
# 文件已选择/可能已提交但未取得可核验成功证据 → unknown,转人工。
raise _UploadResultUnknownError(str(exc)) from exc
class CraneUploadAdapter(_BaseUploadAdapter):
"""Crane 受控上传流程:login_url 登录 → 访问 upload_config.entry_url → 选文件 → 提交 → 结果判定。
启用前(enabled=true)管理端必须已确认提交按钮与成功判定字段;否则 fail-closed。
"""
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
self._require('entry_url', 'file_input_selector', 'submit_mode')
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
self._require('submit_selector')
self._require_result_fields()
_ensure_crane_session(page, login_url)
page.goto(str(self.config['entry_url']), wait_until="domcontentloaded", timeout=self._timeout_ms())
page.locator(str(self.config['file_input_selector'])).first.set_input_files(
str(self.file_path), timeout=self._timeout_ms(),
)
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
page.locator(str(self.config['submit_selector'])).first.click(timeout=self._timeout_ms())
return self._resolve_result(page)
def _require_result_fields(self) -> None:
result_mode = str(self.config.get('result_mode') or '').strip()
if result_mode == 'page_notice':
if not str(self.config.get('result_selector') or '').strip() or not self.config.get('success_texts'):
raise RuntimeError('Crane page_notice upload requires result_selector and success_texts')
elif result_mode == 'history_record' and not str(self.config.get('result_selector') or '').strip():
raise RuntimeError('Crane history_record upload requires result_selector')
else:
raise RuntimeError('Crane upload requires a supported result_mode')
def _resolve_result(self, page: Any) -> dict[str, Any]:
result_mode = str(self.config.get('result_mode') or '').strip()
filename = self.file_path.name
if result_mode == 'history_record':
result_selector = str(self.config.get('result_selector') or '').strip()
try:
loc = page.locator(result_selector).first
loc.wait_for(state='visible', timeout=self._timeout_ms())
except Exception as exc:
raise _UploadResultUnknownError(
f"Crane upload history not confirmed for {filename!r}: {exc}"
) from exc
try:
reference = str(loc.text_content(timeout=self._timeout_ms()) or '').strip()
except Exception:
reference = ''
return {
'reference': reference,
'success_evidence': _capture_success_page_evidence(
page, kind='crane_history_record', selector=result_selector,
filename=filename, reference=reference or None,
),
}
# page_notice:要求 result_selector 可见且内容命中任一 success_texts。
result_selector = str(self.config.get('result_selector') or '').strip()
success_texts = [str(t).strip() for t in (self.config.get('success_texts') or []) if str(t).strip()]
deadline = time.monotonic() + (self._timeout_ms() / 1000)
last_snippet = ''
while time.monotonic() < deadline:
try:
loc = page.locator(result_selector).first
if loc.count() > 0 and loc.is_visible():
snippet = str(loc.text_content(timeout=1000) or '').strip()
last_snippet = snippet
if any(text in snippet for text in success_texts):
return {
'reference': '',
'success_evidence': _capture_success_page_evidence(
page, kind='crane_page_notice', selector=result_selector,
filename=filename, reference=None,
),
}
except Exception:
pass
time.sleep(1)
raise _UploadResultUnknownError(
f"Crane upload page notice not confirmed for {filename!r}; last_snippet={last_snippet!r}"
)
def _upload_shipment_with_browser(
file_path: Path, *, connector_type: str = "", dsv_entry_url: str = ""
file_path: Path, *, connector_type: str = "", upload_source: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""
在受控配置下执行货代 Excel 上传,并以页面成功证据作为回调成功前提。
在受控 Adapter 下执行货代 Excel 上传,并以可核验证据作为回调成功前提。
触发条件:仅当 Worker 非 mock、上传与最终提交两个开关均为 true,且 URL、文件
控件、提交控件和成功标识均已配置时执行。未满足任何条件时抛异常并回调失败,绝不
猜测站点、选择器或提交按钮。
触发条件:连接 upload_config.enabled=true(代表管理员已审核该连接的上传行为),且 Worker 上传与
最终提交两项开关均为 true。未满足/未审核时抛异常并回调失败/未知,绝不猜测站点、选择器或
提交按钮,也不允许后台配置注入任意脚本或浏览器动作。
Args:
file_path: 已由 HXOPS 写入共享上传队列且存在的 Excel 文件。
connector_type: 业务连接类型(dbs / crane),决定使用哪个受控 Adapter。
upload_source: 该连接上传快照(含 login_url / credential_envelope / upload_config_json)。
Returns:
dict: reference(可空)与 success_evidence(DSV 绿 DOM 或通用 success 选择器)。
dict: reference(可空)与 success_evidence。
"""
upload_source = upload_source or {}
upload_config = upload_source.get('upload_config_json')
if not isinstance(upload_config, dict) or not upload_config.get('enabled'):
raise RuntimeError(
"upload RPA is not enabled for this connection; enable it in '系统连接' after validation"
)
if not _upload_worker_enabled():
raise RuntimeError("upload RPA is disabled; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=true after validation")
raise RuntimeError("upload RPA worker is disabled; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED=true after validation")
if not _upload_submit_confirmed():
raise RuntimeError("upload RPA submit is not confirmed; set SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT=true after dry run")
normalized_connector = _worker_connector_type({"connector_type": connector_type}) if connector_type else ""
upload_url = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_URL")
file_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_FILE_SELECTOR")
submit_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUBMIT_SELECTOR")
success_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_SUCCESS_SELECTOR")
if normalized_connector == "crane_footprint":
raise RuntimeError("CRANE upload RPA is not implemented because its upload path is unverified")
if normalized_connector == "dsv360":
dsv_entry_url = dsv_entry_url or _env("SHIPPING_NOTICE_RPA_WORKER_DSV_UPLOAD_ENTRY_URL")
if not dsv_entry_url:
raise RuntimeError("DSV upload RPA requires a reviewed DSV upload entry URL")
# DSV WMS Upload Tool 已在真实页面确认 Browse 与 Process File 的 DOM。
file_selector = file_selector or "#file2"
submit_selector = submit_selector or 'button.upload-button:has-text("Process File")'
elif not upload_url:
raise RuntimeError("upload RPA configuration requires a reviewed upload URL")
if not all((file_selector, submit_selector)) or (
normalized_connector != "dsv360" and not success_selector
):
raise RuntimeError("upload RPA configuration requires file, submit and success selectors")
business = str(connector_type or '').strip().lower()
if business not in {'dbs', 'crane'} and connector_type:
business = {'dsv360': 'dbs', 'crane_footprint': 'crane'}.get(
_worker_connector_type({"connector_type": connector_type}), business,
)
if business == 'dbs':
adapter = DsvUploadAdapter(file_path=file_path, upload_config=upload_config)
elif business == 'crane':
adapter = CraneUploadAdapter(file_path=file_path, upload_config=upload_config)
else:
raise RuntimeError(f'unsupported upload connector_type: {connector_type or "<empty>"}')
login_url = str(upload_source.get('login_url') or '').strip()
playwright = context = runtime_profile_dir = None
failed = False
try:
playwright, context, page, runtime_profile_dir = _open_browser(file_path.parent)
if normalized_connector == "dsv360":
_navigate_dsv_to_upload_tool(page, dsv_entry_url)
else:
page.goto(upload_url, wait_until="domcontentloaded", timeout=_browser_timeout_ms())
file_input = page.locator(file_selector).first
file_input.set_input_files(str(file_path), timeout=_browser_timeout_ms())
submit = page.locator(submit_selector).first
submit.click(timeout=_browser_timeout_ms())
if normalized_connector == "dsv360":
return _wait_for_dsv_upload_history_receipt(page, file_path.name)
page.locator(success_selector).first.wait_for(state="visible", timeout=_browser_timeout_ms())
receipt_selector = _env("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_RECEIPT_SELECTOR")
reference = ''
if receipt_selector:
receipt = page.locator(receipt_selector).first
reference = str(receipt.text_content(timeout=_browser_timeout_ms()) or "").strip()
return {
"reference": reference,
"success_evidence": _capture_success_page_evidence(
page,
kind="configured_success_selector",
selector=success_selector,
filename=file_path.name,
reference=reference or None,
),
}
with _profile_credentials(upload_source):
return adapter.run(page, login_url=login_url)
except Exception:
failed = True
raise
@@ -1795,6 +1903,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
"task_no": task_no,
"attempt_id": attempt_id,
"callback_id": callback_id,
"result": "failed",
"success": False,
"error_message": f"queue file missing: {file_path or '<empty>'}",
})
@@ -1826,15 +1935,15 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
},
}
else:
connector_type = str(body.get("inventory_connector_type") or "").strip()
dsv_entry_url = str(body.get("inventory_entry_url") or "").strip()
# 兼容旧 trigger;新 trigger 才携带站点路由信息并进入专用 Driver。
raw = (
_upload_shipment_with_browser(
Path(file_path), connector_type=connector_type, dsv_entry_url=dsv_entry_url
)
if connector_type
else _upload_shipment_with_browser(Path(file_path))
connector_type = str(body.get("connector_type") or "").strip()
upload_source = {
"connector_type": connector_type,
"login_url": str(body.get("login_url") or "").strip(),
"credential_envelope": body.get("credential_envelope"),
"upload_config_json": body.get("upload_config"),
}
raw = _upload_shipment_with_browser(
Path(file_path), connector_type=connector_type, upload_source=upload_source,
)
upload_result = raw if isinstance(raw, dict) else {"reference": str(raw or ''), "success_evidence": None}
ref = str(upload_result.get("reference") or "").strip()
@@ -1842,6 +1951,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
"task_no": task_no,
"attempt_id": attempt_id,
"callback_id": callback_id,
"result": "success",
"success": True,
"freight_ref_no": ref or None,
"success_evidence": upload_result.get("success_evidence"),
@@ -1854,6 +1964,7 @@ def _handle_upload_trigger(trigger_path: Path, processed_dir: Path) -> None:
"task_no": task_no,
"attempt_id": attempt_id,
"callback_id": callback_id,
"result": "unknown" if isinstance(exc, _UploadResultUnknownError) else "failed",
"success": False,
"error_message": str(exc)[:500],
})