feat(shipping-notice): 添加 RPA 工作者心跳告警开关,更新环境配置以支持样本证据历史记录

This commit is contained in:
hugo committed 2026-07-19 23:15:25 +08:00
1 parent 705971ad03
commit 88408490d7
34 files changed
+1697 -109

No files matched your search

+2
View File
@@ -109,6 +109,8 @@ FREIGHT_SHIPMENT_TEMPLATE_PATH=templates/freight_shipment_upload.xlsx
# FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"} # FREIGHT_INVENTORY_COLUMN_MAP={"AWS Sku":"sku","COM ID":"reservation_id","Qty Available":"available_qty"}
# 本地 RPA(scripts/rpa/freight_rpa_worker.py) # 本地 RPA(scripts/rpa/freight_rpa_worker.py)
SHIPPING_NOTICE_RPA_WORKER_MOCK=false SHIPPING_NOTICE_RPA_WORKER_MOCK=false
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3 # SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS=3
# SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY= # SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY=
# --- 10. 运维、告警与维护工具 --- # --- 10. 运维、告警与维护工具 ---
+2
View File
@@ -82,6 +82,8 @@ SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data
SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微 # 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
+2
View File
@@ -158,6 +158,8 @@ SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns=
SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300 SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300
# Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs. # Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs.
SHIPPING_NOTICE_RPA_WORKER_MOCK=false SHIPPING_NOTICE_RPA_WORKER_MOCK=false
# 企微心跳告警总开关(默认关闭;需要时在环境文件改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# 固资履历共享盘 # 固资履历共享盘
FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历 FIXED_ASSET_HISTORY_SHARE_ROOT=\\192.168.100.130\设备履历记录\履历
FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001 FIXED_ASSET_HISTORY_SHARE_USERNAME=SBLL00001
+2
View File
@@ -109,6 +109,8 @@ SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900
SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3 SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3
SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
# 企微心跳告警总开关(默认关闭;需要时改为 true)
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微 # 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微
# 两者皆无则告警只写日志、不会发企微 # 两者皆无则告警只写日志、不会发企微
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003
@@ -187,6 +187,15 @@ def start_shipping_inventory_configuration_test(source_id: int):
return _ok(inventory_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202) return _ok(inventory_configuration_test.start_test_export(source_id, actor_id=_actor_id()), status=202)
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/latest', methods=['GET'])
@require_admin
def get_latest_shipping_inventory_configuration_test(source_id: int):
"""读取当前库存站点配置对应的最近测试,使管理端可恢复异步执行状态。"""
from app.services.shipping_notice import inventory_configuration_test
return _ok(inventory_configuration_test.get_latest_test_run(source_id))
@admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>', methods=['GET']) @admin_bp.route('/shipping-notice/sources/<int:source_id>/test-export/<string:run_no>', methods=['GET'])
@require_admin @require_admin
def get_shipping_inventory_configuration_test(source_id: int, run_no: str): def get_shipping_inventory_configuration_test(source_id: int, run_no: str):
@@ -350,6 +359,15 @@ def update_shipping_inventory_parsing_profile(profile_id: int):
)) ))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/sample-replacement-preview/<int:analysis_id>', methods=['POST'])
@require_admin
def preview_shipping_inventory_sample_replacement(profile_id: int, analysis_id: int):
"""比较库存映射草稿当前样本与候选样本,替换前必须由管理员确认差异。"""
return _ok(inventory_structure_analysis.preview_profile_sample_replacement(
profile_id, analysis_id, request.get_json(silent=True) or {},
))
@admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/publish', methods=['POST']) @admin_bp.route('/shipping-notice/parsing-profiles/<int:profile_id>/publish', methods=['POST'])
@require_admin @require_admin
def publish_shipping_inventory_parsing_profile(profile_id: int): def publish_shipping_inventory_parsing_profile(profile_id: int):
+1 -1
View File
@@ -266,7 +266,7 @@ class Config:
or '.hxops_rpa_shared_mount' or '.hxops_rpa_shared_mount'
) )
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = ( SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED = (
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'true').lower() == 'true' os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED', 'false').lower() == 'true'
) )
SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int( SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS = int(
os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800' os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800'
@@ -126,7 +126,7 @@ class ShippingInventorySource(Base):
class ShippingInventoryParsingProfile(Base): class ShippingInventoryParsingProfile(Base):
"""可跨库存源复用的库存文件结构与订单匹配配置。""" """可跨库存源复用的库存文件结构、样本证据与订单匹配配置。"""
__tablename__ = 'shipping_inventory_parsing_profiles' __tablename__ = 'shipping_inventory_parsing_profiles'
__table_args__ = ( __table_args__ = (
@@ -147,16 +147,27 @@ class ShippingInventoryParsingProfile(Base):
exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) fingerprint_version: Mapped[Optional[str]] = mapped_column(String(32), nullable=True)
# Draft and published definitions keep their analysed sample evidence without retaining the full uploaded workbook.
sample_analysis_id: Mapped[Optional[int]] = mapped_column(
ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True, index=True,
)
# Preserve every confirmed evidence switch so a draft remains explainable after samples change.
sample_evidence_history_json: Mapped[list[dict[str, Any]]] = mapped_column(
JSON, nullable=False, default=list, server_default=text("'[]'"),
)
created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False)
published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile') sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile')
sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship(
foreign_keys=[sample_analysis_id],
)
class ShippingInventoryStructureAnalysis(Base): class ShippingInventoryStructureAnalysis(Base):
"""库存文件结构分析记录;保存受控样例与建议,不承载正式库存快照。""" """库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。"""
__tablename__ = 'shipping_inventory_structure_analyses' __tablename__ = 'shipping_inventory_structure_analyses'
__table_args__ = ( __table_args__ = (
@@ -169,13 +180,15 @@ class ShippingInventoryStructureAnalysis(Base):
id: Mapped[int] = mapped_column(primary_key=True) id: Mapped[int] = mapped_column(primary_key=True)
source_kind: Mapped[str] = mapped_column(String(32), nullable=False, default='sample_upload', server_default='sample_upload') source_kind: Mapped[str] = mapped_column(String(32), nullable=False, default='sample_upload', server_default='sample_upload')
source_file_name: Mapped[str] = mapped_column(String(255), nullable=False) source_file_name: Mapped[str] = mapped_column(String(255), nullable=False)
storage_path: Mapped[str] = mapped_column(String(500), nullable=False) # Only temporary conversation sessions retain a short-lived source file for confirmation.
storage_path: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
file_checksum: Mapped[str] = mapped_column(String(64), nullable=False) file_checksum: Mapped[str] = mapped_column(String(64), nullable=False)
file_format: Mapped[str] = mapped_column(String(16), nullable=False) file_format: Mapped[str] = mapped_column(String(16), nullable=False)
analysis_status: Mapped[str] = mapped_column(String(32), nullable=False, default='ready', server_default='ready') analysis_status: Mapped[str] = mapped_column(String(32), nullable=False, default='ready', server_default='ready')
structure_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) structure_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
suggested_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) suggested_mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
validation_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) validation_summary_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict)
sample_rows_json: Mapped[list[list[Any]]] = mapped_column(JSON, nullable=False, default=list)
warning_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list) warning_json: Mapped[list[str]] = mapped_column(JSON, nullable=False, default=list)
exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) exact_structure_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) compatibility_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)
@@ -185,7 +198,7 @@ class ShippingInventoryStructureAnalysis(Base):
class ShippingInventoryConfigurationTestRun(Base): class ShippingInventoryConfigurationTestRun(Base):
"""库存站点配置测试的异步 RPA 运行;测试文件不能进入生产库存池。""" """库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。"""
__tablename__ = 'shipping_inventory_configuration_test_runs' __tablename__ = 'shipping_inventory_configuration_test_runs'
__table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),) __table_args__ = (UniqueConstraint('run_no', name='uq_inventory_configuration_test_runs_run_no'),)
@@ -194,6 +207,7 @@ class ShippingInventoryConfigurationTestRun(Base):
run_no: Mapped[str] = mapped_column(String(64), nullable=False) run_no: Mapped[str] = mapped_column(String(64), nullable=False)
inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True) inventory_source_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_sources.id'), nullable=False, index=True)
source_config_version: Mapped[int] = mapped_column(Integer, nullable=False) source_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
rpa_profile_config_version: Mapped[int] = mapped_column(Integer, nullable=False)
status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa') status: Mapped[str] = mapped_column(String(32), nullable=False, default='awaiting_rpa', server_default='awaiting_rpa')
stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker') stage: Mapped[str] = mapped_column(String(32), nullable=False, default='waiting_worker', server_default='waiting_worker')
analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True) analysis_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_structure_analyses.id'), nullable=True)
@@ -406,7 +406,12 @@ def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str
source_config_version=source.config_version, source_config_version=source.config_version,
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
result = confirmed_test.result_json if confirmed_test and isinstance(confirmed_test.result_json, dict) else {} result = confirmed_test.result_json if confirmed_test and isinstance(confirmed_test.result_json, dict) else {}
if not confirmed_test or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0): if (
not confirmed_test
or source.rpa_profile is None
or confirmed_test.rpa_profile_config_version != source.rpa_profile.config_version
or int(result.get('confirmed_profile_id') or 0) != int(source.parsing_profile_id or 0)
):
return ['configuration_test'], details return ['configuration_test'], details
analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id) analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id)
profile = source.parsing_profile profile = source.parsing_profile
@@ -503,29 +508,118 @@ def _template_validation_missing(source: ShippingInventorySource) -> list[str]:
return ['template_validation'] if not mappings or invalid else [] return ['template_validation'] if not mappings or invalid else []
def _activation_missing_requirements(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]: def _latest_test_run_evidence(source: ShippingInventorySource) -> dict[str, Any]:
"""计算库存站点进入正式运行前尚未完成的业务步骤和测试验证详情。""" """提取最近一次配置测试的非敏感证据,供上线检查说明测试是否过期或失败。"""
missing: list[str] = [] run = ShippingInventoryConfigurationTestRun.query.filter_by(
if source.rpa_profile is None or not source.rpa_profile.enabled: inventory_source_id=source.id,
missing.append('rpa_profile') ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
if source.parsing_profile is None or source.parsing_profile.status != 'published': if run is None:
missing.append('parsing_profile') return {'state': 'not_started'}
if source.excel_template is None or source.excel_template.status != 'published': profile_version = source.rpa_profile.config_version if source.rpa_profile is not None else None
missing.append('excel_template') if (
else: run.source_config_version != source.config_version
missing.extend(_template_validation_missing(source)) or run.rpa_profile_config_version != profile_version
):
return {
'state': 'stale', 'run_no': run.run_no, 'status': run.status,
'source_config_version': run.source_config_version,
'rpa_profile_config_version': run.rpa_profile_config_version,
}
if run.status == 'failed':
return {'state': 'failed', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
return {'state': 'current', 'run_no': run.run_no, 'status': run.status, 'stage': run.stage}
def _activation_check(
code: str, *, passed: bool, action: str, evidence: dict[str, Any], status: str | None = None,
blocking: bool | None = None,
) -> dict[str, Any]:
"""构造单项上线门禁结果,确保管理端只展示服务端已判定的业务事实。"""
return {
'code': code,
'status': status or ('passed' if passed else 'pending'),
'blocking': not passed if blocking is None else blocking,
'action': action,
'evidence': evidence,
}
def _source_activation_checks(source: ShippingInventorySource) -> list[dict[str, Any]]:
"""构建库存站点正式运行的权威检查清单。
检查项按管理员完成配置的业务顺序返回。测试、解析、模板和仓库映射均以当前
``config_version`` 的持久化事实为准,避免管理端依据本地表单状态猜测启用资格。
"""
validation_missing, validation_details = _test_analysis_validation(source) validation_missing, validation_details = _test_analysis_validation(source)
missing.extend(validation_missing) missing = set(validation_missing)
return missing, validation_details test_evidence = _latest_test_run_evidence(source)
test_complete = 'configuration_test' not in missing
profile_ready = source.rpa_profile is not None and bool(source.rpa_profile.enabled)
parsing_ready = source.parsing_profile is not None and source.parsing_profile.status == 'published'
template_ready = source.excel_template is not None and source.excel_template.status == 'published'
template_valid = template_ready and 'template_validation' not in missing
checks = [
_activation_check(
'rpa_profile', passed=profile_ready, action='configure_connection',
evidence={'profile_id': source.rpa_profile_id, 'enabled': profile_ready},
),
_activation_check(
'parsing_profile', passed=parsing_ready, action='configure_parsing_profile',
evidence={'profile_id': source.parsing_profile_id, 'published': parsing_ready},
),
_activation_check(
'excel_template', passed=template_ready, action='configure_excel_template',
evidence={'template_id': source.excel_template_id, 'published': template_ready},
),
_activation_check(
'template_validation', passed=not template_ready or template_valid,
action='configure_excel_template', evidence={}, blocking=template_ready and not template_valid,
),
_activation_check(
'configuration_test', passed=test_complete,
action='run_configuration_test', evidence=test_evidence,
status=test_evidence['state'] if test_evidence['state'] in {'stale', 'failed'} else None,
),
_activation_check(
'parsing_validation', passed=test_complete and 'parsing_validation' not in missing,
action='run_configuration_test', evidence={'sample_warehouses': validation_details['sample_warehouses']},
status='pending' if not test_complete else None, blocking='parsing_validation' in missing,
),
]
if source.warehouse_resolution_mode == 'inventory_match':
checks.append(_activation_check(
'warehouse_identification', passed=test_complete and 'warehouse_identification' not in missing,
action='configure_parsing_profile', evidence={'sample_warehouses': validation_details['sample_warehouses']},
status='pending' if not test_complete else None, blocking='warehouse_identification' in missing,
))
checks.append(_activation_check(
'warehouse_mapping', passed=test_complete and 'warehouse_mapping' not in missing, action='configure_warehouse_mapping',
evidence={
'mode': source.warehouse_resolution_mode,
'fixed_warehouse_id': source.fixed_warehouse_id,
'sample_warehouses': validation_details['sample_warehouses'],
},
status='pending' if not test_complete else None, blocking='warehouse_mapping' in missing,
))
return checks
def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]: def get_source_activation_status(source: ShippingInventorySource) -> dict[str, Any]:
"""返回库存站点启用检查结果,供管理端展示下一步操作。""" """返回库存站点正式运行的结构化门禁结果。
missing, validation = _activation_missing_requirements(source)
Args:
source: 已持久化的库存站点,关联配置由当前数据库事务提供。
Returns:
dict[str, Any]: ``checks`` 为前端唯一的检查真相;``ready`` 为启用结论;
``missing_requirements`` 是由 checks 派生的紧凑摘要,供现有调用方读取。
"""
checks = _source_activation_checks(source)
missing = [item['code'] for item in checks if item['blocking']]
return { return {
'ready': not missing, 'ready': not missing,
'checks': checks,
'missing_requirements': missing, 'missing_requirements': missing,
'validation': validation,
} }
@@ -543,7 +637,6 @@ def activate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
) )
source.enabled = True source.enabled = True
source.updated_by = actor_id source.updated_by = actor_id
source.config_version += 1
db.session.commit() db.session.commit()
return _source_payload(source) return _source_payload(source)
@@ -555,7 +648,6 @@ def deactivate_source(source_id: int, *, actor_id: int | None) -> dict[str, Any]
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
source.enabled = False source.enabled = False
source.updated_by = actor_id source.updated_by = actor_id
source.config_version += 1
db.session.commit() db.session.commit()
return _source_payload(source) return _source_payload(source)
@@ -8,11 +8,11 @@ services/shipping_notice/inventory_configuration_test.py
from __future__ import annotations from __future__ import annotations
import shutil from datetime import datetime, timedelta
from datetime import datetime
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
from flask import current_app
from app.core.errors import ConflictError, NotFoundError, ValidationError from app.core.errors import ConflictError, NotFoundError, ValidationError
from app.extensions import db from app.extensions import db
from app.models import ( from app.models import (
@@ -26,15 +26,56 @@ def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]:
"""投影测试运行状态,避免暴露 RPA 文件的服务器路径。""" """投影测试运行状态,避免暴露 RPA 文件的服务器路径。"""
return { return {
'id': run.id, 'run_no': run.run_no, 'inventory_source_id': run.inventory_source_id, 'id': run.id, 'run_no': run.run_no, 'inventory_source_id': run.inventory_source_id,
'source_config_version': run.source_config_version, 'status': run.status, 'stage': run.stage, 'source_config_version': run.source_config_version, 'rpa_profile_config_version': run.rpa_profile_config_version,
'status': run.status, 'stage': run.stage,
'analysis_id': run.analysis_id, 'result': run.result_json or {}, 'error_message': run.error_message, 'analysis_id': run.analysis_id, 'result': run.result_json or {}, 'error_message': run.error_message,
'created_at': run.created_at.isoformat() if run.created_at else None, 'created_at': run.created_at.isoformat() if run.created_at else None,
'completed_at': run.completed_at.isoformat() if run.completed_at else None, 'completed_at': run.completed_at.isoformat() if run.completed_at else None,
} }
def _matches_current_configuration(run: ShippingInventoryConfigurationTestRun, source: ShippingInventorySource) -> bool:
"""判断测试运行是否仍对应当前站点与 RPA 连接配置,避免旧任务阻塞新配置测试。"""
return bool(
source.rpa_profile
and run.source_config_version == source.config_version
and run.rpa_profile_config_version == source.rpa_profile.config_version
)
def _expire_timed_out_runs(source: ShippingInventorySource) -> None:
"""将超出库存 RPA 等待窗口的当前测试标记为失败,避免管理端无限轮询。"""
timeout = max(1, int(current_app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS']))
deadline = datetime.utcnow() - timedelta(seconds=timeout)
runs = ShippingInventoryConfigurationTestRun.query.filter(
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
ShippingInventoryConfigurationTestRun.created_at < deadline,
).all()
for run in runs:
run.status = 'failed'
run.stage = 'failed'
run.error_message = '测试导出等待 RPA Worker 超时,请重新测试'
run.completed_at = datetime.utcnow()
def get_latest_test_run(source_id: int) -> dict[str, Any] | None:
"""返回站点当前配置对应的最近测试运行,供管理端刷新或重开抽屉后恢复真实状态。"""
source = db.session.get(ShippingInventorySource, source_id)
if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
_expire_timed_out_runs(source)
db.session.commit()
run = ShippingInventoryConfigurationTestRun.query.filter_by(
inventory_source_id=source.id,
source_config_version=source.config_version,
rpa_profile_config_version=source.rpa_profile.config_version if source.rpa_profile else -1,
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
return _payload(run) if run else None
def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]: def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]:
"""为停用库存站点写入专用测试 trigger;重复点击复用等待中的运行。""" """为停用库存站点写入专用测试 trigger;仅复用同一配置版本仍在运行的任务。"""
source = db.session.get(ShippingInventorySource, source_id) source = db.session.get(ShippingInventorySource, source_id)
if source is None: if source is None:
raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND') raise NotFoundError('Inventory Source not found', code='SHIPPING.INVENTORY_SOURCE_NOT_FOUND')
@@ -42,8 +83,11 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID') raise ConflictError('Disable inventory source before configuration test', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_INVALID')
if source.rpa_profile is None or not source.rpa_profile.enabled: if source.rpa_profile is None or not source.rpa_profile.enabled:
raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED') raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED')
_expire_timed_out_runs(source)
active = ShippingInventoryConfigurationTestRun.query.filter( active = ShippingInventoryConfigurationTestRun.query.filter(
ShippingInventoryConfigurationTestRun.inventory_source_id == source.id, ShippingInventoryConfigurationTestRun.inventory_source_id == source.id,
ShippingInventoryConfigurationTestRun.source_config_version == source.config_version,
ShippingInventoryConfigurationTestRun.rpa_profile_config_version == source.rpa_profile.config_version,
ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']), ShippingInventoryConfigurationTestRun.status.in_(['awaiting_rpa', 'processing']),
).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first()
if active: if active:
@@ -54,6 +98,7 @@ def start_test_export(source_id: int, *, actor_id: int | None) -> dict[str, Any]
run_no = f'CONFIG-{source.source_code}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}' run_no = f'CONFIG-{source.source_code}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}'
run = ShippingInventoryConfigurationTestRun( run = ShippingInventoryConfigurationTestRun(
run_no=run_no, inventory_source_id=source.id, source_config_version=source.config_version, run_no=run_no, inventory_source_id=source.id, source_config_version=source.config_version,
rpa_profile_config_version=source.rpa_profile.config_version,
status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id, status='awaiting_rpa', stage='waiting_worker', result_json={}, created_by=actor_id,
) )
db.session.add(run) db.session.add(run)
@@ -83,6 +128,10 @@ def get_test_run(source_id: int, run_no: str) -> dict[str, Any]:
).first() ).first()
if run is None: if run is None:
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND') raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
source = db.session.get(ShippingInventorySource, source_id)
if source is not None:
_expire_timed_out_runs(source)
db.session.commit()
return _payload(run) return _payload(run)
@@ -92,10 +141,10 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=run_no).first() run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=run_no).first()
if run is None: if run is None:
raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND') raise NotFoundError('Inventory configuration test run not found', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_NOT_FOUND')
if run.status == 'completed': if run.status in {'completed', 'failed'}:
return _payload(run) return _payload(run)
source = db.session.get(ShippingInventorySource, run.inventory_source_id) source = db.session.get(ShippingInventorySource, run.inventory_source_id)
if source is None or source.config_version != run.source_config_version: if source is None or not _matches_current_configuration(run, source):
run.status = 'failed'; run.stage = 'failed'; run.error_message = '库存站点配置已变更,请重新测试'; run.completed_at = datetime.utcnow() run.status = 'failed'; run.stage = 'failed'; run.error_message = '库存站点配置已变更,请重新测试'; run.completed_at = datetime.utcnow()
db.session.commit() db.session.commit()
return _payload(run) return _payload(run)
@@ -109,28 +158,24 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow() run.status = 'failed'; run.stage = 'failed'; run.error_message = '测试导出文件不存在'; run.completed_at = datetime.utcnow()
db.session.commit() db.session.commit()
return _payload(run) return _payload(run)
from app.services.shipping_notice.inventory_structure_analysis import _analyse_path, _analysis_root, serialize_analysis from app.services.shipping_notice.inventory_structure_analysis import _analyse_path, serialize_analysis
from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix from app.services.shipping_notice.inventory_file_store import resolve_inventory_upload_suffix
from app.models import ShippingInventoryStructureAnalysis from app.models import ShippingInventoryStructureAnalysis
import hashlib import hashlib
import uuid
from app.services.shipping_notice.inventory_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition from app.services.shipping_notice.inventory_structure_fingerprint import compatibility_fingerprint, exact_fingerprint, structure_definition
from app.services.shipping_notice.inventory_profile_matching import recommend_profiles from app.services.shipping_notice.inventory_profile_matching import recommend_profiles
run.status = 'processing'; run.stage = 'analysing_structure'; db.session.flush() run.status = 'processing'; run.stage = 'analysing_structure'; db.session.flush()
suffix = resolve_inventory_upload_suffix(path.name) suffix = resolve_inventory_upload_suffix(path.name)
raw = path.read_bytes() raw = path.read_bytes()
target_dir = _analysis_root() / uuid.uuid4().hex
target_dir.mkdir(parents=True, exist_ok=False)
target = target_dir / f'test{suffix}'
try: try:
shutil.copy2(path, target) # The RPA download is only read for analysis; configuration evidence never retains a second full workbook copy.
structure, suggested, summary, warnings = _analyse_path(target, suffix) structure, suggested, summary, warnings = _analyse_path(path, suffix)
definition = structure_definition(file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), header_row_index=structure.get('selected_header_row_index') or 1, headers=structure.get('selected_headers', [])) definition = structure_definition(file_format=suffix.lstrip('.'), sheet_name=structure.get('selected_sheet_name'), header_row_index=structure.get('selected_header_row_index') or 1, headers=structure.get('selected_headers', []))
analysis = ShippingInventoryStructureAnalysis( analysis = ShippingInventoryStructureAnalysis(
source_kind='configuration_test', source_file_name=path.name, storage_path=str(target), file_checksum=hashlib.sha256(raw).hexdigest(), source_kind='configuration_test', source_file_name=path.name, storage_path=None, file_checksum=hashlib.sha256(raw).hexdigest(),
file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested, file_format=suffix.lstrip('.'), analysis_status='ready', structure_json=structure, suggested_mapping_json=suggested,
validation_summary_json=summary, warning_json=warnings, created_by=run.created_by, validation_summary_json=summary, sample_rows_json=list(structure.get('selected_sample_rows') or []), warning_json=warnings, created_by=run.created_by,
exact_structure_fingerprint=exact_fingerprint(definition), compatibility_fingerprint=compatibility_fingerprint(definition=definition, field_mapping=suggested, match_keys=[]), exact_structure_fingerprint=exact_fingerprint(definition), compatibility_fingerprint=compatibility_fingerprint(definition=definition, field_mapping=suggested, match_keys=[]),
) )
db.session.add(analysis); db.session.flush() db.session.add(analysis); db.session.flush()
@@ -138,7 +183,6 @@ def report_test_export(payload: dict[str, Any]) -> dict[str, Any]:
run.analysis_id = analysis.id; run.status = 'completed'; run.stage = 'ready_for_confirmation'; run.result_json = {'analysis': serialize_analysis(analysis)}; run.completed_at = datetime.utcnow() run.analysis_id = analysis.id; run.status = 'completed'; run.stage = 'ready_for_confirmation'; run.result_json = {'analysis': serialize_analysis(analysis)}; run.completed_at = datetime.utcnow()
db.session.commit() db.session.commit()
except Exception: except Exception:
shutil.rmtree(target_dir, ignore_errors=True)
db.session.rollback() db.session.rollback()
raise raise
return _payload(run) return _payload(run)
@@ -153,7 +197,12 @@ def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_
profile = db.session.get(ShippingInventoryParsingProfile, profile_id) profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
if source is None or profile is None or profile.status != 'published': if source is None or profile is None or profile.status != 'published':
raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED') raise ValidationError('Published parsing profile is required', code='SHIPPING.INVENTORY_PARSING_PROFILE_REQUIRED')
if source.enabled or source.config_version != run.source_config_version: if (
source.enabled
or source.config_version != run.source_config_version
or source.rpa_profile is None
or source.rpa_profile.config_version != run.rpa_profile_config_version
):
raise ConflictError('Inventory Source configuration changed', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE') raise ConflictError('Inventory Source configuration changed', code='SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE')
from app.services.shipping_notice.inventory_structure_analysis import adopt_published_profile from app.services.shipping_notice.inventory_structure_analysis import adopt_published_profile
@@ -162,6 +211,7 @@ def confirm_test_profile(source_id: int, run_no: str, profile_id: int, *, actor_
source.updated_by = actor_id source.updated_by = actor_id
source.config_version += 1 source.config_version += 1
run.source_config_version = source.config_version run.source_config_version = source.config_version
run.rpa_profile_config_version = source.rpa_profile.config_version
run.result_json = {**(run.result_json or {}), 'confirmed_profile_id': profile.id, 'confirmed_profile_checksum': profile.checksum} run.result_json = {**(run.result_json or {}), 'confirmed_profile_id': profile.id, 'confirmed_profile_checksum': profile.checksum}
db.session.commit() db.session.commit()
return {'test_run': _payload(run), 'parsing_profile_id': source.parsing_profile_id} return {'test_run': _payload(run), 'parsing_profile_id': source.parsing_profile_id}
@@ -21,6 +21,7 @@ from app.models import (
ShippingInventoryField, ShippingInventoryField,
ShippingInventoryParsingProfile, ShippingInventoryParsingProfile,
ShippingInventorySource, ShippingInventorySource,
ShippingInventoryStructureAnalysis,
ShippingOrderField, ShippingOrderField,
) )
@@ -97,14 +98,75 @@ def _validate_definition(raw: Any) -> dict[str, Any]:
} }
def _require_sample_evidence(
sample_analysis_id: Any,
definition: dict[str, Any],
*,
file_format: str,
) -> ShippingInventoryStructureAnalysis:
"""校验草稿仅能使用已持久化样本证据中的工作表、表头和来源栏位。"""
try:
analysis_id = int(sample_analysis_id)
except (TypeError, ValueError) as exc:
raise ValidationError(
'Parsing profile requires sample analysis evidence',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
) from exc
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
if analysis is None or analysis.analysis_status != 'ready' or analysis.file_format != file_format:
raise ValidationError(
'Parsing profile sample analysis evidence is unavailable',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED',
)
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
candidates = structure.get('candidates') if isinstance(structure.get('candidates'), list) else []
selected = next((candidate for candidate in candidates if isinstance(candidate, dict)
and candidate.get('sheet_name') == definition.get('sheet_name')
and candidate.get('header_row_index') == definition.get('header_row_index')), None)
if not isinstance(selected, dict):
raise ValidationError(
'Parsing profile worksheet or header row is not present in sample evidence',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
)
headers = {str(header).strip() for header in selected.get('headers', []) if str(header).strip()}
if any(str(header or '').strip() not in headers for header in (definition.get('field_mapping') or {}).values()):
raise ValidationError(
'Parsing profile mapping is not present in sample evidence',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
)
duplicates = {
str(column.get('header') or '').strip()
for column in selected.get('columns', []) if isinstance(column, dict) and column.get('duplicate')
}
if any(str(header).strip() in duplicates for header in (definition.get('field_mapping') or {}).values()):
raise ValidationError(
'Parsing profile mapping uses duplicate sample headers',
code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_INVALID',
)
return analysis
def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]: def payload(profile: ShippingInventoryParsingProfile) -> dict[str, Any]:
"""序列化解析 Profile 管理 DTO。""" """序列化解析 Profile 管理 DTO。"""
sample_analysis = profile.sample_analysis
return { return {
'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name,
'version': profile.version, 'status': profile.status, 'file_format': profile.file_format, 'version': profile.version, 'status': profile.status, 'file_format': profile.file_format,
'definition': profile.definition_json or {}, 'checksum': profile.checksum, 'definition': profile.definition_json or {}, 'checksum': profile.checksum,
'published_at': profile.published_at.isoformat() if profile.published_at else None, 'published_at': profile.published_at.isoformat() if profile.published_at else None,
'source_count': len(profile.sources), 'source_count': len(profile.sources),
'sample_analysis_id': profile.sample_analysis_id,
'sample_evidence_history': profile.sample_evidence_history_json or [],
'sample_evidence': {
'id': sample_analysis.id,
'source_file_name': sample_analysis.source_file_name,
'file_checksum': sample_analysis.file_checksum,
'file_format': sample_analysis.file_format,
'structure': sample_analysis.structure_json or {},
'sample_rows': sample_analysis.sample_rows_json or [],
'validation_summary': sample_analysis.validation_summary_json or {},
'created_at': sample_analysis.created_at.isoformat() if sample_analysis.created_at else None,
} if sample_analysis is not None else None,
} }
@@ -116,7 +178,7 @@ def list_profiles() -> list[dict[str, Any]]:
def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]: def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int | None = None) -> dict[str, Any]:
"""创建或更新解析 Profile 草稿;published 版本不可原地修改。""" """创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None
if profile_id and profile is None: if profile_id and profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
@@ -132,13 +194,37 @@ def save_draft(data: dict[str, Any], *, actor_id: int | None, profile_id: int |
profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id) profile = ShippingInventoryParsingProfile(profile_code=code, version=next_version, created_by=actor_id)
db.session.add(profile) db.session.add(profile)
profile.display_name = str(data.get('display_name') or code).strip() profile.display_name = str(data.get('display_name') or code).strip()
profile.file_format = str(data.get('file_format') or 'xlsx').lower() requested_file_format = str(data.get('file_format') or 'xlsx').lower()
if profile.file_format not in {'xls', 'xlsx', 'csv'}: if requested_file_format not in {'xls', 'xlsx', 'csv'}:
raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') raise ValidationError('file_format is invalid', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
if profile_id and requested_file_format != profile.file_format:
raise ValidationError(
'Draft parsing profile file format is immutable',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
profile.file_format = requested_file_format
definition = _validate_definition(data.get('definition')) definition = _validate_definition(data.get('definition'))
if profile.file_format == 'csv' and definition.get('sheet_name'): if profile.file_format == 'csv' and definition.get('sheet_name'):
raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID') raise ValidationError('CSV parsing profile cannot configure sheet_name', code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID')
sample_analysis = _require_sample_evidence(
data.get('sample_analysis_id', profile.sample_analysis_id), definition, file_format=profile.file_format,
)
if profile.sample_analysis_id and profile.sample_analysis_id != sample_analysis.id:
if not bool(data.get('confirm_sample_replacement')):
raise ValidationError(
'Replacing inventory sample evidence requires confirmation',
code='SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED',
)
history = list(profile.sample_evidence_history_json or [])
history.append({
'previous_analysis_id': profile.sample_analysis_id,
'replacement_analysis_id': sample_analysis.id,
'replaced_at': datetime.utcnow().isoformat(),
'replaced_by': actor_id,
})
profile.sample_evidence_history_json = history
profile.definition_json = definition profile.definition_json = definition
profile.sample_analysis = sample_analysis
db.session.commit() db.session.commit()
return payload(profile) return payload(profile)
@@ -150,6 +236,9 @@ def publish(profile_id: int, *, actor_id: int | None) -> dict[str, Any]:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND') raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'draft': if profile.status != 'draft':
raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID') raise ConflictError('Only draft parsing profile can be published', code='SHIPPING.INVENTORY_PARSING_PROFILE_PUBLISH_INVALID')
_require_sample_evidence(
profile.sample_analysis_id, profile.definition_json or {}, file_format=profile.file_format,
)
from app.services.shipping_notice.order_schema import service as order_schema_service from app.services.shipping_notice.order_schema import service as order_schema_service
published_field_ids = { published_field_ids = {
@@ -14,7 +14,7 @@ import re
import shutil import shutil
import uuid import uuid
from collections import Counter from collections import Counter
from datetime import datetime from datetime import date, datetime
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
@@ -31,6 +31,7 @@ from app.services.shipping_notice.inventory_snapshot import find_inventory_heade
from app.services.shipping_notice.inventory_structure_fingerprint import ( from app.services.shipping_notice.inventory_structure_fingerprint import (
compatibility_fingerprint, compatibility_fingerprint,
exact_fingerprint, exact_fingerprint,
normalise_header,
structure_definition, structure_definition,
) )
@@ -92,6 +93,27 @@ def _value_type(values: list[Any]) -> str:
return 'text' return 'text'
def _evidence_value(value: Any) -> Any:
"""将样本单元格转换为可审计但不暴露业务标识的最小化证据值。"""
if value in (None, ''):
return None
if isinstance(value, (int, float, bool)):
return value
if isinstance(value, (date, datetime)):
return value.isoformat()
text = str(value).strip()
if len(text) <= 2:
return '*' * len(text)
if len(text) <= 6:
return f'{text[:1]}***{text[-1:]}'
return f'{text[:2]}***{text[-2:]}'
def _sample_evidence_rows(sample_rows: list[list[Any]]) -> list[list[Any]]:
"""保留最多五行已脱敏样例,供映射审计和页面预览而非库存运行。"""
return [[_evidence_value(value) for value in row] for row in sample_rows[:MAX_SAMPLE_ROWS]]
def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[dict[str, Any]]: def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[dict[str, Any]]:
"""生成来源栏位的业务预览,包括样例、空值率和建议字段。""" """生成来源栏位的业务预览,包括样例、空值率和建议字段。"""
suggestions = suggest_field_mapping(headers, as_catalog=True) suggestions = suggest_field_mapping(headers, as_catalog=True)
@@ -108,7 +130,7 @@ def _column_summary(headers: list[str], sample_rows: list[list[Any]]) -> list[di
columns.append({ columns.append({
'index': index, 'index': index,
'header': header, 'header': header,
'sample_values': [str(value)[:120] for value in non_empty[:MAX_SAMPLE_ROWS]], 'sample_values': [str(_evidence_value(value))[:120] for value in non_empty[:MAX_SAMPLE_ROWS]],
'sample_empty_rate': round((rows_total - len(non_empty)) / rows_total, 4) if rows_total else 1, 'sample_empty_rate': round((rows_total - len(non_empty)) / rows_total, 4) if rows_total else 1,
'inferred_type': _value_type(non_empty), 'inferred_type': _value_type(non_empty),
'duplicate': bool(header and duplicates[header] > 1), 'duplicate': bool(header and duplicates[header] > 1),
@@ -175,6 +197,7 @@ def _build_workbook_structure(
'header_row_index': header_index + 1, 'header_row_index': header_index + 1,
'headers': headers, 'headers': headers,
'columns': _column_summary(headers, samples), 'columns': _column_summary(headers, samples),
'_sample_rows': _sample_evidence_rows(samples),
'sample_row_count': len(samples), 'sample_row_count': len(samples),
'row_count_hint': row_count, 'row_count_hint': row_count,
'score': score, 'score': score,
@@ -184,14 +207,18 @@ def _build_workbook_structure(
candidates.append(candidate) candidates.append(candidate)
if not candidates: if not candidates:
raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID') raise ValidationError('Inventory file has no analysable worksheet', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID')
selected = max(candidates, key=lambda item: (item['score'], item['sample_row_count'])) # Prefer a populated detail sheet over a same-score cover/summary sheet.
selected = max(candidates, key=lambda item: (
item['score'], item['sample_row_count'], sum(1 for header in item['headers'] if header),
))
structure = { structure = {
'sheets': sheets, 'sheets': sheets,
'candidates': candidates, 'candidates': [{key: value for key, value in candidate.items() if key != '_sample_rows'} for candidate in candidates],
'selected_sheet_name': selected['sheet_name'], 'selected_sheet_name': selected['sheet_name'],
'selected_header_row_index': selected['header_row_index'], 'selected_header_row_index': selected['header_row_index'],
'selected_headers': selected['headers'], 'selected_headers': selected['headers'],
'selected_columns': selected['columns'], 'selected_columns': selected['columns'],
'selected_sample_rows': selected['_sample_rows'],
} }
mapping = suggest_field_mapping(selected['headers'], as_catalog=True) mapping = suggest_field_mapping(selected['headers'], as_catalog=True)
summary = { summary = {
@@ -251,7 +278,7 @@ def _csv_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str
return { return {
'sheets': [], 'candidates': [candidate], 'selected_sheet_name': None, 'sheets': [], 'candidates': [candidate], 'selected_sheet_name': None,
'selected_header_row_index': header_index + 1, 'selected_headers': headers, 'selected_header_row_index': header_index + 1, 'selected_headers': headers,
'selected_columns': candidate['columns'], 'selected_columns': candidate['columns'], 'selected_sample_rows': _sample_evidence_rows(samples),
}, mapping, { }, mapping, {
'candidate_count': 1, 'sample_row_count': len(samples), 'candidate_count': 1, 'sample_row_count': len(samples),
'valid_inventory_field_suggestions': len(mapping), 'valid_inventory_field_suggestions': len(mapping),
@@ -282,6 +309,7 @@ def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, An
'structure': item.structure_json or {}, 'structure': item.structure_json or {},
'suggested_mapping': item.suggested_mapping_json or {}, 'suggested_mapping': item.suggested_mapping_json or {},
'validation_summary': item.validation_summary_json or {}, 'validation_summary': item.validation_summary_json or {},
'sample_rows': item.sample_rows_json or [],
'warnings': item.warning_json or [], 'warnings': item.warning_json or [],
'match_result': item.match_result_json or {}, 'match_result': item.match_result_json or {},
'created_at': item.created_at.isoformat() if item.created_at else None, 'created_at': item.created_at.isoformat() if item.created_at else None,
@@ -289,7 +317,7 @@ def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, An
def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> dict[str, Any]: def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) -> dict[str, Any]:
"""上传并分析管理员选择的库存样本文件,创建后端权威分析记录。""" """上传并分析管理员库存样本,只持久化脱敏结构证据且立即清理完整原件。"""
if upload is None or not str(upload.filename or '').strip(): if upload is None or not str(upload.filename or '').strip():
raise ValidationError('Inventory sample file is required', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_REQUIRED') raise ValidationError('Inventory sample file is required', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_FILE_REQUIRED')
suffix = resolve_inventory_upload_suffix(str(upload.filename)) suffix = resolve_inventory_upload_suffix(str(upload.filename))
@@ -316,10 +344,10 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) ->
header_row_index=structure.get('selected_header_row_index') or 1, headers=selected_headers, header_row_index=structure.get('selected_header_row_index') or 1, headers=selected_headers,
) )
item = ShippingInventoryStructureAnalysis( item = ShippingInventoryStructureAnalysis(
source_kind='sample_upload', source_file_name=_safe_filename(str(upload.filename)), storage_path=str(path), source_kind='sample_upload', source_file_name=_safe_filename(str(upload.filename)), storage_path=None,
file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready', file_checksum=hashlib.sha256(raw).hexdigest(), file_format=suffix.lstrip('.'), analysis_status='ready',
structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary, structure_json=structure, suggested_mapping_json=suggested, validation_summary_json=summary,
warning_json=warnings, created_by=actor_id, sample_rows_json=list(structure.get('selected_sample_rows') or []), warning_json=warnings, created_by=actor_id,
exact_structure_fingerprint=exact_fingerprint(selected_definition), exact_structure_fingerprint=exact_fingerprint(selected_definition),
compatibility_fingerprint=compatibility_fingerprint( compatibility_fingerprint=compatibility_fingerprint(
definition=selected_definition, field_mapping=suggested, match_keys=[], definition=selected_definition, field_mapping=suggested, match_keys=[],
@@ -335,8 +363,12 @@ def create_sample_upload(upload: FileStorage | None, *, actor_id: int | None) ->
'exact_structure_fingerprint': item.exact_structure_fingerprint, 'exact_structure_fingerprint': item.exact_structure_fingerprint,
'compatibility_fingerprint': item.compatibility_fingerprint, 'compatibility_fingerprint': item.compatibility_fingerprint,
}) })
db.session.commit() try:
return serialize_analysis(item) db.session.commit()
return serialize_analysis(item)
finally:
# The sample workbook is only a parsing input. Long-term audit relies on minimised structure evidence.
shutil.rmtree(analysis_dir, ignore_errors=True)
def get_analysis(analysis_id: int) -> dict[str, Any]: def get_analysis(analysis_id: int) -> dict[str, Any]:
@@ -347,11 +379,55 @@ def get_analysis(analysis_id: int) -> dict[str, Any]:
return serialize_analysis(item) return serialize_analysis(item)
def preview_profile_sample_replacement(profile_id: int, analysis_id: int, data: dict[str, Any] | None = None) -> dict[str, Any]:
"""比较草稿当前样本和候选样本,明确列出需要管理员确认的结构变化。"""
profile = db.session.get(ShippingInventoryParsingProfile, profile_id)
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
if profile is None:
raise NotFoundError('Parsing profile not found', code='SHIPPING.INVENTORY_PARSING_PROFILE_NOT_FOUND')
if profile.status != 'draft':
raise ValidationError('Only draft parsing profile can replace sample evidence', code='SHIPPING.INVENTORY_PARSING_PROFILE_IMMUTABLE')
if analysis is None or analysis.analysis_status != 'ready':
raise ValidationError('Inventory sample analysis evidence is unavailable', code='SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED')
previous = profile.sample_analysis
old_headers = list((previous.structure_json or {}).get('selected_headers') or []) if previous else []
new_headers = list((analysis.structure_json or {}).get('selected_headers') or [])
old_normalised = {normalise_header(value): str(value) for value in old_headers if normalise_header(value)}
new_normalised = {normalise_header(value): str(value) for value in new_headers if normalise_header(value)}
definition = profile.definition_json if isinstance(profile.definition_json, dict) else {}
proposed = data if isinstance(data, dict) else {}
mapping = proposed.get('field_mapping') if isinstance(proposed.get('field_mapping'), dict) else definition.get('field_mapping')
mapping = mapping if isinstance(mapping, dict) else {}
missing_mapped_headers = [
str(header) for header in mapping.values()
if normalise_header(header) not in new_normalised
]
return {
'profile_id': profile.id,
'previous_analysis_id': profile.sample_analysis_id,
'replacement_analysis_id': analysis.id,
'difference': {
'added_columns': [new_normalised[key] for key in new_normalised if key not in old_normalised],
'missing_columns': [old_normalised[key] for key in old_normalised if key not in new_normalised],
'column_order_changed': old_normalised.keys() == new_normalised.keys() and old_headers != new_headers,
'missing_mapped_headers': missing_mapped_headers,
'file_format_changed': profile.file_format != analysis.file_format,
},
'can_confirm': not missing_mapped_headers and profile.file_format == analysis.file_format,
}
def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]: def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: int | None) -> dict[str, Any]:
"""用已分析的真实栏位创建库存文件解析方案草稿,禁止前端编造来源栏位。""" """用已分析样本证据创建或更新草稿,禁止前端编造来源栏位或脱离样本保存。"""
analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id)
if analysis is None: if analysis is None:
raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND') raise NotFoundError('Inventory structure analysis not found', code='SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_NOT_FOUND')
existing_profile = db.session.get(ShippingInventoryParsingProfile, data.get('profile_id')) if data.get('profile_id') else None
if existing_profile is not None and existing_profile.file_format != analysis.file_format:
raise ValidationError(
'Draft parsing profile file format is immutable',
code='SHIPPING.INVENTORY_PARSING_PROFILE_INVALID',
)
structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {} structure = analysis.structure_json if isinstance(analysis.structure_json, dict) else {}
sheet_name = str(data.get('sheet_name') or structure.get('selected_sheet_name') or '').strip() or None sheet_name = str(data.get('sheet_name') or structure.get('selected_sheet_name') or '').strip() or None
header_row_index = data.get('header_row_index') or structure.get('selected_header_row_index') header_row_index = data.get('header_row_index') or structure.get('selected_header_row_index')
@@ -378,6 +454,8 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in
'profile_code': data.get('profile_code'), 'profile_code': data.get('profile_code'),
'display_name': data.get('display_name'), 'display_name': data.get('display_name'),
'file_format': analysis.file_format, 'file_format': analysis.file_format,
'sample_analysis_id': analysis.id,
'confirm_sample_replacement': bool(data.get('confirm_sample_replacement')),
'definition': { 'definition': {
'sheet_name': sheet_name, 'sheet_name': sheet_name,
'header_row_index': header_row_index, 'header_row_index': header_row_index,
@@ -3,7 +3,7 @@ services/shipping_notice/rpa_worker_heartbeat_alert.py
用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。 用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。
依赖:rpa_worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。 依赖:rpa_worker_heartbeat、redis_client、wecom_notify、models.User、models.AppSetting。
逻辑:由 schedule worker 每轮循环调用;DB 为告警状态权威源,Redis 仅作缓存同步。 逻辑:由 schedule worker 每轮循环调用;默认 ALERT_ENABLED=false 不发送;DB 为告警状态权威源,Redis 仅作缓存同步。
""" """
from __future__ import annotations from __future__ import annotations
@@ -46,7 +46,7 @@ def _config_bool(key: str, default: bool) -> bool:
def _alert_enabled() -> bool: def _alert_enabled() -> bool:
if not _heartbeat_check_required(): if not _heartbeat_check_required():
return False return False
return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED", True) return _config_bool("SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED", False)
def _alert_cooldown_seconds() -> int: def _alert_cooldown_seconds() -> int:
@@ -0,0 +1,23 @@
"""记录库存映射草稿的样本替换审计。"""
from alembic import op
import sqlalchemy as sa
revision = 'a4c7e9f1b2d3'
down_revision = 'fd2e3f4a5b6c'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""保留样本证据的替换链,避免草稿更新后丢失配置依据。"""
op.add_column(
'shipping_inventory_parsing_profiles',
sa.Column('sample_evidence_history_json', sa.JSON(), server_default=sa.text("'[]'"), nullable=False),
)
def downgrade() -> None:
"""移除样本替换历史字段。"""
op.drop_column('shipping_inventory_parsing_profiles', 'sample_evidence_history_json')
@@ -0,0 +1,35 @@
"""将库存映射样本改为最小化结构证据。"""
from alembic import op
import sqlalchemy as sa
revision = 'fc1d2e3f4a5b'
down_revision = 'fb1c2d3e4f5a'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""保存脱敏样例和 Profile 样本引用,不再要求分析记录持有完整 Excel 路径。"""
with op.batch_alter_table('shipping_inventory_structure_analyses') as batch:
batch.alter_column('storage_path', existing_type=sa.String(length=500), nullable=True)
batch.add_column(sa.Column('sample_rows_json', sa.JSON(), server_default=sa.text("'[]'"), nullable=False))
with op.batch_alter_table('shipping_inventory_parsing_profiles') as batch:
batch.add_column(sa.Column('sample_analysis_id', sa.Integer(), nullable=True))
batch.create_index('ix_shipping_inventory_parsing_profiles_sample_analysis_id', ['sample_analysis_id'])
batch.create_foreign_key(
'fk_inventory_parsing_profiles_sample_analysis',
'shipping_inventory_structure_analyses', ['sample_analysis_id'], ['id'],
)
def downgrade() -> None:
"""移除样本证据引用;旧版重新要求结构分析记录保存来源路径。"""
with op.batch_alter_table('shipping_inventory_parsing_profiles') as batch:
batch.drop_constraint('fk_inventory_parsing_profiles_sample_analysis', type_='foreignkey')
batch.drop_index('ix_shipping_inventory_parsing_profiles_sample_analysis_id')
batch.drop_column('sample_analysis_id')
with op.batch_alter_table('shipping_inventory_structure_analyses') as batch:
batch.drop_column('sample_rows_json')
batch.alter_column('storage_path', existing_type=sa.String(length=500), nullable=False)
@@ -0,0 +1,24 @@
"""锁定库存站点测试使用的 RPA Profile 配置版本。"""
from alembic import op
import sqlalchemy as sa
revision = 'fd2e3f4a5b6c'
down_revision = 'fc1d2e3f4a5b'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""为既有测试运行补充连接版本快照,使凭据或登录配置变更能够使测试失效。"""
with op.batch_alter_table('shipping_inventory_configuration_test_runs') as batch:
batch.add_column(sa.Column(
'rpa_profile_config_version', sa.Integer(), nullable=False, server_default=sa.text('1'),
))
def downgrade() -> None:
"""移除 RPA Profile 配置版本快照。"""
with op.batch_alter_table('shipping_inventory_configuration_test_runs') as batch:
batch.drop_column('rpa_profile_config_version')
@@ -16,7 +16,7 @@ from app.services.admin import shipping_inventory_service
from app.services.shipping_notice import inventory_parsing_profile from app.services.shipping_notice import inventory_parsing_profile
from app.services.shipping_notice.order_schema import service as order_schema_service from app.services.shipping_notice.order_schema import service as order_schema_service
from app import db from app import db
from app.models import ShippingExcelTemplate, ShippingInventoryField from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryStructureAnalysis
def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict: def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict:
@@ -27,6 +27,26 @@ def _profile_data(*, code: str = 'DBS_EU', connector_type: str = 'dbs') -> dict:
} }
def _sample_evidence() -> int:
"""创建最小表头证据,确保库存源服务测试不绕过解析方案样本门禁。"""
item = ShippingInventoryStructureAnalysis(
source_kind='sample_upload', source_file_name='service-sample.xlsx', storage_path=None,
file_checksum='b' * 64, file_format='xlsx', analysis_status='ready',
structure_json={'candidates': [{
'sheet_name': None, 'header_row_index': 1,
'headers': ['Supplier Sku', 'Reservation ID', 'Qty Available'],
'columns': [
{'header': 'Supplier Sku', 'duplicate': False},
{'header': 'Reservation ID', 'duplicate': False},
{'header': 'Qty Available', 'duplicate': False},
],
}]}, suggested_mapping_json={}, validation_summary_json={}, sample_rows_json=[], warning_json=[],
)
db.session.add(item)
db.session.flush()
return item.id
def _parsing_profile() -> dict: def _parsing_profile() -> dict:
"""发布可由多个库存源共享的最小库存解析 Profile。""" """发布可由多个库存源共享的最小库存解析 Profile。"""
state = order_schema_service.get_state() state = order_schema_service.get_state()
@@ -63,6 +83,7 @@ def _parsing_profile() -> dict:
assert set(inventory_fields) == {'part_number', 'reservation_id', 'available_qty'} assert set(inventory_fields) == {'part_number', 'reservation_id', 'available_qty'}
draft = inventory_parsing_profile.save_draft({ draft = inventory_parsing_profile.save_draft({
'profile_code': 'COMMON_DBS', 'display_name': 'Common DBS', 'file_format': 'xlsx', 'profile_code': 'COMMON_DBS', 'display_name': 'Common DBS', 'file_format': 'xlsx',
'sample_analysis_id': _sample_evidence(),
'definition': { 'definition': {
'header_row_index': 1, 'header_row_index': 1,
'field_mapping': { 'field_mapping': {
@@ -206,6 +227,35 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test'] assert exc_info.value.details['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
def test_activation_status_exposes_structured_checks_without_duplicate_test_blocks(app):
"""未测试站点应显示后续验证步骤,但只由测试门禁阻断,避免管理员面对重复待办。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
payload = {
'source_code': 'CHECKS_SOURCE', 'display_name': 'Checks Source', 'connector_type': 'dbs',
'rpa_profile_id': login['id'], 'parsing_profile_id': None, 'excel_template_id': None,
'warehouse_resolution_mode': 'fixed', 'fixed_warehouse_id': 'DUB', 'snapshot_ttl_seconds': 3600,
'report_path_json': {
'program_group': 'Bison', 'program_label': 'AWSBI',
'report_group': 'Inventory', 'report_name': 'On Hand',
},
'query_parameters_json': [], 'match_aliases_json': [], 'enabled': False,
}
draft = shipping_inventory_service.save_source(payload, actor_id=None, allow_enable_transition=False)
checks = {item['code']: item for item in draft['activation']['checks']}
# 关键断言:未进行测试时,解析/仓库验证被展示为待测试而非额外阻断门禁。
assert checks['configuration_test']['blocking'] is True
assert checks['configuration_test']['evidence'] == {'state': 'not_started'}
assert checks['parsing_validation']['status'] == 'pending'
assert checks['parsing_validation']['blocking'] is False
assert checks['warehouse_mapping']['status'] == 'pending'
assert checks['warehouse_mapping']['blocking'] is False
assert draft['activation']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
def test_enabled_source_rejects_disabled_rpa_profile(app): def test_enabled_source_rejects_disabled_rpa_profile(app):
"""启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。""" """启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。"""
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
@@ -176,3 +176,33 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m
error = parse_api_error(activation.get_json()) error = parse_api_error(activation.get_json())
assert error['code'] == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED' assert error['code'] == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED'
assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test'] assert error['details']['missing_requirements'] == ['parsing_profile', 'excel_template', 'configuration_test']
def test_latest_inventory_configuration_test_is_admin_only(app, client):
"""最近测试状态仅允许管理员读取,且没有测试记录时仍返回标准空数据 envelope。"""
app.config['AUTH_JWT_REQUIRED'] = False
with app.app_context():
_create_users()
profile = ShippingRpaProfile(
profile_code='API_LATEST_TEST_LOGIN', display_name='Latest Test', connector_type='dbs',
login_url='https://example.invalid', login_config_json={'auth_mode': 'password'}, enabled=True,
)
db.session.add(profile)
source = ShippingInventorySource(
source_code='API_LATEST_TEST_SOURCE', display_name='Latest Test Source', connector_type='dbs',
rpa_profile=profile, warehouse_resolution_mode='fixed', fixed_warehouse_id='DUB',
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inventory', 'report_name': 'On Hand'},
query_parameters_json=[], match_aliases_json=[], enabled=False,
)
db.session.add(source)
db.session.commit()
source_id = source.id
forbidden = client.get(f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest')
assert forbidden.status_code in {401, 403}
response = client.get(
f'/api/admin/shipping-notice/sources/{source_id}/test-export/latest',
headers=_headers('inventory-admin', 'admin'),
)
assert response.status_code == 200
assert parse_api_data(response.get_json()) is None
@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
from datetime import datetime, timedelta
from pathlib import Path from pathlib import Path
from unittest.mock import patch from unittest.mock import patch
@@ -18,6 +19,7 @@ from app.models import (
ShippingExcelTemplate, ShippingExcelTemplate,
ShippingInventoryFile, ShippingInventoryFile,
ShippingInventoryField, ShippingInventoryField,
ShippingRpaProfile,
ShippingInventorySource, ShippingInventorySource,
) )
from app.services.admin import shipping_inventory_service from app.services.admin import shipping_inventory_service
@@ -125,6 +127,57 @@ def test_configuration_test_callback_isolated_from_production_inventory(app, tmp
assert ShippingInventoryConfigurationTestRun.query.count() == 1 assert ShippingInventoryConfigurationTestRun.query.count() == 1
def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_path):
"""重开配置抽屉只能恢复当前版本测试;站点改动后可发起独立新测试而不复用旧运行。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
first = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
assert inventory_configuration_test.get_latest_test_run(source['id'])['run_no'] == first['run_no']
current = next(item for item in shipping_inventory_service.list_sources() if item['id'] == source['id'])
shipping_inventory_service.save_source({**current, 'display_name': 'Changed before callback'}, actor_id=None, source_id=source['id'])
# 关键断言:旧运行不再属于当前配置,重新测试必须创建新运行而不是误复用。
assert inventory_configuration_test.get_latest_test_run(source['id']) is None
second = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
assert second['run_no'] != first['run_no']
assert inventory_configuration_test.get_latest_test_run(source['id'])['run_no'] == second['run_no']
def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
"""RPA 长时间未回调时,读取最近运行应服务端收口为失败而非让前端无限轮询。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
started = inventory_configuration_test.start_test_export(source['id'], actor_id=None)
run = ShippingInventoryConfigurationTestRun.query.filter_by(run_no=started['run_no']).one()
run.created_at = datetime.utcnow() - timedelta(seconds=2)
db.session.commit()
recovered = inventory_configuration_test.get_latest_test_run(source['id'])
# 关键断言:超时是明确失败终态,客户端无需自行推断或继续轮询。
assert recovered['status'] == 'failed'
assert recovered['stage'] == 'failed'
assert '超时' in recovered['error_message']
result_file = tmp_path / 'late-rpa-result.xlsx'
_workbook(result_file)
late_callback = inventory_configuration_test.report_test_export({
'run_no': started['run_no'], 'status': 'success', 'file_path': str(result_file),
})
# 关键断言:超时后的迟到回调不能将失败任务重新写成完成,也不能生成结构分析证据。
assert late_callback['status'] == 'failed'
assert ShippingInventoryConfigurationTestRun.query.filter_by(run_no=started['run_no']).one().analysis_id is None
def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path): def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path):
"""确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。""" """确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
@@ -165,6 +218,40 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
db.session.commit() db.session.commit()
assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True assert shipping_inventory_service.get_source_activation_status(source_model)['ready'] is True
assert shipping_inventory_service.activate_source(source['id'], actor_id=None)['enabled'] is True assert shipping_inventory_service.activate_source(source['id'], actor_id=None)['enabled'] is True
assert next(
item for item in shipping_inventory_service.get_source_activation_status(source_model)['checks']
if item['code'] == 'configuration_test'
)['status'] == 'passed'
def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path):
"""连接凭据或登录配置变更后,旧测试不得继续作为当前库存站点的启用证据。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context(), patch(
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
):
source = _source()
completed = _complete_test_run(source, tmp_path)
profile = _publish_profile_from_analysis(completed['analysis_id'], _published_order_field(), code='PROFILE_STALE')
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
rpa_profile = db.session.get(ShippingRpaProfile, source['rpa_profile_id'])
shipping_inventory_service.save_profile({
'profile_code': rpa_profile.profile_code, 'display_name': rpa_profile.display_name,
'connector_type': rpa_profile.connector_type, 'login_url': rpa_profile.login_url,
'login_config_json': rpa_profile.login_config_json, 'enabled': True,
'username': 'updated-user', 'password': 'updated-password',
}, actor_id=None, profile_id=rpa_profile.id)
source_model = db.session.get(ShippingInventorySource, source['id'])
test_check = next(
item for item in shipping_inventory_service.get_source_activation_status(source_model)['checks']
if item['code'] == 'configuration_test'
)
# 关键断言:连接配置版本变更使已完成测试失效,不能继续放行正式运行。
assert test_check['status'] == 'stale'
assert test_check['blocking'] is True
def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path): def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path):
@@ -184,6 +271,15 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t
inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None) inventory_configuration_test.confirm_test_profile(source['id'], completed['run_no'], profile['id'], actor_id=None)
assert stale.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE' assert stale.value.code == 'SHIPPING.INVENTORY_CONFIGURATION_TEST_STALE'
# 关键断言:旧配置版本的测试只能作为过期证据展示,不能被误判为当前测试通过。
stale_status = shipping_inventory_service.get_source_activation_status(
db.session.get(ShippingInventorySource, source['id']),
)
test_check = next(item for item in stale_status['checks'] if item['code'] == 'configuration_test')
assert test_check['status'] == 'stale'
assert test_check['blocking'] is True
assert test_check['evidence']['run_no'] == completed['run_no']
source_model = db.session.get(ShippingInventorySource, source['id']) source_model = db.session.get(ShippingInventorySource, source['id'])
source_model.parsing_profile_id = profile['id'] source_model.parsing_profile_id = profile['id']
template = ShippingExcelTemplate( template = ShippingExcelTemplate(
@@ -221,12 +317,13 @@ def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path):
_publish_profile_from_analysis(completed['analysis_id'], field_id, code='TEST_MATCHED') _publish_profile_from_analysis(completed['analysis_id'], field_id, code='TEST_MATCHED')
unrelated = inventory_parsing_profile.save_draft({ unrelated = inventory_parsing_profile.save_draft({
'profile_code': 'TEST_UNRELATED', 'display_name': 'Unrelated', 'file_format': 'xlsx', 'profile_code': 'TEST_UNRELATED', 'display_name': 'Unrelated', 'file_format': 'xlsx',
'sample_analysis_id': completed['analysis_id'],
'definition': { 'definition': {
'sheet_name': 'Other', 'header_row_index': 1, 'sheet_name': 'Sheet', 'header_row_index': 1,
'field_mapping': { 'field_mapping': {
_inventory_field_id('part_number'): 'Other Part', _inventory_field_id('part_number'): 'Supplier Sku',
_inventory_field_id('reservation_id'): 'Other Reservation', _inventory_field_id('reservation_id'): 'Reservation ID',
_inventory_field_id('available_qty'): 'Other Qty', _inventory_field_id('available_qty'): 'Qty Available',
}, },
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}], 'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}],
}, },
@@ -12,7 +12,7 @@ from app.services.admin import shipping_inventory_service
from app.services.shipping_notice import inventory_parsing_profile from app.services.shipping_notice import inventory_parsing_profile
from app.services.shipping_notice.order_schema import service as order_schema_service from app.services.shipping_notice.order_schema import service as order_schema_service
from app import db from app import db
from app.models import ShippingExcelTemplate, ShippingInventoryField from app.models import ShippingExcelTemplate, ShippingInventoryField, ShippingInventoryStructureAnalysis
def _inventory_mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reservation ID', quantity: str = 'Qty Available') -> dict[str, str]: def _inventory_mapping(*, part: str = 'Supplier Sku', reservation: str = 'Reservation ID', quantity: str = 'Qty Available') -> dict[str, str]:
@@ -30,6 +30,21 @@ def _part_number_field_id() -> str:
return str(ShippingInventoryField.query.filter_by(field_code='part_number').one().id) return str(ShippingInventoryField.query.filter_by(field_code='part_number').one().id)
def _sample_evidence(*, headers: list[str], sheet_name: str | None = None, file_format: str = 'xlsx') -> int:
"""构造最小化样本结构证据,使 Profile 测试遵循生产环境的表头绑定门禁。"""
item = ShippingInventoryStructureAnalysis(
source_kind='sample_upload', source_file_name='sample.xlsx', storage_path=None,
file_checksum='a' * 64, file_format=file_format, analysis_status='ready',
structure_json={'candidates': [{
'sheet_name': sheet_name, 'header_row_index': 1, 'headers': headers,
'columns': [{'header': header, 'duplicate': False} for header in headers],
}]}, suggested_mapping_json={}, validation_summary_json={}, sample_rows_json=[], warning_json=[],
)
db.session.add(item)
db.session.flush()
return item.id
def _published_profile() -> dict: def _published_profile() -> dict:
"""创建含 part_number 匹配键的 published 解析 Profile。""" """创建含 part_number 匹配键的 published 解析 Profile。"""
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None) order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
@@ -44,6 +59,7 @@ def _published_profile() -> dict:
) )
draft = inventory_parsing_profile.save_draft({ draft = inventory_parsing_profile.save_draft({
'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common', 'file_format': 'xlsx', 'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common', 'file_format': 'xlsx',
'sample_analysis_id': _sample_evidence(headers=['Supplier Sku', 'Reservation ID', 'Qty Available']),
'definition': { 'definition': {
'header_row_index': 1, 'header_row_index': 1,
'field_mapping': _inventory_mapping(), 'field_mapping': _inventory_mapping(),
@@ -122,9 +138,11 @@ def test_source_rejects_draft_parsing_profile(app):
field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None) field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
draft = inventory_parsing_profile.save_draft({ draft = inventory_parsing_profile.save_draft({
'profile_code': 'DRAFT_ONLY', 'display_name': 'Draft', 'definition': { 'profile_code': 'DRAFT_ONLY', 'display_name': 'Draft', 'definition': {
'sheet_name': None, 'header_row_index': 1,
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'), 'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}], 'match_keys': [{'order_field_id': field['id'], 'inventory_field_id': _part_number_field_id()}],
}, },
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
}, actor_id=None) }, actor_id=None)
login = shipping_inventory_service.save_profile({ login = shipping_inventory_service.save_profile({
'profile_code': 'LOGIN', 'display_name': 'Login', 'connector_type': 'dbs', 'profile_code': 'LOGIN', 'display_name': 'Login', 'connector_type': 'dbs',
@@ -163,7 +181,9 @@ def test_new_published_version_does_not_retire_bound_version(app):
field_id = order_schema_service.get_state()['fields'][0]['id'] field_id = order_schema_service.get_state()['fields'][0]['id']
second_draft = inventory_parsing_profile.save_draft({ second_draft = inventory_parsing_profile.save_draft({
'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common v2', 'file_format': 'xlsx', 'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common v2', 'file_format': 'xlsx',
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
'definition': { 'definition': {
'header_row_index': 1,
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'), 'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _part_number_field_id()}], 'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _part_number_field_id()}],
}, },
@@ -204,7 +224,9 @@ def test_parsing_profile_publish_rejects_field_removed_from_current_schema(app):
) )
profile = inventory_parsing_profile.save_draft({ profile = inventory_parsing_profile.save_draft({
'profile_code': 'STALE_FIELD', 'display_name': 'Stale Field', 'profile_code': 'STALE_FIELD', 'display_name': 'Stale Field',
'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']),
'definition': { 'definition': {
'sheet_name': None, 'header_row_index': 1,
'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'), 'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'),
'match_keys': [{'order_field_id': old_field['id'], 'inventory_field_id': _part_number_field_id()}], 'match_keys': [{'order_field_id': old_field['id'], 'inventory_field_id': _part_number_field_id()}],
}, },
@@ -16,9 +16,10 @@ from werkzeug.datastructures import FileStorage
import pytest import pytest
from app.core.errors import ValidationError from app.core.errors import ValidationError
from app.extensions import db
from app.services.shipping_notice import inventory_structure_analysis from app.services.shipping_notice import inventory_structure_analysis
from app.services.shipping_notice.order_schema import service as order_schema_service from app.services.shipping_notice.order_schema import service as order_schema_service
from app.models import ShippingInventoryField from app.models import ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventoryStructureAnalysis
def _field_id(field_code: str) -> str: def _field_id(field_code: str) -> str:
@@ -75,7 +76,7 @@ def _published_part_number() -> str:
def test_sample_analysis_reads_real_worksheet_headers_and_suggestions(app, tmp_path): def test_sample_analysis_reads_real_worksheet_headers_and_suggestions(app, tmp_path):
"""上传样本必须定位真实库存表头,并仅返回少量样例和值类型统计。""" """上传样本必须定位真实库存表头,只持久化脱敏样例并清理完整工作簿。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context(): with app.app_context():
result = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None) result = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
@@ -88,6 +89,35 @@ def test_sample_analysis_reads_real_worksheet_headers_and_suggestions(app, tmp_p
qty = next(column for column in columns if column['header'] == 'Qty Available') qty = next(column for column in columns if column['header'] == 'Qty Available')
assert qty['inferred_type'] == 'number' assert qty['inferred_type'] == 'number'
assert qty['sample_values'] == ['9', '11'] assert qty['sample_values'] == ['9', '11']
assert result['sample_rows'][0] == ['P***1', '10***51', 9, 'A***U', '00***74']
analysis = db.session.get(ShippingInventoryStructureAnalysis, result['id'])
assert analysis is not None
assert analysis.storage_path is None
assert analysis.sample_rows_json == result['sample_rows']
assert not list((tmp_path / 'shipping' / 'inventory_structure_analyses').rglob('*.xlsx'))
def test_sample_analysis_prefers_populated_detail_sheet_over_same_score_summary(app, tmp_path):
"""同分候选时必须优先明细表,且只保存最终选定工作表的脱敏样例。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
stream = BytesIO()
workbook = Workbook()
summary = workbook.active
summary.title = 'Summary'
summary.append(['Summary'])
summary.append(['SECRET-SUMMARY'])
inventory = workbook.create_sheet('Inventory')
inventory.append(['Supplier SKU', 'Reservation ID', 'Qty Available'])
inventory.append(['PART-001', 'RSV-001', 7])
workbook.save(stream)
stream.seek(0)
result = inventory_structure_analysis.create_sample_upload(
FileStorage(stream=stream, filename='multi-sheet.xlsx'), actor_id=None,
)
assert result['structure']['selected_sheet_name'] == 'Inventory'
assert result['sample_rows'] == [['PA***01', 'RS***01', 7]]
assert all('_sample_rows' not in candidate for candidate in result['structure']['candidates'])
def test_sample_analysis_reads_legacy_xls(app, tmp_path): def test_sample_analysis_reads_legacy_xls(app, tmp_path):
@@ -158,6 +188,89 @@ def test_profile_draft_uses_analysis_header_selection(app, tmp_path):
assert profile['status'] == 'draft' assert profile['status'] == 'draft'
assert profile['definition']['sheet_name'] == 'Inventory' assert profile['definition']['sheet_name'] == 'Inventory'
assert profile['definition']['field_mapping'][_field_id('part_number')] == 'Supplier Sku' assert profile['definition']['field_mapping'][_field_id('part_number')] == 'Supplier Sku'
saved = db.session.get(ShippingInventoryParsingProfile, profile['id'])
assert saved is not None
assert saved.sample_analysis_id == analysis['id']
def test_profile_sample_replacement_requires_confirmation_and_keeps_audit_history(app, tmp_path):
"""替换草稿样本必须显式确认,成功后保留旧样本 ID 的可追溯链。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
field_id = _published_part_number()
first = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
profile = inventory_structure_analysis.create_profile_draft(first['id'], {
'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
}, actor_id=None)
second = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
preview = inventory_structure_analysis.preview_profile_sample_replacement(profile['id'], second['id'])
assert preview['can_confirm'] is True
assert preview['difference']['missing_mapped_headers'] == []
with pytest.raises(ValidationError) as exc_info:
inventory_structure_analysis.create_profile_draft(second['id'], {
'profile_id': profile['id'], 'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SAMPLE_REPLACEMENT_CONFIRMATION_REQUIRED'
updated = inventory_structure_analysis.create_profile_draft(second['id'], {
'profile_id': profile['id'], 'profile_code': 'SAMPLE_REPLACEMENT', 'display_name': 'Sample replacement',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
'confirm_sample_replacement': True,
}, actor_id=None)
assert updated['sample_analysis_id'] == second['id']
assert updated['sample_evidence_history'][-1]['previous_analysis_id'] == first['id']
assert updated['sample_evidence_history'][-1]['replacement_analysis_id'] == second['id']
def test_profile_sample_replacement_rejects_file_format_change(app, tmp_path):
"""草稿不能借由替换样本改变文件格式,防止运行期解析契约被静默改写。"""
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
with app.app_context():
field_id = _published_part_number()
first = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
profile = inventory_structure_analysis.create_profile_draft(first['id'], {
'profile_code': 'FORMAT_REPLACEMENT', 'display_name': 'Format replacement',
'sheet_name': 'Inventory', 'header_row_index': 3,
'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
}, actor_id=None)
csv_upload = FileStorage(
stream=BytesIO(b'Supplier Sku,Reservation ID,Qty Available\nPN-001,R-1,1\n'),
filename='replacement.csv',
)
csv_analysis = inventory_structure_analysis.create_sample_upload(csv_upload, actor_id=None)
with pytest.raises(ValidationError) as exc_info:
inventory_structure_analysis.create_profile_draft(csv_analysis['id'], {
'profile_id': profile['id'], 'profile_code': 'FORMAT_REPLACEMENT', 'display_name': 'Format replacement',
'header_row_index': 1, 'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
'confirm_sample_replacement': True,
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_PARSING_PROFILE_INVALID'
def test_profile_draft_requires_persisted_sample_evidence(app):
"""绕过样本分析直接保存草稿时必须被拒绝,避免来源表头脱离审计依据。"""
with app.app_context():
field_id = _published_part_number()
from app.services.shipping_notice import inventory_parsing_profile
with pytest.raises(ValidationError) as exc_info:
inventory_parsing_profile.save_draft({
'profile_code': 'NO_EVIDENCE', 'display_name': 'No evidence', 'file_format': 'xlsx',
'definition': {
'sheet_name': 'Inventory', 'header_row_index': 1, 'field_mapping': _mapping(),
'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _field_id('part_number')}],
},
}, actor_id=None)
assert exc_info.value.code == 'SHIPPING.INVENTORY_SAMPLE_EVIDENCE_REQUIRED'
def test_sample_analysis_rejects_invalid_file(app, tmp_path): def test_sample_analysis_rejects_invalid_file(app, tmp_path):
+1 -1
View File
@@ -110,7 +110,7 @@
- 管理端必须使用后端字段目录和白名单提供结构化选择器,不要求业务管理员直接编辑 Profile/模板 JSON;发布新 Schema 版本时,若移除仍被路由、库存解析 Profile 或 Excel 模板引用的字段,必须阻断并要求先迁移下游配置。 - 管理端必须使用后端字段目录和白名单提供结构化选择器,不要求业务管理员直接编辑 Profile/模板 JSON;发布新 Schema 版本时,若移除仍被路由、库存解析 Profile 或 Excel 模板引用的字段,必须阻断并要求先迁移下游配置。
- 发货 Excel 模板必须独立版本化管理并由库存源绑定 published 版本;多个同结构库存源共享同一模板,不得在库存源中复制映射。模板发布后文件和映射不可变。 - 发货 Excel 模板必须独立版本化管理并由库存源绑定 published 版本;多个同结构库存源共享同一模板,不得在库存源中复制映射。模板发布后文件和映射不可变。
- 库存站点允许先以禁用状态保存基础信息,逐步通过测试导出确认库存文件解析方案并绑定 published 发货模板;首次保存不要求手工选择解析方案。正式启用是独立门禁动作,必须完成连接、测试导出与解析验证、解析方案、发货模板和仓库映射;一旦启用,各项绑定必须齐全且有效。固定仓须维护该货代仓的精确映射或库存源默认映射;动态仓还须从测试文件识别仓库栏位并覆盖测试样例中的每个仓库。系统绝不根据名称相似度自动创建外部仓库映射。 - 库存站点允许先以禁用状态保存基础信息,逐步通过测试导出确认库存文件解析方案并绑定 published 发货模板;首次保存不要求手工选择解析方案。正式启用是独立门禁动作,必须完成连接、测试导出与解析验证、解析方案、发货模板和仓库映射;一旦启用,各项绑定必须齐全且有效。固定仓须维护该货代仓的精确映射或库存源默认映射;动态仓还须从测试文件识别仓库栏位并覆盖测试样例中的每个仓库。系统绝不根据名称相似度自动创建外部仓库映射。
- 库存文件解析方案支持上传 `.xls` / `.xlsx` / `.csv` 样本;后端必须分析工作表、候选表头、真实列名、少量脱敏样例、类型与空值统计,并以结构化选择器供管理员确认。浏览器端不得作为发布依据,也不得要求管理员手输来源栏位。 - 库存文件解析方案支持上传 `.xls` / `.xlsx` / `.csv` 样本;后端必须分析工作表、候选表头、真实列名、少量脱敏样例、类型与空值统计,并以结构化选择器供管理员确认。完整样本文件仅供即时分析,完成后立即清理;草稿及发布版本必须绑定并保留文件名、校验值、完整表头、结构指纹、统计和最多五行脱敏样例,供后续编辑与审计。浏览器端不得作为发布依据,也不得要求管理员手输来源栏位。
- 相同库存模板按文件结构及已发布方案实际使用的“库存匹配/库存数量”栏位确定性判断,不按文件名、库存数据内容或文件内容 hash 判断。完全一致可推荐复用已发布方案;仅新增无关栏位或非关键顺序变化时提示兼容差异;方案所需栏位缺失、重复或冲突不得复用。推荐方案必须由管理员确认,样本上传不得自动绑定库存站点。 - 相同库存模板按文件结构及已发布方案实际使用的“库存匹配/库存数量”栏位确定性判断,不按文件名、库存数据内容或文件内容 hash 判断。完全一致可推荐复用已发布方案;仅新增无关栏位或非关键顺序变化时提示兼容差异;方案所需栏位缺失、重复或冲突不得复用。推荐方案必须由管理员确认,样本上传不得自动绑定库存站点。
- 停用库存站点可以发起异步测试导出。测试文件仅用于连接、文件结构和解析验证,不得进入正式库存快照、订单库存匹配、发货 Excel 或正式导出记录;管理员确认已发布解析方案后才更新该停用站点的绑定。 - 停用库存站点可以发起异步测试导出。测试文件仅用于连接、文件结构和解析验证,不得进入正式库存快照、订单库存匹配、发货 Excel 或正式导出记录;管理员确认已发布解析方案后才更新该停用站点的绑定。
- 每次正式 RPA 导出在写入库存快照前都必须复核文件结构:完全一致正常入库;仅新增非关键栏位或顺序变化可入库并记录差异;格式、工作表、表头行、关键栏位或映射变化必须阻断入库和库存匹配。正式运行只能使用已发布解析方案的工作表、表头行和字段映射,不允许自动猜列兜底。 - 每次正式 RPA 导出在写入库存快照前都必须复核文件结构:完全一致正常入库;仅新增非关键栏位或顺序变化可入库并记录差异;格式、工作表、表头行、关键栏位或映射变化必须阻断入库和库存匹配。正式运行只能使用已发布解析方案的工作表、表头行和字段映射,不允许自动猜列兜底。
+1 -1
View File
@@ -247,7 +247,7 @@ WYC26071501
| 仓库识别 | 仅按库存行动态识别仓库的站点需要,每个方案只能使用一个 | | 仓库识别 | 仅按库存行动态识别仓库的站点需要,每个方案只能使用一个 |
| 一般业务信息 | 按需创建,可写入发货模板,例如 ODM、批次、库位等;这些名称均不是系统内置 | | 一般业务信息 | 按需创建,可写入发货模板,例如 ODM、批次、库位等;这些名称均不是系统内置 |
上传库存样本后,系统会读取工作表、表头和少量样例。字段名称与表头完全相同时可以自动预填;名称不同时,由管理员从下拉框选择,或让 Dify 根据真实表头给出候选,再由管理员确认。候选不会自动创建字段、发布方案或绑定库存站点。 上传库存样本后,系统会读取工作表、表头和少量样例。完整 Excel 只用于本次即时分析,完成后不会长期保存;系统保留文件名、校验值、完整表头、结构统计和最多五行脱敏样例,作为该库存映射的配置证据。再次打开草稿时,系统从这份证据恢复工作表、表头下拉、字段映射和脱敏预览,管理员可以继续维护,无需重新上传文件;浏览器不会伪造“已选择原文件”。替换样本时,系统先展示新增/缺少栏位、顺序变化和会失效的当前映射;管理员调整映射并在平台确认弹窗确认后,才切换到新样本。旧样本不会删除,而是记录在该草稿的样本替换历史中。字段名称与表头完全相同时可以自动预填;名称不同时,由管理员从下拉框选择,或让 Dify 根据真实表头给出候选,再由管理员确认。候选不会自动创建字段、发布方案或绑定库存站点。
--- ---
+141 -2
View File
@@ -408,9 +408,15 @@ GET /api/admin/shipping-order-schema/published-contract
- `ShippingInventoryParsingProfile` 独立于 RPA 登录 Profile 和 Inventory Source,使用 `draft -> published -> retired` 版本生命周期。 - `ShippingInventoryParsingProfile` 独立于 RPA 登录 Profile 和 Inventory Source,使用 `draft -> published -> retired` 版本生命周期。
- Profile 定义保存 `file_format/sheet_name/header_row_index/field_mapping/match_keys`;`field_mapping` 为 `inventory_field_id -> source_header`,`match_keys` 为稳定订单 `order_field_id -> inventory_field_id`,均不保存显示名称或原始表头以外的技术字段。 - Profile 定义保存 `file_format/sheet_name/header_row_index/field_mapping/match_keys`;`field_mapping` 为 `inventory_field_id -> source_header`,`match_keys` 为稳定订单 `order_field_id -> inventory_field_id`,均不保存显示名称或原始表头以外的技术字段。
- 管理端以结构化行编辑器维护标准库存字段、文件表头与订单行字段匹配键,所有可选项来自后端 `GET /api/admin/shipping-notice/configuration-catalog`,不要求管理员直接编辑 JSON。 - 管理端以结构化行编辑器维护标准库存字段、文件表头与订单行字段匹配键,所有可选项来自后端 `GET /api/admin/shipping-notice/configuration-catalog`,不要求管理员直接编辑 JSON。
- 管理员新建库存文件解析方案时先上传 `.xls/.xlsx/.csv` 样本至 `POST /api/admin/shipping-notice/inventory-structure-analyses`。后端读取所有工作表、候选表头、真实栏位、少量样例、推断类型与空值率;页面只允许从分析结果选择工作表、表头和来源栏位。`POST /inventory-structure-analyses/{id}/create-profile-draft` 用确认后的结果创建草稿,不能以浏览器提交的虚构栏位替代分析结果。 - 管理员新建库存文件解析方案时先上传 `.xls/.xlsx/.csv` 样本至 `POST /api/admin/shipping-notice/inventory-structure-analyses`。后端读取所有工作表、候选表头、真实栏位、推断类型、空值率与最多五行脱敏样例;管理端样本完整文件只在即时分析期间存在,分析完成后立即清理。`shipping_inventory_structure_analyses` 保留文件名、checksum、完整结构、统计、结构指纹和脱敏样例;`ShippingInventoryParsingProfile.sample_analysis_id` 绑定草稿和发布版本的样本证据。页面只允许从该证据选择工作表、表头和来源栏位,`POST /inventory-structure-analyses/{id}/create-profile-draft` 用确认后的结果创建草稿,不能以浏览器提交的虚构栏位替代分析结果。解析方案列表 DTO 返回最小化 `sample_evidence`;管理端再次打开草稿时从此恢复候选工作表、表头、来源栏位下拉和脱敏预览,不读取或回传原始文件。草稿替换样本前通过 `POST /parsing-profiles/{profile_id}/sample-replacement-preview/{analysis_id}` 以当前拟保存映射计算新增/缺少栏位、顺序变化、失效映射和格式差异;仅无失效映射且管理员在平台确认弹窗确认后,`create-profile-draft` 才接受 `confirm_sample_replacement=true` 切换证据。旧/新分析 ID、操作者和时间追加到 `sample_evidence_history_json`,已发布版本不可替换样本。Dify 画布不参与此证据绑定流程。
- 样本分析为文件结构生成精确指纹,解析方案保存同样的不可变结构定义;库存数据和文件名不参与判断。已发布方案的表头完全相同则返回 `exact`;方案实际使用的匹配/数量来源表头仍存在且仅有无关列变化时返回 `compatible` 并列出差异;所需栏位缺失、重复或冲突时不推荐复用。字段显示名称与真实表头标准化后完全相同时可确定性预填,其他陌生表头必须由管理员选择或 Dify 仅给候选。系统不得内置固定业务字段词典或自动创建字段。 - 样本分析为文件结构生成精确指纹,解析方案保存同样的不可变结构定义;库存数据和文件名不参与判断。已发布方案的表头完全相同则返回 `exact`;方案实际使用的匹配/数量来源表头仍存在且仅有无关列变化时返回 `compatible` 并列出差异;所需栏位缺失、重复或冲突时不推荐复用。字段显示名称与真实表头标准化后完全相同时可确定性预填,其他陌生表头必须由管理员选择或 Dify 仅给候选。系统不得内置固定业务字段词典或自动创建字段。
- 停用库存站点通过 `POST /api/admin/shipping-notice/sources/{id}/test-export` 写入 `configuration_test` trigger,Worker 完成后回调 `/api/shipping-notice/rpa/inventory-configuration-test-ready`。该文件只进入结构分析,不创建生产快照或任务链接;管理端轮询 `GET /sources/{id}/test-export/{run_no}` 并通过 `POST .../confirm-profile` 确认解析方案。Dify 不参与该流程。 - 停用库存站点通过 `POST /api/admin/shipping-notice/sources/{id}/test-export` 写入 `configuration_test` trigger,Worker 完成后回调 `/api/shipping-notice/rpa/inventory-configuration-test-ready`。该文件只进入结构分析,不创建生产快照或任务链接;管理端轮询 `GET /sources/{id}/test-export/{run_no}` 并通过 `POST .../confirm-profile` 确认解析方案。Dify 不参与该流程。
- 库存站点详情的 `activation` 是 HXOPS 后端唯一的上线检查真相,返回 `ready` 与按配置顺序排列的 `checks[]`。每项包含稳定业务编号 `code`、`passed / pending / failed / stale` 状态、`blocking`、推荐 `action` 和非敏感 `evidence`;管理端只负责翻译与引导,不得根据表单值重算启用资格。`missing_requirements` 仅是由阻断 checks 派生的紧凑摘要。
- 管理端库存站点抽屉以“正式运行检查”状态轨道呈现 `checks[]`:已完成、待处理、失败/过期均同时提供图形与文本;每个阻断项至多提供一个推荐动作。测试导出留在站点抽屉,连接、解析、模板和仓库映射则跳转到对应维护区。若站点表单存在未保存修改,测试和启用操作必须禁用并提示先保存,禁止隐式保存或以旧配置发起测试。
- 配置测试、解析验证和仓库映射均绑定 `source.config_version` 与测试时的 `rpa_profile.config_version`。修改测试输入(库存站点配置、连接地址、登录方式或凭据)后,旧测试显示为 `stale` 且不能确认方案或启用;启用/停用仅改变运行状态,不使同一配置的已确认测试失效。尚未测试时,后续解析/仓库检查显示 `pending` 但不重复作为额外阻断项。动态仓 evidence 返回测试样例仓库;固定仓 evidence 返回当前固定仓与映射模式。任何 evidence 均不得包含 RPA 凭据、完整文件内容或内部路径。
- **Dify 手动配置说明**:本阶段无需新增、修改或重新导入 Dify Tool/OpenAPI,也无需修改画布或 Prompt。库存站点测试、结构检查、方案确认和启用均由管理端调用 HXOPS Admin API 完成;Dify 不读取或判断 `activation.checks`。
- `GET /api/admin/shipping-notice/sources/{id}/test-export/latest` 只返回**当前站点配置和当前 RPA Profile 配置版本**对应的最近测试,无记录时返回 `null`。管理端打开站点抽屉时读取该接口恢复测试状态,只有 `awaiting_rpa / processing` 才轮询运行详情;关闭抽屉立即停止轮询。重复发起测试仅复用同一版本的运行任务,配置变更后的旧运行不会阻止新测试。
- 测试运行超过 `SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS`(默认 900 秒)仍未完成时,服务端在读取或再次发起测试时将其收口为 `failed / failed`,提示“等待 RPA Worker 超时,请重新测试”。超时、版本不一致和重复/迟到回调都不能更新当前站点绑定或放行启用。**Dify 手动配置说明**:此恢复与轮询机制不要求修改 Dify 画布、Tool 或 Prompt;Dify 不读取此管理端状态接口。
- 多个 Inventory Source 可绑定同一个 published Profile;同模板只维护一份。存在少量列差异时创建新 Profile 版本或新 Profile,不在 Source 中复制完整映射。 - 多个 Inventory Source 可绑定同一个 published Profile;同模板只维护一份。存在少量列差异时创建新 Profile 版本或新 Profile,不在 Source 中复制完整映射。
- 库存站点首次保存不要求绑定解析方案,且普通保存始终保持停用;后端仅允许通过独立启用接口进入正式运行。启用检查列出系统连接、库存文件解析方案、发货模板和测试导出与解析验证;确认后测试记录与站点当前配置版本绑定,后续编辑会使其失效。草稿、缺失或非法作用域字段仍阻断正式运行期自动解析。 - 库存站点首次保存不要求绑定解析方案,且普通保存始终保持停用;后端仅允许通过独立启用接口进入正式运行。启用检查列出系统连接、库存文件解析方案、发货模板和测试导出与解析验证;确认后测试记录与站点当前配置版本绑定,后续编辑会使其失效。草稿、缺失或非法作用域字段仍阻断正式运行期自动解析。
- 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `freight_warehouse_id` 映射或库存源默认映射;动态仓还要求唯一仓库识别字段且测试样例中每个仓库都有精确映射或默认映射。该检查只查询已维护的 `ShippingInventoryExternalMapping`,绝不自动创建映射。 - 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `freight_warehouse_id` 映射或库存源默认映射;动态仓还要求唯一仓库识别字段且测试样例中每个仓库都有精确映射或默认映射。该检查只查询已维护的 `ShippingInventoryExternalMapping`,绝不自动创建映射。
@@ -744,6 +750,7 @@ test/prod 触发库存 RPA 前,后端会检查 Worker 是否在线、环境是
| Windows RPA | `SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` | `test` | `prod` | | Windows RPA | `SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT` | `test` | `prod` |
| Windows RPA | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | `15`~`30`(默认 20) | 同左 | | Windows RPA | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS` | `15`~`30`(默认 20) | 同左 |
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS` | `90`(默认) | `90` | | Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS` | `90`(默认) | `90` |
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED` | `false`(默认关闭企微心跳告警) | 同左;需要时改为 `true` |
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES` | 逗号分隔 HXOPS 用户名(**部署前建议显式填写**) | 同左 | | Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES` | 逗号分隔 HXOPS 用户名(**部署前建议显式填写**) | 同左 |
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN` | `true`(未配用户名时通知已绑企微的 admin) | 建议 `true` | | Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN` | `true`(未配用户名时通知已绑企微的 admin) | 建议 `true` |
| Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS` | `120`(企微发送中短锁,失败后可重试) | `120` | | Ubuntu 后端 | `SHIPPING_NOTICE_RPA_WORKER_ALERT_SEND_LOCK_SECONDS` | `120`(企微发送中短锁,失败后可重试) | `120` |
@@ -768,7 +775,7 @@ 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。
心跳存储:test/prod 默认要求 **Redis**(`SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true`)。Redis 不可用时触发与排程会报 `RPA.HEARTBEAT_STORAGE_UNAVAILABLE`,调度器会按冷却发送企微「心跳存储异常」告警。 心跳存储:test/prod 默认要求 **Redis**(`SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true`)。Redis 不可用时触发与排程会报 `RPA.HEARTBEAT_STORAGE_UNAVAILABLE`;仅当 `SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=true` 时,调度器才会按冷却发送企微「心跳存储异常」告警(默认关闭)。
先验证 DSV 登录: 先验证 DSV 登录:
@@ -939,6 +946,8 @@ SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR=/mnt/hxops-rpa-test-data/upload_queu
SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90
SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true
# 企微心跳告警默认关闭;需要时改为 true
SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false
# 逗号分隔已绑企微的 HXOPS 用户名;留空且 FALLBACK_ADMIN=true 时通知 admin # 逗号分隔已绑企微的 HXOPS 用户名;留空且 FALLBACK_ADMIN=true 时通知 admin
SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=
SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true
@@ -1081,6 +1090,136 @@ Register-ScheduledTask `
- Ubuntu 重启后目录空了:执行 `sudo mount -a`,检查 `/etc/fstab`、网络是否已就绪、Windows 共享是否可访问。 - Ubuntu 重启后目录空了:执行 `sudo mount -a`,检查 `/etc/fstab`、网络是否已就绪、Windows 共享是否可访问。
- 排程一直 running:检查对应环境的 `/mnt/hxops-rpa-*-data/inventory_triggers/processed` 是否有对应 trigger、worker 日志是否回调 `/api/shipping-notice/rpa/inventory-batch-ready` 成功。 - 排程一直 running:检查对应环境的 `/mnt/hxops-rpa-*-data/inventory_triggers/processed` 是否有对应 trigger、worker 日志是否回调 `/api/shipping-notice/rpa/inventory-batch-ready` 成功。
#### 1.5.13 RPA 三环境部署与启停速查
本节是 `1.5.2` 至 `1.5.12` 的运行速查,**不替代也不删除**前述 Windows RPA 主机、SMB 共享、心跳和计划任务说明。Windows 本地仅用于当前项目目录下的联调;Linux 测试、正式环境仍使用“Linux 后端 + Windows RPA 主机 + SMB 共享”的既有架构。所有密钥、货代账号和 Windows 共享密码必须由受控 Secret 渠道注入,不能写入仓库、命令行历史或日志。
| 运行位置 | 适用目的 | 后端目录/环境 | Worker 目录与环境 | 禁止混用 |
| --- | --- | --- | --- | --- |
| Windows 本地 | 开发机联调、测试导出 | 当前项目 `backend/data/shipping_notice/freight_rpa/*`;本地后端 | 当前项目 `scripts/rpa/`;`dev` | 不连接 test/prod 共享目录,不使用 test/prod Key 或凭据 |
| Linux 测试服务器 | 测试环境库存导出 | `/mnt/hxops-rpa-test-data/*`;`.env.test` | Windows `C:\HxopsRpaTest`;`test` | 不得使用 `prod` scope、目录、API Base 或 Key |
| Linux 正式服务器 | 已验收的正式库存导出 | `/mnt/hxops-rpa-prod-data/*`;`.env.prod` | Windows `C:\HxopsRpaProd`;`prod` | 不得使用 `test` scope、目录、API Base 或 Key |
**通用启动顺序**:先确认 Linux 共享挂载与后端容器可用,再启动对应 Windows Worker,等待心跳和哨兵文件正常,最后从管理端发起测试导出。停止时反向执行:先停止发起新的导出,再停止 Windows Worker,最后按需停止 Linux 容器。测试环境的“配置测试导出”应在停用的库存站点发起;生产环境只对已审核、已启用且已绑定 published 解析方案的库存站点发起。
##### 1.5.13.1 Windows 本地:使用当前项目目录进行简单联调
适用于开发电脑直接运行当前项目,不创建 SMB 共享、不复制 RPA 脚本、不设置任务计划。以下命令在项目根目录 PowerShell 执行;Worker 不会自动读取 `.env.dev`,因此必须先由本机受控环境或当前 PowerShell 会话提供必填变量。
首次安装 Python 依赖和浏览器运行时:
```powershell
python -m pip install -r backend\requirements.txt
python -m pip install playwright
python -m playwright install chromium
```
在同一个 PowerShell 窗口中设置本地目录。`SHIPPING_NOTICE_TOOL_API_KEY` 和 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 请从本机受控 Secret 来源注入;真实库存导出需要后者解密平台下发的 RPA Profile 凭据。若只是验证 Worker 扫描、回调与文件流转,可把 `SHIPPING_NOTICE_RPA_WORKER_MOCK` 临时设为 `true`。
```powershell
$repoRoot = (Get-Location).Path
$rpaDataRoot = Join-Path $repoRoot "backend\data\shipping_notice\freight_rpa"
$env:HXOPS_API_BASE = "http://127.0.0.1:5052"
# 由受控 Secret 渠道注入;禁止在此处粘贴真实值。
$env:SHIPPING_NOTICE_TOOL_API_KEY = "<本地 Tool API Key>"
$env:SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = "<本地 RPA 凭据主密钥>"
$env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "dev"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge"
$env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory_triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaDataRoot "inventory_drop"
$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaDataRoot "upload_triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "upload_queue"
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "browser_profile"
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "logs\worker.log"
python scripts\rpa\freight_rpa_worker.py
```
启动成功后,控制台会输出 `[freight_rpa_worker] started`,并持续轮询 trigger。另开一个 PowerShell 可检查日志和哨兵;本地未配置 shared scope 时不要求哨兵包含 test/prod scope:
```powershell
Get-Content "$rpaDataRoot\logs\worker.log" -Tail 100 -Wait
Get-ChildItem "$rpaDataRoot\inventory_triggers"
Get-ChildItem "$rpaDataRoot\inventory_drop"
```
在管理端发起一次测试导出,确认 trigger 被处理并且结果文件进入 `inventory_drop`。结束本地测试时,在运行 Worker 的窗口按 `Ctrl+C`;该方式只停止当前前台进程,不会修改用户级环境变量或创建自启动任务。
##### 1.5.13.2 Linux 测试服务器:部署、启动与停止
以下操作在**测试服务器的项目根目录**执行。首次部署按 `1.5.6` 至 `1.5.9` 完成 Windows 测试共享 `hxops-rpa-test-data` 的访问、`/mnt/hxops-rpa-test-data` 挂载及 `.env.test` 配置;不应使用正式共享目录。启动前确认 `docker-compose.yml` 的 `hxops-backend` 已 bind mount 测试目录到同一路径,否则宿主机虽已挂载,容器内仍无法写入 trigger 或读取导出文件。
```yaml
volumes:
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
```
确认挂载、设置 Compose 环境文件并启动后端及知识库 Worker:
```bash
mountpoint -q /mnt/hxops-rpa-test-data
test -d /mnt/hxops-rpa-test-data/inventory_triggers
export COMPOSE_ENV_BASENAME=.env.test
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
docker compose --env-file .env.test up -d hxops-backend hxops-kb-worker
docker compose --env-file .env.test ps
docker compose --env-file .env.test exec -T hxops-backend \
sh -lc 'test -d /mnt/hxops-rpa-test-data/inventory_triggers && ls -ld /mnt/hxops-rpa-test-data/inventory_triggers'
```
随后在 Windows RPA 主机按 `1.5.5` 的 test 参数启动 Worker(`C:\HxopsRpaTest`、`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT=test`、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-test-data`)。确认 Windows 和 Linux 均能看到 `.hxops_rpa_shared_mount`,并在管理端的 RPA Worker 状态页确认 test Worker 在线后,再发起库存站点测试导出。
需要停止测试环境的 RPA 服务时,先停止/取消新的测试导出,再在 Windows Worker 前台窗口按 `Ctrl+C`(或停止其既有计划任务),最后执行:
```bash
export COMPOSE_ENV_BASENAME=.env.test
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
docker compose --env-file .env.test stop hxops-kb-worker hxops-backend
```
若仅停止 RPA 导出而保留 HXOPS 测试环境对外可用,只需停止 Windows test Worker;不要卸载 SMB 挂载或停止后端容器。
##### 1.5.13.3 Linux 正式服务器:部署、启动与停止
正式环境步骤与测试环境相同,但全部路径、scope、Windows Worker、API Base 和密钥必须是正式环境值。首次部署按 `1.5.6` 至 `1.5.9` 配置 Windows 正式共享 `hxops-rpa-prod-data` 和 `/mnt/hxops-rpa-prod-data`;仅在测试导出、账号、文件结构和回调均验收后才开启正式 RPA。启动前确认 `docker-compose.yml` 的 `hxops-backend` 具有正式共享的 bind mount:
```yaml
volumes:
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
```
在正式服务器项目根目录执行:
```bash
mountpoint -q /mnt/hxops-rpa-prod-data
test -d /mnt/hxops-rpa-prod-data/inventory_triggers
export COMPOSE_ENV_BASENAME=.env.prod
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
docker compose --env-file .env.prod up -d hxops-backend hxops-kb-worker
docker compose --env-file .env.prod ps
docker compose --env-file .env.prod exec -T hxops-backend \
sh -lc 'test -d /mnt/hxops-rpa-prod-data/inventory_triggers && ls -ld /mnt/hxops-rpa-prod-data/inventory_triggers'
```
再在 Windows RPA 主机启动正式 Worker:`C:\HxopsRpaProd`、`SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT=prod`、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data`。必须先验证哨兵内容、管理端 Worker 在线状态以及一笔受控正式导出,才允许启用正式排程。正式上传 RPA 尚未完成时,继续保持 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`。
计划维护或紧急停止时,先暂停正式库存 RPA 排程并等待/处理运行中的 trigger,再停止 Windows prod Worker,最后按需停止容器:
```bash
export COMPOSE_ENV_BASENAME=.env.prod
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
docker compose --env-file .env.prod stop hxops-kb-worker hxops-backend
```
恢复顺序为:确认 SMB 挂载正常 → 启动 Linux 后端与知识库 Worker → 启动 Windows prod Worker → 等待心跳和哨兵 → 管理端确认在线 → 恢复排程。不得通过把测试目录、scope 或密钥复制到正式环境的方式排障。
### 1.6 前端入口 ### 1.6 前端入口
- 聊天界面仍是**主上传入口**,通知附件、库存附件与对话续办都优先在 Chat 完成 - 聊天界面仍是**主上传入口**,通知附件、库存附件与对话续办都优先在 Chat 完成
+3 -3
View File
@@ -80,9 +80,9 @@
| 动态订单字段驱动库存源路由 | 已实现 | 路由条件选择 published 订单稳定 field_id;运行时从 Task 当前 Extraction 的类型化 FieldValue 读取;系统事实仅保留受控枚举 | | 动态订单字段驱动库存源路由 | 已实现 | 路由条件选择 published 订单稳定 field_id;运行时从 Task 当前 Extraction 的类型化 FieldValue 读取;系统事实仅保留受控枚举 |
| 可复用库存解析 Profile | 已实现 | 管理端通过订单字段和库存标准字段结构化选择器版本化维护表头、列映射和 match_keys;多个 published 版本可并存,库存源显式迁移版本;引用中版本不可退役,正常库存源解析无需 LLM | | 可复用库存解析 Profile | 已实现 | 管理端通过订单字段和库存标准字段结构化选择器版本化维护表头、列映射和 match_keys;多个 published 版本可并存,库存源显式迁移版本;引用中版本不可退役,正常库存源解析无需 LLM |
| 库存字段目录 | 已实现 | 作为“库存映射”的子功能以空目录启动,字段名称、说明、格式、用途和顺序完全由用户维护;程序只控制匹配、数量、仓库识别和一般信息四种用途。解析方案、库存行、匹配键和发货模板全程使用库存字段目录 ID;未引用字段可物理删除,当前配置引用字段禁止删除、退役或改变能力用途 | | 库存字段目录 | 已实现 | 作为“库存映射”的子功能以空目录启动,字段名称、说明、格式、用途和顺序完全由用户维护;程序只控制匹配、数量、仓库识别和一般信息四种用途。解析方案、库存行、匹配键和发货模板全程使用库存字段目录 ID;未引用字段可物理删除,当前配置引用字段禁止删除、退役或改变能力用途 |
| 库存样本结构识别与方案复用 | 已实现 | 管理员上传 `.xls/.xlsx/.csv` 后由后端分析工作表、候选表头、真实栏位、少量样例、类型和空值率;同名用户字段可确定性预填,陌生表头由管理员选择或 Dify 给候选,不内置固定业务字段词典;已发布方案按实际使用的匹配/数量表头判断完全一致或兼容,确认只写审计、不自动绑定库存站点 | | 库存样本结构识别与方案复用 | 在建 | 管理员上传 `.xls/.xlsx/.csv` 后由后端分析工作表、候选表头、真实栏位、类型和空值率;样本原件即时分析后清理,草稿/发布版本绑定并保留文件校验值、结构指纹、完整表头和最多五行脱敏样例。再次打开草稿会恢复已保存样本结构、表头下拉和脱敏预览,无需重传原文件;替换样本先展示结构/映射差异,平台确认后才切换,并保留旧/新样本审计链;后续阶段补齐运行闭环;Dify 仅可提供陌生表头候选,不自动生效。 |
| 库存站点测试导出 | 已实现 | 停用库存站点可发起异步 RPA 测试导出;测试文件仅用于结构识别和解析方案确认,不进入正式库存快照、订单匹配或发货导出;只能确认本次推荐的已发布方案,站点配置变更或启用后旧测试自动失效 | | 库存站点测试导出 | 已实现 | 停用库存站点可发起异步 RPA 测试导出;测试文件仅用于结构识别和解析方案确认,不进入正式库存快照、订单匹配或发货导出;只能确认本次推荐的已发布方案,库存站点测试输入或 RPA 连接配置变更后旧测试自动失效,单纯启用/停用不使同配置测试失效 |
| 库存站点启用验证与仓库映射门禁 | 已实现 | 启用前按用户字段用途复核至少一个匹配字段、唯一数量字段及动态仓唯一仓库识别字段,验证发货模板库存字段可由解析方案提供;固定仓要求精确或默认仓库映射,动态仓要求覆盖样例仓库;只提示缺失映射,绝不自动臆造 | | 库存站点启用验证与仓库映射门禁 | 已实现 | 启用前按用户字段用途复核至少一个匹配字段、唯一数量字段及动态仓唯一仓库识别字段,验证发货模板库存字段可由解析方案提供;固定仓要求精确或默认仓库映射,动态仓要求覆盖样例仓库;后端以结构化 `activation.checks` 返回状态、阻断、推荐动作与脱敏证据,配置变更后旧测试明确为 `stale`;只提示缺失映射,绝不自动臆造 |
| 正式库存文件结构漂移门禁 | 已实现 | 每次 RPA 正式导出及缓存快照重读均用已绑定库存文件解析方案复核/解析格式、工作表、表头和核心栏位;完全一致放行,非关键栏位变化记录差异后放行,关键变化阻断快照和库存匹配;正式库存站点运行期不再自动猜列或接收 LLM 映射覆盖 | | 正式库存文件结构漂移门禁 | 已实现 | 每次 RPA 正式导出及缓存快照重读均用已绑定库存文件解析方案复核/解析格式、工作表、表头和核心栏位;完全一致放行,非关键栏位变化记录差异后放行,关键变化阻断快照和库存匹配;正式库存站点运行期不再自动猜列或接收 LLM 映射覆盖 |
| 陌生表头 LLM 候选解释(Dify 手工配置) | 已文档化 | 默认关闭;用户明确声明对话附件为库存文件且后端无精确方案时,可对脱敏真实表头给出本次临时候选;管理员也可在库存文件解析方案草稿中主动请求候选。Dify 不能发布方案、绑定库存站点、创建仓库映射、调用旧库存映射 Tool 或放行结构漂移 | | 陌生表头 LLM 候选解释(Dify 手工配置) | 已文档化 | 默认关闭;用户明确声明对话附件为库存文件且后端无精确方案时,可对脱敏真实表头给出本次临时候选;管理员也可在库存文件解析方案草稿中主动请求候选。Dify 不能发布方案、绑定库存站点、创建仓库映射、调用旧库存映射 Tool 或放行结构漂移 |
| 对话临时库存文件受控解析 | 已实现 | 用户上传 `.xls/.xlsx/.csv` 表格时必须先明确声明为库存文件,系统不会按后缀猜测用途;后端创建当前用户和当前聊天会话隔离的临时文件并确定性检查结构与库存最低特征。跨回合时由 HXOPS 数据库恢复最新待确认会话号,不依赖 Dify 隐式记忆;普通消息不会因此自动进入确认。无完全匹配方案时 Dify 只能基于真实表头、类型/空值率和字段目录提交受控候选映射,用户明确确认后仅锁定本次临时质量审计;不创建正式库存快照、不修改库存站点、不执行订单匹配。管理员可将确认会话沉淀为解析方案草稿,仍需走既有发布门禁 | | 对话临时库存文件受控解析 | 已实现 | 用户上传 `.xls/.xlsx/.csv` 表格时必须先明确声明为库存文件,系统不会按后缀猜测用途;后端创建当前用户和当前聊天会话隔离的临时文件并确定性检查结构与库存最低特征。跨回合时由 HXOPS 数据库恢复最新待确认会话号,不依赖 Dify 隐式记忆;普通消息不会因此自动进入确认。无完全匹配方案时 Dify 只能基于真实表头、类型/空值率和字段目录提交受控候选映射,用户明确确认后仅锁定本次临时质量审计;不创建正式库存快照、不修改库存站点、不执行订单匹配。管理员可将确认会话沉淀为解析方案草稿,仍需走既有发布门禁 |
+1 -1
View File
@@ -1167,7 +1167,7 @@ Dify
- **版本化 Excel 模板与 Artifact**:`shipping_excel_templates` 保存私有 MinIO `bucket/key`、模板文件校验和及字段映射发布版本,`shipping_inventory_sources.excel_template_id` 决定新任务使用的模板;`shipping_export_artifacts` 保存每次生成文件及所锁定的 Schema、Extraction、库存解析 Profile、库存快照、输入/文件 checksum。导出运行时从 MinIO读取模板,不读取全局模板环境变量,也不回退空白工作簿。 - **版本化 Excel 模板与 Artifact**:`shipping_excel_templates` 保存私有 MinIO `bucket/key`、模板文件校验和及字段映射发布版本,`shipping_inventory_sources.excel_template_id` 决定新任务使用的模板;`shipping_export_artifacts` 保存每次生成文件及所锁定的 Schema、Extraction、库存解析 Profile、库存快照、输入/文件 checksum。导出运行时从 MinIO读取模板,不读取全局模板环境变量,也不回退空白工作簿。
- **库存字段目录与确定性订单/库存关联**:库存字段目录独立于 DBS、Crane 和具体库存站点,初始化为空,所有字段由管理员创建。`field_code` 仅作为不展示的审计标识,不参与匹配、解析、仓库识别或导出。解析方案以 `inventory_field_id -> 原始表头` 保存实际列映射,以 `match_keys[].inventory_field_id` 将动态订单 `field_id` 与库存字段关联;库存快照行 JSON、结构兼容指纹和发货模板均直接使用库存字段 ID。字段用途只承担能力角色:至少一个 `match_identity`、恰好一个 `inventory_quantity`,动态仓方案恰好一个 `warehouse_identity`;`general` 字段数量不限。数组顺序和字段名称均不参与匹配,多命中仅在模板所需库存字段值一致时允许合并。 - **库存字段目录与确定性订单/库存关联**:库存字段目录独立于 DBS、Crane 和具体库存站点,初始化为空,所有字段由管理员创建。`field_code` 仅作为不展示的审计标识,不参与匹配、解析、仓库识别或导出。解析方案以 `inventory_field_id -> 原始表头` 保存实际列映射,以 `match_keys[].inventory_field_id` 将动态订单 `field_id` 与库存字段关联;库存快照行 JSON、结构兼容指纹和发货模板均直接使用库存字段 ID。字段用途只承担能力角色:至少一个 `match_identity`、恰好一个 `inventory_quantity`,动态仓方案恰好一个 `warehouse_identity`;`general` 字段数量不限。数组顺序和字段名称均不参与匹配,多命中仅在模板所需库存字段值一致时允许合并。
- **库存站点启用**:库存站点首次保存一律保持停用,普通保存不承担状态切换;启用使用独立 API,后端返回连接、库存文件解析方案、发货模板、测试导出与解析验证及仓库映射等未完成项。数据库 CheckConstraint 继续保证启用站点绑定解析方案和 Excel 模板;测试导出确认记录必须与当前站点配置版本和已绑定方案一致,编辑站点后自动失效。启用时按已绑定方案实际映射的字段用途验证匹配栏位样例非空、唯一数量栏位为数值、发货模板库存字段引用完整和仓库映射覆盖;固定仓允许精确或默认映射,动态仓要求唯一仓库识别字段并覆盖样例仓库。解析方案新发布版本与旧 published 版本并存,站点显式迁移后旧版本方可退役。 - **库存站点启用**:库存站点首次保存一律保持停用,普通保存不承担状态切换;启用使用独立 API,后端返回连接、库存文件解析方案、发货模板、测试导出与解析验证及仓库映射等未完成项。数据库 CheckConstraint 继续保证启用站点绑定解析方案和 Excel 模板;测试导出确认记录必须与当前站点配置版本和已绑定方案一致,编辑站点后自动失效。启用时按已绑定方案实际映射的字段用途验证匹配栏位样例非空、唯一数量栏位为数值、发货模板库存字段引用完整和仓库映射覆盖;固定仓允许精确或默认映射,动态仓要求唯一仓库识别字段并覆盖样例仓库。解析方案新发布版本与旧 published 版本并存,站点显式迁移后旧版本方可退役。
- **库存样本结构分析**:`shipping_inventory_structure_analyses` 保存受控库存样本的文件 checksum、工作表/候选表头、来源栏位、少量样例、类型/空值统计和规则建议,不保存正式库存明细。`POST /api/admin/shipping-notice/inventory-structure-analyses` 由后端校验实际 `.xls` / `.xlsx` / `.csv` 后生成分析;创建解析方案草稿时,工作表、表头和来源栏位必须来自该分析记录。 - **库存样本结构分析**:`shipping_inventory_structure_analyses` 保存受控库存样本的文件名、checksum、工作表/候选表头、来源栏位、类型/空值统计、结构指纹和最多五行脱敏样例,不保存完整样本文件或正式库存明细。管理端样本与配置测试文件只在即时分析期间落盘,分析完成即清理;仅对话临时库存会话可在其短期确认窗口保留受控原件。`ShippingInventoryParsingProfile.sample_analysis_id` 锁定草稿/发布版本的样本证据;创建、保存和发布均要求工作表、表头和来源栏位来自该分析记录。
- **对话临时库存文件**:用户在货代对话上传 `.xls` / `.xlsx` / `.csv` 表格后,系统先保留附件,只有用户明确声明其为库存文件才创建 `FileAsset -> shipping_temporary_inventory_sessions` 短生命周期会话;绝不依据后缀猜测库存或订单。会话同时绑定 `user_id + conversation_id + asset_id`,以 `source_kind=temporary_conversation` 保存结构审计。后端只向 Dify 返回不含样例库存值的结构预览与规则建议;不创建 `shipping_inventory_files`、不写任务库存关联、不绑定库存站点。跨聊天回合时,HXOPS 从数据库恢复当前会话最新、未过期且仍待确认的临时会话号,但不会自动路由或确认;Dify 只有识别到用户明确确认本次临时使用时,才可调用确认 Tool。所有 Tool 输出先按 `text` JSON 标准化,不能依赖 Dify 隐式会话记忆或假定的 Tool 顶层字段。Dify 仅可调用创建、读取、提交候选映射和经用户明确确认后的临时使用 Tool,不能读取二进制、路径、样例值、全量行或直接宣布库存可用于匹配。已确认会话可由管理员沉淀为解析方案草稿,但不能自动发布或绑定库存站点。 - **对话临时库存文件**:用户在货代对话上传 `.xls` / `.xlsx` / `.csv` 表格后,系统先保留附件,只有用户明确声明其为库存文件才创建 `FileAsset -> shipping_temporary_inventory_sessions` 短生命周期会话;绝不依据后缀猜测库存或订单。会话同时绑定 `user_id + conversation_id + asset_id`,以 `source_kind=temporary_conversation` 保存结构审计。后端只向 Dify 返回不含样例库存值的结构预览与规则建议;不创建 `shipping_inventory_files`、不写任务库存关联、不绑定库存站点。跨聊天回合时,HXOPS 从数据库恢复当前会话最新、未过期且仍待确认的临时会话号,但不会自动路由或确认;Dify 只有识别到用户明确确认本次临时使用时,才可调用确认 Tool。所有 Tool 输出先按 `text` JSON 标准化,不能依赖 Dify 隐式会话记忆或假定的 Tool 顶层字段。Dify 仅可调用创建、读取、提交候选映射和经用户明确确认后的临时使用 Tool,不能读取二进制、路径、样例值、全量行或直接宣布库存可用于匹配。已确认会话可由管理员沉淀为解析方案草稿,但不能自动发布或绑定库存站点。
- **方案复用**:结构分析与解析方案分别保存精确结构指纹和兼容指纹,均不包含库存业务数据或文件名。精确指纹覆盖格式、工作表、表头行、标准化列名及顺序;兼容判断验证既有方案实际使用的库存匹配与数量来源表头仍存在,并输出新增/缺少/顺序变化。后端不使用固定字段词典把“内部料号”猜成 `Supplier Sku`;仅当用户字段显示名称与真实表头标准化后完全相同时给出确定性预填,其他情况由管理员选择或 Dify 提供候选。管理员确认复用只写分析审计,不更新库存站点绑定。 - **方案复用**:结构分析与解析方案分别保存精确结构指纹和兼容指纹,均不包含库存业务数据或文件名。精确指纹覆盖格式、工作表、表头行、标准化列名及顺序;兼容判断验证既有方案实际使用的库存匹配与数量来源表头仍存在,并输出新增/缺少/顺序变化。后端不使用固定字段词典把“内部料号”猜成 `Supplier Sku`;仅当用户字段显示名称与真实表头标准化后完全相同时给出确定性预填,其他情况由管理员选择或 Dify 提供候选。管理员确认复用只写分析审计,不更新库存站点绑定。
- **库存站点测试导出**:`shipping_inventory_configuration_test_runs` 保存专用 `configuration_test` RPA run、来源配置版本、分析记录和确认结果。测试回调走 `/api/shipping-notice/rpa/inventory-configuration-test-ready`,只创建 `source_kind=configuration_test` 的结构分析,不创建 `shipping_inventory_files`。确认方案时要求站点仍停用且配置版本未变化,成功后绑定解析方案并使测试记录追随新的配置版本;后续编辑站点自动使旧测试失效。 - **库存站点测试导出**:`shipping_inventory_configuration_test_runs` 保存专用 `configuration_test` RPA run、来源配置版本、分析记录和确认结果。测试回调走 `/api/shipping-notice/rpa/inventory-configuration-test-ready`,只创建 `source_kind=configuration_test` 的结构分析,不创建 `shipping_inventory_files`。确认方案时要求站点仍停用且配置版本未变化,成功后绑定解析方案并使测试记录追随新的配置版本;后续编辑站点自动使旧测试失效。
+43 -2
View File
@@ -21,6 +21,38 @@ import type {
const auth = () => ({ headers: getAuthHeaders() }); const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } }); const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
export type ShippingInventoryReadinessCheck = {
code: string;
status: 'passed' | 'pending' | 'failed' | 'stale';
blocking: boolean;
action: 'configure_connection' | 'configure_parsing_profile' | 'configure_excel_template' | 'configure_warehouse_mapping' | 'run_configuration_test';
evidence: Record<string, unknown>;
};
export type ShippingInventoryReadiness = {
ready: boolean;
checks: ShippingInventoryReadinessCheck[];
missing_requirements: string[];
};
export type ShippingInventoryConfigurationTest = {
run_no: string;
source_config_version: number;
rpa_profile_config_version: number;
status: 'awaiting_rpa' | 'processing' | 'completed' | 'failed';
stage: string;
error_message?: string | null;
created_at?: string | null;
completed_at?: string | null;
result?: {
analysis?: {
match_result?: {
candidates?: Array<{ profile_id: number; display_name: string; version: number; level: string }>;
};
};
};
};
/** 下载管理员可访问的库存快照,并保留服务端指定的原始文件名。 */ /** 下载管理员可访问的库存快照,并保留服务端指定的原始文件名。 */
export const downloadShippingInventorySnapshot = async (snapshotId: number, fallbackName: string): Promise<void> => { export const downloadShippingInventorySnapshot = async (snapshotId: number, fallbackName: string): Promise<void> => {
const response = await fetch(`/api/admin/shipping-notice/snapshots/${snapshotId}/download`, { headers: getAuthHeaders() }); const response = await fetch(`/api/admin/shipping-notice/snapshots/${snapshotId}/download`, { headers: getAuthHeaders() });
@@ -150,6 +182,11 @@ export const createShippingInventoryParsingDraftFromAnalysis = (id: number, payl
`/api/admin/shipping-notice/inventory-structure-analyses/${id}/create-profile-draft`, `/api/admin/shipping-notice/inventory-structure-analyses/${id}/create-profile-draft`,
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
); );
/** 样本替换先读取后端结构差异;管理员确认前不会改动草稿的审计证据。 */
export const previewShippingInventorySampleReplacement = (profileId: number, analysisId: number, payload: Record<string, unknown> = {}) => requestJson<unknown>(
`/api/admin/shipping-notice/parsing-profiles/${profileId}/sample-replacement-preview/${analysisId}`,
{ method: 'POST', body: JSON.stringify(payload), ...jsonAuth() },
);
/** 确认复用后端推荐的已发布解析方案;库存站点绑定仍由后续测试流程确认。 */ /** 确认复用后端推荐的已发布解析方案;库存站点绑定仍由后续测试流程确认。 */
export const adoptShippingInventoryParsingProfile = (analysisId: number, profileId: number) => requestJson<unknown>( export const adoptShippingInventoryParsingProfile = (analysisId: number, profileId: number) => requestJson<unknown>(
`/api/admin/shipping-notice/inventory-structure-analyses/${analysisId}/adopt-profile`, `/api/admin/shipping-notice/inventory-structure-analyses/${analysisId}/adopt-profile`,
@@ -191,13 +228,17 @@ export const deactivateShippingInventorySource = (id: number) => requestJson<unk
`/api/admin/shipping-notice/sources/${id}/deactivate`, { method: 'POST', ...jsonAuth() }, `/api/admin/shipping-notice/sources/${id}/deactivate`, { method: 'POST', ...jsonAuth() },
); );
/** 对停用库存站点发起异步 RPA 测试导出,测试文件不会进入生产库存池。 */ /** 对停用库存站点发起异步 RPA 测试导出,测试文件不会进入生产库存池。 */
export const startShippingInventoryConfigurationTest = (id: number) => requestJson<any>( export const startShippingInventoryConfigurationTest = (id: number) => requestJson<ShippingInventoryConfigurationTest>(
`/api/admin/shipping-notice/sources/${id}/test-export`, { method: 'POST', ...jsonAuth() }, `/api/admin/shipping-notice/sources/${id}/test-export`, { method: 'POST', ...jsonAuth() },
); );
/** 查询库存站点测试导出与结构识别的后端真实状态。 */ /** 查询库存站点测试导出与结构识别的后端真实状态。 */
export const getShippingInventoryConfigurationTest = (id: number, runNo: string) => requestJson<any>( export const getShippingInventoryConfigurationTest = (id: number, runNo: string) => requestJson<ShippingInventoryConfigurationTest>(
`/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}`, auth(), `/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}`, auth(),
); );
/** 读取当前站点配置对应的最近测试,使刷新页面或重开抽屉时可恢复服务端真实状态。 */
export const getLatestShippingInventoryConfigurationTest = (id: number) => requestJson<ShippingInventoryConfigurationTest | null>(
`/api/admin/shipping-notice/sources/${id}/test-export/latest`, auth(),
);
/** 管理员确认测试结果使用的已发布解析方案,才更新停用库存站点绑定。 */ /** 管理员确认测试结果使用的已发布解析方案,才更新停用库存站点绑定。 */
export const confirmShippingInventoryConfigurationTestProfile = (id: number, runNo: string, profileId: number) => requestJson<any>( export const confirmShippingInventoryConfigurationTestProfile = (id: number, runNo: string, profileId: number) => requestJson<any>(
`/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}/confirm-profile`, `/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}/confirm-profile`,
@@ -138,27 +138,50 @@
<label><span>{{ t('admin.shippingInventory.warehouseResolution') }}</span><select v-model="source.warehouse_resolution_mode"><option value="fixed">{{ t('admin.shippingInventory.fixedWarehouse') }}</option><option value="inventory_match">{{ t('admin.shippingInventory.inventoryMatch') }}</option></select></label> <label><span>{{ t('admin.shippingInventory.warehouseResolution') }}</span><select v-model="source.warehouse_resolution_mode"><option value="fixed">{{ t('admin.shippingInventory.fixedWarehouse') }}</option><option value="inventory_match">{{ t('admin.shippingInventory.inventoryMatch') }}</option></select></label>
<label v-if="source.warehouse_resolution_mode === 'fixed'"><span>{{ t('admin.shippingInventory.warehouse') }}</span><input v-model="source.fixed_warehouse_id" required></label> <label v-if="source.warehouse_resolution_mode === 'fixed'"><span>{{ t('admin.shippingInventory.warehouse') }}</span><input v-model="source.fixed_warehouse_id" required></label>
<label><span>{{ t('admin.shippingInventory.snapshotTtl') }}</span><input v-model.number="source.snapshot_ttl_seconds" min="1" type="number" required></label> <label><span>{{ t('admin.shippingInventory.snapshotTtl') }}</span><input v-model.number="source.snapshot_ttl_seconds" min="1" type="number" required></label>
<section v-if="selectedId" class="activation-panel full"> <section v-if="selectedId" class="readiness-card full" :class="{ ready: source.enabled }">
<strong>{{ t('admin.shippingInventory.activationStatus') }}</strong> <header class="readiness-heading">
<p>{{ source.enabled ? t('admin.shippingInventory.activationReady') : t('admin.shippingInventory.activationDraft') }}</p> <div>
<ul v-if="source.activation?.missing_requirements?.length"> <span class="readiness-kicker">{{ t('admin.shippingInventory.activationStatus') }}</span>
<li v-for="requirement in source.activation.missing_requirements" :key="requirement">{{ t(`admin.shippingInventory.activationRequirement.${requirement}`) }}</li> <strong>{{ source.enabled ? t('admin.shippingInventory.activationReady') : t('admin.shippingInventory.activationDraft') }}</strong>
</ul> </div>
<button v-if="!source.enabled" type="button" class="secondary-action" @click="requestSourceActivation">{{ t('admin.shippingInventory.activateSource') }}</button> <span class="readiness-count">{{ readinessSummary }}</span>
<button v-else type="button" class="secondary-action" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button> </header>
</section> <ol class="readiness-steps">
<section v-if="selectedId && !source.enabled" class="activation-panel full"> <li v-for="check in readinessChecks" :key="check.code" :class="`is-${check.status}`">
<strong>{{ t('admin.shippingInventory.configurationTest') }}</strong> <span class="readiness-marker" aria-hidden="true">{{ readinessMarker(check.status) }}</span>
<p>{{ t('admin.shippingInventory.configurationTestHint') }}</p> <div class="readiness-copy">
<button type="button" class="secondary-action" :disabled="configurationTestLoading" @click="startConfigurationTest">{{ configurationTestLoading ? t('admin.shippingInventory.configurationTestRunning') : t('admin.shippingInventory.startConfigurationTest') }}</button> <b>{{ t(`admin.shippingInventory.activationRequirement.${check.code}`) }}</b>
<small>{{ readinessDetail(check) }}</small>
</div>
<button
v-if="readinessActionLabel(check) && !source.enabled"
type="button"
class="readiness-action"
:disabled="isReadinessActionBlocked(check)"
:title="isReadinessActionBlocked(check) ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined"
@click="runReadinessAction(check)"
>{{ readinessActionLabel(check) }}</button>
</li>
</ol>
<p v-if="!source.enabled" class="readiness-note">{{ t('admin.shippingInventory.configurationTestHint') }}</p>
<template v-if="configurationTest"> <template v-if="configurationTest">
<p>{{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</p> <p class="readiness-run" :class="{ failed: configurationTest.status === 'failed' }">{{ t(`admin.shippingInventory.configurationTestStage.${configurationTest.stage}`) }}</p>
<dl class="readiness-audit">
<div><dt>{{ t('admin.shippingInventory.configurationTestRunNo') }}</dt><dd>{{ configurationTest.run_no }}</dd></div>
<div><dt>{{ t('admin.shippingInventory.configurationTestConfigVersion') }}</dt><dd>{{ configurationTest.source_config_version }}</dd></div>
<div><dt>{{ t('admin.shippingInventory.configurationTestConnectionVersion') }}</dt><dd>{{ configurationTest.rpa_profile_config_version }}</dd></div>
<div><dt>{{ t('admin.shippingInventory.configurationTestUpdatedAt') }}</dt><dd>{{ formatDate(configurationTest.completed_at || configurationTest.created_at) }}</dd></div>
</dl>
<p v-if="configurationTest.error_message" class="form-tip">{{ configurationTest.error_message }}</p> <p v-if="configurationTest.error_message" class="form-tip">{{ configurationTest.error_message }}</p>
<section v-if="configurationTest.status === 'completed'" class="recommendation-list"> <section v-if="configurationTest.status === 'completed'" class="recommendation-list">
<article v-for="candidate in configurationTest.result?.analysis?.match_result?.candidates || []" :key="candidate.profile_id"><b>{{ candidate.display_name }} V{{ candidate.version }}</b><small>{{ t(`admin.shippingInventory.recommendationLevel.${candidate.level}`) }}</small><button type="button" class="secondary-action" @click="confirmTestProfile(candidate.profile_id)">{{ t('admin.shippingInventory.confirmTestProfile') }}</button></article> <article v-for="candidate in configurationTest.result?.analysis?.match_result?.candidates || []" :key="candidate.profile_id"><b>{{ candidate.display_name }} V{{ candidate.version }}</b><small>{{ t(`admin.shippingInventory.recommendationLevel.${candidate.level}`) }}</small><button type="button" class="secondary-action" @click="confirmTestProfile(candidate.profile_id)">{{ t('admin.shippingInventory.confirmTestProfile') }}</button></article>
<p v-if="!(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p> <p v-if="!(configurationTest.result?.analysis?.match_result?.candidates || []).length">{{ t('admin.shippingInventory.configurationTestNoRecommendation') }}</p>
</section> </section>
</template> </template>
<footer class="readiness-footer">
<button v-if="!source.enabled" type="button" class="primary-action" :disabled="!source.activation?.ready || sourceDirty" :title="sourceDirty ? t('admin.shippingInventory.saveBeforeReadinessAction') : undefined" @click="requestSourceActivation">{{ t('admin.shippingInventory.activateSource') }}</button>
<button v-else type="button" class="text-action danger" @click="requestSourceDeactivation">{{ t('admin.shippingInventory.deactivateSource') }}</button>
</footer>
</section> </section>
<div v-if="!selectedId" class="form-tip full">{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}</div> <div v-if="!selectedId" class="form-tip full">{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}</div>
<template v-if="source.connector_type === 'dbs'"> <template v-if="source.connector_type === 'dbs'">
@@ -217,7 +240,20 @@
<label><span>{{ t('admin.shippingInventory.fileFormat') }}</span><select v-model="parsing.file_format"><option value="xls">xls</option><option value="xlsx">xlsx</option><option value="csv">csv</option></select></label> <label><span>{{ t('admin.shippingInventory.fileFormat') }}</span><select v-model="parsing.file_format"><option value="xls">xls</option><option value="xlsx">xlsx</option><option value="csv">csv</option></select></label>
<label v-if="!selectedId" class="full"><span>{{ t('admin.shippingInventory.temporaryInventorySession') }}</span><select v-model="selectedTemporaryInventorySession" @change="loadTemporaryInventorySession"><option value="">{{ t('admin.shippingInventory.temporaryInventorySessionNone') }}</option><option v-for="item in temporaryInventorySessions" :key="item.session_no" :value="item.session_no">{{ item.source_file_name }} · {{ item.session_no }}</option></select><small>{{ t('admin.shippingInventory.temporaryInventorySessionHint') }}</small></label> <label v-if="!selectedId" class="full"><span>{{ t('admin.shippingInventory.temporaryInventorySession') }}</span><select v-model="selectedTemporaryInventorySession" @change="loadTemporaryInventorySession"><option value="">{{ t('admin.shippingInventory.temporaryInventorySessionNone') }}</option><option v-for="item in temporaryInventorySessions" :key="item.session_no" :value="item.session_no">{{ item.source_file_name }} · {{ item.session_no }}</option></select><small>{{ t('admin.shippingInventory.temporaryInventorySessionHint') }}</small></label>
<div v-if="temporaryInventorySessionSelected" class="form-tip full">{{ t('admin.shippingInventory.temporaryInventorySessionSelected', { mapping: temporaryInventorySessionSelected.confirmed_usage?.mapping_origin || '-' }) }}</div> <div v-if="temporaryInventorySessionSelected" class="form-tip full">{{ t('admin.shippingInventory.temporaryInventorySessionSelected', { mapping: temporaryInventorySessionSelected.confirmed_usage?.mapping_origin || '-' }) }}</div>
<label class="full"><span>{{ t('admin.shippingInventory.inventorySampleFile') }}</span><input type="file" accept=".xls,.xlsx,.csv" :disabled="analysisLoading || Boolean(temporaryInventorySessionSelected)" @change="analyseInventorySample"><small>{{ t('admin.shippingInventory.inventorySampleFileHint') }}</small></label> <label v-if="!selectedId" class="full"><span>{{ t('admin.shippingInventory.inventorySampleFile') }}</span><input type="file" accept=".xls,.xlsx,.csv" :disabled="analysisLoading || Boolean(temporaryInventorySessionSelected)" @change="analyseInventorySample"><small>{{ t('admin.shippingInventory.inventorySampleFileHint') }}</small></label>
<section v-else-if="structureAnalysis" class="sample-evidence-card full">
<div>
<strong>{{ pendingSampleReplacement ? t('admin.shippingInventory.pendingInventorySampleReplacement') : t('admin.shippingInventory.savedInventorySample') }}</strong>
<p>{{ pendingSampleReplacement ? t('admin.shippingInventory.pendingInventorySampleReplacementHint') : t('admin.shippingInventory.savedInventorySampleHint') }}</p>
</div>
<dl>
<div><dt>{{ t('admin.shippingInventory.sampleFileName') }}</dt><dd>{{ structureAnalysis.source_file_name || '-' }}</dd></div>
<div><dt>{{ t('admin.shippingInventory.fileFormat') }}</dt><dd>{{ String(structureAnalysis.file_format || parsing.file_format).toUpperCase() }}</dd></div>
<div><dt>{{ t('admin.shippingInventory.sampleRowsRetained') }}</dt><dd>{{ structureAnalysis.sample_rows?.length || 0 }}</dd></div>
</dl>
<label class="sample-replacement-input"><span>{{ t('admin.shippingInventory.replaceInventorySample') }}</span><input type="file" accept=".xls,.xlsx,.csv" :disabled="analysisLoading" @change="analyseInventorySample"><small>{{ t('admin.shippingInventory.replaceInventorySampleHint') }}</small></label>
<div v-if="pendingSampleReplacement" class="sample-replacement-warning"><p>{{ sampleReplacementNotice }}</p><ul><li v-for="line in sampleReplacementDifferenceLines" :key="line">{{ line }}</li></ul></div>
</section>
<div v-if="analysisLoading" class="form-tip full">{{ t('admin.shippingInventory.inventorySampleAnalysing') }}</div> <div v-if="analysisLoading" class="form-tip full">{{ t('admin.shippingInventory.inventorySampleAnalysing') }}</div>
<template v-if="structureAnalysis"> <template v-if="structureAnalysis">
<label><span>{{ t('admin.shippingInventory.sheetName') }}</span><select v-model="parsing.sheet_name" @change="applyAnalysisCandidate"><option v-for="candidate in analysisCandidates" :key="candidateKey(candidate)" :value="candidate.sheet_name || ''">{{ candidate.sheet_name || t('admin.shippingInventory.csvFile') }}</option></select></label> <label><span>{{ t('admin.shippingInventory.sheetName') }}</span><select v-model="parsing.sheet_name" @change="applyAnalysisCandidate"><option v-for="candidate in analysisCandidates" :key="candidateKey(candidate)" :value="candidate.sheet_name || ''">{{ candidate.sheet_name || t('admin.shippingInventory.csvFile') }}</option></select></label>
@@ -383,11 +419,13 @@ import {
getShippingExcelTemplateLayout, getShippingExcelTemplateLayout,
createShippingInventoryStructureAnalysis, createShippingInventoryStructureAnalysis,
createShippingInventoryParsingDraftFromAnalysis, createShippingInventoryParsingDraftFromAnalysis,
previewShippingInventorySampleReplacement,
createShippingParsingDraftFromTemporarySession, createShippingParsingDraftFromTemporarySession,
adoptShippingInventoryParsingProfile, adoptShippingInventoryParsingProfile,
listShippingTemporaryInventorySessions, listShippingTemporaryInventorySessions,
startShippingInventoryConfigurationTest, startShippingInventoryConfigurationTest,
getShippingInventoryConfigurationTest, getShippingInventoryConfigurationTest,
getLatestShippingInventoryConfigurationTest,
confirmShippingInventoryConfigurationTestProfile, confirmShippingInventoryConfigurationTestProfile,
downloadShippingInventorySnapshot, downloadShippingInventorySnapshot,
updateShippingExcelTemplate, updateShippingExcelTemplate,
@@ -404,6 +442,8 @@ import {
saveShippingInventorySource, saveShippingInventorySource,
saveShippingRpaProfile, saveShippingRpaProfile,
} from '@/features/admin/api/admin.api'; } from '@/features/admin/api/admin.api';
import type { ShippingInventoryConfigurationTest, ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api';
import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingInventoryReadiness';
type TabKey = 'orderSchema' | 'profiles' | 'parsing' | 'inventoryFields' | 'templates' | 'sources' | 'rules' | 'snapshots' | 'exports' | 'mappings'; type TabKey = 'orderSchema' | 'profiles' | 'parsing' | 'inventoryFields' | 'templates' | 'sources' | 'rules' | 'snapshots' | 'exports' | 'mappings';
type Item = Record<string, any>; type Item = Record<string, any>;
@@ -413,6 +453,7 @@ type ParsingFieldMapping = { inventory_field: string; source_header: string };
type ParsingMatchKey = { order_field_id: string; inventory_field: string }; type ParsingMatchKey = { order_field_id: string; inventory_field: string };
type TemplateMapping = { sheet: string; row_mode: 'header' | 'line'; start_row: number; target_column: number; source_kind: 'order_field' | 'inventory_field' | 'system_fact' | 'constant'; source_key: string; formatter: string }; type TemplateMapping = { sheet: string; row_mode: 'header' | 'line'; start_row: number; target_column: number; source_kind: 'order_field' | 'inventory_field' | 'system_fact' | 'constant'; source_key: string; formatter: string };
type InventoryFieldForm = { display_name: string; description: string; value_type: 'text' | 'integer' | 'decimal' | 'date'; usage_type: 'match_identity' | 'inventory_quantity' | 'warehouse_identity' | 'general'; sort_order: number; status: 'active' | 'retired' }; type InventoryFieldForm = { display_name: string; description: string; value_type: 'text' | 'integer' | 'decimal' | 'date'; usage_type: 'match_identity' | 'inventory_quantity' | 'warehouse_identity' | 'general'; sort_order: number; status: 'active' | 'retired' };
type SourceActivation = { ready: boolean; checks: ShippingInventoryReadinessCheck[]; missing_requirements: string[] };
const { t } = useI18n(); const { t } = useI18n();
const message = useMessage(); const message = useMessage();
@@ -423,7 +464,7 @@ const orderSchemaPublished = ref(false);
const saving = ref(false); const saving = ref(false);
const confirmation = reactive({ const confirmation = reactive({
visible: false, visible: false,
action: '' as 'delete' | 'retireRule' | 'retireTemplate' | 'retireParsing' | 'retireInventoryField' | 'activateSource' | 'deactivateSource' | '', action: '' as 'delete' | 'retireRule' | 'retireTemplate' | 'retireParsing' | 'retireInventoryField' | 'activateSource' | 'deactivateSource' | 'replaceInventorySample' | '',
title: '', title: '',
message: '', message: '',
confirmText: '', confirmText: '',
@@ -444,11 +485,13 @@ const auditDetail = ref<{ kind: 'snapshot' | 'export'; item: Item } | null>(null
const parsingProfiles = ref<Item[]>([]); const parsingProfiles = ref<Item[]>([]);
const inventoryFields = ref<Item[]>([]); const inventoryFields = ref<Item[]>([]);
const structureAnalysis = ref<Item | null>(null); const structureAnalysis = ref<Item | null>(null);
const pendingSampleReplacement = ref<Item | null>(null);
const sampleReplacementConfirmed = ref(false);
const temporaryInventorySessions = ref<Item[]>([]); const temporaryInventorySessions = ref<Item[]>([]);
const selectedTemporaryInventorySession = ref(''); const selectedTemporaryInventorySession = ref('');
const analysisLoading = ref(false); const analysisLoading = ref(false);
const excelTemplates = ref<Item[]>([]); const excelTemplates = ref<Item[]>([]);
const configurationTest = ref<Item | null>(null); const configurationTest = ref<ShippingInventoryConfigurationTest | null>(null);
const configurationTestLoading = ref(false); const configurationTestLoading = ref(false);
let configurationTestTimer: number | null = null; let configurationTestTimer: number | null = null;
const routingFields = ref<Array<{ field_id: string; field_code: string; display_name: string; description?: string; scope: 'header' | 'line' }>>([]); const routingFields = ref<Array<{ field_id: string; field_code: string; display_name: string; description?: string; scope: 'header' | 'line' }>>([]);
@@ -482,7 +525,8 @@ const profile = reactive({ profile_code: '', display_name: '', connector_type: '
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 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 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 }); const excelTemplate = reactive({ template_code: '', display_name: '', filename_pattern: '{business_no}.xlsx', mappings: [] as TemplateMapping[], file: null as File | null });
const source = reactive({ source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [] as Parameter[], match_aliases_json: [] as string[], enabled: false, activation: { ready: false, missing_requirements: [] as string[] } }); const source = reactive({ source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [] as Parameter[], match_aliases_json: [] as string[], enabled: false, activation: { ready: false, checks: [] as ShippingInventoryReadinessCheck[], missing_requirements: [] as string[] } as SourceActivation });
const sourceBaseline = ref('');
const rule = reactive({ rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', system_fact_key: '', operator: 'prefix', expected: '' }] as RuleCondition[], source_codes: [] as string[] }); const rule = reactive({ rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', system_fact_key: '', operator: 'prefix', expected: '' }] as RuleCondition[], source_codes: [] as string[] });
const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true }); const mapping = reactive({ inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
const compatibleRoutingFields = computed(() => routingFields.value.filter((item) => item.scope === (rule.scope === 'task' ? 'header' : 'line'))); const compatibleRoutingFields = computed(() => routingFields.value.filter((item) => item.scope === (rule.scope === 'task' ? 'header' : 'line')));
@@ -498,6 +542,29 @@ const matchingOrderFields = computed(() => routingFields.value.filter((field) =>
const canAddParsingMatchKey = computed(() => Boolean( const canAddParsingMatchKey = computed(() => Boolean(
structureAnalysis.value && unusedMatchingInventoryFields.value.length && unusedOrderMatchFields.value.length, structureAnalysis.value && unusedMatchingInventoryFields.value.length && unusedOrderMatchFields.value.length,
)); ));
const sourceDirty = computed(() => Boolean(selectedId.value && sourceBaseline.value && sourceBaseline.value !== serialiseSourceInput()));
const readinessChecks = computed<ShippingInventoryReadinessCheck[]>(() => source.activation?.checks || []);
const readinessSummary = computed(() => {
const total = readinessChecks.value.length;
const passed = readinessChecks.value.filter((item) => item.status === 'passed').length;
return t('admin.shippingInventory.readinessProgress', { passed, total });
});
const sampleReplacementNotice = computed(() => {
const difference = pendingSampleReplacement.value?.difference || {};
const missing = Array.isArray(difference.missing_mapped_headers) ? difference.missing_mapped_headers : [];
if (difference.file_format_changed) return t('admin.shippingInventory.sampleReplacementFileFormatChanged');
return missing.length
? t('admin.shippingInventory.sampleReplacementMappingRequired', { columns: missing.join('、') })
: t('admin.shippingInventory.sampleReplacementReady');
});
const sampleReplacementDifferenceLines = computed(() => {
const difference = pendingSampleReplacement.value?.difference || {};
const lines: string[] = [];
if (Array.isArray(difference.added_columns) && difference.added_columns.length) lines.push(t('admin.shippingInventory.sampleReplacementAddedColumns', { columns: difference.added_columns.join('、') }));
if (Array.isArray(difference.missing_columns) && difference.missing_columns.length) lines.push(t('admin.shippingInventory.sampleReplacementMissingColumns', { columns: difference.missing_columns.join('、') }));
if (difference.column_order_changed) lines.push(t('admin.shippingInventory.sampleReplacementColumnOrderChanged'));
return lines;
});
const operators = [ const operators = [
{ value: 'equals', label: t('admin.shippingInventory.operatorEquals') }, { value: 'not_equals', label: t('admin.shippingInventory.operatorNotEquals') }, { value: 'equals', label: t('admin.shippingInventory.operatorEquals') }, { value: 'not_equals', label: t('admin.shippingInventory.operatorNotEquals') },
{ value: 'in', label: t('admin.shippingInventory.operatorIn') }, { value: 'not_in', label: t('admin.shippingInventory.operatorNotIn') }, { value: 'in', label: t('admin.shippingInventory.operatorIn') }, { value: 'not_in', label: t('admin.shippingInventory.operatorNotIn') },
@@ -662,14 +729,17 @@ function selectInventoryMappingTab(tab: 'parsing' | 'inventoryFields'): void {
function createNew(): void { function createNew(): void {
selectedId.value = null; 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 });
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; selectedTemporaryInventorySession.value = ''; } 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 === 'inventoryFields') Object.assign(inventoryField, { display_name: '', description: '', value_type: 'text', usage_type: 'general', sort_order: 100, status: 'active' });
if (activeTab.value === 'templates') { if (activeTab.value === 'templates') {
Object.assign(excelTemplate, { template_code: '', display_name: '', filename_pattern: '{business_no}.xlsx', mappings: [], file: null }); Object.assign(excelTemplate, { template_code: '', display_name: '', filename_pattern: '{business_no}.xlsx', mappings: [], file: null });
templateSheets.value = []; templateSheets.value = [];
templateSheetColumns.value = {}; templateSheetColumns.value = {};
} }
if (activeTab.value === 'sources') Object.assign(source, { source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [], match_aliases_json: [], enabled: false, activation: { ready: false, missing_requirements: ['configuration_test'] } }); if (activeTab.value === 'sources') {
Object.assign(source, { source_code: '', display_name: '', connector_type: 'dbs', rpa_profile_id: 0, parsing_profile_id: 0, excel_template_id: 0, warehouse_resolution_mode: 'fixed', fixed_warehouse_id: '', snapshot_ttl_seconds: 86400, report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '' }, query_parameters_json: [], match_aliases_json: [], enabled: false, activation: { ready: false, checks: [], missing_requirements: ['configuration_test'] } });
sourceBaseline.value = '';
}
if (activeTab.value === 'rules') Object.assign(rule, { rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', system_fact_key: '', operator: 'prefix', expected: '' }], source_codes: [] }); if (activeTab.value === 'rules') Object.assign(rule, { rule_code: '', rule_name: '', scope: 'line', priority: 100, conditions: [{ source_kind: 'order_field', order_field_id: '', system_fact_key: '', operator: 'prefix', expected: '' }], source_codes: [] });
if (activeTab.value === 'mappings') Object.assign(mapping, { inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true }); if (activeTab.value === 'mappings') Object.assign(mapping, { inventory_source_id: 0, freight_warehouse_id: '', external_system_code: 'TOPGP', external_organization_code: '', external_site_code: '', external_warehouse_code: '', external_warehouse_name: '', enabled: true });
drawerOpen.value = true; drawerOpen.value = true;
@@ -685,6 +755,13 @@ function selectItem(item: Item): void {
field_mappings: Object.entries(item.definition?.field_mapping || {}).map(([inventory_field, source_header]) => ({ inventory_field, source_header: String(source_header) })), field_mappings: Object.entries(item.definition?.field_mapping || {}).map(([inventory_field, source_header]) => ({ inventory_field, source_header: String(source_header) })),
match_keys: (item.definition?.match_keys || []).map((entry: Record<string, unknown>) => ({ order_field_id: String(entry.order_field_id || ''), inventory_field: String(entry.inventory_field_id || entry.inventory_field || '') })), match_keys: (item.definition?.match_keys || []).map((entry: Record<string, unknown>) => ({ order_field_id: String(entry.order_field_id || ''), inventory_field: String(entry.inventory_field_id || entry.inventory_field || '') })),
}); });
if (activeTab.value === 'parsing') {
// 草稿恢复保存的最小化样本证据,而不是要求管理员再次上传原始库存文件。
structureAnalysis.value = item.sample_evidence || null;
pendingSampleReplacement.value = null;
sampleReplacementConfirmed.value = false;
selectedTemporaryInventorySession.value = '';
}
if (activeTab.value === 'inventoryFields') Object.assign(inventoryField, { if (activeTab.value === 'inventoryFields') Object.assign(inventoryField, {
display_name: item.display_name || '', description: item.description || '', value_type: item.value_type || 'text', display_name: item.display_name || '', description: item.description || '', value_type: item.value_type || 'text',
usage_type: item.usage_type || 'general', sort_order: Number(item.sort_order || 100), usage_type: item.usage_type || 'general', sort_order: Number(item.sort_order || 100),
@@ -705,7 +782,11 @@ function selectItem(item: Item): void {
templateSheetColumns.value = {}; templateSheetColumns.value = {};
void loadTemplateLayout(selectedId.value); void loadTemplateLayout(selectedId.value);
} }
if (activeTab.value === 'sources') Object.assign(source, { ...item, fixed_warehouse_id: item.fixed_warehouse_id || '', report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '', ...(item.report_path_json || {}) }, query_parameters_json: (item.query_parameters_json || []).map((parameter: Parameter) => ({ ...parameter })), match_aliases_json: [...(item.match_aliases_json || [])] }); if (activeTab.value === 'sources') {
Object.assign(source, { ...item, fixed_warehouse_id: item.fixed_warehouse_id || '', report_path_json: { program_group: '', program_label: '', report_group: 'Inventory', report_name: '', ...(item.report_path_json || {}) }, query_parameters_json: (item.query_parameters_json || []).map((parameter: Parameter) => ({ ...parameter })), match_aliases_json: [...(item.match_aliases_json || [])] });
sourceBaseline.value = serialiseSourceInput();
void restoreConfigurationTest(Number(item.id));
}
if (activeTab.value === 'rules') Object.assign(rule, { if (activeTab.value === 'rules') Object.assign(rule, {
rule_code: item.rule_code || '', rule_name: item.rule_name || '', scope: item.scope || 'line', priority: item.priority || 0, rule_code: item.rule_code || '', rule_name: item.rule_name || '', scope: item.scope || 'line', priority: item.priority || 0,
conditions: (item.conditions?.length ? item.conditions : [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected_value_json: '' }]).map((condition: Record<string, unknown>) => ({ conditions: (item.conditions?.length ? item.conditions : [{ source_kind: 'order_field', order_field_id: '', operator: 'prefix', expected_value_json: '' }]).map((condition: Record<string, unknown>) => ({
@@ -734,6 +815,7 @@ function closeDrawer(): void {
if (configurationTestTimer !== null) window.clearTimeout(configurationTestTimer); if (configurationTestTimer !== null) window.clearTimeout(configurationTestTimer);
configurationTestTimer = null; configurationTestTimer = null;
configurationTest.value = null; configurationTest.value = null;
sourceBaseline.value = '';
drawerOpen.value = false; drawerOpen.value = false;
selectedId.value = null; selectedId.value = null;
} }
@@ -754,7 +836,21 @@ async function saveCurrent(): Promise<void> {
await createShippingParsingDraftFromTemporarySession(selectedTemporaryInventorySession.value, payload); await createShippingParsingDraftFromTemporarySession(selectedTemporaryInventorySession.value, payload);
} else { } else {
if (!structureAnalysis.value) throw new Error(t('admin.shippingInventory.inventorySampleRequired')); if (!structureAnalysis.value) throw new Error(t('admin.shippingInventory.inventorySampleRequired'));
await createShippingInventoryParsingDraftFromAnalysis(Number(structureAnalysis.value.id), { ...payload, profile_id: selectedId.value || undefined }); if (pendingSampleReplacement.value && !sampleReplacementConfirmed.value) {
const preview = await previewShippingInventorySampleReplacement(selectedId.value!, Number(structureAnalysis.value.id), {
field_mapping: payload.field_mapping,
}) as Item;
pendingSampleReplacement.value = preview;
if (!preview.can_confirm) throw new Error(t('admin.shippingInventory.sampleReplacementCannotConfirm'));
confirmation.visible = true;
confirmation.action = 'replaceInventorySample';
confirmation.title = t('admin.shippingInventory.replaceInventorySample');
confirmation.message = t('admin.shippingInventory.replaceInventorySampleConfirm');
confirmation.confirmText = t('admin.shippingInventory.confirmSampleReplacement');
confirmation.tone = 'primary';
return;
}
await createShippingInventoryParsingDraftFromAnalysis(Number(structureAnalysis.value.id), { ...payload, profile_id: selectedId.value || undefined, confirm_sample_replacement: sampleReplacementConfirmed.value });
} }
} }
if (activeTab.value === 'inventoryFields') { if (activeTab.value === 'inventoryFields') {
@@ -846,6 +942,7 @@ async function confirmPendingAction(): Promise<void> {
if (action === 'retireInventoryField') await retireShippingInventoryField(selectedId.value); if (action === 'retireInventoryField') await retireShippingInventoryField(selectedId.value);
if (action === 'activateSource') await activateShippingInventorySource(selectedId.value); if (action === 'activateSource') await activateShippingInventorySource(selectedId.value);
if (action === 'deactivateSource') await deactivateShippingInventorySource(selectedId.value); if (action === 'deactivateSource') await deactivateShippingInventorySource(selectedId.value);
if (action === 'replaceInventorySample') { sampleReplacementConfirmed.value = true; await saveCurrent(); return; }
if (action === 'delete' && activeTab.value === 'profiles') await deleteShippingRpaProfile(selectedId.value); if (action === 'delete' && activeTab.value === 'profiles') await deleteShippingRpaProfile(selectedId.value);
if (action === 'delete' && activeTab.value === 'sources') await deleteShippingInventorySource(selectedId.value); if (action === 'delete' && activeTab.value === 'sources') await deleteShippingInventorySource(selectedId.value);
if (action === 'delete' && activeTab.value === 'templates') await deleteShippingExcelTemplate(selectedId.value); if (action === 'delete' && activeTab.value === 'templates') await deleteShippingExcelTemplate(selectedId.value);
@@ -885,18 +982,31 @@ async function startConfigurationTest(): Promise<void> {
if (!selectedId.value) return; if (!selectedId.value) return;
configurationTestLoading.value = true; configurationTestLoading.value = true;
try { try {
configurationTest.value = await startShippingInventoryConfigurationTest(selectedId.value) as Item; configurationTest.value = await startShippingInventoryConfigurationTest(selectedId.value);
await pollConfigurationTest(); await pollConfigurationTest();
} catch (cause) { showError(cause, 'configurationTestFailed'); } } catch (cause) { showError(cause, 'configurationTestFailed'); }
finally { configurationTestLoading.value = false; } finally { configurationTestLoading.value = false; }
} }
/** 恢复当前配置对应的最近测试;只有服务端标记为运行中时才重新启动轮询。 */
async function restoreConfigurationTest(sourceId: number): Promise<void> {
try {
const latest = await getLatestShippingInventoryConfigurationTest(sourceId);
if (selectedId.value !== sourceId) return;
configurationTest.value = latest;
if (isConfigurationTestRunning(latest)) await pollConfigurationTest();
} catch (cause) { showError(cause, 'configurationTestFailed'); }
}
/** 读取测试运行的真实异步阶段;完成或失败后停止轮询。 */ /** 读取测试运行的真实异步阶段;完成或失败后停止轮询。 */
async function pollConfigurationTest(): Promise<void> { async function pollConfigurationTest(): Promise<void> {
if (!selectedId.value || !configurationTest.value?.run_no) return; const sourceId = selectedId.value;
const runNo = configurationTest.value?.run_no;
if (!sourceId || !runNo) return;
try { try {
configurationTest.value = await getShippingInventoryConfigurationTest(selectedId.value, String(configurationTest.value.run_no)) as Item; const updated = await getShippingInventoryConfigurationTest(sourceId, runNo);
if (['awaiting_rpa', 'processing'].includes(String(configurationTest.value.status))) { configurationTest.value = updated;
if (isConfigurationTestRunning(updated)) {
configurationTestTimer = window.setTimeout(() => { void pollConfigurationTest(); }, 2000); configurationTestTimer = window.setTimeout(() => { void pollConfigurationTest(); }, 2000);
} }
} catch (cause) { showError(cause, 'configurationTestFailed'); } } catch (cause) { showError(cause, 'configurationTestFailed'); }
@@ -953,12 +1063,23 @@ async function analyseInventorySample(event: Event): Promise<void> {
if (!file) return; if (!file) return;
analysisLoading.value = true; analysisLoading.value = true;
try { try {
structureAnalysis.value = await createShippingInventoryStructureAnalysis(file) as Item; const analysis = await createShippingInventoryStructureAnalysis(file) as Item;
if (selectedId.value) {
const preview = await previewShippingInventorySampleReplacement(selectedId.value, Number(analysis.id)) as Item;
pendingSampleReplacement.value = preview;
sampleReplacementConfirmed.value = false;
}
structureAnalysis.value = analysis;
const structure = structureAnalysis.value.structure || {}; const structure = structureAnalysis.value.structure || {};
parsing.file_format = String(structureAnalysis.value.file_format || 'xlsx'); parsing.file_format = String(structureAnalysis.value.file_format || 'xlsx');
parsing.sheet_name = String(structure.selected_sheet_name || ''); parsing.sheet_name = String(structure.selected_sheet_name || '');
parsing.header_row_index = Number(structure.selected_header_row_index || 1); parsing.header_row_index = Number(structure.selected_header_row_index || 1);
parsing.field_mappings = Object.entries(structureAnalysis.value.suggested_mapping || {}).map(([inventory_field, source_header]) => ({ inventory_field, source_header: String(source_header) })); if (selectedId.value) {
// 替换样本时保留仍存在的既有映射,避免自动建议覆盖管理员已经确认的业务关系。
applyAnalysisCandidate();
} else {
parsing.field_mappings = Object.entries(structureAnalysis.value.suggested_mapping || {}).map(([inventory_field, source_header]) => ({ inventory_field, source_header: String(source_header) }));
}
} catch (cause) { showError(cause, 'inventoryAnalysisFailed'); } } catch (cause) { showError(cause, 'inventoryAnalysisFailed'); }
finally { analysisLoading.value = false; } finally { analysisLoading.value = false; }
} }
@@ -1084,6 +1205,61 @@ function formatDate(value: unknown): string { return value ? new Date(String(val
function auditDate(value: unknown): string { return value ? formatDate(value) : t('admin.shippingInventory.historyNotCaptured'); } function auditDate(value: unknown): string { return value ? formatDate(value) : t('admin.shippingInventory.historyNotCaptured'); }
function sourceName(sourceCode: unknown): string { return String(sourceCode || t('admin.shippingInventory.historyNotCaptured')); } function sourceName(sourceCode: unknown): string { return String(sourceCode || t('admin.shippingInventory.historyNotCaptured')); }
function parsingProfileName(profileId: unknown): string { const item = parsingProfiles.value.find((row) => Number(row.id) === Number(profileId)); return String(item?.display_name || item?.profile_code || t('admin.shippingInventory.notGenerated')); } function parsingProfileName(profileId: unknown): string { const item = parsingProfiles.value.find((row) => Number(row.id) === Number(profileId)); return String(item?.display_name || item?.profile_code || t('admin.shippingInventory.notGenerated')); }
/** 将会影响测试输入的站点字段稳定序列化,用于阻止管理员针对未保存配置运行测试或启用。 */
function serialiseSourceInput(): string {
return JSON.stringify({
source_code: source.source_code, display_name: source.display_name, connector_type: source.connector_type,
rpa_profile_id: source.rpa_profile_id, parsing_profile_id: source.parsing_profile_id,
excel_template_id: source.excel_template_id, warehouse_resolution_mode: source.warehouse_resolution_mode,
fixed_warehouse_id: source.fixed_warehouse_id, snapshot_ttl_seconds: source.snapshot_ttl_seconds,
report_path_json: source.report_path_json, query_parameters_json: source.query_parameters_json,
match_aliases_json: source.match_aliases_json,
});
}
/** 返回状态轨道的简洁可视标记,文本状态仍由相邻内容提供,避免颜色成为唯一信息来源。 */
function readinessMarker(status: ShippingInventoryReadinessCheck['status']): string {
const marker = readinessMarkerKind(status);
if (marker === 'complete') return '✓';
if (marker === 'attention') return '!';
return '•';
}
/** 将服务端脱敏证据翻译为管理员可理解的当前步骤说明。 */
function readinessDetail(check: ShippingInventoryReadinessCheck): string {
if (check.status === 'passed') return t('admin.shippingInventory.readinessState.passed');
if (check.status === 'stale') return t('admin.shippingInventory.readinessState.stale');
if (check.status === 'failed') return t('admin.shippingInventory.readinessState.failed');
return check.blocking ? t('admin.shippingInventory.readinessState.required') : t('admin.shippingInventory.readinessState.waiting');
}
/** 每项门禁只映射一个推荐动作;已经通过和依赖测试的辅助检查不额外制造操作入口。 */
function readinessActionLabel(check: ShippingInventoryReadinessCheck): string {
if (!needsReadinessAction(check)) return '';
if (check.action === 'run_configuration_test') return configurationTestLoading.value
? t('admin.shippingInventory.configurationTestRunning')
: t('admin.shippingInventory.startConfigurationTest');
return t(`admin.shippingInventory.readinessAction.${check.action}`);
}
/** 未保存的 Source 编辑必须先提交到服务端,确保测试和启用都基于同一配置版本。 */
function isReadinessActionBlocked(check: ShippingInventoryReadinessCheck): boolean {
return sourceDirty.value || (check.action === 'run_configuration_test' && configurationTestLoading.value);
}
/** 将阻断项引导到所属配置区域;测试动作仍停留在当前站点抽屉内执行。 */
function runReadinessAction(check: ShippingInventoryReadinessCheck): void {
if (isReadinessActionBlocked(check)) {
message.warning(t('admin.shippingInventory.saveBeforeReadinessAction'));
return;
}
if (check.action === 'run_configuration_test') { void startConfigurationTest(); return; }
const target: Record<Exclude<ShippingInventoryReadinessCheck['action'], 'run_configuration_test'>, TabKey> = {
configure_connection: 'profiles', configure_parsing_profile: 'parsing',
configure_excel_template: 'templates', configure_warehouse_mapping: 'mappings',
};
selectTab(target[check.action]);
}
function connectionName(sourceCode: unknown): string { const sourceItem = sources.value.find((source) => source.source_code === sourceCode); const profileItem = profiles.value.find((profile) => Number(profile.id) === Number(sourceItem?.rpa_profile_id)); return profileItem?.profile_code || t('admin.shippingInventory.historyNotCaptured'); } function connectionName(sourceCode: unknown): string { const sourceItem = sources.value.find((source) => source.source_code === sourceCode); const profileItem = profiles.value.find((profile) => Number(profile.id) === Number(sourceItem?.rpa_profile_id)); return profileItem?.profile_code || t('admin.shippingInventory.historyNotCaptured'); }
function warehouseName(item: Item): string { return item.warehouse_id || (item.source_code === 'CRANE' ? t('admin.shippingInventory.dynamicWarehouse') : t('admin.shippingInventory.historyNotCaptured')); } function warehouseName(item: Item): string { return item.warehouse_id || (item.source_code === 'CRANE' ? t('admin.shippingInventory.dynamicWarehouse') : t('admin.shippingInventory.historyNotCaptured')); }
function auditStatus(value: unknown): string { const key = String(value || 'unknown'); return t(`admin.shippingInventory.auditStatus.${key}`); } function auditStatus(value: unknown): string { const key = String(value || 'unknown'); return t(`admin.shippingInventory.auditStatus.${key}`); }
@@ -1137,7 +1313,7 @@ onMounted(load);
.workbench-heading p { max-width: 660px; margin: 5px 0 0; color: #64748b; font-size: 13px; } .workbench-heading p { max-width: 660px; margin: 5px 0 0; color: #64748b; font-size: 13px; }
.primary-action, .secondary-action, .text-action { border: 0; border-radius: 6px; padding: 8px 12px; font-size: 13px; font-weight: 600; cursor: pointer; } .primary-action, .secondary-action, .text-action { border: 0; border-radius: 6px; padding: 8px 12px; font-size: 13px; font-weight: 600; cursor: pointer; }
.primary-action { background: #0ea5e9; color: #fff; } .primary-action { background: #0ea5e9; color: #fff; }
.primary-action:disabled, .text-action:disabled { opacity: .5; cursor: not-allowed; } .primary-action:disabled, .secondary-action:disabled, .text-action:disabled { opacity: .5; cursor: not-allowed; }
.secondary-action { background: #f1f5f9; color: #475569; } .secondary-action { background: #f1f5f9; color: #475569; }
.text-action { background: transparent; padding: 4px; color: #0284c7; } .text-action { background: transparent; padding: 4px; color: #0284c7; }
.text-action.danger { color: #b42318; } .text-action.danger { color: #b42318; }
@@ -1173,7 +1349,15 @@ onMounted(load);
.filename-variable-menu { position: absolute; z-index: 3; top: calc(100% + 5px); left: 0; width: min(440px, 100%); overflow: hidden; border: 1px solid #cfdde7; border-radius: 7px; background: #fff; box-shadow: 0 10px 24px rgb(15 23 42 / 14%); padding: 4px; } .filename-variable-menu { position: absolute; z-index: 3; top: calc(100% + 5px); left: 0; width: min(440px, 100%); overflow: hidden; border: 1px solid #cfdde7; border-radius: 7px; background: #fff; box-shadow: 0 10px 24px rgb(15 23 42 / 14%); padding: 4px; }
.filename-variable-menu button { display: grid; width: 100%; grid-template-columns: 154px minmax(0, 1fr); gap: 8px; border: 0; border-radius: 4px; background: transparent; padding: 7px 8px; color: #64748b; font: inherit; font-size: 12px; text-align: left; cursor: pointer; } .filename-variable-menu button { display: grid; width: 100%; grid-template-columns: 154px minmax(0, 1fr); gap: 8px; border: 0; border-radius: 4px; background: transparent; padding: 7px 8px; color: #64748b; font: inherit; font-size: 12px; text-align: left; cursor: pointer; }
.filename-variable-menu button:hover, .filename-variable-menu button.active { background: #eef8f7; color: #145f5a; }.filename-variable-menu code { color: #047f76; font-size: 12px; }.filename-variable-menu p { margin: 0; padding: 8px; color: #94a3b8; font-size: 12px; } .filename-variable-menu button:hover, .filename-variable-menu button.active { background: #eef8f7; color: #145f5a; }.filename-variable-menu code { color: #047f76; font-size: 12px; }.filename-variable-menu p { margin: 0; padding: 8px; color: #94a3b8; font-size: 12px; }
.readiness-card { display: grid; gap: 13px; border: 1px solid #d9e6ef; border-radius: 10px; background: linear-gradient(135deg, #fbfdff, #f4f9fc); padding: 15px; }.readiness-card.ready { border-color: #b7e4c7; background: linear-gradient(135deg, #fbfffc, #f2fbf5); }
.readiness-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }.readiness-heading > div { display: grid; gap: 4px; }.readiness-kicker { color: #64748b; font-size: 11px; font-weight: 700; letter-spacing: .05em; text-transform: uppercase; }.readiness-heading strong { color: #263b4e; font-size: 13px; line-height: 1.45; }.readiness-count { flex: 0 0 auto; border-radius: 999px; background: #eaf4fa; padding: 4px 8px; color: #176f9f; font-size: 11px; font-weight: 700; }.readiness-card.ready .readiness-count { background: #e8f7ed; color: #19703a; }
.readiness-steps { display: grid; gap: 0; margin: 0; padding: 0; list-style: none; }.readiness-steps li { display: grid; grid-template-columns: 24px minmax(0, 1fr) auto; align-items: center; gap: 9px; min-height: 48px; border-top: 1px solid #e6eef4; padding: 8px 0; }.readiness-marker { display: inline-grid; width: 20px; height: 20px; place-items: center; border-radius: 50%; background: #e9eef3; color: #6c7d8d; font-size: 12px; font-weight: 800; }.readiness-copy { display: grid; min-width: 0; gap: 2px; }.readiness-copy b { overflow: hidden; color: #425466; font-size: 12px; text-overflow: ellipsis; white-space: nowrap; }.readiness-copy small { color: #8190a0; font-size: 11px; line-height: 1.35; }.readiness-steps .is-passed .readiness-marker { background: #dff6e6; color: #16803a; }.readiness-steps .is-passed .readiness-copy b { color: #2d6b40; }.readiness-steps .is-failed .readiness-marker, .readiness-steps .is-stale .readiness-marker { background: #fff0ed; color: #bf4a38; }.readiness-steps .is-failed .readiness-copy b, .readiness-steps .is-stale .readiness-copy b { color: #9d382b; }
.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-note, .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 { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 1px; margin: 0; overflow: hidden; border: 1px solid #dce8ef; border-radius: 7px; background: #dce8ef; }.readiness-audit > div { min-width: 0; background: #fff; padding: 8px 9px; }.readiness-audit dt { color: #7b8998; font-size: 10px; font-weight: 700; letter-spacing: .03em; }.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; } .form-tip { border-radius: 8px; background: #f1f6fa; padding: 11px; color: #5d7084; font-size: 12px; line-height: 1.55; }
.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; }
.sample-evidence-card dl { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px 16px; margin: 0; }.sample-evidence-card dl div { min-width: 0; }.sample-evidence-card dt { color: #8190a0; font-size: 11px; }.sample-evidence-card dd { margin: 3px 0 0; overflow-wrap: anywhere; color: #475569; font-size: 12px; font-weight: 600; }
.sample-replacement-input { display: grid; gap: 6px; border-top: 1px solid #e5edf3; padding-top: 11px; color: #52677a; font-size: 12px; font-weight: 600; }.sample-replacement-input input { max-width: 100%; }.sample-replacement-warning { border-left: 3px solid #e5a21a; background: #fff9eb; padding: 8px 10px; color: #855e00 !important; }.sample-replacement-warning p { margin: 0; }.sample-replacement-warning ul { display: grid; gap: 3px; margin: 7px 0 0; padding-left: 17px; }
.parameter-row { display: grid; align-items: center; grid-template-columns: 1.1fr .9fr 1.25fr auto auto auto; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; } .parameter-row { display: grid; align-items: center; grid-template-columns: 1.1fr .9fr 1.25fr auto auto auto; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
.condition-row, .mapping-row, .template-mapping { display: grid; align-items: center; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; } .condition-row, .mapping-row, .template-mapping { display: grid; align-items: center; gap: 8px; border-radius: 8px; background: #f8fafc; padding: 9px; }
.condition-row { grid-template-columns: 1.15fr .9fr 1fr auto; } .condition-row { grid-template-columns: 1.15fr .9fr 1fr auto; }
@@ -1214,6 +1398,6 @@ onMounted(load);
.audit-detail dl { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 0; margin: 0; padding: 18px 20px; }.audit-detail dt, .audit-detail dd { margin: 0; padding: 11px 0; border-bottom: 1px solid #edf2f7; font-size: 13px; }.audit-detail dt { color: #64748b; }.audit-detail dd { overflow-wrap: anywhere; color: #334155; } .audit-detail dl { display: grid; grid-template-columns: 130px minmax(0, 1fr); gap: 0; margin: 0; padding: 18px 20px; }.audit-detail dt, .audit-detail dd { margin: 0; padding: 11px 0; border-bottom: 1px solid #edf2f7; font-size: 13px; }.audit-detail dt { color: #64748b; }.audit-detail dd { overflow-wrap: anywhere; color: #334155; }
.object-list .empty-state { grid-column: 1 / -1; display: grid; min-height: 260px; place-items: center; } .object-list .empty-state { grid-column: 1 / -1; display: grid; min-height: 260px; place-items: center; }
.empty-state { border: 1px dashed #c9d7e5; border-radius: 10px; background: #f9fbfd; padding: 38px 18px; color: #7b899a; font-size: 13px; text-align: center; } .empty-state { border: 1px dashed #c9d7e5; border-radius: 10px; background: #f9fbfd; padding: 38px 18px; color: #7b899a; font-size: 13px; text-align: center; }
@media (max-width: 980px) { .console-header { display: block; } .flow-strip { display: inline-flex; margin-top: 18px; } .console-layout { grid-template-columns: 1fr; } .section-nav { flex-direction: row; gap: 12px; overflow-x: auto; } .nav-group { display: flex; align-items: center; gap: 4px; } .nav-group > p { display: none; } .section-nav button { min-width: max-content; border-bottom: 3px solid transparent; border-left: 0; } .section-nav button.active { border-bottom-color: #16877f; border-left: 0; } .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); } } @media (max-width: 980px) { .console-header { display: block; } .flow-strip { display: inline-flex; margin-top: 18px; } .console-layout { grid-template-columns: 1fr; } .section-nav { flex-direction: row; gap: 12px; overflow-x: auto; } .nav-group { display: flex; align-items: center; gap: 4px; } .nav-group > p { display: none; } .section-nav button { min-width: max-content; border-bottom: 3px solid transparent; border-left: 0; } .section-nav button.active { border-bottom-color: #16877f; border-left: 0; } .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card { grid-template-columns: 1fr 1fr; } .mapping-value-row { grid-template-columns: minmax(0, 1.6fr) minmax(180px, 1fr); }.readiness-audit { grid-template-columns: repeat(2, minmax(0, 1fr)); } }
@media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .primary-action { margin-top: 12px; } } @media (max-width: 640px) { .inventory-console { padding: 18px; } .editor-form, .parameter-row, .condition-row, .mapping-row, .template-mapping, .record-card, .mapping-value-row, .parsing-mapping-card, .readonly-mapping-section .parsing-mapping-card, .parsing-summary { grid-template-columns: 1fr; } .mapping-arrow { transform: rotate(90deg); }.workbench-heading { display: block; } .workbench-heading .primary-action { margin-top: 12px; } .readiness-heading { display: grid; }.readiness-count { justify-self: start; }.readiness-steps li { grid-template-columns: 24px minmax(0, 1fr); }.readiness-action { grid-column: 2; justify-self: start; }.readiness-footer { justify-content: stretch; }.readiness-footer .primary-action { width: 100%; } }
</style> </style>
@@ -0,0 +1,36 @@
/**
* features/admin/modules/shipping-inventory/shippingInventoryReadiness.spec.ts
* 用途:覆盖库存站点上线检查与测试恢复的纯状态映射。
* 依赖:shippingInventoryReadiness、vitest。
* 逻辑:防止页面把已完成项目显示为待办,或持续轮询服务端已结束的测试任务。
*/
import { describe, expect, it } from 'vitest';
import type { ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api';
import { isConfigurationTestRunning, needsReadinessAction, readinessMarkerKind } from './shippingInventoryReadiness';
const check = (status: ShippingInventoryReadinessCheck['status'], blocking: boolean): ShippingInventoryReadinessCheck => ({
code: 'configuration_test', status, blocking, action: 'run_configuration_test', evidence: {},
});
describe('shippingInventoryReadiness', () => {
it('keeps stale checks actionable and visually distinct from ordinary pending work', () => {
// 关键断言:配置已变更的测试不能被渲染成普通待办,管理员必须重新测试。
expect(readinessMarkerKind('stale')).toBe('attention');
expect(needsReadinessAction(check('stale', true))).toBe(true);
});
it('does not offer duplicate actions for passed or non-blocking checks', () => {
// 关键断言:后端已经通过或依赖前置步骤的项目不应再次分散管理员注意力。
expect(needsReadinessAction(check('passed', false))).toBe(false);
expect(needsReadinessAction(check('pending', false))).toBe(false);
});
it('polls only server-declared running test states', () => {
// 关键断言:完成与失败均是终态,页面不得凭前端时间继续请求详情接口。
expect(isConfigurationTestRunning({ run_no: 'RUN-1', status: 'awaiting_rpa', stage: 'waiting_worker' })).toBe(true);
expect(isConfigurationTestRunning({ run_no: 'RUN-2', status: 'processing', stage: 'analysing_structure' })).toBe(true);
expect(isConfigurationTestRunning({ run_no: 'RUN-3', status: 'completed', stage: 'ready_for_confirmation' })).toBe(false);
expect(isConfigurationTestRunning({ run_no: 'RUN-4', status: 'failed', stage: 'failed' })).toBe(false);
});
});
@@ -0,0 +1,42 @@
/**
* features/admin/modules/shipping-inventory/shippingInventoryReadiness.ts
* 用途:归一库存站点上线检查与配置测试的前端展示状态。
* 依赖:admin.api 中的 Inventory Readiness/Test 类型。
* 逻辑:ShippingInventoryPage 调用本文件决定测试轮询、步骤标记和推荐动作;后端仍是门禁真相源。
*/
import type { ShippingInventoryConfigurationTest, ShippingInventoryReadinessCheck } from '@/features/admin/api/admin.api';
export type ReadinessMarker = 'complete' | 'attention' | 'pending';
/**
* 将后端检查状态归类为无障碍视觉标记。
* 核心逻辑:失败和过期都需要管理员处理;完成与待办分别使用稳定语义。
* @param status - 后端 `checks[]` 返回的稳定状态。
* @returns 供页面选择图形和颜色的有限标记,不参与启用门禁计算。
*/
export function readinessMarkerKind(status: ShippingInventoryReadinessCheck['status']): ReadinessMarker {
if (status === 'passed') return 'complete';
if (status === 'failed' || status === 'stale') return 'attention';
return 'pending';
}
/**
* 判断一个检查项是否应展示其唯一推荐操作。
* 核心逻辑:已通过和仅等待其他前置步骤的检查不提供重复入口。
* @param check - 后端权威检查项。
* @returns 为 true 时页面可展示对应的单一下一步动作。
*/
export function needsReadinessAction(check: ShippingInventoryReadinessCheck): boolean {
return check.status !== 'passed' && check.blocking;
}
/**
* 判断测试运行是否需要继续向服务端轮询。
* 核心逻辑:仅运行态轮询;失败与完成均为终态,防止页面无限请求。
* @param test - 当前恢复或新发起的测试运行。
* @returns 是否继续轮询。
*/
export function isConfigurationTestRunning(test: ShippingInventoryConfigurationTest | null): boolean {
return Boolean(test && ['awaiting_rpa', 'processing'].includes(test.status));
}
+22 -1
View File
@@ -219,6 +219,23 @@
"fileFormat": "File format", "fileFormat": "File format",
"inventorySampleFile": "Inventory Sample File", "inventorySampleFile": "Inventory Sample File",
"inventorySampleFileHint": "Upload an Excel or CSV file. The system reads worksheets, headers, and a small sample for plan confirmation.", "inventorySampleFileHint": "Upload an Excel or CSV file. The system reads worksheets, headers, and a small sample for plan confirmation.",
"savedInventorySample": "Saved inventory sample evidence",
"savedInventorySampleHint": "Only headers, structure statistics, and masked samples are retained. Continue editing this inventory mapping without uploading the original file again.",
"pendingInventorySampleReplacement": "Replacement sample awaiting confirmation",
"pendingInventorySampleReplacementHint": "This sample has not replaced the current audit evidence. Review the differences below and save to confirm it.",
"sampleFileName": "Original file name",
"sampleRowsRetained": "Masked sample rows retained",
"replaceInventorySample": "Replace inventory sample",
"replaceInventorySampleHint": "The system compares headers and current mappings first; saved evidence is unchanged until you confirm.",
"replaceInventorySampleConfirm": "The structural differences have been reviewed. Replace this draft's saved sample evidence? The old sample remains in the audit history.",
"confirmSampleReplacement": "Confirm replacement",
"sampleReplacementReady": "The new sample is compatible with the current mappings. Saving still requires replacement confirmation.",
"sampleReplacementMappingRequired": "The new sample is missing mapped columns: {columns}. Update mappings before saving.",
"sampleReplacementFileFormatChanged": "The new sample format differs from this inventory mapping and cannot replace it.",
"sampleReplacementCannotConfirm": "The new sample does not meet replacement conditions. Resolve the mapping differences first.",
"sampleReplacementAddedColumns": "Added columns: {columns}",
"sampleReplacementMissingColumns": "Missing original sample columns: {columns}",
"sampleReplacementColumnOrderChanged": "Column order changed.",
"inventorySampleAnalysing": "Analysing inventory file structure...", "inventorySampleAnalysing": "Analysing inventory file structure...",
"inventorySampleRequired": "Upload an inventory sample file and complete structure recognition first.", "inventorySampleRequired": "Upload an inventory sample file and complete structure recognition first.",
"parsingProfileName": "Inventory Parsing Name", "parsingProfileName": "Inventory Parsing Name",
@@ -337,6 +354,10 @@
"parsingProfileGeneratedByTest": "Save the site first, then identify or confirm its inventory parsing through a test export.", "parsingProfileGeneratedByTest": "Save the site first, then identify or confirm its inventory parsing through a test export.",
"sourceSavedDisabledHint": "The site remains disabled after its first save. Complete the test export, inventory parsing, and shipping template before activation.", "sourceSavedDisabledHint": "The site remains disabled after its first save. Complete the test export, inventory parsing, and shipping template before activation.",
"activationStatus": "Production Readiness", "activationStatus": "Production Readiness",
"readinessProgress": "{passed} of {total} complete",
"readinessState": { "passed": "Complete", "required": "Action required", "waiting": "Waiting for prerequisite", "failed": "Check failed; resolve and retry", "stale": "Configuration changed; run the test again" },
"readinessAction": { "configure_connection": "Configure connection", "configure_parsing_profile": "Configure parsing", "configure_excel_template": "Configure template", "configure_warehouse_mapping": "Configure warehouse mapping" },
"saveBeforeReadinessAction": "Save the current inventory-site changes before taking this action.",
"activationReady": "The inventory site is enabled and can run in production.", "activationReady": "The inventory site is enabled and can run in production.",
"activationDraft": "The inventory site is disabled. Complete the following items before activation.", "activationDraft": "The inventory site is disabled. Complete the following items before activation.",
"activationRequirement": { "rpa_profile": "System connection is available", "parsing_profile": "Inventory file parsing profile", "excel_template": "Shipping template", "configuration_test": "Test export and parsing validation", "parsing_validation": "Part number, reservation ID, and quantity parse correctly in the test file", "warehouse_identification": "The test file identifies the freight warehouse", "warehouse_mapping": "A freight-to-external warehouse mapping is maintained", "template_validation": "All inventory fields used by the shipping template are supplied by the parsing profile" }, "activationRequirement": { "rpa_profile": "System connection is available", "parsing_profile": "Inventory file parsing profile", "excel_template": "Shipping template", "configuration_test": "Test export and parsing validation", "parsing_validation": "Part number, reservation ID, and quantity parse correctly in the test file", "warehouse_identification": "The test file identifies the freight warehouse", "warehouse_mapping": "A freight-to-external warehouse mapping is maintained", "template_validation": "All inventory fields used by the shipping template are supplied by the parsing profile" },
@@ -344,7 +365,7 @@
"deactivateSource": "Disable Inventory Site", "deactivateSource": "Disable Inventory Site",
"activateSourceConfirm": "The system will verify all production prerequisites before enabling this inventory site.", "activateSourceConfirm": "The system will verify all production prerequisites before enabling this inventory site.",
"deactivateSourceConfirm": "The site will no longer join new inventory routing or export jobs. Continue?", "deactivateSourceConfirm": "The site will no longer join new inventory routing or export jobs. Continue?",
"configurationTest": "Test Export", "configurationTestHint": "The test file validates the connection, file structure, and inventory mapping only. It never enters production matching or shipping exports.", "startConfigurationTest": "Test Export", "configurationTestRunning": "Test in progress...", "configurationTestFailed": "Inventory site test export failed.", "configurationTestNoRecommendation": "No published inventory mapping can be used directly. Create or refine an inventory mapping from the test result.", "confirmTestProfile": "Confirm and Bind This Mapping", "configurationTestProfileConfirmed": "The inventory mapping is confirmed; the inventory site remains disabled.", "configurationTestStage": { "waiting_worker": "Waiting for the RPA Worker", "analysing_structure": "Recognising inventory file structure", "ready_for_confirmation": "Test complete; confirm the inventory mapping", "failed": "Test failed" }, "configurationTest": "Test Export", "configurationTestHint": "The test file validates the connection, file structure, and inventory mapping only. It never enters production matching or shipping exports.", "startConfigurationTest": "Test Export", "configurationTestRunning": "Test in progress...", "configurationTestRunNo": "Test run", "configurationTestConfigVersion": "Site configuration version", "configurationTestConnectionVersion": "Connection configuration version", "configurationTestUpdatedAt": "Last updated", "configurationTestFailed": "Inventory site test export failed.", "configurationTestNoRecommendation": "No published inventory mapping can be used directly. Create or refine an inventory mapping from the test result.", "confirmTestProfile": "Confirm and Bind This Mapping", "configurationTestProfileConfirmed": "The inventory mapping is confirmed; the inventory site remains disabled.", "configurationTestStage": { "waiting_worker": "Waiting for the RPA Worker", "analysing_structure": "Recognising inventory file structure", "ready_for_confirmation": "Test complete; confirm the inventory mapping", "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.", "connectionBoundary": "Enter only the login information here. The system handles the required page actions, downloads, and waiting for the selected freight platform.",
"platform": { "dbs": "DBS", "crane": "Crane" }, "platform": { "dbs": "DBS", "crane": "Crane" },
"sourceCode": "Inventory Source ID", "sourceCode": "Inventory Source ID",
+22 -1
View File
@@ -219,6 +219,23 @@
"fileFormat": "รูปแบบไฟล์", "fileFormat": "รูปแบบไฟล์",
"inventorySampleFile": "ไฟล์ตัวอย่างสต็อก", "inventorySampleFile": "ไฟล์ตัวอย่างสต็อก",
"inventorySampleFileHint": "อัปโหลด Excel หรือ CSV แล้วระบบจะอ่านชีต หัวตาราง และตัวอย่างเล็กน้อยเพื่อยืนยันแผนการอ่าน", "inventorySampleFileHint": "อัปโหลด Excel หรือ CSV แล้วระบบจะอ่านชีต หัวตาราง และตัวอย่างเล็กน้อยเพื่อยืนยันแผนการอ่าน",
"savedInventorySample": "หลักฐานไฟล์ตัวอย่างสต็อกที่บันทึกไว้",
"savedInventorySampleHint": "ระบบเก็บเฉพาะหัวตาราง สถิติโครงสร้าง และตัวอย่างที่ปกปิดข้อมูลแล้ว จึงแก้ไขการแมปสต็อกนี้ต่อได้โดยไม่ต้องอัปโหลดไฟล์ต้นฉบับใหม่",
"pendingInventorySampleReplacement": "ไฟล์ตัวอย่างทดแทนที่รอยืนยัน",
"pendingInventorySampleReplacementHint": "ไฟล์ตัวอย่างนี้ยังไม่ได้แทนที่หลักฐานการตรวจสอบปัจจุบัน โปรดตรวจสอบความแตกต่างด้านล่างแล้วบันทึกเพื่อยืนยัน",
"sampleFileName": "ชื่อไฟล์ต้นฉบับ",
"sampleRowsRetained": "จำนวนแถวตัวอย่างที่ปกปิดข้อมูล",
"replaceInventorySample": "เปลี่ยนไฟล์ตัวอย่างสต็อก",
"replaceInventorySampleHint": "ระบบจะเปรียบเทียบหัวตารางและการแมปปัจจุบันก่อน หลักฐานที่บันทึกไว้จะไม่เปลี่ยนจนกว่าจะยืนยัน",
"replaceInventorySampleConfirm": "ตรวจสอบความแตกต่างของโครงสร้างแล้ว ต้องการเปลี่ยนหลักฐานตัวอย่างของฉบับร่างนี้หรือไม่ ไฟล์ตัวอย่างเดิมยังอยู่ในประวัติการตรวจสอบ",
"confirmSampleReplacement": "ยืนยันการเปลี่ยน",
"sampleReplacementReady": "ไฟล์ตัวอย่างใหม่เข้ากันได้กับการแมปปัจจุบัน แต่การบันทึกยังต้องยืนยันการเปลี่ยน",
"sampleReplacementMappingRequired": "ไฟล์ตัวอย่างใหม่ไม่มีคอลัมน์ที่แมปไว้: {columns} โปรดปรับการแมปก่อนบันทึก",
"sampleReplacementFileFormatChanged": "รูปแบบไฟล์ตัวอย่างใหม่ต่างจากการแมปสต็อกนี้ จึงเปลี่ยนไม่ได้",
"sampleReplacementCannotConfirm": "ไฟล์ตัวอย่างใหม่ยังไม่ผ่านเงื่อนไขการเปลี่ยน โปรดแก้ความแตกต่างของการแมปก่อน",
"sampleReplacementAddedColumns": "คอลัมน์ที่เพิ่ม: {columns}",
"sampleReplacementMissingColumns": "คอลัมน์จากไฟล์ตัวอย่างเดิมที่หายไป: {columns}",
"sampleReplacementColumnOrderChanged": "ลำดับคอลัมน์เปลี่ยนแล้ว",
"inventorySampleAnalysing": "กำลังวิเคราะห์โครงสร้างไฟล์สต็อก...", "inventorySampleAnalysing": "กำลังวิเคราะห์โครงสร้างไฟล์สต็อก...",
"inventorySampleRequired": "โปรดอัปโหลดไฟล์ตัวอย่างสต็อกและทำการระบุโครงสร้างให้เสร็จก่อน", "inventorySampleRequired": "โปรดอัปโหลดไฟล์ตัวอย่างสต็อกและทำการระบุโครงสร้างให้เสร็จก่อน",
"parsingProfileName": "ชื่อแผนการอ่านไฟล์", "parsingProfileName": "ชื่อแผนการอ่านไฟล์",
@@ -322,6 +339,10 @@
"parsingProfileGeneratedByTest": "บันทึกไซต์ก่อน แล้วระบุหรือยืนยันแผนการแยกวิเคราะห์ไฟล์สต็อกจากการส่งออกทดสอบ", "parsingProfileGeneratedByTest": "บันทึกไซต์ก่อน แล้วระบุหรือยืนยันแผนการแยกวิเคราะห์ไฟล์สต็อกจากการส่งออกทดสอบ",
"sourceSavedDisabledHint": "ไซต์จะยังปิดใช้งานหลังบันทึกครั้งแรก โปรดทำการส่งออกทดสอบ แผนการอ่าน และเทมเพลตการจัดส่งให้เสร็จก่อนเปิดใช้งาน", "sourceSavedDisabledHint": "ไซต์จะยังปิดใช้งานหลังบันทึกครั้งแรก โปรดทำการส่งออกทดสอบ แผนการอ่าน และเทมเพลตการจัดส่งให้เสร็จก่อนเปิดใช้งาน",
"activationStatus": "การตรวจสอบก่อนใช้งานจริง", "activationStatus": "การตรวจสอบก่อนใช้งานจริง",
"readinessProgress": "เสร็จแล้ว {passed} / {total}",
"readinessState": { "passed": "เสร็จสมบูรณ์", "required": "ต้องดำเนินการ", "waiting": "รอขั้นตอนก่อนหน้า", "failed": "การตรวจสอบไม่ผ่าน โปรดแก้ไขและลองใหม่", "stale": "การตั้งค่าเปลี่ยนแล้ว โปรดทดสอบอีกครั้ง" },
"readinessAction": { "configure_connection": "ตั้งค่าการเชื่อมต่อ", "configure_parsing_profile": "ตั้งค่าการอ่านไฟล์", "configure_excel_template": "ตั้งค่าเทมเพลต", "configure_warehouse_mapping": "ตั้งค่าการแมปคลังสินค้า" },
"saveBeforeReadinessAction": "โปรดบันทึกการเปลี่ยนแปลงไซต์สต็อกปัจจุบันก่อนดำเนินการนี้",
"activationReady": "เปิดใช้งานไซต์สต็อกแล้วและพร้อมใช้งานจริง", "activationReady": "เปิดใช้งานไซต์สต็อกแล้วและพร้อมใช้งานจริง",
"activationDraft": "ไซต์สต็อกยังปิดใช้งาน โปรดทำรายการต่อไปนี้ให้เสร็จก่อนเปิดใช้งาน", "activationDraft": "ไซต์สต็อกยังปิดใช้งาน โปรดทำรายการต่อไปนี้ให้เสร็จก่อนเปิดใช้งาน",
"activationRequirement": { "rpa_profile": "การเชื่อมต่อระบบพร้อมใช้งาน", "parsing_profile": "แผนการแยกวิเคราะห์ไฟล์สต็อก", "excel_template": "เทมเพลตการจัดส่ง", "configuration_test": "การส่งออกทดสอบและการตรวจสอบการอ่าน", "parsing_validation": "อ่านเลขชิ้นส่วน เลขจอง และจำนวนจากไฟล์ทดสอบได้ถูกต้อง", "warehouse_identification": "ไฟล์ทดสอบระบุคลังของผู้ให้บริการได้", "warehouse_mapping": "มีการดูแลการแมประหว่างคลังผู้ให้บริการและคลังระบบภายนอก", "template_validation": "ฟิลด์สต็อกที่เทมเพลตใช้มีอยู่ในแผนการแยกวิเคราะห์" }, "activationRequirement": { "rpa_profile": "การเชื่อมต่อระบบพร้อมใช้งาน", "parsing_profile": "แผนการแยกวิเคราะห์ไฟล์สต็อก", "excel_template": "เทมเพลตการจัดส่ง", "configuration_test": "การส่งออกทดสอบและการตรวจสอบการอ่าน", "parsing_validation": "อ่านเลขชิ้นส่วน เลขจอง และจำนวนจากไฟล์ทดสอบได้ถูกต้อง", "warehouse_identification": "ไฟล์ทดสอบระบุคลังของผู้ให้บริการได้", "warehouse_mapping": "มีการดูแลการแมประหว่างคลังผู้ให้บริการและคลังระบบภายนอก", "template_validation": "ฟิลด์สต็อกที่เทมเพลตใช้มีอยู่ในแผนการแยกวิเคราะห์" },
@@ -329,7 +350,7 @@
"deactivateSource": "ปิดใช้งานไซต์สต็อก", "deactivateSource": "ปิดใช้งานไซต์สต็อก",
"activateSourceConfirm": "ระบบจะตรวจสอบเงื่อนไขก่อนใช้งานจริงทั้งหมดก่อนเปิดใช้งานไซต์สต็อกนี้", "activateSourceConfirm": "ระบบจะตรวจสอบเงื่อนไขก่อนใช้งานจริงทั้งหมดก่อนเปิดใช้งานไซต์สต็อกนี้",
"deactivateSourceConfirm": "ไซต์นี้จะไม่เข้าร่วมการกำหนดเส้นทางหรือการส่งออกสต็อกใหม่ ต้องการดำเนินการต่อหรือไม่?", "deactivateSourceConfirm": "ไซต์นี้จะไม่เข้าร่วมการกำหนดเส้นทางหรือการส่งออกสต็อกใหม่ ต้องการดำเนินการต่อหรือไม่?",
"configurationTest": "ส่งออกทดสอบ", "configurationTestHint": "ไฟล์ทดสอบใช้ตรวจสอบการเชื่อมต่อ โครงสร้างไฟล์ และแผนการแยกวิเคราะห์ไฟล์สต็อกเท่านั้น และจะไม่เข้าสู่การจับคู่หรือการส่งออกจริง", "startConfigurationTest": "ส่งออกทดสอบ", "configurationTestRunning": "กำลังทดสอบ...", "configurationTestFailed": "การส่งออกทดสอบไซต์สต็อกล้มเหลว", "configurationTestNoRecommendation": "ไม่พบแผนการแยกวิเคราะห์ไฟล์สต็อกที่เผยแพร่แล้วซึ่งใช้ได้โดยตรง โปรดสร้างหรือปรับปรุงแผนจากผลการทดสอบ", "confirmTestProfile": "ยืนยันและผูกแผนการแยกวิเคราะห์นี้", "configurationTestProfileConfirmed": "ยืนยันแผนการแยกวิเคราะห์ไฟล์สต็อกแล้ว และไซต์สต็อกยังคงปิดใช้งาน", "configurationTestStage": { "waiting_worker": "กำลังรอ RPA Worker", "analysing_structure": "กำลังระบุโครงสร้างไฟล์สต็อก", "ready_for_confirmation": "ทดสอบเสร็จแล้ว รอยืนยันแผนการแยกวิเคราะห์ไฟล์สต็อก", "failed": "ทดสอบล้มเหลว" }, "configurationTest": "ส่งออกทดสอบ", "configurationTestHint": "ไฟล์ทดสอบใช้ตรวจสอบการเชื่อมต่อ โครงสร้างไฟล์ และแผนการแยกวิเคราะห์ไฟล์สต็อกเท่านั้น และจะไม่เข้าสู่การจับคู่หรือการส่งออกจริง", "startConfigurationTest": "ส่งออกทดสอบ", "configurationTestRunning": "กำลังทดสอบ...", "configurationTestRunNo": "หมายเลขการทดสอบ", "configurationTestConfigVersion": "เวอร์ชันการตั้งค่าไซต์", "configurationTestConnectionVersion": "เวอร์ชันการตั้งค่าการเชื่อมต่อ", "configurationTestUpdatedAt": "อัปเดตล่าสุด", "configurationTestFailed": "การส่งออกทดสอบไซต์สต็อกล้มเหลว", "configurationTestNoRecommendation": "ไม่พบแผนการแยกวิเคราะห์ไฟล์สต็อกที่เผยแพร่แล้วซึ่งใช้ได้โดยตรง โปรดสร้างหรือปรับปรุงแผนจากผลการทดสอบ", "confirmTestProfile": "ยืนยันและผูกแผนการแยกวิเคราะห์นี้", "configurationTestProfileConfirmed": "ยืนยันแผนการแยกวิเคราะห์ไฟล์สต็อกแล้ว และไซต์สต็อกยังคงปิดใช้งาน", "configurationTestStage": { "waiting_worker": "กำลังรอ RPA Worker", "analysing_structure": "กำลังระบุโครงสร้างไฟล์สต็อก", "ready_for_confirmation": "ทดสอบเสร็จแล้ว รอยืนยันแผนการแยกวิเคราะห์ไฟล์สต็อก", "failed": "ทดสอบล้มเหลว" },
"connectionBoundary": "กรอกเฉพาะข้อมูลเข้าสู่ระบบ ระบบจะดำเนินการหน้าเว็บ ดาวน์โหลด และรอตามแพลตฟอร์มผู้ให้บริการที่เลือกโดยอัตโนมัติ", "connectionBoundary": "กรอกเฉพาะข้อมูลเข้าสู่ระบบ ระบบจะดำเนินการหน้าเว็บ ดาวน์โหลด และรอตามแพลตฟอร์มผู้ให้บริการที่เลือกโดยอัตโนมัติ",
"platform": { "dbs": "DBS", "crane": "Crane" }, "platform": { "dbs": "DBS", "crane": "Crane" },
"sourceCode": "หมายเลขแหล่งสต็อก", "sourceCode": "หมายเลขแหล่งสต็อก",
+25
View File
@@ -220,6 +220,23 @@
"fileFormat": "文件格式", "fileFormat": "文件格式",
"inventorySampleFile": "库存样本文件", "inventorySampleFile": "库存样本文件",
"inventorySampleFileHint": "上传 .xls、.xlsx 或 .csv 后,系统会读取工作表、表头和少量样例,供确认库存解析。", "inventorySampleFileHint": "上传 .xls、.xlsx 或 .csv 后,系统会读取工作表、表头和少量样例,供确认库存解析。",
"savedInventorySample": "已保存的库存样本证据",
"savedInventorySampleHint": "系统仅保留表头、结构统计和脱敏样例;您可以直接继续维护当前库存映射,无需重新上传原文件。",
"pendingInventorySampleReplacement": "待确认的替换样本",
"pendingInventorySampleReplacementHint": "这份样本尚未替换当前审计证据;请核对下方差异并保存确认。",
"sampleFileName": "原始文件名",
"sampleRowsRetained": "保留的脱敏样例行",
"replaceInventorySample": "替换库存样本",
"replaceInventorySampleHint": "系统会先比较表头和当前映射;确认前不会替换已保存证据。",
"replaceInventorySampleConfirm": "已核对结构差异,确认用新样本替换当前草稿的样本证据吗?原样本仍保留在审计历史中。",
"confirmSampleReplacement": "确认替换",
"sampleReplacementReady": "新样本与当前映射兼容;保存时仍需确认替换。",
"sampleReplacementMappingRequired": "新样本缺少当前映射栏位:{columns}。请先调整字段映射后再保存。",
"sampleReplacementFileFormatChanged": "新样本文件格式与当前库存映射不一致,不能替换。",
"sampleReplacementCannotConfirm": "新样本尚未满足替换条件,请先处理提示的字段映射差异。",
"sampleReplacementAddedColumns": "新增栏位:{columns}",
"sampleReplacementMissingColumns": "缺少原样本栏位:{columns}",
"sampleReplacementColumnOrderChanged": "栏位顺序已变化。",
"inventorySampleAnalysing": "正在分析库存文件结构...", "inventorySampleAnalysing": "正在分析库存文件结构...",
"inventorySampleRequired": "请先上传库存样本文件并完成结构识别。", "inventorySampleRequired": "请先上传库存样本文件并完成结构识别。",
"parsingProfileName": "库存解析名称", "parsingProfileName": "库存解析名称",
@@ -352,6 +369,10 @@
"parsingProfileGeneratedByTest": "保存站点后,通过测试导出识别或确认库存解析。", "parsingProfileGeneratedByTest": "保存站点后,通过测试导出识别或确认库存解析。",
"sourceSavedDisabledHint": "首次保存后站点保持停用;请完成测试导出、库存解析和发货模板配置后再启用。", "sourceSavedDisabledHint": "首次保存后站点保持停用;请完成测试导出、库存解析和发货模板配置后再启用。",
"activationStatus": "正式运行检查", "activationStatus": "正式运行检查",
"readinessProgress": "{passed} / {total} 已完成",
"readinessState": { "passed": "已完成", "required": "需要完成", "waiting": "待完成前置步骤", "failed": "检查未通过,请重新处理", "stale": "配置已变更,请重新测试" },
"readinessAction": { "configure_connection": "配置连接", "configure_parsing_profile": "配置解析", "configure_excel_template": "配置模板", "configure_warehouse_mapping": "配置仓库映射" },
"saveBeforeReadinessAction": "请先保存当前库存站点更改,再执行此操作。",
"activationReady": "库存站点已启用,可进入正式库存运行。", "activationReady": "库存站点已启用,可进入正式库存运行。",
"activationDraft": "库存站点当前停用;完成以下项目后才可启用。", "activationDraft": "库存站点当前停用;完成以下项目后才可启用。",
"activationRequirement": { "rpa_profile": "系统连接可用", "parsing_profile": "库存解析", "excel_template": "发货模板", "configuration_test": "测试导出与解析验证", "parsing_validation": "测试文件中的料号、预约号和库存数量解析有效", "warehouse_identification": "测试文件中可识别货代仓库", "warehouse_mapping": "已维护货代仓库到外部系统仓库的映射", "template_validation": "发货模板引用的库存字段可由库存解析提供" }, "activationRequirement": { "rpa_profile": "系统连接可用", "parsing_profile": "库存解析", "excel_template": "发货模板", "configuration_test": "测试导出与解析验证", "parsing_validation": "测试文件中的料号、预约号和库存数量解析有效", "warehouse_identification": "测试文件中可识别货代仓库", "warehouse_mapping": "已维护货代仓库到外部系统仓库的映射", "template_validation": "发货模板引用的库存字段可由库存解析提供" },
@@ -363,6 +384,10 @@
"configurationTestHint": "测试文件只用于验证连接、文件结构和库存解析,不会进入正式库存匹配或发货导出。", "configurationTestHint": "测试文件只用于验证连接、文件结构和库存解析,不会进入正式库存匹配或发货导出。",
"startConfigurationTest": "测试导出", "startConfigurationTest": "测试导出",
"configurationTestRunning": "测试进行中...", "configurationTestRunning": "测试进行中...",
"configurationTestRunNo": "测试编号",
"configurationTestConfigVersion": "站点配置版本",
"configurationTestConnectionVersion": "连接配置版本",
"configurationTestUpdatedAt": "最后更新时间",
"configurationTestFailed": "库存站点测试导出失败。", "configurationTestFailed": "库存站点测试导出失败。",
"configurationTestNoRecommendation": "未找到可直接采用的已发布库存解析;请根据测试结果创建或完善库存解析。", "configurationTestNoRecommendation": "未找到可直接采用的已发布库存解析;请根据测试结果创建或完善库存解析。",
"confirmTestProfile": "确认并绑定此库存解析", "confirmTestProfile": "确认并绑定此库存解析",
+22 -1
View File
@@ -219,6 +219,23 @@
"fileFormat": "檔案格式", "fileFormat": "檔案格式",
"inventorySampleFile": "庫存樣本檔案", "inventorySampleFile": "庫存樣本檔案",
"inventorySampleFileHint": "上傳 .xls、.xlsx 或 .csv 後,系統會讀取工作表、表頭與少量樣例,供確認庫存解析。", "inventorySampleFileHint": "上傳 .xls、.xlsx 或 .csv 後,系統會讀取工作表、表頭與少量樣例,供確認庫存解析。",
"savedInventorySample": "已儲存的庫存樣本證據",
"savedInventorySampleHint": "系統僅保留表頭、結構統計和去識別樣例;可直接繼續維護目前的庫存映射,不必重新上傳原始檔案。",
"pendingInventorySampleReplacement": "待確認的替換樣本",
"pendingInventorySampleReplacementHint": "這份樣本尚未替換目前的稽核證據;請核對下方差異並儲存確認。",
"sampleFileName": "原始檔案名稱",
"sampleRowsRetained": "保留的去識別樣例列",
"replaceInventorySample": "替換庫存樣本",
"replaceInventorySampleHint": "系統會先比較表頭和目前映射;確認前不會替換已儲存證據。",
"replaceInventorySampleConfirm": "已核對結構差異,確定用新樣本替換目前草稿的樣本證據嗎?原樣本仍保留在稽核歷史中。",
"confirmSampleReplacement": "確認替換",
"sampleReplacementReady": "新樣本與目前映射相容;儲存時仍須確認替換。",
"sampleReplacementMappingRequired": "新樣本缺少目前映射欄位:{columns}。請先調整欄位映射後再儲存。",
"sampleReplacementFileFormatChanged": "新樣本檔案格式與目前庫存映射不一致,不能替換。",
"sampleReplacementCannotConfirm": "新樣本尚未符合替換條件,請先處理提示的欄位映射差異。",
"sampleReplacementAddedColumns": "新增欄位:{columns}",
"sampleReplacementMissingColumns": "缺少原樣本欄位:{columns}",
"sampleReplacementColumnOrderChanged": "欄位順序已變更。",
"inventorySampleAnalysing": "正在分析庫存檔案結構...", "inventorySampleAnalysing": "正在分析庫存檔案結構...",
"inventorySampleRequired": "請先上傳庫存樣本檔案並完成結構識別。", "inventorySampleRequired": "請先上傳庫存樣本檔案並完成結構識別。",
"parsingProfileName": "庫存解析名稱", "parsingProfileName": "庫存解析名稱",
@@ -346,6 +363,10 @@
"parsingProfileGeneratedByTest": "儲存站點後,透過測試匯出識別或確認庫存解析。", "parsingProfileGeneratedByTest": "儲存站點後,透過測試匯出識別或確認庫存解析。",
"sourceSavedDisabledHint": "首次儲存後站點保持停用;請完成測試匯出、庫存解析與出貨範本設定後再啟用。", "sourceSavedDisabledHint": "首次儲存後站點保持停用;請完成測試匯出、庫存解析與出貨範本設定後再啟用。",
"activationStatus": "正式執行檢查", "activationStatus": "正式執行檢查",
"readinessProgress": "已完成 {passed} / {total}",
"readinessState": { "passed": "已完成", "required": "需要完成", "waiting": "等待前置步驟完成", "failed": "檢查未通過,請重新處理", "stale": "設定已變更,請重新測試" },
"readinessAction": { "configure_connection": "設定連線", "configure_parsing_profile": "設定解析", "configure_excel_template": "設定範本", "configure_warehouse_mapping": "設定倉庫對應" },
"saveBeforeReadinessAction": "請先儲存目前庫存站點的變更,再執行此操作。",
"activationReady": "庫存站點已啟用,可進入正式庫存執行。", "activationReady": "庫存站點已啟用,可進入正式庫存執行。",
"activationDraft": "庫存站點目前停用;完成以下項目後才可啟用。", "activationDraft": "庫存站點目前停用;完成以下項目後才可啟用。",
"activationRequirement": { "rpa_profile": "系統連線可用", "parsing_profile": "庫存解析", "excel_template": "出貨範本", "configuration_test": "測試匯出與解析驗證", "parsing_validation": "測試檔案中的料號、預約號與庫存數量可正確解析", "warehouse_identification": "測試檔案可識別貨代倉庫", "warehouse_mapping": "已維護貨代倉庫至外部系統倉庫的對應", "template_validation": "出貨範本引用的庫存欄位可由庫存解析提供" }, "activationRequirement": { "rpa_profile": "系統連線可用", "parsing_profile": "庫存解析", "excel_template": "出貨範本", "configuration_test": "測試匯出與解析驗證", "parsing_validation": "測試檔案中的料號、預約號與庫存數量可正確解析", "warehouse_identification": "測試檔案可識別貨代倉庫", "warehouse_mapping": "已維護貨代倉庫至外部系統倉庫的對應", "template_validation": "出貨範本引用的庫存欄位可由庫存解析提供" },
@@ -353,7 +374,7 @@
"deactivateSource": "停用庫存站點", "deactivateSource": "停用庫存站點",
"activateSourceConfirm": "系統將複核正式執行前置條件;全部通過後才會啟用庫存站點。", "activateSourceConfirm": "系統將複核正式執行前置條件;全部通過後才會啟用庫存站點。",
"deactivateSourceConfirm": "停用後不再參與新的庫存路由與匯出任務,是否繼續?", "deactivateSourceConfirm": "停用後不再參與新的庫存路由與匯出任務,是否繼續?",
"configurationTest": "測試匯出", "configurationTestHint": "測試檔案僅用於驗證連線、檔案結構與庫存解析,不會進入正式庫存匹配或出貨匯出。", "startConfigurationTest": "測試匯出", "configurationTestRunning": "測試進行中...", "configurationTestFailed": "庫存站點測試匯出失敗。", "configurationTestNoRecommendation": "找不到可直接採用的已發布庫存解析;請根據測試結果建立或完善庫存解析。", "confirmTestProfile": "確認並繫結此庫存解析", "configurationTestProfileConfirmed": "已確認庫存解析,庫存站點仍保持停用。", "configurationTestStage": { "waiting_worker": "等待 RPA Worker 接收測試任務", "analysing_structure": "正在識別庫存檔案結構", "ready_for_confirmation": "測試完成,等待確認庫存解析", "failed": "測試失敗" }, "configurationTest": "測試匯出", "configurationTestHint": "測試檔案僅用於驗證連線、檔案結構與庫存解析,不會進入正式庫存匹配或出貨匯出。", "startConfigurationTest": "測試匯出", "configurationTestRunning": "測試進行中...", "configurationTestRunNo": "測試編號", "configurationTestConfigVersion": "站點設定版本", "configurationTestConnectionVersion": "連線設定版本", "configurationTestUpdatedAt": "最後更新時間", "configurationTestFailed": "庫存站點測試匯出失敗。", "configurationTestNoRecommendation": "找不到可直接採用的已發布庫存解析;請根據測試結果建立或完善庫存解析。", "confirmTestProfile": "確認並繫結此庫存解析", "configurationTestProfileConfirmed": "已確認庫存解析,庫存站點仍保持停用。", "configurationTestStage": { "waiting_worker": "等待 RPA Worker 接收測試任務", "analysing_structure": "正在識別庫存檔案結構", "ready_for_confirmation": "測試完成,等待確認庫存解析", "failed": "測試失敗" },
"connectionBoundary": "連線設定只填寫登入所需資訊;系統會依貨代平台自動執行頁面操作、下載與等待。", "connectionBoundary": "連線設定只填寫登入所需資訊;系統會依貨代平台自動執行頁面操作、下載與等待。",
"platform": { "dbs": "DBS 平台", "crane": "Crane 平台" }, "platform": { "dbs": "DBS 平台", "crane": "Crane 平台" },
"sourceCode": "庫存來源編號", "sourceCode": "庫存來源編號",
+315
View File
@@ -38,6 +38,321 @@ Windows test/prod 部署脚本:`scripts/rpa/set_rpa_worker_env.ps1`(详见 `
`SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。历史 `FREIGHT_RPA_*`、`SHIPPING_RPA_*` `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY`。历史 `FREIGHT_RPA_*`、`SHIPPING_RPA_*`
仅在迁移期兼容读取,不得用于新部署。 仅在迁移期兼容读取,不得用于新部署。
## 部署、启动与停止手册
本节说明库存 RPA 测试导出的三种运行方式:
| 场景 | Linux 后端 | Windows Worker | 适用范围 |
|------|------------|----------------|----------|
| Windows 本地联调 | 当前项目本地后端 | 当前项目 `scripts/rpa/` | 开发、调试、一次性测试导出;不使用 SMB 和任务计划 |
| Linux 测试环境 | `.env.test` + `/mnt/hxops-rpa-test-data` | `C:\HxopsRpaTest` | 测试库存站点的配置测试导出和验收 |
| Linux 正式环境 | `.env.prod` + `/mnt/hxops-rpa-prod-data` | `C:\HxopsRpaProd` | 已审核库存站点的正式库存导出 |
### 运行架构与职责
```text
Linux HXOPS 后端 Windows RPA Worker
---------------- ------------------
写 inventory_triggers/*.json --SMB--> 轮询 trigger,登录 DBS/Crane
接收 /rpa/* 回调 <--HTTPS-- 下载 Excel、写 inventory_drop、回调
读取 inventory_drop/*.xlsx --SMB--> 共享目录中的导出结果
```
- 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。
### 部署前检查
所有环境均需确认以下条件:
1. Windows RPA 终端可手工访问 DBS/Crane,网络、代理、证书、SSO/MFA 均已准备好。
2. Python 使用 3.12;`python --version` 和 `python -m pip --version` 可执行。
3. Windows 到对应 HXOPS 后端 `HXOPS_API_BASE` 的 HTTPS/HTTP 网络可达;Linux 后端到 Windows SMB 共享可读写。
4. RPA Profile 凭据主密钥 `SHIPPING_NOTICE_RPA_CREDENTIAL_KEY` 已通过 Jenkins、Secret 管理器或受控运维渠道提供,且 Windows Worker 与**同一环境**后端值一致。
5. `SHIPPING_NOTICE_TOOL_API_KEY` 与对应后端一致。不得把 Key、Fernet 主密钥、DSV/Crane 密码写入本 README、`.env` 提交内容、命令历史、截图或 Worker 日志。
6. 正式环境还必须确认库存站点已启用,并已绑定 published 库存文件解析方案;配置测试导出只能对停用站点发起,不能把测试文件当作正式库存快照。
### Windows 本地:直接在当前项目目录测试
这是最简方式,适用于在当前项目根目录运行本地后端和 RPA Worker。无需创建 `C:\HxopsRpaTest`、SMB 共享或计划任务;关闭 PowerShell 或按 `Ctrl+C` 即停止 Worker。
#### 1. 启动本地后端
在第一个 PowerShell 中,从项目根目录启动后端:
```powershell
cd backend
.\venv\Scripts\Activate.ps1
python run.py
```
默认 API Base 为 `http://127.0.0.1:5052`。若本地端口不是 5052,后续 Worker 的 `HXOPS_API_BASE` 必须同步修改。
#### 2. 安装 Worker 依赖
在第二个 PowerShell 中回到项目根目录。首次执行时安装 Python 库和 Playwright 浏览器:
```powershell
python -m pip install -r backend\requirements.txt
python -m pip install playwright
python -m playwright install chromium
```
如使用本机 Edge,可设置 `SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL=msedge`,无需让 Worker 下载 Chromium;仍建议保留 Playwright Python 包。
#### 3. 配置当前 PowerShell 会话并启动 Worker
Worker 不会自动加载 `.env.dev`,以下命令明确把四个目录指向当前项目的 `backend/data/shipping_notice/freight_rpa`。密钥使用占位符表示,实际值仅从本机受控 Secret 渠道注入。
```powershell
cd <项目根目录>
$repoRoot = (Get-Location).Path
$rpaDataRoot = Join-Path $repoRoot "backend\data\shipping_notice\freight_rpa"
$env:HXOPS_API_BASE = "http://127.0.0.1:5052"
$env:SHIPPING_NOTICE_TOOL_API_KEY = "<本地 Tool API Key>"
$env:SHIPPING_NOTICE_RPA_CREDENTIAL_KEY = "<本地 RPA 凭据主密钥>"
$env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT = "dev"
$env:SHIPPING_NOTICE_RPA_WORKER_MOCK = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_HEADLESS = "false"
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL = "msedge"
$env:SHIPPING_NOTICE_RPA_WORKER_POLL_SECONDS = "3"
$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR = Join-Path $rpaDataRoot "inventory_triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR = Join-Path $rpaDataRoot "inventory_drop"
$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR = Join-Path $rpaDataRoot "upload_triggers"
$env:SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR = Join-Path $rpaDataRoot "upload_queue"
$env:SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR = Join-Path $rpaDataRoot "browser_profile"
$env:SHIPPING_NOTICE_RPA_WORKER_LOG_FILE = Join-Path $rpaDataRoot "logs\worker.log"
python scripts\rpa\freight_rpa_worker.py
```
若只验证 trigger 扫描、文件流转与回调而不访问真实货代网站,可把 `SHIPPING_NOTICE_RPA_WORKER_MOCK` 设为 `true`。真实库存导出保持 `false`,并在本机受控环境中提供 DSV/Crane 账号或使用平台下发的加密 Profile 凭据。
#### 4. 验证与停止
启动成功会输出 `[freight_rpa_worker] started`。另开一个 PowerShell 检查实时日志、trigger 和导出目录:
```powershell
Get-Content "$rpaDataRoot\logs\worker.log" -Tail 100 -Wait
Get-ChildItem "$rpaDataRoot\inventory_triggers"
Get-ChildItem "$rpaDataRoot\inventory_drop"
```
从管理端发起一次测试导出;成功后 trigger 会被移入 `inventory_triggers\processed`,导出文件位于 `inventory_drop`,后端会收到 RPA 回调。测试结束时,在运行 Worker 的窗口按 `Ctrl+C`。若临时设置过敏感变量,关闭该 PowerShell 即可清除其进程环境,不要把值保存为用户级环境变量。
### Linux 测试环境:Windows Test Worker + SMB 共享
Linux 测试服务器上的 HXOPS 后端使用 `/mnt/hxops-rpa-test-data`,Windows 测试 Worker 使用 `C:\HxopsRpaTest\data`;两者必须是同一 SMB 共享 `hxops-rpa-test-data`。完整 Windows 目录、共享和权限创建步骤见 `docs/features/shipping-notice/technical.md` 的 §1.5.2 至 §1.5.5。
#### 1. Windows 测试 Worker 前置配置
在 Windows RPA 主机:
1. 创建 `C:\HxopsRpaTest\data\inventory_triggers`、`inventory_drop`、`upload_triggers`、`upload_queue`、`browser_profile`、`logs`,并将 `C:\HxopsRpaTest\data` 共享为 `hxops-rpa-test-data`。
2. 从当前仓库复制整个 `scripts\rpa` 目录到 `C:\HxopsRpaTest\scripts\rpa`,保证 Worker 引用的 driver、session、heartbeat 和公共模块版本一致;不要复制 `.env*`、旧浏览器 profile、旧 trigger、`processed` 或 `failed` 目录。
3. 安装依赖和浏览器运行时:
```powershell
cd C:\HxopsRpaTest
python -m pip install --upgrade pip
python -m pip install -r <项目仓库>\backend\requirements.txt playwright
python -m playwright install chromium
```
4. 使用受控方式设置 test 专属变量。推荐执行仓库提供的脚本,它会交互读取 Fernet 主密钥,避免在命令行中传入该密钥:
```powershell
cd C:\HxopsRpaTest
.\scripts\rpa\set_rpa_worker_env.ps1 -Environment test -ApiBase "http://<测试后端地址>:<端口>" -ToolApiKey "<测试 Tool API Key>"
```
重新打开 PowerShell 后,必须确认以下值:
```powershell
echo $env:SHIPPING_NOTICE_RPA_WORKER_ENVIRONMENT # test
echo $env:SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID # hxops-rpa-test-data
echo $env:SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR
echo $env:HXOPS_API_BASE
```
#### 2. Linux 测试服务器挂载和容器检查
首次部署需安装 `cifs-utils`,将 Windows 测试共享挂载到 `/mnt/hxops-rpa-test-data`,并通过 `/etc/fstab` 配置开机自动挂载。凭据文件权限必须为 `600`,后端服务用户必须有读写权限。示例(请替换主机、账号与 uid/gid):
```bash
sudo apt update
sudo apt install -y cifs-utils smbclient
sudo mkdir -p /mnt/hxops-rpa-test-data /etc/smbcredentials
sudo chmod 700 /etc/smbcredentials
# /etc/smbcredentials/hxops-rpa-test 内容仅在服务器本地维护:
# username=<Windows共享账号>
# password=<Windows共享密码>
# domain=WORKGROUP
sudo chmod 600 /etc/smbcredentials/hxops-rpa-test
sudo mount -t cifs //<Windows-RPA-IP>/hxops-rpa-test-data /mnt/hxops-rpa-test-data \
-o credentials=/etc/smbcredentials/hxops-rpa-test,vers=3.0,iocharset=utf8,uid=<hxops-uid>,gid=<hxops-gid>,file_mode=0775,dir_mode=0775
mountpoint -q /mnt/hxops-rpa-test-data
sudo -u hxops touch /mnt/hxops-rpa-test-data/inventory_triggers/linux_write_test.txt
sudo -u hxops rm /mnt/hxops-rpa-test-data/inventory_triggers/linux_write_test.txt
```
`.env.test` 必须指向 `/mnt/hxops-rpa-test-data`,scope 必须为 `hxops-rpa-test-data`。此外,`docker-compose.yml` 的 `hxops-backend` 必须将宿主机挂载目录 bind mount 到容器**同一路径**,否则容器内无法看到 RPA 文件:
```yaml
services:
hxops-backend:
volumes:
- /mnt/hxops-rpa-test-data:/mnt/hxops-rpa-test-data
```
在测试服务器项目根目录启动并验证容器:
```bash
export COMPOSE_ENV_BASENAME=.env.test
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
docker compose --env-file .env.test up -d hxops-backend hxops-kb-worker
docker compose --env-file .env.test ps
docker compose --env-file .env.test exec -T hxops-backend \
sh -lc 'test -d /mnt/hxops-rpa-test-data/inventory_triggers && ls -ld /mnt/hxops-rpa-test-data/inventory_triggers'
```
若这是首次把 bind mount 加入 Compose,必须在变更后重新创建后端容器:
```bash
docker compose --env-file .env.test up -d --force-recreate hxops-backend
```
#### 3. 启动、验证与停止测试 Worker
在 Windows RPA 主机打开 PowerShell:
```powershell
cd C:\HxopsRpaTest
python scripts\rpa\freight_rpa_worker.py
```
应同时验证以下四项后,再在管理端对**停用的库存站点**发起“测试导出”:
```powershell
# Windows:scope 和 Worker 日志
Get-Content C:\HxopsRpaTest\data\inventory_triggers\.hxops_rpa_shared_mount
Get-Content C:\HxopsRpaTest\data\logs\worker.log -Tail 100 -Wait
```
```bash
# Linux:同一哨兵必须可见;管理端还应显示 test Worker 在线
cat /mnt/hxops-rpa-test-data/inventory_triggers/.hxops_rpa_shared_mount
```
哨兵文件应包含 `scope_id=hxops-rpa-test-data`。若管理端显示离线,先检查 Worker 的 `HXOPS_API_BASE`、测试 Tool API Key、Linux 防火墙、Redis 和 scope;不要通过改成 prod scope 绕过检查。
停止测试导出服务时,先停止发起新的测试导出并处理正在执行的 trigger,再在 Windows Worker 窗口按 `Ctrl+C`。如果需要停止 HXOPS 测试后端:
```bash
export COMPOSE_ENV_BASENAME=.env.test
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
docker compose --env-file .env.test stop hxops-kb-worker hxops-backend
```
仅暂停 RPA 时,只停止 Windows test Worker,保持 SMB 挂载和 HXOPS 后端运行,方便查看回调与排障日志。
### Linux 正式环境:Windows Prod Worker + SMB 共享
正式环境的流程与测试环境相同,但资源必须全部切换为 prod。**禁止**复制 test 的 `.env`、Windows 环境变量、浏览器 profile 或共享目录后直接上线。
| 配置项 | 测试 | 正式 |
|--------|------|------|
| Windows 根目录 | `C:\HxopsRpaTest` | `C:\HxopsRpaProd` |
| SMB 共享 | `hxops-rpa-test-data` | `hxops-rpa-prod-data` |
| Linux 挂载目录 | `/mnt/hxops-rpa-test-data` | `/mnt/hxops-rpa-prod-data` |
| 后端环境文件 | `.env.test` | `.env.prod` |
| Worker environment | `test` | `prod` |
| shared scope | `hxops-rpa-test-data` | `hxops-rpa-prod-data` |
#### 1. 正式前置条件
1. 已在测试环境完成真实登录、文件下载、回调、结构校验和库存站点测试导出验收。
2. Windows `C:\HxopsRpaProd\data` 已作为 `hxops-rpa-prod-data` 共享,且 Linux 正式服务器仅挂载该共享。
3. `.env.prod` 使用正式 API Key、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data` 和 `/mnt/hxops-rpa-prod-data/*` 四个共享目录变量。
4. Windows Worker 使用 `-Environment prod` 设置用户级变量;其 Tool API Key 与 Fernet 主密钥只能来自正式 Secret 渠道。
5. 正式库存站点已启用并绑定 published 解析方案;真实上传 Driver 尚未验收时必须保持 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`。
在 Windows RPA 主机设置并启动 prod Worker:
```powershell
cd C:\HxopsRpaProd
.\scripts\rpa\set_rpa_worker_env.ps1 -Environment prod -ApiBase "http://<正式后端地址>:<端口>" -ToolApiKey "<正式 Tool API Key>"
# 关闭并重新打开 PowerShell 后执行
cd C:\HxopsRpaProd
python scripts\rpa\freight_rpa_worker.py
```
#### 2. 启动正式 Linux 后端并验证共享
在正式服务器项目根目录执行。前提是 `/mnt/hxops-rpa-prod-data` 已经通过受控 SMB 凭据挂载,且 `docker-compose.yml` 已有如下 bind mount:
```yaml
services:
hxops-backend:
volumes:
- /mnt/hxops-rpa-prod-data:/mnt/hxops-rpa-prod-data
```
```bash
mountpoint -q /mnt/hxops-rpa-prod-data
test -d /mnt/hxops-rpa-prod-data/inventory_triggers
export COMPOSE_ENV_BASENAME=.env.prod
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
docker compose --env-file .env.prod up -d hxops-backend hxops-kb-worker
docker compose --env-file .env.prod ps
docker compose --env-file .env.prod exec -T hxops-backend \
sh -lc 'test -d /mnt/hxops-rpa-prod-data/inventory_triggers && ls -ld /mnt/hxops-rpa-prod-data/inventory_triggers'
cat /mnt/hxops-rpa-prod-data/inventory_triggers/.hxops_rpa_shared_mount
```
哨兵内容必须包含 `scope_id=hxops-rpa-prod-data`,管理端 RPA Worker 状态页必须显示 prod Worker 在线,才可启用/恢复正式库存 RPA 排程。
#### 3. 正式停止与恢复顺序
计划维护或紧急停止时:
1. 先暂停正式库存 RPA 排程,并确认没有新的 trigger 被写入。
2. 等待当前 Worker 完成,或记录待人工处理的 trigger,再停止 Windows prod Worker(前台运行时按 `Ctrl+C`;若已配置计划任务则停止该任务)。
3. 仅在需要维护 HXOPS 时停止 Linux 容器:
```bash
export COMPOSE_ENV_BASENAME=.env.prod
export COMPOSE_SHARED_ENV_BASENAME=.env.shared
docker compose --env-file .env.prod stop hxops-kb-worker hxops-backend
```
恢复时严格按以下顺序:确认 SMB 挂载和容器内 bind mount正常 → 启动 Linux 后端与知识库 Worker → 启动 Windows prod Worker → 等待一次心跳和哨兵更新 → 管理端确认在线 → 恢复排程。不要用 test Worker 或 test 共享目录验证正式环境。
### 统一故障定位顺序
| 现象 | 先检查 | 常见处理 |
|------|--------|----------|
| 后端触发即提示 Worker 离线 | 管理端 Worker 状态、Worker 控制台、`HXOPS_API_BASE`、Tool API Key | 启动正确环境的 Windows Worker;检查网络和 Key,等待一个心跳周期 |
| `shared_sentinel_missing` 或 scope 不匹配 | `.hxops_rpa_shared_mount` 两端内容、`SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID` | Windows/Linux 使用相同环境的 scope;确认 Worker 有权写 trigger 目录 |
| Linux 宿主机可见共享但容器不可见 | `docker compose exec ... ls /mnt/hxops-rpa-*-data` | 为 `hxops-backend` 添加同路径 bind mount 并重建容器 |
| trigger 长期未处理 | Windows Worker 是否运行、实际 trigger 路径、`processed`/`failed`、Worker 日志 | 确认 test/prod 目录一致;不要手工把 JSON 复制到另一环境 |
| 登录失败 | Windows 手工登录、MFA/SSO、代理、证书、Worker 日志 | 先执行 DSV/Crane smoke,必要时人工完成认证后再重试 |
| 回调失败 | Worker 日志中的 HTTP 状态、后端日志、防火墙 | 核对对应环境 API Base/Key;确认 Windows 能访问 `/api/shipping-notice/rpa/*` |
| 导出文件被结构门禁阻断 | 管理端结构差异、库存站点绑定的 published 方案 | 修订并发布解析方案后重新测试;不得在生产运行期自动猜列 |
## 开发环境 Mock ## 开发环境 Mock
1. 在 `.env.dev` 配置目录与 Tool Key(见 `docs/features/shipping-notice/technical.md` §1)。 1. 在 `.env.dev` 配置目录与 Tool Key(见 `docs/features/shipping-notice/technical.md` §1)。