From 88408490d795c479bfeae6ab2ebb731992d4ce8a Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Sun, 19 Jul 2026 23:15:25 +0800 Subject: [PATCH] =?UTF-8?q?feat(shipping-notice):=20=E6=B7=BB=E5=8A=A0=20R?= =?UTF-8?q?PA=20=E5=B7=A5=E4=BD=9C=E8=80=85=E5=BF=83=E8=B7=B3=E5=91=8A?= =?UTF-8?q?=E8=AD=A6=E5=BC=80=E5=85=B3=EF=BC=8C=E6=9B=B4=E6=96=B0=E7=8E=AF?= =?UTF-8?q?=E5=A2=83=E9=85=8D=E7=BD=AE=E4=BB=A5=E6=94=AF=E6=8C=81=E6=A0=B7?= =?UTF-8?q?=E6=9C=AC=E8=AF=81=E6=8D=AE=E5=8E=86=E5=8F=B2=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.dev | 2 + .env.prod | 2 + .env.shared | 2 + .env.test | 2 + backend/app/api/admin/shipping_inventory.py | 18 + backend/app/core/config/settings.py | 2 +- .../app/models/shipping_inventory_config.py | 22 +- .../admin/shipping_inventory_service.py | 130 ++++++-- .../inventory_configuration_test.py | 84 ++++- .../inventory_parsing_profile.py | 95 +++++- .../inventory_structure_analysis.py | 100 +++++- .../rpa_worker_heartbeat_alert.py | 4 +- ...4e5f6_inventory_sample_evidence_history.py | 23 ++ .../fc1d2e3f4a5b_inventory_sample_evidence.py | 35 ++ ..._add_configuration_test_profile_version.py | 24 ++ .../admin/test_shipping_inventory_service.py | 52 ++- .../tests/test_admin_shipping_inventory.py | 30 ++ .../test_inventory_configuration_test.py | 105 +++++- .../tests/test_inventory_parsing_profile.py | 24 +- .../test_inventory_structure_analysis.py | 117 ++++++- docs/demand.md | 2 +- docs/features/shipping-notice/business.md | 2 +- docs/features/shipping-notice/technical.md | 143 +++++++- docs/funclist.md | 6 +- docs/tec.md | 2 +- frontend/src/features/admin/api/admin.api.ts | 45 ++- .../ShippingInventoryPage.vue | 246 ++++++++++++-- .../shippingInventoryReadiness.spec.ts | 36 ++ .../shippingInventoryReadiness.ts | 42 +++ frontend/src/locales/en/admin.json | 23 +- frontend/src/locales/th/admin.json | 23 +- frontend/src/locales/zh-CN/admin.json | 25 ++ frontend/src/locales/zh-TW/admin.json | 23 +- scripts/rpa/README.md | 315 ++++++++++++++++++ 34 files changed, 1697 insertions(+), 109 deletions(-) create mode 100644 backend/migrations/versions/a1b2c3d4e5f6_inventory_sample_evidence_history.py create mode 100644 backend/migrations/versions/fc1d2e3f4a5b_inventory_sample_evidence.py create mode 100644 backend/migrations/versions/fd2e3f4a5b6c_add_configuration_test_profile_version.py create mode 100644 frontend/src/features/admin/modules/shipping-inventory/shippingInventoryReadiness.spec.ts create mode 100644 frontend/src/features/admin/modules/shipping-inventory/shippingInventoryReadiness.ts diff --git a/.env.dev b/.env.dev index fbd88f08..71fe22b4 100644 --- a/.env.dev +++ b/.env.dev @@ -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"} # 本地 RPA(scripts/rpa/freight_rpa_worker.py) 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_SAMPLE_INVENTORY= # --- 10. 运维、告警与维护工具 --- diff --git a/.env.prod b/.env.prod index 4e5f81a9..f9ac1435 100644 --- a/.env.prod +++ b/.env.prod @@ -82,6 +82,8 @@ SHIPPING_NOTICE_INVENTORY_SNAPSHOT_TTL_HOURS=24 SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID=hxops-rpa-prod-data SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 +# 企微心跳告警总开关(默认关闭;需要时改为 true) +SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false # 运维必填其一:填写已绑企微的用户名,或确保至少一名 admin 已绑企微 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003 SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true diff --git a/.env.shared b/.env.shared index 9c84875a..feb040e7 100644 --- a/.env.shared +++ b/.env.shared @@ -158,6 +158,8 @@ SHIPPING_NOTICE_RPA_CREDENTIAL_KEY=XrYRm8hU6aPAo74TMOQLQdsYH6nKNm2a5R5LSSvwVns= SHIPPING_NOTICE_ORDER_EXTRACTION_TIMEOUT_SECONDS=300 # Freight RPA defaults to real browser automation. Set to true only for local mock/debug runs. 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_USERNAME=SBLL00001 diff --git a/.env.test b/.env.test index 5853d8ca..dbb2fc80 100644 --- a/.env.test +++ b/.env.test @@ -109,6 +109,8 @@ SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS=900 SHIPPING_NOTICE_RPA_UPLOAD_MAX_ATTEMPTS=3 SHIPPING_NOTICE_RPA_UPLOAD_TIMEOUT_SECONDS=30 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS=90 +# 企微心跳告警总开关(默认关闭;需要时改为 true) +SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false # 运维必填其一:填写已绑企微的用户名(逗号分隔),或确保至少一名 admin 已绑企微 # 两者皆无则告警只写日志、不会发企微 SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES=26050003 diff --git a/backend/app/api/admin/shipping_inventory.py b/backend/app/api/admin/shipping_inventory.py index 33331ed6..e51a2d5a 100644 --- a/backend/app/api/admin/shipping_inventory.py +++ b/backend/app/api/admin/shipping_inventory.py @@ -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) +@admin_bp.route('/shipping-notice/sources//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//test-export/', methods=['GET']) @require_admin 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//sample-replacement-preview/', 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//publish', methods=['POST']) @require_admin def publish_shipping_inventory_parsing_profile(profile_id: int): diff --git a/backend/app/core/config/settings.py b/backend/app/core/config/settings.py index 98378cee..2c5a1788 100644 --- a/backend/app/core/config/settings.py +++ b/backend/app/core/config/settings.py @@ -266,7 +266,7 @@ class Config: or '.hxops_rpa_shared_mount' ) 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( os.getenv('SHIPPING_NOTICE_RPA_WORKER_ALERT_COOLDOWN_SECONDS') or '1800' diff --git a/backend/app/models/shipping_inventory_config.py b/backend/app/models/shipping_inventory_config.py index 610cb5fe..ad6db547 100644 --- a/backend/app/models/shipping_inventory_config.py +++ b/backend/app/models/shipping_inventory_config.py @@ -126,7 +126,7 @@ class ShippingInventorySource(Base): class ShippingInventoryParsingProfile(Base): - """可跨库存源复用的库存文件结构与订单匹配配置。""" + """可跨库存源复用的库存文件结构、样本证据与订单匹配配置。""" __tablename__ = 'shipping_inventory_parsing_profiles' __table_args__ = ( @@ -147,16 +147,27 @@ class ShippingInventoryParsingProfile(Base): exact_structure_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) + # 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) published_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) published_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) sources: Mapped[list['ShippingInventorySource']] = relationship(back_populates='parsing_profile') + sample_analysis: Mapped[Optional['ShippingInventoryStructureAnalysis']] = relationship( + foreign_keys=[sample_analysis_id], + ) class ShippingInventoryStructureAnalysis(Base): - """库存文件结构分析记录;保存受控样例与建议,不承载正式库存快照。""" + """库存文件结构分析记录;保存脱敏结构证据,不承载正式库存快照。""" __tablename__ = 'shipping_inventory_structure_analyses' __table_args__ = ( @@ -169,13 +180,15 @@ class ShippingInventoryStructureAnalysis(Base): 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_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_format: Mapped[str] = mapped_column(String(16), nullable=False) 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) 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) + 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) exact_structure_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): - """库存站点配置测试的异步 RPA 运行;测试文件不能进入生产库存池。""" + """库存站点配置测试的异步 RPA 运行;锁定站点和连接配置版本且不进入生产库存池。""" __tablename__ = 'shipping_inventory_configuration_test_runs' __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) 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) + 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') 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) diff --git a/backend/app/services/admin/shipping_inventory_service.py b/backend/app/services/admin/shipping_inventory_service.py index 5b53d1c2..1891b245 100644 --- a/backend/app/services/admin/shipping_inventory_service.py +++ b/backend/app/services/admin/shipping_inventory_service.py @@ -406,7 +406,12 @@ def _test_analysis_validation(source: ShippingInventorySource) -> tuple[list[str source_config_version=source.config_version, ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() 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 analysis = db.session.get(ShippingInventoryStructureAnalysis, confirmed_test.analysis_id) 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 [] -def _activation_missing_requirements(source: ShippingInventorySource) -> tuple[list[str], dict[str, Any]]: - """计算库存站点进入正式运行前尚未完成的业务步骤和测试验证详情。""" - missing: list[str] = [] - if source.rpa_profile is None or not source.rpa_profile.enabled: - missing.append('rpa_profile') - if source.parsing_profile is None or source.parsing_profile.status != 'published': - missing.append('parsing_profile') - if source.excel_template is None or source.excel_template.status != 'published': - missing.append('excel_template') - else: - missing.extend(_template_validation_missing(source)) +def _latest_test_run_evidence(source: ShippingInventorySource) -> dict[str, Any]: + """提取最近一次配置测试的非敏感证据,供上线检查说明测试是否过期或失败。""" + run = ShippingInventoryConfigurationTestRun.query.filter_by( + inventory_source_id=source.id, + ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() + if run is None: + return {'state': 'not_started'} + profile_version = source.rpa_profile.config_version if source.rpa_profile is not None else None + if ( + run.source_config_version != source.config_version + 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) - missing.extend(validation_missing) - return missing, validation_details + missing = set(validation_missing) + 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]: - """返回库存站点启用检查结果,供管理端展示下一步操作。""" - 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 { 'ready': not missing, + 'checks': checks, '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.updated_by = actor_id - source.config_version += 1 db.session.commit() 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') source.enabled = False source.updated_by = actor_id - source.config_version += 1 db.session.commit() return _source_payload(source) diff --git a/backend/app/services/shipping_notice/inventory_configuration_test.py b/backend/app/services/shipping_notice/inventory_configuration_test.py index 7c039549..adde66e3 100644 --- a/backend/app/services/shipping_notice/inventory_configuration_test.py +++ b/backend/app/services/shipping_notice/inventory_configuration_test.py @@ -8,11 +8,11 @@ services/shipping_notice/inventory_configuration_test.py from __future__ import annotations -import shutil -from datetime import datetime +from datetime import datetime, timedelta from pathlib import Path from typing import Any +from flask import current_app from app.core.errors import ConflictError, NotFoundError, ValidationError from app.extensions import db from app.models import ( @@ -26,15 +26,56 @@ def _payload(run: ShippingInventoryConfigurationTestRun) -> dict[str, Any]: """投影测试运行状态,避免暴露 RPA 文件的服务器路径。""" return { '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, 'created_at': run.created_at.isoformat() if run.created_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]: - """为停用库存站点写入专用测试 trigger;重复点击复用等待中的运行。""" + """为停用库存站点写入专用测试 trigger;仅复用同一配置版本仍在运行的任务。""" source = db.session.get(ShippingInventorySource, source_id) if source is None: 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') if source.rpa_profile is None or not source.rpa_profile.enabled: raise ValidationError('Enabled RPA Profile is required', code='SHIPPING.RPA_PROFILE_DISABLED') + _expire_timed_out_runs(source) active = ShippingInventoryConfigurationTestRun.query.filter( 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']), ).order_by(ShippingInventoryConfigurationTestRun.id.desc()).first() 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 = ShippingInventoryConfigurationTestRun( 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, ) db.session.add(run) @@ -83,6 +128,10 @@ def get_test_run(source_id: int, run_no: str) -> dict[str, Any]: ).first() if run is None: 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) @@ -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() if run is None: 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) 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() db.session.commit() 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() db.session.commit() 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.models import ShippingInventoryStructureAnalysis 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_profile_matching import recommend_profiles run.status = 'processing'; run.stage = 'analysing_structure'; db.session.flush() suffix = resolve_inventory_upload_suffix(path.name) 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: - shutil.copy2(path, target) - structure, suggested, summary, warnings = _analyse_path(target, suffix) + # The RPA download is only read for analysis; configuration evidence never retains a second full workbook copy. + 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', [])) 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, - 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=[]), ) 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() db.session.commit() except Exception: - shutil.rmtree(target_dir, ignore_errors=True) db.session.rollback() raise 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) 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') - 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') 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.config_version += 1 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} db.session.commit() return {'test_run': _payload(run), 'parsing_profile_id': source.parsing_profile_id} diff --git a/backend/app/services/shipping_notice/inventory_parsing_profile.py b/backend/app/services/shipping_notice/inventory_parsing_profile.py index 74e6f7d4..c7124551 100644 --- a/backend/app/services/shipping_notice/inventory_parsing_profile.py +++ b/backend/app/services/shipping_notice/inventory_parsing_profile.py @@ -21,6 +21,7 @@ from app.models import ( ShippingInventoryField, ShippingInventoryParsingProfile, ShippingInventorySource, + ShippingInventoryStructureAnalysis, 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]: """序列化解析 Profile 管理 DTO。""" + sample_analysis = profile.sample_analysis return { 'id': profile.id, 'profile_code': profile.profile_code, 'display_name': profile.display_name, 'version': profile.version, 'status': profile.status, 'file_format': profile.file_format, 'definition': profile.definition_json or {}, 'checksum': profile.checksum, 'published_at': profile.published_at.isoformat() if profile.published_at else None, '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]: - """创建或更新解析 Profile 草稿;published 版本不可原地修改。""" + """创建或更新解析 Profile 草稿;必须绑定样本证据,published 版本不可原地修改。""" profile = db.session.get(ShippingInventoryParsingProfile, profile_id) if profile_id else None if profile_id and profile is None: 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) db.session.add(profile) profile.display_name = str(data.get('display_name') or code).strip() - profile.file_format = str(data.get('file_format') or 'xlsx').lower() - if profile.file_format not in {'xls', 'xlsx', 'csv'}: + requested_file_format = str(data.get('file_format') or 'xlsx').lower() + if requested_file_format not in {'xls', 'xlsx', 'csv'}: 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')) 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') + 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.sample_analysis = sample_analysis db.session.commit() 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') if profile.status != 'draft': 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 published_field_ids = { diff --git a/backend/app/services/shipping_notice/inventory_structure_analysis.py b/backend/app/services/shipping_notice/inventory_structure_analysis.py index a7cf78af..51f69c89 100644 --- a/backend/app/services/shipping_notice/inventory_structure_analysis.py +++ b/backend/app/services/shipping_notice/inventory_structure_analysis.py @@ -14,7 +14,7 @@ import re import shutil import uuid from collections import Counter -from datetime import datetime +from datetime import date, datetime from pathlib import Path 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 ( compatibility_fingerprint, exact_fingerprint, + normalise_header, structure_definition, ) @@ -92,6 +93,27 @@ def _value_type(values: list[Any]) -> str: 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]]: """生成来源栏位的业务预览,包括样例、空值率和建议字段。""" 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({ 'index': index, '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, 'inferred_type': _value_type(non_empty), 'duplicate': bool(header and duplicates[header] > 1), @@ -175,6 +197,7 @@ def _build_workbook_structure( 'header_row_index': header_index + 1, 'headers': headers, 'columns': _column_summary(headers, samples), + '_sample_rows': _sample_evidence_rows(samples), 'sample_row_count': len(samples), 'row_count_hint': row_count, 'score': score, @@ -184,14 +207,18 @@ def _build_workbook_structure( candidates.append(candidate) if not candidates: 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 = { '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_header_row_index': selected['header_row_index'], 'selected_headers': selected['headers'], 'selected_columns': selected['columns'], + 'selected_sample_rows': selected['_sample_rows'], } mapping = suggest_field_mapping(selected['headers'], as_catalog=True) summary = { @@ -251,7 +278,7 @@ def _csv_structure(path: Path) -> tuple[dict[str, Any], dict[str, str], dict[str return { 'sheets': [], 'candidates': [candidate], 'selected_sheet_name': None, '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, { 'candidate_count': 1, 'sample_row_count': len(samples), 'valid_inventory_field_suggestions': len(mapping), @@ -282,6 +309,7 @@ def serialize_analysis(item: ShippingInventoryStructureAnalysis) -> dict[str, An 'structure': item.structure_json or {}, 'suggested_mapping': item.suggested_mapping_json or {}, 'validation_summary': item.validation_summary_json or {}, + 'sample_rows': item.sample_rows_json or [], 'warnings': item.warning_json or [], 'match_result': item.match_result_json or {}, '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]: - """上传并分析管理员选择的库存样本文件,创建后端权威分析记录。""" + """上传并分析管理员库存样本,只持久化脱敏结构证据且立即清理完整原件。""" 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') 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, ) 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', 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), compatibility_fingerprint=compatibility_fingerprint( 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, 'compatibility_fingerprint': item.compatibility_fingerprint, }) - db.session.commit() - return serialize_analysis(item) + try: + 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]: @@ -347,11 +379,55 @@ def get_analysis(analysis_id: int) -> dict[str, Any]: 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]: - """用已分析的真实栏位创建库存文件解析方案草稿,禁止前端编造来源栏位。""" + """用已分析样本证据创建或更新草稿,禁止前端编造来源栏位或脱离样本保存。""" analysis = db.session.get(ShippingInventoryStructureAnalysis, analysis_id) if analysis is None: 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 {} 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') @@ -378,6 +454,8 @@ def create_profile_draft(analysis_id: int, data: dict[str, Any], *, actor_id: in 'profile_code': data.get('profile_code'), 'display_name': data.get('display_name'), 'file_format': analysis.file_format, + 'sample_analysis_id': analysis.id, + 'confirm_sample_replacement': bool(data.get('confirm_sample_replacement')), 'definition': { 'sheet_name': sheet_name, 'header_row_index': header_row_index, diff --git a/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py b/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py index 8a8a7916..a8d97339 100644 --- a/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py +++ b/backend/app/services/shipping_notice/rpa_worker_heartbeat_alert.py @@ -3,7 +3,7 @@ services/shipping_notice/rpa_worker_heartbeat_alert.py 用途:库存 RPA Worker 离线/恢复主动告警(企微 textcard + 冷却去重)。 依赖: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 @@ -46,7 +46,7 @@ def _config_bool(key: str, default: bool) -> bool: def _alert_enabled() -> bool: if not _heartbeat_check_required(): 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: diff --git a/backend/migrations/versions/a1b2c3d4e5f6_inventory_sample_evidence_history.py b/backend/migrations/versions/a1b2c3d4e5f6_inventory_sample_evidence_history.py new file mode 100644 index 00000000..d4449102 --- /dev/null +++ b/backend/migrations/versions/a1b2c3d4e5f6_inventory_sample_evidence_history.py @@ -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') diff --git a/backend/migrations/versions/fc1d2e3f4a5b_inventory_sample_evidence.py b/backend/migrations/versions/fc1d2e3f4a5b_inventory_sample_evidence.py new file mode 100644 index 00000000..6f2c107a --- /dev/null +++ b/backend/migrations/versions/fc1d2e3f4a5b_inventory_sample_evidence.py @@ -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) diff --git a/backend/migrations/versions/fd2e3f4a5b6c_add_configuration_test_profile_version.py b/backend/migrations/versions/fd2e3f4a5b6c_add_configuration_test_profile_version.py new file mode 100644 index 00000000..95af0aee --- /dev/null +++ b/backend/migrations/versions/fd2e3f4a5b6c_add_configuration_test_profile_version.py @@ -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') diff --git a/backend/tests/services/admin/test_shipping_inventory_service.py b/backend/tests/services/admin/test_shipping_inventory_service.py index 07dd28dd..d2771b41 100644 --- a/backend/tests/services/admin/test_shipping_inventory_service.py +++ b/backend/tests/services/admin/test_shipping_inventory_service.py @@ -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.order_schema import service as order_schema_service 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: @@ -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: """发布可由多个库存源共享的最小库存解析 Profile。""" state = order_schema_service.get_state() @@ -63,6 +83,7 @@ def _parsing_profile() -> dict: assert set(inventory_fields) == {'part_number', 'reservation_id', 'available_qty'} draft = inventory_parsing_profile.save_draft({ 'profile_code': 'COMMON_DBS', 'display_name': 'Common DBS', 'file_format': 'xlsx', + 'sample_analysis_id': _sample_evidence(), 'definition': { 'header_row_index': 1, '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'] +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): """启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。""" app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii') diff --git a/backend/tests/test_admin_shipping_inventory.py b/backend/tests/test_admin_shipping_inventory.py index 9ee5e850..fed5b699 100644 --- a/backend/tests/test_admin_shipping_inventory.py +++ b/backend/tests/test_admin_shipping_inventory.py @@ -176,3 +176,33 @@ def test_inventory_source_api_saves_new_source_disabled_and_activation_reports_m error = parse_api_error(activation.get_json()) assert error['code'] == 'SHIPPING.INVENTORY_SOURCE_ACTIVATION_BLOCKED' 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 diff --git a/backend/tests/test_inventory_configuration_test.py b/backend/tests/test_inventory_configuration_test.py index 804a8744..dcb4b443 100644 --- a/backend/tests/test_inventory_configuration_test.py +++ b/backend/tests/test_inventory_configuration_test.py @@ -2,6 +2,7 @@ from __future__ import annotations +from datetime import datetime, timedelta from pathlib import Path from unittest.mock import patch @@ -18,6 +19,7 @@ from app.models import ( ShippingExcelTemplate, ShippingInventoryFile, ShippingInventoryField, + ShippingRpaProfile, ShippingInventorySource, ) 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 +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): """确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。""" 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() 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 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): @@ -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) 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.parsing_profile_id = profile['id'] 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') unrelated = inventory_parsing_profile.save_draft({ 'profile_code': 'TEST_UNRELATED', 'display_name': 'Unrelated', 'file_format': 'xlsx', + 'sample_analysis_id': completed['analysis_id'], 'definition': { - 'sheet_name': 'Other', 'header_row_index': 1, + 'sheet_name': 'Sheet', 'header_row_index': 1, 'field_mapping': { - _inventory_field_id('part_number'): 'Other Part', - _inventory_field_id('reservation_id'): 'Other Reservation', - _inventory_field_id('available_qty'): 'Other Qty', + _inventory_field_id('part_number'): 'Supplier Sku', + _inventory_field_id('reservation_id'): 'Reservation ID', + _inventory_field_id('available_qty'): 'Qty Available', }, 'match_keys': [{'order_field_id': field_id, 'inventory_field_id': _inventory_field_id('part_number')}], }, diff --git a/backend/tests/test_inventory_parsing_profile.py b/backend/tests/test_inventory_parsing_profile.py index e6f87ecf..9f5059d6 100644 --- a/backend/tests/test_inventory_parsing_profile.py +++ b/backend/tests/test_inventory_parsing_profile.py @@ -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.order_schema import service as order_schema_service 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]: @@ -30,6 +30,21 @@ def _part_number_field_id() -> str: 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: """创建含 part_number 匹配键的 published 解析 Profile。""" order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None) @@ -44,6 +59,7 @@ def _published_profile() -> dict: ) draft = inventory_parsing_profile.save_draft({ 'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common', 'file_format': 'xlsx', + 'sample_analysis_id': _sample_evidence(headers=['Supplier Sku', 'Reservation ID', 'Qty Available']), 'definition': { 'header_row_index': 1, '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) draft = inventory_parsing_profile.save_draft({ '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'), '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) login = shipping_inventory_service.save_profile({ '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'] second_draft = inventory_parsing_profile.save_draft({ 'profile_code': 'DBS_COMMON', 'display_name': 'DBS Common v2', 'file_format': 'xlsx', + 'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']), 'definition': { + 'header_row_index': 1, 'field_mapping': _inventory_mapping(part='SKU', reservation='RSV', quantity='QTY'), '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_code': 'STALE_FIELD', 'display_name': 'Stale Field', + 'sample_analysis_id': _sample_evidence(headers=['SKU', 'RSV', 'QTY']), 'definition': { + 'sheet_name': None, 'header_row_index': 1, '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()}], }, diff --git a/backend/tests/test_inventory_structure_analysis.py b/backend/tests/test_inventory_structure_analysis.py index 3b1a09f1..d73bd77b 100644 --- a/backend/tests/test_inventory_structure_analysis.py +++ b/backend/tests/test_inventory_structure_analysis.py @@ -16,9 +16,10 @@ from werkzeug.datastructures import FileStorage import pytest 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.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: @@ -75,7 +76,7 @@ def _published_part_number() -> str: def test_sample_analysis_reads_real_worksheet_headers_and_suggestions(app, tmp_path): - """上传样本必须定位真实库存表头,并仅返回少量样例和值类型统计。""" + """上传样本必须定位真实库存表头,只持久化脱敏样例并清理完整工作簿。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') with app.app_context(): 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') assert qty['inferred_type'] == 'number' 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): @@ -158,6 +188,89 @@ def test_profile_draft_uses_analysis_header_selection(app, tmp_path): assert profile['status'] == 'draft' assert profile['definition']['sheet_name'] == 'Inventory' 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): diff --git a/docs/demand.md b/docs/demand.md index bc8333c0..e6288ba0 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -110,7 +110,7 @@ - 管理端必须使用后端字段目录和白名单提供结构化选择器,不要求业务管理员直接编辑 Profile/模板 JSON;发布新 Schema 版本时,若移除仍被路由、库存解析 Profile 或 Excel 模板引用的字段,必须阻断并要求先迁移下游配置。 - 发货 Excel 模板必须独立版本化管理并由库存源绑定 published 版本;多个同结构库存源共享同一模板,不得在库存源中复制映射。模板发布后文件和映射不可变。 - 库存站点允许先以禁用状态保存基础信息,逐步通过测试导出确认库存文件解析方案并绑定 published 发货模板;首次保存不要求手工选择解析方案。正式启用是独立门禁动作,必须完成连接、测试导出与解析验证、解析方案、发货模板和仓库映射;一旦启用,各项绑定必须齐全且有效。固定仓须维护该货代仓的精确映射或库存源默认映射;动态仓还须从测试文件识别仓库栏位并覆盖测试样例中的每个仓库。系统绝不根据名称相似度自动创建外部仓库映射。 -- 库存文件解析方案支持上传 `.xls` / `.xlsx` / `.csv` 样本;后端必须分析工作表、候选表头、真实列名、少量脱敏样例、类型与空值统计,并以结构化选择器供管理员确认。浏览器端不得作为发布依据,也不得要求管理员手输来源栏位。 +- 库存文件解析方案支持上传 `.xls` / `.xlsx` / `.csv` 样本;后端必须分析工作表、候选表头、真实列名、少量脱敏样例、类型与空值统计,并以结构化选择器供管理员确认。完整样本文件仅供即时分析,完成后立即清理;草稿及发布版本必须绑定并保留文件名、校验值、完整表头、结构指纹、统计和最多五行脱敏样例,供后续编辑与审计。浏览器端不得作为发布依据,也不得要求管理员手输来源栏位。 - 相同库存模板按文件结构及已发布方案实际使用的“库存匹配/库存数量”栏位确定性判断,不按文件名、库存数据内容或文件内容 hash 判断。完全一致可推荐复用已发布方案;仅新增无关栏位或非关键顺序变化时提示兼容差异;方案所需栏位缺失、重复或冲突不得复用。推荐方案必须由管理员确认,样本上传不得自动绑定库存站点。 - 停用库存站点可以发起异步测试导出。测试文件仅用于连接、文件结构和解析验证,不得进入正式库存快照、订单库存匹配、发货 Excel 或正式导出记录;管理员确认已发布解析方案后才更新该停用站点的绑定。 - 每次正式 RPA 导出在写入库存快照前都必须复核文件结构:完全一致正常入库;仅新增非关键栏位或顺序变化可入库并记录差异;格式、工作表、表头行、关键栏位或映射变化必须阻断入库和库存匹配。正式运行只能使用已发布解析方案的工作表、表头行和字段映射,不允许自动猜列兜底。 diff --git a/docs/features/shipping-notice/business.md b/docs/features/shipping-notice/business.md index 2491f30e..1bcb1ded 100644 --- a/docs/features/shipping-notice/business.md +++ b/docs/features/shipping-notice/business.md @@ -247,7 +247,7 @@ WYC26071501 | 仓库识别 | 仅按库存行动态识别仓库的站点需要,每个方案只能使用一个 | | 一般业务信息 | 按需创建,可写入发货模板,例如 ODM、批次、库位等;这些名称均不是系统内置 | -上传库存样本后,系统会读取工作表、表头和少量样例。字段名称与表头完全相同时可以自动预填;名称不同时,由管理员从下拉框选择,或让 Dify 根据真实表头给出候选,再由管理员确认。候选不会自动创建字段、发布方案或绑定库存站点。 +上传库存样本后,系统会读取工作表、表头和少量样例。完整 Excel 只用于本次即时分析,完成后不会长期保存;系统保留文件名、校验值、完整表头、结构统计和最多五行脱敏样例,作为该库存映射的配置证据。再次打开草稿时,系统从这份证据恢复工作表、表头下拉、字段映射和脱敏预览,管理员可以继续维护,无需重新上传文件;浏览器不会伪造“已选择原文件”。替换样本时,系统先展示新增/缺少栏位、顺序变化和会失效的当前映射;管理员调整映射并在平台确认弹窗确认后,才切换到新样本。旧样本不会删除,而是记录在该草稿的样本替换历史中。字段名称与表头完全相同时可以自动预填;名称不同时,由管理员从下拉框选择,或让 Dify 根据真实表头给出候选,再由管理员确认。候选不会自动创建字段、发布方案或绑定库存站点。 --- diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index f65574bc..f1d0fa41 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -408,9 +408,15 @@ GET /api/admin/shipping-order-schema/published-contract - `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`,均不保存显示名称或原始表头以外的技术字段。 - 管理端以结构化行编辑器维护标准库存字段、文件表头与订单行字段匹配键,所有可选项来自后端 `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 仅给候选。系统不得内置固定业务字段词典或自动创建字段。 - 停用库存站点通过 `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 中复制完整映射。 - 库存站点首次保存不要求绑定解析方案,且普通保存始终保持停用;后端仅允许通过独立启用接口进入正式运行。启用检查列出系统连接、库存文件解析方案、发货模板和测试导出与解析验证;确认后测试记录与站点当前配置版本绑定,后续编辑会使其失效。草稿、缺失或非法作用域字段仍阻断正式运行期自动解析。 - 启用检查复用确认测试的结构记录,按当前方案实际映射的用途验证:至少一个匹配字段样例非空、唯一数量字段为数值;发货模板的全部库存字段必须由该方案提供。固定仓要求精确 `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_HEARTBEAT_SECONDS` | `15`~`30`(默认 20) | 同左 | | 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_FALLBACK_ADMIN` | `true`(未配用户名时通知已绑企微的 admin) | 建议 `true` | | 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。 -心跳存储: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 登录: @@ -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_WORKER_HEARTBEAT_TTL_SECONDS=90 SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS=true +# 企微心跳告警默认关闭;需要时改为 true +SHIPPING_NOTICE_RPA_WORKER_ALERT_ENABLED=false # 逗号分隔已绑企微的 HXOPS 用户名;留空且 FALLBACK_ADMIN=true 时通知 admin SHIPPING_NOTICE_RPA_WORKER_ALERT_USERNAMES= SHIPPING_NOTICE_RPA_WORKER_ALERT_FALLBACK_ADMIN=true @@ -1081,6 +1090,136 @@ Register-ScheduledTask ` - Ubuntu 重启后目录空了:执行 `sudo mount -a`,检查 `/etc/fstab`、网络是否已就绪、Windows 共享是否可访问。 - 排程一直 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 前端入口 - 聊天界面仍是**主上传入口**,通知附件、库存附件与对话续办都优先在 Chat 完成 diff --git a/docs/funclist.md b/docs/funclist.md index 1ce05ce2..9616f365 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -80,9 +80,9 @@ | 动态订单字段驱动库存源路由 | 已实现 | 路由条件选择 published 订单稳定 field_id;运行时从 Task 当前 Extraction 的类型化 FieldValue 读取;系统事实仅保留受控枚举 | | 可复用库存解析 Profile | 已实现 | 管理端通过订单字段和库存标准字段结构化选择器版本化维护表头、列映射和 match_keys;多个 published 版本可并存,库存源显式迁移版本;引用中版本不可退役,正常库存源解析无需 LLM | | 库存字段目录 | 已实现 | 作为“库存映射”的子功能以空目录启动,字段名称、说明、格式、用途和顺序完全由用户维护;程序只控制匹配、数量、仓库识别和一般信息四种用途。解析方案、库存行、匹配键和发货模板全程使用库存字段目录 ID;未引用字段可物理删除,当前配置引用字段禁止删除、退役或改变能力用途 | -| 库存样本结构识别与方案复用 | 已实现 | 管理员上传 `.xls/.xlsx/.csv` 后由后端分析工作表、候选表头、真实栏位、少量样例、类型和空值率;同名用户字段可确定性预填,陌生表头由管理员选择或 Dify 给候选,不内置固定业务字段词典;已发布方案按实际使用的匹配/数量表头判断完全一致或兼容,确认只写审计、不自动绑定库存站点 | -| 库存站点测试导出 | 已实现 | 停用库存站点可发起异步 RPA 测试导出;测试文件仅用于结构识别和解析方案确认,不进入正式库存快照、订单匹配或发货导出;只能确认本次推荐的已发布方案,站点配置变更或启用后旧测试自动失效 | -| 库存站点启用验证与仓库映射门禁 | 已实现 | 启用前按用户字段用途复核至少一个匹配字段、唯一数量字段及动态仓唯一仓库识别字段,验证发货模板库存字段可由解析方案提供;固定仓要求精确或默认仓库映射,动态仓要求覆盖样例仓库;只提示缺失映射,绝不自动臆造 | +| 库存样本结构识别与方案复用 | 在建 | 管理员上传 `.xls/.xlsx/.csv` 后由后端分析工作表、候选表头、真实栏位、类型和空值率;样本原件即时分析后清理,草稿/发布版本绑定并保留文件校验值、结构指纹、完整表头和最多五行脱敏样例。再次打开草稿会恢复已保存样本结构、表头下拉和脱敏预览,无需重传原文件;替换样本先展示结构/映射差异,平台确认后才切换,并保留旧/新样本审计链;后续阶段补齐运行闭环;Dify 仅可提供陌生表头候选,不自动生效。 | +| 库存站点测试导出 | 已实现 | 停用库存站点可发起异步 RPA 测试导出;测试文件仅用于结构识别和解析方案确认,不进入正式库存快照、订单匹配或发货导出;只能确认本次推荐的已发布方案,库存站点测试输入或 RPA 连接配置变更后旧测试自动失效,单纯启用/停用不使同配置测试失效 | +| 库存站点启用验证与仓库映射门禁 | 已实现 | 启用前按用户字段用途复核至少一个匹配字段、唯一数量字段及动态仓唯一仓库识别字段,验证发货模板库存字段可由解析方案提供;固定仓要求精确或默认仓库映射,动态仓要求覆盖样例仓库;后端以结构化 `activation.checks` 返回状态、阻断、推荐动作与脱敏证据,配置变更后旧测试明确为 `stale`;只提示缺失映射,绝不自动臆造 | | 正式库存文件结构漂移门禁 | 已实现 | 每次 RPA 正式导出及缓存快照重读均用已绑定库存文件解析方案复核/解析格式、工作表、表头和核心栏位;完全一致放行,非关键栏位变化记录差异后放行,关键变化阻断快照和库存匹配;正式库存站点运行期不再自动猜列或接收 LLM 映射覆盖 | | 陌生表头 LLM 候选解释(Dify 手工配置) | 已文档化 | 默认关闭;用户明确声明对话附件为库存文件且后端无精确方案时,可对脱敏真实表头给出本次临时候选;管理员也可在库存文件解析方案草稿中主动请求候选。Dify 不能发布方案、绑定库存站点、创建仓库映射、调用旧库存映射 Tool 或放行结构漂移 | | 对话临时库存文件受控解析 | 已实现 | 用户上传 `.xls/.xlsx/.csv` 表格时必须先明确声明为库存文件,系统不会按后缀猜测用途;后端创建当前用户和当前聊天会话隔离的临时文件并确定性检查结构与库存最低特征。跨回合时由 HXOPS 数据库恢复最新待确认会话号,不依赖 Dify 隐式记忆;普通消息不会因此自动进入确认。无完全匹配方案时 Dify 只能基于真实表头、类型/空值率和字段目录提交受控候选映射,用户明确确认后仅锁定本次临时质量审计;不创建正式库存快照、不修改库存站点、不执行订单匹配。管理员可将确认会话沉淀为解析方案草稿,仍需走既有发布门禁 | diff --git a/docs/tec.md b/docs/tec.md index 28c50ce7..78529ab2 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -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读取模板,不读取全局模板环境变量,也不回退空白工作簿。 - **库存字段目录与确定性订单/库存关联**:库存字段目录独立于 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 版本并存,站点显式迁移后旧版本方可退役。 -- **库存样本结构分析**:`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,不能读取二进制、路径、样例值、全量行或直接宣布库存可用于匹配。已确认会话可由管理员沉淀为解析方案草稿,但不能自动发布或绑定库存站点。 - **方案复用**:结构分析与解析方案分别保存精确结构指纹和兼容指纹,均不包含库存业务数据或文件名。精确指纹覆盖格式、工作表、表头行、标准化列名及顺序;兼容判断验证既有方案实际使用的库存匹配与数量来源表头仍存在,并输出新增/缺少/顺序变化。后端不使用固定字段词典把“内部料号”猜成 `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`。确认方案时要求站点仍停用且配置版本未变化,成功后绑定解析方案并使测试记录追随新的配置版本;后续编辑站点自动使旧测试失效。 diff --git a/frontend/src/features/admin/api/admin.api.ts b/frontend/src/features/admin/api/admin.api.ts index 7e7dcf7d..00603b94 100644 --- a/frontend/src/features/admin/api/admin.api.ts +++ b/frontend/src/features/admin/api/admin.api.ts @@ -21,6 +21,38 @@ import type { const auth = () => ({ headers: 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; +}; + +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 => { 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`, { method: 'POST', body: JSON.stringify(payload), ...jsonAuth() }, ); +/** 样本替换先读取后端结构差异;管理员确认前不会改动草稿的审计证据。 */ +export const previewShippingInventorySampleReplacement = (profileId: number, analysisId: number, payload: Record = {}) => requestJson( + `/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( `/api/admin/shipping-notice/inventory-structure-analyses/${analysisId}/adopt-profile`, @@ -191,13 +228,17 @@ export const deactivateShippingInventorySource = (id: number) => requestJson requestJson( +export const startShippingInventoryConfigurationTest = (id: number) => requestJson( `/api/admin/shipping-notice/sources/${id}/test-export`, { method: 'POST', ...jsonAuth() }, ); /** 查询库存站点测试导出与结构识别的后端真实状态。 */ -export const getShippingInventoryConfigurationTest = (id: number, runNo: string) => requestJson( +export const getShippingInventoryConfigurationTest = (id: number, runNo: string) => requestJson( `/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}`, auth(), ); +/** 读取当前站点配置对应的最近测试,使刷新页面或重开抽屉时可恢复服务端真实状态。 */ +export const getLatestShippingInventoryConfigurationTest = (id: number) => requestJson( + `/api/admin/shipping-notice/sources/${id}/test-export/latest`, auth(), +); /** 管理员确认测试结果使用的已发布解析方案,才更新停用库存站点绑定。 */ export const confirmShippingInventoryConfigurationTestProfile = (id: number, runNo: string, profileId: number) => requestJson( `/api/admin/shipping-notice/sources/${id}/test-export/${encodeURIComponent(runNo)}/confirm-profile`, diff --git a/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue index a18747d8..a7155193 100644 --- a/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue +++ b/frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue @@ -138,27 +138,50 @@ -
- {{ t('admin.shippingInventory.activationStatus') }} -

{{ source.enabled ? t('admin.shippingInventory.activationReady') : t('admin.shippingInventory.activationDraft') }}

-
    -
  • {{ t(`admin.shippingInventory.activationRequirement.${requirement}`) }}
  • -
- - -
-
- {{ t('admin.shippingInventory.configurationTest') }} -

{{ t('admin.shippingInventory.configurationTestHint') }}

- +
+
+
+ {{ t('admin.shippingInventory.activationStatus') }} + {{ source.enabled ? t('admin.shippingInventory.activationReady') : t('admin.shippingInventory.activationDraft') }} +
+ {{ readinessSummary }} +
+
    +
  1. + +
    + {{ t(`admin.shippingInventory.activationRequirement.${check.code}`) }} + {{ readinessDetail(check) }} +
    + +
  2. +
+

{{ t('admin.shippingInventory.configurationTestHint') }}

+
+ + +
{{ t('admin.shippingInventory.sourceSavedDisabledHint') }}