From bcdd8285aead9979f137543da50af51e3cefd603 Mon Sep 17 00:00:00 2001 From: caohuipeng Date: Thu, 27 Aug 2026 19:25:16 +0800 Subject: [PATCH] =?UTF-8?q?perf(shipping-notice):=20=E4=BC=98=E5=8C=96?= =?UTF-8?q?=E5=8F=91=E8=B4=A7=E4=BB=BB=E5=8A=A1=E6=80=A7=E8=83=BD=EF=BC=8C?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E4=B8=8A=E4=BC=A0=E6=B5=81=E7=A8=8B=E4=B8=8E?= =?UTF-8?q?=E7=BB=88=E6=80=81=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- backend/app/api/workspace/shipping_notice.py | 6 + backend/app/models/shipping.py | 3 +- .../shipping_notice/fulfillment_workflow.py | 78 ++++--- .../shipping_notice/process_gate_bridge.py | 6 +- .../process_gate_projection.py | 10 + .../services/shipping_notice/query_service.py | 64 +++++- .../shipping_processing_projection.py | 108 +++++---- .../app/services/shipping_notice/ui_state.py | 6 + .../shipping_notice/upload_attempt_service.py | 10 +- ...z9a_allow_unknown_upload_attempt_status.py | 49 +++++ ...z9a0b_widen_shipping_task_events_source.py | 47 ++++ .../test_shipping_notice_query_service.py | 96 ++++++++ .../tests/test_shipping_notice_ui_state.py | 25 +++ ...t_shipping_processing_projection_stage4.py | 42 ++++ .../test_shipping_upload_unknown_state.py | 14 +- .../test_shipping_uploaded_gate_closure.py | 20 ++ docs/features/shipping-notice/technical.md | 1 + .../api/shipping.api.request-dedupe.spec.ts | 55 +++++ .../src/features/chat/api/shipping.api.ts | 42 +++- .../ReviewLifecycleStageNavigation.spec.ts | 23 ++ .../ReviewLifecycleStageNavigation.vue | 22 +- .../ShippingOrderExtractionCard.spec.ts | 30 +++ .../shipping/ShippingOrderExtractionCard.vue | 6 +- .../shipping-review/useShippingOrderReview.ts | 3 +- .../useShippingNoticeWorkflow.spec.ts | 20 ++ .../views/ShippingOrderReviewView.spec.ts | 72 +++++- .../chat/views/ShippingOrderReviewView.vue | 208 ++++++++++++++++-- .../ShippingTaskCenterPage.vue | 4 + scripts/rpa/freight_rpa_worker.py | 132 ++++++++++- 29 files changed, 1074 insertions(+), 128 deletions(-) create mode 100644 backend/migrations/versions/hv5w6x7y8z9a_allow_unknown_upload_attempt_status.py create mode 100644 backend/migrations/versions/hw6x7y8z9a0b_widen_shipping_task_events_source.py diff --git a/backend/app/api/workspace/shipping_notice.py b/backend/app/api/workspace/shipping_notice.py index 45097399..3587f846 100644 --- a/backend/app/api/workspace/shipping_notice.py +++ b/backend/app/api/workspace/shipping_notice.py @@ -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, )) diff --git a/backend/app/models/shipping.py b/backend/app/models/shipping.py index f658dbdc..e11ef0e0 100644 --- a/backend/app/models/shipping.py +++ b/backend/app/models/shipping.py @@ -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) diff --git a/backend/app/services/shipping_notice/fulfillment_workflow.py b/backend/app/services/shipping_notice/fulfillment_workflow.py index c05d084a..a7e87bba 100644 --- a/backend/app/services/shipping_notice/fulfillment_workflow.py +++ b/backend/app/services/shipping_notice/fulfillment_workflow.py @@ -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", diff --git a/backend/app/services/shipping_notice/process_gate_bridge.py b/backend/app/services/shipping_notice/process_gate_bridge.py index 16567071..f68941d9 100644 --- a/backend/app/services/shipping_notice/process_gate_bridge.py +++ b/backend/app/services/shipping_notice/process_gate_bridge.py @@ -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: diff --git a/backend/app/services/shipping_notice/process_gate_projection.py b/backend/app/services/shipping_notice/process_gate_projection.py index 927031d9..7b060f11 100644 --- a/backend/app/services/shipping_notice/process_gate_projection.py +++ b/backend/app/services/shipping_notice/process_gate_projection.py @@ -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 = [] diff --git a/backend/app/services/shipping_notice/query_service.py b/backend/app/services/shipping_notice/query_service.py index 0fbf0df3..527912ac 100644 --- a/backend/app/services/shipping_notice/query_service.py +++ b/backend/app/services/shipping_notice/query_service.py @@ -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) diff --git a/backend/app/services/shipping_notice/shipping_processing_projection.py b/backend/app/services/shipping_notice/shipping_processing_projection.py index 9cbe4eee..e6509640 100644 --- a/backend/app/services/shipping_notice/shipping_processing_projection.py +++ b/backend/app/services/shipping_notice/shipping_processing_projection.py @@ -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 ''), diff --git a/backend/app/services/shipping_notice/ui_state.py b/backend/app/services/shipping_notice/ui_state.py index 4a686e6f..be7c979b 100644 --- a/backend/app/services/shipping_notice/ui_state.py +++ b/backend/app/services/shipping_notice/ui_state.py @@ -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')) diff --git a/backend/app/services/shipping_notice/upload_attempt_service.py b/backend/app/services/shipping_notice/upload_attempt_service.py index c2eb84e3..eb4294a1 100644 --- a/backend/app/services/shipping_notice/upload_attempt_service.py +++ b/backend/app/services/shipping_notice/upload_attempt_service.py @@ -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: diff --git a/backend/migrations/versions/hv5w6x7y8z9a_allow_unknown_upload_attempt_status.py b/backend/migrations/versions/hv5w6x7y8z9a_allow_unknown_upload_attempt_status.py new file mode 100644 index 00000000..bb7ff8e3 --- /dev/null +++ b/backend/migrations/versions/hv5w6x7y8z9a_allow_unknown_upload_attempt_status.py @@ -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')", + ) diff --git a/backend/migrations/versions/hw6x7y8z9a0b_widen_shipping_task_events_source.py b/backend/migrations/versions/hw6x7y8z9a0b_widen_shipping_task_events_source.py new file mode 100644 index 00000000..d79a4a0e --- /dev/null +++ b/backend/migrations/versions/hw6x7y8z9a0b_widen_shipping_task_events_source.py @@ -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']) diff --git a/backend/tests/test_shipping_notice_query_service.py b/backend/tests/test_shipping_notice_query_service.py index 3ce66bcd..4dfd0198 100644 --- a/backend/tests/test_shipping_notice_query_service.py +++ b/backend/tests/test_shipping_notice_query_service.py @@ -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 diff --git a/backend/tests/test_shipping_notice_ui_state.py b/backend/tests/test_shipping_notice_ui_state.py index 7d69c53e..a26d008f 100644 --- a/backend/tests/test_shipping_notice_ui_state.py +++ b/backend/tests/test_shipping_notice_ui_state.py @@ -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(): diff --git a/backend/tests/test_shipping_processing_projection_stage4.py b/backend/tests/test_shipping_processing_projection_stage4.py index 02ff2c1d..6d7c28ac 100644 --- a/backend/tests/test_shipping_processing_projection_stage4.py +++ b/backend/tests/test_shipping_processing_projection_stage4.py @@ -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 diff --git a/backend/tests/test_shipping_upload_unknown_state.py b/backend/tests/test_shipping_upload_unknown_state.py index 54b78786..f95a896c 100644 --- a/backend/tests/test_shipping_upload_unknown_state.py +++ b/backend/tests/test_shipping_upload_unknown_state.py @@ -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() diff --git a/backend/tests/test_shipping_uploaded_gate_closure.py b/backend/tests/test_shipping_uploaded_gate_closure.py index 27b457ad..d3b8deaa 100644 --- a/backend/tests/test_shipping_uploaded_gate_closure.py +++ b/backend/tests/test_shipping_uploaded_gate_closure.py @@ -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') diff --git a/docs/features/shipping-notice/technical.md b/docs/features/shipping-notice/technical.md index 2b7c6606..6dbb8923 100644 --- a/docs/features/shipping-notice/technical.md +++ b/docs/features/shipping-notice/technical.md @@ -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;建议不可用时人工复核和确定性主链仍可继续。 diff --git a/frontend/src/features/chat/api/shipping.api.request-dedupe.spec.ts b/frontend/src/features/chat/api/shipping.api.request-dedupe.spec.ts index 4495b840..6cf6bf21 100644 --- a/frontend/src/features/chat/api/shipping.api.request-dedupe.spec.ts +++ b/frontend/src/features/chat/api/shipping.api.request-dedupe.spec.ts @@ -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(); diff --git a/frontend/src/features/chat/api/shipping.api.ts b/frontend/src/features/chat/api/shipping.api.ts index 4cea9e77..f5fa3311 100644 --- a/frontend/src/features/chat/api/shipping.api.ts +++ b/frontend/src/features/chat/api/shipping.api.ts @@ -118,9 +118,45 @@ export const listWorkspaceShippingTasks = (params?: { /** 拉取用户可见 Agent 列表,供发货工作台跳转 Chat 时定位目标 Agent。 */ export const listShippingChatAgents = () => requestJson('/api/agents'); -/** 获取单个发货任务详情。 */ -export const getWorkspaceShippingTask = (taskNo: string) => - requestJson(`/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>(); + +/** 获取单个发货任务详情。@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(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) => diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts index 0ce28300..81b9edc5 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts +++ b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.spec.ts @@ -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"]'); diff --git a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue index ed6eb2da..0122f1ba 100644 --- a/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue +++ b/frontend/src/features/chat/components/shipping-review/ReviewLifecycleStageNavigation.vue @@ -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) { >