Files
syops/frontend/src/features/chat/composables/useChatShipping.ts
T
hugo 9c036c825b refactor(chat/shipping): 重构发货通知模块为统一UI State驱动模式
- 重构发货通知的状态与动作获取逻辑:移除从聊天文本解析HXOPS_SHIPPING_ACTIONS注释的旧逻辑,改为统一从后端shipping_ui_state获取任务状态、动作按钮与工作流步骤
- 新增SSE实时推送shipping_ui_state事件,支持前端即时更新聊天气泡与工作台的状态与按钮
- 优化路由与登录流程:调整根路径重定向逻辑,退出登录时跳转到登录页;移除chat路由不必要的props传参;将原路由守卫中的根路径判断迁移到路由配置中
- 完善库存RPA与本地导入流程:新增本地库存文件托管接口,优化RPA回调的文件落盘与任务关联逻辑
- 新增多组单元测试覆盖焦点切换、决策处理、SSE同步等核心场景
- 修复多语言显示逻辑,使用te方法判断翻译key是否存在,避免缺失翻译时的渲染异常
- 新增reparse_inventory菜单动作,支持静默重新解析库存且不追加额外聊天消息
- 重构工作流步骤渲染函数,优先使用后端返回的步骤数据, fallback到本地推导的旧逻辑
- 清理后端旧的chat-actions API接口,将相关逻辑迁移到统一的ui_state接口中
2026-07-02 01:55:19 +08:00

