feat(shipping-notice): 优化货运订单履约流程与用户体验

- 优化聊天附件列表为横向可滚动布局并新增配套测试用例
- 移除自动填充默认用户消息逻辑,空备注时不再伪造默认正文
- 修复流程Gate动作展示逻辑,隐藏历史遗留操作与自动阶段无效按钮
- 完善库存匹配重试与订单快照冻结校验流程
- 优化进度展示优先级,优先显示人工待处理状态
- 移除Excel导出自动推导金额逻辑,强制使用Schema配置字段
- 新增货代通用报表RPA详细设计文档
- 更新相关测试用例与断言逻辑
This commit is contained in:
hugo committed 2026-08-13 00:17:01 +08:00
1 parent dc282f3b1d
commit 11cef575b4
51 files changed
+2197 -112

No files matched your search

@@ -172,12 +172,6 @@ def _mapping_value(
field_code = str(field.field_code or '') if field else '' 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: if value in (None, '') and field_code == 'line_no' and export_sequence is not None:
value = export_sequence 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: if value is None and mapping.get('row_mode') == 'line' and header_values is not None:
value = header_values.get(key) value = header_values.get(key)
elif kind == 'inventory_field': elif kind == 'inventory_field':
@@ -467,9 +461,6 @@ def generate_shipment_excel(task: ShippingNotice) -> tuple[str, str, ShippingExp
if line.id not in available_line_ids: if line.id not in available_line_ids:
continue continue
row = dict(values) row = dict(values)
row['__qty'] = line.qty
row['__unit_price'] = line.unit_price
row['__line_amount'] = line.amount
line_values.append(row) line_values.append(row)
for index, row in enumerate(line_values, start=1): for index, row in enumerate(line_values, start=1):
row['__export_sequence'] = index row['__export_sequence'] = index
@@ -1,5 +1,5 @@
""" """
services/shipping_notice/fulfillment_audit.py backend/app/services/shipping_notice/fulfillment_audit.py
用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。 用途:履约关键节点与敏感访问写入统一审计事件的轻量封装。
依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。 依赖:audit_service.append_shipping_audit_event、Flask g.request_id / request、AppError。
@@ -148,6 +148,49 @@ def record_fulfillment_audit(
) from exc ) from exc
def emit_stp_auto_create_blocked_manual_audit(
*,
case: Any | None,
job_id: int,
error_code: str,
next_action: str,
details: dict[str, Any] | None = None,
) -> None:
"""
记录 STP 自动建单业务阻断的人工处理审计事件。
核心逻辑:使用订单复核 Case 作为可选聚合,Job 作为稳定元数据引用;Worker 无请求上下文时仍可写入。
Args:
case: 可选 ShippingOrderReviewCase,优先提供 case_no;不得传入正文或凭据。
job_id: STP Job 主键。
error_code: 稳定业务阻断错误码。
next_action: 后续人工处理动作编码。
details: 脱敏诊断事实,仅允许审计元数据白名单字段。
Returns:
None。审计失败由 record_fulfillment_audit 按 strict 契约抛出。
"""
case_no = str(getattr(case, 'case_no', '') or '').strip() or None
metadata = {
'job_id': int(job_id),
'next_action': str(next_action or '').strip() or None,
**dict(details or {}),
}
record_fulfillment_audit(
event_type='stp_auto_create_blocked_manual',
aggregate_type='order_review_case' if case_no else 'shipping_job',
aggregate_id=case_no or str(job_id),
action='stp_auto_create_blocked_manual',
actor_type='worker',
task_no=case_no,
review_case_no=case_no,
reason_code=str(error_code or '').strip() or None,
error_code=str(error_code or '').strip() or None,
result='rejected',
metadata=metadata,
source='worker',
)
def record_access_audit( def record_access_audit(
*, *,
action: str, action: str,
@@ -27,7 +27,7 @@ from flask import current_app
from app import db from app import db
from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError from app.core.errors import ConflictError, ServiceUnavailableError, ValidationError
from app.models import ShippingNotice from app.models import ShippingNotice, ShippingNoticeLineInventoryMatch
from app.services.shipping_notice.constants import CP_UPLOADED 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.export import generate_shipment_excel, order_field_id_values
from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution from app.services.shipping_notice.inventory_file_store import resolve_inventory_lines_for_execution
@@ -1170,6 +1170,10 @@ def _recompute_task_match_aggregate(task: ShippingNotice) -> tuple[str, list[dic
'available_qty': float(available_qty) if available_qty is not None else 0.0, 'available_qty': float(available_qty) if available_qty is not None else 0.0,
'shortage_qty': float(shortage_qty) if shortage_qty is not None else 0.0, 'shortage_qty': float(shortage_qty) if shortage_qty is not None else 0.0,
} }
entry['line_status'] = (
'ok' if match_result == 'matched' and entry['shortage_qty'] <= 0
else 'shortage'
)
task.line_results_json.append(entry) task.line_results_json.append(entry)
if match_result == 'matched': if match_result == 'matched':
has_ok = True has_ok = True
@@ -1441,8 +1445,12 @@ def match_inventory(payload: dict[str, Any]) -> dict[str, Any]:
), ),
matching_rule_version='stp_line_v2', matching_rule_version='stp_line_v2',
) )
match_status = str(match_payload.get('match_status') or 'unfulfillable') # 详情投影只读 task JSON;必须基于已落库的 current 行事实重算整单,
line_results = list(match_payload.get('line_results') or []) # 否则匹配失败后订单明细仍显示“待确认”,且局部结果可能覆盖既有缺口。
match_status, shortages = _recompute_task_match_aggregate(task)
line_results = list(task.line_results_json or [])
task.match_status = match_status
task.shortage_json = {'lines': shortages}
from app.services.shipping_notice.reservation_service import record_inventory_verification from app.services.shipping_notice.reservation_service import record_inventory_verification
verification = record_inventory_verification( verification = record_inventory_verification(
task, inventory_snapshot_id=task.inventory_snapshot_id, task, inventory_snapshot_id=task.inventory_snapshot_id,
@@ -299,6 +299,7 @@ def save_batch_inventory_upload(task: ShippingNotice, upload: FileStorage) -> Sh
source_type=str(task.inventory_connector_type or "").strip() or None, source_type=str(task.inventory_connector_type or "").strip() or None,
warehouse_id=warehouse_id, warehouse_id=warehouse_id,
source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(), source_config_version=task.inventory_source_config_version or inventory_sources_runtime_version(),
source_query_json={'trigger_type': 'manual_upload'},
identity_status="pending", identity_status="pending",
snapshot_status="ready", snapshot_status="ready",
exported_at=datetime.utcnow(), exported_at=datetime.utcnow(),
@@ -393,6 +394,7 @@ def save_task_inventory_file_from_local_path(
schema_preview_json=preview, schema_preview_json=preview,
share_mode="task_only", share_mode="task_only",
line_count=0, line_count=0,
source_query_json={'trigger_type': 'manual_upload'},
) )
db.session.add(inv_file) db.session.add(inv_file)
db.session.flush() db.session.flush()
@@ -675,12 +675,27 @@ def _validate_rpa_callback_round(task: ShippingNotice, payload: dict[str, Any])
校验 RPA 回调轮次契约(run_no + 幂等)。 校验 RPA 回调轮次契约(run_no + 幂等)。
核心逻辑:success/skipped/failed 共用;无有效触发或旧轮次/重放均拒绝。 核心逻辑:success/skipped/failed 共用;无有效触发或旧轮次/重放均拒绝。
""" """
# Batch 回调顶层 run_no 是 batch identity;逐源 item 的 source_run_no
# 才是正式 Attempt identity。先按 source_run_no 接受当前 Attempt,避免
# per-source 已成功后又被 task-level batch_run_no 的旧 trigger 校验否决。
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', 'succeeded'}:
return None
run_no_error = _validate_rpa_callback_run_no(task, str(payload.get("run_no") or "")) run_no_error = _validate_rpa_callback_run_no(task, str(payload.get("run_no") or ""))
if run_no_error: if run_no_error:
# 逐源 batch Trigger 的任务事件可能仍保留旧的 task-level batch_run_no; # 逐源 batch Trigger 的任务事件可能仍保留旧的 task-level batch_run_no;
# source_run_no 是本次 Attempt 的正式身份,匹配最新 queued/running Attempt # source_run_no 是本次 Attempt 的正式身份,匹配最新 queued/running Attempt
# 时允许该批次回调继续入库,避免已生成的 Excel 被错误当作迟到回调丢弃。 # 时允许该批次回调继续入库,避免已生成的 Excel 被错误当作迟到回调丢弃。
source_run_no = str(payload.get('source_run_no') or '').strip()
if source_run_no: if source_run_no:
from app.models import ShippingTaskInventoryRpaAttempt from app.models import ShippingTaskInventoryRpaAttempt
@@ -872,9 +887,13 @@ def _validate_single_source_v2_contract(task: ShippingNotice, payload: dict[str,
def _merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]: def _merge_batch_callback_item(payload: dict[str, Any], item: dict[str, Any]) -> dict[str, Any]:
""" """
合并 batch 顶层契约字段到 result item。 合并 batch 顶层契约字段到 result item。
核心逻辑:仅合并 run_no / task_no;成功回调身份字段必须由 Worker 显式返回,禁止后端从任务补齐。 核心逻辑:合并 batch 已认证的 schema_version / run_no / task_no;其余身份字段必须由
Worker item 显式返回,禁止后端从任务或数据库补齐。
""" """
merged = dict(item) merged = dict(item)
top_schema_version = str(payload.get('schema_version') or '').strip()
if top_schema_version and not str(merged.get('schema_version') or '').strip():
merged['schema_version'] = top_schema_version
top_run_no = str(payload.get("run_no") or "").strip() top_run_no = str(payload.get("run_no") or "").strip()
if top_run_no and not str(merged.get("run_no") or "").strip(): if top_run_no and not str(merged.get("run_no") or "").strip():
merged["run_no"] = top_run_no merged["run_no"] = top_run_no
@@ -1909,6 +1928,10 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
structure_check = validate_production_inventory_structure( structure_check = validate_production_inventory_structure(
source_code=str(rpa_source['source_code']), path=ingest_path, source_code=str(rpa_source['source_code']), path=ingest_path,
) )
# RPA 来源已通过正式 Profile 结构校验;映射是确定性事实,不应再要求人工确认。
inv_file.field_mapping_json = dict(structure_check['field_mapping'])
inv_file.mapping_source = 'parsing_profile'
inv_file.mapping_confirmed = True
lines, column_meta = ingest_inventory_file( lines, column_meta = ingest_inventory_file(
ingest_path, move_to=None, ingest_path, move_to=None,
field_mapping=structure_check['field_mapping'], mapping_source='parsing_profile', field_mapping=structure_check['field_mapping'], mapping_source='parsing_profile',
@@ -1956,6 +1979,8 @@ def rpa_report_inventory(payload: dict[str, Any]) -> dict[str, Any]:
column_meta=column_meta, column_meta=column_meta,
source="rpa_callback", source="rpa_callback",
event_type="inventory_rpa_ready", event_type="inventory_rpa_ready",
field_mapping=dict(structure_check['field_mapping']),
mapping_source='parsing_profile',
commit=False, commit=False,
) )
item_savepoint.commit() item_savepoint.commit()
@@ -2245,6 +2270,21 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
}) })
else: else:
_handle_rpa_inventory_failed(task, merged_item, runtime, commit=False) _handle_rpa_inventory_failed(task, merged_item, runtime, commit=False)
# 失败回调已把 Task 从 rpa_pending 还原为库存不可用;必须立即同步正式 Gate,
# 否则 Execution 仍是 waiting_external,前端会错误停在“系统处理中”。
if task.active_process_execution_id:
from app.models import ShippingProcessExecution
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
execution = db.session.get(
ShippingProcessExecution,
int(task.active_process_execution_id),
)
if execution is not None:
sync_fulfillment_gates_from_task(
execution=execution,
actor_type='system',
)
failed.append({ failed.append({
"source_code": source_code, "source_code": source_code,
"warehouse_id": warehouse_id, "warehouse_id": warehouse_id,
@@ -2400,6 +2440,10 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
structure_check = validate_production_inventory_structure( structure_check = validate_production_inventory_structure(
source_code=source_code, path=ingest_path, source_code=source_code, path=ingest_path,
) )
# 定时预热快照同样经过正式 Profile 校验,后续绑定任务可直接匹配。
inv_file.field_mapping_json = dict(structure_check['field_mapping'])
inv_file.mapping_source = 'parsing_profile'
inv_file.mapping_confirmed = True
created_entry = { created_entry = {
"inventory_file_no": inv_file.inventory_file_no, "inventory_file_no": inv_file.inventory_file_no,
"source_code": inv_file.source_code or source_code, "source_code": inv_file.source_code or source_code,
@@ -2455,6 +2499,8 @@ def rpa_report_inventory_batch(payload: dict[str, Any]) -> dict[str, Any]:
column_meta=column_meta, column_meta=column_meta,
source="rpa_batch_callback", source="rpa_batch_callback",
event_type="inventory_rpa_ready", event_type="inventory_rpa_ready",
field_mapping=dict(structure_check['field_mapping']),
mapping_source='parsing_profile',
commit=False, commit=False,
) )
_mark_inventory_rpa_run_no_consumed( _mark_inventory_rpa_run_no_consumed(
@@ -2381,6 +2381,8 @@ def submit_order_extraction(
primary_run: ShippingOrderProcessingRun | None = None primary_run: ShippingOrderProcessingRun | None = None
any_reused = False any_reused = False
for index, intake_no in enumerate(list(intake_nos or [])): for index, intake_no in enumerate(list(intake_nos or [])):
# [STEP 2] 首个 Run 可能在空 conversation_id 下创建本地会话;后续 Intake
# 必须沿用该会话,避免一次多 EML 被拆成多个左侧对话。
created_run, reused_one = create_order_extraction_run( created_run, reused_one = create_order_extraction_run(
user=user, user=user,
agent_id=owner_agent.id, agent_id=owner_agent.id,
@@ -2395,6 +2397,7 @@ def submit_order_extraction(
any_reused = any_reused or reused_one any_reused = any_reused or reused_one
if primary_run is None: if primary_run is None:
primary_run = created_run primary_run = created_run
conversation_id = created_run.conversation_id
if primary_run is None: if primary_run is None:
raise ValidationError( raise ValidationError(
'intake_nos is required', 'intake_nos is required',
@@ -16,6 +16,8 @@ backend/app/services/shipping_notice/order_review_confirmation_service.py
物化 accepted Extraction(保留派生 field_lineage);建单前再次校验客户确认并 物化 accepted Extraction(保留派生 field_lineage);建单前再次校验客户确认并
持久化 Candidate Qualification 快照;客户未确认拒绝建单;同 Case 既有波次 Task 持久化 Candidate Qualification 快照;客户未确认拒绝建单;同 Case 既有波次 Task
豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束; 豁免精确文件哈希重复检查;波次行写入不可变 wave_lines 唯一约束;
新建 Task 完成客户绑定后立即冻结订单快照;冻结失败时整笔确认回滚,禁止把无快照
Task 推入库存/RPA;
成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至 成功确认镜像 review_confirmed 到订单抽取进度流;校验 WorkflowItem 当前版本后推进至
building_order(不关闭);同步 Process Execution 推进至 task_creation 通过, building_order(不关闭);同步 Process Execution 推进至 task_creation 通过,
避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox), 避免重复冻结资格阻断;与确认同事务入队 shipping_notice_run(待推进 Outbox),
@@ -357,6 +359,24 @@ def _materialize_extraction(*, case: ShippingOrderReviewCase, intake_id: int, su
if isinstance(run.input_snapshot_json, dict) else {} if isinstance(run.input_snapshot_json, dict) else {}
) )
configs = [item for item in definition.get('fields') or [] if isinstance(item, dict) and item.get('enabled', True)] configs = [item for item in definition.get('fields') or [] if isinstance(item, dict) and item.get('enabled', True)]
formal_line_codes = {
str(item.get('field_code') or '')
for item in configs
if str(item.get('scope') or '') == 'line' and item.get('field_code')
}
unknown_line_fields = sorted({
str(key)
for line in summary.get('lines') or []
if isinstance(line, dict)
for key in line
if str(key) not in formal_line_codes and not str(key).startswith('_')
})
if unknown_line_fields:
raise ValidationError(
'订单明细包含未在当前 Schema 中定义的字段',
code='SHIPPING_NOTICE.CANDIDATE_REVIEW_REQUIRED',
details={'fields': unknown_line_fields, 'schema_version_id': int(case.current_draft.schema_version_id)},
)
normalized = _build_confirmation_normalized_result(case=case, summary=summary) normalized = _build_confirmation_normalized_result(case=case, summary=summary)
extraction = ShippingOrderExtraction( extraction = ShippingOrderExtraction(
run_id=int(run.id), intake_id=int(intake_id), schema_version_id=int(case.current_draft.schema_version_id), run_id=int(run.id), intake_id=int(intake_id), schema_version_id=int(case.current_draft.schema_version_id),
@@ -1388,6 +1408,16 @@ def confirm_review_case(*, user_id: int, case_no: str, expected_draft_version: A
) )
else: else:
try_auto_confirm_task_customer(task) try_auto_confirm_task_customer(task)
# [STEP] Review 确认建单与自动建单必须共享订单快照前置条件。
# 冻结失败由外层 AppError 回滚,不能留下已建单但库存链路无法启动的半成品。
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=int(task.order_data_version or 1),
freeze_mode='manual',
)
except AppError as err: except AppError as err:
_reject_confirmation( _reject_confirmation(
case, case,
@@ -443,11 +443,17 @@ def ensure_all_required_sources_prepared(
dict(legacy_rpa_source, **{'source_code': source_code}), dict(legacy_rpa_source, **{'source_code': source_code}),
payload=per_source_payload, payload=per_source_payload,
) )
if trigger_result: if not trigger_result:
new_att.trigger_file_path = str(trigger_result) # 没有真实文件就不能宣称 queued;否则 Gate 会显示等待 RPA,Worker 永远不会领取。
new_att.status = 'failed'
new_att.error_code = 'trigger_not_written'
new_att.error_message = '库存 RPA trigger 文件未生成'
new_att.execution_phase = 'trigger_write_failed'
new_att.updated_at = datetime.utcnow()
failed.append(source_code)
else: else:
new_att.trigger_file_path = trigger_fname new_att.trigger_file_path = str(trigger_result)
pending.append(source_code) pending.append(source_code)
except Exception as exc: # pragma: no cover - RPA 环境异常 except Exception as exc: # pragma: no cover - RPA 环境异常
new_att.status = 'failed' new_att.status = 'failed'
new_att.error_code = 'trigger_write_error' new_att.error_code = 'trigger_write_error'
@@ -18,6 +18,7 @@ from __future__ import annotations
import hashlib import hashlib
import json import json
import logging import logging
from datetime import datetime
from typing import Any from typing import Any
from app.models import ( from app.models import (
@@ -666,6 +667,74 @@ def _fulfillment_blocking_finding(
}] }]
def _supersede_auto_inventory_poll_for_rpa_failure(
*,
execution: ShippingProcessExecution,
task: ShippingNotice,
actor_type: str,
actor_id: str | int | None,
) -> None:
"""RPA 已耗尽时终止同 Gate 的自动轮询,释放业务结果回写。
自动轮询 Attempt 不产生新的库存事实;其在 RPA 已失败后继续 queued/running
会使 sync_gate_from_business_result 早退,Gate 永久停留 waiting_external。
仅处理 trigger_type=auto 且 action_code=poll_inventory_preparation,绝不终止
用户主动 retry_inventory_preparation。
"""
from app import db
from app.models import ShippingProcessGateAttempt
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED
from app.services.shipping_notice.fulfillment_audit import record_fulfillment_audit
if (
str(task.process_status or '').strip() != 'waiting_inventory'
or str(task.pending_human_reason or '').strip() != PH_RPA_EXHAUSTED
):
return
gate = ShippingProcessGate.query.filter_by(
execution_id=int(execution.id), gate_code='inventory_preparation',
).with_for_update().first()
if gate is None:
return
active_attempts = (
ShippingProcessGateAttempt.query
.filter(
ShippingProcessGateAttempt.gate_id == int(gate.id),
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
ShippingProcessGateAttempt.trigger_type == 'auto',
)
.with_for_update()
.all()
)
now = datetime.utcnow()
for attempt in active_attempts:
snapshot = attempt.input_snapshot_json if isinstance(attempt.input_snapshot_json, dict) else {}
if str(snapshot.get('action_code') or '').strip() != 'poll_inventory_preparation':
continue
before = {'status': attempt.status, 'gate_code': gate.gate_code}
attempt.status = 'superseded'
attempt.finished_at = now
attempt.lease_token = None
attempt.lease_expires_at = None
attempt.error_code = 'rpa_callback_failed'
attempt.error_summary = 'RPA callback failed; automatic inventory poll superseded.'
record_fulfillment_audit(
event_type='process_gate_attempt_superseded',
aggregate_type='process_gate_attempt',
aggregate_id=str(attempt.id),
action='supersede_auto_inventory_poll',
actor_type=actor_type,
actor_id=actor_id,
task_no=str(task.task_no or '') or None,
reason_code='rpa_callback_failed',
before=before,
after={'status': 'superseded', 'gate_code': gate.gate_code},
metadata={'execution_no': execution.execution_no},
source='process_gate_bridge',
)
db.session.flush()
def sync_fulfillment_gates_from_task( def sync_fulfillment_gates_from_task(
*, *,
execution: ShippingProcessExecution, execution: ShippingProcessExecution,
@@ -690,6 +759,13 @@ def sync_fulfillment_gates_from_task(
if task is None: if task is None:
return return
_supersede_auto_inventory_poll_for_rpa_failure(
execution=execution,
task=task,
actor_type=actor_type,
actor_id=actor_id,
)
from app.services.shipping_notice.fulfillment_workflow import excel_gate_error, match_completed from app.services.shipping_notice.fulfillment_workflow import excel_gate_error, match_completed
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
@@ -711,9 +787,14 @@ def sync_fulfillment_gates_from_task(
match_passed = match_status in {'fulfillable', 'partial', 'unfulfillable'} or status in { match_passed = match_status in {'fulfillable', 'partial', 'unfulfillable'} or status in {
'matched', 'waiting_upload', 'upload_failed', *done_statuses, 'matched', 'waiting_upload', 'upload_failed', *done_statuses,
} }
# 仅当存在活跃库存文件且未确认映射时阻断;无文件但已有解析行视为映射已由 Profile 固化。 # 仅手动上传且未确认映射的文件允许进入人工字段映射;库存源/RPA 文件必须由
# 正式 Profile 在入库时确定性确认,不能因为历史快照缺少该标记而阻塞。
source_query = getattr(inv_file, 'source_query_json', None) if inv_file is not None else None
trigger_type = str((source_query or {}).get('trigger_type') or '').strip().lower() if isinstance(source_query, dict) else ''
is_manual_upload = trigger_type == 'manual_upload'
mapping_needed = ( mapping_needed = (
inv_file is not None inv_file is not None
and is_manual_upload
and not mapping_confirmed and not mapping_confirmed
and status not in {'matched', 'waiting_upload', 'upload_failed', *done_statuses} and status not in {'matched', 'waiting_upload', 'upload_failed', *done_statuses}
) )
@@ -753,7 +834,9 @@ def sync_fulfillment_gates_from_task(
preparation = prep_query.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()).first() preparation = prep_query.order_by(ShippingInventoryPreparationAttempt.attempt_no.desc()).first()
except Exception: # noqa: BLE001 except Exception: # noqa: BLE001
preparation = None preparation = None
if preparation is not None: # 已绑定库存行代表正式快照已成功落库;历史 PreparationAttempt 即使仍标为
# waiting_external,也只能保留审计,不能覆盖当前任务事实并阻止进入匹配。
if preparation is not None and not has_inventory_lines:
source_rows = list(getattr(preparation, 'source_attempts', []) or []) source_rows = list(getattr(preparation, 'source_attempts', []) or [])
required = [str(row.source_code or '').strip().upper() for row in source_rows] 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'}] prepared = [code for code, row in zip(required, source_rows) if row.status in {'ready', 'reusable'}]
@@ -767,7 +850,10 @@ def sync_fulfillment_gates_from_task(
'pending_sources': pending, 'pending_sources': pending,
'failed_sources': failed, 'failed_sources': failed,
}) })
if preparation.status in {'queued', 'running', 'waiting_external'} or pending: # Task 已明确 rpa_exhausted 时,Preparation 的旧 waiting_external 不能
# 继续把 Gate 投影成系统处理中;Preparation 保留 waiting 作为原始审计事实。
task_rpa_exhausted = str(task.pending_human_reason or '').strip() == 'rpa_exhausted'
if not task_rpa_exhausted and (preparation.status in {'queued', 'running', 'waiting_external'} or pending):
apply_gate_outcome( apply_gate_outcome(
execution=execution, gate_code='inventory_preparation', passed=False, execution=execution, gate_code='inventory_preparation', passed=False,
outcome='waiting_external', effective_result={'findings': [], **task_facts}, outcome='waiting_external', effective_result={'findings': [], **task_facts},
@@ -793,17 +879,25 @@ def sync_fulfillment_gates_from_task(
) )
# Continue below for mapping/matching facts. # Continue below for mapping/matching facts.
if status == 'waiting_inventory': if status == 'waiting_inventory':
from app.services.shipping_notice.constants import PH_RPA_PENDING from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
waiting_reason = (
'inventory_rpa_queued' pending_reason = str(task.pending_human_reason or '').strip()
if str(task.pending_human_reason or '').strip() == PH_RPA_PENDING # 只有 Worker 已领取/等待回调才是 waiting_external。RPA 失败或次数耗尽时
else 'inventory_preparation_waiting' # 必须退出自动处理中,回到可恢复 Gate,不能因 process_status 相同再次自动入队。
) if pending_reason == PH_RPA_PENDING:
outcome = 'waiting_external'
waiting_reason = 'inventory_rpa_queued'
elif pending_reason == PH_RPA_EXHAUSTED:
outcome = 'blocked_manual'
waiting_reason = 'inventory_rpa_exhausted'
else:
outcome = 'blocked_retryable'
waiting_reason = inventory_preparation_reason_code(task) or 'inventory_preparation_failed'
apply_gate_outcome( apply_gate_outcome(
execution=execution, execution=execution,
gate_code='inventory_preparation', gate_code='inventory_preparation',
passed=False, passed=False,
outcome='waiting_external', outcome=outcome,
effective_result={ effective_result={
'findings': _fulfillment_blocking_finding( 'findings': _fulfillment_blocking_finding(
gate_code='inventory_preparation', gate_code='inventory_preparation',
@@ -894,7 +988,9 @@ def sync_fulfillment_gates_from_task(
execution=execution, execution=execution,
gate_code='inventory_matching', gate_code='inventory_matching',
passed=match_passed, passed=match_passed,
outcome='blocked_manual' if (not match_passed and status in {'pending_review', 'inventory_ready'}) else None, # 库存快照已就绪但 match_status 未落终态表示匹配自动推进已中断。此时必须
# 提供 retry_inventory_matching,不能保留 pending 并伪装为系统处理中。
outcome='blocked_retryable' if not match_passed else None,
effective_result={ effective_result={
'findings': ( 'findings': (
[] if match_passed else _fulfillment_blocking_finding( [] if match_passed else _fulfillment_blocking_finding(
@@ -15,6 +15,7 @@ from __future__ import annotations
from typing import Any, Callable from typing import Any, Callable
from app import db
from app.core.errors import ValidationError from app.core.errors import ValidationError
from app.models import ( from app.models import (
ShippingOrderDocument, ShippingOrderDocument,
@@ -762,14 +763,33 @@ def _handle_retry_inventory_preparation(
task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None task = ShippingNotice.query.get(int(execution.task_id)) if execution.task_id else None
recovery_plan_id = payload.get('recovery_plan_id') recovery_plan_id = payload.get('recovery_plan_id')
# Gate Worker 通过 _task_payload 传递 operator_id;人工 API 可能传 actor_user_id/user_id。
# 三者必须统一,否则冻结订单快照会收到 None,并在 RPA Attempt/trigger 创建前失败。
actor_id = (
payload.get('actor_user_id')
or payload.get('user_id')
or payload.get('operator_id')
)
preparation_round = None preparation_round = None
if task is not None and payload.get('action_code') != 'poll_inventory_preparation': if task is not None and payload.get('action_code') != 'poll_inventory_preparation':
# 历史 Task 可能在正式建单后遗漏快照。所有 Gate 恢复入口必须先补齐该履约事实,
# 不能依赖某一个旧 Workspace/Chat 重试入口,否则同一个按钮会持续卡在 order_freeze。
if not task.order_snapshot_id:
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
freeze_order_snapshot(
task,
actor_id=actor_id,
expected_order_data_version=int(task.order_data_version or 1),
freeze_mode='manual',
)
db.session.flush()
if payload.get('action_code') in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping'}: if payload.get('action_code') in {'retry_inventory_from_preparation', 'retry_inventory_from_field_mapping'}:
invalidate_inventory_downstream( invalidate_inventory_downstream(
execution=execution, execution=execution,
action_code=str(payload.get('action_code')), action_code=str(payload.get('action_code')),
attempt_id=payload.get('attempt_id'), attempt_id=payload.get('attempt_id'),
actor_id=payload.get('actor_user_id'), actor_id=actor_id,
) )
preparation_round = create_inventory_preparation_round( preparation_round = create_inventory_preparation_round(
task=task, task=task,
@@ -107,6 +107,7 @@ def _resolve_recovery_next_action(
blocking_gate_code = str((blocking or {}).get('gate_code') or '').strip().lower() blocking_gate_code = str((blocking or {}).get('gate_code') or '').strip().lower()
normalized_reason = str((blocking or {}).get('blocking_reason_code') or '').strip().lower() normalized_reason = str((blocking or {}).get('blocking_reason_code') or '').strip().lower()
status = str((blocking or {}).get('status') or '').strip().lower() status = str((blocking or {}).get('status') or '').strip().lower()
has_formal_task = bool(execution and getattr(execution, 'task_id', None))
# [STEP 1] 库存准备失败统一允许业务用户手动重新获取库存;人工上传是辅助输入入口。 # [STEP 1] 库存准备失败统一允许业务用户手动重新获取库存;人工上传是辅助输入入口。
if blocking_gate_code == 'inventory_preparation': if blocking_gate_code == 'inventory_preparation':
@@ -114,6 +115,13 @@ def _resolve_recovery_next_action(
if inventory_action: if inventory_action:
return inventory_action, False return inventory_action, False
# 库存匹配失败属于业务可恢复阻断;即使 Gate 责任方是 worker,
# 业务用户仍必须能重新提交匹配,不能只投影“可重试”状态而隐藏按钮。
if blocking_gate_code == 'inventory_matching' and (
has_formal_task or status == 'blocked_retryable'
):
return 'retry_inventory_matching', False
# [STEP 2] 货代上传 RPA 失败 / 人工交接失败:保持统一的 RPA 重试入口。 # [STEP 2] 货代上传 RPA 失败 / 人工交接失败:保持统一的 RPA 重试入口。
if ( if (
blocking_gate_code == 'freight_upload_rpa' blocking_gate_code == 'freight_upload_rpa'
@@ -143,10 +151,11 @@ def _resolve_recovery_next_action(
next_action = None next_action = None
technical_auto_only = True technical_auto_only = True
# RecoveryPlan 复核入口兜底(inventory_matching / inventory_sufficiency)。 # RecoveryPlan 复核入口兜底(建单前 inventory_matching / inventory_sufficiency)。
# 正式 OT 的库存匹配只能重试,不能下发无写操作的复核导航入口。
if not next_action: if not next_action:
recovery_targets = full.get('recovery_targets') or [] recovery_targets = full.get('recovery_targets') or []
if recovery_targets and blocking_gate_code == 'inventory_matching': if recovery_targets and blocking_gate_code == 'inventory_matching' and not has_formal_task:
next_action = 'open_inventory_match_review' next_action = 'open_inventory_match_review'
technical_auto_only = False technical_auto_only = False
elif recovery_targets and blocking_gate_code == 'inventory_sufficiency': elif recovery_targets and blocking_gate_code == 'inventory_sufficiency':
@@ -428,6 +437,23 @@ def _navigation_for_action(action_code: str | None, refs: dict[str, Any]) -> dic
return None return None
def _has_confirmed_inventory_for_matching(execution: ShippingProcessExecution) -> bool:
"""判断 pending 匹配 Gate 是否已有可复用的已确认库存快照。"""
if not execution.task_id:
return False
from app.models import ShippingNotice
from app.services.shipping_notice.inventory_file_store import active_inventory_file_for_task
task = ShippingNotice.query.get(int(execution.task_id))
if task is None or not isinstance(task.inventory_lines_json, list) or not task.inventory_lines_json:
return False
inventory_file = active_inventory_file_for_task(task)
return bool(
inventory_file is not None
and bool(getattr(inventory_file, 'mapping_confirmed', False))
)
def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, Any]: def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str, Any]:
""" """
用户端安全投影:唯一当前阻断 + 主要恢复动作;不含管理员诊断 JSON。 用户端安全投影:唯一当前阻断 + 主要恢复动作;不含管理员诊断 JSON。
@@ -482,6 +508,20 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
} }
current = full.get('current_gate') current = full.get('current_gate')
blocking = None blocking = None
if (
isinstance(current, dict)
and str(current.get('gate_code') or '').strip().lower() == 'inventory_field_mapping'
and str(current.get('status') or '').strip().lower() == 'pending'
):
current = {**current, 'status': 'blocked_manual', 'next_action_code': 'confirm_inventory_field_mapping'}
if (
isinstance(current, dict)
and str(current.get('gate_code') or '').strip().lower() == 'inventory_matching'
and str(current.get('status') or '').strip().lower() == 'pending'
and _has_confirmed_inventory_for_matching(execution)
):
# 库存快照已确认但匹配未落终态,说明自动推进已中断;不能继续显示系统处理中。
current = {**current, 'status': 'blocked_retryable', 'next_action_code': 'retry_inventory_matching'}
if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | { if current and current.get('status') in PROCESS_GATE_RECOVERABLE_STATUSES | {
'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated', 'blocked_retryable', 'blocked_manual', 'waiting_external', 'failed_terminal', 'invalidated',
}: }:
@@ -525,6 +565,16 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
allowed_actions: list[str] = [] allowed_actions: list[str] = []
action_items: list[dict[str, str]] = [] action_items: list[dict[str, str]] = []
is_formal_inventory_matching = bool(
getattr(execution, 'task_id', None)
and str((blocking or {}).get('gate_code') or '').strip().lower() == 'inventory_matching'
)
recovery_targets = full.get('recovery_targets') or []
if is_formal_inventory_matching:
recovery_targets = [
target for target in recovery_targets
if str(target.get('action_code') or '').strip() == 'retry_inventory_from_preparation'
]
if blocking: if blocking:
if next_action and is_business_user_action(str(next_action)): if next_action and is_business_user_action(str(next_action)):
allowed_actions.append(str(next_action)) allowed_actions.append(str(next_action))
@@ -533,7 +583,7 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
and next_action == 'retry_inventory_preparation' and next_action == 'retry_inventory_preparation'
): ):
allowed_actions.append('upload_inventory_file') allowed_actions.append('upload_inventory_file')
for target in full.get('recovery_targets') or []: for target in recovery_targets:
code = str(target.get('action_code') or '').strip() code = str(target.get('action_code') or '').strip()
if code and code not in allowed_actions and is_business_user_action(code): if code and code not in allowed_actions and is_business_user_action(code):
allowed_actions.append(code) allowed_actions.append(code)
@@ -569,7 +619,7 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
'current_gate': current, 'current_gate': current,
'current_blocking_gate': blocking, 'current_blocking_gate': blocking,
# 客户端只消费服务端已校验的恢复目标,不自行推导跨 Gate 路径。 # 客户端只消费服务端已校验的恢复目标,不自行推导跨 Gate 路径。
'recovery_targets': full.get('recovery_targets') or [], 'recovery_targets': recovery_targets,
'active_recovery_plans': full.get('active_recovery_plans') or [], 'active_recovery_plans': full.get('active_recovery_plans') or [],
'blocking_reason_code': reason_code, 'blocking_reason_code': reason_code,
'blocking_message': _user_facing_blocking_message(reason_code), 'blocking_message': _user_facing_blocking_message(reason_code),
@@ -109,6 +109,20 @@ def get_execution_by_no(execution_no: str) -> ShippingProcessExecution:
return row return row
def _primary_recovery_action(
*, execution: ShippingProcessExecution, gate: ShippingProcessGate,
) -> str | None:
"""按用户投影同一事实裁决当前 Gate 的可提交主恢复动作。"""
if gate.gate_code == 'inventory_preparation':
return inventory_preparation_primary_action(gate.status)
# 正式 OT 的库存匹配不再接受仅导航的旧 Gate 动作;历史行仍保留原值供审计。
if gate.gate_code == 'inventory_matching' and execution.task_id:
return 'retry_inventory_matching'
return gate.next_action_code or primary_next_action_for_gate(
gate_code=gate.gate_code, status=gate.status,
)
def request_gate_action( def request_gate_action(
*, *,
execution_no: str, execution_no: str,
@@ -218,10 +232,7 @@ def request_gate_action(
details={'gate_code': gate.gate_code, 'action_code': action}, details={'gate_code': gate.gate_code, 'action_code': action},
) )
primary = inventory_preparation_primary_action(gate.status) if gate.gate_code == 'inventory_preparation' else None primary = _primary_recovery_action(execution=execution, gate=gate)
primary = primary or gate.next_action_code or primary_next_action_for_gate(
gate_code=gate.gate_code, status=gate.status,
)
# [STEP] 兼容历史 Gate 20:用户投影已将人工待办旧动作纠正为显式 RPA # [STEP] 兼容历史 Gate 20:用户投影已将人工待办旧动作纠正为显式 RPA
# 重试,但数据库 Gate 行可能仍保留 regenerate_manual_upload_todo。 # 重试,但数据库 Gate 行可能仍保留 regenerate_manual_upload_todo。
# 这里必须与用户投影使用同一 Gate/原因事实,否则点击必然被主动作校验拒绝。 # 这里必须与用户投影使用同一 Gate/原因事实,否则点击必然被主动作校验拒绝。
@@ -765,8 +765,16 @@ def _enqueue_auto_progress_after_gate_pass(
if next_gate is None or not next_gate.next_action_code: if next_gate is None or not next_gate.next_action_code:
return return
definition = get_process_gate_definition(next_gate.gate_code) definition = get_process_gate_definition(next_gate.gate_code)
# default_next_actions 中可恢复不等于可自动执行。库存匹配等动作必须由
# 用户明确点击;否则库存准备通过后会立刻消费“重试库存匹配”按钮,页面
# 只剩被自动执行后的结果,用户无法控制重试时机。
if str(definition.get('responsible_party') or '') not in {'system', 'worker'}: if str(definition.get('responsible_party') or '') not in {'system', 'worker'}:
return return
if (
next_gate.next_action_code in {'retry_inventory_matching'}
or str(next_gate.next_action_code).startswith('open_')
):
return
attempt = queue_gate_attempt( attempt = queue_gate_attempt(
execution_no=str(execution.execution_no), execution_no=str(execution.execution_no),
gate_code=next_gate.gate_code, gate_code=next_gate.gate_code,
@@ -911,7 +919,33 @@ def sync_gate_from_business_result(
.first() .first()
) )
if active_attempt is not None: if active_attempt is not None:
return gate # 库存快照已落库时,自动轮询已获得其等待的正式事实。直接复用此 Attempt
# 完成库存准备,避免先终止后重新排队时被自动推进器插入新的轮询。用户主动
# Attempt 绝不在这里完成或覆盖。
snapshot = (
active_attempt.input_snapshot_json
if isinstance(active_attempt.input_snapshot_json, dict)
else {}
)
inventory_ready = bool(
gate_code == 'inventory_preparation'
and passed
and isinstance(effective_result_json, dict)
and effective_result_json.get('has_inventory_lines')
)
is_auto_poll = (
active_attempt.trigger_type == 'auto'
and str(snapshot.get('action_code') or '').strip() == 'poll_inventory_preparation'
)
if not inventory_ready or not is_auto_poll:
return gate
return complete_gate_attempt(
attempt_id=int(active_attempt.id),
outcome='passed',
output_snapshot=effective_result_json,
recommendation_json=recommendation_json,
effective_result_json=effective_result_json,
)
if allow_repass and gate.status == 'passed': if allow_repass and gate.status == 'passed':
gate.status = 'invalidated' gate.status = 'invalidated'
@@ -290,6 +290,7 @@ SHIPPING_PROCESSING_ACTION_INTENTS: Final[tuple[str, ...]] = (
'open_inventory_match_review', 'open_inventory_match_review',
'open_shortage_review', 'open_shortage_review',
'upload_inventory_file', 'upload_inventory_file',
'retry_inventory_matching',
'retry', 'retry',
'refresh', 'refresh',
'regenerate_excel', 'regenerate_excel',
@@ -9,6 +9,7 @@ services/shipping_notice/rpa.py
from __future__ import annotations from __future__ import annotations
import json import json
import os
import shutil import shutil
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
@@ -837,11 +837,19 @@ def _order_task_current_gate(
notice = db.session.get(ShippingNotice, int(order_task.shipping_notice_id)) notice = db.session.get(ShippingNotice, int(order_task.shipping_notice_id))
if notice is not None: if notice is not None:
execution = ( execution = None
ShippingProcessExecution.query.filter_by(task_id=int(notice.id)) active_execution_id = getattr(notice, 'active_process_execution_id', None)
.order_by(ShippingProcessExecution.id.desc()) if active_execution_id is not None:
.first() execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
) if execution is not None and int(getattr(execution, 'task_id', 0) or 0) != int(notice.id):
execution = None
if execution is None:
execution = (
ShippingProcessExecution.query.filter_by(task_id=int(notice.id))
.filter(ShippingProcessExecution.status != 'superseded')
.order_by(ShippingProcessExecution.id.desc())
.first()
)
if execution is not None: if execution is not None:
summary = project_user_gate_summary(execution) summary = project_user_gate_summary(execution)
blocking = summary.get('current_blocking_gate') or summary.get('current_gate') blocking = summary.get('current_blocking_gate') or summary.get('current_gate')
@@ -1015,6 +1023,14 @@ def _project_order_task_work_item(
if shared_code in SHIPPING_PROCESSING_STAGES: if shared_code in SHIPPING_PROCESSING_STAGES:
stage = shared_code stage = shared_code
stage_label_key = str(shared.get('label_key') or '').strip() or None stage_label_key = str(shared.get('label_key') or '').strip() or None
active_execution_id = getattr(notice_for_stage, 'active_process_execution_id', None)
if active_execution_id is not None:
from app.models import ShippingProcessExecution
active_execution = db.session.get(ShippingProcessExecution, int(active_execution_id))
active_gate = str(getattr(active_execution, 'current_gate_code', '') or '').strip().lower()
if active_gate in SHIPPING_PROCESSING_STAGES:
stage = active_gate
stage_label_key = active_gate
# order_creating 无共享投影时仍统一用户文案键。 # order_creating 无共享投影时仍统一用户文案键。
if not stage_label_key and stage == 'order_creating': if not stage_label_key and stage == 'order_creating':
stage_label_key = 'waiting_system_start' stage_label_key = 'waiting_system_start'
@@ -387,8 +387,8 @@ def test_excel_pull_request_number_uses_export_date_without_changing_case_number
assert shipping_case.business_no == 'IVMX26080801' assert shipping_case.business_no == 'IVMX26080801'
def test_export_mapping_falls_back_to_export_sequence_and_derived_line_amount(app): def test_export_mapping_uses_sequence_but_never_derives_formal_line_amount(app):
"""LineNumber 缺失时用导出行序号,Shipment Value 缺失时用数量乘单价。""" """正式金额必须来自 Schema FieldValue,禁止由快照或单价静默推导。"""
with app.app_context(): with app.app_context():
fields = _lookup_standard_fields('line_no', 'line_amount_with_tax') fields = _lookup_standard_fields('line_no', 'line_amount_with_tax')
task = ShippingNotice(task_no='TASK-MAPPING') task = ShippingNotice(task_no='TASK-MAPPING')
@@ -400,7 +400,7 @@ def test_export_mapping_falls_back_to_export_sequence_and_derived_line_amount(ap
assert _mapping_value( assert _mapping_value(
{'source_kind': 'order_field', 'source_key': fields['line_amount_with_tax'].id, 'formatter': 'decimal', 'row_mode': 'line'}, {'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={}, task=task, order_values={'__qty': Decimal('14'), '__unit_price': Decimal('941.76')}, inventory_values={},
) == 13184.64 ) is None
def test_clear_template_data_rows_keeps_headers_and_removes_residual_values(): def test_clear_template_data_rows_keeps_headers_and_removes_residual_values():
@@ -470,6 +470,32 @@ def test_rpa_report_inventory_batch_mixed_results_exposes_partial_failed(app, tm
assert result["failed_count"] == 1 assert result["failed_count"] == 1
def test_rpa_snapshot_persists_confirmed_profile_mapping(app, tmp_path):
"""RPA 文件经过正式 Profile 校验后必须直接确认映射,不进入人工 Gate。"""
from app import db
from app.models import ShippingInventoryFile
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_RPA_SHARED_INVENTORY_DROP_DIR"] = str(drop_dir)
app.config["SHIPPING_NOTICE_STORAGE_ROOT"] = str(tmp_path / "storage")
sample = drop_dir / "inventory-mapping-confirmed.xlsx"
sample.write_bytes(inventory_xlsx_with_warehouse("AWSDU").getvalue())
with app.app_context():
result = rpa_report_inventory_batch(_with_v2_batch_envelope({
"run_no": "RUN-MAPPING-CONFIRMED",
"trigger_type": "scheduled",
"results": [scheduled_rpa_batch_item("DSV360_AWSDU", success=True, file_path=str(sample))],
}))
assert result["success_count"] == 1
snapshot = ShippingInventoryFile.query.filter_by(rpa_run_no="RUN-MAPPING-CONFIRMED").one()
assert snapshot.mapping_source == "parsing_profile"
assert snapshot.mapping_confirmed is True
assert snapshot.field_mapping_json
def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path): def test_rpa_report_inventory_batch_all_failed_still_returns_ok(app, tmp_path):
"""全 failed 时接口 status 仍为 ok,业务结果见 result_status=failed。""" """全 failed 时接口 status 仍为 ok,业务结果见 result_status=failed。"""
from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch from app.services.shipping_notice.inventory_rpa_workflow import rpa_report_inventory_batch
@@ -11,11 +11,12 @@ import pytest
from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task from app.services.shipping_notice.rpa import write_inventory_export_trigger_for_task
def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path): def test_on_demand_uses_batch_trigger_when_enabled(app, tmp_path, monkeypatch):
"""batch 开启时单票按需应写 inventory_export_batch trigger。""" """batch 开启时单票按需应写 inventory_export_batch trigger。"""
trigger_dir = tmp_path / "triggers" trigger_dir = tmp_path / "triggers"
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir) app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
app.config["SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED"] = True app.config.pop("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", None)
monkeypatch.setenv("SHIPPING_NOTICE_INVENTORY_RPA_BATCH_ENABLED", "true")
source = { source = {
"source_code": "DSV360_AWSDU", "source_code": "DSV360_AWSDU",
@@ -13,7 +13,7 @@ from datetime import datetime
import pytest import pytest
from app import db from app import db
from app.models import ShippingOrderProcessingRun from app.models import ChatSession, ShippingOrderProcessingRun
from app.services.shipping_notice.order_extraction_run_service import ( from app.services.shipping_notice.order_extraction_run_service import (
create_order_extraction_run, create_order_extraction_run,
evaluate_can_append, evaluate_can_append,
@@ -167,6 +167,35 @@ def test_submit_idempotent_by_submission_id(app):
assert ShippingOrderProcessingRun.query.count() == 1 assert ShippingOrderProcessingRun.query.count() == 1
def test_submit_multiple_unbound_intakes_creates_one_chat_session(app):
"""一次多邮件首次提交可建多个 Run,但必须共用服务端新建的一个会话。"""
with app.app_context():
user, agent, _session, first_intake, _document = _seed_run_input(suffix='MULTI-EML-A')
_, _, _, second_intake, _document = _seed_run_input(
suffix='MULTI-EML-B',
agent_code='shipping_notice_multi_eml_b',
)
first_intake.conversation_id = None
second_intake.user_id = user.id
second_intake.conversation_id = None
db.session.commit()
payload = submit_order_extraction(
user=user,
agent_id=agent.id,
conversation_id='',
intake_nos=[first_intake.intake_no, second_intake.intake_no],
submission_id='SUB-TEST-MULTI-EML-ONE-CONVERSATION',
)
db.session.commit()
runs = ShippingOrderProcessingRun.query.order_by(ShippingOrderProcessingRun.id).all()
conversation_ids = {run.conversation_id for run in runs}
assert len(runs) == 2
assert conversation_ids == {runs[0].conversation_id}
assert ChatSession.query.filter(ChatSession.session_id.in_(conversation_ids)).count() == 1
def test_legacy_create_can_still_block_parallel_when_flag_false(app): def test_legacy_create_can_still_block_parallel_when_flag_false(app):
"""兼容路径 allow_parallel_conversation_runs=False 仍抛 CONVERSATION_ACTIVE。""" """兼容路径 allow_parallel_conversation_runs=False 仍抛 CONVERSATION_ACTIVE。"""
with app.app_context(): with app.app_context():
@@ -978,6 +978,8 @@ def test_confirm_review_case_creates_one_task_and_immutable_revision(app):
assert getattr(task, 'order_task_id', None) is not None assert getattr(task, 'order_task_id', None) is not None
assert task.source_candidate_id is not None assert task.source_candidate_id is not None
assert task.current_order_extraction_id is not None assert task.current_order_extraction_id is not None
# 关键断言:复核确认建单必须同步冻结,库存/RPA 不可消费可变解析结果。
assert task.order_snapshot_id is not None
# 关键断言:复核确认已完成解析确认,不能把新任务重新放回低置信度解析复核。 # 关键断言:复核确认已完成解析确认,不能把新任务重新放回低置信度解析复核。
assert task.process_status == 'parsed' assert task.process_status == 'parsed'
assert task.review_status is None assert task.review_status is None
@@ -197,6 +197,49 @@ def test_inventory_matching_recovery_keeps_review_entry_when_primary_is_technica
] ]
def test_formal_inventory_matching_uses_only_executable_retries(app, monkeypatch):
"""正式 OT 库存匹配阻断不得投影无写操作的复核入口。"""
from types import SimpleNamespace
from app.services.shipping_notice import process_gate_projection as projection
execution = SimpleNamespace(
id=1, execution_no='EXE-INV-OT-1', status='blocked',
current_gate_code='inventory_matching', primary_next_action_code='open_inventory_match_review',
responsible_party='worker', lock_version=1, review_case_id=None, task_id=99,
)
monkeypatch.setattr(
projection,
'serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EXE-INV-OT-1', 'status': 'blocked',
'primary_next_action_code': 'open_inventory_match_review',
'responsible_party': 'worker',
'current_gate': {
'gate_code': 'inventory_matching',
'status': 'blocked_manual',
'blocking_reason_code': 'inventory_match_incomplete',
'next_action_code': 'open_inventory_match_review',
},
'recovery_targets': [
{'action_code': 'open_inventory_match_review', 'target_gate': 'inventory_matching'},
{'action_code': 'retry_inventory_from_preparation', 'target_gate': 'inventory_preparation'},
],
'gates': [], 'active_recovery_plans': [],
},
)
summary = projection.project_user_gate_summary(execution)
assert summary['next_action_code'] == 'retry_inventory_matching'
assert summary['allowed_actions'] == [
'retry_inventory_matching',
'retry_inventory_from_preparation',
]
assert summary['recovery_targets'] == [
{'action_code': 'retry_inventory_from_preparation', 'target_gate': 'inventory_preparation'},
]
def test_user_gate_summary_exposes_sanitized_failure_detail_for_any_gate(app, monkeypatch): def test_user_gate_summary_exposes_sanitized_failure_detail_for_any_gate(app, monkeypatch):
"""所有 Gate 均应把当前 Attempt 的脱敏失败详情投影给用户,而非只显示泛化原因。""" """所有 Gate 均应把当前 Attempt 的脱敏失败详情投影给用户,而非只显示泛化原因。"""
from types import SimpleNamespace from types import SimpleNamespace
@@ -13,11 +13,16 @@ Gate 的 responsible_party='worker' 被历史「worker/retry_ 技术动作屏蔽
from __future__ import annotations from __future__ import annotations
from types import SimpleNamespace
import pytest import pytest
from app.services.shipping_notice.process_gate_projection import ( from app.services.shipping_notice.process_gate_projection import (
_resolve_recovery_next_action, _resolve_recovery_next_action,
) )
from app.services.shipping_notice.process_gate_recovery_service import (
_primary_recovery_action,
)
@pytest.mark.pure_unit @pytest.mark.pure_unit
@@ -118,6 +123,51 @@ def test_inventory_matching_recovery_target_navigates_to_review():
assert action == 'open_inventory_match_review' assert action == 'open_inventory_match_review'
@pytest.mark.pure_unit
def test_formal_inventory_matching_recovery_target_retries_matching():
"""正式 OT 的库存匹配阻断必须下发可执行的重新库存匹配。"""
full, blocking = _mk(
{'gate_code': 'inventory_matching', 'status': 'blocked_manual',
'blocking_reason_code': 'inventory_match_failed'},
recovery_targets=[{'action_code': 'retry_inventory_from_preparation'}],
)
action, tech_only = _resolve_recovery_next_action(
blocking=blocking,
full=full,
execution=SimpleNamespace(task_id=99),
)
assert action == 'retry_inventory_matching'
assert tech_only is False
@pytest.mark.pure_unit
def test_formal_inventory_matching_request_validation_uses_retry_action():
"""正式 OT 的请求校验必须与用户投影一致,覆盖旧导航动作。"""
action = _primary_recovery_action(
execution=SimpleNamespace(task_id=99),
gate=SimpleNamespace(
gate_code='inventory_matching',
status='blocked_manual',
next_action_code='open_inventory_match_review',
),
)
assert action == 'retry_inventory_matching'
@pytest.mark.pure_unit
def test_inventory_matching_retryable_exposes_retry_action():
"""库存匹配 Gate 可重试时必须直接显示重新匹配按钮。"""
full, blocking = _mk(
{'gate_code': 'inventory_matching', 'status': 'blocked_retryable',
'blocking_reason_code': 'inventory_match_failed'},
)
action, technical_auto_only = _resolve_recovery_next_action(
blocking=blocking, full=full, execution=None,
)
assert action == 'retry_inventory_matching'
assert technical_auto_only is False
@pytest.mark.pure_unit @pytest.mark.pure_unit
def test_inventory_preparation_retryable_without_reason_uses_contract_action(): def test_inventory_preparation_retryable_without_reason_uses_contract_action():
"""无特定原因码、仅 blocked_retryable 时沿用 Gate 合同默认动作(retry_inventory_preparation)。""" """无特定原因码、仅 blocked_retryable 时沿用 Gate 合同默认动作(retry_inventory_preparation)。"""
@@ -114,6 +114,77 @@ def test_preparation_trigger_identity_includes_gate_and_callback(monkeypatch, ap
assert captured['callback_id'].endswith(':C1') assert captured['callback_id'].endswith(':C1')
def test_missing_inventory_trigger_is_failed_not_pending(monkeypatch, app):
"""trigger 写入返回空路径时,Attempt 必须失败,禁止伪装 queued。"""
from app import db
from app.models import ShippingNotice
from app.services.shipping_notice import per_source_rpa_service
task = ShippingNotice(task_no='SN-PREP-TRIGGER-MISSING', process_status='waiting_inventory')
db.session.add(task)
db.session.flush()
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)
monkeypatch.setattr(per_source_rpa_service, 'write_inventory_export_trigger_for_task', lambda *args, **kwargs: None)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_source_repository.get_database_inventory_source',
lambda code: {'source_code': code, 'warehouse_id': 'WH-1'},
)
result = per_source_rpa_service.ensure_all_required_sources_prepared(task, mode='retry_rpa')
assert result.pending_source_codes == []
assert result.failed_source_codes == ['DBS']
attempt = per_source_rpa_service._latest_attempt(task.task_no, 'DBS')
assert attempt.status == 'failed'
assert attempt.error_code == 'trigger_not_written'
def test_formal_gate_inventory_retry_uses_operator_id_for_snapshot_freeze(monkeypatch, app):
"""正式 Gate Worker 仅携带 operator_id 时,也必须先冻结快照再写 RPA trigger。"""
from app import db
from app.models import ShippingNotice, ShippingProcessExecution
from app.services.shipping_notice import process_gate_executor
task = ShippingNotice(
task_no='SN-PREP-FREEZE-OPERATOR', process_status='waiting_inventory',
order_snapshot_id=None, order_data_version=1,
)
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-PREP-FREEZE-OPERATOR', task_id=task.id,
current_gate_code='inventory_preparation', status='blocked',
)
db.session.add(execution)
db.session.flush()
seen = {}
monkeypatch.setattr(
'app.services.shipping_notice.order_freeze_service.freeze_order_snapshot',
lambda task, **kwargs: seen.update(kwargs) or object(),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
lambda **kwargs: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
lambda payload: {'status': 'running', 'data': {'rpa': {}}},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
lambda **kwargs: None,
)
gate = type('Gate', (), {'gate_code': 'inventory_preparation', 'status': 'blocked_manual', 'blocking_reason_code': None})()
result = process_gate_executor._handle_retry_inventory_preparation(
execution=execution, gate=gate,
payload={'action_code': 'retry_inventory_preparation', 'operator_id': 77},
)
assert seen['actor_id'] == 77
assert result['outcome'] in {'blocked_retryable', 'blocked_manual'}
def test_per_source_callback_rejects_candidate_set_identity_mismatch(app): def test_per_source_callback_rejects_candidate_set_identity_mismatch(app):
"""旧 CandidateSet 回调必须在写入库存事实前被拒绝。""" """旧 CandidateSet 回调必须在写入库存事实前被拒绝。"""
from app import db from app import db
@@ -308,6 +379,78 @@ def test_rpa_report_inventory_batch_fails_closed_on_per_source_identity_mismatch
).count() == 1 ).count() == 1
def test_batch_callback_inherits_authenticated_top_level_schema_version():
"""Worker 将 schema_version 放在 batch 顶层时,结果项仍须通过逐源身份校验。"""
from app.services.shipping_notice.inventory_rpa_workflow import _merge_batch_callback_item
merged = _merge_batch_callback_item(
{
'schema_version': 'shipping_inventory_rpa.v2',
'run_no': 'BATCH-1',
'task_no': 'SN-1',
},
{
'source_code': 'DSV360_AWSSG',
'source_run_no': 'PSR-SN-1-DSV360_AWSSG-A1-ABC',
},
)
assert merged['schema_version'] == 'shipping_inventory_rpa.v2'
assert merged['run_no'] == 'BATCH-1'
assert merged['task_no'] == 'SN-1'
def test_inventory_rpa_failure_is_not_projected_back_to_waiting_external(app):
"""RPA 已耗尽时自动轮询必须终态化,Gate 才能退出系统处理中。"""
from app import db
from app.models import ShippingNotice, ShippingProcessExecution, ShippingProcessGate, ShippingProcessGateAttempt
from app.services.shipping_notice.process_gate_bridge import sync_fulfillment_gates_from_task
from app.services.shipping_notice.process_gate_service import queue_gate_attempt
task = ShippingNotice(
task_no='SN-RPA-FAILED-GATE', process_status='waiting_inventory',
pending_human_reason='rpa_exhausted', error_message='RPA export failed',
)
db.session.add(task)
db.session.flush()
execution = ShippingProcessExecution(
execution_no='SPE-RPA-FAILED-GATE', task_id=task.id, status='waiting_external',
current_gate_code='inventory_preparation',
)
db.session.add(execution)
db.session.flush()
sync_fulfillment_gates_from_task(execution=execution)
gate = ShippingProcessGate.query.filter_by(
execution_id=execution.id, gate_code='inventory_preparation',
).one()
auto_poll = queue_gate_attempt(
execution_no=execution.execution_no,
gate_code='inventory_preparation',
trigger_type='auto',
actor_type='system',
idempotency_key='shipping-auto-progress:rpa-failed-poll',
input_snapshot={'action_code': 'poll_inventory_preparation'},
)
db.session.flush()
sync_fulfillment_gates_from_task(execution=execution)
db.session.refresh(auto_poll)
db.session.refresh(gate)
assert auto_poll.status == 'superseded'
assert auto_poll.error_code == 'rpa_callback_failed'
assert ShippingProcessGateAttempt.query.filter(
ShippingProcessGateAttempt.gate_id == gate.id,
ShippingProcessGateAttempt.status.in_(('queued', 'running')),
).count() == 0
assert gate.status == 'blocked_manual'
assert gate.blocking_reason_code == 'inventory_rpa_exhausted'
db.session.refresh(execution)
assert execution.status == 'blocked'
def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch): def test_formal_gate_attempt_creates_preparation_lineage_and_passes_gate(app, monkeypatch):
"""正式库存准备 Gate 执行必须创建 Preparation/Source lineage 并据此通过 Gate。""" """正式库存准备 Gate 执行必须创建 Preparation/Source lineage 并据此通过 Gate。"""
from app import db from app import db
@@ -749,6 +892,67 @@ def test_gate_executor_task_payload_uses_internal_orchestrator_dispatch(monkeypa
assert result['operator_id'] == 9 assert result['operator_id'] == 9
def test_inventory_preparation_retry_freezes_legacy_task_before_rpa(monkeypatch):
"""旧 Task 缺订单快照时,Gate 重试必须先冻结,不能再次返回快照缺失。"""
from types import SimpleNamespace
from app.services.shipping_notice.process_gate_executor import _handle_retry_inventory_preparation
task = SimpleNamespace(
order_snapshot_id=None,
order_data_version=7,
task_no='SN-LEGACY-SNAPSHOT-1',
)
captured = {}
monkeypatch.setattr(
'app.models.ShippingNotice.query',
SimpleNamespace(get=lambda _task_id: task),
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_executor.db.session.flush',
lambda: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.order_freeze_service.freeze_order_snapshot',
lambda target, **kwargs: captured.update(target=target, **kwargs) or setattr(target, 'order_snapshot_id', 901),
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_recovery_service.create_inventory_preparation_round',
lambda **_: None,
)
monkeypatch.setattr(
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
lambda _payload: {'status': 'running', 'message': 'waiting RPA'},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_bridge.inventory_preparation_reason_code',
lambda _task: 'inventory_preparation_failed',
)
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: {'task_id': task.task_no},
)
result = _handle_retry_inventory_preparation(
execution=SimpleNamespace(task_id=13, id=21),
gate=SimpleNamespace(gate_code='inventory_preparation'),
payload={'action_code': 'retry_inventory_preparation', 'actor_user_id': 5},
)
# 关键断言:正式 Gate 入口也补冻结,后续才允许进入库存 RPA。
assert captured == {
'target': task,
'actor_id': 5,
'expected_order_data_version': 7,
'freeze_mode': 'manual',
}
assert task.order_snapshot_id == 901
assert result['outcome'] == 'waiting_external'
def test_manual_business_block_is_a_successful_attempt(app): def test_manual_business_block_is_a_successful_attempt(app):
"""库存匹配已执行但存在缺口时,Attempt 成功、Gate 保持人工阻断。""" """库存匹配已执行但存在缺口时,Attempt 成功、Gate 保持人工阻断。"""
from app import db from app import db
@@ -429,3 +429,58 @@ def test_project_user_gate_summary_clears_stale_confirm_customer(monkeypatch):
summary = project_user_gate_summary(execution) summary = project_user_gate_summary(execution)
assert summary['current_blocking_gate'] is None assert summary['current_blocking_gate'] is None
assert summary['next_action_code'] is None assert summary['next_action_code'] is None
def test_project_user_gate_summary_exposes_retry_for_confirmed_inventory_pending_match(monkeypatch):
"""已确认库存快照而匹配仍 pending 时,必须给精确重匹配按钮。"""
execution = SimpleNamespace(execution_no='EX-MATCH-1', id=1, task_id=9, current_gate_code='inventory_matching')
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection.serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EX-MATCH-1', 'status': 'running', 'primary_next_action_code': None,
'responsible_party': 'worker', 'gates': [],
'current_gate': {'gate_code': 'inventory_matching', 'status': 'pending', 'blocking_reason_code': None},
},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection._has_confirmed_inventory_for_matching',
lambda _execution: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection._execution_navigation_refs',
lambda _execution: {'case_no': 'SORC-1', 'review_case_no': 'SORC-1', 'review_run_no': 'RUN-1', 'task_no': 'SN-1'},
)
summary = project_user_gate_summary(execution)
assert summary['current_blocking_gate']['status'] == 'blocked_retryable'
assert summary['next_action_code'] == 'retry_inventory_matching'
assert summary['allowed_actions'] == ['retry_inventory_matching']
def test_project_user_gate_summary_keeps_pending_match_system_owned_without_inventory(monkeypatch):
"""没有确认库存时不得伪造重匹配入口。"""
execution = SimpleNamespace(execution_no='EX-MATCH-2', id=2, task_id=10, current_gate_code='inventory_matching')
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection.serialize_process_execution',
lambda _execution, include_diagnostics=False: {
'execution_no': 'EX-MATCH-2', 'status': 'running', 'primary_next_action_code': None,
'responsible_party': 'worker', 'gates': [],
'current_gate': {'gate_code': 'inventory_matching', 'status': 'pending', 'blocking_reason_code': None},
},
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection._has_confirmed_inventory_for_matching',
lambda _execution: False,
)
monkeypatch.setattr(
'app.services.shipping_notice.process_gate_projection._execution_navigation_refs',
lambda _execution: {'case_no': None, 'review_case_no': None, 'review_run_no': None, 'task_no': 'SN-2'},
)
summary = project_user_gate_summary(execution)
assert summary['current_blocking_gate'] is None
assert summary['next_action_code'] is None
@@ -17,6 +17,41 @@ from app.services.shipping_notice.stp_line_inventory_match import (
) )
def test_current_match_facts_rebuild_shortage_detail(monkeypatch):
"""当前行事实有缺口时,工作台详情必须拿到数量和 shortage 状态。"""
from app.services.shipping_notice import fulfillment_workflow as mod
rows = [
SimpleNamespace(
line_index=0, line_key='line-1', match_result='matched',
part_number='PN-1', reservation_id='R1', unit='EA',
inventory_source_code='SRC', required_qty=3, available_qty=3,
shortage_qty=0,
),
SimpleNamespace(
line_index=1, line_key='line-2', match_result='not_found',
part_number='PN-2', reservation_id='R2', unit='EA',
inventory_source_code='SRC', required_qty=5, available_qty=0,
shortage_qty=5,
),
]
fake_match_model = SimpleNamespace(
query=SimpleNamespace(
filter_by=lambda **_kwargs: SimpleNamespace(all=lambda: rows),
),
)
monkeypatch.setattr(mod, 'ShippingNoticeLineInventoryMatch', fake_match_model)
task = SimpleNamespace(id=101, line_results_json=None, shortage_json=None)
status, shortages = mod._recompute_task_match_aggregate(task)
assert status == 'partial'
assert task.line_results_json[1]['available_qty'] == 0.0
assert task.line_results_json[1]['shortage_qty'] == 5.0
assert task.line_results_json[1]['line_status'] == 'shortage'
assert task.shortage_json == {'lines': shortages}
def test_cross_candidate_unique_hit_is_fulfillable(): def test_cross_candidate_unique_hit_is_fulfillable():
"""唯一候选文件命中且数量充足 → fulfillable 并冻结源。""" """唯一候选文件命中且数量充足 → fulfillable 并冻结源。"""
result = match_order_lines_across_candidates( result = match_order_lines_across_candidates(
@@ -0,0 +1,189 @@
# 货代通用报表 RPA API 接口文档
## 1. 接口范围与通用约定
本文定义方案新增 API。现有库存接口 `/api/shipping-notice/rpa/inventory-*` 不改路径、不改 `shipping_inventory_rpa.v2` 请求和响应语义;通用报表使用独立 schema 与回调 API。
浏览器管理端 API 使用标准 JSON Envelope:
```json
{
"success": true,
"data": {},
"request_id": "req_abc",
"timestamp": "2026-08-12T00:00:00Z"
}
```
失败统一为 `success=false`,`error.code` 使用 `<DOMAIN>.<SEMANTIC>`,前端通过 `requestJson` 处理。RPA Tool 回调沿用 `shipping_notice_tools` 的历史工具契约,返回 `ok/error_code/message`,不改为浏览器 Envelope。
认证约定:管理端使用现有登录会话/RBAC;Worker 使用机器身份认证、共享 scope 和能力声明;不得在 URL、日志或响应中返回明文凭据、Cookie、对象存储签名 URL。
## 2. 管理端定义与 Driver 模板 API
前缀:`/api/admin/freight-reports`。以下接口均要求管理员权限。
| 方法 | 路径 | 用途 | 请求要点 |
| --- | --- | --- | --- |
| GET | `/definitions` | 分页查询报表定义 | `source_code`、`file_purpose`、`status`、`page`、`page_size` |
| POST | `/definitions` | 新建定义草稿 | `source_code`、`file_purpose`、路径、参数、Warehouse 策略 |
| GET | `/definitions/{definition_id}` | 查看定义、当前版本和审计摘要 | 不返回密文凭据 |
| PATCH | `/definitions/{definition_id}` | 修改草稿 | 仅 draft;要求 `expected_version_no`,避免覆盖他人修改 |
| POST | `/definitions/{definition_id}/versions` | 从当前定义创建新草稿版本 | 发布版本不可原地修改 |
| POST | `/definitions/{definition_id}/test` | 启动一次管理员真实配置测试 | `definition_version_id`、单个 `warehouse_id`(Crane 为来源执行单位) |
| POST | `/definitions/{definition_id}/publish` | 发布定义版本 | 要求同 hash 成功测试、模板版本已发布 |
| POST | `/definitions/{definition_id}/retire` | 退役定义 | 已被启用排程引用时拒绝或先停排程 |
| GET | `/definitions/{definition_id}/versions` | 查询版本历史 | 支持按状态筛选 |
| GET | `/definitions/{definition_id}/audit` | 查询定义审计 | 返回脱敏 before/after、diff、事件 hash |
| GET | `/driver-templates` | 查询模板 | `connector_type`、`file_purpose`、`status` |
| POST | `/driver-templates` | 新建模板草稿 | 名称、连接器、受控 selector/等待/下载规则 |
| GET | `/driver-templates/{template_id}` | 查看模板与版本 | selector 仅管理员可见 |
| PATCH | `/driver-templates/{template_id}` | 修改草稿模板 | 服务端白名单校验 |
| POST | `/driver-templates/{template_id}/versions` | 创建新模板版本 | 发布版本只读 |
| POST | `/driver-templates/{template_id}/test` | 启动模板配置测试 | 绑定定义版本和执行单位 |
| POST | `/driver-templates/{template_id}/publish` | 发布模板版本 | 必须有成功测试且 hash 一致 |
| POST | `/driver-templates/{template_id}/retire` | 退役模板 | 被已发布定义引用时禁止直接删除 |
### 2.1 定义草稿请求示例
```json
{
"source_code": "AWSBI",
"file_purpose": "receipt",
"report_path": {
"customer": "AWS",
"program": "Bison",
"program_label": "AWSBI",
"report_group": "Inbound",
"report_name": "Receipt Detail"
},
"parameters": {
"report_date": null,
"owner": {"mode": "portal_default"},
"type": {"mode": "portal_default"}
},
"warehouse_policy": {
"mode": "fixed",
"warehouse_ids": ["WH-A", "WH-B"]
}
}
```
服务端拒绝:空用途、未配置固定 Warehouse 的 DBS、日期被设置为非 NULL 筛选、未知参数、任意脚本、selector 非白名单或普通用户写请求。
## 3. 配置测试 API
测试只允许管理员调用,使用 `mode=test`,产物进入 test 前缀,三年保留,不推送企微、不写正式库存。
| 方法 | 路径 | 用途 |
| --- | --- | --- |
| POST | `/api/admin/freight-reports/tests` | 创建测试运行 |
| GET | `/api/admin/freight-reports/tests/{test_run_no}` | 查询测试状态、步骤、文件 hash |
| POST | `/api/admin/freight-reports/tests/{test_run_no}/cancel` | 取消尚未领取的测试 |
创建请求必须指定一条 definition/template 草稿版本和一个执行单位。成功响应返回 `test_run_no`、`unit_run_no`、`status=queued`、`content_hash`;服务端不接受管理员直接上传测试结果。
## 4. 通用报表排程与运行 API
排程定义复用现有 Schedule API;`platform_api_path` 固定为 `freight-general-report-rpa`,`job_params` 至少包含 `source_codes`、`file_purposes`,Cron、时区和接收人使用现有字段。
| 方法 | 路径 | 用途 | 权限 |
| --- | --- | --- | --- |
| GET | `/api/schedules/options?job=freight-general-report-rpa` | 返回满足已发布定义条件的来源/用途选项 | 登录用户只读 |
| POST/PATCH | 现有 Schedule Task 接口 | 新建/编辑排程 | 管理员 |
| POST | 现有 Schedule Task 启停接口 | 启停排程 | 管理员 |
| GET | `/api/freight-reports/runs` | 查询父运行分页列表 | 管理员/授权业务用户 |
| GET | `/api/freight-reports/runs/{parent_run_no}` | 查看父运行和单元明细 | 管理员/授权业务用户 |
| GET | `/api/freight-reports/units/{unit_run_no}` | 查看单元、Artifact、通知和脱敏审计 | 管理员/授权业务用户 |
| POST | `/api/admin/freight-reports/units/{unit_run_no}/retry` | 手工重试一个失败单元 | 管理员 |
| GET | `/api/freight-reports/artifacts/{artifact_no}/download` | 授权下载原始文件 | 管理员/授权接收人 |
| GET | `/api/freight-reports/runs/{parent_run_no}/audit` | 查询运行审计摘要 | 管理员完整,业务用户脱敏 |
重试请求:`{"reason":"Crane 页面超时,已确认配置正常"}`。响应返回新 `parent_run_no/unit_run_no`,原失败单元保持不变。
下载接口不把下载 URL 写入审计;审计记录 artifact、操作者、时间、授权结果和 `request_id`。文件过期后返回 `FREIGHT_REPORT.ARTIFACT_EXPIRED`。
## 5. Worker 心跳与通用回调 API
### 5.1 心跳
保留 `POST /api/shipping-notice/rpa/heartbeat`,新增能力字段,不改变旧字段语义:
```json
{
"worker_id": "freight-v2-01",
"worker_version": "2.0.0",
"capabilities": ["inventory_v2", "freight_general_report_v1"],
"shared_scope_id": "scope-test-01",
"runtime_status": "idle",
"sent_at": "2026-08-12T00:00:00Z"
}
```
后端就绪检查仅将声明 `inventory_v2` 或 `freight_general_report_v1` 且 scope、环境、TTL 合法的 Worker 视为可用。
### 5.2 通用报表领取回调
`POST /api/shipping-notice/rpa/general-report-claimed`
请求包含 `schema_version`、`callback_id`、`unit_run_no`、`worker_execution_id`、`claimed_at`、`worker_id`。该回调只记录领取事实,不推进成功终态。
### 5.3 通用报表结果回调
`POST /api/shipping-notice/rpa/general-report-ready`
成功示例:
```json
{
"schema_version": "freight_general_report.v1",
"callback_id": "GRU-20260812-001:C1",
"unit_run_no": "GRU-20260812-001-U01",
"worker_execution_id": "WEX-9f2",
"status": "succeeded",
"artifact": {
"file_path": "drop/GRU-20260812-001-U01.xlsx",
"original_name": "Receipt_Detail_WH-A.xlsx",
"size_bytes": 18342,
"sha256": "<64 hex chars>",
"content_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
},
"diagnostics": {"trace_ref": "trace-hash", "steps": ["login", "navigate", "download"]}
}
```
失败示例:`status=failed`,包含 `error_code`、脱敏 `error_message` 和 `failed_step`,不得携带页面 HTML、Cookie 或凭据。
处理规则:认证、UnitRun 归属、版本 hash、文件存在性、大小/扩展名/SHA-256、状态机和 callback 唯一性全部通过后才归档;重复 callback 返回 `ok=true`、`result=ignored`,不重复副作用。
### 5.4 通用测试回调
`POST /api/shipping-notice/rpa/general-report-test-ready` 与正式回调字段一致,但必须 `mode=test`,只写测试 Artifact 和测试审计,不允许正式通知或库存入库。
## 6. 响应与错误码
标准管理 API 错误码:
| HTTP | code | 场景 |
| --- | --- | --- |
| 400 | `FREIGHT_REPORT.INVALID_PARAM` | 用途、路径、参数或 selector 不合法 |
| 401 | `AUTH.UNAUTHORIZED` | 未登录或 Worker 认证失败 |
| 403 | `AUTH.FORBIDDEN` | 普通用户调用管理/重试或未授权下载 |
| 404 | `RESOURCE.NOT_FOUND` | 定义、运行或 Artifact 不存在 |
| 409 | `FREIGHT_REPORT.VERSION_CONFLICT` | 草稿版本并发编辑或发布 hash 不一致 |
| 409 | `FREIGHT_REPORT.INVALID_STATE` | 非法状态迁移、已发布版本修改 |
| 409 | `FREIGHT_REPORT.DUPLICATE_CALLBACK` | callback 已被其他单元使用 |
| 410 | `FREIGHT_REPORT.ARTIFACT_EXPIRED` | 文件超过三年保留期 |
| 422 | `FREIGHT_REPORT.PUBLISH_GATE_FAILED` | 未通过同 hash 配置测试 |
| 503 | `RPA.WORKER_OFFLINE` | 无可用 v2 Worker 或共享目录不可用 |
| 503 | `RPA.CALLBACK_UNAVAILABLE` | 回调处理依赖不可用 |
新增错误码必须同步 `frontend/src/locales/{zh-CN,zh-TW,en,th}/errors.json`。所有接口响应包含 `request_id`,Worker 日志按该 ID 与 `correlation_id` 关联。
## 7. 接口验收标准
- 管理员可完成定义/模板草稿、测试、发布、退役闭环;普通用户所有写接口返回 403。
- 相同 callback 重放只产生一条 Artifact、一组通知投递和一条 `ignored` 审计,不重复副作用。
- 非法 selector、明文凭据、非 NULL 日期筛选、未发布版本和过期下载均被服务端拒绝。
- 既有库存 callback API 回归测试通过;通用回调不会写入 `shipping_inventory_files`,库存桥接仅处理 `file_purpose=inventory`。
- OpenAPI/接口契约测试覆盖成功 Envelope、错误 Envelope、Tool 回调契约、权限、幂等和下载审计。
@@ -0,0 +1,168 @@
# 货代通用报表 RPA 数据库设计文档
## 1. 设计原则
数据库使用 PostgreSQL + SQLAlchemy 2.0 + Alembic。新增模型集中于 `backend/app/models/freight_report.py`,迁移只新增通用报表表,不修改 `shipping_inventory_files`。所有时间使用 UTC `DateTime`;JSON 仅存结构化快照和脱敏证据,凭据始终沿用 `shipping_rpa_profiles` 的密文配置。
复用表:`schedule_tasks`(排程)、`schedule_runs`(平台调度事实)、`shipping_inventory_sources`(站点/仓库身份)、`shipping_rpa_profiles`(登录连接)、`users`(操作者/接收人)、`shipping_audit_events`(不可变审计)。
## 2. ER 关系
```text
ShippingInventorySource 1--* FreightReportDefinition 1--* FreightReportDefinitionVersion
FreightReportDriverTemplate 1--* FreightReportDriverTemplateVersion
ScheduleTask 1--* ScheduleRun 1--1 FreightReportParentRun 1--* FreightReportUnitRun
FreightReportDefinitionVersion 1--* FreightReportUnitRun
FreightReportDriverTemplateVersion 1--* FreightReportUnitRun
FreightReportUnitRun 1--* FreightReportArtifact
FreightReportUnitRun/ParentRun 1--* FreightReportNotificationDelivery
所有聚合对象 --soft reference--> ShippingAuditEvent
```
## 3. 新增表
### 3.1 `freight_report_driver_templates`
| 字段 | 类型 | 约束/说明 |
| --- | --- | --- |
| `id` | bigint PK | 自增 |
| `template_code` | varchar(64) | `UNIQUE NOT NULL`,稳定业务编号 |
| `name` | varchar(128) | `NOT NULL` |
| `connector_type` | varchar(32) | `CHECK IN ('dbs','crane')` |
| `status` | varchar(16) | `draft/tested/published/retired` |
| `current_published_version_id` | bigint nullable | 发布版本指针,迁移后补 FK |
| `created_by/updated_by` | bigint nullable | FK `users.id` |
| `created_at/updated_at` | timestamp | `NOT NULL` |
索引:`(connector_type,status)`;引用中的模板不得物理删除。
### 3.2 `freight_report_driver_template_versions`
| 字段 | 类型 | 约束/说明 |
| --- | --- | --- |
| `id` | bigint PK | 自增 |
| `template_id` | bigint | FK 到模板,`NOT NULL` |
| `version_no` | integer | `UNIQUE(template_id,version_no)` |
| `status` | varchar(16) | 同生命周期;发布/退役版本不可更新 |
| `selector_json` | jsonb | 仅 allowlist key/locator,禁止脚本 |
| `timeout_json` | jsonb | 正整数超时/轮询配置 |
| `download_rule_json` | jsonb | 文件名、扩展名、最小大小、校验规则 |
| `content_hash` | varchar(64) | SHA-256,`NOT NULL` |
| `tested_at/published_at/retired_at` | timestamp nullable | 生命周期事实 |
| `created_by/created_at` | bigint/timestamp | 创建事实 |
索引:`(template_id,status,version_no DESC)`、`content_hash`。服务和 ORM 禁止更新发布版本;数据库迁移加入触发器或 rule,阻断 UPDATE/DELETE。
### 3.3 `freight_report_definitions`
| 字段 | 类型 | 约束/说明 |
| --- | --- | --- |
| `id` | bigint PK | 自增 |
| `definition_code` | varchar(64) | `UNIQUE NOT NULL` |
| `inventory_source_id` | bigint | FK `shipping_inventory_sources.id` |
| `file_purpose` | varchar(16) | `inventory/receipt/shipment` |
| `status` | varchar(16) | 生命周期状态 |
| `current_published_version_id` | bigint nullable | 发布版本指针 |
| `created_by/updated_by/created_at/updated_at` | 审计字段 | 与现有模型一致 |
约束:`UNIQUE(inventory_source_id,file_purpose)`,保证一个来源+用途只有一个定义实体;启用条件由已发布版本判断,不额外创建可漂移的 enabled 字段。
### 3.4 `freight_report_definition_versions`
| 字段 | 类型 | 约束/说明 |
| --- | --- | --- |
| `id` | bigint PK | 自增 |
| `definition_id` | bigint | FK 定义 |
| `version_no` | integer | `UNIQUE(definition_id,version_no)` |
| `template_version_id` | bigint | FK 模板版本,`NOT NULL` |
| `report_path_json` | jsonb | DBS/Crane 路径或报表名 |
| `parameters_json` | jsonb | 业务参数;日期 NULL/default 表示不覆盖页面默认值 |
| `warehouse_policy_json` | jsonb | DBS 固定 Warehouse 列表;Crane 为空/来源粒度 |
| `content_hash` | varchar(64) | `NOT NULL` |
| `status/tested_at/published_at/retired_at` | 生命周期字段 | 同模板版本 |
| `created_by/created_at` | 审计字段 | |
索引:`(definition_id,status,version_no DESC)`、`(template_version_id)`;发布时模板版本必须是 published,成功测试 hash 必须相同。
### 3.5 `freight_report_parent_runs`
| 字段 | 类型 | 约束/说明 |
| --- | --- | --- |
| `id` | bigint PK | 自增 |
| `parent_run_no` | varchar(64) | `UNIQUE NOT NULL` |
| `schedule_run_id` | bigint | `UNIQUE FK schedule_runs.id` |
| `mode` | varchar(16) | `production/test/retry` |
| `status` | varchar(32) | `queued/running/success/partial_failed/failed` |
| `definition_selection_snapshot_json` | jsonb | 来源/用途/版本冻结快照 |
| `notify_snapshot_json` | jsonb | 接收人 ID 快照,不存通讯录敏感字段 |
| `started_at/finished_at` | timestamp nullable | |
| `created_by/created_at` | 审计字段 | |
索引:`(status,created_at DESC)`、`(schedule_run_id)`。
### 3.6 `freight_report_unit_runs`
| 字段 | 类型 | 约束/说明 |
| --- | --- | --- |
| `id` | bigint PK | 自增 |
| `parent_run_id` | bigint | FK 父运行 |
| `unit_run_no` | varchar(64) | `UNIQUE NOT NULL` |
| `source_code` | varchar(64) | 来源快照,避免历史配置改写事实 |
| `file_purpose` | varchar(16) | 枚举约束 |
| `warehouse_id` | varchar(64) nullable | DBS 必填,Crane 可空 |
| `definition_version_id/template_version_id` | bigint | FK 已发布版本 |
| `definition_snapshot_json/driver_snapshot_json` | jsonb | 完整发布快照、脱敏 |
| `status` | varchar(16) | `queued/dispatched/running/succeeded/failed/cancelled` |
| `callback_id` | varchar(128) | `UNIQUE NOT NULL` |
| `worker_execution_id` | varchar(64) nullable | Worker 执行事实 |
| `retry_of_id` | bigint nullable | 自引用 FK,只能指向 failed 单元 |
| `error_code/error_message` | varchar(64)/text nullable | 脱敏错误 |
| `dispatched_at/claimed_at/finished_at/created_at` | timestamp | 生命周期时间 |
约束:`UNIQUE(parent_run_id,definition_version_id,warehouse_id)`;PostgreSQL 对 NULL 不相等,因此 Crane 使用空字符串规范化值,或采用 `UNIQUE NULLS NOT DISTINCT`(按目标 PostgreSQL 版本确定)。索引:`(parent_run_id,status)`、`(source_code,file_purpose,created_at DESC)`、`(callback_id)`、`(retry_of_id)`。
### 3.7 `freight_report_artifacts`
| 字段 | 类型 | 约束/说明 |
| --- | --- | --- |
| `id` | bigint PK | 自增 |
| `artifact_no` | varchar(64) | `UNIQUE NOT NULL` |
| `unit_run_id` | bigint | FK 单元运行 |
| `storage_key` | varchar(500) | `UNIQUE NOT NULL`,仅内部对象定位 |
| `original_name` | varchar(255) | 原始文件名 |
| `content_type` | varchar(128) | |
| `size_bytes` | bigint | `CHECK > 0` |
| `sha256` | char(64) | `NOT NULL` |
| `retention_expires_at` | timestamp | `NOT NULL`,创建后约三年 |
| `deleted_at/deleted_reason` | timestamp/varchar(64) nullable | 到期删除对象事实 |
| `created_at` | timestamp | |
约束:`UNIQUE(unit_run_id,sha256)`,防重复归档;索引 `(retention_expires_at,deleted_at)`、`(unit_run_id,created_at)`、`sha256`。不存完整下载 URL;到期后 `storage_key` 可保留摘要或按数据治理规则脱敏,Artifact 行不得删除。
### 3.8 `freight_report_notification_deliveries`
| 字段 | 类型 | 约束/说明 |
| --- | --- | --- |
| `id` | bigint PK | 自增 |
| `parent_run_id/unit_run_id/artifact_id` | bigint nullable | 至少一个关联对象;文件消息关联 artifact,汇总关联 parent |
| `recipient_user_id` | bigint | FK `users.id` |
| `message_type` | varchar(16) | `file/summary` |
| `idempotency_key` | varchar(160) | `UNIQUE NOT NULL` |
| `media_id_hash` | varchar(64) nullable | 不保存媒体 ID 明文 |
| `status` | varchar(16) | `pending/sent/failed` |
| `provider_response_redacted_json` | jsonb | 企微响应脱敏摘要 |
| `sent_at/created_at` | timestamp nullable | |
索引:`(parent_run_id,status)`、`(recipient_user_id,created_at DESC)`。服务端按唯一幂等键防重复推送。
## 4. 完整性、审计与迁移
1. 所有 FK 默认 `RESTRICT` 或不设级联删除;运行、版本和 Artifact 历史不可由上游配置删除抹去。
2. `file_purpose`、连接器、状态、模式均使用 PostgreSQL `CHECK`,不创建数据库 Enum,降低多环境迁移耦合。
3. 版本发布后应用层与数据库层双重拒绝 UPDATE/DELETE;草稿修改通过新增修订或允许更新并留下 `ShippingAuditEvent` 前后快照,最终实现以不可变版本新建为准。
4. 审计不新增平行审计表,复用 `shipping_audit_events` 的 append-only trigger、哈希链、IP/UA hash 与永久保留。`aggregate_type` 取 `freight_report_definition`、`freight_report_template`、`freight_report_parent_run`、`freight_report_unit_run`、`freight_report_artifact`。
5. Alembic 迁移顺序:建模板/定义主表 -> 建版本表 -> 回填发布指针 FK -> 建运行/Artifact/通知表 -> 建索引/检查约束/不可变触发器。迁移必须在空库和现有库升级验证。
## 5. 数据生命周期与容量
运行、版本、通知投递和审计永久保留。Artifact 文件对象及测试文件保留三年;定时清理仅对 `retention_expires_at <= now()` 且 `deleted_at IS NULL` 的对象执行,成功后写 `deleted_at/deleted_reason` 和审计。对象删除失败保留待重试状态,禁止删除数据库记录。
@@ -0,0 +1,484 @@
# 货代通用报表 RPA 分阶段实施设计
## 1. 文档状态
| 项目 | 内容 |
| --- | --- |
| 状态 | 已确认设计,待实施计划评审 |
| 日期 | 2026-08-12 |
| 范围 | DBS / Crane 的库存、收料、出货报表定时导出、快照归档、企微推送、审计和新 Worker 切换 |
| 明确不做 | 报表内容解析、库存自动匹配、ERP 写入、自动重试、节假日规则、旧 Worker 并行消费 |
| 实施原则 | 不修改现有 `scripts/rpa/freight_rpa_worker.py`;允许新增或调整后端的 v2 适配、能力识别和切换配置,但冻结既有库存 trigger、callback 与入库业务契约;先新建 Worker 并完成真实测试,再停旧 Worker 并切换 |
## 1.1 配套详细设计与数据库设计
本文件说明范围、决策、线框与分阶段验收;实施细节和数据库物理设计以下列文档为准:
- [详细设计说明](2026-08-12-freight-general-report-rpa-detailed-design.md):组件边界、请求/回调协议、状态机、幂等、权限、异常、切换与回退。
- [数据库设计文档](2026-08-12-freight-general-report-rpa-database-design.md):表、字段、外键、约束、索引、审计与保留策略。
- [API 接口文档](2026-08-12-freight-general-report-rpa-api.md):管理端、运行中心、文件下载、Worker 回调、权限、幂等和错误码。
## 2. 已确认业务规则
1. 新建一个平台排程:`freight-general-report-rpa`(货代通用报表 RPA)。现有 `shipping-inventory-rpa` 排程保留不动,直至新 Worker 准入通过后由管理员停用。
2. 一条排程可选择 `inventory`、`receipt`、`shipment` 任意组合;所有选中类型共享同一 Cron、同一时区、同一接收人和同一启停状态。
3. 排程选择既有库存源,不重复填写站点、登录、路径、仓库或技术 selector。
4. DBS:每个固定 Warehouse 分别导出一份文件;收料路径为 `AWS / Bison / AWSBI / Inbound / Receipt Detail`,出货路径为 `AWS / Bison / AWSBI / Outbound / Shipment Order Detail`;日期字段保持页面 `NULL`,Owner、Type 等不覆盖页面默认值。
5. Crane:库存源本身承担 Warehouse 区分;每个库存源分别新建 `On Hand Details`、`Inbound Details`、`Outbound Details` 报表,使用本次运行唯一 Description 轮询完成后下载,禁止下载历史列表中的最新文件。
6. 三类文件均写入通用报表快照,原样归档并推送企微。仅 `inventory` 在完成通用快照后,调用既有库存快照入库回调;排程本身不触发库存匹配、锁定、订单推进或 ERP 操作。
7. 收料、出货绝不写入 `ShippingInventoryFile`,也不进入库存匹配链路。
8. 成功的每个文件均向当前排程接收人单独发送企微文件消息;所有执行单元结束后发送一条汇总卡片。部分失败仍推送成功文件和失败明细;全部失败只推送汇总失败卡片。
9. 排程不自动重试。管理员可手动重试失败的单个执行单元;重试创建新的运行、快照、文件和审计,不覆盖历史。
10. 原始正式和测试 Excel 都保留 3 年;文件到期后删除对象。审计永久保留,包含删除事件、SHA-256、关联运行和存储定位摘要。
11. 普通业务用户只有运行、文件和审计摘要的查看权限,以及作为企微接收人;无配置、发布、启停、测试、重试或恢复权限。管理员拥有全部治理权限。
12. 报表定义和 Driver 模板均采用 `draft -> tested -> published -> retired`。正式运行只读取不可变的已发布版本。
13. 配置测试仅管理员可执行,对一条草稿定义和一个执行单位运行真实 RPA;结果进入测试快照,不推送企微、不写正式快照、不进入库存业务。
14. 新 Worker 与旧 Worker 不并行运行。上线前新 Worker 必须在测试环境完成 DBS 与 Crane 的三类报表真实导出,并连续 5 个工作日成功处理既有库存 RPA;准入后可修改后端的 Worker 能力识别、版本校验或切换配置,停旧 Worker 后再启动新 Worker 处理生产目录。失败时停新 Worker 并回退旧 Worker。
15. “库存导出无感切换”仅指既有库存排程、`shipping_inventory_rpa.v2` trigger、既有 inventory callback API、库存快照入库及下游业务行为保持兼容;不表示后端零改动。切换所需后端改动只能用于 v2 Worker 识别、能力校验、路由/开关和新增通用报表能力,不得改变上述既有库存业务契约。
## 3. 设计目标与边界
### 3.1 目标
```text
管理员发布配置和排程
-> 排程按 Cron 创建父运行
-> 对 (库存源 x 勾选报表类型 x DBS Warehouse) 展开执行单元
-> 新 Worker 执行并回调
-> 通用文件快照、三年归档、文件级企微推送
-> 父运行汇总通知、可追溯审计、可定点人工重试
```
### 3.2 不可突破的领域边界
| 对象 | 责任 | 不允许承担 |
| --- | --- | --- |
| Inventory Source | 既有业务站点、RPA Profile、固定 Warehouse、库存领域身份 | 收料/出货文件的生命周期或 selector |
| Freight Report Definition | 每个库存源的报表用途、路径、业务参数、已发布模板引用 | 明文凭据、任意脚本 |
| Driver Template | 受控 selector、等待、下载与验证规则 | 业务仓库选择、接收人、任意 JavaScript |
| General Report Snapshot | 原始文件、校验值、归档、下载及其运行事实 | Excel 字段解析、库存匹配、ERP 写入 |
| Inventory callback bridge | 将 `inventory` 通用成功结果送入既有库存入库协议 | 驱动 receipt/shipment 的库存业务 |
| Windows Worker | 消费已发布快照、浏览器操作、文件回传 | 修改配置、直接访问数据库、发送企微 |
## 4. 行业实践与选型结论
本方案吸收 Playwright、Temporal、n8n 的成熟思路,但不引入它们作为新增运行时依赖。
| 可借鉴实践 | 行业来源 | 本项目落地方式 |
| --- | --- | --- |
| 浏览器上下文隔离、可诊断 trace、稳定 locator 优先、下载回读 | [microsoft/playwright](https://github.com/microsoft/playwright),约 94k Stars(2026-08-12 查询) | 新 Worker 每个执行单元隔离 Page/Context;保存脱敏 trace/截图索引;下载后 SHA-256、扩展名、最小大小及文件名规则校验 |
| 持久运行状态、幂等回调、不可变历史、人工重试 | Temporal 的 durable execution 模式 | 不新建 Temporal 集群;复用 `ScheduleRun + Job`,新增父运行/单元运行与 callback idempotency key,显式状态机收口 |
| 已发布版本、凭据与执行节点分离、失败可观测 | [n8n-io/n8n](https://github.com/n8n-io/n8n),约 200k Stars(2026-08-12 查询) | 定义、Driver 模板、RPA Profile 三层分离;发布版本快照下发 Worker;配置测试与正式运行隔离 |
| 企业 RPA 的受控资产、机器人身份、日志证据 | Robocorp 等 RPA 平台通用实践 | Worker 使用机器身份和受控密钥;后端拥有审计与通知;不允许浏览器脚本承载业务决策 |
选择理由:当前项目已有 Flask、SQLAlchemy、PostgreSQL、Redis、Windows Playwright Worker、目录触发和 Job/Schedule 基础。新增独立 Worker 和领域模型的风险、运维成本均小于引入新的工作流引擎;同时通过不可变版本、幂等回调、审计链和人工重试获得可接受的可靠性。
## 5. 总体架构与协议
```text
Admin Vue
| 定义/模板/测试/发布/排程/重试
v
Flask API -- PostgreSQL
| |- published definition/template snapshots
| |- parent run / unit run / artifact / audit events
v
Schedule Worker -- Job queue -- General report trigger JSON
|
v
Windows freight_report_worker_v2.py
|- legacy inventory trigger: existing protocol/callback
|- general report trigger: v1 protocol/new callback
|- DBS driver / Crane driver
|
v
Shared drop directory -> callback API -> archive + WeCom
```
### 5.1 新协议
```json
{
"schema_version": "freight_general_report.v1",
"action": "general_report_export",
"callback_id": "GRU-...:C1",
"worker_execution_id": "WEX-...",
"mode": "production",
"unit_run_no": "GRU-...",
"definition_snapshot": {
"definition_version_no": 3,
"template_version_no": 5,
"connector_type": "dbs",
"source_code": "AWSBI",
"file_purpose": "receipt",
"warehouse_id": "...",
"report_path": { "customer": "AWS", "program": "Bison", "program_label": "AWSBI", "report_group": "Inbound", "report_name": "Receipt Detail" },
"parameters": []
},
"driver_snapshot": { "selector_profile": "published and allowlisted", "timeouts": {} },
"credential_envelope": { "encrypted": true }
}
```
规则:Worker 只能读取其中的发布快照;不接收明文密码、不接收 JavaScript、不接收对象存储签名 URL;`callback_id` 全局唯一并且 callback 只能首次改变单元终态。
### 5.2 执行状态机
```text
draft definition -> tested -> published -> retired
parent run: queued -> running -> success | partial_failed | failed
unit run: queued -> dispatched -> running -> succeeded | failed | cancelled
test unit: queued -> dispatched -> running -> succeeded | failed
failed --管理员手动重试--> 新 unit run(queued)
```
状态只允许向终态推进。Worker 回调、文件归档、企微发送各有 idempotency key。任何重复 callback 只记录 `ignored` 审计事件,不重复存档或发消息。
## 6. 数据与审计设计
### 6.1 新实体
| 表/实体 | 核心字段 | 约束 |
| --- | --- | --- |
| `freight_report_driver_templates` | connector_type、name、status、current_published_version_id | 管理员维护;删除受引用对象被拒绝 |
| `freight_report_driver_template_versions` | template_id、version_no、status、selector_json、timeout_json、download_rule_json、content_hash、tested_at、published_at | 发布后不可更新;selector key 必须白名单 |
| `freight_report_definitions` | inventory_source_id、file_purpose、status、current_published_version_id | 每 Source + purpose 仅一个活动定义 |
| `freight_report_definition_versions` | definition_id、version_no、template_version_id、report_path_json、parameters_json、warehouse_policy_json、content_hash、tested_at、published_at | 发布后不可更新;业务参数与技术 selector 分离 |
| `freight_report_parent_runs` | schedule_run_id、run_no、mode、status、definition_selection_snapshot_json、notify_snapshot_json | 一次排程一个父运行 |
| `freight_report_unit_runs` | parent_run_id、unit_run_no、source_code、file_purpose、warehouse_id、definition_version_id、template_version_id、status、callback_id、retry_of_id | 唯一键:父运行+定义版本+Warehouse;callback id 全局唯一 |
| `freight_report_artifacts` | unit_run_id、artifact_no、storage_key、original_name、size_bytes、sha256、retention_expires_at、deleted_at、deleted_reason | 文件到期后只删除对象,行永久保留 |
| `freight_report_notification_deliveries` | unit_run_id/parent_run_id、user_id、message_type、media_id、status、provider_response_redacted_json | 每用户+文件/汇总幂等 |
`file_purpose` 只能为 `inventory`、`receipt`、`shipment`。所有运行和 artifact 使用独立编号,不复用库存快照编号。
### 6.2 审计硬约束
复用 `ShippingAuditEvent` 的 append-only ORM/数据库保护及哈希链,不创建可改写的第二套审计表。事件的 `aggregate_type` 取 `freight_report_definition`、`freight_report_template`、`freight_report_parent_run`、`freight_report_unit_run` 或 `freight_report_artifact`。
每个业务动作必须写审计:
| 节点 | actor | 必填快照/证据 |
| --- | --- | --- |
| 新建、编辑、删除草稿 | admin | before/after 白名单快照、diff、请求人、时间、IP/UA 哈希 |
| 配置测试开始/结束 | admin / worker | 测试定义和模板版本、选定 Warehouse、callback id、脱敏诊断证据 |
| 发布/退役 | admin | 已测版本、内容 hash、前后状态、理由 |
| 排程创建、编辑、启停 | admin | Cron、报表类型、库存源、接收人快照前后对比 |
| 计划触发与单元展开 | system | parent/unit 编号、定义/模板/接收人发布快照 |
| Worker 领取、导航、参数应用、下载、回调 | worker | 机器 ID、版本、时间、步骤结果、脱敏 trace 引用、错误码 |
| 文件写入、校验、归档、到期删除 | system | 原始名、大小、SHA-256、对象 key 摘要、保留到期日、删除理由 |
| 企微文件/汇总发送 | system | 接收人、消息类型、媒体 ID 摘要、响应脱敏摘要、发送结果 |
| 手动重试 | admin | 原失败单元、失败原因、新旧运行关联、管理员理由 |
| 查看和下载 | user/admin | 读取人、对象、时间、授权结果;不把下载 URL 写入审计 |
敏感信息规则:绝不写明文凭据、完整对象 URL、cookie、HTML 全量内容、原始 IP 或 UA。selector 可存于受限模板版本;审计中只存 selector/version/hash 和最少的失败证据。
## 7. 核心页面 MD 线框
### 7.1 报表定义管理(管理员)
```text
+--------------------------------------------------------------------------------+
| 货代报表定义 [配置测试] [新建定义] |
+--------------------+-----------------------------------------------------------+
| 库存源筛选 | Source | 类型 | 已发布版本 | 模板 | 状态 | 最近测试 | 操作 |
| [DBS/Crane v] | AWSBI | 库存 | v3 | DBS v5| 已发布| 08-12 | 编辑 |
| 用途 [全部 v] | AWSBI | 收料 | v2 | DBS v5| 草稿 | -- | 编辑 |
| 状态 [全部 v] | AWSBI | 出货 | v2 | DBS v5| 已发布| 08-12 | 查看 |
| [搜索_________] | ... |
+--------------------+-----------------------------------------------------------+
| 右侧详情 Drawer: 路径 / 固定 Warehouse / 参数覆盖 / 版本记录 / 审计时间线 |
+--------------------------------------------------------------------------------+
```
- 仅管理员可见新增、编辑、测试、发布、退役;普通用户无该路由权限。
- 路径、固定 Warehouse 与参数属于定义版本;selector、超时、下载规则不可在此页编辑,只展示绑定模板版本。
- 草稿编辑先写 before/after 审计;发布必须存在与内容 hash 匹配的成功配置测试。
### 7.2 Driver 模板编辑与发布(管理员)
```text
+--------------------------------------------------------------------------------+
| Driver 模板 / DBS Receipt v5 [保存草稿] [配置测试] [发布]|
+----------------------+---------------------------------------------------------+
| 左: 版本列表 | 右: 受控编辑表单 |
| v5 草稿 | Connector: DBS Purpose: Receipt |
| v4 已发布 | [导航 selector 组] [参数控件 selector 组] |
| v3 已退役 | [创建/下载 selector 组] [超时/轮询] [文件验证规则] |
| | 允许键仅白名单,CSS 长度/字符集校验,无脚本输入 |
+----------------------+---------------------------------------------------------+
| 测试证据:测试运行号、时间、Worker 版本、下载 SHA-256、失败步骤、审计链接 |
+--------------------------------------------------------------------------------+
```
- 模板编辑权限仅管理员;不允许自由 JavaScript、URL 回调或 Secret 字段。
- 发布后不可编辑,只能复制为新草稿版本;所有正式单元固化引用发布版本。
### 7.3 配置测试(管理员)
```text
+------------------------------------------------------------------------+
| 配置测试:AWSBI / Receipt Detail X |
+------------------------------------------------------------------------+
| 定义草稿版本 [v3 v] Driver 草稿版本 [v5 v] |
| 执行单位 / Warehouse [AWSBI-01 v] |
| 模式:真实 RPA;不推送企微、不进入正式库存、不影响正式排程 |
| |
| [取消] [开始测试] |
+------------------------------------------------------------------------+
| 结果:等待中 / 成功 / 失败 文件:name.xlsx SHA-256: ... |
| 步骤:登录 -> 导航 -> 填参 -> 创建 -> 下载 -> 校验 -> 测试归档 |
+------------------------------------------------------------------------+
```
- 只能选择定义中已配置的一个 Warehouse;Crane 无 Warehouse 参数时选择对应库存源执行单位。
- 成功测试对象进入 test 存储前缀、三年保留;发布时验证测试版本与内容 hash 完全相同。
### 7.4 通用报表 RPA 排程(管理员)
```text
+--------------------------------------------------------------------------------+
| 新建 / 编辑:货代通用报表 RPA |
+--------------------------------------------------------------------------------+
| 名称 [________________] Cron [0 8 * * *] [Cron 设计器] 时区 [Asia/Shanghai]|
| 库存源 [多选:仅启用且三类定义均有已发布版本的来源____________________] |
| 报表类型 [x] 库存 [x] 收料 [x] 出货 |
| 企微接收人 [多选____________________________________________________] |
| 启用 [开关] |
| |
| 预览:N 个库存源 x 选中类型 x DBS 固定 Warehouse = M 个执行单元 |
| [取消] [保存] |
+--------------------------------------------------------------------------------+
```
- 新任务 key 固定为 `freight-general-report-rpa`;不改写旧 `shipping-inventory-rpa`。
- 保存时拒绝:无报表类型、无接收人、无可用库存源、所选类型没有已发布定义或 DBS 固定 Warehouse 为空。
- 普通用户只查看该排程与运行,不显示保存、启停、手动执行、重试控件。
### 7.5 运行中心与定点重试(管理员/业务用户只读)
```text
+--------------------------------------------------------------------------------+
| 通用报表运行中心 [状态 v] [类型 v] [库存源 v] [日期范围____] [查询] |
+--------------------------------------------------------------------------------+
| 父运行 | 计划 | 触发 | 状态 | 成功/失败 | 接收人 | 开始/结束 | 详情 |
| GRP... | 08:00| cron | 部分失败 | 8 / 1 | 3 | ... | [查看] |
+--------------------------------------------------------------------------------+
| 展开单元:来源 | 类型 | Warehouse | 版本 | 状态 | 文件 | SHA-256 | 操作 |
| AWSBI | 收料 | WH01 | D3/T5 | 成功 | [下载] | ... | 管理员: 审计 |
| AWSBI | 出货 | WH01 | D2/T5 | 失败 | -- | -- | 管理员: [重试] [审计] |
+--------------------------------------------------------------------------------+
```
- 普通用户仅能下载其可见范围内的文件、查看运行详情和脱敏审计摘要;下载动作本身写审计。
- `重试`仅在单元失败时展示给管理员,必须填写理由;不会重跑兄弟单元。
### 7.6 审计详情(管理员完整,业务用户脱敏)
```text
+--------------------------------------------------------------------------------+
| 审计事件 #... [哈希链验证: 通过] |
+--------------------------------------------------------------------------------+
| 操作:REPORT_UNIT_FAILED 结果:failure 时间:2026-... |
| 操作人:RPA Worker v2 / machine | 关联:父运行 / 单元 / 文件 / callback |
| 原因:CRANE_REPORT_WAIT_TIMEOUT | 请求/相关编号:... |
+----------------------------------+---------------------------------------------+
| Before 快照 | After 快照 |
| 发布定义 v3/hash... | 状态 failed,错误码... |
+----------------------------------+---------------------------------------------+
| 证据:trace 摘要、截图索引、下载 SHA-256、企微响应脱敏摘要、前后事件哈希 |
+--------------------------------------------------------------------------------+
```
## 8. 分阶段实施计划
### 阶段 0:契约、模型和审计底座
**目标**:建立不影响旧库存运行的通用报表领域模型、迁移、不可变版本与审计约束。
| 文件 | 修改内容 |
| --- | --- |
| `backend/app/models/freight_report.py`(新增) | 定义模板、模板版本、报表定义、定义版本、父运行、单元运行、Artifact、通知投递模型及索引/唯一约束 |
| `backend/app/models/__init__.py` | 导出新模型,供迁移和服务使用 |
| `backend/migrations/versions/<revision>_add_freight_general_report_models.py`(新增) | 创建所有新表、枚举 CheckConstraint、callback/幂等唯一索引及 3 年保留字段;不修改 `ShippingInventoryFile` |
| `backend/app/services/shipping_notice/freight_report_audit_service.py`(新增) | 复用 `ShippingAuditEvent` 追加事件、白名单快照、diff、hash/evidence 引用 |
| `backend/app/services/shipping_notice/freight_report_contract.py`(新增) | 定义 purpose、状态机、schema、selector 白名单、快照脱敏和版本 hash |
| `backend/tests/test_freight_report_models.py`(新增) | 约束、唯一性、发布后不可变、Artifact 保留事实测试 |
| `backend/tests/test_freight_report_audit.py`(新增) | 全节点审计、前后快照、不可更新删除、hash 链测试 |
**验收标准**:
- 数据库迁移可在空库和当前 schema 升级;`flask db upgrade` 成功。
- 发布版本 ORM/API 均无法更新或删除;草稿可编辑且每次编辑生成审计前后快照。
- 重复 callback id、父运行重复单元、同一来源活动定义重复均被数据库约束拒绝。
- 审计测试覆盖表 6.2 中全部事件,`pytest` 通过。
### 阶段 1:定义、模板、配置测试和后台治理
**目标**:管理员能独立维护、测试和发布每库存源三类定义及受控 Driver 模板。
| 文件 | 修改内容 |
| --- | --- |
| `backend/app/api/admin/freight_reports.py`(新增) | 管理员定义/模板 CRUD、版本、测试、发布、退役、审计查询 API |
| `backend/app/api/admin/__init__.py` 或既有 blueprint 注册文件 | 注册新管理 API,统一 `require_admin` 和错误 envelope |
| `backend/app/services/shipping_notice/freight_report_definition_service.py`(新增) | 定义草稿、版本 hash、发布门禁、库存源归属校验 |
| `backend/app/services/shipping_notice/freight_report_driver_template_service.py`(新增) | selector 白名单、模板版本、发布门禁、受引用退役规则 |
| `backend/app/services/shipping_notice/freight_report_test_service.py`(新增) | 创建 test 单元、写 trigger、接收 test callback、test artifact 归档 |
| `frontend/src/features/admin/api/freight-reports.api.ts`(新增) | 全部新 API 的 typed client |
| `frontend/src/features/admin/modules/freight-reports/FreightReportDefinitionsPage.vue`(新增) | 线框 7.1 对应页面 |
| `frontend/src/features/admin/modules/freight-reports/FreightReportDriverTemplatesPage.vue`(新增) | 线框 7.2 对应页面 |
| `frontend/src/features/admin/modules/freight-reports/components/FreightReportTestDialog.vue`(新增) | 线框 7.3 对应测试流程 |
| `frontend/src/locales/{zh-CN,zh-TW,en,th}/freightReports.json`(新增) | 四语言文案和错误码 |
| `frontend/src/app/router/routes/<admin-routes>.ts`(修改,先以实际文件定位) | 注册管理员路由与权限元数据 |
| `backend/tests/test_admin_freight_reports.py`(新增) | 权限、发布门禁、定义/模板 API、测试隔离 |
| `frontend/src/features/admin/modules/freight-reports/*.spec.ts`(新增) | 表单、测试、发布禁用态和权限态单测 |
**验收标准**:
- 普通用户请求任一管理 API 返回 403;管理员可完成草稿-测试-发布-退役闭环。
- 未通过与当前内容 hash 一致的成功测试时不能发布。
- selector/超时字段违反白名单、超长、含脚本或未识别 key 时被服务端拒绝并记录 rejected 审计。
- 测试产物有 `test` 隔离前缀、3 年保留、无企微投递、无 `ShippingInventoryFile` 写入。
- 前端四语言完整,`npm run test:unit` 和 `npm run build` 通过。
### 阶段 2:通用排程、运行和文件生命周期
**目标**:新增独立通用排程,按已发布定义展开执行单元、持久化运行并完成正式归档/企微通知。
| 文件 | 修改内容 |
| --- | --- |
| `backend/app/services/schedule/job_registry.py` | 注册 `freight-general-report-rpa`,schema 含 `source_codes`、`file_purposes`,不改旧库存任务 |
| `backend/app/services/schedule/job_options.py` | 提供只返回满足已发布定义条件的库存源选项 |
| `backend/app/services/schedule/freight_general_report_job.py`(新增) | 创建父运行/单元、冻结版本/接收人快照、写新 trigger、defer 父 ScheduleRun |
| `backend/app/services/schedule/freight_general_report_finalize.py`(新增) | callback 后聚合单元终态、文件级通知、汇总通知、超时收口;不自动重试 |
| `backend/app/services/shipping_notice/freight_report_trigger_service.py`(新增) | 生成 `freight_general_report.v1` trigger,注入密文凭据和发布快照 |
| `backend/app/services/shipping_notice/freight_report_artifact_service.py`(新增) | SHA-256、命名、原样归档、三年到期、受权下载、删除审计 |
| `backend/app/services/shipping_notice/freight_report_notification_service.py`(新增) | 调用既有 `wecom_notify`,文件级和汇总级幂等投递 |
| `backend/app/jobs/handlers/freight_report_retention.py`(新增) | 到期删除对象、保留 Artifact 与永久审计事实 |
| `backend/app/api/schedule/freight_reports.py`(新增) | 运行、单元、下载、管理员重试 API |
| `backend/app/api/schedule/blueprint.py` | 注册运行及下载路由 |
| `backend/app/services/schedule/scheduler_service.py` | 为新 Job 复用现有排程通知字段,但通知实际由新 finalize 处理 |
| `backend/tests/test_freight_general_report_schedule.py`(新增) | 展开、快照冻结、无自动重试、超时、单元定点重试 |
| `backend/tests/test_freight_report_artifact_retention.py`(新增) | SHA-256、下载授权、3 年删除和审计保留 |
| `backend/tests/test_freight_report_wecom_notifications.py`(新增) | 每文件、汇总、部分失败、全失败、幂等投递 |
**验收标准**:
- 新排程可选多个已发布库存源和多个用途;`0 8 * * *` 等现有 Cron 原样复用。
- DBS 每个固定 Warehouse 展开一个单元;Crane 每个库存源每用途展开一个单元,不做 Warehouse 拆分。
- 排程、手动触发、重试均冻结定义/模板/接收人版本;后续配置变更不影响已创建单元。
- 成功文件有通用快照、可授权下载、SHA-256、3 年到期日;receipt/shipment 不写入库存表。
- 部分失败、全失败及重复 callback 的行为满足第 2 节规则。
### 阶段 3:新 Worker 与 DBS/Crane 驱动
**目标**:以新脚本完全接管现有库存 trigger,同时实现通用报表新协议。旧 Worker 在本阶段不改动。
| 文件 | 修改内容 |
| --- | --- |
| `scripts/rpa/freight_report_worker_v2.py`(新增) | 新进程入口、双协议路由、心跳版本/能力上报、目录轮询、错误隔离;复用既有 credential/heartbeat 工具 |
| `scripts/rpa/freight_report_legacy_inventory_adapter.py`(新增) | 消费当前 `shipping_inventory_rpa.v2` trigger,调用既有库存 Driver/回调语义,确保库存行为不变 |
| `scripts/rpa/freight_report_common.py`(新增) | 结构化日志、脱敏、原子文件落盘、SHA-256、trigger claim、trace/截图索引 |
| `scripts/rpa/freight_report_dbs_driver.py`(新增) | DBS 三用途导航、固定 Warehouse、保留 NULL/default 参数、View Report、下载和回读 |
| `scripts/rpa/freight_report_crane_driver.py`(新增) | Crane 三用途新建报表、运行、Schedule Description 唯一标识、轮询、下载和回读 |
| `scripts/rpa/freight_report_selector_registry.py`(新增) | 把已发布模板 selector 映射为 allowlisted Playwright 定位器;禁止执行任意脚本 |
| `scripts/rpa/freight_report_callback.py`(新增) | 对既有库存 callback 与新通用 callback 分别签名发送、超时重试、回调失败隔离 |
| `scripts/rpa/start_freight_report_worker_v2.ps1`(新增) | 复用现有主机/密钥/浏览器 Profile 的新启动入口;打印版本、目录、能力,不输出秘密 |
| `scripts/rpa/README.md` | 增加 v2 单独部署、切换、回退、运行诊断、环境变量和禁止并行运行说明 |
| `backend/app/api/shipping_notice_tools.py` 或实际 RPA callback blueprint | 保留旧 inventory callback 不变;新增通用报表 callback API 和机器身份校验 |
| `backend/app/services/shipping_notice/freight_report_callback_service.py`(新增) | 验证 callback id、文件 hash、模式、版本与单元状态后写 artifact/finalize |
| `backend/tests/test_freight_report_worker_v2.py`(新增) | 双协议路由、DBS/Crane driver mock、callback、落盘、重复处理、脱敏日志 |
| `backend/tests/test_freight_report_callback.py`(新增) | callback 授权、幂等、hash/文件名校验、非法状态拒绝 |
**验收标准**:
- `freight_report_worker_v2.py` 能处理既有库存 trigger,库存入库/回调测试与当前正式契约一致。
- DBS 对已确认 Receipt/Shipment 路径按 Warehouse 独立生成文件,日期保持 NULL,未传 Owner/Type 覆盖值。
- Crane 对 `Inbound Details`、`On Hand Details`、`Outbound Details` 均由本次唯一 Description 创建、轮询、下载;测试证明不会选择历史列表中相同文件名的条目。
- Worker 对每个单元独立失败,不阻塞同一批其他单元;不直接连 PostgreSQL、不直接发送企微。
- 生产日志、trace、截图与 callback 不包含明文凭据、cookie、完整对象 URL 或原始报表数据。
### 阶段 4:管理页面、运行可视化、审计中心和权限
**目标**:完成管理员操作面和普通用户只读体验,所有操作节点可定位、可验证、可审计。
| 文件 | 修改内容 |
| --- | --- |
| `frontend/src/features/admin/modules/schedules/components/DynamicTaskParamsForm.vue` | 为新任务渲染用途多选与发布可用库存源;复用通用动态表单而非任务硬编码 |
| `frontend/src/features/admin/modules/schedules/SchedulesPage.vue` | 展示通用报表任务说明、执行单元预览和管理员操作 |
| `frontend/src/features/admin/modules/freight-reports/FreightReportRunCenterPage.vue`(新增) | 实现线框 7.5 运行中心、文件下载、失败单元重试入口 |
| `frontend/src/features/admin/modules/freight-reports/FreightReportAuditDrawer.vue`(新增) | 实现线框 7.6、前后快照、证据、哈希链结果和权限脱敏 |
| `frontend/src/features/workspace/.../FreightReportReadOnlyPage.vue`(新增,实际归属以现有 workspace 路由确认) | 普通用户只读运行、文件和审计摘要页面 |
| `frontend/src/features/admin/api/schedule.api.ts` | 新任务、运行与重试类型 |
| `frontend/src/locales/{zh-CN,zh-TW,en,th}/scheduleRuns.json` | 新运行状态、类型、审计与权限文案 |
| `backend/app/services/shipping_notice/freight_report_query_service.py`(新增) | 管理员完整视图与普通用户脱敏只读视图、下载授权 |
| `backend/tests/test_freight_report_permissions.py`(新增) | 普通用户无写入/重试/启停权限,仅能读取授权范围 |
| `frontend/src/features/admin/modules/freight-reports/*.spec.ts`(新增) | 线框交互、权限隐藏、失败重试、状态展示 |
**验收标准**:
- 所有新增文案四语言齐全,无硬编码中文。
- 普通用户 UI 和 API 均无法绕过权限修改/重试/启停;管理员可完成操作闭环。
- 每个下载、查看、重试、发布、测试在审计页有可检索事件。
- `npm run test:unit`、`npm run build`、后端针对性 pytest 与 `git diff --check` 均通过。
### 阶段 5:切换、真实验收和回退
**目标**:以不并行运行的方式安全替换现有 Worker;允许为 v2 接管更新后端的 Worker 能力识别、版本校验和切换配置,但不改变既有库存业务契约。
| 文件 | 修改内容 |
| --- | --- |
| `scripts/rpa/start_rpa_worker.ps1` | 本阶段不修改;保留为旧 Worker 回退入口 |
| `scripts/rpa/start_freight_report_worker_v2.ps1` | 作为唯一新 Worker 启动入口,复用原主机、Profile、密钥和计划任务配置 |
| `backend/app/services/shipping_notice/rpa_worker_heartbeat.py` 及实际 Worker 路由/配置文件(以实施时定位为准) | 识别 v2 Worker 的库存导出能力、版本和共享 scope;按受控配置将库存 trigger 消费者切至 v2,不修改 `shipping_inventory_rpa.v2` payload、既有 inventory callback API 或库存入库服务契约 |
| `scripts/rpa/README.md` | 写入测试、停旧、启新、观察、回退的运维步骤 |
| `docs/features/shipping-notice/technical.md` | 更新货代 RPA 架构、双协议、保留策略、审计和切换约束 |
| `docs/funclist.md` | 标记通用报表 RPA 功能及状态 |
| `docs/demand.md`、`docs/tec.md` | 仅在现有章节确有对应需求/架构描述时同步更新 |
**验收标准**:
- 测试环境 DBS 和 Crane 分别完成 inventory/receipt/shipment 共 6 类真实导出;文件、SHA-256、归档、企微和审计逐项核对。
- 新 Worker 在测试环境连续 5 个工作日成功处理现有库存 RPA,且无库存 callback、快照入库、共享目录、心跳回归。
- 切换窗口内先停止旧 Worker,确认旧进程已退出后才启动新 Worker;无双 Worker 消费。
- 后端切换改动只改变 v2 Worker 的就绪/能力识别或受控路由;相同 `shipping_inventory_rpa.v2` 黄金 trigger 在切换前后产生等价的 callback、库存快照入库和终态语义。
- 首个生产排程按预期完成;失败回退演练证明能停新 Worker、启动旧 Worker,且未重复处理已 claim 的 trigger。
## 9. 风险清单与控制
| 类别 | 风险 | 影响 | 控制措施 |
| --- | --- | --- | --- |
| 核心技术 | 新 Worker 对既有库存 trigger/callback 行为不完全等价,切换后库存无法入库 | 高 | 独立 legacy adapter、协议黄金测试、连续 5 工作日真实库存准入、保留旧启动入口 |
| RPA 页面 | DBS/Crane DOM、文本或异步生成机制变更 | 高 | 发布模板版本、selector 白名单、配置测试、trace/截图索引、失败不自动重试 |
| 业务数据 | 把 receipt/shipment 写入库存快照或触发匹配 | 高 | 表与 callback 分流、服务层断言、回归测试、审计检查 |
| 并发 | callback 重放或 Worker 崩溃导致重复归档/重复推送 | 高 | callback 唯一键、状态机、通知投递幂等、原子文件落盘 |
| 权限 | 普通用户绕过 UI 调用重试或读取未授权文件 | 高 | 服务端 RBAC、下载授权、访问审计、前端仅作体验控制 |
| 凭据 | selector/日志/trigger 泄漏密码、cookie 或对象 URL | 高 | 密文 envelope、日志脱敏、字段白名单、禁止脚本、测试扫描 |
| 存储 | 3 年文件积累超出磁盘/对象存储容量 | 中 | 容量预估、对象生命周期、归档监控、到期只删对象不删审计 |
| 企微 | 部分投递失败造成用户误认为全部成功 | 中 | 每文件投递状态、汇总卡片、失败列表、通知审计;不重发成功文件 |
| 进度 | Crane 三个页面 selector 和报表完成条件未完整验证 | 高 | 先以真实配置测试建立 selector 基线,再承诺生产切换日期 |
| 资源 | 单 Windows 主机浏览器资源不足、8 点批次拥塞 | 中 | 单 Worker 串行/受控并发、单元超时、队列长度/耗时监控、按现有排程拆分 |
| 变更治理 | 管理员直接修改生产 selector 导致全站失败 | 高 | draft-test-publish、发布不可变、强制回归测试与退役/回滚版本 |
### 核心关键风险项:新 Worker 接管既有库存 RPA 的等价性
这是上线阻断风险,不是普通缺陷。库存 RPA 已连接库存快照入库与下游业务;即使通用收料/出货功能正确,若新 Worker 在旧 trigger、callback、心跳、目录处理、文件落盘或失败语义上与旧 Worker 有差异,仍可能造成库存快照缺失或状态悬挂。
**必须满足的放行证据**:旧协议黄金样本回放全通过、测试环境 DBS/Crane 三类真实报表通过、新 Worker 连续 5 个工作日库存 RPA 成功、心跳/共享 scope/回调幂等回归通过、停旧启新及回退演练通过。任一项不满足,禁止生产切换。
## 10. 开发与验收顺序
1. 先完成阶段 0,再进行阶段 1;未有不可变定义和审计,不允许写新 trigger。
2. 阶段 2 的通用排程仅消费已发布配置;不以草稿配置“先跑再说”。
3. 阶段 3 完成新 Worker 前,不修改 `scripts/rpa/freight_rpa_worker.py`。
4. 阶段 4 所有 UI 必须先调用受 RBAC 保护的 API,再实现权限隐藏。
5. 阶段 5 是唯一允许接管生产目录的阶段;切换不得让旧、新 Worker 并行。
## 11. 非目标与待现场验证项
- 不实现 Excel 行级解析、内容预览、检索、库存匹配、ERP 写入或自动创建业务单据。
- 不引入假日逻辑;管理员自行在现有排程中配置 Cron 和启停。
- 不要求历史库存排程迁移到新排程;新通用排程独立创建。
- DBS 当前只确认 AWS/Bison/AWSBI 示例路径;其他现有库存源由管理员按定义/模板配置、测试、发布后启用。
- Crane 三类报表的真实 query route、参数控件、生成完成信号和下载 DOM 必须在测试环境配置测试中逐项固化;不可用截图推断替代真实验证。
@@ -0,0 +1,90 @@
# 货代通用报表 RPA 详细设计说明
## 1. 目的与范围
本文是 [主设计](2026-08-12-freight-general-report-rpa-design.md) 的实施级说明。系统新增 `freight-general-report-rpa` 排程,在 DBS 与 Crane 导出库存、收料、出货报表,原样归档并逐文件推送企业微信。库存成功文件额外进入既有库存快照入库桥接;收料和出货不解析、不匹配、不写 ERP。
旧 `shipping-inventory-rpa` 与 `scripts/rpa/freight_rpa_worker.py` 在准入完成前保持不变。v2 可修改后端的能力识别与路由配置,但不得修改 `shipping_inventory_rpa.v2` 的 payload、既有 inventory callback API、库存快照入库及下游语义。
## 2. 组件与职责
| 组件 | 位置 | 责任 | 禁止事项 |
| --- | --- | --- | --- |
| 定义服务 | `shipping_notice/freight_report_definition_service.py` | 草稿、版本 hash、测试、发布、退役 | 保存明文凭据、直接执行 RPA |
| 模板服务 | `shipping_notice/freight_report_driver_template_service.py` | selector 白名单、等待/下载规则版本化 | 接受任意 JS/回调 URL |
| 排程 Job | `schedule/freight_general_report_job.py` | 冻结快照、展开父/单元运行、投递 trigger | 等待浏览器操作、直接发企微 |
| 回调服务 | `shipping_notice/freight_report_callback_service.py` | 认证、幂等、文件校验、归档、库存桥接 | 重新解释定义或选择历史报表 |
| 收尾服务 | `schedule/freight_general_report_finalize.py` | 父运行汇总、文件/汇总通知、超时收口 | 自动重试失败单元 |
| v2 Worker | `scripts/rpa/freight_report_worker_v2.py` | 双协议路由、浏览器导出、下载校验、回调 | 访问 PostgreSQL、发送企微、修改定义 |
| legacy adapter | `scripts/rpa/freight_report_legacy_inventory_adapter.py` | 原样处理既有库存 v2 trigger/callback | 将 receipt/shipment 混入库存链路 |
## 3. 运行流程
```text
管理员发布 Definition/Driver Template
-> 创建/启用 freight-general-report-rpa 排程
-> Cron 创建 ScheduleRun + ParentRun
-> 按来源/用途/Warehouse 展开 UnitRun,冻结版本与接收人
-> 投递 freight_general_report.v1 trigger
-> v2 Worker 领取、导出、校验、回调
-> Artifact 原样归档;inventory 进入既有入库桥接
-> 每成功文件企微投递;所有单元结束后汇总投递
-> ParentRun 成功/部分失败/失败
```
### 3.1 单元展开
1. 排程只能选择启用库存源和每个已选用途均存在已发布定义的来源。
2. DBS 按定义内固定 Warehouse 列表拆分:`source x purpose x warehouse` 一条 `UnitRun`;报告日期不传值,页面保持 `NULL`,Owner/Type 不覆盖默认值。
3. Crane 按库存源拆分:`source x purpose` 一条 `UnitRun`;每次新建报表并写入唯一 Description,只等待该 Description 对应结果,禁止选择历史“最新”文件。
4. 创建时冻结 definition/template 版本、定义/模板内容 hash、接收人、来源显示名、Warehouse 与排程参数;后续配置变更不影响已创建单元。
### 3.2 通用 trigger 与 callback
通用 trigger 使用 `schema_version=freight_general_report.v1`、`action=general_report_export` 和全局唯一 `callback_id`。包含已发布定义/模板快照、执行模式、单元编号和密文凭据 envelope;不包含明文密码、Cookie、签名下载 URL 或任意脚本。
Worker 必须先对 trigger 做原子 claim,再执行。成功 callback 必须带 `callback_id`、单元号、文件路径/受控共享定位、原始文件名、字节数、SHA-256、诊断摘要;失败 callback 必须带结构化错误码和脱敏错误信息。服务端以 `callback_id` 和 UnitRun 状态机校验:首次合法回调可推进终态,重复回调仅记录 `ignored` 审计,绝不再次归档或推送。
### 3.3 库存兼容桥接
v2 以独立 adapter 消费既有 `shipping_inventory_rpa.v2` trigger,保留旧批量领取、逐源身份字段、无库存 `skipped` 语义和 `/rpa/inventory-batch-ready` callback。新通用库存单元的成功 Artifact 在校验和归档完成后,调用既有库存快照入库服务;桥接失败使该库存 UnitRun 失败,但不影响 receipt/shipment 单元。新通用排程不触发库存匹配、锁定、订单推进或 ERP 写入。
## 4. 状态机与异常处理
```text
Definition/Template: draft -> tested -> published -> retired
ParentRun: queued -> running -> success | partial_failed | failed
UnitRun: queued -> dispatched -> running -> succeeded | failed | cancelled
failed UnitRun --admin reason--> new UnitRun(queued, retry_of_id=old)
```
- 发布门禁:必须存在相同 definition/template `content_hash` 的成功测试;发布版本不可更新或删除,只能复制为新草稿。
- 回调超时:未终态单元标为失败,父运行按成功/失败数收口;不自动重试。
- 部分失败:成功文件照常归档并推送,汇总包含失败单元及错误码;全部失败仅推送失败汇总。
- 手工重试:仅管理员、仅失败单元、必须填写原因;新建运行及 Artifact,不覆盖原记录。
- 文件校验失败(缺失、大小不足、扩展名不符、SHA 不符):拒绝 callback,记录失败审计,不发送文件。
## 5. 权限、审计与保留
管理员拥有定义、模板、测试、发布、排程、重试、恢复与完整审计访问权。普通业务用户仅能查看获授权的运行、文件和脱敏审计摘要,并作为企业微信接收人;服务端 RBAC 必须拒绝其写操作。
所有创建、编辑、测试、发布、退役、排程变更、触发、领取、回调、归档、下载、通知、重试和到期删除均追加 `ShippingAuditEvent`。记录操作人、时间、白名单 before/after 快照、diff、关联编号、结果和脱敏证据引用;审计永久保留。正式及测试文件保留三年,到期只删除对象,不删除 Artifact 行或审计。
## 6. 切换与回退
1. v2 在测试环境完成 DBS/Crane 三用途真实导出,并通过旧库存协议黄金样本、心跳、共享目录、callback 幂等与库存入库回归。
2. v2 连续五个工作日成功处理既有库存 RPA 后,才允许进入生产切换窗口。
3. 后端可更新 Worker 能力识别、版本校验、受控路由/开关;相同库存 v2 trigger 必须产生等价 callback 和终态。
4. 停止旧 Worker,确认进程退出且不再持有 trigger 目录后,启动 v2;两个 Worker 不得同时消费库存目录。
5. 首个生产排程逐项核对。若失败,停 v2、恢复旧 Worker 和原路由;以 claim/callback 幂等键避免重复处理。
## 7. 实施验证矩阵
| 类别 | 必验事实 |
| --- | --- |
| 契约 | 新旧库存 v2 trigger 的 callback、入库、`success/failed/skipped` 终态等价 |
| DBS | 每 Warehouse 单独文件;日期 NULL;默认 Owner/Type 未被覆盖 |
| Crane | 三类报表均用本次唯一 Description 创建、轮询、下载,无历史文件误取 |
| 幂等 | 重放 callback、重启 Worker、重复通知均不产生重复 Artifact/企微消息 |
| 权限 | 普通用户 API/UI 无法配置、发布、启停或重试;下载/查看均留审计 |
| 回退 | 停 v2、启旧 Worker 后未处理 trigger 可继续处理,已领取/回调单元不重复 |
@@ -103,6 +103,46 @@ const attachmentUrlInputRef = ref<HTMLInputElement | null>(null);
const showAttachmentMenu = ref(false); const showAttachmentMenu = ref(false);
const showAttachmentUrlPanel = ref(false); const showAttachmentUrlPanel = ref(false);
const attachmentUrlInput = ref(''); const attachmentUrlInput = ref('');
const attachmentScrollerRef = ref<HTMLElement | null>(null);
const attachmentCanScrollLeft = ref(false);
const attachmentCanScrollRight = ref(false);
let attachmentDragStartX = 0;
let attachmentDragScrollLeft = 0;
let attachmentDragging = false;
/** 同步附件横向带的左右可滚动状态,供箭头按钮和无障碍状态使用。 */
function updateAttachmentScrollState() {
const element = attachmentScrollerRef.value;
if (!element) return;
attachmentCanScrollLeft.value = element.scrollLeft > 1;
attachmentCanScrollRight.value = element.scrollLeft + element.clientWidth < element.scrollWidth - 1;
}
/** 按固定步长移动附件横向带,避免大量附件撑高输入区。 */
function scrollAttachments(direction: 'left' | 'right') {
attachmentScrollerRef.value?.scrollBy({ left: direction === 'left' ? -320 : 320, behavior: 'smooth' });
}
/** 开始桌面端指针拖拽;触摸端交给原生横向滚动,避免手势冲突。 */
function startAttachmentDrag(event: PointerEvent) {
const element = attachmentScrollerRef.value;
if (!element || event.pointerType === 'touch') return;
attachmentDragging = true;
attachmentDragStartX = event.clientX;
attachmentDragScrollLeft = element.scrollLeft;
element.setPointerCapture?.(event.pointerId);
}
/** 根据指针位移更新附件横向滚动位置。 */
function moveAttachmentDrag(event: PointerEvent) {
if (!attachmentDragging || !attachmentScrollerRef.value) return;
attachmentScrollerRef.value.scrollLeft = attachmentDragScrollLeft - (event.clientX - attachmentDragStartX);
}
/** 结束附件横向拖拽并恢复普通指针状态。 */
function stopAttachmentDrag() {
attachmentDragging = false;
}
/** 当前发货通知是否仍在上传或预解析,决定输入框下方的操作提示。 */ /** 当前发货通知是否仍在上传或预解析,决定输入框下方的操作提示。 */
const hasShippingNoticeInProgress = computed(() => props.attachments.some( const hasShippingNoticeInProgress = computed(() => props.attachments.some(
@@ -321,11 +361,14 @@ const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
}; };
onMounted(() => { onMounted(() => {
nextTick(updateAttachmentScrollState);
window.addEventListener('resize', updateAttachmentScrollState);
document.addEventListener('mousedown', handleDocumentPointerDown); document.addEventListener('mousedown', handleDocumentPointerDown);
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true }); document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
}); });
onBeforeUnmount(() => { onBeforeUnmount(() => {
window.removeEventListener('resize', updateAttachmentScrollState);
document.removeEventListener('mousedown', handleDocumentPointerDown); document.removeEventListener('mousedown', handleDocumentPointerDown);
document.removeEventListener('touchstart', handleDocumentPointerDown); document.removeEventListener('touchstart', handleDocumentPointerDown);
}); });
@@ -416,12 +459,24 @@ watch(
<div <div
v-if="attachments.length > 0" v-if="attachments.length > 0"
data-testid="chat-attachment-list" data-testid="chat-attachment-list"
class="flex flex-wrap gap-2 px-2.5 pb-2 pt-1" class="relative flex items-center gap-1 px-2.5 pb-2 pt-1"
> >
<button v-if="attachmentCanScrollLeft" type="button" class="z-10 shrink-0 rounded-full border border-default bg-surface p-1 text-muted shadow-sm" aria-label="向左查看附件" @click="scrollAttachments('left')">‹</button>
<div
ref="attachmentScrollerRef"
class="flex min-w-0 flex-1 flex-nowrap gap-2 overflow-x-auto pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
:class="attachmentDragging ? 'cursor-grabbing select-none' : 'cursor-grab'"
@scroll="updateAttachmentScrollState"
@pointerdown="startAttachmentDrag"
@pointermove="moveAttachmentDrag"
@pointerup="stopAttachmentDrag"
@pointercancel="stopAttachmentDrag"
@pointerleave="stopAttachmentDrag"
>
<article <article
v-for="a in attachments" v-for="a in attachments"
:key="a.id" :key="a.id"
class="group relative flex min-w-0 basis-full items-center gap-3 rounded-xl px-3 py-2.5 transition-colors sm:basis-[calc(50%-0.25rem)] lg:max-w-[310px]" class="group relative flex h-[68px] w-[250px] shrink-0 items-center gap-3 rounded-xl px-3 py-2.5 transition-colors"
:class="isProcurementContractAgent && a.kind === 'local' :class="isProcurementContractAgent && a.kind === 'local'
? 'border border-[#9cc7f2] bg-[#eef6ff]' ? 'border border-[#9cc7f2] bg-[#eef6ff]'
: 'border border-default bg-surface-soft'" : 'border border-default bg-surface-soft'"
@@ -522,6 +577,8 @@ watch(
<X class="h-3.5 w-3.5" /> <X class="h-3.5 w-3.5" />
</button> </button>
</article> </article>
</div>
<button v-if="attachmentCanScrollRight" type="button" class="z-10 shrink-0 rounded-full border border-default bg-surface p-1 text-muted shadow-sm" aria-label="向右查看附件" @click="scrollAttachments('right')">›</button>
</div> </div>
<input <input
@@ -0,0 +1,22 @@
import { mount } from '@vue/test-utils';
import { describe, expect, it } from 'vitest';
import ChatMessageAttachmentList from './ChatMessageAttachmentList.vue';
describe('ChatMessageAttachmentList', () => {
it('keeps many sent attachments in a single horizontally scrollable row', () => {
const wrapper = mount(ChatMessageAttachmentList, {
props: {
attachments: [
{ name: 'one.eml', type: 'document', source: 'local', size: 1024, extension: 'eml' },
{ name: 'two.eml', type: 'document', source: 'local', size: 2048, extension: 'eml' },
{ name: 'three.eml', type: 'document', source: 'local', size: 3072, extension: 'eml' },
],
},
});
const list = wrapper.get('[data-testid="chat-message-attachment-list"]');
expect(list.classes()).toContain('overflow-x-auto');
expect(list.classes()).toContain('flex-nowrap');
expect(wrapper.findAll('article')).toHaveLength(3);
});
});
@@ -35,12 +35,12 @@ function attachmentBadge(attachment: ChatMessageAttachment): string {
<div <div
v-if="attachments.length > 0" v-if="attachments.length > 0"
data-testid="chat-message-attachment-list" data-testid="chat-message-attachment-list"
class="mb-2 flex w-full flex-wrap justify-end gap-2" class="mb-2 flex w-full flex-nowrap justify-end gap-2 overflow-x-auto pb-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
> >
<article <article
v-for="(attachment, attachmentIndex) in attachments" v-for="(attachment, attachmentIndex) in attachments"
:key="`${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`" :key="`${attachment.name}-${attachment.size ?? 'unknown'}-${attachmentIndex}`"
class="flex min-w-0 basis-full items-center gap-2.5 rounded-xl border border-default bg-surface px-3 py-2.5 shadow-sm dark:bg-slate-900 sm:basis-[calc(50%-0.25rem)] sm:min-w-[220px] sm:max-w-[290px]" class="flex h-[68px] w-[250px] shrink-0 items-center gap-2.5 rounded-xl border border-default bg-surface px-3 py-2.5 shadow-sm dark:bg-slate-900"
:title="attachment.name" :title="attachment.name"
> >
<div <div
@@ -0,0 +1,77 @@
/**
* features/chat/components/shipping-review/ReviewCurrentProcessingCard.spec.ts
* 用途:验证工作台右侧当前任务卡只在需要人工处理时渲染业务动作。
* 依赖:Vitest、Vue Test Utils、Vue I18n、ReviewCurrentProcessingCard。
* 逻辑:库存自动处理中即使遗留 primary_action,也不得显示编辑正式任务;可重试状态仍保留重试入口。
*/
import { mount } from '@vue/test-utils';
import { createI18n } from 'vue-i18n';
import { describe, expect, it } from 'vitest';
import ReviewCurrentProcessingCard from './ReviewCurrentProcessingCard.vue';
const i18n = createI18n({
legacy: false,
locale: 'zh-CN',
messages: {
'zh-CN': {
'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching': '重新库存匹配',
},
},
});
describe('ReviewCurrentProcessingCard', () => {
it('hides a legacy primary action while inventory preparation is running', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_preparation',
userStatus: 'running',
primaryAction: { code: 'edit_formal_task', i18nKey: 'edit_formal_task' },
},
global: { plugins: [i18n] },
});
// 自动处理只显示状态,不能让历史的正式任务编辑动作干扰当前库存阶段。
expect(wrapper.find('[data-testid="review-current-task-actions"]').exists()).toBe(false);
});
it('keeps the retry action for retryable states', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: { stageCode: 'inventory_preparation', userStatus: 'retryable', retryable: true },
global: { plugins: [i18n] },
});
// 失败后的人工恢复路径不能被运行态过滤误伤。
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(true);
});
it('renders Gate label_key for every primary action presentation', () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_matching',
userStatus: 'waiting_human',
primaryAction: {
code: 'retry_inventory_matching',
label_key: 'chat.shippingOrderReview.processGate.actionCodes.retry_inventory_matching',
} as any,
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').text()).toBe('重新库存匹配');
});
it('renders server-provided recovery actions without duplicating the primary action', async () => {
const wrapper = mount(ReviewCurrentProcessingCard, {
props: {
stageCode: 'inventory_matching',
userStatus: 'waiting_human',
primaryAction: { code: 'retry_inventory_matching', i18nKey: 'retry_inventory_matching' },
recoveryActions: [{ code: 'retry_inventory_from_preparation' }],
},
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="review-current-task-recovery-retry_inventory_from_preparation"]').exists()).toBe(true);
expect(wrapper.findAll('button').length).toBe(2);
});
});
@@ -35,6 +35,12 @@ const props = defineProps<{
retryable?: boolean; retryable?: boolean;
blockingReason?: ShippingProcessingBlockingReason | null; blockingReason?: ShippingProcessingBlockingReason | null;
primaryAction?: ShippingProcessingPrimaryAction | null; primaryAction?: ShippingProcessingPrimaryAction | null;
recoveryActions?: Array<{
code: string;
i18nKey?: string | null;
label_key?: string | null;
parameters?: Record<string, unknown>;
}>;
taskMissing?: boolean; taskMissing?: boolean;
confirmedTaskId?: number | null; confirmedTaskId?: number | null;
@@ -169,6 +175,9 @@ const showNextStep = computed(() => {
const showBusinessAction = computed(() => { const showBusinessAction = computed(() => {
if (props.loading) return false; if (props.loading) return false;
if (props.taskMissing) return false; if (props.taskMissing) return false;
// [STEP] 自动处理期间没有人工业务动作;只保留外层的刷新进度入口。
// 防止正式任务编辑等历史 primary_action 穿透到库存获取运行态。
if (props.userStatus === 'running') return false;
if (props.retryable) return true; if (props.retryable) return true;
const code = String(props.primaryAction?.code || '').trim(); const code = String(props.primaryAction?.code || '').trim();
if (!code) return false; if (!code) return false;
@@ -186,7 +195,13 @@ const businessActionLabel = computed(() => {
} }
const pa = props.primaryAction; const pa = props.primaryAction;
if (!pa) return ''; if (!pa) return '';
const i18nKey = String(pa.i18nKey || '').trim(); // Gate action presentation uses label_key; normalize it at the shared card boundary
// so every gate renders its business label instead of exposing the action code.
const i18nKey = String(
pa.i18nKey
|| (pa as ShippingProcessingPrimaryAction & { label_key?: string | null }).label_key
|| '',
).trim();
if (i18nKey && te(i18nKey)) { if (i18nKey && te(i18nKey)) {
return t(i18nKey); return t(i18nKey);
} }
@@ -214,13 +229,31 @@ const businessActionTitle = computed(() => {
}); });
const actionIsRetry = computed(() => Boolean(props.retryable) || String(props.primaryAction?.code || '') === 'retry'); const actionIsRetry = computed(() => Boolean(props.retryable) || String(props.primaryAction?.code || '') === 'retry');
const recoveryActions = computed(() => (props.recoveryActions || []).filter((action) => {
const code = String(action.code || '').trim();
return code && code !== String(props.primaryAction?.code || '').trim();
}));
function recoveryActionLabel(action: (typeof recoveryActions.value)[number]): string {
const key = String(
action.i18nKey
|| action.label_key
|| `workspace.shippingNotice.processGate.actionCodes.${action.code}`,
).trim();
return key && te(key) ? t(key) : action.code;
}
function handleBusinessActionClick() { function handleBusinessActionClick() {
const primaryActionCode = String(props.primaryAction?.code || '').trim();
if (props.retryable && primaryActionCode && primaryActionCode !== 'retry') {
emit('action', primaryActionCode, props.primaryAction?.parameters ?? {});
return;
}
if (actionIsRetry.value) { if (actionIsRetry.value) {
emit('retry'); emit('retry');
return; return;
} }
emit('action', String(props.primaryAction?.code || ''), props.primaryAction?.parameters ?? {}); emit('action', primaryActionCode, props.primaryAction?.parameters ?? {});
} }
/** /**
@@ -357,6 +390,17 @@ type ReviewCurrentUserStatus =
/> />
{{ businessActionLabel }} {{ businessActionLabel }}
</button> </button>
<button
v-for="action in recoveryActions"
:key="action.code"
type="button"
class="inline-flex items-center gap-1 rounded-md border border-sky-300 bg-white px-2.5 py-1.5 text-xs font-medium text-sky-800 shadow-sm transition hover:bg-sky-50 disabled:opacity-50 dark:border-sky-700 dark:bg-sky-900 dark:text-sky-100 dark:hover:bg-sky-800"
:data-testid="`review-current-task-recovery-${action.code}`"
:disabled="retrying || locating"
@click="$emit('action', action.code, action.parameters || {})"
>
{{ recoveryActionLabel(action) }}
</button>
<button <button
v-if="showLocateAction" v-if="showLocateAction"
type="button" type="button"
@@ -1017,12 +1017,6 @@ export function useChatShipping(options: UseChatShippingOptions) {
t, t,
}); });
// 快览完成后补充可见的用户请求;用户已输入备注时绝不覆盖。
watch([isShippingNoticeAgent, shippingIntakes.allParsedReady], ([isShippingAgent, allParsedReady]) => {
if (!isShippingAgent || !allParsedReady || input.value.trim()) return;
input.value = t('chat.shippingOrderExtractionDefaultUserMessage');
});
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({ const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
isThinking, isThinking,
currentAgentId, currentAgentId,
@@ -619,12 +619,16 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
try { try {
if (authoritativeOrderTaskNo.value) { if (authoritativeOrderTaskNo.value) {
await refreshShippingProcessing(); await refreshShippingProcessing();
const unifiedStatus = String(shippingProcessingProjection.value?.status || '').trim().toLowerCase(); const unifiedStatus = String(
shippingProcessingProjection.value?.userStatus
|| shippingProcessingProjection.value?.status
|| '',
).trim().toLowerCase();
if (unifiedStatus !== lastUnifiedStatus) { if (unifiedStatus !== lastUnifiedStatus) {
lastUnifiedStatus = unifiedStatus; lastUnifiedStatus = unifiedStatus;
options.onWorkflowRefresh?.(); options.onWorkflowRefresh?.();
} }
if (UNIFIED_TERMINAL.has(unifiedStatus)) { if (UNIFIED_TERMINAL.has(unifiedStatus) || unifiedStatus === 'waiting_review') {
stopWorkflowProgressPolling(); stopWorkflowProgressPolling();
} }
return; return;
@@ -174,7 +174,7 @@ describe('useChatShippingSendHandler', () => {
expect(consumed).toBe(true); expect(consumed).toBe(true);
expect(startOrderExtractionRun).toHaveBeenCalledWith( expect(startOrderExtractionRun).toHaveBeenCalledWith(
'chat.shippingOrderExtractionDefaultUserMessage', '',
['SNI-EMPTY-NOTE'], ['SNI-EMPTY-NOTE'],
[{ [{
name: 'orders.eml', name: 'orders.eml',
@@ -214,7 +214,7 @@ describe('useChatShippingSendHandler', () => {
expect(consumed).toBe(true); expect(consumed).toBe(true);
expect(startOrderExtractionRun).toHaveBeenCalledWith( expect(startOrderExtractionRun).toHaveBeenCalledWith(
'chat.shippingOrderExtractionDefaultUserMessage', '',
['SNI-FIRST', 'SNI-SECOND'], ['SNI-FIRST', 'SNI-SECOND'],
[ [
{ name: 'first.eml', size: 100, extension: 'eml', type: 'document', source: 'shipping_notice' }, { name: 'first.eml', size: 100, extension: 'eml', type: 'document', source: 'shipping_notice' },
@@ -189,8 +189,8 @@ export function createShippingSendHandlers(ctx: ShippingSendHandlerContext) {
&& submittedIntakes.has(item.intakeNo.trim().toUpperCase()), && submittedIntakes.has(item.intakeNo.trim().toUpperCase()),
), ),
); );
// 阶段 2:空备注补充用户可见的默认请求,便于会话记录与审计;不改变 Worker 的确定性识别流程。 // 空备注不伪造用户正文;订单抽取动作由结构化 Run 提交承载,用户消息只保留附件快照。
const query = trimmed || ctx.t('chat.shippingOrderExtractionDefaultUserMessage'); const query = trimmed;
ctx.shippingAutoFlowRequested.value = false; ctx.shippingAutoFlowRequested.value = false;
if (typeof textOrEvent !== 'string') ctx.input.value = ''; if (typeof textOrEvent !== 'string') ctx.input.value = '';
try { try {
@@ -179,7 +179,7 @@ describe('useChatShippingUploadHandler', () => {
await handleShippingAutoUploadNoticeBatch([]); await handleShippingAutoUploadNoticeBatch([]);
expect(startOrderExtractionRun).toHaveBeenCalledWith( expect(startOrderExtractionRun).toHaveBeenCalledWith(
'chat.shippingOrderExtractionDefaultUserMessage', '',
['SNI-1'], ['SNI-1'],
[], [],
); );
@@ -231,7 +231,7 @@ export function createShippingUploadHandlers(ctx: ShippingUploadHandlerContext)
ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed')); ctx.msg.warning(ctx.t('chat.shippingNoticeUploadFailed'));
return false; return false;
} }
const query = ctx.input.value.trim() || ctx.t('chat.shippingOrderExtractionDefaultUserMessage'); const query = ctx.input.value.trim();
const ok = await ctx.startOrderExtractionRun(query, intakeNos, []); const ok = await ctx.startOrderExtractionRun(query, intakeNos, []);
if (ok) { if (ok) {
ctx.clearConsumedNoticeAttachments?.(); ctx.clearConsumedNoticeAttachments?.();
@@ -430,7 +430,7 @@ export function useShippingOrderExtractionRuns(options: UseShippingOrderExtracti
/** /**
* 启动订单抽取统一提交:后端裁决 append/create,并只持久化用户操作与唯一 Run 状态卡。 * 启动订单抽取统一提交:后端裁决 append/create,并只持久化用户操作与唯一 Run 状态卡。
* @param query - 用户本次备注;允许为空,不发送给 Dify Chatflow。 * @param query - 用户本次备注;为空时用户消息仅展示附件,不伪造默认正文。
* @param intakeNos - 本次冻结的 Intake 编号。 * @param intakeNos - 本次冻结的 Intake 编号。
* @param attachments - 用户消息中的安全附件快照。 * @param attachments - 用户消息中的安全附件快照。
* @param uploadBatchId - 上传批次隔离键;禁止当作 user_task_no。 * @param uploadBatchId - 上传批次隔离键;禁止当作 user_task_no。
@@ -310,7 +310,8 @@ vi.mock('../components/shipping-review/ReviewInventoryCandidatesPanel.vue', () =
vi.mock('@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue', () => ({ vi.mock('@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue', () => ({
default: { default: {
name: 'ProcessGateRecoveryCard', name: 'ProcessGateRecoveryCard',
template: '<div data-testid="mock-process-gate" />', props: ['showActions'],
template: '<div data-testid="mock-process-gate" :data-actions="showActions === false ? \'hidden\' : \'shown\'" />',
}, },
})); }));
@@ -642,6 +643,7 @@ function resetActiveCaseFixture() {
task_missing: false, task_missing: false,
recovery_available: null, recovery_available: null,
post_confirm_auto_progress: null, post_confirm_auto_progress: null,
process_gate: null,
current_stage: null, current_stage: null,
technical_progress: null, technical_progress: null,
automation: { status: 'idle', can_auto_create: false, can_build: true }, automation: { status: 'idle', can_auto_create: false, can_build: true },
@@ -659,6 +661,38 @@ describe('ShippingOrderReviewView layout phase 1', () => {
reviewProgressContext.value = null; reviewProgressContext.value = null;
}); });
it('uses the current-task card as the only Gate action entry for every formal-OT Gate', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed',
has_formal_ot: true,
task_missing: false,
confirmed_task_id: 88,
confirmed_task_no: 'SN-GATE-1',
process_gate: {
execution_no: 'EXEC-GATE-1',
status: 'blocked',
owner_type: 'human',
technical_auto_only: false,
current_blocking_gate: { gate_code: 'customer_confirmation', status: 'blocked' },
primary_action: {
code: 'confirm_customer',
label_key: 'chat.shippingNotice.processGate.actionCodes.confirm_customer',
kind: 'current_gate',
dispatch: 'mutation',
},
},
automation: { status: 'manual_fallback', can_auto_create: false, can_build: true },
};
const wrapper = await mountView();
await flushPromises();
// 任意正式 OT Gate 的可执行入口只保留在“当前任务”;待处理事项只读说明仍保留。
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="mock-process-gate"]').attributes('data-actions')).toBe('hidden');
});
it('shows restored version as current and latest version only as failed attempt', async () => { it('shows restored version as current and latest version only as failed attempt', async () => {
reviewProgressContext.value = { reviewProgressContext.value = {
item_no: 'WFI-1', item_no: 'WFI-1',
@@ -8,7 +8,7 @@
ReviewCustomerResolutionPanel / ReviewCurrentProcessingCard / ReviewCompletedChecksPanel / ReviewCustomerResolutionPanel / ReviewCurrentProcessingCard / ReviewCompletedChecksPanel /
ReviewBuildEligibilitySummary、ReviewInventory*、 ReviewBuildEligibilitySummary、ReviewInventory*、
ReviewLineInventoryOps(履约操作并入明细右侧列)、ReviewLineFulfillmentDetail(行内履约摘要)、 ReviewLineInventoryOps(履约操作并入明细右侧列)、ReviewLineFulfillmentDetail(行内履约摘要)、
ProcessGateRecoveryCard;formal_task 仅显式动作挂载 TaskTodoPanel(主写在 Footer); formal_task 仅显式动作挂载 TaskTodoPanel(主写在 Footer);
shipping.api.retryWorkspaceConversationAutoProgress(对话级重试)。 shipping.api.retryWorkspaceConversationAutoProgress(对话级重试)。
逻辑:建单前订单检查为主卡;正式 OT 后保持 standard,不自动切 formal_task 空壳; 逻辑:建单前订单检查为主卡;正式 OT 后保持 standard,不自动切 formal_task 空壳;
对话级「重试自动推进」在顶栏;当前 Case 对象级重试优先右栏 CurrentProcessingCard, 对话级「重试自动推进」在顶栏;当前 Case 对象级重试优先右栏 CurrentProcessingCard,
@@ -65,6 +65,7 @@ import ReviewWorkbenchHeader from '../components/shipping-review/ReviewWorkbench
import ReviewWorkbenchModeToggle from '../components/shipping-review/ReviewWorkbenchModeToggle.vue'; import ReviewWorkbenchModeToggle from '../components/shipping-review/ReviewWorkbenchModeToggle.vue';
import ReviewUnsavedSwitchDialog from '../components/shipping-review/ReviewUnsavedSwitchDialog.vue'; import ReviewUnsavedSwitchDialog from '../components/shipping-review/ReviewUnsavedSwitchDialog.vue';
import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue'; import ProcessGateRecoveryCard from '@/features/shipping-process-gates/components/ProcessGateRecoveryCard.vue';
import { useShippingProcessGateRecovery } from '@/features/shipping-process-gates/composables/useShippingProcessGateRecovery';
import TaskTodoPanel from '@/features/workspace/shipping-task-center/TaskTodoPanel.vue'; import TaskTodoPanel from '@/features/workspace/shipping-task-center/TaskTodoPanel.vue';
import ManualUploadEvidenceDialog from '@/features/workspace/shipping-task-center/ManualUploadEvidenceDialog.vue'; import ManualUploadEvidenceDialog from '@/features/workspace/shipping-task-center/ManualUploadEvidenceDialog.vue';
import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shipping-tasks.api'; import { downloadWorkspaceShippingExcelFile } from '@/features/workspace/api/shipping-tasks.api';
@@ -103,6 +104,7 @@ const route = useRoute();
const router = useRouter(); const router = useRouter();
const page = useChatPageContext(); const page = useChatPageContext();
const { t, te } = useI18n(); const { t, te } = useI18n();
const { submitPrimaryAction: submitProcessGatePrimaryAction } = useShippingProcessGateRecovery();
const { const {
reviewRun, reviewRun,
activeCase, activeCase,
@@ -233,11 +235,6 @@ const agentId = computed(() => String(route.params.agentId || ''));
const conversationId = computed(() => String(page.conversationId || route.query.conversation_id || '')); const conversationId = computed(() => String(page.conversationId || route.query.conversation_id || ''));
const itemNoFromQuery = computed(() => String(route.query.item_no || '')); const itemNoFromQuery = computed(() => String(route.query.item_no || ''));
const reviewFocus = computed(() => String(route.query.focus || '').trim()); const reviewFocus = computed(() => String(route.query.focus || '').trim());
/** Gate 恢复卡片导航上下文(复核台深链)。 */
const reviewGateNavigationContext = computed(() => ({
agentId: agentId.value,
conversationId: conversationId.value,
}));
const focusedEvidenceRef = ref<{ fieldId: string; lineIndex?: number } | null>(null); const focusedEvidenceRef = ref<{ fieldId: string; lineIndex?: number } | null>(null);
const workbenchMode = ref<ReviewWorkbenchMode>('standard'); const workbenchMode = ref<ReviewWorkbenchMode>('standard');
@@ -355,21 +352,47 @@ const caseContentSkeleton = computed(() => caseSwitchFailed.value && !activeCase
)); ));
/** /**
* 是否挂载右侧/窄屏「当前处理」卡:task_missing、正式 OT、或自动化进行中/失败态。 * 是否挂载右侧/窄屏「当前处理」卡:task_missing、正式 OT、自动化进行中/失败态,或人工 Gate。
* 核心逻辑:对象级重试优先挂在此卡上,未挂载时才回落底栏。 * 核心逻辑:当前任务是本页唯一 Gate 写入口,对象级重试优先挂在此卡上,未挂载时才回落底栏。
*/ */
const mountCurrentProcessingCard = computed(() => { const mountCurrentProcessingCard = computed(() => {
if (!displayCase.value) return false; if (!displayCase.value) return false;
if (caseContentSkeleton.value) return true; if (caseContentSkeleton.value) return true;
if (Boolean(displayCase.value.task_missing)) return true; if (Boolean(displayCase.value.task_missing)) return true;
if (hasFormalOt.value) return true; if (hasFormalOt.value) return true;
const gate = displayCase.value.process_gate;
if (
gate?.current_blocking_gate
&& !gate.technical_auto_only
&& String(gate.owner_type || '') !== 'system'
) return true;
const status = String(displayCase.value.automation?.status || '').trim().toLowerCase(); const status = String(displayCase.value.automation?.status || '').trim().toLowerCase();
return ['waiting_to_start', 'queued', 'running', 'failed', 'manual_fallback'].includes(status); return ['waiting_to_start', 'queued', 'running', 'failed', 'manual_fallback'].includes(status);
}); });
/** 对象级重试:有当前处理卡时放右栏/窄屏主卡;否则回落底栏。 */ /** 对象级重试:有当前处理卡时放右栏/窄屏主卡;否则回落底栏。 */
const showObjectRetryOnRail = computed(() => showStpRetry.value && mountCurrentProcessingCard.value); const showObjectRetryOnRail = computed(() => showStpRetry.value && mountCurrentProcessingCard.value);
const showObjectRetryOnFooter = computed(() => showStpRetry.value && !mountCurrentProcessingCard.value); const showObjectRetryOnFooter = computed(() => showStpRetry.value && !mountCurrentProcessingCard.value);
/** 当前任务卡是复核页唯一 Gate 写入口;Gate 主动作优先于泛化自动重试。 */
const currentTaskPrimaryAction = computed(() => (
displayCase.value?.process_gate?.primary_action
?? shippingProcessingProjection.value?.primaryAction
?? displayCase.value?.primary_action
?? null
));
const currentTaskRetryable = computed(() => (
showObjectRetryOnRail.value
|| (
Boolean(shippingProcessingProjection.value?.retryable)
&& !String(currentTaskPrimaryAction.value?.code || '').trim()
)
));
const currentTaskRecoveryActions = computed(() => (
(displayCase.value?.process_gate?.recovery_targets || []).map((target) => ({
code: String(target.action_code || '').trim(),
})).filter((action) => action.code)
));
/** 管理员诊断:后端 technical_progress / automation.technical 仅 admin 投影。 */ /** 管理员诊断:后端 technical_progress / automation.technical 仅 admin 投影。 */
const showAdminTaskMissingDiagnosis = computed(() => ( const showAdminTaskMissingDiagnosis = computed(() => (
@@ -1289,10 +1312,30 @@ async function handleCurrentTaskAction(
} }
break; break;
} }
case 'retry_inventory_matching': {
const summary = displayCase.value?.process_gate;
if (!summary) return;
const result = await submitProcessGatePrimaryAction(summary, { actionCode: code });
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
await reloadLatestDraft();
await refreshShippingProcessing();
}
break;
}
case 'mark_manual_uploaded': case 'mark_manual_uploaded':
await formalTodoPanelRef.value?.invokeActionByCode('mark_manual_uploaded'); await formalTodoPanelRef.value?.invokeActionByCode('mark_manual_uploaded');
break; break;
default: default:
if (code.startsWith('retry_') || code.startsWith('recheck_') || code.startsWith('regenerate_')) {
const summary = displayCase.value?.process_gate;
if (!summary) return;
const result = await submitProcessGatePrimaryAction(summary, { actionCode: code });
if (result.outcome === 'submitted' || result.outcome === 'refresh_needed') {
await reloadLatestDraft();
await refreshShippingProcessing();
}
break;
}
msg.info(t('chat.shippingOrderReview.currentTask.actionUnknown', { code })); msg.info(t('chat.shippingOrderReview.currentTask.actionUnknown', { code }));
} }
} }
@@ -3272,15 +3315,17 @@ watch(
:automation="displayCase?.automation" :automation="displayCase?.automation"
:show-retry="showObjectRetryOnRail" :show-retry="showObjectRetryOnRail"
:user-status="shippingProcessingProjection?.userStatus ?? displayCase?.user_status" :user-status="shippingProcessingProjection?.userStatus ?? displayCase?.user_status"
:retryable="displayCase?.process_gate?.current_blocking_gate ? false : (shippingProcessingProjection?.retryable ?? showObjectRetryOnRail)" :retryable="currentTaskRetryable"
:blocking-reason="shippingProcessingProjection?.blockingReason ?? displayCase?.blocking_reason" :blocking-reason="shippingProcessingProjection?.blockingReason ?? displayCase?.blocking_reason"
:primary-action="displayCase?.process_gate?.current_blocking_gate ? null : (shippingProcessingProjection?.primaryAction ?? displayCase?.primary_action)" :primary-action="currentTaskPrimaryAction"
:recovery-actions="currentTaskRecoveryActions"
:retrying="displayCase?.process_gate?.current_blocking_gate :retrying="displayCase?.process_gate?.current_blocking_gate
? (progressRetrying || caseSwitchLoading) ? (progressRetrying || caseSwitchLoading)
: (taskRetryButtonDisabled || progressRetrying || caseSwitchLoading)" : (taskRetryButtonDisabled || progressRetrying || caseSwitchLoading)"
:retry-exhausted-sources="taskInventoryExhaustedSources" :retry-exhausted-sources="taskInventoryExhaustedSources"
:loading="caseContentSkeleton" :loading="caseContentSkeleton"
@retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())" @retry="() => void (hasFormalOt ? retryFormalOtAutoProgress() : retryStpAutoCreate())"
@action="(code, params) => void handleCurrentTaskAction(code, params)"
/> />
<ReviewCustomerResolutionPanel <ReviewCustomerResolutionPanel
v-if="activeCase && !activeCase.customer_resolution?.resolved && showEligibilityAsPrimary" v-if="activeCase && !activeCase.customer_resolution?.resolved && showEligibilityAsPrimary"
@@ -3753,9 +3798,10 @@ watch(
:has-formal-ot="shippingProcessingProjection?.hasFormalOt ?? hasFormalOt" :has-formal-ot="shippingProcessingProjection?.hasFormalOt ?? hasFormalOt"
:shipping-notice-no="shippingProcessingProjection?.shippingNoticeNo ?? confirmedNoticeTaskNo" :shipping-notice-no="shippingProcessingProjection?.shippingNoticeNo ?? confirmedNoticeTaskNo"
:user-status="shippingProcessingProjection?.userStatus ?? displayCase?.user_status" :user-status="shippingProcessingProjection?.userStatus ?? displayCase?.user_status"
:retryable="displayCase?.process_gate?.current_blocking_gate ? false : (shippingProcessingProjection?.retryable ?? showObjectRetryOnRail)" :retryable="currentTaskRetryable"
:blocking-reason="shippingProcessingProjection?.blockingReason ?? displayCase?.blocking_reason" :blocking-reason="shippingProcessingProjection?.blockingReason ?? displayCase?.blocking_reason"
:primary-action="displayCase?.process_gate?.current_blocking_gate ? null : (shippingProcessingProjection?.primaryAction ?? displayCase?.primary_action)" :primary-action="currentTaskPrimaryAction"
:recovery-actions="currentTaskRecoveryActions"
:retrying="displayCase?.process_gate?.current_blocking_gate :retrying="displayCase?.process_gate?.current_blocking_gate
? (progressRetrying || caseSwitchLoading) ? (progressRetrying || caseSwitchLoading)
: (taskRetryButtonDisabled || progressRetrying || caseSwitchLoading)" : (taskRetryButtonDisabled || progressRetrying || caseSwitchLoading)"
@@ -3772,16 +3818,10 @@ watch(
@retry-preparation="() => void retryCaseInventoryFallback()" @retry-preparation="() => void retryCaseInventoryFallback()"
/> />
<ProcessGateRecoveryCard <ProcessGateRecoveryCard
v-if="!reparseProgressActive && showHumanBlockingGate && displayCase?.process_gate && hasCreatedShippingTask" v-if="showHumanBlockingGate && displayCase?.process_gate"
:summary="displayCase.process_gate" :summary="displayCase.process_gate"
:can-handle="workbenchActionsExecutable" :can-handle="false"
:navigation-context="reviewGateNavigationContext" :show-actions="false"
inventory-upload-mode="local"
:field-labels="reviewFieldLabels"
@refreshed="reloadLatestDraft"
@refresh-needed="reloadLatestDraft"
@confirm-customer="(taskNo) => void page.openShippingCustomerDialog?.(taskNo)"
@manual-upload="() => void openManualUploadRegistration()"
/> />
<ReviewProfileMatchPanel <ReviewProfileMatchPanel
:profile-match="displayCase?.profile_match" :profile-match="displayCase?.profile_match"
@@ -167,6 +167,18 @@ describe('ProcessGateRecoveryCard', () => {
expect(wrapper.find('[data-testid="process-gate-recovery-primary"]').exists()).toBe(true); expect(wrapper.find('[data-testid="process-gate-recovery-primary"]').exists()).toBe(true);
}); });
it('keeps the pending-item explanation but hides all actions in read-only mode', () => {
const wrapper = mount(ProcessGateRecoveryCard, {
props: { summary: baseSummary(), canHandle: false, showActions: false },
global: { plugins: [i18n] },
});
expect(wrapper.find('[data-testid="process-gate-recovery-card"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="process-gate-next-action"]').exists()).toBe(true);
expect(wrapper.find('[data-testid="process-gate-recovery-primary"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="process-gate-readonly-hint"]').exists()).toBe(false);
});
it('shows inventory upload as a secondary entry beside retrying inventory retrieval', async () => { it('shows inventory upload as a secondary entry beside retrying inventory retrieval', async () => {
const wrapper = mount(ProcessGateRecoveryCard, { const wrapper = mount(ProcessGateRecoveryCard, {
props: { props: {
@@ -18,15 +18,19 @@ import type { ShippingProcessGateUserSummary } from '../types/process-gate.types
/** 允许在卡片上展示的业务事实键(与后端 _USER_FACING_DETAIL_KEYS 对齐)。 */ /** 允许在卡片上展示的业务事实键(与后端 _USER_FACING_DETAIL_KEYS 对齐)。 */
const props = defineProps<{ const props = withDefaults(defineProps<{
summary: ShippingProcessGateUserSummary | null | undefined; summary: ShippingProcessGateUserSummary | null | undefined;
canHandle: boolean; canHandle: boolean;
/** 复核工作台仅展示待处理说明;唯一可执行入口由“当前任务”承担。 */
showActions?: boolean;
navigationContext?: ProcessGateNavigationContext; navigationContext?: ProcessGateNavigationContext;
/** 复核工作台直接打开人工上传登记;任务中心默认仍导航到任务详情。 */ /** 复核工作台直接打开人工上传登记;任务中心默认仍导航到任务详情。 */
inventoryUploadMode?: 'navigate' | 'local'; inventoryUploadMode?: 'navigate' | 'local';
/** 复核 Schema 的 field_code/field_id 到业务字段名映射。 */ /** 复核 Schema 的 field_code/field_id 到业务字段名映射。 */
fieldLabels?: Record<string, string>; fieldLabels?: Record<string, string>;
}>(); }>(), {
showActions: true,
});
const emit = defineEmits<{ const emit = defineEmits<{
refreshed: []; refreshed: [];
@@ -191,7 +195,7 @@ async function runInventoryUpload() {
<dd class="text-secondary">{{ nextActionDescription }}</dd> <dd class="text-secondary">{{ nextActionDescription }}</dd>
</div> </div>
</dl> </dl>
<div class="mt-3 flex flex-wrap items-center gap-2"> <div v-if="showActions !== false" class="mt-3 flex flex-wrap items-center gap-2">
<button <button
v-if="hasRecoveryAction && canHandle" v-if="hasRecoveryAction && canHandle"
type="button" type="button"
@@ -66,6 +66,7 @@ function mountStrip(projection: ShippingProcessingProjection, polling = false) {
chat: { chat: {
shippingOrderReview: { shippingOrderReview: {
workflowProgress: { polling: '正在刷新进度…' }, workflowProgress: { polling: '正在刷新进度…' },
currentTask: { statusWaitingHuman: '待人工处理' },
}, },
shippingProcessing: { shippingProcessing: {
progress: { progress: {
@@ -130,6 +131,27 @@ describe('ReviewProgressStrip', () => {
expect(wrapper.find('[data-testid="review-progress-refresh"]').exists()).toBe(true); expect(wrapper.find('[data-testid="review-progress-refresh"]').exists()).toBe(true);
}); });
it('gives manual gate priority over stale automating status', () => {
const wrapper = mountStrip(buildProjection({
status: 'automating',
userStatus: 'waiting_human',
stage: 'inventory_fetching',
currentGate: {
gateCode: 'inventory_preparation',
status: 'blocked_manual',
nextActionCode: 'upload_inventory_file',
blockingReasonCode: 'inventory_file_empty',
attemptNo: 3,
},
}), true);
const title = wrapper.get('[data-testid="review-progress-title"]').text();
expect(title).toContain('待人工处理');
expect(title).toContain('inventory_fetching');
expect(title).not.toContain('系统处理中');
expect(wrapper.find('[data-testid="review-progress-refresh"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-workflow-progress-polling"]').exists()).toBe(false);
});
it('hides stage nodes and warns when stageNodes invalid', () => { it('hides stage nodes and warns when stageNodes invalid', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined); const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
const wrapper = mountStrip(buildProjection({ stageNodes: [] })); const wrapper = mountStrip(buildProjection({ stageNodes: [] }));
@@ -44,10 +44,19 @@ const stageNodes = computed(() => readAuthoritativeStageNodes(props.projection))
const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'workbench')); const rangeHint = computed(() => buildProgressRangeHint(props.projection, 'workbench'));
/**
* 人工阻断优先于遗留 processing/automating 投影,避免已中断任务仍显示系统处理中并持续轮询。
*/
const isWaitingHuman = computed(() => (
props.projection.userStatus === 'waiting_human'
|| String(props.projection.currentGate?.status || '').trim().toLowerCase() === 'blocked_manual'
));
/** /**
* 是否处于系统自动推进(用于刷新按钮,不进标题文案)。 * 是否处于系统自动推进(用于刷新按钮,不进标题文案)。
*/ */
const isAutomating = computed(() => { const isAutomating = computed(() => {
if (isWaitingHuman.value) return false;
const status = String(props.projection.status || '').trim().toLowerCase(); const status = String(props.projection.status || '').trim().toLowerCase();
if (!AUTOMATING_STATUSES.has(status)) return false; if (!AUTOMATING_STATUSES.has(status)) return false;
const next = String(props.projection.currentGate?.nextActionCode || '').trim().toLowerCase(); const next = String(props.projection.currentGate?.nextActionCode || '').trim().toLowerCase();
@@ -57,11 +66,15 @@ const isAutomating = computed(() => {
}); });
/** /**
* 标题:默认「订单处理进度 · 当前阶段」;自动推进状态切换为「系统处理中 · 当前阶段」; * 标题:人工阻断优先显示「待人工处理 · 当前阶段」;自动推进才显示「系统处理中 · 当前阶段」;
* 无阶段名时退化为纯标题,保证标题行至少可读。 * 无阶段名时退化为纯标题,保证标题行至少可读。
*/ */
const titleLine = computed(() => { const titleLine = computed(() => {
const stage = currentStageName.value; const stage = currentStageName.value;
if (isWaitingHuman.value) {
const waitingHuman = t('chat.shippingOrderReview.currentTask.statusWaitingHuman');
return stage && stage !== '—' ? `${waitingHuman} · ${stage}` : waitingHuman;
}
if (isAutomating.value) { if (isAutomating.value) {
const withStage = te('chat.shippingProcessing.progress.systemProcessingWithStage'); const withStage = te('chat.shippingProcessing.progress.systemProcessingWithStage');
if (withStage && stage && stage !== '—') { if (withStage && stage && stage !== '—') {
@@ -170,7 +183,7 @@ function nodeShortLabel(stage: string): string {
{{ t('chat.shippingProcessing.progress.currentStage', { stage: currentStageName }) }} {{ t('chat.shippingProcessing.progress.currentStage', { stage: currentStageName }) }}
</span> </span>
<span <span
v-if="polling" v-if="polling && !isWaitingHuman"
class="ml-2 text-[11px] font-normal text-muted" class="ml-2 text-[11px] font-normal text-muted"
data-testid="review-workflow-progress-polling" data-testid="review-workflow-progress-polling"
> >
@@ -9,7 +9,7 @@ import { computed, inject, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute } from 'vue-router'; import { useRoute } from 'vue-router';
import { import {
LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen, ClipboardCheck, LayoutGrid, Bot, FileText, User, LogOut, Edit, Megaphone, Clock, Package, PanelLeftClose, PanelLeftOpen, ClipboardCheck,
ChevronDown, ChevronRight, ContactRound, ListChecks, Inbox, ChevronDown, ChevronRight, ContactRound, Inbox,
} from 'lucide-vue-next'; } from 'lucide-vue-next';
import { WORKSPACE_PATHS } from '../constants/routes'; import { WORKSPACE_PATHS } from '../constants/routes';
import { WORKSPACE_KEY } from '../composables/workspace.context'; import { WORKSPACE_KEY } from '../composables/workspace.context';
@@ -167,14 +167,6 @@ onBeforeUnmount(() => {
<ContactRound class="h-4 w-4" /> <ContactRound class="h-4 w-4" />
<span>{{ $t('workspace.nav.shippingCustomers') }}</span> <span>{{ $t('workspace.nav.shippingCustomers') }}</span>
</RouterLink> </RouterLink>
<RouterLink
:to="WORKSPACE_PATHS.shippingNoticeTasks"
class="ws-nav-btn py-2.5 text-[13px]"
:class="{ 'ws-nav-btn--active': isActive(['workspace-shipping-tasks']) }"
>
<ListChecks class="h-4 w-4" />
<span>{{ $t('workspace.nav.shippingTasks') }}</span>
</RouterLink>
</div> </div>
</div> </div>
<RouterLink <RouterLink
@@ -150,4 +150,39 @@ describe('TaskTodoPanel actionsExecutable', () => {
await flushPromises(); await flushPromises();
expect(postGateAction).not.toHaveBeenCalled(); expect(postGateAction).not.toHaveBeenCalled();
}); });
it('does not render legacy actions while inventory preparation is auto-progressing', () => {
const task = detail();
task.ui_state = {
...task.ui_state,
action_buttons: [{
id: 'edit_formal_task',
label: '编辑正式任务',
message: '',
variant: 'primary',
}],
summary: {
title: '获取库存',
message: '系统正在自动处理',
allowed_actions: ['edit_formal_task'],
},
process_gate: {
execution_no: 'SPE-1',
technical_auto_only: true,
current_blocking_gate: {
gate_code: 'inventory_preparation',
evaluation_version: 3,
next_action_code: 'poll_inventory_preparation',
},
},
} as ShippingTaskDetail['ui_state'];
const wrapper = mount(TaskTodoPanel, {
props: { detail: task, actionsExecutable: true },
global: { plugins: [i18n] },
});
// 自动推进阶段只允许 Gate 的刷新进度入口,不能泄漏正式任务编辑。
expect(wrapper.text()).not.toContain('编辑正式任务');
});
}); });
@@ -221,8 +221,9 @@ const UNIFIED_OWNED_ACTION_IDS = new Set([
const visibleActions = computed(() => { const visibleActions = computed(() => {
// [STEP] 订单处理工作台:写操作仅 Footer;不渲染 Notice action_buttons(D1)。 // [STEP] 订单处理工作台:写操作仅 Footer;不渲染 Notice action_buttons(D1)。
if (props.hidePrimaryActions) return []; if (props.hidePrimaryActions) return [];
// [STEP] Gate 阻断时后端已清零 action_buttons;前端再兜底隐藏,避免双真相。 // [STEP] Gate 阻断或系统自动等待时均由统一 Gate 投影拥有动作;
if (hasBlockingGate.value) return []; // 禁止历史 action_buttons(如 edit_formal_task)穿透到当前阶段。
if (hasBlockingGate.value || isSystemAutoWait.value) return [];
return actionButtons.value.filter((action) => { return actionButtons.value.filter((action) => {
const id = String(action.id || ''); const id = String(action.id || '');
if (id === 'regenerate_manual_upload_todo') return false; if (id === 'regenerate_manual_upload_todo') return false;