/** * features/shipping-progress/actionPresentation.ts * 用途:从统一投影 / 会话 OT 任务解析四页面共用的 ActionPresentation(主/次/溢出)。 * 依赖:ShippingProcessingProjection、ConversationProcessingUserTask、workbenchActionRegistry、types。 * 逻辑:优先级 Gate.nextActionCode → availableActions → 终态查看 → none; * 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'; /** 可映射为统一意图的原始动作码(gate / available_actions)。 */ 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', freeze_order: '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_source_review: 'open_inventory_source_review', confirm_inventory_source: 'open_inventory_source_review', retry_resolve_inventory_source: 'open_inventory_source_review', open_inventory_match_review: 'open_inventory_match_review', rematch: 'open_inventory_match_review', match_inventory: 'open_inventory_match_review', open_shortage_review: 'open_shortage_review', upload_inventory_file: 'upload_inventory_file', retry: 'retry', retry_parse: 'retry', retry_failed_documents: 'retry', retry_failed_attachments: 'retry', retry_upload: 'retry', retry_freight_upload_rpa: 'retry', // 订单识别复核卡后端动作码:统一复用右侧「进入订单处理/重试解析/查看结果」执行器。 edit_draft: 'open_order_review', reconcile_and_progress: 'open_order_review', create_draft: 'open_order_review', retry_stp_auto_create: 'retry', reparse: 'retry', view: 'view_result', refresh: 'refresh', regenerate_excel: 'regenerate_excel', generate_excel: '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']); const NEEDS_ACTION_STATUSES = new Set([ 'blocked', 'waiting_review', 'pending_review', 'waiting_human', 'failed', 'reparse_failed', 'manual_upload_pending', 'upload_rpa_failed', ]); /** 永不升为主 CTA 的动作码(仍可作次要/溢出)。 */ const NEVER_PRIMARY_CODES = new Set(['cancel_task', 'cancel_run', 'view_details']); /** * 将原始动作码映射为统一意图;未知码返回 null。 * * @param code - Gate / available_actions 原始码 */ 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, ): ActionPresentationItem { let labelKey = `chat.shippingProcessing.action.${intent}`; const normalized = String(code || '').trim().toLowerCase(); const chatOrRight = surface === 'chat' || surface === 'right'; if (intent === 'open_order_review' && chatOrRight) { labelKey = 'chat.shippingProcessing.action.open_order_processing'; } else if (normalized === 'retry_freight_upload_rpa' || normalized === 'retry_upload') { labelKey = 'chat.shippingNoticeRetryUploadAction'; } else if (intent === 'retry' && chatOrRight) { labelKey = 'chat.shippingProcessing.action.retry_parse'; } 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, }; } /** * 将动作列表拆成主/次/溢出;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. processing/automating/queued → 主按钮为空(自动推进中); * 2. currentGate.nextActionCode 优先; * 3. availableActions 依次填主/次/溢出; * 4. completed/failed/cancelled → view_result / view_record 兜底; * 5. surface=review 时经注册表 fail-closed(未知隐藏 + 告警;隐藏 refresh/自跳转); * 6. 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 status = String(projection.status || '').trim().toLowerCase(); if (AUTOMATING_STATUSES.has(status) && !projection.currentGate?.nextActionCode) { return empty; } const items: ActionPresentationItem[] = []; const seen = new Set(); const pushCode = (raw: string | null | undefined) => { const code = String(raw || '').trim(); if (!code) return; const key = code.toLowerCase(); // 仅用于管理员恢复缺失待办记录,不作为普通用户履约动作展示。 if (key === 'regenerate_manual_upload_todo') return; if (seen.has(key)) return; seen.add(key); // 识别/建单失败的 view 是进入当前 Case 处理;已完成任务才打开只读结果。 const intent = key === 'view' && NEEDS_ACTION_STATUSES.has(status) ? 'open_order_review' : 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)); }; pushCode(projection.primaryAction?.code || projection.currentGate?.nextActionCode); // Gate 20 同时保留两条用户路径:主动重试 RPA 与人工上传登记。 // 该动作由正式任务面板打开登记弹窗,不走 Gate API。 if ( String(projection.currentGate?.gateCode || '').trim().toLowerCase() === 'manual_upload_handoff' && items.some((item) => String(item.actionCode).toLowerCase() === 'retry_freight_upload_rpa') ) { pushCode('mark_manual_uploaded'); } // [ORDER-STABLE] 对 availableActions 标准化(去重 + 字典序排序),确保后端返回顺序不影响前端按钮顺序。 const normalizedAvailableActions = normalizeActionCodes(projection.availableActions || []); for (const action of normalizedAvailableActions) { pushCode(action); } // Gate 19 RPA 失败时,人工登记作为任务级替代路径展示,避免与 RPA 重试并列。 if ( String(projection.currentGate?.gateCode || '').trim().toLowerCase() === 'freight_upload_rpa' && items.some((item) => String(item.actionCode).toLowerCase() === 'retry_freight_upload_rpa') ) { for (let index = items.length - 1; index >= 0; index -= 1) { const code = String(items[index]?.actionCode || '').toLowerCase(); if (code === 'mark_manual_uploaded' || code === 'open_manual_upload' || code === 'wait_manual_upload') { items.splice(index, 1); } } } if (items.length === 0 && (status === 'completed' || status === 'failed' || status === 'cancelled')) { pushCode('view_result'); } if (AUTOMATING_STATUSES.has(status) && items.length === 0) { return empty; } return partitionActionItems(items); } /** * 从会话 OT 任务投影解析 ActionPresentation(无 workItem 时的统一适配器)。 * 核心逻辑:primary_action 优先;available_actions 补充;无正式入口时 focus_task→查看进度; * 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.userStatus ?? '').trim().toLowerCase(); const legacyStatus = String(task.status_label ?? '').trim().toLowerCase(); const status = userStatus || legacyStatus; const isNeedsAction = task.group === 'needs_action' || NEEDS_ACTION_STATUSES.has(status); 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) => { const code = String(raw || '').trim(); if (!code) return; const key = code.toLowerCase(); if (seen.has(key)) return; const intent = key === 'view' && isNeedsAction ? 'open_order_review' : mapActionCodeToIntent(code); if (!intent || intent === 'none') return; seen.add(key); items.push(toItem(code, intent, surface)); }; pushCode(task.primaryAction?.code || task.primary_action); // [ORDER-STABLE] 对 available_actions 标准化排序,确保后端顺序变化不影响按钮渲染顺序。 const normalizedTaskActions = normalizeActionCodes(task.available_actions || []); for (const action of normalizedTaskActions) { pushCode(action); } // 人工待办禁止伪造查看进度;无明确动作时进入订单处理作为安全兜底。 if (isNeedsAction && !items.some((item) => !NEVER_PRIMARY_CODES.has(String(item.actionCode || '').trim().toLowerCase()))) { pushCode('open_order_processing'); } // 只有系统处理中才允许显示查看进度,且只能作为次要文字链。 if (isProcessing && !items.length) pushCode('focus_task'); 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); }