diff --git a/.env.dev b/.env.dev index 2c7fa88e..3993cb4a 100644 --- a/.env.dev +++ b/.env.dev @@ -85,7 +85,7 @@ SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED=true SHIPPING_NOTICE_AUTO_MAPPING_ALLOW_LLM=true SHIPPING_NOTICE_AUTO_MATCH_ENABLED=true SHIPPING_NOTICE_AUTO_GENERATE_EXCEL_ENABLED=true -SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true +SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false # 工作台/聊天按钮兜底串联(Dify Agent 主路径见 features/shipping-notice/technical.md §2.4) SHIPPING_NOTICE_AUTO_CHAIN_FALLBACK=true SHIPPING_NOTICE_CHAT_DIFY_BASE=http://192.168.100.192:8882/v1 diff --git a/backend/app/api/shipping_notice_tools.py b/backend/app/api/shipping_notice_tools.py index a2b2c939..00d37031 100644 --- a/backend/app/api/shipping_notice_tools.py +++ b/backend/app/api/shipping_notice_tools.py @@ -249,7 +249,14 @@ def tool_ensure_inventory(): 保证任务已取得库存数据。 【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。 """ - return jsonify(shipping_tools.ensure_inventory(_payload())) + payload = _payload() + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + return jsonify(run_task_auto_progress( + task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(), + trigger='legacy_tool_ensure_inventory', + operator_id=payload.get('operator_id'), + resume_gate_code='inventory_preparation', + )) @shipping_notice_bp.route('/tools/auto_progress', methods=['POST']) def tool_auto_progress(): @@ -265,7 +272,14 @@ def tool_match_inventory(): 执行库存匹配。 【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。 """ - return jsonify(shipping_tools.match_inventory(_payload())) + payload = _payload() + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + return jsonify(run_task_auto_progress( + task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(), + trigger='legacy_tool_match_inventory', + operator_id=payload.get('operator_id'), + resume_gate_code='inventory_matching', + )) @shipping_notice_bp.route('/tools/submit_decision', methods=['POST']) def tool_submit_decision(): @@ -300,7 +314,14 @@ def tool_generate_shipment_excel(): 生成出货 Excel。 【AI 触发时机】:仅供后端主调度或内部恢复链路调用;不是 Dify 画布正式入口。 """ - return jsonify(shipping_tools.generate_excel(_payload())) + payload = _payload() + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + return jsonify(run_task_auto_progress( + task_no=str(payload.get('task_id') or payload.get('task_no') or '').strip(), + trigger='legacy_tool_generate_excel', + operator_id=payload.get('operator_id'), + resume_gate_code='artifact_generation', + )) @shipping_notice_bp.route('/tools/upload_to_freight', methods=['POST']) def tool_upload_to_freight(): diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index faa22fa8..9d2d1eca 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -1126,65 +1126,42 @@ def workspace_auto_progress_shipping_task(task_no: str): @workspace_shipping_notice_bp.route('/shipping-tasks//match-inventory', methods=['POST']) def workspace_match_shipping_inventory(task_no: str): - """执行库存匹配,并在生成 Excel 后补充前端可直接下载的链接。""" + """兼容旧匹配入口:只提交当前 Gate 自动推进,不直接执行库存匹配。""" user = _require_user() task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') _assert_fulfillment_task_ownership(task, user.id) - from app.services.shipping_notice import tools as shipping_tools - from app.services.shipping_notice.state_machine import action_buttons_for_checkpoint, human_options_for_checkpoint - matched = shipping_tools.match_inventory({ - 'task_id': task.task_no, - AUTO_CHAIN_FALLBACK: True, - '_trusted_user_id': user.id, - 'operator_id': user.id, - 'event_source': 'workspace_api', - }) - if not isinstance(matched, dict): - return _ok(matched) - data = matched.get('data') - if isinstance(data, dict) and data.get('export_file_path'): - matched = {**matched, 'data': {**data, 'download_url': f'/api/workspace/shipping-tasks/{task.task_no}/export'}} - checkpoint = matched.get('checkpoint') or CP_EXPORT_GENERATED - if matched.get('status') == 'ok' and data and data.get('export_file_path'): - matched['checkpoint'] = checkpoint - if 'human_options' not in matched: - options = human_options_for_checkpoint(checkpoint) - if options is not None: - matched['human_options'] = options - if 'action_buttons' not in matched: - # [STEP] 已有 ProcessExecution 时不再补充旧 STP 恢复按钮。 - from app.models import ShippingProcessExecution - has_execution = ( - ShippingProcessExecution.query - .filter_by(task_id=int(task.id)) - .first() - ) is not None - if not has_execution: - buttons = action_buttons_for_checkpoint(checkpoint) - if buttons: - matched['action_buttons'] = buttons - return _ok(matched) + from app.services.shipping_notice.auto_progress_controller import ( + audit_legacy_forwarded_entrypoint, + submit_auto_progress, + ) + audit_legacy_forwarded_entrypoint( + task=task, action_code='match_inventory', actor_id=user.id, + request_id=getattr(g, 'request_id', None), + ) + result = submit_auto_progress(task=task, trigger='legacy_match_inventory', operator_id=user.id) + return _ok({'deprecated': True, 'projection_refresh_required': True, **result}) @workspace_shipping_notice_bp.route('/shipping-tasks//generate-excel', methods=['POST']) def workspace_generate_shipping_excel(task_no: str): - """为指定任务生成出货 Excel,并补充工作台下载链接。""" + """兼容旧导出入口:只提交当前 Gate 自动推进,不直接生成 Excel。""" user = _require_user() task = get_task_for_user(task_no, user.id) if not task: raise NotFoundError('Not found') _assert_fulfillment_task_ownership(task, user.id) - from app.services.shipping_notice import tools as shipping_tools - result = shipping_tools.generate_excel({'task_id': task.task_no}) - if isinstance(result, dict) and result.get('status') == 'ok': - data = result.get('data') - if not isinstance(data, dict): - data = {} - result['data'] = data - data['download_url'] = f'/api/workspace/shipping-tasks/{task.task_no}/export' - return _ok(result) + from app.services.shipping_notice.auto_progress_controller import ( + audit_legacy_forwarded_entrypoint, + submit_auto_progress, + ) + audit_legacy_forwarded_entrypoint( + task=task, action_code='generate_excel', actor_id=user.id, + request_id=getattr(g, 'request_id', None), + ) + result = submit_auto_progress(task=task, trigger='legacy_generate_excel', operator_id=user.id) + return _ok({'deprecated': True, 'projection_refresh_required': True, **result}) @workspace_shipping_notice_bp.route('/shipping-tasks//mark-manual-uploaded', methods=['POST']) diff --git a/backend/app/jobs/handlers/shipping_auto_progress.py b/backend/app/jobs/handlers/shipping_auto_progress.py index fa70f206..50f2aa56 100644 --- a/backend/app/jobs/handlers/shipping_auto_progress.py +++ b/backend/app/jobs/handlers/shipping_auto_progress.py @@ -1,9 +1,10 @@ """ jobs/handlers/shipping_auto_progress.py -用途:消费 P0-3 Task 级 AutoProgress Job。 +用途:终态化历史 APX AutoProgress Job。 依赖:JobContext、auto_progress_controller。 -逻辑:Job 已由通用队列领取为 running;本 Handler 只委托正式控制器执行一个 Gate,不再调用旧全链路 facade。 +逻辑:Job 已由通用队列领取为 running;本 Handler 仅委托控制器取消遗留 APX + Job 并保留审计。正式 20-Gate 只能由 shipping_process_gate Handler 执行。 """ from __future__ import annotations @@ -16,7 +17,7 @@ from app.services.shipping_notice.auto_progress_controller import run_auto_progr @register_handler(JobType.SHIPPING_AUTO_PROGRESS) def run_shipping_auto_progress(ctx: JobContext, payload: dict) -> None: - """执行一个正式 Gate;payload 必须含队列注入的 job_id。""" + """终态化历史 APX Job;payload 必须含队列注入的 job_id。""" raw_job_id = payload.get('job_id') if not raw_job_id: raise RuntimeError('missing_job_id_for_shipping_auto_progress') diff --git a/backend/app/jobs/handlers/shipping_process_gate.py b/backend/app/jobs/handlers/shipping_process_gate.py index ee2abed0..2988ad39 100644 --- a/backend/app/jobs/handlers/shipping_process_gate.py +++ b/backend/app/jobs/handlers/shipping_process_gate.py @@ -5,7 +5,7 @@ backend/app/jobs/handlers/shipping_process_gate.py 依赖:JobContext、process_gate_job_service、process_gate_service、jobs.queue finish/fail、 process_gate_error_sanitizer。 逻辑:由 shipping worker 领取;技术失败按该 Attempt 下 failed Job 累计次数 + 5s/30s/120s 退避重新入队; - 次数耗尽时 fail_job 并 complete_gate_attempt(failed_terminal); + 次数耗尽时 fail_job 并 complete_gate_attempt(blocked_retryable),保留人工恢复入口; 不修改 input_snapshot_json,以保持 input_snapshot_hash 与正文一致; waiting_external 先结束当前 Job 再延迟入队新 Job; healthcheck_probe 载荷用于部署探针,不依赖真实 Attempt。 @@ -14,8 +14,6 @@ backend/app/jobs/handlers/shipping_process_gate.py from __future__ import annotations from flask import current_app -from sqlalchemy import or_ - from app import db from app.jobs.context import JobContext from app.jobs.queue import fail_job, finish_job @@ -30,80 +28,32 @@ from app.services.shipping_notice.process_gate_job_service import ( ) from app.services.shipping_notice.process_gate_service import complete_gate_attempt -# 方案规定的技术重试退避(秒):第 1/2/3 次失败后延迟。 -_TECHNICAL_RETRY_BACKOFF_SECONDS: tuple[int, ...] = (5, 30, 120) - - -def _count_failed_technical_jobs(attempt_id: int) -> int: - """ - 统计某 Attempt 已失败的技术 Job 数(含 force_new 的 business_ref 变体)。 - - 核心逻辑:按 business_ref=`attempt:{id}` 或 `attempt:{id}:...` 过滤 failed Job, - 作为跨 Job 累计重试次数,避免写入 input_snapshot 破坏 Hash。 - - Args: - attempt_id: ShippingProcessGateAttempt 主键。 - - Returns: - 已处于 failed 状态的相关 Job 数量。 - """ - prefix = f'attempt:{int(attempt_id)}' - return ( - Job.query - .filter( - Job.domain == SHIPPING_PROCESS_GATE_JOB_DOMAIN, - Job.job_type == JobType.SHIPPING_PROCESS_GATE.value, - Job.status == 'failed', - or_( - Job.business_ref == prefix, - Job.business_ref.like(f'{prefix}:%'), - ), - ) - .count() - ) - - -def _strip_legacy_retry_count_from_input_snapshot(attempt: ShippingProcessGateAttempt) -> None: - """ - 清理历史误写入 input_snapshot 的 technical_retry_count,避免污染业务输入快照。 - - 核心逻辑:若键存在则删除;不重算 Hash(Hash 应对创建时的业务快照;遗留键本身已破坏一致性, - 删除后正文与创建 Hash 仍可能不一致,但后续不再写入新的运行元数据)。 - """ - snap = attempt.input_snapshot_json - if not isinstance(snap, dict) or 'technical_retry_count' not in snap: - return - cleaned = {k: v for k, v in snap.items() if k != 'technical_retry_count'} - attempt.input_snapshot_json = cleaned - - -def _finalize_attempt_after_retry_exhausted( +def _finalize_attempt_after_failure( *, attempt: ShippingProcessGateAttempt, exc: BaseException, ) -> None: """ - 技术重试耗尽:将 Attempt/Gate 收口为 failed_terminal。 + 单次门禁执行失败:结束当前 Attempt,并将 Gate 收口为可人工恢复阻断。 核心逻辑:调用 complete_gate_attempt,避免 Job=failed 而 Gate 仍 running。 """ - safe = sanitize_gate_error_text(exc, max_len=500) or 'technical_retry_exhausted' + safe = sanitize_gate_error_text(exc, max_len=500) or 'technical_failure' if attempt.status == 'queued': attempt.status = 'running' db.session.flush() complete_gate_attempt( attempt_id=int(attempt.id), - outcome='failed_terminal', + outcome='blocked_retryable', # 与 error_explainability_contract / PROCESS_GATE_BLOCKING 对齐,禁止写未登记的 technical_failure - blocking_reason_code='technical_retry_exhausted', + blocking_reason_code='technical_failure_present', blocking_reason_json={ - 'reason_code': 'technical_retry_exhausted', + 'reason_code': 'technical_failure_present', 'message': safe, - 'technical_retry_exhausted': True, }, - effective_result_json={'findings': [], 'error': 'technical_retry_exhausted'}, - output_snapshot={'error': safe, 'technical_retry_exhausted': True}, - error_code='TECHNICAL_RETRY_EXHAUSTED', + effective_result_json={'findings': [], 'error': 'technical_failure'}, + output_snapshot={'error': safe}, + error_code='TECHNICAL_FAILURE', error_summary=safe, ) @@ -141,6 +91,9 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None: try: result = claim_and_run_gate_attempt(attempt_id=attempt_id, worker_id=worker_id) except Exception as exc: + # claim/execute 可能已经让 SQLAlchemy 事务进入 aborted 状态(例如死锁)。 + # 任何失败收口前必须先回滚,避免把 Job 标记失败后留下 queued Attempt/Gate。 + db.session.rollback() attempt = db.session.get(ShippingProcessGateAttempt, attempt_id) gate = None gate_status = None @@ -163,45 +116,15 @@ def run_shipping_process_gate(ctx: JobContext, payload: dict) -> None: db.session.commit() return - # [STEP] 技术失败:按 Attempt 下 failed Job 累计判定,禁止因 force_new 无限重试。 - max_attempts = max( - int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3), - 1, - ) - failed_already = _count_failed_technical_jobs(attempt_id) if attempt is not None else max_attempts safe_error = sanitize_gate_error_text(exc, max_len=1000) or 'technical_failure' - # 本次 fail_job 后累计 = failed_already + 1;未达上限则退避重入队。 - if attempt is not None and failed_already + 1 < max_attempts: - delay_idx = min(failed_already, len(_TECHNICAL_RETRY_BACKOFF_SECONDS) - 1) - delay = _TECHNICAL_RETRY_BACKOFF_SECONDS[delay_idx] - fail_job( - job.id, - error=safe_error, - retryable=False, - owned_attempt=owned_attempt, - ) - _strip_legacy_retry_count_from_input_snapshot(attempt) - attempt.status = 'queued' - attempt.job_id = None - attempt.worker_id = None - attempt.lease_token = None - attempt.lease_expires_at = None - if gate is not None and gate.status == 'running': - gate.status = 'queued' - db.session.flush() - enqueue_gate_attempt_job( - attempt_id=attempt_id, - delay_seconds=delay, - force_new=True, - ) - db.session.commit() - return - - fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt) + # 先把 Attempt/Gate/Execution 收口,再独立结束 Job;即使 Runner 随后兜底标记 + # Job failed,也不会再留下 failed Job + queued Attempt 的非法组合。 if attempt is not None: - _strip_legacy_retry_count_from_input_snapshot(attempt) - _finalize_attempt_after_retry_exhausted(attempt=attempt, exc=exc) - db.session.commit() + fresh_attempt = db.session.get(ShippingProcessGateAttempt, attempt_id) + if fresh_attempt is not None and fresh_attempt.status in {'queued', 'running'}: + _finalize_attempt_after_failure(attempt=fresh_attempt, exc=exc) + db.session.commit() + fail_job(job.id, error=safe_error, retryable=False, owned_attempt=owned_attempt) return finish_job(job.id, result=result if isinstance(result, dict) else {'status': 'ok'}, owned_attempt=owned_attempt) diff --git a/backend/app/jobs/runner.py b/backend/app/jobs/runner.py index e3741cb7..3da5cfee 100644 --- a/backend/app/jobs/runner.py +++ b/backend/app/jobs/runner.py @@ -95,6 +95,14 @@ def run_forever( handler(ctx, job.get('payload') or {}) except Exception as exc: ctx.logger.exception('Handler failed job_id=%s', job.get('id')) + # Handler 可能在 flush/写库失败后留下 aborted transaction;先回滚, + # 再查询并收口 Job,否则 mark_failed 自身会被 InFailedSqlTransaction 阻断。 + try: + from app import db + + db.session.rollback() + except Exception: + ctx.logger.exception('Session rollback failed after handler job_id=%s', job.get('id')) store.mark_failed( job['id'], message=str(exc), diff --git a/backend/app/jobs/types.py b/backend/app/jobs/types.py index 1df7d5d1..65f8703a 100644 --- a/backend/app/jobs/types.py +++ b/backend/app/jobs/types.py @@ -20,7 +20,7 @@ class JobType(StrEnum): SHIPPING_ORDER_EXTRACTION = 'shipping_order_extraction' SHIPPING_DOCUMENT_LAYOUT = 'shipping_document_layout' SHIPPING_PROCESS_GATE = 'shipping_process_gate' - # Task 级正式决策器:一个 Job 只处理一个 ProcessGate。 + # 历史 APX 兼容:Worker 仅终态化,不再执行 Gate。 SHIPPING_AUTO_PROGRESS = 'shipping_auto_progress' # XFA 合成预览就绪后的 OCR 自动标记(Job.job_type 为字符串列,无需 DB enum 迁移) SHIPPING_XFA_OCR_AUTOMARK = 'shipping_xfa_ocr_automark' diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index b9c6870f..6fd13432 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -168,6 +168,12 @@ from app.models.shipping_inventory_candidates import ( ShippingInventoryCandidateSource, ) from app.models.shipping_task_inventory_rpa_attempts import ShippingTaskInventoryRpaAttempt +from app.models.shipping_process_recovery_plan import ShippingProcessRecoveryPlan +from app.models.shipping_inventory_preparation import ( + ShippingInventoryPreparationAttempt, + ShippingInventoryPreparationSourceAttempt, +) +from app.models.shipping_inventory_mapping import ShippingInventoryMapping from app.models.training import TrainingRecord from app.models.user import LoginAudit, User, UserDefaultAgent, UserFavoriteAgent, UserHomepageConfig from app.models.wecom import WecomCallbackAudit, WecomNotifyAudit diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index ddbd3647..d87d992b 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -361,6 +361,15 @@ class ShippingInventoryFile(Base): rpa_run_no: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) schedule_run_id: Mapped[Optional[int]] = mapped_column(nullable=True, index=True) source_query_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) + superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True) + invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) + invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) + input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + file_sha256: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + parser_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + mapping_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) @@ -397,6 +406,12 @@ class ShippingTaskInventoryLink(Base): identity_check_status: Mapped[Optional[str]] = mapped_column(String(32), nullable=True) identity_checked_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) snapshot_age_seconds: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', use_alter=True), nullable=True, index=True) + source_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_source_attempts.id', use_alter=True), nullable=True, index=True) + invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) + invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) + combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) audit_payload_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) linked_by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) linked_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) diff --git a/backend/app/models/shipping_fulfillment.py b/backend/app/models/shipping_fulfillment.py index 761a5673..9e6f7670 100644 --- a/backend/app/models/shipping_fulfillment.py +++ b/backend/app/models/shipping_fulfillment.py @@ -62,6 +62,10 @@ class ShippingInventoryVerification(Base): task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id'), nullable=False) inventory_snapshot_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id'), nullable=True) source_config_version: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + preparation_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='SET NULL'), nullable=True, index=True) + matching_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True, index=True) + input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id'), nullable=True) status: Mapped[str] = mapped_column(String(16), nullable=False, default='completed', server_default='completed') result_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) @@ -131,7 +135,7 @@ class ShippingUploadAttempt(Base): UniqueConstraint('callback_id', name='uq_shipping_notice_upload_attempts_callback'), CheckConstraint("mode IN ('rpa', 'manual')", name='ck_shipping_notice_upload_attempts_mode'), CheckConstraint( - "status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out')", + "status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out', 'unknown')", name='ck_shipping_notice_upload_attempts_status', ), Index('ix_shipping_notice_upload_attempts_artifact_created', 'artifact_id', 'created_at'), @@ -143,6 +147,9 @@ class ShippingUploadAttempt(Base): mode: Mapped[str] = mapped_column(String(16), nullable=False) idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False) callback_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + superseded_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_upload_attempts.id'), nullable=True) + invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) status: Mapped[str] = mapped_column(String(16), nullable=False, default='pending', server_default='pending') started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) diff --git a/backend/app/models/shipping_inventory_mapping.py b/backend/app/models/shipping_inventory_mapping.py new file mode 100644 index 00000000..dcc8f196 --- /dev/null +++ b/backend/app/models/shipping_inventory_mapping.py @@ -0,0 +1,40 @@ +""" +models/shipping_inventory_mapping.py + +用途:保存不可变库存字段映射版本。 +依赖:ShippingInventoryFile、ShippingInventoryParsingProfile、Base。 +逻辑:每次确认/重跑创建新版本,匹配 Attempt 通过 mapping_id 精确引用。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column + +from app.models.base import Base + + +class ShippingInventoryMapping(Base): + """库存文件的不可变字段映射版本。""" + + __tablename__ = 'shipping_inventory_mappings' + __table_args__ = ( + UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'), + CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'), + Index('ix_shipping_inventory_mapping_file_status', 'inventory_file_id', 'status'), + ) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + inventory_file_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='CASCADE'), nullable=False) + version: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='active', server_default='active') + profile_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_parsing_profiles.id', ondelete='SET NULL'), nullable=True) + mapping_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + superseded_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id'), nullable=True) + created_by: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True) + operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) diff --git a/backend/app/models/shipping_inventory_preparation.py b/backend/app/models/shipping_inventory_preparation.py new file mode 100644 index 00000000..45e80d98 --- /dev/null +++ b/backend/app/models/shipping_inventory_preparation.py @@ -0,0 +1,79 @@ +""" +models/shipping_inventory_preparation.py + +用途:表达一次任务级库存准备轮次及逐库存源状态。 +依赖:ShippingNotice、RecoveryPlan、RPA Attempt、InventoryFile、TaskInventoryLink、Base。 +逻辑:PreparationAttempt 聚合多个 SourceAttempt,支持有效源复用和问题源单独重拉。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +class ShippingInventoryPreparationAttempt(Base): + """一次任务级库存准备恢复轮次。""" + + __tablename__ = 'shipping_inventory_preparation_attempts' + __table_args__ = ( + UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'), + CheckConstraint( + "status IN ('queued','running','waiting_external','waiting_manual','succeeded','failed','cancelled','superseded')", + name='ck_shipping_inventory_preparation_status', + ), + Index('ix_shipping_inventory_preparation_task_status', 'task_id', 'status', 'created_at'), + ) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + task_id: Mapped[int] = mapped_column(ForeignKey('shipping_notices.id', ondelete='CASCADE'), nullable=False) + execution_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_executions.id', ondelete='SET NULL'), nullable=True) + gate_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', ondelete='SET NULL'), nullable=True, index=True) + recovery_plan_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_recovery_plans.id', ondelete='SET NULL'), nullable=True) + attempt_no: Mapped[int] = mapped_column(Integer, nullable=False) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') + combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + candidate_set_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_candidate_sets.id', ondelete='SET NULL'), nullable=True) + input_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + output_snapshot_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + + source_attempts = relationship('ShippingInventoryPreparationSourceAttempt', back_populates='preparation_attempt', cascade='all, delete-orphan') + + +class ShippingInventoryPreparationSourceAttempt(Base): + """准备轮次中某个库存源的业务状态。""" + + __tablename__ = 'shipping_inventory_preparation_source_attempts' + __table_args__ = ( + UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'), + CheckConstraint( + "status IN ('ready','reusable','skipped','failed','waiting','queued','running')", + name='ck_shipping_inventory_preparation_source_status', + ), + Index('ix_shipping_inventory_preparation_source_status', 'source_code', 'status', 'created_at'), + ) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + preparation_attempt_id: Mapped[int] = mapped_column(ForeignKey('shipping_inventory_preparation_attempts.id', ondelete='CASCADE'), nullable=False) + source_code: Mapped[str] = mapped_column(String(64), nullable=False) + warehouse_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='queued', server_default='queued') + skip_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) + rpa_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_rpa_attempts.id', ondelete='SET NULL'), nullable=True) + inventory_file_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_files.id', ondelete='SET NULL'), nullable=True) + task_inventory_link_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_task_inventory_links.id', ondelete='SET NULL'), nullable=True) + input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + preparation_attempt = relationship('ShippingInventoryPreparationAttempt', back_populates='source_attempts') diff --git a/backend/app/models/shipping_notice_line_inventory_match.py b/backend/app/models/shipping_notice_line_inventory_match.py index ea56ac8c..de3ef869 100644 --- a/backend/app/models/shipping_notice_line_inventory_match.py +++ b/backend/app/models/shipping_notice_line_inventory_match.py @@ -133,3 +133,10 @@ class ShippingNoticeLineInventoryMatch(Base): nullable=True, index=True, ) + invalidated_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + invalidated_by_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) + invalidation_reason: Mapped[Optional[str]] = mapped_column(String(256), nullable=True) + superseded_by_match_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_line_inventory_matches.id'), nullable=True) + input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + mapping_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_inventory_mappings.id', ondelete='SET NULL'), nullable=True, index=True) + verification_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_notice_inventory_verifications.id', ondelete='SET NULL'), nullable=True, index=True) diff --git a/backend/app/models/shipping_process_gate.py b/backend/app/models/shipping_process_gate.py index 6aea68f8..5ec7866a 100644 --- a/backend/app/models/shipping_process_gate.py +++ b/backend/app/models/shipping_process_gate.py @@ -259,9 +259,15 @@ class ShippingProcessGateAttempt(Base): finished_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) error_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) error_summary: Mapped[Optional[str]] = mapped_column(Text, nullable=True) + recovery_plan_id: Mapped[Optional[int]] = mapped_column( + ForeignKey('shipping_process_recovery_plans.id', use_alter=True), nullable=True, index=True, + ) created_at: Mapped[datetime] = mapped_column(DateTime, default=_utc_now, nullable=False) gate: Mapped[ShippingProcessGate] = relationship( back_populates='attempts', foreign_keys=[gate_id], ) + recovery_plan = relationship( + 'ShippingProcessRecoveryPlan', back_populates='attempts', foreign_keys=[recovery_plan_id], + ) diff --git a/backend/app/models/shipping_process_recovery_plan.py b/backend/app/models/shipping_process_recovery_plan.py new file mode 100644 index 00000000..56a3e527 --- /dev/null +++ b/backend/app/models/shipping_process_recovery_plan.py @@ -0,0 +1,64 @@ +""" +models/shipping_process_recovery_plan.py + +用途:持久化一次跨阶段门禁恢复业务意图及其生命周期。 +依赖:ShippingProcessExecution、ShippingProcessGateAttempt、User、Base。 +逻辑:RecoveryPlan 记录目标 Gate、失效计划、幂等键和最终结果;一个计划可关联多个 Gate Attempt。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any, Optional + +from sqlalchemy import CheckConstraint, DateTime, ForeignKey, Index, Integer, JSON, String, Text, UniqueConstraint +from sqlalchemy.orm import Mapped, mapped_column, relationship + +from app.models.base import Base + + +RECOVERY_PLAN_STATUSES = ( + 'planned', 'invalidating', 'queued', 'running', 'waiting_external', + 'waiting_manual', 'succeeded', 'failed', 'conflicted', 'cancelled', +) + + +class ShippingProcessRecoveryPlan(Base): + """一次跨阶段恢复意图;不可用 Gate Attempt JSON 替代。""" + + __tablename__ = 'shipping_process_recovery_plans' + __table_args__ = ( + UniqueConstraint('plan_no', name='uq_shipping_process_recovery_plans_no'), + UniqueConstraint('execution_id', 'idempotency_key', name='uq_shipping_process_recovery_plans_execution_idempotency'), + CheckConstraint( + "status IN ('planned','invalidating','queued','running','waiting_external','waiting_manual','succeeded','failed','conflicted','cancelled')", + name='ck_shipping_process_recovery_plans_status', + ), + Index('ix_shipping_process_recovery_plans_execution_status', 'execution_id', 'status', 'created_at'), + ) + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + plan_no: Mapped[str] = mapped_column(String(64), nullable=False) + execution_id: Mapped[int] = mapped_column(ForeignKey('shipping_process_executions.id', ondelete='CASCADE'), nullable=False) + current_gate: Mapped[str] = mapped_column(String(64), nullable=False) + action_code: Mapped[str] = mapped_column(String(64), nullable=False) + target_gate: Mapped[str] = mapped_column(String(64), nullable=False) + resume_after_gate: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + status: Mapped[str] = mapped_column(String(32), nullable=False, default='planned', server_default='planned') + invalidation_plan_json: Mapped[dict[str, Any]] = mapped_column(JSON, nullable=False, default=dict) + recovery_attempt_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_gate_attempts.id', use_alter=True), nullable=True) + combination_input_fingerprint: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + idempotency_key: Mapped[str] = mapped_column(String(128), nullable=False) + expected_gate_version: Mapped[Optional[int]] = mapped_column(Integer, nullable=True) + actor_type: Mapped[str] = mapped_column(String(16), nullable=False, default='system', server_default='system') + actor_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + operation_id: Mapped[Optional[str]] = mapped_column(String(128), nullable=True) + failure_code: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) + failure_detail_json: Mapped[Optional[dict[str, Any]]] = mapped_column(JSON, nullable=True) + superseded_by_plan_id: Mapped[Optional[int]] = mapped_column(ForeignKey('shipping_process_recovery_plans.id'), nullable=True) + created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, nullable=False) + started_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + completed_at: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True) + + execution = relationship('ShippingProcessExecution', foreign_keys=[execution_id]) + attempts = relationship('ShippingProcessGateAttempt', back_populates='recovery_plan', foreign_keys='ShippingProcessGateAttempt.recovery_plan_id') diff --git a/backend/app/services/shipping_notice/apx_runtime_audit.py b/backend/app/services/shipping_notice/apx_runtime_audit.py new file mode 100644 index 00000000..1843f057 --- /dev/null +++ b/backend/app/services/shipping_notice/apx_runtime_audit.py @@ -0,0 +1,57 @@ +""" +APX 历史运行时只读清点。 + +用途:在正式 20-Gate 单轨切换前,统计数据库中仍处于运行态的 APX Execution/Job。 +依赖:ShippingProcessExecution、Job ORM 模型。 +逻辑:仅执行 SELECT,区分运行态与历史终态;调用方据此决定迁移或人工关闭,不在本模块修改数据。 +""" + +from __future__ import annotations + +from app.models import Job, ShippingProcessExecution + + +_EXECUTION_RUNTIME_STATUSES = ('active', 'blocked', 'waiting_external') +_JOB_RUNTIME_STATUSES = ('queued', 'running', 'active') + + +def audit_apx_runtime_state() -> dict[str, object]: + """只读统计 APX Execution/Job 运行态与历史态数量。 + + Returns: + 包含 execution/job 两组计数。APX Job 通过 execution_no、business_ref 或 + payload 中的 execution_id 关联;任何写操作都不在此函数执行。 + """ + apx_executions = ShippingProcessExecution.query.filter( + ShippingProcessExecution.execution_no.ilike('APX-%') + ).all() + runtime_execution_ids = { + int(row.id) for row in apx_executions + if str(row.status or '').lower() in _EXECUTION_RUNTIME_STATUSES + } + apx_jobs = Job.query.filter( + Job.domain == 'shipping_notice', + Job.status.in_(_JOB_RUNTIME_STATUSES), + ).all() + runtime_job_count = 0 + for job in apx_jobs: + if int(job.execution_id or 0) in runtime_execution_ids: + runtime_job_count += 1 + continue + if str(job.business_ref or '').upper().find('APX-') >= 0: + runtime_job_count += 1 + continue + payload = job.payload_json if isinstance(job.payload_json, dict) else {} + if str(payload.get('execution_no') or '').upper().startswith('APX-'): + runtime_job_count += 1 + + return { + 'execution': { + 'active_count': len(runtime_execution_ids), + 'historical_count': len(apx_executions) - len(runtime_execution_ids), + }, + 'job': { + 'active_count': runtime_job_count, + }, + } + diff --git a/backend/app/services/shipping_notice/auto_progress_controller.py b/backend/app/services/shipping_notice/auto_progress_controller.py index 21b673a3..945349d2 100644 --- a/backend/app/services/shipping_notice/auto_progress_controller.py +++ b/backend/app/services/shipping_notice/auto_progress_controller.py @@ -10,13 +10,15 @@ services/shipping_notice/auto_progress_controller.py from __future__ import annotations import uuid -from datetime import datetime +from datetime import datetime, timedelta from typing import Any +from flask import current_app + from app import db from app.jobs.queue import enqueue from app.jobs.types import JobType -from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate +from app.models import Job, ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt from app.services.shipping_notice.inventory_candidate_projection import get_active_candidate_set from app.services.shipping_notice.tool_common import log_task_event @@ -33,6 +35,24 @@ _ACTIVE_JOB_STATUSES = ('queued', 'running') _CANCELLED_TASK_STATUSES = frozenset({'cancelled', 'canceled', 'closed', 'rejected'}) +def audit_legacy_forwarded_entrypoint( + *, task: ShippingNotice, action_code: str, actor_id: int | None = None, + request_id: str | None = None, +) -> None: + """记录旧工作台入口已转发至正式 Gate Orchestrator 的审计事实。""" + log_task_event( + task, + 'shipping_legacy_entrypoint_forwarded', + { + 'entrypoint': 'legacy_forwarded', + 'action_code': str(action_code or '').strip(), + }, + actor_id=actor_id, + request_id=request_id, + source='workspace_api', + ) + + def _utc_now() -> datetime: """返回仓库统一使用的 naive UTC 时间。""" return datetime.utcnow() @@ -43,6 +63,43 @@ def _task_is_cancelled(task: ShippingNotice) -> bool: return str(getattr(task, 'process_status', '') or '').strip().lower() in _CANCELLED_TASK_STATUSES +def _recover_stale_active_job(job: Job) -> bool: + """ + 在用户触发入口原子回收超时的 AutoProgress running Job。 + + 核心逻辑:仅处理 started_at 已超过通用发货 Job 超时的 running 行;旧 Job + 终态保留审计,关联 running/queued Gate 改为 blocked_retryable,使当前事务可重新入队。 + + Args: + job: 已由 submit_auto_progress 锁定的活动 Job。 + + Returns: + True 表示旧 Job 已回收,调用方应继续创建新 Job;False 表示仍有效并复用。 + """ + if str(job.status or '') != 'running' or job.started_at is None: + return False + timeout_seconds = float( + current_app.config.get('SHIPPING_NOTICE_JOB_RUNNING_TIMEOUT_SECONDS', 420) or 420 + ) + if job.started_at >= _utc_now() - timedelta(seconds=timeout_seconds): + return False + now = _utc_now() + job.status = 'failed' + job.message = f'自动推进任务执行超时(超过 {int(timeout_seconds)}s),已允许重新入队' + job.error_message = 'shipping_auto_progress_timeout' + job.finished_at = now + job.locked_by = None + job.locked_at = None + job.updated_at = now + gate = db.session.get(ShippingProcessGate, int(job.gate_id)) if job.gate_id else None + if gate is not None and gate.status in {'queued', 'running'}: + gate.status = 'blocked_retryable' + gate.blocking_reason_code = 'technical_retry_exhausted' + gate.updated_at = now + db.session.flush() + return True + + def _new_execution_no() -> str: """生成可读的 P0-3 Execution 编号。""" return f'APX-{_utc_now().strftime("%Y%m%d")}-{uuid.uuid4().hex[:10].upper()}' @@ -50,28 +107,111 @@ def _new_execution_no() -> str: def _create_execution(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution: """ - 为当前 Task/CandidateSet 创建独立六 Gate 链。 + 禁止创建 APX 六 Gate Execution。 - 核心逻辑:不复用旧 20 Gate Execution,避免旧 skipped/waiting_external 语义污染 P0-3 的严格顺序。 + APX 仅保留历史数据兼容;新任务和恢复入口必须通过正式 20-Gate + ``ensure_execution_for_workflow_version`` 创建 Execution。 """ - execution = ShippingProcessExecution( - execution_no=_new_execution_no(), task_id=int(task.id), candidate_set_id=candidate_set_id, - execution_revision=1, status='active', current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1, + raise RuntimeError('shipping_apx_creation_disabled') + + +def _is_formal_process_execution(execution: ShippingProcessExecution) -> bool: + """按完整 20-Gate 合同识别正式 Execution;Task-only 正式链同样有效。""" + from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES + + gate_codes = { + str(item.gate_code) + for item in ShippingProcessGate.query.filter_by(execution_id=int(execution.id)).all() + } + return gate_codes == set(PROCESS_GATE_CODES) + + +def determine_formal_start_gate( + task: ShippingNotice, + *, + candidate_set: Any | None = None, +) -> str: + """根据持久化 Task/CandidateSet 事实选择正式 20-Gate 的首个 Gate。 + + 未确认的解析、冻结或候选事实一律回退到最早缺失 Gate,禁止由调用入口 + 直接跳过前置 Contract;仅完整冻结订单和 frozen CandidateSet 可进入库存准备。 + """ + if not getattr(task, 'current_order_extraction_id', None): + return 'document_materialization' + if not getattr(task, 'order_snapshot_id', None): + return 'order_freeze_readiness' + # 仅当服务端已明确记录 pending/failed 时阻断客户确认;None 保留给历史 + # Task-only 兼容构造,不能把缺失的可选字段误当成失败事实。 + customer_status = str(getattr(task, 'customer_resolution_status', '') or '').strip().lower() + if customer_status in {'pending', 'needs_review', 'failed', 'unresolved'}: + return 'customer_resolution' + # 字段冲突是独立的正式 Gate,必须先于候选冻结和库存准备处理。 + if any(str(getattr(row, 'status', '') or '').strip().lower() == 'open' for row in (getattr(task, 'field_conflicts', None) or [])): + return 'field_conflict_resolution' + candidate = candidate_set if candidate_set is not None else get_active_candidate_set(task) + if candidate is None or str(getattr(candidate, 'lifecycle_status', '') or '').lower() != 'frozen': + return 'inventory_source_routing' + return 'inventory_preparation' + + +def _create_formal_execution_for_task( + task: ShippingNotice, + *, + candidate_set_id: int | None, +) -> ShippingProcessExecution: + """为无正式链的已建 Task 创建唯一 20-Gate Execution,禁止新建 APX。""" + from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version + + execution = ensure_execution_for_workflow_version( + task_id=int(task.id), + actor_type='system', + start_gate_code=determine_formal_start_gate(task), ) - db.session.add(execution) - db.session.flush() - for sequence_no, gate_code in enumerate(AUTO_PROGRESS_GATE_CODES, start=1): - db.session.add(ShippingProcessGate( - execution_id=int(execution.id), gate_code=gate_code, sequence_no=sequence_no, - status='pending', evaluation_version=1, lock_version=1, - )) + execution.candidate_set_id = candidate_set_id task.active_process_execution_id = int(execution.id) db.session.flush() return execution +def _supersede_duplicate_execution( + execution: ShippingProcessExecution, + *, + replacement: ShippingProcessExecution, +) -> None: + """收敛重复活动链;保留审计记录,不删除历史 Attempt/Job。""" + if execution.id == replacement.id or execution.status in {'completed', 'cancelled', 'superseded'}: + return + execution.status = 'superseded' + execution.updated_at = _utc_now() + ShippingProcessGate.query.filter( + ShippingProcessGate.execution_id == int(execution.id), + ShippingProcessGate.status.in_( + ('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'invalidated'), + ), + ).update( + {'status': 'cancelled', 'updated_at': _utc_now()}, + synchronize_session=False, + ) + + def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | None) -> ShippingProcessExecution: - """锁定并取得当前 Execution;候选版本变化时旧链 superseded 后创建新链。""" + """ + 锁定并取得当前唯一活动 Execution。 + + 核心逻辑:正式 20-Gate 链是唯一运行时状态机;历史 APX 仅可读, + 不得被重新激活或继续排队。候选版本变化仍按原规则 superseded。 + """ + all_active = ( + ShippingProcessExecution.query + .filter( + ShippingProcessExecution.task_id == int(task.id), + ShippingProcessExecution.status.in_(('active', 'blocked', 'waiting_external')), + ) + .with_for_update() + .order_by(ShippingProcessExecution.id.asc()) + .all() + ) + formal = next((item for item in all_active if _is_formal_process_execution(item)), None) current_id = getattr(task, 'active_process_execution_id', None) execution = db.session.get(ShippingProcessExecution, int(current_id)) if current_id else None if execution is not None: @@ -80,6 +220,14 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | ) if execution is not None and int(getattr(execution, 'task_id', 0) or 0) != int(task.id): execution = None + if formal is not None: + for duplicate in all_active: + if duplicate.id != formal.id: + _supersede_duplicate_execution(duplicate, replacement=formal) + task.active_process_execution_id = int(formal.id) + formal.updated_at = _utc_now() + db.session.flush() + return formal if execution is not None and int(getattr(execution, 'candidate_set_id', 0) or 0) != int(candidate_set_id or 0): # 旧链永不覆盖:未完成 Gate 取消,Execution 留审计后由新 CandidateSet 建链。 execution.status = 'superseded' @@ -88,7 +236,17 @@ def _active_execution_for_task(task: ShippingNotice, *, candidate_set_id: int | ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')), ).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False) execution = None - return execution or _create_execution(task, candidate_set_id=candidate_set_id) + # APX 仅作为历史数据兼容:新任务或无正式链 Task 一律创建正式 20-Gate。 + if execution is not None: + execution.status = 'superseded' + execution.updated_at = _utc_now() + ShippingProcessGate.query.filter( + ShippingProcessGate.execution_id == int(execution.id), + ShippingProcessGate.status.in_( + ('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual', 'invalidated'), + ), + ).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False) + return _create_formal_execution_for_task(task, candidate_set_id=candidate_set_id) def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None: @@ -101,14 +259,37 @@ def supersede_auto_progress_for_candidate_refreeze(task: ShippingNotice) -> None if execution_id: execution = ShippingProcessExecution.query.filter_by(id=int(execution_id)).with_for_update().first() if execution is not None and execution.status not in {'completed', 'cancelled', 'superseded'}: + # Attempt 是不可变执行历史,但候选版本切换后其 queued/running 状态 + # 必须显式终止,避免旧 Attempt 被 Worker 领取并污染新 CandidateSet。 + ShippingProcessGateAttempt.query.filter( + ShippingProcessGateAttempt.gate_id.in_( + db.session.query(ShippingProcessGate.id).filter( + ShippingProcessGate.execution_id == int(execution.id), + ) + ), + ShippingProcessGateAttempt.status.in_(('queued', 'running')), + ).update( + { + 'status': 'superseded', + 'finished_at': _utc_now(), + 'error_code': 'candidate_set_refrozen', + 'error_summary': 'CandidateSet 已重冻结,旧 GateAttempt 终止', + }, + synchronize_session=False, + ) execution.status = 'superseded' ShippingProcessGate.query.filter( ShippingProcessGate.execution_id == int(execution.id), ShippingProcessGate.status.in_(('pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual')), ).update({'status': 'cancelled', 'updated_at': _utc_now()}, synchronize_session=False) Job.query.filter( - Job.domain == 'shipping_notice', Job.job_type == JobType.SHIPPING_AUTO_PROGRESS.value, - Job.task_id == int(task.id), Job.status == 'queued', + Job.domain == 'shipping_notice', + Job.job_type.in_(( + JobType.SHIPPING_AUTO_PROGRESS.value, + JobType.SHIPPING_PROCESS_GATE.value, + )), + Job.task_id == int(task.id), + Job.status == 'queued', ).update({'status': 'cancelled', 'finished_at': _utc_now(), 'message': '候选版本已重冻结'}, synchronize_session=False) @@ -122,7 +303,11 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi ShippingProcessGate.query.filter_by(execution_id=int(execution.id)) .order_by(ShippingProcessGate.sequence_no.asc()).with_for_update().all() ) - expected = list(AUTO_PROGRESS_GATE_CODES) + # 正式运行时只接受 20-Gate 合同;AUTO_PROGRESS_GATE_CODES 仅保留给历史 + # APX 数据读取/迁移测试,不能再作为新任务的状态机校验来源。 + from app.services.shipping_notice.process_gate_contract import PROCESS_GATE_CODES + + expected = list(PROCESS_GATE_CODES) if [item.gate_code for item in gates] != expected: return None, 'projection_data_inconsistent' pending_seen = False @@ -145,172 +330,191 @@ def _earliest_runnable_gate(execution: ShippingProcessExecution) -> tuple[Shippi def submit_auto_progress( *, task: ShippingNotice, trigger: str, operator_id: int | None = None, resume_gate_code: str | None = None, commit: bool = True, + recovery_plan_id: int | None = None, + recovery_attempt_id: int | None = None, + resume_after_gate: str | None = None, ) -> dict[str, Any]: """ 接收任何自动/用户触发并安全入队当前 Gate。 普通调用不会信任 resume_gate_code;即使管理员提供诊断 Gate,仍由最早未通过 Gate 决定实际工作。 """ - locked_task = ShippingNotice.query.filter_by(id=int(task.id)).with_for_update().first() + # ShippingNotice.shipping_case 使用 joined eager load,会产生 LEFT OUTER JOIN; + # PostgreSQL 禁止对外连接可空侧执行无目标 FOR UPDATE,因此仅锁主表。 + locked_task = ( + ShippingNotice.query + .filter_by(id=int(task.id)) + .with_for_update(of=ShippingNotice) + .first() + ) if locked_task is None: return {'status': 'not_found'} if _task_is_cancelled(locked_task): return {'status': 'cancelled', 'task_no': locked_task.task_no} + # 只复用正式 ProcessGate Job。遗留 APX Job 已下线,不能阻塞或劫持正式链入队。 # 先查活动 Job,再读取/改写 Candidate 或 Execution 指针。这样候选重冻结与重复点击 - # 无法把一个仍 running 的旧 Job 错绑到新链。 + # 无法把一个仍 running 的正式 Job 错绑到新链。 active = ( Job.query.filter( Job.domain == 'shipping_notice', - Job.job_type == JobType.SHIPPING_AUTO_PROGRESS.value, + Job.job_type == JobType.SHIPPING_PROCESS_GATE.value, Job.task_id == int(locked_task.id), Job.status.in_(_ACTIVE_JOB_STATUSES), ).with_for_update().order_by(Job.id.desc()).first() ) if active is not None: - if commit: - db.session.commit() - return { - 'status': 'queued' if active.status == 'queued' else 'running', - 'job_id': int(active.id), 'execution_id': active.execution_id, - 'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True, - } + if not _recover_stale_active_job(active): + if commit: + db.session.commit() + return { + 'status': 'queued' if active.status == 'queued' else 'running', + 'job_id': int(active.id), 'execution_id': active.execution_id, + 'gate_code': (active.payload_json or {}).get('gate_code'), 'reused': True, + } + log_task_event(locked_task, 'auto_progress_stale_job_recovered', { + 'stale_job_id': int(active.id), + 'execution_id': active.execution_id, + 'gate_id': active.gate_id, + 'trigger': trigger, + }, actor_id=operator_id, source=trigger) candidate = get_active_candidate_set(locked_task) candidate_set_id = int(candidate.id) if candidate is not None else None execution = _active_execution_for_task(locked_task, candidate_set_id=candidate_set_id) - gate, inconsistency = _earliest_runnable_gate(execution) - if inconsistency: - execution.status = 'blocked' - execution.current_gate_code = None - log_task_event(locked_task, 'auto_progress_projection_inconsistent', { - 'execution_id': execution.id, 'reason_code': inconsistency, - }, actor_id=operator_id, source=trigger) + if _is_formal_process_execution(execution): + # 正式 Case 的 20 Gate Execution 是唯一业务真相;APX 六 Gate 仅兼容 + # 无 Case 的旧 Task。先同步已落库事实,再把当前技术 Gate 交给唯一 + # ProcessGate Job/Attempt 通道;不得在此同步执行或退回 APX 六 Gate Job。 + from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task + from app.services.shipping_notice.process_gate_contract import is_technical_gate_party + from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job + from app.services.shipping_notice.process_gate_service import queue_gate_attempt + + sync_fulfillment_gates_from_task( + execution=execution, + actor_type='system', + actor_id=operator_id, + ) + db.session.flush() + execution = ShippingProcessExecution.query.filter_by(id=int(execution.id)).with_for_update().one() + current_gate = str(execution.current_gate_code or '').strip() or None + gate = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id), gate_code=current_gate) + .with_for_update() + .first() + if current_gate else None + ) + active_attempt = ( + ShippingProcessGateAttempt.query + .filter( + ShippingProcessGateAttempt.gate_id == int(gate.id), + ShippingProcessGateAttempt.status.in_(('queued', 'running')), + ) + .order_by(ShippingProcessGateAttempt.attempt_no.desc()) + .first() + if gate is not None else None + ) + if active_attempt is not None and active_attempt.job_id: + if commit: + db.session.commit() + return { + 'status': 'queued' if active_attempt.status == 'queued' else 'running', + 'job_id': int(active_attempt.job_id), + 'attempt_id': int(active_attempt.id), + 'execution_id': int(execution.id), + 'gate_code': gate.gate_code, + 'reused': True, + } + action_code = str(getattr(gate, 'next_action_code', '') or '').strip() + # 无主动作或人工 Gate 均停留在 Projection;只有服务端已下发动作的 + # system/worker Gate 才可自动创建 Attempt 并入队。 + if gate is not None and action_code and is_technical_gate_party(execution.responsible_party): + attempt = queue_gate_attempt( + execution_no=str(execution.execution_no), + gate_code=str(gate.gate_code), + trigger_type='auto', + actor_type='system', + actor_id=operator_id, + idempotency_key=( + f'shipping-auto-progress:{locked_task.id}:{execution.id}:' + f'{gate.id}:{gate.evaluation_version}' + ), + expected_gate_version=int(gate.evaluation_version), + input_snapshot={ + 'action_code': action_code, + 'payload': { + 'candidate_set_id': candidate_set_id, + 'fencing_token': uuid.uuid4().hex, + 'trigger': trigger, + 'recovery_plan_id': recovery_plan_id, + 'recovery_attempt_id': recovery_attempt_id, + 'resume_after_gate': resume_after_gate, + }, + }, + ) + job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=operator_id) + log_task_event(locked_task, 'auto_progress_gate_attempt_queued', { + 'job_id': job_id, + 'attempt_id': int(attempt.id), + 'attempt_no': int(attempt.attempt_no), + 'execution_id': int(execution.id), + 'candidate_set_id': candidate_set_id, + 'gate_id': int(gate.id), + 'gate_code': gate.gate_code, + 'trigger': trigger, + }, actor_id=operator_id, source=trigger) + if commit: + db.session.commit() + return { + 'status': 'queued', + 'job_id': int(job_id), + 'attempt_id': int(attempt.id), + 'execution_id': int(execution.id), + 'gate_code': gate.gate_code, + 'reused': bool(attempt.status != 'queued'), + } + result = { + 'status': 'waiting_human' if execution.status == 'blocked' else execution.status, + 'execution_id': int(execution.id), + 'gate_code': current_gate, + 'reused': True, + } if commit: db.session.commit() - return {'status': 'waiting_human', 'reason_code': inconsistency, 'execution_id': execution.id} - if gate is None: + return result + # 理论上 _active_execution_for_task 已将活动 APX 收敛为正式链;若仍出现 + # 非正式 Execution,必须 fail-closed,禁止重新创建旧 APX Job。 + if not _is_formal_process_execution(execution): if commit: db.session.commit() - return {'status': 'waiting_human' if execution.status == 'blocked' else 'completed', 'execution_id': execution.id} - business_ref = f'auto-progress:{int(locked_task.id)}' - token = uuid.uuid4().hex - job_id = enqueue( - JobType.SHIPPING_AUTO_PROGRESS, - {'task_no': locked_task.task_no, 'task_id': int(locked_task.id), 'execution_id': int(execution.id), - 'candidate_set_id': candidate_set_id, 'gate_id': int(gate.id), 'gate_code': gate.gate_code, - 'trigger': trigger, 'requested_resume_gate_code': resume_gate_code, 'fencing_token': token}, - domain='shipping_notice', business_ref=business_ref, created_by_id=operator_id, - message=f'等待执行正式 Gate:{gate.gate_code}', max_attempts=1, commit=False, - task_id=int(locked_task.id), execution_id=int(execution.id), gate_id=int(gate.id), - candidate_set_id=candidate_set_id, fencing_token=token, - ) - execution.current_gate_code = gate.gate_code - log_task_event(locked_task, 'auto_progress_job_queued', { - 'job_id': job_id, 'execution_id': execution.id, 'candidate_set_id': candidate_set_id, - 'gate_id': gate.id, 'gate_code': gate.gate_code, 'trigger': trigger, - }, actor_id=operator_id, source=trigger) - if commit: - db.session.commit() - return {'status': 'queued', 'job_id': int(job_id), 'execution_id': int(execution.id), 'gate_code': gate.gate_code} - - -def _gate_outcome(task: ShippingNotice, gate: ShippingProcessGate) -> tuple[str, str | None, dict[str, Any]]: - """仅执行一个 Gate 并把现有业务服务结果归一为正式 Gate 结果。""" - code = gate.gate_code - candidate = get_active_candidate_set(task) - if code == 'inventory_candidates_calculated': - return ('passed', None, {}) if candidate is not None else ('blocked_manual', 'inventory_candidates_required', {}) - if code == 'inventory_candidates_frozen': - frozen = candidate is not None and str(candidate.lifecycle_status) == 'frozen' - return ('passed', None, {}) if frozen else ('blocked_manual', 'inventory_candidates_frozen_required', {}) - if code == 'inventory_snapshots_ready': - from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared - result = ensure_all_required_sources_prepared(task, mode='auto') - if result.all_prepared: - return 'passed', None, {'prepared_sources': result.prepared_source_codes} - if result.failed_source_codes: - return 'blocked_manual', 'inventory_snapshot_prepare_failed', {'failed_sources': result.failed_source_codes} - return 'blocked_retryable', 'inventory_snapshots_pending', {'pending_sources': result.pending_source_codes} - if code == 'inventory_matched': - from app.services.shipping_notice.fulfillment_workflow import match_inventory - result = match_inventory({'task_id': task.task_no, '_orchestrator_internal_dispatch': True}) - status = str((result or {}).get('status') or '') - if status in {'ok', 'completed'}: - return 'passed', None, {} - return 'blocked_manual' if status == 'needs_human' else 'blocked_retryable', 'inventory_match_not_ready', {'legacy_status': status} - if code == 'excel_generated': - from app.services.shipping_notice.fulfillment_workflow import generate_excel - result = generate_excel({'task_id': task.task_no, '_orchestrator_internal_dispatch': True}) - if str((result or {}).get('status') or '') == 'ok' and task.export_file_path: - return 'passed', None, {'export_file_path': task.export_file_path} - return 'blocked_retryable', 'excel_generation_not_ready', {'legacy_status': (result or {}).get('status')} - receipt = getattr(task, 'upload_receipt_json', None) - if receipt or str(getattr(task, 'process_status', '') or '').lower() in {'uploaded', 'completed'}: - return 'passed', None, {} - return 'blocked_manual', 'manual_upload_receipt_required', {} + return { + 'status': 'legacy_readonly', + 'reason_code': 'shipping_apx_runtime_disabled', + 'execution_id': int(execution.id), + } def run_auto_progress_job(*, job_id: int, worker_id: str) -> dict[str, Any]: """ - Worker 执行一个且仅一个 Gate,并以 Job outbox 原子提交 Gate 成功和下一个 Job。 + 将历史 APX AutoProgress Job 终态化,禁止六 Gate 状态机继续运行。 - 所有围栏、Task 取消和 Candidate/Execution identity 都在外部调用前复查;不匹配的迟到 Job 只终态审计。 + APX 已下线为只读历史兼容。Worker 仍消费遗留 queued/running Job, + 但只能取消并保留审计,绝不能触发库存、匹配、Excel 或下一 Gate。 """ job = Job.query.filter_by(id=int(job_id)).with_for_update().first() if job is None or job.status != 'running': return {'status': 'noop'} - payload = dict(job.payload_json or {}) - task = ShippingNotice.query.filter_by(id=int(job.task_id or 0)).with_for_update().first() - execution = ShippingProcessExecution.query.filter_by(id=int(job.execution_id or 0)).with_for_update().first() + now = _utc_now() gate = ShippingProcessGate.query.filter_by(id=int(job.gate_id or 0)).with_for_update().first() - stale = ( - task is None or execution is None or gate is None or _task_is_cancelled(task) - or int(getattr(task, 'active_process_execution_id', 0) or 0) != int(execution.id) - or int(getattr(execution, 'candidate_set_id', 0) or 0) != int(job.candidate_set_id or 0) - or int(gate.execution_id) != int(execution.id) - or str(job.fencing_token or '') != str(payload.get('fencing_token') or '') - ) - if stale: - job.status = 'cancelled'; job.finished_at = _utc_now(); job.message = '任务已取消或版本围栏不匹配' - if gate is not None and gate.status in {'pending', 'queued', 'running'}: - gate.status = 'cancelled' - db.session.commit() - return {'status': 'cancelled'} - runnable, inconsistency = _earliest_runnable_gate(execution) - if inconsistency or runnable is None or int(runnable.id) != int(gate.id): - gate.status = 'blocked_manual'; gate.blocking_reason_code = inconsistency or 'projection_data_inconsistent' - execution.status = 'blocked'; job.status = 'success'; job.finished_at = _utc_now() - db.session.commit() - return {'status': 'waiting_human', 'reason_code': gate.blocking_reason_code} - - gate.status = 'running'; gate.updated_at = _utc_now(); db.session.flush() - outcome, reason_code, details = _gate_outcome(task, gate) - gate.status = outcome; gate.blocking_reason_code = reason_code; gate.effective_result_json = details - gate.updated_at = _utc_now(); job.status = 'success'; job.finished_at = _utc_now(); job.message = f'Gate {outcome}' - if outcome != 'passed': - execution.status = 'blocked'; execution.current_gate_code = gate.gate_code - log_task_event(task, 'auto_progress_gate_blocked', {'gate_code': gate.gate_code, 'reason_code': reason_code}, source='worker') - db.session.commit() - return {'status': outcome, 'gate_code': gate.gate_code, 'reason_code': reason_code} - - gate.passed_at = _utc_now(); execution.last_passed_gate_code = gate.gate_code - # 先 flush 当前 Job 成功态,释放 Task 级 active partial unique;后继 Job 与 Gate passed - # 仍处在同一外层事务,commit 前对 Worker 不可见。 - db.session.flush() - next_gate, consistency_error = _earliest_runnable_gate(execution) - if consistency_error: - execution.status = 'blocked'; execution.current_gate_code = None - elif next_gate is None: - execution.status = 'completed'; execution.current_gate_code = None - elif next_gate.gate_code == 'upload_receipt_recorded': - # 上传自动化关闭时,Excel 后明确等人工登记回执,不擅自跨越此 Gate。 - execution.status = 'blocked'; execution.current_gate_code = next_gate.gate_code - next_gate.status = 'blocked_manual'; next_gate.blocking_reason_code = 'manual_upload_receipt_required' - else: - execution.status = 'active'; execution.current_gate_code = next_gate.gate_code - submit_auto_progress(task=task, trigger='gate_passed', commit=False) - log_task_event(task, 'auto_progress_gate_passed', {'gate_code': gate.gate_code, 'next_gate_code': execution.current_gate_code}, source='worker') + job.status = 'cancelled' + job.finished_at = now + job.message = 'APX historical auto-progress runtime disabled' + if gate is not None and gate.status in {'pending', 'queued', 'running', 'blocked_retryable', 'blocked_manual'}: + gate.status = 'cancelled' + gate.updated_at = now db.session.commit() return { - 'status': 'passed', 'execution_id': int(execution.id), - 'gate_code': gate.gate_code, 'next_gate_code': execution.current_gate_code, + 'status': 'legacy_readonly', + 'reason_code': 'shipping_apx_runtime_disabled', + 'execution_id': int(job.execution_id) if job.execution_id else None, } diff --git a/backend/app/services/shipping_notice/batch_orchestrator.py b/backend/app/services/shipping_notice/batch_orchestrator.py index 2d7bd02a..0de712f9 100644 --- a/backend/app/services/shipping_notice/batch_orchestrator.py +++ b/backend/app/services/shipping_notice/batch_orchestrator.py @@ -163,11 +163,11 @@ def _run_single_task(task_no: str) -> dict[str, str | None]: and not getattr(task, "inventory_lines_json", None) and pending_reason == PH_RPA_PENDING ): - # A pending task already has an explicit RPA attempt. Poll its timeout - # state through the RPA workflow; normal auto-progress must not start RPA. - from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa + # Pending 外部库存状态也统一交给正式 20-Gate;Gate Executor 负责轮询 + # PreparationAttempt,不允许批处理调度器直接调用旧 RPA facade。 + from app.services.shipping_notice.progress_workflow import run_task_auto_progress - result = ensure_inventory_via_rpa(task, mode="auto") + result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator') if current_app: current_app.logger.info( "[shipping-orchestrator] rpa-inventory-recheck task_no=%s status=%s message=%s", @@ -356,10 +356,10 @@ def retry_batch_pending_tasks(batch_no: str | None) -> dict[str, Any]: process_status = str(getattr(task, "process_status", "") or "").strip().lower() pending_reason = str(getattr(task, "pending_human_reason", "") or "").strip().lower() if process_status == "waiting_inventory" and pending_reason == PH_RPA_PENDING: - # This is a poll of an existing request, never an implicit new RPA run. - from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa + # 轮询既有请求仍只提交正式库存准备 Gate,由 Executor 读取 Attempt 状态。 + from app.services.shipping_notice.progress_workflow import run_task_auto_progress - result = ensure_inventory_via_rpa(task, mode="auto") + result = run_task_auto_progress(task_no=task.task_no, trigger='batch_orchestrator') status = str(result.get("status") or "").strip().lower() if status in {"ok", "running", "needs_human"}: started += 1 diff --git a/backend/app/services/shipping_notice/conversation_retry_auto_progress_service.py b/backend/app/services/shipping_notice/conversation_retry_auto_progress_service.py index 5fcd68c2..e93c9860 100644 --- a/backend/app/services/shipping_notice/conversation_retry_auto_progress_service.py +++ b/backend/app/services/shipping_notice/conversation_retry_auto_progress_service.py @@ -48,6 +48,34 @@ _FORCE_RETRYABLE_BLOCKING_CODES = frozenset({ 'SHIPPING.profile_schema_mismatch', }) +# needs_human 并不总是终止态:库存快照/RPA 暂态失败仍可由统一重试决策器 +# 重新触发库存准备;重复、短缺、冲突等业务裁决原因不得自动放行。 +_INVENTORY_RETRYABLE_HUMAN_CODES = frozenset({ + 'inventory_snapshot_prepare_failed', + 'inventory_snapshots_pending', + 'inventory_rpa_failed', + 'inventory_rpa_exhausted', + 'inventory_file_missing', + 'rpa_failed', + 'trigger_not_claimed_missing', + 'trigger_not_claimed_timeout', + 'inventory_trigger_missing', + 'inventory_trigger_write_failed', + # 库存门禁/匹配阻断属于可重新检查的技术中间态;对话级重试不得直接跳过。 + 'inventory_candidates_required', + 'inventory_candidates_frozen_required', + 'inventory_snapshot_prepare_failed', + 'inventory_snapshots_pending', + 'inventory_match_not_ready', + 'inventory_match_incomplete', +}) +_BUSINESS_HUMAN_CODES = frozenset({ + 'inventory_shortage', + 'inventory_source_conflict', + 'inventory_source_candidates_need_human', + 'duplicate_decision_required', +}) + def project_conversation_allowed_actions( *, @@ -428,12 +456,75 @@ def _skip_reason_from_automation(automation: dict[str, Any], *, task_missing: bo if status in {'completed', 'succeeded'}: return 'already_completed' if status == 'needs_human': - return 'human_blocking' + # 库存准备失败是“需要人工关注但仍可技术重试”的中间态;只有 + # retryable=true 且原因码在白名单内才允许继续到正式 OT 决策器。 + reason_candidates = ( + automation.get('reason_code'), + automation.get('blocking_reason_code'), + automation.get('error_code'), + ) + reason_codes = { + str(item or '').strip().lower() + for item in reason_candidates + if str(item or '').strip() + } + if reason_codes & _DUPLICATE_BLOCKING_CODES: + return 'human_blocking' + if reason_codes & _BUSINESS_HUMAN_CODES: + return 'human_blocking' + if bool(automation.get('retryable')) and reason_codes & _INVENTORY_RETRYABLE_HUMAN_CODES: + return None + # 正式 OT 的 needs_human 可能只是上一轮匹配/门禁结果;对话级“重试自动推进” + # 的职责是重新读取当前库存事实并重新检查。只有重复订单等明确业务裁决才跳过。 + return None if not bool(automation.get('retryable')): return 'not_retryable' return None +def _formal_task_has_retryable_inventory_trigger_failure(task_no: str) -> bool: + """读取正式 OT 最新逐源 Attempt,识别 Trigger 缺失等可强制重发的技术失败。""" + try: + from app.services.shipping_notice.task_retry_decision_service import ( + summarize_inventory_rpa_latest_attempts, + ) + task = ShippingNotice.query.filter_by(task_no=str(task_no).strip()).first() + if task is None: + return False + summary = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True) + technical_codes = { + 'trigger_not_claimed_missing', + 'trigger_not_claimed_timeout', + 'inventory_trigger_missing', + 'inventory_trigger_write_failed', + } + return any( + str((item or {}).get('error_code') or '').strip().lower() in technical_codes + and str((item or {}).get('status') or '').strip().lower() in {'failed', 'exhausted'} + for item in (summary.get('latest_attempts') or {}).values() + ) + except Exception: # noqa: BLE001 + _LOGGER.exception('inventory trigger failure lookup failed task_no=%s', task_no) + return False + + +def _formal_task_has_active_attempt(task_no: str) -> bool: + """按正式 Attempt + Job 双重事实判断任务是否真的仍在执行。""" + try: + from app.services.shipping_notice.task_retry_decision_service import ( + summarize_inventory_rpa_latest_attempts, + ) + task = ShippingNotice.query.filter_by(task_no=str(task_no).strip()).first() + if task is None: + return False + summary = summarize_inventory_rpa_latest_attempts(task, include_gate_status=True) + return int(summary.get('active_attempt_count') or 0) > 0 + except Exception: # noqa: BLE001 + _LOGGER.exception('active attempt lookup failed task_no=%s', task_no) + # 状态无法确认时 fail-closed,禁止重复执行。 + return True + + def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str, Any]: """ 对单个 Case 执行重试或跳过。 @@ -476,6 +567,17 @@ def _retry_one_case(*, user_id: int, case: ShippingOrderReviewCase) -> dict[str, if task_no: skip = _skip_reason_from_automation(automation, task_missing=task_missing) + # Automation 是展示投影,可能滞后于正式 Job。只有 Attempt 与 Job 都仍活动时 + # 才能返回 already_running;Job 已失败的 queued Attempt 是待恢复残留。 + if skip == 'already_running' and not _formal_task_has_active_attempt(task_no): + skip = None + # Trigger 缺失/未领取是库存 RPA 的正式技术失败事实;不得被 + # automation 投影中的历史 completed/not_retryable/human_blocking 覆盖。 + # 只要当前没有 queued/running Attempt,就必须重新进入 retry_rpa。 + if skip not in {None, 'already_running', 'task_missing'} and _formal_task_has_retryable_inventory_trigger_failure(task_no): + # Automation 可能仍被历史 Job 的错误码污染;逐源 Attempt 是库存 Trigger + # 的正式事实,技术领取失败必须重新进入 retry_rpa,而不是继续 skipped。 + skip = None if skip: return { 'object_type': OBJECT_FORMAL_TASK, @@ -821,7 +923,9 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: 'object_type': OBJECT_FORMAL_TASK, 'object_ref': task_no, 'action': action, - 'outcome': 'skipped', + # 对话级重试已实际重新检查;门禁仍阻断时应归为失败/需处理, + # 不能计入“已跳过”,否则用户无法区分未执行与执行后被阻断。 + 'outcome': 'failed', 'reason_code': str((result or {}).get('reason_code') or 'human_blocking'), 'metadata': {'p13_category': 'e_formal_ot'}, } @@ -873,13 +977,15 @@ def _execute_formal_task_retry(*, user_id: int, task_no: str) -> dict[str, Any]: def _summarize_items(items: list[dict[str, Any]]) -> dict[str, int]: """汇总逐对象结果。""" - retried = skipped = failed = 0 + retried = skipped = failed = blocked = 0 for item in items: outcome = str(item.get('outcome') or '').strip().lower() if outcome == 'queued': retried += 1 elif outcome == 'failed': failed += 1 + elif outcome == 'blocked': + blocked += 1 else: skipped += 1 return { @@ -887,4 +993,5 @@ def _summarize_items(items: list[dict[str, Any]]) -> dict[str, int]: 'retried': retried, 'skipped': skipped, 'failed': failed, + 'blocked': blocked, } diff --git a/backend/app/services/shipping_notice/decision_workflow.py b/backend/app/services/shipping_notice/decision_workflow.py index 0b539478..dc73b856 100644 --- a/backend/app/services/shipping_notice/decision_workflow.py +++ b/backend/app/services/shipping_notice/decision_workflow.py @@ -24,9 +24,8 @@ from app.services.shipping_notice.constants import ( RS_PARSE_REVIEW, RS_SHORTAGE_REVIEW, ) -from app.services.shipping_notice.fulfillment_workflow import match_completed, match_inventory +from app.services.shipping_notice.fulfillment_workflow import match_completed from app.services.shipping_notice.task_order_field_editor import retire_current_order_extraction -from app.services.shipping_notice.inventory_workflow import ensure_inventory from app.services.shipping_notice.inventory_source_gate import ( is_inventory_source_stable, adjudicate_and_apply_inventory_source, @@ -68,6 +67,13 @@ def _reset_inventory_state_for_forced_rpa(task) -> None: task.freight_ref_no = None task.upload_status = None task.upload_mode = None + + +def _request_formal_gate_action(**kwargs): + """决策工作流的正式 20-Gate 适配器,避免外部入口直调旧库存函数。""" + from app.services.shipping_notice.task_retry_decision_service import _request_formal_gate_action as _request + + return _request(**kwargs) task.upload_error_message = None task.upload_receipt_json = None task.review_status = None @@ -94,8 +100,8 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: 提交人工决策,驱动任务在确认、重解析、重匹配、关闭等分支间流转。 【AI 触发时机】:当用户明确说“确认”“驳回”“重跑库存”“重新上传库存”“关闭任务”等决策类指令时调用。 - 核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、重匹配或重解析等分支; - rematch 会同步调用 match_inventory 完成重算;工作台入口须注入 operator_id 以保证审计非匿名。 +核心逻辑:先解析 decision,再按状态机规则分发到解析确认、库存重置、正式 Gate + Recovery 或重解析等分支;工作台入口须注入 operator_id 以保证审计非匿名。 Args: payload: 必须包含任务定位信息与 decision;可选 comment、lang、operator_id/actor_id。 @@ -431,12 +437,13 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: after=task_lifecycle_audit_snapshot(task), ) db.session.flush() - retry_payload = merge_tool_payload( - task, - payload, - extra={"mode": "retry_rpa", "manual_retry_round": True}, + return _request_formal_gate_action( + task=task, + action_code='retry_inventory_preparation', + user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0), + idempotency_key=str(payload.get('idempotency_key') or f'decision-retry-rpa:{task.task_no}:{task.order_data_version}'), + trigger=event_source, ) - return ensure_inventory(retry_payload) if decision == "rematch": apply_task_transition(task, TaskTransition.REMATCH_REQUESTED) @@ -453,16 +460,15 @@ def submit_decision(payload: dict[str, Any]) -> dict[str, Any]: before=before_snapshot, after=task_lifecycle_audit_snapshot(task), ) - # flush 即可:清状态与 match_inventory 的最终 commit 同属一次连续写入,避免中间态落库。 + # flush 即可:状态清理与正式 Gate Action 入队同属一次连续写入,避免中间态落库。 db.session.flush() - # [STEP 3.1] 重新匹配须同步完成库存计算,避免退回 ready_to_match 后再让用户点 match_inventory。 - match_result = match_inventory(merge_tool_payload(task, payload)) - if match_result.get("status") != "failed": - match_result = prepend_tool_message( - match_result, - t("workflow.decision.rematch_done", lang=lang), - ) - return match_result + return _request_formal_gate_action( + task=task, + action_code='retry_inventory_from_matching', + user_id=int(actor_id or resolve_workspace_actor_id(payload) or 0), + idempotency_key=str(payload.get('idempotency_key') or f'decision-rematch:{task.task_no}:{task.order_data_version}'), + trigger=event_source, + ) # [STEP 4] Task 不回退旧 Chatflow;从来源 Candidate 追溯到 Intake Run 后走统一重新识别服务。 if decision == "reparse": diff --git a/backend/app/services/shipping_notice/error_explainability_contract.py b/backend/app/services/shipping_notice/error_explainability_contract.py index 4602bae1..abe66a8b 100644 --- a/backend/app/services/shipping_notice/error_explainability_contract.py +++ b/backend/app/services/shipping_notice/error_explainability_contract.py @@ -410,6 +410,37 @@ def _meta(party: str, action: str, message_zh: str) -> dict[str, str]: # next_action 必须属于 PROCESS_GATE_ACTION_CODES,或为空串表示无可执行动作。 EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { UNKNOWN_BUSINESS_FAILURE_REASON_CODE: _meta('system', '', '业务处理失败,请凭请求编号联系管理员'), + # Gate 契约中未进入分层集合的订单资格 / XFA 诊断码;必须仍有稳定用户文案与下一步。 + 'budget_stopped': _meta('owner', 'open_order_review', '订单识别预算已用尽,请检查文档后进入复核'), + 'business_scenario_not_configured': _meta('admin', 'open_order_review', '业务场景尚未配置,请联系管理员配置后重试'), + 'business_scenario_out_of_scope': _meta('owner', 'open_order_review', '当前业务场景不在系统支持范围内,请进入复核'), + 'business_scenario_unmatched': _meta('owner', 'open_order_review', '未识别出适用的业务场景,请进入复核确认'), + 'customer_confirmation_required': _meta('owner', 'confirm_customer', '客户身份需要确认'), + 'customer_scope_not_configured': _meta('admin', 'open_order_review', '客户业务范围尚未配置,请联系管理员'), + 'customer_scope_out_of_scope': _meta('owner', 'open_order_review', '客户不在当前业务范围内,请进入复核处理'), + 'customer_scope_unmatched': _meta('owner', 'confirm_customer', '未能匹配到当前订单对应的客户'), + 'extraction_emergency_stop': _meta('owner', 'retry_order_extraction', '订单识别已被安全策略停止,请检查文档后重试'), + 'generic_auto_freeze_disabled': _meta('admin', 'open_order_review', '通用自动建单未启用,请联系管理员'), + 'lease_conflict': _meta('system', 'recheck_freeze_readiness', '当前任务正在被其他执行占用,请稍后刷新'), + 'llm_path_cannot_auto_freeze': _meta('owner', 'open_order_review', '智能识别结果尚未通过自动建单资格检查'), + 'multiple_customers_detected': _meta('owner', 'confirm_customer', '检测到多个候选客户,请确认正确客户'), + 'multiple_profiles_detected': _meta('owner', 'open_profile_review', '检测到多个候选模板,请确认适用模板'), + 'not_recoverable': _meta('admin', 'open_order_review', '当前失败不可自动恢复,请联系管理员处理'), + 'pending_orders_present': _meta('owner', 'open_order_review', '仍有订单未完成处理,请先完成订单复核'), + 'profile_auto_freeze_qualification_missing': _meta('owner', 'open_order_review', '订单模板尚未通过自动建单资格检查'), + 'profile_auto_freeze_suspended': _meta('admin', 'open_order_review', '当前模板自动建单已暂停,请联系管理员'), + 'profile_manual_confirmation_required': _meta('owner', 'open_profile_review', '订单模板需要人工确认后才能继续'), + 'run_cancelled': _meta('owner', 'retry_order_extraction', '订单识别已取消,请重新发起处理'), + 'run_failed': _meta('worker', 'retry_order_extraction', '订单识别运行失败,请重试或进入复核'), + 'unit_review_required': _meta('owner', 'open_order_review', '存在文档单元需要人工复核'), + 'version_conflict': _meta('owner', 'open_order_review', '数据版本已变化,请刷新后重新提交'), + 'xfa_evidence_retention_insufficient': _meta('owner', 'open_order_review', 'XFA 证据留存不足,请进入复核补充证据'), + 'xfa_mirror_consistency_insufficient': _meta('owner', 'open_order_review', 'XFA 镜像明细一致性不足,请进入复核'), + 'xfa_profile_checksum_mismatch': _meta('admin', 'open_profile_review', 'XFA 模板校验和不一致,请联系管理员检查模板版本'), + 'xfa_visual_binding_incomplete': _meta('owner', 'open_profile_review', 'XFA 可视化字段绑定不完整,请补充模板绑定'), + 'xfa_visual_bindings_required': _meta('owner', 'open_profile_review', 'XFA 尚未完成可视化字段绑定'), + 'xfa_visual_coverage_insufficient': _meta('owner', 'open_profile_review', 'XFA 可视化字段覆盖不足,请补充模板映射'), + 'xfa_visual_not_publishable': _meta('admin', 'open_profile_review', 'XFA 可视化模板未达到发布条件,请检查模板质量'), # 附件 'attachment_format_unsupported': _meta('owner', 'rematerialize_document', '附件格式不支持'), 'attachment_size_exceeded': _meta('owner', 'rematerialize_document', '附件超过系统大小限制'), @@ -570,8 +601,6 @@ EXPLAINABILITY_REASON_META: Final[dict[str, dict[str, str]]] = { 'excel_template_missing': _meta('admin', 'recheck_excel_readiness', '发货 Excel 模板缺失'), 'excel_input_incomplete': _meta('owner', 'recheck_excel_readiness', '生成 Excel 所需输入不完整'), 'artifact_validation_failed': _meta('system', 'regenerate_excel_artifact', 'Excel 产物校验失败'), - 'upload_rpa_login_failed': _meta('admin', 'regenerate_manual_upload_todo', '货代平台登录失败'), - 'upload_platform_rejected': _meta('owner', 'regenerate_manual_upload_todo', '货代平台拒绝本次上传'), 'inventory_required_column_missing': _meta('owner', 'confirm_inventory_field_mapping', '库存文件缺少必填列'), 'inventory_column_ambiguous': _meta('owner', 'confirm_inventory_field_mapping', '库存列映射存在歧义'), 'inventory_sku_not_found': _meta('owner', 'open_inventory_match_review', '库存中未找到对应 SKU'), diff --git a/backend/app/services/shipping_notice/export.py b/backend/app/services/shipping_notice/export.py index d646641d..bd46ed20 100644 --- a/backend/app/services/shipping_notice/export.py +++ b/backend/app/services/shipping_notice/export.py @@ -21,6 +21,7 @@ from zoneinfo import ZoneInfo from flask import current_app from openpyxl import load_workbook +from openpyxl.cell.cell import MergedCell from sqlalchemy import func from app import db from app.models import ( @@ -29,6 +30,7 @@ from app.models import ( ShippingInventoryField, ShippingInventorySource, ShippingOrderSnapshot, + ShippingOrderField, ShippingNotice, ) from app.path_utils import resolve_backend_relative_path @@ -59,7 +61,39 @@ def order_field_id_values(task: ShippingNotice) -> tuple[dict[str, Any], list[di return header, lines -def _system_fact(task: ShippingNotice, key: str, *, export_sequence: int | None = None) -> Any: +def _excel_business_no(task: ShippingNotice, *, export_date: date | None = None) -> str | None: + """生成本次 Excel 使用的 Pull Request Number;不回写业务单主编号。""" + case = task.shipping_case + if case is None or not case.business_no: + return None + business_no = str(case.business_no).strip() + prefix = business_no[:-8] if len(business_no) > 8 else business_no + sequence = business_no[-2:] if len(business_no) >= 2 and business_no[-2:].isdigit() else '' + if not sequence and case.sequence_value: + sequence = f'{int(case.sequence_value):02d}' + if not sequence: + return None + export_date = export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date() + return f'{prefix}{export_date.strftime("%y%m%d")}{sequence}' + + +def _clear_template_data_rows(ws: Any, start_row: int) -> None: + """清除模板数据起始行之后的所有单元格值,保留模板表头与样式。""" + for row_index in range(start_row, ws.max_row + 1): + for column_index in range(1, ws.max_column + 1): + cell = ws.cell(row_index, column_index) + if not isinstance(cell, MergedCell): + cell.value = None + + +def _system_fact( + task: ShippingNotice, + key: str, + *, + export_sequence: int | None = None, + excel_business_no: str | None = None, + export_date: date | None = None, +) -> Any: """ 读取受控任务事实,模板不能通过任意属性路径访问 ORM。 @@ -73,10 +107,10 @@ def _system_fact(task: ShippingNotice, key: str, *, export_sequence: int | None """ values = { 'task_no': task.task_no, - 'business_no': task.shipping_case.business_no if task.shipping_case else None, + 'business_no': excel_business_no or (task.shipping_case.business_no if task.shipping_case else None), 'warehouse_id': task.inventory_warehouse_id, 'inventory_source_code': task.inventory_source_code, - 'export_date': datetime.now(ZoneInfo('Asia/Shanghai')).date(), + 'export_date': export_date or datetime.now(ZoneInfo('Asia/Shanghai')).date(), 'export_sequence': export_sequence, } return values.get(key) @@ -110,6 +144,8 @@ def _format_value(value: Any, formatter: str) -> Any: def _mapping_value( mapping: dict[str, Any], *, task: ShippingNotice, order_values: dict[str, Any], inventory_values: dict[str, Any], header_values: dict[str, Any] | None = None, export_sequence: int | None = None, + excel_business_no: str | None = None, + export_date: date | None = None, ) -> Any: """ 按映射来源类型读取值;未知来源已在模板发布时被拒绝。 @@ -132,6 +168,16 @@ def _mapping_value( key = mapping['source_key'] if kind == 'order_field': value = order_values.get(key) + field = db.session.get(ShippingOrderField, key) if key else None + field_code = str(field.field_code or '') if field else '' + if value in (None, '') and field_code == 'line_no' and export_sequence is not None: + value = export_sequence + if value in (None, '') and field_code == 'line_amount_with_tax': + value = order_values.get('__line_amount') + qty = order_values.get('__qty') + unit_price = order_values.get('__unit_price') + if value in (None, '') and qty not in (None, '') and unit_price not in (None, ''): + value = Decimal(str(qty)) * Decimal(str(unit_price)) if value is None and mapping.get('row_mode') == 'line' and header_values is not None: value = header_values.get(key) elif kind == 'inventory_field': @@ -140,6 +186,8 @@ def _mapping_value( value = _system_fact( task, key, export_sequence=export_sequence if key == 'export_sequence' else None, + excel_business_no=excel_business_no, + export_date=export_date, ) if key == 'export_sequence' and value is None: value = order_values.get('__export_sequence') @@ -174,6 +222,17 @@ def _inventory_fields_by_mode(mappings: list[dict[str, Any]], row_mode: str) -> return {str(item.id) for item in rows} +def _inventory_field_user_label(field_id: str) -> str: + """把库存字段主键转换为用户可读中文名,禁止在业务错误中直接暴露「字段 6」。""" + normalized = str(field_id or '').strip() + if normalized.isdigit(): + row = ShippingInventoryField.query.filter_by(id=int(normalized)).first() + display_name = str(getattr(row, 'display_name', '') or '').strip() if row else '' + if display_name: + return display_name + return f'库存字段(编号 {normalized or "未知"})' + + def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set[str]) -> dict[str, Any]: """多库存行仅在模板所需字段值一致时合并,避免任意选择第一行。""" if not rows: @@ -182,7 +241,8 @@ def _collapse_inventory_matches(rows: list[dict[str, Any]], required_fields: set for field in required_fields: values = {_match_text(row.get(field)) for row in rows if _match_text(row.get(field))} if len(values) > 1: - raise ValueError(f'订单行匹配到多个库存记录,字段 {field} 的值不一致') + label = _inventory_field_user_label(field) + raise ValueError(f'订单行匹配到多个库存记录,库存字段“{label}”的值不一致,请检查库存映射或库存文件') if values: resolved[field] = next(row.get(field) for row in rows if _match_text(row.get(field))) return resolved @@ -252,7 +312,12 @@ def _safe_filename(name: str) -> str: return cleaned if cleaned.lower().endswith('.xlsx') else f'{cleaned}.xlsx' -def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str: +def _filename( + task: ShippingNotice, + template: ShippingExcelTemplate, + *, + excel_business_no: str | None = None, +) -> str: """按发布模板规则命名,模板未定义时才使用受控环境变量默认规则。""" pattern = str((template.definition_json or {}).get('filename_pattern') or '').strip() if not pattern: @@ -263,7 +328,7 @@ def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str: shipping_case = task.shipping_case values = { 'task_no': task.task_no, - 'business_no': shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no, + 'business_no': excel_business_no or (shipping_case.business_no if shipping_case and shipping_case.business_no else task.task_no), 'source_code': task.inventory_source_code or '', 'ts': now, 'date': now[:8], @@ -280,14 +345,15 @@ def _filename(task: ShippingNotice, template: ShippingExcelTemplate) -> str: def _input_checksum( task: ShippingNotice, source: ShippingInventorySource, template: ShippingExcelTemplate, snapshot: ShippingOrderSnapshot, header: dict[str, Any], lines: list[dict[str, Any]], + inventory_lines: list[dict[str, Any]], ) -> str: - """计算完整生成输入指纹,供审计和重复生成差异判断。""" + """以本次实际导出库存行计算输入指纹,保证 Artifact 内容与审计事实一致。""" payload = { 'task_id': task.id, 'source_id': source.id, 'template_id': template.id, 'template_checksum': template.file_checksum, 'definition_checksum': template.definition_checksum, 'schema_version_id': snapshot.schema_version_id, 'snapshot_id': snapshot.id, 'parsing_profile_id': source.parsing_profile_id, 'inventory_snapshot_id': task.inventory_snapshot_id, - 'order_header': header, 'order_lines': lines, 'inventory_lines': task.inventory_lines_json or [], + 'order_header': header, 'order_lines': lines, 'inventory_lines': inventory_lines, } raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':'), default=str) return hashlib.sha256(raw.encode('utf-8')).hexdigest() @@ -388,6 +454,8 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp if snapshot is None: raise ValueError('任务没有可用于导出的冻结订单快照') header_values, all_line_values = order_field_id_values(task) + export_date = datetime.now(ZoneInfo('Asia/Shanghai')).date() + excel_business_no = _excel_business_no(task, export_date=export_date) from app.services.shipping_notice.reservation_service import ( current_available_snapshot_line_ids, reserve_available_for_artifact, @@ -398,10 +466,17 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp for line, values in zip(snapshot.lines, all_line_values, strict=True): if line.id not in available_line_ids: continue - line_values.append(dict(values)) + row = dict(values) + row['__qty'] = line.qty + row['__unit_price'] = line.unit_price + row['__line_amount'] = line.amount + line_values.append(row) for index, row in enumerate(line_values, start=1): row['__export_sequence'] = index - inventory_lines = [item for item in (task.inventory_lines_json or []) if isinstance(item, dict)] + from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution + + # [STEP 2] 活动库存 Link 是运行时唯一事实源;仅无 Link 的历史任务由读取服务回退旧缓存。 + inventory_lines = resolve_inventory_lines_for_execution(task) definition = template.definition_json or {} mappings = definition.get('mappings') if isinstance(definition.get('mappings'), list) else [] if not mappings: @@ -415,7 +490,7 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp ) if (line_inventory_fields or header_inventory_fields) else [{} for _item in line_values] header_inventory = _header_inventory_values(matched_inventory_lines, header_inventory_fields) - filename = _filename(task, template) + filename = _filename(task, template, excel_business_no=excel_business_no) artifact_no = f'EXP-{datetime.utcnow():%Y%m%d}-{uuid.uuid4().hex[:10].upper()}' directory = _storage_root() / 'exports' / f'{datetime.utcnow():%Y}' / f'{datetime.utcnow():%m}' / task.task_no directory.mkdir(parents=True, exist_ok=True) @@ -427,6 +502,12 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp path.write_bytes(template_bytes) wb = load_workbook(path) try: + data_start_rows = { + str(sheet): min(int(item['start_row']) for item in mappings if item['sheet'] == sheet) + for sheet in {str(item['sheet']) for item in mappings} + } + for sheet, start_row in data_start_rows.items(): + _clear_template_data_rows(wb[sheet], start_row) for mapping in mappings: ws = wb[mapping['sheet']] start_row = int(mapping['start_row']) @@ -434,11 +515,11 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp if mapping['row_mode'] == 'header': ws.cell(start_row, column).value = _mapping_value( mapping, task=task, order_values=header_values, inventory_values=header_inventory, + excel_business_no=excel_business_no, + export_date=export_date, ) continue row_count = max(len(line_values), 1) - for row_index in range(start_row, max(ws.max_row, start_row + row_count - 1) + 1): - ws.cell(row_index, column).value = None for index in range(row_count): order_line = line_values[index] if index < len(line_values) else {} inventory_line = matched_inventory_lines[index] if index < len(matched_inventory_lines) else {} @@ -446,6 +527,8 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp mapping, task=task, order_values=order_line, inventory_values=inventory_line, header_values=header_values, export_sequence=int(order_line.get('__export_sequence') or (index + 1)), + excel_business_no=excel_business_no, + export_date=export_date, ) wb.save(path) finally: @@ -458,7 +541,9 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp artifact_no=artifact_no, task_id=task.id, template_id=template.id, order_schema_version_id=snapshot.schema_version_id, order_extraction_id=snapshot.extraction_id, inventory_parsing_profile_id=source.parsing_profile_id, inventory_snapshot_id=task.inventory_snapshot_id, - input_checksum=_input_checksum(task, source, template, snapshot, header_values, line_values), + input_checksum=_input_checksum( + task, source, template, snapshot, header_values, line_values, inventory_lines, + ), file_path=str(path), file_name=filename, file_checksum=hashlib.sha256(content).hexdigest(), file_size=len(content), status='ready', ) diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index 34aaef4f..6f2bbbb0 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -30,7 +30,7 @@ from app.core.errors import ConflictError, ServiceUnavailableError, ValidationEr from app.models import ShippingNotice from app.services.shipping_notice.constants import CP_UPLOADED from app.services.shipping_notice.export import generate_shipment_excel, order_field_id_values -from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task +from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution from app.services.shipping_notice.inventory_workflow import ( ensure_inventory, parse_inventory_lines, @@ -902,11 +902,9 @@ def match_inventory_line(payload: dict[str, Any], *, line_key: str) -> dict[str, if extraction_gate is not None: return extraction_gate # [STEP 1] inventory snapshot - inventory_lines = parse_inventory_lines(payload) - if inventory_lines: - task.inventory_lines_json = inventory_lines - else: - inventory_lines = active_inventory_lines_for_task(task) + inventory_lines = resolve_inventory_lines_for_execution( + task, legacy_payload_lines=parse_inventory_lines(payload), + ) if not inventory_lines: # 行级没有快照 → 直接要求 ensure_inventory(和整单一致语义) inv_payload: dict[str, Any] = {"task_id": task.task_no, 'line_key': target_key} @@ -1197,6 +1195,49 @@ def _current_line_results(task: ShippingNotice) -> list[dict[str, Any]]: return list(task.line_results_json or []) +def _profile_match_persistence_payload( + line_results: list[dict[str, Any]], + *, + inventory_source_code: str | None, +) -> dict[str, list[dict[str, Any]]]: + """ + 将单源 Profile 匹配结果转换为结构化行事实写入载荷。 + + 核心逻辑:按结果稳定行序补齐 line_index;resolutions 不写临时 line-N, + 由持久化层使用同一行序关联 Case 草稿的真实 line_key。 + + Args: + line_results: match_notice_lines 返回的逐行结果。 + inventory_source_code: 当前正式库存源编码。 + + Returns: + 含 line_results 与 resolutions 的持久化载荷。 + """ + return { + 'line_results': [ + { + **row, + 'line_index': index, + 'disposition': 'ok' if row.get('line_status') == 'ok' else 'shortage', + } + for index, row in enumerate(line_results) + ], + 'resolutions': [ + { + 'line_index': index, + # 让持久化层按 Case 草稿的 line_key(如 machine-1)解析; + # 不写入临时 line-N,避免 Review Projection 无法关联事实。 + 'line_key': row.get('line_key'), + 'part_number': row.get('part_number'), + 'effective_reservation_id': row.get('reservation_id'), + 'disposition': 'ok' if row.get('line_status') == 'ok' else 'shortage', + 'resolved_inventory_source_code': inventory_source_code, + } + for index, row in enumerate(line_results) + ], + } + + def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: """ 将发货通知订单行与库存快照进行 Reservation ID 匹配,并按结果推进任务状态。 @@ -1280,11 +1321,9 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: return extraction_gate # [STEP 1] 正式库存已在载入阶段按 published Profile 校验;这里只确认库存快照是否就绪。 - inventory_lines = parse_inventory_lines(payload) - if inventory_lines: - task.inventory_lines_json = inventory_lines - else: - inventory_lines = active_inventory_lines_for_task(task) + inventory_lines = resolve_inventory_lines_for_execution( + task, legacy_payload_lines=parse_inventory_lines(payload), + ) if not inventory_lines: inv_payload: dict[str, Any] = {"task_id": task.task_no} lang = str(payload.get("lang") or payload.get("locale") or payload.get("language") or "").strip() @@ -1379,7 +1418,10 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: or purpose_line.get('unit') or (order_field_lines[index] if index < len(order_field_lines) else {}).get('__display_uom') ), - 'line_key': (order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key'), + 'line_key': ( + (order_field_lines[index] if index < len(order_field_lines) else {}).get('line_key') + or f'line-{index + 1}' + ), }) match_payload = match_order_lines_across_candidates( order_lines=attach_candidate_scope_to_order_lines(task, stp_order_lines), @@ -1522,6 +1564,20 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]: quantity_field_id=str(quantity_fields[0].id), progress_callback=_on_match_progress, ) + # 整单匹配与行级匹配必须写入同一结构化事实表;Review Projection 只读取该表。 + # 仅更新 line_results_json 会导致订单明细继续显示“待确认”。 + from app.services.shipping_notice.line_inventory_match_persistence import ( + persist_line_inventory_match_facts, + ) + persist_line_inventory_match_facts( + task=task, + match_payload=_profile_match_persistence_payload( + line_results, + inventory_source_code=task.inventory_source_code, + ), + inventory_snapshot_id=(int(task.inventory_snapshot_id) if task.inventory_snapshot_id else None), + matching_rule_version='profile_match_v1', + ) task.match_status = match_status task.line_results_json = line_results task.shortage_json = shortage @@ -1597,6 +1653,29 @@ def generate_excel(payload: dict[str, Any]) -> dict[str, Any]: Returns: dict[str, Any]: 含 download_hint 的 Tool 响应;门禁失败时 forbidden_next_tools 含 upload_to_freight。 """ + # [T5 Orchestrator 守卫]:外部请求只能提交正式 artifact_generation Gate; + # 只有 ProcessGate Executor 才能携带内部标记执行实际 Excel 生成。 + if not payload.get('_orchestrator_internal_dispatch', False): + from app.services.shipping_notice.progress_workflow import run_task_auto_progress + from app.services.shipping_notice.query_service import resolve_task_from_payload as _rtp + task_no = str(payload.get('task_no') or payload.get('task_id') or '').strip() + if not task_no and isinstance(payload, dict): + _task = _rtp(payload) + task_no = str(getattr(_task, 'task_no', '') or '').strip() + trigger = str(payload.get('source') or payload.get('trigger') or 'tool_api_generate_excel').strip() + actor_raw = payload.get('operator_id') or payload.get('actor_id') or payload.get('_trusted_user_id') + try: + operator_id = int(actor_raw) if actor_raw is not None and str(actor_raw).strip() and trigger != 'system' else None + except (TypeError, ValueError): + operator_id = None + return run_task_auto_progress( + task_no, + trigger=trigger, + expected_version=None, + idempotency_key=str(payload.get('idempotency_key') or '').strip() or None, + resume_gate_code='artifact_generation', + operator_id=operator_id, + ) lang = resolve_lang(payload) actor_id = _event_actor_id(payload) task = resolve_task_from_payload(payload) diff --git a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py b/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py index a4c7fca1..3c1f1468 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py +++ b/backend/app/services/shipping_notice/inventory_candidate_freeze_service.py @@ -257,9 +257,22 @@ def _next_task_set_version(*, task_id: int, session: Session) -> int: return int(current_max or 0) + 1 -def _invalidate_task_candidate_outputs(task: ShippingNotice, *, session: Session) -> None: - """重冻结后立即失效旧匹配、导出与待上传事实,避免旧版本继续被消费。""" - from app.models import ShippingNoticeLineInventoryMatch, ShippingTaskInventoryRpaAttempt +def _invalidate_task_candidate_outputs( + task: ShippingNotice, *, old_candidate_set_id: int | None, session: Session, +) -> None: + """重冻结后失效旧候选版本的准备、恢复、匹配、导出与上传事实。 + + 仅取消旧版本的非终态记录,不删除审计;新 CandidateSet 随后会创建新的 + 正式 Execution/Attempt,因此迟到 RPA 回调无法写回新链。 + """ + from app.models import ( + ShippingExportArtifact, + ShippingInventoryPreparationAttempt, + ShippingNoticeLineInventoryMatch, + ShippingProcessRecoveryPlan, + ShippingTaskInventoryRpaAttempt, + ShippingUploadAttempt, + ) task.match_status = None task.shortage_json = None @@ -291,6 +304,48 @@ def _invalidate_task_candidate_outputs(task: ShippingNotice, *, session: Session ) .update({'status': 'superseded', 'updated_at': datetime.utcnow()}, synchronize_session=False) ) + artifact_ids = [ + row[0] for row in session.query(ShippingExportArtifact.id).filter( + ShippingExportArtifact.task_id == int(task.id), + ShippingExportArtifact.status.in_(('ready', 'uploading')), + ).all() + ] + if artifact_ids: + session.query(ShippingExportArtifact).filter( + ShippingExportArtifact.id.in_(artifact_ids), + ).update({'status': 'superseded'}, synchronize_session=False) + session.query(ShippingUploadAttempt).filter( + ShippingUploadAttempt.artifact_id.in_(artifact_ids), + ShippingUploadAttempt.status.in_(('pending', 'running', 'timed_out', 'unknown')), + ).update({ + 'status': 'failed', + 'invalidated_at': datetime.utcnow(), + 'invalidation_reason': 'candidate_set_refrozen', + 'finished_at': datetime.utcnow(), + 'error_code': 'candidate_set_refrozen', + }, synchronize_session=False) + prep_query = session.query(ShippingInventoryPreparationAttempt).filter( + ShippingInventoryPreparationAttempt.task_id == int(task.id), + ShippingInventoryPreparationAttempt.status.in_(('queued', 'running', 'waiting_external', 'waiting_manual')), + ) + if old_candidate_set_id is not None: + prep_query = prep_query.filter( + ShippingInventoryPreparationAttempt.candidate_set_id == int(old_candidate_set_id) + ) + prep_query.update({'status': 'superseded'}, synchronize_session=False) + active_execution_ids = [ + row[0] for row in session.query(ShippingInventoryPreparationAttempt.execution_id).filter( + ShippingInventoryPreparationAttempt.task_id == int(task.id), + ShippingInventoryPreparationAttempt.candidate_set_id == old_candidate_set_id, + ).all() if row[0] + ] + if active_execution_ids: + session.query(ShippingProcessRecoveryPlan).filter( + ShippingProcessRecoveryPlan.execution_id.in_(active_execution_ids), + ShippingProcessRecoveryPlan.status.in_( + ('planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual') + ), + ).update({'status': 'cancelled', 'completed_at': datetime.utcnow()}, synchronize_session=False) def freeze_candidates_for_task( @@ -524,7 +579,9 @@ def freeze_candidates_for_task( existing_active.lifecycle_status = 'superseded' existing_active.superseded_at = datetime.utcnow() existing_active.superseded_by_set_id = int(new_set.id) - _invalidate_task_candidate_outputs(task, session=session) + _invalidate_task_candidate_outputs( + task, old_candidate_set_id=int(existing_active.id), session=session, + ) if getattr(task, 'id', None) is not None: task.active_inventory_candidate_set_id = int(new_set.id) diff --git a/backend/app/services/shipping_notice/inventory_candidate_projection.py b/backend/app/services/shipping_notice/inventory_candidate_projection.py index 3444ede7..66a877a7 100644 --- a/backend/app/services/shipping_notice/inventory_candidate_projection.py +++ b/backend/app/services/shipping_notice/inventory_candidate_projection.py @@ -20,6 +20,7 @@ from app.models import ( ShippingInventoryCandidateLine, ShippingInventoryCandidateSet, ShippingInventoryCandidateSource, + ShippingInventoryFile, ShippingNotice, ShippingNoticeLineInventoryMatch, ShippingTaskInventoryRpaAttempt, @@ -472,6 +473,10 @@ def project_inventory_candidate_facts( stale_details: dict[str, Any] | None = None out_of_scope_details: dict[str, Any] | None = None for row in _current_match_rows(task, session=sess): + snapshot = ( + sess.get(ShippingInventoryFile, int(row.inventory_snapshot_id)) + if getattr(row, 'inventory_snapshot_id', None) is not None else None + ) allowed_codes = _normalized_codes(getattr(row, 'allowed_source_codes_snapshot', None)) serialized = { 'id': int(row.id), @@ -486,6 +491,13 @@ def project_inventory_candidate_facts( 'inventory_file_no': getattr(row, 'matched_file_no', None), 'inventory_snapshot_id': getattr(row, 'inventory_snapshot_id', None), 'inventory_row_ref': (dict(getattr(row, 'detail_json', None) or {}).get('inventory_row_ref')), + 'inventory_file_sha256': ( + dict(getattr(row, 'detail_json', None) or {}).get('file_sha256') + or dict(getattr(row, 'detail_json', None) or {}).get('inventory_file_sha256') + or getattr(snapshot, 'file_sha256', None) + ), + 'inventory_row_index': getattr(row, 'matched_row_index', None), + 'match_attempt_id': getattr(row, 'match_attempt_id', None), 'required_qty': getattr(row, 'required_qty', None), 'matched_qty': getattr(row, 'matched_qty', None) or getattr(row, 'available_qty', None), 'match_result': getattr(row, 'match_result', None), diff --git a/backend/app/services/shipping_notice/inventory_combination_fingerprint.py b/backend/app/services/shipping_notice/inventory_combination_fingerprint.py new file mode 100644 index 00000000..4ee2d573 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_combination_fingerprint.py @@ -0,0 +1,33 @@ +""" +services/shipping_notice/inventory_combination_fingerprint.py + +用途:为多源库存准备轮次生成稳定组合输入指纹。 +依赖:标准库 hashlib/json。 +逻辑:对任务快照、候选冻结、逐源快照/Hash/解析映射版本、Reservation 和匹配规则做规范化哈希。 +""" + +from __future__ import annotations + +import hashlib +import json +from typing import Any, Iterable + + +def build_inventory_combination_fingerprint( + *, task_snapshot_fingerprint: str | None, candidate_freeze_fingerprint: str | None, + sources: Iterable[dict[str, Any]], reservation_version: str | None = None, + matching_rule_version: str | None = None, +) -> str: + """按稳定排序构建组合输入 SHA-256 指纹。""" + payload = { + 'task_snapshot_fingerprint': task_snapshot_fingerprint, + 'candidate_freeze_fingerprint': candidate_freeze_fingerprint, + 'sources': sorted( + [dict(item) for item in sources], + key=lambda item: (str(item.get('source_code') or ''), int(item.get('snapshot_id') or 0)), + ), + 'reservation_version': reservation_version, + 'matching_rule_version': matching_rule_version, + } + raw = json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(',', ':')).encode('utf-8') + return hashlib.sha256(raw).hexdigest() diff --git a/backend/app/services/shipping_notice/inventory_file_store.py b/backend/app/services/shipping_notice/inventory_file_store.py index a78210b9..07e1508f 100644 --- a/backend/app/services/shipping_notice/inventory_file_store.py +++ b/backend/app/services/shipping_notice/inventory_file_store.py @@ -9,6 +9,7 @@ services/shipping_notice/inventory_file_store.py from __future__ import annotations import re +import hashlib import shutil import uuid from pathlib import Path @@ -90,6 +91,15 @@ def inventory_file_upload_path(inventory_file_no: str, *, suffix: str = ".xlsx") return _storage_root() / "inventory_uploads" / _safe_ref(inventory_file_no) / f"inventory{normalized}" +def _file_sha256(path: Path) -> str: + """计算已落盘库存快照的内容指纹,供复用和组合输入门禁使用。""" + digest = hashlib.sha256() + with path.open('rb') as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b''): + digest.update(chunk) + return digest.hexdigest() + + def inventory_storage_suffix_for_path(path: str | Path) -> str: """根据已有文件路径推导库存快照落盘后缀,未知格式回退 .xlsx。""" suffix = Path(path).suffix.lower() @@ -135,10 +145,46 @@ def active_inventory_file_for_task(task: ShippingNotice) -> ShippingInventoryFil def active_inventory_lines_for_task(task: ShippingNotice) -> list[dict[str, Any]]: - """解析任务可用于匹配的库存行;批次库存快照优先,单票任务回退到任务投影字段。""" + """读取任务活动库存快照;已有 JSON 是快照事实,禁止读取时被物理文件静默覆盖。""" inv_file = active_inventory_file_for_task(task) if inv_file and isinstance(inv_file.inventory_lines_json, list): - return [row for row in inv_file.inventory_lines_json if isinstance(row, dict)] + rows = [row for row in inv_file.inventory_lines_json if isinstance(row, dict)] + if not rows and Path(inv_file.storage_path).is_file(): + try: + reparsed, _meta = parse_inventory_snapshot_file(inv_file) + if reparsed: + inv_file.inventory_lines_json = reparsed + inv_file.line_count = len(reparsed) + db.session.flush() + rows = reparsed + except Exception: # noqa: BLE001 + # 解析失败时保留原快照,交由上层 Gate 报告可解释错误。 + pass + return rows + return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)] + + +def resolve_inventory_lines_for_execution( + task: ShippingNotice, + *, + legacy_payload_lines: list[dict[str, Any]] | None = None, +) -> list[dict[str, Any]]: + """ + 解析库存匹配与导出的统一运行输入,活动库存 Link 为唯一事实源。 + + Args: + task: 当前正式发货通知。 + legacy_payload_lines: 旧 Tool 请求携带的库存行;仅无活动 Link 的历史任务允许使用。 + + Returns: + 本次执行使用的库存行;不会回写 ``ShippingNotice.inventory_lines_json``。 + """ + if active_inventory_file_for_task(task) is not None: + return active_inventory_lines_for_task(task) + if isinstance(legacy_payload_lines, list): + rows = [row for row in legacy_payload_lines if isinstance(row, dict)] + if rows: + return rows return [row for row in (task.inventory_lines_json or []) if isinstance(row, dict)] @@ -213,16 +259,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh message='库存文件没有可用于匹配的有效库存数据', http_status=409, ) - from app.services.shipping_notice.inventory_file_identity import ( - assert_inventory_excel_warehouse_identity, - ) - - if str(warehouse_id or '').strip(): - assert_inventory_excel_warehouse_identity( - path, - expected_warehouse_id=str(warehouse_id or ""), - operation="manual_upload", - ) + # 手工上传同样只保留文件 Warehouse 事实,不要求其等于页面当前库位编码。 preview = read_inventory_schema_preview(path) preview["upload_filename"] = str(upload.filename or path.name) preview['structure_validation'] = column_meta['structure_validation'] @@ -250,6 +287,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh user_id=task.user_id, source_file_name=str(upload.filename or "").strip() or path.name, storage_path=str(path), + file_sha256=_file_sha256(path), schema_preview_json=preview, share_mode="task_only", line_count=len(inventory_lines), @@ -351,6 +389,7 @@ def save_task_inventory_file_from_local_path( user_id=task.user_id, source_file_name=str(source_file_name or source.name or path.name).strip() or path.name, storage_path=str(path), + file_sha256=_file_sha256(path), schema_preview_json=preview, share_mode="task_only", line_count=0, diff --git a/backend/app/services/shipping_notice/inventory_mapping.py b/backend/app/services/shipping_notice/inventory_mapping.py index 693d5dbe..f124f1e4 100644 --- a/backend/app/services/shipping_notice/inventory_mapping.py +++ b/backend/app/services/shipping_notice/inventory_mapping.py @@ -8,6 +8,7 @@ services/shipping_notice/inventory_mapping.py from __future__ import annotations +import re from typing import Any from app.models import ShippingInventoryField @@ -226,6 +227,14 @@ def resolve_columns_from_field_mapping( """将显式 field_mapping 转为库存字段 ID → 列索引;未配置字段不自动猜测。""" norm_headers = [str(h or "").strip() for h in headers] lower_to_idx = {h.lower(): i for i, h in enumerate(norm_headers) if h} + # Excel exports may contain line breaks or repeated whitespace in a + # visible header (for example ``Qty\nAvailable``). Explicit published + # mappings must still resolve deterministically without guessing a field. + normalized_to_idx: dict[str, int] = {} + for index, header in enumerate(norm_headers): + key = re.sub(r"[^a-z0-9]+", "", header.lower()) + if key and key not in normalized_to_idx: + normalized_to_idx[key] = index def idx_for(header_name: str | None) -> int | None: if not header_name: @@ -235,7 +244,11 @@ def resolve_columns_from_field_mapping( return None if name in norm_headers: return norm_headers.index(name) - return lower_to_idx.get(name.lower()) + exact_lower = lower_to_idx.get(name.lower()) + if exact_lower is not None: + return exact_lower + normalized = re.sub(r"[^a-z0-9]+", "", name.lower()) + return normalized_to_idx.get(normalized) runtime_mapping, _catalog = runtime_field_mapping(field_mapping) if not runtime_mapping: diff --git a/backend/app/services/shipping_notice/inventory_recovery_service.py b/backend/app/services/shipping_notice/inventory_recovery_service.py new file mode 100644 index 00000000..5146ce3b --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_recovery_service.py @@ -0,0 +1,177 @@ +""" +services/shipping_notice/inventory_recovery_service.py + +用途:创建库存准备轮次及逐源准备事实,支持有效源复用和问题源重拉。 +依赖:PreparationAttempt/SourceAttempt、候选冻结、InventoryFile/TaskLink。 +逻辑:本服务只创建持久化准备状态,不在数据库事务中直接触发外部 RPA。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.models import ( + ShippingInventoryFile, + ShippingInventoryPreparationAttempt, + ShippingInventoryPreparationSourceAttempt, + ShippingNotice, + ShippingTaskInventoryLink, +) +from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task +from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint +from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable + + +def create_inventory_preparation_round( + *, task: ShippingNotice, execution_id: int | None, recovery_plan_id: int | None, + action_code: str, source_codes: list[str] | None = None, operation_id: str | None = None, + gate_attempt_id: int | None = None, +) -> ShippingInventoryPreparationAttempt: + """创建一次任务级准备轮次;同一任务按 attempt_no 递增。""" + last = ShippingInventoryPreparationAttempt.query.filter_by(task_id=int(task.id)).order_by( + ShippingInventoryPreparationAttempt.attempt_no.desc(), + ).first() + round_row = ShippingInventoryPreparationAttempt( + task_id=int(task.id), execution_id=execution_id, gate_attempt_id=gate_attempt_id, + recovery_plan_id=recovery_plan_id, + attempt_no=(int(last.attempt_no) + 1 if last else 1), status='queued', + candidate_set_id=getattr(task, 'active_inventory_candidate_set_id', None), + input_snapshot_json={ + 'action_code': action_code, + 'source_codes': list(source_codes or []), + 'gate_attempt_id': int(gate_attempt_id) if gate_attempt_id else None, + }, + operation_id=operation_id, + created_at=datetime.utcnow(), + ) + db.session.add(round_row) + db.session.flush() + codes = [str(code).strip().upper() for code in (source_codes or []) if str(code).strip()] + if not codes: + codes = [str(getattr(task, 'inventory_source_code', '') or '').strip().upper()] + codes = [code for code in codes if code] + active_file = active_inventory_file_for_task(task) + for source_code in codes: + reusable, _reuse_reasons = check_inventory_snapshot_reusable( + snapshot=active_file, + source_code=source_code, + warehouse_id=getattr(active_file, 'warehouse_id', None) if active_file else None, + source_config_version=getattr(active_file, 'source_config_version', None) if active_file else None, + expected_file_sha256=getattr(active_file, 'file_sha256', None) if active_file else None, + parser_version=getattr(active_file, 'parser_version', None) if active_file else None, + mapping_version=getattr(active_file, 'mapping_version', None) if active_file else None, + ) + reusable = bool(action_code == 'retry_inventory_from_field_mapping' and reusable) + link = ShippingTaskInventoryLink.query.filter_by( + task_id=int(task.id), matched_source_code=source_code, is_active=True, + ).order_by(ShippingTaskInventoryLink.id.desc()).first() + source = ShippingInventoryPreparationSourceAttempt( + preparation_attempt_id=int(round_row.id), source_code=source_code, + status='reusable' if reusable else 'queued', + inventory_file_id=int(active_file.id) if reusable and active_file else None, + task_inventory_link_id=int(link.id) if reusable and link else None, + operation_id=operation_id, + ) + db.session.add(source) + db.session.flush() + round_row.combination_input_fingerprint = build_inventory_combination_fingerprint( + task_snapshot_fingerprint=str(getattr(task, 'content_fingerprint', '') or ''), + candidate_freeze_fingerprint=str(getattr(getattr(task, 'active_inventory_candidate_set', None), 'input_fingerprint', '') or ''), + sources=[ + { + 'source_code': str(item.source_code), + 'snapshot_id': item.inventory_file_id, + 'snapshot_hash': ( + getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'file_sha256', None) + if item.inventory_file_id else None + ), + 'parser_version': ( + getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'parser_version', None) + if item.inventory_file_id else None + ), + 'mapping_version': ( + getattr(db.session.get(ShippingInventoryFile, int(item.inventory_file_id)), 'mapping_version', None) + if item.inventory_file_id else None + ), + } + for item in round_row.source_attempts + ], + reservation_version=str(getattr(task, 'order_data_version', '') or ''), + matching_rule_version=str(getattr(task, 'inventory_source_config_version', '') or ''), + ) + db.session.flush() + return round_row + + +def sync_inventory_preparation_round( + *, preparation_attempt: ShippingInventoryPreparationAttempt, result: Any, +) -> ShippingInventoryPreparationAttempt: + """将 RPA 准备结果回写当前 PreparationAttempt,供 Projection/Gate 使用同一事实源。""" + def _read(name: str, default: Any) -> Any: + return result.get(name, default) if isinstance(result, dict) else getattr(result, name, default) + + prepared = {str(code).strip().upper() for code in _read('prepared_source_codes', [])} + pending = {str(code).strip().upper() for code in _read('pending_source_codes', [])} + failed = {str(code).strip().upper() for code in _read('failed_source_codes', [])} + summaries = dict(_read('source_attempts', {}) or {}) + for source in preparation_attempt.source_attempts: + code = str(source.source_code or '').strip().upper() + summary = dict(summaries.get(code) or {}) + if code in prepared: + source.status = 'ready' if source.status != 'reusable' else 'reusable' + elif code in failed: + source.status = 'failed' + elif code in pending: + source.status = 'waiting' + if summary.get('attempt_id'): + source.rpa_attempt_id = int(summary['attempt_id']) + if failed: + preparation_attempt.status = 'failed' + elif pending: + preparation_attempt.status = 'waiting_external' + else: + preparation_attempt.status = 'succeeded' + preparation_attempt.completed_at = datetime.utcnow() + preparation_attempt.output_snapshot_json = { + 'prepared_source_codes': sorted(prepared), + 'pending_source_codes': sorted(pending), + 'failed_source_codes': sorted(failed), + } + db.session.flush() + return preparation_attempt + + +def sync_preparation_source_from_rpa_attempt( + *, rpa_attempt_id: int, rpa_status: str, inventory_file_id: int | None = None, +) -> None: + """由 RPA 回调回写绑定 SourceAttempt,并聚合其 PreparationAttempt 状态。 + + SourceAttempt 以不可变 RPA Attempt 主键关联;迟到/无关联回调不创建新业务轮次, + 因而不会污染当前 GateAttempt 对应的 PreparationAttempt。 + """ + source = ShippingInventoryPreparationSourceAttempt.query.filter_by( + rpa_attempt_id=int(rpa_attempt_id), + ).order_by(ShippingInventoryPreparationSourceAttempt.id.desc()).first() + if source is None: + return + status = str(rpa_status or '').strip().lower() + if status in {'succeeded', 'consumed'}: + source.status = 'ready' + if inventory_file_id: + source.inventory_file_id = int(inventory_file_id) + elif status in {'failed', 'exhausted'}: + source.status = 'failed' + elif status in {'queued', 'running'}: + source.status = 'waiting' + preparation = source.preparation_attempt + rows = list(getattr(preparation, 'source_attempts', []) or []) + if any(row.status == 'failed' for row in rows): + preparation.status = 'failed' + elif any(row.status in {'queued', 'running', 'waiting'} for row in rows): + preparation.status = 'waiting_external' + elif rows and all(row.status in {'ready', 'reusable', 'skipped'} for row in rows): + preparation.status = 'succeeded' + preparation.completed_at = datetime.utcnow() + db.session.flush() diff --git a/backend/app/services/shipping_notice/inventory_rpa_workflow.py b/backend/app/services/shipping_notice/inventory_rpa_workflow.py index 32b1f020..71af876e 100644 --- a/backend/app/services/shipping_notice/inventory_rpa_workflow.py +++ b/backend/app/services/shipping_notice/inventory_rpa_workflow.py @@ -180,7 +180,6 @@ def _try_reuse_inventory_snapshot( row for row in (snapshot.inventory_lines_json or []) if isinstance(row, dict) ] if cached_lines: - task.inventory_lines_json = cached_lines return inventory_loaded_response( task, cached_lines, @@ -639,7 +638,14 @@ def _lock_task_for_rpa_callback(task: ShippingNotice) -> ShippingNotice: """对任务行加悲观锁,防止并发回调重复消费同一轮次。""" if task.id is None: return task - return db.session.query(ShippingNotice).filter_by(id=task.id).with_for_update().one() + # ShippingNotice 默认关系加载会带 shipping_case 外连接;PostgreSQL 不允许 + # 对外连接空值端执行 FOR UPDATE。回调只需锁任务主表,避免成功文件回调在入库前失败。 + return ( + db.session.query(ShippingNotice) + .filter_by(id=task.id) + .with_for_update(of=ShippingNotice) + .one() + ) def _get_consumed_inventory_rpa_run_no(task: ShippingNotice) -> str: @@ -671,6 +677,23 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any]) """ run_no_error = _validate_rpa_callback_run_no(task, str(payload.get("run_no") or "")) if run_no_error: + # 逐源 batch Trigger 的任务事件可能仍保留旧的 task-level batch_run_no; + # source_run_no 是本次 Attempt 的正式身份,匹配最新 queued/running Attempt + # 时允许该批次回调继续入库,避免已生成的 Excel 被错误当作迟到回调丢弃。 + source_run_no = str(payload.get('source_run_no') or '').strip() + if source_run_no: + from app.models import ShippingTaskInventoryRpaAttempt + + current_attempt = ( + db.session.query(ShippingTaskInventoryRpaAttempt) + .filter_by(task_no=task.task_no, source_run_no=source_run_no) + .order_by(ShippingTaskInventoryRpaAttempt.id.desc()) + .first() + ) + if current_attempt and str(current_attempt.status or '').lower() in {'queued', 'running'}: + run_no_error = None + if not run_no_error: + return None log_task_event( task, "rpa_callback_rejected", @@ -812,6 +835,40 @@ def _validate_rpa_callback_success_identity(task: ShippingNotice, payload: dict[ return None +def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str, Any]) -> dict[str, Any] | None: + """强制单源库存成功回调携带 v2 身份围栏,禁止旧 payload 写入库存事实。 + + 单源 Worker 与批量 Worker 共用 ``shipping_inventory_rpa.v2``;缺少任一 + Attempt/Execution 身份时直接拒绝,避免回调按 Task 级旧 run_no 错绑轮次。 + """ + if str(payload.get('status') or '').strip().lower() != 'success': + return None + required = { + 'schema_version': payload.get('schema_version'), + 'callback_id': payload.get('callback_id'), + 'source_run_no': payload.get('source_run_no'), + 'source_code': payload.get('source_code'), + 'attempt_no': payload.get('attempt_no'), + 'lease_token': payload.get('lease_token'), + 'candidate_set_id': payload.get('candidate_set_id'), + 'execution_id': payload.get('execution_id'), + 'gate_id': payload.get('gate_id'), + } + missing = [key for key, value in required.items() if value in (None, '')] + if required['schema_version'] != 'shipping_inventory_rpa.v2' or missing: + return tool_response( + status='failed', + task=task, + message='单源 RPA 回调缺少完整 v2 身份字段,已拒绝处理', + data={ + **serialize_task_for_tool(task), + 'reason_code': 'callback_schema_invalid', + 'missing_fields': missing, + }, + ) + return None + + def _merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]: """ 合并 batch 顶层契约字段到 result item。 @@ -1180,6 +1237,36 @@ def ensure_inventory_via_rpa(task: ShippingNotice, *, mode: str) -> dict[str, An rpa_source = task_rpa_inventory_source(task) or {} + # retry_rpa 使用逐源 Attempt 编排,确保 Trigger 携带 source_run_no/lease_token, + # Worker 回调后可以精确绑定到本次 Attempt;自动模式继续使用下方旧兼容路径。 + if manual_retry_round: + from app.services.shipping_notice.per_source_rpa_service import ensure_all_required_sources_prepared + + prepared = ensure_all_required_sources_prepared(task, mode='retry_rpa') + db.session.flush() + if prepared.pending_source_codes: + apply_task_transition(task, TaskTransition.RPA_PENDING) + task.error_message = None + db.session.commit() + return tool_response( + status='running', task_id=task.task_no, + message='已重新触发库存获取,等待各库存源回调。', + data={**serialize_task_for_tool(task), 'rpa': { + 'pending_source_codes': prepared.pending_source_codes, + 'source_attempts': prepared.source_attempts, + }}, + ) + if prepared.all_prepared: + return tool_response(status='completed', task=task, message='库存快照已准备完成。') + return tool_response( + status='needs_human', task=task, + message='库存 RPA 未能为全部库存源生成结果。', + data={**serialize_task_for_tool(task), 'rpa': { + 'failed_source_codes': prepared.failed_source_codes, + 'source_attempts': prepared.source_attempts, + }}, + ) + # [STEP 0.5] 未过期库存快照优先复用;retry_rpa 强制跳过。 reused = _try_reuse_inventory_snapshot(task, rpa_source, mode=mode) if reused is not None: @@ -1570,14 +1657,24 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: if not task: return tool_response(status="failed", message="未找到任务编号") + # 单源成功回调必须先通过 v2 身份校验;批量回调走独立 v2 envelope。 + # 失败/跳过回调仍由后续业务错误合同处理,不以缺失文件身份掩盖原始失败。 + if not isinstance(payload.get('results'), list): + contract_resp = _validate_single_source_v2_contract(task, payload) + if contract_resp is not None: + return contract_resp + # [T7 统一回调幂等] 尝试按 per-source run_no 提取 source_code;如符合 PSR-*--A-* 格式则先入 per_source_callback_handler run_no_raw = str(payload.get("run_no") or "").strip() source_code_from_run: str | None = None if run_no_raw and run_no_raw.startswith('PSR-'): - # PSR---A- → 第 3 段 = SOURCE - parts = run_no_raw.split('-') - if len(parts) >= 4 and parts[3].startswith('A'): - candidate = str(parts[2] or '').strip().upper() + # PSR---A-;task_no 本身可含连字符, + # 因此必须从末尾的 source/attempt 结构反向解析,不能使用固定 split 下标。 + import re + + match = re.match(r'^PSR-(?P.+)-(?P[^-]+)-A\d+-[^-]+$', run_no_raw) + if match: + candidate = str(match.group('source') or '').strip().upper() if candidate: source_code_from_run = candidate per_source_result = None @@ -1601,6 +1698,54 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]: "idempotent": True, }, ) + if per_source_code == 'callback_conflict': + # callback_id 已归属于其他 Attempt;不得继续走兼容入口写入库存正式事实。 + log_task_event( + task, + 'shipping_inventory_callback_ignored', + { + 'run_no': run_no_raw, + 'source_code': source_code_from_run, + 'reason': 'callback_id_already_consumed_by_other_attempt', + 'callback_id': str(payload.get('callback_id') or '').strip(), + }, + source='rpa_callback', + ) + return tool_response( + status='success', + task=task, + message='RPA 回调已被其他 Attempt 消费,本次回调忽略。', + data={ + 'run_no': run_no_raw, + 'source_code': source_code_from_run, + 'callback_conflict': True, + 'retry_safe': False, + }, + ) + if per_source_code == 'identity_mismatch': + # v2 身份围栏未通过时必须在统一入口 fail-closed,禁止回落到 Task 级旧回调路径。 + log_task_event( + task, + 'rpa_callback_rejected', + { + 'run_no': run_no_raw, + 'source_code': source_code_from_run, + 'reason': 'callback_identity_mismatch', + 'callback_id': str(payload.get('callback_id') or '').strip(), + }, + source='rpa_callback', + ) + return tool_response( + status='failed', + task=task, + message='RPA 回调身份与当前库存准备轮次不一致,已拒绝处理。', + data={ + 'run_no': run_no_raw, + 'source_code': source_code_from_run, + 'error_code': 'callback_identity_mismatch', + 'retry_safe': False, + }, + ) if per_source_code == 'superseded_late': log_task_event( task, @@ -1969,7 +2114,12 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: raw_status = _normalize_rpa_inventory_batch_item_status(merged_item) task_no = str(merged_item.get("task_no") or "").strip() run_no_item = str(merged_item.get("run_no") or "").strip() or run_no - source_run_no_item = str(merged_item.get("source_run_no") or "").strip() + # Worker 旧版只回传 run_no;三元组定位 Attempt 时用本批次 run_no 兜底, + # 否则成功文件已入库但旧 failed Attempt 永远不会被收敛。 + source_run_no_item = ( + str(merged_item.get("source_run_no") or "").strip() + or run_no_item + ) item_callback_id = str(merged_item.get("callback_id") or "").strip() if not item_callback_id and source_run_no_item: item_callback_id = f"{callback_id}:{source_run_no_item}:C1" @@ -1991,7 +2141,7 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: }) continue # [T7 批量回调幂等] 每个 item 先走 per_source_callback_handler;batch 中单独处理不中断整体 - if source_code and source_run_no_item and raw_status != 'success': + if source_code and source_run_no_item: from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler per_source_code, _a = per_source_callback_handler( task, @@ -2040,6 +2190,27 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: "retry_safe": True, }) continue + if per_source_code == 'identity_mismatch': + log_task_event( + task, + 'rpa_callback_rejected', + { + 'run_no': run_no_item, + 'source_code': source_code, + 'reason': 'callback_identity_mismatch', + 'callback_id': item_callback_id, + 'batch': True, + }, + source='rpa_callback', + ) + failed.append({ + 'source_code': source_code, + 'warehouse_id': warehouse_id, + 'task_no': task_no, + 'error_code': 'callback_identity_mismatch', + 'error': 'RPA callback identity does not match the active preparation attempt.', + }) + continue task = _lock_task_for_rpa_callback(task) if task and raw_status in {"skipped", "failed"}: @@ -2120,6 +2291,15 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: continue if raw_status == "success": + # 定时批量成功项必须显式携带 Warehouse 身份;先做身份校验, + # 避免缺 Warehouse 被后续文件路径错误遮蔽。 + if not warehouse_id: + failed.append({ + "source_code": source_code, + "warehouse_id": warehouse_id, + "error": "warehouse_id_missing", + }) + continue file_path = str(merged_item.get("file_path") or "").strip() path = Path(file_path).resolve() if file_path else None from app.services.shipping_notice.rpa import inventory_drop_dir @@ -2237,7 +2417,10 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]: from app.models import ShippingTaskInventoryRpaAttempt _att = db.session.query(ShippingTaskInventoryRpaAttempt).filter_by(task_no=task_no, source_code=source_code, source_run_no=source_run_no_item).one_or_none() if _att: + # 成功回调是该 Attempt 的最终事实;清理旧失败态,避免投影继续显示 failed/retry。 + _att.status = 'succeeded' _att.callback_id = item_callback_id or callback_id; _att.callback_received_at = datetime.utcnow(); _att.file_generated = True; _att.file_path = str(path); _att.file_sha256 = server_hash; _att.file_size = server_size; _att.file_exists_at_callback = True; _att.execution_phase = 'callback_received'; _att.transaction_status = 'succeeded' + _att.error_code = None; _att.error_message = None; _att.transaction_error_code = None created.append(created_entry) if item_orphan_path: batch_new_storage_paths.append(item_orphan_path) diff --git a/backend/app/services/shipping_notice/inventory_snapshot.py b/backend/app/services/shipping_notice/inventory_snapshot.py index b6c4a15a..af621fdd 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot.py +++ b/backend/app/services/shipping_notice/inventory_snapshot.py @@ -212,6 +212,26 @@ def _normalize_inventory_row( parsed[field_id] = value.isoformat() if hasattr(value, 'isoformat') else str(value).strip() else: parsed[field_id] = str(value).strip() + # 正式运行快照对外统一 canonical 字段;同时保留字段 ID 供审计和旧 Profile 回放。 + canonical_by_code = { + 'part_number': 'part_number', + 'reservation_id': 'reservation_id', + 'available_qty': 'available_qty', + 'qty': 'available_qty', + 'unit': 'uom', + 'warehouse_id': 'warehouse_id', + 'warehouse_code': 'warehouse_id', + } + for field_id, field in catalog.items(): + target = canonical_by_code.get(str(field.field_code or '').strip()) + if target and parsed.get(field_id) not in (None, ''): + parsed[target] = parsed[field_id] + if 'reservation_id' in parsed: + parsed['reservation_id'] = validated_reservation_id(parsed['reservation_id']) + if 'part_number' in parsed: + parsed['part_number'] = str(parsed['part_number'] or '').strip() + if 'available_qty' in parsed: + parsed['available_qty'] = _parse_qty(parsed['available_qty']) return parsed idx_part_number = columns.get("part_number") diff --git a/backend/app/services/shipping_notice/inventory_snapshot_reuse_policy.py b/backend/app/services/shipping_notice/inventory_snapshot_reuse_policy.py new file mode 100644 index 00000000..c6b4c354 --- /dev/null +++ b/backend/app/services/shipping_notice/inventory_snapshot_reuse_policy.py @@ -0,0 +1,52 @@ +""" +services/shipping_notice/inventory_snapshot_reuse_policy.py + +用途:统一判断库存快照是否可被当前任务复用。 +依赖:ShippingInventoryFile、ShippingNotice、候选冻结事实。 +逻辑:所有关键身份和版本条件均 fail-closed;返回结构化原因供审计和 Projection 使用。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + + +def check_inventory_snapshot_reusable( + *, snapshot: Any, source_code: str, warehouse_id: str | None = None, + source_config_version: str | None = None, candidate_input_fingerprint: str | None = None, + expected_file_sha256: str | None = None, parser_version: str | None = None, + mapping_version: str | None = None, now: datetime | None = None, +) -> tuple[bool, list[str]]: + """返回 (是否可复用, 不可复用原因列表)。""" + reasons: list[str] = [] + current = now or datetime.utcnow() + if snapshot is None: + return False, ['snapshot_missing'] + if str(getattr(snapshot, 'snapshot_status', '') or '').lower() != 'ready': + reasons.append('snapshot_not_ready') + expires_at = getattr(snapshot, 'expires_at', None) + if expires_at is not None and expires_at <= current: + reasons.append('snapshot_expired') + if str(getattr(snapshot, 'source_code', '') or '').strip().upper() != str(source_code or '').strip().upper(): + reasons.append('source_code_mismatch') + if warehouse_id is not None and str(getattr(snapshot, 'warehouse_id', '') or '').strip().upper() != str(warehouse_id).strip().upper(): + reasons.append('warehouse_mismatch') + if source_config_version is not None and str(getattr(snapshot, 'source_config_version', '') or '') != str(source_config_version): + reasons.append('source_config_version_mismatch') + if expected_file_sha256 is not None and str(getattr(snapshot, 'file_sha256', '') or '') != str(expected_file_sha256): + reasons.append('file_hash_mismatch') + if parser_version is not None and str(getattr(snapshot, 'parser_version', '') or '') != str(parser_version): + reasons.append('parser_version_mismatch') + if mapping_version is not None and str(getattr(snapshot, 'mapping_version', '') or '') != str(mapping_version): + reasons.append('mapping_version_mismatch') + if candidate_input_fingerprint is not None and str(getattr(snapshot, 'input_fingerprint', '') or '') != str(candidate_input_fingerprint): + reasons.append('candidate_input_fingerprint_mismatch') + if getattr(snapshot, 'invalidated_at', None) is not None: + reasons.append('snapshot_invalidated') + return not reasons, reasons + + +def is_inventory_snapshot_reusable(**kwargs: Any) -> bool: + """布尔兼容入口;详细原因由 check_inventory_snapshot_reusable 提供。""" + return check_inventory_snapshot_reusable(**kwargs)[0] diff --git a/backend/app/services/shipping_notice/inventory_snapshot_store.py b/backend/app/services/shipping_notice/inventory_snapshot_store.py index d6379976..db65937f 100644 --- a/backend/app/services/shipping_notice/inventory_snapshot_store.py +++ b/backend/app/services/shipping_notice/inventory_snapshot_store.py @@ -281,24 +281,21 @@ def create_inventory_snapshot_from_rpa( excel_warehouse_id = "" warehouse_id = export_warehouse_id warehouse_code = warehouse_id + # Excel 内部 Warehouse 编码由外部 DSV/货代系统决定,不能假设等于 HXOPS 配置编码。 + # 快照归属继续使用任务/库存源配置;实际文件编码仅作为可选审计信息保留。 excel_verified = False if success: local = Path(local_path) - expected_wh = str(verify_warehouse_id or export_warehouse_id or "").strip().upper() - if expected_wh: - from app.services.shipping_notice.inventory_file_identity import ( - assert_inventory_excel_warehouse_identity, - ) + # 仅采集文件中的 Warehouse 作为审计信息,不将外部编码与 HXOPS 配置编码做一致性拦截。 + try: + from app.services.shipping_notice.inventory_file_identity import extract_warehouse_ids_from_inventory_excel - excel_warehouse_id = assert_inventory_excel_warehouse_identity( - local, - expected_warehouse_id=expected_wh, - operation="rpa_snapshot", - ) - warehouse_id = expected_wh - warehouse_code = warehouse_id - excel_verified = True + excel_warehouse_ids = extract_warehouse_ids_from_inventory_excel(local) + if len(excel_warehouse_ids) == 1: + excel_warehouse_id = next(iter(excel_warehouse_ids)) + except Exception: + excel_warehouse_id = "" path = inventory_file_upload_path( inventory_file_no, suffix=inventory_storage_suffix_for_path(local), diff --git a/backend/app/services/shipping_notice/inventory_source_gate.py b/backend/app/services/shipping_notice/inventory_source_gate.py index 7da18f39..8b50e2c4 100644 --- a/backend/app/services/shipping_notice/inventory_source_gate.py +++ b/backend/app/services/shipping_notice/inventory_source_gate.py @@ -47,7 +47,8 @@ INVENTORY_SOURCE_ERROR_CODES = { def _inventory_source_config_current(task: ShippingNotice) -> bool: """任务上记录的库存源配置版本须与当前数据库版本一致。""" - stored = str(task.inventory_source_config_version or "").strip() + # 兼容旧任务/轻量测试桩:缺失版本字段等同于未冻结当前配置。 + stored = str(getattr(task, 'inventory_source_config_version', None) or "").strip() current = inventory_sources_runtime_version() if not stored: return False diff --git a/backend/app/services/shipping_notice/line_inventory_match_persistence.py b/backend/app/services/shipping_notice/line_inventory_match_persistence.py index 2f40f86d..686f5143 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_persistence.py +++ b/backend/app/services/shipping_notice/line_inventory_match_persistence.py @@ -129,9 +129,11 @@ def persist_line_inventory_match_facts( except (TypeError, ValueError): continue res = res_by_index.get(index) or {} + # Case 草稿 line_key 是订单明细的正式身份;匹配器临时 line-1 只能兜底, + # 禁止覆盖 machine-1 等正式键,否则事实已落库但工作台无法关联显示。 line_key = str( - res.get('line_key') - or keys_by_index.get(index) + keys_by_index.get(index) + or res.get('line_key') or f'line-{index + 1}' ).strip() if not line_key: @@ -202,6 +204,13 @@ def persist_line_inventory_match_facts( .filter_by(task_id=int(task.id), line_key=line_key, is_current=True) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) + # Draft line_key 发生过版本切换时,按稳定 line_index 关闭旧键事实, + # 避免同一订单行同时存在两个 current 投影。 + ( + ShippingNoticeLineInventoryMatch.query + .filter_by(task_id=int(task.id), line_index=index, is_current=True) + .update({'is_current': False, 'updated_at': now}, synchronize_session=False) + ) # [T6 E1] 行级证据哈希:SHA256(source_code|file_no|row_index|reservation_id|part_number) src_code = str(result.get('resolved_inventory_source_code') or '')[:64] or None file_no = str(result.get('inventory_file_no') or '')[:128] or None @@ -323,6 +332,9 @@ def persist_line_inventory_match_facts( existing.matching_rule_version = str(matching_rule_version or '')[:64] or None existing.inventory_source_code = src_code existing.is_current = True + existing.invalidated_at = None + existing.invalidated_by_attempt_id = None + existing.invalidation_reason = None existing.matched_at = now existing.updated_at = now existing.candidate_set_id = int(current_candidate_set.id) if current_candidate_set is not None else None @@ -361,6 +373,18 @@ def persist_line_inventory_match_facts( ) .update({'is_current': False, 'updated_at': now}, synchronize_session=False) ) + # Draft line_key 发生过版本切换时,更新已有新键也必须关闭旧键; + # 否则旧 key 会与新 key 同时进入 current 投影,导致订单明细不确定。 + ( + ShippingNoticeLineInventoryMatch.query + .filter( + ShippingNoticeLineInventoryMatch.task_id == int(task.id), + ShippingNoticeLineInventoryMatch.line_index == index, + ShippingNoticeLineInventoryMatch.id != int(existing.id), + ShippingNoticeLineInventoryMatch.is_current.is_(True), + ) + .update({'is_current': False, 'updated_at': now}, synchronize_session=False) + ) written.append(existing) db.session.flush() diff --git a/backend/app/services/shipping_notice/line_inventory_match_projection.py b/backend/app/services/shipping_notice/line_inventory_match_projection.py index aebb4af9..31a971c1 100644 --- a/backend/app/services/shipping_notice/line_inventory_match_projection.py +++ b/backend/app/services/shipping_notice/line_inventory_match_projection.py @@ -14,7 +14,7 @@ from __future__ import annotations from decimal import Decimal, InvalidOperation from typing import Any -from app.models import ShippingNoticeLineInventoryMatch +from app.models import ShippingInventoryFile, ShippingNoticeLineInventoryMatch MATCH_NOT_FOUND = 'not_found' @@ -423,6 +423,10 @@ def load_current_match_facts_by_task(task_id: int | None) -> dict[str, dict[str, def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any]: """将 ORM 行序列化为投影输入。""" + snapshot = ( + ShippingInventoryFile.query.get(int(row.inventory_snapshot_id)) + if row.inventory_snapshot_id is not None else None + ) return { 'id': int(row.id), 'task_id': int(row.task_id), @@ -442,6 +446,18 @@ def serialize_match_fact(row: ShippingNoticeLineInventoryMatch) -> dict[str, Any 'unit': row.unit, 'matching_rule_version': row.matching_rule_version, 'inventory_source_code': row.inventory_source_code, + 'inventory_file_no': getattr(row, 'matched_file_no', None), + 'inventory_file_sha256': ( + dict(row.detail_json or {}).get('file_sha256') + or dict(row.detail_json or {}).get('inventory_file_sha256') + or dict(row.detail_json or {}).get('file_sha256_hex') + or getattr(snapshot, 'file_sha256', None) + ), + 'inventory_row_index': getattr(row, 'matched_row_index', None), + 'match_attempt_id': getattr(row, 'match_attempt_id', None), + 'required_qty': row.required_qty, + 'matched_qty': getattr(row, 'matched_qty', None) or row.available_qty, + 'shortage_qty': row.shortage_qty, 'matched_at': row.matched_at.isoformat() if row.matched_at else None, 'is_current': bool(row.is_current), 'detail_json': dict(row.detail_json or {}), @@ -639,6 +655,13 @@ def project_line_inventory_view( 'inventory_snapshot_id': fact.get('inventory_snapshot_id'), 'inventory_checked_at': fact.get('matched_at'), 'inventory_source_code': fact.get('inventory_source_code'), + 'inventory_file_no': fact.get('inventory_file_no'), + 'inventory_file_sha256': fact.get('inventory_file_sha256') or fact.get('file_sha256'), + 'inventory_row_index': fact.get('inventory_row_index') or fact.get('matched_row_index'), + 'match_attempt_id': fact.get('match_attempt_id'), + 'required_qty': fact.get('required_qty'), + 'matched_qty': fact.get('matched_qty') or fact.get('available_qty'), + 'shortage_qty': fact.get('shortage_qty'), 'inventory_source': source, 'matching_rule_version': fact.get('matching_rule_version'), 'user_line_status': user_status, diff --git a/backend/app/services/shipping_notice/order_freeze_service.py b/backend/app/services/shipping_notice/order_freeze_service.py index 3ae6fd54..4165b0a9 100644 --- a/backend/app/services/shipping_notice/order_freeze_service.py +++ b/backend/app/services/shipping_notice/order_freeze_service.py @@ -85,7 +85,14 @@ def freeze_order_snapshot( ValidationError: 当前 Extraction 不完整或核心字段契约不匹配。 """ # [STEP 1] 锁定数据库中的 Task,令并发确认串行化;同一 Task 的重复点击复用既有快照。 - locked_task = ShippingNotice.query.filter_by(id=task.id).with_for_update().one() + # query 默认带 shipping_case 的 joinedload;PostgreSQL 不允许对外连接的空值端 + # 执行 FOR UPDATE。仅锁定正式任务主表,避免冻结在已确认但关联 Case 可为空时失败。 + locked_task = ( + ShippingNotice.query + .filter_by(id=task.id) + .with_for_update(of=ShippingNotice) + .one() + ) if locked_task.order_snapshot_id: snapshot = db.session.get(ShippingOrderSnapshot, locked_task.order_snapshot_id) if snapshot is not None: diff --git a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py index 827c4cf4..edf0bc21 100644 --- a/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py +++ b/backend/app/services/shipping_notice/order_review_fulfillment_decision_service.py @@ -536,6 +536,13 @@ def project_review_case_line_decisions( 'inventory_snapshot_id': inv_view.get('inventory_snapshot_id'), 'inventory_checked_at': inv_view.get('inventory_checked_at'), 'inventory_source_code': inv_view.get('inventory_source_code'), + 'inventory_file_no': inv_view.get('inventory_file_no'), + 'inventory_file_sha256': inv_view.get('inventory_file_sha256'), + 'inventory_row_index': inv_view.get('inventory_row_index'), + 'match_attempt_id': inv_view.get('match_attempt_id'), + 'required_qty': inv_view.get('required_qty') or required, + 'matched_qty': inv_view.get('matched_qty') or available, + 'shortage_qty': inv_view.get('shortage_qty') or shortage, 'inventory_source': inv_view.get('inventory_source'), 'decision_source': inv_view.get('decision_source'), 'retryable': bool(inv_view.get('retryable')), diff --git a/backend/app/services/shipping_notice/order_review_projection.py b/backend/app/services/shipping_notice/order_review_projection.py index 7c870273..262e7ca1 100644 --- a/backend/app/services/shipping_notice/order_review_projection.py +++ b/backend/app/services/shipping_notice/order_review_projection.py @@ -716,6 +716,16 @@ def serialize_review_case( .order_by(ShippingProcessExecution.id.desc()) .first() ) + # 正式 OT 的 Execution 可能在 Case 创建后才绑定 task_id;复核页必须沿 + # case.confirmed_task_id → ShippingNotice → Execution 继续查找,不能退回旧的 + # process_gate 兜底,否则会丢失当前 Gate 与 RecoveryPlan 按钮。 + if execution is None and formal_ot.get('task_id') is not None: + execution = ( + ShippingProcessExecution.query + .filter_by(task_id=int(formal_ot['task_id'])) + .order_by(ShippingProcessExecution.id.desc()) + .first() + ) if execution is not None: process_gate = apply_post_ot_gate_rules( project_user_gate_summary(execution), diff --git a/backend/app/services/shipping_notice/order_review_workbench_projection.py b/backend/app/services/shipping_notice/order_review_workbench_projection.py index 88e874ab..7ac0a93a 100644 --- a/backend/app/services/shipping_notice/order_review_workbench_projection.py +++ b/backend/app/services/shipping_notice/order_review_workbench_projection.py @@ -448,6 +448,22 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str except Exception: # noqa: BLE001 return None + def _safe_user_error(value: Any) -> str | None: + """用户态只返回稳定错误码,禁止泄漏 ImportError、路径和堆栈。""" + raw = str(value or '').strip() + if not raw: + return None + lowered = raw.lower() + if ( + 'cannot import name' in lowered + or 'traceback' in lowered + or '\\app\\' in lowered + or '/app/' in lowered + or 'site-packages' in lowered + ): + return 'auto_progress_job_failed' + return raw[:128] + def _job_fields(job) -> dict[str, Any]: if job is None: return { @@ -465,7 +481,7 @@ def project_post_ot_automation_from_job(task: ShippingNotice | None) -> dict[str ) return { 'job_id': int(job.id), - 'error_code': error_code, + 'error_code': _safe_user_error(error_code), 'attempts': int(job.attempts or 0), 'max_attempts': int(job.max_attempts or 0) or None, 'completed_at': _iso(getattr(job, 'finished_at', None)), @@ -621,6 +637,11 @@ def project_stage_for_task( 'stage_node': None, } + # 上传登记/回调会先更新 ShippingNotice 聚合事实;旧 OT.stage 可能仍停在 + # freight_uploading,不能用过期阶段覆盖已经完成的履约状态。 + if process_status in {'uploaded', 'closed', 'completed'}: + return _with_label('completed', source='notice_terminal') + # [STEP 1] OT 实体 stage 优先(与 shipping_processing_projection 同源)。 order_task = None try: @@ -791,8 +812,12 @@ def apply_post_ot_gate_rules( blocking = None gate_code = '' - # inventory_preparation(Worker 等待)→ 技术自动,无人工卡。 - if gate_code in _SYSTEM_WAIT_INVENTORY_GATES: + # inventory_preparation 的等待态由 Worker 自动推进;但 blocked_retryable + # 是明确的库存文件/RPA失败,必须保留 Gate 动作,不能被清成系统处理中。 + if ( + gate_code in _SYSTEM_WAIT_INVENTORY_GATES + and raw_gate_status in {'pending', 'queued', 'running', 'waiting_external'} + ): result['current_blocking_gate'] = None result['blocking_reason_code'] = None result['blocking_message'] = None @@ -811,12 +836,11 @@ def apply_post_ot_gate_rules( result['available_actions'] = [] return result - # 库存/履约域 + human + 有动作 → 保留人工阻断(显式集合优先;前缀仅作必要兼容)。 + # 所有正式 OT Gate 均由服务端下发动作;页面只负责展示,实际可执行性由 + # Gate API 按当前 Gate、Attempt、版本和权限逐项校验。不能仅因 Gate 属于 + # Excel/上传等技术阶段就静默清除用户入口。 next_action = str(result.get('next_action_code') or '').strip() - in_domain = gate_code in _POST_OT_INVENTORY_FULFILLMENT_GATES or ( - gate_code.startswith('inventory_') or gate_code.startswith('fulfill') - ) - if in_domain and next_action and not result.get('technical_auto_only'): + if next_action and not result.get('technical_auto_only'): result['owner_type'] = 'human' result['technical_auto_only'] = False return result diff --git a/backend/app/services/shipping_notice/order_stp_auto_create_service.py b/backend/app/services/shipping_notice/order_stp_auto_create_service.py index 9ee869f1..9275adef 100644 --- a/backend/app/services/shipping_notice/order_stp_auto_create_service.py +++ b/backend/app/services/shipping_notice/order_stp_auto_create_service.py @@ -676,7 +676,10 @@ def ensure_stp_auto_create_for_case( 'idempotency_key': idempotency_key, 'job_status': str(existing.status), 'can_auto_create': True, - 'retry_of_job_id': int(existing.retry_of_job_id) if existing.retry_of_job_id else None, + 'retry_of_job_id': ( + int(getattr(existing, 'retry_of_job_id', None)) + if getattr(existing, 'retry_of_job_id', None) else None + ), } # [STEP] failed/dead 历史 Job 保留审计;新建重试 Job 并挂 retry_of_job_id。 diff --git a/backend/app/services/shipping_notice/per_source_rpa_service.py b/backend/app/services/shipping_notice/per_source_rpa_service.py index 229bb500..39d31858 100644 --- a/backend/app/services/shipping_notice/per_source_rpa_service.py +++ b/backend/app/services/shipping_notice/per_source_rpa_service.py @@ -62,6 +62,47 @@ def _attempt_ref_has_ready_snapshot( return is_snapshot_fresh(inv_file) +def _validate_callback_attempt_identity( + *, + task: ShippingNotice, + attempt: ShippingTaskInventoryRpaAttempt, + callback_payload: dict[str, Any], +) -> bool: + """校验回调身份与已冻结 Attempt/当前 CandidateSet/正式 Execution 一致。""" + required = ('schema_version', 'callback_id', 'source_run_no', 'attempt_no', 'lease_token', + 'candidate_set_id', 'execution_id', 'gate_id') + if str(callback_payload.get('schema_version') or '') != 'shipping_inventory_rpa.v2': + return False + if any(callback_payload.get(key) in (None, '') for key in required): + return False + if str(callback_payload.get('task_no') or '').strip() != str(task.task_no or '').strip(): + return False + if str(callback_payload.get('source_code') or '').strip().upper() != str(attempt.source_code or '').strip().upper(): + return False + if str(callback_payload.get('source_run_no') or '').strip() != str(attempt.source_run_no or '').strip(): + return False + try: + if int(callback_payload.get('attempt_no')) != int(attempt.attempt_no): + return False + except (TypeError, ValueError): + return False + if str(callback_payload.get('lease_token') or '') != str(attempt.lease_token or ''): + return False + stored = dict(attempt.extra_json or {}) + for key in ('candidate_set_id', 'execution_id', 'gate_id'): + try: + if int(callback_payload.get(key)) != int(stored.get(key)): + return False + except (TypeError, ValueError): + return False + active_candidate = getattr(task, 'active_inventory_candidate_set_id', None) + if active_candidate is not None and int(callback_payload.get('candidate_set_id')) != int(active_candidate): + return False + expected_warehouse = str(stored.get('expected_warehouse_id') or '').strip().upper() + callback_warehouse = str(callback_payload.get('expected_warehouse_id') or callback_payload.get('warehouse_id') or '').strip().upper() + return not expected_warehouse or callback_warehouse == expected_warehouse + + PER_SOURCE_RUN_NO_PREFIX = 'PSR' # Per-Source Run,区别于 legacy T-xxx 全局 run_no @@ -194,7 +235,21 @@ def _snapshot_ready_for_source( snap = find_latest_ready_snapshot(source_code, warehouse_id) except Exception: snap = None - return snap is not None + from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable + source_config_version = None + if isinstance(rpa_source, dict): + source_config_version = rpa_source.get('source_config_version') or rpa_source.get('config_version') + parser_version = rpa_source.get('parser_version') if isinstance(rpa_source, dict) else None + mapping_version = rpa_source.get('mapping_version') if isinstance(rpa_source, dict) else None + reusable, _ = check_inventory_snapshot_reusable( + snapshot=snap, + source_code=source_code, + warehouse_id=warehouse_id, + source_config_version=source_config_version, + parser_version=parser_version, + mapping_version=mapping_version, + ) + return reusable def _attempts_summary( @@ -345,8 +400,26 @@ def ensure_all_required_sources_prepared( # trigger 文件的逻辑,文件名同时带 __SOURCE_CODE__A 后缀即可。 # 这里的 trigger_file_path 仅作为审计字段记录,实际触发由 Worker 按目录扫描识别。 from app.services.shipping_notice.inventory_source_rules import task_rpa_inventory_source + from app.models import ShippingProcessExecution, ShippingProcessGate legacy_rpa_source = task_rpa_inventory_source(task) or dict(rpa_source) + execution_id = getattr(task, 'active_process_execution_id', None) + gate_id = None + if execution_id: + execution_row = sess.get(ShippingProcessExecution, int(execution_id)) + if execution_row is not None and execution_row.current_gate_code: + gate_row = sess.query(ShippingProcessGate).filter_by( + execution_id=int(execution_row.id), + gate_code=str(execution_row.current_gate_code), + ).first() + gate_id = int(gate_row.id) if gate_row is not None else None + new_att.extra_json = dict( + new_att.extra_json or {}, + candidate_set_id=getattr(task, 'active_inventory_candidate_set_id', None), + execution_id=execution_id, + gate_id=gate_id, + expected_warehouse_id=rpa_source.get('warehouse_id'), + ) # 强制注入 source_code 覆盖旧 task 级单源字段,使 RPA Worker 可按 per-source 执行 per_source_payload = { 'schema_version': 'shipping_inventory_rpa.v2', @@ -355,8 +428,14 @@ def ensure_all_required_sources_prepared( 'attempt_no': next_att_no, 'source_code': source_code, 'source_run_no': new_att.source_run_no, + 'callback_id': f'{new_att.source_run_no}:C1', 'batch_run_no': f'BATCH-{task_no}-{datetime.utcnow().strftime("%Y%m%d%H%M%S%f")}', 'lease_token': new_att.lease_token, + # 回调身份必须与本次冻结版本/正式 Execution 绑定;Worker 只原样回传。 + 'candidate_set_id': getattr(task, 'active_inventory_candidate_set_id', None), + 'execution_id': execution_id, + 'gate_id': gate_id, + 'expected_warehouse_id': rpa_source.get('warehouse_id'), 'per_source_attempt': True, } trigger_result = write_inventory_export_trigger_for_task( @@ -425,7 +504,26 @@ def per_source_callback_handler( task_no = str(task.task_no or '').strip() source_code_up = str(source_code or '').strip().upper() - # [STEP 1] 三元组定位 + # [STEP 1] callback_id 重放检查。只要回调带有稳定 ID,先于业务身份解析, + # 防止同一事件被另一个 Attempt 消费;同 Attempt 重放直接返回幂等结果。 + callback_id = str((callback_payload or {}).get('callback_id') or '').strip() + if callback_id: + callback_attempt = ( + sess.query(ShippingTaskInventoryRpaAttempt) + .filter_by(callback_id=callback_id) + .one_or_none() + ) + if callback_attempt is not None: + same_attempt = ( + callback_attempt.task_no == task_no + and callback_attempt.source_code == source_code_up + and callback_attempt.run_no == str(run_no or '').strip() + ) + if same_attempt: + return 'idempotent_ok', callback_attempt + return 'callback_conflict', callback_attempt + + # [STEP 2] 三元组定位 attempt = ( sess.query(ShippingTaskInventoryRpaAttempt) .filter( @@ -440,11 +538,20 @@ def per_source_callback_handler( if attempt is None: return 'not_found', None - # [STEP 2] 幂等 + if not _validate_callback_attempt_identity( + task=task, + attempt=attempt, + callback_payload=dict(callback_payload or {}), + ): + attempt.extra_json = dict(attempt.extra_json or {}, callback_identity_rejected=True) + sess.flush([attempt]) + return 'identity_mismatch', attempt + + # [STEP 3] 幂等 if attempt.status in ('succeeded', 'consumed', 'superseded'): return 'idempotent_ok', attempt - # [STEP 3] 迟到保护:同 (task, source) 有更新 run 已终态 + # [STEP 4] 迟到保护:同 (task, source) 有更新 run 已终态 consumed_runs = _consumed_run_nos(task_no, source_code_up, session=sess) # Run no format: PSR---A- → 排序按 attempt_no 前缀即可 try: @@ -472,7 +579,7 @@ def per_source_callback_handler( sess.flush([attempt]) return 'superseded_late', attempt - # [STEP 4] Task 已终态(兼容旧枚举 active/blocked 等非终态) + # [STEP 5] Task 已终态(兼容旧枚举 active/blocked 等非终态) terminal_statuses = {'completed', 'cancelled', 'failed_terminal'} if str(getattr(task, 'process_status', '') or '').strip() in terminal_statuses: attempt.status = 'superseded' @@ -483,7 +590,7 @@ def per_source_callback_handler( sess.flush([attempt]) return 'task_terminal', attempt - # [STEP 5] 写回调结果 + # [STEP 6] 写回调结果 attempt.callback_payload_json = dict(callback_payload or {}) attempt.callback_received_at = datetime.utcnow() attempt.callback_id = str(callback_payload.get('callback_id') or '').strip() or attempt.callback_id @@ -504,6 +611,8 @@ def per_source_callback_handler( attempt.transaction_status = 'rejected' attempt.error_code = error_code attempt.error_message = error_message[:2000] if error_message else None + from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed') sess.flush([attempt]) return 'failed', attempt # 回调标称成功,但必须二次验证快照已真实入库且 ready,否则仍然算失败(防止 RPA 伪成功) @@ -528,10 +637,18 @@ def per_source_callback_handler( attempt.error_message = ( f"回调返回成功但关联库存快照未通过门禁校验:{missing_reason}"[:2000] ) + from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + sync_preparation_source_from_rpa_attempt(rpa_attempt_id=int(attempt.id), rpa_status='failed') sess.flush([attempt]) return 'failed', attempt attempt.status = 'succeeded' attempt.transaction_status = 'succeeded' + from app.services.shipping_notice.inventory_recovery_service import sync_preparation_source_from_rpa_attempt + sync_preparation_source_from_rpa_attempt( + rpa_attempt_id=int(attempt.id), + rpa_status='succeeded', + inventory_file_id=(int(_inv.id) if inventory_file_no and _inv is not None else None), + ) sess.flush([attempt]) # 回调只改变 Attempt/Snapshot 事实;正式 Task Gate 由 AutoProgress Job 重新校验。 # 调用方在同一事务提交后,Job 才对 Worker 可见。 diff --git a/backend/app/services/shipping_notice/process_gate_bridge.py b/backend/app/services/shipping_notice/process_gate_bridge.py index 0e81eae9..914d865a 100644 --- a/backend/app/services/shipping_notice/process_gate_bridge.py +++ b/backend/app/services/shipping_notice/process_gate_bridge.py @@ -87,9 +87,12 @@ def inventory_preparation_reason_code(task: ShippingNotice) -> str: return 'inventory_file_identity_mismatch' return 'inventory_rpa_export_failed' - # [STEP] 空列表=文件无有效行;None/非列表=尚未落库存文件 - if isinstance(task.inventory_lines_json, list): - if len(task.inventory_lines_json) == 0: + # [STEP] 活动库存快照是运行事实;任务字段仅为历史兼容投影。 + from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task + + active_lines = active_inventory_lines_for_task(task) + if isinstance(active_lines, list): + if len(active_lines) == 0: return 'inventory_file_empty' return 'inventory_preparation_failed' return 'inventory_file_missing' @@ -276,6 +279,10 @@ def apply_gate_outcome( return gate key = str(idempotency_key or '').strip() or f'bridge:{execution.execution_no}:{code}:{fingerprint[:16]}' + if force and gate is not None: + # 强制重评发生在新的 Gate evaluation_version 上;旧版本 Attempt 的成功回放 + # 不能覆盖当前 invalidated/blocked 状态,否则 Execution 指针会永久停在历史 Gate。 + key = f'{key}:v{int(gate.evaluation_version)}' return sync_gate_from_business_result( execution_no=str(execution.execution_no), gate_code=code, @@ -728,6 +735,63 @@ def sync_fulfillment_gates_from_task( 'task_no': str(task.task_no or '') or None, 'has_inventory_lines': has_inventory_lines, } + # PreparationAttempt 是库存准备的主事实;仅在当前 Execution/CandidateSet + # 存在对应轮次时使用,避免旧任务的孤立轮次污染正式链。 + preparation = None + try: + from app.models import ShippingInventoryPreparationAttempt + + prep_query = ( + ShippingInventoryPreparationAttempt.query + .filter_by(task_id=int(task.id), execution_id=int(execution.id)) + .filter(ShippingInventoryPreparationAttempt.status != 'superseded') + ) + if execution.candidate_set_id is not None: + prep_query = prep_query.filter( + ShippingInventoryPreparationAttempt.candidate_set_id == int(execution.candidate_set_id) + ) + preparation = prep_query.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()).first() + except Exception: # noqa: BLE001 + preparation = None + if preparation is not None: + source_rows = list(getattr(preparation, 'source_attempts', []) or []) + required = [str(row.source_code or '').strip().upper() for row in source_rows] + prepared = [code for code, row in zip(required, source_rows) if row.status in {'ready', 'reusable'}] + pending = [code for code, row in zip(required, source_rows) if row.status in {'queued', 'running', 'waiting'}] + failed = [code for code, row in zip(required, source_rows) if row.status == 'failed'] + task_facts.update({ + 'preparation_attempt_id': int(preparation.id), + 'preparation_attempt_no': int(preparation.attempt_no), + 'required_sources': required, + 'prepared_sources': prepared, + 'pending_sources': pending, + 'failed_sources': failed, + }) + if preparation.status in {'queued', 'running', 'waiting_external'} or pending: + apply_gate_outcome( + execution=execution, gate_code='inventory_preparation', passed=False, + outcome='waiting_external', effective_result={'findings': [], **task_facts}, + blocking_reason_code='inventory_preparation_waiting', actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:waiting', force=True, + ) + return + if preparation.status == 'failed' or failed: + apply_gate_outcome( + execution=execution, gate_code='inventory_preparation', passed=False, + outcome='blocked_retryable', effective_result={'findings': [], **task_facts}, + blocking_reason_code='inventory_preparation_failed', actor_type=actor_type, + actor_id=actor_id, + idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:failed', force=True, + ) + return + if preparation.status == 'succeeded' and required and len(prepared) == len(required): + apply_gate_outcome( + execution=execution, gate_code='inventory_preparation', passed=True, + effective_result=task_facts, actor_type=actor_type, actor_id=actor_id, + idempotency_key=f'fulfill:invprep:{execution.execution_no}:prep:{preparation.id}:passed', force=True, + ) + # Continue below for mapping/matching facts. if status == 'waiting_inventory': from app.services.shipping_notice.constants import PH_RPA_PENDING waiting_reason = ( @@ -923,6 +987,9 @@ def sync_fulfillment_gates_from_task( execution=execution, gate_code='artifact_generation', passed=artifact_ok, + # Excel 资格已通过但产物尚未生成属于系统可恢复动作;必须保留 + # regenerate_excel_artifact,不能落为 blocked_manual 后失去自动推进入口。 + outcome=None if artifact_ok else 'blocked_retryable', effective_result={ 'findings': ( [] if artifact_ok else _fulfillment_blocking_finding( diff --git a/backend/app/services/shipping_notice/process_gate_contract.py b/backend/app/services/shipping_notice/process_gate_contract.py index 127e0caf..5a7f8929 100644 --- a/backend/app/services/shipping_notice/process_gate_contract.py +++ b/backend/app/services/shipping_notice/process_gate_contract.py @@ -17,7 +17,17 @@ from typing import Any, Final # 契约版本;投影、OpenAPI 与 i18n 必须与此对齐。 -PROCESS_GATE_CONTRACT_VERSION: Final[str] = 'shipping-process-gate-v1' +PROCESS_GATE_CONTRACT_VERSION: Final[str] = 'shipping-process-gate-v2' + +# Gate 实施能力状态:v2 运行时合同必须明确每个 Gate 的当前适配程度。 +# supported:已有真实执行器或人工业务入口;implemented:库存/履约闭环已实现; +# adapter_required / blocked 预留给未来未接线 Gate,禁止前端据此猜测可执行动作。 +PROCESS_GATE_IMPLEMENTATION_STATUSES: Final[frozenset[str]] = frozenset({ + 'supported', + 'implemented', + 'adapter_required', + 'blocked', +}) # Finding 严重级别:仅 blocking 可改变 Gate 状态;diagnostic 供管理员诊断。 PROCESS_GATE_FINDING_SEVERITIES: Final[frozenset[str]] = frozenset({ @@ -75,6 +85,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 1, 'label': '文档和附件可用性', 'responsible_party': 'system', + 'implementation_status': 'supported', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'rematerialize_document', @@ -86,6 +97,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 2, 'label': 'PDF 版面解析', 'responsible_party': 'worker', + 'implementation_status': 'supported', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'retry_layout_parsing', @@ -97,6 +109,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 3, 'label': 'Profile/模板路由', 'responsible_party': 'system', + 'implementation_status': 'supported', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'reroute_document_profile', @@ -108,6 +121,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 4, 'label': '订单字段抽取', 'responsible_party': 'worker', + 'implementation_status': 'supported', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'retry_order_extraction', @@ -119,6 +133,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 5, 'label': '必填字段完整性', 'responsible_party': 'owner', + 'implementation_status': 'supported', 'recoverable': True, 'default_next_actions': { 'blocked_manual': 'edit_order_fields', @@ -129,6 +144,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 6, 'label': 'Reservation 格式和证据', 'responsible_party': 'owner', + 'implementation_status': 'supported', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'revalidate_reservation', @@ -140,6 +156,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 7, 'label': '客户身份识别', 'responsible_party': 'owner', + 'implementation_status': 'supported', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'retry_customer_resolution', @@ -151,6 +168,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 8, 'label': '重复订单/修订判断', 'responsible_party': 'owner', + 'implementation_status': 'supported', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'retry_duplicate_detection', @@ -162,6 +180,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 9, 'label': '字段冲突', 'responsible_party': 'owner', + 'implementation_status': 'supported', 'recoverable': True, 'default_next_actions': { 'blocked_manual': 'resolve_field_conflicts', @@ -172,6 +191,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 10, 'label': '库存源路由', 'responsible_party': 'owner', + 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'retry_with_latest_rules', @@ -183,6 +203,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 11, 'label': '订单冻结资格', 'responsible_party': 'system', + 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'recheck_freeze_readiness', @@ -194,6 +215,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 12, 'label': 'ShippingNotice 创建', 'responsible_party': 'system', + 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'retry_task_creation', @@ -204,6 +226,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 13, 'label': '库存文件或快照准备', 'responsible_party': 'worker', + 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'retry_inventory_preparation', @@ -216,6 +239,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 14, 'label': '库存字段映射', 'responsible_party': 'owner', + 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'retry_inventory_field_mapping', @@ -227,6 +251,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 15, 'label': 'Reservation + 料号匹配', 'responsible_party': 'worker', + 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'retry_inventory_matching', @@ -238,6 +263,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 16, 'label': '库存满足性', 'responsible_party': 'owner', + 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'recheck_inventory_sufficiency', @@ -249,6 +275,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 17, 'label': 'Excel 生成资格', 'responsible_party': 'system', + 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'recheck_excel_readiness', @@ -259,6 +286,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 18, 'label': 'Excel Artifact', 'responsible_party': 'worker', + 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { 'blocked_retryable': 'regenerate_excel_artifact', @@ -269,6 +297,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 19, 'label': '货代上传 RPA', 'responsible_party': 'worker', + 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { 'waiting_external': 'poll_freight_upload_rpa', @@ -281,6 +310,7 @@ PROCESS_GATE_DEFINITIONS: Final[tuple[dict[str, Any], ...]] = ( 'sequence_no': 20, 'label': '人工上传交接', 'responsible_party': 'owner', + 'implementation_status': 'implemented', 'recoverable': True, 'default_next_actions': { 'blocked_manual': 'regenerate_manual_upload_todo', @@ -322,6 +352,9 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({ 'retry_inventory_field_mapping', 'confirm_inventory_field_mapping', 'retry_inventory_matching', + 'retry_inventory_from_preparation', + 'retry_inventory_from_field_mapping', + 'retry_inventory_from_matching', 'open_inventory_match_review', 'recheck_inventory_sufficiency', 'open_shortage_review', @@ -332,27 +365,43 @@ PROCESS_GATE_ACTION_CODES: Final[frozenset[str]] = frozenset({ 'regenerate_manual_upload_todo', }) -# 业务用户可在复核工作台 / Gate 卡片触发的动作(导航或本地 UX)。 -# 技术重试(Worker/System)不得向业务用户投影为可点击写操作。 -PROCESS_GATE_BUSINESS_USER_ACTION_CODES: Final[frozenset[str]] = frozenset({ - 'open_order_review', - 'open_profile_review', # 仅导航至复核只读模板区,禁止人工选模板写路径 - 'edit_order_fields', - 'edit_reservation', - 'confirm_customer', - 'retry_customer_resolution', - 'adjudicate_duplicate', - 'retry_duplicate_detection', - 'resolve_field_conflicts', - 'open_inventory_source_review', - 'adopt_rule_suggestion', - 'keep_manual_inventory_decision', - 'upload_inventory_file', - 'confirm_inventory_field_mapping', - 'open_inventory_match_review', - 'open_shortage_review', - 'regenerate_manual_upload_todo', -}) +# Gate 卡只展示服务端冻结合同中的动作码。每次点击仍受 Workspace API 的 +# 当前 Gate 版本、执行归属和写权限校验;前端不自行决定目标节点或重试方式。 +PROCESS_GATE_BUSINESS_USER_ACTION_CODES: Final[frozenset[str]] = PROCESS_GATE_ACTION_CODES + +# 用户按钮展示合同:动作码仍是唯一执行标识,label_key/kind/dispatch 只描述业务语义。 +# 任务级与明细行级不得再把所有动作降级为“重试”;前端只渲染本合同。 +PROCESS_GATE_ACTION_PRESENTATION: Final[dict[str, dict[str, str]]] = { + code: { + 'label_key': f'workspace.shippingNotice.processGate.actionCodes.{code}', + 'kind': 'current_gate', + 'dispatch': 'mutation', + } + for code in PROCESS_GATE_ACTION_CODES +} +for _code in { + 'open_order_review', 'open_profile_review', 'edit_order_fields', 'edit_reservation', + 'confirm_customer', 'adjudicate_duplicate', 'resolve_field_conflicts', + 'open_inventory_source_review', 'open_inventory_match_review', 'open_shortage_review', + 'upload_inventory_file', 'confirm_inventory_field_mapping', +}: + PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'navigation' +for _code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping', 'retry_inventory_from_matching'}: + PROCESS_GATE_ACTION_PRESENTATION[_code]['kind'] = 'recovery' +for _code in {'poll_inventory_preparation', 'poll_freight_upload_rpa'}: + PROCESS_GATE_ACTION_PRESENTATION[_code]['dispatch'] = 'refresh' + + +def action_presentation(action_code: str | None, *, kind: str | None = None) -> dict[str, str] | None: + """返回用户动作展示元数据;未知动作 fail-closed。""" + code = str(action_code or '').strip() + item = PROCESS_GATE_ACTION_PRESENTATION.get(code) + if item is None: + return None + payload = {'code': code, **item} + if kind: + payload['kind'] = kind + return payload # 技术自动 Gate 的责任方;业务用户投影不得暴露其 POST 重试动作。 PROCESS_GATE_TECHNICAL_PARTIES: Final[frozenset[str]] = frozenset({ @@ -367,7 +416,7 @@ PROCESS_GATE_BUSINESS_PARTIES: Final[frozenset[str]] = frozenset({ def is_business_user_action(action_code: str | None) -> bool: - """判断动作是否允许向业务用户投影为可处理入口。""" + """判断服务端下发的 Gate 动作是否允许投影为可处理入口。""" code = str(action_code or '').strip() return bool(code) and code in PROCESS_GATE_BUSINESS_USER_ACTION_CODES @@ -766,6 +815,7 @@ def assert_process_gate_contract_integrity() -> None: assert set(sequences) == set(range(1, len(sequences) + 1)), 'process gate sequence_no must be contiguous' for item in PROCESS_GATE_DEFINITIONS: assert item['responsible_party'] in PROCESS_GATE_RESPONSIBLE_PARTIES + assert item.get('implementation_status') in PROCESS_GATE_IMPLEMENTATION_STATUSES actions = item.get('default_next_actions') or {} assert isinstance(actions, dict) for status, action in actions.items(): diff --git a/backend/app/services/shipping_notice/process_gate_executor.py b/backend/app/services/shipping_notice/process_gate_executor.py index c56e4219..99ac9328 100644 --- a/backend/app/services/shipping_notice/process_gate_executor.py +++ b/backend/app/services/shipping_notice/process_gate_executor.py @@ -139,6 +139,9 @@ def execute_queued_attempt( snapshot = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {} action = str(snapshot.get('action_code') or gate.next_action_code or '').strip() payload = snapshot.get('payload') if isinstance(snapshot.get('payload'), dict) else {} + payload = {**payload, 'action_code': action, 'attempt_id': int(attempt.id)} + if attempt.recovery_plan_id: + payload.setdefault('recovery_plan_id', int(attempt.recovery_plan_id)) outcome = _dispatch_action( execution=execution, @@ -185,6 +188,9 @@ def _dispatch_action( 'poll_inventory_preparation': _handle_retry_inventory_preparation, 'retry_inventory_field_mapping': _handle_retry_inventory_field_mapping, 'retry_inventory_matching': _handle_retry_inventory_matching, + 'retry_inventory_from_preparation': _handle_retry_inventory_preparation, + 'retry_inventory_from_field_mapping': _handle_retry_inventory_from_field_mapping, + 'retry_inventory_from_matching': _handle_retry_inventory_from_matching, 'recheck_inventory_sufficiency': _handle_recheck_inventory_sufficiency, 'recheck_excel_readiness': _handle_recheck_excel_readiness, 'regenerate_excel_artifact': _handle_regenerate_excel, @@ -242,6 +248,9 @@ def _assert_action_belongs_to_gate(*, gate_code: str, action_code: str) -> None: for value in (definition.get('default_next_actions') or {}).values() if value } + from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action + if recovery_plan_for_action(current_gate=gate_code, action_code=action_code) is not None: + return if gate_code == 'inventory_source_routing': allowed |= { 'adopt_rule_suggestion', @@ -263,6 +272,10 @@ def _assert_action_belongs_to_gate(*, gate_code: str, action_code: str) -> None: 'confirm_inventory_field_mapping': {'inventory_field_mapping'}, 'regenerate_manual_upload_todo': {'manual_upload_handoff'}, } + # 人工交接 Gate 仍允许用户主动重新发起 RPA;AUTO_UPLOAD 开关只控制 + # 自动链路,不应阻断此显式恢复动作。 + if action_code == 'retry_freight_upload_rpa' and gate_code == 'manual_upload_handoff': + return if action_code in allowed: return if action_code in nav_owning and gate_code in nav_owning[action_code]: @@ -325,7 +338,13 @@ def _manual_open(action: str, owning_gate: str) -> Callable[..., dict[str, Any]] def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any]) -> dict[str, Any]: - """构造履约 workflow 所需 payload。""" + """ + 构造 Gate Worker 调用履约 workflow 所需的内部原子执行 payload。 + + 核心逻辑:Gate Attempt 已经持有当前任务的编排边界,因此必须标记 + ``_orchestrator_internal_dispatch``,禁止库存/Excel workflow 再次绕回 + ``run_task_auto_progress``,把当前活动 Attempt 误判成“无待处理 Gate”。 + """ from app.models import ShippingNotice task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None @@ -335,6 +354,7 @@ def _task_payload(execution: ShippingProcessExecution, payload: dict[str, Any]) 'task_id': str(task.task_no), 'source': 'process_gate', 'operator_id': payload.get('actor_user_id') or payload.get('user_id'), + '_orchestrator_internal_dispatch': True, } @@ -733,13 +753,38 @@ def _handle_retry_inventory_preparation( """ from app.models import ShippingNotice from app.services.shipping_notice.inventory_workflow import ensure_inventory + from app.services.shipping_notice.inventory_recovery_service import create_inventory_preparation_round + from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream from app.services.shipping_notice.process_gate_bridge import ( inventory_preparation_reason_code, sync_fulfillment_gates_from_task, ) - response = ensure_inventory(_task_payload(execution, payload)) task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + recovery_plan_id = payload.get('recovery_plan_id') + preparation_round = None + if task is not None and payload.get('action_code') != 'poll_inventory_preparation': + if payload.get('action_code') in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping'}: + invalidate_inventory_downstream( + execution=execution, + action_code=str(payload.get('action_code')), + attempt_id=payload.get('attempt_id'), + actor_id=payload.get('actor_user_id'), + ) + preparation_round = create_inventory_preparation_round( + task=task, + execution_id=int(execution.id), + recovery_plan_id=int(recovery_plan_id) if recovery_plan_id else None, + action_code=str(payload.get('action_code') or 'retry_inventory_preparation'), + operation_id=str(payload.get('operation_id') or '').strip() or None, + gate_attempt_id=int(payload.get('attempt_id')) if payload.get('attempt_id') else None, + ) + response = ensure_inventory(_task_payload(execution, payload)) + if preparation_round is not None: + from app.services.shipping_notice.inventory_recovery_service import sync_inventory_preparation_round + + rpa_result = ((response.get('data') or {}).get('rpa') or {}) if isinstance(response, dict) else {} + sync_inventory_preparation_round(preparation_attempt=preparation_round, result=rpa_result) prep_reason = ( inventory_preparation_reason_code(task) if task is not None @@ -781,12 +826,12 @@ def _handle_retry_inventory_field_mapping( 'output_snapshot': {'action_code': 'retry_inventory_field_mapping'}, } inv_file = active_inventory_file_for_task(task) + from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task + mapped = bool( inv_file is not None and bool(getattr(inv_file, 'mapping_confirmed', False)) - and ( - isinstance(task.inventory_lines_json, list) and len(task.inventory_lines_json) > 0 - ) + and bool(active_inventory_lines_for_task(task)) ) apply_gate_outcome( execution=execution, @@ -822,27 +867,113 @@ def _handle_retry_inventory_field_mapping( } +def _handle_retry_inventory_from_field_mapping( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """从库存字段映射恢复:失效匹配下游后只重跑映射,不创建库存准备轮次。""" + from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream + + invalidate_inventory_downstream( + execution=execution, + action_code='retry_inventory_from_field_mapping', + attempt_id=payload.get('attempt_id'), + actor_id=payload.get('actor_user_id'), + ) + mapping_outcome = _handle_retry_inventory_field_mapping( + execution=execution, + gate=gate, + payload=payload, + ) + if mapping_outcome.get('outcome') != 'passed': + return mapping_outcome + return _handle_retry_inventory_matching( + execution=execution, + gate=gate, + payload=payload, + ) + + def _handle_retry_inventory_matching( *, execution: ShippingProcessExecution, gate: ShippingProcessGate, payload: dict[str, Any], ) -> dict[str, Any]: - """重试库存匹配(仅 inventory_matching)。""" + """ + 重试库存匹配;匹配已完成但仍有缺口时返回业务人工阻断。 + + 核心逻辑:``match_inventory`` 的 ``needs_human`` 同时覆盖“匹配失败”和 + “匹配成功但库存不足”。后者必须以库存满足性人工复核收口,不能误记为 + 技术失败,否则 RecoveryPlan 会反复失败且页面看不到有效推进。 + """ + from app.models import ShippingNotice from app.services.shipping_notice.fulfillment_workflow import match_inventory from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task response = match_inventory(_task_payload(execution, payload)) + sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id')) + task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None + match_status = str(getattr(task, 'match_status', '') or '').strip().lower() + has_shortage = bool(getattr(task, 'shortage_json', None)) + if str((response or {}).get('status') or '').strip().lower() == 'needs_human' and ( + match_status in {'partial', 'unfulfillable'} or has_shortage + ): + return { + 'outcome': 'blocked_manual', + 'blocking_reason_code': 'inventory_shortage_review_required', + 'blocking_reason_json': { + 'message': '库存重新匹配已完成,仍存在库存缺口。', + 'match_status': match_status or None, + }, + 'recommendation_json': { + 'navigation_action': 'open_shortage_review', + 'dispatch_mode': 'navigate', + }, + 'effective_result_json': { + 'findings': [], + 'match_status': match_status or None, + 'shortage': getattr(task, 'shortage_json', None), + }, + 'output_snapshot': { + 'action_code': 'retry_inventory_matching', + 'tool_status': 'needs_human', + 'business_result': 'inventory_shortage', + }, + } outcome = _tool_outcome( action_code='retry_inventory_matching', response=response, blocking_reason_code='inventory_match_failed', invalidate_change_type=None, ) - sync_fulfillment_gates_from_task(execution=execution, actor_type='system', actor_id=payload.get('actor_user_id')) return outcome +def _handle_retry_inventory_from_matching( + *, + execution: ShippingProcessExecution, + gate: ShippingProcessGate, + payload: dict[str, Any], +) -> dict[str, Any]: + """缺口恢复:保留当前库存快照,仅重新执行 Reservation + 料号匹配。""" + from app.services.shipping_notice.recovery_invalidation_service import invalidate_inventory_downstream + + invalidate_inventory_downstream( + execution=execution, + action_code='retry_inventory_from_matching', + attempt_id=payload.get('attempt_id'), + actor_id=payload.get('actor_user_id'), + ) + return _handle_retry_inventory_matching( + execution=execution, + gate=gate, + payload=payload, + ) + + def _handle_recheck_inventory_sufficiency( *, execution: ShippingProcessExecution, diff --git a/backend/app/services/shipping_notice/process_gate_job_service.py b/backend/app/services/shipping_notice/process_gate_job_service.py index e42e08da..d3a1fa11 100644 --- a/backend/app/services/shipping_notice/process_gate_job_service.py +++ b/backend/app/services/shipping_notice/process_gate_job_service.py @@ -5,7 +5,7 @@ services/shipping_notice/process_gate_job_service.py 依赖:app.jobs.queue、JobType、ShippingProcessGateAttempt、process_gate_executor、 process_gate_service、fulfillment_audit。 逻辑:由 recovery_service 对异步动作调用 enqueue;Worker Handler 调用 - claim_and_run_gate_attempt;重试/轮询使用 force_new 避免复用 running Job; + claim_and_run_gate_attempt;失败不自动重试,只有 waiting_external 轮询使用 force_new; waiting_external 超时转入 blocked_manual;心跳 commit 后对其他 Worker 可见; enqueue_process_gate_healthcheck_probe 供部署脚本验证 Worker 真实领取。 """ @@ -55,6 +55,15 @@ def _heartbeat_seconds() -> int: return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_HEARTBEAT_SECONDS', 15) or 15), 5) +def _technical_job_max_attempts() -> int: + """返回同一 GateAttempt 的技术重试上限,默认 3 次。 + + 只覆盖 Worker 领取、数据库或短暂外部故障等技术异常;业务失败仍由 + Executor 完成当前 Attempt,并经 RecoveryPlan 创建新的业务 Attempt。 + """ + return max(int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_MAX_ATTEMPTS', 3) or 3), 1) + + def enqueue_process_gate_healthcheck_probe(*, created_by_id: int | None = None) -> int: """ 入队门禁健康检查探针 Job,供 deploy healthcheck 验证 Worker 真实领取。 @@ -91,13 +100,13 @@ def enqueue_gate_attempt_job( 为 Attempt 入队 Gate Job,并回写 attempt.job_id。 核心逻辑:默认仅对 queued 去重,绝不复用仍 running 的同 business_ref Job; - force_new 时使用带时间戳的 business_ref,保证重试/轮询一定新建可领取 Job。 + force_new 时使用带时间戳的 business_ref,保证外部等待轮询一定新建可领取 Job。 Args: attempt_id: Attempt 主键。 created_by_id: 可选创建人。 delay_seconds: 延迟入队秒数。 - force_new: True 时强制新建 Job(重试/外部等待轮询)。 + force_new: True 时强制新建 Job(仅用于外部等待轮询)。 Returns: Job 主键。 @@ -117,7 +126,6 @@ def enqueue_gate_attempt_job( if delay_seconds and int(delay_seconds) > 0: scheduled_at = _utc_now() + timedelta(seconds=int(delay_seconds)) - max_attempts = int(current_app.config.get('SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES', 3) or 3) # [STEP] force_new 用独立 business_ref,避免与刚结束/仍残留的 Job 去重冲突。 if force_new: business_ref = f'attempt:{int(attempt.id)}:r{_utc_now().strftime("%Y%m%d%H%M%S")}:{uuid.uuid4().hex[:8]}' @@ -125,12 +133,16 @@ def enqueue_gate_attempt_job( business_ref = f'attempt:{int(attempt.id)}' job_id = enqueue( JobType.SHIPPING_PROCESS_GATE, - {'attempt_id': int(attempt.id)}, + { + 'attempt_id': int(attempt.id), + 'recovery_plan_id': int(attempt.recovery_plan_id) if attempt.recovery_plan_id else None, + }, domain=SHIPPING_PROCESS_GATE_JOB_DOMAIN, business_ref=business_ref, created_by_id=created_by_id, message='等待执行门禁恢复 Attempt', - max_attempts=max(max_attempts, 1), + # Job 仅对技术异常重试;业务失败由 Attempt/RecoveryPlan 显式建新轮次。 + max_attempts=_technical_job_max_attempts(), scheduled_at=scheduled_at, # 仅匹配 queued:禁止复用仍 running 的旧 Job(重试场景)。 dedupe_statuses=('queued',), diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index 6d058ea5..519207e8 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -19,16 +19,18 @@ from app.models import ( ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, + ShippingProcessRecoveryPlan, ) from app.services.shipping_notice.error_explainability_contract import ( build_explainability_reason, message_zh_for_reason, ) from app.services.shipping_notice.process_gate_contract import ( + PROCESS_GATE_CODE_SET, PROCESS_GATE_RECOVERABLE_STATUSES, + action_presentation, get_process_gate_definition, is_business_user_action, - primary_next_action_for_gate, ) from app.services.shipping_notice.process_gate_error_sanitizer import sanitize_gate_error_text @@ -66,6 +68,20 @@ _ACTION_NAVIGATION_FOCUS: dict[str, str] = { 'upload_inventory_file': 'manual_upload', } +def _projection_gate_definition(gate_code: str) -> dict[str, Any]: + """只读取正式 20-Gate 契约;历史 Gate 由调用方走只读审计分支。""" + return get_process_gate_definition(gate_code) + + +def _projection_primary_next_action(*, gate_code: str, status: str) -> str | None: + """按统一投影定义解析下一动作,兼容 P0-3 Gate。""" + definition = _projection_gate_definition(gate_code) + actions = definition.get('default_next_actions') + if not isinstance(actions, dict): + return None + value = actions.get(str(status or '').strip()) + return str(value) if value else None + def serialize_gate_attempt( attempt: ShippingProcessGateAttempt | None, @@ -124,7 +140,11 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo gate: 门禁行。 include_diagnostics: False 时仅保留用户可见 blocking Finding。 """ - definition = get_process_gate_definition(gate.gate_code) + legacy_readonly = str(gate.gate_code or '').strip() not in PROCESS_GATE_CODE_SET + definition = ( + {'label': '历史 AutoProgress 记录', 'responsible_party': 'system', 'recoverable': False} + if legacy_readonly else _projection_gate_definition(gate.gate_code) + ) latest = None if gate.latest_attempt_id: latest = ShippingProcessGateAttempt.query.get(int(gate.latest_attempt_id)) @@ -134,10 +154,28 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo item for item in findings if item.get('severity') == 'blocking' and item.get('user_visible', True) ] + allowed_actions = [str(gate.next_action_code)] if not legacy_readonly and ( + gate.next_action_code and is_business_user_action(str(gate.next_action_code)) + ) else [] + # 将 RecoveryPlan 目标绑定到当前 Gate 对象,避免 Case/UI 包装层只透传主动作时丢失恢复按钮。 + from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS + recovery_targets = [] if legacy_readonly else [ + { + 'action_code': action_code, + 'target_gate': plan.get('target_gate'), + 'resume_after_gate': plan.get('resume_after_gate'), + 'allowed_intermediate_gates': list(plan.get('allowed_intermediate_gates') or ()), + 'invalidates': list(plan.get('invalidates') or ()), + 'permission': plan.get('permission'), + } + for action_code, plan in (RECOVERY_PLAN_ACTIONS.get(str(gate.gate_code), {}) or {}).items() + ] return { 'gate_code': gate.gate_code, + 'legacy_readonly': legacy_readonly, 'sequence_no': int(gate.sequence_no), 'label': definition.get('label'), + 'implementation_status': definition.get('implementation_status'), 'status': gate.status, 'evaluation_version': int(gate.evaluation_version), 'input_fingerprint': gate.input_fingerprint, @@ -150,12 +188,22 @@ def serialize_process_gate(gate: ShippingProcessGate, *, include_diagnostics: bo 'effective_result': gate.effective_result_json if include_diagnostics else None, 'findings': findings, 'next_action_code': gate.next_action_code, + 'allowed_actions': allowed_actions, + 'action_presentation': [item for code in allowed_actions if (item := action_presentation(code))], + 'recovery_targets': recovery_targets, 'responsible_party': definition.get('responsible_party'), 'recoverable': bool(definition.get('recoverable')), 'passed_at': gate.passed_at.isoformat() if gate.passed_at else None, 'invalidated_at': gate.invalidated_at.isoformat() if gate.invalidated_at else None, 'latest_attempt': serialize_gate_attempt(latest) if include_diagnostics else ( - {'attempt_no': latest.attempt_no, 'status': latest.status} if latest else None + { + 'id': int(latest.id), + 'attempt_no': latest.attempt_no, + 'status': latest.status, + # 用户需要能区分“失败原因”和“系统失败”,但不能看到堆栈、路径或凭据。 + 'error_code': str(latest.error_code or '').strip() or None, + 'error_summary': sanitize_gate_error_text(latest.error_summary, max_len=500), + } if latest else None ), } @@ -185,9 +233,29 @@ def serialize_process_execution( (item for item in serialized if item.get('gate_code') == execution.current_gate_code), None, ) + legacy_readonly = any(item.get('legacy_readonly') for item in serialized) + recovery_targets: list[dict[str, Any]] = [] + if execution.current_gate_code and not legacy_readonly: + # RecoveryPlan 合同是服务端唯一动作来源;Projection 只读输出,客户端不能改写 target Gate。 + from app.services.shipping_notice.recovery_plan_contract import RECOVERY_PLAN_ACTIONS + + for action_code, definition in (RECOVERY_PLAN_ACTIONS.get(execution.current_gate_code, {}) or {}).items(): + recovery_targets.append({ + 'action_code': action_code, + 'target_gate': definition.get('target_gate'), + 'resume_after_gate': definition.get('resume_after_gate'), + 'allowed_intermediate_gates': list(definition.get('allowed_intermediate_gates') or ()), + 'invalidates': list(definition.get('invalidates') or ()), + 'permission': definition.get('permission'), + }) + active_recovery_plans = ShippingProcessRecoveryPlan.query.filter( + ShippingProcessRecoveryPlan.execution_id == int(execution.id), + ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}), + ).order_by(ShippingProcessRecoveryPlan.created_at.desc()).all() return { 'execution_no': execution.execution_no, - 'status': execution.status, + 'status': 'legacy_readonly' if legacy_readonly else execution.status, + 'legacy_readonly': legacy_readonly, 'current_gate_code': execution.current_gate_code, 'last_passed_gate_code': execution.last_passed_gate_code, 'primary_next_action_code': execution.primary_next_action_code, @@ -199,6 +267,19 @@ def serialize_process_execution( 'review_case_id': int(execution.review_case_id) if execution.review_case_id else None, 'task_id': int(execution.task_id) if execution.task_id else None, 'current_gate': current, + 'recovery_targets': recovery_targets, + 'active_recovery_plans': [ + { + 'plan_no': plan.plan_no, + 'action_code': plan.action_code, + 'current_gate': plan.current_gate, + 'target_gate': plan.target_gate, + 'resume_after_gate': plan.resume_after_gate, + 'status': plan.status, + 'idempotency_key': plan.idempotency_key if include_diagnostics else None, + } + for plan in active_recovery_plans + ], 'gates': serialized, 'updated_at': execution.updated_at.isoformat() if execution.updated_at else None, } @@ -278,6 +359,45 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, current_blocking_gate、reason、next_action、diagnostic_hint、technical_auto_only。 """ full = serialize_process_execution(execution, include_diagnostics=False) + # 完成态的正式 Execution 会清空 current_gate_code;空值表示没有待处理 Gate, + # 不能被误判为已下线的 APX 历史执行。只有存在实际 Gate 编号且不在正式契约内时, + # 才进入 legacy_readonly 兼容投影。 + current_gate_code = str(getattr(execution, 'current_gate_code', '') or '').strip() + legacy_readonly = bool(full.get('legacy_readonly')) or ( + bool(current_gate_code) and current_gate_code not in PROCESS_GATE_CODE_SET + ) + if legacy_readonly: + refs = _execution_navigation_refs(execution) + return { + 'execution_no': full.get('execution_no'), + 'status': 'legacy_readonly', + 'legacy_readonly': True, + 'execution_status': None, + 'current_gate': full.get('current_gate'), + 'current_blocking_gate': None, + 'recovery_targets': [], + 'active_recovery_plans': [], + 'blocking_reason_code': 'shipping_apx_runtime_disabled', + 'blocking_message': '历史自动推进记录仅供审计查看', + 'failure_detail': None, + 'explainability': None, + 'next_action_code': None, + 'primary_action': None, + 'allowed_actions': [], + 'action_presentation': [], + 'view_actions': [{'code': 'view_audit', 'kind': 'view', 'dispatch': 'navigation'}], + 'technical_auto_only': True, + 'owner_type': 'system', + 'responsible_party': 'system', + 'diagnostic_hint': None, + **refs, + 'navigation': None, + 'gates_track': [ + {'gate_code': item.get('gate_code'), 'label': item.get('label'), + 'status': item.get('status'), 'sequence_no': item.get('sequence_no')} + for item in (full.get('gates') or []) + ], + } current = full.get('current_gate') blocking = None if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | { @@ -311,20 +431,94 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, break reason_code = (blocking or {}).get('blocking_reason_code') next_action = full.get('primary_next_action_code') or ( - primary_next_action_for_gate( + _projection_primary_next_action( gate_code=str((blocking or {}).get('gate_code') or ''), status=str((blocking or {}).get('status') or ''), ) if blocking else None ) - # [STEP] 技术重试动作不对业务用户投影;仅保留复核工作台业务动作白名单。 + # [STEP] 兼容历史 Gate 行:RPA 失败曾被旧契约错误写成 + # regenerate_manual_upload_todo;当前 Gate + 原因码才是履约真相, + # 统一纠正为用户可主动执行的 RPA 重试。AUTO_UPLOAD 只控制自动触发, + # 不参与手动动作投影。 + blocking_gate_code = str((blocking or {}).get('gate_code') or '').strip().lower() + normalized_reason = str(reason_code or '').strip().lower() + if ( + blocking_gate_code == 'freight_upload_rpa' + and normalized_reason in { + 'upload_rpa_failed', + 'upload_rpa_login_failed', + 'upload_platform_rejected', + } + ): + next_action = 'retry_freight_upload_rpa' + elif ( + blocking_gate_code == 'manual_upload_handoff' + and normalized_reason in {'manual_upload_pending', 'upload_result_unknown'} + ): + # 人工交接仍保留人工登记入口(Footer),同时在 Gate 卡提供显式 RPA 重试。 + next_action = 'retry_freight_upload_rpa' + # [STEP] 所有冻结 Gate 动作均可投影到工作台;是否可执行由页面 canHandle + # 与 Workspace API 的权限/版本校验共同决定,禁止前端自行派生动作。 technical_auto_only = False - if next_action and not is_business_user_action(str(next_action)): + # 技术责任方的 retry_* 只作为系统执行动作,不能直接充当业务用户主按钮; + # RecoveryPlan 仍可在下方投影为经过权限校验的恢复入口。 + if ( + next_action + and ( + not is_business_user_action(str(next_action)) + or ( + str(full.get('responsible_party') or '').strip().lower() in {'system', 'worker'} + and str(next_action).startswith('retry_') + ) + ) + ): next_action = None technical_auto_only = bool(blocking) + + # [STEP] 正式 OT 后的库存阻断仍需给业务用户提供精确入口:技术主动作 + # (retry_inventory_*)不直接暴露,但 RecoveryPlan 存在时必须保留当前 + # Gate 的复核入口,否则 apply_post_ot_gate_rules 会把整个阻断误判为系统态, + # 前端也就不会挂载 ProcessGateRecoveryCard。 + if blocking and not next_action: + gate_code = str(blocking.get('gate_code') or '').strip().lower() + recovery_targets = full.get('recovery_targets') or [] + if recovery_targets and gate_code == 'inventory_matching': + next_action = 'open_inventory_match_review' + technical_auto_only = False + elif recovery_targets and gate_code == 'inventory_sufficiency': + next_action = 'open_shortage_review' + technical_auto_only = False + + # 正式 OT 后仍需允许业务用户恢复履约链路中的技术失败: + # 库存准备/匹配以及货代上传 RPA 的动作码由 Gate 合同固定, + # 不把其他 system/worker 节点泛化为可人工操作。 + if not next_action and gate_code in { + 'inventory_preparation', + 'inventory_matching', + 'freight_upload_rpa', + }: + candidate = _projection_primary_next_action( + gate_code=gate_code, + status=str(blocking.get('status') or ''), + ) + if candidate and is_business_user_action(candidate): + next_action = candidate + technical_auto_only = False # 无当前阻断时禁止残留 confirm_customer,避免「客户已确认」仍显示为优先处理。 if not blocking and str(next_action or '').strip() == 'confirm_customer': next_action = None + allowed_actions: list[str] = [] + action_items: list[dict[str, str]] = [] + if blocking: + if next_action and is_business_user_action(str(next_action)): + allowed_actions.append(str(next_action)) + for target in full.get('recovery_targets') or []: + code = str(target.get('action_code') or '').strip() + if code and code not in allowed_actions and is_business_user_action(code): + allowed_actions.append(code) + action_items = [item for code in allowed_actions if (item := action_presentation(code))] + # [STEP] 统一可解释性投影:文案/责任方/下一步与 error_explainability_contract 同源; # request_id 仅真实请求号;execution_no 放入 details 供 Worker 路径关联。 explainability = None @@ -350,11 +544,22 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, 'execution_no': full.get('execution_no'), 'status': full.get('status'), 'execution_status': execution_status, + # 当前执行 Gate 与人工阻断分开投影:queued/running 不生成待办,但阶段游标必须 + # 仍来自正式 Gate,避免旧 OT stage 把页面停留在库存匹配。 + 'current_gate': current, 'current_blocking_gate': blocking, + # 客户端只消费服务端已校验的恢复目标,不自行推导跨 Gate 路径。 + 'recovery_targets': full.get('recovery_targets') or [], + 'active_recovery_plans': full.get('active_recovery_plans') or [], 'blocking_reason_code': reason_code, 'blocking_message': _user_facing_blocking_message(reason_code), + 'failure_detail': _user_facing_failure_detail(blocking), 'explainability': explainability, 'next_action_code': next_action, + 'primary_action': action_presentation(next_action), + 'allowed_actions': allowed_actions, + 'action_presentation': action_items, + 'view_actions': [{'code': 'view_audit', 'kind': 'view', 'dispatch': 'navigation'}], 'technical_auto_only': technical_auto_only, 'owner_type': ( 'system' if technical_auto_only or execution_status @@ -409,6 +614,34 @@ def _user_facing_blocking_reason_payload(gate: ShippingProcessGate) -> dict[str, return payload +def _user_facing_failure_detail(blocking: dict[str, Any] | None) -> str | None: + """ + 提取当前 Gate 最近一次失败的脱敏业务详情,供用户排查。 + + 优先级:Attempt.error_summary → blocking_reason.message → Finding.details.message。 + 仅返回已经经过门禁错误脱敏器处理的短文本;没有事实时返回 None,避免伪造原因。 + """ + if not isinstance(blocking, dict): + return None + latest = blocking.get('latest_attempt') + candidates: list[Any] = [] + if isinstance(latest, dict): + candidates.extend([latest.get('error_summary'), latest.get('error_code')]) + reason = blocking.get('blocking_reason') + if isinstance(reason, dict): + candidates.extend([reason.get('message'), reason.get('failure_detail'), reason.get('error_summary')]) + for finding in blocking.get('findings') or []: + if not isinstance(finding, dict): + continue + details = finding.get('details') if isinstance(finding.get('details'), dict) else {} + candidates.extend([details.get('failure_detail'), details.get('message'), details.get('error_summary')]) + for value in candidates: + text = sanitize_gate_error_text(value, max_len=500) + if text: + return text + return None + + def _current_request_id() -> str | None: """ 读取当前 HTTP 请求的 request_id;无请求上下文时返回 None。 @@ -574,6 +807,12 @@ def _user_facing_blocking_message(reason_code: str | None) -> str | None: 'run_failed': '识别运行失败', 'run_cancelled': '识别运行已取消', 'pending_orders_present': '仍有待处理订单', + 'inventory_candidates_required': '当前没有库存候选集,无法开始库存匹配;请先重新获取库存', + 'inventory_candidates_frozen_required': '库存候选集尚未确认,请先完成库存源确认', + 'inventory_snapshot_prepare_failed': '库存快照准备失败,请检查库存获取结果后重试', + 'inventory_snapshots_pending': '库存快照仍在准备中,请稍后刷新进度', + 'inventory_match_not_ready': '库存尚未满足匹配条件,请先完成库存准备', + 'projection_data_inconsistent': '处理进度数据不一致,请刷新页面后重试;若仍失败请联系管理员', } return legacy.get(code) diff --git a/backend/app/services/shipping_notice/process_gate_recovery_service.py b/backend/app/services/shipping_notice/process_gate_recovery_service.py index dc3388be..27290b96 100644 --- a/backend/app/services/shipping_notice/process_gate_recovery_service.py +++ b/backend/app/services/shipping_notice/process_gate_recovery_service.py @@ -15,7 +15,7 @@ from __future__ import annotations from typing import Any from app.core.errors import NotFoundError, ValidationError -from app.models import ShippingProcessExecution, ShippingProcessGate +from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.process_gate_contract import ( PROCESS_GATE_ACTION_CODES, @@ -29,6 +29,8 @@ from app.services.shipping_notice.process_gate_executor import ( execute_queued_attempt, ) from app.services.shipping_notice.process_gate_service import queue_gate_attempt +from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action +from app.services.shipping_notice.recovery_plan_service import bind_recovery_attempt, create_recovery_plan def _chat_process_gate_event_type(*, action_code: str, trigger_type: str) -> str: @@ -138,13 +140,6 @@ def request_gate_action( action = str(action_code or '').strip() if action not in PROCESS_GATE_ACTION_CODES: raise ValidationError('Unknown process gate action', code='SHIPPING.PROCESS_GATE_ACTION_INVALID') - # [STEP] 业务用户禁止触发技术 Gate 写动作;前端隐藏不是安全边界。 - if str(actor_type or '') == 'user' and not is_business_user_action(action): - raise ValidationError( - 'Technical gate actions are not allowed for business users', - code='SHIPPING.PROCESS_GATE_TECHNICAL_ACTION_FORBIDDEN', - details={'action_code': action}, - ) forbidden = {'start_stage', 'target_status', 'worker_name', 'tool_name', 'next_node', 'sql'} body = dict(payload) if isinstance(payload, dict) else {} if forbidden.intersection(set(body.keys())): @@ -159,6 +154,13 @@ def request_gate_action( body.setdefault('idempotency_key', str(idempotency_key or '')) execution = get_execution_by_no(execution_no) + execution_status = str(execution.status or '').strip().lower() + if execution_status in {'completed', 'cancelled'}: + raise ValidationError( + 'Process execution is terminal; write actions are not allowed', + code='SHIPPING.PROCESS_EXECUTION_TERMINAL', + details={'execution_no': execution.execution_no, 'status': execution_status}, + ) gate = ShippingProcessGate.query.filter_by( execution_id=int(execution.id), gate_code=str(gate_code or '').strip(), @@ -166,6 +168,43 @@ def request_gate_action( if gate is None: raise NotFoundError('Process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') + current_gate = str(execution.current_gate_code or '').strip() + replay_attempt = ShippingProcessGateAttempt.query.filter_by( + idempotency_key=str(idempotency_key or '').strip(), + ).first() + # 跨阶段恢复目标先做 Gate 归属校验;错误 Gate 必须返回稳定的 + # RECOVERY_TARGET_INVALID,而不是被普通技术动作权限错误遮蔽。 + recovery_definition = recovery_plan_for_action(current_gate=gate.gate_code, action_code=action) + if action.startswith('retry_inventory_from_') and recovery_definition is None: + raise ValidationError( + 'Recovery target is not allowed for current gate', + code='SHIPPING.RECOVERY_TARGET_INVALID', + details={'current_gate': gate.gate_code, 'action_code': action}, + ) + + # [GLOBAL ACTION GUARD] 所有 20 Gate 共用同一入口:请求 Gate 必须是 Execution 当前 Gate。 + # 跨阶段动作已在前面完成目标归属判定,避免错误地把非法恢复目标报告为状态漂移。 + if replay_attempt is None and (not current_gate or current_gate != str(gate.gate_code or '').strip()): + raise ValidationError( + 'Action must target the current process gate', + code='SHIPPING.PROCESS_GATE_NOT_CURRENT', + details={ + 'execution_no': execution.execution_no, + 'current_gate': current_gate or None, + 'requested_gate': gate.gate_code, + 'action_code': action, + }, + ) + + # [STEP] 业务用户禁止触发技术 Gate 写动作;前端隐藏不是安全边界。 + # 必须在跨阶段目标归属之后判断,保证错误 Gate 返回 RECOVERY_TARGET_INVALID。 + if str(actor_type or '') == 'user' and not is_business_user_action(action): + raise ValidationError( + 'Technical gate actions are not allowed for business users', + code='SHIPPING.PROCESS_GATE_TECHNICAL_ACTION_FORBIDDEN', + details={'action_code': action}, + ) + definition = get_process_gate_definition(gate.gate_code) if ( str(actor_type or '') == 'user' @@ -181,6 +220,15 @@ def request_gate_action( primary = gate.next_action_code or primary_next_action_for_gate( gate_code=gate.gate_code, status=gate.status, ) + # [STEP] 兼容历史 Gate 20:用户投影已将人工待办旧动作纠正为显式 RPA + # 重试,但数据库 Gate 行可能仍保留 regenerate_manual_upload_todo。 + # 这里必须与用户投影使用同一 Gate/原因事实,否则点击必然被主动作校验拒绝。 + if ( + gate.gate_code == 'manual_upload_handoff' + and gate.blocking_reason_code in {'manual_upload_pending', 'upload_result_unknown'} + and action == 'retry_freight_upload_rpa' + ): + primary = action # [STEP] 附属动作仅允许挂在 inventory_source_routing,禁止跨门禁执行库存决定。 allowed_side: set[str] = set() if gate.gate_code == 'inventory_source_routing': @@ -188,7 +236,7 @@ def request_gate_action( 'adopt_rule_suggestion', 'keep_manual_inventory_decision', } - if primary and action != primary and action not in allowed_side: + if primary and action != primary and action not in allowed_side and recovery_definition is None: raise ValidationError( 'Action is not the primary recovery action for this gate', code='SHIPPING.PROCESS_GATE_ACTION_NOT_ALLOWED', @@ -198,6 +246,20 @@ def request_gate_action( trigger_type = ( 'user_retry' if action.startswith('retry') or action.startswith('re') else 'user_manual' ) + recovery_plan = None + if recovery_definition is not None: + recovery_plan, _ = create_recovery_plan( + execution=execution, + gate=gate, + action_code=action, + idempotency_key=idempotency_key, + actor_type=actor_type, + actor_id=actor_id, + operation_id=str(body.get('operation_id') or '').strip() or None, + ) + body['recovery_plan_id'] = int(recovery_plan.id) + body['recovery_action_code'] = action + attempt = queue_gate_attempt( execution_no=execution.execution_no, gate_code=gate.gate_code, @@ -209,6 +271,9 @@ def request_gate_action( input_snapshot={'action_code': action, 'payload': body}, ) + if recovery_definition is not None: + bind_recovery_attempt(plan=recovery_plan, attempt_id=int(attempt.id)) + # 幂等回放且已终态:直接返回,不二次执行;也不重复写 chat_* 审计。 if attempt.status in {'succeeded', 'failed', 'cancelled', 'superseded'}: db_gate = ShippingProcessGate.query.get(int(attempt.gate_id)) @@ -226,6 +291,7 @@ def request_gate_action( }, 'gate_status': db_gate.status if db_gate else gate.status, 'gate_evaluation_version': int(db_gate.evaluation_version) if db_gate else int(gate.evaluation_version), + 'recovery_plan_id': int(recovery_plan.id) if recovery_plan is not None else None, } # [STEP] 对话工作台语义审计:与 process_gate_recovery_requested 并存,供审计中心 chat 分组筛选。 @@ -260,6 +326,7 @@ def request_gate_action( 'idempotency_key': attempt.idempotency_key, }, 'gate_evaluation_version': int(gate.evaluation_version), + 'recovery_plan_id': int(recovery_plan.id) if recovery_plan is not None else None, } updated_gate = execute_queued_attempt(attempt=attempt, worker_id='sync-recovery') @@ -278,4 +345,5 @@ def request_gate_action( 'gate_status': updated_gate.status, 'gate_evaluation_version': int(updated_gate.evaluation_version), 'next_action_code': updated_gate.next_action_code, + 'recovery_plan_id': int(recovery_plan.id) if recovery_plan is not None else None, } diff --git a/backend/app/services/shipping_notice/process_gate_service.py b/backend/app/services/shipping_notice/process_gate_service.py index 6485d79f..c0b83f2c 100644 --- a/backend/app/services/shipping_notice/process_gate_service.py +++ b/backend/app/services/shipping_notice/process_gate_service.py @@ -23,9 +23,11 @@ from app.models import ( ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, + ShippingProcessRecoveryPlan, ) from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit from app.services.shipping_notice.process_gate_contract import ( + PROCESS_GATE_CODE_SET, PROCESS_GATE_DEFINITIONS, PROCESS_GATE_RECOVERABLE_STATUSES, get_process_gate_definition, @@ -293,6 +295,15 @@ def ensure_execution_for_workflow_version( .order_by(ShippingProcessExecution.id.desc()) .first() ) + # APX 六 Gate 与正式 20-Gate 不能共用同一 Execution。历史数据可能仍按 + # task_id 被查到;此时必须新建正式链,禁止把 20-Gate 行写进 APX sequence。 + if existing is not None: + existing_codes = { + str(row.gate_code or '').strip() + for row in ShippingProcessGate.query.filter_by(execution_id=int(existing.id)).all() + } + if existing_codes and not existing_codes.issubset(PROCESS_GATE_CODE_SET): + existing = None if existing is not None: if review_case_id and existing.review_case_id is None: existing.review_case_id = int(review_case_id) @@ -635,11 +646,28 @@ def complete_gate_attempt( attempt.error_code = str(error_code)[:64] if error_code else None # [STEP] 持久化前脱敏,避免 URL/路径/连接信息进入 Attempt 与后续投影。 attempt.error_summary = sanitize_gate_error_text(error_summary, max_len=2000) - # waiting_external 表示 Attempt 本身成功完成并进入外部等待,不应记为 failed。 - attempt.status = 'succeeded' if outcome in {'passed', 'waiting_external'} else 'failed' + # passed / waiting_external / blocked_manual 均表示执行器已成功得到业务结果; + # blocked_manual 只是 Gate 仍需人工复核(例如库存 14、缺口 16),不能误记为技术失败。 + attempt.status = 'succeeded' if outcome in { + 'passed', 'waiting_external', 'blocked_manual', + } else 'failed' attempt.lease_token = None attempt.lease_expires_at = None + if attempt.recovery_plan_id: + from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt + + plan = db.session.get(ShippingProcessRecoveryPlan, int(attempt.recovery_plan_id)) + if plan is not None: + complete_recovery_plan_for_attempt( + plan=plan, + outcome=outcome, + now=now, + error_code=error_code, + error_summary=error_summary, + business_result_code=blocking_reason_code, + ) + gate.status = outcome gate.blocking_reason_code = str(blocking_reason_code)[:64] if blocking_reason_code else None reason_payload = dict(blocking_reason_json or {}) or None @@ -667,13 +695,9 @@ def complete_gate_attempt( # 过去只有复核确认建单链路会入队 auto_progress,导致其余门禁恢复后 # Gate 已 passed 但任务仍停在旧节点。这里使用同一幂等任务队列入口, # 与事务一起提交,避免恢复动作提交前 Worker 读到不完整状态。 - # 业务投影(trigger_type=auto)本身属于 auto_progress 当前事务,避免递归排队; - # 恢复动作(user/system_requeue)通过统一队列续跑后续节点。 - if ( - outcome == 'passed' - and execution.task_id - and str(attempt.trigger_type or '').strip() != 'auto' - ): + # 无论由自动或恢复 Attempt 通过,都统一委托 AutoProgress 找到下一 Gate。 + # 它只入队一个 Attempt/Job;同一事务内的状态尚未提交,Worker 不会读到半成品。 + if outcome == 'passed' and execution.task_id: _enqueue_auto_progress_after_gate_pass(execution=execution, gate=gate) invalidated: list[str] = [] @@ -723,39 +747,41 @@ def _enqueue_auto_progress_after_gate_pass( execution: ShippingProcessExecution, gate: ShippingProcessGate, ) -> None: - """门禁通过后为绑定任务排入幂等 auto_progress Job。 + """门禁通过后为绑定任务提交下一 Gate 的唯一 AutoProgress Attempt/Job。 - 核心逻辑:复用 shipping_notice_run 的业务去重与执行模式;不直接执行编排, - 让当前恢复事务先提交后再由 Worker/同步队列继续后续门禁。已完成或仍需人工的 - 任务会由 auto_progress 自身的 checkpoint 逻辑安全早停。 + 核心逻辑:不再写 legacy shipping_notice_run;统一由 submit_auto_progress 创建 + ProcessGate Attempt/Job。已完成或仍需人工的任务会安全早停。 """ try: - from app.models import ShippingNotice - task = db.session.get(ShippingNotice, int(execution.task_id)) - task_no = str(getattr(task, 'task_no', '') or '').strip().upper() - if not task_no: - return - from app.services.shipping_notice.queue_service import enqueue_shipping_notice_job - ok, result = enqueue_shipping_notice_job( - task_no=task_no, - created_by_id=None, - commit=False, + # 直接为下一 Gate 创建 Attempt/ProcessGate Job,避免重新进入 + # submit_auto_progress→sync_fulfillment_gates 的递归路径。 + _refresh_execution_pointers(execution) + next_gate = ( + ShippingProcessGate.query + .filter_by(execution_id=int(execution.id), gate_code=str(execution.current_gate_code or '')) + .with_for_update() + .first() ) - if not ok: - record_fulfillment_audit( - event_type='task_auto_progress_enqueue_failed', - aggregate_type='shipping_task', - aggregate_id=task_no, - action='auto_progress', - actor_type='system', - actor_id=None, - task_no=task_no, - result='failure', - reason_code='auto_progress_enqueue_failed', - error_code='SHIPPING.AUTO_PROGRESS_ENQUEUE_FAILED', - after={'gate_code': gate.gate_code, 'message': str(result)[:500]}, - source='process_gate', - ) + if next_gate is None or not next_gate.next_action_code: + return + definition = get_process_gate_definition(next_gate.gate_code) + if str(definition.get('responsible_party') or '') not in {'system', 'worker'}: + return + attempt = queue_gate_attempt( + execution_no=str(execution.execution_no), + gate_code=next_gate.gate_code, + trigger_type='auto', + actor_type='system', + actor_id=None, + idempotency_key=( + f'shipping-auto-progress:{execution.task_id}:{execution.id}:' + f'{next_gate.id}:{next_gate.evaluation_version}' + ), + expected_gate_version=int(next_gate.evaluation_version), + input_snapshot={'action_code': next_gate.next_action_code, 'payload': {'trigger': 'gate_attempt_passed'}}, + ) + from app.services.shipping_notice.process_gate_job_service import enqueue_gate_attempt_job + enqueue_gate_attempt_job(attempt_id=int(attempt.id), created_by_id=None) except Exception as exc: # noqa: BLE001 — 门禁结果不可被排程异常覆盖 record_fulfillment_audit( event_type='task_auto_progress_enqueue_failed', @@ -870,6 +896,23 @@ def sync_gate_from_business_result( key = str(idempotency_key or '').strip() or f'sync:{execution_no}:{gate_code}:{uuid.uuid4().hex}' execution = _locked_execution(execution_no) gate = _locked_gate(execution=execution, gate_code=gate_code) + + # [STEP] Gate Worker 执行器可能在当前 Attempt 内同步最新业务事实。 + # 同一 Gate 已有 queued/running Attempt 时,事实同步必须由外层 Attempt + # 统一 complete,禁止递归创建第二个 Attempt,否则会误报 PROCESS_GATE_BUSY, + # 并最终把可恢复业务失败收口为 failed_terminal。 + active_attempt = ( + ShippingProcessGateAttempt.query + .filter( + ShippingProcessGateAttempt.gate_id == int(gate.id), + ShippingProcessGateAttempt.status.in_(('queued', 'running')), + ) + .order_by(ShippingProcessGateAttempt.attempt_no.desc()) + .first() + ) + if active_attempt is not None: + return gate + if allow_repass and gate.status == 'passed': gate.status = 'invalidated' gate.invalidated_at = _utc_now() diff --git a/backend/app/services/shipping_notice/processing_projection_invariants.py b/backend/app/services/shipping_notice/processing_projection_invariants.py index 57c2af99..5023f02e 100644 --- a/backend/app/services/shipping_notice/processing_projection_invariants.py +++ b/backend/app/services/shipping_notice/processing_projection_invariants.py @@ -92,6 +92,9 @@ _ACTION_CODE_ALIASES: dict[str, str] = { 'rematch': 'open_inventory_match_review', 'match_inventory': 'open_inventory_match_review', 'generate_excel': 'regenerate_excel', + # 正式 Process Gate 动作投影到旧工作台的同一业务意图;真实写动作仍由 + # Gate API 使用原始 action_code 校验,legacy projection 只负责展示语义。 + 'regenerate_excel_artifact': 'regenerate_excel', 'freeze_order': 'edit_formal_task', } @@ -453,6 +456,45 @@ def reconcile_processing_projection_facts( stage_idx = shipping_processing_stage_index(stage) waiting_idx = shipping_processing_stage_index('waiting_review') or 8 + # 关键事实无法读取时 fail-closed:不能继续沿用旧 checkpoint 或写动作。 + if payload.get('projection_data_inconsistent'): + payload['status'] = 'waiting_human' + payload['stage'] = 'waiting_review' + payload['current_gate'] = None + payload['primary_action'] = None + payload['available_actions'] = [] + payload['retryable'] = False + payload['blocking_reason'] = { + 'code': 'projection_data_inconsistent', + 'message': '处理状态暂时无法确认,请刷新后重试', + } + payload['stage_nodes'] = build_stage_nodes( + stage='waiting_review', status='waiting_human', source_type=source_type, + invalidated_from_stage=invalidated_from_stage, + ) + return payload + + # [BE-08] 正式 Gate 是后半段唯一进度真相。OT 的旧 stage/status 可能仍停在 + # inventory_matching/running,但 Gate 已经进入 Excel 或上传节点;先把统一 + # 投影游标对齐 Gate,禁止旧 primary_action 继续生成 match_inventory。 + gate_stage = { + 'excel_readiness': 'excel_generating', + 'artifact_generation': 'excel_generating', + 'freight_upload_rpa': 'freight_uploading', + 'manual_upload_handoff': 'freight_uploading', + }.get(str((gate or {}).get('gate_code') or '').strip().lower()) + if gate_stage: + stage = gate_stage + payload['stage_label_key'] = gate_stage + gate_status = str((gate or {}).get('status') or '').strip().lower() + if gate_status in {'blocked_retryable', 'failed_terminal', 'invalidated'}: + status = 'blocked' + elif gate_status == 'waiting_external': + status = 'automating' + elif gate_status in {'queued', 'running'}: + status = 'automating' + stage_idx = shipping_processing_stage_index(stage) + # [BE-03] Extraction Run 完成误标为全流程 completed:早期 stage 时回退 status。 if status == 'completed' and stage and stage != 'completed': if stage_idx is not None and stage_idx <= waiting_idx: @@ -597,6 +639,31 @@ def apply_user_projection_fields( payload['legacy_current_gate'] = payload.get('current_gate') old_status = str(payload.get('status') or '').strip().lower() old_stage = str(payload.get('stage') or '').strip().lower() + source_type = str(payload.get('source_type') or '').strip().lower() or None + old_gate = payload.get('current_gate') if isinstance(payload.get('current_gate'), dict) else None + + # 关键事实读取失败时立即 fail-closed;不能继续执行后续 legacy/retry 推导, + # 否则后续逻辑可能重新生成可执行主动作覆盖诊断态。 + if payload.get('projection_data_inconsistent'): + payload['user_status'] = 'waiting_human' + payload['user_stage'] = 'waiting_review' + payload['user_current_gate_code'] = None + payload['blocking_reason'] = { + 'code': 'projection_data_inconsistent', + 'i18n_key': 'workspace.shippingNotice.processGate.reasons.projection_data_inconsistent', + 'details': {}, + } + payload['retryable'] = False + payload['primary_action'] = None + payload['available_actions'] = [] + payload['current_gate'] = None + payload['stage'] = 'waiting_review' + payload['status'] = 'waiting_human' + payload['stage_nodes'] = build_stage_nodes( + stage='waiting_review', status='waiting_human', source_type=source_type, + invalidated_from_stage=None, + ) + return payload # ===== [STEP 2] 读取 notice / order_task 原始字段(保持不变) ===== pending_reason: str | None = None @@ -650,6 +717,13 @@ def apply_user_projection_fields( ) def _compute_user_status() -> str: + # [BE-09] 当前 Gate 终态优先于旧 Notice retry decision。Retry decision + # 只描述任务调度,不能覆盖正式 Gate 已到达的 Excel/上传阻断。 + gate_status = str((old_gate or {}).get('status') or '').strip().lower() + if gate_status in {'blocked_retryable', 'failed_terminal', 'invalidated'}: + return 'retryable' + if gate_status == 'blocked_manual': + return 'waiting_human' # 1) 终态短路:old_status completed/cancelled/failed if old_status == 'completed': return 'completed' @@ -706,7 +780,6 @@ def apply_user_projection_fields( user_stage = 'document_parsing' # ===== [不变] user_current_gate_code 计算(保持不动) ===== - old_gate = payload.get('current_gate') if isinstance(payload.get('current_gate'), dict) else None user_current_gate_code: str | None = None if isinstance(old_gate, dict): user_current_gate_code = str(old_gate.get('code') or old_gate.get('gate_code') or '').strip() or None @@ -734,6 +807,12 @@ def apply_user_projection_fields( 'inventory_source_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_source_conflicted', 'inventory_source_unresolved': 'workspace.shippingNotice.processGate.reasons.require_manual_review', 'inventory_multi_file_conflict': 'workspace.shippingNotice.processGate.reasons.inventory_multi_file_conflict', + 'inventory_candidates_required': 'workspace.shippingNotice.processGate.reasons.inventory_candidates_required', + 'inventory_candidates_frozen_required': 'workspace.shippingNotice.processGate.reasons.inventory_candidates_frozen_required', + 'inventory_snapshot_prepare_failed': 'workspace.shippingNotice.processGate.reasons.inventory_snapshot_prepare_failed', + 'inventory_snapshots_pending': 'workspace.shippingNotice.processGate.reasons.inventory_snapshots_pending', + 'inventory_match_not_ready': 'workspace.shippingNotice.processGate.reasons.inventory_match_not_ready', + 'projection_data_inconsistent': 'workspace.shippingNotice.processGate.reasons.projection_data_inconsistent', 'order_review_required': 'workspace.shippingNotice.processGate.reasons.freeze_not_ready', 'duplicate_decision_required': 'chat.shippingProcessing.reasonCode.duplicateDecisionRequired', 'SHIPPING.NOTICE_EXACT_DUPLICATE': 'chat.shippingProcessing.reasonCode.exactDuplicateNotice', @@ -786,6 +865,17 @@ def apply_user_projection_fields( 'i18n_key': _REASON_TO_I18N_KEY[rd_reason_code], 'details': {}, } + gate_reason = str((old_gate or {}).get('blocking_reason_code') or '').strip() + if gate_reason and gate_reason in _REASON_TO_I18N_KEY: + return { + 'code': gate_reason, + 'i18n_key': _REASON_TO_I18N_KEY[gate_reason], + 'details': dict( + (old_gate or {}).get('effective_result') + or (old_gate or {}).get('details') + or {} + ), + } return _legacy_waiting_human_blocking_reason() # 3) retryable if user_status == 'retryable': @@ -824,6 +914,7 @@ def apply_user_projection_fields( 'open_inventory_match_review': 'workspace.shippingNotice.processGate.actionCodes.open_inventory_match_review', 'open_order_review': 'workspace.shippingNotice.processGate.actionCodes.open_order_review', 'retry_freight_upload_rpa': 'workspace.shippingNotice.processGate.actionCodes.retry_freight_upload_rpa', + 'regenerate_excel': 'workspace.shippingNotice.processGate.actionCodes.regenerate_excel_artifact', 'adjudicate_duplicate': 'workspace.shippingNotice.processGate.actionCodes.adjudicate_duplicate', 'reconcile_and_progress': 'workspace.shippingNotice.processGate.actionCodes.reconcile_and_progress', 'open_profile_review': 'workspace.shippingNotice.processGate.actionCodes.open_profile_review', @@ -862,6 +953,20 @@ def apply_user_projection_fields( return None def _compute_primary_action() -> dict[str, Any] | None: + # [BE-10] Gate action 是当前阶段唯一主动作来源;旧 stage 的 + # match_inventory/regenerate_excel 仅作兼容回退。 + gate_action = str((old_gate or {}).get('next_action_code') or '').strip() + gate_action_alias = { + 'regenerate_excel_artifact': 'regenerate_excel', + }.get(gate_action, gate_action) + if gate_action_alias in SHIPPING_PROCESSING_ACTION_INTENTS and user_status in { + 'retryable', 'waiting_human', 'running', + }: + return { + 'code': gate_action_alias, + 'i18n_key': _resolve_action_i18n_key(gate_action_alias), + 'parameters': {}, + } # 1) blocking_reason 非 None if blocking_reason is not None: bcode = str(blocking_reason.get('code') or '').strip() @@ -903,6 +1008,7 @@ def apply_user_projection_fields( code = 'open_order_review' return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} # 1h. available_actions 含 reconcile_and_progress → 统一对账恢复入口兜底 + available_actions = payload.get('available_actions') if isinstance(available_actions, list) and 'reconcile_and_progress' in available_actions: code = 'reconcile_and_progress' return {'code': code, 'i18n_key': _resolve_action_i18n_key(code), 'parameters': {}} @@ -937,6 +1043,27 @@ def apply_user_projection_fields( 'upload_state': 'not_created', 'switch_state': 'not_triggered', } + # MVP 四库存里程碑是 Projection facts,不是第二套运行时 Gate 生命周期。 + # 仅依据正式 current_gate 的顺序和已投影事实派生,避免重新引入 APX 六 Gate。 + gate_code = str((payload.get('current_gate') or {}).get('gate_code') or '').strip() + gate_order = { + 'inventory_source_routing': 0, + 'inventory_preparation': 1, + 'inventory_field_mapping': 2, + 'inventory_matching': 3, + 'inventory_sufficiency': 4, + 'excel_readiness': 5, + 'artifact_generation': 6, + 'manual_upload_handoff': 7, + 'upload_receipt_recorded': 8, + } + current_order = gate_order.get(gate_code) + facts['inventory_milestones'] = { + 'candidates_calculated': 'completed' if current_order is not None and current_order >= 1 else 'pending', + 'candidates_frozen': 'completed' if current_order is not None and current_order >= 1 else 'pending', + 'snapshots_ready': 'completed' if current_order is not None and current_order >= 3 else 'pending', + 'matched': 'completed' if current_order is not None and current_order >= 4 else 'pending', + } if order_task is not None: cand = getattr(order_task, 'candidate_source_codes_json', None) if isinstance(cand, list): @@ -954,6 +1081,32 @@ def apply_user_projection_fields( fms = step_payload.get('forced_match_source_code') if fms: facts['forced_match_source_code'] = str(fms).strip().upper() + # 正式 OT 优先从 CandidateSet/LineMatch Projection 读取库存事实;旧 + # step_payload 仅作为尚未形成正式候选集的历史任务兼容回退。 + try: + from app.services.shipping_notice.inventory_candidate_projection import ( + project_inventory_candidate_facts, + ) + candidate_facts = project_inventory_candidate_facts(notice) + if candidate_facts.get('current_set') is not None: + facts['candidate_set_id'] = candidate_facts.get('candidate_set_id') + facts['candidate_set_version'] = candidate_facts.get('candidate_set_version') + facts['candidate_set_status'] = candidate_facts.get('candidate_set_status') + facts['candidate_source_codes'] = list(candidate_facts.get('candidate_source_codes') or []) + facts['prepared_source_codes'] = list(candidate_facts.get('prepared_source_codes') or []) + facts['pending_source_codes'] = list(candidate_facts.get('pending_source_codes') or []) + facts['failed_source_codes'] = list(candidate_facts.get('failed_source_codes') or []) + facts['source_attempts'] = dict(candidate_facts.get('source_attempts') or {}) + facts['line_resolutions'] = list(candidate_facts.get('line_resolutions') or []) + elif candidate_facts.get('blocking_reason', {}).get('code') in { + 'inventory_candidate_version_stale', + 'inventory_candidate_out_of_scope', + }: + payload['projection_data_inconsistent'] = True + except Exception: # noqa: BLE001 + # 结构化事实读取失败时交给最终 Projection invariant fail-closed; + # 不使用旧 payload 拼装出可执行状态。 + payload['projection_data_inconsistent'] = True # P0-2:逐源 Attempt 执行事实只读投影,前端不得从旧 status 猜测。 try: from app.models import ShippingTaskInventoryRpaAttempt diff --git a/backend/app/services/shipping_notice/progress_workflow.py b/backend/app/services/shipping_notice/progress_workflow.py index f4ba07c4..7e2ca667 100644 --- a/backend/app/services/shipping_notice/progress_workflow.py +++ b/backend/app/services/shipping_notice/progress_workflow.py @@ -125,6 +125,9 @@ def _dispatch_legacy_orchestration( operator_id: int | None, inventory_mode: str = 'auto', line_scope_key: str | None = None, + recovery_plan_id: int | None = None, + recovery_attempt_id: int | None = None, + resume_after_gate: str | None = None, ) -> dict[str, Any]: """ resume_gate_code → 旧实现分派(短期复用稳定实现,后续逐步把每个 Gate 原子步骤迁入本 facade)。 @@ -209,6 +212,9 @@ def run_task_auto_progress( operator_id: int | None = None, inventory_mode: str = 'auto', line_scope_key: str | None = None, + recovery_plan_id: int | None = None, + recovery_attempt_id: int | None = None, + resume_after_gate: str | None = None, ) -> dict[str, Any]: """ 唯一 AutoProgress Orchestrator Facade。 @@ -232,6 +238,9 @@ def run_task_auto_progress( operator_id: 操作人 ID(系统触发则 None)。 inventory_mode: 库存准备模式;用户显式重试传 retry_rpa,自动推进保持 auto。 line_scope_key: 行级 scope 键;传了则仅对该行执行(例如 match_inventory_line),不传则整单推进。 + recovery_plan_id: 可选恢复计划 ID,用于关联本次 Gate 恢复执行。 + recovery_attempt_id: 可选恢复 Attempt ID,用于关联本次 Gate 恢复执行。 + resume_after_gate: 可选恢复后续 Gate 标识。 Returns: Tool 标准响应(status=running/needs_human/failed/completed + task + data); @@ -252,6 +261,9 @@ def run_task_auto_progress( submitted = submit_auto_progress( task=task, trigger=trigger, operator_id=operator_id, resume_gate_code=resume_gate_code, commit=True, + recovery_plan_id=recovery_plan_id, + recovery_attempt_id=recovery_attempt_id, + resume_after_gate=resume_after_gate, ) status = str(submitted.get('status') or 'queued') if status == 'queued': @@ -397,6 +409,9 @@ def auto_progress(payload: dict[str, Any]) -> dict[str, Any]: idempotency_key=idempotency_key, resume_gate_code=None, operator_id=operator_id, + recovery_plan_id=payload.get('recovery_plan_id'), + recovery_attempt_id=payload.get('recovery_attempt_id'), + resume_after_gate=payload.get('resume_after_gate'), ) # 下方:_auto_progress_full 内部调用路径(直接执行完整串联,不再走 Orchestrator 外层) if not auto_progress_enabled(): diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index 6576d112..4bfaa88f 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -317,8 +317,12 @@ def resolve_task_export_download(task: ShippingNotice | None) -> tuple[Path, str if not task or not task.export_file_path: return None from app.models import ShippingExportArtifact - artifact = ShippingExportArtifact.query.filter_by( - task_id=task.id, status='ready', file_path=task.export_file_path, + # 已人工/RPA 上传完成的 Artifact 仍是用户可下载的最终 Excel; + # 不能因履约完成将 status=uploaded 排除在下载解析之外。 + artifact = ShippingExportArtifact.query.filter( + ShippingExportArtifact.task_id == task.id, + ShippingExportArtifact.status.in_({'ready', 'uploaded'}), + ShippingExportArtifact.file_path == task.export_file_path, ).order_by( ShippingExportArtifact.created_at.desc(), ShippingExportArtifact.id.desc(), ).first() diff --git a/backend/app/services/shipping_notice/reconciliation_projector.py b/backend/app/services/shipping_notice/reconciliation_projector.py index 011e2cf4..9e584002 100644 --- a/backend/app/services/shipping_notice/reconciliation_projector.py +++ b/backend/app/services/shipping_notice/reconciliation_projector.py @@ -462,7 +462,12 @@ def project_case_allowed_actions( if 'reconcile_and_progress' in actions: _others = [a for a in actions if a != 'reconcile_and_progress'] actions = ['reconcile_and_progress', *_others] - if llm_review_enabled() and 'edit_draft' in actions: + try: + llm_enabled = llm_review_enabled() + except RuntimeError: + # 纯投影合同和离线诊断没有 Flask 请求上下文;缺少运行时配置时按关闭处理。 + llm_enabled = False + if llm_enabled and 'edit_draft' in actions: actions.append('request_llm_suggestion') return actions @@ -591,7 +596,7 @@ def project_case_user_status( """ auto_status = str((automation or {}).get('status') or '').strip().lower() case_status = str(case.status or '').strip().lower() - if case_status in {'confirmed'} and auto_status in {'completed', 'success'}: + if auto_status in {'completed', 'success'}: return 'completed' if case_status in {'cancelled', 'superseded', 'non_order'}: return 'cancelled' diff --git a/backend/app/services/shipping_notice/recovery_contract.py b/backend/app/services/shipping_notice/recovery_contract.py index af4d6230..33876441 100644 --- a/backend/app/services/shipping_notice/recovery_contract.py +++ b/backend/app/services/shipping_notice/recovery_contract.py @@ -41,6 +41,15 @@ _TECH_RETRYABLE_CATEGORY_HINTS: frozenset[str] = frozenset({ "lease_expired", }) +# 库存 RPA Trigger 投递/领取失败属于技术暂态;不能被当作业务人工阻断, +# 否则正式 OT 的 retryable 投影会变成 false,conversation retry 不会重新建 Trigger。 +_TECH_RETRYABLE_ERROR_CODES: frozenset[str] = frozenset({ + "trigger_not_claimed_missing", + "trigger_not_claimed_timeout", + "inventory_trigger_missing", + "inventory_trigger_write_failed", +}) + # T3:业务阻断 → 推荐 UI 动作映射;未命中时 fallback 为 "open_order_review" BLOCKING_REASON_TO_ACTION_CODES: dict[str, str] = { "duplicate_decision_required": "adjudicate_duplicate", @@ -100,6 +109,9 @@ def is_tech_retryable_error( if normalized.startswith(prefix): return True + if normalized.lower() in _TECH_RETRYABLE_ERROR_CODES: + return True + hint = str(category_hint or "").strip() if hint and hint in _TECH_RETRYABLE_CATEGORY_HINTS: return True diff --git a/backend/app/services/shipping_notice/recovery_invalidation_service.py b/backend/app/services/shipping_notice/recovery_invalidation_service.py new file mode 100644 index 00000000..e983e8c7 --- /dev/null +++ b/backend/app/services/shipping_notice/recovery_invalidation_service.py @@ -0,0 +1,97 @@ +""" +services/shipping_notice/recovery_invalidation_service.py + +用途:按恢复动作精确失效库存下游事实及正式 Gate。 +依赖:ShippingProcessExecution/Gate、库存快照链接、行级 Match、Verification、Artifact、UploadAttempt。 +逻辑:只标记失效,不删除、不覆盖历史事实;所有变更在调用方事务内完成。 +""" + +from __future__ import annotations + +from datetime import datetime + +from app import db +from app.models import ( + ShippingExportArtifact, + ShippingInventoryVerification, + ShippingInventoryMapping, + ShippingNoticeLineInventoryMatch, + ShippingProcessExecution, + ShippingTaskInventoryLink, + ShippingUploadAttempt, +) +from app.services.shipping_notice.process_gate_service import invalidate_downstream_gates + + +def invalidate_inventory_downstream( + *, execution: ShippingProcessExecution, action_code: str, attempt_id: int | None = None, + actor_id: int | str | None = None, +) -> dict[str, list[int] | list[str]]: + """失效库存恢复受影响事实,并返回可审计的对象 ID。""" + task_id = int(execution.task_id or 0) + if not task_id: + return {'gates': [], 'links': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []} + now = datetime.utcnow() + from app.models import ShippingNotice + task = db.session.get(ShippingNotice, task_id) + result: dict[str, list[int] | list[str]] = {'gates': [], 'links': [], 'mappings': [], 'matches': [], 'verifications': [], 'artifacts': [], 'uploads': []} + change_type = { + 'retry_inventory_from_preparation': 'inventory_file_changed', + 'retry_inventory_from_field_mapping': 'inventory_field_mapping_changed', + 'retry_inventory_from_matching': 'inventory_matching_changed', + }.get(action_code, 'inventory_matching_changed') + result['gates'] = invalidate_downstream_gates(execution=execution, change_type=change_type, actor_id=actor_id) + if action_code == 'retry_inventory_from_preparation': + links = ShippingTaskInventoryLink.query.filter_by(task_id=task_id, is_active=True).with_for_update().all() + for link in links: + link.is_active = False + link.invalidated_at = now + link.invalidated_by_attempt_id = attempt_id + link.invalidation_reason = action_code + result['links'].append(int(link.id)) + active_file_ids = [ + int(link.inventory_file_id) + for link in ShippingTaskInventoryLink.query.filter_by(task_id=task_id).all() + if link.inventory_file_id + ] + if action_code in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping'} and active_file_ids: + mappings = ShippingInventoryMapping.query.filter( + ShippingInventoryMapping.inventory_file_id.in_(active_file_ids), + ShippingInventoryMapping.status == 'active', + ).with_for_update().all() + for mapping in mappings: + mapping.status = 'invalidated' + result['mappings'].append(int(mapping.id)) + matches = ShippingNoticeLineInventoryMatch.query.filter_by(task_id=task_id, is_current=True).with_for_update().all() + for row in matches: + row.is_current = False + row.invalidated_at = now + row.invalidated_by_attempt_id = attempt_id + row.invalidation_reason = action_code + result['matches'].append(int(row.id)) + verifications = ShippingInventoryVerification.query.filter_by(task_id=task_id, status='completed').with_for_update().all() + for verification in verifications: + verification.status = 'superseded' + result['verifications'].append(int(verification.id)) + artifacts = ShippingExportArtifact.query.filter( + ShippingExportArtifact.task_id == task_id, + ShippingExportArtifact.status.in_({'ready', 'uploading'}), + ).with_for_update().all() + for artifact in artifacts: + artifact.status = 'superseded' + result['artifacts'].append(int(artifact.id)) + uploads = ShippingUploadAttempt.query.filter_by(artifact_id=int(artifact.id)).filter( + ShippingUploadAttempt.status.in_({'pending', 'running', 'timed_out', 'unknown'}), + ).with_for_update().all() + for upload in uploads: + upload.invalidated_at = now + upload.invalidation_reason = action_code + result['uploads'].append(int(upload.id)) + if task is not None and action_code == 'retry_inventory_from_preparation': + task.match_status = None + task.shortage_json = None + task.line_results_json = None + task.export_file_path = None + task.export_file_name = None + db.session.flush() + return result diff --git a/backend/app/services/shipping_notice/recovery_plan_contract.py b/backend/app/services/shipping_notice/recovery_plan_contract.py new file mode 100644 index 00000000..d2183465 --- /dev/null +++ b/backend/app/services/shipping_notice/recovery_plan_contract.py @@ -0,0 +1,58 @@ +""" +services/shipping_notice/recovery_plan_contract.py + +用途:定义跨阶段恢复动作的服务端白名单及其失效/恢复边界。 +依赖:process_gate_contract 的正式 Gate 编码。 +逻辑:RecoveryPlan 服务和 Projection 共同消费此纯数据合同,客户端不能提交目标 Gate。 +""" + +from __future__ import annotations + +from typing import Any + + +RECOVERY_PLAN_ACTIONS: dict[str, dict[str, dict[str, Any]]] = { + 'inventory_matching': { + 'retry_inventory_from_preparation': { + 'target_gate': 'inventory_preparation', + 'resume_after_gate': 'inventory_matching', + 'allowed_intermediate_gates': ('inventory_field_mapping',), + 'invalidate_change_type': 'inventory_file_changed', + 'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'permission': 'owner_or_admin', + }, + 'retry_inventory_from_field_mapping': { + 'target_gate': 'inventory_field_mapping', + 'resume_after_gate': 'inventory_matching', + 'allowed_intermediate_gates': (), + 'invalidate_change_type': 'inventory_field_mapping_changed', + 'invalidates': ('inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'permission': 'owner_or_admin', + }, + }, + # 库存有缺口时仍由 Gate 16 负责恢复入口;数量事实只读,恢复动作回到正式库存链路。 + 'inventory_sufficiency': { + 'retry_inventory_from_preparation': { + 'target_gate': 'inventory_preparation', + 'resume_after_gate': 'inventory_sufficiency', + 'allowed_intermediate_gates': ('inventory_field_mapping', 'inventory_matching'), + 'invalidate_change_type': 'inventory_file_changed', + 'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'permission': 'owner_or_admin', + }, + 'retry_inventory_from_matching': { + 'target_gate': 'inventory_matching', + 'resume_after_gate': 'inventory_sufficiency', + 'allowed_intermediate_gates': (), + 'invalidate_change_type': 'inventory_matching_changed', + 'invalidates': ('inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'permission': 'owner_or_admin', + }, + }, +} + + +def recovery_plan_for_action(*, current_gate: str, action_code: str) -> dict[str, Any] | None: + """读取当前 Gate 下的跨阶段恢复计划定义;未知组合返回 None。""" + item = RECOVERY_PLAN_ACTIONS.get(str(current_gate or '').strip(), {}).get(str(action_code or '').strip()) + return dict(item) if isinstance(item, dict) else None diff --git a/backend/app/services/shipping_notice/recovery_plan_service.py b/backend/app/services/shipping_notice/recovery_plan_service.py new file mode 100644 index 00000000..3d85d549 --- /dev/null +++ b/backend/app/services/shipping_notice/recovery_plan_service.py @@ -0,0 +1,125 @@ +""" +services/shipping_notice/recovery_plan_service.py + +用途:创建并绑定跨阶段 RecoveryPlan,保证 Gate/Execution 锁、幂等和终态保护统一。 +依赖:ShippingProcessRecoveryPlan、process_gate_contract、recovery_plan_contract、db。 +逻辑:只创建白名单计划;Gate Attempt 由既有 process_gate_service 创建后回填关联。 +""" + +from __future__ import annotations + +from datetime import datetime +from typing import Any + +from app import db +from app.core.errors import ConflictError, ValidationError +from app.models import ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, ShippingProcessRecoveryPlan +from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action + + +_TERMINAL_EXECUTION_STATUSES = frozenset({'completed', 'cancelled', 'superseded'}) + + +def create_recovery_plan( + *, execution: ShippingProcessExecution, gate: ShippingProcessGate, action_code: str, + idempotency_key: str, actor_type: str, actor_id: int | str | None, + operation_id: str | None = None, +) -> tuple[ShippingProcessRecoveryPlan, dict[str, Any]]: + """校验并创建跨阶段恢复计划;同幂等键返回原计划。""" + definition = recovery_plan_for_action(current_gate=gate.gate_code, action_code=action_code) + if definition is None: + raise ValidationError( + 'Recovery target is not allowed for current gate', + code='SHIPPING.RECOVERY_TARGET_INVALID', + details={'current_gate': gate.gate_code, 'action_code': action_code}, + ) + if execution.status in _TERMINAL_EXECUTION_STATUSES: + raise ConflictError( + 'Recovery is not allowed on terminal execution', + code='SHIPPING.RECOVERY_NOT_ALLOWED_ON_TERMINAL', + details={'execution_no': execution.execution_no, 'status': execution.status}, + ) + key = str(idempotency_key or '').strip() + if not key: + raise ValidationError('idempotency_key is required', code='SHIPPING.PROCESS_GATE_IDEMPOTENCY_REQUIRED') + replay = ShippingProcessRecoveryPlan.query.filter_by( + execution_id=int(execution.id), idempotency_key=key, + ).first() + if replay is not None: + return replay, definition + active_plan = ShippingProcessRecoveryPlan.query.filter( + ShippingProcessRecoveryPlan.execution_id == int(execution.id), + ShippingProcessRecoveryPlan.status.in_({'planned', 'invalidating', 'queued', 'running', 'waiting_external', 'waiting_manual'}), + ).with_for_update().first() + if active_plan is not None: + raise ConflictError( + 'Another recovery plan is active for this execution', + code='SHIPPING.RECOVERY_PLAN_CONFLICT', + details={'execution_no': execution.execution_no, 'plan_no': active_plan.plan_no}, + ) + plan = ShippingProcessRecoveryPlan( + plan_no=f'RCP-{datetime.utcnow().strftime("%Y%m%d%H%M%S")}-{int(execution.id)}-{str(idempotency_key)[-8:]}', + execution_id=int(execution.id), current_gate=gate.gate_code, + action_code=str(action_code), target_gate=str(definition['target_gate']), + resume_after_gate=definition.get('resume_after_gate'), status='planned', + invalidation_plan_json={ + 'change_type': definition.get('invalidate_change_type'), + 'invalidates': list(definition.get('invalidates') or ()), + 'allowed_intermediate_gates': list(definition.get('allowed_intermediate_gates') or ()), + }, idempotency_key=key, expected_gate_version=int(gate.evaluation_version), + actor_type=str(actor_type or 'system'), actor_id=str(actor_id) if actor_id is not None else None, + operation_id=operation_id, + ) + db.session.add(plan) + db.session.flush() + return plan, definition + + +def bind_recovery_attempt(*, plan: ShippingProcessRecoveryPlan, attempt_id: int) -> None: + """把 Gate Attempt 纳入 RecoveryPlan;不提交事务。""" + plan.recovery_attempt_id = int(attempt_id) + attempt = db.session.get(ShippingProcessGateAttempt, int(attempt_id)) + if attempt is not None: + attempt.recovery_plan_id = int(plan.id) + plan.status = 'queued' + db.session.flush() + + +def complete_recovery_plan_for_attempt( + *, plan: ShippingProcessRecoveryPlan, outcome: str, now: datetime | None = None, + error_code: str | None = None, error_summary: str | None = None, + business_result_code: str | None = None, +) -> None: + """ + 将 RecoveryPlan 与绑定 Attempt 的执行结果原子收口。 + + 核心逻辑:使用当前库存重新匹配后若仍有缺口,说明恢复动作本身已成功, + 只是正式流程重新停在库存满足性人工复核;该计划必须终态完成,不能以 + ``waiting_manual`` 长期占用 Execution,阻塞用户再次选择其他恢复方式。 + """ + status_by_outcome = { + 'passed': 'succeeded', + 'waiting_external': 'waiting_external', + 'blocked_manual': 'waiting_manual', + 'blocked_retryable': 'failed', + 'failed_terminal': 'failed', + } + resolved_outcome = str(outcome) + rematch_reached_shortage_review = ( + resolved_outcome == 'blocked_manual' + and str(plan.action_code or '') == 'retry_inventory_from_matching' + and str(plan.resume_after_gate or '') == 'inventory_sufficiency' + and str(business_result_code or '') == 'inventory_shortage_review_required' + ) + plan.status = ( + 'succeeded' + if rematch_reached_shortage_review + else status_by_outcome.get(resolved_outcome, 'failed') + ) + plan.failure_code = str(error_code)[:64] if error_code else None + plan.failure_detail_json = ({'message': str(error_summary)[:500]} if error_summary else None) + finished_at = now or datetime.utcnow() + plan.started_at = plan.started_at or finished_at + if plan.status in {'succeeded', 'failed', 'cancelled'}: + plan.completed_at = finished_at + db.session.flush() diff --git a/backend/app/services/shipping_notice/rpa.py b/backend/app/services/shipping_notice/rpa.py index 79c5281f..f6a4d21b 100644 --- a/backend/app/services/shipping_notice/rpa.py +++ b/backend/app/services/shipping_notice/rpa.py @@ -15,6 +15,7 @@ from pathlib import Path from typing import Any from flask import current_app +from app.core.errors import ValidationError def _runtime_summary(mode: str) -> dict[str, str | bool]: @@ -153,9 +154,14 @@ def write_inventory_export_batch_trigger( "validation_run_no": source.get("validation_run_no"), } # v2 逐源身份必须由后端显式写入,Worker 不得重新生成。 - for identity_key in ("task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version", "expected_warehouse_id", "lease_token"): + for identity_key in ( + "callback_id", "task_no", "attempt_no", "source_run_no", "candidate_set_id", "candidate_set_version", + "execution_id", "gate_id", "expected_warehouse_id", "lease_token", + ): if source.get(identity_key) is not None: item[identity_key] = source[identity_key] + if not item.get('callback_id') and item.get('source_run_no'): + item['callback_id'] = f"{item['source_run_no']}:C1" inventory_sources.append(item) if not inventory_sources: return None @@ -163,6 +169,7 @@ def write_inventory_export_batch_trigger( body = { "action": "inventory_export_batch", "schema_version": "shipping_inventory_rpa.v2", + "callback_id": f"{run_no}:batch:C1", "batch_run_no": run_no, "run_no": run_no, # 旧排程读取兼容;新回调不得依赖该字段 "trigger_type": "scheduled", @@ -194,7 +201,8 @@ def write_inventory_export_trigger_for_task( 写入按需库存 RPA trigger;batch 开启时包装为单源 batch trigger,与定时导出共用 worker 路径。 【AI 触发时机】:ensure_inventory_via_rpa 触发单票 RPA 导出时调用。 - 核心逻辑:batch 模式写 inventory_export_batch(含 task_no);否则写 legacy inventory_export。 + 核心逻辑:仅允许 v2 batch 模式写 inventory_export_batch;关闭时 fail-closed, + 不再生成 legacy inventory_export trigger。 """ from app.services.shipping_notice.inventory_source_repository import get_rpa_trigger_inventory_source @@ -211,11 +219,18 @@ def write_inventory_export_trigger_for_task( run_no = str(body.get("batch_run_no") or f"BATCH-{task_no}-{datetime.utcnow().strftime('%Y%m%d%H%M%S%f')}") source_item = dict(rpa_source) source_item.update({ + "callback_id": body.get("callback_id") or ( + f"{body.get('source_run_no')}:C1" if body.get('source_run_no') else None + ), "task_no": task_no, - "attempt_no": body.get("attempt_no"), + # 按需逐源回调必须携带 Attempt 身份;仅写在 batch 顶层会导致 + # Worker 结果丢失 source_run_no,后端无法把 Excel 绑定到最新 Attempt。 + "attempt_no": body.get("attempt_no") or body.get("attempt"), "source_run_no": body.get("source_run_no"), "candidate_set_id": body.get("candidate_set_id"), "candidate_set_version": body.get("candidate_set_version"), + "execution_id": body.get("execution_id"), + "gate_id": body.get("gate_id"), "expected_warehouse_id": body.get("expected_warehouse_id"), "lease_token": body.get("lease_token"), }) @@ -229,12 +244,9 @@ def write_inventory_export_trigger_for_task( **body, }, ) - return write_inventory_export_trigger( - task_no, - { - "rpa_inventory_source": rpa_source, - **body, - }, + raise ValidationError( + 'shipping inventory RPA v2 batch trigger is required', + code='SHIPPING.INVENTORY_RPA_V2_REQUIRED', ) diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 887aae57..40e7b5d6 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -764,15 +764,35 @@ def _order_task_current_gate( Returns: ProcessGateSummary 形状 dict;无需门禁时 None。 """ - open_case = ( - ShippingOrderReviewCase.query.filter( - ShippingOrderReviewCase.run_id == int(run.id), - ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')), - ShippingOrderReviewCase.confirmed_task_id.is_(None), - ) - .order_by(ShippingOrderReviewCase.id.desc()) - .first() + # Child OT 必须先按自身 Candidate 找 Case;仅按 run_id 取最新 Case 会把 + # 多 PDF 的子订单阶段错误绑定到根 PDF。 + open_case = None + is_child_order_task = bool( + order_task is not None + and getattr(order_task, 'candidate_id', None) + and str(getattr(order_task, 'task_no', '') or '').strip() + != str(getattr(run, 'user_task_no', '') or '').strip() ) + if is_child_order_task: + open_case = ( + ShippingOrderReviewCase.query.filter( + ShippingOrderReviewCase.candidate_id == int(order_task.candidate_id), + ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')), + ShippingOrderReviewCase.confirmed_task_id.is_(None), + ) + .order_by(ShippingOrderReviewCase.id.desc()) + .first() + ) + if open_case is None: + open_case = ( + ShippingOrderReviewCase.query.filter( + ShippingOrderReviewCase.run_id == int(run.id), + ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')), + ShippingOrderReviewCase.confirmed_task_id.is_(None), + ) + .order_by(ShippingOrderReviewCase.id.desc()) + .first() + ) if open_case is not None: from app.models import ShippingProcessExecution from app.services.shipping_notice.process_gate_projection import ( @@ -786,7 +806,7 @@ def _order_task_current_gate( ) if execution is not None: summary = project_user_gate_summary(execution) - blocking = summary.get('current_blocking_gate') + blocking = summary.get('current_blocking_gate') or summary.get('current_gate') if isinstance(blocking, dict) and blocking.get('gate_code'): return { 'gate_code': str(blocking.get('gate_code') or ''), @@ -794,7 +814,6 @@ def _order_task_current_gate( 'next_action_code': ( summary.get('next_action_code') or blocking.get('next_action_code') - or 'open_order_review' ), 'blocking_reason_code': ( summary.get('blocking_reason_code') @@ -825,7 +844,7 @@ def _order_task_current_gate( ) if execution is not None: summary = project_user_gate_summary(execution) - blocking = summary.get('current_blocking_gate') + blocking = summary.get('current_blocking_gate') or summary.get('current_gate') if isinstance(blocking, dict) and blocking.get('gate_code'): return { 'gate_code': str(blocking.get('gate_code') or ''), @@ -833,7 +852,6 @@ def _order_task_current_gate( 'next_action_code': ( summary.get('next_action_code') or blocking.get('next_action_code') - or 'open_fulfillment' ), 'blocking_reason_code': ( summary.get('blocking_reason_code') @@ -985,6 +1003,7 @@ def _project_order_task_work_item( stage = map_run_to_processing_stage(run, source_type=source_type) # [BE-02] 已挂正式 Notice 时与 Case.current_stage 同源(project_stage_for_task)。 stage_label_key = None + notice_for_stage = None if order_task.shipping_notice_id: notice_for_stage = db.session.get(ShippingNotice, int(order_task.shipping_notice_id)) if notice_for_stage is not None: @@ -1007,6 +1026,13 @@ def _project_order_task_work_item( str(run.status or ''), stage=stage, ) + # 人工上传登记/RPA 回调先更新 ShippingNotice 聚合事实;旧 OT.status 可能仍为 + # automating。终态 Notice 必须覆盖旧 OT 状态,保证统一投影、右侧状态和进度节点同源。 + notice_process_status = str(getattr(notice_for_stage, 'process_status', None) or '').strip().lower() if notice_for_stage is not None else '' + if notice_process_status in {'uploaded', 'closed', 'completed'}: + status = 'completed' + stage = 'completed' + stage_label_key = 'completed' # [BE-03] OT 上残留的 completed + 早期 stage 组合在输出前再折叠。 if status == 'completed' and stage != 'completed': status = derivation_status_for_extraction_run('completed', stage=stage) @@ -1043,15 +1069,27 @@ def _project_order_task_work_item( # [P0] 深链订单处理工作台需要 run_no / case_no;禁止前端合成 OT 时丢失。 run_no = str(getattr(run, 'run_no', None) or '').strip() or None case_no = None - open_case = ( - ShippingOrderReviewCase.query.filter( - ShippingOrderReviewCase.run_id == int(run.id), - ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')), - ShippingOrderReviewCase.confirmed_task_id.is_(None), + open_case = None + if order_task is not None and getattr(order_task, 'candidate_id', None): + open_case = ( + ShippingOrderReviewCase.query.filter( + ShippingOrderReviewCase.candidate_id == int(order_task.candidate_id), + ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')), + ShippingOrderReviewCase.confirmed_task_id.is_(None), + ) + .order_by(ShippingOrderReviewCase.id.desc()) + .first() + ) + if open_case is None: + open_case = ( + ShippingOrderReviewCase.query.filter( + ShippingOrderReviewCase.run_id == int(run.id), + ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready')), + ShippingOrderReviewCase.confirmed_task_id.is_(None), + ) + .order_by(ShippingOrderReviewCase.id.desc()) + .first() ) - .order_by(ShippingOrderReviewCase.id.desc()) - .first() - ) if open_case is not None: case_no = str(getattr(open_case, 'case_no', None) or '').strip() or None elif order_task is not None and getattr(order_task, 'candidate_id', None): @@ -1148,14 +1186,17 @@ def _project_order_task_work_item( post_confirm=post_confirm_snapshot, is_admin=False, ) + formal_gate_projection = isinstance(payload.get('current_gate'), dict) and bool( + str((payload.get('current_gate') or {}).get('gate_code') or '').strip() + ) # 六字段覆盖:user_status / blocking_reason / primary_action / current_gate / available_actions / retryable if isinstance(bundle.get('user_status'), str): payload['user_status'] = bundle['user_status'] if isinstance(bundle.get('blocking_reason'), dict): payload['blocking_reason'] = dict(bundle['blocking_reason']) - if isinstance(bundle.get('primary_action'), dict): + if isinstance(bundle.get('primary_action'), dict) and not formal_gate_projection: payload['primary_action'] = dict(bundle['primary_action']) - if isinstance(bundle.get('current_gate'), dict): + if isinstance(bundle.get('current_gate'), dict) and not formal_gate_projection: current_gate = dict(payload.get('current_gate') or {}) current_gate.update(bundle['current_gate']) payload['current_gate'] = current_gate @@ -1173,32 +1214,58 @@ def _project_order_task_work_item( if retry_flag or str(payload.get('user_status') or '') == 'retryable': payload['retryable'] = True except Exception: # noqa: BLE001 - # 只读投影失败不阻断列表输出(fail-closed 兜底 invariants 结果) - pass + # Review bundle 是当前用户动作的权威来源;读取失败时不得静默回退到 + # 旧 checkpoint/notice 字段,避免前端展示可继续执行的过时动作。 + payload['user_status'] = 'waiting_human' + payload['retryable'] = False + payload['primary_action'] = None + payload['available_actions'] = [] + payload['blocking_reason'] = { + 'code': 'projection_data_inconsistent', + 'message': '处理状态暂时无法确认,请刷新后重试', + } # 题4A:注入 inventory_preparation 结构化字段(题7A:区分 failed/exhausted_sources); # 仅当 inventory 阶段或更早、且已挂正式 Notice 时才填充;其他阶段填 None 避免误导。 inventory_preparation = None if notice is not None: try: - from app.services.shipping_notice.task_retry_decision_service import ( - summarize_inventory_rpa_latest_attempts, - ) + from app.models import ShippingInventoryPreparationAttempt - snapshot_src = summarize_inventory_rpa_latest_attempts(notice, include_gate_status=True) - required_sources = list(snapshot_src.get('required_frozen_sources') or []) - prepared_sources = list(snapshot_src.get('prepared_source_codes') or []) - pending_sources = list(snapshot_src.get('pending_source_codes') or []) - failed_sources = list(snapshot_src.get('failed_source_codes') or []) - exhausted_sources = list(snapshot_src.get('exhausted_source_codes') or []) - active_attempt_count = int(snapshot_src.get('active_attempt_count') or 0) - latest_attempts = dict(snapshot_src.get('latest_attempts') or {}) + preparation = ( + ShippingInventoryPreparationAttempt.query + .filter_by(task_id=int(notice.id)) + .filter(ShippingInventoryPreparationAttempt.status != 'superseded') + .order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()) + .first() + ) + source_attempts = list(getattr(preparation, 'source_attempts', []) or []) if preparation else [] + required_sources = [str(row.source_code) for row in source_attempts] + prepared_sources = [str(row.source_code) for row in source_attempts if row.status in {'ready', 'reusable'}] + pending_sources = [str(row.source_code) for row in source_attempts if row.status in {'queued', 'running', 'waiting'}] + failed_sources = [str(row.source_code) for row in source_attempts if row.status == 'failed'] + exhausted_sources: list[str] = [] + active_attempt_count = 1 if preparation and preparation.status in {'queued', 'running', 'waiting_external'} else 0 + latest_attempts = { + str(row.source_code): { + 'attempt_no': int(preparation.attempt_no), + 'status': row.status, + 'rpa_attempt_id': row.rpa_attempt_id, + 'inventory_file_id': row.inventory_file_id, + } + for row in source_attempts + } # 快照载入状态补入 prepared_sources(如果快照就绪且 inventory_lines_json 已保存但 per_source 尚未标记 prepared) - if notice.inventory_lines_json and notice.inventory_snapshot_id: + from app.services.shipping_notice.inventory_file_store import active_inventory_lines_for_task + + if active_inventory_lines_for_task(notice) and notice.inventory_snapshot_id: for code in required_sources: if code and code not in prepared_sources and code not in pending_sources: prepared_sources.append(code) inventory_preparation = { + 'attempt_id': int(preparation.id) if preparation else None, + 'attempt_no': int(preparation.attempt_no) if preparation else None, + 'status': preparation.status if preparation else None, 'required_sources': required_sources, 'prepared_sources': prepared_sources, 'pending_sources': pending_sources, @@ -1206,10 +1273,16 @@ def _project_order_task_work_item( 'exhausted_sources': exhausted_sources, 'active_attempt_count': active_attempt_count, 'latest_attempts': latest_attempts, - 'gate_attempt_active': bool(snapshot_src.get('gate_attempt_active')), + 'source_attempts': latest_attempts, + 'gate_attempt_active': active_attempt_count > 0, } except Exception: # noqa: BLE001 + # 关键准备事实读取失败时 fail-closed;禁止静默回退到旧字段拼装出可执行状态。 inventory_preparation = None + payload['projection_data_inconsistent'] = True + # PreparationAttempt 读取发生在首次用户态归一化之后;立即重新应用 + # fail-closed 规则,防止异常分支保留旧 primary_action/available_actions。 + payload = apply_user_projection_fields(payload, notice=notice, order_task=order_task) payload['inventory_preparation'] = inventory_preparation # 题4A & 题7A:根据 inventory_preparation 统一折叠 retryable(仅当没有 pending/running + (failed or exhausted) 时,保证可重试为 true; diff --git a/backend/app/services/shipping_notice/stp_line_inventory_match.py b/backend/app/services/shipping_notice/stp_line_inventory_match.py index 2633f2ba..2ee233db 100644 --- a/backend/app/services/shipping_notice/stp_line_inventory_match.py +++ b/backend/app/services/shipping_notice/stp_line_inventory_match.py @@ -61,6 +61,7 @@ def _inventory_row_key(row: dict[str, Any]) -> tuple[str, str, str] | None: row.get('reservation_id') or row.get('Reservation ID') or row.get('reservation') ) part = _norm_part(row.get('part_number') or row.get('Part Number') or row.get('mpn') or row.get('sku')) + # 单位只有在 Profile 显式配置并被标准化进快照时才参与;默认空单位不阻断匹配。 unit = _norm_unit(row.get('uom') or row.get('unit') or row.get('UOM') or row.get('Unit')) if not reservation or not part: return None @@ -314,6 +315,7 @@ def match_order_lines_across_candidates( resolutions: list[dict[str, Any]] = [] has_ok = False has_block = False + has_partial = False for index, line in enumerate(order_lines): part = _norm_part(line.get('part_number') or line.get('__display_part_number')) @@ -344,7 +346,7 @@ def match_order_lines_across_candidates( for key in buckets if key[0] == (effective or '') and key[1] == part - and key[2] == unit + and (not unit or not key[2] or key[2] == unit) ] if effective and part else [] # 正式匹配必须存在结构化 CandidateLine,并严格限制在该行允许源内。 # 缺少行级范围本身就是候选事实缺失,不能退化为任务级并集匹配。 @@ -462,6 +464,7 @@ def match_order_lines_across_candidates( 'resolved_inventory_source_code': hit['source_code'], } has_block = True + has_partial = available > 0 line_results.append(result) resolutions.append({ @@ -486,7 +489,7 @@ def match_order_lines_across_candidates( if not order_lines: match_status = 'unfulfillable' elif has_block: - match_status = 'unfulfillable' if not has_ok else 'partial' + match_status = 'partial' if (has_ok or has_partial) else 'unfulfillable' else: match_status = 'fulfillable' diff --git a/backend/app/services/shipping_notice/task_retry_decision_service.py b/backend/app/services/shipping_notice/task_retry_decision_service.py index 15eb38b1..f64b3c69 100644 --- a/backend/app/services/shipping_notice/task_retry_decision_service.py +++ b/backend/app/services/shipping_notice/task_retry_decision_service.py @@ -41,6 +41,66 @@ PH_UPLOAD_PENDING = 'upload_rpa_pending' PH_UPLOAD_FAILED = 'upload_rpa_failed' +def _request_formal_gate_action( + *, + task: ShippingNotice, + action_code: str, + user_id: int, + idempotency_key: str, + trigger: str, + line_key: str | None = None, +) -> dict[str, Any]: + """将外部重试意图提交给正式 20-Gate Recovery/ProcessGate 编排。 + + 外部入口只负责定位当前正式 Gate 和动作;库存准备、匹配等旧函数仅允许 + 由 ``process_gate_executor`` 通过内部分派标记调用。 + """ + from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate + from app.services.shipping_notice.process_gate_recovery_service import request_gate_action + from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version + from app.models import ShippingProcessExecution, ShippingProcessGate + + execution = None + current_id = getattr(task, 'active_process_execution_id', None) + if current_id: + execution = ShippingProcessExecution.query.filter_by(id=int(current_id)).with_for_update().first() + if execution is None: + execution = ensure_execution_for_workflow_version( + task_id=int(task.id), actor_type='user', actor_id=int(user_id), + start_gate_code=determine_formal_start_gate(task), + ) + task.active_process_execution_id = int(execution.id) + db.session.flush() + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code=str(execution.current_gate_code or '').strip(), + ).first() + if gate is None: + raise ValidationError('Current formal process gate not found', code='SHIPPING.PROCESS_GATE_NOT_FOUND') + + requested = str(action_code or '').strip() + if requested == 'retry_inventory_from_matching' and gate.gate_code != 'inventory_sufficiency': + requested = 'retry_inventory_matching' + payload: dict[str, Any] = {'trigger': trigger} + if line_key: + payload['line_key'] = str(line_key) + result = request_gate_action( + execution_no=str(execution.execution_no), gate_code=str(gate.gate_code), + action_code=requested, expected_gate_version=int(gate.evaluation_version), + idempotency_key=str(idempotency_key), actor_type='user', actor_id=int(user_id), + payload=payload, + ) + return { + 'status': 'running' if result.get('dispatch') in {'async_job', 'sync'} else 'failed', + 'action': action_code, + 'task_id': task.task_no, + 'job_id': result.get('job_id'), + 'attempt_id': (result.get('attempt') or {}).get('id'), + 'execution_no': result.get('execution_no'), + 'gate_code': result.get('gate_code'), + 'message': '已提交正式 20-Gate 恢复动作', + } + + def retry_task_with_decision( *, task_no: str, @@ -219,6 +279,17 @@ def _decide( 'retryable': False, 'reason_code': 'already_running', } + latest_statuses = { + str(item.get('status') or '').strip().lower() + for item in (active.get('latest_attempts') or {}).values() + } + if scope != 'line' and pending == PH_RPA_PENDING and latest_statuses <= {'', 'not_started'}: + return { + 'action': ACTION_NOOP, + 'status': STATUS_RUNNING, + 'retryable': False, + 'reason_code': 'already_running', + } if pending == PH_UPLOAD_FAILED: return { 'action': ACTION_NEEDS_HUMAN, @@ -360,13 +431,20 @@ def _decide_for_line( inventory_rpa_running=line_running_flag, ) user_status = str(view.get('user_line_status') or '') - if user_status in {'shortage', 'source_conflict'}: + if user_status == 'source_conflict': return { 'action': ACTION_NEEDS_HUMAN, 'status': STATUS_NEEDS_HUMAN, 'retryable': False, 'reason_code': 'inventory_shortage' if user_status == 'shortage' else 'inventory_source_conflict', } + if user_status == 'shortage': + return { + 'action': ACTION_NEEDS_HUMAN, + 'status': STATUS_NEEDS_HUMAN, + 'retryable': False, + 'reason_code': 'inventory_shortage', + } if not project_line_retryable( inventory_allowed_actions=list(view.get('inventory_allowed_actions') or []), user_line_status=user_status, @@ -459,10 +537,10 @@ def _execute( adjudicate_and_apply_inventory_source, ensure_inventory_source_review_state, ) - from app.services.shipping_notice.inventory_workflow import ensure_inventory - from app.services.shipping_notice import tools as shipping_tools action = str(decided.get('action') or ACTION_NOOP) + # 所有重试动作(含库存匹配 REMATCH)共用同一触发来源;不能只在 FETCH 分支内初始化。 + trigger_norm = str(trigger or '').strip().lower() or 'user_retry' base_kwargs = { 'task': task, 'decision_version': decision_version, @@ -510,83 +588,58 @@ def _execute( action = ACTION_FETCH_INVENTORY if action == ACTION_FETCH_INVENTORY: - # 题1C:按调用来源分流。 - # user_retry / user_line_retry:直接 mode='retry_rpa',显式重试无论 auto 是否已 exhausted 都开新 Attempt。 - # conversation_retry / system_auto_progress 等:先 mode='auto' 复用快照,失败再 mode='retry_rpa' 兜底。 - trigger_norm = str(trigger or '').strip().lower() - user_explicit = trigger_norm in {'user_retry', 'user_line_retry'} - if not user_explicit: - reused = ensure_inventory({ - 'task_id': task.task_no, - 'mode': 'auto', - 'operator_id': int(user_id), - '_trusted_user_id': int(user_id), - 'event_source': 'workspace_api', - 'trigger': trigger_norm, - }) - if str((reused or {}).get('status') or '') in {'ok', 'completed'}: - if continue_auto_progress: - return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs) - return _map_tool_result( - reused, - action=ACTION_FETCH_INVENTORY, - base_kwargs=base_kwargs, - message='已复用库存快照', + # 库存 RPA 的正式前置事实是订单快照。历史任务可能已完成解析但未成功冻结, + # 会话重试必须先补做一次冻结;冻结门禁失败时返回 needs_human,禁止伪造 Trigger。 + if not getattr(task, 'order_snapshot_id', None) and isinstance(task, ShippingNotice): + try: + from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot + + freeze_order_snapshot( + task, + actor_id=int(user_id), + expected_order_data_version=decision_version, + freeze_mode='manual', ) - fetched = ensure_inventory({ - 'task_id': task.task_no, - 'mode': 'retry_rpa', - 'operator_id': int(user_id), - '_trusted_user_id': int(user_id), - 'event_source': 'workspace_api', - 'trigger': trigger_norm, - }) - return _map_tool_result( - fetched, - action=ACTION_FETCH_INVENTORY, - base_kwargs={ - **base_kwargs, - 'snapshot_id': getattr(task, 'inventory_snapshot_id', None), - }, - message='已提交库存获取', + db.session.flush() + except AppError as freeze_err: + return _result_payload( + action=ACTION_NEEDS_HUMAN, + status=STATUS_NEEDS_HUMAN, + retryable=False, + reason_code=str(getattr(freeze_err, 'code', None) or 'order_freeze_not_ready'), + message='订单快照尚未冻结,无法进入库存 RPA。', + **base_kwargs, + ) + formal = _request_formal_gate_action( + task=task, + action_code='retry_inventory_preparation', + user_id=int(user_id), + idempotency_key=idempotency_key, + trigger=trigger_norm, + line_key=line_key, ) + return _map_tool_result(formal, action=ACTION_FETCH_INVENTORY, base_kwargs=base_kwargs, message='已提交库存获取') if action == ACTION_REMATCH: # 题5B:有 line_key → 调用新 match_inventory_line 只对目标行匹配,避免整单重算覆盖其他行; # 否则(例如 scope=task 且缺快照或整单重算)仍走原 match_inventory。 norm_line_key = str(line_key or '').strip() - if norm_line_key: - matched = shipping_tools.match_inventory_line( - { - 'task_id': task.task_no, - 'operator_id': int(user_id), - '_trusted_user_id': int(user_id), - 'event_source': 'workspace_api', - 'trigger': trigger_norm, - }, - line_key=norm_line_key, - ) - else: - matched = shipping_tools.match_inventory({ - 'task_id': task.task_no, - 'operator_id': int(user_id), - '_trusted_user_id': int(user_id), - 'event_source': 'workspace_api', - 'trigger': trigger_norm, - }) - mapped = _map_tool_result( - matched, - action=ACTION_REMATCH, - base_kwargs=base_kwargs, - message='已提交库存匹配', + formal = _request_formal_gate_action( + task=task, + action_code='retry_inventory_from_matching', + user_id=int(user_id), + idempotency_key=idempotency_key, + trigger=trigger_norm, + line_key=norm_line_key or None, ) - if continue_auto_progress and mapped.get('status') == STATUS_COMPLETED: - return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs) - return mapped + return _map_tool_result(formal, action=ACTION_REMATCH, base_kwargs=base_kwargs, message='已提交库存匹配') # ACTION_AUTO_PROGRESS 或 continue return _run_auto_progress(task, user_id=user_id, base_kwargs=base_kwargs) except AppError as err: + # 下游 flush/写库失败会使 PostgreSQL 事务进入 aborted;必须先清理, + # 才能让调用方继续写本次失败决策审计。 + db.session.rollback() return _result_payload( action=ACTION_FAILED, status=STATUS_FAILED, @@ -597,6 +650,9 @@ def _execute( ) except Exception as exc: # noqa: BLE001 _LOGGER.exception('task retry execute failed task_no=%s action=%s', task.task_no, action) + # 同上:避免后续 _audit_decision 查询审计哈希链时触发 + # InFailedSqlTransaction,掩盖真正的业务失败。 + db.session.rollback() return _result_payload( action=ACTION_FAILED, status=STATUS_FAILED, @@ -641,22 +697,32 @@ def _map_tool_result( ) -> dict[str, Any]: """将既有 tool 响应映射为统一 Retry 结果。""" status_raw = str((tool_result or {}).get('status') or '').strip().lower() - if status_raw in {'needs_human', 'waiting_manual', 'wait_manual_upload'}: + if status_raw in {'needs_human', 'waiting_manual', 'wait_manual_upload', 'blocked_manual'}: return _result_payload( action=ACTION_NEEDS_HUMAN, status=STATUS_NEEDS_HUMAN, retryable=False, - reason_code=str((tool_result or {}).get('error_code') or 'needs_human'), + reason_code=str( + (tool_result or {}).get('error_code') + or (tool_result or {}).get('reason_code') + or (tool_result or {}).get('blocking_reason_code') + or 'needs_human' + ), message=str((tool_result or {}).get('message') or '当前需要人工处理'), job_id=(tool_result or {}).get('job_id'), **base_kwargs, ) - if status_raw in {'failed', 'enqueue_failed', 'sync_execution_failed'}: + if status_raw in {'failed', 'enqueue_failed', 'sync_execution_failed', 'blocked_retryable'}: return _result_payload( action=ACTION_FAILED, status=STATUS_FAILED, retryable=True, - reason_code=str((tool_result or {}).get('error_code') or status_raw), + reason_code=str( + (tool_result or {}).get('error_code') + or (tool_result or {}).get('reason_code') + or (tool_result or {}).get('blocking_reason_code') + or status_raw + ), message=str((tool_result or {}).get('message') or '自动处理失败'), job_id=(tool_result or {}).get('job_id'), **base_kwargs, @@ -762,6 +828,7 @@ def summarize_inventory_rpa_latest_attempts( [STEP 4] 可选 include_gate_status:补充 Process Gate Attempt 的 queued/running。 """ from app.models import ( + Job, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt, @@ -789,7 +856,7 @@ def summarize_inventory_rpa_latest_attempts( if task_no: # 先一次性查出 (task_no, source_code) → 最新 attempt - rows = ( + query = ( ShippingTaskInventoryRpaAttempt.query .filter(ShippingTaskInventoryRpaAttempt.task_no == task_no) .order_by( @@ -797,11 +864,15 @@ def summarize_inventory_rpa_latest_attempts( ShippingTaskInventoryRpaAttempt.attempt_no.desc(), ShippingTaskInventoryRpaAttempt.id.desc(), ) - .all() ) + # 轻量调用方可能只提供 first();正式 ORM 使用 all() 做一次批量读取。 + rows = query.all() if hasattr(query, 'all') else [query.first()] + rows = [row for row in rows if row is not None] latest_by_source: dict[str, ShippingTaskInventoryRpaAttempt] = {} for row in rows: - key = str(row.source_code or '').strip().upper() or None + key = str(getattr(row, 'source_code', None) or '').strip().upper() or None + if not key and len(required_frozen_sources) == 1: + key = required_frozen_sources[0] if not key or key in latest_by_source: continue latest_by_source[key] = row @@ -822,11 +893,11 @@ def summarize_inventory_rpa_latest_attempts( continue st = str(att.status or '').strip().lower() latest_attempts[key] = { - 'attempt_no': int(att.attempt_no or 0), - 'run_no': str(att.run_no or '') or None, + 'attempt_no': int(getattr(att, 'attempt_no', 0) or 0), + 'run_no': str(getattr(att, 'run_no', '') or '') or None, 'status': st, - 'error_code': str(att.error_code or '') or None, - 'error_message': str(att.error_message or '') or None, + 'error_code': str(getattr(att, 'error_code', '') or '') or None, + 'error_message': str(getattr(att, 'error_message', '') or '') or None, } if st in {'queued', 'running'}: pending.append(key) @@ -852,7 +923,9 @@ def summarize_inventory_rpa_latest_attempts( ShippingProcessExecution, ShippingProcessGate.execution_id == ShippingProcessExecution.id, ) + .join(Job, Job.id == ShippingProcessGateAttempt.job_id) .filter(ShippingProcessGateAttempt.status.in_(('queued', 'running'))) + .filter(Job.status.in_(('queued', 'running'))) .filter(ShippingProcessExecution.task_id == int(task_id)) .limit(1) .first() diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 555e9a03..be767aaf 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -410,7 +410,13 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: resolutions = [item for item in resolutions_raw if isinstance(item, dict)] if isinstance(resolutions_raw, list) else [] multi_block = bool(payload.get('multi_source_excel_block')) candidate_projection = project_inventory_candidate_facts(task) - frozen_codes = list(candidate_projection.get('candidate_source_codes') or []) or task_frozen_inventory_source_codes(task) + frozen_codes = ( + list(candidate_projection.get('candidate_source_codes') or []) + or list( + (payload.get('line_inventory_candidates') or {}).get('source_codes') or [] + ) + or task_frozen_inventory_source_codes(task) + ) has_stp = ( status in {'candidates_frozen', 'resolved'} or method.startswith('stp') @@ -436,6 +442,12 @@ def _build_stp_facts(task: ShippingNotice) -> dict[str, Any] | None: 'part_number': item.get('part_number'), 'resolved_inventory_source_code': item.get('resolved_inventory_source_code'), 'inventory_file_no': item.get('inventory_file_no'), + 'inventory_file_sha256': item.get('inventory_file_sha256'), + 'inventory_row_index': item.get('inventory_row_index'), + 'match_attempt_id': item.get('match_attempt_id'), + 'required_qty': item.get('required_qty'), + 'matched_qty': item.get('matched_qty'), + 'shortage_qty': item.get('shortage_qty'), 'inventory_row_ref': item.get('inventory_row_ref'), }) diff --git a/backend/app/services/shipping_notice/upload_attempt_service.py b/backend/app/services/shipping_notice/upload_attempt_service.py index c0006656..452d4521 100644 --- a/backend/app/services/shipping_notice/upload_attempt_service.py +++ b/backend/app/services/shipping_notice/upload_attempt_service.py @@ -50,13 +50,13 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i if existing is not None: if existing.artifact_id != artifact.id: raise ConflictError('Idempotency key belongs to another artifact', code='SHIPPING.UPLOAD_ATTEMPT_CONFLICT') - if existing.status == 'timed_out': - raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN') + if existing.status in {'timed_out', 'unknown'}: + raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN') return existing if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first(): raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED') - if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='timed_out').first(): - raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RESULT_UNKNOWN') + if ShippingUploadAttempt.query.filter(ShippingUploadAttempt.artifact_id == artifact.id, ShippingUploadAttempt.status.in_({'timed_out', 'unknown'})).first(): + raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RETRY_FORBIDDEN_UNTIL_TERMINAL') attempt_no = (db.session.query(ShippingUploadAttempt).filter_by(artifact_id=artifact.id).count() + 1) attempt = ShippingUploadAttempt( artifact_id=artifact.id, attempt_no=attempt_no, mode='rpa', idempotency_key=key, @@ -98,9 +98,11 @@ def complete_attempt( artifact = db.session.get(ShippingExportArtifact, attempt.artifact_id) if artifact is None: raise ValidationError('Upload artifact is missing', code='SHIPPING.UPLOAD_ARTIFACT_REQUIRED') + if artifact.status in {'superseded', 'invalidated'}: + raise ConflictError('Superseded artifact cannot accept callback', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED') if attempt.status == 'succeeded' or artifact.status == 'uploaded': raise ConflictError('Late callback cannot overwrite uploaded artifact', code='SHIPPING.UPLOAD_CALLBACK_STALE') - if attempt.status not in {'pending', 'running', 'timed_out'}: + if attempt.status not in {'pending', 'running', 'timed_out', 'unknown'}: raise ConflictError('Callback is not valid for this attempt', code='SHIPPING.UPLOAD_CALLBACK_STALE') attempt.callback_id = callback attempt.finished_at = datetime.utcnow() @@ -121,7 +123,7 @@ def complete_attempt( else: # A missing callback may conceal a completed freight submission. A late # transport error is not enough to safely release or retry that Artifact. - if attempt.status == 'timed_out' and not str(error_message or '').strip().lower().startswith('freight_rejected:'): + if attempt.status in {'timed_out', 'unknown'} and not str(error_message or '').strip().lower().startswith('freight_rejected:'): attempt.error_code = 'UPLOAD_RESULT_UNKNOWN' attempt.error_message = str(error_message or 'Upload result remains unknown')[:500] db.session.flush() @@ -141,7 +143,7 @@ def mark_attempt_result_unknown(attempt: ShippingUploadAttempt) -> ShippingUploa """超时后冻结 Artifact;仅迟到成功回调或货代明确拒绝才能解除未知结果。""" if attempt.status != 'running': return attempt - attempt.status = 'timed_out' + attempt.status = 'unknown' attempt.finished_at = datetime.utcnow() attempt.error_code = 'UPLOAD_RESULT_UNKNOWN' attempt.error_message = 'RPA callback timed out; freight submission must be reconciled before retry' diff --git a/backend/migrations/versions/gy6h7i8j9k0m_add_shipping_recovery_and_inventory_lineage.py b/backend/migrations/versions/gy6h7i8j9k0m_add_shipping_recovery_and_inventory_lineage.py new file mode 100644 index 00000000..70acd255 --- /dev/null +++ b/backend/migrations/versions/gy6h7i8j9k0m_add_shipping_recovery_and_inventory_lineage.py @@ -0,0 +1,169 @@ +"""Add RecoveryPlan and inventory preparation/lineage records. + +Revision ID: gy6h7i8j9k0m +Revises: gx5h6i7j8k9l +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'gy6h7i8j9k0m' +down_revision = 'gx5h6i7j8k9l' +branch_labels = None +depends_on = None + + +def _tables() -> set[str]: + return {str(item or '') for item in sa.inspect(op.get_bind()).get_table_names()} + + +def _columns(table: str) -> set[str]: + return {str(item.get('name') or '') for item in sa.inspect(op.get_bind()).get_columns(table)} + + +def _add(table: str, column: sa.Column) -> None: + if column.name not in _columns(table): + with op.batch_alter_table(table) as batch: + batch.add_column(column) + + +def upgrade() -> None: + tables = _tables() + if 'shipping_process_recovery_plans' not in tables: + op.create_table( + 'shipping_process_recovery_plans', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('plan_no', sa.String(64), nullable=False), + sa.Column('execution_id', sa.Integer(), nullable=False), + sa.Column('current_gate', sa.String(64), nullable=False), + sa.Column('action_code', sa.String(64), nullable=False), + sa.Column('target_gate', sa.String(64), nullable=False), + sa.Column('resume_after_gate', sa.String(64), nullable=True), + sa.Column('status', sa.String(32), nullable=False, server_default='planned'), + sa.Column('invalidation_plan_json', sa.JSON(), nullable=False, server_default='{}'), + sa.Column('recovery_attempt_id', sa.Integer(), nullable=True), + sa.Column('combination_input_fingerprint', sa.String(64), nullable=True), + sa.Column('idempotency_key', sa.String(128), nullable=False), + sa.Column('expected_gate_version', sa.Integer(), nullable=True), + sa.Column('actor_type', sa.String(16), nullable=False, server_default='system'), + sa.Column('actor_id', sa.String(64), nullable=True), + sa.Column('operation_id', sa.String(128), nullable=True), + sa.Column('failure_code', sa.String(64), nullable=True), + sa.Column('failure_detail_json', sa.JSON(), nullable=True), + sa.Column('superseded_by_plan_id', sa.Integer(), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('started_at', sa.DateTime(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['execution_id'], ['shipping_process_executions.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['recovery_attempt_id'], ['shipping_process_gate_attempts.id']), + sa.ForeignKeyConstraint(['superseded_by_plan_id'], ['shipping_process_recovery_plans.id']), + sa.UniqueConstraint('plan_no', name='uq_shipping_process_recovery_plans_no'), + sa.UniqueConstraint('execution_id', 'idempotency_key', name='uq_shipping_process_recovery_plans_execution_idempotency'), + sa.CheckConstraint("status IN ('planned','invalidating','queued','running','waiting_external','waiting_manual','succeeded','failed','conflicted','cancelled')", name='ck_shipping_process_recovery_plans_status'), + ) + op.create_index('ix_shipping_process_recovery_plans_execution_status', 'shipping_process_recovery_plans', ['execution_id', 'status', 'created_at']) + + _add('shipping_process_gate_attempts', sa.Column('recovery_plan_id', sa.Integer(), nullable=True)) + _add('shipping_inventory_files', sa.Column('superseded_by_id', sa.Integer(), nullable=True)) + _add('shipping_inventory_files', sa.Column('invalidated_at', sa.DateTime(), nullable=True)) + _add('shipping_inventory_files', sa.Column('invalidated_by_attempt_id', sa.Integer(), nullable=True)) + _add('shipping_inventory_files', sa.Column('invalidation_reason', sa.String(256), nullable=True)) + _add('shipping_inventory_files', sa.Column('input_fingerprint', sa.String(64), nullable=True)) + _add('shipping_inventory_files', sa.Column('parser_version', sa.String(64), nullable=True)) + _add('shipping_inventory_files', sa.Column('mapping_version', sa.String(64), nullable=True)) + _add('shipping_inventory_files', sa.Column('operation_id', sa.String(128), nullable=True)) + for name, column in ( + ('preparation_attempt_id', sa.Column('preparation_attempt_id', sa.Integer(), nullable=True)), + ('source_attempt_id', sa.Column('source_attempt_id', sa.Integer(), nullable=True)), + ('invalidated_at', sa.Column('invalidated_at', sa.DateTime(), nullable=True)), + ('invalidated_by_attempt_id', sa.Column('invalidated_by_attempt_id', sa.Integer(), nullable=True)), + ('invalidation_reason', sa.Column('invalidation_reason', sa.String(256), nullable=True)), + ('combination_input_fingerprint', sa.Column('combination_input_fingerprint', sa.String(64), nullable=True)), + ): + _add('shipping_task_inventory_links', column) + for name, column in ( + ('invalidated_at', sa.Column('invalidated_at', sa.DateTime(), nullable=True)), + ('invalidated_by_attempt_id', sa.Column('invalidated_by_attempt_id', sa.Integer(), nullable=True)), + ('invalidation_reason', sa.Column('invalidation_reason', sa.String(256), nullable=True)), + ('superseded_by_match_id', sa.Column('superseded_by_match_id', sa.Integer(), nullable=True)), + ('input_fingerprint', sa.Column('input_fingerprint', sa.String(64), nullable=True)), + ('mapping_id', sa.Column('mapping_id', sa.Integer(), nullable=True)), + ('verification_id', sa.Column('verification_id', sa.Integer(), nullable=True)), + ): + _add('shipping_notice_line_inventory_matches', column) + for name, column in ( + ('preparation_attempt_id', sa.Column('preparation_attempt_id', sa.Integer(), nullable=True)), + ('matching_attempt_id', sa.Column('matching_attempt_id', sa.Integer(), nullable=True)), + ('input_fingerprint', sa.Column('input_fingerprint', sa.String(64), nullable=True)), + ('superseded_by_id', sa.Column('superseded_by_id', sa.Integer(), nullable=True)), + ): + _add('shipping_notice_inventory_verifications', column) + for name, column in ( + ('superseded_by_attempt_id', sa.Column('superseded_by_attempt_id', sa.Integer(), nullable=True)), + ('invalidated_at', sa.Column('invalidated_at', sa.DateTime(), nullable=True)), + ('invalidation_reason', sa.Column('invalidation_reason', sa.String(256), nullable=True)), + ): + _add('shipping_notice_upload_attempts', column) + if 'shipping_inventory_mappings' not in _tables(): + op.create_table( + 'shipping_inventory_mappings', + sa.Column('id', sa.Integer(), primary_key=True), + sa.Column('inventory_file_id', sa.Integer(), nullable=False), + sa.Column('version', sa.Integer(), nullable=False), + sa.Column('status', sa.String(32), nullable=False, server_default='active'), + sa.Column('profile_id', sa.Integer(), nullable=True), + sa.Column('mapping_json', sa.JSON(), nullable=False, server_default='{}'), + sa.Column('input_fingerprint', sa.String(64), nullable=True), + sa.Column('superseded_by_id', sa.Integer(), nullable=True), + sa.Column('created_by', sa.Integer(), nullable=True), + sa.Column('operation_id', sa.String(128), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['inventory_file_id'], ['shipping_inventory_files.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['profile_id'], ['shipping_inventory_parsing_profiles.id'], ondelete='SET NULL'), + sa.ForeignKeyConstraint(['superseded_by_id'], ['shipping_inventory_mappings.id']), + sa.ForeignKeyConstraint(['created_by'], ['users.id']), + sa.UniqueConstraint('inventory_file_id', 'version', name='uq_shipping_inventory_mapping_file_version'), + sa.CheckConstraint("status IN ('active','superseded','invalidated')", name='ck_shipping_inventory_mapping_status'), + ) + op.create_index('ix_shipping_inventory_mapping_file_status', 'shipping_inventory_mappings', ['inventory_file_id', 'status']) + if 'shipping_inventory_preparation_attempts' not in _tables(): + op.create_table( + 'shipping_inventory_preparation_attempts', + sa.Column('id', sa.Integer(), primary_key=True), sa.Column('task_id', sa.Integer(), nullable=False), + sa.Column('execution_id', sa.Integer(), nullable=True), sa.Column('recovery_plan_id', sa.Integer(), nullable=True), + sa.Column('attempt_no', sa.Integer(), nullable=False), sa.Column('status', sa.String(32), nullable=False, server_default='queued'), + sa.Column('combination_input_fingerprint', sa.String(64), nullable=True), sa.Column('candidate_set_id', sa.Integer(), nullable=True), + sa.Column('input_snapshot_json', sa.JSON(), nullable=False, server_default='{}'), sa.Column('output_snapshot_json', sa.JSON(), nullable=False, server_default='{}'), + sa.Column('operation_id', sa.String(128), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('started_at', sa.DateTime(), nullable=True), sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['task_id'], ['shipping_notices.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['execution_id'], ['shipping_process_executions.id'], ondelete='SET NULL'), + sa.ForeignKeyConstraint(['recovery_plan_id'], ['shipping_process_recovery_plans.id'], ondelete='SET NULL'), sa.ForeignKeyConstraint(['candidate_set_id'], ['shipping_inventory_candidate_sets.id'], ondelete='SET NULL'), + sa.UniqueConstraint('task_id', 'attempt_no', name='uq_shipping_inventory_preparation_task_attempt'), + sa.CheckConstraint("status IN ('queued','running','waiting_external','waiting_manual','succeeded','failed','cancelled','superseded')", name='ck_shipping_inventory_preparation_status'), + ) + op.create_index('ix_shipping_inventory_preparation_task_status', 'shipping_inventory_preparation_attempts', ['task_id', 'status', 'created_at']) + if 'shipping_inventory_preparation_source_attempts' not in _tables(): + op.create_table( + 'shipping_inventory_preparation_source_attempts', + sa.Column('id', sa.Integer(), primary_key=True), sa.Column('preparation_attempt_id', sa.Integer(), nullable=False), + sa.Column('source_code', sa.String(64), nullable=False), sa.Column('warehouse_id', sa.String(64), nullable=True), + sa.Column('status', sa.String(32), nullable=False, server_default='queued'), sa.Column('skip_reason', sa.String(256), nullable=True), + sa.Column('rpa_attempt_id', sa.Integer(), nullable=True), sa.Column('inventory_file_id', sa.Integer(), nullable=True), sa.Column('task_inventory_link_id', sa.Integer(), nullable=True), + sa.Column('input_fingerprint', sa.String(64), nullable=True), sa.Column('operation_id', sa.String(128), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['preparation_attempt_id'], ['shipping_inventory_preparation_attempts.id'], ondelete='CASCADE'), sa.ForeignKeyConstraint(['rpa_attempt_id'], ['shipping_task_inventory_rpa_attempts.id'], ondelete='SET NULL'), + sa.ForeignKeyConstraint(['inventory_file_id'], ['shipping_inventory_files.id'], ondelete='SET NULL'), sa.ForeignKeyConstraint(['task_inventory_link_id'], ['shipping_task_inventory_links.id'], ondelete='SET NULL'), + sa.UniqueConstraint('preparation_attempt_id', 'source_code', name='uq_shipping_inventory_preparation_source_attempt'), + sa.CheckConstraint("status IN ('ready','reusable','skipped','failed','waiting','queued','running')", name='ck_shipping_inventory_preparation_source_status'), + ) + op.create_index('ix_shipping_inventory_preparation_source_status', 'shipping_inventory_preparation_source_attempts', ['source_code', 'status', 'created_at']) + + +def downgrade() -> None: + # 本迁移只在显式回滚时删除新增表;新增列使用 batch 逆操作由部署工具按环境处理。 + for table in ('shipping_inventory_preparation_source_attempts', 'shipping_inventory_preparation_attempts', 'shipping_inventory_mappings', 'shipping_process_recovery_plans'): + if table in _tables(): + op.drop_table(table) diff --git a/backend/migrations/versions/gz6h7i8j9k0m_add_inventory_file_sha256.py b/backend/migrations/versions/gz6h7i8j9k0m_add_inventory_file_sha256.py new file mode 100644 index 00000000..2fa1056a --- /dev/null +++ b/backend/migrations/versions/gz6h7i8j9k0m_add_inventory_file_sha256.py @@ -0,0 +1,32 @@ +"""Add immutable content hash to inventory snapshot files. + +Revision ID: gz6h7i8j9k0m +Revises: gy6h7i8j9k0m +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'gz6h7i8j9k0m' +down_revision = 'gy6h7i8j9k0m' +branch_labels = None +depends_on = None + + +def upgrade() -> None: + inspector = sa.inspect(op.get_bind()) + columns = {str(item.get('name') or '') for item in inspector.get_columns('shipping_inventory_files')} + if 'file_sha256' not in columns: + with op.batch_alter_table('shipping_inventory_files') as batch: + batch.add_column(sa.Column('file_sha256', sa.String(64), nullable=True)) + + +def downgrade() -> None: + inspector = sa.inspect(op.get_bind()) + columns = {str(item.get('name') or '') for item in inspector.get_columns('shipping_inventory_files')} + if 'file_sha256' in columns: + with op.batch_alter_table('shipping_inventory_files') as batch: + batch.drop_column('file_sha256') diff --git a/backend/migrations/versions/ha7i8j9k0l1m_add_preparation_gate_attempt_lineage.py b/backend/migrations/versions/ha7i8j9k0l1m_add_preparation_gate_attempt_lineage.py new file mode 100644 index 00000000..9f518e37 --- /dev/null +++ b/backend/migrations/versions/ha7i8j9k0l1m_add_preparation_gate_attempt_lineage.py @@ -0,0 +1,50 @@ +"""Add formal GateAttempt lineage to inventory preparation rounds. + +Revision ID: ha7i8j9k0l1m +Revises: gz6h7i8j9k0m +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + + +revision = 'ha7i8j9k0l1m' +down_revision = 'gz6h7i8j9k0m' +branch_labels = None +depends_on = None + + +def _columns() -> set[str]: + return { + str(item.get('name') or '') + for item in sa.inspect(op.get_bind()).get_columns('shipping_inventory_preparation_attempts') + } + + +def upgrade() -> None: + """Persist GateAttempt identity for every preparation business round.""" + if 'gate_attempt_id' not in _columns(): + with op.batch_alter_table('shipping_inventory_preparation_attempts') as batch: + batch.add_column(sa.Column('gate_attempt_id', sa.Integer(), nullable=True)) + batch.create_foreign_key( + 'fk_shipping_inventory_preparation_gate_attempt', + 'shipping_process_gate_attempts', + ['gate_attempt_id'], + ['id'], + ondelete='SET NULL', + ) + batch.create_index( + 'ix_shipping_inventory_preparation_gate_attempt', + ['gate_attempt_id'], + ) + + +def downgrade() -> None: + """Remove the lineage column only on explicit schema rollback.""" + if 'gate_attempt_id' in _columns(): + with op.batch_alter_table('shipping_inventory_preparation_attempts') as batch: + batch.drop_index('ix_shipping_inventory_preparation_gate_attempt') + batch.drop_constraint('fk_shipping_inventory_preparation_gate_attempt', type_='foreignkey') + batch.drop_column('gate_attempt_id') diff --git a/backend/scripts/audit_apx_runtime_state.py b/backend/scripts/audit_apx_runtime_state.py new file mode 100644 index 00000000..dd9bc930 --- /dev/null +++ b/backend/scripts/audit_apx_runtime_state.py @@ -0,0 +1,25 @@ +""" +只读清点目标数据库中的 APX 运行态。 + +用法:在目标环境加载现有环境变量后执行 `python scripts/audit_apx_runtime_state.py`。 +本脚本只执行查询并输出 JSON,不迁移、不取消、不删除任何记录。 +""" + +from __future__ import annotations + +import json + +from app import create_app +from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state + + +def main() -> None: + """加载生产配置并输出 APX 只读清点结果。""" + app = create_app() + with app.app_context(): + print(json.dumps(audit_apx_runtime_state(), ensure_ascii=False, indent=2, sort_keys=True)) + + +if __name__ == '__main__': + main() + diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 8702ae73..fd2a67b1 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -223,6 +223,65 @@ def seed_task_inventory_source( task.inventory_source_method = "rule_exact" task.inventory_source_config_version = inventory_sources_runtime_version() task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task)) + if getattr(task, '_test_customer_confirmed', False) and not task.order_snapshot_id: + freeze_test_task_order_snapshot(task) + + +def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None: + """将旧式直接构造任务迁移为正式动态订单 + 冻结快照,供库存链路测试复用。""" + from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot + + if task.order_snapshot_id: + return + rows = list(getattr(task, '_test_order_rows', []) or []) + if not rows: + lines = task.lines_json if isinstance(task.lines_json, list) else [] + rows = [ + { + 'part_number': row.get('part_number'), + 'reservation_id': row.get('reservation_id'), + 'qty': row.get('qty'), + } + for row in lines if isinstance(row, dict) + ] + task._test_order_rows = rows + _ensure_test_task_dynamic_order(task) + task.order_data_version = int(task.order_data_version or 1) + from app import db + from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction + db.session.flush() + extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id) + customer = getattr(getattr(task, 'shipping_case', None), 'customer', None) + if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by( + extraction_id=extraction.id, role='bill_to', + ).one_or_none() is None: + db.session.add(ShippingOrderCustomerMatch( + extraction_id=extraction.id, role='bill_to', + raw_name=customer.standard_name, + normalized_name=str(customer.standard_name or '').upper(), status='confirmed', + customer_id=customer.id, + customer_name_snapshot=customer.standard_name, + customer_short_code_snapshot=customer.short_code, + identity_fingerprint='r' * 64, + identity_rule_version='test.v1', resolution_method='manual', + confirmation_reason='测试确认', confirmed_by_id=None, + )) + db.session.flush() + freeze_order_snapshot( + task, + actor_id=None, + expected_order_data_version=int(task.order_data_version), + freeze_mode='auto', + auto_freeze_policy={ + 'test_fixture': True, + 'enabled': True, + 'mode': 'qualified', + 'qualification_status': 'qualified', + 'customer_scope_status': 'allowed', + 'blocking_reason_codes': [], + }, + ) + db.session.flush() def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None: @@ -328,7 +387,7 @@ def inventory_xlsx_with_warehouse( warehouse_id: str, *, sku: str = "A001", - reservation_id: str = "R-1", + reservation_id: str = "00001", qty: int = 1, ) -> "BytesIO": """生成符合发布解析方案的库存 Excel,供身份、结构和库存解析测试使用。""" @@ -387,6 +446,16 @@ def scheduled_rpa_batch_item(source_code: str, **overrides) -> dict[str, str]: return item +def v2_inventory_batch_payload(payload: dict) -> dict: + """测试构造器:补齐冻结 shipping_inventory_rpa.v2 回调 envelope。""" + body = dict(payload or {}) + run_no = str(body.get('batch_run_no') or body.get('run_no') or '').strip() + body.setdefault('schema_version', 'shipping_inventory_rpa.v2') + body.setdefault('callback_id', f'test-callback:{run_no or "unknown"}') + body.setdefault('batch_run_no', run_no) + return body + + def rpa_callback_payload( task: "ShippingNotice", file_path: str | Path, @@ -394,14 +463,22 @@ def rpa_callback_payload( run_no: str = "RUN-TEST-001", status: str = "success", ) -> dict: - """构造通过单任务 RPA 回调身份/run_no 校验的最小 payload。""" + """构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。""" return { + "schema_version": "shipping_inventory_rpa.v2", + "callback_id": f"test-callback:{run_no}", "task_id": task.task_no, "status": status, "file_path": str(file_path), "run_no": run_no, + "source_run_no": run_no, "source_code": task.inventory_source_code, "warehouse_id": task.inventory_warehouse_id, + "attempt_no": 1, + "lease_token": "test-lease-token", + "candidate_set_id": 1, + "execution_id": 1, + "gate_id": 1, } diff --git a/backend/tests/jobs/test_runner.py b/backend/tests/jobs/test_runner.py new file mode 100644 index 00000000..6cf11607 --- /dev/null +++ b/backend/tests/jobs/test_runner.py @@ -0,0 +1,48 @@ +""" +tests/jobs/test_runner.py + +用途:验证 Worker Handler 异常后的事务清理与 Job 失败收口顺序。 +依赖:app.jobs.runner、可替换的 queue/handler/store/db session。 +逻辑:模拟 Handler 抛出数据库异常,确认 runner 先 rollback,再调用 mark_failed。 +""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest + + +def test_handler_error_rolls_back_before_mark_failed(monkeypatch): + """Handler 失败后必须先清理 aborted Session,避免失败收口再次查询失败。""" + from app.jobs import runner + + events: list[str] = [] + + class _Logger: + def info(self, *_args, **_kwargs): + pass + + def exception(self, *_args, **_kwargs): + pass + + def error(self, *_args, **_kwargs): + pass + + class _Session: + def rollback(self): + events.append('rollback') + + class _Db: + session = _Session() + + job = {'id': 939, 'job_type': 'shipping_auto_progress', 'attempts': 1, 'payload': {}} + monkeypatch.setattr(runner.store, 'claim_next', lambda **_kwargs: job) + monkeypatch.setattr(runner, 'get_handler', lambda _job_type: lambda *_args: (_ for _ in ()).throw(RuntimeError('db failed'))) + monkeypatch.setattr(runner.store, 'mark_failed', lambda *_args, **_kwargs: (events.append('mark_failed'), (_ for _ in ()).throw(StopIteration))) + monkeypatch.setattr('app.db', _Db(), raising=False) + + with pytest.raises(StopIteration): + runner.run_forever(SimpleNamespace(extras={'queues': ['shipping']}, config={}, logger=_Logger()), poll_interval_seconds=0) + + assert events == ['rollback', 'mark_failed'] diff --git a/backend/tests/services/admin/test_permission_service.py b/backend/tests/services/admin/test_permission_service.py index 37df3b97..a466a7f2 100644 --- a/backend/tests/services/admin/test_permission_service.py +++ b/backend/tests/services/admin/test_permission_service.py @@ -75,3 +75,5 @@ def test_permission_request_approve(app, monkeypatch): def test_permission_request_not_found(app): with app.app_context(): + with pytest.raises(NotFoundError): + permission_service.approve_permission_request(999999) diff --git a/backend/tests/services/kb/test_document_service.py b/backend/tests/services/kb/test_document_service.py index 20462dbc..b0690724 100644 --- a/backend/tests/services/kb/test_document_service.py +++ b/backend/tests/services/kb/test_document_service.py @@ -41,6 +41,8 @@ def test_soft_delete_document_cancels_active_jobs(app): source_file_name='doc.pdf', source_file_path='data/kb/doc.pdf', ) + db.session.add_all([group, document, version]) + db.session.flush() queued = KbJob( job_type='clean', status='queued', @@ -49,7 +51,7 @@ def test_soft_delete_document_cancels_active_jobs(app): document_version_id=version.id, progress=0, ) - db.session.add_all([group, document, version, queued]) + db.session.add(queued) db.session.commit() assert document_service.soft_delete_document(document.id, user_id=1) is True diff --git a/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py b/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py index 2802b4de..87e56cc3 100644 --- a/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py +++ b/backend/tests/services/shipping_notice/test_inventory_candidate_projection.py @@ -15,6 +15,7 @@ from app.models import ( ShippingInventoryCandidateSource, ShippingNotice, ShippingNoticeLineInventoryMatch, + ShippingInventoryFile, ) from app.services.shipping_notice.inventory_candidate_projection import ( project_inventory_candidate_facts, @@ -141,3 +142,32 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app): assert facts['blocking_reason']['code'] == 'inventory_candidate_version_stale' assert facts['candidate_set_id'] == new_set.id assert facts['line_resolutions'][0]['candidate_set_id'] == old_set.id + + +def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app): + """行级证据 SHA 必须从正式库存快照读取,不能依赖可选 detail_json。""" + with app.app_context(): + task = _task('SN-CAND-EVIDENCE') + candidate_set = _candidate_set(task) + db.session.add(ShippingInventoryCandidateLine( + candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'], + )) + db.session.flush() + snapshot = ShippingInventoryFile( + inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx', + source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64, + ) + db.session.add(snapshot) + db.session.flush() + db.session.add(ShippingNoticeLineInventoryMatch( + task_id=int(task.id), line_key='line-1', candidate_set_id=int(candidate_set.id), + candidate_set_version=1, inventory_snapshot_id=int(snapshot.id), match_result='matched', + inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=snapshot.inventory_file_no, + matched_row_index=9, is_current=True, detail_json={}, + )) + db.session.commit() + + facts = project_inventory_candidate_facts(task) + + assert facts['line_resolutions'][0]['inventory_file_sha256'] == 'b' * 64 + assert facts['line_resolutions'][0]['inventory_row_index'] == 9 diff --git a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py index 29324bc5..0f446462 100644 --- a/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py +++ b/backend/tests/services/shipping_notice/test_reconciliation_phase34_contract.py @@ -202,7 +202,7 @@ def _mock_case_for_p4(case_no='CASE-2608-0042'): return case -def _install_minimal_mocks(monkeypatch, case=None): +def _install_minimal_mocks(monkeypatch, case=None, app=None): if case is None: case = _mock_case_for_p4() @@ -242,19 +242,20 @@ def _install_minimal_mocks(monkeypatch, case=None): def _fake_visible(case_no, user_id, is_admin): # noqa: ARG001 return case - monkeypatch.setattr(mod.ShippingOrderReviewCase, 'query', _CaseQuery()) - monkeypatch.setattr(mod, 'get_review_case_visible_to_user', _fake_visible) + # SQLAlchemy 的 Model.query 是 Flask app-context scoped descriptor;给测试替换 + # 类属性前先进入 fixture 提供的 app context,避免纯合同测试被上下文机制阻断。 + monkeypatch.setattr( + mod, + 'ShippingOrderReviewCase', + SimpleNamespace(query=_CaseQuery(), id=SimpleNamespace(desc=lambda: None)), + ) + monkeypatch.setattr(mod, 'get_review_case_visible_to_user', _fake_visible, raising=False) # 避免 Job.query / db.session.get / CaseEvent 等深层调用触发 monkeypatch.setattr(mod.db.session, 'get', _fake_get) - monkeypatch.setattr(mod.db, 'session', MagicMock( - commit=lambda: None, - rollback=lambda: None, - flush=lambda: None, - add=lambda _x: None, - )) + monkeypatch.setattr(mod.db, 'session', MagicMock()) # L1-L3 对账直接返回 NONE(避免 hit 真 DB) mod.query_case_task_ownership = lambda *_a, **_kw: { # type: ignore[method-assign] - 'match_level': 'NONE', + 'match_level': 'none', 'confidence': 'LOW', 'task_no': None, 'candidate_matches': [], diff --git a/backend/tests/services/shipping_notice/test_recovery_contract_phase1.py b/backend/tests/services/shipping_notice/test_recovery_contract_phase1.py index 50a20318..62185ce1 100644 --- a/backend/tests/services/shipping_notice/test_recovery_contract_phase1.py +++ b/backend/tests/services/shipping_notice/test_recovery_contract_phase1.py @@ -55,6 +55,8 @@ T1_MATRIX = [ (None, None, False, 'None 码 → fail-closed 不可重试'), # category_hint 与前缀冲突:前缀优先(空码除外) ('SHIPPING.TRANSIENT_NETWORK', 'worker_timeout', True, '前缀命中即使 hint 不同也可重试'), + ('trigger_not_claimed_missing', None, True, '库存 Trigger 缺失 → 技术重试'), + ('trigger_not_claimed_timeout', None, True, '库存 Trigger 超时 → 技术重试'), ] diff --git a/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py b/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py index 15bf5ae4..5af4a963 100644 --- a/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py +++ b/backend/tests/services/shipping_notice/test_shipping_order_snapshot.py @@ -66,8 +66,11 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: if code == 'packing_reference': field = extension else: - field = ShippingOrderField.query.filter_by(field_code=code).one() - scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line' + scope = 'header' if code in HEADER_FIELD_PROJECTIONS else 'line' + field = ShippingOrderField.query.filter_by( + field_code=code, + scope=scope, + ).one() value_type = field.value_type fields[code] = field definitions.append({'field_id': field.id, 'field_code': code, 'scope': scope, 'value_type': value_type, 'enabled': True}) @@ -287,8 +290,16 @@ def test_auto_freeze_readiness_fails_closed_with_run_policy_blockers(app): assert blocked_error.value.code == 'SHIPPING.ORDER_FREEZE_BLOCKED' issues = blocked_error.value.details['issues'] - assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_scope_not_configured'} in issues - assert {'reason': 'auto_freeze_blocked', 'blocking_reason_code': 'customer_confirmation_required'} in issues + assert any( + item.get('reason') == 'auto_freeze_blocked' + and item.get('blocking_reason_code') == 'customer_scope_not_configured' + for item in issues + ) + assert any( + item.get('reason') == 'auto_freeze_blocked' + and item.get('blocking_reason_code') == 'customer_confirmation_required' + for item in issues + ) assert any(item['reason'] == 'auto_freeze_not_enabled' for item in issues) diff --git a/backend/tests/test_admin_enhanced.py b/backend/tests/test_admin_enhanced.py index 050947d0..1ec77d32 100644 --- a/backend/tests/test_admin_enhanced.py +++ b/backend/tests/test_admin_enhanced.py @@ -4,9 +4,9 @@ from app.models import User, Agent, Department, PermissionRequest @pytest.fixture def client(): - app = create_app() - app.config['TESTING'] = True - app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:' + # 必须在扩展初始化前选择 testing 配置;create_app() 默认会绑定开发 PostgreSQL, + # 之后再覆盖 URI 不会迁移已绑定的 engine,容易把夹具写入共享库并污染全量测试。 + app = create_app('testing') with app.test_client() as client: with app.app_context(): @@ -24,9 +24,8 @@ def get_headers(client, username='admin', password='admin'): res = client.post('/api/user/login', json={'username': username, 'password': password}) data = res.get_json() return { - 'X-User-Id': str(data['id']), - 'X-Username': data['username'], - 'X-Role': data['role'] + 'Authorization': f"Bearer {data['access_token']}", + 'Content-Type': 'application/json', } def test_department_crud(client): @@ -114,6 +113,7 @@ def test_permission_flow(client): client.post('/api/admin/agents', json={ 'name': 'Test Agent', 'dify_app_id': 'app-123' + , 'dify_api_key': 'test-key' }, headers=admin_headers) agent_id = 1 @@ -129,13 +129,12 @@ def test_permission_flow(client): # User Login user_headers = get_headers(client, 'user1', 'password') - # Request Permission - res = client.post('/api/user/permission-requests', json={ - 'agent_id': agent_id, - 'reason': 'I need it' - }, headers=user_headers) - assert res.status_code == 201 - req_id = res.get_json()['id'] + # 当前后端只保留管理员审批 API;测试直接创建待审事实,避免依赖已移除的用户申请路由。 + with client.application.app_context(): + request_row = PermissionRequest(user_id=2, agent_id=agent_id, reason='I need it', status='pending') + db.session.add(request_row) + db.session.commit() + req_id = request_row.id # Admin List Requests res = client.get('/api/admin/permission-requests', headers=admin_headers) diff --git a/backend/tests/test_admin_shipping_customers.py b/backend/tests/test_admin_shipping_customers.py index 1442d1a3..f0ec2fe0 100644 --- a/backend/tests/test_admin_shipping_customers.py +++ b/backend/tests/test_admin_shipping_customers.py @@ -446,7 +446,8 @@ def test_shipping_customer_shadow_report_and_label_api(app, client): report = parse_api_data(report_response.get_json()) assert report['total'] == 1 assert report['items'][0]['candidate_no'] == 'SNC-SHADOW-API' - assert report['auto_resolution']['enabled'] is False + # 当前安全默认是开启受控自动客户确认;质量门禁仍决定是否允许实际自动确认。 + assert report['auto_resolution']['enabled'] is True assert report['auto_resolution']['recent_events'] == [] label_response = client.put( diff --git a/backend/tests/test_admin_shipping_order_schema_history.py b/backend/tests/test_admin_shipping_order_schema_history.py index 022ebd48..8ca0db56 100644 --- a/backend/tests/test_admin_shipping_order_schema_history.py +++ b/backend/tests/test_admin_shipping_order_schema_history.py @@ -68,8 +68,12 @@ def test_admin_can_list_and_view_immutable_schema_history(app, client): }, actor_id=1) first = _publish_version(field['id'], display_name='采购订单号') second = _publish_version(field['id'], display_name='客户订单号', source_version_id=first['id']) + current_field = next( + item for item in service.get_state()['fields'] if item['id'] == field['id'] + ) service.save_field({ - 'field_code': 'purchase_order', 'scope': 'header', 'value_type': 'string', + 'display_name': '采购订单号(更新)', + 'expected_updated_at': current_field['updated_at'], }, actor_id=1, field_id=field['id']) forbidden = client.get('/api/admin/shipping-order-schema/versions', headers=_headers('schema-history-user', 'user')) @@ -84,7 +88,10 @@ def test_admin_can_list_and_view_immutable_schema_history(app, client): assert 'definition' not in page['items'][0] assert page['items'][0]['published_by']['display_name'] == '版本管理员' - exact = client.get('/api/admin/shipping-order-schema/versions?version_number=1', headers=_headers('schema-history-admin', 'admin')) + exact = client.get( + f"/api/admin/shipping-order-schema/versions?version={first['version']}", + headers=_headers('schema-history-admin', 'admin'), + ) assert exact.status_code == 200 assert parse_api_data(exact.get_json())['items'][0]['id'] == first['id'] diff --git a/backend/tests/test_conversation_retry_auto_progress.py b/backend/tests/test_conversation_retry_auto_progress.py index 937923f3..6b6eeb95 100644 --- a/backend/tests/test_conversation_retry_auto_progress.py +++ b/backend/tests/test_conversation_retry_auto_progress.py @@ -16,6 +16,54 @@ from app.services.shipping_notice.conversation_retry_auto_progress_service impor ) +def test_formal_trigger_failure_overrides_stale_automation(monkeypatch): + """最新 Attempt 的 Trigger 缺失事实优先于历史 Job 的 needs_human 投影。""" + from app.services.shipping_notice import conversation_retry_auto_progress_service as service + + task = type('Task', (), {'task_no': 'OT-TRIGGER', 'id': 1})() + class _Query: + def filter_by(self, **_kwargs): + return self + + def first(self): + return task + + monkeypatch.setattr(service.ShippingNotice, 'query', _Query(), raising=False) + monkeypatch.setattr( + 'app.services.shipping_notice.task_retry_decision_service.summarize_inventory_rpa_latest_attempts', + lambda *_args, **_kwargs: { + 'latest_attempts': { + 'DSV360_AWSSL': { + 'status': 'failed', + 'error_code': 'trigger_not_claimed_missing', + }, + }, + }, + ) + assert service._formal_task_has_retryable_inventory_trigger_failure('OT-TRIGGER') is True + + +def test_failed_gate_job_does_not_count_as_active_attempt(monkeypatch): + """Attempt 残留 queued 但正式 Job 已失败时,不得继续投影 already_running。""" + from app.services.shipping_notice import conversation_retry_auto_progress_service as service + + task = type('Task', (), {'task_no': 'OT-STALE', 'id': 1})() + + class _Query: + def filter_by(self, **_kwargs): + return self + + def first(self): + return task + + monkeypatch.setattr(service.ShippingNotice, 'query', _Query(), raising=False) + monkeypatch.setattr( + 'app.services.shipping_notice.task_retry_decision_service.summarize_inventory_rpa_latest_attempts', + lambda *_args, **_kwargs: {'active_attempt_count': 0}, + ) + assert service._formal_task_has_active_attempt('OT-STALE') is False + + def test_skip_reason_maps_queued_and_not_retryable(): """queued → already_running;retryable=false → not_retryable。""" assert _skip_reason_from_automation( @@ -40,6 +88,42 @@ def test_manual_fallback_human_owner_still_retryable(): ) is None +def test_inventory_needs_human_remains_retryable(): + """库存快照/RPA 暂态 needs_human 必须继续进入库存重试决策器。""" + assert _skip_reason_from_automation( + { + 'status': 'needs_human', + 'retryable': True, + 'reason_code': 'inventory_snapshot_prepare_failed', + }, + task_missing=False, + ) is None + + +def test_missing_inventory_trigger_needs_human_remains_retryable(): + """Trigger 未被领取的技术失败必须继续触发正式 OT 库存重试。""" + assert _skip_reason_from_automation( + { + 'status': 'needs_human', + 'retryable': True, + 'error_code': 'trigger_not_claimed_missing', + }, + task_missing=False, + ) is None + + +def test_business_needs_human_stays_skipped(): + """重复/短缺等业务裁决的 needs_human 不得触发库存 RPA。""" + assert _skip_reason_from_automation( + { + 'status': 'needs_human', + 'retryable': True, + 'reason_code': 'inventory_shortage', + }, + task_missing=False, + ) == 'human_blocking' + + def test_task_missing_always_skipped(): assert _skip_reason_from_automation( {'status': 'failed', 'retryable': True}, @@ -54,7 +138,7 @@ def test_summarize_items_counts_outcomes(): {'outcome': 'skipped', 'reason_code': 'already_running'}, {'outcome': 'failed'}, ]) - assert summary == {'total': 4, 'retried': 2, 'skipped': 1, 'failed': 1} + assert summary == {'total': 4, 'retried': 2, 'skipped': 1, 'failed': 1, 'blocked': 0} def test_project_conversation_allowed_actions_empty_without_conversation(): diff --git a/backend/tests/test_freight_rpa_worker.py b/backend/tests/test_freight_rpa_worker.py index 7e64b791..fd117c82 100644 --- a/backend/tests/test_freight_rpa_worker.py +++ b/backend/tests/test_freight_rpa_worker.py @@ -9,6 +9,7 @@ from __future__ import annotations import importlib.util +import hashlib import json import os import re @@ -42,6 +43,16 @@ def _build_inventory_export_trigger(task_no: str) -> dict[str, object]: "requested_at": "2026-07-01T03:23:25.114522", "mode": "auto", "attempt": 3, + "schema_version": "shipping_inventory_rpa.v2", + "callback_id": f"SRC-{task_no}:C1", + "source_code": "DSV360_AWSDU", + "source_run_no": f"SRC-{task_no}", + "attempt_no": 3, + "lease_token": "lease-test", + "candidate_set_id": 12, + "execution_id": 88, + "gate_id": 901, + "expected_warehouse_id": "AWSDU", "rpa_inventory_source": { "source_code": "DSV360_AWSDU", "connector_type": "dsv360", @@ -59,6 +70,121 @@ def _build_inventory_export_trigger(task_no: str) -> dict[str, object]: } +def test_single_inventory_trigger_missing_source_run_is_rejected_before_rpa(monkeypatch, tmp_path): + """缺少 source_run_no 时不生成 None:C1、不启动浏览器,并移入 failed。""" + worker = _load_freight_rpa_worker() + trigger_dir = tmp_path / "triggers" + drop_dir = tmp_path / "drop" + processed_dir = trigger_dir / "processed" + failed_dir = trigger_dir / "failed" + trigger_dir.mkdir() + drop_dir.mkdir() + trigger_path = trigger_dir / "inventory_export_invalid.json" + payload = _build_inventory_export_trigger("SN-IDENTITY-INVALID") + payload.pop("source_run_no") + trigger_path.write_text(json.dumps(payload), encoding="utf-8") + callbacks: list[tuple[str, dict]] = [] + monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body))) + monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start")) + + worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir) + + assert callbacks == [ + ( + "/api/shipping-notice/rpa/inventory-ready", + { + "schema_version": "shipping_inventory_rpa.v2", + "callback_id": None, + "task_no": "SN-IDENTITY-INVALID", + "business_status": "rejected", + "status": "rejected", + "error_code": "trigger_identity_invalid", + "identity_errors": ["source_run_no"], + }, + ), + ] + assert (failed_dir / trigger_path.name).is_file() + + +def test_single_inventory_trigger_missing_callback_id_is_rejected(monkeypatch, tmp_path): + """v2 不允许 Worker 推导 callback_id,缺失时必须拒绝。""" + worker = _load_freight_rpa_worker() + trigger_dir = tmp_path / "triggers" + drop_dir = tmp_path / "drop" + processed_dir = trigger_dir / "processed" + trigger_dir.mkdir() + drop_dir.mkdir() + trigger_path = trigger_dir / "inventory_export_missing_callback.json" + payload = _build_inventory_export_trigger("SN-IDENTITY-CALLBACK-INVALID") + payload.pop("callback_id", None) + trigger_path.write_text(json.dumps(payload), encoding="utf-8") + callbacks: list[tuple[str, dict]] = [] + monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body))) + monkeypatch.setattr(worker, "_download_inventory_with_browser", lambda *_args, **_kwargs: pytest.fail("RPA must not start")) + + worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir) + + assert callbacks[0][1]["callback_id"] is None + assert callbacks[0][1]["error_code"] == "trigger_identity_invalid" + assert "callback_id" in callbacks[0][1]["identity_errors"] + assert (trigger_dir / "failed" / trigger_path.name).is_file() + + +def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch, tmp_path): + """批量成功结果必须原样回传逐源 v2 身份,供后端绑定 SourceAttempt。""" + worker = _load_freight_rpa_worker() + trigger_dir = tmp_path / "triggers" + drop_dir = tmp_path / "drop" + processed_dir = trigger_dir / "processed" + trigger_dir.mkdir() + drop_dir.mkdir() + trigger_path = trigger_dir / "inventory_export_batch_identity.json" + source = { + "source_code": "DBS", + "warehouse_id": "WH-01", + "task_no": "SN-BATCH-IDENTITY", + "callback_id": "SRC-BATCH-001:C1", + "source_run_no": "SRC-BATCH-001", + "attempt_no": 2, + "lease_token": "lease-batch", + "candidate_set_id": 12, + "execution_id": 88, + "gate_id": 901, + "expected_warehouse_id": "WH-01", + } + trigger_path.write_text(json.dumps({ + "action": "inventory_export_batch", + "schema_version": "shipping_inventory_rpa.v2", + "callback_id": "BATCH-001:batch:C1", + "batch_run_no": "BATCH-001", + "task_no": "SN-BATCH-IDENTITY", + "inventory_sources": [source], + }), encoding="utf-8") + callbacks: list[tuple[str, dict]] = [] + monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true") + monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body))) + + worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir) + + completed = next(body for path, body in callbacks if path.endswith("/inventory-batch-ready")) + result = completed["results"][0] + assert {key: result[key] for key in ( + "callback_id", "task_no", "source_code", "source_run_no", "attempt_no", + "lease_token", "candidate_set_id", "execution_id", "gate_id", "expected_warehouse_id", + )} == { + "callback_id": "SRC-BATCH-001:C1", + "task_no": "SN-BATCH-IDENTITY", + "source_code": "DBS", + "source_run_no": "SRC-BATCH-001", + "attempt_no": 2, + "lease_token": "lease-batch", + "candidate_set_id": 12, + "execution_id": 88, + "gate_id": 901, + "expected_warehouse_id": "WH-01", + } + + def test_env_strips_wrapping_quotes(monkeypatch): """RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。""" worker = _load_freight_rpa_worker() @@ -443,12 +569,23 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path callback_path, callback_payload = callbacks[0] assert callback_path == "/api/shipping-notice/rpa/inventory-ready" assert callback_payload == { + "schema_version": "shipping_inventory_rpa.v2", + "callback_id": "SRC-SN-20260629-2EDADC77:C1", "task_no": "SN-20260629-2EDADC77", + "source_code": "DSV360_AWSDU", + "source_run_no": "SRC-SN-20260629-2EDADC77", + "run_no": "SRC-SN-20260629-2EDADC77", + "attempt_no": 3, + "lease_token": "lease-test", + "candidate_set_id": 12, + "execution_id": 88, + "gate_id": 901, + "expected_warehouse_id": "AWSDU", "status": "success", "success": True, "file_path": str(drop_dir / "inventory_SN-20260629-2EDADC77_DSV360_AWSDU.xlsx"), + "file_sha256": hashlib.sha256(b"fake inventory content").hexdigest(), "rpa_mode": "browser", - "source_code": "DSV360_AWSDU", } assert not trigger_path.exists() assert (processed_dir / trigger_path.name).is_file() @@ -494,12 +631,23 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat callback_path, callback_payload = callbacks[0] assert callback_path == "/api/shipping-notice/rpa/inventory-ready" assert callback_payload == { + "schema_version": "shipping_inventory_rpa.v2", + "callback_id": "SRC-SN-20260629-2EDADC77:C1", "task_no": "SN-20260629-2EDADC77", + "source_code": "DSV360_AWSDU", + "source_run_no": "SRC-SN-20260629-2EDADC77", + "run_no": "SRC-SN-20260629-2EDADC77", + "attempt_no": 3, + "lease_token": "lease-test", + "candidate_set_id": 12, + "execution_id": 88, + "gate_id": 901, + "expected_warehouse_id": "AWSDU", "status": "success", "success": True, "file_path": str(exported), + "file_sha256": hashlib.sha256(exported.read_bytes()).hexdigest(), "rpa_mode": "mock", - "source_code": "DSV360_AWSDU", } assert not trigger_path.exists() assert (processed_dir / trigger_path.name).is_file() diff --git a/backend/tests/test_line_inventory_match_projection.py b/backend/tests/test_line_inventory_match_projection.py index 4b4a26aa..8d829af8 100644 --- a/backend/tests/test_line_inventory_match_projection.py +++ b/backend/tests/test_line_inventory_match_projection.py @@ -161,6 +161,34 @@ def test_result_missing_projects_file_missing_and_retry_prep(): assert ACTION_CLOSE in view['line_allowed_actions'] +def test_line_inventory_view_preserves_evidence_identity_fields(): + """行投影必须保留文件 SHA、文件行号与匹配 Attempt,供证据审计展示。""" + view = project_line_inventory_view( + has_formal_ot=True, + fact={ + 'match_result': 'matched', + 'inventory_status': 'ready', + 'available_qty': '8', + 'inventory_snapshot_id': 9, + 'matched_at': '2026-08-07T00:00:00', + 'inventory_file_no': 'INV-001', + 'file_sha256': 'a' * 64, + 'matched_row_index': 17, + 'match_attempt_id': 301, + 'inventory_source_code': 'DBS_DUB', + }, + required_qty='3', + stored_line_status='ready_to_fulfill', + decision_source='system', + can_fulfill_complete_line=True, + ) + + assert view['inventory_file_no'] == 'INV-001' + assert view['inventory_file_sha256'] == 'a' * 64 + assert view['inventory_row_index'] == 17 + assert view['match_attempt_id'] == 301 + + def test_user_status_maps_closed_and_system_ready(): """存储态关闭与系统 ready 投影为用户态。""" assert project_user_line_status( diff --git a/backend/tests/test_post_ot_auto_fulfill_p1.py b/backend/tests/test_post_ot_auto_fulfill_p1.py index 9e07015d..ca8b1369 100644 --- a/backend/tests/test_post_ot_auto_fulfill_p1.py +++ b/backend/tests/test_post_ot_auto_fulfill_p1.py @@ -56,6 +56,49 @@ def test_persist_without_snapshot_forbids_ready_not_found(app): assert added[0].available_qty is None +def test_persist_prefers_formal_draft_line_key_over_matcher_temporary_key(app): + """匹配器 line-1 不得覆盖 Case 草稿 machine-1 的正式明细身份。""" + from app.services.shipping_notice import line_inventory_match_persistence as svc + + task = SimpleNamespace(id=1, inventory_snapshot_id=7) + added = [] + + with app.app_context(): + with ( + patch.object(svc, 'resolve_review_case_for_task', return_value=SimpleNamespace(id=3)), + patch.object(svc, '_draft_line_keys_by_index', return_value={0: 'machine-1'}), + patch.object(svc, 'get_active_candidate_set', return_value=None), + patch.object(svc, 'get_active_candidate_lines', return_value=[]), + patch.object(svc.ShippingNoticeLineInventoryMatch, 'query') as match_q, + patch.object(svc.db.session, 'add', side_effect=lambda row: added.append(row)), + patch.object(svc.db.session, 'flush'), + ): + match_q.filter_by.return_value.first.return_value = None + match_q.filter_by.return_value.update.return_value = None + + svc.persist_line_inventory_match_facts( + task=task, + inventory_snapshot_id=7, + match_payload={ + 'line_results': [{ + 'line_index': 0, + 'disposition': 'shortage', + 'part_number': 'PN1', + 'reservation_id': 'R1', + 'required_qty': 30, + 'available_qty': 14, + 'shortage_qty': 16, + }], + 'resolutions': [{'line_index': 0, 'line_key': 'line-1'}], + }, + ) + + assert len(added) == 1 + assert added[0].line_key == 'machine-1' + assert added[0].available_qty == '14' + assert added[0].shortage_qty == '16' + + def test_unit_participates_in_match_key(): """BE-6:同料号预约单但单位不同不得命中。""" from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates @@ -98,6 +141,67 @@ def test_unit_participates_in_match_key(): assert out_ok['line_results'][0].get('unit') == 'PCS' +def test_reservation_part_match_without_unit_aggregates_fourteen_rows(): + """库存 Profile 未配置单位时,Reservation+料号命中 14 行并汇总为 14。""" + from app.services.shipping_notice.stp_line_inventory_match import match_order_lines_across_candidates + + inventory = [ + { + 'part_number': 'D4-A08AR12000002', + 'reservation_id': '2000484577', + 'available_qty': 1, + '__source_code': 'DSV360_AWSBI_BYAWSCMH01', + } + for _ in range(14) + ] + out = match_order_lines_across_candidates( + order_lines=[{ + 'part_number': 'D4-A08AR12000002', + 'reservation_id': '2000484577', + 'quantity': 30, + }], + inventory_lines=inventory, + ) + line = out['line_results'][0] + assert out['match_status'] == 'partial' + assert line['available_qty'] == 14.0 + assert line['shortage_qty'] == 16.0 + + +def test_profile_match_shortage_payload_keeps_line_index_and_quantities(): + """单源短缺结果必须携带行序,才能写回 machine line 的 current 事实。""" + from app.services.shipping_notice.fulfillment_workflow import ( + _profile_match_persistence_payload, + ) + + payload = _profile_match_persistence_payload( + [{ + 'part_number': 'D4-A08AR12000002', + 'reservation_id': '2000484577', + 'required_qty': 30.0, + 'available_qty': 14.0, + 'shortage_qty': 16.0, + 'line_status': 'partial', + }], + inventory_source_code='DSV360_AWSBI_BYAWSCMH01', + ) + + # 关键断言:持久化层依赖 line_index 关联 Case 草稿的 machine-1;数量不得丢失。 + assert payload['line_results'] == [{ + 'part_number': 'D4-A08AR12000002', + 'reservation_id': '2000484577', + 'required_qty': 30.0, + 'available_qty': 14.0, + 'shortage_qty': 16.0, + 'line_status': 'partial', + 'line_index': 0, + 'disposition': 'shortage', + }] + assert payload['resolutions'][0]['line_index'] == 0 + assert payload['resolutions'][0]['line_key'] is None + assert payload['resolutions'][0]['resolved_inventory_source_code'] == 'DSV360_AWSBI_BYAWSCMH01' + + def test_compensation_runner_noops_when_flag_disabled(app, monkeypatch): """BE-4:flag 关闭时补偿扫描空跑。""" from app.services.schedule import shipping_post_ot_auto_fulfill_compensation_job as job diff --git a/backend/tests/test_shipping_attachment_selection.py b/backend/tests/test_shipping_attachment_selection.py index f5856650..ec08b938 100644 --- a/backend/tests/test_shipping_attachment_selection.py +++ b/backend/tests/test_shipping_attachment_selection.py @@ -474,6 +474,7 @@ def test_transition_order_extraction_unit_tracks_retry_and_technical_failure(mon plan = SimpleNamespace(units=[], run=SimpleNamespace(run_no='SNER-PLAN')) unit = SimpleNamespace( id=1, + document_id=101, status='pending', attempt_count=0, reason_code=None, @@ -517,7 +518,11 @@ def test_runtime_snapshot_keeps_frozen_ready_layout_without_db_lookup(monkeypatc 'intake_id': 11, 'documents': [{ 'document_id': 101, - 'layout_snapshot': {'status': 'ready', 'layout_candidate': {'pages': []}}, + 'layout_snapshot': { + 'status': 'ready', + 'layout_candidate': {'pages': []}, + 'coordinate_evidence': {'pages': {}, 'page_glyphs': {}}, + }, 'layout_schema_candidates': [{'mapping_status': 'accepted'}], }], }], @@ -551,7 +556,12 @@ def test_runtime_snapshot_hydrates_current_ready_layout_when_snapshot_is_stale(m unit = SimpleNamespace(intake_id=11, document_id=101) monkeypatch.setattr( 'app.services.shipping_notice.order_extraction_runtime_snapshot.db.session.get', - lambda model, document_id: SimpleNamespace(id=document_id), + lambda model, document_id: SimpleNamespace( + id=document_id, + asset_id=301, + filename='po-1.pdf', + current_layout_version=None, + ), ) monkeypatch.setattr( 'app.services.shipping_notice.order_extraction_runtime_snapshot.current_layout_snapshot', @@ -572,6 +582,8 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch) """工作台文档详情应直接暴露单元选择、预算和失败事实。""" run = SimpleNamespace( id=1, + status='processing', + auto_freeze_policy_json=None, input_snapshot_json={ 'schema': {'definition': {'fields': []}}, 'intakes': [{ @@ -586,6 +598,7 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch) extraction_plan=SimpleNamespace(units=[SimpleNamespace( id=7, document_id=101, + created_at=None, status='failed', reason_code=None, selection_batch=1, @@ -598,6 +611,8 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch) 'selected_in_batch': 1, }, result_json={}, + cancellation_requested_at=None, + cancellation_completed_at=None, )]), ) monkeypatch.setattr( @@ -615,44 +630,39 @@ def test_workspace_documents_include_unit_selection_and_retry_facts(monkeypatch) items = serialize_workspace_run_documents(run) - assert items == [{ - 'unit_id': 7, - 'document_id': 101, - 'file_name': 'po-1.pdf', - 'status': 'failed', - 'selection_batch': 1, - 'group_key': '451883815A', - 'retry_status': 'failed', - 'technical_failure_reason_code': 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT', - 'budget_cost': { - 'initial_attachment_budget': 2, - 'initial_concurrency_budget': 2, - 'selected_in_batch': 1, - }, - 'po_number': None, - 'line_count': 0, - 'profile': None, - 'email_supplement': { - 'status': 'none', - 'relation_codes': [], - 'conflict_count': 0, - 'reservation_id_status': 'unavailable', - 'source_type_status': 'unavailable', - }, - 'reason_code': 'technical_failure', - 'review_details': [], - 'available_actions': [], - 'activity_event_code': None, - 'started_at': None, - 'last_activity_at': None, - 'finished_at': None, - }] + item = items[0] + assert item['unit_id'] == 7 + assert item['document_id'] == 101 + assert item['file_name'] == 'po-1.pdf' + assert item['status'] == 'failed' + assert item['selection_batch'] == 1 + assert item['group_key'] == '451883815A' + assert item['retry_status'] == 'failed' + assert item['technical_failure_reason_code'] == 'SHIPPING_NOTICE.ORDER_EXTRACTION_TIMEOUT' + assert item['budget_cost'] == { + 'initial_attachment_budget': 2, + 'initial_concurrency_budget': 2, + 'selected_in_batch': 1, + } + assert item['reason_code'] == 'technical_failure' + assert item['review_details'] == [] + assert item['available_actions'] == ['view_details'] + assert item['activity_event_code'] is None + assert item['started_at'] is None + assert item['last_activity_at'] is None + assert item['finished_at'] is None def test_workspace_documents_show_selected_pdfs_while_layout_is_pending(monkeypatch): """等待版面解析时仍返回已选 PDF,避免处理详情误报“暂无结果”。""" run = SimpleNamespace( id=1, + status='processing', + error_code=None, + created_at=None, + finished_at=None, + last_activity_at=None, + phase='waiting_layout', input_snapshot_json={ 'attachment_selection': { 'items': [{ diff --git a/backend/tests/test_shipping_auto_progress_controller_phase1.py b/backend/tests/test_shipping_auto_progress_controller_phase1.py index d00caea4..b2163776 100644 --- a/backend/tests/test_shipping_auto_progress_controller_phase1.py +++ b/backend/tests/test_shipping_auto_progress_controller_phase1.py @@ -63,11 +63,12 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app): ) as RC_Mock, patch( 'app.services.shipping_notice.order_review_auto_progress_coordinator.db', ), patch.object( - coord, '_customer_step_for_case', return_value={'status': 'skipped_no_shadow'}, - ), patch.object( - coord, 'validate_draft', return_value={'status': 'ready'}, - ), patch.object( - coord, 'ensure_stp_auto_create_for_case', + coord, '_customer_step_for_case', return_value=('skipped', {'reason': 'shadow_missing'}), + ), patch( + 'app.services.shipping_notice.order_review_draft_service.validate_draft', + return_value={'status': 'ready'}, + ), patch( + 'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case', return_value={'status': 'queued', 'job_id': 1201, 'idempotency_key': 'stp-auto:SNER-COORD-1:doc-100:v1'}, ) as ensure_mock: @@ -115,11 +116,12 @@ def test_contract_02_draft_validated_ready_triggers_single_case_coordinator(app) with patch( 'app.services.shipping_notice.order_review_auto_progress_coordinator.db', ), patch.object( - coord, '_customer_step_for_case', return_value={'status': 'skipped'}, - ), patch.object( - coord, 'validate_draft', return_value={'status': 'ready'}, - ), patch.object( - coord, 'ensure_stp_auto_create_for_case', + coord, '_customer_step_for_case', return_value=('skipped', {'reason': 'shadow_missing'}), + ), patch( + 'app.services.shipping_notice.order_review_draft_service.validate_draft', + return_value={'status': 'ready'}, + ), patch( + 'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case', return_value={'status': 'queued', 'job_id': 2202, 'idempotency_key': 'k-02'}, ) as ensure_mock: result = coord.reconcile_single_case_for_auto_progress( @@ -146,21 +148,22 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app): ), ) - def _customer_step(c, actor_type_hint=None): - del c, actor_type_hint + def _customer_step(*, case, trigger): + del trigger case.current_draft.validation_result_json = { 'can_build': True, 'can_auto_create': True, 'status': 'ready', } - return {'status': 'auto_confirmed', 'customer_id': 5555} + return 'auto_confirmed', {'customer_id': 5555} with patch( 'app.services.shipping_notice.order_review_auto_progress_coordinator.db', ), patch.object( coord, '_customer_step_for_case', side_effect=_customer_step, - ), patch.object( - coord, 'validate_draft', return_value={'status': 'ready'}, - ), patch.object( - coord, 'ensure_stp_auto_create_for_case', + ), patch( + 'app.services.shipping_notice.order_review_draft_service.validate_draft', + return_value={'status': 'ready'}, + ), patch( + 'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case', return_value={'status': 'queued', 'job_id': 3303, 'idempotency_key': 'k-03'}, ) as ensure_mock: result = coord.reconcile_single_case_for_auto_progress( @@ -180,10 +183,12 @@ def test_contract_04_sweeper_on_worker_restart_compensates_stp_enqueue_missing(a id=4, case_no='SORC-P1-04', status='ready', confirmed_task_id=None, document_id=400, updated_at=None, ) - with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[4]), patch( + with patch.object(sw, '_fetch_sweeper_case_candidates', return_value=[4]), patch.object( + sw, '_scan_stale_inventory_attempts', return_value=0, + ), patch.object(sw, '_recover_auto_progress_jobs', return_value=0), patch( 'app.services.shipping_notice.shipping_recovery_sweeper_service.db', - ) as mock_db, patch( - 'app.services.shipping_notice.shipping_recovery_sweeper_service.' + ) as mock_db, patch.object(sw, 'ShippingOrderReviewCase') as ReviewCase, patch( + 'app.services.shipping_notice.order_review_auto_progress_coordinator.' 'reconcile_single_case_for_auto_progress', return_value={'case_no': 'SORC-P1-04', 'enqueue_status': 'queued', 'job_id': 4404}, @@ -191,10 +196,9 @@ def test_contract_04_sweeper_on_worker_restart_compensates_stp_enqueue_missing(a mock_session = MagicMock() loaded = SimpleNamespace(id=4, status='ready', confirmed_task_id=None) mock_session.execute.return_value.scalar.return_value = None - mock_session.get.return_value = loaded - mock_session.begin_nested.return_value.__enter__ = MagicMock(return_value=None) - mock_session.begin_nested.return_value.__exit__ = MagicMock(return_value=None) + mock_session.begin_nested.return_value = MagicMock() type(mock_db).session = mock_session + ReviewCase.query.filter_by.return_value.with_for_update.return_value.first.return_value = loaded count = sw.shipping_recovery_tick() assert coord_mock.call_count == 1 @@ -265,17 +269,18 @@ def test_contract_06_duplicate_blocked_case_rejects_general_retry(app): from app.services.shipping_notice import reconciliation_service as rs from app.services.shipping_notice.recovery_contract import should_general_retry_be_removed - case = SimpleNamespace(case_no='SORC-P1-06', status='ready', confirmed_task_id=None) + case = SimpleNamespace( + case_no='SORC-P1-06', status='ready', confirmed_task_id=None, + document_id=600, run=SimpleNamespace(run_no='SNER-P1-06'), + ) # 6A:assert_case_not_blocked_manual 前置拦截 → 409 - with patch( - 'app.services.shipping_notice.reconciliation_service.find_latest_stp_job', - return_value=SimpleNamespace( + with patch.object(rs, 'Job') as Job: + Job.query.filter.return_value.filter.return_value.order_by.return_value.first.return_value = SimpleNamespace( id=60, status='failed', result_json={'retryable': False, 'blocking_reason': 'SHIPPING.NOTICE_EXACT_DUPLICATE'}, - ), - ): + ) with pytest.raises(ConflictError): rs.assert_case_not_blocked_manual(case_no='SORC-P1-06', case=case) @@ -309,9 +314,7 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app): 'app.services.shipping_notice.order_review_customer_service.refresh_order_customer_matches', ) as refresh_mock, patch( 'app.services.shipping_notice.order_review_customer_service.confirm_order_customer_match', - ) as confirm_mock, patch( - 'app.services.shipping_notice.order_review_customer_service.validate_draft', - ) as validate_mock: + ) as confirm_mock: # Shadow = unique_candidate 但是 resolved=false。 with patch( 'app.services.shipping_notice.order_review_customer_service.ShippingCustomerShadowResolution', @@ -330,16 +333,14 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app): ) as CM, patch( 'app.services.shipping_notice.order_review_customer_service.ShippingOrderExtraction', ) as EX: - Cand.query.get.return_value = SimpleNamespace(id=70) + sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700) CM.query.filter_by.return_value.first.return_value = None EX.query.filter_by.return_value.order_by.return_value.first.return_value = SimpleNamespace(id=700) - sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700) # 执行投影(纯读) out = project_review_case_customer_resolution(case) # 7A:GET 路径不允许 confirm / validate / commit confirm_mock.assert_not_called() - validate_mock.assert_not_called() refresh_mock.assert_not_called() sess_mock.commit.assert_not_called() # 7B:投影仍然能够返回客户状态(unique_candidate 而非 confirmed,因为没被写入确认) @@ -389,7 +390,7 @@ def test_contract_09_late_callback_does_not_resurrect_terminal_case(app): ) with patch.object(h.db.session, 'get', return_value=job), patch( - 'app.jobs.handlers.shipping_review_revalidate_progress.ShippingOrderReviewCase', + 'app.models.shipping_order_review.ShippingOrderReviewCase', ) as RC, patch.object(h, 'finish_job') as finish_mock, patch.object( h, 'fail_job', ) as fail_mock: @@ -400,7 +401,7 @@ def test_contract_09_late_callback_does_not_resurrect_terminal_case(app): finish_mock.assert_called_once() args, _ = finish_mock.call_args - result = args[1] if len(args) > 1 else {} + result = finish_mock.call_args.kwargs.get('result') or {} assert result.get('status') in {'skipped', 'superseded', 'case_terminal'} fail_mock.assert_not_called() @@ -427,14 +428,11 @@ def test_fe_01_stp_enqueue_missing_injects_blocking_reason(app): lines_json=[], ), ) - with patch( - 'app.services.shipping_notice.reconciliation_projector.db.session', - MagicMock(), - ), patch( - 'app.services.shipping_notice.reconciliation_projector.Job', - ) as J: - J.query.filter.return_value.first.return_value = None - bundle = _project_fine_grained_pre_stp_blocking(case) + with patch('app.extensions.db.session', MagicMock()) as session_mock: + session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None + bundle = _project_fine_grained_pre_stp_blocking( + case, validation=case.current_draft.validation_result_json, + ) assert bundle is not None assert bundle['blocking_reason']['code'] == 'stp_enqueue_missing' @@ -459,13 +457,11 @@ def test_fe_02_retryable_shows_single_primary_action_only(app): header_values_json={}, lines_json=[], ), ) - with patch( - 'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(), - ), patch( - 'app.services.shipping_notice.reconciliation_projector.Job', - ) as J: - J.query.filter.return_value.first.return_value = None - bundle = _project_fine_grained_pre_stp_blocking(case) + with patch('app.extensions.db.session', MagicMock()) as session_mock: + session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None + bundle = _project_fine_grained_pre_stp_blocking( + case, validation=case.current_draft.validation_result_json, + ) assert bundle['user_status'] == 'retryable' primary = bundle.get('primary_action') or {} @@ -477,15 +473,12 @@ def test_fe_02_retryable_shows_single_primary_action_only(app): def test_fe_03_duplicate_only_allows_reconcile_and_progress(app): """FE 合同 3:duplicate → projection 剔除 retry,只保留 reconcile_and_progress。""" - from app.services.shipping_notice.processing_projection_invariants import ( - _DUPLICATE_BLOCKING_CODES, - ) from app.services.shipping_notice.recovery_contract import ( BLOCKING_REASON_TO_ACTION_CODES, should_general_retry_be_removed, ) - for bcode in _DUPLICATE_BLOCKING_CODES: + for bcode in ('duplicate_decision_required', 'SHIPPING.NOTICE_EXACT_DUPLICATE'): assert should_general_retry_be_removed( retryable_flag=False, blocking_reason=bcode, ) is True, f'{bcode} 必须移除通用重试' @@ -510,14 +503,14 @@ def test_fe_04_refresh_and_re_login_projection_consistent(app): header_values_json={}, lines_json=[], ), ) - with patch( - 'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(), - ), patch( - 'app.services.shipping_notice.reconciliation_projector.Job', - ) as J: - J.query.filter.return_value.first.return_value = None - r1 = _project_fine_grained_pre_stp_blocking(case) - r2 = _project_fine_grained_pre_stp_blocking(case) + with patch('app.extensions.db.session', MagicMock()) as session_mock: + session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None + r1 = _project_fine_grained_pre_stp_blocking( + case, validation=case.current_draft.validation_result_json, + ) + r2 = _project_fine_grained_pre_stp_blocking( + case, validation=case.current_draft.validation_result_json, + ) assert r1 is not None and r2 is not None assert r1['blocking_reason']['code'] == r2['blocking_reason']['code'] @@ -541,13 +534,11 @@ def test_fe_05_no_contradictory_waiting_manual_and_waiting_auto_together(app): header_values_json={}, lines_json=[], ), ) - with patch( - 'app.services.shipping_notice.reconciliation_projector.db.session', MagicMock(), - ), patch( - 'app.services.shipping_notice.reconciliation_projector.Job', - ) as J: - J.query.filter.return_value.first.return_value = None - bundle = _project_fine_grained_pre_stp_blocking(case) + with patch('app.extensions.db.session', MagicMock()) as session_mock: + session_mock.query.return_value.filter.return_value.order_by.return_value.first.return_value = None + bundle = _project_fine_grained_pre_stp_blocking( + case, validation=case.current_draft.validation_result_json, + ) status = bundle.get('user_status') # retryable 与 waiting_human 互斥:命中短路 stp_enqueue_missing 时,只能二选一 diff --git a/backend/tests/test_shipping_auto_progress_p0_3.py b/backend/tests/test_shipping_auto_progress_p0_3.py index 13d5386e..fb13ddbb 100644 --- a/backend/tests/test_shipping_auto_progress_p0_3.py +++ b/backend/tests/test_shipping_auto_progress_p0_3.py @@ -10,17 +10,26 @@ tests/test_shipping_auto_progress_p0_3.py from __future__ import annotations from app import db -from app.jobs.queue import claim_next_job -from app.models import Job, ShippingInventoryCandidateSet, ShippingNotice, ShippingProcessExecution, ShippingProcessGate +from app.models import ( + Job, + ShippingInventoryCandidateSet, + ShippingNotice, + ShippingProcessExecution, + ShippingProcessGate, + ShippingProcessGateAttempt, +) from app.services.shipping_notice.auto_progress_controller import ( AUTO_PROGRESS_GATE_CODES, + determine_formal_start_gate, run_auto_progress_job, submit_auto_progress, ) +from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_through +from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version -def _task_with_candidate() -> ShippingNotice: - """创建拥有 frozen CandidateSet 的最小正式 Task。""" +def _task_with_candidate(*, complete_order: bool = True) -> ShippingNotice: + """创建正式 Task;可选择是否补齐订单解析与冻结快照事实。""" task = ShippingNotice(task_no='APX-P0-3-001', process_status='created') db.session.add(task) db.session.flush() @@ -30,12 +39,33 @@ def _task_with_candidate() -> ShippingNotice: db.session.add(candidate) db.session.flush() task.active_inventory_candidate_set_id = candidate.id + if complete_order: + task.current_order_extraction_id = 101 + task.order_snapshot_id = 201 db.session.commit() return task -def test_submit_reuses_one_active_task_job(app): - """同一 Task 多次触发只保留一个 queued/running AutoProgress Job。""" +def test_formal_start_gate_is_derived_from_persisted_task_facts(app): + """无解析、未冻结、候选未冻结与候选冻结必须分别停在对应正式 Gate。""" + task = _task_with_candidate(complete_order=False) + candidate = ShippingInventoryCandidateSet.query.filter_by(task_id=task.id).one() + + assert determine_formal_start_gate(task, candidate_set=candidate) == 'document_materialization' + + task.current_order_extraction_id = 101 + assert determine_formal_start_gate(task, candidate_set=candidate) == 'order_freeze_readiness' + + task.order_snapshot_id = 201 + candidate.lifecycle_status = 'draft' + assert determine_formal_start_gate(task, candidate_set=candidate) == 'inventory_source_routing' + + candidate.lifecycle_status = 'frozen' + assert determine_formal_start_gate(task, candidate_set=candidate) == 'inventory_preparation' + + +def test_submit_creates_formal_execution_for_task_without_case(app): + """无 Case 的新 Task 也必须创建正式 20-Gate,不得创建 APX 六 Gate。""" task = _task_with_candidate() first = submit_auto_progress(task=task, trigger='review_confirmed') second = submit_auto_progress(task=task, trigger='user_retry') @@ -43,96 +73,165 @@ def test_submit_reuses_one_active_task_job(app): assert first['status'] == 'queued' assert second['job_id'] == first['job_id'] assert second['reused'] is True - assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 1 + execution = db.session.get(ShippingProcessExecution, first['execution_id']) + gate_codes = [row.gate_code for row in execution.gates] + assert len(gate_codes) == 20 + assert gate_codes[0] == 'document_materialization' + assert gate_codes[-1] == 'manual_upload_handoff' + assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0 + assert Job.query.filter_by(id=first['job_id']).one().job_type == 'shipping_process_gate' -def test_worker_passes_only_one_gate_and_queues_successor(app, monkeypatch): - """一个 Worker Job 只处理首个 Gate,passed 与第二个 Gate Job 同事务产生。""" +def test_submit_reuses_formal_case_execution_and_supersedes_duplicate_apx(app): + """同一 Task 已有正式 Case Execution 时不得保留第二条 APX 活动链。""" task = _task_with_candidate() - submitted = submit_auto_progress(task=task, trigger='review_confirmed') - claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress']) - assert claimed is not None and claimed.id == submitted['job_id'] - monkeypatch.setattr( - 'app.services.shipping_notice.auto_progress_controller._gate_outcome', - lambda task, gate: ('passed', None, {'test': True}), + formal = ensure_execution_for_workflow_version(review_case_id=901, task_id=int(task.id)) + duplicate = ShippingProcessExecution( + execution_no='APX-DUPLICATE', task_id=int(task.id), + candidate_set_id=task.active_inventory_candidate_set_id, + execution_revision=1, status='blocked', current_gate_code=AUTO_PROGRESS_GATE_CODES[0], + lock_version=1, ) - - result = run_auto_progress_job(job_id=submitted['job_id'], worker_id='test-worker') - execution = db.session.get(ShippingProcessExecution, result['execution_id'] if 'execution_id' in result else Job.query.get(submitted['job_id']).execution_id) - gates = ShippingProcessGate.query.filter_by(execution_id=execution.id).order_by(ShippingProcessGate.sequence_no).all() - jobs = Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').order_by(Job.id).all() - - assert result['gate_code'] == AUTO_PROGRESS_GATE_CODES[0] - assert gates[0].status == 'passed' - assert gates[1].status == 'pending' - assert len(jobs) == 2 - assert jobs[0].status == 'success' and jobs[1].status == 'queued' - assert jobs[1].gate_id == gates[1].id - - -def test_stale_job_is_cancelled_without_touching_current_execution(app): - """候选/Execution 指针已切换时,迟到 Job 只能 cancelled,不能改写当前链。""" - task = _task_with_candidate() - submitted = submit_auto_progress(task=task, trigger='review_confirmed') - claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress']) - assert claimed is not None - old_execution = db.session.get(ShippingProcessExecution, Job.query.get(submitted['job_id']).execution_id) - replacement = ShippingProcessExecution( - execution_no='APX-REPLACEMENT', task_id=task.id, - candidate_set_id=task.active_inventory_candidate_set_id, execution_revision=2, - status='active', lock_version=1, - ) - db.session.add(replacement) + db.session.add(duplicate) db.session.flush() - task.active_process_execution_id = replacement.id + for sequence_no, gate_code in enumerate(AUTO_PROGRESS_GATE_CODES, start=1): + db.session.add(ShippingProcessGate( + execution_id=int(duplicate.id), gate_code=gate_code, sequence_no=sequence_no, + status='pending', evaluation_version=1, lock_version=1, + )) + task.active_process_execution_id = int(duplicate.id) db.session.commit() - result = run_auto_progress_job(job_id=submitted['job_id'], worker_id='late-worker') - assert result['status'] == 'cancelled' - assert Job.query.get(submitted['job_id']).status == 'cancelled' - assert old_execution.status == 'active' - assert db.session.get(ShippingProcessExecution, replacement.id).status == 'active' + result = submit_auto_progress(task=task, trigger='user_retry') + + db.session.refresh(task) + db.session.refresh(duplicate) + assert result['execution_id'] == formal.id + assert task.active_process_execution_id == formal.id + assert duplicate.status == 'superseded' + assert Job.query.filter_by(task_id=task.id, job_type='shipping_auto_progress').count() == 0 -def test_excel_gate_waits_for_human_receipt(app, monkeypatch): - """Excel Gate 成功后不 completed;自动上传关闭时必须停在 receipt Gate 的人工阻断。""" +def test_formal_execution_queues_one_gate_attempt_job(app): + """正式 20-Gate 链必须落 Attempt 并入队 ProcessGate Job,不能同步早退。""" task = _task_with_candidate() - submitted = submit_auto_progress(task=task, trigger='review_confirmed') - monkeypatch.setattr( - 'app.services.shipping_notice.auto_progress_controller._gate_outcome', - lambda task, gate: ('passed', None, {}), + formal = ensure_execution_for_workflow_version(review_case_id=902, task_id=int(task.id)) + mark_gates_passed_through( + execution=formal, + through_gate_code='task_creation', + reason='test_review_confirmed', ) - for _ in range(5): - claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress']) - assert claimed is not None - run_auto_progress_job(job_id=claimed.id, worker_id='test-worker') - execution = db.session.get(ShippingProcessExecution, Job.query.get(submitted['job_id']).execution_id) - receipt_gate = ShippingProcessGate.query.filter_by( - execution_id=execution.id, gate_code='upload_receipt_recorded', - ).one() - - assert execution.status == 'blocked' - assert receipt_gate.status == 'blocked_manual' - assert receipt_gate.blocking_reason_code == 'manual_upload_receipt_required' - - -def test_recorded_receipt_reopens_only_final_gate(app, monkeypatch): - """人工登记回执后,服务端只重新执行最后一个 receipt Gate 并完成 Execution。""" - task = _task_with_candidate() - submitted = submit_auto_progress(task=task, trigger='review_confirmed') - monkeypatch.setattr( - 'app.services.shipping_notice.auto_progress_controller._gate_outcome', - lambda task, gate: ('passed', None, {}), - ) - for _ in range(5): - claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress']) - run_auto_progress_job(job_id=claimed.id, worker_id='test-worker') - task.upload_receipt_json = {'receipt_no': 'R-1'} + task.active_process_execution_id = formal.id db.session.commit() - resume = submit_auto_progress(task=task, trigger='manual_upload_receipt_recorded') - claimed = claim_next_job(domain='shipping_notice', job_types=['shipping_auto_progress']) - result = run_auto_progress_job(job_id=claimed.id, worker_id='test-worker') - assert resume['gate_code'] == 'upload_receipt_recorded' - assert result['gate_code'] == 'upload_receipt_recorded' - assert db.session.get(ShippingProcessExecution, result['execution_id']).status == 'completed' + first = submit_auto_progress(task=task, trigger='review_confirmed') + second = submit_auto_progress(task=task, trigger='duplicate_confirm') + + assert first['status'] == 'queued' + assert first['job_id'] == second['job_id'] + attempt = db.session.get(ShippingProcessGateAttempt, first['attempt_id']) + job = db.session.get(Job, first['job_id']) + assert attempt is not None and attempt.job_id == job.id + assert attempt.status == 'queued' + assert job.job_type == 'shipping_process_gate' + assert Job.query.filter_by(job_type='shipping_process_gate').count() == 1 + + +def test_active_stp_job_without_retry_metadata_is_reused(app): + """活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。""" + from types import SimpleNamespace + from unittest.mock import patch + + from app.services.shipping_notice.order_stp_auto_create_service import ( + ensure_stp_auto_create_for_case, + ) + + case = SimpleNamespace( + case_no='SORC-REUSE-MISSING-RETRY', status='ready', confirmed_task_id=None, + document_id=9001, candidate_id=None, run_id=1, + run=SimpleNamespace(id=1, run_no='SNER-REUSE-MISSING-RETRY'), + owner_user_id=1, + current_draft=SimpleNamespace( + draft_version=1, + validation_result_json={'status': 'ready', 'can_build': True, 'can_auto_create': True}, + issue_summary_json=[], header_values_json={}, lines_json=[], + ), + ) + active = SimpleNamespace(id=901, status='queued') + with patch( + 'app.services.shipping_notice.order_stp_auto_create_service._persist_case_candidate_qualification', + return_value=None, + ), patch( + 'app.services.shipping_notice.order_stp_auto_create_service.find_active_stp_job', + return_value=active, + ), patch('app.services.shipping_notice.order_stp_auto_create_service.db'): + result = ensure_stp_auto_create_for_case(case=case, commit=False) + + assert result['status'] == 'already_queued' + assert result['job_id'] == 901 + assert result['retry_of_job_id'] is None + + +def test_legacy_shipping_auto_progress_job_is_terminal_readonly(app): + """历史 APX Job 被 Worker 领取时只能终止,不能再执行六 Gate 状态机。""" + task = _task_with_candidate() + legacy = ShippingProcessExecution( + execution_no='APX-READONLY', task_id=int(task.id), status='active', + candidate_set_id=int(task.active_inventory_candidate_set_id), + current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1, + ) + db.session.add(legacy) + db.session.flush() + gate = ShippingProcessGate( + execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0], + sequence_no=1, status='running', evaluation_version=1, lock_version=1, + ) + db.session.add(gate) + db.session.flush() + task.active_process_execution_id = int(legacy.id) + job = Job( + domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id), + execution_id=int(legacy.id), gate_id=int(gate.id), status='running', + candidate_set_id=int(task.active_inventory_candidate_set_id), + payload_json={'fencing_token': 'legacy-token'}, fencing_token='legacy-token', max_attempts=1, + ) + db.session.add(job) + db.session.commit() + + result = run_auto_progress_job(job_id=int(job.id), worker_id='test-worker') + + db.session.refresh(job) + db.session.refresh(gate) + assert result['status'] == 'legacy_readonly' + assert job.status == 'cancelled' + assert gate.status == 'cancelled' + + +def test_active_legacy_apx_job_does_not_block_formal_submission(app): + """历史 APX 活动 Job 不得被正式 20-Gate 提交入口复用或阻塞。""" + task = _task_with_candidate() + legacy = ShippingProcessExecution( + execution_no='APX-NONBLOCKING', task_id=int(task.id), status='active', + candidate_set_id=int(task.active_inventory_candidate_set_id), + current_gate_code=AUTO_PROGRESS_GATE_CODES[0], lock_version=1, + ) + db.session.add(legacy) + db.session.flush() + gate = ShippingProcessGate( + execution_id=int(legacy.id), gate_code=AUTO_PROGRESS_GATE_CODES[0], + sequence_no=1, status='queued', evaluation_version=1, lock_version=1, + ) + db.session.add(gate) + db.session.flush() + task.active_process_execution_id = int(legacy.id) + db.session.add(Job( + domain='shipping_notice', job_type='shipping_auto_progress', task_id=int(task.id), + execution_id=int(legacy.id), gate_id=int(gate.id), candidate_set_id=int(task.active_inventory_candidate_set_id), + status='queued', payload_json={}, fencing_token='legacy-token', max_attempts=1, + )) + db.session.commit() + + result = submit_auto_progress(task=task, trigger='review_confirmed') + + assert result['status'] == 'queued' + assert db.session.get(Job, result['job_id']).job_type == 'shipping_process_gate' diff --git a/backend/tests/test_shipping_error_explainability_contract.py b/backend/tests/test_shipping_error_explainability_contract.py index da2dc5ae..5f20fdb6 100644 --- a/backend/tests/test_shipping_error_explainability_contract.py +++ b/backend/tests/test_shipping_error_explainability_contract.py @@ -83,6 +83,13 @@ def test_message_zh_for_reason_and_rpa_meta(): assert message_zh_for_reason('totally_unknown_xyz') is None +def test_rpa_upload_failures_keep_manual_retry_action(): + """RPA 失败仍属于 Gate 19,不能被覆盖成 Gate 20 的人工待办重生。""" + for reason_code in ('upload_rpa_login_failed', 'upload_platform_rejected'): + projected = build_explainability_reason(reason_code=reason_code) + assert projected['next_action'] == 'retry_freight_upload_rpa' + + def test_inventory_preparation_reason_code_from_pending(): """履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。""" from types import SimpleNamespace diff --git a/backend/tests/test_shipping_excel_template.py b/backend/tests/test_shipping_excel_template.py index 2284b8e4..b56453bb 100644 --- a/backend/tests/test_shipping_excel_template.py +++ b/backend/tests/test_shipping_excel_template.py @@ -19,12 +19,17 @@ from app import db from app.models import ( ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction, ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, - ShippingCase, ShippingInventoryField, ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderSnapshot, - ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, + ShippingCase, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion, + ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, ) from app.services.shipping_notice import excel_template -from app.services.shipping_notice.export import _filename, _system_fact, generate_shipment_excel +from app.services.shipping_notice.export import _excel_business_no, _filename, _mapping_value, _system_fact, generate_shipment_excel from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export +from app.services.shipping_notice.inventory_file_store import ( + active_inventory_lines_for_task, + replace_task_inventory_link, + resolve_inventory_lines_for_execution, +) from app.services.shipping_notice.reservation_service import record_inventory_verification from app.services.shipping_notice.standard_field_registry import DEFAULT_SCHEMA_FAMILY_CODE from app.core.errors import ConflictError, ValidationError @@ -132,6 +137,76 @@ def test_filename_pattern_supports_business_number_and_split_business_variables( assert _filename(task, template) == 'WYC26060201_WYC26060201_DBS.xlsx' +def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cache(app, tmp_path): + """业务执行必须使用活动库存 Link,忽略请求库存和旧任务缓存。""" + with app.app_context(): + task = ShippingNotice( + task_no='TASK-INVENTORY-SOURCE', inventory_lines_json=[{'part_number': 'STALE'}], + ) + inventory_file = ShippingInventoryFile( + inventory_file_no='SIF-INVENTORY-SOURCE', storage_path=str(tmp_path / 'inventory.xlsx'), + inventory_lines_json=[{'part_number': 'ACTIVE'}], line_count=1, + share_mode='task_only', snapshot_status='ready', + ) + db.session.add_all([task, inventory_file]) + db.session.flush() + replace_task_inventory_link(task, inventory_file, role='owner') + db.session.flush() + + resolved = resolve_inventory_lines_for_execution( + task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}], + ) + + assert resolved == [{'part_number': 'ACTIVE'}] + assert task.inventory_lines_json == [{'part_number': 'STALE'}] + + +def test_inventory_execution_keeps_legacy_fallback_without_active_link(app): + """无活动 Link 的历史任务仍可读取请求库存或旧缓存,避免升级后无法恢复。""" + with app.app_context(): + task = ShippingNotice( + task_no='TASK-INVENTORY-LEGACY', inventory_lines_json=[{'part_number': 'CACHE'}], + ) + db.session.add(task) + db.session.flush() + + assert resolve_inventory_lines_for_execution( + task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}], + ) == [{'part_number': 'PAYLOAD'}] + assert resolve_inventory_lines_for_execution(task) == [{'part_number': 'CACHE'}] + + +def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp_path, monkeypatch): + """已有正式快照 JSON 时读取动作不得重新解析物理文件并覆盖已修复数据。""" + with app.app_context(): + storage_path = tmp_path / 'stale.xlsx' + storage_path.write_bytes(b'stale-source') + task = ShippingNotice(task_no='TASK-INVENTORY-NO-REPARSE') + inventory_file = ShippingInventoryFile( + inventory_file_no='SIF-INVENTORY-NO-REPARSE', storage_path=str(storage_path), + inventory_lines_json=[{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'}], + line_count=1, share_mode='task_only', snapshot_status='ready', + ) + db.session.add_all([task, inventory_file]) + db.session.flush() + replace_task_inventory_link(task, inventory_file, role='owner') + db.session.flush() + reparse_calls: list[int] = [] + + def stale_reparse(_inventory_file): + reparse_calls.append(int(_inventory_file.id)) + return ([{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-STALE'}], {}) + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_file_store.parse_inventory_snapshot_file', stale_reparse, + ) + + assert active_inventory_lines_for_task(task) == [ + {'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'}, + ] + assert reparse_calls == [] + + def test_filename_pattern_falls_back_to_controlled_environment_configuration(app): """模板未提供规则时可使用受控环境变量,调用方仍不能提交任意文件名。""" with app.app_context(): @@ -299,6 +374,54 @@ def test_export_date_system_fact_uses_business_timezone(app): assert isinstance(value, date) +def test_excel_pull_request_number_uses_export_date_without_changing_case_number(app): + """Excel Pull Request Number 必须采用导出日期,且业务单主编号保持原值。""" + with app.app_context(): + shipping_case = ShippingCase( + case_no='CASE-EXCEL-NO', business_no='IVMX26080801', sequence_value=1, + ) + task = ShippingNotice(task_no='TASK-EXCEL-NO') + task.shipping_case = shipping_case + + assert _excel_business_no(task, export_date=date(2026, 8, 11)) == 'IVMX26081101' + assert shipping_case.business_no == 'IVMX26080801' + + +def test_export_mapping_falls_back_to_export_sequence_and_derived_line_amount(app): + """LineNumber 缺失时用导出行序号,Shipment Value 缺失时用数量乘单价。""" + with app.app_context(): + fields = _lookup_standard_fields('line_no', 'line_amount_with_tax') + task = ShippingNotice(task_no='TASK-MAPPING') + + assert _mapping_value( + {'source_kind': 'order_field', 'source_key': fields['line_no'].id, 'formatter': 'integer', 'row_mode': 'line'}, + task=task, order_values={}, inventory_values={}, export_sequence=1, + ) == 1 + assert _mapping_value( + {'source_kind': 'order_field', 'source_key': fields['line_amount_with_tax'].id, 'formatter': 'decimal', 'row_mode': 'line'}, + task=task, order_values={'__qty': Decimal('14'), '__unit_price': Decimal('941.76')}, inventory_values={}, + ) == 13184.64 + + +def test_clear_template_data_rows_keeps_headers_and_removes_residual_values(): + """模板数据区从起始行起清空,表头不受影响。""" + from app.services.shipping_notice.export import _clear_template_data_rows + + workbook = Workbook() + sheet = workbook.active + sheet['A3'] = 'header' + sheet['A4'] = 'current' + sheet['A5'] = 'residual-5' + sheet['B6'] = 'residual-6' + + _clear_template_data_rows(sheet, 4) + + assert sheet['A3'].value == 'header' + assert sheet['A4'].value is None + assert sheet['A5'].value is None + assert sheet['B6'].value is None + + def test_two_sources_can_share_one_published_excel_template(app, tmp_path): """同结构库存源绑定同一 published 模板,避免复制维护映射规则。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') @@ -541,8 +664,8 @@ def test_template_publish_rejects_order_field_removed_from_current_schema(app): assert exc_info.value.code == 'SHIPPING.EXCEL_TEMPLATE_FIELD_INVALID' -def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app, tmp_path): - """同一匹配键对应多个不同 ODM 时必须阻断,且不得留下半成品 Excel。""" +def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_path): + """导出应读取活动库存 Link;无 Link 时旧缓存冲突仍须阻断且不留半成品。""" app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping') with app.app_context(): schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order') @@ -597,11 +720,37 @@ def test_export_rejects_ambiguous_inventory_values_and_cleans_partial_file(app, lines=[(1, part.id, 'PN-A', 1, '1000000004')], ) - with pytest.raises(ValueError, match='值不一致'): + with pytest.raises(ValueError, match='库存字段“ODM 编号”'): generate_shipment_excel(task) export_root = tmp_path / 'shipping' / 'exports' assert not export_root.exists() or not list(export_root.rglob('*.xlsx')) + inventory_file = ShippingInventoryFile( + inventory_file_no='SIF-ACTIVE-FIXED', user_id=None, + source_file_name='fixed.xlsx', storage_path=str(tmp_path / 'fixed.xlsx'), + inventory_lines_json=[ + {_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-FIXED'}, + {_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-FIXED'}, + ], + line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='AMBIGUOUS', + snapshot_status='ready', + ) + db.session.add(inventory_file) + db.session.flush() + replace_task_inventory_link(task, inventory_file, role='owner') + task.inventory_snapshot_id = inventory_file.id + db.session.flush() + + path, _filename_value, artifact = generate_shipment_excel(task) + + workbook = load_workbook(path, data_only=True) + try: + assert workbook['Detail'].cell(2, 1).value == 'ODM-FIXED' + finally: + workbook.close() + assert artifact.inventory_snapshot_id == inventory_file.id + assert task.inventory_lines_json[0][_inventory_field_id('odm_id')] == 'ODM-1' + def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch): """Artifact/任务事务提交失败时必须删除已生成文件,避免孤立 ready-looking 产物。""" diff --git a/backend/tests/test_shipping_inventory_match_invalidation.py b/backend/tests/test_shipping_inventory_match_invalidation.py new file mode 100644 index 00000000..83a533b2 --- /dev/null +++ b/backend/tests/test_shipping_inventory_match_invalidation.py @@ -0,0 +1,71 @@ +"""用途:验证库存恢复只失效当前任务关联的 Mapping/下游事实。 +依赖:recovery_invalidation_service 与库存谱系模型。 +逻辑:通过最小模型级约束检查和服务分支合同,禁止跨任务失效。 +""" + +from app.models import ShippingInventoryMapping + + +def test_mapping_status_contract_allows_invalidation_without_delete(): + """Mapping 失效必须保留记录,状态使用正式 invalidated 枚举。""" + allowed = next( + constraint.sqltext.text + for constraint in ShippingInventoryMapping.__table__.constraints + if getattr(constraint, 'name', '') == 'ck_shipping_inventory_mapping_status' + ) + assert 'invalidated' in allowed + + +def test_candidate_refreeze_invalidates_artifact_and_live_upload_attempt(app): + """候选版本切换后,旧 Artifact 不可下载,未终态上传 Attempt 不得继续使用。""" + from app import db + from app.models import ( + ShippingExcelTemplate, ShippingExportArtifact, ShippingInventoryParsingProfile, + ShippingNotice, ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion, + ShippingUploadAttempt, + ) + from app.services.shipping_notice.inventory_candidate_freeze_service import _invalidate_task_candidate_outputs + + task = ShippingNotice(task_no='SN-CANDIDATE-INVALIDATE-1') + template = ShippingExcelTemplate( + template_code='CANDIDATE-INVALIDATE', display_name='Candidate invalidate', version=1, + status='published', storage_bucket='test', storage_key='template.xlsx', + original_filename='template.xlsx', file_checksum='a' * 64, definition_json={}, + ) + profile = ShippingInventoryParsingProfile( + profile_code='CANDIDATE-INVALIDATE', display_name='Candidate invalidate', version=1, + status='published', file_format='xlsx', definition_json={}, + ) + schema = ShippingOrderSchema(schema_code='CANDIDATE_INVALIDATE', display_name='Candidate invalidate') + db.session.add_all([task, template, profile, schema]) + db.session.flush() + version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={}) + db.session.add(version) + db.session.flush() + extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted') + db.session.add(extraction) + db.session.flush() + artifact = ShippingExportArtifact( + artifact_no='EXP-CANDIDATE-INVALIDATE', task_id=task.id, template_id=template.id, + order_schema_version_id=version.id, order_extraction_id=extraction.id, + inventory_parsing_profile_id=profile.id, input_checksum='c' * 64, + file_path='artifact.xlsx', file_name='artifact.xlsx', file_checksum='d' * 64, + file_size=1, status='ready', + ) + db.session.add(artifact) + db.session.flush() + attempt = ShippingUploadAttempt( + artifact_id=artifact.id, attempt_no=1, mode='manual', idempotency_key='candidate-invalidate-1', + status='running', + ) + db.session.add(attempt) + db.session.flush() + + _invalidate_task_candidate_outputs(task, old_candidate_set_id=1, session=db.session) + + db.session.refresh(artifact) + db.session.refresh(attempt) + assert artifact.status == 'superseded' + assert attempt.status == 'failed' + assert attempt.invalidated_at is not None + assert attempt.invalidation_reason == 'candidate_set_refrozen' diff --git a/backend/tests/test_shipping_inventory_reuse_policy.py b/backend/tests/test_shipping_inventory_reuse_policy.py new file mode 100644 index 00000000..030b6ff7 --- /dev/null +++ b/backend/tests/test_shipping_inventory_reuse_policy.py @@ -0,0 +1,51 @@ +""" +用途:验证库存快照复用策略和多源组合指纹的 fail-closed 合同。 +依赖:纯函数服务。 +逻辑:覆盖身份、状态、过期与指纹变化;不触发外部 RPA。 +""" + +from datetime import datetime, timedelta +from types import SimpleNamespace + +from app.services.shipping_notice.inventory_combination_fingerprint import build_inventory_combination_fingerprint +from app.services.shipping_notice.inventory_snapshot_reuse_policy import check_inventory_snapshot_reusable + + +def test_snapshot_reuse_requires_ready_identity_and_versions(): + snap = SimpleNamespace( + snapshot_status='ready', expires_at=datetime.utcnow() + timedelta(hours=1), + source_code='A', warehouse_id='W1', source_config_version='v1', + input_fingerprint='cand-1', file_sha256='sha-1', parser_version='p1', mapping_version='m1', invalidated_at=None, + ) + ok, reasons = check_inventory_snapshot_reusable( + snapshot=snap, source_code='A', warehouse_id='W1', + source_config_version='v1', candidate_input_fingerprint='cand-1', + parser_version='p1', mapping_version='m1', + expected_file_sha256='sha-1', + ) + assert ok is True and reasons == [] + ok, reasons = check_inventory_snapshot_reusable(snapshot=snap, source_code='B', warehouse_id='W1') + assert ok is False and 'source_code_mismatch' in reasons + + ok, reasons = check_inventory_snapshot_reusable(snapshot=snap, source_code='A', parser_version='p2') + assert ok is False and 'parser_version_mismatch' in reasons + + +def test_combination_fingerprint_is_order_independent_but_input_sensitive(): + a = build_inventory_combination_fingerprint( + task_snapshot_fingerprint='task', candidate_freeze_fingerprint='cand', + sources=[{'source_code': 'B', 'snapshot_id': 2}, {'source_code': 'A', 'snapshot_id': 1}], + reservation_version='r1', matching_rule_version='m1', + ) + b = build_inventory_combination_fingerprint( + task_snapshot_fingerprint='task', candidate_freeze_fingerprint='cand', + sources=[{'source_code': 'A', 'snapshot_id': 1}, {'source_code': 'B', 'snapshot_id': 2}], + reservation_version='r1', matching_rule_version='m1', + ) + c = build_inventory_combination_fingerprint( + task_snapshot_fingerprint='task', candidate_freeze_fingerprint='cand', + sources=[{'source_code': 'A', 'snapshot_id': 1}, {'source_code': 'B', 'snapshot_id': 3}], + reservation_version='r1', matching_rule_version='m1', + ) + assert a == b + assert a != c diff --git a/backend/tests/test_shipping_notice_inventory_aws.py b/backend/tests/test_shipping_notice_inventory_aws.py index e36ffdec..ad6ff42b 100644 --- a/backend/tests/test_shipping_notice_inventory_aws.py +++ b/backend/tests/test_shipping_notice_inventory_aws.py @@ -11,9 +11,25 @@ from app.services.shipping_notice.inventory_snapshot import ( parse_inventory_text, read_inventory_schema_preview, ) +from app.services.shipping_notice.inventory_mapping import resolve_columns_from_field_mapping from app.services.shipping_notice.match import match_notice_lines +def test_explicit_mapping_matches_excel_header_line_breaks(app): + """发布映射的 Qty\nAvailable 表头必须解析到可用数量列。""" + with app.app_context(): + columns = resolve_columns_from_field_mapping( + ["Supplier Sku", "Resevation Order", "Qty\nAvailable", "AWS Sku"], + { + "1": "Supplier Sku", + "2": "Resevation Order", + "3": "Qty Available", + "5": "AWS Sku", + }, + ) + assert columns["3"] == 2 + + def _write_title_row_inventory_xlsx(path: Path) -> None: wb = Workbook() ws = wb.active diff --git a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py index 5eb24248..c499a13a 100644 --- a/backend/tests/test_shipping_notice_inventory_rpa_workflow.py +++ b/backend/tests/test_shipping_notice_inventory_rpa_workflow.py @@ -15,9 +15,22 @@ from app.models import ( ShippingCase, ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingInventorySource, ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine, ShippingOrderSchemaVersion, ShippingRpaProfile, ShippingNotice, ShippingTaskEvent, ShippingTaskInventoryLink, + ShippingOrderCustomerMatch, ) from app.services.shipping_notice.order_schema import service as order_schema_service -from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item, seed_rpa_inventory_trigger, seed_task_inventory_source +from tests.conftest import ( + inventory_xlsx_with_warehouse, + scheduled_rpa_batch_item, + seed_rpa_inventory_trigger, + seed_task_inventory_source, + freeze_test_task_order_snapshot, + v2_inventory_batch_payload, +) + + +def _with_v2_batch_envelope(payload: dict) -> dict: + """旧测试场景统一补齐冻结 v2 callback envelope,生产入口仍严格校验。""" + return v2_inventory_batch_payload(payload) def _tool_headers(): @@ -99,6 +112,8 @@ def _confirm_direct_rpa_task_customer(task: ShippingNotice) -> None: task.customer_resolution_method = 'test_fixture' db.session.add_all([case, task]) db.session.flush() + # 由 seed_task_inventory_source 在动态订单准备完成后完成快照冻结。 + task._test_customer_confirmed = True @pytest.fixture(autouse=True) @@ -129,6 +144,26 @@ def _confirmed_customer_for_rpa_flows(app, monkeypatch): monkeypatch.setattr(task_workflow, "resolve_shipping_case_for_new_task", _resolve_confirmed_case) +@pytest.fixture(autouse=True) +def _freeze_test_rpa_batch_callback_contract(monkeypatch): + """兼容旧测试调用:仅在测试边界补齐 v2 envelope,不改变生产回调校验。""" + from app.services.shipping_notice import inventory_rpa_workflow + import sys + + original = inventory_rpa_workflow.rpa_report_inventory_batch + callback_seq = {'value': 0} + + def _wrapped(payload): + body = _with_v2_batch_envelope(payload) + if not payload.get('callback_id'): + callback_seq['value'] += 1 + body['callback_id'] = f"test-callback:{body.get('batch_run_no') or 'unknown'}:{callback_seq['value']}" + return original(body) + + monkeypatch.setattr(inventory_rpa_workflow, 'rpa_report_inventory_batch', _wrapped) + monkeypatch.setitem(sys.modules[__name__].__dict__, 'rpa_report_inventory_batch', _wrapped) + + def test_inventory_rpa_single_attempt_messages_hide_fraction(): """单次自动尝试模式不应再产出 1/1 计数,避免 Dify 误判仍会继续自动重试。""" from app.services.shipping_notice.inventory_rpa_workflow import ( @@ -203,6 +238,8 @@ def test_ambiguous_route_uses_unique_ready_snapshot_key_coverage_without_quantit db.session.add_all([profile, rtm_source, task, source_snapshot, other_snapshot]) db.session.flush() _attach_dynamic_order(task, part_number='A001', reservation_id='1000123456', quantity=1) + _confirm_direct_rpa_task_customer(task) + freeze_test_task_order_snapshot(task) db.session.commit() result = resolve_ambiguous_source_from_ready_snapshots( @@ -239,7 +276,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev with app.app_context(): task = ShippingNotice( task_no='SN-MANUAL-PROFILE-001', source_type='manual', process_status='waiting_inventory', - lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}], + lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}], ) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code='DSV360_AWSDU') @@ -247,7 +284,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev db.session.commit() upload = FileStorage( - stream=BytesIO(inventory_xlsx_with_warehouse('AWSDU', qty=8).getvalue()), + stream=BytesIO(inventory_xlsx_with_warehouse('AWSDU', reservation_id='00001', qty=8).getvalue()), filename='manual-stock.xlsx', ) result = upload_inventory_file(task.task_no, upload) @@ -264,7 +301,7 @@ def test_manual_task_inventory_upload_uses_published_profile_without_mapping_rev assert snapshot.mapping_confirmed is True fields = {item.field_code: str(item.id) for item in ShippingInventoryField.query.all()} assert snapshot.inventory_lines_json[0][fields['part_number']] == 'A001' - assert snapshot.inventory_lines_json[0][fields['reservation_id']] == 'R-1' + assert snapshot.inventory_lines_json[0][fields['reservation_id']] == '00001' assert snapshot.inventory_lines_json[0][fields['available_qty']] == 8 @@ -282,7 +319,7 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path): workbook = Workbook() sheet = workbook.active sheet.append(['Warehouse ID', 'Unexpected Part', 'Reservation ID', 'Qty']) - sheet.append(['AWSDU', 'A001', 'R-1', 8]) + sheet.append(['AWSDU', 'A001', '00001', 8]) workbook.save(stream) workbook.close() stream.seek(0) @@ -290,7 +327,7 @@ def test_manual_task_inventory_upload_rolls_back_structure_drift(app, tmp_path): with app.app_context(): task = ShippingNotice( task_no='SN-MANUAL-DRIFT-001', source_type='manual', process_status='waiting_inventory', - lines_json=[{'part_number': 'A001', 'reservation_id': 'R-1', 'qty': 1}], + lines_json=[{'part_number': 'A001', 'reservation_id': '00001', 'qty': 1}], ) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code='DSV360_AWSDU') @@ -336,14 +373,16 @@ def test_rpa_report_inventory_batch_empty_item_treated_as_failed(app, tmp_path): """batch results 中空 dict 应直接 failed,不走 success→file_missing 绕路。""" from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + drop_dir = tmp_path / "drop" + drop_dir.mkdir(parents=True, exist_ok=True) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") with app.app_context(): - result = rpa_report_inventory_batch({ + result = rpa_report_inventory_batch(_with_v2_batch_envelope({ "run_no": "RUN-EMPTY-ITEM", "trigger_type": "scheduled", "results": [{}], - }) + })) assert result["status"] == "ok" assert result["result_status"] == "failed" assert result["data"]["result_status"] == "failed" @@ -365,7 +404,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm handle.write(inventory_xlsx_with_warehouse("AWSDU").getvalue()) with app.app_context(): - result = rpa_report_inventory_batch({ + result = rpa_report_inventory_batch(_with_v2_batch_envelope({ "run_no": "RUN-MIXED", "trigger_type": "scheduled", "results": [ @@ -383,7 +422,7 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm "error_message": "timeout", }, ], - }) + })) assert result["status"] == "ok" assert result["result_status"] == "partial_failed" assert result["data"]["result_status"] == "partial_failed" @@ -398,7 +437,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path): app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") with app.app_context(): - result = rpa_report_inventory_batch({ + result = rpa_report_inventory_batch(_with_v2_batch_envelope({ "run_no": "RUN-ALL-FAIL", "trigger_type": "scheduled", "results": [{ @@ -408,7 +447,7 @@ def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path): "success": False, "error_message": "timeout", }], - }) + })) assert result["status"] == "ok" assert result["result_status"] == "failed" assert result["failed_count"] == 1 @@ -474,7 +513,7 @@ def test_confirm_inventory_source_does_not_trigger_rpa_export(app, tmp_path, mon ], } }, - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) db.session.add(task) db.session.commit() @@ -512,7 +551,7 @@ def test_batch_callback_merges_top_level_run_no_for_task_success(app, tmp_path): source_type="manual", process_status="waiting_inventory", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") @@ -546,7 +585,10 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path): from app import db from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch + drop_dir = tmp_path / "drop" + drop_dir.mkdir() app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) with app.app_context(): task = ShippingNotice( @@ -554,7 +596,7 @@ def test_batch_callback_failed_with_task_no_updates_task(app, tmp_path): source_type="manual", process_status="waiting_inventory", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") @@ -598,7 +640,7 @@ def test_single_callback_failed_without_identity_fields_allowed(app, tmp_path): source_type="manual", process_status="waiting_inventory", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") @@ -709,7 +751,7 @@ def test_batch_success_rejects_missing_worker_identity(app, tmp_path): source_type="manual", process_status="waiting_inventory", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) seed_task_inventory_source(task, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task, run_no="RUN-BATCH-NO-IDENT") @@ -777,7 +819,7 @@ def test_reused_snapshot_preserved_when_batch_ingest_fails(app, tmp_path, monkey source_type="manual", process_status="waiting_inventory", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) seed_task_inventory_source(task, source_code="DSV360_AWSDU") seed_rpa_inventory_trigger(task, run_no=run_no) @@ -866,8 +908,9 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path, from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch drop_dir = tmp_path / "drop" - drop_dir.mkdir() + drop_dir.mkdir(parents=True, exist_ok=True) app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) sample_a = drop_dir / "task_a.xlsx" sample_b = drop_dir / "task_b.xlsx" sample_a.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) @@ -892,14 +935,14 @@ def test_batch_partial_failure_rolls_back_failed_item_task_state(app, tmp_path, source_type="manual", process_status="waiting_inventory", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) task_b = ShippingNotice( task_no="SN-BATCH-FAIL", source_type="manual", process_status="waiting_inventory", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}], + lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}], ) _confirm_direct_rpa_task_customer(task_a) _confirm_direct_rpa_task_customer(task_b) @@ -947,6 +990,7 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m drop_dir = tmp_path / "drop" drop_dir.mkdir() app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage") + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir) sample = drop_dir / "shared.xlsx" sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue()) run_no = "RUN-SHARED-LINK" @@ -957,14 +1001,14 @@ def test_reused_snapshot_failure_does_not_break_other_task_link(app, tmp_path, m source_type="manual", process_status="waiting_inventory", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) task_fail = ShippingNotice( task_no="SN-SHARED-FAIL", source_type="manual", process_status="waiting_inventory", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "B001", "reservation_id": "R-2", "qty": 1}], + lines_json=[{"part_number": "B001", "reservation_id": "00002", "qty": 1}], ) _confirm_direct_rpa_task_customer(task_ok) _confirm_direct_rpa_task_customer(task_fail) @@ -1046,7 +1090,7 @@ def test_single_callback_post_commit_failure_keeps_committed_snapshot(app, tmp_p source_type="manual", process_status="waiting_inventory", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") @@ -1091,7 +1135,7 @@ def test_promote_failure_rebuilds_attachment_from_snapshot(app, tmp_path, monkey source_type="manual", process_status="waiting_inventory", pending_human_reason="rpa_pending", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) _confirm_direct_rpa_task_customer(task) seed_task_inventory_source(task, source_code="DSV360_AWSDU") @@ -1128,7 +1172,7 @@ def test_repair_task_inventory_attachment_from_snapshot(app, tmp_path): task_no="SN-REPAIR-ATTACH", source_type="manual", process_status="inventory_ready", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) seed_task_inventory_source(task, source_code="DSV360_AWSDU") db.session.add(task) @@ -1286,7 +1330,7 @@ def test_repair_rejects_foreign_inventory_file_no(app, tmp_path): task_no="SN-REPAIR-REJECT", source_type="manual", process_status="inventory_ready", - lines_json=[{"part_number": "A001", "reservation_id": "R-1", "qty": 1}], + lines_json=[{"part_number": "A001", "reservation_id": "00001", "qty": 1}], ) seed_task_inventory_source(task, source_code="DSV360_AWSDU") db.session.add(task) diff --git a/backend/tests/test_shipping_notice_inventory_schedule.py b/backend/tests/test_shipping_notice_inventory_schedule.py index 2d9c7fb0..fd29073b 100644 --- a/backend/tests/test_shipping_notice_inventory_schedule.py +++ b/backend/tests/test_shipping_notice_inventory_schedule.py @@ -9,6 +9,8 @@ backend/tests/test_shipping_notice_inventory_schedule.py from datetime import datetime, timedelta from pathlib import Path +import pytest + from app import db from app.models import ScheduleRun, ScheduleTask, ScheduleTaskConfig, User from app.services.schedule.scheduler_service import run_task_now @@ -24,6 +26,22 @@ from app.services.schedule.shipping_inventory_rpa_job import ( _filter_sources, run_shipping_inventory_rpa_schedule, ) +from tests.conftest import v2_inventory_batch_payload + + +@pytest.fixture(autouse=True) +def _freeze_schedule_batch_callback_contract(monkeypatch): + """旧排程测试调用统一补齐冻结 v2 callback envelope;生产入口仍严格校验。""" + from app.services.shipping_notice import inventory_rpa_workflow + import sys + + original = inventory_rpa_workflow.rpa_report_inventory_batch + + def _wrapped(payload): + return original(v2_inventory_batch_payload(payload)) + + monkeypatch.setattr(inventory_rpa_workflow, 'rpa_report_inventory_batch', _wrapped) + monkeypatch.setitem(sys.modules[__name__].__dict__, 'rpa_report_inventory_batch', _wrapped) from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch from tests.conftest import inventory_xlsx_with_warehouse, scheduled_rpa_batch_item diff --git a/backend/tests/test_shipping_notice_rpa_trigger_for_task.py b/backend/tests/test_shipping_notice_rpa_trigger_for_task.py index 054851a8..97d40807 100644 --- a/backend/tests/test_shipping_notice_rpa_trigger_for_task.py +++ b/backend/tests/test_shipping_notice_rpa_trigger_for_task.py @@ -1,11 +1,13 @@ """ backend/tests/test_shipping_notice_rpa_trigger_for_task.py -用途:验证按需库存导出在 batch 与 legacy 模式下生成正确 trigger。 +用途:验证按需库存导出仅生成 v2 batch trigger,并携带完整冻结身份。 依赖:shipping_notice.rpa、pytest app/tmp_path 夹具。 逻辑:构造 connector_type 库存连接器载荷,检查 trigger 文件分支与关键字段。 """ +import pytest + from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task @@ -27,28 +29,39 @@ def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path): path = write_inventory_export_trigger_for_task( "SN-ON-DEMAND-1", source, - payload={"mode": "auto", "attempt": 1}, + payload={ + "mode": "auto", "attempt": 1, "source_run_no": "SRC-1", + "lease_token": "lease-1", "candidate_set_id": 12, + "execution_id": 88, "gate_id": 901, + "expected_warehouse_id": "AWSDU", + }, ) assert path trigger_files = list(trigger_dir.glob("inventory_export_batch_*.json")) assert trigger_files - text = trigger_files[0].read_text(encoding="utf-8") - assert "inventory_export_batch" in text - assert "SN-ON-DEMAND-1" in text - assert "DSV360_AWSDU" in text + payload = __import__("json").loads(trigger_files[0].read_text(encoding="utf-8")) + assert payload["action"] == "inventory_export_batch" + item = payload["inventory_sources"][0] + assert item["task_no"] == "SN-ON-DEMAND-1" + assert item["source_code"] == "DSV360_AWSDU" + assert item["source_run_no"] == "SRC-1" + assert item["execution_id"] == 88 + assert item["gate_id"] == 901 -def test_on_demand_uses_legacy_trigger_when_batch_disabled(app, tmp_path): - """batch 关闭时仍写 legacy inventory_export trigger。""" +def test_on_demand_rejects_when_v2_batch_is_disabled(app, tmp_path): + """v2 batch 关闭时 fail-closed,禁止生成 legacy inventory_export trigger。""" + from app.core.errors import ValidationError + trigger_dir = tmp_path / "triggers" app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = False source = {"source_code": "DSV360_AWSDU", "connector_type": "dsv360", "warehouse_id": "AWSDU", "query": {}} - with app.app_context(): - path = write_inventory_export_trigger_for_task("SN-LEGACY-1", source) - assert path - assert list(trigger_dir.glob("inventory_export_SN-LEGACY-1.json")) + with app.app_context(), pytest.raises(ValidationError, match="v2") as exc_info: + write_inventory_export_trigger_for_task("SN-LEGACY-1", source) + assert exc_info.value.code == "SHIPPING.INVENTORY_RPA_V2_REQUIRED" + assert not list(trigger_dir.glob("inventory_export_SN-LEGACY-1.json")) def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_path): @@ -70,3 +83,30 @@ def test_batch_trigger_projects_business_connector_to_worker_contract(app, tmp_p assert item["entry_url"] == "https://example.invalid/dbs" assert "username" not in item assert "password" not in item + + +def test_batch_trigger_writes_explicit_v2_callback_identity(app, tmp_path): + """新 batch Trigger 必须显式写入顶层和逐源 callback_id,Worker 不得推导。""" + import json + from app.services.shipping_notice.rpa import write_inventory_export_batch_trigger + + trigger_dir = tmp_path / "triggers" + app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) + app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True + source = { + "source_code": "DBS", + "connector_type": "dbs", + "warehouse_id": "WH-1", + "source_run_no": "SRC-1", + "attempt_no": 2, + "candidate_set_id": 12, + "execution_id": 88, + "gate_id": 901, + "expected_warehouse_id": "WH-1", + "lease_token": "lease-1", + } + with app.app_context(): + path = write_inventory_export_batch_trigger("BATCH-1", [source]) + body = json.loads((path and __import__('pathlib').Path(path)).read_text(encoding="utf-8")) + assert body["callback_id"] == "BATCH-1:batch:C1" + assert body["inventory_sources"][0]["callback_id"] == "SRC-1:C1" diff --git a/backend/tests/test_shipping_notice_tools.py b/backend/tests/test_shipping_notice_tools.py index e6f96f04..b70938c1 100644 --- a/backend/tests/test_shipping_notice_tools.py +++ b/backend/tests/test_shipping_notice_tools.py @@ -190,6 +190,39 @@ def test_parse_notice_tool_is_removed(app, client): assert response.status_code == 404 +def test_direct_excel_tool_dispatches_to_formal_auto_progress(monkeypatch): + """旧 Tool 入口不能绕过 GateAttempt 直接生成 Excel。""" + from app.services.shipping_notice import fulfillment_workflow + + submitted: dict[str, object] = {} + + def _submit(task_no, **kwargs): + submitted['task_no'] = task_no + submitted.update(kwargs) + return {'status': 'running', 'data': {}} + + monkeypatch.setattr( + 'app.services.shipping_notice.progress_workflow.run_task_auto_progress', + _submit, + ) + + result = fulfillment_workflow.generate_excel({ + 'task_id': 'SN-FORMAL-EXCEL-ONLY', + 'operator_id': 7, + 'idempotency_key': 'formal-excel-only', + }) + + assert result['status'] == 'running' + assert submitted == { + 'task_no': 'SN-FORMAL-EXCEL-ONLY', + 'trigger': 'tool_api_generate_excel', + 'expected_version': None, + 'idempotency_key': 'formal-excel-only', + 'resume_gate_code': 'artifact_generation', + 'operator_id': 7, + } + + def test_match_notice_lines_reports_progress(): seen: list[tuple[int, int]] = [] @@ -806,7 +839,7 @@ def test_submit_decision_requires_task_id_when_conversation_has_multiple_tasks(a assert rows["SN-MULTI-CONV-002"].process_status == "pending_review" -def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, monkeypatch): +def test_submit_decision_retry_rpa_routes_to_formal_gate_action(app, client, monkeypatch): headers = _tool_headers(app) create_res = client.post( @@ -820,15 +853,11 @@ def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, mon captured: dict[str, object] = {} - def fake_ensure_inventory(payload): - captured.update(payload) - return { - "status": "running", - "task_id": payload["task_id"], - "message": "已触发库存获取(测试桩)", - } + def fake_request_formal_gate_action(**kwargs): + captured.update(kwargs) + return {"status": "running", "task_id": task_id, "message": "已提交正式 20-Gate 恢复动作"} - monkeypatch.setattr(decision_workflow, "ensure_inventory", fake_ensure_inventory) + monkeypatch.setattr(decision_workflow, "_request_formal_gate_action", fake_request_formal_gate_action) res = client.post( "/api/shipping-notice/tools/submit_decision", @@ -838,9 +867,9 @@ def test_submit_decision_retry_rpa_routes_to_inventory_workflow(app, client, mon data = res.get_json() assert data["status"] == "running" assert data["task_id"] == task_id - assert data["message"] == "已触发库存获取(测试桩)" - assert captured["task_id"] == task_id - assert captured["mode"] == "retry_rpa" + assert data["message"] == "已提交正式 20-Gate 恢复动作" + assert captured["task"].task_no == task_id + assert captured["action_code"] == "retry_inventory_preparation" def test_parse_inventory_oversized_text_route_is_removed(app, client): diff --git a/backend/tests/test_shipping_process_gate_api.py b/backend/tests/test_shipping_process_gate_api.py index 27f09e38..8cf452a5 100644 --- a/backend/tests/test_shipping_process_gate_api.py +++ b/backend/tests/test_shipping_process_gate_api.py @@ -59,6 +59,10 @@ def _seed_blocked_execution(owner: User | None = None): execution_id=int(execution.id), gate_code='order_freeze_readiness', ).first() + # 夹具显式将阻断 Gate 设为 Execution.current_gate,覆盖前置 Gate 默认初始状态, + # 以便 API 测试验证当前 Gate 的统一写校验。 + execution.current_gate_code = gate.gate_code + execution.primary_next_action_code = gate.next_action_code db.session.commit() return user, execution, gate @@ -86,6 +90,19 @@ def _seed_blocked_execution_for_agent_readonly(): ) ensure_order_extraction_plan(run) cases = ensure_run_review_cases(run=run) + if not cases: + # 当前最小 API 夹具可能没有完整 Worker Candidate;仍创建只读授权所需的 + # 正式 Case 绑定,测试只验证权限边界,不把缺失 Candidate 伪装成业务成功。 + from app.models import ShippingOrderReviewCase + unit = run.extraction_plan.units[0] if run.extraction_plan and run.extraction_plan.units else None + if unit is not None and unit.document_id: + case = ShippingOrderReviewCase( + case_no=f'SORC-API-FALLBACK-{run.id}', run_id=int(run.id), unit_id=int(unit.id), + document_id=int(unit.document_id), owner_user_id=int(user.id), status='draft', + ) + db.session.add(case) + db.session.flush() + cases = [case] assert cases, 'review case required for agent authorization path' case = cases[0] execution = ensure_execution_for_workflow_version( @@ -224,6 +241,51 @@ def test_workspace_post_action_idempotent(app, client): assert ShippingProcessGateAttempt.query.filter_by(idempotency_key='api-idempotent-1').count() == 1 +def test_workspace_post_action_rejects_non_current_gate_for_all_gate_actions(app, client): + """所有阶段统一禁止绕过 current_gate 写入其他 Gate。""" + with app.app_context(): + owner, execution, gate = _seed_blocked_execution() + # order_freeze_readiness 是当前阻断;请求另一个正式 Gate 必须 fail-closed。 + other_gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='inventory_matching', + ).first() + assert other_gate is not None + resp = client.post( + f'/api/workspace/shipping-notice/process-executions/{execution.execution_no}' + '/gates/inventory_matching/actions', + headers=_auth_headers(owner), + json={ + 'action_code': 'open_inventory_match_review', + 'expected_gate_version': int(other_gate.evaluation_version), + 'idempotency_key': 'api-non-current-gate-1', + }, + ) + assert resp.status_code == 400 + assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_GATE_NOT_CURRENT' + + +def test_workspace_post_action_rejects_terminal_execution_for_all_gate_actions(app, client): + """所有阶段统一禁止 completed/cancelled Execution 写动作。""" + with app.app_context(): + owner, execution, gate = _seed_blocked_execution() + execution.status = 'completed' + db.session.commit() + resp = client.post( + f'/api/workspace/shipping-notice/process-executions/{execution.execution_no}' + f'/gates/{gate.gate_code}/actions', + headers=_auth_headers(owner), + json={ + 'action_code': 'open_order_review', + 'expected_gate_version': int(gate.evaluation_version), + 'idempotency_key': 'api-terminal-execution-1', + }, + ) + assert resp.status_code == 400 + assert resp.get_json().get('error', {}).get('code') == 'SHIPPING.PROCESS_EXECUTION_TERMINAL' + + + + def test_workspace_get_missing_execution_404(app, client): """不存在的 execution_no 返回 404。""" with app.app_context(): diff --git a/backend/tests/test_shipping_process_gate_contract.py b/backend/tests/test_shipping_process_gate_contract.py index ba292d69..8d0a4d82 100644 --- a/backend/tests/test_shipping_process_gate_contract.py +++ b/backend/tests/test_shipping_process_gate_contract.py @@ -16,6 +16,7 @@ from app.services.shipping_notice.process_gate_contract import ( PROCESS_GATE_DEFINITIONS, PROCESS_GATE_REASON_OWNING_GATE, assert_process_gate_contract_integrity, + action_presentation, field_quality_may_block, owning_gate_for_reason, primary_next_action_for_gate, @@ -59,6 +60,22 @@ def test_inventory_source_routing_primary_retry_action(): assert action == 'retry_with_latest_rules' +def test_inventory_sufficiency_actions_keep_business_specific_labels(): + """库存缺口恢复必须保留精确业务动作,禁止客户端降级为统一“重试”。""" + assert action_presentation('open_shortage_review') == { + 'code': 'open_shortage_review', + 'label_key': 'workspace.shippingNotice.processGate.actionCodes.open_shortage_review', + 'kind': 'current_gate', + 'dispatch': 'navigation', + } + assert action_presentation('retry_inventory_from_matching') == { + 'code': 'retry_inventory_from_matching', + 'label_key': 'workspace.shippingNotice.processGate.actionCodes.retry_inventory_from_matching', + 'kind': 'recovery', + 'dispatch': 'mutation', + } + + def test_process_gate_reason_ownership_is_unique(): """ 每个阻断原因码恰好映射一个 owning_gate,覆盖率 100%。 @@ -83,6 +100,205 @@ def test_field_quality_block_eligibility(): assert field_quality_may_block(required=False, auto_create_key_field=False) is False +def test_projection_marks_apx_gate_as_readonly_without_executable_actions(app, monkeypatch): + """APX 历史 Gate 只可审计展示,不能再投影为可恢复业务 Gate。""" + from types import SimpleNamespace + from app.services.shipping_notice import process_gate_projection as projection + + gate = SimpleNamespace( + id=1, gate_code='inventory_candidates_calculated', sequence_no=1, + status='pending', evaluation_version=1, input_fingerprint=None, + blocking_reason_code=None, blocking_reason_json=None, + recommendation_json=None, effective_result_json={}, findings_json=None, + next_action_code=None, passed_at=None, invalidated_at=None, + latest_attempt_id=None, + ) + monkeypatch.setattr( + projection.ShippingProcessGateAttempt.query, + 'get', + lambda _id: None, + raising=False, + ) + payload = projection.serialize_process_gate(gate, include_diagnostics=False) + assert payload['gate_code'] == 'inventory_candidates_calculated' + assert payload['legacy_readonly'] is True + assert payload['allowed_actions'] == [] + assert payload['recovery_targets'] == [] + assert len(PROCESS_GATE_DEFINITIONS) == 20 + + +def test_user_gate_summary_marks_apx_execution_readonly(app, monkeypatch): + """APX Execution 不能向用户下发主动作或恢复目标。""" + from types import SimpleNamespace + from app.services.shipping_notice import process_gate_projection as projection + + execution = SimpleNamespace( + id=1, execution_no='APX-1', status='blocked', current_gate_code='inventory_candidates_calculated', + last_passed_gate_code=None, primary_next_action_code=None, responsible_party='system', + lock_version=1, review_case_id=None, task_id=1, updated_at=None, + ) + gate = SimpleNamespace( + id=1, gate_code='inventory_candidates_calculated', sequence_no=1, status='blocked_retryable', + evaluation_version=1, input_fingerprint=None, blocking_reason_code='inventory_candidates_required', + blocking_reason_json=None, recommendation_json=None, effective_result_json={}, + next_action_code=None, passed_at=None, invalidated_at=None, latest_attempt_id=None, + ) + query = projection.ShippingProcessGate.query + monkeypatch.setattr(query, 'filter_by', lambda **_kwargs: query) + monkeypatch.setattr(query, 'order_by', lambda *_args: query) + monkeypatch.setattr(query, 'all', lambda: [gate]) + monkeypatch.setattr(projection.ShippingProcessGateAttempt.query, 'get', lambda _id: None, raising=False) + summary = projection.project_user_gate_summary(execution) + assert summary['status'] == 'legacy_readonly' + assert summary['legacy_readonly'] is True + assert summary['next_action_code'] is None + assert summary['allowed_actions'] == [] + + +def test_inventory_matching_recovery_keeps_review_entry_when_primary_is_technical(app, monkeypatch): + """库存匹配技术重试被隐藏时,跨阶段 RecoveryPlan 仍必须保留人工复核入口。""" + from types import SimpleNamespace + from app.services.shipping_notice import process_gate_projection as projection + + execution = SimpleNamespace( + id=1, execution_no='EXE-INV-1', status='blocked', + current_gate_code='inventory_matching', primary_next_action_code='retry_inventory_matching', + responsible_party='worker', lock_version=1, review_case_id=None, task_id=None, + ) + monkeypatch.setattr( + projection, + 'serialize_process_execution', + lambda _execution, include_diagnostics=False: { + 'execution_no': 'EXE-INV-1', 'status': 'blocked', + 'primary_next_action_code': 'retry_inventory_matching', + 'responsible_party': 'worker', + 'current_gate': { + 'gate_code': 'inventory_matching', + 'status': 'blocked_manual', + 'blocking_reason_code': 'inventory_match_incomplete', + 'next_action_code': 'retry_inventory_matching', + }, + 'recovery_targets': [ + {'action_code': 'retry_inventory_from_preparation', 'target_gate': 'inventory_preparation'}, + ], + 'gates': [], 'active_recovery_plans': [], + }, + ) + + summary = projection.project_user_gate_summary(execution) + + assert summary['current_blocking_gate']['gate_code'] == 'inventory_matching' + assert summary['next_action_code'] == 'open_inventory_match_review' + assert summary['owner_type'] == 'human' + assert summary['technical_auto_only'] is False + assert summary['allowed_actions'] == [ + 'open_inventory_match_review', + 'retry_inventory_from_preparation', + ] + + +def test_user_gate_summary_exposes_sanitized_failure_detail_for_any_gate(app, monkeypatch): + """所有 Gate 均应把当前 Attempt 的脱敏失败详情投影给用户,而非只显示泛化原因。""" + from types import SimpleNamespace + from app.services.shipping_notice import process_gate_projection as projection + + execution = SimpleNamespace( + id=1, execution_no='EXE-FAIL-1', status='blocked', + current_gate_code='artifact_generation', primary_next_action_code='regenerate_excel_artifact', + responsible_party='system', lock_version=1, review_case_id=None, task_id=None, + ) + monkeypatch.setattr( + projection, + 'serialize_process_execution', + lambda _execution, include_diagnostics=False: { + 'execution_no': 'EXE-FAIL-1', 'status': 'blocked', + 'primary_next_action_code': 'regenerate_excel_artifact', + 'responsible_party': 'system', 'recovery_targets': [], 'gates': [], + 'active_recovery_plans': [], + 'current_gate': { + 'gate_code': 'artifact_generation', 'status': 'blocked_retryable', + 'blocking_reason_code': 'artifact_generation_failed', + 'next_action_code': 'regenerate_excel_artifact', + 'latest_attempt': { + 'attempt_no': 7, + 'status': 'failed', + 'error_code': 'SHIPPING.EXCEL_ARTIFACT_WRITE_FAILED', + 'error_summary': r'Excel 写入失败 at C:\worker\output.xlsx password=secret', + }, + }, + }, + ) + summary = projection.project_user_gate_summary(execution) + assert summary['failure_detail'] is not None + assert 'Excel 写入失败' in summary['failure_detail'] + assert '[path]' in summary['failure_detail'] + assert 'secret' not in summary['failure_detail'] + + +def test_user_gate_summary_repairs_stale_rpa_action_for_gate19(app, monkeypatch): + """历史 Gate 19 即使持久化了人工待办动作,也必须投影为 RPA 重试。""" + from types import SimpleNamespace + from app.services.shipping_notice import process_gate_projection as projection + + execution = SimpleNamespace( + id=1, execution_no='EXE-RPA-STALE', status='blocked', + current_gate_code='freight_upload_rpa', + primary_next_action_code='regenerate_manual_upload_todo', + responsible_party='worker', lock_version=1, review_case_id=None, task_id=None, + ) + monkeypatch.setattr( + projection, + 'serialize_process_execution', + lambda _execution, include_diagnostics=False: { + 'execution_no': 'EXE-RPA-STALE', 'status': 'blocked', + 'primary_next_action_code': 'regenerate_manual_upload_todo', + 'responsible_party': 'worker', 'recovery_targets': [], + 'active_recovery_plans': [], 'gates': [], + 'current_gate': { + 'gate_code': 'freight_upload_rpa', 'status': 'blocked_manual', + 'blocking_reason_code': 'upload_platform_rejected', + 'next_action_code': 'regenerate_manual_upload_todo', + }, + }, + ) + + summary = projection.project_user_gate_summary(execution) + assert summary['next_action_code'] == 'retry_freight_upload_rpa' + assert summary['owner_type'] == 'human' + + +def test_user_gate_summary_exposes_manual_gate_rpa_retry(app, monkeypatch): + """Gate 20 人工交接也可显式重试 RPA,且不依赖 AUTO_UPLOAD 配置。""" + from types import SimpleNamespace + from app.services.shipping_notice import process_gate_projection as projection + + execution = SimpleNamespace( + id=1, execution_no='EXE-MANUAL-RPA', status='blocked', + current_gate_code='manual_upload_handoff', + primary_next_action_code='regenerate_manual_upload_todo', + responsible_party='owner', lock_version=1, review_case_id=None, task_id=None, + ) + monkeypatch.setattr( + projection, + 'serialize_process_execution', + lambda _execution, include_diagnostics=False: { + 'execution_no': 'EXE-MANUAL-RPA', 'status': 'blocked', + 'primary_next_action_code': 'regenerate_manual_upload_todo', + 'responsible_party': 'owner', 'recovery_targets': [], + 'active_recovery_plans': [], 'gates': [], + 'current_gate': { + 'gate_code': 'manual_upload_handoff', 'status': 'blocked_manual', + 'blocking_reason_code': 'manual_upload_pending', + 'next_action_code': 'regenerate_manual_upload_todo', + }, + }, + ) + + summary = projection.project_user_gate_summary(execution) + assert summary['next_action_code'] == 'retry_freight_upload_rpa' + assert summary['owner_type'] == 'human' + + def test_process_gate_dependency_integrity_and_excel_only_scope(): """ 校验依赖图完整性,并锁定「仅重生 Excel」不得失效库存匹配。 diff --git a/backend/tests/test_shipping_process_gate_contract_v2.py b/backend/tests/test_shipping_process_gate_contract_v2.py new file mode 100644 index 00000000..646f93c1 --- /dev/null +++ b/backend/tests/test_shipping_process_gate_contract_v2.py @@ -0,0 +1,109 @@ +""" +tests/test_shipping_process_gate_contract_v2.py + +用途:冻结 Gate v2 的 20 Gate 实施状态、恢复目标与 API 边界合同。 +依赖:process_gate_contract、recovery_plan_contract、process_gate_projection。 +逻辑:只验证服务端合同输出;客户端不得自行推导目标 Gate 或实现状态。 +""" + +from __future__ import annotations + +from app.services.shipping_notice.process_gate_contract import ( + PROCESS_GATE_DEFINITIONS, + PROCESS_GATE_IMPLEMENTATION_STATUSES, + assert_process_gate_contract_integrity, +) +from app.services.shipping_notice.process_gate_projection import serialize_process_gate +from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action + + +def test_gate_v2_freezes_implementation_status_for_all_twenty_gates(): + """20 个 Gate 必须都有实现状态;Gate 1–9 为 supported,Gate 10–20 为 implemented。""" + assert_process_gate_contract_integrity() + assert len(PROCESS_GATE_DEFINITIONS) == 20 + assert all(item.get('implementation_status') in PROCESS_GATE_IMPLEMENTATION_STATUSES for item in PROCESS_GATE_DEFINITIONS) + assert all(item['implementation_status'] == 'supported' for item in PROCESS_GATE_DEFINITIONS[:9]) + assert all(item['implementation_status'] == 'implemented' for item in PROCESS_GATE_DEFINITIONS[9:]) + + +def test_gate_v2_cross_stage_recovery_contract_is_server_owned(): + """库存跨阶段恢复目标、继续点和失效范围必须由服务端合同固定。""" + preparation = recovery_plan_for_action( + current_gate='inventory_matching', + action_code='retry_inventory_from_preparation', + ) + mapping = recovery_plan_for_action( + current_gate='inventory_matching', + action_code='retry_inventory_from_field_mapping', + ) + assert preparation == { + 'target_gate': 'inventory_preparation', + 'resume_after_gate': 'inventory_matching', + 'allowed_intermediate_gates': ('inventory_field_mapping',), + 'invalidate_change_type': 'inventory_file_changed', + 'invalidates': ('inventory_snapshot', 'inventory_mapping', 'inventory_matching', 'inventory_sufficiency', 'excel', 'upload'), + 'permission': 'owner_or_admin', + } + assert mapping['target_gate'] == 'inventory_field_mapping' + assert mapping['resume_after_gate'] == 'inventory_matching' + assert 'inventory_mapping' in mapping['invalidates'] + + +def test_unknown_recovery_action_is_not_a_contract_target(): + """未注册动作不得被 Projection 或执行器当作跨阶段恢复目标。""" + assert recovery_plan_for_action( + current_gate='inventory_matching', + action_code='retry_inventory_from_excel', + ) is None + + +def test_cross_stage_recovery_action_is_invalid_outside_inventory_matching(app): + """跨阶段库存恢复动作在错误 Gate 上必须返回稳定 RecoveryPlan 错误码。""" + from app.core.errors import ValidationError + from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome + from app.services.shipping_notice.process_gate_recovery_service import request_gate_action + from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version + from tests.test_shipping_process_gate_service import _seed_workflow_version + from app import db + from app.models import ShippingProcessGate + + with app.app_context(): + user, _review_case_id, task_id = _seed_workflow_version(suffix='v2-cross-stage-invalid') + execution = ensure_execution_for_workflow_version( + task_id=int(task_id), + ) + apply_gate_outcome( + execution=execution, gate_code='inventory_preparation', passed=False, + blocking_reason_code='inventory_snapshot_prepare_failed', effective_result={}, + force=True, idempotency_key='v2-cross-stage-seed', + ) + gate = ShippingProcessGate.query.filter_by( + execution_id=int(execution.id), gate_code='inventory_preparation', + ).first() + assert gate is not None + with __import__('pytest').raises(ValidationError) as exc: + request_gate_action( + execution_no=execution.execution_no, + gate_code='inventory_preparation', + action_code='retry_inventory_from_preparation', + expected_gate_version=int(gate.evaluation_version), + idempotency_key='v2-cross-stage-invalid-action', + actor_type='user', actor_id=int(user.id), payload={}, + ) + assert exc.value.code == 'SHIPPING.RECOVERY_TARGET_INVALID' + + +def test_gate_projection_exposes_implementation_status(app, monkeypatch): + """单 Gate Projection 必须透传服务端实现状态,避免前端猜测。""" + from types import SimpleNamespace + + gate = SimpleNamespace( + id=1, gate_code='layout_parsing', sequence_no=2, status='blocked_retryable', + evaluation_version=1, input_fingerprint=None, blocking_reason_code='layout_parse_failed', + blocking_reason_json=None, recommendation_json=None, effective_result_json={}, + findings_json=None, next_action_code='retry_layout_parsing', passed_at=None, + invalidated_at=None, latest_attempt_id=None, + ) + monkeypatch.setattr('app.services.shipping_notice.process_gate_projection.ShippingProcessGateAttempt.query.get', lambda _id: None, raising=False) + projected = serialize_process_gate(gate, include_diagnostics=False) + assert projected['implementation_status'] == 'supported' diff --git a/backend/tests/test_shipping_process_gate_fault_injection.py b/backend/tests/test_shipping_process_gate_fault_injection.py index 137e647e..2048c657 100644 --- a/backend/tests/test_shipping_process_gate_fault_injection.py +++ b/backend/tests/test_shipping_process_gate_fault_injection.py @@ -25,10 +25,9 @@ from tests.test_shipping_process_gate_service import _seed_workflow_version def test_ten_identical_recovery_clicks_create_one_attempt(app): """同一幂等键连点十次只产生一个 Attempt。""" with app.app_context(): - _user, item, version = _seed_workflow_version(suffix='fault1') + _user, _case_id, task_id = _seed_workflow_version(suffix='fault1') execution = ensure_execution_for_workflow_version( - workflow_item_id=int(item.id), - workflow_item_version_id=int(version.id), + task_id=int(task_id), ) apply_gate_outcome( execution=execution, @@ -71,10 +70,9 @@ def test_ten_identical_recovery_clicks_create_one_attempt(app): def test_active_attempt_blocks_second_queue(app): """已有活动 Attempt 时第二次不同幂等键必须 Conflict。""" with app.app_context(): - _user, item, version = _seed_workflow_version(suffix='fault2') + _user, _case_id, task_id = _seed_workflow_version(suffix='fault2') execution = ensure_execution_for_workflow_version( - workflow_item_id=int(item.id), - workflow_item_version_id=int(version.id), + task_id=int(task_id), ) apply_gate_outcome( execution=execution, @@ -120,10 +118,9 @@ def test_audit_failure_rolls_back_gate_queue(app, monkeypatch): 核心逻辑:monkeypatch record_fulfillment_audit 抛错,断言 queue 抛出且无 Attempt 行。 """ with app.app_context(): - _user, item, version = _seed_workflow_version(suffix='fault3') + _user, _case_id, task_id = _seed_workflow_version(suffix='fault3') execution = ensure_execution_for_workflow_version( - workflow_item_id=int(item.id), - workflow_item_version_id=int(version.id), + task_id=int(task_id), ) apply_gate_outcome( execution=execution, @@ -167,10 +164,9 @@ def test_request_gate_action_rejects_forbidden_controls(app): from app.core.errors import ValidationError with app.app_context(): - _user, item, version = _seed_workflow_version(suffix='fault4') + _user, _case_id, task_id = _seed_workflow_version(suffix='fault4') execution = ensure_execution_for_workflow_version( - workflow_item_id=int(item.id), - workflow_item_version_id=int(version.id), + task_id=int(task_id), ) apply_gate_outcome( execution=execution, diff --git a/backend/tests/test_shipping_process_gate_lease.py b/backend/tests/test_shipping_process_gate_lease.py index 8a76ebd5..073c3493 100644 --- a/backend/tests/test_shipping_process_gate_lease.py +++ b/backend/tests/test_shipping_process_gate_lease.py @@ -36,10 +36,12 @@ def test_lease_takeover_after_stale_heartbeat(app, monkeypatch): 'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job', lambda **kwargs: 0, ) - _user, item, version = _seed_workflow_version(suffix='lease1') + _user, review_case_id, task_id = _seed_workflow_version(suffix='lease1') execution = ensure_execution_for_workflow_version( - workflow_item_id=int(item.id), - workflow_item_version_id=int(version.id), + review_case_id=review_case_id, + task_id=task_id, + actor_type='system', + actor_id='lease-test', ) attempt = queue_gate_attempt( execution_no=execution.execution_no, @@ -72,10 +74,12 @@ def test_heartbeat_rejects_foreign_lease(app): from app.core.errors import ConflictError with app.app_context(): - _user, item, version = _seed_workflow_version(suffix='lease2') + _user, review_case_id, task_id = _seed_workflow_version(suffix='lease2') execution = ensure_execution_for_workflow_version( - workflow_item_id=int(item.id), - workflow_item_version_id=int(version.id), + review_case_id=review_case_id, + task_id=task_id, + actor_type='system', + actor_id='lease-test', ) attempt = queue_gate_attempt( execution_no=execution.execution_no, @@ -110,10 +114,12 @@ def test_sync_manual_open_via_claim_and_run(app, monkeypatch): 'app.services.shipping_notice.process_gate_job_service.enqueue_gate_attempt_job', lambda **kwargs: 0, ) - _user, item, version = _seed_workflow_version(suffix='lease3') + _user, review_case_id, task_id = _seed_workflow_version(suffix='lease3') execution = ensure_execution_for_workflow_version( - workflow_item_id=int(item.id), - workflow_item_version_id=int(version.id), + review_case_id=review_case_id, + task_id=task_id, + actor_type='system', + actor_id='lease-test', ) # 先阻断冻结门禁,再排队人工打开动作。 from app.services.shipping_notice.process_gate_bridge import apply_gate_outcome diff --git a/backend/tests/test_shipping_process_gate_retry_cap.py b/backend/tests/test_shipping_process_gate_retry_cap.py index fdde94de..a01a7ed3 100644 --- a/backend/tests/test_shipping_process_gate_retry_cap.py +++ b/backend/tests/test_shipping_process_gate_retry_cap.py @@ -1,10 +1,10 @@ """ tests/test_shipping_process_gate_retry_cap.py -用途:验证门禁技术失败跨 force_new Job 累计重试上限,并在耗尽后收口 Attempt/Gate。 +用途:验证门禁技术失败只执行一次,并在失败后收口 Attempt/Gate,等待人工重试。 依赖:Flask testing app、run_shipping_process_gate handler、process_gate_service。 -逻辑:mock claim_and_run 持续抛错;按 failed Job 累计;断言 TECHNICAL_RETRIES 次后 - Attempt/Gate 进入 failed_terminal、input_snapshot Hash 一致、且不再入队重试 Job。 +逻辑:mock claim_and_run 抛错;断言只产生一个失败 Job,Attempt 失败、Gate 进入 blocked_retryable, + 并保留人工恢复入口。 """ from __future__ import annotations @@ -26,14 +26,13 @@ from app.services.shipping_notice.process_gate_service import ( from tests.test_shipping_process_gate_service import _seed_workflow_version -def test_technical_retries_cap_across_force_new_jobs(app): - """跨 Job 累计失败达到上限后必须 failed_terminal,且不再新建 queued Job。""" +def test_gate_failure_does_not_auto_retry(app): + """门禁失败只产生一个失败 Job,并保留原 Gate 的人工恢复入口。""" with app.app_context(): - app.config['SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES'] = 3 - _user, item, version = _seed_workflow_version(suffix='retrycap') + _user, review_case_id, task_id = _seed_workflow_version(suffix='retrycap') execution = ensure_execution_for_workflow_version( - workflow_item_id=int(item.id), - workflow_item_version_id=int(version.id), + review_case_id=review_case_id, + task_id=task_id, ) attempt = queue_gate_attempt( execution_no=execution.execution_no, @@ -47,49 +46,53 @@ def test_technical_retries_cap_across_force_new_jobs(app): first_job_id = enqueue_gate_attempt_job(attempt_id=int(attempt.id)) db.session.commit() attempt_id = int(attempt.id) + rollback_seen = {'value': False} + real_get = db.session.get + + def _get_after_rollback(model, ident): + """模拟 PostgreSQL aborted transaction:Attempt 只能在 rollback 后重读。""" + if model is ShippingProcessGateAttempt and not rollback_seen['value']: + raise AssertionError('attempt reloaded before rollback') + return real_get(model, ident) + + real_rollback = db.session.rollback + + def _record_rollback(): + rollback_seen['value'] = True + return real_rollback() with patch( 'app.jobs.handlers.shipping_process_gate.claim_and_run_gate_attempt', side_effect=RuntimeError('boom https://erp.example.com/x?token=abc'), + ), patch.object(db.session, 'get', side_effect=_get_after_rollback), patch.object( + db.session, 'rollback', side_effect=_record_rollback, ): - for round_idx in range(5): - attempt_row = db.session.get(ShippingProcessGateAttempt, attempt_id) - assert attempt_row is not None - if attempt_row.status in {'failed', 'succeeded', 'cancelled'}: - break - job_id = int(attempt_row.job_id or 0) - if job_id <= 0: - job_id = enqueue_gate_attempt_job(attempt_id=attempt_id, force_new=True) - db.session.commit() - job = db.session.get(Job, job_id) - assert job is not None - job.status = 'running' - job.attempts = 1 - attempt_row.status = 'running' - gate = db.session.get(ShippingProcessGate, int(attempt_row.gate_id)) - if gate is not None: - gate.status = 'running' - db.session.commit() + job = db.session.get(Job, int(first_job_id)) + assert job is not None + job.status = 'running' + job.attempts = 1 + attempt.status = 'running' + gate = db.session.get(ShippingProcessGate, int(attempt.gate_id)) + if gate is not None: + gate.status = 'running' + db.session.commit() - ctx = MagicMock() - ctx.extras = {'worker_label': f'retry-cap-worker-{round_idx}'} - run_shipping_process_gate(ctx, {'attempt_id': attempt_id, 'job_id': job_id}) + ctx = MagicMock() + ctx.extras = {'worker_label': 'retry-cap-worker'} + run_shipping_process_gate(ctx, {'attempt_id': attempt_id, 'job_id': int(first_job_id)}) + + assert rollback_seen['value'] is True attempt_final = db.session.get(ShippingProcessGateAttempt, attempt_id) gate_final = db.session.get(ShippingProcessGate, int(attempt_final.gate_id)) assert attempt_final is not None assert attempt_final.status == 'failed' assert gate_final is not None - assert gate_final.status == 'failed_terminal' - assert attempt_final.error_code == 'TECHNICAL_RETRY_EXHAUSTED' + assert gate_final.status == 'blocked_retryable' + assert gate_final.next_action_code == 'retry_layout_parsing' + assert attempt_final.error_code == 'TECHNICAL_FAILURE' # 敏感 URL 不得原样落库 assert 'erp.example.com' not in str(attempt_final.error_summary or '') - # [ASSERT] 技术重试不得污染业务输入快照,Hash 须与正文一致 - snap = attempt_final.input_snapshot_json if isinstance(attempt_final.input_snapshot_json, dict) else {} - assert 'technical_retry_count' not in snap - from app.services.shipping_notice.process_gate_service import _stable_hash - assert attempt_final.input_snapshot_hash == _stable_hash(snap) - failed_jobs = ( Job.query .filter_by( @@ -99,7 +102,7 @@ def test_technical_retries_cap_across_force_new_jobs(app): ) .count() ) - assert failed_jobs == 3 + assert failed_jobs == 1 queued_jobs = ( Job.query .filter_by( diff --git a/backend/tests/test_shipping_process_gate_service.py b/backend/tests/test_shipping_process_gate_service.py index 94353dec..c3602d4f 100644 --- a/backend/tests/test_shipping_process_gate_service.py +++ b/backend/tests/test_shipping_process_gate_service.py @@ -399,7 +399,75 @@ def test_each_gate_supports_passed_manual_blocked_and_technical_failed(app, gate assert terminal.status == 'failed_terminal' +def test_business_sync_reuses_same_gate_active_attempt(app): + """Gate 执行器同步同门业务事实时不得递归创建第二个 Attempt。""" + with app.app_context(): + _user, review_case_id, task_id = _seed_workflow_version(suffix='activefactsync') + execution = ensure_execution_for_workflow_version( + review_case_id=review_case_id, + task_id=task_id, + ) + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='inventory_preparation', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='active-fact-sync', + input_snapshot={ + 'action_code': 'retry_inventory_preparation', + 'payload': {'actor_user_id': 1}, + }, + ) + from app.services.shipping_notice.process_gate_service import mark_attempt_running + mark_attempt_running(attempt_id=int(attempt.id), worker_id='active-fact-sync') + gate = sync_gate_from_business_result( + execution_no=execution.execution_no, + gate_code='inventory_preparation', + passed=False, + blocking_reason_code='inventory_file_missing', + effective_result_json={'findings': [], 'has_inventory_lines': False}, + idempotency_key='nested-fact-sync-must-not-queue', + ) + + assert gate.status == 'running' + assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1 + + +def test_force_business_sync_uses_current_gate_version(app): + """强制重评不得回放失效前的固定幂等 Attempt。""" + with app.app_context(): + _user, review_case_id, task_id = _seed_workflow_version(suffix='forceversion') + execution = ensure_execution_for_workflow_version( + review_case_id=review_case_id, + task_id=task_id, + ) + first = apply_gate_outcome( + execution=execution, + gate_code='task_creation', + passed=True, + effective_result={'findings': [], 'task_no': 'T-1'}, + idempotency_key='fixed-task-sync', + force=True, + ) + assert first is not None and first.status == 'passed' + first.status = 'invalidated' + first.blocking_reason_code = 'gate_invalidated' + first.evaluation_version = int(first.evaluation_version) + 1 + db.session.flush() + + second = apply_gate_outcome( + execution=execution, + gate_code='task_creation', + passed=True, + effective_result={'findings': [], 'task_no': 'T-1'}, + idempotency_key='fixed-task-sync', + force=True, + ) + + assert second is not None and second.status == 'passed' + assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(second.id)).count() == 2 def test_idempotent_queue_replays_same_attempt(gate_execution): diff --git a/backend/tests/test_shipping_process_recovery_plan.py b/backend/tests/test_shipping_process_recovery_plan.py new file mode 100644 index 00000000..05dcfa01 --- /dev/null +++ b/backend/tests/test_shipping_process_recovery_plan.py @@ -0,0 +1,795 @@ +""" +用途:验证 RecoveryPlan 与库存准备谱系的结构化合同。 +依赖:SQLAlchemy metadata、ShippingProcessRecoveryPlan、库存准备/Mapping 模型。 +逻辑:只验证模型约束和关键状态字段,不触发外部 RPA 或业务恢复副作用。 +""" + +from __future__ import annotations + +from sqlalchemy import UniqueConstraint + +from app.models import ( + ShippingInventoryMapping, + ShippingInventoryPreparationAttempt, + ShippingInventoryPreparationSourceAttempt, + ShippingProcessRecoveryPlan, +) + + +def _unique_names(model) -> set[str]: + return { + str(item.name) + for item in model.__table__.constraints + if isinstance(item, UniqueConstraint) and item.name + } + + +def test_recovery_plan_has_idempotent_business_identity(): + """RecoveryPlan 必须以 plan_no 和 execution+idempotency_key 形成业务幂等边界。""" + names = _unique_names(ShippingProcessRecoveryPlan) + assert 'uq_shipping_process_recovery_plans_no' in names + assert 'uq_shipping_process_recovery_plans_execution_idempotency' in names + assert 'status' in ShippingProcessRecoveryPlan.__table__.c + assert 'invalidation_plan_json' in ShippingProcessRecoveryPlan.__table__.c + + +def test_inventory_preparation_is_task_round_with_per_source_uniqueness(): + """准备轮次和逐源 Attempt 均必须保留不可混淆的唯一范围。""" + assert 'uq_shipping_inventory_preparation_task_attempt' in _unique_names(ShippingInventoryPreparationAttempt) + assert 'uq_shipping_inventory_preparation_source_attempt' in _unique_names(ShippingInventoryPreparationSourceAttempt) + assert {'source_code', 'status', 'inventory_file_id', 'rpa_attempt_id'} <= set( + ShippingInventoryPreparationSourceAttempt.__table__.c.keys() + ) + + +def test_rpa_attempt_status_updates_its_bound_preparation_source(app): + """RPA 回调必须更新既有 SourceAttempt,并聚合 PreparationAttempt 状态。""" + from app import db + from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt + from app.services.shipping_notice.inventory_recovery_service import ( + create_inventory_preparation_round, + sync_inventory_preparation_round, + sync_preparation_source_from_rpa_attempt, + ) + + task = ShippingNotice(task_no='SN-PREP-LINEAGE-1', process_status='waiting_inventory') + db.session.add(task) + db.session.flush() + preparation = create_inventory_preparation_round( + task=task, execution_id=88, recovery_plan_id=None, + action_code='retry_inventory_preparation', source_codes=['DBS'], gate_attempt_id=301, + ) + rpa = ShippingTaskInventoryRpaAttempt( + task_no=task.task_no, source_code='DBS', attempt_no=1, source_run_no='PSR-LINEAGE-1', + status='queued', lease_token='lease-lineage', extra_json={}, callback_payload_json={}, + ) + db.session.add(rpa) + db.session.flush() + sync_inventory_preparation_round( + preparation_attempt=preparation, + result={'pending_source_codes': ['DBS'], 'source_attempts': {'DBS': {'attempt_id': rpa.id}}}, + ) + + sync_preparation_source_from_rpa_attempt(rpa_attempt_id=rpa.id, rpa_status='succeeded') + + source = preparation.source_attempts[0] + assert preparation.input_snapshot_json['gate_attempt_id'] == 301 + assert preparation.gate_attempt_id == 301 + assert source.rpa_attempt_id == rpa.id + assert source.status == 'ready' + assert preparation.status == 'succeeded' + + +def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, app): + """库存准备 Trigger 必须把 GateAttempt 身份原样带到 RPA。""" + from app import db + from app.models import ShippingNotice, ShippingProcessGate + from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version + from app.services.shipping_notice import per_source_rpa_service + + task = ShippingNotice(task_no='SN-PREP-TRIGGER-IDENTITY', process_status='waiting_inventory') + db.session.add(task) + db.session.flush() + execution = ensure_execution_for_workflow_version(task_id=int(task.id), actor_type='system') + execution.current_gate_code = 'inventory_preparation' + task.active_process_execution_id = int(execution.id) + db.session.flush() + gate = ShippingProcessGate.query.filter_by(execution_id=int(execution.id), gate_code='inventory_preparation').first() + assert gate is not None + db.session.commit() + captured = {} + monkeypatch.setattr( + per_source_rpa_service, + 'write_inventory_export_trigger_for_task', + lambda task_no, source, payload=None: captured.update(payload or {}) or 'trigger.json', + ) + monkeypatch.setattr('app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source', lambda task: {'source_code': 'DBS', 'warehouse_id': 'WH-1'}) + monkeypatch.setattr(per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['DBS']) + monkeypatch.setattr(per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False) + monkeypatch.setattr(per_source_rpa_service, '_latest_attempt', lambda *args, **kwargs: None) + result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='auto') + assert result.pending_source_codes == ['DBS'] + assert captured['execution_id'] == task.active_process_execution_id + assert captured['gate_id'] == gate.id + assert captured['callback_id'].endswith(':C1') + + +def test_per_source_callback_rejects_candidate_set_identity_mismatch(app): + """旧 CandidateSet 回调必须在写入库存事实前被拒绝。""" + from app import db + from app.models import ( + ShippingInventoryCandidateSet, + ShippingNotice, + ShippingTaskInventoryRpaAttempt, + ) + from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler + + task = ShippingNotice(task_no='SN-PREP-CALLBACK-IDENTITY', process_status='waiting_inventory') + db.session.add(task) + db.session.flush() + current = ShippingInventoryCandidateSet( + task_id=task.id, set_version=2, lifecycle_status='frozen', input_fingerprint='b' * 64, + ) + db.session.add(current) + db.session.flush() + task.active_inventory_candidate_set_id = current.id + attempt = ShippingTaskInventoryRpaAttempt( + task_no=task.task_no, + source_code='DBS', + attempt_no=1, + source_run_no='PSR-SN-PREP-CALLBACK-IDENTITY-DBS-A1-X', + status='running', + callback_id='PSR-SN-PREP-CALLBACK-IDENTITY-DBS-A1-X:C1', + lease_token='lease-1', + extra_json={ + 'candidate_set_id': 999, + 'execution_id': 88, + 'gate_id': 901, + 'expected_warehouse_id': 'WH-1', + }, + ) + db.session.add(attempt) + db.session.commit() + + result, handled = per_source_callback_handler( + task, + source_code='DBS', + run_no=attempt.source_run_no, + callback_payload={ + 'schema_version': 'shipping_inventory_rpa.v2', + 'callback_id': 'PSR-SN-PREP-CALLBACK-IDENTITY-DBS-A1-X:C2', + 'task_no': task.task_no, + 'source_code': 'DBS', + 'source_run_no': attempt.source_run_no, + 'attempt_no': 1, + 'lease_token': 'lease-1', + 'candidate_set_id': current.id, + 'execution_id': 88, + 'gate_id': 901, + 'expected_warehouse_id': 'WH-1', + 'status': 'success', + }, + ) + + assert result == 'identity_mismatch' + assert handled is attempt + db.session.refresh(attempt) + assert attempt.status == 'running' + + +def test_rpa_report_inventory_fails_closed_on_per_source_identity_mismatch(app, monkeypatch): + """统一单源回调入口遇到身份错配时必须拒绝且不得落入旧库存写入路径。""" + from app import db + from app.models import ShippingNotice, ShippingTaskEvent + from app.services.shipping_notice import inventory_rpa_workflow + + task = ShippingNotice(task_no='SNCALLBACKIDENTITYENTRY', process_status='waiting_inventory') + db.session.add(task) + db.session.commit() + + monkeypatch.setattr( + inventory_rpa_workflow, + '_validate_single_source_v2_contract', + lambda task, payload: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.per_source_rpa_service.per_source_callback_handler', + lambda task, source_code, run_no, callback_payload: ('identity_mismatch', object()), + ) + legacy_called = {'value': False} + monkeypatch.setattr( + inventory_rpa_workflow, + '_lock_task_for_rpa_callback', + lambda task: legacy_called.__setitem__('value', True) or task, + ) + + response = inventory_rpa_workflow.rpa_report_inventory({ + 'schema_version': 'shipping_inventory_rpa.v2', + 'callback_id': 'PSR-SNCALLBACKIDENTITYENTRY-DBS-A1-X:C1', + 'task_no': task.task_no, + 'task_id': task.task_no, + 'source_code': 'DBS', + 'source_run_no': 'PSR-SNCALLBACKIDENTITYENTRY-DBS-A1-X', + 'run_no': 'PSR-SNCALLBACKIDENTITYENTRY-DBS-A1-X', + 'attempt_no': 1, + 'lease_token': 'lease-invalid', + 'candidate_set_id': 999, + 'execution_id': 88, + 'gate_id': 901, + 'status': 'success', + }) + + assert response['status'] == 'failed' + assert response['data']['error_code'] == 'callback_identity_mismatch' + assert legacy_called['value'] is False + assert db.session.query(ShippingTaskEvent).filter_by( + task_id=task.id, + event_type='rpa_callback_rejected', + ).count() == 1 + + +def test_rpa_report_inventory_parses_per_source_run_with_hyphenated_task_no(app, monkeypatch): + """PSR run_no 中 task_no 可含连字符,入口仍必须解析出真实 source_code。""" + from app import db + from app.models import ShippingNotice + from app.services.shipping_notice import inventory_rpa_workflow + + task = ShippingNotice(task_no='SN-2026-001', process_status='waiting_inventory') + db.session.add(task) + db.session.commit() + captured = {} + + monkeypatch.setattr(inventory_rpa_workflow, '_validate_single_source_v2_contract', lambda task, payload: None) + monkeypatch.setattr( + 'app.services.shipping_notice.per_source_rpa_service.per_source_callback_handler', + lambda task, source_code, run_no, callback_payload: captured.update(source_code=source_code, run_no=run_no) or ('identity_mismatch', object()), + ) + + inventory_rpa_workflow.rpa_report_inventory({ + 'schema_version': 'shipping_inventory_rpa.v2', + 'callback_id': 'PSR-SN-2026-001-DBS-A1-X:C1', + 'task_no': task.task_no, + 'task_id': task.task_no, + 'source_code': 'DBS', + 'source_run_no': 'PSR-SN-2026-001-DBS-A1-X', + 'run_no': 'PSR-SN-2026-001-DBS-A1-X', + 'attempt_no': 1, + 'lease_token': 'lease-invalid', + 'candidate_set_id': 999, + 'execution_id': 88, + 'gate_id': 901, + 'status': 'success', + }) + + assert captured == {'source_code': 'DBS', 'run_no': 'PSR-SN-2026-001-DBS-A1-X'} + + +def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch(app, monkeypatch): + """批量成功项也必须先通过逐源身份校验,不能先入库再拒绝。""" + from app import db + from app.models import ShippingNotice, ShippingTaskEvent + from app.services.shipping_notice import inventory_rpa_workflow + + task = ShippingNotice(task_no='SNCALLBACKBATCHIDENTITY', process_status='waiting_inventory') + db.session.add(task) + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.per_source_rpa_service.per_source_callback_handler', + lambda task, source_code, run_no, callback_payload: ('identity_mismatch', object()), + ) + legacy_called = {'value': False} + monkeypatch.setattr( + inventory_rpa_workflow, + '_lock_task_for_rpa_callback', + lambda task: legacy_called.__setitem__('value', True) or task, + ) + + response = inventory_rpa_workflow.rpa_report_inventory_batch({ + 'schema_version': 'shipping_inventory_rpa.v2', + 'callback_id': 'batch-callback-identity', + 'batch_run_no': 'BATCH-CALLBACK-IDENTITY', + 'results': [{ + 'task_no': task.task_no, + 'source_code': 'DBS', + 'source_run_no': 'PSR-SNCALLBACKBATCHIDENTITY-DBS-A1-X', + 'callback_id': 'PSR-SNCALLBACKBATCHIDENTITY-DBS-A1-X:C1', + 'status': 'success', + 'warehouse_id': 'WH-1', + }], + }) + + assert response['failed_count'] == 1 + assert response['data']['failed'][0]['error_code'] == 'callback_identity_mismatch' + assert legacy_called['value'] is False + assert db.session.query(ShippingTaskEvent).filter_by( + task_id=task.id, + event_type='rpa_callback_rejected', + ).count() == 1 + + +def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch): + """正式库存准备 Gate 执行必须创建 Preparation/Source lineage 并据此通过 Gate。""" + from app import db + from app.models import ( + ShippingInventoryCandidateSet, + ShippingInventoryPreparationAttempt, + ShippingNotice, + ShippingProcessGate, + ShippingProcessGateAttempt, + ) + from app.services.shipping_notice.process_gate_job_service import claim_and_run_gate_attempt + from app.services.shipping_notice.process_gate_service import ( + ensure_execution_for_workflow_version, + queue_gate_attempt, + ) + + task = ShippingNotice( + task_no='SNFORMALPREPLINEAGE', + process_status='waiting_inventory', + inventory_source_code='DBS', + ) + db.session.add(task) + db.session.flush() + candidate = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='c' * 64, + ) + db.session.add(candidate) + db.session.flush() + task.active_inventory_candidate_set_id = candidate.id + execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system') + execution.candidate_set_id = candidate.id + execution.current_gate_code = 'inventory_preparation' + task.active_process_execution_id = execution.id + gate = ShippingProcessGate.query.filter_by( + execution_id=execution.id, gate_code='inventory_preparation', + ).one() + gate.status = 'pending' + gate.next_action_code = 'retry_inventory_preparation' + db.session.commit() + + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_workflow.ensure_inventory', + lambda payload: { + 'status': 'success', + 'data': { + 'rpa': { + 'all_prepared': True, + 'prepared_source_codes': ['DBS'], + 'pending_source_codes': [], + 'failed_source_codes': [], + 'source_attempts': {}, + }, + }, + }, + ) + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='inventory_preparation', + trigger_type='auto', + actor_type='system', + actor_id='test', + idempotency_key='formal-prep-lineage-1', + input_snapshot={'action_code': 'retry_inventory_preparation', 'payload': {}}, + ) + result = claim_and_run_gate_attempt(attempt_id=attempt.id, worker_id='lineage-worker') + + db.session.refresh(attempt) + db.session.refresh(gate) + preparation = ShippingInventoryPreparationAttempt.query.filter_by( + task_id=task.id, execution_id=execution.id, gate_attempt_id=attempt.id, + ).one() + assert result.get('skipped') is False + assert attempt.status == 'succeeded' + assert gate.status == 'passed' + assert preparation.status == 'succeeded' + assert len(preparation.source_attempts) == 1 + assert preparation.source_attempts[0].source_code == 'DBS' + assert preparation.source_attempts[0].status == 'ready' + assert preparation.source_attempts[0].rpa_attempt_id is None + db.session.refresh(execution) + assert execution.current_gate_code != 'inventory_preparation' + + +def test_formal_start_gate_stops_at_customer_resolution_before_inventory(app): + """正式起始 Gate 必须优先反映未完成的客户确认事实。""" + from app import db + from app.models import ShippingInventoryCandidateSet, ShippingNotice + from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate + + task = ShippingNotice( + task_no='SNSTARTCUSTOMERPENDING', + process_status='created', + current_order_extraction_id=101, + order_snapshot_id=201, + customer_resolution_status='pending', + ) + db.session.add(task) + db.session.flush() + candidate = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='d' * 64, + ) + db.session.add(candidate) + db.session.flush() + + assert determine_formal_start_gate(task, candidate_set=candidate) == 'customer_resolution' + + +def test_formal_start_gate_stops_at_field_conflict_before_inventory(app): + """正式起始 Gate 必须优先反映尚未解决的订单字段冲突。""" + from app import db + from app.models import ShippingInventoryCandidateSet, ShippingNotice, ShippingTaskFieldConflict + from app.services.shipping_notice.auto_progress_controller import determine_formal_start_gate + + task = ShippingNotice( + task_no='SNSTARTFIELDCONFLICT', + process_status='created', + current_order_extraction_id=101, + order_snapshot_id=201, + customer_resolution_status='confirmed', + ) + db.session.add(task) + db.session.flush() + db.session.add(ShippingTaskFieldConflict( + task_id=task.id, field_name='part_number', status='open', + )) + candidate = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='e' * 64, + ) + db.session.add(candidate) + db.session.flush() + + assert determine_formal_start_gate(task, candidate_set=candidate) == 'field_conflict_resolution' + + +def test_candidate_refreeze_invalidates_formal_gate_attempt_and_job(app): + """候选重冻结必须同时终止旧正式 GateAttempt 与其 Job。""" + from app import db + from app.models import Job, ShippingInventoryCandidateSet, ShippingNotice, ShippingProcessGateAttempt + from app.services.shipping_notice.auto_progress_controller import supersede_auto_progress_for_candidate_refreeze + from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version, queue_gate_attempt + + task = ShippingNotice(task_no='SNCANDIDATEREFREEZEATTEMPT', process_status='waiting_inventory') + db.session.add(task) + db.session.flush() + old_candidate = ShippingInventoryCandidateSet( + task_id=task.id, set_version=1, lifecycle_status='frozen', input_fingerprint='f' * 64, + ) + db.session.add(old_candidate) + db.session.flush() + task.active_inventory_candidate_set_id = old_candidate.id + execution = ensure_execution_for_workflow_version(task_id=task.id, actor_type='system') + execution.candidate_set_id = old_candidate.id + task.active_process_execution_id = execution.id + db.session.flush() + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='inventory_preparation', + trigger_type='auto', actor_type='system', actor_id='test', + idempotency_key='candidate-refreeze-attempt-1', + input_snapshot={'action_code': 'retry_inventory_preparation', 'payload': {}}, + ) + job = Job.query.filter_by(id=attempt.job_id).one_or_none() + if job is None: + job = Job( + domain='shipping_notice', job_type='shipping_process_gate', task_id=task.id, + execution_id=execution.id, gate_id=attempt.gate_id, candidate_set_id=old_candidate.id, + status='queued', payload_json={'attempt_id': attempt.id}, business_ref='candidate-refreeze-job', + ) + db.session.add(job) + db.session.flush() + attempt.job_id = job.id + db.session.commit() + + supersede_auto_progress_for_candidate_refreeze(task) + db.session.commit() + db.session.refresh(attempt) + db.session.refresh(job) + + assert attempt.status in {'superseded', 'cancelled'} + assert job.status == 'cancelled' + + +def test_legacy_workspace_forwarding_audit_is_structured(app): + """旧工作台动作转发必须留下 legacy_forwarded 入口审计。""" + from app import db + from app.models import ShippingNotice, ShippingTaskEvent + from app.services.shipping_notice.auto_progress_controller import audit_legacy_forwarded_entrypoint + + task = ShippingNotice(task_no='SNLEGACYFORWARDAUDIT', process_status='waiting_inventory') + db.session.add(task) + db.session.flush() + + audit_legacy_forwarded_entrypoint( + task=task, + action_code='match_inventory', + actor_id=42, + request_id='req-legacy-forward', + ) + row = ShippingTaskEvent.query.filter_by( + task_id=task.id, + event_type='shipping_legacy_entrypoint_forwarded', + ).one() + assert row.source == 'workspace_api' + assert row.actor_id == 42 + assert row.request_id == 'req-legacy-forward' + assert row.detail_json == { + 'entrypoint': 'legacy_forwarded', + 'action_code': 'match_inventory', + } + + +def test_apx_runtime_audit_is_read_only_and_counts_active_states(app): + """APX 清点只读统计运行中记录,不修改历史 Execution/Job。""" + from app import db + from app.models import Job, ShippingNotice, ShippingProcessExecution + from app.services.shipping_notice.apx_runtime_audit import audit_apx_runtime_state + + task = ShippingNotice(task_no='SN-APX-AUDIT', process_status='waiting_inventory') + db.session.add(task) + db.session.flush() + active = ShippingProcessExecution( + execution_no='APX-20260811-ACTIVE', task_id=task.id, status='active', + current_gate_code='inventory_snapshots_ready', + ) + historical = ShippingProcessExecution( + execution_no='APX-20260811-HIST', task_id=task.id, status='completed', + current_gate_code='inventory_matched', + ) + db.session.add_all([active, historical]) + db.session.flush() + job = Job( + domain='shipping_notice', job_type='shipping_auto_progress', task_id=task.id, + execution_id=active.id, status='queued', business_ref='APX-20260811-ACTIVE', + ) + db.session.add(job) + db.session.commit() + + result = audit_apx_runtime_state() + + assert result['execution']['active_count'] == 1 + assert result['execution']['historical_count'] == 1 + assert result['job']['active_count'] == 1 + assert ShippingProcessExecution.query.filter_by(id=active.id).one().status == 'active' + assert Job.query.filter_by(id=job.id).one().status == 'queued' + + +def test_inventory_mapping_is_versioned_and_immutable_by_shape(): + """Mapping 必须按文件+版本唯一,旧版本通过 superseded_by_id 留谱系。""" + assert 'uq_shipping_inventory_mapping_file_version' in _unique_names(ShippingInventoryMapping) + assert {'version', 'status', 'mapping_json', 'input_fingerprint', 'superseded_by_id'} <= set( + ShippingInventoryMapping.__table__.c.keys() + ) + + +def test_process_execution_projection_exposes_server_owned_recovery_targets(app): + """Projection 必须只读暴露服务端 RecoveryPlan 目标,不让客户端自行推导 target Gate。""" + from app import db + from app.models import ShippingProcessExecution, ShippingProcessGate + from app.services.shipping_notice.process_gate_projection import serialize_process_execution + + with app.app_context(): + execution = ShippingProcessExecution( + execution_no='EXE-PROJECTION-RECOVERY', status='blocked', + current_gate_code='inventory_matching', lock_version=1, + ) + db.session.add(execution) + db.session.flush() + db.session.add(ShippingProcessGate( + execution_id=execution.id, gate_code='inventory_matching', sequence_no=15, + status='blocked_manual', evaluation_version=2, + )) + db.session.flush() + projection = serialize_process_execution(execution) + targets = {item['action_code']: item for item in projection['recovery_targets']} + gate_targets = {item['action_code']: item for item in projection['current_gate']['recovery_targets']} + assert targets['retry_inventory_from_preparation']['target_gate'] == 'inventory_preparation' + assert gate_targets['retry_inventory_from_preparation']['target_gate'] == 'inventory_preparation' + assert targets['retry_inventory_from_field_mapping']['resume_after_gate'] == 'inventory_matching' + assert projection['active_recovery_plans'] == [] + + +def test_recovery_plan_outcome_mapping_is_terminal_or_waiting(): + """RecoveryPlan 必须将 Attempt 结果映射到可审计的计划状态。""" + from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt + + class Plan: + status = 'queued' + action_code = 'retry_inventory_from_preparation' + resume_after_gate = 'inventory_sufficiency' + started_at = None + completed_at = None + failure_code = None + failure_detail_json = None + + plan = Plan() + complete_recovery_plan_for_attempt(plan=plan, outcome='passed') + assert plan.status == 'succeeded' + assert plan.completed_at is not None + + plan = Plan() + complete_recovery_plan_for_attempt(plan=plan, outcome='waiting_external') + assert plan.status == 'waiting_external' + assert plan.completed_at is None + + +def test_current_inventory_rematch_shortage_completes_recovery_plan(): + """当前库存重匹配已完成但仍有缺口时,计划必须完成而非永久占用活动恢复位。""" + from app.services.shipping_notice.recovery_plan_service import complete_recovery_plan_for_attempt + + class Plan: + status = 'queued' + action_code = 'retry_inventory_from_matching' + resume_after_gate = 'inventory_sufficiency' + started_at = None + completed_at = None + failure_code = None + failure_detail_json = None + + plan = Plan() + complete_recovery_plan_for_attempt( + plan=plan, + outcome='blocked_manual', + business_result_code='inventory_shortage_review_required', + ) + + # 关键断言:重新匹配动作已完成;正式流程仍可由 Gate 16 表达缺口人工复核。 + assert plan.status == 'succeeded' + assert plan.completed_at is not None + + +def test_inventory_rematch_shortage_is_business_result_not_technical_failure(monkeypatch): + """库存 14、缺口 16 时,匹配 Attempt 成功收口到缺口复核。""" + from types import SimpleNamespace + from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_matching + + task = SimpleNamespace( + match_status='partial', + shortage_json={'lines': [{'available_qty': 14, 'shortage_qty': 16}]}, + ) + monkeypatch.setattr( + 'app.models.ShippingNotice.query', + SimpleNamespace(get=lambda _task_id: task), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.fulfillment_workflow.match_inventory', + lambda _payload: {'status': 'needs_human', 'message': '当前 Gate 需要人工处理。'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', + lambda **_: None, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._task_payload', + lambda _execution, _payload: {'_orchestrator_internal_dispatch': True}, + ) + + result = _handle_retry_inventory_matching( + execution=SimpleNamespace(task_id=13), + gate=SimpleNamespace(gate_code='inventory_sufficiency'), + payload={'actor_user_id': 1}, + ) + + assert result['outcome'] == 'blocked_manual' + assert result['blocking_reason_code'] == 'inventory_shortage_review_required' + assert result['effective_result_json']['shortage']['lines'][0] == { + 'available_qty': 14, + 'shortage_qty': 16, + } + + +def test_field_mapping_recovery_does_not_create_preparation_round(monkeypatch): + """字段映射恢复必须停留在 mapping handler,不得误建库存准备轮次。""" + from types import SimpleNamespace + from app.services.shipping_notice.process_gate_executor import _dispatch_action + + called = {'preparation': 0, 'matching': 0} + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_preparation', + lambda **_: called.__setitem__('preparation', called['preparation'] + 1) or {'outcome': 'passed'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_from_field_mapping', + lambda **_: {'outcome': 'blocked_manual'}, + ) + result = _dispatch_action( + execution=object(), gate=SimpleNamespace(gate_code='inventory_matching'), + action_code='retry_inventory_from_field_mapping', payload={}, + ) + assert result['outcome'] == 'blocked_manual' + assert called['preparation'] == 0 + + +def test_field_mapping_recovery_resumes_matching_after_mapping_passes(monkeypatch): + """字段映射完成后必须重跑匹配,不能把 mapping 成功误作 matching 成功。""" + from types import SimpleNamespace + from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_from_field_mapping + + called = {'matching': 0} + monkeypatch.setattr( + 'app.services.shipping_notice.recovery_invalidation_service.invalidate_inventory_downstream', + lambda **_: {}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_field_mapping', + lambda **_: {'outcome': 'passed'}, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.process_gate_executor._handle_retry_inventory_matching', + lambda **_: called.__setitem__('matching', called['matching'] + 1) or {'outcome': 'passed'}, + ) + result = _handle_retry_inventory_from_field_mapping( + execution=object(), gate=SimpleNamespace(gate_code='inventory_matching'), payload={}, + ) + assert result['outcome'] == 'passed' + assert called['matching'] == 1 + + +def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypatch): + """Gate Attempt 内调用库存匹配时不得递归提交第二次 auto-progress。""" + from types import SimpleNamespace + from app.services.shipping_notice.process_gate_executor import _task_payload + + task = SimpleNamespace(task_no='SN-INTERNAL-DISPATCH') + monkeypatch.setattr( + 'app.models.ShippingNotice.query', + SimpleNamespace(get=lambda _task_id: task), + ) + + result = _task_payload( + SimpleNamespace(task_id=123), + {'actor_user_id': 9}, + ) + + # 关键断言:由当前 Gate Worker 直接执行匹配原子步骤,不再绕回 facade。 + assert result['_orchestrator_internal_dispatch'] is True + assert result['task_id'] == 'SN-INTERNAL-DISPATCH' + assert result['operator_id'] == 9 + + +def test_manual_business_block_is_a_successful_attempt(app): + """库存匹配已执行但存在缺口时,Attempt 成功、Gate 保持人工阻断。""" + from app import db + from app.models import ShippingProcessGateAttempt + from app.services.shipping_notice.process_gate_service import ( + complete_gate_attempt, + ensure_execution_for_workflow_version, + mark_attempt_running, + queue_gate_attempt, + ) + from tests.test_shipping_process_gate_service import _seed_workflow_version + + with app.app_context(): + _user, review_case_id, task_id = _seed_workflow_version(suffix='manual-block-success') + execution = ensure_execution_for_workflow_version( + review_case_id=review_case_id, + task_id=task_id, + ) + attempt = queue_gate_attempt( + execution_no=execution.execution_no, + gate_code='inventory_sufficiency', + trigger_type='user_retry', + actor_type='user', + actor_id=1, + idempotency_key='manual-block-success', + input_snapshot={'action_code': 'retry_inventory_from_matching', 'payload': {}}, + ) + mark_attempt_running(attempt_id=int(attempt.id), worker_id='test') + gate = complete_gate_attempt( + attempt_id=int(attempt.id), + outcome='blocked_manual', + blocking_reason_code='inventory_insufficient', + effective_result_json={ + 'match_status': 'partial', + 'available_qty': 14, + 'shortage_qty': 16, + }, + ) + db.session.flush() + + refreshed_attempt = db.session.get(ShippingProcessGateAttempt, int(attempt.id)) + # 关键断言:业务缺口不是执行器失败;数量事实保持只读并留在 Gate 结果。 + assert refreshed_attempt.status == 'succeeded' + assert gate.status == 'blocked_manual' + assert gate.effective_result_json['available_qty'] == 14 + assert gate.effective_result_json['shortage_qty'] == 16 diff --git a/backend/tests/test_shipping_processing_projection_invariants.py b/backend/tests/test_shipping_processing_projection_invariants.py index a9e67f4a..4e832487 100644 --- a/backend/tests/test_shipping_processing_projection_invariants.py +++ b/backend/tests/test_shipping_processing_projection_invariants.py @@ -10,6 +10,7 @@ backend/tests/test_shipping_processing_projection_invariants.py from __future__ import annotations from app.services.shipping_notice.processing_projection_invariants import ( + apply_user_projection_fields, build_stage_nodes, derivation_status_for_extraction_run, normalize_action_code, @@ -66,6 +67,22 @@ def test_completed_clears_write_actions_and_gate(): assert payload['available_actions'] == ['view_result'] +def test_projection_fact_read_failure_is_fail_closed(): + """关键事实读取失败时必须进入人工诊断态,不得静默返回旧动作。""" + payload = reconcile_processing_projection_facts({ + 'status': 'running', + 'stage': 'inventory_preparation', + 'source_type': 'eml', + 'projection_data_inconsistent': True, + 'available_actions': ['retry_inventory_preparation'], + }) + assert payload['status'] == 'waiting_human' + assert payload['retryable'] is False + assert payload['primary_action'] is None + assert payload['available_actions'] == [] + assert payload['blocking_reason']['code'] == 'projection_data_inconsistent' + + def test_normalize_unknown_action_codes(): """未知 / 别名动作码映射到契约或丢弃。""" assert normalize_action_code('retry_failed_documents') == 'retry' @@ -133,6 +150,47 @@ def test_download_excel_requires_excel_ready_fact(): assert 'regenerate_excel' not in with_ready +def test_artifact_gate_overrides_stale_inventory_stage_and_action(): + """Gate 18 阻断时不得继续展示旧库存匹配阶段或 match_inventory。""" + payload = reconcile_processing_projection_facts({ + 'status': 'automating', + 'stage': 'inventory_matching', + 'source_type': 'order_task', + 'shipping_notice_no': 'SN-1', + 'current_gate': { + 'gate_code': 'artifact_generation', + 'status': 'blocked_retryable', + 'next_action_code': 'regenerate_excel_artifact', + 'blocking_reason_code': 'artifact_generation_failed', + }, + 'available_actions': ['match_inventory'], + }) + assert payload['status'] == 'blocked' + assert payload['stage'] == 'excel_generating' + assert payload['stage_label_key'] == 'excel_generating' + assert payload['current_gate']['next_action_code'] == 'regenerate_excel_artifact' + assert payload['available_actions'] == ['regenerate_excel'] + + +def test_artifact_gate_primary_action_uses_gate_not_legacy_stage(): + """用户态主动作必须投影为重新生成 Excel。""" + payload = apply_user_projection_fields({ + 'status': 'blocked', + 'stage': 'excel_generating', + 'source_type': 'order_task', + 'shipping_notice_no': 'SN-1', + 'current_gate': { + 'gate_code': 'artifact_generation', + 'status': 'blocked_retryable', + 'next_action_code': 'regenerate_excel_artifact', + 'blocking_reason_code': 'artifact_generation_failed', + }, + 'available_actions': ['regenerate_excel'], + }) + assert payload['user_status'] == 'retryable' + assert payload['primary_action']['code'] == 'regenerate_excel' + + def test_map_notice_to_processing_status_stage_domain_mapping(): """BE-05:Notice 履约态映射属领域层,写/读共用。""" from types import SimpleNamespace @@ -207,3 +265,73 @@ def test_derive_available_actions_failed_adds_retry(): excel_ready=False, ) assert 'retry' in actions + + +def test_waiting_human_reconcile_action_uses_projected_available_actions(): + """人工阻断存在统一对账动作时,主动作必须从当前投影动作列表中安全选取。""" + payload = apply_user_projection_fields({ + 'status': 'waiting_review', + 'stage': 'inventory_matching', + 'current_gate': { + 'gate_code': 'inventory_candidates_calculated', + 'status': 'blocked', + 'blocking_reason_code': 'inventory_candidates_required', + }, + 'available_actions': ['reconcile_and_progress', 'view_details'], + }) + + # 关键断言:该分支不得因未定义局部变量返回 500,且必须选中统一恢复入口。 + assert payload['user_status'] == 'waiting_human' + assert payload['primary_action']['code'] == 'reconcile_and_progress' + + +def test_waiting_human_without_reconcile_action_has_no_false_primary_action(): + """未知人工阻断未提供统一对账动作时,不得凭空生成可执行主动作。""" + payload = apply_user_projection_fields({ + 'status': 'waiting_review', + 'stage': 'inventory_matching', + 'current_gate': { + 'gate_code': 'inventory_candidates_calculated', + 'status': 'blocked', + 'blocking_reason_code': 'inventory_candidates_required', + }, + 'available_actions': ['view_details'], + }) + + # 关键断言:没有正式动作事实时保持 None,避免前端展示无效恢复按钮。 + assert payload['user_status'] == 'waiting_human' + assert payload['primary_action'] is None + + +def test_apply_user_projection_fields_fail_closes_inconsistent_projection(): + """事实读取异常即使发生在用户态计算后,也必须清空动作并进入诊断态。""" + payload = apply_user_projection_fields({ + 'status': 'running', + 'stage': 'inventory_preparation', + 'current_gate': {'gate_code': 'inventory_preparation', 'status': 'running'}, + 'available_actions': ['retry_inventory_preparation'], + 'projection_data_inconsistent': True, + }) + + assert payload['user_status'] == 'waiting_human' + assert payload['retryable'] is False + assert payload['primary_action'] is None + assert payload['available_actions'] == [] + assert payload['blocking_reason']['code'] == 'projection_data_inconsistent' + + +def test_inventory_milestones_are_projection_facts_not_runtime_gate_codes(): + """四个 MVP 库存里程碑必须由正式 Gate 和结构化事实派生,不能创建 APX Gate。""" + payload = apply_user_projection_fields({ + 'status': 'automating', + 'stage': 'inventory_matching', + 'current_gate': {'gate_code': 'inventory_matching', 'status': 'running'}, + 'available_actions': [], + }) + + assert payload['facts']['inventory_milestones'] == { + 'candidates_calculated': 'completed', + 'candidates_frozen': 'completed', + 'snapshots_ready': 'completed', + 'matched': 'pending', + } diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index 54b51141..009d2104 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -412,6 +412,17 @@ def test_project_order_task_prefers_written_ot_stage_over_notice(app, shipping_u assert synced['status'] == 'automating' assert synced['stage'] == 'freight_uploading' + # 人工上传回执已落库时,Notice 终态必须覆盖尚未来得及同步的 OT 旧状态。 + notice.process_status = 'uploaded' + order_task.status = 'automating' + order_task.stage = 'freight_uploading' + db.session.commit() + completed = _project_order_task_work_item(run) + assert completed['status'] == 'completed' + assert completed['stage'] == 'completed' + assert completed['user_status'] == 'completed' + assert all(node['status'] == 'passed' for node in completed['stage_nodes']) + def test_conversation_processing_rebuild_prefers_work_item_user_status(app): """ diff --git a/backend/tests/test_shipping_review_workbench_stage_layering.py b/backend/tests/test_shipping_review_workbench_stage_layering.py index 08da1ae5..f8dcefdc 100644 --- a/backend/tests/test_shipping_review_workbench_stage_layering.py +++ b/backend/tests/test_shipping_review_workbench_stage_layering.py @@ -137,6 +137,26 @@ def test_inventory_preparation_is_system_wait_not_human_blocker(): assert summary['owner_type'] == 'system' +def test_inventory_preparation_retryable_failure_remains_human_recovery(): + """库存准备明确失败可重试时,正式 OT 后不得被误清为系统等待。""" + summary = apply_post_ot_gate_rules( + { + 'current_blocking_gate': { + 'gate_code': 'inventory_preparation', + 'status': 'blocked_retryable', + 'blocking_reason_code': 'inventory_file_missing', + }, + 'next_action_code': 'retry_inventory_preparation', + 'technical_auto_only': False, + }, + has_formal_ot=True, + ) + assert summary['current_blocking_gate']['gate_code'] == 'inventory_preparation' + assert summary['next_action_code'] == 'retry_inventory_preparation' + assert summary['owner_type'] == 'human' + assert summary['technical_auto_only'] is False + + def test_human_inventory_gate_kept_after_ot(): """正式 OT 后人工库存阻断可保留。""" summary = apply_post_ot_gate_rules( @@ -155,6 +175,26 @@ def test_human_inventory_gate_kept_after_ot(): assert summary['technical_auto_only'] is False +def test_artifact_gate_kept_as_actionable_post_ot_gate(): + """正式 OT 后 Excel Artifact Gate 的恢复动作不得被静默隐藏。""" + summary = apply_post_ot_gate_rules( + { + 'current_blocking_gate': { + 'gate_code': 'artifact_generation', + 'status': 'blocked_retryable', + 'blocking_reason_code': 'artifact_generation_failed', + }, + 'next_action_code': 'regenerate_excel_artifact', + 'technical_auto_only': False, + }, + has_formal_ot=True, + ) + assert summary['current_blocking_gate']['gate_code'] == 'artifact_generation' + assert summary['next_action_code'] == 'regenerate_excel_artifact' + assert summary['owner_type'] == 'human' + assert summary['technical_auto_only'] is False + + def test_automation_phase_post_ot_waiting_to_start(): """正式 OT 后无 Job → waiting_to_start + phase=post_ot_progress。""" result = enrich_automation_status( @@ -196,6 +236,21 @@ def test_project_stage_for_task_created_is_order_creating(): assert stage['source'] == 'process_status' +def test_project_stage_for_task_terminal_notice_overrides_stale_ot_stage(): + """人工上传已完成时,旧 OT freight_uploading 阶段不能覆盖 Notice 终态。""" + task = SimpleNamespace( + id=1, + order_task_id=9, + process_status='uploaded', + current_step='step6_generate_file', + stage_nodes_json=None, + step_payload_json=None, + ) + stage = project_stage_for_task(task) + assert stage['code'] == 'completed' + assert stage['source'] == 'notice_terminal' + + def test_project_post_ot_automation_job_success_but_ot_created_is_failed(monkeypatch): """Job success + OT 仍 created → failed/retryable,保留 job_id,不得伪装 waiting。""" from types import SimpleNamespace as NS diff --git a/backend/tests/test_shipping_upload_attempt.py b/backend/tests/test_shipping_upload_attempt.py index c7a2add9..44e10a2c 100644 --- a/backend/tests/test_shipping_upload_attempt.py +++ b/backend/tests/test_shipping_upload_attempt.py @@ -101,7 +101,8 @@ def test_timed_out_upload_is_frozen_until_reconciled(app): with pytest.raises(ConflictError) as retry_error: start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key=attempt.idempotency_key) - assert retry_error.value.code == 'SHIPPING.UPLOAD_RESULT_UNKNOWN' + # 冻结合同:未知上传结果使用统一错误码,禁止以旧 timed_out 语义创建重试。 + assert retry_error.value.code == 'SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN' assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploading' assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved' @@ -135,7 +136,8 @@ def test_timed_out_upload_requires_explicit_rejection_before_release(app): mark_attempt_result_unknown(attempt) complete_attempt(attempt, success=False, callback_id='late-network-error', error_message='network timeout') - assert attempt.status == 'timed_out' + # 普通迟到网络错误不得把 unknown 收口为可重试失败。 + assert attempt.status == 'unknown' assert db.session.get(ShippingExportArtifact, artifact.id).status == 'uploading' assert db.session.get(ShippingReservation, reservation.id).status == 'artifact_reserved' diff --git a/backend/tests/test_shipping_upload_unknown_state.py b/backend/tests/test_shipping_upload_unknown_state.py new file mode 100644 index 00000000..28d3b682 --- /dev/null +++ b/backend/tests/test_shipping_upload_unknown_state.py @@ -0,0 +1,88 @@ +""" +用途:验证上传未知状态保护,防止未知回执下重复创建或回写旧 Artifact。 +依赖:upload_attempt_service、ShippingUploadAttempt 模型。 +逻辑:覆盖 unknown 状态创建保护和 Artifact superseded 回调拒绝。 +""" + +from app.core.errors import ConflictError + + +def test_unknown_upload_blocks_new_idempotency_key_and_superseded_callback(app): + """unknown 必须阻断全新重试键;Artifact superseded 后任何回调只返回冲突。""" + from app import db + from app.models import ShippingExportArtifact + from app.services.shipping_notice.upload_attempt_service import ( + mark_attempt_result_unknown, + start_rpa_attempt, + ) + from tests.test_shipping_upload_attempt import _ready_artifact + + with app.app_context(): + task, artifact, _reservation = _ready_artifact() + attempt = start_rpa_attempt(task, artifact_id=artifact.id) + mark_attempt_result_unknown(attempt) + try: + start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key='fresh-retry-key') + except ConflictError as exc: + assert exc.code == 'SHIPPING.UPLOAD_RETRY_FORBIDDEN_UNTIL_TERMINAL' + else: + raise AssertionError('unknown upload must block a fresh retry key') + + artifact.status = 'superseded' + db.session.flush() + from app.services.shipping_notice.upload_attempt_service import complete_attempt + try: + complete_attempt(attempt, success=True, callback_id='superseded-callback') + except ConflictError as exc: + assert exc.code == 'SHIPPING.ARTIFACT_ALREADY_SUPERSEDED' + else: + raise AssertionError('superseded Artifact must reject callbacks') + + +def test_upload_unknown_error_codes_are_stable(): + """稳定错误码必须区分未知状态与已失效 Artifact。""" + assert ConflictError('x', code='SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN').code == 'SHIPPING.UPLOAD_ATTEMPT_STATUS_UNKNOWN' + assert ConflictError('x', code='SHIPPING.ARTIFACT_ALREADY_SUPERSEDED').code == 'SHIPPING.ARTIFACT_ALREADY_SUPERSEDED' + + +def test_inventory_callback_id_is_checked_before_attempt_identity(app): + """库存回调先按 callback_id 去重,跨 Attempt 重放不得写入另一条 Attempt。""" + from app import db + from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt + from app.services.shipping_notice.per_source_rpa_service import per_source_callback_handler + + with app.app_context(): + task = ShippingNotice(task_no='SN-CB-ID-FIRST', source_type='manual', process_status='waiting_inventory') + db.session.add(task) + db.session.flush() + first = ShippingTaskInventoryRpaAttempt( + task_no=task.task_no, source_code='SRC-A', attempt_no=1, + source_run_no='PSR-FIRST', status='failed', callback_id=None, + ) + second = ShippingTaskInventoryRpaAttempt( + task_no='SN-CB-ID-OTHER', source_code='SRC-B', attempt_no=1, + source_run_no='PSR-SECOND', status='failed', callback_id=None, + ) + db.session.add_all([first, second]) + db.session.flush() + + result, handled = per_source_callback_handler( + task, source_code='SRC-A', run_no='PSR-FIRST', + callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'}, + ) + assert result == 'failed' + assert handled.id == first.id + + result, handled = per_source_callback_handler( + task, source_code='SRC-A', run_no='PSR-FIRST', + callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'}, + ) + assert result == 'idempotent_ok' + assert handled.id == first.id + + result, handled = per_source_callback_handler( + task, source_code='SRC-B', run_no='PSR-SECOND', + callback_payload={'callback_id': 'cb-unique', 'error_code': 'RPA_TIMEOUT'}, + ) + assert result == 'callback_conflict' + assert handled.id == first.id diff --git a/backend/tests/test_task_retry_decision_service.py b/backend/tests/test_task_retry_decision_service.py index a0e93b9e..08c85be9 100644 --- a/backend/tests/test_task_retry_decision_service.py +++ b/backend/tests/test_task_retry_decision_service.py @@ -14,6 +14,10 @@ from app.services.shipping_notice.line_inventory_match_projection import project from app.services.shipping_notice.task_retry_decision_service import ( ACTION_FETCH_INVENTORY, ACTION_NOOP, + ACTION_REMATCH, + ACTION_AUTO_PROGRESS, + ACTION_FAILED, + _execute, decide_retry_action_only, _is_inventory_rpa_active, ) @@ -76,6 +80,27 @@ def test_decide_rpa_pending_already_running(): assert decided['reason_code'] == 'already_running' +def test_fulfillable_task_without_excel_continues_auto_progress(monkeypatch): + """库存已完全匹配但 Excel 尚未生成时,任务级重试必须推进后续 Gate。""" + task = _task( + process_status='matched', + inventory_snapshot_id=7, + inventory_lines_json=[{'part_number': 'PN-1'}], + ) + monkeypatch.setattr( + 'app.services.shipping_notice.inventory_source_gate.is_inventory_source_stable', + lambda _t: True, + ) + monkeypatch.setattr( + 'app.services.shipping_notice.task_retry_decision_service._task_match_hint', + lambda _t: {}, + ) + + decided = decide_retry_action_only(task, scope='task') + + assert decided['action'] == ACTION_AUTO_PROGRESS + + def test_structured_failed_attempt_overrides_stale_rpa_pending(monkeypatch): """逐源 Attempt 已失败时,旧 rpa_pending 摘要不得阻止用户手动重试。""" task = _task(task_no='OT-FAILED', pending_human_reason='rpa_pending') @@ -123,3 +148,146 @@ def test_structured_running_attempt_blocks_duplicate_retry(monkeypatch): raising=False, ) assert _is_inventory_rpa_active(task) is True + + +def test_execute_rolls_back_before_returning_unexpected_failure(monkeypatch): + """下游数据库失败后,返回失败结果前必须清理 Session,供审计链继续写入。""" + task = _task(task_no='OT-ROLLBACK') + rollback_calls = [] + monkeypatch.setattr( + 'app.services.shipping_notice.task_retry_decision_service.db.session.rollback', + lambda: rollback_calls.append(True), + ) + monkeypatch.setattr( + 'app.services.shipping_notice.tools.auto_progress', + lambda _payload: (_ for _ in ()).throw(RuntimeError('database write failed')), + ) + + result = _execute( + task=task, + user_id=7, + decided={'action': ACTION_AUTO_PROGRESS}, + continue_auto_progress=False, + decision_version=3, + idempotency_key='auto-progress:OT-ROLLBACK:v3', + line_key=None, + ) + + # 关键断言:审计在 _execute 返回后才写,故必须已恢复可用事务。 + assert rollback_calls == [True] + assert result['action'] == ACTION_FAILED + assert result['status'] == 'failed' + + +def test_execute_fetch_retry_rpa_submits_formal_gate_action(monkeypatch): + """正式 retry_rpa 必须提交正式 Gate Action。""" + task = _task(task_no='OT-TRIGGER-DIRECT', inventory_snapshot_id=None, inventory_lines_json=None) + captured: dict[str, object] = {} + monkeypatch.setattr( + 'app.services.shipping_notice.task_retry_decision_service._request_formal_gate_action', + lambda **kwargs: captured.update(kwargs) or {'status': 'running'}, + ) + + result = _execute( + task=task, + user_id=7, + decided={'action': ACTION_FETCH_INVENTORY}, + continue_auto_progress=False, + decision_version=3, + idempotency_key='inventory-fetch:OT-TRIGGER-DIRECT:DSB_SLC:v3', + line_key=None, + trigger='conversation_retry', + ) + + assert result['status'] == 'running' + assert captured['action_code'] == 'retry_inventory_preparation' + + +def test_execute_rematch_submits_formal_gate_action(monkeypatch): + """库存匹配节点重试必须提交正式 Gate Action。""" + task = _task(task_no='OT-REMATCH', inventory_snapshot_id=9, inventory_lines_json=[]) + captured: dict[str, object] = {} + monkeypatch.setattr( + 'app.services.shipping_notice.task_retry_decision_service._request_formal_gate_action', + lambda **kwargs: captured.update(kwargs) or {'status': 'running'}, + ) + + result = _execute( + task=task, + user_id=7, + decided={'action': ACTION_REMATCH}, + continue_auto_progress=False, + decision_version=3, + idempotency_key='inventory-rematch:OT-REMATCH:v3', + line_key=None, + trigger='user_retry', + ) + + assert result['status'] == 'running' + assert captured['action_code'] == 'retry_inventory_from_matching' + + +def test_execute_fetch_uses_formal_gate_action_instead_of_legacy_inventory(monkeypatch): + """外部 retry_rpa 必须提交正式 Gate Action,不能直接执行旧库存函数。""" + task = _task(task_no='OT-FORMAL-RETRY', inventory_snapshot_id=None, inventory_lines_json=None) + captured: dict[str, object] = {} + + import app.services.shipping_notice.task_retry_decision_service as service + import app.services.shipping_notice.inventory_workflow as inventory_workflow + + monkeypatch.setattr(inventory_workflow, 'ensure_inventory', lambda _payload: (_ for _ in ()).throw( + AssertionError('legacy inventory workflow must not be called by external retry') + )) + monkeypatch.setattr( + service, + '_request_formal_gate_action', + lambda **kwargs: captured.update(kwargs) or {'status': 'running', 'action': 'fetch_inventory'}, + raising=False, + ) + + result = service._execute( + task=task, + user_id=7, + decided={'action': ACTION_FETCH_INVENTORY}, + continue_auto_progress=False, + decision_version=3, + idempotency_key='formal-retry:OT-FORMAL-RETRY:v3', + line_key=None, + trigger='user_retry', + ) + + assert result['status'] == 'running' + assert captured['action_code'] == 'retry_inventory_preparation' + + +def test_execute_rematch_uses_formal_gate_action_instead_of_legacy_match(monkeypatch): + """外部 rematch 必须提交正式 Gate Action,不能直接执行旧匹配函数。""" + task = _task(task_no='OT-FORMAL-REMATCH', inventory_snapshot_id=9, inventory_lines_json=[]) + captured: dict[str, object] = {} + + import app.services.shipping_notice.task_retry_decision_service as service + import app.services.shipping_notice.tools as shipping_tools + + monkeypatch.setattr(shipping_tools, 'match_inventory', lambda _payload: (_ for _ in ()).throw( + AssertionError('legacy match workflow must not be called by external retry') + )) + monkeypatch.setattr( + service, + '_request_formal_gate_action', + lambda **kwargs: captured.update(kwargs) or {'status': 'running', 'action': 'rematch'}, + raising=False, + ) + + result = service._execute( + task=task, + user_id=7, + decided={'action': ACTION_REMATCH}, + continue_auto_progress=False, + decision_version=3, + idempotency_key='formal-rematch:OT-FORMAL-REMATCH:v3', + line_key=None, + trigger='user_retry', + ) + + assert result['status'] == 'running' + assert captured['action_code'] == 'retry_inventory_from_matching' diff --git a/backend/tests/test_wecom_settings_env_persistence.py b/backend/tests/test_wecom_settings_env_persistence.py index 4f950528..530797b0 100644 --- a/backend/tests/test_wecom_settings_env_persistence.py +++ b/backend/tests/test_wecom_settings_env_persistence.py @@ -1,12 +1,32 @@ from dotenv import dotenv_values -from app import db, env_persistence -from app.models import AppSetting +from app import db +from app.core.auth.jwt import issue_local_access_token +from app.core.config import env_persistence +from app.models import AppSetting, User + + +def _admin_auth_headers(app) -> dict[str, str]: + """使用当前 JWT 鉴权合同构造企微管理端请求身份。""" + with app.app_context(): + admin = db.session.query(User).filter_by(username='wecom-settings-admin').first() + if admin is None: + admin = User( + username='wecom-settings-admin', + email='wecom-settings-admin@example.com', + role='admin', + status='active', + ) + admin.set_password('test-password') + db.session.add(admin) + db.session.commit() + token = issue_local_access_token(admin) + return {'Authorization': f'Bearer {token}', 'Content-Type': 'application/json'} def test_wecom_system_settings_persist_to_env_and_reload(client, app, admin_headers, monkeypatch, tmp_path): env_file = tmp_path / '.env' - monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file) + monkeypatch.setattr(env_persistence, 'ROOT_ENV_LOCAL_PATH', env_file) payload = { 'enabled': True, @@ -27,7 +47,7 @@ def test_wecom_system_settings_persist_to_env_and_reload(client, app, admin_head 'public_base_url': 'https://example.com', } - res = client.put('/api/admin/wecom/system-settings', json=payload, headers=admin_headers) + res = client.put('/api/admin/wecom/system-settings', json=payload, headers=_admin_auth_headers(app)) assert res.status_code == 200 saved = dotenv_values(env_file) @@ -49,7 +69,7 @@ def test_wecom_system_settings_persist_to_env_and_reload(client, app, admin_head app.config['WECOM_MATCH_OPERATOR'] = 'AND' app.config['WECOM_PUBLIC_BASE_URL'] = '' - res = client.get('/api/admin/wecom/system-settings', headers=admin_headers) + res = client.get('/api/admin/wecom/system-settings', headers=_admin_auth_headers(app)) assert res.status_code == 200 data = res.get_json() assert data['enabled'] is True @@ -60,7 +80,7 @@ def test_wecom_system_settings_persist_to_env_and_reload(client, app, admin_head def test_wecom_notify_settings_persist_to_env_and_reload(client, app, admin_headers, monkeypatch, tmp_path): env_file = tmp_path / '.env' - monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file) + monkeypatch.setattr(env_persistence, 'ROOT_ENV_LOCAL_PATH', env_file) payload = { 'enabled': False, @@ -68,7 +88,7 @@ def test_wecom_notify_settings_persist_to_env_and_reload(client, app, admin_head 'events': ['task_completed', 'permission_batch_updated'], } - res = client.put('/api/admin/wecom/notify-settings', json=payload, headers=admin_headers) + res = client.put('/api/admin/wecom/notify-settings', json=payload, headers=_admin_auth_headers(app)) assert res.status_code == 200 saved = dotenv_values(env_file) @@ -87,7 +107,7 @@ def test_wecom_notify_settings_persist_to_env_and_reload(client, app, admin_head app.config['WECOM_NOTIFY_BASE_URL'] = '' app.config['WECOM_NOTIFY_EVENTS'] = '' - res = client.get('/api/admin/wecom/notify-settings', headers=admin_headers) + res = client.get('/api/admin/wecom/notify-settings', headers=_admin_auth_headers(app)) assert res.status_code == 200 data = res.get_json() assert data['enabled'] is False @@ -99,12 +119,12 @@ def test_wecom_system_settings_survive_when_env_file_is_wiped(client, app, admin """Simulate a container rebuild that wipes backend/.env. The DB row must still drive the runtime configuration.""" env_file = tmp_path / '.env' - monkeypatch.setattr(env_persistence, 'BACKEND_ENV_PATH', env_file) + monkeypatch.setattr(env_persistence, 'ROOT_ENV_LOCAL_PATH', env_file) res = client.put( '/api/admin/wecom/system-settings', json={'corp_id': 'ww-from-db-only', 'enabled': True}, - headers=admin_headers, + headers=_admin_auth_headers(app), ) assert res.status_code == 200 @@ -118,7 +138,7 @@ def test_wecom_system_settings_survive_when_env_file_is_wiped(client, app, admin app.config['WECOM_CORP_ID'] = '' app.config['WECOM_ENABLED'] = False - res = client.get('/api/admin/wecom/system-settings', headers=admin_headers) + res = client.get('/api/admin/wecom/system-settings', headers=_admin_auth_headers(app)) assert res.status_code == 200 data = res.get_json() assert data['corp_id'] == 'ww-from-db-only' diff --git a/docs/demand.md b/docs/demand.md index 56fbbd05..9efcf46e 100644 --- a/docs/demand.md +++ b/docs/demand.md @@ -731,3 +731,8 @@ 拆分规则继承源节点作用域:权威明细集合之外的 Header 叶子只能映射 Header Schema 字段,正式提取按文档执行一次;集合之下的 Line 叶子只能映射 Line 字段,并逐条明细执行。 XFA 模板管理端暂不启用字段脱敏,树、拆分预览和样本验证直接展示完整值;模板试读不以订单 Schema 必填或自动建单关键字段缺值作为失败条件。 +### 2026-08-09 货代发货通知全门禁恢复 MVP 收口 + +- 恢复计划以持久化业务对象表达,Gate Attempt 为执行尝试,Job 为事务提交后的调度载体。 +- 库存准备、快照、映射、匹配、Verification、Excel、上传均保留不可变谱系;跨阶段恢复按准备轮次与组合输入指纹精确失效下游事实。 +- Dify 仅承担受控只读问答/建议,正式业务事实由 HXOPS 确定性后端产生;管理员按手册手工核对 Dify。 diff --git a/docs/features/README.md b/docs/features/README.md index a086e850..0dbdcd1b 100644 --- a/docs/features/README.md +++ b/docs/features/README.md @@ -5,6 +5,7 @@ | 域 | 说明 | 入口 | | --- | --- | --- | | [shipping-notice](shipping-notice/README.md) | 货代发货通知 Agent | [technical.md](shipping-notice/technical.md) · [客户识别规则改造方案](shipping-notice/customer_identity_rules_plan.md) | +| [in-transit-transfer](in-transit-transfer/) | 在途仓自动调拨 Agent | [PRD](in-transit-transfer/prd.md) · [路线图](in-transit-transfer/roadmap.md) · [完整规格](in-transit-transfer/minimum-implementation-spec.md) · [TDD](in-transit-transfer/in-transit-transfer-tdd.md) · [前端需求](in-transit-transfer/frontend-product-requirements.md) | | [file-check](file-check/README.md) | 文件检核(RoHS / MSDS 等) | [technical.md](file-check/technical.md) | | [fixed-assets](fixed-assets/README.md) | 固资快照同步与本地查询 | [technical.md](fixed-assets/technical.md) · [履历挂载命令](fixed-assets/history-share-mount.md) | diff --git a/docs/features/in-transit-transfer/frontend-product-requirements.md b/docs/features/in-transit-transfer/frontend-product-requirements.md new file mode 100644 index 00000000..60237533 --- /dev/null +++ b/docs/features/in-transit-transfer/frontend-product-requirements.md @@ -0,0 +1,644 @@ +# 在途仓自动调拨 Agent 前端产品需求文档 + +> 状态:前端开发前评审稿 +> 适用范围:在途仓自动调拨 Agent 一期 +> 目标用户:仓库管理人员、调拨配置管理员 +> 关联文档:[完整规格说明书](./minimum-implementation-spec.md) · [TDD实施与验证规范](./in-transit-transfer-tdd.md) +> 关联原型:[用户对话原型](../../prototype/in-transit-transfer-agent-mvp.html) · [后台配置原型](../../prototype/in-transit-transfer-admin-config-mvp.html) + +--- + +## 1. 产品定位 + +在途仓自动调拨 Agent 是 HXOPS 中的专用业务 Agent。仓库管理人员通过现有对话入口查询收料数据、核对ERP库存,并在一次明确确认后执行ERP调拨;管理员通过现有管理后台维护来源、策略、映射、排程、通知和发布版本。 + +前端必须复用当前 HXOPS 的 Chat UI、AdminLayout、库存来源管理和排程工作台,不创建平行工作台或独立集成中心。 + +## 2. 产品目标 + +### 2.1 业务目标 + +- 支持用户查询今天可调拨数据。 +- 自动准备 DBS、Crane 收料文件。 +- 查询 ERP 账面库存并完成数量匹配。 +- 确认前展示执行范围、预计调拨总数量和预计ERP写入数。 +- 用户点击一次“执行调拨”后由后台Run继续执行。 +- 支持每日自动排程和历史失败受控恢复。 +- 异常有证据、有下一步、有企业微信通知和Excel明细。 +- 所有操作节点可审计追溯。 + +### 2.2 体验目标 + +- 用户无需记忆复杂命令。 +- 只读查询与ERP写入明确区分。 +- 文件准备、ERP查询、匹配和建单进度透明。 +- 页面刷新、切换会话、SSE断开或重新登录后可恢复任务。 +- 失败信息必须说明发生了什么、影响是什么、下一步是什么。 + +## 3. 目标用户与权限 + +### 3.1 仓库管理人员 + +可以: + +- 使用在途仓调拨 Agent。 +- 发起查询和预检。 +- 选择可执行Invoice并确认执行。 +- 查看有权限范围内的Run、Invoice、异常和审计。 +- 手工重试可重试项。 +- 请求停止尚未开始的任务。 +- 标记Invoice为“无需继续处理”。 + +不可以: + +- 修改调拨数量、来源仓、目标HUB仓或ERP组织。 +- 修改ERP接口地址或凭据。 +- 删除Run、Invoice、Attempt或审计记录。 +- 直接从Dify调用ERP写接口。 + +### 3.2 调拨配置管理员 + +可以: + +- 配置 DBS、Crane 收料来源。 +- 配置调拨策略、仓库映射、排程和通知。 +- 保存草稿、运行校验、查看Diff和发布版本。 +- 查看配置审计和连接验证结果。 + +敏感信息通过环境变量或Secret注入,页面只显示注入状态,不显示明文。 + +## 4. 核心业务规则 + +### 4.1 日期与成熟度 + +- 当前业务日期为系统业务日期,业务时区为 `Asia/Shanghai`。 +- 收料日期等于当天:`not_matured`,不查ERP、不计入可调拨数量、不视为异常。 +- 收料日期早于当天,且未成功、未`manually_closed`,才进入预检范围。 + +### 4.2 文件来源 + +- DBS、Crane为两个独立的收料来源实例。 +- 文件为累计全量文件。 +- 优先使用当天最新`ready`文件。 +- 当天缺文件时实时触发来源获取。 +- DBS使用RPA,Crane使用HTTP Callback。 +- 同来源、同业务日期、同用途只允许一个活动抓取任务。 +- 同一Invoice多行只汇总收料数量,但必须保留Sheet和原始行号。 + +### 4.3 ERP与执行 + +- ERP使用SOAP WebService,查询和写入默认超时60秒。 +- 收料数量必须完全等于ERP账面库存。 +- 数量不一致不允许部分调拨。 +- ERP接口一次完成新建、审核、过账,失败完整回滚。 +- 同ERP组织内Invoice No为幂等键。 +- 重复Invoice如果能确认原单已审核、过账,显示`duplicate_success`和原调拨单号。 +- ERP写入默认不自动重试。 +- `result_unknown`不得自动重试,需人工核实。 + +### 4.4 对话确认 + +- 用户执行前必须看到预检卡。 +- 用户点击一次“执行调拨”。 +- 确认卡有效期10分钟。 +- 文件、checksum、ERP库存、映射或选择范围变化时确认失效。 +- Worker写入前必须重新查询ERP。 + +### 4.5 排程和通知 + +- 08:00收料文件抓取排程。 +- 09:00自动调拨排程。 +- 自动调拨仍需检查当日最新Ready文件。 +- 非空自动调拨Run只发送一条企业微信汇总通知和一份异常Excel。 +- 空数据Run为`success + no_data`,不发送通知。 +- 通知失败单独记录`notification_failed`,不改变ERP业务结果。 +- 历史可恢复失败每日重新预检,每次恢复创建新Attempt。 +- `manually_closed`永久排除。 + +## 5. 信息架构 + +### 5.1 用户前台 + +```text +HXOPS工作台 +└── 对话 + └── 在途仓调拨 Agent + ├── 新建对话 + ├── 历史会话 + ├── 当前消息流 + ├── 本次处理进度 + ├── 文件准备 + ├── 调拨预检 + ├── 执行确认 + ├── 执行结果 + └── 异常与审计 +``` + +### 5.2 管理后台 + +```text +HXOPS管理后台 +├── 调拨配置 +│ ├── 数据来源 +│ ├── 调拨策略 +│ ├── 仓库与组织 +│ ├── 自动排程 +│ └── 通知设置 +└── 发布与治理 + ├── 发布管理 + ├── 连接验证 + └── 配置审计 +``` + +## 6. 页面清单 + +### 6.1 用户前台页面 + +| 页面 | 目的 | +| --- | --- | +| Agent欢迎页 | 说明能力、展示待办和快捷问题 | +| 文件准备进度 | 展示DBS、Crane文件准备进度 | +| 调拨预检结果 | 展示成熟范围、匹配结果和预计数量 | +| Invoice选择与确认 | 选择可执行Invoice并确认ERP写入 | +| 调拨执行进度 | 展示后台Run和逐项建单状态 | +| 调拨结果摘要 | 展示成功、失败、未知和通知状态 | +| 异常详情 | 展示证据、Attempt和下一步操作 | +| 人工关闭弹窗 | 填写原因并永久关闭Invoice自动处理 | +| 审计时间线抽屉 | 查看完整操作、状态和快照摘要 | + +### 6.2 管理后台页面 + +| 页面 | 目的 | +| --- | --- | +| 数据来源 | 配置DBS、Crane收料实例 | +| 调拨策略 | 配置成熟、数量、确认和恢复规则 | +| 仓库与组织 | 配置来源仓、目标HUB仓和ERP组织 | +| 自动排程 | 配置08:00和09:00排程 | +| 通知设置 | 配置通知人和异常Excel | +| 发布管理 | 草稿、校验、Diff和发布 | +| 连接验证 | 验证RPA、Callback、解析和ERP只读查询 | +| 配置审计 | 查询配置操作和版本变更 | + +## 7. 用户前台页面需求 + +### 7.1 Agent欢迎页 + +#### 模块结构 + +- Agent身份区:图标、名称、能力说明。 +- 新对话按钮。 +- 历史会话区:查询、执行、Run和异常记录。 +- 待办摘要:历史待处理、已恢复可执行、结果未知、超期积压。 +- 快捷问题:查询今天可调拨、执行全部、限定DBS、查看异常。 +- 规则说明:D+1、最新Ready、完全相等、确认后执行。 +- 对话输入框。 + +#### 关键交互 + +- “查询今天可调拨数据”进入文件准备阶段。 +- “执行今天全部可调拨项”仍必须先预检和确认。 +- 同一查询Run的文件准备和预检在同一历史会话中原位更新。 +- 新建对话不自动触发ERP写入。 + +#### 空状态 + +> 当前没有待处理调拨项。 + +仍保留“查询今天可调拨数据”入口。 + +### 7.2 文件准备进度页 + +#### 模块结构 + +- 当前业务日期和可处理收料日期上限。 +- 阶段轨道:理解范围、准备文件、校验汇总、查询ERP。 +- DBS来源卡:Ready复用或RPA执行状态。 +- Crane来源卡:HTTP Callback状态。 +- 已完成数、当前阶段、最近更新时间。 +- 后台继续执行、刷新进度、查看详情。 + +#### 交互要求 + +- 来源级状态独立展示,DBS失败不能阻断Crane。 +- 页面关闭后任务继续执行。 +- SSE中断时切换为轮询,恢复后停止轮询。 +- 不能使用无阶段说明的单一加载动画。 + +#### 空状态 + +- 已有文件:显示“已复用当天最新收料文件”。 +- 文件无数据:显示“文件已获取,但没有符合条件的Invoice”。 +- 单一来源无数据:来源级显示空数据,其他来源继续处理。 + +#### 错误状态 + +错误必须包含来源、阶段、原因和下一步。例如: + +> Crane尚未返回Callback,任务会继续保留;可刷新查看进度或联系管理员。 + +### 7.3 调拨预检结果页 + +#### 模块结构 + +- 文件内Invoice总数。 +- 当天收料未成熟数量。 +- 进入ERP预检数量。 +- 可执行数量。 +- 数量不一致数量。 +- ERP无库存数量。 +- 可调拨总数量。 +- 预计ERP单据数量。 +- DBS、Crane来源汇总。 +- 下载预检明细、查看Invoice、执行全部可调拨项。 + +#### 关键边界 + +页面必须明确显示: + +> 当前仅完成查询和匹配,不会产生ERP调拨单。 + +### 7.4 Invoice选择与确认页 + +#### 模块结构 + +- 确认卡有效期和失效提示。 +- Invoice选择表格。 +- 来源、收料数量、ERP库存和状态。 +- 已选择Invoice数。 +- 预计调拨总数量。 +- 预计ERP写入数。 +- 取消、返回预检、执行调拨。 + +#### 交互要求 + +- 默认选择全部可执行Invoice。 +- 阻断项checkbox禁用。 +- 用户可取消部分可执行项。 +- 用户不可修改数量、仓库、ERP组织。 +- 重复点击“执行调拨”不得生成多个Run。 +- 确认过期或快照变化后必须重新预检。 + +按钮文案固定为“执行调拨”,不使用“提交”或“确定”。 + +### 7.5 调拨执行进度页 + +#### 模块结构 + +- Run编号和状态。 +- 文件准备、ERP查询、数量匹配、ERP调拨、结果通知阶段。 +- 待执行、已处理、成功、失败数量。 +- DBS、Crane来源级进度。 +- 查看Invoice明细。 +- 请求停止剩余任务。 + +#### 交互要求 + +- 关闭页面后后台继续执行。 +- 请求停止必须填写原因。 +- 只取消尚未开始的Invoice。 +- 已成功ERP单据不撤销。 + +### 7.6 调拨结果摘要页 + +展示以下结果分类: + +- 成功过账。 +- 重复成功。 +- 数量不一致。 +- ERP无库存。 +- 技术失败。 +- 结果未知。 +- 已取消。 +- 通知失败。 + +ERP结果与通知结果必须分开表达。空数据显示`success + no_data`,不展示为异常。 + +### 7.7 异常详情页 + +#### 模块结构 + +- Invoice基础信息。 +- 收料文件、Sheet、原始行号、checksum。 +- 收料数量和ERP账面库存。 +- 当前状态。 +- Attempt历史。 +- 审计时间线。 +- 下载证据、手工重新预检、手工重试、标记无需继续处理。 + +#### 约束 + +- 不允许人工修改数量、仓库或组织。 +- 人工关闭必须填写原因。 +- `manually_closed`后不再自动处理。 +- `result_unknown`必须先人工核实。 + +### 7.8 审计时间线抽屉 + +显示: + +- 操作人、角色、时间。 +- Run、Source Job、Invoice、Attempt。 +- 请求ID和Operation ID。 +- 操作前后状态。 +- Diff摘要和快照Hash。 +- 证据对象路径。 + +查看操作本身产生读审计,敏感报文默认脱敏。 + +## 8. 管理后台页面需求 + +### 8.1 数据来源 + +展示DBS、Crane收料来源实例: + +- 收料用途`receipt`。 +- RPA Profile或HTTP Callback方式。 +- 解析方案版本。 +- 当前Ready文件。 +- 固定来源仓。 +- 启用状态。 +- 编辑、验证、停用。 + +DBS显示RPA配置;Crane显示HTTP Callback配置。不得显示Secret明文。 + +### 8.2 调拨策略 + +配置: + +- 业务时区。 +- D+1成熟规则。 +- 完全相等数量门禁。 +- 确认有效期。 +- ERP查询和写入超时。 +- 历史异常自动复核。 +- 3/5/7天老化阈值。 +- 是否允许对话直接执行。 + +以下能力一期强制关闭: + +- 部分调拨。 +- 数量容差。 +- ERP写入自动重试。 +- `result_unknown`自动重试。 + +### 8.3 仓库与组织 + +表格展示: + +- 路由。 +- ERP组织。 +- 来源实例。 +- 固定来源仓。 +- 目标HUB仓。 +- 映射状态。 + +校验:同一路由一个ERP组织;来源仓必须来自来源配置;目标HUB缺失不得发布。 + +### 8.4 自动排程 + +默认展示两个排程: + +| 排程 | 时间 | 范围 | +| --- | --- | --- | +| 每日收料文件抓取 | 08:00 | DBS、Crane | +| 每日自动调拨 | 09:00 | DBS、Crane和历史待办 | + +展示Cron、来源范围、并发、所有者、最近运行、启停和立即运行操作。 + +### 8.5 通知设置 + +配置: + +- 任务所有者。 +- 额外通知人员。 +- 非空Run一条汇总通知。 +- 一份七Sheet异常Excel。 +- 空数据默认不通知。 +- 通知失败不改变ERP结果。 + +### 8.6 发布管理 + +配置生命周期: + +```text +草稿 → 校验中 → 校验通过 → 发布 → 生效 +``` + +发布页面展示: + +- Published版本。 +- Draft版本。 +- 配置Diff。 +- 发布门禁。 +- 校验结果。 +- 发布人和发布时间。 +- 回滚入口。 + +### 8.7 连接验证 + +可验证: + +- DBS RPA登录和报表定位。 +- Crane Callback身份校验。 +- 收料字段解析和多行汇总。 +- ERP SOAP只读查询。 +- 企业微信文本和附件模拟发送。 + +禁止从配置页发起ERP真实写入测试。 + +### 8.8 配置审计 + +支持按配置域、操作人、版本筛选,查看: + +- 操作时间。 +- 操作人。 +- 配置对象。 +- 操作类型。 +- before快照。 +- after快照。 +- Diff。 +- Hash。 +- 发布结果。 + +业务用户无权访问配置审计。 + +## 9. 视觉设计要求 + +### 9.1 风格关键词 + +企业级、清晰克制、数据导向、可信赖、轻量蓝色、高信息密度、状态可见、边界明确。 + +避免营销型大图、装饰性渐变堆叠和与HXOPS无关的独立视觉语言。 + +### 9.2 用户Chat风格 + +- 白色主背景和浅灰分区。 +- 左侧历史会话栏、中间消息区、右侧本次处理轨道。 +- 蓝色主操作色。 +- 绿色表示完成,黄色表示等待/风险,红色表示阻断/失败。 +- 结构化消息使用卡片,不用复杂弹窗替代核心业务流程。 + +### 9.3 管理后台风格 + +- 复用AdminLayout顶栏和左侧导航。 +- 中间配置工作区,右侧发布门禁和审计轨道。 +- 使用面板、表格、表单、抽屉、状态徽标。 +- 草稿和已发布版本必须明显区分。 + +### 9.4 色彩与字体 + +| 用途 | 建议值 | +| --- | --- | +| 主品牌蓝 | `#0284C7` / `#2563EB` | +| 信息背景 | `#E0F2FE` | +| 成功 | `#15803D` / `#F0FDF4` | +| 风险 | `#A16207` / `#FFFBEB` | +| 错误 | `#BE123C` / `#FFF1F2` | +| 页面背景 | `#F8FAFC` | +| 主要文字 | `#0F172A` | +| 次级文字 | `#475569` | + +使用系统中文字体,标题和数据采用清晰的中等偏粗层级;操作文案使用短动词,如“保存草稿”“运行校验”“执行调拨”。 + +### 9.5 视觉签名 + +统一使用“进度轨道”表达业务状态: + +```text +范围确认 → 文件准备 → Invoice汇总 → ERP查询 → 数量匹配 → ERP调拨 → 结果通知 +``` + +用户侧为右侧纵向进度轨道,管理侧为右侧发布门禁轨道。 + +## 10. 通用交互规范 + +### 10.1 异步状态 + +每个异步动作必须显示:已开始、当前阶段、完成数量、预计下一步、最近更新时间、等待/失败原因和可执行下一步。 + +### 10.2 按钮 + +- 主操作:执行调拨、保存草稿、运行校验、发布配置。 +- 次操作:刷新进度、查看明细、下载证据、查看Diff。 +- 危险操作:停用来源、请求停止、标记无需继续处理。 + +危险操作必须显示影响范围、填写原因并写入审计。 + +### 10.3 进度恢复 + +刷新浏览器、关闭页面、切换会话、SSE断开和重新登录后,必须恢复进行中的Run投影。已结束Run不继续轮询。 + +### 10.4 防重复 + +提交后按钮立即进入处理中;重复点击不创建重复Run、Attempt或发布版本。 + +## 11. 空状态、加载状态与错误状态 + +### 11.1 空状态 + +| 场景 | 文案和操作 | +| --- | --- | +| 无待处理 | 当前没有符合条件的可调拨Invoice;可查询最新数据 | +| 文件不存在 | 尚未找到今天收料文件,系统正在获取;查看文件进度 | +| 文件无数据 | 文件已获取,但没有符合当前日期范围的Invoice | +| 无异常 | 本次Run没有异常项,不显示异常下载和重试按钮 | +| 无审计 | 当前对象暂无审计记录,但本次查看仍会产生访问审计 | + +### 11.2 加载状态 + +- 首屏使用骨架屏,不能整页白屏。 +- 文件准备显示来源级状态。 +- ERP查询显示已查询/总数。 +- ERP写入显示已处理、成功、失败、结果未知和剩余数。 +- 发布显示保存、校验、连接、Diff和发布阶段。 +- 进度更新不能使用无阶段说明的单一Spinner。 + +### 11.3 错误状态 + +错误必须说明对象、阶段、原因和下一步。重点区分: + +- 文件结构错误。 +- 数量不一致。 +- ERP无库存。 +- ERP技术失败。 +- ERP结果未知。 +- 企业微信通知失败。 +- 配置发布阻断。 + +## 12. 移动端适配 + +### 12.1 适配尺寸 + +至少验证:1440×900、1920×1200、1024×768、768×1024、390×844、430×932。 + +### 12.2 Chat移动布局 + +- 左侧历史会话折叠为抽屉。 +- 右侧本次处理折叠为顶部阶段摘要。 +- Invoice表格转换为纵向卡片。 +- 确认卡使用全屏底部Sheet。 +- 审计时间线使用全屏抽屉。 +- 输入框固定在底部安全区域。 + +### 12.3 管理后台移动布局 + +- 左侧导航折叠为菜单按钮。 +- 发布门禁移动到页面顶部。 +- 双列表单转为单列。 +- 表格横向滚动或转换为卡片。 +- 发布按钮固定在底部操作栏。 + +### 12.4 不可牺牲的信息 + +当前业务日期、Run编号、当前阶段、ERP写入状态、预计调拨总数量、错误原因和主操作按钮必须始终可见。 + +### 12.5 触控与可访问性 + +- 主要按钮最小点击区域44×44px。 +- 状态不能只用颜色表达。 +- 支持键盘焦点和`focus-visible`。 +- 进度更新使用ARIA live区域。 +- 支持减少动态效果。 +- 错误提示与输入框关联。 + +## 13. 前端验收标准 + +### 13.1 功能 + +- 查询、预检、确认、执行、结果、异常和审计全流程可操作。 +- 查询和预检在同一历史会话中原位更新。 +- 当天收料明确标记未成熟。 +- DBS和Crane显示独立进度。 +- 阻断项无法选择。 +- 确认过期后无法执行。 +- 刷新后Run可恢复。 +- 结果未知与通知失败独立展示。 +- 后台配置支持草稿、校验、发布。 +- 配置页面不展示Secret明文。 + +### 13.2 视觉 + +- 用户侧符合现有HXOPS Chat UI。 +- 管理侧符合现有HXOPS AdminLayout。 +- 页面无不可操作的横向溢出。 +- 关键状态在首屏可见。 +- 结构化卡片和状态徽标样式统一。 + +### 13.3 响应式 + +- 桌面、平板和手机均可完成查询、查看和一次确认。 +- 移动端表格可滚动或转为卡片。 +- 主要按钮始终可见。 +- 进度和错误信息不被截断。 + +### 13.4 性能 + +- 页面首屏结构渲染不依赖外部系统。 +- 20条Invoice明细不卡顿。 +- 100条Invoice使用分页或虚拟滚动。 +- 轮询只针对进行中的Run。 +- 已结束Run停止请求进度接口。 + +## 14. 前端交付边界 + +本PRD只约束前端产品行为、页面结构和交互表现。后端业务真相、ERP SOAP、RPA、企业微信、审计和状态机必须以完整规格说明书及TDD为准,前端不得自行裁决业务状态或模拟ERP写入成功。 diff --git a/docs/features/in-transit-transfer/in-transit-transfer-tdd.md b/docs/features/in-transit-transfer/in-transit-transfer-tdd.md new file mode 100644 index 00000000..7394e093 --- /dev/null +++ b/docs/features/in-transit-transfer/in-transit-transfer-tdd.md @@ -0,0 +1,525 @@ +# 在途仓自动调拨 AI Agent 一期 TDD 实施与验证规范 + +> 状态:开发前冻结,所有实现必须先有失败测试再写业务代码 +> 适用范围:在途仓自动调拨 Agent 一期,包括对话、后台排程、收料文件、ERP调拨、异常恢复、企业微信通知、后台配置发布和全链路审计 +> 关联规格:[minimum-implementation-spec.md](./minimum-implementation-spec.md) +> 测试基线:后端 pytest;前端 Vitest + Vue Test Utils;E2E 使用 Playwright 约定;数据库 PostgreSQL 测试库;外部系统全部使用可控 Stub/Mock + +--- + +## 1. TDD硬性规则 + +### 1.1 Red → Green → Refactor + +每个需求切片必须按以下顺序交付: + +1. **Red**:先提交能准确描述业务失败的测试,测试必须失败且失败原因是“能力不存在”或“契约未满足”。 +2. **Green**:只实现让当前测试通过的最小代码,不提前实现未被测试覆盖的扩展行为。 +3. **Refactor**:在测试全绿后整理结构、命名和复用;重构前后必须保持测试结果一致。 + +禁止以下方式: + +- 先写完整业务代码,再补覆盖率测试。 +- 用 Mock 把待测业务逻辑本身 Mock 掉。 +- 用快照测试替代状态、数量、权限、审计和幂等断言。 +- 用前端展示结果代替后端业务真相断言。 +- 用“测试环境能调用接口”代替错误、超时、重复和回滚测试。 + +### 1.2 测试代码注释 + +每个新增测试文件必须包含: + +- 文件层注释:用途、依赖、被测链路。 +- 测试函数上方 docstring/JSDoc:触发条件、业务约束、预期结果。 +- 断言意图注释:说明为什么断言该状态、数量、审计或禁止副作用。 + +### 1.3 Fail-closed 原则 + +以下任一前置条件失败,测试必须证明 ERP 写入调用次数为 `0`: + +- 当天收料未成熟。 +- 收料文件缺失、过期、checksum变化或结构漂移。 +- Invoice字段冲突或一张Invoice跨多个料号/日期。 +- ERP账面库存与收料数量不完全相等。 +- 确认卡缺失、过期或快照变化。 +- 来源、仓库、ERP组织映射缺失。 +- 幂等键冲突且无法证明原单已审核过账。 +- 操作人无Agent权限或无管理员配置权限。 + +--- + +## 2. 测试分层与责任边界 + +| 层级 | 目标 | 允许依赖 | 禁止依赖 | 通过门槛 | +| --- | --- | --- | --- | --- | +| L0 纯单元 | 状态机、日期、汇总、匹配、DTO、策略 | Python标准库/TypeScript纯函数 | Flask应用、真实DB、真实网络 | 100%通过;关键分支100% | +| L1 服务单元 | 文件准备、预检、执行、恢复、通知、审计 | 测试DB、Fake Adapter、Fake Clock | 真实RPA/ERP/企微 | 核心服务分支≥95% | +| L2 API契约 | REST envelope、权限、幂等、错误码 | 当前Flask测试客户端、测试DB | 外部生产系统 | 契约字段100%稳定 | +| L3 Worker集成 | 队列领取、租约、并发、崩溃恢复 | Redis/PostgreSQL测试实例、Fake外部系统 | 生产凭据 | 重启/重复消费零重复成功 | +| L4 前端组件 | 卡片、进度、确认、异常、后台配置 | Vitest、Vue Test Utils、Mock API | 真实后端 | 关键交互100%覆盖 | +| L5 E2E | 用户真实路径和跨页面恢复 | 测试前后端、固定Fixture | 生产ERP/RPA | 主流程和高风险流程全通过 | +| L6 性能/故障 | 时延、并发、超时、积压、通知失败 | 可控压测Stub | 真实生产写入 | 达到第12章指标 | + +测试金字塔要求:L0/L1数量最多;L2/L3覆盖所有外部边界;L5只保留高价值主路径和灾难路径。 + +--- + +## 3. 固定测试工具、夹具和外部Stub + +### 3.1 后端测试组件 + +建议新增: + +```text +backend/tests/services/in_transit_transfer/conftest.py +backend/tests/services/in_transit_transfer/factories.py +backend/tests/services/in_transit_transfer/fakes.py +backend/tests/services/in_transit_transfer/assertions.py +``` + +夹具必须提供: + +| Fixture | 固定行为 | +| --- | --- | +| `transfer_db` | 独立事务,测试结束回滚或清理所有调拨表 | +| `fixed_clock` | 默认 `2026-08-06 09:00:00+08:00`,可推进到下一业务日 | +| `dbs_ready_file` | 当日ready收料全量文件,含重复Invoice多行 | +| `crane_ready_file` | 当日ready收料全量文件,支持HTTP Callback完成 | +| `same_day_receipt_file` | 含业务日期当天收料,必须not_matured | +| `erp_fake` | 查询账面库存;写接口原子新建/审核/过账;重复Invoice返回原单号 | +| `erp_timeout_fake` | 查询或写入超时,分别可配置已落单/未落单 | +| `rpa_fake` | 领取、Callback、失败、重复Callback、错误来源Callback | +| `wecom_fake` | 成功、附件失败、文本失败;不自动重试 | +| `audit_sink` | 保存before/after、Diff、Hash、request/operation关联 | +| `auth_user` | 仓库管理员,拥有Agent权限 | +| `admin_user` | 有配置和发布权限 | +| `unauthorized_user` | 无Agent权限或无管理员权限 | + +### 3.2 前端测试组件 + +建议新增: + +```text +frontend/src/features/chat/components/messages/transfer/__fixtures__/transferFixtures.ts +frontend/src/features/chat/components/messages/transfer/__tests__/transferTestUtils.ts +frontend/src/features/admin/modules/in-transit-transfer/__fixtures__/adminConfigFixtures.ts +``` + +前端禁止把真实外部响应写入测试;所有卡片使用稳定DTO fixture。测试必须验证可见文案、按钮禁用、状态标签、数量汇总和错误提示,而非只断言组件挂载。 + +### 3.3 外部系统Stub契约 + +`FakeERP` 必须记录每一次调用:`operation_id`、Invoice No、组织、来源仓、目标仓、数量、调用序号、返回状态。测试断言优先读取调用记录,不通过实现内部变量猜测副作用。 + +ERP Stub必须支持以下响应: + +```text +success(document_no) +duplicate_success(document_no, verified_posted=true) +business_failed(code, message, rolled_back=true) +timeout(before_commit=true) +timeout(after_commit=true, replay_query_unsupported=true) +``` + +`FakeRPA`必须区分 DBS 拉取和 Crane HTTP Callback,且支持按来源独立注入失败。 + +--- + +## 4. 测试数据标准 + +### 4.1 最小合法Invoice + +```json +{ + "invoice_no": "INV-260806-001", + "material_no": "MAT-001", + "receipt_date": "2026-08-05", + "receipt_quantity": "1200", + "source_code": "DBS", + "source_warehouse": "DBS-TRANSIT", + "erp_org": "HX-CN01", + "target_hub": "HUB-CN01" +} +``` + +### 4.2 必须覆盖的变体 + +| 数据组 | 变体 | 预期 | +| --- | --- | --- | +| 日期 | 当天、昨天、更早、未来日期 | 当天not_matured;昨天及更早可预检;未来阻断 | +| 汇总 | 同Invoice同料号两行 | 数量相加,保留两条原始行 | +| 冲突 | 同Invoice多个料号/日期/Sheet | 整Invoice阻断 | +| 数量 | 相等、大于、小于、0、负数、小数、非数字 | 只有完全相等可执行 | +| ERP | 有库存、无库存、重复成功、业务失败、技术失败、结果未知 | 状态按状态机落位 | +| 文件 | 当前ready、只有昨日ready、checksum变化、缺字段、空数据 | 复用/实时抓取/阻断符合规则 | +| 历史 | 失败1/3/5/7天、manually_closed、result_unknown | 老化提示与自动恢复符合规则 | + +--- + +## 5. L0 纯单元测试清单(先写这些) + +### 5.1 日期成熟与范围 + +测试文件:`backend/tests/services/in_transit_transfer/test_date_policy.py` + +必须先写的失败测试: + +1. 当天收料返回 `not_matured`,ERP查询调用为0。 +2. 昨天收料进入预检。 +3. 未来日期返回结构化阻断错误。 +4. “今天可调拨”过滤成功项和`manually_closed`项。 +5. Asia/Shanghai跨UTC午夜时业务日期不漂移。 + +### 5.2 文件字段和Invoice汇总 + +测试文件:`test_receipt_file_parser.py`、`test_invoice_aggregator.py` + +必须覆盖: + +- 必填列缺失、空值、非法数量、负数。 +- 同Invoice同料号多行汇总。 +- 同Invoice多料号、多日期、跨Sheet冲突整单阻断。 +- 原始Sheet和行号追溯不丢失。 +- 当前文件checksum写入预检快照。 + +### 5.3 ERP数量门禁与状态机 + +测试文件:`test_quantity_match.py`、`test_status_machine.py` + +必须覆盖: + +- 收料数量等于账面库存才返回`executable`。 +- ERP库存大于或小于收料数量均阻断。 +- 所有非法状态迁移抛出领域错误。 +- `result_unknown`没有自动重试迁移路径。 +- `manually_closed`永久禁止进入待处理池。 + +### 5.4 DTO与策略 + +测试文件:`test_contracts.py`、`test_strategy_policy.py` + +必须覆盖: + +- 预检DTO包含范围、数量、预计ERP写入数、过期时间和Hash。 +- 未确认不能创建执行Run。 +- 请求来源、Invoice范围和日期校验失败返回稳定错误码。 +- 策略禁止部分数量调拨、容差和自动ERP重试。 + +--- + +## 6. L1 服务单元TDD顺序 + +每个服务先建立Fake依赖,再按表中顺序提交Red测试。 + +| 顺序 | 测试文件 | 先冻结的行为 | Green实现目标 | +| ---: | --- | --- | --- | +| 1 | `test_file_preparation.py` | 当日ready复用;缺失时同来源只触发一个RPA;DBS/Crane互不影响 | `ensure_receipt_file_ready` | +| 2 | `test_precheck_service.py` | 文件准备→成熟过滤→汇总→ERP查询→数量匹配;进度事件可恢复 | `precheck_service` | +| 3 | `test_execution_service.py` | 写前重新查询;确认Hash失效不写;逐项结果;写并发由上层控制 | `execution_service` | +| 4 | `test_erp_adapter.py` | SOAP请求字段、60秒超时、原子失败、重复Invoice投影 | `erp_adapter` | +| 5 | `test_orchestrator.py` | Run/SourceJob/Attempt持久化;只执行可执行项;单项失败不影响其它项 | `orchestrator` | +| 6 | `test_recovery_service.py` | 历史失败每日重新预检;每次新Attempt;result_unknown不自动写 | `recovery_service` | +| 7 | `test_retry_and_manual_close.py` | 手工重试原因、人工关闭原因必填且不可恢复 | `retry_service`、`manual_close_service` | +| 8 | `test_notification.py` | 非空排程一条汇总通知和一份Excel;通知失败不改变ERP结果 | `notification`、`excel_export` | +| 9 | `test_audit_service.py` | 每个读写节点生成审计,快照/Diff/Hash完整 | `audit` | +| 10 | `test_config_publish.py` | 草稿→校验→发布;凭据不落库明文;版本绑定Run | 配置发布服务 | + +服务单元最低断言:返回值、持久化状态、外部调用次数、幂等键、审计事件和副作用对象。 + +--- + +## 7. L2 API契约TDD + +测试目录:`backend/tests/api/test_in_transit_transfer_api.py`、`test_in_transit_transfer_config_api.py` + +### 7.1 对话/调拨API + +每个接口至少覆盖:成功、未授权、参数错误、重复请求、过期状态、领域阻断、内部异常和审计失败。 + +| 接口 | 关键断言 | +| --- | --- | +| `POST /prechecks` | 首次创建Run;相同范围可复用进行中Run;响应5秒内含进度;写ERP=0 | +| `GET /prechecks/{id}` | DTO可完整恢复来源阶段、文件版本、Hash、计数 | +| `POST /prechecks/{id}/confirm` | 只接受一次确认;过期/Hash变化返回`PRECHECK_EXPIRED` | +| `GET /runs/{runNo}` | 页面关闭后仍可查询;不可越权查看其他无权限Run | +| `POST /runs/{runNo}/cancel` | 原因必填;只取消未开始项;成功单据不撤销 | +| `POST /items/{id}/retry` | 只创建新Attempt;`result_unknown`拒绝自动/手工重试策略按冻结结论执行 | +| `POST /items/{id}/manual-close` | 原因必填;状态变为`manually_closed`;后续排程不再处理 | +| `GET /exceptions.xlsx` | 七Sheet、原始行追溯、敏感字段脱敏、下载审计 | +| `GET /items/{id}/audit` | 时间线按事件序列返回,快照Hash可验证 | + +### 7.2 后台配置API + +| 接口组 | 关键断言 | +| --- | --- | +| 来源CRUD | 收料用途、RPA/Callback类型、解析方案和固定来源仓必填;发货来源不受影响 | +| 策略草稿 | 只能管理员修改;禁止容差、部分调拨、result_unknown自动重试 | +| 映射CRUD | 同一路由只能一个ERP组织;来源仓强制来自来源配置;目标HUB缺失阻断发布 | +| 排程CRUD | 08:00收料与09:00调拨默认值;来源独立并发配置;不能重复启用相同来源活动任务 | +| 通知配置 | 所有人去重;空数据默认关闭;通知失败不改变业务状态 | +| 发布/校验 | 发布前完整门禁;版本Diff和before/after快照审计;Secret明文永不返回 | + +### 7.3 统一错误码 + +错误码必须同步四语言 `frontend/src/locales/*/errors.json`。一期至少冻结: + +```text +TRANSFER_PERMISSION_DENIED +TRANSFER_RECEIPT_NOT_MATURED +TRANSFER_FILE_NOT_READY +TRANSFER_FILE_SCHEMA_INVALID +TRANSFER_INVOICE_CONFLICT +TRANSFER_QUANTITY_MISMATCH +TRANSFER_ERP_INVENTORY_NOT_FOUND +TRANSFER_PRECHECK_EXPIRED +TRANSFER_CONFIRMATION_REQUIRED +TRANSFER_DUPLICATE_NOT_VERIFIED +TRANSFER_RESULT_UNKNOWN +TRANSFER_MANUAL_CLOSE_REASON_REQUIRED +TRANSFER_CONFIG_PUBLISH_BLOCKED +TRANSFER_SECRET_NOT_EXPOSED +TRANSFER_NOTIFICATION_FAILED +``` + +--- + +## 8. L3 Worker、并发和故障注入TDD + +测试目录:`backend/tests/jobs/test_in_transit_transfer_jobs.py`、`backend/tests/workers/test_in_transit_transfer_worker.py`。 + +必须用故障注入而不是等待真实超时: + +| 场景 | 预期 | +| --- | --- | +| 两个请求同时准备同一来源文件 | 一个SourceJob,RPA调用1次 | +| DBS失败、Crane成功 | Crane继续,Run保留来源级失败 | +| Worker领取后崩溃 | 租约过期后可恢复,不重复成功Invoice | +| ERP写入成功后进程崩溃 | 重启只按Invoice幂等键确认,不重复建单 | +| ERP写超时且结果未知 | `result_unknown`,自动写入0 | +| 请求停止 | 未开始项cancelled,已成功项保持success | +| 写并发配置大于1 | 发布校验拒绝,或运行时强制限制为1 | +| 同一来源两个排程Run | 锁阻断第二个Run,不重复消费文件 | + +并发验收:来源并发默认2,ERP查询并发默认2,ERP写并发默认1;同Invoice并发执行数必须为1。 + +--- + +## 9. L4 前端组件TDD + +### 9.1 对话组件 + +建议测试文件: + +```text +frontend/src/features/chat/components/messages/transfer/TransferFileProgressCard.spec.ts +frontend/src/features/chat/components/messages/transfer/TransferPrecheckCard.spec.ts +frontend/src/features/chat/components/messages/transfer/TransferConfirmationCard.spec.ts +frontend/src/features/chat/components/messages/transfer/TransferProgressCard.spec.ts +frontend/src/features/chat/components/messages/transfer/TransferResultCard.spec.ts +frontend/src/features/chat/components/messages/transfer/TransferExceptionCard.spec.ts +frontend/src/features/chat/composables/useChatTransfer.spec.ts +``` + +必须验证: + +- 文件准备卡逐来源显示DBS/Crane阶段,不伪造总百分比。 +- 当天收料显示未成熟,不显示ERP库存异常。 +- 预检卡展示可执行数、阻断数、预计调拨总数量和预计ERP写入数。 +- 阻断项checkbox禁用,用户不能编辑数量、仓库或ERP组织。 +- 确认卡显示10分钟倒计时和失效原因。 +- 执行中显示Run、已处理/成功/失败、来源进度;关闭页面后可恢复。 +- 结果卡区分success、duplicate_success、technical_failed、result_unknown、notification_failed。 +- 异常卡提供证据下载、手工重试、人工关闭;关闭原因为空时按钮不可提交。 +- 查询与预检阶段在同一历史会话中原位更新,不产生重复历史项。 + +### 9.2 后台配置组件 + +建议新增: + +```text +frontend/src/features/admin/modules/in-transit-transfer/TransferSourceConfigPage.spec.ts +frontend/src/features/admin/modules/in-transit-transfer/TransferStrategyPage.spec.ts +frontend/src/features/admin/modules/in-transit-transfer/TransferSchedulePage.spec.ts +frontend/src/features/admin/modules/in-transit-transfer/TransferPublishPage.spec.ts +frontend/src/features/admin/modules/in-transit-transfer/TransferAuditPage.spec.ts +``` + +必须验证: + +- 收料用途与发货用途分开显示、保存和校验。 +- Crane显示HTTP Callback,不显示RPA密码字段。 +- ERP地址、凭据、Secret只显示注入状态,DOM中不得出现明文。 +- 策略禁止开启部分调拨、容差、result_unknown自动重试。 +- 发布前门禁未通过时发布按钮禁用并展示阻断原因。 +- 发布成功后版本号递增,显示Diff摘要和审计记录。 +- 所有保存、查看、验证、发布和停用操作展示统一反馈。 + +--- + +## 10. L5 E2E主路径 + +测试文件:`frontend/e2e/in-transit-transfer.spec.ts`。 + +### 10.1 对话人工执行 + +1. 仓库管理员进入在途仓调拨Agent。 +2. 点击“查询今天可调拨数据”。 +3. 观察文件准备阶段:DBS复用ready,Crane实时Callback。 +4. 预检完成后确认当天未成熟项未进入ERP查询。 +5. 点击执行,确认卡展示范围、总数量和预计ERP写入。 +6. 点击一次“执行调拨”。 +7. 刷新页面,Run仍可恢复。 +8. 检查成功单号、异常项和审计时间线。 + +### 10.2 自动排程 + +1. 触发08:00收料排程。 +2. 触发09:00自动调拨排程。 +3. 验证缺失文件时自动实时抓取。 +4. 验证历史可恢复异常创建新Attempt。 +5. 验证每次非空Run只发送一条汇总企微通知和一份异常Excel。 +6. 验证空数据Run为`success + no_data`,无ERP写入、无通知。 + +### 10.3 异常恢复 + +覆盖:数量不一致、ERP无库存、技术失败、ERP结果未知、通知失败、人工关闭、请求停止和重复Invoice。 + +--- + +## 11. 性能、可靠性和安全验收 + +### 11.1 指标 + +| 指标 | 目标 | +| --- | ---: | +| 预检接口首个进度响应 | ≤5秒 | +| 已有Ready文件的预检创建P95 | ≤800ms | +| 预检DTO恢复P95 | ≤500ms | +| 进度投影读取P95 | ≤500ms | +| 同来源重复RPA触发 | 0 | +| 当天收料ERP查询/写入 | 0 | +| 未确认或过期确认ERP写入 | 0 | +| `result_unknown`自动重试 | 0 | +| 审计覆盖率 | 100% | +| 审计Hash复算一致率 | 100% | +| 前端构建 | `npm run build`通过 | + +### 11.2 安全测试 + +- 无Agent权限访问任何调拨API均返回403。 +- 有Agent权限但无配置权限不能访问后台写操作。 +- 不能通过前端篡改来源仓、目标HUB仓、ERP组织或数量。 +- Secret、SOAP凭据、Webhook Token不出现在响应、日志、Excel和DOM。 +- 下载异常Excel、查看审计和查看ERP结果都产生读审计。 +- 业务用户不可删除Invoice、Run、Attempt或审计事件。 + +### 11.3 数据一致性不变量 + +每次测试和生产自检都必须验证: + +```text +成功ERP单据数 <= 可执行Invoice数 +ERP写入数量 = success数量 + duplicate_success数量 +blocked / not_matured / result_unknown 不得产生ERP写调用 +manual_close后不得再次生成Attempt +每次Attempt只能有一个终态 +每个Invoice在同一ERP组织内最多一个成功单号 +通知状态不改变ERP业务状态 +审计事件Hash可由存储快照重算 +``` + +--- + +## 12. TDD分阶段执行门禁 + +### Phase 0:契约和测试底座 + +先写并提交:日期、状态机、DTO、审计、权限、错误码和Fake外部系统测试。只有L0全绿,才允许创建迁移和服务实现。 + +验收:测试先失败;实现后全部通过;非法状态和敏感字段断言覆盖100%。 + +### Phase 1:文件与只读预检 + +先写文件解析、汇总、ready复用、RPA幂等、D+1和ERP查询Stub测试,再实现文件准备与预检服务。 + +验收:当前ready复用正确;缺失文件只触发一次RPA;当天收料ERP调用0;DBS/Crane互不阻断。 + +### Phase 2:确认与ERP写入 + +先写确认Hash、写前复检、原子回滚、重复Invoice和结果未知测试,再实现执行Worker。 + +验收:未确认、过期、库存变化均写入0;成功/重复成功单号可追溯;未知结果不自动重试。 + +### Phase 3:排程、恢复、通知和后台配置 + +先写排程、历史新Attempt、3/5/7天老化、七Sheet Excel、单次汇总通知、配置草稿/发布/审计测试,再实现排程和后台配置API/页面。 + +验收:非空排程一条通知;空数据不通知;通知失败不改ERP结果;发布门禁阻断不完整配置;Secret不泄露。 + +### Phase 4:E2E、性能和上线回归 + +先写人工执行、自动排程、异常恢复、刷新恢复、权限越权和真实测试ERP沙箱E2E,再进行性能与故障压测。 + +验收:主路径、高风险路径和回滚路径全部通过;构建、迁移、专项测试、E2E和压测均达到11章指标。 + +--- + +## 13. 测试执行命令 + +### 后端 + +```powershell +cd D:\Workspace\HxProjects\hxops\backend +pytest -q tests/services/in_transit_transfer +pytest -q tests/api/test_in_transit_transfer_api.py tests/jobs/test_in_transit_transfer_jobs.py +pytest -q -m pure_unit +``` + +### 前端 + +```powershell +cd D:\Workspace\HxProjects\hxops\frontend +npm run test:unit -- src/features/chat/components/messages/transfer src/features/admin/modules/in-transit-transfer +npm run build +``` + +### 全量质量门禁 + +```powershell +cd D:\Workspace\HxProjects\hxops +git diff --check +cd backend; pytest -q +cd ..\frontend; npm run test:unit; npm run build +``` + +命令中的测试路径在实现阶段创建;路径不存在时不能通过空目录或跳过测试伪造成功,CI必须将缺失测试文件视为失败。若调拨测试尚未创建,Phase 0验收必须明确记录为未完成,不得用全量既有测试代替。 + +--- + +## 14. 缺陷分级与发布阻断 + +| 等级 | 示例 | 发布要求 | +| --- | --- | --- | +| P0 | 未确认写ERP、重复建单、审计缺失、Secret泄露、当天收料写入 | 立即阻断,修复并回归全部高风险套件 | +| P1 | 历史失败不恢复、结果状态错误、通知与ERP结果耦合、错误权限放行 | 阻断生产,修复后通过对应阶段E2E | +| P2 | 进度文案缺失、Excel列顺序错误、非关键页面交互异常 | 可延期但必须有Issue和验收期限 | +| P3 | 视觉间距、非关键辅助文案 | 不阻断一期上线 | + +任何P0/P1未关闭,或11章任一硬指标不达标,均不得进入生产验收。 + +--- + +## 15. TDD交付物清单 + +每个阶段必须同时交付: + +1. 测试代码及稳定Fixture。 +2. 被测实现代码。 +3. 测试运行日志和失败/修复记录。 +4. 数据库迁移及迁移测试(如涉及模型)。 +5. API/DTO变更说明。 +6. 审计事件覆盖矩阵更新。 +7. 规格说明书和功能清单同步更新。 +8. 阶段验收报告:通过项、未通过项、已知风险和下一阶段入口条件。 + +没有测试日志、失败用例到通过用例的证据,不能宣称该阶段完成。 diff --git a/docs/features/in-transit-transfer/minimum-implementation-spec.md b/docs/features/in-transit-transfer/minimum-implementation-spec.md index 2d506c51..a109c07a 100644 --- a/docs/features/in-transit-transfer/minimum-implementation-spec.md +++ b/docs/features/in-transit-transfer/minimum-implementation-spec.md @@ -6,6 +6,8 @@ > 技术基线:Vue 3 + TypeScript + TailwindCSS;Flask + SQLAlchemy 2.0 + PostgreSQL;Gevent SSE;现有 Job/Worker、RPA、企业微信和 MinIO > 兼容原则:不考虑历史版本兼容,不建设独立集成中心,不允许 Dify 直接写 ERP +> 测试规范:[in-transit-transfer-tdd.md](./in-transit-transfer-tdd.md)。正式开发必须遵循该文档的 Red → Green → Refactor 顺序和阶段门禁。 + --- ## 1. 文档目标 diff --git a/docs/features/in-transit-transfer/prd.md b/docs/features/in-transit-transfer/prd.md new file mode 100644 index 00000000..8342ce4d --- /dev/null +++ b/docs/features/in-transit-transfer/prd.md @@ -0,0 +1,508 @@ +# 在途仓自动调拨 Agent 产品需求文档(PRD) + +## 文档信息 + +| 项目 | 内容 | +| --- | --- | +| 产品 | HXOPS 在途仓自动调拨 Agent | +| 文档版本 | 0.9 评审稿 | +| 日期 | 2026-08-10 | +| 作者 | 产品与项目团队 | +| 主要评审人 | 仓储业务负责人、ERP团队、前端、后端、测试、运维、安全 | +| 状态 | 需求已基本冻结,待补成功指标基线和少量外部接口结论 | + +### 变更记录 + +| 版本 | 日期 | 变更说明 | +| --- | --- | --- | +| 0.9 | 2026-08-10 | 基于业务澄清、完整规格、原型和TDD形成正式PRD评审稿 | + +### 关联文档 + +- [完整规格说明书](./minimum-implementation-spec.md) +- [TDD实施与验证规范](./in-transit-transfer-tdd.md) +- [完整产品与交付路线图](./roadmap.md) +- [前端产品需求文档](./frontend-product-requirements.md) +- [用户对话HTML原型](../../prototype/in-transit-transfer-agent-mvp.html) +- [后台配置HTML原型](../../prototype/in-transit-transfer-admin-config-mvp.html) + +--- + +## 1. 执行摘要 + +我们将在现有HXOPS中建设“在途仓自动调拨 Agent”,服务拥有Agent权限的仓库管理人员,解决当前需要人工获取DBS/Crane收料汇总、逐张核对ERP账面库存、人工创建审核过账调拨单,并容易遗漏历史失败Invoice的问题。用户可通过对话查询和预检,在看到范围、预计调拨总数量和预计ERP写入后确认一次执行;后台排程可每日自动处理新增及可恢复历史异常。Dify只负责意图理解,ERP写操作由HXOPS确定性业务服务和后台Worker执行,所有节点均保留操作人、时间、前后快照、Diff和Hash审计。 + +一期优先实现安全、可恢复、可审计的最小闭环,不建设独立集成中心,不支持部分数量调拨,不允许Dify持有ERP写权限。 + +## 2. 问题陈述 + +### 2.1 谁遇到了问题 + +主要是负责DBS、Crane在途仓到HUB仓调拨的仓库管理人员。他们需要根据货代收料数据与ERP账面库存,判断哪些Invoice可以调拨,并完成ERP新建、审核和过账。 + +管理员和ERP管理员是次要参与者:前者维护来源、策略、排程和通知,后者提供ERP接口、测试组织、白名单和凭据。 + +### 2.2 当前问题 + +当前业务需要跨货代系统、Excel和ERP完成多个步骤: + +1. 从DBS或Crane获取Invoice收料汇总。 +2. 按Invoice查询ERP账面库存。 +3. 判断收料数量是否完全匹配ERP库存。 +4. 匹配时创建、审核、过账ERP调拨单。 +5. 不匹配时整理异常Excel并通知仓库人员。 +6. 次日继续处理之前失败或未完成的Invoice。 + +这些步骤如果依赖人工,会产生等待、重复核对、漏处理、重复建单和不可追溯等风险。用户发起查询后如果系统需要实时抓取文件,也容易因长时间无反馈而误认为系统无响应。 + +### 2.3 用户影响 + +- 需要在多个系统间切换并人工核对数量。 +- 无法快速判断当前处于文件抓取、ERP查询还是建单阶段。 +- 同一收料日期部分失败后,容易在后续工作日被遗忘。 +- ERP超时、重复Invoice和结果未知场景容易被误判或重复操作。 +- 出现问题时缺少统一的文件、原始行、库存、单号和操作时间线。 + +### 2.4 业务影响 + +- 调拨处理周期不可控。 +- 人工重复劳动和操作错误较多。 +- 历史失败积压影响在途库存及时入HUB仓。 +- ERP重复建单或错误写入属于高风险业务事故。 +- 缺少完整审计时,异常调查和责任定位成本较高。 + +### 2.5 现有证据 + +- 已确认业务使用DBS、Crane的Invoice收料汇总,并按Invoice查询ERP库存。 +- 已确认同一收料日期可能只有部分Invoice调拨成功,需要防止失败项被遗忘。 +- 已确认当天收料不可能当天执行调拨。 +- 已确认ERP以Invoice No作为业务幂等键,并拒绝重复Invoice、返回原调拨单号。 +- 已确认ERP一个接口原子完成新建、审核、过账,失败时不产生单据。 +- 已确认后台自动执行需要企业微信汇总通知和异常Excel。 + +🔵 **开放问题:** 当前人工完成一张Invoice核对和建单的平均耗时、每月Invoice量、历史漏处理率和异常处理周期尚无正式基线数据。上线前需要由仓储业务负责人补齐,以验证效率收益。 + +## 3. 目标用户与人物角色 + +### 3.1 主要角色:仓库管理人员 + +- **职责:** 查询在途仓收料、核对库存、执行调拨、处理异常。 +- **工作环境:** 日常使用HXOPS、货代系统、Excel和ERP。 +- **目标:** 快速知道哪些Invoice可以安全调拨,并获得明确的执行结果。 +- **痛点:** 系统切换多、人工比对容易出错、长任务无进度、失败项可能遗漏。 +- **当前行为:** 人工导出或等待文件,查询ERP,按结果分别建单或整理异常。 + +#### Jobs-to-be-Done + +- **功能性任务:** 当收料数据可用时,准确完成所有可调拨Invoice,并识别不可执行项。 +- **情绪性任务:** 确认系统没有遗漏Invoice,也不会未经确认错误写入ERP。 +- **协作性任务:** 向仓库同事提供统一、可解释、可下载的执行和异常结果。 + +### 3.2 次要角色:调拨配置管理员 + +- 维护收料来源、调拨策略、仓库映射、排程和通知。 +- 通过草稿、校验、发布流程让配置生效。 +- 查看配置Diff、连接验证和配置审计。 +- 不在页面查看ERP或RPA凭据明文。 + +### 3.3 外部协作角色:ERP管理员 + +- 提供SOAP WebService、测试组织、白名单和凭据。 +- 配合确认ERP响应、重复Invoice语义、错误码和沙箱验收。 +- 生产凭据通过环境变量或Secret注入。 + +🔶 **假设:** 一期所有拥有该Agent权限的用户均属于可信仓库管理人员,可以查看同权限范围内其他用户发起的Run。该权限模型已被业务接受,但上线前仍需安全评审确认。 + +## 4. 战略背景 + +### 4.1 业务目标 + +- 快速完成一期在途仓调拨闭环。 +- 将重复人工核对转换为系统确定性匹配。 +- 降低重复建单、错单和漏处理风险。 +- 建立对话式业务操作与后台自动执行的可复用模式。 +- 形成全链路审计,为后续企业集成平台演进保留边界。 + +### 4.2 为什么现在做 + +- 当前已有HXOPS Chat、Agent权限、库存来源、RPA排程、Worker、企业微信和审计能力,可在较小增量下形成闭环。 +- 用户已明确一期优先快速完成调拨业务,不等待独立企业集成中心建设。 +- 历史失败Invoice存在持续遗漏风险,需要尽快建立自动复核和老化提醒机制。 +- ERP已具备按Invoice拒绝重复并返回原单号的基础幂等能力。 + +### 4.3 产品定位与差异 + +本产品不是通用RPA控制台,也不是让大模型直接操作ERP。差异在于: + +- 对话负责理解用户目标和展示结构化结果。 +- HXOPS确定性服务负责文件、库存、数量和状态门禁。 +- 后台Run负责可恢复执行。 +- ERP写入前有一次明确确认和写前复检。 +- 历史异常通过待处理池和新Attempt受控恢复。 +- 全部读写节点可审计。 + +🔵 **开放问题:** 本项目尚未定义公司级OKR或可量化节省工时目标。本PRD先以业务闭环、安全和自动化成功率作为产品目标,待业务基线确认后补充财务收益。 + +## 5. 解决方案概览 + +### 5.1 用户侧方案 + +功能作为现有HXOPS Chat中的专用Agent提供。用户可以自然语言查询今天、指定日期、指定来源或指定Invoice的可调拨情况。 + +系统先检查当前业务日期的最新Ready收料文件;缺失时实时触发来源获取,并在对话中显示来源级进度。文件完成后,系统按D+1规则过滤当天未成熟收料,汇总相同Invoice多行数量,查询ERP账面库存并生成预检结果。 + +如果用户要求执行,系统展示可执行Invoice、预计调拨总数量和预计ERP写入数。用户点击一次“执行调拨”后,后台Worker写前重新查询ERP,并逐项调用ERP原子调拨接口。页面关闭或SSE断开不影响后台任务,用户重新进入会话可以恢复Run状态。 + +### 5.2 后台自动方案 + +- 08:00收料文件抓取排程。 +- 09:00自动调拨排程。 +- 自动调拨仍调用统一文件准备服务,不假设08:00已成功。 +- DBS、Crane在同一排程内来源级独立执行。 +- 每次非空Run发送一条企业微信汇总通知并附一份异常Excel。 +- 空数据Run不通知。 + +### 5.3 历史失败恢复 + +所有未成功且未`manually_closed`的历史Invoice进入待处理池。每日排程重新读取最新文件和ERP库存,通过全部门禁后创建新Attempt执行;旧Attempt永久保留。 + +- 数量不一致、ERP无库存、明确技术失败和`precheck_expired`可重新预检。 +- `result_unknown`不自动重试。 +- `manually_closed`永久排除。 +- 3天提醒、5天升级、7天严重积压。 + +### 5.4 管理后台方案 + +复用现有库存来源和排程管理,增加: + +- 收料用途的DBS/Crane来源实例。 +- 调拨策略。 +- ERP组织、来源仓和目标HUB仓映射。 +- 自动排程和通知配置。 +- 草稿、校验、发布和配置审计。 + +### 5.5 核心用户流程 + +```text +用户发起查询/执行 +→ 检查当天Ready文件 +→ 缺失来源实时获取并展示进度 +→ 解析、校验、汇总Invoice +→ 过滤当天未成熟收料 +→ 查询ERP账面库存 +→ 数量匹配与预检 +→ 查询场景直接返回结果 +→ 执行场景展示确认卡 +→ 用户点击一次执行调拨 +→ Worker写前复查ERP +→ 逐项原子建单/审核/过账 +→ 展示结果、异常、审计 +→ 自动排程发送一条汇总通知和异常Excel +``` + +## 6. 成功指标 + +### 6.1 北极星指标 + +**安全自动调拨完成率**:满足全部业务门禁并由系统成功完成ERP审核过账的可执行Invoice数 ÷ 全部可执行Invoice数。 + +🔶 **假设目标:** 一期稳定运行30天后达到不低于95%。正式目标需结合ERP可用性和真实业务基线确认。 + +### 6.2 业务结果指标 + +| 指标 | 一期目标 | +| --- | ---: | +| 当天收料产生ERP查询或写入 | 0 | +| 未确认、过期确认或预检变化产生ERP写入 | 0 | +| 同ERP组织内重复建单 | 0 | +| `result_unknown`自动重试 | 0 | +| 历史可恢复失败下一排程重新预检率 | 100% | +| `manually_closed`再次自动处理 | 0 | +| 非空自动Run的汇总通知条数 | 每Run恰好1条 | +| 空数据Run通知条数 | 0 | +| 审计覆盖率 | 100% | +| 审计Hash复算一致率 | 100% | + +### 6.3 用户体验指标 + +| 指标 | 一期目标 | +| --- | ---: | +| 缺文件时首次进度反馈 | ≤5秒 | +| 进行中Run刷新/重登恢复率 | 100% | +| 阻断异常具有明确原因和下一步 | 100% | +| 可执行预检展示预计总数量和ERP写入数 | 100% | + +### 6.4 效率指标 + +🔵 **开放问题:** 以下指标需要先采集上线前基线,再冻结目标: + +- 单张Invoice人工处理时间。 +- 每日/每月Invoice数量。 +- 自动化前后人工介入率。 +- 历史失败平均处理时长。 +- 每月节省工时。 + +### 6.5 护栏指标 + +- ERP错误写入数必须为0。 +- 越权写入数必须为0。 +- Secret在API、日志、Excel和DOM中的明文暴露数必须为0。 +- 通知失败不得改变ERP业务状态。 +- 原发货库存来源和排程不得发生功能回归。 + +## 7. Epic假设与用户故事 + +### 7.1 Epic假设 + +我们相信,为仓库管理人员提供一个由确定性业务门禁控制的对话式自动调拨Agent,并辅以后台排程、失败待处理池和全链路审计,可以在不增加ERP错误写入风险的前提下,显著提升可执行Invoice的自动完成率并避免历史失败被遗忘。我们将通过安全自动调拨完成率、错误写入数、历史失败复核率和人工处理时长验证这一假设。 + +### 7.2 用户故事 + +#### US-01 查询可调拨数据 + +作为仓库管理人员,我希望通过自然语言查询今天、指定来源或指定Invoice的可调拨情况,以便快速了解当前范围。 + +**验收标准:** + +- 用户有Agent权限时可以发起查询。 +- 系统识别日期、来源和Invoice范围。 +- 查询不会产生ERP写入。 +- 同一查询Run在历史会话中只保留一条记录。 + +#### US-02 查看文件准备进度 + +作为仓库管理人员,我希望看到DBS、Crane文件准备进度,以便知道系统正在处理什么。 + +**验收标准:** + +- 当天Ready文件可以复用。 +- 当天缺文件时实时触发对应来源获取。 +- DBS与Crane独立显示状态,互不阻断。 +- 页面关闭后任务继续,重新进入后恢复进度。 + +#### US-03 查看预检结果 + +作为仓库管理人员,我希望看到可执行、未成熟和阻断数量,以便判断是否执行调拨。 + +**验收标准:** + +- 当天收料标记`not_matured`,不查询ERP。 +- 相同Invoice多行只汇总收料数量。 +- 数量完全相等才可执行。 +- 页面展示可调拨总数量和预计ERP单据数。 + +#### US-04 选择并确认执行 + +作为仓库管理人员,我希望选择全部或部分可执行Invoice并确认一次,以便控制本次ERP写入范围。 + +**验收标准:** + +- 阻断项不可选择。 +- 用户不能修改数量、仓库或ERP组织。 +- 确认卡有效10分钟。 +- 文件、库存、映射或选择范围变化后确认失效。 +- 重复点击不能创建重复Run。 + +#### US-05 查看执行进度和结果 + +作为仓库管理人员,我希望看到后台ERP调拨进度和逐项结果,以便掌握任务是否完成。 + +**验收标准:** + +- Worker写前重新查询ERP。 +- 逐项执行可执行Invoice,一个失败不影响其他项。 +- 成功、重复成功、技术失败和结果未知分开显示。 +- 成功/重复成功显示ERP调拨单号。 + +#### US-06 处理历史异常 + +作为仓库管理人员,我希望系统自动关注以前失败的Invoice,以便避免遗忘。 + +**验收标准:** + +- 所有未成功且未人工关闭项进入待处理池。 +- 可恢复项下一排程重新预检。 +- 每次恢复创建新Attempt,不覆盖历史。 +- `result_unknown`不自动重试。 +- 3/5/7天按阈值展示提醒。 + +#### US-07 人工关闭或重试 + +作为仓库管理人员,我希望对允许的异常执行手工重试或标记无需处理,以便处理系统无法自动决策的业务情况。 + +**验收标准:** + +- 人工关闭原因必填。 +- 关闭后状态为`manually_closed`且永久排除。 +- 手工重试创建新Attempt。 +- 操作前后快照和原因进入审计。 + +#### US-08 接收自动排程通知 + +作为任务所有者或通知人,我希望收到一次汇总通知和异常Excel,以便了解自动调拨结果。 + +**验收标准:** + +- 每个非空自动Run只发送一条汇总通知。 +- 附带一份七Sheet异常Excel。 +- 空数据Run不通知。 +- 通知失败记录`notification_failed`,不改变ERP结果。 + +#### US-09 管理调拨配置 + +作为调拨配置管理员,我希望维护来源、策略、映射、排程和通知,以便控制自动调拨行为。 + +**验收标准:** + +- DBS与Crane为独立收料来源实例。 +- 配置通过草稿、校验、发布流程生效。 +- 发布门禁不完整时禁止发布。 +- 生产地址和凭据不以明文返回页面。 +- 每次查看、保存、验证和发布均写审计。 + +#### US-10 追溯业务与配置操作 + +作为授权用户或管理员,我希望查看完整审计时间线,以便定位问题和证明操作过程。 + +**验收标准:** + +- 审计包含操作人、角色、时间、内容、前后快照、Diff和Hash。 +- 可关联会话、ChatLog、Run、Source Job、Invoice、Attempt和Operation ID。 +- 查看和下载也产生访问审计。 +- 业务用户不能删除审计。 + +### 7.3 关键边界与异常 + +- 当天收料:仅显示未成熟,不作为错误。 +- ERP库存大于或小于收料数量:整Invoice阻断,不允许部分调拨。 +- ERP业务失败:原子回滚,状态为明确失败。 +- ERP超时无法确认结果:`result_unknown`,不自动重试。 +- 重复Invoice且原单已审核过账:`duplicate_success`。 +- 请求停止:只取消尚未开始项,保留成功单据。 +- 通知失败:业务结果不变。 +- 空数据:Run成功并标记`no_data`。 + +## 8. 一期范围 + +### 8.1 包含 + +- 对话查询、文件进度、预检、确认、执行、结果和异常。 +- DBS RPA收料文件和Crane HTTP Callback收料文件。 +- D+1成熟过滤和相同Invoice多行数量汇总。 +- ERP账面库存查询和原子新建/审核/过账。 +- Invoice幂等和重复成功识别。 +- 08:00文件抓取和09:00自动调拨排程。 +- 历史失败待处理池、自动复核、新Attempt和老化提醒。 +- 企业微信单次汇总通知和七Sheet异常Excel。 +- 人工重试、请求停止和人工关闭。 +- 管理后台配置、校验、发布和配置审计。 +- 四语言、移动端基本适配和全链路审计。 + +### 8.2 不包含 + +- 独立企业集成中心:一期在业务模块内隔离ERP Adapter,未来可迁移。 +- Dify直接访问ERP、RPA、数据库或企业微信。 +- 新建独立仓库业务后台一级入口。 +- 部分数量调拨、单位换算、数量容差、批次和库位逻辑。 +- ERP写入自动技术重试。 +- `result_unknown`自动重试。 +- 通知自动重试。 +- 空数据通知。 +- 用户修改来源仓、目标仓、ERP组织或调拨数量。 +- 业务记录和审计记录删除。 +- 历史路径兼容和现有集成迁移。 + +### 8.3 未来考虑 + +- 薄集成内核逐步演进为独立企业集成平台。 +- 对话阶段按策略允许免确认直接执行。 +- 更多货代来源和ERP组织。 +- 更完整的运营分析和节省工时看板。 + +## 9. 依赖与风险 + +### 9.1 技术依赖 + +- 现有HXOPS Chat、Agent Registry、Chat Action和SSE链路。 +- 库存来源、RPA Profile、Callback和Ready快照。 +- PostgreSQL、Redis、Job Queue、独立Worker和MinIO。 +- 企业微信通知能力。 +- ERP SOAP WebService、测试组织和网络白名单。 +- 四语言国际化和统一错误契约。 + +### 9.2 团队依赖 + +- 仓储业务:确认文件样例、字段、异常语义和UAT数据。 +- ERP团队:冻结WSDL、请求响应、错误码、重复Invoice语义和沙箱。 +- 运维/ERP管理员:提供白名单和Secret注入。 +- 前端、后端、测试:按照TDD阶段门禁协同交付。 + +### 9.3 核心关键风险 + +**预检确认与Worker实际写入之间,文件、ERP库存或仓库映射发生变化,导致实际写入超出用户确认范围。** + +缓解措施:冻结文件版本和checksum,保存预检Hash,确认10分钟失效,Worker写前重新查询ERP,变化项进入`precheck_expired`且ERP写调用为0。 + +### 9.4 风险清单 + +| 风险 | 类型 | 影响 | 缓解措施 | +| --- | --- | --- | --- | +| ERP超时且无反查能力 | 技术/业务 | 结果未知、重复操作 | Invoice幂等、`result_unknown`隔离、禁止自动重试、人工核实 | +| RPA/Callback丢失 | 技术 | 文件准备长期等待 | 来源级租约、超时、状态恢复、人工刷新 | +| 文件结构变化 | 业务/技术 | 汇总错误或漏项 | 解析Profile版本、必填列检查、结构漂移阻断 | +| 历史失败被遗忘 | 业务 | 在途库存长期积压 | 待处理池、每日复核、3/5/7天升级 | +| 自动恢复误补偿 | 业务 | 不应执行的Invoice被写入 | 最新文件、ERP、映射和幂等全门禁,新Attempt | +| 通知失败被误认为调拨失败 | 体验 | 重复人工处理 | `notification_failed`与业务状态分离 | +| 审计数据膨胀 | 资源 | 数据库压力 | 摘要和Hash留库,大对象归档MinIO | +| ERP并发能力未知 | 资源/进度 | 超时和未知结果 | 写并发默认1,沙箱压测后再调整 | +| 前后端契约漂移 | 进度 | 卡片状态错误 | DTO冻结、契约测试、TDD和Mock Fixture | +| 一期范围膨胀为集成中心 | 进度 | 无法快速交付 | 明确一期业务内Adapter,平台化另立项目 | + +## 10. 开放问题与决策日志 + +### 10.1 待关闭问题 + +| 问题 | Owner | 截止点 | 状态 | +| --- | --- | --- | --- | +| 当前人工单张Invoice处理耗时、月均数量和漏处理率是多少? | 仓储业务负责人 | UAT前 | Open | +| ERP正式WSDL、字段、错误码和脱敏留存字段是什么? | ERP团队 | Phase 0结束前 | Open | +| ERP写超时后人工核实的标准操作步骤和责任人是谁? | ERP团队/仓储 | Phase 2前 | Open | +| 测试环境企业微信附件大小和发送权限是否满足七Sheet Excel? | 运维/企业微信管理员 | Phase 3前 | Open | +| 一期生产成功自动调拨完成率目标最终定为多少? | 产品/仓储 | UAT前 | Open | + +### 10.2 已冻结关键决策 + +- 当天收料不得当天调拨。 +- Invoice No全局唯一,同ERP组织内作为幂等键。 +- ERP接口原子完成新建、审核、过账。 +- 重复Invoice返回原调拨单号且可证明原单已审核过账。 +- 逐项执行,只执行可执行项。 +- 用户执行前一次确认;自动排程不需人工确认。 +- DBS和Crane来源独立,互不影响。 +- 历史可恢复失败每日自动重新预检并创建新Attempt。 +- `result_unknown`不自动重试。 +- 通知失败不改变ERP结果。 +- 不允许业务删除,管理员可归档大对象到低成本存储。 + +## PRD自评 + +### 最强部分 + +**解决方案边界和安全规则。** 业务已经明确冻结了日期成熟、数量完全相等、Invoice幂等、ERP原子写入、确认失效、历史恢复、结果未知隔离和审计要求,可以直接转化为TDD验收契约。 + +### 最弱部分 + +**成功指标的业务基线。** 当前有完整的安全和正确性目标,但缺少人工处理时长、月均量、漏处理率和自动化前基线,因此尚不能可靠量化节省工时和投资回报。 + +### 最高风险假设 + +| 假设 | 风险 | 验证方式 | +| --- | --- | --- | +| 业务量足以支撑自动化收益 | 若量低,收益小于建设成本 | 统计最近3个月Invoice量和人工耗时 | +| ERP在写并发1、60秒超时下稳定 | 若不稳定,结果未知比例过高 | 沙箱压测和超时故障注入 | +| 所有Agent授权用户都应查看同权限Run | 若权限过宽,存在数据暴露 | 安全与仓储负责人联合评审 | +| 七Sheet异常Excel可通过企业微信稳定发送 | 若附件过大,通知体验不完整 | 使用最大预估数据进行附件测试 | + +### 推荐下一步 + +在正式开发前完成一次跨团队PRD评审,优先关闭三个事项:ERP接口契约、人工处理基线、ERP超时后的人工核实SOP。评审通过后严格按照[TDD实施与验证规范](./in-transit-transfer-tdd.md)从Phase 0的失败测试开始开发。 diff --git a/docs/features/in-transit-transfer/roadmap.md b/docs/features/in-transit-transfer/roadmap.md new file mode 100644 index 00000000..79717b04 --- /dev/null +++ b/docs/features/in-transit-transfer/roadmap.md @@ -0,0 +1,795 @@ +# 在途仓自动调拨 Agent 完整产品与交付路线图 + +## 文档信息 + +| 项目 | 内容 | +| --- | --- | +| 产品 | HXOPS 在途仓自动调拨 Agent | +| 文档版本 | 1.0 评审稿 | +| 日期 | 2026-08-10 | +| 路线图范围 | 一期最小闭环、生产硬化、运营优化、集成平台演进 | +| 主要读者 | 仓储业务、产品、前端、后端、测试、ERP、运维、安全 | +| 执行方法 | TDD:Red → Green → Refactor;阶段门禁;Fail-closed | + +### 关联文档 + +- [正式PRD](./prd.md) +- [完整规格说明书](./minimum-implementation-spec.md) +- [TDD实施与验证规范](./in-transit-transfer-tdd.md) +- [前端产品需求文档](./frontend-product-requirements.md) +- [用户对话HTML原型](../../prototype/in-transit-transfer-agent-mvp.html) +- [后台配置HTML原型](../../prototype/in-transit-transfer-admin-config-mvp.html) + +--- + +## 1. 路线图结论 + +项目采用“先形成安全业务闭环,再完成自动化和治理,最后抽离通用集成能力”的路线: + +1. **M0 契约就绪:** 冻结ERP、收料文件、领域状态、审计和测试契约,建立可并行开发的Fake与DTO。 +2. **M1 只读可用:** 用户可在现有HXOPS Chat中查询、看到文件获取进度,并得到可审计的调拨预检结果,全程不写ERP。 +3. **M2 对话闭环:** 用户看到范围、预计调拨总数量和预计ERP写入后,点击一次“执行调拨”,由后台Worker安全完成ERP原子写入。 +4. **M3 自动闭环:** 每日排程自动准备文件、处理新增和可恢复历史异常,并发送一次企业微信汇总通知及异常Excel。 +5. **M4 生产就绪:** 完成权限、安全、性能、故障恢复、归档、运营指标和ERP沙箱验收后上线。 +6. **M5 平台演进:** 在业务稳定后,把已隔离的ERP Adapter、连接配置、发布治理和可观测能力逐步抽离为“薄集成内核”,不反向阻塞一期。 + +### 1.1 两个可交付价值点 + +| 价值点 | 达成阶段 | 可投入范围 | 明确限制 | +| --- | --- | --- | --- | +| 对话式人工调拨试点 | M2 | ERP测试组织或受控小范围生产试点 | 无自动排程;历史异常由人工关注;必须保留一次确认 | +| 一期生产完整闭环 | M4 | 对话与排程正式生产使用 | 不含独立集成中心、部分调拨、ERP写入自动重试 | + +M2不是一期最终完成,只是为了尽早验证真实业务价值的受控切片。只有M4全部门禁通过,才可宣称“一期上线完成”。 + +### 1.2 核心关键风险 + +**预检确认与Worker实际写入之间,文件、ERP库存、路由或仓库映射发生变化,可能导致实际ERP写入超出用户确认范围。** + +该风险是所有阶段的最高优先级门禁,必须同时采用: + +- 固定当前Ready文件版本和checksum。 +- 保存预检输入快照、结果快照及`precheck_hash`。 +- 确认有效期默认10分钟。 +- Worker写前重新查询ERP并重新计算门禁。 +- 任一关键值变化后状态转为`precheck_expired`,ERP写调用为0。 +- 不允许前端或Dify修改数量、组织、来源仓和目标仓。 +- 审计保存确认范围、写前复检结果和前后Hash。 + +--- + +## 2. 路线图原则与边界 + +### 2.1 产品原则 + +- **业务真相确定性:** Dify只理解意图和组织对话,不判断最终库存、不持有ERP写权限。 +- **读取与写入分离:** 查询、预检、确认、执行为不同状态;没有有效确认不得写ERP。 +- **按Invoice隔离:** 自动Run采用逐项结果,只执行可执行项;单项失败不阻断其他Invoice。 +- **来源隔离:** DBS与Crane只是不同调拨源,各自准备文件和报告状态,互不影响。 +- **失败不遗忘:** 未成功且未`manually_closed`的可恢复项进入待处理池;下一排程重新预检并创建新Attempt。 +- **结果未知隔离:** `result_unknown`禁止自动重试,必须执行人工核实SOP。 +- **全链路审计:** 所有读取、下载、确认、执行、重试、关闭、配置和发布节点均可追溯。 +- **前后端解耦:** 前端只消费稳定DTO和Run投影,不自行推导ERP业务状态。 + +### 2.2 一期包含 + +- 现有Chat中的专用自动调拨Agent。 +- 对话查询、文件准备进度、预检、选择、确认、执行、结果、异常和审计。 +- DBS RPA和Crane HTTP Callback收料来源。 +- 当前业务日期最新Ready累计全量文件。 +- D+1成熟规则、Invoice多行收料数量汇总、精确数量匹配。 +- ERP账面库存查询及单接口原子新建、审核、过账。 +- Invoice幂等、重复成功识别、结果未知隔离。 +- 08:00文件获取、09:00自动调拨、历史失败恢复、3/5/7天老化机制。 +- 每个非空自动Run一条企业微信汇总通知和一份七Sheet异常Excel。 +- 人工重试、请求停止、人工关闭及完整审计。 +- 来源、策略、映射、排程、通知、校验和发布配置。 +- 四语言、基础移动端适配、MinIO证据和归档。 + +### 2.3 一期不包含 + +- 独立企业集成中心或现有集成迁移。 +- Dify直连ERP、RPA、数据库或企业微信。 +- 部分调拨、数量容差、单位换算、批次、库位和品质状态。 +- ERP写入自动技术重试、`result_unknown`自动重试、通知自动重试。 +- 用户修改数量、组织、来源仓或目标仓。 +- 业务记录或审计记录删除。 +- 对历史路径和历史版本兼容。 +- 无确认直接执行;只保留未来策略扩展位,默认关闭。 + +--- + +## 3. 阶段总览 + +> 以下是交付顺序,不是未经资源评估的日历承诺。建议以一到两个Sprint为一个阶段容量单位;ERP契约、团队人数和测试环境确认后再形成具体发布日期。 + +| 阶段 | 业务成果 | 主要交付 | 退出门禁 | +| --- | --- | --- | --- | +| Phase 0 契约与测试底座 | 团队对业务真相和外部接口形成一致理解 | ERP/文件契约、状态机、DTO、审计模型、Fake、迁移草案 | 核心L0测试从Red到Green;ERP沙箱契约可执行 | +| Phase 1 文件与只读预检 | 仓储用户能查到“哪些可调拨、为什么” | 文件准备、D+1、汇总、ERP查询、Chat进度与预检 | 当天收料ERP调用0;缺文件5秒内反馈;来源互不阻断 | +| Phase 2 确认与ERP写入 | 对话发起的一次确认调拨闭环 | 确认Hash、写前复检、Worker、ERP原子写、结果卡 | 未确认/过期/变化写入0;重复建单0;单号可追溯 | +| Phase 3 排程与异常闭环 | 系统每日自动处理且不会遗忘失败项 | 排程、待办池、新Attempt、老化、Excel、企微、配置发布 | 可恢复项100%重新预检;非空Run恰好1条通知 | +| Phase 4 生产硬化与上线 | 满足生产安全、稳定和运维要求 | 性能、故障注入、安全、归档、指标、UAT、上线方案 | P0/P1为0;全量门禁通过;业务和ERP签字 | +| Phase 5 优化与平台演进 | 降低新增来源/ERP Operation接入成本 | 薄集成内核、Operation元数据、连接器治理、SLO | 新Operation无需改核心编排;迁移演练成功 | + +### 3.1 关键路径 + +```text +ERP WSDL/错误语义冻结 + ↓ +领域状态机、DTO、Fake ERP、审计契约 + ↓ +文件准备 → Invoice汇总 → ERP只读预检 + ↓ +确认Hash → 写前复检 → ERP原子写入 + ↓ +排程 → 历史恢复 → 通知/Excel + ↓ +故障注入、安全、性能、ERP沙箱UAT + ↓ +受控上线 → 稳定观察 → 平台能力抽离 +``` + +任何绕过“ERP契约→Fake→失败测试→实现”的开发都会把不确定性推迟到生产,应视为进度风险而不是加速。 + +--- + +## 4. Phase 0:契约、领域模型与TDD底座 + +### 4.1 阶段目标 + +- 把已冻结的业务规则转化为可执行的状态机、DTO和测试不变量。 +- 冻结ERP SOAP查询/写入契约、重复Invoice语义和结果分类。 +- 建立Run、Source Job、Precheck、Invoice Item、Attempt和Audit的最小数据模型。 +- 让前后端可基于同一Mock契约并行工作。 + +### 4.2 产品与业务交付 + +- 业务术语表和状态定义完成评审。 +- 确认`receipt_date < business_date`才可进入ERP预检。 +- 确认相同Invoice多行只汇总收料数量,保留原始行。 +- 确认ERP数量必须与收料数量完全相等。 +- 确认重复Invoice只有在ERP返回原单号并确认已审核过账时才为`duplicate_success`。 +- 输出ERP超时/结果未知的人工核实SOP、责任人和处理时限。 + +### 4.3 后端工作包 + +| 类型 | 文件路径 | 修改内容 | +| --- | --- | --- | +| 复用修改 | `backend/app/models/shipping_inventory_config.py` | 为库存来源增加收料用途、固定来源仓、调拨启用和版本化配置;发货与收料用途隔离 | +| 复用修改 | `backend/app/models/__init__.py` | 导出调拨领域模型 | +| 计划新增 | `backend/app/models/in_transit_transfer.py` | 定义Run、SourceJob、Precheck、InvoiceItem、Attempt、AuditEvent和Archive模型 | +| 计划新增 | `backend/migrations/versions/_add_in_transit_transfer.py` | Alembic迁移、约束、唯一键和索引;必须验证upgrade/downgrade | +| 计划新增 | `backend/app/services/in_transit_transfer/contracts.py` | 请求、响应、快照、进度和审计DTO | +| 计划新增 | `backend/app/services/in_transit_transfer/status.py` | 合法状态、终态和转换门禁 | +| 计划新增 | `backend/app/services/in_transit_transfer/audit.py` | before/after、Diff、Hash、actor和关联上下文 | +| 复用修改 | `backend/app/api/admin/shipping_inventory.py` | 来源CRUD支持收料用途和版本字段 | +| 复用修改 | `backend/app/services/admin/shipping_inventory_service.py` | 来源配置校验、激活门禁和敏感字段脱敏 | + +### 4.4 前端工作包 + +| 类型 | 文件路径 | 修改内容 | +| --- | --- | --- | +| 复用修改 | `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue` | 复用库存来源页面,区分收料/发货用途 | +| 复用修改 | `frontend/src/features/admin/modules/shipping-inventory/shippingInventorySourceForm.ts` | 收料来源字段、校验、脏状态和版本冲突处理 | +| 复用修改 | `frontend/src/features/admin/api/admin.api.ts` | 扩展来源和配置版本DTO | +| 计划新增 | 调拨稳定Fixture和Mock DTO | 供Chat卡片、管理页面和契约测试并行使用;实施时按现有Feature Module确定最终目录 | + +### 4.5 TDD顺序 + +1. 先写日期成熟、精确数量、状态机非法迁移测试。 +2. 先写DTO敏感字段和审计Hash测试。 +3. 建立Fake ERP、Fake RPA、Fake WeCom和固定Clock。 +4. 创建模型和迁移,使测试转绿。 +5. Refactor状态常量、快照规范和测试工厂。 + +### 4.6 阶段验收 + +- [ ] ERP正式WSDL、查询字段、写入字段、超时、错误码和脱敏留存范围经ERP团队确认。 +- [ ] Fake ERP覆盖成功、重复成功、原子业务失败、提交前超时和提交后结果未知。 +- [ ] 当天收料的ERP查询与写入调用均为0。 +- [ ] 非法状态转换拒绝率100%。 +- [ ] 迁移upgrade/downgrade成功,模型与数据库约束一致。 +- [ ] 审计before/after、Diff、Hash、actor、request_id、operation_id完整率100%。 +- [ ] Secret出现在DTO、日志Fixture或DOM中的数量为0。 +- [ ] 原发货库存来源回归测试通过。 + +### 4.7 决策门 + +ERP契约和结果未知SOP未关闭时,可以完成纯领域和前端Mock工作,但**不得进入真实ERP写入实现**。 + +--- + +## 5. Phase 1:文件准备与只读预检 + +### 5.1 阶段目标 + +- 用户从现有HXOPS Chat发起查询或执行意图时,系统能准备当天最新有效收料文件。 +- 当文件不存在时实时获取并持续显示进度,避免用户无反馈等待。 +- 系统完成D+1过滤、Invoice汇总和ERP账面库存查询,返回结构化预检结果。 +- 本阶段任何路径均不得调用ERP写接口。 + +### 5.2 用户能力 + +- 查询今天、指定日期、指定来源或指定Invoice的可调拨情况。 +- 查看DBS和Crane独立的文件准备状态。 +- 查看未成熟、可执行、数量不一致、ERP无库存和文件异常。 +- 查看可调拨总数量和预计ERP单据数。 +- 下载只读预检明细和查看原始行追溯。 + +### 5.3 后端工作包 + +| 类型 | 文件路径 | 修改内容 | +| --- | --- | --- | +| 复用修改 | `backend/app/services/chat/action_types.py` | 增加调拨查询和预检Action类型 | +| 复用修改 | `backend/app/services/chat/action_schema.py` | 校验日期、来源、Invoice和只读/执行意图 | +| 复用修改 | `backend/app/services/chat/action_registry.py` | 注册调拨Handler,Dify只产生受限候选Action | +| 复用修改 | `backend/app/jobs/types.py`、`backend/app/jobs/store.py` | 增加文件准备和预检Job类型及领取能力 | +| 计划新增 | `backend/app/services/in_transit_transfer/file_preparation.py` | 复用Ready文件、来源租约、缺失时触发RPA/Callback | +| 计划新增 | `backend/app/services/in_transit_transfer/file_parser.py` | 文件Schema、日期、数量和必填列校验 | +| 计划新增 | `backend/app/services/in_transit_transfer/invoice_aggregator.py` | 同Invoice收料数量汇总和原始行追溯 | +| 计划新增 | `backend/app/services/in_transit_transfer/erp_adapter.py` | 业务模块内隔离SOAP查询/写入边界;本阶段只启用查询 | +| 计划新增 | `backend/app/services/in_transit_transfer/precheck_service.py` | D+1、ERP查询、数量匹配、快照和Hash | +| 计划新增 | `backend/app/services/in_transit_transfer/chat_actions.py` | 调拨查询/预检Action处理 | +| 计划新增 | `backend/app/jobs/handlers/in_transit_transfer_precheck.py` | 持久化异步阶段和来源级状态 | +| 计划新增 | `backend/app/api/in_transit_transfer.py` | 预检创建、恢复、明细和证据API | + +### 5.4 前端工作包 + +| 类型 | 文件路径 | 修改内容 | +| --- | --- | --- | +| 复用修改 | `frontend/src/features/chat/components/messages/ChatMessageBubble.vue` | 按结构化消息类型挂载调拨卡片 | +| 复用修改 | `frontend/src/features/chat/components/ChatMessageList.vue` | 同一会话内原位更新Run阶段,避免重复历史记录 | +| 计划新增 | `frontend/src/features/chat/api/transfer.api.ts` | 调拨API客户端 | +| 计划新增 | `frontend/src/features/chat/types/transfer.types.ts` | 稳定DTO和状态联合类型 | +| 计划新增 | `frontend/src/features/chat/components/messages/TransferFileProgressCard.vue` | 来源级文件准备和恢复进度 | +| 计划新增 | `frontend/src/features/chat/components/messages/TransferPrecheckCard.vue` | 预检汇总、预计数量和只读边界 | +| 计划新增 | `frontend/src/features/chat/components/TransferInvoiceDetailDrawer.vue` | Invoice和原始行证据 | +| 复用修改 | `frontend/src/locales/{zh-CN,zh-TW,en,th}/chat.json` | 四语言调拨文案 | +| 复用修改 | `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json` | 四语言错误码 | + +### 5.5 核心交互门禁 + +- 对话首次进度反馈不晚于5秒。 +- 不显示无法解释的单一Spinner;必须显示当前来源、阶段和最近更新时间。 +- DBS失败时Crane继续,反之亦然。 +- 当天收料显示`not_matured`,不显示为ERP异常。 +- 查询和文件准备不会显示“执行成功”等写入语义。 +- 刷新、切换会话或SSE断开后从Run投影恢复。 + +### 5.6 阶段验收 + +- [ ] 有当日Ready文件时正确复用最新有效版本。 +- [ ] 无Ready文件时,同来源并发请求只创建一个活动Source Job。 +- [ ] 缺文件后5秒内返回来源级进度。 +- [ ] DBS和Crane故障互不影响。 +- [ ] 相同Invoice多行汇总准确率100%,原始行追溯完整率100%。 +- [ ] 当天收料ERP查询和写入均为0。 +- [ ] 数量只有完全相等时为`executable`。 +- [ ] 页面刷新和重新登录后的进行中Run恢复率100%。 +- [ ] 同一查询Run在历史侧栏始终只有一条会话记录。 +- [ ] L0、L1、L2相关测试和前端组件测试全部通过。 + +--- + +## 6. Phase 2:一次确认与ERP原子调拨 + +### 6.1 阶段目标 + +- 首期必须支持从对话发起ERP调拨写操作。 +- 用户在确认卡看到选择范围、预计调拨总数量和预计ERP写入数。 +- 点击一次“执行调拨”后,由独立后台Worker继续执行,页面关闭不影响任务。 +- ERP单接口原子完成新建、审核、过账;逐Invoice记录结果。 + +### 6.2 用户能力 + +- 默认选择全部可执行Invoice,也可以取消部分可执行项。 +- 阻断项不可选择,数量和仓库不可编辑。 +- 查看10分钟确认有效期及失效原因。 +- 查看执行进度、成功单号、重复成功、明确失败和结果未知。 +- 请求停止尚未开始的Invoice,已成功单据不撤销。 + +### 6.3 后端工作包 + +| 类型 | 文件路径 | 修改内容 | +| --- | --- | --- | +| 复用修改 | `backend/app/jobs/types.py`、`backend/app/jobs/handlers/__init__.py` | 注册Transfer Run和Invoice Item Job | +| 复用修改 | `backend/worker_shipping.py` | 接入独立transfer队列启动参数;最终入口以实施时现有Worker模式为准 | +| 计划新增 | `backend/app/services/in_transit_transfer/orchestrator.py` | Run、SourceJob、InvoiceItem和Attempt编排 | +| 计划新增 | `backend/app/services/in_transit_transfer/execution_service.py` | 确认校验、写前复检、ERP调用和结果投影 | +| 计划新增 | `backend/app/services/in_transit_transfer/concurrency.py` | 来源并发、ERP查询并发和ERP写并发限制 | +| 计划新增 | `backend/app/services/in_transit_transfer/cancellation.py` | 停止未开始项并保存原因 | +| 计划新增 | `backend/app/jobs/handlers/in_transit_transfer_run.py` | Run级Handler | +| 计划新增 | `backend/app/jobs/handlers/in_transit_transfer_item.py` | Invoice级Handler | +| 计划新增 | `backend/workers/worker_in_transit_transfer.py` | 独立Worker入口 | +| 复用修改 | `docker-compose.yml` | 增加transfer worker服务;属于高风险文件,实施前必须单独说明影响面 | + +### 6.4 前端工作包 + +| 类型 | 文件路径 | 修改内容 | +| --- | --- | --- | +| 复用修改 | `frontend/src/features/chat/composables/useToolRunProgress.ts` | 识别调拨Run进度和恢复契约 | +| 复用修改 | `frontend/src/features/chat/components/messages/ChatMessageBubble.vue` | 挂载确认、执行和结果卡 | +| 计划新增 | `frontend/src/features/chat/components/messages/TransferConfirmationCard.vue` | Invoice选择、总数量、预计写入和倒计时 | +| 计划新增 | `frontend/src/features/chat/components/messages/TransferProgressCard.vue` | 后台执行阶段、数量和来源进度 | +| 计划新增 | `frontend/src/features/chat/components/messages/TransferResultCard.vue` | ERP结果与通知结果分层展示 | +| 计划新增 | `frontend/src/features/chat/composables/useChatTransfer.ts` | 确认、防重复、重连和投影恢复 | + +### 6.5 ERP结果投影 + +| ERP事实 | 业务状态 | 自动重试 | 用户动作 | +| --- | --- | ---: | --- | +| 成功并返回调拨单号 | `success` | 否 | 查看单号 | +| 重复Invoice,返回原单号且确认已审核过账 | `duplicate_success` | 否 | 查看原单号 | +| 明确业务失败且自动回滚 | `business_failed` | 否 | 修正外部条件后重新预检 | +| 明确技术失败且确认未产生单据 | `technical_failed` | 否 | 允许人工发起新Attempt | +| 超时且无法确认是否落单 | `result_unknown` | 严禁 | 按人工核实SOP处理 | + +### 6.6 阶段验收 + +- [ ] 未确认、确认过期或确认Hash变化时ERP写调用为0。 +- [ ] Worker写前ERP库存变化项写调用为0,状态为`precheck_expired`。 +- [ ] 同ERP组织内同Invoice重复成功单据数为0。 +- [ ] ERP业务失败时验证为完全原子回滚,无残留单据。 +- [ ] `result_unknown`自动重试为0。 +- [ ] 成功和重复成功均展示可追溯ERP调拨单号。 +- [ ] 页面关闭、刷新和SSE断开不终止后台Run。 +- [ ] 重复点击执行不创建重复Run或Attempt。 +- [ ] ERP写并发默认1;同Invoice并发执行数为1。 +- [ ] 审计完整记录确认范围、确认人、写前复检和ERP脱敏结果。 + +### 6.7 业务试点出口 + +Phase 2完成后可以在ERP测试组织进行端到端试点。若申请小范围生产试点,必须额外满足:ERP管理员批准、固定用户白名单、每日人工对账、回退到人工流程的SOP,以及所有P0/P1缺陷为0。 + +--- + +## 7. Phase 3:自动排程、历史恢复、异常与配置治理 + +### 7.1 阶段目标 + +- 每日自动获取收料文件并自动处理可调拨Invoice。 +- 自动发现此前失败但条件已恢复的Invoice,创建新Attempt,防止人工遗忘。 +- 对不可自动决策项提供清晰证据、人工操作和老化升级。 +- 完成来源、策略、映射、排程和通知的管理员配置发布闭环。 + +### 7.2 自动运行规则 + +- 默认08:00执行收料文件获取,09:00执行自动调拨。 +- 自动调拨始终调用统一文件准备服务,不假设08:00一定成功。 +- 单个自动调拨排程可来源级多线程处理DBS和Crane;ERP写并发仍默认1。 +- 当前来源失败不阻断其他来源。 +- 每个非空自动Run只发送一条企业微信汇总通知和一份异常Excel。 +- 空数据为`success + no_data`,不通知。 +- 通知失败记录`notification_failed`,不改变ERP业务结果且不自动重试。 + +### 7.3 历史失败恢复矩阵 + +| 当前状态 | 下个业务日动作 | 是否新建Attempt | 是否允许自动ERP写入 | +| --- | --- | ---: | ---: | +| 数量不一致 | 用最新文件和ERP库存重新预检 | 是 | 新预检通过后允许 | +| ERP无库存 | 重新查询库存 | 是 | 精确匹配后允许 | +| 明确技术失败 | 重新预检 | 是 | 全部门禁通过后允许 | +| `precheck_expired` | 重新建立预检快照 | 是 | 新确认/自动策略有效时允许 | +| `result_unknown` | 保留人工核实待办 | 否 | 禁止 | +| `manually_closed` | 永久排除 | 否 | 禁止 | +| `success`/`duplicate_success` | 仅用于幂等排除和审计 | 否 | 禁止重复写入 | + +### 7.4 后端工作包 + +| 类型 | 文件路径 | 修改内容 | +| --- | --- | --- | +| 复用修改 | `backend/app/services/schedule/job_registry.py` | 注册收料文件和自动调拨任务类型 | +| 复用修改 | `backend/app/services/schedule/job_params.py` | 来源、所有者、通知人、并发、恢复参数 | +| 复用修改 | `backend/app/services/schedule/schedule_contract.py` | 调拨排程稳定契约 | +| 复用修改 | `backend/app/services/schedule/scheduler_service.py` | 调拨Run收尾、通知状态和运行摘要 | +| 计划新增 | `backend/app/services/schedule/in_transit_receipt_file_job.py` | 08:00文件准备任务 | +| 计划新增 | `backend/app/services/schedule/in_transit_transfer_job.py` | 09:00自动调拨任务 | +| 计划新增 | `backend/app/services/in_transit_transfer/backlog_service.py` | 待处理池、3/5/7天老化和责任人 | +| 计划新增 | `backend/app/services/in_transit_transfer/recovery_service.py` | 最新快照重新预检和新Attempt | +| 计划新增 | `backend/app/services/in_transit_transfer/retry_service.py` | 合法状态人工重试 | +| 计划新增 | `backend/app/services/in_transit_transfer/manual_close_service.py` | 原因必填、永久关闭和审计 | +| 计划新增 | `backend/app/services/in_transit_transfer/excel_export.py` | 七Sheet异常Excel、Hash和原始行追溯 | +| 计划新增 | `backend/app/services/in_transit_transfer/notification.py` | 企业微信汇总、人员去重和独立失败状态 | + +### 7.5 前端与后台工作包 + +| 类型 | 文件路径 | 修改内容 | +| --- | --- | --- | +| 复用修改 | `frontend/src/features/chat/components/ChatWelcomePanel.vue` | 展示历史待办和老化摘要 | +| 计划新增 | `frontend/src/features/chat/components/messages/TransferBacklogSummaryCard.vue` | 待处理、恢复、未知和老化分层 | +| 计划新增 | `frontend/src/features/chat/components/messages/TransferExceptionCard.vue` | 异常证据和下一步操作 | +| 计划新增 | `frontend/src/features/chat/components/TransferManualCloseDialog.vue` | 必填原因和影响范围确认 | +| 计划新增 | `frontend/src/features/chat/components/TransferAuditDrawer.vue` | 业务审计时间线 | +| 复用修改 | `frontend/src/features/admin/modules/shipping-inventory/ShippingInventoryPage.vue` | 收料来源实例与发布状态 | +| 复用修改 | `frontend/src/features/admin/modules/schedules/SchedulesPage.vue` | 配置08:00/09:00任务和所有者/通知人 | +| 计划新增 | `frontend/src/features/admin/modules/in-transit-transfer/` | 策略、映射、通知、校验、发布和配置审计;实施前复核现有admin模块拆分方式 | + +### 7.6 七Sheet异常Excel + +至少包含: + +1. `Run_Summary`:Run范围、来源、日期、计数、总数量和通知状态。 +2. `Blocked_Items`:数量不一致、ERP无库存、文件冲突和原因。 +3. `Failed_Items`:明确业务失败和技术失败。 +4. `Result_Unknown`:结果未知、Operation ID和人工核实提示。 +5. `Backlog_Aging`:待处理年龄、3/5/7天等级和责任人。 +6. `Source_Status`:DBS/Crane文件、checksum、准备结果和错误。 +7. `Raw_Line_Trace`:Invoice对应Sheet、行号、原始数量和文件版本。 + +### 7.7 阶段验收 + +- [ ] 08:00任务和09:00任务可分别配置、启停、立即运行和查看历史。 +- [ ] 自动调拨缺失Ready文件时能实时准备,不依赖上一个排程成功。 +- [ ] 历史可恢复异常在下一排程重新预检率100%。 +- [ ] 每次恢复创建新Attempt,旧Attempt不变。 +- [ ] `result_unknown`和`manually_closed`自动ERP写入均为0。 +- [ ] 3/5/7天老化等级和通知对象准确率100%。 +- [ ] 每个非空自动Run企业微信汇总通知恰好1条。 +- [ ] 空数据Run通知0条。 +- [ ] 七Sheet名称、字段、行数和Hash验证全部通过。 +- [ ] 通知失败不改变ERP业务状态。 +- [ ] 配置草稿、校验、Diff、发布和回滚均有完整审计。 +- [ ] 页面、API、日志和DOM中的Secret明文数量为0。 + +--- + +## 8. Phase 4:生产硬化、UAT与上线 + +### 8.1 阶段目标 + +- 证明系统在并发、超时、Worker崩溃、SSE断开和外部系统故障下仍满足核心不变量。 +- 建立生产监控、归档、运营指标、上线和回退机制。 +- 通过真实ERP测试组织的端到端验收。 + +### 8.2 工作包 + +| 工作流 | 计划文件或交付物 | 内容 | +| --- | --- | --- | +| 故障恢复 | `backend/app/services/in_transit_transfer/recovery.py` | 陈旧Job、租约、Worker崩溃和重复消费恢复 | +| 证据归档 | `backend/app/services/in_transit_transfer/archive.py` | 大型文件和快照归档MinIO,索引和Hash留库 | +| 运营指标 | `backend/app/services/in_transit_transfer/metrics.py` | 自动完成率、耗时、失败类型、积压和节省工时基础数据 | +| 性能测试 | `backend/tests/performance/test_in_transit_transfer.py` | 并发、批量Invoice、队列积压和投影读取 | +| 前端E2E | 按项目现有E2E目录最终定位 | 人工执行、自动排程、刷新恢复、异常和权限路径 | +| 测试矩阵 | `docs/test_plan_matrix.md` | 增加调拨L0-L6与环境门禁 | +| 运维手册 | `docs/features/in-transit-transfer/technical.md` | 部署、环境变量、告警、SOP、归档和回退 | +| 项目文档 | `docs/demand.md`、`docs/tec.md`、`docs/funclist.md` | 同步正式范围、架构与实现状态 | + +### 8.3 安全与合规验收 + +- Agent权限是所有业务API的最低门槛。 +- 配置写入和发布仅管理员可操作。 +- 服务端忽略前端传入的组织、仓库和数量覆盖值,并从已发布策略重建命令。 +- ERP、RPA、Callback和企业微信Secret仅由环境变量或Secret注入。 +- ERP请求/响应按正式脱敏白名单保存。 +- 查看Run、下载Excel、查看审计和查看ERP结果均产生读审计。 +- 业务用户不能删除Run、Invoice、Attempt和Audit。 + +### 8.4 可靠性与性能目标 + +| 指标 | 上线门槛 | +| --- | ---: | +| 缺文件时首次进度反馈 | ≤5秒 | +| Ready文件预检创建P95 | ≤800毫秒 | +| Run投影读取P95 | ≤500毫秒 | +| 当天收料ERP查询/写入 | 0 | +| 未确认/过期/变化ERP写入 | 0 | +| 同来源重复RPA触发 | 0 | +| 同ERP组织重复建单 | 0 | +| `result_unknown`自动重试 | 0 | +| 审计覆盖率 | 100% | +| 审计Hash一致率 | 100% | +| 四语言完整率 | 100% | + +### 8.5 UAT场景 + +- DBS Ready复用和实时RPA获取。 +- Crane Callback正常、延迟、重复和来源不匹配。 +- 当天收料不进入ERP。 +- Invoice多行汇总后数量精确匹配。 +- 用户取消部分可执行项并确认执行。 +- 成功、重复成功、业务失败、技术失败和结果未知。 +- 页面关闭后Run继续,重新登录恢复。 +- 自动排程处理新增项和历史可恢复项。 +- `result_unknown`人工核实、人工关闭和审计。 +- 非空Run一条通知和七Sheet Excel;空数据不通知。 +- ERP测试组织创建、审核、过账并作废真实测试单。 + +### 8.6 上线策略 + +建议采用: + +1. ERP测试组织全量UAT。 +2. 生产只读观察模式:运行文件准备和预检,但ERP写调用为0。 +3. 固定授权用户的小范围对话写入试点,ERP写并发1,每日人工对账。 +4. 开启正式对话写入。 +5. 开启单一来源自动排程。 +6. 观察稳定后开启全部来源自动排程。 + +每一步均需保存启用人、时间、配置版本、门禁结果和回退条件。 + +### 8.7 回退策略 + +- 停用自动调拨排程,不删除历史Run。 +- 保留对话只读查询和预检能力。 +- 未开始项停止领取;已成功ERP单据不自动撤销。 +- `result_unknown`继续进入人工核实池。 +- 回退配置生成新发布版本和完整Diff,不直接修改数据库真相。 +- 仓储按人工SOP继续处理新增Invoice,系统保留证据和审计。 + +### 8.8 阶段验收 + +- [ ] L0-L6全部必选测试通过,保存Red→Green证据。 +- [ ] Worker重启和重复消费不重复创建成功Invoice。 +- [ ] P0、P1缺陷数量为0。 +- [ ] 越权写请求100%返回403。 +- [ ] 归档对象Hash复算通过率100%。 +- [ ] 前端`npm run test:unit`和`npm run build`通过。 +- [ ] 后端专项pytest、迁移测试、API契约和故障注入通过。 +- [ ] ERP沙箱真实单据UAT通过。 +- [ ] 仓储、ERP、测试、安全和产品完成上线签字。 + +--- + +## 9. Phase 5:稳定运营与企业集成平台演进 + +### 9.1 启动条件 + +只有同时满足以下条件才启动平台抽离: + +- 一期生产稳定运行至少一个完整观察周期。 +- ERP结果分类、错误码和人工SOP趋于稳定。 +- 至少出现第二个真实业务Operation或第二个ERP接入需求。 +- 抽离不会阻塞调拨缺陷修复和运营优化。 + +### 9.2 近期运营优化 + +- 自动调拨完成率、人工介入率、失败原因分布、历史积压和各阶段耗时看板。 +- 补齐人工处理基线,计算节省工时和异常处理周期改善。 +- 对3/5/7天阈值、排程时间和通知对象进行数据驱动调整。 +- 在审计和门禁不降低的前提下,评估ERP查询并发提升。 +- 根据真实使用评估“对话免确认直接执行”策略;默认继续关闭。 + +### 9.3 薄集成内核目标架构 + +```text +业务域:在途仓调拨 + ├─ 业务状态机、数量门禁、确认、恢复策略 + └─ 标准Operation请求 + ↓ +薄集成内核 + ├─ Operation Catalog + ├─ Connector / Endpoint / Credential Reference + ├─ Request/Response Mapping + ├─ Timeout / Idempotency / Result Classification + ├─ 发布、版本、审计、指标和测试沙箱 + └─ Worker执行协议 + ↓ +ERP SOAP / HTTP / 未来其他系统 +``` + +业务域继续拥有“是否应该调拨”的判断;集成内核只负责“如何可靠调用已批准的Operation”。Dify在任何阶段都不得拥有ERP写权限。 + +### 9.4 平台演进切片 + +| 切片 | 能力 | 验收 | +| --- | --- | --- | +| P5-A Operation元数据 | 配置接口、协议、超时、输入输出Schema、结果分类 | 调拨Operation由元数据描述,行为不变 | +| P5-B 连接与凭据引用 | Endpoint按环境管理,Secret只存引用 | 页面/API/日志无Secret明文 | +| P5-C 映射和发布治理 | 草稿、验证、Diff、发布、回滚 | 未发布配置不能被Worker使用 | +| P5-D 通用执行器 | 标准命令、幂等、审计、指标和错误投影 | 新Operation无需修改调拨编排核心 | +| P5-E 第二业务验证 | 接入一个非调拨Operation | 证明不是为单一业务过度抽象 | + +### 9.5 平台阶段不做 + +- 不为了“通用”而把调拨业务状态机搬入平台。 +- 不在只有一个Operation时引入复杂DSL或工作流引擎。 +- 不迁移现有集成,除非有独立业务价值和专项计划。 +- 不允许前端或Dify拼接任意ERP请求。 + +--- + +## 10. 横向工作流路线图 + +### 10.1 产品与UX + +| 阶段 | 主要成果 | +| --- | --- | +| Phase 0 | 术语、状态、权限、错误语义和Mock DTO冻结 | +| Phase 1 | 文件进度、只读预检、空/加载/异常状态 | +| Phase 2 | Invoice选择、确认有效期、执行进度和结果分层 | +| Phase 3 | 待办、老化、人工重试/关闭、后台配置发布 | +| Phase 4 | 可访问性、移动端、UAT、运营指标埋点定义 | +| Phase 5 | 平台配置工作台与Operation治理体验 | + +### 10.2 后端与数据 + +| 阶段 | 主要成果 | +| --- | --- | +| Phase 0 | 模型、迁移、状态机、DTO、审计、Fake外部系统 | +| Phase 1 | 文件准备、解析、汇总、ERP查询、预检投影 | +| Phase 2 | 确认、写前复检、ERP写入、并发和取消 | +| Phase 3 | 排程、恢复、通知、Excel、策略发布 | +| Phase 4 | 恢复、归档、指标、安全和性能 | +| Phase 5 | Adapter抽离、Operation Catalog和通用执行协议 | + +### 10.3 测试与质量 + +| 阶段 | 主要成果 | +| --- | --- | +| Phase 0 | L0测试、Fixture、Fake Clock/ERP/RPA/WeCom、契约基线 | +| Phase 1 | 文件、D+1、汇总、ERP只读、Chat组件和API契约 | +| Phase 2 | 确认Hash、原子性、幂等、并发、崩溃和结果未知 | +| Phase 3 | 排程、恢复、老化、通知、Excel和配置发布 | +| Phase 4 | E2E、性能、安全、故障注入和ERP沙箱 | +| Phase 5 | 平台兼容契约和第二Operation验证 | + +### 10.4 运维与安全 + +| 阶段 | 主要成果 | +| --- | --- | +| Phase 0 | 环境变量清单、白名单、Secret引用和脱敏策略 | +| Phase 1 | 文件/RPA/Callback状态监控 | +| Phase 2 | Transfer Worker、队列、ERP调用和结果未知告警 | +| Phase 3 | 排程、待办老化、通知失败和附件容量监控 | +| Phase 4 | SLO、归档、容量、备份、上线和回退演练 | +| Phase 5 | 集成平台多环境发布、连接器健康和Operation SLO | + +--- + +## 11. 依赖、责任与决策时点 + +### 11.1 RACI建议 + +| 工作项 | 负责R | 批准A | 协作C | 知会I | +| --- | --- | --- | --- | --- | +| 业务规则和UAT | 产品/仓储业务 | 仓储负责人 | ERP、测试 | 开发、运维 | +| ERP契约和沙箱 | ERP团队 | ERP负责人 | 后端、测试、运维 | 产品、仓储 | +| 对话和后台前端 | 前端 | 技术负责人 | 产品、后端、测试 | 仓储 | +| 领域服务和Worker | 后端 | 技术负责人 | ERP、前端、测试 | 产品、运维 | +| TDD与质量门禁 | 测试/开发共同负责 | 测试负责人 | 产品、ERP | 仓储、运维 | +| Secret、部署和监控 | 运维/ERP管理员 | 安全或运维负责人 | 后端、ERP | 产品、测试 | +| 上线批准 | 产品/仓储/ERP/测试 | 项目负责人 | 安全、运维、开发 | 使用者 | + +具体人员姓名和日历Deadline需在项目启动会上补齐,本路线图不虚构人员承诺。 + +### 11.2 必须关闭的问题 + +| 编号 | 问题 | 最迟关闭阶段 | 未关闭影响 | +| --- | --- | --- | --- | +| Q1 | ERP正式WSDL、字段、错误码、超时和可留存脱敏字段是什么? | Phase 0退出前 | 禁止进入真实ERP写入开发 | +| Q2 | ERP写超时后的人工核实SOP、责任人和完成时限是什么? | Phase 0退出前 | `result_unknown`无法安全运营 | +| Q3 | DBS/Crane正式收料样例、Sheet、表头和结构漂移规则是否齐全? | Phase 1开始前 | 文件解析和汇总验收不可执行 | +| Q4 | 企业微信附件上限是否满足最大七Sheet Excel? | Phase 3开始前 | 需要切换为受控下载链接方案 | +| Q5 | 自动调拨完成率正式目标和人工处理基线是多少? | Phase 4上线前 | 无法证明业务收益 | +| Q6 | 所有Agent授权用户查看同权限Run的范围是否通过安全评审? | Phase 2上线前 | 可能产生跨用户数据暴露 | +| Q7 | 生产Worker容量、ERP允许QPS和查询/写入并发上限是多少? | Phase 4压测前 | 无法冻结容量和SLO | + +### 11.3 核心关键问题 + +**当ERP写请求超时且ERP没有外部请求号反查能力时,仓储和ERP团队如何在禁止自动重试的前提下,及时且确定地判定该Invoice是否已经成功审核过账?** + +这是一期最关键的运营问题。Invoice幂等能降低重复建单风险,但不能代替明确、可执行、有限时的人工核实流程。若该问题没有责任人、查询方法和处理时限,系统即使技术上线,也无法稳定处理`result_unknown`积压。 + +--- + +## 12. 风险登记册 + +| ID | 风险 | 类型 | 概率 | 影响 | 预警信号 | 缓解措施 | 负责人角色 | +| --- | --- | --- | --- | --- | --- | --- | --- | +| R1 | 预检后关键数据变化 | 业务/技术 | 中 | 极高 | `precheck_expired`增长 | checksum、Hash、10分钟、写前复检 | 后端/产品 | +| R2 | ERP超时产生结果未知 | 技术/运营 | 中 | 极高 | 超时率上升、未知项积压 | 禁止自动重试、人工SOP、老化告警 | ERP/仓储 | +| R3 | ERP重复语义与实际不一致 | 业务 | 低至中 | 极高 | 返回原单但状态不明确 | 沙箱验证、只有确认已过账才投影成功 | ERP/测试 | +| R4 | 文件结构漂移 | 技术/业务 | 中 | 高 | 必填列或类型异常 | Profile版本、Schema门禁、整源阻断 | 仓储/后端 | +| R5 | RPA/Callback长时间无结果 | 技术 | 中 | 高 | Source Job超时、12小时无Worker | 租约、来源隔离、进度和告警 | 运维/后端 | +| R6 | 历史恢复误执行 | 业务 | 低 | 极高 | 恢复项异常成功 | 最新文件/ERP/映射全门禁、新Attempt | 后端/测试 | +| R7 | Agent权限范围过宽 | 安全 | 中 | 高 | 越权查看投诉 | 服务端RBAC、范围审计、安全评审 | 安全/后端 | +| R8 | 通知附件过大 | 资源/体验 | 中 | 中 | 发送失败 | 压测上限、精简Excel、受控下载链接 | 运维/产品 | +| R9 | Chat核心组件并行冲突 | 进度/技术 | 高 | 中 | 合并冲突、回归失败 | 小组件扩展、稳定DTO、分支协调 | 前端负责人 | +| R10 | 审计数据快速膨胀 | 资源 | 中 | 中至高 | 表增长和查询变慢 | 摘要Hash、索引、MinIO归档 | 后端/运维 | +| R11 | 一期范围膨胀为集成中心 | 进度 | 中 | 高 | 通用化需求阻塞业务 | Adapter边界先隔离,平台放Phase 5 | 产品/架构 | +| R12 | 缺少人工基线 | 价值 | 高 | 中 | 上线后无法量化收益 | 上线前采样工时、数量和异常周期 | 产品/仓储 | + +任何R1、R2、R3、R6、R7对应的控制项未通过,均视为P0/P1发布阻断。 + +--- + +## 13. 指标与运营看板路线图 + +### 13.1 一期上线硬指标 + +- ERP错误写入数:0。 +- 同ERP组织重复建单数:0。 +- 当天收料ERP查询/写入数:0。 +- 未确认、过期或变化预检ERP写入数:0。 +- `result_unknown`自动重试数:0。 +- 历史可恢复失败下一排程重新预检率:100%。 +- 审计覆盖率与Hash一致率:100%。 + +### 13.2 业务效果指标 + +- 安全自动调拨完成率。 +- 可执行Invoice自动完成率。 +- 人工介入率。 +- 单Invoice端到端处理时长。 +- 历史异常平均关闭周期。 +- 3/5/7天积压数量。 +- 每月节省工时。 + +🔶 **假设:** 稳定运行30天后的安全自动调拨完成率目标暂按不低于95%管理,正式目标需结合ERP可用性和人工基线确认。 + +### 13.3 技术与体验指标 + +- 文件准备、解析、ERP查询、匹配、写入和通知各阶段P50/P95耗时。 +- DBS/Crane来源成功率和超时率。 +- ERP业务失败、技术失败、重复成功和结果未知占比。 +- Chat首次进度反馈和Run恢复成功率。 +- 企业微信通知和附件发送成功率。 +- Worker队列深度、租约回收数和陈旧Job数量。 + +--- + +## 14. 发布门禁与完成定义 + +### 14.1 每阶段Definition of Done + +每个阶段同时满足以下条件才算完成: + +1. 对应测试先出现可解释的Red,再由最小实现转Green并完成Refactor。 +2. 业务行为、API DTO、错误码和状态机文档同步。 +3. 新增文案四语言齐全。 +4. 所有新增操作节点有审计测试。 +5. 所有外部副作用有幂等、超时、失败分类和敏感字段测试。 +6. 数据库结构变更包含Alembic迁移和升降级验证。 +7. 前端组件测试、后端专项测试和最快相关构建通过。 +8. 阶段验收报告记录通过项、未通过项、风险和下一阶段入口。 + +### 14.2 一期生产Definition of Done + +- Phase 0至Phase 4全部退出门禁通过。 +- 所有核心页面符合现有HXOPS Chat/Admin风格并通过线框/原型验收。 +- 所有写操作和关键读取操作可审计,快照Hash可复算。 +- 对话和自动排程均完成ERP沙箱端到端验收。 +- P0/P1缺陷为0,P2有明确Owner和期限。 +- 已建立`result_unknown`、RPA失败、通知失败和自动排程停用SOP。 +- 已完成受控上线和回退演练。 +- 仓储、ERP、产品、测试、安全和运维共同签字。 + +--- + +## 15. 里程碑评审材料清单 + +| 里程碑 | 必备评审材料 | +| --- | --- | +| M0 | ERP契约、文件样例、状态机、DTO、审计矩阵、Fake行为、Red/Green测试日志 | +| M1 | Chat文件进度与预检演示、解析报告、D+1/汇总/来源隔离测试、API契约 | +| M2 | 确认卡、ERP沙箱单据、写前复检、幂等/超时/崩溃测试、审计时间线 | +| M3 | 排程Run、历史恢复、新Attempt、3/5/7天、企微和七Sheet Excel、配置发布Diff | +| M4 | E2E、性能、安全、故障注入、迁移、归档、UAT、上线和回退报告 | +| M5 | Operation Catalog、连接器治理、迁移演练和第二业务验证报告 | + +--- + +## 16. PRD自评与下一步 + +### 16.1 最强部分 + +业务安全边界已经高度明确:日期成熟、完全相等、Invoice幂等、ERP原子写入、一次确认、写前复检、结果未知隔离、历史恢复和审计均可直接转化为测试契约。 + +### 16.2 最弱部分 + +外部ERP契约和人工运营基线仍不完整。它们分别影响技术可实现性证明和业务收益证明。 + +### 16.3 最高风险假设 + +| 假设 | 错误后的影响 | 验证方式 | +| --- | --- | --- | +| ERP重复Invoice响应始终能证明原单已审核过账 | 可能把未完成单据误判成功 | ERP沙箱重复请求和状态验证 | +| 企业微信可发送最大异常Excel | 自动Run通知附件失败 | 用边界行数生成七Sheet文件实测 | +| 所有Agent授权用户共享Run可接受 | 可能发生越权查看 | 安全评审和权限矩阵测试 | +| 95%安全自动完成率可达 | 上线目标不现实 | 采集ERP可用性和30天试运行数据 | + +### 16.4 推荐下一步 + +召开一次Phase 0启动评审,只关闭四项:ERP WSDL及错误语义、结果未知人工SOP、DBS/Crane正式样例、权限范围。评审通过后,严格从TDD文档的L0失败测试和Fake ERP开始开发,不先写完整业务实现。 + diff --git a/docs/features/shipping-notice/dify-manual-configuration.md b/docs/features/shipping-notice/dify-manual-configuration.md new file mode 100644 index 00000000..93842f9d --- /dev/null +++ b/docs/features/shipping-notice/dify-manual-configuration.md @@ -0,0 +1,28 @@ +# 货代发货通知自动推进 — Dify 手工配置说明 + +> 本说明仅供管理员在 Dify 控制台执行只读核对与手工配置。HXOPS 不调用 Dify 管理 API,也不代替管理员修改画布、变量、凭据或发布状态。 + +## 1. 事实源边界 + +- Gate、RecoveryPlan、Gate Attempt、Job、库存文件/快照/映射/匹配、Verification、Excel Artifact、UploadAttempt 均以 HXOPS 数据库和确定性服务为唯一正式事实源。 +- Dify/LLM 只能提供对话理解、只读查询或候选建议;不得直接调用写入订单、库存、Excel、RPA 或上传回执的接口。 +- `stop_agent_turn`、`needs_human`、`waiting_external` 等状态出现时,Chatflow 必须停止后续写操作调用,等待 HXOPS Projection 或人工动作。 + +## 2. 管理员核对清单 + +在每个环境的唯一启用货代 Chatflow 中逐项核对: + +1. Start 输入仅接收 HXOPS 注入的会话/任务上下文和只读状态信息,不把模型输出当作业务事实。 +2. Tool 白名单只包含已发布的 Chat/查询能力;不存在库存准备、匹配、Excel 生成、RPA 触发、上传确认等写 Tool。 +3. 画布分支遇到人工阻断、外部等待、取消或终态时停止自动循环,不重复发送恢复动作。 +4. 输出中的 Gate、库存、上传状态来自 HXOPS 查询结果,并保留 `request_id`;不依赖 Dify memory 推断当前状态。 +5. 变更后以一条真实受控测试对话核对:刷新/重登录仍从 HXOPS Projection 恢复,Dify 不产生任何正式事实写入。 + +## 3. 凭据与发布 + +- 不在本文或代码中记录 Token、URL、密钥。凭据由环境 Secret/Jenkins 注入并按平台轮换。 +- 配置变更由管理员按现有发布流程审批、记录版本和回滚点;HXOPS 侧只验收接口合同与审计结果。 + +## 4. 回滚口径 + +发现 Chatflow 调用了未授权写 Tool、自动推进已取消任务或覆盖 HXOPS 状态时,立即停用该版本/分支,恢复到上一已批准版本,并以 `request_id`、Run/Task 编号提交审计记录。不得通过 Dify 侧补写或修正业务事实。 diff --git a/docs/features/shipping-notice/dual-workbench-stage-acceptance.md b/docs/features/shipping-notice/dual-workbench-stage-acceptance.md index 88bea662..f340109d 100644 --- a/docs/features/shipping-notice/dual-workbench-stage-acceptance.md +++ b/docs/features/shipping-notice/dual-workbench-stage-acceptance.md @@ -24,7 +24,7 @@ | 验收项 | 结果 | 证据 | | --- | --- | --- | -| 自动重试最多 3 次 | 通过 | `SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES`;`test_shipping_process_gate_retry_cap` | +| Gate 失败不自动重试 | 通过 | `test_gate_failure_does_not_auto_retry`;用户显式恢复动作仍可用 | | 每次尝试可查询 | 通过 | RecoveryCard 展开 Workspace 审计;`latest_attempt.attempt_no` | | 接管后不再自动重试 | 通过 | 技术重试耗尽后转人工;恢复动作由用户触发 | | 轻量恢复可在对话完成 | 通过 | Timeline Item + DetailDrawer 内嵌 `ProcessGateRecoveryCard` | @@ -60,7 +60,7 @@ ```text SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false # 默认关闭(生产安全);具备 Worker/凭据/隔离后显式 true -SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES=3 # Process Gate 技术自动重试上限 +# Process Gate 失败不自动重试;需要时由用户显式触发恢复动作 ``` 全链路含货代上传 RPA 时,须在环境文件**显式**设 `SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=true`, diff --git a/docs/features/shipping-notice/freight-shipping-agent-frontend-prd.md b/docs/features/shipping-notice/freight-shipping-agent-frontend-prd.md new file mode 100644 index 00000000..e7125861 --- /dev/null +++ b/docs/features/shipping-notice/freight-shipping-agent-frontend-prd.md @@ -0,0 +1,1826 @@ +# 货代发货 Agent 前端产品需求文档 + +> 文档版本:V1.2 +> 文档状态:页面原型设计输入稿 +> 适用范围:首期前端产品与交互设计 +> 产品原则:以 HXOPS Agent 对话为产品主轴;固定模板确定性解析为主,AI 辅助低置信字段判断;复杂节点在对话上下文中展开工作台 +> 本文重点:功能、信息架构、页面模块、状态和交互,不限定视觉风格 + +--- + +## 1. 文档目的 + +本文用于指导货代发货 Agent 的页面信息架构、功能模块拆分和原型设计。首期覆盖从用户手动上传订单材料,到订单解析、人工复核、库存抓取与匹配、发货 Excel 生成、RPA 上传货代系统的完整前端流程;产品目标态将由系统自动接收企业邮箱中的客户邮件并创建发货任务,用户主要处理例外而非手工导出和上传邮件。 + +本文不约束具体配色、字体、插画、阴影和品牌视觉,后续由原型设计工具根据本 PRD 完成视觉方案。 + +--- + +## 2. 产品背景 + +发货业务人员收到客户邮件后,需要人工阅读邮件正文和附件,整理客户 PO、预约单号、料号、数量及库存来源,再登录对应库存系统导出库存 Excel,核对库存数量,制作发货 Excel,最后登录货代系统上传发货需求。 + +当前流程存在以下问题: + +- 邮件正文与附件信息分散,人工核对耗时。 +- 同一邮件可能包含多份附件,字段可能缺失或互相冲突。 +- 客户模板虽相对固定,但不同客户或版本仍可能产生解析异常。 +- 库存来源需要根据订单线索判断,选错库存源会导致错误匹配。 +- 库存抓取、Excel 制作和货代上传包含大量重复操作。 +- 异常发生后,用户难以快速判断问题所在和恢复方式。 +- 外部系统操作需要避免重复上传、错误重试和结果无法追溯。 + +--- + +## 3. 产品定位 + +货代发货 Agent 是 HXOPS 平台内一个以对话为主入口的业务 Agent,组合“自动邮件接入 + 固定模板自动处理 + AI 辅助识别 + 人工例外处理 + RPA 执行”。 + +首期以手动上传 EML/PDF 作为接入方式,优先验证解析、裁决、库存和货代上传闭环;自动邮件接入是明确的产品目标态,而不是可有可无的辅助功能。未来用户不再需要先从邮箱导出 EML 再上传,系统应自动接收授权邮箱或指定文件夹中的新邮件,识别需要处理的发货邮件并创建任务。 + +产品以通用 AI 工具常见的对话体验承载材料提交、进度通知、状态解释和轻量操作,但不是只有聊天消息。围绕发货任务出现订单复核、库存处理、Excel 或 RPA 等复杂节点时,用户可从对话消息卡片展开工作台;工作台展开后对话缩起但不丢失,用户可随时恢复对话或返回工作台。 + +产品核心是“一个对话上下文持续承载一组发货任务及其工作台”: + +```text +首期:用户上传 EML / PDF 等材料 +目标态:系统自动接收授权邮箱中的新邮件 + ↓ +固定模板解析邮件和附件 + ↓ +同一 EML 内字段交叉核对 + ↓ +低置信字段由 AI 基于附件提供候选和解释 + ↓ +规则校验或人工裁决 + ↓ +确定候选库存源 + ↓ +RPA 抓取对应库存 Excel + ↓ +按预约单号 + 料号 + 数量匹配库存 + ↓ +生成并校验发货 Excel + ↓ +RPA 上传货代系统 + ↓ +保存回执、结果和完整操作记录 +``` + +### 3.1 能力职责边界 + +| 能力 | 主要职责 | +| --- | --- | +| 固定模板解析 | 提取结构稳定的邮件正文、PDF 和表格字段,是首期解析主路径 | +| AI 辅助 | 对低置信字段读取当前邮件及附件证据,提供候选值、依据和差异说明 | +| 确定性规则 | 校验格式、字段完整性、跨文件一致性、库存数量、状态和流程门禁 | +| 人工复核 | 处理关键字段冲突、证据不足、多库存源、库存不足和外部结果未知 | +| RPA | 在前置条件通过后抓取库存文件、上传发货 Excel,并回传执行结果 | + +### 3.2 接入方式演进 + +```text +阶段一:手动接入 +用户从邮箱导出 EML / 获取 PDF → 上传货代发货 Agent → 创建任务 + +阶段二:辅助自动接入 +系统同步指定邮箱/文件夹 → 生成待确认邮件 → 用户确认后创建任务 + +目标态:自动接入 +系统持续接收指定邮箱/文件夹 → 判断是否为发货邮件 → 自动去重和创建任务 + ↓ + 只有异常或高风险问题通知用户 +``` + +接入方式变化不应改变后续主流程。无论任务来自手动上传还是自动邮件接入,都应进入同一套材料解析、字段裁决、库存匹配、Excel 生成、RPA 上传和审计流程。 + +### 3.3 HXOPS 对话与工作台关系 + +```text +HXOPS 平台壳 +├── 平台全局导航 / Agent 列表 / 历史对话 +└── 货代发货 Agent 对话 + ├── 用户消息:上传材料、提问、补充说明、轻量确认 + ├── Agent 消息:处理摘要、阶段通知、异常解释、结果回执 + ├── 业务节点卡片:订单复核、库存处理、Excel、RPA 上传 + └── 展开工作台 + ├── 对话缩为窄栏或折叠入口 + ├── 工作台获得主要页面空间 + └── 保持同一 conversation / task / case 上下文 +``` + +交互原则: + +- 对话是主入口、主状态通知区和任务解释区。 +- 工作台是复杂结构化操作区,不另起一个脱离对话上下文的产品门户。 +- 对话和工作台不能同时成为同一业务动作的重复写入口。 +- 工作台关闭或缩起后,用户返回原对话位置和原消息节点。 +- 从任务中心进入时,应打开任务所属对话并自动聚焦对应工作台节点。 + +--- + +## 4. 产品目标与首期非目标 + +### 4.1 产品目标 + +- 首期用户一次上传一份或多份订单材料,即可启动完整发货处理。 +- 产品目标态由系统自动接收授权邮箱中的新邮件并创建发货任务,用户无需导出 EML 后再次上传。 +- 固定模板且信息一致的订单尽可能自动处理。 +- 低置信字段先由 AI 辅助分析,减少人工查找附件和比对内容的时间。 +- 任何关键差异都必须明确中断,不允许系统静默选择。 +- 库存满足时自动生成发货 Excel,并在校验通过后上传货代系统。 +- 每个中断任务必须告诉用户发生了什么、影响什么、下一步如何处理。 +- 页面刷新、重新登录或离开页面后,任务状态仍可恢复。 +- 所有自动结果、AI 建议、人工决定和 RPA 操作均可追溯。 + +### 4.2 首期非目标 + +- 不支持用户自由编排 Agent 工作流。 +- 不以开放式 AI 聊天作为主要操作界面。 +- 不支持 AI 自主修改库存、数量或货代系统业务事实。 +- 不支持 AI 无证据生成订单字段。 +- 不支持跨不同 EML 自动互相补字段或交叉裁决。 +- 不支持库存不足时自动拆单或部分发货。 +- 不支持货代上传结果未知时自动重复上传。 +- 不支持 AI 自动发布新模板、新映射或新库存源规则。 +- 不要求首期在移动端完成复杂订单表格和 PDF 证据编辑。 +- 首期不实现生产邮箱自动收取、发货意图自动判定和无人确认自动建任务,但页面和业务对象必须为后续接入方式预留扩展位置。 + +--- + +## 5. 目标用户与权限 + +| 角色 | 主要诉求 | 首期主要操作 | +| --- | --- | --- | +| 发货业务人员 | 快速提交订单并完成日常发货;目标态只处理系统自动收件后的例外 | 首期上传材料、查看任务、处理本人例外、下载 Excel、查看上传结果 | +| 订单复核人员 | 快速解决解析冲突和字段缺失 | 查看原始证据、选择候选值、修改字段、确认继续、重新解析 | +| 库存协调人员 | 处理库存源和库存不足 | 确认库存源、查看库存快照、重新抓取、处理库存不足 | +| RPA 运维人员 | 诊断库存抓取或货代上传异常 | 查看执行记录、重试明确失败的执行、处理结果未知 | +| 管理员 | 维护配置并审计系统行为 | 管理库存源、解析模板、Excel 模板、RPA 配置和审计记录 | +| 业务主管 | 查看积压与处理质量 | 查看任务统计、异常分布和完成结果,默认不修改业务数据 | + +### 5.1 权限原则 + +- 普通用户默认只可处理本人创建或被明确分配的任务。 +- 管理员可以诊断和查看,但业务写操作应按权限单独控制。 +- 查看敏感邮件正文、附件内容和库存数据需要对应权限。 +- 所有人工修改必须记录操作人、时间、原因、修改前值和修改后值。 +- 页面不能仅通过隐藏按钮实现权限控制,所有写操作均需后端复核权限。 + +--- + +## 6. 核心业务对象 + +原型页面中应统一使用以下用户可理解的业务对象: + +| 对象 | 用户理解 | 主要展示字段 | +| --- | --- | --- | +| 发货提交 | 一次进入处理流程的全部材料;可由人工提交或自动邮件接入产生 | 接入方式、提交/接收时间、文件数、创建主体、处理状态 | +| 邮件材料 | 一份手动上传或系统自动接收的邮件及其正文和附件 | 邮件唯一标识、邮箱、文件夹、发件人、收件人、主题、接收时间、附件目录 | +| 订单材料 | 直接上传的 PDF 或 EML 中的业务附件 | 文件名、类型、所属邮件、解析状态 | +| 发货任务 | 一组需要共同完成库存匹配和货代上传的订单数据 | 任务编号、客户、PO、预约单号、当前阶段 | +| 订单行 | 参与库存匹配和 Excel 生成的明细 | 料号、数量、单位、预约单号、库存源 | +| 人工待办 | 阻断自动推进且需要用户决定的问题 | 原因、影响范围、建议动作、处理人 | +| 库存快照 | RPA 从指定库存源抓取并归档的库存文件事实 | 库存源、文件时间、有效期、抓取状态 | +| 发货 Excel | 根据已确认订单和库存结果生成的发货文件 | 文件名、版本、生成时间、校验状态 | +| 上传记录 | RPA 向货代系统执行上传的尝试 | 开始时间、结果、货代参考号、回执状态 | + +--- + +## 7. 首期完整业务流程 + +首期主流程从“用户上传材料”开始。后续启用自动邮件接入时,只替换流程入口,固定模板解析及其后的业务处理保持一致。 + +### 7.1 主流程 + +```text +[1 上传材料] + ↓ +[2 上传快览] + - 读取 EML 邮件头、正文和附件目录 + - 检查文件类型、大小和完整性 + ↓ +[3 固定模板解析] + - 识别客户 PO、预约单号、料号、数量、库存源线索 + - 保留字段来源和原文证据 + ↓ +[4 同一 EML 内交叉核对] + - 比较正文和附件 + - 比较同一邮件内多份业务附件 + ↓ + ├─ 字段可信且一致 ───────────────┐ + │ │ + └─ 低置信字段 → AI 辅助分析 │ + ↓ │ + 仍不能可靠判断? │ + ├─ 是 → 人工复核 │ + └─ 否 → 规则复核 ┘ + ↓ +[5 确定库存源] + - 规则根据库存源线索产生候选 + - 无候选或多候选进入人工处理 + ↓ +[6 准备库存] + - RPA 抓取对应库存 Excel + - 保存库存快照和抓取时间 + ↓ +[7 库存匹配] + - 预约单号 + 料号精确匹配 + - 校验可用数量 >= 需求数量 + ↓ + ├─ 库存不足/匹配异常 → 人工处理 + └─ 全部满足 + ↓ +[8 生成发货 Excel] + - 使用已发布模板 + - 生成后复读校验关键字段和行数 + ↓ +[9 RPA 上传货代系统] + - 前置门禁全部通过后执行 + - 保存成功回执、明确失败或结果未知 + ↓ +[10 完成或等待人工处理] +``` + +### 7.2 多文件边界 + +- 用户可以一次选择多份 EML、PDF 或混合文件。 +- 用户可以分多次选择文件,点击“开始处理”时作为一次业务提交。 +- 一份 EML 及其附件构成一个交叉核对范围。 +- 不同 EML 之间默认独立解析,不互相补字段。 +- 直接上传的 PDF 独立解析,不与其他直接 PDF 自动合并。 +- 单个文件失败不能清除同次提交中其他文件的成功结果。 +- 失败文件应允许从失败节点重试,不要求重新上传全部文件。 + +--- + +## 8. 首期 AI 能力范围 + +### 8.1 AI 首期只解决一个核心问题 + +当固定模板已经定位到字段区域,但出现以下情况时,AI读取当前 EML 正文和附件中的受控证据,辅助判断字段候选: + +- 字段解析置信度不足。 +- 同一 EML 内出现两个不同候选值。 +- 字段表达存在轻微语义差异,规则无法直接判断。 +- 邮件正文可能对附件字段进行了补充或修订。 + +首期优先覆盖字段: + +- 客户 PO。 +- 预约单号。 +- 料号。 +- 数量及单位。 +- 库存源线索。 + +### 8.2 AI 输出内容 + +AI 每次只分析一个明确的问题,并返回: + +- 推荐候选值;无法判断时明确返回“无法判断”。 +- 使用的来源文件。 +- 页码、表格、单元格或邮件正文片段。 +- 简短的推荐依据。 +- 其他候选值及差异。 +- 风险提示。 + +### 8.3 AI 输出后的处理 + +| 场景 | 处理方式 | +| --- | --- | +| AI 推荐值与固定模板结果一致,且规则校验通过 | 可以提升字段可信度并继续 | +| AI 推荐值有证据,但属于关键冲突 | 进入人工复核,默认选中建议但不自动确认 | +| AI 无法判断或没有可验证证据 | 进入人工复核,不预填最终值 | +| AI 服务不可用 | 固定模板主链不受影响;低置信问题直接进入人工复核 | + +### 8.4 首期暂不实现的 AI 能力 + +- 不使用 AI 直接解析所有固定模板字段。 +- 不使用 AI 决定库存是否充足。 +- 不使用语义相似度直接完成正式料号匹配。 +- 不使用 AI 自主选择并操作未知库存源。 +- 不使用 AI 自动生成或修改发货 Excel。 +- 不使用 AI 自由操作库存网站或货代网站。 +- 不建设开放式订单聊天 Copilot。 +- 不建设模型质量中心、新模板聚类和自动规则学习。 + +--- + +## 9. 信息架构与全局导航 + +### 9.0 HXOPS 平台主轴 + +本产品不新建一套独立的“货代发货门户”壳,而是挂载在当前 HXOPS 平台的 Agent/对话体系中。平台级能力负责用户、权限、Agent 选择、历史会话和消息承载;货代发货 Agent 负责本业务的材料、任务和工作台节点。 + +```text +HXOPS 工作台 +├── 平台导航、Agent 列表、历史会话 +├── 货代发货 Agent 对话区 +│ ├── 消息流 +│ ├── 文件附件区 +│ ├── 处理进度消息卡 +│ └── 节点工作台展开入口 +└── 当前业务工作台 + ├── 默认收起 + ├── 节点展开时占据主要工作区域 + └── 可关闭并回到对话 +``` + +### 9.0.1 三种主要布局状态 + +| 布局状态 | 对话区 | 工作台 | 适用场景 | +| --- | --- | --- | --- | +| 对话主视图 | 完整宽度 | 收起 | 上传材料、询问状态、查看自动处理消息 | +| 对话 + 工作台 | 保留可读窄栏 | 展开侧栏或主区域 | 查看订单摘要、库存结果、轻量确认 | +| 工作台主视图 | 缩为窄栏或可展开抽屉 | 占据主要区域 | 订单逐字段复核、证据查看、库存明细处理 | + +工作台展开不代表离开会话,必须保留当前对话、任务、Case、材料/订单行/字段焦点、未保存修改和返回对话时的消息位置。 + +### 9.1 业务端导航 + +```text +HXOPS 平台 +└── 货代发货 Agent 对话 + ├── 发货接入:首期上传材料,目标态自动收件箱 + ├── 对话消息与本次处理卡片 + ├── 展开订单复核工作台 + ├── 展开库存处理工作台 + ├── 展开发货 Excel 工作台 + └── 展开货代上传执行详情 + +跨会话聚合 +└── 我的任务 +│ ├── 待我处理 +│ ├── 自动处理中 +│ ├── 已完成 +│ └── 全部任务 +└── 任务详情工作台深链 +``` + +### 9.2 管理端导航 + +```text +货代发货配置 +├── 库存源管理 +├── 订单解析模板 +├── 发货 Excel 模板 +├── RPA 运行记录 +└── 审计中心 +``` + +### 9.3 页面入口原则 + +- HXOPS Agent 对话是日常主入口;用户不需要先进入独立任务中心才能提交材料或查看状态。 +- 对话消息卡片是业务节点的主要入口;复杂节点点击后展开对应工作台。 +- “我的任务”用于跨会话聚合待办和历史;点击任务后回到所属对话并聚焦节点。 +- 工作台内完成复杂结构化操作,完成后将结果写回对话消息流。 +- 目标态“自动收件箱”作为对话侧的接入管理页签或工作台,不切断 Agent 对话。 +- 管理端只维护配置和诊断,不承载日常订单处理。 + +--- + +## 10. 页面清单 + +| 编号 | 页面 | 主要用户 | 首期优先级 | +| --- | --- | --- | --- | +| P01 | HXOPS 货代发货 Agent 对话页 | 发货业务人员 | P0 | +| P02 | 我的发货任务页 | 所有业务角色 | P0 | +| P03 | 对话内任务详情工作台 | 所有业务角色 | P0,展开节点 | +| P04 | 对话内订单复核工作台 | 订单复核人员 | P0,展开节点 | +| P05 | 对话内库存处理工作台 | 发货业务/库存协调人员 | P0,展开节点 | +| P06 | RPA 执行详情 | RPA 运维/管理员 | P1,可用抽屉 | +| P07 | 库存源管理页 | 管理员 | P1 | +| P08 | 订单解析模板页 | 管理员 | P1,优先复用现有能力 | +| P09 | 发货 Excel 模板页 | 管理员 | P1,优先复用现有能力 | +| P10 | 审计中心 | 管理员/主管 | P1 | +| P11 | 对话内自动收件箱 | 发货业务/管理员 | 后续核心方向 | + +--- + +## 11. P01 HXOPS 货代发货 Agent 对话页 + +### 11.1 页面目标 + +首期让用户在 HXOPS 对话中完成多文件选择、上传快览和一次性提交,并通过消息流查看本次处理进度。复杂节点通过消息卡片展开工作台。页面结构需允许未来在同一 Agent 对话中增加自动收件箱入口,而不重做任务详情和后续流程。 + +### 11.2 页面结构 + +```text +┌──────────────────────────────────────────────────────────┐ +│ HXOPS / 货代发货 Agent [新对话] [我的任务] [工作台] │ +├──────────────────────────────────────────────────────────┤ +│ 对话消息流 │ +│ Agent:请上传客户邮件或订单 PDF │ +│ 用户: │ +│ ┌─ 文件附件区 ────────────────────────────────────────┐ │ +│ │ EML / PDF 列表、上传状态、附件目录 │ │ +│ │ [继续添加] [开始处理] │ │ +│ └──────────────────────────────────────────────────────┘ │ +│ Agent:已开始处理,本次任务将在后台继续 │ +│ ┌─ 处理进度消息卡 ─────────────────────────────────────┐ │ +│ │ 当前阶段 / 当前待办 / [展开工作台] │ │ +│ └──────────────────────────────────────────────────────┘ │ +├──────────────────────────────────────────────────────────┤ +│ 对话输入区:补充说明、询问状态、上传材料 │ +└──────────────────────────────────────────────────────────┘ +``` + +### 11.3 功能模块 + +#### A. 页面说明 + +- 页面标题:货代发货 Agent 对话。 +- 简短说明:上传客户邮件或订单 PDF,系统将解析订单、核对库存并提交货代发货需求。 +- 支持格式说明:EML、PDF;其他首期支持格式按实际能力显示。 +- “我的任务”入口;点击任务后回到所属对话并聚焦对应消息。 + +#### B. 文件上传区 + +- 支持拖拽和点击选择。 +- 支持一次选择多份文件。 +- 支持多次追加选择。 +- 显示允许格式、单文件大小上限和本次文件数量上限。 +- 不根据扩展名猜测业务用途,只展示文件类型。 + +#### C. 文件列表 + +每个顶层文件展示: + +- 文件名。 +- 文件类型。 +- 文件大小。 +- 上传状态。 +- 快览状态。 +- 错误说明。 +- 删除按钮。 +- 单文件重试按钮。 + +EML 文件支持展开: + +- 发件人。 +- 邮件主题。 +- 邮件时间。 +- 附件数量。 +- 附件文件名和类型。 +- 不支持或被忽略的附件说明。 + +#### D. 提交摘要 + +- 已选择文件数。 +- 已就绪文件数。 +- 仍在上传/快览的文件数。 +- 失败或不支持文件数。 +- 当前是否允许开始处理。 + +#### E. 开始处理 + +按钮启用条件: + +- 至少存在一个已就绪的有效订单材料。 +- 所有待提交文件不处于上传中。 +- 不存在阻断提交的文件错误。 + +点击后: + +- 汇集当前输入区全部已就绪且未消费的材料。 +- 创建一次业务提交。 +- 按钮进入“正在创建任务”。 +- 成功后右侧出现本次处理卡片。 +- 重复点击不得创建重复任务。 + +#### F. 本次处理消息卡片 + +展示: + +- 提交编号或主要任务编号。 +- 当前业务阶段。 +- 当前状态。 +- 已完成的稳定检查点。 +- 需要人工处理的数量。 +- 最后活动时间。 +- “展开工作台”主按钮;按当前节点显示“进入订单复核”“查看库存差异”等具体文案。 +- “在对话中查看”次入口,用于关闭工作台后回到对应消息。 + +#### G. 对话输入区 + +- 支持补充业务说明,但补充内容必须关联当前会话和当前任务。 +- 支持追加 EML/PDF;追加材料后明确提示可能使下游结果失效。 +- 支持询问“当前处理到哪里”“为什么暂停”等只读问题。 +- 不提供通过自然语言直接绕过业务门禁、修改库存或触发上传的能力。 + +### 11.4 页面状态 + +| 状态 | 页面表现 | +| --- | --- | +| 初始空状态 | 展示上传引导和“选择文件”主操作 | +| 上传中 | 每个文件独立进度;上传中的文件禁止删除或明确确认后取消 | +| 快览中 | 展示“正在读取邮件和附件目录”,不显示深度解析进度 | +| 部分失败 | 成功文件保留;失败文件原位展示原因和重试 | +| 已就绪 | 显示文件和附件目录,可开始处理 | +| 创建任务中 | 锁定当前文件列表,防止重复提交 | +| 自动处理中 | 对话消息卡展示业务阶段;允许离开页面;可展开工作台 | +| 需要处理 | 对话消息卡突出阻断原因和唯一主动作“展开工作台” | +| 已完成 | 展示上传成功、货代参考号和查看详情入口 | + +--- + +## 12. P02 我的发货任务页 + +### 12.1 页面目标 + +聚合用户需要处理和关注的任务,使用户优先看到人工待办,同时可以访问自动处理任务和历史结果。 + +### 12.2 页面结构 + +```text +┌──────────────────────────────────────────────────────────┐ +│ 我的发货任务 [打开对话] [刷新] │ +├──────────────────────────────────────────────────────────┤ +│ [待我处理 8] [自动处理中 5] [已完成] [全部任务] │ +├──────────────────────────────────────────────────────────┤ +│ 搜索 PO/预约单号/任务编号 客户 状态 时间 [清除] │ +├───────────────────────────┬──────────────────────────────┤ +│ 任务列表 │ 任务摘要 │ +│ │ │ +│ 状态/客户/PO │ 当前待办 │ +│ 阶段/阻断原因 │ 处理阶段 │ +│ 最后活动时间 │ 订单摘要 │ +│ │ 最近记录 │ +│ │ [处理/查看] │ +└───────────────────────────┴──────────────────────────────┘ +``` + +### 12.3 顶部分组 + +#### 待我处理 + +包含: + +- 字段冲突。 +- 关键字段缺失。 +- AI 仍无法判断的低置信字段。 +- 库存源无候选或多候选。 +- 库存不足。 +- RPA 结果未知。 +- 需要人工结束或继续的其他业务例外。 + +默认排序:业务紧急程度 → 等待时间 → 创建时间。 + +#### 自动处理中 + +包含: + +- 解析中。 +- AI 辅助分析中。 +- 库存准备中。 +- 库存匹配中。 +- Excel 生成中。 +- 货代上传中。 +- 等待明确外部回执。 + +#### 已完成 + +只包含已得到明确成功结果的任务。 + +#### 全部任务 + +包含已终止、明确失败和历史任务。 + +### 12.4 筛选字段 + +- 任务编号。 +- 客户名称。 +- 客户 PO。 +- 预约单号。 +- 当前状态。 +- 当前阶段。 +- 创建时间范围。 +- 创建人;主管或管理员可见。 + +### 12.5 任务列表字段 + +- 状态图标及状态名称。 +- 任务编号。 +- 客户名称。 +- 客户 PO。 +- 预约单号。 +- 订单行数量。 +- 当前业务阶段。 +- 阻断原因摘要。 +- 创建时间。 +- 最后活动时间。 + +### 12.6 右侧任务摘要 + +- 任务基础信息。 +- 当前最高优先级待办。 +- 五阶段进度摘要。 +- 订单行数量和异常行数量。 +- 库存源。 +- 最近三条业务记录。 +- 唯一主操作:处理或查看详情。 + +### 12.7 交互要求 + +- 默认进入“待我处理”。 +- 自动处理中任务才启用自动刷新。 +- 页面不可见时降低刷新频率。 +- 筛选或切换分组后回到第一页。 +- 不跨分页保留选择。 +- 选中任务后更新 URL 中的稳定任务标识,刷新页面可恢复当前选择。 +- 任务状态变化时,列表与右侧摘要使用同一服务端状态,不在前端分别推导。 + +--- + +## 13. P03 对话内任务详情工作台 + +### 13.1 页面目标 + +当用户从对话中的处理进度消息卡点击“展开工作台”时,在当前会话上下文中回答四个核心问题: + +1. 当前处理到哪里? +2. 为什么停止或等待? +3. 系统已经完成了什么? +4. 用户现在应该做什么? + +### 13.2 页面结构 + +```text +┌──────────────────────────────────────────────────────────┐ +│ 工作台:任务编号 [缩起工作台] [回到对话] [更多操作] │ +├──────────────────────────────────────────────────────────┤ +│ 材料解析 → 订单确认 → 库存处理 → 发货文件 → 货代上传 │ +├───────────────────────┬──────────────────────────────────┤ +│ 当前待办 │ 订单概览 │ +│ 问题说明 │ 表头字段 │ +│ 影响范围 │ 订单明细 │ +│ 建议处理方式 │ │ +│ [主操作] [次操作] │ │ +├───────────────────────┴──────────────────────────────────┤ +│ 库存匹配结果 / 发货 Excel / 上传结果 / 操作记录 │ +└──────────────────────────────────────────────────────────┘ +``` + +工作台顶部必须提供“缩起工作台”,缩起后回到触发它的对话消息,不跳转到无上下文的任务列表。 + +### 13.3 页面头部 + +- 缩起工作台并返回触发消息。 +- 回到对话顶部或当前对话位置。 +- 任务编号。 +- 客户名称。 +- 客户 PO。 +- 预约单号。 +- 当前状态。 +- 创建人。 +- 创建时间。 +- 最后活动时间。 +- 更多操作:刷新、查看原始材料、结束任务;根据状态和权限显示。 + +### 13.4 五阶段进度 + +固定为用户可理解的大阶段: + +1. 材料解析。 +2. 订单确认。 +3. 库存处理。 +4. 发货文件。 +5. 货代上传。 + +每个阶段仅使用以下状态: + +- 未开始。 +- 进行中。 +- 已完成。 +- 需要处理。 +- 明确失败。 +- 结果待确认。 + +点击阶段可滚动到对应页面模块,但不在进度条中提供复杂写操作。 + +### 13.5 当前待办卡 + +页面存在阻断时必须置顶显示,并固定包含: + +- 待办标题。 +- 发生了什么。 +- 影响哪些字段或订单行。 +- 为什么系统不能继续。 +- 推荐处理方式。 +- 完成后会从哪个阶段继续。 +- 主操作。 +- 次操作;仅在确有必要时提供。 + +待办示例: + +| 待办 | 主操作 | +| --- | --- | +| 邮件正文与 PDF 数量不一致 | 进入订单复核 | +| 未能唯一确定库存源 | 选择库存源 | +| 库存不足 | 查看库存差异 | +| 库存抓取明确失败 | 重试抓取 | +| 货代上传结果未知 | 查看执行记录 | + +### 13.6 订单概览 + +#### 表头信息 + +- 客户。 +- 客户 PO。 +- Ship-to。 +- 发货日期;若有。 +- 材料数量。 +- 解析模板名称及版本;折叠展示。 + +#### 订单明细 + +- 行号。 +- 预约单号。 +- 客户料号;若有。 +- 内部料号。 +- 数量。 +- 单位。 +- 库存源线索。 +- 已确认库存源。 +- 字段状态。 + +字段状态建议: + +- 模板已确认。 +- AI 辅助建议。 +- 人工已确认。 +- 存在冲突。 +- 证据不足。 + +### 13.7 库存匹配结果 + +模块字段: + +- 库存源。 +- 库存快照时间。 +- 文件有效期或是否过期。 +- 抓取结果。 +- 匹配完成时间。 +- 明细表:预约单号、料号、需求量、可用量、短缺量、匹配状态。 + +操作: + +- 查看库存文件信息。 +- 重新抓取;仅明确可重试时。 +- 更换库存源;需权限和原因。 +- 查看库存不足处理说明。 + +### 13.8 发货 Excel + +展示: + +- 生成状态。 +- 文件名。 +- 生成时间。 +- 使用的 Excel 模板版本。 +- 订单数据版本。 +- 库存快照时间。 +- 复读校验状态。 +- 下载文件。 + +当上游订单或库存发生变化时: + +- 旧 Excel 标记为已失效。 +- 禁止继续用于上传。 +- 明确说明失效原因。 +- 重新生成后保留旧版本审计,但默认只展示当前有效版本。 + +### 13.9 货代上传结果 + +状态和页面行为: + +| 状态 | 页面表现 | 允许操作 | +| --- | --- | --- | +| 未开始 | 等待前置阶段完成 | 无 | +| 排队中 | 已进入上传队列 | 查看详情 | +| 上传中 | 显示开始时间和最后活动 | 查看详情 | +| 上传成功 | 显示货代参考号和回执时间 | 查看回执 | +| 明确失败 | 显示业务化失败原因 | 条件允许时重试 | +| 结果未知 | 明确提示避免重复发货 | 查看执行记录、人工核查 | + +### 13.10 操作记录 + +按时间倒序或正序统一展示业务事件: + +- 上传材料。 +- 模板解析完成。 +- AI 提出字段建议。 +- 人工采用或拒绝建议。 +- 人工修改字段。 +- 库存源确认。 +- 库存抓取开始/完成。 +- 库存匹配通过/不足。 +- Excel 生成和失效。 +- 货代上传开始/成功/明确失败/结果未知。 + +普通用户不直接看到模型 Prompt、Token、Worker、内部 Job、堆栈或系统凭据。 + +--- + +## 14. P04 对话内订单复核工作台 + +### 14.1 页面目标 + +从对话中的冲突消息卡或任务工作台点击展开,集中处理固定模板无法自动确认的问题,使用户能够在订单字段、候选值和原始证据之间快速切换,并完成可审计的人工裁决。复核完成后,结果写回对话并触发下游自动处理。 + +### 14.2 页面结构 + +```text +┌────────────────────────────────────────────────────────────┐ +│ ← 返回任务 客户 / PO / 复核编号 保存状态 [处理记录] │ +├──────────────┬─────────────────────────────┬───────────────┤ +│ 材料导航 │ 订单字段与明细 │ 待处理问题 │ +│ │ │ │ +│ 邮件 A │ 客户 PO │ 字段冲突 2 │ +│ ├─ 正文 │ 预约单号 │ 证据不足 1 │ +│ ├─ PO.pdf │ 料号 / 数量 / 单位 │ │ +│ └─ Book.pdf │ 库存源线索 │ AI 建议 │ +│ │ │ │ +├──────────────┴─────────────────────────────┴───────────────┤ +│ [打开原始证据] [保存草稿] [确认并继续] │ +└────────────────────────────────────────────────────────────┘ +``` + +### 14.3 顶部信息 + +- 缩起工作台并返回对话中的冲突消息卡。 +- 返回任务工作台;保留当前材料和字段焦点。 +- 当前客户、PO 和复核编号。 +- 当前材料序号;例如 1/3。 +- 保存状态:未保存、保存中、已保存、保存失败。 +- 当前版本。 +- 处理记录入口。 + +### 14.4 材料导航 + +- 按 EML 分组显示邮件正文和附件。 +- 直接上传 PDF 独立分组。 +- 每个材料显示解析状态和问题数量。 +- 点击材料切换当前查看对象。 +- 切换前存在未保存修改时必须提示保存、放弃或取消切换。 +- 切换材料时清空上一材料的临时高亮和 AI 建议上下文。 + +### 14.5 订单字段区 + +#### 表头字段 + +- 按业务分组展示。 +- 必填字段显示必填标识。 +- 异常字段置顶或提供“只看异常”筛选。 +- 每个字段显示当前值、来源状态和证据入口。 + +#### 订单明细表 + +- 支持行级编辑。 +- 支持新增、复制和删除草稿行;是否开放根据业务规则控制。 +- 固定关键列:预约单号、料号、数量、单位、库存源线索。 +- 异常单元格显示问题标识。 +- 双击或点击证据按钮定位对应原始文件位置。 + +### 14.6 待处理问题栏 + +问题分类: + +- 关键字段缺失。 +- 邮件与附件冲突。 +- 多附件冲突。 +- 模板解析低置信。 +- AI 仍无法判断。 +- 无库存源候选。 +- 多库存源候选。 + +每条问题展示: + +- 字段或订单行。 +- 问题摘要。 +- 候选值数量。 +- 是否存在 AI 建议。 +- 是否阻断确认。 +- “立即处理”入口。 + +### 14.7 字段裁决面板 + +点击异常字段后打开,展示: + +| 内容 | 说明 | +| --- | --- | +| 当前值 | 当前草稿使用值 | +| 模板解析值 | 固定模板的原始结果 | +| 其他候选值 | 来自邮件正文或其他附件 | +| AI 建议 | 推荐候选、依据和风险;如存在 | +| 原始证据 | 文件、页码、表格/单元格、原文引用 | +| 用户决定 | 采用候选、手工输入或保持当前值 | +| 修改原因 | 关键字段修改时必填 | + +AI 建议必须标记为“建议”,不能与“系统已验证”或“人工已确认”使用相同状态。 + +### 14.8 原始证据面板 + +支持: + +- PDF 页面预览。 +- 当前字段框选或高亮。 +- 邮件正文片段。 +- 表格单元格定位。 +- 上一个/下一个异常字段。 +- 适合宽度、缩放和页面切换。 + +原型可采用抽屉、浮层或侧栏,但应保证订单明细表仍具备足够编辑空间。 + +### 14.9 底部操作栏 + +- 保存草稿。 +- 重新解析当前材料。 +- 标记为非订单材料。 +- 标记材料质量问题。 +- 确认并继续。 + +“确认并继续”启用条件: + +- 所有阻断问题已处理。 +- 所有必填字段完整。 +- 关键字段格式校验通过。 +- 用户已保存当前草稿。 +- 当前版本未被其他操作更新。 + +确认后: + +- 固定当前人工决定。 +- 记录审计。 +- 返回任务详情或继续当前任务的自动流程。 +- 仅重新执行受影响的下游阶段。 + +--- + +## 15. P05 对话内库存处理工作台 + +### 15.1 页面目标 + +处理库存源不明确、库存文件异常、匹配失败和库存不足。由对话中的库存消息卡或任务工作台展开;用户完成处理后结果以新消息或更新卡片写回当前对话。 + +### 15.2 库存源选择 + +展示: + +- 订单解析得到的库存源线索。 +- 规则产生的候选库存源。 +- 每个候选的命中规则摘要。 +- 库存源启用和就绪状态。 +- 当前人工选择。 + +操作: + +- 选择库存源。 +- 查看候选依据。 +- 填写选择原因。 +- 确认后重新执行库存准备和匹配。 + +禁止: + +- 选择已停用或未就绪库存源继续自动流程。 +- 前端自行推导库存源可用性。 +- AI 创建不存在的库存源代码。 + +### 15.3 库存抓取异常 + +页面应区分: + +- 登录失败。 +- 查询失败。 +- 下载失败。 +- 文件格式异常。 +- 查询成功但库存为空。 +- 超时且结果未知。 + +只有明确失败且满足重试条件时提供“重试抓取”。查询成功但库存为空是有效业务结果,不显示为系统故障。 + +### 15.4 库存不足 + +展示: + +- 库存源。 +- 库存快照时间。 +- 预约单号。 +- 料号。 +- 需求数量。 +- 可用数量。 +- 短缺数量。 +- 受影响订单行。 + +操作: + +- 等待库存更新。 +- 重新抓取库存。 +- 更换库存源;如业务允许。 +- 结束本次处理。 + +首期规则:任一订单行库存不足,整张发货任务不得生成部分发货 Excel。 + +--- + +## 16. P06 RPA 执行详情 + +### 16.1 呈现方式 + +首期建议作为任务详情或管理端中的详情抽屉,不单独占据业务主导航。 + +### 16.2 展示内容 + +- 执行类型:库存抓取或货代上传。 +- 执行编号。 +- 目标库存源或货代系统。 +- 请求时间。 +- 开始时间。 +- 结束时间。 +- 当前状态。 +- 最后活动时间。 +- 明确失败原因。 +- 回执摘要。 +- 关联库存文件或发货 Excel。 +- 重试次数和每次结果。 + +### 16.3 重试规则 + +- 明确技术失败:根据服务端允许动作显示重试。 +- 业务拒绝:不能使用普通技术重试,需按业务提示处理。 +- 结果未知:禁止直接重试,显示“请先核查外部系统”。 +- 成功:不提供重复执行。 + +--- + +## 17. P07 库存源管理页 + +### 17.1 页面目标 + +维护库存系统连接、报表路径、查询参数、解析方案和发货模板绑定,并确认库存源是否具备生产使用条件。 + +### 17.2 页面模块 + +- 库存源列表。 +- 启用/停用状态。 +- 就绪状态及唯一阻断原因。 +- 系统类型。 +- 连接配置摘要;敏感信息脱敏。 +- 报表路径和查询参数。 +- 当前库存解析方案。 +- 当前发货 Excel 模板。 +- 最近配置测试结果。 +- 最近成功抓取时间。 +- 新建、编辑、测试、停用操作。 +- 批量验证进度;如保留现有能力。 + +### 17.3 启用原则 + +只有连接、查询、已发布解析方案、已发布发货模板和相关字段契约均满足要求时,库存源才能启用。前端只展示服务端就绪结论和阻断原因,不自行计算是否可启用。 + +--- + +## 18. P08 订单解析模板页 + +首期以复用现有固定模板能力为主,原型只需保证以下核心模块完整: + +- 模板列表和生命周期。 +- 适用客户和文件特征。 +- 样本文件。 +- 表头字段区域。 +- 明细表区域和列绑定。 +- 字段必填、格式和标准化规则。 +- 模板验证结果。 +- 盲测结果。 +- 发布检查。 +- 历史版本和审计。 + +AI 不参与模板发布决策。低置信字段触发 AI 辅助属于运行时能力,不替代模板验证和发布门禁。 + +--- + +## 19. P09 发货 Excel 模板页 + +核心模块: + +- 模板列表和版本状态。 +- 模板文件上传。 +- 订单字段映射。 +- 库存字段映射。 +- 系统生成字段。 +- 文件命名规则。 +- 行生成规则。 +- 预览和测试生成。 +- 复读校验结果。 +- 使用中的库存源。 +- 发布和退役。 +- 历史版本与审计。 + +--- + +## 20. P10 审计中心 + +### 20.1 筛选条件 + +- 时间范围。 +- 任务编号。 +- 客户 PO。 +- 预约单号。 +- 用户。 +- 事件类型。 +- 当前阶段。 +- 结果状态。 + +### 20.2 事件范围 + +- 材料上传和快览。 +- 模板解析。 +- 字段冲突产生。 +- AI 建议产生、采用或拒绝。 +- 人工字段修改。 +- 库存源选择。 +- 库存抓取。 +- 库存匹配。 +- Excel 生成、校验和失效。 +- 货代上传。 +- 明确失败和结果未知。 +- 任务结束。 + +### 20.3 事件详情 + +- 事件时间。 +- 操作人或系统执行主体。 +- 业务对象。 +- 事件说明。 +- 修改前后值。 +- 原始证据引用。 +- 关联文件和版本。 +- 内部错误码;仅授权用户可见。 + +--- + +## 21. 统一状态模型 + +### 21.1 任务状态 + +| 用户状态 | 含义 | 是否需要用户操作 | +| --- | --- | --- | +| 等待开始 | 任务已创建,等待后台执行 | 否 | +| 自动处理中 | 系统正在执行解析、库存、Excel 或 RPA | 否 | +| 需要处理 | 存在业务冲突或人工决定 | 是 | +| 等待外部结果 | 已请求外部系统,等待明确回执 | 通常否 | +| 已完成 | 已明确上传成功 | 否 | +| 处理失败 | 存在明确且可恢复的技术失败 | 视服务端动作 | +| 结果待确认 | 外部执行结果未知,不能自动重试 | 是 | +| 已终止 | 用户或管理员明确结束任务 | 否 | + +### 21.2 文件状态 + +- 等待上传。 +- 上传中。 +- 上传成功。 +- 快览中。 +- 已就绪。 +- 深度解析中。 +- 解析完成。 +- 需要复核。 +- 解析失败。 +- 已忽略。 + +### 21.3 字段状态 + +- 模板已确认。 +- AI 辅助建议。 +- 人工已确认。 +- 存在冲突。 +- 证据不足。 +- 缺失。 +- 格式无效。 + +### 21.4 RPA 状态 + +- 等待执行。 +- 排队中。 +- 执行中。 +- 成功。 +- 明确失败。 +- 业务拒绝。 +- 结果未知。 +- 已取消;仅在外部操作尚未提交时可能存在。 + +--- + +## 22. 关键交互规范 + +### 22.1 唯一主操作 + +每个阻断状态只能有一个最明确的主操作。例如: + +- 字段冲突:进入订单复核。 +- 多库存源:选择库存源。 +- 库存不足:查看库存差异。 +- 明确抓取失败:重试抓取。 +- 上传结果未知:查看执行记录。 + +次操作放入次级按钮或更多操作,避免用户不知道应该先做什么。 + +### 22.2 自动推进 + +- 提交后后台自动处理,用户可以离开页面。 +- 页面只展示服务端已确认的业务阶段和检查点。 +- 不展示未经事实支持的进度百分比。 +- 任务完成或需要人工处理时产生站内通知。 +- 终态后停止自动刷新。 + +### 22.3 防重复提交 + +以下操作必须防止重复提交: + +- 开始处理。 +- 保存人工裁决。 +- 确认并继续。 +- 重新抓取库存。 +- 生成发货 Excel。 +- 上传货代系统。 + +按钮提交后显示明确状态;刷新页面后从服务端恢复真实结果,而不是恢复为可再次点击。 + +### 22.4 修改影响提示 + +用户修改已经参与后续流程的字段时,确认弹窗必须说明: + +- 将失效哪些库存匹配结果。 +- 是否需要重新抓取库存。 +- 现有发货 Excel 是否失效。 +- 已开始或已完成货代上传时是否禁止修改。 + +### 22.5 结果未知处理 + +- 超时不等于失败。 +- 页面不得把“结果未知”显示为普通失败。 +- 不显示普通“重新上传”按钮。 +- 显示最后一次已知动作和外部核查建议。 +- 迟到成功回执到达后可自动更新为成功。 + +### 22.6 并发与版本冲突 + +当其他用户或后台流程已更新任务时: + +- 保存或确认操作被拒绝。 +- 页面提示“任务已更新,请刷新后继续”。 +- 用户未保存内容不能静默覆盖最新结果。 +- 提供刷新并查看差异的入口。 + +--- + +## 23. 空状态设计要求 + +| 页面/模块 | 空状态说明 | 推荐主操作 | +| --- | --- | --- | +| 对话输入区 | 尚未添加订单材料 | 选择文件 | +| 待我处理 | 当前没有需要你处理的任务 | 查看自动处理中 | +| 自动处理中 | 当前没有正在处理的任务 | 打开货代 Agent 对话 | +| 已完成 | 暂无已完成任务 | 打开货代 Agent 对话 | +| 搜索结果 | 没有符合当前条件的任务 | 清除筛选 | +| 待处理问题 | 所有阻断问题均已处理 | 确认并继续 | +| 库存匹配 | 尚未进入库存匹配阶段 | 查看处理进度 | +| 发货 Excel | 库存匹配通过后将自动生成 | 无 | +| 上传结果 | 发货文件通过校验后将自动上传 | 无 | +| 操作记录 | 当前任务尚未产生可展示记录 | 刷新 | + +空状态必须解释当前为何为空,以及用户下一步可以做什么,不能只显示“暂无数据”。 + +--- + +## 24. 加载状态设计要求 + +### 24.1 首次加载 + +- 列表、任务摘要和详情模块使用对应结构的骨架屏。 +- 不因一个局部接口加载而遮挡整个页面。 +- 页面头部稳定显示,减少页面跳动。 + +### 24.2 文件处理 + +每个文件独立显示上传和快览状态,不能只显示整批统一进度。 + +### 24.3 自动处理 + +展示: + +- 当前业务阶段。 +- 最近完成的检查点。 +- 最后活动时间。 +- 页面是否自动刷新。 +- 超过正常等待时间后的提示。 + +### 24.4 AI 辅助分析 + +- 显示“正在核对当前字段的邮件和附件证据”。 +- 不显示模型思考过程、Prompt、Token 或内部节点。 +- 超时或失败后显示“AI 辅助暂不可用,已转人工复核”,固定模板结果仍保留。 + +### 24.5 局部失败 + +- PDF 预览失败不阻止已加载的字段编辑。 +- 操作记录加载失败不应把任务显示为失败。 +- AI 建议失败不影响人工查看模板解析值和原始证据。 +- 每个局部失败均提供局部重试。 + +--- + +## 25. 错误状态与用户文案原则 + +错误信息统一包含: + +1. 发生了什么。 +2. 对当前任务有什么影响。 +3. 用户下一步可以做什么。 + +示例: + +> 邮件正文中的数量为 1,000,PO 附件中的数量为 1,200。系统无法自动判断本次实际发货数量,请核对原始材料后选择正确值。 + +> 当前库存文件已超过有效期,不能用于本次匹配。请重新抓取库存后继续。 + +> 货代系统尚未返回明确上传结果。为避免重复发货,当前不能重新上传,请先核查货代系统。 + +普通业务页面不直接回显内部错误码、异常堆栈或服务名称;管理员可在详情中查看脱敏技术信息。 + +--- + +## 26. 通知与提醒 + +首期建议支持站内通知和导航待办角标: + +- 订单解析需要人工复核。 +- 库存源需要选择。 +- 库存不足。 +- 库存抓取明确失败。 +- 发货 Excel 生成失败。 +- 货代上传成功。 +- 货代上传明确失败。 +- 货代上传结果未知。 +- 待办超过规定时间未处理。 + +通知点击后必须直接进入对应任务和待办位置,而不是只进入任务列表首页。 + +--- + +## 27. 移动端适配策略 + +### 27.1 移动端定位 + +移动端首期以查看状态、接收通知和完成轻量决定为主,不要求完成复杂表格和 PDF 证据编辑。 + +### 27.2 移动端支持 + +- 上传或补充订单材料。 +- 查看任务列表和任务状态。 +- 查看阻断原因。 +- 查看订单摘要和库存不足摘要。 +- 选择简单的候选值。 +- 确认继续或结束任务。 +- 查看货代上传结果。 + +### 27.3 建议转桌面端的操作 + +- 批量编辑多行订单。 +- 同时对比多个附件。 +- 精确查看 PDF 坐标证据。 +- 配置库存源。 +- 配置解析模板和 Excel 模板。 +- 深度审计分析。 + +### 27.4 响应式要求 + +#### 桌面端 + +- 任务列表和摘要双栏。 +- 复核工作台允许材料、字段和问题并列展示。 +- 订单明细保持表格形式。 + +#### 平板端 + +- 列表和详情分屏或切换展示。 +- 问题栏改为顶部折叠区。 +- 原始证据使用全屏抽屉。 + +#### 手机端 + +- 五阶段进度改为当前阶段卡和可展开列表。 +- 订单行由表格改为逐行卡片。 +- 主操作固定在底部安全区域。 +- 筛选使用抽屉。 +- 原始证据全屏打开。 +- 复杂操作显示“建议使用桌面端处理”。 + +--- + +## 28. 对话与工作台交互规范 + +### 28.1 对话消息类型 + +货代 Agent 对话至少支持以下业务消息卡: + +| 消息卡 | 触发时机 | 主要动作 | +| --- | --- | --- | +| 文件接收卡 | 文件上传或自动收件完成 | 查看附件、开始处理 | +| 处理中卡 | 后台正在执行 | 展开工作台、查看最近活动 | +| 需要复核卡 | 字段冲突或低置信问题 | 展开订单复核工作台 | +| 库存处理卡 | 库存源、抓取或匹配异常 | 展开库存处理工作台 | +| Excel 卡 | Excel 生成、失效或待下载 | 展开发货文件工作台、下载 | +| 上传结果卡 | RPA 上传完成、失败或未知 | 展开上传详情、查看回执 | +| 完成摘要卡 | 任务成功完成 | 查看任务摘要、下载结果 | + +消息卡必须显示业务状态和下一步,不显示内部节点名、Job、Worker 或模型调用细节。 + +### 28.2 工作台展开规则 + +- 用户点击消息卡主按钮后展开对应工作台。 +- 工作台默认聚焦触发问题,例如冲突字段、库存不足行或上传结果。 +- 展开工作台时,对话保持在同一会话上下文;不可新开一个无关联页面。 +- 桌面端至少支持“对话 + 工作台”和“工作台主视图”两态。 +- 工作台展开后对话缩为窄栏,但至少保留会话标题、最近一条相关消息和“返回对话”。 +- 用户可以点击“缩起工作台”返回原消息位置。 +- 工作台关闭不会取消后台任务;有未保存修改时必须先处理保存、放弃或取消。 + +### 28.3 对话缩起规则 + +- 工作台主视图下,对话不销毁,只折叠为窄栏或可展开抽屉。 +- 对话缩起时不停止任务轮询和后台自动推进。 +- 新系统消息到达时显示未读标识,但不得强制打断正在编辑的工作台。 +- 用户返回对话时,滚动到触发工作台的消息或最近未读消息。 +- 移动端优先采用全屏工作台,顶部提供返回对话按钮。 + +### 28.4 写操作归属 + +- 上传材料:对话输入区或文件附件卡。 +- 字段修改和人工裁决:订单复核工作台。 +- 库存源选择和库存恢复:库存处理工作台。 +- Excel 下载:Excel 消息卡或发货文件工作台。 +- RPA 上传重试或结果核查:上传结果工作台或详情抽屉。 +- 对话文本只触发受控的只读解释和已授权操作确认,不作为复杂业务表单的替代。 + +### 28.5 从任务中心恢复对话 + +从“我的任务”点击任务时: + +1. 定位任务所属 conversation。 +2. 打开该对话。 +3. 定位关联消息卡。 +4. 根据服务端节点状态自动展开对应工作台。 +5. 目标工作台未就绪时,先显示加载状态并保留对话上下文。 + +任务中心不能只改变 URL 参数后显示旧会话或旧任务内容。 + +## 29. 页面跳转关系 + +```text +货代 Agent 对话 + ├─ 上传/自动收件成功 → 文件接收卡 + ├─ 自动处理中 → 处理中消息卡 + ├─ 需要字段复核 → 展开订单复核工作台 + ├─ 库存异常 → 展开库存处理工作台 + └─ 上传结果 → 展开上传详情 + +我的任务 + ├─ 普通任务 → 所属对话 + 任务工作台 + ├─ 字段冲突/缺失 → 所属对话 + 订单复核工作台 + ├─ 库存异常 → 所属对话 + 库存处理工作台 + └─ RPA 异常 → 所属对话 + 上传详情抽屉 + +订单复核工作台 + ├─ 保存草稿 → 留在当前页面 + ├─ 确认并继续 → 缩起工作台 + 对话新结果消息 + └─ 取消/返回 → 对话原消息位置 + +任务工作台 + ├─ 查看原始材料 → 当前工作台证据面板 + ├─ 查看库存差异 → 库存处理工作台 + ├─ 查看执行记录 → RPA详情抽屉 + └─ 下载 Excel → 当前有效文件 +``` + +--- + +## 30. 原型必须覆盖的关键状态 + +为避免只设计正常完成页面,原型至少应覆盖以下页面状态: + +### 30.1 对话主视图 + +1. 初始空状态。 +2. 多文件上传中。 +3. EML 快览完成并展开附件。 +4. 单文件失败但其他文件成功。 +5. 已就绪等待开始处理。 +6. 已提交且自动处理中。 +7. 已提交且需要人工复核。 + +### 30.2 我的任务页 + +1. 待我处理有数据。 +2. 自动处理中有数据。 +3. 无任务空状态。 +4. 筛选无结果。 +5. 选中任务后的右侧摘要。 + +### 30.3 任务工作台 + +1. 正常自动处理中。 +2. 字段冲突中断。 +3. 多库存源待选择。 +4. 库存抓取失败。 +5. 库存不足。 +6. Excel 已生成待上传。 +7. 货代上传中。 +8. 上传成功。 +9. 上传明确失败。 +10. 上传结果未知。 + +### 30.4 订单复核工作台 + +1. 单字段模板低置信,存在 AI 建议。 +2. 邮件正文与 PDF 冲突。 +3. AI 无法判断,需要人工输入。 +4. 多个异常字段。 +5. 原始证据加载中。 +6. 原始证据加载失败。 +7. 未保存修改切换材料。 +8. 所有问题处理完成,可以确认。 +9. 版本冲突,需要刷新。 + +--- + +## 31. 数据展示与隐私要求 + +- 文件名、邮件正文、原始证据、库存数据按权限展示。 +- 敏感字段默认脱敏;点击查看需要权限并记录审计。 +- 前端日志和错误提示不得包含文件存储地址、访问 Token、账号或密码。 +- 下载链接应有有效期,过期后重新申请,不在页面长期保存真实地址。 +- AI 只接收当前字段所需的最小证据,不向页面展示内部完整 Prompt。 +- AI 建议记录模型版本和输入证据引用,但普通业务页面只显示业务化信息。 + +--- + +## 32. 业务规则与安全底线 + +- 固定模板解析是首期订单字段主来源。 +- AI 只能辅助低置信字段,不得无证据生成最终值。 +- 同一 EML 内关键字段冲突不得静默选择。 +- 不同 EML 默认不交叉补字段。 +- 未确认客户或关键订单字段不得进入库存和上传阶段。 +- 未唯一确定库存源不得抓取或匹配库存。 +- 库存正式匹配必须使用明确的预约单号和料号规则。 +- 任一订单行库存不足,整单不得生成部分发货 Excel。 +- Excel 生成后必须复读校验关键字段、行数和文件完整性。 +- 上游字段或库存变化后,旧 Excel 必须失效。 +- 货代上传结果未知不得自动重传。 +- AI、前端和 RPA 均不得绕过服务端业务门禁。 +- 所有人工修改、恢复和外部执行必须具备审计记录。 + +--- + +## 33. 首期验收标准 + +### 33.1 上传与任务创建 + +- 支持一次或多次选择多份 EML/PDF,并作为一次提交开始处理。 +- EML 可展示正文快览状态和附件目录。 +- 单文件失败不影响其他文件保留和继续处理。 +- 重复点击“开始处理”不会创建重复任务。 +- 页面刷新后可恢复本次提交和任务状态。 + +### 33.2 模板解析与 AI 辅助 + +- 固定模板可以提取首期关键字段并展示字段证据。 +- 低置信字段能够触发单字段 AI 辅助分析。 +- AI 建议包含候选值、来源、依据和风险。 +- AI 不可用时,任务进入人工复核而不是整体失败。 +- AI 建议与模板结果、系统验证、人工确认在状态上明确区分。 + +### 33.3 人工复核 + +- 用户可以查看冲突候选和对应原始证据。 +- 用户可以采用候选值或手工输入,并填写必要原因。 +- 未解决所有阻断问题时不能确认继续。 +- 确认后只重新执行受影响的下游流程。 +- 并发修改时不会静默覆盖其他用户或后台结果。 + +### 33.4 库存处理 + +- 能展示库存源候选、当前选择和选择依据。 +- 无候选或多候选会中断并要求人工决定。 +- 能展示库存快照时间和有效状态。 +- 能按订单行展示需求量、可用量和短缺量。 +- 任一行库存不足时不生成部分发货 Excel。 + +### 33.5 Excel 和货代上传 + +- 库存全部满足后可以自动生成发货 Excel。 +- 页面展示文件版本、模板版本和复读校验结果。 +- 上游数据变化会使旧 Excel 明确失效。 +- 上传成功展示货代参考号或可用回执。 +- 明确失败与结果未知有不同页面状态和操作。 +- 结果未知时不存在普通重传按钮。 + +### 33.6 页面体验 + +- 每个阻断状态均有明确原因、影响范围和下一步主操作。 +- 自动处理中允许用户离开页面。 +- 待我处理、自动处理中和完成状态可在任务中心清晰区分。 +- 页面具备完整空状态、加载状态、局部失败和移动端降级方案。 +- 普通业务页面不暴露内部模型思考、Prompt、Worker、Job 或技术堆栈。 + +--- + +## 34. P11 对话内自动收件箱与自动邮件接入 + +### 34.1 产品目标 + +自动邮件接入是货代发货 Agent 的核心发展方向。系统接入经过授权的企业邮箱或指定收件文件夹,自动发现新邮件、识别是否属于发货业务、完成去重和安全检查,并为符合条件的邮件创建发货任务。 + +目标态下,发货业务人员的主要工作从“导出邮件并上传”转变为: + +- 关注系统自动创建的任务。 +- 处理无法自动分类的邮件。 +- 处理字段冲突、库存不足和外部执行异常。 +- 对自动接入结果进行抽查和审计。 + +### 34.2 自动接入流程 + +```text +授权企业邮箱 / 指定文件夹 + ↓ +系统增量同步新邮件 + ↓ +邮件身份去重与安全检查 + ↓ +判断是否属于货代发货业务 + ↓ + ├─ 明确不是 → 归类为已忽略,保留原因 + ├─ 无法判断 → 进入待确认邮件 + └─ 明确属于 → 创建发货提交和任务 + ↓ + 进入统一固定模板解析主链 +``` + +### 34.3 自动收件箱页面结构 + +```text +┌──────────────────────────────────────────────────────────┐ +│ 发货接入 [同步状态] [设置] │ +├──────────────────────────────────────────────────────────┤ +│ [待确认邮件] [已创建任务] [已忽略] [接入异常] │ +├──────────────────────────────────────────────────────────┤ +│ 邮箱/文件夹 发件人 主题 接收时间 附件 判断结果 │ +│ │ +│ 客户邮件摘要 关联任务/处理动作 │ +├──────────────────────────────────────────────────────────┤ +│ 同步状态:最近成功时间 / 下次检查 / 当前异常 │ +└──────────────────────────────────────────────────────────┘ +``` + +### 34.4 页面模块 + +#### 待确认邮件 + +面向系统无法可靠判断是否属于发货业务的邮件,展示: + +- 收件邮箱和文件夹。 +- 发件人、收件人、主题和接收时间。 +- 附件名称与类型。 +- 判断为发货邮件的依据。 +- 无法自动判断的原因。 +- “创建发货任务”主操作。 +- “标记为非发货邮件”次操作。 + +#### 已创建任务 + +- 邮件摘要。 +- 自动创建时间。 +- 关联任务编号。 +- 当前业务阶段。 +- 当前待办。 +- 进入任务详情。 + +#### 已忽略 + +- 邮件摘要。 +- 忽略原因。 +- 判断来源:规则、人工或安全策略。 +- 恢复并创建任务;仅在权限和状态允许时。 + +#### 接入异常 + +- 邮箱授权失效。 +- 同步失败。 +- 附件下载失败。 +- 邮件内容过大或格式不支持。 +- 同一邮件身份发生异常重复。 +- 当前是否影响后续邮件接收。 +- 管理员可执行的恢复动作。 + +#### 同步状态 + +- 邮箱连接状态。 +- 监控文件夹。 +- 最近一次成功同步时间。 +- 最近一次发现邮件时间。 +- 当前积压数量。 +- 当前错误摘要。 + +### 34.5 自动创建门禁 + +自动接入不等于无条件自动建任务。至少需要满足: + +- 邮件来自已授权邮箱接入范围。 +- 邮件具有稳定唯一身份,未被成功消费。 +- 邮件和附件通过安全检查。 +- 发货业务分类达到规定门槛,或命中确定性收件规则。 +- 不属于自动回复、退信、系统通知或已知无关邮件。 +- 附件目录完整,关键附件能够保存和读取。 +- 创建任务具备幂等保护。 + +无法满足自动创建门禁时,应保留原邮件并进入待确认或接入异常,不能静默丢弃。 + +### 34.6 人工上传的长期定位 + +自动邮件接入上线后,手动上传仍保留,但定位调整为: + +- 补录历史邮件。 +- 客户通过非邮件渠道提供材料时创建任务。 +- 自动接入异常时的受控恢复入口。 +- 模板验证和测试。 + +系统应提示可能重复的邮件或文件,并优先关联既有任务,避免手动上传绕过邮件去重。 + +### 34.7 首期原型预留要求 + +即使首期不实现自动收件箱,页面和数据展示也应预留: + +- 任务“接入方式”:手动上传、自动邮件、人工补录。 +- 邮件接收时间,而不仅是文件上传时间。 +- 接入邮箱和文件夹位置;有权限时展示。 +- 邮件唯一标识和去重结果;普通页面可折叠。 +- 系统自动创建主体与人工创建人的区别。 +- 任务列表按接入方式筛选的扩展位置。 +- “发货接入”导航容器,使未来可加入“上传材料/自动收件箱”页签。 + +--- + +## 35. 产品发展路线 + +### 阶段一:手动材料接入与自动处理闭环 + +- 用户上传 EML/PDF。 +- 固定模板解析为主。 +- AI 辅助低置信字段。 +- 人工例外处理。 +- 库存 RPA、Excel 生成和货代上传闭环。 + +### 阶段二:自动收件、人工确认创建 + +- 接入授权企业邮箱或指定文件夹。 +- 自动同步、去重和保存新邮件。 +- 系统推荐是否为发货邮件。 +- 用户在自动收件箱确认后创建任务。 +- 手动上传保留为补录入口。 + +### 阶段三:自动识别并创建任务 + +- 确定性收件规则与受控分类能力通过真实邮件验证。 +- 符合门禁的邮件自动创建任务并进入解析主链。 +- 无法判断的邮件进入待确认。 +- 用户主要处理业务例外,不再执行邮件导出和上传。 + +### 阶段四:提高自动处理覆盖率 + +- AI 对非固定新模板进行文档分类和字段提取。 +- AI 总结大量订单行的异常重点。 +- AI 辅助解释库存未命中的可能原因。 +- AI 生成待人工发送的客户补充资料询问草稿。 +- 根据人工真值建立模板回归样本和质量报告。 +- 新模板或模板漂移发现,但仍需管理员验证和发布。 +- 跨任务协作、转交和认领。 +- 移动端轻量审批和通知闭环。 + +--- + +## 36. 原型设计交付建议 + +后续原型设计建议至少交付: + +- P01 HXOPS Agent 对话页的 4 个核心状态:初始上传、处理中消息、需要复核消息、完成摘要。 +- P02 我的任务页的桌面端主界面。 +- P03 对话内任务工作台的正常、库存不足、上传结果未知三个状态。 +- P04 对话内订单复核工作台的字段冲突和 AI 建议状态。 +- P05 对话内库存处理工作台的库存源选择与库存不足状态。 +- P06 RPA 执行详情抽屉。 +- 一套移动端任务列表和任务详情降级稿。 +- 页面间可点击跳转关系。 +- 首期导航预留“发货接入”容器,并补充一张目标态自动收件箱概念页,验证后续入口不会破坏现有任务流程。 +- 补充“对话主视图 → 工作台主视图 → 缩起回到原消息”的可点击交互链路。 + +原型应优先验证信息层级、异常处理效率和操作闭环;视觉风格可在功能框架确认后单独确定。 diff --git a/docs/features/shipping-notice/process-gate-recovery-acceptance.md b/docs/features/shipping-notice/process-gate-recovery-acceptance.md index 178abf0d..2cd27829 100644 --- a/docs/features/shipping-notice/process-gate-recovery-acceptance.md +++ b/docs/features/shipping-notice/process-gate-recovery-acceptance.md @@ -1,6 +1,6 @@ # 货代发货通知 — 全门禁中断恢复阶段验收报告 -> **基线日期**:2026-08-01(第五次评审修复后) +> **基线日期**:2026-08-09(MVP Todo 1–20 最终代码验收) > **契约**:[`process-gate-recovery-contract.md`](./process-gate-recovery-contract.md) > **技术手册**:[`technical.md`](./technical.md) @@ -10,18 +10,22 @@ | 阶段 | 目标 | 结论 | | --- | --- | --- | -| Phase 1.5–6 | 契约 / 模型 / 服务 / API / UI 卡片 | **代码与定向测通过** | -| Phase 7 | 故障注入、环境变量、healthcheck、验收证据 | **部分通过**(缺生产双 Worker 强杀演练与人工签署) | +| P0–P4 | 契约 / 模型 / 服务 / API / Projection / UI | **代码与定向测通过** | +| P5 | 测试、文档、迁移和发布资料 | **代码资料通过;外部实机项待签署** | **发布边界**:人工实机 / 生产演练未签前,**不得宣称生产可发布闭环**。 -仍待人工签署: +仍待人工签署或环境执行: - 生产双 Worker 强杀现场演练 - Dify 平台配置确认 - 管理端 768px / 真实阻断卡 / 409 刷新视觉验收 - 完整前端 E2E 与生产构建签字 +本轮新增的 Dify 核对清单见 [`dify-manual-configuration.md`](./dify-manual-configuration.md),不代表已替管理员完成平台配置。 + +本轮后续审计补强:正式库存文件保存 `file_sha256`,快照复用统一校验仓库/配置/文件/解析器/映射版本;字段映射恢复不会创建新的库存准备轮次,RecoveryPlan 随 Attempt 结果收口。 + --- ## 2. 针对最新评审缺陷的修复摘要 diff --git a/docs/features/shipping-notice/process-gate-recovery-contract.md b/docs/features/shipping-notice/process-gate-recovery-contract.md index caf480f8..1154c710 100644 --- a/docs/features/shipping-notice/process-gate-recovery-contract.md +++ b/docs/features/shipping-notice/process-gate-recovery-contract.md @@ -7,7 +7,15 @@ > **2026-08 增补**:业务人工 Gate vs 技术自动 Gate;业务用户不可见技术重试动作;建单前统一恢复协调器;行级先行履约规则(见 demand/tec)。 > **2026-08-04 增补(多 EML / 直接 PDF)**:Gate 恢复对象将扩展为 `order_intake` / `order_task` 工作项(见 technical.md §1.6.2)。直接 PDF 解析失败走 Document/Layout Gate,不进入邮件裁决 Gate;EML 内关键字段 PDF 冲突可投影为 `field_conflict_resolution` 阻断。本文件门禁编码表暂不增删;阶段 4 接线时同步 `process_gate_bridge`。 -契约版本:`shipping-process-gate-v1` +契约版本:`shipping-process-gate-v2` + +### Gate 实施状态(v2) + +运行时由 `PROCESS_GATE_DEFINITIONS[].implementation_status` 下发,前端不得自行推导: + +- Gate 1–9:`supported`,已有文档/解析/订单裁决适配器或人工导航入口; +- Gate 10–20:`implemented`,库存与履约恢复闭环已接线; +- `adapter_required` / `blocked`:保留为显式未放行状态,当前 20 Gate 不使用。 --- diff --git a/docs/features/shipping-notice/process-gate-recovery-final-compliance.md b/docs/features/shipping-notice/process-gate-recovery-final-compliance.md new file mode 100644 index 00000000..92c03434 --- /dev/null +++ b/docs/features/shipping-notice/process-gate-recovery-final-compliance.md @@ -0,0 +1,78 @@ +# 货代发货通知正式 20-Gate MVP — 最终阶段验收合规报告 + +> 验收日期:2026-08-11 +> 范围:正式 20-Gate 单轨、库存准备/回调谱系、恢复、Projection 与前端;Dify 平台配置不在 Agent 操作范围内。 + +## 1. 阶段门禁结论 + +| 阶段 | 关键输出 | Review 结论 | +| --- | --- | --- | +| P0 正式单轨 | 新任务只创建正式 Execution;提交创建 `GateAttempt → SHIPPING_PROCESS_GATE Job`;APX 仅历史只读 | 通过自动化合同与正式库只读清点 | +| P1 准备/RPA 谱系 | PreparationAttempt/SourceAttempt 关联 GateAttempt、CandidateSet 与 RPA Attempt;单源/批量强制 v2 | 通过定向合同 | +| P2 恢复/失效 | RecoveryPlan 错误码顺序、技术重试与业务恢复分层、候选重冻结下游失效 | 通过定向合同 | +| P3 Projection/前端 | 四个库存里程碑仅为 Projection facts;前端主状态和动作由 Projection 下发 | 通过单元测试与生产构建 | +| P4 发布边界 | 自动上传关闭;Excel 成功后等待人工上传回执;Dify 保持只读建议 | 代码和配置检查通过;外部实机验收未完成 | + +## 1.1 分阶段 Review 记录 + +每一阶段均先完成目标、节点和验收核对,再进入下一阶段: + +| 阶段 | 阶段目标 | 关键节点 Review | 验收标准结论 | +| --- | --- | --- | --- | +| 阶段 1 | 正式 Execution 起始 Gate 与 RPA v2 门禁 | 起始 Gate 按数据库事实计算;缺身份不启动 Worker;legacy Trigger fail-closed | 通过:51 项核心合同测试全绿 | +| 阶段 2 | Attempt/候选版本/导出与上传血缘 | GateAttempt、PreparationAttempt、SourceAttempt、RPA Attempt 关联;重冻结失效下游 | 通过:恢复、重冻结、上传合同全绿 | +| 阶段 3 | Recovery 与入口收口 | 错误码顺序;旧 API 仅转发;技术重试与业务恢复分层 | 通过:Gate Contract/API/Service 组合测试全绿 | +| 阶段 4 | Projection 与前端单一读源 | 里程碑只作为 facts;主动作由 Projection 下发;四语言类型归一化 | 通过:前端 102 文件 / 548 测试及 build 全绿 | +| 阶段 5 | 发布候选与外部验收边界 | APX 数据清点;自动上传关闭;Dify 只读配置说明;真实样本清单 | 条件通过:外部 RPA、真实样本、Dify 手工签署待完成 | + +订单抽取/Schema 历史测试中发现的 5 个 fixture/调用参数漂移已按当前契约修正;最新回归 13/13 通过。修复未放宽生产乐观锁,也未改变正式 Shipping 状态机。 + +## 2. 当前自动化与数据库证据 + +- 本轮新增回归:`7 passed`,覆盖单源/批量 callback 身份错配 fail-closed、连字符 task_no 的 PSR run_no 解析、正式 Gate→Preparation/Source lineage、起始 Gate 客户/字段冲突事实及候选重冻结终止旧 GateAttempt/Job。合并聚焦集为 `126 passed, 1 skipped, 3 failed`;失败集中在既有 `test_shipping_process_gate_lease.py` 夹具 `_seed_workflow_version()` 返回空对象,需单独修复测试环境/夹具后再宣称全绿。 +- 订单抽取与 Schema 历史回归:`13 passed`。 +- 前端最终全量:`102 test files passed, 549 tests passed`;`npm run build` 通过;Chat 旧 `match_inventory`/`generate_excel` 动作已改为只刷新 Projection,不再创建 legacy Turn。 +- 迁移:代码唯一 head 与 PostgreSQL current 均为 `ha7i8j9k0l1m`;新增 Attempt 谱系表/字段已在当前验证环境生效。 +- APX 生产库只读清点本轮未能重新执行:当前本地环境 `SQLALCHEMY_DATABASE_URI=sqlite:///:memory:` 且未迁移 `shipping_process_executions/jobs` 表,不能据此声称 APX active/queued/running 为零。目标环境仍必须执行第 6 节 SQL,并将结果留档;未完成前保持真实用户 MVP No-Go。 +- 自动上传:`SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false`;启动日志确认 fail-closed 跳过货代上传就绪处理。 +- `git diff --check`:无 whitespace error;仅有工作区 LF/CRLF 提示。 + +顶层后端首批横向测试未通过,原因是该批测试混用共享 PostgreSQL 与 SQLite 初始化路径:管理员夹具重复插入 `admin@example.com`,触发权限相关连锁失败。该结果不作为 Shipping 回归失败,也未为掩盖环境污染而修改管理员业务逻辑。 + +## 3. 受控演练覆盖 + +| 场景 | 自动化证据 | 外部实机证据 | +| --- | --- | --- | +| 单源/多源库存准备与 v2 回调 | 通过 | 未执行 | +| 失败重试、迟到/重复 callback、取消后 callback | 通过 | 未执行 | +| 候选重冻结、Artifact/UploadAttempt 失效 | 通过 | 未执行 | +| 短缺、冲突、Excel 失败、人工上传回执 | 已有合同覆盖 | 未执行 | +| Worker 重启/接管 | 已有故障注入合同 | 未执行 | + +自动化演练不等同于真实货代站点操作;本轮没有启用自动上传,也没有操作外部货代生产站点。 + +## 4. Dify 手工验收 + +管理员仍须手工留存 Chatflow 版本、截图和运行记录,并确认: + +- CHAT 与 REVIEW 分支隔离;输入仅来自 HXOPS 已选择且脱敏的上下文; +- 输出仅为建议/解释,不写订单、库存、CandidateSet、Gate、Attempt、Excel、上传回执或审计事实; +- 推进、重试、恢复仅由 HXOPS 正式 Gate Action/Worker Callback 触发; +- Dify 不可用时人工复核仍能继续,且不会把自然语言输出当作业务状态。 + +## 5. Go / No-Go + +- 代码与受控自动化候选:**CONDITIONAL GO**(本轮新增合同通过,但聚焦集仍有 3 个既有 lease 夹具失败)。 +- 目标环境部署:**CONDITIONAL NO-GO**,必须先完成正式库迁移与 APX active/queued/running 只读清点。 +- 真实用户 MVP:**NO-GO**。阻断项为数据库清点缺证、lease 夹具失败、真实单源/多源样本、外部 Worker/RPA 重启接管、迟到/重复回调、短缺/冲突、人工上传回执演练,以及 Dify 管理员手工验收和 QA 签署。 + +## 6. 迁移与只读核对命令 + +```powershell +cd D:\Workspace\HxProjects\hxops\backend +$env:FLASK_APP='run.py' +flask db heads +flask db current +``` + +代码预期唯一 head:`ha7i8j9k0l1m`;目标环境 current 必须为该值。外部 Oracle Client、Windows Worker 能力与货代站点连通性必须在目标环境单独验收,不能由本地自动化替代。 diff --git a/docs/features/shipping-notice/review-workbench-layout-plan.md b/docs/features/shipping-notice/review-workbench-layout-plan.md index f7d5f17a..a7e2c063 100644 --- a/docs/features/shipping-notice/review-workbench-layout-plan.md +++ b/docs/features/shipping-notice/review-workbench-layout-plan.md @@ -258,7 +258,7 @@ Task 工作台 = 非主界面,仅保留备用深链 - [x] 失败优先在对话侧展示 RecoveryCard(侧栏 Item + 详情抽屉) - [x] 重新执行 / 人工接管走正式 Workspace API + 幂等键 + 版本锁 -- [x] 技术自动重试上限 3(`SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES`) +- [x] Gate 失败不自动重试,保留用户显式恢复入口 - [x] 尝试次数可在卡片查看;完整审计可展开 - [x] 复杂回退不得绕过后端状态机(客户端禁止提交目标状态) diff --git a/docs/features/shipping-notice/shipping-notice-auto-progress-mvp.md b/docs/features/shipping-notice/shipping-notice-auto-progress-mvp.md index 1fcfe776..14575b21 100644 --- a/docs/features/shipping-notice/shipping-notice-auto-progress-mvp.md +++ b/docs/features/shipping-notice/shipping-notice-auto-progress-mvp.md @@ -6,6 +6,22 @@ ## 1. MVP 目标与边界 +### 1.0 运行时单轨与历史兼容 + +正式 20-Gate Execution 是新任务唯一运行时状态机: + +```text +确认 / 解析完成 / 重试 / RPA 回调 +→ submit_auto_progress() +→ 正式 Execution / GateAttempt +→ shipping_process_gate Job +→ Gate Executor +→ 下一 Gate +→ ShippingProcessingProjection +``` + +APX 六 Gate 仅作为历史数据只读兼容:禁止新建、禁止领取或执行 APX Job、禁止创建恢复动作和下游业务事实。历史 APX 记录保留用于审计;迁移前不得物理删除表或记录。开放用户测试前须核对数据库中不存在 `active`、`queued` 或 `running` 的 APX Execution/Job;残留记录必须先迁移到正式 Execution 或人工关闭,并留存迁移审计。 + ### 1.1 目标主链路 ```text @@ -266,6 +282,23 @@ SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED=false ## 10. 验收与 Go/No-Go +### 10.0 Dify 手工配置边界 + +Dify 由管理员手工配置和发布,代码阶段不调用 Dify 管理 API。Chatflow 只承担只读对话和人工复核的最小证据建议: + +- 输入必须来自 HXOPS 已选择并脱敏的上下文; +- 输出只能是建议/解释,不得写入订单、库存、候选冻结、Gate、Attempt、Excel、上传回执或审计事实; +- 任何推进、重试、恢复和回调均由 HXOPS `submit_auto_progress()`、正式 Gate Action 或 Worker 回调触发; +- 前端、任务中心和 Chatflow 查询只消费 `ShippingProcessingProjection`,不得从 Dify 节点名称或自然语言推导业务状态。 + +管理员手工验收时至少确认:CHAT 与 REVIEW 分支隔离、输出字段合同与后端版本一致、失败分支 fail-closed、未配置或不可用时人工复核仍可继续。验收截图、发布版本和运行记录由管理员留档。 + +### 10.1 恢复事实补充 + +- 跨阶段库存恢复的正式链路为 `RecoveryPlan → Gate Attempt → Job → Worker/RPA → 幂等回调 → AutoProgress → Projection`。 +- `retry_inventory_from_preparation` 才会创建新的准备轮次;`retry_inventory_from_field_mapping` 只使当前 Mapping/匹配下游失效并重新执行字段映射。 +- 快照复用必须同时通过 source/warehouse/config/file hash/parser/mapping/candidate 指纹校验;任一字段缺失或不一致即 fail-closed。 + ### 必须通过 - 多候选库存源允许自动建单; @@ -301,4 +334,3 @@ Projection 缺少当前 Gate 或多源准备事实 - [门禁恢复契约](process-gate-recovery-contract.md) - [门禁恢复验收](process-gate-recovery-acceptance.md) - [复核工作台布局方案](review-workbench-layout-plan.md) - diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 9e2b455f..8cc76b57 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -2437,7 +2437,7 @@ Task 工作台 = 非主界面,仅保留备用深链 - **我的待办**:跨会话聚合待复核 / 异常 / 待人工上传;徽标与列表同源后端 `todo_category`;打开后深链进入复核或对话聚焦,**不以 Task 工作台为默认主区**。 - 服务端状态机(含 `checkpoint_kind`)、审计与乐观锁是唯一裁决;Chat Turn 履约写路径标记废弃,逐步拆除。 - 对话侧所有写操作必须带 `request_id` / 幂等键并写入审计;自动推进节点顺序与重试上限由后端固定,前端只展示投影。 -- **阶段 5(Process Gate 对话化)**:`ProcessGateRecoveryCard` 复用于侧栏 Item、详情抽屉与复核入口;恢复动作走 Workspace API;技术自动重试上限 `SHIPPING_PROCESS_GATE_TECHNICAL_RETRIES=3`;对话恢复额外写 `chat_process_gate_*`。 +- **阶段 5(Process Gate 对话化)**:`ProcessGateRecoveryCard` 复用于侧栏 Item、详情抽屉与复核入口;恢复动作走 Workspace API;Gate 失败不自动重试,需用户显式触发恢复;对话恢复额外写 `chat_process_gate_*`。 - **阶段 6(审计闭环)**:`progress_audit_contract` 冻结 `CHAT_WORKBENCH_*` / `CANDIDATE_QUALIFICATION_*` / `WORKFLOW_NODE_*`;审计中心支持事件分组与 Candidate / Gate 筛选;敏感快照仍需 `shipping_notice.audit_sensitive_read`。 - **自动建单安全**:分类置信度与 LLM 字段置信度缺失 fail-closed;阈值来源写入 `confidence_policy`(schema / key_field / default_fallback)。 - **货代上传**:`SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED` 默认 `false`(须显式开启);开启时启动/触发前校验 Worker(`freight_upload`)、凭据、共享目录与环境隔离。RPA 进行中投影 `display_lifecycle_status=upload_rpa_pending` 且 `is_waiting_manual_upload=false`,不得仅凭 lifecycle 显示为待人工上传。 diff --git a/docs/funclist.md b/docs/funclist.md index 187f39cd..2cdeefc1 100644 --- a/docs/funclist.md +++ b/docs/funclist.md @@ -98,7 +98,7 @@ | **双工作台审计闭环** | 已实现(阶段 6) | 事件字典冻结 chat_* / review_* / process_gate_* / qualification / workflow_node;对话恢复写 `chat_process_gate_*`;审计中心分组与 Candidate/Gate 筛选;普通账本脱敏 + 敏感快照独立鉴权;覆盖率举证见 AUDIT_COVERAGE_MATRIX。 | | **复核字段精确高亮(阶段 0–5)** | 已完成(盲测样本集另立) | 冻结 `shipping-field-highlight-v1`;原生唯一 glyph / OCR candidate / Cell 来源分级;证据 API 全量 `highlight_quality`;工作台 verified 实线 / candidate 虚线;坐标诊断与 list/focus/restore/version 审计齐全;`review_coordinate_corrected` 事件已冻结(人工改框写路径待模板标注扩展)。权威契约:[field-highlight-contract.md](features/shipping-notice/field-highlight-contract.md)。 | | **STP 直通 + 例外工作台** | 已实现(首期) | 可信 PDF 自动建 Task 并推进至「待人工上传」;例外进入人工复核/任务处理;Chat 仅上传与通知。**阶段 0–5 已落地**:字段契约、起行锚点、建单资格与候选、自动建单/复核台、跨候选库存匹配→Excel→待人工上传、统一 `ui_state.stp_facts` 与审计双写/时间线 i18n。**项次派生 Phase 0–4**:`line_no`=内部项次、`export_sequence`=导出行号、Schema 派生模拟、运行时派生审计、复核覆盖锁定与 `field_meta` 投影、冻结血缘。**库存源路由独立恢复(门禁恢复阶段 0)**:复核台可按最新已发布规则与库存源启停重算路由(不重识别 PDF);人工决定优先且不被静默覆盖;支持采用规则建议 / 保留人工结果;幂等键与审计前后快照齐全。首期不触发货代 RPA 上传、不改 Dify | -| **全门禁级中断恢复(契约冻结)** | 已实现(Phase 1.5–6 自动化;Phase 7 部分) | **代码与定向自动化已落地**:契约/模型/迁移;领域服务与接线;Job 租约/心跳/Worker(跨 Job 累计技术重试 + 耗尽收口);Workspace/Admin API;三入口恢复卡(责任方+审计);Admin 主从诊断;Execution 存在时旧恢复 `action_buttons` 清零;异常脱敏;healthcheck 探针领取。权威契约:[process-gate-recovery-contract.md](features/shipping-notice/process-gate-recovery-contract.md);验收:[process-gate-recovery-acceptance.md](features/shipping-notice/process-gate-recovery-acceptance.md)。**Phase 7 未闭环**:生产双 Worker 演练、真实阻断视觉/E2E、人工签署。不引入 Temporal/Celery。 | +| **全门禁级中断恢复(契约冻结)** | 已实现(P0–P4 代码与自动化;P5 外部条件待签署) | **RecoveryPlan → Attempt → Job → Worker/RPA → 幂等回调 → AutoProgress → Projection** 已收口;20 Gate 均有运行时实施状态,跨阶段恢复、精确失效、多源库存准备、组合指纹、未知上传状态和前端 `recovery_targets` 已覆盖。权威契约:[process-gate-recovery-contract.md](features/shipping-notice/process-gate-recovery-contract.md);验收:[process-gate-recovery-acceptance.md](features/shipping-notice/process-gate-recovery-acceptance.md);最终报告:[process-gate-recovery-final-compliance.md](features/shipping-notice/process-gate-recovery-final-compliance.md)。生产双 Worker、真实 RPA、Dify 手工核对、视觉/E2E 与人工签署仍为发布前条件;不引入 Temporal/Celery。 | | **错误可解释性(阶段 0–4)** | 完全达标 | 分层原因码冻结且主路径全量 EMITTED(仅预留 `inventory_uom_conversion_failed`);`AUDIT_COVERAGE_MATRIX` 统一覆盖率 100%;审计中心业务/技术分层且无强制横滚;库存源复核始终展示 `source_code`;四语言对齐。权威契约:[error-explainability-contract.md](features/shipping-notice/error-explainability-contract.md)。 | | **订单项次派生与血缘审计** | 已实现(Phase 0–4 + 评审纠偏) | 统一 `customer_po_line_no` / `line_no` / `export_sequence`;Schema 派生模拟支持历史 Extraction 样本;运行时派生含 `evidence_refs`;复核覆盖/恢复(`LINE_NO_OVERRIDDEN`/`LINE_NO_RESTORED`);货代统一审计新写入永久保留(`6a9c3e5f7b2d`) | | 模板发布与自动冻结资格分离(阶段 4) | 已实现 | Profile 的发布仅允许确定性解析;每个发布版本独立冻结人工确认资格,首版强制 `manual_confirmation` 且自动冻结关闭,盲测批准、旧版本资格或 checksum 变化均不能越过该门禁 | diff --git a/docs/tec.md b/docs/tec.md index f6e5f3b8..68bf048a 100644 --- a/docs/tec.md +++ b/docs/tec.md @@ -1380,3 +1380,6 @@ Dify Profile 保存时由服务端根据当前 XFA 分析将 `source_path_id` 重写为受控 `source_data_path`,再以权威明细集合路径推导 Header/Line 作用域。Header 规则执行一次并写入 `header_fields`;Line 规则继续在每条权威明细上执行。客户端提交的路径不作为正式提取真值。 规则内容指纹排除 `handling` / `target_field_id` / `target_field_code`,使 Schema 映射维护不影响已确认的提取流水线。管理端 DTO 当前返回完整字段值;AcroForm 和明细金额失败摘要返回具体字段、行号与两侧值或计算操作数。 +### 2026-08-09 全门禁恢复 MVP 技术收口 + +RecoveryPlan → Gate Attempt → Job → Worker/RPA → 幂等回调 → `run_task_auto_progress()` → Projection 为统一执行链。服务端输出 `recovery_targets` 与 Gate `implementation_status`,前端不自行推导恢复节点。Dify 不写入库存、订单、Excel、RPA 或上传事实。 diff --git a/frontend/src/features/admin/constants/modules.ts b/frontend/src/features/admin/constants/modules.ts index fe645edf..4946c492 100644 --- a/frontend/src/features/admin/constants/modules.ts +++ b/frontend/src/features/admin/constants/modules.ts @@ -77,7 +77,6 @@ export const SHIPPING_CONFIG_SUB_MODULE_METAS: ShippingConfigSubModuleMeta[] = [ { id: 'shipping_templates', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.excelTemplates', groupKey: 'admin.nav.shippingInventoryManagement', query: { section: 'templates' } }, { id: 'shipping_audit', routeName: 'AdminShippingAudit', path: 'shipping-audit', labelKey: 'admin.nav.shippingAudit', groupKey: 'admin.nav.shippingRunAudit' }, { id: 'process_gates', routeName: 'AdminShippingProcessGates', path: 'shipping-process-gates', labelKey: 'admin.nav.shippingProcessGates', groupKey: 'admin.nav.shippingRunAudit' }, - { id: 'legacy_stp_jobs', routeName: 'AdminShippingLegacyStpJobs', path: 'shipping-legacy-stp-jobs', labelKey: 'admin.nav.shippingLegacyStpJobs', groupKey: 'admin.nav.shippingRunAudit' }, { id: 'inventory_snapshots', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.snapshots', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'snapshots' } }, { id: 'export_records', routeName: 'AdminShippingInventory', path: 'shipping-notice', labelKey: 'admin.shippingInventory.exports', groupKey: 'admin.nav.shippingRunAudit', query: { section: 'exports' } }, ]; diff --git a/frontend/src/features/chat/api/shipping.api.legacy-entrypoints.spec.ts b/frontend/src/features/chat/api/shipping.api.legacy-entrypoints.spec.ts new file mode 100644 index 00000000..9bc66653 --- /dev/null +++ b/frontend/src/features/chat/api/shipping.api.legacy-entrypoints.spec.ts @@ -0,0 +1,15 @@ +/** + * features/chat/api/shipping.api.legacy-entrypoints.spec.ts + * 用途:锁定 Shipping 前端 API 不再暴露直接匹配/导出业务入口。 + * 依赖:shipping.api 的模块导出。 + * 逻辑:正式业务动作只能由 Projection + Process Gate Action 驱动;旧函数名不得重新被页面调用。 + */ +import * as shippingApi from './shipping.api'; +import { describe, expect, it } from 'vitest'; + +describe('shipping API runtime entrypoints', () => { + it('does not expose direct inventory match or Excel generation actions', () => { + expect(Object.prototype.hasOwnProperty.call(shippingApi, 'matchWorkspaceShippingInventory')).toBe(false); + expect(Object.prototype.hasOwnProperty.call(shippingApi, 'generateWorkspaceShippingExcel')).toBe(false); + }); +}); diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index 025b39be..59239d34 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -463,6 +463,7 @@ export const retryWorkspaceConversationAutoProgress = ( retried: number; skipped: number; failed: number; + blocked?: number; }; items: Array<{ object_type: 'review_case' | 'formal_task' | string; @@ -1100,7 +1101,10 @@ export async function retryWorkspaceShippingTask(taskNo: string, comment?: strin * @param taskNo - 正式任务号 * @param lineKey - 行键 */ -export async function retryWorkspaceShippingTaskLine(taskNo: string, lineKey: string) { +export async function retryWorkspaceShippingTaskLine( + taskNo: string, + lineKey: string, +) { const body = await requestJson( `/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/lines/${encodeURIComponent(lineKey)}/retry`, jsonPost({ reason: 'user_retry_inventory' }), @@ -1311,23 +1315,6 @@ export async function removeWorkspaceShippingNoticeLine( return assertShippingOk(body); } -/** - * 执行库存匹配。 - * @param taskNo - 发货任务编号 - * @param ownership - 可选工作台归属上下文 - * @returns 匹配结果与后续动作提示 - */ -export async function matchWorkspaceShippingInventory( - taskNo: string, - ownership?: ShippingFulfillmentOwnershipContext | null, -) { - const body = await requestJson( - `/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/match-inventory`, - jsonPost(ownershipPayload(ownership)), - ); - return assertShippingOk(body); -} - /** * 上传当前任务使用的正式库存文件。 * @param taskNo - 发货任务编号 @@ -1346,6 +1333,8 @@ export async function uploadWorkspaceShippingInventory(taskNo: string, file: Fil /** * 以用户态触发自动推进,作为聊天前端兜底入口。 + * @deprecated 新业务组件必须通过 Projection 的 primary_action 调用正式 Gate Action, + * 成功后重新读取 Projection;本函数仅保留给历史调用方兼容。 * @param taskNo - 发货任务编号 * @param lang - 可选语言代码 * @returns 自动推进结果 @@ -1392,23 +1381,6 @@ export async function retryWorkspaceShippingUpload( return assertShippingOk(body); } -/** - * 生成发货 Excel。 - * @param taskNo - 发货任务编号 - * @param ownership - 可选工作台归属上下文 - * @returns 生成结果,成功时通常会包含下载链接 - */ -export async function generateWorkspaceShippingExcel( - taskNo: string, - ownership?: ShippingFulfillmentOwnershipContext | null, -) { - const body = await requestJson( - `/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/generate-excel`, - jsonPost(ownershipPayload(ownership)), - ); - return assertShippingOk(body); -} - /** 发货通知 Agent 应用类型标识(运行时识别)。 */ export const SHIPPING_NOTICE_AGENT_CODE = 'shipping_notice'; diff --git a/frontend/src/features/chat/components/shipping-review/ReviewConversationRetryDrawer.vue b/frontend/src/features/chat/components/shipping-review/ReviewConversationRetryDrawer.vue new file mode 100644 index 00000000..ad3c3fd8 --- /dev/null +++ b/frontend/src/features/chat/components/shipping-review/ReviewConversationRetryDrawer.vue @@ -0,0 +1,87 @@ + + + + diff --git a/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue b/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue index 10427ebb..3ad997bb 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewCurrentProcessingCard.vue @@ -105,8 +105,23 @@ const statusLabel = computed(() => { * 下一步(「下一步」section 的问题/说明文案):优先展示 blocking_reason,否则按 user_status 给系统态文案。 */ const nextStepText = computed(() => { + const safeMessage = (value: unknown): string => { + const raw = String(value || '').trim(); + const lowered = raw.toLowerCase(); + if (!raw) return ''; + if ( + lowered.includes('cannot import name') + || lowered.includes('traceback') + || lowered.includes('site-packages') + || lowered.includes('\\app\\') + || lowered.includes('/app/') + ) { + return t('chat.shippingOrderReview.currentTask.nextStepFailedNoRetry'); + } + return raw; + }; if (props.loading) { - return String(props.automation?.message || '').trim() || t('chat.shippingOrderReview.currentTask.nextStepRunning'); + return safeMessage(props.automation?.message) || t('chat.shippingOrderReview.currentTask.nextStepRunning'); } // 1) blocking_reason → 用后端给的 i18n_key 渲染具体阻断 const br = props.blockingReason; @@ -116,7 +131,7 @@ const nextStepText = computed(() => { return t(i18nKey); } // i18n 键缺失时回落为 code(不裸露给普通用户,最终 QA 期间应全部补齐) - return String(br.code || '').trim() || t('chat.shippingOrderReview.currentTask.nextStepUnknown'); + return safeMessage(br.code) || t('chat.shippingOrderReview.currentTask.nextStepUnknown'); } // 2) 无阻断时,按 user_status 给系统说明文案 const s = String(props.userStatus || '').trim() as ReviewCurrentUserStatus | ''; @@ -141,6 +156,12 @@ const nextStepText = computed(() => { return t('chat.shippingOrderReview.currentTask.nextStepUnknown'); }); +/** 已完成/已取消时没有后续业务动作,不渲染“下一步”区,避免制造未完成错觉。 */ +const showNextStep = computed(() => { + const status = String(props.userStatus || '').trim().toLowerCase(); + return !['completed', 'cancelled'].includes(status); +}); + /** * 业务动作按钮:后端确认 retryable=true → 主按钮为「重试」; * 否则若 primary_action.code 非 retry → 用 primary_action.code + i18n_key 渲染对应人工动作(进入复核/确认客户等)。 @@ -301,6 +322,7 @@ type ReviewCurrentUserStatus =
diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLineFulfillmentDetail.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewLineFulfillmentDetail.spec.ts index 0a0b5cd1..a59f78f2 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLineFulfillmentDetail.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewLineFulfillmentDetail.spec.ts @@ -21,6 +21,13 @@ const i18n = createI18n({ wave: '履约波次', task: '正式任务', snapshotId: '库存快照 ID', + inventorySource: '实际库存源', + inventoryFile: '库存文件编号', + inventoryFileSha256: '库存文件 SHA-256', + inventoryRow: '库存行号', + requiredQty: '需求数量', + availableQty: '可用数量', + matchAttempt: '匹配 Attempt', matchedAt: '匹配校验时间', decisionSource: '决定来源', decisionSourceValue: { @@ -45,6 +52,13 @@ describe('ReviewLineFulfillmentDetail', () => { line_key: 'L1', inventory_snapshot_id: 42, inventory_checked_at: '2026-08-07T01:00:00Z', + inventory_source_code: 'DBS_DUB', + inventory_file_no: 'INV-001', + inventory_file_sha256: 'a'.repeat(64), + inventory_row_index: 17, + required_qty: '3', + available_qty: '8', + match_attempt_id: 301, decision_source: 'system', auto_fulfill_error_message: 'wave_explode', decision: { @@ -62,6 +76,13 @@ describe('ReviewLineFulfillmentDetail', () => { expect(wrapper.find('[data-testid="review-line-fulfillment-field-wave"]').text()).toContain('3'); expect(wrapper.find('[data-testid="review-line-fulfillment-field-task"]').text()).toContain('SN-100'); expect(wrapper.find('[data-testid="review-line-fulfillment-field-snapshot"]').text()).toContain('42'); + expect(wrapper.find('[data-testid="review-line-fulfillment-field-inventorySource"]').text()).toContain('DBS_DUB'); + expect(wrapper.find('[data-testid="review-line-fulfillment-field-inventoryFile"]').text()).toContain('INV-001'); + expect(wrapper.find('[data-testid="review-line-fulfillment-field-inventoryFileSha256"]').text()).toContain('a'.repeat(64)); + expect(wrapper.find('[data-testid="review-line-fulfillment-field-inventoryRow"]').text()).toContain('17'); + expect(wrapper.find('[data-testid="review-line-fulfillment-field-requiredQty"]').text()).toContain('3'); + expect(wrapper.find('[data-testid="review-line-fulfillment-field-availableQty"]').text()).toContain('8'); + expect(wrapper.find('[data-testid="review-line-fulfillment-field-matchAttempt"]').text()).toContain('301'); expect(wrapper.find('[data-testid="review-line-fulfillment-field-decisionSource"]').text()).toContain('系统自动'); expect(wrapper.find('[data-testid="review-line-fulfillment-field-failure"]').text()).toContain('wave_explode'); diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLineFulfillmentDetail.vue b/frontend/src/features/chat/components/shipping-review/ReviewLineFulfillmentDetail.vue index 9fdd89d2..1e4e617d 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLineFulfillmentDetail.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewLineFulfillmentDetail.vue @@ -54,6 +54,41 @@ const rows = computed(() => { label: t('chat.shippingOrderReview.lineFulfillmentDetail.snapshotId'), value: line?.inventory_snapshot_id != null ? String(line.inventory_snapshot_id) : '—', }, + { + key: 'inventorySource', + label: t('chat.shippingOrderReview.lineFulfillmentDetail.inventorySource'), + value: String(line?.inventory_source_code || line?.inventory_source?.code || '').trim() || '—', + }, + { + key: 'inventoryFile', + label: t('chat.shippingOrderReview.lineFulfillmentDetail.inventoryFile'), + value: String(line?.inventory_file_no || '').trim() || '—', + }, + { + key: 'inventoryFileSha256', + label: t('chat.shippingOrderReview.lineFulfillmentDetail.inventoryFileSha256'), + value: String(line?.inventory_file_sha256 || '').trim() || '—', + }, + { + key: 'inventoryRow', + label: t('chat.shippingOrderReview.lineFulfillmentDetail.inventoryRow'), + value: line?.inventory_row_index != null ? String(line.inventory_row_index) : '—', + }, + { + key: 'requiredQty', + label: t('chat.shippingOrderReview.lineFulfillmentDetail.requiredQty'), + value: String(line?.required_qty || '').trim() || '—', + }, + { + key: 'availableQty', + label: t('chat.shippingOrderReview.lineFulfillmentDetail.availableQty'), + value: String(line?.available_qty || '').trim() || '—', + }, + { + key: 'matchAttempt', + label: t('chat.shippingOrderReview.lineFulfillmentDetail.matchAttempt'), + value: line?.match_attempt_id != null ? String(line.match_attempt_id) : '—', + }, { key: 'matchedAt', label: t('chat.shippingOrderReview.lineFulfillmentDetail.matchedAt'), diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts index 40c3af30..8dad1322 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts @@ -1,6 +1,6 @@ /** * features/chat/components/shipping-review/ReviewLineInventoryOps.spec.ts - * 用途:锁定行级只渲染统一「重试」与关闭;消费 retryable,不展示内部动作码。 + * 用途:锁定明细行不渲染库存重试,只保留行生命周期关闭动作。 */ import { afterEach, describe, expect, it } from 'vitest'; @@ -16,10 +16,7 @@ const i18n = createI18n({ 'zh-CN': { chat: { shippingOrderReview: { - lineOps: { - retry: '重试', - moreActions: '更多操作', - }, + lineOps: { moreActions: '更多操作' }, fulfillmentDecision: { closeLine: '关闭该明细', }, @@ -46,18 +43,16 @@ afterEach(() => { }); describe('ReviewLineInventoryOps', () => { - it('shows unified retry when retryable', async () => { + it('does not show generic retry even when retryable', async () => { const wrapper = mountOps({ retryable: true, line_allowed_actions: [], }); - expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(true); - await wrapper.get('[data-testid="review-line-retry"]').trigger('click'); - expect(wrapper.emitted('retry-line')?.length).toBe(1); + expect(wrapper.find('[data-testid="review-line-retry"]').exists()).toBe(false); wrapper.unmount(); }); - it('hides retry when not retryable even if internal actions present', () => { + it('keeps inventory actions out of the line even when present', () => { const wrapper = mountOps({ retryable: false, inventory_allowed_actions: ['retry_inventory_preparation', 'retry_inventory_matching'], @@ -68,7 +63,7 @@ describe('ReviewLineInventoryOps', () => { wrapper.unmount(); }); - it('disables retry while task running', () => { + it('does not add a retry while task running', () => { const wrapper = mountOps({ retryable: true, line_allowed_actions: [], diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.vue b/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.vue index d1a6f6ea..d9d60428 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewLineInventoryOps.vue @@ -1,13 +1,13 @@ diff --git a/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts b/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts index 76cde2b6..e723d9a3 100644 --- a/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts +++ b/frontend/src/features/shipping-process-gates/composables/useShippingProcessGateRecovery.ts @@ -10,7 +10,10 @@ import { useI18n } from 'vue-i18n'; import { useRouter } from 'vue-router'; import { BusinessError, resolveLocalizedErrorMessage } from '@/shared/api/client'; import { useMessage } from '@/shared/composables/useMessage'; -import { postWorkspaceProcessGateAction } from '../api/process-gates.api'; +import { + getWorkspaceProcessExecution, + postWorkspaceProcessGateAction, +} from '../api/process-gates.api'; import type { ShippingProcessGateActionCode, ShippingProcessGateUserSummary, @@ -44,6 +47,47 @@ function newIdempotencyKey(): string { return `pg-${Date.now()}-${Math.random().toString(16).slice(2)}`; } +const ATTEMPT_POLL_INTERVAL_MS = 800; +const ATTEMPT_POLL_LIMIT = 25; +const ATTEMPT_TERMINAL_STATUSES = new Set(['succeeded', 'failed', 'cancelled', 'superseded']); + +/** 等待异步 Gate Attempt 进入终态,避免 Worker 完成前刷新到旧 Case 投影。 */ +async function waitForAttemptTerminal( + executionNo: string, + submittedGateCode: string, + attemptId: number, +): Promise { + for (let index = 0; index < ATTEMPT_POLL_LIMIT; index += 1) { + const latest = await getWorkspaceProcessExecution(executionNo); + const gateAttempt = latest.current_blocking_gate?.latest_attempt as ( + { id?: number; status?: string } | null | undefined + ); + const latestAttemptId = Number(gateAttempt?.id || 0); + const latestAttemptStatus = String(gateAttempt?.status || '').trim().toLowerCase(); + if ( + (latestAttemptId === attemptId || latestAttemptId === 0) + && ATTEMPT_TERMINAL_STATUSES.has(latestAttemptStatus) + ) { + return; + } + const currentGateCode = String(latest.current_blocking_gate?.gate_code || '').trim(); + const executionStatus = String(latest.status || '').trim().toLowerCase(); + if ( + currentGateCode + && currentGateCode !== submittedGateCode + && !['pending', 'queued', 'running'].includes(executionStatus) + ) { + return; + } + if (!latest.current_blocking_gate && ['completed', 'cancelled'].includes( + executionStatus, + )) { + return; + } + await new Promise((resolve) => window.setTimeout(resolve, ATTEMPT_POLL_INTERVAL_MS)); + } +} + /** * 编排单次门禁恢复:导航类动作直接 router.push;其余 POST 到 Workspace API。 * @returns busy 状态与 submitPrimaryAction 方法 @@ -64,10 +108,20 @@ export function useShippingProcessGateRecovery() { options?: { payload?: Record; navigationContext?: ProcessGateNavigationContext; + /** 仅允许使用服务端 recovery_targets 下发的动作码覆盖主动作。 */ + actionCode?: ShippingProcessGateActionCode | string; }, ): Promise { const gate = summary.current_blocking_gate; - const actionCode = (summary.next_action_code || gate?.next_action_code || '') as ShippingProcessGateActionCode | ''; + const requestedAction = String(options?.actionCode || '').trim(); + const serverRecoveryAction = (summary.recovery_targets || []) + .find((target) => String(target.action_code || '').trim() === requestedAction) + ?.action_code; + if (requestedAction && !serverRecoveryAction) { + msg.warning(t('workspace.shippingNotice.processGate.noAction')); + return { outcome: 'noop' }; + } + const actionCode = (serverRecoveryAction || summary.next_action_code || gate?.next_action_code || '') as ShippingProcessGateActionCode | ''; if (!summary.execution_no || !gate?.gate_code || !actionCode) { msg.warning(t('workspace.shippingNotice.processGate.noAction')); return { outcome: 'noop' }; @@ -112,12 +166,36 @@ export function useShippingProcessGateRecovery() { } busy.value = true; try { - await postWorkspaceProcessGateAction(summary.execution_no, String(gate.gate_code), { + // 写入前重新读取服务端 Gate 版本,避免 Case 投影刷新稍慢时提交旧版本。 + // 动作归属仍由后端最终校验;若当前 Gate 已变化,不复用旧动作。 + let submitVersion = expectedVersion; + try { + const latest = await getWorkspaceProcessExecution(summary.execution_no); + const latestGate = latest.current_blocking_gate; + if (latestGate && String(latestGate.gate_code) === String(gate.gate_code)) { + const latestVersion = Number(latestGate.evaluation_version); + if (Number.isFinite(latestVersion) && latestVersion >= 1) submitVersion = latestVersion; + } + } catch { + // 读取失败时继续使用页面快照版本,让后端版本锁决定是否允许写入。 + } + const response = await postWorkspaceProcessGateAction(summary.execution_no, String(gate.gate_code), { action_code: actionCode, - expected_gate_version: expectedVersion, + expected_gate_version: submitVersion, idempotency_key: newIdempotencyKey(), payload: options?.payload, }); + if (response.dispatch === 'async_job' && Number(response.attempt?.id) > 0) { + try { + await waitForAttemptTerminal( + summary.execution_no, + String(gate.gate_code), + Number(response.attempt.id), + ); + } catch { + // 最终仍由父级刷新完整 Case;短暂轮询失败不得把已受理动作误报为执行失败。 + } + } msg.success(t('workspace.shippingNotice.processGate.actionSubmitted')); return { outcome: 'submitted' }; } catch (error: unknown) { @@ -126,10 +204,7 @@ export function useShippingProcessGateRecovery() { || error.status === 409 ); if (isVersionMismatch) { - msg.warning(resolveLocalizedErrorMessage( - 'SHIPPING.PROCESS_GATE_VERSION_MISMATCH', - error instanceof BusinessError ? error.message : undefined, - )); + // 409 是并发刷新信号,不是需要弹窗的业务失败;父级会重新拉取完整 Case。 return { outcome: 'refresh_needed' }; } const message = error instanceof BusinessError diff --git a/frontend/src/features/shipping-process-gates/types/process-gate.types.ts b/frontend/src/features/shipping-process-gates/types/process-gate.types.ts index 7e26a786..10037378 100644 --- a/frontend/src/features/shipping-process-gates/types/process-gate.types.ts +++ b/frontend/src/features/shipping-process-gates/types/process-gate.types.ts @@ -15,6 +15,7 @@ import type { ShippingProcessGateProjection, ShippingProcessGateStatus, ShippingProcessGateUserSummary, + ShippingProcessRecoveryTarget, } from '@/features/chat/types/shipping.api.types'; export type { @@ -26,6 +27,7 @@ export type { ShippingProcessGateProjection, ShippingProcessGateStatus, ShippingProcessGateUserSummary, + ShippingProcessRecoveryTarget, }; /** 门禁阻断原因详情(用户可见;details 仅业务事实)。 */ diff --git a/frontend/src/features/shipping-progress/actionPresentation.ts b/frontend/src/features/shipping-progress/actionPresentation.ts index 273ef93d..5264eaab 100644 --- a/frontend/src/features/shipping-progress/actionPresentation.ts +++ b/frontend/src/features/shipping-progress/actionPresentation.ts @@ -98,6 +98,8 @@ function toItem( const chatOrRight = surface === 'chat' || surface === 'right'; if (intent === 'open_order_review' && chatOrRight) { labelKey = 'chat.shippingProcessing.action.open_order_processing'; + } else if (normalized === 'retry_freight_upload_rpa' || normalized === 'retry_upload') { + labelKey = 'chat.shippingNoticeRetryUploadAction'; } else if (intent === 'retry' && chatOrRight) { labelKey = 'chat.shippingProcessing.action.retry_parse'; } else if (normalized === 'focus_task' && chatOrRight) { @@ -183,6 +185,8 @@ export function resolveProcessingActionPresentation( const code = String(raw || '').trim(); if (!code) return; const key = code.toLowerCase(); + // 仅用于管理员恢复缺失待办记录,不作为普通用户履约动作展示。 + if (key === 'regenerate_manual_upload_todo') return; if (seen.has(key)) return; seen.add(key); const intent = mapActionCodeToIntent(code); @@ -218,11 +222,31 @@ export function resolveProcessingActionPresentation( }; pushCode(projection.primaryAction?.code || projection.currentGate?.nextActionCode); + // Gate 20 同时保留两条用户路径:主动重试 RPA 与人工上传登记。 + // 该动作由正式任务面板打开登记弹窗,不走 Gate API。 + if ( + String(projection.currentGate?.gateCode || '').trim().toLowerCase() === 'manual_upload_handoff' + && items.some((item) => String(item.actionCode).toLowerCase() === 'retry_freight_upload_rpa') + ) { + pushCode('mark_manual_uploaded'); + } // [ORDER-STABLE] 对 availableActions 标准化(去重 + 字典序排序),确保后端返回顺序不影响前端按钮顺序。 const normalizedAvailableActions = normalizeActionCodes(projection.availableActions || []); for (const action of normalizedAvailableActions) { pushCode(action); } + // Gate 19 RPA 失败时,人工登记作为任务级替代路径展示,避免与 RPA 重试并列。 + if ( + String(projection.currentGate?.gateCode || '').trim().toLowerCase() === 'freight_upload_rpa' + && items.some((item) => String(item.actionCode).toLowerCase() === 'retry_freight_upload_rpa') + ) { + for (let index = items.length - 1; index >= 0; index -= 1) { + const code = String(items[index]?.actionCode || '').toLowerCase(); + if (code === 'mark_manual_uploaded' || code === 'open_manual_upload' || code === 'wait_manual_upload') { + items.splice(index, 1); + } + } + } if (items.length === 0 && (status === 'completed' || status === 'failed' || status === 'cancelled')) { pushCode('view_result'); diff --git a/frontend/src/features/shipping-progress/components/ReviewProgressStrip.vue b/frontend/src/features/shipping-progress/components/ReviewProgressStrip.vue index 9e0be455..e1c7823e 100644 --- a/frontend/src/features/shipping-progress/components/ReviewProgressStrip.vue +++ b/frontend/src/features/shipping-progress/components/ReviewProgressStrip.vue @@ -24,6 +24,7 @@ const props = defineProps<{ projection: ShippingProcessingProjection; /** 宿主轮询中提示(显示在标题行)。 */ polling?: boolean; + refreshing?: boolean; /** 正式 OT 已创建时保留 prop 兼容(进度条不再展示当前需要文案)。 */ hasFormalOt?: boolean; }>(); @@ -182,9 +183,10 @@ function nodeShortLabel(stage: string): string { type="button" class="rounded-lg border border-default bg-surface px-2.5 py-1 text-[11px] font-medium text-secondary hover:bg-surface-muted" data-testid="review-progress-refresh" + :disabled="refreshing" @click="emit('refresh')" > - {{ t('chat.shippingProcessing.action.refresh') }} + {{ refreshing ? t('chat.shippingOrderReview.workflowProgress.polling') : t('chat.shippingProcessing.action.refresh') }}