!15 perf(shipping-notice): 优化发货任务性能,修复上传流程与终态问题
Merge pull request !15 from 曹惠鹏/hugo-shipping-notice
This commit is contained in:
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,
|
||||
))
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user