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

Merge pull request !13 from 曹惠鹏/hugo-shipping-notice
This commit is contained in:
sophie authored and Gitee committed 2026-08-27 07:51:42 +00:00
commit 2921c8d90f
93 files changed
+4867 -601

No files matched your search

+1 -12
View File
@@ -56,7 +56,7 @@ PROCUREMENT_CONTRACT_LLM_DIFY_BASE=http://192.168.100.192:8882/v1
GUNICORN_WORKERS=10
# --- 5. 数据库与基础设施 ---
DATABASE_URL=postgresql://hxops:1qaz%40WSX@127.0.0.1/hxops
DATABASE_URL=postgresql://postgres:postgres@127.0.0.1:5432/hxops_db
ORACLE_CLIENT_MOUNT_DIR=/home/lisq/ai/platform/hxops/oracle_client
ORACLE_CLIENT_LIB_DIR=/app/oracle_client/instantclient_19_31
LD_LIBRARY_PATH=/app/oracle_client/instantclient_19_31:/app/oracle_client
@@ -101,17 +101,12 @@ SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
# Dify Chatflow(seed_shipping_notice_agents.py)
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
# Tool API Key(Dify / RPA 回调共用,可与 INTEGRATION_API_KEY 相同)
SHIPPING_NOTICE_TOOL_API_KEY=MymLe1StfTCuMOl0IYTp-BRYKln_TnywEDxJ0X0mraYjhFtGeL8mRqoiVPlP9Er8
# 文件存储(相对 backend/ 根目录)
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
# 解析与文本上限
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
# MinerU 订单附件表格结构化(服务地址由环境/Secret 注入,未配置时保持关闭)
@@ -129,11 +124,7 @@ SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
# 字段对齐确认(生产建议 true;测试可设 false)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
@@ -144,8 +135,6 @@ SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=data/shipping_notice/freight_rp
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=data/shipping_notice/freight_rpa/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=data/shipping_notice/freight_rpa/upload_triggers
SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=data/shipping_notice/freight_rpa/browser_profile
# 发货 Excel 模板(可选)
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 RPA(scripts/rpa/freight_rpa_worker.py)
+1 -26
View File
@@ -206,15 +206,9 @@ SHIPPING_PROCESS_GATE_TAKEOVER_SECONDS=120
SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES=3
SHIPPING_PROCESS_GATE_EXTERNAL_POLL_SECONDS=30
SHIPPING_PROCESS_GATE_EXTERNAL_WAIT_TIMEOUT_SECONDS=1800
# 订单行双写/切读:dual 写 + shadow 观察;全量 verify 零差异且观察窗口通过后切 table。
# 回滚:将 READ_MODE 改回 json(或 shadow)即可,本期不删 lines_json。
SHIPPING_NOTICE_ORDER_LINES_WRITE_MODE=dual
SHIPPING_NOTICE_ORDER_LINES_READ_MODE=shadow
# RPA Profile Fernet 主密钥:仅由 Jenkins/Secret/系统环境注入,禁止写入仓库真实值。
# 若本仓库曾提交过非空密钥,须立即轮换所有环境凭据。
SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=KMhO4FolYoBGJeJ4X2JcV47MdAWPAIBRT6CmgdXuMBE=
# 点击发送后的完整订单识别超时;超时 Intake 在状态读取时收口为 failed。
SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300
# 订单解析主链灰度(默认关闭高风险路径;主链不依赖 Dify)。
# L7 验收完成前禁止开启通用解析与通用自动冻结。
# 通用确定性解析:仅 no_special_profile_feature / 无漂移 no_match 可进入。
@@ -225,27 +219,8 @@ SHIPPING_NOTICE_GENERIC_AUTO_FREEZE_ENABLED=false
SHIPPING_NOTICE_PROFILE_AUTO_SELECTION_ENABLED=true
# 阶段四全量切换:全部模板重签并重新发布后改为 true
SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED=true
# XFA 数据路径 Profile(识别到 xfa_hybrid 即正式提取)
# XFA 数据路径 Profile(识别到 xfa_hybrid 即正式提取;资源上限由 xfa_contract 常量承担)
SHIPPING_NOTICE_XFA_ENABLED=true
# 独立自动建单总闸(阶段 5+);默认关。开启前须合成预览门禁 / CQ / 盲测 / 审计补偿就绪。
SHIPPING_NOTICE_XFA_AUTO_CREATE_ENABLED=false
# 离线完整 flatten 引擎是否已交付;默认 false(禁 overlay/壳图充当图源)。
SHIPPING_NOTICE_XFA_FLATTEN_ENGINE_READY=false
# 自动建单硬前置:审计写失败补偿能力就绪前禁止开自动建单。
SHIPPING_NOTICE_XFA_AUDIT_COMPENSATION_REQUIRED_FOR_AUTO_CREATE=true
# shadow=true:完整解析与资格评估,但阻断真实自动建单(仅记录 would_auto_create)
SHIPPING_NOTICE_XFA_SHADOW_MODE=false
# 自动建单硬门禁白名单:客户或 Profile checksum 为空 → fail-closed
SHIPPING_NOTICE_XFA_CUSTOMER_ALLOWLIST=
SHIPPING_NOTICE_XFA_PROFILE_CHECKSUM_ALLOWLIST=
SHIPPING_NOTICE_XFA_SCENARIO_ALLOWLIST=shipping_notice_order
SHIPPING_NOTICE_XFA_MAX_PDF_BYTES=20971520
SHIPPING_NOTICE_XFA_MAX_PACKET_BYTES=10485760
SHIPPING_NOTICE_XFA_MAX_XML_DEPTH=64
SHIPPING_NOTICE_XFA_MAX_XML_NODES=100000
SHIPPING_NOTICE_XFA_MAX_LINE_ROWS=2000
SHIPPING_NOTICE_XFA_PARSE_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_XFA_MAX_RETRIES=2
# XFA 字段拆分规则资源上限(统一方案阶段 1;与 settings.XFA_SPLIT_* 对齐)
XFA_SPLIT_MAX_RULES_PER_SET=32
XFA_SPLIT_MAX_RULE_SETS=64
-11
View File
@@ -126,17 +126,12 @@ SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true
SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false
# 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4)
SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
# Dify Chatflow(seed_shipping_notice_agents.py)
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
# 货代专用 Tool API Key(RPA 回调优先读取;真实值请在服务器本地配置,禁止提交真实密钥)
SHIPPING_NOTICE_TOOL_API_KEY=GOnGt04o0-Ev4wEw6a6C4NOmm4XF7dxsLPP6fPtTC2vV341l1QKVASV75ONj72er
# 文件存储(相对 backend/ 根目录)
SHIPPING_NOTICE_STORAGE_ROOT=data/shipping_notice
# 解析与文本上限
SHIPPING_NOTICE_PARSE_CONFIDENCE_THRESHOLD=0.8
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE=0.8
SHIPPING_NOTICE_INVENTORY_TEXT_MAX_CHARS=80000
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=200000
# MinerU 订单附件表格结构化(服务地址由环境/Secret 注入,未配置时保持关闭)
@@ -154,13 +149,9 @@ SHIPPING_NOTICE_LAYOUT_OCR_PAGE_CACHE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_NATIVE_PAGE_REUSE_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_ENABLED=true
SHIPPING_NOTICE_LAYOUT_OCR_CROP_MARGIN_RATIO=0.03
SHIPPING_NOTICE_INVENTORY_SOURCES_CONFIG=backend/config/shipping_inventory_sources.yaml
SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
# 字段对齐确认(生产建议 true;测试可设 false)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW=true
# 共享目录逻辑标识(Ubuntu 后端与 Windows RPA 必须一致,用于哨兵校验与跨平台路径对齐)
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
SHIPPING_NOTICE_RPA_INVENTORY_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
@@ -181,8 +172,6 @@ SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR=/mnt/hxops-rpa-test-data/inventory
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR=/mnt/hxops-rpa-test-data/inventory_triggers
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queue
SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR=/mnt/hxops-rpa-test-data/upload_triggers
# 发货 Excel 模板(可选)
FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
# AWS 库存列映射(可选 JSON 字符串)
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 Mock RPA(scripts/rpa/freight_rpa_worker.py,可选)
+7
View File
@@ -351,6 +351,13 @@ def rpa_inventory_batch_claimed():
return jsonify({'success': True, 'data': claim_inventory_batch(_payload())})
@shipping_notice_bp.route('/rpa/inventory-batch-progress', methods=['POST'])
def rpa_inventory_batch_progress():
"""RPA 批量库存导出进度回调:实时回写排程 run 计数(非终态,最终以 batch-ready 为准)。"""
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
return jsonify(report_inventory_batch_progress(_payload()))
@shipping_notice_bp.route('/rpa/inventory-configuration-test-ready', methods=['POST'])
def rpa_inventory_configuration_test_ready():
"""RPA 配置测试回调:仅分析文件结构,不创建生产库存快照或任务关联。"""
+39 -4
View File
@@ -548,10 +548,9 @@ def workspace_shipping_task_detail(task_no: str):
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
return _ok({
**serialize_task_detail(task, viewer_user_id=user.id, is_admin=is_admin),
'ui_state': build_task_ui_state(task, include_stage_context=True),
})
return _ok(serialize_task_detail(
task, viewer_user_id=user.id, is_admin=is_admin, include_stage_context=True,
))
@workspace_shipping_notice_bp.route('/shipping-tasks/<task_no>/audit-timeline', methods=['GET'])
@@ -877,9 +876,43 @@ def workspace_mark_manual_uploaded(task_no: str):
run_task_auto_progress(
str(task.task_no), trigger='manual_upload_confirmed', operator_id=int(user.id),
)
# 终态兜底:确认上传必须收口正式 Execution Gate,不允许依赖 auto_progress/Job 链。
_ensure_uploaded_execution_gates_closed(task, actor_id=int(user.id))
return _ok(result)
def _ensure_uploaded_execution_gates_closed(task: ShippingNotice, *, actor_id: int) -> None:
"""人工确认上传(终态)后兜底收口正式 Execution 门禁,禁止依赖 auto_progress/Job 链。
核心逻辑:upload_manual_confirmed 是业务终态事实;只有把正式 Execution 的前置履约
Gate 一并收口,批次中心/对话卡才不会因陈旧「库存不足」Gate 把阶段回退成「通知准备」。
``auto_progress_enabled()`` 可能为 False(``run_task_auto_progress`` 提前返回),
或 ``submit_auto_progress`` 存在活动 Job / 候选集等早退分支而跳过 sync,故此处兜底:
仅当 Execution 尚未 completed 时显式同步(幂等,重复无害)。已 completed 时不重复处理,
避免与 ``_active_execution_for_task`` 将 completed Execution 误判为可重建。
Args:
task: 已确认人工上传的正式 ShippingNotice。
actor_id: 触发确认的服务端用户主键。
"""
from app.services.shipping_notice.process_gate_bridge import (
find_execution_for_task,
sync_fulfillment_gates_from_task,
)
execution = find_execution_for_task(task)
if execution is None:
return
if str(getattr(execution, 'status', '') or '').strip().lower() == 'completed':
return
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='user',
actor_id=actor_id,
)
db.session.flush()
def _confirm_notice_uploaded(*, business_no: str, user_id: int, artifact_id: int | None = None) -> dict[str, Any]:
"""
按发货通知单号确认唯一 Excel 已上传;内部 task_no 仅用于既有状态机和审计追溯。
@@ -916,6 +949,8 @@ def _confirm_notice_uploaded(*, business_no: str, user_id: int, artifact_id: int
run_task_auto_progress(
str(task.task_no), trigger='manual_upload_confirmed', operator_id=user_id,
)
# 终态兜底:确认上传必须收口正式 Execution Gate,不允许依赖 auto_progress/Job 链。
_ensure_uploaded_execution_gates_closed(task, actor_id=user_id)
return {'business_no': str(task.business_no), **dict(result or {})}
+1 -25
View File
@@ -257,9 +257,6 @@ class Config:
SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED = (
os.getenv('SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY = int(
os.getenv('SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY') or '3'
)
SHIPPING_NOTICE_TASK_EXECUTION_MODE = os.getenv('SHIPPING_NOTICE_TASK_EXECUTION_MODE', 'worker').strip().lower()
SHIPPING_NOTICE_WORKER_POLL_SECONDS = float(os.getenv('SHIPPING_NOTICE_WORKER_POLL_SECONDS', '2'))
SHIPPING_NOTICE_WORKER_CONCURRENCY = int(os.getenv('SHIPPING_NOTICE_WORKER_CONCURRENCY', '2'))
@@ -270,11 +267,7 @@ class Config:
SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_STP_WAITING_TIMEOUT_SECONDS', '120') or '120'
)
SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW = os.getenv('SHIPPING_NOTICE_INVENTORY_MAPPING_REVIEW', 'true')
SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED = os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED', 'false').lower() == 'true'
SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS = int(
os.getenv('SHIPPING_NOTICE_AUTO_PROGRESS_RECOVERY_MAX_AGE_HOURS', '72') or '72'
)
SHIPPING_NOTICE_WORKER_RECOVERY_TICK_SECONDS = float(
os.getenv('SHIPPING_NOTICE_WORKER_RECOVERY_TICK_SECONDS', '60') or '60'
)
@@ -301,22 +294,10 @@ class Config:
os.getenv('SHIPPING_NOTICE_PROFILE_LAYOUT_SIGNATURE_REQUIRED', 'false').lower() == 'true'
)
# XFA 数据路径 Profile:识别到 xfa_hybrid 后允许使用 datasets adapter。
# XFA 资源上限(max_pdf/packet/xml/line/retries/parse_timeout)由 xfa_contract 常量承担,不再经环境变量注入。
SHIPPING_NOTICE_XFA_ENABLED = (
os.getenv('SHIPPING_NOTICE_XFA_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_XFA_MAX_PDF_BYTES = int(
os.getenv('SHIPPING_NOTICE_XFA_MAX_PDF_BYTES') or str(20 * 1024 * 1024)
)
SHIPPING_NOTICE_XFA_MAX_PACKET_BYTES = int(
os.getenv('SHIPPING_NOTICE_XFA_MAX_PACKET_BYTES') or str(10 * 1024 * 1024)
)
SHIPPING_NOTICE_XFA_MAX_XML_DEPTH = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_XML_DEPTH') or '64')
SHIPPING_NOTICE_XFA_MAX_XML_NODES = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_XML_NODES') or '100000')
SHIPPING_NOTICE_XFA_MAX_LINE_ROWS = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_LINE_ROWS') or '2000')
SHIPPING_NOTICE_XFA_PARSE_TIMEOUT_SECONDS = int(
os.getenv('SHIPPING_NOTICE_XFA_PARSE_TIMEOUT_SECONDS') or '30'
)
SHIPPING_NOTICE_XFA_MAX_RETRIES = int(os.getenv('SHIPPING_NOTICE_XFA_MAX_RETRIES') or '2')
SHIPPING_NOTICE_LLM_REVIEW_ENABLED = (
os.getenv('SHIPPING_NOTICE_LLM_REVIEW_ENABLED', 'false').lower() == 'true'
)
@@ -422,9 +403,6 @@ class Config:
SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED = (
os.getenv('SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED', 'true').lower() == 'true'
)
SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE = float(
os.getenv('SHIPPING_NOTICE_AUTO_INVENTORY_CONFIDENCE') or '0.8'
)
SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS = os.getenv('SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS')
FREIGHT_INVENTORY_COLUMN_MAP = os.getenv('FREIGHT_INVENTORY_COLUMN_MAP')
SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = _rpa_data_path(
@@ -680,8 +658,6 @@ class Config:
# parser v6:阶段二附件派生 FileAsset + Document/Candidate;相对 v5 须强制重解析
# parser v5:mixed 保留独立 HTML 段 + 附件型 alternative 可提取正文
SHIPPING_NOTICE_EML_MAX_ATTACHMENTS = int(os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENTS', '20'))
# 单次批量上传通知文件上限;与 EML 内附件上限独立,防止请求级资源耗尽。
SHIPPING_NOTICE_BATCH_MAX_FILES = int(os.getenv('SHIPPING_NOTICE_BATCH_MAX_FILES', '20'))
SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES = int(
os.getenv('SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES', str(20 * 1024 * 1024))
)
@@ -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)
@@ -70,15 +70,23 @@ def _reset_inventory_state_for_forced_rpa(task) -> None:
def _request_formal_gate_action(**kwargs):
"""决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。"""
"""决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。
核心逻辑:请求正式 Gate 恢复前先清除任务级解析/复核阻断残留
(review_status / pending_human_reason / error_message / upload 错误),
避免旧阻断事实污染重启后的 Gate 投影。写入由被调用方的事务统一提交。
"""
task = kwargs.get('task')
if task is not None:
task.upload_error_message = None
task.upload_receipt_json = None
task.review_status = None
task.pending_human_reason = None
task.error_message = None
from app.services.shipping_notice.task_retry_decision_service import _request_formal_gate_action as _request
return _request(**kwargs)
task.upload_error_message = None
task.upload_receipt_json = None
task.review_status = None
task.pending_human_reason = None
task.error_message = None
def _prepare_task_for_inventory_reupload(task) -> None:
+20 -3
View File
@@ -195,20 +195,24 @@ def _mapping_value(
excel_business_no: str | None = None,
notice_no: str | None = None,
export_date: date | None = None,
field_id_by_code: dict[str, str] | None = None,
) -> Any:
"""
按映射来源类型读取值;未知来源已在模板发布时被拒绝。
核心逻辑:order_field 读订单快照;inventory_field 读库存行;system_fact 仅读白名单事实;
export_sequence 优先用调用方传入值,缺失时回退行上注入的 ``__export_sequence``。
项次缺失时经 order_line_no_resolver 统一解析(line_no 字段 → 客户 PO 行号 →
导出行序号),与 UI 展示同一口径,禁止此处另造回退链。
Args:
mapping: 已发布模板映射项。
task: 发货任务。
order_values: 当前行或表头订单字段值。
order_values: 当前行或表头订单字段值(field_id 为键)。
inventory_values: 当前行库存字段值。
header_values: 明细行模式下可回退的表头字段。
export_sequence: 本次导出行序号(1..N)。
field_id_by_code: field_code → field_id 映射(快照 Schema);缺失时按 code 键兼容。
Returns:
经 formatter 处理后的单元格值。
@@ -219,8 +223,14 @@ def _mapping_value(
value = order_values.get(key)
field = db.session.get(ShippingOrderField, key) if key else None
field_code = str(field.field_code or '') if field else ''
if value in (None, '') and field_code == 'line_no' and export_sequence is not None:
value = export_sequence
if value in (None, '') and field_code == 'line_no':
from app.services.shipping_notice.order_line_no_resolver import resolve_order_line_no
value = resolve_order_line_no(
field_values=order_values,
field_id_by_code=field_id_by_code,
fallback_sequence=export_sequence,
)['value']
if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
value = header_values.get(key)
elif kind == 'inventory_field':
@@ -617,6 +627,11 @@ def generate_shipment_excel(
# [STEP 4] Notice 的业务单号与首个 Excel 同一事务产生。此处已完成业务、
# 库存和导出行校验;随后 Excel、Artifact 或 Reservation 任一步失败都会回滚编号流水。
from app.services.shipping_notice.order_line_no_resolver import field_id_by_code_from_definition
field_id_by_code = field_id_by_code_from_definition(
snapshot.schema_version.definition_json if snapshot.schema_version is not None else None,
)
if not task.business_no:
from app.services.shipping_notice.business_numbering_service import assign_notice_business_number
@@ -650,6 +665,7 @@ def generate_shipment_excel(
mapping, task=task, order_values=header_values, inventory_values=header_inventory,
excel_business_no=excel_business_no,
export_date=export_date,
field_id_by_code=field_id_by_code,
)
continue
row_count = max(len(line_values), 1)
@@ -662,6 +678,7 @@ def generate_shipment_excel(
export_sequence=int(order_line.get('__export_sequence') or (index + 1)),
excel_business_no=excel_business_no,
export_date=export_date,
field_id_by_code=field_id_by_code,
)
wb.save(path)
finally:
@@ -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'
@@ -581,20 +619,17 @@ def _sync_workflow_stage(
)
def match_completed(task: ShippingNotice) -> bool:
"""
STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。
def _released_line_keys_for_task(task: ShippingNotice) -> set[str]:
"""读取当前任务已审计的短缺放行行键集,供满足性与聚合重算共用。
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
核心逻辑:只认活动 ``release_inventory_shortage`` 决定;无放行事实时返回空集,
保证聚合重算与 ``match_completed`` 读到的放行语义完全一致,避免两处分裂。
"""
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewLineDecision
from app.models import ShippingOrderReviewCase, ShippingOrderReviewLineDecision
if task.id is None:
return False
rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
if not rows:
return False
released_keys = {
return set()
return {
str(row.line_key)
for row in (
ShippingOrderReviewLineDecision.query
@@ -607,6 +642,23 @@ def match_completed(task: ShippingNotice) -> bool:
.all()
)
}
def match_completed(task: ShippingNotice) -> bool:
"""
STP 整单满足性门禁:仅当全部明细匹配成功(fulfillable 且每行 ok)时通过。
核心逻辑:该函数只代表整单满足性,不代表滚动 Excel 是否存在可导出行。
已人工放行的短缺行视同满足(与 ``_recompute_task_match_aggregate`` 同源)。
"""
from app.models import ShippingNoticeLineInventoryMatch
if task.id is None:
return False
rows = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=int(task.id), is_current=True).all()
if not rows:
return False
released_keys = _released_line_keys_for_task(task)
for row in rows:
result = str(row.match_result or '').strip()
shortage = _line_shortage_qty(getattr(row, 'shortage_qty', None))
@@ -1171,7 +1223,12 @@ def _merge_line_inventory_resolutions(
def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dict[str, Any]]]:
"""根据 ShippingNoticeLineInventoryMatch(current=True)重新聚合成 match_status(fulfillable/partial/unfulfillable)+ shortages。"""
"""根据 ShippingNoticeLineInventoryMatch(current=True)重新聚合成 match_status(fulfillable/partial/unfulfillable)+ shortages。
核心逻辑:与 ``match_completed`` 同款放行语义——已人工放行(release_inventory_shortage)
且仍有缺口的行视同满足,不再计入 has_block/缺货;否则会与 Excel 门禁分裂,
出现"Gate 认为满足、任务却仍标 unfulfillable"的矛盾。
"""
rows = (
ShippingNoticeLineInventoryMatch.query
.filter_by(task_id=int(task.id), is_current=True)
@@ -1179,6 +1236,7 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
)
if not rows:
return 'unfulfillable', []
released_keys = _released_line_keys_for_task(task)
has_ok = False
has_block = False
shortages: list[dict[str, Any]] = []
@@ -1200,16 +1258,21 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
'available_qty': float(available_qty) if available_qty is not None else 0.0,
'shortage_qty': float(shortage_qty) if shortage_qty is not None else 0.0,
}
entry['line_status'] = (
'ok' if match_result == 'matched' and entry['shortage_qty'] <= 0
else 'shortage'
)
task.line_results_json.append(entry)
if match_result == 'matched':
# 已审计放行的短缺行视同满足:不阻断、不进入缺货列表。
shortage = _line_shortage_qty(shortage_qty)
released = str(getattr(row, 'line_key', '') or '') in released_keys
if match_result == 'matched' and shortage <= 0:
entry['line_status'] = 'ok'
has_ok = True
continue
has_block = True
shortages.append(entry)
elif released and shortage > 0:
# 放行行状态仍暴露"放行",但聚合按满足计入,避免整单误判缺货。
entry['line_status'] = 'released'
has_ok = True
else:
entry['line_status'] = 'shortage'
has_block = True
shortages.append(entry)
task.line_results_json.append(entry)
task.shortage_json = {'lines': shortages}
if has_block and has_ok:
status = 'partial'
@@ -1229,6 +1292,28 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]:
return list(task.line_results_json or [])
def recompute_task_fulfillment_state(task: ShippingNotice) -> str:
"""按当前匹配/放行事实重算任务履约态:match_status、line_results_json、shortage_json 与 review/pending。
核心逻辑:委托 ``_recompute_task_match_aggregate``(与 ``match_completed`` 同款放行语义),
再据此同步 ``review_status``/``pending_human_reason`` 并应用对应任务迁移。
供放行(release)回调、库存满足性复核与其它恢复路径复用,杜绝旧状态残留。
Args:
task: 待重算的 ShippingNotice(尚未 commit)。
Returns:
重算后的 match_status(fulfillable / partial / unfulfillable)。
"""
status, _shortages = _recompute_task_match_aggregate(task)
task.match_status = status
if status == 'fulfillable':
apply_task_transition(task, TaskTransition.MATCHED_FULFILLABLE)
else:
apply_task_transition(task, TaskTransition.MATCH_SHORTAGE)
return status
def _profile_match_persistence_payload(
line_results: list[dict[str, Any]],
*,
@@ -1956,14 +2041,6 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
if reservation_gate is not None:
return reservation_gate
if not is_inventory_source_stable(task):
return tool_response(
status="failed",
task=task,
message="库存源尚未确定,无法上传货代系统。",
data=serialize_task_for_tool(task),
)
# [STEP 1] 先确保至少有一份 Artifact;后续上传始终由 Artifact 而非 Task 文件指针驱动。
if not task.export_file_path:
gen = generate_excel({"task_id": task.task_no})
@@ -1989,6 +2066,15 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
stop_agent_turn=True,
next_required_action='请在任务处理工作台使用「确认已上传」。',
)
# RPA 上传仍需从库存源取数,必须在触发前确认源仍可用;
# 人工确认已上传不在此路径,不依赖库存源(Excel 已生成、外部已上传)。
if not is_inventory_source_stable(task):
return tool_response(
status="failed",
task=task,
message="库存源尚未确定,无法上传货代系统。",
data=serialize_task_for_tool(task),
)
return _trigger_freight_upload_rpa(
task,
payload={**payload, 'artifact_id': artifact_id, 'mode': mode},
@@ -2112,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 = (
@@ -2139,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))
@@ -2204,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": "ไฟล์อาจถูกส่งไปแล้วแต่ไม่สามารถยืนยันผลจากหน้าเว็บได้ เพื่อหลีกเลี่ยงการอัปโหลดซ้ำ กรุณาตรวจสอบระบบขนส่งด้วยตนเอง",
},
}
@@ -472,9 +472,22 @@ def project_inventory_candidate_facts(
serialized_matches: list[dict[str, Any]] = []
stale_details: dict[str, Any] | None = None
out_of_scope_details: dict[str, Any] | None = None
for row in _current_match_rows(task, session=sess):
current_match_rows = _current_match_rows(task, session=sess)
# [BE-性能] 批量预取当前匹配行引用的库存快照,避免循环内逐行 sess.get() 造成 N+1。
snapshot_ids = {
int(row.inventory_snapshot_id)
for row in current_match_rows
if getattr(row, 'inventory_snapshot_id', None) is not None
}
snapshot_by_id: dict[int, Any] = {}
if snapshot_ids:
snapshot_by_id = {
int(item.id): item
for item in sess.query(ShippingInventoryFile).filter(ShippingInventoryFile.id.in_(snapshot_ids)).all()
}
for row in current_match_rows:
snapshot = (
sess.get(ShippingInventoryFile, int(row.inventory_snapshot_id))
snapshot_by_id.get(int(row.inventory_snapshot_id))
if getattr(row, 'inventory_snapshot_id', None) is not None else None
)
allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None))
@@ -67,6 +67,16 @@ def inventory_loaded_response(
else:
task.inventory_lines_json = inventory_lines
# [BE-放行-恢复] 库存内容已重新载入/复用,旧匹配结果必然失效:清空任务级派生状态,
# 强制 Gate 链路在下一轮重新匹配,避免复用旧快照的短缺/匹配结果而造成"库存已刷新
# 却仍显示旧缺口/旧 match_status"的矛盾(对 task 及其同库存文件的关联任务一并清理)。
for affected in [task, *linked_tasks]:
if affected is None:
continue
affected.match_status = None
affected.line_results_json = None
affected.shortage_json = None
try:
order_lines = task_line_purpose_values(task)
except ValueError:
@@ -918,6 +918,73 @@ def _validate_schedule_batch_callback_run_no(schedule_run_id: int | None, callba
return None
def report_inventory_batch_progress(payload: dict[str, Any]) -> dict[str, Any]:
"""
RPA 批量导出进度回调:实时回写排程 run 的成功/跳过/失败笔数(非终态)。
【AI 触发时机】:freight_rpa_worker 每完成一个库存站点导出后调用,用于管理端实时
展示"执行中"run 的笔数;最终计数仍以 inventory-batch-ready 回调为准(终态化时重算覆盖)。
核心逻辑:校验 schema_version、schedule_run_id 与 run_no 匹配且 run 仍处于 awaiting_rpa;
仅更新计数列与 response_summary_json.progress,不修改 status/started_at/finished_at,
不影响超时回收与最终终态化。计数采用 max(现有, 上报) 防乱序回退。
Returns:
tool_response: 进度已回写为 ok;无效/非等待态为 failed(不改变 run 状态)。
"""
if payload.get('schema_version') != 'shipping_inventory_rpa.v2':
return tool_response(status='failed', message='callback_schema_invalid', data={
'progress_status': 'invalid', 'error_code': 'callback_schema_invalid',
})
schedule_run_id = payload.get('schedule_run_id')
try:
schedule_run_id = int(schedule_run_id) if schedule_run_id is not None else None
except (TypeError, ValueError):
schedule_run_id = None
run_no = str(payload.get('batch_run_no') or payload.get('run_no') or '').strip()
if not schedule_run_id or not run_no:
return tool_response(status='failed', message='progress_schema_invalid', data={
'progress_status': 'invalid', 'error_code': 'callback_schema_invalid',
})
schedule_run_error = _validate_schedule_batch_callback_run_no(schedule_run_id, run_no)
if schedule_run_error:
return tool_response(status='failed', message=f'排程进度回调无效: {schedule_run_error}', data={
'progress_status': 'rejected', 'schedule_run_error': schedule_run_error,
})
from app.models import ScheduleRun
run = db.session.get(ScheduleRun, schedule_run_id)
if run is None:
return tool_response(status='failed', message='schedule_run_not_found', data={
'progress_status': 'rejected', 'schedule_run_error': 'schedule_run_not_found',
})
incoming = {
'success_count': max(0, int(payload.get('success_count') or 0)),
'skipped_count': max(0, int(payload.get('skipped_count') or 0)),
'failed_count': max(0, int(payload.get('failed_count') or 0)),
}
run.success_count = max(int(run.success_count or 0), incoming['success_count'])
run.skipped_count = max(int(run.skipped_count or 0), incoming['skipped_count'])
run.failed_count = max(int(run.failed_count or 0), incoming['failed_count'])
summary = dict(run.response_summary_json or {})
summary['progress'] = {
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
'batch_run_no': run_no,
'updated_at': datetime.utcnow().isoformat(),
}
run.response_summary_json = summary
db.session.commit()
return tool_response(status='ok', message='库存 RPA 导出进度已回写', data={
'progress_status': 'updated',
'run_no': run_no,
'success_count': int(run.success_count or 0),
'skipped_count': int(run.skipped_count or 0),
'failed_count': int(run.failed_count or 0),
})
def _validate_rpa_callback_inventory_source(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None:
"""
校验 RPA 成功回调是否允许处理当前任务库存(门禁 + 轮次 + 身份)。
@@ -14,6 +14,8 @@ from pathlib import Path
from typing import Any
from flask import current_app
from sqlalchemy import event as _sa_event
from sqlalchemy.orm import Session
from app import db
from app.models import ShippingInventoryFile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink
@@ -30,6 +32,24 @@ _SNAPSHOT_STATUS_READY = "ready"
_SNAPSHOT_STATUS_EMPTY = "empty"
_SNAPSHOT_STATUS_FAILED = "failed"
_SNAPSHOT_STATUS_EXPIRED = "expired"
# 请求内只读缓存(key: (source_code, warehouse_id) → ShippingInventoryFile | None)。
# 同一请求内 _build_stp_facts / _build_stage_context / 行级匹配会重复查询同一
# (source, warehouse) 的最新 ready 快照(实测 task detail 一次请求重复 3 次)。
# 任何快照行写入(新建/过期/更新)都会由 after_flush 事件失效,保证写后读可见。
_READ_CACHE_KEY = "shipping_inventory_snapshot_read_cache"
@_sa_event.listens_for(Session, "after_flush")
def _clear_snapshot_read_cache_on_write(session, flush_context): # noqa: ANN001
"""快照写入路径统一失效点:覆盖全部创建/过期/更新调用方,无需逐处接线。"""
touched = (
any(isinstance(obj, ShippingInventoryFile) for obj in session.new)
or any(isinstance(obj, ShippingInventoryFile) for obj in session.dirty)
or any(isinstance(obj, ShippingInventoryFile) for obj in session.deleted)
)
if touched:
session.info.pop(_READ_CACHE_KEY, None)
_WAREHOUSE_ID_HEADER_ALIASES = {
"warehouseid",
"warehouse",
@@ -77,12 +97,22 @@ def find_latest_ready_snapshot(
"""
查找指定 Source 的最新 ready 且未过期库存快照。
核心逻辑:固定 Source 限定 Warehouse;动态 Source 先复用文件,再由 reservation + PN 匹配确定 Warehouse。
性能约束:结果按 (source_code, warehouse_id) 请求内记忆化——同一读请求中 STP 事实、
阶段上下文与行级匹配会重复调用;任何快照写入都会失效该缓存(after_flush 事件)。
"""
code = str(source_code or "").strip().upper()
warehouse = str(warehouse_id or "").strip().upper()
if not code:
return None
read_cache = db.session.info.get(_READ_CACHE_KEY)
if not isinstance(read_cache, dict):
read_cache = {}
db.session.info[_READ_CACHE_KEY] = read_cache
cache_key = (code, warehouse)
if cache_key in read_cache:
return read_cache[cache_key]
query = ShippingInventoryFile.query.filter_by(
source_code=code,
snapshot_status=_SNAPSHOT_STATUS_READY,
@@ -91,10 +121,13 @@ def find_latest_ready_snapshot(
query = query.filter_by(warehouse_id=warehouse)
rows = query.order_by(ShippingInventoryFile.exported_at.desc(), ShippingInventoryFile.id.desc()).limit(5).all()
result = None
for row in rows:
if is_snapshot_fresh(row):
return row
return None
result = row
break
read_cache[cache_key] = result
return result
def find_ready_rpa_inventory_snapshot(
@@ -42,34 +42,17 @@ INVENTORY_SOURCE_ERROR_CODES = {
}
def _inventory_source_config_current(task: ShippingNotice) -> bool:
"""任务上记录的库存源配置版本须与当前数据库版本一致。"""
# 兼容旧任务/轻量测试桩:缺失版本字段等同于未冻结当前配置。
stored = str(getattr(task, 'inventory_source_config_version', None) or "").strip()
current = inventory_sources_runtime_version()
if not stored:
return False
return stored == current
def is_inventory_source_stable(task: ShippingNotice) -> bool:
"""
判断任务库存源是否稳定,可供后续库存/RPA/匹配流程使用。
核心逻辑:单源须 Source/Driver/配置一致;STP 多候选冻结(candidates_frozen)
在配置版本与指纹有效且候选非空时亦视为稳定,可进入库存准备。
核心逻辑(档位一:只做必要管控):单源须 Source 存在且启用、Driver 一致;
STP 多候选冻结(candidates_frozen)在候选非空且各候选源存在时视为稳定。
不比对全局配置版本 hash 或路由指纹——无关库存源的改动不使本任务失效。
"""
status = str(task.inventory_source_status or "").strip()
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
return False
if not _inventory_source_config_current(task):
return False
fingerprint = str(task.inventory_routing_fingerprint or "").strip()
if not fingerprint:
return False
context = extract_routing_context(task)
if fingerprint != compute_routing_fingerprint(context):
return False
if status == "candidates_frozen":
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
@@ -107,11 +90,17 @@ def routing_fingerprint_changed(task: ShippingNotice, context: dict[str, Any]) -
def inventory_source_config_changed(task: ShippingNotice) -> bool:
"""配置版本变化会使已有库存源裁决失效。"""
stored = str(task.inventory_source_config_version or "").strip()
if not stored:
return bool(str(task.inventory_source_status or "").strip())
return stored != inventory_sources_runtime_version()
"""
配置变更判定(档位一收窄):仅当任务实际选中的库存源自身不再可用时才算配置已变。
核心逻辑:不再比对全局配置版本 hash——无关库存源的改动不影响本任务;
只检查任务冻结时选中的源(或冻结候选集)当前是否仍可用(存在且启用、驱动一致)。
"""
status = str(task.inventory_source_status or "").strip()
if status not in STABLE_INVENTORY_SOURCE_STATUSES:
# 未稳定任务沿用旧语义:已有裁决状态即视为需要重新裁决。
return bool(status)
return not is_inventory_source_stable(task)
def apply_destination_fields(task: ShippingNotice, context: dict[str, Any]) -> None:
@@ -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 []),
@@ -3361,9 +3361,25 @@ def list_order_extraction_run_summaries(
}
def _run_no_via_fk(fk_id: int | None) -> str | None:
"""
按自引用外键经 identity map 读取父/后继 Run 号。
性能约束:禁止再走 reparse_source/superseding_run 关系懒加载——它们每次都会
全列 SELECT 父行(含 MB 级 input_snapshot_json);父行通常已由谱系遍历加载,
此处命中 identity map 后 0 SQL。
"""
if fk_id is None:
return None
parent = db.session.get(ShippingOrderProcessingRun, int(fk_id))
return parent.run_no if parent is not None else None
def _reparse_difference_summary(run: ShippingOrderProcessingRun) -> dict[str, Any] | None:
"""返回新版与来源 Run 的脱敏规则差异计数,禁止比较或暴露邮件正文和 Provider 输出。"""
source = run.reparse_source
if not run.reparse_of_run_id:
return None
source = db.session.get(ShippingOrderProcessingRun, int(run.reparse_of_run_id))
if source is None:
return None
current = run.input_snapshot_json if isinstance(run.input_snapshot_json, dict) else {}
@@ -3602,8 +3618,9 @@ def serialize_order_extraction_run(run: ShippingOrderProcessingRun) -> dict[str,
'schema_checksum': schema_snapshot.get('checksum'),
'attempt_count': int(run.attempt_count or 0),
'reparse': {
'source_run_no': run.reparse_source.run_no if run.reparse_source is not None else None,
'superseding_run_no': run.superseding_run.run_no if run.superseding_run is not None else None,
# [PERF] 用 identity-map 直取替代关系加载,避免对父行重复全列 SELECT(含 MB 级 JSON)。
'source_run_no': _run_no_via_fk(run.reparse_of_run_id),
'superseding_run_no': _run_no_via_fk(run.superseded_by_run_id),
'reason': run.reparse_reason,
'superseded_at': run.superseded_at.isoformat() + 'Z' if run.superseded_at else None,
'difference_summary': _reparse_difference_summary(run),
@@ -0,0 +1,153 @@
"""
backend/app/services/shipping_notice/order_line_no_resolver.py
用途:内部项次(line_no)展示/导出值的唯一解析器——冻结字段真实值 → 客户 PO 行号 →
行展示序号,并输出来源标注(field / customer_po_line_no / sequence / None)。
依赖:app.models(ShippingNotice/Snapshot/Extraction)、order_schema.field_rules(格式门禁)。
逻辑:Excel 导出(export._mapping_value)与 UI 投影(query_service / ui_state)统一调用
本模块,禁止各调用方自行兜底,避免同一数据出现两套口径;缺失事实必须显式标注来源,
不得把内部行号伪装成业务项次。
"""
from __future__ import annotations
from typing import Any
from app import db
from app.models import ShippingNotice, ShippingOrderExtraction, ShippingOrderSnapshot
from app.services.shipping_notice.order_schema.field_rules import is_valid_line_no_value
LINE_NO_SOURCE_FIELD = 'field'
LINE_NO_SOURCE_CUSTOMER_PO_LINE = 'customer_po_line_no'
LINE_NO_SOURCE_SEQUENCE = 'sequence'
def field_id_by_code_from_definition(
definition_json: dict[str, Any] | None,
) -> dict[str, str]:
"""从 Schema 版本定义提取 field_code → field_id 映射。
Args:
definition_json: 已发布 Schema 版本的 definition_json;无 fields 时返回空映射。
Returns:
{field_code: field_id};仅保留同时具备 code/id 的字段。
"""
fields = (definition_json or {}).get('fields') or []
return {
str(item.get('field_code')): str(item.get('field_id'))
for item in fields
if isinstance(item, dict) and item.get('field_code') and item.get('field_id')
}
def notice_line_field_id_map(task: ShippingNotice) -> dict[str, str]:
"""按任务冻结 Schema 构建行字段 code→id 映射。
核心逻辑:优先读冻结快照的 Schema 版本(与快照行 field_values_json 的 field_id 键同源);
无快照时回退当前探测 Extraction 的 Schema 版本;均不可得时返回空映射,
由解析器按 field_code 键兼容读取(历史/测试数据)。
Args:
task: 正式发货任务。
Returns:
{field_code: field_id};无法取得 Schema 时返回空映射。
"""
snapshot_id = getattr(task, 'order_snapshot_id', None)
if snapshot_id:
snapshot = db.session.get(ShippingOrderSnapshot, int(snapshot_id))
if snapshot is not None and snapshot.schema_version is not None:
return field_id_by_code_from_definition(snapshot.schema_version.definition_json)
extraction_id = getattr(task, 'current_order_extraction_id', None)
if extraction_id:
extraction = db.session.get(ShippingOrderExtraction, int(extraction_id))
if extraction is not None and extraction.schema_version is not None:
return field_id_by_code_from_definition(extraction.schema_version.definition_json)
return {}
def _read_field(
field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None,
code: str,
) -> str | None:
"""按 field_id 优先、field_code 兼容的稳定顺序读取行字段值。
核心逻辑:冻结 JSON 以 field_id(UUID)为键;历史/测试数据可能仍按 field_code 存储。
任一键命中且非空即返回规范化字符串,避免把 0/False 等合法值误判为空。
"""
values = field_values if isinstance(field_values, dict) else {}
field_id = str(field_id_by_code.get(code) or '') if field_id_by_code else ''
if field_id and field_id in values:
raw = values[field_id]
if raw not in (None, ''):
text = str(raw).strip()
return text or None
if code in values:
raw = values[code]
if raw not in (None, ''):
text = str(raw).strip()
return text or None
return None
def resolve_order_line_no(
*,
field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None,
fallback_sequence: int | None = None,
) -> dict[str, Any]:
"""解析一行内部项次展示值(唯一权威入口)。
【AI 触发时机】需要展示或导出某订单行的项次时统一调用;禁止在展示层自行回退。
核心逻辑:
[STEP 1] line_no 字段真实值(须通过 is_valid_line_no_value 格式门禁)→ source=field;
[STEP 2] customer_po_line_no 字段真实值(同格式门禁)→ source=customer_po_line_no;
[STEP 3] 调用方提供的 1..N 行序号 → source=sequence(明确标注为展示序号);
[STEP 4] 全部缺失 → {'value': None, 'source': None}。
与派生规则同门禁:非法项次格式(非 1–6 位数字)一律跳过,不得以序号冒充业务值。
Args:
field_values: 行字段值 JSON(field_id 或 field_code 键均可)。
field_id_by_code: field_code → field_id 映射;为空时仅按 field_code 键兼容读取。
fallback_sequence: 1 基展示序号;None 表示无序号兜底。
Returns:
{'value': 规范化字符串或 None, 'source': 'field'|'customer_po_line_no'|'sequence'|None}。
"""
line_no = _read_field(field_values, field_id_by_code, 'line_no')
if line_no is not None and is_valid_line_no_value(line_no):
return {'value': line_no, 'source': LINE_NO_SOURCE_FIELD}
customer_line_no = _read_field(field_values, field_id_by_code, 'customer_po_line_no')
if customer_line_no is not None and is_valid_line_no_value(customer_line_no):
return {'value': customer_line_no, 'source': LINE_NO_SOURCE_CUSTOMER_PO_LINE}
if fallback_sequence is not None and int(fallback_sequence) >= 1:
return {'value': str(int(fallback_sequence)), 'source': LINE_NO_SOURCE_SEQUENCE}
return {'value': None, 'source': None}
def resolve_order_line_no_projection(
*,
field_values: dict[str, Any] | None,
field_id_by_code: dict[str, str] | None,
fallback_sequence: int | None = None,
) -> dict[str, Any]:
"""与 resolve_order_line_no 同源的 UI/导出投影形(line_no / line_no_source 键)。
核心逻辑:仅供展示层消费;把语义结果映射为前端契约键,避免各处手写
{'line_no': result['value'], 'line_no_source': result['source']} 产生分叉。
Returns:
{'line_no': str|None, 'line_no_source': 'field'|'customer_po_line_no'|'sequence'|None}。
"""
resolved = resolve_order_line_no(
field_values=field_values,
field_id_by_code=field_id_by_code,
fallback_sequence=fallback_sequence,
)
return {'line_no': resolved['value'], 'line_no_source': resolved['source']}
@@ -18,6 +18,8 @@ from __future__ import annotations
import uuid
from typing import Any, NoReturn
from sqlalchemy.orm import defer
from app import db
from app.core.errors import AppError, ConflictError, NotFoundError, ValidationError
from app.models import (
@@ -44,16 +46,41 @@ _NON_ORDER_REASONS = frozenset({'non_order', 'duplicate_file', 'other'})
_TERMINAL_DISPOSITION_STATUSES = frozenset({'confirmed', 'non_order', 'superseded', 'reparse_pending'})
_RUN_LINEAGE_ROOT_CACHE_KEY = 'shipping_order_review_run_lineage_root_cache'
def _run_lineage_root(*, run: ShippingOrderProcessingRun) -> ShippingOrderProcessingRun:
"""沿重解析父链定位批次的初始 Run,阻止从局部子 Run 缩小原批次范围。"""
"""
沿重解析父链定位批次的初始 Run,阻止从局部子 Run 缩小原批次范围。
性能约束:父链每跳只窄列读取(defer 大 JSON 冻结快照),同一请求内按 Run 记忆化,
避免工作台每次投影都沿谱系重拉整行 input_snapshot_json(MB 级)。
"""
cache = db.session.info.get(_RUN_LINEAGE_ROOT_CACHE_KEY)
if not isinstance(cache, dict):
cache = {}
db.session.info[_RUN_LINEAGE_ROOT_CACHE_KEY] = cache
cached = cache.get(int(run.id))
if cached is not None:
return cached
current = run
seen_ids = {int(run.id)}
while current.reparse_of_run_id:
parent = db.session.get(ShippingOrderProcessingRun, int(current.reparse_of_run_id))
parent = (
ShippingOrderProcessingRun.query
.options(
defer(ShippingOrderProcessingRun.input_snapshot_json),
defer(ShippingOrderProcessingRun.execution_result_json),
defer(ShippingOrderProcessingRun.result_json),
)
.filter(ShippingOrderProcessingRun.id == int(current.reparse_of_run_id))
.first()
)
if parent is None or int(parent.id) in seen_ids:
break
seen_ids.add(int(parent.id))
current = parent
cache[int(run.id)] = current
return current
@@ -429,6 +429,23 @@ def _sync_confirmed_task_fulfillment_gates(*, case: ShippingOrderReviewCase, act
task = db.session.get(ShippingNotice, int(task_id))
if task is None:
return
# [BE-释放-重算] 放行是库存充分性 Gate 的受控业务事实:必须先把任务级履约态
# (match_status/line_results_json/shortage_json/review_status/pending_human_reason)
# 重算到与放行决定一致,否则 Gate 重投影后任务仍残留 shortage/unfulfillable,
# 出现"Excel 已生成但任务仍显示库存不足/缺货"的矛盾。仅当任务确有匹配行事实时重算,
# 空事实任务不得被误标为缺货。
if getattr(task, 'id', None) is not None:
from app.models import ShippingNoticeLineInventoryMatch as _MatchRow
has_match_rows = (
_MatchRow.query.filter_by(task_id=int(task.id), is_current=True).first()
is not None
)
if has_match_rows:
from app.services.shipping_notice.fulfillment_workflow import (
recompute_task_fulfillment_state,
)
recompute_task_fulfillment_state(task)
execution_id = getattr(task, 'active_process_execution_id', None)
if execution_id is not None:
from app.models import ShippingProcessExecution
@@ -1185,15 +1185,39 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
.all()
)
counts = {key: 0 for key in ('unreviewed', 'draft', 'ready', 'confirmed', 'non_order', 'quality_issue')}
items = []
for case in cases:
counts[case.status] = counts.get(case.status, 0) + 1
items.append(_serialize_review_case_summary(case, run=run))
batch = _load_review_case_summary_batch([(case, run) for case in cases])
previous_cache = db.session.info.get('shipping_conversation_projection_read_cache')
cache = dict(previous_cache) if isinstance(previous_cache, dict) else {}
cache['stp_jobs_by_ref'] = {**cache.get('stp_jobs_by_ref', {}), **batch['jobs_by_ref']}
cache['stp_jobs_by_prefix'] = {**cache.get('stp_jobs_by_prefix', {}), **batch['jobs_by_prefix']}
cache['execution_by_case_id'] = {**cache.get('execution_by_case_id', {}), **batch['executions_by_case_id']}
cache['gates_by_execution_id'] = {**cache.get('gates_by_execution_id', {}), **batch['gates_by_execution_id']}
cache['latest_attempt_by_id'] = {**cache.get('latest_attempt_by_id', {}), **batch['latest_attempt_by_id']}
db.session.info['shipping_conversation_projection_read_cache'] = cache
try:
items = []
for case in cases:
counts[case.status] = counts.get(case.status, 0) + 1
items.append(_serialize_review_case_summary(
case,
run=run,
candidates_by_id=batch['candidates_by_id'],
intakes_by_no=batch['intakes_by_no'],
drafts_by_id=batch['drafts_by_id'],
))
finally:
if previous_cache is None:
db.session.info.pop('shipping_conversation_projection_read_cache', None)
else:
db.session.info['shipping_conversation_projection_read_cache'] = previous_cache
# 同一事务中刚写入 superseded_by_run_id 时,SQLAlchemy 不会自动刷新已加载的
# self-referential relationship。投影按外键补读,保证旧 Run 可稳定指向后继 Run。
superseding_run = run.superseding_run
if superseding_run is None and run.superseded_by_run_id is not None:
superseding_run = db.session.get(ShippingOrderProcessingRun, int(run.superseded_by_run_id))
# self-referential relationship。投影按外键直取,保证旧 Run 可稳定指向后继 Run。
superseding_run = (
db.session.get(ShippingOrderProcessingRun, int(run.superseded_by_run_id))
if run.superseded_by_run_id is not None
else None
)
return {
'run_no': run.run_no,
'superseded_by_run_no': superseding_run.run_no if superseding_run is not None else None,
@@ -1204,49 +1228,28 @@ def serialize_review_run(run: ShippingOrderProcessingRun) -> dict[str, Any]:
}
def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, Any]:
"""返回会话级文件当前队列;Run/Case 历史均不参与主队列平铺。"""
if not runs:
return {'conversation_id': None, 'summary': {'total': 0, 'needs_action': 0, 'processing': 0, 'completed': 0}, 'items': []}
conversation_id = str(runs[0].conversation_id)
owner_ids = {int(run.user_id) for run in runs if run.user_id is not None}
query = (
db.session.query(ShippingOrderReviewStream, ShippingOrderReviewCase, ShippingOrderProcessingRun)
.join(ShippingOrderReviewCase, ShippingOrderReviewCase.id == ShippingOrderReviewStream.current_case_id)
.join(ShippingOrderProcessingRun, ShippingOrderProcessingRun.id == ShippingOrderReviewCase.run_id)
.filter(ShippingOrderProcessingRun.conversation_id == conversation_id)
.filter(ShippingOrderReviewCase.status != 'superseded')
.options(
Load(ShippingOrderReviewCase).load_only(
ShippingOrderReviewCase.id,
ShippingOrderReviewCase.stream_id,
ShippingOrderReviewCase.revision_no,
ShippingOrderReviewCase.case_no,
ShippingOrderReviewCase.run_id,
ShippingOrderReviewCase.document_id,
ShippingOrderReviewCase.candidate_id,
ShippingOrderReviewCase.current_draft_id,
ShippingOrderReviewCase.confirmed_task_id,
ShippingOrderReviewCase.status,
ShippingOrderReviewCase.disposition,
),
Load(ShippingOrderProcessingRun).load_only(
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.run_no,
ShippingOrderProcessingRun.conversation_id,
ShippingOrderProcessingRun.user_id,
ShippingOrderProcessingRun.schema_version_id,
ShippingOrderProcessingRun.input_snapshot_json,
),
)
)
if owner_ids:
query = query.filter(ShippingOrderReviewStream.owner_user_id.in_(owner_ids))
rows = query.order_by(ShippingOrderReviewStream.updated_at.desc(), ShippingOrderReviewStream.id.desc()).all()
case_ids = [int(case.id) for _, case, _ in rows]
candidate_ids = [int(case.candidate_id) for _, case, _ in rows if case.candidate_id]
draft_ids = [int(case.current_draft_id) for _, case, _ in rows if case.current_draft_id]
task_ids = [int(case.confirmed_task_id) for _, case, _ in rows if case.confirmed_task_id]
def _load_review_case_summary_batch(
rows: list[tuple[ShippingOrderReviewCase, ShippingOrderProcessingRun]],
) -> dict[str, Any]:
"""
一次性批量预取列表投影所需的子实体,禁止按 Case N+1 查询。
性能约束:候选 / Draft / Intake / 正式 Notice / STP Job / Execution / Gate / Attempt
全部聚合为固定次数批量查询;STP Job 与 Execution 事实写入会话级只读缓存
(shipping_conversation_projection_read_cache),供既有 find_active_stp_job 等消费,
保证会话队列与单 Run 摘要在同一请求内复用同一批事实。正式 Notice 仅预热身份映射,
后续 resolve_formal_ot / ui_state 的 db.session.get 命中 identity map(0 SQL)。
Args:
rows: (Case, Run) 行列表。
Returns:
批量化后的候选 / Draft / Intake 映射与 STP Job / Execution 缓存数据。
"""
case_ids = [int(case.id) for case, _ in rows]
candidate_ids = [int(case.candidate_id) for case, _ in rows if case.candidate_id]
draft_ids = [int(case.current_draft_id) for case, _ in rows if case.current_draft_id]
task_ids = [int(case.confirmed_task_id) for case, _ in rows if case.confirmed_task_id]
candidates_by_id = {
int(candidate.id): candidate
for candidate in ShippingOrderCandidate.query.filter(ShippingOrderCandidate.id.in_(candidate_ids)).all()
@@ -1255,13 +1258,11 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
int(draft.id): draft
for draft in ShippingOrderReviewDraft.query.filter(ShippingOrderReviewDraft.id.in_(draft_ids)).all()
} if draft_ids else {}
_tasks_by_id = {
int(task.id): task
for task in ShippingNotice.query.filter(ShippingNotice.id.in_(task_ids)).all()
} if task_ids else {}
if task_ids:
ShippingNotice.query.filter(ShippingNotice.id.in_(task_ids)).all()
intake_nos = {
str(intake_snapshot.get('intake_no') or '').strip().upper()
for _, case, run in rows
for case, run in rows
for intake_snapshot in (run.input_snapshot_json or {}).get('intakes', [])
if isinstance(intake_snapshot, dict)
for document in intake_snapshot.get('documents') or []
@@ -1277,7 +1278,7 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
stp_prefixes = {
f"stp-auto:{run.run_no}:doc-{int(case.document_id)}:"
for _, case, run in rows
for case, run in rows
if case.document_id is not None
}
stp_refs = {
@@ -1286,7 +1287,7 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
document_id=int(case.document_id),
draft_version=int(drafts_by_id[int(case.current_draft_id)].draft_version),
)
for _, case, run in rows
for case, run in rows
if case.current_draft_id and int(case.current_draft_id) in drafts_by_id
}
jobs_by_ref: dict[str, list[Job]] = {ref: [] for ref in stp_refs}
@@ -1345,23 +1346,75 @@ def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str,
ShippingProcessGateAttempt.id.in_(latest_attempt_ids),
).all()
}
return {
'candidates_by_id': candidates_by_id,
'drafts_by_id': drafts_by_id,
'intakes_by_no': intakes_by_no,
'jobs_by_ref': jobs_by_ref,
'jobs_by_prefix': jobs_by_prefix,
'executions_by_case_id': executions_by_case_id,
'gates_by_execution_id': gates_by_execution_id,
'latest_attempt_by_id': latest_attempt_by_id,
}
def serialize_review_queue(runs: list[ShippingOrderProcessingRun]) -> dict[str, Any]:
"""返回会话级文件当前队列;Run/Case 历史均不参与主队列平铺。"""
if not runs:
return {'conversation_id': None, 'summary': {'total': 0, 'needs_action': 0, 'processing': 0, 'completed': 0}, 'items': []}
conversation_id = str(runs[0].conversation_id)
owner_ids = {int(run.user_id) for run in runs if run.user_id is not None}
query = (
db.session.query(ShippingOrderReviewStream, ShippingOrderReviewCase, ShippingOrderProcessingRun)
.join(ShippingOrderReviewCase, ShippingOrderReviewCase.id == ShippingOrderReviewStream.current_case_id)
.join(ShippingOrderProcessingRun, ShippingOrderProcessingRun.id == ShippingOrderReviewCase.run_id)
.filter(ShippingOrderProcessingRun.conversation_id == conversation_id)
.filter(ShippingOrderReviewCase.status != 'superseded')
.options(
Load(ShippingOrderReviewCase).load_only(
ShippingOrderReviewCase.id,
ShippingOrderReviewCase.stream_id,
ShippingOrderReviewCase.revision_no,
ShippingOrderReviewCase.case_no,
ShippingOrderReviewCase.run_id,
ShippingOrderReviewCase.document_id,
ShippingOrderReviewCase.candidate_id,
ShippingOrderReviewCase.current_draft_id,
ShippingOrderReviewCase.confirmed_task_id,
ShippingOrderReviewCase.status,
ShippingOrderReviewCase.disposition,
),
Load(ShippingOrderProcessingRun).load_only(
ShippingOrderProcessingRun.id,
ShippingOrderProcessingRun.run_no,
ShippingOrderProcessingRun.conversation_id,
ShippingOrderProcessingRun.user_id,
ShippingOrderProcessingRun.schema_version_id,
ShippingOrderProcessingRun.input_snapshot_json,
),
)
)
if owner_ids:
query = query.filter(ShippingOrderReviewStream.owner_user_id.in_(owner_ids))
rows = query.order_by(ShippingOrderReviewStream.updated_at.desc(), ShippingOrderReviewStream.id.desc()).all()
batch = _load_review_case_summary_batch([(case, run) for _, case, run in rows])
previous_cache = db.session.info.get('shipping_conversation_projection_read_cache')
cache = dict(previous_cache) if isinstance(previous_cache, dict) else {}
cache['stp_jobs_by_ref'] = {**cache.get('stp_jobs_by_ref', {}), **jobs_by_ref}
cache['stp_jobs_by_prefix'] = {**cache.get('stp_jobs_by_prefix', {}), **jobs_by_prefix}
cache['execution_by_case_id'] = {**cache.get('execution_by_case_id', {}), **executions_by_case_id}
cache['gates_by_execution_id'] = {**cache.get('gates_by_execution_id', {}), **gates_by_execution_id}
cache['latest_attempt_by_id'] = {**cache.get('latest_attempt_by_id', {}), **latest_attempt_by_id}
cache['stp_jobs_by_ref'] = {**cache.get('stp_jobs_by_ref', {}), **batch['jobs_by_ref']}
cache['stp_jobs_by_prefix'] = {**cache.get('stp_jobs_by_prefix', {}), **batch['jobs_by_prefix']}
cache['execution_by_case_id'] = {**cache.get('execution_by_case_id', {}), **batch['executions_by_case_id']}
cache['gates_by_execution_id'] = {**cache.get('gates_by_execution_id', {}), **batch['gates_by_execution_id']}
cache['latest_attempt_by_id'] = {**cache.get('latest_attempt_by_id', {}), **batch['latest_attempt_by_id']}
db.session.info['shipping_conversation_projection_read_cache'] = cache
try:
items = [{
**_serialize_review_case_summary(
case,
run=run,
candidates_by_id=candidates_by_id,
intakes_by_no=intakes_by_no,
drafts_by_id=drafts_by_id,
candidates_by_id=batch['candidates_by_id'],
intakes_by_no=batch['intakes_by_no'],
drafts_by_id=batch['drafts_by_id'],
),
'stream_id': int(stream.id),
'stream_state': stream.state,
@@ -884,6 +884,40 @@ def sync_fulfillment_gates_from_task(
mapping_confirmed = bool(inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False)))
# [STEP 1] 优先读匹配/短缺实体;阶段由领域事实推导。
done_statuses = {'uploaded', 'closed'}
# [STEP 1A] 已上传/已关闭是终态事实:直接收口 RPA 与人工交接 Gate 后返回,
# 禁止再用当前库存不足/匹配缺失重算前置 Gate(否则已上传任务会被 gate 16
# 倒打回 blocked_manual,execution.current_gate 回退、OT 阶段与前端状态横跳)。
if status in done_statuses:
# 人工确认已上传 = 覆盖前序预警门禁(含短路时的 blocked_manual 短缺门禁),
# 使 Execution 全部通过并进入 completed;短缺事实仍保留在 Gate 审计 effective_result。
mark_gates_passed_through(
execution=execution,
through_gate_code='manual_upload_handoff',
actor_type=actor_type,
actor_id=actor_id,
reason='task_uploaded',
)
apply_gate_outcome(
execution=execution,
gate_code='freight_upload_rpa',
passed=True,
effective_result={'derived_fulfillment_status': status, 'findings': []},
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:freight_rpa:{execution.execution_no}:{status}:passed',
force=True,
)
apply_gate_outcome(
execution=execution,
gate_code='manual_upload_handoff',
passed=True,
effective_result={'derived_fulfillment_status': status, 'findings': []},
actor_type=actor_type,
actor_id=actor_id,
idempotency_key=f'fulfill:upload:{execution.execution_no}:{status}:passed',
force=True,
)
return
post_inventory = {'inventory_ready', 'matched', 'waiting_upload', 'upload_failed', *done_statuses}
sufficiency_ok = match_completed(task)
shortage = (not sufficiency_ok) and (
@@ -1085,7 +1085,9 @@ def _handle_recheck_inventory_sufficiency(
) -> dict[str, Any]:
"""独立库存满足性复核:读取 match_status / shortage_json,不重跑匹配。"""
from app.models import ShippingNotice
from app.services.shipping_notice.fulfillment_workflow import match_completed
from app.services.shipping_notice.fulfillment_workflow import (
recompute_task_fulfillment_state,
)
from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
@@ -1097,6 +1099,16 @@ def _handle_recheck_inventory_sufficiency(
'effective_result_json': {'findings': []},
'output_snapshot': {'action_code': 'recheck_inventory_sufficiency'},
}
# [BE-满足性复盘] 复核先按当前放行/匹配事实重算任务级履约态,避免"Gate 认为满足、
# 任务却仍标 unfulfillable/shortage"的旧状态残留。仅在确有匹配行时重算(空事实不误标缺货)。
from app.models import ShippingNoticeLineInventoryMatch as _MatchRow
if getattr(task, 'id', None) is not None and (
_MatchRow.query.filter_by(task_id=int(task.id), is_current=True).first() is not None
):
recompute_task_fulfillment_state(task)
from app.services.shipping_notice.fulfillment_workflow import match_completed
sufficient = match_completed(task)
shortage = task.shortage_json if isinstance(task.shortage_json, (dict, list)) else None
apply_gate_outcome(
@@ -328,6 +328,32 @@ def serialize_process_execution(
.order_by(ShippingProcessGate.sequence_no.asc())
.all()
)
# [BE-性能] ui_state 等工作台路径不预置 conversation 投影缓存,导致 serialize_process_gate
# 对每个 Gate 各做一次 latest_attempt_id 的 query.get()(N+1)。此处批量加载本 Execution 的
# 全部 LatestAttempt 并写入会话缓存,缓存生效后逐 Gate 命中、不再逐条查询。
previous_cache = db.session.info.get('shipping_conversation_projection_read_cache')
merged_cache = dict(previous_cache) if isinstance(previous_cache, dict) else {}
latest_attempt_ids = [
int(gate.latest_attempt_id)
for gate in gates
if gate.latest_attempt_id is not None
]
if latest_attempt_ids:
attempt_by_id = {
int(a.id): a
for a in ShippingProcessGateAttempt.query.filter(
ShippingProcessGateAttempt.id.in_(latest_attempt_ids),
).all()
}
merged_cache['latest_attempt_by_id'] = {
**((merged_cache.get('latest_attempt_by_id') or {})),
**attempt_by_id,
}
merged_cache['gates_by_execution_id'] = {
**((merged_cache.get('gates_by_execution_id') or {})),
**{int(execution.id): gates},
}
db.session.info['shipping_conversation_projection_read_cache'] = merged_cache
serialized = [
serialize_process_gate(gate, include_diagnostics=include_diagnostics)
for gate in gates
@@ -245,6 +245,7 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
execution.responsible_party = None
if execution.status not in {'cancelled', 'failed'}:
execution.status = 'completed'
_sync_order_task_stage_after_gate_refresh(execution)
return
execution.current_gate_code = current.gate_code
execution.primary_next_action_code = current.next_action_code
@@ -258,6 +259,24 @@ def _refresh_execution_pointers(execution: ShippingProcessExecution) -> None:
execution.status = 'active'
else:
execution.status = 'active'
# [OT SYNC] Gate 指针刷新后回写挂接 OT 的 stage/status,避免主卡/批次只读
# 投影停留在技术阶段(如 excel_generating),与当前 Gate 事实分叉。
# 仅已绑定任务时同步;建单前执行(无 task_id)自然跳过。延迟导入避免循环依赖。
_sync_order_task_stage_after_gate_refresh(execution)
def _sync_order_task_stage_after_gate_refresh(execution: ShippingProcessExecution) -> None:
"""Gate 指针刷新后回写挂接 OT 的 stage/status(completed 与阻断两个出口共用)。"""
if getattr(execution, 'task_id', None) is None:
return
from app.models import ShippingNotice
from app.services.shipping_notice.order_task_stage_machine import (
sync_order_task_stage_for_notice,
)
notice = db.session.get(ShippingNotice, int(execution.task_id))
if notice is not None:
sync_order_task_stage_for_notice(notice)
def ensure_execution_for_workflow_version(
@@ -792,8 +792,11 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
"""
投影发货通知列表需要的项次、料号、数量与当前库存事实。
核心逻辑:Notice 行定义“本通知包含哪些业务行”;当前库存只读取同 Notice、
`is_current=true` 的匹配事实。未找到匹配事实时明确返回 null,禁止由前端估算库存。
核心逻辑:Notice 行定义“本通知包含哪些业务行”;项次(line_no)经
order_line_no_resolver 统一解析(字段真实值 → 客户 PO 行号 → 展示序号),
并附 line_no_source 标注,禁止前端按 position 或序号自行推导业务项次。
当前库存只读取同 Notice、`is_current=true` 的匹配事实;未找到匹配事实时明确
返回 null,禁止由前端估算库存。
"""
if task.id is None:
return []
@@ -808,8 +811,18 @@ def _notice_line_summary_for_task(task: ShippingNotice) -> list[dict[str, Any]]:
rows = ShippingNoticeLine.query.filter_by(notice_id=int(task.id)).order_by(
ShippingNoticeLine.position.asc(), ShippingNoticeLine.id.asc(),
).all()
from app.services.shipping_notice.order_line_no_resolver import (
notice_line_field_id_map,
resolve_order_line_no_projection,
)
field_id_by_code = notice_line_field_id_map(task)
return [{
'line_no': (item.field_values_json or {}).get('line_no') or item.position,
**resolve_order_line_no_projection(
field_values=item.field_values_json,
field_id_by_code=field_id_by_code,
fallback_sequence=(int(item.position) + 1) if item.position is not None else None,
),
'part_number': item.part_number,
'customer_part_number': (item.field_values_json or {}).get('customer_part_number'),
'reservation_id': item.reservation_id,
@@ -889,6 +902,7 @@ def _enrich_task_center_fields(
*,
viewer_user_id: int | None = None,
is_admin: bool = False,
include_stage_context: bool = False,
) -> dict[str, Any]:
"""
为 SUMMARY/DETAIL 投影补充任务中心字段(就地写入并返回 data)。
@@ -896,12 +910,15 @@ def _enrich_task_center_fields(
核心逻辑:todo_category / created_by 始终写入;viewer 给定时写入 can_handle;
recent_event / artifact_summary / ui_state 懒加载同源状态;
注入 shipping_processing_status / progress_version / order_task_no(统一进度)。
``include_stage_context`` 直接透传给 ``build_task_ui_state``,使 DETAIL 一次投影即可携带
工作面只读事实,避免调用方在同一请求里再 build 一次被覆盖。
Args:
task: 源任务。
data: 已构建的序列化字典。
viewer_user_id: 当前查看者;为 None 时省略 can_handle。
is_admin: 是否管理员视图(仅影响 can_handle 调用签名,不开放代操作)。
include_stage_context: 是否让内嵌 ui_state 附带 stage_context。
Returns:
同一 data 引用(已 enrich)。
@@ -918,7 +935,7 @@ def _enrich_task_center_fields(
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
from app.services.shipping_notice.ui_state import build_task_ui_state
data["ui_state"] = build_task_ui_state(task)
data["ui_state"] = build_task_ui_state(task, include_stage_context=include_stage_context)
_inject_unified_processing_fields(task, data)
# [BE-06] WorkflowItem 账本已下线;固定为 None,禁止前端再当 OT 身份源。
data['workflow_item'] = None
@@ -950,6 +967,7 @@ def serialize_task_detail(
*,
viewer_user_id: int | None = None,
is_admin: bool = False,
include_stage_context: bool = False,
) -> dict[str, Any]:
"""
工作台任务详情用的 DETAIL 投影(含 lines、events 与任务中心 enrich)。
@@ -958,10 +976,12 @@ def serialize_task_detail(
task: 源任务。
viewer_user_id: 当前查看者;用于 can_handle。
is_admin: 是否管理员视图。
include_stage_context: 是否让内嵌 ui_state 附带 stage_context(避免调用方重复 build)。
"""
data = serialize_task(task, TaskProjection.DETAIL)
return _enrich_task_center_fields(
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
include_stage_context=include_stage_context,
)
@@ -1123,17 +1143,19 @@ def list_freight_notice_groups_for_task(
if not business_no:
continue
# [STEP] 主区单条菜单只消费服务端已裁决的 Notice 动作,禁止按 upload_status 猜测。
from app.services.shipping_notice.ui_state import build_task_ui_state
actions = (build_task_ui_state(notice).get('actions') or {})
available_actions = [
str(action.get('code')).strip()
for action in [actions.get('primary'), *(actions.get('secondary') or [])]
if isinstance(action, dict) and action.get('enabled') is True and str(action.get('code') or '').strip()
]
# 轻量投影仅返回动作码,避免逐张 Notice 跑完整 build_task_ui_state 造成 N 倍放大。
from app.services.shipping_notice.ui_state import project_notice_available_actions
available_actions = project_notice_available_actions(notice)
items.append({
'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),
@@ -92,10 +92,22 @@ def invalidate_inventory_downstream(
upload.invalidated_at = now
upload.invalidation_reason = action_code
result['uploads'].append(int(upload.id))
if task is not None and action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'}:
if task is not None and action_code in {
'retry_inventory_preparation',
'retry_inventory_from_preparation',
'retry_inventory_from_field_mapping',
'retry_inventory_from_matching',
}:
# [BE-放行-恢复] 本动作已把当前匹配行置 is_current=False(上方),必须同步清空任务级
# 派生状态,否则 UI 与 Gate 在下一轮重匹配前仍读到旧 match_status/shortage/line_results,
# 出现"已重试却仍显示旧缺货"的矛盾。
task.match_status = None
task.shortage_json = None
task.line_results_json = None
if task is not None and (
action_code in {'retry_inventory_preparation', 'retry_inventory_from_preparation'}
):
# 仅库存文件级重试才清空导出指针;匹配/字段映射级重试只作废匹配,不改已生成文件。
task.export_file_path = None
task.export_file_name = None
db.session.flush()
+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:
@@ -1588,7 +1588,23 @@ def _project_order_task_work_item(
active_execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
active_gate = str(getattr(active_execution, 'current_gate_code', '') or '').strip().lower()
active_status = str(getattr(active_execution, 'status', '') or '').strip().lower()
if active_status != 'superseded' and active_gate in SHIPPING_PROCESSING_STAGES:
# [BE-10] 正式 Execution 的当前 Gate 只允许把阶段「向前抬起」,严禁把阶段回退。
# 人工确认上传后 Notice 已进入 upload 终态事实(OT.stage/project_stage_for_task 可能已
# 是 freight_uploading/completed),但 Execution 前置履约 Gate 若因 upload_status 未到位
# 而未被 STEP 1A 收口,仍会停在 inventory_sufficiency 等前置 Gate。此时若用 active_gate
# 无条件覆盖 stage,批次中心/对话卡会被回退成「通知准备」,与工作台的「通知完成」分叉。
# 只在 active_gate 不落后于 Notice 当前阶段时才覆盖。
from app.services.shipping_notice.processing_projection_invariants import (
shipping_processing_stage_index,
)
current_stage_idx = shipping_processing_stage_index(stage)
active_gate_idx = shipping_processing_stage_index(active_gate)
if (
active_status != 'superseded'
and active_gate in SHIPPING_PROCESSING_STAGES
and active_gate_idx is not None
and (current_stage_idx is None or active_gate_idx >= current_stage_idx)
):
stage = active_gate
stage_label_key = active_gate
# order_creating 无共享投影时仍统一用户文案键。
@@ -1345,6 +1345,11 @@ def retry_task(payload: dict[str, Any]) -> dict[str, Any]:
task.review_status = None
task.pending_human_reason = None
task.error_message = None
# [BE-放行-重试] 重试应重新评估当前库存事实:清空旧匹配结果,强制 orchest 在下一轮
# 重新匹配,而不是带着旧的 unfulfillable/shortage 直接跳到步骤(避免旧缺货残留)。
task.match_status = None
task.line_results_json = None
task.shortage_json = None
try:
order_lines = current_line_field_values(task)
@@ -610,6 +610,12 @@ def _build_stage_context(
}
# 冻结订单与库存匹配是不同事实:库存文件尚未准备好时,用户仍必须能核对
# 已冻结的预约号、料号和需求数量。禁止用“是否有匹配结果”决定订单行是否展示。
from app.services.shipping_notice.order_line_no_resolver import (
notice_line_field_id_map,
resolve_order_line_no_projection,
)
line_no_field_id_by_code = notice_line_field_id_map(task)
frozen_order_lines: list[dict[str, Any]] = []
preparation_lines: list[dict[str, Any]] = []
notice_lines = (
@@ -619,6 +625,11 @@ def _build_stage_context(
for line in notice_lines:
frozen_order_lines.append({
'line_key': getattr(line, 'line_key', None),
**resolve_order_line_no_projection(
field_values=dict(getattr(line, 'field_values_json', None) or {}),
field_id_by_code=line_no_field_id_by_code,
fallback_sequence=(int(line.position) + 1) if line.position is not None else None,
),
'reservation_id': getattr(line, 'reservation_id', None),
'part_number': getattr(line, 'part_number', None),
'required_qty': str(getattr(line, 'required_qty', None)) if getattr(line, 'required_qty', None) is not None else None,
@@ -660,6 +671,11 @@ def _build_stage_context(
shortage_qty = result.get('shortage_qty', source.get('shortage_qty', verification.get('shortage_qty')))
preparation_lines.append({
'line_key': getattr(line, 'line_key', None) or source.get('line_key'),
**resolve_order_line_no_projection(
field_values=dict(getattr(line, 'field_values_json', None) or {}) if line is not None else None,
field_id_by_code=line_no_field_id_by_code,
fallback_sequence=index + 1,
),
'reservation_id': result.get('reservation_id') or source.get('effective_reservation_id') or source.get('reservation_id') or getattr(line, 'reservation_id', None),
'part_number': result.get('part_number') or source.get('part_number') or getattr(line, 'part_number', None),
'required_qty': required_qty,
@@ -672,7 +688,7 @@ def _build_stage_context(
has_match_result = bool(current_match_rows or raw_rows or any(
row.get('matched_qty') is not None
or row.get('shortage_qty') is not None
or str(row.get('disposition') or '').lower() in {'ok', 'partial', 'shortage'}
or str(row.get('disposition') or '').lower() in {'ok', 'partial', 'shortage', 'released'}
for row in fact_rows if isinstance(row, dict)
))
gate = process_gate if isinstance(process_gate, dict) else {}
@@ -930,3 +946,31 @@ def _process_gate_user_summary_for_task(task: ShippingNotice) -> dict[str, Any]
)
def project_notice_available_actions(task: ShippingNotice) -> list[str]:
"""轻量投影单张 Notice 的已授权动作码,供货代上传面板按 business_no 展示单条菜单。
核心逻辑:与 ``build_task_ui_state`` 的 actions 同源(Gate 摘要 + 统一动作 + 已验证
Excel 下载授权),但**不**构建 stage_context / summary / steps / progress_nodes 等昂贵
重活。list_freight_notice_groups_for_task 会遍历同 PO 的多张 Notice,逐张调用完整
``build_task_ui_state`` 会造成 N 倍放大;此处只返回动作码,用于面板首屏即可。
Returns:
已启用动作码列表(primary + secondary + 已验证下载)。
"""
process_gate = _process_gate_user_summary_for_task(task)
actions = _unified_actions(process_gate=process_gate)
codes = [
str(item.get('code') or '').strip()
for item in [actions.get('primary'), *(actions.get('secondary') or [])]
if isinstance(item, dict) and item.get('enabled') is True and str(item.get('code') or '').strip()
]
# 与 build_task_ui_state 同款下载授权:Artifact 已验证后补入只读下载。
from app.services.shipping_notice.query_service import resolve_task_export_download
if resolve_task_export_download(task) is not None:
download_code = 'download_excel'
if download_code not in codes:
codes.append(download_code)
return codes
@@ -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,46 @@
"""允许库存快照 empty 状态以配合 RPA 空结果审计快照。
用途:RPA 批量回调对 no_inventory_data 写入 audit 快照时使用 snapshot_status='empty',
但 d6e7f8a9b0c1 建的表级检查约束只允许 ('ready','failed','expired'),导致插入必然违反
约束并整笔回滚(job 回执 CheckViolation: ck_shipping_inventory_files_snapshot_status)。
依赖:shipping_inventory_files。
逻辑:放宽同一检查约束,加入 'empty';保留其余取值不变。
"""
from __future__ import annotations
from alembic import op
revision = 'hq0r1s2t3u4v'
down_revision = 'hp9q0r1s2t3u'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""放宽快照状态检查约束,允许 'empty' 审计快照。"""
op.drop_constraint(
"ck_shipping_inventory_files_snapshot_status",
"shipping_inventory_files",
type_="check",
)
op.create_check_constraint(
"ck_shipping_inventory_files_snapshot_status",
"shipping_inventory_files",
"snapshot_status IS NULL OR snapshot_status IN ('ready', 'failed', 'expired', 'empty')",
)
def downgrade() -> None:
"""恢复原约束(仅允许 ready/failed/expired)。"""
op.drop_constraint(
"ck_shipping_inventory_files_snapshot_status",
"shipping_inventory_files",
type_="check",
)
op.create_check_constraint(
"ck_shipping_inventory_files_snapshot_status",
"shipping_inventory_files",
"snapshot_status IS NULL OR snapshot_status IN ('ready', 'failed', 'expired')",
)
@@ -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'],
)
+133
View File
@@ -167,3 +167,136 @@ def test_fill_dsv_multi_select_parameter_supports_select_all_checkbox_dropdown()
assert ok is True
assert payloads[-1]["dropdownSelector"] == "#ReportViewerMain_ctl08_ctl17_divDropDown"
assert payloads[-1]["selectAll"] is True
def test_resolve_parameter_controls_jda_report_warehouse_multi_value():
"""JDA 版 On Hand Inventory by Location 的 Warehouse 模板应为多选框下拉(multi_value)。"""
module = _load_module()
controls = module.resolve_parameter_controls("On Hand Inventory by Location", "Warehouse")
assert controls["control"] == "multi_value"
assert controls["text"] == "#ReportViewerMain_ctl08_ctl17_txtValue"
assert controls["toggle"] == "#ReportViewerMain_ctl08_ctl17_ctl01"
assert controls["dropdown"] == "#ReportViewerMain_ctl08_ctl17_divDropDown"
def test_resolve_parameter_controls_3lv_report_warehouse_select():
"""3lv 报表的 Warehouse 模板应是原生 select(ddValue)。"""
module = _load_module()
controls = module.resolve_parameter_controls("On Hand Inventory By Location 3lv", "Warehouse")
assert controls == {
"control": "select",
"selector": "#ReportViewerMain_ctl08_ctl17_ddValue",
}
def test_resolve_parameter_controls_unknown_report_empty():
"""未登记报表名应返回空配置,由调用方回退参数名默认值(保持旧行为)。"""
module = _load_module()
assert module.resolve_parameter_controls("On Hand Inventory by Location XX", "Warehouse") == {}
assert module.resolve_parameter_controls(None, "Warehouse") == {}
def test_fill_dsv_multi_select_select_all_via_report_template():
"""selectors 缺省时,应按报表模板解析控件并完成全选(AWSAMS Warehouse 场景)。"""
module = _load_module()
payloads: list[dict[str, object]] = []
class _FakeLocator:
first = None
def __init__(self) -> None:
self.first = self
def wait_for(self, *args, **kwargs) -> None:
return None
def input_value(self, timeout: int | None = None) -> str:
return ""
def click(self, timeout: int | None = None, force: bool = False) -> None:
return None
class _FakeReportRootLocator:
def count(self) -> int:
return 1
class _FakeFrame:
def locator(self, selector: str):
if selector == "#ReportViewerMain":
return _FakeReportRootLocator()
return _FakeLocator()
def evaluate(self, script: str, payload: dict[str, object]) -> bool:
payloads.append(payload)
return True
class _FakePage:
frames = [_FakeFrame()]
ok = module.fill_dsv_multi_select_parameter(
_FakePage(),
"Warehouse",
["RTM"],
selectors=None,
select_all=True,
browser_timeout_ms=lambda: 3_000,
report_name="On Hand Inventory by Location",
)
assert ok is True
assert payloads[-1]["dropdownSelector"] == "#ReportViewerMain_ctl08_ctl17_divDropDown"
assert payloads[-1]["selectAll"] is True
def test_fill_dsv_filter_if_needed_jda_report_uses_template_multi_value():
"""单一值填充 Warehouse 时,JDA 报表应走模板登记的多选框下拉而非默认 select。"""
module = _load_module()
payloads: list[dict[str, object]] = []
class _FakeLocator:
first = None
def __init__(self) -> None:
self.first = self
def wait_for(self, *args, **kwargs) -> None:
return None
def input_value(self, timeout: int | None = None) -> str:
return ""
def click(self, timeout: int | None = None, force: bool = False) -> None:
return None
class _FakeReportRootLocator:
def count(self) -> int:
return 1
class _FakeFrame:
def locator(self, selector: str):
if selector == "#ReportViewerMain":
return _FakeReportRootLocator()
return _FakeLocator()
def evaluate(self, script: str, payload: dict[str, object]) -> bool:
payloads.append(payload)
return True
class _FakePage:
frames = [_FakeFrame()]
def get_by_text(self, text: str, exact: bool = False):
raise RuntimeError("not visible")
module.fill_dsv_filter_if_needed(
_FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"Warehouse",
"RTM",
env=lambda name, default="": default,
browser_timeout_ms=lambda: 3_000,
report_name="On Hand Inventory by Location",
)
assert payloads, "应进入多选框下拉填充路径而不是无痕失败"
assert payloads[-1]["dropdownSelector"] == "#ReportViewerMain_ctl08_ctl17_divDropDown"
+157 -51
View File
@@ -263,6 +263,65 @@ def test_batch_invalid_trigger_rejection_preserves_batch_callback_id(monkeypatch
assert callbacks[0][1]["identity_errors"] == ["inventory_sources[0].expected_warehouse_id"]
def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp_path):
"""定时排程 batch 按 run 计价:无逐源任务身份也应执行并按 run 回调,而非拒绝。"""
worker = _load_freight_rpa_worker()
trigger_dir = tmp_path / "triggers"
drop_dir = tmp_path / "drop"
processed_dir = trigger_dir / "processed"
failed_dir = trigger_dir / "failed"
trigger_dir.mkdir()
drop_dir.mkdir()
trigger_path = trigger_dir / "inventory_export_batch_scheduled.json"
# 与 run_shipping_inventory_rpa_schedule 写入的 trigger 形状一致:
# batch 级无 task_no,逐源无 task_no/source_run_no/lease_token/candidate_set_id/execution_id/gate_id。
trigger_path.write_text(json.dumps({
"action": "inventory_export_batch",
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": "RUN-SCHEDULED:batch:C1",
"batch_run_no": "RUN-SCHEDULED",
"run_no": "RUN-SCHEDULED",
"trigger_type": "scheduled",
"schedule_run_id": 713,
"requested_at": "2026-08-26T04:47:05.323691",
"inventory_sources": [{
"source_code": "DSV360_AWSDU",
"connector_type": "dbs",
"worker_connector_type": "dsv360",
"warehouse_id": "AWSDU",
"login_url": "https://s360.dbschenker.com/",
"entry_url": "https://s360.dbschenker.com/",
"navigation": {},
"parameters": [],
"query": {},
"credential_envelope": {},
"validation_run_no": None,
}],
}), encoding="utf-8")
callbacks: list[tuple[str, dict]] = []
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready"))
assert completed["schedule_run_id"] == 713
assert completed["trigger_type"] == "scheduled"
result = completed["results"][0]
assert result["source_code"] == "DSV360_AWSDU"
assert result["warehouse_id"] == "AWSDU"
assert result["status"] == "success"
# 每完成一个站点应回传一次累计进度,供后端实时回写排程 run 笔数。
progress = next(body for path, body in callbacks if path.endswith("/inventory-batch-progress"))
assert progress["schedule_run_id"] == 713
assert progress["batch_run_no"] == "RUN-SCHEDULED"
assert progress["success_count"] == 1
assert progress["skipped_count"] == 0
assert progress["failed_count"] == 0
assert (processed_dir / trigger_path.name).is_file()
assert not (failed_dir / trigger_path.name).exists()
def test_batch_interrupt_keeps_trigger_and_completes_best_effort_browser_cleanup(monkeypatch, tmp_path):
"""Ctrl+C 中断导出时不回调或移动 trigger,且清理异常不能阻止停止 Playwright。"""
worker = _load_freight_rpa_worker()
@@ -862,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:
@@ -892,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))
@@ -916,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:
@@ -932,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")
@@ -977,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)
@@ -998,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
@@ -1130,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()
@@ -1766,6 +1835,43 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
assert filled == {"#ReportViewerMain_ctl08_ctl03_txtValue": "CADU-0000000100"}
def test_fill_dsv_filter_if_needed_accepts_report_name_kwarg():
"""_fill_dsv_filter_if_needed 包装层必须透传 report_name(报表控件模板依赖)。"""
worker = _load_freight_rpa_worker()
filled: dict[str, str] = {}
class _FakeText:
first = None
def __init__(self) -> None:
self.first = self
def is_visible(self, timeout: int | None = None) -> bool:
return False
class _FakeFrame:
def evaluate(self, script: str, payload: dict[str, str], timeout: int | None = None) -> bool:
assert "disabled = false" in script
filled[payload["selector"]] = payload["value"]
return True
class _FakePage:
frames = [_FakeFrame()]
def get_by_text(self, text: str, exact: bool = False) -> _FakeText:
return _FakeText()
worker._fill_dsv_filter_if_needed(
_FakePage(),
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
"Owner",
"CADU-0000000100",
report_name="On Hand Inventory by Location",
)
assert filled == {"#ReportViewerMain_ctl08_ctl03_txtValue": "CADU-0000000100"}
def test_validate_inventory_excel_accepts_real_report_shape(tmp_path):
"""下载完成后必须能打开 Excel,并包含库存报表标题和关键表头。"""
worker = _load_freight_rpa_worker()
@@ -38,7 +38,7 @@ def test_fill_report_parameter_multi_select(monkeypatch):
page = MagicMock()
calls: list[tuple[str, str, list[str]]] = []
def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False):
def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False, report_name=None):
calls.append((selector_env, label, list(values)))
monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi)
@@ -60,7 +60,7 @@ def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
page = MagicMock()
calls: list[dict[str, object]] = []
def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False):
def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False, report_name=None):
calls.append(
{
"selector_env": selector_env,
@@ -92,6 +92,66 @@ def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
]
def test_fill_report_parameter_multi_select_jda_report_passes_template_selectors(monkeypatch):
"""传入 JDA 报表名时,multi_select 应向 checkbox 下拉处理链路透传 report_name 用于模板解析。"""
worker = _load_dsv_report_export()
page = MagicMock()
calls: list[dict[str, object]] = []
def _fake_multi(page_arg, selector_env, label, values, *, selectors=None, select_all=False, report_name=None):
calls.append(
{
"selector_env": selector_env,
"label": label,
"values": list(values),
"selectors": selectors,
"select_all": select_all,
"report_name": report_name,
}
)
monkeypatch.setattr(worker, "_fill_dsv_multi_select", _fake_multi)
worker._fill_report_parameter(
page,
{
"name": "Warehouse",
"mode": "multi_select",
"select_all": True,
"values": ["RTM"],
},
report_name="On Hand Inventory by Location",
)
assert calls == [
{
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
"label": "Warehouse",
"values": ["RTM"],
"selectors": None,
"select_all": True,
"report_name": "On Hand Inventory by Location",
}
]
def test_dsv_report_inventory_rows_polls_until_detail_rows_render(monkeypatch):
"""明细行异步渲染时应轮询等待,而不是单次快照误判为无数据。"""
worker = _load_dsv_report_export()
outcomes = iter([False, False, True])
def _fake_rows(page_arg):
return next(outcomes, False)
monkeypatch.setattr(worker, "_dsv_report_has_inventory_data_rows", _fake_rows)
assert worker._wait_dsv_report_inventory_rows(page=object(), timeout_ms=5_000) is True
def test_dsv_report_inventory_rows_returns_false_when_no_data_within_deadline(monkeypatch):
"""超时前始终无明细行时应返回 False(交由调用方判定 skip)。"""
worker = _load_dsv_report_export()
monkeypatch.setattr(worker, "_dsv_report_has_inventory_data_rows", lambda page_arg: False)
assert worker._wait_dsv_report_inventory_rows(page=object(), timeout_ms=2_500) is False
def test_download_dsv360_inventory_delegates_to_shared_export(monkeypatch):
"""单票 DSV 导出应走与批量相同的 session + export 函数。"""
worker = _load_worker()
@@ -321,8 +381,8 @@ def test_dsv_existing_portal_session_skips_all_auth_probes(monkeypatch):
auth_ready.assert_not_called()
def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatch):
"""program/report 变化时仍应回 portal 首页。"""
def test_prepare_dsv_batch_export_no_reset_when_navigation_differs(monkeypatch):
"""program/report 变化时应直接在当前页导航(不再整页重置首页)。"""
worker = _load_dsv_report_export()
page = MagicMock()
reset = MagicMock()
@@ -347,10 +407,70 @@ def test_prepare_dsv_batch_export_resets_home_when_navigation_differs(monkeypatc
}
assert worker._prepare_dsv_batch_export_step(page, "https://s360.dbschenker.com/", prev, curr, index=1) is False
reset.assert_called_once()
reset.assert_not_called()
reuse.assert_not_called()
def test_navigate_dsv_to_report_form_retries_once_with_home_reset(monkeypatch):
"""导航直连失败时应整页重置首页并重试一次(防旧 SSRS 状态串站)。"""
worker = _load_dsv_report_export()
page = MagicMock()
monkeypatch.setattr(worker, "_env", lambda key, default=None: "")
menu = MagicMock(side_effect=[RuntimeError("menu not found"), None])
monkeypatch.setattr(worker, "_click_dsv_reports_menu", menu)
monkeypatch.setattr(worker, "_wait_for_dsv_reports_open", MagicMock())
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
reset = MagicMock()
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
monkeypatch.setattr(worker, "_report_dsv_chain_stage", MagicMock())
source = {
"entry_url": "https://s360.dbschenker.com/main/portal",
"navigation": {
"program_group": "Singapore",
"program_label": "AWSSG - Prod (JDA)",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location",
},
}
assert worker._navigate_dsv_to_report_form(page, source) == "On Hand Inventory by Location"
reset.assert_called_once_with(page, "https://s360.dbschenker.com/main/portal")
def test_navigate_dsv_to_report_form_raises_when_retry_fails(monkeypatch):
"""重置首页后重试仍失败时应上抛原始导航异常(含 error 阶段日志)。"""
worker = _load_dsv_report_export()
page = MagicMock()
monkeypatch.setattr(worker, "_env", lambda key, default=None: "")
monkeypatch.setattr(worker, "_click_dsv_reports_menu", MagicMock(side_effect=RuntimeError("menu not found")))
monkeypatch.setattr(worker, "_wait_for_dsv_reports_open", MagicMock())
monkeypatch.setattr(worker, "_click_dsv_menu_item", MagicMock())
monkeypatch.setattr(worker, "_click_dsv_report_group", MagicMock())
monkeypatch.setattr(worker, "_wait_for_dsv_report_form_ready", MagicMock())
reset = MagicMock()
monkeypatch.setattr(worker, "_reset_dsv_export_entry", reset)
chain = MagicMock()
monkeypatch.setattr(worker, "_report_dsv_chain_stage", chain)
source = {
"entry_url": "https://s360.dbschenker.com/main/portal",
"navigation": {
"program_group": "Singapore",
"program_label": "AWSSG - Prod (JDA)",
"report_group": "Inventory",
"report_name": "On Hand Inventory by Location",
},
}
import pytest
with pytest.raises(RuntimeError, match="menu not found"):
worker._navigate_dsv_to_report_form(page, source)
reset.assert_called_once_with(page, "https://s360.dbschenker.com/main/portal")
assert any(call.args[:2] == ("report_navigation", "error") for call in chain.call_args_list)
def test_reset_dsv_export_entry_skips_login_when_session_active(monkeypatch):
"""同 entry_url 且 session 有效时 reset 不应再触发 auto_login,但应 goto portal 首页。"""
worker = _load_dsv_report_export()
@@ -0,0 +1,97 @@
"""
tests/test_inventory_snapshot_store_read_cache.py
用途:库存快照「最新 ready」查找的请求内缓存回归测试。
逻辑:同一 (source_code, warehouse_id) 在同一请求内只查一次 DB;
快照行写入(新增/过期)后缓存必须失效,保证写后读可见。
"""
from datetime import datetime, timedelta
from sqlalchemy import event
from app import db
from app.models import ShippingInventoryFile
from app.services.shipping_notice.inventory_snapshot_store import (
expire_snapshot,
find_latest_ready_snapshot,
)
def _seed_snapshot(*, inventory_file_no: str, source_code: str, warehouse_id: str, tmp_path, exported_at=None):
"""写入一个 ready 且文件真实存在(freshness 通过)的快照行。"""
path = tmp_path / f'{inventory_file_no}.xlsx'
path.write_bytes(b'placeholder')
row = ShippingInventoryFile(
inventory_file_no=inventory_file_no,
storage_path=str(path),
source_code=source_code,
warehouse_id=warehouse_id,
snapshot_status='ready',
exported_at=exported_at or datetime.utcnow(),
expires_at=datetime.utcnow() + timedelta(hours=1),
)
db.session.add(row)
db.session.commit()
return row
def _count_sql(call) -> int:
"""统计 call 执行期间的 SQL 语句数。"""
count = 0
def _capture(conn, cursor, statement, parameters, context, executemany):
nonlocal count
count += 1
event.listen(db.engine, 'before_cursor_execute', _capture)
try:
call()
finally:
event.remove(db.engine, 'before_cursor_execute', _capture)
return count
def test_find_latest_ready_snapshot_caches_result_per_request(app, tmp_path):
"""同一请求内重复查找同一 (source, warehouse) 只查一次 DB。"""
with app.app_context():
_seed_snapshot(inventory_file_no='FA-CACHE-1', source_code='DSV360_CACHE', warehouse_id='WH1', tmp_path=tmp_path)
first = find_latest_ready_snapshot('DSV360_CACHE', 'WH1')
sql_count = _count_sql(lambda: find_latest_ready_snapshot('DSV360_CACHE', 'WH1'))
# 关键断言:缓存命中且为同一实例;SQL 数为 0(首次查询发生在计数之前)。
assert first is not None
assert sql_count == 0
def test_find_latest_ready_snapshot_cache_cleared_on_new_snapshot(app, tmp_path):
"""本请求新写入更快的快照后,再次查找必须看到最新行(缓存失效)。"""
with app.app_context():
_seed_snapshot(inventory_file_no='FA-CACHE-OLD', source_code='DSV360_CACHE', warehouse_id='WH1', tmp_path=tmp_path)
older = find_latest_ready_snapshot('DSV360_CACHE', 'WH1')
assert older is not None
newer = _seed_snapshot(
inventory_file_no='FA-CACHE-NEW', source_code='DSV360_CACHE', warehouse_id='WH1', tmp_path=tmp_path,
exported_at=datetime.utcnow() + timedelta(seconds=2),
)
found = find_latest_ready_snapshot('DSV360_CACHE', 'WH1')
# 关键断言:新写入已被下一次读取发现,不能停留在请求内缓存旧结果。
assert found is not None and found.id == newer.id
def test_find_latest_ready_snapshot_cache_cleared_on_expire(app, tmp_path):
"""快照过期写入后缓存失效:再次查找重新查询并返回 None。"""
with app.app_context():
row = _seed_snapshot(inventory_file_no='FA-CACHE-EXPIRE', source_code='DSV360_CACHE', warehouse_id='WH1', tmp_path=tmp_path)
assert find_latest_ready_snapshot('DSV360_CACHE', 'WH1') is not None
expire_snapshot(row, 'test-expire')
db.session.commit()
sql_count = _count_sql(lambda: find_latest_ready_snapshot('DSV360_CACHE', 'WH1'))
assert sql_count == 1
assert find_latest_ready_snapshot('DSV360_CACHE', 'WH1') is None
@@ -284,6 +284,56 @@ def test_inventory_loaded_response_syncs_affected_order_task_progress(monkeypatc
assert synced == [task, linked_task]
def test_inventory_loaded_response_clears_stale_match_state(monkeypatch):
"""库存重新载入/复用后必须清空任务级旧匹配结果,避免旧缺货/旧 match_status 残留。"""
from app.services.shipping_notice import inventory_mapping_workflow as workflow
task = SimpleNamespace(
id=1, task_no="SN-INV-CLEAR", inventory_lines_json=None,
match_status="unfulfillable", line_results_json=[{"a": 1}], shortage_json={"lines": []},
)
linked_task = SimpleNamespace(
id=2, task_no="SN-INV-CLEAR-LINKED", inventory_lines_json=None,
match_status="unfulfillable", line_results_json=None, shortage_json=None,
)
inventory_file = SimpleNamespace(inventory_file_no="INV-CLEAR")
monkeypatch.setattr(workflow, "active_inventory_file_for_task", lambda _task: inventory_file)
monkeypatch.setattr(
workflow,
"apply_inventory_parse_result_to_linked_tasks",
lambda *_args, **_kwargs: [task, linked_task],
)
monkeypatch.setattr(workflow, "task_line_purpose_values", lambda _task: [])
monkeypatch.setattr(workflow, "build_field_alignment_preview", lambda *_args, **_kwargs: {})
monkeypatch.setattr(workflow, "set_task_step_progress", lambda *_args, **_kwargs: None)
monkeypatch.setattr(workflow, "apply_task_transition", lambda *_args, **_kwargs: None)
monkeypatch.setattr(workflow, "log_task_event", lambda *_args, **_kwargs: None)
monkeypatch.setattr(workflow, "serialize_task_for_tool", lambda _task: {})
monkeypatch.setattr(workflow, "tool_response", lambda **kwargs: kwargs)
monkeypatch.setattr(workflow.db.session, "flush", lambda: None)
monkeypatch.setattr(
"app.services.shipping_notice.order_task_stage_machine.sync_order_task_stage_for_notice",
lambda notice: None,
)
workflow.inventory_loaded_response(
task,
[{"part_number": "A001", "qty": 1}],
source="rpa",
event_type="inventory_rpa_loaded",
commit=False,
)
# 库存内容变更后,task 与其同库存文件的关联任务都不能再读旧匹配结果。
assert task.match_status is None
assert task.line_results_json is None
assert task.shortage_json is None
assert linked_task.match_status is None
assert linked_task.line_results_json is None
assert linked_task.shortage_json is None
def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantity_selection(app, tmp_path):
"""多个 Source 候选仅按 Reservation + PN 的唯一快照命中确定,数量为零也不改选其他 Source。"""
from app.services.shipping_notice.inventory_source_rules import (
@@ -724,6 +724,122 @@ def test_schedule_batch_rejects_mismatched_run_no(app, tmp_path):
assert run.status == "running"
def test_scheduled_batch_progress_updates_run_counts(app):
"""定时 batch 进度回调应实时回写排程 run 的累计笔数。"""
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-PROGRESS",
username="schedule_inv_progress_user",
)
run = ScheduleRun(
run_no="RUN-PROGRESS",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=2,
response_summary_json={"awaiting_rpa": True, "pending_details": []},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
result = report_inventory_batch_progress({
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": "RUN-PROGRESS:batch:C1",
"batch_run_no": "RUN-PROGRESS",
"run_no": "RUN-PROGRESS",
"schedule_run_id": run.id,
"success_count": 1,
"skipped_count": 0,
"failed_count": 1,
})
db.session.refresh(run)
assert result["status"] == "ok"
assert (result.get("data") or {}).get("progress_status") == "updated"
assert run.success_count == 1
assert run.failed_count == 1
assert run.skipped_count == 0
assert run.status == "running"
assert (run.response_summary_json or {}).get("progress", {}).get("success_count") == 1
def test_scheduled_batch_progress_rejects_mismatched_run_no(app):
"""进度回调 run_no 与排程 run 不一致时必须拒绝,且不改变 run 计数。"""
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-PROGRESS-MISMATCH",
username="schedule_progress_mismatch_user",
)
run = ScheduleRun(
run_no="RUN-PROGRESS-EXPECTED",
schedule_task_id=task.id,
status="running",
started_at=datetime.utcnow(),
total_count=1,
response_summary_json={"awaiting_rpa": True, "pending_details": []},
step_logs=[{"step": "shipping_inventory_rpa", "status": "awaiting_rpa_callback"}],
)
db.session.add(run)
db.session.commit()
result = report_inventory_batch_progress({
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": "RUN-PROGRESS-WRONG:batch:C1",
"batch_run_no": "RUN-PROGRESS-WRONG",
"schedule_run_id": run.id,
"success_count": 1,
"skipped_count": 0,
"failed_count": 0,
})
db.session.refresh(run)
assert result["status"] == "failed"
assert (result.get("data") or {}).get("schedule_run_error") == "schedule_run_no_mismatch"
assert run.success_count == 0
def test_scheduled_batch_progress_noop_after_finalized(app):
"""run 已终态(不再 awaiting)时进度回调应为 no-op,不修改计数。"""
from app.services.shipping_notice.inventory_rpa_workflow import report_inventory_batch_progress
with app.app_context():
task = _make_inventory_schedule_task(
schedule_no="SCH-INV-PROGRESS-FINAL",
username="schedule_progress_final_user",
)
run = ScheduleRun(
run_no="RUN-PROGRESS-FINAL",
schedule_task_id=task.id,
status="success",
started_at=datetime.utcnow(),
finished_at=datetime.utcnow(),
total_count=1,
success_count=1,
failed_count=0,
skipped_count=0,
)
db.session.add(run)
db.session.commit()
result = report_inventory_batch_progress({
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": "RUN-PROGRESS-FINAL:batch:C1",
"batch_run_no": "RUN-PROGRESS-FINAL",
"schedule_run_id": run.id,
"success_count": 1,
"skipped_count": 0,
"failed_count": 0,
})
assert result["status"] == "failed"
assert (result.get("data") or {}).get("schedule_run_error") == "schedule_run_not_awaiting"
def test_scheduled_batch_success_rejects_missing_warehouse_id(app, tmp_path):
"""定时 batch 成功项缺少 Warehouse 时必须拒绝,不能仅凭 Source 入库。"""
from app.models import ShippingInventoryFile
@@ -335,7 +335,8 @@ def test_serialize_task_summary_projects_only_current_notice_line_facts(app):
assert data['business_no'] == 'WVC26082301'
assert data['notice_line_summary'] == [{
'line_no': '00010', 'part_number': 'PART-FIRST', 'customer_part_number': None,
'line_no': '00010', 'line_no_source': 'field', 'part_number': 'PART-FIRST',
'customer_part_number': None,
'reservation_id': 'RES-1', 'shipment_qty': '12.00000000', 'available_qty': '20',
'shortage_qty': '0', 'inventory_status': 'ready',
}]
@@ -377,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():
@@ -222,6 +222,82 @@ def test_upload_to_freight_manual_confirm_does_not_hard_reject(app, monkeypatch)
assert ok.get("forbidden_next_tools") in (None, [])
def test_upload_to_freight_manual_confirm_ignores_inventory_source_stability(app, monkeypatch) -> None:
"""回归锁:人工确认已上传不依赖库存源稳定性。
原缺陷:upload_to_freight 在 mode 分支之前统一做 is_inventory_source_stable 门禁,
库存源未稳定(或冻结指纹/配置版本与运行时不一致)时 manual_confirm 被 failed 拦截,
任务永远停在 manual_upload_handoff。修复后仅 auto/retry 路径校验库存源。
"""
with app.app_context():
from app import db
from types import SimpleNamespace
task = ShippingNotice(
task_no="SN-STP-MANUAL-CFM-UNSTABLE",
source_type="manual",
export_file_path="/tmp/m.xlsx",
export_file_name="m.xlsx",
inventory_source_status="resolved",
inventory_source_code="SRC1",
inventory_connector_type="crane",
inventory_source_config_version="stale-version",
inventory_routing_fingerprint="stale-fingerprint",
)
db.session.add(task)
db.session.commit()
attempt = SimpleNamespace(id=10, artifact_id=3, operator_id=42)
# 关键:模拟库存源确实不稳定(真实 is_inventory_source_stable 返回 False)。
monkeypatch.setattr(
"app.services.shipping_notice.fulfillment_workflow.is_inventory_source_stable",
lambda _t: False,
)
monkeypatch.setattr(
"app.services.shipping_notice.fulfillment_workflow.customer_gate_tool_response",
lambda *a, **k: None,
)
monkeypatch.setattr(
"app.services.shipping_notice.fulfillment_workflow.field_conflict_gate_response",
lambda *a, **k: None,
)
monkeypatch.setattr(
"app.services.shipping_notice.fulfillment_workflow._reservation_gate_response",
lambda *a, **k: None,
)
monkeypatch.setattr(
"app.services.shipping_notice.fulfillment_workflow._task_disposition_gate_response",
lambda *a, **k: None,
)
monkeypatch.setattr(
"app.services.shipping_notice.fulfillment_workflow.record_manual_upload",
lambda *a, **k: attempt,
)
monkeypatch.setattr(
"app.services.shipping_notice.fulfillment_audit.record_fulfillment_audit",
lambda **k: None,
)
monkeypatch.setattr(
"app.services.shipping_notice.workflow_ledger_service.find_item_by_current_task_no",
lambda **k: None,
)
ok = upload_to_freight({
"task_id": task.task_no,
"mode": "manual_confirm",
"operator_id": 42,
"artifact_id": 3,
})
# 断言:库存源不稳定不得阻断人工确认登记。
assert ok["status"] == "ok"
# 断言:RPA 路径仍受库存源门禁保护(行为不变)。
rejected = upload_to_freight({"task_id": task.task_no, "mode": "retry_upload"})
assert rejected["status"] == "failed"
assert "库存源尚未确定" in str(rejected.get("message") or "")
def test_upload_to_freight_manual_confirm_propagates_close_item_failure(app, monkeypatch) -> None:
"""关键断言:绑定 WorkflowItem 关闭失败须向上抛出,不得吞异常后仍返回成功。"""
with app.app_context():
@@ -405,6 +405,8 @@ def test_stp_facts_projects_line_resolutions(app) -> None:
assert stage_context["preparation"]["status"] == "ready"
assert stage_context["preparation"]["lines"] == [{
"line_key": None,
"line_no": "1",
"line_no_source": "sequence",
"reservation_id": "3000092917",
"part_number": "PN-1",
"required_qty": None,
@@ -452,6 +454,8 @@ def test_stage_context_prefers_current_structured_inventory_match(app) -> None:
assert preparation["has_match_result"] is True
assert preparation["lines"] == [{
"line_key": "line-1",
"line_no": "1",
"line_no_source": "sequence",
"reservation_id": "RSV-1",
"part_number": "PN-1",
"required_qty": "10",
@@ -483,6 +487,8 @@ def test_stage_context_keeps_frozen_order_lines_when_inventory_match_is_not_read
# 关键断言:冻结订单与库存匹配是两类事实;无库存文件不能抹掉订单行。
assert preparation["frozen_order_lines"] == [{
"line_key": "line-frozen-1",
"line_no": "1",
"line_no_source": "sequence",
"reservation_id": "RSV-FROZEN",
"part_number": "PN-FROZEN",
"required_qty": "6.00000000",
@@ -0,0 +1,120 @@
"""
backend/tests/test_shipping_order_line_no_resolver.py
用途:order_line_no_resolver 单一解析器契约测试(项次展示/导出同源)。
依赖:pytest、resolver、field_rules 格式门禁。
逻辑:覆盖 field 真实值 / customer_po_line_no 回退 / sequence 展示序号 / 全空缺失四级分支,
并验证 field_id 键与历史 field_code 键两种入参格式;mark 为 pure_unit 跳过 Flask 创建。
"""
import pytest
from app.services.shipping_notice.order_line_no_resolver import (
LINE_NO_SOURCE_CUSTOMER_PO_LINE,
LINE_NO_SOURCE_FIELD,
LINE_NO_SOURCE_SEQUENCE,
field_id_by_code_from_definition,
resolve_order_line_no,
)
LINE_NO_ID = 'line-no-id'
CUSTOMER_PO_LINE_ID = 'customer-po-line-id'
FIELD_ID_BY_CODE = {
'line_no': LINE_NO_ID,
'customer_po_line_no': CUSTOMER_PO_LINE_ID,
}
@pytest.mark.pure_unit
def test_resolver_prefers_real_line_no_field_value():
"""line_no 字段真实值必须优先于客户 PO 行号与序号。"""
assert resolve_order_line_no(
field_values={LINE_NO_ID: '00010', CUSTOMER_PO_LINE_ID: '00020'},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=1,
) == {'value': '00010', 'source': LINE_NO_SOURCE_FIELD}
@pytest.mark.pure_unit
def test_resolver_prefers_real_line_no_over_sequence_and_customer():
"""line_no 缺失时按顺序回退 customer_po_line_no,不直接落序号。"""
assert resolve_order_line_no(
field_values={CUSTOMER_PO_LINE_ID: '10'},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=1,
) == {'value': '10', 'source': LINE_NO_SOURCE_CUSTOMER_PO_LINE}
@pytest.mark.pure_unit
def test_resolver_rejects_invalid_customer_line_no_format():
"""客户 PO 行号格式非法(非 1–6 位数字)时不得当业务项次,回退展示序号。"""
assert resolve_order_line_no(
field_values={'line_no': None, CUSTOMER_PO_LINE_ID: 'ABC'},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=2,
) == {'value': '2', 'source': LINE_NO_SOURCE_SEQUENCE}
@pytest.mark.pure_unit
def test_resolver_uses_sequence_when_business_fields_missing():
"""line_no 与 customer_po_line_no 均缺失时仅能使用显式标注的展示序号。"""
assert resolve_order_line_no(
field_values={'line_no': None},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=3,
) == {'value': '3', 'source': LINE_NO_SOURCE_SEQUENCE}
@pytest.mark.pure_unit
def test_resolver_missing_everything_returns_none_source():
"""全部事实缺失且无序号时返回 None/None,禁止伪造空字符串或 0。"""
assert resolve_order_line_no(
field_values={},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=None,
) == {'value': None, 'source': None}
@pytest.mark.pure_unit
def test_resolver_supports_legacy_field_code_keys():
"""历史/测试数据按 field_code 键存储时,解析器仍能正确读取。"""
assert resolve_order_line_no(
field_values={'line_no': '00020', 'customer_po_line_no': '00030'},
field_id_by_code=None,
fallback_sequence=5,
) == {'value': '00020', 'source': LINE_NO_SOURCE_FIELD}
@pytest.mark.pure_unit
def test_resolver_fallbacks_to_code_key_when_field_id_missing():
"""field_id 键缺失时回退读取 field_code 键,避免跨格式读取失败。"""
assert resolve_order_line_no(
field_values={CUSTOMER_PO_LINE_ID: '10', 'customer_po_line_no': '20'},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=1,
) == {'value': '10', 'source': LINE_NO_SOURCE_CUSTOMER_PO_LINE}
@pytest.mark.pure_unit
def test_resolver_keeps_leading_zeros():
"""项次原样输出,保留前导零(如 00010),禁止转 int 丢零。"""
assert resolve_order_line_no(
field_values={'line_no': '00010'},
field_id_by_code=FIELD_ID_BY_CODE,
fallback_sequence=1,
) == {'value': '00010', 'source': LINE_NO_SOURCE_FIELD}
@pytest.mark.pure_unit
def test_field_id_by_code_from_definition_extracts_only_pair():
"""Schema 定义中仅提取同时具备 field_code/field_id 的字段。"""
definition = {'fields': [
{'field_code': 'line_no', 'field_id': 'a', 'scope': 'line'},
{'field_code': 'customer_po_line_no', 'field_id': 'b'},
{'field_code': 'orphan', 'field_id': None},
'invalid',
]}
assert field_id_by_code_from_definition(definition) == {
'line_no': 'a',
'customer_po_line_no': 'b',
}
@@ -2673,3 +2673,154 @@ def test_unvalidated_draft_is_not_projected_as_build_blocked(app):
assert eligibility['status'] == 'not_validated'
assert eligibility['can_build'] is None
def _seed_extra_document(*, intake, user, suffix) -> ShippingOrderDocument:
"""为多 PDF 同批次测试向同一 Intake 追加一个附件 Document。"""
asset = FileAsset(
asset_no=f'FA-{suffix}',
owner_user_id=user.id,
original_filename=f'orders-{suffix}.pdf',
storage_provider='minio',
storage_bucket='test',
storage_key=f'temporary/{user.id}/orders-{suffix}.pdf',
content_hash=(suffix.lower() * 64)[:64],
file_size=100,
mime_type='application/pdf',
upload_status='ready',
lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
document = ShippingOrderDocument(
intake_id=intake.id,
asset_id=asset.id,
document_type='attachment',
attachment_key=f'orders-{suffix}.pdf',
filename=f'orders-{suffix}.pdf',
content_hash=(suffix.upper() * 64)[:64],
classification='order_notice',
parse_status='parsed',
)
db.session.add(document)
db.session.flush()
return document
def _capture_sql_statements(statements: list[str]):
"""SQLAlchemy 语句捕获监听器,供读模型查询数回归测试使用。"""
def _capture(conn, cursor, statement, parameters, context, executemany):
statements.append(str(statement))
return _capture
def test_review_run_serialization_keeps_query_count_flat_with_case_count(app):
"""
回归:Run 摘要投影必须批量预取候选 / Draft / Intake / STP Job,
SQL 数不得随 Case 数线性放大(防 N+1 复发拖慢工作台首屏)。
"""
from sqlalchemy import event
with app.app_context():
user, agent, session, intake, first_document = _seed_run_input(suffix='PERF-FLAT-RUN')
extra_documents = [
_seed_extra_document(intake=intake, user=user, suffix='PERF-FLAT-RUN-B'),
_seed_extra_document(intake=intake, user=user, suffix='PERF-FLAT-RUN-C'),
]
documents = [first_document] + extra_documents
db.session.flush()
run, _ = create_order_extraction_run(
user=user, agent_id=agent.id, conversation_id=session.session_id,
intake_nos=[intake.intake_no],
)
ensure_order_extraction_plan(run)
for unit in run.extraction_plan.units:
unit.status = 'candidate_ready'
unit.result_json = {
'orders': [{
'header_fields': [{'field_id': 'po-id', 'observations': [{'value': 'PO-1'}]}],
'lines': [{'fields': [{'field_id': 'part-id', 'observations': [{'value': 'A001'}]}]}],
'conflicts': [],
}],
}
for document in documents:
db.session.add(ShippingOrderCandidate(
candidate_no=f'CAND-{document.id}',
intake_id=intake.id,
primary_document_id=document.id,
candidate_key=f'perf-flat-{document.id}',
order_extraction_run_id=run.id,
candidate_status='provisional',
))
db.session.commit()
cases = ensure_run_review_cases(run=run)
db.session.commit()
assert len(cases) == 3
# 冷会话模拟独立 HTTP 请求:新 scoped session 的 identity map 无预热对象。
run_id = int(run.id)
db.session.remove()
with app.test_request_context():
pending = db.session.get(ShippingOrderProcessingRun, run_id)
statements: list[str] = []
listener = _capture_sql_statements(statements)
event.listen(db.engine, 'before_cursor_execute', listener)
try:
items = serialize_review_run(pending)['items']
finally:
event.remove(db.engine, 'before_cursor_execute', listener)
assert len(items) == 3
# 关键断言:3 个带 Candidate/Draft 的 Case 也必须保持固定数量级读取。
assert len(statements) <= 14
def test_run_lineage_root_walk_loads_parent_runs_without_frozen_snapshot_columns(app):
"""
回归:重解析父链遍历每跳只能窄列读取,禁止全列 SELECT 拉 MB 级
input_snapshot_json / result_json(工作台投影重复解析大 JSON 的根源)。
"""
from sqlalchemy import event
with app.app_context():
user, agent, session, intake, _document = _seed_run_input(suffix='PERF-LINEAGE')
source = _materialized_run(user=user, agent=agent, session=session, intake=intake)
source_case = ensure_run_review_cases(run=source)[0]
transition_order_extraction_run(source, target_status='processing')
transition_order_extraction_run(source, target_status='review_required', result={})
replacement, _ = reparse_case_document(
user_id=user.id, case_no=source_case.case_no, reason='rule_updated',
)
ensure_order_extraction_plan(replacement)
for unit in replacement.extraction_plan.units:
unit.status = 'candidate_ready'
replacement_case = ensure_run_review_cases(run=replacement)[0]
activate_review_case(case=replacement_case, trigger='document_reparse_succeeded')
db.session.commit()
replacement_id = int(replacement.id)
source_id = int(source.id)
db.session.remove()
with app.test_request_context():
latest = db.session.get(ShippingOrderProcessingRun, replacement_id)
from app.services.shipping_notice.order_review_disposition_service import _run_lineage_root
statements: list[str] = []
listener = _capture_sql_statements(statements)
event.listen(db.engine, 'before_cursor_execute', listener)
try:
root = _run_lineage_root(run=latest)
finally:
event.remove(db.engine, 'before_cursor_execute', listener)
assert root.id == source_id
point_loads = [
s for s in statements
if 'shipping_order_processing_runs' in s and 'WHERE shipping_order_processing_runs.id' in s
]
# 关键断言:父链逐跳读取必须存在且为窄列(不含大 JSON 冻结快照)。
assert point_loads, '谱系遍历必须按外键逐跳窄列查询父 Run'
for statement in point_loads:
assert 'input_snapshot_json' not in statement
assert 'result_json' not in statement
@@ -1033,6 +1033,55 @@ def test_process_execution_projection_exposes_server_owned_recovery_targets(app)
assert projection['active_recovery_plans'] == []
def test_process_execution_projection_batch_loads_latest_attempts(app):
"""serialize_process_execution 必须批量预取 LatestAttempt 并写入会话读缓存,避免逐 Gate N+1。"""
from app import db
from app.models import (
ShippingProcessExecution,
ShippingProcessGate,
ShippingProcessGateAttempt,
)
from app.services.shipping_notice.process_gate_projection import serialize_process_execution
with app.app_context():
execution = ShippingProcessExecution(
execution_no='EXE-BATCH-ATTEMPT', status='blocked',
current_gate_code='inventory_matching', lock_version=1,
)
db.session.add(execution)
db.session.flush()
gate = ShippingProcessGate(
execution_id=execution.id, gate_code='inventory_matching', sequence_no=15,
status='blocked_manual', evaluation_version=2,
)
db.session.add(gate)
db.session.flush()
attempt = ShippingProcessGateAttempt(
gate_id=gate.id, attempt_no=1, status='failed',
idempotency_key='exec-batch-attempt-1',
)
db.session.add(attempt)
db.session.flush()
# 把 Gate 的最新 attempt 指针指向该 attempt。
gate.latest_attempt_id = attempt.id
db.session.flush()
# 先清除任何遗留的会话读缓存,模拟工作台路径(ui_state 不预置缓存)。
db.session.info.pop('shipping_conversation_projection_read_cache', None)
projection = serialize_process_execution(execution)
# 调用后应把本 Execution 的 gates + latest_attempt 写入读缓存。
cache = db.session.info.get('shipping_conversation_projection_read_cache') or {}
gates_by_execution = cache.get('gates_by_execution_id', {})
latest_by_id = cache.get('latest_attempt_by_id', {})
assert int(execution.id) in gates_by_execution
assert any(gate.id == g.id for g in gates_by_execution[int(execution.id)])
# current_gate 的 latest 信息必须命中缓存里预取的 attempt,而不是触发额外的 query.get()。
current_gate_latest = projection.get('current_gate', {}).get('latest_attempt')
# 未提供 attempt snapshot / error 时也可能为 None;关键断言是缓存已填充。
assert int(attempt.id) in latest_by_id
def test_recovery_plan_outcome_mapping_is_terminal_or_waiting():
"""RecoveryPlan 必须将 Attempt 结果映射到可审计的计划状态。"""
from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt
@@ -86,3 +86,112 @@ def test_match_step_progress_fulfillable_is_completed_100():
)
assert fields['status'] == 'completed'
assert fields['progress_percent'] == 100
def _patch_released_keys(monkeypatch, *, released_line_keys: set[str]):
"""把放行行键读取替换为给定集合,直接验证聚合/满足性的放行语义。
说明:放行决定读取是纯 SQL join,构造真实 Case/LineDecision 表关系较复杂;
这里只打补丁到 ``_released_line_keys_for_task`` 这个稳定接缝,聚合重算与
``match_completed`` 都会消费它。
"""
from app.services.shipping_notice import fulfillment_workflow as mod
monkeypatch.setattr(mod, '_released_line_keys_for_task', lambda _task: set(released_line_keys))
def test_release_shortage_marks_aggregate_fulfillable(app, monkeypatch):
"""短缺行被人工放行后,聚合重算应视为满足(fulfillable),不再标 unfulfillable。"""
from app.services.shipping_notice.fulfillment_workflow import (
_recompute_task_match_aggregate,
match_completed,
)
with app.app_context():
task = _task_with_current_matches(
task_no='SN-RELEASE-OK',
rows=[{'match_result': 'matched'}, {'match_result': 'matched', 'shortage_qty': '1'}],
)
# 放行前:缺口行未放行 → 整单不满足。
assert match_completed(task) is False
status, _ = _recompute_task_match_aggregate(task)
assert status in {'partial', 'unfulfillable'}
# 放行缺口行(行键 L2)
_patch_released_keys(monkeypatch, released_line_keys={'L2'})
# 放行后:匹配满足;聚合重算不再误判缺货。
assert match_completed(task) is True
status, shortages = _recompute_task_match_aggregate(task)
assert status == 'fulfillable'
assert shortages == []
assert task.line_results_json[1]['line_status'] == 'released'
def test_release_shortage_leaves_unreleased_shortage_blocks(app, monkeypatch):
"""仅放行其中一行,其它未放行缺口仍应阻断整单。"""
from app.services.shipping_notice.fulfillment_workflow import _recompute_task_match_aggregate
with app.app_context():
task = _task_with_current_matches(
task_no='SN-RELEASE-PARTIAL',
rows=[
{'match_result': 'matched', 'shortage_qty': '1'},
{'match_result': 'not_found', 'shortage_qty': '1'},
],
)
# 只放行第一行(L1),L2 的 not_found 缺口未被放行 → 不满足。
_patch_released_keys(monkeypatch, released_line_keys={'L1'})
status, shortages = _recompute_task_match_aggregate(task)
assert status in {'partial', 'unfulfillable'}
assert shortages
def test_recompute_fulfillment_state_syncs_review_pending_on_release(app, monkeypatch):
"""放行后 recompute_task_fulfillment_state 应把 review/pending 从 shortage_review 改为满足态。"""
from app.services.shipping_notice.fulfillment_workflow import (
recompute_task_fulfillment_state,
)
with app.app_context():
task = _task_with_current_matches(
task_no='SN-RECOMPUTE-RELEASE',
rows=[{'match_result': 'matched', 'shortage_qty': '1'}],
)
task.review_status = 'shortage_review'
task.pending_human_reason = 'shortage'
db.session.flush()
_patch_released_keys(monkeypatch, released_line_keys={'L1'})
status = recompute_task_fulfillment_state(task)
assert status == 'fulfillable'
assert task.match_status == 'fulfillable'
assert task.review_status != 'shortage_review'
assert task.pending_human_reason is None
assert task.line_results_json[0]['line_status'] == 'released'
def test_recompute_fulfillment_state_keeps_shortage_when_not_released(app, monkeypatch):
"""未放行的缺口行重算后仍保持 shortage_review,不能把缺货单误标为满足。"""
from app.services.shipping_notice.fulfillment_workflow import (
recompute_task_fulfillment_state,
)
with app.app_context():
task = _task_with_current_matches(
task_no='SN-RECOMPUTE-SHORT',
rows=[{'match_result': 'not_found', 'shortage_qty': '1'}],
)
task.review_status = 'shortage_review'
task.pending_human_reason = 'shortage'
db.session.flush()
# 没有放行决定
_patch_released_keys(monkeypatch, released_line_keys=set())
status = recompute_task_fulfillment_state(task)
assert status in {'partial', 'unfulfillable'}
assert task.review_status == 'shortage_review'
assert task.pending_human_reason == 'shortage'
assert task.line_results_json[0]['line_status'] == 'shortage'
@@ -0,0 +1,71 @@
"""
tests/test_shipping_uploaded_gate_closure.py
用途:锁定「已上传任务确认后,Execution 全部门禁必须收口」与「阶段投影不得被陈旧 Execution Gate 回退」的一致性。
背景:
- 订单生命周期工作台按 has_verified_upload_success / Notice 阶段裁决 → 展示「通知完成」;
- 批次中心 / 对话卡按 OT work-item 的 Execution.current_gate_code 覆盖 stage
(shipping_processing_projection),若该 Gate 仍是前置履约 Gate,会把 stage 回退成「通知准备」。
- sync_fulfillment_gates_from_task 的 STEP 1A 只在 _derived_fulfillment_status==uploaded 时收口全部前置 Gate;
因而 upload_status 未落到 uploaded(预约单未全量/迟回调覆盖)时,前置 Gate 保留,阶段投影即回退。
"""
from __future__ import annotations
from app import db
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
def _mk_execution(task: ShippingNotice) -> ShippingProcessExecution:
"""建正式 20-Gate Execution,并把 inventory_sufficiency 置为人工阻断,让任务停留在「通知准备」。"""
execution = ensure_execution_for_workflow_version(task_id=int(task.id))
task.active_process_execution_id = int(execution.id)
suff = ShippingProcessGate.query.filter_by(
execution_id=execution.id, gate_code='inventory_sufficiency',
).one()
suff.status = 'blocked_manual'
suff.blocking_reason_code = 'inventory_shortage_review_required'
execution.status = 'blocked'
execution.current_gate_code = 'inventory_sufficiency'
db.session.commit()
return execution
def test_step1a_closes_all_gates_when_uploaded(app):
"""upload_status=uploaded → STEP 1A 收口全部前置 Gate,Execution 落到 completed。"""
task = ShippingNotice(task_no='SN-UPLOADED-GATE', upload_status='uploaded', match_status='fulfillable')
db.session.add(task)
db.session.flush()
execution = _mk_execution(task)
sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=1)
db.session.commit()
db.session.refresh(execution)
open_cnt = ShippingProcessGate.query.filter(
ShippingProcessGate.execution_id == int(execution.id),
ShippingProcessGate.status.notin_(('passed', 'skipped')),
).count()
assert open_cnt == 0, f'已上传任务仍有 {open_cnt} 个 Gate 未收口'
assert execution.current_gate_code is None
assert execution.status == 'completed'
def test_missing_upload_status_keeps_gate_stuck(app):
"""upload_status != uploaded → STEP 1A 不触发,前置 Gate 保留(阶段投影可被回退)。"""
task = ShippingNotice(task_no='SN-UPLOAD-NOT-SET', upload_status='partial', match_status='fulfillable')
db.session.add(task)
db.session.flush()
execution = _mk_execution(task)
sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=1)
db.session.commit()
db.session.refresh(execution)
suff = ShippingProcessGate.query.filter_by(
execution_id=execution.id, gate_code='inventory_sufficiency',
).one()
# 关键断言:非 uploaded 时前置 Gate 不能被收口 —— 这正是批次中心回退「通知准备」的根因。
assert suff.status != 'passed'
@@ -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_*`,如存在)。
- 手工:发送带附件消息(附件在前/后)→ 附件立即上屏;解析中 → 进度行显示「生成订单候选 · 正在匹配订单模板」;工作台接收解析「当前附件」秒开;未命中模板+通用解析关闭 → 仅「未命中模板 / 未匹配任何模板 / 通用解析被安全门禁阻断(已本地化原因)」。
+33 -14
View File
@@ -15,9 +15,10 @@
- 订单复核只展示字段、客户、冲突、重复和 Reservation 人工裁决;不得展示库存数量、缺口或上传操作。
- 通知准备只展示冻结订单、库存匹配行和 Excel 产物状态。任务详情的 `ui_state.stage_context.preparation` 是只读摘要;未生成匹配结果时必须明确显示当前 Gate,不能显示“处理结果已完成”。
- 货代上传展示 Excel、RPA 状态、人工确认已上传、失败恢复、未知结果核对和最新上传 Attempt;`freight_upload_rpa` / `manual_upload_handoff` 的动作只落在此工作面。人工确认只提交当前 Notice 的 `business_no`(可选受控 Artifact 标识),不接收回执号、截图或 PDF;未知结果禁止自动重试。
- 通知完成只读展示上传时间、成功 Attempt 和预约单汇总。只有 `has_verified_upload_success(task)`(Task `uploaded`、全部预约单 `uploaded`、关联 Artifact 存在 `ShippingUploadAttempt.status=succeeded`)才进入;历史 `uploaded/completed`、候选/PDF 成功、单独外部参考、取消或归档均不得进入完成统计。
- 通知完成只读展示同 PO 全部已上传发货通知(按 `business_no` 聚合,可展开明细:项次/料号/Reservation/需求数量),并提供「下载本批 ZIP」留底入口(复用 `/shipping-notices/batch/export` 按 business_no 打包)。只有 `has_verified_upload_success(task)`(Task `uploaded`、全部预约单 `uploaded`、关联 Artifact 存在 `ShippingUploadAttempt.status=succeeded`)才进入;未上传通知留在货代上传面处理;历史 `uploaded/completed`、候选/PDF 成功、单独外部参考、取消或归档均不得进入完成统计。
- 桌面右栏 `ReviewCurrentProcessingCard` 是每个 Gate 唯一全局写入口;主区仅显示事实、行级局部操作或被右栏定位的裁决表单。`TaskTodoPanel` 在生命周期工作台仅作无界面动作执行宿主,禁止重复渲染 Gate 或主按钮。
- `stage_context` 不落库、不驱动状态、不授权动作,仅由正式任务详情与单票 `/ui-state` 按需返回;任务列表、聊天轻量投影不加载它,以避免 N+1 查询。
- **OT 阶段随 Gate 推进回写(2026-08-26)**:`_refresh_execution_pointers`(Gate 状态/指针刷新的唯一收口)在 Execution 已绑定任务时补调 `sync_order_task_stage_for_notice`,使 `shipping_order_tasks.stage/status` 与当前 Gate 事实一致(如 `manual_upload_handoff` → `freight_uploading/blocked`),避免右侧「当前任务」主卡/批次投影停留在旧技术阶段(如 `excel_generating`)。建单前执行(无 task_id)不触发。
### Dify 配置边界(2026-08)
@@ -753,7 +754,7 @@ Hxops **货代发货通知 Agent** 的部署、目标架构、Dify 配置、Open
**阶段 7 试点、容量与恢复验收(HXOPS 运维执行)**:
1. 保持 `auto_create_enabled=false` 和 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`,选择 3–5 个高频模板逐个建立独立盲测集;每个模板至少 3 个独立样本全通过并经管理员批准后,才可进入下一模板试点。不得用一个模板的结果覆盖其他模板。
2. 请求级文件数由 `SHIPPING_NOTICE_BATCH_MAX_FILES`(默认 `20`)控制;单文件由 `FILE_ASSET_MAX_SIZE_MB` 控制;EML 展开由 `SHIPPING_NOTICE_EML_MAX_ATTACHMENTS`、`SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES` 和 `SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES` 控制。任一限制超出必须在解析或建单前明确拒绝,不创建 Batch/Task,也不保留临时文件。
2. 单文件由 `FILE_ASSET_MAX_SIZE_MB` 控制;EML 展开由 `SHIPPING_NOTICE_EML_MAX_ATTACHMENTS`、`SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES` 和 `SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES` 控制。任一限制超出必须在解析或建单前明确拒绝,不创建 Batch/Task,也不保留临时文件。
3. 每日试点记录管理员 `GET /api/admin/shipping-notice/order-extraction-runs/health` 的队列、Provider、HXOPS 落库与总时延 P50/P95、失败率、重试与积压;库存 RPA 从配置测试运行记录读取耗时,上传 RPA 从 `ShippingUploadAttempt.started_at/finished_at` 统计。试点累计数据形成正式容量 SLA 前,不提高并发或放开自动建单。
4. 恢复演练在测试环境完成:人为中断 Worker 后重启,确认 stale Job 被恢复、已有 Provider 结果只续做 HXOPS 落库、相同文件重试不重复建单;再从经批准的数据库备份与 RPA 共享目录备份恢复到隔离环境,核对 Artifact、Attempt、Reservation 和审计记录。演练记录必须包含环境、备份时间、操作者、耗时、校验结果及遗留问题;失败时保持自动建单和自动上传关闭。
@@ -1735,7 +1736,7 @@ GET /api/admin/shipping-order-schema/published-contract
- 批量测试创建时各站点先处于 `awaiting_rpa / waiting_worker`。Windows Worker 实际领取某个站点前,会向 `POST /api/shipping-notice/rpa/inventory-configuration-test-batch-progress` 回调该站点的 `validation_run_no` 与受控阶段 `rpa_exporting`;后端仅允许将当前批次的非终态运行写为 `processing / rpa_exporting`。因此管理端可以区分“尚未被 Worker 领取”和“RPA 正在登录并导出”;最终成功、无库存或失败仍必须通过原有 `inventory-configuration-test-batch-ready` 回调确认,进度回调不得覆盖终态。同一 Profile 仍只登录一次,但每个 DSV 站点使用新的页面并复用同一 browser context 的登录 Cookie,避免上一站报表 iframe、下载菜单或等待状态污染下一站。
- 测试运行超过 `SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS`(默认 900 秒)仍未完成时,服务端在读取或再次发起测试时将其收口为 `failed / failed`,提示“等待 RPA Worker 超时,请重新测试”。同一 Worker 队列中的批量站点按队列站点数线性扩展等待窗口,避免后排站点尚未领取就按单站时限误判超时;单站测试仍使用原始等待窗口。超时、版本不一致和重复/迟到回调都不能更新当前站点绑定或放行启用。**Dify 手动配置说明**:此恢复与轮询机制不要求修改 Dify 画布、Tool 或 Prompt;Dify 不读取此管理端状态接口。
- **DSV SSO 回跳优化(2026-07)**:密码提交后,Worker 将 `auth.dbschenker.com` 的授权回跳与 Portal Reports 菜单加载分开计时。空白 `authorization.ping/oauth2` 中转页停留 `SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS`(默认 12000)后只刷新一次;超过 `SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS`(默认 90000)仍未回到 Portal 时,明确报 `DSV SSO authorization return timed out`,不再伪装为库存测试超时。Portal 壳层出现后仅轮询 Reports 导航,避免反复读取整页与 iframe。Dify 无需修改配置。
- **DSV 性能证据与快速路径(2026-08)**:库存导出 Worker 以 `[dsv-chain]` 输出不含凭据和查询参数的 `session_prepare`、`report_navigation`、`report_parameter_fill`、`report_execute_and_download`,并将最后一段拆为 `report_result_ready` 与 `excel_export_and_download` 的 `start/end/error` 与 `elapsedMs`;登录内层继续输出 `auto_login.*` 子阶段,Warehouse option 等待继续输出 `waitedMs`。提交 View Report 后直接等待 SSRS 业务就绪条件,不以可能被长连接阻塞的 `networkidle` 作为前置条件。Reports 级联菜单先走一次精确文本的 hover/click 快速路径,只有未确认下一级已展开时才退回原多 selector、多动作兼容链;不得因优化删除回退逻辑。一次真实运行据此区分认证/首页、报表菜单/参数页、参数异步加载、SSRS 结果与 Excel 导出下载耗时。
- **DSV 性能证据与快速路径(2026-08)**:库存导出 Worker 以 `[dsv-chain]` 输出不含凭据和查询参数的 `session_prepare`、`report_navigation`、`report_parameter_fill`、`report_execute_and_download`,并将最后一段拆为 `report_result_ready` 与 `excel_export_and_download` 的 `start/end/error` 与 `elapsedMs`;登录内层继续输出 `auto_login.*` 子阶段,Warehouse option 等待继续输出 `waitedMs`。- 提交 View Report 后直接等待 SSRS 业务就绪条件,不以可能被长连接阻塞的 `networkidle` 作为前置条件。result_ready(分页/工具栏)之后**明细行是异步渲染**的:worker 用 `_wait_dsv_report_inventory_rows` 做条件轮询(1s 间隔、上限 45s)等待真实数据行,而非单次快照,避免"分页已出、行未渲染"被误判为无库存数据(2026-08-26 真实案例:160 页报表被单次探针误判 skip)。Excel 下载等待窗口按实测放宽:`expect_download` 使用 `SHIPPING_NOTICE_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS`(默认 240s,SSRS 生成 34s~90s+ 波动),目录兜底 60s;禁止复用全局 60s 浏览器超时作为下载等待(2026-08-26 多次 `Timeout 60000ms exceeded while waiting for event "download"` 根因)。Reports 级联菜单先走一次精确文本的 hover/click 快速路径,只有未确认下一级已展开时才退回原多 selector、多动作兼容链;不得因优化删除回退逻辑。一次真实运行据此区分认证/首页、报表菜单/参数页、参数异步加载、SSRS 结果与 Excel 导出下载耗时。
- 多个 Inventory Source 可绑定同一个 published Profile;同模板只维护一份。存在少量列差异时创建新 Profile 版本或新 Profile,不在 Source 中复制完整映射。
- 库存站点首次保存不要求绑定解析方案,且普通保存始终保持停用;后端仅允许通过独立启用接口进入正式运行。启用检查列出系统连接、库存文件解析方案、发货模板和测试导出与解析验证;确认后测试记录与站点当前配置版本绑定,后续编辑会使其失效。草稿、缺失或非法作用域字段仍阻断正式运行期自动解析。
- 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `freight_warehouse_id` 映射或库存源默认映射;动态仓还要求唯一仓库识别字段且测试样例中每个仓库都有精确映射或默认映射。该检查只查询已维护的 `ShippingInventoryExternalMapping`,绝不自动创建映射。
@@ -1747,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 模板
@@ -1825,9 +1844,6 @@ GET /api/admin/shipping-order-schema/published-contract
# SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES=52428800
# SHIPPING_NOTICE_EML_MAX_NESTING_DEPTH=3
# 批次后台调度:每个批次最多同时派发几张票(默认 3)
# SHIPPING_NOTICE_BATCH_DISPATCH_CONCURRENCY=3
# 单票调用 Dify 解析的总超时(秒,默认 180)
# SHIPPING_NOTICE_DIFY_PARSE_TIMEOUT_SECONDS=180
@@ -1844,16 +1860,11 @@ GET /api/admin/shipping-order-schema/published-contract
# SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS=300
# 说明:发货通知后台任务写入通用 jobs 表;kb_jobs 仅保留知识库清洗/同步任务。
# Dify Chatflow(对话续办)
SHIPPING_NOTICE_CHAT_DIFY_APP_ID=
SHIPPING_NOTICE_CHAT_DIFY_API_KEY=
SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1
```
### 1.3 配置 Agent 记录
货代发货通知 Agent 由管理端手工创建和维护。配置完成后填写本节的 Dify Chatflow 环境变量;不使用种子脚本写入或覆盖 Agent 记录。
货代发货通知 Agent 由管理端手工创建和维护。Agent 的 Dify Chatflow 连接参数(API Base / App ID / API Key)由管理端 Agent 记录承载,不使用种子脚本写入或覆盖 Agent 记录,也不存在对应的 `SHIPPING_NOTICE_CHAT_DIFY_*` 环境变量。
### 1.4 Mock RPA(开发)
@@ -2074,7 +2085,7 @@ Get-Content C:\HxopsRpaTest\data\inventory_triggers\.hxops_rpa_shared_mount
cat /mnt/hxops-rpa-test-data/inventory_triggers/.hxops_rpa_shared_mount
```
管理端 `GET /api/admin/rpa-workers/status` 可查看最后心跳;Worker 离线时触发库存 RPA 会立即失败(fail-fast),不再空等 900s。
管理端 `GET /api/admin/rpa-workers/status` 可查看最后心跳;Worker 离线时触发库存 RPA 会立即失败(fail-fast),不再空等 900s。排程管理工作台的「RPA Worker 在线」徽标对该接口做 **10s 前台轮询**(仅库存排程工作台模式,后台标签页暂停、请求未返回时跳过);执行记录列表按**历史查询**处理,仅切任务/点查询/重置时加载,不做定时自动刷新。
心跳存储:test/prod 默认要求 **Redis**(`SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true`)。Redis 不可用时触发与排程会报 `RPA.HEARTBEAT_STORAGE_UNAVAILABLE`;仅当 `SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=true` 时,调度器才会按冷却发送企微「心跳存储异常」告警(默认关闭)。
@@ -2919,6 +2930,9 @@ pytest tests/test_shipping_notice_state_machine.py tests/test_shipping_notice_ui
- **Excel 生成与人工上传闭环**:自动链止于待人工上传;人工仅按 `business_no` 确认当前 Notice 的唯一 Excel 已上传,服务端创建受控 Attempt 与审计,不要求 `evidence_asset_no`、截图、回执或 PDF。
- **发货通知单与 Excel 的一一对应(2026-08-25)**:一个 `ShippingNotice` 就是一张发货通知单、一个业务单号和唯一一个 Excel;Notice 可聚合多条订单明细,但同一明细只能属于一个有效 Notice。业务单号在该 Notice 的首个 Excel 生成事务中分配;后续分批履约必须先创建独立 Notice,不能向同一 Notice 追加或替换 Excel。
- **短缺放行后的单条自动履约(2026-08-26)**:单条 `release_inventory_shortage` 成功后仅入队既有 auto-fulfill Job;Worker 确认当前恰有一条开放且可履约的明细时,创建独立 `ShippingNotice` 并排程其 Excel。若有多条开放明细,系统不自动合并,用户仍须勾选后创建 wave;暂不提供批次放行。前端写入成功即关闭确认弹窗并重启处理投影轮询,后续只读刷新不阻塞操作。
- **短缺放行后任务级状态重算(2026-08-26)**:`release_inventory_shortage` 是对"库存满足性"Gate 的受控业务事实。放行回写后,任务级履约态必须按同一放行语义重算,否则会出现"Excel 已生成、任务却仍显示 `unfulfillable`/`shortage_review`/缺货"的矛盾。为此:① 放行决定与满足性/聚合重算共用 `_released_line_keys_for_task`(只认活动放行决定);② `_recompute_task_match_aggregate` 对已放行的缺口行视同满足(`line_status='released'`,不计入缺货),与 `match_completed` 语义对齐;③ 放行回写 `_sync_confirmed_task_fulfillment_gates` 与库存满足性复核 `recheck_inventory_sufficiency` 在确有匹配行事实时调用 `recompute_task_fulfillment_state`,同步 `match_status`/`line_results_json`/`shortage_json`/`review_status`/`pending_human_reason` 并应用对应迁移(`MATCHED_FULFILLABLE` / `MATCH_SHORTAGE`)。空事实任务不重算,避免被误标为缺货。
- **异常中断/恢复的旧状态残留统一清理(2026-08-26)**:除放行外,其余"中断恢复后未重算任务级状态"路径统一按"失效即清空派生状态、强制下轮重匹配"处理:① `inventory_loaded_response`(库存快照复用/重载)与 `inventory_mapping_workflow` 在载入新库存后清空 task 及其同库存文件关联任务的 `match_status`/`line_results_json`/`shortage_json`;② `recovery_invalidation_service.invalidate_inventory_downstream` 对 `retry_inventory_from_field_mapping`/`retry_inventory_from_matching` 同样清空匹配派生字段(仅库存文件级重试才清导出指针);③ `retry_task` 重试前清空旧匹配结果,强制 orchestr 重匹配而非带旧缺货跳过;④ `decision_workflow._request_formal_gate_action` 请求正式 Gate 前清除 review/pending/error 残留(原为 return 后不可达的死代码)。
- **工作台详情/货代上传面板查询数优化(2026-08-26)**:单票详情(`/shipping-tasks/<task_no>`)与货代上传面板首屏曾耗时约 12s,根因是 `build_task_ui_state` 的高单次成本被重复/循环放大。已修复:① detail 请求不再同一请求内重复投影 `build_task_ui_state`(`serialize_task_detail` 直接透传 `include_stage_context`,去掉被覆盖的内层调用);② 货代上传面板聚合对每个同 PO Notice 不再跑完整 `build_task_ui_state`,改用轻量 `project_notice_available_actions` 只返回已授权动作码;③ `serialize_process_execution` 在会话读缓存缺失时批量预取本 Execution 的 LatestAttempt(`latest_attempt_by_id`)与 `gates_by_execution_id`,消除 `serialize_process_gate` 逐 Gate 的 `query.get()` N+1;④ `project_inventory_candidate_facts` 批量预取当前匹配行引用的库存快照(`ShippingInventoryFile`),消除逐行 `sess.get()` N+1。
- **Gate 恢复的统一页面同步(2026-08-26)**:所有正式 OT Gate 恢复在服务端受理后立即解除交互等待,后台刷新任务详情、Case 与处理投影,并重启五阶段轮询及会话级刷新;不得等待只读请求完成才恢复按钮,也不得依赖浏览器手动刷新显示 Worker 推进结果。
- **库存 RPA 超时恢复(2026-08-25)**:`inventory_rpa_timeout` / `inventory_rpa_exhausted` 的主动作是 `reload_inventory_result`,仅复用既有有效库存快照并重新挂接,不写 trigger、不新建 RPA Attempt;若未找到结果,保持原阻断并将“重新获取库存(RPA)”作为用户显式备用动作。
- **人工复核**:Case/Draft 版本冲突、确认建单幂等;确认后复用 `auto_progress`;布局重构完成(见 layout-plan §11)。
@@ -3127,16 +3141,19 @@ API 层
### 6.4 批量 RPA(一次登录多 Warehouse)
- Trigger action:`inventory_export_batch`;按 `connector_type` 分组,DSV/Crane 各登录一次
- **每个 source 导出前**:DSV 调用 `_reset_dsv_export_entry`(goto entry + session 检测,不重复登录);Crane 调用 `_reset_crane_export_entry`
- **每个 source 导出前**:DSV 首源 `_ensure_dsv_session` 完整登录一次;后续源复用当前 tab 登录态——同 navigation 用 `_return_to_dsv_report_parameters` 复用参数页(返回 True 则跳过菜单导航),导航不同**直接在当前页开 Reports 菜单导航(不再整页 goto 首页,省 ~12s 并避开 public/login 一闪)**;导航失败时 `_navigate_dsv_to_report_form` 内部整页回首页重置后重试一次。**批内不得每源新开页面/重复走 OAuth**(2026-08-26 修复:曾因"每源新开空白页 + 写死 index=0"导致每源重复 SSO 重定向 2-2.5 分钟且偶发 OAuth 空白页单源失败);仅当会话疑似失效(login/session/oauth 异常)时,新开干净页面重试一次完整登录。Crane 调用 `_reset_crane_export_entry`
- **按需单票**:`write_inventory_export_trigger_for_task`;batch 开启时包装为单源 batch trigger(与定时共用 worker 路径)
- **单票 legacy 路径**:`_download_dsv360_inventory` / `_download_crane_inventory` 已委托 `_export_*_inventory_source`,与批量共用 `parameters` 填充
- **multi_select**:worker `_fill_dsv_multi_select` 支持多选控件(非仅取第一个值)
- **报表控件模板**(2026-08-26):同一参数名在不同报表的 SSRS 控件长相不同(`On Hand Inventory By Location 3lv` 的 Warehouse 是原生 select `ddValue`,JDA 版 `On Hand Inventory by Location` 是 txtValue/toggle/divDropDown 多选框下拉)。控件差异由 Worker 按归一化报表名登记在 `dsv_report_parameters._DSV_REPORT_PARAM_TEMPLATES`,填参时把 `report_name` 透传到模块解析;`selector_env/selectors` 继续不进入数据库,未登记报表回退参数名默认值。填参失败会输出参数区控件探针日志(`[dsv-filter] ... control probe`),便于定位控件 ID/类型漂移。
- Worker:`scripts/rpa/freight_rpa_worker.py` → `_handle_inventory_batch_trigger`
- 回调:`POST /api/shipping-notice/rpa/inventory-batch-ready`
- **回调响应语义**(2026-08):HTTP 回调只做信封校验、成功 Excel 从 RPA shared drop 复制到 HXOPS 受控 `rpa_callback_receipts/<callback_id>/`、创建 `shipping_inventory_callback_process` Job 后立即返回 `status=ok` + 顶层/`data.result_status=accepted`。它**不得**在 HTTP 请求中做 Excel 结构校验、库存行解析、快照/任务关联或 Gate 自动推进;这些业务步骤只由 shipping worker 消费 Job 后执行。这样 Worker 的 30 秒 HTTP 等待只代表“平台已收件”,不再把实际导出成功误判为 callback timeout。Job 的最终 `callback_result.result_status` 才是 `success` / `partial_failed` / `failed`;排程场景(含 `schedule_run_id` 且 finalize 成功)由该异步结果终态化 `ScheduleRun`。worker 回调 payload 顶层含 `status`、`success`(legacy)、`has_success`、`success_count`、`skipped_count`、`failed_count`、`results[]`(每项含 `status`)。
- **单票身份与失败收口**(2026-08-20):首次自动库存准备和用户重试均必须经 `ensure_all_required_sources_prepared` 创建逐源 Attempt;禁止写缺少 `source_run_no / lease_token / candidate_set_id / execution_id / gate_id` 的旧 task 级 trigger。Worker 发现 `trigger_identity_invalid` 时必须在 `results[]` 回传可用的 source 身份片段;后端按已定位的 Attempt 立即标记失败、同步 PreparationSourceAttempt、`inventory_preparation` Gate 与 `step3_inventory_prepare=needs_human`,不得等待库存轮询超时。
- 定时排程:`schedule_type=platform_job`,`platform_api_path=shipping-inventory-rpa`,`data_source_type=null`;建议 cron `0 3 * * *`(Asia/Shanghai)
- 排程语义:`data_source_type` 仅用于 `schedule_type=data_pipeline`(`database` | `external_api`);平台任务通过 Job Registry 注册,由 `platform_api_path` 引用 job key
- **排程完成企微通知门禁**(`_notify_schedule_run_wecom`,2026-08-26 排障确认):finalize 成功后按序检查 ① `response_summary_json.domain_notification_managed`(领域自管时跳过)→ ② `WECOM_NOTIFY_ENABLED`(默认 true,被本地 `.env.local` 覆盖为 false 会静默拦截并写 `schedule_runs.wecom_notify_error='WECOM_NOTIFY_ENABLED=false'`)→ ③ `schedule_completed` ∈ `WECOM_NOTIFY_EVENTS`(本地覆盖列表漏掉它时同样拦截)→ ④ 任务 `notify_enabled` 且 `notify_user_ids_json` 非空 → ⑤ 用户已绑 `wecom_userid`。任一环节不满足都不发消息;排障先查 `schedule_runs.wecom_notified / wecom_notify_error`,再对 `app_settings`(DB 权威源)与 `.env.<env>` 的合并结果核对 ②③(DB 优先于 env 文件)。
- **空快照状态约束**(2026-08-26):`create_empty_rpa_inventory_snapshot` 写入 `snapshot_status='empty'`(no_inventory_data 审计快照),依赖迁移 `hq0r1s2t3u4v` 把 `ck_shipping_inventory_files_snapshot_status` 检查约束从 `('ready','failed','expired')` 放宽为含 `'empty'`;未执行该迁移(或回退版本)时,批量回调插入空快照会触发 CheckViolation 导致整笔 Job 事务回滚、ScheduleRun 停在 awaiting 后被超时回收为 failed。
### 6.5 审计字段
@@ -3155,6 +3172,8 @@ API 层
3. **独立字段为真相源**:`inventory_source_code`、`inventory_connector_type`、`inventory_warehouse_id` 存于 `shipping_tasks` 列,gate 不读 `step_payload_json`。
4. **用户只确认 source_code**:`confirm_inventory_source` 固化 Source;fixed 模式回填 Warehouse,动态模式在库存行 `reservation_id + part_number` 匹配后回填。
5. **硬 Gate**:`inventory_rpa_workflow`、`inventory_workflow`、`fulfillment_workflow`、`progress_workflow` 入口均调用 `assert_inventory_source_gate`。
- **人工确认已上传例外(2026-08-26)**:`upload_to_freight(mode=manual_confirm)` 不经过库存源稳定性校验——人工确认是"外部已上传、服务端登记",不触发 RPA、不依赖库存源;只有 `auto/retry_upload`(RPA 路径)在触发前校验库存源。
- **稳定性判定收窄(2026-08-26)**:`is_inventory_source_stable` 只校验任务实际命中 Source 的必要事实(状态 ∈ {resolved, candidates_frozen}、Source 存在且启用、connector_type 一致、fixed 仓一致;多候选冻结时各候选源存在且启用)。**不再**比对全局配置版本 hash 或路由指纹——无关库存源的改动、订单头字段漂移不再使已有任务失效;`inventory_source_config_changed` 同步只对"选中源自身不可用/驱动变化"返回 True。
6. **快照复用键**:`find_latest_ready_snapshot(source_code, warehouse_id)`;link 时做 identity check。
7. **迁移**:`2b3c4d5e6f7a_add_shipping_inventory_configuration`、`3c4d5e6f7a8b_remove_shipping_inventory_site_id`、`4c5d6e7f8a9_add_dynamic_inventory_snapshot_idempotency`。
+1 -1
View File
@@ -241,7 +241,7 @@ PDF 证据锚定优先使用现有 `pypdfium2` 逐字文本坐标定位,并由
- **原子编号服务**:业务编号格式固定为 `{customer_short_code}{YYMMDD}{sequence_2}`,例如 `WYC26071501`;日期使用 `Asia/Shanghai`。PostgreSQL 按 `(business_type, customer_id, business_date)` 原子递增两位流水,并由 `business_no` 唯一约束兜底;不得使用“查询最大值 + 1”。
- **格式约束**:客户简码为全局唯一的 `2-6` 位大写英文字母(`^[A-Z]{2,6}$`);完整业务编号正则为 `^[A-Z]{2,6}\d{8}$`。
- **容量与幂等**:单客户单日允许 `01-99`;第 100 票抛出明确业务错误。同一业务单重复确认直接返回原编号,不重复消耗流水。
- **试点保护与恢复**:`SHIPPING_NOTICE_BATCH_MAX_FILES`(默认 `20`)限制单次通知批量文件数;`FILE_ASSET_MAX_SIZE_MB`、`SHIPPING_NOTICE_EML_MAX_ATTACHMENTS`、`SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES`、`SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES` 分别限制文件和 EML 展开规模。超限在接入/抽取前失败,不生成批次或任务。订单抽取管理员健康接口提供队列、Provider、HXOPS 落库和总时延 P50/P95、失败率、重试与积压;RPA 耗时由配置测试和 Artifact Attempt 审计追溯。通用 Job stale recovery 在 Worker 重新领取前恢复超时任务;数据库与 RPA 共享目录备份恢复演练须在非生产环境按运维记录执行,禁止以演练替代真实试点指标。
- **试点保护与恢复**:`FILE_ASSET_MAX_SIZE_MB`、`SHIPPING_NOTICE_EML_MAX_ATTACHMENTS`、`SHIPPING_NOTICE_EML_MAX_ATTACHMENT_BYTES`、`SHIPPING_NOTICE_EML_MAX_TOTAL_ATTACHMENT_BYTES` 分别限制文件和 EML 展开规模。超限在接入/抽取前失败,不生成批次或任务。订单抽取管理员健康接口提供队列、Provider、HXOPS 落库和总时延 P50/P95、失败率、重试与积压;RPA 耗时由配置测试和 Artifact Attempt 审计追溯。通用 Job stale recovery 在 Worker 重新领取前恢复超时任务;数据库与 RPA 共享目录备份恢复演练须在非生产环境按运维记录执行,禁止以演练替代真实试点指标。
- **编号后纠错**:管理员必须填写原因;尚未上传货代时保留原业务号并标记作废,创建 `supersedes_task_id` 指向原 Notice 的替代 Notice 并申请正确客户的新流水。旧号查询跟随替代链,已上传货代的任务须先完成外部作废流程。
- **期初数据导入**:使用客户导入批次和导入行暂存表保存原文件哈希、原始值、标准化值、校验结果、处理决定和发布结果;正式发布前完成简码冲突、疑似重复、公共域名和标识歧义检查。
- **渐进发布**:按 `off → shadow → manual_gate → auto_gate` 开启客户识别;影子阶段只记录候选不阻断生产,强规则质量达标后先启用人工 Gate,再开放有限自动确认。
@@ -0,0 +1,83 @@
/**
* features/admin/modules/schedules/components/DynamicTaskParamsForm.spec.ts
* 用途:复现「货代库存 RPA」平台任务参数表单的渲染。
* 背景:排程编辑弹窗选择 shipping-inventory-rpa 后,库存源多选字段不呈现,且弹窗按钮疑似失效。
* 断言:给定带 source_codes(multi_select/options_source=shipping_inventory_sources) 的定义,
* 挂载后应渲染「库存源」标签及动态选项,而不是抛错或渲染为空。
*/
import { describe, expect, it, vi, beforeEach } from 'vitest';
import { flushPromises, mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import DynamicTaskParamsForm from './DynamicTaskParamsForm.vue';
vi.mock('@/features/admin/api/schedule.api', () => ({
listAdminPlatformTaskOptions: vi.fn(() =>
Promise.resolve([
{ label: 'DSV 360 / Rooms BK HK', value: 'DSV360', description: 'dbs · fixed · W01' },
{ label: 'Crane Footprint', value: 'CRANE', description: 'crane · inventory_match · -' },
]),
),
}));
const shippingInventoryRpaDefinition = {
task_type: 'shipping-inventory-rpa',
label: '货代库存 RPA',
label_key: 'admin.schedule.form.platformJobShippingInventory',
description: '按计划从配置的库存源抓取库存数据,由 freight_rpa_worker 异步导出。',
description_key: 'admin.schedule.form.shippingInventoryJobHint',
category: 'shipping',
params_schema: [
{
key: 'source_codes',
type: 'multi_select',
label: '库存源',
label_key: 'admin.schedule.form.shippingInventorySources',
required: false,
default: [],
options_source: 'shipping_inventory_sources',
placeholder: '留空则导出全部启用库存源',
placeholder_key: 'admin.schedule.form.shippingInventorySourcesPlaceholder',
help: '选择需要执行的库存源;选项来自库存源配置,留空则全部执行。',
help_key: 'admin.schedule.form.shippingInventorySourcesHelp',
},
],
defaults: { source_codes: [] },
};
function mountForm() {
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
'admin.schedule.form.dynamicParamsAdvancedPlaceholder': '可选:粘贴高级 JSON 对象参数,例如添加 timeout_seconds 等键值对',
'admin.schedule.form.dynamicParamsAdvanced': '高级配置(JSON,可选)',
},
},
});
return mount(DynamicTaskParamsForm, {
props: {
definition: shippingInventoryRpaDefinition as any,
modelValue: { source_codes: [] },
valid: true,
},
global: { plugins: [i18n] },
});
}
describe('DynamicTaskParamsForm (shipping-inventory-rpa)', () => {
beforeEach(() => vi.clearAllMocks());
it('renders the 库存源 label and the two dynamic options', async () => {
const wrapper = mountForm();
await flushPromises();
expect(wrapper.text()).toContain('库存源');
expect(wrapper.text()).toContain('DSV 360 / Rooms BK HK');
expect(wrapper.text()).toContain('Crane Footprint');
expect(wrapper.find('input[type="checkbox"]').exists()).toBe(true);
});
it('does not throw during mount/render given the definition', async () => {
expect(() => mountForm()).not.toThrow();
});
});
@@ -30,6 +30,7 @@ const emit = defineEmits<{
const { t, te } = useI18n();
/** options_source → 选项列表缓存(组件生命周期内共享,避免重复请求) */
const optionsCache = reactive<Record<string, PlatformTaskOption[]>>({});
const optionsLoading = reactive<Record<string, boolean>>({});
@@ -18,8 +18,8 @@ const showCreateModal = useScheduleCreateModalOpen();
<template>
<Teleport to="body">
<div v-if="showCreateModal" class="admin-modal-overlay items-center">
<div class="admin-modal-panel max-w-3xl">
<div class="flex items-center justify-between border-b border-subtle px-8 py-6">
<div class="admin-modal-panel max-h-[92vh] max-w-3xl min-h-0">
<div class="flex shrink-0 items-center justify-between border-b border-subtle px-8 py-6">
<h3 class="text-2xl font-bold tracking-tight text-primary">{{ admin.scheduleEditingId ? $t('admin.schedule.form.editTitle') : $t('admin.schedule.form.createTitle') }}</h3>
<button
class="rounded-full p-2 text-muted transition hover-surface-soft hover:text-secondary"
@@ -28,7 +28,7 @@ const showCreateModal = useScheduleCreateModalOpen();
✕
</button>
</div>
<div class="max-h-[72vh] space-y-5 overflow-y-auto px-8 py-6">
<div class="min-h-0 flex-1 space-y-5 overflow-y-auto px-8 py-6">
<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
<div>
<label class="mb-2 block text-sm font-medium text-secondary">{{ $t('admin.schedule.form.name') }}</label>
@@ -300,18 +300,31 @@ const showCreateModal = useScheduleCreateModalOpen();
</template>
</div>
<!-- 平台任务参数区:完全由注册表 params_schema 决定,无任务级 v-if -->
<div
v-if="admin.scheduleCreateForm.schedule_type === 'platform_job' && admin.selectedPlatformTaskDefinition"
class="mt-3"
>
<!-- 平台任务参数区:完全由注册表 params_schema 决定,无任务级 v-if。
外层仅按 schedule_type 判定(同步、必然为真),不依赖异步 definitions;
定义解析完成前显示加载提示,完成后立即渲染 DynamicTaskParamsForm(含库存源)。 -->
<div v-if="admin.scheduleCreateForm.schedule_type === 'platform_job'" class="mt-3">
<DynamicTaskParamsForm
v-if="admin.selectedPlatformTaskDefinition"
:definition="admin.selectedPlatformTaskDefinition"
:model-value="admin.scheduleCreateForm.job_params"
:valid="admin.platformJobParamsValid"
@update:model-value="admin.scheduleCreateForm.job_params = $event"
@update:valid="admin.platformJobParamsValid = $event"
/>
<div v-else-if="admin.platformTaskDefinitionsLoading || admin.platformTaskDefinitionsError" class="space-y-2 rounded-xl border border-blue-200 bg-blue-50/40 px-4 py-3 text-sm text-muted">
<p>{{ admin.platformTaskDefinitionsLoading
? $t('admin.schedule.form.dynamicParamsLoading')
: $t('admin.schedule.form.dynamicParamsLoadFailed') }}</p>
<button
v-if="admin.platformTaskDefinitionsError && !admin.platformTaskDefinitionsLoading"
type="button"
class="btn-secondary btn-sm"
@click="admin.loadPlatformTaskDefinitions"
>
{{ $t('admin.schedule.form.dynamicParamsRetry') }}
</button>
</div>
</div>
<div v-if="admin.scheduleTestResult" class="mt-4 rounded-2xl border border-emerald-200 bg-emerald-50/40 p-4">
@@ -463,7 +476,7 @@ const showCreateModal = useScheduleCreateModalOpen();
</div>
</div>
<div class="admin-modal-footer admin-modal-footer--muted justify-end gap-3 px-8 py-5">
<div class="admin-modal-footer admin-modal-footer--muted relative z-10 pointer-events-auto justify-end gap-3 px-8 py-5">
<button
type="button"
class="btn-secondary"
@@ -0,0 +1,26 @@
/**
* features/admin/modules/schedules/components/dynamicParamsLocale.spec.ts
* 回归防护:vue-i18n 会把 {xxx} 当作命名插值;若 locale 文案里出现裸 {(如示例 JSON),
* 会导致 $t() 在渲染 DynamicTaskParamsForm 时抛错("'multipliers' of null"/编译报错),
* 进而整套参数区无法渲染、弹窗按钮失效。本测试确保四语言该占位文案不含花括号。
*/
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
const LOCALES = ['zh-CN', 'zh-TW', 'en', 'th'];
describe('admin.schedule.form.dynamicParamsAdvancedPlaceholder', () => {
LOCALES.forEach((locale) => {
it(`${locale} must NOT contain message-compiler braces`, () => {
const text = readFileSync(resolve(__dirname, `../../../../../locales/${locale}/admin.json`), 'utf8');
const line = text
.split('\n')
.find((l) => l.includes('"dynamicParamsAdvancedPlaceholder"'));
expect(line, `missing key for ${locale}`).toBeTruthy();
// vue-i18n 编译器会把 { 视为插值起始,示例 JSON 的花括号会导致渲染抛错
expect(line!.includes('{')).toBe(false);
expect(line!.includes('}')).toBe(false);
});
});
});
@@ -18,6 +18,8 @@ export function createScheduleAdminState() {
const platformJobs = ref<PlatformJobOption[]>([]);
/** 平台任务完整契约(含 params_schema),供 DynamicTaskParamsForm 渲染 */
const platformTaskDefinitions = ref<PlatformTaskDefinition[]>([]);
const platformTaskDefinitionsLoading = ref(false);
const platformTaskDefinitionsError = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmTitle = ref('');
@@ -118,6 +120,8 @@ export function createScheduleAdminState() {
kbGroups,
platformJobs,
platformTaskDefinitions,
platformTaskDefinitionsLoading,
platformTaskDefinitionsError,
showDeleteConfirmDialog,
deleteConfirmTitle,
deleteConfirmMessage,
@@ -22,6 +22,7 @@ import {
type ScheduleCreateForm,
} from '../../types/schedule-admin.types';
import { buildScheduleConfigPayload } from '../../utils/schedule-form-payload.utils';
import { normalizePlatformJobKey } from '../../utils/schedule-job-key.utils';
import { useScheduleCronDesigner } from '../useScheduleCronDesigner';
import type { ScheduleAdminState } from './schedule-admin.state';
import type { ScheduleAdminLookups } from './useScheduleAdminLookups';
@@ -63,7 +64,10 @@ export function useScheduleAdminForm(
const selectedPlatformTaskDefinition = computed(() => {
const form = scheduleCreateForm.value;
if (form.schedule_type !== 'platform_job' || !form.platform_api_path) return null;
return platformTaskDefinitions.value.find((d) => d.task_type === form.platform_api_path) || null;
// 后端保存时经 normalize_job_key 归一化;历史数据可能存下划线/完整路径/大小写差异,
// 前端比较也归一化,避免严格 === 失配导致参数表单(含库存源)被静默隐藏。
const normalized = normalizePlatformJobKey(form.platform_api_path);
return platformTaskDefinitions.value.find((d) => normalizePlatformJobKey(d.task_type) === normalized) || null;
});
/**
@@ -71,8 +75,9 @@ export function useScheduleAdminForm(
* 核心逻辑:由 modal select @change 触发(不用 watch,防止编辑回填被覆盖)。
*/
const handlePlatformJobChange = (): void => {
const normalized = normalizePlatformJobKey(scheduleCreateForm.value.platform_api_path);
const definition = platformTaskDefinitions.value.find(
(d) => d.task_type === scheduleCreateForm.value.platform_api_path,
(d) => normalizePlatformJobKey(d.task_type) === normalized,
);
scheduleCreateForm.value.job_params = definition && Object.keys(definition.defaults || {}).length
? { ...definition.defaults }
@@ -237,11 +242,13 @@ export function useScheduleAdminForm(
data_source_type: task.schedule_type === 'data_pipeline'
? ((task.data_source_type || 'database') as ScheduleCreateForm['data_source_type'])
: null,
platform_api_path: task.schedule_type === 'platform_job' ? (task.platform_api_path || null) : null,
platform_api_path: task.schedule_type === 'platform_job'
? (normalizePlatformJobKey(task.platform_api_path) || null)
: null,
// 历史 FAQ 任务兼容:无 job_params 时把旧 dify_agent_id 迁移为 app_id
job_params: task.schedule_type === 'platform_job'
? (task.job_params
|| (task.platform_api_path === 'faq-aggregate-hot' && task.dify_agent_id
|| (normalizePlatformJobKey(task.platform_api_path) === 'faq-aggregate-hot' && task.dify_agent_id
? { app_id: task.dify_agent_id }
: null))
: null,
@@ -1,6 +1,9 @@
/**
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminList.ts
* 任务列表加载、概览统计、启停/立即执行/删除与视图切换。
* 等待轮询策略:点「立即执行」后每 RUN_NOW_POLL_MS 刷新记录与列表,直到任务离开 running;
* 同一任务仅保留一个轮询(重复点击先清旧定时器)、上一轮未返回时跳过本轮,
* 并设 RUN_NOW_POLL_MAX_MS 上限,防止任务长时间不终态造成页面无限请求。
*/
import { computed } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
@@ -15,6 +18,11 @@ import { useMessage } from '@/shared/composables/useMessage';
import type { ScheduleAdminState } from './schedule-admin.state';
import type { ScheduleAdminRuns } from './useScheduleAdminRuns';
/** 立即执行后的等待轮询间隔 */
const RUN_NOW_POLL_MS = 5_000;
/** 等待轮询总上限:与服务端库存导出超时(默认 900s)对齐,超限后停止自动刷新提示手动查询 */
const RUN_NOW_POLL_MAX_MS = 15 * 60_000;
export function useScheduleAdminList(
state: ScheduleAdminState,
runs: Pick<ScheduleAdminRuns, 'viewScheduleRuns'>,
@@ -30,6 +38,11 @@ export function useScheduleAdminList(
openDeleteConfirm,
} = state;
/** 各任务运行中的单实例等待轮询句柄(重复点「立即执行」复用同一句柄) */
const runNowPollTimers = new Map<number, ReturnType<typeof setInterval>>();
/** 正在执行的等待轮询任务(上一轮未返回时跳过 tick,防请求堆叠) */
const runNowPollsInFlight = new Set<number>();
const scheduleEnabledCount = computed(() => schedules.value.filter((item) => item.enabled).length);
const scheduleDisabledCount = computed(() => schedules.value.filter((item) => !item.enabled).length);
const scheduleRunningCount = computed(() => schedules.value.filter((item) => item.last_status === 'running').length);
@@ -77,17 +90,37 @@ export function useScheduleAdminList(
msg.error(err?.message || t('admin.schedule.msg.runNowFailed'));
return;
}
await runs.viewScheduleRuns(taskId);
await runs.viewScheduleRuns(taskId, true);
await loadSchedules();
// 同一任务只保留一个等待轮询:重复点击先停旧定时器,避免多路 interval 并行放大请求频率
const previousPoll = runNowPollTimers.get(taskId);
if (previousPoll) clearInterval(previousPoll);
let elapsedMs = 0;
const pollInterval = setInterval(async () => {
await runs.viewScheduleRuns(taskId);
await loadSchedules();
const target = schedules.value.find((s: ScheduleTask) => s.id === taskId);
if (target && target.last_status && target.last_status !== 'running') {
clearInterval(pollInterval);
// 上一轮尚未返回时跳过本轮;慢后端下每轮耗时可能超过间隔,跳过可避免请求逐轮堆叠
if (runNowPollsInFlight.has(taskId)) return;
runNowPollsInFlight.add(taskId);
try {
await runs.viewScheduleRuns(taskId, true);
await loadSchedules();
elapsedMs += RUN_NOW_POLL_MS;
const target = schedules.value.find((s: ScheduleTask) => s.id === taskId);
const terminal = !!target?.last_status && target.last_status !== 'running';
const timedOut = elapsedMs >= RUN_NOW_POLL_MAX_MS;
if (terminal || timedOut) {
clearInterval(pollInterval);
runNowPollTimers.delete(taskId);
if (timedOut && !terminal) {
msg.warning(t('admin.schedule.msg.runNowWaitTimeout'));
}
}
} finally {
runNowPollsInFlight.delete(taskId);
}
}, 5000);
}, RUN_NOW_POLL_MS);
runNowPollTimers.set(taskId, pollInterval);
};
const setScheduleEnabled = async (taskId: number, enabled: boolean) => {
@@ -8,7 +8,15 @@ import { getKbGroups } from '@/features/kb/api/kb.api';
import type { ScheduleAdminState } from './schedule-admin.state';
export function useScheduleAdminLookups(state: ScheduleAdminState) {
const { agents, users, kbGroups, platformJobs, platformTaskDefinitions } = state;
const {
agents,
users,
kbGroups,
platformJobs,
platformTaskDefinitions,
platformTaskDefinitionsLoading,
platformTaskDefinitionsError,
} = state;
const loadAgents = async (): Promise<void> => {
try {
@@ -55,11 +63,16 @@ export function useScheduleAdminLookups(state: ScheduleAdminState) {
* 核心逻辑:GET /api/admin/platform-tasks/definitions,供 DynamicTaskParamsForm 按 schema 渲染。
*/
const loadPlatformTaskDefinitions = async (): Promise<void> => {
platformTaskDefinitionsLoading.value = true;
platformTaskDefinitionsError.value = false;
try {
platformTaskDefinitions.value = await listAdminPlatformTaskDefinitions();
} catch (e) {
console.error('Failed to load platform task definitions', e);
platformTaskDefinitions.value = [];
platformTaskDefinitionsError.value = true;
} finally {
platformTaskDefinitionsLoading.value = false;
}
};
@@ -1,8 +1,11 @@
/**
* features/admin/modules/schedules/composables/schedule-admin/useScheduleAdminRuns.ts
* 执行批次列表:筛选、列宽、展开详情、Excel 下载与指标派生。
* 执行批次列表:筛选、列宽、展开详情、Excel 下载、指标派生与 RPA Worker 心跳轮询。
* 轮询策略(历史查询与监控职责分离):执行记录列表是纯历史查询,仅切任务/查询/重置时按需加载;
* RPA Worker 在线状态是监控信号,仅在库存排程工作台模式下每 RPA_WORKER_STATUS_POLL_MS 静默轮询一次,
* 后台标签页暂停、请求未返回时跳过(防堆叠),使「在线/离线」徽标及时反映心跳。
*/
import { computed, watch, type Ref } from 'vue';
import { computed, onBeforeUnmount, watch, type Ref } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import { listAdminScheduleRuns, adminRunInventoryRawZipUrl, getAdminRpaWorkersStatus } from '@/features/admin/api/schedule.api';
import { useMessage } from '@/shared/composables/useMessage';
@@ -33,6 +36,7 @@ export function useScheduleAdminRuns(
scheduleRunColumnDefs,
resizingScheduleCol,
expandedScheduleRunId,
scheduleViewMode,
} = state;
const syncScheduleRunColumnLabels = () => {
@@ -162,21 +166,63 @@ export function useScheduleAdminRuns(
return latest ? formatDateTime(String(latest)) : '-';
});
const refreshRpaWorkerStatus = async () => {
/**
* 拉取 RPA Worker 心跳状态概览(刷新「在线/离线」徽标与最后心跳时间)。
* @param silent - 静默模式:由后台轮询调用,不翻转 loading,避免徽标每轮闪烁「加载中」
*/
const refreshRpaWorkerStatus = async (silent = false) => {
if (!isInventoryRpaSchedule.value) {
rpaWorkerStatus.value = null;
return;
}
rpaWorkerStatusLoading.value = true;
if (!silent) rpaWorkerStatusLoading.value = true;
try {
rpaWorkerStatus.value = await getAdminRpaWorkersStatus();
} catch {
rpaWorkerStatus.value = null;
} finally {
rpaWorkerStatusLoading.value = false;
if (!silent) rpaWorkerStatusLoading.value = false;
}
};
// ── RPA Worker 心跳轮询(监控信号,仅库存排程) ─────────────────────────
// 心跳由 Worker 每约 20s 上报一次(服务端 TTL 默认 90s),UI 每 10s 刷新即足够;
// 2s 固定轮询只有少量时间点在变化,属于对无变化数据的过度请求。
const RPA_WORKER_STATUS_POLL_MS = 10_000;
/** 是否需要前台轮询心跳:仅工作台模式且当前排程为库存类(该徽标仅在此时可见) */
const shouldPollRpaWorkerStatus = computed(
() => scheduleViewMode.value === 'workbench' && isInventoryRpaSchedule.value && !!selectedScheduleId.value,
);
let rpaStatusPollTimer: ReturnType<typeof setInterval> | null = null;
let rpaStatusPollInFlight = false;
const stopRpaStatusPolling = () => {
if (rpaStatusPollTimer) {
clearInterval(rpaStatusPollTimer);
rpaStatusPollTimer = null;
}
};
const startRpaStatusPolling = () => {
stopRpaStatusPolling();
if (!shouldPollRpaWorkerStatus.value) return;
rpaStatusPollTimer = setInterval(async () => {
// 后台标签页不轮询;上一次请求未返回时跳过本轮,防止请求堆叠与旧响应覆盖
if (document.hidden || rpaStatusPollInFlight) return;
rpaStatusPollInFlight = true;
try {
await refreshRpaWorkerStatus(true);
} finally {
rpaStatusPollInFlight = false;
}
}, RPA_WORKER_STATUS_POLL_MS);
};
watch(shouldPollRpaWorkerStatus, startRpaStatusPolling, { immediate: true });
onBeforeUnmount(stopRpaStatusPolling);
const todayStart = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}T00:00:00`;
@@ -192,7 +238,12 @@ export function useScheduleAdminRuns(
scheduleRunStartedBefore.value = todayEnd();
};
const viewScheduleRuns = async (taskId: number) => {
/**
* 加载指定排程的执行记录并顺带刷新 RPA Worker 心跳状态。
* @param taskId - 排程任务 ID
* @param silentRpaStatusRefresh - 静默刷新心跳(用于「立即执行」等待轮询),不翻转 loading 徽标避免闪烁
*/
const viewScheduleRuns = async (taskId: number, silentRpaStatusRefresh = false) => {
selectedScheduleId.value = taskId;
scheduleRunsLoading.value = true;
if (!scheduleRunStartedAfter.value && !scheduleRunStartedBefore.value) {
@@ -208,7 +259,7 @@ export function useScheduleAdminRuns(
params.started_before = new Date(scheduleRunStartedBefore.value).toISOString();
}
selectedScheduleRuns.value = await listAdminScheduleRuns(taskId, params);
await refreshRpaWorkerStatus();
await refreshRpaWorkerStatus(silentRpaStatusRefresh);
} finally {
scheduleRunsLoading.value = false;
}
@@ -0,0 +1,35 @@
/**
* features/admin/modules/schedules/utils/schedule-job-key.utils.spec.ts
* 验证 normalizePlatformJobKey 与后端 schedule_contract.normalize_job_key 语义一致,
* 确保 selectedPlatformTaskDefinition 对历史非规范 platform_api_path 仍能命中参数契约。
*/
import { describe, expect, it } from 'vitest';
import { normalizePlatformJobKey } from './schedule-job-key.utils';
describe('normalizePlatformJobKey', () => {
it('保留规范化连字符 key', () => {
expect(normalizePlatformJobKey('shipping-inventory-rpa')).toBe('shipping-inventory-rpa');
});
it('下划线转连字符(历史小写别名)', () => {
expect(normalizePlatformJobKey('shipping_inventory_rpa')).toBe('shipping-inventory-rpa');
});
it('大小写不敏感', () => {
expect(normalizePlatformJobKey('Shipping-Inventory-RPA')).toBe('shipping-inventory-rpa');
});
it('取完整内部路径最后一段', () => {
expect(normalizePlatformJobKey('/api/internal/jobs/shipping-inventory-rpa')).toBe('shipping-inventory-rpa');
});
it('去 query / hash / 首尾斜杠', () => {
expect(normalizePlatformJobKey('/faq-aggregate-hot?x=1#frag')).toBe('faq-aggregate-hot');
});
it('空值与 null 返回空串', () => {
expect(normalizePlatformJobKey('')).toBe('');
expect(normalizePlatformJobKey(null)).toBe('');
expect(normalizePlatformJobKey(undefined)).toBe('');
});
});
@@ -0,0 +1,26 @@
/**
* features/admin/modules/schedules/utils/schedule-job-key.utils.ts
* 平台任务 key 归一化,与后端 schedule_contract.normalize_job_key 保持同一语义。
* 逻辑:小写 → 去 query/hash → 去首尾斜杠 → 取路径最后一段 → 下划线转连字符。
* 用途:openScheduleEditModal 读入 platform_api_path 时归一化,使「平台任务」下拉回显与
* selectedPlatformTaskDefinition 的 task_type 精确匹配不受历史非规范存储值影响。
* 后端在保存时已归一化,历史数据仍可能存下划线(shipping_inventory_rpa)、完整内部路径
* (/api/internal/jobs/shipping-inventory-rpa)或大小写差异;前端此前用严格 === 字符串比较,
* 一旦不匹配即静默隐藏参数表单(含库存源),本工具修复该匹配漏洞。
*/
export function normalizePlatformJobKey(value: string | null | undefined): string {
let raw = String(value || '').trim().toLowerCase();
// 取 query 之前
const queryIdx = raw.indexOf('?');
if (queryIdx >= 0) raw = raw.slice(0, queryIdx);
// 取 hash 之前
const hashIdx = raw.indexOf('#');
if (hashIdx >= 0) raw = raw.slice(0, hashIdx);
// 去首尾斜杠
raw = raw.replace(/^\/+|\/+$/g, '');
// 取最后一段路径
const lastSlash = raw.lastIndexOf('/');
if (lastSlash >= 0) raw = raw.slice(lastSlash + 1);
// 下划线转连字符
return raw.replace(/_/g, '-');
}
@@ -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; }
@@ -126,6 +126,8 @@ export const getWorkspaceShippingTask = (taskNo: string) =>
export const getWorkspaceShippingFreightNoticeGroups = (taskNo: string) =>
requestJson<ShippingFreightNoticeGroupsResponse>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/freight-notice-groups`,
// [PERF] Priority Hints:货代上传聚合仅在对应阶段工作面展示,非首屏关键路径。
{ priority: 'low' },
);
/**
@@ -316,7 +318,8 @@ export const getWorkspaceShippingProcessingWorkItem = async (
) => {
const raw = await requestJson<Record<string, unknown>>(
`/api/workspace/shipping-processing/work-items/${encodeURIComponent(workItemType)}/${encodeURIComponent(workItemNo)}`,
{ signal },
// [PERF] Priority Hints:轮询接口让位于首屏关键请求(run/case/task 详情)。
{ signal, priority: 'low' },
);
const normalized = normalizeShippingProcessingProjection(raw);
if (!normalized) {
@@ -752,7 +755,8 @@ export const reparseWorkspaceShippingOrderReviewDocument = (caseNo: string, reas
export const getWorkspaceShippingOrderReviewEvidence = (caseNo: string, signal?: AbortSignal) =>
requestJson<{ case_no: string; items: ShippingOrderReviewEvidence[] }>(
`/api/workspace/shipping-notice/order-review-cases/${encodeURIComponent(caseNo)}/evidence`,
{ signal },
// [PERF] Priority Hints:证据摘要非首屏关键路径,让位于 run/case/task 详情。
{ signal, priority: 'low' },
);
/**
@@ -972,6 +976,8 @@ export const getWorkspaceShippingOrderReviewIntakeParseContext = (caseNo: string
export const getWorkspaceShippingOrderReviewQueue = (runNo: string) =>
requestJson<ShippingOrderReviewQueue>(
`/api/workspace/shipping-notice/order-review-queue/${encodeURIComponent(runNo)}`,
// [PERF] Priority Hints:队列仅驱动导航/阶段摘要,非主编辑区关键路径。
{ priority: 'low' },
);
/** 用户展开状态卡时获取脱敏进度时间线;不返回节点或Workflow诊断数据。 */
@@ -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">
@@ -24,9 +29,6 @@ const props = defineProps<{
stageLabelKey?: string | null;
stageInconsistent?: boolean;
hasFormalOt?: boolean;
shippingNoticeNo?: string | null;
userStatus?:
| 'running'
| 'waiting_human'
@@ -70,10 +72,16 @@ const { t, te } = useI18n();
/**
* 当前阶段展示文案:优先消费 stage_label_key,禁止直接展示 stage 码。
* 核心逻辑:loading 是「权威投影读取中」占位,不是业务运行态——只要已有可展示的
* 阶段(Case 快照 current_stage 与投影同源,见 currentProcessingStageDisplay),
* 照常展示真实阶段;仅在连降级阶段都没有时才回退 stageLoading 占位文案。
*/
const stageLabel = computed(() => {
if (props.loading) {
return t('chat.shippingOrderReview.caseSwitchLoading');
const hasKnownStage = Boolean(
String(props.stageCode || '').trim() || String(props.stageLabelKey || '').trim(),
);
if (props.loading && !hasKnownStage) {
return t('chat.shippingOrderReview.currentProcessing.stageLoading');
}
if (props.stageInconsistent) {
return t('chat.shippingOrderReview.currentProcessing.stateInconsistent');
@@ -88,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'),
@@ -132,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) {
@@ -219,6 +228,10 @@ function isNonTaskCapabilityAction(code: string): boolean {
/**
* 业务动作按钮只消费 primary_action;retryable 是状态,不是授权。
*
* 核心逻辑:除既有授权过滤外,文案必须是后端下发且经受控映射解析出的非空文案
* (businessActionLabel 已 fail-closed 为 '');无文案时整体隐藏按钮,防止
* 渲染成只有图标/空壳的“幽灵按钮”误导用户以为是开关或其他控件。
*/
const showBusinessAction = computed(() => {
if (props.loading) return false;
@@ -233,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;
});
@@ -365,16 +380,6 @@ type ReviewCurrentUserStatus =
{{ statusLabel }}
</dd>
</div>
<div
v-if="hasFormalOt && shippingNoticeNo"
class="flex flex-wrap gap-x-2"
>
<dt class="text-muted">{{ t('chat.shippingOrderReview.currentTask.labelFormalSn') }}</dt>
<dd
class="font-mono"
data-testid="review-current-processing-ot"
>{{ shippingNoticeNo }}</dd>
</div>
</dl>
<p
@@ -168,8 +168,11 @@ function drawEvidenceHighlight(
context.strokeStyle = 'rgba(202, 138, 4, 0.95)';
context.setLineDash([]);
} else {
context.fillStyle = 'rgba(244, 63, 94, 0.18)';
context.strokeStyle = 'rgba(225, 29, 72, 0.95)';
// unavailable / invalid 证据高亮统一使用品牌色(对齐编辑画布匹配锚点的 sky/brand 蓝),
// 避免在纯文档预览上出现刺眼的红色,导致「模板预览图标颜色不一致」的观感。
// 说明:质量仅影响可信度提示,不改变「该处确有取值位置」的语义,故不再用警示红。
context.fillStyle = 'rgba(14, 165, 233, 0.22)';
context.strokeStyle = 'rgba(2, 132, 199, 0.95)';
context.setLineDash([3, 3]);
}
context.lineWidth = 2;
@@ -23,6 +23,8 @@ import {
REVIEW_DRAFT_VERSION_MISMATCH,
PROGRESS_POLL_MS,
summarizeDraftConflictDiff,
useShippingOrderReview,
@@ -924,7 +926,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
expect(review.workflowProgressPolling.value).toBe(true);
expect(api.getProcessingWorkItem).toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(2600);
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
expect(review.workflowProgressPolling.value).toBe(false);
@@ -971,7 +973,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
const review = useShippingOrderReview();
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
await review.confirm();
await vi.advanceTimersByTimeAsync(2600);
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
// 关键断言:活动窗口内同步刷新 Case 与队列,让顶部五阶段读取到后端已推进的通知准备。
expect(api.getCase.mock.calls.length).toBeGreaterThanOrEqual(2);
@@ -1008,13 +1010,13 @@ describe('useShippingOrderReview build eligibility writes', () => {
const review = useShippingOrderReview({ onWorkflowRefresh });
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'WFI-1' });
await review.confirm();
await vi.advanceTimersByTimeAsync(2600);
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
expect(onWorkflowRefresh).toHaveBeenCalled();
// RPA 可重试失败不是工作流关闭;必须继续读取后续成功回调的 Projection。
expect(review.workflowProgressPolling.value).toBe(true);
await vi.advanceTimersByTimeAsync(2600);
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
expect(review.workflowProgressPolling.value).toBe(false);
review.stopWorkflowProgressPolling();
@@ -1118,7 +1120,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
await review.load('RUN-1', 'CASE-1', { conversationId: 'conv-1', itemNo: 'SWI-1' });
await review.reparseDocument('document_quality');
await vi.advanceTimersByTimeAsync(2600);
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
expect(review.reviewRun.value?.run_no).toBe('RUN-2');
@@ -1240,7 +1242,7 @@ describe('useShippingOrderReview build eligibility writes', () => {
await review.reparseDocument('document_quality');
await vi.advanceTimersByTimeAsync(0);
await Promise.resolve();
await vi.advanceTimersByTimeAsync(2600);
await vi.advanceTimersByTimeAsync(PROGRESS_POLL_MS + 100);
await Promise.resolve();
expect(review.reviewRun.value?.run_no).toBe('RUN-1');
@@ -71,6 +71,12 @@ export const REVIEW_DRAFT_VERSION_MISMATCH = 'SHIPPING.REVIEW_DRAFT_VERSION_MISM
/** ?????????? confirm ????? */
export const REVIEW_BUILD_ELIGIBILITY_BLOCKED = 'SHIPPING.REVIEW_BUILD_ELIGIBILITY_BLOCKED';
/**
* 自动推进轮询基础间隔:5 秒。自动化推进通常是分钟级,原 2.5 秒会对
* 单线程/低并发后端造成持续请求排队;页面不可见时轮询另会暂停。
*/
export const PROGRESS_POLL_MS = 5000;
/** ????????????/??????????? Case ??? */
export type DraftVersionConflict = {
localVersion: number;
@@ -394,7 +400,6 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
let contextItemNo = '';
let progressPollTimer: ReturnType<typeof window.setInterval> | null = null;
let reparseCaseRefreshTimer: ReturnType<typeof window.setInterval> | null = null;
const PROGRESS_POLL_MS = 2500;
/**
* 应用后端返回的完整 Case 快照。
@@ -435,6 +440,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
const targetDocumentId = currentStreamDocumentId();
if (!targetRunNo) return;
const tick = async () => {
// 页面不可见时暂停轮询(返回前台后下一拍自动恢复),避免后台标签持续占用服务端。
if (typeof document !== 'undefined' && document.hidden) return;
try {
const run = await getWorkspaceShippingOrderExtractionRun(targetRunNo);
extractionLifecycleProgress.value = run.lifecycle_progress || null;
@@ -520,6 +527,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
let lastLifecycleFingerprint = '';
const RUN_TERMINAL = new Set(['completed', 'partially_completed', 'failed', 'cancelled']);
const tick = async () => {
// 页面不可见时暂停轮询(返回前台后下一拍自动恢复),避免后台标签持续占用服务端。
if (typeof document !== 'undefined' && document.hidden) return;
try {
if (authoritativeOrderTaskNo.value) {
await refreshShippingProcessing();
@@ -828,7 +828,10 @@ export interface ShippingTaskSummary {
business_no?: string | null;
/** 通知单列表只读行摘要;库存数据由后端当前匹配事实投影,前端不得自行计算。 */
notice_line_summary?: Array<{
/** 项次展示值;来源由 line_no_source 标注,前端不得按行号自行回退。 */
line_no?: string | number | null;
/** 项次来源:field=冻结字段,customer_po_line_no=客户 PO 行号,sequence=系统行序。 */
line_no_source?: 'field' | 'customer_po_line_no' | 'sequence' | string | null;
part_number?: string | null;
customer_part_number?: string | null;
reservation_id?: string | null;
@@ -1483,6 +1486,10 @@ export interface ShippingTaskUiState {
/** 冻结订单行始终可读;不依赖库存文件或匹配结果。 */
frozen_order_lines?: Array<{
line_key?: string | null;
/** 项次展示值;来源由 line_no_source 标注。 */
line_no?: string | number | null;
/** 项次来源:field=冻结字段,customer_po_line_no=客户 PO 行号,sequence=系统行序。 */
line_no_source?: 'field' | 'customer_po_line_no' | 'sequence' | string | null;
reservation_id?: string | null;
part_number?: string | null;
required_qty?: string | number | null;
@@ -1500,6 +1507,10 @@ export interface ShippingTaskUiState {
has_match_result?: boolean;
lines?: Array<{
line_key?: string | null;
/** 项次展示值;来源由 line_no_source 标注。 */
line_no?: string | number | null;
/** 项次来源:field=冻结字段,customer_po_line_no=客户 PO 行号,sequence=系统行序。 */
line_no_source?: 'field' | 'customer_po_line_no' | 'sequence' | string | null;
reservation_id?: string | null;
part_number?: string | null;
required_qty?: string | number | null;
@@ -1619,10 +1630,23 @@ 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<{
/** 项次展示值;来源由 line_no_source 标注,前端不得按行号自行回退。 */
line_no?: string | number | null;
/** 项次来源:field=冻结字段,customer_po_line_no=客户 PO 行号,sequence=系统行序。 */
line_no_source?: 'field' | 'customer_po_line_no' | 'sequence' | string | null;
part_number?: string | null;
reservation_id?: string | null;
shipment_qty?: string | number | null;
@@ -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;
@@ -2632,16 +2826,27 @@ describe('ShippingOrderReviewView layout phase 1', () => {
summary: {}, steps: [],
},
} as any);
// 完成面改版后按「已上传通知聚合」消费同一份 freight groups;仅 uploaded 通知进入完成面。
vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockResolvedValue({
po_number: 'PO-100',
items: [
{ business_no: 'WYC26082401', po_number: 'PO-100', upload_status: 'uploaded', export_file_name: 'WYC26082401.xlsx', lines: [
{ line_no: '00010', part_number: 'PART-A', reservation_id: 'RSV-A', qty: '2' },
] },
{ business_no: 'WYC26082402', po_number: 'PO-100', upload_status: 'pending', export_file_name: 'WYC26082402.xlsx', lines: [] },
],
} as any);
const wrapper = await mountView({ lifecycle_stage: 'upload_complete' });
await flushPromises();
const evidence = wrapper.get('[data-testid="review-lifecycle-upload-complete"]');
expect(evidence.text()).toContain('succeeded');
expect(evidence.text()).not.toContain('LATEST-FAILED');
// 只展示已上传通知(uploaded),未上传(pending)不进入完成面。
expect(evidence.text()).toContain('WYC26082401');
expect(evidence.text()).not.toContain('WYC26082402');
// 人工确认不再展示或依赖货代回执号,即使历史投影仍带有 freight_ref_no。
expect(evidence.text()).not.toContain('LEGACY-REF-MUST-NOT-BE-SHOWN');
expect(evidence.text()).not.toContain('failed');
expect(evidence.text()).not.toContain('LATEST-FAILED');
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
});
@@ -2894,7 +3099,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
expect(wrapper.find('[data-testid="review-confirm-outcome"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="retry-auto-progress-after-confirm"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-RECOVER-1');
// 发货通知单号与订单明细行绑定,不在任务级整单显示;当前任务卡不展示单条通知单号。
expect(wrapper.find('[data-testid="review-current-processing-ot"]').exists()).toBe(false);
}, 15000);
it('does not submit an action before the formal OT Gate projection arrives (UI-01)', async () => {
@@ -3168,7 +3374,8 @@ describe('ShippingOrderReviewView audit and progress recovery', () => {
await flushPromises();
expect(wrapper.find('[data-testid="review-confirm-create"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-ot"]').text()).toContain('SN-CONFIRM-PROGRESS-FAIL');
// 发货通知单号随订单明细绑定,不在任务级整单展示;当前任务卡不含单条通知单号。
expect(wrapper.find('[data-testid="review-current-processing-ot"]').exists()).toBe(false);
}, 15000);
});
@@ -16,7 +16,7 @@
<script setup lang="ts">
import { computed, defineAsyncComponent, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Bot, Check, Crosshair, Download, MoreHorizontal, Plus, RefreshCw, Undo2, Copy, Trash2 } from 'lucide-vue-next';
import { Bot, Check, ChevronDown, Crosshair, Download, MoreHorizontal, Plus, RefreshCw, Undo2, Copy, Trash2 } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { BusinessError } from '@/shared/api/client';
import { useMessage } from '@/shared/composables/useMessage';
@@ -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)
@@ -2107,14 +2205,39 @@ const freightNoticeGroups = ref<ShippingFreightNoticeGroup[]>([]);
const freightNoticeGroupsLoading = ref(false);
const freightNoticeGroupsReason = ref<string | null>(null);
const freightNoticeGroupsLoadFailed = ref(false);
/** 右栏业务主身份必须是 business_no;技术 OT 仅用于内部追踪。 */
const currentShippingBusinessNo = computed(() => (
String(formalTaskDetail.value?.business_no || '').trim()
|| String(shippingProcessingProjection.value?.shippingNoticeNo || '').trim()
|| null
));
const selectedFreightBusinessNos = ref<string[]>([]);
const freightBatchBusy = ref<'download' | 'confirm' | 'rpa' | 'regenerate' | null>(null);
/**
* 通知完成面的只读聚合:同 PO 中已有上传成功证据(upload_status=uploaded)的发货通知。
* 核心逻辑:与货代上传面消费同一份 freightNoticeGroups,仅按终态过滤;未上传的
* 通知仍留在货代上传面处理,完成面不出现混淆态。
*/
const uploadedFreightNoticeGroups = computed(() =>
freightNoticeGroups.value.filter((item) =>
String(item.upload_status || '').trim().toLowerCase() === 'uploaded',
),
);
/** 批次留底下载:把已完成通知全部打包为 ZIP(复用后端 /shipping-notices/batch/export)。 */
const uploadingBatchArchive = ref(false);
async function downloadCompletedBatchArchive() {
const businessNos = uploadedFreightNoticeGroups.value
.map((item) => String(item.business_no || '').trim())
.filter(Boolean);
if (!businessNos.length || uploadingBatchArchive.value) return;
uploadingBatchArchive.value = true;
try {
await downloadWorkspaceShippingNoticeExportArchive(businessNos);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
} finally {
uploadingBatchArchive.value = false;
}
}
/** 通知完成面的展开明细:同一时刻只展开一张通知(与货代上传面交互一致)。 */
const expandedCompletedNoticeNo = ref<string | null>(null);
function toggleCompletedNoticeLine(businessNo: string) {
expandedCompletedNoticeNo.value = expandedCompletedNoticeNo.value === businessNo ? null : businessNo;
}
const formalTaskDetailLoading = ref(false);
const formalTaskDetailLoadFailed = ref(false);
/**
@@ -2136,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,
@@ -2249,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 {
@@ -2331,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 {
@@ -2407,6 +2536,11 @@ async function runFreightBatchAction(action: 'download' | 'confirm' | 'rpa') {
} else {
await batchStartWorkspaceShippingNoticeRpaUpload(selectedFreightBusinessNos.value);
}
// 确认/RPA 后重拉同 PO 通知聚合,使通知完成面能立即呈现最新 uploaded 状态。
if (action === 'confirm' || action === 'rpa') {
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (taskNo) await loadFreightNoticeGroups(taskNo);
}
await Promise.all([loadFormalTaskDetail(), refreshShippingProcessing()]);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
@@ -2438,6 +2572,9 @@ async function runFreightNoticeAction(
await submitFormalGateAction('regenerate_excel_artifact');
return;
}
// 确认/RPA 后重拉同 PO 通知聚合,使通知完成面能立即呈现最新 uploaded 状态。
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (taskNo) await loadFreightNoticeGroups(taskNo);
await Promise.all([loadFormalTaskDetail(), refreshShippingProcessing()]);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
@@ -2461,13 +2598,14 @@ function canRunFreightNoticeAction(group: ShippingFreightNoticeGroup, actionCode
}
watch(
[confirmedNoticeTaskNo, workbenchMode, hasCreatedShippingTask, isLifecycleFreightUpload],
([taskNo, mode, created, isFreightUpload]) => {
[confirmedNoticeTaskNo, workbenchMode, hasCreatedShippingTask, isLifecycleFreightUpload, isLifecycleUploadComplete],
([taskNo, mode, created, isFreightUpload, isUploadComplete]) => {
const completed = String(displayCase.value?.current_stage?.code || '').trim().toLowerCase() === 'completed'
|| String(displayCase.value?.user_status || '').trim().toLowerCase() === 'completed';
// Notice 聚合只服务货代上传工作面;通知准备/文件切换不能为此扫描同 PO 全部 Notice。
if (taskNo && created && isFreightUpload) void loadFreightNoticeGroups(taskNo);
if (!isFreightUpload) {
// Notice 聚合服务货代上传与通知完成两个工作面;通知准备/文件切换不扫描同 PO 全部 Notice。
const needsNoticeGroups = isFreightUpload || isUploadComplete;
if (taskNo && created && needsNoticeGroups) void loadFreightNoticeGroups(taskNo);
if (!needsNoticeGroups) {
freightNoticeGroups.value = [];
selectedFreightBusinessNos.value = [];
}
@@ -2603,6 +2741,102 @@ function preparationLineCustomerPoLine(line: { line_key?: string | null; custome
return draftValueText || String(line.customer_po_line_no || '').trim() || '—';
}
/**
* 通知行项次展示:按后端 line_no_source 区分渲染。
* 核心逻辑:field=冻结字段真实值(普通展示);customer_po_line_no=客户 PO 行号(普通展示,
* 附带来源提示);sequence=系统行序(弱化样式 + 来源提示);缺失直接显示 —。
* 禁止前端按 position/序号自行推导业务项次。
*/
function freightLineNoDisplay(line: { line_no?: string | number | null; line_no_source?: string | null }): {
text: string;
muted: boolean;
title: string;
} {
const value = line.line_no ?? null;
if (value === null || value === '') return { text: '—', muted: false, title: '' };
const source = String(line.line_no_source || '').trim();
if (source === 'sequence') {
return {
text: String(value),
muted: true,
title: t('chat.shippingOrderReview.lifecycle.freightUpload.lineNoSourceSequence'),
};
}
if (source === 'customer_po_line_no') {
return {
text: String(value),
muted: false,
title: t('chat.shippingOrderReview.lifecycle.freightUpload.lineNoSourceCustomerPo'),
};
}
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;
@@ -3601,6 +3835,7 @@ watch(
watch(
lifecycleCurrentStageCode,
async (current, previous) => {
if (await syncPendingReleaseAutoAdvance()) return;
if (!current || !previous || current === previous) return;
// 只响应后端 current 阶段的真实推进:用户点击已完成阶段只会改路由,
// 绝不能触发自动跳转而被带回当前阶段。
@@ -3826,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>
@@ -3973,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">
@@ -4035,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>
@@ -4055,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>
@@ -4068,7 +4300,8 @@ watch(
</details>
</div>
</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">{{ line.line_no || '—' }}</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 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>
<p v-else class="mt-3 rounded-lg border border-default bg-surface-muted/50 p-3 text-xs text-secondary">{{ freightNoticeGroupsReason === 'po_missing' ? t('chat.shippingOrderReview.lifecycle.freightUpload.poMissing') : t('chat.shippingOrderReview.lifecycle.freightUpload.empty') }}</p>
@@ -4081,9 +4314,88 @@ watch(
>
<h2 class="text-sm font-semibold text-primary">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.title') }}</h2>
<p class="mt-1 text-xs text-secondary">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.subtitle') }}</p>
<div class="mt-3 rounded-lg border border-emerald-200 bg-surface/70 p-3 text-xs text-secondary dark:border-emerald-900">
<p v-if="formalTaskDetail.ui_state?.stage_context?.upload?.succeeded_attempt" class="mt-1">{{ t('chat.shippingOrderReview.lifecycle.upload.attempt', { status: formalTaskDetail.ui_state.stage_context.upload.succeeded_attempt.status || '-', mode: formalTaskDetail.ui_state.stage_context.upload.succeeded_attempt.mode || '-' }) }}</p>
<!-- 聚合头:本批已上传数量 + 留底下载(ZIP 打包全部已完成通知) -->
<div class="mt-3 flex flex-wrap items-center justify-between gap-2 rounded-lg border border-emerald-200 bg-surface px-3 py-2 text-xs dark:border-emerald-900" data-testid="review-upload-complete-toolbar">
<span class="font-medium text-emerald-900 dark:text-emerald-100">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.batchCount', { count: uploadedFreightNoticeGroups.length }) }}</span>
<button
type="button"
class="rounded border border-emerald-300 px-2 py-1 font-medium text-emerald-700 hover:bg-emerald-50 disabled:opacity-50 dark:border-emerald-700 dark:text-emerald-200 dark:hover:bg-emerald-950/40"
:disabled="!uploadedFreightNoticeGroups.length || uploadingBatchArchive"
data-testid="review-upload-complete-batch-download"
@click="void downloadCompletedBatchArchive()"
>
{{ uploadingBatchArchive
? t('chat.shippingOrderReview.lifecycle.uploadComplete.batchDownloading')
: t('chat.shippingOrderReview.lifecycle.uploadComplete.batchDownload') }}
</button>
</div>
<div v-if="uploadedFreightNoticeGroups.length" class="mt-3 space-y-3" data-testid="review-upload-complete-groups">
<div
v-for="group in uploadedFreightNoticeGroups"
:key="group.business_no"
class="rounded-lg border border-emerald-200 bg-surface/70 dark:border-emerald-900"
data-testid="review-upload-complete-notice"
>
<!-- 单据行:identity + 状态 + 单张下载 + 展开明细 -->
<div class="flex flex-wrap items-center justify-between gap-3 border-b border-emerald-200/70 px-3 py-2 text-xs dark:border-emerald-900/70">
<div class="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1">
<span class="font-semibold text-primary">{{ group.business_no }}</span>
<span class="inline-flex items-center gap-1 font-medium text-emerald-700 dark:text-emerald-300">
<Check class="h-3.5 w-3.5" aria-hidden="true" />
{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.uploaded') }}
</span>
<span class="text-secondary">{{ group.po_number ? `PO: ${group.po_number}` : '' }}</span>
</div>
<div class="flex items-center gap-2">
<button
type="button"
class="rounded border border-emerald-300 px-2 py-1 font-medium text-emerald-700 hover:bg-emerald-50 dark:border-emerald-700 dark:text-emerald-200 dark:hover:bg-emerald-950/40"
data-testid="review-upload-complete-download"
@click="void downloadFreightNotice(group.business_no)"
>{{ t('chat.shippingOrderReview.lifecycle.freightUpload.download') }}</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded border border-default px-2 py-1 font-medium text-primary hover:bg-surface disabled:opacity-50"
:aria-expanded="expandedCompletedNoticeNo === group.business_no"
:aria-label="expandedCompletedNoticeNo === group.business_no
? t('chat.shippingOrderReview.lifecycle.uploadComplete.collapse')
: t('chat.shippingOrderReview.lifecycle.uploadComplete.expand')"
data-testid="review-upload-complete-toggle-lines"
@click="toggleCompletedNoticeLine(group.business_no)"
>
{{ expandedCompletedNoticeNo === group.business_no
? t('chat.shippingOrderReview.lifecycle.uploadComplete.collapse')
: t('chat.shippingOrderReview.lifecycle.uploadComplete.expand') }}
<ChevronDown class="h-3.5 w-3.5 transition-transform" :class="{ 'rotate-180': expandedCompletedNoticeNo === group.business_no }" aria-hidden="true" />
</button>
</div>
</div>
<div v-if="expandedCompletedNoticeNo === group.business_no" class="space-y-2 px-3 pb-3 pt-2 text-xs" data-testid="review-upload-complete-lines">
<p v-if="group.export_file_name" class="text-secondary">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.exportFile', { file: group.export_file_name }) }}</p>
<table class="min-w-full text-left">
<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-upload-complete-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>
</div>
<p v-else class="mt-3 rounded-lg border border-emerald-200 bg-surface/70 p-3 text-xs text-secondary dark:border-emerald-900">{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.empty') }}</p>
</section>
<ReviewIntakeParsePanel
@@ -4514,8 +4826,6 @@ watch(
:task-no="displayCase?.confirmed_task_no || displayCase?.post_confirm_auto_progress?.task_no"
:confirmed-task-id="displayCase?.confirmed_task_id"
:show-admin-diagnosis="showAdminTaskMissingDiagnosis"
:has-formal-ot="shippingProcessingProjection?.hasFormalOt ?? hasFormalOt"
:shipping-notice-no="currentShippingBusinessNo"
:user-status="currentTaskUserStatus"
:retryable="visibleCurrentTaskRetryable"
:blocking-reason="currentTaskBlockingReason"
+23 -2
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"
@@ -2253,9 +2270,12 @@
"shippingInventorySourcesHelp": "Select the inventory sources to run; options come from the source config. Empty means all.",
"dynamicParamsSelectPlaceholder": "Please select",
"dynamicParamsOptionsLoading": "Loading options...",
"dynamicParamsLoading": "Loading platform task parameters…",
"dynamicParamsLoadFailed": "Failed to load platform task parameters. Please retry.",
"dynamicParamsRetry": "Reload",
"dynamicParamsNoOptions": "No options available",
"dynamicParamsAdvanced": "Advanced config (JSON, optional)",
"dynamicParamsAdvancedPlaceholder": "{\"timeout_seconds\": 300}",
"dynamicParamsAdvancedPlaceholder": "Optional: paste advanced JSON object params, e.g. add a timeout_seconds key",
"dynamicParamsAdvancedInvalid": "Advanced config JSON is invalid; fix it before it can be saved.",
"dynamicParamsJsonInvalid": "JSON is invalid; fix it before it can be saved.",
"dynamicParamsInvalid": "Fix invalid task parameters before saving.",
@@ -2438,6 +2458,7 @@
"headerLabelsJsonInvalid": "header_labels JSON format is invalid.",
"apiHeadersJsonInvalid": "API Headers JSON format is invalid.",
"runNowFailed": "Manual run failed",
"runNowWaitTimeout": "Timed out waiting for the run to finish (about 15 min); auto refresh stopped, query records manually",
"downloadExcelFailed": "Failed to download Excel",
"downloadInventoryRawZipFailed": "Failed to download raw inventory ZIP",
"deleteFailed": "Delete schedule failed"
@@ -3504,7 +3525,7 @@
"confirmReview": "Confirm review and add",
"correctionInvalid": "A line correction must be a JSON field object.",
"expectedRows": "Human truth (JSON array)",
"expectedRowsPlaceholder": "[{\"customer_po_line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]",
"expectedRowsPlaceholder": "Example line: customer_po_line_no=00010, part_number=PN-1, qty=3",
"expectedRowsHint": "Enter at least one human-confirmed line truth; do not copy the candidate output.",
"expectedRowsInvalid": "Truth must be a JSON array containing at least one non-empty line object.",
"expectedOrderFields": "Order field truth (JSON object)",
+4 -2
View File
@@ -1490,8 +1490,8 @@
"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", "selected": "{count} notices selected", "batchDownload": "Download selected", "batchRpa": "Batch RPA upload", "batchConfirm": "Confirm selected uploaded"},
"uploadComplete": {"title": "Notification completion", "subtitle": "Upload-success evidence is verified. This view is read only."},
"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": {
"intake_parse": "Intake and parsing",
@@ -2223,6 +2223,7 @@
"adminDiagnosisStatus": "Status: task_missing",
"adminDiagnosisHint": "Use task audit / data repair. This page does not auto-recover.",
"stateInconsistent": "State syncing / inconsistent state data",
"stageLoading": "Fetching latest status…",
"statusRunning": "System processing",
"statusFailedRetryable": "Failed — retry available",
"statusCompleted": "Completed",
@@ -2744,6 +2745,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",
+23 -2
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"
@@ -2149,9 +2166,12 @@
"shippingInventorySourcesHelp": "เลือกแหล่งสต็อกที่ต้องการรัน; ตัวเลือกมาจากการตั้งค่าแหล่งสต็อก เว้นว่าง = ทั้งหมด",
"dynamicParamsSelectPlaceholder": "กรุณาเลือก",
"dynamicParamsOptionsLoading": "กำลังโหลดตัวเลือก...",
"dynamicParamsLoading": "กำลังโหลดพารามิเตอร์งานแพลตฟอร์ม…",
"dynamicParamsLoadFailed": "โหลดพารามิเตอร์งานแพลตฟอร์มไม่สำเร็จ โปรดลองอีกครั้ง",
"dynamicParamsRetry": "โหลดใหม่",
"dynamicParamsNoOptions": "ไม่มีตัวเลือก",
"dynamicParamsAdvanced": "การตั้งค่าขั้นสูง (JSON, ไม่บังคับ)",
"dynamicParamsAdvancedPlaceholder": "{\"timeout_seconds\": 300}",
"dynamicParamsAdvancedPlaceholder": "ไม่บังคับ: วางพารามิเตอร์ JSON ขั้นสูง เช่น เพิ่มคีย์ timeout_seconds",
"dynamicParamsAdvancedInvalid": "รูปแบบ JSON ของการตั้งค่าขั้นสูงไม่ถูกต้อง จะไม่ถูกบันทึกจนกว่าจะแก้ไข",
"dynamicParamsJsonInvalid": "รูปแบบ JSON ไม่ถูกต้อง จะไม่ถูกบันทึกจนกว่าจะแก้ไข",
"dynamicParamsInvalid": "โปรดแก้ไขพารามิเตอร์งานที่ผิดพลาดก่อนบันทึก",
@@ -2307,6 +2327,7 @@
"headerLabelsJsonInvalid": "รูปแบบ JSON ของ header_labels ไม่ถูกต้อง",
"apiHeadersJsonInvalid": "รูปแบบ JSON ของ API Headers ไม่ถูกต้อง",
"runNowFailed": "การรันด้วยตนเองล้มเหลว",
"runNowWaitTimeout": "รอการรันเสร็จสิ้นเกินเวลาที่กำหนด (ประมาณ 15 นาที) หยุดรีเฟรชอัตโนมัติแล้ว โปรดค้นหาบันทึกด้วยตนเอง",
"downloadExcelFailed": "ดาวน์โหลด Excel ล้มเหลว",
"downloadInventoryRawZipFailed": "ดาวน์โหลด ZIP สต็อกดิบล้มเหลว",
"deleteFailed": "ลบตารางเวลาล้มเหลว"
@@ -3373,7 +3394,7 @@
"confirmReview": "ยืนยันการตรวจทานและเพิ่ม",
"correctionInvalid": "ค่าที่แก้ไขของรายการต้องเป็นออบเจ็กต์ฟิลด์ JSON",
"expectedRows": "ข้อมูลจริงที่ยืนยันโดยคน (อาร์เรย์ JSON)",
"expectedRowsPlaceholder": "[{\"customer_po_line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]",
"expectedRowsPlaceholder": "ตัวอย่าง: customer_po_line_no=00010, part_number=PN-1, qty=3 หนึ่งรายการ",
"expectedRowsHint": "กรอกข้อมูลจริงของรายการที่มนุษย์ยืนยันอย่างน้อยหนึ่งรายการ ห้ามคัดลอกผลลัพธ์ตัวเลือก.",
"expectedRowsInvalid": "ข้อมูลจริงต้องเป็นอาร์เรย์ JSON ที่มีอ็อบเจ็กต์รายการที่ไม่ว่างอย่างน้อยหนึ่งรายการ.",
"expectedOrderFields": "ข้อมูลจริงของฟิลด์คำสั่งซื้อ (ออบเจ็กต์ JSON)",
+4 -2
View File
@@ -1490,8 +1490,8 @@
"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": "รายการ", "selected": "เลือกแล้ว {count} ใบแจ้งส่งสินค้า", "batchDownload": "ดาวน์โหลดที่เลือก", "batchRpa": "อัปโหลด RPA แบบกลุ่ม", "batchConfirm": "ยืนยันว่าอัปโหลดแล้ว"},
"uploadComplete": {"title": "แจ้งเสร็จสิ้น", "subtitle": "ยืนยันหลักฐานความสำเร็จของการอัปโหลดแล้ว หน้านี้อ่านได้อย่างเดียว"},
"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": {
"intake_parse": "รับและแยกวิเคราะห์",
@@ -2223,6 +2223,7 @@
"adminDiagnosisStatus": "สถานะ: task_missing",
"adminDiagnosisHint": "ใช้การตรวจสอบงาน/ซ่อมข้อมูล ไม่กู้คืนอัตโนมัติในหน้านี้",
"stateInconsistent": "กำลังซิงก์สถานะ / ข้อมูลไม่สอดคล้อง",
"stageLoading": "กำลังโหลดสถานะล่าสุด…",
"statusRunning": "ระบบกำลังประมวลผล",
"statusFailedRetryable": "ล้มเหลว — ลองใหม่ได้",
"statusCompleted": "เสร็จสิ้น",
@@ -2744,6 +2745,7 @@
"domainFulfillmentShip": "จัดส่ง",
"currentNeedLabel": "ความต้องการปัจจุบัน: ",
"systemProcessingNeed": "ระบบกำลังประมวลผลอัตโนมัติ รอสักครู่หรือรีเฟรชความคืบหน้า",
"lifecycleWaitingNeed": "ขั้นตอนปัจจุบันต้องดำเนินการด้วยตนเอง",
"progressTitleWithStage": "ความคืบหน้าการประมวลผลคำสั่ง · {stage}",
"systemProcessingWithStage": "ระบบกำลังประมวลผล · {stage}",
"viewProcessDetails": "ดูรายละเอียดกระบวนการ",
+23 -2
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 平台"
@@ -2364,9 +2381,12 @@
"shippingInventorySourcesHelp": "选择需要执行的库存源;选项来自库存源配置,留空则全部执行。",
"dynamicParamsSelectPlaceholder": "请选择",
"dynamicParamsOptionsLoading": "选项加载中...",
"dynamicParamsLoading": "正在加载平台任务参数…",
"dynamicParamsLoadFailed": "平台任务参数加载失败,请重试",
"dynamicParamsRetry": "重新加载",
"dynamicParamsNoOptions": "暂无可选项",
"dynamicParamsAdvanced": "高级配置(JSON,可选)",
"dynamicParamsAdvancedPlaceholder": "{\"timeout_seconds\": 300}",
"dynamicParamsAdvancedPlaceholder": "可选:粘贴高级 JSON 对象参数,例如添加 timeout_seconds 等键值对",
"dynamicParamsAdvancedInvalid": "高级配置 JSON 格式错误,修正后才会保存",
"dynamicParamsJsonInvalid": "JSON 格式错误,修正后才会保存",
"dynamicParamsInvalid": "请修正任务参数中的错误后再保存",
@@ -2549,6 +2569,7 @@
"headerLabelsJsonInvalid": "header_labels JSON 格式错误,请检查",
"apiHeadersJsonInvalid": "API Headers JSON 格式错误,请检查",
"runNowFailed": "手动执行失败",
"runNowWaitTimeout": "等待执行完成超时(约 15 分钟),已停止自动刷新,可手动查询记录",
"downloadExcelFailed": "下载 Excel 失败",
"downloadInventoryRawZipFailed": "下载原始库存包失败",
"deleteFailed": "删除排程失败"
@@ -3615,7 +3636,7 @@
"confirmReview": "确认复核并加入盲测",
"correctionInvalid": "明细更正值必须是 JSON 字段对象。",
"expectedRows": "人工真值(JSON 数组)",
"expectedRowsPlaceholder": "[{\"customer_po_line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]",
"expectedRowsPlaceholder": "示例:customer_po_line_no 为 00010、part_number 为 PN-1、qty 为 3 的一条明细",
"expectedRowsHint": "请输入至少一条人工确认的明细真值;不能复制候选结果。",
"expectedRowsInvalid": "真值必须是至少包含一条非空明细对象的 JSON 数组。",
"expectedOrderFields": "订单字段真值(JSON 对象)",
+4 -2
View File
@@ -1597,8 +1597,8 @@
"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": "项次", "selected": "已选 {count} 个发货通知", "batchDownload": "批量下载", "batchRpa": "批量 RPA 上传", "batchConfirm": "批量确认已上传"},
"uploadComplete": {"title": "通知完成", "subtitle": "上传成功证据已核验,以下内容仅供查看。"},
"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": {
"intake_parse": "接收解析",
@@ -2342,6 +2342,7 @@
"adminDiagnosisStatus": "状态:task_missing",
"adminDiagnosisHint": "请通过任务审计/数据修复流程处理;本页不提供自动恢复。",
"stateInconsistent": "状态同步中 / 状态数据不一致",
"stageLoading": "正在获取最新状态…",
"statusRunning": "系统处理中",
"statusFailedRetryable": "失败可重试",
"statusCompleted": "已完成",
@@ -2818,6 +2819,7 @@
"domainFulfillmentShip": "发货履约",
"currentNeedLabel": "当前需要:",
"systemProcessingNeed": "系统正在自动处理,请稍候或刷新进度",
"lifecycleWaitingNeed": "当前步骤需要人工处理",
"progressTitleWithStage": "订单处理进度 · {stage}",
"systemProcessingWithStage": "系统处理中 · {stage}",
"viewProcessDetails": "查看流程详情",
+23 -2
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 平台"
@@ -2154,9 +2171,12 @@
"shippingInventorySourcesHelp": "選擇需要執行的庫存來源;選項來自庫存來源配置,留空則全部執行。",
"dynamicParamsSelectPlaceholder": "請選擇",
"dynamicParamsOptionsLoading": "選項載入中...",
"dynamicParamsLoading": "正在載入平台任務參數…",
"dynamicParamsLoadFailed": "平台任務參數載入失敗,請重試",
"dynamicParamsRetry": "重新載入",
"dynamicParamsNoOptions": "暫無可選項",
"dynamicParamsAdvanced": "進階配置(JSON,可選)",
"dynamicParamsAdvancedPlaceholder": "{\"timeout_seconds\": 300}",
"dynamicParamsAdvancedPlaceholder": "可選:貼上進階 JSON 物件參數,例如新增 timeout_seconds 等鍵值對",
"dynamicParamsAdvancedInvalid": "進階配置 JSON 格式錯誤,修正後才會儲存",
"dynamicParamsJsonInvalid": "JSON 格式錯誤,修正後才會儲存",
"dynamicParamsInvalid": "請修正任務參數中的錯誤後再儲存",
@@ -2312,6 +2332,7 @@
"headerLabelsJsonInvalid": "header_labels JSON 格式錯誤,請檢查",
"apiHeadersJsonInvalid": "API Headers JSON 格式錯誤,請檢查",
"runNowFailed": "手動執行失敗",
"runNowWaitTimeout": "等待執行完成逾時(約 15 分鐘),已停止自動重新整理,可手動查詢記錄",
"downloadExcelFailed": "下載 Excel 失敗",
"downloadInventoryRawZipFailed": "下載原始庫存包失敗",
"deleteFailed": "刪除排程失敗"
@@ -3378,7 +3399,7 @@
"confirmReview": "確認複核並加入盲測",
"correctionInvalid": "明細更正值必須是 JSON 欄位物件。",
"expectedRows": "人工真值(JSON 陣列)",
"expectedRowsPlaceholder": "[{\"customer_po_line_no\": \"00010\", \"part_number\": \"PN-1\", \"qty\": \"3\"}]",
"expectedRowsPlaceholder": "範例:customer_po_line_no 為 00010、part_number 為 PN-1、qty 為 3 的一筆明細",
"expectedRowsHint": "請輸入至少一筆人工確認的明細真值;不可複製候選結果。",
"expectedRowsInvalid": "真值必須是至少包含一個非空明細物件的 JSON 陣列。",
"expectedOrderFields": "訂單欄位真值(JSON 物件)",
+4 -2
View File
@@ -1490,8 +1490,8 @@
"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": "項次", "selected": "已選 {count} 個發貨通知", "batchDownload": "批量下載", "batchRpa": "批量 RPA 上傳", "batchConfirm": "批量確認已上傳"},
"uploadComplete": {"title": "通知完成", "subtitle": "上傳成功證據已核驗,以下內容僅供查看。"},
"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": {
"intake_parse": "接收解析",
@@ -2223,6 +2223,7 @@
"adminDiagnosisStatus": "狀態:task_missing",
"adminDiagnosisHint": "請透過任務審計/資料修復流程處理;本頁不提供自動恢復。",
"stateInconsistent": "狀態同步中 / 狀態資料不一致",
"stageLoading": "正在取得最新狀態…",
"statusRunning": "系統處理中",
"statusFailedRetryable": "失敗可重試",
"statusCompleted": "已完成",
@@ -2744,6 +2745,7 @@
"domainFulfillmentShip": "發貨履約",
"currentNeedLabel": "目前需要:",
"systemProcessingNeed": "系統正在自動處理,請稍候或重新整理進度",
"lifecycleWaitingNeed": "目前步驟需要人工處理",
"progressTitleWithStage": "訂單處理進度 · {stage}",
"systemProcessingWithStage": "系統處理中 · {stage}",
"viewProcessDetails": "查看流程詳情",
+48 -7
View File
@@ -123,7 +123,8 @@ Linux HXOPS 后端 Windows RPA Worker
- Linux 后端负责生成 trigger、接收回调、校验库存文件结构并入库;不在 Linux 上执行浏览器自动化。
- Windows Worker 负责浏览器自动化、读取 trigger、写入库存文件和发送心跳;它不直接连接 HXOPS 数据库。
- test 与 prod 必须使用不同的 SMB 共享、Windows 根目录、Linux 挂载目录、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID`、API Base、Tool API Key 和 RPA 凭据主密钥。
- Worker 进程启动后会在库存 trigger 目录写入 `.hxops_rpa_shared_mount`,并每 15 至 30 秒向 `/api/shipping-notice/rpa/heartbeat` 发送心跳。HXOPS 在 test/prod 写 trigger 前会检查 Worker 心跳、环境和共享 scope。
- Worker 进程启动后会在库存 trigger 目录写入 `.hxops_rpa_shared_mount`,并由**独立守护心跳线程**按 `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS`(默认 20s)周期向 `/api/shipping-notice/rpa/heartbeat` 发送心跳——心跳与批量导出解耦,长任务执行期间不会停发、后端不会误判离线。HXOPS 在 test/prod 写 trigger 前会检查 Worker 心跳、环境和共享 scope。
- 定时排程批量导出(`trigger_type=scheduled`)每完成一个站点,Worker 会调用 `/api/shipping-notice/rpa/inventory-batch-progress` 上报累计成功/跳过/失败笔数,管理端"库存RPA·执行记录"可实时看到当前 run 的进度;最终笔数仍以 `inventory-batch-ready` 回调为准。
@@ -541,7 +542,7 @@ docker compose --env-file .env.prod exec -T hxops-backend sh -lc 'ls -ld /mnt/hx
powershell.exe -NoProfile -ExecutionPolicy Bypass -File `
"C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1" `
-Environment test `
-ApiBase "http://192.168.100.192:5052" `
-ApiBase "http://192.168.100.192:8890" `
-WorkerRoot "C:\HxopsRpaTest" `
-SecretFile "C:\HxopsRpaSecrets\test.xml"
```
@@ -558,14 +559,13 @@ Test-Path "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1"
Unblock-File "C:\HxopsRpaTest\scripts\rpa\start_rpa_worker.ps1"
```
`-ApiBase` 必须填写 HXOPS 业务后端地址,不要填写 `HXOPS_TOOLS_API_BASE`(Tool API)。例如 `http://192.168.100.192:5052` 只有在该服务器确实监听测试后端并允许 Worker 访问时才可使用。启动前验证:
`-ApiBase` 必须填 Worker 实际可达的 HXOPS API 入口,判据是 `{base}/api/shipping-notice/rpa/heartbeat` 能访问到后端。Docker Compose 部署下后端容器内部监听 `5000`(`backend/deploy/gunicorn_config.py` 绑定 `0.0.0.0:5000`),而 `docker-compose.yml` 把宿主 `5052` 映射到容器内一个无监听端口,因此 `http://<host>:5052` 直连不可用;前端 nginx 网关(宿主 `8890`)把 `/api/` 反代到 `hxops-backend:5000`(见 `frontend/nginx.conf`),所以 Worker 应填网关地址,如 `http://192.168.100.192:8890`。该地址与 `HXOPS_TOOLS_API_BASE` 指向同一对外网关(都经 `/api/` 反代),实际以“`{base}/api/...` 可达”为准,不必拘泥于 Tool API / 业务后端的命名区分。启动前先验证网关端口连通:
```powershell
Test-NetConnection 192.168.100.192 -Port 5052
Invoke-WebRequest "http://192.168.100.192:5052/health" -UseBasicParsing
Test-NetConnection 192.168.100.192 -Port 8890
```
若 `TcpTestSucceeded` 为 `False`,应先核对测试服务器端口映射、防火墙和实际发布地址,不要改用 Tool API 端口代替。
注意 `<网关>:8890/health` 会命中前端 SPA、不会透传到后端,不能作为后端连通性判据;是否可达以后端为准(Worker 心跳 `[heartbeat]` 上报成功或管理端显示 Worker 在线)。若 `TcpTestSucceeded` 为 `False`,应先核对测试服务器网关端口映射、nginx `/api/` 反代与防火墙。
确认通过后,也可以在当前窗口执行普通命令:
@@ -609,7 +609,7 @@ test 必须包含 `scope_id=hxops-rpa-test-data`,prod 必须包含 `scope_id=h
### 步骤 11:创建 test/prod 后台任务
使用 RPA Windows 账号打开 PowerShell。先把 `$PythonExe`、test/prod API Base 替换成真实值,然后整段执行:
使用 RPA Windows 账号打开 PowerShell。先把 `$PythonExe`、test/prod API Base 替换成真实值,然后整段执行。test/prod 的 `-ApiBase` 应填实际可达的后端入口(同步骤 10:Docker Compose 部署填网关地址如 `http://192.168.100.192:8890`):
```powershell
$PythonExe = "C:\Users\<RPA用户>\AppData\Local\Programs\Python\Python312\python.exe"
@@ -1353,6 +1353,47 @@ Unregister-ScheduledTask -TaskName $TaskName -Confirm:$false
计划维护时,必须按“暂停新触发 → 处理/记录运行中 trigger → 停止任务”的顺序执行。恢复时按“确认 SMB 挂载 → 确认 HXOPS 后端 → 启动 Worker → 等待心跳/哨兵 → 恢复排程”的顺序执行。
#### 2.3.1 headless 后台模式(无可见 Edge,完全后台)
> 适用:希望彻底摆脱「可见 Edge + 交互式桌面」,让 Worker 无控制台、无浏览器窗口地后台常驻。
> 交付脚本:`scripts/rpa/register_rpa_background_tasks.ps1`(test/prod 双任务,headless + 隐藏控制台,仍为 RPA 账号的 `AtLogOn + Interactive` 任务)。
**切换前必须先完成 headless 冒烟预检(风险最高,不要跳过):**
```powershell
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "true"
# 在 RPA 主机验证真实登录/导出可通:
python scripts\rpa\dsv_login_smoke.py
python scripts\rpa\crane_login_smoke.py
# 若触及上传,再验证一次 headless 下的上传流程
```
只有 DSV/Crane 在 headless 下登录、下载、回调(以及在启用时的上传)都能通过,才切换正式运行;否则仍用 2.3 的可见模式。
**注册后台任务(在 RPA 账号的 PowerShell 中执行):**
```powershell
cd C:\HxopsRpaTest
.\scripts\rpa\register_rpa_background_tasks.ps1 # 注册 test/prod 两个任务
.\scripts\rpa\register_rpa_background_tasks.ps1 -Start # 立即启动(默认 all)
.\scripts\rpa\register_rpa_background_tasks.ps1 -Status # 查看状态(默认 all)
.\scripts\rpa\register_rpa_background_tasks.ps1 -Stop # 停止(默认 all)
.\scripts\rpa\register_rpa_background_tasks.ps1 -Unregister # 注销(默认 all)
# 区分环境:用 -Scope test|prod|all(默认 all)
.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope test -Status # 只看 test
.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope prod -Start # 只启动 prod
.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope test -Unregister # 只注销 test
```
- **`-Scope test|prod|all`**:`Start/Stop/Status/Unregister`(以及默认注册)都可只作用于单个环境;不带 `-Scope` 时默认操作 test 和 prod 两个任务。两个任务是独立命名的(`HXOPS Inventory RPA Worker TEST` / `...PROD`),也可用原生 `Get-ScheduledTask -TaskName <任务名>` 单独查询。
- 与 2.3 可见模式仅两处差异:计划任务给 `powershell.exe` 加 `-WindowStyle Hidden`(无控制台),并给 `start_rpa_worker.ps1` 加 `-Headless`(Playwright headless,无可见 Edge)。其余 `AtLogOn`、`Interactive`、`RestartCount/RestartInterval`、`ExecutionTimeLimit=0`、`MultipleInstances=IgnoreNew` 均与 2.3 一致。
- **不能改成 `SYSTEM` / `AtStartup` / Session 0 服务**:此处约束已从“浏览器需要交互桌面”变为“Secret 文件是用户级 DPAPI”。`new_rpa_worker_secret.ps1` 用 `Export-Clixml` 生成用户级 DPAPI 密文,改成非交互上下文(SYSTEM/服务/其他账号)会解密失败。
- **RPA 账号请配置自动登录,且不要锁屏/注销**:headless 去掉了浏览器窗口依赖,但 `AtLogOn + Interactive` 仍要求该账号保持交互登录,否则任务不会常驻。
- `-ApiBase` 同样填前端 nginx 网关地址(例如 `http://192.168.100.192:8890`),与 2.3 一致;脚本默认值已按此预填,可按实际地址改。
- **回滚**:改用 2.3 的可见模式重新注册即可(去掉 `-Headless` 与 `-WindowStyle Hidden`),无需改动 Worker 或共享目录。
### 2.4 Linux 正式环境:Windows Prod Worker + SMB 共享
正式环境的流程与测试环境相同,但资源必须全部切换为 prod。**禁止**复制 test 的 `.env`、Windows 环境变量、浏览器 profile 或共享目录后直接上线。
+8
View File
@@ -477,6 +477,10 @@ def _submit_dsv_password_form(page: Any) -> bool:
核心逻辑:优先直接点击可见登录按钮;如果页面使用 Vue/隐藏字段组合提交,
则退回到 DOM 脚本里触发 `pf.ok` / form submit / Enter,避免“密码已填完但未真正登录”。
"""
# 密码已填写后 DSV 也可能弹出“使用密码升级登录!”(也许以后/立即启用)遮挡登录按钮;
# 提交前先关闭,避免“DSV login password step detected but login button was not found”。
if _is_dsv_password_upgrade_redirect(page) and _has_dsv_password_upgrade_prompt(page):
_dismiss_dsv_password_upgrade_prompt(page)
selectors = (
'button[name="login"]',
'button[type="submit"]',
@@ -546,6 +550,10 @@ def _submit_dsv_password_form(page: Any) -> bool:
def _looks_like_dsv_login_method_page(page: Any) -> bool:
# 升级提示弹窗文案含“密码”(“使用密码升级登录!”),会命中“选择登录方法”的
# 宽泛 needle 造成误判(反复尝试点击“密码方式”而非关闭弹窗);命中升级提示时直接判非方法页。
if _has_dsv_password_upgrade_prompt(page):
return False
needles = ("选择登录方法", "密码", "Password", "输入您的密码并登录", "Choose a sign-on method")
for frame in page.frames:
try:
+7
View File
@@ -30,6 +30,7 @@ _DSV_USERNAME_SELECTORS = dsv_auth._DSV_USERNAME_SELECTORS
_click_dsv_continue = dsv_auth._click_dsv_continue
_click_dsv_password_method = dsv_auth._click_dsv_password_method
_debug_dsv_login_method_page = dsv_auth._debug_dsv_login_method_page
_dismiss_dsv_password_upgrade_prompt = dsv_auth._dismiss_dsv_password_upgrade_prompt
_dismiss_dsv_password_upgrade_prompt_after_login_redirect = dsv_auth._dismiss_dsv_password_upgrade_prompt_after_login_redirect
_dsv_login_debug_value = dsv_auth._dsv_login_debug_value
_dsv_login_ready_timeout_ms = dsv_auth._dsv_login_ready_timeout_ms
@@ -37,8 +38,10 @@ _fill_dsv_password_page_fields = dsv_auth._fill_dsv_password_page_fields
_fill_dsv_username = dsv_auth._fill_dsv_username
_find_dsv_password_locator = dsv_auth._find_dsv_password_locator
_has_dsv_human_check_prompt = dsv_auth._has_dsv_human_check_prompt
_has_dsv_password_upgrade_prompt = dsv_auth._has_dsv_password_upgrade_prompt
_is_dsv_blank_auth_transition = dsv_auth._is_dsv_blank_auth_transition
_is_dsv_oauth_handshake_url = dsv_auth._is_dsv_oauth_handshake_url
_is_dsv_password_upgrade_redirect = dsv_auth._is_dsv_password_upgrade_redirect
_is_dsv_username_page = dsv_auth._is_dsv_username_page
_submit_dsv_password_form = dsv_auth._submit_dsv_password_form
_wait_for_dsv_auth_page_ready = dsv_auth._wait_for_dsv_auth_page_ready
@@ -241,6 +244,10 @@ def _maybe_auto_login_dsv(page: Any) -> None:
password_method_clicked_at = 0.0
username_retry_allowed_at = time.monotonic() + 6
while time.monotonic() < login_deadline:
# [STEP 1] DSV 在密码阶段前(authorization.ping)也会弹出“使用密码升级登录!”
# 引导弹窗(也许以后/立即启用),会遮挡密码表单和登录按钮;先点“也许以后”关闭再探测。
if _is_dsv_password_upgrade_redirect(page) and _has_dsv_password_upgrade_prompt(page):
_dismiss_dsv_password_upgrade_prompt(page)
password_locator = _find_dsv_password_locator(page, timeout_ms=250)
if password_locator is not None:
break
+122 -48
View File
@@ -840,8 +840,39 @@ def _dsv_report_has_inventory_data_rows(page: Any) -> bool:
return False
def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value: str | None) -> None:
"""委托 dsv_report_parameters 按 SSRS 控件类型填充报表参数。"""
def _wait_dsv_report_inventory_rows(page: Any, *, timeout_ms: int) -> bool:
"""
条件轮询等待 SSRS 结果页出现真实库存明细行。
核心逻辑:result_ready(分页/导出按钮状态)先就绪,但当前页明细行是异步渲染进 DOM 的,
单次快照可能撞上"分页已出、行未渲染"的窗口,把有数据的报表误判为无数据;
这里以 1s 间隔轮询,直到明细行出现或超时,再交给调用方决定 success/skip。
"""
deadline = time.monotonic() + max(1.0, timeout_ms / 1000)
while time.monotonic() < deadline:
if _dsv_report_has_inventory_data_rows(page):
return True
time.sleep(1.0)
return False
def _fill_dsv_filter_if_needed(
page: Any,
selector_env: str,
label: str,
value: str | None,
*,
report_name: str | None = None,
) -> None:
"""委托 dsv_report_parameters 按 SSRS 控件类型填充报表参数。
Args:
page: Playwright Page。
selector_env: Warehouse/Owner/PutawayZone 对应 selector 环境变量名。
label: 参数名。
value: 参数值。
report_name: 报表名;透传给 dsv_report_parameters 按报表模板解析控件。
"""
module_path = Path(__file__).resolve().parent / "dsv_report_parameters.py"
spec = importlib.util.spec_from_file_location("dsv_report_parameters_runtime", module_path)
assert spec and spec.loader
@@ -855,6 +886,7 @@ def _fill_dsv_filter_if_needed(page: Any, selector_env: str, label: str, value:
env=_env,
browser_timeout_ms=_browser_timeout_ms,
debug_stage=_debug_dsv_stage,
report_name=report_name,
)
@@ -866,11 +898,13 @@ def _fill_dsv_multi_select(
*,
selectors: dict[str, str] | None = None,
select_all: bool = False,
report_name: str | None = None,
) -> None:
"""
填充 DSV 报表多选控件(multi_select)。
核心逻辑:显式配置 SSRS checkbox 下拉时委托 dsv_report_parameters;
否则优先 select_option 多值,失败则展开控件后逐条点击 option/checkbox。
report_name 用于按报表模板解析控件(同参数名在不同报表控件长相不同)。
"""
cleaned = [str(item).strip() for item in values if str(item).strip()]
if not cleaned and not select_all:
@@ -888,6 +922,7 @@ def _fill_dsv_multi_select(
selectors=selectors,
select_all=select_all,
browser_timeout_ms=_browser_timeout_ms,
report_name=report_name,
):
return
selector = _env(selector_env)
@@ -918,13 +953,14 @@ def _fill_dsv_multi_select(
except Exception as exc:
print(f"[dsv-filter] {label} multi_select click fallback failed: {exc}", file=sys.stderr)
for value in cleaned:
_fill_dsv_filter_if_needed(page, selector_env, label, value)
_fill_dsv_filter_if_needed(page, selector_env, label, value, report_name=report_name)
def _fill_report_parameter(page: Any, parameter: dict[str, Any]) -> None:
def _fill_report_parameter(page: Any, parameter: dict[str, Any], *, report_name: str | None = None) -> None:
"""按库存源业务参数填充 DSV 报表条件(single / multi_text / multi_select)。
核心逻辑:selector 从 Driver 内部参数名映射获取,不允许库存源配置携带页面实现细节。
核心逻辑:selector 从 Driver 内部参数名映射获取,不允许库存源配置携带页面实现细节;
report_name 交给 dsv_report_parameters 按报表模板解析控件类型(3lv select vs JDA multi_value)。
"""
if not isinstance(parameter, dict):
return
@@ -936,7 +972,7 @@ def _fill_report_parameter(page: Any, parameter: dict[str, Any]) -> None:
return
if mode == "multi_text":
joiner = str(parameter.get("joiner") or ",")
_fill_dsv_filter_if_needed(page, selector_env, name, joiner.join(values))
_fill_dsv_filter_if_needed(page, selector_env, name, joiner.join(values), report_name=report_name)
return
if mode == "multi_select":
_fill_dsv_multi_select(
@@ -946,9 +982,10 @@ def _fill_report_parameter(page: Any, parameter: dict[str, Any]) -> None:
values,
selectors=None,
select_all=bool(parameter.get("select_all", False)),
report_name=report_name,
)
return
_fill_dsv_filter_if_needed(page, selector_env, name, values[0])
_fill_dsv_filter_if_needed(page, selector_env, name, values[0], report_name=report_name)
def _dsv_parameter_selector_env(parameter_name: str) -> str:
@@ -966,15 +1003,16 @@ def _dsv_parameter_selector_env(parameter_name: str) -> str:
def _fill_report_parameters(page: Any, source: dict[str, Any]) -> None:
"""填充 source.parameters;无 parameters 时回退 query 字段。"""
report_name = _dsv_report_name(source)
parameters = source.get("parameters")
if isinstance(parameters, list) and parameters:
for item in parameters:
_fill_report_parameter(page, item)
_fill_report_parameter(page, item, report_name=report_name)
return
query = source.get("query") if isinstance(source.get("query"), dict) else {}
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"))
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"))
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", query.get("warehouse_code"))
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR", "Owner", query.get("owner_code"), report_name=report_name)
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_PUTAWAY_ZONE_SELECTOR", "PutawayZone", query.get("putaway_zone"), report_name=report_name)
_fill_dsv_filter_if_needed(page, "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", query.get("warehouse_code"), report_name=report_name)
def _dsv_entry_url_host(entry_url: str) -> str:
@@ -1164,46 +1202,65 @@ def _return_to_dsv_report_parameters(page: Any, report_name: str) -> None:
_wait_for_dsv_report_form_ready(page, report_name)
def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str:
"""从 portal 首页导航至目标报表参数页,并记录完整导航耗时。"""
def _navigate_dsv_to_report_form_once(page: Any, source: dict[str, Any], report_name: str) -> None:
"""单次报表导航:开 Reports 菜单 → program_group → program_label → 分组 → 报表 → 等表单就绪。"""
query = source.get("query") if isinstance(source.get("query"), dict) else {}
navigation = source.get("navigation") if isinstance(source.get("navigation"), dict) else {}
reports_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORTS_SELECTOR")
if reports_selector:
page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True)
else:
_click_dsv_reports_menu(page)
_wait_for_dsv_reports_open(page, timeout_ms=10_000)
program_group = str(query.get("program_group") or navigation.get("program_group") or "").strip()
program_label = str(query.get("program_label") or navigation.get("program_label") or "").strip()
report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory")
program_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_PROGRAM_SELECTOR")
if program_selector:
page.locator(program_selector).first.click(timeout=_browser_timeout_ms())
else:
if program_group and program_group != program_label:
_click_dsv_menu_item(page, program_group, next_text=program_label)
_click_dsv_menu_item(page, program_label, next_text=report_group)
report_group_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_GROUP_SELECTOR")
if report_group_selector:
page.locator(report_group_selector).first.click(timeout=_browser_timeout_ms())
else:
_click_dsv_report_group(page, report_group, next_text=report_name)
report_name_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_NAME_SELECTOR")
if report_name_selector:
page.locator(report_name_selector).first.click(timeout=_browser_timeout_ms())
else:
_click_dsv_menu_item(page, report_name)
_wait_for_dsv_report_form_ready(page, report_name)
def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str:
"""
从当前页导航至目标报表参数页,并记录完整导航耗时。
核心逻辑:直连优先——当前页若已带常驻 Reports 导航(批内后续源),直接开菜单导航;
失败时整页回 portal 首页重置一次再试(清理旧 SSRS 状态),仍失败才上抛。
"""
report_name = _dsv_report_name(source)
entry_url = str(source.get("entry_url") or source.get("login_url") or "").strip()
started_at = time.monotonic()
_report_dsv_chain_stage("report_navigation", "start", extra={"reportName": report_name})
try:
reports_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORTS_SELECTOR")
if reports_selector:
page.locator(reports_selector).first.click(timeout=_browser_timeout_ms(), force=True)
else:
_click_dsv_reports_menu(page)
_wait_for_dsv_reports_open(page, timeout_ms=10_000)
program_group = str(query.get("program_group") or navigation.get("program_group") or "").strip()
program_label = str(query.get("program_label") or navigation.get("program_label") or "").strip()
report_group = str(query.get("report_group") or navigation.get("report_group") or "Inventory")
program_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_PROGRAM_SELECTOR")
if program_selector:
page.locator(program_selector).first.click(timeout=_browser_timeout_ms())
else:
if program_group and program_group != program_label:
_click_dsv_menu_item(page, program_group, next_text=program_label)
_click_dsv_menu_item(page, program_label, next_text=report_group)
report_group_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_GROUP_SELECTOR")
if report_group_selector:
page.locator(report_group_selector).first.click(timeout=_browser_timeout_ms())
else:
_click_dsv_report_group(page, report_group, next_text=report_name)
report_name_selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_REPORT_NAME_SELECTOR")
if report_name_selector:
page.locator(report_name_selector).first.click(timeout=_browser_timeout_ms())
else:
_click_dsv_menu_item(page, report_name)
_wait_for_dsv_report_form_ready(page, report_name)
try:
_navigate_dsv_to_report_form_once(page, source, report_name)
except Exception as exc:
# [RETRY] 报表上下文直连失败:整页回首页清掉旧 SSRS/菜单状态后重试一次。
if not entry_url:
raise
print(f"[dsv-navigation] direct navigation failed, reset home and retry once: {exc}", file=sys.stderr)
_reset_dsv_export_entry(page, entry_url)
_navigate_dsv_to_report_form_once(page, source, report_name)
except Exception as exc:
_report_dsv_chain_stage(
"report_navigation", "error", started_at=started_at,
@@ -1214,6 +1271,17 @@ def _navigate_dsv_to_report_form(page: Any, source: dict[str, Any]) -> str:
return report_name
def _dsv_download_wait_ms() -> int:
"""
DSV Excel 导出下载等待窗口(毫秒)。
核心逻辑:按实测 P99 设定——报表结果就绪后,SSRS 端生成+响应在 34s~90s+ 波动
(2026-08-26 实测 54s 命中、87s 兜底救回、90s+ 超时)。默认 240s 覆盖长尾,
用 `SHIPPING_NOTICE_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS` 可按站点调整。
"""
return max(60_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_DOWNLOAD_WAIT_MS", "240000") or "240000"))
def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> Any:
"""参数页已就绪后:填参 → View Report → 等结果 → 导出 Excel,并分别记录阶段耗时。"""
report_name = _dsv_report_name(source)
@@ -1240,7 +1308,9 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
# [STEP 1] DSV 页面会维持长连接;等待 networkidle 不能说明 SSRS 已可导出,
# 反而可能额外消耗十秒。直接等待现有的报表业务就绪条件。
_wait_dsv_report_ready(page, timeout_ms=_browser_timeout_ms())
if not _dsv_report_has_inventory_data_rows(page):
# [STEP 2] result_ready 只代表分页/导出状态就绪,明细行异步渲染可能晚几秒;
# 用条件轮询等待真实数据行,避免把"有数据但行未渲染"误判成 skip。
if not _wait_dsv_report_inventory_rows(page, timeout_ms=min(_browser_timeout_ms(), 45_000)):
raise NoInventoryDataError("DSV report has no inventory data")
except Exception as exc:
_report_dsv_chain_stage(
@@ -1267,7 +1337,7 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
download_event_started_at = time.monotonic()
_report_dsv_chain_stage("excel_download_event", "start", extra={"reportName": report_name})
try:
with page.expect_download(timeout=_browser_timeout_ms()) as download_info:
with page.expect_download(timeout=_dsv_download_wait_ms()) as download_info:
_click_dsv_export_excel(page)
except Exception as exc:
selected = _find_dsv_report_result_frame(page)
@@ -1301,9 +1371,11 @@ def _run_dsv_inventory_export_from_form(page: Any, source: dict[str, Any]) -> An
file=sys.stderr,
)
if download_dir:
# 事件确实晚到/丢失时的目录兜底:窗口放宽到 60s,覆盖已观测的"超时后 0-3s 落盘"场景。
fallback_download = _wait_for_new_download_file(
download_dir=download_dir,
baseline_names=baseline_names,
timeout_seconds=60.0,
)
if fallback_download is not None:
print(
@@ -1373,7 +1445,9 @@ def _prepare_dsv_batch_export_step(
return True
except Exception as exc:
print(f"[dsv-batch] parameter reuse failed, fallback home reset: {exc}", file=sys.stderr)
_reset_dsv_export_entry(page, entry_url)
# 导航不同的后续源:当前页已带登录态与常驻 Reports 导航,直接进入菜单导航,
# 不再整页 goto portal 首页(省 ~12s 且避开 public/login 认证回落一闪)。
# 旧 SSRS 状态串站/导航失败由 _navigate_dsv_to_report_form 内部"重置首页重试一次"兜底。
return False
+117 -5
View File
@@ -34,6 +34,51 @@ _DSV_REPORT_PARAM_DEFAULTS: dict[str, dict[str, str]] = {
}
def _normalize_report_name(report_name: str) -> str:
"""报表名归一化:去首尾空白并折叠连续空白、统一小写,用于模板精确匹配。"""
return " ".join(str(report_name or "").strip().lower().split())
# 报表名 → 参数控件模板。同名的 SSRS 参数在不同报表里的控件长相不同:
# - 3lv 版(On Hand Inventory By Location 3lv,Bison/AWSBI):Warehouse 是原生 select(ddValue);
# - JDA 版(On Hand Inventory by Location,Moerdijk 等):Warehouse 是 txtValue + toggle + divDropDown
# 组成的多选框下拉(multi_value),历史 YAML 为该源配置的 selectors 即源于此。
# 模板按"归一化报表名"精确匹配;未命中时回退 _DSV_REPORT_PARAM_DEFAULTS(保持旧行为)。
_DSV_REPORT_PARAM_TEMPLATES: dict[str, dict[str, dict[str, str]]] = {
"on hand inventory by location 3lv": {
"Warehouse": {
"control": "select",
"selector": "#ReportViewerMain_ctl08_ctl17_ddValue",
},
},
"on hand inventory by location": {
"Warehouse": {
"control": "multi_value",
"text": "#ReportViewerMain_ctl08_ctl17_txtValue",
"toggle": "#ReportViewerMain_ctl08_ctl17_ctl01",
"dropdown": "#ReportViewerMain_ctl08_ctl17_divDropDown",
},
},
}
def resolve_parameter_controls(report_name: str | None, label: str) -> dict[str, str]:
"""
按(报表名, 参数名)解析 SSRS 控件配置;报表模板优先,未命中返回空 dict。
Args:
report_name: 当前报表名(如 navigation.report_name),允许为空。
label: 参数名(Owner / PutawayZone / Warehouse)。
Returns:
dict[str, str]: 控件配置(control/selector 或 control/text/toggle/dropdown);
报表未登记时为空 dict,由调用方回退参数名默认值。
"""
key = _normalize_report_name(report_name)
template = _DSV_REPORT_PARAM_TEMPLATES.get(key) or {}
return dict(template.get(str(label or "").strip()) or {})
def _iter_dsv_report_roots(page: Any) -> list[Any]:
"""返回包含 ReportViewerMain 的 frame;找不到时回退到全部 roots。"""
matched: list[Any] = []
@@ -370,6 +415,52 @@ def _fill_select_parameter(page: Any, label: str, value: str, selector: str, *,
return False
def _probe_report_parameter_controls(page: Any) -> dict[str, Any]:
"""
枚举报表参数区(ReportViewerMain_ctl08)的实际控件,用于填参失败时定位控件类型漂移。
核心逻辑:SSRS 对同一参数名在不同报表里可能渲染成原生 select、文本框或多选框下拉;
失败日志带上本探针后,无需人工开浏览器即可判断目标控件是否存在、option 数是否为空。
"""
roots = _iter_dsv_report_roots(page)
probe: dict[str, Any] = {"roots": len(roots), "controls": []}
for root in roots:
try:
items = root.evaluate(
"""
() => {
const normalize = (text) => ((text || '') + '').replace(/\\s+/g, ' ').trim();
const nodes = Array.from(document.querySelectorAll(
'#ReportViewerMain_ctl08 select, #ReportViewerMain_ctl08 input, ' +
'#ReportViewerMain_ctl08 [id$="_divDropDown"]'
));
return nodes.slice(0, 60).map((node) => {
const table = node.tagName.toLowerCase() === 'select'
? Array.from(node.options || []).map((item) => normalize(item.textContent)).filter(Boolean)
: [];
const dropdown = node.getAttribute('id') || '';
return {
id: dropdown,
tag: node.tagName.toLowerCase(),
type: node.getAttribute('type') || '',
hidden: node.getAttribute('type') === 'hidden',
optionCount: table.length,
firstOptions: table.slice(0, 12),
labelText: normalize(
(node.closest('td') || {}).innerText || ''
).slice(0, 120),
};
});
}
""",
)
if isinstance(items, list):
probe["controls"].extend(items)
except Exception as exc:
probe["controls"].append({"probe_error": str(exc)[:120]})
return probe
def fill_dsv_filter_if_needed(
page: Any,
selector_env: str,
@@ -379,10 +470,13 @@ def fill_dsv_filter_if_needed(
env: Callable[[str, str], str],
browser_timeout_ms: Callable[[], int],
debug_stage: Callable[..., None] | None = None,
report_name: str | None = None,
) -> None:
"""
按 ReportViewer 控件类型填充 DSV 报表参数。
核心逻辑:优先使用 JSON/页面默认 selector;Warehouse 走 select_option,Owner/PutawayZone 走 checkbox。
报表模板(_DSV_REPORT_PARAM_TEMPLATES)登记了同类报表的控件差异:传入 report_name 时,
先按模板选择 multi_value/select;未命中的报表回退参数名默认值(旧行为)。
"""
text = str(value or "").strip()
if not text:
@@ -401,7 +495,11 @@ def fill_dsv_filter_if_needed(
pass
timeout_ms = browser_timeout_ms()
defaults = _DSV_REPORT_PARAM_DEFAULTS.get(label, {})
defaults = dict(_DSV_REPORT_PARAM_DEFAULTS.get(label, {}))
# 报表模板优先:同一参数名在不同报表的控件长相不同(3lv select vs JDA multi_value)。
template_controls = resolve_parameter_controls(report_name, label)
if template_controls:
defaults.update(template_controls)
custom_selector = str(env(selector_env) or "").strip()
selector = custom_selector or defaults.get("selector") or defaults.get("text")
@@ -412,17 +510,22 @@ def fill_dsv_filter_if_needed(
values = [part.strip() for part in text.split(",") if part.strip()] if label == "PutawayZone" else [text]
# [STEP 1] 模板登记为 multi_value(或 Owner/PutawayZone 固有多选)时,优先走 checkbox 下拉填充。
if defaults.get("control") == "multi_value" or label in {"Owner", "PutawayZone"}:
if _fill_multi_value_parameter(page, label, values, timeout_ms=timeout_ms):
if _fill_multi_value_parameter(
page, label, values, timeout_ms=timeout_ms, config_override=defaults,
):
_debug(f"filter-filled-{label.lower()}", text)
return
# [STEP 2] 原生 select 路径:模板为 select 或未登记时继续旧行为(ddValue + 选项等待/脚本赋值)。
select_selector = custom_selector or defaults.get("selector", "")
if defaults.get("control") == "select" or label == "Warehouse" or select_selector.endswith("ddValue"):
if select_selector and (defaults.get("control") == "select" or select_selector.endswith("ddValue")):
if _fill_select_parameter(page, label, text, select_selector, timeout_ms=timeout_ms):
_debug(f"filter-filled-{label.lower()}", text)
return
# [STEP 3] 文本输入/脚本兜底:适用于普通文本参数与多选控件的输入框。
print(f"[dsv-filter] filling {label} text={text!r} selector={selector!r}")
for root in _iter_dsv_report_roots(page):
if _fill_input_via_script(root, selector, text):
@@ -440,6 +543,12 @@ def fill_dsv_filter_if_needed(
except Exception as exc:
print(f"[dsv-filter] {label} fill fallback failed: {exc}", file=sys.stderr)
# 全部路径失败:输出参数区控件探针,便于下轮直接定位控件 ID/类型漂移。
print(
f"[dsv-filter] {label} control probe: "
f"{json.dumps(_probe_report_parameter_controls(page), ensure_ascii=False)[:1500]}",
file=sys.stderr,
)
print(f"[dsv] failed to fill {label} filter text={text!r}", file=sys.stderr)
_debug(f"filter-failed-{label.lower()}", text)
@@ -452,16 +561,19 @@ def fill_dsv_multi_select_parameter(
selectors: dict[str, str] | None = None,
select_all: bool = False,
browser_timeout_ms: Callable[[], int],
report_name: str | None = None,
) -> bool:
"""
填充由 YAML `mode: multi_select` 显式声明的 SSRS checkbox 下拉参数。
【AI 触发时机】:当 DSV 报表参数不是原生 select,而是 `txtValue + divDropDown + checkbox`
组合控件时调用;例如 AWSAMS 的 Warehouse 下拉需要全选。
核心逻辑:selectors 缺省时按报表模板(report_name)解析控件;两者都没有则返回 False。
"""
config_override = {"control": "multi_value"}
if selectors:
effective_selectors = selectors or (resolve_parameter_controls(report_name, label) or None)
if effective_selectors:
for key in ("text", "toggle", "dropdown"):
value = str(selectors.get(key) or "").strip()
value = str(effective_selectors.get(key) or "").strip()
if value:
config_override[key] = value
if not all(config_override.get(key) for key in ("text", "toggle", "dropdown")):
+39
View File
@@ -235,3 +235,42 @@ def maybe_send_heartbeat(
_start_heartbeat_request(payload)
_LAST_HEARTBEAT_MONO = now
return now
def start_heartbeat_loop(
*,
trigger_dir: str | Path,
drop_dir: str | Path,
interval_seconds: float,
) -> threading.Thread:
"""
启动独立守护心跳线程,使心跳节奏与业务主循环解耦。
核心逻辑:批量站点导出(浏览器登录+下载)会长时间阻塞 worker 主循环;若心跳由
主循环发送,执行期间会停发,后端按心跳 TTL 误判 Worker 离线。本线程按固定间隔
持续上报,主循环只负责业务扫描;线程内异常仅打印,绝不退出。
Args:
trigger_dir: 触发目录(哨兵写入与心跳 payload 使用)。
drop_dir: 库存落盘目录(心跳 payload 使用)。
interval_seconds: 心跳间隔;实际以环境变量最小 15s 为准。
Returns:
已启动的守护线程(daemon,随进程退出)。
"""
def _loop() -> None:
while True:
time.sleep(max(5.0, float(interval_seconds)))
try:
maybe_send_heartbeat(
trigger_dir=trigger_dir,
drop_dir=drop_dir,
last_sent_mono=0.0,
force=True,
)
except Exception:
print("[heartbeat] loop tick failed", file=sys.stderr)
thread = threading.Thread(target=_loop, name="shipping-rpa-heartbeat-loop", daemon=True)
thread.start()
return thread
+267 -86
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
@@ -1080,6 +1079,34 @@ def _configuration_test_callback_payload(run_no: str, results: list) -> dict:
}
def _emit_batch_progress(body: dict[str, Any], run_no: str, results: list[dict[str, Any]]) -> None:
"""
定时排程批量导出每完成一个站点即上报累计进度,后端实时回写排程 run 笔数。
核心逻辑:仅 scheduled 触发且携带 schedule_run_id 时上报,按需单票不受影响;
best-effort,上报失败不影响导出与最终回调;最终笔数以 inventory-batch-ready 为准。
"""
if str(body.get("trigger_type") or "").strip() != "scheduled":
return
schedule_run_id = body.get("schedule_run_id")
if schedule_run_id is None:
return
summary = _summarize_inventory_batch_results(results)
try:
_post_callback("/api/shipping-notice/rpa/inventory-batch-progress", {
"schema_version": "shipping_inventory_rpa.v2",
"callback_id": body.get("callback_id"),
"batch_run_no": run_no,
"run_no": run_no,
"schedule_run_id": schedule_run_id,
"success_count": summary["success_count"],
"skipped_count": summary["skipped_count"],
"failed_count": summary["failed_count"],
})
except Exception as exc:
print(f"[inventory-batch] progress callback failed {run_no}: {exc}", file=sys.stderr)
def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processed_dir: Path) -> None:
body = json.loads(trigger_path.read_text(encoding="utf-8"))
run_no = str(body.get("batch_run_no") or body.get("run_no") or trigger_path.stem).strip()
@@ -1094,7 +1121,19 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
identity_errors.append("schema_version")
if body.get("callback_id") is None or (isinstance(body.get("callback_id"), str) and not body.get("callback_id").strip()):
identity_errors.append("callback_id")
if body.get("task_no") is None or (isinstance(body.get("task_no"), str) and not body.get("task_no").strip()):
# 定时排程批量触发是按 run 计价的:只携带 run_no/schedule_run_id,没有逐源
# Attempt/Gate 身份。身份校验按模式取值:scheduled 只强制信封与站点分发字段,
# 业务终态由后端按 schedule_run_id + DB 配置校验;其余模式保持逐源身份 fail-closed。
is_scheduled_batch = str(body.get("trigger_type") or "").strip() == "scheduled"
source_required = set(_INVENTORY_V2_REQUIRED_FIELDS) - {"schema_version", "task_no", "callback_id"}
if is_scheduled_batch:
source_required -= {
"task_no", "source_run_no", "attempt_no", "lease_token", "candidate_set_id",
"execution_id", "gate_id", "callback_id", "expected_warehouse_id",
}
if not is_scheduled_batch and (
body.get("task_no") is None or (isinstance(body.get("task_no"), str) and not body.get("task_no").strip())
):
identity_errors.append("task_no")
for index, source in enumerate(sources):
if not isinstance(source, dict):
@@ -1107,9 +1146,8 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
).strip().lower() not in {"crane", "crane_footprint"}
identity_errors.extend(
f"inventory_sources[{index}].{key}"
for key in _INVENTORY_V2_REQUIRED_FIELDS
if key not in {"schema_version", "task_no", "callback_id"}
and (key != "expected_warehouse_id" or requires_expected_warehouse)
for key in source_required
if (key != "expected_warehouse_id" or requires_expected_warehouse)
and (source.get(key) is None or (isinstance(source.get(key), str) and not source.get(key).strip()))
)
if identity_errors:
@@ -1152,6 +1190,11 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
mode = "mock" if mock else "browser"
results: list[dict[str, Any]] = []
def record_result(item: dict[str, Any]) -> None:
"""记录单站点结果并即时上报累计进度(仅定时排程会真正上报)。"""
results.append(item)
_emit_batch_progress(body, run_no, results)
# v2 claimed 回调只记录领取事实,不代表业务成功。
if body.get("schema_version") == "shipping_inventory_rpa.v2":
claimed_items = []
@@ -1191,7 +1234,7 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
report_configuration_test_progress(source)
task_stub = run_no
out_file = _write_sample_inventory(drop_dir, task_stub)
results.append({
record_result({
"source_code": source.get("source_code"),
"warehouse_id": source.get("warehouse_id"),
"status": "success",
@@ -1228,28 +1271,52 @@ def _handle_inventory_batch_trigger(trigger_path: Path, drop_dir: Path, processe
_validate_inventory_source_for_rpa(source)
skip_navigation = False
if site == "dsv360":
# DSV 报表页会保留 iframe、导出菜单与下载等待状态;同一 tab
# 串行切换站点会让下一站误用上一站页面。复用 context 登录态,但每站新开页面。
if index > 0:
# [STEP 3] 批内同一 Profile 只登录一次:首源完整登录,后续源复用当前 tab
# 的登录态——同导航走 _return_to_dsv_report_parameters 复用参数页,
# 导航不同走 _reset_dsv_export_entry(goto entry + 会话检测,不重复 OAuth)。
# 曾因"每源新开空白页 + 写死 index=0"导致每源重复走 SSO 重定向链
# (每源 2-2.5 分钟,且偶发 OAuth 空白页单源失败),现已移除。
# 页面串站状态由整页/帧重载兜底,无需隔离页。
previous_source = site_sources[index - 1] if index > 0 else None
try:
# 返回 True 表示参数页已就绪:后续跳过菜单导航直接填参/导出。
skip_navigation = bool(
_prepare_dsv_batch_export_step(page, entry_url, previous_source, source, index=index)
)
except Exception as exc:
# 会话复用的安全网:登录/会话类偶发异常(SSO/OAuth 链、
# “密码升级”弹窗遮挡、字段未渲染)时,新开干净页面重试一次完整登录;
# 凭据校验类(invalid/verification)不重试,直接失败。
message = str(exc).lower()
login_related = any(token in message for token in ("login", "session", "oauth"))
credential_mismatch = any(token in message for token in ("invalid", "verification"))
if not login_related or credential_mismatch:
raise
print(
f"[inventory-batch] dsv360 session prepare failed for {code}, retry with clean page: {exc}",
file=sys.stderr,
)
page = _open_clean_batch_page(context, page)
_prepare_dsv_batch_export_step(page, entry_url, None, source, index=0)
skip_navigation = bool(
_prepare_dsv_batch_export_step(page, entry_url, None, source, index=0)
)
elif index == 0:
_ensure_crane_session(page, entry_url)
else:
_reset_crane_export_entry(page, entry_url)
download = export_fn(page, body, source, skip_navigation=skip_navigation) if site == "dsv360" else export_fn(page, body, source)
out_file = _save_batch_download(download, drop_dir, run_no, source)
results.append({"source_code": code, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or source.get("task_no") or None, "validation_run_no": source.get("validation_run_no"), **{k: source.get(k) for k in ("attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")}})
record_result({"source_code": code, "warehouse_id": wh, "status": "success", "success": True, "file_path": str(out_file), "task_no": task_no or source.get("task_no") or None, "validation_run_no": source.get("validation_run_no"), **{k: source.get(k) for k in ("attempt_no", "source_run_no", "lease_token", "expected_warehouse_id")}})
print(f"[inventory-batch] {site} export done {code}/{wh} -> {out_file.name}")
except NoInventoryDataError as exc:
results.append({"source_code": code, "warehouse_id": wh, "status": "skipped", "success": False, "skipped": True, "skip_reason": "no_inventory_data", "message": str(exc), "validation_run_no": source.get("validation_run_no")})
record_result({"source_code": code, "warehouse_id": wh, "status": "skipped", "success": False, "skipped": True, "skip_reason": "no_inventory_data", "message": str(exc), "validation_run_no": source.get("validation_run_no")})
print(f"[inventory-batch] {site} export skipped {code}/{wh}: {exc}")
except Exception as exc:
results.append({"source_code": code, "warehouse_id": wh, "status": "failed", "success": False, "error_code": "rpa_export_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
record_result({"source_code": code, "warehouse_id": wh, "status": "failed", "success": False, "error_code": "rpa_export_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
print(f"[inventory-batch] {site} export failed {code}/{wh}: {exc}", file=sys.stderr)
except Exception as exc:
for source in site_sources:
results.append({"source_code": source.get("source_code"), "warehouse_id": source.get("warehouse_id"), "status": "failed", "success": False, "error_code": "rpa_profile_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
record_result({"source_code": source.get("source_code"), "warehouse_id": source.get("warehouse_id"), "status": "failed", "success": False, "error_code": "rpa_profile_failed", "error_message": str(exc), "validation_run_no": source.get("validation_run_no")})
finally:
_close_batch_browser_resources(context, playwright, runtime_profile_dir)
@@ -1622,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
@@ -1727,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>'}",
})
@@ -1758,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()
@@ -1774,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"),
@@ -1786,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],
})
@@ -1837,20 +2016,22 @@ def main() -> None:
print(f" drop={drop_dir}")
print(f" queue={upload_queue_dir}")
last_heartbeat_mono = 0.0
last_heartbeat_mono = freight_rpa_heartbeat.maybe_send_heartbeat(
# 启动时立即上报一次,让管理端第一时间看到 Worker 上线。
freight_rpa_heartbeat.maybe_send_heartbeat(
trigger_dir=inv_trigger_dir,
drop_dir=drop_dir,
last_sent_mono=last_heartbeat_mono,
last_sent_mono=0.0,
force=True,
)
# 心跳节奏交由独立守护线程承担:批量站点导出会长时间阻塞主循环,
# 若由主循环发送心跳,执行期间会停发并被后端按 TTL 误判离线。
freight_rpa_heartbeat.start_heartbeat_loop(
trigger_dir=inv_trigger_dir,
drop_dir=drop_dir,
interval_seconds=heartbeat_seconds,
)
while True:
last_heartbeat_mono = freight_rpa_heartbeat.maybe_send_heartbeat(
trigger_dir=inv_trigger_dir,
drop_dir=drop_dir,
last_sent_mono=last_heartbeat_mono,
)
_scan_triggers(inv_trigger_dir, _handle_inventory_trigger, (drop_dir, inv_processed))
_scan_triggers(upload_trigger_dir, _handle_upload_trigger, (upload_processed,))
time.sleep(poll)
@@ -0,0 +1,181 @@
<#
.SYNOPSIS
Register the test/prod RPA Worker scheduled tasks in FULL-BACKGROUND mode.
.DESCRIPTION
Runs the Worker as a background scheduled task with NO visible console and NO
visible Edge (the Worker launches Playwright headless via -Headless). Deliberately
ASCII-only so it parses identically under any Windows console code page.
Differences vs the standard "visible" scheduled task (README step 11 / 2.3):
- powershell.exe gets -WindowStyle Hidden -> no console window to close by accident.
- start_rpa_worker.ps1 gets -Headless -> no visible Edge / no interactive desktop.
Shape constraints (same as README 2.3):
- Keep AtLogOn + Interactive (auto-start after the RPA account logs on to Windows).
- Do NOT switch to SYSTEM / AtStartup / Session 0 service: the Secret file is
per-user DPAPI (Export-Clixml in new_rpa_worker_secret.ps1) and cannot be
decrypted in a non-interactive context.
- The RPA account should be configured for auto-logon and must not be locked
/ logged-off, otherwise the AtLogOn task does not stay resident.
- Before trusting headless, run the headless smoke preflight (README 2.3.1):
set $env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS="true" then run
dsv_login_smoke.py / crane_login_smoke.py.
Scope:
All actions can target one environment or both via -Scope test|prod|all (default all).
Usage (run in the RPA account's PowerShell):
.\scripts\rpa\register_rpa_background_tasks.ps1 # register test+prod
.\scripts\rpa\register_rpa_background_tasks.ps1 -Scope test # register only test
.\scripts\rpa\register_rpa_background_tasks.ps1 -Start # start both now
.\scripts\rpa\register_rpa_background_tasks.ps1 -Start -Scope prod # start only prod
.\scripts\rpa\register_rpa_background_tasks.ps1 -Status -Scope test # only test
.\scripts\rpa\register_rpa_background_tasks.ps1 -Stop -Scope prod # stop only prod
.\scripts\rpa\register_rpa_background_tasks.ps1 -Unregister # unregister both
#>
[CmdletBinding()]
param(
[switch]$Register,
[switch]$Start,
[switch]$Stop,
[switch]$Status,
[switch]$Unregister,
[ValidateSet("test", "prod", "all")]
[string]$Scope = "all",
[string]$TestApiBase = "http://192.168.100.192:8890",
[string]$ProdApiBase = "http://192.168.100.230:8890",
[string]$TestRoot = "C:\HxopsRpaTest",
[string]$ProdRoot = "C:\HxopsRpaProd",
[string]$SecretFile = "C:\HxopsRpaSecrets"
)
$ErrorActionPreference = "Stop"
$TestTask = "HXOPS Inventory RPA Worker TEST"
$ProdTask = "HXOPS Inventory RPA Worker PROD"
$RunAsUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
function Get-TasksForScope {
# Return the task name(s) selected by -Scope.
param([string]$Scope)
switch ($Scope) {
"test" { return @($TestTask) }
"prod" { return @($ProdTask) }
default { return @($TestTask, $ProdTask) }
}
}
function Assert-Launcher {
# Validate the launcher and DPAPI Secret file required for one environment.
param([string]$Root, [string]$Environment)
$launcher = Join-Path $Root "scripts\rpa\start_rpa_worker.ps1"
if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
throw "Launcher not found: $launcher"
}
$secret = Join-Path $SecretFile ("{0}.xml" -f $Environment)
if (-not (Test-Path -LiteralPath $secret -PathType Leaf)) {
throw "Secret file not found: $secret. Run new_rpa_worker_secret.ps1 first."
}
}
function New-TaskDefinition {
param(
[string]$TaskName,
[string]$Root,
[string]$ApiBase,
[string]$EnvName
)
$launcher = Join-Path $Root "scripts\rpa\start_rpa_worker.ps1"
$secret = Join-Path $SecretFile ("{0}.xml" -f $EnvName)
# Key differences vs the visible scheduled task:
# -WindowStyle Hidden (no console) + -Headless (no visible browser).
$actionArgs = "-NoProfile -ExecutionPolicy Bypass -WindowStyle Hidden -File `"$launcher`" -Environment $EnvName -Headless -ApiBase `"$ApiBase`" -WorkerRoot `"$Root`" -SecretFile `"$secret`""
$action = New-ScheduledTaskAction `
-Execute "powershell.exe" `
-Argument $actionArgs `
-WorkingDirectory $Root
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $RunAsUser
$principal = New-ScheduledTaskPrincipal `
-UserId $RunAsUser `
-LogonType Interactive `
-RunLevel Limited
$settings = New-ScheduledTaskSettingsSet `
-StartWhenAvailable `
-RestartCount 10 `
-RestartInterval (New-TimeSpan -Minutes 1) `
-ExecutionTimeLimit ([TimeSpan]::Zero) `
-MultipleInstances IgnoreNew
Register-ScheduledTask `
-TaskName $TaskName `
-Action $action `
-Trigger $trigger `
-Principal $principal `
-Settings $settings `
-Description "HXOPS RPA Worker ($EnvName) background (headless + hidden console)"
}
# Default action is Register when no switch is given.
if ($Start -or $Stop -or $Status -or $Unregister -or $Register) {
# handled below
} else {
$Register = $true
}
if ($Unregister) {
foreach ($t in (Get-TasksForScope $Scope)) {
Stop-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
Unregister-ScheduledTask -TaskName $t -Confirm:$false -ErrorAction SilentlyContinue
Write-Host "Unregistered task: $t"
}
exit 0
}
if ($Start) {
foreach ($t in (Get-TasksForScope $Scope)) {
Start-ScheduledTask -TaskName $t
Write-Host "Started task: $t"
}
exit 0
}
if ($Stop) {
foreach ($t in (Get-TasksForScope $Scope)) {
Stop-ScheduledTask -TaskName $t
Write-Host "Stopped task: $t"
}
exit 0
}
if ($Status) {
foreach ($t in (Get-TasksForScope $Scope)) {
$tobj = Get-ScheduledTask -TaskName $t -ErrorAction SilentlyContinue
if ($tobj) {
$info = Get-ScheduledTaskInfo -TaskName $t
Write-Host ("{0} State={1} LastRun={2} LastResult={3}" -f $t, $info.State, $info.LastRunTime, $info.LastTaskResult)
Write-Host " (267009 / 0x41301 = running, not an error)"
} else {
Write-Host "Task not registered yet: $t"
}
}
exit 0
}
if ($Register) {
if ($Scope -eq "test" -or $Scope -eq "all") {
Assert-Launcher $TestRoot "test"
New-TaskDefinition -TaskName $TestTask -Root $TestRoot -ApiBase $TestApiBase -EnvName "test"
}
if ($Scope -eq "prod" -or $Scope -eq "all") {
Assert-Launcher $ProdRoot "prod"
New-TaskDefinition -TaskName $ProdTask -Root $ProdRoot -ApiBase $ProdApiBase -EnvName "prod"
}
Write-Host "Registered background task(s) for scope=${Scope}:"
foreach ($t in (Get-TasksForScope $Scope)) { Write-Host " $t" }
Write-Host "Tasks are AtLogOn + Interactive + headless + hidden console."
Write-Host "Use -Start to launch now. Configure auto-logon for the RPA account."
exit 0
}
+9 -1
View File
@@ -94,8 +94,16 @@ $jobs += Start-Job -Name "hxops-shipping-worker" -ScriptBlock {
Set-Location $dir
& $python .\worker_shipping.py 2>&1
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL, $ShippingConcurrency)
# 排程 worker:消费 schedule 队列并执行到期 ScheduleTask(入口为 backend/workers/worker_scheduler.py,与 start_local.ps1 的 schedule-worker 对齐)
$jobs += Start-Job -Name "hxops-schedule-worker" -ScriptBlock {
param($dir, $python, $db)
if ($db) { $env:DATABASE_URL = $db }
$env:ENV_NAME = "dev"
Set-Location $dir
& $python .\workers\worker_scheduler.py 2>&1
} -ArgumentList @($backendDir, $venvPython, $env:DATABASE_URL)
Write-Host "[startup] backend, frontend, kb-worker and shipping-worker are running in this IDE terminal." -ForegroundColor Green
Write-Host "[startup] backend, frontend, kb-worker, shipping-worker and schedule-worker are running in this IDE terminal." -ForegroundColor Green
Write-Host "[startup] Press Ctrl+C to stop all services." -ForegroundColor DarkGray
try {