1509 lines
57 KiB
TypeScript
1509 lines
57 KiB
TypeScript
/**
|
||
* features/chat/composables/useChatShipping.ts
|
||
* 用途:发货通知聊天编排入口,组合 shipping/* 子模块并对 ChatView 暴露统一交互能力。
|
||
* 依赖:shipping.api、shipping/ 下各 handler 工厂、chat.deps、chat.types、Vue refs/computed/watch。
|
||
* 逻辑:上游由 ChatView/ChatPage 调用本 composable;本文件再把任务状态、动作刷新、文件上传、决策与发送拦截分发给 shipping 子模块。
|
||
* 批次「重试所有失败」成功后不弹居中 msg.success,由页面级 toast 展示 started/skipped。
|
||
*/
|
||
|
||
import {
|
||
computed,
|
||
onBeforeUnmount,
|
||
ref,
|
||
watch,
|
||
type ComputedRef,
|
||
type Ref,
|
||
} from 'vue';
|
||
import { useAuthStore } from '@/features/auth/stores/auth.store';
|
||
import { agentUsesWorkspaceStepperProgress, isShippingNoticeAgent as resolveShippingNoticeAgent } from '@/shared/utils/agent-registry.utils';
|
||
import type { AgentRegistryFields } from '@/shared/utils/agent-registry.utils';
|
||
import { hasActiveRunningChatRun } from '../shipping/shippingActionBusy';
|
||
|
||
import { useShippingNoticeIntakes } from '../shipping/useShippingNoticeIntakes';
|
||
import {
|
||
createShippingActionsRefresher,
|
||
createShippingConversationHelpers,
|
||
createShippingDecisionHandlers,
|
||
createShippingMappingFormHandlers,
|
||
createShippingMenuHandlers,
|
||
createShippingParseReviewHandlers,
|
||
createShippingSendHandlers,
|
||
createShippingUploadHandlers,
|
||
onNoticeBatchConversationChanging,
|
||
findLatestShippingTaskId,
|
||
getShippingInventoryMappingPayload,
|
||
getShippingMatchResultPayload,
|
||
getShippingParseReviewPayload,
|
||
getShippingInventorySampleRowText,
|
||
hasShippingInventorySampleRows,
|
||
normalizeShippingHeaderForDisplay,
|
||
sanitizeShippingConversationText,
|
||
shippingActionButtonClass,
|
||
} from '../shipping';
|
||
import { reportShippingDebugEvent } from '../shipping/shippingDebugReporter';
|
||
import { classifyShippingUploadFile } from '../shipping/shippingUploadPrompt';
|
||
import { extractExt } from '../constants/shipping';
|
||
import {
|
||
getWorkspaceShippingConversationBatches,
|
||
getWorkspaceShippingBatch,
|
||
getWorkspaceShippingTask,
|
||
listWorkspaceShippingCustomerOptions,
|
||
confirmWorkspaceShippingCustomer,
|
||
switchWorkspaceShippingBatchFocusTask,
|
||
type ShippingBatchUiState,
|
||
type ShippingBatchSummary,
|
||
type ShippingConversationWorkspace,
|
||
type ShippingTaskDetail,
|
||
type ShippingTaskSummary,
|
||
} from '@/features/chat/api/shipping.api';
|
||
import type { ShippingCustomerOption } from '../types/shipping.api.types';
|
||
import { buildShippingQueryShortageTurn } from '../shipping/shippingTurnActions';
|
||
import {
|
||
hasShortageLines,
|
||
isShippingShortageQueryIntent,
|
||
} from '../shipping/shippingShortageDetails';
|
||
|
||
import type { ChatMessage, ChatRun, ChatSessionItem, ShippingMessageRecoveryPayload } from '../types/chat.types';
|
||
import type { SendMessageLifecycleHooks } from './useChat';
|
||
import type { ChatUploadFileSpec, PendingAttachment, ShippingActionButton } from '../types/shipping.types';
|
||
import type { ChatDeps } from './chat.deps';
|
||
import { listChatMessages } from '../api/chat.api';
|
||
|
||
export interface UseChatShippingOptions {
|
||
deps: ChatDeps;
|
||
currentAgent: Ref<AgentRegistryFields | null>;
|
||
currentAgentId: ComputedRef<number>;
|
||
messages: Ref<ChatMessage[]>;
|
||
conversationId: Ref<string | null>;
|
||
isThinking: Ref<boolean>;
|
||
shippingActionBusy: ComputedRef<boolean>;
|
||
activeRunId: Ref<number | null>;
|
||
runs: Ref<ChatRun[]>;
|
||
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; shipping_intake_nos?: string[]; display_query?: string },
|
||
hooks?: SendMessageLifecycleHooks,
|
||
) => Promise<boolean | void>;
|
||
startChatTurn: (options: import('../types/chat-turn.types').StartChatTurnOptions) => Promise<boolean>;
|
||
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 : '',
|
||
};
|
||
};
|
||
|
||
/**
|
||
* 从会话工作台选择本轮应展示的批次。
|
||
* 核心逻辑:订单抽取完成后选服务端按创建时间升序返回的最后一个批次;普通续办优先保留当前批次。
|
||
*/
|
||
export const selectShippingConversationBatch = <T extends { batch_no: string; focus_task?: unknown }>(
|
||
batches: T[],
|
||
currentBatchNo: string,
|
||
queryBatchNo: string,
|
||
preferLatest = false,
|
||
): T | undefined => (
|
||
(preferLatest ? batches[batches.length - 1] : undefined)
|
||
|| batches.find((item) => item.batch_no === currentBatchNo)
|
||
|| (queryBatchNo ? batches.find((item) => item.batch_no === queryBatchNo) : undefined)
|
||
|| batches.find((item) => Boolean(item.focus_task))
|
||
|| batches[0]
|
||
);
|
||
|
||
/**
|
||
* 从消息列表解析最近一次权威批次快照。
|
||
* 核心逻辑:只接受包含批次号和任务数组的 `shipping_batch_ui_state`,供实时终态与历史会话共用。
|
||
* @param sourceMessages - 当前会话消息
|
||
* @returns 最近的合法批次快照;不存在时返回 null
|
||
*/
|
||
export const resolveLatestShippingBatchSnapshot = (
|
||
sourceMessages: ChatMessage[],
|
||
): ShippingBatchUiState | null => {
|
||
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
|
||
const message = sourceMessages[index];
|
||
const payload = message?.payload && typeof message.payload === 'object'
|
||
? message.payload as Record<string, unknown>
|
||
: null;
|
||
const rawSnapshot = payload?.shipping_batch_ui_state;
|
||
if (!rawSnapshot || typeof rawSnapshot !== 'object') continue;
|
||
const snapshot = rawSnapshot as ShippingBatchUiState;
|
||
if (String(snapshot.batch_no || '').trim() && Array.isArray(snapshot.tasks)) {
|
||
return snapshot;
|
||
}
|
||
}
|
||
return null;
|
||
};
|
||
|
||
/**
|
||
* 从单条助手消息中提取工作台恢复锚点。
|
||
* 核心逻辑:优先识别合法 `shipping_batch_ui_state`,其次回退到 `task_no / batch_no / shipping_ui_state`;
|
||
* 供实时终态、历史回放与刷新恢复共用。
|
||
*/
|
||
export const resolveShippingMessageRecoveryPayload = (
|
||
message: ChatMessage | null | undefined,
|
||
): ShippingMessageRecoveryPayload | null => {
|
||
const payload = message?.payload && typeof message.payload === 'object'
|
||
? message.payload as ShippingMessageRecoveryPayload
|
||
: null;
|
||
if (!payload) return null;
|
||
const batchSnapshot = payload.shipping_batch_ui_state;
|
||
const hasBatchSnapshot = Boolean(
|
||
batchSnapshot
|
||
&& String(batchSnapshot.batch_no || '').trim()
|
||
&& Array.isArray(batchSnapshot.tasks),
|
||
);
|
||
const taskNo = String(
|
||
payload.task_no
|
||
|| payload.shipping_ui_state?.task_no
|
||
|| batchSnapshot?.current_focus_task_no
|
||
|| batchSnapshot?.focus_task?.task_no
|
||
|| batchSnapshot?.tasks?.[0]?.task_no
|
||
|| '',
|
||
).trim();
|
||
const batchNo = String(
|
||
payload.batch_no
|
||
|| payload.shipping_ui_state?.batch_no
|
||
|| batchSnapshot?.batch_no
|
||
|| '',
|
||
).trim();
|
||
const hasTaskUiState = Boolean(payload.shipping_ui_state && typeof payload.shipping_ui_state === 'object');
|
||
if (!hasBatchSnapshot && !taskNo && !batchNo && !hasTaskUiState) {
|
||
return null;
|
||
}
|
||
return {
|
||
...payload,
|
||
...(taskNo ? { task_no: taskNo } : {}),
|
||
...(batchNo ? { batch_no: batchNo } : {}),
|
||
};
|
||
};
|
||
|
||
/**
|
||
* 从消息列表中选择最近一条可恢复工作台的消息载荷。
|
||
* 核心逻辑:从后往前找最近的权威恢复锚点,允许 `open_existing` 只靠 `task_no/ui_state` 恢复。
|
||
*/
|
||
export const resolveLatestShippingMessageRecoveryPayload = (
|
||
sourceMessages: ChatMessage[],
|
||
): ShippingMessageRecoveryPayload | null => {
|
||
for (let index = sourceMessages.length - 1; index >= 0; index -= 1) {
|
||
const payload = resolveShippingMessageRecoveryPayload(sourceMessages[index]);
|
||
if (payload) return payload;
|
||
}
|
||
return null;
|
||
};
|
||
|
||
/**
|
||
* 组装发货通知聊天所需的状态、动作处理器与发送拦截逻辑。
|
||
*
|
||
* 核心逻辑:统一管理当前任务/批次上下文,组合上传、映射、决策、动作刷新等子模块,并对 ChatView 暴露稳定 API。
|
||
* @param options - 聊天页依赖与响应式状态集合
|
||
* @returns 发货通知聊天场景所需的状态、事件处理器和工具函数
|
||
*/
|
||
export function useChatShipping(options: UseChatShippingOptions) {
|
||
const {
|
||
deps: { t, msg, router, route },
|
||
currentAgent,
|
||
currentAgentId,
|
||
messages,
|
||
conversationId,
|
||
isThinking,
|
||
shippingActionBusy,
|
||
activeRunId,
|
||
runs,
|
||
history,
|
||
loadHistory,
|
||
input,
|
||
chatScrollContainer,
|
||
attachments,
|
||
selectedKb,
|
||
isUploadingAttachments,
|
||
attachmentPolicy,
|
||
presetQuestion,
|
||
saveLocalMessageToBackend,
|
||
newLocalMessageId,
|
||
stripReasoningPrelude,
|
||
sendMessage,
|
||
startChatTurn,
|
||
buildFileSpecsForSend,
|
||
createNewChatView,
|
||
} = options;
|
||
|
||
const shippingBindSend = (_fn: () => Promise<void>) => {
|
||
void _fn;
|
||
// 保留旧绑定入口,续办链路已改为直接调用 sendMessage 以支持 display_query 上下文。
|
||
};
|
||
|
||
// ── 功能开关与 UI refs ────────────────────────────────────
|
||
const isShippingNoticeAgent = computed(() => resolveShippingNoticeAgent(currentAgent.value));
|
||
const showShippingProgressWorkspace = computed(() => agentUsesWorkspaceStepperProgress(currentAgent.value));
|
||
const isShippingActionBusy = computed(() => {
|
||
if (shippingActionBusy.value) return true;
|
||
return hasActiveRunningChatRun(isThinking.value, activeRunId.value, runs.value);
|
||
});
|
||
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 pendingShippingNoticeTaskId = 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;
|
||
|
||
// #region debug-point B:shipping-retry-chain
|
||
const reportRetryRpaDebug = (hypothesisId: string, msg: string, data: Record<string, unknown>) =>
|
||
reportShippingDebugEvent('useChatShipping.ts', hypothesisId, msg, data);
|
||
// #endregion
|
||
|
||
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,
|
||
options?: { preferLatest?: boolean },
|
||
) => {
|
||
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 = selectShippingConversationBatch(
|
||
batches,
|
||
currentBatchNo,
|
||
queryBatchNo,
|
||
Boolean(options?.preferLatest),
|
||
);
|
||
if (!selectedBatch) return;
|
||
if (options?.preferLatest) {
|
||
activeShippingBatchNo.value = selectedBatch.batch_no;
|
||
}
|
||
applyShippingBatchDetail(selectedBatch, selectedBatch.batch_no);
|
||
};
|
||
|
||
const syncShippingConversationWorkspace = async (
|
||
options?: { preferLatest?: boolean },
|
||
): Promise<boolean> => {
|
||
const localConversationId = String(conversationId.value || '').trim();
|
||
if (!localConversationId || !isShippingNoticeAgent.value) {
|
||
shippingConversationWorkspace.value = null;
|
||
return false;
|
||
}
|
||
try {
|
||
const workspace = await getWorkspaceShippingConversationBatches(localConversationId);
|
||
shippingConversationWorkspace.value = workspace;
|
||
applyConversationWorkspaceFocus(workspace, options);
|
||
return true;
|
||
} catch {
|
||
shippingConversationWorkspace.value = null;
|
||
return false;
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 从本轮 SSE 助手消息恢复权威批次快照。
|
||
*
|
||
* 核心逻辑:订单识别可能打开属于旧会话的已有任务,此时按当前会话补拉工作台会返回空批次;
|
||
* 优先应用 `shipping_ui_state` 事件随消息持久化的 `shipping_batch_ui_state`,再由接口刷新后续状态。
|
||
* @param message - 当前流式回答完成后的助手消息
|
||
* @returns 是否找到并应用了合法批次快照
|
||
*/
|
||
const applyResolvedShippingBatchSnapshot = (snapshot: ShippingBatchUiState | null): boolean => {
|
||
if (!snapshot) return false;
|
||
const batchNo = String(snapshot.batch_no || '').trim();
|
||
applyShippingBatchDetail(snapshot, batchNo);
|
||
return true;
|
||
};
|
||
|
||
const applyShippingBatchSnapshot = (message: ChatMessage): boolean => (
|
||
applyResolvedShippingBatchSnapshot(resolveLatestShippingBatchSnapshot([message]))
|
||
);
|
||
|
||
/**
|
||
* 按“批次快照 -> 任务/批次锚点 -> 会话工作台”顺序恢复聊天工作台。
|
||
*
|
||
* 核心逻辑:`open_existing` 可能只携带 `task_no / shipping_ui_state`;此时先恢复任务锚点并补拉任务详情,
|
||
* 再尝试按任务所属批次加载批次详情,最后才回退到当前会话工作台。
|
||
* @param payload - 从消息中解析出的恢复载荷
|
||
* @returns 是否至少恢复出一层任务或批次上下文
|
||
*/
|
||
const applyResolvedShippingMessageRecovery = async (
|
||
payload: ShippingMessageRecoveryPayload | null,
|
||
): Promise<boolean> => {
|
||
if (!payload) return false;
|
||
let recovered = false;
|
||
const snapshot = payload.shipping_batch_ui_state ?? null;
|
||
if (applyResolvedShippingBatchSnapshot(snapshot)) {
|
||
recovered = true;
|
||
}
|
||
|
||
const taskNo = String(
|
||
payload.task_no
|
||
|| payload.shipping_ui_state?.task_no
|
||
|| '',
|
||
).trim().toUpperCase();
|
||
let batchNo = String(
|
||
payload.batch_no
|
||
|| payload.shipping_ui_state?.batch_no
|
||
|| snapshot?.batch_no
|
||
|| '',
|
||
).trim();
|
||
|
||
if (batchNo) {
|
||
resolvedShippingBatchNo.value = batchNo;
|
||
activeShippingBatchNo.value = batchNo;
|
||
}
|
||
if (taskNo) {
|
||
resolvedShippingTaskId.value = taskNo;
|
||
focusedShippingTaskNo.value = taskNo;
|
||
if (!shippingFocusReason.value) {
|
||
shippingFocusReason.value = t('chat.shippingNoticeUi.currentFocusDefaultReason');
|
||
}
|
||
}
|
||
if (payload.shipping_ui_state && taskNo) {
|
||
activeShippingTaskDetail.value = {
|
||
...(activeShippingTaskDetail.value || {}),
|
||
task_no: taskNo,
|
||
batch_no: batchNo || payload.shipping_ui_state.batch_no || null,
|
||
lines: activeShippingTaskDetail.value?.lines || [],
|
||
events: activeShippingTaskDetail.value?.events || [],
|
||
ui_state: payload.shipping_ui_state,
|
||
} as ShippingTaskDetail;
|
||
recovered = true;
|
||
}
|
||
if (!snapshot && batchNo) {
|
||
try {
|
||
const detail = await getWorkspaceShippingBatch(batchNo);
|
||
applyShippingBatchDetail(detail, batchNo);
|
||
recovered = true;
|
||
} catch {
|
||
// ignore and continue with task-first recovery
|
||
}
|
||
}
|
||
if (taskNo) {
|
||
await syncActiveShippingTaskDetail(taskNo);
|
||
const detailBatchNo = String(activeShippingTaskDetail.value?.batch_no || '').trim();
|
||
if (detailBatchNo) {
|
||
batchNo = detailBatchNo;
|
||
resolvedShippingBatchNo.value = detailBatchNo;
|
||
activeShippingBatchNo.value = detailBatchNo;
|
||
}
|
||
if (!snapshot && batchNo && String(shippingBatchSummary.value?.batch_no || '').trim() !== batchNo) {
|
||
try {
|
||
const detail = await getWorkspaceShippingBatch(batchNo);
|
||
applyShippingBatchDetail(detail, batchNo);
|
||
recovered = true;
|
||
} catch {
|
||
// ignore and keep task-only recovery
|
||
}
|
||
}
|
||
recovered = recovered || Boolean(activeShippingTaskDetail.value);
|
||
}
|
||
return recovered || Boolean(batchNo);
|
||
};
|
||
|
||
const applyShippingMessageRecovery = async (message: ChatMessage): Promise<boolean> => (
|
||
applyResolvedShippingMessageRecovery(resolveShippingMessageRecoveryPayload(message))
|
||
);
|
||
|
||
const switchShippingFocusTask = async (taskNo: string) => {
|
||
const batchNo = getActiveShippingBatchNo();
|
||
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
|
||
// #region debug-point C:switch-focus-entry
|
||
void reportRetryRpaDebug('C', 'switchShippingFocusTask entry', {
|
||
batchNo,
|
||
normalizedTaskNo,
|
||
activeBatchNo: activeShippingBatchNo.value,
|
||
resolvedBatchNo: resolvedShippingBatchNo.value,
|
||
routeBatchNo: shippingBatchNoFromQuery.value,
|
||
});
|
||
// #endregion
|
||
if (!batchNo || !normalizedTaskNo) {
|
||
// #region debug-point C:switch-focus-guard
|
||
void reportRetryRpaDebug('C', 'switchShippingFocusTask guard returned false', {
|
||
batchNo,
|
||
normalizedTaskNo,
|
||
});
|
||
// #endregion
|
||
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();
|
||
// #region debug-point C:switch-focus-success
|
||
void reportRetryRpaDebug('C', 'switchShippingFocusTask success', {
|
||
batchNo,
|
||
normalizedTaskNo,
|
||
resolvedTaskId: resolvedShippingTaskId.value,
|
||
});
|
||
// #endregion
|
||
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 = '';
|
||
pendingShippingNoticeTaskId.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(),
|
||
shipping_intake_nos: shippingIntakes.getParsedIntakeNos(),
|
||
});
|
||
|
||
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 || isShippingActionBusy.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,
|
||
resolvedShippingTaskId,
|
||
shippingTaskIdFromQuery,
|
||
getActiveBatchTaskId,
|
||
});
|
||
|
||
const {
|
||
openShippingInventoryMappingFormForTask,
|
||
applyShippingInventoryMappingForm,
|
||
reuploadShippingInventoryFromMappingForm,
|
||
} = createShippingMappingFormHandlers({
|
||
messages,
|
||
chatScrollContainer,
|
||
shippingInventorySchemaPreviewCache,
|
||
shippingInventoryPickerRef,
|
||
pendingShippingUploadTaskId,
|
||
resolvedShippingTaskId,
|
||
newLocalMessageId,
|
||
saveLocalMessageToBackend,
|
||
startChatTurn,
|
||
currentAgentId,
|
||
refreshShippingActions,
|
||
msg,
|
||
});
|
||
|
||
/**
|
||
* Dify SSE 完成后立即净化最后一条回复,并同步后端动作按钮。
|
||
*
|
||
* 核心逻辑:流式过程中只做展示层净化;终态事件到达后消息对象已经完整,
|
||
* 此时调用统一 refreshShippingActions,把 action_buttons 回写到当前 assistant 气泡。
|
||
*/
|
||
const finalizeShippingAssistantMessage = async () => {
|
||
if (!isShippingNoticeAgent.value) return;
|
||
await shippingIntakes.refreshStatuses();
|
||
if (!(await syncShippingConversationWorkspace())) {
|
||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||
await syncShippingConversationWorkspace();
|
||
}
|
||
shippingIntakes.clearConsumedAttachments();
|
||
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;
|
||
}
|
||
};
|
||
|
||
/**
|
||
* 在聊天流中输出确定性的缺口明细(Chat Turn SSE)。
|
||
*/
|
||
const queryShippingShortageDetails = async (taskNo?: string, displayText?: string) => {
|
||
const task = await resolveShippingTaskForShortageQuery(taskNo);
|
||
if (!task) {
|
||
msg.warning(t('chat.shippingNoticeMissingTaskId'));
|
||
return true;
|
||
}
|
||
const normalizedTaskNo = String(task.task_no || '').trim().toUpperCase();
|
||
const turn = buildShippingQueryShortageTurn(
|
||
normalizedTaskNo,
|
||
displayText || t('chat.shippingNoticeUi.queryShortageDetails'),
|
||
);
|
||
await startChatTurn({
|
||
agentId: currentAgentId.value,
|
||
inputType: 'action',
|
||
displayText: turn.displayText,
|
||
actionType: turn.actionType,
|
||
payload: turn.payload,
|
||
refs: turn.refs,
|
||
});
|
||
return true;
|
||
};
|
||
|
||
const { sendShippingMenuMessage } = createShippingConversationHelpers({
|
||
conversationId,
|
||
history,
|
||
loadHistory,
|
||
getActiveShippingTaskId,
|
||
currentAgentId,
|
||
selectedKb,
|
||
sendMessage,
|
||
});
|
||
|
||
const { executeShippingDecision, executeShippingManualUpload } = createShippingDecisionHandlers({
|
||
messages,
|
||
conversationId,
|
||
history,
|
||
isShippingNoticeAgent,
|
||
currentAgentId,
|
||
shippingInventorySchemaPreviewCache,
|
||
getActiveShippingTaskId,
|
||
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
|
||
loadHistory,
|
||
openShippingInventoryMappingFormForTask,
|
||
refreshShippingActions,
|
||
startChatTurn,
|
||
msg,
|
||
t,
|
||
});
|
||
|
||
const {
|
||
syncShippingParseReviewCard,
|
||
updateShippingParseReviewHeader,
|
||
updateShippingParseReviewLine,
|
||
addShippingParseReviewLine,
|
||
removeShippingParseReviewLine,
|
||
} = createShippingParseReviewHandlers({
|
||
messages,
|
||
resolvedShippingTaskId,
|
||
newLocalMessageId,
|
||
saveLocalMessageToBackend,
|
||
refreshShippingActions,
|
||
msg,
|
||
});
|
||
|
||
const shippingIntakes = useShippingNoticeIntakes({
|
||
attachments,
|
||
conversationId,
|
||
msg,
|
||
t,
|
||
});
|
||
|
||
const showShippingDuplicateDialog = ref(false);
|
||
const showShippingCustomerDialog = ref(false);
|
||
const shippingCustomerDialogTaskId = ref('');
|
||
const shippingCustomerOptions = ref<ShippingCustomerOption[]>([]);
|
||
const shippingCustomerLoading = ref(false);
|
||
const shippingDuplicateAttachmentId = ref<string | null>(null);
|
||
const shippingDuplicateAttachment = computed(() => {
|
||
const id = shippingDuplicateAttachmentId.value;
|
||
if (!id) return null;
|
||
return shippingIntakes.noticeAttachments.value.find((item) => item.id === id) || null;
|
||
});
|
||
const canForceCreateShippingDuplicate = computed(() => {
|
||
const user = useAuthStore().user;
|
||
if (!user) return false;
|
||
if (String(user.role || '') === 'admin') return true;
|
||
return Boolean(user.feature_permissions?.shipping_notice_force_create);
|
||
});
|
||
|
||
/**
|
||
* 打开首个(或指定)阻断型重复附件的处理弹窗。
|
||
*/
|
||
const openShippingDuplicateDialog = (attachmentId?: string) => {
|
||
const targetId =
|
||
attachmentId
|
||
|| shippingIntakes.noticeAttachments.value.find(
|
||
(item) => item.duplicate?.blocking && !item.duplicateResolution?.action,
|
||
)?.id
|
||
|| null;
|
||
if (!targetId) {
|
||
msg.warning(t('chat.shippingNoticeDuplicateNeedsResolution'));
|
||
return;
|
||
}
|
||
shippingDuplicateAttachmentId.value = targetId;
|
||
showShippingDuplicateDialog.value = true;
|
||
};
|
||
|
||
/**
|
||
* 提交重复决策并写回附件状态。
|
||
*/
|
||
const resolveShippingDuplicateDialog = async (payload: {
|
||
action: import('../types/shipping.types').ShippingDuplicateAction;
|
||
targetTaskNo?: string;
|
||
reason?: string;
|
||
}) => {
|
||
const id = shippingDuplicateAttachmentId.value;
|
||
if (!id) return;
|
||
try {
|
||
await shippingIntakes.resolveDuplicateAttachment(
|
||
id,
|
||
payload.action,
|
||
payload.targetTaskNo,
|
||
payload.reason,
|
||
);
|
||
msg.success(t('chat.shippingNoticeDuplicateResolved'));
|
||
} catch (e: unknown) {
|
||
msg.warning(e instanceof Error ? e.message : t('chat.shippingNoticeDuplicateResolveFailed'));
|
||
}
|
||
};
|
||
|
||
const removeShippingDuplicateDialogAttachment = async () => {
|
||
const id = shippingDuplicateAttachmentId.value;
|
||
if (!id) return;
|
||
await shippingIntakes.removeNoticeAttachment(id);
|
||
shippingDuplicateAttachmentId.value = null;
|
||
};
|
||
|
||
/** 打开客户确认对话框并加载启用标准客户。 */
|
||
const openShippingCustomerDialog = async (taskId: string): Promise<void> => {
|
||
shippingCustomerDialogTaskId.value = String(taskId || '').trim().toUpperCase();
|
||
showShippingCustomerDialog.value = true;
|
||
shippingCustomerLoading.value = true;
|
||
try {
|
||
shippingCustomerOptions.value = await listWorkspaceShippingCustomerOptions();
|
||
} catch (error: unknown) {
|
||
shippingCustomerOptions.value = [];
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
|
||
} finally {
|
||
shippingCustomerLoading.value = false;
|
||
}
|
||
};
|
||
|
||
/** 按关键词刷新客户选项。 */
|
||
const searchShippingCustomers = async (query: string): Promise<void> => {
|
||
shippingCustomerLoading.value = true;
|
||
try {
|
||
shippingCustomerOptions.value = await listWorkspaceShippingCustomerOptions(query);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.loadFailed'));
|
||
} finally {
|
||
shippingCustomerLoading.value = false;
|
||
}
|
||
};
|
||
|
||
/** 确认客户后刷新任务详情与动作菜单;业务号仍由后续阶段生成。 */
|
||
const confirmShippingCustomer = async (customerId: number): Promise<void> => {
|
||
const taskId = shippingCustomerDialogTaskId.value;
|
||
if (!taskId) return;
|
||
shippingCustomerLoading.value = true;
|
||
try {
|
||
await confirmWorkspaceShippingCustomer(taskId, customerId);
|
||
showShippingCustomerDialog.value = false;
|
||
await Promise.all([syncActiveShippingTaskDetail(taskId), refreshShippingActions()]);
|
||
msg.success(t('chat.shippingCustomer.confirmed'));
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCustomer.confirmFailed'));
|
||
} finally {
|
||
shippingCustomerLoading.value = false;
|
||
}
|
||
};
|
||
|
||
/** 更新 Candidate 选择状态,并将 API 失败统一反馈给用户。 */
|
||
const setShippingCandidateSelected = async (candidateNo: string, selected: boolean) => {
|
||
try {
|
||
await shippingIntakes.setCandidateSelected(candidateNo, selected);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
|
||
}
|
||
};
|
||
|
||
/** 保存 Candidate 结构化修订,并保留服务端校验错误。 */
|
||
const updateShippingCandidateSummary = async (
|
||
candidateNo: string,
|
||
businessSummary: Record<string, unknown>,
|
||
done?: (success: boolean) => void,
|
||
) => {
|
||
try {
|
||
await shippingIntakes.updateCandidateSummary(candidateNo, businessSummary);
|
||
msg.success(t('chat.shippingCandidateUpdateDone'));
|
||
done?.(true);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingCandidateUpdateFailed'));
|
||
done?.(false);
|
||
}
|
||
};
|
||
|
||
/** 保存 Candidate 重复决策,并统一展示权限或目标漂移错误。 */
|
||
const resolveShippingCandidateDuplicate = async (
|
||
candidateNo: string,
|
||
action: import('../types/shipping.types').ShippingDuplicateAction,
|
||
targetTaskNo?: string,
|
||
reason?: string,
|
||
done?: (success: boolean) => void,
|
||
) => {
|
||
try {
|
||
await shippingIntakes.resolveCandidateDuplicate(candidateNo, action, targetTaskNo, reason);
|
||
msg.success(t('chat.shippingNoticeDuplicateResolved'));
|
||
done?.(true);
|
||
} catch (error: unknown) {
|
||
msg.warning(error instanceof Error ? error.message : t('chat.shippingNoticeDuplicateResolveFailed'));
|
||
done?.(false);
|
||
}
|
||
};
|
||
|
||
const {
|
||
handleShippingAutoUploadFile,
|
||
handleShippingAutoUploadNoticeBatch,
|
||
openShippingInventoryPicker,
|
||
openShippingNoticePicker,
|
||
selectShippingInventoryUploadTask,
|
||
cancelShippingInventoryTaskSelection,
|
||
handleShippingInventorySelected,
|
||
shippingSuggestedPrompt,
|
||
useShippingSuggestedPrompt,
|
||
isShippingNoticeBatchSubmitting,
|
||
} = createShippingUploadHandlers({
|
||
conversationId,
|
||
currentAgentId,
|
||
attachments,
|
||
input,
|
||
shippingAutoFlowRequested,
|
||
shippingInventoryPickerRef,
|
||
shippingNoticePickerRef,
|
||
pendingShippingUploadTaskId,
|
||
pendingShippingNoticeTaskId,
|
||
pendingShippingInventoryFile,
|
||
resolvedShippingTaskId,
|
||
resolvedShippingBatchNo,
|
||
shippingBatchSummary,
|
||
shippingBatchTasks,
|
||
shippingInventorySelectionActive,
|
||
shippingInventorySelectionTaskId,
|
||
shippingInventorySchemaPreviewCache,
|
||
getActiveShippingTaskId,
|
||
startChatTurn,
|
||
refreshShippingActions,
|
||
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
|
||
getSelectedCandidateNos: shippingIntakes.getSelectedCandidateNos,
|
||
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
|
||
msg,
|
||
t,
|
||
});
|
||
|
||
const { handleShippingMenuAction, handleShippingActionClick } = createShippingMenuHandlers({
|
||
isThinking,
|
||
currentAgentId,
|
||
getActiveShippingTaskId,
|
||
getActiveShippingBatchNo: () => resolvedShippingBatchNo.value || shippingBatchNoFromQuery.value || '',
|
||
messages,
|
||
sendShippingMenuMessage,
|
||
openShippingInventoryMappingFormForTask,
|
||
openShippingInventoryPicker,
|
||
openShippingNoticePicker,
|
||
openShippingCustomerDialog,
|
||
executeShippingDecision,
|
||
executeShippingManualUpload,
|
||
refreshShippingActions,
|
||
startChatTurn,
|
||
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,
|
||
startChatTurn,
|
||
openShippingInventoryPicker,
|
||
executeShippingDecision,
|
||
executeShippingManualUpload,
|
||
handleShippingMenuAction,
|
||
handleShippingAutoUploadFile,
|
||
handleShippingAutoUploadNoticeBatch,
|
||
isShippingNoticeBatchSubmitting,
|
||
hasBlockingNoticeIntake: () => shippingIntakes.hasBlockingUploadOrParse.value,
|
||
hasNoticeIntakeFailures: () => shippingIntakes.hasParseFailures.value,
|
||
hasBlockingNoticeDuplicates: () => shippingIntakes.hasBlockingDuplicates.value,
|
||
hasCandidateReviewIssues: () => shippingIntakes.hasCandidateReviewIssues.value,
|
||
hasSelectedNoticeCandidates: () => shippingIntakes.getSelectedCandidateNos().length > 0,
|
||
openShippingDuplicateDialog,
|
||
getParsedIntakeNos: shippingIntakes.getParsedIntakeNos,
|
||
markOrderExtractionStarted: shippingIntakes.markOrderExtractionStarted,
|
||
rollbackOrderExtractionStarted: shippingIntakes.rollbackOrderExtractionStarted,
|
||
refreshNoticeIntakeStatuses: shippingIntakes.refreshStatuses,
|
||
clearConsumedNoticeAttachments: shippingIntakes.clearConsumedAttachments,
|
||
applyShippingMessageRecovery,
|
||
applyShippingBatchSnapshot,
|
||
syncShippingConversationWorkspace,
|
||
refreshShippingActions,
|
||
shippingSuggestedPrompt,
|
||
isShippingShortageQueryIntent,
|
||
queryShippingShortageDetails,
|
||
msg,
|
||
t,
|
||
});
|
||
|
||
// ── 路由 / 会话生命周期 ───────────────────────────────────
|
||
/**
|
||
* 根据路由中的 `task_id/batch_no` 恢复发货任务上下文。
|
||
* 核心逻辑:优先同步显式传入的批次摘要;若仍缺少会话,则直接基于 `task_id` 发起一次继续任务请求,
|
||
* 禁止再按历史标题模糊猜测旧会话,避免多批次/多票场景跳进错误会话。
|
||
* @returns Promise<void>
|
||
*/
|
||
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;
|
||
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) => {
|
||
onNoticeBatchConversationChanging(nextId, prevId);
|
||
shippingIntakes.stopPolling();
|
||
if (nextId && nextId !== prevId) {
|
||
void shippingIntakes.restoreForConversation(nextId);
|
||
}
|
||
if (prevId !== nextId) {
|
||
resolvedShippingTaskId.value = '';
|
||
if (!shippingBatchNoFromQuery.value) {
|
||
resolvedShippingBatchNo.value = '';
|
||
shippingBatchSummary.value = null;
|
||
shippingBatchTasks.value = [];
|
||
}
|
||
}
|
||
};
|
||
|
||
const WORKSPACE_DIRECT_PICKER_ACTION_IDS = new Set(['upload_inventory_file', 'replace_notice_file']);
|
||
|
||
/**
|
||
* 从右侧批次工作台触发指定任务的后端状态机动作。
|
||
*
|
||
* 核心逻辑:普通动作先把 batch focus 切到目标 task,再复用聊天气泡的统一 action.id 分发器;
|
||
* 文件选择类动作必须先同步打开 picker,再异步切焦点,避免浏览器丢失用户点击手势。
|
||
* @param taskNo - 被点击按钮所属的任务编号
|
||
* @param action - 后端 `ui_state.action_buttons` 返回的动作按钮
|
||
* @returns 是否成功进入统一动作处理链
|
||
*/
|
||
const handleShippingWorkspaceAction = async (taskNo: string, action: ShippingActionButton) => {
|
||
const normalizedTaskNo = String(taskNo || '').trim().toUpperCase();
|
||
if (!normalizedTaskNo || !action?.id || !isShippingNoticeAgent.value) return false;
|
||
if (isShippingActionBusy.value) {
|
||
msg.warning(t('chat.shippingNoticeUi.actionBusyHint'));
|
||
return false;
|
||
}
|
||
if (WORKSPACE_DIRECT_PICKER_ACTION_IDS.has(String(action.id || ''))) {
|
||
await handleShippingMenuAction(action, undefined, { taskId: normalizedTaskNo });
|
||
void switchShippingFocusTask(normalizedTaskNo);
|
||
return true;
|
||
}
|
||
const switched = await switchShippingFocusTask(normalizedTaskNo);
|
||
if (!switched) return false;
|
||
await handleShippingMenuAction(action, undefined, { taskId: normalizedTaskNo });
|
||
return true;
|
||
};
|
||
|
||
/**
|
||
* 重试当前聚焦批次中可恢复的失败/排队任务。
|
||
* 核心逻辑:调 workspace retry-pending → 刷新会话工作台/批次摘要/动作;成功反馈交给页面级非阻塞 toast,避免居中成功弹窗。
|
||
* @returns 成功时返回 started/skipped;失败或跳过时返回 null
|
||
*/
|
||
const retryCurrentShippingBatchPendingTasks = async (): Promise<{
|
||
started: number;
|
||
skipped: number;
|
||
} | null> => {
|
||
const batchNo = getActiveShippingBatchNo();
|
||
if (!batchNo || retryingShippingPendingTasks.value) return null;
|
||
if (isShippingActionBusy.value) {
|
||
msg.warning(t('chat.shippingNoticeUi.actionBusyHint'));
|
||
return null;
|
||
}
|
||
retryingShippingPendingTasks.value = true;
|
||
try {
|
||
const { retryWorkspaceShippingBatchPending } = await import('@/features/chat/api/shipping.api');
|
||
const result = await retryWorkspaceShippingBatchPending(batchNo);
|
||
await syncShippingConversationWorkspace();
|
||
await syncShippingBatchSummary(batchNo);
|
||
await refreshShippingActions();
|
||
return {
|
||
started: Number(result.started ?? 0),
|
||
skipped: Number(result.skipped ?? 0),
|
||
};
|
||
} catch (error) {
|
||
msg.error(error instanceof Error ? error.message : t('chat.shippingNoticeUi.retryFailed'));
|
||
return null;
|
||
} finally {
|
||
retryingShippingPendingTasks.value = false;
|
||
}
|
||
};
|
||
|
||
const handleShippingLocalFilesSelected = (event: Event): boolean => {
|
||
if (!isShippingNoticeAgent.value) return false;
|
||
const inputEl = event.target as HTMLInputElement | null;
|
||
const files = inputEl?.files ? Array.from(inputEl.files) : [];
|
||
if (!files.length) return false;
|
||
const noticeFiles = files.filter((file) => classifyShippingUploadFile(file, extractExt) === 'notice');
|
||
const otherFiles = files.filter((file) => classifyShippingUploadFile(file, extractExt) !== 'notice');
|
||
if (noticeFiles.length) {
|
||
void shippingIntakes.enqueueNoticeFiles(noticeFiles);
|
||
}
|
||
// 同一次选择中的库存/其他文件直接落入本地附件,避免清空 input 后通用 handler 丢失 FileList
|
||
for (const file of otherFiles) {
|
||
const kind = classifyShippingUploadFile(file, extractExt);
|
||
attachments.value = [
|
||
...attachments.value,
|
||
{
|
||
id: `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
|
||
kind: 'local',
|
||
file,
|
||
type: kind === 'inventory' ? 'document' : 'document',
|
||
uploadStatus: 'waiting',
|
||
uploadProgress: 0,
|
||
},
|
||
];
|
||
}
|
||
if (inputEl) inputEl.value = '';
|
||
return true;
|
||
};
|
||
|
||
const onConversationLoadedEmpty = async () => {
|
||
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isShippingActionBusy.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 || isShippingActionBusy.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() && !isShippingActionBusy.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('|');
|
||
});
|
||
const shippingRecoveryWatchKey = computed(() => {
|
||
const recovery = resolveLatestShippingMessageRecoveryPayload(messages.value);
|
||
const snapshot = recovery?.shipping_batch_ui_state;
|
||
const uiState = recovery?.shipping_ui_state;
|
||
return [
|
||
String(conversationId.value || ''),
|
||
String(recovery?.batch_no || snapshot?.batch_no || uiState?.batch_no || ''),
|
||
String(recovery?.task_no || snapshot?.current_focus_task_no || uiState?.task_no || ''),
|
||
String(snapshot?.updated_at || ''),
|
||
String(uiState?.updated_at || ''),
|
||
String(snapshot?.tasks.length || 0),
|
||
].join('|');
|
||
});
|
||
watch([shippingRecoveryWatchKey, isShippingNoticeAgent], () => {
|
||
if (!isShippingNoticeAgent.value) return;
|
||
void applyResolvedShippingMessageRecovery(resolveLatestShippingMessageRecoveryPayload(messages.value));
|
||
}, { immediate: true });
|
||
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,
|
||
showShippingProgressWorkspace,
|
||
prepareMarkdownDisplayText,
|
||
shippingAutoFlowRequested,
|
||
shippingInventoryPickerRef,
|
||
shippingNoticePickerRef,
|
||
pendingShippingUploadTaskId,
|
||
shippingInventorySelectionActive,
|
||
shippingInventorySelectionTaskId,
|
||
allowsSendWithAttachmentsOnly,
|
||
shippingTaskIdFromQuery,
|
||
shippingBatchNoFromQuery,
|
||
resolvedShippingBatchNo,
|
||
activeShippingBatchNo,
|
||
focusedShippingTaskNo,
|
||
shippingFocusReason,
|
||
shippingConversationWorkspace,
|
||
shippingBatchSummary,
|
||
shippingBatchTasks,
|
||
shippingWorkspaceOpen,
|
||
isShippingActionBusy,
|
||
retryingShippingPendingTasks,
|
||
activeShippingTaskDetail,
|
||
getCurrentShippingChatContext,
|
||
getActiveShippingBatchNo,
|
||
switchShippingBatch,
|
||
switchShippingFocusTask,
|
||
clearShippingFocus,
|
||
handleShippingWorkspaceAction,
|
||
retryCurrentShippingBatchPendingTasks,
|
||
queryShippingShortageDetails,
|
||
resetShippingConversationState,
|
||
resumeShippingTaskFromQuery,
|
||
normalizeShippingHeaderForDisplay,
|
||
getShippingInventoryMappingPayload,
|
||
getShippingMatchResultPayload,
|
||
getShippingParseReviewPayload,
|
||
hasShippingInventorySampleRows,
|
||
getShippingInventorySampleRowText,
|
||
applyShippingInventoryMappingForm,
|
||
reuploadShippingInventoryFromMappingForm,
|
||
updateShippingParseReviewHeader,
|
||
updateShippingParseReviewLine,
|
||
addShippingParseReviewLine,
|
||
removeShippingParseReviewLine,
|
||
handleShippingActionClick,
|
||
handleShippingInventorySelected,
|
||
finalizeShippingAssistantMessage,
|
||
selectShippingInventoryUploadTask,
|
||
cancelShippingInventoryTaskSelection,
|
||
shippingActionButtonClass,
|
||
shippingSuggestedPrompt,
|
||
useShippingSuggestedPrompt,
|
||
enqueueShippingNoticeFiles: shippingIntakes.enqueueNoticeFiles,
|
||
handleShippingLocalFilesSelected,
|
||
removeShippingNoticeAttachment: shippingIntakes.removeNoticeAttachment,
|
||
retryShippingNoticeAttachment: shippingIntakes.retryNoticeAttachment,
|
||
shippingNoticeAllReadyForConfirmation: shippingIntakes.allReadyForConfirmation,
|
||
setShippingCandidateSelected,
|
||
updateShippingCandidateSummary,
|
||
resolveShippingCandidateDuplicate,
|
||
showShippingDuplicateDialog,
|
||
showShippingCustomerDialog,
|
||
shippingCustomerOptions,
|
||
shippingCustomerLoading,
|
||
searchShippingCustomers,
|
||
confirmShippingCustomer,
|
||
closeShippingCustomerDialog: () => {
|
||
showShippingCustomerDialog.value = false;
|
||
},
|
||
shippingDuplicateAttachment,
|
||
canForceCreateShippingDuplicate,
|
||
openShippingDuplicateDialog,
|
||
resolveShippingDuplicateDialog,
|
||
removeShippingDuplicateDialogAttachment,
|
||
closeShippingDuplicateDialog: () => {
|
||
showShippingDuplicateDialog.value = false;
|
||
},
|
||
tryHandleShippingAttachmentAutoFlow,
|
||
tryHandleShippingSend,
|
||
onConversationIdChanging,
|
||
onConversationLoadedEmpty,
|
||
onConversationLoadFailed,
|
||
};
|
||
}
|