/** * features/shipping-progress/actionPresentation.ts * 用途:从统一投影 / 会话 OT 任务解析四页面共用的 ActionPresentation(主/次/溢出)。 * 依赖:ShippingProcessingProjection、ConversationProcessingUserTask、workbenchActionRegistry、types。 * 逻辑:只消费后端 ui_state.primary_action / secondary_actions; * cancel_* 与 view_details 永不作主 CTA;无业务入口时 focus_task 兜底并映射「查看进度」; * 自动处理中(processing/automating)主按钮为空;review 面经注册表 fail-closed 过滤。 */ import type { ConversationProcessingUserTask, ShippingProcessingActionIntent, ShippingProcessingProjection, } from '@/features/chat/types/shipping.api.types'; import { normalizeActionCodes } from '@/features/chat/shipping/conversationProcessingProjection'; import type { ActionPresentation, ActionPresentationItem, ActionPresentationSurface } from './types'; import type { WorkbenchPanelAvailability } from './workbenchActionRegistry'; import { lookupWorkbenchAction, shouldRenderWorkbenchAction, warnUnregisteredWorkbenchAction, } from './workbenchActionRegistry'; /** 可映射为统一意图的后端已授权动作码。 */ const ACTION_CODE_TO_INTENT: Record = { open_order_review: 'open_order_review', open_review: 'open_order_review', open_order_processing: 'open_order_review', enter_manual_review: 'open_order_review', edit_formal_task: 'edit_formal_task', open_profile_review: 'open_profile_review', confirm_customer: 'confirm_customer', resolve_field_conflicts: 'resolve_field_conflicts', adjudicate_duplicate: 'adjudicate_duplicate', open_inventory_match_review: 'open_inventory_match_review', open_shortage_review: 'open_shortage_review', reload_inventory_result: 'reload_inventory_result', retry_inventory_preparation: 'retry_inventory_preparation', retry_inventory_matching: 'retry_inventory_matching', reparse_batch: 'reparse_batch', retry_parse: 'retry_parse', retry_failed_documents: 'retry_failed_documents', retry_failed_attachments: 'retry_failed_attachments', retry_freight_upload_rpa: 'retry_freight_upload_rpa', retry_order_extraction: 'retry_order_extraction', retry_layout_parsing: 'retry_layout_parsing', rematerialize_document: 'rematerialize_document', reroute_document_profile: 'reroute_document_profile', revalidate_reservation: 'revalidate_reservation', retry_customer_resolution: 'retry_customer_resolution', retry_duplicate_detection: 'retry_duplicate_detection', retry_with_latest_rules: 'retry_with_latest_rules', recheck_freeze_readiness: 'recheck_freeze_readiness', retry_task_creation: 'retry_task_creation', retry_inventory_field_mapping: 'retry_inventory_field_mapping', recheck_inventory_sufficiency: 'recheck_inventory_sufficiency', recheck_excel_readiness: 'recheck_excel_readiness', poll_inventory_preparation: 'refresh', poll_freight_upload_rpa: 'refresh', edit_order_fields: 'open_order_review', edit_reservation: 'open_order_review', // 订单识别复核卡后端动作码:统一复用右侧「进入订单处理/重试解析/查看结果」执行器。 edit_draft: 'open_order_review', reconcile_and_progress: 'open_order_review', create_draft: 'open_order_review', retry_stp_auto_create: 'retry_stp_auto_create', reparse: 'reparse', view: 'view_result', refresh: 'refresh', regenerate_excel_artifact: 'regenerate_excel', download_excel: 'download_excel', open_manual_upload: 'open_manual_upload', wait_manual_upload: 'open_manual_upload', mark_manual_uploaded: 'open_manual_upload', regenerate_manual_upload_todo: 'open_manual_upload', open_fulfillment: 'view_result', view_result: 'view_result', view_details: 'view_result', focus_task: 'view_result', view_record: 'view_record', /** 取消类动作映射为 view_record,以便进入 presentation(再由 NEVER_PRIMARY 降为次要)。 */ cancel_task: 'view_record', cancel_run: 'view_record', }; const AUTOMATING_STATUSES = new Set(['processing', 'automating', 'queued']); /** 需要在聊天/右侧展示精确恢复动作文案的正式 action_code。 */ const RECOVERY_ACTION_CODES = new Set([ 'reload_inventory_result', 'retry_inventory_preparation', 'retry_inventory_matching', 'retry_parse', 'retry_failed_documents', 'retry_failed_attachments', 'retry_freight_upload_rpa', 'retry_order_extraction', 'retry_layout_parsing', 'rematerialize_document', 'reroute_document_profile', 'revalidate_reservation', 'retry_customer_resolution', 'retry_duplicate_detection', 'retry_with_latest_rules', 'recheck_freeze_readiness', 'retry_task_creation', 'retry_inventory_field_mapping', 'recheck_inventory_sufficiency', 'recheck_excel_readiness', 'retry_stp_auto_create', 'reparse', ]); /** 永不升为主 CTA 的动作码(仍可作次要/溢出)。 */ const NEVER_PRIMARY_CODES = new Set(['cancel_task', 'cancel_run', 'view_details']); /** 五阶段已单独提供入口的纯查看/导航动作,不应再占用文件行主 CTA。 */ const FILE_ROW_NAVIGATION_CODES = new Set([ 'open_order_review', 'open_review', 'open_order_processing', 'enter_manual_review', 'view', 'view_result', 'view_record', ]); /** * 仅供执行编排或历史审计使用的库存恢复动作;不得重新暴露为正式用户 CTA。 * 它们会绕过当前库存步骤的标准语义,用户入口必须使用 retry_inventory_preparation * 或 retry_inventory_matching 等稳定动作码。 */ const INTERNAL_INVENTORY_ACTION_CODES = new Set([ 'retry_inventory_from_preparation', 'retry_inventory_from_matching', 'retry_inventory_field_mapping', 'retry_inventory_from_field_mapping', 'poll_inventory_preparation', 'refresh_inventory_candidate_projection', 'recheck_inventory_sufficiency', ]); /** * 返回库存业务动作的唯一展示文案键。 * 核心逻辑:所有 Surface 以 action_code 为准共享同一翻译,而不改变后端 Gate 的执行码。 * @param code - 后端下发的库存 Gate 动作码 * @returns 统一翻译键;非库存动作返回 null */ export function inventoryActionLabelKey(code: string | null | undefined): string | null { const normalized = String(code || '').trim().toLowerCase(); const keyByCode: Record = { reload_inventory_result: 'workspace.shippingNotice.processGate.inventoryActions.reloadInventoryResult', retry_inventory_preparation: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryPreparation', retry_inventory_matching: 'workspace.shippingNotice.processGate.inventoryActions.retryInventoryMatching', open_inventory_match_review: 'workspace.shippingNotice.processGate.inventoryActions.openInventoryMatchReview', open_shortage_review: 'workspace.shippingNotice.processGate.inventoryActions.openShortageReview', download_inventory_file: 'workspace.shippingNotice.processGate.inventoryActions.downloadInventoryFile', release_inventory_shortage: 'workspace.shippingNotice.processGate.inventoryActions.releaseInventoryShortage', }; return keyByCode[normalized] || null; } /** * 判断动作是否只能留在内部恢复编排中。 * @param code - Gate / Projection 原始动作码 * @returns true 表示正式用户界面必须 fail-closed 隐藏 */ export function isInternalInventoryAction(code: string | null | undefined): boolean { return INTERNAL_INVENTORY_ACTION_CODES.has(String(code || '').trim().toLowerCase()); } /** * 将原始动作码映射为统一意图;未知码返回 null。 * * @param code - 后端已授权动作码 */ export function mapActionCodeToIntent(code: string | null | undefined): ShippingProcessingActionIntent | null { const normalized = String(code || '').trim().toLowerCase(); if (!normalized) return null; return ACTION_CODE_TO_INTENT[normalized] || null; } /** * 构建单个动作项。 * 核心逻辑:默认 labelKey=action.{intent};chat/right 面只改写重试解析 / 查看进度。 */ function toItem( code: string, intent: ShippingProcessingActionIntent, surface?: ActionPresentationSurface, targetLifecycleStage?: string | null, ): ActionPresentationItem { let labelKey = `chat.shippingProcessing.action.${intent}`; const normalized = String(code || '').trim().toLowerCase(); const chatOrRight = surface === 'chat' || surface === 'right'; // 后端明确指定接收解析 surface 时,文案必须与目标一致;不能因复用同一 // 只读导航动作码而误显示为订单处理。该分支不改变权限或路由目标。 if (targetLifecycleStage === 'intake_parse') { labelKey = 'chat.shippingProcessing.action.open_intake_parse'; } else if (normalized === 'create_draft' || normalized === 'edit_draft' || normalized === 'validate') { labelKey = `chat.shippingProcessing.action.${normalized}`; } else if (inventoryActionLabelKey(normalized)) { labelKey = inventoryActionLabelKey(normalized)!; } else if (normalized === 'retry_freight_upload_rpa') { labelKey = 'chat.shippingNoticeRetryUploadAction'; } else if (normalized === 'reparse_batch') { labelKey = 'chat.shippingProcessing.action.reparse_batch'; } else if (normalized === 'reparse' || normalized === 'retry_parse') { // 两者都是对当前文件重新执行解析;不同 action_code 只区分后端目标, // 用户界面统一使用同一业务名称,避免把同一能力误解为不同操作。 labelKey = 'chat.shippingProcessing.action.reparse'; } else if (RECOVERY_ACTION_CODES.has(normalized) && chatOrRight) { // 重试必须保留 Gate/对象边界,不能退化为泛化动作名称。 labelKey = `workspace.shippingNotice.processGate.actionCodes.${normalized}`; } else if (normalized === 'focus_task' && chatOrRight) { labelKey = 'chat.shippingProcessing.action.view_progress'; } else if (normalized === 'cancel_task' || normalized === 'cancel_run') { labelKey = 'chat.shippingProcessing.cancelEntireTaskSingle'; } else if (normalized === 'view_details') { labelKey = 'chat.shippingProcessing.viewTaskDetails'; } return { intent, actionCode: code, labelKey, targetLifecycleStage: ( targetLifecycleStage === 'intake_parse' || targetLifecycleStage === 'order_review' || targetLifecycleStage === 'fulfillment_prep' || targetLifecycleStage === 'freight_upload' || targetLifecycleStage === 'upload_complete' ) ? targetLifecycleStage : null, }; } /** * 将动作列表拆成主/次/溢出;cancel 与 view_details 永不作 primary。 */ function partitionActionItems(items: ActionPresentationItem[]): ActionPresentation { if (!items.length) { return { primary: null, secondary: null, overflow: [] }; } const primaryPool = items.filter( (item) => !NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()), ); const demoted = items.filter( (item) => NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()), ); const primary = primaryPool[0] || null; const rest = [ ...primaryPool.slice(1), ...demoted, ]; return { primary, secondary: rest[0] || null, overflow: rest.slice(1), }; } export interface ResolveProcessingActionPresentationOptions { surface?: ActionPresentationSurface; /** 订单处理工作台写权限;仅 surface=review 时生效。 */ actionsExecutable?: boolean; /** 面板可用性(review 面 requiresPanel 守卫)。 */ panels?: WorkbenchPanelAvailability | null; } /** * 解析统一动作投影。 * * 核心逻辑: * 1. 有 ui_state 时只渲染其已授权主/次动作; * 2. processing/automating/queued 且无 ui_state 动作时主按钮为空; * 3. surface=review 时经注册表 fail-closed(未知隐藏 + 告警;隐藏 refresh/自跳转); * 4. cancel / view_details 强制降为次要或溢出。 * * @param projection - 统一处理投影 * @param options - surface / actionsExecutable / panels */ export function resolveProcessingActionPresentation( projection: ShippingProcessingProjection | null | undefined, options?: ResolveProcessingActionPresentationOptions, ): ActionPresentation { const empty: ActionPresentation = { primary: null, secondary: null, overflow: [] }; if (!projection) return empty; const surface = options?.surface; const actionsExecutable = options?.actionsExecutable !== false; const panels = options?.panels ?? null; const authoritativeUiState = projection.uiState; const status = String(authoritativeUiState?.status || '').trim().toLowerCase(); if (!authoritativeUiState || AUTOMATING_STATUSES.has(status) && !authoritativeUiState.primary_action) { return empty; } const items: ActionPresentationItem[] = []; const seen = new Set(); const pushCode = ( raw: string | null | undefined, targetLifecycleStage?: string | null, ) => { const code = String(raw || '').trim(); if (!code || code.toLowerCase() === 'retry') return; const key = code.toLowerCase(); if (isInternalInventoryAction(key)) return; // 仅用于管理员恢复缺失待办记录,不作为普通用户履约动作展示。 if (key === 'regenerate_manual_upload_todo') return; if (seen.has(key)) return; seen.add(key); // [AUTHORITY] view 仅表示查看;生命周期入口必须由后端显式下发 open_order_review。 const intent = mapActionCodeToIntent(code); if (!intent || intent === 'none') { // [fail-closed] 未知动作不渲染原始码,仅告警。 warnUnregisteredWorkbenchAction({ actionCode: code, surface: surface || 'workbench', workItemType: projection.workItemType, }); return; } if (surface === 'review') { const entry = lookupWorkbenchAction(code) || lookupWorkbenchAction(intent); if (!entry) { warnUnregisteredWorkbenchAction({ actionCode: code, surface: 'review', workItemType: projection.workItemType, }); return; } if (!shouldRenderWorkbenchAction(entry, { actionsExecutable, surface: 'review', panels, actionCode: code, })) { return; } } items.push(toItem( code, intent, surface, targetLifecycleStage ?? ( authoritativeUiState?.primary_action?.code === code ? authoritativeUiState.primary_action.targetLifecycleStage : null ), )); }; // [AUTHORITY] ui_state 是唯一按钮合同;缺失即 fail-closed。 pushCode(authoritativeUiState.primary_action?.code); const actionCodes = authoritativeUiState.secondary_actions .filter((action) => action.enabled) .map((action) => action.code); for (const action of actionCodes) { const secondary = authoritativeUiState?.secondary_actions.find((item) => item.code === action); pushCode(action, secondary?.targetLifecycleStage); } // Gate 19 RPA 失败时,人工登记作为任务级替代路径展示,避免与 RPA 重试并列。 return partitionActionItems(items); } /** * 解析批次中心文件行的主动作。 * * 核心逻辑:五阶段按钮是唯一的纯导航入口;文件行只保留后端授权的业务动作, * 不根据状态推导或新增动作,也不改变通用任务卡的动作展示。 */ export function resolveFilePrimaryActionPresentation( projection: ShippingProcessingProjection | null | undefined, ): ActionPresentationItem | null { const primaryAction = projection?.uiState?.primary_action; const code = String(primaryAction?.code || '').trim().toLowerCase(); if ( primaryAction?.executionMode === 'navigate' && FILE_ROW_NAVIGATION_CODES.has(code) ) { return null; } return resolveProcessingActionPresentation(projection, { surface: 'right' }).primary; } /** * 从会话 OT 任务投影解析 ActionPresentation(无 workItem 时的统一适配器)。 * 核心逻辑:仅消费 ui_state 的 primary_action / secondary_actions; * cancel/view_details 永不作主 CTA。 * @param task - 会话用户可见任务 * @param options.surface - 展示面(默认 right) */ export function resolveConversationTaskActionPresentation( task: ConversationProcessingUserTask | null | undefined, options?: { surface?: ActionPresentationSurface }, ): ActionPresentation { const empty: ActionPresentation = { primary: null, secondary: null, overflow: [] }; if (!task) return empty; const surface = options?.surface || 'right'; const userStatus = String(task.uiState?.status ?? '').trim().toLowerCase(); const status = userStatus; const isProcessing = task.group === 'processing' || AUTOMATING_STATUSES.has(status); if (task.group === 'history' || status === 'cancelled') { return empty; } const items: ActionPresentationItem[] = []; const seen = new Set(); const pushCode = ( raw: string | null | undefined, targetLifecycleStage?: string | null, ) => { const code = String(raw || '').trim(); if (!code || code.toLowerCase() === 'retry') return; const key = code.toLowerCase(); if (isInternalInventoryAction(key)) return; if (seen.has(key)) return; // 任务卡同样禁止通过“待处理 + view”补造订单生命周期权限。 const intent = mapActionCodeToIntent(code); if (!intent || intent === 'none') return; seen.add(key); items.push(toItem(code, intent, surface, targetLifecycleStage)); }; if (!task.uiState) return empty; pushCode(task.uiState.primary_action?.code, task.uiState.primary_action?.targetLifecycleStage); const normalizedTaskActions = normalizeActionCodes( task.uiState.secondary_actions.filter((item) => item.enabled).map((item) => item.code), ); for (const action of normalizedTaskActions) { const secondary = task.uiState?.secondary_actions.find((item) => item.code === action); pushCode(action, secondary?.targetLifecycleStage); } const hasPrimaryCandidate = items.some( (item) => !NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()), ); if (!hasPrimaryCandidate && !isProcessing) { return empty; } if (isProcessing) { const progress = items.find((item) => String(item.actionCode).toLowerCase() === 'focus_task'); return { primary: null, secondary: progress || null, overflow: [] }; } return partitionActionItems(items); }