968 lines
35 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* features/chat/composables/useChatShipping.ts
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
* 依赖:shipping.api、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件再把任务状态、动作刷新、文件上传、决策与发送拦截分发给 shipping 子模块。
*/
import {
computed,
onBeforeUnmount,
ref,
watch,
type ComputedRef,
type Ref,
} from 'vue';
import { SHIPPING_NOTICE_AGENT_NAME } from '@/features/chat/api/shipping.api';
import {
createShippingActionsRefresher,
createShippingConversationHelpers,
createShippingDecisionHandlers,
createShippingLocalMessages,
createShippingMappingFormHandlers,
createShippingMenuHandlers,
createShippingParseReviewHandlers,
createShippingSendHandlers,
createShippingUploadHandlers,
findHistorySessionForShippingTask,
findLatestShippingTaskId,
getShippingInventoryMappingPayload,
getShippingMatchResultPayload,
getShippingParseReviewPayload,
getShippingInventorySampleRowText,
hasShippingInventorySampleRows,
normalizeShippingHeaderForDisplay,
sanitizeShippingConversationText,
shippingActionButtonClass,
} from '../shipping';
import {
getWorkspaceShippingConversationBatches,
getWorkspaceShippingBatch,
getWorkspaceShippingTask,
switchWorkspaceShippingBatchFocusTask,
type ShippingBatchUiState,
type ShippingBatchSummary,
type ShippingConversationWorkspace,
type ShippingTaskDetail,
type ShippingTaskSummary,
} from '@/features/chat/api/shipping.api';
import {
buildShortageDetailsMessage,
hasShortageLines,
isShippingShortageQueryIntent,
} from '../shipping/shippingShortageDetails';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
import type { ChatDeps } from './chat.deps';
import { listChatMessages } from '../api/chat.api';
export interface UseChatShippingOptions {
deps: ChatDeps;
currentAgent: Ref<{ name?: string } | null>;
currentAgentId: ComputedRef<number>;
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
isThinking: Ref<boolean>;
history: Ref<ChatSessionItem[]>;
loadHistory: () => Promise<void>;
input: Ref<string>;
chatScrollContainer: Ref<HTMLElement | null>;
attachments: Ref<PendingAttachment[]>;
selectedKb: Ref<string>;
isUploadingAttachments: Ref<boolean>;
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
presetQuestion: ComputedRef<string>;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
newLocalMessageId: (prefix: string) => string;
stripReasoningPrelude: (text: string) => string;
sendMessage: (
content: string,
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
context?: { task_id?: string; batch_no?: string; display_query?: string },
hooks?: { onAssistantMessageFinished?: (message: ChatMessage, runMessages: ChatMessage[]) => void | Promise<void> },
) => Promise<void>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
createNewChatView: () => void;
}
/**
* 解析批次切换后的默认焦点状态。
* 核心逻辑:优先取状态机记录的 current focus,其次回退到 process summary 当前任务,再回退到任务列表首票;只有拿到 task_no 才回填默认聚焦原因。
* @param batchSummary - 当前批次摘要
* @param batchTasks - 当前批次任务列表
* @param defaultReason - 批次切换后写入输入栏提示的默认焦点原因
* @returns 供步骤条、按钮与右侧工作台共用的 focus 状态;取不到 task 时返回空焦点
*/
export const resolveShippingBatchFocusState = (
batchSummary: {
current_focus_task_no?: string | null;
process_summary?: { current_task_no?: string | null } | null;
} | null | undefined,
batchTasks: Array<{ task_no?: string | null }> | null | undefined,
defaultReason: string,
) => {
const taskNo = String(
batchSummary?.current_focus_task_no
|| batchSummary?.process_summary?.current_task_no
|| batchTasks?.[0]?.task_no
|| '',
).trim();
return {
taskNo,
focusReason: taskNo ? defaultReason : '',
};
};
/**
* 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。
*
* 核心逻辑:统一管理当前任务/批次上下文,组合上传、映射、决策、动作刷新等子模块,并对 ChatView 暴露稳定 API。
* @param options - 聊天页依赖与响应式状态集合
* @returns 发货通知聊天场景所需的状态、事件处理器和工具函数
*/
export function useChatShipping(options: UseChatShippingOptions) {
const {
deps: { t, msg, router, route },
currentAgent,
currentAgentId,
messages,
conversationId,
isThinking,
history,
loadHistory,
input,
chatScrollContainer,
attachments,
selectedKb,
isUploadingAttachments,
attachmentPolicy,
presetQuestion,
saveLocalMessageToBackend,
newLocalMessageId,
stripReasoningPrelude,
sendMessage,
buildFileSpecsForSend,
loadConversation,
createNewChatView,
} = options;
const shippingBindSend = (_fn: () => Promise<void>) => {
void _fn;
// 保留旧绑定入口,续办链路已改为直接调用 sendMessage 以支持 display_query 上下文。
};
// ── 功能开关与 UI refs ────────────────────────────────────
const isShippingNoticeAgent = computed(() => currentAgent.value?.name === SHIPPING_NOTICE_AGENT_NAME);
const allowsSendWithAttachmentsOnly = computed(
() => isShippingNoticeAgent.value && attachments.value.length > 0,
);
const shippingAutoFlowRequested = ref(false);
const shippingInventoryPickerRef = ref<HTMLInputElement | null>(null);
const shippingNoticePickerRef = ref<HTMLInputElement | null>(null);
const pendingShippingUploadTaskId = ref('');
const pendingShippingInventoryFile = ref<File | null>(null);
const shippingInventorySelectionActive = ref(false);
const shippingInventorySelectionTaskId = ref('');
const prepareMarkdownDisplayText = (text: string) => {
return sanitizeShippingConversationText(stripReasoningPrelude(text), isShippingNoticeAgent.value);
};
// ── 任务编号状态 ──────────────────────────────────────────
const shippingTaskIdFromQuery = computed(() => {
const value = route.query.task_id;
return typeof value === 'string' ? value.trim() : '';
});
const shippingBatchNoFromQuery = computed(() => {
const value = route.query.batch_no;
return typeof value === 'string' ? value.trim() : '';
});
const resolvedShippingTaskId = ref('');
const resolvedShippingBatchNo = ref('');
const activeShippingBatchNo = ref('');
const focusedShippingTaskNo = ref('');
const shippingConversationWorkspace = ref<ShippingConversationWorkspace | null>(null);
const shippingBatchSummary = ref<ShippingBatchSummary | null>(null);
const shippingBatchTasks = ref<ShippingTaskSummary[]>([]);
const shippingWorkspaceOpen = ref(false);
const retryingShippingPendingTasks = ref(false);
const activeShippingTaskDetail = ref<ShippingTaskDetail | null>(null);
const shippingFocusReason = ref('');
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
const lastConversationSyncKey = ref('');
let shippingStatusPollTimer: ReturnType<typeof setInterval> | null = null;
const applyShippingBatchDetail = (
detail: ShippingBatchUiState,
fallbackBatchNo: string,
) => {
const normalizedBatchNo = detail.batch_no || fallbackBatchNo;
resolvedShippingBatchNo.value = normalizedBatchNo;
if (!activeShippingBatchNo.value || activeShippingBatchNo.value === fallbackBatchNo) {
activeShippingBatchNo.value = normalizedBatchNo;
}
shippingBatchTasks.value = Array.isArray(detail.tasks) ? detail.tasks : [];
shippingBatchSummary.value = {
id: detail.id,
batch_no: detail.batch_no,
conversation_id: detail.conversation_id,
current_focus_task_no: detail.focus_task?.task_no || detail.current_focus_task_no || null,
file_count: detail.file_count,
process_summary: detail.process_summary || null,
created_at: detail.created_at,
updated_at: detail.updated_at,
};
const preferredTaskNo = String(
detail.focus_task?.task_no
|| detail.process_summary?.current_task_no
|| detail.current_focus_task_no
|| '',
).trim();
if (preferredTaskNo) {
resolvedShippingTaskId.value = preferredTaskNo;
}
if (detail.focus_task && detail.focus_task_ui_state) {
activeShippingTaskDetail.value = {
...(activeShippingTaskDetail.value || {}),
...detail.focus_task,
lines: activeShippingTaskDetail.value?.lines || [],
events: activeShippingTaskDetail.value?.events || [],
ui_state: detail.focus_task_ui_state,
} as ShippingTaskDetail;
}
};
const syncShippingBatchSummary = async (batchNo: string) => {
const normalized = String(batchNo || '').trim();
if (!normalized) {
shippingBatchSummary.value = null;
shippingBatchTasks.value = [];
return;
}
try {
const detail = await getWorkspaceShippingBatch(normalized);
applyShippingBatchDetail(detail, normalized);
} catch {
// ignore summary refresh failure in chat flow
}
};
const applyConversationWorkspaceFocus = (workspace: ShippingConversationWorkspace) => {
const batches = Array.isArray(workspace.batches) ? workspace.batches : [];
if (!batches.length) return;
const queryBatchNo = String(shippingBatchNoFromQuery.value || '').trim();
const currentBatchNo = String(activeShippingBatchNo.value || resolvedShippingBatchNo.value || queryBatchNo || '').trim();
const selectedBatch = batches.find((item) => item.batch_no === currentBatchNo)
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : null)
|| batches.find((item) => item.focus_task?.task_no)
|| batches[0];
if (!selectedBatch) return;
applyShippingBatchDetail(selectedBatch, selectedBatch.batch_no);
};
const syncShippingConversationWorkspace = async () => {
const localConversationId = String(conversationId.value || '').trim();
if (!localConversationId || !isShippingNoticeAgent.value) {
shippingConversationWorkspace.value = null;
return;
}
try {
const workspace = await getWorkspaceShippingConversationBatches(localConversationId);
shippingConversationWorkspace.value = workspace;
applyConversationWorkspaceFocus(workspace);
} catch {
shippingConversationWorkspace.value = null;
}
};
const switchShippingFocusTask = async (taskNo: string) => {
const batchNo = getActiveShippingBatchNo();
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
if (!batchNo || !normalizedTaskNo) return false;
await switchWorkspaceShippingBatchFocusTask(batchNo, normalizedTaskNo);
resolvedShippingTaskId.value = normalizedTaskNo;
focusedShippingTaskNo.value = normalizedTaskNo;
shippingFocusReason.value = t('chat.shippingNoticeUi.currentFocusDefaultReason');
if (shippingBatchSummary.value) {
shippingBatchSummary.value = {
...shippingBatchSummary.value,
current_focus_task_no: normalizedTaskNo,
};
}
await syncShippingBatchSummary(batchNo);
await syncShippingConversationWorkspace();
await syncActiveShippingTaskDetail(normalizedTaskNo);
await refreshShippingActions();
return true;
};
const clearShippingFocus = () => {
focusedShippingTaskNo.value = '';
shippingFocusReason.value = '';
};
const switchShippingBatch = async (batchNo: string) => {
const normalizedBatchNo = String(batchNo || '').trim();
if (!normalizedBatchNo) return false;
activeShippingBatchNo.value = normalizedBatchNo;
resolvedShippingBatchNo.value = normalizedBatchNo;
const workspaceBatch = shippingConversationWorkspace.value?.batches.find((item) => item.batch_no === normalizedBatchNo);
if (workspaceBatch) {
applyShippingBatchDetail(workspaceBatch, normalizedBatchNo);
} else {
await syncShippingBatchSummary(normalizedBatchNo);
}
const nextFocusState = resolveShippingBatchFocusState(
shippingBatchSummary.value,
shippingBatchTasks.value,
t('chat.shippingNoticeUi.currentFocusDefaultReason'),
);
const nextTaskNo = nextFocusState.taskNo;
focusedShippingTaskNo.value = nextFocusState.taskNo;
shippingFocusReason.value = nextFocusState.focusReason;
if (nextTaskNo) {
resolvedShippingTaskId.value = nextTaskNo;
await syncActiveShippingTaskDetail(nextTaskNo);
}
await refreshShippingActions();
return true;
};
/**
* 清空当前聊天页绑定的发货任务上下文。
*
* 核心逻辑:在新建对话、切换 Agent 或离开发货任务场景时,主动清掉批次/任务/上传缓存,
* 避免顶部 Stepper、列表展开态和待上传库存文件残留到下一次新会话。
*/
const resetShippingConversationState = () => {
shippingAutoFlowRequested.value = false;
pendingShippingUploadTaskId.value = '';
pendingShippingInventoryFile.value = null;
shippingInventorySelectionActive.value = false;
shippingInventorySelectionTaskId.value = '';
resolvedShippingTaskId.value = '';
resolvedShippingBatchNo.value = '';
activeShippingBatchNo.value = '';
focusedShippingTaskNo.value = '';
shippingFocusReason.value = '';
shippingConversationWorkspace.value = null;
shippingBatchSummary.value = null;
shippingBatchTasks.value = [];
shippingWorkspaceOpen.value = false;
retryingShippingPendingTasks.value = false;
activeShippingTaskDetail.value = null;
shippingInventorySchemaPreviewCache.value = {};
lastConversationSyncKey.value = '';
};
const getActiveShippingTaskId = () =>
findLatestShippingTaskId(messages.value)
|| resolvedShippingTaskId.value
|| shippingTaskIdFromQuery.value
|| '';
const getActiveShippingBatchNo = () =>
activeShippingBatchNo.value
|| resolvedShippingBatchNo.value
|| shippingBatchNoFromQuery.value
|| String(shippingBatchSummary.value?.batch_no || '').trim()
|| '';
const getCurrentShippingChatContext = () => ({
task_id: getActiveBatchTaskId() || getActiveShippingTaskId(),
batch_no: getActiveShippingBatchNo(),
});
const getCurrentShippingChatContextWithDisplay = (displayQuery: string) => ({
...getCurrentShippingChatContext(),
display_query: displayQuery,
});
const getActiveBatchTaskId = () => String(
shippingBatchSummary.value?.current_focus_task_no
|| shippingBatchSummary.value?.process_summary?.current_task_no
|| shippingBatchTasks.value[0]?.task_no
|| focusedShippingTaskNo.value
|| resolvedShippingTaskId.value
|| '',
).trim();
const hasRunningShippingBatchTasks = () =>
shippingBatchTasks.value.some(
(task) => !['uploaded', 'completed', 'closed', 'rejected'].includes(String(task.process_status || '').trim()),
);
/**
* 同步当前焦点任务详情,并在仅恢复 `task_no` 的场景下补齐 `batch_no` 上下文。
*
* 核心逻辑:先拉取任务详情,再把详情里的批次号回填到聊天状态,确保会话恢复后仍能继续按批次模式加载 2 票/多票摘要。
* @param taskId - 可选任务编号;未传时回退到当前激活任务
*/
const syncActiveShippingTaskDetail = async (taskId?: string) => {
const normalized = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
if (!normalized) {
activeShippingTaskDetail.value = null;
return;
}
try {
const detail = await getWorkspaceShippingTask(normalized);
const detailBatchNo = String(detail.batch_no || '').trim();
const activeBatchNo = String(activeShippingBatchNo.value || '').trim();
if (activeBatchNo && detailBatchNo && detailBatchNo !== activeBatchNo) {
return;
}
activeShippingTaskDetail.value = detail;
if (detailBatchNo && resolvedShippingBatchNo.value !== detailBatchNo) {
resolvedShippingBatchNo.value = detailBatchNo;
activeShippingBatchNo.value = activeShippingBatchNo.value || detailBatchNo;
}
} catch {
activeShippingTaskDetail.value = null;
}
};
const syncConversationMessagesIfNeeded = async (taskId?: string) => {
const conversationKey = String(conversationId.value || '').trim();
const normalizedTaskId = String(taskId || getActiveShippingTaskId() || '').trim().toUpperCase();
if (!conversationKey || !normalizedTaskId || !isShippingNoticeAgent.value || isThinking.value) return;
const detail = activeShippingTaskDetail.value;
// 任务详情接口当前不返回顶层 checkpoint,parse_review 需从详情状态字段回推。
const checkpoint = String(
(detail?.step_payload as Record<string, unknown> | undefined)?.checkpoint
|| detail?.review_status
|| '',
).trim();
if (checkpoint !== 'parse_review') return;
const exists = messages.value.some((msg) => {
if (msg.type !== 'shipping-parse-review' || !msg.payload || typeof msg.payload !== 'object') return false;
return String((msg.payload as { taskId?: string }).taskId || '').trim().toUpperCase() === normalizedTaskId;
});
if (exists) return;
const syncKey = `${conversationKey}|${normalizedTaskId}|parse_review`;
if (lastConversationSyncKey.value === syncKey) return;
const loaded = await listChatMessages(conversationKey, currentAgentId.value);
if (Array.isArray(loaded) && loaded.length > 0) {
messages.value = loaded;
lastConversationSyncKey.value = syncKey;
}
};
const lastAssistantMessageContent = () => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const item = messages.value[i];
if (item?.role === 'assistant') return String(item.content || '');
}
return '';
};
const lastAssistantShippingActions = () => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const item = messages.value[i];
if (item?.role === 'assistant' && Array.isArray(item.shipping_actions)) {
return item.shipping_actions;
}
}
return [];
};
const { refreshShippingActions } = createShippingActionsRefresher({
isShippingNoticeAgent,
messages,
conversationId,
isThinking,
history,
resolvedShippingTaskId,
shippingTaskIdFromQuery,
getActiveBatchTaskId,
});
const { pushShippingLocalUserMessage, pushShippingLocalAssistantMessage } = createShippingLocalMessages({
messages,
newLocalMessageId,
saveLocalMessageToBackend,
});
/**
* Dify SSE 完成后立即净化最后一条回复,并同步后端动作按钮。
*
* 核心逻辑:流式过程中只做展示层净化;终态事件到达后消息对象已经完整,
* 此时调用统一 refreshShippingActions,把 action_buttons 回写到当前 assistant 气泡。
*/
const finalizeShippingAssistantMessage = async () => {
if (!isShippingNoticeAgent.value) return;
await refreshShippingActions();
};
/**
* 为“查询缺口明细”定位任务事实来源。
*
* 核心逻辑:优先使用显式任务号或当前聚焦任务,再从批次摘要/当前详情中读取;
* 摘要缺少逐行缺口时补拉既有任务详情接口,确保聊天回复只基于后端事实数据。
*/
const resolveShippingTaskForShortageQuery = async (taskNo?: string) => {
const normalizedTaskNo = String(
taskNo
|| focusedShippingTaskNo.value
|| getActiveBatchTaskId()
|| getActiveShippingTaskId()
|| '',
).trim().toUpperCase();
if (!normalizedTaskNo) return null;
const summaryTask = shippingBatchTasks.value.find(
(item) => String(item.task_no || '').trim().toUpperCase() === normalizedTaskNo,
);
if (summaryTask && hasShortageLines(summaryTask)) return summaryTask;
const detail = activeShippingTaskDetail.value;
if (String(detail?.task_no || '').trim().toUpperCase() === normalizedTaskNo && hasShortageLines(detail)) {
return detail;
}
try {
return await getWorkspaceShippingTask(normalizedTaskNo);
} catch {
return summaryTask || null;
}
};
/**
* 在聊天流中输出确定性的缺口明细。
*
* 核心逻辑:追加一条本地用户意图消息和一条本地助手事实回复,不转发给 Dify,
* 避免大模型复述或重新计算预订单、料号与缺口数量。
*/
const queryShippingShortageDetails = async (taskNo?: string, displayText?: string) => {
const task = await resolveShippingTaskForShortageQuery(taskNo);
if (!task) {
msg.warning(t('chat.shippingNoticeMissingTaskId'));
return true;
}
await pushShippingLocalUserMessage(displayText || t('chat.shippingNoticeUi.queryShortageDetails'));
await pushShippingLocalAssistantMessage(buildShortageDetailsMessage(task, t));
return true;
};
const { sendShippingMenuMessage } = createShippingConversationHelpers({
conversationId,
history,
loadHistory,
getActiveShippingTaskId,
currentAgentId,
selectedKb,
sendMessage,
});
const {
openShippingInventoryMappingFormForTask,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
} = createShippingMappingFormHandlers({
messages,
chatScrollContainer,
shippingInventorySchemaPreviewCache,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
resolvedShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
pushShippingLocalAssistantMessage,
refreshShippingActions,
msg,
});
const { executeShippingDecision, executeShippingManualUpload } = createShippingDecisionHandlers({
messages,
conversationId,
history,
isShippingNoticeAgent,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
loadHistory,
openShippingInventoryMappingFormForTask,
refreshShippingActions,
msg,
t,
});
const {
syncShippingParseReviewCard,
updateShippingParseReviewHeader,
updateShippingParseReviewLine,
addShippingParseReviewLine,
removeShippingParseReviewLine,
} = createShippingParseReviewHandlers({
messages,
resolvedShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
refreshShippingActions,
msg,
});
const {
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
openShippingInventoryPicker,
selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection,
handleShippingInventorySelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
} = createShippingUploadHandlers({
conversationId,
attachments,
input,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
pendingShippingInventoryFile,
resolvedShippingTaskId,
resolvedShippingBatchNo,
shippingBatchSummary,
shippingBatchTasks,
shippingInventorySelectionActive,
shippingInventorySelectionTaskId,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
sendShippingMenuMessage,
pushShippingLocalUserMessage,
pushShippingLocalAssistantMessage,
refreshShippingActions,
msg,
t,
});
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
isThinking,
getActiveShippingTaskId,
messages,
newLocalMessageId,
saveLocalMessageToBackend,
sendShippingMenuMessage,
openShippingInventoryMappingFormForTask,
openShippingInventoryPicker,
openShippingNoticePicker: () => {
shippingNoticePickerRef.value?.click();
return true;
},
executeShippingDecision,
executeShippingManualUpload,
refreshShippingActions,
msg,
t,
});
const { tryHandleShippingSend, tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers({
isShippingNoticeAgent,
isThinking,
isUploadingAttachments,
messages,
conversationId,
history,
input,
attachments,
shippingAutoFlowRequested,
resolvedShippingTaskId,
getActiveShippingBatchNo,
currentAgentId,
selectedKb,
attachmentPolicy,
getActiveShippingTaskId,
lastAssistantMessageContent,
lastAssistantShippingActions,
sendMessage,
buildFileSpecsForSend,
loadHistory,
sendShippingMenuMessage,
pushShippingLocalUserMessage,
pushShippingLocalAssistantMessage,
openShippingInventoryPicker,
executeShippingDecision,
executeShippingManualUpload,
handleShippingMenuAction,
handleShippingAutoUploadFile,
handleShippingAutoUploadNoticeBatch,
refreshShippingActions,
shippingSuggestedPrompt,
isShippingShortageQueryIntent,
queryShippingShortageDetails,
msg,
t,
});
// ── 路由 / 会话生命周期 ───────────────────────────────────
const resumeShippingTaskFromQuery = async () => {
const batchNo = shippingBatchNoFromQuery.value;
if (batchNo && isShippingNoticeAgent.value) {
await syncShippingBatchSummary(batchNo);
if (!shippingTaskIdFromQuery.value && resolvedShippingTaskId.value) {
return;
}
}
const taskId = shippingTaskIdFromQuery.value;
if (!taskId || !isShippingNoticeAgent.value) return;
if (route.query.conversation_id) return;
if (presetQuestion.value) return;
if (autoResumedShippingTasks.value[taskId]) return;
const existing = findHistorySessionForShippingTask(history.value, taskId);
if (existing) {
await loadConversation(existing.conversation_id, { force: true });
return;
}
autoResumedShippingTasks.value[taskId] = true;
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId });
await sendMessage(
t('chat.shippingNoticeContinue', { taskId }),
currentAgentId.value,
selectedKb.value,
[],
getCurrentShippingChatContextWithDisplay(displayText),
);
await loadHistory();
};
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
if (prevId !== nextId) {
resolvedShippingTaskId.value = '';
if (!shippingBatchNoFromQuery.value) {
resolvedShippingBatchNo.value = '';
shippingBatchSummary.value = null;
shippingBatchTasks.value = [];
}
}
};
/**
* 续办指定任务,并把聊天上下文切到该任务继续推进。
*
* 核心逻辑:先切换批次焦点任务,再把内部续办指令发给 Agent;
* 前端和历史只展示业务端可理解的简短重试话术,避免暴露工具名。
* @param taskNo - 需要续办的任务编号
* @returns 是否已成功触发续办
*/
const resumeShippingTask = async (taskNo: string) => {
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
if (!normalizedTaskNo || !isShippingNoticeAgent.value || isThinking.value) return false;
const switched = await switchShippingFocusTask(normalizedTaskNo);
if (!switched) return false;
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId: normalizedTaskNo });
await sendMessage(
t('chat.shippingNoticeContinue', { taskId: normalizedTaskNo }),
currentAgentId.value,
selectedKb.value,
[],
getCurrentShippingChatContextWithDisplay(displayText),
);
await loadHistory();
await refreshShippingActions();
return true;
};
const retryShippingInventoryRpa = async (taskNo: string) => {
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
if (!normalizedTaskNo || !isShippingNoticeAgent.value || isThinking.value) return false;
const switched = await switchShippingFocusTask(normalizedTaskNo);
if (!switched) return false;
const ok = await executeShippingDecision('retry_rpa', t('chat.shippingNoticeUi.retryRpa'));
await syncShippingConversationWorkspace();
const batchNo = getActiveShippingBatchNo();
if (batchNo) await syncShippingBatchSummary(batchNo);
await refreshShippingActions();
return ok;
};
const retryCurrentShippingBatchPendingTasks = async () => {
const batchNo = getActiveShippingBatchNo();
if (!batchNo || retryingShippingPendingTasks.value) return false;
retryingShippingPendingTasks.value = true;
try {
const { retryWorkspaceShippingBatchPending } = await import('@/features/chat/api/shipping.api');
const result = await retryWorkspaceShippingBatchPending(batchNo);
msg.success(result.message || t('chat.shippingNoticeUi.retryPendingDone'));
await syncShippingConversationWorkspace();
await syncShippingBatchSummary(batchNo);
await refreshShippingActions();
return true;
} catch (error) {
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
return false;
} finally {
retryingShippingPendingTasks.value = false;
}
};
const onConversationLoadedEmpty = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
await router.replace({ path: route.path, query: nextQuery });
};
const onConversationLoadFailed = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
createNewChatView();
const nextQuery: Record<string, string> = { task_id: shippingTaskIdFromQuery.value };
if (shippingBatchNoFromQuery.value) nextQuery.batch_no = shippingBatchNoFromQuery.value;
void router.replace({ path: route.path, query: nextQuery });
const displayText = t('chat.shippingNoticeUi.retrySingleTaskMessage', { taskId: shippingTaskIdFromQuery.value });
await sendMessage(
t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value }),
currentAgentId.value,
selectedKb.value,
[],
getCurrentShippingChatContextWithDisplay(displayText),
);
await loadHistory();
};
/**
* 启停发货批次状态短轮询。
*
* 核心逻辑:聊天流当前没有 shipping 专属 SSE;因此在存在任务/批次上下文时每 3 秒补拉一次,
* 让顶部 Stepper、批次统计和动作按钮能在后端异步状态变化后自动更新。
*/
const restartShippingStatusPolling = () => {
if (shippingStatusPollTimer) {
clearInterval(shippingStatusPollTimer);
shippingStatusPollTimer = null;
}
if (!isShippingNoticeAgent.value) return;
const batchNo = getActiveShippingBatchNo();
const taskId = getActiveBatchTaskId();
if (!batchNo && !taskId) return;
shippingStatusPollTimer = setInterval(() => {
if (!isShippingNoticeAgent.value) return;
const nextBatchNo = getActiveShippingBatchNo();
const nextTaskId = getActiveBatchTaskId();
if (!nextBatchNo && !nextTaskId) return;
void (async () => {
await syncShippingConversationWorkspace();
if (nextBatchNo) await syncShippingBatchSummary(nextBatchNo);
if (nextTaskId) {
await syncActiveShippingTaskDetail(nextTaskId);
await syncConversationMessagesIfNeeded(nextTaskId);
}
await refreshShippingActions();
if (!hasRunningShippingBatchTasks() && !isThinking.value && shippingStatusPollTimer) {
clearInterval(shippingStatusPollTimer);
shippingStatusPollTimer = null;
}
})();
}, 3000);
};
// ── 动作按钮 watch ────────────────────────────────────────
const shippingActionsWatchKey = computed(() => {
const msgs = messages.value;
const last = msgs.length ? msgs[msgs.length - 1] : null;
return [
String(conversationId.value || ''),
String(msgs.length),
String(last?.role || ''),
String(last?.content || '').slice(-120),
].join('|');
});
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
void refreshShippingActions().then(async () => {
const taskId = getActiveBatchTaskId() || getActiveShippingTaskId();
await Promise.all([
syncShippingParseReviewCard(taskId),
syncActiveShippingTaskDetail(taskId),
]);
await syncConversationMessagesIfNeeded(taskId);
});
});
watch([activeShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingBatchNo], ([activeBatchNo, queryBatchNo, batchNo]) => {
const nextBatchNo = String(activeBatchNo || queryBatchNo || batchNo || '').trim();
if (!nextBatchNo) {
shippingBatchSummary.value = null;
return;
}
void syncShippingBatchSummary(nextBatchNo);
}, { immediate: true });
watch([conversationId, isShippingNoticeAgent], () => {
void syncShippingConversationWorkspace();
}, { immediate: true });
watch(
[isShippingNoticeAgent, conversationId, resolvedShippingBatchNo, shippingBatchNoFromQuery, resolvedShippingTaskId, shippingTaskIdFromQuery, isThinking],
() => {
restartShippingStatusPolling();
},
{ immediate: true },
);
onBeforeUnmount(() => {
if (shippingStatusPollTimer) {
clearInterval(shippingStatusPollTimer);
shippingStatusPollTimer = null;
}
});
return {
shippingBindSend,
isShippingNoticeAgent,
prepareMarkdownDisplayText,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
shippingNoticePickerRef,
pendingShippingUploadTaskId,
shippingInventorySelectionActive,
shippingInventorySelectionTaskId,
allowsSendWithAttachmentsOnly,
shippingTaskIdFromQuery,
shippingBatchNoFromQuery,
resolvedShippingBatchNo,
activeShippingBatchNo,
focusedShippingTaskNo,
shippingFocusReason,
shippingConversationWorkspace,
shippingBatchSummary,
shippingBatchTasks,
shippingWorkspaceOpen,
retryingShippingPendingTasks,
activeShippingTaskDetail,
getCurrentShippingChatContext,
getActiveShippingBatchNo,
switchShippingBatch,
switchShippingFocusTask,
clearShippingFocus,
resumeShippingTask,
retryShippingInventoryRpa,
retryCurrentShippingBatchPendingTasks,
queryShippingShortageDetails,
resetShippingConversationState,
resumeShippingTaskFromQuery,
normalizeShippingHeaderForDisplay,
getShippingInventoryMappingPayload,
getShippingMatchResultPayload,
getShippingParseReviewPayload,
hasShippingInventorySampleRows,
getShippingInventorySampleRowText,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
updateShippingParseReviewHeader,
updateShippingParseReviewLine,
addShippingParseReviewLine,
removeShippingParseReviewLine,
handleShippingActionClick,
handleShippingInventorySelected,
finalizeShippingAssistantMessage,
selectShippingInventoryUploadTask,
cancelShippingInventoryTaskSelection,
shippingActionButtonClass,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
tryHandleShippingAttachmentAutoFlow,
tryHandleShippingSend,
onConversationIdChanging,
onConversationLoadedEmpty,
onConversationLoadFailed,
};
}