!15 perf(shipping-notice): 优化发货任务性能,修复上传流程与终态问题

Merge pull request !15 from 曹惠鹏/hugo-shipping-notice
This commit is contained in:
sophie authored and Gitee committed 2026-08-27 11:40:31 +00:00
commit 09deada712
29 files changed
+1074 -128

No files matched your search

@@ -548,8 +548,14 @@ def workspace_shipping_task_detail(task_no: str):
task = get_task_visible_to_user(task_no, user.id, is_admin=is_admin)
if not task:
raise NotFoundError('Not found')
# [PERF] view=workbench 供订单生命周期工作台首屏裁剪:剔除复核编辑器重字段,
# 响应体与序列化耗时显著下降;缺省/非法值一律回退 full,保持兼容。
view = str(request.args.get('view', 'full') or 'full').strip().lower()
if view not in ('full', 'workbench'):
view = 'full'
return _ok(serialize_task_detail(
task, viewer_user_id=user.id, is_admin=is_admin, include_stage_context=True,
view=view,
))
+2 -1
View File
@@ -265,7 +265,8 @@ class ShippingTaskEvent(Base):
detail_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
before_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
after_json: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
source: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, index=True)
# source 记录触发/来源码(如 freight_upload_rpa_callback_succeeded);保证能容纳长触发码。
source: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
actor_id: Mapped[Optional[int]] = mapped_column(ForeignKey('users.id'), nullable=True, index=True)
request_id: Mapped[Optional[str]] = mapped_column(String(64), nullable=True, index=True)
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True)
@@ -362,7 +362,8 @@ def _trigger_freight_upload_rpa(
"""
触发货代上传 RPA:创建 Attempt、写 trigger、进入 upload_rpa_pending。
核心逻辑:达最大次数则转人工;trigger 目录不可用时返回失败并允许手工上传。
核心逻辑:不按次数熔断(业务决定),每次触发都下发 Worker;trigger 目录不可用、
配置未启用或 Worker 未就绪时才返回失败并允许手工上传。
Args:
task: 已生成 Excel 的任务。
@@ -376,22 +377,10 @@ def _trigger_freight_upload_rpa(
body = dict(payload or {})
attempts = upload_rpa_attempts(task)
max_attempts = max_rpa_upload_attempts()
if attempts >= max_attempts:
apply_task_transition(task, TaskTransition.WAITING_UPLOAD)
task.error_message = t('workflow.fulfillment.upload_exhausted', lang=lang).format(attempts=attempts)
log_task_event(task, 'upload_rpa_exhausted', {'attempts': attempts, 'max_attempts': max_attempts})
db.session.commit()
# RPA 成功只登记可信回执;P0-3 completed 仍必须由 receipt Gate 重读事实决定。
from app.services.shipping_notice.auto_progress_controller import submit_auto_progress
submit_auto_progress(task=task, trigger='freight_upload_rpa_callback_succeeded', commit=True)
return tool_response(
status='needs_human',
task=task,
message=task.error_message,
data=serialize_task_for_tool(task),
stop_agent_turn=True,
)
# [STEP] 业务决定:货代上传 RPA 不按次数熔断(不再因 attempts>=max_attempts 提前转为
# needs_human)。自动推进与人工点击都会继续下发 Worker;真正不可自愈的失败由配置就绪
# 校验或人工确认(mark_manual_uploaded)兜底,避免“点了没反应”。attempts/max_attempts
# 仍用于运行中提示文案。
if not task.export_file_path:
return tool_response(
@@ -501,6 +490,12 @@ def _trigger_freight_upload_rpa(
)
apply_task_transition(task, TaskTransition.UPLOAD_RPA_PENDING)
# 业务决定:重新发起 RPA 上传时立即把 upload_status 置为 uploading 并清空上一次失败原因,
# 使前端在触发瞬间即显示「上传中」并隐藏旧的失败文案;RPA 结果回来后由 complete_attempt 覆盖为真实状态。
task.upload_status = 'uploading'
task.upload_error_code = None
task.upload_error_message = None
task.error_message = None
timeout = _rpa_upload_timeout_seconds()
set_task_step_progress(
task,
@@ -2101,6 +2096,7 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
except (ConflictError, ValidationError, TypeError, ValueError) as exc:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
_close_uploaded_task(task, actor_type='user', actor_id=attempt.operator_id)
log_task_event(
task,
'upload_manual_confirmed',
@@ -2155,6 +2151,39 @@ def upload_to_freight(payload: dict[str, Any]) -> dict[str, Any]:
)
def _close_uploaded_task(
task: ShippingNotice,
*,
actor_type: str,
actor_id: int | None,
) -> None:
"""将已验证的上传成功事实同步到任务、OT 阶段和正式 Execution。
核心逻辑:人工确认与 RPA 回调均先由 UploadAttempt 写入 ``upload_status=uploaded``;
此处统一清理历史上传阻断并收口 Gate,避免旧 ``upload_rpa_pending`` 被后续投影读取。
Args:
task: 已具有可信上传成功事实的任务。
actor_type: 成功来源(user 或 rpa)。
actor_id: 可选操作主体标识,用于 Gate 审计。
"""
apply_task_transition(task, TaskTransition.UPLOADED)
from app.services.shipping_notice.order_task_stage_machine import sync_order_task_stage_for_notice
from app.services.shipping_notice.process_gate_bridge import (
find_execution_for_task,
sync_fulfillment_gates_from_task,
)
sync_order_task_stage_for_notice(task)
execution = find_execution_for_task(task)
if execution is not None and str(execution.status or '').strip().lower() != 'completed':
sync_fulfillment_gates_from_task(
execution=execution,
actor_type=actor_type,
actor_id=actor_id,
)
def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
"""
RPA 上传货代回调入口,报告成功或失败并更新任务终态。
@@ -2239,12 +2268,7 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
return tool_response(status='failed', task=task, message=str(exc), data=serialize_task_for_tool(task))
# 重复 callback 由 Attempt 的持久化结果决定,不能按本次请求值重写 UI 状态。
if completed.status == 'succeeded':
apply_task_transition(task, TaskTransition.UPLOADED)
from app.services.shipping_notice.order_task_stage_machine import (
sync_order_task_stage_for_notice,
)
sync_order_task_stage_for_notice(task)
_close_uploaded_task(task, actor_type='rpa', actor_id=None)
set_task_step_progress(
task,
step_key="step7_upload_freight",
@@ -2334,12 +2358,8 @@ def rpa_report_upload(payload: dict[str, Any]) -> dict[str, Any]:
)
task.error_message = completed.error_message or 'RPA upload failed'
log_task_event(task, "upload_rpa_failed", {"artifact_id": completed.artifact_id, "attempt_id": completed.id, "error": task.error_message})
db.session.flush()
attempts = upload_rpa_attempts(task)
max_attempts = max_rpa_upload_attempts()
if attempts >= max_attempts:
task.error_message = t("workflow.fulfillment.upload_exhausted", lang=lang).format(attempts=attempts)
log_task_event(task, "upload_rpa_exhausted", {"attempts": attempts, "max_attempts": max_attempts})
# 业务决定:货代上传 RPA 不按次数熔断,失败后仍可重试或转人工确认;此处保留真实失败原因,
# 不再以「已达最大重试次数」覆盖错误正文。
db.session.commit()
return tool_response(
status="needs_human",
@@ -41,14 +41,14 @@ _LOGGER = logging.getLogger(__name__)
def _derived_fulfillment_status(task: ShippingNotice) -> str:
"""从领域结果事实推导履约分支,不读取旧流程状态字段。"""
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
if upload_status in {'uploaded', 'succeeded', 'success'}:
return 'uploaded'
pending = str(getattr(task, 'pending_human_reason', None) or '').strip()
if pending in {'rpa_pending', 'rpa_exhausted', 'inventory_unavailable'}:
return 'waiting_inventory'
if pending in {'upload_rpa_pending', 'upload_rpa_failed', 'upload_result_unknown'}:
return 'waiting_upload'
upload_status = str(getattr(task, 'upload_status', None) or '').strip().lower()
if upload_status in {'uploaded', 'succeeded', 'success'}:
return 'uploaded'
if upload_status == 'failed':
return 'upload_failed'
if isinstance(getattr(task, 'shortage_json', None), (dict, list)) and task.shortage_json:
@@ -637,6 +637,16 @@ def project_user_gate_summary(execution: ShippingProcessExecution) -> dict[str,
code = str(target.get('action_code') or '').strip()
if code and code not in allowed_actions and is_business_user_action(code):
allowed_actions.append(code)
# [STEP] 货代上传 RPA 失败(含配置/登录/平台拒绝等用户无法自愈的故障)时,业务用户
# 既可按 Gate 授权重试 RPA,也可直接人工确认已上传,避免卡在 RPA 重试循环。
# mark_manual_uploaded 由 Gate 授权后打开人工上传确认,不取代 retry 主动作。
if (
str(blocking.get('gate_code') or '').strip().lower() == 'freight_upload_rpa'
and str(blocking.get('status') or '').strip().lower()
in {'blocked_retryable', 'blocked_manual', 'failed_terminal'}
and 'mark_manual_uploaded' not in allowed_actions
):
allowed_actions.append('mark_manual_uploaded')
from app.services.shipping_notice.recovery_plan_contract import recovery_plan_for_action
action_items = []
@@ -923,7 +923,6 @@ def _enrich_task_center_fields(
Returns:
同一 data 引用(已 enrich)。
"""
data["todo_category"] = task_todo_category(task)
data["item_kind"] = "task"
data["todo_ref"] = task.task_no
data["created_by"] = task.user_id
@@ -935,7 +934,15 @@ def _enrich_task_center_fields(
# [STEP] 懒导入避免与 ui_state ↔ query_service 循环依赖。
from app.services.shipping_notice.ui_state import build_task_ui_state
data["ui_state"] = build_task_ui_state(task, include_stage_context=include_stage_context)
ui_state = build_task_ui_state(task, include_stage_context=include_stage_context)
data["ui_state"] = ui_state
# [PERF] todo_category 与 ui_state 同源(均由 resolve_task_ui_state 推导):直接在
# 已构建的 ui_state 上推导,避免 task_todo_category 在请求内对同一任务再算一次
# resolve_task_ui_state(每次含 has_dynamic_order_lines 的取数),削减重复查询。
data["todo_category"] = _todo_category_from_ui(
ui_state.get("checkpoint_code"),
CheckpointKind(str(ui_state.get("checkpoint_kind"))),
)
_inject_unified_processing_fields(task, data)
# [BE-06] WorkflowItem 账本已下线;固定为 None,禁止前端再当 OT 身份源。
data['workflow_item'] = None
@@ -968,6 +975,7 @@ def serialize_task_detail(
viewer_user_id: int | None = None,
is_admin: bool = False,
include_stage_context: bool = False,
view: str = 'full',
) -> dict[str, Any]:
"""
工作台任务详情用的 DETAIL 投影(含 lines、events 与任务中心 enrich)。
@@ -977,8 +985,21 @@ def serialize_task_detail(
viewer_user_id: 当前查看者;用于 can_handle。
is_admin: 是否管理员视图。
include_stage_context: 是否让内嵌 ui_state 附带 stage_context(避免调用方重复 build)。
view: 投影视图。``full`` 返回完整详情(含复核编辑器数据);``workbench`` 为
订单生命周期工作台首屏裁剪版:工作台只消费 ui_state + 进度/产物/行摘要,
不读取行明细/订单头/事件/字段冲突等复核编辑器重字段。把这些字段从响应剔除,
避免每次进入工作台都拉取 67KB 级详情(对应 /shipping-tasks/:task_no 的大响应)。
"""
data = serialize_task(task, TaskProjection.DETAIL)
if view == 'workbench':
# [PERF] 工作台首屏不消费以下复核编辑器字段,剔除后显著缩小响应体与序列化耗时。
# 仅剔除编辑重字段;ui_state(含 stage_context)、notice_line_summary、
# artifact_summary、_fulfillment_timeline(export_artifacts) 与进度字段原样保留。
for key in (
'lines', 'order_header', 'order_header_fields', 'order_line_fields',
'events', 'field_conflicts',
):
data.pop(key, None)
return _enrich_task_center_fields(
task, data, viewer_user_id=viewer_user_id, is_admin=is_admin,
include_stage_context=include_stage_context,
@@ -1146,12 +1167,15 @@ def list_freight_notice_groups_for_task(
# 轻量投影仅返回动作码,避免逐张 Notice 跑完整 build_task_ui_state 造成 N 倍放大。
from app.services.shipping_notice.ui_state import project_notice_available_actions
available_actions = project_notice_available_actions(notice)
# [STEP] upload_mode/upload_attempt 从 ShippingUploadAttempt 权威事实解析。
# denormalized Notice.upload_mode 恒为 None,不能作为「人工/RPA」展示来源。
upload_mode, upload_attempt = _task_upload_attempt_facts(notice.id)
items.append({
'business_no': business_no,
'po_number': po_number,
'upload_status': notice.upload_status,
'upload_mode': notice.upload_mode,
'upload_attempt': notice.upload_attempt,
'upload_mode': upload_mode,
'upload_attempt': upload_attempt,
'upload_error_code': notice.upload_error_code,
# 逐单失败原因:优先取最近一次上传的错误正文,回退到任务级 error_message。
'upload_error_message': (notice.upload_error_message or notice.error_message or '')[:500] or None,
@@ -1167,6 +1191,38 @@ def list_freight_notice_groups_for_task(
}
def _task_upload_attempt_facts(task_id: int | None) -> tuple[str | None, int]:
"""从 ShippingUploadAttempt 权威事实解析任务上传方式与尝试次数。
读取侧不再消费 denormalized 的 Notice.upload_mode / upload_attempt(这两个列从未被
写入真实值,恒为 None/0)。成功态的 mode 优先(通知完成面以此区分人工/RPA),
否则回退最近一条 attempt 的 mode,与 ui_state._build_stage_context 的判定保持一致。
Args:
task_id: 正式 Notice 主键;为空时返回 (None, 0)。
Returns:
tuple[str | None, int]: (mode, attempt_count);无任何 attempt 时返回 (None, 0)。
"""
if not task_id:
return None, 0
attempts = (
ShippingUploadAttempt.query
.join(ShippingExportArtifact, ShippingUploadAttempt.artifact_id == ShippingExportArtifact.id)
.filter(ShippingExportArtifact.task_id == int(task_id))
.order_by(ShippingUploadAttempt.created_at.desc(), ShippingUploadAttempt.id.desc())
.all()
)
if not attempts:
return None, 0
succeeded = next(
(item for item in attempts if str(item.status or '').strip().lower() == 'succeeded'),
None,
)
anchor = succeeded or attempts[0]
return (anchor.mode if anchor is not None else None), len(attempts)
def _notice_po_number(notice: ShippingNotice) -> str:
"""读取 Notice 的正式客户 PO;动态 Schema、冻结快照和兼容投影按稳定顺序回退。"""
header = current_header_field_values_or_empty(notice)
@@ -2104,7 +2104,11 @@ def _eml_aggregate_user_group(
upload_states: list[str],
children: list[dict[str, Any]],
) -> str:
"""按用户关注优先级确定一张 EML Intake 卡的唯一分组。"""
"""按用户关注优先级确定一张 EML Intake 卡的唯一分组。
完成附件须已上传成功,或已被正式裁决为无需上传(例如非订单);两者都不能
被旧 Unit 的处理中状态重新覆盖。
"""
if any(state in {'failed', 'retryable'} for state in states):
return 'failed'
if any(state in {'waiting_human', 'idle'} for state in states):
@@ -2114,7 +2118,7 @@ def _eml_aggregate_user_group(
if any(state == 'cancelled' for state in states):
return 'cancelled'
if states and all(state == 'completed' for state in states) and all(
state == 'succeeded' for state in upload_states
state in {'succeeded', 'not_required'} for state in upload_states
):
return 'completed'
if children and all(bool(item.get('is_archived')) for item in children):
@@ -2238,17 +2242,21 @@ def _eml_aggregate_document_children(
ShippingOrderReviewStream.current_case_id == ShippingOrderReviewCase.id,
).filter(
ShippingOrderReviewStream.document_id == int(document.id),
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready', 'confirming')),
ShippingOrderReviewCase.status.in_(('unreviewed', 'draft', 'ready', 'confirming', 'non_order')),
).one_or_none()
)
)
if review_case is not None and str(review_case.status or '') not in {
'unreviewed', 'draft', 'ready', 'confirming',
review_case_status = str(getattr(review_case, 'status', '') or '').strip().lower()
non_order_completed = review_case_status == 'non_order'
if review_case is not None and review_case_status not in {
'unreviewed', 'draft', 'ready', 'confirming', 'non_order',
}:
review_case = None
review_required = review_required or review_case is not None
review_case_status = ''
non_order_completed = False
review_required = review_required or (review_case is not None and not non_order_completed)
review_bundle: dict[str, Any] | None = None
if review_case is not None:
if review_case is not None and not non_order_completed:
from app.services.shipping_notice.reconciliation_projector import (
project_review_case_projection_bundle,
)
@@ -2275,13 +2283,17 @@ def _eml_aggregate_document_children(
is_current_reviewable_candidate(review_candidate)
and int(getattr(review_candidate, 'primary_document_id', 0) or 0) == int(document.id)
)
review_status = str((review_bundle or {}).get('user_status') or 'waiting_human')
review_stage = str((review_bundle or {}).get('user_stage') or 'order_review')
review_gate = (review_bundle or {}).get('current_gate')
review_reason = (review_bundle or {}).get('blocking_reason')
review_primary = (review_bundle or {}).get('primary_action')
review_actions = list((review_bundle or {}).get('available_actions') or [])
if review_case is not None and not has_current_candidate:
review_status = 'completed' if non_order_completed else str(
(review_bundle or {}).get('user_status') or 'waiting_human'
)
review_stage = 'completed' if non_order_completed else str(
(review_bundle or {}).get('user_stage') or 'order_review'
)
review_gate = None if non_order_completed else (review_bundle or {}).get('current_gate')
review_reason = None if non_order_completed else (review_bundle or {}).get('blocking_reason')
review_primary = None if non_order_completed else (review_bundle or {}).get('primary_action')
review_actions = [] if non_order_completed else list((review_bundle or {}).get('available_actions') or [])
if review_case is not None and not non_order_completed and not has_current_candidate:
# 无 Candidate 不等于无人工处置:review_required Unit 已有正式 Case,
# 后端按 Case 的可用动作裁决入口。批次页的「重新解析」只能来自
# Case 已授予的 reparse;前端不得由“状态待确认”自行补出该动作。
@@ -2340,9 +2352,9 @@ def _eml_aggregate_document_children(
'conversation_id': str(intake.conversation_id or '').strip() or None,
'submission_no': '',
'intake_no': str(intake.intake_no),
'status': 'failed' if (failed or unit_failed) else 'waiting_review' if review_required else 'processing',
'stage': 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
'stage_label_key': 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
'status': 'completed' if non_order_completed else 'failed' if (failed or unit_failed) else 'waiting_review' if review_required else 'processing',
'stage': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
'stage_label_key': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
'progress_version': int(getattr(intake, 'progress_version', None) or 1),
'last_activity_at': _iso(document.updated_at) or _iso(intake.updated_at) or '',
'current_gate': review_gate if review_case is not None else None,
@@ -2354,14 +2366,14 @@ def _eml_aggregate_document_children(
{'code': review_reason_code, 'details': {}} if review_required else None
),
'primary_action': review_primary if (review_case is not None or unit_failed) else None,
'user_status': 'failed' if (failed or unit_failed) else review_status if review_case is not None else 'waiting_human' if review_required else 'running',
'user_stage': 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
'user_group': 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'processing',
'facts': {'upload_state': 'not_created'},
'user_status': 'completed' if non_order_completed else 'failed' if (failed or unit_failed) else review_status if review_case is not None else 'waiting_human' if review_required else 'running',
'user_stage': 'completed' if non_order_completed else 'document_parsing' if (failed or unit_failed) else review_stage if review_required else 'candidate_creating',
'user_group': 'completed' if non_order_completed else 'failed' if (failed or unit_failed) else 'waiting_human' if review_required else 'processing',
'facts': {'upload_state': 'not_required' if non_order_completed else 'not_created'},
# 接收解析阶段入口由后端裁决:开放 Case 可进入处置;尚无 Case 的失败
# 附件只有明确授予 reparse 时才展示当前阶段,不能由前端按失败态猜测。
'intake_parse_authorized': bool(
(review_case is not None and not has_current_candidate)
(review_case is not None and not non_order_completed and not has_current_candidate)
or (unit_reparse_authorized and 'reparse' in review_actions)
),
'child_order_tasks': [],
@@ -2451,13 +2463,19 @@ def _aggregate_eml_order_task_work_items(
upload_states = [_upload_state(item) for item in aggregate_children]
failed_count = sum(state in {'failed', 'retryable'} for state in states)
waiting_count = sum(state in {'waiting_human', 'idle'} for state in states)
# 用户视角的完成必须同时满足任务完成和货代上传成功;候选已生成等中间态仍在处理中。
# 用户视角的完成必须同时满足任务完成,且已货代上传或已正式裁决无需上传;
# 候选已生成等中间态仍在处理中。
completed_count = sum(
state == 'completed' and upload_state == 'succeeded'
state == 'completed' and upload_state in {'succeeded', 'not_required'}
for state, upload_state in zip(states, upload_states)
)
processing_count = len(aggregate_children) - failed_count - waiting_count - completed_count
all_uploaded = bool(upload_states) and all(state == 'succeeded' for state in upload_states)
all_completed_without_upload = bool(upload_states) and all(
state == 'not_required' for state in upload_states
)
all_completed_for_batch = bool(upload_states) and all(
state in {'succeeded', 'not_required'} for state in upload_states
)
aggregate_group = _eml_aggregate_user_group(
states=states,
upload_states=upload_states,
@@ -2476,13 +2494,14 @@ def _aggregate_eml_order_task_work_items(
if str(item.get('user_stage') or '').strip().lower() == 'pre_ot_stp'
else str(item.get('user_stage') or item.get('stage') or '').strip()
for item in aggregate_children
if _state(item) != 'completed' or _upload_state(item) != 'succeeded'
if _state(item) != 'completed' or _upload_state(item) not in {'succeeded', 'not_required'}
),
'completed',
)
aggregate_upload_state = (
'failed' if any(state == 'failed' for state in upload_states) else
'succeeded' if all_uploaded else
'not_required' if all_completed_without_upload else
'succeeded' if all_completed_for_batch else
'uploading' if any(state in {'uploading', 'callback_received'} for state in upload_states) else
'manual_upload_pending' if any(state == 'manual_upload_pending' for state in upload_states) else
'not_created'
@@ -2792,6 +2811,13 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]:
processing_stage=str(item.get('user_stage') or item.get('stage') or '').strip() or None,
)
lifecycle_stage = lifecycle['lifecycle_stage']
if lifecycle_stage == 'upload_complete':
# [STEP] 已核验上传成功是唯一完成事实。即便 Gate 投影异步滞后,聊天与
# 批次中心也不得保留历史恢复动作或“下一步”。
primary = None
secondary = []
else:
secondary = []
if primary is not None:
action_target = _action_lifecycle_target(primary.get('code'), lifecycle_stage=lifecycle_stage)
if action_target is not None:
@@ -2799,20 +2825,20 @@ def _processing_ui_state_from_item(item: dict[str, Any]) -> dict[str, Any]:
primary['target_surface'] = 'order_lifecycle_workbench'
primary['target_lifecycle_stage'] = action_target
primary_code = str((primary or {}).get('code') or '').strip()
secondary: list[dict[str, Any]] = []
for raw_code in item.get('available_actions') or []:
code = str(raw_code or '').strip()
if not code or code == primary_code:
continue
action_target = _action_lifecycle_target(code, lifecycle_stage=lifecycle_stage)
action = {'code': code, 'enabled': True}
if action_target is not None:
action.update({
'execution_mode': 'navigate',
'target_surface': 'order_lifecycle_workbench',
'target_lifecycle_stage': action_target,
})
secondary.append(action)
if lifecycle_stage != 'upload_complete':
for raw_code in item.get('available_actions') or []:
code = str(raw_code or '').strip()
if not code or code == primary_code:
continue
action_target = _action_lifecycle_target(code, lifecycle_stage=lifecycle_stage)
action = {'code': code, 'enabled': True}
if action_target is not None:
action.update({
'execution_mode': 'navigate',
'target_surface': 'order_lifecycle_workbench',
'target_lifecycle_stage': action_target,
})
secondary.append(action)
return {
'status': str(item.get('user_status') or item.get('status') or 'running'),
'stage': str(item.get('user_stage') or item.get('stage') or ''),
@@ -852,6 +852,12 @@ def build_task_ui_state(
}
if download_action['code'] not in action_codes:
actions['secondary'].append(download_action)
if stage['code'] == 'upload_complete':
# [STEP] 上传成功已核验即为生命周期终态。历史 Gate 可能在异步收口窗口仍
# 可读取,但不能继续下发“下一步”或下载 Excel 等工作台动作;完成面只提供
# 同 PO 成功通知明细与批次 ZIP 的只读留档入口。
process_gate = None
actions = {'primary': None, 'secondary': []}
# summary 仅作为 ui_state.actions 的只读镜像,禁止由 checkpoint 或任务字段另行推导。
summary['allowed_actions'] = [
str(item.get('code'))
@@ -54,8 +54,9 @@ def start_rpa_attempt(task: ShippingNotice, *, artifact_id: int | None = None, i
return existing
if ShippingUploadAttempt.query.filter_by(artifact_id=artifact.id, status='succeeded').first():
raise ConflictError('Artifact has already been uploaded', code='SHIPPING.UPLOAD_ARTIFACT_COMPLETED')
if ShippingUploadAttempt.query.filter(ShippingUploadAttempt.artifact_id == artifact.id, ShippingUploadAttempt.status.in_({'timed_out', 'unknown'})).first():
raise ConflictError('Upload result is unknown and must be reconciled before retry', code='SHIPPING.UPLOAD_RETRY_FORBIDDEN_UNTIL_TERMINAL')
# 业务决定:结果未知(timed_out/unknown)不再阻断重新下发 RPA。该状态表示“无法判断上传是否成功/失败”,
# 为避免用户卡死、无法继续尝试,允许再次触发;若上次实际上传成功,重复触发可能产生重复单,
# 需由用户在 CRANE 侧核查(错误文案已提示)。幂等 key 去重仍保留。
attempt_no = (db.session.query(ShippingUploadAttempt).filter_by(artifact_id=artifact.id).count() + 1)
attempt = ShippingUploadAttempt(
artifact_id=artifact.id, attempt_no=attempt_no, mode='rpa', idempotency_key=key,
@@ -195,7 +196,10 @@ def complete_attempt(
):
attempt.status = 'unknown'
attempt.error_code = 'UPLOAD_RESULT_UNKNOWN'
attempt.error_message = str(error_message or 'Upload result remains unknown')[:500]
attempt.error_message = str(
error_message
or '无法判断上传是否成功/失败:RPA 结果未确认,可能已上传成功但未出现成功提示,或上传配置(result_selector/success_texts)有误;请人工核查或确认已上传'
)[:500]
# 逐单状态展示:未知结果仍须在 Notice 上保留失败原因(不强制改 upload_status,
# 因为迟到的成功回调仍可解除该未知态)。
if task is not None:
@@ -0,0 +1,49 @@
"""allow unknown upload attempt status
Revision ID: hv5w6x7y8z9a
Revises: hs1t2u3v4w5x
Create Date: 2026-08-27 13:30:00.000000
用途:修复货代上传尝试状态约束与模型不一致造成的落库失败。
依赖:shipping_notice_upload_attempts、ShippingUploadAttempt(models/shipping_fulfillment.py)。
逻辑:RPA 回调缺失/超时会把 Attempt 置为 unknown 并写 UPLOAD_RESULT_UNKNOWN,
但历史迁移只允许 running/succeeded/failed/timed_out,导致 complete_attempt 落库时
违反 ck_shipping_notice_upload_attempts_status(CheckViolation)。此迁移将状态枚举
补齐 'unknown',使数据库约束与模型一致;不清扫既有数据(unknown 行此前无法写入)。
"""
from alembic import op
revision = 'hv5w6x7y8z9a'
down_revision = 'hs1t2u3v4w5x'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""放宽状态检查约束,允许 unknown。"""
op.drop_constraint(
'ck_shipping_notice_upload_attempts_status',
'shipping_notice_upload_attempts',
type_='check',
)
op.create_check_constraint(
'ck_shipping_notice_upload_attempts_status',
'shipping_notice_upload_attempts',
"status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out', 'unknown')",
)
def downgrade() -> None:
"""回退为不含 unknown 的旧枚举,回退前须确认不存在 unknown 状态行。"""
op.drop_constraint(
'ck_shipping_notice_upload_attempts_status',
'shipping_notice_upload_attempts',
type_='check',
)
op.create_check_constraint(
'ck_shipping_notice_upload_attempts_status',
'shipping_notice_upload_attempts',
"status IN ('pending', 'running', 'succeeded', 'failed', 'timed_out')",
)
@@ -0,0 +1,47 @@
"""widen shipping task events source
Revision ID: hw6x7y8z9a0b
Revises: hv5w6x7y8z9a
Create Date: 2026-08-27 13:30:00.000000
用途:修复 ShippingTaskEvent.source 列过窄导致的事件审计落库截断失败。
依赖:shipping_task_events、ShippingTaskEvent(models/shipping.py)。
逻辑:source 记录触发来源码,由 trigger 直接赋值(如 freight_upload_rpa_callback_succeeded,
长度 37),历史 String(32) 在写入时会抛 StringDataRightTruncation。此迁移将列宽扩充到
String(64),与 request_id / event_type 的 64 宽度对齐;列可空语义保持不变。
"""
from alembic import op
import sqlalchemy as sa
revision = 'hw6x7y8z9a0b'
down_revision = 'hv5w6x7y8z9a'
branch_labels = None
depends_on = None
def upgrade() -> None:
"""扩充 source 列宽,容纳完整触发来源码。"""
op.drop_index('ix_shipping_task_events_source', table_name='shipping_task_events')
with op.batch_alter_table('shipping_task_events', schema=None) as batch_op:
batch_op.alter_column(
'source',
existing_type=sa.String(length=32),
type_=sa.String(length=64),
existing_nullable=True,
)
op.create_index('ix_shipping_task_events_source', 'shipping_task_events', ['source'])
def downgrade() -> None:
"""回退 source 列宽;回退前须确认不存在超过 32 字符的 source 值。"""
op.drop_index('ix_shipping_task_events_source', table_name='shipping_task_events')
with op.batch_alter_table('shipping_task_events', schema=None) as batch_op:
batch_op.alter_column(
'source',
existing_type=sa.String(length=64),
type_=sa.String(length=32),
existing_nullable=True,
)
op.create_index('ix_shipping_task_events_source', 'shipping_task_events', ['source'])
@@ -440,6 +440,69 @@ def test_freight_notice_groups_reads_frozen_snapshot_po_when_extraction_projecti
assert [item['business_no'] for item in result['items']] == ['WYC26082411', 'WYC26082412']
def test_freight_notice_groups_upload_mode_reads_attempt_not_stale_column(app):
"""通知完成面的上传方式必须取自 ShippingUploadAttempt,而非恒为 None 的 Notice.upload_mode。
回归点:denormalized Notice.upload_mode 从未被写入真实值;人工确认/RPA 的成功事实
只保存在 ShippingUploadAttempt.mode。聚合投影若直接读列会导致「通知完成」卡片拿不到
「人工確認 vs RPA 上传」的徽标来源。
"""
with app.app_context():
from app import db
from app.models import (
ShippingExportArtifact, ShippingExcelTemplate, ShippingInventoryParsingProfile,
ShippingNotice, ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
)
from app.services.shipping_notice import query_service
from app.services.shipping_notice.upload_attempt_service import record_manual_upload
notice = ShippingNotice(task_no='SN-GROUP-MODE-1', business_no='WYC26082501', source_type='manual', user_id=11)
template = ShippingExcelTemplate(
template_code='MODE', display_name='Mode', version=1, status='published', storage_bucket='test',
storage_key='test/template.xlsx', original_filename='template.xlsx', file_checksum='a' * 64,
definition_json={},
)
profile = ShippingInventoryParsingProfile(
profile_code='MODE', display_name='Mode', version=1, status='published', file_format='xlsx',
definition_json={},
)
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Order')
db.session.add_all([notice, template, profile, schema]); db.session.flush()
version = ShippingOrderSchemaVersion(schema_id=schema.id, version=1, status='published', definition_json={})
db.session.add(version); db.session.flush()
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted')
db.session.add(extraction); db.session.flush()
artifact = ShippingExportArtifact(
artifact_no='ART-MODE-1', task_id=notice.id, template_id=template.id, order_schema_version_id=version.id,
order_extraction_id=extraction.id, inventory_parsing_profile_id=profile.id, input_checksum='b' * 64,
file_path='/tmp/notice.xlsx', file_name='notice.xlsx', file_checksum='c' * 64, file_size=100, status='ready',
)
db.session.add(artifact); db.session.flush()
notice.export_file_name = 'notice.xlsx'
notice.export_file_path = '/tmp/notice.xlsx'
# 人为把陈旧列写成错误值,证明聚合不再消费它。
notice.upload_mode = 'rpa'
notice.upload_attempt = 99
db.session.commit()
# 一条人工确认成功 Attempt = 唯一可信的来源。
record_manual_upload(notice, artifact_id=artifact.id, operator_id=22)
db.session.commit()
original_header_reader = query_service.current_header_field_values_or_empty
query_service.current_header_field_values_or_empty = lambda _task: {'customer_po_number': 'PO-MODE'}
try:
result = list_freight_notice_groups_for_task(notice, user_id=11)
finally:
query_service.current_header_field_values_or_empty = original_header_reader
item = result['items'][0]
assert item['business_no'] == 'WYC26082501'
# 权威事实:人工确认成功 → manual;不读陈旧列('rpa')或恒 0/99 的 attempt 计数。
assert item['upload_mode'] == 'manual'
assert item['upload_attempt'] == 1
def test_list_my_todos_and_count_buckets(app):
"""list_my_todos 按 bucket 分类;count 徽标与 pending 一致。"""
with app.app_context():
@@ -848,3 +911,36 @@ def test_todo_category_lightweight_matches_orm_and_count(app):
assert counts["done"] == 1
assert counts["processing"] == 1
assert counts["total_pending_badge"] == 3
def test_serialize_task_detail_workbench_view_drops_editor_fields(app):
"""工作台 view=workbench 剔除复核编辑器重字段,保留 ui_state/产物/行摘要,全量视图不受影响。"""
with app.app_context():
from app import db
from app.services.shipping_notice.query_service import serialize_task_detail
task = ShippingNotice(
task_no="SN-WORKBENCH-VIEW", source_type="manual", user_id=11,
export_file_name="n.xlsx", export_file_path="/tmp/n.xlsx",
)
db.session.add(task)
db.session.commit()
full = serialize_task_detail(task, viewer_user_id=11, include_stage_context=True)
wb = serialize_task_detail(
task, viewer_user_id=11, include_stage_context=True, view="workbench",
)
# full 保留编辑器重字段;workbench 剔除它们,显著缩小响应体。
for key in (
"lines", "order_header", "order_header_fields", "order_line_fields",
"events", "field_conflicts",
):
assert key in full
assert key not in wb
# workbench 仍保留工作台所需字段(ui_state/stage_context、产物、行摘要)。
assert wb["ui_state"]["task_no"] == "SN-WORKBENCH-VIEW"
assert wb["ui_state"]["stage_context"] is not None
assert wb["artifact_summary"]["export_file_name"] == "n.xlsx"
assert "notice_line_summary" in wb
assert "export_artifacts" in wb
@@ -345,6 +345,31 @@ def test_task_ui_state_keeps_resolved_download_alongside_process_gate(app, monke
assert [item['code'] for item in state['actions']['secondary']] == ['download_excel']
def test_verified_upload_complete_state_has_no_follow_up_actions(app, monkeypatch) -> None:
"""通知完成是终态,即使旧 Gate 尚未清理也不得继续下发下一步。"""
with app.app_context():
task = ShippingNotice(task_no='SN-UI-UPLOAD-COMPLETE', source_type='manual')
monkeypatch.setattr(
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
lambda _task: True,
)
monkeypatch.setattr(
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
lambda _task: {
'current_gate': {'gate_code': 'manual_upload_handoff', 'evaluation_version': 3},
'current_blocking_gate': {'gate_code': 'manual_upload_handoff', 'evaluation_version': 3},
'primary_action': {'code': 'mark_manual_uploaded', 'label': '确认上传'},
'action_presentation': [],
},
)
state = build_task_ui_state(task)
# 关键断言:已核验上传成功优先于滞后的 Gate,完成态不能渲染任何下一步。
assert state['lifecycle_stage'] == 'upload_complete'
assert state['actions'] == {'primary': None, 'secondary': []}
def test_stp_facts_candidates_frozen_projected(app) -> None:
"""多候选冻结任务须投影 stp_facts.frozen_candidate_codes。"""
with app.app_context():
@@ -2188,6 +2188,48 @@ def test_eml_leaf_prefers_open_review_case_over_candidate_ready_unit(app, shippi
assert 'edit_draft' in leaf['available_actions']
def test_eml_leaf_treats_current_non_order_case_as_completed(app, shipping_user):
"""当前 Case 标记非订单后,EML 详情不得回退为旧 Unit 的处理中状态。"""
del shipping_user
with app.app_context():
from app.models import ShippingOrderCandidate
from app.services.shipping_notice.order_review_service import ensure_run_review_cases
from tests.test_shipping_order_extraction_runs import _seed_run_input
from tests.test_shipping_order_review_service import _materialized_run
user, agent, session, intake, document = _seed_run_input(suffix='EML-NON-ORDER-LEAF')
run = _materialized_run(user=user, agent=agent, session=session, intake=intake)
candidate = ShippingOrderCandidate(
candidate_no=f'OCAND-NON-ORDER-{uuid.uuid4().hex[:8]}', intake_id=intake.id,
primary_document_id=document.id, candidate_key='eml-non-order-leaf',
order_extraction_run_id=run.id, is_current_version=True,
)
db.session.add(candidate)
db.session.flush()
case = ensure_run_review_cases(run=run)[0]
case.status = 'non_order'
db.session.commit()
result = _aggregate_eml_order_task_work_items([{
'work_item_type': 'order_task', 'work_item_no': 'OT-EML-NON-ORDER',
'source_type': 'eml', 'intake_no': intake.intake_no, 'run_no': run.run_no,
'status': 'processing', 'stage': 'candidate_creating', 'user_status': 'running',
'user_stage': 'candidate_creating', 'user_group': 'processing',
'last_activity_at': '', 'available_actions': [], 'facts': {'upload_state': 'not_created'},
'source_summary': {'document_id': 0, 'filename': 'mail.eml'},
}])
aggregate = result[0]
leaf = aggregate['aggregate_children'][0]
assert leaf['case_no'] == case.case_no
assert leaf['user_status'] == 'completed'
assert leaf['user_stage'] == 'completed'
assert leaf['ui_state']['status'] == 'completed'
assert aggregate['user_status'] == 'completed'
assert aggregate['aggregate_summary']['completed'] == 1
assert aggregate['aggregate_summary']['processing'] == 0
def test_eml_aggregate_keeps_run_authorized_batch_reparse_action(app, shipping_user):
"""EML 父卡不能因叶子只有 Case 动作而遗漏按原 PDF 的批次重解析入口。"""
del shipping_user
@@ -7,8 +7,8 @@
from app.core.errors import ConflictError
def test_unknown_upload_blocks_new_idempotency_key_and_superseded_callback(app):
"""unknown 必须阻断全新重试键;Artifact superseded 后任何回调只返回冲突。"""
def test_unknown_upload_allows_fresh_retry_key_and_superseded_callback(app):
"""unknown 结果不阻断全新重试键(业务决定:允许继续尝试 RPA,避免卡死);Artifact superseded 后任何回调仍返回冲突。"""
from app import db
from app.models import ShippingExportArtifact
from app.services.shipping_notice.upload_attempt_service import (
@@ -21,12 +21,10 @@ def test_unknown_upload_blocks_new_idempotency_key_and_superseded_callback(app):
task, artifact, _reservation = _ready_artifact()
attempt = start_rpa_attempt(task, artifact_id=artifact.id)
mark_attempt_result_unknown(attempt)
try:
start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key='fresh-retry-key')
except ConflictError as exc:
assert exc.code == 'SHIPPING.UPLOAD_RETRY_FORBIDDEN_UNTIL_TERMINAL'
else:
raise AssertionError('unknown upload must block a fresh retry key')
# 业务决定:unknown(无法判断上传是否成功/失败)不再阻断重新下发 RPA,允许再次尝试。
retry = start_rpa_attempt(task, artifact_id=artifact.id, idempotency_key='fresh-retry-key')
assert retry.id != attempt.id
assert retry.status == 'running'
artifact.status = 'superseded'
db.session.flush()
@@ -53,6 +53,26 @@ def test_step1a_closes_all_gates_when_uploaded(app):
assert execution.status == 'completed'
def test_uploaded_fact_closes_gates_despite_stale_upload_pending_reason(app):
"""上传已成功时,历史 upload_rpa_pending 不得将正式 Gate 重新投影为阻断。"""
task = ShippingNotice(
task_no='SN-UPLOADED-STALE-PENDING',
upload_status='uploaded',
pending_human_reason='upload_rpa_pending',
match_status='fulfillable',
)
db.session.add(task)
db.session.flush()
execution = _mk_execution(task)
sync_fulfillment_gates_from_task(execution=execution, actor_type='user', actor_id=1)
db.session.commit()
db.session.refresh(execution)
assert execution.current_gate_code is None
assert execution.status == 'completed'
def test_missing_upload_status_keeps_gate_stuck(app):
"""upload_status != uploaded → STEP 1A 不触发,前置 Gate 保留(阶段投影可被回退)。"""
task = ShippingNotice(task_no='SN-UPLOAD-NOT-SET', upload_status='partial', match_status='fulfillable')
@@ -29,6 +29,7 @@
- `Case/Draft.field_conflicts`、Candidate Qualification 和 Process Gate 必须读取同一份当前开放冲突事实;UI 不得用过滤后的空列表覆盖资格层仍未解决的冲突。真实冲突缺少可裁决值时必须保留为 Review Finding,不能降级为“无冲突”。
- “保存订单并校验”是唯一确认入口。后端先保存 Draft,再在同一业务链路重新计算必填、证据、冲突、重复、客户确认和自动建单策略门禁;只有 `auto_create_enabled=true` 且全部自动建单门禁通过时,才返回 `can_auto_create=true` 并进入建单,否则返回稳定阻断原因及可执行的 Review 动作。
- Review Gate 或字段冲突发生变化时,即使生命周期 `stage/status` 不变,也必须递增 `progress_version` 并写入对应审计事件。Review 工作台、聊天投影和任务详情均按该版本刷新,禁止以前端旧 Projection 推导按钮。
- 上传成功(人工确认或 RPA 回调)必须统一清除历史上传阻断原因并收口正式 Execution 的履约 Gate;`upload_status=uploaded` 是终态成功事实,投影不得被遗留的 `upload_rpa_pending`、失败或未知原因重新降级。
- `resolve_field_conflicts` 仅在当前 Case 仍存在开放字段冲突时展示;Case 已无开放冲突时,旧 Projection 中残留的该动作必须被前端隐藏,同时以后端 `ui_state.actions` 为最终动作契约。
- Dify 的 Review 建议只能消费 HXOPS 下发的最小脱敏证据并返回候选建议,不能改变 Gate、Projection、Candidate 或 Task;建议不可用时人工复核和确定性主链仍可继续。
@@ -16,8 +16,63 @@ vi.mock('@/shared/api/client', () => ({
import {
getWorkspaceShippingOrderExtractionRun,
getWorkspaceShippingProcessing,
getWorkspaceShippingTask,
} from './shipping.api';
describe('getWorkspaceShippingTask', () => {
beforeEach(() => {
requestJson.mockReset();
});
it('coalesces concurrent reads of the same task detail into one HTTP request', async () => {
let resolveRequest!: (value: { task_no: string }) => void;
requestJson.mockImplementationOnce(() => new Promise((resolve) => {
resolveRequest = resolve;
}));
const first = getWorkspaceShippingTask('SN-DEDUPE-1');
const second = getWorkspaceShippingTask('SN-DEDUPE-1');
// 关键断言:重型任务详情在途时,同 task_no 的并行消费者(工作台 loadFormalTaskDetail
// 与对话侧 syncActiveShippingTaskDetail)必须复用一个网络请求,禁止重复拉取。
expect(requestJson).toHaveBeenCalledTimes(1);
resolveRequest({ task_no: 'SN-DEDUPE-1' });
await expect(Promise.all([first, second])).resolves.toEqual([
{ task_no: 'SN-DEDUPE-1' },
{ task_no: 'SN-DEDUPE-1' },
]);
});
it('does not cache a completed task detail across a later read', async () => {
requestJson.mockResolvedValueOnce({ task_no: 'SN-FRESH-1' });
requestJson.mockResolvedValueOnce({ task_no: 'SN-FRESH-1' });
// 单飞去重只合并「在途」请求;完成后不得返回过期快照,保证 Gate 动作后的新鲜重读。
await getWorkspaceShippingTask('SN-FRESH-1');
await getWorkspaceShippingTask('SN-FRESH-1');
expect(requestJson).toHaveBeenCalledTimes(2);
});
it('keys dedup by view so workbench and full projections do not merge', async () => {
requestJson.mockResolvedValue({ task_no: 'SN-VIEW-1' });
// 关键断言:workbench(裁剪)与 full 是两个不同响应体,缺省 view 与 view=workbench
// 共享同一个 task_no 时不能合并成一个请求,否则会把裁剪版响应交给 full 消费者。
const full = getWorkspaceShippingTask('SN-VIEW-1');
const wb = getWorkspaceShippingTask('SN-VIEW-1', { view: 'workbench' });
const wbAgain = getWorkspaceShippingTask('SN-VIEW-1', { view: 'workbench' });
// 两个视图各一次、workbench 同视图合并:共 2 次底层请求。
expect(requestJson).toHaveBeenCalledTimes(2);
expect(requestJson).toHaveBeenNthCalledWith(1, '/api/workspace/shipping-tasks/SN-VIEW-1');
expect(requestJson).toHaveBeenNthCalledWith(
2,
'/api/workspace/shipping-tasks/SN-VIEW-1?view=workbench',
);
await Promise.allSettled([full, wb, wbAgain]);
});
});
describe('getWorkspaceShippingOrderExtractionRun', () => {
beforeEach(() => {
requestJson.mockReset();
+39 -3
View File
@@ -118,9 +118,45 @@ export const listWorkspaceShippingTasks = (params?: {
/** 拉取用户可见 Agent 列表,供发货工作台跳转 Chat 时定位目标 Agent。 */
export const listShippingChatAgents = () => requestJson<ShippingChatAgentOption[]>('/api/agents');
/** 获取单个发货任务详情。 */
export const getWorkspaceShippingTask = (taskNo: string) =>
requestJson<ShippingTaskDetail>(`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}`);
/** 任务详情单飞去重:同一瞬间并发的同一 task_no 详情只发一次网络请求。
* [PERF] 订单生命周期工作台首屏会由 hasFormalOt / confirmedNoticeTaskNo 两个
* immediate watcher 同时触发 loadFormalTaskDetail,加上对话侧 syncActiveShippingTaskDetail,
* 会在同一时刻并发拉取同一任务详情;单飞将多次并发请求合并为一次,
* 显著削减 /shipping-tasks/:task_no 的重型重复请求。
* 只对「在途」请求去重、不缓存完成结果:保留 Gate 动作后的新鲜重读,
* 避免把写操作后的过期详情误当作最新状态。
* 去重键含 view:workbench(裁剪)与 full 是两个不同响应体,不能相互合并。 */
export type ShippingTaskDetailView = 'full' | 'workbench';
const shippingTaskDetailRequests = new Map<string, Promise<ShippingTaskDetail>>();
/** 获取单个发货任务详情。@param options.view 「workbench」返回订单生命周期工作台首屏裁剪版。 */
export const getWorkspaceShippingTask = (
taskNo: string,
options?: { view?: ShippingTaskDetailView },
) => {
const normalized = String(taskNo || '').trim();
if (!normalized) {
return Promise.reject(new BusinessError({
message: 'task_no is required',
code: 'SHIPPING.TASK_REQUIRED',
status: 400,
}));
}
const view = options?.view === 'workbench' ? 'workbench' : 'full';
const cacheKey = `${normalized}|${view}`;
const existing = shippingTaskDetailRequests.get(cacheKey);
if (existing) return existing;
const url = view === 'workbench'
? `/api/workspace/shipping-tasks/${encodeURIComponent(normalized)}?view=workbench`
: `/api/workspace/shipping-tasks/${encodeURIComponent(normalized)}`;
const request = requestJson<ShippingTaskDetail>(url).finally(() => {
if (shippingTaskDetailRequests.get(cacheKey) === request) {
shippingTaskDetailRequests.delete(cacheKey);
}
});
shippingTaskDetailRequests.set(cacheKey, request);
return request;
};
/** 读取当前 PO 下按 business_no 聚合的货代上传 Notice。 */
export const getWorkspaceShippingFreightNoticeGroups = (taskNo: string) =>
@@ -111,6 +111,29 @@ describe('ReviewLifecycleStageNavigation', () => {
expect(stage.find('[data-testid="review-lifecycle-stage-spinner"]').exists()).toBe(true);
});
it('renders the current upload-complete stage as completed instead of running', () => {
const wrapper = mount(ReviewLifecycleStageNavigation, {
props: {
stages: [
{ code: 'intake_parse', label: '接收解析', state: 'completed' },
{ code: 'order_review', label: '订单复核', state: 'completed' },
{ code: 'fulfillment_prep', label: '通知准备', state: 'completed' },
{ code: 'freight_upload', label: '货代上传', state: 'completed' },
{ code: 'upload_complete', label: '通知完成', state: 'current' },
],
activeCode: 'upload_complete',
// 迟到的运行态不能覆盖后端已裁决的通知完成终态。
processingCode: 'upload_complete',
},
global: { plugins: [i18n] },
});
const stage = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]');
expect(stage.find('.text-emerald-600').exists()).toBe(true);
expect(stage.find('.bg-brand-600').exists()).toBe(false);
expect(stage.find('[data-testid="review-lifecycle-stage-spinner"]').exists()).toBe(false);
});
it('disables a future stage and does not emit a selection', async () => {
const wrapper = mountNavigation();
const future = wrapper.get('[data-testid="review-lifecycle-stage-upload_complete"]');
@@ -42,8 +42,16 @@ function canRetryParse(stage: ReviewLifecycleStageItem): boolean {
&& (props.availableActions || []).includes('retry_parse');
}
/** 通知完成是当前生命周期终态,不是仍在执行的当前工作阶段。 */
function isCompletedStage(stage: ReviewLifecycleStageItem): boolean {
return stage.state === 'completed' || (
stage.code === 'upload_complete' && stage.state === 'current'
);
}
/**
* 阶段导航只允许进入当前或已完成阶段;blocked 仅说明前置条件,不替代后端 Gate 判定。
* 阶段导航只允许进入后端下发为 current / available / completed 的阶段;
* blocked 仅说明前置条件,不替代后端 Gate 判定。
*/
function selectStage(stage: ReviewLifecycleStageItem) {
if (stage.state === 'blocked') return;
@@ -73,12 +81,12 @@ function selectStage(stage: ReviewLifecycleStageItem) {
>
<span class="flex items-center gap-2 text-sm font-semibold">
<RefreshCw
v-if="stage.code === props.processingCode"
v-if="stage.code === props.processingCode && !isCompletedStage(stage)"
class="h-4 w-4 shrink-0 animate-spin text-brand-600"
data-testid="review-lifecycle-stage-spinner"
aria-hidden="true"
/>
<Check v-if="stage.state === 'completed'" class="h-4 w-4 shrink-0 text-emerald-600" />
<Check v-if="isCompletedStage(stage)" class="h-4 w-4 shrink-0 text-emerald-600" />
<LockKeyhole v-else-if="stage.state === 'blocked'" class="h-4 w-4 shrink-0 text-muted" />
<span v-else class="h-2 w-2 shrink-0 rounded-full bg-brand-600" aria-hidden="true" />
<button
@@ -96,13 +104,13 @@ function selectStage(stage: ReviewLifecycleStageItem) {
:disabled="stage.state === 'blocked'"
@click="selectStage(stage)"
>
{{ stage.state === 'current'
{{ isCompletedStage(stage)
? $t('chat.shippingOrderReview.lifecycle.completed')
: stage.state === 'current'
? (stage.code === props.processingCode
? $t('chat.shippingOrderReview.lifecycle.processing')
: $t('chat.shippingOrderReview.lifecycle.current'))
: stage.state === 'completed'
? $t('chat.shippingOrderReview.lifecycle.completed')
: (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }}
: (stage.reason || $t('chat.shippingOrderReview.lifecycle.blocked')) }}
</button>
<button
v-if="canRetryParse(stage)"
@@ -353,6 +353,36 @@ describe('ShippingOrderExtractionCard', () => {
expect(wrapper.text()).not.toContain('stale.pdf');
});
it('renders a completed non-order attachment without a spinner', async () => {
const child = {
workItemNo: 'DOCUMENT:NON-ORDER', sourceSummary: { filename: 'not-an-order.pdf', documentId: 1 },
status: 'completed', stage: 'completed', userStatus: 'completed', userStage: 'completed',
facts: { uploadState: 'not_created' }, uiState: { status: 'completed', stage: 'completed' },
} as any;
const task = {
user_task_no: 'INTAKE:SNI-NON-ORDER', title: 'mail.eml', file_count: 1,
userGroup: 'completed', group: 'completed', aggregateChildren: [child],
aggregateSummary: { intakeNo: 'SNI-NON-ORDER', total: 1, completed: 1, processing: 0, needsAction: 0, failed: 0, stages: ['completed'], reasonCodes: [] },
} as any;
const wrapper = mount(ShippingOrderExtractionCard, {
props: { state: buildState({ status: 'completed' }) },
global: { plugins: [i18n], provide: { [SHIPPING_WORKFLOW_KEY as symbol]: {
processing: ref({
ui_state: { status: 'completed' },
summary: { total_files: 1, completed_files: 1, waiting_human_files: 0, failed_files: 0 },
status_groups: { failed: [], waiting_human: [], processing: [], completed: [task], cancelled: [], archived: [] },
}),
processingWorkItems: ref([]),
} } },
});
await wrapper.get('[data-testid="shipping-order-extraction-status-groups"] section button').trigger('click');
await wrapper.get('[data-testid="shipping-order-extraction-eml-completed-INTAKE:SNI-NON-ORDER"] button').trigger('click');
expect(wrapper.findAll('.animate-spin')).toHaveLength(0);
expect(wrapper.get('[data-testid="shipping-order-extraction-child-status-DOCUMENT:NON-ORDER"]').text()).not.toContain('处理中');
});
it('uses the authoritative attachment total when a historical message only carries the EML task count', () => {
const task = {
user_task_no: 'INTAKE:SNI-MAILS', title: 'mail-batch.eml', file_count: 30,
@@ -126,6 +126,7 @@ function taskFileCount(task: { aggregateChildren?: ShippingProcessingProjection[
function childStatusLabel(child: ShippingProcessingProjection) {
const status = displayProjectionStatus(child);
if (status === 'completed' && child.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
if (status === 'completed') return t('chat.shippingProcessing.groupRecordCompleted');
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
@@ -149,7 +150,7 @@ function isWaitingProjection(item: ShippingProcessingProjection): boolean {
return displayProjectionStatus(item) === 'waiting_human';
}
function isCompletedProjection(item: ShippingProcessingProjection): boolean {
return displayProjectionStatus(item) === 'completed' && item.facts?.uploadState === 'succeeded';
return displayProjectionStatus(item) === 'completed';
}
function taskReason(task: { uiState?: { blocking_reason: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null }; blockingReason?: import('../../types/shipping.api.types').ShippingProcessingBlockingReason | null }) {
return task.uiState ? task.uiState.blocking_reason : task.blockingReason;
@@ -223,6 +224,7 @@ function aggregateStageLabel(item: ShippingProcessingProjection): string {
function aggregateChildStatusLabel(item: ShippingProcessingProjection): string {
const status = displayProjectionStatus(item);
if (status === 'completed' && item.facts?.uploadState === 'succeeded') return t('chat.shippingProcessing.aggregate.completed', { count: 1 });
if (status === 'completed') return t('chat.shippingProcessing.groupRecordCompleted');
if (status === 'failed' || status === 'retryable') return t('chat.shippingProcessing.aggregate.failed', { count: 1 });
if (status === 'waiting_human') return t('chat.shippingProcessing.aggregate.needsAction', { count: 1 });
return t('chat.shippingProcessing.aggregate.processing', { count: 1 });
@@ -654,7 +656,7 @@ async function onPrimaryChatAction() {
<div class="flex items-center justify-between gap-3">
<div class="flex items-center gap-2 text-lg font-semibold">
<LoaderCircle v-if="hasConversationStatusGroups ? conversationProcessing?.ui_state?.status === 'running' : emlAggregate ? emlAggregate.userStatus === 'running' : state.status === 'queued' || state.status === 'processing'" class="h-5 w-5 animate-spin text-blue-600" />
<CheckCircle2 v-else-if="hasConversationStatusGroups ? conversationProcessing?.ui_state?.status === 'completed' : emlAggregate ? emlAggregate.userStatus === 'completed' && emlAggregate.facts?.uploadState === 'succeeded' : state.status === 'completed'" class="h-5 w-5 text-emerald-500" />
<CheckCircle2 v-else-if="hasConversationStatusGroups ? conversationProcessing?.ui_state?.status === 'completed' : emlAggregate ? emlAggregate.userStatus === 'completed' : state.status === 'completed'" class="h-5 w-5 text-emerald-500" />
<TriangleAlert v-else class="h-5 w-5 text-amber-500" />
<span>{{ t('chat.shippingProcessing.multiPdfTaskTitle') }}</span>
</div>
@@ -522,7 +522,8 @@ export function useShippingOrderReview(options: { onWorkflowRefresh?: () => void
showWorkflowProgress.value = true;
workflowProgressPolling.value = true;
// RPA 超时、可重试失败和人工复核都可能被后续回调推进,页面留存期间持续读取 Projection。
const UNIFIED_TERMINAL = new Set(['completed', 'cancelled']);
// needs_human(等待人工)视为线性终态:结果不会自行变化,继续轮询浪费资源。
const UNIFIED_TERMINAL = new Set(['completed', 'cancelled', 'needs_human']);
let lastUnifiedStatus = '';
let lastLifecycleFingerprint = '';
const RUN_TERMINAL = new Set(['completed', 'partially_completed', 'failed', 'cancelled']);
@@ -153,6 +153,26 @@ describe('useShippingNoticeWorkflow helpers', () => {
history: [],
})).toBe(true);
});
it('keeps polling after an RPA upload succeeds while a later task step is processing', () => {
expect(shouldContinueProcessingPolling({
summary: { total_tasks: 1, processing: 1, needs_action: 0, history: 0 },
processing: [{
user_task_no: 'OT-RPA-SUCCEEDED',
group: 'processing',
can_append: false,
status_label: 'processing',
ui_state: {
status: 'running',
stage: 'post_upload_processing',
lifecycle_stage: 'freight_upload',
},
facts: { upload_state: 'succeeded' },
}],
needs_action: [],
history: [],
})).toBe(true);
});
});
describe('useShippingNoticeWorkflow', () => {
@@ -663,6 +663,8 @@ async function mountView(query: Record<string, string> = {}) {
uploadComplete: {
title: '通知完成',
subtitle: '上传成功证据已核验。',
uploadModeManual: '人工确认',
uploadModeRpa: 'RPA 上传',
},
upload: {
receipt: '货代回执:{value}',
@@ -2830,7 +2832,7 @@ describe('ShippingOrderReviewView layout phase 1', () => {
vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockResolvedValue({
po_number: 'PO-100',
items: [
{ business_no: 'WYC26082401', po_number: 'PO-100', upload_status: 'uploaded', export_file_name: 'WYC26082401.xlsx', lines: [
{ business_no: 'WYC26082401', po_number: 'PO-100', upload_status: 'uploaded', upload_mode: 'manual', export_file_name: 'WYC26082401.xlsx', lines: [
{ line_no: '00010', part_number: 'PART-A', reservation_id: 'RSV-A', qty: '2' },
] },
{ business_no: 'WYC26082402', po_number: 'PO-100', upload_status: 'pending', export_file_name: 'WYC26082402.xlsx', lines: [] },
@@ -2847,8 +2849,44 @@ describe('ShippingOrderReviewView layout phase 1', () => {
// 人工确认不再展示或依赖货代回执号,即使历史投影仍带有 freight_ref_no。
expect(evidence.text()).not.toContain('LEGACY-REF-MUST-NOT-BE-SHOWN');
expect(evidence.text()).not.toContain('LATEST-FAILED');
// 上传来源徽标:成功事实取自 ShippingUploadAttempt 的 mode=manual。
expect(wrapper.find('[data-testid="review-upload-complete-mode"]').text()).toContain(
'人工确认',
);
expect(wrapper.find('[data-testid="review-current-task-primary-action"]').exists()).toBe(false);
expect(wrapper.find('[data-testid="review-current-processing-retry"]').exists()).toBe(false);
expect(wrapper.get('[data-testid="review-current-processing-card"]').text()).toContain('已完成');
expect(wrapper.get('[data-testid="review-current-processing-card"]').text()).not.toContain('状态待确认');
expect(wrapper.find('[data-testid="review-current-task-next-step-section"]').exists()).toBe(false);
});
it('allows inspecting a completed order-review stage without allowing edits', async () => {
activeCase.value = {
...activeCase.value,
status: 'confirmed', confirmed_task_no: 'SN-COMPLETED-REVIEW', confirmed_task_id: 23, has_formal_ot: true,
};
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-COMPLETED-REVIEW', status: 'completed', upload_status: 'uploaded', lines: [], events: [],
ui_state: {
lifecycle_stage: 'upload_complete',
lifecycle_entries: [
{ code: 'intake_parse', state: 'available' },
{ code: 'order_review', state: 'available' },
{ code: 'fulfillment_prep', state: 'available' },
{ code: 'freight_upload', state: 'available' },
{ code: 'upload_complete', state: 'current' },
],
actions: { primary: null, secondary: [] }, summary: {}, steps: [],
},
} as any);
const wrapper = await mountView({ lifecycle_stage: 'order_review' });
await flushPromises();
expect(wrapper.find('[data-testid="review-editor-body"]').exists()).toBe(true);
expect(wrapper.get('[data-testid="shipping-order-review-view"]').attributes('data-readonly')).toBe('true');
expect(wrapper.find('[data-testid="review-header-field-input"]').attributes('disabled')).toBeDefined();
});
it('aggregates freight upload by business_no and keeps one Excel action per notice', async () => {
@@ -2907,22 +2945,46 @@ describe('ShippingOrderReviewView layout phase 1', () => {
await flushPromises();
await wrapper.get('[aria-label="WYC26082411"]').setValue(true);
await wrapper.get('[aria-label="WYC26082412"]').setValue(true);
const buttons = wrapper.get('[data-testid="review-freight-upload-batch-toolbar"]').findAll('button');
await buttons[0].trigger('click');
await wrapper.get('[data-testid="review-freight-upload-batch-toolbar"]').find('button').trigger('click');
await flushPromises();
expect(downloadFreightArchiveMock).toHaveBeenCalledWith(['WYC26082411', 'WYC26082412']);
await wrapper.get('[aria-label="WYC26082411"]').setValue(true);
await wrapper.get('[aria-label="WYC26082412"]').setValue(true);
await buttons[1].trigger('click');
await wrapper.get('[data-testid="review-freight-upload-batch-rpa"]').trigger('click');
await flushPromises();
expect(batchRpaFreightMock).toHaveBeenCalledWith(['WYC26082411', 'WYC26082412']);
await wrapper.get('[aria-label="WYC26082411"]').setValue(true);
await wrapper.get('[aria-label="WYC26082412"]').setValue(true);
await buttons[2].trigger('click');
await wrapper.get('[data-testid="review-freight-upload-batch-confirm"]').trigger('click');
await flushPromises();
expect(batchConfirmFreightMock).toHaveBeenCalledWith(['WYC26082411', 'WYC26082412']);
});
it('disables upload batch actions and hides more actions when an uploaded notice is selected', async () => {
activeCase.value = { ...activeCase.value, status: 'confirmed', confirmed_task_no: 'SN-PO-UPLOADED', confirmed_task_id: 24, has_formal_ot: true };
const taskApi = await import('@/features/chat/api/shipping.api');
vi.mocked(taskApi.getWorkspaceShippingTask).mockResolvedValue({
task_no: 'SN-PO-UPLOADED', status: 'processing', lines: [], events: [],
ui_state: { lifecycle_stage: 'freight_upload', lifecycle_entries: [], actions: { primary: null, secondary: [] }, stage_context: { upload: {} } },
} as any);
vi.mocked(taskApi.getWorkspaceShippingFreightNoticeGroups).mockResolvedValue({
po_number: 'PO-UPLOADED', items: [
{ business_no: 'WYC-UPLOADED', po_number: 'PO-UPLOADED', upload_status: 'uploaded', lines: [] },
{ business_no: 'WYC-PENDING', po_number: 'PO-UPLOADED', upload_status: 'pending', lines: [] },
],
} as any);
const wrapper = await mountView({ lifecycle_stage: 'freight_upload' });
await flushPromises();
await wrapper.get('[aria-label="WYC-UPLOADED"]').setValue(true);
await wrapper.get('[aria-label="WYC-PENDING"]').setValue(true);
// 已上传项混入选择集时,批量写入不允许部分静默提交,必须让用户显式取消选择。
expect(wrapper.get('[data-testid="review-freight-upload-batch-rpa"]').attributes('disabled')).toBeDefined();
expect(wrapper.get('[data-testid="review-freight-upload-batch-confirm"]').attributes('disabled')).toBeDefined();
expect(wrapper.findAll('[data-testid="review-freight-upload-more"]')).toHaveLength(0);
});
it('does not place internal inventory hint fields in the primary line table', async () => {
const wrapper = await mountView();
const inputs = wrapper.findAll('[data-testid="review-line-field-input"]');
@@ -198,6 +198,11 @@ const msg = useMessage();
* 无论哪一路都带 label_key,禁止把 code 当用户文案。
*/
const currentProcessingStageDisplay = computed(() => {
// 正式任务已明确通知完成时,该终态优先于可能迟到的 Processing 投影,
// 右侧不能再退化为“处理中 / 待机”。此处直接读取详情,避免引用后方生命周期 computed。
if (formalTaskDetail.value?.ui_state?.lifecycle_stage === 'upload_complete') {
return { code: 'completed', labelKey: 'completed', inconsistent: false };
}
const projection = shippingProcessingProjection.value;
if (projection?.stage) {
return {
@@ -309,7 +314,10 @@ const lifecycleActiveStageCode = computed<ReviewLifecycleStageCode | null>(() =>
if (requested === 'intake_parse' && lifecycleUiState.value.intakeParseAuthorized === true) {
return 'intake_parse';
}
return lifecycleEntryIsEnterable(entry) ? requested : lifecycleCurrentStageCode.value;
const current = lifecycleCurrentStageCode.value;
// 用户可回看后端已授权的 available 前置阶段;自动推进由下方 watcher 在
// 「路由仍停留原 current 阶段且用户未固定查看」时处理,不能在这里抢占用户选择。
return lifecycleEntryIsEnterable(entry) ? requested : current;
});
/** 当前后端投影明确在自动推进时,五阶段导航只为该阶段展示 Spinner,不改变授权。 */
const lifecycleProcessingStageCode = computed<ReviewLifecycleStageCode | null>(() => {
@@ -376,6 +384,17 @@ const isLifecycleIntakeParse = computed(() => (
const isLifecycleFulfillmentPrep = computed(() => lifecycleActiveStageCode.value === 'fulfillment_prep');
const isLifecycleFreightUpload = computed(() => lifecycleActiveStageCode.value === 'freight_upload');
const isLifecycleUploadComplete = computed(() => lifecycleActiveStageCode.value === 'upload_complete');
/** 正式任务已通知完成时,即使用户回看前置阶段也只能查看,不能再修改已产出通知。 */
const isCompletedFormalTask = computed(() => lifecycleCurrentStageCode.value === 'upload_complete');
const isReviewContentReadOnly = computed(() => isReadOnly.value || isCompletedFormalTask.value);
/**
* 统一字段写权限,确保通知完成后的前置阶段回看不会绕过只读边界。
* @param fieldId - 后端 Schema 下发的字段标识。
* @returns 当前字段是否允许编辑。
*/
function canEditReviewField(fieldId: string): boolean {
return !isReviewContentReadOnly.value && isFieldEditable(fieldId);
}
/** 当前阶段重试只取 Case 的服务端授权,不从输入框附件卡或本地状态推断。 */
const intakeParseRetryAvailable = computed(() => (
isLifecycleIntakeParse.value
@@ -451,7 +470,7 @@ async function syncPendingReleaseAutoAdvance(): Promise<boolean> {
async function selectLifecycleStage(code: ReviewLifecycleStageCode, options: { replace?: boolean } = {}) {
const target = lifecycleStageItems.value.find((item) => item.code === code);
if (!target || target.state === 'blocked') return;
// 用户主动回看已完成阶段时,异步投影抵达不得将其强制带回当前阶段。
// 用户主动回看后端 available 或已完成阶段时,异步投影抵达不得将其强制带回当前阶段。
// 自动推进均使用 replace,不会写入该意图。
if (!options.replace) {
const caseNo = String(activeCase.value?.case_no || '').trim() || null;
@@ -675,6 +694,7 @@ const currentTaskPrimaryAction = computed(() => {
return null;
});
const currentTaskUserStatus = computed(() => {
if (formalTaskDetail.value?.ui_state?.lifecycle_stage === 'upload_complete') return 'completed';
// 已确认 OT 且权威投影在途时,先消费后端 automation 运行态(queued/running → running,
// failed/manual_fallback → failed),状态行即显真实值,不应退回「正在获取最新状态」骨架;
// authority 仍以右侧投影为准,投影到达后覆盖。
@@ -686,11 +706,13 @@ const currentTaskUserStatus = computed(() => {
return null;
});
const currentTaskBlockingReason = computed(() => {
if (formalTaskDetail.value?.ui_state?.lifecycle_stage === 'upload_complete') return null;
if (formalTaskProjectionPending.value) return null;
return currentTaskUiState.value?.blocking_reason ?? null;
});
/** 当前 Gate 状态必须与右栏动作同源,均来自统一处理 Projection。 */
const currentTaskGateStatus = computed(() => {
if (formalTaskDetail.value?.ui_state?.lifecycle_stage === 'upload_complete') return null;
if (formalTaskProjectionPending.value) return null;
const projection = shippingProcessingProjection.value;
if (projection?.currentGate?.status) return projection.currentGate.status;
@@ -728,13 +750,13 @@ const currentTaskRecoveryActions = computed(() => {
* @returns 当前工作面允许交给 ReviewCurrentProcessingCard 展示的动作。
*/
const visibleCurrentTaskPrimaryAction = computed(() => (
isLifecycleUploadComplete.value ? null : currentTaskPrimaryAction.value
isCompletedFormalTask.value ? null : currentTaskPrimaryAction.value
));
const visibleCurrentTaskRecoveryActions = computed(() => (
isLifecycleUploadComplete.value ? [] : currentTaskRecoveryActions.value
isCompletedFormalTask.value ? [] : currentTaskRecoveryActions.value
));
const visibleCurrentTaskRetryable = computed(() => (
isLifecycleUploadComplete.value ? false : currentTaskRetryable.value
isCompletedFormalTask.value ? false : currentTaskRetryable.value
));
/** 管理员诊断:后端 technical_progress / automation.technical 仅 admin 投影。 */
@@ -1156,6 +1178,8 @@ const onExceptionNavKeydown = (event: KeyboardEvent) => {
onMounted(() => {
document.addEventListener('keydown', onExceptionNavKeydown, true);
// [PERF] 深链进入时尽早并行发起任务详情,与 load() 重叠,削减首屏串行加载。
prefetchDeepLinkedTaskDetail();
});
onBeforeUnmount(() => {
@@ -1899,9 +1923,9 @@ const canEnterInventory = computed(() => {
});
const availableActions = computed(() => activeCase.value?.available_actions || []);
/** 订单处理工作台写权限(只读查看 / Case 切换中为 false)。 */
/** 订单处理工作台写权限(历史查看、通知完成回看或 Case 切换中均为 false)。 */
const workbenchActionsExecutable = computed(() => (
!isReadOnly.value
!isReviewContentReadOnly.value
&& !runLoading.value
&& !caseSwitchLoading.value
&& !progressRetrying.value
@@ -2246,6 +2270,19 @@ const formalTaskDetailLoadFailed = ref(false);
*/
let formalTaskDetailGeneration = 0;
const manualUploadRegistrationOpen = ref(false);
/** 深链预取:批次进度中心已带 task_no 时,挂载即并行发起任务详情读取,与 load() 重叠。
* [PERF] 订单生命周期工作台首屏的关键路径是 load() 完成后才轮到 loadFormalTaskDetail
* (getWorkspaceShippingTask)。提前发起让这两个重型请求并行,消除串行叠加;
* 结果仅在被 loadFormalTaskDetail 认领且任务号一致时使用,避免双源身份。 */
const deepLinkTaskPrefetch = ref<{ taskNo: string; promise: Promise<ShippingTaskDetail | null> } | null>(null);
function prefetchDeepLinkedTaskDetail() {
const taskNo = String(route.query.task_no || route.query.task_id || '').trim();
if (!taskNo) return;
const promise = getWorkspaceShippingTask(taskNo, { view: 'workbench' })
.then((detail) => detail)
.catch(() => null);
deepLinkTaskPrefetch.value = { taskNo, promise };
}
/**
* 通知准备优先消费正式任务 ui_state;详情摘要暂时为空时,仅回退到当前 Case 的
@@ -2462,10 +2499,28 @@ async function loadFormalTaskDetail() {
if (formalTaskDetail.value?.task_no !== taskNo) {
formalTaskDetail.value = null;
}
// [PERF] 复用深链预取的任务详情:首次进入时它与 load() 并行发起,避免任务详情在
// load() 完成之后再串行重拉;仅当预取与当前确认任务号一致时使用,用完即清空,
// 后续 Gate 动作后的写后刷新仍走正常网络读取,保证新鲜度。
const prefetch = deepLinkTaskPrefetch.value;
if (prefetch && prefetch.taskNo === taskNo) {
deepLinkTaskPrefetch.value = null;
const prefetched = await prefetch.promise;
if (
prefetched
&& String(prefetched.task_no || '').trim() === taskNo
&& generation === formalTaskDetailGeneration
) {
formalTaskDetail.value = prefetched;
formalTaskDetailLoadFailed.value = false;
formalTaskDetailLoading.value = false;
return;
}
}
formalTaskDetailLoadFailed.value = false;
formalTaskDetailLoading.value = true;
try {
const detail = await getWorkspaceShippingTask(taskNo);
const detail = await getWorkspaceShippingTask(taskNo, { view: 'workbench' });
if (generation !== formalTaskDetailGeneration) return;
// 同代也必须核对任务身份;服务端异常返回或旧请求均不能成为当前生命周期事实。
if (String(detail?.task_no || '').trim() !== taskNo) {
@@ -2511,12 +2566,83 @@ async function loadFreightNoticeGroups(taskNo: string) {
}
}
// [STEP] 货代上传面板独立、轻量轮询(解耦):仅货代上传工作面激活时每 5s 重拉,达到终态即停。
// 各数据源独立轮询,避免把两个网络请求串进同一个 tick(串行 await 会拖慢单个轮询)。
const FREIGHT_GROUPS_POLL_MS = 5000;
const freightGroupsPollTimer = ref<ReturnType<typeof window.setInterval> | null>(null);
function stopFreightGroupsPolling() {
if (freightGroupsPollTimer.value != null) {
window.clearInterval(freightGroupsPollTimer.value);
freightGroupsPollTimer.value = null;
}
}
function startFreightGroupsPolling() {
stopFreightGroupsPolling();
if (!isLifecycleFreightUpload.value) return;
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (!taskNo) return;
const tick = () => {
if (freightNoticeGroupsLoading.value) return;
const no = String(confirmedNoticeTaskNo.value || '').trim();
if (no) void loadFreightNoticeGroups(no);
};
tick();
freightGroupsPollTimer.value = window.setInterval(tick, FREIGHT_GROUPS_POLL_MS);
}
// 货代上传工作面激活/切出时启停独立轮询。
watch(isLifecycleFreightUpload, (active) => {
if (active) startFreightGroupsPolling();
else stopFreightGroupsPolling();
});
// 货代分组达到终态后只停止分组轮询。RPA 回调成功/失败不代表整个任务结束,
// 后续 Gate 仍可能自动推进,任务级工作流轮询必须继续由统一投影裁决。
watch(freightNoticeGroups, (groups) => {
if (!isLifecycleFreightUpload.value || !groups.length) return;
const terminal = groups.every((group) => {
const st = String(group.upload_status || '').trim().toLowerCase();
const reason = group.upload_error_message || group.upload_error_code || null;
if (['uploaded', 'succeeded', 'success'].includes(st)) return true;
if (st === 'failed') return true;
return Boolean(reason);
});
if (terminal) {
stopFreightGroupsPolling();
}
});
onBeforeUnmount(() => stopFreightGroupsPolling());
function toggleFreightNoticeSelection(businessNo: string, checked: boolean) {
selectedFreightBusinessNos.value = checked
? Array.from(new Set([...selectedFreightBusinessNos.value, businessNo]))
: selectedFreightBusinessNos.value.filter((item) => item !== businessNo);
}
/**
* 判断通知单是否已有后端确认的上传成功事实。
* 核心逻辑:仅消费当前分组的 upload_status;已上传通知不得再次发起 RPA 或人工确认。
* @param group - 后端下发的发货通知单聚合行。
* @returns 是否已上传成功。
*/
function isFreightNoticeUploaded(group: ShippingFreightNoticeGroup): boolean {
return ['uploaded', 'succeeded', 'success'].includes(
String(group.upload_status || '').trim().toLowerCase(),
);
}
/** 已选通知单中任一已上传时,批量写入动作必须 fail-closed,避免重复提交成功通知。 */
const selectedFreightNoticesContainUploaded = computed(() => {
const selected = new Set(selectedFreightBusinessNos.value);
return freightNoticeGroups.value.some((group) => (
selected.has(group.business_no) && isFreightNoticeUploaded(group)
));
});
async function downloadFreightNotice(businessNo: string) {
try {
await downloadWorkspaceShippingNoticeExcelFile(businessNo);
@@ -2527,6 +2653,7 @@ async function downloadFreightNotice(businessNo: string) {
async function runFreightBatchAction(action: 'download' | 'confirm' | 'rpa') {
if (!selectedFreightBusinessNos.value.length || freightBatchBusy.value) return;
if (action !== 'download' && selectedFreightNoticesContainUploaded.value) return;
freightBatchBusy.value = action;
try {
if (action === 'download') {
@@ -2540,6 +2667,9 @@ async function runFreightBatchAction(action: 'download' | 'confirm' | 'rpa') {
if (action === 'confirm' || action === 'rpa') {
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (taskNo) await loadFreightNoticeGroups(taskNo);
// 启动 5 秒轮询:RPA 上传结果/失败原因异步回传后自动刷新,无需手动刷新页面。
startWorkflowProgressPolling();
startFreightGroupsPolling();
}
await Promise.all([loadFormalTaskDetail(), refreshShippingProcessing()]);
} catch (error) {
@@ -2561,6 +2691,7 @@ async function runFreightNoticeAction(
action: 'confirm' | 'rpa' | 'regenerate',
) {
if (freightBatchBusy.value) return;
if (action !== 'regenerate' && isFreightNoticeUploaded(group)) return;
freightBatchBusy.value = action;
try {
if (action === 'confirm') {
@@ -2575,6 +2706,9 @@ async function runFreightNoticeAction(
// 确认/RPA 后重拉同 PO 通知聚合,使通知完成面能立即呈现最新 uploaded 状态。
const taskNo = String(confirmedNoticeTaskNo.value || '').trim();
if (taskNo) await loadFreightNoticeGroups(taskNo);
// 启动 5 秒轮询:RPA 上传结果/失败原因异步回传后自动刷新,无需手动刷新页面。
startWorkflowProgressPolling();
startFreightGroupsPolling();
await Promise.all([loadFormalTaskDetail(), refreshShippingProcessing()]);
} catch (error) {
msg.warning(error instanceof Error ? error.message : t('chat.shippingOrderReview.workbench.resultNotReady'));
@@ -2592,6 +2726,19 @@ function canRegenerateFreightNotice(group: ShippingFreightNoticeGroup): boolean
));
}
/**
* 判断单条通知单是否存在可展开的更多操作。
* 核心逻辑:已上传通知一律不展示更多按钮;其他状态仅在后端授权了至少一个动作时展示,避免空白菜单。
* @param group - 当前发货通知单聚合行。
* @returns 是否显示更多操作入口。
*/
function hasFreightNoticeMoreActions(group: ShippingFreightNoticeGroup): boolean {
if (isFreightNoticeUploaded(group)) return false;
return canRunFreightNoticeAction(group, 'retry_freight_upload_rpa')
|| canRunFreightNoticeAction(group, 'mark_manual_uploaded')
|| canRegenerateFreightNotice(group);
}
/** 仅展示 Notice 聚合接口下发的已授权动作;最终写入仍由对应 API 二次校验。 */
function canRunFreightNoticeAction(group: ShippingFreightNoticeGroup, actionCode: string): boolean {
return (group.available_actions || []).includes(actionCode);
@@ -2837,6 +2984,19 @@ function freightUploadStatusDisplay(group: ShippingFreightNoticeGroup): {
};
}
/**
* 通知完成面:解析上传成功证据的来源方式(人工确认 / RPA),用于徽标展示。
* 核心逻辑:upload_mode 为后端从 ShippingUploadAttempt 权威事实解析的 rpa|manual;
* 仅该两值可映射,未知/空一律返回 null,避免把历史遗留或未知模式伪装成人话。
* @param mode - 后端解析出的上传方式(rpa / manual / 空)。
*/
function freightUploadModeLabel(mode: string | null | undefined): string | null {
const value = String(mode || '').trim().toLowerCase();
if (value === 'rpa') return t('chat.shippingOrderReview.lifecycle.uploadComplete.uploadModeRpa');
if (value === 'manual') return t('chat.shippingOrderReview.lifecycle.uploadComplete.uploadModeManual');
return null;
}
async function confirmPreparationWave() {
const caseNo = String(activeCase.value?.case_no || '').trim();
const draftVersion = activeCase.value?.draft?.draft_version;
@@ -3919,7 +4079,7 @@ watch(
<main
class="flex h-full min-h-0 flex-1 flex-col overflow-hidden bg-slate-50 text-slate-900 dark:bg-slate-950 dark:text-slate-100"
data-testid="shipping-order-review-view"
:data-readonly="isReadOnly ? 'true' : 'false'"
:data-readonly="isReviewContentReadOnly ? 'true' : 'false'"
:data-workbench-mode="workbenchMode"
>
<ReviewWorkbenchHeader
@@ -3930,7 +4090,7 @@ watch(
:saving="saving"
:save-failed="saveFailed"
:draft-conflict="Boolean(draftConflict)"
:is-read-only="isReadOnly"
:is-read-only="isReviewContentReadOnly"
:show-version-history="Boolean(activeCase)"
:show-audit-trail="Boolean(activeCase)"
@back="back"
@@ -4281,16 +4441,20 @@ watch(
<div v-else-if="freightNoticeGroups.length" class="mt-3 space-y-3" data-testid="review-freight-upload-groups">
<div class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-default bg-surface-muted/30 px-3 py-2 text-xs" data-testid="review-freight-upload-batch-toolbar">
<span class="text-secondary">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.selected', { count: selectedFreightBusinessNos.length }) }}</span>
<div class="flex flex-wrap gap-2"><button type="button" class="rounded border border-default px-2 py-1 disabled:opacity-50" :disabled="!selectedFreightBusinessNos.length || freightBatchBusy !== null" @click="void runFreightBatchAction('download')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchDownload') }}</button><button type="button" class="rounded border border-default px-2 py-1 disabled:opacity-50" :disabled="!selectedFreightBusinessNos.length || freightBatchBusy !== null" @click="void runFreightBatchAction('rpa')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchRpa') }}</button><button type="button" class="rounded border border-default px-2 py-1 disabled:opacity-50" :disabled="!selectedFreightBusinessNos.length || freightBatchBusy !== null" @click="void runFreightBatchAction('confirm')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchConfirm') }}</button></div>
<div class="flex flex-wrap gap-2">
<button type="button" class="rounded border border-default px-2 py-1 disabled:opacity-50" :disabled="!selectedFreightBusinessNos.length || freightBatchBusy !== null" @click="void runFreightBatchAction('download')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchDownload') }}</button>
<button type="button" class="rounded border border-default px-2 py-1 disabled:opacity-50" data-testid="review-freight-upload-batch-rpa" :disabled="!selectedFreightBusinessNos.length || selectedFreightNoticesContainUploaded || freightBatchBusy !== null" @click="void runFreightBatchAction('rpa')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchRpa') }}</button>
<button type="button" class="rounded border border-default px-2 py-1 disabled:opacity-50" data-testid="review-freight-upload-batch-confirm" :disabled="!selectedFreightBusinessNos.length || selectedFreightNoticesContainUploaded || freightBatchBusy !== null" @click="void runFreightBatchAction('confirm')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchConfirm') }}</button>
</div>
</div>
<div v-for="group in freightNoticeGroups" :key="group.business_no" class="rounded-lg border border-default" data-testid="review-freight-upload-notice">
<div class="flex flex-wrap items-center justify-between gap-3 border-b border-default bg-surface-muted/40 px-3 py-2 text-xs">
<label class="flex items-center gap-2 font-semibold text-primary"><input type="checkbox" :checked="selectedFreightBusinessNos.includes(group.business_no)" :aria-label="group.business_no" @change="toggleFreightNoticeSelection(group.business_no, ($event.target as HTMLInputElement).checked)"><span>{{ group.business_no }}</span></label>
<span class="text-secondary">PO: {{ group.po_number || '—' }} · {{ group.export_file_name || '—' }}</span>
<div class="flex items-center gap-2">
<span :class="freightUploadStatusDisplay(group).chipClass" class="rounded-full px-2 py-0.5 font-medium">{{ freightUploadStatusDisplay(group).label }}</span>
<span :class="freightUploadStatusDisplay(group).chipClass" :title="freightUploadStatusDisplay(group).reason || undefined" class="rounded-full px-2 py-0.5 font-medium cursor-help" tabindex="0">{{ freightUploadStatusDisplay(group).label }}</span>
<button type="button" class="rounded border border-brand-200 px-2 py-1 font-medium text-brand-700 hover:bg-brand-50" data-testid="review-freight-upload-download" :disabled="saving" @click="void downloadFreightNotice(group.business_no)">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.download') }}</button>
<details class="relative">
<details v-if="hasFreightNoticeMoreActions(group)" class="relative" data-testid="review-freight-upload-more">
<summary class="list-none rounded border border-default p-1 text-secondary hover:bg-surface" :aria-label="t('chat.shippingProcessing.action.more')"><MoreHorizontal class="h-3.5 w-3.5" aria-hidden="true" /></summary>
<div class="absolute right-0 top-7 z-10 flex min-w-40 flex-col gap-1 rounded border border-default bg-surface p-1 shadow-lg">
<button v-if="canRunFreightNoticeAction(group, 'retry_freight_upload_rpa')" type="button" class="rounded px-2 py-1 text-left text-[11px] text-primary hover:bg-surface-muted disabled:opacity-50" :disabled="freightBatchBusy !== null" @click="void runFreightNoticeAction(group, 'rpa')">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.batchRpa') }}</button>
@@ -4300,7 +4464,6 @@ watch(
</details>
</div>
</div>
<div v-if="freightUploadStatusDisplay(group).reason" class="border-b border-default bg-rose-50/50 px-3 py-2 text-xs text-rose-700 dark:bg-rose-950/10 dark:text-rose-300" data-testid="review-freight-upload-error">{{ freightUploadStatusDisplay(group).reason }}</div>
<table class="min-w-full text-left text-xs"><thead class="border-b border-default bg-surface-muted/30"><tr><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.freightUpload.lineNo') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultPartNumber') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.workbench.resultReservation') }}</th><th class="px-3 py-2">{{ t('chat.shippingOrderReview.lifecycle.prepare.requiredQty') }}</th></tr></thead><tbody><tr v-for="line in group.lines" :key="`${group.business_no}-${line.line_no}-${line.part_number}`" class="border-b border-default last:border-0" data-testid="review-freight-upload-line"><td class="px-3 py-2"><span :class="freightLineNoDisplay(line).muted ? 'text-muted' : ''" :title="freightLineNoDisplay(line).title">{{ freightLineNoDisplay(line).text }}</span></td><td class="px-3 py-2">{{ line.part_number || '—' }}</td><td class="px-3 py-2">{{ line.reservation_id || '—' }}</td><td class="px-3 py-2">{{ line.shipment_qty || '—' }}</td></tr></tbody></table>
</div>
</div>
@@ -4346,6 +4509,13 @@ watch(
<Check class="h-3.5 w-3.5" aria-hidden="true" />
{{ t('chat.shippingOrderReview.lifecycle.uploadComplete.uploaded') }}
</span>
<span
v-if="freightUploadModeLabel(group.upload_mode)"
class="inline-flex items-center gap-1 rounded-full border border-emerald-300/60 bg-emerald-100/60 px-2 py-0.5 font-medium text-emerald-700 dark:border-emerald-700/60 dark:bg-emerald-950/40 dark:text-emerald-300"
data-testid="review-upload-complete-mode"
>
{{ freightUploadModeLabel(group.upload_mode) }}
</span>
<span class="text-secondary">{{ group.po_number ? `PO: ${group.po_number}` : '' }}</span>
</div>
<div class="flex items-center gap-2">
@@ -4452,7 +4622,7 @@ watch(
<h2 class="text-sm font-semibold">{{ t('chat.shippingOrderReview.orderFields') }}</h2>
<p class="mt-1 text-xs text-slate-500">{{ t('chat.shippingOrderReview.schemaVersion', { version: displayCase?.schema.schema_version_id || '-' }) }}</p>
</div>
<span v-if="isReadOnly" class="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600 dark:bg-slate-800 dark:text-slate-300">
<span v-if="isReviewContentReadOnly" class="rounded-full bg-slate-100 px-2 py-0.5 text-xs text-slate-600 dark:bg-slate-800 dark:text-slate-300">
{{ t('chat.shippingOrderReview.readOnly') }}
</span>
</div>
@@ -4476,7 +4646,7 @@ watch(
</div>
<input
:value="draftValue(displayHeaderValues, field.field_id)"
:disabled="caseContentSkeleton || !isFieldEditable(field.field_id) || saving"
:disabled="caseContentSkeleton || !canEditReviewField(field.field_id) || saving"
class="mt-1 w-full rounded-md border border-slate-300 bg-white px-2.5 py-2 text-sm dark:border-slate-600 dark:bg-slate-950"
:class="{
'border-sky-400 ring-2 ring-sky-300 dark:border-sky-500 dark:ring-sky-700': isEvidenceLinkedField(field.field_id),
@@ -4490,7 +4660,7 @@ watch(
>
<div class="mt-1 flex items-center justify-between gap-2 text-[11px] text-slate-500">
<span>{{ valueSourceLabel(draftFieldMeta(displayHeaderValues as Record<string, unknown> | undefined, field.field_id).value_source) }}</span>
<button v-if="!caseContentSkeleton && isFieldEditable(field.field_id)" type="button" class="hover:text-sky-600" @click="reportSave(() => patchHeader(field.field_id, null, true))">
<button v-if="!caseContentSkeleton && canEditReviewField(field.field_id)" type="button" class="hover:text-sky-600" @click="reportSave(() => patchHeader(field.field_id, null, true))">
<Undo2 class="mr-1 inline h-3 w-3" />{{ t('chat.shippingOrderReview.restoreMachine') }}
</button>
</div>
@@ -4599,7 +4769,7 @@ watch(
<div class="relative flex min-w-0 items-center gap-1">
<input
:value="lineFieldDisplayValue(line, field)"
:disabled="!isFieldEditable(field.field_id) || saving || (field.field_code === 'line_no' && Boolean(draftFieldMeta(line, field.field_id).locked))"
:disabled="!canEditReviewField(field.field_id) || saving || (field.field_code === 'line_no' && Boolean(draftFieldMeta(line, field.field_id).locked))"
class="min-w-0 flex-1 rounded border border-slate-300 bg-white px-1.5 py-1 text-xs dark:border-slate-600 dark:bg-slate-950"
:class="{
'border-amber-400 ring-1 ring-amber-300 dark:border-amber-500': field.field_code === 'line_no'
@@ -5030,7 +5200,7 @@ watch(
:show-stp-retry="showObjectRetryOnFooter"
:auto-gate-hint="t(autoGateHintKey)"
:saving="saving"
:is-read-only="isReadOnly"
:is-read-only="isReviewContentReadOnly"
:has-draft="Boolean(displayCase?.draft) || isLifecycleIntakeParse"
:unsaved-count="unsavedEditCount"
:flow-presentation="flowPresentation"
@@ -529,6 +529,10 @@ function openOrderProcessing(
if (cid) query.conversation_id = cid;
const caseNo = String(item.review_case_no || '').trim();
if (caseNo) query.case_no = caseNo;
// [PERF] 深链携带正式任务号,工作台挂载即可并行拉取任务详情,与 load() 重叠,
// 消除「load() 完成后才轮到任务详情」的串行叠加。
const taskNo = String(item.task_no || '').trim();
if (taskNo) query.task_no = taskNo;
void router.push({ path: `/chat/${agentId}`, query });
}
+130 -2
View File
@@ -1748,6 +1748,28 @@ class CraneUploadAdapter(_BaseUploadAdapter):
启用前(enabled=true)管理端必须已确认提交按钮与成功判定字段;否则 fail-closed。
"""
# SweetAlert2 上传失败弹窗识别(受控 Adapter 内置,禁止开放到 upload_config):Crane 上传
# 失败会弹 swal2-icon-error(如 “The Customer account [...] was not found” / “Warehouse [...] not found”),
# 必须读取原因并点击 OK 关闭,否则页面被模态框拦截,无法继续上传下一个文件。
_ERROR_DIALOG_SELECTORS = (
'.swal2-popup.swal2-icon-error',
'.swal2-icon.swal2-error',
'.swal2-x-mark',
)
_ERROR_MESSAGE_SELECTORS = (
'.swal2-html-container',
'.swal2-content',
'.swal2-title',
)
_ERROR_OK_SELECTOR = '.swal2-confirm'
# SweetAlert2 上传成功弹窗识别(绿色勾):Crane 上传成功同样以 swal2 弹窗反馈。
# 即便 upload_config.result_selector 配置错误,也能据此确认成功,避免误报 unknown。
_SUCCESS_DIALOG_SELECTORS = (
'.swal2-popup.swal2-icon-success',
'.swal2-icon.swal2-success',
)
def run(self, page: Any, *, login_url: str) -> dict[str, Any]:
self._require('entry_url', 'file_input_selector', 'submit_mode')
if str(self.config.get('submit_mode') or '').strip() == 'click_submit':
@@ -1772,17 +1794,115 @@ class CraneUploadAdapter(_BaseUploadAdapter):
else:
raise RuntimeError('Crane upload requires a supported result_mode')
def _take_error_popup_reason(self, page: Any) -> str | None:
"""检测 Crane 上传失败的 SweetAlert2 错误弹窗。
命中时读取失败原因(swal2-html-container,回退 swal2-content / swal2-title)并点击 OK 关闭,
关闭后返回原因文本;未出现错误弹窗时返回 None。点击 OK 是继续上传下一个文件的前提。
"""
try:
popup = None
for selector in self._ERROR_DIALOG_SELECTORS:
loc = page.locator(selector).first
if loc.count() > 0:
try:
if loc.is_visible():
popup = loc
break
except Exception:
continue
if popup is None:
return None
reason = ''
# 优先逐条取 html-container 内的错误行(.my-1),多错误用分号连接;
# 无则回退到容器整体文本,再回退标题。
try:
items = [
str(text or '').strip()
for text in page.locator('.swal2-html-container .my-1').all_text_contents()
if str(text or '').strip()
]
if items:
reason = '; '.join(items)
except Exception:
items = []
if not reason:
for selector in self._ERROR_MESSAGE_SELECTORS:
try:
text = str(page.locator(selector).first.text_content(timeout=1000) or '').strip()
if text:
reason = text
break
except Exception:
continue
ok = page.locator(self._ERROR_OK_SELECTOR).first
try:
if ok.count() > 0:
ok.click(timeout=2000)
except Exception:
pass
return reason or 'Crane upload rejected'
except Exception:
return None
def _take_success_popup(self, page: Any) -> str | None:
"""检测 Crane 上传成功的 SweetAlert2 成功弹窗(绿色勾),返回命中的选择器;未出现返回 None。"""
try:
for selector in self._SUCCESS_DIALOG_SELECTORS:
loc = page.locator(selector).first
if loc.count() > 0:
try:
if loc.is_visible():
return selector
except Exception:
continue
return None
except Exception:
return None
def _raise_if_crane_error(self, page: Any) -> None:
"""若出现 Crane 上传失败弹窗:读取原因、点击 OK 关闭后抛出失败,交由调用方上报真实原因。"""
reason = self._take_error_popup_reason(page)
if reason:
raise RuntimeError(f"Crane upload rejected: {reason}")
def _success_from_popup(self, page: Any, filename: str) -> dict[str, Any] | None:
"""返回成功弹窗的 success_evidence;未命中成功弹窗时返回 None。"""
selector = self._take_success_popup(page)
if selector:
return {
'reference': '',
'success_evidence': _capture_success_page_evidence(
page, kind='crane_page_notice', selector=selector,
filename=filename, reference=None,
),
}
return None
def _resolve_result(self, page: Any) -> dict[str, Any]:
result_mode = str(self.config.get('result_mode') or '').strip()
filename = self.file_path.name
# 提交后先探测一次失败/成功弹窗;判定期内仍会持续探测(结果选择器可能晚于弹窗出现)。
self._raise_if_crane_error(page)
success = self._success_from_popup(page, filename)
if success:
return success
if result_mode == 'history_record':
result_selector = str(self.config.get('result_selector') or '').strip()
try:
loc = page.locator(result_selector).first
loc.wait_for(state='visible', timeout=self._timeout_ms())
except Exception as exc:
# 判定期内可能出现失败弹窗(如 Customer/Warehouse 未找到);先读取并关闭,
# 以真实原因上报失败;否则仍按“结果未知”转人工。
self._raise_if_crane_error(page)
success = self._success_from_popup(page, filename)
if success:
return success
raise _UploadResultUnknownError(
f"Crane upload history not confirmed for {filename!r}: {exc}"
f"无法判断上传是否成功/失败:{filename!r} 历史结果未确认({exc});"
f"可能已上传成功但页面未出现成功提示,或 upload_config 的 result_selector/success_texts 配置有误;"
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
) from exc
try:
reference = str(loc.text_content(timeout=self._timeout_ms()) or '').strip()
@@ -1801,6 +1921,12 @@ class CraneUploadAdapter(_BaseUploadAdapter):
deadline = time.monotonic() + (self._timeout_ms() / 1000)
last_snippet = ''
while time.monotonic() < deadline:
# 上传失败时 Crane 会先弹错误窗而非成功提示;命中则读取原因、点 OK 关闭并上报失败。
self._raise_if_crane_error(page)
# 成功也可能以 SweetAlert2 成功弹窗反馈;优先于配置 result_selector 判定,避免配置错误误报 unknown。
success = self._success_from_popup(page, filename)
if success:
return success
try:
loc = page.locator(result_selector).first
if loc.count() > 0 and loc.is_visible():
@@ -1818,7 +1944,9 @@ class CraneUploadAdapter(_BaseUploadAdapter):
pass
time.sleep(1)
raise _UploadResultUnknownError(
f"Crane upload page notice not confirmed for {filename!r}; last_snippet={last_snippet!r}"
f"无法判断上传是否成功/失败:{filename!r} 结果未确认(last_snippet={last_snippet!r});"
f"可能已上传成功但页面未出现成功提示,或 upload_config 的 result_selector/success_texts 配置有误;"
f"请人工在 CRANE 核查,或用「确认已上传」登记,或修正配置后重试。"
)